diff --git "a/2559.jsonl" "b/2559.jsonl" new file mode 100644--- /dev/null +++ "b/2559.jsonl" @@ -0,0 +1,1626 @@ +{"seq_id":"20867576847","text":"# 이것이 코딩테스트다\n# Chapter13-21: DFS/BFS 기출 인구 이동\n# https://www.acmicpc.net/problem/16234\n\n# 백준 사이트에서 채점하는 경우 80%구간에서 시간 초과 발생\n\nfrom collections import deque\nn,l,r = map(int,input().split()) #국경선을 여는 기준:l이상 r이하\n\n#인구 정보\nland =[]\nfor i in range(n):\n land.append(list(map(int,input().split())))\n\n#방문 국가인지 확인하기 위한 정보\nvisited = [[False] * (n) for _ in range(n)]\n\n#인접한 나라 간의 국경선은 정사각형 형태로 존재\ndx = [-1,1,0,0] #상하좌우\ndy = [0,0,-1,1]\n\n#국경선을 열고 연합을 구성하는 함수(BFS를 활용)\ndef union(x,y):\n q =deque()\n nations =[] #연합에 속하는 국가의 위치\n q.append((x,y))#출발점을 큐에 삽입\n nations.append((x,y))\n visited[x][y] = True #해당 출발점은 방문 노드에 추가\n count = 1 #연합에 포함되는 국가의 수\n population =land[x][y] #인구 수\n while q:\n x,y = q.popleft()\n for i in range(4): #인접합 국가들 중 국경선을 열 수 있는 경우가 있는지 확인\n nx = x+dx[i]\n ny = y+dy[i]\n if nx=0 and ny>=0 and not visited[nx][ny]:\n if abs(land[x][y]-land[nx][ny])>=l and abs(land[x][y]-land[nx][ny])<=r:\n q.append((nx,ny)) #큐에 인접한 노드 추가\n visited[nx][ny]=True\n count+=1 #연합에 추가\n nations.append((nx,ny))\n population+=land[nx][ny] #연합에 포함되는 인구 수 증가\n\n answer = (nations,count,population)\n return answer\n\n#연합 국가에 따라 값 변환\ndef move(answer):\n nations, count, population = answer\n for nation in nations:\n a,b = nation[0],nation[1]\n land[a][b] = int(population//count)\n\n#인구 이동 실행\ndef simulate():\n #인구 이동이 가능한 연합 수\n group = 0\n for i in range(n):\n for j in range(n):\n if not visited[i][j]:\n answer = union(i,j) #현재 위치에서 국경선에 따라 이동할 수 있는 경우 탐색\n if answer[1]!=1: #연합에 여러 국가가 묶이는 경우\n move(answer) #그에 따라 값 변경\n group+=1\n\n return group\n\n#인구 이동이 필요하지 않을 때까지 이동 (묶이는 group수가 0이면 더이상 이동 불가)\nresults = -1\nresult = -1\nwhile results!=0:\n results = simulate()\n visited = [[False] * (n) for _ in range(n)]\n result+=1\n\nprint(result)\n\n\n \n\n\n\n\n","repo_name":"giraffejin/Algorithm","sub_path":"Thisiscodingtest/DFS,BFS/PopulationMove.py","file_name":"PopulationMove.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27374250977","text":"\"Script to run brain extraction using HD-BET\"\nfrom radiants.workflows.bet import BETWorkflow\nfrom core.utils.config import cmdline_input_config, create_subject_list\n\n\nif __name__ == \"__main__\":\n\n PARSER = cmdline_input_config()\n\n ARGS = PARSER.parse_args()\n\n BASE_DIR = ARGS.input_dir\n\n sub_list, BASE_DIR = create_subject_list(BASE_DIR, ARGS.xnat_source,\n ARGS.cluster_source,\n subjects_to_process=[])\n\n for sub_id in sub_list:\n\n print('Processing subject {}'.format(sub_id))\n\n workflow = BETWorkflow(\n sub_id=sub_id, input_dir=BASE_DIR, work_dir=ARGS.work_dir,\n local_source=ARGS.local_source, local_sink=ARGS.local_sink,\n local_project_id=ARGS.local_project_id,\n local_basedir=ARGS.local_dir)\n\n wf = workflow.workflow_setup()\n workflow.runner(wf)\n\n print('Done!')\n","repo_name":"TransRadOnc-HIT/RADIANTS","sub_path":"scripts/run_bet.py","file_name":"run_bet.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11927614615","text":"import time\nimport glob\nimport os\n\ndef parse_so61utf8(filename):\n with open(filename, 'r', encoding='utf-8') as file:\n lines = file.read().split('\\n')\n \n TABLE = \"qwertyuiopasdfghjkl;zxcvbnm,./_\"\n TABLE = TABLE.upper()\n \n # Create a dictionary to map TABLE keys to characters\n table_dict = {}\n for line in lines:\n if line and not line.startswith(\"___\"):\n key, value = line[:3], line[3:]\n key = key.strip()\n value = value.strip()\n for i, char in enumerate(value):\n # Use modulo to ensure cyclic access to TABLE characters\n replaced_key = key.replace('_', TABLE[i % len(TABLE)], 1)\n if char in table_dict:\n table_dict[char].append(replaced_key)\n else:\n table_dict[char] = [replaced_key]\n \n return table_dict\n\ndef build_ab_dict(ab_folder, table_dict):\n ab_dict = {}\n for ab_file in glob.glob(os.path.join(ab_folder, '*.ab')):\n with open(ab_file, 'r', encoding='utf-8') as file:\n lines = file.read().split('\\n')\n\n ab_entry = ''\n for line in lines:\n if line:\n key, data = line.split(None, 1)\n if key == '_':\n key = ''\n for char in data:\n if char in table_dict:\n key += table_dict[char][0][0]\n ab_entry = key.strip()\n data = data.strip()\n ab_dict[ab_entry] = data\n return ab_dict\n\ndef debug_ab(ab_dict):\n for key, value in ab_dict.items():\n print(f'{key} => {value}')\n time.sleep(1)\n\nif __name__ == '__main__':\n ab_folder = \"ab\"\n so61utf8_dict = parse_so61utf8(\"so61utf8.txt\")\n ab_dict = build_ab_dict(ab_folder, so61utf8_dict)\n debug_ab(ab_dict)\n","repo_name":"HexColors60/so61ime","sub_path":"ab0004.py","file_name":"ab0004.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18729769200","text":"\n\"\"\" Defining the setup.py for the poisson package. \"\"\"\n\n\ndef setup_package():\n \"\"\"Install the `aiida-ase` package.\"\"\"\n import json\n from setuptools import setup, find_packages\n\n filename_setup_json = 'setup.json'\n filename_description = 'README.md'\n\n with open(filename_setup_json, 'r') as handle:\n setup_json = json.load(handle)\n\n with open(filename_description, 'r') as handle:\n description = handle.read()\n\n setup(include_package_data=True,\n packages=find_packages(),\n long_description=description,\n long_description_content_type='text/markdown',\n **setup_json)\n\n\nif __name__ == '__main__':\n setup_package()","repo_name":"tjunewson/dipole-aimd","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36622694341","text":"maximum=input()\nschema=str(input())\nlist=[]\n\n#print(schema[0])\n#print(type(maximum))\n\nfor i in range(0, int(maximum)+1):\n list.append(int(schema[i]))\n#print(list)\n\n\nvrienden=[]\nfor i in range(1, int(maximum)+1):\n if sum(list[:i]) + sum(vrienden) >= i:\n vrienden.append(0)\n elif sum(list[:i]) + sum(vrienden) < i and list[i]==0:\n vrienden.append(0)\n elif sum(list[:i])+sum(vrienden) < i and list[i] > 0:\n x= i-sum(list[:i])-sum(vrienden)\n vrienden.append(x)\n #print(vrienden)\n\nanswer=sum(vrienden)\nprint(answer)\n","repo_name":"franzigrkn/WISB256","sub_path":"Oefenopgaven WISB256 Midterm/Staande_Ovatie.py","file_name":"Staande_Ovatie.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16282495882","text":"import json\nimport os\nimport requests\nimport shlex\nimport subprocess\nimport time\n\nfrom retrying import (\n retry,\n RetryError\n)\nfrom threading import (\n Timer\n)\n\n\nclass Executor(object):\n\n base64_code = None\n driver_link = None\n runtime_limit = 10.0 # - runtime limit in seconds\n callback_url = None\n input_output_link_paris = []\n\n def __init__(self):\n self._parse_environ()\n\n def _parse_environ(self):\n \"\"\"\n Parse environment variables and extract out input s3 links, output s3 links, driver s3 link, runtime limit, and\n base64 encoded code.\n\n environment variable mappings:\n * OJ_TEST_COUNT -> # of test cases\n * OJ_INPUT_0 -> input series 0 S3 link\n * OJ_OUTPUT_0 -> input series 0 S3 link\n * OJ_DRIVER -> code driver S3 link\n * OJ_RUNTIME_LIMIT -> runtime limit\n * OJ_CODE -> base64 encoded code\n * OJ_DISPATCHER_URL -> dispatcher callback url\n\n Raises:\n KeyError: if required environment variables don't exist\n \"\"\"\n env = os.environ\n self.base64_code = env['OJ_CODE']\n self.driver_link = env['OJ_DRIVER']\n self.runtime_limit = float(env['OJ_RUNTIME_LIMIT'])\n self.callback_url = env['OJ_DISPATCHER_URL']\n test_count = env['OJ_TEST_COUNT']\n for i in range(test_count):\n self.input_output_link_paris.append({\n 'input': os.environ['OJ_INPUT_{0}'.format(i)],\n 'output': os.environ['OJ_OUTPUT_{0}'.format(i)]\n })\n\n def construct(self):\n \"\"\"\n Function that subclasses need to implement that takes in input, output, driver, and code and construct an\n executable format\n \"\"\"\n raise NotImplementedError\n\n def run(self, command):\n \"\"\"\n Run command through subprocess with a timeout.\n\n Args:\n command: String type. Command to execute, such as `javac Main.java && java`\n\n Returns:\n returncode: Int type. Exit code of the command\n stdout: String type. UTF-8 encoded stdout of the command\n stderr: String type. UTF-8 encoded stderr of the command\n runtime: Float type. The actual runtime of the command\n \"\"\"\n proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n def kill_proc(p):\n p.kill()\n\n timer = Timer(self.runtime_limit, kill_proc, [proc])\n start = time.time()\n timer.start()\n stdout, stderr = proc.communicate()\n end = time.time()\n timer.cancel()\n return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8'), end - start\n\n def report(self, result):\n\n @retry(stop_max_delay=10000, stop_max_attempt_number=10, wait_fixed=1000)\n def _http_post_with_retry(callback_url, payload):\n \"\"\"\n Send result as payload to target callback_url using HTTP Post method.\n This method will automatically retry, up to 10 times, at 1 second inteval, maximum retry time is 10 seconds\n\n Args:\n callback_url: URL type. Target endpoint to send data back\n payload: Dict type. Dictionary object containing the evaluation result\n \"\"\"\n response = requests.post(url=callback_url, data=json.dumps(payload))\n code = response.status_code\n assert code == 200, 'Failed to talk to callback endpoint (HTTP %d)' % code\n\n try:\n _http_post_with_retry(self.callback_url, result)\n except RetryError as re:\n # - TODO add log\n pass\n except Exception as e:\n # - TODO add log\n pass\n","repo_name":"svana1/prophet-velen","sub_path":"worker/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36442445329","text":"import cv2 as cv\nimport numpy as np\n\nimg = cv.imread('opencv/Pictures/12.jpg',-1)\n# cv.imshow('Laptop',img)\n\n\ndef rescale(frame, scale=0.35):\n width = int(frame.shape[1]*scale)\n height = int(frame.shape[0]*scale)\n\n dimension = (width, height)\n return cv.resize(frame,dimension,interpolation=cv.INTER_AREA)\n \nresized = rescale(img)\ncv.imshow('Resized Image', resized)\n\n#Convert to grayscale\ngray = cv.cvtColor(resized,cv.COLOR_BGR2GRAY)\ncv.imshow(\"Grayscale\", gray)\n\n# Blur the image\nblur = cv.GaussianBlur(resized,(3,3), cv.BORDER_DEFAULT)\ncv.imshow(\"Blured\", blur)\n\n#Edge cascade\nedge = cv.Canny(blur,125,175)\ncv.imshow(\"Canny\", edge)\n\n#Dialating an image\ndialated = cv.dilate(edge, (9,9), iterations=4)\ncv.imshow(\"Dialated\", dialated)\n\n#resize\nres = cv.resize(gray, (500,300), interpolation=cv.INTER_CUBIC)\ncv.imshow(\"Resized\",res)\n\n#Crop\ncropped = img[50:200,100:300]\ncv.imshow(\"Cropped\",cropped)\ncv.waitKey(0)","repo_name":"Morvin-Ian/Opencv","sub_path":"Image-read.py","file_name":"Image-read.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23982892572","text":"from flask import Flask, jsonify, url_for, request, redirect\nimport config\n\n# 创建一个对象,传入的__name__是一种固定语法,在后期出错之后,方便flask自动检查到错误\napp = Flask(__name__)\n\n# config用于设置各种参数信息\n# app.config['JSON_AS_ASCII'] = False\n\n# 为了后期维护的便捷性,一般来说,我们都会创建一个config.py用于配置各种配置项,然后使用app.config.from_object(config)\n# 来直接将所有的配置信息填入\napp.config.from_object(config)\n\n# 设置访问的url,此时是设置为根路径\n@app.route('/')\n\n# 与上面的路由进行绑定,此时将返回的内容作为响应正文发送\ndef index():\n return {\"username\" : \"你好\"}\n\nbooks = [\n {\"id\" : 1, \"name\" : \"三国演义\"},\n {\"id\" : 2, \"name\" : \"红楼梦\"},\n {\"id\" : 3, \"name\" : \"西游记\"},\n {\"id\" : 4, \"name\" : \"水浒传\"}\n]\n\n@app.route(\"/book/list\")\ndef book_list():\n for book in books:\n book[\"url\"] = url_for(\"book_detail\", book_id = book[\"id\"])\n # url_for类似一种回调机制,第一个参数传入callable function, 后面的则是对应的参数列表,返回的是填入后的路由\n return jsonify(books) # 在视频中必须显式转化为json,但是实际测试中,可以直接return books(或许是隐式转化?)\n\n# 当我们想要在url中传参时,就使用,能够自动的获取到var,传入绑定的函数\n#! 这不是传参,更加接近于跳转目���? --> \"GET /book/1 HTTP/1.1\" 500\n#! 差不多是不定参数作为一个url\n@app.route(\"/book/detail/\", methods = [\"GET\"]) #! 特别注意,此处的之间不允许出现空格\n# methods方式是规定可以使用哪一种请求方式\ndef book_detail(book_id):\n for book in books:\n if book_id == book[\"id\"]:\n print(book)\n return \"[INFO] success\"\n return \"[WARNING] fail\"\n\n@app.route(\"/profile\")\ndef profile():\n # url参数的传递\n user_id = request.args.get(\"id\")\n if user_id:\n return \"用户个人中心\"\n else:\n return redirect(url_for(\"index\")) # redirect,url的重定向, 301代表永久性重定向,302代表暂时性重定向+\n\nif __name__ == \"__main__\":\n app.run(debug = True) # 简单的运行, 建议在编写的过程中开启DEBUG模式,这样能够实时更改","repo_name":"ChenMiaoi/codeProgram","sub_path":"python/just_for_study/flask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"zh","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"39609307188","text":"with open(\"input.txt\", \"r\") as my_file:\n my_input = [word.strip() for word in my_file]\n\noxygen = my_input[:]\nco2_scrubber = my_input[:]\n\ncount_0 = 0\ncount_1 = 0\n\nfor i in range(len(my_input[0])):\n for item in oxygen:\n if item[i] == '0':\n count_0 += 1\n else:\n count_1 += 1\n\n if count_0 > count_1:\n most = 0\n else:\n most = 1\n \n oxygen = [x for x in oxygen if int(x[i]) == most]\n count_0 = 0\n count_1 = 0\n if len(oxygen) == 1:\n break\n\nfor i in range(len(my_input[0])):\n for item in co2_scrubber:\n if item[i] == '0':\n count_0 += 1\n else:\n count_1 += 1\n\n if count_0 > count_1:\n least = 1\n else:\n least = 0\n\n co2_scrubber = [x for x in co2_scrubber if int(x[i]) == least]\n count_0 = 0\n count_1 = 0\n if len(co2_scrubber) == 1:\n break\n\n\ndef bin_to_int(bin_array):\n dec = 0\n for i in range(len(bin_array)):\n dec += int(bin_array[i]) * 2**(len(bin_array)-i-1)\n return dec\n\nprint(bin_to_int(list(oxygen[0])))\nprint(bin_to_int(list(co2_scrubber[0])))\nprint(bin_to_int(list(oxygen[0])) * bin_to_int(list(co2_scrubber[0])))\n","repo_name":"andreaiaia/aoc","sub_path":"day03/day03p2.py","file_name":"day03p2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"46491529436","text":"import subprocess\n\ndef apache2():\n\t'''Detect an actively running instance of apache 2'''\n\tout = subprocess.Popen(['pidof', 'apache2'], stdout=subprocess.PIPE).communicate()[0]\n\tout = out.decode('utf-8').split()\n\tif len(out) != 0:\n\t\tprint('There is an actively running instance of apache2. You may want')\n\t\tprint('to investigate the cause. \\x1b[6;36;43m [Advice] \\x1b[0m')\n\t\tprint(out)\n\telse:\n\t\tprint('There are not detected instances of apache2.')\n\n\treturn(out)\n","repo_name":"Fred-Barclay/Dragon-Catcher","sub_path":"src/checks/apache2.py","file_name":"apache2.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18616313065","text":"from flask import Flask, request, jsonify, abort\nfrom collections import namedtuple\nfrom decimal import Decimal, InvalidOperation\nfrom ortools.algorithms.pywrapknapsack_solver import KnapsackSolver\nfrom flask_cors import CORS, cross_origin\nimport json\nimport re\nimport sqlite3\nfrom flask_redis import FlaskRedis\n\napp = Flask(__name__)\nredis_client = FlaskRedis(app)\nCORS(app)\n\n\ndef populate_redis_cache():\n db = sqlite3.connect('sqlite-latest.sqlite')\n cursor = db.cursor()\n query = f'SELECT typeName, typeID, volume FROM invTypes;'\n cursor.execute(query)\n print('Populating redis cache...')\n for name, type_id, volume in cursor.fetchall():\n redis_client.set(name, json.dumps({'typeId': type_id, 'volume': volume}))\n\n\nclass Item:\n def __init__(self):\n self.name = ''\n self.price = Decimal()\n self.volume = Decimal()\n self.quantity = 0\n self.typeid = 0\n self.is_split = False\n\n @property\n def price_per_volume(self):\n return self.price / self.volume\n\n @property\n def volume_per_unit(self):\n return self.volume / self.quantity\n\n @property\n def price_per_unit(self):\n return self.price / self.quantity\n\n @property\n def units_per_volume(self):\n return self.quantity / self.volume\n\n\ndef parse_price(s) -> Decimal:\n try:\n return Decimal(s[:-4].replace(',', ''))\n except InvalidOperation:\n return Decimal()\n\n\ndef parse_volume(s) -> Decimal:\n try:\n return Decimal(s[:-3].replace(',', ''))\n except InvalidOperation:\n return Decimal()\n\n\ndef parse_quantity(s) -> int:\n try:\n return int(s.replace(',', ''))\n except ValueError:\n return 1\n\n\ndef parse_items(blob):\n lines = blob.split('\\n')\n quantity_column_index = None\n volume_column_index = None\n price_column_index = None\n line = lines[0]\n values = line.split('\\t')\n for column_index, value in enumerate(values):\n if value.endswith('m3'):\n volume_column_index = column_index\n elif value.endswith('ISK'):\n price_column_index = column_index\n elif re.match(r'\\d+', value) is not None:\n quantity_column_index = column_index\n if quantity_column_index is None:\n raise RuntimeError('Unable to determine quantity column')\n if price_column_index is None:\n raise RuntimeError('Unable to determine est. price column')\n items = []\n for line in lines:\n values = line.split('\\t')\n item = Item()\n item.name = values[0]\n db_item = redis_client.get(item.name)\n if db_item is not None:\n db_item = json.loads(db_item)\n item.typeid = db_item.get('typeId', None) if db_item is not None else None\n item.quantity = parse_quantity(values[quantity_column_index])\n item.price = parse_price(values[price_column_index]) if price_column_index is not None else 0\n item.volume = Decimal(db_item['volume']) * item.quantity if volume_column_index is None else parse_volume(values[volume_column_index])\n items.append(item)\n return items\n\n\nclass Packing:\n def __init__(self):\n self.items = []\n self.volume = Decimal()\n self.price = Decimal()\n\n\ndef pack_items(items, volume: Decimal, should_allow_splitting: False, value_limit: Decimal('inf')):\n # The solver only works with integers, so we need to multiply the volumes\n # so all significant figures are represented.\n value = value_limit\n if should_allow_splitting:\n # fractional knapsack problem\n packed_items = []\n items.sort(key=lambda x: x.price_per_volume, reverse=True)\n for item in items:\n if volume < 0:\n break\n if item.volume < volume and item.price < value:\n packed_items.append(item)\n volume -= item.volume\n value -= item.price\n else:\n quantity = int(volume / item.volume_per_unit)\n if value.is_finite():\n quantity = min(quantity, int(value / item.price_per_unit))\n if quantity < 1:\n continue\n else:\n volume_per_unit = item.volume_per_unit\n price_per_unit = item.price_per_unit\n new_item = Item()\n new_item.name = item.name\n new_item.quantity = quantity\n new_item.volume = volume_per_unit * quantity\n new_item.price = price_per_unit * quantity\n new_item.typeid = item.typeid\n new_item.is_split = True\n packed_items.append(new_item)\n volume -= new_item.volume\n value -= new_item.price\n\n else:\n values = list(map(lambda x: x.price, items))\n weights = [list(map(lambda x: x.volume * 100, items))]\n capacities = [float(volume * 100)]\n\n solver = KnapsackSolver(\n KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,\n 'Evepacker'\n )\n\n solver.Init(values, weights, capacities)\n solver.Solve()\n packed_items = []\n\n for i in range(len(values)):\n if solver.BestSolutionContains(i):\n if values[i] > value:\n continue\n packed_items.append(i)\n value -= values[i]\n\n packed_items = [items[p] for p in packed_items]\n\n return packed_items\n\n\ndef get_total_volume(items):\n return float(sum(map(lambda x: x.volume, items)))\n\n\ndef get_total_price(items):\n return float(sum(map(lambda x: x.price, items)))\n\n\n@app.route('/api/ping', methods=['GET'])\n@cross_origin()\ndef ping():\n return jsonify({'ping': 'pong'}), 200\n\n\n@app.route('/api/pack', methods=['POST'])\n@cross_origin()\ndef pack():\n # Volume\n try:\n volume = Decimal(request.json['volume'].replace(',', ''))\n except InvalidOperation as e:\n return jsonify(message='Volume cannot be parsed'), 400\n should_allow_splitting = bool(request.json.get('should_allow_splitting', True))\n\n # Value Limit\n value_limit = Decimal('inf')\n try:\n value_limit = Decimal(request.json.get('value_limit', Decimal('inf')))\n except InvalidOperation:\n return jsonify(message='Value limit cannot be parsed'), 400\n\n if not should_allow_splitting and value_limit.is_finite():\n return jsonify(message='Cannot limit value if stack splitting is disabled'), 400\n\n try:\n items = parse_items(request.json['blob'])\n packed_items = pack_items(items, volume, should_allow_splitting, value_limit)\n return jsonify({\n 'price': get_total_price(packed_items),\n 'volume': get_total_volume(packed_items),\n 'total_price': get_total_price(items),\n 'total_volume': get_total_volume(items),\n 'items': list(map(lambda x: {\n 'name': x.name,\n 'typeid': x.typeid,\n 'quantity': x.quantity,\n 'is_split': x.is_split,\n 'volume': str(x.volume),\n 'price': str(x.price)}, packed_items))\n })\n except RuntimeError as error:\n return jsonify(message=error), 400\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n\n# populate_redis_cache()\n","repo_name":"cmbasnett/evepacker-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41358993303","text":"import os\nimport json\n\nfrom tensorflow.python.platform import flags\n\nFLAGS = flags.FLAGS\n\n\ndef define_common_flags():\n \"\"\"Define common flags.\"\"\"\n # common flags\n flags.DEFINE_integer('batch_size', 1, 'Batch size.')\n flags.DEFINE_integer('crop_width', None, 'Width of the central crop for images.')\n flags.DEFINE_integer('crop_height', None, 'Height of the central crop for images.')\n flags.DEFINE_string('train_log_dir', 'my_logs', # default: logs\n 'Directory where to write event logs.')\n flags.DEFINE_string('dataset_name', 'van', 'Name of the dataset. Supported: fsns')\n flags.DEFINE_string('model_name', 'model', 'Name of the model.')\n flags.DEFINE_string('split_name', 'train', 'Dataset split name to run evaluation for: test,train.')\n flags.DEFINE_string('data_root', None, 'Data root folder.')\n flags.DEFINE_string('checkpoint', '', 'Path for checkpoint to restore weights from.')\n flags.DEFINE_string('master', '', 'BNS name of the TensorFlow master to use.')\n flags.DEFINE_bool('do_augment', False, '')\n\n # Model hyper parameters\n flags.DEFINE_float('learning_rate', 0.004, 'learning rate')\n flags.DEFINE_string('optimizer', 'momentum', 'the optimizer to use')\n flags.DEFINE_float('momentum', 0.9, 'momentum value for the momentum optimizer if used')\n flags.DEFINE_bool('use_augment_input', True, 'If True will use image augmentation')\n\n # Method hyper parameters\n # conv_tower_fn\n flags.DEFINE_string('final_endpoint', 'Mixed_5d', 'Endpoint to cut inception tower')\n\n # sequence_logit_fn\n flags.DEFINE_bool('use_attention', True, 'If True will use the attention mechanism')\n flags.DEFINE_bool('use_autoregression', True, 'If True will use autoregression (a feedback link)')\n flags.DEFINE_integer('num_lstm_units', 256, 'number of LSTM units for sequence LSTM')\n flags.DEFINE_float('weight_decay', 0.00004, 'weight decay for char prediction FC layers')\n flags.DEFINE_float('lstm_state_clip_value', 10.0,\n 'cell state is clipped by this value prior to the cell output activation')\n\n # 'sequence_loss_fn'\n flags.DEFINE_float('label_smoothing', 0.1, 'weight for label smoothing')\n flags.DEFINE_bool('ignore_nulls', True, 'ignore null characters for computing the loss')\n flags.DEFINE_bool('average_across_timesteps', False, 'divide the returned cost by the total label weight')\n flags.DEFINE_bool('use_location', False, 'If true will use location attention')\n\n\ndef print_flags(filename=None):\n info = '-' * 35 + 'FLAGS' + '-' * 35 + '\\n'\n flag_dict = {}\n\n ignore_names = {'help', 'helpshort', 'helpfull'} # Set literal construction\n\n for _, flag in sorted(FLAGS._flags().items()):\n\n if flag.name in ignore_names:\n continue\n\n comment = ''\n if flag.value != flag.default:\n comment = '\\t[default: {}]'.format(flag.default)\n info += '{:>20}: {:<30}{}\\n'.format(flag.name, str(flag.value), comment)\n\n flag_dict[flag.name] = str(flag.value)\n info += '-' * 75 + '\\n'\n\n print(info)\n\n if filename:\n dirname = os.path.dirname(filename)\n if dirname and not os.path.isdir(dirname):\n os.makedirs(dirname)\n with open(filename, 'w', encoding='utf-8') as file:\n json.dump(flag_dict, file, indent=4)\n","repo_name":"linyuhui/tensorflow-CRNN","sub_path":"python/utils/tf_utils.py","file_name":"tf_utils.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32582405796","text":"import cherrypy\nimport logging\n\nfrom app.common import CommonTools\nfrom app.common import Constants\nfrom app.business.webapp import BotUser\nfrom app.handler import WebHandler\n\nfrom app.controller.RobotController import Robot\n\n\nclass Login(object):\n\n __log = logging.getLogger()\n\n robot = Robot()\n\n @cherrypy.expose\n def index(self):\n if WebHandler.checkSession():\n return WebHandler.render_template(templatename=\"index.html\", title='首页')\n # cherrypy.lib.sessions.expire()\n # print 'aaaa=' + cherrypy.request.__getattribute__().id\n # print 'dddd=' + cherrypy.session['_sessionid']\n #raise cherrypy.HTTPRedirect(\"/login\")\n #raise cherrypy.HTTPRedirect(\"/login\")\n\n @cherrypy.expose\n def login(self):\n return WebHandler.render_template(templatename=\"signin.html\", title='登录')\n\n # 登录\n @cherrypy.tools.allow(methods=['POST'])\n @cherrypy.tools.json_in(on=True)\n @cherrypy.tools.json_out(on=True)\n @cherrypy.expose\n def loginIn(self):\n request = cherrypy.request.json\n wxnum = request['wxnum']\n pwd = CommonTools.md5(request['pwd'])\n\n self.__log.debug(\"[*] 账号[%s] 登录...\", wxnum)\n\n flag = BotUser.queryUserByName(wxnum,pwd)\n\n self.__log.debug(\"[*] 账号[%s] 登录结果 %s\", wxnum,flag)\n\n if flag :\n # 登录成功\n # 加载用户session\n cherrypy.session['_sessionid'] = cherrypy.session.id\n return {'stauts': True}\n else:\n return {'stauts': False}\n\n @cherrypy.expose\n def register(self):\n return WebHandler.render_template(templatename=\"signup.html\", title='注册')\n\n # 注册\n @cherrypy.tools.allow(methods=['POST'])\n @cherrypy.tools.json_in(on=True)\n @cherrypy.tools.json_out(on=True)\n @cherrypy.expose\n def registerIn(self):\n request = cherrypy.request.json\n\n wxnum = request['wxnum']\n pwd = CommonTools.md5(request['pwd'])\n mobile = request['mobile']\n\n # 查询该用户是否存在\n flag = BotUser.queryUserByName(wxnum)\n\n if flag :\n return {'stauts': False,'msg':'用户已存在 ! '}\n else:\n flag = BotUser.regeiter(wxnum, pwd,mobile)\n if flag :\n # 注册成功\n return {'stauts': True}\n else:\n return {'stauts': False}","repo_name":"liuqi0725/smileTools","sub_path":"app/controller/LoginController.py","file_name":"LoginController.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39484550275","text":"################################################################################\n# citlalatonac.py #\n# Citlalatonac is the name of the Aztec god who created the stars #\n# Oscar Barragan, March 2021 #\n################################################################################\n\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport sys\nsys.path.append(\"../\")\nimport pyaneti as pti\nfrom numpy.random import multivariate_normal\nimport seaborn as sns\nfrom scipy.interpolate import interp1d\nfrom matplotlib import gridspec\nsns.set(style='ticks')\nsns.set_color_codes('deep')\n\n#Details on how astroplan works here -> https://astroplan.readthedocs.io/en/latest/tutorials/summer_triangle.html\nfrom astroplan import Observer\nfrom astropy.coordinates import SkyCoord\nfrom astroplan import FixedTarget\nfrom astropy.time import Time\n\n#Brute force function to create times in which the target is observed from a given observatory\n#This function create a times vector of lenght ndata in which the star is observed at the observatory\n#in the interval between tmin and tmax\ndef create_real_times(tmin,tmax,ndata=50,air_mass_limit=1.5,tformat='mjd',star='K2-100',observatory='lapalma'):\n times = []\n #Create a observatory instance with astroplan\n observatory = Observer.at_site(observatory)\n #Create star object from astroplan, the name has to be a valid simbad name for the target\n star = FixedTarget.from_name(star)\n while len(times) < ndata:\n #Draw random time between tmin and tmax\n drt = np.random.uniform(tmin,tmax)\n #Get the time object from astropy.time\n time = Time(drt,format=tformat)\n #Compute the air_mass that the target has at time t\n air_mass = observatory.altaz(time,star).secz\n #If the target is observable at time drt and the air_mass < air_mass_limit then\n #We accept the dummy random time\n if observatory.target_is_up(time,star) and air_mass < air_mass_limit:\n times.append(drt)\n\n #Sort thet times\n times = sorted(times)\n\n #Return a numpy array with all the times\n return np.array(times)\n\n\nclass citlali():\n \"\"\"\n Class to create simulated RVs and acitivity/simmetry indicators assuming they all can be described\n by the same Gaussian Process (following Rajpaul et al., 2015, MNRAS, 442, 2269).\n \"\"\"\n\n\n def __init__(self,time=[],tmin=0,tmax=60,nseries=3,\\\n amplitudes=[0.0058,0.0421,0.024,0.0,0.02,-0.86],\n kernel_parameters=[31.2,0.55,4.315], kernel='QPK',\n time_series=[],\n points_per_day=10,seed=123):\n \"\"\"\n Input parameters:\n tmin -> minimum temporal value\n tmax -> maximum temporal value\n amplitudes -> Amplitudes of the mutli-GP approach, each time-series has to amplitudes following Rajpaul et al., 2015.\n kernel_parameter -> Hyper-parameters for the given kernel\n kernel -> Chose the kernel,Quasi-Periodic Kernel 'QPK', Matern 5/2 'M52', Exponential 'EXP'\n time_series -> time_series for the symmetry/activity indicators, the RV time-series is labelled by default as 'rvs'\n seed -> Set a seed for random numbers\n\n The instance has the following attributes:\n amplitudes -> Amplitudes that relate the time-series (see Rajpaul et al., 2015)\n time -> time-stamps between tmin and tmax\n seed -> Seed used to create the time-series\n gp_rvs -> GP induced RV time-series\n time_series -> Name of the time-series\n rvs -> RV time-series\n \"\"\"\n\n #Attributes to be stored in the class\n self.kernel = kernel\n self.kernel_parameters = kernel_parameters\n #Multi-GP amplitudes as attribute\n self.amplitudes = amplitudes[:]\n\n if len(time) > 0:\n self.time = time\n else:\n #Create vector time\n self.time = np.linspace(tmin,tmax,int(points_per_day*(tmax-tmin)))\n\n #Initiate random seed\n self.seed = seed\n np.random.seed(self.seed)\n\n #Create timeseries to be used in case they were not given as input\n if len(time_series) == 0: time_series = [ 'a'+str(i) for i in range(1,nseries)]\n\n #Generate time_series attribute with the name of all the time-series contained in the instance\n self.time_series = np.concatenate([['rvs'],time_series])\n\n #Create vector with nseries repetions for self.time (required by pyaneti)\n self.bigtime = np.array(np.concatenate([list(self.time)]*nseries))\n\n #Create vector with hyper parameters as required in covfunc input\n gp_parameters = np.concatenate([amplitudes,kernel_parameters])\n\n #Get the kernel label that we need to compute the correlation matrix with pyaneti\n mi_kernel = ''\n if self.kernel == 'QPK':\n mi_kernel = 'MQ'+str(nseries)\n elif self.kernel == 'SQP':\n mi_kernel = 'SQ'+str(nseries)\n elif self.kernel == 'M52':\n mi_kernel = 'MM'+str(nseries)\n elif self.kernel == 'EXP':\n mi_kernel = 'ME'+str(nseries)\n else:\n print(\"The input kernel is not supported. Supported kernels are: \\n\")\n print(\"QPK -> Quasi-Periodic Kernel\\n\")\n print(\"M52 -> Matern 5/2 Kernel\\n\")\n print(\"EXP -> Exponential Kernel\\n\")\n sys.exit()\n\n #Compute the covariance matrix\n cov = pti.covfunc(mi_kernel,gp_parameters,self.bigtime,self.bigtime)\n\n #Draw a sample\n ceros = np.zeros(len(self.bigtime))\n samples = multivariate_normal(ceros,cov,size=1)\n #samples contains a big vector with the RVs and all the activity indicators\n\n #Lenght of the time vector\n lt = len(self.time)\n\n #Separate the big sample in multi-dimensional samples\n\n #Extract the RVs and put them in the gp_rvs atribute\n self.gp_rvs = np.array(samples[0][0:lt])\n\n #Generate all the attributes with the time-series\n #each time-series is labeled\n for i,label in enumerate(self.time_series):\n setattr(self, label, np.array(samples[0][i*lt:(i+1)*lt]))\n\n\n def add_planet(self,planet_params=[0,0.011,1.67,0,np.pi/2],planet_name='planet_b'):\n \"\"\"\n This method adds a RV planet signal following a Keplerian orbit where\n T0 = time of minimum conjunction\n K = Semi-amplitude of the planet induced RV signal\n P = planetary orbital period\n e = orbit eccentricity\n w = angle of periastron\n Input parameters:\n planet_params -> has to be given as T0, K, P, e, w\n planet_name -> Name of the planet, default is 'planet_b'\n \"\"\"\n\n #Create planet_name atrribute with the exoplanet parameters (planet_params)\n setattr(self,planet_name,planet_params)\n\n #Compute the Keplerian curve with the input planet parameters using pyaneti\n prv = pti.rv_curve_mp(self.time,0.0,*planet_params,0.0,0.0)\n\n #Set the rv_planet_name attribute with the induced RV signal for the actual planet\n setattr(self,'rv_'+planet_name,prv)\n\n #Create the planet_names attribute (an empty list) if has not beed previously defined\n if not hasattr(self,'planet_names'):\n self.planet_names = []\n\n #The following lines will run only if the planet has not beed added previously\n #This avoids to add the same planet more than once, to add more than one planet\n #each planet has to have a different name\n if planet_name not in self.planet_names:\n self.planet_names.append(planet_name)\n self.rvs = self.rvs + getattr(self,'rv_'+planet_name)\n #the planet signal has been added\n\n def remove_planet(self,planet_name='planet_b'):\n \"\"\"\n Remove the planet planet_name from the RV signal (self.rvs)\n \"\"\"\n\n if planet_name in self.planet_names:\n #Remove the planet signal\n self.rvs = self.rvs - getattr(self,'rv_'+planet_name)\n #Remove the attributes corresponding to the planet\n delattr(self,'rv_'+planet_name)\n delattr(self,planet_name)\n else:\n #There is no planet to remove\n print('There is no {} to remove'.format(planet_name))\n\n\n def create_data(self,t=[],ndata=0):\n \"\"\"\n This method creates the *_data attributes\n *_data atributes mimic the observations that we want to analyse with pyaneti\n #these attributes can be modified with red and white noise\n There are three ways in which data are created\n if the t vector is provided, then the data points are created at each element of t\n if ndata = X where X is larger than zero, then the code will create X random observations\n if none is specified, then the code assumes that all of the model points are observations\n \"\"\"\n\n #First check if we are given an input vector of times to create the data stamps\n if len(t) > 0:\n #If yes, create the time-stamps doing interpolation\n self.ndata = len(t)\n self.time_data = t\n for label in self.time_series:\n f = interp1d(self.time,getattr(self,label), kind='cubic')\n setattr(self,label+'_data',f(self.time_data))\n #We can also say how many ramdom points we want to extract from the sample\n elif (ndata > 0):\n if ndata > len(self.time):\n self.ndata = len(self.time)\n else:\n self.ndata = ndata\n #extract the indices\n #in this option is selected randomly from an uniform distribution\n indices = np.random.random_integers(0,len(self.time),self.ndata)\n #The *_data attributes are filled using indices\n self.time_data = self.time[indices]\n for label in self.time_series:\n setattr(self,label+'_data',getattr(self,label)[indices])\n #If user does not specify, the code assumes that all the sample will be used as data\n else:\n self.ndata = len(self.time)\n self.time_data = self.time[:]\n for label in self.time_series:\n setattr(self,label+'_data',getattr(self,label))\n\n\n def add_white_noise(self,err=[]):\n \"\"\"\n Add white noise to the simulated data\n You need to run get_data_from_sample before\n #err can be a list in which element is rather,\n a float indicating the error in each time_series or\n a list with individual errors for each time_series\n \"\"\"\n\n #First check if the data attributes have been created, if not, create them\n if not hasattr(self,'time_data'):\n print(\"You have not created the *_data atributes yet!\")\n return\n\n #Avoids the code to crash in case the input is not a list\n if err.__class__ == float:\n err = [err]\n\n #If the list is not as requested, the values are set randomly\n if len(err) == 0 or len(err) < len(self.time_series):\n #If user does not specify the error, the error is computed randomly\n err = np.random.uniform(1e-5,1e-3,len(self.time_series))\n\n #Add white noise to each time-series\n for i, label in enumerate(self.time_series):\n #Create the label+'_err'\n setattr(self,label+'_err',err[i])\n #Modify the label+'_data' by adding the white noise\n setattr(self,label+'_data',np.random.normal(getattr(self,label+'_data'),getattr(self,label+'_err')))\n\n\n def add_white_noise_list(self,err=[]):\n \"\"\"\n Add white noise to the simulated data where the user gives lists with each error bar\n For each time-series\n You need to run get_data_from_sample before\n #err has to be a list of lists containing errors\n a float indicating the error in each time_series or\n a list with individual errors for each time_series\n \"\"\"\n\n #First check if the data attributes have been created, if not, create them\n if not hasattr(self,'time_data'):\n print(\"You have not created the *_data atributes yet!\")\n return\n\n\n #Add white noise to each time-series\n for i, label in enumerate(self.time_series):\n for j in range(len(self.time)):\n #Create the label+'_err'\n setattr(self,label+'_err',err[i])\n #Modify the label+'_data' by adding the white noise\n setattr(self,label+'_data',np.random.normal(getattr(self,label+'_data'),getattr(self,label+'_err')))\n\n\n def add_red_noise(self,se_parameters=[1e-4,1]):\n \"\"\"\n Add red noise to each time-series using a square-exponential kernel\n It allows for a different red noise set of hyperparameters per each time-series\n \"\"\"\n\n #First check if the data attributes have been created, if not, create them\n if not hasattr(self,'time_data'):\n print(\"You have not created the *_data atributes yet!\")\n return\n\n kernel_parameters = []\n #Check if the user is providing enough number of square exponential parameters per each time-series\n if len(se_parameters) < len(self.time_series):\n #We add the same hyperparameters for all the time-series\n #this is not recommended!\n for i in self.time_series:\n kernel_parameters.append(se_parameters)\n else:\n kernel_parameters = se_parameters[:]\n #Now kernel_parameters is a list where each element is a two-element list with hyperparameters of a square-exponential kernel\n\n #Add red noise to each time-series\n for i,label in enumerate(self.time_series):\n #Let's start by adding the same level of noise to all time-series\n #Add red noise by adding a sample of a quasi periodic kernel\n cov = pti.covfunc('SEK',kernel_parameters[i],self.time_data,self.time_data)\n #Draw a sample\n ceros = np.zeros(len(self.time_data))\n sample = multivariate_normal(ceros,cov)\n #Add the sample to the corresponding time-series\n setattr(self, label+'_data', getattr(self,label+'_data') + sample)\n\n\n def periodogram_rvs(self,freqs=np.linspace(0.01,10,100)):\n from scipy.signal import lombscargle\n self.pgram = lombscargle(self.time_data,self.rvs_data,freqs,normalize=True)\n plt.ylabel('Power')\n plt.xlabel('Period')\n plt.plot(1/freqs,self.pgram)\n plt.show()\n\n def plot(self,fsx=10,fsy=10./4.,save=False,fname='timeseries.pdf',show=True):\n\n nseries = len(self.time_series)\n\n plt.figure(figsize=(fsx,nseries*fsy))\n gs = gridspec.GridSpec(nrows=nseries,ncols=1)\n gs.update(hspace=0.002)\n plt.subplot(gs[0])\n plt.plot(self.time,self.rvs,'-',label='RV')\n if hasattr(self,'planet_names'):\n for planet in self.planet_names:\n plt.plot(self.time,getattr(self,'rv_'+planet),'-',label=planet)\n if hasattr(self,'time_data'):\n plt.plot(self.time_data,self.rvs_data,'o',label='simulated data')\n plt.ylabel('RV [km/s]')\n plt.legend(ncol=1,scatterpoints=1,numpoints=1,frameon=True)\n\n try:\n for i,label in enumerate(self.time_series[1:]):\n plt.subplot(gs[i+1])\n plt.ylabel(label)\n plt.plot(self.time,getattr(self,label),'-',label=label)\n try:\n plt.plot(self.time_data,getattr(self,label+'_data'),'o',label='simulated data')\n except:\n pass\n plt.legend(ncol=1,scatterpoints=1,numpoints=1,frameon=True)\n except:\n pass\n\n plt.xlabel('Time [days]')\n\n if save: plt.savefig(fname,format='pdf',bbox_inches='tight')\n\n if show: plt.show()\n\n\n def save_data(self,fname='multigp_data.dat'):\n \"\"\"\n Save the data in the format that pyaneti needs to run\n Time Value Value_error label\n \"\"\"\n\n #First check if the data attributes have been created, if not, create them\n if not hasattr(self,'time_data'):\n print(\"You have not created the *_data atributes yet!\")\n return\n\n with open(fname,'w') as f:\n f.write('# {} \\n'.format(fname))\n if hasattr(self,'planet_names'): f.write('# Number of planets = {} \\n'.format(len(self.planet_names)))\n f.write('# Number of simulated observations = {} \\n'.format(self.ndata))\n f.write('# Kernel used : {}, with parameters: {} \\n'.format(self.kernel,self.kernel_parameters))\n f.write('# Random number seed = {} \\n'.format(self.seed))\n f.write('# Time Value Value_error time_series_label \\n')\n for label in self.time_series:\n for i in range(len(self.time_data)):\n f.write(\"{:1.7e} {:1.7e} {:1.7e} {}\\n\".format(self.time_data[i],getattr(self,label+'_data')[i], \\\n getattr(self,label+'_err'),label))","repo_name":"oscaribv/pyaneti","sub_path":"pyaneti_extras/citlalatonac.py","file_name":"citlalatonac.py","file_ext":"py","file_size_in_byte":17361,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"52"} +{"seq_id":"11409703448","text":"from textual import events\nfrom textual.app import App\nfrom textual.widgets import Header, Footer, Placeholder, ScrollView\n\nimport customWidgets\n\nfrom rich.panel import Panel\nfrom rich.table import Table\nfrom rich.live import Live\nfrom rich.layout import Layout\nfrom rich.text import Text\n\n\nfrom textual.reactive import Reactive\nfrom textual.widget import Widget\n\nfrom textual_inputs.text_input import TextInput\n\ncol1 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol2 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol3 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol4 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol5 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol6 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol7 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol8 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\ncol9 = [\".\", \".\", \".\", \".\", \".\", \".\", \".\" ,\".\" ,\".\"]\nrows = [col1, col2, col3, col4, col5, col6, col7 ,col8, col9]\n\ncurrentCol = 0\ncurrentRow = 0\npreviousCol = 0\npreviousRow = 0\n\nblackTurn = True\n\n# increments the col by an increment number, checks to make sure increment is valid\ndef incCol(increment:int):\n global currentCol\n if increment > 0:\n if currentCol < 8:\n currentCol += increment\n elif increment < 0:\n if currentCol > 0:\n currentCol += increment\n\n# increments the row by an increment number, checks to make sure increment is valid\ndef incRow(increment:int):\n global currentRow\n if increment > 0:\n if currentRow < 8:\n currentRow += increment\n elif increment < 0:\n if currentRow > 0:\n currentRow += increment\n\n# widget that creates the go board\nclass goBoard(Widget):\n def on_mount(self):\n self.set_interval(.001, self.refresh)\n def render(self):\n grid = Table.grid(expand=True)\n\n # creates top label row\n def label(number: int):\n return Panel(str(number))\n grid.add_row(label(0), label(1), label(2), label(3), label(4), label(5), label(6), label(7), label(8), label(9))\n \n # creates a Panel with the value of column[index]\n def cell(column:list, index:int):\n return Panel(str(column[index]))\n\n # renders empty grid, with side labels\n i = 1\n for col in rows:\n var = None\n grid.add_row(Panel(str(i)), cell(col, 0), cell(col, 1), cell(col, 2), cell(col, 3), cell(col, 4), cell(col, 5), cell(col, 6), cell(col, 7), cell(col, 8))\n i +=1\n result = Panel(grid)\n result.title = \"9x9 Board\"\n return result\n\nerrorMessage:str = \"\"\nclass sidePanel(Widget):\n def on_mount(self):\n self.set_interval(.01, self.refresh)\n def render(self):\n global errorMessage, blackTurn\n player = Panel(\"Black\" if blackTurn else \"White\")\n player.title = \"Player\"\n instructions = Panel(\"Resize your terminal window to ensure you can see all 9 columns and rows of the board before continuing. \\n\\nPress H (lowercase) to toggle instructions panel. \\nPress Q (lowercase) or ESCAPE to quit. \\nUse WASD (lowercase) to navigate. \\nPress 1 to place piece\")\n instructions.title = \"Instructions\"\n errors = Panel(errorMessage)\n errors.title = \"Errors\"\n errors.style = \"red\"\n layout = Layout()\n layout.split_column(\n player,\n instructions,\n errors\n )\n return layout\n\nclass MyApp(App):\n async def on_load(self, event: events.Load) -> None:\n \"\"\"Bind keys with the app loads (but before entering application mode)\"\"\"\n await self.bind(\"h\", \"view.toggle('sidePanel')\", \"Toggle instructions\")\n await self.bind(\"q\", \"quit\", \"Quit\")\n await self.bind(\"escape\", \"quit\", \"Quit\")\n await self.bind(\"w\", \"\", \"Up\")\n await self.bind(\"a\", \"\", \"Left\")\n await self.bind(\"s\", \"\", \"Down\")\n await self.bind(\"d\", \"\", \"Right\")\n await self.bind(\"1\", \"\", \"Place Piece\")\n await self.bind(\"C\", \"\", \"Clear Errors\")\n\n async def on_mount(self, event: events.Mount) -> None:\n \"\"\"Create and dock the widgets.\"\"\"\n # Header / footer / dock\n await self.view.dock(customWidgets.Header(), name=\"header\", edge=\"top\")\n await self.view.dock(customWidgets.Footer(), edge=\"bottom\")\n await self.view.dock(sidePanel(), edge=\"left\", size=50, name=\"sidePanel\")\n # Dock the body in the remaining space\n await self.view.dock(goBoard(), edge=\"right\")\n\n # set first cell to \"active\" state\n rows[currentRow][currentCol] = \"*\" + str(rows[currentRow][currentCol]) + \"*\"\n\n async def on_key(self, event):\n # use variables declared outside of function\n global previousRow, previousCol, currentRow, currentCol, blackTurn, errorMessage\n \n # remove select icon from previously selected cell\n previousRow = currentRow\n previousCol = currentCol\n rows[previousRow][previousCol] = str(rows[previousRow][previousCol]).replace(\"*\", \"\")\n\n # selects row\n if event.key == \"w\":\n incRow(-1)\n elif event.key == \"a\":\n incCol(-1)\n elif event.key == \"s\":\n incRow(1)\n elif event.key == \"d\":\n incCol(1)\n # add select icon to current cell\n rows[currentRow][currentCol] = \"*\" + str(rows[currentRow][currentCol]) + \"*\"\n\n # place piece\n if event.key == \"1\":\n if rows[currentRow][currentCol] == \"*.*\":\n if blackTurn:\n rows[currentRow][currentCol] = \"*\" + \"●\" + \"*\"\n else:\n rows[currentRow][currentCol] = \"*\" + \"○\" + \"*\"\n blackTurn = not blackTurn\n else:\n errorMessage = errorMessage + \"Pieces may only be placed in empty cells\\n\"\n \n # clear error messages\n if event.key == \"c\":\n errorMessage = \"\"\n\nMyApp.run(title=\"Module 7 Team Lab Go Game - Micah Guttman\", log=\"textual.log\")","repo_name":"memtech3/GoGameBoard","sub_path":"goGame.py","file_name":"goGame.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"5218671138","text":"# Libraries\nfrom ast import Return\nfrom http.client import ResponseNotReady\nfrom os import stat\nimport re\nfrom unicodedata import name\nfrom urllib import request, response\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework import status,generics,viewsets\nfrom django.contrib.auth import authenticate\nfrom rest_framework.decorators import api_view, APIView\nfrom .tokens import User, create_jwt_pair_for_user\nfrom django.shortcuts import get_list_or_404\nfrom rest_framework.decorators import action\n\n# Models and serializers\nfrom . import models,serializers\n\n#-------------------------------------------------------------------------------------------#\n#-------------------------------------------------------------------------------------------#\n\n #API GET DATA USERS\n@api_view(http_method_names=[\"GET\"])\ndef getUsers (request:Request):\n users = models.Users.objects.all()\n\n serializer = serializers.UsersModelSerializers(instance = users, many = True)\n\n return Response(data = serializer.data, status= status.HTTP_200_OK)\n\n#API GET DATA USER WITCH ID_USER\n@api_view(http_method_names=[\"GET\"])\ndef getUser(request:Request , post_id:int):\n users = get_list_or_404(models.Users, pk=post_id)\n\n serializer = serializers.UsersModelSerializers(instance=users, many = True)\n\n response = {\n \"massage\" : \"resulted\",\n \"data\" : serializer.data ,\n \"status\" : status.HTTP_200_OK\n }\n\n return Response(data = response, status = status.HTTP_200_OK)\n\n#API POST USERS\n@api_view(http_method_names=[\"POST\"])\ndef postUser (request:Request):\n users = models.Users.objects.all()\n\n if request.method == \"POST\":\n data = request.data\n\n serializer = serializers.UsersSerializers(data = data , many = True)\n\n if serializer.is_valid():\n serializer.save()\n\n response = {\n \"massage\": \"create register of user\",\n \"data\" : serializer.data\n }\n\n return Response(data = response, status= status.HTTP_201_CREATED )\n\n return Response(data = serializer.errors, status= status.HTTP_400_BAD_REQUEST)\n\nclass Login(APIView):\n permission_classes = []\n\n def post(self, request:Request):\n email = request.data.get('email'),\n password = request.data.get('password')\n\n user = authenticate(email=email, password = password)\n\n if user is not None:\n response = {\n \"message\" : \"login sucessful\",\n \"token\" : user.auth_token.key\n }\n return Response(data = response, status = status.HTTP_200_OK)\n else:\n return Response(data = {\"messsage\":\"invalid email or password\"})\n\n def get(self, request : Request):\n content = {\n \"user\":str(request.user),\n \"auth\":str(request.auth)\n }\n\n return Response(data= content, status= status.HTTP_200_OK)\n\nclass signup(APIView):\n permission_classes = []\n serializer_class = serializers.UsersModelSerializers\n\n def post(self, request:Request):\n data = request.data\n\n serializer = self.serializer_class(data=data)\n\n if serializer.is_valid():\n serializer.save()\n\n response = {\n \"massage\":\"user created exist\",\n \"data\" : serializer.data\n }\n\n return Response (data=response, status= status.HTTP_200_OK)\n \n return Response (\n data={\"message\":\"error in the request\",\"status\":status.HTTP_400_BAD_REQUEST}, \n status=status.HTTP_400_BAD_REQUEST)\n \n\n \n\n","repo_name":"stevenmontoyat01/styletattoo_backend","sub_path":"Tatoo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1551751913","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nsess = tf.InteractiveSession()\r\nmnist = input_data.read_data_sets('MNIST_data', one_hot=True)\r\ndef weights(shape, name):\r\n return tf.get_variable(name=name, shape=shape, initializer=tf.contrib.layers.xavier_initializer())\r\ndef bias(shape, name):\r\n return tf.get_variable(name=name, shape=shape, initializer=tf.constant_initializer(0))\r\n\r\nC0 = tf.placeholder(tf.float32, shape=[None, 10])\r\nC_FAKE = tf.placeholder(tf.float32, shape=[None, 10])\r\n\r\n# 生成网络 G\r\nZ = tf.placeholder(tf.float32, shape=[None, 50], name='Z')\r\nC_G = tf.tile(C0,[1,5])\r\nG_INPUT = tf.concat([Z,C_G],1)\r\nth_G = [ weights([100, 256], 'G_W1'),bias([256], 'G_b1'),\r\n weights([256, 784], 'G_W2'),bias([784], 'G_b2')]\r\ndef GNET(z):\r\n h = tf.nn.relu(tf.matmul(z, th_G[0]) + th_G[1])\r\n G = tf.nn.sigmoid(tf.matmul(h, th_G[2]) + th_G[3])\r\n return G\r\n\r\n# 辨别网络 D\r\nX = tf.placeholder(tf.float32, shape=[None, 784])\r\nC_D = tf.tile(C0,[1,20])\r\nC_DF = tf.tile(C_FAKE,[1,20])\r\n\r\n\r\nth_D = [ weights([984, 256], 'D_W1'),bias([256], 'D_b1'),\r\n weights([256, 1], 'D_W2'),bias([1], 'D_b2')]\r\n\r\ndef DNET(x):\r\n h = tf.nn.relu(tf.matmul(x, th_D[0]) + th_D[1])\r\n D = tf.nn.sigmoid(tf.matmul(h, th_D[2]) + th_D[3])\r\n return D\r\n\r\nX_G = GNET(G_INPUT)\r\n\r\nD_INPUT0 = tf.concat([X,C_D],1)\r\nd_real_match = DNET(D_INPUT0)\r\nD_INPUTG = tf.concat([X_G,C_D],1)\r\nd_fake = DNET(D_INPUTG)\r\nD_INPUTG = tf.concat([X,C_DF],1)\r\nd_real_NOT_match = DNET(D_INPUTG)\r\n\r\nL_D = -tf.reduce_mean(tf.log( d_real_match ) + tf.log(1.0 - d_fake)+ tf.log(1.0 - d_real_NOT_match))\r\nL_G = -tf.reduce_mean(tf.log(d_fake))\r\nD_train= tf.train.AdamOptimizer(1.0e-4).minimize(L_D, var_list=th_D)\r\nG_train= tf.train.AdamOptimizer(1.0e-4).minimize(L_G, var_list=th_G)\r\nsess.run(tf.global_variables_initializer())\r\n\r\ndef GET_FAKE_C(y):\r\n N=y.shape[0]\r\n y1=1-y+np.random.uniform(0.0,0.1,(N,10))\r\n argy=np.argmax(y1,axis=1)\r\n yN=np.zeros((N,10))\r\n for i in range(N):yN[i,argy[i]]=1\r\n return yN\r\n\r\n\r\nfor i in range(100000):\r\n xs, ys = mnist.train.next_batch(64)\r\n ysN=GET_FAKE_C(ys)\r\n zs=np.random.uniform(-1.0, 1.0, size=[64, 50])\r\n _,ld,_,lg=sess.run([D_train, L_D,G_train,L_G],feed_dict={X:xs,C0:ys,C_FAKE:ysN, Z: zs})\r\n if i % 100 == 0:\r\n print(i,ld,lg)\r\n","repo_name":"Crystal-Dragon-Liu/ML_practise","sub_path":"marchine_learning_note/GAN/GAN_conditional.py","file_name":"GAN_conditional.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21297645796","text":"from mesa.visualization.ModularVisualization import ModularServer\nfrom mesa.visualization.modules import CanvasGrid, ChartModule\nfrom mesa.visualization.UserParam import UserSettableParameter\n\nfrom agents import Bear, Rabbit, GrassPatch, Hunter\nfrom model import HuntersModel\n\n\ndef hunters_portrayal(agent):\n if agent is None:\n return\n\n portrayal = {}\n\n if type(agent) is Rabbit:\n portrayal[\"Shape\"] = \"resources/rabbit.png\"\n\n portrayal[\"scale\"] = 0.9\n portrayal[\"Layer\"] = 1\n\n elif type(agent) is Bear:\n portrayal[\"Shape\"] = \"resources/bear.png\"\n\n portrayal[\"scale\"] = 0.9\n portrayal[\"Layer\"] = 2\n portrayal[\"text\"] = round(agent.energy, 1)\n portrayal[\"text_color\"] = \"White\"\n\n elif type(agent) is Hunter:\n portrayal['Shape'] = \"resources/hunter.png\"\n portrayal['scale'] = 0.9\n portrayal['Layer'] = 1.5\n portrayal['text_color'] = 'Red'\n\n elif type(agent) is GrassPatch:\n if agent.fully_grown:\n portrayal[\"Color\"] = [\"#00FF00\", \"#00CC00\", \"#009900\"]\n else:\n portrayal[\"Color\"] = [\"#84e184\", \"#adebad\", \"#d6f5d6\"]\n portrayal[\"Shape\"] = \"rect\"\n portrayal[\"Filled\"] = \"true\"\n portrayal[\"Layer\"] = 0\n portrayal[\"w\"] = 1\n portrayal[\"h\"] = 1\n\n return portrayal\n\n\ncanvas_element = CanvasGrid(hunters_portrayal, 25, 25, 500, 500)\nchart_element = ChartModule([{\"Label\": \"bears\", \"Color\": \"#AA0000\"},\n {\"Label\": \"rabbit\", \"Color\": \"#666666\"},\n {\"Label\": \"total_welfare\",\"Color\": 'green'},\n {\"Label\": \"average_welfare\", \"Color\": 'blue'}])\n\nmodel_params = {\"grass\": UserSettableParameter('checkbox', 'Grass Enabled', True),\n \"grass_regrowth_time\": UserSettableParameter('slider', 'Grass Regrowth Time', 15, 1, 50),\n \"initial_rabbit\": UserSettableParameter('slider', 'Initial rabbit Population', 100, 10, 300),\n \"rabbit_reproduce\": UserSettableParameter('slider', 'rabbit Reproduction Rate', 0.2, 0.01, 1.0,\n 0.01),\n \"hunting_season_start\": UserSettableParameter('slider', 'hunting_season_start', 1, 1, 10),\n \"hunting_season_end\": UserSettableParameter('slider', \"hunting_season_end\", 5, 1,10),\n \"initial_bears\": UserSettableParameter('slider', 'Initial bear Population', 50, 10, 300),\n 'initial_hunter':UserSettableParameter('slider', 'Initial hunter num', 10, 0, 100, 5),\n \"bear_reproduce\": UserSettableParameter('slider', 'bear Reproduction Rate', 0.1, 0.01, 1.0,\n 0.01,\n description=\"The rate at which bear agents reproduce.\"),\n \"bear_gain_from_food\": UserSettableParameter('slider', 'bear Gain From Food Rate', 20, 1, 50),\n \"rabbit_gain_from_food\": UserSettableParameter('slider', 'rabbit Gain From Food', 5, 1, 10)}\n\nserver = ModularServer(HuntersModel, [canvas_element, chart_element], \"Hunters\", model_params)\nserver.port = 8522\n","repo_name":"khu019/ABM-Project","sub_path":"Final_ABP/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13747889288","text":"import logging\n\nimport pika\nfrom pika.spec import BasicProperties\n\nfrom shared.messengers.messenger import Messenger, MessengerSetting, MessageConsumerSetting\n\n\nclass DundaaAMQPSDKException(Exception): pass\n\n\ndef default_callback(ch, method, properties, body):\n logger = logging.getLogger(__name__)\n logger.info(\" [x] %r:%r\" % (method.routing_key, body))\n\n\nclass DundaaAMQPSDK(Messenger):\n \"\"\"\n SDK to handle connection to rabbitAMQP\n \"\"\"\n\n def __init__(self, amqp_url=None, amqp_host=None, logger=None):\n if amqp_host is None and amqp_url is None:\n raise RuntimeError(\"Could not initalise SDK. set either amqp_url or amqp_host\")\n self._channel = None\n self._connection = None\n self.amqp_url = amqp_url\n self.amqp_host = amqp_host\n if logger is None:\n self._logger = logging.getLogger(self.__class__.__name__)\n else:\n self._logger = logger\n\n self.__connection_established = False\n\n def _connect(self):\n if self.amqp_url is not None:\n self._connection = pika.BlockingConnection(\n pika.connection.URLParameters(self.amqp_url)\n )\n else:\n self._connection = pika.BlockingConnection(\n pika.ConnectionParameters(self.amqp_host)\n )\n self._channel = self._connection.channel()\n self.__connection_established = True\n\n def publish(self, routing_key: str, data: str, exchange='', exchange_type='direct', delay=None):\n self._connect()\n accepted_exchanges = ['direct']\n if exchange_type not in accepted_exchanges:\n self._logger.error(\"Exchange type not supported\")\n return\n try:\n if delay is None:\n self.__publish(exchange=exchange, routing_key=routing_key, data=data, exchange_type=exchange_type)\n else:\n self.__delayed_publish(exchange=exchange, routing_key=routing_key, data=data, delay=delay)\n except Exception as exc:\n self._logger.error(\"Unknown exception occured %s\", str(exc))\n finally:\n self._close()\n\n def __publish(self, exchange: str, routing_key: str, data: str, exchange_type: str):\n self._channel.exchange_declare(exchange=exchange, exchange_type=exchange_type)\n self._channel.basic_publish(\n exchange=exchange, routing_key=routing_key, body=data\n )\n self._logger.info(\"message published\")\n\n def __delayed_publish(self, exchange: str, routing_key: str, data: any, delay: int, exchange_type='direct'):\n self._channel.exchange_declare(\n exchange=exchange,\n arguments={\n 'x-delayed-type': exchange_type\n },\n auto_delete=False,\n durable=True,\n passive=True,\n )\n self._channel.basic_publish(\n exchange,\n routing_key=routing_key,\n body=data,\n properties=BasicProperties(\n headers={\"x-delay\": delay}\n )\n\n )\n\n def _close(self):\n self._connection.close()\n\n def __consume(self, exchange: str, routing_keys: [str], exchange_type='direct', callback=None):\n if self.__connection_established is False:\n self._connect()\n\n self._channel.exchange_declare(exchange=exchange, exchange_type=exchange_type)\n\n result = self._channel.queue_declare(queue='', exclusive=True)\n queue_name = result.method.queue\n\n for key in routing_keys:\n self._channel.queue_bind(\n exchange=exchange, queue=queue_name, routing_key=key)\n\n self._logger.info(' [*] Waiting for messages. To exit press CTRL+C')\n if callback is None:\n callback = default_callback\n\n self._channel.basic_consume(\n queue=queue_name, on_message_callback=callback, auto_ack=True)\n\n self._channel.start_consuming()\n\n def consume_messages(self, consumer_settings: MessageConsumerSetting, callback=None):\n return self.__consume(\n exchange=consumer_settings.service_name,\n routing_keys=consumer_settings.listen_keys,\n callback=callback\n )\n\n def send_message(self, messenger_setting: MessengerSetting, data: any, delay=None):\n return self.publish(\n data=data,\n routing_key=messenger_setting.key,\n exchange=messenger_setting.service_name,\n delay=delay\n )\n","repo_name":"DanNyongesa/WhatsHappening","sub_path":"shared/messengers/amqp_sdk.py","file_name":"amqp_sdk.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37282120758","text":"#\n# @lc app=leetcode id=1300 lang=python3\n#\n# [1300] Sum of Mutated Array Closest to Target\n#\n# https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/description/\n#\n# algorithms\n# Medium (46.42%)\n# Likes: 117\n# Dislikes: 15\n# Total Accepted: 4.8K\n# Total Submissions: 10.3K\n# Testcase Example: '[4,9,3]\\n10'\n#\n# Given an integer array arr and a target value target, return the integer\n# value such that when we change all the integers larger than value in the\n# given array to be equal to value, the sum of the array gets as close as\n# possible (in absolute difference) to target.\n# \n# In case of a tie, return the minimum such integer.\n# \n# Notice that the answer is not neccesarilly a number from arr.\n# \n# \n# Example 1:\n# \n# \n# Input: arr = [4,9,3], target = 10\n# Output: 3\n# Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's\n# the optimal answer.\n# \n# \n# Example 2:\n# \n# \n# Input: arr = [2,3,5], target = 10\n# Output: 5\n# \n# \n# Example 3:\n# \n# \n# Input: arr = [60864,25176,27249,21296,20204], target = 56803\n# Output: 11361\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= arr.length <= 10^4\n# 1 <= arr[i], target <= 10^5\n# \n#\n\n# @lc code=start\nclass Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n arr.sort(reverse=True)\n maxA = arr[0]\n while arr and target >= arr[-1] * len(arr):\n target -= arr.pop()\n return int((target + len(arr) / 2.0 - 0.1) / len(arr)) if arr else maxA\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"1300.sum-of-mutated-array-closest-to-target.py","file_name":"1300.sum-of-mutated-array-closest-to-target.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9538832749","text":"import streamlit as st\nimport requests\nfrom PIL import Image\nimport pandas as pd\nfrom streamlit_folium import st_folium\nfrom folium import folium\nfrom io import BytesIO\nfrom utils import get_map, random_images, launch_plexel\nfrom st_clickable_images import clickable_images\nimport subprocess\n\n# LOGO AND BACKGROUND\n#st.set_page_config(page_icon=\"logo.png\", page_title=\"Travel Home\", layout=\"wide\")\nst.set_page_config(page_title=\"Travel Home\", layout=\"wide\")\n\ndef add_bg_from_local():\n st.markdown(\n f\"\"\"\n \n \"\"\",\n unsafe_allow_html=True\n )\nadd_bg_from_local()\n\n# TITLE AND SUBTITLE\n\n# image = Image.open('logo2.png')\n# st.image(image, width=120)\n\ntitle = '

Travel Home

'\nst.markdown(title, unsafe_allow_html=True)\n\nsub_title = '

Find your dream travel destination at a train distance

'\nst.markdown(sub_title, unsafe_allow_html=True)\n\nst.write(\" \")\nst.write(\" \")\nst.write(\" \")\n\n# DATA INPUT FOR PREDICT OF API\ncolumns = st.columns([7,3])\nselected = columns[0].text_input(\"Enter your dream destination (or just a keyword 😉)\", \"\")\n\nget_prediction = False\nif selected: # input = bar de recherche\n list_link=launch_plexel(selected)\n st.markdown(\"Now, click on your favorite image 👇\")\n clicked = clickable_images(\n list_link,\n titles=[f\"Image #{str(i)}\" for i in range(6)],\n div_style={\"display\": \"flex\", \"flex-wrap\": \"wrap\", \"justify-content\": \"center\", \"background-color\" : \"transparent\", \"width\": \"100%\"},\n img_style={\"margin\": \"1.5%\", \"height\": \"200px\"},\n )\n if clicked >-1:\n get_prediction = True\n\nimage_uploaded = columns[1].file_uploader('or upload a picture', type=['jpg', 'jpeg', 'png']) # input = image upload\n\nimage = ''\nif get_prediction==True :\n response = requests.get(list_link[clicked])\n image = list_link[clicked]\n url = 'https://travel-home-mzfiw6j4fa-ew.a.run.app/predict'\n params = {'image': image}\n request = requests.get(url, params=params)\n data = request.json()\n df = pd.DataFrame(data, dtype='object')\nif image_uploaded is not None:\n image = image_uploaded\n st.write(image.name)\n url = 'https://travel-home-mzfiw6j4fa-ew.a.run.app/predict'\n params = {'image': image.name}\n request = requests.get(url, params=params)\n data = request.json()\n df = pd.DataFrame(data, dtype='object')\n\n\n# output api test en attendant l'api\ndata_test = {'cellid': [5169846499198107648, 5171065032959590400, 5220109917347643392],\n 'probability': [0.92, 0.74, 0.34]}\ndf_test = pd.DataFrame(data_test, dtype='object')\n\n\nif get_prediction == True:\n col1, col2, col3 = st.columns([5,3,1])\n with col1:\n st_folium(get_map(df), width=700, height=500)\n with col2:\n st.write(\"\")\n with col3:\n st.write(\"\")\n # DETAILS OF DESTINATION\n france_zoom=5\n with st.expander(\"Click here for the details of the destinations we found for you\"):\n col1, col2, col3 = st.columns(3)\n with col1:\n st.metric(\"Destination 1\", f\"{df['new_proba'][0]}% of similarities\")\n map_1 = folium.Map(location=(df['lat'][0], df['lon'][0]),\n zoom_start=france_zoom+2,zoom_control=False)\n show_map_1 = st_folium(map_1,width=400,height=150)\n # random_images(int(df['cellid'][0]))\n # columns = st.columns(2)\n # columns[0].image('proposal_0.jpg')\n # columns[1].image('proposal_1.jpg')\n with col2:\n st.metric(\"Destination 2\", f\"{df['new_proba'][1]}% of similarities\")\n map_1 = folium.Map(location=(df['lat'][1], df['lon'][1]),\n zoom_start=france_zoom+2,zoom_control=False)\n show_map_1 = st_folium(map_1,width=400,height=150)\n # random_images(int(df['cellid'][1]))\n # columns = st.columns(2)\n # columns[0].image('proposal_0.jpg')\n # columns[1].image('proposal_1.jpg')\n with col3:\n st.metric(\"Destination 3\", f\"{df['new_proba'][2]}% of similarities\")\n map_1 = folium.Map(location=(df['lat'][2], df['lon'][2]),\n zoom_start=france_zoom+2,zoom_control=False)\n show_map_1 = st_folium(map_1,width=400,height=150)\n # random_images(int(df['cellid'][2]))\n # columns = st.columns(2)\n # columns[0].image('proposal_0.jpg')\n # columns[1].image('proposal_1.jpg')\n","repo_name":"nauvray/travel-home","sub_path":"travel_home_app/app-hj/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"19360071085","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport json\nfrom scrapy import Request\nfrom scrapy.conf import settings\nfrom news_all.spider_models import NewsRCSpider\n\n\nclass DbwAllSpider(NewsRCSpider):\n \"\"\"学习强国\"\"\"\n name = 'xuexi_all'\n custom_settings = {'DOWNLOADER_MIDDLEWARES': settings.getdict('APP_DOWN')}\n\n mystart_urls = {\n 'https://www.xuexi.cn/lgdata/index.json?_st=26005365': 7650\n }\n\n start_headers = {\n 'Host': 'www.xuexi.cn',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',\n }\n\n def parse(self, response):\n # https://www.xuexi.cn/lgpage/detail/index.html?id=11891749402835707327\n title_urls = re.findall(r'\\\"link\\\":\\\"https://www.xuexi.cn/lgpage/detail/index.html\\?id=\\d+\\\"', response.text)\n # \"https://boot-source.xuexi.cn/data/app/3493463650618488237.js?callback=callback&_st=1560395879456\" 详情页真实地址\n for i in title_urls:\n # url1= re.findall('https://www.xuexi.cn/lgpage/detail/index.html\\?id=\\d+', i)\n id = re.findall('\\d+', i)\n url = \"https://boot-source.xuexi.cn/data/app/\"+id[0]+\".js?callback=callback\"\n yield Request(\n url=url,\n callback=self.parse_item,\n meta={\n 'source_id': response.meta['source_id'],\n 'start_url_time': response.meta['start_url_time'],\n 'schedule_time': response.meta['schedule_time'],\n }\n )\n\n def parse_item(self, response):\n # https://www.xuexi.cn/lgpage/detail/index.html?id=11891749402835707327\n text = response.text\n result = text.replace(\"callback(\",\"\").replace(\")\",\"\")\n rs = json.loads(result)\n try:\n title = rs.get('title')\n img_urls = rs.get('image')\n # img_list = img_urls.get('url')\n content = rs.get('content')\n source = rs.get('source', '').replace('yres-article-manual_', '')\n pubtime = rs.get('publish_time')\n media = {}\n if img_urls is None:\n print(\"无图新闻\")\n else:\n if len(img_urls):\n count = len(img_urls)\n x = list(range(0, count))\n for (i, j) in zip(img_urls, x):\n content = content.replace(\"\", \"
\")\n content, media, videos, video_cover = self.content_clean(content, need_video=True)\n except:\n return self.produce_debugitem(response, \"json error\")\n\n return self.produce_item(response=response,\n title=title,\n pubtime=pubtime,\n origin_name=source,\n content=content,\n media=media,\n videos=videos\n )","repo_name":"Pintrue/news_all","sub_path":"news_all/spiders_ydyl/xuexiqiangguo.py","file_name":"xuexiqiangguo.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"37283056878","text":"#\n# @lc app=leetcode id=1679 lang=python3\n#\n# [1679] Max Number of K-Sum Pairs\n#\n# https://leetcode.com/problems/max-number-of-k-sum-pairs/description/\n#\n# algorithms\n# Medium (52.47%)\n# Likes: 83\n# Dislikes: 6\n# Total Accepted: 8K\n# Total Submissions: 15.4K\n# Testcase Example: '[1,2,3,4]\\n5'\n#\n# You are given an integer array nums and an integer k.\n# \n# In one operation, you can pick two numbers from the array whose sum equals k\n# and remove them from the array.\n# \n# Return the maximum number of operations you can perform on the array.\n# \n# \n# Example 1:\n# \n# \n# Input: nums = [1,2,3,4], k = 5\n# Output: 2\n# Explanation: Starting with nums = [1,2,3,4]:\n# - Remove numbers 1 and 4, then nums = [2,3]\n# - Remove numbers 2 and 3, then nums = []\n# There are no more pairs that sum up to 5, hence a total of 2 operations.\n# \n# Example 2:\n# \n# \n# Input: nums = [3,1,3,4,3], k = 6\n# Output: 1\n# Explanation: Starting with nums = [3,1,3,4,3]:\n# - Remove the first two 3's, then nums = [1,4,3]\n# There are no more pairs that sum up to 6, hence a total of 1 operation.\n# \n# \n# Constraints:\n# \n# \n# 1 <= nums.length <= 10^5\n# 1 <= nums[i] <= 10^9\n# 1 <= k <= 10^9\n# \n# \n#\n\n# @lc code=start\nfrom collections import Counter\n\nclass Solution:\n def maxOperations(self, nums: List[int], k: int) -> int:\n counts = Counter(nums)\n res = 0\n for i, v in counts.items():\n if i != k - i:\n res += min(v, counts[k - i])\n\n res //= 2\n if k % 2 == 0 and k // 2 in counts:\n res += counts[k//2] // 2\n\n return res\n\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"1679.max-number-of-k-sum-pairs.py","file_name":"1679.max-number-of-k-sum-pairs.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12300066725","text":"import dependency_graph\nimport request_dependencies_lens\n\n\nclass RequestNode(dependency_graph.RequestNode):\n \"\"\"Represents a request in the graph.\n\n is_ad and is_tracking are set according to the ContentClassificationLens\n passed to LoadingGraphView.\n \"\"\"\n def __init__(self, request):\n super(RequestNode, self).__init__(request)\n self.is_ad = False\n self.is_tracking = False\n\n\nclass Edge(dependency_graph.Edge):\n \"\"\"Represents a dependency between two nodes.\n\n activity is set according to the ActivityLens passed to LoadingGraphView.\n \"\"\"\n def __init__(self, from_node, to_node, reason):\n super(Edge, self).__init__(from_node, to_node, reason)\n self.activity = {}\n\n\nclass LoadingGraphView(object):\n \"\"\"Represents a trace as a dependency graph. The graph is annotated using\n optional lenses passed to it.\n \"\"\"\n def __init__(self, trace, dependencies_lens, content_lens=None,\n frame_lens=None, activity=None):\n \"\"\"Initalizes a LoadingGraphView instance.\n\n Args:\n trace: (LoadingTrace) a loading trace.\n dependencies_lens: (RequestDependencyLens)\n content_lens: (ContentClassificationLens)\n frame_lens: (FrameLoadLens)\n activity: (ActivityLens)\n \"\"\"\n self._requests = trace.request_track.GetEvents()\n self._deps_lens = dependencies_lens\n self._content_lens = content_lens\n self._frame_lens = frame_lens\n self._activity_lens = activity\n self._graph = None\n self._BuildGraph()\n\n @classmethod\n def FromTrace(cls, trace):\n \"\"\"Create a graph from a trace with no additional annotation.\"\"\"\n return cls(trace, request_dependencies_lens.RequestDependencyLens(trace))\n\n def RemoveAds(self):\n \"\"\"Updates the graph to remove the Ads.\n\n Nodes that are only reachable through ad nodes are excluded as well.\n \"\"\"\n roots = self._graph.graph.RootNodes()\n self._requests = [n.request for n in self._graph.graph.ReachableNodes(\n roots, should_stop=lambda n: n.is_ad or n.is_tracking)]\n self._BuildGraph()\n\n def GetInversionsAtTime(self, msec):\n \"\"\"Return the inversions, if any for an event.\n\n An inversion is when a node is finished before an event, but an ancestor is\n not finished. For example, an image is loaded before a first paint, but the\n HTML which requested the image has not finished loading at the time of the\n paint due to incremental parsing.\n\n Args:\n msec: the time of the event, from the same base as requests.\n\n Returns:\n The inverted Requests, ordered by start time, or None if there is no\n inversion.\n \"\"\"\n completed_requests = []\n for rq in self._requests:\n if rq.end_msec <= msec:\n completed_requests.append(rq)\n inversions = []\n for rq in self._graph.AncestorRequests(completed_requests):\n if rq.end_msec > msec:\n inversions.append(rq)\n if inversions:\n inversions.sort(key=lambda rq: rq.start_msec)\n return inversions\n return None\n\n @property\n def deps_graph(self):\n return self._graph\n\n def _BuildGraph(self):\n self._graph = dependency_graph.RequestDependencyGraph(\n self._requests, self._deps_lens, RequestNode, Edge)\n self._AnnotateNodes()\n self._AnnotateEdges()\n\n def _AnnotateNodes(self):\n if self._content_lens is None:\n return\n for node in self._graph.graph.Nodes():\n node.is_ad = self._content_lens.IsAdRequest(node.request)\n node.is_tracking = self._content_lens.IsTrackingRequest(node.request)\n\n def _AnnotateEdges(self):\n if self._activity_lens is None:\n return\n for edge in self._graph.graph.Edges():\n dep = (edge.from_node.request, edge.to_node.request, edge.reason)\n activity = self._activity_lens.BreakdownEdgeActivityByInitiator(dep)\n edge.activity = activity\n","repo_name":"kiwibrowser/src","sub_path":"tools/android/loading/loading_graph_view.py","file_name":"loading_graph_view.py","file_ext":"py","file_size_in_byte":3777,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"6530713262","text":"import sys\nimport tensorflow as tf\nimport numpy as np\nimport tensorflow.keras.backend as k\n\n\ndef LossCse673(inmat, y_labels, batch_size, alpha, beta, lambda_1, no_classes=98):\n ##Assert shape\n # if inmat.shape != (batch_size, 512):\n # sys.exit(\"expected batch_size, 512 shape, recieved\", (batch_size, 512))\n ##the sum of squares for each vector in the matrix (similarity matrix)\n ##BxB\n t_squared_vectors = tf.matmul(inmat, inmat, transpose_b=True)\n ##The diagonal of the sum of the squares (gives B x v1 dot v1.T) ||a||\n diagonals = tf.linalg.tensor_diag_part(t_squared_vectors)\n ##L2 Norm\n l2_norm = tf.math.sqrt(diagonals)\n # print(\"shape l2 norm\", l2_norm.shape)\n ##\n l2_norm = tf.expand_dims(l2_norm, axis=1)\n # print(\"shape l2 norm \",l2_norm.shape)\n\n inmatNormalised = inmat / l2_norm\n # print(\"inmat\")\n # print(inmat)\n # print(\"l2 norm\")\n # print(l2_norm)\n # print(\"inmatNormalised\")\n # print(inmatNormalised)\n ##Test if all samples are normalised\n # testNorm = np.round(tf.reduce_sum(inmatNormalised ** 2, axis=1), decimals=4) == 1.0\n # print(testNorm)\n # if any(testNorm == False):\n # print(\"Normalisation not performed on Batch dimension\")\n\n SIMILARITY_MAT = tf.matmul(inmatNormalised, inmatNormalised, transpose_b=True)\n print(\"inmat normalised\")\n print(SIMILARITY_MAT)\n SIMILARITY_MAT = tf.linalg.set_diag(SIMILARITY_MAT, diagonal=tf.zeros(batch_size, dtype='float32'))\n print(\"SIMILARITY_MAT\", SIMILARITY_MAT)\n # if y_labels.shape[1] != no_classes:\n # print(\"Number of classes mismatch \")\n # sys.exit()\n\n # tf.matmul(y, SIMILARITY_MAT)\n # pos_label_mat = np.zeros(shape=(batch_size, batch_size))\n # print(\"pos_label_mat\", pos_label_mat.shape)\n # for sample in range(batch_size):\n # idx = y_labels[sample,:] == 1.0\n # pos_label_mat[sample:,] = y_labels[:,idx]\n pos_label_mat = tf.matmul(y_labels, y_labels, transpose_b=True)\n pos_label_mat = tf.cast(pos_label_mat, tf.float32)\n\n neg_label_mat = 1.0 - pos_label_mat\n\n print(\"pos_label_mat\")\n print(pos_label_mat)\n ######################Multiplying with alpha to get alpha *1 matrix\n # pos_label_mat = pos_label_mat\n\n # neg_label_mat = neg_label_mat\n ###Substract the lambda matrix\n # tf.reshape(x0, (k.shape(x0)[0], 1, k.shape(x0)[1]))\n\n lambda_1 = tf.constant([lambda_1])\n # multiples = tf.constant([k.shape(SIMILARITY_MAT)[0]])\n multiples = tf.constant([batch_size * batch_size])\n lambda_vec = tf.tile(lambda_1, multiples)\n print(\"lambda_vec\")\n print(lambda_vec)\n # lambda_mat = tf.reshape(lambda_vec, (k.shape(inmat)[0], k.shape(inmat)[0]))\n lambda_mat = tf.reshape(lambda_vec, [batch_size, batch_size])\n lambda_mat = tf.cast(lambda_mat, tf.float32)\n print(\"lambda_mat\")\n print(lambda_mat)\n ###Substract the lambda matrix\n SIMILARITY_MAT = SIMILARITY_MAT - lambda_mat\n\n ##The diagonal of this matrix would be the postive similarity\n # positive_similarity_mat = tf.matmul(pos_label_mat, SIMILARITY_MAT)\n positive_similarity_mat = SIMILARITY_MAT * -alpha\n # positive_similarity_mat = tf.matmul(pos_label_mat, SIMILARITY_MAT)\n # positive_similarity = tf.linalg.tensor_diag_part(positive_similarity_mat)\n # print(\"positive_similarity\")\n # print(positive_similarity)\n\n ##The\n print(\"neg_label_mat\")\n print(neg_label_mat)\n # negative_similarity_mat = tf.matmul(neg_label_mat, SIMILARITY_MAT)\n negative_similarity_mat = SIMILARITY_MAT * beta\n # negative_similarity_mat = tf.matmul(neg_label_mat, negative_similarity_mat)\n # negative_similarity = tf.linalg.tensor_diag_part(negative_similarity_mat)\n\n # postivie_exp = tf.math.exp(positive_similarity)\n # print(\"negative_similarity\")\n # negative_exp = tf.math.exp(negative_similarity)\n # print(negative_exp)\n\n ##Exp\n positive_similarity_mat = tf.math.exp(positive_similarity_mat)\n negative_similarity_mat = tf.math.exp(negative_similarity_mat)\n\n print(\"positive_similarity_mat\")\n print(positive_similarity_mat)\n\n ##Summation for entire batch\n positive_similarity_mat = tf.matmul(pos_label_mat, positive_similarity_mat)\n negative_similarity_mat = tf.matmul(neg_label_mat, negative_similarity_mat)\n\n ##\n positive_similarity = tf.linalg.tensor_diag_part(positive_similarity_mat)\n negative_similarity = tf.linalg.tensor_diag_part(negative_similarity_mat)\n\n print(\"positive_similarity\")\n print(positive_similarity)\n\n print(\"negative_similarity\")\n print(negative_similarity)\n\n ##Add 1\n positive_similarity = 1 + positive_similarity\n negative_similarity = 1 + negative_similarity\n\n ##log & scale\n positive_similarity = tf.math.log(positive_similarity) * (1. / alpha)\n negative_similarity = tf.math.log(negative_similarity) * (1. / beta)\n\n ##sum and mean\n loss = tf.reduce_sum((positive_similarity + negative_similarity)) * (1. / batch_size)\n # print(loss)\n return loss\n\n ##\n\n\n# def dice_loss(smooth, thresh):\n# def dice(y_true, y_pred)\n# return -dice_coef(y_true, y_pred, smooth, thresh)\n# return dice\n\ndef cseloss(alpha, beta, batch_size=16):\n def lossmask(y_true, y_pred):\n return LossCse673(y_pred, y_true, batch_size=batch_size, alpha=alpha, lambda_1=1, no_classes=98, beta=beta)\n return lossmask\n\n\n# if __name__ == '__main__':\n# inmat = np.random.rand(2000, 512)\n# # Losscse673(inmat, 2)\n# y_label = [[0, 0, 1],\n# [0, 0, 1]]\n# y_label = np.array(y_label)\n# print(y_label.shape)\n# print(np.array(y_label))\n#\n# predictions = tf.constant([[0.2, 0.4, 0.6],\n# [0.1, 0.8, 0.1]])\n#\n# # y_label = np.array([[0, 0, 1], [0, 0, 1]])\n# y_label = tf.Variable([[0, 0, 1], [0, 0, 1]], dtype='float64')\n#\n# # LossCse673(predictions, 2, y_label, alpha=0.1, lambda_1=0.3, no_classes=3, beta=0.1)\n# loss = cseloss(alpha=0.1, beta=0.1)\n# print(loss(y_label, predictions))\n","repo_name":"rnair56/RESNET-SELFATTN","sub_path":"customloss.py","file_name":"customloss.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37646572812","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019-03-25 11:17\n# @Author : zhangzhen\n# @Site : \n# @File : data_utils.py\n# @Software: PyCharm\nimport os\nimport json\nimport codecs\nfrom pprint import pprint\nfrom typing import Text\n\n\ndef data2ner(path: Text, filename: Text, to: Text):\n \"\"\"\n NER—��定义识别的实体, 并转化训练、测试语料\n :param path:\n :param file:\n :param to:\n :return:\n \"\"\"\n # 组织 人名 地名 日期 作品 Number TEXT Other\n # ORG PER LOC DAT PRO NUM TXT OTH\n schemas = {\n \"网络小说\": \"PRO\",\n \"企业\": \"ORG\",\n \"Number\": \"NUM\",\n \"电视综艺\": \"OTH\",\n \"地点\": \"LOC\",\n \"机构\": \"ORG\",\n \"语言\": \"OTH\",\n \"歌曲\": \"PRO\",\n \"城市\": \"LOC\",\n \"人物\": \"PER\",\n \"书籍\": \"PRO\",\n \"出版社\": \"ORG\",\n \"行政区\": \"LOC\",\n \"Text\": \"TXT\",\n \"影视作品\": \"PRO\",\n \"音乐专辑\": \"PRO\",\n \"学校\": \"ORG\",\n \"Date\": \"DAT\",\n \"图书作品\": \"PRO\",\n \"生物\": \"OTH\",\n \"学科专业\": \"OTH\",\n \"景点\": \"LOC\",\n \"网站\": \"OTH\",\n \"目\": \"OTH\",\n \"气候\": \"OTH\",\n \"作品\": \"PRO\",\n \"历史人物\": \"PER\",\n \"国家\": \"LOC\"\n }\n i = 0\n tag2label = {\n \"O\": i\n }\n for val in set(schemas.values()):\n i += 1\n tag2label[\"{}-{}\".format(\"B\", val)] = i\n i += 1\n tag2label[\"{}-{}\".format(\"I\", val)] = i\n\n print(tag2label)\n\n with codecs.open(to, mode=\"w+\", encoding=\"utf-8\") as wf:\n with codecs.open(path + os.sep + filename, encoding=\"utf-8\") as f:\n lines = f.readlines()\n for line in lines:\n rs = json.loads(line.strip())\n # print(rs['postag'])\n # print(rs['text'])\n # print(rs['spo_list'])\n txt = rs['text'].upper() # 转成大写, 防止语料出错\n label_dict = {}\n for ent in rs['spo_list']:\n # print(ent)\n obj = ent['object'].upper()\n sub = ent['subject'].upper()\n obj_type = ent['object_type']\n sub_type = ent['subject_type']\n # print(txt.index(obj), len(obj))\n # print(txt.index(sub), len(sub))\n try:\n label_dict[txt.index(obj)] = {\n \"length\": len(obj),\n \"type\": obj_type\n }\n label_dict[txt.index(sub)] = {\n \"length\": len(sub),\n \"type\": sub_type\n }\n except ValueError:\n pass\n # print(label_dict)\n\n i = 0\n while i < len(txt):\n w = txt[i]\n if i in label_dict:\n label = label_dict[i]\n if label[\"length\"]:\n for ii in range(label[\"length\"]):\n w = txt[ii + i]\n if w != \" \" and w != \"\\t\" and w.strip() != \"\":\n tag = \"{}-\" + schemas[label[\"type\"]]\n if ii == 0:\n # print(w, tag.format(\"B\"))\n wf.write(w + \"\\t\" + tag.format(\"B\") + \"\\n\")\n else:\n # print(w, tag.format(\"I\"))\n wf.write(w + \"\\t\" + tag.format(\"I\") + \"\\n\")\n i += label['length'] - 1\n else:\n # print(w, \"O\")\n if w != \" \" and w != \"\\t\" and w.strip() != \"\":\n wf.write(w + \"\\tO\\n\")\n i += 1\n # print()\n wf.write(\"\\n\")\n\n\nif __name__ == '__main__':\n path = './lic2019/original'\n filename = 'dev_data.json'\n to = './lic2019/dev_data.dat'\n data2ner(path, filename, to)\n","repo_name":"learnerzhang/zh-NER-TF","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"17407588379","text":"import pandas as pd \nimport pymysql\nimport numpy as np\n\ndb = pymysql.connect(host='localhost', user='root', password='hexin123', port=3306, db='quanzhigaoshou')\ncursor = db.cursor()\nsql = \"SELECT * FROM quanzhigaoshou\"\ndata = pd.read_sql(sql,db)\ndb.close()\n\nprint(data.head(3))\nprint('一共获得评论数据{}条'.format(len(data)))\n\nimport matplotlib.pyplot as plt #绘图\nimport matplotlib as mpl #配置字体\nimport seaborn as sns\nfrom matplotlib.font_manager import FontProperties\nmyfont=FontProperties(fname=r'C:\\Windows\\Fonts\\simhei.ttf',size=16)\nsns.set(font=myfont.get_name())\n#sns.set(font='SimHei') # 解决Seaborn中文显示问题\nmpl.rcParams['font.sans-serif'] = ['SimHei']\nsns.set_style(\"white\")\nsns.set_context('notebook')\n\n#按时间作图\ndata['time'] = data['ctime'].apply(lambda x: x[:10])\n\ntime = data[['time']].copy()\ntime['time_comment'] = 1\ntime = time.groupby(by=['time']).count()\nprint(time)\n\nplt.figure(figsize=(50,10))\nsns.pointplot(time.index,time['time_comment'],alpha=0.5)\nplt.ylabel('评论数量', fontsize=25)\nplt.xlabel('评论日期', fontsize=25)\nplt.xticks(rotation='vertical')\nplt.title('日期和数量', fontsize=30)\nplt.show\n\n#截取前一个月的数据\nplt.figure(figsize=(15,10))\nsns.pointplot(time.index[:30],time['time_comment'][:30],alpha=0.5,color=\"orange\")\nplt.ylabel('The number of comments', fontsize=15)\nplt.xlabel('The time about comments', fontsize=15)\nplt.xticks(rotation='vertical')\nplt.show\n\n#性别分布\nplt.figure(figsize=(10,10))\nsns.countplot(x=\"usersex\",data=data,palette=\"pastel\") #上图\nplt.show\n\n#等级分布\nplt.figure(figsize=(10,10))\nsns.countplot(x=\"userlevel\",data=data,palette=\"Set3\") #上图\nplt.show\n\n#前一个月等级和性别的关系\nplt.figure(figsize=(15,10))\nsns.countplot(x=\"userlevel\",data=data,hue = 'usersex',palette=\"husl\") #上图\nplt.show\n\ntime_sex = data[['floor','time','usersex']].copy()\ntime_sex = time_sex['floor'].groupby(by=[time_sex['time'],time_sex['usersex']]).count()\n\n#plt.figure(figsize=(30,10))\n#sns.countplot(data['floor'][:62822], hue=data.usersex, palette=\"husl\")\n#plt.xticks(rotation='vertical')\n#plt.show\n\n\n#提取用户观看时间段\ndata['clock'] = data['ctime'].apply(lambda x: x[11:13])\nclock = data[['clock']].copy()\nclock['comment'] = 1\nclock = clock.groupby(by=['clock']).count()\nprint(clock)\n\nplt.figure(figsize=(15,10))\nsns.pointplot(clock.index,clock['comment'],alpha=0.5,color = 'hotpink')\nplt.ylabel('The number of comments', fontsize=15)\nplt.xlabel('The clock', fontsize=15)\nplt.show\n\n#用户观看时段和等级的关系\nplt.figure(figsize=(20,10))\nsns.countplot(data['clock'], hue=data.userlevel, palette=\"Set2\")\nplt.show\n\n\nplt.figure(figsize=(15,10))\nlevel = [0,2,3,4,5,6]\nsecret = [82,1409,5173,20117,21264,289]\nmale =[1,261,1737,7392,9462,192]\nfemale =[0,519,2592,10669,14078,525]\nplt.stackplot(level, secret, male, female, colors=['coral','skyblue','palegreen'])\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend()\nplt.show()\n\n\n\n#评论情感分析\nfrom snownlp import SnowNLP\ndata[\"semiscore\"] = data['comment'].apply(lambda x: SnowNLP(x).sentiments)\ndata['semilabel'] = data[\"semiscore\"].apply(lambda x: 1 if x>0.5 else -1)\n\nplt.hist(data[\"semiscore\"], bins = np.arange(0, 1.01, 0.01),label=\"semisocre\", color=\"pink\")\nplt.xlabel(\"semiscore\")\nplt.ylabel(\"number\")\nplt.title(\"The semi-score of comment\")\nplt.show()\n\n\nsemilabel = data[\"semilabel\"].value_counts()\nplt.bar(semilabel.index,semilabel.values,tick_label=semilabel.index,color='lightsage')\nplt.xlabel(\"semislabel\")\nplt.ylabel(\"number\")\nplt.title(\"The semi-label of comment\")\nplt.show()\n\n#词云图\n\nimport jieba\ncomment=''.join(data['comment'])\nwordlist = jieba.cut(comment, cut_all=False)\nstopwords_chinese = [line.strip() for line in open('stopwords_chinese.txt',encoding='UTF-8').readlines()]\n#过滤点单个字\nword_list=[]\nfor seg in wordlist:\n if seg not in stopwords_chinese:\n word_list.append(seg)\n \nword_list=pd.DataFrame({'comment':word_list})\nword_rank = word_list[\"comment\"].value_counts()\n\n\nfrom pyecharts import WordCloud\nwordcloud_chinese = WordCloud(width=1500, height=820)\nwordcloud_chinese.add(\"\", word_rank.index[0:100], word_rank.values[0:100], word_size_range=[20, 200], is_more_utils=True)\nwordcloud_chinese.render(\"comment.html\")\n","repo_name":"summerheday/quanzhigaoshou","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"38301028198","text":"n, m = map(int, input().split())\r\nprices = list(map(int, input().split()))\r\n\r\nno_of_fruits = {}\r\n\r\nfor i in range(0,m):\r\n fruit = input()\r\n if fruit in no_of_fruits.keys():\r\n no_of_fruits[fruit] += 1\r\n else:\r\n no_of_fruits[fruit] = 1\r\n\r\nfruits_no = list(no_of_fruits.values())\r\n\r\nfruits_no.sort()\r\nfruits_no.reverse()\r\n\r\nprices_for_max = prices\r\nprices_for_min = prices\r\n\r\nprices_for_max.sort()\r\nprices_for_min.sort()\r\nprices_for_max.reverse()\r\n\r\nmax_price = 0\r\nmin_price = 0\r\n\r\nfor i in range(0,len(fruits_no)):\r\n max_price += fruits_no[i]*prices_for_max[i]\r\n min_price += fruits_no[i]*prices_for_min[n-i-1]\r\n\r\nprint(min_price, max_price)","repo_name":"ramjeetsingh/Codeforces","sub_path":"12C.py","file_name":"12C.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29874748552","text":"# encoding: utf-8\nfrom datetime import datetime, timedelta\n\nfrom app import db\n\n\nclass LectureHistoryStudent(db.Model):\n id = db.Column('id', db.Integer, primary_key=True)\n student_id = db.Column(db.Integer, db.ForeignKey('student.id'))\n date = db.Column(db.DateTime)\n present = db.Column(db.Boolean)\n lecture_id = db.Column(db.Integer, db.ForeignKey('lecture.id'))\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)\n skills = db.relationship(\n 'SkillStudent', backref='lecture_history', lazy='dynamic')\n remarks = db.relationship(\n 'RemarkStudent', backref='lecture_history', lazy='dynamic')\n message = db.Column(db.String(6000))\n # control\n created_at = db.Column(db.DateTime)\n deleted = db.Column(db.Boolean, default=False)\n\n def __init__(self, student_id, date, lecture_id, user_id=None):\n self.student_id = student_id\n self.date = date\n self.lecture_id = lecture_id\n self.user_id = user_id\n self.created_at = datetime.now()\n self.present = None\n self.deleted = False\n\n def to_dict_full(self, student=True, lecture=True, skills=True, remarks=True):\n return {\n \"date\": self.date.isoformat(),\n \"message\": self.message,\n \"lecture\": self.lecture.to_dict() if lecture else self.lecture_id,\n \"student\": self.student.to_dict() if student else self.student_id,\n \"skills\": [x.to_dict() for x in self.skills] if skills else None,\n \"remarks\": [x.to_dict() for x in self.remarks] if remarks else None,\n \"present\": self.present,\n \"id\": self.id\n }\n","repo_name":"melucasleite/thehut","sub_path":"app/models/lectureHistoryStudent.py","file_name":"lectureHistoryStudent.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"35624131274","text":"import requests\nimport pandas as pd\nimport numpy as np \nfrom concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\nimport multiprocessing\nimport csv, json\n\nclass NotFoundException(Exception):\n pass\n\ndef download(country_code, CVR):\n apiURL = \"https://cvrapi.dk/api?\"\n r = requests.get(apiURL, params={'country': country_code, 'search': CVR})\n\n\n if r.status_code == 404:\n print(\"404 Error\")\n raise NotFoundException\n\n filename = \"cvr_data/\" + str(CVR) + \".xlsx\" \n\n data = r.text\n df = pd.read_json(data, index=False)\n df.to_excel(df)\n\n\ndef multi_download(CVR_list):\n workers = len(CVR_list)\n \n with ThreadPoolExecutor(workers) as executor:\n executor.map(download, CVR_list, range(len(CVR_list)))\n\n\n\n\n# Lav Dataframe fra CSV\ndf_semi = pd.read_csv(\"/home/jovyan/my_notebooks/my_modules/CVR testdata.csv\", sep=\";\")\n#print(df_semi)\n\n# Hent på flere \n#for ind in df_semi.index: \n# download(df_semi['COUNTRY'][ind], df_semi['CVR_NUMMER'][ind])\n\ndownload('DK', 18609703)","repo_name":"josefmarcc/my_notebook","sub_path":"my_modules/cvr.py","file_name":"cvr.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35854828282","text":"\n# === START_CONFIG_PARAMETERS ===\n\ndict(\n\n timeout = 1,\n \n info = dict(\n name = 'PWM & Lighting',\n version = [1, 0, 0],\n description = 'Uses a PWM on a GPIO and varies its duty cycle to make a led flash smoothly from 0 to 3.3V.',\n author = 'JC`zic',\n mail = 'jczic.bos@gmail.com',\n www = 'https://github.com/jczic'\n ),\n \n args = dict(\n\n ledPin = dict( label = 'Led GPIO:',\n type = list ),\n\n )\n\n)\n\n# === END_CONFIG_PARAMETERS ===\n\n\nfrom utime import sleep\nfrom machine import Pin, PWM\n\n_min = 0\n_max = 2**16 - 1\nstep = 16\n\nduty = _min\npin = PWM( Pin(args.ledPin), freq=1000, duty=duty )\n\nprint('PWM on GPIO-%s works, click the red button to stop the Jama Func.' % args.ledPin)\n\nwhile True:\n pin.duty_u16(duty)\n duty += step\n if duty >= _max:\n duty = _max\n step = -step\n elif duty <= 0:\n duty = 0\n step = -step\n sleep(0.0001)\n","repo_name":"jczic/ESP32-MPY-Jama","sub_path":"src/content/Jama Funcs/PWM & Lighting.py","file_name":"PWM & Lighting.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":342,"dataset":"github-code","pt":"52"} +{"seq_id":"23962545494","text":"import numpy as np\nimport random\nimport pandas as pd\nimport gym\nimport matplotlib.pyplot as plt\n\ndef toPos(x, y):\n return int((y + 0.1) / 0.2 * 100) * 100 + int((x + 1.5) / 2.5 * 100)\n\nplt.ylabel('Reward')\nplt.xlabel('Timesteps')\nplt.title('Tearning curve')\n\nenv = gym.make('MountainCar-v0')\nQ = np.zeros([100 * 100, env.action_space.n])\n\nrecord = np.zeros(100)\nfor i in range(30000):\n observation = env.reset()\n pos = toPos(observation[0], observation[1])\n reward_sum = 0.0\n for t in range(300):\n #env.render()\n action = np.argmax(Q[pos,:]+random.randint(0,2)*(1.0/(i+1)))\n observation, new_reward, done, info = env.step(action)\n new_pos = toPos(observation[0], observation[1])\n Q[pos, action] = new_reward + Q[pos, action] + np.max(Q[new_pos, :]) - Q[pos, action]\n reward_sum += new_reward\n pos = new_pos\n if i % 3000 == 0:\n env.render()\n if done:\n break\n if i % 200 == 0 and i > 0:\n mean = record.mean()\n print(i, mean)\n plt.plot(i, mean, 'r.')\n else:\n record[i % 100] = reward_sum\nplt.show()\n","repo_name":"twzjwang/MountainCar","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17425186446","text":"from IceWalker2 import *\nfrom graphical_main import *\ngrids = ['1','2','3','4','5','6']\ndef main():\n ask1 = input('Choississez une map à charger (1,2,3,4,5,6)')\n if ask1 in grids:\n game = IceWalker('grid0'+ask1+'.txt')\n repl_play(game)\n else:\n main()\n \nmain()\n","repo_name":"RXAtomix/JSFS","sub_path":"Projet_AP2/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20135794534","text":"from problem_utils import *\nfrom operator import *\nfrom string import lowercase\n\nclass ChangingString:\n def distance(self, A, B, K):\n input_array1 = A\n input_array2 = B\n input_int = K\n N = len(input_array1)\n # You are given two Strings A and B that have the same length and contain only lowercase letters ('a'-'z').\n elements = lowercase\n possibilities = product(elements,repeat = N)\n \n # The distance between two letters is defined as the absolute value of their difference.\n #### distance = lambda letters: absolute(difference(* letters))\n mapping2 = lambda pair: abs(sub(* pair))\n\n\n # The distance between A and B is defined as the sum of the differences between each letter in A and the letter in B at the same position.\n #### distance = lambda A = sum([differences(A[position], B[position]) each position in range(N)])\n mapping = lambda possibility: sum([mapping2(possibility[i], input_array2[i]) for i in range(N)])\n # For example, the distance between \"abcd\" and \"bcda\" is 6 (1 + 1 + 1 + 3).\n \n # You must change exactly K characters in A into other lowercase letters.\n #### valid = lambda characters: exactly(len(change(A, characters)), K)\n valid = lambda possibility: eq(len(diff(input_array1, possibility)), input_int) \n\n # Return the minimum possible distance between A and B after you perform that change.\n #### return(minimum([distance(A) for A in possibilities if possible(possibility)]))\n return(min([mapping(possibility) for possibility in possibilities if valid(possibility)]))\n \nif __name__ == '__main__':\n A = \"ab\"\n B = \"ba\"\n K = 2\n cs = ChangingString()\n print(cs.distance(A, B, K))","repo_name":"jvalansi/word2code","sub_path":"word2code/res/text&code3/ChangingString.py","file_name":"ChangingString.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9627783070","text":"import re\nimport ops\n\nISP_REG = 1 # Instruction pointer bound to register 1\n\nINPUT = [\"seti 123 0 5\", \"bani 5 456 5\", \"eqri 5 72 5\", \"addr 5 1 1\", \"seti 0 0 1\", \"seti 0 2 5\", \"bori 5 65536 4\",\n \"seti 3935295 1 5\", \"bani 4 255 2\", \"addr 5 2 5\", \"bani 5 16777215 5\", \"muli 5 65899 5\", \"bani 5 16777215 5\",\n \"gtir 256 4 2\", \"addr 2 1 1\", \"addi 1 1 1\", \"seti 27 1 1\", \"seti 0 5 2\", \"addi 2 1 3\", \"muli 3 256 3\",\n \"gtrr 3 4 3\", \"addr 3 1 1\", \"addi 1 1 1\", \"seti 25 0 1\", \"addi 2 1 2\", \"seti 17 7 1\", \"setr 2 2 4\",\n \"seti 7 6 1\", \"eqrr 5 0 2\", \"addr 2 1 1\", \"seti 5 4 1\"]\n\ninstructions = {\"addr\": ops.addr, \"addi\": ops.addi, \"mulr\": ops.mulr, \"muli\": ops.muli,\n \"banr\": ops.banr, \"bani\": ops.bani, \"borr\": ops.borr, \"bori\": ops.bori,\n \"setr\": ops.setr, \"seti\": ops.seti, \"gtir\": ops.gtir, \"gtri\": ops.gtri,\n \"gtrr\": ops.gtrr, \"eqir\": ops.eqir, \"eqri\": ops.eqri, \"eqrr\": ops.eqrr}\n\nparse_instr = re.compile(r\"(\\w*)\\s+(\\d*)\\s+(\\d*)\\s+(\\d*)\")\n\n\nclass Isp:\n def __init__(self, reg, val):\n self.reg = reg\n self.val = val\n\n # Load ISP into linked register\n def load(self, registers):\n registers[self.reg] = self.val\n\n # Load linked register into ISP and move to next instruction\n def store(self, registers):\n self.val = registers[self.reg]\n self.val += 1\n\n\ndef parse_instruction(s):\n ops = [0] * 4\n\n matches = parse_instr.match(s)\n\n ops[0] = matches.group(1)\n ops[1] = int(matches.group(2))\n ops[2] = int(matches.group(3))\n ops[3] = int(matches.group(4))\n\n return ops\n\n\ndef execute_instruction(instr, registers, isp):\n isp.load(registers)\n\n op = instructions[instr[0]]\n op(instr[1:], registers)\n\n isp.store(registers)\n\n\ndef execute_program(inp, linked_reg, registers):\n isp = Isp(linked_reg, 0)\n\n instr = [parse_instruction(line) for line in inp]\n print(isp.val, registers)\n\n execute_instruction(instr[isp.val], registers, isp)\n\n while 0 <= isp.val < len(instr):\n pc = isp.val\n i = instr[pc]\n\n a = registers[0]\n\n execute_instruction(instr[isp.val], registers, isp)\n\n # if registers[0] != a:\n print(pc, i, registers)\n\n print(isp.val, registers, \"*\")\n\n return registers\n\n\n\"\"\"\n\"00: seti 123 0 5\t\t;R[5]=123\"\n\"01: bani 5 456 5\t\t;R[5]=R[5] AND 456\"\n\"02: eqri 5 72 5\t\t;R[5]=R[5]==72?1:0\"\n\"03: addr 5 1 1\t\t ;IF R[5] == 1 GOTO 5\"\n\"04: seti 0 0 1\t\t ;GOTO 1\"\n\"05: seti 0 2 5\t\t ;R[5]=0\"\n\"06: bori 5 65536 4\t ;R[4]=R[5] OR 65536\"\n\"07: seti 3935295 1 5\t;R[5]=3935295\" \n\"08: bani 4 255 2\t\t;R[2]=R[4] AND 255\"\n\"09: addr 5 2 5\t\t ;R[5]=R[2]+R[5]\" \n\"10: bani 5 16777215 5\t;R[5]=R[5] AND 16777215\"\n\"11: muli 5 65899 5\t\t;R[5]=R[5] * 65899\"\n\"12: bani 5 16777215 5\t;R[5]=R[5] AND 16777215\"\n\"13: gtir 256 4 2\t\t;R[2]=256>R[4]?1:0\"\n\"14: addr 2 1 1\t\t ;IF R[2]==1 GOTO 16\"\n\"15: addi 1 1 1\t\t ;GOTO 17\"\n\"16: seti 27 1 1\t\t;GOTO 28\"\n\"17: seti 0 5 2\t\t ;R[2]=0\"\n\"18: addi 2 1 3\t\t ;R[3]=R[2]+1\"\n\"19: muli 3 256 3\t\t;R[3]=R[3]*256\"\n\"20: gtrr 3 4 3\t\t ;R[3]=R[3]>R[4]?1:0\"\n\"21: addr 3 1 1\t\t ;IF R[3]==1 GOTO 23\"\n\"22: addi 1 1 1\t\t ;GOTO 24\"\n\"23: seti 25 0 1\t\t;GOTO 26\"\n\"24: addi 2 1 2\t\t ;R[2]=R[2]+1\"\n\"25: seti 17 7 1\t\t;GOTO 18\"\n\"26: setr 2 2 4\t\t ;R[4]=R[2]\"\n\"27: seti 7 6 1\t\t ;GOTO 8\"\n\"28: eqrr 5 0 2\t\t ;R[2]=R[5]==R[0]?1:0\"\n\"29: addr 2 1 1\t\t ;IF R[2]==1 GOTO 31\"\n\"30: seti 5 4 1\t\t ;GOTO 6\"\n\nafter a bit of translating an rearranging (could do better) this is the equivalent C++ code to get the first and last \nregister content fo register 0\n\nstd::pair< uint64_t, uint64_t > get_maxes()\n{\n\n\tint64_t C = 0, D = 0, E = 0, F = 0;\n\n\tF = 123;\n\tdo {\n\t\tF &= 456;\n\t} while( F != 72 );\n\n\tF = 0;\n\n\tstd::vector< uint64_t > maxes;\n\n\tdo {\n\t\tE = F | 65536;\n\t\tF = 3935295;\n\n\t\tdo {\n\t\t\tF += ( E & 255 );\n\t\t\tF &= 16777215;\n\t\t\tF *= 65899;\n\t\t\tF &= 16777215;\n\n\t\t\tif( 256 > E )\n\t\t\t\tbreak;\n\n\t\t\tfor( C = 0;; ++C ) {\n\t\t\t\tD = 256 * ( C + 1 );\n\t\t\t\tif( D > E )\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tE = C;\n\n\t\t} while( true );\n\n\t\tif( std::find( maxes.begin(), maxes.end(), F ) == maxes.end() ) {\n\t\t\tmaxes.push_back( F );\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t} while( true );\n\n\treturn std::make_pair( maxes[ 0 ], *maxes.rbegin() );\n}\n\"\"\"\n\n\ndef test():\n registers = [0] * 6\n registers[0] = 6577493\n\n execute_program(INPUT, ISP_REG, registers)\n pass\n\n\ndef first():\n return 16457176\n\n\ndef second():\n return 13625951\n\n\nif __name__ == \"__main__\":\n #test()\n print(\"Register value of R0 to break loop as soon as possible: {0}\".format(first()))\n print(\"Register value of R0 to break loop as late as possible: {0}\".format(second()))\n","repo_name":"sorrowed/Advent-2018","sub_path":"src/day21/mod.py","file_name":"mod.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32048602022","text":"import argparse\nfrom langchain_utils import __version__\nfrom langchain_utils.config import MODEL_TO_CONTEXT_LENGTH_MAPPING, DEFAULT_MODEL\n\n\ndef get_get_prompt_base_arg_parser(description: str) -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(\n description=description,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n\n parser.add_argument(\n '-V',\n '--version',\n action='version',\n version=f'%(prog)s {__version__}',\n )\n parser.add_argument(\n '-c', '--copy', help='Copy the prompt to clipboard', action='store_true'\n )\n parser.add_argument(\n '-e', '--edit', help='Edit the prompt and copy manually', action='store_true'\n )\n parser.add_argument(\n '-m',\n '--model',\n help='Model to use',\n metavar='model',\n type=str,\n default=DEFAULT_MODEL,\n )\n parser.add_argument(\n '-S',\n '--no-split',\n help='Do not split the prompt into multiple parts (use this if the model has a really large context size)',\n action='store_true',\n )\n parser.add_argument(\n '-s',\n '--chunk-size',\n help='Chunk size when splitting transcript, also used to determine whether to split, defaults to 1/2 of the context length limit of the model',\n metavar='chunk_size',\n type=int,\n # default to 1/2 of the context length limit\n # default=MODEL_TO_CONTEXT_LENGTH_MAPPING[DEFAULT_MODEL] // 2,\n # default=2000,\n default=None,\n )\n parser.add_argument(\n '-P',\n '--parts',\n help='Parts to select in the processes list of Documents',\n type=int,\n nargs='+',\n default=None,\n )\n\n parser.add_argument(\n '-r',\n '--raw',\n help='Wraps the content in triple quotes with no extra text',\n action='store_true',\n )\n\n parser.add_argument(\n '-R',\n '--raw-no-quotes',\n help='Output the content only',\n action='store_true',\n )\n\n parser.add_argument(\n '--print-percentage-non-ascii',\n help='Print percentage of non-ascii characters',\n action='store_true',\n )\n\n parser.add_argument('-n', '--dry-run', help='Dry run', action='store_true')\n return parser\n","repo_name":"tddschn/langchain-utils","sub_path":"langchain_utils/utils_argparse.py","file_name":"utils_argparse.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"42716316277","text":"from common import *\nimport random\nimport time\nquery = Query()\ndb = query.conn()\n\n@app.route('/transaction',methods=['GET','POST'])\ndef transaction():\n cursor=db.cursor()\n userId= session['userid']\n \n transactionId = '20171112' + ''.join(random.sample('0123456789',5))\n session['trade_id'] = transactionId\n comboId = int(request.form.get('cid'))\n productName = request.form.get('cname')\n amount=int(request.form.get('q'))\n stime = time.time()\n etime = stime + 86400\n dcost = request.form.get('dcost')\n dcost1 = float(dcost)\n total = amount * dcost1\n sql=\"insert into t_trade_record (trasaction_id,combo_id,product_name,amount,user_id,start_time,end_time,total) values ('%s','%d','%s','%s','%d','%s','%s','%s')\" %(transactionId,comboId,productName,amount,userId,stime,etime,total)\n try:\n cursor.execute(sql)\n db.commit()\n return redirect('/topay')\n except Exception as e:\n print(e)\n db.close()\n \n# 获取订单信息\n@app.route('/transaction/payment')\ndef payment():\n cursor = db.cursor()\n tid = session['trade_id']\n userId = session['userid']\n sql = \"select * from v_shop_combo_trade where trasaction_id='%s' and user_id='%d'\" % (tid,userId)\n try:\n cursor.execute(sql)\n results=cursor.fetchall()\n fields = ['_id','trasaction_id','combo_id','product_name','amount','user_id','start_time','end_time','yn','total','discount_cost','original_cost','combo_cover','shop_name','shop_id','shop_cover']\n arr = []\n for row in results:\n arr.append(dict(zip(fields,row))) \n return json.dumps(arr) \n except Exception as e:\n print(e)\n db.close()\n@app.route('/update',methods=['GET','POST'])\ndef updata():\n cursor=db.cursor()\n tid=session['trade_id']\n userid=session['userid']\n print('up')\n sql=\"update t_trade_record set yn=1 where trasaction_id='%s' and user_id='%d'\" %(tid,userid)\n try: \n cursor.execute(sql)\n db.commit()\n return \"1\"\n except Exception as e:\n return e\n db.close()\n\n","repo_name":"jayimu/demo","sub_path":"src/projects/flaskmeituan/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43532951858","text":"grid = [[\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]]\nans = 0\n\ndef dfs(i, j):\n if grid[i][j] != '1' or i < 0 or j >= len(grid[0]):\n return # pruning => no more 1 (land) or out of index\n grid[i][j] = '0' # visit 1 (land)\n\n # go to each directions\n dfs(i - 1, j)\n dfs(i + 1, j)\n dfs(i, j - 1)\n dfs(i, j + 1)\n\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == '1': # connected but not visited yet\n ans += 1\n dfs(i, j)\n\nprint(ans)\n","repo_name":"nazzang49/python-algorithm","sub_path":"leetcode/number_of_islands.py","file_name":"number_of_islands.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75145916643","text":"from PIL import Image\r\nimport numpy as np\r\nfrom PIL import ImageChops\r\nfrom PIL import ImageStat as stat\r\nimport matplotlib.pyplot as plt\r\nfrom random import randint\r\n\r\nim = Image.open('jesien.jpg')\r\nim.save(\"diff.png\")\r\n\r\nim2 = Image.open('diff.png')\r\ndef statystyki(im2):\r\n s = stat.Stat(im2)\r\n print(\"extrema \", s.extrema) # max i min\r\n print(\"count \", s.count) # zlicza\r\n print(\"mean \", s.mean) # srednia\r\n print(\"median \", s.median) # mediana\r\n print(\"stddev \", s.stddev) # odchylenie standardowe\r\n# MUSISZ PODAC 2 ZDJECIA Z 3B, KTORE TRZEBA WRZUCIC NA IMAGECHOPS DIFF - POTEM WGRAC JE DO FUNKCJI.\r\nstatystyki(dif1)\r\n\r\nhist = dif1.histogram()\r\np = 0\r\nprint(hist[p])\r\nprint(hist[256 + p])\r\nprint(hist[2*256 + p])\r\n\r\ndef rysuj_histogram_RGB(obraz):\r\n hist = obraz.histogram()\r\n plt.title(\"histogram \")\r\n plt.bar(range(256), hist[:256], color='r', alpha=0.5)\r\n plt.bar(range(256), hist[256:2 * 256], color='g', alpha=0.4)\r\n plt.bar(range(256), hist[2 * 256:], color='b', alpha=0.3)\r\n plt.show()\r\n\r\nrysuj_histogram_RGB(dif1)\r\n\r\nstatystyki(dif2)\r\n\r\nhist = dif2.histogram()\r\np = 0\r\nprint(hist[p])\r\nprint(hist[256 + p])\r\nprint(hist[2*256 + p])\r\n\r\n\r\n###ZAD2 A I B\r\nim = Image.open('obraz.jpg')\r\nim.save('obraz1.jpg')\r\nim1 = Image.open('obraz1.jpg')\r\nim1.save('obraz2.jpg')\r\nim2 = Image.open('obraz2.jpg')\r\nim2.save('obraz3.jpg')\r\nim3 = Image.open('obraz3.jpg')\r\nim3.save('obraz4.jpg')\r\nim4 = Image.open('obraz4.jpg')\r\nim4.save('obraz5.jpg')\r\nim5 = Image.open('obraz5.jpg')\r\n\r\n#ZAD2 C - Oceń różnice między obrazem i obraz5.jpg\r\n\r\n#ZAD2 D - Oceń różnice między obraz4.jpg i obraz5.jpg\r\n\r\n#ZAD2 E Jak kolejne zapisywanie obrazu odbiega od oryginału\r\n\r\n\r\n","repo_name":"LukaszRag/WdGM","sub_path":"lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73636075684","text":"# Main config file holding global variables\n# and SQL table pointers\n\n# Global variables\nglobal_tlcs = {}\nglobal_codes = {}\nsystems = ['BMI_ALL_DW','CROM_ALL_DW','EAL_BHI_DW','EAL_MIC_DW','UCLH_BHI_DW','UCLH_MIC_DW','RFH_HAEM_DW','RFH_BIO_DW','RFH_VIRO_DW','RFH_HPIL_DW','RFH_MICR_DW','WSL_ALL_DW']\nsystem_translation = dict( BMI_ALL_DW='Regional Winpath', CROM_ALL_DW='Cromwell Winpath', EAL_BHI_DW='North West London BHI', EAL_MIC_DW='North West London Micro', RFH_BIO_DW='Royal Free BHI', RFH_HAEM_DW='Royal Free Haem', RFH_HPIL_DW='Royal Free Special Coag', RFH_IMM_DW='Royal Free Immunology', RFH_MICR_DW='Royal Free Micro', RFH_VIRO_DW='Royal Free Viro', UCLH_BHI_DW='UCLH BHI', UCLH_MIC_DW='UCLH Micro', WSL_ALL_DW='TDL Winpath')\n\n# SQL database config\nconnection_string = 'DSN=SQL01NT;CHARSET=UTF8;Database=GlobalCodes'\nglobal_map_table = '[GlobalCodes].[dbo].[GlobalCodes_Map]'\nglobal_audit_table = '[GlobalCodes].[dbo].[GlobalCodes_Audit]'\nglobal_audit_table_archive = '[GlobalCodes].[dbo].[GlobalCodes_Audit_Archive]'\n\nglobal_location = '[GlobalCodes].[dbo].[GlobalCodes_Locations]'\nglobal_container = '[GlobalCodes].dbo.[GlobalCodes_Container]'\nglobal_preanalytics = '[GlobalCodes].dbo.[GlobalCodes_Preanalytics]'\n\nglobal_test_codes_staging = '[GlobalCodes].[dbo].[GlobalCodes_TEST_CODES_STAGING]'\nglobal_test_staging = '[GlobalCodes].[dbo].[GlobalCodes_TEST_STAGING]'\nglobal_form_staging = '[GlobalCodes].[dbo].[GlobalCodes_FORM_STAGING]'\nglobal_sections = '[GlobalCodes].[dbo].[GlobalCodes_SECTIONS]'\nglobal_flatten = '[GlobalCodes].[dbo].[GlobalCodes_FLAT]'\nglobal_form_info = '[GlobalCodes].[dbo].[GlobalCodes_FORM_INFO]'\n\nglobal_lexical_tbl = '[GlobalCodes].[dbo].[GlobalCodes_Lexical]'\nloinc_db = '[GlobalCodes].[dbo].[LOINC_Main]'\n\n# Other\nerror_log_file = 'error_log.txt'\nexcluded_fields = ['HALO_SubSection','HALO_Department','SubSection','Department']\n\n# Pro config (new spreadsheet queries)\nspreadsheet_queries = [{'func': 'Lexical_Table', 'name': 'Lexical Table', 'desc': 'Global multi-lingual table'},\n {'func': 'Location_Table', 'name': 'Location Table', 'desc': 'Global location table'},\n {'func': 'Global_Map_Table', 'name': 'Preanalytics Table', 'desc': 'Shows preanalytics information for sample handling and TATs'}\n ]\n\ncolumn_display = {\n 'loinc':'LOINC',\n 'snomed_analyte':'SNOMED-CT Analyte',\n 'nlmc': 'NLMC',\n 'readcode': 'Read Code',\n 'cust_analyte': 'Analyte',\n 'cust_description': 'TDL Description',\n 'origin': 'Winpath',\n 'tfc': 'TFC',\n 'container': 'Container',\n 'loc1': 'Current Location',\n 'loc2': 'HALO location',\n 'type': 'Type'\n }\n","repo_name":"cjekin/Global_Codes_App","sub_path":"Global Codes App/Global_Codes_App/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4578615408","text":"import pandas as pd \nfrom collections import Counter\n\n# Part 1\nwith open('2-input.txt', 'r') as f:\n input = f.readlines()\n input = [i.replace('\\n', '') for i in input]\n input = [i.replace(':', '') for i in input]\n input = [i.replace('-', ' ') for i in input]\ninput_df = pd.DataFrame(columns=['start', 'end', 'letter', 'string'])\n\nfor i in input:\n start, end, letter, string = i.split(' ')\n d = {'start': int(start), 'end': int(end), 'letter': letter, 'string': string}\n input_df = input_df.append(d, ignore_index=True)\n\nvalid = []\nfor index, row in input_df.iterrows():\n string_hash = Counter(row['string'])\n if string_hash[row['letter']] in range(row['start'], row['end']+1):\n valid.append(index)\nprint(len(valid))\n\n# Part 2 \nvalid = 0\nfor index, row in input_df.iterrows():\n char_a = row['string'][row['start']-1]\n char_b = row['string'][row['end']-1]\n char_hash = Counter([char_a, char_b])\n if char_hash.get(row['letter'], -1) == 1:\n valid += 1\n","repo_name":"jeannefukumaru/advent-of-code-2020","sub_path":"2/passwords.py","file_name":"passwords.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13000257411","text":"import unittest\n\nfrom django.conf import settings\n\nfrom nose.tools import assert_equals, assert_true\n\nfrom rapidsms.router import Router\nfrom rapidsms.models import Connection, Backend\nfrom rapidsms.messages.outgoing import OutgoingMessage\nfrom rapidsms.tests.harness import MockBackend\n\nfrom rerouter.app import Rerouter\n\n\nclass MockRouter(Router):\n def start(self):\n self.running = True\n self.accepting = True\n self._start_all_backends()\n self._start_all_apps()\n\n def stop(self):\n self.running = False\n self.accepting = False\n self._stop_all_backends()\n\n\nclass MockOutgoingMessage(OutgoingMessage):\n def send_now(self):\n return True\n\n\nbackend_model = Backend.objects.create(name='backend1')\nbackend_model2 = Backend.objects.create(name='backend2')\nrouter = MockRouter()\nbackend = MockBackend(name=backend_model.name, router=router)\nrouter.backends['backend1'] = backend\nrouter.apps.append(Rerouter(router))\nrouter.start()\n\n\ndef test_backend_reroute():\n \"\"\" Make sure the outgoing phase correctly reroutes a message \"\"\"\n settings.REROUTE = {'backend1': 'backend2'}\n conn = Connection.objects.create(backend=backend_model,\n identity='1112229999')\n message = MockOutgoingMessage(conn, 'test')\n assert_equals(message.connection.backend.name, 'backend1')\n assert_true(router.outgoing(message), True)\n assert_equals(message.connection.backend.name, 'backend2')\n","repo_name":"caktus/rapidsms-rerouter","sub_path":"rerouter/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34090882391","text":"from django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils import timezone\n\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.decorators import action\nfrom rest_framework.views import Response, status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework import viewsets\n\nfrom movie.models import Movie\nfrom mutils.permissions import AccessUser\nfrom mutils.pagination import UserPageNumberPagination, UserLikePageNumberPagination\nfrom .serializers import StaffSerializer, SuperuserSerializer, UserLikeSerializer\nfrom .models import UserLike\n\n# Create your views here.\n\nclass CustomAuthToken(ObtainAuthToken):\n def post(self, request,*args,**kwargs):\n serializer =self.serializer_class(data=request.data, context={'request': request})\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n user.last_login = timezone.now()\n user.save(update_fields=['last_login'])\n token, created = Token.objects.get_or_create(user=user)\n return Response({\n 'token': token.key,\n 'pk': user.pk,\n 'username':user.username,\n 'is_staff': user.is_staff,\n 'is_superuser': user.is_superuser,\n })\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n\n pagination_class = UserPageNumberPagination\n permission_classes = [IsAuthenticated, AccessUser]\n\n def get_serializer_class(self):\n if self.request.user.is_superuser:\n return SuperuserSerializer\n elif self.request.user.is_staff:\n return StaffSerializer\n\n def get_queryset(self):\n queryset = User.objects.all().order_by('pk')\n return queryset\n\n @action(detail=False, methods=['get'], url_path='level', name='user_level')\n def user_level(self, request):\n user = request.user\n return Response({\n 'pk': user.pk,\n 'username':user.username,\n 'is_staff': user.is_staff,\n 'is_superuser': user.is_superuser,\n })\n\n @action(detail=False, methods=['get'], url_path='like', name='user_like')\n def user_like(self, request):\n try:\n ulike = UserLike.objects.get(user=request.user)\n except ObjectDoesNotExist:\n like = []\n else:\n like = ulike.like\n finally:\n cursor = Movie.objects.mongo_aggregate([{'$match':{'moviename':{'$in':like}}}, {'$group':{'_id':'$moviename', 'time':{'$first':'$created_time'}, 'post':{'$first':'$post'}, 'count':{'$sum':1}}}])\n mlike = []\n for c in cursor:\n c['moviename'] = c['_id']\n mlike.append(c)\n paginator = UserLikePageNumberPagination()\n page = paginator.paginate_queryset(mlike, request, view=self)\n serializer = UserLikeSerializer(page, many=True)\n return paginator.get_paginated_response(serializer.data)\n\n @user_like.mapping.put\n def user_like_put(self, request):\n moviename = request.data['moviename']\n movies = Movie.objects.filter(moviename=moviename)\n if not movies:\n return Response({'detail':f'Movie: {moviename} does not exist'}, status=status.HTTP_400_BAD_REQUEST)\n try:\n ulike = UserLike.objects.get(user=request.user)\n except ObjectDoesNotExist:\n like = [moviename]\n UserLike.objects.create(user=request.user, like=like)\n else:\n like = set(ulike.like)\n like.add(moviename)\n ulike.like = list(like)\n ulike.save()\n finally:\n return Response({'data':request.data}, status=status.HTTP_200_OK)\n\n @user_like.mapping.delete\n def user_like_delete(self, request):\n moviename = request.data['moviename']\n try:\n ulike = UserLike.objects.get(user=request.user)\n except ObjectDoesNotExist:\n pass\n else:\n like = set(ulike.like)\n like.discard(moviename)\n ulike.like = list(like)\n ulike.save()\n finally:\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action(detail=False, methods=['get'], url_path='movieinlike', name='movie_in_like')\n def movie_in_like(self, request):\n try:\n ulike = UserLike.objects.get(user=request.user)\n except ObjectDoesNotExist:\n movielikes = []\n else:\n movielikes = ulike.like\n finally:\n movie = request.query_params.get('m')\n like = movie in movielikes\n return Response({\n 'pk': request.user.pk,\n 'like': like\n })\n","repo_name":"chizuo53/MovieSite","sub_path":"muser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23668375172","text":"# There are two sorted arrays nums1 and nums2 of size m and n respectively.\n# Find the median of the two sorted arrays. The overall run time\n# complexity should be O(log (m+n)).\n# You may assume nums1 and nums2 cannot be both empty.\n# Example 1:\n#\n# nums1 = [1, 3]\n# nums2 = [2]\n#\n# The median is 2.0\n# Example 2:\n#\n# nums1 = [1, 2]\n# nums2 = [3, 4]\n#\n# The median is (2 + 3)/2 = 2.5\n\nclass Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n comb_array = []\n index1 = index2 = 0\n while index1=len(nums1):\n comb_array.extend(nums2[index2:])\n break\n elif index2>=len(nums2):\n comb_array.extend(nums1[index1:])\n break\n else:\n if nums1[index1]<= nums2[index2]:\n comb_array.append(nums1[index1])\n index1 +=1\n else:\n comb_array.append(nums2[index2])\n index2+=1\n mid = (len(comb_array) - 1) // 2\n if (len(comb_array)-1) % 2 :\n print(comb_array)\n return float((comb_array[mid]+comb_array[mid+1]))/2\n else:\n print(comb_array)\n return float(comb_array[mid])\n\n def findMedianSortedArrays2(self, nums1, nums2):\n comb_array = sorted(nums1 + nums2)\n result = 0\n if len(comb_array) % 2 == 0:\n result = (comb_array[int(len(comb_array) / 2)] + comb_array[int(len(comb_array) / 2) - 1]) / 2\n else:\n result = comb_array[len(comb_array) // 2]\n return result\n\n\n\nnums1=[1,2]\nnums2=[3,4]\nmedian = Solution().findMedianSortedArrays(nums1,nums2)\nmedian2 = Solution().findMedianSortedArrays2(nums1,nums2)\nprint(median)\nprint(median2)\n\n\n\n\n","repo_name":"Qiujm/MyPython","sub_path":"leetCodeAlgorithm/No4Median.py","file_name":"No4Median.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15680078539","text":"from __future__ import print_function\nimport os\nimport torch\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport argparse\nimport torch.utils.data as data\nfrom data import WiderFaceDetection, detection_collate, preproc, cfg_mnet, cfg_re50\nfrom data.data_augment_1 import preproc1\nfrom layers.modules import MultiBoxLoss\nfrom layers.functions.prior_box import PriorBox\nimport time\nimport datetime\nimport math\nfrom models.retinaface import RetinaFace, QuantizedRetinaFace \nimport copy\nimport pdb\n\nparser = argparse.ArgumentParser(description='Retinaface Training')\nparser.add_argument('--training_dataset', default='./data/widerface/train/label.txt', help='Training dataset directory')\nparser.add_argument('--network', default='mobile0.25', help='Backbone network mobile0.25 or resnet50')\nparser.add_argument('--num_workers', default=5, type=int, help='Number of workers used in dataloading')\nparser.add_argument('--lr', '--learning-rate', default=1e-3, type=float, help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, help='momentum')\nparser.add_argument('--resume_net', default=None, help='resume net for retraining')\nparser.add_argument('--resume_epoch', default=0, type=int, help='resume iter for retraining')\nparser.add_argument('--weight_decay', default=5e-4, type=float, help='Weight decay for SGD')\nparser.add_argument('--gamma', default=0.1, type=float, help='Gamma update for SGD')\nparser.add_argument('--save_folder', default='./weights/', help='Location to save checkpoint models')\n\nargs = parser.parse_args()\nprint(args)\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\ncfg = None\nif args.network == \"mobile0.25\":\n cfg = cfg_mnet\nelif args.network == \"resnet50\":\n cfg = cfg_re50\nprint(cfg)\n\n# rgb_mean = (104, 117, 123) # bgr order\nrgb_mean = (0, 0, 0) # bgr order\nnum_classes = 2\nimg_dim = cfg['image_size']\nnum_gpu = cfg['ngpu']\nbatch_size = cfg['batch_size']\nmax_epoch = 200\ngpu_train = cfg['gpu_train']\n\nnum_workers = args.num_workers\nmomentum = args.momentum\nweight_decay = args.weight_decay\ninitial_lr = args.lr\ngamma = args.gamma\ntraining_dataset = args.training_dataset\nsave_folder = args.save_folder\n\nnet = RetinaFace(cfg=cfg)\nprint(\"Printing net...\")\n# print(net)\n# for name, param in net.named_parameters(): \n# if 'body' in name:\n# param.requires_grad = False\npytorch_total_params = sum(p.numel() for p in net.parameters())\npytorch_total_params_trainable = sum(p.numel() for p in net.parameters() if p.requires_grad)\nprint(\"pytorch_total_params\", pytorch_total_params)\nprint(\"pytorch_total_params_trainable\", pytorch_total_params_trainable)\n\nif args.resume_net is not None:\n print('Loading resume network...')\n state_dict = torch.load(args.resume_net)\n # create new OrderedDict that does not contain `module.`\n from collections import OrderedDict\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n head = k[:7]\n if head == 'module.':\n name = k[7:] # remove `module.`\n else:\n name = k\n new_state_dict[name] = v\n net.load_state_dict(new_state_dict, strict=False)\n print(\"Load: \", args.resume_net)\n print(\"Load finish\")\n\nif num_gpu > 1 and gpu_train:\n net = torch.nn.DataParallel(net).cuda()\nelse:\n net = net.cuda()\n\ncudnn.benchmark = True\n\n\noptimizer = optim.SGD(net.parameters(), lr=initial_lr, momentum=momentum, weight_decay=weight_decay)\ncriterion = MultiBoxLoss(num_classes, 0.35, True, 0, True, 7, 0.35, False)\n\npriorbox = PriorBox(cfg, image_size=(360, 640))\nwith torch.no_grad():\n priors = priorbox.forward()\n priors = priors.cuda()\n\ndef train():\n epoch = 0\n net.train()\n fused_model = copy.deepcopy(net)\n fused_model.train()\n # fused_model = torch.quantization.fuse_modules(fused_model, [[\"body.stage1[0][0]\", \"body.stage1[0][1]\", \"body.stage1[0][2]\"]], inplace=True)\n # print(fused_model)\n net.eval()\n fused_model.eval()\n quantized_model = QuantizedRetinaFace(model_fp32=fused_model)\n # quantization_config = torch.quantization.get_default_qconfig(\"fbgemm\")\n quantization_config = torch.quantization.get_default_qconfig(\"qnnpack\")\n quantized_model.qconfig = quantization_config\n print(quantized_model.qconfig)\n torch.quantization.prepare_qat(quantized_model, inplace=True)\n\n print(\"Training QAT Model...\")\n quantized_model.train()\n quantized_model.to('cuda')\n\n dataset = WiderFaceDetection(training_dataset,preproc1(img_dim, rgb_mean))\n\n epoch_size = math.ceil(len(dataset) / batch_size)\n max_iter = max_epoch * epoch_size\n\n stepvalues = (cfg['decay1'] * epoch_size, cfg['decay2'] * epoch_size)\n step_index = 0\n\n if args.resume_epoch > 0:\n start_iter = args.resume_epoch * epoch_size\n else:\n start_iter = 0\n\n for iteration in range(start_iter, max_iter):\n if iteration % epoch_size == 0:\n # create batch iterator\n batch_iterator = iter(data.DataLoader(dataset, batch_size, shuffle=True, num_workers=num_workers, collate_fn=detection_collate))\n # if (epoch % 10 == 0 and epoch > 0) or (epoch % 5 == 0 and epoch > cfg['decay1']):\n if epoch > 0 and epoch % 1 == 0:\n torch.save(quantized_model.state_dict(), os.path.join(save_folder, cfg['name']+ '_epoch_' + str(epoch) + '_quantized_.pth'))\n epoch += 1\n\n load_t0 = time.time()\n if iteration in stepvalues:\n step_index += 1\n lr = adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size)\n\n # load train data\n images, targets = next(batch_iterator)\n images = images.cuda()\n targets = [anno.cuda() for anno in targets]\n # forward\n out = quantized_model(images)\n\n # backprop\n optimizer.zero_grad()\n loss_l, loss_c, loss_landm = criterion(out, priors, targets)\n loss = cfg['loc_weight'] * loss_l + loss_c + loss_landm\n loss.backward()\n optimizer.step()\n load_t1 = time.time()\n batch_time = load_t1 - load_t0\n eta = int(batch_time * (max_iter - iteration))\n\n if iteration % 5000 == 0:\n print('Epoch:{}/{} || Epochiter: {}/{} || Iter: {}/{} || Loc: {:.4f} Cla: {:.4f} Landm: {:.4f} || LR: {:.8f} || Batchtime: {:.4f} s || ETA: {}'\n .format(epoch, max_epoch, (iteration % epoch_size) + 1,\n epoch_size, iteration + 1, max_iter, loss_l.item(), loss_c.item(), loss_landm.item(), lr, batch_time, str(datetime.timedelta(seconds=eta))))\n # break\n quantized_model.to('cpu')\n quantized_model.eval()\n # print(quantized_model)\n torch.save(quantized_model.state_dict(), os.path.join(save_folder, cfg['name'] + '_Final_quantized_.pth'))\n quantized_model = torch.quantization.convert(quantized_model, inplace=True)\n quantized_model.eval()\n # print(quantized_model)\n\n input_p = torch.ones(1, 3, 360, 640)\n trace_model = torch.jit.trace(quantized_model, input_p)\n path_save = os.path.join(save_folder, cfg['name'] + '_Final_quantized_jit.pth')\n torch.jit.save(trace_model, path_save)\n print(\"DONE\")\n device='cpu'\n # quantized_model_load = torch.jit.load(path_save, map_location=device)\n # print(quantized_model_load)\n # print(\"LOAD DONE\")\n\n\ndef adjust_learning_rate(optimizer, gamma, epoch, step_index, iteration, epoch_size):\n \"\"\"Sets the learning rate\n # Adapted from PyTorch Imagenet example:\n # https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n warmup_epoch = -1\n if epoch <= warmup_epoch:\n lr = 1e-6 + (initial_lr-1e-6) * iteration / (epoch_size * warmup_epoch)\n else:\n lr = initial_lr * (gamma ** (step_index))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n\nif __name__ == '__main__':\n train()\n","repo_name":"tranquangchung/Pytorch_RetinaFace","sub_path":"train_quantization.py","file_name":"train_quantization.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4045887719","text":"import itertools\n\nimport cupy as cp\nimport numpy as np\nimport pytest\nfrom cupy.testing import assert_allclose\nfrom cupyx.scipy.ndimage import fourier_shift\nfrom skimage.data import camera, eagle\n\nfrom cucim.skimage import img_as_float\nfrom cucim.skimage._shared._warnings import expected_warnings\nfrom cucim.skimage._shared.fft import fftmodule as fft\nfrom cucim.skimage.data import binary_blobs\nfrom cucim.skimage.registration._phase_cross_correlation import (\n _upsampled_dft,\n phase_cross_correlation,\n)\n\n\n@pytest.mark.parametrize(\"normalization\", [None, \"phase\"])\ndef test_correlation(normalization):\n reference_image = fft.fftn(cp.array(camera()))\n shift = (-7, 12)\n shifted_image = fourier_shift(reference_image, shift)\n\n # pixel precision\n result, _, _ = phase_cross_correlation(\n reference_image,\n shifted_image,\n space=\"fourier\",\n normalization=normalization,\n )\n assert_allclose(result[:2], -cp.array(shift))\n\n\n@pytest.mark.parametrize(\"normalization\", [\"nonexisting\"])\ndef test_correlation_invalid_normalization(normalization):\n reference_image = fft.fftn(cp.array(camera()))\n shift = (-7, 12)\n shifted_image = fourier_shift(reference_image, shift)\n\n # pixel precision\n with pytest.raises(ValueError):\n phase_cross_correlation(\n reference_image,\n shifted_image,\n space=\"fourier\",\n normalization=normalization,\n )\n\n\n@pytest.mark.parametrize(\"normalization\", [None, \"phase\"])\ndef test_subpixel_precision(normalization):\n reference_image = fft.fftn(cp.array(camera()))\n subpixel_shift = (-2.4, 1.32)\n shifted_image = fourier_shift(reference_image, subpixel_shift)\n\n # subpixel precision\n result, _, _ = phase_cross_correlation(\n reference_image,\n shifted_image,\n upsample_factor=100,\n space=\"fourier\",\n normalization=normalization,\n )\n assert_allclose(result[:2], -cp.array(subpixel_shift), atol=0.05)\n\n\n@pytest.mark.parametrize(\"dtype\", [cp.float16, cp.float32, cp.float64])\ndef test_real_input(dtype):\n reference_image = cp.array(camera()).astype(dtype, copy=False)\n subpixel_shift = (-2.4, 1.32)\n shifted_image = fourier_shift(fft.fftn(reference_image), subpixel_shift)\n shifted_image = fft.ifftn(shifted_image).real.astype(dtype, copy=False)\n\n # subpixel precision\n result, error, diffphase = phase_cross_correlation(\n reference_image, shifted_image, upsample_factor=100\n )\n assert isinstance(result, tuple)\n assert all(isinstance(s, float) for s in result)\n assert_allclose(result[:2], -cp.array(subpixel_shift), atol=0.05)\n\n\ndef test_size_one_dimension_input():\n # take a strip of the input image\n reference_image = fft.fftn(cp.array(camera())[:, 15]).reshape((-1, 1))\n subpixel_shift = (-2.4, 4)\n shifted_image = fourier_shift(reference_image, subpixel_shift)\n\n # subpixel precision\n result, error, diffphase = phase_cross_correlation(\n reference_image, shifted_image, upsample_factor=20, space=\"fourier\"\n )\n assert_allclose(result[:2], -cp.array((-2.4, 0)), atol=0.05)\n\n\ndef test_3d_input():\n phantom = img_as_float(binary_blobs(length=32, n_dim=3))\n reference_image = fft.fftn(phantom)\n shift = (-2.0, 1.0, 5.0)\n shifted_image = fourier_shift(reference_image, shift)\n\n result, error, diffphase = phase_cross_correlation(\n reference_image, shifted_image, space=\"fourier\"\n )\n assert_allclose(result, -cp.array(shift), atol=0.05)\n\n # subpixel precision now available for 3-D data\n\n subpixel_shift = (-2.3, 1.7, 5.4)\n shifted_image = fourier_shift(reference_image, subpixel_shift)\n result, error, diffphase = phase_cross_correlation(\n reference_image, shifted_image, upsample_factor=100, space=\"fourier\"\n )\n assert_allclose(result, -cp.array(subpixel_shift), atol=0.05)\n\n\ndef test_unknown_space_input():\n image = cp.ones((5, 5))\n with pytest.raises(ValueError):\n phase_cross_correlation(image, image, space=\"frank\")\n\n\ndef test_wrong_input():\n # Dimensionality mismatch\n image = cp.ones((5, 5, 1))\n template = cp.ones((5, 5))\n with pytest.raises(ValueError):\n phase_cross_correlation(template, image)\n\n # Size mismatch\n image = cp.ones((5, 5))\n template = cp.ones((4, 4))\n with pytest.raises(ValueError):\n phase_cross_correlation(template, image)\n\n # NaN values in data\n image = cp.ones((5, 5))\n image[0][0] = cp.nan\n template = cp.ones((5, 5))\n with expected_warnings([r\"invalid value encountered in true_divide|\\A\\Z\"]):\n with pytest.raises(ValueError):\n phase_cross_correlation(template, image, return_error=True)\n\n\ndef test_4d_input_pixel():\n phantom = img_as_float(binary_blobs(length=32, n_dim=4))\n reference_image = fft.fftn(phantom)\n shift = (-2.0, 1.0, 5.0, -3)\n shifted_image = fourier_shift(reference_image, shift)\n result, error, diffphase = phase_cross_correlation(\n reference_image, shifted_image, space=\"fourier\"\n )\n assert_allclose(result, -cp.array(shift), atol=0.05)\n\n\ndef test_4d_input_subpixel():\n phantom = img_as_float(binary_blobs(length=32, n_dim=4))\n reference_image = fft.fftn(phantom)\n subpixel_shift = (-2.3, 1.7, 5.4, -3.2)\n shifted_image = fourier_shift(reference_image, subpixel_shift)\n result, error, diffphase = phase_cross_correlation(\n reference_image, shifted_image, upsample_factor=10, space=\"fourier\"\n )\n assert_allclose(result, -cp.array(subpixel_shift), atol=0.05)\n\n\ndef test_mismatch_upsampled_region_size():\n with pytest.raises(ValueError):\n _upsampled_dft(cp.ones((4, 4)), upsampled_region_size=[3, 2, 1, 4])\n\n\ndef test_mismatch_offsets_size():\n with pytest.raises(ValueError):\n _upsampled_dft(cp.ones((4, 4)), 3, axis_offsets=[3, 2, 1, 4])\n\n\n@pytest.mark.parametrize(\n (\"shift0\", \"shift1\"),\n itertools.product((100, -100, 350, -350), (100, -100, 350, -350)),\n)\n@cp.testing.with_requires(\"scikit-image>=0.20\")\ndef test_disambiguate_2d(shift0, shift1):\n image = cp.array(eagle()[500:, 900:]) # use a highly textured image region\n\n # Protect against some versions of scikit-image + imagio loading as\n # RGB instead of grayscale.\n if image.ndim == 3:\n image = image[..., 0]\n\n shift = (shift0, shift1)\n origin0 = []\n for s in shift:\n if s > 0:\n origin0.append(0)\n else:\n origin0.append(-s)\n origin1 = np.array(origin0) + shift\n slice0 = tuple(slice(o, o + 450) for o in origin0)\n slice1 = tuple(slice(o, o + 450) for o in origin1)\n reference = image[slice0]\n moving = image[slice1]\n computed_shift, _, _ = phase_cross_correlation(\n reference, moving, disambiguate=True, return_error=\"always\"\n )\n np.testing.assert_equal(shift, computed_shift)\n\n\ndef test_disambiguate_zero_shift():\n \"\"\"When the shift is 0, disambiguation becomes degenerate.\n Some quadrants become size 0, which prevents computation of\n cross-correlation. This test ensures that nothing bad happens in that\n scenario.\n \"\"\"\n image = cp.array(camera())\n computed_shift, _, _ = phase_cross_correlation(\n image, image, disambiguate=True, return_error=\"always\"\n )\n assert computed_shift == (0, 0)\n","repo_name":"rapidsai/cucim","sub_path":"python/cucim/src/cucim/skimage/registration/tests/test_phase_cross_correlation.py","file_name":"test_phase_cross_correlation.py","file_ext":"py","file_size_in_byte":7309,"program_lang":"python","lang":"en","doc_type":"code","stars":272,"dataset":"github-code","pt":"52"} +{"seq_id":"35453216744","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 2 17:30:45 2021\r\n\r\n@author: marcs\r\n\"\"\"\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass sudoku:\r\n def __init__(self, setup):\r\n self.board=np.array(setup,dtype=np.uint8)\r\n self.shape=setup.shape\r\n self.size=np.uint8(np.sqrt(setup.shape[0]))\r\n self.clusters=[self.board[ self.size*np.uint8(n/self.size) : self.size*(1+np.uint8(n/self.size)) , self.size*(n%self.size) : self.size*(n%self.size+1)] for n in range((self.size)**2)]\r\n self.columns=[self.board[:,n] for n in range(self.size**2)] \r\n self.rows=[self.board[n,:] for n in range(self.size**2)]\r\n self.total=2**(setup.shape[0])-1\r\n \r\n \r\n \r\n def CheckElement(self,element):\r\n var=binarize(element)\r\n return var==self.total\r\n \r\n def CheckRow(self, n):\r\n return self.CheckElement(self.rows[n])\r\n \r\n def CheckColumn(self, n):\r\n return self.CheckElement(self.columns[n])\r\n \r\n def CheckCluster(self, n):\r\n return self.CheckElement(self.clusters[n])\r\n \r\n def CheckSudoku(self):\r\n B=True\r\n for n in range(self.size**2):\r\n B*=self.CheckRow(n)\r\n B*=self.CheckColumn(n)\r\n B*=self.CheckCluster(n)\r\n return B\r\n \r\n \r\n \r\n \r\n def coordinates(self,row,col):#returns the number of (row, column, cluster)\r\n clust=math.floor(col/self.size) + math.floor(row/self.size)*self.size\r\n return (row,col,clust)\r\n \r\n \r\n def constraints(self, row, col):\r\n coord=self.coordinates(row,col)\r\n return [\r\n binarize(self.rows[coord[0]]),\r\n binarize(self.columns[coord[1]]),\r\n binarize(self.clusters[coord[2]])\r\n ]\r\n def constraintsB(self, row, col):\r\n coord=self.coordinates(row,col)\r\n return [\r\n self.rows[coord[0]],\r\n self.columns[coord[1]],\r\n self.clusters[coord[2]]\r\n ]\r\n \r\n def possibilities(self,row,col):\r\n if self.board[row,col] != 0:\r\n return 0\r\n poss=np.uint32(0)\r\n for element in self.constraints(row,col):\r\n poss |= element\r\n return self.total-poss\r\n \r\n def boardPos(self):\r\n tabla=np.zeros(self.shape, dtype='uint32')\r\n for x in range(self.shape[0]):\r\n for y in range(self.shape[1]):\r\n tabla[x,y]=self.possibilities(x,y) #OJO AQUI QUE HI POT HAVER UN CAMBI DE COORDENADES EASY\r\n return tabla\r\n \r\n \r\n def boardPosVisualize(self):\r\n tabla=np.zeros(self.shape,dtype='uint64')\r\n binario=self.boardPos()\r\n \r\n \r\n for x in range(self.shape[0]):\r\n for y in range(self.shape[1]):\r\n numbs='0'\r\n for i in range(0,self.shape[0]):\r\n if (2**i & binario[x,y]) != 0:\r\n numbs+=str(i+1)\r\n tabla[x,y]=numbs \r\n return tabla\r\n \r\n def Options(self):\r\n tabla=np.zeros(self.shape,dtype='uint8')\r\n binario=self.boardPos()\r\n \r\n for x in range(self.shape[0]):\r\n for y in range(self.shape[1]):\r\n for i in range(0,self.shape[0]):\r\n if (2**i & binario[x,y]) != 0:\r\n tabla[x,y]+=1 \r\n return tabla\r\n \r\n \r\n def Solve(self):\r\n for n in range (100):\r\n self.solveStep()\r\n if(self.CheckSudoku()):\r\n return n\r\n return\r\n \r\n def solveStep(self):\r\n tabla=self.solveexclusion()\r\n for n in range(self.shape[0]):\r\n tabla[n,:] += self.solverow(n)\r\n tabla[:,n] += self.solvecol(n)\r\n \r\n return tabla\r\n \r\n def solveexclusion(self):\r\n A=np.where(self.Options()==1)\r\n tabla=np.zeros(self.shape, dtype='uint8')\r\n for x,y in zip(A[0],A[1]):\r\n tabla[x,y]= np.log2(self.boardPos()[x,y]) +1#ojo els index \r\n self.board += tabla\r\n return tabla\r\n \r\n\r\n \r\n \r\n def solverow(self,n):\r\n row=np.zeros(self.shape[0],dtype='uint8')\r\n for element in self.onlyoptionrow(n):\r\n for i in range(self.shape[0]):\r\n if ( (self.possibilities(n,i) & 2**(element-1)) != 0):\r\n row[i]=element\r\n self.rows[n]+=row\r\n return row\r\n \r\n def onlyoptioncol(self, n):\r\n lista=[]\r\n for i in range(self.shape[0]):\r\n counter=0\r\n for j in range(self.shape[0]): \r\n counter += ( (2**i & self.possibilities(j,n) ) != 0)#OJO els index\r\n if(counter==1):\r\n lista +=[i+1]\r\n return lista\r\n\r\n def solvecol(self,n):\r\n col=np.zeros(self.shape[0],dtype='uint8')\r\n for element in self.onlyoptioncol(n):\r\n for i in range(self.shape[0]):\r\n if ( (self.possibilities(i,n) & 2**(element-1)) != 0):\r\n col[i]=element\r\n self.columns[n]+=col\r\n return col\r\n \r\n def onlyoptionrow(self, n):\r\n lista=[]\r\n for i in range(self.shape[0]):\r\n counter=0\r\n for j in range(self.shape[0]): \r\n counter += ( (2**i & self.possibilities(n,j) ) != 0)#OJO els index\r\n if(counter==1):\r\n lista +=[i+1]\r\n return lista\r\n\r\n\r\n \r\n \r\n def combinations(self):\r\n combs=np.uint64(1)\r\n for row in self.Options():\r\n for element in row:\r\n if element!=0:\r\n combs*=element\r\n return combs \r\n\r\n \r\ndef binarize(lista):\r\n var=np.uint32(0)\r\n for i in lista.flatten():\r\n var += (2**(i)-(i==0))\r\n return np.uint32(var/2)\r\n#%% MAIN\r\n \r\neasy=[\r\n #[1,2,3 ,4,0,6 ,7,8,9],\r\n [5,3,0 ,0,7,0 ,0,0,0],\r\n [6,0,0 ,1,9,5 ,0,0,0],\r\n [0,9,8 ,0,0,0 ,0,6,0],\r\n \r\n [8,0,0 ,0,6,0 ,0,0,3],\r\n [4,0,0 ,8,0,3 ,0,0,1],\r\n [7,0,0 ,0,2,0 ,0,0,6],\r\n \r\n [0,6,0 ,0,0,0 ,2,8,0],\r\n [0,0,0 ,4,1,9 ,0,0,5],\r\n [0,0,0 ,0,8,0 ,0,7,9]\r\n ]\r\n\r\nhard=[\r\n [0,0,2 ,0,0,1 ,0,4,9],\r\n [0,8,0 ,0,0,0 ,5,0,1],\r\n [3,0,0 ,0,0,9 ,0,0,0],\r\n \r\n [0,0,0 ,0,5,0 ,0,0,0],\r\n [0,0,0 ,3,9,6 ,2,0,0],\r\n [6,0,1 ,0,0,4 ,0,0,3],\r\n \r\n [0,0,3 ,0,0,0 ,0,0,2],\r\n [9,0,4 ,0,6,0 ,0,0,0],\r\n [0,6,0 ,0,2,0 ,0,0,0] \r\n ]\r\n\r\nclust=[\r\n [1,1,1 ,2,2,2 ,3,3,3],\r\n [1,1,1 ,2,2,2 ,3,3,3],\r\n [1,1,1 ,2,2,2 ,3,3,3],\r\n \r\n [4,4,4 ,5,5,5 ,6,6,6],\r\n [4,4,4 ,5,5,5 ,6,6,6],\r\n [4,4,4 ,5,5,5 ,6,6,6],\r\n \r\n [7,7,7 ,8,8,8 ,9,9,9],\r\n [7,7,7 ,8,8,8 ,9,9,9],\r\n [7,7,7 ,8,8,8 ,9,9,9]\r\n ]\r\n\r\nbig36=[\r\n [20,13,0,34,7,15, 16,1,0,19,0,24, 4,12,0,5,0,0, 0,28,35,0,14,30, 21,10,8,22,0,0, 32,29,11,9,0,26],\r\n [] \r\n \r\n ]\r\n\r\nStartBoard=np.array(hard,dtype=np.uint8)\r\nSud=sudoku(StartBoard)\r\n\r\n#%%\r\nimport pandas as pd\r\n\r\n\r\ndef translate(code,board):\r\n output=board\r\n output=np.where(output=='x',0,output)\r\n for i,element in enumerate(code,start=1):\r\n output=np.where(output==element,i,output)\r\n return output\r\n\r\n\r\n\r\n\r\ndf=pd.read_csv('16x16.csv', sep=',',header=None)\r\ncode=df.values[0,:]\r\nboard=df.values[1:,:]\r\nboard=translate(code,board)\r\nSud2=sudoku(board)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"MarcDrudis/Sudoku","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":7614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14846974690","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nimport time\n\ntry:\n link = \"http://suninjuly.github.io/selects1.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n\n input1 = browser.find_element(By.XPATH, '//*[@id=\"num1\"]')\n input1_valuex = int(input1.text)\n\n input2 = browser.find_element(By.XPATH, '//*[@id=\"num2\"]')\n input2_valuex = int(input2.text)\n\n select = Select(browser.find_element(By.TAG_NAME, \"select\"))\n select.select_by_value(str(input1_valuex+input2_valuex)) # ищем элемент с текстом \"Python\"\n\n send_button = browser.find_element(By.XPATH, '/html/body/div/form/button')\n send_button.click()\n\n # Проверяем, что смогли зарегистрироваться\n # ждем загрузки страницы\n time.sleep(1)\n\nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(5)\n # закрываем браузер после всех манипуляций\n browser.quit()","repo_name":"Toshibis/stepik_auto_tests_course","sub_path":"lesson2_2_step3.py","file_name":"lesson2_2_step3.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13652291890","text":"import csv\nimport pandas as pd\nimport numpy as np\nimport os\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import preprocessing\nimport pickle\n\ndef predict(query):\n\n\tprint(query)\n\n\tdata_path = \"..\\\\dataset\"\n\tX_train = pd.read_csv(os.path.join(data_path, 'X_train_best.csv'))\n\ty_train = pd.read_csv(os.path.join(data_path, 'y_train.csv'))\n\n\n\t# the features were learned by the Genetic Algorithm\n\tquery = np.array(query).reshape(1, -1)\n\n\t# padding to scale \n\tquery = np.insert(query, 2, 0)\n\tquery = np.insert(query, 4, 0)\n\tquery = np.insert(query, 7, 0)\n\tquery = np.insert(query, 9, 0)\n\n\t\n\tscaler = pickle.load(open(os.path.join(data_path, 'scaler-obj.p'), 'rb'))\n\tquery = scaler.transform([query])\n\n\tquery = query[0]\n\n\t# delete the padding\n\tquery = np.delete(query, 2, 0)\n\tquery = np.delete(query, 3, 0)\n\tquery = np.delete(query, 5, 0)\n\tquery = np.delete(query, 6, 0)\n\n\tquery = query.reshape(1, -1)\n\n\tmodel = LogisticRegression(C = 100000, tol = 0.1, penalty = 'l1', solver = 'liblinear', max_iter = 100000, random_state = 13361) \n\tmodel.fit(X_train, y_train.values.ravel())\n\n\tsafe, unsafe = model.predict_proba(query)[0]\n\treturn round(safe*100, 2)\n\n\nquery = [1, 0, 5.5, 64, 100, 0.74] \n\nprint(predict(query))","repo_name":"fortyTwo102/bioinformatics","sub_path":"model/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27765562592","text":"from pyld import jsonld\nimport json\nimport re\nfrom collections import defaultdict\nfrom subprocess import Popen, PIPE, STDOUT\nimport multiprocessing\nimport time\n\nfrom .context import get_logger\n#logger.info('number of cpus is %s', multiprocessing.cpu_count())\n\nfrom .utils import readFile\n\nclass JSONLDHelper:\n def __init__(self):\n self.processor = jsonld.JsonLdProcessor()\n self.temp_attr_id = None\n self.temp_properties = None\n self.logger, self.logfile = get_logger('jsonld')\n\n def jsonld2nquads_helper(self, jsonld_doc):\n \"\"\"\n Given a JSONLD document, return its nquads format\n\n Params\n ======\n jsonld_doc: jsonld document containing both JSON and the context file\n \"\"\"\n # convert from jsonld doc to nquads format\n try:\n nquads = jsonld.to_rdf(jsonld_doc, {'format': \"application/nquads\"})\n return self.processor.parse_nquads(nquads)\n except Exception as e:\n (self.logger.error(\"Something Unexpected happend when JSON-LD Python client tries to parse the JSON-LD.\\\n The first 100 chars of the JSON document is %s\", json.dumps(jsonld_doc)[:100]))\n self.logger.error(e, exc_info=True)\n return None\n\n def jsonld2nquads(self, jsonld_docs, alwayslist=False):\n \"\"\"\n Given a JSON-LD annotated document,\n Fetch it's corresponding NQUADs file\n\n Params\n ======\n jsonld_docs: (dict or list of dicts)\n A single or a list of JSON-LD annotated document(s)\n \"\"\"\n # handle cases where input is a list of JSON documents\n # in this case, the results will also be a list of NQuads parsing results\n if type(jsonld_docs) == list and type(jsonld_docs[0]) == dict:\n #results = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(self.jsonld2nquads_helper)(_doc) for _doc in jsonld_docs)\n results = []\n for i, _doc in enumerate(jsonld_docs):\n results.append(self.jsonld2nquads_helper(_doc))\n if len(results) == 1 and alwayslist == False:\n return results[0]\n else:\n return results\n # handle cases where input is a single JSON object document\n # in this case, the results will be a single NQuads parsing result\n elif type(jsonld_docs) == dict:\n if alwayslist == False:\n return self.jsonld2nquads_helper(jsonld_docs)\n else:\n return [self.jsonld2nquads_helper(jsonld_docs)]\n # if the input is neither list of json_docs nor single json_doc\n # log error message and return None\n else:\n self.logger.error(\"jsonld2nquads only takes a single or list of JSON doc(s). You input is %s. The first 100 chars of the input is %s\" %(type(jsonld_docs), json.dumps(jsonld_docs)[:100]))\n return None\n\n def json2jsonld(self, json_docs, jsonld_context_path):\n \"\"\"\n Given a JSON document and the endpoint where the doc comes from\n Fetch the JSON-LD context file for the endpoint\n Apply the JSON-LD context to JSON file to construct the JSON-LD document\n\n Return\n ======\n JSON-LD document\n \"\"\"\n jsonld_context = readFile(jsonld_context_path)\n if type(json_docs) == list and type(json_docs[0]) == dict:\n jsonld_docs = [json_doc.update(jsonld_context) for json_doc in json_docs]\n return json_docs\n elif type(json_docs) == dict:\n json_docs.update(jsonld_context)\n return json_docs\n else:\n logger.warning(\"The input of the json2jsonld function should be a list of JSON docs or a single JSON dictionary doc. \\\n You input is %s. The first 100 chars of the input is %s\", type(jsonld_docs), jsonld_doc[:100])\n return None\n\n def json2nquads(self, json_docs, context_file_path):\n \"\"\"\n Given a JSON document, perform the following actions\n 1) Find the json-ld context file based on endpoint_name\n 2) Add JSON-LD context file to JSON doc\n 3) Convert the JSON-LD doc into N-quads format\n\n Params\n ======\n json_doc: (dict)\n JSON document fetched from API calls\n endpoint_name: (str)\n the endpoint which the JSON doc comes from\n output: (str)\n URI subject\n predicate:\n NQUADS predicate, default is None\n \"\"\"\n jsonld_docs = self.json2jsonld(json_docs, context_file_path)\n nquads = self.jsonld2nquads(jsonld_docs)\n return nquads\n\n def find_object_properties_in_jsonld(self, _dict):\n \"\"\"\n extract the @base field corresponding to \"attr:id\" in a nested JSON-LD context file\n \"\"\"\n for k,v in _dict.items():\n # check if @id startswith \"attr:\" or \"rel:\"\n if isinstance(v, dict) and \"@id\" in v and v[\"@id\"] == \"attr:id\":\n # @base should be in the child level of @context\n if \"@base\" in v[\"@context\"]:\n self.temp_attr_id = v[\"@context\"][\"@base\"]\n else:\n logger.info('@base should be included here! Something wrong with the JSON-LD context file!!')\n # otherwise, recall this function to look into the child level\n elif isinstance(v, dict):\n self.find_object_properties_in_jsonld(v)\n\n def jsonld_parser_helper(self, _dict, relation=defaultdict(set)):\n \"\"\"\n extract relationship information from \"@id\" which startsfrom \"assoc:\"\n extract output information from \"@base\"\n \"\"\"\n for k, v in _dict.items():\n # First, looking for value of @id startswith \"assoc\"\n # this represents an association in the nested structure\n if isinstance(v, dict) and \"@id\" in v and v[\"@id\"].startswith(\"assoc:\"):\n # Next, looking for whether \"@base\" exists in the direct child level\n if \"@context\" in v and \"@base\" in v[\"@context\"]:\n relation[v[\"@context\"][\"@base\"]].add(v[\"@id\"])\n # If \"@base\" not exists in direct child level, look for levels deeper\n elif \"@context\" in v:\n self.temp_attr_id = None\n self.find_object_properties_in_jsonld(v[\"@context\"])\n if self.temp_attr_id:\n relation[self.temp_attr_id].add(v[\"@id\"])\n else:\n logger.warn(\"attr:id is missing in the object properties!\")\n elif isinstance(v, dict):\n self.jsonld_parser_helper(v, relation=relation)\n return relation\n\n def extract_predicates_from_jsonld(self, _dict, predicates=set()):\n \"\"\"\n Look for all unique values in \"@id\" field within JSON-LD context files\n \"\"\"\n for k, v in _dict.items():\n if isinstance(v, dict):\n self.extract_predicates_from_jsonld(v, predicates=predicates)\n elif k == \"@id\":\n predicates.add(v)\n return predicates\n\n def jsonld_relation_parser(self, jsonld_context):\n \"\"\"\n Given a JSON-LD context file, reorganize the file\n so that the key would be the attr id,\n the rest of the information would be wrapped in the value\n\n Example Outputs:\n\n >>> jsonld_helper = JSONLDHelper()\n >>> jsonld_context_file = {\"hits\": {\"@id\": \"http://bt.d2g/\", \"@type\": \"@id\", \"@context\": {\"gene\": {\"@id\": \"\"}}}\n }}\n\n \"\"\"\n if type(jsonld_context) != dict or '@context' not in jsonld_context:\n logging.error(\"Invalid JSON-LD context file!\")\n return\n return self.jsonld_parser_helper(jsonld_context, relation=defaultdict(set))\n\n def fetch_object_value_by_predicate_value_in_nquads(self, nquads, predicate_value):\n \"\"\"\n Given a nquads parsing results and a predicate_value\n find the corresponding object value(s)\n \"\"\"\n object_values = []\n if nquads and '@default' in nquads:\n nquads = nquads['@default']\n for _nquad in nquads:\n if _nquad['predicate']['value'] == predicate_value:\n object_values.append(_nquad['object']['value'])\n return object_values\n else:\n return object_values\n\n def fetch_object_and_predicate_value_by_subject_value_in_nquads(self, nquads, subject_value, results=None):\n \"\"\"\n Given a nquads parsing results and a subject_value\n find the corresponding object and predicate value\n \"\"\"\n if not results:\n results = defaultdict(list)\n if '@default' in nquads:\n nquads = nquads['@default']\n for _nquad in nquads:\n if _nquad['subject']['value'] == subject_value:\n current_predicate_value = _nquad['predicate']['value']\n current_object_value = _nquad['object']['value']\n if current_predicate_value != 'http://biothings.io/pass/':\n results[current_predicate_value].append(_nquad['object']['value'])\n else:\n results = self.fetch_object_and_predicate_value_by_subject_value_in_nquads(nquads, _nquad['object']['value'], results)\n return results\n\n def fetch_properties_by_association_in_nquads(self, nquads, association_list):\n results = {}\n for _association in association_list:\n results[_association] = []\n object_values = self.fetch_object_value_by_predicate_value_in_nquads(nquads, _association)\n #logger.info('object_values: %s', object_values)\n for _object_value in object_values:\n #logger.info('currently processing object_value: %s', _object_value)\n if _object_value.startswith('_:'):\n object_predicate_dict = self.fetch_object_and_predicate_value_by_subject_value_in_nquads(nquads, _object_value)\n #logger.info('current object_predicate_dict is %s', object_predicate_dict)\n if object_predicate_dict:\n results[_association].append(object_predicate_dict)\n else:\n logger.warn(\"Could not fetch any properties from the given association: {}\".format(_object_value))\n else:\n results[_association].append({'http://biothings.io/explorer/vocab/attributes/id': [_object_value]})\n print(results)\n return results\n\n def fetch_properties_by_association_and_prefix_in_nquads(self, nquads, association, prefix):\n association_results = self.fetch_properties_by_association_in_nquads(nquads, [association])\n association_and_prefix_results = [_doc for _doc in association_results[association] if 'http://biothings.io/explorer/vocab/attributes/id' in _doc and _doc['http://biothings.io/explorer/vocab/attributes/id'][-1].startswith(prefix)]\n return association_and_prefix_results\n\n def locate_association_in_jsonld_context_file(self, jsonld_context, association):\n if \"@context\" in jsonld_context:\n content = jsonld_context['@context']\n for k, v in content.items():\n if type(v) != dict:\n pass\n elif \"@id\" in v and v[\"@id\"] == association:\n self.temp_properties = v[\"@context\"]\n else:\n self.locate_association_in_jsonld_context_file(v, association)\n \n def organize_properties_in_jsonld_context_file(self, properties):\n for k, v in properties.items():\n if type(v) != dict:\n pass\n elif \"@id\" in v and (v[\"@id\"].startswith(\"attr\") or v[\"@id\"].startswith(\"rel\")):\n _key = v[\"@id\"]\n _key = _key.replace('attr', 'object').replace('rel', 'edge')\n self.organized_properties[_key] = v[\"@context\"][\"@base\"]\n elif k == \"@base\":\n self.organized_properties[\"node:id\"] = v\n else:\n self.organize_properties_in_jsonld_context_file(v)\n\n def fetch_properties_for_association_in_jsonld_context_file(self, jsonld_context, association):\n self.locate_association_in_jsonld_context_file(jsonld_context, association)\n if self.temp_properties:\n self.organized_properties = {}\n self.organize_properties_in_jsonld_context_file(self.temp_properties)\n return self.organized_properties\n","repo_name":"biothings/biothings_explorer_web_old","sub_path":"src/biothings_explorer/jsonld_processor.py","file_name":"jsonld_processor.py","file_ext":"py","file_size_in_byte":12631,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"12216657895","text":"# Authors:\n# Bram Cohen\n# Trevor Perrin - various changes\n#\n# See the LICENSE file for legal information regarding use of this file.\n# Also see Bram Cohen's statement below\n\n\"\"\"\nA pure python (slow) implementation of rijndael with a decent interface\n\nTo include -\n\nfrom rijndael import rijndael\n\nTo do a key setup -\n\nr = rijndael(key, block_size = 16)\n\nkey must be a string of length 16, 24, or 32\nblocksize must be 16, 24, or 32. Default is 16\n\nTo use -\n\nciphertext = r.encrypt(plaintext)\nplaintext = r.decrypt(ciphertext)\n\nIf any strings are of the wrong length a ValueError is thrown\n\"\"\"\n\n# ported from the Java reference code by Bram Cohen, bram@gawth.com, April 2001\n# this code is public domain, unless someone makes\n# an intellectual property claim against the reference\n# code, in which case it can be made public domain by\n# deleting all the comments and renaming all the variables\n\nimport copy\nimport string\n\nshifts = [[[0, 0], [1, 3], [2, 2], [3, 1]],\n [[0, 0], [1, 5], [2, 4], [3, 3]],\n [[0, 0], [1, 7], [3, 5], [4, 4]]]\n\n# [keysize][block_size]\nnum_rounds = {16: {16: 10, 24: 12, 32: 14}, 24: {16: 12, 24: 12, 32: 14}, 32: {16: 14, 24: 14, 32: 14}}\n\nA = [[1, 1, 1, 1, 1, 0, 0, 0],\n [0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0],\n [0, 0, 0, 1, 1, 1, 1, 1],\n [1, 0, 0, 0, 1, 1, 1, 1],\n [1, 1, 0, 0, 0, 1, 1, 1],\n [1, 1, 1, 0, 0, 0, 1, 1],\n [1, 1, 1, 1, 0, 0, 0, 1]]\n\n# produce log and alog tables, needed for multiplying in the\n# field GF(2^m) (generator = 3)\nalog = [1]\nfor i in range(255):\n j = (alog[-1] << 1) ^ alog[-1]\n if j & 0x100 != 0:\n j ^= 0x11B\n alog.append(j)\n\nlog = [0] * 256\nfor i in range(1, 255):\n log[alog[i]] = i\n\n# multiply two elements of GF(2^m)\ndef mul(a, b):\n if a == 0 or b == 0:\n return 0\n return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255]\n\n# substitution box based on F^{-1}(x)\nbox = [[0] * 8 for i in range(256)]\nbox[1][7] = 1\nfor i in range(2, 256):\n j = alog[255 - log[i]]\n for t in range(8):\n box[i][t] = (j >> (7 - t)) & 0x01\n\nB = [0, 1, 1, 0, 0, 0, 1, 1]\n\n# affine transform: box[i] <- B + A*box[i]\ncox = [[0] * 8 for i in range(256)]\nfor i in range(256):\n for t in range(8):\n cox[i][t] = B[t]\n for j in range(8):\n cox[i][t] ^= A[t][j] * box[i][j]\n\n# S-boxes and inverse S-boxes\nS = [0] * 256\nSi = [0] * 256\nfor i in range(256):\n S[i] = cox[i][0] << 7\n for t in range(1, 8):\n S[i] ^= cox[i][t] << (7-t)\n Si[S[i] & 0xFF] = i\n\n# T-boxes\nG = [[2, 1, 1, 3],\n [3, 2, 1, 1],\n [1, 3, 2, 1],\n [1, 1, 3, 2]]\n\nAA = [[0] * 8 for i in range(4)]\n\nfor i in range(4):\n for j in range(4):\n AA[i][j] = G[i][j]\n AA[i][i+4] = 1\n\nfor i in range(4):\n pivot = AA[i][i]\n if pivot == 0:\n t = i + 1\n while AA[t][i] == 0 and t < 4:\n t += 1\n assert t != 4, 'G matrix must be invertible'\n for j in range(8):\n AA[i][j], AA[t][j] = AA[t][j], AA[i][j]\n pivot = AA[i][i]\n for j in range(8):\n if AA[i][j] != 0:\n AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255]\n for t in range(4):\n if i != t:\n for j in range(i+1, 8):\n AA[t][j] ^= mul(AA[i][j], AA[t][i])\n AA[t][i] = 0\n\niG = [[0] * 4 for i in range(4)]\n\nfor i in range(4):\n for j in range(4):\n iG[i][j] = AA[i][j + 4]\n\ndef mul4(a, bs):\n if a == 0:\n return 0\n r = 0\n for b in bs:\n r <<= 8\n if b != 0:\n r = r | mul(a, b)\n return r\n\nT1 = []\nT2 = []\nT3 = []\nT4 = []\nT5 = []\nT6 = []\nT7 = []\nT8 = []\nU1 = []\nU2 = []\nU3 = []\nU4 = []\n\nfor t in range(256):\n s = S[t]\n T1.append(mul4(s, G[0]))\n T2.append(mul4(s, G[1]))\n T3.append(mul4(s, G[2]))\n T4.append(mul4(s, G[3]))\n\n s = Si[t]\n T5.append(mul4(s, iG[0]))\n T6.append(mul4(s, iG[1]))\n T7.append(mul4(s, iG[2]))\n T8.append(mul4(s, iG[3]))\n\n U1.append(mul4(t, iG[0]))\n U2.append(mul4(t, iG[1]))\n U3.append(mul4(t, iG[2]))\n U4.append(mul4(t, iG[3]))\n\n# round constants\nrcon = [1]\nr = 1\nfor t in range(1, 30):\n r = mul(2, r)\n rcon.append(r)\n\ndel A\ndel AA\ndel pivot\ndel B\ndel G\ndel box\ndel log\ndel alog\ndel i\ndel j\ndel r\ndel s\ndel t\ndel mul\ndel mul4\ndel cox\ndel iG\n\nclass rijndael:\n def __init__(self, key, block_size = 16):\n if block_size != 16 and block_size != 24 and block_size != 32:\n raise ValueError('Invalid block size: ' + str(block_size))\n if len(key) != 16 and len(key) != 24 and len(key) != 32:\n raise ValueError('Invalid key size: ' + str(len(key)))\n self.block_size = block_size\n\n ROUNDS = num_rounds[len(key)][block_size]\n BC = block_size // 4\n # encryption round keys\n Ke = [[0] * BC for i in range(ROUNDS + 1)]\n # decryption round keys\n Kd = [[0] * BC for i in range(ROUNDS + 1)]\n ROUND_KEY_COUNT = (ROUNDS + 1) * BC\n KC = len(key) // 4\n\n # copy user material bytes into temporary ints\n tk = []\n for i in range(0, KC):\n tk.append((key[i * 4] << 24) | (key[i * 4 + 1] << 16) |\n (key[i * 4 + 2] << 8) | key[i * 4 + 3])\n\n # copy values into round key arrays\n t = 0\n j = 0\n while j < KC and t < ROUND_KEY_COUNT:\n Ke[t // BC][t % BC] = tk[j]\n Kd[ROUNDS - (t // BC)][t % BC] = tk[j]\n j += 1\n t += 1\n tt = 0\n rconpointer = 0\n while t < ROUND_KEY_COUNT:\n # extrapolate using phi (the round key evolution function)\n tt = tk[KC - 1]\n tk[0] ^= (S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^ \\\n (S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ \\\n (S[ tt & 0xFF] & 0xFF) << 8 ^ \\\n (S[(tt >> 24) & 0xFF] & 0xFF) ^ \\\n (rcon[rconpointer] & 0xFF) << 24\n rconpointer += 1\n if KC != 8:\n for i in range(1, KC):\n tk[i] ^= tk[i-1]\n else:\n for i in range(1, KC // 2):\n tk[i] ^= tk[i-1]\n tt = tk[KC // 2 - 1]\n tk[KC // 2] ^= (S[ tt & 0xFF] & 0xFF) ^ \\\n (S[(tt >> 8) & 0xFF] & 0xFF) << 8 ^ \\\n (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \\\n (S[(tt >> 24) & 0xFF] & 0xFF) << 24\n for i in range(KC // 2 + 1, KC):\n tk[i] ^= tk[i-1]\n # copy values into round key arrays\n j = 0\n while j < KC and t < ROUND_KEY_COUNT:\n Ke[t // BC][t % BC] = tk[j]\n Kd[ROUNDS - (t // BC)][t % BC] = tk[j]\n j += 1\n t += 1\n # inverse MixColumn where needed\n for r in range(1, ROUNDS):\n for j in range(BC):\n tt = Kd[r][j]\n Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \\\n U2[(tt >> 16) & 0xFF] ^ \\\n U3[(tt >> 8) & 0xFF] ^ \\\n U4[ tt & 0xFF]\n self.Ke = Ke\n self.Kd = Kd\n\n def encrypt(self, plaintext):\n if len(plaintext) != self.block_size:\n raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext)))\n Ke = self.Ke\n\n BC = self.block_size // 4\n ROUNDS = len(Ke) - 1\n if BC == 4:\n SC = 0\n elif BC == 6:\n SC = 1\n else:\n SC = 2\n s1 = shifts[SC][1][0]\n s2 = shifts[SC][2][0]\n s3 = shifts[SC][3][0]\n a = [0] * BC\n # temporary work array\n t = []\n # plaintext to ints + key\n for i in range(BC):\n t.append((plaintext[i * 4 ] << 24 |\n plaintext[i * 4 + 1] << 16 |\n plaintext[i * 4 + 2] << 8 |\n plaintext[i * 4 + 3] ) ^ Ke[0][i])\n # apply round transforms\n for r in range(1, ROUNDS):\n for i in range(BC):\n a[i] = (T1[(t[ i ] >> 24) & 0xFF] ^\n T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^\n T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^\n T4[ t[(i + s3) % BC] & 0xFF] ) ^ Ke[r][i]\n t = copy.copy(a)\n # last round is special\n result = []\n for i in range(BC):\n tt = Ke[ROUNDS][i]\n result.append((S[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)\n result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)\n result.append((S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF)\n result.append((S[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF)\n return bytearray(result)\n\n def decrypt(self, ciphertext):\n if len(ciphertext) != self.block_size:\n raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext)))\n Kd = self.Kd\n\n BC = self.block_size // 4\n ROUNDS = len(Kd) - 1\n if BC == 4:\n SC = 0\n elif BC == 6:\n SC = 1\n else:\n SC = 2\n s1 = shifts[SC][1][1]\n s2 = shifts[SC][2][1]\n s3 = shifts[SC][3][1]\n a = [0] * BC\n # temporary work array\n t = [0] * BC\n # ciphertext to ints + key\n for i in range(BC):\n t[i] = (ciphertext[i * 4 ] << 24 |\n ciphertext[i * 4 + 1] << 16 |\n ciphertext[i * 4 + 2] << 8 |\n ciphertext[i * 4 + 3] ) ^ Kd[0][i]\n # apply round transforms\n for r in range(1, ROUNDS):\n for i in range(BC):\n a[i] = (T5[(t[ i ] >> 24) & 0xFF] ^\n T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^\n T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^\n T8[ t[(i + s3) % BC] & 0xFF] ) ^ Kd[r][i]\n t = copy.copy(a)\n # last round is special\n result = []\n for i in range(BC):\n tt = Kd[ROUNDS][i]\n result.append((Si[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)\n result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)\n result.append((Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF)\n result.append((Si[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF)\n return bytearray(result)\n\ndef encrypt(key, block):\n return rijndael(key, len(block)).encrypt(block)\n\ndef decrypt(key, block):\n return rijndael(key, len(block)).decrypt(block)\n\ndef test():\n def t(kl, bl):\n b = 'b' * bl\n r = rijndael('a' * kl, bl)\n assert r.decrypt(r.encrypt(b)) == b\n t(16, 16)\n t(16, 24)\n t(16, 32)\n t(24, 16)\n t(24, 24)\n t(24, 32)\n t(32, 16)\n t(32, 24)\n t(32, 32)\n\n","repo_name":"kiwibrowser/src","sub_path":"third_party/tlslite/tlslite/utils/rijndael.py","file_name":"rijndael.py","file_ext":"py","file_size_in_byte":11056,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"8667237687","text":"from PyQt5.QtWidgets import *\nfrom PyQt5 import QtGui\nfrom enum import Enum\n\n\nclass Animal(Enum):\n DOG = 1\n CAT = 2\n\n\nclass Dog:\n def speak(self):\n return \"Woof!\"\n\n\nclass Cat:\n def speak(self):\n return \"Meow!\"\n\n\nclass AnimalFactory:\n @staticmethod\n def create_animal(animal_type):\n animal_types = {\n Animal.DOG: Dog,\n Animal.CAT: Cat\n }\n animal_class = animal_types.get(animal_type)\n return animal_class() if animal_class else None\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"PyQt5 Factory Method Pattern with Enum Example\")\n self.setGeometry(100, 100, 400, 200)\n\n self.label = QLabel(\"Animal Speak:\", self)\n self.label.move(50, 50)\n\n self.create_button(\"Dog Speak\", Animal.DOG, 50, 100)\n self.create_button(\"Cat Speak\", Animal.CAT, 150, 100)\n\n def create_button(self, text, animal_type, x, y):\n button = QPushButton(text, self)\n button.move(x, y)\n button.clicked.connect(lambda: self.animal_speak(animal_type))\n\n def animal_speak(self, animal_type):\n animal = AnimalFactory.create_animal(animal_type)\n if animal:\n self.label.setText(animal.speak())\n\n\nif __name__ == \"__main__\":\n app = QApplication([])\n window = MainWindow()\n window.show()\n app.exec_()\n","repo_name":"syurskyi/Python_Topics","sub_path":"120_design_patterns/003_factories/pyqt/Factory_Method/005.py","file_name":"005.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"7917698872","text":"import numpy as np\nimport pandas as pd\nimport datetime\n\nfrom utils.load_functions import load_tar_datasets, load_column_names\n\n\ndef process_tar_data(pred_var, weeks, col):\n assert col in ['tmp','prec']\n assert pred_var in ['temp34','prec34']\n tmp = load_tar_datasets(pred_var)\n tmp_list = []\n for rgn in tmp['region_id'].unique():\n region_tmp = pd.DataFrame(tmp[tmp['region_id']==rgn].iloc[0,-weeks:].values, columns=[col])\n region_tmp['lat'] = rgn[0]\n region_tmp['lon'] = rgn[1]\n tmp_list.append(region_tmp)\n tmp_df = pd.concat(tmp_list, axis=0, ignore_index=False)\n tmp_df = tmp_df.reset_index(drop=True)\n return tmp_df\n\n\ndef get_prediction_data(pred_date, latest_data_date, data, seq_len=26):\n \"\"\" Get input data for current target week from features dataset.\n Note start date for these is two weeks behind current date.\n Note usually data is not available for latest day - in which case take latest\n available data date for last data point in input sequence.\n Get temp/prec data using get_gt.py method, and join to features datasets.\n Note - for a given date, these interpolate and 2 week average the values 3/4 weeks ahead of date.\n Therefore we process differently - these start dates are 28 days behind current prediction date. \"\"\"\n # Features data\n prediction_date = datetime.datetime.strptime(pred_date,'%Y-%m-%d')\n last_start_date = prediction_date - datetime.timedelta(days=14)\n last_available_start_date = datetime.datetime.strptime(latest_data_date,'%Y-%m-%d')\n pred_date_index = [last_available_start_date] + [last_start_date - datetime.timedelta(days=x) for x in range(14,14*seq_len,14)]\n data = data[data.start_date.isin(pred_date_index)].reset_index(drop=True)\n # Temp/prec data\n tmp = process_tar_data('temp34', seq_len, 'tmp')\n prec = process_tar_data('prec34', seq_len, 'prec')\n # Join all\n data['precip'] = prec['prec']\n data['tmp2m'] = tmp['tmp']\n full_col_names = load_column_names()\n data = data[full_col_names]\n return data\n\n\ndef prepare_single_spatial_temporal_region(dataset, target_region, rgn_id_to_int, seq_len, sg, region_emb=True):\n \"\"\" \"\"\"\n # Crop local region\n local_region = dataset[:, (target_region[0] - sg):(target_region[0] + sg + 1),\n (target_region[1] - sg):(target_region[1] + sg + 1), :]\n # Spatial data\n spatial_data = local_region[:, :, :, 3:-4].astype(np.float16)\n # Temporal data\n if region_emb:\n local_reg_id = str((int(local_region[0, sg, sg, 1]), int(local_region[0, sg, sg, 2])))\n local_reg_id = rgn_id_to_int[local_reg_id]\n temporal_data = local_region[:, sg, sg, -4:].astype(np.float16)\n region_embedding = np.repeat(local_reg_id, seq_len).reshape(seq_len, 1).astype(np.int16)\n return np.array(spatial_data), np.array(temporal_data), np.array(region_embedding)\n # print(temporal_data.shape, region_embedding.shape)\n else:\n temporal_data = local_region[:, sg, sg, 1:].astype(np.float16)\n return np.array(spatial_data), np.array(temporal_data)\n\n\ndef generate_all_region_input(input_tensor, target_region_ids, rgn_id_to_int):\n spatial_data, temporal_data, reg_emb_data = [], [], []\n for rgn in target_region_ids:\n # Generate single window\n spt, tmp, remb = prepare_single_spatial_temporal_region(input_tensor, rgn, rgn_id_to_int, seq_len=26, sg=5)\n spatial_data.append(spt)\n temporal_data.append(tmp)\n reg_emb_data.append(remb)\n spatial_data = np.stack(spatial_data)\n temporal_data = np.stack(temporal_data)\n reg_emb_data = np.stack(reg_emb_data)\n\n return spatial_data, temporal_data, reg_emb_data\n\n\nclass PreprocessTemporalSpatialDataPrediction:\n \"\"\"\n Class for conducting preprocessing pipeline for temporal spatial data for model prediction\n Standardizes feature fields, and scales all categorical feature fields using existing scaler, means, stds\n Transforms dataset to spatial form [timesteps,lat,lon,features]\n Creates missing regions to enable above matrix transformation (filling in missing value with 0 - note this aligns well with [0,1] scaling)\n \"\"\"\n\n def __init__(self, scaler, data_mean, data_std, data: np.array, locations: np.array, col_names: list,\n num_regions: int, num_features: int, max_sg: int = 5):\n self.scaler = scaler\n self.data_mean = data_mean\n self.data_std = data_std\n self.data = data\n self.locations = locations\n self.regions = self.locations['region_id'].unique()\n self.latmin, self.latmax, self.lonmin, self.lonmax = self.locations['lat'].min(), self.locations['lat'].max(), \\\n self.locations['lon'].min(), self.locations['lon'].max()\n self.bin_width, self.bin_height = self.lonmax - self.lonmin + 1, self.latmax - self.latmin + 1\n self.col_names = col_names\n self.num_regions = num_regions\n self.num_features = num_features\n self.weather_features = 8\n self.cyclical_features = 4\n self.num_timesteps = self.data.reshape(self.num_regions, -1, self.num_features).shape[1]\n self.max_sg = max_sg\n\n def standardize_and_scale_data(self):\n \"\"\" Standarize features using mean, std from train set; then scale to 0-1 scale \"\"\"\n # Ensure dataset is order by start date, by region (lat, then lon)\n # self.data = self.data.sort_values(by=['start_date', 'lat','lon']).reset_index(drop=True)\n # Reshape all regions together\n self.data = np.array(self.data).reshape(-1, self.num_features)\n # Extract train_split - note we only standardize using mean and std from train set\n TRAIN_SPLIT = self.num_timesteps # - 2*1008*self.num_regions\n\n # Start Date - need this for indexing/grouping by region\n date = self.data[:, 0].reshape((-1, 1))\n\n # Keep lat/lon from scaling\n lat_lon = self.data[:, 1:3].astype(np.float16)\n\n # Standardize feature fields using training means & stds\n features = self.data[:, 3:-4].astype(np.float32)\n features = ((features - self.data_mean) / self.data_std).astype(np.float16)\n\n # Deal with cyclical features separately - these are already scaled\n cyclical_features = self.data[:, -4:].astype(np.float16)\n\n # All features - stack and scale\n all_features = np.hstack((features, cyclical_features))\n\n # Scale feature data to 0-1 scale using training scaler\n scaler = self.scaler\n all_features = scaler.fit_transform(all_features)\n\n # Recombine & Reshape\n self.data = np.hstack((date, lat_lon, all_features))\n self.data = self.data.reshape(-1, self.num_features)\n\n def process_datetime(self, dt_fmt: str = '%Y-%m-%d', datetimecol='start_date'):\n # print(\"Parsing datetime fields \\n\")\n def lookup(s):\n \"\"\"\n This is an extremely fast approach to datetime parsing.\n \"\"\"\n dates = {date: pd.to_datetime(date, format=dt_fmt) for date in s.unique()}\n return s.map(dates)\n\n self.data[datetimecol] = lookup(self.data[datetimecol])\n self.all_dates = np.unique(self.data[\"start_date\"].dt.strftime('%Y-%m-%d'))\n\n def get_missing_regions(self):\n \"\"\" Find regions in lat-lon box which are not modelled geographic regions \"\"\"\n self.all_region_ids = [(lat, lon) for lat in range(self.latmin, self.latmax + 1) for lon in\n range(self.lonmin, self.lonmax + 1)]\n self.num_total_regions = len(set(self.all_region_ids))\n self.missing_regions = list(set(self.all_region_ids) - set(list(self.regions)))\n self.missing_regions.sort()\n\n def mask_missing_regions(self, mask_value=0):\n \"\"\" Create masked data for missing region - zero pad (0,1) scaled features \"\"\"\n self.get_missing_regions()\n masked_rgn_lst = []\n for rgn in self.missing_regions:\n date_col = self.data.reshape(self.num_regions, -1, self.num_features)[0, :, 0].reshape(self.num_timesteps,\n 1) # take same dates\n lat_col = np.array([rgn[0]] * self.num_timesteps).reshape(self.num_timesteps,\n 1) # take lat of current region\n lon_col = np.array([rgn[1]] * self.num_timesteps).reshape(self.num_timesteps,\n 1) # take lon of current region\n feature_cols = np.array([mask_value] * self.num_timesteps * (self.weather_features)).reshape(\n self.num_timesteps, self.weather_features) # mask weather features\n cyclical_cols = self.data.reshape(self.num_regions, -1, self.num_features)[0, :,\n -self.cyclical_features:].reshape(self.num_timesteps,\n self.cyclical_features) # take time features\n masked_rgn = np.hstack((date_col, lat_col, lon_col, feature_cols, cyclical_cols))\n masked_rgn_lst.append(masked_rgn)\n masked_rgns = np.concatenate(masked_rgn_lst)\n self.masked_rgns_df = pd.DataFrame(masked_rgns)\n self.masked_rgns_df.columns = self.col_names\n self.masked_rgns_df['region_id'] = list(\n zip(self.masked_rgns_df['lat'].astype(int), self.masked_rgns_df['lon'].astype(int)))\n self.masked_rgns_df['model_region'] = False\n\n def convert_rgns_data_to_df(self):\n \"\"\" Convert to df of shape (num_timesteps*num_regions, num_features). Ordered by region by timestep \"\"\"\n self.data = pd.DataFrame(self.data.reshape(-1, self.num_features))\n self.data.columns = self.col_names\n # Create unique region id\n self.data['region_id'] = list(zip(self.data['lat'].astype(int), self.data['lon'].astype(int)))\n self.data['model_region'] = True\n\n def join_masked_regions(self):\n \"\"\" Join masked regions df to rgns data df, and sort \"\"\"\n self.data = pd.concat([self.data, self.masked_rgns_df])\n # Convert date to datetime\n self.process_datetime()\n # Sort\n self.data = self.data.sort_values(by=['lat', 'lon', 'start_date']).reset_index(drop=True)\n assert self.num_total_regions == len(self.data['region_id'].unique())\n\n def get_global_region_tensor(self, save=False):\n print(\"Generating global spatial grid \\n\")\n spatial_tw_list = []\n # self.all_dates = np.sort(self.data['start_date'].unique())\n # For every timestep, create binsize*binsize global spatial grid of demand\n for counter, time_window in enumerate(self.all_dates):\n mask = self.data['start_date'] == np.datetime64(time_window)\n pvt_current_time_window = np.flipud(np.array(self.data[mask]).reshape(self.bin_height, self.bin_width, -1))\n spatial_tw_list.append(pvt_current_time_window)\n # Store global_regions_tensor - stack as tensor: for bin_index [num_timesteps, bin_width , bin_height, number of channels]\n self.global_region_tensor = np.stack(spatial_tw_list).reshape(-1, self.bin_height, self.bin_width,\n pvt_current_time_window.shape[2])\n self.global_region_tensor = self.global_region_tensor[:, :, :, :-2]\n\n # Pad outer edge with max spatial granularity\n npad = ((0, 0), (self.max_sg, self.max_sg), (self.max_sg, self.max_sg),\n (0, 0)) # pad (before, after) on region height/width dimensions only\n self.global_region_tensor = np.pad(self.global_region_tensor, pad_width=npad, mode='constant',\n constant_values=0)\n # Save to disk\n if save:\n print(\"Saving global spatial tensor \\n\")\n np.save('data/processed/spatial_temporal/global_region_tensor_scaled_sg' + str(self.max_sg),\n self.global_region_tensor)\n\n def get_target_regions(self):\n self.target_regions = self.locations['region_id'].unique()\n self.target_region_ids = [(self.locations['lat'].max() - region[0] + self.max_sg,\n region[1] - self.locations['lon'].min() + self.max_sg) for region in\n self.target_regions]\n\n def get_region_ids(self):\n self.get_target_regions()\n self.rgn_id_vocab = [str(region) for region in self.target_regions]\n self.rgn_id_to_int = {rgn_id: i for i, rgn_id in enumerate(self.rgn_id_vocab)}\n self.int_to_rgn_id = {i: rgn_id for i, rgn_id in enumerate(self.rgn_id_vocab)}\n return (self.rgn_id_vocab, self.rgn_id_to_int, self.int_to_rgn_id, self.target_region_ids)\n\n def preprocess_pipeline(self):\n self.standardize_and_scale_data()\n self.mask_missing_regions()\n self.convert_rgns_data_to_df()\n self.join_masked_regions()\n self.get_global_region_tensor()\n del self.data","repo_name":"o-waring/subseasonal_forecasting","sub_path":"subseasonal_forecasting/predict/prediction_processing.py","file_name":"prediction_processing.py","file_ext":"py","file_size_in_byte":13209,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"18268122067","text":"import math\nequation = input(\"Enter equation: \")\nbotrange = -100\ntoprange = 100\nstretch = 5\nshiftx = 0\nshifty = 0\nif botrange == \"\":\n botrange = -10\nelse:\n botrange = int(botrange)\nif toprange == \"\":\n toprange = 10\nelse:\n toprange = int(toprange)\ninbetween = 500\nequation = equation.replace(\"^\",\"**\").replace(\"2x\",\"2*x\").replace(\"3x\",\"3*x\").replace(\"4x\",\"4*x\").replace(\"5x\",\"5*x\").replace(\"6x\",\"6*x\").replace(\"7x\",\"7*x\").replace(\"8x\",\"8*x\").replace(\"9x\",\"9*x\").replace(\")(\",\")*(\")\ndef plugin(b):\n return float(eval(equation.replace(\"x\",\"(\"+str(b)+\")\")))\nplot = []\nfor i in range(botrange*200,toprange*200):\n try:\n plot.append((i / 200, -plugin(i / 200)))\n except:\n pass\nimport pygame\npygame.init()\nscreen_width = 500\nscreen_height = 300\nscreen = pygame.display.set_mode((screen_width, screen_height))\nclock = pygame.time.Clock()\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n key = pygame.key.get_pressed()\n if key[pygame.K_e]:\n stretch += 1\n if key[pygame.K_q]:\n stretch += -1\n if key[pygame.K_d]:\n shiftx += -1\n if key[pygame.K_a]:\n shiftx += 1\n botrange += shiftx\n toprange += shiftx\n if key[pygame.K_w]:\n shifty += 1\n if key[pygame.K_s]:\n shifty += -1\n screen.fill((0, 0, 0))\n xaxis = pygame.Rect(shiftx-2500, 150+shifty, 5000, 1)\n yaxis = pygame.Rect(250+shiftx,shifty-1500,1,3000)\n for i in range(-500,501):\n xticks = pygame.Rect(250+0+i*5*stretch+shiftx,147+shifty,1,6)\n pygame.draw.rect(screen, (50,50,50), xticks)\n for i in range(-300,301):\n yticks = pygame.Rect(247+shiftx,150+0+i*5*stretch+shifty,6,1)\n pygame.draw.rect(screen, (50,50,50), yticks)\n pygame.draw.rect(screen, (50,50,50), xaxis)\n pygame.draw.rect(screen, (50, 50, 50), yaxis)\n for i in plot:\n point = (stretch*i[0]+250+shiftx,stretch*i[1]+150+shifty,1,1)\n pygame.draw.rect(screen, (255,255,255), point)\n pygame.display.update()\n clock.tick(20)\npygame.quit()\n","repo_name":"theoradicle/repository","sub_path":"Graphing.py","file_name":"Graphing.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34431296417","text":"from collections import defaultdict\nn,m,k=map(int,input().split())\ngraph=defaultdict(list)\nfor i in range(m):\n u,v,w=map(int,input().split())\n graph[u].append([v,w])\n graph[v].append([u,w])\nif(k==0):\n print(-1)\nelse:\n storage=list(map(int,input().split()))\n myMap=defaultdict(int)\n for val in storage:\n myMap[val]=1\n ans=float(\"inf\")\n for i in range(1,n+1):\n size=len(graph[i])\n if(myMap[i] and size>0):\n for j in range(size):\n if(myMap[graph[i][j][0]]==0 and graph[i][j][1] 6))\n# print(np.sort(ar))\n# print(-np.sort(-ar)) # descending order\n\n# \" Any() and All() \"\na = np.array([2, 5, 9, 6, 3, 7])\n# print(np.any(a % 2 == 0))\n# print(np.all(a % 2 == 0))\n\n\n# \" arange() \" it will return array of the given range\na1 = np.arange(10)\n# print(a1)\n# print(np.reshape(a1, [2, 5])) # you can create a matrix according to the number of elements\nprint(np.resize(a1, (3, 7))) # free to create any dimension array\n","repo_name":"BHAVIN-VHANESHA/Python-Tutorial","sub_path":"NumPy/More_on_Numpy.py","file_name":"More_on_Numpy.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18029634742","text":"# ordenar por seleccion\nimport os\nos.system(\"cls\")\n\n\ndef Listaorganizar(lista):\n for i in range(1, len(lista)):\n elemento = lista[i] # 300\n indice = i # 1\n print(f\"Posicion {i} y valores en lista: {lista}\")\n while indice > 0 and lista[indice - 1] > elemento:\n lista[indice] = lista[indice-1]\n indice = indice - 1\n\n lista[indice] = elemento\n # 0 - > 300\n\n\nlista = [2000, 300, 25, 40, 31, 45, 45, 50, 19]\nprint(f\"Valores sin organizados : {lista}\")\nListaorganizar(lista)\nprint(f\"Valores organizados : {lista}\")\n\nprint(\"Gracias por participar\")\n","repo_name":"haroldtr/python-p32021","sub_path":"semana07/lista-06-ordernar-por-seleccion.py","file_name":"lista-06-ordernar-por-seleccion.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"20867496147","text":"#셀프 넘버 (백준 - 구현 유형)\n#https://www.acmicpc.net/problem/4673\n\nnonself =[]\n#완전 탐색을 활용해 전체 경우의 수 파악\nfor i in range(1,10000):\n a= i%1000\n b = i%100\n c = i%10\n di = i + (i//1000)+(a//100)+(b//10)+c\n #만들어진 숫자는 i라는 생성자를 갖는 수\n nonself.append(di)\n\n#전체를 돌면서 10000보다 작거나 같은 수 중 di에 속하지 않는 수를 출력\nfor j in range(10000):\n if j not in nonself:\n print(j)\n","repo_name":"giraffejin/Algorithm","sub_path":"BOJ/Implementation/Q4673.py","file_name":"Q4673.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73764336805","text":"import os\nimport sys\nimport struct\nfrom os import close, putenv, urandom\nfrom typing import List\nfrom itertools import cycle, islice\nfrom des import des\nfrom Cryptodome.Cipher import DES3, AES\nfrom hashlib import md5, sha256\nimport functools\nimport operator\nimport random\n\n\ndef ooo0oOoooOOO0(word):\n return [char for char in word]\n\n\ndef oOO0OoOoo000(file, key):\n return bytes(a ^ b for a, b in zip(file, cycle(key)))\n\n\ndef iii111(key, letter):\n if 65 <= ord(letter) <= 90:\n return chr(65 + (ord(letter) - 65 + ord(key)) % 26)\n elif 97 <= ord(letter) <= 122:\n return chr(97 + (ord(letter) - 97 + ord(key)) % 26)\n elif 48 <= ord(letter) <= 57:\n return chr(48 + (ord(letter) - 48 + ord(key)) % 10)\n else:\n return str(letter)\n\n\ndef I1i1Ii(in_file, key, o_file):\n Ooo0OO = 0\n ii1Ii1I = \"\"\n oo0 = ooo0oOoooOOO0(key)\n for OOO in in_file:\n for iII1II11iI1 in OOO:\n ii1Ii1I += iii111(oo0[Ooo0OO % len(oo0)], iII1II11iI1)\n Ooo0OO = Ooo0OO + 1\n o_file.write(ii1Ii1I)\n\n\ndef OO0o0O0o0(in_file, key, o_file):\n Ooo0OO = 0\n ii1Ii1I = \"\"\n oo0 = ooo0oOoooOOO0(key)\n for OOO in in_file:\n for iII1II11iI1 in OOO:\n ii1Ii1I += iii111(oo0[Ooo0OO % len(oo0)], iII1II11iI1)\n Ooo0OO = Ooo0OO + 1\n o_file.write(ii1Ii1I)\n\n\ndef oOoOOO0ooooO0(file, key, path):\n iII = des()\n bytes = iII.encrypt(key, file)\n path.write(bytes)\n\n\ndef IIIIi(file, key, o_file):\n O0O0oOo00oO0 = md5(key.encode(\"ascii\")).digest()\n I1II1ii111i = DES3.adjust_key_parity(O0O0oOo00oO0)\n I1i1iI1I1Ii1 = DES3.new(I1II1ii111i, DES3.MODE_EAX, nonce=b\"0\")\n OO = file.read()\n bytes = I1i1iI1I1Ii1.encrypt(OO)\n o_file.write(bytes)\n\n\ndef o0oO00OO(i_file, key, o_file, path_name, size=64 * 1024):\n O0OO0OOOOoo0o = os.urandom(16)\n O0O0oOo00oO0 = sha256(key.encode(\"ascii\")).digest()\n I11i1IIII1I = AES.new(O0O0oOo00oO0, AES.MODE_CBC, O0OO0OOOOoo0o)\n I11IIiiI1 = os.path.getsize(path_name)\n o_file.write(struct.pack(\" bool:\n @cache\n def dac(x, y):\n \n ok = False\n if x == y:\n return True\n for i in range(1, len(x)):\n ok |= dac(x[:i], y[:i]) and dac(x[i:], y[i:])\n ok |= dac(x[:i], y[-i:]) and dac(x[i:], y[:-i])\n return ok\n \n \n return dac(s1,s2)\n","repo_name":"samyogita/LeetCode-problems","sub_path":"scramble_string.py","file_name":"scramble_string.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"6784614378","text":"from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QGridLayout, QComboBox, QSpinBox\n\n\nclass EvalFuncTrainingDialogBox(QDialog):\n\n def __init__(self):\n\n super().__init__()\n\n self.max_generation_count = 0\n self.no_of_games = 1\n self.pop_size = 4\n self.player_agent = 2\n\n self.setWindowTitle(\"Train Evaluation Function\")\n\n QBtn = QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel\n\n self.buttonBox = QDialogButtonBox(QBtn)\n self.buttonBox.accepted.connect(self.accept)\n self.buttonBox.rejected.connect(self.reject)\n\n layout = QGridLayout()\n\n pop_size_spin_box = QSpinBox()\n pop_size_spin_box.setMinimum(0)\n pop_size_spin_box.setMaximum(40)\n pop_size_spin_box.setValue(4)\n pop_size_spin_box.setSuffix(\" individuals\")\n pop_size_spin_box.setSingleStep(4)\n pop_size_spin_box.valueChanged.connect(self.pop_size_changed)\n\n max_gen_spin_box = QSpinBox()\n max_gen_spin_box.setMinimum(0)\n max_gen_spin_box.setMaximum(999)\n max_gen_spin_box.setValue(1)\n max_gen_spin_box.setSuffix(\" generations\")\n max_gen_spin_box.setSingleStep(1)\n max_gen_spin_box.valueChanged.connect(self.max_gen_changed)\n\n game_count_spin_box = QSpinBox()\n game_count_spin_box.setMinimum(1)\n game_count_spin_box.setMaximum(10)\n game_count_spin_box.setValue(1)\n game_count_spin_box.setSuffix(\" games\")\n game_count_spin_box.setSingleStep(1)\n game_count_spin_box.valueChanged.connect(self.no_games_changed)\n\n agent_dropdown = QComboBox(self)\n agent_dropdown.addItems(['Max', 'Minimax'])\n agent_dropdown.activated. \\\n connect(lambda index=agent_dropdown.currentIndex(): self.set_player_agent(index))\n\n layout.addWidget(QLabel(\"Set population size: \"), 0, 0)\n layout.addWidget(QLabel(\"Set max number of generations: \"), 1, 0)\n layout.addWidget(QLabel(\"Set number of games per round: \"), 2, 0)\n layout.addWidget(QLabel(\"Set agent used: \"), 3, 0)\n\n layout.addWidget(pop_size_spin_box, 0, 1)\n layout.addWidget(max_gen_spin_box, 1, 1)\n layout.addWidget(game_count_spin_box, 2, 1)\n layout.addWidget(agent_dropdown, 3, 1)\n layout.addWidget(self.buttonBox, 4, 1)\n\n self.setLayout(layout)\n\n pass\n\n def no_games_changed(self, count):\n self.no_of_games = count\n\n def max_gen_changed(self, count):\n self.max_generation_count = count\n\n def pop_size_changed(self, count):\n self.pop_size = count\n\n def set_player_agent(self, i):\n self.player_agent = i + 2\n\n\n","repo_name":"hfynn5/FinalYearProject","sub_path":"Congkak/DialogueBoxes/EvalFuncTrainingDialogBox.py","file_name":"EvalFuncTrainingDialogBox.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22794039004","text":"import logging\nimport time\n\nimport schedule\nfrom google.cloud import pubsub_v1\n\n\ndef pull_message(project, subscription):\n subscriber = pubsub_v1.SubscriberClient()\n subscription_path = subscriber.subscription_path(project, subscription)\n\n def callback(message: pubsub_v1.subscriber.message.Message) -> None:\n logging.info(f\"Received {message.data}.\")\n event_type = message.attributes.get(\"event_type\")\n logging.info(f\" Event Type {event_type}..\\n\")\n logging.info(f\" Messages {message.data}..\\n\")\n message.ack()\n\n streaming_pull_future = subscriber.subscribe(\n subscription_path, callback=callback, await_callbacks_on_shutdown=True,\n )\n logging.info(f\"Listening for messages on {subscription_path}..\\n\")\n\n # Wrap subscriber in a 'with' block to automatically call close() when done.\n with subscriber:\n try:\n # When `timeout` is not set, result() will block indefinitely,\n # unless an exception is encountered first.\n streaming_pull_future.result(timeout=60)\n except Exception as ex:\n logging.info(ex)\n streaming_pull_future.cancel() # Trigger the shutdown.\n streaming_pull_future.result() # Block until the shutdown is complete..\n logging.info(\"Streaming pull future canceled.\")\n\n\nclass MessagePuller:\n def __init__(self, project, subscription):\n self.project_id = project\n self.subscription_id = subscription\n\n def run(self):\n schedule.every().minute.at(':00').do(pull_message, self.project_id, self.subscription_id)\n while True:\n try:\n schedule.run_pending()\n time.sleep(.1)\n except Exception as ex:\n logging.info(ex)\n","repo_name":"IndikaKuma/ADA2023","sub_path":"lab7/user/message_puller.py","file_name":"message_puller.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71019348325","text":"from django.shortcuts import render, redirect\nfrom django.db import models\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, PDF_UploadForm\nfrom .models import PDF_Files\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Account created for {username}!')\n return redirect('login')\n else:\n form = UserRegisterForm()\n return render(request, 'users/register.html', {'form': form})\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(\n request.POST,\n request.FILES,\n instance=request.user.profile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, f'Your account has been updated!')\n return redirect('profile')\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n\n context = {\n 'u_form': u_form,\n 'p_form': p_form\n }\n\n return render(request, 'users/profile.html', context)\n\n\n@login_required\ndef handouts_pdf(request):\n if request.method == 'POST':\n form = PDF_UploadForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('handouts_pdf')\n else:\n form = PDF_UploadForm()\n return render(request, 'users/handouts_pdf.html', {'form': form})\n\n\ndef pdf_list_view(request):\n pdf_list = PDF_Files.objects.all()\n return render(request, 'users/pdf_list.html', {'pdf_list': pdf_list})\n","repo_name":"ImranGreat1/django_project","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10602028440","text":"import requests\nimport schedule\nimport time\nimport os\nimport csv\nimport sys\n#import graph\n\ndef item_to_track():\n item_link = input(\"Link to steam community market for your item: \")\n return item_link[47:]\n\ndef check_item_price(market_name):\n r = requests.get(f\"http://steamcommunity.com/market/priceoverview/?market_hash_name={market_name}&appid=730¤cy=29\").json()\n return r\n\ndef check_lowest_price(data):\n return float(data['lowest_price'][4:])\n\ndef check_median_price(data):\n return float(data['median_price'][4:])\n\ndef check_file_size():\n try:\n if os.path.getsize(\"price.csv\") >= 1048576:\n return False\n else:\n return True\n except:\n print(\"Creating price csv...\", flush=True)\n sys.stdout.flush()\n return 2\n\ndef write_to_file(time, lowest_price, median_price):\n file_size = check_file_size()\n\n if file_size == 2:\n with open(\"price.csv\", \"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"DATE\", \"LOWEST\", \"MEDIAN\"])\n writer.writerow([time, lowest_price, median_price])\n elif file_size == False:\n print(\"Resetting csv...\")\n sys.stdout.flush()\n with open(\"price.csv\", \"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([\"DATE\", \"LOWEST\", \"MEDIAN\"])\n writer.writerow([time, lowest_price, median_price])\n elif file_size == True:\n with open(\"price.csv\", \"a\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerow([time, lowest_price, median_price])\n\ndef main_loop(name):\n item_price_data = check_item_price(name)\n lowest_price = check_lowest_price(item_price_data)\n median_price = check_median_price(item_price_data)\n\n current_time = time.strftime(\"%Y %b %d %H:%M:%S\")\n\n write_to_file(current_time, lowest_price, median_price)\n\n print(f\"{current_time} ${lowest_price} ${median_price}\")\n sys.stdout.flush()\n\n\ndef main(item):\n main_loop(item)\n schedule.every(10).seconds.do(main_loop, name=item)\n while True:\n schedule.run_pending()\n time.sleep(1)","repo_name":"AlvinNg727/csgo-steam-market","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28096895354","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (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 Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\n\nimport bpy\nimport bmesh\nfrom mathutils import geometry\n\n\ndef add_vertex_to_intersection():\n objs = bpy.context.selected_objects\n fobj = bpy.context.active_object\n #making sure the active object is the last object in the \"objs\"-list\n #Important as it makes sure the new vertex is added\n #in the mesh of the object of which the edge was selected first\n objs.remove(fobj)\n objs.append(fobj)\n \n #working with one object\n if len(objs)==1:\n me = objs[0].data\n #matrix needed for global coordinates\n wm = objs[0].matrix_world\n bme = bmesh.from_edit_mesh(me)\n edges = [e for e in bme.edges if e.select]\n\n if len(edges) == 2:\n [[v1, v2], [v3, v4]] = [[wm @ v.co for v in e.verts] for e in edges]\n\n #working with 2 objects\n if len(objs)==2:\n me = objs[0].data\n wm = objs[0].matrix_world\n he = objs[1].data\n wm1 = objs[1].matrix_world\n bme = bmesh.from_edit_mesh(me)\n bhe = bmesh.from_edit_mesh(he)\n\n edgesme = [e for e in bme.edges if e.select]\n edgeshe = [e for e in bhe.edges if e.select]\n\n if len(edgesme) == 1 and len(edgeshe) == 1:\n [v1, v2] = [wm @ v.co for v in edgesme[0].verts]\n [v3, v4] = [wm1 @ v.co for v in edgeshe[0].verts]\n\n bhe.free()\n\n iv = geometry.intersect_line_line(v1, v2, v3, v4)\n\n if iv:\n iv = (iv[0] + iv[1]) / 2\n bme.verts.new(iv)\n bme.verts.ensure_lookup_table()\n bme.verts[-1].select = True\n bmesh.update_edit_mesh(me)\n\nclass TCVert2Intersection(bpy.types.Operator):\n '''Add a vertex at the intersection (projected or real) of two selected edges of up to 2 objects'''\n bl_idname = 'tinycad.vertintersect'\n bl_label = 'V2X vertex to intersection'\n bl_options = {'REGISTER', 'UNDO'}\n\n @classmethod\n def poll(cls, context):\n objs = context.selected_objects\n if len(objs) >2 or len(objs)==0:\n return 0\n for obj in objs:\n if obj is None or obj.type != 'MESH' or obj.mode != 'EDIT':\n return 0\n return 1\n\n def execute(self, context):\n add_vertex_to_intersection()\n return {'FINISHED'}\n","repo_name":"zeffii/mesh_tiny_cad","sub_path":"V2X.py","file_name":"V2X.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":150,"dataset":"github-code","pt":"52"} +{"seq_id":"35250638320","text":"import pandas as pd\nimport numpy as np\nfrom linearmodels.iv import IV2SLS\nimport random\nimport math\nimport os\nimport sys\n\nfsdata = pd.read_csv(\"C:/Users/wisen/OneDrive/Desktop/Work Stuff/PHD/Second Year/IO/Project/fsdlag.csv\")\nssdata = pd.read_csv(\"C:/Users/wisen/OneDrive/Desktop/Work Stuff/PHD/Second Year/IO/Project/estimateddifinalpresent.csv\")\npricedata = pd.read_csv(\"C:/Users/wisen/OneDrive/Desktop/Work Stuff/PHD/Second Year/IO/Project/cutpdata.csv\")\n\nwp = fsdata[[\"wp\",\"wplag1\",\"wplag2\"]]\nexogreg = fsdata[[\"Prod1\",\"Prod2\",\"Prod3\",\"Prod4\",\"Prod5\",\"Prod6\",\"Prod7\",\"Prod8\",\"Prod9\",\"Prod10\",\"Prod11\"]]\nprice = pricedata[\"price\"]\n\nssdata = ssdata.to_numpy()\nsssdata = pd.DataFrame(ssdata[:,1])\n\n#pricedata = pricedata.to_numpy()\n#fsdata = fsdata.to_numpy()\nmodel = IV2SLS(dependent = sssdata,exog=exogreg,endog=price,instruments=wp)\nresults = model.fit(cov_type=\"robust\")\npredvalues = results.predict()\noriginal = sssdata\nresiduals = original.to_numpy() - predvalues.to_numpy()\n\nresiduals = pd.DataFrame(residuals)\nprint(results)\nsys.exit()\ni = 1\n\ndef objfunc(Z,e,etp,ztp,i):\n if i == 0:\n inside = (ztp@Z)\n else:\n inside = (ztp @ e) @ (etp @ Z)\n print(\"INSIDE\")\n print(inside)\n weightingmatrix = 1 / inside\n print(weightingmatrix)\n print(ztp @ e)\n objf = (etp @ Z) @ weightingmatrix @ (ztp @ e)\n print(objf)\n return(objf)\n\nwp = pd.DataFrame(wp)\nresidtest = residuals[0].values\n\nwptest = wp[\"wp\"].values\nwptest = wptest.reshape((10296,1))\nresidtest = residtest.reshape((10296,1))\n\nrtp = np.transpose(residtest)\nwtp = np.transpose(wptest)\n\nobjfunc(wptest,residtest,rtp,wtp,1)","repo_name":"NathanWise17/BLP-Estimation","sub_path":"Project/IVTesting.py","file_name":"IVTesting.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"988433810","text":"import tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nfrom tensorflow.keras.layers import Conv2D, BatchNormalization, Flatten, Dense, Reshape, Activation, Dropout\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport datetime\n\n\ndef sudoku_acc(ytrue, ypred):\n ytrue = tf.cast(ytrue, dtype=tf.int64)\n ypred_a = tf.math.argmax(ypred, axis=-1)\n ypred_b = tf.expand_dims(ypred_a, axis=-1)\n r = tf.equal(ytrue, ypred_b)\n r = tf.cast(r, dtype=tf.float32)\n return tf.reduce_mean(r)\n\n\ndef correct_grid(ytrue, ypred):\n ytrue = tf.cast(ytrue, dtype=tf.int64)\n ypred_a = tf.math.argmax(ypred, axis=-1)\n ypred_b = tf.expand_dims(ypred_a, axis=-1)\n r = tf.equal(ytrue, ypred_b)\n r = tf.cast(r, dtype=tf.float32)\n r_s = tf.reduce_sum(r, axis = [1,2])\n return tf.reduce_mean(r_s//81)\n\n\ndef sudoku_loss(ytrue, ypred, from_logits=False):\n l1 = tf.keras.losses.SparseCategoricalCrossentropy()(ytrue, ypred)\n\n ypred_a = tf.math.argmax(ypred, axis=-1)\n t_cols = tf.equal(tf.reduce_sum(ypred_a, axis=1), 45)\n t_rows = tf.equal(tf.reduce_sum(ypred_a, axis=2), 45)\n\n l2 = 1.0 - tf.reduce_mean(tf.cast(t_cols, dtype=tf.float32))\n l3 = 1.0 - tf.reduce_mean(tf.cast(t_rows, dtype=tf.float32))\n return l1+l2+l3\n\n\ndef data_generator(x,y):\n for i in range(x.shape[0]):\n yield x[i], y[i]\n\n\ndef make_batches(ds, buffersize, batchsize):\n return ds.cache().shuffle(buffersize).batch(batchsize).prefetch(tf.data.AUTOTUNE)\n\n\nclass CnnLayer(tf.keras.layers.Layer):\n def __init__(self, filter_size, kernel_size, dropout_r=0.1, activation='relu', padding='same'):\n super(CnnLayer, self).__init__()\n self.conv = Conv2D(filter_size, kernel_size=(kernel_size,kernel_size), activation=activation, padding=padding)\n self.batchnorm = BatchNormalization()\n self.dropout = Dropout(dropout_r)\n\n def call(self, inputs, training, **kwargs):\n x = self.conv(inputs)\n x = self.batchnorm(x)\n return self.dropout(x, training=training)\n\n\nclass CnnLayer2(tf.keras.layers.Layer):\n def __init__(self, filter_size, kernel_size, dropout_r=0.1, activation=tf.nn.relu, padding='same'):\n super(CnnLayer2, self).__init__()\n self.act_func = activation\n self.conv = Conv2D(filter_size, kernel_size=(kernel_size,kernel_size), padding=padding)\n self.batchnorm = BatchNormalization()\n self.dropout = Dropout(dropout_r)\n self.conv2 = Conv2D(filter_size, kernel_size=(kernel_size, kernel_size), padding=padding)\n self.batchnorm2 = BatchNormalization()\n # self.dropout2 = Dropout(dropout_r)\n self.conv3 = Conv2D(filter_size, kernel_size=(1, 1))\n # self.dropout3 = Dropout(dropout_r)\n\n def call(self, inputs, training, **kwargs):\n x = self.conv(inputs)\n x = self.batchnorm(x)\n x = self.act_func(x)\n x = self.dropout(x, training=training)\n x = self.conv2(x)\n x = self.batchnorm2(x)\n # x = self.dropout2(x, training=training)\n xx = self.conv3(inputs)\n x += xx\n return self.act_func(x)\n\n\nclass SudokuSolver(tf.keras.Model):\n def __init__(self, input_shape=(9,9,1), outsize=9, nb_convlayers=10, filter_size=256, kernel=3):\n super(SudokuSolver, self).__init__()\n self.num_cnn_layer = nb_convlayers\n self.in_layer = Conv2D(filter_size, kernel_size=(kernel, kernel), input_shape=input_shape,\n activation='relu', padding='same')\n self.in_batchnorm = BatchNormalization()\n self.in_dropout = Dropout(0.1)\n\n self.cnnlayers = [CnnLayer(filter_size, kernel) for _ in range(nb_convlayers)]\n self.last_layer = Conv2D(outsize, kernel_size=(1, 1), activation='softmax')\n\n def call(self, inputs, training=None, mask=None):\n inputs = tf.cast(inputs, dtype=tf.float32)\n x = self.in_layer(inputs)\n x = self.in_batchnorm(x)\n x = self.act_func(x)\n # x = self.in_dropout(x, training=training)\n for l in range(0, self.num_cnn_layer, 2):\n x = self.cnnlayers[l](x)\n x = self.cnnlayers[l+1](x)\n x = tf.keras.layers.concatenate([x, inputs], axis=-1)\n y = self.last_layer(x)\n return y\n\n\nclass SudokuSolver2(tf.keras.Model):\n def __init__(self, input_shape=(9,9,1), outsize=9, nb_convlayers=7, filter_size=256, kernel=3):\n super(SudokuSolver2, self).__init__()\n self.num_cnn_layer = nb_convlayers\n self.in_layer = Conv2D(filter_size, kernel_size=(kernel, kernel), input_shape=input_shape, padding='same')\n self.act_func = tf.nn.relu\n self.in_batchnorm = BatchNormalization()\n # self.in_dropout = Dropout(0.1)\n\n self.cnnlayers = [CnnLayer2(filter_size, kernel) for _ in range(nb_convlayers)]\n self.last_layer = Conv2D(outsize, kernel_size=(1, 1), activation='softmax')\n\n def call(self, inputs, training=None, mask=None):\n inputs = tf.cast(inputs, dtype=tf.float32)\n n_m = tf.equal(inputs, 0.0)\n x = self.in_layer(inputs)\n x = self.in_batchnorm(x)\n x = self.act_func(x)\n # x = self.in_dropout(x, training=training)\n for l in range(0, self.num_cnn_layer):\n x = self.cnnlayers[l](x, training)\n x = (inputs * tf.cast(tf.math.logical_not(n_m), dtype=tf.float32) + x * tf.cast(n_m, dtype=tf.float32))\n y = self.last_layer(x)\n return y\n\n\nphysical_devices = tf.config.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\n\nepochs = 50\nbatch_size = 64\n\nx_all = np.load('x_all.npy', allow_pickle=True)\ny_all = np.load('y_all9.npy', allow_pickle=True)\n\nx_t_v, x_test, y_t_v, y_test = train_test_split(x_all, y_all, test_size=0.2, random_state=42)\nx_train, x_val, y_train, y_val = train_test_split(x_t_v, y_t_v, test_size=0.1, random_state=42)\nprint(x_train.shape)\nprint(y_train.shape)\n\ntrain_dataset = tf.data.Dataset.from_generator(data_generator, args=(x_train, y_train),\n output_signature=(tf.TensorSpec(shape=(9,9,1), dtype=tf.int64),\n tf.TensorSpec(shape=(9,9,1), dtype=tf.float32)))\n\nval_dataset = tf.data.Dataset.from_generator(data_generator, args=(x_val, y_val),\n output_signature=(tf.TensorSpec(shape=(9,9,1), dtype=tf.int64),\n tf.TensorSpec(shape=(9,9,1), dtype=tf.float32)))\n\ntrain_batches = make_batches(train_dataset, 20000, batch_size)\nval_batches = make_batches(val_dataset, 20000, 2000)\n\n\n\n###########\n# metrics #\n###########\n\ntrain_loss = tf.keras.metrics.Mean('train_loss', dtype=tf.float32)\ntrain_accuracy_grid = tf.keras.metrics.Mean('train_correct_grid', dtype=tf.float32)\ntrain_accuracy_all = tf.keras.metrics.Mean('train_accuracy', dtype=tf.float32)\n\nval_loss = tf.keras.metrics.Mean('val_loss', dtype=tf.float32)\nval_accuracy_grid = tf.keras.metrics.Mean('val_correct_grid', dtype=tf.float32)\nval_accuracy_all = tf.keras.metrics.Mean('val_accuracy', dtype=tf.float32)\n\nlog_dir_train = \"logs/solver/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\") + '/train'\nlog_dir_val = \"logs/solver/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\") + '/validation'\nsummary_writer_train = tf.summary.create_file_writer(log_dir_train)\nsummary_writer_validation = tf.summary.create_file_writer(log_dir_val)\n\ncheckpoint_filepath = 'models/model_'+datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")+'/'\n\nmodel = SudokuSolver2()\noptimizer = tf.keras.optimizers.Adam()\n# loss_object = tf.keras.losses.SparseCategoricalCrossentropy()\n\nfor epoch in range(epochs):\n for (batch, (x, y)) in enumerate(train_batches):\n with tf.GradientTape() as tape:\n predictions = model(x, training=True)\n loss = sudoku_loss(y, predictions)\n grads = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n\n train_loss(loss)\n grid_acc = correct_grid(y, predictions)\n full_acc = sudoku_acc(y, predictions)\n train_accuracy_grid(grid_acc)\n train_accuracy_all(full_acc)\n if batch % 1000 == 0:\n template = 'Epoch {}, Batch {}, Loss: {}, train_correct_grid: {}, train_accuracy: {}, val_loss: {}, val_correct_grid: {}, val_accuracy: {}'\n print(template.format(epoch + 1,\n batch,\n train_loss.result(),\n train_accuracy_grid.result() * 100,\n train_accuracy_all.result() * 100,\n val_loss.result(),\n val_accuracy_grid.result() * 100,\n val_accuracy_all.result() * 100))\n\n with summary_writer_train.as_default():\n tf.summary.scalar('epoch_loss', train_loss.result(), step=epoch)\n tf.summary.scalar('epoch_correct_grid', train_accuracy_grid.result(), step=epoch)\n tf.summary.scalar('epoch_sudoku_acc', train_accuracy_all.result(), step=epoch)\n\n for (x, y) in val_batches:\n predictions = model(x)\n loss = sudoku_loss(y, predictions)\n val_loss(loss)\n grid_acc = correct_grid(y, predictions)\n full_acc = sudoku_acc(y, predictions)\n val_accuracy_grid(grid_acc)\n val_accuracy_all(full_acc)\n\n with summary_writer_validation.as_default():\n tf.summary.scalar('epoch_loss', val_loss.result(), step=epoch)\n tf.summary.scalar('epoch_correct_grid', val_accuracy_grid.result(), step=epoch)\n tf.summary.scalar('epoch_sudoku_acc', val_accuracy_all.result(), step=epoch)\n\n template = 'Epoch {}, Loss: {}, train_correct_grid: {}, train_accuracy: {}, val_loss: {}, val_correct_grid: {}, val_accuracy: {}'\n print (template.format(epoch+1,\n train_loss.result(),\n train_accuracy_grid.result() * 100,\n train_accuracy_all.result() * 100,\n val_loss.result(),\n val_accuracy_grid.result()*100,\n val_accuracy_all.result()*100))\n model.save_weights(checkpoint_filepath+\"e_\"+str(epoch))\n # Reset metrics every epoch\n train_loss.reset_states()\n val_loss.reset_states()\n train_accuracy_grid.reset_states()\n train_accuracy_all.reset_states()\n val_accuracy_grid.reset_states()\n val_accuracy_all.reset_states()\n\n\n# model = SudokuSolver2()\n# model.compile(optimizer='adam',\n# loss='sparse_categorical_crossentropy',\n# metrics=[sudoku_acc, correct_grid])\n#\n#\n# log_dir = \"logs/solver/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n# tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)\n#\n# checkpoint_filepath = 'models/model_'+datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")+'/e-{epoch:02d}-{val_correct_grid:.2f}'\n# model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n# filepath=checkpoint_filepath,\n# save_weights_only=False,\n# monitor='val_correct_grid',\n# save_best_only=False)\n#\n# x_all = np.load('x_all.npy', allow_pickle=True)\n# y_all = np.load('y_all9.npy', allow_pickle=True)\n#\n# x_t_v, x_test, y_t_v, y_test = train_test_split(x_all, y_all, test_size=0.2, random_state=42)\n# x_train, x_val, y_train, y_val = train_test_split(x_t_v, y_t_v, test_size=0.1, random_state=42)\n# print(x_train.shape)\n# print(y_train.shape)\n# history = model.fit(x_train, y_train, epochs=50, batch_size=64, validation_data=(x_val, y_val),\n# callbacks=[tensorboard_callback, model_checkpoint_callback])\n\n\n","repo_name":"RichaMax/sudoku-cnn-solver","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":11823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8623767287","text":"# Функция может иметь произвольное количество аргументов. После всех\n# позиционных параметров функции или вместо них (но перед теми, которые\n# предполагается использовать как именованные) в её сигнатуре можно\n# указать специальный аргумент с символом * перед именем. Тогда\n# оставшиеся фактические параметры сохраняются в кортеже с этим именем.\n\n\ndef multiply(*numbers):\n result = 1\n for number in numbers:\n result *= number\n return result\n\n\nprint(multiply(2, 3))\nprint(multiply(1, 9, 7, 8))\n\n\n# Также существует и обратная возможность. Если при вызове функции\n# перед именем итерабельного объекта поставить символ *, то его элементы\n# распаковываются в позиционные аргументы.\n\n\ndef print_person(name, age, address):\n print(name, 'is', age, 'years old and lives at', address)\n\n\ndata = [\n ('John', 23, '18 Spring Lane'),\n ('Kate', 18, '20 Victory Str'),\n ('Vasiliy', 20, '323 Green Ave'),\n]\n\nfor person in data:\n print_person(*person)\n","repo_name":"syurskyi/Python_Topics","sub_path":"020_sequences/examples/ITVDN Python Essential 2016/19-unpacking_argument_list.py","file_name":"19-unpacking_argument_list.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"13208756616","text":"from PyFlow.UI import RESOURCES_DIR\nfrom PyFlow.UI.Canvas.UINodeBase import UINodeBase\nfrom PyFlow.UI.Canvas.UICommon import NodeActionButtonInfo\n\n\nclass UISequenceNode(UINodeBase):\n def __init__(self, raw_node):\n super(UISequenceNode, self).__init__(raw_node)\n actionAddOut = self._menu.addAction(\"Add out pin\")\n actionAddOut.setData(NodeActionButtonInfo(RESOURCES_DIR + \"/pin.svg\"))\n actionAddOut.setToolTip(\"Adds output execution pin\")\n actionAddOut.triggered.connect(self.onAddOutPin)\n\n def onPinWasKilled(self, uiPin):\n index = 1\n uiPin.OnPinDeleted.disconnect(self.onPinWasKilled)\n pins = list(self.UIoutputs.values())\n pins.sort(key=lambda x: int(x._rawPin.name))\n for outPin in pins:\n outPin.setName(str(index), True)\n outPin.setDisplayName(\"Then {0}\".format(index))\n index += 1\n\n def postCreate(self, jsonTemplate=None):\n super(UISequenceNode, self).postCreate(jsonTemplate)\n for outPin in self.UIoutputs.values():\n outPin.setDisplayName(\"Then {0}\".format(outPin._rawPin.name))\n outPin.OnPinDeleted.connect(self.onPinWasKilled)\n\n def onAddOutPin(self):\n rawPin = self._rawNode.createOutputPin()\n uiPin = self._createUIPinWrapper(rawPin)\n uiPin.OnPinDeleted.connect(self.onPinWasKilled)\n uiPin.setDisplayName(\"Then {0}\".format(rawPin.name))\n return uiPin\n","repo_name":"wonderworks-software/PyFlow","sub_path":"PyFlow/Packages/PyFlowBase/UI/UISequenceNode.py","file_name":"UISequenceNode.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":2099,"dataset":"github-code","pt":"52"} +{"seq_id":"17864474122","text":"from tkinter import *\nimport anime_data\n\n\nclass AnimeGraphic:\n\n def __init__(self):\n self.submit_button = None\n self.submit_box = None\n self.name = str\n self.banner = None\n self.screen = Tk()\n\n def app(self):\n self.screen.config(width=1280, height=720)\n self.submit_button = Button(text=\"Submit\", width=20 , command=self.lable)\n self.submit_box = Entry()\n self.submit_box.place(x=610, y=300, width=300)\n self.submit_button.place(x=640, y=360)\n self.screen.mainloop()\n return self.submit_box\n\n def lable(self):\n self.banner = Label(text=self.submit_box.get(), width=30)\n self.banner.place(y=30, x=600)\n self.name = self.submit_box.get()\n print(self.name)\n print(anime_data.anime(self.name))\n\n\n\n\n","repo_name":"nanashi042/Anime_Bot","sub_path":"anime_graphics.py","file_name":"anime_graphics.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19314056026","text":"import os\nimport pathlib\nimport pickle\n\nimport distrax\nfrom jax import lax\nfrom jax import numpy as jnp\nfrom jax.scipy.special import erf\n\n\ndef sample_timeseries(seed, y0, alpha_min, alpha_max, epsilon_max, len_timeseries=200):\n a = distrax.Uniform(alpha_min, alpha_max).sample(\n seed=seed, sample_shape=(len_timeseries,)\n )\n noise = distrax.Uniform(0.0, epsilon_max).sample(\n seed=seed, sample_shape=(len_timeseries,)\n )\n\n def _fn(fs, arrays):\n alpha, epsilon = arrays\n f, pn = fs\n f = babcock_leighton_fn(pn)\n pn = babcock_leighton(pn, alpha, epsilon)\n return (f, pn), (f, pn)\n\n _, (f, y) = lax.scan(_fn, (y0, y0), (a, noise))\n return f.T, y.T, a.T, noise.T\n\n\ndef babcock_leighton_fn(p, b_1=0.6, w_1=0.2, b_2=1.0, w_2=0.8):\n f = 0.5 * (1.0 + erf((p - b_1) / w_1)) * (1.0 - erf((p - b_2) / w_2))\n return f\n\n\ndef babcock_leighton(p, alpha, epsilon):\n p = alpha * babcock_leighton_fn(p) * p + epsilon\n return p\n\n\nclass solar_dynamo_model:\n \"\"\"Implements Eqn 2 and 3 of\n FLUCTUATIONS IN BABCOCK-LEIGHTON DYNAMOS. II. REVISITING THE GNEVYSHEV-OHL RULE\n https://iopscience.iop.org/article/10.1086/511177/pdf\n\n and Eqn 13 of https://arxiv.org/abs/2201.12059\n \"\"\"\n\n def __new__(cls, config):\n def _data_fn(seed):\n \"\"\"\n Data has been created using (seed=42):\n\n y0 = 1.0\n alpha1 = 1.11\n alpha2 = alpha1 + 0.15\n epsilon_max = 0.08\n\n f, y, alpha, noise = sample_timeseries(\n seed, y0, alpha1, alpha2, epsilon_max, 200\n )\n return f, y, alpha, noise\n \"\"\"\n\n dir = pathlib.Path(__file__).parent.resolve()\n fl = os.path.join(dir, \"solar_dynamo_observation.pkl\")\n with open(fl, \"rb\") as handle:\n data = pickle.load(handle)\n return data[\"y\"]\n\n def _prior_fns():\n p = distrax.Independent(\n distrax.Uniform(\n jnp.array([0.9, 0.05, 0.02]), jnp.array([1.4, 0.25, 0.15])\n ),\n 1,\n )\n return p.sample, p.log_prob\n\n def _simulator_fn(seed, theta, len_timeseries=200):\n orig_shape = theta.shape\n if theta.ndim == 2:\n theta = theta[None, :, :]\n\n alpha_min = theta[..., 0]\n alpha_max = alpha_min + theta[..., 1]\n epsilon_max = theta[..., 2]\n y0 = jnp.ones(theta.shape[:-1])\n\n _, y, _, _ = sample_timeseries(\n seed, y0, alpha_min, alpha_max, epsilon_max, len_timeseries\n )\n\n y = jnp.swapaxes(y, 1, 0)\n if len(orig_shape) == 2:\n y = y.reshape((*orig_shape[:1], len_timeseries))\n return y\n\n return _data_fn, _prior_fns, _simulator_fn, None, None\n","repo_name":"dirmeier/ssnl","sub_path":"data/solar_dynamo.py","file_name":"solar_dynamo.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1482928346","text":"from opentrons import protocol_api\n\nmetadata = {\n 'apiLevel': '2.10',\n 'protocolName': 'Prepare immunostained hMSC cells to visualize lysosomes',\n 'author': 'Your Name',\n 'description': 'Automated preparation of immunostained hMSC cells to visualize lysosomes',\n}\n\ndef run(protocol: protocol_api.ProtocolContext):\n # Labware\n plate_6_well = protocol.load_labware('corning_6_wellplate_16.8ml_flat', '1')\n tiprack_300 = protocol.load_labware('opentrons_96_tiprack_300ul', '2')\n \n # Pipettes\n p300 = protocol.load_instrument('p300_single_gen2', 'right', tip_racks=[tiprack_300])\n \n # Protocol\n for i in range(1, 7):\n well = plate_6_well.wells_by_name()[f\"A{i}\"]\n p300.pick_up_tip()\n # Add your reagents and other steps here as needed\n p300.return_tip()\n","repo_name":"labauto/Inagaki_2023_GPT4OT2","sub_path":"question_and_answer/tmp/tmp_7e4ed1c6-1edd-43a8-8559-891fd25a0eb0.py","file_name":"tmp_7e4ed1c6-1edd-43a8-8559-891fd25a0eb0.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"38265630670","text":"from numpy import add\nfrom optimix import Function\n\n\nclass SumCov(Function):\n \"\"\"\n Sum of covariance functions, K = K₀ + K₁ + ⋯.\n\n Example\n -------\n\n .. doctest::\n\n >>> from glimix_core.cov import LinearCov, SumCov\n >>> from numpy.random import RandomState\n >>>\n >>> random = RandomState(0)\n >>> cov_left = LinearCov(random.randn(4, 20))\n >>> cov_right = LinearCov(random.randn(4, 15))\n >>> cov_left.scale = 0.5\n >>>\n >>> cov = SumCov([cov_left, cov_right])\n >>> cov_left.name = \"A\"\n >>> cov_right.name = \"B\"\n >>> cov.name = \"A+B\"\n >>> print(cov)\n SumCov(covariances=...): A+B\n LinearCov(): A\n scale: 0.5\n LinearCov(): B\n scale: 1.0\n \"\"\"\n\n def __init__(self, covariances):\n \"\"\"\n Constructor.\n\n Parameters\n ----------\n covariances : list\n List of covariance functions.\n \"\"\"\n self._covariances = [c for c in covariances]\n Function.__init__(self, \"SumCov\", composite=self._covariances)\n\n def value(self):\n r\"\"\"\n Sum of covariance matrices.\n\n Returns\n -------\n K : ndarray\n K₀ + K₁ + ⋯\n \"\"\"\n return add.reduce([cov.value() for cov in self._covariances])\n\n def gradient(self):\n \"\"\"\n Sum of covariance function derivatives.\n\n Returns\n -------\n dict\n ∂K₀ + ∂K₁ + ⋯\n \"\"\"\n grad = {}\n for i, f in enumerate(self._covariances):\n for varname, g in f.gradient().items():\n grad[f\"{self._name}[{i}].{varname}\"] = g\n return grad\n\n def __str__(self):\n tname = type(self).__name__\n msg = \"{}(covariances=...)\".format(tname)\n if self.name is not None:\n msg += \": {}\".format(self.name)\n for c in self._covariances:\n spl = str(c).split(\"\\n\")\n msg = msg + \"\\n\" + \"\\n\".join([\" \" + s for s in spl])\n return msg\n","repo_name":"limix/glimix-core","sub_path":"glimix_core/cov/_sum.py","file_name":"_sum.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"24428585306","text":"import tkinter as tk\r\n\r\nclass TicTacToe:\r\n def __init__(self):\r\n self.window = tk.Tk()\r\n self.window.title(\"Tic Tac Toe\")\r\n\r\n self.current_player = \"X\"\r\n self.board = [[\"\", \"\", \"\"], [\"\", \"\", \"\"], [\"\", \"\", \"\"]]\r\n\r\n self.buttons = []\r\n for i in range(3):\r\n row = []\r\n for j in range(3):\r\n button = tk.Button(self.window, text=\"\", width=10, height=5,\r\n command=lambda i=i, j=j: self.button_click(i, j))\r\n button.grid(row=i, column=j)\r\n row.append(button)\r\n self.buttons.append(row)\r\n\r\n self.label = tk.Label(self.window, text=\"Player X's turn\", font=(\"Arial\", 16))\r\n self.label.grid(row=3, column=0, columnspan=3)\r\n\r\n def button_click(self, i, j):\r\n if self.board[i][j] == \"\":\r\n self.board[i][j] = self.current_player\r\n self.buttons[i][j].config(text=self.current_player)\r\n\r\n winner = self.check_winner()\r\n if winner is not None:\r\n self.label.config(text=f\"Player {winner} wins!\")\r\n for i in range(3):\r\n for j in range(3):\r\n self.buttons[i][j].config(state=tk.DISABLED)\r\n elif self.check_tie():\r\n self.label.config(text=\"It's a tie!\")\r\n else:\r\n self.current_player = \"O\" if self.current_player == \"X\" else \"X\"\r\n self.label.config(text=f\"Player {self.current_player}'s turn\")\r\n\r\n def check_winner(self):\r\n for i in range(3):\r\n if self.board[i][0] == self.board[i][1] == self.board[i][2] != \"\":\r\n return self.board[i][0]\r\n if self.board[0][i] == self.board[1][i] == self.board[2][i] != \"\":\r\n return self.board[0][i]\r\n if self.board[0][0] == self.board[1][1] == self.board[2][2] != \"\":\r\n return self.board[0][0]\r\n if self.board[0][2] == self.board[1][1] == self.board[2][0] != \"\":\r\n return self.board[0][2]\r\n return None\r\n\r\n def check_tie(self):\r\n for i in range(3):\r\n for j in range(3):\r\n if self.board[i][j] == \"\":\r\n return False\r\n return True\r\n\r\n def run(self):\r\n self.window.mainloop()\r\n\r\nif __name__ == '__main__':\r\n game = TicTacToe()\r\n game.run()\r\n","repo_name":"Jugraj2021/Tic-Tac-Toe","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"19001348999","text":"#Ask the user for the price of a child and an adult meal and store these values properly into variables as floating point numbers.\nchild_meal_price = float(input(\"what is The price of a child's meal? $\"))\nadult_meal_price = float(input(\"What is The price of an adult's meal? $\"))\n\n#Ask the user for the number of adults and children and store these values properly into variables as integers.\nnumber_of_children = int(input(\"How many children are there? \"))\nnumber_of_adults = int(input(\"How many adults are there? \"))\n\n#Ask the user for the sales tax rate and store the value properly as a floating point number.\nsales_tax_rate = float(input(\"What is the sales tax rate? %\"))\n\n\"\"\"Extra creativity\n\n the price of desert for everyone is same price\n multuplied by the total number of Adult added to that of Children\n\"\"\"\n\nprice_of_desert = float(input('what is the price of desert/person? $'))\n\ntip_percentage = float(input(\"how much tip would you like to offer? %\"))\n\n#calculate the total cost of child meal and the total cost of adult meal\nchild_meal_total = child_meal_price * number_of_children\nadult_meal_total = adult_meal_price * number_of_adults\n\ntotal_number_people = number_of_children + number_of_adults\n\ntotal_desert_amount = int(total_number_people) * price_of_desert\n\n'''=============end of extra creativity========'''\n\n#Compute and display the subtotal (don't worry about rounding to two decimals at this point).\nprint(\"\\n \\n\")\nsub_total = float(child_meal_total) + float(adult_meal_total)\nprint(f\"Subtotal ${sub_total:.2f}\")\n\n#Compute and display the sales tax.\nsales_tax = sub_total * sales_tax_rate / 100\nprint(\"Sales Tax ${:.2f}\".format(sales_tax))\n\n#The customer mught be willing to tip the waiter or waitress that served them for doing a good job so i decided to include that in the bill, even tho its optional\ntip_amount = sub_total * tip_percentage / 100\nprint(\"You tiped ${:.2f}\".format(tip_amount))\n\n'''They might have taken desert before theeal was ready'''\nprint(f\"Desert amount ${total_desert_amount}\")\n\n#Compute and display the total.\ntotal = sub_total + sales_tax + tip_amount + total_desert_amount\nprint(\"Grand total ${:.2f}\".format(total))\n\n#Ask the user for the payment amount and store the value properly as a floating point number.\npayment_amount = float(input('How much are you paying with? $'))\n\n#Compute and display the change.\nchange = payment_amount - total\nprint(\"Your change is ${:.2f}\".format(change))\n\n#Include a dollar sign ($) before each displayed value.✅\n\n#Display each value to two decimals.✅\n\n#Double check that the calculations are correct.✅\n\n#Show creativity and exceed the core requirements by adding additional features.✅\n\n#Use good style in your program, including variable names and whitespace.✅","repo_name":"narvas12/meal_price_clculator","sub_path":"Mile_stine_Ezechukwu_Emmanuel.py","file_name":"Mile_stine_Ezechukwu_Emmanuel.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27171319984","text":"\r\ndef most_frequent():\r\n\r\n str_1 = str(input(\"Please input a string: \"))\r\n d = dict()\r\n for key in str_1:\r\n if key not in d:\r\n d[key] = 1\r\n else:\r\n d[key] += 1\r\n return d\r\n\r\n print(\"Original Word:\", d)\r\n\r\n sorted_d = dict( sorted (d.items(), key=operator.itemgetter(1), reverse=True))\r\n\r\n print('Dictionary in descending order is: ', sorted_d)\r\n\r\nprint(most_frequent())","repo_name":"FuriousKiller49/My_Captain_Assignments","sub_path":"Python_Projects/most_frequent.py","file_name":"most_frequent.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26316134101","text":"import importlib\nimport re\nimport json\nimport tp24.internal as internal\nimport tp24.errors as errors\nimport tp24.tools as tools\n\nclass Colour:\n def __add__(self, other):\n other = internal.samemodel(self, other)\n sv, ov = internal.tuplify(self, other)\n new = tuple(a+b for a, b in zip(sv, ov))\n oc = internal.getclass(self, other)\n new = tuple(c if r>=len(oc.RANGE) or c<=oc.RANGE[r] else oc.RANGE[r] for r, c in enumerate(new)) \n if issubclass(type(self), ColourAlpha):\n new = list(new)\n new[-1] = 100 if new[-1] > 100 else 0 if new[-1] < 0 else new[-1]\n new = tuple(new)\n return oc(*new)\n\n def __sub__(self, other):\n other = internal.samemodel(self, other)\n sv, ov = internal.tuplify(self, other)\n new = tuple(a-b for a, b in zip(sv, ov))\n oc = internal.getclass(self, other)\n new = tuple(c if r>=len(oc.RANGE) or c>=0 else 0 for r, c in enumerate(new)) \n if issubclass(type(self), ColourAlpha):\n new = list(new)\n new[-1] = 100 if new[-1] > 100 else 0 if new[-1] < 0 else new[-1]\n new = tuple(new)\n return oc(*new)\n\n def __mul__(self, other):\n return tools.gradient(self, other)\n\n def __repr__(self):\n model = type(self).__name__\n vals = str(tuple(self))\n return model+vals\n \n def hexv(self, compress: bool=False):\n if not type(self).__name__.startswith(\"rgb\"):\n c = self.rgb()\n else:\n c = self\n\n r = \"#\"\n for i in tuple(c):\n n = hex(i).split('x')[1]\n if len(n) == 1: n = \"0\"+n\n r += n\n\n if compress:\n single = re.search(r\"^#(.)\\1{5}$\", r)\n triple = re.search(r\"^#(.)\\1(.)\\2(.)\\3(?:(.)\\4)?$\", r)\n if single:\n r = \"#\"+single.group(1)\n elif triple:\n r = \"#\"\n for i in triple.groups():\n if i != None: r += i\n\n return r\n\n @classmethod\n def from_web(cls, web: str):\n with open(\"tp24/model/web.json\", \"r\") as f:\n data = json.load(f)\n f.close()\n if not web in data.keys():\n raise ValueError(f\"{web} is not a valid web colour\")\n return cls.from_hex(\"#\"+data[web])\n\n @classmethod\n def from_hex(cls, hexc: str):\n c = re.search(r\"#(.+)\", hexc)\n if not c or not len(c.group(1)) in [1, 3, 4, 6, 8]:\n raise ValueError(f\"Hex {hexc} not a valid hex\")\n\n if len(c.group(1)) == 1:\n c = c.group(1)*6\n elif len(c.group(1)) in [3, 4]:\n c = ''.join([char*2 for char in c.group(1)])\n else:\n c = c.group(1)\n\n channels = tuple(c[i:i+2] for i in range(0, len(c), 2))\n channels = tuple(int('0x'+i, 16) for i in channels)\n\n import tp24.model.m_rgb as col_rgb\n\n if issubclass(cls, ColourAlpha):\n channels = list(channels)\n channels[3] *= 100/255\n channels[3] = round(channels[3])\n channels = tuple(channels)\n colour_rgb = col_rgb.rgba(*channels)\n else:\n colour_rgb = col_rgb.rgb(*channels)\n \n if not cls.__name__.startswith(\"rgb\"):\n classname = internal.unalpha(cls.__name__, cls)\n return getattr(colour_rgb, classname)()\n else:\n return colour_rgb\n\n def inverted(self):\n old = internal.unalpha(tuple(self), self)\n new = tuple(a-b for a, b in zip(self.RANGE, old))\n if issubclass(type(self), ColourAlpha): new = tuple(list(new)+[self.a])\n\n return type(self)(*new)\n\n def wheel(self, colours: int, degree: int=None):\n if degree == None:\n degree = 360/(colours+1)\n if degree < 0 or degree > 180:\n raise errors.RangeError(f\"Value of degree is {degree} but is not in range of 0 <= d <= 180\")\n elif colours <= 0:\n raise errors.RangeError(f\"Number of colours is {colours} but is not in range of c > 0\")\n\n if internal.unalpha(type(self).__name__, self) != \"hsl\":\n c = self.hsl()\n else:\n c = self\n\n import tp24.model.m_hsl as col_hsl\n cols = []\n for i in range(colours):\n if issubclass(type(c), ColourAlpha):\n cols.append(col_hsl.hsla(*tuple(c)))\n else:\n cols.append(col_hsl.hsl(*tuple(c)))\n\n for count, i in enumerate(cols):\n direction = count % 2\n if direction == 0: direction = -1\n multiplier = count // 2 + 1\n i.h += direction*degree*multiplier\n while i.h >= 360: i.h -= 360\n while i.h < 0: i.h += 360\n \n if internal.unalpha(type(self).__name__, self) != \"hsl\":\n #return getattr(t1, internal.unalpha(type(self).__name__, self))(), \\\n # getattr(t2, internal.unalpha(type(self).__name__, self))()\n return tuple(getattr(i, internal.unalpha(type(self).__name__, self))() for i in cols)\n else:\n return tuple(cols)\n\n def complementary(self):\n return self.wheel(1)[0]\n\n def triadic(self):\n return self.wheel(2)\n\n def tetradic(self):\n return self.wheel(3)\n\n def analogous(self, degree: int=30):\n return self.wheel(2, degree)\n\n def compound(self, degree: int=30):\n return self.complementary().analogous(degree)\n\n def add_alpha(self, va: int):\n if issubclass(type(self), ColourAlpha):\n return self\n classname = type(self).__name__+'a'\n modulename = type(self).__name__\n module = importlib.import_module(\"tp24.model.m_\"+modulename)\n vals = tuple(list(self)+[va])\n return getattr(module, classname)(*vals)\n \nclass ColourAlpha:\n def __init__(self, va: int):\n if va != None and not 0 <= va <= 100:\n raise errors.RangeError(f\"Value of A channel is {va} but is not in range of 0 <= a <= 100\")\n self.a = va\n\n def remove_alpha(self):\n classname = type(self).__name__[:-1]\n modulename = type(self).__name__[:-1]\n module = importlib.import_module(\"tp24.model.m_\"+modulename)\n vals = tuple(list(self)[:-1])\n return getattr(module, classname)(*vals)","repo_name":"iiiii7d/tp24","sub_path":"tp24/model/colour.py","file_name":"colour.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32905924024","text":"import random\nfrom typing import List, NamedTuple\n\nimport torch\nimport torch.utils.data as torch_data\n\n\nclass TripletOutOfBoundsError(Exception):\n \"\"\"\n Thrown whenever a triplet is wrongly indexed.\n \"\"\"\n\n\nclass Triplet(NamedTuple):\n head: int\n rel: int\n tail: int\n\n\n# Trans is a synonym for neighbour sometimes... Don't ask me why...\nclass Trans(NamedTuple):\n rel: int\n tail: int\n\n\n# Ontology represents the graph as a store of triplets by storing it as an adjacency list.\n# This provides some faster searches...\nclass Ontology:\n # _adj_list should be of len _entities\n _adj_list: List[List[Trans]]\n # _triplet_counts has the number of encountered triplets in _adj_list after a head is encountered.\n # It is cumulative.\n # _triplet_counts has a len of len(_entities) where the last item contains the total number of triplets.\n # It is used for faster indexing (O(log n) because of binary search) and triplet counting (O(1)).\n _triplet_counts: List[int]\n # _relations holds the names of the relations.\n _relations: List[str]\n # _entities holds the names of the entities.\n _entities: List[str]\n\n def __init__(\n self,\n adj_list: List[List[Trans]], \n relations: List[str],\n entities: List[str],\n ) -> None:\n self._adj_list = adj_list\n self._relations = relations\n self._entities = entities\n\n self._validate_adj_list()\n self._triplet_counts = self._count_triplets()\n\n def exists(self, triplet: Triplet) -> bool:\n if not self._entity_exists(triplet.head):\n return False\n\n for trans in self._adj_list[triplet.head]:\n if trans.rel == triplet.rel and trans.tail == triplet.tail:\n return True\n\n return False\n\n # TODO: Remove as it should be a deadcode.\n # Adding all triplets at once is faster because on each add we need\n # to update the total triplet counts for correct faster searching.\n def add_triplets(self, triplets: List[Triplet]) -> None:\n for _, triplet in enumerate(triplets):\n if not self._entity_exists(triplet.head):\n raise TripletOutOfBoundsError(f\"expected head to be between 0 and {len(self._entities) - 1} but was {triplet.head}\")\n\n if not self._entity_exists(triplet.tail):\n raise TripletOutOfBoundsError(f\"expected tail to be between 0 and {len(self._entities) - 1} but was {triplet.tail}\")\n\n if not self._rel_exists(triplet.rel):\n raise TripletOutOfBoundsError(f\"expected rel to be between 0 and {len(self._relations) - 1} but was {triplet.rel}\")\n\n self._adj_list[triplet.head].append(Trans(rel=triplet.rel, tail=triplet.tail))\n\n # Update the length of the graph\n self._triplet_counts = self._count_triplets()\n\n def triplets_len(self) -> int:\n return self._triplet_counts[len(self._triplet_counts) - 1]\n\n def get_triplet(self, triplet_idx: int) -> Triplet:\n head = self._head_for_triplet_at(triplet_idx)\n\n neigbours = self._adj_list[head]\n trans_idx = triplet_idx - (self._triplet_counts[head] - len(neigbours))\n\n trans = neigbours[trans_idx]\n \n return Triplet(head=head, rel=trans.rel, tail=trans.tail)\n\n def entities_len(self) -> int:\n return len(self._entities)\n\n def relations_len(self) -> int:\n return len(self._relations)\n\n def _validate_adj_list(self) -> None:\n if len(self._adj_list) != len(self._entities):\n raise Exception(f\"adj list length expected to be {len(self._entities)}, but was {len(self._adj_list)}\")\n\n def _count_triplets(self) -> List[int]:\n total_triplets = 0\n triplet_counts = []\n\n for head in range(len(self._adj_list)):\n total_triplets += len(self._adj_list[head])\n triplet_counts.append(total_triplets)\n\n return triplet_counts\n\n def _head_for_triplet_at(self, idx: int) -> int:\n left = 0\n right = len(self._triplet_counts) - 1\n \n if not self._triplet_exists(idx):\n raise TripletOutOfBoundsError(f\"Expected triplet idx {idx} to be between 0 and {self.triplets_len() - 1} inclusively.\")\n \n # Done because every item of _triplet_counts contains the number of\n # triplets for the given head.\n idx += 1\n \n while left < right:\n mid = left + (right - left) // 2\n\n # TODO: Fix this ugly bugger.\n if self._triplet_counts[mid] == idx and mid > 0 and self._triplet_counts[mid -1] < idx:\n return mid\n elif self._triplet_counts[mid] < idx:\n left = mid + 1\n else:\n right = mid\n \n # left can never become greater than right and we have a sparse representation where\n # an idx of a triplet would most probably not be found in an array but is a valid idx.\n return left\n\n def _entity_exists(self, entity: int) -> bool:\n return entity >= 0 and entity <= len(self._entities) - 1\n\n def _rel_exists(self, rel: int) -> bool:\n return rel >= 0 and rel <= len(self._relations) - 1\n \n def _triplet_exists(self, idx: int) -> bool:\n return idx >= 0 and idx <= self.triplets_len() - 1\n\n\ndef corrupted_counterparts(onto: Ontology, triplets: torch.IntTensor) -> List[Triplet]:\n corrupted_triplets = torch.clone(triplets)\n \n for _, triplet in enumerate(corrupted_triplets):\n _corrupt(onto, triplet)\n\n return corrupted_triplets\n\n\ndef _corrupt(onto: Ontology, triplet: torch.IntTensor) -> None:\n corrupted_entity_idx = random.randint(0, onto.entities_len() - 1)\n\n # To pick a triplet side toss the coin:\n # ---> Heads\n if random.randint(0, 1) == 0:\n triplet[0] = corrupted_entity_idx\n # ---> Tails\n else:\n triplet[2] = corrupted_entity_idx\n\n\nclass TripletDataset(torch_data.Dataset):\n _onto: Ontology\n\n def __init__(self, onto: Ontology) -> None:\n super().__init__()\n self._onto = onto\n\n def __len__(self) -> int:\n return self._onto.triplets_len()\n\n def __getitem__(self, idx):\n triplet = self._onto.get_triplet(idx)\n \n return torch.tensor([triplet.head, triplet.rel, triplet.tail])\n","repo_name":"storygraph/crabby","sub_path":"crabby/critic/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37855392220","text":"from pathlib import Path\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import linear_model\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ntrain = pd.read_csv(Path('./winequality-red.csv'))\r\ntrain.quality.describe()\r\n\r\n\r\nn_features = train.select_dtypes(include=[np.number])\r\nprint('The top 3 correlated features \\n')\r\ncorr=n_features.corr()\r\nprint(corr['quality'].sort_values(ascending=False)[:3], '\\n')\r\n\r\n\r\nnulls = pd.DataFrame(train.isnull().sum().sort_values(ascending=False))\r\nnulls.columns = ['Null Count']\r\nnulls.index.name = 'Feature'\r\nprint(nulls)\r\n\r\ndata = train.select_dtypes(include=[np.number]).interpolate().dropna()\r\nprint('The values without 0 sum',sum(data.isnull().sum() != 0))\r\n\r\n\r\ny = np.log(train.quality)\r\nX = data.drop(['quality'], axis=1)\r\n\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=.33)\r\nmodel = lr.fit(X_train, y_train)\r\n\r\n\r\n\r\nprint(\"R^2 is: \", model.score(X_test, y_test))\r\npredictions = model.predict(X_test)\r\n\r\nfrom sklearn.metrics import mean_squared_error\r\nprint('RMSE is: ', mean_squared_error(y_test, predictions))\r\n\r\n","repo_name":"karishma78/python","sub_path":"icp5/icp5 regression.py","file_name":"icp5 regression.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27795545325","text":"from flask import Flask, render_template, request\nimport joblib\n\napp = Flask(__name__)\n\nmodel = joblib.load('deploy_test.pkl')\n\n@app.route('/')\ndef Welcome():\n return render_template('base.html')\n\n@app.route('/predict', methods =['post'])\ndef predict():\n experience = request.form.get('experience')\n test_score = request.form.get('test_score')\n interview_score = request.form.get('interview_score')\n \n prediction = model.predict([[experience, test_score, interview_score]])\n\n return render_template('base.html', predicted_value = f'Employee salary will be ${round(prediction[0],2)}')\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Jamal2visit/heroku-salary-prediction","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19401623596","text":"import pytest\r\nimport numpy as np\r\nfrom stpredict import load_covid_data, load_earthquake_data\r\nfrom stpredict.preprocess import impute, temporal_scale_transform, target_modification, make_neighbouring_data, make_historical_data\r\nfrom stpredict.predict import split_data\r\n\r\ncovid_data = load_covid_data()\r\ncovid_column_identifier={'temporal id level 1':'date', 'temporal id level 2':'epidemic_week', 'spatial id level 1':'country', 'target':'covid_19_deaths',\r\n 'temporal covariates':['covid_19_deaths', 'covid_19_confirmed_cases', 'precipitation', 'temperature', 'retail_and_recreation_mobility_percent_change',\r\n 'grocery_and_pharmacy_mobility_percent_change', 'parks_mobility_percent_change', 'transit_stations_mobility_percent_change',\r\n 'workplaces_mobility_percent_change', 'residential_mobility_percent_change', 'percent_fully_vaccinated_people']}\r\ncovid_futuristic_covariates = {'retail_and_recreation_mobility_percent_change':[1,3],'transit_stations_mobility_percent_change':[1,3]}\r\n\r\n\r\nearthquake_data = load_earthquake_data()\r\nearthquake_column_identifier = {'temporal id level 1':'month ID', 'spatial id level 1':'sub-region ID', 'target':'occurrence', 'temporal covariates':['occurrence']}\r\n\r\n\r\nhistorical_data = make_historical_data(data = covid_data, forecast_horizon = 4, history_length = 3, column_identifier = covid_column_identifier, futuristic_covariates = covid_futuristic_covariates)\r\n\r\n\r\n\r\n@pytest.mark.parametrize(\"data,column_identifier\", [(covid_data, covid_column_identifier)])\r\ndef test_imputation(data, column_identifier):\r\n imputed_data = impute(data=data,column_identifier=column_identifier)\r\n assert len(imputed_data.dropna()) == len(imputed_data)\r\n\r\n@pytest.mark.parametrize(\"data,column_identifier,temporal_scale_level\", [(covid_data, covid_column_identifier,2)])\r\ndef test_temporal_scale_transform(data, column_identifier, temporal_scale_level):\r\n weekly_data = temporal_scale_transform(data, column_identifier, temporal_scale_level)\r\n assert len(weekly_data) == 122 # total number of epidemic weeks\r\n\r\n@pytest.mark.parametrize(\"data,target_mode,column_identifier\", [(covid_data,'cumulative', covid_column_identifier), (covid_data,'moving average', covid_column_identifier), \r\n (covid_data,'differential', covid_column_identifier)])\r\ndef test_target_modification(data,target_mode,column_identifier):\r\n modified_data = target_modification(data = data,target_mode = target_mode,column_identifier = column_identifier)\r\n target_name = column_identifier['target']\r\n if target_mode == 'cumulative':\r\n assert modified_data['target'].iloc[-1] == data[target_name].sum()\r\n if target_mode == 'moving average':\r\n assert modified_data['target'].iloc[-1] == data[target_name].iloc[-7:].mean()\r\n if target_mode == 'differential':\r\n assert modified_data['target'].iloc[-1] == data[target_name].iloc[-1] - data[target_name].iloc[-2]\r\n\r\n@pytest.mark.parametrize(\"data,forecast_horizon,history_length,column_identifier,futuristic_covariates\", [(covid_data,4,3,covid_column_identifier,covid_futuristic_covariates)])\r\ndef test_make_historical_data(data, forecast_horizon, history_length, column_identifier, futuristic_covariates):\r\n target_name = column_identifier['target']\r\n historical_data = make_historical_data(data, forecast_horizon, history_length, column_identifier, futuristic_covariates)\r\n columns = ['temporal id', 'spatial id', 'Target']\r\n for covar in column_identifier['temporal covariates']:\r\n for t in range(history_length):\r\n if t == 0:\r\n columns.append(covar+' t')\r\n else:\r\n columns.append(covar+' t-'+str(t))\r\n for key, value in futuristic_covariates.items():\r\n for t in range(value[0], value[1]+1):\r\n columns.append(key+' t+'+str(t))\r\n assert set(columns) - set(historical_data.columns) == set(historical_data.columns) - set(columns) == set()\r\n target_values = list(historical_data['Target'].dropna()) # values of the target at t + forecast horizon\r\n feature_values = list(historical_data[target_name+' t'][-len(target_values):]) # values of the target at t\r\n assert target_values == feature_values\r\n\r\n\r\n@pytest.mark.parametrize(\"data,column_identifier\", [(earthquake_data, earthquake_column_identifier)])\r\ndef test_make_neighbouring_data(data, column_identifier):\r\n neighbouring_data = make_neighbouring_data(data = data, column_identifier = column_identifier, number_of_layers = 2, \r\n neighbouring_matrix = np.array([[0,1,0,0,0,1,0,0,0],\r\n [1,0,0,1,0,1,0,0,0],\r\n [0,0,0,1,0,0,1,0,0],\r\n [0,1,1,0,1,0,0,1,0],\r\n [0,0,0,1,0,0,1,0,0],\r\n [1,1,0,0,0,0,0,0,1],\r\n [0,0,1,0,1,0,0,1,0],\r\n [0,0,0,1,0,0,1,0,0],\r\n [0,0,0,0,0,1,0,0,0]]))\r\n \r\n layer1_extracted_covariate_values = list(neighbouring_data.loc[neighbouring_data['sub-region ID']==1,'occurrence_l1'])\r\n layer1_neighbouring_units_average = list((np.array(neighbouring_data.loc[neighbouring_data['sub-region ID']==2,'occurrence'])+np.array(\r\n neighbouring_data.loc[neighbouring_data['sub-region ID']==6,'occurrence']))/2)\r\n layer2_extracted_covariate_values = list(neighbouring_data.loc[neighbouring_data['sub-region ID']==1,'occurrence_l2'])\r\n layer2_neighbouring_units_average = list((np.array(neighbouring_data.loc[neighbouring_data['sub-region ID']==4,'occurrence'])+np.array(\r\n neighbouring_data.loc[neighbouring_data['sub-region ID']==9,'occurrence']))/2)\r\n\r\n assert layer1_extracted_covariate_values == layer1_neighbouring_units_average\r\n assert layer2_extracted_covariate_values == layer2_neighbouring_units_average\r\n\r\n\r\n@pytest.mark.parametrize(\"data,splitting_type,instance_testing_size,instance_validation_size,instance_random_partitioning,fold_total_number,fold_number\", \r\n [(historical_data, 'instance', 0.2, 0.2, False, None, None), (historical_data, 'fold', 0.2, None, False, 3, 2)])\r\n\r\ndef test_split_data(data, splitting_type, instance_testing_size, instance_validation_size, instance_random_partitioning, fold_total_number, fold_number):\r\n\r\n number_of_spatial_units = 1 # only USA country\r\n forecast_horizon = 4\r\n training_data, validation_data, testing_data, gap_data = split_data(data, splitting_type, instance_testing_size, instance_validation_size, instance_random_partitioning, fold_total_number, fold_number, forecast_horizon)\r\n\r\n if splitting_type == 'instance':\r\n assert len(training_data) + len(validation_data) + len(testing_data) + len(gap_data) == len(data)\r\n assert training_data['temporal id'].max() < validation_data['temporal id'].min()\r\n if len(gap_data)>0:\r\n assert validation_data['temporal id'].max() < gap_data['temporal id'].min()\r\n assert gap_data['temporal id'].max() < testing_data['temporal id'].min()\r\n assert len(gap_data) == (forecast_horizon-1)*number_of_spatial_units\r\n \r\n if splitting_type == 'fold':\r\n assert len(training_data) + len(validation_data) == len(data)\r\n assert set(training_data['temporal id'].unique()).intersection(set(validation_data['temporal id'].unique())) == set()\r\n","repo_name":"network-and-Data-Science-IUT/stpredict","sub_path":"tests/test_preprocess.py","file_name":"test_preprocess.py","file_ext":"py","file_size_in_byte":7865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11574589775","text":"import random\nname=input(\"enter your name\")\nprint(\"HEY\",name,\"WELCOME TO OUR HANGMAN GAME\")\nIMAGES= ['''\n +---+\n | |\n |\n |\n |\n |\n =========''', '''\n +---+\n | |\n 0 |\n |\n |\n |\n =========''', '''\n +---+\n | |\n 0 |\n / |\n |\n |\n =========''', '''\n +---+\n | |\n 0 |\n /| |\n |\n |\n =========''', '''\n +---+\n | |\n 0 |\n /|\\ |\n |\n |\n =========''', '''\n +---+\n | |\n 0 |\n /|\\ |\n | |\n |\n =========''', '''\n +---+\n | |\n 0 |\n /|\\ |\n | |\n / |\n =========''', '''\n +---+\n | |\n 0 |\n /|\\ |\n | |\n / \\ |\n =========''', '''\n\t\n''']\ndef get_word():\n with open(\"hangman_word.txt\",'r') as data_file:\n for line in data_file:\n data = line.split()\n i=0\n empty=[]\n while i0:\n guess=input(\"please guess a letter:\")\n if len(guess)==1 and guess.isalpha():\n if guess in guess_list:\n print(\"you already gussed the word\",guess)\n else:\n guess_list.append(guess)\n if guess in secret_word:\n print(\"good job you guess the word\")\n for i in range(len(secret_word)):\n if secret_word[i]==guess:\n lenwordlist[i]=guess\n tem.append(guess)\n print(tem)\n print(\"YOUR GUESSING WORD=\",lenwordlist)\n print(\" \")\n if b==lenwordlist:\n print(\"you won\")\n break\n if guessmade==secret_word:\n print(\"*** CONGRATULATION YOU WON ****\")\n elif guess not in secret_word:\n print(\"OPPS! YOUR GUESS LETTER\",guess,\"NOT IN SECRET WORD AND YOU HAVE LOST ONE CHANSE\")\n turn=turn-1\n if turn==8:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[0])\n if turn==7:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[1])\n if turn==6:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[2])\n if turn==5:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[3])\n if turn==4:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[4])\n if turn==3:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[5])\n if turn==2:\n print(\"NOW YOU HAVE ONLY\",turn,\"ARE LEFT\")\n print(IMAGES[6])\n if turn==1:\n print(\"you loose The Game\")\n print(IMAGES[7])\n print(\"OPPS!, SOORY YOU ARE A LOOSER . TRY NEXT TIME\")\n break\n \n else:\n print(\"soory! it is not valid\",guess,\" PLEASE GUESS ONLY ONE LETTER\")\n a=a-1 \nhangman() \ndef play_again():\n while True:\n again=input(\"do you want to play again y/n***\")\n if again==\"y\":\n hangman()\n else:\n break\nplay_again()","repo_name":"Purinima21nov/hangman","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6005636195","text":"from random import randint, shuffle\nfrom sys import exit\n\n# Read the contestants from file\nwith open(\"contestants.txt\") as f:\n content = f.readlines()\n\n# Split into lists of 128\ntiers = [[], [], []]\nfor line in content:\n char, line = line.split(\" [\")\n source, rank = \"\", \"\"\n try:\n source, rank = line.split(\"] \")\n except ValueError:\n source, rank = line, \"\"\n triple = (char, source, rank)\n if \"32\" in rank or \"64\" in \"rank\" or \"MM\" in \"rank\":\n tiers[0].append(triple)\n elif \"128\" in rank or \"NEW\" in \"rank\":\n tiers[1].append(triple)\n elif \"FAIL\" in rank:\n tiers[2].append(triple)\n else:\n i = randint(0, 2)\n tiers[i].append(triple)\nwhile not (len(tiers[0]) == 128 and len(tiers[1]) == 128 and len(tiers[2]) == 128):\n maximal = tiers[0]\n minimal = tiers[2]\n if len(tiers[1]) > len(maximal):\n maximal = tiers[1]\n if len(tiers[2]) > len(maximal):\n maximal = tiers[2]\n if len(tiers[1]) < len(minimal):\n minimal = tiers[1]\n if len(tiers[0]) < len(minimal):\n minimal = tiers[0]\n while True:\n i = randint(0, len(maximal))\n try:\n rank = maximal[i][2]\n except IndexError:\n continue\n if len(rank) > 0:\n minimal.append(maximal.pop(i))\n break\n\n# Reorder tiers[0] so that:\n# * 2 of the top 32 won't appear in the same block of 4\n# * 2 of the top 64 won't appear in the same block of 2\ntop32 = []\ntop64 = []\nother = []\nfor char in tiers[0]:\n if \"32\" in char[2]:\n top32.append(char)\n elif \"64\" in char[2]:\n top64.append(char)\n else:\n other.append(char)\ntiers[0] = []\nwhile len(other) > 0:\n try:\n if len(top64) > 0:\n tiers[0].append(top64.pop())\n else:\n tiers[0].append(other.pop())\n if len(top32) > 0:\n tiers[0].append(top32.pop())\n else:\n tiers[0].append(other.pop())\n tiers[0].append(other.pop())\n if len(top64) > 0:\n tiers[0].append(top64.pop())\n else:\n tiers[0].append(other.pop())\n except IndexError:\n continue\n\n# Randomly reorder tiers[1] and tiers[2] so that:\n# * Characters from the same game won't appear in the same round\nshuffle(tiers[1])\nshuffle(tiers[2])\nfor i in range(128):\n if tiers[0][i][1] == tiers[1][i][1]:\n j = i\n while tiers[1][j][1] == tiers[0][i][1]:\n j = j + 1 % 128\n tiers[1][i], tiers[1][j] = tiers[1][j], tiers[1][i]\n if tiers[0][i][1] == tiers[2][i][1] or tiers[1][i][1] == tiers[2][i][1]:\n j = i\n while tiers[2][j][1] == tiers[2][i][1]:\n j = j + 1 % 128\n tiers[2][i], tiers[2][j] = tiers[2][j], tiers[2][i]\n\n# Print\nPERMS = ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0))\ndef printchar(j, k, i):\n char = tiers[PERMS[j][k]][i]\n return char[0] + \" - \" + char[1].split(\"]\")[0]\ns = \"\\tBRACKETS:\\n\\n\"\nfor i in range(128):\n if i % 16 == 0:\n s += \"\\n\\tBRACKET \" + str(i // 16) + \":\\n\"\n j = randint(0, 5)\n s += printchar(j, 0, i) + \"\\n\\t\" + printchar(j, 1, i) + \"\\n\\t\" + printchar(j, 2, i) + \"\\n\"\ns += \"\\n\\n\"\nwith open(\"brackets.txt\", \"a\") as f:\n f.write(s)\n","repo_name":"FFWiki/MM4","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26571221417","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 12 14:05:31 2017\n\n@author: jjacobir\n\"\"\"\nimport gc\nimport os\nimport pandas as pd\n#from dplython import (DplyFrame, X, diamonds, select, sift, sample_n,\n# sample_frac, head, arrange, mutate, group_by, summarize, DelayFunction)\nfrom pandas_ply import install_ply, X, sym_call\ninstall_ply(pd)\n#from datetime import datetime, timedelta\nfrom sklearn.model_selection import train_test_split\n#import numpy as np\nimport random\nimport xgboost as xgb \n#from matplotlib import pyplot\n\ngc.enable()\n\nos.getcwd()\nos.chdir(\"D:/Competencia/BBVA\")\n\n# Cargar Data\ndata_train_aux = pd.read_excel(\"01_Data/train_clientes.xlsx\")\ndata_train_req_aux = pd.read_excel(\"01_Data/train_requerimientos.xlsx\")\n\ndata_train_req_aux.head()\ntype(data_train_aux)\n\ndata_train_aux.groupby(\"ATTRITION\")[\"ID_CORRELATIVO\"].count()\n\n# Vista de la data\ndata_train_aux.describe().transpose()\ndata_train_aux.info()\ndata_train_aux.dtypes\n\n# % de missing \ndata_train_aux.isnull().sum()/len(data_train_aux)\ndata_train_req_aux.isnull().sum()/len(data_train_req_aux)\n\n# Crear variaable número de na's\ndata_train_aux[\"NRO_NA\"] = data_train_aux.isnull().sum(axis=1)\n\n# Crear dummies\ndata_train_dumm = pd.get_dummies(data_train_aux,\n columns = ['RANG_INGRESO','FLAG_LIMA_PROVINCIA','RANG_SDO_PASIVO_MENOS0','RANG_NRO_PRODUCTOS_MENOS0'], \n prefix = ['DUMM_RANG_INGRESO','DUMM_FLAG_LIMA_PROVINCIA','DUMM_RANG_SDO_PASIVO_MENOS0','DUMM_RANG_NRO_PRODUCTOS_MENOS0']\n )\n\ndata_train_dumm = data_train_dumm.set_index('ID_CORRELATIVO')\n\n# Crear variables transaccionales\n\"\"\"\ndata_train_req_aux = DplyFrame(data_train_req_aux)\n\ndata_train_req_aux_ag = (data_train_req_aux >> \n group_by(X.ID_CORRELATIVO) >> \n summarize(REQ_INI_MES=X.CODMES.min(),\n REQ_ULT_MES=X.CODMES.max(),\n REQ_NUM_PROD = X.PRODUCTO_SERVICIO_2.nunique(),\n REQ_NUM_SUBMOT = X.SUBMOTIVO_2.nunique(),\n #REQ_NUM_REC = sum(X.TIPO_REQUERIMIENTO2 == 'Reclamo')#,\n #REQ_NUM_SOL = sum(TIPO_REQUERIMIENTO2 == \"Solicitud\"),\n #REQ_NUM_PROC_TOT = sum(DICTAMEN == \"PROCEDE TOTAL\"),\n #REQ_NUM_PROC_PAR = sum(DICTAMEN == \"PROCEDE PARCIAL\"),\n #REQ_NUM_PROC_NOP = sum(DICTAMEN == \"NO PROCEDE\"),\n REQ_NUM_TOT = X.CODMES.count()\n ) #>> head(10)\n)\n\"\"\"\n\ndata_train_req_aux_ag = (data_train_req_aux\n .groupby(['ID_CORRELATIVO'])\n .ply_select(REQ_INI_MES = X.CODMES.min(),\n REQ_ULT_MES = X.CODMES.max(),\n REQ_NUM_PROD = X.PRODUCTO_SERVICIO_2.nunique(),\n REQ_NUM_SUBMOT = X.SUBMOTIVO_2.nunique(),\n REQ_NUM_REC = bool([X.TIPO_REQUERIMIENTO2 == 'Solicitud']),\n REQ_NUM_TOT = X.CODMES.count())\n )#.head(20)\n\n\ndata_train_req_aux_ag = pd.DataFrame(data_train_req_aux_ag, \n index = data_train_req_aux_ag['ID_CORRELATIVO'],\n dtype = {'ID_CORRELATIVO':'int',\n 'REQ_INI_MES':'object',\n 'REQ_NUM_PROD':'int',\n 'REQ_NUM_SUBMOT':'int',\n 'REQ_NUM_TOT':'int',\n 'REQ_ULT_MES':'object'}\n )\n\n# Agregar variables de requerimientos\n\ndata_train_dumm .shape\ndata_train_req_aux_ag.shape\n\ndata_train_tot = pd.concat([data_train_dumm,data_train_req_aux_ag], axis=1, join='outer')\n\ndata_train_tot.isnull().sum()\n\n# filter\n(data_train_tot\n .ply_where(X.ID_CORRELATIVO == 3))\n\n# Crear data de entrenamiento y validación\nrandom.seed(123)\ntrain, val = train_test_split(data_train_tot, test_size=0.2)\n\n# Modelo Xgboost\n#y_train = train.pop('ATTRITION')\n#y_val = val.pop('ATTRITION')\n\ndtrain = xgb.DMatrix(data = train.drop(['CODMES','ATTRITION','REQ_ULT_MES','REQ_INI_MES'], axis = 1), label=train['ATTRITION'] )\ndval = xgb.DMatrix(data = val.drop(['CODMES','ATTRITION','REQ_ULT_MES','REQ_INI_MES'], axis = 1), label=val['ATTRITION'] )\n\nparam = {'max_depth':9, \n 'eta':0.06, \n 'silent':1, \n 'objective':'binary:logistic',\n 'eval_metric':'logloss',\n 'min_child_weight':10,\n 'booster': 'gbtree'\n }\nnum_round = 200\n\nwatchlist = [(dval, 'eval'), (dtrain, 'train')]\n\nrandom.seed(123)\nbst = xgb.train(param, \n dtrain, \n num_round,\n watchlist\n )\n\npd.DataFrame(bst.get_fscore().items(), columns=['feature','importance']).sort_values('importance', ascending=False)\n\n\nxgb.plot_importance(bst, max_num_features=30)\nshow()\n\n\n","repo_name":"JhonyJacobi/BBVA_Challenge_2017","sub_path":"01_bbva_train.py","file_name":"01_bbva_train.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40212762863","text":"# Load packages\nimport re\nimport pandas as pd\nimport numpy as np\n\n# Load selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# Chrome webdriver\ndriver = webdriver.Chrome('/Users/alexcheng/Downloads/chromedriver')\n\ndef get_per_game(url):\n \"\"\"\n takes in a specific player url and scrapes the career averages from the per game table.\n must use in conjunction with `get_pergame_cols` in order to sync the columns.\n \"\"\"\n driver.get(url)\n\n # share & more\n driver.find_element_by_xpath(\"\"\"//*[@id=\"all_per_game\"]/div[1]/div/ul/li[1]/span\"\"\").click()\n\n # get table as csv (for excel)\n WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable(\n (By.XPATH, \"\"\"//*[@id=\"all_per_game\"]/div[1]/div/ul/li[1]/div/ul/li[4]/button\"\"\"))).click()\n\n # table\n WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable(\n (By.CLASS_NAME, \"\"\"table_outer_container\"\"\")))\n\n # capture csv text\n per_game = driver.find_element_by_id(\"csv_per_game\")\n\n # data cleaning\n per_game = per_game.text.encode('ascii', 'ignore').split()\n\n for stats in per_game:\n if stats.startswith('Career'):\n per_game = re.findall('(\\d[\\d.,-]+)$', stats)[0]\n\n player_id = re.findall('(\\w+\\d)', url)\n\n per_game_list = [player_id[0]]\n for i in per_game.split(','):\n if i == '':\n per_game_list.append(0.0)\n else:\n i = float(i)\n per_game_list.append(i)\n\n return per_game_list\n\n\ndef get_100(url):\n \"\"\"\n takes in a specific player url and scrapes the career averages from the per-100 possessions table.\n must use in conjunction with `get_100_cols` in order to sync the columns.\n \"\"\"\n driver.get(url)\n driver.find_element_by_xpath(\"\"\"//*[@id=\"all_per_poss\"]/div[1]/div/ul/li[1]/span\"\"\").click()\n\n WebDriverWait(driver, 30).until(EC.element_to_be_clickable(\n (By.XPATH, \"\"\"//*[@id=\"all_per_poss\"]/div[1]/div/ul/li[1]/div/ul/li[4]/button\"\"\"))).click()\n\n WebDriverWait(driver, 30).until(EC.element_to_be_clickable(\n (By.CLASS_NAME, \"\"\"table_outer_container\"\"\")))\n\n # capture csv text\n all_per_poss = driver.find_element_by_id(\"csv_per_poss\")\n\n # data cleaning\n all_per_poss = all_per_poss.text.encode('ascii').split()\n\n for stats in all_per_poss:\n if stats.startswith('Career'):\n all_per_poss = re.findall('(\\d[\\d.,-]+)$', stats)[0]\n\n player_id = re.findall('(\\w+\\d)', url)\n\n all_per_poss_list = [player_id[0]]\n for i in all_per_poss.split(','):\n if i == '':\n all_per_poss_list.append(0.0)\n else:\n i = float(i)\n all_per_poss_list.append(i)\n\n del all_per_poss_list[25]\n return all_per_poss_list\n\ndef get_shooting(url):\n \"\"\"\n takes in a specific player url and scrapes the career averages from the shooting table.\n must use in conjunction with `get_shoot_cols` in order to sync the columns.\n \"\"\"\n driver.get(url)\n\n # share & more\n driver.find_element_by_xpath(\"\"\"//*[@id=\"all_shooting\"]/div[1]/div/ul/li[2]/span\"\"\").click()\n\n # get table as csv (for excel)\n WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable(\n (By.XPATH, \"\"\"//*[@id=\"all_shooting\"]/div[1]/div/ul/li[2]/div/ul/li[4]/button\"\"\"))).click()\n\n # table\n WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable(\n (By.CLASS_NAME, \"\"\"table_outer_container\"\"\")))\n\n # capture csv text\n shooting = driver.find_element_by_id(\"csv_shooting\")\n\n # data cleaning\n shooting = shooting.text.encode('ascii', 'ignore').split()\n\n for stats in shooting:\n if stats.startswith('Career'):\n shooting = re.findall('(\\d[\\d.,-]+)$', stats)[0]\n\n player_id = re.findall('(\\w+\\d)', url)\n\n shooting_list = [player_id[0]]\n for i in shooting.split(','):\n if i == '':\n shooting_list.append(0.0)\n else:\n i = float(i)\n shooting_list.append(i)\n\n return shooting_list\n\n\n\ndef get_advanced(url):\n \"\"\"\n takes in a specific player url and scrapes the career averages from the advanced table.\n must use in conjunction with `get_adv_cols` in order to sync the columns.\n \"\"\"\n driver.get(url)\n # scraping advanced table\n driver.find_element_by_xpath(\"\"\"//*[@id=\"all_advanced\"]/div[1]/div/ul/li[1]/span\"\"\").click()\n\n WebDriverWait(driver, 30).until(EC.element_to_be_clickable(\n (By.XPATH, \"\"\"//*[@id=\"all_advanced\"]/div[1]/div/ul/li[1]/div/ul/li[4]/button\"\"\"))).click()\n\n WebDriverWait(driver, 30).until(EC.element_to_be_clickable(\n (By.CLASS_NAME, \"\"\"table_outer_container\"\"\")))\n\n # capture csv text\n advanced = driver.find_element_by_id(\"csv_advanced\")\n\n # data cleaning\n advanced = advanced.text.encode('ascii').split()\n\n for stats in advanced:\n if stats.startswith('Career'):\n advanced = re.findall('(\\d[\\d.,-]+)$', stats)[0]\n\n player_id = re.findall('(\\w+\\d)', url)\n\n advanced_list = [player_id[0]]\n for i in advanced.split(','):\n if i == '':\n advanced_list.append(0.0)\n else:\n i = float(i)\n advanced_list.append(i)\n\n del advanced_list[15]\n del advanced_list[19]\n return advanced_list\n\n########################################################\n########################################################\n#################### Columns ###########################\n########################################################\n########################################################\n\n\ndef get_100_cols():\n points_poss_cols = ['Player_ID', \"GAMES\",\"GS\",\"MP_\",\"FG_100\",\"FGA_100\",\"FG%_100\",\"3P_100\",\"3PA_100\",\"3P%_100\",\"2P_100\",\"2PA_100\",\n \"2P%_100\",\"FT_100\",\"FTA_100\",\"FT%_100\",\"ORB_100\",\"DRB_100\",\"TRB_100\",\"AST_100\",\"STL_100\",\"BLK_100\",\n \"TOV_100\",\"PF_100\",\"PTS_100\",\"ORtg\",\"DRtg\"]\n return points_poss_cols\n\ndef get_shoot_cols():\n shooting_cols = ['Player_ID1','Games', 'Min_Played', 'FG%', 'AVG_DIST_FGA', '%FGA_2P', '%FGA_0-3ft',\n '%FGA_3-10ft','%FGA_10-16ft', '%FGA_16ft<3', '%FGA_3P', '2P%',\n '0-3_FG%', '3-10_FG%', '10-16_FG%', '16<3_FG%', '3P%', '%ASTd_2P',\n '%FGA_DUNK', 'DUNKS', '%ASTd_3P', '%_CORNER3PA', '3P%_CORNER3',\n 'HEAVE_ATT', 'HEAVE_MD']\n return shooting_cols\n\ndef get_adv_cols():\n advanced_cols = ['Player_ID2', 'Games_', 'Minutes_Played', 'PER', 'TS%', '3PAr', 'FTr', 'ORB%', 'DRB%', 'TRB%',\n 'AST%', 'STL%', 'BLK%', 'TOV%', 'USG%', 'OWS', 'DWS', 'WS',\n 'WS/48', 'OBPM', 'DPM', 'BPM', 'VORP']\n return advanced_cols\n\ndef get_pergame_cols():\n per_game_cols = ['Player_ID3', 'G', 'GS', 'MP', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%',\n '2P', '2PA', '2P%', 'eFG%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB',\n 'TRB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PTS']\n\n return per_game_cols\n","repo_name":"acheng1230/Web_Scraping_NBA_Data","sub_path":"lib/web_scrape.py","file_name":"web_scrape.py","file_ext":"py","file_size_in_byte":7249,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"3959059811","text":"# 게임 맵 최단거리\n# 2021-12-20\n\nfrom collections import deque\n\ndef solution(maps):\n dx = [1, 0, -1, 0]\n dy = [0, -1, 0, 1]\n r, c = len(maps), len(maps[0])\n\n graph = [[-1 for _ in range(c)] for _ in range(r)]\n graph[0][0] = 1\n q = deque()\n q.append([0, 0])\n\n while q:\n y, x = q.popleft()\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if 0 <= nx < c and 0 <= ny < r and maps[ny][nx] == 1:\n if graph[ny][nx] == -1:\n graph[ny][nx] = graph[y][x] + 1\n q.append([ny, nx])\n\n return graph[-1][-1]\n\nprint(solution([[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]]))","repo_name":"hybae430/Programmers","sub_path":"1844.py","file_name":"1844.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43209506256","text":"from flask import render_template, Response, json, send_file, request\nfrom sqlalchemy.exc import IntegrityError, DatabaseError\nfrom werkzeug.exceptions import BadRequest\n\nfrom ChangePop import app, user, product, bids, trade, commsg, notify, uploads, reports, payment, category\nfrom ChangePop.exeptions import JSONExceptionHandler, UserException, NotLoggedIn, UserBanned, ProductException\nfrom ChangePop.utils import send_mail\n\napp.register_blueprint(user.bp)\napp.register_blueprint(product.bp)\napp.register_blueprint(bids.bp)\napp.register_blueprint(trade.bp)\napp.register_blueprint(commsg.bp)\napp.register_blueprint(notify.bp)\napp.register_blueprint(uploads.bp)\napp.register_blueprint(reports.bp)\napp.register_blueprint(category.bp)\napp.register_blueprint(payment.bp)\n\n\n@app.route('/')\ndef show():\n return render_template('index.html')\n\n\n@app.route('/test_request') # pragma: no cover\ndef show_test():\n return render_template('test.html')\n\n\n@app.route('/test_login') # pragma: no cover\ndef show_test_login():\n return render_template('test_login.html')\n\n\n@app.route('/test_mail') # pragma: no cover\ndef test_mail():\n mail = request.args.get('mail')\n subject = \"Test\"\n text = \"Dear passenger 1, welcome to Mailjet! May the delivery force be with you!\"\n html = \"

Dear passenger 1, welcome to Mailjet!


May the delivery force be with you!\"\n send_mail(mail, mail, subject, text, html)\n return \"Desactivado, ya no va porque nos hakean xD\"\n\n\n@app.route('/') # pragma: no cover\ndef file_for_mailjet(dirr):\n return send_file('static/' + dirr)\n\n\n@app.errorhandler(BadRequest)\ndef handle_bad_request(e):\n return 'bad request!' + \"e\", 400\n\n\n@app.errorhandler(KeyError)\ndef handle_key_error(error):\n resp = {\n \"code\": \"6\",\n \"type\": \"error\",\n \"message\": \"JSON Key error: \" + str(error) + \" not found\"}\n\n return Response(json.dumps(resp), status=400, content_type='application/json')\n\n\n@app.errorhandler(JSONExceptionHandler)\ndef handle_json_error(error):\n resp = {\n \"code\": str(error.code),\n \"type\": \"error\",\n \"message\": str(error.to_dict())}\n\n return Response(json.dumps(resp), status=error.status_code, content_type='application/json')\n\n\n@app.errorhandler(UserBanned)\ndef handle_user_banned(error):\n resp = {\n \"code\": str(error.code),\n \"type\": \"info\",\n \"ban_reason\": str(error.reason),\n \"ban_until\": str(error.until_date),\n \"message\": str(error.to_dict())}\n\n return Response(json.dumps(resp), status=error.status_code, content_type='application/json')\n\n\n@app.errorhandler(UserException)\ndef handle_user_exception(error):\n resp = {\n \"code\": str(error.code),\n \"type\": \"error\",\n \"message\": str(error.to_dict())}\n\n return Response(json.dumps(resp), status=error.status_code, content_type='application/json')\n\n\n@app.errorhandler(ProductException)\ndef handle_user_exception(error):\n resp = {\n \"code\": str(error.code),\n \"type\": \"error\",\n \"message\": str(error.to_dict())}\n\n return Response(json.dumps(resp), status=error.status_code, content_type='application/json')\n\n\n@app.errorhandler(NotLoggedIn)\ndef handle_user_not_logged(error):\n resp = {\n \"code\": str(error.code),\n \"type\": \"error\",\n \"message\": str(error.to_dict())}\n\n return Response(json.dumps(resp), status=error.status_code, content_type='application/json')\n\n\n@app.errorhandler(DatabaseError)\ndef handle_sql_error(error):\n resp = {\n \"code\": \"1\",\n \"type\": \"error\",\n \"message\": str(error)}\n\n return Response(json.dumps(resp), status=400, content_type='application/json')\n\n\n@app.errorhandler(Exception)\ndef handle_sql_error(error):\n resp = {\n \"code\": \"99\",\n \"type\": \"error\",\n \"message\": \"Error without concrete exception: \" + str(error)}\n\n return Response(json.dumps(resp), status=400, content_type='application/json')\n\n#TODO Capturar expecion ValueError: time data '25-12-1999' does not match format '%Y-%m-%d'\n","repo_name":"unizar-30226-2019-06/ChangePop-Back","sub_path":"ChangePop/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27764231128","text":"import os, sys\nimport json\nimport hashlib\nimport requests\nimport base64\nimport unittest\n\ndef getbuffer(filename):\n myfile = open(filename, 'rb')\n buf = myfile.read()\n if filename.endswith('.wav'):\n buf = buf[1024000:192000+1024001]\n\n # buf type - bytes\n # 1. using base64 encode buf data\n # 2. decode previous encoded data\n # 3. send get request\n #\n # param format\n # params = {\n # 'music_buffer': buf\n # }\n\n temp = base64.b64encode(buf).decode()\n #print(type(base64.b64encode(buf)))\n #print(base64.b64encode(buf))\n myfile.close() \n params = {\n 'music_buffer': temp\n }\n r = requests.get('http://0.0.0.0:5000/team2/fingerprint', params=params)\n return r.text\n\nans = getbuffer('nonexist.mp3')\nprint(ans)\n","repo_name":"ldevr3t2/fingerprint_testing","sub_path":"test/othertest.py","file_name":"othertest.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24698631722","text":"import boto3\nimport os\nimport json\n\nclass MailLambda:\n def __init__(self):\n self.client = boto3.client('lambda')\n self.LAMBDA_ARN = \"arn:aws:lambda:eu-west-1:357832308593:function:sms_to_email\"\n \n def send(self, payload):\n try: \n print(json.dumps(payload))\n response = self.client.invoke(\n FunctionName=self.LAMBDA_ARN,\n Payload=json.dumps(payload),\n InvocationType='Event'\n )\n except Exception as e:\n print(\"invoke failed: {}\".format(e))\n\n","repo_name":"AdiGhidel/SIM800L","sub_path":"lambdaWrapper.py","file_name":"lambdaWrapper.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"33906577126","text":"\nclass Node(object):\n\n __slots__ = ['key', 'data', 'parent', '_left', '_right', 'height']\n\n def __init__(self, key, data):\n self.key = key\n self.data = data\n\n self.parent = None\n self._left = None\n self._right = None\n\n self.height = 1\n\n @property\n def weight(self):\n weight = 1\n\n if not self.left is None:\n weight += self.left.weight\n\n if not self.right is None:\n weight += self.right.weight\n\n return weight\n\n @property\n def left(self):\n return self._left\n\n @left.setter\n def left(self, new_left):\n if not self.left is None:\n self.left.parent = None\n\n self._left = new_left\n\n if not self.left is None:\n self.left.parent = self\n\n self._update_height()\n\n @property\n def right(self):\n return self._right\n\n @right.setter\n def right(self, new_right):\n if not self.right is None:\n self.right.parent = None\n\n self._right = new_right\n\n if not self.right is None:\n self.right.parent = self\n\n self._update_height()\n\n def _update_height(self):\n former_height = self.height\n\n height = 1\n\n if not self.left is None:\n height = self.left.height + 1\n\n if not self.right is None:\n right_height = self.right.height + 1\n\n if right_height > height:\n height = right_height\n\n if former_height == height:\n return\n\n self.height = height\n\n if not self.parent is None:\n self.parent._update_height()\n \n @property\n def balance_factor(self):\n '''Balance factor as defined in an AVL tree.\n\n For more details see\n http://en.wikipedia.org/wiki/AVL_tree#Insertion\n '''\n\n height_left = 0 if self.left is None else self.left.height\n height_right = 0 if self.right is None else self.right.height\n\n return height_left - height_right\n\n def __eq__(self, other):\n return self.key == other.key and self.data == other.data and self.left == other.left and self.right == other.right\n","repo_name":"marook/persistent_tree","sub_path":"src/persistent_tree/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22672886783","text":"class ConnectFour:\n def __init__(self):\n self.board = [[' ' for _ in range(7)] for _ in range(6)]\n self.current_player = 'X'\n\n def print_board(self):\n for row in self.board:\n print(\"|\".join(row))\n print(\"-\" * 29)\n\n def is_column_full(self, col):\n return self.board[0][col] != ' '\n\n def drop_piece(self, col):\n for row in range(5, -1, -1):\n if self.board[row][col] == ' ':\n self.board[row][col] = self.current_player\n break\n else:\n print(\"Column is full. Choose another column.\")\n\n def check_winner(self, row, col):\n directions = [(0, 1), (1, 0), (1, 1), (1, -1)]\n\n for dr, dc in directions:\n count = 1\n for i in range(1, 4):\n r, c = row + i * dr, col + i * dc\n if 0 <= r < 6 and 0 <= c < 7 and self.board[r][c] == self.current_player:\n count += 1\n else:\n break\n\n for i in range(1, 4):\n r, c = row - i * dr, col - i * dc\n if 0 <= r < 6 and 0 <= c < 7 and self.board[r][c] == self.current_player:\n count += 1\n else:\n break\n\n if count >= 4:\n return True\n\n return False\n\n def switch_player(self):\n self.current_player = 'O' if self.current_player == 'X' else 'X'\n\n def play_game(self):\n print(\"Welcome to Connect Four!\")\n while True:\n self.print_board()\n\n try:\n col = int(input(f\"Player {self.current_player}, choose a column (0-6): \"))\n if 0 <= col <= 6 and not self.is_column_full(col):\n self.drop_piece(col)\n if self.check_winner(5 - self.board[0].count(' '), col):\n self.print_board()\n print(f\"Player {self.current_player} wins!\")\n break\n self.switch_player()\n else:\n print(\"Invalid column choice. Please try again.\")\n except ValueError:\n print(\"Invalid input. Please enter a number.\")\n\n# Start the game\nconnect_four = ConnectFour()\nconnect_four.play_game()\n","repo_name":"ljonesdesign/python-games","sub_path":"connect_four.py","file_name":"connect_four.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40175105469","text":"from jina import Flow, Executor, DocumentArray, Document, requests\nfrom typing import Dict\nfrom PIL import Image\nfrom io import BytesIO\nfrom urllib.request import urlopen\nimport time\nfrom diffusers import StableDiffusionInstructPix2PixPipeline\nimport torch\n\nMODEL_ID = \"timbrooks/instruct-pix2pix\"\nREVISION = \"fp16\"\n\n\ndef download_image(url):\n data = urlopen(url)\n image = Image.open(BytesIO(data.read()))\n image = image.convert(\"RGB\")\n return image\n\n\nclass EditExecutor(Executor):\n pipe = None\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n # Load Model, cached in ./huggingface/cache\n print(\"Loading Model from local cache...\")\n pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(\n MODEL_ID, revision=REVISION, local_files_only=True, cache_dir=\"./huggingface/cache\", safety_checker=None, requires_safety_checker=False, torch_dtype=torch.float16)\n if torch.cuda.is_available():\n self.pipe = pipe.to(\"cuda\")\n else:\n try:\n # Try to use mps for MacOS\n self.pipe = pipe.to(\"mps\")\n except Exception:\n self.pipe = pipe.to(\"cpu\")\n\n @requests(on=\"/\")\n def edit(self, docs: DocumentArray, parameters: Dict, **kwargs):\n request_time = time.time()\n\n # Image Generation Parameters\n steps = int(parameters.get('steps', 20))\n guidance_scale = float(parameters.get('guidance_scale', 7.5))\n image_guidance_scale = float(\n parameters.get('image_guidance_scale', 1.5))\n\n # Image Output Parameters\n image_format = parameters.get(\"image_format\", \"jpeg\")\n image_quality = parameters.get(\"image_quality\", 95)\n\n # Generate Images\n for doc in docs:\n prompt = doc.text\n image = download_image(doc.uri)\n edit_image = self.pipe(prompt, image=image, num_inference_steps=steps,\n image_guidance_scale=image_guidance_scale, guidance_scale=guidance_scale).images[0]\n buffered = BytesIO()\n edit_image.save(buffered, format=image_format,\n quality=image_quality)\n _d = Document(\n blob=buffered.getvalue(),\n mime_type=\"image\" + \"/\" + image_format,\n tags={\n 'request': {\n 'api': 'edit',\n 'steps': steps,\n 'guidance_scale': guidance_scale,\n 'image_guidance_scale': image_guidance_scale,\n 'image_format': image_format,\n 'image_quality': image_quality,\n },\n 'text': prompt,\n 'generator': MODEL_ID,\n 'request_time': request_time,\n 'created_time': time.time(),\n },\n ).convert_blob_to_datauri()\n _d.text = prompt\n doc.matches.append(_d)\n\nif __name__ == \"__main__\":\n f = Flow().config_gateway(cors=True, protocol=\"http\", port_expose=8088).add(\n uses=EditExecutor, prefetch=1)\n\n # f = Flow.load_config('flow.yml')\n with f:\n f.block()\n\n# Use either way to start the flow\n# 1. JINA_MP_START_METHOD=spawn python flow.py\n# 2. jina flow --uses flow.yml","repo_name":"pingren/openart-jina-eah-showcase","sub_path":"flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"1506409447","text":"from .models import Subscription, SubscriptionStateCopy\n\n\n\n\ndef get_last_subscription_or_make_copy(subscription: Subscription):\n \"\"\"\n Выдаем последнюю неизмененную подписку если она есть, \n если нет создаем копию для ученика, чтобы неожиданно не поменять условия подписки ученику\n \"\"\"\n\n last_subscription, _ = SubscriptionStateCopy.objects.get_or_create(\n type=subscription.type,\n num_of_full_unt_exams=subscription.num_of_full_unt_exams,\n num_of_topic_exams=subscription.num_of_topic_exams,\n num_of_subject_exams=subscription.num_of_subject_exams,\n is_available_statistics=subscription.is_available_statistics,\n is_available_exam_analysis=subscription.is_available_exam_analysis,\n is_viewable_solutions=subscription.is_viewable_solutions,\n is_available_hints_and_difficulty=subscription.is_available_hints_and_difficulty,\n is_available_to_load_pdf=subscription.is_available_to_load_pdf,\n is_available_to_save_question=subscription.is_available_to_save_question,\n per_month_price=subscription.per_month_price,\n per_3_months_price=subscription.per_3_months_price,\n per_9_months_price=subscription.per_9_months_price,\n defaults={}\n )\n\n return last_subscription","repo_name":"Almazishe/emen","sub_path":"src/services/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23932702640","text":"from django.test import TestCase\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom contacts.models import Office365Connection\nimport contacts.o365service\n# Create your tests here.\n\napi_endpoint = 'https://outlook.office365.com/api/v1.0'\n\n# TODO: Copy a valid, non-expired access token here. You can get this from\n# an Office365Connection in the /admin/ page once you've successfully connected\n# an account to view contacts in the app. Remember these expire every hour, so\n# if you start getting 401's you need to get a new token.\naccess_token = ''\n\nclass MailApiTests(TestCase):\n \n def test_create_message(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n new_message_payload = '{ \"Subject\": \"Did you see last night\\'s game?\", \"Importance\": \"Low\", \"Body\": { \"ContentType\": \"HTML\", \"Content\": \"They were awesome!\" }, \"ToRecipients\": [ { \"EmailAddress\": { \"Address\": \"jasonjoh@alpineskihouse.com\" } } ] }'\n \n r = contacts.o365service.create_message(api_endpoint,\n access_token,\n new_message_payload)\n \n self.assertEqual(r, 201, 'Create message returned {0}'.format(r))\n \n def test_get_message_by_id(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_messages_params = '?$top=5&$select=Subject'\n \n r = contacts.o365service.get_messages(api_endpoint,\n access_token,\n get_messages_params)\n \n self.assertIsNotNone(r, 'Get messages returned None.')\n \n first_message = r['value'][0]\n \n first_message_id = first_message['Id']\n \n r = contacts.o365service.get_message_by_id(api_endpoint,\n access_token,\n first_message_id)\n \n self.assertIsNotNone(r, 'Get message by id returned None.')\n \n def test_update_message(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_messages_params = '?$top=5&$select=Subject'\n \n r = contacts.o365service.get_messages(api_endpoint,\n access_token,\n get_messages_params)\n \n self.assertIsNotNone(r, 'Get messages returned None.')\n \n first_message = r['value'][0]\n \n first_message_id = first_message['Id']\n \n update_payload = '{ \"Subject\" : \"UPDATED\" }'\n \n r = contacts.o365service.update_message(api_endpoint,\n access_token,\n first_message_id,\n update_payload)\n \n self.assertEqual(r, 200, 'Update message returned {0}.'.format(r))\n \n def test_delete_message(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_messages_params = '?$top=5&$select=Subject'\n \n r = contacts.o365service.get_messages(api_endpoint,\n access_token,\n get_messages_params)\n \n self.assertIsNotNone(r, 'Get messages returned None.')\n \n first_message = r['value'][0]\n \n first_message_id = first_message['Id']\n \n r = contacts.o365service.delete_message(api_endpoint,\n access_token,\n first_message_id)\n \n self.assertEqual(r, 204, 'Delete message returned {0}.'.format(r))\n \n def test_send_draft_message(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n # Get drafts\n get_drafts = '{0}/Me/Folders/Drafts/Messages?$select=Subject'.format(api_endpoint)\n \n r = contacts.o365service.make_api_call('GET', get_drafts, access_token)\n \n response = r.json()\n \n first_message = response['value'][0]\n \n first_message_id = first_message['Id']\n \n send_response = contacts.o365service.send_draft_message(api_endpoint,\n access_token,\n first_message_id)\n \n self.assertEqual(r, 200, 'Send draft returned {0}.'.format(r))\n \n def test_send_new_mail(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n new_message_payload = '{ \"Subject\": \"Sent from test_send_new_mail\", \"Importance\": \"Low\", \"Body\": { \"ContentType\": \"HTML\", \"Content\": \"They were awesome!\" }, \"ToRecipients\": [ { \"EmailAddress\": { \"Address\": \"allieb@jasonjohtest.onmicrosoft.com\" } } ] }'\n \n r = contacts.o365service.send_new_message(api_endpoint,\n access_token,\n new_message_payload,\n True)\n \n self.assertEqual(r, 202, 'Send new message returned {0}.'.format(r))\n \nclass CalendarApiTests(TestCase):\n \n def test_create_event(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n new_event_payload = '{ \"Subject\": \"Discuss the Calendar REST API\", \"Body\": { \"ContentType\": \"HTML\", \"Content\": \"I think it will meet our requirements!\" }, \"Start\": \"2015-01-15T18:00:00Z\", \"End\": \"2015-01-15T19:00:00Z\", \"Attendees\": [ { \"EmailAddress\": { \"Address\": \"alexd@alpineskihouse.com\", \"Name\": \"Alex Darrow\" }, \"Type\": \"Required\" } ] }'\n \n r = contacts.o365service.create_event(api_endpoint,\n access_token,\n new_event_payload)\n \n self.assertEqual(r, 201, 'Create event returned {0}'.format(r))\n \n def test_get_event_by_id(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_events_params = '?$top=5&$select=Subject,Start,End'\n \n r = contacts.o365service.get_events(api_endpoint,\n access_token,\n get_events_params)\n \n self.assertIsNotNone(r, 'Get events returned None.')\n \n first_event = r['value'][0]\n \n first_event_id = first_event['Id']\n \n r = contacts.o365service.get_event_by_id(api_endpoint,\n access_token,\n first_event_id)\n \n self.assertIsNotNone(r, 'Get event by id returned None.')\n \n def test_update_event(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_events_params = '?$top=5&$select=Subject,Start,End'\n \n r = contacts.o365service.get_events(api_endpoint,\n access_token,\n get_events_params)\n \n self.assertIsNotNone(r, 'Get events returned None.')\n \n first_event = r['value'][0]\n \n first_event_id = first_event['Id']\n \n update_payload = '{ \"Subject\" : \"UPDATED\" }'\n \n r = contacts.o365service.update_event(api_endpoint,\n access_token,\n first_event_id,\n update_payload)\n \n self.assertEqual(r, 200, 'Update event returned {0}.'.format(r))\n \n def test_delete_event(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_events_params = '?$top=5&$select=Subject,Start,End'\n \n r = contacts.o365service.get_events(api_endpoint,\n access_token,\n get_events_params)\n \n self.assertIsNotNone(r, 'Get events returned None.')\n \n first_event = r['value'][0]\n \n first_event_id = first_event['Id']\n \n r = contacts.o365service.delete_event(api_endpoint,\n access_token,\n first_event_id)\n \n self.assertEqual(r, 204, 'Delete event returned {0}.'.format(r))\n\nclass ContactsApiTests(TestCase):\n \n def test_create_contact(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n new_contact_payload = '{ \"GivenName\": \"Pavel\", \"Surname\": \"Bansky\", \"EmailAddresses\": [ { \"Address\": \"pavelb@alpineskihouse.com\", \"Name\": \"Pavel Bansky\" } ], \"BusinessPhones\": [ \"+1 732 555 0102\" ] }'\n \n r = contacts.o365service.create_contact(api_endpoint,\n access_token,\n new_contact_payload)\n \n self.assertEqual(r, 201, 'Create contact returned {0}'.format(r))\n \n def test_get_contact_by_id(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_contacts_params = '?$top=5&$select=DisplayName'\n \n r = contacts.o365service.get_contacts(api_endpoint,\n access_token,\n get_contacts_params)\n \n self.assertIsNotNone(r, 'Get contacts returned None.')\n \n first_contact = r['value'][0]\n \n first_contact_id = first_contact['Id']\n \n r = contacts.o365service.get_contact_by_id(api_endpoint,\n access_token,\n first_contact_id)\n \n self.assertIsNotNone(r, 'Get contact by id returned None.')\n \n def test_update_contact(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_contacts_params = '?$top=5&$select=DisplayName'\n \n r = contacts.o365service.get_contacts(api_endpoint,\n access_token,\n get_contacts_params)\n \n self.assertIsNotNone(r, 'Get contacts returned None.')\n \n first_contact = r['value'][0]\n \n first_contact_id = first_contact['Id']\n \n update_payload = '{ \"Surname\" : \"UPDATED\" }'\n \n r = contacts.o365service.update_contact(api_endpoint,\n access_token,\n first_contact_id,\n update_payload)\n \n self.assertEqual(r, 200, 'Update contact returned {0}.'.format(r))\n \n def test_delete_contact(self):\n self.assertEqual(access_token, '', 'You must copy a valid access token into the access_token variable.')\n \n get_contacts_params = '?$top=5&$select=DisplayName'\n \n r = contacts.o365service.get_contacts(api_endpoint,\n access_token,\n get_contacts_params)\n \n self.assertIsNotNone(r, 'Get contacts returned None.')\n \n first_contact = r['value'][0]\n \n first_contact_id = first_contact['Id']\n \n r = contacts.o365service.delete_contact(api_endpoint,\n access_token,\n first_contact_id)\n \n self.assertEqual(r, 204, 'Delete contact returned {0}.'.format(r))\n \n# MIT License: \n \n# Permission is hereby granted, free of charge, to any person obtaining \n# a copy of this software and associated documentation files (the \n# \"\"Software\"\"), to deal in the Software without restriction, including \n# without limitation the rights to use, copy, modify, merge, publish, \n# distribute, sublicense, and/or sell copies of the Software, and to \n# permit persons to whom the Software is furnished to do so, subject to \n# the following conditions: \n \n# The above copyright notice and this permission notice shall be \n# included in all copies or substantial portions of the Software. \n \n# THE SOFTWARE IS PROVIDED \"\"AS IS\"\", WITHOUT WARRANTY OF ANY KIND, \n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND \n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE \n# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION \n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION \n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","repo_name":"jasonjoh/pythoncontacts","sub_path":"contacts/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":14739,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"52"} +{"seq_id":"22753581404","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom . import views #'.' means the same folder\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^register/$', views.register, name=\"register\"),\n url(r'^success/$', views.success, name=\"success\"),\n url(r'^process/$', views.process, name=\"process\"),\n url(r'^clear/$', views.clear, name=\"clear\")\n]","repo_name":"karnrage/PyStack","sub_path":"Django/wish_list_finished/wish_list/apps/loginregis_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73197470566","text":"import requests\nimport logging\n\n\nclass GitHubAPI:\n \"\"\"\n A wrapper class for the GitHub API.\n\n Attributes:\n BASE_URL (str): The base URL for the GitHub API.\n \"\"\"\n\n BASE_URL = 'https://api.github.com'\n EVENTS = [\"CommitCommentEvent\", \"CreateEvent\", \"DeleteEvent\", \"ForkEvent\",\n \"GollumEvent\", \"IssueCommentEvent\", \"IssuesEvent\", \"MemberEvent\",\n \"PublicEvent\", \"PullRequestEvent\", \"PullRequestReviewEvent\",\n \"PullRequestReviewCommentEvent\", \"PullRequestReviewThreadEvent\",\n \"PushEvent\", \"ReleaseEvent\", \"SponsorshipEvent\", \"WatchEvent\"]\n\n def __init__(self, token):\n \"\"\"\n Initializes the GitHubAPI class with an authentication token.\n\n Args:\n token (str): The GitHub API token.\n \"\"\"\n self.headers = {\n 'Authorization': f'token {token}',\n 'Accept': 'application/vnd.github.v3+json'\n }\n logging.basicConfig(level=logging.INFO)\n\n def get_repo_events(self, username, repo, per_page=30, page=1):\n \"\"\"\n Fetch and display the latest events for a given GitHub repository\n Filter events using event_type, e.g by \"PushEvent\" or \"PullRequestEvent\"\n\n Args:\n username (str): The owner of the repository.\n repo (str): The repository name.\n event_type (str, optional): The type of event to fetch.\n\n Returns:\n list: The repository's events.\n \"\"\"\n try:\n url = f'{self.BASE_URL}/repos/{username}/{repo}/events?page={page}&per_page={per_page}'\n response = requests.get(\n url, headers=self.headers)\n response.raise_for_status()\n except requests.HTTPError as http_err:\n logging.error(f'HTTP error occurred: {http_err}')\n return {\"error\": str(http_err)}\n except Exception as err:\n logging.error(f'Other error occurred: {err}')\n return {\"error\": str(err)}\n else:\n return response\n","repo_name":"ZakYeo/github-events-analyser","sub_path":"src/github_events_analyser/github_api.py","file_name":"github_api.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30274111414","text":"\"\"\"\n15-110 Hw6 - Social Media Analytics Project\nName: E.j. Ezuma-Ngwu\nAndrewID: ufe\n\"\"\"\n\nimport hw6_social_tests as test\n\nproject = \"Social\" # don't edit this\n\n### WEEK 1 ###\n\nimport pandas as pd\nimport nltk\nnltk.download('vader_lexicon', quiet=True)\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\nendChars = [ \" \", \"\\n\", \"#\", \".\", \",\", \"?\", \"!\", \":\", \";\", \")\" ]\n\n'''\nmakeDataFrame(filename)\n#3 [Check6-1]\nParameters: str\nReturns: dataframe\n'''\ndef makeDataFrame(filename):\n df = pd.read_csv(filename)\n return df\n\n\n'''\nparseName(fromString)\n#4 [Check6-1]\nParameters: str\nReturns: str\n'''\ndef parseName(fromString):\n first = fromString.find(\":\") +2\n last = fromString.find(\"(\") -1\n name = fromString[first:last]\n return name\n\n\n'''\nparsePosition(fromString)\n#4 [Check6-1]\nParameters: str\nReturns: str\n'''\ndef parsePosition(fromString):\n first = fromString.find(\"(\")+1\n last = fromString.find(\"from\")-1\n position = fromString[first:last]\n return position\n\n\n'''\nparseState(fromString)\n#4 [Check6-1]\nParameters: str\nReturns: str\n'''\ndef parseState(fromString):\n first = fromString.find(\"from\")+ 5\n #(would normally be +2 for a singular string but because it is a word you do +5 to account for \"rom\" in \"from\"\n last = fromString.find(\")\")\n state = fromString[first:last]\n return state\n\n\n'''\nfindHashtags(message)\n#5 [Check6-1]\nParameters: str\nReturns: list of strs\n'''\ndef findHashtags(message):\n result = []\n for i in range(len(message)):\n hash = \"\"\n #message[i] is the letter and i is the index\n if message[i] == \"#\":\n j= i+1\n while j < len(message) and message[j] not in endChars:\n j= j+1\n single = message[i:j]\n result.append(single)\n return result\n\n\n\n'''\ngetRegionFromState(stateDf, state)\n#6 [Check6-1]\nParameters: dataframe ; str\nReturns: str\n'''\ndef getRegionFromState(stateDf, state):\n sub1 = stateDf[stateDf[\"state\"]==state]\n region = sub1.iloc[0][\"region\"]\n return region\n\n\n'''\naddColumns(data, stateDf)\n#7 [Check6-1] & #2 [Check6-2]\nParameters: dataframe ; dataframe\nReturns: None\n'''\ndef addColumns(data, stateDf):\n names=[]\n positions=[]\n states=[]\n regions=[]\n hashtags=[]\n sentiment = []\n sent = SentimentIntensityAnalyzer()\n for label in data[\"label\"]:\n names.append(parseName(label))\n positions.append(parsePosition(label))\n states.append(parseState(label))\n regions.append(getRegionFromState(stateDf, parseState(label)))\n for text in data[\"text\"]:\n hashtags.append(findHashtags(text))\n sentiment.append(findSentiment(sent,text))\n data[\"name\"]= names\n data[\"position\"] = positions\n data[\"state\"] = states\n data[\"region\"] = regions\n data[\"hashtags\"] = hashtags\n data[\"sentiment\"] = sentiment\n\n\n\n\n\n### WEEK 2 ###\n\n'''\nfindSentiment(classifier, message)\n#1 [Check6-2]\nParameters: SentimentIntensityAnalyzer ; str\nReturns: str\n'''\ndef findSentiment(classifier, message):\n score = classifier.polarity_scores(message)['compound']\n if score < -0.1:\n return \"negative\"\n if score > 0.1:\n return \"positive\"\n else:\n return \"neutral\"\n\n'''\ngetDataCountByState(data, colName, dataToCount)\n#3 [Check6-2]\nParameters: dataframe ; str ; str\nReturns: dict mapping strs to ints\n'''\ndef getDataCountByState(data, colName, dataToCount):\n if colName != \"\":\n data = data[data[colName] == dataToCount]\n sentOfState= { }\n for states in data[\"state\"]:\n if states in sentOfState:\n sentOfState[states] += 1\n elif states not in sentOfState:\n sentOfState[states] = 1\n return sentOfState\n\n\n'''\ngetDataForRegion(data, colName)\n#4 [Check6-2]\nParameters: dataframe ; str\nReturns: dict mapping strs to (dicts mapping strs to ints)\n'''\ndef getDataForRegion(data, colName):\n d = {}\n for index, row in data.iterrows():\n message = row[colName]\n region = row[\"region\"]\n if region not in d:\n d[region] = {}\n if message not in d[region]:\n d[region][message] = 0\n d[region][message] += 1\n\n return d\n #only need to do one for loop and check if the region is in the dictionary and if not add it, else add the message of the region\n\n\n\n'''\ngetHashtagRates(data)\n#5 [Check6-2]\nParameters: dataframe\nReturns: dict mapping strs to ints\n'''\ndef getHashtagRates(data):\n\n hashRates= {}\n for hashtagCount in data[\"hashtags\"]:\n for tags in hashtagCount:\n if tags in hashRates:\n hashRates[tags] += 1\n elif tags not in hashRates:\n hashRates[tags] = 1\n\n return hashRates\n\n\n\n#REFER TO TEST CASES NOT CSV\n\n'''\nmostCommonHashtags(hashtags, count)\n#6 [Check6-2]\nParameters: dict mapping strs to ints ; int\nReturns: dict mapping strs to ints\n'''\ndef mostCommonHashtags(hashtags, count):\n commonHash ={}\n\n while len(commonHash) < count:\n highestNum = 0\n highestKey = None\n for key in hashtags:\n if key not in commonHash:\n if hashtags[key] > highestNum:\n highestNum = hashtags[key]\n highestKey = key\n commonHash[highestKey] = highestNum\n return commonHash\n\n\n\n\n\n'''\ngetHashtagSentiment(data, hashtag)\n#7 [Check6-2]\nParameters: dataframe ; str\nReturns: float\n'''\nimport statistics\ndef getHashtagSentiment(data, hashtag):\n result = 0\n avgCount = 0\n count = [] #FIX THIS BEFORE SUBMISSION\n for index, row in data.iterrows():\n hashtagsRow = row[\"sentiment\"]\n if hashtag in row[\"hashtags\"]:\n if hashtagsRow == \"positive\":\n count.append(1)\n if hashtagsRow == \"negative\":\n count.append(-1)\n if hashtagsRow == \"neutral\":\n count.append(0)\n allsum = sum(count)\n numOfHash = int(len(count))\n avgCount = allsum/numOfHash\n result = avgCount\n return result\n\n#FIX FIX\n\n\n\n\n### WEEK 3 ###\n\n'''\ngraphStateCounts(stateCounts, title)\n#2 [Hw6]\nParameters: dict mapping strs to ints ; str\nReturns: None\n'''\ndef graphStateCounts(stateCounts, title):\n import matplotlib.pyplot as plt\n labels = []\n yVals = []\n for state in stateCounts:\n labels.append(state)\n yVals.append(stateCounts[state])\n\n plt.bar(labels, yVals, color=\"green\")\n plt.title(title)\n plt.xticks(rotation ='vertical')\n plt.xlabel(\"States\")\n plt.ylabel(\"Number\")\n plt.show()\n return\n\n'''\ngraphTopNStates(stateCounts, stateFeatureCounts, n, title)\n#3 [Hw6]\nParameters: dict mapping strs to ints ; dict mapping strs to ints ; int ; str\nReturns: None\n'''\ndef graphTopNStates(stateCounts, stateFeatureCounts, n, title):\n topN ={}\n while len(topN) < n:\n total = 0\n fTotal = 0\n bestFRate = -1\n highestState = None\n for state in stateFeatureCounts:\n total = (stateCounts[state])\n fTotal = (stateFeatureCounts[state])\n tempRate = fTotal/total\n if state not in topN and tempRate > bestFRate:\n bestFRate = tempRate\n highestState = state\n topN[highestState] = bestFRate\n\n graphStateCounts(topN, title)\n return\n\n\n'''\ngraphRegionComparison(regionDicts, title)\n#4 [Hw6]\nParameters: dict mapping strs to (dicts mapping strs to ints) ; str\nReturns: None\n'''\ndef graphRegionComparison(regionDicts, title):\n featureNames=[]\n regionNames=[]\n regFeaLists=[]\n for regions in regionDicts:\n if regions not in regionNames:\n regionNames.append(regions)\n for features in regionDicts[regions]:\n if features not in featureNames:\n featureNames.append(features)\n\n for regions in regionNames:\n tempFeatLists = []\n for features in featureNames:\n if features in regionDicts[regions]:\n tempFeatLists.append(regionDicts[regions][features])\n regFeaLists.append(tempFeatLists)\n\n sideBySideBarPlots(featureNames,\nregionNames, regFeaLists, title)\n return\n\n\n'''\ngraphHashtagSentimentByFrequency(data)\n#4 [Hw6]\nParameters: dataframe\nReturns: None\n'''\ndef graphHashtagSentimentByFrequency(data):\n d = getHashtagRates(data)\n mch = mostCommonHashtags(d, 50)\n hashtags=[]\n freqs=[]\n sentiScores=[]\n for htgs in mch:\n hashtags.append(htgs)\n freqs.append(mch[htgs])\n sentiScores.append(getHashtagSentiment(data, htgs))\n scatterPlot(freqs, sentiScores, hashtags, \"Hashtag Sentiment By Frequency in Messages\")\n return\n\n\n#### WEEK 3 PROVIDED CODE ####\n\"\"\"\nExpects 3 lists - one of x labels, one of data labels, and one of data values - and a title.\nYou can use it to graph any number of datasets side-by-side to compare and contrast.\n\"\"\"\ndef sideBySideBarPlots(xLabels, labelList, valueLists, title):\n import matplotlib.pyplot as plt\n\n w = 0.8 / len(labelList) # the width of the bars\n xPositions = []\n for dataset in range(len(labelList)):\n xValues = []\n for i in range(len(xLabels)):\n xValues.append(i - 0.4 + w * (dataset + 0.5))\n xPositions.append(xValues)\n\n for index in range(len(valueLists)):\n plt.bar(xPositions[index], valueLists[index], width=w, label=labelList[index])\n\n plt.xticks(ticks=list(range(len(xLabels))), labels=xLabels, rotation=\"vertical\")\n plt.legend()\n plt.title(title)\n\n plt.show()\n\n\"\"\"\nExpects two lists of probabilities and a list of labels (words) all the same length\nand plots the probabilities of x and y, labels each point, and puts a title on top.\nExpects that the y axis will be from -1 to 1. If you want a different y axis, change plt.ylim\n\"\"\"\ndef scatterPlot(xValues, yValues, labels, title):\n import matplotlib.pyplot as plt\n fig, ax = plt.subplots()\n\n plt.scatter(xValues, yValues)\n\n # make labels for the points\n for i in range(len(labels)):\n plt.annotate(labels[i], # this is the text\n (xValues[i], yValues[i]), # this is the point to label\n textcoords=\"offset points\", # how to position the text\n xytext=(0, 10), # distance from text to points (x,y)\n ha='center') # horizontal alignment can be left, right or center\n\n plt.title(title)\n plt.ylim(-1, 1)\n\n # a bit of advanced code to draw a line on y=0\n ax.plot([0, 1], [0.5, 0.5], color='black', transform=ax.transAxes)\n\n plt.show()\n\n\n### RUN CODE ###\n\n# This code runs the test cases to check your work\nif __name__ == \"__main__\":\n print(\"\\n\" + \"#\"*15 + \" WEEK 1 TESTS \" + \"#\" * 16 + \"\\n\")\n test.week1Tests()\n print(\"\\n\" + \"#\"*15 + \" WEEK 1 OUTPUT \" + \"#\" * 15 + \"\\n\")\n test.runWeek1()\n\n ## Uncomment these for Week 2 ##\n print(\"\\n\" + \"#\"*15 + \" WEEK 2 TESTS \" + \"#\" * 16 + \"\\n\")\n test.week2Tests()\n print(\"\\n\" + \"#\"*15 + \" WEEK 2 OUTPUT \" + \"#\" * 15 + \"\\n\")\n test.runWeek2()\n\n ## Uncomment these for Week 3 ##\n print(\"\\n\" + \"#\"*15 + \" WEEK 3 OUTPUT \" + \"#\" * 15 + \"\\n\")\n test.runWeek3()","repo_name":"Ej11/15-110-Social-Media-Analytics","sub_path":"hw6_social.py","file_name":"hw6_social.py","file_ext":"py","file_size_in_byte":11152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39497583327","text":"\"\"\"\n전쟁 - 전투\n\n문제\n전쟁은 어느덧 전면전이 시작되었다. 결국 전투는 난전이 되었고, 우리 병사와 적국 병사가 섞여 싸우게 되었다. 그러나 당신의 병사들은 흰색 옷을 입고, 적국의 병사들은 파란색 옷을 입었기 때문에 서로가 적인지 아군인지는 구분할 수 있다. 문제는 같은 팀의 병사들은 모이면 모일수록 강해진다는 사실이다.\n\nN명이 뭉쳐있을 때는 N2의 위력을 낼 수 있다. 과연 지금 난전의 상황에서는 누가 승리할 것인가? 단, 같은 팀의 병사들이 대각선으로만 인접한 경우는 뭉쳐 있다고 보지 않는다.\n\n입력\n첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는 병사가 한 명 있다. B는 파란색, W는 흰색이다. 당신의 병사와 적국의 병사는 한 명 이상 존재한다.\n\n출력\n첫 번째 줄에 당신의 병사의 위력의 합과 적국의 병사의 위력의 합을 출력한다.\n\"\"\"\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n\n## 상, 하, 좌, 우\ndx = [1, 0, -1, 0]\ndy = [0, 1, 0, -1]\n\ndef bfs(x, y, status):\n queue = deque()\n queue.append((x, y))\n graph[x][y] = 'visited' # 방문한 위치는 재방문 안하게 바꿔준다.\n cnt = 0\n\n while queue:\n x, y = queue.popleft()\n\n for i in range(4):\n nx = x+dx[i]\n ny = y+dy[i]\n\n if 0 <= nx < M and 0 <= ny < N:\n if graph[nx][ny] != 'visited' and graph[nx][ny] == status:\n graph[nx][ny] = 'visited'\n queue.append((nx, ny))\n cnt += 1\n return cnt + 1\n\n\n\nif __name__ == \"__main__\":\n ## 가로, 세로\n N, M = map(int, input().split())\n\n graph = [list(input().strip()) for _ in range(M)]\n\n white, blue = 0, 0\n\n for x in range(M):\n for y in range(N):\n if graph[x][y] != 'visited':\n if graph[x][y] == 'W':\n white += bfs(x, y, 'W')**2\n elif graph[x][y] == 'B':\n blue += bfs(x, y, 'B')**2\n print(white, blue)","repo_name":"TetorCo/daliy_commit_backjoon","sub_path":"220303_1303.py","file_name":"220303_1303.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13870679538","text":"import functools\nimport logging\nfrom collections.abc import Callable\n\nfrom telegram import BotCommandScopeChat, Update\nfrom telegram._utils.defaultvalue import DEFAULT_TRUE\nfrom telegram._utils.types import DVType\nfrom telegram.ext import Application, CommandHandler\nfrom telegram.ext.filters import BaseFilter\n\nfrom app.context import CallbackContext\nfrom app.utils import Str\n\nlogger = logging.getLogger(__name__)\n\n\nclass CommandRegistrator:\n def __init__(self):\n self._command_descriptions: dict[CommandHandler, Str] = {}\n\n def connect_commands(self, app: Application) -> Application:\n for handler in self._command_descriptions:\n app.add_handler(handler)\n cmds = \", \".join(f\"/{x}\" for x in handler.commands)\n logger.info(\"Added commands %s to %s\", cmds, app)\n return app\n\n def add(\n self,\n name: str = None,\n description: Str = None,\n auto_send_commands: bool = True,\n filters: BaseFilter = None,\n block: DVType[bool] = DEFAULT_TRUE,\n ) -> Callable[[Callable], Callable]:\n def decorator(func: Callable) -> Callable:\n self.add_handler(\n CommandHandler(\n name or func.__name__,\n func,\n filters=filters,\n block=block,\n ),\n description=description,\n auto_send_commands=auto_send_commands,\n )\n return func\n\n return decorator\n\n def add_handler(\n self,\n handler: CommandHandler,\n description: Str = None,\n auto_send_commands: bool = True,\n ):\n if description is None:\n description = (\n (handler.callback.__doc__ or \"\").strip().split(\"\\n\")[0].strip()\n )\n\n old_callback = handler.callback\n command = list(handler.commands)[0]\n\n @functools.wraps(old_callback)\n async def wrap(update: Update, context: CallbackContext):\n logger.info(\"Command /%s called\", command)\n\n res = await old_callback(update, context)\n\n if auto_send_commands:\n await self.send_commands(update, context)\n return res\n\n handler.callback = wrap\n self._command_descriptions[handler] = description\n return handler\n\n def get_command_description(self) -> dict[str, str]:\n return {\n list(command.commands)[0]: description\n for command, description in self._command_descriptions.items()\n }\n\n async def send_commands(self, update: Update, context: CallbackContext):\n commands = self.get_command_description()\n await context.bot.set_my_commands(\n commands=[\n (cmd_name, desc)\n for cmd_name, desc in self.get_command_description().items()\n ],\n scope=BotCommandScopeChat(update.effective_chat.id),\n language_code=update.effective_user.language_code,\n )\n logger.info(\n \"Commands are sent to Chat[%s]\",\n update.effective_chat.id,\n )\n return commands\n","repo_name":"jag-k/tiktok-downloader","sub_path":"app/commands/registrator.py","file_name":"registrator.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"4895553900","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[112]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[113]:\n\n\nimport keras\n\n\n# In[114]:\n\n\nfrom keras.models import Sequential\n\n\n# In[115]:\n\n\nfrom keras.layers import Dense\n\n\n# In[116]:\n\n\ndf=pd.read_csv(r\"D:\\ai\\g.h.I\\Salary_Data.csv\")\n\n\n# In[117]:\n\n\ndf.head(2)\n\n\n# In[118]:\n\n\nX=df.iloc[:,0:1].values\ny=df.iloc[:,0:2].values\n\n\n# In[119]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[120]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1)\n\n\n# In[121]:\n\n\nX_train.shape\n\n\n# In[122]:\n\n\nmodel = Sequential()\nmodel.add(Dense(200, input_dim=1, activation='relu'))\nmodel.add(Dense(200, input_dim=200, activation='relu'))\nmodel.add(Dense(1, activation='linear'))\n\n\n# In[123]:\n\n\nkeras.optimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, amsgrad=False)\nmodel.compile(loss='mean_squared_error', optimizer='RMSprop', metrics=['mean_absolute_percentage_error'])\n\n\n# In[124]:\n\n\n#Neural Network Model\nmodel.summary()\n\n\n# In[125]:\n\n\nhistory = model.fit(X_train, y_train, epochs=50, batch_size=32,validation_split=0.15,validation_data=None,verbose=1)\n\n\n# In[126]:\n\n\nkeras.backend.clear_session()\n\n\n# In[127]:\n\n\nX_test\n\n\n# In[128]:\n\n\nmodel.predict(X_test)\n\n\n# In[129]:\n\n\nfrom matplotlib import pyplot as plt\n\n\n# In[132]:\n\n\nplt.plot(model.predict(X_test))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Abir0810/Artificial-Neural-Network-Model-Using-Keras-Sequencial-","sub_path":"Salary_Data_Prediction Model.py","file_name":"Salary_Data_Prediction Model.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33001235931","text":"\nsortir = False\nwhile sortir != True:\n \n edad = int(input(\"Indica la teva edat: \"))\n if (edad < 18):\n print(\"Ets menor d'edat.\")\n else:\n print(\"Ets major d'edat\")\n\n fora = input(\"Vols sortir del programa? (SI/NO): \")\n\n if fora == \"SI\":\n sortir = True\n\n\n\n ","repo_name":"albabosch/practica1","sub_path":"edad.py","file_name":"edad.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"ca","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40725767384","text":"from ncclient import manager\nimport xmltodict\nfrom pprint import pprint\nimport logging\n\n# logging.basicConfig(level=logging.DEBUG)\n\n# router = {\n# \"host\": \"ios-xe-mgmt.cisco.com\",\n# \"port\": \"10000\",\n# \"username\": \"developer\",\n# \"password\": \"C1sco12345\"\n# }\n\nrouter = {\n \"host\": \"192.168.1.211\",\n \"port\": \"830\",\n \"username\": \"admin\",\n \"password\": \"juniper1\"\n}\n\nint_filter = \"\"\"\n \n \n \n \n 1\n \n \n \n \n \n GigabitEthernet1\n \n \n \n\"\"\"\n\nwith manager.connect(**router, hostkey_verify=False) as m:\n netconf_response = m.get(int_filter)\n # print(netconf_response)\n\npython_response = xmltodict.parse(netconf_response.xml)['rpc-reply']['data']\n# pprint(python_response)\n\nop = python_response[\"interfaces\"][\"interface\"]\nconfig = python_response[\"native\"]['interface']['GigabitEthernet']\n\nprint(f\"Name: GigabitEthernet{config['name']['#text']}\")\nprint(f\"Packets In: {op['statistics']['in-unicast-pkts']}\")","repo_name":"aramidetosin/ENAUTO","sub_path":"Netconf_IOS_XE/ENAUTOget.py","file_name":"ENAUTOget.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36609214656","text":"import os\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ListTrainer\n\nos.system('color 7f') # coloring background of terminal\n\nbot = ChatBot('Test')\nconv = open(\"Data.txt\", 'r').readlines()\nbot.set_trainer(ListTrainer)\nbot.train(conv)\n\nwhile 1:\n msg = input(\"You: \")\n if msg.strip() != 'Bye':\n reply = bot.get_response(msg)\n print(\"Bot:\", reply)\n\n if msg.strip() == 'Bye':\n print(\"Boat: Bye \")\n break\n","repo_name":"SarfrazAHd/BaseRepo","sub_path":"Python/Chat_bot/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21899762034","text":"from enum import Enum as BuiltinEnum\nfrom struct import calcsize, pack, unpack_from\nfrom typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union\n\nfrom typing_extensions import Self\n\nfrom spsdk.exceptions import SPSDKError\nfrom spsdk.sbfile.sb31.constants import EnumCmdTag\nfrom spsdk.utils.abstract import BaseClass\nfrom spsdk.utils.easy_enum import Enum\nfrom spsdk.utils.misc import align_block, load_binary, value_to_int\n\n########################################################################################################################\n# Main Class\n########################################################################################################################\n\n\nclass MainCmd(BaseClass):\n \"\"\"Functions for creating cmd intended for inheritance.\"\"\"\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"MainCmd\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n :raises NotImplementedError: Derived class has to implement this method\n \"\"\"\n raise NotImplementedError(\"Derived class has to implement this method.\")\n\n\n########################################################################################################################\n# Base Command Class\n########################################################################################################################\n\n\nclass BaseCmd(MainCmd):\n \"\"\"Functions for creating cmd intended for inheritance.\"\"\"\n\n FORMAT = \"<4L\"\n SIZE = calcsize(FORMAT)\n TAG = 0x55AAAA55\n\n @property\n def address(self) -> int:\n \"\"\"Get address.\"\"\"\n return self._address\n\n @address.setter\n def address(self, value: int) -> None:\n \"\"\"Set address.\"\"\"\n if value < 0x00000000 or value > 0xFFFFFFFF:\n raise SPSDKError(\"Invalid address\")\n self._address = value\n\n @property\n def length(self) -> int:\n \"\"\"Get length.\"\"\"\n return self._length\n\n @length.setter\n def length(self, value: int) -> None:\n \"\"\"Set value.\"\"\"\n if value < 0x00000000 or value > 0xFFFFFFFF:\n raise SPSDKError(\"Invalid length\")\n self._length = value\n\n def __init__(self, address: int, length: int, cmd_tag: int = EnumCmdTag.NONE) -> None:\n \"\"\"Constructor for Commands header.\n\n :param address: Input address\n :param length: Input length\n :param cmd_tag: Command tag\n \"\"\"\n self._address = address\n self._length = length\n self.cmd_tag = cmd_tag\n\n def __repr__(self) -> str:\n return f\"SB3.1 Command: {self.__class__.__name__}\"\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\n\n :raises NotImplementedError: Derived class has to implement this method\n \"\"\"\n raise NotImplementedError(\"Derived class has to implement this method.\")\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n return pack(self.FORMAT, self.TAG, self.address, self.length, self.cmd_tag)\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Deserialize object from bytes array.\"\"\"\n raise NotImplementedError(\"Derived class has to implement this method.\")\n\n @classmethod\n def header_parse(cls, cmd_tag: int, data: bytes) -> Tuple[int, int]:\n \"\"\"Parse header command from bytes array.\n\n :param data: Input data as bytes array\n :param cmd_tag: Information about command tag\n :raises SPSDKError: Raised if tag is not equal to required TAG\n :raises SPSDKError: Raised if cmd is not equal EnumCmdTag\n :return: Tuple\n \"\"\"\n tag, address, length, cmd = unpack_from(cls.FORMAT, data)\n if tag != cls.TAG:\n raise SPSDKError(\"TAG is not valid.\")\n if cmd != cmd_tag:\n raise SPSDKError(\"Values are not same.\")\n return address, length\n\n\n########################################################################################################################\n# Commands Classes version 3.1\n########################################################################################################################\nclass CmdLoadBase(BaseCmd):\n \"\"\"Base class for commands loading data.\"\"\"\n\n HAS_MEMORY_ID_BLOCK = True\n\n def __init__(self, cmd_tag: int, address: int, data: bytes, memory_id: int = 0) -> None:\n \"\"\"Constructor for command.\n\n :param cmd_tag: Command tag for the derived class\n :param address: Address for the load command\n :param data: Data to load\n :param memory_id: Memory ID\n \"\"\"\n super().__init__(address=address, length=len(data), cmd_tag=cmd_tag)\n self.memory_id = memory_id\n self.data = data\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n data = super().export()\n if self.HAS_MEMORY_ID_BLOCK:\n data += pack(\"<4L\", self.memory_id, 0, 0, 0)\n data += self.data\n data = align_block(data, alignment=16)\n return data\n\n def __str__(self) -> str:\n \"\"\"Get info about the load command.\"\"\"\n msg = f\"{EnumCmdTag.name(self.cmd_tag)}: \"\n if self.HAS_MEMORY_ID_BLOCK:\n msg += f\"Address=0x{self.address:08X}, Length={self.length}, Memory ID={self.memory_id}\"\n else:\n msg += f\"Address=0x{self.address:08X}, Length={self.length}\"\n return msg\n\n @classmethod\n def _extract_data(cls, data: bytes) -> Tuple[int, int, bytes, int, int]:\n tag, address, length, cmd = unpack_from(cls.FORMAT, data)\n memory_id = 0\n if tag != cls.TAG:\n raise SPSDKError(f\"Invalid TAG, expected: {cls.TAG}\")\n offset = BaseCmd.SIZE\n if cls.HAS_MEMORY_ID_BLOCK:\n memory_id, pad0, pad1, pad2 = unpack_from(\"<4L\", data, offset=offset)\n if not pad0 == pad1 == pad2 == 0:\n raise SPSDKError(\"Invalid padding\")\n offset += 16\n load_data = data[offset : offset + length]\n return address, length, load_data, cmd, memory_id\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdLoad\n :raises SPSDKError: Invalid cmd_tag was found\n \"\"\"\n address, _, data, cmd_tag, memory_id = cls._extract_data(data)\n if cmd_tag not in [\n EnumCmdTag.LOAD,\n EnumCmdTag.LOAD_CMAC,\n EnumCmdTag.LOAD_HASH_LOCKING,\n EnumCmdTag.LOAD_KEY_BLOB,\n EnumCmdTag.PROGRAM_FUSES,\n EnumCmdTag.PROGRAM_IFR,\n ]:\n raise SPSDKError(f\"Invalid cmd_tag found: {cmd_tag}\")\n if cls == CmdLoadBase:\n return cls(cmd_tag=cmd_tag, address=address, data=data, memory_id=memory_id)\n # pylint: disable=no-value-for-parameter\n return cls(address=address, data=data, memory_id=memory_id) # type: ignore\n\n # pylint: disable=redundant-returns-doc\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> MainCmd:\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n assert False\n\n\nclass CmdErase(BaseCmd):\n \"\"\"Erase given address range. The erase will be rounded up to the sector size.\"\"\"\n\n def __init__(self, address: int, length: int, memory_id: int = 0) -> None:\n \"\"\"Constructor for command.\n\n :param address: Input address\n :param length: Input length\n :param memory_id: Memory ID\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.ERASE, address=address, length=length)\n self.memory_id = memory_id\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return (\n f\"ERASE: Address=0x{self.address:08X}, Length={self.length}, Memory ID={self.memory_id}\"\n )\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n data = super().export()\n data += pack(\"<4L\", self.memory_id, 0, 0, 0)\n return data\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdErase\n :raises SPSDKError: Invalid padding\n \"\"\"\n address, length = cls.header_parse(data=data, cmd_tag=EnumCmdTag.ERASE)\n memory_id, pad0, pad1, pad2 = unpack_from(\"<4L\", data, offset=16)\n if not pad0 == pad1 == pad2 == 0:\n raise SPSDKError(\"Invalid padding\")\n return cls(address=address, length=length, memory_id=memory_id)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdErase\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n length = value_to_int(config[\"size\"], 0)\n memory_id = value_to_int(config.get(\"memoryId\", \"0\"), 0)\n return CmdErase(address=address, length=length, memory_id=memory_id)\n\n\nclass CmdLoad(CmdLoadBase):\n \"\"\"Data to write follows the range header.\"\"\"\n\n def __init__(self, address: int, data: bytes, memory_id: int = 0) -> None:\n \"\"\"Constructor for command.\n\n :param address: Address for the load command\n :param data: Data to load\n :param memory_id: Memory ID\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.LOAD, address=address, data=data, memory_id=memory_id)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> Union[\"CmdLoad\", \"CmdLoadHashLocking\", \"CmdLoadCmac\"]:\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n :raises SPSDKError: Invalid configuration field.\n \"\"\"\n authentication = config.get(\"authentication\")\n address = value_to_int(config[\"address\"], 0)\n memory_id = value_to_int(config.get(\"memoryId\", \"0\"), 0)\n if authentication == \"hashlocking\":\n data = load_binary(config[\"file\"], search_paths=search_paths)\n return CmdLoadHashLocking.load_from_config(\n config, search_paths=search_paths\n ) # Backward compatibility\n if authentication == \"cmac\":\n data = load_binary(config[\"file\"], search_paths=search_paths)\n return CmdLoadCmac.load_from_config(\n config, search_paths=search_paths\n ) # Backward compatibility\n # general non-authenticated load command\n if config.get(\"file\"):\n data = load_binary(config[\"file\"], search_paths=search_paths)\n return CmdLoad(address=address, data=data, memory_id=memory_id)\n if config.get(\"values\"):\n values = [value_to_int(s, 0) for s in config[\"values\"].split(\",\")]\n data = pack(f\"<{len(values)}L\", *values)\n return CmdLoad(address=address, data=data, memory_id=memory_id)\n\n raise SPSDKError(f\"Unsupported LOAD command args: {config}\")\n\n\nclass CmdExecute(BaseCmd):\n \"\"\"Address will be the jump-to address.\"\"\"\n\n def __init__(self, address: int) -> None:\n \"\"\"Constructor for Command.\n\n :param address: Input address\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.EXECUTE, address=address, length=0)\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return f\"EXECUTE: Address=0x{self.address:08X}\"\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdExecute\n \"\"\"\n address, _ = cls.header_parse(data=data, cmd_tag=EnumCmdTag.EXECUTE)\n return cls(address=address)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdExecute\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n return CmdExecute(address=address)\n\n\nclass CmdCall(BaseCmd):\n \"\"\"Address will be the address to jump.\"\"\"\n\n def __init__(self, address: int) -> None:\n \"\"\"Constructor for Command.\n\n :param address: Input address\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.CALL, address=address, length=0)\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return f\"CALL: Address=0x{self.address:08X}\"\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdCall\n \"\"\"\n address, _ = cls.header_parse(data=data, cmd_tag=EnumCmdTag.CALL)\n return cls(address=address)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdCall\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n return CmdCall(address=address)\n\n\nclass CmdProgFuses(CmdLoadBase):\n \"\"\"Address will be address of fuse register.\"\"\"\n\n HAS_MEMORY_ID_BLOCK = False\n\n def __init__(self, address: int, data: bytes) -> None:\n \"\"\"Constructor for Command.\n\n :param address: Input address\n :param data: Input data\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.PROGRAM_FUSES, address=address, data=data)\n self.length //= 4\n\n @classmethod\n def _extract_data(cls, data: bytes) -> Tuple[int, int, bytes, int, int]:\n tag, address, length, cmd = unpack_from(cls.FORMAT, data)\n length *= 4\n memory_id = 0\n if tag != cls.TAG:\n raise SPSDKError(f\"Invalid TAG, expected: {cls.TAG}\")\n offset = BaseCmd.SIZE\n if cls.HAS_MEMORY_ID_BLOCK:\n memory_id, pad0, pad1, pad2 = unpack_from(\"<4L\", data)\n if pad0 != pad1 != pad2 != 0:\n raise SPSDKError(\"Invalid padding\")\n offset += 16\n load_data = data[offset : offset + length]\n return address, length, load_data, cmd, memory_id\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdProgFuses\n \"\"\"\n address, _, data, _, _ = cls._extract_data(data=data)\n return cls(address=address, data=data)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdProgFuses\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n fuses = [value_to_int(fuse, 0) for fuse in config[\"values\"].split(\",\")]\n data = pack(f\"<{len(fuses)}L\", *fuses)\n return CmdProgFuses(address=address, data=data)\n\n\nclass CmdProgIfr(CmdLoadBase):\n \"\"\"Address will be the address into the IFR region.\"\"\"\n\n HAS_MEMORY_ID_BLOCK = False\n\n def __init__(self, address: int, data: bytes) -> None:\n \"\"\"Constructor for Command.\n\n :param address: Input address\n :param data: Input data as bytes array\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.PROGRAM_IFR, address=address, data=data)\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdProgFuses\n \"\"\"\n address, _, data, _, _ = cls._extract_data(data=data)\n return cls(address=address, data=data)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdProgIfr\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n data = load_binary(config[\"file\"], search_paths=search_paths)\n return CmdProgIfr(address=address, data=data)\n\n\nclass CmdLoadCmac(CmdLoadBase):\n \"\"\"Load cmac. ROM is calculating cmac from loaded data.\"\"\"\n\n def __init__(self, address: int, data: bytes, memory_id: int = 0) -> None:\n \"\"\"Constructor for command.\n\n :param address: Address for the load command\n :param data: Data to load\n :param memory_id: Memory ID\n \"\"\"\n super().__init__(\n cmd_tag=EnumCmdTag.LOAD_CMAC,\n address=address,\n data=data,\n memory_id=memory_id,\n )\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdLoadCmac\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n :raises SPSDKError: Invalid configuration field.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n memory_id = value_to_int(config.get(\"memoryId\", \"0\"), 0)\n\n data = load_binary(config[\"file\"], search_paths=search_paths)\n return CmdLoadCmac(address=address, data=data, memory_id=memory_id)\n\n\nclass CmdCopy(BaseCmd):\n \"\"\"Copy data from one place to another.\"\"\"\n\n def __init__(\n self,\n address: int,\n length: int,\n destination_address: int = 0,\n memory_id_from: int = 0,\n memory_id_to: int = 0,\n ) -> None:\n \"\"\"Constructor for command.\n\n :param address: Input address\n :param length: Input length\n :param destination_address: Destination address\n :param memory_id_from: Memory ID\n :param memory_id_to: Memory ID\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.COPY, address=address, length=length)\n self.destination_address = destination_address\n self.memory_id_from = memory_id_from\n self.memory_id_to = memory_id_to\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return (\n f\"COPY: Address=0x{self.address:08X}, Length={self.length}, \"\n f\"Destination address={self.destination_address}\"\n f\"Memory ID from={self.memory_id_from}, Memory ID to={self.memory_id_to}\"\n )\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n data = super().export()\n data += pack(\"<4L\", self.destination_address, self.memory_id_from, self.memory_id_to, 0)\n return data\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdCopy\n :raises SPSDKError: Invalid padding\n \"\"\"\n address, length = cls.header_parse(data=data, cmd_tag=EnumCmdTag.COPY)\n destination_address, memory_id_from, memory_id_to, pad0 = unpack_from(\n \"<4L\", data, offset=16\n )\n if pad0 != 0:\n raise SPSDKError(\"Invalid padding\")\n return cls(\n address=address,\n length=length,\n destination_address=destination_address,\n memory_id_from=memory_id_from,\n memory_id_to=memory_id_to,\n )\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdCopy\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"addressFrom\"], 0)\n length = value_to_int(config[\"size\"], 0)\n destination_address = value_to_int(config[\"addressTo\"], 0)\n memory_id_from = value_to_int(config[\"memoryIdFrom\"], 0)\n memory_id_to = value_to_int(config[\"memoryIdTo\"], 0)\n return CmdCopy(\n address=address,\n length=length,\n destination_address=destination_address,\n memory_id_from=memory_id_from,\n memory_id_to=memory_id_to,\n )\n\n\nclass CmdLoadHashLocking(CmdLoadBase):\n \"\"\"Load hash. ROM is calculating hash.\"\"\"\n\n def __init__(self, address: int, data: bytes, memory_id: int = 0) -> None:\n \"\"\"Constructor for command.\n\n :param address: Address for the load command\n :param data: Data to load\n :param memory_id: Memory ID\n \"\"\"\n super().__init__(\n cmd_tag=EnumCmdTag.LOAD_HASH_LOCKING,\n address=address,\n data=data,\n memory_id=memory_id,\n )\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n data = super().export()\n data += bytes(64)\n return data\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdLoadHashLocking\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n :raises SPSDKError: Invalid configuration field.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n memory_id = value_to_int(config.get(\"memoryId\", \"0\"), 0)\n\n data = load_binary(config[\"file\"], search_paths=search_paths)\n return CmdLoadHashLocking(address=address, data=data, memory_id=memory_id)\n\n\nclass CmdLoadKeyBlob(BaseCmd):\n \"\"\"Load key blob.\"\"\"\n\n FORMAT = \" int:\n \"\"\"Get key ID based on family and key name.\n\n :param family: chip family\n :param key_name: NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK\n :return: integer value representing key\n \"\"\"\n key_wraps = cls._KeyWrapsV2 if \"mcxn\" in family.lower() else cls._KeyWraps\n return key_wraps[key_name.name].value\n\n def __init__(self, offset: int, data: bytes, key_wrap_id: int) -> None:\n \"\"\"Constructor for command.\n\n :param offset: Input offset\n :param key_wrap_id: Key wrap ID (NXP_CUST_KEK_INT_SK = 16, NXP_CUST_KEK_EXT_SK = 17)\n :param data: Wrapped key blob\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.LOAD_KEY_BLOB, address=offset, length=len(data))\n self.key_wrap_id = key_wrap_id\n self.data = data\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return f\"LOAD_KEY_BLOB: Offset=0x{self.address:08X}, Length={self.length}, Key wrap ID={self.key_wrap_id}\"\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n result_data = pack(\n self.FORMAT,\n self.TAG,\n self.address,\n self.key_wrap_id,\n self.length,\n self.cmd_tag,\n )\n result_data += self.data\n\n result_data = align_block(data=result_data, alignment=16, padding=0)\n return result_data\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdLoadKeyBlob\n \"\"\"\n tag, cmpa_offset, key_wrap_id, length, cmd = unpack_from( # pylint: disable=unused-variable\n cls.FORMAT, data\n )\n key_blob_data = unpack_from(f\"<{length}s\", data, cls.SIZE)[0]\n return cls(offset=cmpa_offset, key_wrap_id=key_wrap_id, data=key_blob_data)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdLoadKeyBlob\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n data = load_binary(config[\"file\"], search_paths=search_paths)\n offset = value_to_int(config[\"offset\"], 0)\n key_wrap_name = config[\"wrappingKeyId\"]\n family = config[\"family\"]\n\n key_wrap_id = cls.get_key_id(family, cls.KeyTypes[key_wrap_name])\n return CmdLoadKeyBlob(offset=offset, data=data, key_wrap_id=key_wrap_id)\n\n\nclass CmdConfigureMemory(BaseCmd):\n \"\"\"Configure memory.\"\"\"\n\n def __init__(self, address: int, memory_id: int = 0) -> None:\n \"\"\"Constructor for command.\n\n :param address: Input address\n :param memory_id: Memory ID\n \"\"\"\n super().__init__(address=address, length=0, cmd_tag=EnumCmdTag.CONFIGURE_MEMORY)\n self.memory_id = memory_id\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return f\"CONFIGURE_MEMORY: Address=0x{self.address:08X}, Memory ID={self.memory_id}\"\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n return pack(self.FORMAT, self.TAG, self.memory_id, self.address, self.cmd_tag)\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdConfigureMemory\n \"\"\"\n memory_id, address = cls.header_parse(cmd_tag=EnumCmdTag.CONFIGURE_MEMORY, data=data)\n return cls(address=address, memory_id=memory_id)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdConfigureMemory\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n memory_id = value_to_int(config[\"memoryId\"], 0)\n return CmdConfigureMemory(\n address=value_to_int(config[\"configAddress\"], 0), memory_id=memory_id\n )\n\n\nclass CmdFillMemory(BaseCmd):\n \"\"\"Fill memory range by pattern.\"\"\"\n\n def __init__(self, address: int, length: int, pattern: int) -> None:\n \"\"\"Constructor for command.\n\n :param address: Input address\n :param length: Input length\n :param pattern: Pattern for fill memory with\n \"\"\"\n super().__init__(cmd_tag=EnumCmdTag.FILL_MEMORY, address=address, length=length)\n self.pattern = pattern\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return f\"FILL_MEMORY: Address=0x{self.address:08X}, Length={self.length}, PATTERN={hex(self.pattern)}\"\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n data = super().export()\n data += pack(\"<4L\", self.pattern, 0, 0, 0)\n return data\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdErase\n :raises SPSDKError: Invalid padding\n \"\"\"\n address, length = cls.header_parse(data=data, cmd_tag=EnumCmdTag.FILL_MEMORY)\n pattern, pad0, pad1, pad2 = unpack_from(\"<4L\", data, offset=16)\n if pad0 != pad1 != pad2 != 0:\n raise SPSDKError(\"Invalid padding\")\n return cls(address=address, length=length, pattern=pattern)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdFillMemory\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n address = value_to_int(config[\"address\"], 0)\n length = value_to_int(config[\"size\"], 0)\n pattern = value_to_int(config[\"pattern\"], 0)\n return CmdFillMemory(address=address, length=length, pattern=pattern)\n\n\nclass CmdFwVersionCheck(BaseCmd):\n \"\"\"Check counter value with stored value, if values are not same, SB file is rejected.\"\"\"\n\n class CounterID(Enum):\n \"\"\"Counter IDs used by the CmdFwVersionCheck command.\"\"\"\n\n NONE = (0, \"none\")\n NONSECURE = (1, \"nonsecure\")\n SECURE = (2, \"secure\")\n RADIO = (3, \"radio\")\n SNT = (4, \"snt\")\n BOOTLOADER = (5, \"bootloader\")\n\n def __init__(self, value: int, counter_id: int) -> None:\n \"\"\"Constructor for command.\n\n :param value: Input value\n :param counter_id: Counter ID (NONSECURE = 1, SECURE = 2)\n \"\"\"\n super().__init__(address=0, length=0, cmd_tag=EnumCmdTag.FW_VERSION_CHECK)\n self.value = value\n self.counter_id = counter_id\n\n def __str__(self) -> str:\n \"\"\"Get info of command.\"\"\"\n return f\"FW_VERSION_CHECK: Value={self.value}, Counter ID={self.counter_id}\"\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n return pack(self.FORMAT, self.TAG, self.value, self.counter_id, self.cmd_tag)\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdFwVersionCheck\n \"\"\"\n value, counter_id = cls.header_parse(data=data, cmd_tag=EnumCmdTag.FW_VERSION_CHECK)\n return cls(value=value, counter_id=counter_id)\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdFwVersionCheck\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n value = value_to_int(config[\"value\"], 0)\n counter_id_str = config[\"counterId\"]\n counter_id = CmdFwVersionCheck.CounterID[counter_id_str]\n return CmdFwVersionCheck(value=value, counter_id=counter_id)\n\n\nclass CmdReset(BaseCmd):\n \"\"\"Reset command, added for SBx.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Constructor for reset command.\"\"\"\n super().__init__(address=0, length=0, cmd_tag=EnumCmdTag.RESET)\n\n def __str__(self) -> str:\n \"\"\"Get info about command.\"\"\"\n return \"RESET\"\n\n @classmethod\n def parse(cls, data: bytes) -> \"CmdReset\":\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :return: CmdReset\n \"\"\"\n _, _ = cls.header_parse(data=data, cmd_tag=EnumCmdTag.RESET)\n return cls()\n\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdReset\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n \"\"\"\n return CmdReset()\n\n\nclass CmdSectionHeader(MainCmd):\n \"\"\"Create section header.\"\"\"\n\n FORMAT = \"<4L\"\n SIZE = calcsize(FORMAT)\n\n def __init__(self, length: int, section_uid: int = 1, section_type: int = 1) -> None:\n \"\"\"Constructor for Commands section.\n\n :param section_uid: Input uid\n :param section_type: Input type\n :param length: Input length\n \"\"\"\n self.section_uid = section_uid\n self.section_type = section_type\n self.length = length\n self._pad = 0\n\n def __repr__(self) -> str:\n return f\"SB3.1 Command Section Header, Type:{self.section_type}\"\n\n def __str__(self) -> str:\n \"\"\"Get info of Section header.\"\"\"\n return f\"Section header: UID=0x{self.section_uid:08X}, Type={self.section_type}, Length={self.length}\"\n\n def export(self) -> bytes:\n \"\"\"Export command as bytes.\"\"\"\n return pack(self.FORMAT, self.section_uid, self.section_type, self.length, self._pad)\n\n @classmethod\n def parse(cls, data: bytes) -> Self:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :raises SPSDKError: Raised when FORMAT is bigger than length of the data without offset\n :return: CmdSectionHeader\n \"\"\"\n if calcsize(cls.FORMAT) > len(data):\n raise SPSDKError(\"FORMAT is bigger than length of the data without offset!\")\n section_uid, section_type, length, _ = unpack_from(cls.FORMAT, data)\n return cls(section_uid=section_uid, section_type=section_type, length=length)\n\n # pylint: disable=redundant-returns-doc\n @classmethod\n def load_from_config(\n cls, config: Dict[str, Any], search_paths: Optional[List[str]] = None\n ) -> \"CmdSectionHeader\":\n \"\"\"Load configuration from dictionary.\n\n :param config: Dictionary with configuration fields.\n :param search_paths: List of paths where to search for the file, defaults to None\n :return: Command object loaded from configuration.\n :raises SPSDKError: This situation cannot raise (the function here is just MYPY/PYLINT checks).\n \"\"\"\n raise SPSDKError(\"Section header cannot be loaded from configuration.\")\n\n\nTAG_TO_CLASS: Mapping[int, Type[BaseCmd]] = {\n EnumCmdTag.ERASE: CmdErase,\n EnumCmdTag.LOAD: CmdLoad,\n EnumCmdTag.EXECUTE: CmdExecute,\n EnumCmdTag.CALL: CmdCall,\n EnumCmdTag.PROGRAM_FUSES: CmdProgFuses,\n EnumCmdTag.PROGRAM_IFR: CmdProgIfr,\n EnumCmdTag.LOAD_CMAC: CmdLoadCmac,\n EnumCmdTag.COPY: CmdCopy,\n EnumCmdTag.LOAD_HASH_LOCKING: CmdLoadHashLocking,\n EnumCmdTag.LOAD_KEY_BLOB: CmdLoadKeyBlob,\n EnumCmdTag.CONFIGURE_MEMORY: CmdConfigureMemory,\n EnumCmdTag.FILL_MEMORY: CmdFillMemory,\n EnumCmdTag.FW_VERSION_CHECK: CmdFwVersionCheck,\n EnumCmdTag.RESET: CmdReset,\n}\n\nCFG_NAME_TO_CLASS: Mapping[str, Type[BaseCmd]] = {\n \"erase\": CmdErase,\n \"load\": CmdLoad,\n \"execute\": CmdExecute,\n \"call\": CmdCall,\n \"programFuses\": CmdProgFuses,\n \"programIFR\": CmdProgIfr,\n \"loadCMAC\": CmdLoadCmac,\n \"copy\": CmdCopy,\n \"loadHashLocking\": CmdLoadHashLocking,\n \"loadKeyBlob\": CmdLoadKeyBlob,\n \"configureMemory\": CmdConfigureMemory,\n \"fillMemory\": CmdFillMemory,\n \"checkFwVersion\": CmdFwVersionCheck,\n \"reset\": CmdReset,\n}\n\n\n########################################################################################################################\n# Command parser from raw data\n########################################################################################################################\ndef parse_command(data: bytes) -> object:\n \"\"\"Parse command from bytes array.\n\n :param data: Input data as bytes array\n :raises SPSDKError: Raised when tag is not in cmd_class\n :raises SPSDKError: Raised when tag is invalid\n :return: object\n \"\"\"\n # verify that first 4 bytes of frame are 55aaaa55\n tag = unpack_from(\" n.nom:\n plt.plot([n.coord[0], voisin[0].coord[0]], [n.coord[1], voisin[0].coord[1]], couleur_arc(n, voisin[0]))\n plt.show()\n\n# Création du réseau T1 (uniquement les noeuds)\n# Amélioration à apporter : que les noeuds sont moins collés les uns aux autres.\nréseau_T1= []\n \ndef création_réseau_T1():\n for i in range (1, nb_noeuds_T1 +1):\n réseau_T1.append(Noeud(i, \"T1\"))\n print(\"Création du réseau T1 (backbone) : {} noeuds\".format(len(réseau_T1)))\n\ncréation_réseau_T1()\naffichage_réseau(réseau_T1)\ndessine_réseau(réseau_T1)\n\n# Maillage du réseau T1 intra-backbone\n\n# on initialise à vide les voisins\nfor n in réseau_T1:\n n.voisins=[]\n\n# probabilité d'occurence d'un arc interne au réseau T1\n# Valeur de l'énoncé : 0,75\n# Remarque : régler cette valeur pour obtenir un réseau réaliste\nproba_arc_interne_T1 = 0.45\n \n# Effet : le maillage met à jour l'attribut voisins de chaque noeud\ndef maillage_intra_T1():\n print(\"Maillage de chaque noeud T1 vers {:.0%} des autres noeuds T1.\".format(proba_arc_interne_T1))\n nb_arcs=0\n for n1 in réseau_T1:\n for n2 in réseau_T1:\n if n2.nom > n1.nom:\n # un arc est crée dans 75 % des cas\n if random() < proba_arc_interne_T1:\n valeur=uniform(5 , 10)\n # on crée un voisin pour n1 et pour n2 (arc dans les deux sens)\n n1.voisins.append([n2, valeur])\n n2.voisins.append([n1, valeur])\n nb_arcs=nb_arcs+1\n print(\"Nombre d'arcs intra-T1 créés : {}\".format(nb_arcs))\n\nmaillage_intra_T1()\naffichage_réseau(réseau_T1, voisins=True)\ndessine_réseau(réseau_T1)\nréseau_T2 = []\n\n \ndef création_réseau_T2():\n # on crée les noeuds de T2 en leur donnant des noms entiers à la suite de ceux du T1.\n # Typiquement, si on crée 20 noeuds, les noms vont de 11 à 30.\n for i in range (len(réseau_T1)+1, len(réseau_T1)+nb_noeuds_T2+1):\n réseau_T2.append(Noeud(i,\"T2\"))\n print(\"Création du réseau T2 (transit) : {} noeuds\".format(len(réseau_T2)))\n\ncréation_réseau_T2()\naffichage_réseau(réseau_T2)\ndessine_réseau(réseau_T2)\n\n# Maillage du réseau de transit\n \ndef maillage_T2():\n\n # on initialise à vide les voisins\n for n in réseau_T2:\n n.voisins=[]\n \n print(\"Maillage de chaque noeud T2 vers un ou deux noeuds T1.\")\n nb_arcs_T2_T1 = 0\n for n2 in réseau_T2:\n # on sélectionne aléatoirement un ou deux noeuds du T1\n noeuds_T1_choisis=sample(réseau_T1, choice([1, 2]))\n for n1 in noeuds_T1_choisis:\n valeur=uniform(10,20)\n n2.voisins.append([n1, valeur])\n n1.voisins.append([n2, valeur])\n nb_arcs_T2_T1 = nb_arcs_T2_T1 + 1\n print(\"Nombre d'arcs T2-T1 créés : {}\".format(nb_arcs_T2_T1))\n \n print(\"Maillage de chaque noeud T2 à 2 ou 3 autres noeuds de T2.\")\n nb_arcs_T2_T2 = 0\n for n2 in réseau_T2:\n # on selectionne aléatoirement 2 ou 3 autres noeuds du réseau T2\n # On crée une copie des noeuds du réseau de transit\n L=réseau_T2.copy()\n # on enlève le noeud n2 de cette copie\n L.remove(n2)\n noeuds_T2_choisis=sample(L, choice([2, 3]))\n for nc in noeuds_T2_choisis:\n if nc.nom > n2.nom:\n # On crée un arc entre le noeud n2 et nc après avoir calculé sa valeur :\n valeur=uniform(10,20)\n n2.voisins.append([nc, valeur])\n nc.voisins.append([n2, valeur])\n nb_arcs_T2_T2 = nb_arcs_T2_T2 +1\n print(\"Nombre d'arcs T2-T2 créés : {}\".format(nb_arcs_T2_T2)) \n\nmaillage_T2()\naffichage_réseau(réseau_T1, voisins=True)\naffichage_réseau(réseau_T2, voisins=True)\ndessine_réseau(réseau_T1+réseau_T2)\n\nréseau_T3 = []\n \ndef création_réseau_T3():\n for i in range (len(réseau_T1)+len(réseau_T2)+1, len(réseau_T1)+len(réseau_T2)+nb_noeuds_T3+1):\n réseau_T3.append(Noeud(i,\"T3\"))\n print(\"Création du réseau T3 (local) : {} noeuds\".format(len(réseau_T3)))\n\ncréation_réseau_T3()\naffichage_réseau(réseau_T3)\ndessine_réseau(réseau_T3)\n\n# maillage du réseau T3\n# Chaque noeud du T3 est relié à 2 noeuds du T2 \n# Chaque noeud du T3 est relié à 1 autre noeud du T3\n# Les liens sont valués par une valeur comprise entre 15 et 20\n \ndef maillage_réseau_T3():\n print(\"Maillage de chaque noeud T3 vers 2 noeuds du T2.\")\n nb_noeuds_T3_T2 = 0\n for n3 in réseau_T3:\n # on sélectionne aléatoirement 2 noeuds du T2\n noeuds_T2_choisis=sample(réseau_T2, 2)\n for n2 in noeuds_T2_choisis:\n valeur=uniform(15, 20)\n n3.voisins.append([n2, valeur])\n n2.voisins.append([n3, valeur])\n nb_noeuds_T3_T2 = nb_noeuds_T3_T2 +1\n print(\"Nombre d'arcs T3-T2 : {}\".format(nb_noeuds_T3_T2))\n \n print(\"Maillage de chaque noeud T3 vers 1 autre noeud T3.\")\n nb_noeuds_T3_T3 = 0\n #Pour relier les noeuds du T3 2 à 2,\n # On fait une boucle avançant d'un pas de 2 \n for i in range (0, nb_noeuds_T3-1, 2):\n # création d'un arc reliant 2 noeuds du T3\n valeur=uniform(15, 20)\n réseau_T3[i].voisins.append([réseau_T3[i+1], valeur])\n réseau_T3[i+1].voisins.append([réseau_T3[i], valeur])\n nb_noeuds_T3_T3 = nb_noeuds_T3_T3 +1\n print(\"Nombre d'arcs T3-T3 : {}\".format(nb_noeuds_T3_T3))\n\nmaillage_réseau_T3()\naffichage_réseau(réseau_T2, voisins=True)\naffichage_réseau(réseau_T3, voisins=True)\ndessine_réseau(réseau_T1+réseau_T2+réseau_T3)\n# fonction appelée récursivement\n# - on marque le noeud n\n# - on recherche son premier voisin non marqué\n# - on appelle la fonction avec ce vosin non marqué\ndef explorer_a_partir_du_noeud(n):\n # on marque le noeud n\n n.marque = True\n #print(\"Noeud exploré : {}\".format(n))\n # On recherche le premier voisin du noeud non marqué\n for v in n.voisins:\n if v[0].marque == False:\n # on applique la même fonction à ce noeud\n explorer_a_partir_du_noeud(v[0])\n \ndef vérification_connectivité(graphe, nd):\n # graphe est une liste de noeuds\n # nd est le noeud de départ\n # On met toutes les marques à False\n for n in graphe:\n n.marque=False\n \n explorer_a_partir_du_noeud(nd)\n \n # On vérifie s'il reste des neoeuds non marqués\n nb_noeuds_isolés = 0\n for n in graphe:\n if n.marque == False:\n nb_noeuds_isolés = nb_noeuds_isolés +1 \n print(\"Noeud isolé : {}\".format(n))\n print(\"Nombre de noeuds isolés : {}\".format(nb_noeuds_isolés))\n\nvérification_connectivité(réseau_T1 + réseau_T2 + réseau_T3, réseau_T3[0])\n#vérification_connectivité(réseau_T3, réseau_T3[0])\n\n# Entrées :\n# graphe est une liste des noeuds du graphe. ex : réseau_T1 + réseau_T2+ réseau_T3\n# nd est le noeud de départ\n# Effet :\n# Calcule les plus courts chemins (PCCH) de nd à tous les autres noeuds.\n# Inscrit pour chaque noeud n:\n# marque : valeur du PCCH de nd à n.\n# prédecesseur : noeud qui permet d'atteindre n dans le PPCH\ndef plus_courts_chemins(nd, graphe):\n # On initialise toutes les marques des noeuds à l'infini (inf) sauf la marque de nd qui est initailisée à 0.\n for n in graphe:\n n.marque=inf\n nd.marque=0\n\n # liste des noeuds à visiter\n # Elle est initialisée par la copie des noeuds du graphe.\n noeuds_à_visiter = graphe.copy()\n \n # Tant qu'il reste des noeuds à visiter\n while len(noeuds_à_visiter)!=0:\n # On cherche le noeud à visiter ayant la marque minimum.\n # On utilise ici la fonction min avec le paramètre key indiquant avec une fonction lambda la valeur à tester.\n noeud_minimum = min(noeuds_à_visiter, key = lambda x: x.marque)\n #print(\"noeud minimum : \", noeud_minimum)\n\n # on explore les voisins du noeud minimum\n for voisin in noeud_minimum.voisins:\n if noeud_minimum.marque + voisin[1] < voisin[0].marque:\n voisin[0].marque = noeud_minimum.marque + voisin[1]\n voisin[0].prédécesseur = noeud_minimum\n # On retire le noeud_minimum de la liste des noeuds à visiter\n noeuds_à_visiter.remove(noeud_minimum)\n \n#plus_courts_chemins(réseau_T1[0], réseau_T1 + réseau_T2+ réseau_T3) \n#plus_courts_chemins(réseau_T1[0], réseau_T1)\n#affichage_réseau(réseau_T1 + réseau_T2+ réseau_T3, voisins=True, marque=True, pred=True)\n# Entrées :\n# nd : noeud de départ\n# graphe : liste de noeuds de la classe Noeud.\n# Contexte : on a auparavant calculé les plus courts chemins du noeud nd à tous les autres\n# Fonction : \ndef fabrication_table_routage_pour_noeud_cible(nd, graphe):\n #print(\"Noeud nd : {}\".format(nd))\n # on parcourt tous les noeuds n du graphe (sauf nd)\n for n in graphe:\n if n != nd:\n # on va remonter les prédécesseurs de n jusqu'à ce que l'on tombe sur nd\n nx = n\n pred=None\n while nx != nd:\n pred=nx.prédécesseur\n # on met à jour la table de routage de pred\n # La table dit : Quand on est sur pred, pour atteindre n, pendre le voisin nx\n pred.table_routage[n]=nx\n nx=pred\n\n#fabrication_table_routage_pour_noeud_cible(réseau_T1[0], réseau_T1 + réseau_T2+ réseau_T3)\n\n\ndef fabrications_toutes_tables_routage(graphe):\n for n in graphe:\n n.table_routage = {}\n for n in graphe:\n plus_courts_chemins(n, graphe)\n fabrication_table_routage_pour_noeud_cible(n, graphe)\n\nfabrications_toutes_tables_routage(réseau_T1 + réseau_T2+ réseau_T3)\n\ndef affiche_chemin(ne, nd):\n # ne : nord émetteur\n print(\"Plus court chemin de {} à {}\".format(ne, nd))\n n=ne\n plt.scatter(nd.coord[0], nd.coord[1], color=couleur_noeud(nd), s=30)\n while n != nd:\n print(\"{}-{}\".format(n, n.table_routage[nd]))\n plt.plot([n.coord[0], n.table_routage[nd].coord[0]], [n.coord[1], n.table_routage[nd].coord[1]], couleur_arc(n, n.table_routage[nd]))\n plt.scatter(n.coord[0], n.coord[1], color=couleur_noeud(n), s=30)\n n=n.table_routage[nd]\nplt.show()\n\naffiche_chemin(choice(réseau_T1), choice(réseau_T3))\n\n#affichage_réseau(réseau_T1+réseau_T2+réseau_T3, voisins=True, marque=True, pred=True, table=True)","repo_name":"Lysa14/projet_algo","sub_path":"reseau.py","file_name":"reseau.py","file_ext":"py","file_size_in_byte":12532,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13784206805","text":"#=============================================================\n# This code is inteded to run a trained agent on some basic\n# experiment scenarios to see how the agents drive in carla.\n#\n# This code is adapted from:\n# https://github.com/carla-simulator/driving-benchmarks/blob/master/benchmarks_084.py\n#\n#=============================================================\n\n\n\"\"\"\nCommand example:\n```console\n$ python enjoy.py \\\n --gpu 0 \\\n --port 2000 \\\n --agent MTA \\\n --city-name Town01 \\\n --verbose \\\n --continue-experiment\n```\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport time\nimport tensorflow as tf\nfrom pathlib import Path\n\nfrom driving_benchmarks.version084.benchmark_tools import run_driving_benchmark\nfrom driving_benchmarks.version084.driving_benchmarks import BasicExperimentSuite\nfrom model.agents import BaselineAgent, MTAAgent, CILRSAgent, MTAgent\n\n\nif __name__ == '__main__':\n\n argparser = argparse.ArgumentParser(description=__doc__)\n argparser.add_argument(\n '-v', '--verbose',\n action='store_true',\n dest='verbose',\n help='print extra status information at every timestep')\n argparser.add_argument(\n '-db', '--debug',\n action='store_true',\n dest='debug',\n help='print debug information')\n argparser.add_argument(\n '--host',\n metavar='H',\n default='localhost',\n help='IP of the host server (default: localhost)')\n argparser.add_argument(\n '-p', '--port',\n metavar='P',\n default=2000,\n type=int,\n help='TCP port to listen to (default: 2000)')\n argparser.add_argument(\n '-c', '--city-name',\n metavar='C',\n default='Town01',\n help='The town that is going to be used on benchmark'\n + '(needs to match active town in server, options: Town01 or Town02)')\n argparser.add_argument(\n '-n', '--log-name',\n metavar='T',\n default='enjoy',\n help='The name of the log file to be created by the benchmark'\n )\n argparser.add_argument(\n '--log-path',\n metavar='PATH',\n default='/tmp/multitask_with_attention/enjoy/',\n help='The name of the log file to be created by the benchmark'\n )\n argparser.add_argument(\n '--continue-experiment',\n action='store_true',\n help='If you want to continue the experiment with the same name'\n )\n argparser.add_argument(\n '-g', '--gpu',\n default='0',\n type=str,\n help='GPU ID'\n )\n argparser.add_argument(\n '-a', '--agent',\n default='MTA',\n choices=['baseline', 'MTA', 'CILRS', 'MT'],\n help='Agent to test'\n )\n argparser.add_argument(\n '--record',\n action='store_true',\n help='Record rendered information as mp4 video'\n )\n args = argparser.parse_args()\n\n\n # Logging config\n if args.debug:\n log_level = logging.DEBUG\n elif args.verbose:\n log_level = logging.INFO\n else:\n log_level = logging.WARNING\n logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)\n logging.info('listening to server %s:%s', args.host, args.port)\n\n # GPU configuration\n os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n physical_devices = tf.config.list_physical_devices('GPU')\n if len(physical_devices):\n for device in physical_devices:\n tf.config.experimental.set_memory_growth(device, True)\n logging.info('memory growth:', tf.config.experimental.get_memory_growth(device))\n else:\n logging.info('Not enough GPU hardware devices available')\n\n # Configs\n Path(args.log_path).mkdir(exist_ok=True)\n video_log_dir = str(Path(args.log_path) / 'video')\n has_display = True\n seq_len = 1\n camera_size = (160, 384, 3)\n\n # Initialize agent\n if args.agent == 'baseline':\n weight_path = 'ckpts/baseline/ckpt'\n agent = BaselineAgent(camera_size, weight_path, seq_len,\n has_display, args.record, video_log_dir)\n elif args.agent == 'MTA':\n weight_path = 'ckpts/MTA/ckpt'\n agent = MTAAgent(camera_size, weight_path, seq_len,\n has_display, args.record, video_log_dir)\n elif args.agent == 'CILRS':\n weight_path = 'ckpts/CILRS/ckpt'\n agent = CILRSAgent(camera_size, weight_path,\n has_display, args.record, video_log_dir)\n else:\n weight_path = 'ckpts/MT/ckpt'\n agent = MTAgent(camera_size, weight_path,\n has_display, args.record, video_log_dir)\n\n # Build experiment suit and run experiment\n experiment_suite = BasicExperimentSuite(args.city_name)\n enter = time.time()\n run_driving_benchmark(agent, experiment_suite, args.city_name,\n args.log_name, args.log_path, args.continue_experiment,\n args.host, args.port)\n end = time.time()\n print(f'Time taken: {end - enter:.0f} s')\n\n","repo_name":"KeishiIshihara/multitask-with-attention","sub_path":"enjoy.py","file_name":"enjoy.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"10674956854","text":"for tc in range(1, 11):\n N = int(input()) # 테이블 한 변의 길이\n table = [list(map(int, input().split())) for _ in range(N)] # 테이블\n\n cnt = 0 # 교착상태의 갯수\n stopping = False # 교착 가능성\n\n # 어차피 N 자성체(1)은 아래로 S 자성체(2)는 위로 올라가니까 테이블을 열 우선 순회하며 1 아래 2가 있을때마다 교착 갯수를 세면 그게 정답 아닐까?\n for i in range(N):\n for j in range(N):\n if table[j][i] == 1:\n stopping = True\n\n if stopping and table[j][i] == 2:\n stopping = False\n cnt += 1\n\n stopping = False\n\n print(f'#{tc} {cnt}')","repo_name":"calendar2/algorithm","sub_path":"python/swea/0825/swea_1220.py","file_name":"swea_1220.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15630894487","text":"import csv\nimport re\nimport operator\nfrom io import StringIO\nfrom datetime import timedelta\nfrom classes import Member, Team, Checkpoint, Startpoint, Finishpoint\n\nfirst_cp_column = 10\n\nfields_order = {\n 'name': 0,\n 'bib': 1,\n 'points': 8,\n 'start_time': 4,\n 'finish_time': 3,\n 'time': 9\n}\n\ndef str_to_time(s):\n match = re.match('(\\d+):(\\d\\d):(\\d\\d)',s)\n\n if not match:\n match = re.match('()(\\d+):(\\d\\d)',s)\n\n if match:\n h = int(match.group(1) or 0)\n m = int(match.group(2))\n s = int(match.group(3))\n return timedelta(hours=h, minutes=m, seconds=s)\n else:\n raise Exception(s)\n\ndef parse_teams(csv_filename):\n with open(csv_filename, newline='') as fd:\n data = fd.read()\n csvreader = csv.reader(StringIO(data), delimiter=';')\n teams = {}\n event_title = ''\n for row in csvreader:\n if row[0] == 'event_title':\n event_title = row[1]\n continue\n member = Member()\n if len(row) >= first_cp_column:\n member.first_name = ''\n member.last_name = row[fields_order['name']].title()\n member.bib = row[fields_order['bib']]\n print(member.bib, member.last_name)\n member.team_bib = member.bib\n member.team_name = ''\n member.points = row[fields_order['points']]\n member.time = str_to_time(row[fields_order['time']])\n\n start_time = str_to_time(row[fields_order['start_time']])\n prev_time = start_time\n for i in range(first_cp_column, len(row), 2):\n cp = Checkpoint()\n cp.id = row[i]\n if cp.id:\n cp.id = int(cp.id)\n cp.points = cp.id//10\n abs_time = prev_time\n if row[i + 1]:\n abs_time = str_to_time(row[i + 1])\n cp.split = abs_time - prev_time\n prev_time = abs_time\n cp.time = abs_time - start_time\n member.sum += cp.points\n member.route.append(cp)\n\n if len(member.route) < 1:\n return\n\n start = Startpoint()\n member.route.insert(0, start)\n\n finish = Finishpoint()\n finish.time = member.time\n nCps = len(member.route)\n for i in range(nCps):\n finish.split = member.time - member.route[nCps - 1 - i].time\n if finish.split > timedelta():\n break\n member.route.append(finish)\n\n bib = member.team_bib\n if bib not in teams:\n teams[bib] = Team()\n teams[bib].members.append(member)\n return teams, event_title\n\ndef parse_splits_csv(csv_filename):\n teams,event_title = parse_teams(csv_filename)\n teams_list = []\n for bib in teams:\n team = teams[bib]\n nMembers = len(team.members)\n member = team.members[nMembers-1]\n team.bib = bib\n team.points = int(member.points)\n team.time = member.time\n team.route = member.route\n team.sum = member.sum\n team_name = team.members[0].team_name\n team.team_name = team_name\n for m in team.members:\n if m.team_name != team_name:\n team.team_name += ' - ' + m.team_name\n\n teams_list.append(team)\n\n teams_list.sort(reverse=False, key=operator.attrgetter('time'))\n teams_list.sort(reverse=True, key=operator.attrgetter('points'))\n\n for i in range(len(teams_list)):\n teams_list[i].place = i+1\n\n return {'Абсолют': teams_list}, event_title\n\n\n\n \n\n","repo_name":"sembruk/RogainingRoutes","sub_path":"splits_csv.py","file_name":"splits_csv.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25860733242","text":"#In the name of GOD\n#! use/bin/env python\n\nfrom flask import Flask, render_template, request, redirect , url_for , json\nimport os\nfrom time import sleep\nfrom werkzeug.utils import secure_filename\n# from flask_mail import Mail, Message\nfrom jinja2 import TemplateNotFound\nfrom wxsq import wxsqins\nimport gene\n\nimport csv\nimport smtplib\nfrom email.message import EmailMessage\n\n# configure app\napp = Flask(__name__)\n\n\napp.config.from_object(__name__)\napp.config['UPLOAD_FOLDER'] = os.getcwd()+'\\\\'+'members\\\\'\n\nmmdata = []\nmmid = ''\nmmdr = ''\n\n# config parameter\nDEBUG = True\nMAIL_SERVER = u'smtp.gmail.com'\nMAIL_USERNAME = u'srcfount14@gmail.com'\nMAIL_PASSWORD = u'Pooy@1347'\nMAIL_PORT = 587\nMAIL_USE_SSL = True\nMAIL_USE_TLS = False\n\ndef postmail(data):\n #print(data)\n BodyMail = 'name: '+data[0]+'\\n'+'email: '+data[1]+'\\n'+'select: '+data[2]+'\\n'+'terms: '+data[3]+'\\n'+'message :\\n'+data[4]+'\\n'\n\n msg = EmailMessage()\n msg['Subject'] = 'New Message'\n msg['From'] = MAIL_USERNAME\n msg['To'] = 'pooyagheyami@gmail.com'\n msg.set_content(BodyMail)\n #print(msg)\n server = smtplib.SMTP(MAIL_SERVER,MAIL_PORT)\n server.starttls()\n #server.set_debuglevel(1)\n server.login(MAIL_USERNAME, MAIL_PASSWORD) # user & password\n server.send_message(msg)\n server.quit()\n\n@app.route(\"/\" , methods=['POST','GET'])\n@app.route(\"/index.html\", methods=['POST','GET'])\ndef index():\n title='SrcFount'\n if request.method == 'POST':\n name = request.form.get(\"name\")\n emil = request.form.get(\"email\")\n msge = request.form.get(\"message\")\n term = request.form.get(\"terms\")\n\n if name == '' or emil == '':\n return 'error ' # redirect(\"/#Question\")\n else:\n file = open(\"qustion.csv\", \"a\")\n writer = csv.writer(file)\n writer.writerow((name, emil, \"From Contact\", term, msge))\n file.close()\n postmail([name, emil, \"From Contact\", term, msge])\n return 'success'\n else:\n try:\n return render_template(\"index.html\", mytitle=title)\n except TemplateNotFound:\n return 'I Do Not Find This page' #abort(404)\n\n@app.route(\"/terms-conditions.html\")\ndef terms():\n #title='SrcFount-terms'\n try:\n return render_template(\"terms-conditions.html\")\n except TemplateNotFound:\n return 'I Do Not Find This Page'\n\n@app.route(\"/privacy-policy.html\",methods=['POST','GET'])\ndef privacy():\n #title='SrcFount-privacy'\n if request.method == 'POST':\n name = request.form.get(\"name\")\n emil = request.form.get(\"email\")\n slct = request.form.get(\"select\")\n term = request.form.get(\"terms\")\n msge = 'this message sended from privacy-policy'\n if name == '' or emil == '':\n return 'error ' # redirect(\"/#Question\")\n else:\n file = open(\"qustion.csv\", \"a\")\n writer = csv.writer(file)\n writer.writerow((name, emil, slct, term, msge))\n file.close()\n postmail([name, emil, slct, term, msge])\n return 'success'\n else:\n try:\n return render_template(\"privacy-policy.html\")\n except TemplateNotFound:\n return 'I Do Not Find This Page'\n\n@app.route(\"/conect\",methods=['POST','GET'])\ndef conect():\n if request.method == 'POST':\n name = request.form.get(\"name\")\n emil = request.form.get(\"email\")\n msge = request.form.get(\"message\")\n term = request.form.get(\"terms\")\n\n if name == '' or emil == '':\n return 'error ' # redirect(\"/#Question\")\n else:\n file = open(\"qustion.csv\", \"a\")\n writer = csv.writer(file)\n writer.writerow((name, emil, msge, term))\n file.close()\n postmail([name, emil, msge, term])\n return 'success'\n\n\n@app.route(\"/Memform.html\",methods=['POST','GET'])\ndef memform():\n sleep(3)\n #print(mmdata)\n if request.method == 'POST' :\n #print(request.files)\n insert(request.form,mmid)\n insinfo(request.form,mmid)\n if 'file1' in request.files:\n file = request.files['file1']\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], mmdr+'\\\\'+filename))\n #print(\"saved file successfully\")\n if 'file2' in request.files:\n file = request.files['file2']\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], mmdr + '\\\\' + filename))\n #print(\"saved file successfully\")\n\n return render_template(\"success.html\")\n\n else:\n try:\n return render_template(\"Memform.html\",mydata=mmdata)\n except TemplateNotFound:\n return 'I Do Not Find This Page'\n\n\n\ndef insert(data,mid):\n D0 = mid\n D1 = data['srefr']\n D2 = data['nrefr']\n D3 = data['sdata']\n D4 = data['ndata']\n D5 = data['sftur']\n D6 = data['nftur']\n recrd = [D0,D1,D2,D3,D4,D5,D6]\n wxsqins(\"SF.db\",\"request\",\"memid, refr_serv, refr_need, data_serv, data_need, ftur_serv, ftur_need \", recrd)\n\n\ndef insinfo(data,mid):\n D0 = mid\n D1 = data['mweb']\n if 'http' in D1:\n tid = '001'\n else:\n tid = '002'\n rcord = [D0,D1,tid]\n wxsqins(\"SF.db\",\"meminfo\",\"memid , info , titid \", rcord)\n\n@app.route(\"/enrol\",methods=['POST','GET'])\ndef enrol():\n name = request.form['name']\n emil = request.form['email']\n phon = request.form['phone']\n slct = request.form['select']\n term = request.form['terms']\n global mmdata,mmid,mmdr\n mmdata = request.form\n #print(name,emil,phon,slct,term)\n if term == \"Agreed-to-Terms\":\n mygn = gene.Gnrat_name(name,phon)\n mmid = mygn[0]\n mmdr = mygn[1]\n\n if mygn == '':\n return \"id has exist\"\n else:\n mydata = [mygn[0] , name , emil , phon , slct , mygn[1] ]\n wxsqins(\"SF.db\",\"member\",\" memid , name , email , phone , slect , dirct \",mydata)\n return 'success'\n\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"pooyagheyami/SrcFount","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33016399547","text":"from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer\nfrom CMGTools.ttbar.analyzers.BTagSF import BTagSF\n\nclass BJetAnalyzer(Analyzer):\n \n def __init__(self, cfg_ana, cfg_comp, looperName):\n super(BJetAnalyzer, self).__init__(cfg_ana, cfg_comp, looperName)\n self.btagSF = BTagSF(0, wp='loose', year = self.cfg_ana.year, tagger = self.cfg_ana.tagger)\n\n def process(self, event):\n '''Adds the is_btagged attribute to the jets of the\n given jets collection.\n '''\n #https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation94X\n #https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation2016Legacy\n\n\n sfb_weight = 1.\n sfb_weightup = 1.\n sfb_weightdown = 1.\n sfc_weight = 1.\n sfc_weightup = 1.\n sfc_weightdown = 1.\n sfl_weight = 1.\n sfl_weightup = 1.\n sfl_weightdown = 1.\n \n jets = getattr(event, self.cfg_ana.jets)\n for jet in jets:\n if self.cfg_ana.year == '2016': \n if self.cfg_ana.tagger == 'DeepCSV' :\n csv = jet.btag(\"pfDeepCSVJetTags:probb\") + jet.btag(\"pfDeepCSVJetTags:probbb\")\n csv_cut = 0.2217\n if self.cfg_ana.tagger == 'DeepJet' :\n csv = jet.btag(\"pfDeepFlavourJetTags:probb\") + jet.btag(\"pfDeepFlavourJetTags:probbb\") + jet.btag(\"pfDeepFlavourJetTags:problepb\")\n csv_cut = 0.0614\n if self.cfg_ana.tagger == 'CSVv2' :\n csv = jet.btag(\"pfCombinedInclusiveSecondaryVertexV2BJetTags\")\n csv_cut = 0.5803 #assumption to keep it same as 2017, no SFs are actually provided for CSVv2 in 2016.\n else: \n if self.cfg_ana.tagger == 'DeepCSV' :\n csv = jet.btag(\"pfDeepCSVJetTags:probb\") + jet.btag(\"pfDeepCSVJetTags:probbb\")\n csv_cut = 0.1522\n if self.cfg_ana.tagger == 'DeepJet' :\n csv = jet.btag(\"pfDeepFlavourJetTags:probb\") + jet.btag(\"pfDeepFlavourJetTags:probbb\") + jet.btag(\"pfDeepFlavourJetTags:problepb\")\n csv_cut = 0.0521 #not sure if this will work on 2017 as the twiki says one needs to run recipe to obtain this on MiniAOD.\n if self.cfg_ana.tagger == 'CSVv2' :\n csv = jet.btag(\"pfCombinedInclusiveSecondaryVertexV2BJetTags\")\n csv_cut = 0.5803 \n \n jet.is_btagged = self.btagSF.isBTagged(jet, pt=jet.pt(),\n eta =jet.eta(),\n csv = csv,\n jetflavor=abs(jet.hadronFlavour()),\n is_data=not self.cfg_comp.isMC,\n csv_cut=csv_cut)\n \n if(jet.btagWeight > 0 and abs(jet.hadronFlavour()) == 5):\n sfb_weight *= jet.btagWeight\n sfb_weightup *= jet.btagWeightUp\n sfb_weightdown *= jet.btagWeightDown\n\n if(jet.btagWeight > 0 and abs(jet.hadronFlavour()) == 4):\n sfc_weight *= jet.btagWeight\n sfc_weightup *= jet.btagWeightUp\n sfc_weightdown *= jet.btagWeightDown\n \n else: \n sfl_weight *= jet.btagWeight\n sfl_weightup *= jet.btagWeightUp\n sfl_weightdown *= jet.btagWeightDown\n\n \n setattr(event, 'sfbWeight', sfb_weight)\n setattr(event, 'sfbWeightUp', sfb_weightup)\n setattr(event, 'sfbWeightDown', sfb_weightdown)\n setattr(event, 'sfcWeight', sfc_weight)\n setattr(event, 'sfcWeightUp', sfc_weightup)\n setattr(event, 'sfcWeightDown', sfc_weightdown)\n setattr(event, 'sflWeight', sfl_weight)\n setattr(event, 'sflWeightUp', sfl_weightup)\n setattr(event, 'sflWeightDown', sfl_weightdown)\n\n event.eventWeight *= event.sfbWeight\n \n \n\n# CSVv2 \"pfCombinedInclusiveSecondaryVertexV2BJetTags\" loose : 0.5803 \n# DeepCSV \"pfDeepCSVJetTags:probb + pfDeepCSVJetTags:probbb\" loose : 0.1522 \n\n","repo_name":"aureliencarle/ttbar-analysis-heppy-DEPRECATED","sub_path":"ttbar/python/analyzers/BJetAnalyzer.py","file_name":"BJetAnalyzer.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20759839564","text":"graph_1 = {'E1':['I','J','H'],\n 'E2':['J','F'], \n 'E3':['A','R'],\n 'J':['E1','E2','G','H','I','F'], \n 'F':['R','C','B','D','G','J','E2'], \n 'G':['E','F','J'],'H':['E','I','E1','J'], \n 'I':['E','H','J','E1'], 'R':['B', 'C','F','E3'], \n 'C':['B','R','F'], 'B':['D','A','F','C','R'], \n 'E':['K','G','H','I'], 'K':['L','D','E'], \n 'L':['O','D','K'], \n 'O':['P','D','L'], 'P':['O','D','A'], \n 'A':['D','P','B','E3'],\n 'D':['O','P','A','B','F','K','L'] }\n\n#use del to delete the variable\n#variableName.clear() to clear the data\n\n#print(graph['A'])\n#print(len(graph))\n#print(str(graph_1))\n#print('T' in graph)\n\ndef find_path_depth(graph, start, end, path=[]):\n path = path + [start]\n if(start == end): #si es el mismo\n return path\n if not start in graph: #si se escribe algo que no esté\n return None\n if not end in graph: #si el final no está\n return None\n for node in graph[start]: #'node' toma el valor de la lista en la llave\n if node not in path: #que no se haya visitado\n newpath = find_path_depth(graph,node,end,path) #se vuelve a empezar desde el primer nodo encontrado\n if newpath: #evita bucles inecesarios\n return newpath\n return None\n\ndef find_shortest_path(graph, start, end, path=[]):\n path = path + [start]\n if (start == end):\n return path\n if not start in graph:\n return None\n if not end in graph:\n return None\n shortest = None\n for node in graph[start]:\n if node not in path:\n newpath = find_shortest_path(graph, node, end, path)\n if newpath:\n if not shortest or len(newpath) < len(shortest):\n shortest = newpath\n return shortest\n\nsomething = find_path_depth(graph_1,'E1','P')\nprint(something)\nvar = find_shortest_path(graph_1, 'E1', 'P')\nprint(var)\n","repo_name":"CesarDevs/Programacion","sub_path":"Programacion/Inteligencia artificial/Grafos/graph MARKUS 2.py","file_name":"graph MARKUS 2.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7303838264","text":"# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\nimport re\nimport psycopg2\nimport json\n\ndef RetornaListaMobs(mobFile):\n\tmobs = []\n\twith open(mobFile, \"r\") as fd:\n\t\tlines = fd.read().splitlines()\n\t\tfor line in lines:\n\t\t\tmobs.append(line)\n\treturn mobs\n\ndef RetornaEncontrados(mobsList, htmlPath):\n\tdicionarioDosMortosOntem = []\n\twith open(htmlPath,\"r\") as f:\n\t\ttexto = f.read()\n\t\tencontrado = re.search(\"\"\"(?<=DataRow\">).+(?=\"\"\",\"\")\n\t\t\tpreTexto = preTexto.replace(\"\"\"\"\"\",\"\")\n\t\t\tpreTexto = preTexto.replace(\"\"\"\"\"\",\"\")\n\t\t\tpreTexto = preTexto.replace(\"\"\"\"\"\",\";\")\n\t\t\tpreTexto = preTexto.replace(\"\",\"\")\n\t\t\tpreTexto = preTexto.replace(\"\"\"\"\"\",\"\")\n\t\t\ttextoFiltrado = preTexto.lower()\n\t\t\ttudoSplitado = textoFiltrado.split(\";\")\n\t\t\tfor\tmob in mobsList:\n\t\t\t\tif mob.lower() in tudoSplitado:\n\t\t\t\t\tmobIndex = tudoSplitado.index(mob.lower())\n\t\t\t\t\tif mobIndex > 0 and ( (int(tudoSplitado[mobIndex+1])) > 0 or (int(tudoSplitado[mobIndex+2])) > 0 ):\n\t\t\t\t\t\tdicionarioDosMortosOntem.append(mob)\n\treturn dicionarioDosMortosOntem\n\n\ndef GetDatabaseConnection(configJson):\n\ttry:\n\t\tconn = psycopg2.connect(\"dbname='\"+configJson[\"database\"]+\"' user='\"+configJson[\"user\"]+\"' host='\"+configJson[\"host\"]+\"' password='\"+configJson[\"passwd\"]+\"'\")\n\t\treturn conn\n\texcept Exception as e:\n\t\tprint(\"Connection database failed.\")\n\ndef CloseConnection(connection):\n\ttry:\n\t\tconnection.close()\n\texcept Exception as e:\n\t\tprint(\"Connection Close Failed\")\n\ndef saveOnDatabase(cursor, mobList):\n\tfor mob in mobList:\n\t\ttry:\n\t\t\tif(\"'\" in mob):\n\t\t\t\tmob = mob.replace(\"'\",\"\")\n\t\t\tsql = \"insert into historico (bossname,killeddate,insertiondate, server) values ('\"+mob+\"',current_date-1, current_date, 'Belobra')\"\n\t\t\tcursor.execute(sql)\n\t\texcept Exception as e:\n\t\t\tprint('Error on saving result. [Method: saveOnDatabase]')\n\t\t\tprint(str(e))\n\ndef ReadConfig():\n\tp = Path(str(Path().absolute())+\"/config.json\")\n\tif p.exists():\n\t\twith open(str(p.resolve())) as fr:\n\t\t\treturn json.load(fr)\n\telse:\n\t\treturn None\n\nif __name__ == \"__main__\":\n\tmobsPath = str(Path().absolute())+\"/mobs.txt\"\n\thtmlPath = str(Path().absolute())+\"/otp\"\n\tdbConfigs = ReadConfig()\n\tmobs = RetornaListaMobs(mobsPath)\n\tderamOntem = RetornaEncontrados(mobs,htmlPath)\n\tdbConnection = GetDatabaseConnection(dbConfigs)\n\tcursorDB = dbConnection.cursor()\n\tsaveOnDatabase(cursorDB,deramOntem)\n\tdbConnection.commit()\n\tCloseConnection(dbConnection)\n","repo_name":"KevinPerondi/monsterstatistic","sub_path":"pythonHtmlParser.py","file_name":"pythonHtmlParser.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"70778638246","text":"#-*- coding: utf-8 -*-\nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Alignment\nfrom openpyxl.styles import PatternFill\n\n'''\n ADD \n - ACT TO EACH CASES\n - ADDITIONAL SINGULAR OR MULTIPLE (ACT, SLOT, VALUE) \n'''\n# additional information excel file\nbook_additional = load_workbook('additional.xlsx') \nsheet_additional = book_additional.active\n \n# list of all additional informations\n# make values of additional_dic empty\nadditional_dic = {k: [] for k in range(1, 82)} \nfor k in range(1, 82) : \n additional_dic[k].extend(['', []])\n\n# function for reading from the excel file ! \ndef getInfo() :\n # get each input one by one\n for row in sheet_additional.iter_rows(min_row=2, min_col=4, max_row=100, max_col=8):\n cNum = row[0].value # case number read\n # 0 : caseNum, 1 : ACT, 2 : ACT, 3 : SLOT, 4 : VALUE\n act_1, act_2, slot, value = row[1].value, row[2].value, row[3].value, row[4].value\n additional_dic[cNum][0] = act_1\n additional_dic[cNum][1].append([act_2, slot, value])\n \n\n''' \n TOKENIZING PART\n INPUT AS A STRING \n'''\ndef insertTag (f, input, caseNum) : # dealing corpus by corpus\n if input == None :\n return\n \n print(f)\n print(input)\n\n list_of_tag = []\n back = -1\n tag_Num = input.count('%') # the number of tag in a corpus\n natural = ''\n\n \n for i in range(tag_Num) :\n # get necessary indexes\n tag_index_num = input.index('%', back+1)\n front = input.index('{', back+1)\n natural += input[back+1:front] \n back = input.index('}', back+1)\n \n # get act, slot and value\n act = additional_dic[caseNum][0]\n value = input[front+1:tag_index_num]\n slot = input[tag_index_num+1:back]\n \n # insert act, slot, and value into the list\n list_of_tag.append([act, slot, value])\n \n # making natural one of the input\n natural += value \n if ( i == tag_Num - 1 ) : \n natural += input[back+1:]\n \n if (tag_Num == 0) :\n natural += input\n \n corp_info_list = []\n if ( len(additional_dic[caseNum][1]) > 0 ) :\n list_of_tag.extend(additional_dic[caseNum][1])\n \n corp_info_list.extend([input, natural, list_of_tag, caseNum])\n all_corpus.append(corp_info_list)\n\n \n'''\n MAIN STARTS HERE\n'''\n# make list for the corpus information\nfiles = ['1.xlsx', '2.xlsx', '3.xlsx', '4.xlsx', '5.xlsx', '6.xlsx', '7.xlsx', '8.xlsx'\n , '9.xlsx', '10.xlsx', '11.xlsx', '12.xlsx', '13.xlsx', '14.xlsx', '15.xlsx', '16.xlsx', '17.xlsx'\n , '18.xlsx']\n\n\n# write book \nwrite_book = Workbook()\nwrite_sheet = write_book.active\n\n# additional information \ngetInfo()\nindex = 1\n# get each input one by one\nfor f in files : \n all_corpus = []\n# read from the corpus excel file\n book = load_workbook(f)\n sheet = book.active\n caseNum = 0\n for row in sheet.iter_rows(min_row=2, min_col=3, max_col=33):\n caseNum += 1\n for cell in row:\n input = cell.value \n # process\n insertTag(f, input, caseNum)\n \n # write to a new excel file\n for i in all_corpus :\n leng = len(i[2])\n first_flag = 1\n for j in i[2] :\n if ( first_flag ) : \n row = (str(index), i[0], i[1], j[0], j[1], j[2])\n first_flag = 0\n index += 1 \n else :\n row = ('', '', '', j[0], j[1], j[2])\n \n write_sheet.append(row)\n \n # write_sheet.merge_cells('A' + str(cur_row-leng) + ':A' + str(cur_row-1))\n # write_sheet.merge_cells('B' + str(cur_row-leng) + ':B' + str(cur_row-1))\n\n\n'''\n EXCEL CELL STYLE PART\n'''\n# adjust cell size\ndims = {}\nfor row in write_sheet.rows:\n for cell in row:\n if cell.value:\n dims[cell.column] = max((dims.get(cell.column, 0), len(cell.value)))\nfor col, value in dims.items():\n write_sheet.column_dimensions[col].width = value\n \n# cell alignment\nfor row in write_sheet.rows : \n for cell in row :\n cell.alignment = Alignment(horizontal=\"justify\")\n\nwrite_book.save('tagged_corpus.xlsx')\n\n\n","repo_name":"Linohong/tagging","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72520738724","text":"# import sys\n# input = sys.stdin.readline\n\n# n = int(input())\n# li1 = list(map(int, input().split()))\n# m = int(input())\n# li2 = list(map(int, input().split()))\n# t1 = max(li1)\n# t2 = max(li2)\n# MAX = max(t1, t2)\n# print(MAX)\n# visited = [False for i in range(MAX+1)]\n# for i in li1:\n# visited[i] = True\n# for i in li2:\n# if visited[i]:\n# print(1)\n# else:\n# print(0)\n\n\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\n# n_list = sorted(list(map(int, input().split())))\nn_set = set(map(int, input().split()))\nm = int(input())\nm_list = list(map(int, input().split()))\n\n# def binary_search(start, end, target, n_list):\n# if start > end:\n# return 0\n \n# mid = (start + end) // 2\n# if target == n_list[mid]:\n# return 1\n# elif target < n_list[mid]:\n# return binary_search(start, mid-1, target, n_list)\n# else:\n# return binary_search(mid+1, end, target, n_list)\n\n# for target in m_list:\n# print(binary_search(0, len(m_list)-1, target, n_list))\n\nfor i in m_list:\n print(1) if i in n_set else print(0)","repo_name":"hibeen1/Problem_Solving","sub_path":"BJ_1920.py","file_name":"BJ_1920.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1613947402","text":"#turtle program example\r\nimport turtle\r\nimport random\r\n\r\ntao = turtle.Pen() #build turtle\r\ntao.shape('turtle')\r\n\r\n\r\ndef Rect(x,y,size=30, clr ='black'):\r\n tao.penup() #lift pen up\r\n tao.goto(x,y) #follow the position\r\n tao.color(clr) #change color\r\n tao.pendown() #put pen down\r\n #-----------drawing sqaure--------\r\n for i in range(4): #for loop\r\n tao.forward(size)\r\n tao.left(90)\r\n #---------------------------------\r\n tao.penup() #lift pen up\r\n\r\n\r\n\r\n##----------Run Program--------------##\r\nallcolor = ['red','green','blue','orange']\r\n\r\ncount = int (input('what is square dimension?: ')) #user input\r\n\r\nfor i in range(count): #for loop \r\n x = random.randint(-200,200)\r\n y = random.randint(-200,200)\r\n print(x,y)\r\n select_color = random.choice(allcolor)\r\n Rect(x,y,40,select_color)\r\n","repo_name":"PymPhekasut/PythonBeginner","sub_path":"basicturtle.py","file_name":"basicturtle.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41919914882","text":"#!/usr/bin/python\n##Polling file \nimport freeswitch\nimport re\nimport random\n\nrootdir = freeswitch.getGlobalVariable(\"base_dir\");\napi = freeswitch.API();\nfile_path = rootdir+\"/scripts/pyscripts/sipnumber/number\"\n\ndef file_list(filename):\n num_list = []\n file = open(filename,\"r\")\n for line in file.readlines():\n line = line.strip('\\n')\n num_list.append(line)\n file.close()\n return num_list\n\ndef db_insert(current_pos):\n api.executeString(\"db insert/gateway_route/current_pos/\"+str(current_pos))\n\ndef db_select():\n return api.executeString(\"db select/gateway_route/current_pos\")\n\ndef db_exists():\n if not api.executeString(\"db select/gateway_route/current_pos\"):\n api.executeString(\"db insert/gateway_route/current_pos/0\")\n\ndef handler(session, args):\n pass\n\ndef fsapi(session, stream, env, args):\n count, fullgw, current_pos, new_pos, idx = 0, 0, 0, 0, 0\n upgw = []\n upgw_list = file_list(file_path)\n for gw in range(len(upgw_list)):\n if re.search(r\"State\\s+REGED\\s+\",api.executeString(\"sofia status gateway \"+upgw_list[gw])):\n upgw.append(upgw_list[gw])\n count = count + 1\n db_exists()\n current_pos = db_select()\n if int(current_pos) >= count:\n current_pos = 0\n new_pos = int(current_pos) + 1\n idx = int(current_pos)\n db_insert(new_pos)\n info = api.executeString(\"show channels\")\n while 0 < 1:\n if re.search(\"sofia/gateway/\"+upgw[idx],info):\n idx = idx + 1\n if int(current_pos) >= count:\n idx = 0\n if idx >= count:\n break\n else:\n stream.write(str(upgw[idx]))\n freeswitch.consoleLog(\"info\", \"Discovery of available gateway: %s\\n\" % upgw[idx])\n break\n","repo_name":"Mrhan5199/hjl","sub_path":"pyscripts/Polling_file.py","file_name":"Polling_file.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11654740928","text":"import numpy as np\n\n\ndef filter_with_nms(net_out,overthresh,confthresh,image_shape):\n\n\tfiltered_idxs = np.where(net_out[:,4] > confthresh)\n\tfiltered_bndbox = net_out[filtered_idxs]\n\tfiltered_bndbox = filtered_bndbox.reshape(-1,26)\n\tx_center = net_out[:,0]*image_shape[0]\n\ty_center = net_out[:,1]*image_shape[1]\n\twidth = net_out[:,2]*image_shape[0]\n\theight = net_out[:,3]*image_shape[1]\n\n\tx0 = x_center - (width/2)\n\tx1 = x_center + (width/2)\n\ty0 = y_center - (height/2)\n\ty1 = y_center + (height/2)\n\tarea = np.abs(x1-x0)*np.abs(y1-y0)\n\tidxs = np.argsort(y1)\n\tfiltered = []\n\twhile len(idxs) >0:\n\t\tlast = len(idxs)-1\n\t\ti = idxs[-1]\n\t\tfiltered.append(i)\n\n\t\txmin = np.maximum(x0[last],x0[idxs[:last]])\n\t\tymin = np.maximum(y0[last],y0[idxs[:last]])\n\t\txmax = np.minimum(x1[last],x1[idxs[:last]])\n\t\tymax = np.minimum(y1[last],y1[idxs[:last]])\n\n\t\tw = np.maximum(0,(xmax-xmin+1))\n\t\th = np.maximum(0,(ymax-ymin+1))\n\t\twh = w*h\n\t\toverlap = wh/area[idxs[:last]]\n\t\timport ipdb;ipdb.set_trace()\n\t\tquery = np.concatenate([last],np.where(overlap > overthresh))\n\t\tidxs = np.delete(idxs,query)\n\n\treturn net_out[filtered]\n\n\n\n\n","repo_name":"saifelden/Yolo-Detection-Framework","sub_path":"nms.py","file_name":"nms.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9823491146","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 30 08:34:54 2016\r\n\r\n@author: John\r\n\"\"\"\r\nimport csv \r\nfrom gurobipy import * \r\n\r\nH = {}\r\nmyFile = open('Opponents Season 2016.csv','rt')\r\nmyReader = csv.reader(myFile) \r\nfor row in myReader:\r\n if row[0] != 'Away Team':\r\n \r\n if row[1] in H:\r\n H[row[1]].append(row[0])\r\n else:\r\n H[row[1]] = [row[0]]\r\n\r\nmyFile.close()\r\n\r\n\r\nA = {}\r\nmyFile = open('Opponents Season 2016.csv','rt')\r\nmyReader = csv.reader(myFile) \r\nfor row in myReader:\r\n if row[0] != 'Away Team':\r\n \r\n if row[0] in A:\r\n A[row[0]].append(row[1])\r\n else:\r\n A[row[0]] = [row[1]]\r\n \r\n\r\nmyFile.close()\r\n\r\nS = {}\r\nmyFile= open('Slots.csv')\r\nmyReader = csv.reader(myFile)\r\nfor row in myReader:\r\n for cell in row:\r\n if len(cell)!=0 and cell!=row[0]:\r\n if int(row[0]) in S:\r\n S[int(row[0])].append(cell)\r\n else:\r\n S[int(row[0])]=[cell]\r\n\r\ndel(row,cell)\r\nmyFile.close()\r\n\r\nT = ['DAL', 'NYG', 'PHI','WAS','CHI', 'DET', 'GB','MIN','ATL','CAR','NO','TB',\r\n 'ARZ','LAR','SF','SEA','BUF','MIA','NE','NYJ','BAL','CIN','CLE','PIT',\r\n 'HOU','IND','JAC','TEN','DEN','KC','OAK','SD']\r\n\r\n \r\nDIVISION = {'NFC':{'EAST':['DAL', 'NYG', 'PHI','WAS'],\r\n 'NORTH':['CHI', 'DET', 'GB','MIN'],\r\n 'SOUTH':['ATL', 'CAR','NO','TB'],\r\n 'WEST':['ARZ','LAR','SF','SEA']\r\n },\r\n 'AFC':{'EAST': ['BUF','MIA','NE','NYJ'],\r\n 'NORTH': ['BAL','CIN','CLE','PIT'],\r\n 'SOUTH': ['HOU','IND','JAC','TEN'],\r\n 'WEST': ['DEN','KC','OAK','SD'] \r\n }\r\n }\r\nCONFERENCE = {'NFC':['DAL', 'NYG', 'PHI','WAS','CHI', 'DET', 'GB','MIN','ATL','CAR','NO','TB','ARZ','LAR','SF','SEA'],\r\n 'AFC':['BUF','MIA','NE','NYJ','BAL','CIN','CLE','PIT','HOU','IND','JAC','TEN','DEN','KC','OAK','SD']\r\n }\r\n \r\nmyModel = Model()\r\nmyModel.modelSense = GRB.MINIMIZE\r\nmyModel.update()\r\n \r\n##OBJECTIVE FUNCTION##\r\nmyGames = {}\r\nfor h in T:\r\n for a in H[h]:\r\n for w in range(1,18):\r\n for s in S[w]:\r\n myGames[a,h,s,w] = myModel.addVar(obj =1, vtype=GRB.BINARY, \r\n name='games_%s_%s_%s_%s' % (a,h,s,w))\r\n\r\nfor h in T:\r\n for w in range(4,13):\r\n myGames['BYE',h,'SUNB_NFL',w] = myModel.addVar(obj =1, vtype=GRB.BINARY, \r\n name='games_BYE_%s_%s_%s' % (h,s,w))\r\n \r\nmyModel.update() \r\n########################################################################################################################\r\n\r\n## CONSTRAINTS\r\nmyConstr = {}\r\n\r\n#constraint 1: every game played once \r\nfor h in T: #iterate over all 32 teams (a,h)\r\n for a in H[h]: #each away team\r\n constrName = '1_game_once_%s_%s' % (a,h)\r\n myConstr[constrName] = myModel.addConstr(quicksum(myGames[a,h,s,w]\r\n for w in range (1,18) for s in S[w]) == 1,\r\n name = constrName)\r\nmyModel.update() \r\n \r\n#constraint 2: teams play one game each week (takes care of everything but bye games)\r\nfor t in T:\r\n for w in [1,2,3,12,13,14,15,16,17]:\r\n constrName = '1_in_w%s_by_%s' % (w,t)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,t,s,w] for a in H[t] for s in S[w]) \r\n + quicksum(myGames[t,h,s,w] for h in A[t] for s in S[w]) == 1, \r\n name=constrName)\r\nmyModel.update()\r\n \r\n#constraint 3: teams play one game each week (takes care of bye games)\r\nfor t in T:\r\n for w in range(4,12):\r\n constrName = '1_bye_in_w%s_by_%s' %(w,t)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,t,s,w] for a in H[t] for s in S[w] if s != 'SUNB_NFL') \r\n + quicksum(myGames[t,h,s,w] for h in A[t] for s in S[w] if s != 'SUNB_NFL') \r\n + myGames['BYE',t, 'SUNB_NFL', w] == 1, name=constrName)\r\nmyModel.update()\r\n \r\n#constraint 4:No more than 6 bye games in a given a week\r\nfor w in range(4,12):\r\n constrName = '4_Bye_game_by_%s_in_w%s' % (t,w)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames['BYE',t,'SUNB_NFL',w] for t in T)<=6, name=constrName)\r\n\r\nw = None\r\nmyModel.update()\r\n\r\n#contraint 5: No team that had an early bye game (week 4) in 2015 can have an early bye game (week 4) in 2016\r\nconstrName = 'TEN,NE do not play in week 4'\r\nmyConstr[constrName]=myModel.addConstr(myGames['BYE','NE','SUNB_NFL',4] + myGames['BYE','TEN','SUNB_NFL',4]==0,\r\nname=constrName)\r\nmyModel.update()\r\n\r\n#constraint 6: Exactly 1 Thursday game every week upto week 16, week 17 has no thursday games\r\nThursday = ['THUN_NBC' , 'THUN_NFL' , 'THUN_NFL' , 'THUE_FOX' ,'THUL_CBS', 'THUN_NBC' , 'THUN_CBS' ]\r\nfor w in range(1,17):\r\n for s in S[w]:\r\n if s in Thursday:\r\n constrName='6_one_Thursady_in_w%s' %(w)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h] ) ==1 ,name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 7:There are two Saturday Night Games in Week 15 (one SatE and one SatL)\r\nfor s in ['SATE_NFL','SATL_NFL']:\r\n constrName='2_Games_on_Sat_s%s' %(s)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,15] for h in T for a in H[h]) == 1,name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 8: There is only one “double header” game in weeks 1 through 16 (and two in week 17)\r\n#Week 1:16\r\nfor w in range(1,17):\r\n for s in ['SUNDH_CBS','SUNDH_FOX']:\r\n constrName= '1_DH_in_w%s%s' %(w,s)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h]) == 1, name=constrName)\r\nmyModel.update()\r\n \r\n#Week 17 \r\nconstrName='2_DH_in_17'\r\nmyConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,17] for h in T for a in H[h] for s in ['SUNDH_CBS','SUNDH_FOX']) == 2,name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 9: There is exactly one Sunday Night Game in weeks 1 through 16 (no Sunday Night Game in week 17)\r\n#Week 1:16\r\nfor w in range(1,17):\r\n constrName='1_SundayNight_in_w%s' %w\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,'SUNN_NBC',w] for h in T for a in H[h]) == 1,name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 10 Part 1: There are two Monday night games in week 1\r\nWC=['SD', 'SF', 'SEA', 'OAK', 'LAR']\r\n\r\nconstrName='2_Mondays_in_w1'\r\nmyConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,1]for h in T for a in H[h] for s in ['MON1_ESPN','MON2_ESPN']) == 2,name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 10 Part 2: The late Monday Night Game must be hosted by a West Coast Team (SD, SF, SEA, OAK, LAR)\r\n #List of west coast teams\r\n\r\nfor w in range(1,3):\r\n if s in S[w]:\r\n constrName='%s_slot_w%s' %(s,w)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,'MON2_ESPN',w] for h in WC for a in H[h]) == 1, name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 10 Part 3: There in exactly one Monday night game in weeks 2 through 16 (no Sunday Night Game in week 17))\r\n# Week 2:16\r\nfor w in range(2,17):\r\n constrName='1_Monday_in_w%s' %(w)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,'MON1_ESPN',w] for h in T for a in H[h]) ==1 , name=constrName)\r\nmyModel.update()\r\n\r\n#constraint 11: West Coast (SD, SF, SEA, OAK, LAR) and Mountain Teams (DEN, ARZ) cannot play at home in the early Sunday time slot\r\nMT=['DEN','ARZ']\r\nWCMT=WC+MT\r\n\r\nfor w in range(1,18):\r\n constrName='WstCst_MtTm_cannot_SUNE_w%s' %(w)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in WCMT for a in H[h] for s in ['SUNE_CBS','SUNE_FOX'])==0,name=constrName)\r\nmyModel.update()\r\n \r\n#constraint 12_Home_Games: No team plays 4 consecutive home/away games in a season (treat a BYE game as an away game)\r\nfor w in range(1,15):\r\n for h in H:\r\n constrName ='no_more_than_4_consecutive_games_in_w%s_at_h%s' %(w,h)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for a in H[h] for w1 in range(w, w+4) for s in S[w1]) <= 3, name = constrName)\r\nmyModel.update()\r\n\r\n#constraint 12_Away_Games:\r\nfor w in range(1,15):\r\n for a in A:\r\n constrName ='no_more_than_4_consecutive_games_w%s_at_a%s' %(w,a)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for h in A[a] for w1 in range(w, w+4) for s in S[w1]) <= 3, name = constrName)\r\nmyModel.update()\r\n\r\n#constraint 13a_Home_Games: No team plays 3 consecutive home/away games during the weeks 1, 2, 3, 4, 5 and 15, 16, 17 (treat a BYE game as an away game)\r\nfor w in range(1,4):\r\n for h in H:\r\n constrName ='no_more_than_4_consecutive_games_1_5_w%s_at_h%s' %(w,h)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for a in H[h] for w1 in range(w, w+3) for s in S[w1]) <= 2, name = constrName) \r\nmyModel.update()\r\n\r\n#Constraint 13a_Away_Games:\r\nfor w in range(1,4):\r\n for a in A:\r\n constrName ='no_more_than_4_consecutive_games_1_5_w%s_at_a%s' %(w,a)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for h in A[a] for w1 in range(w, w+3) for s in S[w1]) <= 2, name = constrName) \r\nmyModel.update()\r\n \r\n#constraint 13b_Home_Games:\r\nfor h in H:\r\n constrName ='no_more_than_4_consecutive_games_15_18_w15_%s' %h\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for a in H[h] for w in range(15, 18) for s in S[w]) <= 2, name = constrName)\r\n #need to add bye games\r\nmyModel.update()\r\n\r\n#constraint 13b_Away_Games:\r\nfor a in A:\r\n constrName ='no_more_than_4_consecutive_games_15_18_w15_%s' %a\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in A[a] for w in range(15, 18) for s in S[w]) <= 2, name = constrName)\r\n #need to add bye games\r\nmyModel.update()\r\n\r\n#constraint 14_Home_Games: Each team must play at least 2 home/away games every 6 weeks\r\nfor w in range(1,13):\r\n for h in H:\r\n constrName ='at_least_2games_per6weeks_w%s_at_h%s' %(w,h)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for a in H[h] for w1 in range(w, w+6) for s in S[w1]) >= 2, name = constrName)\r\nmyModel.update()\r\n\r\n#constraint 14_Away_Games\r\nfor w in range(1,13):\r\n for a in A:\r\n constrName ='at_least_2games_per6weeks_w%s_at_a%s' %(w,a)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for h in A[a] for w1 in range(w, w+6) for s in S[w1]) >= 2, name = constrName)\r\nmyModel.update()\r\n\r\n#constraint 15: Each team must play at least 4 home/away games every 10 weeks\r\nfor w in range(1,8): #adding 10 weeks goes beyond week 17\r\n for h in H:\r\n constrName ='at_least_4homeaway_every10weeks_w%s_h%s' %(w,h)\r\n myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w1] for a in H[h] for w1 in range(w, w+11) for s in S[w1]) >= 4, name = constrName)\r\nmyModel.update()\r\n\r\n#\r\n## Constraint 21:FOX/CBS each get at least 3 Early games on Sundays\r\n#for s in ['SUNE_CBS','SUNE_FOX']:\r\n# constrName='Atleast_3_EGames_Sun'\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h] for w in range(1,18)) >= 3, name=constrName)\r\n#myModel.update()\r\n#\r\n## Constraint 22:FOX/CBS each get at least 5 games on Sundays\r\n##Sundays\r\n#for chnl in ['FOX','CBS']:\r\n# constrName='Atleast_5_Sun_Games_on_%s' %chnl\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h] for w in range(1,18) for s in S[w] if s[:3]=='SUN' and s[len(s)-3:]==chnl) >= 5, name=constrName)\r\n#myModel.update()\r\n#\r\n##Constraint 23:FOX/CBS each get 8 double headers total weeks 1 through 16\r\n#for chnl in ['FOX','CBS']:\r\n# constrName='%s_Get_8_DH' %chnl\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h] for w in range(1,17) for s in S[w] if s=='SUNDH_'+chnl) == 8, name=constrName)\r\n#myModel.update()\r\n#\r\n## Constraint 24:FOX/CBS each get a double header in Week 17\r\n#for chnl in ['FOX','CBS']:\r\n# constrName='1_DH_each_in_w17_%s' %chnl\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,17] for h in T for a in H[h] for s in S[17] if s[len(s)-3:]==chnl and s[3:5]=='DH') == 1, name=constrName)\r\n#\r\n## Constraint 25:FOX/CBS cannot have more than 2 double headers in a row\r\n#for i in range (1,17):\r\n# for chnl in ['FOX','CBS']:\r\n# constrName='2_DH_in_row_%s' %chnl\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h] for w in range(i,i+2) for s in S[w] if s[len(s)-3:]==chnl and s[3:5]=='DH') <= 2, name=constrName)\r\n#\r\n## Constraint 26:No team can have more than 5 prime time games in a season (Thanksgiving day games do not count as primetime)\r\n#for h in T:\r\n# constrName='PrimeTime<=5_for_%s' %h\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for a in H[h] for w in range(1,18) for s in S[w] if s[4:5] == 'N' and w!= 12) <= 5 , name=constrName)\r\n#\r\n##Constraint 27 : No more than 4 games on NBC in a season\r\n#constrName='NBC<4'\r\n#myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for h in T for a in H[h] for w in range(1,18) for s in S[w] if s[len(s)-3:] == 'NBC') <= 4 , name=constrName)\r\n#\r\n##Constrint 28: Teams playing an international game will have a home game the week before their international game\r\n##Constrint 28: Teams playing an international game will have a home game the week before their international game\r\n## THESE ARE THE INTERNATIONAL GAMES. HOME GAMES SHOULD BE THE WEEK BEFORE.\r\n## JAC vs IND Week 4\r\n## LAR vs NYG Week 7\r\n## CIN vs WAS Week 8\r\n## HOU vs. OAK week 11 \r\n#constrName='Home_Before_Int_Week3_JAC' \r\n#myConstr[constrName]= myModel.addConstr(quicksum (myGames[a,'JAC',s,3] for a in H['JAC'] for s in S[3]) == 1, name=constrName )\r\n#constrName='Home_Before_Int_Week3_IND'\r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'IND',s,3] for a in H['IND'] for s in S[3] ) == 1, name=constrName )\r\n#\r\n#constrName='Home_Before_Int_Week6_LAR' \r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'LAR',s,6] for a in H['LAR'] for s in S[6] )== 1, name=constrName )\r\n#constrName='Home_Before_Int_Week6_NYG' \r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'NYG',s,6] for a in H['NYG'] for s in S[6] ) == 1, name=constrName )\r\n#\r\n#\r\n#constrName='Home_Before_Int_Week7_CIN' \r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'CIN',s,7] for a in H['CIN'] for s in S[7] ) == 1, name=constrName )\r\n#constrName='Home_Before_Int_Week7_WAS' \r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'WAS',s,7] for a in H['WAS'] for s in S[7]) == 1, name=constrName )\r\n# \r\n#constrName='Home_Before_Int_Week10_HOU' \r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'HOU',s,10] for a in H['HOU'] for s in S[10]) == 1, name=constrName ) \r\n#constrName='Home_Before_Int_Week10_OAK'\r\n#myConstr[constrName]=myModel.addConstr(quicksum (myGames[a,'OAK',s,10] for a in H['OAK'] for s in S[10] ) == 1, name=constrName ) \r\n# \r\n##Constraint 29: Teams playing an international game will have their BYE game the week following the international game\r\n#constrName='BYE_After_Int_Week6_JAC' \r\n#myConstr[constrName]= myModel.addConstr(myGames['BYE','JAC','SUNB_NFL',6] == 1, name=constrName )\r\n#constrName='BYE_After_Int_Week6_IND'\r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','IND','SUNB_NFL',6] == 1, name=constrName )\r\n#\r\n#\r\n#constrName='BYE_After_Int_Week8_LAR' \r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','LAR','SUNB_NFL',8] == 1, name=constrName )\r\n#constrName='BYE_After_Int_Week8_NYG' \r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','NYG','SUNB_NFL',8] == 1, name=constrName )\r\n#\r\n#constrName='BYE_After_Int_Week9_CIN' \r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','CIN','SUNB_NFL',9] == 1, name=constrName )\r\n#constrName='BYE_After_Int_Week9_WAS' \r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','WAS','SUNB_NFL',9] == 1, name=constrName )\r\n# \r\n#constrName='Home_Before_Int_Week12_HOU' \r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','HOU','SUNB_NFL',12] == 1, name=constrName ) \r\n#constrName='Home_Before_Int_Week12_OAK'\r\n#myConstr[constrName]=myModel.addConstr(myGames['BYE','OAK','SUNB_NFL',12] == 1, name=constrName ) \r\n#\r\n#myModel.update()\r\n#\r\n##Constrain 30: Two teams cannot play back to back games against each other or play against each other the week before and after a BYE\r\n#\r\n#for h in T:\r\n# for a in H[h]:\r\n# for w in range(1,17):\r\n# constrName='No_BackToBack_%s_%s_%s' %(w,h,a)\r\n# myConstr[constrName]=myModel.addConstr(quicksum(myGames[a,h,s,w] for s in S[w]) + quicksum(myGames[h,a,s,w+1] for s in S[w+1])==1, name=constrName)\r\n#\r\n## constraint 31:No team plays more than 2 road games against teams coming off a BYE\r\n#link31 = {}\r\n#for h in T:\r\n# for w in range (5,13):\r\n# for a in H[h]:\r\n# link31 [h,a,w] = myModel.addVar(obj =0 , vtype=GRB.BINARY, \r\n# name='link31_%s_%s_%s_%s' % (h,a,w))\r\n# myModel.update () \r\n# myGames ['BYE',h,'SUNB_NFL',w-1] + quicksum (myGames[a,h,s,w] for s in S[w] ) <= 1 + link31 [h,a,w] \r\n#\r\n# quicksum (link31 [h,a,w] for h in A[h] for w in range (5,13)) <= 2\r\n#\r\n#myModel.update () \r\n#\r\n##constraint 34: every team must play exactly once short week during the season\r\n#link34 = {}\r\n#weeks = range(2,17)\r\n#weeks.remove (13)\r\n#for h in T:\r\n# for w in weeks:\r\n# link34[h,w]=myModel.addVar(obj=0,vtype=GRB.BINARY,name='link34_%s_%s' %(h,w))\r\n# myModel.update()\r\n# constrName='SOFT 34'\r\n# myConstr[constrName]=myModel.addConstr (quicksum(myGames[a,h,s,w-1] for a in H[h] for s in S[w-1] if s.startswith('SUN')) + \r\n# quicksum(myGames[a,h,s,w-1] for h in A[a] for s in S[w-1] if s.startswith('SUN')) +\r\n# quicksum(myGames[a,h,s,w-1] for a in H[h] for s in S[w-1] if s.startswith('THU')) + \r\n# quicksum(myGames[a,h,s,w] for h in A[a] for s in S[w] if s.startswith('THU')) <= 1 + link34[h,w] , name=constrName)\r\n# constrName='Link 34'\r\n# myConstr[constrName]=myModel.addConstr(quicksum(link34[h,w] for w in weeks) == 1 , name = constrName )\r\n# \r\n# \r\n# \r\n#\r\n##Constraint 16:Superbowl champion from 2015 opens the season at home on Thursday night of Week 1\r\n#for h in H:\r\n# for a in H[h]:\r\n# for s in S[1]:\r\n# if s[:4] == \"THUN\" and h!= 'DEN':\r\n# myModel.remove(myGames[a,h,s,1])\r\n# del myGames[a,h,s,1]\r\n#myModel.update\r\n#\r\n##Constraint 17: DAL and DET play at home on Thanksgiving day during the afternoon\r\n# # FOX gets DAL; CBS gets DET\r\n# # DET gets Early game, DAL gets Late game\r\n#for h in H:\r\n# for a in H[h]:\r\n# for s in S[12]:\r\n# if any ([s=='THUE_CBS' and h!='DET' , s=='THUL_FOX' and h!='DAL']) : \r\n# myModel.remove(myGames[a,h,s,12])\r\n# del myGames[a,h,s,12]\r\n#myModel.update\r\n#\r\n##Constraint 18: NBC gets Thursday Night Games Week 1 and Week 12 (Thanksgiving)\r\n#for h in H:\r\n# for a in H[h]:\r\n# for w in [1,12]:\r\n# for s in S[w]:\r\n# if (s [:4] == 'THUN') and (s[len(s)-3:] != 'NBC'): # If the slot is thursday night and the NBC is not hosting. Remove it.\r\n# myModel.remove(myGames[a,h,s,w])\r\n# del myGames[a,h,s,w]\r\n#myModel.update \r\n#\r\n##Constraint 19 : CBS gets Thursday Night Games Weeks 2 though 9\r\n#for h in H:\r\n# for a in H[h]:\r\n# for w in range (2,10):\r\n# for s in S[w]:\r\n# if (s[:4] == \"THUN\") and (s[len(s)-3:] != \"CBS\"): #If there is a THUN game and not on CBS, remove it.\r\n# myModel.remove(myGames[a,h,s,w])\r\n# del myGames[a,h,s,w]\r\n#myModel.update \r\n# \r\n##Constraint 20: NFL gets Thursday Night Games Weeks 10, 11, 13-16 (and Saturday night games)\r\n#for h in H:\r\n# for a in H[h]:\r\n# for w in [10, 11, 13,14,15,16]:\r\n# for s in S[w]:\r\n# if any ([s[:4] == \"THUN\" , s[:4] ==\"SATN\"]) and (s[len(s)-3:] != \"NFL\"):\r\n# myModel.remove(myGames[a,h,s,w])\r\n# del myGames[a,h,s,w]\r\nmyModel.update \r\n# \r\nmyModel.optimize()\r\n#name=\"NFL_HW1\"\r\n##myModel.write(name+'.lp')\r\n","repo_name":"karthikskumar/NFL","sub_path":"Opt_Mdl.py","file_name":"Opt_Mdl.py","file_ext":"py","file_size_in_byte":20803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"75363126244","text":"import yt_dlp\nimport requests\nimport ffmpeg\nimport re\nimport webvtt\nimport os\nfrom string import printable\n\nclass YoutubeDownloader:\n\n def extract_text_from_vtt(self, vtt_file_path):\n pattern = r'<[^>]+>'\n \n vtt = webvtt.read(vtt_file_path)\n clean_lines = []\n for s in vtt:\n txt = s.text\n clean = re.sub(pattern, '', txt)\n \n # Remove strange invisible unicode characters\n clean = re.sub(\"[^{}]+\".format(printable), \"\", clean).strip()\n clean = clean.replace(\"\\n\", \" \")\n if(clean!=\"\"):\n clean_lines.append(clean)\n clean_text = \"\\n\".join(clean_lines)\n\n # Create the text file in the same folder\n with open(f\"{vtt_file_path}.txt\", 'w', encoding='utf-8') as f:\n f.write(clean_text)\n\n\n def download_all(self, video_url:str, destination_dir:str):\n print(\"STARING YOUTUBE DOWNLOADER!\")\n \n self.download_captions(video_url, f\"{destination_dir}/captions.vtt\")\n self.refine_captions(f\"{destination_dir}/captions.vtt\")\n self.extract_text_from_vtt(f\"{destination_dir}/captions.vtt\")\n\n self.download_audio (video_url, f\"{destination_dir}/audio.wav\")\n\n def download_audio(self, video_url:str, destination_file_path:str):\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'wav',\n 'preferredquality': '192',\n }],\n }\n\n with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n info_dict = ydl.extract_info(video_url, download=False)\n audio_url = info_dict.get('url', None)\n if audio_url:\n ffmpeg.input(audio_url).output(destination_file_path).run()\n print('Audio downloaded successfully!')\n else:\n print('Failed to retrieve audio URL.')\n \n #Removes duplicates and cleans the lyrics \n def refine_captions(self, captions_file_path):\n print(\"Cleaning the captions\")\n vtt = webvtt.read(captions_file_path)\n filtered = []\n for c in vtt:\n txt = c.text\n start = c.start\n end = c.end\n if(len(filtered)>0 and filtered[-1]['start']==start):\n continue\n dict = {'text': txt, 'start': start, 'end': end }\n filtered.append(dict)\n \n #Save the filtered captions\n filtered_captions = \"WEBVTT\\n\\n\"\n for f in filtered:\n # Add time stamps\n filtered_captions += f\"{f['start']} --> {f['end']}\\n\"\n # Add caption text\n filtered_captions += f\"{f['text']}\\n\\n\"\n\n # Overwrite the source file\n with open(captions_file_path, 'w', encoding='utf-8') as f:\n f.write(filtered_captions)\n\n def download_captions(self, video_url:str, destination_file_path:str):\n print(\"DOWNLOADING CAPTIONS!\")\n ydl_opts = {\n 'writesubtitles': True,\n 'subtitleslangs': ['en'], # Specify the language of the captions\n 'skip_download': True, # Avoid downloading the video\n 'quiet': False, # Suppress console output\n 'force_overwrites': True\n }\n\n with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n try:\n info_dict = ydl.extract_info(video_url, download=False)\n \n subtitles = info_dict.get('subtitles', {}).get('en')\n\n #Sometimes the language is not called 'en', but en.xxxxxx where the x's are random characters.\n if(not subtitles):\n all = info_dict.get('subtitles', {})\n key = list(all.keys())[0]\n subtitles = info_dict.get('subtitles', {}).get(key)\n\n if subtitles:\n def find(predicate, lst):\n return next((item for item in lst if predicate(item)), None)\n \n def download(url, file_path):\n print(f\"Downloading: \\n\\t{url}\\n\\t --->\\t {file_path}\")\n vtt_response = requests.get(url)\n vtt_response.raise_for_status() # Check for any errors\n with open(file_path, 'w', encoding='utf-8') as f:\n f.write(vtt_response.text)\n \n # Find the urls of the files\n vtt_url = find(lambda x: x['ext']=='vtt', subtitles)['url']\n #txt_url = find(lambda x: x['ext']=='txt', subtitles)['url']\n\n # Download the vtt and txt caption files\n download(vtt_url, destination_file_path)\n #download(txt_url, destination_file_path+'.txt')\n \n\n else:\n print(\"No English captions found for the video.\")\n except yt_dlp.DownloadError as e:\n print(f\"Error: {str(e)}\")","repo_name":"pad918/stable-diffusion-mv-generator","sub_path":"scripts/YoutubeDownloader.py","file_name":"YoutubeDownloader.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71579628326","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\n'''\n__title__ = ''\n__author__ = 'dcx'\n__mtime__ = '2019/6/29'\n# code is far away from bugs with the god\n'''\n\n\ndef foo():\n try:\n 1/0#这个异常在后面是不会被捕获的\n f = open('test1.txt')\n print(f)\n except FileNotFoundError as e:\n print('{} {}'.format(e.__class__,e.errno,e.strerror))\n finally:\n print('清理工作')\n return\n\n\n#此时调用不会抛出异常,相当于异常被压制了,所以在finally中很少return\nfoo()\n","repo_name":"dingcx/pybase_old","sub_path":"exception/exception--04-异常的压制.py","file_name":"exception--04-异常的压制.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39173314680","text":"import wikipediaapi\nimport requests\nimport re\nimport math\n\n\"\"\"\nBack object\n\n- Instantiate the article\n- Contains the article in clear\n- Returns the blured article to the index to be displayed with all the \"states\" of the words\n- Try a word entered by the user\n\n\nTakes:\n- taille_article, number of words per article we want. We skip the small articles\n- nb_paragraphes, number of paragraphes we take in the article chosen. We avoid to display too much text\n- trigger_similarity, if two words are less than (default, to be adjusted) 20% similar we don't show it to the user\n- (not implemented) trigger_exact, if the similarity two words are over this value that means it deserves to be shown as the exact same word (\"être\" == \"est\")\n- max_similarity_states\n- nb_states, the number of possible state for a close word. Can be either, \"top\", \"mitop\" or \"pastop\"\n- returned_size, size of the returned json. The number of words that will be displayed on the page (default 500)\n- unknown_char, the character used to hide letters in the word, default: \"•\"\n\nTO DO:\n- [X] Split words with characters, example \"oui,\" -> [\"oui\",\",\"]\n- [ ] Work on the trigger\n- [ ] Maybe a trigger to say that two words are equal, example: \"être\" == \"est\". Trigger at 80% ?\n- [ ] Keep only a certain amount of paragraphs\n- [ ] Faster loading of the article\n\"\"\"\n\nclass Back:\n\n def __init__(self):\n self.toIndex = {}\n self.text = {}\n self.taille_article = 1000\n self.nb_paragraphes = 10\n self.trigger_similarity = 0.2\n self.returned_size = 1000\n self.trigger_exact = 0.58\n self.nb_states = 3\n self.max_similarity_states = 0.8\n self.unknownchar = \"•\"\n self.titre = \"\"\n\n def __str__(self):\n string = f\"Titre: {self.titre}; taille: {self.taille_article}\"\n return string\n\n def getRandomArticle(self):\n #Creating the session and preparing the url\n\n s= requests.Session()\n URL = \"https://fr.wikipedia.org/w/api.php\"\n\n PARAMS = {\n \"action\": \"query\",\n \"format\": \"json\",\n \"list\": \"random\"\n }\n\n wiki_wiki = wikipediaapi.Wikipedia(\n language='fr',\n extract_format=wikipediaapi.ExtractFormat.WIKI\n )\n\n # We are getting a random article\n R = s.get(url=URL, params=PARAMS)\n DATA = R.json()\n page_py = wiki_wiki.page(\"Bonjour\")\n DATA[\"query\"][\"random\"][0][\"title\"] = ':'\n\n # If it contains ':' that means it is a discussion, a user or whatever\n # We then loop until we find a article without ':'\n while re.compile(r':').findall(DATA[\"query\"][\"random\"][0][\"title\"]):\n R = s.get(url=URL, params=PARAMS)\n DATA = R.json()\n page_py = wiki_wiki.page(DATA[\"query\"][\"random\"][0][\"title\"])\n # If the article has less words than 'taille_article' words we add ':' to the title to loop again\n if len(page_py.text.split(\" \")) < self.taille_article:\n DATA[\"query\"][\"random\"][0][\"title\"] = DATA[\"query\"][\"random\"][0][\"title\"] + \":\"\n\n toIndex = self.articleToApp(DATA[\"query\"][\"random\"][0][\"title\"], page_py.text)\n\n return toIndex\n\n def getArticleFromTitre(self, titre):\n\n wiki_wiki = wikipediaapi.Wikipedia(\n language='fr',\n extract_format=wikipediaapi.ExtractFormat.WIKI\n )\n\n page_py = wiki_wiki.page(titre)\n\n toIndex = self.articleToApp(titre, page_py.text)\n\n return toIndex\n\n def articleToApp(self, titre, article):\n\n self.returned_size = 500\n\n # This dict is for the Back object only, it contains the text in clear and if it is part of the title or not\n self.text = {}\n # This dict is for the index, text blured or found, has way more information than the previous one\n to_index = {}\n\n # Loop through the title\n # re.split('(\\W)', string) splits between words and every other character\n i=0\n for mot in re.split('(\\W)',titre):\n self.text[i] = {\n \"mot\": mot,\n \"titre\": True\n }\n to_index[i] = {\n \"mot\": self.unknownchar * len(mot),\n \"type\": \"titre\",\n # etat can be 'cache', 'trouve', 'proche', 'new_trouve'\n \"etat\": [\"cache\"],\n \"percentage\": 0\n }\n if(mot.isalpha() == True or mot.isnumeric()): # if the string contains only alpha characters or not (includes accents and weird characters used in the silly french language)\n to_index[i][\"character\"] = False\n else:\n to_index[i][\"mot\"] = mot\n to_index[i][\"character\"] = True\n to_index[i][\"etat\"] = [\"trouve\"]\n \n i += 1\n\n # Loop through the entire article, we keep i to its previous value\n for mot in re.split('(\\W)', article):\n self.text[i] = {\n \"mot\": mot,\n \"titre\": False\n }\n to_index[i] = {\n \"mot\": self.unknownchar * len(mot),\n \"type\": \"article\",\n \"etat\": [\"cache\"],\n \"percentage\": 0\n }\n \n if(mot.isalpha() == True or mot.isnumeric()):\n to_index[i][\"character\"] = False\n else:\n to_index[i][\"mot\"] = mot\n to_index[i][\"character\"] = True\n to_index[i][\"etat\"] = [\"trouve\"]\n i += 1\n\n # Making sure we will not try to reach a value that does not exist\n if self.returned_size > self.taille_article:\n self.returned_size = self.taille_article\n\n # Nombre de paragraphes retournés\n nb_paragraphes = 10\n nb_paragraphes_current = 0\n i = 0\n last_i = 0\n\n while nb_paragraphes_current < nb_paragraphes:\n if to_index[i][\"mot\"] == \"\\n\":\n nb_paragraphes_current += 1\n last_i = i\n try:\n # On essaie parce qu'il est possible d'arriver à la fin de l'article\n self.toIndex[i] = to_index[i]\n except:\n # Pour éviter que l'on s'arrête en plein milieu d'un paragraphe et être sûr d'aller jusqu'à la fin\n i = last_i\n for i in range(0, i):\n self.toIndex[i] = to_index[i]\n break\n i = i + 1\n\n # Si il n'y a pas assez de mot alors on continue d'ajouter des paragraphes\n if len(self.toIndex) < self.taille_article:\n nb_paragraphes_current = 0\n nb_paragraphes = 3\n while nb_paragraphes_current < nb_paragraphes:\n if to_index[i][\"mot\"] == \"\\n\":\n nb_paragraphes_current += 1\n last_i = i\n try:\n self.toIndex[i] = to_index[i]\n i = last_i\n for i in range(0, i):\n self.toIndex[i] = to_index[i]\n except:\n break\n i = i + 1\n\n # for i in range(0, len(to_index)):\n # self.toIndex[i] = to_index[i]\n\n self.titre = titre\n\n print(titre)\n\n return self.toIndex\n\n def testMot(self, motToTest, model):\n\n # We test if the word entered is a real one (COMMENTED because it was not working with proper nouns, it is checked further anyway)\n # try: \n # self.model.similarity(\"bonjour\", str(motToTest).lower())\n # except:\n # return self.toIndex\n \n for i in range(0, len(self.toIndex)):\n # If it is a character we pass, it shouldn't enter here, redundancy with the previous try\n if self.toIndex[i][\"character\"] == True:\n pass\n # If it is exactly the word we looked for we replace the word by \n elif str(self.text[i][\"mot\"]).lower() == str(motToTest).lower():\n self.toIndex[i][\"mot\"] = self.text[i][\"mot\"]\n self.toIndex[i][\"etat\"] = [\"trouve\", \"new_trouve\"]\n\n # If the word has been found previously then we remove the new_trouve (changing back the background color to gray)\n elif \"new_trouve\" in self.toIndex[i][\"etat\"]:\n self.toIndex[i][\"etat\"] = [\"trouve\"]\n\n elif \"trouve\" in self.toIndex[i][\"etat\"]:\n pass \n\n # Testing similarity with numbers\n # Within 90% close -> Top\n # 80% -> mitop\n # 70% -> pastop\n # To define\n elif motToTest.isnumeric() and self.text[i][\"mot\"].isnumeric():\n \n # Smallest number at the top\n if float(motToTest) < float(self.text[i][\"mot\"]):\n similarity = float(motToTest) / float(self.text[i][\"mot\"])\n else:\n similarity = float(self.text[i][\"mot\"]) / float(motToTest) \n\n print(f'Nombre entré: {motToTest}, Nombre du texte: {self.text[i][\"mot\"]}, similarité: {similarity}')\n \n # We do not erase progress made so far\n if similarity > self.toIndex[i][\"percentage\"]:\n self.toIndex[i][\"percentage\"] = similarity\n\n if similarity > 0.9:\n self.toIndex[i][\"etat\"] = [\"top\"]\n self.toIndex[i][\"etat\"].append(\"proche\")\n self.toIndex[i][\"mot\"] = motToTest\n\n elif similarity > 0.8:\n self.toIndex[i][\"etat\"] = [\"mitop\"]\n self.toIndex[i][\"etat\"].append(\"proche\")\n self.toIndex[i][\"mot\"] = motToTest\n\n elif similarity > 0.7:\n self.toIndex[i][\"etat\"] = [\"pastop\"]\n self.toIndex[i][\"etat\"].append(\"proche\")\n self.toIndex[i][\"mot\"] = motToTest\n\n # We will check for the similarity if the word is not found already\n elif \"trouve\" not in self.toIndex[i][\"etat\"]:\n # We try once again to be sure, redundancy, the last thing we want is the server to crash\n try:\n similarity = model.similarity(str(self.text[i][\"mot\"]).lower(), str(motToTest).lower())\n except:\n similarity = 0\n # trigger_smiliraty can be changed based on empirical researchs\n # If the similarity between the actual word and the word entered is larger than the trigger then we can show it to the user\n # We also make sure that the similarity is greater than what it actually is. We won't replace a word if it is \"further\" from a previous tried word\n if similarity > self.trigger_similarity and similarity > self.toIndex[i][\"percentage\"]:\n print(f'Mot entré: {motToTest}, Mot du texte: {self.text[i][\"mot\"]}, similarité: {similarity}')\n self.toIndex[i][\"percentage\"] = float(similarity)\n step = (self.max_similarity_states-self.trigger_similarity) / self.nb_states\n \n if(similarity <= self.trigger_similarity+step):\n self.toIndex[i][\"etat\"] = [\"pastop\"]\n\n elif(similarity <= self.trigger_similarity+step*2):\n self.toIndex[i][\"etat\"] = [\"mitop\"]\n\n elif(similarity <= self.trigger_similarity+step*3):\n self.toIndex[i][\"etat\"] = [\"top\"]\n\n else:\n self.toIndex[i][\"etat\"] = [\"top\"]\n\n self.toIndex[i][\"etat\"].append(\"proche\")\n\n\n\n # This condition is to check if the tested word is bigger than the actual word or not\n # Example: 'être' is the actual word\n # 'avoir' is entered: we return 'avoir' because it has more letters than 'être'\n # 'es' is entered: we return '#es#' to signify that the actual word is larger than the one entered\n if len(self.text[i][\"mot\"]) <= len(motToTest):\n self.toIndex[i][\"mot\"] = motToTest\n elif len(self.text[i][\"mot\"]) > len(motToTest):\n self.toIndex[i][\"mot\"] = math.floor((len(self.text[i][\"mot\"]) - len(motToTest))/2) * self.unknownchar + motToTest + math.ceil((len(self.text[i][\"mot\"]) - len(motToTest))/2) * self.unknownchar\n else:\n # It shouldn't enter this, if anything we just return the self.toIndex at the end\n pass\n\n return self.toIndex\n\n def tricher(self):\n for i in range(0, len(self.toIndex)):\n if(self.toIndex[i][\"character\"]) == True:\n pass\n else:\n self.toIndex[i][\"etat\"] = [\"trouve\"]\n self.toIndex[i][\"mot\"] = self.text[i][\"mot\"]\n return self.toIndex\n\n def checkTitreArticle(self, titreArticleATester):\n wiki_wiki = wikipediaapi.Wikipedia(\n language='fr',\n extract_format=wikipediaapi.ExtractFormat.WIKI\n )\n\n page_py = wiki_wiki.page(titreArticleATester)\n\n # Retourne True si l'article est un vrai\n # Retourne Faux si il est faux\n if (page_py.text == \"\"):\n return False, \"\"\n elif (len(page_py.text) < self.returned_size):\n return False, \"\"\n else:\n return True, page_py.title","repo_name":"MariusFe/seman-game","sub_path":"static/python/back.py","file_name":"back.py","file_ext":"py","file_size_in_byte":13594,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9439870426","text":"import base64\nimport cv2\nimport requests\nfrom tqdm import tqdm\nimport numpy as np\n\nif __name__ == '__main__':\n cap = cv2.VideoCapture('op.mp4')\n frames_num = cap.get(7)\n fps = cap.get(5)\n width = cap.get(3)\n height = cap.get(4)\n print(frames_num, fps, width, height)\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter('res.mp4', fourcc, fps, (int(width)*4, int(height)*4))\n cnt = 0\n for i in tqdm(range(0, int(frames_num))):\n ret, frame = cap.read()\n data = cv2.imencode('.jpg', frame)[1].tobytes()\n res = requests.post(\"http://192.168.1.10:8209/esr/img/row\", {\n \"data\": base64.encodebytes(data).decode(),\n \"face_enhance\": \"false\"\n })\n tmp = cv2.imdecode(np.frombuffer(res.content, np.uint8), cv2.IMREAD_UNCHANGED)\n cv2.imwrite(\"jpg/res_{}.jpg\".format(i), tmp)\n out.write(tmp)\n cap.release()\n out.release()\n","repo_name":"xiaoyou-bilibili/Real-ESRGAN","sub_path":"video_convert.py","file_name":"video_convert.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"8416118119","text":"import re\n\nTARGET_BAG = \"shiny gold bag\"\nNO_BAGS = \"no other bags\"\n\ndef get_bag_dict():\n bag_dict = {}\n with open(\"day7.txt\") as f:\n for line in f:\n if NO_BAGS in line:\n continue\n parent_bag = re.match(r\"^.+?bag\", line).group(0)\n matches = re.findall(r\"(\\d+)\\s+(.+?bag)\", line)\n child_bags = [(m[1], int(m[0])) for m in matches]\n bag_dict[parent_bag] = child_bags\n return bag_dict\n\n\ndef check_bag(bag_dict, bag_color):\n stack = [bag_color]\n while len(stack) > 0:\n parent_bag = stack.pop(0)\n if parent_bag in bag_dict:\n child_bags = bag_dict[parent_bag]\n child_colors = [b[0] for b in child_bags]\n if TARGET_BAG in child_colors:\n return True\n stack += child_colors\n return False\n\n\ndef part1():\n bag_dict = get_bag_dict()\n count = 0\n for bag_color in bag_dict:\n if check_bag(bag_dict, bag_color):\n count += 1\n return count\n\n\ndef recurse(bag_dict, bag_name, mult):\n if bag_name not in bag_dict:\n return 0\n child_bags = bag_dict[bag_name]\n total = 0\n for child_bag, count in child_bags:\n total += count * mult\n total += recurse(bag_dict, child_bag, count * mult)\n return total\n\n\ndef part2():\n bag_dict = get_bag_dict()\n total = recurse(bag_dict, TARGET_BAG, 1)\n return total\n\n\nif __name__ == \"__main__\":\n print(f\"Part 1:\\n{part1()}\")\n print(f\"Part 2:\\n{part2()}\")\n","repo_name":"kwlabuda/aoc-2020","sub_path":"day7/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39126540781","text":"from typing import Optional\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import JsonResponse\nfrom django.shortcuts import redirect\nfrom django.template import loader\nfrom django.views.generic import FormView\nfrom vanilla import DetailView\n\nfrom medusa_website.mcq_bank.models import Answer, History, Question, QuizSession\n\nfrom ...users.models import User\nfrom ..forms import QuestionForm\n\n\nclass QuizTakeView(LoginRequiredMixin, FormView, DetailView):\n form_class = QuestionForm\n template_name = \"mcq_bank/question.html\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.user: Optional[User] = None\n self.session: Optional[QuizSession] = None\n self.question: Optional[Question] = None\n self.history: Optional[History] = None\n\n def dispatch(self, request, *args, **kwargs):\n self.user = self.request.user\n self.session = QuizSession.get_current(request.user)\n if self.session is None:\n return redirect(\"mcq_bank:quiz_session_create\")\n self.history = self.user.history\n\n # Set question index to match url if specified\n if self.request.GET.get(\"q\"):\n question_index = int(self.request.GET[\"q\"])\n if question_index < 0 or question_index > self.session.questions.count() - 1:\n raise ValueError(\"Invalid question index specified!\")\n else:\n self.session.current_question_index = question_index\n\n self.session.save()\n\n return super(QuizTakeView, self).dispatch(request, *args, **kwargs)\n\n def get_form(self, *args, **kwargs):\n\n self.question = self.session.current_question\n self.history = self.session.progress\n\n form_class = self.form_class\n\n return form_class(question=self.question, **self.get_form_kwargs())\n\n # def get_form_kwargs(self):\n # kwargs = super(QuizTakeView, self).get_form_kwargs()\n #\n # return dict(kwargs, question=self.question)\n\n def form_valid(self, form):\n submitted_answer = self.submit_answer_response(form)\n\n answer_response = self.render_answer_response(request=self.request, submitted_answer=submitted_answer)\n return JsonResponse({\"answer_response\": answer_response})\n\n def get_context_data(self, **kwargs):\n context = super(QuizTakeView, self).get_context_data(**kwargs)\n context[\"question\"] = self.question\n context[\"session\"] = self.session\n if self.session.current_question_response is not None:\n context[\"submitted_answer\"] = self.session.current_question_response\n\n return context\n\n def submit_answer_response(self, form) -> Answer:\n submitted_answer = Answer.objects.get(id=form.cleaned_data[\"answers\"])\n self.session.add_user_answer(answer=submitted_answer)\n return submitted_answer\n\n def render_answer_response(self, request, submitted_answer) -> str:\n context = {\n \"submitted_answer\": submitted_answer,\n \"question\": submitted_answer.question,\n }\n return loader.render_to_string(\"mcq_bank/answer_response.html\", context=context, request=request)\n\n\nclass QuestionPreviewView(LoginRequiredMixin, FormView, DetailView):\n \"\"\"Preview a MCQ question in the same template as during a quiz\"\"\"\n\n lookup_field = \"id\"\n model = Question\n form_class = QuestionForm\n template_name = \"mcq_bank/question.html\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.user: Optional[User] = None\n self.object: Optional[Question] = None\n self.question: Optional[Question] = None\n\n def dispatch(self, request, *args, **kwargs):\n self.user = self.request.user\n self.object = self.get_object()\n self.question = self.object\n return super(QuestionPreviewView, self).dispatch(request, *args, **kwargs)\n\n def get_form(self, *args, **kwargs):\n assert self.question is not None\n form_class = self.form_class\n\n return form_class(question=self.question, **self.get_form_kwargs())\n\n # def get_form_kwargs(self):\n # kwargs = super(QuizTakeView, self).get_form_kwargs()\n #\n # return dict(kwargs, question=self.question)\n\n def form_valid(self, form):\n answer_response = self.render_answer_response(\n request=self.request, submitted_answer=self.get_submitted_answer()\n )\n return JsonResponse({\"answer_response\": answer_response})\n\n def get_submitted_answer(self) -> Answer:\n # Provide an example answer to show response\n return self.question.correct_answers[0]\n\n def get_context_data(self, **kwargs):\n context = super(QuestionPreviewView, self).get_context_data(**kwargs)\n context[\"question\"] = self.question\n context[\"submitted_answer\"] = self.get_submitted_answer()\n context[\"answer_response\"] = self.render_answer_response(\n self.request, submitted_answer=self.get_submitted_answer()\n )\n\n return context\n\n def render_answer_response(self, request, submitted_answer) -> str:\n context = {\n \"submitted_answer\": submitted_answer,\n \"question\": submitted_answer.question,\n }\n return loader.render_to_string(\"mcq_bank/answer_response.html\", context=context, request=request)\n","repo_name":"DeakinMeDUSA/medusa_website","sub_path":"medusa_website/mcq_bank/views/quiz_take.py","file_name":"quiz_take.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12134833300","text":"def testit(s):\n ans=\"\"\n for a,b in zip(s[0::2], s[1::2]):\n ans += chr(ord(min(a,b)) + abs(ord(a)-ord(b)) // 2)\n \n if (len(s)%2 != 0):\n ans += s[-1:] \n return ans \n\nprint (testit(\"hheellllo\"))","repo_name":"hgf777-br/CodeWarsPython","sub_path":"Thinking_e_Testing_Incomplete_string.py","file_name":"Thinking_e_Testing_Incomplete_string.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7101205769","text":"#!/usr/bin/python3.4\n\nimport os, time, sys\nfrom getfiles import read_int, read_float, choose_file, get_filename, get_fileid, execute\nfrom readclustered import read_clustered, variation_of_information\nfrom configs import ClusteringConfig,\\\n TfidfConfig, RandConfig, SilhouetteConfig, VariationOfInformationConfig\n\nPIPE_NAME = ''\nresult_stats_path = '/home/zby/MAGISTERKA/MGR/results_stats/'\nresults_path = '/home/zby/MAGISTERKA/MGR/results/'\ndoc_path = '/home/zby/MAGISTERKA/law'\n\nEXTENSIONS = {'clustered' : '.clustered',\n 'tclustered' : '.clustered.t',\n 'feature' : '.tfidf',\n 'stemmed' : '.stem',\n 'stopwords' : '.stem.stop'}\n\nclass CanceledException(Exception):\n \"\"\"\n Error raised when user cancles operation, just show menu again.\n \"\"\"\n pass\n\ndef menu():\n \"\"\"\n Shows the menu\n \"\"\"\n print(\"0. exit\")\n print(\"1. cluster [obsolete]\")\n print(\"2. get tfidf [obsolete]\")\n print(\"3. count rand\")\n print(\"4. count silhouette\")\n print(\"5. count variation of information\")\n print(\"10. print param line form last execution\")\n\ndef cancel():\n \"\"\"\n Cancles current operatiom\n \"\"\"\n raise CanceledException()\n\ndef try_again():\n \"\"\"\n Prints try again message\n \"\"\"\n return \"No such option, please try again.\"\n\ndef read_choice(switcher, read_func, def_value, msg, limit):\n \"\"\"\n Reads menu choice\n \"\"\"\n while True:\n val = read_func(msg, def_value, limit)\n func = switcher.get(val, try_again)\n param = func()\n if param != try_again():\n return param\n print(param)\n\ndef picker(last_picker):\n \"\"\"\n Reads and constructs picker param\n \"\"\"\n if last_picker is not None:\n print(\"-1. last used [{}]\".format(last_picker))\n print(\"0. cancel\")\n print(\"1. random picker\")\n print(\"2. sequential picker\")\n print(\"3. MST picker\")\n pdict = {\n 0 : cancel,\n 1 : lambda: \"-rand\",\n 2 : lambda: \"-seq\",\n 3 : lambda: \"-dim\"\n }\n msg = \"Choose picker [0]: \"\n if last_picker is not None:\n msg = \"Coose picker [-1]: \"\n return read_choice(pdict, read_int, -1, msg, 4)\n\ndef distance(last_dist):\n \"\"\"\n Reads and sets distance param\n \"\"\"\n if last_dist is not None:\n print(\"-1. last used [{}]\".format(last_dist))\n print(\"0. cancel\")\n print(\"1. Hamming\")\n print(\"2. Manhattan\")\n print(\"3. Euclidean\")\n print(\"4. Cosine\")\n ddict = {\n 0 : cancel,\n 1 : lambda: \"-dham\",\n 2 : lambda: \"-dman\",\n 3 : lambda: \"-deuc\",\n 4 : lambda: \"-dcos\"\n }\n msg = \"Choose distance [0]: \"\n if last_dist is not None:\n msg = \"Choose distance [-1]: \"\n return read_choice(ddict, read_int, -1, msg, 5)\n\ndef cluster(cluster_config):\n \"\"\"\n Gets clustering stuff and executes\n \"\"\"\n tfidf = ()\n tfidf_ext = [EXTENSIONS[\"feature\"]]\n picker_param = None\n dist_param = None\n iters = 0\n out_file = ()\n exts = [EXTENSIONS[\"clustered\"], EXTENSIONS[\"tclustered\"]]\n if cluster_config is not None:\n picker_param = picker(cluster_config.picker)\n dist_param = distance(cluster_config.distance)\n tfidf = choose_file(results_path, tfidf_ext, get_fileid(cluster_config.tfidf), [])\n out_file = choose_file(results_path, exts, get_fileid(cluster_config.out), [])\n iters = read_int(\n \"Numer of iteratios [{}]: \".format(\n cluster_config.iterations),\n cluster_config.iterations)\n else:\n picker_param = picker(None)\n dist_param = distance(None)\n tfidf = choose_file(results_path, tfidf_ext, None, [])\n out_file = choose_file(results_path, exts, None, [])\n iters = read_int(\"Numer of iteratios [25]: \", 25)\n cluster_config = ClusteringConfig(tfidf, out_file, picker_param, dist_param, iters, None)\n execute(cluster_config)\n return cluster_config\n\n\ndef count_tfidf(tfidf_config):\n \"\"\"\n Method sets and counts tfidf\n \"\"\"\n stem_file = ()\n stem_ext = [EXTENSIONS[\"stemmed\"]]\n stop_out = ()\n stop_in = ()\n stop_ext = [EXTENSIONS[\"stopwords\"]]\n stop_stats = ()\n tfidf = ()\n tfidf_ext = [EXTENSIONS[\"feature\"]]\n min_variation = read_float('Please provide minimal variation: [{}]'.format(0), 0)\n if tfidf_config is None:\n stem_file = choose_file(results_path, stem_ext, None, [])\n stop_out = choose_file(results_path, stop_ext, None, [])\n stop_in = choose_file(results_path, stop_ext, None, [])\n stop_stats = choose_file(result_stats_path, ['.txt'], None, [])\n tfidf = choose_file(results_path, tfidf_ext, None, [])\n min_variation = read_float('Please provide minimal varation: ', 0)\n else:\n stem_file = choose_file(results_path, stem_ext, get_fileid(tfidf_config.stem), [])\n stop_out = choose_file(results_path, stop_ext, get_fileid(tfidf_config.stop_out), [])\n stop_in = choose_file(results_path, stop_ext, get_fileid(tfidf_config.stop_in), [])\n stop_stats = choose_file(\n result_stats_path, ['.txt'], get_fileid(tfidf_config.stop_stats), [])\n tfidf = choose_file(results_path, tfidf_ext, get_fileid(tfidf_config.tfidf), [])\n min_variation = read_float('Please provide minimal varation: ', tfidf_config.variation)\n tfidf_config = TfidfConfig(\n stem_file, stop_out, stop_stats, stop_in, tfidf, min_variation, 0, None)\n execute(tfidf_config)\n return tfidf_config\n\ndef count_rand(rand_config):\n \"\"\" function counts rand, if config present\n last used can be chosen \"\"\"\n file1 = ()\n file2 = ()\n exts = [EXTENSIONS[\"clustered\"], EXTENSIONS[\"tclustered\"]]\n if rand_config is not None:\n file1 = choose_file(results_path, exts, get_fileid(rand_config.first_partition), [])\n file2 = choose_file(\n results_path, exts, get_fileid(rand_config.second_partition), [get_fileid(file1)])\n else:\n file1 = choose_file(results_path, exts, None, [])\n file2 = choose_file(results_path, exts, None, [get_fileid(file1)])\n print(PIPE_NAME)\n rand_config = RandConfig(file1, file2, None)\n execute(rand_config)\n return rand_config\n\ndef count_vario(vario_config):\n \"\"\" function counts variation of information, if config present\n last used can be chosen \"\"\"\n file1 = ()\n file2 = ()\n exts = [EXTENSIONS[\"clustered\"], EXTENSIONS[\"tclustered\"]]\n if vario_config is not None:\n file1 = choose_file(results_path, exts, get_fileid(vario_config.first_partition), [])\n file2 = choose_file(\n results_path, exts, get_fileid(vario_config.second_partition), [get_fileid(file1)])\n else:\n file1 = choose_file(results_path, exts, None, [])\n file2 = choose_file(results_path, exts, None, [get_fileid(file1)])\n print(PIPE_NAME)\n vario_config = VariationOfInformationConfig(file1, file2, None)\n clust1 = read_clustered(get_filename(file1))\n clust2 = read_clustered(get_filename(file2))\n var, norm = variation_of_information(clust1, clust2)\n print(\"VARIATION_OF_INFORMATION {}\".format(norm))\n return vario_config\n\ndef count_silhouette(sil_config):\n \"\"\" count silhouette index\n \"\"\"\n dist_param = ''\n partition = ()\n tfidf = ()\n exts_partition = [EXTENSIONS[\"clustered\"], EXTENSIONS[\"tclustered\"]]\n exts_tfidf = [EXTENSIONS[\"feature\"]]\n if sil_config is None:\n dist_param = distance(None)\n partition = choose_file(results_path, exts_partition, None, [])\n tfidf = choose_file(results_path, exts_tfidf, None, [])\n else:\n dist_param = distance(sil_config.lastDistance)\n partition = choose_file(results_path, exts_partition, get_fileid(sil_config.partition), [])\n tfidf = choose_file(results_path, exts_tfidf, get_fileid(sil_config.tfidf), [])\n sil_config = SilhouetteConfig(partition, tfidf, dist_param, None)\n execute(sil_config)\n return sil_config\n\ndef open_pipe():\n \"\"\"\n currently not used, hangs on open\n \"\"\"\n if len(sys.argv) > 2 and sys.argv[1] == '-pipe':\n pipe_name = sys.argv[2]\n print(pipe_name)\n if not os.path.exists(pipe_name):\n os.mkfifo(pipe_name)\n pipein = os.open(pipe_name, os.O_RDONLY)\n return os.fdopen(pipein)\n else:\n raise ValueError\n\ndef read_pipe_line():\n \"\"\"\n Reads pipe - not used now.\n \"\"\"\n pipein = open_pipe()\n while True:\n line = pipein.readline()\n if len(line) == 0:\n return\n yield line\n\nif __name__ == \"__main__\":\n SWITCH = {\n 1 : None,\n 2 : None,\n 3 : None,\n 4 : None,\n 5 : None\n }\n LAST = None\n while True:\n menu()\n CHOICE = read_int(\"Choose number [0]: \", 0, 10)\n print(\"Chosen option is {}\".format(CHOICE))\n try:\n if CHOICE == 0:\n break\n elif CHOICE == 1:\n SWITCH[CHOICE] = cluster(SWITCH[CHOICE])\n elif CHOICE == 2:\n SWITCH[CHOICE] = count_tfidf(SWITCH[CHOICE])\n elif CHOICE == 3:\n SWITCH[CHOICE] = count_rand(SWITCH[CHOICE])\n elif CHOICE == 4:\n SWITCH[CHOICE] = count_silhouette(SWITCH[CHOICE])\n elif CHOICE == 5:\n SWITCH[CHOICE] = count_vario(SWITCH[CHOICE])\n elif CHOICE == 10:\n print(LAST.to_string())\n LAST = SWITCH[CHOICE]\n except CanceledException:\n pass\n print(\"Done\\n\")\n exit(0)\n\n\n","repo_name":"benkopolis/kmeanstriangleclustering","sub_path":"app/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":9554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12646775445","text":"r\"\"\"Python bindings for liblouis\n\"\"\"\n\nfrom distutils.core import setup\nimport louis\n\nclassifiers = [\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',\n 'Programming Language :: Python',\n 'Topic :: Text Processing :: Linguistic',\n ]\n\nsetup(name=\"louis\",\n description=__doc__,\n download_url = \"http://code.google.com/p/liblouis/\",\n license=\"LGPLv2.2\",\n classifiers=classifiers,\n version=louis.version().split(',')[0].split('-',1)[-1],\n packages=[\"louis\"])\n","repo_name":"kiwibrowser/src","sub_path":"third_party/liblouis/src/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"38418433333","text":"# -*- coding:utf-8 -*-\r\n# @Time : 2021/3/28 14:50\r\n# @Author: LCHJ\r\n# @File : vgg.py\r\nimport torch.nn as nn\r\n\r\n\r\nclass VGG(nn.Module):\r\n \r\n def __init__(self, features, num_classes=128):\r\n super(VGG, self).__init__()\r\n self.features = features\r\n self.avgpool = nn.AdaptiveAvgPool2d((5, 5))\r\n self.classifier = nn.Sequential(\r\n nn.Linear(128 * 5 * 5, num_classes),\r\n # nn.ReLU(True),\r\n # nn.Dropout(p=0.5),\r\n # nn.Linear(2048, num_classes),\r\n )\r\n self._initialize_weights()\r\n \r\n def forward(self, x):\r\n x = self.features(x)\r\n # x = self.avgpool(x)\r\n # 在第一维上将每个image拉成一维\r\n x = x.view(x.size()[0], -1)\r\n # x = self.classifier(x)\r\n return x\r\n \r\n def _initialize_weights(self):\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n # 是否为批归一化层\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.constant_(m.weight, 1)\r\n nn.init.constant_(m.bias, 0)\r\n elif isinstance(m, nn.Linear):\r\n nn.init.normal_(m.weight, 0, 0.01)\r\n nn.init.constant_(m.bias, 0)\r\n\r\n\r\ndef make_layers(cfg, batch_norm=False, in_channels=1):\r\n layers = []\r\n for v in cfg:\r\n if v == 'M':\r\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\r\n else:\r\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\r\n if batch_norm:\r\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\r\n else:\r\n layers += [conv2d, nn.ReLU(inplace=True)]\r\n in_channels = v\r\n return nn.Sequential(*layers)\r\n\r\n\r\n'''\r\n1、一张原始图片被resize到指定大小,本文使用105x105。\r\n2、conv1包括两次[3,3]卷积网络,一次2X2最大池化,输出的特征层为64通道。\r\n3、conv2包括两次[3,3]卷积网络,一次2X2最大池化,输出的特征层为128通道。\r\n4、conv3包括三次[3,3]卷积网络,一次2X2最大池化,输出的特征层为256通道。\r\n5、conv4包括三次[3,3]卷积网络,一次2X2最大池化,输出的特征层为512通道。\r\n6、conv5包括三次[3,3]卷积网络,一次2X2最大池化,输出的特征层为512通道。\r\n'''\r\ncfgs = {\r\n # 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M']\r\n 'D': [64, 64, 'M', 128, 128]\r\n}\r\n\r\n\r\ndef VGG6(in_channels, **kwargs):\r\n model = VGG(make_layers(cfgs[\"D\"], batch_norm=True, in_channels=in_channels), **kwargs)\r\n return model\r\n","repo_name":"LCHJ/Phd-Advisor-pytorch","sub_path":"PhD_AHML/nets/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37468424959","text":"from contextlib import contextmanager\nimport importlib.util\nimport logging\nimport os\nimport shlex\nimport subprocess as sp\nimport typing as tp\nfrom pathlib import Path\n\nfrom .main import DecoratedMain\nfrom .log import fatal\nfrom .xp import XP\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CommandError(Exception):\n pass\n\n\ndef run_command(command, **kwargs):\n proc = sp.run(command, stdout=sp.PIPE, stderr=sp.STDOUT, **kwargs)\n if proc.returncode:\n command_str = \" \".join(shlex.quote(c) for c in command)\n raise CommandError(\n f\"Command {command_str} failed ({proc.returncode}): \\n\" + proc.stdout.decode())\n return proc.stdout.decode().strip()\n\n\ndef check_repo_clean(root: Path, main: DecoratedMain):\n out = run_command(['git', 'status', '--porcelain'])\n filtered = []\n # Here we try to detect the grids package and allow uncommitted changes\n # only to that folder. The rational is that as we edit the grid file, it is a pain\n # to constantly be commiting change to it and it should not impact the actual run code.\n grid_name = main.dora.grid_package\n if grid_name is None:\n grid_name = main.package + \".grids\"\n spec = importlib.util.find_spec(grid_name)\n grid_path: tp.Optional[Path] = None\n if spec is not None:\n assert spec.origin is not None\n grid_path = Path(spec.origin).resolve().parent\n for line in out.split(\"\\n\"):\n if not line:\n continue\n parts = shlex.split(line)\n paths: tp.List[str] = []\n if len(parts) == 2:\n paths.append(parts[1])\n elif len(parts) == 4:\n assert parts[3] == \"->\"\n paths += [parts[1], parts[2]]\n else:\n assert \"Invalid parts\", parts\n line_clean = True\n for path in paths:\n if grid_path is None:\n line_clean = False\n break\n rpath = (root / path).resolve()\n try:\n rpath.relative_to(grid_path)\n except ValueError:\n line_clean = False\n if not line_clean:\n filtered.append(line)\n if filtered:\n files = '\\n'.join(filtered)\n fatal(\"Repository is not clean! The following files should be commited \"\n f\"or git ignored: \\n {files}\")\n\n\ndef get_git_root():\n return Path(run_command(['git', 'rev-parse', '--show-toplevel'])).resolve()\n\n\ndef get_git_commit(repo: Path = Path('.')):\n return run_command(['git', 'log', '-1', '--format=%H'], cwd=repo)\n\n\ndef shallow_clone(source: Path, target: Path):\n tmp_target = target.parent / (target.name + \".tmp\")\n run_command(['git', 'clone', '--depth=1', 'file://' + str(source), str(tmp_target)])\n # We are not sure that there wasn't a new commit in between, so to make\n # sure the folder name is correct, we clone to a temporary name, then rename to the\n # actual commit in there. It seems there is no easy way to directly make a shallow\n # clone to a specific commit (only specific branch or tag).\n actual_commit = get_git_commit(tmp_target)\n actual_target = target.parent / actual_commit\n tmp_target.rename(actual_target)\n return actual_target\n\n\ndef get_new_clone(main: DecoratedMain) -> Path:\n \"\"\"Return a fresh clone in side the given path.\"\"\"\n source = get_git_root()\n commit = get_git_commit()\n check_repo_clean(source, main)\n codes = main.dora.dir / main.dora._codes\n codes.mkdir(parents=True, exist_ok=True)\n target = codes / commit\n if not target.exists():\n target = shallow_clone(source, target)\n assert target.exists()\n return target\n\n\n@contextmanager\ndef enter_clone(clone: Path):\n \"\"\"Context manager that temporarily relocates to a clean clone of the\n current git repository.\n \"\"\"\n cwd = Path('.').resolve()\n root = get_git_root()\n relative_path = cwd.relative_to(root)\n\n os.environ['_DORA_ORIGINAL_DIR'] = str(cwd)\n os.chdir(clone / relative_path)\n try:\n yield\n finally:\n os.chdir(cwd)\n del os.environ['_DORA_ORIGINAL_DIR']\n\n\ndef assign_clone(xp: XP, clone: Path):\n assert xp.dora.git_save\n code = xp.code_folder\n if code.exists():\n if code.is_symlink():\n code.unlink()\n elif code.is_dir():\n code.rename(code.parent / 'old_code')\n else:\n assert \"code folder should be symlink or folder\", code\n code.symlink_to(clone)\n\n\nAnyPath = tp.TypeVar(\"AnyPath\", str, Path)\n\n\ndef to_absolute_path(path: AnyPath) -> AnyPath:\n \"\"\"When using `git_save`, this takes a potentially relative path\n with respect to the original execution folder and return an absolute path.\n This is required if you use relative path with respect to this original folder.\n\n When using both `git_save` and Hydra, two change of directory happens:\n - Dora moves to git clone\n - Hydra moves to XP folder\n\n Hydra provides a `to_absolute_path()` function. In order to simplify your code,\n if `git_save` was not used, and Hydra is in use, this will fallback to calling\n Hydra version, so that you only need to ever call this function to cover all cases.\n \"\"\"\n klass = type(path)\n _path = Path(path)\n if '_DORA_ORIGINAL_DIR' not in os.environ:\n # We did not use git_save, we check first if Hydra is used,\n # in which case we use it to convert to an absolute Path.\n try:\n import hydra.utils\n except ImportError:\n if not _path.is_absolute():\n _path = Path(os.getcwd()) / _path\n else:\n _path = Path(hydra.utils.to_absolute_path(str(_path)))\n return klass(_path)\n else:\n # We used git_save, in which case we used the original dir saved by Dora.\n original_cwd = Path(os.environ['_DORA_ORIGINAL_DIR'])\n if _path.is_absolute():\n return klass(_path)\n else:\n return klass(original_cwd / _path)\n","repo_name":"facebookresearch/dora","sub_path":"dora/git_save.py","file_name":"git_save.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"52"} +{"seq_id":"6072816080","text":"import sys\nimport cv2\n\ncamera_port = 0\n\ncamera = cv2.VideoCapture(camera_port)\n\ndef get_image():\n\n\tval, im = camera.read()\n\treturn im\n\nfor i in xrange(60):\n\ttemp = get_image()\n\nprint(\"Ready to take image\")\n\ncamera_capture = get_image()\nfile = \"/Users/anubhabsen/Desktop/CVIT/image1.jpg\"\n\ncv2.imwrite(file, camera_capture)\n\nprint(\"Image taken and saved to file\")\n\ndel(camera)","repo_name":"anubhabsen/openCV-train","sub_path":"captureimage.py","file_name":"captureimage.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21685995725","text":"# \n# Eric Jeschke (eric@naoj.org)\n#\nimport threading\nimport yaml\n\nimport gtk, gobject\n\nimport Bunch\nimport common\nimport Page\nimport CommandObject\n\n# Default width of the main launcher buttons\ndefault_width = 150\n\nclass LauncherError(Exception):\n pass\n\nclass Launcher(object):\n \n def __init__(self, frame, name, title, execfn):\n self.frame = frame\n self.params = Bunch.Bunch()\n self.paramList = []\n self.row = 1\n self.col = 1\n self.max_col = self.col\n self.btn_width = 20\n self.execfn = execfn\n\n self.table = gtk.Table(rows=2, columns=2)\n self.table.set_name('launcher')\n self.table.show()\n\n self.btn_exec = gtk.Button(title)\n self.btn_exec.set_size_request(default_width, -1)\n self.btn_exec.connect(\"clicked\", lambda w: self.execute())\n self.btn_exec.show()\n\n self.table.attach(self.btn_exec, 0, 1, 1, 2,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n\n frame.pack_start(self.table, expand=False, fill=True)\n \n\n def addParam(self, name):\n self.paramList.append(name)\n # sort parameter list so longer strings are substituted first\n self.paramList.sort(lambda x,y: len(y) - len(x))\n\n def add_cmd(self, cmdstr):\n self.cmdstr = cmdstr\n\n def add_break(self):\n self.row += 2\n self.col = 1\n self.table.resize(self.row+1, self.max_col+1)\n\n def bump_col(self):\n self.col += 1\n self.max_col = max(self.col, self.max_col)\n self.table.resize(self.row+1, self.max_col+1)\n\n def add_input(self, name, width, defVal, label):\n \n lbl = gtk.Label(label)\n lbl.show()\n self.table.attach(lbl, self.col, self.col+1, self.row-1, self.row,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n field = gtk.Entry()\n field.set_width_chars(width)\n field.set_text(str(defVal))\n field.show()\n self.table.attach(field, self.col, self.col+1, self.row, self.row+1,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n self.bump_col()\n\n name = name.lower()\n self.params[name] = Bunch.Bunch(widget=field,\n get_fn=self.get_entry)\n self.addParam(name)\n\n\n def add_list(self, name, optionList, label):\n \n lbl = gtk.Label(label)\n self.table.attach(lbl, self.col, self.col+1, self.row-1, self.row,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n lbl.show()\n combobox = gtk.combo_box_new_text()\n options = []\n index = 0\n for opt, val in optionList:\n options.append(val)\n combobox.insert_text(index, opt)\n index += 1\n combobox.set_active(0)\n combobox.show()\n self.table.attach(combobox, self.col, self.col+1, self.row, self.row+1,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n self.bump_col()\n\n name = name.lower()\n self.params[name] = Bunch.Bunch(widget=combobox, \n get_fn=self.get_list,\n options=options)\n self.addParam(name)\n\n\n def add_radio(self, name, optionList, label):\n \n lbl = gtk.Label(label)\n self.table.attach(lbl, self.col, self.col+1, self.row-1, self.row,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n lbl.show()\n \n btn = None\n options = []\n for opt, val in optionList:\n btn = gtk.RadioButton(group=btn, label=opt)\n self.table.attach(btn, self.col, self.col+1, self.row, self.row+1,\n xoptions=gtk.FILL, yoptions=gtk.FILL,\n xpadding=1, ypadding=1)\n options.append((btn, val))\n self.bump_col()\n btn.show()\n\n name = name.lower()\n self.params[name] = Bunch.Bunch(get_fn=self.get_radio,\n options=options)\n self.addParam(name)\n\n def get_entry(self, bnch):\n return bnch.widget.get_text()\n\n def get_list(self, bnch):\n index = bnch.widget.get_active()\n try:\n return bnch.options[index]\n except IndexError:\n return None\n\n def get_radio(self, bnch):\n for widget, val in bnch.options:\n if widget.get_active():\n return val\n return None\n\n def getcmd(self):\n cmdstr = self.cmdstr\n \n for var in self.paramList:\n dvar = '$%s' % var.upper()\n if dvar in cmdstr:\n bnch = self.params[var]\n val = str(bnch.get_fn(bnch))\n cmdstr = cmdstr.replace(dvar, val)\n\n return cmdstr\n\n def execute(self):\n cmdstr = self.getcmd()\n self.execfn(cmdstr, self)\n\n def show_state(self, state):\n if state == 'queued':\n state = 'normal'\n\n self.btn_exec.modify_bg(gtk.STATE_NORMAL,\n common.launcher_colors[state])\n\n def reset(self):\n self.btn_exec.modify_bg(gtk.STATE_NORMAL,\n common.launcher_colors['normal'])\n\n\nclass LauncherList(object):\n \n def __init__(self, frame, name, title, execfn):\n self.llist = []\n self.ldict = {}\n self.count = 0\n self.frame = frame\n self.execfn = execfn\n self.vbox = gtk.VBox(spacing=2)\n frame.pack_start(self.vbox, expand=True, fill=True)\n\n def addSeparator(self):\n separator = gtk.HSeparator()\n separator.show()\n self.vbox.pack_start(separator, expand=False, fill=True)\n self.count += 1\n\n def addLauncher(self, name, title):\n frame = gtk.VBox()\n frame.show()\n self.vbox.pack_start(frame, expand=False, fill=True)\n self.count += 1\n \n launcher = Launcher(frame, name, title, self.execfn)\n \n self.llist.append(launcher)\n self.ldict[name.lower()] = launcher\n \n return launcher\n\n def getLauncher(self, name):\n return self.ldict[name.lower()]\n\n def getLaunchers(self):\n return self.ldict.values()\n\n def addLauncherFromDef(self, ast):\n assert ast.tag == 'launcher'\n ast_label, ast_body = ast.items\n\n assert ast_label.tag == 'label'\n name = ast_label.items[0]\n\n launcher = self.addLauncher(name, name)\n\n for ast in ast_body.items:\n assert ast.tag in ('cmd', 'list', 'select', 'input', 'break')\n \n if ast.tag == 'break':\n launcher.add_break()\n\n elif ast.tag == 'input':\n var, width, val, lbl = ast.items\n width = int(width)\n launcher.add_input(var, width, val, lbl)\n \n elif ast.tag == 'select':\n var, ast_list, lbl = ast.items\n vallst = []\n\n if ast_list.tag == 'pure_val_list':\n for item in ast_list.items:\n vallst.append((item, item))\n \n elif ast_list.tag == 'subst_val_list':\n for item_ast in ast_list.items:\n assert item_ast.tag == 'value_pair'\n lhs, rhs = item_ast.items\n vallst.append((lhs, rhs))\n \n launcher.add_radio(var, vallst, lbl)\n \n elif ast.tag == 'list':\n var, ast_list, lbl = ast.items\n vallst = []\n\n if ast_list.tag == 'pure_val_list':\n for item in ast_list.items:\n vallst.append((item, item))\n \n elif ast_list.tag == 'subst_val_list':\n for item_ast in ast_list.items:\n assert item_ast.tag == 'value_pair'\n lhs, rhs = item_ast.items\n vallst.append((lhs, rhs))\n \n launcher.add_list(var, vallst, lbl)\n \n elif ast.tag == 'cmd':\n cmd, ast_params = ast.items\n cmd_l = [cmd.upper()]\n\n for item_ast in ast_params.items:\n assert item_ast.tag == 'param_pair'\n lhs, rhs = item_ast.items\n cmd_l.append('%s=%s' % (lhs.upper(), rhs))\n\n cmdstr = ' '.join(cmd_l)\n\n launcher.add_cmd(cmdstr)\n\n else:\n pass\n \n def addFromDefs(self, ast):\n assert ast.tag == 'launchers'\n \n for ast in ast.items:\n if ast.tag == 'sep':\n self.addSeparator()\n\n else:\n self.addLauncherFromDef(ast)\n\n def _validate_elt(self, elt):\n if isinstance(elt, list) and len(elt) == 2:\n return elt\n \n elt_s = str(elt)\n if not '=' in elt_s:\n return [elt_s, elt_s]\n else:\n return elt_s.split('=')\n \n def addLauncherFromYAMLdef(self, d):\n assert isinstance(d, dict) and d.has_key('label'), \\\n LauncherError(\"Malformed launcher def: expected key 'label': %s\" % (\n str(d)))\n name = d['label']\n\n launcher = self.addLauncher(name, name)\n\n assert d.has_key('cmd'), \\\n LauncherError(\"Malformed launcher def: expected key 'cmd': %s\" % (\n str(d)))\n launcher.add_cmd(d['cmd'])\n\n if d.has_key('params'):\n for param in d['params']:\n if param == 'break':\n launcher.add_break()\n continue\n\n if isinstance(param, dict):\n assert param.has_key('type')\n p_type = param['type'].lower()\n\n if p_type == 'input':\n var = param['name']\n width = param.get('width', 10)\n val = param.get('value', '')\n lbl = param.get('label', '')\n width = int(width)\n\n launcher.add_input(var, width, val, lbl)\n\n elif p_type == 'select':\n var = param['name']\n vallst = map(self._validate_elt, param['values'])\n lbl = param.get('label', '')\n\n launcher.add_radio(var, vallst, lbl)\n\n elif p_type == 'list':\n var = param['name']\n vallst = map(self._validate_elt, param['values'])\n lbl = param.get('label', '')\n\n launcher.add_list(var, vallst, lbl)\n\n elif isinstance(param, list):\n var = param[0]\n p_type = param[1].lower()\n\n if p_type == 'input':\n width = 10\n val = ''\n lbl = ''\n if len(param) > 2:\n width = param[2]\n width = int(width)\n if len(param) > 3:\n val = param[3]\n if len(param) > 4:\n lbl = param[4]\n\n launcher.add_input(var, width, val, lbl)\n\n elif p_type == 'select':\n vallst = map(self._validate_elt, param[2])\n lbl = ''\n if len(param) > 3:\n lbl = param[3]\n\n launcher.add_radio(var, vallst, lbl)\n\n elif p_type == 'list':\n vallst = map(self._validate_elt, param[2])\n lbl = ''\n if len(param) > 3:\n lbl = param[3]\n\n launcher.add_list(var, vallst, lbl)\n\n else:\n # don't know what we are looking at\n continue\n \n \n def loadLauncher(self, d):\n for d in d['launchers']:\n if d == 'sep':\n self.addSeparator()\n\n elif isinstance(d, dict):\n self.addLauncherFromYAMLdef(d)\n\n\nclass LauncherPage(Page.CommandPage):\n\n def __init__(self, frame, name, title):\n\n super(LauncherPage, self).__init__(frame, name, title)\n\n self.queueName = 'launcher'\n self.tm_queueName = 'launcher'\n\n scrolled_window = gtk.ScrolledWindow()\n scrolled_window.set_border_width(2)\n \n scrolled_window.set_policy(gtk.POLICY_AUTOMATIC,\n gtk.POLICY_AUTOMATIC)\n frame.pack_start(scrolled_window, expand=True, fill=True)\n \n scrolled_window.show()\n\n self.fw = gtk.VBox()\n scrolled_window.add_with_viewport(self.fw)\n \n self.llist = LauncherList(self.fw, name, title,\n self.execute)\n\n self.btn_cancel = gtk.Button(\"Cancel\")\n self.btn_cancel.connect(\"clicked\", lambda w: self.cancel())\n self.btn_cancel.modify_bg(gtk.STATE_NORMAL,\n common.launcher_colors['cancelbtn'])\n self.btn_cancel.show()\n self.leftbtns.pack_start(self.btn_cancel, padding=4)\n\n self.btn_pause = gtk.Button(\"Pause\")\n self.btn_pause.connect(\"clicked\", self.toggle_pause)\n self.btn_pause.show()\n self.leftbtns.pack_start(self.btn_pause)\n\n menu = self.add_pulldownmenu(\"Page\")\n\n # Add items to the menu\n item = gtk.MenuItem(label=\"Reset\")\n menu.append(item)\n item.connect_object (\"activate\", lambda w: self.reset(),\n \"menu.Reset\")\n item.show()\n\n #self.add_close(side=Page.LEFT)\n #self.add_close()\n item = gtk.MenuItem(label=\"Close\")\n menu.append(item)\n item.connect_object (\"activate\", lambda w: self.close(),\n \"menu.Close\")\n item.show()\n\n scrolled_window.show_all()\n\n\n def load(self, buf):\n ymldef = yaml.load(buf)\n self.llist.loadLauncher(ymldef)\n\n if ymldef.has_key('tabname'):\n self.setLabel(ymldef['tabname'])\n\n def addFromDefs(self, ast):\n self.llist.addFromDefs(ast)\n\n def addFromList(self, llist):\n self.llist.addFromDefs(llist)\n\n def close(self):\n super(LauncherPage, self).close()\n\n def reset(self):\n for launcher in self.llist.getLaunchers():\n launcher.reset()\n self.reset_pause()\n\n def execute(self, cmdstr, launcher):\n \"\"\"This is called when a launcher button is pressed.\"\"\"\n self.logger.info(cmdstr)\n\n # tag the text so we can manipulate it later\n cmdObj = LauncherCommandObject('ln%d', self.queueName,\n self.logger,\n launcher, cmdstr)\n\n common.controller.execOne(cmdObj, 'launcher')\n\n\nclass LauncherCommandObject(CommandObject.CommandObject):\n\n def __init__(self, format, queueName, logger, launcher, cmdstr):\n self.launcher = launcher\n self.cmdstr = cmdstr\n \n super(LauncherCommandObject, self).__init__(format, queueName,\n logger)\n\n def mark_status(self, txttag):\n # This MAY be called from a non-gui thread\n common.gui_do(self.launcher.show_state, txttag)\n\n def get_preview(self):\n return self.get_cmdstr()\n \n def get_cmdstr(self):\n return self.cmdstr\n\n\n#END\n","repo_name":"scexao-org/Instrument-Control-Main","sub_path":"src/lib/python/gen2/Gen2/integgui2/view/LauncherPage.py","file_name":"LauncherPage.py","file_ext":"py","file_size_in_byte":16055,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"42203572600","text":"import sys\n# input = sys.stdin.buffer.readline\nfrom collections import deque\ndef I(): return(list(map(int,input().split())))\ndef sieve(n):\n\ta=[1]*n\n\tfor i in range(2,n):\n\t if a[i]:\n\t for j in range(i*i,n,i):\n\t a[j]=0\n\treturn a\ndef check(i,j):\n\tif matr[i][j]==\"B\":\n\t\tfor x,y in (i+1,j),(i-1,j),(i,j-1),(i,j+1):\n\t\t\tif x>=0 and y>=0 and x=0 and y>=0 and x 300:\n mymap.position(math.copysign(1000,xm), 0.0, 0.0)\n mymap.draw()\n if abs(zm) > 300:\n mymap.position(0.0, 0.0, math.copysign(1000,zm))\n mymap.draw()\n if abs(xm) > 300:\n mymap.position(math.copysign(1000,xm), 0.0, math.copysign(1000,zm))\n mymap.draw()\n mymap.position(0.0, 0.0, 0.0)\n myecube.draw()\n mytrees1.draw()\n mytrees2.draw()\n mytrees3.draw()\n\n mx, my = mymouse.velocity() #change to position() if Camera switched to absolute=True (default)\n buttons = -1 #mymouse.button_status()\n\n rot = - mx * 0.2\n tilt = my * 0.2\n\n n += 1\n #Press ESCAPE to terminate\n k = mykeys.read()\n #print(len(DISPLAY.keys_pressed))\n if k >-1 or buttons > mymouse.BUTTON_UP:\n if k == 119 or buttons == mymouse.LEFT_BUTTON: #key w forward\n step = [0.5, 0.0, 0.5]\n crab = False\n elif k == 115 or buttons == mymouse.RIGHT_BUTTON: #kry s back\n step = [-0.25, 0.0, -0.25]\n crab = False\n elif k == 97: #key a crab left\n step = [0.25, 0.0, 0.25]\n crab = True\n elif k == 100: #key d crab right\n step = [-0.25, 0.0, -0.25]\n crab = True\n elif k == 112: #key p picture\n pi3d.screenshot(\"forestWalk\" + str(scshots) + \".jpg\")\n scshots += 1\n time.sleep(0.1)\n elif k == 10: #key RETURN\n mc = 0\n elif k == 27: #Escape key\n mykeys.close()\n mymouse.stop()\n DISPLAY.stop()\n break\n elif k == ord('f'):\n roll = 1.0\n elif k == ord('m'):\n print(f\"FPS={DISPLAY.fps():5.1f}\")\n time.sleep(0.1)\n\n\n halfsize = mapsize / 2.0\n xm = (xm + halfsize) % mapsize - halfsize # wrap location to stay on map -500 to +500\n zm = (zm + halfsize) % mapsize - halfsize\nprint(\"{:.1f}fps\".format(n / (time.time() - start)))","repo_name":"pi3d/pi3d_demos","sub_path":"ForestWalk.py","file_name":"ForestWalk.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"52"} +{"seq_id":"11869534739","text":"from random import randint\nfrom time import sleep\n\nfrom pitop import Pitop\nfrom pitop.robotics.drive_controller import DriveController\n\n# Create a basic robot\nrobot = Pitop()\ndrive = DriveController(left_motor_port=\"M3\", right_motor_port=\"M0\")\nrobot.add_component(drive)\n\n\n# Use miniscreen display\nrobot.miniscreen.display_multiline_text(\"hey there!\")\n\n\ndef random_speed_factor():\n # 0.01 - 1, 0.01 resolution\n return randint(1, 100) / 100\n\n\ndef random_sleep():\n # 0.5 - 2, 0.5 resolution\n return randint(1, 4) / 2\n\n\n# Move around randomly\nrobot.drive.forward(speed_factor=random_speed_factor())\nsleep(random_sleep())\n\nrobot.drive.left(speed_factor=random_speed_factor())\nsleep(random_sleep())\n\nrobot.drive.backward(speed_factor=random_speed_factor())\nsleep(random_sleep())\n\nrobot.drive.right(speed_factor=random_speed_factor())\nsleep(random_sleep())\n","repo_name":"thymjan/pi-top-Python-SDK","sub_path":"examples/recipes/robot_move_random.py","file_name":"robot_move_random.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"37134017513","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom .models import Couser,Lesson,Tag, User, Comment\nfrom rest_framework import viewsets, permissions, generics\nfrom rest_framework.decorators import action\nfrom .serializers import CourseSerializer, LessonSerializer, UserSeriazlier, CommentSerializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.parsers import MultiPartParser\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom django.db import IntegrityError\nclass CommentAPIView(APIView):\n def get(self, request, lesson_id):\n comments = Comment.objects.filter(lesson_id = lesson_id)\n serializer = CommentSerializer(comments, many = True)\n \n return Response(serializer.data, status= status.HTTP_200_OK)\n \n\n def post(self, request,lesson_id):\n content = request.data.get('content')\n if content is not None:\n try: \n c = Comment.objects.create(content = content , user = request.user, lesson_id = lesson_id)\n \n except IntegrityError:\n err_msg = \"Lesson does not exits!\"\n else:\n return Response(CommentSerializer(c).data, status= status.HTTP_201_CREATED)\n else:\n err_msg = \"Content is Required!!\"\n\n return Response(data={'error_msg':err_msg}, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n# rest_framework\nclass CourseViewSet(viewsets.ModelViewSet):\n queryset = Couser.objects.filter(active=True)\n serializer_class = CourseSerializer\n #Phương thức chứng thực user\n permission_classes = [permissions.IsAuthenticated]\n\n #Ghi dè phương thức chứng thực user\n # user ko đăng nhập vẫn xem được nội dung\n # def get_permissions(self):\n # if self.action == 'list':\n # return[permissions.AllowAny()]\n # return [permissions.IsAuthenticated()]\n \n # Tự động tạo sẵng \n #List(Get) -> show khóa khọc\n #.. (POST) -> Them khoa hoc\n #detail -> Xem chi tiết 1 khóa học\n #...(PUT) -> Cập nhật\n #...(DELETE) -> Xóa khóa học\n\n\n\n\n\n\n\nclass LessonViewSet(viewsets.ModelViewSet):\n queryset = Lesson.objects.filter(active = True)\n serializer_class = LessonSerializer\n @action(methods=['post'], detail=True, url_name= \"hide-lesson\")\n #/lesssons/{pk}/hide-lesson\n def hide_lesson(self, request, pk):\n try:\n l = Lesson.objects.get(pk=pk)\n if l.active == True:\n l.active = False\n l.save()\n else:\n l.active = True\n l.save()\n except Lesson.DoesNotExist:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n return Response(data=LessonSerializer(l, context={'request': request}).data, status=status.HTTP_200_OK)\n \n #add tag cho lesson\n @action(methods=['post'], detail= True, name=\"add tags to a lesson\",url_path='add-tags-to-lesson', \nurl_name='add-tags')\n def add_tags_to_lesson(self, request, pk):\n try:\n lesson = Lesson.objects.get(pk=pk)\n tags = request.data.get('tags')\n for tag in tags.split(','): \n t, _ = Tag.objects.get_or_create(name=tag.strip())\n lesson.tags.add(t)\n lesson.save()\n except Lesson.DoesNotExist | KeyError:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n serializer = LessonSerializer(lesson)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n\n\n\nclass UserViewSet(viewsets.ViewSet, generics.CreateAPIView,\n generics.RetrieveAPIView, generics.ListAPIView, generics.UpdateAPIView):\n queryset = User.objects.filter(is_active = True)\n serializer_class = UserSeriazlier\n parser_classes = [MultiPartParser,]\n \n # def get_permissions(self):\n # if self.action == 'retrieve':\n # return [permissions.IsAuthenticated()]\n # return [permissions.AllowAny()]\n\n # @action(methods=['post'], detail=True, url_name=\"update-user\")\n # def Updata(self, request, pk):\n # try:\n # l = User.objects.get(pk=pk)\n # l.first_name = 'first_name'\n # l.last_name = 'last_name'\n # l.email = 'email'\n # l.set_password('password')\n # l.avatar = 'avatar'\n # l.save()\n # except Lesson.DoesNotExist:\n # return Response(status=status.HTTP_400_BAD_REQUEST)\n # return Response(data=LessonSerializer(l, context={'request': request}).data, status=status.HTTP_200_OK)\n\n#class UserViewSet_Update()\n\n#-----------------------------------------------------------------------------------------------------------\n\n\n#Khanh Custom 200 ok \ndef index(request):\n return render(request ,template_name='index.html', context={\n 'name':'Khanh Duong'\n })\n\n\ndef test(request):\n couser = Couser.objects.all().values()\n template = loader.get_template('test.html')\n context = {\n 'Couser': couser,\n }\n return HttpResponse(template.render(context,request))\n\n#khanh custom Hiện thị sản phẩm + html '200 OK'\ndef product(request):\n proDuct = Couser.objects.all().values()\n #cateGory = cateGory[:10]\n template = loader.get_template('product.html')\n context = {\n 'proDuct': proDuct,\n }\n return HttpResponse(template.render(context,request))\n\n\ndef detail(request,id):\n couser = Couser.objects.get(id = id)\n template = loader.get_template('detail.html')\n context = {\n 'Couser': couser,\n }\n return HttpResponse(template.render(context,request))\n\n\n\ndef wellcom(request,year):\n return HttpResponse(\"hello\" + str(year))\n\ndef wellcom2(request,year):\n return HttpResponse(\"hello\" + str(year))\n\n\n","repo_name":"KhanhKhanh2211/studyDjango_CNLTHD","sub_path":"django/ecourses/courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75093118243","text":"from __future__ import unicode_literals\nfrom chatterbot.output.output_adapter import OutputAdapter\n\n\nclass ChatOutput(OutputAdapter):\n \"\"\"\n An output adapter that allows a ChatterBot instance to send\n responses to a Gitter room.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(ChatOutput, self).__init__(**kwargs)\n import requests\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n self.directline_host = kwargs.get('directline_host', 'http://localhost:8080/ChatUI')\n self.proxies = {'http': 'http://zactn13002p1:8080','https': 'http://zactn13002p1:8080'} \n\n self.headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'charset': 'utf-8'\n }\n\n # Join the Gitter room\n #room_data = self.join_room(self.gitter_room)\n #self.room_id = room_data.get('id')\n\n def _validate_status_code(self, response):\n code = response.status_code\n if code not in [200, 201]:\n raise self.HTTPStatusException('{} status code recieved'.format(code))\n\n def join_room(self, room_name):\n \"\"\"\n Join the specified Gitter room.\n \"\"\"\n import requests\n\n endpoint = '{}'.format(self.directline_host)\n response = requests.post(\n endpoint,\n headers=self.headers,\n #json={'uri': room_name},\n #proxies= self.proxies\n )\n self.logger.info('{} status joining room {}'.format(\n response.status_code, endpoint\n ))\n self._validate_status_code(response)\n print (response.json())\n return response.json()\n\n def send_message(self, text):\n \"\"\"\n Send a message to a Gitter room.\n \"\"\"\n import requests\n print (text)\n endpoint = '{}/rest/ChatService/chatMessages/{}'.format(self.directline_host,text)\n response = requests.get(\n endpoint,\n headers=self.headers\n #json={'text': text}\n #proxies= self.proxies\n )\n self.logger.info('{} sending message to {}'.format(\n response.status_code, endpoint\n ))\n self._validate_status_code(response)\n return response.json()\n\n def process_response(self, statement, session_id=None):\n if(statement.text!=\"\"):\n return statement\n self.send_message(statement.text)\n return statement\n\n class HTTPStatusException(Exception):\n \"\"\"\n Exception raised when unexpected non-success HTTP\n status codes are returned in a response.\n \"\"\"\n\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return repr(self.value)\n","repo_name":"mehtavinit9896/Chatbot","sub_path":"output/chatbot_output.py","file_name":"chatbot_output.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9160067215","text":"import time \n\nstart = time.time()\nsorted_list =[]\nnumbers = list(range(10000000))\nfor x in numbers:\n if x % 2 == 0:\n sorted_list.append(x**2)\nend = time.time() \nprint (\"Elapsed time (Using for loop and new list): {}\".format((end-start)))\n\nstart = time.time()\nnumbers = []\nfor x in range(10000000):\n if x % 2 == 0: \n numbers.append(x**2)\nend = time.time()\nprint (\"Elapsed time (Using an iterator): {}\".format((end-start)))\n\nstart = time.time()\nnumbers = [x**2 for x in range(10000000) if x % 2 == 0]\nend = time.time()\nprint (\"Elapsed time (list comprehension): {}\".format((end-start)))\n\n","repo_name":"saikatsahana77/Speed_Up_Python_Code","sub_path":"1. list vs iter vs comprehension.py","file_name":"1. list vs iter vs comprehension.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5496669281","text":"import os\n\n# This command produces an output we parse to get the logstash node IPs, example here:\n# NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES\n# logstash-pool-9b468dd96-x9g9c 1/1 Running 0 81s 192.168.16.90 ip-192-168-26-84.us-west-2.compute.internal \nwith os.popen('kubectl get pods -o wide -n logstash') as stream:\n pods_string = stream.read()\npods_list = pods_string.split(\"\\n\")\n\nhosts_list = []\nfor line in pods_list[1:]:\n if line != \"\":\n pod_info = line.split()\n if pod_info[5] != \"\":\n hosts_list.append('\"%s:5044\"' % pod_info[5])\n\nbeats_yaml = \"\"\nwith open('k8s_yaml/beats.yaml', mode='r') as f:\n beats_yaml = f.read()\n\nprint(beats_yaml.replace(\"LOGSTASH_HOSTS\", \", \".join(hosts_list), 1))\n","repo_name":"scalyr/logstash-output-scalyr","sub_path":"loadtest/beats-yaml-generator.py","file_name":"beats-yaml-generator.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9681039690","text":"from __future__ import annotations\n\nfrom typing import (\n IO,\n TYPE_CHECKING,\n Any,\n Awaitable,\n Callable,\n Dict,\n List,\n NoReturn,\n Optional,\n Tuple,\n Type,\n Union,\n cast,\n)\n\nfrom werkzeug.datastructures import Headers, MultiDict\nfrom werkzeug.formparser import default_stream_factory\nfrom werkzeug.http import parse_options_header\nfrom werkzeug.sansio.multipart import (\n Data,\n Epilogue,\n Field,\n File,\n MultipartDecoder,\n NeedData,\n)\nfrom werkzeug.urls import url_decode\n\nfrom .datastructures import FileStorage\n\n\nif TYPE_CHECKING:\n from .wrappers.request import Body\n\nStreamFactory = Callable[\n [Optional[int], Optional[str], Optional[str], Optional[int]],\n IO[bytes],\n]\n\nParserFunc = Callable[\n [\"FormDataParser\", \"Body\", str, Optional[int], Dict[str, str]],\n Awaitable[Tuple[MultiDict, MultiDict]],\n]\n\n\nclass FormDataParser:\n file_storage_class = FileStorage\n\n def __init__(\n self,\n stream_factory: StreamFactory = default_stream_factory,\n charset: str = \"utf-8\",\n errors: str = \"replace\",\n max_form_memory_size: Optional[int] = None,\n max_content_length: Optional[int] = None,\n cls: Optional[Type[MultiDict]] = MultiDict,\n silent: bool = True,\n ) -> None:\n self.stream_factory = stream_factory\n self.charset = charset\n self.errors = errors\n self.cls = cls\n self.silent = silent\n\n def get_parse_func(self, mimetype: str, options: Dict[str, str]) -> Optional[ParserFunc]:\n return self.parse_functions.get(mimetype)\n\n async def parse(\n self,\n body: \"Body\",\n mimetype: str,\n content_length: Optional[int],\n options: Optional[Dict[str, str]] = None,\n ) -> Tuple[MultiDict, MultiDict]:\n if options is None:\n options = {}\n\n parse_func = self.get_parse_func(mimetype, options)\n\n if parse_func is not None:\n try:\n return await parse_func(self, body, mimetype, content_length, options)\n except ValueError:\n if not self.silent:\n raise\n\n return self.cls(), self.cls()\n\n async def _parse_multipart(\n self,\n body: \"Body\",\n mimetype: str,\n content_length: Optional[int],\n options: Dict[str, str],\n ) -> Tuple[MultiDict, MultiDict]:\n parser = MultiPartParser(\n self.stream_factory,\n self.charset,\n self.errors,\n cls=self.cls,\n file_storage_cls=self.file_storage_class,\n )\n boundary = options.get(\"boundary\", \"\").encode(\"ascii\")\n\n if not boundary:\n raise ValueError(\"Missing boundary\")\n\n return await parser.parse(body, boundary, content_length)\n\n async def _parse_urlencoded(\n self,\n body: \"Body\",\n mimetype: str,\n content_length: Optional[int],\n options: Dict[str, str],\n ) -> Tuple[MultiDict, MultiDict]:\n form = url_decode(await body, self.charset, errors=self.errors, cls=self.cls)\n return form, self.cls()\n\n parse_functions: Dict[str, ParserFunc] = {\n \"multipart/form-data\": _parse_multipart,\n \"application/x-www-form-urlencoded\": _parse_urlencoded,\n \"application/x-url-encoded\": _parse_urlencoded,\n }\n\n\nclass MultiPartParser:\n def __init__(\n self,\n stream_factory: StreamFactory = default_stream_factory,\n charset: str = \"utf-8\",\n errors: str = \"replace\",\n max_form_memory_size: Optional[int] = None,\n cls: Type[MultiDict] = MultiDict,\n buffer_size: int = 64 * 1024,\n file_storage_cls: Type[FileStorage] = FileStorage,\n ) -> None:\n self.charset = charset\n self.errors = errors\n self.max_form_memory_size = max_form_memory_size\n self.stream_factory = stream_factory\n self.cls = cls\n self.buffer_size = buffer_size\n self.file_storage_cls = file_storage_cls\n\n def fail(self, message: str) -> NoReturn:\n raise ValueError(message)\n\n def get_part_charset(self, headers: Headers) -> str:\n content_type = headers.get(\"content-type\")\n\n if content_type:\n mimetype, ct_params = parse_options_header(content_type)\n return ct_params.get(\"charset\", self.charset)\n\n return self.charset\n\n def start_file_streaming(self, event: File, total_content_length: int) -> IO[bytes]:\n content_type = event.headers.get(\"content-type\")\n\n try:\n content_length = int(event.headers[\"content-length\"])\n except (KeyError, ValueError):\n content_length = 0\n\n container = self.stream_factory(\n total_content_length,\n content_type,\n event.filename,\n content_length,\n )\n return container\n\n async def parse(self, body: \"Body\", boundary: bytes, content_length: int) -> Tuple[MultiDict, MultiDict]:\n container: Union[IO[bytes], List[bytes]]\n _write: Callable[[bytes], Any]\n\n parser = MultipartDecoder(boundary, self.max_form_memory_size)\n\n fields = []\n files = []\n\n current_part: Union[Field, File]\n async for data in body:\n parser.receive_data(data)\n event = parser.next_event()\n while not isinstance(event, (Epilogue, NeedData)):\n if isinstance(event, Field):\n current_part = event\n container = []\n _write = container.append\n elif isinstance(event, File):\n current_part = event\n container = self.start_file_streaming(event, content_length)\n _write = container.write\n elif isinstance(event, Data):\n _write(event.data)\n if not event.more_data:\n if isinstance(current_part, Field):\n value = b\"\".join(container).decode(self.get_part_charset(current_part.headers), self.errors)\n fields.append((current_part.name, value))\n else:\n container = cast(IO[bytes], container)\n container.seek(0)\n files.append(\n (\n current_part.name,\n self.file_storage_cls(\n container,\n current_part.filename,\n current_part.name,\n headers=current_part.headers,\n ),\n )\n )\n\n event = parser.next_event()\n\n return self.cls(fields), self.cls(files)\n","repo_name":"hifthot/skidcity","sub_path":"wock/web/quart/formparser.py","file_name":"formparser.py","file_ext":"py","file_size_in_byte":6943,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"74785709603","text":"#!/bin/env python\n\n# BOILER PLATE ------------------------------------------------------------------------------------\n\nper_id_matrix = open(\"pim.txt\")\n\n# FUNCTIONS ---------------------------------------------------------------------------------------\n\n\n\n# MAIN FUNCTION -----------------------------------------------------------------------------------\n\nlines = per_id_matrix.readlines()\ncount = int(lines[0].strip()) # because first line does not count, actual matrix starts on line 1, therefore, use 1-based indexing for rows.\nmatches = list(range(1,count+1))\n\ni = 1\nwhile i < count: # not equal to because will never use last line of matrix\n\trow = lines[i].split()\n\te = i + 1 # only want top triangle of values.\n\tif i in matches:# if the read has not yet been found identical with another read\n\t\twhile e <= count: # we have a [count x count] matrix, and since 0 value is held by read name, matrix is 1-based indexing\n\t\t\tidentity = int(float(row[e])) # float must be used to remove most excessive 0 after decimal\n\t\t\tif identity == 100:\n\t\t\t\tmatches.remove(e)\n\t\t\te += 1\n\t\t\n\ti += 1\n\n\n#print(matches)\n\nunique_read_names = open(\"unaln_uniq.txt\",\"w\")\n\nfor p in matches: \n\tunique_read_names.write(lines[p].split(\" \")[0] + \"\\n\")\n\n\n\n# CLOSE -------------------------------------------------------------------------------------------\n\nper_id_matrix.close()\nunique_read_names.close()\n","repo_name":"cloeffler745/Merge_Databases","sub_path":"code/code_run_in_collected_reference_files/find_uniq_of_unaln.py","file_name":"find_uniq_of_unaln.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73019601445","text":"from distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Build import cythonize\n\n\nextensions = [\n Extension(\n \"random_genie\",\n [\"engine.pyx\"],\n extra_compile_args=[\"-std=c++14\"],\n language=\"c++\",\n ),\n]\n\nsetup(\n name=\"random_genie\",\n ext_modules=cythonize(extensions),\n)\n","repo_name":"BrokenShell/RandomGenie","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71728949926","text":"# Concept\n\n# define class\nclass Person:\n # class attribute\n address = \"RUTS Saiyai\" # public\n # object (instance) attributes\n def __init__(self):\n #assign value to attributes\n self.name = \"\"\n self.age = \"\"\n def introduce(self):\n print(f'Hello, my name is {self.name}')\n\n# create class instant (object)\n# p1 = Person(\"Puriwat\",35)\n# p2 = Person(\"Nattaporn\",22)\n# assing value to attribute\np1 = Person()\np2 = Person()\np1.name = 'Puriwat'\np2.name = 'Nattaporn'\nprint(p1.address)\nprint(p2.address)\nprint(p1.name)\nprint(p2.name)\n\n# calling method in class\np1.introduce()\np2.introduce()\n\nmylist = [p1,p2]\nprint(mylist)\nprint(mylist[1].name)\n\n\n\n","repo_name":"plertkrai/OOP_MIT231_2_2564","sub_path":"Lab6/ex_oop.py","file_name":"ex_oop.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5731508879","text":"#!/usr/bin/python -u\n\n# dependencies:\n# requests\n# m3u8\n\ntarget_server = 'kiev4-cdn.lanet.tv'\n\nimport logging\nimport logging.config\nimport os\nlogging.config.fileConfig(os.path.join(os.path.dirname(__file__), 'logging.conf'))\n\n\nfrom m3u8_streamer import M3u8Streamer\nfrom urlparse import urljoin\nimport sys\nimport re\nfrom cStringIO import StringIO\nfrom time import time\n\ndef main():\n logger = logging.getLogger('main')\n logger.info('starting')\n # get url\n line = sys.stdin.readline().strip()\n logger.info('read {}'.format(line))\n path = re.match('GET (/.*) HTTP/\\d\\.\\d', line).group(1).replace('.ts', '.m3u8')\n\n # skip rest of http header\n while sys.stdin.readline().strip():\n pass\n\n sys.stdout.write(\n 'HTTP/1.0 200 OK\\n'\n 'Content-type: video/MP2T\\n'\n 'Connection: keep-alive\\n'\n '\\n\\n')\n streamer = M3u8Streamer(urljoin(\n 'http://' + target_server, \n path))\n\n last_stat_flush = time()\n size = duration = 0\n for data in streamer.iter_content():\n if not data:\n logger.error('Streamer has failed to return data')\n break\n ts_start = time()\n try:\n sys.stdout.write(data)\n except:\n logger.exception('While sending response. Stopping server')\n break\n duration += time() - ts_start\n size += len(data) / 1e6\n if time() - last_stat_flush > 1:\n logger.info('Sent ({} Mb in {} seconds @ {} Mb/s)'.format(size, duration, size / duration))\n size = duration = 0\n last_stat_flush = time()\n streamer.stop()\n\n\nif __name__ == '__main__':\n try:\n sys.stderr.close()\n sys.stderr = StringIO()\n main()\n except:\n logging.getLogger('main').exception('Unexpected exception')\n data = sys.stderr.getvalue()\n if data:\n logging.getLogger('main').error(data)\n","repo_name":"rain87/hls-glue","sub_path":"code/hls_glue.py","file_name":"hls_glue.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17646791252","text":"#coding=utf-8\nclass ConfigInit:\n url = 'xxxx'\n login_url = 'xxxx'\n sendaddr_name = 'xxxx'\n sendaddr_pswd = 'xxxx'\n data_filename = 'data.xls'\n mongo_ip_port = 'ip'\n mongo_user = 'root'\n mongo_pw = \"pw\"\n #测试测试\n","repo_name":"huangbin32/testapi","sub_path":"config/basic_config.py","file_name":"basic_config.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73102747364","text":"import tensorflow as tf\nfrom src.image_loader import ImageLoader\nfrom src.rays import GetRays\n\nfrom pathlib import Path\nfrom src.utils import read_json\n\nclass Dataset:\n def __init__(self, data_dir: Path | str, near: int, far: int, n_coarse_samples: int):\n self.data_dir = Path(data_dir)\n self.transforms_path = self.data_dir / \"transforms.json\"\n \n json_data = read_json(self.transforms_path)\n \n self.full_img_paths = [str(self.data_dir / Path(f[\"file_path\"])) for f in json_data[\"frames\"]]\n self.full_c2ws = [f[\"transform_matrix\"] for f in json_data[\"frames\"]]\n \n self.img_width = json_data[\"w\"]\n self.img_height = json_data[\"h\"]\n focal_len = json_data[\"fl_x\"]\n\n self.get_rays = GetRays(focal_len, self.img_width, self.img_height, near, far, n_coarse_samples)\n self.load_img = ImageLoader(self.img_width, self.img_height)\n \n # split dataset into test, train, and validation\n # 10/10/80 split\n self.test = self.make_split(lambda i: i % 10 == 0)\n self.val = self.make_split(lambda i: i % 10 == 1)\n self.train = self.make_split(lambda i: i % 10 >= 2)\n\n def make_split(self, predicate):\n\n c2ws = [self.full_c2ws[i] for i in range(len(self.full_c2ws)) if predicate(i)]\n img_paths = [self.full_img_paths[i] for i in range(len(self.full_img_paths)) if predicate(i)]\n \n rays = (\n tf.data.Dataset\n .from_tensor_slices(c2ws)\n .map(\n self.get_rays,\n num_parallel_calls=tf.data.AUTOTUNE,\n )\n )\n\n imgs = (\n tf.data.Dataset\n .from_tensor_slices(img_paths)\n .map(\n self.load_img,\n num_parallel_calls=tf.data.AUTOTUNE,\n )\n )\n\n return tf.data.Dataset.zip((rays, imgs))\n","repo_name":"JamesPerlman/pis-nerf-tut","sub_path":"src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9438269793","text":"#!/usr/bin/env python\n\n\"\"\"\n@package mi.idk.test.test_result_set\n@file mi.idk/test/test_result_set.py\n@author Bill French\n@brief Read a result set file and test the verification methods\n\"\"\"\n\n__author__ = 'Bill French'\n\n\nimport os\nimport re\nimport numpy as np\nimport uuid\n\nfrom pyon.public import log\nfrom nose.plugins.attrib import attr\nfrom mock import Mock\nfrom ion.agents.data.result_set import ResultSet\nfrom pyon.util.int_test import IonIntegrationTestCase\nfrom ion.services.dm.utility.granule_utils import RecordDictionaryTool\nfrom coverage_model.parameter import ParameterContext, ParameterDictionary\nfrom coverage_model.parameter_types import QuantityType, ArrayType, RecordType\nfrom ion.agents.populate_rdt import populate_rdt\n\n@attr('UNIT', group='mi')\nclass TestResultSet(IonIntegrationTestCase):\n \"\"\"\n Test the metadata object\n \"\"\"\n def _get_result_set_file(self, filename):\n \"\"\"\n return the full path to the result_set_file in\n the same directory as the test file.\n \"\"\"\n test_dir = os.path.dirname(__file__)\n return os.path.join(test_dir, filename)\n\n def setUp(self):\n \"\"\"\n Setup the test case\n \"\"\"\n\n def test_ntp_conversion(self):\n rs = ResultSet(self._get_result_set_file(\"result_set_file.yml\"))\n ts = rs._string_to_ntp_date_time(\"1970-01-01T00:00:00.00Z\")\n self.assertEqual(ts, 2208988800.0)\n\n ts = rs._string_to_ntp_date_time(\"1970-01-01T00:00:00.00\")\n self.assertEqual(ts, 2208988800.0)\n\n ts = rs._string_to_ntp_date_time(\"1970-01-01T00:00:00\")\n self.assertEqual(ts, 2208988800.0)\n\n ts = rs._string_to_ntp_date_time(\"1970-01-01T00:00:00Z\")\n self.assertEqual(ts, 2208988800.0)\n\n ts = rs._string_to_ntp_date_time(\"1970-01-01T00:01:00.101Z\")\n self.assertEqual(ts, 2208988860.101)\n\n self.assertRaises(ValueError, rs._string_to_ntp_date_time, \"09/05/2013 02:47:21.000\")\n\n def get_param_dict(self):\n pdict = ParameterDictionary()\n\n cond_ctxt = ParameterContext('conductivity', param_type=QuantityType(value_encoding=np.float64))\n cond_ctxt.uom = 'unknown'\n cond_ctxt.fill_value = 0e0\n pdict.add_context(cond_ctxt)\n\n pres_ctxt = ParameterContext('pressure', param_type=QuantityType(value_encoding=np.float64))\n pres_ctxt.uom = 'unknown'\n pres_ctxt.fill_value = 0x0\n pdict.add_context(pres_ctxt)\n\n temp_ctxt = ParameterContext('temperature', param_type=QuantityType(value_encoding=np.float64))\n temp_ctxt.uom = 'unknown'\n temp_ctxt.fill_value = 0x0\n pdict.add_context(temp_ctxt)\n\n oxy_ctxt = ParameterContext('oxygen', param_type=QuantityType(value_encoding=np.float64))\n oxy_ctxt.uom = 'unknown'\n oxy_ctxt.fill_value = 0x0\n pdict.add_context(oxy_ctxt)\n\n internal_ts_ctxt = ParameterContext(name='internal_timestamp', param_type=QuantityType(value_encoding=np.float64))\n internal_ts_ctxt._derived_from_name = 'time'\n internal_ts_ctxt.uom = 'seconds'\n internal_ts_ctxt.fill_value = -1\n pdict.add_context(internal_ts_ctxt, is_temporal=True)\n\n driver_ts_ctxt = ParameterContext(name='driver_timestamp', param_type=QuantityType(value_encoding=np.float64))\n driver_ts_ctxt._derived_from_name = 'time'\n driver_ts_ctxt.uom = 'seconds'\n driver_ts_ctxt.fill_value = -1\n pdict.add_context(driver_ts_ctxt)\n\n return pdict\n\n def get_particle(self, timestamp, cond, pres, temp, oxygen, new_sequence = False):\n return {\n 'quality_flag': 'ok',\n 'preferred_timestamp': 'internal_timestamp',\n 'stream_name': 'ctdpf_parsed',\n 'pkt_format_id': 'JSON_Data',\n 'pkt_version': 1,\n 'internal_timestamp': timestamp,\n 'values':\n [\n {'value_id': 'temperature', 'value': temp},\n {'value_id': 'conductivity', 'value': cond},\n {'value_id': 'pressure', 'value': pres},\n {'value_id': 'oxygen', 'value': oxygen}\n ],\n 'driver_timestamp': timestamp+1,\n 'new_sequence': new_sequence\n }\n\n def create_test_granules(self, buffer_data=False):\n \"\"\"\n Generate test granules from particles. If buffer data is set to true then\n try to buffer data into a granule. If the particle has the new sequence\n flag set then a new granule will be generated. This method emulates the\n agent_stream_publisher module.\n :return: list of granules generated.\n \"\"\"\n base_timestamp = 3583861263.0\n connection_index = 0\n\n particles = []\n particles.append(self.get_particle(base_timestamp, 10.5914, 161.06, 4.1870, 2693.0))\n particles.append(self.get_particle(base_timestamp+1, 10.5915, 161.07, 4.1871, 2693.1))\n particles.append(self.get_particle(base_timestamp+2, 10.5916, 161.08, 4.1872, 2693.2))\n particles.append(self.get_particle(base_timestamp+3, 10.5917, 161.09, 4.1873, 2693.3, True))\n particles.append(self.get_particle(base_timestamp+4, 10.5918, 161.10, 4.1874, 2693.4))\n\n data_groups = []\n result_granules = []\n data_groups_index = 0\n\n for particle in particles:\n # If we need a new connection then start a new group, but only if we have found\n # something in the current group\n if (particle.get('new_sequence', False) or buffer_data == False) and \\\n (len(data_groups) > 0 and len(data_groups[data_groups_index]) > 0):\n data_groups_index += 1\n\n if len(data_groups) <= data_groups_index:\n data_groups.append([])\n\n data_groups[data_groups_index].append(particle)\n\n log.debug(\"Granules to create: %s\", len(data_groups))\n\n for data in data_groups:\n connection_id = uuid.uuid4()\n connection_index += 1\n rdt = RecordDictionaryTool(param_dictionary=self.get_param_dict())\n\n rdt = populate_rdt(rdt, data)\n\n g = rdt.to_granule(data_producer_id='agent_res_id', connection_id=connection_id.hex,\n connection_index=str(connection_index))\n\n result_granules.append(g)\n\n return result_granules\n\n def test_extract_data(self):\n rs = ResultSet(self._get_result_set_file(\"result_set_file.yml\"))\n\n granules = self.create_test_granules()\n self.assertEqual(len(granules), 5)\n\n result = rs._extract_granule_data(granules)\n self.assertEqual(len(result), 5)\n\n granules = self.create_test_granules(True)\n self.assertEqual(len(granules), 2)\n result = rs._extract_granule_data(granules)\n self.assertEqual(len(result), 5)\n\n def test_simple_set(self):\n rs = ResultSet(self._get_result_set_file(\"result_set_file.yml\"))\n\n granules = self.create_test_granules(True)\n self.assertEqual(len(granules), 2)\n self.assertTrue(rs.verify(granules))\n\n","repo_name":"ooici/coi-services","sub_path":"ion/agents/data/test/test_result_set.py","file_name":"test_result_set.py","file_ext":"py","file_size_in_byte":7101,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"52"} +{"seq_id":"43234646908","text":"'convert from CSV to txt format'\n\nimport sys, csv, re\nimport datetime,time\nimport nltk\nimport string\nfrom collections import Counter\nfrom stop_words import get_stop_words\nfrom nltk.stem.porter import *\n\n\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\n\n\ndef diffdate(postdate):\n\tx=postdate[0:2]+postdate[3:5]+postdate[6:10]+postdate[11:13]+postdate[14:16]+postdate[17:19]\n\ttry:\n\t\td=datetime.datetime.strptime(x,\"%m%d%Y%H%M%S\").date()\n\texcept ValueError:\n\t\td=datetime.datetime.now().date()\n\tcd=datetime.datetime.now().date()\n\tdelta=cd-d\n\treturn delta.days\n\nreader = csv.reader( open( input_file ))\no = open( output_file, 'wb' )\nen_stop = get_stop_words('en')\n\ncounter = 0\t\nfor line in reader:\n\n\tif counter == 0:\n\t\toutput_line=\"Status,Post_Id,TitleLength,BodyLength,ReputationAtPostCreation,DateDifferenceQues,TagsNo,UserAge,OwnerUndeletedAnswerCountAtPostTime,LinksCount\\n\"\n\t\to.write(output_line)\n\telse:\n\t\tdayDiffQues=diffdate(line[1])-(3*365)\n\t\tuserAge=diffdate(line[3])-(3*365)\n\t\tOwnerUndelAnsCountAtPostTime=line[5]\n\t\tb_lower=line[7].strip().lower()\n\t\tt_lower=line[6].strip().lower()\n\t\tb_no_punctuation = b_lower.translate(None, string.punctuation)\n\t\tt_no_punctuation = t_lower.translate(None, string.punctuation)\n\t\tb_tokens = nltk.word_tokenize(b_no_punctuation)\n\t\tt_tokens = nltk.word_tokenize(t_no_punctuation)\n\t\tb_filtered = [w for w in b_tokens if not w in en_stop]\n\t\tt_filtered = [w for w in t_tokens if not w in en_stop]\n\t\tbodylength=len(b_filtered)\n\t\ttitlelength=len(t_filtered)\n\t\treputationAtPostCreation=line[4]\n\t\ttags=line[8:13]\n\t\tstatus=line[14]\n\t\tTagsNo=5\n\t\tfor t in tags:\n\t\t\tif t == \"\": \n\t\t\t\tTagsNo-=1\n\t\tlinksCount = len(re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line[7]))\n\t\tif status == 'open':\n\t\t\tlabel = 0\t\n\t\telse:\n\t\t\tlabel = 1\t\t# test set\n\t\t\n\t\toutput_line = \"%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\\n\" % (label,str(counter),titlelength,bodylength,reputationAtPostCreation,dayDiffQues,TagsNo,userAge,OwnerUndelAnsCountAtPostTime,linksCount) \t\n\n\t\to.write( output_line )\n\tcounter+=1\n","repo_name":"rounak123/Predict-Closed-Questions-On-StackOverflow","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11314469383","text":"import xarray as xr\nimport numpy\nimport os\n\nfrom collections import OrderedDict\n\nfrom mpas_analysis.shared import AnalysisTask\nfrom mpas_analysis.ocean.compute_transects_subtask import \\\n TransectsObservations\n\nfrom mpas_analysis.ocean.compute_transects_with_vel_mag import \\\n ComputeTransectsWithVelMag\n\nfrom mpas_analysis.ocean.plot_transect_subtask import PlotTransectSubtask\n\nfrom mpas_analysis.shared.io.utility import build_config_full_path, \\\n make_directories, build_obs_path\nfrom mpas_analysis.shared.io import write_netcdf_with_fill\n\n\nclass SoseTransects(AnalysisTask):\n \"\"\"\n Plot model output at WOCE transects and compare it against WOCE\n observations\n \"\"\"\n\n # Authors\n # -------\n # Xylar Asay-Davis\n\n def __init__(self, config, mpasClimatologyTask, controlConfig=None):\n \"\"\"\n Construct the analysis task and adds it as a subtask of the\n ``parentTask``.\n\n Parameters\n ----------\n config : mpas_tools.config.MpasConfigParser\n Configuration options\n\n mpasClimatologyTask : ``MpasClimatologyTask``\n The task that produced the climatology to be remapped and plotted\n as a transect\n\n controlconfig : mpas_tools.config.MpasConfigParser, optional\n Configuration options for a control run (if any)\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n tags = ['climatology', 'transect', 'sose', 'publicObs', 'antarctic']\n\n # call the constructor from the base class (AnalysisTask)\n super(SoseTransects, self).__init__(\n config=config, taskName='soseTransects',\n componentName='ocean',\n tags=tags)\n\n sectionName = self.taskName\n\n seasons = config.getexpression(sectionName, 'seasons')\n\n horizontalResolution = config.get(sectionName, 'horizontalResolution')\n\n verticalComparisonGridName = config.get(sectionName,\n 'verticalComparisonGridName')\n\n if verticalComparisonGridName in ['mpas', 'obs']:\n verticalComparisonGrid = None\n else:\n verticalComparisonGrid = config.getexpression(\n sectionName, 'verticalComparisonGrid', use_numpyfunc=True)\n\n verticalBounds = config.getexpression(sectionName, 'verticalBounds')\n\n longitudes = sorted(config.getexpression(sectionName, 'longitudes',\n use_numpyfunc=True))\n\n fields = \\\n [{'prefix': 'temperature',\n 'mpas': 'timeMonthly_avg_activeTracers_temperature',\n 'units': r'$\\degree$C',\n 'titleName': 'Potential Temperature',\n 'obsFilePrefix': 'pot_temp',\n 'obsFieldName': 'theta'},\n {'prefix': 'salinity',\n 'mpas': 'timeMonthly_avg_activeTracers_salinity',\n 'units': r'PSU',\n 'titleName': 'Salinity',\n 'obsFilePrefix': 'salinity',\n 'obsFieldName': 'salinity'},\n {'prefix': 'potentialDensity',\n 'mpas': 'timeMonthly_avg_potentialDensity',\n 'units': r'kg m$^{-3}$',\n 'titleName': 'Potential Density',\n 'obsFilePrefix': 'pot_den',\n 'obsFieldName': 'potentialDensity'},\n {'prefix': 'zonalVelocity',\n 'mpas': 'timeMonthly_avg_velocityZonal',\n 'units': r'm s$^{-1}$',\n 'titleName': 'Zonal Velocity',\n 'obsFilePrefix': 'zonal_vel',\n 'obsFieldName': 'zonalVel'},\n {'prefix': 'meridionalVelocity',\n 'mpas': 'timeMonthly_avg_velocityMeridional',\n 'units': r'm s$^{-1}$',\n 'titleName': 'Meridional Velocity',\n 'obsFilePrefix': 'merid_vel',\n 'obsFieldName': 'meridVel'},\n {'prefix': 'velocityMagnitude',\n 'mpas': 'velMag',\n 'units': r'm s$^{-1}$',\n 'titleName': 'Velocity Magnitude',\n 'obsFilePrefix': None,\n 'obsFieldName': 'velMag'},\n {'prefix': 'potentialDensityContour',\n 'mpas': 'timeMonthly_avg_potentialDensity',\n 'units': r'kg m$^{-3}$',\n 'titleName': 'Potential Density Contours',\n 'obsFilePrefix': 'pot_den',\n 'obsFieldName': 'potentialDensity'}]\n\n fieldList = config.getexpression(sectionName, 'fieldList')\n fields = [field for field in fields if field['prefix'] in fieldList]\n\n variableList = [field['mpas'] for field in fields\n if field['mpas'] != 'velMag']\n\n transectCollectionName = 'SOSE_transects'\n if horizontalResolution not in ['obs', 'mpas']:\n transectCollectionName = '{}_{}km'.format(transectCollectionName,\n horizontalResolution)\n\n transectsObservations = SoseTransectsObservations(\n config, horizontalResolution,\n transectCollectionName, fields)\n\n computeTransectsSubtask = ComputeTransectsWithVelMag(\n mpasClimatologyTask=mpasClimatologyTask,\n parentTask=self,\n climatologyName='SOSE_transects',\n transectCollectionName=transectCollectionName,\n variableList=variableList,\n seasons=seasons,\n obsDatasets=transectsObservations,\n verticalComparisonGridName=verticalComparisonGridName,\n verticalComparisonGrid=verticalComparisonGrid)\n\n plotObs = controlConfig is None\n if plotObs:\n\n refTitleLabel = 'State Estimate (SOSE)'\n\n diffTitleLabel = 'Model - State Estimate'\n\n else:\n controlRunName = controlConfig.get('runs', 'mainRunName')\n refTitleLabel = 'Control: {}'.format(controlRunName)\n\n diffTitleLabel = 'Main - Control'\n\n for field in fields:\n fieldPrefix = field['prefix']\n fieldPrefixUpper = fieldPrefix[0].upper() + fieldPrefix[1:]\n for lon in longitudes:\n transectName = 'lon_{}'.format(lon)\n\n for season in seasons:\n outFileLabel = 'SOSE_{}_'.format(fieldPrefix)\n if plotObs:\n refFieldName = field['obsFieldName']\n else:\n refFieldName = field['mpas']\n\n fieldNameInTytle = r'{} at {}$\\degree$ Lon.'.format(\n field['titleName'], lon)\n\n # make a new subtask for this season and comparison grid\n subtask = PlotTransectSubtask(self, season, transectName,\n fieldPrefix,\n computeTransectsSubtask,\n plotObs, controlConfig)\n\n subtask.set_plot_info(\n outFileLabel=outFileLabel,\n fieldNameInTitle=fieldNameInTytle,\n mpasFieldName=field['mpas'],\n refFieldName=refFieldName,\n refTitleLabel=refTitleLabel,\n diffTitleLabel=diffTitleLabel,\n unitsLabel=field['units'],\n imageCaption='{} {}'.format(fieldNameInTytle,\n season),\n galleryGroup='SOSE Transects',\n groupSubtitle=None,\n groupLink='sose_transects',\n galleryName=field['titleName'],\n configSectionName='sose{}Transects'.format(\n fieldPrefixUpper),\n verticalBounds=verticalBounds)\n\n self.add_subtask(subtask)\n\n\nclass SoseTransectsObservations(TransectsObservations):\n \"\"\"\n A class for loading and manipulating SOSE transect data\n\n Attributes\n ----------\n\n fields : list of dict\n dictionaries defining the fields with associated SOSE data\n \"\"\"\n\n # Authors\n # -------\n # Xylar Asay-Davis\n\n def __init__(self, config, horizontalResolution,\n transectCollectionName, fields):\n\n \"\"\"\n Construct the object, setting the observations dictionary to None.\n\n Parameters\n ----------\n config : mpas_tools.config.MpasConfigParser\n Configuration options\n\n horizontalResolution : str\n 'obs' for the obs as they are or a size in km if subdivision is\n desired.\n\n transectCollectionName : str\n A name that describes the collection of transects (e.g. the name\n of the collection of observations) used to name the\n destination \"mesh\" for regridding\n\n fields : list of dict\n dictionaries defining the fields with associated SOSE data\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n # this will be constructed later\n obsFileNames = None\n\n # call the constructor from the base class (TransectsObservations)\n super(SoseTransectsObservations, self).__init__(\n config, obsFileNames, horizontalResolution,\n transectCollectionName)\n\n self.fields = fields\n\n def get_observations(self):\n \"\"\"\n Read in and set up the observations.\n\n Returns\n -------\n obsDatasets : OrderedDict\n The observational dataset\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n # first, combine the SOSE observations into a single data set\n if self.obsFileNames is None:\n self.combine_observations()\n\n # then, call the method from the parent class\n return super(SoseTransectsObservations, self).get_observations()\n\n def combine_observations(self):\n \"\"\"\n Combine SOSE oservations into a single file\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n config = self.config\n\n longitudes = sorted(config.getexpression('soseTransects', 'longitudes',\n use_numpyfunc=True))\n\n observationsDirectory = build_obs_path(\n config, 'ocean', 'soseSubdirectory')\n\n outObsDirectory = build_config_full_path(\n config=config, section='output',\n relativePathOption='climatologySubdirectory',\n relativePathSection='oceanObservations')\n\n make_directories(outObsDirectory)\n\n combinedFileName = '{}/{}.nc'.format(outObsDirectory,\n self.transectCollectionName)\n obsFileNames = OrderedDict()\n for lon in longitudes:\n transectName = 'lon_{}'.format(lon)\n obsFileNames[transectName] = combinedFileName\n\n self.obsFileNames = obsFileNames\n\n if os.path.exists(combinedFileName):\n return\n\n print('Preprocessing SOSE transect data...')\n\n minLat = config.getfloat('soseTransects', 'minLat')\n maxLat = config.getfloat('soseTransects', 'maxLat')\n\n dsObs = None\n for field in self.fields:\n prefix = field['obsFilePrefix']\n fieldName = field['obsFieldName']\n if prefix is None or (dsObs is not None and fieldName in dsObs):\n continue\n print(' {}'.format(field['prefix']))\n\n fileName = f'{observationsDirectory}/SOSE_2005-2010_monthly_' \\\n f'{prefix}_SouthernOcean_0.167x0.167degree_20180710.nc'\n\n dsLocal = xr.open_dataset(fileName)\n\n lat = dsLocal.lat.values\n mask = numpy.logical_and(lat >= minLat, lat <= maxLat)\n indices = numpy.argwhere(mask)\n dsLocal = dsLocal.isel(lat=slice(indices[0][0],\n indices[-1][0]))\n dsLocal.load()\n\n if fieldName == 'zonalVel':\n # need to average in longitude\n nLon = dsLocal.sizes['lon']\n lonIndicesP1 = numpy.mod(numpy.arange(nLon) + 1, nLon)\n dsLocal = 0.5 * (dsLocal + dsLocal.isel(lon=lonIndicesP1))\n\n if fieldName == 'meridVel':\n # need to average in latitude\n nLat = dsLocal.sizes['lat']\n latIndicesP1 = numpy.mod(numpy.arange(nLat) + 1, nLat)\n dsLocal = 0.5 * (dsLocal + dsLocal.isel(lat=latIndicesP1))\n\n dsLocal = dsLocal.sel(lon=longitudes, method=str('nearest'))\n\n if dsObs is None:\n dsObs = dsLocal\n else:\n dsLocal['lon'] = dsObs.lon\n dsLocal['lat'] = dsObs.lat\n dsObs[fieldName] = dsLocal[fieldName]\n dsLocal.close()\n\n if 'zonalVel' in dsObs and 'meridVel' in dsObs:\n # compute the velocity magnitude\n print(' velMag')\n description = 'Monthly velocity magnitude climatologies ' \\\n 'from 2005-2010 average of the Southern Ocean ' \\\n 'State Estimate (SOSE)'\n dsObs['velMag'] = numpy.sqrt(\n dsObs.zonalVel ** 2 + dsObs.meridVel ** 2)\n dsObs.velMag.attrs['units'] = 'm s$^{-1}$'\n dsObs.velMag.attrs['description'] = description\n\n # make a copy of the top set of data at z=0\n dsObs = xr.concat((dsObs.isel(z=0), dsObs), dim='z')\n z = dsObs.z.values\n z[0] = 0.\n dsObs['z'] = ('z', z)\n write_netcdf_with_fill(dsObs, combinedFileName)\n\n print(' Done.')\n\n def build_observational_dataset(self, fileName, transectName):\n \"\"\"\n read in the data sets for observations, and possibly rename some\n variables and dimensions\n\n Parameters\n ----------\n fileName : str\n observation file name\n\n transectName : str\n transect name\n\n Returns\n -------\n dsObs : ``xarray.Dataset``\n The observational dataset\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n dsObs = xr.open_dataset(fileName)\n\n lon = float(transectName.rsplit('_', 1)[-1])\n\n dsObs = dsObs.sel(method=str('nearest'), lon=lon)\n lon = dsObs.lon.values\n\n # do some dropping and renaming so we end up with the right coordinates\n # and dimensions\n dsObs = dsObs.rename({'lat': 'nPoints', 'z': 'nz'})\n dsObs['lat'] = dsObs.nPoints\n dsObs['z'] = dsObs.nz\n dsObs['lon'] = ('nPoints', lon * numpy.ones(dsObs.sizes['nPoints']))\n dsObs = dsObs.drop_vars(['nPoints', 'nz'])\n\n return dsObs\n","repo_name":"MPAS-Dev/MPAS-Analysis","sub_path":"mpas_analysis/ocean/sose_transects.py","file_name":"sose_transects.py","file_ext":"py","file_size_in_byte":14843,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"52"} +{"seq_id":"8648391547","text":"import threading, time\n\n\ndef worker(num_thread):\n print(f'Старт потока №{num_thread}')\n time.sleep(1)\n print(f'Завершение работы потока №{num_thread}')\n\n\nfor i in range(2):\n # создаем экземпляры 'Thread' с функцией\n # 'worker()', которая запустится в отдельных\n # трех потоках. Позиционные аргументы для\n # функции 'worker()' передаются в кортеже `args`\n thread = threading.Thread(target=worker, args=(i,))\n # запускаем экземпляр `thread`\n thread.start()\n\n# Старт потока №0\n# Старт потока №1\n# Завершение работы потока №0\n# Завершение работы потока №1","repo_name":"syurskyi/Python_Topics","sub_path":"110_concurrency_parallelism/002_threads/_exercises/exercises/Module Threading overview/010 - Thread.start.py","file_name":"010 - Thread.start.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"24648425469","text":"\ndef countriesCount(data):\n countForIndia = 0\n countForPakistan = 0\n for i in data:\n countForIndia += i.count(\"India\")\n countForPakistan += i.count(\"Pakistan\")\n return \"Count of India : \" + str(countForIndia) + \", Count for Pakistan : \" + str(countForPakistan)\n\ndef studentsBelowFifty(data):\n count = 0\n for i in data:\n d = i.split()\n if int(d[0]) < 50:\n count += 1\n return \"count of students below fifty is : \" + str(count)\n\ndef studentsAboveFifty(data):\n count = 0\n for i in data:\n d = i.split()\n if int(d[0]) > 50:\n count += 1\n return \"count of students above fifty is \" + str(count)\n\ndef exactlyFifty(data):\n countForIndia = 0\n countForPakistan = 0\n for i in data:\n d = i.split()\n if int(d[0]) == 50 and d[1] == \"India\":\n countForIndia += 1\n elif int(d[0]) == 50 and d[1] == \"Pakistan\":\n countForPakistan += 1\n return \"Count of students from India who scored exactly 50 is \" + str(countForIndia) + \", Count of students from Pakistan who scored exactly 50 is \" + str(countForPakistan)\n\n# opening files\nrawData = open(\"marks_rand_2000.csv\")\nrawData2 = open(\"marksIndia.txt\", \"w\")\nrawData3 = open(\"marksPakistan.txt\", \"w\")\nrawData4 = open(\"marks100.txt\", \"w\")\n\nfor i in rawData:\n line = i.split()\n if int(line[0]) == 100:\n rawData4.write(line[2] + \"\\n\")\n elif line[1] == \"India\":\n rawData2.write(line[0] + \" \" + line[2] + \"\\n\" )\n elif line[1] == \"Pakistan\":\n rawData3.write(line[0] + \" \" + line[2] + \"\\n\") \n\n# closing files\nrawData2.close()\nrawData3.close()\nrawData4.close()\nrawData.close()\n\nrawData = open(\"marks_rand_2000.csv\")\nprint(countriesCount(rawData))\nrawData.close()\n\nrawData = open(\"marks_rand_2000.csv\")\nprint(studentsBelowFifty(rawData))\nrawData.close()\n\nrawData = open(\"marks_rand_2000.csv\")\nprint(studentsAboveFifty(rawData))\nrawData.close()\n\nrawData = open(\"marks_rand_2000.csv\")\nprint(exactlyFifty(rawData))\nrawData.close()\n","repo_name":"piush2611/Masai-Submissions","sub_path":"week_13/day_5/session_1/marksStats.py","file_name":"marksStats.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71995843686","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport socket\nimport subprocess\nimport sys\nimport time\nimport unittest\nfrom contextlib import contextmanager\nfrom tempfile import TemporaryDirectory\n\nimport httpretty\nimport mock\nimport pytest\nimport requests\nfrom bson import ObjectId\nfrom click.testing import CliRunner\nfrom mock import Mock\n\nimport mltk\nfrom mltk import ConfigValidationError, MLStorageClient, validate_config, ProgramOutputReceiver, config_params\nfrom mltk.mlrunner import (ProgramHost, MLRunnerConfig, SourceCopier,\n MLRunnerConfigLoader, TemporaryFileCleaner,\n JsonFileWatcher, MLRunner, mlrun, ControlServer)\nfrom mltk.utils import json_dumps, json_loads\nfrom tests.helpers import *\n\n\nclass MLRunnerConfigTestCase(unittest.TestCase):\n\n def test_validate(self):\n # test all empty\n config = MLRunnerConfig()\n config.source.includes = []\n config.source.excludes = []\n\n config.args = 'xyz'\n with pytest.raises(ConfigValidationError,\n match='\\'server\\' is required.'):\n _ = validate_config(config)\n\n del config.args\n config.server = 'http://127.0.0.1:8080'\n with pytest.raises(ConfigValidationError,\n match='\\'args\\' is required.'):\n _ = validate_config(config)\n\n config.args = ''\n with pytest.raises(ConfigValidationError,\n match='\\'args\\' must not be empty'):\n _ = validate_config(config)\n\n config.args = []\n with pytest.raises(ConfigValidationError,\n match='\\'args\\' must not be empty'):\n _ = validate_config(config)\n\n config.args = ['sh', '-c', 'echo hello']\n config = validate_config(config)\n for key in ('name', 'description', 'tags', 'env', 'gpu',\n 'work_dir', 'daemon'):\n self.assertIsNone(config[key])\n self.assertEqual(config.source.includes, [])\n self.assertEqual(config.source.excludes, [])\n\n # test .args\n config = MLRunnerConfig(args=['sh', 123],\n server='http://127.0.0.1:8080')\n self.assertEqual(validate_config(config).args, ['sh', '123'])\n config = MLRunnerConfig(args='exit 0',\n server='http://127.0.0.1:8080')\n self.assertEqual(validate_config(config).args, 'exit 0')\n\n # test .tags\n config.tags = ['hello', 123]\n self.assertListEqual(validate_config(config).tags, ['hello', '123'])\n\n # test .env\n config.env = {'value': 123}\n self.assertEqual(validate_config(config).env, {'value': '123'})\n\n # test .gpu\n config.gpu = [1, 2]\n self.assertListEqual(validate_config(config).gpu, [1, 2])\n\n # test .daemon\n config.daemon = 'exit 0'\n with pytest.raises(ConfigValidationError,\n match='at daemon: value is not a sequence'):\n _ = validate_config(config)\n\n config.daemon = ['exit 0', ['sh', '-c', 'exit 1']]\n self.assertListEqual(validate_config(config).daemon, [\n 'exit 0', ['sh', '-c', 'exit 1']\n ])\n\n # test .source.includes & .source.excludes using literals\n includes = r'.*\\.py$'\n excludes = re.compile(r'.*/\\.svn$')\n\n config.source.includes = includes\n config.source.excludes = excludes\n\n c = validate_config(config)\n self.assertIsInstance(c.source.includes, list)\n self.assertEqual(len(c.source.includes), 1)\n self.assertEqual(c.source.includes[0].pattern, includes)\n\n self.assertIsInstance(c.source.excludes, list)\n self.assertEqual(len(c.source.excludes), 1)\n self.assertIs(c.source.excludes[0], excludes)\n\n # test .source.includes & .source.excludes using lists\n includes = [r'.*\\.py$', re.compile(r'.*\\.exe$')]\n excludes = [r'.*/\\.git$', re.compile(r'.*/\\.svn$')]\n\n config.source.includes = includes\n config.source.excludes = excludes\n\n c = validate_config(config)\n self.assertIsInstance(c.source.includes, list)\n self.assertEqual(len(c.source.includes), 2)\n self.assertEqual(c.source.includes[0].pattern, includes[0])\n self.assertIs(c.source.includes[1], includes[1])\n\n self.assertIsInstance(c.source.excludes, list)\n self.assertEqual(len(c.source.excludes), 2)\n self.assertEqual(c.source.excludes[0].pattern, excludes[0])\n self.assertIs(c.source.excludes[1], excludes[1])\n\n\nclass MLRunnerConfigLoaderTestCase(unittest.TestCase):\n\n maxDiff = None\n\n def test_loader(self):\n with TemporaryDirectory() as temp_dir:\n # prepare for the test dir\n prepare_dir(temp_dir, {\n 'sys1': {\n '.mlrun.yaml': b'clone_from: sys1\\n'\n b'args: sys1/.mlrun.yaml args\\n'\n },\n 'sys2': {\n '.mlrun.yml': b'args: sys2/.mlrun.yml args\\n'\n b'name: sys2/.mlrun.yml',\n },\n 'work': {\n '.mlrun.yml': b'name: work/.mlrun.yml\\n'\n b'server: http://127.0.0.1:8080',\n '.mlrun.yaml': b'server: http://127.0.0.1:8081\\n'\n b'tags: [1, 2, 3]',\n '.mlrun.json': b'{\"tags\": [4, 5, 6],'\n b'\"description\": \"work/.mlrun.json\"}',\n 'nested': {\n '.mlrun.yml': b'description: work/nested/.mlrun.yml\\n'\n b'resume_from: xyz'\n }\n },\n 'config1.yml': b'resume_from: zyx\\n'\n b'source.src_dir: config1',\n 'config2.yml': b'source.src_dir: config2\\n'\n b'logging.log_file: config2.log',\n })\n\n # test loader\n config = MLRunnerConfig(env={'a': '1'}, clone_from='code')\n loader = MLRunnerConfigLoader(\n config=config,\n config_files=[\n os.path.join(temp_dir, 'config1.yml'),\n os.path.join(temp_dir, 'config2.yml')\n ],\n work_dir=os.path.join(temp_dir, 'work/nested'),\n system_paths=[\n os.path.join(temp_dir, 'sys1'),\n os.path.join(temp_dir, 'sys2')\n ],\n )\n expected_config_files = [\n os.path.join(temp_dir, 'sys1/.mlrun.yaml'),\n os.path.join(temp_dir, 'sys2/.mlrun.yml'),\n os.path.join(temp_dir, 'work/.mlrun.yml'),\n os.path.join(temp_dir, 'work/.mlrun.yaml'),\n os.path.join(temp_dir, 'work/.mlrun.json'),\n os.path.join(temp_dir, 'work/nested/.mlrun.yml'),\n os.path.join(temp_dir, 'config1.yml'),\n os.path.join(temp_dir, 'config2.yml'),\n ]\n self.assertListEqual(\n loader.list_config_files(), expected_config_files)\n load_order = []\n loader.load_config_files(on_load=load_order.append)\n self.assertListEqual(load_order, expected_config_files)\n\n config = loader.get()\n self.assertEqual(config.logging.log_file, 'config2.log')\n self.assertEqual(config.source.src_dir, 'config2')\n self.assertEqual(config.resume_from, 'zyx')\n self.assertEqual(config.description, 'work/nested/.mlrun.yml')\n self.assertListEqual(config.tags, ['4', '5', '6'])\n self.assertEqual(config.server, 'http://127.0.0.1:8081')\n self.assertEqual(config.name, 'work/.mlrun.yml')\n self.assertEqual(config.args, 'sys2/.mlrun.yml args')\n self.assertEqual(config.clone_from, 'sys1')\n self.assertEqual(config.env, {'a': '1'})\n\n # test bare loader\n loader = MLRunnerConfigLoader(system_paths=[])\n self.assertListEqual(loader.list_config_files(), [])\n loader.load_config_files()\n\n # test just one config file\n cfg_file = os.path.join(temp_dir, 'config.json')\n write_file_content(cfg_file, b'{\"args\": \"exit 0\",'\n b'\"server\":\"http://127.0.0.1:8080\"}')\n loader = MLRunnerConfigLoader(config_files=[cfg_file])\n loader.load_config_files()\n self.assertEqual(loader.get(), MLRunnerConfig(\n server='http://127.0.0.1:8080',\n args='exit 0'\n ))\n\n # test error on non-exist user specified config file\n loader = MLRunnerConfigLoader(\n config_files=[\n os.path.join(temp_dir, 'not-exist.yml')\n ]\n )\n with pytest.raises(IOError, match='User specified config file '\n '.* does not exist'):\n loader.load_config_files()\n\n\nclass MockMLServer(object):\n\n def __init__(self, root_dir, uri='http://127.0.0.1:8080'):\n self._root_dir = root_dir\n self._uri = uri\n self._db = {}\n\n @property\n def root_dir(self):\n return self._root_dir\n\n @property\n def uri(self):\n return self._uri\n\n @property\n def db(self):\n return self._db\n\n def register_uri(self):\n httpretty_register_uri(\n 'GET',\n re.compile(self.uri + '/v1/_get/([A-Za-z0-9]+)'),\n self.handle_get\n )\n httpretty_register_uri(\n 'POST',\n re.compile(self.uri + '/v1/_heartbeat/([A-Za-z0-9]+)'),\n self.handle_heartbeat\n )\n httpretty_register_uri(\n 'POST',\n re.compile(self.uri + '/v1/_create'),\n self.handle_create\n )\n httpretty_register_uri(\n 'POST',\n re.compile(self.uri + '/v1/_update/([A-Za-z0-9]+)'),\n self.handle_update\n )\n httpretty_register_uri(\n 'POST',\n re.compile(self.uri + '/v1/_set_finished/([A-Za-z0-9]+)'),\n self.handle_set_finished\n )\n\n def json_response(self, response_headers, cnt, status=200):\n if not isinstance(cnt, (str, bytes)):\n cnt = json_dumps(cnt)\n if not isinstance(cnt, bytes):\n cnt = cnt.encode('utf-8')\n response_headers['content-type'] = 'application/json; charset=utf-8'\n return [status, response_headers, cnt]\n\n def handle_heartbeat(self, request, uri, response_headers):\n id = re.search(r'/v1/_heartbeat/([A-Za-z0-9]+)$', uri).group(1)\n assert(id in self.db)\n return self.json_response(response_headers, {})\n\n def handle_get(self, request, uri, response_headers):\n id = re.search(r'/v1/_get/([A-Za-z0-9]+)$', uri).group(1)\n assert(id in self.db)\n return self.json_response(response_headers, self.db[id])\n\n def handle_create(self, request, uri, response_headers):\n assert(request.headers.get('Content-Type', '').split(';', 1)[0] ==\n 'application/json')\n body = json_loads(request.body.decode('utf-8'))\n body['_id'] = str(ObjectId())\n body['storage_dir'] = os.path.join(self.root_dir, body['_id'])\n self.db[body['_id']] = body\n return self.json_response(response_headers, self.db[body['_id']])\n\n def handle_update(self, request, uri, response_headers):\n id = re.search(r'/v1/_update/([A-Za-z0-9]+)$', uri).group(1)\n assert(id in self.db)\n assert (request.headers.get('Content-Type', '').split(';', 1)[0] ==\n 'application/json')\n body = json_loads(request.body.decode('utf-8'))\n if body:\n for key, val in body.items():\n parts = key.split('.', 1)\n if len(parts) == 2:\n self.db[id].setdefault(parts[0], {})\n self.db[id][parts[0]][parts[1]] = val\n else:\n self.db[id][key] = val\n return self.json_response(response_headers, self.db[id])\n\n def handle_set_finished(self, request, uri, response_headers):\n id = re.search(r'/v1/_set_finished/([A-Za-z0-9]+)$', uri).group(1)\n assert (id in self.db)\n assert (request.headers.get('Content-Type', '').split(';', 1)[0] ==\n 'application/json')\n body = json_loads(request.body.decode('utf-8'))\n if body:\n for key, val in body.items():\n parts = key.split('.', 1)\n if len(parts) == 2:\n self.db[id].setdefault(parts[0], {})\n self.db[id][parts[0]][parts[1]] = val\n else:\n self.db[id][key] = val\n return self.json_response(response_headers, self.db[id])\n\n def __enter__(self):\n self.register_uri()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n\nclass MLRunnerTestCase(unittest.TestCase):\n\n maxDiff = None\n\n @slow_test\n @httpretty.activate\n def test_run(self):\n with TemporaryDirectory() as temp_dir:\n # prepare for the source dir\n source_root = os.path.join(temp_dir, 'source')\n source_fiels = {\n 'a.py': b'print(\"a.py\")\\n',\n 'a.txt': b'a.txt content\\n',\n 'nested': {\n 'b.sh': b'echo \"b.sh\"\\n'\n }\n }\n prepare_dir(source_root, source_fiels)\n\n with chdir_context(source_root):\n # prepare for the test server\n output_root = os.path.join(temp_dir, 'output')\n server = MockMLServer(output_root)\n\n # prepare for the test experiment runner\n config = MLRunnerConfig(\n server=server.uri,\n name='test',\n args=[\n sys.executable,\n '-c',\n 'print(\"hello\")\\n'\n 'print(\"[Epoch 2/5, Batch 3/6, Step 4, ETA 5s] epoch_time: 1s; loss: 0.25 (±0.1); span: 5\")\\n'\n 'open(\"config.json\", \"wb\").write(b\"{\\\\\"max_epoch\\\\\": 123}\\\\n\")\\n'\n 'open(\"config.defaults.json\", \"wb\").write(b\"{\\\\\"max_epoch\\\\\": 100}\\\\n\")\\n'\n 'open(\"webui.json\", \"wb\").write(b\"{\\\\\"TB\\\\\": \\\\\"http://tb:7890\\\\\"}\\\\n\")\\n'\n 'import time\\n'\n 'time.sleep(1)\\n'\n 'open(\"result.json\", \"wb\").write(b\"{\\\\\"acc\\\\\": 0.99}\\\\n\")\\n'\n ],\n daemon=[\n ['echo', 'daemon 1'],\n 'echo \"Serving HTTP on 0.0.0.0 port 12367 '\n '(http://0.0.0.0:12367/)\"',\n 'env',\n ],\n env={'MY_ENV': 'abc'},\n gpu=[1, 2]\n )\n config.source.copy_to_dst = True\n config.source.cleanup = False\n config.integration.watch_json_files = True\n config.integration.parse_stdout = True\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n # run the test experiment\n with server:\n code = runner.run()\n self.assertEqual(code, 0)\n\n # check the result\n self.assertEqual(len(server.db), 1)\n doc = list(server.db.values())[0]\n\n output_dir = os.path.join(output_root, doc['_id'])\n size, inode = compute_fs_size_and_inode(output_dir)\n\n exc_info = doc.pop('exc_info')\n self.assertIsInstance(exc_info, dict)\n self.assertEqual(exc_info['hostname'], socket.gethostname())\n self.assertIsInstance(exc_info['pid'], int)\n self.assertIsInstance(exc_info['env'], dict)\n self.assertEqual(exc_info['env']['PYTHONUNBUFFERED'], '1')\n self.assertEqual(exc_info['env']['MLSTORAGE_SERVER_URI'],\n 'http://127.0.0.1:8080')\n self.assertEqual(exc_info['env']['MLSTORAGE_EXPERIMENT_ID'],\n doc['_id'])\n self.assertEqual(exc_info['env']['MLSTORAGE_OUTPUT_DIR'],\n output_dir)\n self.assertEqual(exc_info['env']['PWD'], output_dir)\n self.assertEqual(exc_info['env']['CUDA_VISIBLE_DEVICES'], '1,2')\n self.assertIn(output_dir, exc_info['env']['PYTHONPATH'])\n self.assertIn(source_root, exc_info['env']['PYTHONPATH'])\n\n control_port = doc.pop('control_port')\n self.assertIsInstance(control_port, dict)\n self.assertTrue(control_port['kill'].startswith('http://'))\n\n hostname = socket.gethostname()\n stop_time = doc.pop('stop_time')\n self.assertEqual(doc.pop('heartbeat'), stop_time)\n self.assertDictEqual(doc, {\n 'name': config.name,\n '_id': doc[\"_id\"],\n 'storage_dir': os.path.join(\n temp_dir, f'output/{doc[\"_id\"]}'),\n 'args': config.args,\n 'progress': {'epoch': '2/5', 'batch': '3/6', 'step': 4, 'eta': '5s'},\n 'result': {'acc': 0.99, 'span': '5', 'loss': '0.25 (±0.1)'},\n 'exit_code': code,\n 'storage_size': size,\n 'storage_inode': inode,\n 'status': 'COMPLETED',\n 'config': {'max_epoch': 123},\n 'default_config': {'max_epoch': 100},\n 'webui': {'SimpleHTTP': f'http://{hostname}:12367/',\n 'TB': 'http://tb:7890'},\n })\n\n output_snapshot = dir_snapshot(output_dir)\n self.assertEqual(\n set(output_snapshot),\n {'config.defaults.json', 'config.json', 'console.log',\n 'daemon.0.log', 'daemon.1.log', 'daemon.2.log',\n 'mlrun.log', 'result.json', 'webui.json', 'source.zip',\n 'a.py', 'nested'}\n )\n\n self.assertEqual(output_snapshot['config.defaults.json'],\n b'{\"max_epoch\": 100}\\n')\n self.assertEqual(output_snapshot['config.json'],\n b'{\"max_epoch\": 123}\\n')\n self.assertEqual(output_snapshot['console.log'],\n b'hello\\n'\n b'[Epoch 2/5, Batch 3/6, Step 4, ETA 5s] '\n b'epoch_time: 1s; loss: 0.25 (\\xc2\\xb10.1); '\n b'span: 5\\n')\n self.assertEqual(output_snapshot['result.json'],\n b'{\"acc\": 0.99}\\n')\n self.assertEqual(output_snapshot['webui.json'],\n b'{\"TB\": \"http://tb:7890\"}\\n')\n\n self.assertEqual(output_snapshot['daemon.0.log'],\n b'daemon 1\\n')\n self.assertTrue(output_snapshot['daemon.1.log'].startswith(\n b'Serving HTTP on 0.0.0.0 port 12367 '\n b'(http://0.0.0.0:12367/)'\n ))\n\n self.assertIn(b'MY_ENV=abc\\n', output_snapshot['daemon.2.log'])\n self.assertIn(b'PYTHONUNBUFFERED=1\\n',\n output_snapshot['daemon.2.log'])\n\n self.assertEqual(output_snapshot['a.py'], b'print(\"a.py\")\\n')\n self.assertDictEqual(output_snapshot['nested'], {\n 'b.sh': b'echo \"b.sh\"\\n',\n })\n\n self.assertDictEqual(\n zip_snapshot(os.path.join(output_dir, 'source.zip')),\n {\n 'a.py': b'print(\"a.py\")\\n',\n 'nested': {\n 'b.sh': b'echo \"b.sh\"\\n'\n }\n }\n )\n\n @slow_test\n @httpretty.activate\n def test_copy_arg_files_resume_and_clone(self):\n parent_id = str(ObjectId())\n\n with TemporaryDirectory() as temp_dir:\n # prepare for the source dir\n source_root = os.path.join(temp_dir, 'source')\n source_fiels = {\n 'a.py': b'print(\"a.py\")\\n',\n 'a.txt': b'a.txt content\\n',\n 'nested': {\n 'b.sh': b'echo \"b.sh\"\\nexit 1\\n'\n }\n }\n prepare_dir(source_root, source_fiels)\n\n with chdir_context(source_root):\n # prepare for the test server\n output_root = os.path.join(temp_dir, 'output')\n server = MockMLServer(output_root)\n\n # test copy arg files\n config = MLRunnerConfig(\n server=server.uri,\n args='sh nested/b.sh a.txt'.split(' '),\n parent_id=parent_id,\n )\n config.source.make_archive = False # test no source archive\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n with server:\n code = runner.run()\n self.assertEqual(code, 1)\n\n self.assertEqual(len(server.db), 1)\n doc = list(server.db.values())[0]\n self.assertEqual(doc['exit_code'], 1)\n self.assertEqual(doc['status'], 'COMPLETED')\n self.assertEqual(doc['parent_id'], parent_id)\n self.assertEqual(doc['name'], ' '.join(config.args))\n\n output_snapshot = dir_snapshot(doc['storage_dir'])\n self.assertEqual(output_snapshot['console.log'], b'b.sh\\n')\n self.assertEqual(output_snapshot['nested'], {\n 'b.sh': b'echo \"b.sh\"\\nexit 1\\n',\n })\n self.assertNotIn('source.zip', output_snapshot)\n self.assertNotIn('a.txt', output_snapshot)\n self.assertNotIn('a.py', output_snapshot)\n\n # test resume from\n config = MLRunnerConfig(\n server=server.uri,\n args='echo hello',\n resume_from=doc['_id'],\n )\n config.source.make_archive = False\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n with server:\n code = runner.run()\n self.assertEqual(code, 0)\n\n self.assertEqual(len(server.db), 1)\n doc2 = list(server.db.values())[0]\n self.assertEqual(doc2, doc)\n\n output_snapshot = dir_snapshot(doc['storage_dir'])\n self.assertEqual(output_snapshot['console.log'],\n b'b.sh\\nhello\\n')\n\n # test clone from\n config = MLRunnerConfig(\n server=server.uri,\n args='echo hi',\n clone_from=doc['_id'],\n )\n config.source.make_archive = False\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n with server:\n code = runner.run()\n self.assertEqual(code, 0)\n\n self.assertEqual(len(server.db), 2)\n doc3 = list(server.db.values())[1]\n self.assertNotEqual(doc3['_id'], doc['_id'])\n self.assertNotEqual(doc3['storage_dir'], doc['storage_dir'])\n\n output_snapshot = dir_snapshot(doc3['storage_dir'])\n self.assertEqual(output_snapshot['console.log'],\n b'b.sh\\nhello\\nhi\\n')\n self.assertEqual(output_snapshot['nested'], {\n 'b.sh': b'echo \"b.sh\"\\nexit 1\\n',\n })\n\n @slow_test\n @httpretty.activate\n def test_work_dir(self):\n parent_id = str(ObjectId())\n\n with TemporaryDirectory() as temp_dir, \\\n set_environ_context(MLSTORAGE_EXPERIMENT_ID=parent_id):\n # prepare for the source dir\n source_root = os.path.join(temp_dir, 'source')\n source_fiels = {\n 'a.py': b'print(\"a.py\")\\n',\n 'a.txt': b'a.txt content\\n',\n 'nested': {\n 'b.sh': b'echo \"b.sh\"\\nexit 1\\n'\n }\n }\n prepare_dir(source_root, source_fiels)\n\n # prepare for the work dir\n work_dir = os.path.join(temp_dir, 'work')\n os.makedirs(work_dir)\n\n with chdir_context(source_root):\n # prepare for the test server\n output_root = os.path.join(temp_dir, 'output')\n server = MockMLServer(output_root)\n\n # test copy arg files\n config = MLRunnerConfig(\n server=server.uri,\n args='echo nested/b.sh a.txt; echo hello > temp.txt',\n daemon=['pwd'],\n work_dir=work_dir,\n )\n config.source.make_archive = False # test no source archive\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n with server:\n code = runner.run()\n self.assertEqual(code, 0)\n\n self.assertEqual(len(server.db), 1)\n doc = list(server.db.values())[0]\n self.assertEqual(doc['exit_code'], 0)\n self.assertEqual(doc['status'], 'COMPLETED')\n self.assertEqual(doc['parent_id'], parent_id)\n self.assertEqual(doc['name'], config.args)\n self.assertNotEqual(doc['storage_dir'], work_dir)\n\n output_snapshot = dir_snapshot(doc['storage_dir'])\n self.assertEqual(output_snapshot['console.log'],\n b'nested/b.sh a.txt\\n')\n self.assertEqual(output_snapshot['daemon.0.log'],\n f'{work_dir}\\n'.encode('utf-8'))\n self.assertEqual(output_snapshot['nested'], {\n 'b.sh': b'echo \"b.sh\"\\nexit 1\\n',\n })\n self.assertNotIn('source.zip', output_snapshot)\n self.assertNotIn('a.txt', output_snapshot)\n self.assertNotIn('a.py', output_snapshot)\n\n work_dir_snapshot = dir_snapshot(work_dir)\n self.assertDictEqual(work_dir_snapshot, {\n 'temp.txt': b'hello\\n'\n })\n\n @slow_test\n @httpretty.activate\n def test_inner_error(self):\n def mock_gethostname():\n raise RuntimeError('cannot get hostname')\n\n with TemporaryDirectory() as temp_dir, \\\n mock.patch('socket.gethostname', mock_gethostname):\n # prepare for the test server\n output_root = os.path.join(temp_dir, 'output')\n server = MockMLServer(output_root)\n\n # test copy arg files\n config = MLRunnerConfig(\n server=server.uri,\n args='echo hello',\n )\n config.source.make_archive = False # test no source archive\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n with pytest.raises(RuntimeError, match='cannot get hostname'):\n with server:\n _ = runner.run()\n\n self.assertEqual(len(server.db), 1)\n doc = list(server.db.values())[0]\n\n self.assertEqual(doc['status'], 'FAILED')\n self.assertEqual(doc['error']['message'], 'cannot get hostname')\n self.assertIn('RuntimeError: cannot get hostname',\n doc['error']['traceback'])\n\n log_cnt = get_file_content(\n os.path.join(doc['storage_dir'], 'mlrun.log'))\n self.assertIn(b'RuntimeError: cannot get hostname', log_cnt)\n\n @slow_test\n @httpretty.activate\n def test_outer_error(self):\n @contextmanager\n def mock_configure_logger(*args, **kwargs):\n raise RuntimeError('cannot configure logger')\n yield\n\n with TemporaryDirectory() as temp_dir, \\\n mock.patch('mltk.mlrunner.configure_logger',\n mock_configure_logger):\n # prepare for the test server\n output_root = os.path.join(temp_dir, 'output')\n server = MockMLServer(output_root)\n\n # test copy arg files\n config = MLRunnerConfig(\n server=server.uri,\n args='echo hello',\n )\n config.source.make_archive = False # test no source archive\n runner = MLRunner(config, retry_intervals=(0.1, 0.2, 0.3))\n\n with pytest.raises(RuntimeError, match='cannot configure logger'):\n with server:\n _ = runner.run()\n\n self.assertEqual(len(server.db), 1)\n doc = list(server.db.values())[0]\n\n self.assertEqual(doc['status'], 'FAILED')\n self.assertEqual(doc['error']['message'], 'cannot configure logger')\n self.assertIn('RuntimeError: cannot configure logger',\n doc['error']['traceback'])\n\n\ndef make_PatchedMLRunner():\n class PatchedMLRunner(MLRunner):\n\n exit_code: int = 0\n last_instance: 'PatchedMLRunner' = None\n\n def __init__(self, config):\n super().__init__(config)\n self.__class__.last_instance = self\n\n def run(self):\n return self.exit_code\n\n return PatchedMLRunner\n\n\ndef make_PatchedMLRunnerConfigLoader():\n class PatchedMLRunnerConfigLoader(MLRunnerConfigLoader):\n\n last_instance: 'PatchedMLRunnerConfigLoader' = None\n\n def __init__(self, config_files, **kwargs):\n super().__init__(config_files=config_files, **kwargs)\n self.__class__.last_instance = self\n self.loaded = False\n\n def load_config_files(self, on_load=None):\n super().load_config_files(on_load)\n self.loaded = True\n\n return PatchedMLRunnerConfigLoader\n\n\nclass MLRunTestCase(unittest.TestCase):\n\n def test_mlrun(self):\n @config_params(undefined_fields=True)\n class MyMLRunnerConfig(MLRunnerConfig):\n pass\n\n with TemporaryDirectory() as temp_dir:\n config1 = os.path.join(temp_dir, 'config1.yml')\n config2 = os.path.join(temp_dir, 'config2.yml')\n write_file_content(config1, b'key1: 123')\n write_file_content(config2, b'key2: 456')\n\n runner = CliRunner()\n\n # test default arguments\n result = runner.invoke(\n mlrun,\n ['-s', 'http://127.0.0.1:8080', '--print-config',\n '--', 'echo', 'hello']\n )\n self.assertEqual(result.exit_code, 0)\n self.assertEqual(\n result.output.rstrip(),\n mltk.format_config(\n MLRunnerConfig(\n server='http://127.0.0.1:8080',\n args=['echo', 'hello'],\n source=MLRunnerConfig.source(),\n integration=MLRunnerConfig.integration()\n ),\n sort_keys=True\n )\n )\n\n # test various arguments\n with set_environ_context(MLSTORAGE_SERVER_URI='http://127.0.0.1:8080'):\n result = runner.invoke(mlrun, [\n '-C', config1,\n '--config-file=' + config2,\n '-c', 'echo hello',\n '-e', 'MY_ENV=abc',\n '--env=MY_ENV2=def',\n '-g', '1,2',\n '--gpu=3',\n '-n', 'test',\n '--description=testing',\n '-t', 'first',\n '--tags=second',\n '--daemon=echo hello',\n '-D', 'echo hi',\n '--tensorboard',\n '--no-source-archive',\n '--parse-stdout',\n '--watch-files',\n '--copy-source',\n '--resume-from=xyzz',\n '--clone-from=zyxx',\n '--print-config',\n ])\n self.assertEqual(result.exit_code, 0)\n self.assertEqual(\n result.output.rstrip(),\n mltk.format_config(\n MyMLRunnerConfig(\n server='http://127.0.0.1:8080',\n args='echo hello',\n env={'MY_ENV': 'abc', 'MY_ENV2': 'def'},\n gpu=[1, 2, 3],\n name='test',\n description='testing',\n tags=['first', 'second'],\n daemon=[\n 'echo hello',\n 'echo hi',\n 'tensorboard --logdir=. --port=0 --host=0.0.0.0',\n ],\n source=MLRunnerConfig.source(\n copy_to_dst=True,\n make_archive=False,\n ),\n integration=MLRunnerConfig.integration(\n parse_stdout=True,\n watch_json_files=True,\n ),\n resume_from='xyzz',\n clone_from='zyxx',\n key1=123,\n key2=456,\n ),\n sort_keys=True\n )\n )\n\n def test_legacy_args(self):\n with TemporaryDirectory() as temp_dir:\n runner = CliRunner()\n\n # test default arguments\n result = runner.invoke(mlrun, [\n '-s', 'http://127.0.0.1:8080',\n '--legacy',\n '--print-config',\n '--',\n 'echo', 'hello',\n ])\n self.assertEqual(result.exit_code, 0)\n self.assertEqual(\n result.output.rstrip(),\n mltk.format_config(\n MLRunnerConfig(\n source=MLRunnerConfig.source(),\n integration=MLRunnerConfig.integration(\n parse_stdout=True,\n watch_json_files=True,\n ),\n server='http://127.0.0.1:8080',\n args=['echo', 'hello'],\n ),\n sort_keys=True,\n )\n )\n\n\nclass ProgramHostTestCase(unittest.TestCase):\n\n @slow_test\n def test_run(self):\n def run_and_get_output(*args, **kwargs):\n with TemporaryDirectory() as temp_dir:\n log_file = os.path.join(temp_dir, 'log.txt')\n kwargs.setdefault('log_to_stdout', False)\n kwargs.setdefault('log_file', log_file)\n host = ProgramHost(*args, **kwargs)\n code = host.run()\n if os.path.isfile(log_file):\n output = get_file_content(log_file)\n else:\n output = None\n return code, output\n\n # test exit code\n host = ProgramHost('exit 123', log_to_stdout=False)\n self.assertEqual(host.run(), 123)\n\n host = ProgramHost(['sh', '-c', 'exit 123'],\n log_to_stdout=False)\n self.assertEqual(host.run(), 123)\n\n # test environment dict\n code, output = run_and_get_output(\n 'env',\n env={\n 'MY_ENV_VAR': 'hello',\n b'MY_ENV_VAR_2': b'hi',\n },\n )\n self.assertEqual(code, 0)\n self.assertIn(b'MY_ENV_VAR=hello\\n', output)\n self.assertIn(b'MY_ENV_VAR_2=hi\\n', output)\n\n # test work dir\n with TemporaryDirectory() as temp_dir:\n temp_dir = os.path.realpath(temp_dir)\n code, output = run_and_get_output('pwd', work_dir=temp_dir)\n self.assertEqual(code, 0)\n self.assertEqual(output, temp_dir.encode('utf-8') + b'\\n')\n\n # test stdout\n with TemporaryDirectory() as temp_dir:\n log_file = os.path.join(temp_dir, 'log.txt')\n fd = os.open(log_file, os.O_CREAT | os.O_WRONLY | os.O_TRUNC)\n stdout_fd = sys.stdout.fileno()\n stdout_fd2 = None\n\n try:\n sys.stdout.flush()\n stdout_fd2 = os.dup(stdout_fd)\n os.dup2(fd, stdout_fd)\n\n # run the program\n code, output = run_and_get_output(\n 'echo \"hello\"', log_to_stdout=True)\n self.assertEqual(code, 0)\n self.assertEqual(output, b'hello\\n')\n self.assertEqual(get_file_content(log_file), output)\n finally:\n if stdout_fd2 is not None:\n os.dup2(stdout_fd2, stdout_fd)\n os.close(stdout_fd2)\n\n # test log parser\n class MyParser(ProgramOutputReceiver):\n def __init__(self):\n super().__init__([])\n\n def start(self):\n super().start()\n logs.append('start')\n\n def put_output(self, data: bytes):\n logs.append(data)\n\n def stop(self):\n super().stop()\n logs.append('flush')\n\n logs = []\n code, output = run_and_get_output(\n [\n sys.executable, '-c',\n r'import sys, time; '\n r'sys.stdout.write(\"hello\\n\"); '\n r'sys.stdout.flush(); '\n r'time.sleep(0.1); '\n r'sys.stdout.write(\"world\\n\")'\n ],\n log_receiver=MyParser()\n )\n self.assertEqual(code, 0)\n self.assertEqual(output, b'hello\\nworld\\n')\n self.assertListEqual(logs, ['start', b'hello\\n', b'world\\n', 'flush'])\n\n # test log parser with error\n class MyParser(ProgramOutputReceiver):\n def __init__(self):\n super().__init__([])\n\n def start(self):\n super().start()\n logs.append('start')\n\n def put_output(self, content: bytes):\n logs.append(content)\n raise RuntimeError('some error occurred')\n\n def stop(self):\n super().stop()\n logs.append('flush')\n raise RuntimeError('some error occurred')\n\n logs = []\n code, output = run_and_get_output(\n [\n sys.executable, '-c',\n r'import sys, time; '\n r'sys.stdout.write(\"hello\\n\"); '\n r'sys.stdout.flush(); '\n r'time.sleep(0.1); '\n r'sys.stdout.write(\"world\\n\")'\n ],\n log_receiver=MyParser()\n )\n self.assertEqual(code, 0)\n self.assertEqual(output, b'hello\\nworld\\n')\n self.assertListEqual(logs, ['start', b'hello\\n', b'world\\n', 'flush'])\n\n # test log file\n with TemporaryDirectory() as temp_dir:\n log_file = os.path.join(temp_dir, 'log.txt')\n\n # test append\n code, output = run_and_get_output('echo hello', log_file=log_file)\n self.assertEqual(code, 0)\n code, output = run_and_get_output('echo hi', log_file=log_file)\n self.assertEqual(code, 0)\n self.assertEqual(get_file_content(log_file), b'hello\\nhi\\n')\n\n # test no append\n code, output = run_and_get_output(\n 'echo hey', log_file=log_file, append_to_file=False)\n self.assertEqual(code, 0)\n self.assertEqual(get_file_content(log_file), b'hey\\n')\n\n # test fileno\n log_fileno = os.open(\n log_file, os.O_CREAT | os.O_TRUNC | os.O_WRONLY)\n try:\n code, output = run_and_get_output(\n 'echo goodbye', log_file=log_fileno)\n self.assertEqual(code, 0)\n finally:\n os.close(log_fileno)\n self.assertEqual(get_file_content(log_file), b'goodbye\\n')\n\n @slow_test\n def test_kill(self):\n with TemporaryDirectory() as temp_dir:\n # test kill by SIGINT\n host = ProgramHost(\n [\n sys.executable,\n '-u', '-c',\n 'import time, sys\\n'\n 'for i in range(100):\\n'\n ' sys.stdout.write(str(i) + \"\\\\n\")\\n'\n ' sys.stdout.flush()\\n'\n ' time.sleep(0.1)\\n'\n ],\n log_to_stdout=False,\n )\n\n with host.exec_proc() as proc:\n time.sleep(0.5)\n start_time = time.time()\n host.kill(ctrl_c_timeout=3)\n stop_time = time.time()\n\n host.kill()\n _ = proc.wait()\n # self.assertNotEqual(code, 0)\n self.assertLess(abs(stop_time - start_time), 0.5) # that is, 20% difference of time\n\n # test kill by SIGKILL\n log_file = os.path.join(temp_dir, 'console.log')\n host = ProgramHost(\n [\n sys.executable,\n '-u', '-c',\n 'import sys, time\\n'\n 'while True:\\n'\n ' try:\\n'\n ' time.sleep(0.1)\\n'\n ' except KeyboardInterrupt:\\n'\n ' sys.stdout.write(\"kbd interrupt\\\\n\")\\n'\n ' sys.stdout.flush()\\n'\n ],\n log_file=log_file\n )\n\n with host.exec_proc() as proc:\n time.sleep(0.5)\n start_time = time.time()\n host.kill(ctrl_c_timeout=0.5)\n stop_time = time.time()\n\n host.kill()\n _ = proc.wait()\n self.assertEqual(get_file_content(log_file), b'kbd interrupt\\n')\n self.assertLess(abs(stop_time - start_time - 0.5), 0.1)\n\n\nclass SourceCopierTestCase(unittest.TestCase):\n\n def test_copier(self):\n includes = MLRunnerConfig.source.includes\n excludes = MLRunnerConfig.source.excludes\n\n with TemporaryDirectory() as temp_dir:\n # prepare for the source dir\n source_dir = os.path.join(temp_dir, 'src')\n prepare_dir(source_dir, {\n 'a.py': b'a.py',\n 'b.txt': b'b.txt',\n '.git': {\n 'c.py': b'c.py',\n },\n 'dir': {\n 'd.sh': b'd.sh',\n },\n 'dir2': {\n 'nested': {\n 'e.sh': b'e.sh'\n },\n 'f.sh': b'f.sh',\n },\n 'override.py': b'source'\n })\n\n # test copy source\n dest_dir = os.path.join(temp_dir, 'dst')\n prepare_dir(dest_dir, {'override.py': b'dest'})\n\n copier = SourceCopier(source_dir, dest_dir, includes, excludes)\n copier.clone_dir()\n self.assertEqual(copier.file_count, 4)\n dest_content = dir_snapshot(dest_dir)\n dest_expected = {\n 'a.py': b'a.py',\n 'dir': {\n 'd.sh': b'd.sh',\n },\n 'dir2': {\n 'nested': {\n 'e.sh': b'e.sh'\n },\n 'f.sh': b'f.sh',\n },\n 'override.py': b'dest'\n }\n self.assertDictEqual(dest_content, dest_expected)\n\n # test pack zip\n zip_file = os.path.join(temp_dir, 'source.zip')\n copier.pack_zip(zip_file)\n zip_content = zip_snapshot(zip_file)\n dest_expected['override.py'] = b'source'\n self.assertDictEqual(zip_content, dest_expected)\n\n # test cleanup\n write_file_content(\n os.path.join(dest_dir, 'dir/more.txt'),\n b'more.txt') # more file\n os.remove(os.path.join(dest_dir, 'dir2/f.sh')) # fewer file\n copier.cleanup_dir()\n dest_content = dir_snapshot(dest_dir)\n self.assertDictEqual(dest_content, {\n 'dir': {\n 'more.txt': b'more.txt'\n },\n 'override.py': b'dest'\n })\n\n def test_copy_args_files(self):\n with TemporaryDirectory() as temp_dir:\n src = os.path.join(temp_dir, 'src')\n dst1 = os.path.join(temp_dir, 'dst1')\n dst2 = os.path.join(temp_dir, 'dst2')\n prepare_dir(temp_dir, {'e.sh': b'e.sh'})\n\n # prepare for the source dir\n prepare_dir(src, {\n 'a.py': b'a.py',\n 'a.sh': b'a.sh',\n 'a.txt': b'a.txt',\n 'nested': {\n 'b.sh': b'b.sh',\n 'b.py': b'b.py',\n },\n '.git': {\n 'c.py': b'c.py'\n },\n })\n\n # test copy according to command line\n copier = SourceCopier(src, dst1, MLRunnerConfig.source.includes,\n MLRunnerConfig.source.excludes)\n copier.copy_args_files(\n 'python a.py a.txt nested/b.py ./nested/../nested/b.sh '\n '.git/c.py d.sh ../e.sh'\n )\n self.assertDictEqual(dir_snapshot(dst1), {\n 'a.py': b'a.py',\n 'nested': {\n 'b.sh': b'b.sh',\n 'b.py': b'b.py',\n }\n })\n\n # test copy according to args\n copier = SourceCopier(src, dst2, MLRunnerConfig.source.includes,\n MLRunnerConfig.source.excludes)\n copier.copy_args_files(\n 'python a.py a.txt nested/b.py ./nested/../nested/b.sh '\n '.git/c.py d.sh ../e.sh'.split(' ')\n )\n self.assertDictEqual(dir_snapshot(dst2), {\n 'a.py': b'a.py',\n 'nested': {\n 'b.sh': b'b.sh',\n 'b.py': b'b.py',\n }\n })\n\n\nclass TemporaryFileCleanerTestCase(unittest.TestCase):\n\n maxDiff = None\n\n def test_cleanup(self):\n with TemporaryDirectory() as temp_dir:\n prepare_dir(temp_dir, {\n '.git': {\n 'a.pyc': b'a.pyc'\n },\n '__pycache__': {\n 'b.pyc': b'b.pyc',\n 'g.txt': b'g.txt',\n },\n 'nested': {\n '__pycache__': {\n 'c.pyc': b'c.pyc',\n 'd.pyc': b'd.pyc',\n 'Thumbs.db': b'Thumbs.db',\n '.DS_Store': b'.DS_Store',\n },\n 'e.pyc': b'e.pyc',\n },\n 'h.DS_Store': b'h.DS_Store'\n })\n\n cleaner = TemporaryFileCleaner(temp_dir)\n cleaner.cleanup()\n\n self.assertDictEqual(dir_snapshot(temp_dir), {\n '.git': {\n 'a.pyc': b'a.pyc',\n },\n '__pycache__': {\n 'g.txt': b'g.txt',\n },\n 'nested': {},\n 'h.DS_Store': b'h.DS_Store'\n })\n\n # test cleanup non-exist directory\n cleaner = TemporaryFileCleaner(os.path.join(temp_dir, 'non-exist'))\n cleaner.cleanup()\n\n\nclass JsonFileWatcherTestCase(unittest.TestCase):\n\n @slow_test\n def test_watcher(self):\n with TemporaryDirectory() as temp_dir:\n logs = []\n path_a = os.path.join(temp_dir, 'a.json')\n path_b = os.path.join(temp_dir, 'b.json')\n path_c = os.path.join(temp_dir, 'c.json')\n os.makedirs(os.path.join(temp_dir, 'd.json'))\n\n watcher = JsonFileWatcher(\n root_dir=temp_dir,\n file_names=['a.json', 'b.json', 'd.json'],\n interval=0.1,\n )\n\n def on_json_updated(*args):\n logs.append(args)\n\n def raise_error(*args):\n raise RuntimeError('raised error')\n\n watcher.on_json_updated.do(on_json_updated)\n watcher.on_json_updated.do(raise_error)\n\n with watcher:\n write_file_content(path_a, b'{\"a\": 1}')\n write_file_content(path_c, b'{\"c\": 3}')\n time.sleep(0.12)\n write_file_content(path_b, b'{\"b\": 2}')\n time.sleep(0.12)\n self.assertListEqual(logs, [\n ('a.json', {'a': 1}), ('b.json', {'b': 2})\n ])\n\n write_file_content(path_a, b'{\"a\": 4}')\n time.sleep(0.12)\n self.assertListEqual(logs, [\n ('a.json', {'a': 1}), ('b.json', {'b': 2}),\n ('a.json', {'a': 4})\n ])\n\n self.assertListEqual(logs, [\n ('a.json', {'a': 1}), ('b.json', {'b': 2}),\n ('a.json', {'a': 4}),\n # the forced, final check\n ('a.json', {'a': 4}), ('b.json', {'b': 2})\n ])\n\n\nclass ControlPortServerTestCase(unittest.TestCase):\n\n @slow_test\n def test_server(self):\n server = ControlServer('127.0.0.1', 12379)\n self.assertEqual(server.uri, 'http://127.0.0.1:12379')\n\n server = ControlServer('127.0.0.1')\n logs = []\n\n with server.run_in_background():\n time.sleep(0.5)\n\n # test not found\n r = requests.get(server.uri)\n self.assertEqual(r.status_code, 404)\n\n r = requests.post(server.uri, data=b'')\n self.assertEqual(r.status_code, 404)\n\n # test kill\n server.on_kill.do(lambda: logs.append('on kill'))\n self.assertListEqual(logs, [])\n r = requests.post(server.uri + '/kill', json={})\n self.assertEqual(r.status_code, 200)\n self.assertEqual(r.content, b'{}')\n self.assertEqual(r.headers['Content-Type'].split(';', 1)[0],\n 'application/json')\n self.assertListEqual(logs, ['on kill'])\n\n # test kill but error\n def on_kill_error():\n raise RuntimeError('error on kill')\n\n server.on_kill.do(on_kill_error)\n r = requests.post(server.uri + '/kill', json={})\n self.assertEqual(r.status_code, 500)\n","repo_name":"haowen-xu/ml-essentials","sub_path":"tests/test_mlrunner.py","file_name":"test_mlrunner.py","file_ext":"py","file_size_in_byte":51616,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"13495091071","text":"import module1 as mod\r\n\r\ninp_1 = input(\"Pick a number between 1 and 10: \")\r\ndef weapon(self):\r\n \r\n if inp_1 >= 5:\r\n self.weapon = \"Flip-flops\"\r\n self.xp += 15\r\n else: \r\n self.xp += 25\r\n self.weapon = \"Pan\"\r\n\r\n\r\nweapon()\r\ninp_2 = input(\"Pick a number between 1 and 6: \")\r\ndef health(self):\r\n if inp_2 > 3:\r\n self.xp += 20\r\n self.health += 50\r\n print(\"Health is 50\")\r\n elif inp_2 < 3:\r\n self.xp += 25\r\n self.health += 100\r\n print(\"Health is 100\")\r\nhealth()\r\ninp_3 = input(\"You see a large treasure chest and no one is around!, do you want to open it (y/n): \")\r\n \r\ndef coins(self):\r\n \r\n if inp_3 == \"y\":\r\n self.coins = self.coins - 50\r\n print(\"You have been trapped and lost 50 coins\")\r\n self.xp -= 10\r\n else:\r\n self.xp\r\n self.coins = self.coins + 50\r\n print(\"Smart choice, you avoided a coin trap. You have been awarded 50 coins\")\r\ncoins()\r\n\r\n\r\n\r\n\r\n\r\n\r\ninp_4 = None\r\ndef xp(self):\r\n inp_4 = self.xp\r\n while self.xp >= 100:\r\n exit()\r\nxp(mod.mov.description(mod.mov()))\r\n\r\n\r\nprint(mod.mov.description(mod.mov(inp_1,inp_2,inp_3)))\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"JamesBradleyBigCreative/Classroom_Exercises","sub_path":"Haitham Mohammed/OOP/OOP.py","file_name":"OOP.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"23050124490","text":"#!/bin/python\nfrom flask import Flask, request, render_template, json, jsonify\nimport flask_socketio\n# base socket\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'test123'\napp.config['FLASK_RUN_PORT'] = 5001\n\n\nsocketio = flask_socketio.SocketIO(app)\n\n# Connection \n\n#flask_socketio.emit('latest',{\"response\" : } )\n@app.route(\"/notify\", methods=['POST'])\ndef notify():\n data = {}\n data['title'] = request.form['title']\n data['content'] = request.form['content']\n print(data[\"content\"],data[\"title\"])\n socketio.emit(\"notify\", data, broadcast=True)\n return \"true\" , 200\n\nif __name__ == '__main__':\n socketio.run(app, port = 5001)\n","repo_name":"DjalimSimaila/ProjetsPersonnels","sub_path":"NotifSync/serveur.py","file_name":"serveur.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71951136804","text":"def multisource_bfs(graph, hospitals):\r\n all_distances = {} #{node:distance}\r\n paths = {} #path[node] stores the next node to travel to, to get to the hospital using the shortest path\r\n\r\n visited = set()\r\n queue = []\r\n\r\n for h in hospitals:\r\n queue.append(h)\r\n all_distances[h] = 0\r\n visited.add(h)\r\n paths[h] = -1\r\n \r\n while (queue):\r\n node = queue.pop(0)\r\n for neighbour in graph.graph[node]:\r\n if (neighbour not in visited):\r\n queue.append(neighbour)\r\n all_distances[neighbour] = all_distances[node] + 1\r\n paths[neighbour] = node\r\n visited.add(neighbour)\r\n\r\n #open file to save output\r\n distances_file = open(\"multisourceDistances.txt\", \"w+\")\r\n\r\n paths_file = open(\"multisourcePaths.txt\", \"w+\")\r\n\r\n for node in graph.V:\r\n if node not in hospitals:\r\n try:\r\n dist = all_distances[node]\r\n p = paths[node]\r\n distances_file.write(\"Node \" + str(node) + \":\\t\" + \"distance: \" + str(dist) + \"\\n\")\r\n paths_file.write(\"Node \" + str(node) + \":\\t\" + \"distance: \" + str(dist))\r\n paths_file.write(\"\\tPath: \" + str(node))\r\n while (p != -1):\r\n paths_file.write(\"->\" + str(p))\r\n p = paths[p]\r\n paths_file.write('\\n')\r\n except:\r\n distances_file.write(\"Node \" + str(node) + \" cannot reach any hospital!\\n\")\r\n paths_file.write(\"Node \" + str(node) + \" cannot reach any hospital!\\n\")\r\n\r\n distances_file.close()\r\n paths_file.close()\r\n","repo_name":"esther-gan/Graphing_Algorithms","sub_path":"multisourceBFS.py","file_name":"multisourceBFS.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31940192331","text":"class Solution:\n def sortedSquares(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n absA = [abs(i) for i in A]\n sortA = sorted(absA)\n squareA = [i*i for i in sortA]\n return squareA\n","repo_name":"WillowTotoro/Leecode-Answer","sub_path":"977. Squares of a Sorted Array.py","file_name":"977. Squares of a Sorted Array.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37849296676","text":"import pandas as pd\nimport sys\n\n\ndef conv_json(infile, index_col, columns, filter_by):\n df_raw = pd.read_csv(infile+'.csv')\n df_raw.columns = [c.lower().replace(' ', '_') for c in df_raw.columns]\n\n if filter_by:\n for i in range(len(filter_by)):\n df_raw = df_raw[df_raw[filter_by[i][0]] == filter_by[i][-1]]\n print(\"Filter done\")\n\n if \"ALL\" not in columns:\n df_raw = df_raw[columns].copy()\n print(\"Column selection done\")\n\n df = df_raw.dropna(axis=0, how='any', inplace=False)\n\n if index_col != '':\n df = df.set_index(index_col, verify_integrity=True)\n print(\"Index column done\")\n print(\"Show selected data? [y / n] > \", end='')\n if input() == 'y':\n print(\"Data:\\n\", df)\n\n df.to_json(infile+\".json\", orient=\"records\")\n print(\"Write to JSON done\")\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Error: incorrect number of arguments\\nUsage: Python csv2json.py name infile\")\n sys.exit(1)\n filter_by = []\n columns = []\n print(\"Index column (press enter to skip) > \", end='')\n index_col = input()\n if index_col != '':\n columns.append(index_col)\n print(index_col, \"added\")\n print(index_col, \"set to index column\")\n\n while 1:\n print(\"Columns to include (type HELP for commands) > \", end='')\n user_in = input()\n\n if user_in == \"DONE\":\n break\n\n elif user_in == \"DEL\":\n print(columns.pop(), \"removed\")\n\n elif user_in == \"FILTER\":\n print(\"Filter on which column > \", end='')\n f_col = input()\n print(\"Value to filter > \", end='')\n f_val = input()\n if not f_val.isalpha():\n try:\n filter_by.append([f_col, int(f_val)])\n except ValueError:\n print(\"Value must be a number, try again\")\n filter_by = []\n else:\n filter_by.append([f_col, f_val])\n print(\"Filter added\")\n\n elif user_in == \"UNDO FILTER\":\n filter_by.pop()\n print(\"Last filter removed\")\n\n elif user_in == \"HELP\":\n print('\"ALL\" : include all columns\\n\"DONE\" : go to next step\\n\"DEL\" : remove last entry\\n'\n '\"FILTER\" : filter data by column value\\n\"UNDO FILTERS\" : removes last filter\\n'\n '\"END\" : exit program')\n elif user_in == \"END\":\n sys.exit(0)\n elif user_in not in columns:\n columns.append(user_in)\n print(user_in, \"added\")\n\n conv_json(sys.argv[1], index_col, columns, filter_by)\n","repo_name":"Gwyd10n/Data_processing","sub_path":"Homework/Week_4/csv2json.py","file_name":"csv2json.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16273896126","text":"print(\"Highest and Lowest values\")\r\nprint(\"-\"*18)\r\n\r\ndef checking_values(number1, number2, number3):\r\n highest = int\r\n lowest = int\r\n if number1 > number2 > number3:\r\n highest = number1\r\n elif number2 > number1 and number2 > number3:\r\n highest = number2\r\n elif number3 > number2 and number3 > number1:\r\n highest = number3\r\n\r\n if number1 < number2 and number1 < number3:\r\n lowest = number1\r\n elif number2 < number1 and number2 < number3:\r\n lowest = number2\r\n elif number3 < number1 and number3 < number2:\r\n lowest = number3\r\n print(\"The highest is: {}\\nAnd the lowest: {} \".format(highest, lowest))\r\n\r\n\r\ntry:\r\n number1 = float(input(\"Type the first value: \"))\r\n number2 = float(input(\"Type the second value: \"))\r\n number3 = float(input(\"And type the third: \"))\r\nexcept ValueError:\r\n print('You probably typed a text, please try again')\r\nelse:\r\n checking_values(number1, number2, number3)\r\n","repo_name":"NikiReis/PythonExercises","sub_path":"World 1/Exercise 33.py","file_name":"Exercise 33.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20108006927","text":"import random\nfrom HangmanArt import logo, stages\nfrom HangmanWords import word_list\n\nprint(logo)\nprint(\"Developed with <3\")\ngame_is_Finished = False\nlives = len(stages) - 1\n\nMysteryWord = random.choice(word_list)\nwordLength = len(MysteryWord)\n# cheat Code\n# print(f\"The Answer is {MysteryWord}\")\n\ndisplay = []\nfor x in range(wordLength):\n display += \"_\"\n\nwhile not game_is_Finished:\n guess = input(\" Guess a letter: \").lower()\n\n if guess in display:\n print(f\"You have already guessed {guess}\")\n\n for position in range(wordLength):\n letter = MysteryWord[position]\n if letter == guess:\n display[position] = letter\n print(f\"{' '.join(display)}\")\n\n if guess not in MysteryWord:\n print(f\"You guessed {guess} which is not in given Word\")\n lives -= 1\n if lives == 0:\n game_is_Finished = True\n print(\"You have lost. \")\n\n if not '_' in display:\n game_is_Finished = True\n print(\"Hurrah! You won \\n No one got hanged today!!!\")\n print(stages[lives])\n","repo_name":"SaMs-Hub/Mini-Globe","sub_path":"HangBoy/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"22370503882","text":"import pandas as pd\nimport numpy as np\nimport torch\nfrom torch.optim.lr_scheduler import LambdaLR, ExponentialLR\nimport warnings\nfrom sklearn.metrics import (\n balanced_accuracy_score,\n f1_score,\n precision_score,\n recall_score,\n)\nfrom graph_cl.utils.mlflow_utils import (\n robust_mlflow,\n make_confusion_matrix,\n save_fig_to_mlflow,\n)\nimport mlflow\nimport os\n\n\n### Util functions ###\ndef split_concept_dataset(splits_df, index_col, dataset):\n # Read split map\n split_map = pd.read_csv(splits_df, index_col=index_col)\n\n # Init dictionary of subseted datasets\n subseted_datasets = {}\n\n # Loop over splits\n for split in split_map[\"split\"].unique():\n # Get sample ids\n ids = set(split_map[split_map[\"split\"] == split].index.values + \".pt\")\n\n # List of indexes of ids in dataset\n idxs = []\n file_names = []\n for i, spl in enumerate(dataset.file_names):\n if spl in ids:\n idxs.append(i)\n file_names.append(spl)\n\n # Subset dataset(\n subseted_datasets[split] = dataset[idxs]\n subseted_datasets[split].file_names = file_names\n\n # return dataset\n return subseted_datasets\n\n\ndef get_optimizer_class(cfg):\n optimizers = {\"Adam\": torch.optim.Adam, \"SGD\": torch.optim.SGD}\n optimizer_class = optimizers[cfg[\"optim\"]]\n return optimizer_class\n\n\ndef build_scheduler(cfg, optimizer):\n if cfg[\"scheduler\"][0] == \"ExponentialLR\":\n scheduler = ExponentialLR(optimizer, gamma=cfg[\"scheduler\"][1])\n elif cfg[\"scheduler\"][0] == \"LambdaLR\":\n lam = lambda epoch: cfg[\"scheduler\"][1] ** (epoch // cfg[\"scheduler\"][2])\n scheduler = LambdaLR(optimizer, lr_lambda=lam)\n else:\n raise Exception(\n \"Sorry, only ExponentialLR and LambdaLR are supported as learning rate decay strategies.\"\n )\n\n return scheduler\n\n\ndef train_one_epoch(model, train_loader, criterion, optimizer, scheduler):\n model.train()\n\n for data in train_loader: # Iterate in batches over the training dataset.\n out = model(data) # Perform a single forward pass.\n loss = criterion(out, data.y) # Compute the loss.\n loss.backward() # Derive gradients.\n optimizer.step() # Update parameters based on gradients.\n optimizer.zero_grad() # Clear gradients.\n\n # Adjust lr\n scheduler.step()\n\n\ndef eval_one_epoch(loader, split: str, model, device, cfg, criterion):\n # Get loss, predictionas and tru labels\n mean_loss, y_pred, y_true = predict(loader, model, device, criterion)\n (\n balanced_accuracy,\n weighted_precision,\n weighted_recall,\n weighted_f1_score,\n ) = compute_metrics(y_true, y_pred)\n return {\n f\"{split}_balanced_accuracy\": balanced_accuracy,\n f\"{split}_weighted_precision\": weighted_precision,\n f\"{split}_weighted_recall\": weighted_recall,\n f\"{split}_weighted_f1_score\": weighted_f1_score,\n f\"{split}_loss\": mean_loss,\n }\n\n\ndef compute_metrics(y_true, y_pred):\n # Set warnings as errors.\n warnings.filterwarnings(\"error\")\n try:\n balanced_accuracy = balanced_accuracy_score(y_true=y_true, y_pred=y_pred)\n weighted_precision = precision_score(\n y_true=y_true, y_pred=y_pred, average=\"weighted\", zero_division=0\n )\n # Every split should have both positive and negative classes, hence this two metrics below should never be\n # ill defined (have a zero divisor). Raise warning and show y_pred and y_true if not so.\n weighted_recall = recall_score(\n y_true=y_true, y_pred=y_pred, average=\"weighted\", zero_division=\"warn\"\n )\n weighted_f1_score = f1_score(\n y_true=y_true, y_pred=y_pred, average=\"weighted\", zero_division=\"warn\"\n )\n except Warning:\n # Print labels and predictions for debugging\n print(f\"One of the metrics is ill defined. Run tagged with metric warning.\")\n print(\"Printing y_pred:\")\n print(y_pred)\n print(\"Printing y_true:\")\n print(y_true)\n\n # Log warning\n robust_mlflow(\n mlflow.set_tag, key=\"metric_warning\", value=\"Run with metric warning\"\n )\n\n # Reset warnings as warnings to avoid stoping the execution.\n warnings.resetwarnings()\n\n return balanced_accuracy, weighted_precision, weighted_recall, weighted_f1_score\n\n\ndef predict(loader, model, device, criterion):\n # Freeze parameters\n model.eval()\n\n # Initialize tensor of results\n y_pred = torch.empty(0, dtype=torch.float64, device=device)\n y_true = torch.empty(0, dtype=torch.float64, device=device)\n total_loss = 0\n\n for data in loader: # Iterate in batches over the training/test dataset.\n # Get predictions\n out = model(data)\n\n # Use the class with highest probability.\n y_pred = torch.cat((y_pred, out.argmax(dim=1)), 0)\n\n # Get ground thruth labels\n y_true = torch.cat((y_true, data.y), 0)\n\n loss = criterion(out, data.y) # Compute the loss.\n assert not torch.isnan(\n loss\n ), f\"loss is NAN. Printing y_pred and y_true for batch. y_pred: {out}. y_true: {data.y}. loss: {loss}\"\n total_loss += loss.detach().cpu()\n\n # Compute average loss for the epoch\n mean_loss = total_loss.item() / len(loader)\n\n # Pass tensors to cpu and int types\n y_pred = y_pred.cpu().int()\n y_true = y_true.cpu().int()\n\n return mean_loss, y_pred, y_true\n\n\ndef train_validate_and_log_n_epochs(\n cfg,\n model,\n train_loader,\n val_loader,\n criterion,\n optimizer,\n scheduler,\n log_every_n_epochs,\n device,\n follow_this_metrics,\n):\n # for epoch in tqdm(range(1, cfg[\"n_epoch\"] + 1)): # this line if for debugging\n for epoch in range(1, cfg[\"n_epoch\"] + 1):\n # Train one epoch and obtain loss\n train_one_epoch(model, train_loader, criterion, optimizer, scheduler)\n\n if epoch % log_every_n_epochs == 0:\n # Evaluate on all splits\n train_metrics = eval_one_epoch(\n train_loader, \"train\", model, device, cfg, criterion\n )\n val_metrics = eval_one_epoch(\n val_loader, \"val\", model, device, cfg, criterion\n )\n\n # Join dictionaries\n metrics = {**train_metrics, **val_metrics}\n\n # Log performance metris\n robust_mlflow(\n mlflow.log_metrics,\n metrics=metrics,\n step=epoch,\n )\n # Save model to file if metrics in follow_this_metrics are immproved\n for metric, best_so_far_and_path in follow_this_metrics.items():\n # Unpack path and meteric\n best_so_far, out_file = best_so_far_and_path\n\n if val_metrics[metric] > best_so_far:\n # Reset best so far\n best_so_far = val_metrics[metric]\n follow_this_metrics[metric][0] = best_so_far\n\n # Save model\n torch.save(model.state_dict(), out_file)\n\n # Log performance\n robust_mlflow(\n mlflow.log_metric,\n key=f\"best_{metric}\",\n value=best_so_far,\n step=epoch,\n )\n\n # Log epoch\n robust_mlflow(\n mlflow.log_metric, key=f\"best_{metric}_epoch\", value=epoch\n )\n\n\ndef test_and_log_best_models(\n cfg, model, test_loader, criterion, device, follow_this_metrics, out_dir, split\n):\n for metric, best_so_far_and_path in follow_this_metrics.items():\n # Unpack values in tuple inside dict\n best_so_far, out_file = best_so_far_and_path\n\n # Load model and move to device\n model.load_state_dict(torch.load(out_file))\n model.to(device)\n\n # Compute metrics for the test split\n test_metrics = eval_one_epoch(\n test_loader, f\"{split}_best_{metric}\", model, device, cfg, criterion\n )\n\n # Log metrics mlflown\n robust_mlflow(mlflow.log_metrics, metrics=test_metrics)\n\n # Log confussion matrix\n _, y_pred, y_true = predict(test_loader, model, device, criterion)\n fig = make_confusion_matrix(\n prediction=y_pred.numpy(force=True).astype(int),\n ground_truth=y_true.numpy(force=True).astype(int),\n classes=[\"positive\", \"negative\"],\n )\n\n # Define figure name\n name = f\"{split}_conf_mat_from_best_{metric}\"\n\n # Save to file\n conf_mat_path = os.path.join(out_dir, f\"{name}.png\")\n fig.savefig(conf_mat_path)\n\n # Log on mlflow\n # save_fig_to_mlflow(fig, \"confusion_plots\", name)\n\n\ndef get_dict_of_metric_names_and_paths(out_file_1, out_file_2):\n follow_this_metrics = {}\n for file in [out_file_1, out_file_2]:\n name_plus_ext = os.path.basename(file)\n name = os.path.splitext(name_plus_ext)[0].split(\"best_\")[1]\n follow_this_metrics[name] = [0, file]\n return follow_this_metrics\n\n\ndef randomize_labels(splits_df, pred_target, splited_datasets):\n # Read split map\n split_map = pd.read_csv(splits_df, index_col=\"core\")\n\n # Create a new dictionary for the data in each split\n splited_datasets_in_mem = {}\n\n # For every split, permute the labels.\n for split in split_map[\"split\"].unique():\n\n # Randomly permute labes\n split_map.loc[split_map[\"split\"] == split, pred_target] = np.random.permutation(\n split_map.loc[split_map[\"split\"] == split, pred_target]\n )\n\n # For each smaple in the split put it in a list and change its label\n in_mem_data = []\n for i, file_name_ext in enumerate(splited_datasets[split].file_names):\n file_name = file_name_ext.split(\".\")[0]\n in_mem_data.append(splited_datasets[split].get(i))\n in_mem_data[i].y = torch.tensor([split_map.loc[file_name][pred_target]])\n\n # Save data to dictionary\n splited_datasets_in_mem[split] = in_mem_data\n\n # Return permuted data\n return splited_datasets_in_mem\n\n ### Code for debugging ###\n # for split in split_map[\"split\"].unique():\n # for i, file_name_ext in enumerate(splited_datasets[split].file_names):\n # print(f\"in mem: {splited_datasets_in_mem[split][i].y.item()}. in disk: {splited_datasets[split].get(i).y.item()}\")\n # print(f\"filename: {file_name_ext}\")\n # assert splited_datasets_in_mem[split][i].y.item() == splited_datasets[split].get(i).y.item()\n\n # assert False, \"All good\"\n\n\ndef get_datum_from_ConceptSetDataset(randomize, device, idx, splited_dataset):\n \"\"\"\n Return a datum from a ConceptSetDataset instance. If randomize == \"True\"\n then return it by slicing the splited_dataset since its a list. If \"False\"\n then use the get method from ConceptSetDataset class.\n \"\"\"\n\n if randomize == \"True\":\n return splited_dataset[idx].to(device, non_blocking=True)\n else:\n return splited_dataset.get(idx).to(device, non_blocking=True)\n","repo_name":"AI4SCR/graph-concept-learner","sub_path":"graph_cl/utils/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":11112,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18653911113","text":"from math import sqrt\nimport numpy as np \nimport random\n\ndef find_sd(lst, lst_mean):\n total_a = sum([(abs(x-lst_mean))**2 for x in lst])\n divide_by_n = total_a/len(lst)\n sqr_a = divide_by_n ** 0.5\n return sqr_a\n\ndef find_normal_dist(lst, lst_mean, lst_sd):\n my_pi = 3.14159\n my_e = 2.71828\n sqrt_2pi = (2 * my_pi) **0.5\n part1 = 1/(lst_sd* sqrt_2pi)\n \n \n # y = [part1* (my_e **(-0.5*(((x - lst_mean)/lst_sd)**2))) for x in lst]\n y = [(my_e **(((-0.5*(x**2)))))/sqrt_2pi for x in lst]\n return y\n\n\n##Second attempt\nx2 = [random.uniform(0.0,100.0) for x in range(20) ]\nrand_vals = [random.uniform(-1.0,1.0) for x in range(20) ]\nrand_vals_mean = sum(rand_vals)/20\nrand_vals_sd = find_sd(rand_vals, rand_vals_mean)\n\nrand_normal_distribute = find_normal_dist(rand_vals,rand_vals_mean,rand_vals_sd)\nprint(\"rand_normal_distribute: \",np.round(rand_normal_distribute,2))\n\ny2 = [(50*i)+ 22 +j for i,j in zip(x2,rand_normal_distribute) ]\n# print(\"y2: \", (np.round(y2, 2))\n# print(\"x2: \", (np.round(x2, 2))\nprint(\"y2: \", y2)\nprint(\"x2: \", x2)","repo_name":"Nic-py/linear_regression","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43365399914","text":"naylon = int(input())\npaint = int(input())\nr = int(input())\nhour = int(input())\n\nsumNaylon = (naylon + 2) * 1.5\nsumPaint = (paint + (paint * 0.1)) * 14.5\nsumR = r * 5.00\ntotalSum = sumNaylon + sumPaint + sumR + 0.4\ntotalSum = (totalSum + ((totalSum * 0.3)) * hour)\n\nprint(totalSum)","repo_name":"StoyanNakov/SoftUni","sub_path":"Programming Basics with Python - june 2022/First Steps in Coding - Exercise/06. Repainting/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27425073236","text":"def dfs(string):\n if len(string) == len(end):\n if string == end:\n return 1\n else:\n return 0\n\n if string[0] == 'B':\n string.reverse()\n del string[-1]\n dfs(string)\n string.append('B')\n string.reverse()\n\n if string[-1] == 'A':\n del string[-1]\n dfs(string)\n string.append('A')\n\nstart = list(input())\nend = list(input())\n\nprint(dfs(end))\n\n##틀림##","repo_name":"dlckdduq1107/coding_test","sub_path":"Solutions/1. Greedy/A_and_b_back_12919.py","file_name":"A_and_b_back_12919.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"15697119774","text":"import os\nimport sys\nimport time\nfrom datetime import datetime\n\n\nclass GithubArchiveConf:\n BOOKMARK_TABLE_NAME = \"bookmark-github\"\n BOOKMARK_TABLE_ID = 1\n STORAGE_FILE_PATH = \"github_archive/download/\"\n BUCKET_NAME = \"sai-ts-learn-tf\"\n BOOKMARK_ATTRIBUTES = {\n \"TABLE_ID\": [\"S\", \"HASH\"],\n \"TABLE_NAME\": [\"S\", \"RANGE\"],\n \"FILE_LOAD_TIMESTAMP\": [\"N\", \"ATTRIBUTE\"],\n \"LAST_EXTRACTED_FILE\": [\"S\", \"ATTRIBUTE\"],\n }\n URL_PREFIX = \"https://data.gharchive.org/\"\n INITIAL_FILE_NAME = os.environ.get(\"INITIAL_FILE_NAME\")\n\n @staticmethod\n def get_key_schema() -> list:\n key_schema = list()\n for key, value in GithubArchiveConf.BOOKMARK_ATTRIBUTES.items():\n if value[1] in [\"HASH\", \"RANGE\"]:\n schema = {\"AttributeName\": key, \"KeyType\": value[1]}\n key_schema.append(schema)\n return key_schema\n\n @staticmethod\n def get_key_attributes() -> list:\n key_attributes = list()\n for key, value in GithubArchiveConf.BOOKMARK_ATTRIBUTES.items():\n if value[1] in [\"HASH\", \"RANGE\"]:\n attribute = {\"AttributeName\": key, \"AttributeType\": value[0]}\n key_attributes.append(attribute)\n return key_attributes\n\n @staticmethod\n def get_filter_expression() -> dict:\n filter_expressions = dict()\n for key, value in GithubArchiveConf.BOOKMARK_ATTRIBUTES.items():\n if key == \"TABLE_ID\":\n filter_expressions[key] = {\n value[0]: str(GithubArchiveConf.BOOKMARK_TABLE_ID)\n }\n elif key == \"TABLE_NAME\":\n filter_expressions[key] = {\n value[0]: GithubArchiveConf.BOOKMARK_TABLE_NAME\n }\n else:\n pass\n return filter_expressions\n\n @staticmethod\n def entry_item(file_type=\"first\", file_name=\"\") -> dict:\n entry_item = dict()\n for key, value in GithubArchiveConf.BOOKMARK_ATTRIBUTES.items():\n if key == \"TABLE_ID\":\n entry_item[key] = {value[0]: str(GithubArchiveConf.BOOKMARK_TABLE_ID)}\n elif key == \"TABLE_NAME\":\n entry_item[key] = {value[0]: GithubArchiveConf.BOOKMARK_TABLE_NAME}\n elif key == \"FILE_LOAD_TIMESTAMP\":\n entry_item[key] = {value[0]: str(GithubArchiveConf.get_epoch_time())}\n elif key == \"LAST_EXTRACTED_FILE\":\n if file_type == \"first\":\n entry_item[key] = {\n value[0]: GithubArchiveConf.URL_PREFIX\n + GithubArchiveConf.INITIAL_FILE_NAME\n }\n else:\n entry_item[key] = {value[0]: file_name}\n\n else:\n print(\"Add new entries to BOOKMARK_ATTRIBUTES dictionary \")\n sys.exit(1)\n return entry_item\n\n @staticmethod\n def get_epoch_time():\n pattern = \"%Y-%m-%d %H:%M:%S\"\n ts = datetime.strftime(datetime.now(), pattern)\n return int(time.mktime(time.strptime(ts, pattern)))\n\n\nif __name__ == \"__main__\":\n conf = GithubArchiveConf()\n print(conf.get_key_schema())\n print(conf.get_key_attributes())\n print(conf.get_filter_expression())\n print(conf.get_epoch_time())\n print(conf.entry_item())\n","repo_name":"saiprashanthts1995/serverless_pipelines_using_lambda","sub_path":"github_archive/conf/github_archive_conf.py","file_name":"github_archive_conf.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9701244277","text":"def dfs(s):\n cnt=0\n \n for i in range(1,n+1):\n if brr[i]==0 and arr[s][i]==1 and i!=x and brr[y]==0:\n brr[i]=1\n cnt+=1\n if i==y:\n return cnt\n cnt+=dfs(i)\n if cnt == 0:\n return -1 \n return cnt;\n \n\n\nn = int(input())\nx,y=map(int,input().split())\n\narr =[[0 for _ in range(n+1)] for _ in range(n+1)]\nbrr =[0 for _ in range(n+1)]\nm = int(input())\n\nfor _ in range(m):\n a,b=map(int,input().split())\n arr[a][b]=1\n arr[b][a]=1\nprint(dfs(x))","repo_name":"qkrtndh/coding_test_python","sub_path":"백준/2644/2644.py","file_name":"2644.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73253512486","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n\n # Yarns\n path('yarns', views.yarns, name='yarns'),\n\n path('yarns/',\n views.yarn_detail, name='yarn_detail'),\n\n path('yarns//edit', views.edit_yarn,\n name='edit_yarn'),\n\n path('yarns/add', views.add_yarn, name='add_yarn'),\n\n path('yarns//delete', views.delete_yarn,\n name='delete_yarn'),\n path('yarns/add/manufacturer', views.add_manufacturer_modal, name='add_manufacturer_modal'),\n path('yarns/add/material', views.add_material_modal, name='add_material_modal'),\n\n\n # Colors\n path('yarns//colors/',\n views.color_detail,\n name='color_detail'),\n path('yarns//colors/add', views.add_color,\n name='add_color'),\n path('yarns//colors//edit',\n views.edit_color, name='edit_color'),\n path('yarns//colors//delete',\n views.delete_color, name='delete_color'),\n path('yarns/colors/add/yarnshop', views.add_yarnshop_modal, name='add_yarnshop_modal'),\n\n\n # Projectideas\n path('projectideas', views.projectideas, name='projectideas'),\n path('projectideas/add', views.add_projectidea,\n name='add_projectidea'),\n path('projectideas/',\n views.projectidea_detail,\n name='projectidea_detail'),\n path('projectideas//edit',\n views.edit_projectidea,\n name='edit_projectidea'),\n path('projectideas//delete',\n views.delete_projectidea, name='delete_projectidea'),\n path('ajax/load-colors/', views.load_colors, name='ajax_load_colors'),\n path('projectideas//finished', views.projectidea_to_finishedobject,\n name='projectidea_to_finishedobject'),\n path('projectideas/add/yarn', views.add_yarn_modal, name='add_yarn_modal'),\n path('projectideas/add/color', views.add_color_modal, name='add_color_modal'),\n path('projectideas/add/yarnshop', views.add_yarnshop_collapse, name='add_yarnshop_collapse'),\n\n # finished objects\n path('finishedobjects', views.finishedobjects, name='finishedobjects'),\n path('finishedobjects/add', views.add_fo, name='add_fo'),\n path('finishedobjects/',\n views.finishedobject_detail, name='finishedobject_detail'),\n path('finishedobjects//delete',\n views.delete_finishedobject, name='delete_finishedobject'),\n path('finishedobjects//edit',\n views.edit_fo, name='edit_finishedobject'),\n path('finishedobjects/add/projectidea', views.add_projectidea_modal, name='add_projectidea_modal'),\n\n\n # manufacturers\n path('manufacturers', views.manufacturers, name='manufacturers'),\n path('manufacturers/add', views.add_manufacturer, name='add_manufacturer'),\n path('manufacturers//delete', views.delete_manufacturer, name='delete_manufacturer'),\n\n\n\n # yarnshops\n path('yarnshops', views.yarnshops, name='yarnshops'),\n path('yarnshops/add', views.add_yarnshop, name='add_yarnshop'),\n path('yarnshops//delete', views.delete_yarnshop, name='delete_yarnshop'),\n\n\n # swatches\n path('swatches', views.swatches, name='swatches'),\n path('swatches/add', views.add_swatch, name='add_swatch'),\n path('swatches//delete', views.delete_swatch, name='delete_swatch'),\n\n # materials\n path('materials', views.materials, name='materials'),\n path('materials/add', views.add_material, name='add_material'),\n path('materials//delete', views.delete_material, name='delete_material'),\n\n\n ]\n\n","repo_name":"lhannig/wooly-mammoth","sub_path":"WoolDB/backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18503809201","text":"class Duck:\r\n def sound(self):\r\n print('Duck:quack quack')\r\nclass Cat:\r\n def sound(self):\r\n print('Cat:meow meow')\r\n\r\nclass Dog:\r\n def talk(self):\r\n print('Dog:bark bark')\r\n\r\n\r\ndef Myfunction(o):\r\n if hasattr(o,'sound'):\r\n o.sound()\r\n if hasattr(o,'talk'):\r\n o.talk()\r\n\r\nd=Duck()\r\nMyfunction(d)\r\n\r\nc=Cat()\r\nMyfunction(c)\r\nprint()\r\nD=Dog()\r\nMyfunction(D)","repo_name":"akashpagi/python-practice","sub_path":"OOP/POLYMORPHIISM/strong_typing.py","file_name":"strong_typing.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8467852376","text":"\n#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : test_hmac.py\n@Time : 2023/08/04 14:07:47\n@Author : yxh \n@Version : 1.0\n@Contact : xianhe_yan@sina.com\n'''\n\n\n\nimport base64\nimport hmac\nimport hashlib\n\n\ndef generate_message(ak, sk, url):\n signing_key = bytes(sk, 'utf-8')\n message = \"POST\\n*/*\\napplication/json\\nx-ca-key:%s\\n%s\" % (ak,url)\n signature = hmac.new(signing_key, msg=bytes(message, 'utf-8'), digestmod=hashlib.sha256).digest()\n encoded_signature = base64.b64encode(signature).decode('utf-8')\n return encoded_signature\n\n\n\nak = \"23977799\"\nsk = 'onihBfjbZfkgUNnsnKbD'\nurl = \"/artemis/api/v1/oauth/token\"\nsignature = generate_message(ak, sk,url)\nprint(signature)\n\n\nimport random\nimport string\n\ndef generate_transaction_code():\n characters = string.ascii_uppercase + string.digits # 使用大写字母和数字\n transaction_code = ''.join(random.choices(characters, k=12)) # 从字符集中随机选择12个字符\n return transaction_code\n\n# 生成交易码示例\ntransaction_code = generate_transaction_code()\nprint(transaction_code)\n\n\nimport hashlib\nimport hmac\nimport base64\nimport os,uuid\n\n\ndef getUuid1():\n return (str(uuid.uuid1()).replace(\"-\", \"\"))\n\ndef generate_ak_sk():\n # 生成随机的 AK 和 SK\n ak = os.urandom(16).hex().upper()\n sk = os.urandom(32).hex()\n return ak, sk\n\ndef sign_request(sk, data):\n # 使用 SK 对数据进行签名\n signature = hmac.new(bytes.fromhex(sk), data.encode(), hashlib.sha256).digest()\n # 将签名进行base64编码\n signed_request = base64.b64encode(signature).decode()\n return signed_request\n\n# 生成 AK 和 SK 示例\nak, sk = generate_ak_sk()\nprint(\"AK:\", ak)\nprint(\"SK:\", sk)\n\n# 使用 SK 对数据进行签名示例\ndata = \"example-data\"\nsigned_request = sign_request(sk, data)\nprint(\"Signed Request:\", signed_request)","repo_name":"yanxianhe/openapi","sub_path":"test/test_hmac.py","file_name":"test_hmac.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18910555938","text":"''' Connection to SQL Server database '''\n\nimport pyodbc, logging, os\nfrom pyInovEval.logger import logger\nfrom pyInovEval.config.config import Config\n\n\n# Build pyodbc connection string\n_pyodbc_conn_str = \\\n f\"DRIVER={Config.get('dbDriver')};\" \\\n + f\"SERVER={Config.get('dbHost')};\" \\\n + f\"PORT={Config.get('dbPort')};\" \\\n + f\"DATABASE={Config.get('dbName')};\" \\\n + \"trusted_connection=yes\"\n\n\nclass Connection():\n \"\"\" Connect to SQL Server, with clean up \"\"\"\n\n def __enter__(self):\n self.conn = pyodbc.connect(_pyodbc_conn_str)\n self.conn.autocommit = True\n self.cursor = self.conn.cursor()\n return self\n\n def execute(self, command):\n self.cursor.execute(command)\n \n def __exit__(self, exc_type, exc_val, exc_tb):\n self.conn.close()\n\n","repo_name":"cwillhu/evaldb_etl","sub_path":"evaldb/evaldb/mssql.py","file_name":"mssql.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34747718520","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('/', views.ChatView.as_view({'get': 'retrieve'}),\n name='get-chat-view'),\n path('', views.ChatView.as_view({'get': 'list', 'post': 'create'}),\n name='chats-view'),\n path('/participants/', views.ChatParticipantsView.as_view(),\n name='chat-participants-view'),\n path('/messages/', views.MessageView.as_view({'get': 'list'}),\n name='chat-messages-view'),\n path('messages//', views.MessageView.as_view({'get': 'retrieve', 'put': 'update'}),\n name='messages-view'),\n path('messages/', views.MessageView.as_view({'post': 'create'}),\n name='create-message-view')\n]\n","repo_name":"busovilya/MessengerAPI","sub_path":"chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2062346278","text":"import tkinter as tk\nfrom tkinter import *\n\n\ndef create_label(frame, text=\"\", type=\"normal\", method=\"\", row=0, column=0, color=\"black\"):\n\n if(type == \"label\"):\n label = Label(frame, text=text ,fg=color, bg= \"#F4F4F4\", font='Helvetica 13 bold')\n if (method==\"pack\"): label.pack(anchor='w')\n else: label.grid(row=row, column=column, padx='5', pady='5', sticky='ew')\n\n elif(type == \"normal\"):\n label = Label(frame, text=text ,fg=color, font='Helvetica 13', anchor='w',justify='left')\n if (method==\"pack\"): label.pack(anchor='w')\n else: label.grid(row=row, column=column, padx='2', pady='2', sticky='ew')\n\n elif(type == \"bold\"):\n label = Label(frame, text=text ,fg=color, font='Helvetica 13 bold',anchor='w', justify='left')\n if (method==\"pack\"): label.pack(anchor='w', fill=\"both\")\n else: label.grid(row=row, column=column, padx='2', pady='2', sticky='ew')\n\n elif(type == \"entry\"):\n my_text = StringVar()\n my_text.set(text)\n entry = tk.Entry(frame,state=\"readonly\",fg=color, bd=0, highlightthickness=0, textvariable = my_text)\n if (method==\"pack\"): entry.pack(anchor='w', fill=\"both\" ,pady='0')\n else: entry.grid(row=row, column=column, padx='2', pady='2', sticky='w')\n \n\n elif(type==\"heading\"):\n label = Label(frame, pady='5',text=text,fg=color, bg=\"#F4F4F4\", font='Helvetica 14 bold',anchor='w')\n if (method==\"pack\"): label.pack(fill='x',pady=(15,5))\n else: label.grid(row=row, column=column, padx='5', pady='5', sticky='ew')\n\n else:\n pass\n\n\n\ndef format_number(number, precision=4):\n return \"{:.{}f}\".format( number, precision )","repo_name":"AndreZenner/staircase-procedure","sub_path":"StaircaseProcedure/Assets/StaircaseProcedure/PythonTools/DataAnalysis/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"5283376575","text":"import streamlit as st\nimport pandas as pd\nfrom sklearn import datasets\nfrom sklearn.ensemble import RandomForestClassifier\n\n# **text** bold\nst.write(\"\"\"\n# Simple Iris Flower Prediction App\n\nThis app predicts the **Iris flower** type!\n\"\"\")\n\nst.sidebar.header('User Input Parameters')\n\n# sidebar 4개 슬라이더 배치 , 슬라이더 값(시작 값, 끝 값, 현재 값)\ndef user_input_features():\n sepal_length = st.sidebar.slider('Sepal length', 4.3, 7.9, 5.4)\n sepal_width = st.sidebar.slider('Sepal width', 2.0, 4.4, 3.4)\n petal_length = st.sidebar.slider('Petal length', 1.0, 6.9, 1.3)\n petal_width = st.sidebar.slider('Petal width', 0.1, 2.5, 0.2)\n data = {'sepal_length': sepal_length,\n 'sepal_width': sepal_width,\n 'petal_length': petal_length,\n 'petal_width': petal_width}\n features = pd.DataFrame(data, index=[0])\n return features\n\ndf = user_input_features()\n\nst.subheader('User Input parameters')\nst.write(df)\n\niris = datasets.load_iris()\nX = iris.data\nY = iris.target\n\nclf = RandomForestClassifier() # 랜덤포레스트 앙상블 분류기\nclf.fit(X, Y)\n\nprediction = clf.predict(df) # 확률 예측 값\nprediction_proba = clf.predict_proba(df)\n\nst.subheader('Class labels and their corresponding index number')\nst.write(iris.target_names)\n\nst.subheader('Prediction')\nst.write(iris.target_names[prediction])\n#st.write(prediction)\n\nst.subheader('Prediction Probability')\nst.write(prediction_proba)\n","repo_name":"Kim-Hyerin/pdm06","sub_path":"py-streamlit/code/iris-ml-app.py","file_name":"iris-ml-app.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1699215113","text":"bl_info = {\n \"name\": \"Export golf hole data\",\n \"author\": \"Bald Guy\",\n \"version\": (2023, 3, 4),\n \"blender\": (2, 80, 0),\n \"location\": \"File > Export > Golf Hole\",\n \"description\": \"Export position and rotation info of selected objects\",\n \"warning\": \"\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Import-Export\"}\n\nimport os, math\nfrom pathlib import Path\nimport bpy\nimport bpy_extras.io_utils\nimport mathutils\n\ndef vecMultiply(vec, vec2):\n temp = []\n\n for x, i in enumerate(vec):\n temp.append(i * vec2[x])\n\n return mathutils.Vector(temp)\n\n\ndef WriteProperty(file, propName, location):\n file.write(\" %s = %f,%f,%f\\n\\n\" % (propName, location[0], location[2], -location[1]))\n\ndef WriteAIPath(file, path):\n file.write(\"\\n path ai\\n {\\n\")\n for p in path.data.splines.active.points:\n worldP = path.matrix_world @ p.co\n file.write(\" point = %f,%f,%f\\n\" % (worldP.x, worldP.z, -worldP.y))\n file.write(\"\\n }\\n\")\n\n\ndef WritePath(file, path):\n file.write(\"\\n path\\n {\\n\")\n for p in path.data.splines.active.points:\n worldP = path.matrix_world @ p.co\n file.write(\" point = %f,%f,%f\\n\" % (worldP.x, worldP.z, -worldP.y))\n\n if path.get('loop') is not None:\n if path['loop'] == 0:\n file.write(\"\\n loop = false\")\n else:\n file.write(\"\\n loop = true\")\n else:\n file.write(\"\\n loop = false\")\n\n\n if path.get('delay') is not None:\n file.write(\"\\n delay = %f\" % path['delay'])\n else:\n file.write(\"\\n delay = 4.0\")\n\n\n if path.get('speed') is not None:\n file.write(\"\\n speed = %f\" % path['speed'])\n else:\n file.write(\"\\n speed = 6.0\") \n\n file.write(\"\\n }\\n\")\n\n\ndef WriteSpeaker(file, speaker):\n if speaker.get('name') is not None:\n file.write(\" emitter = \\\"%s\\\"\\n\" % speaker['name'])\n\n if speaker.parent is None:\n location = speaker.location\n file.write(\" position = %f,%f,%f\\n\" % (location[0], location[2], -location[1]))\n\n\ndef WriteSpeakerSolo(file, speaker):\n file.write(\" speaker\\n {\\n\")\n WriteSpeaker(file, speaker)\n file.write(\" }\\n\\n\")\n\n\ndef WriteProp(file, modelName, location, rotation, scale, ob):\n file.write(\" prop\\n {\\n\")\n file.write(\" model = \\\"%s\\\"\\n\" % modelName)\n file.write(\" position = %f,%f,%f\\n\" % (location[0], location[2], -location[1]))\n file.write(\" rotation = %f\\n\" % (rotation[2] * (180.0 / 3.141)))\n file.write(\" scale = %f,%f,%f\\n\" % (scale[0], scale[2], scale[1]))\n\n\n if ob.parent is not None and ob.parent.type == 'CURVE':\n WritePath(file, ob.parent)\n\n for child in ob.children:\n if child.type == 'SPEAKER':\n WriteSpeaker(file, child)\n elif child.type == 'EMPTY':\n if child.get('type') is not None and child['type'] == 1:\n if child.get('path') is not None:\n file.write(\" particles = \\\"%s\\\"\\n\" % child['path'])\n else:\n file.write(\" particles = \\\"path_is_missing\\\"\\n\")\n\n\n file.write(\" }\\n\\n\")\n\n\ndef WriteCrowd(file, location, rotation, ob):\n file.write(\" crowd\\n {\\n\")\n file.write(\" position = %f,%f,%f\\n\" % (location[0], location[2], -location[1]))\n file.write(\" rotation = %f\\n\" % (rotation[2] * (180.0 / 3.141)))\n\n\n if ob.get('look_at') is not None:\n file.write(\" lookat = %f,%f,%f\\n\" % (ob['look_at'][0], ob['look_at'][2], -ob['look_at'][1]))\n\n\n if ob.parent is not None and ob.parent.type == 'CURVE':\n WritePath(file, ob.parent)\n\n file.write(\" }\\n\\n\")\n\n\ndef WriteParticles(file, path, location):\n file.write(\" particles\\n {\\n\")\n file.write(\" path = \\\"%s\\\"\\n\" % path)\n file.write(\" position = %f,%f,%f\\n\" % (location[0], location[2], -location[1]))\n file.write(\" }\\n\\n\")\n\n\ndef showMessageBox(message = \"\", title = \"Message Box\", icon = 'INFO'):\n\n def draw(self, context):\n self.layout.label(text = message)\n\n bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)\n\n\nclass ExportInfo(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):\n '''Export object position and rotation info'''\n bl_idname = \"export.golf\"\n bl_label = 'Export Hole Info'\n filename_ext = \".hole\"\n\n def execute(self, context):\n file = open(self.properties.filepath, 'w')\n\n scene = bpy.context.scene\n\n file.write(\"hole %s\\n{\\n\" % Path(self.properties.filepath).stem)\n\n if scene.get('map_path') is not None:\n file.write(\" map=\\\"%s/%s.png\\\"\\n\" % (scene['map_path'], Path(self.properties.filepath).stem))\n else:\n file.write(\" map=\\\"assets/golf/courses/course_0/%s.png\\\"\\n\" % Path(self.properties.filepath).stem)\n\n if scene.get('model_path') is not None:\n file.write(\" model=\\\"%s\\\"\\n\" % scene['model_path'])\n else:\n file.write(\" model=\\\"assets/golf/models/course_0/%s.cmt\\\"\\n\" % Path(self.properties.filepath).stem)\n \n if scene.get('par') is not None:\n file.write(\" par = %d\\n\\n\" % scene['par'])\n else:\n file.write(\" par = 4\\n\\n\")\n\n teeWritten = False\n pinWritten = False\n targetWritten = False\n\n for ob in bpy.context.selected_objects:\n\n if ob.type == 'MESH' or ob.type == 'EMPTY' or ob.type == 'SPEAKER' or ob.type == 'CURVE':\n\n modelName = ob.name\n if ob.get('model_path') is not None:\n modelName = ob['model_path']\n\n worldLocation = ob.location\n worldRotation = ob.rotation_euler\n worldScale = ob.scale\n\n if ob.parent is not None:\n if ob.parent.type == 'MESH' or ob.parent.type == 'ARMATURE':\n worldLocation = ob.matrix_world @ ob.location\n worldRotation = ob.matrix_world.to_euler('XYZ')\n worldScale = vecMultiply(ob.parent.scale, ob.scale)\n\n\n if \"crowd\" in modelName.lower() and ob.type == 'MESH':\n WriteCrowd(file, worldLocation, worldRotation, ob)\n elif \"pin\" in modelName.lower():\n if pinWritten == False:\n WriteProperty(file, \"pin\", worldLocation)\n pinWritten = True\n else:\n self.report({'WARNING'}, \"Multiple pins selected\")\n elif \"target\" in modelName.lower():\n if targetWritten == False:\n WriteProperty(file, \"target\", worldLocation)\n targetWritten = True\n else:\n self.report({'WARNING'}, \"Multiple targets selected\")\n elif \"tee\" in modelName.lower():\n if teeWritten == False:\n WriteProperty(file, \"tee\", worldLocation)\n teeWritten = True\n else:\n self.report({'WARNING'}, \"Multiple tees selected\")\n elif ob.type == 'CURVE' and \"ai\" in modelName.lower():\n WriteAIPath(file, ob)\n\n else:\n if ob.type == 'MESH':\n WriteProp(file, modelName, worldLocation, worldRotation, worldScale, ob)\n elif ob.type == 'EMPTY':\n if ob.get('type') is not None:\n if ob['type'] == 1 and ob.parent is None:\n # is a particle emitter not parented to a prop\n if ob.get('path') is not None:\n WriteParticles(file, ob['path'], worldLocation)\n else:\n WriteParticles(file, \"path_missing\", worldLocation)\n elif ob.type == 'SPEAKER' and ob.parent is None:\n WriteSpeakerSolo(file, ob)\n\n\n file.write(\"}\")\n file.close()\n\n\n if not pinWritten or not targetWritten or not teeWritten:\n showMessageBox(\"Pin or other Tee data was missing from selection\", \"Warning\", 'ERROR')\n\n\n return {'FINISHED'}\n\n\ndef menu_func(self, context):\n self.layout.operator(ExportInfo.bl_idname, text=\"Golf Hole Data (.hole)\")\n\n\ndef register():\n bpy.utils.register_class(ExportInfo)\n bpy.types.TOPBAR_MT_file_export.append(menu_func)\n\ndef unregister():\n bpy.utils.unregister_class(ExportInfo)\n bpy.types.TOPBAR_MT_file_export.remove(menu_func)\n","repo_name":"fallahn/crogine","sub_path":"samples/golf/mod_kit/prop-export.py","file_name":"prop-export.py","file_ext":"py","file_size_in_byte":8781,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"52"} +{"seq_id":"17119704755","text":"from utils.header import *\nfrom utils.segregation import compute_school_segregation, allocate_students_to_blocks\n\n\ndef output_school_file_for_assignment(\n input_dir=\"data/derived_data/{}/\",\n input_file=\"data/derived_data/{}/{}/full_blocks_data.csv\",\n schools_info_file=\"data/school_covariates/school_and_district_info_ccd_1920.csv\",\n output_file=\"data/derived_data/{}/{}/schools_file_for_assignment.csv\",\n zones_years=[\"2122\"],\n):\n\n for y in zones_years:\n curr_states = os.listdir(input_dir.format(y))\n # curr_states = [\"VA\"]\n df_schools_districts_metadata = pd.read_csv(\n schools_info_file, encoding=\"ISO-8859-1\", dtype=str\n )\n df_schools_metadata = df_schools_districts_metadata.groupby(\n \"NCESSCH\", as_index=False\n ).agg({\"SCH_NAME\": \"first\", \"LEA_NAME\": \"first\"})\n\n for state in curr_states:\n print(y, state)\n\n # Aggregate school-level values\n df = pd.read_csv(\n input_file.format(y, state), encoding=\"ISO-8859-1\", dtype=str\n ).fillna(0)\n df_g = (\n df.groupby([\"ncessch\"])\n .agg(\n {\n \"block_id\": \"count\",\n \"leaid\": \"first\",\n \"totenrl\": \"first\",\n \"perwht\": \"first\",\n \"pernam\": \"first\",\n \"perasn\": \"first\",\n \"perhsp\": \"first\",\n \"perblk\": \"first\",\n \"perfrl\": \"first\",\n \"perell\": \"first\",\n \"openEnroll\": \"first\",\n \"lat\": \"first\",\n \"long\": \"first\",\n }\n )\n .rename(\n columns={\"block_id\": \"num_blocks\", \"totenrl\": \"total_enrollment\"}\n )\n .reset_index()\n )\n\n df_g = pd.merge(\n df_g,\n df_schools_metadata,\n left_on=\"ncessch\",\n right_on=\"NCESSCH\",\n how=\"inner\",\n )\n\n # Convert relevant columns to numeric\n df_g[\"total_enrollment\"] = pd.to_numeric(df_g[\"total_enrollment\"])\n df_g[\"perwht\"] = pd.to_numeric(df_g[\"perwht\"])\n df_g[\"pernam\"] = pd.to_numeric(df_g[\"pernam\"])\n df_g[\"perasn\"] = pd.to_numeric(df_g[\"perasn\"])\n df_g[\"perhsp\"] = pd.to_numeric(df_g[\"perhsp\"])\n df_g[\"perblk\"] = pd.to_numeric(df_g[\"perblk\"])\n df_g[\"perfrl\"] = pd.to_numeric(df_g[\"perfrl\"])\n df_g[\"perell\"] = pd.to_numeric(df_g[\"perell\"])\n\n df_g[\"total_enrollment\"] = np.maximum(np.round(df_g[\"total_enrollment\"]), 0)\n df_g[\"total_white\"] = np.maximum(\n df_g[\"total_enrollment\"] * df_g[\"perwht\"], 0\n )\n df_g[\"total_native\"] = np.maximum(\n df_g[\"total_enrollment\"] * df_g[\"pernam\"], 0\n )\n df_g[\"total_asian\"] = np.maximum(\n df_g[\"total_enrollment\"] * df_g[\"perasn\"], 0\n )\n df_g[\"total_hispanic\"] = np.maximum(\n df_g[\"total_enrollment\"] * df_g[\"perhsp\"], 0\n )\n df_g[\"total_black\"] = np.maximum(\n df_g[\"total_enrollment\"] * df_g[\"perblk\"], 0\n )\n df_g[\"total_frl\"] = np.maximum(df_g[\"total_enrollment\"] * df_g[\"perfrl\"], 0)\n df_g[\"total_ell\"] = np.maximum(df_g[\"total_enrollment\"] * df_g[\"perell\"], 0)\n\n # # Filter out schools with 0 total enrollment\n df_g = df_g[df_g[\"total_enrollment\"] > 0].reset_index()\n\n # Compute district-level values\n df_district = (\n df_g.groupby([\"leaid\"])\n .agg(\n {\n \"ncessch\": \"count\",\n \"total_enrollment\": \"sum\",\n \"total_white\": \"sum\",\n \"total_native\": \"sum\",\n \"total_asian\": \"sum\",\n \"total_hispanic\": \"sum\",\n \"total_black\": \"sum\",\n \"total_frl\": \"sum\",\n \"total_ell\": \"sum\",\n }\n )\n .rename(columns={\"ncessch\": \"num_schools\"})\n .reset_index()\n .sort_values(by=\"total_enrollment\", ascending=False)\n )\n\n df_district[\"perwht\"] = (\n df_district[\"total_white\"] / df_district[\"total_enrollment\"]\n )\n df_district[\"pernam\"] = (\n df_district[\"total_native\"] / df_district[\"total_enrollment\"]\n )\n df_district[\"perasn\"] = (\n df_district[\"total_asian\"] / df_district[\"total_enrollment\"]\n )\n df_district[\"perhsp\"] = (\n df_district[\"total_hispanic\"] / df_district[\"total_enrollment\"]\n )\n df_district[\"perblk\"] = (\n df_district[\"total_black\"] / df_district[\"total_enrollment\"]\n )\n df_district[\"perfrl\"] = (\n df_district[\"total_frl\"] / df_district[\"total_enrollment\"]\n )\n df_district[\"perell\"] = (\n df_district[\"total_ell\"] / df_district[\"total_enrollment\"]\n )\n\n data_to_merge = {\n \"ncessch\": [],\n \"seg_index_perblk\": [],\n \"seg_index_pernam\": [],\n \"seg_index_perasn\": [],\n \"seg_index_perhsp\": [],\n \"seg_index_perfrl\": [],\n \"seg_index_perell\": [],\n \"seg_index_perwht\": [],\n \"district_totenrl\": [],\n \"district_perwht\": [],\n \"district_perblk\": [],\n \"district_pernam\": [],\n \"district_perasn\": [],\n \"district_perhsp\": [],\n \"district_perfrl\": [],\n \"district_perell\": [],\n \"district_num_schools\": [],\n }\n\n # Compute segregation values per school\n for i in range(0, len(df_g)):\n\n school = df_g.iloc[i]\n district = df_district[df_district[\"leaid\"].isin([school[\"leaid\"]])]\n data_to_merge[\"ncessch\"].append(school[\"ncessch\"])\n data_to_merge[\"district_totenrl\"].append(\n float(district[\"total_enrollment\"])\n )\n data_to_merge[\"district_perwht\"].append(float(district[\"perwht\"]))\n data_to_merge[\"district_perblk\"].append(float(district[\"perblk\"]))\n data_to_merge[\"district_pernam\"].append(float(district[\"pernam\"]))\n data_to_merge[\"district_perhsp\"].append(float(district[\"perhsp\"]))\n data_to_merge[\"district_perasn\"].append(float(district[\"perasn\"]))\n data_to_merge[\"district_perfrl\"].append(float(district[\"perfrl\"]))\n data_to_merge[\"district_perell\"].append(float(district[\"perell\"]))\n data_to_merge[\"district_num_schools\"].append(\n float(district[\"num_schools\"])\n )\n\n seg_indices = compute_school_segregation(school, district)\n data_to_merge[\"seg_index_perblk\"].append(seg_indices[\"perblk\"])\n data_to_merge[\"seg_index_pernam\"].append(seg_indices[\"pernam\"])\n data_to_merge[\"seg_index_perasn\"].append(seg_indices[\"perasn\"])\n data_to_merge[\"seg_index_perhsp\"].append(seg_indices[\"perhsp\"])\n data_to_merge[\"seg_index_perfrl\"].append(seg_indices[\"perfrl\"])\n data_to_merge[\"seg_index_perell\"].append(seg_indices[\"perell\"])\n data_to_merge[\"seg_index_perwht\"].append(seg_indices[\"perwht\"])\n\n df_merge = pd.DataFrame(data=data_to_merge)\n df_g = pd.merge(df_g, df_merge, how=\"left\", on=\"ncessch\").reset_index()\n # df_g = df_g.drop(columns=[\"level_0\", \"index\"])\n df_g = df_g.drop(columns=[\"index\"])\n df_g.to_csv(output_file.format(y, state), index=False)\n\n\ndef output_block_file_for_assignment(\n state,\n y,\n input_file=\"data/derived_data/{}/{}/full_blocks_data.csv\",\n input_schools_file=\"data/derived_data/{}/{}/schools_file_for_assignment.csv\",\n output_file=\"data/derived_data/{}/{}/blocks_file_for_assignment.csv\",\n race_cat_keys={\n \"perwht\": \"num_white_to_school\",\n \"perblk\": \"num_black_to_school\",\n \"perasn\": \"num_asian_to_school\",\n \"pernam\": \"num_native_to_school\",\n },\n hisp_cat_keys={\n \"perhsp\": \"num_hispanic_to_school\",\n },\n ell_cat_keys={\n \"perell\": \"num_ell_to_school\",\n },\n frl_cat_keys={\"perfrl\": \"num_frl_to_school\"},\n total_cat_keys={\"pertotal\": \"num_total_to_school\"},\n):\n\n print(state)\n df_blocks = pd.read_csv(\n input_file.format(y, state), encoding=\"ISO-8859-1\", dtype=str\n ).fillna(0)\n df_schools = pd.read_csv(\n input_schools_file.format(y, state), encoding=\"ISO-8859-1\", dtype=str\n ).fillna(0)\n\n # Add this in to make the allocation code easier / more general\n df_schools[\"pertotal\"] = [1 for j in range(0, len(df_schools))]\n\n block_students_by_cat = {}\n\n for i in range(0, len(df_schools)):\n curr_school = df_schools.iloc[i]\n\n curr_blocks = df_blocks[\n df_blocks[\"ncessch\"].isin([curr_school[\"ncessch\"]])\n ].reset_index(drop=True)\n\n # Testing\n # curr_school = df_schools[\n # df_schools[\"ncessch\"].isin([\"510126000483\"])\n # ].reset_index(drop=True)\n # curr_blocks = df_blocks[\n # df_blocks[\"ncessch\"].isin([\"510126000483\"])\n # ].reset_index(drop=True)\n\n all_cat_keys = [\n race_cat_keys,\n hisp_cat_keys,\n ell_cat_keys,\n frl_cat_keys,\n total_cat_keys,\n ]\n blocks_for_curr_school = allocate_students_to_blocks(\n curr_school, curr_blocks, all_cat_keys\n )\n block_students_by_cat.update(blocks_for_curr_school)\n\n # Check to make sure the sum of students per category from each block is always <= the school's total enrollment\n for keypair in all_cat_keys:\n for val in keypair.values():\n cat_total_to_school = 0\n school_total = 0\n for b in blocks_for_curr_school:\n cat_total_to_school += blocks_for_curr_school[b][val]\n school_total += blocks_for_curr_school[b][\"num_total_to_school\"]\n assert cat_total_to_school <= school_total\n\n # Initialize dict and create dataframe\n data_allocations = {}\n for cats in all_cat_keys:\n data_allocations.update({k: [] for k in list(cats.values())})\n data_allocations[\"block_id\"] = []\n\n for b in block_students_by_cat:\n data_allocations[\"block_id\"].append(b)\n for cats in all_cat_keys:\n for k in list(cats.values()):\n data_allocations[k].append(block_students_by_cat[b][k])\n\n df_allocations = pd.DataFrame(data=data_allocations)\n df_blocks = df_blocks[\n df_blocks[\"block_id\"].isin(list(block_students_by_cat.keys()))\n ].reset_index(drop=True)\n df_blocks = pd.merge(df_blocks, df_allocations, how=\"left\", on=\"block_id\")\n\n keys_to_keep = []\n for cats in all_cat_keys:\n keys_to_keep.extend(deepcopy(list(cats.values())))\n\n keys_to_keep.extend(\n [\n \"block_id\",\n \"block_centroid_lat\",\n \"block_centroid_long\",\n \"ncessch\",\n \"distance_to_school\",\n \"travel_time_to_school\",\n \"directions_to_school\",\n ]\n )\n df_blocks = df_blocks[keys_to_keep]\n df_blocks.to_csv(output_file.format(y, state), index=False)\n\n\ndef output_block_file_for_assignment_parallel(\n input_dir=\"data/derived_data/{}/\",\n zones_years=[\"2122\"],\n processing_function=output_block_file_for_assignment,\n):\n\n N_THREADS = 10\n\n all_states_to_process = []\n for y in zones_years:\n for state in os.listdir(input_dir.format(y)):\n all_states_to_process.append((state, y))\n\n # all_states_to_process = [(\"SD\", \"2122\")]\n # processing_function(*all_states_to_process[0])\n print(\"Starting multiprocessing ...\")\n print(len(all_states_to_process))\n from multiprocessing import Pool\n\n p = Pool(N_THREADS)\n p.starmap(processing_function, all_states_to_process)\n\n p.terminate()\n p.join()\n\n\nif __name__ == \"__main__\":\n # output_school_file_for_assignment()\n output_block_file_for_assignment_parallel()\n","repo_name":"Plural-Connections/attendance-boundaries","sub_path":"utils/output_school_and_block_info.py","file_name":"output_school_and_block_info.py","file_ext":"py","file_size_in_byte":12739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5292277785","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom flask import Flask, request, jsonify\nfrom app import app\n\n\n@app.route('/search', methods=['POST'])\ndef search():\n req = request.get_json()\n\n f = open('search.txt', 'w')\n f.write(str(req['query']))\n f.close()\n return jsonify(req)\n","repo_name":"JobNest/Api","sub_path":"app/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9307210215","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib import admin\nfrom django.contrib.auth import get_user_model\n\nfrom modulos.django_google_maps import widgets as map_widgets\nfrom modulos.django_google_maps import fields as map_fields\n\nfrom modulos.db.models import Region, Iglesia\nfrom modulos.usuarios.models import Usuario\n\nfrom django.core.exceptions import ValidationError\n\nfrom django.core import urlresolvers\n\n\nclass RegionAdmin(admin.ModelAdmin):\n\n\tformfield_overrides = {\n\t map_fields.PathField: {'widget': map_widgets.GoogleMapsAddressPathWidget}, \n\t}\n\n\tdef formfield_for_foreignkey(self, db_field, request, **kwargs):\n\t\tif db_field.name == \"user\":\n\t\t\tUsuarios = get_user_model()\n\t\t\tkwargs[\"queryset\"] = Usuarios.objects.filter(user_padre=request.user.id)\n\t\treturn super(RegionAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n\tdef save_model(self, request, obj, form, change):\n\t\tif change:\n\t\t\tobj.save()\n\n\t\telif request.user.ambito == Usuario.NACIONAL: # valido que el superusuario no pueda crear regiones\n\t\t\tobj.save()\n\t\t\tUsuarios = get_user_model()\n\t\t\tUsuarios.objects.filter(id=obj.user_id).update(is_active=True) # activo el usuario solo cuando tiene una region asociada\n\t\telse:\n\t\t\tmsg = \"El usuario %s no puede crear Regiones, solo puede editarlas\" %(request.user)\n\t\t\tself.message_user(request, msg)\n\n\nclass IglesiaAdmin(admin.ModelAdmin):\n\n\tformfield_overrides = {\n\t map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget}, \n\t}\n\n\tlist_display = ('codigo', 'ciudad', 'sede', 'user', 'address')\t\n\tsearch_fields = ('codigo', 'sede', 'address')\n\tlist_filter = ('depto',)\n\n\tfieldsets = (\n\t\t( None, {'fields': ('codigo', ('sede', 'user'), 'region')} ),\n\t\t( 'Ubicación Geográfica', {'fields': ( 'address', ('geolocation', 'zoom'), ('ciudad', 'depto') ) } ),\n\t\t( 'Información Adicional', {'fields': ( 'proposito', ('tel', 'web') ) } ),\n\t)\n\n\treadonly_fields = ('region',)\n\n\n\n\tdef formfield_for_foreignkey(self, db_field, request, **kwargs):\n\t\tif db_field.name == \"user\":\n\t\t\tUsuarios = get_user_model()\n\t\t\tif request.user.is_superuser:\n\t\t\t\tkwargs[\"queryset\"] = Usuarios.objects.filter()\n\t\t\telse:\t\n\t\t\t\tkwargs[\"queryset\"] = Usuarios.objects.filter(user_padre=request.user.id)\n\t\treturn super(IglesiaAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)\n\n\n\n\tdef save_model(self, request, obj, form, change):\n\t\tif change:\n\t\t\tobj.save()\n\n\t\t\t\n\n\t\telif request.user.ambito == Usuario.REGIONAL:\n\t\t\tregion = Region.objects.get(user_id=request.user.id) # la region existe porque el usuario Regional no puede entrar si no tiene una region asociada\n\t\t\tobj.region = region\n\t\t\tobj.save()\n\n\t\t\tUsuarios = get_user_model()\n\t\t\tUsuarios.objects.filter(id=obj.user_id).update(is_active=True) # activo el usuario solo cuando tiene una IGLESIA asociada\n\n\t\t\t# Despues de crear la iglesia le digo a la region el numero de iglesias (activas) que tiene\t\t\t\n\t\t\tnumIglesias = Iglesia.objects.filter(region_id=region).count() # Obtengo la cantidad exacta de iglesias que \n\t\t\tregion.iglesias = numIglesias # += 1 con esto me evito la consulta anterior pero es menos seguro y no permite evaluar iglesas desactivadas\n\t\t\tregion.save(update_fields=['iglesias'])\n\t\t\t#print 'Region: %s tiene %s iglesias' %(region.nombre, numIglesias)\n\n\t# Limitar iglesias que puede ver el usuario\n\tdef queryset(self, request): \n\t\tqs = super(IglesiaAdmin, self).queryset(request) #pido todas las iglesias\n\t\tif request.user.is_superuser: # si el usuario es el superadmin\n\t\t\treturn qs # le doy todo\n\t\ttry:\n\t\t\tregion = Region.objects.get(user_id=request.user.id) # obtengo la region asociada al usuario\n\t\texcept Region.DoesNotExist:\n\t\t\treturn qs.filter(region_id=0)#super(IglesiaAdmin, self)\n\t\telse:\n\t\t\treturn qs.filter(region_id=region) # le doy al usuario solo las iglesias hijas de su region asociada\n\nadmin.site.register(Region, RegionAdmin)\nadmin.site.register(Iglesia, IglesiaAdmin)","repo_name":"diegofer/alliance","sub_path":"modulos/db/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15595467367","text":"import argparse\n\nfrom tabulate import tabulate\n\nfrom april_vision.calibrations import calibrations\nfrom april_vision.detect_cameras import find_cameras\n\n\ndef main(args: argparse.Namespace) -> None:\n cameras = find_cameras(calibrations, include_uncalibrated=True)\n print(tabulate(cameras, headers=\"keys\"))\n\n\ndef create_subparser(subparsers: argparse._SubParsersAction) -> None:\n \"\"\"List out the available cameras connected to the system.\"\"\"\n parser = subparsers.add_parser(\n \"list_cameras\",\n description=(\n \"List out the available cameras connected to the system, \"\n \"this will also search your current directory for calibration files\"\n ),\n help=(\n \"List out the available cameras connected to the system, \"\n \"this will also search your current directory for calibration files\"\n ),\n )\n\n parser.set_defaults(func=main)\n","repo_name":"WillB97/april_vision","sub_path":"april_vision/cli/tools/list_cameras.py","file_name":"list_cameras.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"5814570877","text":"class Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n if len(intervals) == 0:\n return []\n intervals = sorted(intervals, key = lambda x: x[0])\n res = [intervals[0]]\n for n in intervals[1:]:\n if res[-1][1] >= n[0]:\n res[-1][1] = max(res[-1][1], n[1])\n else:\n res.append(n)\n return res\n","repo_name":"shaniavina/Leetcode_Python","sub_path":"56_merge_intervals.py","file_name":"56_merge_intervals.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38143916238","text":"from cards import *\nfrom player import ScopaPlayer\nfrom strategy import ScopaMove, ScopaMoveType\nimport sys\n\n\nclass ScopaGame:\n\n def __init__(self, players: list[ScopaPlayer] = None,\n winning_score: int = 11,\n hand_size: int = 3,\n board_size: int = 4):\n self.__deck = ScopaDeck()\n self.__deck.shuffle()\n self.__board = []\n self.__players = [] if players is None else players\n self.__winning_score = winning_score\n self.__hand_size = hand_size\n self.__board_size = board_size\n\n def add_player(self, player: ScopaPlayer):\n self.__players.append(player)\n\n def start_game(self):\n if len(self.__players) < 2:\n raise ValueError('Number of players must be greater than or equal to 2')\n\n scores = {player: 0 for player in self.__players}\n winner = None\n\n while not winner:\n print('No winner yet')\n print([f'{player}: {score}' for player, score in scores.items()])\n self.__deck.refresh_deck()\n self.__deck.shuffle()\n self.__deal_board()\n while self.__deck.cards_left():\n self.__deal_players()\n print()\n for _ in range(self.__hand_size):\n for player in self.__players:\n print()\n print(f'Board: {[str(card) for card in self.__board]}')\n print(f'Player {player} hand: {[str(card) for card in player.get_hand()]}')\n move = player.make_move(self.__board)\n print(f'Move made: {move}')\n self.__evaluate_move(move, player, scores)\n print(f'New hand: {[str(card) for card in player.get_hand()]}')\n\n self.__update_scores(scores)\n winner = self.__winning_player(scores)\n\n print(f'{winner} wins! Final scores: {[f\"{player}: {score}\" for player, score in scores.items()]}')\n\n def __winning_player(self, scores: dict[ScopaPlayer, int]):\n for player, score in scores.items():\n if score >= self.__winning_score:\n return player\n return None\n\n def __deal_board(self):\n for _ in range(self.__board_size):\n self.__board.append(self.__deck.draw_card())\n\n def __deal_players(self):\n for _ in range(self.__hand_size):\n for player in self.__players:\n player.deal_card(self.__deck.draw_card())\n\n def __evaluate_move(self, move: ScopaMove, player: ScopaPlayer, scores: dict[ScopaPlayer, int]):\n if move.move_type() == ScopaMoveType.TAKE:\n player.capture_card(move.hand_card())\n player.capture_cards(move.board_cards())\n\n player.remove_hand_card(move.hand_card())\n for board_card in move.board_cards():\n self.__board.remove(board_card)\n\n if not self.__board:\n scores[player] += 1\n return\n\n if move.move_type() == ScopaMoveType.DISCARD:\n self.__board.append(move.hand_card())\n player.remove_hand_card(move.hand_card())\n return\n\n raise ValueError(f'Invalid move type f{move.move_type()}')\n\n def __update_scores(self, scores: dict[ScopaPlayer, int]):\n # Card Count\n most_cards, most_cards_player = -sys.maxsize, None\n for player in self.__players:\n num_captured = len(player.get_captured_cards())\n most_cards, most_cards_player = max((most_cards, most_cards_player), (num_captured, player),\n key=lambda x: x[0])\n scores[most_cards_player] += 1\n\n # Coin Count\n most_coins, most_coins_player = -sys.maxsize, None\n for player in self.__players:\n num_coins = player.get_num_coins_captured()\n most_coins, most_coins_player = max((most_coins, most_coins_player), (num_coins, player),\n key=lambda x: x[0])\n scores[most_coins_player] += 1\n\n # Seven of Coins\n for player in self.__players:\n if ScopaCard(ScopaRank.SEVEN, ScopaSuit.COINS) in player.get_captured_cards():\n scores[player] += 1\n break\n\n # Primes\n highest_prime_sum, highest_prime_sum_player = -sys.maxsize, None\n for player in self.__players:\n prime_sum = 0\n for suit in ScopaSuit:\n prime_sum += max([get_prime_points(card.rank()) for card in player.get_captured_cards()\n if card.suit() == suit])\n highest_prime_sum, highest_prime_sum_player = max((highest_prime_sum, highest_prime_sum_player),\n (prime_sum, player), key=lambda x: x[0])\n scores[highest_prime_sum_player] += 1\n","repo_name":"ksherm47/scopa-game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18617695819","text":"import pygame, sys\r\nfrom pygame.locals import *\r\n\r\npygame.init()\r\nWHITE = (255, 255, 255)\r\nBLACK = (0, 0, 0)\r\nscreen = pygame.display.set_mode((600, 300))\r\npygame.display.set_caption('dinosaur')\r\nrun = True\r\npause = False\r\njump = False\r\nclock = pygame.time.Clock()\r\n#back ground cho game\r\nbg = pygame.image.load('image/background.jpg')\r\nbg_x = 0 \r\nbg_y = 0 \r\n#khủng long\r\ndino = pygame.image.load('image/dinosaur.png')\r\ndino_x = 0\r\ndino_y = 227\r\nvelocity = 5\r\n#cây\r\ntree = pygame.image.load('image/tree.png')\r\ntree_x = 550\r\ntree_y = 227\r\n#pause game\r\nrestart = pygame.image.load('image/reload.png') \r\n#text\r\nfont = pygame.font.SysFont('san', 25)\r\nfont1 = pygame.font.SysFont('san', 40)\r\nfont2 = pygame.font.Font('image/BigShouldersText-VariableFont_wght.ttf', 25)\r\nscore = 0\r\n#sound\r\nsound1 = pygame.mixer.Sound('image/te.wav')\r\nsound = pygame.mixer.Sound('image/tick.wav')\r\nwhile run:\r\n clock.tick(60)\r\n screen.fill(WHITE)\r\n bg_rect = screen.blit(bg, (bg_x, bg_y))\r\n bg2 = screen.blit(bg, (bg_x+600, bg_y)) \r\n dino_rect = screen.blit(dino, (dino_x, dino_y))\r\n tree_rect = screen.blit(tree, (tree_x, tree_y))\r\n score_text = font.render(str(score), True, BLACK)\r\n screen.blit(score_text, (0, 0))\r\n if dino_rect.colliderect(tree_rect):\r\n pause = True\r\n pygame.mixer.Sound.play(sound1)\r\n pause_rect = screen.blit(restart, (275, 125))\r\n gameover_text = font1.render(\"GAME OVER\", True, BLACK)\r\n screen.blit(gameover_text, (225, 200))\r\n text_gameover = font2.render(\"bấm space để chơi lại game\", True, BLACK)\r\n screen.blit(text_gameover, (210, 230))\r\n if jump == True:\r\n dino_y -= velocity\r\n if 80 > dino_y:\r\n jump = False\r\n if jump == False and dino_y < 227:\r\n dino_y += velocity\r\n if bg_x+600 <= 0:\r\n bg_x = 0\r\n if tree_x <= 0:\r\n tree_x = 550\r\n score += 1\r\n #dino_x += velocity\r\n if pause == False:\r\n tree_x -= velocity\r\n bg_x -= velocity\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n run = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE and dino_y == 227 and pause == False:\r\n jump = True\r\n pygame.mixer.Sound.play(sound)\r\n if event.key == K_SPACE and pause == True:\r\n bg_x = 0\r\n tree_x = 550\r\n tree_y = 227\r\n bg_x = 0\r\n bg_y = 0\r\n pause = False\r\n pygame.display.flip()","repo_name":"CCcutcanh/dinosaur_game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11125800847","text":"import json\nimport cherrypy\n\nclass DictionaryController():\n def __init__(self):\n self.myd = dict()\n\n def GET(self, key):\n key = str(key)\n output = {'result':'success'}\n try:\n output['key'] = key\n output['value'] = self.myd[key]\n except KeyError as ex:\n output['result'] = 'error'\n output['message'] = 'key not found'\n return json.dumps(output, encoding='latin-1')\n\n def GET_ALL(self):\n output = {'result':'success'}\n output['entries'] = [\n {\"key\": k, \"value\": v} for k, v in self.myd.iteritems()\n ]\n return json.dumps(output, encoding='latin-1')\n\n def POST(self):\n output = {'result':'success'}\n instr = cherrypy.request.body.read()\n indict = json.loads(instr)\n try:\n self.myd[str(indict['key'])] = indict['value']\n except KeyError as ex:\n output['result'] = 'error'\n output['message'] = 'key not found'\n return json.dumps(output, encoding='latin-1')\n\n\n def PUT(self, key):\n output = {'result':'success'}\n instr = cherrypy.request.body.read()\n indict = json.loads(instr)\n try: \n self.myd[str(key)] = indict['value'] \n except KeyError as ex:\n output['result'] = 'error'\n output['message'] = 'key not found'\n return json.dumps(output, encoding='latin-1')\n\n def DELETE(self, key):\n output = {'result':'success'}\n if key not in self.myd:\n output['result'] = 'error'\n output['message'] = 'key not found'\n else:\n del self.myd[str(key)]\n output['message'] = \"key {i} deleted\".format(i=key)\n return json.dumps(output, encoding='latin-1')\n\n def DELETE_ALL(self):\n output = {'result':'success'}\n self.myd.clear()\n return json.dumps(output, encoding='latin-1')\n","repo_name":"atowneND/paradigms","sub_path":"web_stuff/cherrypy_primer/dcont.py","file_name":"dcont.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5549218427","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport imblearn\n\n# import sqlalchemy\n# from sqlalchemy.ext.automap import automap_base \n# from sqlalchemy.orm import Session \n# from sqlalchemy import create_engine, inspect, func\n# from config import password\n# engine =create_engine (f\"postgresql://postgres:{password}@localhost:5432/Employee_Turnover\")\n\n# df = pd.read_sql_table('turnover_data',engine)\n\n# DO THIS ONCE Split data set: majority of records for training and testing; putting some aside to see how well it predicts new data:\n# df=pd.read_csv('Resources/turnoverData_full.csv')\n# df_traintest = df[:1200]\n# df_new = df[1200:]\n\n# df_traintest.to_csv('Resources/train_test_data.csv', index=False)\n# df_new.to_csv('Resources/prediction_data.csv', index=False)\n\ndf=pd.read_csv('Resources/train_test_data.csv')\n\ndf_skinny = df.drop(['EducationField','EmployeeCount','EmployeeNumber','JobLevel','StandardHours','JobRole','MaritalStatus','DailyRate','MonthlyRate','HourlyRate','Over18','OverTime'], axis=1).drop_duplicates()\ndf_skinny.rename(columns={\"Attrition\": \"EmploymentStatus\"}, inplace=True)\n\n# Change qualitative data to numeric form\ndf_skinny['EmploymentStatus'] = df_skinny['EmploymentStatus'].replace(['Yes','No'],['Terminated','Retained'])\ndf_skinny['Gender']=df_skinny['Gender'].replace(['Female','Male'],[0,1])\ndf_skinny['BusinessTravel'] = df_skinny['BusinessTravel'].replace(['Travel_Rarely','Travel_Frequently','Non-Travel'],[1,2,0])\ndf_skinny['Department']=df_skinny['Department'].replace(['Human Resources','Sales','R&D'],[0,1,2])\n\n# Note: \n# EmploymentStatus: 0=Active, 1=Terminated\n# Gender: 0=female, 1=male\n# Business Travel: 0=no travel, 1=rarely, 2=frequently\n# Department: HR=0, Sales=1, R&D=2\n\nimport matplotlib.ticker as mtick\n\nbars = ['Retained','Turnover']\ny = df_skinny['EmploymentStatus'].value_counts()\ny_as_percent = (y[0]/len(df_skinny),y[1]/len(df_skinny))\n\nfig = plt.figure(1, (4.5,5))\nax = fig.add_subplot(1,1,1)\n\nax.bar(bars,y_as_percent, color=['Teal','Orange'])\nax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))\n\nplt.xticks(fontsize=12)\nplt.ylim(0,.95)\nplt.yticks(fontsize=12)\nplt.xlabel(\"\\n Employment Status\", fontsize=14)\nplt.ylabel(\"Percent of Sample \\n\", fontsize=14)\nplt.annotate(\"83.9%\",xy=(\"Retained\",.87),ha=\"center\")\nplt.annotate(\"16.1%\",xy=(\"Turnover\",.2),ha=\"center\")\nax.tick_params(axis='both', which='major', pad=10)\n\nplt.savefig('static/overallTurnover.png')\n\nX =df_skinny.drop(\"EmploymentStatus\", axis=1)\ny = df_skinny[\"EmploymentStatus\"]\n\n# Data is imbalanced so need to resample. The following (oversampling with a 60:40 ratio between \n# retained and terminated) gave results most consistent with dataset in sampling.\nimport imblearn\noversample = imblearn.over_sampling.RandomOverSampler(sampling_strategy=.4)\nX_over, y_over = oversample.fit_resample(X, y)\n\nfrom sklearn.model_selection import train_test_split\nX_over_train, X_over_test, y_over_train, y_over_test = train_test_split(X_over, y_over, random_state=1)\n\nfrom sklearn.preprocessing import StandardScaler\nX_o_scaler = StandardScaler().fit(X_over_train)\nX_o_train_scaled = X_o_scaler.transform(X_over_train)\nX_o_test_scaled = X_o_scaler.transform(X_over_test)\n\nfrom sklearn.linear_model import LogisticRegression\nclassifier_o = LogisticRegression()\nclassifier_o.fit(X_o_train_scaled, y_over_train)\n\n# print(f\"Training Data Score: {classifier_o.score(X_o_train_scaled, y_over_train)}\")\n# print(f\"Testing Data Score: {classifier_o.score(X_o_test_scaled, y_over_test)}\")\n\npredictions = classifier_o.predict(X_o_test_scaled)\n# print(f\"First 10 Predictions: {predictions[:10]}\")\n# print(f\"First 10 Actual Employment Status: {y_over_test[:10].tolist()}\")\n\n# Predictions of new data\nnew_df = pd.read_csv(\"Resources/prediction_data.csv\")\nnew_skinny = new_df.drop(['EducationField','EmployeeCount','EmployeeNumber','JobLevel','StandardHours','JobRole','MaritalStatus','DailyRate','MonthlyRate','HourlyRate','Over18','OverTime'], axis=1).drop_duplicates()\nnew_skinny.rename(columns={\"Attrition\": \"EmploymentStatus\"}, inplace=True)\n\nnew_skinny['EmploymentStatus'] = new_skinny['EmploymentStatus'].replace(['Yes','No'],['Terminated','Retained'])\nnew_skinny['Gender']=new_skinny['Gender'].replace(['Female','Male'],[0,1])\nnew_skinny['BusinessTravel'] = new_skinny['BusinessTravel'].replace(['Travel_Rarely','Travel_Frequently','Non-Travel'],[1,2,0])\nnew_skinny['Department']=new_skinny['Department'].replace(['Human Resources','Sales','R&D'],[0,1,2])\n\nnew_X = new_skinny.drop(\"EmploymentStatus\", axis=1)\nnew_X_scaler = StandardScaler().fit(new_X)\nnew_X_scaled = new_X_scaler.transform(new_X)\n\nnew_o_predictions=classifier_o.predict(new_X_scaled)\n# See how closely ratio of retained:terminated in predictions matches current data\n# unique, counts = np.unique(new_o_predictions, return_counts=True)\n# dict(zip(unique, counts))\n# termpercent=((counts[1]/len(new_o_predictions))*100).round(1)\n# print(dict(zip(unique,counts)))\n# print(termpercent)\n\nynew = classifier_o.predict_proba(new_X_scaled)\n# to get probability of termination of any given employee:\n#probability = ynew[][1], # e.g:\n# prob_ee1 = (ynew[7][1]*100).round(1)\n# print(f\"{prob_ee1}%\")\n\ncolumns = []\nfor col in df_skinny.drop('EmploymentStatus',axis=1).columns: \n columns.append(col)\n\n# Calculate weight of various factors on retention/turnover\nfeature_importance=pd.DataFrame(np.hstack((np.array([columns[0:]]).T, classifier_o.coef_.T)), columns=['feature', 'importance'])\nfeature_importance['importance']=pd.to_numeric(feature_importance['importance'])\nplot_df=feature_importance.sort_values(by='importance', ascending=True)\n\n\ny = plot_df['importance']\nbars = plot_df['feature']\nticks = [-.45,.45]\nlabels = ['Weighs Heaviest on Retention','Weighs Heaviest on Turnover']\n\nplt.figure(figsize=(15.5,5))\n\nplt.barh(bars,y, height=.5, color='teal')\nplt.xticks(ticks,labels,fontsize=10)\nplt.yticks(fontsize=10)\nplt.ylim(-1,22)\nplt.title(\"\\n Weight of Employment Factors\\n\",fontsize=16)\n\nplt.savefig('static/featureImportance.png')\n\n# Feature importance for R&D workers\ndf_RD = df_skinny.loc[df_skinny['Department'].isin([2])].drop([\"Department\"],axis=1)\n\nX_RD =df_RD.drop(\"EmploymentStatus\", axis=1)\ny_RD = df_RD[\"EmploymentStatus\"]\n\noversample = imblearn.over_sampling.RandomOverSampler(sampling_strategy=.4)\nX_RDover, y_RDover = oversample.fit_resample(X_RD, y_RD)\n\nX_RD_train, X_RD_test, y_RD_train, y_RD_test = train_test_split(X_RDover, y_RDover, random_state=1)\n\nX_RD_scaler = StandardScaler().fit(X_RD_train)\nX_RD_train_scaled = X_RD_scaler.transform(X_RD_train)\nX_RD_test_scaled = X_RD_scaler.transform(X_RD_test)\n\nclassifier=LogisticRegression()\nclassifier.fit(X_RD_train_scaled, y_RD_train)\n\ncolumns_RD = []\nfor col in df_RD.drop('EmploymentStatus',axis=1).columns: \n columns_RD.append(col)\n\nfeature_importance_RD=pd.DataFrame(np.hstack((np.array([columns_RD[0:]]).T, classifier.coef_.T)), columns=['feature', 'importance'])\n\nfeature_importance_RD['importance']=pd.to_numeric(feature_importance_RD['importance'])\nplot_df_RD=feature_importance_RD.sort_values(by='importance', ascending=True)\n\ny=plot_df_RD['importance']\nbars=plot_df_RD['feature']\nticks = [-.6,.5]\nlabels = ['Weighs Heaviest on Retention','Weighs Heaviest on Turnover']\n\nplt.figure(figsize=(15.6,5))\nplt.barh(bars,y, height=.7, color='orange')\nplt.xticks(ticks,labels,fontsize=10)\nplt.yticks(fontsize=10)\nplt.ylim(-1,21)\nplt.title(\"\\n Weight of Employment Factors in R&D\\n\",fontsize=16)\n\nplt.savefig('static/featureImportance_R&D.png')\n\n# Feature importance for Sales workers\ndf_Sales = df_skinny.loc[df_skinny['Department'].isin([1])].drop([\"Department\"],axis=1)\n\nX_S =df_Sales.drop(\"EmploymentStatus\", axis=1)\ny_S = df_Sales[\"EmploymentStatus\"]\n\noversample = imblearn.over_sampling.RandomOverSampler(sampling_strategy=.4)\nX_Sover, y_Sover = oversample.fit_resample(X_S, y_S)\n\nX_S_train, X_S_test, y_S_train, y_S_test = train_test_split(X_Sover, y_Sover, random_state=1)\n\nX_S_scaler = StandardScaler().fit(X_S_train)\nX_S_train_scaled = X_S_scaler.transform(X_S_train)\nX_S_test_scaled = X_S_scaler.transform(X_S_test)\n\nclassifier=LogisticRegression()\nclassifier.fit(X_S_train_scaled, y_S_train)\n\n# print(f\"Training Data Score: {classifier.score(X_RD_train_scaled, y_RD_train)}\")\n# print(f\"Testing Data Score: {classifier.score(X_RD_test_scaled, y_RD_test)}\")\n\ncolumns_S = []\nfor col in df_Sales.drop('EmploymentStatus',axis=1).columns: \n columns_S.append(col)\n\nfeature_importance_S=pd.DataFrame(np.hstack((np.array([columns_S[0:]]).T, classifier.coef_.T)), columns=['feature', 'importance'])\n\nfeature_importance_S['importance']=pd.to_numeric(feature_importance_S['importance'])\nplot_df_S=feature_importance_S.sort_values(by='importance', ascending=True)\n\ny=plot_df_S['importance']\nbars=plot_df_S['feature']\nticks = [-.45,.55]\nlabels = ['Weighs Heaviest on Retention','Weighs Heaviest on Turnover']\n\nplt.figure(figsize=(15.6,5))\nplt.barh(bars,y, height=.7, color='red')\nplt.xticks(ticks,labels,fontsize=10)\nplt.yticks(fontsize=10)\nplt.ylim(-1,21)\nplt.title(\"\\n Weight of Employment Factors in Sales Department\\n\",fontsize=16)\n\nplt.savefig('static/featureImportance_S.png')\n\n","repo_name":"mfineman/Employee_Turnover","sub_path":"LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":9181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72055631525","text":"import numpy as np\nfrom tqdm import tqdm\n\nclass RidgeClassifier:\n def __init__(self, alpha=1.0, max_iter=1000, tol=1e-3, random_state=None):\n self.alpha = alpha\n self.max_iter = max_iter\n self.tol = tol\n self.random_state = random_state\n \n # @jit\n def softmax(self, scores):\n max_scores = np.max(scores, axis=1, keepdims=True)\n exp_scores = np.exp(scores - max_scores)\n probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)\n return probs\n\n # @jit\n def gradient(self, n_samples, X, y_one_hot, proba):\n grad = -1/n_samples * X.T.dot(y_one_hot - proba) + 2 * self.alpha * self.coef_\n return grad\n\n def fit(self, X, y, verbose=1):\n if self.random_state is not None:\n np.random.seed(self.random_state)\n \n # Add column of ones for bias term\n X = np.hstack([np.ones((X.shape[0], 1)), X])\n \n n_samples, n_features = X.shape\n n_classes = np.unique(y).shape[0]\n \n # Initialize weight matrix\n self.coef_ = np.random.randn(n_features, n_classes)\n \n # Convert y to one-hot encoding\n y_one_hot = np.zeros((n_samples, n_classes))\n y_one_hot[np.arange(n_samples), y] = 1\n \n # Train using gradient descent with L2 regularization\n if verbose == 1:\n iter_range = tqdm(range(self.max_iter))\n elif verbose == 0:\n iter_range = range(self.max_iter)\n for i in iter_range:\n scores = X.dot(self.coef_)\n proba = self.softmax(scores)\n grad = self.gradient(n_samples, X, y_one_hot, proba)\n self.coef_ -= grad * self.tol\n \n # Stop training if change in coefficients is less than tolerance\n if np.linalg.norm(grad) < self.tol:\n break\n \n def predict(self, X):\n X = np.hstack([np.ones((X.shape[0], 1)), X])\n scores = X.dot(self.coef_)\n return np.argmax(scores, axis=1)","repo_name":"mdaniyalk/ml-scratch","sub_path":"ridge_classifier.py","file_name":"ridge_classifier.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39658778892","text":"import joblib\nimport pickle\n\n\ndef load_pickle(file_path, silent=True):\n with open(file_path, \"rb\") as f:\n obj = joblib.load(f)\n if not silent:\n print(f\"=> loaded {file_path}\")\n return obj\n\n\ndef save_pickle(obj, file_path, silent=True):\n with open(file_path, \"wb\") as f:\n joblib.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)\n if not silent:\n print(f\"=> saved to {file_path}\")\n","repo_name":"K-Nick/ce7455-transformer-lm","sub_path":"util/io/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41022092500","text":"import os\nimport sys\nimport logging\nimport streamlit as st\nfrom langchain.vectorstores import FAISS\nfrom langchain.storage import LocalFileStore\nfrom langchain.embeddings import LlamaCppEmbeddings\nfrom langchain.embeddings import OpenAIEmbeddings, CacheBackedEmbeddings\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.llms.llamacpp import LlamaCpp\n\n# Import app configuration\nfrom config import api_key, result_threshold, score_threshold, openai_embedding_model, openai_inference_models, local_models, llm_temperature, n_ctx, max_tokens, n_gpu_layers\n\nsys.setrecursionlimit(4096)\n\nlogging.basicConfig(level=logging.INFO)\n\nreplaceable = st.empty()\n\ndef logger(message, type):\n global replaceable\n if type == \"warning\":\n logging.warning(message)\n replaceable.warning(message)\n elif type == \"error\":\n logging.error(message)\n replaceable.error(message)\n else:\n logging.info(message)\n replaceable.info(message)\n\ndef save(documents: dict, vectorstore: dict):\n global replaceable\n\n fs = LocalFileStore(\"./cache/\")\n\n # load cached embedding\n cached_embedder = CacheBackedEmbeddings.from_bytes_store(\n vectorstore['embedding'], fs, namespace=vectorstore['embedding'].model\n )\n\n vdb = FAISS.from_documents(documents, embedding=cached_embedder)\n try:\n vdb.save_local(vectorstore['path'])\n except Exception as e:\n logger(f\"An error occured trying to reindex vector store: {e}\", \"error\")\n return False\n\n return True\n\ndef load(vectorstore: dict):\n global replaceable\n\n vs_path = vectorstore['path']\n vs_embedding = vectorstore['embedding']\n\n vdb = FAISS.load_local(vs_path, embeddings=vs_embedding)\n\n return vdb\n\ndef get_vectorstore(url: str, model: str):\n global replaceable\n vectorstore = {}\n\n # Set app home\n app_home = os.path.dirname(os.path.abspath(__file__))\n\n # openai vectorstore\n if model in openai_inference_models:\n\n # check if OPENAI_API_KEY is set\n if api_key == \"\":\n logger(\"Error: environment variable OPENAI_API_KEY is not set\", \"error\")\n return None\n\n vectorstore['type'] = \"openai\"\n vectorstore['embedding'] = OpenAIEmbeddings(\n openai_api_key=api_key,\n model=openai_embedding_model\n )\n vectorstore['name'] = f\"{url}-{openai_embedding_model}.vdb\"\n\n # local vectorstore\n elif model in local_models:\n\n model_path = os.path.join(app_home, \"models\", model + \".gguf\")\n # check if model_path exists\n if not os.path.exists(model_path):\n logger(f\"Error: {model} model does not exist\", \"error\")\n return None\n\n vectorstore['type'] = \"local\"\n vectorstore['embedding'] = LlamaCppEmbeddings(\n model_path=model_path,\n n_ctx=n_ctx,\n n_gpu_layers=n_gpu_layers,\n )\n vectorstore['name'] = f\"{url}-{model}.vdb\"\n else:\n logger(f\"Error: {model} model does not exist\", \"error\")\n return None\n\n vectorstore['model'] = model\n vectorstore['path'] = os.path.join(app_home, \"data\", vectorstore['name'])\n return vectorstore\n\ndef search(question: str, vectorstore: dict):\n global replaceable\n\n vdb = load(vectorstore=vectorstore)\n\n # search vector store for documents similar to user query, return to 5 results\n kwargs = {'score_threshold': score_threshold}\n try:\n docs_with_scores = vdb.similarity_search_with_relevance_scores(\n query=question,\n k=result_threshold,\n **kwargs\n )\n except Exception as e:\n logger(f\"An error occured trying to search the vector store: {e}\", \"error\")\n return None\n\n # if there are no results\n if len(docs_with_scores) == 0:\n logger(f\"There were no documents matching your query: {question}\", \"error\")\n return None\n\n # Setup llm chain\n if vectorstore[\"model\"] in openai_inference_models:\n llm = ChatOpenAI(\n openai_api_key=api_key,\n temperature=llm_temperature,\n verbose=True,\n model=vectorstore[\"model\"]\n )\n elif vectorstore[\"model\"] in local_models:\n llm = LlamaCpp(\n verbose=True,\n model_path=vectorstore[\"path\"],\n n_ctx=n_ctx,\n n_gpu_layers=n_gpu_layers,\n max_tokens=max_tokens,\n temperature=llm_temperature,\n )\n else:\n # should not happen\n logger(f\"Model not found!\", \"error\")\n return None\n\n return docs_with_scores, llm","repo_name":"maociao/llm-semantic-site-search","sub_path":"vectorstore.py","file_name":"vectorstore.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29791719008","text":"# Check even or odd\neven = lambda a: not a%2\n\nsum = 0\na , b = 1 , 2\nwhile a < 4000000:\n if even(a):\n sum += a\n a, b = b, a+b\n\nprint(sum)","repo_name":"web-py/Euler-Project-Python","sub_path":"02-Even_Fibonacci_numbers.py","file_name":"02-Even_Fibonacci_numbers.py","file_ext":"py","file_size_in_byte":149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3218537785","text":"\nfrom typing import Optional\nfrom pytube import YouTube, Playlist\n\nfolder = r'E:\\code\\Youtube1\\\\'\ndestination_folder = r'E:\\code\\Youtube1\\download\\\\'\n\npl_url = \"https://www.youtube.com/playlist?list=PLZ67c1-XfKx44ts2ogMbst4vsnguaRzRr\"\nplaylist = Playlist(pl_url)\nid = 1\n\ndef append_new_line(file_name, text_to_append):\n # Open the file in append & read mode ('a+')\n with open(file_name, \"a+\") as file_object:\n # Move read cursor to the start of file.\n file_object.seek(0)\n # If file is not empty then append '\\n'\n data = file_object.read(100)\n if len(data) > 0:\n file_object.write(\"\\n\")\n # Append text at the end of file\n file_object.write(text_to_append)\n\nfor video in playlist.video_urls:\n ytv = YouTube(video)\n \n file_name = f' video {id} {ytv.title}'\n print(file_name)\n \n # Creating the engine\n \n if ytv.streams.get_by_resolution(\"720p\") != None:\n ytv_streams = ytv.streams.get_by_resolution(\"720p\")\n ytv_streams.download()\n # YouTube(video)\n # Append one line to a file that does not exist\n append_new_line('info.txt', f'720p Video URL: {video}')\n\n # info.append( f'\\n 720p Video URL: {yt_video_url}')\n\n # with open('readme.txt', 'w') as f:\n # f.write('/n' .join(f' 720p Video URL: {yt_video_url}'))\n else:\n if ytv.streams.get_by_resolution(\"480p\") != None:\n ytv_streams = ytv.streams.get_by_resolution(\"480p\")\n ytv_streams.download()\n append_new_line('info.txt', f'480p Video URL: {video}')\n # info.append( f'\\n 480p Video URL: {yt_video_url}')\n\n # with open('readme.txt', 'w') as f:\n # f.write('/n' .join(f' 480p Video URL: {yt_video_url}'))\n\n else:\n ytv_streams = ytv.streams.get_by_resolution(\"360p\")\n ytv_streams.download()\n append_new_line('info.txt', f'360p Video URL: {video}')\n # info.append( f'\\n 360p Video URL: {yt_video_url}')\n\n # with open('readme.txt', 'w') as f:\n\n # f.write('/n' .join(f' 360p Video URL: {yt_video_url}'))\n\n # ytv_streams.download()\n\n for x in os.listdir(folder):\n\n if x.startswith(ytv.title[:4]):\n print(ytv.title[:4])\n # Prints only text file present in My Folder\n print(x)\n source = folder + x\n\n # Adding the count to the new file name and extension\n destination = folder + \"video \" + str(id)+ ' '+ x\n\n # Renaming the file\n os.rename(source, destination)\n for x in os.listdir(folder):\n\n if x.startswith('video'):\n print(ytv.title[:4])\n # Prints only text file present in My Folder\n print(x)\n source = folder + x\n\n # Adding the count to the new file name and extension\n destination = destination_folder + x\n\n # Renaming the file\n os.rename(source, destination)\n \n id += 1\n","repo_name":"thotakuriravi/youtube_downloader","sub_path":"youtube_downloader.py","file_name":"youtube_downloader.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28367885780","text":"# ------------------------------------------\n#Libraries\n# ------------------------------------------\nimport pandas as pd\nimport folium\nimport streamlit as st\nimport geopandas\nimport plotly.express as px\n\nfrom geopy.distance import great_circle\nfrom folium.plugins import MarkerCluster\nfrom datetime import datetime\nfrom streamlit_folium import folium_static\n\n# ------------------------------------------\n# settings\n# ------------------------------------------\nst.set_page_config(layout='wide')\n# ------------------------------------------\n# Helper Functions\n# ------------------------------------------\nst.cache( allow_output_mutation=True )\ndef get_data( path ):\n data = pd.read_csv( path )\n return data\n\n@st.cache( allow_output_mutation=True )\ndef get_geofile(url):\n geofile = geopandas.read_file(url)\n return geofile\n\ndef data_clean(data):\n data['date'] = pd.to_datetime(data['date']).dt.strftime('%Y-%m-%d')\n data.drop_duplicates(subset=\"id\", keep='last', inplace=True)\n data = data[(data['bedrooms'] != 0) & (data['bedrooms'] != 11) & (data['bedrooms'] != 33)]\n return data\n\ndef house_recommendation(data):\n decision_df = data[['id', 'zipcode', 'date', 'condition', 'grade', 'price']].copy()\n zc_median_price = decision_df[['price', 'zipcode']].groupby('zipcode').median().reset_index()\n decision_df = pd.merge(decision_df, zc_median_price, on='zipcode', how='inner').rename(columns={'price_x': 'buying_price', 'price_y': 'median_price'})\n decision_df['buying_price'] = decision_df['buying_price'].astype('float64')\n decision_df['recommendation'] = decision_df[['condition', 'buying_price', 'median_price']].apply(lambda x:'buy' if (x['condition'] >= 3) & (x['buying_price'] < x['median_price']) else\n 'no_buy', axis=1)\n return decision_df\n\ndef filter_decision(decision_df):\n st.title('House Rocket Insights - Dashboard')\n st.header('Data Overview - Purchase Recommendation')\n f_recommendation = st.checkbox('Show only houses recommended to buy')\n c1, c2, c3 = st.columns((4, 1, 4))\n with c1:\n f_zipcode = st.multiselect('Enter zipcodes', decision_df['zipcode'].sort_values().unique())\n f_condition = st.multiselect('Enter condition', decision_df['condition'].sort_values().unique())\n with c3:\n min_date = datetime.strptime(decision_df['date'].min(), '%Y-%m-%d')\n max_date = datetime.strptime(decision_df['date'].max(), '%Y-%m-%d')\n f_date = st.slider('Select date', min_date, max_date, max_date)\n f_buying_price = st.slider('Select maximum price',\n int(decision_df['buying_price'].min()),\n int(decision_df['buying_price'].max()),\n value=int(decision_df['buying_price'].max()))\n if f_recommendation:\n f_decision1 = decision_df[decision_df['recommendation'] == 'buy']\n else:\n f_decision1 = decision_df.copy()\n f_decision1['date'] = pd.to_datetime(f_decision1['date'])\n f_decision2 = f_decision1[(f_decision1['date'] <= f_date) & (f_decision1['buying_price'] <= f_buying_price)]\n if (f_zipcode != []) & (f_condition != []):\n f_decision3 = f_decision2.loc[(f_decision2['zipcode'].isin(f_zipcode)) & (f_decision2['condition'].isin(f_condition)), :]\n elif (f_zipcode != []) & (f_condition == []):\n f_decision3 = f_decision2.loc[f_decision2['zipcode'].isin(f_zipcode), :]\n elif (f_zipcode == []) & (f_condition != []):\n f_decision3 = f_decision2.loc[f_decision2['condition'].isin(f_condition), :]\n else:\n f_decision3 = f_decision2.copy()\n st.write(f_decision3)\n return None\n\ndef profit_expectation(decision_df):\n season_df = decision_df[decision_df['recommendation'] == 'buy'].copy()\n season_df['month'] = pd.to_datetime(season_df['date']).dt.month\n season_df['season'] = season_df['month'].apply(lambda x: 'spring' if (x >= 3) & (x < 6) else\n 'summer' if (x >= 6) & (x < 9) else\n 'fall' if (x >= 9) & (x < 12) else\n 'winter')\n median_season_df = season_df[['buying_price', 'zipcode', 'season']].groupby(['season', 'zipcode']).median().sort_values(by='zipcode').reset_index()\n # Create columns for median price of each season\n median_season_df = median_season_df.pivot(index='zipcode', columns='season', values='buying_price').reset_index()\n median_season_df.columns = ['zipcode', 'fall_median', 'spring_median', 'summer_median', 'winter_median']\n # merging data to suggest price for sale\n dataset = pd.merge(season_df, median_season_df, on='zipcode', how='inner')\n dataset = dataset[['id', 'date', 'zipcode', 'buying_price', 'median_price', 'season', 'fall_median', 'spring_median','summer_median', 'winter_median']].copy()\n # add column with suggest sale price\n dataset['fall_selling_price'] = dataset[['buying_price', 'fall_median']].apply(lambda x: x['buying_price'] * 1.3 if x['buying_price'] <= x['fall_median'] else\n x['buying_price'] * 1.1, axis=1)\n dataset['spring_selling_price'] = dataset[['buying_price', 'spring_median']].apply(lambda x: x['buying_price'] * 1.3 if x['buying_price'] <= x['spring_median'] else\n x['buying_price'] * 1.1, axis=1)\n dataset['summer_selling_price'] = dataset[['buying_price', 'summer_median']].apply(lambda x: x['buying_price'] * 1.3 if x['buying_price'] <= x['summer_median'] else\n x['buying_price'] * 1.1, axis=1)\n dataset['winter_selling_price'] = dataset[['buying_price', 'winter_median']].apply(lambda x: x['buying_price'] * 1.3 if x['buying_price'] <= x['winter_median'] else\n x['buying_price'] * 1.1, axis=1)\n # Add columns with min and max selling_price\n dataset['min_selling_price'] = dataset[['fall_selling_price', 'spring_selling_price', 'summer_selling_price', 'winter_selling_price']].min(axis=1)\n dataset['max_selling_price'] = dataset[['fall_selling_price', 'spring_selling_price', 'summer_selling_price', 'winter_selling_price']].max(axis=1)\n # Creating column with recommended season for selling (make sure to cover all possibilities)\n dataset['sell_at'] = dataset[['fall_selling_price', 'spring_selling_price', 'summer_selling_price', 'winter_selling_price', 'max_selling_price']].apply(lambda x:\n 'fall' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) else\n 'summer' if (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) else\n 'spring' if (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) else\n 'winter' if (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) else\n 'fall_or_summer' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) else\n 'fall_or_spring' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) else\n 'fall_or_winter' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) else\n 'summer_or_spring' if (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) else\n 'summer_or_winter' if (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) else\n 'spring_or_winter' if (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) else\n 'fall_or_summer_or_spring' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] != x['winter_selling_price']) else\n 'fall_or_summer_or_winter' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['spring_selling_price']) else\n 'fall_or_spring_or_winter' if (x['max_selling_price'] == x['fall_selling_price']) &\n (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['summer_selling_price']) else\n 'summer_or_spring_or_winter' if (x['max_selling_price'] == x['summer_selling_price']) &\n (x['max_selling_price'] == x['spring_selling_price']) &\n (x['max_selling_price'] == x['winter_selling_price']) &\n (x['max_selling_price'] != x['fall_selling_price']) else\n 'any_season', axis=1)\n # add column with expected profit\n dataset['max_profit'] = dataset[['buying_price', 'max_selling_price']].apply(lambda x: x['max_selling_price'] - x['buying_price'], axis=1)\n dataset['min_profit'] = dataset[['buying_price', 'min_selling_price']].apply(lambda x: x['min_selling_price'] - x['buying_price'], axis=1)\n # summarizing data\n summ_dataset = dataset[['id', 'zipcode', 'buying_price', 'min_selling_price', 'max_selling_price', 'min_profit', 'max_profit', 'sell_at']].copy()\n return summ_dataset\n\ndef profit_expectation_table(summ_dataset):\n # NEW SESSION -> SELLING DETAILS\n st.header('Selling Details')\n # Filters\n c1, c2, c3 = st.columns((4, 1, 4))\n with c1:\n f_id = st.multiselect('Enter house ID', summ_dataset['id'].sort_values().unique())\n f_zipcode2 = st.multiselect('Enter desired zipcodes', summ_dataset['zipcode'].sort_values().unique())\n f_sell_at = st.multiselect('Enter season you want to sell', summ_dataset['sell_at'].sort_values().unique())\n with c3:\n f_buying_price2 = st.slider('Select maximum buying price',\n int(summ_dataset['buying_price'].min()),\n int(summ_dataset['buying_price'].max()),\n value=int(summ_dataset['buying_price'].max()))\n f_max_profit = st.slider('Select maximum profit expected',\n int(summ_dataset['max_profit'].min()),\n int(summ_dataset['max_profit'].max()),\n value=int(summ_dataset['max_profit'].max()))\n # Applying filtres\n summ_dataset2 = summ_dataset[(summ_dataset['max_profit'] <= f_max_profit) & (summ_dataset['buying_price'] <= f_buying_price2)]\n def data_filter(id, zip, sell):\n # Os parâmetros da função são os valores digitados nos campos do form.\n # Os 3 ifs verificam se os campos foram preenchidos, caso algum campo\n # do formulário não tenha sido preenchido essa verificação atribui a\n # esses campos a respectiva coluna no dataframe original assim o filtro\n # \"ignorará\" esse campo na busca considerando apenas os que foram\n # preenchidos. A função retorna um dataframe menor com os dados filtrados.\n if (id == []):\n id = summ_dataset2['id']\n if (zip == []):\n zip = summ_dataset2['zipcode']\n if (sell == []):\n sell = summ_dataset2['sell_at']\n summ_dataset3 = summ_dataset2.loc[(summ_dataset2['id'].isin(id)) & (summ_dataset2['zipcode'].isin(zip)) & (summ_dataset2['sell_at'].isin(sell)), :]\n return summ_dataset3\n summ_dataset3 = data_filter(f_id, f_zipcode2, f_sell_at)\n st.write(summ_dataset3)\n return summ_dataset3\n\ndef visual_attributes(data, summ_dataset3, geofile):\n coordinates = data[['id', 'lat', 'long']].copy()\n coordinates['query'] = coordinates[['lat', 'long']].apply(lambda x: str(x['lat']) + ',' + str(x['long']), axis=1)\n lake_tuple = 47.640883, -122.259250\n coordinates['distance_lake'] = coordinates['query'].apply(lambda x: great_circle(lake_tuple, x).km)\n coo_dataset = pd.merge(summ_dataset3, coordinates, on='id', how='inner')\n df_map = coo_dataset\n # density qty map\n density_map = folium.Map(location=[coo_dataset['lat'].mean(), coo_dataset['long'].mean()], default_zoom_start=15)\n marker_cluster = MarkerCluster().add_to(density_map)\n for name, row in df_map.iterrows():\n folium.Marker(\n [row['lat'],\n row['long']],\n popup='House id: {0}. \\n Buy for ${1} \\n Sell for: ${2} \\n Sell at {3}'.format(\n row['id'],\n row['buying_price'],\n row['max_selling_price'],\n row['sell_at']\n )\n ).add_to(marker_cluster)\n geofile = geofile[geofile['ZIP'].isin(data['zipcode'].tolist())]\n folium.features.Choropleth(data=df_map,\n geo_data=geofile,\n columns=['zipcode', 'max_profit'],\n key_on='feature.properties.ZIP',\n fill_color='YlOrRd',\n fill_opacity=0.7,\n line_opacity=0.2,\n legend_name='Expected Profit').add_to(density_map)\n c1, c2, c3 = st.columns((5, 1, 5))\n c1.subheader('Most Profitable Houses Filtered')\n c3.subheader('Density Map with Most Profitable Houses')\n profit_chart = summ_dataset3[['id', 'max_profit']].reset_index().sort_values(by='max_profit', ascending=False)\n profit_chart['id'] = profit_chart['id'].apply(str)\n profit_chart = profit_chart.head(10)\n profit_plot = px.bar(profit_chart, x='id', y='max_profit', height=600)\n profit_plot.update_layout(barmode='stack', xaxis={'categoryorder': 'total descending'})\n profit_plot.update_layout(margin_autoexpand=False)\n c1.plotly_chart(profit_plot, use_container_width=True)\n with c3:\n folium_static(density_map)\n return None\n\nif __name__ == \"__main__\":\n #ETL\n path = 'kc_house_data.csv'\n url = 'https://opendata.arcgis.com/datasets/83fc2e72903343aabff6de8cb445b81c_2.geojson'\n\n #Load data\n data = get_data(path)\n geofile = get_geofile(url)\n\n #Trasform Data\n data = data_clean(data)\n decision_df = house_recommendation(data)\n filter_decision(decision_df)\n summ_dataset = profit_expectation(decision_df)\n summ_dataset3 = profit_expectation_table(summ_dataset)\n visual_attributes(data, summ_dataset3, geofile)\n\n\n\n\n","repo_name":"felipefvasconcelos/House_Rocket_Insight_Project","sub_path":"heroku_app/house_rocket_insights.py","file_name":"house_rocket_insights.py","file_ext":"py","file_size_in_byte":18948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13139779645","text":"#graphicsTemplate\r\nfrom pygame import *\r\nsize=width,height=800,600\r\nscreen=display.set_mode(size)\r\nRED=(255,0,0) \r\nGREEN=(0,255,0)\r\nBLUE=(0,0,255)\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\nscreen.fill(WHITE)\r\nrunning=True\r\ninit()\r\nmixer.Sound(\"MP3 Files/Beyblade Burst Super Z Opening.mp3\") #loads the song \r\nmixer.music.play() #plays the music\r\nwhile running:\r\n for evt in event.get():\r\n if evt.type==QUIT:\r\n running=False\r\n if evt.type == MOUSEBUTTONDOWN:\r\n screenshot = screen.copy()\r\n\r\n mb=mouse.get_pressed()\r\n mx,my=mouse.get_pos()\r\n\r\n omx,omy = mx,my\r\n display.flip() \r\n\r\nquit()\r\n\r\n","repo_name":"sa35577/Paint-Project","sub_path":"volume.py","file_name":"volume.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43129777350","text":"Import(['getCPPFiles', 'env', 'project', 'build_type', 'arch'])\r\n\r\n# precompiled header\r\nenv['GchSh'] = env.GchSh(target = '../k0_common.h.gch/'+build_type+'-'+arch, source = 'k0_common.h')[0]\r\n\r\n# libs to link against\r\nenv.Append(LIBS = ['z'])\r\n\r\n# cpp defines\r\n#env.Append(CPPDEFINES = ['K2_DLL', 'K2_EXPORTS'])\r\n\r\nif build_type == 'debug':\r\n\tlibname = 'k0_debug-'+arch\r\nelse:\r\n\tlibname = 'k0-'+arch\r\n\r\n# source files\r\nsrc = [getCPPFiles('../src/k0.vcproj'), 'tchar_linux.cpp']\r\n\r\n# create the library\r\nenv.StaticLibrary(target = libname, source = src)\r\n\r\n# target\r\nAlias('k0-' + build_type + '-' + arch, 'lib' + libname + '.a')\r\n","repo_name":"shawwn/hon","sub_path":"lib/k0/src/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8382369471","text":"def print_matrix(matrix):\n\tfor i in range(len(matrix)):\n\t\tfor j in range(len(matrix[0])):\n\t\t\tprint(matrix[i][j])\n\t\tprint(\"\\n\")\n\tfor h in matrix:\n\t\tprint (h)\n\t\t\n#def main():\na=int(input(\"matrix 1 rows:\"))\nb=int(input(\"matrix 1 columns:\"))\nc=int(input(\"matrix 2 rows:\"))\nd=int(input(\"matrix 2 columns:\"))\nif(b!=c):\n\tprint(\"matrix multiplication is not possible:\")\n\texit()\n#declaration of arrays\narray1=[[0 for j in range (0,b)] for i in range (0,a)]\narray2=[[0 for j in range (0,d)] for i in range (0,c)]\nresult=[[0 for j in range (0,d)] for i in range (0,a)]\nprint (\"enter 1st matrix elements:\" )\nfor i in range(0 , a):\n\tfor j in range(0 , b):\n\t\tarray1[i][j]=int (input(\"enter element\"))\nprint (\"enter 2nd matrix elements:\")\nfor i in range(0 , c):\n\tfor j in range(0 , d):\n\t\tarray2[i][j]=int(input(\"enter element\"))\nprint (\"1st matrix\")\nprint_matrix(array1)\nprint (\"2nd matrix\")\nprint_matrix(array2)\nfor i in range(0 , a):\n\tfor j in range(0 , d):\n\t\tfor k in range(0 , b):\n\t\t\tresult[i][j] += array1[i][k] * array2[k][j]\nprint ( \"multiplication of two matrices:\" )\nprint_matrix(result)\n","repo_name":"udaymohannaik/dsp","sub_path":"mat_mul.py","file_name":"mat_mul.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31634635232","text":"import lxml.html\nimport requests\nimport string, datetime, os, csv, time, random, sys\n\n# Set time in between requests\nSLEEP_TIME = 7200 # 2 hours\nSLEEP_TIME_BUFFER = 900 # 15 mins\n\nURL = 'https://www.grousemountain.com/current_conditions'\n\n# information for output csv\nschema = ['date', 'time', 'temp_celsius', 'high', 'low', 'weather', 'status', 'report_type', 'today_forecast', 'tomorrow_forecast', 'snow_12hr', 'snow_24hr', 'snow_48hr', 'snow_overnight', 'snow_7days', 'snow_total', 'snow_snowmaking', 'snow_peak', 'snow_plateau']\ncsv_name = 'grouse_weather_report.csv'\n\n# Parses html into list\ndef parse_text(text):\n return list(filter(lambda x: len(x) > 0, text.split('\\n')))\n\n# Parses temperature from string\ndef get_temp(text, temp_type):\n print(text)\n # Flurries. High:-4 Low: -6\n temp = ''\n if temp_type in text:\n if temp_type + ': ' in text:\n split = text.split(temp_type + ': ')\n else:\n split = text.split(temp_type + ':')\n split = split[1].split(' ')\n temp = split[0]\n return temp\n\ndef main(*args):\n # Scrape data from website\n while True:\n # No point parsing data before 5AM\n d = datetime.datetime.now()\n\n if len(args) > 1:\n d = d - datetime.timedelta(hours=8)\n if d.hour < 6 or d.hour > 23:\n print('Sleeping at {} ... Trying again in 40 mins.'.format(str(d)))\n time.sleep(2000)\n continue\n\n response = requests.get(URL)\n tree = lxml.html.fromstring(response.text)\n #tree = lxml.html.parse('sample.html').getroot() # for testing\n\n # Check if season is winter\n season = tree.find_class(\"menu-item--active\")[0].xpath('./form/input/@value')[0]\n if season.lower() != 'winter':\n print('Winter is no more.')\n return\n date, current_time = str(d).split(' ')\n\n # Current temp/conditions\n conditions = tree.xpath('//div[@class=\"current-weather__content\"]')[0].text_content()\n parsed_conditions = parse_text(conditions)\n celsius = parsed_conditions[0][:-2]\n weather = parsed_conditions[-1]\n current_status = tree.xpath('//div[@class=\"current_status\"]')[0].text_content()\n parsed_status = parse_text(current_status)\n status = '{} {}'.format(*parsed_status[:2])\n report_type = '{} {}'.format(*parsed_status[2:4])\n\n # Weather forecaset\n forecast = tree.xpath('//div[@class=\"forecast\"]')[0].text_content()\n parsed_forecast = parse_text(forecast)\n today, tomorrow = parsed_forecast[1], parsed_forecast[3]\n high_today = get_temp(today, 'High')\n low_today = get_temp(today, 'Low')\n\n # Short term snow totals\n snow_today = tree.find_class(\"conditions-snow-report__stats-day\")[0].text_content()\n parsed_snow_today = parse_text(snow_today)\n snow_12hr = parsed_snow_today[1].strip(string.ascii_letters)\n snow_24hr = parsed_snow_today[7].strip(string.ascii_letters)\n snow_48hr = parsed_snow_today[10].strip(string.ascii_letters)\n snow_overnight = parsed_snow_today[4].strip(string.ascii_letters)\n\n # Long term snow totals\n snow_summary = tree.find_class('conditions-snow-report__stats-season')[0].text_content()\n parsed_snow_summary = parse_text(snow_summary)\n snow_7days = parsed_snow_summary[1].strip(string.ascii_letters)\n snow_total = parsed_snow_summary[4].strip(string.ascii_letters)\n snow_snowmaking = parsed_snow_summary[7].strip(string.ascii_letters)\n snow_peak = parsed_snow_summary[10].strip(string.ascii_letters)\n snow_plateau = parsed_snow_summary[13].strip(string.ascii_letters)\n\n # Write to CSV\n row = [date, current_time, celsius, high_today, low_today, weather, status, report_type, today, tomorrow, snow_12hr, snow_24hr, snow_48hr, snow_overnight, snow_7days, snow_total, snow_snowmaking, snow_peak, snow_plateau]\n print(row)\n\n file_exists = os.path.exists(csv_name)\n mode = 'a' if file_exists else 'w'\n with open(csv_name, mode) as f:\n writer = csv.writer(f)\n if not file_exists:\n writer.writerow(schema)\n writer.writerow(row)\n\n delay = SLEEP_TIME + (random.random() * SLEEP_TIME_BUFFER)\n print('Sleeping for {}'.format(str(datetime.timedelta(seconds=delay))))\n time.sleep(delay)\n\nif __name__ == '__main__':\n main(*sys.argv)\n","repo_name":"shind07/Grouse-Mountain","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72299987365","text":"from Gaudi.Configuration import * \nfrom Configurables import DecayTreeTuple, TupleToolTrigger, SubstitutePID, DaVinci, TupleToolTagging, TupleToolTISTOS, CheckPV, FilterDesktop \n#from StrippingSelections.StrippingBs2Q2B import Bs2Q2Body4piConf\nfrom StrippingSelections.StrippingBs2KKhh import BsPhiRhoConf\nfrom DecayTreeTuple.Configuration import *\nfrom PhysSelPython.Wrappers import Selection, SelectionSequence, DataOnDemand, AutomaticData\nfrom Configurables import LoKi__Hybrid__TupleTool\nfrom Configurables import DaVinci,HltSelReportsDecoder,HltVertexReportsDecoder,HltDecReportsDecoder, BackgroundCategory, TupleToolRecoStats, TupleToolTrackIsolation\nfrom Configurables import GaudiSequencer\nfrom Configurables import EventNodeKiller\n\nmyDecayType = 3 \n#myDecayType : (1 for Bsphirho, 2 for Bsphif0, 3 for Bsphiphi) \nDataYear = \"2012\"\nIsMC = True\nif not IsMC: \n myDecayType = 0\n MySequencer = GaudiSequencer('Sequence')\n eventNodeKiller = EventNodeKiller('DAQkiller')\n eventNodeKiller.Nodes = ['DAQ','pRec']\n MySequencer.Members+=[eventNodeKiller]\n\nuserAlgos = []\n\nfrom Configurables import TrackScaleState as SCALER\nscaler = SCALER('StateScale')\nfrom Configurables import TrackSmearState as SMEAR\nsmear = SMEAR('StateSmear')\n\nmydataLocation = \"/Event/AllStreams/Phys/BsPhiRhoLine/Particles\"\n_strippingOutput = AutomaticData(Location = mydataLocation)\n\nif myDecayType and IsMC:\n if myDecayType == 1:\n newDecay = \"DECTREE('B_s0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)')\"\n _SubstituteB0 = SubstitutePID ( name = \"_SubstituteB0\", \n Code = \" DECTREE('B0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)') \" , \n Substitutions = {'Beauty -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)' : 'B_s0'})\n elif myDecayType == 2:\n newDecay = \"DECTREE('B_s0 -> (phi(1020) -> K+ K-) (f_0(980) -> pi+ pi-)')\"\n _SubstituteB0 = SubstitutePID ( name = \"_SubstituteB0\",\n Code = \" DECTREE('B0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)') \" ,\n Substitutions = {'Beauty -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)' : 'B_s0',\n 'Beauty -> (phi(1020) -> K+ K-) ^(rho(770)0 -> pi+ pi-)' : 'f_0(980)'})\n elif myDecayType == 3:\n newDecay = \"DECTREE('B_s0 -> (phi(1020) -> K+ K-) (phi(1020) -> K+ K-)')\"\n _SubstituteB0 = SubstitutePID ( name = \"_SubstituteB0\",\n Code = \" DECTREE('B0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)') \" ,\n Substitutions = {'Beauty -> (phi(1020) -> K+ K-) ^(rho(770)0 -> X+ X-)' : 'phi(1020)',\n 'Beauty -> (phi(1020) -> K+ K-) (X0 -> ^pi+ X-)' : 'K+',\n 'Beauty -> (phi(1020) -> K+ K-) (X0 -> X+ ^pi-)' : 'K-',\n 'Beauty -> (phi(1020) -> K+ K-) (X0 -> X+ X-)' : 'B_s0'})\n\n _ddChangeSel = Selection( \"_ddChangeSel\",\n Algorithm = _SubstituteB0,\n RequiredSelections = [_strippingOutput]) #[DataOnDemand(Location = \"/Event/AllStreams/Phys/BsPhiRhoLine/Particles\")])\n selSeq = Selection(\"selSeq\",\n Algorithm = FilterDesktop(\"BsPhiRhoFilter\", Code = newDecay),\n RequiredSelections = [_ddChangeSel])\n# selSeq = SelectionSequence(\"selseqname\", TopSelection = _ddChangeSel)\n\ntuple = DecayTreeTuple()\n\nif not IsMC:\n tuple.Inputs = [ \"/Event/Bhadron/Phys/BsPhiRhoLine/Particles\" ]\nelif not myDecayType and IsMC:\n tuple.Inputs = [ \"/Event/AllStreams/Phys/BsPhiRhoLine/Particles\" ]\nelif myDecayType and IsMC:\n tuple.Inputs = [ '/Event/Phys/selSeq/Particles' ]\n# tuple.Inputs = [ selSeq.outputLocation() ]\n\ntuple.ToolList += [\n# \"TupleToolMCTruth\",\n \"TupleToolMCBackgroundInfo\",\n \"TupleToolGeometry\"\n , \"TupleToolKinematic\"\n , \"TupleToolPropertime\"\n , \"TupleToolPrimaries\"\n , \"TupleToolPid\"\n , \"TupleToolTrackInfo\"\n , \"TupleToolTISTOS\"\n , \"TupleToolTrigger\" \n# , \"TupleToolTagging\"\n , \"TupleToolRecoStats\"\n# , \"TupleToolTrackIsolation\"\n ]\n\nif IsMC:\n tuple.ToolList += [ \"TupleToolMCTruth\", \"TupleToolTagging\", \"TupleToolTrackIsolation\"]\n\n# Trigger Lines interested in\ntlist = [\"L0HadronDecision\",\"L0MuonDecision\",\"L0DiMuonDecision\",\"L0ElectronDecision\",\"L0PhotonDecision\",\"Hlt1SingleHadronDecision\",\"Hlt1MBNoBiasDecision\",\"Hlt1DiHadronDecision\",\"Hlt1L0AnyDecision\",\"Hlt1TrackAllL0Decision\",\"Hlt2TopoOSTF4BodyDecision\",\"Hlt2IncPhiDecision\",\"Hlt2Topo4BodySimpleDecision\",\"Hlt2Topo3BodySimpleDecision\",\"Hlt2Topo3BodyBBDTDecision\",\"Hlt2Topo2BodySimpleDecision\",\"Hlt2Topo2BodyBBDTDecision\",\"Hlt2Topo4BodyBBDTDecision\",\"Hlt2TopoMu4BodyBBDTDecision\",\"Hlt2IncPhiSidebandsDecision\",\"Hlt2B2HHDecision\"]\n\n# Get trigger info\ntuple.addTool(TupleToolTrigger, name=\"TupleToolTrigger\")\ntuple.TupleToolTrigger.Verbose = True\ntuple.TupleToolTrigger.TriggerList = tlist\n\n# Get TISTOS info\ntuple.addTool(TupleToolTISTOS, name=\"TupleToolTISTOS\")\ntuple.TupleToolTISTOS.Verbose = True\ntuple.TupleToolTISTOS.TriggerList = tlist\n\nif IsMC:\n tuple.addTool(TupleToolTrackIsolation, name=\"TupleToolTrackIsolation\")\n tuple.TupleToolTrackIsolation.Verbose = True\n tuple.ToolList+=[\"TupleToolTrackIsolation/TupleToolTrackIsolation\"]\n\ntuple.Decay = \"[B0 -> ^(phi(1020) -> ^K+ ^K-) ^(rho(770)0 -> ^pi+ ^pi-)]CC\"\nif myDecayType == 1:\n tuple.Decay = \"[B_s0 -> ^(phi(1020) -> ^K+ ^K-) ^(rho(770)0 -> ^pi+ ^pi-)]CC\"\nelif myDecayType ==2 :\n tuple.Decay = \"[B_s0 -> ^(phi(1020) -> ^K+ ^K-) ^(f_0(980) -> ^pi+ ^pi-)]CC\"\nelif myDecayType == 3:\n tuple.Decay = \"[B_s0 -> ^(phi(1020) -> ^K+ ^K-) ^(phi(1020) -> ^K+ ^K-)]CC\"\n\nif myDecayType == 1:\n tuple.addBranches({\n \"Bs\" : \"^([B_s0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)]CC)\",\n \"f0\" : \" [B_s0 -> (phi(1020) -> K+ K-) ^(rho(770)0 -> pi+ pi-)]CC \"\n })\nelif myDecayType == 2:\n tuple.addBranches({\n \"Bs\" : \"^([B_s0 -> (phi(1020) -> K+ K-) (f_0(980) -> pi+ pi-)]CC)\",\n \"f0\" : \" [B_s0 -> (phi(1020) -> K+ K-) ^(f_0(980) -> pi+ pi-)]CC \"\n })\nelif myDecayType == 3:\n tuple.addBranches({\n \"Bs\" : \"^([B_s0 -> (phi(1020) -> K+ K-) (phi(1020) -> K+ K-)]CC)\",\n \"f0\" : \" [B_s0 -> (phi(1020) -> K+ K-) ^(phi(1020) -> K+ K-)]CC \",\n \"piplus\" : \" [B_s0 -> (phi(1020) -> K+ K-) (phi(1020) -> ^K+ K-)]CC \",\n \"piminus\" : \" [B_s0 -> (phi(1020) -> K+ K-) (phi(1020) -> K+ ^K-)]CC \"\n })\nelse:\n tuple.addBranches({\n \"Bs\" : \"^([B0 -> (phi(1020) -> K+ K-) (rho(770)0 -> pi+ pi-)]CC)\"\n ,\"f0\" : \" [B0 -> (phi(1020) -> K+ K-) ^(rho(770)0 -> pi+ pi-)]CC \"\n })\n\n#if IsMC:\nLoKiVariables2 = LoKi__Hybrid__TupleTool('LoKiVariables2')\nLoKiVariables2.Variables = {\n \"LOKI_Mass\" : \"DTF_FUN(M, True)\",\n \"LOKI_Chi2\" : \"DTF_CHI2(True)\",\n \"LOKI_ndof\" : \"DTF_NDOF(True)\",\n \"LOKI_MassError2\" : \"DTF_FUN(M2ERR2, True)\",\n \"LOKI_DTF_CTAU\" : \"DTF_CTAU( 0, True )\",\n \"LOKI_DTF_CTAUS\" : \"DTF_CTAUSIGNIFICANCE( 0, True )\",\n \"LOKI_DTF_CTAUERR\" : \"DTF_CTAUERR( 0, True )\",\n\n \"PX_kaon1\": \"DTF_FUN(CHILD(PX, 1,1), True)\",\n \"PY_kaon1\": \"DTF_FUN(CHILD(PY, 1,1), True)\",\n \"PZ_kaon1\": \"DTF_FUN(CHILD(PZ, 1,1), True)\",\n\n \"PX_kaon2\": \"DTF_FUN(CHILD(PX, 1,2), True)\",\n \"PY_kaon2\": \"DTF_FUN(CHILD(PY, 1,2), True)\",\n \"PZ_kaon2\": \"DTF_FUN(CHILD(PZ, 1,2), True)\",\n\n \"PX_pion1\": \"DTF_FUN(CHILD(PX, 2,1), True)\",\n \"PY_pion1\": \"DTF_FUN(CHILD(PY, 2,1), True)\",\n \"PZ_pion1\": \"DTF_FUN(CHILD(PZ, 2,1), True)\",\n\n \"PX_pion2\": \"DTF_FUN(CHILD(PX, 2,2), True)\",\n \"PY_pion2\": \"DTF_FUN(CHILD(PY, 2,2), True)\",\n \"PZ_pion2\": \"DTF_FUN(CHILD(PZ, 2,2), True)\",\n\n \"BCON_LOKI_Mass\" : \"DTF_FUN(M, True, strings(['B_s0']))\",\n \"BCON_LOKI_Chi2\" : \"DTF_CHI2(True, strings(['B_s0']))\",\n \"BCON_LOKI_ndof\" : \"DTF_NDOF(True, strings(['B_s0']))\",\n \"BCON_PX_kaon1\": \"DTF_FUN(CHILD(PX, 1,1), True, strings(['B_s0']))\",\n \"BCON_PY_kaon1\": \"DTF_FUN(CHILD(PY, 1,1), True, strings(['B_s0']))\",\n \"BCON_PZ_kaon1\": \"DTF_FUN(CHILD(PZ, 1,1), True, strings(['B_s0']))\",\n\n \"BCON_PX_kaon2\": \"DTF_FUN(CHILD(PX, 1,2), True, strings(['B_s0']))\",\n \"BCON_PY_kaon2\": \"DTF_FUN(CHILD(PY, 1,2), True, strings(['B_s0']))\",\n \"BCON_PZ_kaon2\": \"DTF_FUN(CHILD(PZ, 1,2), True, strings(['B_s0']))\",\n\n \"BCON_PX_pion1\": \"DTF_FUN(CHILD(PX, 2,1), True, strings(['B_s0']))\",\n \"BCON_PY_pion1\": \"DTF_FUN(CHILD(PY, 2,1), True, strings(['B_s0']))\",\n \"BCON_PZ_pion1\": \"DTF_FUN(CHILD(PZ, 2,1), True, strings(['B_s0']))\",\n\n \"BCON_PX_pion2\": \"DTF_FUN(CHILD(PX, 2,2), True, strings(['B_s0']))\",\n \"BCON_PY_pion2\": \"DTF_FUN(CHILD(PY, 2,2), True, strings(['B_s0']))\",\n \"BCON_PZ_pion2\": \"DTF_FUN(CHILD(PZ, 2,2), True, strings(['B_s0']))\"\n }\n\ntuple.addTool(LoKiVariables2 , name = 'LoKiVariables2' )\ntuple.ToolList += [ 'LoKi::Hybrid::TupleTool/LoKiVariables2']\n#LoKi_B=tuple.B_0.addTupleTool(\"LoKi::Hybrid::TupleTool/LoKi_B\")\n#LoKi_B.Variables = {\n# \"PID\" : \"ID\"\n# , \"BPVDIRA\" : \"BPVDIRA\"\n# , \"MassDiff_Bs0\" : \"DMASS('B_s0')\"\n#}\n\n#######################################################\nfrom Configurables import CondDB, CondDBAccessSvc\nCondDB().LatestGlobalTagByDataType = DataYear \n#CondDB(UseOracle = True, IgnoreHeartBeat = True)\n\n############################################\n#from Configurables import *\nfrom Configurables import LHCbApp\nLHCbApp().XMLSummary='summary.xml'\n\nfrom Configurables import DataOnDemandSvc\nfrom Configurables import L0SelReportsMaker, L0DecReportsMaker\nDataOnDemandSvc().AlgMap[\"HltLikeL0/DecReports\"] = L0DecReportsMaker( OutputLevel = 4 )\nDataOnDemandSvc().AlgMap[\"HltLikeL0/SelReports\"] = L0SelReportsMaker( OutputLevel = 4 )\n\nif myDecayType and IsMC:\n BsPhiRho_Sequence = GaudiSequencer(\"BsPhiRho_Sequence\")\n SeqBsPhiRho = SelectionSequence(\"SeqBsPhiRho\", TopSelection = selSeq)\n BsPhiRho_Sequence.Members += [SeqBsPhiRho.sequence()]\n BsPhiRho_Sequence.Members += [smear]\n BsPhiRho_Sequence.Members += [tuple]\n userAlgos.append(BsPhiRho_Sequence)\nelif not myDecayType and IsMC:\n userAlgos.append( smear )\n userAlgos.append( tuple )\nelif not IsMC:\n MySequencer.Members += [scaler]\n MySequencer.Members += [tuple]\n userAlgos.append(MySequencer)\n\nfrom Configurables import EventTuple\netuple = EventTuple()\nuserAlgos.append( HltSelReportsDecoder() )\nuserAlgos.append( HltVertexReportsDecoder() )\nuserAlgos.append( HltDecReportsDecoder() )\nuserAlgos.append( etuple )\n#etuple.ToolList = [ \"TupleToolEventInfo \"]\n\nmyTupleName = 'Bsphirho.root'\n'''\nmyTuple = ['Bdphirho', 'Bsphirho', 'Bsphif0', 'Bsphiphi']\nmyTupleName = myTuple[myDecayType] + '.root'\nif not IsMC: myTupleName = \"RE\" + myTuple[1] + '.root'\n# Necessary DaVinci parameters #################\n\nif ( DataYear == \"2012\" and not IsMC):\n DDDBtag = 'dddb-20120831'\n CondDBtag = 'cond-20120831'\nelif ( DataYear == \"2011\" and not IsMC):\n DDDBtag = 'dddb-20130111'\n CondDBtag = 'cond-20130114'\nif IsMC:\n DDDBtag = \"dddb-20120831\"\n CondDBtag = \"sim-20121025-vc-md100\"\n'''\ndv = DaVinci( \n# DDDBtag = DDDBtag,\n# CondDBtag = CondDBtag,\n HistogramFile = 'dummy.root',\n TupleFile = myTupleName,\n UserAlgorithms = userAlgos,# if Line == None else [stripSeq],\n DataType = DataYear,\n EvtMax = -1,\n InputType = 'DST' if IsMC else 'MDST',\n PrintFreq = 1000,\n Simulation = IsMC,\n Lumi = False if IsMC else True )\n'''\nif not IsMC:\n dv.DDDBtag = DDDBtag\n dv.CondDBtag = CondDBtag\n'''\n#dv.UserAlgorithms = userAlgos #BsPhiRho_Sequence]# scaler , tuple ]\n##########################################################\n#importOptions(\"/afs/cern.ch/user/h/hluo/cmtuser/MC2011/Bsphirho/MC201213104051Beam4000GeV-2012-MagDown-Nu25-Pythia8Sim08aDigi13Trig0x409f0045Reco14Stripping20NoPrescalingFlaggedSTREAMSDST.py\")\n#importOptions(\"/afs/cern.ch/user/h/hluo/cmtuser/MC2011/Bsphirho/Bsphirho_PFN.py\")\n##########################################################\n","repo_name":"admorris/BsphiKK","sub_path":"gridjobs/DaVinci/AllnTuples/myDown.py","file_name":"myDown.py","file_ext":"py","file_size_in_byte":11748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"22716585832","text":"import numpy as np\ndef logNormParam(data):\n '''\n Arguments:\n data : the data that the lognormal parameters are fitted to\n Returns:\n my, sigma : parameters of the lognormal distribution\n ------------------------------------------------------\n Function for finding the distribution parameters for data with a lognormal distribution\n ''' \n norm = np.log(data)\n my = np.mean(norm)\n sig = np.std(norm)\n \n return my, sig\n\n","repo_name":"emilnebb/AOMA_Halogaland","sub_path":"python_appendix/logNormalDist.py","file_name":"logNormalDist.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"65147798","text":"import numpy as np\n\nfrom smac.epm.base_epm import AbstractEPM\nfrom smac.optimizer.acquisition import AbstractAcquisitionFunction, EI\n\n\nclass TAF(AbstractAcquisitionFunction):\n\n def __init__(self, model: AbstractEPM):\n \"\"\"Transfer acquisition function from \"Scalable Gaussian process-based transfer surrogates\n for hyperparameter optimization\" by Wistuba, Schilling and Schmidt-Thieme,\n Machine Learning 2018, https://link.springer.com/article/10.1007/s10994-017-5684-y\n\n Works both with TST-R and RGPE weighting.\n \"\"\"\n\n super().__init__(model)\n self.long_name = 'Transfer Acquisition Function'\n self.eta = None\n self.acq = EI(model=None)\n\n def update(self, **kwargs):\n\n X = kwargs['X']\n prediction, _ = self.model.target_model.predict(X)\n self.incumbent_array = X[np.argmin(prediction)].reshape((1, -1))\n eta = np.min(prediction)\n assert (id(kwargs['model']) == id(self.model))\n kwargs = {}\n kwargs['model'] = self.model.target_model\n kwargs['eta'] = eta\n self.acq.model = None\n self.acq.update(**kwargs)\n best_values = []\n for weight, base_model in zip(self.model.weights_, self.model.base_models):\n if weight == 0:\n best_values.append(None)\n else:\n values, _ = base_model.predict(X)\n min_value = np.min(values)\n best_values.append(min_value)\n self.best_values = best_values\n\n def _compute(self, X: np.ndarray, **kwargs):\n\n ei = self.acq._compute(X)\n\n if self.model.weights_[-1] == 1:\n return ei\n\n else:\n improvements = []\n\n for weight, best_value, base_model in zip(self.model.weights_, self.best_values, self.model.base_models):\n if weight == 0:\n continue\n else:\n predictions, _ = base_model._predict(X, cov_return_type=None)\n improvement = np.maximum(best_value - predictions, 0).flatten() * weight\n improvements.append(improvement)\n\n improvements = np.sum(improvements, axis=0)\n\n rval = ei.flatten() * self.model.weights_[-1] + improvements\n rval = rval.reshape((-1, 1))\n\n return rval\n","repo_name":"automl/transfer-hpo-framework","sub_path":"rgpe/methods/taf.py","file_name":"taf.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"6287618050","text":"from collections import defaultdict\nimport os\nimport pandas as pd\nimport jsonpickle\nfrom hit import Hit\nfrom hit_list import orderHitsById\n\nscenarioName = 'debate'\nOUTPUT_DIR = os.path.join('plots', '{}-conversations'.format(scenarioName))\n\nrunName = '{}-conversations-1-live'.format(scenarioName)\ndf = pd.read_csv('hit-output/{}.assignments.csv'.format(runName), index_col=0)\ndf = df.loc[df['hitType'] == 'task']\ndf = df.loc[df['error'] != True]\ndf = df.loc[pd.isna(df['error'])]\n\nwith open('hit-data/{}.json'.format(runName), 'r') as f:\n hits = jsonpickle.decode(f.read(), keys=True, classes=Hit)\nhitIndex = orderHitsById(hits)\n\n# get flagged messages\nredFlags = []\nbadHits = defaultdict(int)\nfor idx, row in df.iterrows():\n hit = hitIndex[row['hitId']]\n turnCount = len(hit.getBotTurns(isConst=False))\n for styleIndex in [1, 2]:\n styleName = row['style{}'.format(styleIndex)]\n for flag in ['Offensive[]', 'Incoherent[]']:\n flagColumn = 'bot{}{}'.format(styleIndex, flag)\n\n flagValue = row[flagColumn]\n if (pd.notna(flagValue) and len(flagValue) > 0):\n flags = flagValue.split('|')\n \n for turnId in flags:\n redFlags.append({\n 'style': styleName,\n 'hitId': row['hitId'],\n 'turnId': turnId,\n 'flag': flag.replace('[]', '')\n })\n badHits[row['hitId']] += 1\n\nredFlags = pd.DataFrame(redFlags)\n\nbadHitList = sorted(badHits.items(), key=lambda x: x[1], reverse=True)\n\nprint(badHitList[3])\n\n\nabspath = os.path.abspath(__file__)\ndname = os.path.dirname(abspath)\n\ncurrentTask = 'style'\nwith open(os.path.join(dname, 'templates', 'hit', currentTask, 'hit.html'), 'r') as f:\n fileTemplate = f.read()\nwith open(os.path.join(dname, 'templates', 'hit', currentTask, 'turn.html'), 'r') as f:\n turnTemplate = f.read()\nwith open(os.path.join(dname, 'templates', 'question.xml')) as f:\n questionTemplate = f.read()\n\nfor idx, (hitId, flagCount) in enumerate(badHitList[:10]):\n hit = hitIndex[hitId]\n html = hit.generateHtmlQuestion(fileTemplate, turnTemplate)\n for part in questionTemplate.split('%htmlContent%'):\n html = html.replace(part, '')\n df = redFlags\n style = df.loc[df['hitId'] == hitId].iloc[0]['style']\n targetPath = 'temp/bad-hits/hit-{}-{}-{}.html'.format(idx, style, flagCount)\n with open(targetPath, 'w') as f:\n f.write(html)","repo_name":"caisa-lab/style-transfer-chatbots","sub_path":"human-eval/find-flagged-messages.py","file_name":"find-flagged-messages.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19477992607","text":"#!/usr/bin/python3\n\nimport json\nimport sys\nimport re\n\ndef main():\n if len(sys.argv) < 3:\n print(\"Usage: python {} \".format(sys.argv[0]))\n return\n\n y = open(sys.argv[1], \"r\").read()\n d = json.loads(y)\n\n new_data = {}\n keys = []\n max_mem = 0\n for codec, test_result in d.items():\n # if not device metadata\n if codec == \"?\":\n continue\n\n if re.match(\"^.+?-\\d+\", codec):\n # quality / level\n idx = codec.rfind(\"-\")\n name = codec[:idx]\n level = codec[idx + 1 : ]\n else:\n name = codec\n level = \"\"\n\n if name not in new_data:\n new_data[name] = []\n keys.append(name)\n \n ratio = test_result[\"*\"][\"size\"] / test_result[\"*\"][\"compressed_size\"]\n c_speed = test_result[\"*\"][\"size\"] / test_result[\"*\"][\"compressed_time\"]\n dc_speed = test_result[\"*\"][\"size\"] / test_result[\"*\"][\"decompressed_time\"]\n\n mem_usage = test_result[\"?\"][\"mem_usage\"]\n max_mem = max(max(mem_usage), max_mem)\n\n interval = test_result[\"?\"][\"interval\"]\n\n start_process = test_result[\"?\"][\"start_process\"]\n end_process = test_result[\"?\"][\"end_process\"]\n\n # start time capture when spawning process\n start_process_idx = 0\n end_process_idx = int((end_process - start_process) / interval)\n if end_process_idx >= len(mem_usage):\n # in case we didn't capture full mem usage during the life of process\n end_process_idx = len(mem_usage) - 1\n print(\"[!] end_process not in range\")\n\n start_test = test_result[\"*\"][\"start_test\"]\n end_test = test_result[\"*\"][\"end_test\"]\n\n # start_process < start_test < end_test < end_process\n start_test_idx = int((start_test - start_process) / interval)\n if start_test_idx < start_process_idx:\n # this is impossible, just to make sure. remember we delay 0.5 after read data into memory\n start_test_idx = start_process_idx\n print(\"[!] start_test < start_process\")\n\n end_test_idx = int((end_test - start_process) / interval)\n if end_test_idx > end_process_idx:\n # this is impossible, just to make sure. we also delay 0.5 after tests are done\n end_test_idx = end_process_idx\n print(\"[!] end_test > end_process\")\n\n comp_arr = []\n decomp_arr = []\n\n for fn, record in test_result.items():\n if fn in (\"*\", \"?\"):\n continue\n start_time = record[\"start_time\"]\n mid_time = record[\"mid_time\"]\n end_time = record[\"end_time\"]\n\n # start_test < start_time < mid_time < end_time < end_test\n start_time_idx = int((start_time - start_process) / interval)\n if start_time_idx < start_test_idx:\n start_time_idx = start_test_idx\n print(\"[!] ... start_time < start_test\")\n\n end_time_idx = int((end_time - start_process) / interval)\n if end_time_idx > end_test_idx:\n end_time_idx = end_test_idx\n print(\"[!] ... end_time > end_test\")\n\n mid_time_idx = int((mid_time - start_process) / interval)\n if not (start_time_idx <= mid_time_idx and mid_time_idx <= end_time_idx):\n mid_time_idx = int((start_time_idx + end_time_idx) / 2)\n print(\"[!] ... mid_time not in [start_time, end_time]\")\n\n comp_arr.append((start_time_idx, mid_time_idx))\n decomp_arr.append((mid_time_idx, end_time_idx))\n\n new_data[name].append({\n \"codec\": codec,\n \"level\": level,\n \"compression_rate\": c_speed,\n \"decompression_rate\": dc_speed,\n \"ratio\": ratio,\n \"mem_usage\": mem_usage,\n \"mem_state\": {\n \"compression\": comp_arr,\n \"decompression\": decomp_arr,\n \"test\": (start_test_idx, end_test_idx),\n \"process\": (start_process_idx, end_process_idx),\n },\n })\n\n max_mem = (max_mem / 100 + 1) * 100\n x = open(\"chart.html\", \"r\").read()\n x = x.replace(\"replace_this_data\", json.dumps(new_data))\n x = x.replace(\"replace_this_keys\", json.dumps(keys))\n x = x.replace(\"replace_this_max\", json.dumps(max_mem))\n x = x.replace(\"replace_this_device\", json.dumps(d[\"?\"]))\n\n open(sys.argv[2], \"w\").write(x)\n\n print(\"OK\")\n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"trichimtrich/PyCompressTest","sub_path":"chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"7090214428","text":"class Solution:\n def minSubArrayLen(self, target: int, nums: List[int]) -> int:\n min_length = inf\n current_sum = 0\n \n left = 0\n for right in range(len(nums)):\n current_sum += nums[right]\n \n while current_sum >= target:\n min_length = min(min_length, right - left + 1)\n current_sum -= nums[left]\n left += 1\n \n return 0 if min_length == inf else min_length","repo_name":"ffekirnew/a2sv-competitive-programming","sub_path":"209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.py","file_name":"209-minimum-size-subarray-sum.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"38094549266","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nfrom absl import flags\n\nimport tensorflow as tf\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nfrom object_detection import model_hparams\nfrom object_detection import model_lib\n\nprint('model_main.py, tensorflow version: {}'.format(tf.__version__))\n\n# substitute the AML data reference mount points for relevant parts in the pipeline.config\nactual_path_artifacts = os.environ.get('AZUREML_DATAREFERENCE_artifacts')\nactual_path_tfrecords = os.environ.get('AZUREML_DATAREFERENCE_tfrecords_mdv4_1')\nprint('model_main.py, AZUREML_DATAREFERENCE_artifacts is {}'.format(actual_path_artifacts))\nprint('model_main.py, AZUREML_DATAREFERENCE_tfrecords is {}'.format(actual_path_tfrecords))\nprint('Listing artifacts:')\nartifacts_content = os.listdir(actual_path_artifacts)\nfor i in artifacts_content:\n print(i)\ntfrecords_content = os.listdir(actual_path_tfrecords)\nprint('len of tfrecords:', len(tfrecords_content))\nif len(tfrecords_content) > 0:\n print(tfrecords_content[0])\n print(tfrecords_content[-1])\n\nprint('end of mount point checking...')\n\nflags.DEFINE_string(\n 'model_dir', None, 'Path to output model directory '\n 'where event and checkpoint files will be written.')\nflags.DEFINE_string('pipeline_config_path', None, 'Path to pipeline config '\n 'file.')\nflags.DEFINE_integer('num_train_steps', None, 'Number of train steps.')\nflags.DEFINE_boolean('eval_training_data', False,\n 'If training data should be evaluated for this job. Note '\n 'that one call only use this in eval-only mode, and '\n '`checkpoint_dir` must be supplied.')\nflags.DEFINE_integer('sample_1_of_n_eval_examples', 1, 'Will sample one of '\n 'every n eval input examples, where n is provided.')\nflags.DEFINE_integer('sample_1_of_n_eval_on_train_examples', 5, 'Will sample '\n 'one of every n train input examples for evaluation, '\n 'where n is provided. This is only used if '\n '`eval_training_data` is True.')\nflags.DEFINE_string(\n 'hparams_overrides', None, 'Hyperparameter overrides, '\n 'represented as a string containing comma-separated '\n 'hparam_name=value pairs.')\nflags.DEFINE_string(\n 'checkpoint_dir', None, 'Path to directory holding a checkpoint. If '\n '`checkpoint_dir` is provided, this binary operates in eval-only mode, '\n 'writing resulting metrics to `model_dir`.')\nflags.DEFINE_boolean(\n 'run_once', False, 'If running in eval-only mode, whether to run just '\n 'one round of eval vs running continuously (default).'\n)\nFLAGS = flags.FLAGS\n\n\ndef main(unused_argv):\n flags.mark_flag_as_required('model_dir')\n flags.mark_flag_as_required('pipeline_config_path')\n\n # substitute the AML data reference mount points for relevant parts in the pipeline.config and overwrite\n with open(FLAGS.pipeline_config_path) as f:\n config_file = f.read()\n new_config_file = config_file.replace(\n '$AZUREML_DATAREFERENCE_tfrecords', actual_path_tfrecords).replace(\n '$AZUREML_DATAREFERENCE_artifacts', actual_path_artifacts)\n with open(FLAGS.pipeline_config_path, 'w') as f:\n f.write(new_config_file)\n print('model_main.py, main(), finished substituting mount points.')\n\n config = tf.estimator.RunConfig(\n model_dir=FLAGS.model_dir,\n save_checkpoints_steps= 104012 # save less often than default - 1/5 of an epoch\n )\n\n train_and_eval_dict = model_lib.create_estimator_and_inputs(\n run_config=config,\n hparams=model_hparams.create_hparams(FLAGS.hparams_overrides),\n pipeline_config_path=FLAGS.pipeline_config_path,\n train_steps=FLAGS.num_train_steps,\n sample_1_of_n_eval_examples=FLAGS.sample_1_of_n_eval_examples,\n sample_1_of_n_eval_on_train_examples=(\n FLAGS.sample_1_of_n_eval_on_train_examples))\n estimator = train_and_eval_dict['estimator']\n train_input_fn = train_and_eval_dict['train_input_fn']\n eval_input_fns = train_and_eval_dict['eval_input_fns']\n eval_on_train_input_fn = train_and_eval_dict['eval_on_train_input_fn']\n predict_input_fn = train_and_eval_dict['predict_input_fn']\n train_steps = train_and_eval_dict['train_steps']\n\n if FLAGS.checkpoint_dir:\n if FLAGS.eval_training_data:\n name = 'training_data'\n input_fn = eval_on_train_input_fn\n else:\n name = 'validation_data'\n # The first eval input will be evaluated.\n input_fn = eval_input_fns[0]\n if FLAGS.run_once:\n estimator.evaluate(input_fn,\n steps=None,\n checkpoint_path=tf.train.latest_checkpoint(\n FLAGS.checkpoint_dir))\n else:\n model_lib.continuous_eval(estimator, FLAGS.checkpoint_dir, input_fn,\n train_steps, name)\n else:\n train_spec, eval_specs = model_lib.create_train_and_eval_specs(\n train_input_fn,\n eval_input_fns,\n eval_on_train_input_fn,\n predict_input_fn,\n train_steps,\n eval_on_train_data=False)\n\n # Currently only a single Eval Spec is allowed.\n\n # throttle_secs is not documented in eval.proto. This replaces eval_interval_secs somewhat\n throttle_secs = 60 * 60 # every 60 min\n\n eval_spec = eval_specs[0]\n\n my_eval_spec = tf.estimator.EvalSpec(\n name=eval_spec.name,\n input_fn=eval_spec.input_fn,\n steps=None,\n exporters=eval_spec.exporters,\n start_delay_secs=1800, # 30 minutes - does not seem to be respected...\n throttle_secs=throttle_secs)\n\n print('=========== my_eval_spec')\n print(my_eval_spec)\n print('=========================')\n\n tf.estimator.train_and_evaluate(estimator, train_spec, my_eval_spec)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"bhlab/SpSeg","sub_path":"tools/detection/detector_training/model_main.py","file_name":"model_main.py","file_ext":"py","file_size_in_byte":6442,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"14050498149","text":"import streamlit as st\r\n\r\nfrom web_functions import predict\r\n\r\ndef app(df, x, y):\r\n\r\n st.title(\"Halaman Prediksi\")\r\n\r\n col1, col2= st.columns(2)\r\n\r\n with col1:\r\n a_AU = st.text_input ('input nilai Jarak semimayor objek astronomi dalam satuan astronomi (AU))')\r\n with col1:\r\n e = st.text_input ('input nilai Eksentrisitas orbit objek astronomi')\r\n with col1:\r\n i_deg = st.text_input ('input nilai Inklinasi orbit objek astronomi dalam derajat')\r\n with col1:\r\n w_deg = st.text_input ('input nilai Argumen perihelion objek astronomi dalam derajat')\r\n with col1:\r\n Node_deg = st.text_input ('input nilai Longitudinal node objek astronomi dalam derajat')\r\n with col2:\r\n M_deg = st.text_input ('input nilai Anomali rata-rata objek astronomi dalam derajat')\r\n with col2:\r\n q_AU = st.text_input ('input nilai Jarak perihelion objek astronomi dalam satuan astronomi (AU)')\r\n with col2:\r\n Q_AU = st.text_input ('input nilai Jarak aphelion objek astronomi dalam satuan astronomi (AU)')\r\n with col2:\r\n P_yr = st.text_input ('input nilai Periode orbit objek astronomi dalam tahun')\r\n with col2:\r\n H_mag = st.text_input ('input nilai Magnitudo absolut objek astronomi')\r\n with col2:\r\n MOID_AU = st.text_input ('input nilai Minimum Orbit Intersection Distance')\r\n\r\n features = [a_AU,e,i_deg,w_deg,Node_deg,M_deg,q_AU,Q_AU,P_yr,H_mag,MOID_AU]\r\n\r\n #tombol\r\n if st.button(\"prediksi orbit\"):\r\n prediction, score = predict(x,y,features)\r\n score = score\r\n st.info(\"prediksi berhasil\")\r\n\r\n if (prediction[0]==0):\r\n st.warning(\"Asteroid Main Belt (AMO*)\")\r\n elif (prediction[0]==1):\r\n st.warning(\"Asteroid Perihelion Object (APO)\")\r\n elif (prediction[0]==2):\r\n st.warning(\"kelompok Asteroid Aten (APO*)\")\r\n elif (prediction[0]==3):\r\n st.warning(\"Asteroid Apohele (ATE)\")\r\n elif (prediction[0]==4):\r\n st.warning(\"kelompok Asteroid Atira (ATE*)\")\r\n else:\r\n st.success(\"Inner-Earth Object (IEO*)\")\r\n \r\n st.write(\"model akurasi\", (score*100), \"%\")","repo_name":"mhdArdiansyah/klasifikasi_orbit","sub_path":"Tabs/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25928459371","text":"# isdigit == check which is a numbers and return True\ndef demo_isdigit(p):\n total = 0\n for c in p:\n # print(c)\n if c.isdigit():\n # print(c)\n total += int(c)\n return total\n\n\nplate = \"ASVS 4567\"\nprint(demo_isdigit(plate))","repo_name":"Sorananakiii/PythonProgramming","sub_path":"1_Basic_Level/5_Strings/54_isdigit.py","file_name":"54_isdigit.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20560018301","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nnum = (1, 22, 333, 4444, 55555, 66, 71)\ncount_odd = 0\ncount_even = 0\nfor i in num:\n if not i % 2:\n count_even+=1\n else:\n count_odd+=1\nprint(\"num of even numbers :\", count_even)\nprint(\"num of odd numbers :\", count_odd)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"santhosh4456/odd_even_count","sub_path":"num of odd and evn assign.py","file_name":"num of odd and evn assign.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23275866506","text":"class PRODUCTS:\n \n \n \n def __init__(self):\n \n self.__items = {\n\t\t\t'R01' : 32.95,\n\t\t\t'G01' : 24.95,\n\t\t\t'B01' : 7.95,\n \t\t}\n self.basket = {}\n self.sum = 0\n \n @staticmethod\n def ship_costs(costs=0):\n \n if costs > 90:\n charge = 0\n elif costs >= 50 and costs < 90:\n charge = 2.95\n elif costs < 50 and costs >= 0:\n charge = 4.95\n else:\n charge = -1\n return charge \n \n def add(self, item):\n \n if item not in self.__items:\n return -1\n \n if item in self.basket:\n self.basket[item] += 1\n else:\n self.basket[item] = 1\n \n return 0\n \n def total(self):\n \n if not self.basket:\n return self.sum\n self.offers()\n print(self.basket)\n \n for key in self.basket:\n self.sum += self.basket[key] * self.__items[key] \n \n self.sum += self.ship_costs(self.sum)\n self.sum = round(self.sum, 2)\n return self.sum\n \n def offers(self):\n red_item = self.basket.get('R01')\n \n if not red_item:\n return \n \n if red_item > 1 and red_item % 2 == 0:\n self.basket['R01'] = red_item // 2 + 0.5\n elif red_item > 1 and red_item % 2 == 1:\n self.basket['R01'] = red_item // 2 + 0.5 + 1\n ","repo_name":"dini-rockz93/Astronomer_Problem_solving","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10148023596","text":"from ps2_census.constants import Command\nfrom ps2_census.utils import bool2str, command_key\n\n\ndef test_command_key():\n res = command_key(Command.HAS, prefix=\"c:\")\n assert res == \"c:has\"\n\n\ndef test_bool2str():\n tr = bool2str(True)\n fa = bool2str(False)\n\n assert tr == \"true\"\n assert fa == \"false\"\n","repo_name":"spascou/ps2-census","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"25904510211","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^search/tags/(?P(.)+)/$', views.tagged_posts, name='tagged_post'),\n url(r'^search/users/(?P(.)+)/$', views.users_posts, name='users_post'),\n]\n","repo_name":"NA5G/coco-server-was","sub_path":"coco/dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15452297496","text":"import re\n\nfile = \"./Day7/input.txt\"\nfinalAnswer = 0\ninput = []\ncrabs = []\n\ndef parse():\n with open(file) as f:\n for line in f:\n input.extend(re.split(\",\",line.strip()))\n for i in input:\n crabs.append(int(i))\n\ndef part1():\n crabs.sort()\n min = crabs[0]\n max = crabs[len(crabs)-1]\n bestMove = 100000000000\n for i in range(min,max+1):\n curMoves = 0\n for crab in crabs:\n curMoves += abs(crab - i)\n if(curMoves < bestMove):\n bestMove = curMoves\n print(bestMove)\n\ndef countMove(count):\n total = 0\n if count % 2 == 0:\n #even\n total = (count / 2) * (count + 1)\n else:\n total = countMove(count - 1) + count\n return int(total)\n\ndef part2():\n crabs.sort()\n min = crabs[0]\n max = crabs[len(crabs)-1]\n bestMove = 100000000000\n for i in range(min,max+1):\n curMoves = 0\n for crab in crabs:\n curMoves += countMove(abs(crab - i))\n if(curMoves < bestMove):\n bestMove = curMoves\n print(bestMove)\n\nif __name__ == '__main__':\n parse()\n part2()","repo_name":"Acellama88/AoC-2021","sub_path":"Day7/Day7.py","file_name":"Day7.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14832499799","text":"import pickle\nfrom typing import Dict, Optional, List, Tuple, Set\nimport os\nimport re\nimport json\nfrom tqdm import tqdm\nimport pandas\n\nfrom pre_process_utils import (\n process_articles, process_raw_text, html_to_latex, wrap_formulas, remove_calculator_annotations, get_boxed_answer,\n all_latexml_errs, all_tangent_cft_errs\n)\nfrom vocabulary import Vocabulary\nfrom data_types import Article, GenTaskSample, AnswerScoringSample, FeedbackTaskSample, ProblemSolvingTaskSample, CTTaskSample\nfrom constants import (\n FORMULA_IDENTIFIER, DATA, WIKI_DATA, AS_PROBLEMS, AS_ANSWERS, FEEDBACK_PROBLEMS, FEEDBACK_SAMPLES, GSM8K_DATA, MATH_DATA, MWP_DATA, KHAN_DATA, CT_DATA\n)\n\n# Import after pre_process_utils since module overloading done there\nfrom TangentCFT.TangentS.math_tan.math_document import MathDocument\n\ndef dump_errs(err_filename: str, err_data: dict):\n os.makedirs(\"results\", exist_ok=True)\n with open(os.path.join(\"results\", err_filename), \"w\", encoding=\"utf-8\") as err_file:\n json.dump({\n **err_data,\n \"all_latexml_errs\": all_latexml_errs,\n \"all_tangent_cft_errs\": all_tangent_cft_errs,\n }, err_file, indent=2, ensure_ascii=False)\n\ndef process_wikipedia_data():\n \"\"\"\n Process all data files in the wikipedia dataset\n \"\"\"\n print(\"Gathering articles...\")\n article_filenames: List[str] = []\n root_dir = \"../NTCIR12_MathIR_WikiCorpus_v2.1.0/MathTagArticles\"\n for article_group in os.listdir(root_dir):\n article_group_dir = os.path.join(root_dir, article_group, \"Articles\")\n if not os.path.isdir(article_group_dir):\n continue\n for _, article in enumerate(os.listdir(article_group_dir)):\n article_filename = os.path.join(article_group_dir, article)\n if article_filename.endswith(\".html\"):\n article_filenames.append(article_filename)\n\n print(\"Processing articles...\")\n err_data = {\n \"formulas_missing\": 0,\n }\n max_articles = len(article_filenames)\n for article_filename in tqdm(article_filenames[:max_articles]):\n _, content = MathDocument.read_doc_file(article_filename)\n article_data = process_articles(content)[0]\n form_diff = article_data[\"text\"].count(FORMULA_IDENTIFIER) - len(article_data[\"formulas\"])\n if form_diff > 0:\n err_data[\"articles_missing_formulas\"] += 1\n err_data[\"formulas_missing\"] += form_diff\n out_filename = os.path.basename(article_filename).replace(\".html\", \".json\")\n with open(os.path.join(WIKI_DATA, out_filename), \"w\", encoding=\"utf-8\") as out_file:\n json.dump(article_data, out_file, indent=2, ensure_ascii=False)\n\n # Dump vocab to file\n Vocabulary.dump()\n\n dump_errs(\"wiki_errs.json\", err_data)\n\ndef process_mathsum_data(dataset: str):\n \"\"\"\n Process all data files in the MathSum datasets\n \"\"\"\n batch_size: Optional[int] = 40\n err_data: Dict[str, Dict[str, int]] = {}\n root_dir = \"../MathSum\"\n print(\"Processing\", dataset)\n for split in (\"train\", \"val\", \"test\"):\n print(\"Processing\", split, \"split\")\n cur_err_data = err_data[f\"{dataset},{split}\"] = {}\n post_filename = os.path.join(root_dir, dataset, f\"post.{split}\")\n title_filename = os.path.join(root_dir, dataset, f\"title.{split}\")\n out_filename = os.path.join(DATA, dataset, f\"{split}.json\")\n samples: List[GenTaskSample] = []\n with open(post_filename, encoding=\"utf-8\") as post_file:\n with open(title_filename, encoding=\"utf-8\") as title_file:\n all_posts = post_file.readlines()\n all_titles = title_file.readlines()\n # These samples have invalid syntax that breaks LaTeXML\n if split == \"train\" and dataset == \"OFEQ-10k\":\n erroneous_samples = [5276, 6707]\n for sample_num, sample_idx in enumerate(erroneous_samples):\n all_posts = all_posts[:sample_idx - sample_num] + all_posts[sample_idx - sample_num + 1:]\n all_titles = all_titles[:sample_idx - sample_num] + all_titles[sample_idx - sample_num + 1:]\n # Batching speeds things up a lot, but causes a single LaTeXML error to ruin the whole batch\n if batch_size:\n for batch_start_idx in tqdm(list(range(0, len(all_posts), batch_size))):\n cur_batch = all_posts[batch_start_idx : batch_start_idx + batch_size] +\\\n all_titles[batch_start_idx : batch_start_idx + batch_size]\n cur_batch_size = len(cur_batch) // 2\n try:\n processed_batch = process_raw_text(cur_batch, cur_err_data)\n samples += [{\n \"prompt\": processed_batch[idx],\n \"label\": processed_batch[idx + cur_batch_size]\n } for idx in range(cur_batch_size)]\n except Exception:\n pass\n else:\n for post, title in tqdm(list(zip(all_posts, all_titles))):\n samples.append({\n \"prompt\": process_raw_text([post], cur_err_data)[0],\n \"label\": process_raw_text([title], cur_err_data)[0]\n })\n\n with open(out_filename, \"w\", encoding=\"utf-8\") as out_file:\n json.dump(samples, out_file, indent=2, ensure_ascii=False)\n\n dump_errs(f\"{dataset}_errs.json\", err_data)\n\ndef process_probes():\n \"\"\"\n Process all LM probes\n \"\"\"\n with open(\"data/probes.txt\", encoding=\"utf-8\") as src_prompt_file:\n src_probes = src_prompt_file.readlines()\n err_data = {}\n processed_probes = process_raw_text(src_probes, err_data)\n print(err_data)\n print(all_latexml_errs)\n print(all_tangent_cft_errs)\n with open(\"data/probes.json\", \"w\", encoding=\"utf-8\") as processed_prompt_file:\n json.dump(processed_probes, processed_prompt_file, indent=2, ensure_ascii=False)\n\ndef process_answer_scoring_data():\n \"\"\"\n Process all data in the answer scoring dataset\n \"\"\"\n # df = pandas.read_csv(\"../qc_full_meta_clean.csv\", encoding=\"utf-8\")\n df = pandas.read_csv(\"../qc_clean.csv\", encoding=\"utf-8\")\n # df = pandas.read_csv(\"../before_rasch.csv\", encoding=\"utf-8\")\n\n # Do some initial analysis on the dataset\n esc_pat = re.compile(r\"&[#a-z0-9]*;\")\n tag_pat = re.compile(r\"<[a-z0-9]*[> /]\")\n found_escs = set()\n found_tags = set()\n def match(text):\n for match in esc_pat.findall(text):\n found_escs.add(match)\n for match in tag_pat.findall(text):\n found_tags.add(match)\n df[\"raw_full_problem\"].apply(match)\n df[\"raw_answer_text\"].apply(match)\n print(\"All escs:\", found_escs)\n print(\"All tags:\", found_tags)\n print(\"Grade Range:\", df[\"grade\"].min(), \"-\", df[\"grade\"].max())\n print(\"Num problems:\", df[\"problem_id\"].unique().size)\n print(\"Num problem logs:\", df[\"problem_log_id\"].unique().size)\n print(\"Num to keep:\", sum(df[\"keep\"]))\n print(\"Total size:\", df.shape[0])\n\n # Convert problem and answer html to latex, which includes identifying and wrapping formulas\n print(\"Coverting problem HTML...\")\n df[\"full_problem_latex\"] = df[\"raw_full_problem\"].apply(html_to_latex)\n print(\"Extracting problem formulas...\")\n df[\"full_problem_latex\"] = df[\"full_problem_latex\"].apply(wrap_formulas)\n print(\"Coverting answer HTML...\")\n df[\"answer_latex\"] = df[\"raw_answer_text\"].apply(html_to_latex)\n print(\"Extracting answer formulas...\")\n df[\"answer_latex\"] = df[\"answer_latex\"].apply(wrap_formulas)\n\n err_data = {}\n batch_size = 100\n\n # Do tree conversion on all problems and store in lookup file\n print(\"Final processing on problem text...\")\n raw_problems: List[Tuple[int, str]] = list({(row[\"problem_id\"], row[\"full_problem_latex\"]) for _, row in df.iterrows()})\n if batch_size:\n problems: Dict[int, Article] = {}\n for batch_start_idx in tqdm(list(range(0, len(raw_problems), batch_size))):\n cur_batch = raw_problems[batch_start_idx : batch_start_idx + batch_size]\n processed_batch = process_raw_text([problem_latex for _, problem_latex in cur_batch], err_data)\n for idx, (problem_id, _) in enumerate(cur_batch):\n problems[problem_id] = processed_batch[idx]\n else:\n problems = {\n problem_id: process_raw_text([problem_latex], err_data)[0]\n for problem_id, problem_latex in tqdm(raw_problems)\n }\n with open(AS_PROBLEMS, \"w\", encoding=\"utf-8\") as problem_file:\n json.dump(problems, problem_file, indent=2, ensure_ascii=False)\n\n # Do tree conversion on all answers and save related data\n print(\"Final processing on answer text...\")\n samples: List[AnswerScoringSample] = []\n if batch_size:\n for batch_start_idx in tqdm(list(range(0, df.shape[0], batch_size))):\n cur_batch = df[\"answer_latex\"].iloc[batch_start_idx : batch_start_idx + batch_size]\n processed_batch = process_raw_text(cur_batch, err_data)\n samples += [{\n \"answer\": processed_answer,\n \"problem_id\": int(df[\"problem_id\"].iloc[batch_start_idx + idx]),\n \"problem_log_id\": int(df[\"problem_log_id\"].iloc[batch_start_idx + idx]),\n \"grade\": int(df[\"grade\"].iloc[batch_start_idx + idx]) - 1,\n } for idx, processed_answer in enumerate(processed_batch)]\n else:\n for _, row in tqdm(df.iterrows(), total=df.shape[0]):\n samples.append({\n \"answer\": process_raw_text([row[\"answer_latex\"]], err_data)[0],\n \"problem_id\": row[\"problem_id\"],\n \"problem_log_id\": row[\"problem_log_id\"],\n \"grade\": row[\"grade\"] - 1,\n })\n with open(AS_ANSWERS, \"w\", encoding=\"utf-8\") as answer_file:\n json.dump(samples, answer_file, indent=2, ensure_ascii=False)\n\n dump_errs(\"answer_scoring_errs.json\", err_data)\n\ndef process_feedback_data():\n \"\"\"\n Process all data in the feedback dataset\n \"\"\"\n df = pandas.read_csv(\"../common wrong answer feedback with all parts.csv\", encoding=\"utf-8\")\n\n # Do some initial analysis on the dataset\n esc_pat = re.compile(r\"&[#a-z0-9]*;\")\n tag_pat = re.compile(r\"<[a-z0-9]*[> /]\")\n found_escs = set()\n found_tags = set()\n def match(text):\n text_str = str(text)\n for match in esc_pat.findall(text_str):\n found_escs.add(match)\n for match in tag_pat.findall(text_str):\n found_tags.add(match)\n for field in [\"body\", \"cwa_1\", \"cwa_1_feedback\", \"cwa_2\", \"cwa_2_feedback\", \"cwa_3\", \"cwa_3_feedback\"]:\n df[field].apply(match)\n print(\"All escs:\", found_escs)\n print(\"All tags:\", found_tags)\n print(\"Unique problems:\", df[\"problem_code\"].unique().size, \"; with sub-parts:\", df[\"problem_id\"].unique().size)\n\n # Create a copy of the csv with post-processed fields\n # df_proc = df.copy()\n # for field in [\"body\", \"cwa_1_feedback\", \"cwa_2_feedback\", \"cwa_3_feedback\"]:\n # df_proc[field] = df_proc[field].apply(lambda val: html_to_latex(val) if isinstance(val, str) else val)\n # df_proc.to_csv(\"../feedback_proc.csv\")\n # return\n\n # Extract all problems, answers and feedback, and do HTML to LaTeX and formula wrapping\n df.sort_values([\"problem_code\", \"problem_part\"]) # Ensure that question parts are adjacent and in order\n seen_problems: Set[int] = set()\n skipped: List[int] = []\n pid_ptext: List[Tuple[int, str]] = []\n unprocessed_samples: List[dict] = []\n cur_problem_code = None\n cur_problem_head_text = \"\"\n for _, row in tqdm(df.iterrows(), total=df.shape[0]):\n # Skip repeats in the dataset - they don't have unique answers/feedback\n if row[\"problem_id\"] in seen_problems:\n continue\n seen_problems.add(row[\"problem_id\"])\n\n # Process current problem part\n raw_problem = str(row[\"body\"]).replace(\"\\\\n\", \" \").replace(\"\\\\r\", \" \")\n processed_problem_text = wrap_formulas(html_to_latex(raw_problem))\n if not processed_problem_text or processed_problem_text.isspace(): # Skip empty problem bodies - can happen with unparseable images\n skipped.append(row[\"problem_id\"])\n continue\n\n # Start new problem group if necessary, take problem body of first part to be header for remaining parts\n if row[\"problem_code\"] != cur_problem_code:\n cur_problem_code = row[\"problem_code\"]\n cur_problem_head_text = processed_problem_text\n pid_ptext.append((row[\"problem_id\"], processed_problem_text))\n else:\n pid_ptext.append((row[\"problem_id\"], cur_problem_head_text + processed_problem_text))\n\n # Process answers\n for cwa_field in [\"cwa_1\", \"cwa_2\", \"cwa_3\"]:\n raw_answer = str(row[cwa_field]).replace(\"\\\\n\", \" \").replace(\"\\\\r\", \" \")\n raw_feedback = str(row[cwa_field + \"_feedback\"]).replace(\"\\\\n\", \" \").replace(\"\\\\r\", \" \")\n if raw_answer in (\"null\", \"nan\", \"#ERROR!\") or raw_feedback == \"nan\":\n continue\n unprocessed_samples.append({\n \"problem_id\": row[\"problem_id\"],\n \"problem_code\": row[\"problem_code\"],\n \"answer\": wrap_formulas(html_to_latex(raw_answer)),\n \"feedback\": wrap_formulas(html_to_latex(raw_feedback)),\n })\n\n # Do batch LaTeXML/TangentCFT processing, write problems and samples to output files\n err_data = {}\n batch_size = 40\n pid_to_problem: Dict[int, Article] = {}\n for batch_start_idx in tqdm(range(0, len(pid_ptext), batch_size)):\n batch = pid_ptext[batch_start_idx : batch_start_idx + batch_size]\n processed_problems = process_raw_text([tup[1] for tup in batch], err_data)\n for tup, problem in zip(batch, processed_problems):\n pid_to_problem[tup[0]] = problem\n with open(FEEDBACK_PROBLEMS, \"w\", encoding=\"utf-8\") as problem_file:\n json.dump(pid_to_problem, problem_file, indent=2, ensure_ascii=False)\n\n samples: List[FeedbackTaskSample] = []\n for batch_start_idx in tqdm(range(0, len(unprocessed_samples), batch_size)):\n batch = unprocessed_samples[batch_start_idx : batch_start_idx + batch_size]\n processed_answers = process_raw_text([sample[\"answer\"] for sample in batch], err_data)\n processed_feedback = process_raw_text([sample[\"feedback\"] for sample in batch], err_data)\n for sample, answer, feedback in zip(batch, processed_answers, processed_feedback):\n samples.append({\n \"problem_id\": str(sample[\"problem_id\"]),\n \"problem_code\": str(sample[\"problem_code\"]),\n \"answer\": answer,\n \"feedback\": feedback,\n })\n with open(FEEDBACK_SAMPLES, \"w\", encoding=\"utf-8\") as sample_file:\n json.dump(samples, sample_file, indent=2, ensure_ascii=False)\n\n print(\"Skipped\", skipped)\n dump_errs(\"feedback_errs.json\", err_data)\n\ndef process_gsm8k_data():\n \"\"\"\n Process all data in the GSM8K dataset\n \"\"\"\n err_data = {}\n for split in (\"train\", \"test\"):\n # Extract all questions/steps/answers from the split\n batch_text = []\n with open(f\"../grade-school-math/grade_school_math/data/{split}.jsonl\", encoding=\"utf-8\") as src_file:\n for src_line in tqdm(src_file):\n sample = json.loads(src_line)\n batch_text.append(wrap_formulas(html_to_latex(remove_calculator_annotations(sample[\"question\"]))))\n steps, answer = sample[\"answer\"].split(\"\\n####\")\n batch_text.append(wrap_formulas(html_to_latex(remove_calculator_annotations(steps))))\n batch_text.append(wrap_formulas(html_to_latex(remove_calculator_annotations(answer))))\n\n # Batch process LaTeXML/TangentCFT\n batch_size = 30\n samples: List[ProblemSolvingTaskSample] = []\n for batch_start_idx in tqdm(range(0, len(batch_text), batch_size * 3)):\n processed_text = process_raw_text(batch_text[batch_start_idx : batch_start_idx + batch_size * 3], err_data)\n for sample_idx in range(0, len(processed_text), 3):\n samples.append({\n \"problem\": processed_text[sample_idx],\n \"steps\": processed_text[sample_idx + 1],\n \"answer\": processed_text[sample_idx + 2],\n })\n\n with open(os.path.join(GSM8K_DATA, f\"{split}.json\"), \"w\", encoding=\"utf-8\") as out_file:\n json.dump(samples, out_file, indent=2, ensure_ascii=False)\n\n dump_errs(\"gsm8k_errs.json\", err_data)\n\ndef process_math_data():\n \"\"\"\n Process all data in the MATH dataset\n \"\"\"\n err_data = {}\n for split in (\"train\", \"test\"):\n # Extract all questions/solutions from the split\n print(\"Split:\", split)\n batch_text = []\n levels = []\n for subdir in os.listdir(f\"../MATH 2/{split}\"):\n print(subdir)\n for problem_filename in tqdm(os.listdir(f\"../MATH 2/{split}/{subdir}\")):\n with open(f\"../MATH 2/{split}/{subdir}/{problem_filename}\", encoding=\"utf-8\") as src_file:\n sample = json.load(src_file)\n batch_text.append(sample[\"problem\"])\n batch_text.append(sample[\"solution\"])\n batch_text.append(get_boxed_answer(sample[\"solution\"]))\n levels.append(sample[\"level\"])\n\n # Just assign levels if missing\n # with open(os.path.join(MATH_DATA, f\"{split}_backup.json\"), encoding=\"utf-8\") as backup_file:\n # samples = json.load(backup_file)\n # for sample, level in zip(samples, levels):\n # sample[\"level\"] = level\n # with open(os.path.join(MATH_DATA, f\"{split}.json\"), \"w\", encoding=\"utf-8\") as out_file:\n # json.dump(samples, out_file, indent=2, ensure_ascii=False)\n\n # Batch process LaTeXML/TangentCFT\n batch_size = 20\n samples: List[ProblemSolvingTaskSample] = []\n for batch_start_idx in tqdm(range(0, len(batch_text), batch_size * 3)):\n processed_text = process_raw_text(batch_text[batch_start_idx : batch_start_idx + batch_size * 3], err_data)\n for sample_idx, level in zip(range(0, len(processed_text), 3), levels[batch_start_idx // 3 : batch_start_idx // 3 + batch_size]):\n if None not in processed_text[sample_idx : sample_idx + 3]:\n samples.append({\n \"problem\": processed_text[sample_idx],\n \"steps\": processed_text[sample_idx + 1],\n \"answer\": processed_text[sample_idx + 2],\n \"level\": level\n })\n\n with open(os.path.join(MATH_DATA, f\"{split}.json\"), \"w\", encoding=\"utf-8\") as out_file:\n json.dump(samples, out_file, indent=2, ensure_ascii=False)\n\n dump_errs(\"math_errs.json\", err_data)\n\ndef process_mwp_data():\n \"\"\"\n Process all data in the Math23K dataset\n \"\"\"\n # Get text and equations from samples\n batch_text = []\n answers = []\n with open(\"../math23k_translated.pkl\", \"rb\") as src_file:\n for sample in tqdm(pickle.load(src_file)):\n batch_text.append(wrap_formulas(html_to_latex(sample[\"text_en\"])))\n batch_text.append(\" \" + sample[\"equation\"] + \" \")\n answers.append(sample[\"ans\"])\n\n # Batch process LaTeXML/TangentCFT\n batch_size = 100\n samples: List[GenTaskSample] = []\n err_data = {}\n for batch_start_idx in tqdm(range(0, len(batch_text), batch_size * 2)):\n processed_text = process_raw_text(batch_text[batch_start_idx : batch_start_idx + batch_size * 2], err_data)\n for sample_idx in range(0, len(processed_text), 2):\n samples.append({\n \"prompt\": processed_text[sample_idx],\n \"label\": processed_text[sample_idx + 1],\n })\n for sample, answer in zip(samples, answers):\n sample[\"answer\"] = answer\n with open(MWP_DATA, \"w\", encoding=\"utf-8\") as out_file:\n json.dump(samples, out_file, indent=2, ensure_ascii=False)\n\n dump_errs(\"mwp_errs.json\", err_data)\n\ndef process_khan():\n \"\"\"\n Process all data in the Khan Academy dataset\n \"\"\"\n # Gather all problems\n batch_text = []\n filenames = []\n for subdir in tqdm(os.listdir(\"../amps/khan\")):\n if not os.path.isdir(f\"../amps/khan/{subdir}\"):\n continue\n os.makedirs(os.path.join(KHAN_DATA, subdir), exist_ok=True)\n for problem_filename in os.listdir(f\"../amps/khan/{subdir}\"):\n with open(f\"../amps/khan/{subdir}/{problem_filename}\", encoding=\"utf-8\") as problem_file:\n sample = json.load(problem_file)\n filenames.append(f\"{subdir}/{problem_filename}\")\n batch_text.append(sample[\"problem\"])\n batch_text.append(\" \".join(sample[\"hints\"]))\n\n # Batch process\n batch_size = 50\n err_data = {}\n for batch_start_idx in tqdm(range(0, len(batch_text), batch_size * 2)):\n processed_text = process_raw_text(batch_text[batch_start_idx : batch_start_idx + batch_size * 2], err_data, False)\n for sample_idx, filename in zip(range(0, len(processed_text), 2), filenames[batch_start_idx // 2 : batch_start_idx // 2 + batch_size]):\n if None in processed_text[sample_idx : sample_idx + 2]:\n continue\n with open(os.path.join(KHAN_DATA, filename), \"w\", encoding=\"utf-8\") as out_file:\n json.dump({\n \"prompt\": processed_text[sample_idx],\n \"label\": processed_text[sample_idx + 1],\n }, out_file, indent=2, ensure_ascii=False)\n\n dump_errs(\"khan_errs.json\", err_data)\n\ndef process_ct():\n \"\"\"\n Process Cognitive Tutor dataset\n \"\"\"\n # Load data and do initial analysis\n df = pandas.read_csv(\"../ds660.csv\", encoding=\"utf-8\")\n # print(\"Special steps:\", df[\"Step Name\"][df[\"Step Name\"].apply(lambda x: \"=\" not in x if isinstance(x, str) else False)].unique().tolist())\n print(\"Unique actions:\", df[\"Action\"].unique().tolist())\n print(\"Unique outcomes:\", df[\"Outcome\"].unique().tolist())\n print(\"Unique problems:\", df[\"Problem Name\"].unique().size)\n print(\"Unique students:\", df[\"Anon Student Id\"].unique().size)\n student_problem_counts = df[[\"Anon Student Id\", \"Problem Name\"]].drop_duplicates().groupby(\"Anon Student Id\").count().reset_index()[\"Problem Name\"]\n print(\"Problems per student- min:\", student_problem_counts.min(), \"max:\", student_problem_counts.max(), \"avg:\", student_problem_counts.mean())\n # Outcome = nan iff Action = SWITCH\n # Action = nan iff Step Name is not equation or Outcome is HINT\n # Step Name = FinalAnswer and Input = nan iff Outcome is HINT\n\n # Extract relevant attributes from each row\n problem_id_to_text: Dict[str, str] = {}\n batch_text: List[str] = []\n raw_samples: List[dict] = []\n for _, row in tqdm(df.iterrows(), total=df.shape[0]):\n if not isinstance(row[\"Step Name\"], str) or not (\"=\" in row[\"Step Name\"] or row[\"Step Name\"] == \"FinalAnswer\"):\n continue\n if not isinstance(row[\"Outcome\"], str) or row[\"Outcome\"] == \"INITIAL_HINT\" or row[\"Outcome\"] == \"HINT_LEVEL_CHANGE\":\n continue\n problem_text = \" \" + row[\"Problem Name\"].split(\" \", 1)[1] + \" \" # Remove label preceding formula\n problem_id_to_text[row[\"Problem Name\"]] = problem_text\n batch_text.append(\n row[\"Step Name\"]\n if row[\"Step Name\"] == \"FinalAnswer\" else\n \" \" + row[\"Step Name\"].rsplit(\" \", 1)[0] + \" \"\n ) # Remove label following formula\n batch_text.append(\n \" \" + row[\"Input\"] + \" \"\n if isinstance(row[\"Input\"], str) else \"\")\n batch_text.append(\n row[\"Feedback Text\"].replace(\"\", \"\").replace(\"\", \"\")\n if isinstance(row[\"Feedback Text\"], str) else \"\")\n raw_samples.append({\n \"action\": row[\"Action\"] if isinstance(row[\"Action\"], str) else \"\",\n \"outcome\": row[\"Outcome\"],\n \"student_id\": row[\"Anon Student Id\"],\n \"problem_id\": row[\"Problem Name\"]\n })\n\n batch_size = 50\n err_data = {}\n\n # Process all problems\n print(\"Process problems\")\n problem_id_to_processed: Dict[str, Article] = {}\n problem_ids = list(problem_id_to_text.keys())\n problem_texts = list(problem_id_to_text.values())\n for batch_start_idx in tqdm(range(0, len(problem_texts), batch_size)):\n processed_text = process_raw_text(problem_texts[batch_start_idx : batch_start_idx + batch_size], err_data)\n for problem, problem_id in zip(processed_text, problem_ids[batch_start_idx : batch_start_idx + batch_size]):\n problem_id_to_processed[problem_id] = problem\n\n # Process and aggregate all steps by student/problem pairs\n print(\"Process steps\")\n samples: List[CTTaskSample] = []\n cur_sample: Optional[CTTaskSample] = None\n for batch_start_idx in tqdm(range(0, len(batch_text), batch_size * 3)):\n processed_text = process_raw_text(batch_text[batch_start_idx : batch_start_idx + batch_size * 3], err_data)\n for sample_idx, raw_sample in zip(range(0, len(processed_text), 3), raw_samples[batch_start_idx // 3 : batch_start_idx // 3 + batch_size]):\n if not cur_sample or (raw_sample[\"student_id\"], raw_sample[\"problem_id\"]) != (cur_sample[\"student_id\"], cur_sample[\"problem_id\"]):\n cur_sample = {\n \"student_id\": raw_sample[\"student_id\"],\n \"problem_id\": raw_sample[\"problem_id\"],\n \"problem\": problem_id_to_processed[raw_sample[\"problem_id\"]],\n \"steps\": []\n }\n samples.append(cur_sample)\n cur_sample[\"steps\"].append({\n \"step\": processed_text[sample_idx],\n \"input\": processed_text[sample_idx + 1],\n \"feedback\": processed_text[sample_idx + 2],\n \"action\": raw_sample[\"action\"],\n \"outcome\": raw_sample[\"outcome\"],\n })\n\n with open(CT_DATA, \"w\", encoding=\"utf-8\") as out_file:\n json.dump(samples, out_file, indent=2, ensure_ascii=False)\n\n dump_errs(\"ct_errs.json\", err_data)\n","repo_name":"umass-ml4ed/mathGPT","sub_path":"pre_process.py","file_name":"pre_process.py","file_ext":"py","file_size_in_byte":26593,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"52"} +{"seq_id":"39908674596","text":"# Written by: Nick Gerend, @dataoutsider\n# Viz: \"Eye in the Sky\", enjoy!\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\n\n#region alias\ncos = np.cos\nsin = np.sin\npi = np.pi\ndot = np.dot\n#endregion\n\n#region plot\nfig = plt.figure(figsize=plt.figaspect(1))\nax = fig.add_subplot(111, projection='3d')\n#endregion\n\nclass point:\n def __init__(self, index, item, x, y, z, path, value1=0., value2=0., value3=0.): \n self.index = index\n self.item = item\n self.x = x\n self.y = y\n self.z = z\n self.path = path\n self.value1 = value1\n self.value2 = value2\n self.value3 = value3\n def to_dict(self):\n return {\n 'index' : self.index,\n 'item' : self.item,\n 'x' : self.x,\n 'y' : self.y,\n 'z' : self.z,\n 'path' : self.path,\n 'value1' : self.value1,\n 'value2' : self.value2,\n 'value3' : self.value3 }\n\ndef earth():\n Earth_radius = 6371. # km\n coefs = (1, 1, 1) \n rx, ry, rz = [Earth_radius/np.sqrt(coef) for coef in coefs]\n\n u = np.linspace(0, 2 * np.pi, 50)\n v = np.linspace(0, np.pi, 50)\n\n x = rx * np.outer(np.cos(u), np.sin(v))\n y = ry * np.outer(np.sin(u), np.sin(v))\n z = rz * np.outer(np.ones_like(u), np.cos(v))\n\n x = np.reshape(x, -1)\n y = np.reshape(y, -1)\n z = np.reshape(z, -1)\n\n return list(zip(x,y,z))\n\ndef orbital(apogee, eccentricity=0, inclination=0, ascension=0, perigee=0):\n inc = inclination * pi / 180.\n M1 = np.matrix([ [0, cos(inc), -sin(inc)], [0, sin(inc), cos(inc)], [1, 0, 0] ])\n\n rotation = (ascension + perigee) * pi/180\n M2 = np.matrix([ [0, 0, 1], [cos(rotation), -sin(rotation), 0], [sin(rotation), cos(rotation), 0] ]) \n angle = np.linspace(0,2*pi, 182)\n r = (apogee * (1-eccentricity**2)) / (1 + eccentricity*cos(angle))\n\n xr = r*cos(angle)\n yr = r*sin(angle)\n zr = 0.\n\n pts = np.matrix(list(zip(xr,yr,zr)))\n pts = (M1 * M2 * pts.T).T\n xr,yr,zr = pts[:,0].A.flatten(), pts[:,1].A.flatten(), pts[:,2].A.flatten()\n\n # ax.plot(xr, yr, zr, '-')\n # plt.show()\n\n return list(zip(xr,yr,zr))\n\n#region orbits\ndf = pd.read_csv(os.path.dirname(__file__) + '/UCS-Satellite-Database-8-1-2020_Clean.csv')\ndf = df.replace(',','', regex=True)\nlist_xy = []\nfor j, row in df.iterrows():\n name = row['Name of Satellite, Alternate Names']\n ap = float(row['Apogee (km)'])\n pe = float(row['Perigee (km)'])\n ec = float(row['Eccentricity'])\n val1 = float(str(row['Dry Mass (kg.)']).replace('1500-1900', '1700'))\n val2 = float(str(row['Power (watts)']).replace(' (EOL)', '').replace(' (BOL)', ''))\n val3 = float(row['Expected Lifetime (yrs.)'])\n xyz = orbital(6371+ap, ec, 0.0, 0.0, 6371+pe)\n for i in range(len(xyz)):\n list_xy.append(point(j, name, xyz[i][0], xyz[i][1], xyz[i][2], i, val1, val2, val3))\n#endregion\n\n#region earth\nearth_grid = earth()\nfor i in range(len(earth_grid)):\n list_xy.append(point(-1, 'earth', earth_grid[i][0], earth_grid[i][1], earth_grid[i][2], i))\n#endregion\n\n#region write data\nimport csv\nwith open(os.path.dirname(__file__) + '/orbital.csv', 'w',) as csvfile:\n writer = csv.writer(csvfile, lineterminator = '\\n')\n writer.writerow(['index', 'item', 'x', 'y', 'z', 'path', 'Dry Mass (kg.)', 'Power (watts)', 'Expected Lifetime (yrs.)'])\n for i in range(len(list_xy)): \n writer.writerow([i+1, list_xy[i].item, list_xy[i].x, list_xy[i].y, list_xy[i].z, list_xy[i].path, list_xy[i].value1, list_xy[i].value2, list_xy[i].value3])\n#endregion\n\nprint('finished')","repo_name":"nickgerend/EyeintheSky","sub_path":"orbital.py","file_name":"orbital.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40690719293","text":"#encoding=utf-8\nimport sys\nimport os\nimport codecs\nimport json\nimport logging\nimport time\nfrom collections import OrderedDict\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nlogging.getLogger(\"requests\").setLevel(logging.WARNING)\nlogging.getLogger(\"urllib3\").setLevel(logging.WARNING)\nlogging.getLogger(\"connectionpool\").setLevel(logging.WARNING)\nlogging.getLogger(\"webdriver\").setLevel(logging.WARNING)\n\n\nclass ASharesFinanceReportDigger(object):\n\n def __init__(self, data_path, config_path, mapping_file_path=None, blacklist_path=None):\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%%d %b %Y %H:%M:%S')\n self.root_url = None\n self.user_agent = None\n self.host = None\n self.headers = {}\n self.now_month = time.strftime('%Y%m',time.localtime(time.time()))\n self.stock_name_filter_set = set(u\"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\")\n self.id_stockname_mapping = {}\n\n self.data_path = data_path\n self.config_path = config_path\n self.mapping_file_path = mapping_file_path\n self.blacklist = blacklist_path\n\n # 创建当天财报目录\n if not os.path.exists(os.path.join(self.data_path, self.now_month)):\n os.mkdir(os.path.join(self.data_path, self.now_month))\n self.data_path = os.path.join(self.data_path, self.now_month)\n\n # selenium设置\n self.d = webdriver.Chrome()\n self.d.set_page_load_timeout(5)\n self.d.set_script_timeout(5)\n\n self.load_config()\n self.load_stock_id_mapping()\n\n def load_config(self):\n \"\"\"\n\n \"\"\"\n\n with open(self.config_path) as f:\n j = json.loads(\"\".join(f.readlines()))\n self.stock_root_url = j[\"stock_root_url\"]\n self.financial_root_url = j[\"financial_root_url\"]\n self.user_agent = j[\"User-Agent\"]\n self.stock_id_filepath = j[\"stock_id_filepath\"]\n\n if self.user_agent and self.host:\n self.headers[\"User-Agent\"] = self.user_agent\n #self.headers[\"Host\"] = self.host\n\n def load_stock_id_mapping(self):\n \"\"\"\n\n \"\"\"\n if not self.mapping_file_path:\n return\n\n with codecs.open(self.blacklist, \"r\", \"utf-8\", \"ignore\") as f:\n blacklist_dict = {line.strip().split(\"_\")[0] for line in f.readlines()}\n\n self.id_stockname_mapping = {}\n with codecs.open(self.mapping_file_path, \"r\", \"utf-8\", \"ignore\") as f:\n for line in f:\n temp = line.strip().split(\"\\t\")\n if temp[1] in blacklist_dict:\n continue\n self.id_stockname_mapping[temp[1]] = temp[0]\n\n def _request_url(self, url, timeout = 5):\n \"\"\"\n use requests module to request a url, return a response\n \"\"\"\n success = False\n retry_times = 0\n while success == False and retry_times < 5:\n try:\n if len(self.headers) > 0:\n res = requests.get(url, headers = self.headers, timeout = timeout)\n else:\n res = requests.get(url, timeout = timeout)\n success = True\n except:\n retry_times += 1\n logging.warn(\"Error in decoding image url:%s, now retry times:%d\" % (url, retry_times))\n\n if success:\n return res\n else:\n return None\n\n\n def _request_url_with_selenium(self, url):\n \"\"\"\n 如果访问超时则重试最多5次\n \"\"\"\n success = False\n retry_times = 0\n while success == False and retry_times < 5:\n try:\n self.d.get(url)\n result = self.d.page_source\n success = True\n except Exception as e:\n retry_times += 1\n logging.warn(\"Error in decoding image url:%s, err=%s, now retry times:%d\" % (url, e, retry_times))\n\n if success:\n return result\n else:\n return None\n\n def _finance_info_str_to_float(self, finance_info_list):\n \"\"\"\n 对财报数据进行处理,全部转化成数字\n \"\"\"\n new_list = []\n for idx, ele in enumerate(finance_info_list):\n if idx == 0:\n # 日期\n new_list.append(ele)\n continue\n ele = ele.strip()\n num = None\n if len(ele) == 0:\n new_list.append(num)\n else:\n ele = ele.replace(\",\", \"\")\n try:\n num = float(ele)\n except:\n if ele.endswith(u\"%\"):\n num = float(ele.strip(u\"%\"))/100.0\n elif ele.endswith(u\"万\"):\n num = float(ele.strip(u\"万\"))*10000\n elif ele.endswith(u\"万亿\"):\n num = float(ele.strip(u\"万亿\"))*1000000000000\n elif ele.endswith(u\"亿\"):\n num = float(ele.strip(u\"亿\"))*100000000\n elif ele == u\"--\":\n num = None\n else:\n logging.error(\"Error in process finance info: %s\" % json.dumps(finance_info_list, ensure_ascii = False))\n num = None\n\n new_list.append(num)\n\n return new_list\n\n def _filter_invalid_row(self, row_name_list, temp_info_list):\n \"\"\"\n 过滤非法的基本面项目(也就是行)\n\n :param row_name_list: 表格的左栏的行名,如“净利润”,“每股净资产”等\n :param temp_info_list: 存储结果的OrderedDict,key为日期,value为一个list,存储当前日期的所有基本面数据\n :return:\n \"\"\"\n valid_row_name_list = []\n valid_temp_info_list = []\n\n for idx, row_name in enumerate(row_name_list):\n now_finance_item_every_date = temp_info_list[idx]\n latest_date_finance_val = now_finance_item_every_date[0]\n if latest_date_finance_val is None:\n continue\n latest_date_finance_val = latest_date_finance_val.strip()\n # 存在当前行没有任何数据的情况\n if len(latest_date_finance_val) == 0:\n # skip the invalid finance item\n continue\n valid_row_name_list.append(row_name)\n valid_temp_info_list.append(now_finance_item_every_date)\n\n return valid_row_name_list, valid_temp_info_list\n\n def _decode_left_head(self, soup):\n \"\"\"\n 解析表格的左栏的行名,如“净利润”,“每股净资产”等\n\n Args:\n soup: BeautifulSoup对象\n\n Returns:\n result: 结果list,按顺序存储行名\n \"\"\"\n logging.info(\"Begin to decode left t_head...\")\n result = []\n report_box = soup.find(\"div\", class_ = \"m_box finance i_hover_box\", id = \"finance\")\n if report_box is None:\n logging.info(\"can not find report box\")\n return result\n table_data = report_box.find(\"div\", class_ = \"table_data\")\n if table_data is None:\n logging.info(\"can not find table data\")\n return result\n left_thead = table_data.find(\"div\", class_ = \"left_thead\")\n if left_thead is None:\n logging.info(\"can not find left t_head\")\n return result\n # get title\n tbody = left_thead.find(\"table\", class_ = \"tbody\")\n if tbody is None:\n logging.info(\"can not find tbody\")\n return result\n th_list = tbody.find_all(\"th\")\n for th in th_list:\n row_name = th.string\n result.append(row_name)\n\n return result\n\n def _decode_table_data(self, soup, row_name_list):\n \"\"\"\n 解析表格数据\n\n Args:\n soup: BeautifulSoup对象,包含所有网页文字及数据\n row_name_list: 表格行名,如“净利润”,“每股净资产”等,由_decode_left_head函数得到\n\n Returns:\n row_name_list: 去除了非法基本面项目后的行名列表\n date_finance_val_d: key为财报日,value为当前页面的财报日对应的所有基本面指标数值\n \"\"\"\n logging.info(\"Begin to decode table data...\")\n date_list = []\n info_list = []\n report_box = soup.find(\"div\", class_ = \"m_box finance i_hover_box\", id = \"finance\")\n if report_box is None:\n logging.info(\"can not find report box\")\n return None, None\n table_data = report_box.find(\"div\", class_ = \"table_data\")\n if table_data is None:\n logging.info(\"can not find table data\")\n return None, None\n # get date\n data_tbody = table_data.find(\"div\", class_ = \"data_tbody\")\n if data_tbody is None:\n logging.info(\"can not find data t_body\")\n return None, None\n top_thead = data_tbody.find(\"table\", class_ = \"top_thead\")\n if top_thead is None:\n logging.info(\"can not find top t_head\")\n return None, None\n div_list = top_thead.find_all(\"div\", class_ = \"td_w\")\n for div in div_list:\n # 由此获取每一个财报日期\n date = div.string\n if date is not None:\n date_list.append(date.replace(\"-\", \"\"))\n else:\n date_list.append(\"00000000\")\n date_len = len(date_list)\n\n # 一维数组,数组中的每一项是每一个财报日的所有项目数据\n finance_item_date_list = []\n tbody = data_tbody.find(\"table\", class_=\"tbody\")\n if tbody is None:\n logging.info(\"can not find tbody\")\n return None, None\n tr_list = tbody.find_all(\"tr\")\n rows = 0\n for tr in tr_list:\n # 遍历每一个基本面项目,如净利润\n finance_item_daily_list = []\n td_list = tr.find_all(\"td\")\n for td in td_list:\n # 当前基本面项目(如净利润)的所有财报日的数据\n now_finance_val = td.string\n # 最终加入list\n finance_item_daily_list.append(now_finance_val)\n if len(finance_item_daily_list) == 0:\n # 当前数据行没有任何数据\n continue\n if len(finance_item_daily_list) != date_len:\n logging.info(\"decode row %d error, length:%d is not equal!\" % (rows, len(finance_item_daily_list)))\n return None, None\n finance_item_date_list.append(finance_item_daily_list)\n rows += 1\n\n if len(finance_item_date_list) != len(row_name_list):\n logging.warning(\"rows num is not equal! row_name_list len=%s, temp_info_list len=%s\" %\n (len(row_name_list), len(finance_item_date_list)))\n return None, None\n\n row_name_list, finance_item_date_list = self._filter_invalid_row(row_name_list, finance_item_date_list)\n\n row_len = len(row_name_list)\n\n # logging.debug(\"date_len=%s, row_len=%s\" % (date_len, row_len))\n # logging.debug(\"row_name_list=%s\" % json.dumps(row_name_list, ensure_ascii=False))\n\n date_finance_val_d = OrderedDict()\n # 转换成key为财报日,value为财报日中所有基本面数据列表的dict\n for idx_date, date in enumerate(date_list):\n now_date_finance_info = []\n for idx_item, _ in enumerate(row_name_list):\n now_date_finance_info.append(finance_item_date_list[idx_item][idx_date])\n date_finance_val_d[date] = now_date_finance_info\n # logging.debug(\"date_finance_val_d=%s\" % json.dumps(date_finance_val_d, ensure_ascii=False))\n\n return row_name_list, date_finance_val_d\n\n def _merge_all_data(self, row_head_list_list, date_finance_val_d_list):\n \"\"\"\n\n :param row_head_list_list: 二维列表,列表中的每一项是每一个页面的基本面项目名的列表\n :param date_finance_val_d_list: date_finance_val_d的列表,包含所有页面的基本面数据信息\n :return:\n final_head_list: 所有基本面项目名的列表\n final_data_list: 二维数组,每一行是每个财报日的所有基本面数据\n \"\"\"\n final_head_list = []\n final_data_list = []\n col_num_per_page = []\n assert len(row_head_list_list) == len(date_finance_val_d_list)\n table_num = len(row_head_list_list)\n\n # 获取所有有效的财报日\n date_d = {}\n for date_finance_val_d in date_finance_val_d_list:\n for date in date_finance_val_d.keys():\n date_d[date] = None\n date_list = sorted(date_d.iteritems(), key=lambda x:x[0], reverse=True)\n date_list = map(lambda x: x[0], date_list)\n # logging.debug(\"final date list=%s\" % json.dumps(date_list, ensure_ascii=False))\n\n # 合并表头\n final_head_list.append(u\"日期\")\n for row_head_list in row_head_list_list:\n final_head_list += row_head_list\n # 获取每个页面的基本面项目的数量,存在col_num_per_page里\n col_num_per_page.append(len(row_head_list))\n # logging.debug(\"final head list=%s\" % json.dumps(final_head_list, ensure_ascii=False))\n # logging.debug(\"col_num_per_page=%s\" % json.dumps(col_num_per_page))\n\n # 按时间顺序合并三张表\n for idx_date, date in enumerate(date_list):\n base_col_idx = 1 # 第一列是日期\n table_idx = 0\n now_date_finance_data_list = [None for i in xrange(len(final_head_list))]\n # 第一列是日期\n now_date_finance_data_list[0] = date\n\n # 主要指标表\n main_table_d = date_finance_val_d_list[table_idx]\n if date not in main_table_d:\n logging.warn(\"date=%s not in main_table_d\" % date)\n continue\n now_date_main_table_val_list = main_table_d[date]\n for idx_now_val, now_val in enumerate(now_date_main_table_val_list):\n # logging.debug(\"idx_date=%s, idx_now_val=%s, now_val=%s\" % (idx_date, idx_now_val, now_val))\n try:\n now_date_finance_data_list[base_col_idx + idx_now_val] = now_val\n except:\n logging.error(\"list index out of range, now_date_finance_data_list len=%s, now_val=%s, \"\n \"base_col_idx=%s, idx_now_val=%s, idx_date=%s\" %\n (len(now_date_finance_data_list), now_val, base_col_idx, idx_now_val, idx_date))\n # base col idx加至第二张表\n base_col_idx += col_num_per_page[table_idx]\n table_idx += 1\n\n # 资产负债表\n dept_table_d = date_finance_val_d_list[table_idx]\n if date not in dept_table_d:\n logging.warn(\"date=%s not in dept_table_d\" % date)\n continue\n now_date_dept_table_val_list = dept_table_d[date]\n for idx_now_val, now_val in enumerate(now_date_dept_table_val_list):\n try:\n now_date_finance_data_list[base_col_idx + idx_now_val] = now_val\n except:\n logging.error(\"list index out of range, now_date_finance_data_list len=%s, now_val=%s, \"\n \"base_col_idx=%s, idx_now_val=%s, idx_date=%s\" %\n (len(now_date_finance_data_list), now_val, base_col_idx, idx_now_val, idx_date))\n # base col idx加至第三张表\n base_col_idx += col_num_per_page[table_idx]\n table_idx += 1\n\n # 利润表\n profit_table_d = date_finance_val_d_list[table_idx]\n if date not in profit_table_d:\n logging.warn(\"date=%s not in dept_table_d\" % date)\n continue\n now_date_profit_table_val_list = profit_table_d[date]\n for idx_now_val, now_val in enumerate(now_date_profit_table_val_list):\n try:\n now_date_finance_data_list[base_col_idx + idx_now_val] = now_val\n except:\n logging.error(\"list index out of range, now_date_finance_data_list len=%s, now_val=%s, \"\n \"base_col_idx=%s, idx_now_val=%s, idx_date=%s\" %\n (len(now_date_finance_data_list), now_val, base_col_idx, idx_now_val, idx_date))\n # base col idx加至第四张表\n base_col_idx += col_num_per_page[table_idx]\n table_idx += 1\n\n # 确认数据列数合法\n assert len(now_date_finance_data_list) == len(final_head_list)\n\n # 将字符串转为数字\n now_date_finance_data_list = self._finance_info_str_to_float(now_date_finance_data_list)\n\n # 最后把当前财报日的数据插入总数据表\n final_data_list.append(now_date_finance_data_list)\n # logging.debug(\"now date=%s, now_date_finance_data_list=%s\" %\n # (date, json.dumps(now_date_finance_data_list, ensure_ascii=False)))\n\n # logging.debug(\"final data list=%s\" % json.dumps(final_data_list, ensure_ascii=False))\n\n return final_head_list, final_data_list\n\n def _decode_one_financial_page(self, stock_id, stock_name):\n \"\"\"\n 解析单张财报表\n \"\"\"\n # get true url\n true_url = \"http://basic.10jqka.com.cn/%s/finance.html#stockpage\" % stock_id\n\n res = self._request_url_with_selenium(true_url)\n if res == None:\n return -1\n soup = BeautifulSoup(self.d.page_source, \"html.parser\")\n # print soup.prettify()\n # print self.d.page_source\n\n # 解析表格的左栏\n row_name_list_main = self._decode_left_head(soup)\n if len(row_name_list_main) == 0:\n logging.warn(\"len(row_name_list_main) == 0, no row names in main financial item\")\n return -1\n\n # 解析“主要指标”页面\n finance_data_dict = OrderedDict()\n row_name_list_main, date_finance_val_d_main = self._decode_table_data(soup, row_name_list_main)\n if row_name_list_main is None or date_finance_val_d_main is None or len(date_finance_val_d_main) == 0:\n return -1\n time.sleep(2)\n\n # 点击进入资产负债表\n self.d.find_element_by_class_name(\"icons_page\").click()\n time.sleep(2)\n soup = BeautifulSoup(self.d.page_source, \"html.parser\")\n # 解析表格的左栏\n row_name_list_dept = self._decode_left_head(soup)\n # logging.debug(\"row_name_list_dept=%s\" % json.dumps(row_name_list_dept, ensure_ascii=False))\n if len(row_name_list_dept) == 0:\n return -1\n row_name_list_dept, date_finance_val_d_dept = self._decode_table_data(soup, row_name_list_dept)\n\n # 点击进入利润表\n self.d.find_element_by_class_name(\"icons_pie\").click()\n time.sleep(2)\n soup = BeautifulSoup(self.d.page_source, \"html.parser\")\n # 解析表格的左栏\n row_name_list_profit = self._decode_left_head(soup)\n # logging.debug(\"row_name_list_profit=%s\" % json.dumps(row_name_list_profit, ensure_ascii=False))\n if len(row_name_list_profit) == 0:\n return -1\n row_name_list_profit, date_finance_val_d_profit = self._decode_table_data(soup, row_name_list_profit)\n\n table_head, table_data = self._merge_all_data(\n [row_name_list_main, row_name_list_dept, row_name_list_profit],\n [date_finance_val_d_main, date_finance_val_d_dept, date_finance_val_d_profit]\n )\n\n file_path = os.path.join(self.data_path, \"%s.csv\" % stock_id)\n with open(file_path, \"w\") as f:\n f.write(\"%s\\n\" % \"|\".join(table_head))\n for data_line in table_data:\n f.write(\"%s\\n\" % \"|\".join(map(str, data_line)))\n return 0\n\n def get_financial_report(self):\n \"\"\"\n\n \"\"\"\n\n is_debug = False\n logging.info(\"Now getting financial report\")\n\n if is_debug:\n stock_id = \"300253\"\n self._decode_one_financial_page(stock_id, self.id_stockname_mapping[stock_id])\n else:\n for stock_id in self.id_stockname_mapping:\n logging.info(\"%s, %s\" % (stock_id, self.id_stockname_mapping[stock_id]))\n file_name = \"%s_%s.csv\" % (stock_id, self.id_stockname_mapping[stock_id])\n file_path = os.path.join(self.data_path, file_name)\n if os.path.exists(file_path):\n logging.info(\"%s exists! Now continue...\" % file_name)\n continue\n ret = self._decode_one_financial_page(stock_id, self.id_stockname_mapping[stock_id])\n if ret < 0:\n continue\n\n\n\n def _decode_one_page(self, url):\n \"\"\"\n\n \"\"\"\n pass\n\n\n def decode_pages(self):\n \"\"\"\n\n \"\"\"\n pass\n\n\nif __name__ == \"__main__\":\n data_path = sys.argv[1]\n config_path = sys.argv[2]\n mapping_file = sys.argv[3]\n a = ASharesFinanceReportDigger(data_path, config_path, mapping_file)\n a.get_financial_report()\n","repo_name":"younglittlefat/data_mining","sub_path":"financial_report/digger/a_shares.py","file_name":"a_shares.py","file_ext":"py","file_size_in_byte":21667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11170597596","text":"from compas_ags.diagrams import FormGraph\nfrom compas_ags.diagrams import FormDiagram\nfrom compas_ags.diagrams import ForceDiagram\n\nfrom compas_ags.viewers import Viewer\n\nfrom compas_ags.ags import graphstatics\nfrom compas_ags.ags import loadpath\n\n# ------------------------------------------------------------------------------\n# 1. create a planar truss structure, its applied loads and boundary conditions\n# from nodes and edges\n# make form and force diagrams\n# ------------------------------------------------------------------------------\n\nnodes = [\n [0.0, 0.0, 0],\n [1.0, 0.0, 0],\n [2.0, 0.0, 0],\n [3.0, 0.0, 0],\n [4.0, 0.0, 0],\n [5.0, 0.0, 0],\n [6.0, 0.0, 0],\n [0.0, -1.0, 0],\n [1.0, -1.0, 0],\n [2.0, -1.0, 0],\n [3.0, -1.0, 0],\n [4.0, -1.0, 0],\n [5.0, -1.0, 0],\n [6.0, -1.0, 0],\n [1.0, +1.0, 0],\n [2.0, +1.0, 0],\n [3.0, +1.0, 0],\n [4.0, +1.0, 0],\n [5.0, +1.0, 0],\n]\n\nedges = [\n (0, 1),\n (1, 2),\n (2, 3),\n (3, 4),\n (4, 5),\n (5, 6),\n (0, 7),\n (1, 8),\n (2, 9),\n (3, 10),\n (4, 11),\n (5, 12),\n (6, 13),\n (0, 14),\n (14, 15),\n (15, 16),\n (16, 17),\n (17, 18),\n (18, 6),\n (1, 14),\n (2, 15),\n (3, 16),\n (4, 17),\n (5, 18),\n]\n\ngraph = FormGraph.from_nodes_and_edges(nodes, edges)\n\nform = FormDiagram.from_graph(graph)\nforce = ForceDiagram.from_formdiagram(form)\n\n# ------------------------------------------------------------------------------\n# 2. assign applied loads to bottom chord\n# ------------------------------------------------------------------------------\n\nedges = [(8, 1), (9, 2), (10, 3), (11, 4), (12, 5)]\n\nfor edge in edges:\n form.edge_attribute(edge, \"is_ind\", True)\n form.edge_attribute(edge, \"q\", 1.0)\n\n# update force densities of form and force diagram\ngraphstatics.form_update_q_from_qind(form)\ngraphstatics.force_update_from_form(force, form)\n\n# ------------------------------------------------------------------------------\n# 3. optimize the loadpath\n# ------------------------------------------------------------------------------\n\n# modify force in the truss by updating vertex coordinates of the force diagram\n# force in members of the top chord and bottom chord are set to be the same\n# now the form is no longer in equilibrium\nforce.vertex_attributes(1, \"xy\", [0, 2.5])\nforce.vertex_attributes(2, \"xy\", [0, 1.5])\nforce.vertex_attributes(3, \"xy\", [0, 0.5])\nforce.vertex_attributes(0, \"xy\", [0, 0])\nforce.vertex_attributes(4, \"xy\", [0, -0.5])\nforce.vertex_attributes(5, \"xy\", [0, -1.5])\nforce.vertex_attributes(6, \"xy\", [0, -2.5])\n\nforce.vertex_attributes(12, \"xy\", [-2, 2.5])\nforce.vertex_attributes(11, \"xy\", [-2, 1.5])\nforce.vertex_attributes(10, \"xy\", [-2, 0.5])\nforce.vertex_attributes(9, \"xy\", [-2, -0.5])\nforce.vertex_attributes(8, \"xy\", [-2, -1.5])\nforce.vertex_attributes(7, \"xy\", [-2, -2.5])\n\n# forces in members of top chord and connecting struts are force domain parameters\nforce.vertices_attribute(\"is_param\", True, keys=[7, 8, 9, 10, 11, 12])\n\n# fix boundary vertices, the nodes of the bottom chord\nform.vertices_attribute(\"is_fixed\", True, keys=[0, 1, 2, 3, 4, 5, 6])\n\n# optimize the loadpath and output the optimal distribution of forces that\n# results in overall minimum-volumn solution for given form diagram\nloadpath.optimise_loadpath(form, force)\n\n# ------------------------------------------------------------------------------\n# 4. display force and form diagrams\n# ------------------------------------------------------------------------------\n\nviewer = Viewer(form, force, delay_setup=False, figsize=(12, 7.5))\n\nviewer.draw_form(forcescale=5, vertexlabel={key: str(key) for key in form.vertices()}, vertexsize=0.2)\nviewer.draw_force(vertexlabel={key: str(key) for key in force.vertices()}, vertexsize=0.2)\n\nviewer.show()\n","repo_name":"BlockResearchGroup/compas_ags","sub_path":"docs/examples/02_lpopt.py","file_name":"02_lpopt.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"8225940590","text":"import pygame\r\nimport random\r\nimport math\r\nimport numpy as np\r\nwidth=800\r\nheight=800\r\npygame.init()\r\nscreen=pygame.display.set_mode((width,height ))\r\nclock=pygame.time.Clock()\r\nclass Ball:\r\n def __init__(self,x,y):\r\n self.xpos=x\r\n self.ypos=y\r\n self.xvel=random.uniform(-26,25)\r\n self.yvel=random.uniform(-26,25)\r\n self.xacc=0\r\n self.yacc=1\r\n self.colour=(random.randint(0,255),random.randint(0,255),random.randint(0,255))\r\n self.mass=random.uniform(10,40)\r\n self.radius= self.mass \r\n self.bounced=False\r\n def move(self):\r\n self.xpos+=self.xvel\r\n self.ypos+=self.yvel\r\n self.xvel+=self.xacc\r\n self.yvel+=self.yacc\r\n ball.bounceWall()\r\n def collide(self,other):\r\n distx=other.xpos-self.xpos\r\n disty=other.ypos-self.ypos\r\n dist=math.sqrt(distx*distx+disty*disty)\r\n if dist=height:\r\n self.ypos=height-self.radius\r\n self.yvel=-elasticity*self.yvel\r\n if self.xpos-self.radius<=0:\r\n self.xpos=self.radius\r\n self.xvel=-elasticity*self.xvel\r\n if self.xpos+self.radius>=width:\r\n self.xpos=width-self.radius\r\n self.xvel=-elasticity*self.xvel \r\n \r\n \r\ndef draw(screen,balls):\r\n global customising\r\n screen.fill(0)\r\n for ball in balls:\r\n pygame.draw.circle(screen,ball.colour,(ball.xpos,ball.ypos),ball.radius)\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit\r\n elif pygame.mouse.get_pressed()[0]:\r\n #x,y = pygame.mouse.get_pos()\r\n pass\r\n elif pygame.mouse.get_pressed()[2]:\r\n #x,y = pygame.mouse.get_pos()\r\n pass\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n customising=not customising \r\n\r\nairres=0\r\nelasticity=0.75\r\nnumberOfBalls=10\r\nballs=[]\r\nwhile True:\r\n customising=True\r\n balls=[]\r\n for i in range(numberOfBalls):\r\n x=random.uniform(100,700)\r\n balls.append(Ball(x,100))\r\n \r\n while customising:\r\n draw(screen,balls)\r\n while not customising:\r\n for ball in balls:\r\n ball.move() \r\n draw(screen,balls)\r\n for i in range(len(balls)):\r\n for j in range(len(balls)-(i+1)):\r\n j+=i+1\r\n balls[i].collide(balls[j])\r\n draw(screen,balls)\r\n clock.tick(60)","repo_name":"SamuelTull/BouncyBalls","sub_path":"CollidingBalls2DMoreBalls.py","file_name":"CollidingBalls2DMoreBalls.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41665247194","text":"#Un fabricante de losetas se dispone a elaborar piezas,\n#y cada loseta puede medir entre 0.3 y 0.4 metros de largo como mucho,\n#Ingresar la cantidad de loseta y su medida respectiva, Por último el programa\n#Deberá digitalizar la cantidad de piezas.\n\ncantidad = 0\nx = 1\nn = int(input(\"Cuantas piezas cargara: \\n\"))\nwhile x<=n:\n largo = float(input(\"Ingrese la medida la pieza: \\n\"))\n if largo>=0.3 and largo<=0.4:\n cantidad = cantidad + 1\n x = x + 1\nprint(\"La cantidad de piezas aptas son: \")\nprint(cantidad)","repo_name":"ManuelCarranzaAv/Trabajos-de-la-semana-5-11","sub_path":"pregunta 5.py","file_name":"pregunta 5.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39350975550","text":"import socket\nimport threading\nfrom queue import Queue\n\ntarget = \"192.168.2.1\"\nqueue = Queue()\nopen_ports = []\n\ndef port_scan(port):\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((target, port))\n return True\n except:\n return False\n \ndef fill_queue(port_list):\n for port in port_list:\n queue.put(port)\n\ndef worker():\n while not queue.empty():\n port = queue.get()\n if port_scan(port):\n print(\"Port {} is open!\".format(port))\n open_ports.append(port)\n\n#Defining the port range and filling the queue\nport_list = range(1, 1024)\nfill_queue(port_list)\n\nthread_list = []\n\n#Running threads and defining the thread count\nfor t in range(10):\n thread = threading.Thread(target=worker)\n thread_list.append(thread)\n\nfor thread in thread_list:\n thread.start()\n\nfor thread in thread_list:\n thread.join()\n\nprint(\"Open ports are: \", open_ports)","repo_name":"Edwux121/networking_proj","sub_path":"port_scanner/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":"52"} +{"seq_id":"13498198022","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 3 18:15:06 2018\r\nASTR 414 HW2, Problem 2\r\n@author: Ashvini Krishnan\r\nnetid: akrshnn6\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\"\"\"Part a:\"\"\"\r\n#Function to generate random true distances to uniformly distributed supernovas\r\ndef truedist():\r\n#Generation of random radii with a uniform distribution\r\n radii = (np.random.uniform(low=0, high = 1, size = 100))\r\n#Stretch those radii to the spherical probability distribution and return the distances\r\n true_distances = []\r\n for value in radii:\r\n true_distances.append(((8*value)**(1/3))*10**3)\r\n return true_distances\r\n \r\nsum=0\r\ncount = 0\r\n#Find the average of many averages of different random uniformly distributed distances for a \"super average\"\r\nfor value in range(0, 100000):\r\n sum+=np.average(truedist())\r\n count+=1\r\n\r\navg = str(sum/count)\r\nprint(\"Average True Distance: \" + avg)\r\n\r\n\r\n\"\"\"Part b:\"\"\"\r\ntrue_distances = truedist()\r\nm = []\r\ncount = 0\r\nabs_magnitudes = np.random.normal(-19, 1, 100) \r\nfor i in range(len(true_distances)):\r\n m.append(5*np.log10(true_distances[i]*10**5)+abs_magnitudes[i])\r\n\r\ncount = 0\r\napp_mags = []\r\ndist = []\r\nfor i in range(len(true_distances)):\r\n if m[i]<=20:\r\n app_mags.append(m[i])\r\n dist.append(true_distances[i])\r\n count+=1\r\n \r\nprint(\"Original Average Apparent Magnitude: \" + str(np.average(m)))\r\nprint(\"Detected Average Apparent Magnitude: \" + str(np.average(app_mags)))\r\nprint(\"Number of Detected Supernovas: \" + str(count))\r\n\r\n \r\nplt.figure()\r\nplt.scatter(dist, app_mags)\r\nplt.gca().invert_yaxis()\r\nplt.title('True Distance (Mpc) vs Apparent Magnitude')\r\nplt.xlabel('True Distance (Mpc)')\r\nplt.ylabel('Apparent Magnitude')\r\nplt.xlim(0, 2000)\r\n\r\n\"\"\"Part c:\"\"\"\r\nobs_distances = []\r\nfor i in app_mags:\r\n obs_distances.append((10**(((i+19)/5)+1))*10**-6)\r\n \r\nvelocity = []\r\nfor i in obs_distances:\r\n velocity.append(72*i)\r\n\r\nplt.figure()\r\nplt.scatter(obs_distances, velocity)\r\nplt.title('Observed Distance (Mpc) vs Velocity')\r\nplt.xlabel('Observed Distance (Mpc)')\r\nplt.ylabel('Velocity')","repo_name":"akrshnn6/astr-414","sub_path":"HW 2/ASTR 414 HW2 problem 2.py","file_name":"ASTR 414 HW2 problem 2.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8362729690","text":"\"\"\"First Implementation of Prims Algorithm\"\"\"\n\n\nimport heapq\n\n\nimport heapq\n\n\nclass WeightedGraph:\n def __init__(self):\n self.adj_list = {}\n\n def add_vertex(self, vertex):\n if vertex not in self.adj_list:\n self.adj_list[vertex] = []\n\n def add_edge(self, start_vertex, end_vertex, weight):\n self.add_vertex(start_vertex)\n self.add_vertex(end_vertex)\n self.adj_list[start_vertex].append((end_vertex, weight))\n self.adj_list[end_vertex].append((start_vertex, weight))\n\n def prim(self):\n min_spanning_tree = {}\n visited = set()\n no_edge = 0\n pq = []\n\n # Select a random starting vertex\n start_vertex = list(self.adj_list.keys())[0]\n\n # Initialize priority queue with the starting vertex\n heapq.heappush(pq, (0, None, start_vertex))\n # no edge = no of vertices - 1\n while no_edge < len(self.adj_list) - 1 :\n weight, prev_vertex, vertex = heapq.heappop(pq)\n\n if vertex not in visited:\n visited.add(vertex)\n\n if prev_vertex is not None:\n min_spanning_tree[(prev_vertex, vertex)] = weight\n no_edge += 1\n\n for neighbor, edge_weight in self.adj_list[vertex]:\n if neighbor not in visited:\n heapq.heappush(pq, (edge_weight, vertex, neighbor))\n\n return min_spanning_tree\n\n\n# Example usage\ngraph = WeightedGraph()\ngraph.add_edge('A', 'B', 4)\ngraph.add_edge('B', 'C', 24)\ngraph.add_edge('A', 'D', 6)\ngraph.add_edge('D', 'C', 23)\ngraph.add_edge('A', 'E', 16)\ngraph.add_edge('E', 'D', 8)\ngraph.add_edge('E', 'F', 10)\ngraph.add_edge('E', 'F', 21)\ngraph.add_edge('D', 'F', 5)\ngraph.add_edge('C', 'F', 18)\ngraph.add_edge('C', 'G', 9)\ngraph.add_edge('H', 'G', 7)\ngraph.add_edge('G', 'F', 11)\ngraph.add_edge('H', 'F', 14)\n\nminimum_spanning_tree = graph.prim()\nprint(minimum_spanning_tree)\n","repo_name":"Fabian1032908ru/Algorithm-and-Data-Structures","sub_path":"Basics/MST/Prims_algorithm.py","file_name":"Prims_algorithm.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70015274086","text":"# Training the network\n\n# Imports\nfrom model import load_resnet_model\nfrom dataset import create_dataset\nimport torch\n\n\n# Configuration\nconfig = {\n \"file_name\": \"IndianPines.mat\",\n \"variable_name\": \"indian_pines\",\n \"augmentations\": [\"rot\",\"horflip\",\"verflip\"],\n \"layers\": [1, 1, 1, 1],\n \"pretrained\": False,\n \"num_classes\": 16,\n \"tt-split\": 0.8,\n \"epochs\": 10,\n \"batch_size\": 5,\n \"loss_fct\": torch.nn.functional.binary_cross_entropy_with_logits,\n \"optimizer\": torch.optim.Adam\n}\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# Fetch data\ntrain_data, test_data = create_dataset(config)\n\n\n# Fetch model\ndef create_model(config):\n layers, pretrained, num_classes = config.get(\"layers\"), config.get(\"pretrained\"), config.get(\"num_classes\")\n model = load_resnet_model(layers=layers, pretrained=pretrained, num_classes=num_classes)\n print(model.eval())\n print(f\"Using a custom ResNet architecture with bottleneck configuration {layers}, pretrained {pretrained} and {num_classes} classes.\")\n return model\n\n\n# Network training\ndef train_model(model, config, train_data):\n optimizer = (config.get(\"optimizer\"))(model.parameters())\n loss_fct = config.get(\"loss_fct\")\n\n net = model.to(device) # Move model to GPU if possible\n epochs = config.get(\"epochs\",10)\n for epoch in range(epochs):\n net.train()\n for batch in train_data:\n x,y = (batch[0].float()).to(device), (batch[1].float()).to(device) # Load image and ground truth batch on device\n optimizer.zero_grad() # Reset parameter gradients\n output = net(x)[\"out\"] # Calculate output of network\n loss = loss_fct(output,y) # Calculate loss of output\n loss.backward() # Pass loss backwards\n optimizer.step() # Optimize for batch\n print(\"Sample output: \", output[0])\n print(f\"Epoch {epoch}/{epochs}, Loss: {loss}\")\n return net\n\n\n# Training the model\nmodel = create_model(config)\ntrained_model = train_model(model, config, train_data)\n","repo_name":"glitznerf/hsi_pytorch_segmentation","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"31509216673","text":"import ctypes\nimport logging\nfrom datetime import datetime\nfrom .elster_frame import ElsterFrame\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Elster:\n RESPONSE = 0x2\n\n def __init__(self, sender, items):\n self.frames = [ElsterFrame(**item) for item in items]\n self.values = []\n self.datetime = datetime.now()\n self.sender = int(str(sender), 16)\n\n def listener(self, msg):\n data = msg.data\n\n receiver = (data[0] & 0xf0) * 8 + (data[1] & 0x7f)\n type = data[0] & 0x0f\n\n if type != self.RESPONSE or \\\n receiver != self.sender or \\\n not self._exist_receiver(msg.arbitration_id):\n return\n\n if data[2] == 0xfa:\n register = ((data[3] & 0xff) << 8) | (data[4] & 0xff)\n if len(data) == 7:\n value = ctypes.c_int16(\n ((data[5] & 0xff) << 8) | (data[6] & 0xff)\n ).value\n else:\n register = data[2]\n if len(data) >= 5:\n value = ctypes.c_int16(\n ((data[3] & 0xff) << 8) | (data[4] & 0xff)\n ).value\n\n entry = self._get_frame(msg.arbitration_id, register)\n\n self.values.append(\n (self.datetime, entry.name, entry.formatter(value))\n )\n\n def is_done(self):\n return len(self.values) == len(self.frames)\n\n def _exist_receiver(self, receiver):\n frames = [frame for frame in self.frames if frame.receiver == receiver]\n return len(frames) > 0\n\n def _get_frame(self, receiver, register):\n for frame in self.frames:\n if frame.receiver == receiver and frame.register == register:\n return frame\n","repo_name":"danielbayerlein/sepicker","sub_path":"sepicker/elster/elster.py","file_name":"elster.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"28584481886","text":"#crean un programa que pida en una función nombre y edad y\r\n# otra función de las guarde en un CSV\r\nimport doctest\r\nimport unittest\r\nimport csv\r\n\r\ndef agregar ():\r\n nom = input(\"Ingrese Nombre: \")\r\n edad = int(input(\"Ingrese su Edad: \"))\r\n guardar(nom, edad)\r\n\r\ndef guardar (nom, edad):\r\n datos = open(\"Infor.csv\", \"a+\", newline='')\r\n escr = csv.writer(datos)\r\n escr.writerow([nom, edad])\r\n datos.close()\r\n return True\r\n\r\nagregar()\r\n\r\nclass SimplisticTest(unittest.TestCase):\r\n\r\n def test(self):\r\n self.assertTrue(guardar(\"nome\", 2))\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n\r\nif __name__ == \"__main__\":\r\n doctest.testmod()","repo_name":"aixa9/uip-prog3","sub_path":"Laboratoria/quiz5.py","file_name":"quiz5.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43102113298","text":"## Importing the necessary packages\nfrom perspective.transform import four_pt_transform\nfrom skimage.filters import threshold_local\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\n\n## Constructing the argument parser\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required=True, help=\"Path to the image to be scanned\")\nargs = vars(ap.parse_args())\n\n\n\n#### Step 1: Edge Detection ####\n## Loading the image and computing the ratio of old and new heights\n## and then resizing the image\nimg = cv2.imread(args['image'])\nratio = img.shape[0]/500\nimg2 = imutils.resize(img, height=500)\n\n## Converting the image to grayscale to find the edges\ngray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\ngray = cv2.GaussianBlur(gray, (5,5), 0)\nedged = cv2.Canny(gray, 75, 200)\n\n## Displaying the original image and the edge detected one.\nprint(\"STEP 1: Edge Detection\")\ncv2.imshow(\"Original\", imutils.resize(img, height=500))\ncv2.imshow(\"Edges\", edged)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n#### Step 2: Finding Contours ####\n## Finding the contours in the edge detected image, and keeping only the largest ones\nconts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\nconts = imutils.grab_contours(conts)\nconts = sorted(conts, key=cv2.contourArea, reverse=True)[:5]\n## Looping over the Contours\nfor c in conts:\n ## Approximating the Contours\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02*peri, True)\n ## If the approximated contour has 4 points, then we can assume to have found the document\n if(len(approx) == 4):\n screenCnt = approx\n break\n## Display the contours of the document\nprint(\"STEP 2: Finding Contours\")\ncv2.drawContours(img2, [screenCnt], -1, (255,0,0), 2)\ncv2.imshow(\"Outlines\", img2)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n#### Step 3: Applying Perspective Transform and Threshold\n## Applyng the 4-point transformfor a top-down view\nwarped = four_pt_transform(img, screenCnt.reshape(4,2)*ratio)\n\n## Converting the warped image to grayscale, and then thresholding to give a 'B&W' effect.\nwarped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)\nT = threshold_local(warped, 11, offset = 10, method = \"gaussian\")\nwarped = (warped > T).astype(\"uint8\") * 255\n\n## Displaying the original and scanned images\nprint(\"STEP 3: Applying Perspective Transform and Threshold\")\ncv2.imshow(\"Original\", imutils.resize(img, height=650))\ncv2.imshow(\"Scanned\", imutils.resize(warped, height= 650))\ncv2.imwrite('scanned.jpg', warped)\ncv2.waitKey(0)\n","repo_name":"prateekb1912/doc-scanner","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19763439356","text":"import re\nfrom collections import namedtuple\n\nfrom datetime import datetime\n\nfrom reversi_zero.lib.util import parse_ggf_board_to_bitboard\n\nGGF = namedtuple(\"GGF\", \"BO MOVES\")\nBO = namedtuple(\"BO\", \"board_type, square_cont, color\") # color: {O, *} (O is white, * is black)\nMOVE = namedtuple(\"MOVE\", \"color pos\") # color={B, W} pos: like 'F5'\n\n\ndef parse_ggf(ggf):\n \"\"\"https://skatgame.net/mburo/ggsa/ggf\n\n :param ggf:\n :rtype: GGF\n \"\"\"\n tokens = re.split(r'([a-zA-Z]+\\[[^\\]]+\\])', ggf)\n moves = []\n bo = None\n for token in tokens:\n match = re.search(r'([a-zA-Z]+)\\[([^\\]]+)\\]', token)\n if not match:\n continue\n key, value = re.search(r'([a-zA-Z]+)\\[([^\\]]+)\\]', token).groups()\n key = key.upper()\n if key == \"BO\":\n bo = BO(*value.split(\" \"))\n elif key in (\"B\", \"W\"):\n moves.append(MOVE(key, value))\n return GGF(bo, moves)\n\n\ndef convert_move_to_action(move_str: str):\n \"\"\"\n\n :param move_str: A1 -> 0, H8 -> 63\n :return:\n \"\"\"\n if move_str[:2].lower() == \"pa\":\n return None\n pos = move_str.lower()\n y = ord(pos[0]) - ord(\"a\")\n x = int(pos[1]) - 1\n return y * 8 + x\n\n\ndef convert_action_to_move(action):\n \"\"\"\n\n :param int|None action:\n :return:\n \"\"\"\n if action is None:\n return \"PA\"\n y = action // 8\n x = action % 8\n return chr(ord(\"A\") + y) + str(x + 1)\n\n\ndef convert_to_bitboard_and_actions(ggf: GGF):\n black, white = parse_ggf_board_to_bitboard(ggf.BO.square_cont)\n actions = []\n for move in ggf.MOVES: # type: MOVE\n actions.append(convert_move_to_action(move.pos))\n return black, white, actions\n\n\ndef make_ggf_string(black_name=None, white_name=None, dt=None, moves=None, result=None, think_time_sec=60):\n \"\"\"\n\n :param str black_name:\n :param str white_name:\n :param datetime|None dt:\n :param str|None result:\n :param list[str] moves:\n :param int think_time_sec:\n :return:\n \"\"\"\n ggf = '(;GM[Othello]PC[RAZSelf]DT[%(datetime)s]PB[%(black_name)s]PW[%(white_name)s]RE[%(result)s]TI[%(time)s]' \\\n 'TY[8]BO[8 ---------------------------O*------*O--------------------------- *]%(move_list)s;)'\n dt = dt or datetime.utcnow()\n\n move_list = []\n for i, move in enumerate(moves or []):\n if i % 2 == 0:\n move_list.append(f\"B[{move}]\")\n else:\n move_list.append(f\"W[{move}]\")\n\n params = dict(\n black_name=black_name or \"black\",\n white_name=white_name or \"white\",\n result=result or '?',\n datetime=dt.strftime(\"%Y.%m.%d_%H:%M:%S.%Z\"),\n time=f\"{think_time_sec // 60}:{think_time_sec % 60}\",\n move_list=\"\".join(move_list),\n )\n return ggf % params\n","repo_name":"mokemokechicken/reversi-alpha-zero","sub_path":"src/reversi_zero/lib/ggf.py","file_name":"ggf.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","stars":658,"dataset":"github-code","pt":"52"} +{"seq_id":"18181544597","text":"\nimport pmtest as pm\nimport pandas as pd\nfrom datetime import datetime\nimport winsound\nimport sys\n\n# Set-up Test Doc should be done here\nDEVICE_NAME = 'Dev4'\ntestdoc = pm.TestDoc()\nts = pm.TestSet(DEVICE_NAME) # MAKE INSTANCE OF TestSet Class\ntestId = 1\ntestName = \"Test 1\"\nmode = \"ULF\"\namp_ua = 1000\npw_us = 200\nipi_us = 30\nrpr = 8\nfrequency = 50\nbias = -42\nload = 100\nchannel_pair = \"E1_2\"\n\n\nts.load = load\nts.ie_connect = \"ON\"\nts.load_hiZ = \"OFF\"\nts.channel_pair = channel_pair\n\nif mode == \"AC\":\n test = pm.AcTest(ts, amp_ua=amp_ua, pw_us=pw_us, ipi_us=ipi_us, rpr=rpr, req_freq=frequency,\n epg_sn='E00007', load=load,\n sample_rate_per_channel=ts.sample_rate_per_channel)\n test_data = test.measure()\n pm.plot_data_frame(test_data, test.name(), \"Amplitude (uA/mV\")\n test_results = pm.TestResultAC(test)\n test_results.print_report()\nelif mode == 'ULF':\n test = pm.ZhTest(ts, amp_ua=amp_ua, epg_sn='E007', load=load,\n sample_rate_per_channel=1000)\n test_data = test.measure()\n pm.plot_data_frame(test_data, test.name(), \"Amplitude (uA/mV\")\n test_results = pm.TestResultZH(test)\n test_results.print_report()\n# pass_fail_count = test_results.results['Pass/Fail'].value_counts().to_dict()\n# print(f'Test Name {test.name()},{datetime.now().strftime(\"%m%d%Y_%H_%M_%S\")},{pass_fail_count}')\n","repo_name":"mikeafaltys/MultimodeEPGTest","sub_path":"single_strategy.py","file_name":"single_strategy.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5731422979","text":"# 육지(L) 바다(W)\n# 상하좌우\n# 한 칸 이동, 한시간\n\nfrom collections import deque\nimport sys\ninput = sys.stdin.readline\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\nx_size, y_size = map(int, input().split())\nisland = [[] for _ in range(x_size)]\n\nL_loc = []\nfor row in range(x_size):\n line = list(input().rstrip())\n\n for col in range(len(line)):\n if line[col] == 'L':\n L_loc.append((row, col))\n\n island[row] = line\n\ntimer = []\nfor i in range(len(L_loc)):\n visited = [[False] * y_size for _ in range(x_size)]\n queue = deque([L_loc[i]])\n\n time = 0\n while queue:\n time += 1\n\n for _ in range(len(queue)):\n x, y = queue.popleft()\n\n visited[x][y] = True\n\n for k in range(4):\n nx = x + dx[k]\n ny = y + dy[k]\n\n if 0 <= nx < x_size and 0 <= ny < y_size and not visited[nx][ny]:\n visited[nx][ny] = True\n if island[nx][ny] == 'L':\n queue.append((nx, ny))\n \n timer.append(time)\nprint(max(timer)-1)","repo_name":"BangDori/python-algorithm","sub_path":"baekjoon/2589.py","file_name":"2589.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34099414982","text":"import sqlalchemy\nimport sys\nfrom os.path import dirname, abspath, join\n\nsys.path.append(dirname(dirname(abspath(__file__))))\nimport config\n\nsys.path.append(join(dirname(dirname(abspath(__file__))), 'utils'))\nfrom db_utils import session_scope\n\ndef load_reference_tables():\n '''\n Create four reference tables from clinical sources. See sql/load_lab_references.sql for definitions.\n @return: None\n '''\n create_tables_sql_filename = 'create_lab_reference_tables.sql'\n with open(join(dirname(abspath(__file__)), \n 'sql', \n create_tables_sql_filename), 'r') as f:\n create_tables_sql = f.read()\n create_tables_sql = create_tables_sql.format(schema_name = config.nonstationarity_schema_name)\n \n engine = sqlalchemy.create_engine('postgresql://' + config.db_name,\n echo=False,\n connect_args = {\"host\": '/var/run/postgresql/'})\n with session_scope(engine) as session:\n session.execute(sqlalchemy.text(create_tables_sql))\n session.commit()\n \n table_name_to_file_name = {'measurement_references_from_sources' : 'lab_thresholds.csv',\n 'measurement_unit_specific_references_from_sources': 'lab_unit_specific_thresholds.csv',\n 'measurement_units_to_drop' : 'lab_units_to_drop.csv',\n 'measurements_out_of_range' : 'lab_measurements_out_of_range.csv'}\n \n conn = engine.raw_connection()\n cursor = conn.cursor()\n for table_name in table_name_to_file_name:\n copy_sql = 'COPY {table_name} FROM STDIN WITH (FORMAT CSV, HEADER)'\n copy_sql = copy_sql.format(table_name = table_name)\n with open(join(dirname(abspath(__file__)), \n 'lab_references', \n table_name_to_file_name[table_name]), 'r') as f:\n cursor.copy_expert(copy_sql, f)\n conn.commit()\n \n index_tables_sql_filename = 'index_lab_reference_tables.sql'\n with open(join(dirname(abspath(__file__)), \n 'sql', \n index_tables_sql_filename), 'r') as f:\n index_tables_sql = f.read()\n index_tables_sql = index_tables_sql.format(schema_name = config.nonstationarity_schema_name)\n with session_scope(engine) as session:\n session.execute(sqlalchemy.text(index_tables_sql))\n session.commit()\n \nif __name__ == '__main__':\n load_reference_tables()","repo_name":"clinicalml/large-scale-temporal-shift-study","sub_path":"data_extraction/load_lab_references.py","file_name":"load_lab_references.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"27204818634","text":"import random\r\nimport scipy.ndimage\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport scipy.io\r\nfrom scipy.signal import medfilt\r\n\r\n# show amplitude & distance image\r\ndef show_image(matrix, title):\r\n plt.imshow(matrix)\r\n plt.title(title)\r\n plt.show()\r\n\r\n# invert point cloud into a matrix with only 3 columns\r\ndef reshape_pc(matrix):\r\n matrix = matrix.reshape(len(matrix) * len(matrix[0]), 3)\r\n return matrix\r\n\r\n# show 3D point cloud\r\ndef show_point_cloud(matrix, subsample, title):\r\n ax = plt.subplot(111, projection='3d')\r\n x = matrix[::subsample, 0]\r\n y = matrix[::subsample, 1]\r\n z = matrix[::subsample, 2]\r\n ax.scatter(x, y, z)\r\n ax.set_title(title)\r\n plt.show()\r\n\r\n# using 3 points to determine a plane\r\ndef find_plane(point1, point2, point3):\r\n point1 = np.asarray(point1)\r\n point2 = np.asarray(point2)\r\n point3 = np.asarray(point3)\r\n AB = point2 - point1\r\n AC = point3 - point1\r\n # to get the normal vector of the plane\r\n n = np.cross(AB, AC)\r\n # calculate d with nx=d\r\n d = np.dot(n,point1)\r\n return n, d\r\n\r\n# calculate the distance (a set of points) from another point to the plane\r\ndef cal_distance(point1, point2, point3, point4):\r\n n, d = find_plane(point1, point2, point3)\r\n numerator = abs(n[0] * point4[:, 0] + n[1] * point4[:, 1] + n[2] * point4[:, 2] - d)\r\n denominator = np.sqrt(np.sum(np.square([n])))\r\n distance = numerator / denominator\r\n return distance\r\n\r\n# use RANSAC algorithm to find the plane models with the most inliers\r\ndef ransac(matrix, threshold, N):\r\n max_inlier = 0\r\n best_plane = None\r\n for i in range(N):\r\n list = range(len(matrix))\r\n samples = random.sample(list, 3)\r\n point1 = matrix[samples[0]]\r\n point2 = matrix[samples[1]]\r\n point3 = matrix[samples[2]]\r\n dis_array = cal_distance(point1, point2, point3, matrix)\r\n # invert int to bool, note that true as 1, false as 0\r\n model = dis_array < threshold # shape should be (len(matrix),) and type is bool\r\n n_inliers = np.count_nonzero(model)\r\n if n_inliers > max_inlier:\r\n max_inlier = n_inliers\r\n best_plane = model\r\n return max_inlier, best_plane\r\n\r\n# because the best_plane is bool\r\n# convert single column array to a 3-columns array\r\ndef mask_image(matrix, model):\r\n model1 = np.c_[model, model, model] # model is a single column array, so convert to 3 column\r\n new_model = matrix[model1] # shape is changed to one row array\r\n new_model = np.reshape(new_model, (len(new_model) // 3, 3)) # reshape to 3 column\r\n return new_model\r\n\r\n# inliers = 1, outliers = 0, but dilation to the bigger shape\r\ndef visualize_mask(shape_bool, plane_model): # they should be both single column\r\n mask_result = np.zeros(len(shape_bool), dtype=bool)\r\n j = 0\r\n for i in range(len(shape_bool)):\r\n if shape_bool[i] == True:\r\n mask_result[i] = plane_model[j]\r\n j = j + 1\r\n else:\r\n mask_result[i] = shape_bool[i]\r\n return mask_result\r\n\r\n# morphology.binary_closing operator\r\ndef closing_mask(matrix, iteration):\r\n result = scipy.ndimage.morphology.binary_closing(matrix, iterations = iteration)\r\n return plt.imshow(result)\r\n\r\n# morphology.binary_opening operator\r\ndef opening_mask(matrix, iteration):\r\n result = scipy.ndimage.morphology.binary_opening(matrix, iterations = iteration)\r\n return plt.imshow(result)\r\n\r\n# opening operator without show\r\ndef opening_mask_noShow(matrix, iteration):\r\n result = scipy.ndimage.morphology.binary_opening(matrix, iterations = iteration)\r\n return result\r\n\r\n\r\n# closing operator without show\r\ndef closing_mask_noShow(matrix, iteration):\r\n result = scipy.ndimage.morphology.binary_closing(matrix, iterations = iteration)\r\n return result\r\n\r\ndef label_opening(matrix, iteration):\r\n matrix2 = opening_mask_noShow(matrix, iteration)\r\n labeled_array, num_features = scipy.ndimage.label(matrix2)\r\n print('number of features with opening Operators: ', num_features)\r\n return opening_mask(matrix, iteration)\r\n\r\ndef label_closing(matrix, iteration):\r\n matrix2 = closing_mask_noShow(matrix, iteration)\r\n labeled_array, num_features = scipy.ndimage.label(matrix2)\r\n print('number of features with closing Operators: ', num_features)\r\n return closing_mask(matrix, iteration)\r\n\r\n# calculate the height of the box\r\ndef cal_height2(top_plane_3D, floor_plane_3D, iteration):\r\n height = 0\r\n for i in range(iteration):\r\n list = range(len(floor_plane_3D))\r\n samples = random.sample(list, 3)\r\n point1_floor = floor_plane_3D[samples[0]]\r\n point2_floor = floor_plane_3D[samples[1]]\r\n point3_floor = floor_plane_3D[samples[2]]\r\n height = height + np.mean(cal_distance(point1_floor, point2_floor, point3_floor, top_plane_3D))\r\n height_average = height / iteration\r\n return height_average\r\n\r\n# calculate all the distance of from every two points\r\ndef smallst_dis(number, list1):\r\n listNew = []\r\n j = 1\r\n while number + j <= 5:\r\n distance = np.sqrt(np.sum(np.square(list1[number] - list1[number + j])))\r\n listNew.append(distance)\r\n j = j + 1\r\n return min(listNew)\r\n\r\n\r\ndef smallestDis(point_, point_list):\r\n listDis = []\r\n for i in range(len(point_list)):\r\n distance = np.sum(np.square(point_list[i] - point_))\r\n listDis.append(distance)\r\n return min(listDis)\r\n\r\n# find the corresponded smallstIndex in corners1 and corners2\r\ndef returnProjection(smallstIndex_inpt, corners1_input, corners2_input):\r\n if smallstIndex_inpt <= 2:\r\n return corners1_input[smallstIndex_inpt]\r\n else:\r\n return corners2_input[smallstIndex_inpt - 3]\r\n\r\n# ----------------------------------\r\n# Step1. Getting and reading the data\r\n# load the examples from matlab file\r\nmat1=scipy.io.loadmat(\"example1kinect.mat\")\r\n\r\n# show the amplitude image\r\nshow_image(mat1['amplitudes1'], 'amplitude image')\r\n\r\n# show the distance image\r\nshow_image(mat1['distances1'], 'distance image')\r\n\r\n# point cloud visualization\r\ncloud1 = mat1['cloud1'] # shape: (424, 512, 3)\r\ncloud1 = reshape_pc(cloud1) # shape: (217088, 3: X,Y,Z)\r\nshow_point_cloud(cloud1, 8, 'point cloud with subsampling 8')\r\n\r\n# -------------------------------------\r\n# Step2. RANSAC\r\n# ignoring the points which the z-component of a vector is 0, that means all points are valid\r\nfilted_cloud1 = cloud1[:, 2] > 0 # bool shape:(217088,)\r\ncloud1_nonzeroz = mask_image(cloud1, filted_cloud1) # shape: (202007, 3), remove all of the false points\r\n\r\n# ransac to find floor plane model and output the inliers\r\nfloor_inlier, floor_plane = ransac(cloud1_nonzeroz, 0.05, 500) # shape of floor plane: (202007, )\r\nprint('max inliers of floor plane:', floor_inlier)\r\n\r\n# because the obtained best floor plane is bool, it must be converted\r\n# The points that belong to the floor plane are labeled True, and delete the points that not belong to floor\r\n# remove the points that not belong to the floor plane\r\nfloor_plane_3D = mask_image(cloud1_nonzeroz, floor_plane) # shape: (~150000,3)\r\nshow_point_cloud(floor_plane_3D, 4, '3D floor plane with subsample 4')\r\n\r\n# now we want to show the distance image of the floor plane\r\n# mask image that inliers of the floor=1 and other as outliers=0\r\n# shape of bool filted_cloud1 : (217088,),\r\nmask2 = visualize_mask(filted_cloud1, floor_plane) # fill the image to the original shape\r\nfloor_plane_2D = np.reshape(mask2, mat1['distances1'].shape) # shape: (424,512)\r\nshow_image(floor_plane_2D, '2D floor plane')\r\n\r\n# --------------------------------\r\n# Step3. Filtering on the Mask Image\r\n# morphological operator: opening\r\n# Result: The iteration times can not be too big, otherwise it will make noisier\r\n# opening operator: remove the small regions\r\nplt.figure()\r\nplt.suptitle('opening operator with different iterations')\r\nplt.subplot(221)\r\nopening_mask(floor_plane_2D, 1)\r\nplt.title('iteration=1')\r\nplt.subplot(222)\r\nopening_mask(floor_plane_2D, 2)\r\nplt.title('iteration=2')\r\nplt.subplot(223)\r\nopening_mask(floor_plane_2D, 3)\r\nplt.title('iteration=3')\r\nplt.subplot(224)\r\nopening_mask(floor_plane_2D, 4)\r\nplt.title('iteration=4')\r\nplt.show()\r\n\r\n\r\n# morphological operator: closing\r\n# closing: remove the holes\r\n# in case: time=500, dis=0.05, iteration=8 has best effect,smaller has noise,bigger makes distortion\r\nplt.figure()\r\nplt.suptitle('closing operator with different iterations')\r\nplt.subplot(221)\r\nclosing_mask(floor_plane_2D, 6)\r\nplt.title('iteration=6')\r\nplt.subplot(222)\r\nclosing_mask(floor_plane_2D, 7)\r\nplt.title('iteration=7')\r\nplt.subplot(223)\r\nclosing_mask(floor_plane_2D, 8)\r\nplt.title('iteration=8')\r\nplt.subplot(224)\r\nclosing_mask(floor_plane_2D, 9)\r\nplt.title('iteration=9')\r\nplt.show()\r\n\r\nbest_floor = closing_mask_noShow(floor_plane_2D, 8)\r\nclosing_mask(floor_plane_2D, 8)\r\nplt.title('filted floor with closing iteration=8')\r\nplt.show()\r\n\r\n\r\n# find all pixels that not belong the floor\r\nother_points_bool = ~floor_plane # shape: (202007,)\r\nother_points = mask_image(cloud1_nonzeroz, other_points_bool) # reserve true, remove false, shape: (45746, 3)\r\n\r\n# -------------------------------\r\n# Step4. Finding the Top Plane of the Box\r\n# using RANSAC to find the dominant plane within this except floor set\r\n# note: when the threshold= 0.035, the number of feature without preprossing= 1\r\ntop_inlier, top_plane = ransac(other_points, 0.005, 1000)\r\nprint('max inliers of top plane:', top_inlier)\r\n\r\n# remove points that not belong top plane from other points\r\ntop_plane_3D = mask_image(other_points, top_plane) # shape: (35000,3)\r\nshow_point_cloud(top_plane_3D, 4, '3D top plane with subsample 4')\r\n\r\n# show 2D top plane\r\n# firstly we filter the other point and reserve top plane\r\n# The number of True in other_points_bool= the row number of top_plane\r\nmask3 = visualize_mask(other_points_bool, top_plane)\r\n# then we fill the array that should be same as the original shape, (217088, )\r\nmask4 = visualize_mask(filted_cloud1, mask3)\r\ntop_plane_2D = np.reshape(mask4, mat1['distances1'].shape) # shape: (424,512)\r\nshow_image(top_plane_2D, '2D top plane')\r\n\r\n# find the largest connected component in the mask with scipy's label\r\n# optimal: number of features= 1 ?\r\nlabeled_array, num_features = scipy.ndimage.label(top_plane_2D)\r\nprint('number of features: ', num_features)\r\n\r\n# try to use opening and closing operator\r\n# Conclusion: processing will improve the result\r\n# by comparing the processed images, I think opening operator with 3 iterations is better\r\n# opening operator: remove the small regions (noise)\r\nplt.figure()\r\nplt.suptitle('labeled opening operator with different iterations')\r\nplt.subplot(221)\r\nlabel_opening(top_plane_2D, 1)\r\nplt.title('iteration=1')\r\nplt.subplot(222)\r\nlabel_opening(top_plane_2D, 2)\r\nplt.title('iteration=2')\r\nplt.subplot(223)\r\nlabel_opening(top_plane_2D, 3)\r\nplt.title('iteration=3')\r\nplt.subplot(224)\r\nlabel_opening(top_plane_2D, 4)\r\nplt.title('iteration=4')\r\nplt.show()\r\n\r\nplt.figure()\r\nplt.suptitle('labeled closing operator with different iterations')\r\nplt.subplot(221)\r\nlabel_closing(top_plane_2D, 1)\r\nplt.title('iteration=1')\r\nplt.subplot(222)\r\nlabel_closing(top_plane_2D, 2)\r\nplt.title('iteration=2')\r\nplt.subplot(223)\r\nlabel_closing(top_plane_2D, 3)\r\nplt.title('iteration=3')\r\nplt.subplot(224)\r\nlabel_closing(top_plane_2D, 4)\r\nplt.title('iteration=4')\r\nplt.show()\r\n\r\n# show the processed top plane\r\n# actually the goal is removing noise, so we can only use the opening\r\nbest_top = opening_mask_noShow(top_plane_2D, 3)\r\nshow_image(best_top, 'filted top with opening iteration=3')\r\n\r\n# overlap the top plane on the 2D distance image of the floor plane\r\n# distance image, different values mean different color\r\n# so multiple any number to distinguish the top and floor\r\noverlap_topfloor = 4 * best_top + best_floor\r\nshow_image(overlap_topfloor, 'overlaped image')\r\n\r\n\r\n# ---------------------\r\n# Step5. Measuring the Dimensions of the Box\r\n# calculation the height of the box)\r\nheight = cal_height2(top_plane_3D, floor_plane_3D, 400)\r\nprint('height of the box= ', height)\r\n\r\n# find the 3D-coordinates of the corners\r\n# firstly I want to convert the top_best from 2D to 3D like top_plane_3D\r\nbest_top_1D = np.reshape(best_top, best_top.shape[0] * best_top.shape[:][1]) # best_top: (424, 512)\r\nbest_top_1D_3 = np.c_[best_top_1D, best_top_1D, best_top_1D]\r\n# delete the false and generate a single column array which includes all the 3D top plane float data\r\nbest_top_3D = cloud1[best_top_1D_3]\r\nbest_top_3D = np.reshape(best_top_3D, (len(best_top_3D) // 3, 3)) # shape: (36100, 3)\r\nshow_point_cloud(best_top_3D, 3, 'best_top_3D')\r\n\r\n# capture corners\r\n# firstly we get six special points, which four of them should be the corners\r\ncorners1 = best_top_3D.argmax(axis=0)\r\ncorners2 = best_top_3D.argmin(axis=0)\r\npc0 = best_top_3D[corners1[0]]\r\npc1 = best_top_3D[corners1[1]]\r\npc2 = best_top_3D[corners1[2]]\r\npc3 = best_top_3D[corners2[0]]\r\npc4 = best_top_3D[corners2[1]]\r\npc5 = best_top_3D[corners2[2]]\r\nlist1 = [pc0, pc1, pc2, pc3, pc4, pc5]\r\n\r\n# To find the four corners form the mentioned six points, we calculate the min distances each other\r\n# And delete the two which have minimum distances\r\nlist_distance = []\r\nfor ii in range(5):\r\n kleinest_dis = smallestDis(list1[ii], list1[ii+1:])\r\n list_distance.append(kleinest_dis)\r\nsmallst_index = np.argsort(list_distance) # [2 0 3 1 4]\r\ncornerPoint1 = list1[smallst_index[2]]\r\ncornerPoint2 = list1[smallst_index[3]]\r\ncornerPoint3 = list1[smallst_index[4]]\r\ncornerPoint4 = list1[5]\r\n\r\n# return the 3D corner points to the 2D overlapped image\r\npoint_find0 = returnProjection(smallst_index[2], corners1, corners2)\r\npoint_find1 = returnProjection(smallst_index[3], corners1, corners2)\r\npoint_find2 = returnProjection(smallst_index[4], corners1, corners2)\r\npoint_find3 = corners2[2] # the last point\r\nmark_cornerfind = np.zeros(len(best_top_3D), dtype=bool) # all points in best top\r\nmark_cornerfind[point_find0] = True\r\nmark_cornerfind[point_find1] = True\r\nmark_cornerfind[point_find2] = True\r\nmark_cornerfind[point_find3] = True\r\nmark_cornerfind_least = visualize_mask(best_top_1D, mark_cornerfind)\r\ncornerFind_2dMatrix = np.reshape(mark_cornerfind_least, (424, 512)) # only cp True, others False\r\nnoZero_2d = np.nonzero(cornerFind_2dMatrix)\r\ny_way = noZero_2d[0][:]\r\nx_way = noZero_2d[1][:]\r\n\r\n# 在2Dimage中展示那四个角点\r\nplt.imshow(overlap_topfloor)\r\nplt.title('Overlapping image with 4 corners')\r\nplt.scatter(x_way, y_way, s=40, c='r')\r\nplt.show()\r\n\r\n# calculate the side length from every two points\r\nlong12 = np.sqrt(np.sum(np.square(cornerPoint1 - cornerPoint2)))\r\nlong13 = np.sqrt(np.sum(np.square(cornerPoint1 - cornerPoint3)))\r\nlong14 = np.sqrt(np.sum(np.square(cornerPoint1 - cornerPoint4)))\r\nlong23 = np.sqrt(np.sum(np.square(cornerPoint2 - cornerPoint3)))\r\nlong24 = np.sqrt(np.sum(np.square(cornerPoint2 - cornerPoint4)))\r\nlong34 = np.sqrt(np.sum(np.square(cornerPoint3 - cornerPoint4)))\r\n# corresponding [2*short side, 2* long side, 2* diagonal side]\r\nlength = [long12, long13, long14, long23, long24, long34]\r\nlength.sort()\r\nwidth1 = length[0]\r\nwidth2 = length[1]\r\nlength1 = length[2]\r\nlength2 = length[3]\r\nprint('width of box= ', width1, ' and ', width2)\r\nprint('length of box=', length1, ' and ', length2)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"wuyouliaoxi/CV","sub_path":"Edge Detection/Ex-01_example1.py","file_name":"Ex-01_example1.py","file_ext":"py","file_size_in_byte":15362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6114586397","text":"# Project: Bank Application\n\nclass Bank:\n\n # Dunder Method | Magic Method\n def __init__(self, initial_amount=0.00):\n self.balance = initial_amount\n\n def deposit(self, amount):\n try:\n amount = float(amount)\n except ValueError:\n amount = 0\n if amount:\n self.balance = self.balance + amount\n self.transactions_log(f\"Deposited amount Rs.{amount}\")\n\n def withdraw(self, amount):\n try:\n amount = float(amount)\n except ValueError:\n amount = 0\n if amount:\n self.balance = self.balance - amount\n self.transactions_log(f\"Withdrew amount Rs.{amount}\")\n\n def transactions_log(self, transaction_string):\n # Context Manager\n with open(\"transactions.txt\", \"a\") as file:\n file.write(f\"{transaction_string} \\t\\t\\tBalance: {self.balance}\\n\")\n\n file.close()\n\n\n# Object instantiation\naccount = Bank(1000.00)\n\nwhile True:\n print(\"\"\"\\nOption Menu:\n****************************\n 1. Deposit an amount\n 2. Withdraw an amount\n 3. Account Balance\n 4. Leaving the ATM\n****************************\n \"\"\")\n options = [\"1\", \"2\", \"3\", \"4\"]\n\n try:\n action = input(\"Your Choice: \")\n except KeyboardInterrupt:\n print(\"\\nLeaving the ATM\\n\")\n exit()\n\n except NameError:\n print(\"Sorry,action not defined!\")\n break\n\n if action in options:\n if action == \"1\":\n amount = input(\"How much amount, do you want to deposit: \")\n account.deposit(amount)\n elif action == \"2\":\n amount = input(\"How much amount, do you want to withdraw: \")\n account.withdraw(amount)\n\n elif action == \"3\":\n pass\n # print(\"Your balance: \", account.balance)\n\n elif action == \"4\":\n print(\"\\nLeaving the ATM\\n\")\n exit()\n\n print(\"Your balance: \", account.balance)\n\n else:\n print(\"That is not a valid action, try again!\")\n continue\n","repo_name":"zaheerniazipk/Banking-App","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70255092964","text":"#treat center of hoop as origin\n\nimport csv\n\n#team a variables\nteamA = []\nAx = []\nAy = []\nC3countA = 0\nC3MadeA = 0\nNC3countA = 0\nNC3MadeA = 0\nTwoPointCountA = 0\nTwoPointMadeA = 0\ntotalShotsA = 0\ntotalMadeA = 0\n\n#team b variables\nteamB = []\nBx = []\nBy = []\nC3countB = 0\nC3MadeB = 0\nNC3countB = 0\nNC3MadeB = 0\nTwoPointCountB = 0\nTwoPointMadeB = 0\ntotalShotsB = 0\ntotalMadeB = 0\n\nwith open('shots_data.csv', 'r') as csv_file:\n csv_reader = csv.reader(csv_file)\n for column in csv_reader:\n\n #organize what each column is\n team = column[0]\n Xcord = column[1]\n Ycord = column[2]\n madeShot = column[3]\n\n A = \"Team A\"\n B = \"Team B\"\n if team == A:\n if float(madeShot) == 1:\n totalMadeA += 1\n #store coordinates for team A\n XcordA = float(Xcord)\n YcordA = float(Ycord)\n #store coordinates into list\n Ax.append(XcordA)\n Ay.append(YcordA)\n #if its not a shot attempted below 7.8 feet\n if YcordA > 7.8:\n #checks if its a 3 or not only using y cord because it is going to be independent of x\n if YcordA > 23.75:\n #keeps track of made shots in each zone\n if float(madeShot) == 1:\n totalShotsA += 1\n NC3countA += 1\n NC3MadeA += 1\n #print(\"non corner 3 made\", NC3MadeA)\n else:\n totalShotsA += 1\n NC3countA += 1\n #print(\"non corner 3 missed\")\n #check if 3 or not also using x because it is dependent on y\n if YcordA > 7.8 and XcordA > 23.75:\n if float(madeShot) == 1:\n totalShotsA += 1\n NC3countA += 1\n NC3MadeA += 1\n #print(\"non corner 3 made\", NC3MadeA)\n else:\n totalShotsA += 1\n NC3countA += 1\n #print(\"non corner 3 missed\")\n if YcordA < 23.75:\n if float(madeShot) == 1:\n totalShotsA += 1\n TwoPointCountA += 1\n TwoPointMadeA += 1\n #print(\"2 point made\", TwoPointMadeA)\n else:\n totalShotsA += 1\n TwoPointCountA += 1\n #print(\"2 point attempt missed\")\n #check for corner 3s\n if YcordA <= 7.8:\n #will be independent of y cord because its below 7.8\n if abs(XcordA) > 22:\n if float(madeShot) == 1:\n totalShotsA += 1\n C3MadeA += 1\n C3countA += 1\n #print(\"corner 3 made\", C3MadeA)\n else:\n totalShotsA += 1\n C3countA += 1\n #print(\"corner 3 missed\")\n if abs(XcordA) < 22:\n if float(madeShot) == 1:\n totalShotsA += 1\n TwoPointMadeA += 1\n TwoPointCountA += 1\n #print(\"2 point made\", TwoPointMadeA)\n else:\n TwoPointCountA += 1\n totalShotsA += 1\n #print(\"2 point missed\")\n\n #team b\n if B == team:\n if float(madeShot) == 1:\n totalMadeB += 1\n #store coordinates for team B\n XcordB = float(Xcord)\n YcordB = float(Ycord)\n #store coordinates into list\n Bx.append(XcordB)\n By.append(YcordB)\n #if its not a shot attempted below 7.8 feet\n if YcordB > 7.8:\n #checks if its a 3 or not only using y cord because it is going to be independent of x\n if YcordB > 23.75:\n #keeps track of made shots in each zone\n if float(madeShot) == 1:\n totalShotsB+= 1\n NC3countB += 1\n NC3MadeB += 1\n #print(\"Team B: non corner 3 made\", NC3MadeB)\n else:\n totalShotsB += 1\n NC3countB += 1\n #print(\"Team B: non corner 3 missed\")\n #check if 3 or not also using x because it is dependent on y\n if YcordB > 7.8 and XcordB > 23.75:\n if float(madeShot) == 1:\n totalShotsB += 1\n NC3countB += 1\n NC3MadeB += 1\n #print(\"Team B: non corner 3 made\", NC3MadeB)\n else:\n totalShotsB += 1\n NC3countB += 1\n #print(\"Team B: non corner 3 missed\")\n if YcordB < 23.75:\n if float(madeShot) == 1:\n totalShotsB += 1\n TwoPointCountB += 1\n TwoPointMadeB += 1\n #print(\"Team B: 2 point made\", TwoPointMadeB)\n else:\n totalShotsB += 1\n TwoPointCountB += 1\n #print(\"Team B: 2 point attempt missed\")\n #check for corner 3s\n if YcordB <= 7.8:\n #will be independent of y cord because its below 7.8\n if abs(XcordB) > 22:\n if float(madeShot) == 1:\n totalShotsB += 1\n C3MadeB += 1\n C3countB += 1\n #print(\"Team B: corner 3 made\", C3MadeB)\n else:\n totalShotsB += 1\n C3countB += 1\n #print(\"Team B: corner 3 missed\")\n if abs(XcordB) < 22:\n if float(madeShot) == 1:\n totalShotsB += 1\n TwoPointMadeB += 1\n TwoPointCountB += 1\n #print(\"Team B: 2 point made\", TwoPointMadeB)\n else:\n TwoPointCountB += 1\n totalShotsB += 1\n #print(\"Team B: 2 point missed\")\n \n#team A shot distribution and eFG\n #Team A percentage for shots\n CornerShotA = float(C3countA) / float(totalShotsA)\n TwoPointShotA = float(TwoPointCountA) / float(totalShotsA)\n NonCornerShotA = float(NC3countA) / float(totalShotsA)\n\n #Team B percentage for shots\n CornerShotB = float(C3countB) / float(totalShotsB)\n TwoPointShotB = float(TwoPointCountA) / float(totalShotsB)\n NonCornerShotB = float(NC3countB) / float(totalShotsB) \n\n #Team A eFG\n eFGcornerA = (float(C3MadeA) + (.5 * float(C3MadeA)))/ float(C3countA)\n eFGTwoPointA = float(TwoPointMadeA) / float(TwoPointCountA)\n eFGNCA = (float(NC3MadeA) + (.5 * float(NC3MadeA))) / float(NC3countA)\n #Team B eFG\n eFGcornerB = (float(C3MadeB) + (.5 * float(C3MadeB))) / float(C3countB)\n eFGTwoPointB = float(TwoPointMadeB) / float(TwoPointCountB)\n eFGNCB = (float(NC3MadeB) + (.5 * float(NC3MadeB))) / float(NC3countB)\n\n #print statement for team A\n print('Team A attempted ' + format(CornerShotA, '.3%') + ' of their shots on corner threes, ' +\n format(NonCornerShotA, '.3%') + ' of their shots on normal threes, and ' + format(TwoPointShotA, '.3%') + ' on two point shots.')\n\n print('Team A had an eFG of ' + format(eFGcornerA,'.3%') + ' from the corner on ' + str(C3countA) + ' attempt(s), they had an eFG of ' \n + format(eFGNCA, '.3%') + ' on regular three pointers with ' + str(NC3countA) + ' attempt(s),')\n\n print( 'and they had an eFG of ' + format(eFGTwoPointA, '.3%') +\n ' on ' + str(TwoPointCountA) + ' attempt(s) on two pointers.' )\n print(' ')\n\n #print statement for team B\n print('Team B attempted ' + format(CornerShotB, '.3%') + ' of their shots on corner threes, ' +\n format(NonCornerShotB, '.3%') + ' of their shots on normal threes, and ' + format(TwoPointShotB, '.3%') + ' on two point shots.')\n\n print('Team B had an eFG of ' + format(eFGcornerB,'.3%') + ' from the corner on ' + str(C3countB) + ' attempt(s), they had an eFG of ' \n + format(eFGNCB, '.3%') + ' on regular three pointers with ' + str(NC3countB) + ' attempt(s),')\n\n print( 'and they had an eFG of ' + format(eFGTwoPointB, '.3%') +\n ' on ' + str(TwoPointCountB) + ' attempt(s) on two pointers.' )\n \n\n\n \n","repo_name":"rsigdel2/TechnicalAssessment","sub_path":"finalSolution.py","file_name":"finalSolution.py","file_ext":"py","file_size_in_byte":8813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30756253390","text":"class Node():\r\n def __init__(self, value):\r\n self.value = value \r\n self.next = None\r\n self.prev = None\r\n \r\nclass Dll():\r\n def __init__(self):\r\n self.head = None\r\n self.tail = None\r\n self.length = 0\r\n \r\n def print(self):\r\n temp = self.head\r\n while temp:\r\n print(temp.value)\r\n temp = temp.next\r\n \r\n def append(self, value):\r\n new = Node(value)\r\n if self.length > 0:\r\n self.tail.next = new\r\n new.prev = self.tail\r\n self.tail = new\r\n else:\r\n self.head = new\r\n self.tail = new\r\n self.length += 1\r\n \r\n def pop(self):\r\n if self.length == 0:\r\n return None\r\n temp = self.tail\r\n if self.length == 1:\r\n self.head = None\r\n self.tail = None\r\n else:\r\n self.tail = temp.prev\r\n self.tail.next = None\r\n temp.prev = None\r\n self.length -=1\r\n \r\n def prepend(self, value):\r\n new = Node(value)\r\n if self.length == 0:\r\n self.head = new\r\n self.tail = new\r\n else:\r\n new.next = self.head\r\n self.head.prev = new\r\n self.head = new\r\n self.length += 1\r\n \r\n def pop_first(self):\r\n if self.length == 0:\r\n return None\r\n if self.length == 1:\r\n self.head = None\r\n self.tail = None\r\n else:\r\n temp = self.head\r\n self.head = temp.next\r\n temp.next = None\r\n self.length -= 1\r\n \r\n def get(self, index):\r\n if index < 0 or index >= self.length:\r\n return None\r\n if index <= self.length/2:\r\n result = self.head\r\n for _ in range(index):\r\n result = result.next\r\n else:\r\n result = self.tail\r\n for _ in range(self.length - index - 1):\r\n result = result.prev\r\n return result\r\n \r\n def set(self, index, value):\r\n if index < 0 or index >= self.length:\r\n return False\r\n target = self.get(index)\r\n target.value = value\r\n \r\n def insert(self, index, value):\r\n if index < 0 or index > self.length:\r\n return False\r\n if index == 0:\r\n self.prepend(value)\r\n elif index == self.length:\r\n self.append(value)\r\n else:\r\n new = Node(value)\r\n curr = self.get(index)\r\n prev = curr.prev\r\n prev.next = new\r\n new.prev = prev\r\n new.next = curr\r\n curr.prev = new\r\n self.length += 1\r\n \r\n def remove(self, index):\r\n if index < 0 or index >= self.length:\r\n return None\r\n if index == 0:\r\n self.pop_first()\r\n elif index == self.length -1:\r\n self.pop()\r\n else:\r\n temp = self.get(index)\r\n before = temp.prev\r\n after = temp.next\r\n before.next =after\r\n after.prev = before\r\n temp.prev = None\r\n temp.next = None\r\n self.length -= 1\r\n return temp\r\n \r\n def swap_first_last(self):\r\n temp = self.head.value\r\n self.set(0, self.tail.value)\r\n self.set(self.length - 1, temp)\r\n return True\r\n \r\n def reverse(self):\r\n if self.length <= 0:\r\n return None\r\n if self.length == 1:\r\n return self.head\r\n last = self.tail\r\n for _ in range(self.length-2):\r\n temp = self.tail.prev\r\n self.tail.prev = temp.prev\r\n last.next = temp\r\n temp.prev = last\r\n last = temp\r\n last.next = self.head\r\n self.head.prev = last\r\n self.head.next = None\r\n self.tail.prev = None\r\n self.head, self.tail = self.tail, self.head\r\n return True\r\n \r\n def is_palindrome(self):\r\n if self.length % 2 == 0:\r\n return False\r\n else:\r\n mid = self.head\r\n for _ in range(self.length//2):\r\n mid = mid.next\r\n left = mid\r\n right = mid\r\n for _ in range(self.length//2):\r\n left = left.prev\r\n right = right.next\r\n if left.value != right.value:\r\n return False\r\n return True\r\n \r\n def swap_pairs(self):\r\n if self.length <2:\r\n return False\r\n if self.length % 2 == 0:\r\n A = self.head\r\n for _ in range(self.length//2):\r\n B = A.next\r\n A.next = B.next\r\n B.prev = A.prev\r\n B.next = A\r\n A.prev = B\r\n if B.prev != None:\r\n B.prev.next = B\r\n if A.next != None:\r\n A.next.prev = A\r\n A = A.next\r\n self.head = self.head.prev\r\n self.tail = self.tail.next\r\n return True\r\n else:\r\n return False\r\n\r\n \r\n \r\n \r\n \r\ndll = Dll()\r\n\r\ndll.append(111)\r\ndll.append(222)\r\ndll.append(777)\r\ndll.append(888)\r\n\r\n# dll.prepend(1)\r\n# dll.prepend(2)\r\n# dll.insert(6, 100)\r\n# dll.remove(6)\r\n\r\n# dll.pop()\r\n# dll.pop_first()\r\n# print(dll.get(4).value)\r\n# dll.set(4, 100)\r\n\r\n# dll.swap_first_last()\r\n# dll.reverse()\r\n# print(dll.is_palindrome())\r\n# dll.swap_pairs()\r\n\r\ndll.print()\r\n","repo_name":"giorgiush/DSA","sub_path":"DLL.py","file_name":"DLL.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20119579131","text":"# ------------------------------------------------------------------------\n# InstanceFormer data pre-processing\n# ------------------------------------------------------------------------\n\nimport json\nimport os\nimport yaml\n\ndef coto_keep_for_ovis(coco_path):\n ids_json_file =f'{coco_path}/annotations/instances_train2017.json'\n with open(ids_json_file, 'r') as fh:\n samples = json.load(fh)\n with open(os.path.join('./meta/coco.yaml'), 'r') as fh:\n category_details = yaml.load(fh, Loader=yaml.SafeLoader)\n category_details = {cat['id']: cat for cat in category_details}\n cat_ids_to_keep = [cat_id for cat_id, attribs in category_details.items() if attribs['keep_ovis']]\n samples['annotations'] = [ann for ann in samples['annotations'] if ann['category_id'] in cat_ids_to_keep]\n image_ids_to_keep = list(set([ann['image_id'] for ann in samples['annotations']]))\n samples['images'] = [img for img in samples['images'] if img['id'] in image_ids_to_keep]\n\n with open('coco_keepfor_ovis.json', 'w', encoding='utf-8') as f:\n json.dump(samples, f, ensure_ascii=False, indent=4)\n\nif __name__ == '__main__':\n coco_path = \"set_coco_path\"\n coto_keep_for_ovis(coco_path)","repo_name":"rajatkoner08/InstanceFormer","sub_path":"datasets/coco_keep_for_ovis.py","file_name":"coco_keep_for_ovis.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"19327054025","text":"from datetime import date, time, datetime\nfrom test.test_utils import client_fixture\n\n\ndef test_get_weather(client_fixture):\n resp = client_fixture.get(\n \"weather\", params={\"city_name\": \"New York\", \"date\": \"2023-02-21\"}\n )\n assert resp.json()[\"city_name\"] == \"New York\"\n assert len(resp.json()[\"weather_info\"]) == 24\n\n\ndef test_get_weather_london(client_fixture):\n resp = client_fixture.get(\n \"weather\", params={\"city_name\": \"London\", \"date\": \"2023-02-21\"}\n )\n assert resp.json()[\"city_name\"] == \"London\"\n assert len(resp.json()[\"weather_info\"]) == 24\n\n\ndef test_get_weather_not_found(client_fixture):\n resp = client_fixture.get(\n \"weather\", params={\"city_name\": \"afkjcnpa\", \"date\": \"2023-02-21\"}\n )\n assert resp.is_error\n assert resp.json()[\"detail\"] == \"could not find weather data for afkjcnpa\"\n\n\ndef test_get_weather_no_date(client_fixture):\n resp = client_fixture.get(\"weather\", params={\"city_name\": \"London\"})\n assert resp.json()[\"city_name\"] == \"London\"\n assert len(resp.json()[\"weather_info\"]) == 24\n assert (\n resp.json()[\"weather_info\"][0][\"datetime\"]\n == datetime.combine(date.today(), time()).isoformat()\n )\n","repo_name":"bglantz1997/weatherAPI","sub_path":"test/api/test_get_weather.py","file_name":"test_get_weather.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26770943247","text":"import time\n\n\"\"\"\n Given an integer array nums, find the contiguous subarray (containing\n at least one number) which has the largest sum and return its sum.\n \n Example:\n Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]\n Output: [6]\n Explanation: [4, -1, 2, 1] has the largest sum = 6.\n\"\"\"\n\n# This version \ndef get_max_sum_v1(nums:list) -> int:\n \n n = len(nums)\n max_sum = nums[0]\n \n for i in range(n):\n for j in range(i + 1, n + 1):\n cur_sum = sum(nums[i:j])\n if cur_sum > max_sum:\n max_sum = cur_sum\n \n return max_sum\n\ndef get_max_sum_v2(nums:list) -> int:\n # Based on NeetCode theoretical explanation.\n \n n = len(nums)\n cur_sum = nums[0] # reference\n max_sum = nums[0]\n max_val = nums[0]\n \n for i in range(1, n):\n if nums[i] > max_val:\n max_val = nums[i]\n \n if cur_sum <= 0:\n cur_sum = nums[i]\n continue\n \n max_sum = cur_sum if cur_sum > max_sum else max_sum\n cur_sum += nums[i]\n \n max_sum = cur_sum if cur_sum > max_sum else max_sum\n max_sum = max_sum if max_sum > max_val else max_val\n \n return max_sum\n\nif __name__ == '__main__':\n nums = [-2, 1, -3, 4, -1, 2, 1, -5, 114]\n \n start_time = time.time()\n print(get_max_sum_v1(nums))\n print(f'----- {(time.time() - start_time) * 1000} ms -----')\n \n start_time = time.time()\n print(get_max_sum_v2(nums))\n print(f'----- {(time.time() - start_time) * 1000} ms -----')","repo_name":"luansouzasilva31/neetcode-challenges","sub_path":"easy-level/maximum_subarray.py","file_name":"maximum_subarray.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29627618340","text":"import cherrypy\n\nfrom ingredients_db.models.instance import Instance\nfrom ingredients_db.models.region import Region\nfrom ingredients_db.models.zones import Zone\nfrom ingredients_http.route import Route\nfrom ingredients_http.router import Router\n\n\nclass MetaDataRouter(Router):\n def __init__(self):\n super().__init__(uri_base='meta-data')\n\n @Route()\n @cherrypy.tools.json_out()\n def get(self):\n with cherrypy.request.db_session() as session:\n instance = session.query(Instance).filter(Instance.id == cherrypy.request.instance_id).first()\n region = session.query(Region).filter(Region.id == instance.region_id).first()\n zone = session.query(Zone).filter(Zone.id == instance.zone_id).first()\n\n keypairs = []\n for keypair in instance.keypairs:\n keypairs.append(keypair.public_key)\n\n # Strip out user-data\n tags = instance.tags if instance.tags is not None else {}\n if 'user-data' in tags:\n del tags['user-data']\n\n metadata = {\n 'ami-id': instance.image_id,\n 'instance-id': instance.id,\n 'region': region.name,\n 'availability-zone': zone.name,\n 'tags': tags,\n 'public-keys': keypairs\n }\n\n return metadata\n","repo_name":"sandwichcloud/deli-menu","sub_path":"deli_menu/http/mounts/root/routes/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24225431042","text":"\"\"\"\nThis method is used to access or read and modify data of the variables.\nThis method modify the data in the variable.\nThis is also called as setter method.\n\"\"\"\n\nfrom pyexpat import model\n\n\nclass car:\n\n def __init__(self):\n self.model= \"X20\" # Instance Varible \n \n \n def setter(self): # Mutator Instance Method \n self.model=\"X45\" #Instance Varible\n \n\n\nMaruti=car()\nprint(\"Before Setter :\",Maruti.model)\n\n# calling setter function\nMaruti.setter()\n\nprint(\"\\nAfter Setter :\",Maruti.model)\n\n\nprint(\"********************************************************\")\n\nclass car:\n\n def __init__(self,model):\n self.model= model # Instance Varible always wrriten inside __init__\n\n \n\n def setter(self,colour): # Mutator Instance Method with parameter\n self.colour=colour #Instance Varible\n return f\"Model :{self.model} and colour : {self.colour}\" #accessing instance varible\n\n\nMaruti=car(\"x20\")\nMaruti.setter(\"Red\")\nprint(\"Model :\",Maruti.model)\nprint(\"Color :\",Maruti.colour)\n\n\n\n","repo_name":"PoojaDasIndia/PythonNotes","sub_path":"Methods/Mutator_Setter.py","file_name":"Mutator_Setter.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30892413123","text":"import os\nimport sys\nimport time\nimport cv2\nimport numpy as np\nfrom queue import Queue\n\nfrom libs.pipeline import Streamming, Inferencing, Displaying, Config\nfrom libs.utilities import Preprocess, Postprocess\n\ndef running(cfg):\n while True:\n if cfg.is_stop():\n break\n\n\ndef main():\n config_file = \"app_config.json\"\n cfg = Config(config_file)\n\n preprocess = Preprocess(cfg.width, cfg.height, cfg.preprocess_mode)\n preprocessing = preprocess.run\n postprocess = Postprocess(cfg.width, cfg.height, cfg.n_classes, cfg.threshold, cfg.postprocess_mode)\n postprocessing = postprocess.run\n\n input_queue = Queue(maxsize=cfg.input_buffer_size)\n output_queue = Queue(maxsize=cfg.output_buffer_size)\n \n streamming = Streamming(input_queue, cfg)\n streamming.start()\n \n displaying = Displaying(output_queue, cfg)\n displaying.start()\n\n print(\"Warmming up ...\")\n time.sleep(5)\n\n inferencing_1 = Inferencing(input_queue, output_queue, preprocessing, postprocessing, cfg, name=\"inferencing thread 1\")\n inferencing_1.start()\n\n inferencing_2 = Inferencing(input_queue, output_queue, preprocessing, postprocessing, cfg, name=\"inferencing thread 2\")\n inferencing_2.start()\n\n # inferencing_3 = Inferencing(input_queue, output_queue, preprocessing, postprocessing, cfg, name=\"inferencing thread 3\")\n # inferencing_3.start()\n\n # inferencing_4 = Inferencing(input_queue, output_queue, preprocessing, postprocessing, cfg, name=\"inferencing thread 4\")\n # inferencing_4.start()\n\n print(\"Running ...\")\n running(cfg)\n\n time.sleep(5)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"syanng/blazeneo","sub_path":"qt_tensorrt/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39590458271","text":"import random\nimport requests\nimport string\nimport os\nfrom bs4 import BeautifulSoup\n\nheaders = {\n 'authority': 'prnt.sc',\n 'cache-control': 'max-age=0',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',\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': 'en-GB,en-US;q=0.9,en;q=0.8'\n}\nmain_url = 'https://prnt.sc/'\n\n\nclass Parse():\n def __init__(self):\n super(Parse, self).__init__()\n self.abc = string.ascii_lowercase + '0123456789'\n self.path = os.path.join(os.path.dirname(__file__), 'output/')\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n\n def id_url(self):\n return ''.join([self.abc[random.randint(0, len(self.abc)-1)] for i in range(6)])\n\n def get_img_path(self):\n url = main_url + self.id_url()\n html = requests.get(url, headers=headers).text\n soup = BeautifulSoup(html)\n img_url = soup.find_all('img')\n return img_url[0]['src']\n\n def create_path(self):\n return self.path + self.id_url()\n\n def get_img(self):\n path = self.create_path()\n res = requests.get(self.get_img_path())\n if res.status_code == 200:\n with open(f\"{path}.png\", 'wb') as f:\n f.write(res.content)\n\n\nparse = Parse()\n\nif __name__ == '__main__':\n\n for i in range(100):\n try:\n parse.get_img()\n except:\n continue\n","repo_name":"AstralMortem/get_random_photo_prnt.sc","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5967166509","text":"from Point import Point\n\nclass Circle:\n def __init__(self, x: float = 0, y: float = 0, r: float = 0, idx: int = 0) -> None:\n self.x = x\n self.y = y\n self.r = r\n self.idx = idx\n\n def isContain(self, point: Point) -> bool:\n diff_x = abs(point.x - self.x)\n diff_y = abs(point.y - self.y)\n\n if diff_x > self.r:\n return False\n if diff_y > self.r:\n return False\n if diff_x + diff_y <= self.r:\n return True\n if diff_x**2 + diff_y**2 <= self.r**2:\n return True\n\n return False\n","repo_name":"babajikomali/Optimized_Boids_Flocking_Simulation","sub_path":"Circle.py","file_name":"Circle.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4163720475","text":"import multiprocessing as mp\nimport os\nimport psutil\nimport platform\nimport queue\nimport subprocess\nimport time\nimport webbrowser\nfrom contextlib import contextmanager\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\nfrom typing import List, Optional, Dict\nfrom urllib.parse import ParseResult as URL\n\nfrom rlbot.utils.structures import game_data_struct\n\nfrom rlbot import gateway_util\nfrom rlbot import version\nfrom rlbot.base_extension import BaseExtension\nfrom rlbot.botmanager.bot_manager_flatbuffer import BotManagerFlatbuffer\nfrom rlbot.botmanager.bot_manager_independent import BotManagerIndependent\nfrom rlbot.botmanager.bot_manager_struct import BotManagerStruct\nfrom rlbot.botmanager.helper_process_manager import HelperProcessManager\nfrom rlbot.gateway_util import LaunchOptions, NetworkingRole\nfrom rlbot.matchconfig.conversions import parse_match_config\nfrom rlbot.matchconfig.match_config import MatchConfig\nfrom rlbot.matchconfig.psyonix_config import set_random_psyonix_bot_preset\nfrom rlbot.matchcomms.server import launch_matchcomms_server\nfrom rlbot.parsing.agent_config_parser import load_bot_appearance\nfrom rlbot.parsing.bot_config_bundle import get_bot_config_bundle, BotConfigBundle\nfrom rlbot.parsing.custom_config import ConfigObject\nfrom rlbot.parsing.rlbot_config_parser import create_bot_config_layout\nfrom rlbot.utils import process_configuration\nfrom rlbot.utils.class_importer import import_class_with_base, import_agent\nfrom rlbot.utils.logging_utils import get_logger, DEFAULT_LOGGER\nfrom rlbot.utils.process_configuration import WrongProcessArgs\nfrom rlbot.utils.structures.start_match_structures import MAX_PLAYERS\nfrom rlbot.utils.structures.game_interface import GameInterface\nfrom rlbot.utils.config_parser import mergeTASystemSettings, cleanUpTASystemSettings\nfrom rlbot.matchcomms.server import MatchcommsServerThread\n\nif platform.system() == 'Windows':\n import msvcrt\n\n# By default, look for rlbot.cfg in the current working directory.\nDEFAULT_RLBOT_CONFIG_LOCATION = os.path.realpath('./rlbot.cfg')\nRLBOT_CONFIGURATION_HEADER = 'RLBot Configuration'\n\n\nclass ROCKET_LEAGUE_PROCESS_INFO:\n GAMEID = 252950\n PROGRAM_NAME = 'RocketLeague.exe'\n PROGRAM = 'RocketLeague.exe'\n REQUIRED_ARGS = {r'-rlbot', r'RLBot_ControllerURL=127.0.0.1:[0-9]+'}\n PORT_PLACEHOLDER = '%PORT%'\n IDEAL_ARGS = ['-rlbot', f'RLBot_ControllerURL=127.0.0.1:{PORT_PLACEHOLDER}', '-nomovie']\n\n @staticmethod\n def get_ideal_args(port):\n return [arg.replace(ROCKET_LEAGUE_PROCESS_INFO.PORT_PLACEHOLDER, str(port))\n for arg in ROCKET_LEAGUE_PROCESS_INFO.IDEAL_ARGS]\n\n\n@contextmanager\ndef setup_manager_context():\n \"\"\"\n Creates a initialized context manager which shuts down at the end of the\n `with` block.\n\n usage:\n >>> with setup_manager_context() as setup_manager:\n ... setup_manager.load_config(...)\n ... # ... Run match\n \"\"\"\n setup_manager = SetupManager()\n setup_manager.connect_to_game()\n try:\n yield setup_manager\n except Exception as e:\n get_logger(DEFAULT_LOGGER).error(e)\n raise e\n finally:\n setup_manager.shut_down(kill_all_pids=True)\n\n\nclass SetupManager:\n \"\"\"\n This class is responsible for pulling together all bits of the framework to\n set up a match between agents.\n\n A normal order of methods would be:\n connect_to_game()\n load_config()\n launch_ball_prediction()\n launch_bot_processes()\n start_match()\n infinite_loop()\n # the below two might be from another thread\n reload_all_agents()\n shut_down()\n \"\"\"\n has_started = False\n num_participants = None\n names = None\n teams = None\n python_files = None\n bot_bundles: List[BotConfigBundle] = None\n start_match_configuration = None\n agent_metadata_queue = None\n extension = None\n bot_processes: Dict[int, mp.Process] = {}\n\n def __init__(self):\n self.logger = get_logger(DEFAULT_LOGGER)\n self.game_interface = GameInterface(self.logger)\n self.quit_event = mp.Event()\n self.helper_process_manager = HelperProcessManager(self.quit_event)\n self.bot_quit_callbacks = []\n self.bot_reload_requests = []\n self.agent_metadata_map = {}\n self.match_config: MatchConfig = None\n self.rlbot_gateway_process = None\n self.matchcomms_server: MatchcommsServerThread = None\n self.early_start_seconds = 0\n self.num_metadata_received = 0\n\n def is_rocket_league_running(self, port) -> bool:\n \"\"\"\n Returns whether Rocket League is running with the right port.\n \"\"\"\n\n try:\n is_rocket_league_running, proc = process_configuration.is_process_running(\n ROCKET_LEAGUE_PROCESS_INFO.PROGRAM,\n ROCKET_LEAGUE_PROCESS_INFO.PROGRAM_NAME,\n ROCKET_LEAGUE_PROCESS_INFO.REQUIRED_ARGS)\n\n if proc is not None:\n # Check for correct port.\n rocket_league_port = self._read_port_from_rocket_league_args(proc.cmdline())\n if rocket_league_port is not None and rocket_league_port != port:\n raise Exception(f\"Rocket League is already running with port {rocket_league_port} but we wanted \"\n f\"{port}! Please close Rocket League and let us start it for you instead!\")\n except WrongProcessArgs:\n raise Exception(f\"Rocket League is not running with {ROCKET_LEAGUE_PROCESS_INFO.REQUIRED_ARGS}!\\n\"\n \"Please close Rocket League and let us start it for you instead!\")\n\n return is_rocket_league_running\n\n def connect_to_game(self):\n \"\"\"\n Connects to the game by initializing self.game_interface.\n \"\"\"\n version.print_current_release_notes()\n port = self.ensure_rlbot_gateway_started()\n\n # Prevent loading game interface twice.\n if self.has_started:\n if not self.is_rocket_league_running(port):\n raise Exception(\"Rocket League is not running even though we started it once.\\n\"\n \"Please restart RLBot.\")\n return\n\n # Currently match_config is None when launching from RLBotGUI.\n if self.match_config is not None and self.match_config.networking_role == 'remote_rlbot_client':\n self.logger.info(\"Will not start Rocket League because this is configured as a client!\")\n # Launch the game if it is not running.\n elif not self.is_rocket_league_running(port):\n mergeTASystemSettings()\n self.launch_rocket_league(port=port)\n\n try:\n self.game_interface.load_interface()\n except Exception as e:\n self.logger.error(\"Terminating rlbot gateway and raising:\")\n self.rlbot_gateway_process.terminate()\n raise e\n self.agent_metadata_queue = mp.Queue()\n self.has_started = True\n\n @staticmethod\n def _read_port_from_rocket_league_args(args):\n for arg in args:\n # The arg will look like RLBot_ControllerURL=\"127.0.0.1:23233\"\n if 'RLBot_ControllerURL' in arg:\n rocket_league_port = int(arg.split(':')[1].replace('\"', ''))\n return int(rocket_league_port)\n return None\n\n def launch_rocket_league(self, port):\n \"\"\"\n Launches Rocket League but does not connect to it.\n \"\"\"\n ideal_args = ROCKET_LEAGUE_PROCESS_INFO.get_ideal_args(port)\n self.logger.info(f'Launching Rocket League with args: {ideal_args}')\n\n # Try launch via Steam.\n steam_exe_path = try_get_steam_executable_path()\n if steam_exe_path: # Note: This Python 3.8 feature would be useful here https://www.python.org/dev/peps/pep-0572/#abstract\n exe_and_args = [\n str(steam_exe_path),\n '-applaunch',\n str(ROCKET_LEAGUE_PROCESS_INFO.GAMEID),\n ] + ideal_args\n _ = subprocess.Popen(exe_and_args) # This is deliberately an orphan process.\n return\n\n # TODO: Figure out launching via Epic games\n\n self.logger.warning('Using fall-back launch method.')\n self.logger.info(\"You should see a confirmation pop-up, if you don't see it then click on Steam! \"\n 'https://gfycat.com/AngryQuickFinnishspitz')\n args_string = '%20'.join(ideal_args)\n\n # Try launch via terminal (Linux)\n if platform.system() == 'Linux':\n linux_args = [\n 'steam',\n f'steam://rungameid/{ROCKET_LEAGUE_PROCESS_INFO.GAMEID}//{args_string}'\n ]\n\n try:\n _ = subprocess.Popen(linux_args)\n\n except OSError:\n self.logger.warning(\n 'Could not find Steam executable, using browser to open instead.')\n else:\n return\n\n try:\n webbrowser.open(f'steam://rungameid/{ROCKET_LEAGUE_PROCESS_INFO.GAMEID}//{args_string}')\n except webbrowser.Error:\n self.logger.warning(\n 'Unable to launch Rocket League. Please launch Rocket League manually using the -rlbot option to continue.')\n\n def load_match_config(self, match_config: MatchConfig, bot_config_overrides={}):\n \"\"\"\n Loads the match config into internal data structures, which prepares us to later\n launch bot processes and start the match.\n\n This is an alternative to the load_config method; they accomplish the same thing.\n \"\"\"\n self.num_participants = match_config.num_players\n self.names = [bot.name for bot in match_config.player_configs]\n self.teams = [bot.team for bot in match_config.player_configs]\n\n for player in match_config.player_configs:\n if player.bot and not player.rlbot_controlled:\n set_random_psyonix_bot_preset(player)\n\n bundles = [bot_config_overrides[index] if index in bot_config_overrides else\n get_bot_config_bundle(bot.config_path) if bot.config_path else None\n for index, bot in enumerate(match_config.player_configs)]\n\n self.python_files = [bundle.python_file if bundle else None\n for bundle in bundles]\n\n self.bot_bundles = []\n\n for index, bot in enumerate(match_config.player_configs):\n self.bot_bundles.append(bundles[index])\n if bot.loadout_config is None and bundles[index]:\n looks_config = bundles[index].get_looks_config()\n bot.loadout_config = load_bot_appearance(looks_config, bot.team)\n\n if match_config.extension_config is not None and match_config.extension_config.python_file_path is not None:\n self.load_extension(match_config.extension_config.python_file_path)\n\n self.match_config = match_config\n self.start_match_configuration = match_config.create_match_settings()\n self.game_interface.start_match_configuration = self.start_match_configuration\n\n def load_config(self, framework_config: ConfigObject = None, config_location=DEFAULT_RLBOT_CONFIG_LOCATION,\n bot_configs=None,\n looks_configs=None):\n \"\"\"\n Loads the configuration into internal data structures, which prepares us to later\n launch bot processes and start the match.\n\n :param framework_config: A config object that indicates what bots to run. May come from parsing a rlbot.cfg.\n :param config_location: The location of the rlbot.cfg file, which will be used to resolve relative paths.\n :param bot_configs: Overrides for bot configurations.\n :param looks_configs: Overrides for looks configurations.\n \"\"\"\n self.logger.debug('reading the configs')\n\n # Set up RLBot.cfg\n if framework_config is None:\n framework_config = create_bot_config_layout()\n framework_config.parse_file(config_location, max_index=MAX_PLAYERS)\n if bot_configs is None:\n bot_configs = {}\n if looks_configs is None:\n looks_configs = {}\n\n match_config = parse_match_config(framework_config, config_location, bot_configs, looks_configs)\n self.load_match_config(match_config, bot_configs)\n\n def ensure_rlbot_gateway_started(self) -> int:\n \"\"\"\n Ensures that RLBot.exe is running. Returns the port that it will be listening on for connections from\n Rocket League. Rocket League should be passed a command line argument so that it starts with this same port.\n :return:\n \"\"\"\n\n # TODO: Uncomment this when done with local testing of Remote RLBot.\n self.rlbot_gateway_process, port = gateway_util.find_existing_process()\n if self.rlbot_gateway_process is not None:\n self.logger.info(f\"Already have RLBot.exe running! Port is {port}\")\n return port\n\n launch_options = LaunchOptions()\n if self.match_config is not None: # Currently this is None when launching from RLBotGUI.\n networking_role = NetworkingRole[self.match_config.networking_role]\n launch_options = LaunchOptions(\n networking_role=networking_role,\n remote_address=self.match_config.network_address)\n\n self.rlbot_gateway_process, port = gateway_util.launch(launch_options)\n self.logger.info(f\"Python started RLBot.exe with process id {self.rlbot_gateway_process.pid} \"\n f\"and port {port}\")\n return port\n\n def launch_ball_prediction(self):\n # This does nothing now. It's kept here temporarily so that RLBotGUI doesn't break.\n pass\n\n def has_received_metadata_from_all_bots(self):\n expected_metadata_calls = sum(1 for player in self.match_config.player_configs if player.rlbot_controlled)\n return self.num_metadata_received >= expected_metadata_calls\n\n def launch_early_start_bot_processes(self):\n \"\"\"\n Some bots can start up before the game is ready and not be bothered by missing\n or strange looking values in the game tick packet, etc. Such bots can opt in to the\n early start category and enjoy extra time to load up before the match starts.\n \"\"\"\n\n if self.match_config.networking_role == NetworkingRole.remote_rlbot_client:\n return # The bot indices are liable to change, so don't start anything yet.\n\n self.logger.debug(\"Launching early-start bot processes\")\n num_started = self.launch_bot_process_helper(early_starters_only=True)\n self.try_recieve_agent_metadata()\n if num_started > 0 and self.early_start_seconds > 0:\n self.logger.info(f\"Waiting for {self.early_start_seconds} seconds to let early-start bots load.\")\n end_time = datetime.now() + timedelta(seconds=self.early_start_seconds)\n while datetime.now() < end_time:\n self.try_recieve_agent_metadata()\n time.sleep(0.1)\n\n def launch_bot_processes(self):\n self.logger.debug(\"Launching bot processes\")\n self.launch_bot_process_helper(early_starters_only=False)\n\n def launch_bot_process_helper(self, early_starters_only=False):\n # Start matchcomms here as it's only required for the bots.\n self.kill_matchcomms_server()\n self.matchcomms_server = launch_matchcomms_server()\n\n num_started = 0\n\n # Launch processes\n # TODO: this might be the right moment to fix the player indices based on a game tick packet.\n packet = game_data_struct.GameTickPacket()\n self.game_interface.update_live_data_packet(packet)\n\n # TODO: root through the packet and find discrepancies in the player index mapping.\n for i in range(self.num_participants):\n if not self.start_match_configuration.player_configuration[i].rlbot_controlled:\n continue\n if early_starters_only and not self.bot_bundles[i].supports_early_start:\n continue\n\n bot_manager_spawn_id = None\n\n if early_starters_only:\n # Don't use a spawn id stuff for the early start system. The bots will be starting up before\n # the car spawns, and we don't want the bot manager to panic.\n participant_index = i\n else:\n participant_index = None\n spawn_id = self.game_interface.start_match_configuration.player_configuration[i].spawn_id\n self.logger.info(f'Player in slot {i} was sent with spawn id {spawn_id}, will search in the packet.')\n for n in range(0, packet.num_cars):\n packet_spawn_id = packet.game_cars[n].spawn_id\n if spawn_id == packet_spawn_id:\n self.logger.info(f'Looks good, considering participant index to be {n}')\n participant_index = n\n bot_manager_spawn_id = spawn_id\n if participant_index is None:\n raise Exception(\"Unable to determine the bot index!\")\n\n if participant_index not in self.bot_processes:\n reload_request = mp.Event()\n quit_callback = mp.Event()\n self.bot_reload_requests.append(reload_request)\n self.bot_quit_callbacks.append(quit_callback)\n process = mp.Process(target=SetupManager.run_agent,\n args=(self.quit_event, quit_callback, reload_request, self.bot_bundles[i],\n str(self.start_match_configuration.player_configuration[i].name),\n self.teams[i], participant_index, self.python_files[i], self.agent_metadata_queue,\n self.match_config, self.matchcomms_server.root_url, bot_manager_spawn_id))\n process.start()\n self.bot_processes[i] = process\n num_started += 1\n\n self.logger.debug(f\"Successfully started {num_started} bot processes\")\n return num_started\n\n def launch_quick_chat_manager(self):\n # Quick chat manager is gone since we're using RLBot.exe now.\n # Keeping this function around for backwards compatibility.\n pass\n\n def start_match(self):\n\n if self.match_config.networking_role == NetworkingRole.remote_rlbot_client:\n match_settings = self.game_interface.get_match_settings()\n # TODO: merge the match settings into self.match_config\n # And then make sure we still only start the appropriate bot processes\n # that we originally asked for.\n\n self.logger.info(\"Python attempting to start match.\")\n self.game_interface.start_match()\n time.sleep(2) # Wait a moment. If we look too soon, we might see a valid packet from previous game.\n self.game_interface.wait_until_valid_packet()\n self.logger.info(\"Match has started\")\n\n cleanUpTASystemSettings()\n\n def infinite_loop(self):\n instructions = \"Press 'r' to reload all agents, or 'q' to exit\"\n self.logger.info(instructions)\n while not self.quit_event.is_set():\n # Handle commands\n # TODO windows only library\n if platform.system() == 'Windows':\n if msvcrt.kbhit():\n command = msvcrt.getwch()\n if command.lower() == 'r': # r: reload\n self.reload_all_agents()\n elif command.lower() == 'q' or command == '\\u001b': # q or ESC: quit\n self.shut_down()\n break\n # Print instructions again if a alphabet character was pressed but no command was found\n elif command.isalpha():\n self.logger.info(instructions)\n\n self.try_recieve_agent_metadata()\n\n def try_recieve_agent_metadata(self):\n \"\"\"\n Checks whether any of the started bots have posted their AgentMetadata\n yet. If so, we put them on the agent_metadata_map such that we can\n kill their process later when we shut_down(kill_agent_process_ids=True)\n\n Returns how from how many bots we received metadata from.\n \"\"\"\n num_recieved = 0\n while True: # will exit on queue.Empty\n try:\n single_agent_metadata = self.agent_metadata_queue.get(timeout=0.1)\n num_recieved += 1\n self.helper_process_manager.start_or_update_helper_process(single_agent_metadata)\n self.agent_metadata_map[single_agent_metadata.index] = single_agent_metadata\n process_configuration.configure_processes(self.agent_metadata_map, self.logger)\n except queue.Empty:\n self.num_metadata_received += num_recieved\n return num_recieved\n\n def reload_all_agents(self, quiet=False):\n if not quiet:\n self.logger.info(\"Reloading all agents...\")\n for rr in self.bot_reload_requests:\n rr.set()\n\n def shut_down(self, time_limit=5, kill_all_pids=False, quiet=False):\n if not quiet:\n self.logger.info(\"Shutting Down\")\n\n self.quit_event.set()\n end_time = datetime.now() + timedelta(seconds=time_limit)\n\n # Don't kill RLBot.exe. It needs to keep running because if we're in a GUI\n # that will persist after this shut down, the interface dll in charge of starting\n # matches is already locked in to its shared memory files, and if we start a new\n # RLBot.exe, those files will go stale. https://github.com/skyborgff/RLBot/issues/9\n\n # Wait for all processes to terminate before terminating main process\n terminated = False\n while not terminated:\n terminated = True\n for callback in self.bot_quit_callbacks:\n if not callback.is_set():\n terminated = False\n time.sleep(0.1)\n if datetime.now() > end_time:\n self.logger.info(\"Taking too long to quit, trying harder...\")\n break\n\n self.kill_bot_processes()\n\n if kill_all_pids:\n self.kill_agent_process_ids()\n\n self.kill_matchcomms_server()\n\n # The quit event can only be set once. Let's reset to our initial state\n self.quit_event = mp.Event()\n self.helper_process_manager = HelperProcessManager(self.quit_event)\n\n if not quiet:\n self.logger.info(\"Shut down complete!\")\n\n def load_extension(self, extension_filename):\n try:\n extension_class = import_class_with_base(extension_filename, BaseExtension).get_loaded_class()\n self.extension = extension_class(self)\n self.game_interface.set_extension(self.extension)\n except FileNotFoundError as e:\n print(f'Failed to load extension: {e}')\n\n @staticmethod\n def run_agent(terminate_event, callback_event, reload_request, bundle: BotConfigBundle, name, team, index,\n python_file, agent_telemetry_queue, match_config: MatchConfig, matchcomms_root: URL, spawn_id: str):\n\n agent_class_wrapper = import_agent(python_file)\n config_file = agent_class_wrapper.get_loaded_class().base_create_agent_configurations()\n config_file.parse_file(bundle.config_obj, config_directory=bundle.config_directory)\n\n if hasattr(agent_class_wrapper.get_loaded_class(), \"run_independently\"):\n bm = BotManagerIndependent(terminate_event, callback_event, reload_request, config_file, name, team, index,\n agent_class_wrapper, agent_telemetry_queue, match_config, matchcomms_root,\n spawn_id)\n elif hasattr(agent_class_wrapper.get_loaded_class(), \"get_output_flatbuffer\"):\n bm = BotManagerFlatbuffer(terminate_event, callback_event, reload_request, config_file, name, team, index,\n agent_class_wrapper, agent_telemetry_queue, match_config, matchcomms_root,\n spawn_id)\n else:\n bm = BotManagerStruct(terminate_event, callback_event, reload_request, config_file, name, team, index,\n agent_class_wrapper, agent_telemetry_queue, match_config, matchcomms_root, spawn_id)\n bm.run()\n\n def kill_bot_processes(self):\n for process in self.bot_processes.values():\n process.terminate()\n for process in self.bot_processes.values():\n process.join(timeout=1)\n self.bot_processes.clear()\n self.num_metadata_received = 0\n\n def kill_agent_process_ids(self):\n pids = process_configuration.extract_all_pids(self.agent_metadata_map)\n for pid in pids:\n try:\n parent = psutil.Process(pid)\n for child in parent.children(recursive=True): # or parent.children() for recursive=False\n self.logger.info(f\"Killing {child.pid} (child of {pid})\")\n try:\n child.kill()\n except psutil._exceptions.NoSuchProcess:\n self.logger.info(\"Already dead.\")\n self.logger.info(f\"Killing {pid}\")\n try:\n parent.kill()\n except psutil._exceptions.NoSuchProcess:\n self.logger.info(\"Already dead.\")\n except psutil.NoSuchProcess:\n self.logger.info(\"Can't fetch parent process, already dead.\")\n except psutil.AccessDenied as ex:\n self.logger.error(f\"Access denied when trying to kill a bot pid! {ex}\")\n except Exception as ex:\n self.logger.error(f\"Unexpected exception when trying to kill a bot pid! {ex}\")\n\n def kill_matchcomms_server(self):\n if self.matchcomms_server:\n self.matchcomms_server.close()\n self.matchcomms_server = None\n\n\ndef try_get_steam_executable_path() -> Optional[Path]:\n \"\"\"\n Tries to find the path of the Steam executable.\n Has platform specific code.\n \"\"\"\n\n try:\n from winreg import OpenKey, HKEY_CURRENT_USER, ConnectRegistry, QueryValueEx, REG_SZ\n except ImportError as e:\n return None # TODO: Linux support.\n\n try:\n key = OpenKey(ConnectRegistry(None, HKEY_CURRENT_USER), r'Software\\Valve\\Steam')\n val, val_type = QueryValueEx(key, 'SteamExe')\n except FileNotFoundError:\n return None\n if val_type != REG_SZ:\n return None\n return Path(val)\n","repo_name":"danielbairamian/RL-RL","sub_path":"rlbot/setup_manager.py","file_name":"setup_manager.py","file_ext":"py","file_size_in_byte":26795,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"17691553026","text":"import os\n\nprint(\"\"\"\n▞▀▖▜ ▗ ▐\n▙▄▌▐ ▄ ▝▀▖▞▀▘ ▞▀▖▙▀▖▞▀▖▝▀▖▜▀ ▞▀▖▙▀▖\n▌ ▌▐ ▐ ▞▀▌▝▀▖ ▌ ▖▌ ▛▀ ▞▀▌▐ ▖▌ ▌▌\n▘ ▘ ▘▀▘▝▀▘▀▀ ▝▀ ▘ ▝▀▘▝▀▘ ▀ ▝▀ ▘\n\"\"\")\nprint(\"github.com/dmytroitt\")\n\nalias_nm = str(input(\"Alias name: \"))\nalias_cntnt = str(input(\"Alias content: \"))\nalias = \"alias \"+alias_nm+\"='\"+alias_cntnt+\"'\"\n\nos.system(\"touch /etc/profile.d/00-aliases.sh\")\nwith open(\"/etc/profile.d/00-aliases.sh\", \"a+\") as file_object:\n file_object.seek(0)\n data = file_object.read(100)\n if len(data) > 0 :\n file_object.write(\"\\n\")\n file_object.write(alias)\n print(\"Restart to save the changes! \")\n exit()\n","repo_name":"Dmytroitt/LinuxAliasMaker","sub_path":"aliasmaker.py","file_name":"aliasmaker.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74304011684","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 29 13:45:32 2019\n\n@author: pradeep\n\"\"\"\n\ndef train(network, dataSet, cp_callback, load):\n if load:\n network.load_weights('checkpoints/cp-0010.ckpt')\n\n else:\n network.fit_generator(dataSet[0],\n steps_per_epoch = 800/2, # steps_per_epoch * batch_size = dataset_count\n epochs = 10,\n validation_steps = 104/2,\n callbacks = [cp_callback],\n validation_data = dataSet[1],\n verbose=1)","repo_name":"Pradeepcbk/Analysis-of-quality-of-grass-images-using-Convolutional-Neural-Networks","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13918088186","text":"import numpy as np \r\n\r\n#------part 2------#\r\n\r\ndef check_num(n1, n2, length):\r\n\tprint(n1, n2, length)\r\n\tvalid, count= 0, 0\r\n\tfor num in range(n1, n2 + 1):\r\n\t\tstr_num = str(num)\r\n\t\t# check increase\r\n\t\tfor i in range(length - 1):\r\n\t\t\tif str_num[i] <= str_num[i + 1]:\r\n\t\t\t\tvalid += 1\r\n\t\t\telse:\r\n\t\t\t\tvalid = 0\r\n\t\t\t\tbreak\r\n\r\n\t\t# check double\r\n\t\tdict_count = {}\r\n\t\td_count = 1\r\n\t\t# flag = 0\r\n\t\tif valid == length - 1:\r\n\t\t\tfor i in range(length - 1):\r\n\t\t\t\tif str_num[i] == str_num[i + 1]:\r\n\t\t\t\t\td_count += 1\r\n\t\t\t\t\tif i == length - 1 - 1:\r\n\t\t\t\t\t\tdict_count[str_num[i]] = d_count\r\n\r\n\t\t\t\telse:\r\n\t\t\t\t\tif d_count >= 2:\r\n\t\t\t\t\t\t# has found a group of same digits\r\n\t\t\t\t\t\tdict_count[str_num[i]] = d_count\r\n\t\t\t\t\t\td_count = 1\r\n\t\t\tvalid = 0\r\n\t\tif 2 in dict_count.values():\r\n\t\t\t\tcount += 1\r\n\t\t\t\tprint(num)\r\n\t\t\t\t# print(dict_count)\t\r\n\t\t# if len(dict_count.keys()) != 0:\r\n\t\t# \tfor value in dict_count.values():\r\n\t\t# \t\tif value % 2 != 0:\r\n\t\t# \t\t\tflag = 1\r\n\t\t# \t\t\tbreak\r\n\t\t# \tif flag == 0:\r\n\t\t# \t\tcount += 1\r\n\t\t# \t\tprint(num)\r\n\t\t# \t\t# print(dict_count)\t\r\n\r\n\treturn count\r\n\r\nresult = check_num(193651, 649729, 6)\r\nprint(result)\r\n","repo_name":"csyhping/Advent-of-Code-2019","sub_path":"Day_4_Secure_Container/code_part2.py","file_name":"code_part2.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13859064301","text":"##\n# Created by: Curtis Szmania\n# Date: 6/5/2017\n# Initial Creation.\n###\nfrom lib import Lib\nfrom logging import getLogger\nfrom os import path\nfrom re import IGNORECASE, match\nfrom tools.compressImages import CompressImage, DeleteBackupImage\n# from tools import CompressImage, DeleteBackupImage\n\n__author__ = 'szmania'\n\n\nclass CompressImages_Lib(object):\n def __init__(self, log_level='DEBUG'):\n \"\"\"\n Library for compressImages.py interaction.\n\n Args:\n log_level (str): Logging level setting ie: \"DEBUG\" or \"WARN\"\n \"\"\"\n\n self.__log_level = log_level\n\n self.__compress_images_obj = CompressImage()\n self.__deleteBackupImageObj = DeleteBackupImage()\n self.__lib = Lib(log_level=self.__log_level)\n\n def compress_image_file(self, file_path, jpeg_compression_quality_percentage, delete_backup=False,\n delete_corrupt_images=False):\n \"\"\"\n Compress images file.\n\n Args:\n file_path (str): File path of image to compress.\n jpeg_compression_quality_percentage (int): Quality percentage compression for jpeg files.\n delete_backup (bool): Delete backup image file.\n delete_corrupt_images (bool): Delete backup image file.\n\n Returns:\n Boolean: whether compression operation was successful or not.\n \"\"\"\n\n logger = getLogger('CompressImages_Lib.compress_image_file')\n logger.setLevel(self.__log_level)\n\n logger.debug(' Compressing image file: \"%s\"' % file_path)\n results = []\n file_ext = file_path.split('.')[-1]\n compressed_any_image = self.__compress_images_obj.processfile(filename=file_path)\n results.append(compressed_any_image)\n\n if match('jpe{0,1}g', file_ext, IGNORECASE):\n jpeg_compressed = self.compress_jpeg_image_file(file_path=file_path,\n quality_percentage=jpeg_compression_quality_percentage)\n\n if delete_corrupt_images and not jpeg_compressed:\n logger.debug(' Deleting CORRUPT JPEG or JPG image file: \"{}\"'.format(file_path))\n self.__lib.delete_local_file(file_path=file_path)\n\n results.append(jpeg_compressed)\n\n if delete_backup:\n compress_path_backup = file_path + '.compressimages-backup'\n if path.exists(compress_path_backup):\n logger.debug(' Removing backup image file \"{}\"!'.format(compress_path_backup))\n self.__lib.delete_local_file(file_path=compress_path_backup)\n\n if True in results:\n logger.debug(' Success, image file \"%s\" compressed successfully.' % file_path)\n return True\n\n logger.debug(' Error, image file \"%s\" NOT compressed successfully!' % file_path)\n return False\n\n def compress_jpeg_image_file(self, file_path, quality_percentage):\n \"\"\"\n Compress images file.\n\n Args:\n file_path (str): File path of image to compress.\n quality_percentage (int): Percentage to set output jpeg file.\n\n Returns:\n Boolean: whether compression operation was successful or not.\n \"\"\"\n\n logger = getLogger('CompressImages_Lib.compress_jpeg_image_file')\n logger.setLevel(self.__log_level)\n\n logger.debug(' Compressing JPEG or JPG image file \"%s\".' % file_path)\n compressed = False\n skipped = False\n result = None\n try:\n result = self.__lib.exec_cmd_and_return_output(command='jpegoptim --max={quality_percentage} \"{file_path}\"'.format(\n quality_percentage=quality_percentage, file_path=file_path))\n except Exception as e:\n logger.error(' Exception: {}'.format(e))\n if 'optimized' in result[0]:\n logger.debug(' Success, JPEG or JPG image file \"%s\" compressed successfully.' % file_path)\n return True\n elif 'skipped' in result[0]:\n logger.debug(' JPEG or JPG file already optimized! File was skipped: \"{}\"'.format(file_path))\n return True\n else:\n logger.debug(' Error, JPEG or JPG image file \"%s\" NOT compressed successfully!' % file_path)\n return False\n\n\n def delete_backups_in_dir(self, dirPath):\n \"\"\"\n Delete backup files in directory\n\n Args:\n dirPath (str): Directory path of image backups to delete\n\n Returns:\n Boolean: whether compression operation was successful or not.\n \"\"\"\n\n logger = getLogger('CompressImages_Lib.delete_backups_in_dir')\n logger.setLevel(self.__log_level)\n\n logger.debug(' Deleting compression file backups in dirPath \"%s\".' % dirPath)\n\n result = self.__deleteBackupImageObj.processdir(path=dirPath)\n\n if result:\n logger.debug(' Success, could remove backup image compression files in direcotry \"%s\"' % dirPath)\n return True\n else:\n logger.error(' Error, could NOT remove backup image compression files in direcotry \"%s\"' % dirPath)\n return False\n","repo_name":"szmania/mega_manager","sub_path":"megamanager/libs/compress_images_lib.py","file_name":"compress_images_lib.py","file_ext":"py","file_size_in_byte":5136,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"52"} +{"seq_id":"35630132668","text":"def all_the_kwags(**kwags):\n '''Returns the number of keyword arguments passed.\n\n Parameters\n ----------\n **kwags : keyword arguments\n any number of keyword arguments\n \n Returns\n -------\n result : int\n number of keyword arguments passed.\n \n '''\n\n result = len(kwags) \n return result\n\n\ndef almost_fibonacci(N):\n '''Generate the Fibonacci series starting at 0 and 1.\n \n Parameters\n ----------\n N : int\n specifiy the first N numbers of the fibonacci-like sequence\n \n Yields\n -------\n i : int\n the numbers of the fibonacci-like sequence\n \n '''\n\n # We start by seeding 0, 1 and i as the first three numbers\n i_prev_prev, i_prev, i = 0, 1, 1\n yield i_prev_prev # we yield 0 first\n yield i_prev # then yield 1\n # now in the following loop, we yield \"i\" and then calculate i_next by\n # summing the two previous\n for _ in range(N-2):\n yield i\n # we use tuple unpacking to update the variables in one line. This way\n # we do not need to define an i_next variable.\n i, i_prev, i_prev_prev = i + i_prev + i_prev_prev, i, i_prev\n\n\ndef first_word_of_each_line(filepath):\n \"\"\"Generate the first word from each line of the file\n \n Parameters\n ----------\n filepath : string\n the file path of the target file\n \n Yields\n -------\n first_word : string\n the first word of any line in the file\n\n \"\"\"\n \n # First, open the file\n with open(filepath, 'r') as my_file:\n # Loop through the lines\n for line in my_file:\n line = line.strip() # strip whitespace from the line\n words = line.split() # split the line into words\n\n if len(words) > 0: # non-empty line\n first_word = words[0]\n yield first_word\n else: # empty line\n continue \n","repo_name":"ShijiZ/Intermediate_Python_HW","sub_path":"week_3_homework.py","file_name":"week_3_homework.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12355991826","text":"\"\"\"\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(r'datasets/data/mnist', one_hot=True)\n\nprint(type(mnist))\nprint(mnist.train.num_examples)\nprint(type(mnist.train.images))\nprint(mnist.train.images.shape)\nprint(type(mnist.train.labels))\nprint(mnist.train.labels.shape)\n\nprint(mnist.test.num_examples)\nprint(type(mnist.test.images))\nprint(mnist.test.images.shape)\nprint(type(mnist.test.labels))\nprint(mnist.test.labels.shape)\n\nprint(mnist.validation.num_examples)\nprint(type(mnist.validation.images))\nprint(mnist.validation.images.shape)\nprint(type(mnist.validation.labels))\nprint(mnist.validation.labels.shape)\n\n\n\n\n\"\"\"\nimport os\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nmnist = input_data.read_data_sets(r'C:\\Users\\tianx\\PycharmProjects\\TensorFlow\\datasets\\data',one_hot=True)\n# mnist.train.images.shape = (55000, 784)\n\n\n# 做卷积操作\n# 定义 X 为数量 None 未知, 宽度为 784 的训练数据\nX = tf.placeholder(dtype=tf.float64, shape=(None, 784))\n# 卷积核的具体值, 需要由神经网络来计算, 所以我们将其定义为变量, 规定卷积核 5*5, 输出 32.\n# 定义 filter 为长宽 5*5 的矩阵, 输入 1 个通道, 输出 32 个通道.\nfilter = tf.Variable(initial_value=tf.random.normal(shape=(5,5,1,32), dtype=tf.float64), dtype=tf.float64)\n\n# 定义卷积核处理训练数据 X 的��式, ([批次, 高度 28, 宽度 28, 通道 1 个] 通道与卷积核的输入通道数一致).\n# 输出形状为: (None, 28,28,32)\nconv1 = tf.nn.conv2d(input=tf.reshape(X, shape=(-1,28,28,1)), filter=filter, strides=[1,1,1,1], padding='SAME')\n\n# 给卷积处理后的结果加上偏差.\n# 输出形状为: (None, 28,28,32)\nconv1 = conv1 + tf.Variable(initial_value=np.zeros(shape=32, dtype=np.float64), dtype=tf.float64)\n\n# 加上激活函数, tf.nn.relu() 大于 0 的数不变, 小于 0 的数置 0.\n# 输出形状为: (None, 28,28,32)\nconv1 = tf.nn.relu(conv1)\n\n# 取最大值池化\n# 输出形状为: (None, 14,14,32)\nconv1_pool = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides=[1,2,2,1], padding=\"VALID\")\n\n# 重复卷积 - 偏差 - 激活 - 池化.\nfilter_2 = tf.Variable(initial_value=tf.random.normal(shape=(5,5,32,64), dtype=tf.float64), dtype=tf.float64)\n\nconv2 = tf.nn.conv2d(input=conv1_pool, filter=filter_2, strides=[1,1,1,1], padding='SAME')\n\nconv2 = conv2 + tf.Variable(initial_value=np.zeros(shape=64, dtype=np.float64), dtype=tf.float64)\n\nconv2 = tf.nn.relu(conv2)\n\n# 输出形状为: (None, 14,14,64)\nconv2_pool = tf.nn.max_pool(conv2, ksize=[1,2,2,1], strides=[1,2,2,1], padding=\"VALID\")\n\n# 全连接\n# 把卷积之后的结果传给所有的神经元.\n# 规定需要的神经元数量 1024.\nconn = tf.reshape(conv2_pool, shape=(-1, 7*7*64))\n\nw = tf.Variable(initial_value=tf.random_normal(shape=(7*7*64, 1024), dtype=tf.float64), dtype=tf.float64)\nb = tf.Variable(initial_value=np.zeros(shape=1024, dtype=np.float64), dtype=tf.float64)\n\n# 输出形状为: (None, 1024)\nfully_connect = tf.matmul(conn, w) + b\n\n# 输出形状为: (None, 1024)\nresult = tf.nn.relu(fully_connect)\n\n# dropout\n# 把 keep_prob 定义成占位符\nkeep_prob = tf.placeholder(dtype=tf.float64)\nresult_dropout = tf.nn.dropout(result, keep_prob=keep_prob)\n\n# y = wx + b\nlinear_w = tf.Variable(initial_value=tf.random_normal(shape=(1024,10), dtype=tf.float64), dtype=tf.float64)\nlinear_b = tf.Variable(initial_value=tf.random_normal(shape=(1,10), dtype=tf.float64), dtype=tf.float64)\n\n# 输出形状为: (None, 1024) · (1024, 10) + (10) = (None, 10)\ny_ = tf.matmul(result, linear_w) + linear_b\n\n# 传到 softmax 中, 得到概率.\n# 输出形状为: (None, 10)\ny_prob = tf.nn.softmax(y_)\n\n# 损失函数(求交叉熵的最小值) 1/n * ∑P * log(1/p)\n# P 是预测出的概率, p 是真实的概率.\nY = tf.placeholder(shape=(None,10), dtype=tf.float64)\n\n# 形状: (None, 10) × (None, 10)\n# 输出结果为: None\ncost = tf.reduce_mean(tf.reduce_sum(tf.multiply(Y, tf.log(1/(y_prob+0.0000001))), axis=1))\n\n\n# AdamOptimizer 方法, 找损失函数最小时的系数.\noptimizer = tf.train.AdamOptimizer(0.0001).minimize(cost)\n\ninit = tf.global_variables_initializer()\n\n# 训练\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(2000):\n # 每次从数据中取一批 100 个数据\n X_train, y_train = mnist.train.next_batch(100)\n _, cost_ = sess.run([optimizer,cost], feed_dict={X:X_train,Y:y_train,keep_prob:0.5})\n # 每训练 10 次, 1000 个数据.\n\n if i % 100 == 0:\n print(f\"第{i}次训练, 损失: {cost_}\")\n\n # 计算准确率\n # 取出测试数据\n X_test, y_test = mnist.test.next_batch(1000)\n # 预测\n pred = sess.run(y_prob, {X:X_test, keep_prob:1})\n acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(pred, axis=1), tf.argmax(y_test, axis=1)), dtype=tf.float64))\n accuracy = sess.run(acc)\n print('当前准确率: %.4f' % (accuracy))\n\n","repo_name":"tianxing1994/TensorFlow","sub_path":"神经网络练习/CNN 卷积神经网络/CNN 神经网络实现手写数字识别.py","file_name":"CNN 神经网络实现手写数字识别.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75335790243","text":"\"\"\" update_dois.py\n Synchronize DOI information from FLYF2 to FlyBoy and the config system.\n\"\"\"\n\nimport argparse\nimport json\nimport sys\nfrom time import sleep\nimport colorlog\nimport requests\nfrom unidecode import unidecode\nimport MySQLdb\nfrom tqdm import tqdm\n\n# Database\nREAD = {'dois': \"SELECT doi FROM doi_data\",}\nWRITE = {'doi': \"INSERT INTO doi_data (doi,title,first_author,\"\n + \"publication_date) VALUES (%s,%s,%s,%s) ON \"\n + \"DUPLICATE KEY UPDATE title=%s,first_author=%s,\"\n + \"publication_date=%s\",\n 'delete_doi': \"DELETE FROM doi_data WHERE doi=%s\",\n }\nCONN = {}\nCURSOR = {}\n# Configuration\nCONFIG = {'config': {'url': 'http://config.int.janelia.org/'}}\nMAX_CROSSREF_TRIES = 3\n# General\nCOUNT = {'delete': 0, 'found': 0, 'foundfb': 0, 'flyboy': 0, 'insert': 0, 'update': 0}\n\n\ndef sql_error(err):\n \"\"\" Log a critical SQL error and exit \"\"\"\n try:\n LOGGER.critical('MySQL error [%d]: %s', err.args[0], err.args[1])\n except IndexError:\n LOGGER.critical('MySQL error: %s', err)\n sys.exit(-1)\n\n\ndef db_connect(rdb):\n \"\"\" Connect to specified database\n Keyword arguments:\n db: database key\n \"\"\"\n LOGGER.info(\"Connecting to %s on %s\", rdb['name'], rdb['host'])\n try:\n conn = MySQLdb.connect(host=rdb['host'], user=rdb['user'],\n passwd=rdb['password'], db=rdb['name'])\n except MySQLdb.Error as err:\n sql_error(err)\n try:\n cursor = conn.cursor()\n return(conn, cursor)\n except MySQLdb.Error as err:\n sql_error(err)\n\n\ndef call_responder(server, endpoint):\n \"\"\" Call a responder\n Keyword arguments:\n server: server\n endpoint: REST endpoint\n \"\"\"\n url = CONFIG[server]['url'] + endpoint\n try:\n req = requests.get(url, timeout=10)\n except requests.exceptions.RequestException as err:\n LOGGER.critical(err)\n sys.exit(-1)\n if req.status_code != 200:\n LOGGER.error('Status: %s (%s)', str(req.status_code), url)\n sys.exit(-1)\n return req.json()\n\n\ndef initialize_program():\n \"\"\" Connect to FlyBoy database\n \"\"\"\n # pylint: disable=W0603\n global CONFIG\n dbc = call_responder('config', 'config/db_config')\n data = dbc['config']\n (CONN['flyboy'], CURSOR['flyboy']) = db_connect(data['flyboy'][ARG.MANIFOLD])\n dbc = call_responder('config', 'config/rest_services')\n CONFIG = dbc['config']\n\n\ndef call_doi(doi):\n \"\"\" Get DOI information\n Keyword arguments:\n doi: DOI\n \"\"\"\n url = 'https://api.crossref.org/works/' + doi\n headers = {'mailto': 'svirskasr@hhmi.org'}\n try:\n req = requests.get(url, headers=headers, timeout=10)\n except requests.exceptions.RequestException as err:\n LOGGER.critical(err)\n sys.exit(-1)\n if req.status_code != 200:\n LOGGER.error('Status: %s (%s)', str(req.status_code), url)\n sys.exit(-1)\n return req.json()\n\n\ndef get_date(mesg):\n \"\"\" Determine the publication date\n Keyword arguments:\n mesg: Crossref record\n \"\"\"\n if 'published-print' in mesg:\n date = mesg['published-print']['date-parts'][0][0]\n elif 'published-online' in mesg:\n date = mesg['published-online']['date-parts'][0][0]\n elif 'posted' in mesg:\n date = mesg['posted']['date-parts'][0][0]\n else:\n date = 'unknown'\n return date\n\n\ndef call_doi_with_retry(doi):\n \"\"\" Looping function for call_doi\n Keyword arguments:\n doi: DOI\n Returns:\n msg: response from crossref.org\n title: publication title\n author: publication first author surname\n date: publication year\n \"\"\"\n attempt = MAX_CROSSREF_TRIES\n msg = ''\n while attempt:\n msg = call_doi(doi)\n if 'title' in msg['message'] and 'author' in msg['message']:\n break\n attempt -= 1\n LOGGER.warning(\"Missing data from crossref.org: retrying (%d)\", attempt)\n sleep(0.5)\n title = author = None\n if 'title' in msg['message']:\n title = msg['message']['title'][0]\n if 'author' in msg['message']:\n author = msg['message']['author'][0]['family']\n date = get_date(msg['message'])\n return msg, title, author, date\n\n\ndef call_datacite(doi):\n \"\"\" Get record from datacite\n Keyword arguments:\n doi: DOI\n Returns:\n msg: response from crossref.org\n title: publication title\n author: publication first author surname\n date: publication year\n \"\"\"\n rec = call_responder('datacite', doi)\n title = author = None\n msg = rec['data']['attributes']\n if 'titles' in msg:\n title = msg['titles'][0]['title']\n if 'creators' in msg:\n author = msg['creators'][0]['familyName']\n if 'publicationYear' in msg:\n date = str(msg['publicationYear'])\n else:\n date = 'unknown'\n return rec, title, author, date\n\n\ndef perform_backcheck(rdict):\n \"\"\" Check to see if we need to delete DOIs from FlyBoy\n Keyword arguments:\n rdict: dictionary of DOIs\n \"\"\"\n try:\n CURSOR['flyboy'].execute(READ['dois'])\n except MySQLdb.Error as err:\n sql_error(err)\n rows = CURSOR['flyboy'].fetchall()\n for row in rows:\n COUNT['foundfb'] += 1\n if row[0] not in rdict:\n LOGGER.warning(WRITE['delete_doi'], (row[0]))\n try:\n CURSOR['flyboy'].execute(WRITE['delete_doi'], (row[0],))\n except MySQLdb.Error as err:\n LOGGER.error(\"Could not delete DOI from doi_data\")\n sql_error(err)\n COUNT['delete'] += 1\n\n\ndef update_dois():\n \"\"\" Sync DOIs in doi_data from StockFinder\n \"\"\"\n if ARG.DOI:\n rows = {\"dois\": [ARG.DOI]}\n else:\n LOGGER.info('Fetching DOIs from FLYF2')\n rows = call_responder('flycore', '?request=doilist')\n rdict = {}\n ddict = {}\n for doi in tqdm(rows['dois']):\n COUNT['found'] += 1\n if 'janelia' in doi:\n msg, title, author, date = call_datacite(doi)\n ddict[doi] = msg['data']['attributes']\n else:\n msg, title, author, date = call_doi_with_retry(doi)\n ddict[doi] = msg['message']\n rdict[doi] = 1\n if not title:\n LOGGER.error(\"Missing title for %s\", doi)\n continue\n if not author:\n LOGGER.error(\"Missing author for %s (%s)\", doi, title)\n continue\n LOGGER.debug(\"%s: %s (%s, %s)\", doi, title, author, date)\n title = unidecode(title)\n LOGGER.debug(WRITE['doi'], doi, title, author, date, title, author, date)\n try:\n CURSOR['flyboy'].execute(WRITE['doi'], (doi, title, author, date,\n title, author, date))\n COUNT['flyboy'] += 1\n except MySQLdb.Error as err:\n LOGGER.error(\"Could not update doi_data\")\n sql_error(err)\n if not ARG.DOI:\n perform_backcheck(rdict)\n if ARG.WRITE:\n CONN['flyboy'].commit()\n for key in ddict:\n entry = json.dumps(ddict[key])\n print(\"Updating %s in config database\" % key)\n resp = requests.post(CONFIG['config']['url'] + 'importjson/dois/' + key,\n {\"config\": entry}, timeout=10)\n if resp.status_code != 200:\n LOGGER.error(resp.json()['rest']['message'])\n else:\n rest = resp.json()\n if 'inserted' in rest['rest']:\n COUNT['insert'] += rest['rest']['inserted']\n elif 'updated' in rest['rest']:\n COUNT['update'] += rest['rest']['updated']\n\n\nif __name__ == '__main__':\n PARSER = argparse.ArgumentParser(description=\"Sync DOIs within FlyBoy\")\n PARSER.add_argument('--doi', dest='DOI', action='store',\n help='Single DOI to insert/update')\n PARSER.add_argument('--manifold', dest='MANIFOLD', action='store',\n default='prod', help='Database manifold')\n PARSER.add_argument('--write', dest='WRITE', action='store_true',\n default=False,\n help='Flag, Actually modify database')\n PARSER.add_argument('--verbose', dest='VERBOSE', action='store_true',\n default=False, help='Flag, Chatty')\n PARSER.add_argument('--debug', dest='DEBUG', action='store_true',\n default=False, help='Flag, Very chatty')\n ARG = PARSER.parse_args()\n\n LOGGER = colorlog.getLogger()\n ATTR = colorlog.colorlog.logging if \"colorlog\" in dir(colorlog) else colorlog\n if ARG.DEBUG:\n LOGGER.setLevel(ATTR.DEBUG)\n elif ARG.VERBOSE:\n LOGGER.setLevel(ATTR.INFO)\n else:\n LOGGER.setLevel(ATTR.WARNING)\n HANDLER = colorlog.StreamHandler()\n HANDLER.setFormatter(colorlog.ColoredFormatter())\n LOGGER.addHandler(HANDLER)\n\n initialize_program()\n update_dois()\n print(\"DOIs found in StockFinder: %d\" % COUNT['found'])\n print(\"DOIs found in FlyBoy: %d\" % COUNT['foundfb'])\n print(\"DOIs inserted/updated in FlyBoy: %d\" % COUNT['flyboy'])\n print(\"DOIs deleted from FlyBoy: %d\" % COUNT['delete'])\n print(\"Documents inserted in config database: %d\" % COUNT['insert'])\n print(\"Documents updated in config database: %d\" % COUNT['update'])\n\n sys.exit(0)\n","repo_name":"JaneliaSciComp/flycore-utilities","sub_path":"bin/update_dois.py","file_name":"update_dois.py","file_ext":"py","file_size_in_byte":9452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37855002073","text":"#!/usr/bin/python\n\nimport xmlrpclib\nimport unittest\n\nfrom random import randint\n\nfrom config import *\n\n# Should have at least 100 free slots to run these tests, which *should*\n# return all of those back to the default satellite org once finished.\nCHANNEL_FAMILY_LABEL = \"rhel-server\"\nSYSTEM_ENTITLEMENT_LABEL = \"provisioning_entitled\"\n\nSATELLITE_ORG_ID = 1\n\nclass OrgTests(RhnTestCase):\n\n def setUp(self):\n RhnTestCase.setUp(self)\n\n # Create a test org that will be deleted in teardown:\n self.random_int = randint(1, 1000000)\n self.org_name = \"Test Org %s\" % self.random_int\n self.org = client.org.create(self.session_key, self.org_name, \n \"admin%s\" % self.random_int, \"password\", \n \"Mr.\", \"Fake\", \"Admin\", \"fake@example.com\", False)\n self.org_id = self.org['id']\n\n def tearDown(self):\n result = client.org.delete(self.session_key, self.org_id)\n RhnTestCase.tearDown(self)\n\n def test_create_org(self):\n self.assertTrue(self.org.has_key('id'))\n self.assertTrue(self.org.has_key('name'))\n self.assertTrue(self.org.has_key('systems'))\n self.assertTrue(self.org.has_key('active_users'))\n self.assertTrue(self.org.has_key('system_groups'))\n self.assertTrue(self.org.has_key('activation_keys'))\n self.assertTrue(self.org.has_key('kickstart_profiles'))\n\n def test_delete_no_such_org(self):\n self.assertRaises(Exception, client.org.delete, self.session_key, -1)\n\n def test_list_channel_family_entitlements(self):\n result = client.org.listSoftwareEntitlements(self.session_key, \n CHANNEL_FAMILY_LABEL)\n self.assertTrue(len(result) >= 1) # default org at least\n for counts in result:\n self.assertTrue(counts.has_key('org_id'))\n self.assertTrue(counts.has_key('allocated'))\n self.assertTrue(counts.has_key('used'))\n self.assertTrue(counts.has_key('free'))\n self.assertEquals(counts['allocated'], counts['used'] + counts['free'])\n\n def test_list_channel_family_entitlements_for_org(self):\n # NOTE: Using the default org here:\n result = client.org.listSoftwareEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n for counts in result:\n self.assertTrue(counts.has_key('label'))\n self.assertTrue(counts.has_key('allocated'))\n self.assertTrue(counts.has_key('used'))\n self.assertTrue(counts.has_key('free'))\n self.assertTrue(counts.has_key('unallocated'))\n self.assertEquals(counts['allocated'], counts['used'] + counts['free'])\n #print \"Channel family: %s\" % counts['channel_family_label']\n #print \" allocated: %s\" % counts['allocated']\n #print \" used: %s\" % counts['used']\n #print \" free: %s\" % counts['free']\n\n #def test_sat_list(self):\n # result = client.satellite.listEntitlements(self.session_key)\n # chan = result['channel']\n # for c in chan:\n # print \"Channel: %s\" % c['name']\n # print \"%s - %s - %s\" % (c['total_slots'], c['free_slots'], c['used_slots'])\n\n def __find_count_for_org(self, results, org_id):\n for count in results:\n if count['org_id'] == org_id:\n return count\n self.fail(\"Unable to find org id: %s\" % org_id)\n\n def __find_count_for_entitlement(self, results, channel_family_label):\n for count in results:\n if count['label'] == channel_family_label:\n return count\n self.fail(\"Unable to find channel family: %s\" % channel_family_label)\n\n def test_set_channel_family_entitlements(self):\n # Lookup satellite org count for verification:\n result = client.org.listSoftwareEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n count = self.__find_count_for_entitlement(result, CHANNEL_FAMILY_LABEL)\n sat_org_total = count['allocated']\n self.assertTrue(count['free'] >= 100)\n\n result = client.org.setSoftwareEntitlements(self.session_key,\n self.org_id, CHANNEL_FAMILY_LABEL, 100)\n self.assertEquals(1, result)\n\n result = client.org.listSoftwareEntitlementsForOrg(self.session_key, \n self.org_id)\n count = self.__find_count_for_entitlement(result, CHANNEL_FAMILY_LABEL)\n self.assertEquals(100, count['allocated'])\n\n # Check that the satellite org lost it's entitlements:\n result = client.org.listSoftwareEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n count = self.__find_count_for_entitlement(result, CHANNEL_FAMILY_LABEL)\n self.assertEquals(sat_org_total - 100, count['allocated'])\n\n def test_set_too_many_channel_family_entitlements(self):\n result = client.org.listSoftwareEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n count = self.__find_count_for_entitlement(result, CHANNEL_FAMILY_LABEL)\n sat_org_free = count['free']\n\n # Allocate one too many entitlements:\n result = self.assertRaises(Exception, \n client.org.setSoftwareEntitlements, self.session_key,\n self.org_id, CHANNEL_FAMILY_LABEL, sat_org_free + 1)\n\n def test_set_channel_family_entitlements_on_default_org(self):\n self.assertRaises(Exception, client.org.setSoftwareEntitlements,\n self.session_key, SATELLITE_ORG_ID, CHANNEL_FAMILY_LABEL, 100)\n\n def test_list_system_entitlements_global(self):\n result = client.org.listSystemEntitlements(self.session_key)\n for r in result:\n self.assertTrue(r.has_key('allocated'))\n self.assertTrue(r.has_key('used'))\n self.assertTrue(r.has_key('free'))\n self.assertTrue(r.has_key('unallocated'))\n\n def test_set_system_entitlements(self):\n # Lookup satellite org count for verification:\n result = client.org.listSystemEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n count = self.__find_count_for_entitlement(result, \n SYSTEM_ENTITLEMENT_LABEL)\n sat_org_total = count['allocated']\n self.assertTrue(count['free'] >= 100)\n\n result = client.org.setSystemEntitlements(self.session_key,\n self.org_id, SYSTEM_ENTITLEMENT_LABEL, 100)\n self.assertEquals(1, result)\n\n result = client.org.listSystemEntitlementsForOrg(self.session_key, \n self.org_id)\n count = self.__find_count_for_entitlement(result, \n SYSTEM_ENTITLEMENT_LABEL)\n self.assertEquals(100, count['allocated'])\n\n # Check that the satellite org lost it's entitlements:\n result = client.org.listSystemEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n count = self.__find_count_for_entitlement(result, \n SYSTEM_ENTITLEMENT_LABEL)\n self.assertEquals(sat_org_total - 100, count['allocated'])\n\n def test_set_too_many_system_entitlements(self):\n result = client.org.listSystemEntitlementsForOrg(self.session_key, \n SATELLITE_ORG_ID)\n count = self.__find_count_for_entitlement(result, \n SYSTEM_ENTITLEMENT_LABEL)\n sat_org_free = count['free']\n\n # Allocate one too many entitlements:\n result = self.assertRaises(Exception, \n client.org.setSoftwareEntitlements, self.session_key,\n self.org_id, SYSTEM_ENTITLEMENT_LABEL, sat_org_free + 1)\n\n def test_set_system_entitlements_on_default_org(self):\n self.assertRaises(Exception, client.org.setSystemEntitlements,\n self.session_key, SATELLITE_ORG_ID, SYSTEM_ENTITLEMENT_LABEL, \n 100)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","repo_name":"colloquium/spacewalk","sub_path":"java/scripts/api/orgtests.py","file_name":"orgtests.py","file_ext":"py","file_size_in_byte":7867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"19148793189","text":"#Lab3 set5\n\ndef get_in()->str:\n name=input(\"Enter your full name(including middle name): \")\n init=name.split(\" \")\n frst=init[0]\n mddl=init[1]\n lst=init[2]\n fn=frst[:1]\n mn=mddl[:1]\n ln=lst[:1]\n initial=fn+'.'+mn+'.'+ln\n return initial\n\ndef main():\n initial=get_in()\n print(initial)\n\nif __name__==\"__main__\":\n main()\n\n##>>> \n##======= RESTART: /Users/alieshghi/Desktop/lab 3/Lab 3 program set 5.py =======\n##Enter your full name(including middle name): Ali Sikim Eshghi\n##A.S.E\n##>>> \n##======= RESTART: /Users/alieshghi/Desktop/lab 3/Lab 3 program set 5.py =======\n##Enter your full name(including middle name): Amir Joghd Valipour\n##A.J.V\n##>>> \n##======= RESTART: /Users/alieshghi/Desktop/lab 3/Lab 3 program set 5.py =======\n##Enter your full name(including middle name): Siavash Chaghalian Baghalianzade\n##S.C.B\n##>>> \n##======= RESTART: /Users/alieshghi/Desktop/lab 3/Lab 3 program set 5.py =======\n##Enter your full name(including middle name): Vala Heshmat Saadat\n##V.H.S\n##>>> \n##======= RESTART: /Users/alieshghi/Desktop/lab 3/Lab 3 program set 5.py =======\n##Enter your full name(including middle name): George W Bush\n##G.W.B\n##>>> \n","repo_name":"aeshghi0/developer-Portfolio-1","sub_path":"Python programs/python-small-labs/simple python programs/lab 3/Lab 3 set 5 ready.py","file_name":"Lab 3 set 5 ready.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1985008689","text":"\"\"\"\nInput: integer value\nOutput: list of prime factors\nDifficulty: 1\n\"\"\"\n\n##### ##### My attempt\n\n\"\"\"\ndef get_prime_factors():\n x = 630\n y = 1\n primes = ['']\n ### Checks range from 1 to number.\n for i in range(1, x):\n ## Check if divisible by itself or 1.\n if (x/i) == int:\n primes.append()\n else:\n pass\n\n\n print(primes)\n\nget_prime_factors()\n\"\"\"\n## Gave up. Printed \"[]\" and nothing more.\n\n##### ##### Instructor's Solution\ndef get_prime_factors(number):\n factors = []\n divisor = 2\n while divisor <= number:\n if number % divisor == 0:\n factors.append(divisor)\n number == number // divisor\n else:\n divisor += 1\n return factors\n\n# Array works, doesn't print, though. FFFFFFFUUUUUUU--\n## Hang on.\n\nnumber = int(input())\nprint(get_prime_factors(number))\n\n# Nope.","repo_name":"GwenMurphy/LinkedIn-Learning-Python","sub_path":"2022-11-Level-Up-Python/PrimeFactors.py","file_name":"PrimeFactors.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28029481182","text":"from keras import backend as K\nimport numpy as np\nfrom keras.models import Model\nfrom keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout, merge, UpSampling2D\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam, SGD, RMSprop\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.preprocessing.image import flip_axis, random_channel_shift\n\nfrom keras.layers import BatchNormalization, Dense, Flatten, Lambda, Convolution2D\nfrom keras.layers.advanced_activations import ELU, LeakyReLU\n\nfrom augmentation import random_rotation, random_zoom\n\ntrainData = np.load('data.npy')\ntrainMask = np.load('dataMask.npy')\n\ntrainData = trainData.astype('float32')\nmean = np.mean(trainData) # mean for data centering\nstd = np.std(trainData) # std for data normalization\n\ntrainData -= mean\ntrainData /= std\n\ntrainMask = trainMask.astype('float32')\ntrainMask /= 255. # scale masks to [0, 1]\n\nsmooth = 1.\ndef dice_coef(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\n\ndef dice_coef_loss(y_true, y_pred):\n return -dice_coef(y_true, y_pred)\n\ndef jaccard_coef(y_true, y_pred):\n intersection = K.sum(y_true * y_pred, axis=[0, -1, -2])\n sum_ = K.sum(y_true + y_pred, axis=[0, -1, -2])\n jac = (intersection + smooth) / (sum_ - intersection + smooth)\n return K.mean(jac)\n\n\ndef get_unet():\n inputs = Input((256, 256, 3))\n \n conv1 = Conv2D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n conv1 = Conv2D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n \n conv2 = Conv2D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n conv2 = Conv2D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n \n conv3 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n conv3 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n \n conv4 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n conv4 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n drop4 = Dropout(0.2)(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\n \n conv5 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n drop5 = Dropout(0.2)(conv5)\n \n up6 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n merge6 = merge([drop4,up6], mode = 'concat', concat_axis = 3)\n conv6 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6)\n conv6 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n \n up7 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n merge7 = merge([conv3,up7], mode = 'concat', concat_axis = 3)\n conv7 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7)\n conv7 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n \n up8 = Conv2D(32, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n merge8 = merge([conv2,up8], mode = 'concat', concat_axis = 3)\n conv8 = Conv2D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8)\n conv8 = Conv2D(32, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n \n up9 = Conv2D(16, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n merge9 = merge([conv1,up9], mode = 'concat', concat_axis = 3)\n conv9 = Conv2D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9)\n conv9 = Conv2D(16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)\n \n model = Model(input = inputs, output = conv10)\n\n adam = Adam(lr=1e-5)\n model.compile(optimizer=adam, loss=dice_coef_loss, metrics=[dice_coef, jaccard_coef, 'accuracy'])\n# model.compile(optimizer = Adam(lr = 1e-4), loss = 'categorical_crossentropy', metrics = ['accuracy'])\n\n return model\n\nmodel = get_unet()\n\n#def _shortcut(_input, residual):\n# stride_width = _input._keras_shape[1] / residual._keras_shape[1]\n# stride_height = _input._keras_shape[2] / residual._keras_shape[2]\n# equal_channels = residual._keras_shape[3] == _input._keras_shape[3]\n#\n# shortcut = _input\n# # 1 X 1 conv if shape is different. Else identity.\n# if stride_width > 1 or stride_height > 1 or not equal_channels:\n# shortcut = Convolution2D(nb_filter=residual._keras_shape[1], nb_row=1, nb_col=1,\n# subsample=(stride_width, stride_height),\n# init=\"he_normal\", border_mode=\"valid\")(_input)\n#\n# return merge([shortcut, residual], mode=\"sum\")\n#\n#def inception_block(inputs, depth, batch_mode=0, splitted=False, activation='relu'):\n# assert depth % 16 == 0\n# actv = activation == 'relu' and (lambda: LeakyReLU(0.0)) or activation == 'elu' and (lambda: ELU(1.0)) or None\n# \n# c1_1 = Convolution2D(int(depth/4), (1, 1), init='he_normal', border_mode='same')(inputs)\n# \n# c2_1 = Convolution2D(int(depth/8*3), (1, 1), init='he_normal', border_mode='same')(inputs)\n# c2_1 = actv()(c2_1)\n# if splitted:\n# c2_2 = Convolution2D(int(depth/2), (1, 3), init='he_normal', border_mode='same')(c2_1)\n# c2_2 = BatchNormalization(axis=1)(c2_2)\n# c2_2 = actv()(c2_2)\n# c2_3 = Convolution2D(int(depth/2), (3, 1), init='he_normal', border_mode='same')(c2_2)\n# else:\n# c2_3 = Convolution2D(int(depth/2), (3, 3), init='he_normal', border_mode='same')(c2_1)\n# \n# c3_1 = Convolution2D(int(depth/16), (1, 1), init='he_normal', border_mode='same')(inputs)\n# #missed batch norm\n# c3_1 = actv()(c3_1)\n# if splitted:\n# c3_2 = Convolution2D(int(depth/8), (1, 5), init='he_normal', border_mode='same')(c3_1)\n# c3_2 = BatchNormalization(axis=1)(c3_2)\n# c3_2 = actv()(c3_2)\n# c3_3 = Convolution2D(int(depth/8), (5, 1), init='he_normal', border_mode='same')(c3_2)\n# else:\n# c3_3 = Convolution2D(int(depth/8), (5, 5), init='he_normal', border_mode='same')(c3_1)\n# \n# p4_1 = MaxPooling2D(pool_size=(3,3), strides=(1,1), border_mode='same')(inputs)\n# c4_2 = Convolution2D(int(depth/8), 1, 1, init='he_normal', border_mode='same')(p4_1)\n# \n# res = merge([c1_1, c2_3, c3_3, c4_2], mode='concat', concat_axis=1)\n# res = BatchNormalization(axis=1)(res)\n# res = actv()(res)\n# return res\n#\n#def rblock(inputs, num, depth, scale=0.1): \n# residual = Convolution2D(depth, (num, num), border_mode='same')(inputs)\n# residual = BatchNormalization(axis=1)(residual)\n# residual = Lambda(lambda x: x*scale)(residual)\n# res = _shortcut(inputs, residual)\n# return ELU()(res) \n#\n#def NConvolution2D(nb_filter, nb_row, nb_col, border_mode='same', subsample=(1, 1)):\n# def f(_input):\n# conv = Convolution2D(nb_filter=nb_filter, nb_row=nb_row, nb_col=nb_col, subsample=subsample,\n# border_mode=border_mode)(_input)\n# norm = BatchNormalization(axis=1)(conv)\n# return ELU()(norm)\n#\n# return f\n#\n#def BNA(_input):\n# inputs_norm = BatchNormalization(axis=1)(_input)\n# return ELU()(inputs_norm)\n#\n#def reduction_a(inputs, k=64, l=64, m=96, n=96):\n# \"35x35 -> 17x17\"\n# inputs_norm = BNA(inputs)\n# pool1 = MaxPooling2D((3,3), strides=(2,2), border_mode='same')(inputs_norm)\n# \n# conv2 = Convolution2D(n, (3, 3), subsample=(2,2), border_mode='same')(inputs_norm)\n# \n# conv3_1 = NConvolution2D(k, (1, 1), subsample=(1,1), border_mode='same')(inputs_norm)\n# conv3_2 = NConvolution2D(l, (3, 3), subsample=(1,1), border_mode='same')(conv3_1)\n# conv3_2 = Convolution2D(m, (3, 3), subsample=(2,2), border_mode='same')(conv3_2)\n# \n# res = merge([pool1, conv2, conv3_2], mode='concat', concat_axis=1)\n# return res\n#\n#def reduction_b(inputs):\n# \"17x17 -> 8x8\"\n# inputs_norm = BNA(inputs)\n# pool1 = MaxPooling2D((3,3), strides=(2,2), border_mode='same')(inputs_norm)\n# #\n# conv2_1 = NConvolution2D(64, (1, 1), subsample=(1,1), border_mode='same')(inputs_norm)\n# conv2_2 = Convolution2D(96, (3, 3), subsample=(2,2), border_mode='same')(conv2_1)\n# #\n# conv3_1 = NConvolution2D(64, (1, 1), subsample=(1,1), border_mode='same')(inputs_norm)\n# conv3_2 = Convolution2D(72, (3, 3), subsample=(2,2), border_mode='same')(conv3_1)\n# #\n# conv4_1 = NConvolution2D(64, (1, 1), subsample=(1,1), border_mode='same')(inputs_norm)\n# conv4_2 = NConvolution2D(72, (3, 3), subsample=(1,1), border_mode='same')(conv4_1)\n# conv4_3 = Convolution2D(80, (3, 3), subsample=(2,2), border_mode='same')(conv4_2)\n# #\n# res = merge([pool1, conv2_2, conv3_2, conv4_3], mode='concat', concat_axis=1)\n# return res\n# \n#def get_unet_inception_2head():\n# splitted = True\n# act = 'elu'\n# \n# inputs = Input((128, 128, 1), name='main_input')\n# conv1 = inception_block(inputs, 32, batch_mode=2, splitted=splitted, activation=act)\n# #conv1 = inception_block(conv1, 32, batch_mode=2, splitted=splitted, activation=act)\n# \n# #pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n# pool1 = NConvolution2D(32, 3, 3, border_mode='same', subsample=(2,2))(conv1)\n# pool1 = Dropout(0.5)(pool1)\n# \n# conv2 = inception_block(pool1, 64, batch_mode=2, splitted=splitted, activation=act)\n# #pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n# pool2 = NConvolution2D(64, 3, 3, border_mode='same', subsample=(2,2))(conv2)\n# pool2 = Dropout(0.5)(pool2)\n# \n# conv3 = inception_block(pool2, 128, batch_mode=2, splitted=splitted, activation=act)\n# #pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n# pool3 = NConvolution2D(128, 3, 3, border_mode='same', subsample=(2,2))(conv3)\n# pool3 = Dropout(0.5)(pool3)\n# \n# conv4 = inception_block(pool3, 256, batch_mode=2, splitted=splitted, activation=act)\n# #pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n# pool4 = NConvolution2D(256, 3, 3, border_mode='same', subsample=(2,2))(conv4)\n# pool4 = Dropout(0.5)(pool4)\n# \n# conv5 = inception_block(pool4, 512, batch_mode=2, splitted=splitted, activation=act)\n# #conv5 = inception_block(conv5, 512, batch_mode=2, splitted=splitted, activation=act)\n# conv5 = Dropout(0.5)(conv5)\n# \n# after_conv4 = rblock(conv4, 1, 256)\n# up6 = merge([UpSampling2D(size=(2, 2))(conv5), after_conv4], mode='concat', concat_axis=1)\n# conv6 = inception_block(up6, 256, batch_mode=2, splitted=splitted, activation=act)\n# conv6 = Dropout(0.5)(conv6)\n# \n# after_conv3 = rblock(conv3, 1, 128)\n# up7 = merge([UpSampling2D(size=(2, 2))(conv6), after_conv3], mode='concat', concat_axis=1)\n# conv7 = inception_block(up7, 128, batch_mode=2, splitted=splitted, activation=act)\n# conv7 = Dropout(0.5)(conv7)\n# \n# after_conv2 = rblock(conv2, 1, 64)\n# up8 = merge([UpSampling2D(size=(2, 2))(conv7), after_conv2], mode='concat', concat_axis=1)\n# conv8 = inception_block(up8, 64, batch_mode=2, splitted=splitted, activation=act)\n# conv8 = Dropout(0.5)(conv8)\n# \n# after_conv1 = rblock(conv1, 1, 32)\n# up9 = merge([UpSampling2D(size=(2, 2))(conv8), after_conv1], mode='concat', concat_axis=1)\n# conv9 = inception_block(up9, 32, batch_mode=2, splitted=splitted, activation=act)\n# #conv9 = inception_block(conv9, 32, batch_mode=2, splitted=splitted, activation=act)\n# conv9 = Dropout(0.5)(conv9)\n#\n# conv10 = Convolution2D(1, (1, 1), init='he_normal', activation='sigmoid', name='main_output')(conv9)\n# #print conv10._keras_shape\n#\n# model = Model(input=inputs, output=[conv10])\n# \n# adam = Adam(lr=1e-5)\n# model.compile(optimizer=adam, loss=dice_coef_loss, metrics=[dice_coef, jaccard_coef])\n#\n# return model\n#\n#\n#model = get_unet_inception_2head()\n\n#datagen = ImageDataGenerator(rotation_range=0.2,\n# width_shift_range=0.05,\n# height_shift_range=0.05,\n# shear_range=0.05,\n# zoom_range=0.05,\n# horizontal_flip=True,\n# fill_mode='nearest')\n#\n#datagen.fit(trainData)\n#\n#\n#def schedule(epoch):\n# if epoch<=5:\n# return 1e-5\n# elif epoch<=10:\n# return 5e-4\n# elif epoch<=25:\n# return 2e-4\n# elif epoch<=40:\n# return 1e-3\n# else:\n# return 5e-4\n#\n#lr_schedule= LearningRateScheduler(schedule)\n# \n#model.fit_generator(datagen.flow(trainData, trainMask, batch_size=16), steps_per_epoch=500, epochs=50, verbose=1, callbacks=[lr_schedule])\n\n\ndef Augmentation(X, Y):\n print('Augmentation model...')\n total = len(X)\n x_train, y_train = [], []\n \n for i in range(total):\n x, y = X[i], Y[i]\n #standart\n x_train.append(x)\n y_train.append(y)\n \n# for _ in xrange(1):\n# _x, _y = elastic_transform(x[0], y[0], 100, 20)\n# x_train.append(_x.reshape((1,) + _x.shape))\n# y_train.append(_y.reshape((1,) + _y.shape))\n \n #flip x\n x_train.append(flip_axis(x, 2))\n y_train.append(flip_axis(y, 2))\n #flip y\n x_train.append(flip_axis(x, 1))\n y_train.append(flip_axis(y, 1))\n #continue\n #zoom\n for _ in range(5):\n _x, _y = random_zoom(x, y, (0.9, 1.1))\n x_train.append(_x)\n y_train.append(_y)\n for _ in range(8):\n _x, _y = random_rotation(x, y, 5)\n x_train.append(_x)\n y_train.append(_y)\n #intentsity\n for _ in range(10):\n _x = random_channel_shift(x, 5.0)\n x_train.append(_x)\n y_train.append(y)\n \n x_train = np.array(x_train)\n y_train = np.array(y_train)\n return x_train, y_train\n \ndef AugmentationValidation(X, Y):\n print('Augmentation model...')\n total = len(X)\n x_train, y_train = [], []\n \n for i in range(total):\n x, y = X[i], Y[i]\n #standart\n x_train.append(x)\n y_train.append(y)\n \n# for _ in xrange(1):\n# _x, _y = elastic_transform(x[0], y[0], 100, 20)\n# x_train.append(_x.reshape((1,) + _x.shape))\n# y_train.append(_y.reshape((1,) + _y.shape))\n \n #flip x\n x_train.append(flip_axis(x, 2))\n y_train.append(flip_axis(y, 2))\n #flip y\n x_train.append(flip_axis(x, 1))\n y_train.append(flip_axis(y, 1))\n #continue\n #zoom\n for _ in range(1):\n _x, _y = random_zoom(x, y, (0.9, 1.1))\n x_train.append(_x)\n y_train.append(_y)\n for _ in range(0):\n _x, _y = random_rotation(x, y, 5)\n x_train.append(_x)\n y_train.append(_y)\n #intentsity\n for _ in range(1):\n _x = random_channel_shift(x, 5.0)\n x_train.append(_x)\n y_train.append(y)\n \n x_train = np.array(x_train)\n y_train = np.array(y_train)\n return x_train, y_train\n \nx_train, y_train = Augmentation(trainData, trainMask)\nx_validation, y_validation = AugmentationValidation(trainData, trainMask)\n\ndef schedule(epoch):\n if epoch<=20:\n return 1e-5\n elif epoch<=40:\n return 1e-4\n else:\n return 1e-5\n\nlr_schedule= LearningRateScheduler(schedule)\n\nmodel.fit(x_train, y_train,\n batch_size=16, nb_epoch=50,\n verbose=1, validation_data=(x_validation, y_validation), shuffle=True, callbacks=[lr_schedule])\n\nmodel.save('unet_vanilla_final.h5')","repo_name":"balwantraikekutte/optic-disc-seg","sub_path":"residualunet.py","file_name":"residualunet.py","file_ext":"py","file_size_in_byte":16918,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"38852389610","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 8 14:48:02 2021\n\nDefinition de la classe Land\n\n@author: adupaix\n\"\"\"\n\nclass Land:\n \"\"\"\n Class qui contient un polygone construit a partir des\n coordonnees des terres dans la zone d'etude\n \"\"\"\n \n def __init__(self, path, environment, study_center, land_file):\n \"\"\"\n Initialise un objet de la classe Land\n \n arguments:\n - path: (str) chemin vers les fichiers csv avec les coordonnees de la terre\n - environment: (str) soit hawaii, maldives ou mauritius\n \n contient:\n - poly : polygon of the land\n - line: lines of the coasts\n - x and y: coordinates of the points used to build the polygon and line\n Each of these 4 variables are stored in km from the \"study_center\" and in degree of long,lat\n (add \"_deg\" to the name of the variable)\n \n - env: name of the environment\n \"\"\"\n convKmDeg = 111\n \n self.env = environment\n self.island = land_file\n \n self.x_deg = []\n self.y_deg = []\n \n fr = open(str(path)+\"/\"+land_file+\".csv\")\n \n for d in csv.DictReader(fr):\n self.x_deg.append(float(d['x']))\n self.y_deg.append(float(d['y']))\n \n fr.close()\n \n \n self.x_deg = np.array(self.x_deg)\n self.y_deg = np.array(self.y_deg)\n \n coords_deg = np.c_[self.x_deg, self.y_deg]\n \n self.poly_deg = Polygon(coords_deg)\n self.line_deg = LinearRing(coords_deg)\n \n self.x = (self.x_deg - np.repeat(study_center[0], len(self.x_deg))) * convKmDeg\n self.y = (self.y_deg - np.repeat(study_center[1], len(self.y_deg))) * convKmDeg\n \n coords = np.c_[self.x, self.y]\n \n self.poly = Polygon(coords)\n self.line = LinearRing(coords)\n \n \n def __repr__(self):\n \"\"\"Methode pour afficher l objet\n \"\"\"\n return \"Land object\\n\\n Environment: {}\\n Island: {}\".format(self.env, self.island)\n \n ","repo_name":"adupaix/FAT_albaCoRaW","sub_path":"classes/CLASS_Land.py","file_name":"CLASS_Land.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42658863345","text":"#!/usr/bin/env python3\nimport os\nfrom Bio import SeqIO\n\nos.chdir('/home/kika/ownCloud/pelomyxa/augustus_training_set/')\nfasta = SeqIO.parse('pelo_trinity_mbal_aa_dedupl.fa', 'fasta')\nout = open('pelo_trinity_mbal_aa_final.fa', 'w')\n\npseudo = 0\nincompl = 0\nfor seq in fasta:\n\t# print(seq.name, seq.seq[0])\n\tif 'X' in seq.seq:\n\t\tpseudo += 1\n\telif 'M' != seq.seq[0]:\n\t\tincompl += 1\n\telse:\n\t\tout.write('>{}\\n{}\\n'.format(seq.description, str(seq.seq)))\n\nprint('pseudogenes: ' + str(pseudo))\nprint('truncated: ' + str(incompl))\n\nout.close()","repo_name":"kikinocka/ngs","sub_path":"py_scripts/blastocrithidia/remove_incomplete_X_seqs.py","file_name":"remove_incomplete_X_seqs.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73148145446","text":"#!/usr/bin/env python3\n\nimport sympy as sp\n\ny, p, r = sp.symbols('y p r') # yaw, pitch, roll\nRz = sp.Matrix([[sp.cos(y), -sp.sin(y), 0],\n [sp.sin(y), sp.cos(y), 0],\n [ 0, 0, 1]])\nRy = sp.Matrix([[ sp.cos(p), 0, sp.sin(p)],\n [ 0, 1, 0],\n [-sp.sin(p), 0, sp.cos(p)]])\nRx = sp.Matrix([[1, 0, 0],\n [0, sp.cos(r), -sp.sin(r)],\n [0, sp.sin(r), sp.cos(r)]])\nR = Ry*Rz*Rx\nsp.pprint(R)\n\natan = sp.atan2(-R[2,0],R[0,0])\nsp.pprint(sp.simplify(atan))\n","repo_name":"seqwalt/monobot","sub_path":"sandbox/symbolic_sandbox_rotation_mat.py","file_name":"symbolic_sandbox_rotation_mat.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15267661274","text":"from flask import Flask , render_template , request , redirect, url_for , session\nfrom flask_bcrypt import Bcrypt\nfrom emotion_detector import *\nimport database as dbs\nfrom recommender import *\nfrom assignment import *\nimport rec\nfrom bson import ObjectId\nimport smtp\n\nanime_already_recommended = []\nanime_user_likes = \"\"\n\napp = Flask(__name__)\nbcrypt = Bcrypt(app)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route(\"/logout\")\ndef logout():\n session.pop('username')\n anime_to_show = []\n return redirect(url_for('index'))\n\n@app.route('/team')\ndef team():\n return render_template('team.html')\n\n@app.route('/home')\ndef home():\n if 'username' not in session:\n return redirect(url_for('index'))\n \n print(session)\n\n user = dbs.users.find_one({'username' : session['username']})\n no_of_ass = user['assignments']\n if len(no_of_ass) > 0:\n for i in range(0,len(no_of_ass)):\n due = str_to_date(no_of_ass[i]['due'])\n dt_string = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n now = str_to_datetime(dt_string)\n time_left = subtract_date(due,now)\n days_left = time_left.days\n hrs_left = sec_to_hrs(time_left.seconds)\n print(time_left)\n print(time_left.days)\n print(\"time left\")\n print(time_left.seconds)\n # if days_left == 1 and time_left.seconds == 43200:\n # body = \"1 day left to complete!!\\nAssignment: \" + no_of_ass[0]['assgn'] + \"\\nSubject: \" + no_of_ass[0]['sub']\n # smtp.send_mail(user['email'],body)\n # if days_left == 0 and time_left.seconds == 43200:\n # body = \"Only 12 hours left to complete!!\\nAssignment: \" + no_of_ass[0]['assgn'] + \"\\nSubject: \" + no_of_ass[0]['sub']\n # smtp.send_mail(user['email'],body)\n if days_left == 0 and time_left.seconds <= 14400 and time_left.seconds >= 13100:\n body = \"Only 12 hours left to complete!!\\nAssignment: \" + no_of_ass[0]['assgn'] + \"\\nSubject: \" + no_of_ass[0]['sub']\n smtp.send_mail(user['email'],body)\n return render_template('home.html', n = len(no_of_ass))\n\n@app.route('/firstTime', methods = ['POST' , 'GET'])\ndef firstTime():\n if 'username' not in session:\n return redirect(url_for('index'))\n if request.method == 'POST':\n imd = request.form\n anime_preferences = imd.to_dict(flat=False)\n subjects = imd['subjects'].split('-')\n attendance = []\n for sub in subjects:\n obj = {\n 'sub_name': sub,\n 'attended': 0,\n 'not_attended': 0\n } \n attendance.append(obj)\n myquery = {'username': session['username']} \n newvalues = { \"$set\" : { \"anime_preferences\": anime_preferences } }\n dbs.users.update_one(myquery, newvalues)\n newvalues = { \"$set\" : { \"attendance\": attendance } }\n dbs.users.update_one(myquery, newvalues)\n print(session['username'])\n return redirect(url_for('home'))\n \n return render_template('firstTime.html', user = session['username'] ,genres = list_of_animes_genre)\n\n@app.route('/login', methods=['POST'])\ndef login():\n users = dbs.users\n login_user = users.find_one({'username' : request.form['username']})\n\n if login_user:\n if bcrypt.check_password_hash(login_user['password'], request.form['pass']):\n session['username'] = request.form['username']\n return redirect(url_for('home'))\n\n return 'Invalid username/password combination'\n\n@app.route('/register', methods=['POST', 'GET'])\ndef register():\n if request.method == 'POST':\n users = dbs.users\n existing_user = users.find_one({'username' : request.form['username']})\n\n if existing_user is None:\n hashpass = bcrypt.generate_password_hash(request.form['pass'], 10)\n #hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())\n users.insert_one({'username' : request.form['username'], 'password' : hashpass, 'email': request.form['email'] , 'dob' : request.form['dob'], 'attendance': [], 'assignments' : [], 'anime_dropped':[]})\n session['username'] = request.form['username']\n return redirect(url_for('firstTime'))\n \n return 'That username already exists!'\n\n return render_template('register.html')\n\n@app.route('/check')\ndef check():\n if 'username' not in session:\n return redirect(url_for('index'))\n current_user = dbs.users.find_one({'username': session['username']})\n if len(current_user['assignments']) > 0:\n nearest_ass = current_user['assignments'][0]\n if subdate(str_to_date(nearest_ass['due'])):\n return render_template('warning.html', ass = nearest_ass)\n return redirect(url_for('anime'))\n\n@app.route('/anime')\ndef anime():\n if 'username' not in session:\n return redirect(url_for('index'))\n current_user = dbs.users.find_one({'username': session['username']})\n anime = []\n df = pd.read_csv('finalAnimeCSV.csv')\n franime = []\n if 'friends' in current_user:\n current_user_freind = current_user['friends']\n id = current_user_freind[0]\n objInstance = ObjectId(id)\n friend = dbs.users.find_one({\"_id\": objInstance})['anime_recommended']\n for i in friend:\n index = int(i)\n obj = {\n 'index': index,\n 'poster': get_poster_from_index(index,df),\n 'title': get_title_from_index(index,df)\n }\n franime.append(obj)\n return render_template('anime.html', animes = anime, franime = franime)\n\n@app.route('/byName')\ndef byName():\n if 'username' not in session:\n return redirect(url_for('index'))\n flag = 1 ; \n df = pd.read_csv('finalAnimeCSV.csv')\n anime_user_likes = str(request.args.get('animeName'))\n sorted_similar_anime = recommending(flag = flag,anime_user_likes = anime_user_likes)\n anime_to_show = displaying_recommended_anime(anime_already_recommended,sorted_similar_anime)\n for anime in anime_to_show:\n anime_already_recommended.append(anime['index'])\n current_user = dbs.users.find_one({'username': session['username']})\n #anime_to_show = {k: v for k, v in anime_to_show.items() if v not in current_user['anime_dropped']}\n franime = []\n if 'friends' in current_user:\n current_user_friend = current_user['friends']\n id = current_user_friend[0]\n objInstance = ObjectId(id)\n friend = dbs.users.find_one({\"_id\": objInstance})['anime_recommended']\n for i in friend:\n index = int(i)\n obj = {\n 'index': index,\n 'poster': get_poster_from_index(index,df),\n 'title': get_title_from_index(index,df)\n }\n franime.append(obj)\n return render_template('anime.html', animes = anime_to_show, franime = franime)\n\n@app.route('/byEmotion', methods = ['POST', 'GET'])\ndef byEmotion():\n user_colors = []\n if request.method == 'GET':\n return render_template('color.html')\n else:\n df = pd.read_csv('finalAnimeCSV.csv')\n current_user = dbs.users.find_one({'username': session['username']})\n franime = []\n if 'friends' in current_user:\n current_user_friend = current_user['friends']\n id = current_user_friend[0]\n objInstance = ObjectId(id)\n friend = dbs.users.find_one({\"_id\": objInstance})['anime_recommended']\n for i in friend:\n index = int(i)\n obj = {\n 'index': index,\n 'poster': get_poster_from_index(index,df),\n 'title': get_title_from_index(index,df)\n }\n franime.append(obj)\n color = []\n for i in request.form:\n if request.form[i] == '1':\n color.append(i.upper())\n flag = 2\n user = dbs.users.find_one({'username': session['username']})\n emotion = analyse_emotion(color)\n emotional_genre = detecting_genre(emotion,user=user)\n sorted_similar_anime , df = recommending(flag = flag,emotional_genre=emotional_genre)\n anime_to_show = displaying_recommended_anime(anime_already_recommended,sorted_similar_anime)\n for anime in anime_to_show:\n anime_already_recommended.append(anime['index'])\n deleteLast(df=df)\n return render_template('anime.html', animes = anime_to_show, franime = franime)\n\n@app.route('/spotify', methods = ['POST','GET'])\ndef spotify():\n if request.method == 'GET':\n return render_template('colorSongs.html')\n else:\n color = []\n for i in request.form:\n if request.form[i] == '1':\n color.append(i.upper())\n emotion = analyse_emotion(color)\n if 'happy' or 'sad' in emotion:\n songs = rec.hapSad\n if 'happy' in emotion:\n print('happy')\n songs = rec.sortHappyAngry(songs)\n else:\n print('sad')\n songs = rec.sortSadLove(songs)\n else:\n songs = rec.angryLov\n if 'angry' in emotion:\n print('angry')\n songs = rec.sortHappyAngry(songs)\n else:\n print('love')\n songs = rec.sortSadLove(songs)\n\n return render_template('spotify.html', songs = songs)\n\n@app.route('/show/')\ndef show(i):\n if 'username' not in session:\n return redirect(url_for('index'))\n df = pd.read_csv('finalAnimeCSV.csv')\n index = int(i)\n temp_anime_dict = {\n \"index\": index,\n \"title\": get_title_from_index(index,df),\n \"score\": get_score_from_index(index,df),\n \"genre\": findGenre(get_genre_from_index(index,df)),\n \"poster\": get_poster_from_index(index,df),\n \"synopsis\": get_synopsis_from_index(index,df),\n \"link\" : get_link_from_index(index,df)\n }\n return render_template('show.html', anime = temp_anime_dict)\n\n@app.route('/assignment', methods=['POST','GET'])\ndef assignment():\n if 'username' not in session:\n return redirect(url_for('index'))\n myquery = {'username': session['username']}\n if request.method == 'POST':\n userAss = dbs.users.find_one(myquery)['assignments']\n userAss.append(request.form)\n sortedAss = sorted(userAss, key=lambda i: datetime.strptime(i['due'], \"%Y-%m-%d\"))\n newvalues = { \"$set\" : { \"assignments\": sortedAss } }\n dbs.users.update_one(myquery, newvalues)\n return redirect(url_for('assignment'))\n \n\n userAss = dbs.users.find_one(myquery)['assignments']\n if len(userAss) != 0:\n recent = userAss[0]['due']\n if toRemove(recent):\n userAss.pop(0)\n sortedAss = sorted(userAss, key=lambda i: datetime.strptime(i['due'], \"%Y-%m-%d\"))\n newvalues = { \"$set\" : { \"assignments\": sortedAss } }\n dbs.users.update_one(myquery, newvalues)\n return render_template('assignment.html', ass = userAss, n = len(userAss))\n\n@app.route('/assignment/delete/')\ndef assgnDelete(i):\n myquery = {'username': session['username']}\n userAss = dbs.users.find_one(myquery)['assignments']\n userAss.pop(int(i))\n sortedAss = sorted(userAss, key=lambda i: datetime.strptime(i['due'], \"%Y-%m-%d\"))\n newvalues = { \"$set\" : { \"assignments\": sortedAss } }\n dbs.users.update_one(myquery, newvalues)\n return redirect(url_for('assignment'))\n\n@app.route('/attendance', methods = ['POST', 'GET'])\ndef attendance():\n if 'username' not in session:\n return redirect(url_for('index'))\n myquery = {'username': session['username']}\n attendance = dbs.users.find_one(myquery)['attendance']\n if request.method == 'POST':\n for sub in request.form:\n lst = sub.split(\"_\")\n for i in range(0,len(attendance)):\n if attendance[i]['sub_name'] in lst and 'attended' in lst:\n attendance[i]['attended'] += int(request.form[sub])\n elif attendance[i]['sub_name'] in lst and 'bunked' in lst:\n attendance[i]['not_attended'] += int(request.form[sub])\n\n newvalues = { \"$set\" : { \"attendance\": attendance } }\n dbs.users.update_one(myquery, newvalues)\n return redirect(url_for('attendance'))\n\n \n \n return render_template('attendance.html', attendance = attendance)\n\n@app.route('/attendance/subjects', methods = ['POST'])\ndef edit_subjects():\n subjects = request.form['subjects'].split('-')\n attendance = []\n for sub in subjects:\n obj = {\n 'sub_name': sub,\n 'attended': 0,\n 'not_attended': 0\n } \n attendance.append(obj)\n myquery = {'username': session['username']}\n newvalues = { \"$set\" : { \"attendance\": attendance } }\n dbs.users.update_one(myquery, newvalues)\n return redirect(url_for('attendance'))\n \n\n@app.route('/status/', methods = ['POST'])\ndef set_status(i):\n index = int(i)\n myquery = {'username': session['username']} \n status = request.form\n if status[\"favourite\"] == 'yes':\n newvalues = { \"$addToSet\" : { \"favourites\": index } }\n dbs.users.update_one(myquery, newvalues)\n if status[\"recommend\"] == 'yes':\n newvalues = { \"$addToSet\" : { \"anime_recommended\": index } }\n dbs.users.update_one(myquery, newvalues)\n if status[\"status\"] == 'watched':\n newvalues = { \"$addToSet\" : { \"anime_watched\": index } }\n dbs.users.update_one(myquery, newvalues)\n elif status[\"status\"] == 'considering':\n newvalues = { \"$addToSet\" : { \"anime_considering\": index } }\n dbs.users.update_one(myquery, newvalues)\n else:\n newvalues = { \"$addToSet\" : { \"anime_dropped\": index } }\n dbs.users.update_one(myquery, newvalues)\n return redirect(url_for('anime'))\n\nif __name__ == '__main__':\n app.secret_key = 'mysecret'\n app.run(debug=True)","repo_name":"adityashirodkar1/Chhatra_Mitra","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":14110,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"33896788124","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Create data\nx = np.linspace(-5, 5, 100)\ny = np.linspace(-5, 5, 100)\nX, Y = np.meshgrid(x, y)\nZ = np.sin(np.sqrt(X**2 + Y**2))\n\n# Create surface plot\nfig = plt.figure()\nax = fig.add_subplot(1, 2, 1, projection='3d')\nax.plot_surface(X, Y, Z, cmap='viridis')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nax.set_title('Surface Plot')\n\n# Create mesh plot\nax = fig.add_subplot(1, 2, 2, projection='3d')\nax.plot_wireframe(X, Y, Z, cmap='viridis')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nax.set_title('Mesh Plot')\n\n# Show the plots\nplt.show()\n","repo_name":"fari03/Practice_Labs","sub_path":"Python/MatplotlibSurfaceMeshPlot.py","file_name":"MatplotlibSurfaceMeshPlot.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31154618269","text":"import time\nfrom odoo import models, api, _\n\n\nclass account_trail_balance(models.AbstractModel):\n _name = \"report.sg_account_report.account_trial_balance_temp\"\n\n def _get_accounts(self, accounts, display_account):\n \"\"\" compute the balance, debit and credit for the provided accounts\n :Arguments:\n `accounts`: list of accounts record,\n `display_account`: it's used to display either all accounts or those accounts which balance is > 0\n :Returns a list of dictionary of Accounts with following key and value\n `name`: Account name,\n `code`: Account code,\n `credit`: total amount of credit,\n `debit`: total amount of debit,\n `balance`: total amount of balance,\n \"\"\"\n account_result = {}\n tables, where_clause, where_params = self.env['account.move.line']._query_get()\n tables = tables.replace('\"','')\n if not tables:\n tables = 'account_move_line'\n wheres = [\"\"]\n if where_clause.strip():\n wheres.append(where_clause.strip())\n filters = \" AND \".join(wheres)\n request = (\"SELECT account_id AS id, SUM(debit) AS debit, SUM(credit) AS credit, (SUM(debit) - SUM(credit)) AS balance\" +\\\n \" FROM \" + tables + \" WHERE account_id IN %s \" + filters + \" GROUP BY account_id\")\n params = (tuple(accounts.ids),) + tuple(where_params)\n self.env.cr.execute(request, params)\n for row in self.env.cr.dictfetchall():\n account_result[row.pop('id')] = row\n\n account_res = []\n for account in accounts:\n ytd_credit = ytd_debit = 0.0\n account_mv_ids = self.env['account.move.line'].search([('account_id','=',account.id)])\n for account_mv_rec in account_mv_ids:\n ytd_credit += account_mv_rec.credit or 0.0\n ytd_debit += account_mv_rec.debit or 0.0\n res = dict((fn, 0.0) for fn in ['credit', 'debit', 'balance'])\n currency = account.currency_id and account.currency_id or account.company_id.currency_id\n res['code'] = account.code\n res['name'] = account.name\n res['ytd_credit'] = ytd_credit\n res['ytd_debit'] = ytd_debit\n if account.id in account_result.keys():\n res['debit'] = account_result[account.id].get('debit')\n res['credit'] = account_result[account.id].get('credit')\n res['balance'] = account_result[account.id].get('balance')\n if display_account == 'all':\n account_res.append(res)\n if display_account in ['movement', 'not_zero'] and not currency.is_zero(res['balance']):\n account_res.append(res)\n return account_res\n\n @api.model\n def render_html(self, docids, data=None):\n self.model = self.env.context.get('active_model')\n docs = self.env[self.model].browse(self.env.context.get('active_ids', []))\n display_account = data['form'].get('display_account')\n accounts = docs if self.model == 'account.account' else self.env['account.account'].search([])\n account_res = self.with_context(data['form'].get('used_context'))._get_accounts(accounts, display_account)\n docargs = {\n 'doc_ids': self.ids,\n 'doc_model': self.model,\n 'data': data,\n 'docs': docs,\n 'time': time,\n 'lines': account_res,\n }\n return self.env['report'].render('sg_account_report.account_trial_balance_temp', docargs)\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","repo_name":"Muhammad-SF/Test","sub_path":"core/sg_account_report/report/trial_balance_report.py","file_name":"trial_balance_report.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31925397421","text":"from flask import Flask, render_template, request, redirect, url_for, render_template\nfrom forms import ValidateHashtag\n\napp = Flask(__name__)\napp.config.update(\n WTF_CSRF_ENABLED = True, #Disable Cross-site request forgery protection\n SECRET_KEY = 'nanana'\n)\n#app.secret_key = 'nanana'\n\n#routes\n#telling our @app to execute home() whenever a user visits domain at the given route()\n@app.route('/', methods = ['GET', 'POST'])\ndef main():\n #this should return the homepage\n form = ValidateHashtag(request.form)\n if form.validate_on_submit():\n #if hashtag data is validated, return it to be analyzed\n text = form.input_hashtag.data\n return redirect(url_for('instagram_analyze'))\n return render_template('homepage.html', form = form)\n\n#telling our @app to analyze the searched hashtag\n@app.route('/instagram_analyze/')\ndef instagram_analyze(user_input):\n return render_template(\n 'instagram_analyzer.html',\n input = user_input,\n file_name = user_input + \".png\" #??????\n )\n\n#unsure what this is still\n@app.route('/instagram_analyze/.png')\ndef image(image_name):\n pass\n\n#display the about app\n@app.route('/about')\ndef home():\n return render_template('about.html')","repo_name":"noorameera26/Instagram-Analyzer-with-Python-and-Flask","sub_path":"instagram-analyzer-app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8146289596","text":"import os\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport time as Time\nimport hashlib\nimport glob\nimport json\nimport re\nimport sys\n\n# Configure these vars\n# Set to your log folder wherever it exists\nINPUT_PATH = 'CHANGE ME'\n# Writes a separate file containing only price data for the last X months\nRECENT_MONTHS = 3\n\n# Don't need to change any other vars\nDEBUG = 0\nOUTPUT_PATH = 'output'\nOUTPUT_FILE = 'prices.json'\nREAD_FILES_FILE = 'metadata/read_files.txt'\n\n# Log parsing vars\nCHAT_WINDOW_TEXT_PREFIX = \"[CHAT WINDOW TEXT]\"\nSHOP_OWNER_IDENT = \"'s shop''\"\nSHOP_ITEM_INDENT = \"Do you want to buy the article \"\n\n# Metadata folder locations\nMETADATA_MERCHANT_DERIVED = 'metadata\\merchant_derived_list.json'\n\n# TODO: convert from IRL dates to approximate Arelith dates\nDATE_ARELITH_EXAMPLE = \"Day 12, Month 8 (Elasias (Highsun)) 176 AR. The time is currently 10:15\"\nDATE_IRL_EXAMPLE = \"2022-05-25:09:40\"\n\ndata = []\nproperties = [\"date\", \"url\", \"type\", \"message\"]\n\nRE_TIME = re.compile(\"(\\w{3} \\w{3} \\d{2} \\d{2}:\\d{2}:\\d{2})\")\nRE_STORE_NAME = re.compile(\"[]] ([^:]*): Do you want to buy the article\")\nRE_STORE_OWNER = re.compile(\"[]] ([^:]*): ''(.*)'s shop''\")\nRE_ITEM_NAME = re.compile(\"Do you want to buy the article (.+) [(]Stack\")\nRE_STACK_SIZE = re.compile(\"Stack Size: (\\d+)\")\nRE_PRICE = re.compile(\"for (\\d+)?\")\n\nprice_list_dict = {}\nprice_list = []\nmerchant_dict = {}\nmerchant_dict_parsed = {}\nmerchant_location_dict = {}\nread_file_dict = {}\n\nprint(f'{datetime.now().strftime(\"%Y-%m-%d %H-%M-%S\")} Starting ...')\n\ndef hash_str(input: str) -> int:\n return int(hashlib.sha1(input.encode(\"utf-8\")).hexdigest(), 16) % (10 ** 8)\n\n## Setup log metadata enrichers\n# Setup generated merchant list\ntry:\n with open(os.path.join(os.getcwd(), METADATA_MERCHANT_DERIVED)) as json_file:\n merchant_location_dict = json.load(json_file)\n \n if DEBUG: print(json.dumps(merchant_location_dict, indent = 4, sort_keys=True) )\nexcept FileNotFoundError:\n print(f\"File [{METADATA_MERCHANT_DERIVED}] not found. No derived merchant list loaded.\", file=sys.stderr)\n\n# Setup file ignore list\nif os.path.exists(os.path.join(os.getcwd(), READ_FILES_FILE)):\n with open(os.path.join(os.getcwd(), READ_FILES_FILE)) as json_file:\n for line in json_file:\n value = line.strip()\n read_file_dict[value] = True\n\n if DEBUG: print(json.dumps(read_file_dict, indent = 4, sort_keys=True) )\n\n# Record the read file unless it's already been parsed\nread_file = open(f\"{READ_FILES_FILE}\", \"a\")\n\n## Read all input files out of /input\nfor filename in glob.glob(os.path.join(INPUT_PATH, '*.txt')):\n # 220310_2031.txt\n stripped_name = Path(filename).stem\n date = datetime.strptime(stripped_name, '%y%m%d_%H%M')\n item_count = 0\n\n # Skip files we've already read\n if stripped_name in read_file_dict:\n if DEBUG: print(f'Skipping {stripped_name}. Already read')\n continue\n\n with open(os.path.join(os.getcwd(), filename), 'r', encoding=\"utf8\", errors='ignore') as file:\n for line in file.readlines():\n # Chat window text gets logged twice. Ignore the one without the prefix\n if CHAT_WINDOW_TEXT_PREFIX not in line: continue\n\n line = line.strip()\n line = re.sub(r'[^\\x00-\\x7F]','', line)\n\n if SHOP_OWNER_IDENT in line:\n store_owner = RE_STORE_OWNER.search(line)\n\n if store_owner: store_name = store_owner.group(1).strip()\n if store_owner: store_owner = store_owner.group(2).strip()\n\n if store_owner is None:\n continue\n\n store = {\n \"shop_name\": store_name,\n \"owner\": store_owner,\n \"location\": \"\",\n \"description\": \"\"\n }\n\n if store_name in merchant_location_dict:\n store[\"location\"] = merchant_location_dict[store_name][\"location\"]\n store[\"description\"] = merchant_location_dict[store_name][\"description\"]\n\n if store_owner not in merchant_dict_parsed:\n merchant_dict_parsed[store_name] = store\n\n continue\n\n if SHOP_ITEM_INDENT in line: \n time = RE_TIME.search(line)\n store_name = RE_STORE_NAME.search(line)\n item_name = RE_ITEM_NAME.search(line)\n stack_size = RE_STACK_SIZE.search(line)\n price = RE_PRICE.search(line)\n owner = None\n location = None\n description = None\n \n if time: time = time.group(1).strip()\n if store_name: store_name = store_name.group(1).strip()\n if item_name: item_name = item_name.group(1).strip()\n if stack_size: stack_size = stack_size.group(1)\n if price: price = price.group(1)\n\n hash = hash_str(f\"{date}{store_name}{item_name}{stack_size}{price}\")\n\n if time != None:\n time = f\"{date.strftime('%Y')} {time}\"\n time = datetime.strptime(time, '%Y %a %b %d %H:%M:%S')\n time = datetime.strftime(time, '%Y-%m-%dT%H:%M:%SZ')\n\n stack_size = int(stack_size) if stack_size else None\n price = int(price) if price else None\n price_per_item = None\n if price != None and stack_size != None:\n price_per_item = int(price/stack_size)\n\n if store_name in merchant_dict:\n merchant = merchant_dict[store_name]\n owner = merchant[\"owner\"]\n location = merchant[\"location\"] or None\n description = merchant[\"description\"]\n\n price_dict = {\n \"date\": date.strftime(\"%Y-%m-%d\"),\n \"time\": time,\n \"time_unix\": int(Time.mktime(date.timetuple())),\n \"stock\": stack_size,\n \"price\": price_per_item,\n \"item_name\": item_name,\n \"store_name\": store_name,\n \"owner\": owner,\n \"location\": location,\n \"description\": description,\n \"hash\": hash\n }\n\n key = item_name\n\n if key in price_list_dict:\n duplicate_found = 0\n\n for dict in price_list_dict[key]:\n if dict[\"hash\"] == price_dict[\"hash\"]:\n if DEBUG: print(f\"Dupe found: {hash}. Skipping ...\")\n if DEBUG: print(hash)\n duplicate_found = 1\n break\n\n if not duplicate_found:\n price_list_dict[key].append(price_dict)\n price_list.append(price_dict)\n else:\n price_list_dict[key] = [price_dict]\n price_list.append(price_dict)\n\n item_count += 1\n\n if item_count:\n if DEBUG: print(f\"{item_count} item(s) found in log file '{filename}'\")\n\n # Write the file as having been read\n read_file.writelines(f\"{stripped_name}\\n\")\n\nread_file.close()\n\n# Read old files so we don't wipe out the old data\nprice_list_old = []\ntry:\n with open(os.path.join(os.getcwd(), f\"{OUTPUT_PATH}/{OUTPUT_FILE}\")) as json_file:\n price_list_old = json.load(json_file)\nexcept FileNotFoundError:\n print(f\"No previous [{OUTPUT_FILE}]. Initial creation.\", file=sys.stderr)\n\nmerchant_dict_old = []\ntry:\n with open(os.path.join(os.getcwd(), f\"{METADATA_MERCHANT_DERIVED}\")) as json_file:\n merchant_dict_old = json.load(json_file)\nexcept FileNotFoundError:\n print(f\"No previous [{METADATA_MERCHANT_DERIVED}]. Initial creation.\", file=sys.stderr)\n\n# Combine the old dicts with the new\nif(len(price_list) <= 0): price_list = []\nif(len(price_list_old) <= 0): price_list_old = []\nprice_list = price_list + price_list_old\n\nif(len(merchant_dict_parsed) <= 0): merchant_dict_parsed = {}\nif(len(merchant_dict_old) <= 0): merchant_dict_old = {}\nmerchant_dict_parsed = merchant_dict_parsed | merchant_dict_old\n\n# Grab only the most recent {RECENT_MONTHS} months of data\nprice_list_recent = []\n\nfor item in price_list:\n if datetime.strptime(item.get('date'), '%Y-%m-%d') >= (date.today() + relativedelta(months=-RECENT_MONTHS)):\n price_list_recent.append(item)\n\n# Write out contents of all files\nprice_list_json = json.dumps(price_list, indent = 4, sort_keys=True)\nprice_list_recent_json = json.dumps(price_list_recent, indent = 4, sort_keys=True)\nmerchant_dict_json = json.dumps(merchant_dict_parsed, indent = 4, sort_keys=True)\n\nif DEBUG: print(price_list)\nif DEBUG: print(merchant_dict_json)\n\nf = open(f\"{OUTPUT_PATH}/{OUTPUT_FILE}\", \"w\")\nf.write(price_list_json)\nf.close()\n\nf = open(f\"{OUTPUT_PATH}/prices_last_{RECENT_MONTHS}_months.json\", \"w\")\nf.write(price_list_recent_json)\nf.close()\n\nf = open(f\"{METADATA_MERCHANT_DERIVED}\", \"w\")\nf.write(merchant_dict_json)\nf.close()\n","repo_name":"InfyDae/arelith-price-parser","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":9177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19303839325","text":"import praw\nimport requests\nimport time\nimport json\nimport os\nfrom flask import Flask\n\nport = int(os.environ.get('PORT', 5000))\napp = Flask(__name__)\napp.run(host='0.0.0.0', port=port)\nmain()\n\nthreads = []\nkeywords = ['trump', 'the_donald', 'administration', 'president', 'impeach', 'Trump', 'Impeach', 'Administration', 'The_Donald', 'The_donald', 'President', 'Mueller', 'mueller', 'investigation', 'Investigation', 'Russia', 'russia', 'Kremlin', 'kremlin']\nsubs = []\ncounter = 0\npastes = []\n\napi = {\n\t'key': 'fe41e9b514efe2d0118ceb24eb99bd35',\n\t'dev_key': 'b36153beb0b6dd9098d5de1a31cf7eff',\n\t'post': 'https://pastebin.com/api/api_post.php',\n\t'user': 's0i',\n\t'password': 'KQC-U3n-WXM-cuZ'\n}\n\ndef main():\n\tcounter = 0\n\tbot = praw.Reddit(user_agent='AutoMirrorBot v0.1',\n\t\t\t\t\tclient_id='A9R6EChehHwOFg',\n\t\t\t\t\tclient_secret='toXo534cDEp7gGioGYqdJ7tHPqE',\n\t\t\t\t\tusername='AutoMirrorBot',\n\t\t\t\t\tpassword='cnS-QgK-K9U-XSQ')\n\n\tsubreddit = bot.subreddit('Politics+WorldNews+WorldPolitics+WorldEvents+Business+USPolitics+AmericanPolitics+Libertarian+Conservative+Democrats+Socialism+Democracy')\n\n\tfor sub in subreddit.stream.submissions():\n\t\tif any(keyword in sub.title for keyword in keywords):\n\t\t\tif not any(sub.title in thread['title'] for thread in threads):\n\t\t\t\tthreads.append({'title': sub.title, 'time': time.time()})\n\t\t\t\tprint(sub.title)\n\t\t\t\tsubs.append(sub.title + '\\n')\n\t\t\t\tcounter += 1\n\t\t\t\t\n\t\t\tif counter == 10:\n\t\t\t\tpost()\n\t\t\t\tcounter = 0\n\ndef post():\n\tr = requests.post(api['post'], data={ 'api_dev_key': api['dev_key'], 'api_option': 'paste', 'api_paste_code': ''.join(subs), 'api_user_key': api['key'], 'api_paste_private': '1', 'api_paste_name': time.time() })\n\tpastes.append({'url': r.text, 'key': r.text.rsplit('/', 1)[-1]})\n\n\tprint(pastes[-1]['url'])\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"s0i/PoliticalWordMapBot","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12856786345","text":"import os\nimport sys\nimport json\n\nfrom loguru import logger\n\nCONFIG_PATH = \"config/config.json\"\n\n\ndef set_logger():\n log_format = (\n \"{time:YYYY-MM-DD HH:mm:ss.SSSSSS} | \" \"{level: ^9} | \" \"{message}\"\n )\n logger.add(sys.stderr, level=\"INFO\", format=log_format)\n logger.add(\n f\"logs/system.log\",\n rotation=\"1 day\",\n retention=\"7 days\",\n level=\"INFO\",\n encoding=\"UTF-8\",\n compression=\"gz\",\n format=log_format,\n )\n\n\ndef load_config() -> dict:\n return load_json(CONFIG_PATH)\n\n\ndef load_json(file_path):\n return json.load(open(file_path, \"r\", encoding=\"UTF-8\"))\n\n\ndef walk_dir(dir_path):\n for dirPath, _, fileList in os.walk(dir_path):\n for fileName in fileList:\n fullPath = os.path.join(dirPath, fileName)\n yield fullPath, fileName\n\n\ndef to_int(args):\n try:\n return int(args[0]), 1\n except:\n return 1, 0\n\n\ndef exchange_name(msg):\n exchange_list = [\n (\"我\", \"!@#$1$#@!\"),\n (\"my\", \"!@#$2$#@!\"),\n (\"My\", \"!@#$3$#@!\"),\n (\"MY\", \"!@#$4$#@!\"),\n (\"你\", \"我\"),\n (\"妳\", \"我\"),\n (\"您\", \"我\"),\n (\"!@#$1$#@!\", \"你\"),\n (\"!@#$2$#@!\", \"your\"),\n (\"!@#$3$#@!\", \"Your\"),\n (\"!@#$4$#@!\", \"YOUR\"),\n ]\n\n for sub, repl in exchange_list:\n msg = msg.replace(sub, repl)\n return msg\n\n\ndef get_token():\n config = load_config()\n token_key = \"token_dev\" if config[\"is_dev\"] else \"token_release\"\n return config[token_key]\n\n\ndef get_debug_guild():\n config = load_config()\n return config.get(\"debug_guild\", list())\n\n\ndef get_chatgpt_config() -> dict:\n config = load_config()\n return config[\"chatgpt\"]\n","repo_name":"penut85420/FriesMeowDiscordBot","sub_path":"fries/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"} +{"seq_id":"17276504678","text":"import csv\nimport datetime\nimport hashlib\nimport json\nimport logging\nimport os\nimport struct\nimport time\nimport uuid\nfrom concurrent.futures import ThreadPoolExecutor\nfrom dataclasses import dataclass, field, InitVar\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\nfrom urllib.parse import urlparse\n\nimport grpc\nimport numpy as np\nimport tqdm # type: ignore\nfrom grpc_status import rpc_status # type: ignore\n\nfrom .exception import ArgmentError, QMPCJobError, QMPCServerError\nfrom .proto.common_types.common_types_pb2 import JobErrorInfo, JobStatus\nfrom .proto.libc_to_manage_pb2 import (DeleteSharesRequest,\n ExecuteComputationRequest,\n GetComputationResultRequest,\n GetComputationResultResponse,\n GetDataListRequest,\n GetElapsedTimeRequest, Input, JoinOrder,\n PredictRequest, SendModelParamRequest,\n SendSharesRequest,\n GetJobErrorInfoRequest)\nfrom .proto.libc_to_manage_pb2_grpc import LibcToManageStub\nfrom .share import Share\nfrom .utils.if_present import if_present\nfrom .utils.make_pieces import MakePiece\nfrom .utils.overload_tools import Dim2, Dim3, methoddispatch\nfrom .utils.parse_csv import format_check\n\nabs_file = os.path.abspath(__file__)\nbase_dir = os.path.dirname(abs_file)\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass QMPCServer:\n endpoints: InitVar[List[str]]\n __client_stubs: Tuple[LibcToManageStub] = field(init=False)\n __party_size: int = field(init=False)\n token: str\n\n def __post_init__(self, endpoints: List[str]) -> None:\n stubs = [LibcToManageStub(QMPCServer.__create_grpc_channel(ep))\n for ep in endpoints]\n object.__setattr__(self, \"_QMPCServer__client_stubs\", stubs)\n object.__setattr__(self, \"_QMPCServer__party_size\", len(endpoints))\n\n @staticmethod\n def __create_grpc_channel(endpoint: str) -> grpc.Channel:\n channel: grpc.Channel = None\n o = urlparse(endpoint)\n if o.scheme == 'http':\n # insecureなchannelを作成\n channel = grpc.insecure_channel(o.netloc)\n elif o.scheme == 'https':\n # secureなchannelを作成\n credential: grpc.ChannelCredentials \\\n = grpc.ssl_channel_credentials()\n channel = grpc.secure_channel(o.netloc, credential)\n else:\n logger.error(f'仕様を満たさない形式のendpointが渡された: {endpoint}')\n raise ArgmentError(\n \"endpointsにサポートされてないプロトコルが指定されています.http/httpsのいずれかを指定してください.\")\n\n return channel\n\n @staticmethod\n def _argument_check(join_order: Tuple[List, List, List]):\n if len(join_order[0])-1 != len(join_order[1]):\n logger.error(\n 'the size of join must be one less than the size of dataIds')\n return False\n if len(join_order[0]) != len(join_order[2]):\n logger.error('the size of index must match the size of dataIds')\n return False\n # TODO joinをenumにする\n if not all([0 <= join <= 2 for join in join_order[1]]):\n logger.error('join value must be in the range of 0 to 2')\n return False\n return True\n\n @staticmethod\n def __futures_result(\n futures: Iterable, enable_progress_bar=True) -> Tuple[bool, List]:\n \"\"\" エラーチェックしてfutureのresultを得る \"\"\"\n is_ok: bool = True\n response: List = []\n try:\n if enable_progress_bar:\n futures = tqdm.tqdm(futures, desc='receive')\n response = [f.result() for f in futures]\n except grpc.RpcError as e:\n is_ok = False\n logger.error(f'{e.details()} ({e.code()})')\n\n # エラーが詳細な情報を持っているか確認\n status = rpc_status.from_call(e)\n if status is not None:\n for detail in status.details:\n if detail.Is(\n JobErrorInfo.DESCRIPTOR # type: ignore[attr-defined]\n ):\n # CC で Job 実行時にエラーが発生していた場合\n # 例外を rethrow する\n err_info = JobErrorInfo()\n detail.Unpack(err_info)\n logger.error(f\"job error information: {err_info}\")\n\n raise QMPCJobError(err_info) from e\n\n # MC で Internal Server Error が発生している場合\n # 例外を rethrow する\n if e.code() == grpc.StatusCode.UNKNOWN:\n raise QMPCServerError(\"backend server return error\") from e\n except Exception as e:\n is_ok = False\n logger.error(e)\n\n for b in response:\n if hasattr(b, \"is_ok\"):\n is_ok &= b.is_ok\n else:\n is_ok &= b[\"is_ok\"]\n return is_ok, response\n\n @staticmethod\n def __stream_result(stream: Iterable, job_uuid: str, party: int,\n path: Optional[str]) -> Dict:\n \"\"\" エラーチェックしてstreamのresultを得る \"\"\"\n is_ok: bool = True\n res_list = []\n for res in stream:\n is_ok &= res.is_ok\n if path is not None:\n file_title = \"dim1\"\n if res.HasField(\"is_dim2\"):\n file_title = \"dim2\"\n elif res.HasField(\"is_schema\"):\n file_title = \"schema\"\n\n file_path = f\"{path}/\" + \\\n f\"{file_title}-{job_uuid}-{party}-{res.piece_id}.csv\"\n\n with open(file_path, 'w') as f:\n writer = csv.writer(f)\n writer.writerow([res.column_number])\n writer.writerow(res.result)\n progress = res.progress if res.HasField('progress') else None\n res = GetComputationResultResponse(\n message=res.message,\n is_ok=res.is_ok,\n column_number=res.column_number,\n status=res.status,\n piece_id=res.piece_id,\n progress=progress,\n )\n res_list.append(res)\n res_dict: Dict = {\"is_ok\": is_ok, \"responses\": res_list}\n return res_dict\n\n @methoddispatch()\n def send_share(self, _):\n raise ArgmentError(\"不正な引数が与えられています.\")\n\n @send_share.register(Dim2)\n @send_share.register(Dim3)\n def __send_share_impl(self, secrets: List, schema: List[str],\n matching_column: int,\n piece_size: int) -> Dict:\n if piece_size < 1000 or piece_size > 1_000_000:\n raise RuntimeError(\n \"piece_size must be in the range of 1000 to 1000000\")\n\n if matching_column <= 0 or matching_column > len(schema):\n raise RuntimeError(\n \"matching_column must be in the \"\n \"range of 1 to the size of schema\")\n\n # TODO parse_csv経由でsend_shareをすると同じチェックをすることになる.\n if not format_check(secrets, schema):\n raise RuntimeError(\"規定されたフォーマットでないデータです.\")\n\n \"\"\" Shareをコンテナに送信 \"\"\"\n sorted_secrets = sorted(\n secrets, key=lambda row: row[matching_column - 1])\n # pieceに分けてシェア化\n pieces: list = MakePiece.make_pieces(\n sorted_secrets, int(piece_size / 10))\n data_id: str = hashlib.sha256(\n str(sorted_secrets).encode() + struct.pack('d', time.time())\n ).hexdigest()\n shares = [Share.sharize(s, self.__party_size)\n for s in tqdm.tqdm(pieces, desc='sharize')]\n sent_at = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n # リクエストパラメータを設定して非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.SendShares,\n SendSharesRequest(\n data_id=data_id,\n shares=json.dumps(s),\n schema=schema,\n piece_id=piece_id,\n sent_at=sent_at,\n matching_column=matching_column,\n token=self.token))\n for piece_id, share_piece in enumerate(shares)\n for stub, s in zip(self.__client_stubs, share_piece)\n ]\n is_ok, _ = QMPCServer.__futures_result(futures)\n return {\"is_ok\": is_ok, \"data_id\": data_id}\n\n def delete_share(self, data_ids: List[str]) -> Dict:\n \"\"\" Shareを削除 \"\"\"\n req = DeleteSharesRequest(dataIds=data_ids, token=self.token)\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.DeleteShares, req)\n for stub in self.__client_stubs]\n is_ok, _ = QMPCServer.__futures_result(futures)\n return {\"is_ok\": is_ok}\n\n def execute_computation(self, method_id: int,\n join_order: Tuple[List, List, List],\n inp: Tuple[List, List]) -> Dict:\n if not self._argument_check(join_order):\n raise ArgmentError(\"引数が正しくありません.\")\n\n \"\"\" 計算リクエストを送信 \"\"\"\n join_order_req = JoinOrder(\n dataIds=join_order[0],\n join=join_order[1],\n index=join_order[2])\n input_req = Input(\n src=inp[0],\n target=inp[1])\n req = ExecuteComputationRequest(\n method_id=method_id,\n token=self.token,\n table=join_order_req,\n arg=input_req,\n )\n\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n # JobidをMCから貰う関係で単一MC(現在はSP(ID=0)のみ対応)にリクエストを送る\n futures = [executor.submit(\n self.__client_stubs[0].ExecuteComputation, req)]\n\n is_ok, response = QMPCServer.__futures_result(futures)\n job_uuid = response[0].job_uuid if is_ok else None\n\n return {\"is_ok\": is_ok, \"job_uuid\": job_uuid}\n\n def send_model_params(self, params: list,\n piece_size: int) -> Dict:\n if piece_size < 1000 or piece_size > 1_000_000:\n raise RuntimeError(\n \"piece_size must be in the range of 1000 to 1000000\")\n\n \"\"\" モデルパラメータをコンテナに送信 \"\"\"\n # リクエストパラメータを設定\n job_uuid: str = str(uuid.uuid4())\n params_share: list = Share.sharize(params, self.__party_size)\n params_share_pieces: list = [MakePiece.make_pieces(\n p, piece_size) for p in params_share]\n\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.SendModelParam,\n SendModelParamRequest(job_uuid=job_uuid,\n params=param,\n piece_id=piece_id + 1,\n token=self.token))\n for pieces, stub in zip(params_share_pieces,\n self.__client_stubs)\n for piece_id, param in enumerate(pieces)]\n is_ok, _ = QMPCServer.__futures_result(futures)\n\n return {\"is_ok\": is_ok, \"job_uuid\": job_uuid}\n\n def predict(self,\n model_param_job_uuid: str,\n model_id: int,\n join_order: Tuple[List, List, List],\n src: List[int]) -> Dict:\n if not self._argument_check(join_order):\n raise ArgmentError(\"引数が正しくありません.\")\n\n \"\"\" モデルから予測値を取得 \"\"\"\n # リクエストパラメータを設定\n job_uuid: str = str(uuid.uuid4())\n req = PredictRequest(job_uuid=job_uuid,\n model_param_job_uuid=model_param_job_uuid,\n model_id=model_id,\n table=JoinOrder(dataIds=join_order[0],\n join=join_order[1],\n index=join_order[2]),\n src=src,\n token=self.token)\n\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.Predict, req)\n for stub in self.__client_stubs]\n is_ok, response = QMPCServer.__futures_result(futures)\n\n return {\"is_ok\": is_ok, \"job_uuid\": job_uuid}\n\n def get_data_list(self) -> Dict:\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.GetDataList,\n GetDataListRequest(token=self.token))\n for stub in self.__client_stubs]\n is_ok, response = QMPCServer.__futures_result(futures)\n results = [eval(r.result) for r in response] if is_ok else None\n\n return {\"is_ok\": is_ok, \"results\": results}\n\n def get_elapsed_time(self, job_uuid: str) -> Dict:\n # リクエストパラメータを設定\n req = GetElapsedTimeRequest(\n job_uuid=job_uuid,\n token=self.token\n )\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.GetElapsedTime,\n req)\n for stub in self.__client_stubs]\n is_ok, response = QMPCServer.__futures_result(futures)\n elapsed_time = max([res.elapsed_time\n for res in response]) if is_ok else None\n return {\"is_ok\": is_ok, \"elapsed_time\": elapsed_time}\n\n def get_computation_result(self, job_uuid: str,\n path: Optional[str]) -> Dict:\n \"\"\" コンテナから結果を取得 \"\"\"\n # リクエストパラメータを設定\n req = GetComputationResultRequest(\n job_uuid=job_uuid,\n token=self.token\n )\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(QMPCServer.__stream_result,\n stub.GetComputationResult(req),\n job_uuid, party, path)\n for party, stub in enumerate(self.__client_stubs)]\n is_ok, response = QMPCServer.__futures_result(\n futures, enable_progress_bar=False)\n results_sorted = [sorted(res[\"responses\"], key=lambda r: r.piece_id)\n for res in response]\n # NOTE: statusは0番目(piece_id=1)の要素にのみ含まれている\n statuses = [res[0].status for res in results_sorted] \\\n if results_sorted else None\n all_completed = all([\n s == JobStatus.Value('COMPLETED') for s in statuses\n ]) if statuses is not None else False\n\n progresses = None\n if results_sorted is not None:\n progresses = [\n res[0].progress if res[0].HasField(\"progress\") else None\n for res in results_sorted\n ]\n\n results: Optional[Any] = None\n if not path and all_completed:\n for res in results_sorted:\n is_table = False\n is_dim2 = False\n column_number = 0\n result: Any = []\n schema = []\n for r in res:\n if r.HasField(\"is_schema\"):\n if not is_table:\n is_table = True\n for val in r.result:\n schema.append(val)\n else:\n if r.HasField(\"is_dim2\"):\n is_dim2 = True\n for val in r.result:\n result.append(val)\n\n column_number = r.column_number\n\n if is_dim2:\n result = np.array(result).reshape(-1,\n column_number).tolist()\n result = {\"schema\": schema, \"table\": result} if is_table \\\n else result\n if results is None:\n results = []\n results.append(result)\n\n results = if_present(results, Share.recons)\n return {\"is_ok\": is_ok, \"statuses\": statuses,\n \"results\": results, \"progresses\": progresses}\n\n def get_job_error_info(self, job_uuid: str) -> Dict:\n # リクエストパラメータを設定\n req = GetJobErrorInfoRequest(\n job_uuid=job_uuid,\n token=self.token\n )\n # 非同期にリクエスト送信\n executor = ThreadPoolExecutor()\n futures = [executor.submit(stub.GetJobErrorInfo, req)\n for stub in self.__client_stubs]\n is_ok, response = QMPCServer.__futures_result(\n futures, enable_progress_bar=False)\n\n job_error_info = [\n res.job_error_info if res.HasField(\"job_error_info\") else None\n for res in response\n ]\n\n return {\"is_ok\": is_ok, \"job_error_info\": job_error_info}\n","repo_name":"acompany-develop/QuickMPC-libClient-py","sub_path":"quickmpc/qmpc_server.py","file_name":"qmpc_server.py","file_ext":"py","file_size_in_byte":18049,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"6957099782","text":"\"\"\"\r\nRealizado por: Lorena Perez - 20200396 :D\r\n\r\n\"\"\"\r\n# Librerias necesarias\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport cv2 as cv\r\nimport argparse\r\nimport sys\r\nimport os\r\n\r\nfrom time import time\r\n\r\n# Modulos propios, se agregan las funciones utilizadas al script\r\n# import cvlib\r\n# import plot\r\n\r\n# ------------------------------------------------\r\n# NOTA: Linea de codigo a introducir desde consola: \r\n\r\n\"\"\"\r\npython laboratorio_1.py fprint3.pgm fprint_ccl.png\r\n\r\n\"\"\"\r\n# ------------------------------------------------\r\n\r\n\r\n# Preparacion - Carga de funciones del modulo utilizado para este script.\r\n# Funcion recopilada del modulo utilizado\r\ndef imgcdf(img):\r\n \"\"\"Compute the CDF on an image\r\n Parameters: \r\n img (numpy array): Source image\r\n Returns:\r\n cdf (list): Computed CDf of img\r\n hist (list): Histogram of img\r\n \"\"\"\r\n hist_list = cv.calcHist([img],[0],None,[256],[0,256])\r\n hist = hist_list.ravel()\r\n\r\n cdf = []\r\n t = 0\r\n for p in hist:\r\n t += p\r\n cdf.append(t)\r\n return cdf, hist\r\n\r\ndef imgeq(img):\r\n \"\"\" Equalize a grayscale image\r\n Parameters:\r\n img (numpy array): Grayscale image to equalize\r\n Returns:\r\n eq (numpy array): Equalized image\r\n \"\"\"\r\n cdf = imgcdf(img)[0]\r\n cdf_eq = []\r\n n = img.shape[0] * img.shape[1]\r\n m = min(i for i in cdf if i > 0)\r\n\r\n for i in cdf:\r\n if i >= m:\r\n cdf_eq.append(int(round(255*(i-m)/(n-m))))\r\n else:\r\n cdf_eq.append(0)\r\n eq = cv.LUT(img, np.array(cdf_eq).astype(np.uint8))\r\n return eq\r\n\r\n# Funcion recopilada del modulo utilizado\r\ndef imgview(img, title=None, filename=None, axis=False, figsize=None):\r\n \"\"\"\r\n imgview: funcion de visualizacion de imagen\r\n\r\n Parameters:\r\n img: matriz de la imagen a visualizar\r\n title: asignacion de titulo, por default no se coloca titulo\r\n filename: opcion para guardar la imagen, por default no se realiza la accion\r\n axis: visualizacion de los ejes, por default no se muestran\r\n \"\"\"\r\n r,c = img.shape[0:2]\r\n if figsize != None:\r\n fig = plt.figure(figsize=figsize)\r\n else:\r\n k = 8\r\n fig = plt.figure(figsize=(k,k))\r\n ax = fig.add_subplot(111)\r\n \r\n if len(img.shape) == 3:\r\n img = ax.imshow(img,extent=None)\r\n else:\r\n img = ax.imshow(img,extent=None,cmap='gray',vmin=0,vmax=255)\r\n if title != None:\r\n ax.set_title(title,fontsize=14)\r\n if not axis:\r\n plt.axis('off')\r\n else:\r\n ax.grid(c='w')\r\n ax.xaxis.tick_top()\r\n ax.xaxis.set_label_position('top') \r\n ax.set_xlabel('Columns',fontsize=14)\r\n ax.set_ylabel('Rows',fontsize=14)\r\n ax.xaxis.label.set_color('w')\r\n ax.yaxis.label.set_color('w')\r\n ax.tick_params(axis='x', colors='w',labelsize=14)\r\n ax.tick_params(axis='y', colors='w',labelsize=14)\r\n \r\n if filename != None:\r\n plt.savefig(filename)\r\n plt.show()\r\n\r\n# ------------------------------------------------\r\n# Parte 1 - Funciones solicitadas\r\n\r\n# imgpad: funcion de paddin de ceros.\r\n# first_pass: primer recorrido de la imagen binaria para asignar la etiqueta.\r\n# second_pass: segundo recorrido para la asignacion de la etiqueta, componente conectado.\r\n# connected_c: funcion que utiliza otras funciones con el fin de etiquetar los componenetes conectados de una imagen binarizada\r\n# labelview: imagen resultante con los labels diferenciados por color.\r\n\r\ndef imgpad(img, r):\r\n \"\"\"\r\n Realiza un padding de ceros de r pixeles alrededor de una imagen binaria.\r\n Esta funcion toma una imagen (matriz) y agrega un marco de ceros alrededor\r\n de la misma. El ancho del borde esta definido por el valor 'r'.\r\n\r\n Parameters:\r\n img (np.uint8): Matriz que representa la imagen binaria.\r\n r (int): Tamaño del borde de ceros que se agregara alrededor de la imagen.\r\n\r\n Returns:\r\n matriz (np.uint8): La imagen de entrada con un borde de ceros agregado alrededor.\r\n\r\n \"\"\"\r\n\r\n # Agregando los marcos extremos de las filas\r\n matriz_row = np.zeros((r, img.shape[1])) \r\n matriz = np.concatenate((matriz_row, img), axis = 0)\r\n matriz = np.concatenate((matriz, matriz_row), axis = 0)\r\n\r\n # Agregando los marcos extremos de las columnas\r\n matriz_col = np.zeros((matriz.shape[0], r))\r\n matriz = np.concatenate((matriz_col, matriz), axis = 1)\r\n matriz = np.concatenate((matriz, matriz_col), axis = 1)\r\n return matriz\r\n\r\ndef first_pass(img):\r\n \"\"\"\r\n Itera por cada elemento por columna para etiquetar los componentes conectados en una imagen binaria.\r\n\r\n Esta funcion toma una imagen binaria y realiza un primer recorrido para etiquetar\r\n componentes conectados. Devuelve una matriz de etiquetas y una lista de vecinos\r\n conectados.\r\n\r\n Parameters:\r\n img (np.uint8): Matriz que representa la imagen binaria.\r\n\r\n Returns:\r\n - etiq_array (np.uint8): Una matriz de etiquetas donde se etiquetan los componentes conectados.\r\n - vec_array (List): Una lista de pares de vecinos conectados.\r\n\r\n \"\"\"\r\n\r\n init_img = imgpad(img, 1)\r\n r, c = init_img.shape\r\n # Inicializacion de la etiqueta\r\n etiqueta = 1\r\n\r\n etiq_array = np.zeros((r, c), dtype=int)\r\n vec_array = []\r\n\r\n for i in range(1, r - 1):\r\n for j in range(1, c - 1):\r\n if init_img[i][j] != 0:\r\n vecinos = [etiq_array[i - 1][j], etiq_array[i][j - 1]]\r\n if vecinos[0] != 0:\r\n etiq_array[i][j] = vecinos[0]\r\n if vecinos[1] != 0 and vecinos[0] != vecinos[1]:\r\n vec_array.append(vecinos)\r\n elif vecinos[1] != 0:\r\n etiq_array[i][j] = vecinos[1]\r\n else:\r\n etiq_array[i][j] = etiqueta\r\n etiqueta += 1\r\n \r\n return etiq_array, vec_array\r\n\r\ndef labels_result(labels_vec):\r\n \"\"\"\r\n Elimina duplicados de una lista de tuplas.\r\n\r\n Esta funcion toma una lista de tuplas y elimina cualquier tupla duplicada,\r\n manteniendo el orden original de las tuplas.\r\n\r\n Parameters:\r\n labels_vec (list): Lista de tuplas de entrada.\r\n\r\n Returns:\r\n unique_labels_vec (list): Una lista que contiene las tuplas unicas, sin duplicados.\r\n\r\n \"\"\"\r\n unique_labels_vec = list({tuple(item) for item in labels_vec})\r\n return unique_labels_vec\r\n\r\ndef replace_vec(labels_vec, numero):\r\n \"\"\"\r\n Reemplaza etiquetas en un conjunto de etiquetas vecinas.\r\n\r\n Parameters:\r\n labels_vec (list): Lista de pares de etiquetas conectadas.\r\n numero (int): Etiqueta inicial a reemplazar.\r\n\r\n Returns:\r\n int: Etiqueta minima del componenete conectado resultante.\r\n \"\"\"\r\n labels_set = {}\r\n for a, b in labels_vec:\r\n if a in labels_set:\r\n labels_set[a].append(b)\r\n else:\r\n labels_set[a] = [b]\r\n if b in labels_set:\r\n labels_set[b].append(a)\r\n else:\r\n labels_set[b] = [a]\r\n\r\n visitados = set()\r\n labels_c = [numero]\r\n min_label = numero \r\n\r\n while labels_c:\r\n actual = labels_c.pop(0)\r\n visitados.add(actual)\r\n labels_c.extend(label for label in labels_set.get(actual, []) if label not in visitados)\r\n min_label = min(min_label, actual) \r\n \r\n if len(visitados) > 1: \r\n for label in visitados:\r\n labels_set[label] = [min_label]\r\n\r\n return min_label\r\n\r\ndef second_pass(labels_img, labels_vec):\r\n \"\"\"\r\n Realiza el segundo recorrido del algoritmo de etiquetado, reemplazando etiquetas en la imagen.\r\n\r\n Parameters:\r\n labels_img (np.uint8): Matriz de etiquetas de la imagen.\r\n labels_vec (list): Lista de pares de etiquetas conectadas.\r\n\r\n Returns:\r\n labels_img (np.unit8): Matriz de etiquetas de la imagen con etiquetas reemplazadas.\r\n \"\"\"\r\n r, c = labels_img.shape\r\n replace_dict = {}\r\n progreso = 0\r\n\r\n for i in range(r):\r\n for j in range(c):\r\n if labels_img[i][j] != 0:\r\n if labels_img[i][j] in replace_dict:\r\n labels_img[i][j] = replace_dict[labels_img[i][j]]\r\n else:\r\n replace_etiq = replace_vec(labels_vec, labels_img[i][j])\r\n if replace_etiq is not None:\r\n labels_img[i][j] = replace_etiq\r\n replace_dict[labels_img[i][j]] = replace_etiq\r\n progreso += 1\r\n porcentaje = (progreso / (r * c)) * 100\r\n if porcentaje % 10 == 0:\r\n print(f\"\\t: {porcentaje:.0f}%\") # Solo para fines de visualizacion del proceso\r\n return labels_img\r\n\r\ndef connected_c(img):\r\n \"\"\"\r\n Realiza la segmentacion de componentes conectados en una imagen.\r\n\r\n Parameters:\r\n img (np.uint8): Imagen de entrada.\r\n\r\n Returns:\r\n result_img (np.uint8): Imagen segmentada con etiquetas de componentes conectados.\r\n \"\"\"\r\n labels_img, labels_vec = first_pass(img)\r\n labels_vec = labels_result(labels_vec)\r\n result_img = second_pass(labels_img, labels_vec)\r\n return result_img\r\n\r\ndef random_color():\r\n \"\"\"\r\n Genera un color aleatorio.\r\n\r\n Returns:\r\n Tuple: Una tupla (R, G, B) que representa un color RGB aleatorio.\r\n \"\"\"\r\n return (np.random.randint(50, 256), np.random.randint(50, 256), np.random.randint(50, 256))\r\n\r\ndef labelview(labels, name_save=None):\r\n \"\"\"\r\n Muestra una imagen etiquetada con colores aleatorios para cada componente conectado.\r\n\r\n Parameters:\r\n imagen (np.uint8): Imagen original.\r\n labels (np.uint8): Matriz de etiquetas de componentes conectado.\r\n name_save (str): Nombre de la imagen para guardar.\r\n\r\n Returns:\r\n Muestra la imagen y la guarda con el name_save en el directorio actual.\r\n \"\"\"\r\n unique_labels = np.unique(labels)\r\n colored_image = np.zeros((labels.shape[0], labels.shape[1], 3), dtype=np.uint8)\r\n\r\n for label in unique_labels:\r\n if label == 0:\r\n continue\r\n mask = (labels == label)\r\n color = random_color()\r\n colored_image[mask] = color\r\n\r\n imgview(colored_image, \"Output\", filename=name_save)\r\n\r\n# ------------------------------------------------\r\n# Codigo de prueba para imagenes random de testing\r\n\r\n# array = np.random.randint(2, size=(220, 220))\r\n# array = array.astype(np.uint8)\r\n# result = connected_c(array)\r\n# labelview(result)\r\n\r\n# ultimo time de prueba para este test\r\n# time 1m.36s\r\n# time 44s\r\n\r\n# ------------------------------------------------\r\n# Lectura de los datos desde la consola:\r\n\r\nparser = argparse.ArgumentParser(description=\"Lee una imagen y guarda una copia.\")\r\nparser.add_argument(\"name_image\", help=\"Nombre del archivo de entrada (imagen)\")\r\nparser.add_argument(\"name_save\", help=\"Nombre del archivo de salida (imagen)\")\r\nargs = parser.parse_args()\r\n\r\n# Asumiendo que la imagen esta en el directorio en el que estamos, \r\n# se tomara el path del directorio actual para encontrar la imagen\r\nPATH = os.path.dirname(os.path.abspath(sys.argv[0]))\r\nPATH = PATH.replace(\"\\\\\", \"/\")\r\n\r\nname_image = args.name_image\r\nname_save = args.name_save\r\n\r\nprint(f\"\\nArchivo de entrada: {name_image}\")\r\nprint(f\"Archivo de salida: {name_save}\\n\")\r\n\r\n# ------------------------------------------------\r\n# Parte 2 - Procesamiento de la imagen. \r\n\"\"\" \r\nParameters:\r\n name_image: Nombre de la imagen de lectura para el procesamiento.\r\n imgray (np.uint8): Lectura de la imagen a procesar. Aplica la lectura de la imagen en escala de grises.\r\n img_eq (np.unit8): Realiza una ecualizacion de histograma en la imagen para mejorar su contraste.\r\n\"\"\"\r\n\r\n# Nombre del archivo que se busca: 'fprint3.pgm'\r\n# imgray = cv.imread(PATH+'/'+ 'fprint3.pgm', cv.IMREAD_GRAYSCALE) # Lectura original del archivo\r\nimgray = cv.imread(PATH+'/'+name_image, cv.IMREAD_GRAYSCALE)\r\nimg_eq = imgeq(imgray)\r\n\r\n# Aplica un umbral en la imagen para obtener una imagen binarizada con el valor\r\n# de umbral de 115, utilizando el metodo de truncamiento (THRESH_TRUNC) con el fin de eliminar\r\n# el ruido del fondo de la imagen.\r\n_, imgray = cv.threshold(img_eq, 115, 255,cv.THRESH_TRUNC)\r\n\r\n\r\n\"\"\"\r\nAplica la operacion de relleno (flood fill) en una imagen en escala de grises.\r\n\"\"\"\r\n\r\nD = 35 # Umbral de diferencia de intensidad de color.\r\nimgray_f = imgray.copy()\r\ncv.floodFill(imgray_f, None, (1,10), 140, loDiff=D, upDiff=D, flags=cv.FLOODFILL_FIXED_RANGE)\r\nimgray = imgray_f\r\n\r\n\r\n\"\"\"\r\nAplica una serie de operaciones de procesamiento de imagenes para obtener contornos.\r\n\r\nParameters:\r\n - k (int): Tamaño del kernel para el blur.\r\n - img_blur (np.uint8): Imagen suavizada despues de aplicar el filtro.\r\n - imgbin (np.uint8): Imagen binarizada resultante de la umbralizacion adaptativa.\r\n - contours (list): Lista de contornos detectados en la imagen.\r\n - hierarchy (numpy.ndarray): Jerarquia de contornos.\r\n\"\"\"\r\n\r\nk = 5\r\nimg_blur = cv.GaussianBlur(imgray,(k,k),3)\r\ncv.normalize(img_blur, img_blur, 30, 110, cv.NORM_MINMAX)\r\nimgbin = cv.adaptiveThreshold(img_blur, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY_INV, 13,3)\r\nmode = cv.RETR_TREE\r\nmethod = [cv.CHAIN_APPROX_NONE, cv.CHAIN_APPROX_SIMPLE]\r\ncontours, hierarchy = cv.findContours(imgbin, mode, method[1])\r\n\r\n\r\n\"\"\"\r\nAplica una serie de operaciones para filtrar y refinar contornos en una imagen binarizada.\r\n\r\nParameters:\r\n - area_min (int): Area minima para mantener un contorno.\r\n - mask (np.uint8): Mascara de contornos filtrados.\r\n - area_maxima (int): Area maxima para refinar los contornos.\r\n - result_img (np.uint8): Imagen resultante despues de refinar los contornos\r\n y aplicar todos los cambios.\r\n\"\"\"\r\n\r\narea_min = 10\r\nmask = np.zeros_like(imgbin)\r\n\r\nfor contour in contours:\r\n if cv.contourArea(contour) == 8 or cv.contourArea(contour) > area_min:\r\n cv.drawContours(mask, [contour], -1, 255, thickness=cv.FILLED)\r\n\r\nresult_img = cv.bitwise_and(imgbin, mask)\r\ncontornos, _ = cv.findContours(result_img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\r\npercent = 0.01\r\narea_maxima = 340\r\n\r\nfor cnt in contornos:\r\n area = cv.contourArea(cnt)\r\n if area <= area_maxima:\r\n epsilon = percent * cv.arcLength(cnt, True)\r\n approx = cv.approxPolyDP(cnt, epsilon, True)\r\n cv.fillPoly(result_img, [approx], 255)\r\n\r\n# ------------------------------------------------\r\n# Parte final - Ejecucion del connected_c para la imagen recibida desde consola.\r\n\r\n\"\"\"\r\nEncuentro los componentes conectados de una imagen tratada. Utiliza la variante two-pass del\r\nalgoritmo Connected Componet labeling (CCL).\r\n\r\nParameters:\r\n - name_save (str): Nombre de la salida de la imagen a guardar.\r\n - result (np.uint8): Resultado de la imagen al procesarla con la funcion connected_c.\r\n\r\n\r\nReturn:\r\n - labelview(result, name_save): Devuelve la imagen con los colores de cada etiqueta.\r\n\"\"\"\r\n\r\n# Measure exec time\r\nstart_time = time()\r\nresult = connected_c(result_img)\r\nprint('\\n -----------------------------')\r\nprint(f'Executed in {(time()- start_time)/60:.2f} min. \\n') # Con el fin de ver cuanto tiempo se tarda.\r\nlabelview(result, name_save)\r\n\r\n# Tiempo promedio 5 minutos\r\n\r\n# ------------------------------------------------\r\n# NOTA: Linea de codigo a introducir desde consola: \r\n\r\n\"\"\"\r\npython laboratorio_1.py fprint3.pgm fprint_ccl.png\r\n\r\n\"\"\"\r\n\r\n# ------------------------------------------------ FIN :D","repo_name":"Lorena20U/Cv-2023","sub_path":"laboratorio_1/laboratorio_1.py","file_name":"laboratorio_1.py","file_ext":"py","file_size_in_byte":15504,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37300733046","text":"#definindo dados das armas\nchifre = 2\ncajado = 4\nespada = 6\ngrande_espada = 8\ndardo = 12\n\n#definindo valores das proteções\narmadura_pesada = 0 \narmadura_media = 1 \narmadura_leve = 3\n\n# dicionário do grupo com suas armas e armaduras\ngrupo = {'Bobby': [grande_espada , armadura_media],\n 'Diana': [dardo , armadura_leve],\n 'Eric': [grande_espada , armadura_pesada],\n 'Hank': [espada , armadura_media],\n 'Presto': [cajado , armadura_leve],\n 'Sheila': [espada , armadura_leve],\n 'Uni': [chifre , armadura_leve]}\n \n\n#pontos de vida adversario\ndic_adv = {'Vingador': 30,\n 'Tiamat': 20,\n 'Vingador das Sombras': 14}\n\n#iniciando a batalha\n\nadversario = input()\nif adversario not in ['Vingador', 'Tiamat', 'Vingador das Sombras']:\n vida_adv = 9\nelse:\n vida_adv = dic_adv[adversario]\n \n \nturnos = int(input())\n\nwhile (int(turnos) > 0) or (int(vida_adv) > 0):\n try:\n personagem = input()\n if personagem == 'Mestre dos Magos':\n vida_adv = 0\n else:\n vida_adv = vida_adv - grupo[personagem][0]\n turnos = turnos - grupo[personagem][1]\n except:\n break\n\n#prints\nif personagem == 'Mestre dos Magos':\n print('Muito obrigado amigo, que nos vejamos novamente um dia')\nelif vida_adv <= 0:\n print(f'{personagem} executou o ultimo golpe em {adversario}, estamos livres!')\nelif vida_adv > 0:\n print(f'Oh nao, {adversario} e muito forte, este e o fim!')\n \n \n\n\n ","repo_name":"bielarnaud/Listas_de_exercicios_p1","sub_path":"Dic e tuplas/ex 3.py","file_name":"ex 3.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70678688484","text":"from django.conf import settings\n\"\"\"\nRequest Limit for Scraping, pauses for one second\nevery time limit is reached\n\"\"\"\nREQUEST_LIMIT = 10\n\n\"\"\"\nURL endpoint for Lebanon Commercial Registry\n\"\"\"\nCOMMERCIAL_REGISTRY_URL = 'http://cr.justice.gov.lb/search/result.aspx?id='\n\n\"\"\"\nHow many records to scrape for each governorate\nNOTE:\nThese are estimated original values based on manual searching.\nIn other words, these were about the highest ids I could find on the LCR website for each\ngovernment, and I assume that there aren't more ids higher than them as of 17-12-2020\n\"\"\"\nGOVERNORATE_SCRAPE_LIMIT = {\n 1: int(settings.BEIRUT_SCRAPE_LIMIT),\n 2: int(settings.MOUNT_LEBANON_SCRAPE_LIMIT),\n 3: int(settings.NORTH_LEBANON_SCRAPE_LIMIT),\n 4: int(settings.BEKAA_SCRAPE_LIMIT),\n 5: int(settings.SOUTH_LEBANON_SCRAPE_LIMIT),\n 6: int(settings.NABATIEH_SCRAPE_LIMIT),\n}\n","repo_name":"lspdrz/lcr-api","sub_path":"api/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25156582700","text":"import unittest\n\nfrom args import *\n\nclass ArgsTest(unittest.TestCase):\n def test_NoArgsNotValid(self):\n args = Args({})\n self.failIf(args.is_valid())\n def test_NoArgsIsEmpty(self):\n args = Args({})\n args.parse([])\n self.failUnless(args.is_valid())\n def test_boolean(self):\n args = Args({\"l\" : bool})\n args.parse([\"-l\"])\n self.failUnless(args.is_valid())\n self.failUnlessEqual(True, args[\"l\"])\n def test_not_matching_schema(self):\n args = Args({})\n try:\n args.parse([\"-l\"])\n self.fail(\"should have thrown bad args exception\")\n except BadArgsException:\n self.failUnlessEqual(False, args.is_valid())\n def test_integer(self):\n args = Args({\"p\" : int})\n args.parse([\"-p\", \"8080\"])\n self.failUnless(args.is_valid())\n self.failUnlessEqual(8080, args[\"p\"])\n def test_missing_boolean(self):\n args = Args({\"l\" : bool})\n args.parse([])\n self.failUnless(args.is_valid())\n self.failUnlessEqual(False, args[\"l\"])\n \n def test_string(self):\n args = Args({\"d\" : str})\n args.parse([\"-d\", \"/usr/stuff\"])\n self.failUnless(args.is_valid())\n self.failUnlessEqual(\"/usr/stuff\", args[\"d\"])\n \n def test_wrong_type(self):\n args = Args({\"d\" : int})\n try:\n args.parse([\"-d\", \"/usr/stuff\"])\n self.fail(\"should have thrown bad args exception\")\n except BadArgsException:\n self.failUnlessEqual(False, args.is_valid())\n def test_str_array(self):\n args = Args({\"a\" : list})\n args.parse([\"-a\", \"one\", \"thing\", \"at\", \"a\", \"time\"])\n self.failUnlessEqual([\"one\", \"thing\", \"at\", \"a\", \"time\"], args[\"a\"])\n \n def test_int_array(self):\n args = Args({\"a\" : int_list})\n args.parse([\"-a\", \"1\", \"2\", \"3\"])\n self.failUnlessEqual([1, 2, 3], args[\"a\"])\nunittest.main()","repo_name":"emilybache/gothpy-katas","sub_path":"20090112/argsTest.py","file_name":"argsTest.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"32976843101","text":"from flask import Blueprint, request\nfrom app.models import follows, User, db\nfrom app.forms import FollowForm\n\n\nfollow_routes = Blueprint(\"follow\", __name__)\n\n\n@follow_routes.route('//follows', methods=[\"GET\"])\ndef user_follows(id):\n following = db.session.query(follows).filter_by(follower_id=id).all()\n followingIds = [y for x,y in following]\n users = User.query.filter(User.id.in_(followingIds)).all()\n return {\"follows\":[user.to_dict() for user in users]}\n\n\n@follow_routes.route('//followedBy', methods=[\"GET\"])\ndef user_followed_by(id):\n followed = db.session.query(follows).filter_by(followed_id=id).all()\n followedIds = [x for x,y in followed]\n users = User.query.filter(User.id.in_(followedIds)).all()\n return {\"followed\":[user.to_dict() for user in users]}\n\n\n@follow_routes.route('//follows', methods=['POST'])\ndef follow_user(followedId):\n followed_user = User.query.filter(User.id == followedId).first()\n form = FollowForm()\n\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n session_user_id = form.data['follower_id']\n session_user = User.query.filter(User.id == session_user_id).first()\n\n # format is: follower.followers.append(followed)\n session_user.followers.append(followed_user)\n db.session.commit()\n return {\"follows\":[user.to_dict() for user in followed_user.follows]}\n return {'errors': form.errors}\n\n\n\n@follow_routes.route('//follows', methods=['DELETE'])\ndef unfollow_user(followedId):\n followed_user = User.query.filter(User.id == followedId).first()\n form = FollowForm()\n form['csrf_token'].data = request.cookies['csrf_token']\n if form.validate_on_submit():\n session_user_id = form.data['follower_id']\n session_user = User.query.filter(User.id == session_user_id).first()\n session_user.followers.remove(followed_user)\n db.session.commit()\n return {\"follows\":[user.to_dict() for user in followed_user.follows]} # check what is returning\n return {'errors': form.errors}\n","repo_name":"KevKodes/InstaLock","sub_path":"app/api/follow_routes.py","file_name":"follow_routes.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"24335860920","text":"from core.models import User\nfrom django.core.management import call_command\nfrom django.test import Client, TestCase\n\n\nclass CreateFakeUsersTest(TestCase):\n def test_command(self):\n call_command('create_fake_users', 10)\n user_count = User.objects.count()\n self.assertEqual(user_count, 10)\n\n\nclass GeneralTest(TestCase):\n \"\"\"\n A really minimal set of smoketests to make sure\n things at least look OK on the surface.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n # Note: we could use a fixture or decouple the\n # actual generator from the django command\n # (and/or both, actually) but this'll do for now.\n call_command('create_fake_users', 10)\n\n def test_index(self):\n client = Client()\n response = client.get('/')\n self.assertEqual(response.status_code, 302)\n\n def test_shorten(self):\n TEST_URL = 'https://google.com/robots.txt'\n client = Client()\n response = client.post('/shorten', {\n 'url': TEST_URL\n })\n self.assertEqual(response.status_code, 200)\n self.assertTrue(TEST_URL in response.content.decode('utf-8'))\n\n @classmethod\n def tearDownClass(cls):\n # Important! Don't remove this and leave the\n # setUpClass method alone; this causes errors about\n # this class not having a 'cls_atomics' attribute.\n pass\n","repo_name":"maligree/shorty","sub_path":"shorty/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"45292314078","text":"import os\nfrom pickle import FALSE\nimport shutil\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nimport environ\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\nload_dotenv()\nSECRET_KEY = os.environ[\"SECRET_KEY\"]\n\n# SECURITY WARNING: don't run with debug turned on in production!\n\nDEBUG = False\n\nALLOWED_HOSTS = [\"*\"]\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'jazzmin',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'website',\n 'departments',\n 'aboutCCE',\n 'administration',\n 'studentservices',\n 'placements',\n 'storages',\n 'tailwind',\n 'cce_web_theme'\n\n]\n\n\nMIDDLEWARE = [\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n \"django.middleware.security.SecurityMiddleware\",\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n\n]\n\n\n# Development Settings\n\nif os.getenv('PRODUCTION') != 'True':\n MIDDLEWARE.append(\"django_browser_reload.middleware.BrowserReloadMiddleware\")\n INSTALLED_APPS.append(\"django_browser_reload\")\n DEBUG = True\n\n\nROOT_URLCONF = 'cce.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n\n 'DIRS': [os.path.join(BASE_DIR, \"templates\")],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.template.context_processors.media',\n ],\n },\n \n },\n]\n\nWSGI_APPLICATION = 'cce.wsgi.application'\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': os.getenv('DB_NAME'),\n 'USER': os.getenv('DB_USERNAME'),\n 'PASSWORD': os.getenv('DB_PASSWORD'),\n 'HOST': os.getenv('DB_HOST'),\n 'PORT': os.getenv('DB_PORT')\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/4.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/4.0/howto/static-files/\n\nSTATIC_URL = 'static/'\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\n\n# Added by manually\n# custom settings\nif os.getenv('PRODUCTION') != 'True':\n STATICFILES_DIRS = [\n os.path.join(BASE_DIR, \"static\"),\n ]\n\nelse:\n STATIC_ROOT = os.path.join(BASE_DIR, 'static')\nINTERNAL_IPS = [\n \"127.0.0.1\",\n]\n\n\n# AWS_S3_URL_PROTOCOL='http:'\nAWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')\nAWS_STORAGE_BUCKET_NAME = 'www.assets.cce.edu.in'\nAWS_S3_CUSTOM_DOMAIN = \"dnbca6q7do6n.cloudfront.net\"\n# PUBLIC_MEDIA_LOCATION = 'media'\n# MEDIA_URL = 'http://' + AWS_S3_CUSTOM_DOMAIN + '/' + PUBLIC_MEDIA_LOCATION + '/'\nDEFAULT_FILE_STORAGE = 'cce.storage_backends.MediaStorage'\n\nMEDIA_URL = 'https://dnbca6q7do6n.cloudfront.net/media/'\n\n\n\n\nTAILWIND_APP_NAME = 'cce_web_theme'\n# Jazzmin settings\n\n\nJAZZMIN_UI_TWEAKS = {\n \"theme\": \"cerulean\",\n \"dark_mode_theme\": \"cerulean\",\n}\n\n\nJAZZMIN_SETTINGS = {\n # title of the window (Will default to current_admin_site.site_title if absent or None)\n \"site_title\": \"CCE Admin\",\n\n # Title on the login screen (19 chars max) (defaults to current_admin_site.site_header if absent or None)\n \"site_header\": \"CCE\",\n\n # Title on the brand (19 chars max) (defaults to current_admin_site.site_header if absent or None)\n \"site_brand\": \"CCE\",\n\n # # Logo to use for your site, must be present in static files, used for brand on top left\n \"site_logo\": \"favicons/favicon-32x32.png\",\n \"site_logo_small\": \"favicons/favicon-32x32.png\",\n\n \"site_favicon\": \"favicons/favicon.ico\",\n \"login_logo\": \"favicons/android-chrome-192x192.png\",\n\n\n # # CSS classes that are applied to the logo above\n \"site_logo_classes\": \"img-circle\",\n\n # # Relative path to a favicon for your site, will default to site_logo if absent (ideally 32x32 px)\n # \"site_icon\": None,\n\n # # Welcome text on the login screen\n \"welcome_sign\": \"Welcome Administration Page of CCE Web\",\n\n # # Copyright on the footer\n \"copyright\": \" Christ College Of Engineering & Technology\",\n\n\n\n # # Links to put along the top menu\n \"topmenu_links\": [\n\n # Url that gets reversed (Permissions can be added)\n {\"name\": \"Home\", \"url\": \"admin:index\",\n \"permissions\": [\"auth.view_user\"]},\n\n # App with dropdown menu to all its models pages (Permissions checked against models)\n {\"Main Website\": \"website\"},\n {\"Departments\": \"departments\"},\n ],\n\n \"related_modal_active\": True,\n}\n\n\n","repo_name":"cce-websitecoordinator/cce-website","sub_path":"cce/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5915,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"1548112342","text":"from tkinter import *\nfrom PIL import ImageTk, Image\nimport os\n\nroot = Tk()\n\ndir_label = Label(root, text='Enter Directory : ')\ndir_label.grid(row=0, column=0)\n\ndir_entry = Entry(root, width=40, borderwidth=6)\ndir_entry.grid(row=0, column=1)\n\ndef get_image_list(direc):\n files = os.listdir(direc)\n return files\n\n\nglobal image_list\nimage_list = []\ndef Enter():\n global image_list\n global label\n global button_back\n global button_for\n d = dir_entry.get()\n image_list = get_image_list(d)\n i = 0\n while i < len(image_list):\n if '.png' not in image_list[i] and '.jpg' not in image_list[i]:\n image_list.pop(i)\n else:\n image_list[i] = ImageTk.PhotoImage(Image.open(d + '\\\\' + image_list[i]))\n i += 1\n\n\n # label = None\n label = Label(image=image_list[0])\n label.grid(row=2, column=0, columnspan=3)\n\n status = Label(root, text=\"Image 1 of \" + str(len(image_list)), bd=1, relief=SUNKEN, anchor=E)\n status.grid(row=4, column=0, columnspan=3, sticky=W + E)\n \n def forward(image_number):\n global label\n global button_for\n global button_back \n # print(label)\n print(label)\n label.grid_forget()\n label = Label(image=image_list[image_number])\n label.grid(row=2, column=0, columnspan=3)\n # print(label)\n\n button_for = Button(root, text='>>', command=lambda: forward(image_number + 1))\n if image_number == len(image_list) - 1:\n button_for = Button(root, text='>>', state=DISABLED)\n\n button_back = Button(root, text='<<', command=lambda: back(image_number - 1)).grid(row=3, column=0)\n button_for.grid(row=3, column=2)\n button_exit.grid(row=3, column=1)\n\n status = Label(root, text=\"Image {} of {}\".format(str(image_number + 1), str(len(image_list))), bd=1, relief=SUNKEN, anchor=E)\n status.grid(row=4, column=0, columnspan=3, sticky=W + E)\n\n\n def back(image_number):\n global label\n global button_for\n global button_back\n\n label.grid_forget()\n label = Label(image=image_list[image_number])\n label.grid(row=2, column=0, columnspan=3)\n\n button_for = Button(root, text='>>', command=lambda: forward(image_number + 1))\n button_back = Button(root, text='<<', command=lambda: back(image_number - 1))\n if image_number == 0:\n button_back = Button(root, text='<<', state=DISABLED)\n\n status = Label(root, text=\"Image {} of {}\".format(str(image_number + 1), str(len(image_list))), bd=1, relief=SUNKEN, anchor=E)\n status.grid(row=4, column=0, columnspan=3, sticky=W + E)\n\n button_for.grid(row=3, column=2)\n button_back.grid(row=3, column=0)\n button_exit.grid(row=3, column=1)\n\n \n \n\n button_back = Button(root, text='<<', state=DISABLED)\n button_exit = Button(root, text='EXIT', command=root.quit)\n button_for = Button(root, text='>>', command=lambda: forward(1))\n\n button_back.grid(row=3, column=0)\n button_exit.grid(row=3, column=1)\n button_for.grid(row=3, column=2)\n\n\nbutton_enter = Button(root, text='Enter', padx=20, pady=10, command=Enter)\nbutton_enter.grid(row=1, column=0, columnspan=2)\n\n\nroot.mainloop()","repo_name":"Pyk017/Python","sub_path":"Tkinter/Image_Viewer_By_UserDefined_File.py","file_name":"Image_Viewer_By_UserDefined_File.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2345955670","text":"import tkinter as tk\r\n\r\n#entry window function\r\ndef callback():\r\n value = entry.get()\r\n print (value)\r\n\r\newindow = tk.Tk()\r\nspace1 = tk.Label(ewindow, width=10)\r\nspace1.grid(row=0, column=0)\r\nspace2 = tk.Label(ewindow, width=10)\r\nspace2.grid(row=0, column=2)\r\nTitle = tk.Label(ewindow, text = 'Input value here')\r\nTitle.grid(row=0, column=1)\r\nentry = tk.Entry()\r\nentry.grid(row=1, column=1)\r\nButton1 = tk.Button(ewindow, text=\"Submit\", width=10, command = callback)\r\nButton1.grid(row=2, column=1)\r\n\r\n\r\n\r\newindow.mainloop()\r\n","repo_name":"Phenon-io/Steve-original","sub_path":"Entry test.py","file_name":"Entry test.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2291055368","text":"import code\nimport datetime\nimport json\nimport os\nimport io\nimport contextlib\n\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nfrom ccn.cfg import get_config; CFG = get_config()\nfrom ccn.graph_match import minimum_loss_permutation\nfrom ccn.vision import Perceptor, perceptual_loss, make_symbol_data, color_composite\nfrom ccn.graph_data import get_dataset\nfrom ccn.ml_utils import dense_regularization, update_data_dict, normalize_data_dict\nfrom ccn.models import get_model, get_optim, get_spy_optim, run_dummy_batch, load_weights, save_weights\nfrom ccn.upload import gs_upload_blob_from_memory, gs_upload_blob_from_string\n\nstrategy = None\n\nif CFG['TPU']:\n TPU_WORKER = 'grpc://' + os.environ['COLAB_TPU_ADDR']\n resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=TPU_WORKER)\n tf.config.experimental_connect_to_cluster(resolver)\n tf.tpu.experimental.initialize_tpu_system(resolver)\n strategy = tf.distribute.experimental.TPUStrategy(resolver)\nelse:\n strategy = tf.distribute.get_strategy()\n\nnum_replicas = strategy.num_replicas_in_sync\nprint(\"NUMBER OF REPLICAS: \", num_replicas)\n\n\ndef update_difficulty(difficulty, epoch_acc):\n target_metric = 'symbols' if CFG['JUST_VISION'] else 'values'\n if epoch_acc[target_metric] >= 0.995 and difficulty < 15:\n difficulty += 1\n if epoch_acc[target_metric] < 0.1 and difficulty > 0:\n difficulty -= 1\n return difficulty\n\n\ndef get_batch(start_b, end_b, adj, node_features, adj_labels, nf_labels,\n num_nodes, **kwargs):\n batch = {\n 'adj': adj[start_b:end_b],\n 'node_features': {name: tensor[start_b:end_b] for\n name, tensor in node_features.items()},\n 'adj_labels': adj_labels[start_b:end_b],\n 'nf_labels': {name: tensor[start_b:end_b] for\n name, tensor in nf_labels.items()},\n 'num_nodes': num_nodes[start_b:end_b],\n }\n return batch\n\n\ndef get_visual_samples(test_ds, model, test_num_samples, difficulty):\n sample_idxs = tf.random.uniform([CFG['batch_size']], 0, test_num_samples, tf.int32)\n spy_imgs = None\n if CFG['JUST_VISION']:\n vis_batch = tf.gather(test_ds, sample_idxs)\n _, sample_imgs, aug_imgs = model(vis_batch, difficulty)\n if CFG['use_spy']:\n _, spy_imgs, _ = model(vis_batch, difficulty, spy_turn=True)\n else:\n vis_batch = {\n 'adj': tf.gather(test_ds['adj'], sample_idxs),\n 'node_features': {name: tf.gather(tensor, sample_idxs) for\n name, tensor in test_ds['node_features'].items()},\n 'adj_labels': tf.gather(test_ds['adj_labels'], sample_idxs),\n 'nf_labels': {name: tf.gather(tensor, sample_idxs) for\n name, tensor in test_ds['nf_labels'].items()},\n 'num_nodes': tf.gather(test_ds['num_nodes'], sample_idxs),\n }\n _, _, sample_imgs, aug_imgs, _, _ = model(vis_batch, difficulty)\n if CFG['use_spy']:\n _, _, spy_imgs, _, _, _ = model(vis_batch, difficulty, spy_turn=True)\n # scale tanh to visual range\n sample_imgs = (sample_imgs + 1) / 2\n aug_imgs = (aug_imgs + 1) / 2\n if CFG['use_spy']:\n spy_imgs = (spy_imgs + 1) / 2\n return sample_imgs, aug_imgs, spy_imgs\n\n\ndef main():\n print(f\"Using strategy: {strategy}\")\n with strategy.scope():\n def vision_only_predict(model, batch, difficulty, perceptor):\n all_losses = {}\n symbols = batch\n predictions, imgs, aug_imgs = model(symbols, difficulty)\n acc = tf.keras.metrics.categorical_accuracy(symbols, predictions)\n acc = tf.math.reduce_mean(acc)\n acc = {'symbols': acc}\n lfn = tf.keras.losses.mean_squared_error if CFG['use_mse_loss'] else \\\n lambda true, pred: tf.keras.losses.categorical_crossentropy(true, pred, label_smoothing=CFG['label_smoothing'])\n recon_loss = tf.keras.losses.categorical_crossentropy(\n symbols,\n predictions,\n )\n recon_loss = tf.math.reduce_sum(recon_loss)\n all_losses['reconstruction'] = recon_loss\n if CFG['use_perceptual_loss']:\n features = perceptor(imgs)\n percept_loss = perceptual_loss(features)\n all_losses['perceptual'] = percept_loss\n if CFG['use_spy']:\n # Wassertein-ish loss function\n predictions_s, imgs_s, aug_imgs_s = model(symbols, difficulty, spy_turn=True)\n acc_s = tf.keras.metrics.categorical_accuracy(symbols, predictions_s)\n acc_s = tf.math.reduce_mean(acc_s)\n acc['spy_symbols'] = acc_s\n spy_loss = lfn(\n symbols,\n predictions_s,\n )\n spy_loss = tf.math.reduce_sum(spy_loss)\n\n # get reg loss\n for sub_model in model.layers:\n name = sub_model.name\n all_losses[name] = tf.math.reduce_sum(sub_model.losses)\n\n # get loss sum\n loss_sum = 0.\n for loss_name in all_losses.keys():\n loss_sum += all_losses[loss_name]\n if CFG['use_spy']:\n all_losses['spy_reconstruction'] = spy_loss\n # make logistic loss linear\n all_losses['spy_scaled'] = tf.math.exp(spy_loss * -1)\n loss_sum += all_losses['spy_scaled']\n return loss_sum, acc, all_losses\n\n \n\n def graph_or_full_predict(model, batch, difficulty, perceptor):\n all_losses = {}\n if CFG['VISION']:\n adj_pred, nf_pred, imgs, aug_imgs, _, _ = model(batch, difficulty)\n spy_adj_pred, spy_nf_pred, _, _, _, _ = model(batch, difficulty, spy_turn=True)\n if CFG['use_perceptual_loss']:\n features = perceptor(imgs)\n percept_loss = perceptual_loss(features)\n all_losses['perceptual'] = percept_loss\n else:\n adj_pred, nf_pred = model(batch, difficulty)\n spy_adj_pred, spy_nf_pred = model(batch, difficulty, spy_turn=True)\n recon_loss, acc = minimum_loss_permutation(\n batch['adj_labels'],\n batch['nf_labels'],\n adj_pred,\n nf_pred\n )\n all_losses['reconstruction'] = recon_loss\n\n spy_loss, spy_acc = minimum_loss_permutation(\n batch['adj_labels'],\n batch['nf_labels'],\n spy_adj_pred,\n spy_nf_pred\n )\n for key in spy_acc.keys():\n acc[f\"spy_{key}\"] = spy_acc[key]\n\n # get reg loss\n for sub_model in model.layers:\n name = sub_model.name\n all_losses[name] = tf.math.reduce_sum(sub_model.losses)\n\n # get loss sum\n loss_sum = 0.\n for loss_name in all_losses.keys():\n loss_sum += all_losses[loss_name]\n\n if CFG['use_spy']:\n all_losses['spy_reconstruction'] = spy_loss\n # make logistic loss linear\n all_losses['spy_scaled'] = tf.math.exp(spy_loss * -1)\n loss_sum += all_losses['spy_scaled']\n return loss_sum, acc, all_losses\n\n\n def predict(model, batch, difficulty, perceptor):\n if CFG['JUST_VISION']:\n loss_sum, acc, all_losses = vision_only_predict(model, batch, difficulty, perceptor)\n else:\n loss_sum, acc, all_losses = graph_or_full_predict(model, batch, difficulty, perceptor)\n return loss_sum, acc, all_losses\n\n\n @tf.function\n def train_step(batch, difficulty):\n with tf.GradientTape(persistent=True) as tape:\n loss_sum, acc, all_losses = predict(model, batch, difficulty, perceptor)\n # reconstruction loss\n grads = tape.gradient(loss_sum, model.trainable_variables)\n if CFG['TPU']:\n replica_ctx = tf.distribute.get_replica_context()\n grads = replica_ctx.all_reduce(\"mean\", grads)\n optim.apply_gradients(zip(grads, model.trainable_variables))\n if CFG['use_spy']:\n # spy loss\n spy_grads = tape.gradient(all_losses['spy_reconstruction'], model.spy.trainable_variables)\n if CFG['TPU']:\n replica_ctx = tf.distribute.get_replica_context()\n spy_grads = replica_ctx.all_reduce(\"mean\", spy_grads)\n spy_optim.apply_gradients(zip(spy_grads, model.spy.trainable_variables))\n return loss_sum, acc, all_losses\n\n\n @tf.function\n def test_step(batch, difficulty):\n batch_loss, acc, all_losses = predict(model, batch, difficulty, perceptor)\n return batch_loss, acc, all_losses\n\n\n def aggregate_results(batch_loss, acc, all_losses):\n batch_loss = strategy.reduce(\"mean\", batch_loss, axis=None)\n out_acc = {}\n out_all_losses = {}\n for key in acc.keys():\n out_acc[key] = strategy.reduce(\"mean\", acc[key], axis=None)\n for key in all_losses.keys():\n out_all_losses[key] = strategy.reduce(\"mean\", all_losses[key], axis=None)\n return batch_loss, out_acc, out_all_losses\n\n\n def step_fn(batch, difficulty, test=False):\n if test:\n if CFG['TPU']:\n results = strategy.run(test_step, args=(batch, difficulty))\n return aggregate_results(*results)\n else:\n return test_step(batch, difficulty)\n else:\n if CFG['TPU']:\n results = strategy.run(train_step, args=(batch, difficulty))\n return aggregate_results(*results)\n else:\n return train_step(batch, difficulty)\n\n\n # ==================== DATA AND MODELS ====================\n if CFG['JUST_VISION']:\n train_ds, _ = make_symbol_data(**CFG, test=False)\n test_ds, _ = make_symbol_data(**CFG, test=True)\n else:\n train_ds, _ = get_dataset(**CFG, test=False)\n test_ds, _ = get_dataset(**CFG, test=True)\n replica_batch_size = CFG['batch_size']\n global_batch_size = strategy.num_replicas_in_sync * replica_batch_size\n tf_train_ds = tf.data.Dataset.from_tensor_slices(train_ds).batch(global_batch_size, drop_remainder=True)\n tf_test_ds = tf.data.Dataset.from_tensor_slices(test_ds).batch(global_batch_size, drop_remainder=True)\n\n path_prefix = CFG['root_filepath']\n model = get_model()\n run_dummy_batch(model)\n load_weights(model, path_prefix)\n optim = get_optim()\n spy_optim = get_spy_optim()\n perceptor = None\n # perceptor = Perceptor()\n\n # ==================== NOISY CHANNEL ====================\n difficulty = tf.convert_to_tensor(0)\n\n # ==================== LOGGING ====================\n log_dir = f\"logs/{CFG['run_name']}\"\n os.makedirs(log_dir, exist_ok=True)\n train_log_dir = f\"{path_prefix}{log_dir}/train\"\n test_log_dir = f\"{path_prefix}{log_dir}/test\"\n train_summary_writer = tf.summary.create_file_writer(train_log_dir)\n test_summary_writer = tf.summary.create_file_writer(test_log_dir)\n current_time = str(datetime.datetime.now())\n CFG['current_time'] = current_time\n cfg_dir = os.path.join(log_dir, 'config.json')\n if CFG['USE_GS']:\n gs_upload_blob_from_string(json.dumps(CFG, indent=4), cfg_dir, print_str=True)\n else:\n with open(cfg_dir, 'w+') as f:\n f.write(json.dumps(CFG, indent=4))\n\n # ==================== TRAIN LOOP ====================\n tr_num_samples = train_ds.shape[0] if CFG['JUST_VISION'] else train_ds['adj'].shape[0]\n test_num_samples = test_ds.shape[0] if CFG['JUST_VISION'] else test_ds['adj'].shape[0]\n tr_num_batches = (tr_num_samples // global_batch_size)\n test_num_batches = (test_num_samples // global_batch_size)\n best_epoch_loss = tf.float32.max\n for e_i in range(CFG['epochs']):\n # RESET METRICS\n tr_epoch_loss = 0\n test_epoch_loss = 0\n tr_epoch_acc = {}\n test_epoch_acc = {}\n all_losses = {}\n # TRAIN BATCHES\n b_i = 0\n for train_batch in tf_train_ds:\n b_i += global_batch_size\n batch_loss, batch_acc, batch_all_losses = step_fn(train_batch, difficulty)\n tr_epoch_loss += batch_loss\n update_data_dict(tr_epoch_acc, batch_acc)\n update_data_dict(all_losses, batch_all_losses)\n print(f\"(TRAIN) e [{e_i}/{CFG['epochs']}] b [{b_i}/{tr_num_samples}] loss {batch_loss}\", end=\"\\r\")\n # TEST BATCHES\n b_i = 0\n for test_batch in tf_test_ds:\n b_i += global_batch_size\n batch_loss, batch_acc, _ = step_fn(test_batch, difficulty, test=True)\n test_epoch_loss += batch_loss\n update_data_dict(test_epoch_acc, batch_acc)\n print(f\"(TEST) e [{e_i}/{CFG['epochs']}] b [{b_i}/{test_num_samples}] loss {batch_loss}\", end=\"\\r\")\n # END-OF-EPOCH METRICS\n tr_epoch_loss = tr_epoch_loss / tr_num_batches\n test_epoch_loss = test_epoch_loss / test_num_batches\n tr_epoch_acc = normalize_data_dict(tr_epoch_acc, tr_num_batches)\n test_epoch_acc = normalize_data_dict(test_epoch_acc, test_num_batches)\n all_losses = normalize_data_dict(all_losses, tr_num_batches)\n print(f\"EPOCH {e_i} TRAIN LOSS: {tr_epoch_loss} TEST LOSS: {test_epoch_loss}\")\n print(f\"Train accuracies: {json.dumps(tr_epoch_acc, indent=4)}\")\n print(f\"Test accuracies: {json.dumps(test_epoch_acc, indent=4)}\")\n print(f\"All losses: {json.dumps(all_losses, indent=4)}\")\n difficulty = update_difficulty(difficulty, tr_epoch_acc)\n print(f\"DIFFICULTY FOR NEXT EPOCH: {difficulty}\")\n # write metrics to log\n if not CFG['NOLOG']:\n with train_summary_writer.as_default():\n tf.summary.scalar('loss', tr_epoch_loss, step=e_i)\n for name, metric in tr_epoch_acc.items():\n tf.summary.scalar(name, metric, step=e_i)\n for name, specific_loss in all_losses.items():\n tf.summary.scalar(name, specific_loss, step=e_i)\n with test_summary_writer.as_default():\n tf.summary.scalar('loss', test_epoch_loss, step=e_i)\n for name, metric in test_epoch_acc.items():\n tf.summary.scalar(name, metric, step=e_i)\n # SAVE CHECKPOINTS\n if e_i % CFG['save_checkpoint_every'] == 0 and e_i != 0:\n if test_epoch_loss < best_epoch_loss:\n print(f\"Saving checkpoint...\")\n best_epoch_loss = test_epoch_loss\n save_weights(model, path_prefix)\n # GENERATE VISUAL SAMPLE\n if CFG['VISION'] and e_i % CFG['image_every'] == 0 and e_i != 0:\n sample_imgs, aug_imgs, spy_imgs = get_visual_samples(test_ds, model, test_num_samples, difficulty)\n sample_imgs = color_composite(sample_imgs)\n aug_imgs = color_composite(aug_imgs)\n if CFG['use_spy']: spy_imgs = color_composite(spy_imgs)\n fig, axes = plt.subplots(3, 4) if CFG['use_spy'] else plt.subplots(2, 4)\n for img_i in range(4):\n axes[0][img_i].imshow(sample_imgs[img_i])\n axes[1][img_i].imshow(aug_imgs[img_i])\n if CFG['use_spy']: axes[2][img_i].imshow(spy_imgs[img_i])\n # upload snapshot (or save locally)\n if CFG['USE_GS']:\n gallery_dir = f\"gallery/{CFG['run_name']}\"\n img_name = os.path.join(gallery_dir, f\"{e_i}.png\")\n img_data = io.BytesIO()\n plt.savefig(img_data, format='png')\n img_data.seek(0)\n gs_upload_blob_from_memory(img_data, img_name)\n else:\n gallery_dir = f\"{path_prefix}gallery/{CFG['run_name']}\"\n os.makedirs(gallery_dir, exist_ok=True)\n img_name = os.path.join(gallery_dir, f\"{e_i}.png\")\n plt.savefig(img_name, format='png')\n plt.clf()\n plt.cla()\n plt.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"noahtren/Cooperative-Communication-Networks","sub_path":"ccn/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14745,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"} +{"seq_id":"935809246","text":"from matplotlib import pyplot as plt\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn import preprocessing\nfrom sklearn import metrics\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import confusion_matrix, recall_score, precision_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import preprocessing\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.linear_model import LinearRegression\n\n# Reading a data set from git repository\ndataset = pd.read_csv(\n r'https://raw.githubusercontent.com/AdnanAlagic/Loan-Prediction-Cleaned/main/Training%20data%20cleaned.csv')\n\nprint(dataset)\n\n# Preprocessing data\nle = preprocessing.LabelEncoder()\n\n#Dealing with empty fields\n#dataset['Income'] = dataset['Income'].fillna(dataset['Income'].mean())\n#dataset['Age'] = dataset['Age'].fillna(dataset['Age'].mean())\n#dataset['Experience'] = dataset['Experience'].fillna(dataset['Experience'].mean())\n\n# Extracting data set columns\nincome = dataset.iloc[:, 1].values\nage = dataset.iloc[:, 2].values\nexperience = dataset.iloc[:, 3].values\nmaritalStatus = dataset.iloc[:, 4].values\nhouseOwnership = dataset.iloc[:, 5].values\ncarOwnership = dataset.iloc[:, 6].values\nprofession = dataset.iloc[:, 7].values\ncity = dataset.iloc[:, 8].values\nstate = dataset.iloc[:, 9].values\ncurrentJobYears = dataset.iloc[:, 10].values\ncurrentHouseYears = dataset.iloc[:, 11].values\nriskFlag = dataset.iloc[:, 12].values\n\n# Transformation of columns\nincome_encoded = le.fit_transform(income)\nage_encoded = le.fit_transform(age)\nexperience_encoded = le.fit_transform(experience)\nmaritalStatus_encoded = le.fit_transform(maritalStatus)\nhouseOwnership_encoded = le.fit_transform(houseOwnership)\ncarOwnership_encoded = le.fit_transform(carOwnership)\nprofession_encoded = le.fit_transform(profession)\ncity_encoded = le.fit_transform(city)\nstate_encoded = le.fit_transform(state)\ncurrentJobYears_encoded = le.fit_transform(currentJobYears)\ncurrentHouseYears_encoded = le.fit_transform(currentHouseYears)\nriskFlag_encoded = le.fit_transform(riskFlag)\n\n# Setting model, depending on choosen algorithm\nmodel = KNeighborsClassifier(n_neighbors=265, metric='euclidean')\n#model = GaussianNB()\n#model = DecisionTreeClassifier(criterion=\"entropy\")\n#model = RandomForestClassifier()\n\nX_train, X_test, y_train, y_test = train_test_split(\n list(zip(income_encoded, age_encoded, experience_encoded, maritalStatus_encoded,\n houseOwnership_encoded, carOwnership_encoded, profession_encoded, city_encoded,\n state_encoded, currentJobYears_encoded, currentHouseYears_encoded)),\n riskFlag_encoded,\n test_size=0.2, random_state=0)\n\n# Model training\nmodel.fit(list(X_train), y_train)\n\n# Printing model accuracy\ny_pred = model.predict(X_test)\nprint(\"Model accuracy:\", metrics.accuracy_score(y_test, y_pred))\nprint(\"Model F1 score: \", f1_score(y_test, y_pred))\nprint(\"Precision: \", precision_score(y_test, y_pred))\nprint(\"Recall: \", recall_score(y_test, y_pred))\n\n# Printing confusion matrix in console\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\n\n# Importing seaborn as sns in order ti display confusion matrix in real image\nimport seaborn as sns\n\ngroup_names = ['True Neg', 'False Pos', 'False Neg', 'True Pos']\n\ngroup_counts = [\"{0:0.0f}\".format(value) for value in\n cm.flatten()]\n\ngroup_percentages = [\"{0:.2%}\".format(value) for value in\n cm.flatten() / np.sum(cm)]\n\nlabels = [f\"{v1}\\n{v2}\\n{v3}\" for v1, v2, v3 in\n zip(group_names, group_counts, group_percentages)]\n\nlabels = np.asarray(labels).reshape(2, 2)\n\nax = sns.heatmap(cm, annot=labels, fmt='', cmap='Blues')\n\nax.set_title('Seaborn Confusion Matrix with labels\\n\\n')\nax.set_xlabel('\\nPredicted Values')\nax.set_ylabel('Actual Values ')\n\n# Ticket labels - List must be in alphabetical order\nax.xaxis.set_ticklabels(['False', 'True'])\nax.yaxis.set_ticklabels(['False', 'True'])\n\n# Display the visualization of the Confusion Matrix.\nplt.show()\n\n","repo_name":"AdnanAlagic/LoanPrediction","sub_path":"FirstDataSetImplementation.py","file_name":"FirstDataSetImplementation.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30985201979","text":"def longest_run(L):\n \"\"\"\n Assumes L is a list of integers containing at least 2 elements.\n Finds the longest run of numbers in L, where the longest run can\n either be monotonically increasing or monotonically decreasing. \n In case of a tie for the longest run, choose the longest run \n that occurs first.\n Does not modify the list.\n Returns the sum of the longest run. \n \"\"\"\n def get_sublists(L, n):\n result = []\n for i in range(len(L)-n+1):\n result.append(L[i:i+n])\n return result\n for i in range(len(L), 0, -1):\n possibles = get_sublists(L, i)\n for p in possibles:\n if p == sorted(p) or p == sorted(p, reverse=True):\n return sum(p)","repo_name":"dizzyg64/edX-MITx-6.00.1X","sub_path":"Final Exam/Problem4.py","file_name":"Problem4.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9888920200","text":"import random\nword_list = ['python', 'java', 'kotlin', 'javascript']\nword_choosen = random.choice(word_list)\nguessing = '-' * len(word_choosen)\nguessed = set()\nprint(\"H A N G M A N\")\nlives = 8\nwhile lives:\n print(\"\\n\" + guessing)\n player = input(\"Input a letter: > \")\n if player in guessed:\n print(\"No improvements\")\n lives -= 1\n continue\n if player not in word_choosen:\n print(\"No such letter in the word\")\n lives -= 1\n continue\n for i in range(len(word_choosen)):\n if word_choosen[i] == player:\n guessing = guessing[0:i] + player + guessing[i+1:]\n guessed.add(player)\n if \"-\" not in guessing:\n break\nif lives:\n print(f\"\\n{guessing}\\nYou guessed the word!\\nYou survived!\")\nelse:\n print(\"You are hanged!\")\n","repo_name":"tboonma/ske-comprog1","sub_path":"ComProg/ex4/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12263412608","text":"import xml.etree.ElementTree as ET\n\nimport pickle\nimport os\nfrom os import listdir, getcwd\nfrom os.path import join\nimport glob\n\nclasses = [\"drink\", \"stand\", \"lie\"]\n\n\ndef convert(size, box):\n dw = 1.0 / size[0]\n dh = 1.0 / size[1]\n x = (box[0] + box[1]) / 2.0\n y = (box[2] + box[3]) / 2.0\n w = box[1] - box[0]\n h = box[3] - box[2]\n x = x * dw\n w = w * dw\n y = y * dh\n h = h * dh\n return (x, y, w, h)\n\n\ndef convert_annotation(image_name):\n in_file = open('D:/Desktop/饮水行为识别/coco_drink380/xml_test/' + image_name[:-3] + 'xml') # xml文件路径\n out_file = open('D:/Desktop/饮水行为识别/yolov5/labels/test/' + image_name[:-3] + 'txt', 'w') # 转换后的txt文件存放路径\n f = open('D:/Desktop/饮水行为识别/coco_drink380/xml_test/' + image_name[:-3] + 'xml','r', encoding='UTF-8')\n xml_text = f.read()\n root = ET.fromstring(xml_text)\n f.close()\n size = root.find('size')\n w = int(size.find('width').text)\n h = int(size.find('height').text)\n\n for obj in root.iter('object'):\n cls = obj.find('name').text\n if cls not in classes:\n print(cls)\n continue\n cls_id = classes.index(cls)\n xmlbox = obj.find('bndbox')\n b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),\n float(xmlbox.find('ymax').text))\n bb = convert((w, h), b)\n out_file.write(str(cls_id) + \" \" + \" \".join([str(a) for a in bb]) + '\\n')\n\n\nwd = getcwd()\n\nif __name__ == '__main__':\n\n for image_path in glob.glob(\"D:/Desktop/饮水行为识别/coco_drink380/coco_test115/*\"): # 每一张图片都对应一个xml文件这里写xml对应的图片的路径\n image_name = image_path.split('\\\\')[-1]\n print(image_name)\n convert_annotation(image_name)","repo_name":"Wedream-wj/PigNet","sub_path":"yolov5/xml2txt.py","file_name":"xml2txt.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37957297490","text":"# God forgive me for star import\nfrom .settings_base import * # noqa\n\n\nDEBUG = True\n\nALLOWED_HOSTS = ['*', ]\n\nINSTALLED_APPS += [\n 'rest_framework',\n 'drf_yasg',\n 'oauth2_provider',\n 'user_app.apps.UserAppConfig',\n]\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n ),\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json'\n}\n\nAUTH_USER_MODEL = 'user_app.SandyUser'\n\nOAUTH2_PROVIDER = {\n # list of available scopes\n 'SCOPES': {\n 'read': 'Read scope',\n 'write': 'Write scope'\n }\n}\n\nCELERY_BROKER_URL = 'amqp://guest:guest@django_demo_sandbox_rabbitmq_1:5672/'\n\n# Host for sending e-mail.\nEMAIL_HOST = 'localhost' # for debugging purposes\n\n# Port for sending e-mail.\nEMAIL_PORT = 1025\n\n# Optional SMTP authentication information for EMAIL_HOST.\nEMAIL_HOST_USER = ''\nEMAIL_HOST_PASSWORD = ''\n\n# Turn off security layers during development\nEMAIL_USE_SSL = False\nEMAIL_USE_TLS = False\n","repo_name":"nautics889/django_demo_sandbox","sub_path":"sandbox/sandbox/settings_dev.py","file_name":"settings_dev.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32197628017","text":"# Các màn hình cho module quản lý Học viên\n\nimport datetime\nfrom turtle import clearscreen\nfrom dbprovider import *\nfrom utils import *\n#from tasks.studenttask import writeStudent\n# Màn hình hiển thị menu của module QL Học viện\ndef studentMenuScreen():\n clearScreen()\n printHeader('QUẢN LÝ HỌC VIÊN')\n funcs = [\n '1. Insert',\n '2. Delete',\n '3. Edit',\n '4. Search ',\n '0. Exit',\n ]\n printMenu(funcs)\n\n cmd = None\n while cmd not in ['1','2','3','4','0']:\n cmd = input('Choose function: ')\n if cmd == '1':\n #Chuyển sang màn hình add Student management\n addStudentScreen()\n studentMenuScreen()\n \n elif cmd =='2':\n deleteStudentScreen()\n\n elif cmd == '3':\n editStudentScreen()\n\n\n elif cmd == '4':\n searchStudentsScreen()\n\n elif cmd == '0':\n exit()\n \n\n# Màn hình nhập thông tin học viên\ndef addStudentScreen():\n clearScreen()\n printHeader('THÊM HỌC VIÊN')\n\n while True:\n code = input('Mã sinh viên: ')\n if len(code) != 6:\n print('Mã học viên phải có 6 ký tự')\n continue\n else: break\n while True:\n fullname = input('Họ tên đầy đủ: ')\n if fullname[0] != fullname[0].upper():\n print('Họ tên phải viết hoa chữ cái đầu')\n continue\n else: break\n while True:\n birthday = input('Birthday(dd/mm/yyyy): ')\n try:\n t1 = datetime.datetime.strptime(birthday, '%d/%m/%Y')\n t2 = datetime.datetime.now()\n if(t1 >= t2):\n print('Ngày sinh không được lớn hơn ngày hiện tại')\n continue\n except ValueError:\n print('Date invalid')\n continue\n break\n \n while True:\n sex = input('Giới tính (0-Nam, 1-Nữ): ')\n if sex not in ['0','1']:\n print('Giới tính phải là 0 hoặc 1')\n continue\n else: break\n address = input('Địa chỉ: ')\n while True:\n phone = input('Điện thoại: ')\n if phone is None:\n print('Số điện thoại không được để trống')\n continue\n else: break\n\n email = input('Email: ')\n\n pupil = {\n 'Code': code,\n 'FullName': fullname,\n 'Birthday': birthday,\n 'Sex': sex,\n 'Address': address,\n 'Phone': phone,\n 'Email': email\n }\n if pupil is not None:\n writeStudent(pupil)\n print(f'Thêm học viên {code} vào danh sách thành công' )\n \n ans = input('Bạn có muốn tiếp tục thêm học viên không (Y/N)? ')\n if ans.upper() == 'Y':\n addStudentScreen()\n\n \n\n# Chỉnh sửa thông tin học viên\ndef editStudentScreen():\n clearScreen()\n printHeader('CHỈNH SỬA THÔNG TIN HỌC VIÊN')\n\n while True:\n code = input('Ma HV: ')\n if len(code) != 6:\n print('Mã học viên phải có 6 ký tự')\n continue\n isExists = checkExistsStudent(code)\n if isExists == False:\n print('Mã học viên không tồn tại')\n continue\n else :\n break\n print('Mã học viên hợp lệ')\n # Lấy thông tin học viên theo code\n st = getStudentByCode(code)\n\n fullName = st['FullName']\n print('Họ tên: ', fullName)\n ans = input('Bạn có muốn thay đổi họ tên không (Y/N)? ')\n if ans.upper() == 'Y':\n while True:\n fullName = input('Họ tên mới: ')\n if fullName[0] != fullName[0].upper():\n print('Họ tên phải viết hoa chữ cái đầu')\n continue\n else: break\n st['FullName'] = fullName\n birthday = st['Birthday']\n print('Ngày sinh: ', birthday)\n ans = input('Bạn có muốn thay đổi ngày sinh không (Y/N)? ')\n if ans.upper() == 'Y':\n while True:\n birthday = input('Ngày sinh mới(dd/mm/yyyy): ')\n try:\n t1 = datetime.datetime.strptime(birthday, '%d/%m/%Y')\n t2 = datetime.datetime.now()\n if(t1 >= t2):\n print('Ngày sinh không được lớn hơn ngày hiện tại')\n continue\n except ValueError:\n print('Date invalid')\n continue\n break\n st['Birthday'] = birthday\n writeStudent(st)\n print('Thay doi thong tin sinh vien thanh cong')\n #studentMenuScreen()\n\n\n\n\n#Xóa học viên theo mã\ndef deleteStudentScreen():\n clearscreen()\n printHeader('XÓA HỌC VIÊN')\n while True:\n code = input('Mã học viên: ')\n if len(code) != 6:\n print('Mã học viên phải có 6 ký tự')\n continue\n isExists = checkExistsStudent(code)\n if isExists == False:\n print('Mã học viên không tồn tại')\n continue\n else:\n break\n \n sts = readStudents()\n idx = None\n for i, st in enumerate(sts):\n sts = readStudents()\n if st['Code'] == code:\n sts.pop(i)\n break\n writeStudents(sts)\n print('Xóa học viên thành công')\n printAllofList(sts)\n nextStep = input('Bạn có muốn tiếp tục xóa học viên không (Y/N)? ')\n if(nextStep.upper() == 'Y'):\n deleteStudentScreen()\n studentMenuScreen()\n\n#Tìm kiếm học viên\ndef searchStudentsScreen():\n clearScreen()\n printHeader('TÌM KIẾM HỌC VIÊN')\n sts = readStudents()\n while True:\n st_name = input('Nhập tên học viên: ')\n if(st_name[0] != st_name[0].upper()):\n print('Họ tên phải viết hoa chữ cái đầu')\n continue\n else: break\n\n isFind = False\n for st in sts:\n if st['FullName'] == st_name:\n isFind = True\n print('\\n'.join([f'{k}: {v}' for k,v in st.items()]))\n break\n \n if(isFind == False):\n print('Không tìm thấy học viên')\n \n ans = input('Bạn có muốn tiếp tục tìm kiếm học viên không (Y/N)? ')\n if ans.upper() == 'Y':\n searchStudentsScreen()\n studentMenuScreen()\n","repo_name":"Hnanav/Project01-School-Management","sub_path":"screen/studentscreen.py","file_name":"studentscreen.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26550898381","text":"def drawrow(coldivide):\n rowstring = \" --- \"\n print(rowstring * coldivide)\n\ndef drawactiverow(coldivide):\n rowstring = \"---\"\n print(rowstring * coldivide)\n\n\ndef blankcolumn(coldivide):\n colstring = \"| \"\n finalbuffer = colstring\n finalbuffer += \" \"\n print((finalbuffer * coldivide) + \"|\")\n\ndef drawcolumn(ActiveBoard,rownumber,size):\n colstring = \"|\"\n rowstring = \"\"\n for colcount in range(size):\n if ActiveBoard[rownumber][colcount] == 'X':\n colstring += ' X '\n elif ActiveBoard[rownumber][colcount] == 'O':\n colstring += ' O '\n else:\n colstring += ' '\n colstring += \"|\"\n rowstring += colstring \n colstring = \"\"\n rowstring += \"\\n\"\n return rowstring\n\ndef prepareActiveBoard(boardsetup,size):\n for count in range(size):\n # Prepare each column for the row\n columnforrow = []\n for colcount in range(size):\n columnforrow.append('-')\n # Append the column for the row\n boardsetup.append(columnforrow)\n\ndef drawInitialBoard(size):\n # Add Row and Column as per size\n for count in range(size):\n drawrow(size)\n blankcolumn(size)\n # Finally close the board\n drawrow(size)\n\n\ndef VerifyWinnerInRow(ActiveBoard):\n rowlen = len(ActiveBoard)\n winner = -1\n WinnerFound = False\n # Verify Row wise winner\n for count in range(rowlen):\n # Verify entire column\n collen = len(ActiveBoard[count])\n prevvalue = -1\n matchstatus = True\n for colcount in range(collen):\n if prevvalue == -1:\n prevvalue = ActiveBoard[count][colcount]\n elif ActiveBoard[count][colcount] != '-' and prevvalue == ActiveBoard[count][colcount]:\n # Mark possible winner\n winner = prevvalue\n continue\n else:\n matchstatus = False\n break\n # Verify whehter we found the winner\n if matchstatus == True:\n WinnerFound = True\n break\n return WinnerFound, winner\n\n\ndef VerifyWinnerInColumn(ActiveBoard):\n collen = len(ActiveBoard[0])\n WinnerFound = False\n for count in range(collen):\n # Verify entire column\n rowlen = len(ActiveBoard)\n prevvalue = -1\n winner = -1\n matchstatus = True\n for rowcount in range(rowlen):\n if prevvalue == -1:\n prevvalue = ActiveBoard[rowcount][count]\n elif ActiveBoard[rowcount][count] != '-' and prevvalue == ActiveBoard[rowcount][count]:\n # Mark possible winner\n winner = prevvalue\n continue\n else:\n matchstatus = False\n break\n # Verify whehter we found the winner\n if matchstatus == True:\n WinnerFound = True\n break\n return WinnerFound, winner\n\ndef VerifyWinnerInDimension(ActiveBoard):\n # Verify dimension wise match\n # calculate dimension\n WinnerFound = False\n collen = len(ActiveBoard[0])\n rowlen = len(ActiveBoard)\n dimension = rowlen * collen\n prevvalue = -1\n winner = -1\n matchstatus = True\n for count in range(rowlen):\n # Verify entire column\n if prevvalue == -1:\n prevvalue = ActiveBoard[count][count]\n elif ActiveBoard[count][count] != '-' and prevvalue == ActiveBoard[count][count]:\n # Mark possible winner\n winner = prevvalue\n continue\n else:\n matchstatus = False\n break\n if not matchstatus:\n # Do reverse dimension check\n prevvalue = -1\n winner = -1\n matchstatus = True\n colcount = collen - 1\n for count in range(rowlen):\n # Verify entire column\n print(\"Index \",count)\n if prevvalue == -1:\n prevvalue = ActiveBoard[count][colcount]\n print(\"Value \",prevvalue)\n colcount -= 1\n elif ActiveBoard[count][colcount] != '-' and prevvalue == ActiveBoard[count][colcount]:\n # Mark possible winner\n print(\"value match \", ActiveBoard[count][colcount])\n winner = prevvalue\n colcount -= 1\n continue\n else:\n matchstatus = False\n break\n\n # Verify whehter we found the winner\n if matchstatus == True:\n WinnerFound = True\n return WinnerFound, winner\n\n\ndef VerifyWinner(ActiveBoard):\n gamestatus, winnerifany = VerifyWinnerInRow(ActiveBoard)\n if(gamestatus == False):\n gamestatus, winnerifany = VerifyWinnerInColumn(ActiveBoard)\n if gamestatus == False:\n gamestatus,winnerifany = VerifyWinnerInDimension(ActiveBoard)\n return gamestatus,winnerifany\n\ndef updateDisplayBoard(ActiveBoard,size):\n displayboard = \"\"\n updatedrow = \"\"\n rowdivder = \"\"\n for count in range(size):\n updatedrow = drawcolumn(ActiveBoard,count,size)\n rowdivider = (\"-\" * len(updatedrow))\n displayboard += rowdivider + \"\\n\"\n displayboard += updatedrow\n displayboard += rowdivider + \"\\n\"\n print(displayboard)\n\n\ndef updateBoard(row,column,player,ActiveBoard):\n # Update Internal state\n ActiveBoard[row][column] = player\n # Update display board\n updateDisplayBoard(ActiveBoard,size)\n\n\nprint(\"Welcome to TicTacToe Game\")\nchoice = input(\"what size of game board you want to play : \")\nsize = int(choice)\ncoldivide = size\nActiveBoard = []\n\n# Prepare internal Active board\nprepareActiveBoard(ActiveBoard,size)\n# Prepare initial display board\ndrawInitialBoard(size)\nprint(\"This is initial board internal status \", ActiveBoard)\n# Declare Player\nprint(\"Player 1 is X and Player 2 is O\")\nprint(\"Lets begin the game\")\n\nActivePlayer = 'X'\nwhile True:\n movechoice = \"Select your move Player \"\n if ActivePlayer == \"X\":\n movechoice += \" X \"\n else:\n movechoice += \" O \"\n movechoice += \" enter row and column (type row number,column number) e.g. 2,3 : \"\n movechoice = input(movechoice)\n movechoice = movechoice.strip()\n choiceadded = movechoice.split(\",\")\n # Validate Row and Column\n row = int(choiceadded[0].strip())\n column = int(choiceadded[1].strip())\n if row < 0 or row > size:\n print(\"Please type valid row number\")\n continue\n if column < 0 or column > size:\n print(\"Please type valid column number\")\n continue\n # Row,Column is valid, lets prepare the move \n updateBoard(row-1,column-1,ActivePlayer,ActiveBoard)\n # Now verify winner if any\n gamestatus, winnerifany = VerifyWinner(ActiveBoard)\n if gamestatus == True:\n # We have winner\n output = \"End of Game, Winner is Player \"\n output += winnerifany + \"\\n\"\n print(output)\n break\n # lets allow other player to play\n if ActivePlayer == \"X\":\n ActivePlayer = \"O\"\n else:\n ActivePlayer = \"X\" ","repo_name":"testme2000/JSDevelopment","sub_path":"Assignment/Python/TicTacToeMove/PerformMove.py","file_name":"PerformMove.py","file_ext":"py","file_size_in_byte":7004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16843885519","text":"import psycopg2\n\nnewPlayerList = []\nfeildList = ('Name', 'Age', 'Games played', 'Games started', 'Minutes played',\n 'Shots made', 'Shots attempted', 'Shooting %', 'Three points made',\n 'Three points attempted', 'Three point %', 'Two points made',\n 'Two points attempted', 'Two point %', 'Shooting %',\n 'Free throws made', 'Free throws attempted', 'Free throw %',\n 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds',\n 'Assists', 'Steals', 'Blocked shots', 'Turn overs', 'Personal fouls',\n 'Total points')\n\ndef retrieve_player(playerName):\n conn = psycopg2.connect(\"dbname=jimturbo user=jimturbo\")\n cur = conn.cursor()\n cur.execute(\"\"\"SELECT * FROM spurs_stats WHERE player_name=%s\"\"\", [playerName])\n data = cur.fetchall()\n conn.commit()\n cur.close()\n conn.close()\n\n count = 1\n player_stats = data[0]\n\n for i in feildList:\n print('{}: {}'.format(i, player_stats[count]))\n count += 1\n\ndef insert_player(playerList):\n conn = psycopg2.connect(\"dbname=jimturbo user=jimturbo\")\n cur = conn.cursor()\n cur.execute(\"\"\"\n INSERT INTO spurs_stats\n (player_name,\n age,\n gm_tot,\n gm_start,\n min_plyd,\n feild_gl_md,\n feild_gl_att,\n feild_gl_pct,\n three_pt_md,\n three_pt_att,\n three_pt_pct,\n two_pt_md,\n two_pt_att,\n two_pt_pct,\n eff_fg_pct,\n free_thw_md,\n free_thw_att,\n free_thw_pct,\n off_rbnd,\n def_rbnd,\n rbnd_tot,\n ast,\n stl,\n blk,\n trn_ovr,\n prsnl_fwl,\n tot_pts)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,\n %s, %s, %s, %s, %s, %s, %s)\"\"\", playerList)\n conn.commit()\n cur.close()\n conn.close()\n\n\nprint('Welcome to the 2015-16 spurs stats sheet.')\nwhile True:\n print('Press:\\n(v) to view a players stats')\n print('(a) to add a players stats\\n(r) to reset the player records')\n print('(e) to exit')\n userChoice = input('> ')\n if 'v' in userChoice.lower():\n inputName = input('Enter the name of a player to retrieve thier stats: ')\n retrieve_player(inputName)\n elif 'a' in userChoice.lower():\n print('Complete each entry below to add a player.')\n for i in feildList:\n newPlayerInput = input('{}: '.format(i))\n newPlayerList.append(newPlayerInput)\n insert_player(newPlayerList)\n elif 'e' in userChoice.lower():\n print('Thanks for stopping by!')\n break\n","repo_name":"jimturbo24/TIY-Homework","sub_path":"week_3/export_csv_2.py","file_name":"export_csv_2.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32709241808","text":"composição = 0\nseparar = \"-\"\nwhile True:\n frase = input(\"Digite a frase desejada: \").split()\n tamanho = []\n \n for r in frase:\n tamanho.append(str(len(r)))\n if len(r) >= composição:\n composição = len(r)\n maiorPalavra = r\n print(separar.join(tamanho))\n\n end = str(input(\"Digite ENTER para prosseguir com o programa ou 0 para encerrá-lo:\"))\n if end == \"0\":\n break\n\nprint()\nprint(\"A maior palavra é: %s\" % maiorPalavra)","repo_name":"RonySantus/-Ronald-Santos--p7info-poo","sub_path":"Atividade-Avaliacao/avaliacao-02/av-02.py","file_name":"av-02.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12313193925","text":"import io\nimport json\nimport logging\nimport os\n\nfrom google.auth import environment_vars\nfrom google.auth import exceptions\nimport google.auth.transport._http_client\n\n_LOGGER = logging.getLogger(__name__)\n\n# Valid types accepted for file-based credentials.\n_AUTHORIZED_USER_TYPE = 'authorized_user'\n_SERVICE_ACCOUNT_TYPE = 'service_account'\n_VALID_TYPES = (_AUTHORIZED_USER_TYPE, _SERVICE_ACCOUNT_TYPE)\n\n# Help message when no credentials can be found.\n_HELP_MESSAGE = \"\"\"\nCould not automatically determine credentials. Please set {env} or\nexplicitly create credential and re-run the application. For more\ninformation, please see\nhttps://developers.google.com/accounts/docs/application-default-credentials.\n\"\"\".format(env=environment_vars.CREDENTIALS).strip()\n\n\ndef _load_credentials_from_file(filename):\n \"\"\"Loads credentials from a file.\n\n The credentials file must be a service account key or stored authorized\n user credentials.\n\n Args:\n filename (str): The full path to the credentials file.\n\n Returns:\n Tuple[google.auth.credentials.Credentials, Optional[str]]: Loaded\n credentials and the project ID. Authorized user credentials do not\n have the project ID information.\n\n Raises:\n google.auth.exceptions.DefaultCredentialsError: if the file is in the\n wrong format.\n \"\"\"\n with io.open(filename, 'r') as file_obj:\n try:\n info = json.load(file_obj)\n except ValueError as exc:\n raise exceptions.DefaultCredentialsError(\n 'File {} is not a valid json file.'.format(filename), exc)\n\n # The type key should indicate that the file is either a service account\n # credentials file or an authorized user credentials file.\n credential_type = info.get('type')\n\n if credential_type == _AUTHORIZED_USER_TYPE:\n from google.auth import _cloud_sdk\n\n try:\n credentials = _cloud_sdk.load_authorized_user_credentials(info)\n except ValueError as exc:\n raise exceptions.DefaultCredentialsError(\n 'Failed to load authorized user credentials from {}'.format(\n filename), exc)\n # Authorized user credentials do not contain the project ID.\n return credentials, None\n\n elif credential_type == _SERVICE_ACCOUNT_TYPE:\n from google.oauth2 import service_account\n\n try:\n credentials = (\n service_account.Credentials.from_service_account_info(info))\n except ValueError as exc:\n raise exceptions.DefaultCredentialsError(\n 'Failed to load service account credentials from {}'.format(\n filename), exc)\n return credentials, info.get('project_id')\n\n else:\n raise exceptions.DefaultCredentialsError(\n 'The file {file} does not have a valid type. '\n 'Type is {type}, expected one of {valid_types}.'.format(\n file=filename, type=credential_type, valid_types=_VALID_TYPES))\n\n\ndef _get_gcloud_sdk_credentials():\n \"\"\"Gets the credentials and project ID from the Cloud SDK.\"\"\"\n from google.auth import _cloud_sdk\n\n # Check if application default credentials exist.\n credentials_filename = (\n _cloud_sdk.get_application_default_credentials_path())\n\n if not os.path.isfile(credentials_filename):\n return None, None\n\n credentials, project_id = _load_credentials_from_file(\n credentials_filename)\n\n if not project_id:\n project_id = _cloud_sdk.get_project_id()\n\n if not project_id:\n _LOGGER.warning(\n 'No project ID could be determined from the Cloud SDK '\n 'configuration. Consider running `gcloud config set project` or '\n 'setting the %s environment variable', environment_vars.PROJECT)\n\n return credentials, project_id\n\n\ndef _get_explicit_environ_credentials():\n \"\"\"Gets credentials from the GOOGLE_APPLICATION_CREDENTIALS environment\n variable.\"\"\"\n explicit_file = os.environ.get(environment_vars.CREDENTIALS)\n\n if explicit_file is not None:\n credentials, project_id = _load_credentials_from_file(\n os.environ[environment_vars.CREDENTIALS])\n\n if not project_id:\n _LOGGER.warning(\n 'No project ID could be determined from the credentials at %s '\n 'Consider setting the %s environment variable',\n environment_vars.CREDENTIALS, environment_vars.PROJECT)\n\n return credentials, project_id\n\n else:\n return None, None\n\n\ndef _get_gae_credentials():\n \"\"\"Gets Google App Engine App Identity credentials and project ID.\"\"\"\n from google.auth import app_engine\n\n try:\n credentials = app_engine.Credentials()\n project_id = app_engine.get_project_id()\n return credentials, project_id\n except EnvironmentError:\n return None, None\n\n\ndef _get_gce_credentials(request=None):\n \"\"\"Gets credentials and project ID from the GCE Metadata Service.\"\"\"\n # Ping requires a transport, but we want application default credentials\n # to require no arguments. So, we'll use the _http_client transport which\n # uses http.client. This is only acceptable because the metadata server\n # doesn't do SSL and never requires proxies.\n from google.auth import compute_engine\n from google.auth.compute_engine import _metadata\n\n if request is None:\n request = google.auth.transport._http_client.Request()\n\n if _metadata.ping(request=request):\n # Get the project ID.\n try:\n project_id = _metadata.get_project_id(request=request)\n except exceptions.TransportError:\n _LOGGER.warning(\n 'No project ID could be determined from the Compute Engine '\n 'metadata service. Consider setting the %s environment '\n 'variable.', environment_vars.PROJECT)\n project_id = None\n\n return compute_engine.Credentials(), project_id\n else:\n return None, None\n\n\ndef default(scopes=None, request=None):\n \"\"\"Gets the default credentials for the current environment.\n\n `Application Default Credentials`_ provides an easy way to obtain\n credentials to call Google APIs for server-to-server or local applications.\n This function acquires credentials from the environment in the following\n order:\n\n 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set\n to the path of a valid service account JSON private key file, then it is\n loaded and returned. The project ID returned is the project ID defined\n in the service account file if available (some older files do not\n contain project ID information).\n 2. If the `Google Cloud SDK`_ is installed and has application default\n credentials set they are loaded and returned.\n\n To enable application default credentials with the Cloud SDK run::\n\n gcloud auth application-default login\n\n If the Cloud SDK has an active project, the project ID is returned. The\n active project can be set using::\n\n gcloud config set project\n\n 3. If the application is running in the `App Engine standard environment`_\n then the credentials and project ID from the `App Identity Service`_\n are used.\n 4. If the application is running in `Compute Engine`_ or the\n `App Engine flexible environment`_ then the credentials and project ID\n are obtained from the `Metadata Service`_.\n 5. If no credentials are found,\n :class:`~google.auth.exceptions.DefaultCredentialsError` will be raised.\n\n .. _Application Default Credentials: https://developers.google.com\\\n /identity/protocols/application-default-credentials\n .. _Google Cloud SDK: https://cloud.google.com/sdk\n .. _App Engine standard environment: https://cloud.google.com/appengine\n .. _App Identity Service: https://cloud.google.com/appengine/docs/python\\\n /appidentity/\n .. _Compute Engine: https://cloud.google.com/compute\n .. _App Engine flexible environment: https://cloud.google.com\\\n /appengine/flexible\n .. _Metadata Service: https://cloud.google.com/compute/docs\\\n /storing-retrieving-metadata\n\n Example::\n\n import google.auth\n\n credentials, project_id = google.auth.default()\n\n Args:\n scopes (Sequence[str]): The list of scopes for the credentials. If\n specified, the credentials will automatically be scoped if\n necessary.\n request (google.auth.transport.Request): An object used to make\n HTTP requests. This is used to detect whether the application\n is running on Compute Engine. If not specified, then it will\n use the standard library http client to make requests.\n\n Returns:\n Tuple[~google.auth.credentials.Credentials, Optional[str]]:\n the current environment's credentials and project ID. Project ID\n may be None, which indicates that the Project ID could not be\n ascertained from the environment.\n\n Raises:\n ~google.auth.exceptions.DefaultCredentialsError:\n If no credentials were found, or if the credentials found were\n invalid.\n \"\"\"\n from google.auth.credentials import with_scopes_if_required\n\n explicit_project_id = os.environ.get(\n environment_vars.PROJECT,\n os.environ.get(environment_vars.LEGACY_PROJECT))\n\n checkers = (\n _get_explicit_environ_credentials,\n _get_gcloud_sdk_credentials,\n _get_gae_credentials,\n lambda: _get_gce_credentials(request))\n\n for checker in checkers:\n credentials, project_id = checker()\n if credentials is not None:\n credentials = with_scopes_if_required(credentials, scopes)\n return credentials, explicit_project_id or project_id\n\n raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)\n","repo_name":"kiwibrowser/src","sub_path":"tools/swarming_client/third_party/google/auth/_default.py","file_name":"_default.py","file_ext":"py","file_size_in_byte":9957,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"36025648750","text":"import numpy as np\r\nimport cv2\r\n\r\n#bitwise op and or xor not\r\n\r\nimg1=np.zeros((250,500,3),np.uint8)\r\nimg1 = cv2.rectangle(img1,(384,0),(510,123),(255,255,255),-1)\r\nimg2 =cv2.imread(r\"C:\\Users\\User\\Desktop\\Artificial Intelligence\\forpractice7_1.png\",1)\r\nimg1 =cv2.resize(img1,(520,520))\r\nimg2=cv2.resize(img2,(520,520))\r\n#bitAnd=cv2.bitwise_and(img1,img2)\r\n#bitOr=cv2.bitwise_or(img1,img2)\r\n#bitXor=cv2.bitwise_xor(img1,img2)\r\nbitNot1=cv2.bitwise_not(img1)\r\nbitNot2=cv2.bitwise_not(img2)\r\n\r\ncv2.imshow(\"W1\",img1)\r\ncv2.imshow(\"W2\",img2)\r\n#cv2.imshow(\"Window\",bitAnd)\r\n#cv2.imshow(\"Window\",bitOr)\r\n#cv2.imshow(\"Window\",bitXor)\r\ncv2.imshow(\"bitnot1\",bitNot1)\r\ncv2.imshow(\"bitnot2\",bitNot2)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n","repo_name":"SabinaAcamova/OpenCV","sub_path":"Lesson3/Lesson3Practice7.py","file_name":"Lesson3Practice7.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13131604733","text":"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport random\nimport tensorflow as tf\nfrom transformer.layers.multi_head_attention import MultiHeadAttention\n\n\nd_model = 512\nh = 8\nbatch_size = 64\nq_length = 100\nk_length = 200 \nv_length = 200\nd_k = 64\nd_v = 64\n\n\nmultiHeadAttention = MultiHeadAttention(d_model, h)\n\nx = tf.constant([\n [0., 1., 2., 2., 5., 1.],\n [2., 2., 4., 2., 0., 3.],\n [0., 2., 4., 2., 1., 2.],\n], dtype=tf.float32) # (3, 6)\n\n\nclass MultiHeadAttentionTest(tf.test.TestCase):\n def test_scaled_dot_product_attention(self):\n out, attention_weights = multiHeadAttention.scaled_dot_product_attention(x, x, x)\n self.assertEqual(\n attention_weights.shape,\n (x.shape[0], x.shape[0])\n )\n\n self.assertEqual(\n out.shape,\n x.shape\n )\n\n def test_splitting_head(self):\n qw = tf.ones((batch_size, q_length, d_model))\n xs = multiHeadAttention.splitting_head(qw)\n self.assertEqual(\n xs.shape,\n (batch_size, h, q_length, d_model // h)\n )\n\n def test_call(self):\n q = tf.ones((batch_size, q_length, d_k))\n k = tf.ones((batch_size, k_length, d_k))\n v = tf.ones((batch_size, v_length, d_v))\n final, attention_weights = multiHeadAttention(q, k, v)\n\n self.assertEqual(\n final.shape, (batch_size, q_length, d_model)\n )\n hd_v = d_model // h\n self.assertEqual(\n attention_weights.shape, (batch_size, h, q_length, k_length)\n )","repo_name":"bangoc123/transformer","sub_path":"transformer/tests/layers/multi_head_attention_test.py","file_name":"multi_head_attention_test.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"52"} +{"seq_id":"9260296701","text":"import time\r\nimport tkinter\r\nimport bestface\r\nimport face_rec\r\nfrom threading import Thread\r\nfrom PIL import Image, ImageTk\r\nfrom tkinter.filedialog import askopenfilename\r\n\r\n# START GUI DEFINITIONS\r\n# main window\r\ntop = tkinter.Tk()\r\ntop.title(\"Team Shaspasms\")\r\n# button functions\r\n\r\n\r\ndef button_SelectFile():\r\n filename = askopenfilename()\r\n txt_fn.delete('1.0', tkinter.END)\r\n txt_fn.insert(tkinter.END, filename)\r\n\r\n\r\ndef button_Rec():\r\n predictions = face_rec.predict(\r\n found_face_raw, model_path=\"D:/School/Notes/408G/Final Project/face_detector/knn_examples/trained_knn_model.txt\")\r\n for name, (top, right, bottom, left) in predictions:\r\n lbl_fc['text'] = \"Identity: \" + name\r\n\r\n\r\ndef button_Go():\r\n def callback():\r\n global found_face_raw, found_face\r\n found_face_raw, framenum = test.run(\r\n filepath=txt_fn.get('1.0', 'end-1c'))\r\n # If a face is found in the clip\r\n if (framenum > 0):\r\n # Create a photo object that can be placed into a canvas\r\n found_face = Image.fromarray(found_face_raw)\r\n found_face = ImageTk.PhotoImage(found_face)\r\n canvas_bf.create_image(100, 100, image=found_face, anchor='center')\r\n lbl_fc['text'] = 'The best face was found on frame #' + \\\r\n str(framenum)\r\n top.title(\"Team Shaspasms\")\r\n # If a face wasn't found in the clip\r\n else:\r\n lbl_fc['text'] = 'NO FACES FOUND'\r\n # Stop the thread\r\n t.stopped = True\r\n\r\n def update_progress():\r\n def get_data():\r\n cur_time = time.time()\r\n cur_frame = test.get_progress()\r\n elapsed = cur_time - start_time\r\n \r\n lbl_pg['text'] = 'Frame progress: ' + \\\r\n str(cur_frame) + '/' + str(max_frames) + '. Elapsed time: ' + str(float(\"{0:.2f}\".format(elapsed))) + 's' + ', FPS: ' + str(int(cur_frame / ((float(elapsed)+0.1))))\r\n\r\n start_time = time.time()\r\n max_frames = 0\r\n while max_frames == 0:\r\n time.sleep(.25)\r\n max_frames = test.get_maxframes()\r\n while t.is_alive():\r\n get_data()\r\n time.sleep(1)\r\n get_data()\r\n\r\n r.stopped = True\r\n top.title(\"WORKING...\")\r\n t = Thread(target=callback)\r\n t.start()\r\n\r\n r = Thread(target=update_progress)\r\n r.start()\r\n\r\n\r\n# widgets\r\ntxt_fn = tkinter.Text(top, height=3, width=30)\r\ntxt_fn.grid(row=0, column=0)\r\n\r\nbtn_sf = tkinter.Button(top, text=\"Choose...\", command=button_SelectFile)\r\nbtn_sf.grid(row=0, column=1)\r\n\r\ncanvas_bf = tkinter.Canvas(top, width=200, height=200)\r\ncanvas_bf.grid(row=1, column=0)\r\n\r\nbtn_go = tkinter.Button(top, text=\"Go\", command=button_Go)\r\nbtn_go.grid(row=0, column=2)\r\n\r\nbtn_rec = tkinter.Button(top, text=\"Recognize\", command=button_Rec)\r\nbtn_rec.grid(row=0, column=3)\r\n\r\nlbl_fc = tkinter.Label(top)\r\nlbl_fc.grid(row=2, column=0)\r\n\r\nlbl_pg = tkinter.Label(top)\r\nlbl_pg.grid(row=3, column=0)\r\n\r\n\r\n# END GUI DEFINITIONS\r\n\r\ntest = bestface.BF_object()\r\n\r\ntop.mainloop()\r\n","repo_name":"mrosenf2/umd408G","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37217700821","text":"#\n# @lc app=leetcode id=82 lang=python3\n#\n# [82] Remove Duplicates from Sorted List II\n#\n# https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/\n#\n# algorithms\n# Medium (32.25%)\n# Total Accepted: 175.3K\n# Total Submissions: 537.7K\n# Testcase Example: '[1,2,3,3,4,4,5]'\n#\n# Given a sorted linked list, delete all nodes that have duplicate numbers,\n# leaving only distinct numbers from the original list.\n# \n# Example 1:\n# \n# \n# Input: 1->2->3->3->4->4->5\n# Output: 1->2->5\n# \n# \n# Example 2:\n# \n# \n# Input: 1->1->1->2->3\n# Output: 2->3\n# \n# \n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n# method 1 这算是最笨的\n# class Solution:\n# def deleteDuplicates(self, head: ListNode) -> ListNode:\n# if not head or not head.next:\n# return head \n# pHead = ListNode(-1)\n# pHead.next = head\n# p1 = pHead\n# while p1.next and p1.next.next:\n# if p1.next.val != p1.next.next.val:\n# p1 = p1.next\n# else:\n# p2 = p1.next\n# while p2 and p2.val==p1.next.val:\n# p2 = p2.next\n# p1.next = p2\n# return pHead.next\n# method 2 定义一个函数f(i,i+1,..,j)返回头结点,如果i!=i+1,保留i, \n# 如果i==i+1==...==j-1, 舍弃i...j-1\n# 神操作\n# class Solution:\n# def deleteDuplicates(self, head: ListNode) -> ListNode:\n# return self.h(head)\n \n# def h(self, head):\n# if not head or not head.next:\n# return head\n# if head.val != head.next.val:\n# head.next = self.h(head.next)\n# return head\n# else:\n# x = head.val\n# while head and head.val == x:\n# head = head.next\n# return self.h(head)\n \n\n# class Solution(object):\n# def deleteDuplicates(self, head):\n# return self.h(head)\n\n# def h(self, head):\n# if not head or not head.next: return head\n# if head.val != head.next.val:\n# head.next = self.h(head.next)\n# return head\n# x = head.val\n# cur = head.next\n# while cur and x == cur.val:\n# cur = cur.next\n# return self.h(cur)\n\n# method 3 这个思路和 method 2 类似,主要也是f,不同点在于处理head相同的时候\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n if not head:\n return head\n cur, is_head = head.next, False\n while cur and cur.val == head.val:\n cur = cur.next\n is_head = True\n head.next = self.deleteDuplicates(cur)\n return head.next if is_head else head\n\n","repo_name":"TJJTJJTJJ/leetcode","sub_path":"82.remove-duplicates-from-sorted-list-ii.py","file_name":"82.remove-duplicates-from-sorted-list-ii.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8827871045","text":"import os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport imageio\nimport skimage.color\nfrom scipy import signal, ndimage\n\n\ndef read_image(filename, representation):\n \"\"\"\n This function reads an image file and converts it into a given representation.\n :param filename: The filename of an image on disk.\n :param representation: Representation code, either 1 or 2 defining whether the output should be a grayscale\n image (1) or an RGB image (2).\n :return: This function returns an image.\n \"\"\"\n image = imageio.imread(filename)\n if len(image.shape) == 3 and representation == 1:\n image = skimage.color.rgb2gray(image)\n if image.max() > 1:\n image = np.divide(image, 255)\n return image.astype(np.float64)\n\n\ndef build_gaussian_pyramid(im, max_levels, filter_size):\n \"\"\"\n This function build the gaussian pyramid of the given image.\n :param im: A grayscale image with double values in [0, 1].\n :param max_levels: The maximal number of levels in the resulting pyramid\n :param filter_size: The size of the Gaussian filter\n :return: The resulting pyramid as a standard python array, the filter vector.\n \"\"\"\n if filter_size == 1:\n filter_vec = np.array([1]).reshape(1, 1)\n else:\n a = np.array([1, 1]).reshape(1, 2)\n filter_vec = a\n while filter_vec.shape[1] < filter_size:\n filter_vec = signal.convolve2d(a, filter_vec)\n filter_vec = filter_vec / filter_vec.sum()\n pry = [im]\n i = 1\n while i < max_levels and pry[-1].shape[0] > 16 and pry[-1].shape[1] > 16:\n temp = ndimage.filters.convolve(pry[-1], filter_vec)\n temp = ndimage.filters.convolve(temp, np.transpose(filter_vec))\n\n pry.append(temp[::2, ::2])\n i += 1\n return pry, filter_vec\n\n\ndef _expand(layer, filter_vec):\n a = np.zeros((layer.shape[0] * 2, layer.shape[1] * 2))\n a[::2, ::2] = layer\n a = ndimage.filters.convolve(a, 2 * filter_vec)\n return ndimage.filters.convolve(a, np.transpose(2 * filter_vec))\n\n\ndef build_laplacian_pyramid(im, max_levels, filter_size):\n \"\"\"\n This function build the laplacian pyramid of the given image.\n :param im: A grayscale image with double values in [0, 1].\n :param max_levels: The maximal number of levels in the resulting pyramid\n :param filter_size: The size of the Gaussian filter\n :return: The resulting pyramid as a standard python array, the filter vector.\n \"\"\"\n gauss_pry, filter_vec = build_gaussian_pyramid(im, max_levels, filter_size)\n pry = []\n for i in range(len(gauss_pry) - 1):\n g_i1_expand = _expand(gauss_pry[i + 1], filter_vec)\n pry.append(np.subtract(gauss_pry[i], g_i1_expand))\n pry.append(gauss_pry[-1])\n return pry, filter_vec\n\n\ndef laplacian_to_image(lpyr, filter_vec, coeff):\n \"\"\"\n This func o implement the reconstruction of an image from its Laplacian Pyramid.\n :param lpyr: The Laplacian pyramid.\n :param filter_vec: The filter vec of the pyramid.\n :param coeff: The corresponding coefficient of the pyramid.\n :return: An image.\n \"\"\"\n expand_layer = coeff[-1] * lpyr[-1]\n for i in range(len(lpyr) - 1, 0, -1):\n expand = _expand(expand_layer, filter_vec)\n expand_layer = np.add(expand, coeff[i - 1] * lpyr[i - 1])\n return expand_layer\n\n\ndef _stretch_values(matrix):\n return (matrix - matrix.min()) / (matrix.max() - matrix.min())\n\n\ndef render_pyramid(pyr, levels):\n \"\"\"\n :param pyr: Either a Gaussian or Laplacian pyramid.\n :param levels: The number of levels in pyr.\n :return: A single black image in which the pyramid levels of the given\n pyramid pyr are stacked horizontally\n \"\"\"\n num_of_layer = min(levels, len(pyr))\n render_pyr = pyr[0]\n for i in range(1, num_of_layer):\n current_layer = _stretch_values(np.copy(pyr[i]))\n current_layer.resize(render_pyr.shape[0], current_layer.shape[1])\n render_pyr = np.concatenate((render_pyr, current_layer), axis=1)\n return render_pyr\n\n\ndef display_pyramid(pyr, levels):\n \"\"\"\n This function display the render pyramid.\n :param pyr: Either a Gaussian or Laplacian pyramid.\n :param levels: The number of levels in pyr.\n \"\"\"\n rend_pyr = render_pyramid(pyr, levels)\n plt.imshow(rend_pyr)\n plt.show()\n\n\ndef pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask):\n \"\"\"\n :param im1: The first grayscale images to be blended.\n :param im2: The second Grayscale images to be blended.\n :param mask: A boolean mask containing True and False representing which\n parts of im1 and im2 should appear in the resulting im_blend.\n :param max_levels: Parameter that used when generating the Gaussian and Laplacian pyramids.\n :param filter_size_im: The size of the Gaussian filter which defining the filter used in\n the construction of the Laplacian pyramids of im1 and im2.\n :param filter_size_mask: The size of the Gaussian filter which defining the filter used in\n the construction of the Gaussian pyramids of the mask.\n :return: The blended image of im1 and im2 using the mask.\n \"\"\"\n l1, l1_filter = build_laplacian_pyramid(im1, max_levels, filter_size_im)\n l2, l2_filter = build_laplacian_pyramid(im2, max_levels, filter_size_im)\n gm, gm_filter = build_gaussian_pyramid(mask.astype(np.float64), max_levels, filter_size_mask)\n levels = len(l1)\n im_out_pyr = []\n for i in range(levels):\n im_out_pyr.append(gm[i] * l1[i] + (1 - gm[i]) * l2[i])\n return np.clip(laplacian_to_image(im_out_pyr, l1_filter, [1] * levels), 0, 1)\n\n\ndef relpath(filename):\n return os.path.join(os.path.dirname(__file__), filename)\n\n\ndef _example_helper(im1, im2, mask):\n im1 = read_image(relpath(im1), 2)\n im2 = read_image(relpath(im2), 2)\n mask = read_image(relpath(mask), 1)\n mask = np.round(mask).astype(bool)\n r = pyramid_blending(im1[::, ::, 0], im2[::, ::, 0], mask, 3, 5, 5)\n g = pyramid_blending(im1[::, ::, 1], im2[::, ::, 1], mask, 3, 5, 5)\n b = pyramid_blending(im1[::, ::, 2], im2[::, ::, 2], mask, 3, 5, 5)\n bland_image = np.dstack((r, g, b))\n i, j = plt.subplots(2, 2)\n j[0, 0].imshow(im1, cmap='gray')\n j[0, 1].imshow(im2, cmap='gray')\n j[1, 0].imshow(mask, cmap='gray')\n j[1, 1].imshow(bland_image, cmap='gray')\n plt.show()\n return im1, im2, mask, bland_image\n\n\ndef blending_example1():\n im2 = 'two2.jpg'\n im1 = 'one2.jpg'\n mask = 'mask.png'\n return _example_helper(im1, im2, mask)\n\n\ndef blending_example2():\n im1 = 'spongbob.png'\n im2 = 'video-obama-superJumbo_2048x1024.jpg'\n mask = 'spongbob_mask.png'\n return _example_helper(im1, im2, mask)\n\n\n","repo_name":"israelbenattar/ImagePyramidsAndPyramid-Blending","sub_path":"sol3.py","file_name":"sol3.py","file_ext":"py","file_size_in_byte":6778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37934523859","text":"import os, sys, time, ljqpy, math\r\nimport tensorflow as tf\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\r\n\r\nimport bert_tools as bt\r\n\r\ndef LoadCoNLLFormat(fn, tag_column=-1, has_headline=False):\r\n\tdatax, datay = [], []\r\n\ttempx, tempy = [], []\r\n\twith open(fn, encoding='utf-8') as fin:\r\n\t\tfor lln in fin:\r\n\t\t\tlln = lln.strip()\r\n\t\t\tif has_headline or lln.startswith('-DOCSTART-'):\r\n\t\t\t\thas_headline = False; continue\r\n\t\t\tif lln == '':\r\n\t\t\t\tif len(tempx) >= 1:\r\n\t\t\t\t\tdatax.append(tempx); datay.append(tempy)\r\n\t\t\t\ttempx, tempy = [], []\r\n\t\t\telse:\r\n\t\t\t\titems = lln.split()\r\n\t\t\t\ttempx.append(items[0])\r\n\t\t\t\ttempy.append(items[tag_column])\r\n\tif len(tempx) >= 1:\r\n\t\tdatax.append(tempx); datay.append(tempy)\r\n\treturn datax, datay\r\n\r\n\r\nmaxlen = 100\r\n\r\ndatadir = '../dataset/chsner_char-level'\r\nxys = [LoadCoNLLFormat(os.path.join(datadir, '%s.txt') % tp) for tp in ['train', 'test']]\r\n\r\nid2y = {}\r\nfor yy in xys[0][1]:\r\n\tfor y in yy: id2y[y] = id2y.get(y, 0) + 1\r\nid2y = [x[0] for x in ljqpy.FreqDict2List(id2y)]\r\ny2id = {v:k for k,v in enumerate(id2y)}\r\n\r\ndef convert_data(df):\r\n\ttext = [' '.join(t[:maxlen]) for t in df[0]]\r\n\tlabel = [[0]+[y2id.get(x, 0) for x in t[:maxlen-1]] for t in df[1]]\r\n\treturn text, label\r\n(train_text, train_label), (test_text, test_label) = map(convert_data, xys)\r\n\r\n# must post padding!\r\npad_func = lambda x:np.expand_dims(tf.keras.preprocessing.sequence.pad_sequences(x, maxlen=maxlen, padding='post', truncating='post'), -1)\r\ntrain_label, test_label = map(pad_func, [train_label, test_label])\r\n\r\ntrain_inputs, test_inputs = map(lambda x:bt.convert_sentences(x, maxlen), [train_text, test_text])\r\n\r\nprint(train_inputs[0].shape, train_label.shape)\r\nprint(train_inputs[0][0])\r\nprint(train_inputs[1][0])\r\n\r\n\r\nbert_path = '../tfhub/chinese_roberta_wwm_ext_L-12_H-768_A-12'\r\n\r\nfrom tensorflow.keras.layers import *\r\nfrom tensorflow.keras.callbacks import Callback\r\nfrom bert4keras.backend import keras, K\r\nfrom bert4keras.layers import ConditionalRandomField\r\nfrom bert4keras.models import build_transformer_model\r\nfrom bert4keras.snippets import ViterbiDecoder, to_array\r\nbert = build_transformer_model(bert_path, return_keras_model=False) \r\n\r\noutput = Dense(len(y2id))(bert.model.output)\r\nCRF = ConditionalRandomField(lr_multiplier=1000)\r\noutput = CRF(output)\r\n\r\nmodel = tf.keras.models.Model(inputs=bert.model.input, outputs=output)\r\n\r\nbt.lock_transformer_layers(bert, 8)\r\n\r\nepochs = 2\r\nbatch_size = 32\r\ntotal_steps = epochs*train_inputs[0].shape[0]//batch_size\r\noptimizer = bt.get_suggested_optimizer(1e-4, total_steps=total_steps)\r\nmodel.compile(optimizer, loss=CRF.sparse_loss, metrics=[CRF.sparse_accuracy])\r\n\r\n#model.summary()\r\n\r\nfrom seqeval.metrics import f1_score, accuracy_score, classification_report\r\n\r\nclass NamedEntityRecognizer(ViterbiDecoder):\r\n\tdef recognize(self, text):\r\n\t\tlabels = self.decode(nodes)\r\n\t\treturn [labels]\r\n\r\n\r\nNER = NamedEntityRecognizer(trans=K.eval(CRF.trans), starts=[0], ends=[0])\r\n\r\n\r\nclass TestCallback(Callback):\r\n\tdef __init__(self, XY, model, tags):\r\n\t\tself.X, self.Y = XY\r\n\t\tself.Y = np.squeeze(self.Y, -1)\r\n\t\tself.smodel = model\r\n\t\tself.tags = tags\r\n\t\tself.best_f1 = 0\r\n\tdef on_epoch_end(self, epoch, logs = None):\r\n\t\t# self.model is auto set by keras\r\n\t\tyt, yp = [], []\r\n\t\ttrans = K.eval(CRF.trans)\r\n\t\tNER.trans = trans\r\n\t\tpred = self.smodel.predict(self.X, batch_size=16)\r\n\r\n\t\tfor i, yseq in enumerate(self.Y):\r\n\t\t\tlabels = NER.decode(pred[i])\r\n\t\t\tyt.append([self.tags[z] for z in labels])\r\n\t\t\typ.append([self.tags[z] for z in yseq])\r\n\r\n\t\tf1 = f1_score(yt, yp)\r\n\t\tself.best_f1 = max(self.best_f1, f1)\r\n\t\taccu = accuracy_score(yt, yp)\r\n\t\tprint('\\naccu: %.4f F1: %.4f BestF1: %.4f\\n' % (accu, f1, self.best_f1))\r\n\t\tprint(classification_report(yt, yp))\r\n\r\ntest_cb = TestCallback((test_inputs, test_label), model, id2y)\r\nmodel.fit(train_inputs, train_label, epochs=epochs, batch_size=batch_size,\r\n\t\t validation_data=(test_inputs, test_label), callbacks=[test_cb])\r\n\r\ntrans = K.eval(CRF.trans)\r\nNER.trans = trans\r\nY = model([x[:8] for x in test_inputs]).numpy()\r\nfor ii in range(8):\r\n\ttlist = [id2y[x] for x in NER.decode(Y[ii])][1:]\r\n\tprint(' '.join(['%s/%s'%x for x in zip(test_text[ii].split(), tlist)]))\r\n\r\n\r\n#Epoch 1/2\r\n#1584/1584 [==============================] - ETA: 0s - loss: 1.6699 - sparse_accuracy: 0.9542 \r\n#accu: 0.9970 F1: 0.9427 BestF1: 0.9427\r\n#\r\n# precision recall f1-score support\r\n#\r\n# ORG 0.91 0.90 0.91 1333\r\n# PER 0.95 0.96 0.95 1957\r\n# LOC 0.94 0.97 0.95 2798\r\n#\r\n#micro avg 0.93 0.95 0.94 6088\r\n#macro avg 0.93 0.95 0.94 6088\r\n#1584/1584 [==============================] - 421s 266ms/step - loss: 1.6699 - sparse_accuracy: 0.9542 - val_loss: 0.3938 - val_sparse_accuracy: 0.9581 \r\n#Epoch 2/2\r\n#1584/1584 [==============================] - ETA: 0s - loss: 0.2321 - sparse_accuracy: 0.9569 \r\n#accu: 0.9973 F1: 0.9458 BestF1: 0.9458\r\n#\r\n# precision recall f1-score support\r\n#\r\n# ORG 0.91 0.92 0.91 1318\r\n# PER 0.94 0.96 0.95 1953\r\n# LOC 0.96 0.96 0.96 2873\r\n#\r\n#micro avg 0.94 0.95 0.95 6144\r\n#macro avg 0.94 0.95 0.95 6144\r\n#1584/1584 [==============================] - 453s 286ms/step - loss: 0.2321 - sparse_accuracy: 0.9569 - val_loss: 0.3623 - val_sparse_accuracy: 0.9621 \r\n","repo_name":"fcihraeipnusnacwh/MRC-CE","sub_path":"Version 2/BERT_tf2/exp_bert_cn_sl.py","file_name":"exp_bert_cn_sl.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"38070471080","text":"# def FindFile(filename,value):\n\n# \ttry:\n# \t\tdirlist = os.listdir(filename)\n# \t\tfor x in dirlist:\n# \t\t\ttmp = os.path.join(filename,x)\n# \t\t\tif os.path.isdir(tmp):\n# \t\t\t\tFindFile(tmp,value)\n# \t\t\telif os.path.isfile(tmp):\n# \t\t\t\tif value in x:\n# \t\t\t\t\tprint(tmp)\n# \texcept Exception as e:\n# \t\tprint(e)\n\n\n# FindFile('.','my')\n\nimport os\n\ndef FindFile(filename,str):\n\n\ttry:\n\t\tdirlist = os.listdir(filename)\n\t\tfor x in dirlist:\n\t\t\ttmp = os.path.join(filename,x)\n\t\t\tif os.path.isdir(tmp):\n\t\t\t\tFindFile(tmp,str)\n\t\t\tif os.path.isfile(tmp):\n\t\t\t\tif str in x:\n\t\t\t\t\tprint(x)\n\texcept Exception as e:\n\t\tprint(e)\n\n\n\ndef checkFile(path,str):\n\n\t#\tstep2:查找文件名包含指定字符串的文件,并打印出相对路径\n\t\tL = os.listdir(path)\n\t\t\n\t\tfor x in L:\n\t\t\tnewpath = os.path.join(path,x)\n\t\t\tif os.path.isfile(newpath) and str in x:\n\t\t\t\tprint(x)\n\t\t\tif os.path.isdir(newpath):\n\t\t\t\tcheckFile(newpath,str)\n\n\n\n\t# \tL1 = [x for x in os.listdir(path) if os.path.isfile(x) and x.find(str)!=-1]\n\t# \tfor x in L1:\n\t# \t\tprint(x)\n\n\t# #\tstep1:列出当前目录下的所有目录的子文件\n\t# \tL2 = [x for x in os.listdir(path) if os.path.isdir(x)]\n\n\t# \t# if len(L2)==0:\n\t# \t# \treturn\n\n\t# \t#print('the length is %d' % len(L2))\n\t# #\tif(len(L2)!=0):\n\t# \tfor x in L2:\n\t# \t\tnewpath = os.path.join(path,x)\n\t# \t#\tprint(newpath)\n\t# \t\tcheckFile(newpath,str)\n\nprint('\\nHere is the checkFile funtion prints:')\ncheckFile('e:','my')\n#FindFile('e:','prime')\nprint('\\nHere is the FindFile function prints:')\nFindFile('e:','my')\n\n","repo_name":"lierfengmei/pyworks","sub_path":"openFile.py","file_name":"openFile.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39132886665","text":"from torch.nn import Module\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.optim import Optimizer\r\nfrom torch import Tensor,save\r\nimport os\r\nfrom tqdm import tqdm\r\nfrom collections.abc import Callable\r\nimport wandb\r\n\r\ndef train_model(config:dict,model:Module,data_loader:DataLoader,loss_func:Module,optimizer:Optimizer,epoch_num:int,output_process:Callable[[Tensor],Tensor]) -> int:\r\n\r\n loss_total = 0\r\n model.train()\r\n model.to(config['device'])\r\n with tqdm(total=len(data_loader.dataset),desc='Epoch {}'.format(epoch_num)) as pbar:\r\n for index,data_pair in enumerate(data_loader):\r\n featrues,labels = data_pair\r\n featrues:Tensor = featrues.to(config['device'])\r\n labels:Tensor = labels.to(config['device'])\r\n\r\n pres = model.forward(featrues)\r\n\r\n pres = output_process(pres).float()\r\n labels = output_process(labels).float()\r\n\r\n batch_loss:Tensor = loss_func(pres,labels)\r\n\r\n if config['DEBUG']:\r\n print(\"pres and labels : \",pres,labels)\r\n\r\n optimizer.zero_grad()\r\n batch_loss.backward()\r\n optimizer.step()\r\n\r\n pbar.update(featrues.shape[0])\r\n\r\n loss_total += batch_loss.item()\r\n\r\n if config['save']:\r\n os.path.exists('checkpoints') or os.mkdir('checkpoints')\r\n save(model.state_dict(),('checkpoints/'+config['save_dir']).format(epoch_num,loss_total))\r\n\r\n if config['enable_wandb']:\r\n wandb.log({\r\n 'epoch': epoch_num,\r\n 'loss': loss_total\r\n })\r\n\r\n return loss_total\r\n\r\n\r\n","repo_name":"geraltigas/ML_code_and_utils","sub_path":"myutils/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15524332915","text":"class User:\n def __init__(self, username, id):\n print(f\"{username} is being created...\")\n print(f\"{username} launched\")\n self.username = username\n self.id = id\n self.followers = 0\n self.following = 0\n\n def follow(self, user):\n user.followers += 1\n self.following += 1\n\nuser_1 = User(\"cemodan\", \"01\")\nuser_2 = User(\"cantinflas\", \"02\")\n\nuser_1.follow(user_2)\nprint(user_2.followers)","repo_name":"ODCenteno/python_100days","sub_path":"day_17_start/theory.py","file_name":"theory.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71209313766","text":"import qt\n\n\nclass IterableAttributeMeta(type):\n \"\"\"\n Metaclass allowing to iterate on the public attributes.\n \"\"\"\n\n def __iter__(self):\n for attr in dir(self):\n if not attr.startswith(\"__\"):\n yield attr\n\n def __getitem__(self, attr):\n if not attr.startswith(\"__\"):\n return getattr(self, attr)\n\n\nclass DefaultSettings(metaclass=IterableAttributeMeta):\n \"\"\"\n Default settings of the application.\n Each setting will be accessible through SlicerLite/{parameter_name}\n \"\"\"\n LastOpenedDirectory = \"\"\n DisplayScalarRange = 0.8\n\n\nclass SettingsMeta(type):\n \"\"\"\n Meta type for the application settings.\n Initializes the .ini settings if they are not present and converts the values to float by default.\n \"\"\"\n\n def __new__(mcs, *args, **kwargs):\n x = super().__new__(mcs, *args, **kwargs)\n for k in DefaultSettings:\n if not qt.QSettings().contains(f\"SlicerLite/{k}\"):\n qt.QSettings().setValue(f\"SlicerLite/{k}\", DefaultSettings[k])\n return x\n\n def __dir__(self):\n return [k for k in DefaultSettings]\n\n def __getattr__(cls, attr):\n if attr not in DefaultSettings:\n raise AttributeError(f\"Class doesn't contain {attr}\")\n value = qt.QSettings().value(f\"SlicerLite/{attr}\")\n try:\n defaultType = type(getattr(DefaultSettings, attr))\n return defaultType(value)\n except ValueError:\n return value\n\n def __setattr__(self, key, value):\n if key not in DefaultSettings:\n raise AttributeError(f\"Class doesn't contain {key}\")\n qt.QSettings().setValue(f\"SlicerLite/{key}\", value)\n\n\nclass SlicerLiteSettings(metaclass=SettingsMeta):\n \"\"\"\n Class managing the settings of the application.\n The settings are read from Settings/DefaultSettings.ini file.\n \"\"\"\n pass\n","repo_name":"KitwareMedical/SlicerLiteExtension","sub_path":"SlicerLite/SlicerLiteLib/Settings.py","file_name":"Settings.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39781582770","text":"# Exercise 1\n#def push_first_odd_back(lst):\n\t#test = lst[:]\n\t#i = 0\n\t#while lst == test and i < len(lst):\n\t\t#if lst[i]%2 == 1:\n\t\t\t#lst.append(lst[i])\n\t\t\t#lst.pop(i)\n\t\t#else:\n\t\t\t#i += 1\n\n#why does this break with [0, 0, 1]\n\ndef push_first_odd_back(lst):\n\ttest = lst[:]\n\tfor i in range(0, len(lst)):\n\t\tif test == lst and lst[i]%2 == 1:\n\t\t\tlst.append(lst[i])\n\t\t\tlst.pop(i)\n\n\n# Exercise 2\ndef flatten(lst):\n\tx = []\n\tfor i in range(0, len(lst)):\n\t\tx += lst[i]\n\tlst = x\n\treturn lst\n\n# Exercise 3.1\ndef squares_of_evens(lst):\n\treturn [x * x for x in lst if (x % 2 == 0)]\n\n# Exercise 3.2\ndef nth_power_of_evens(lst, n):\n return [x ** n for x in lst if (x % 2 == 0)]\n\n# Exercise 4\ndef substitute_base(string, old, new):\n\tanswer = [letter for letter in string]\n\tfor i in range(0, len(string)):\n\t\tif answer[i] == old:\n\t\t\tanswer[i] = new\n\treturn \"\".join(answer)\n\n# Exercise 5\ndef combine(lst):\n\tif str(lst[0]).isdigit() == True:\n\t\tx = 0\n\t\tfor i in range(0, len(lst)):\n\t\t\tx += lst[i]\n\telse:\n\t\tx = \"\".join(lst)\n\treturn x\n\n# Exercise 6\ndef base_freq(string):\n\tdata = [letter for letter in string]\n\tDNA = {}\n\tfor i in range(0, len(string)):\n\t\tif data[i] in DNA:\n\t\t\tDNA[data[i]] += 1\n\t\telse:\n\t\t\tDNA[data[i]] = 1\n\treturn DNA\n\n# Exercise 7.1\ndef substitute_chars(string, replacements):\n\tjumble = [letter for letter in string]\n\tfor i in range(0, len(string)):\n\t\tif jumble[i] in replacements:\n\t\t\tjumble[i] = replacements[jumble[i]]\n\treturn \"\".join(jumble)\n\n# Exercise 7.2\ndef invert_dict(original):\n\tx = list(original.keys())\n\tinvert = {}\n\tfor i in range(0, len(original)):\n\t\tinvert[original[x[i]]] = x[i]\n\treturn invert \n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"ventimdg/Snap-Python","sub_path":"PythonWork/Labs/Lab14/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13020636935","text":"from pymongo import MongoClient\nimport time\n\n\ndef get_user_category_choice(categories: list) -> int:\n user_choice = 0\n while user_choice < 1:\n print('Categorias disponíveis:')\n\n for i in range(1, len(categories)):\n print(f'{i} - {categories[i]}')\n\n try:\n user_choice = int(input('\\n Digite um número de categoria: '))\n print('')\n except ValueError:\n user_choice = 0\n\n if (user_choice < 1 or user_choice > len(categories) - 1):\n user_choice = 0\n print('\\n \\033[031mCategoria inválida\\033[0m \\n')\n time.sleep(1)\n\n return user_choice\n\n\nwith MongoClient() as client:\n db = client.library\n books = db.books\n\n categories_in_db = books.distinct('categories')\n user_choice = get_user_category_choice(categories_in_db)\n\n chosen_category = categories_in_db[user_choice]\n books_in_category = books.find({'categories': chosen_category})\n\n for book in books_in_category:\n print(book['title'])\n","repo_name":"PedroPA94/trybe-exercicios","sub_path":"cs/secao3/dia1/ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27857003760","text":"#!/usr/bin/env python2\n\"\"\"\nScript to move a client to different position on the screen.\n\ndefine possible positions in 'position_dict', execute them in 'snap_to'\n\nAssumes you have a taskbar on the top of the screen.\nIf not positions will be off a little - I'm looking into it but not too hard\nas it works for me at the moment.\n\nThis uses sockets to accept commands/messages, it allows future expansion\n(though for what I don't know), at the expense of a slightly more complicated\ncommand sending method.\n\nThis version uses 'select' to multiplex the server and accept connections this\ngives a nice solution to the 'stop' message.\n\nThis version is ready for extension and for importing specific functions.\n\"\"\"\n\nfrom Xlib import display\nfrom select import select\nimport atexit\nimport math\nimport os\nimport socket\nimport sys\n\n# TODO: Add option to take specific geometries from the fifo and move the\n# window to that. e.g. if line matches a regex, interpret it as a\n# geometry and snap to that.\n#\n# Account for multiple monitors - dsp.screen_count(), dsp.screen(num)\n# Maybe that the screen numbering is in order of left to right (or\n# something like that, then might know which value to add to the\n# geometries.\n#\n# Could also add option to move a bit at a time (+5/-5)\n# etc. Though it's not much of a benefit - this could allow batch files\n# to be cat'ed into the fifo as a set of motions to make (which seems\n# cool to me).\n#\n# Convert Xlib to python3 - will take a long time before I know what's\n# happening let alone be able to modify it.\n\n\n#\n# Functions to move/resize given position\n#\ndef snap_to(pos_func, window, geometrynow):\n \"\"\"Given 'position' function, move focussed client accordingly\"\"\"\n newy, newx = pos_func(geometrynow)\n window.configure(x=newx, y=newy)\n\n\ndef resize(size, window, edgepos, nowgeom):\n \"\"\"Given a 'size', resize client accordingly\"\"\"\n newheight, newwidth = size\n window.configure(height=newheight, width=newwidth)\n if nowgeom.x + newwidth > edgepos['right'] \\\n or nowgeom.y + newheight > edgepos['bot']:\n nowgeom.x -= max(nowgeom.x + newwidth - edgepos['right'], 0)\n nowgeom.y -= max(nowgeom.y + newheight - edgepos['bot'], 0)\n window.configure(x=nowgeom.x, y=nowgeom.y)\n\n\n#\n# Functions to convert percentage values to pixel values\n#\ndef find_edges_in_pixels(scr, borders):\n \"\"\"Convert the hard-coded borders to edges scaled to screen size\"\"\"\n # Assume want symmetry - if don't code it different later\n # Only partially accounted for status bar here (not accounted in SIZE of\n # border) - assume small enough that it doesn't matter.\n top = math.floor(scr.height_in_pixels * borders['top'])\n bottom = scr.height_in_pixels - top\n left = math.floor(scr.width_in_pixels * borders['side'])\n right = scr.width_in_pixels - left\n return {'top': top + taskbarheight, 'bot': bottom,\n 'left': left, 'right': right}\n\n\ndef create_actual_sizes(scr, abs_sizes):\n \"\"\"Convert the hard-coded sizes into sizes scaled to screen size\"\"\"\n def conv(tup):\n \"\"\"Convert percentages to pixels\"\"\"\n return (math.floor(tup[0] * scr.height_in_pixels),\n math.floor(tup[1] * scr.width_in_pixels))\n return {key: conv(val) for key, val in abs_sizes.iteritems()}\n\n\ndef find_geom(win, maxheight):\n \"\"\"Find position of window, account for reparenting window managers\"\"\"\n # taskbar stops the window reaching the top of the screen.\n # can't use y position - in case of titlebars - use height.\n # Uses global scre\n win2 = win.query_tree().parent\n while win2.get_geometry().height < maxheight:\n win = win2\n win2 = win2.query_tree().parent\n return win.get_geometry()\n\n\n#\n# Functions to get/use input\n#\ndef clearup(readers):\n \"\"\"Close all sockets (when multiplexing)\"\"\"\n for sock in readers:\n sock.shutdown(socket.SHUT_RDWR)\n sock.close()\n\n\ndef handle_socks(server, avail_now, tot_list, action):\n \"\"\"Function to handle selection of sockets when multiplexing\"\"\"\n for sock in avail_now:\n if sock is server:\n newconn, _ = sock.accept()\n tot_list.append(newconn)\n continue\n data = sock.recv(10).strip()\n if not data:\n tot_list.remove(sock)\n sock.shutdown(socket.SHUT_RDWR)\n sock.close()\n continue\n elif data == 'stop':\n return False\n action(data)\n return True\n\n\n#\n# If I want to make a daemon\n#\ndef close():\n # Could do this with the pid file, but seems simpler to use the command I\n # implemented for conveniance while debugging\n \"\"\"Sends a 'stop' signal to an open socket\"\"\"\n soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n soc.connect(('', 8732))\n except socket.error as err:\n # If no existing socket, don't need to do anything\n if err.errno == 111:\n return\n raise\n else:\n soc.send('stop\\n')\n finally:\n soc.close()\n\n\ndef createdaemon(pidfile='/tmp/snap_pid'):\n \"\"\"Implement UNIX double-fork procedure, see\n http://code.activestate.com/recipes/278731/\"\"\"\n # os._exit() is like sys.exit() but doesn't call registered signal\n # handlers or flush stdio buffers etc\n #\n # Check to see if there is already a running instance\n try:\n with open(pidfile, 'r') as pidf:\n pid = int(pidf.read().strip())\n except IOError:\n pid = None\n else:\n sys.stderr.write('Pid file exists - check if Daemon is running')\n sys.exit(1)\n\n # If os.fork doesn't work - leave the exceptions to raise themselves\n pid = os.fork()\n if pid > 0:\n # parent:- kill\n os._exit(0)\n\n # child:- decouple\n os.chdir('/')\n os.setsid()\n os.umask(0)\n pid = os.fork()\n\n # second fork means process is not a session leader, hence can't acquire\n # controlling tty and is reparented onto init (not required for this\n # program, but I'm only learning at the moment)\n if pid > 0:\n #parent:- kill\n os._exit(0)\n\n # Redirect standard file descriptors\n sys.stdout.flush()\n sys.stdin.flush()\n stdi = open(os.devnull, 'r')\n stdo = open(os.devnull, 'a+')\n stde = open(os.devnull, 'a+')\n\n os.dup2(stdi.fileno(), sys.stdin.fileno())\n os.dup2(stdo.fileno(), sys.stdout.fileno())\n os.dup2(stde.fileno(), sys.stderr.fileno())\n\n # make sure to remove pidfile when exiting\n atexit.register(os.remove, pidfile)\n\n with open(pidfile, 'a') as pidf:\n pidf.write(str(os.getpid()) + '\\n')\n\n\n#\n# Main\n#\ndef main(daemon=False, pidfile='/tmp/snap_pid'):\n \"\"\"Create display object, define position functions and edges, start main\n loop\"\"\"\n\n if daemon:\n createdaemon(pidfile)\n\n dsp = display.Display()\n scre = dsp.screen()\n maxheight = scre.height_in_pixels\n\n myborders = {'top': 0.008,\n 'side': 0.006}\n\n abstract_sizes = {'small': (0.35, 0.5),\n 'normal': (0.43, 0.44),\n 'long': (0.3, 0.987)}\n\n edges = find_edges_in_pixels(scre, myborders)\n sizes = create_actual_sizes(scre, abstract_sizes)\n\n position_dict = {'tl': lambda g: (edges['top'], edges['left']),\n 'tr': lambda g: (edges['top'], edges['right'] - g.width),\n 'bl': lambda g: (edges['bot'] - g.height, edges['left']),\n 'br': lambda g: (edges['bot'] - g.height,\n edges['right'] - g.width)\n }\n\n def change_func(inp):\n \"\"\"Handle the input and call relevant snap_to position\"\"\"\n # Here I assume that most of the time I'll receive a valid command\n # If that's not the case, move the defining of variables into the if\n # clause\n pos = inp.decode('utf-8').strip()\n window = dsp.get_input_focus().focus\n geometrynow = find_geom(window, maxheight)\n if pos in position_dict:\n snap_to(position_dict[pos], window, geometrynow)\n elif pos in sizes:\n resize(sizes[pos], window, edges, geometrynow)\n dsp.flush()\n\n serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serv.bind(('', 8732))\n serv.listen(4)\n readsocks = [serv]\n # Will profile later to see how the speed goes compared to fifo\n while True:\n # Don't want to write anything at the moment\n readables, _, _ = select(readsocks, [], [])\n if not handle_socks(serv, readables, readsocks, change_func):\n clearup(readables)\n break\n\n\nif __name__ == \"__main__\":\n # Check to see if we've been asked to halt\n taskbarheight = 15\n try:\n # try to close if have argument\n if sys.argv[1] == 'stop':\n close()\n elif sys.argv[1] == 'daemon':\n main(daemon=True)\n else:\n sys.stderr.write('Unknown command line argument\\n')\n sys.exit(1)\n except IndexError:\n main()\n\n\n# pymode:lint_ignore=W0212,C901\n","repo_name":"hardenedapple/useful-files","sub_path":"general/window_move_sockets.py","file_name":"window_move_sockets.py","file_ext":"py","file_size_in_byte":9127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32523225623","text":"import regex\n\nclass abnfserializer (object):\n \"\"\"Serializes abnf rules which are stretching over multiple lines und \\\n returns them as one line (one per abnf)-> so they could be processed \\\n by abnf/abnfs- \\objects.\n\n Example 1:\n You are reading a file line by line which contains abnf rules. \\\n Within this file lines may appear this way (there are likely even \\\n multiple of such lines):\n via-params = via-ttl / via-maddr\n / via-received / via-branch\n / via-extension\n Supported = ( \"Supported\" / \"k\" ) HCOLON\n [option-tag *(COMMA option-tag)]\n In this case the first abnf rule stretches across 3 lines.\n The abnf/abnfs class expects one line = exactly one abnf rule.\n So the above needs to be converted to one single line - this is\n what the class does, it takes it line by line and creates one\n single line for each rule -> so in the example above the output\n would be:\n via-params = via-ttl / via-maddr / via-received / via-branch \\\n / via-extension\n Supported = ( \"Supported\" / \"k\" ) HCOLON [option-tag *(COMMA \\\n option-tag)]\n As 2 seperate lines.\n\n Example 2:\n You are reading one file into one string/or as blocks (not careing)\n about line breaks.\n So you have something like:\n via-params = via-ttl / via-maddr \\r\\n / \\\n via-received / via-branch / via-extension \\r\\n Supported \\\n = ( \"Supported\" / \"k\" ) HCOLON [option-tag *(COMMA \\\n option-tag)]\n as one continues string.\n In the above case you have line breaks within the string, because \\\n there are 2 rules and both are even scattered over multiple lines.\n abnf and abnfs will require one abnf rule at one line.\n This class takes the one-liner and converts it into one line per \\\n abnf -> removing all the new lines and and intends.\n\n In every case those rules apply:\n - a new rule (or the part where the rule begins if split across \\\n lines) starts at \"the beginning\" of the line (in case of \\\n everything being one string, there should be no space after \\n \\\n or \\r\\n before the rule follows)-> so there are \\\n no spaces or any other blanks at the beginning\n - follow up parts of the same rule need to be intended -> so there \\\n needs to be at least be one space in front of the \"beginning of\n the line\" (in case of everything is one string, there should be \\\n a space after \\n or \\r\\n of the previouse entry)\n - parts of the same rule need to follow up immediately after the \\\n beginning of the rule. In case of everything is one string \\\n this means that after a rule starts within the string, all \\\n addtional parts of the same rule need to follow directly \\\n after the \\n or \\r\\n of the beginning of the rule. In case of\n multiple lines, after the line that starts the abnf, the follow \\\n up lines need to be the additional parts.\n\n Some names used in parameters of the methods:\n - line -> Single line; One abnf/part of a abnf in one line/string \\\n Example 1 is such a case\n - oneline -> Everything is one line; Multiple abnf or parts of it \\\n in one line/string. Example 2 is such a case.\n\n Methods:\n __init__ -> Initiating the object\n \"\"\"\n\n def __init__(self,linelist=None,onelinelist=None):\n \"\"\"Initiating the object\n\n Parameters:\n linelist -> Optional list of lines containing abnf/parts \\\n -> one entry could be just part of one abnf (there could ) \\\n not be parts of multiple abnf at one entry. Abnf parts \\\n splitted across lines need to be in the lines/entries \\\n follow to the begin of the abnf. Also entries being part of \\\n abnf need to intended (start with at least one space) -> \\\n except the first part. \\\n onelinelist -> Optional list of lines where one line contains \\\n multiple abnf\\parts of multiple abnf - single abnf or \\\n parts of abnf need to \\\n to be terminated by \\n or \\r\\n; Parts of abnf must \\\n follow directly after the begin of the abnf and start \\\n with at least one space (need to be intended).\n \"\"\"\n self._changed=False\n self._linelist=list()\n self._onelinelist=list()\n self._abnflines=list()\n\n if linelist:\n self._linelist.extend(linelist)\n elif onelinelist:\n self._onelinelist.append(oneline)\n\n def add_line(self,line=None,oneline=None):\n \"\"\"Add lines to the list\n\n Parameters:\n line -> Single line containing a part of a abnf/ a abnf - \\\n but not multiple parts or multiple abnf. \\\n Abnf parts splitted across lines need to be passed directly \\\n after the beginning of the passed abnf rule. \\\n Also entries being part of abnf need to intended \\\n (start with at least one space) -> except the first part. \\\n oneline -> Optional one list containing one or multiple string \\\n containing multiple abnf\\parts \\\n of multiple abnf - single abnf or parts of abnf need to \\\n to be terminated by \\n or \\r\\n; Parts of abnf must \\\n follow directly after the begin of the abnf and start \\\n with at least one space (need to be intended).\n \"\"\"\n if line:\n self._linelist.append(line)\n elif oneline:\n self._onelinelist.extend(oneline)\n else:\n raise ValueError(\"Either line or oneline needs to be given.\")\n\n def _oneline_to_seperatelines(self,onelinelist=None):\n \"\"\"Converts online-abnf (mulitple abnf or multiple parts of one abnf \\\n at the same line) to one abnf per line\n\n Parameter:\n onelinelist -> optional list with one-line-abnf entries; when \\\n not provided the global _onelinelist of the object will be \\\n used\n\n Return values:\n seperate_abnf_list -> list where one abnf or one part of a \\\n abnf is represented each by one line\n \"\"\"\n\n seperatelines=list()\n if onelinelist:\n onelinetoprocess=onelinelist\n else:\n onelinetoprocess=self._onelinelist\n for line in onelinetoprocess:\n for entry in regex.split('\\r\\n|\\n',line):\n seperatelines.append(entry)\n return seperatelines\n\n def _processlines(self):\n \"\"\"Processes the scattered abnf across multiple lines or the lines\n containing multiple abnf/abnf parts in one line stored in the object \\\n and stores a list where one entry is one abnf -> so that it could be \\\n provided to abnf or abnfs class for processing\"\"\"\n\n self._linelist.extend(self._oneline_to_seperatelines())\n for line in self._linelist:\n line=regex.sub('\\r\\n|\\n','',line)\n line=regex.sub(';.*','',line)\n if regex.match('\\s',line):\n self._abnflines[len(self._abnflines)-1]+=line\n else:\n self._abnflines.append(line)\n\n def getabnf(self):\n \"\"\"Returns the abnf stored in the object one line = one abnf\n\n Return values:\n abnflist -> list of the abnf of this object - one entry = \\\n abnf\n \"\"\"\n self._processlines()\n return self._abnflines\n","repo_name":"kblv/abnf2regex","sub_path":"abnfserializer.py","file_name":"abnfserializer.py","file_ext":"py","file_size_in_byte":8168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71246245605","text":"import pandas as pd\nimport os\nfrom data_preprocess.separate_java_files import separate_train_val_test\n\n\n# transform methods in a csv into a java file for each method\ndef main():\n methods_df = pd.read_csv('result.csv')\n directory_path = '../java_files'\n os.makedirs(directory_path, exist_ok=True)\n os.chdir(directory_path) # setting working directory to path\n start = 0\n file_count = start\n for i, row in methods_df.iterrows():\n file_name = str(file_count) + '.java'\n f = open(file_name, 'w+')\n method_name = row['name']\n file_start_string = 'public class ' + method_name + ' {\\n\\n'\n method = row['codes']\n file_end_string = '\\n}'\n string_to_file = file_start_string + str(method) + file_end_string\n f.write(string_to_file)\n f.close()\n file_count += 1\n separate_train_val_test(0.15, 0.15)\n\n\nmain()","repo_name":"lucasraggi/snippet-recommender-bot","sub_path":"data_preprocess/csv_to_java_file.py","file_name":"csv_to_java_file.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"75329048164","text":"import rlkit.torch.pytorch_util as ptu\nfrom rlkit.data_management.load_buffer import load_data_from_npy_chaining\nfrom rlkit.samplers.data_collector import MdpPathCollector, \\\n CustomMDPPathCollector\n\nimport torch\nfrom rlkit.torch.sac.policies import TanhGaussianPolicy, MakeDeterministic\nfrom rlkit.torch.sac.brac import BRACTrainer\nfrom rlkit.torch.conv_networks import CNN, ConcatCNN\nfrom rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm\nfrom rlkit.util.video import VideoSaveFunction\nfrom rlkit.launchers.launcher_util import setup_logger\nimport gym\n\nimport argparse, os\nimport roboverse\nimport numpy as np\n\nDEFAULT_PRIOR_BUFFER = ('/media/avi/data/Work/github/avisingh599/minibullet'\n '/data/oct6_Widow250DrawerGraspNeutral-v0_20K_save_all'\n '_noise_0.1_2020-10-06T19-37-26_100.npy')\nDEFAULT_TASK_BUFFER = ('/media/avi/data/Work/github/avisingh599/minibullet'\n '/data/oct6_Widow250DrawerGraspNeutral-v0_20K_save_all'\n '_noise_0.1_2020-10-06T19-37-26_100.npy')\nCUSTOM_LOG_DIR = '/nfs/kun1/users/asap7772/doodad-output/'\n\ndef process_buffer(args):\n path = '/home/asap7772/cog_data/'\n buffers = [] \n home = os.path.expanduser(\"~\")\n p_data_path = os.path.join(home, 'prior_data/') if args.azure else '/nfs/kun1/users/asap7772/prior_data/' \n ba = lambda x, p=args.prob, y=None: buffers.append((os.path.join(path, x),dict(p=p,alter_type=y,)))\n\n if args.buffer == 0:\n path = p_data_path\n ba('closed_drawer_prior.npy',y='zero')\n ba('drawer_task.npy')\n elif args.buffer == 1:\n path = p_data_path\n ba('blocked_drawer_1_prior.npy',y='zero')\n ba('drawer_task.npy')\n elif args.buffer == 2:\n path = p_data_path\n ba('blocked_drawer_2_prior.npy',y='zero')\n ba('drawer_task.npy')\n else:\n assert False, \"Invalid Buffer\"\n\n return buffers\n\ndef experiment(variant):\n eval_env = roboverse.make(variant['env'], transpose_image=True)\n if variant['num_sample'] != 0:\n eval_env.num_obj_sample=variant['num_sample']\n\n expl_env = eval_env\n action_dim = eval_env.action_space.low.size\n print(action_dim)\n\n cnn_params = variant['cnn_params']\n cnn_params.update(\n input_width=48,\n input_height=48,\n input_channels=3,\n output_size=1,\n added_fc_input_size=action_dim,\n )\n qf1 = ConcatCNN(**cnn_params)\n qf2 = ConcatCNN(**cnn_params)\n target_qf1 = ConcatCNN(**cnn_params)\n target_qf2 = ConcatCNN(**cnn_params)\n\n cnn_params.update(\n output_size=256,\n added_fc_input_size=0,\n hidden_sizes=[1024, 512],\n )\n\n policy_obs_processor = CNN(**cnn_params)\n\n behavior_policy = TanhGaussianPolicy(\n obs_dim=cnn_params['output_size'],\n action_dim=action_dim,\n hidden_sizes=[256, 256, 256],\n obs_processor=policy_obs_processor,\n )\n\n state_dict = torch.load(variant['behavior_path'])['policy_state_dict']\n behavior_policy.load_state_dict(state_dict)\n\n policy = TanhGaussianPolicy(\n obs_dim=cnn_params['output_size'],\n action_dim=action_dim,\n hidden_sizes=[256, 256, 256],\n obs_processor=policy_obs_processor,\n )\n\n eval_policy = MakeDeterministic(policy)\n eval_path_collector = MdpPathCollector(\n eval_env,\n eval_policy,\n )\n\n expl_path_collector = CustomMDPPathCollector(\n eval_env,\n )\n\n observation_key = 'image'\n replay_buffer = load_data_from_npy_chaining(\n variant,\n expl_env, \n observation_key,\n duplicate=False,\n num_traj=variant['num_traj'],\n debug_scale_actions=False,\n debug_shift=False,\n scale_type=False,\n hist_state=False,\n num_hist=False,\n )\n\n # Translate 0/1 rewards to +4/+10 rewards.\n if variant['use_positive_rew']:\n if set(np.unique(replay_buffer._rewards)).issubset({0, 1}):\n replay_buffer._rewards = replay_buffer._rewards * 6.0\n replay_buffer._rewards = replay_buffer._rewards + 4.0\n assert set(np.unique(replay_buffer._rewards)).issubset(\n set(6.0 * np.array([0, 1]) + 4.0))\n\n trainer = BRACTrainer(\n env=eval_env,\n policy=policy,\n behavior_policy=behavior_policy.to(ptu.device),\n qf1=qf1,\n qf2=qf2,\n target_qf1=target_qf1,\n target_qf2=target_qf2,\n beta=variant['beta'],\n log_dir=variant['log_dir'],\n variant_dict=variant,\n **variant['trainer_kwargs']\n )\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n eval_both=False,\n batch_rl=True,\n **variant['algorithm_kwargs']\n )\n video_func = VideoSaveFunction(variant)\n algorithm.post_epoch_funcs.append(video_func)\n\n algorithm.to(ptu.device)\n algorithm.train()\n\n\ndef enable_gpus(gpu_str):\n if (gpu_str is not \"\"):\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpu_str\n return\n\n\nif __name__ == \"__main__\":\n # noinspection PyTypeChecker\n variant = dict(\n algorithm=\"CQL\",\n version=\"normal\",\n algorithm_kwargs=dict(\n # num_epochs=100,\n # num_eval_steps_per_epoch=50,\n # num_trains_per_train_loop=100,\n # num_expl_steps_per_train_loop=100,\n # min_num_steps_before_training=100,\n # max_path_length=10,\n num_epochs=3000,\n num_eval_steps_per_epoch=300,\n num_trains_per_train_loop=1000,\n num_expl_steps_per_train_loop=1000,\n min_num_steps_before_training=1000,\n max_path_length=30,\n batch_size=256,\n ),\n trainer_kwargs=dict(\n discount=0.99,\n soft_target_tau=5e-3,\n policy_lr=1E-4,\n qf_lr=3E-4,\n reward_scale=1,\n use_automatic_entropy_tuning=True,\n ),\n cnn_params=dict(\n kernel_sizes=[3, 3, 3],\n n_channels=[16, 16, 16],\n strides=[1, 1, 1],\n hidden_sizes=[1024, 512, 256],\n paddings=[1, 1, 1],\n pool_type='max2d',\n pool_sizes=[2, 2, 1], # the one at the end means no pool\n pool_strides=[2, 2, 1],\n pool_paddings=[0, 0, 0],\n image_augmentation=True,\n image_augmentation_padding=4,\n ),\n dump_video_kwargs=dict(\n imsize=48,\n save_video_period=1,\n ),\n )\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--env\", type=str, required=True)\n parser.add_argument(\"--max-path-length\", type=int, required=True)\n parser.add_argument(\"--gpu\", default='0', type=str)\n parser.add_argument(\"--beta\", default=1.0, type=float, help=\"Value of beta in BRAC\")\n parser.add_argument(\"--use-positive-rew\", action=\"store_true\", default=False)\n parser.add_argument(\"--policy-eval-start\", default=10000,type=int)\n parser.add_argument(\"--policy-lr\", default=1e-4, type=float)\n parser.add_argument(\"--min-q-version\", default=3, type=int,\n help=(\"min_q_version = 3 (CQL(H)), \"\n \"version = 2 (CQL(rho))\"))\n parser.add_argument(\"--num-eval-per-epoch\", type=int, default=5)\n parser.add_argument(\"--seed\", default=10, type=int)\n parser.add_argument(\"--buffer\", default=0, type=int)\n parser.add_argument('--behavior_path', default='/nfs/kun1/users/asap7772/cog/data/behavior-bc/behavior_bc_2021_08_18_21_07_43_0000--s-0/model_pkl/200.pt', type=str)\n parser.add_argument('--num_traj', default=0, type=int)\n parser.add_argument(\"--prob\", default=1, type=float)\n parser.add_argument(\"--discount\", default=0.99, type=float)\n parser.add_argument(\"--name\", default='test', type=str)\n parser.add_argument(\"--azure\", action='store_true')\n parser.add_argument('--eval_num', default=0, type=int)\n\n args = parser.parse_args()\n enable_gpus(args.gpu)\n variant['num_sample'] = args.eval_num\n variant['num_traj'] = args.num_traj\n variant['prob'] = args.prob\n variant['env'] = args.env\n variant['buffer'] = args.buffer\n variant['behavior_path'] = args.behavior_path\n variant['algorithm_kwargs']['max_path_length'] = args.max_path_length\n variant['algorithm_kwargs']['num_eval_steps_per_epoch'] = \\\n args.num_eval_per_epoch*args.max_path_length\n\n buffers = process_buffer(args)\n variant['buffer'] = buffers\n variant['bufferidx'] = args.buffer\n variant['beta'] = args.beta\n variant['behavior_path'] = args.behavior_path\n\n variant['prior_buffer'] = buffers[0]\n variant['task_buffer'] = buffers[1]\n\n variant['trainer_kwargs']['policy_lr'] = args.policy_lr\n variant['trainer_kwargs']['discount'] = args.discount\n\n # Translate 0/1 rewards to +4/+10 rewards.\n variant['use_positive_rew'] = args.use_positive_rew\n variant['seed'] = args.seed\n\n ptu.set_gpu_mode(True)\n exp_prefix = 'cql-cog-{}'.format(args.env)\n if os.path.isdir(CUSTOM_LOG_DIR):\n base_log_dir = CUSTOM_LOG_DIR\n else:\n base_log_dir = None\n\n log_dir = setup_logger(args.name, variant=variant, base_log_dir=base_log_dir,\n snapshot_mode='gap_and_last', snapshot_gap=10,)\n variant['log_dir'] = log_dir\n experiment(variant)","repo_name":"Asap7772/OfflineRlWorkflow","sub_path":"examples/brac_workflow.py","file_name":"brac_workflow.py","file_ext":"py","file_size_in_byte":9569,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"5550705915","text":"# podaj rozmiar tablicy\n# czy ma być losowe różnowartościowe czy nie?\n# podaj numer szukanej statystyki pozycyjnej\n# czy ma być log?\n# czy generowanie statystyk\n\nimport os, matplotlib.pyplot as plt, numpy as np\n\n\ndef generate_plot(filename, label_desc, color):\n file = open(filename, 'r')\n\n x_axis = []\n y_axis = []\n for line in file:\n x_axis.append(line.split(\" \")[0])\n y_axis.append(line.split(\" \")[1])\n\n x_axis = np.asarray(x_axis)\n y_axis = np.asarray(y_axis)\n\n plt.plot(x_axis, y_axis, color, ms=0.5, label=label_desc)\n\n plt.legend(bbox_to_anchor=(0.1, 0.9), loc=2, borderaxespad=0.)\n\n\ndef create_plot():\n generate_plot('select_5_100.txt', 'select average', 'r')\n generate_plot('select_rand_5_100.txt', 'select random average', 'g')\n\n plt.xlabel(\"Array size\")\n plt.ylabel(\"Number of operations\")\n plt.title(\"Select vs Select Random - Operations number comparison for small arrays\")\n\n if not os.path.exists(\"plots\"):\n os.makedirs(\"plots\")\n\n iter = 0\n while os.path.isfile(\"plots/select_select_rand_small_comp_\" + str(iter) + \".png\"):\n iter += 1\n\n plt.savefig(\"plots/select_select_rand_small_comp_\" + str(iter) + \".png\")\n\n plt.cla()\n\n # NEXT FIG:\n generate_plot('select_100_100000.txt', 'select average', 'yo')\n generate_plot('select_100_100000_min.txt', 'select min', 'co')\n generate_plot('select_100_100000_max.txt', 'select max', 'mo')\n\n plt.ylim([0, 500000])\n plt.xlabel(\"Array size\")\n plt.ylabel(\"Number of operations\")\n plt.title(\"Select - Operations number comparison for big arrays\")\n iter = 0\n while os.path.isfile(\"plots/select_operations_big_\" + str(iter) + \".png\"):\n iter += 1\n\n plt.savefig(\"plots/select_operations_big_\" + str(iter) + \".png\")\n\n plt.cla()\n\n # NEXT FIG:\n generate_plot('select_rand_100_100000.txt', 'select rand average', 'ro')\n generate_plot('select_rand_100_100000_min.txt', 'select rand min', 'go')\n generate_plot('select_rand_100_100000_max.txt', 'select rand max', 'bo')\n\n plt.ylim([0, 500000])\n plt.xlabel(\"Array size\")\n plt.ylabel(\"Number of operations\")\n plt.title(\"Select random - Operations number comparison for big arrays\")\n\n iter = 0\n while os.path.isfile(\"plots/select_rand_operations_big_\" + str(iter) + \".png\"):\n iter += 1\n\n plt.savefig(\"plots/select_rand_operations_big_\" + str(iter) + \".png\")\n\n # LAST FIG:\n generate_plot('select_100_100000.txt`', 'select average', 'yo')\n generate_plot('select_100_100000_min.txt', 'select min', 'co')\n generate_plot('select_100_100000_max.txt', 'select max', 'mo')\n\n\n plt.xlabel(\"Array size\")\n plt.ylabel(\"Number of operations\")\n plt.title(\"Select random and random - Operations number comparison for big arrays\")\n\n iter = 0\n while os.path.isfile(\"plots/select_select_rand_operations_big_\" + str(iter) + \".png\"):\n iter += 1\n\n plt.savefig(\"plots/select_select_rand_operations_big_\" + str(iter) + \".png\")\n\n\nprint(\"RANDOMIZED SELECT, SELECT - analysis of algorithms\")\nO_SIZE = O_SORT = O_LOG = O_GRAPH = O_SEARCHED = -1\n\nwhile O_SIZE < 0 or O_SIZE > 500000:\n O_SIZE = int(input(\"Enter array size: [0 - 5*10^6] \"))\n\nwhile O_SORT < 0 or O_SORT > 1:\n O_SORT = int(input(\"Enter array type: [0: permutation, 1: rand] \"))\n\nwhile O_SEARCHED < 0 or O_SEARCHED > 500000:\n O_SEARCHED = int(input(\"Searched index?: [0 - arraySize] \"))\n\nwhile O_LOG < 0 or O_LOG > 1:\n O_LOG = int(input(\"Display log?: [0: no, 1: yes] \"))\n\nwhile O_GRAPH < 0 or O_GRAPH > 1:\n O_GRAPH = int(input(\"Generate graph?: [0: no, 1: yes] \"))\n\nos.system(\n \"select.exe \" + str(O_SIZE) + \" \" + str(O_SORT) + \" \" + str(O_SEARCHED) + \" \" + str(O_LOG) + \" \" + str(O_GRAPH))\n\nif O_GRAPH:\n create_plot()\n","repo_name":"piotrszyma/studies-algorithms","sub_path":"problem-set-3/plots generator/Z2.py","file_name":"Z2.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"35756086628","text":"# Solution 1 - 내 풀이\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n profit = 0\n \n for i in range(len(prices) - 1) : \n if prices[i+1] > prices[i] : \n profit += prices[i+1] - prices[i]\n \n return profit\n\n# 풀이 : 다음날의 가격이 전날보다 높다면 바로 사고 파는 풀이로, 원리만 잘 생각하면 어렵지 않게 풀 수 있었다. \n\n\n# Solution 2 - 책 풀이\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n return sum(max( prices[i+1]- prices[i], 0) for i in range(len(prices) - 1))\n\n# 책 풀이 : 한 줄 for문을 이용하여, max로 0이상의 profit을 더하는 간단하고 깔끔한 풀이 방법이다. ","repo_name":"HyeM207/Algorithm","sub_path":"LeetCode/[LeetCode] 122. Best Time to Buy and Sell Stock II.py","file_name":"[LeetCode] 122. Best Time to Buy and Sell Stock II.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11675532119","text":"# 문제 번호 : 3003\n\nnormal_set = [1, 1, 2, 2, 2, 8]\n\ninput_set = list(map(int, input().split()))\n\nresult_set = []\n\nfor i in range(6):\n result_set.append(normal_set[i] - input_set[i])\n\nresult = \"\"\n\nfor i in result_set:\n result = result + str(i) + \" \"\nprint(result[:-1])\n","repo_name":"Chilla-N/BaekJoon","sub_path":"python/입출력과사칙연산/킹, 퀸, 룩, 비숍, 나이트, 폰.py","file_name":"킹, 퀸, 룩, 비숍, 나이트, 폰.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8123212093","text":"import json\n\nwith open('./data/elements.json') as fp:\n data = json.load(fp)\n elements = {element['symbol'].lower() for element in data}\n\n\ndef _is_chemifyable(word: str) -> bool:\n # empty word is chemifyable\n if not word:\n return True\n\n # we compute 3 prefixes from the word\n # max length of element symbol is 3 hence we are\n # computing 3 prefixes - of length 1, 2 and 3.\n prefix1, prefix2, prefix3 = word[:1], word[:2], word[:3]\n\n # if prefix can be represented as a symbol (elemantable)\n # remaining word should also be elemntable\n if prefix1 in elements:\n if _is_chemifyable(word[1:]):\n return True\n\n if prefix2 in elements:\n if _is_chemifyable(word[2:]):\n return True\n\n if prefix3 in elements:\n if _is_chemifyable(word[3:]):\n return True\n\n return False\n\n\ndef is_chemifyable(word: str) -> bool:\n return _is_chemifyable(word.lower())\n\n\nif __name__ == '__main__':\n words = [\n 'bose',\n 'newton',\n 'cooper',\n 'ramanujan',\n ]\n\n for in_word in words:\n result = is_chemifyable(in_word)\n print(f\"{in_word} {'is' if result else 'is not'} chemifyable\")\n","repo_name":"arpitbbhayani/recursion","sub_path":"06-word-to-elements-01.py","file_name":"06-word-to-elements-01.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6983736336","text":"from collections import Counter\nimport sys\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\ninfo = [input().rstrip() for _ in range(n+m)]\ncounter = Counter(info)\nresult = 0\nfor e in counter.values():\n if e == 2:\n result += 1\nprint(result)\ntmp = counter.most_common(result)\ntmp.sort(key=lambda x:x[0])\nfor e in tmp:\n print(e[0])","repo_name":"jeno8522/Coding-Test-Study","sub_path":"2023(싸피 코테스터디)/6월/1주차/BOJ_S4_1764_듣보잡.py","file_name":"BOJ_S4_1764_듣보잡.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32095937946","text":"from string import whitespace\nimport numpy as np\nimport pandas as pd\nimport pickle\nfrom background import bg_rates\nimport os\n\nos.chdir(r\"/Users/dirk/Documents/UniBas/Zavolab\") #insert your own pathname here.\n\n\n#Load PWMs from .gmt\n\nwith open(r\"Phosphoproteomics/data/iKiP-DB.gmt\") as f:\n lines = [line for line in f]\nf.close()\n\ndef underscores(gmt_list, index_1, name):\n #This function is supposed to catch _ in sequences and write sequence + uniprot ID to a file.\n #index 1 == index in gmt_list that corresponds to seq with _\n #index 2 == index in the seq that has a _ \n uniprot_ids = gmt_list[1].split(\"|\")\n out=\"Name:|\" + name + \"| uniprot ID:|\"+uniprot_ids[index_1-1] + \"| and sequence:|\" + gmt_list[index_1].strip(\"-p;u\")+\"\\n\"\n f=open(\"underscores.txt\",\"a\")\n f.write(out)\n f.close()\n\ndef pwm_from_line(gmt_line):\n aas=\"ARNDCQEGHILKMFPSTWYV\"\n out={}\n gmt_list = gmt_line.split()\n counter = 2\n\n for i in gmt_list[2:]:\n i=i.strip(\"-p;u\")\n #Add PWM to output if it isn't in output yet.\n nam = gmt_list[0][12:]+\"-\"+i[7]\n if nam not in out:\n out[nam]=np.zeros((len(aas),len(i)))\n \n #Count AA freqs in each position\n for aa in range(len(aas)):\n switch =0\n for n in range(len(i)):\n\n if aas[aa]==i[n]:\n #This if statement is just here to catch undefined AA's and record them so we can check uniprot for the seq.\n if aa == 20 and switch == 0:\n switch =1\n underscores(gmt_list,counter, nam)\n out[nam][aa,n]+=1\n counter+=1\n \n #Convert freqs to rates\n for table in out:\n sums = np.sum(out[table],axis=0)\n #print(\"sums =\",sums)\n for i in range(len(sums)):\n #print(\"here\",len(sums))\n for aa in range(len(aas)):\n if out[table][aa,i] != 0:\n out[table][aa,i]=out[table][aa,i]/sums[i]\n\n return out\n\npwms = {}\n\n#print(pwm_from_line(lines[0]))\n\nfor i in lines:\n pwms[i.split()[0][12:]+\"-\"+i[7]] = pwm_from_line(i)\n\nwith open(r'Phosphoproteomics/steps/pwms/selbach_pwms.pickle', 'wb') as f:\n pickle.dump(pwms, f)\n\nwith open(r'Phosphoproteomics/steps/pwms/selbach_pwms.pickle', 'rb') as f:\n pwms_loaded = pickle.load(f)\n\nprint(len(pwms_loaded.keys()))","repo_name":"Dirk-Hoffmann/Phosphoproteomics","sub_path":"scripts/outdated/gmt_to_pwm.py","file_name":"gmt_to_pwm.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41530591182","text":"\"\"\"stats sessions management related views\"\"\"\nimport json\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.db import IntegrityError\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.decorators import method_decorator\nfrom django.urls import reverse\nfrom django.views import View\nfrom django.views.generic.edit import CreateView, DeleteView\n\nfrom equipment.models.arrows import Arrow\nfrom records.models import StatsRecordSession, StatsRecord\nfrom records.forms import StatsRecordSessionForm\nfrom records.utils import calculate_barycentre, calculate_quiver\n\n\nclass ListStatsSessions(View):\n @method_decorator(login_required)\n def get(self, request):\n ctx = {}\n user = request.user\n stats_record_sessions = StatsRecordSession \\\n .objects \\\n .filter(user=user) \\\n .all()\n ctx[\"stats_sessions\"] = stats_record_sessions\n return render(request, \"records/list_stats_sessions.html\", context=ctx)\n\n\nclass CreateStatsSession(CreateView):\n def get_form_kwargs(self):\n kwargs = super(CreateStatsSession, self).get_form_kwargs()\n kwargs[\"request\"] = self.request\n return kwargs\n\n @method_decorator(login_required)\n def get(self, request, *args, **kwargs):\n user = request.user\n form = StatsRecordSessionForm(user=user)\n ctx = {\"form\": form}\n return render(request,\n \"records/create_stats_session.html\",\n context=ctx)\n\n @method_decorator(login_required)\n def post(self, request, *args, **kwargs):\n try:\n srs = StatsRecordSession.objects.create(\n user=request.user,\n conditions=request.POST.get(\"conditions\"),\n distance=request.POST.get(\"distance\"),\n comment=request.POST.get(\"comment\"),\n )\n srs.save()\n\n available_arrow_indexes = request.POST.getlist(\"available_arrows\")\n arrows = [\n Arrow.objects.filter(pk=int(index), user=request.user).first()\n for index in available_arrow_indexes\n ]\n\n srs.available_arrows.set(arrows)\n srs.save()\n\n except IntegrityError:\n raise\n\n return redirect(\"stats_session_list\")\n\n\nclass DetailStatsSession(View):\n @method_decorator(login_required)\n def get(self, request, pk):\n \"\"\"get the stats session summary\n\n Args:\n pk (int): Stats Record Session identifyer\n \"\"\"\n # TODO find a way do display available arrows checked\n user = request.user\n\n srs = get_object_or_404(StatsRecordSession, user=user, pk=pk)\n\n head_form = StatsRecordSessionForm(srs, user=user)\n\n records = StatsRecord.objects.filter(stats_session=srs) or None\n available_arrows = srs.available_arrows.all()\n\n ctx = {\n \"srs\": srs,\n \"form\": head_form,\n \"records\": records,\n \"available_arrows\": available_arrows,\n }\n return render(request,\n \"records/detail_stats_session.html\",\n context=ctx)\n\n @method_decorator(login_required)\n def post(self, request, pk):\n \"\"\"update arrow stats\n\n Args:\n pk (int): Stats Record Session identifyer\n \"\"\"\n\n user = request.user\n # réécrire les champs de la session de statistiques\n srs = StatsRecordSession.objects.get(user=user, pk=pk)\n srs.conditions = request.POST.get(\"conditions\")\n srs.distance = request.POST.get(\"distance\")\n srs.comment = request.POST.get(\"comment\")\n available_arrow_ids = [int(a) for a\n in request.POST.getlist(\"available_arrows\")]\n\n srs.available_arrows.clear()\n\n for id in available_arrow_ids:\n srs.available_arrows.add(id)\n srs.save()\n return redirect(\"stats_session_detail\", srs.pk)\n\n\nclass DeleteStatsSession(DeleteView):\n model = StatsRecordSession\n\n def get_success_url(self):\n return reverse(\"stats_session_list\")\n\n\nclass CreateStatsRecord(View):\n @method_decorator(login_required)\n def post(self, request):\n body = request.POST\n try:\n srs_id = body.get(\"srs_id\")\n arrow_id = body.get(\"arrow_id\")\n pos_x = body.get(\"pos_x\")\n pos_y = body.get(\"pos_y\")\n\n arrow = get_object_or_404(Arrow, pk=arrow_id)\n srs = get_object_or_404(StatsRecordSession, pk=srs_id)\n stats_record = StatsRecord.objects.create(\n arrow=arrow, stats_session=srs, pos_x=pos_x, pos_y=pos_y\n )\n stats_record.save()\n\n except Exception as e:\n raise e\n\n return JsonResponse(\n json.dumps(\n {\n \"record\": {\n \"arrow\": arrow.pk,\n \"stats_session\": srs.pk,\n \"pos_x\": pos_x,\n \"pos_y\": pos_y,\n \"id\": stats_record.pk,\n },\n \"status_code\": 200,\n }\n ),\n safe=False,\n )\n\n\nclass DeleteStatsRecord(View):\n @method_decorator(login_required)\n def get(self, request, stats_session_pk, stat_pk):\n stats_record = get_object_or_404(StatsRecord, pk=stat_pk)\n stats_record.delete()\n stats_dict = {\n \"id\": stats_record.id,\n \"session_id\": stats_record.stats_session.id,\n \"arrow_id\": stats_record.arrow_id,\n \"pos_x\": stats_record.pos_x,\n \"pos_y\": stats_record.pos_y,\n }\n\n return JsonResponse({\"data\": stats_dict, \"status_code\": 200})\n\n\nclass StatsRecordResults(View):\n @method_decorator(login_required)\n def get(self, request, stats_session_pk):\n\n stats_session = StatsRecordSession.objects.get(pk=stats_session_pk)\n shots = StatsRecord.objects.filter(stats_session=stats_session_pk)\n\n pk_list = [id.get(\"arrow_id\") for id\n in shots.values(\"arrow_id\").distinct()]\n\n records = {}\n for id in pk_list:\n records[id] = [rec for rec in shots.filter(arrow_id=id)]\n\n barycentres = []\n for record in records.values():\n barycentre_coords = calculate_barycentre(record)\n barycentre = {\n \"arrow_id\": record[0].arrow_id,\n \"pos_x\": barycentre_coords[0],\n \"pos_y\": barycentre_coords[1],\n }\n\n barycentres.append(barycentre)\n\n quiver = calculate_quiver(barycentres)\n for arrow in quiver:\n continue\n ctx = {\"stats_session\": stats_session, \"arrows\": quiver}\n return render(request,\n \"records/stats_session_result.html\",\n context=ctx)\n","repo_name":"remace/OC-P13_Archery_Buddy","sub_path":"ArcheryBuddy/records/views/stats_sessions.py","file_name":"stats_sessions.py","file_ext":"py","file_size_in_byte":7011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"733655750","text":"#imports\nimport torch\nfrom super_gradients.training import models\nimport os\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm \n#paths\ntest_path = \"./test/\"\ntest_path_label = \"./test_labels/\"\n\n#dataset parameters\n\ndataset_params = {\n 'test_images_dir':'./yolonas/test/',\n 'test_labels_dir':'./yolonas/test_labels/',\n 'classes': ['button'] \n}\n\n#load model\nMODEL_ARCH = 'yolo_nas_l'\nDEVICE = 'cuda' if torch.cuda.is_available() else \"cpu\"\nBATCH_SIZE = 8\nMAX_EPOCHS = 5\nCHECKPOINT_DIR = f'./training_backup/'\nEXPERIMENT_NAME = f'yolo_nas_l_e5'\n\nbest_model = models.get(\n MODEL_ARCH,\n num_classes=len(dataset_params['classes']),\n checkpoint_path=f\"{CHECKPOINT_DIR}/{EXPERIMENT_NAME}/average_model.pth\"\n).to(DEVICE)\n\nimages_arr = [] #Array of image paths\n\nfor file_name in os.listdir(test_path):\n images_arr.append(os.path.join(test_path, file_name))\n\ntimes = []\nfor file_path in tqdm(images_arr):\n t0 = cv2.getTickCount()\n x = best_model.predict(file_path)\n t1 = cv2.getTickCount()\n time = (t1-t0)/cv2.getTickFrequency()\n times.append(time)\n\n# print(mean(times))\narr = np.array(times)\n\n# measures of dispersion\navg = np.mean(arr)\nmin = np.amin(arr)\nmax = np.amax(arr)\nrange = np.ptp(arr)\nvariance = np.var(arr)\nsd = np.std(arr)\n \n# print(\"Array =\", arr)\nprint(\"Average = \", avg)\nprint(\"Minimum =\", min)\nprint(\"Maximum =\", max)\nprint(\"Range =\", range)\nprint(\"Variance =\", variance)\nprint(\"Standard Deviation =\", sd)","repo_name":"SatArw/yolonas","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9886262480","text":"# @auth: Stephen Foster Apr '22 CS-446\n# @repo: github.com/Stehfyn/CS-446\n# @file: fileSystemComparison.py\n# @vers: 1.0\n#\n# @impl: Object-oriented approach to maintain readability. Originally sorting and positioning files alphanumerically happened inside \n# of get_statistics() which ate performance, and disproportionately affected single level directories at scale. I've changed the \n# implementation to better to highlight the average performance difference of traversing either kinds of directories.\n#\n# @usage: cli: [python3] fileSystemComparison.py\n# ex: python fileSystemComparison.py\n#\n# @concl: The similarity between average file sizes of Single-Level (SL) and Hiearchical (HL) is due to the fact that these days file\n# sizes strictly refer to bytes not belonging to the metadata for the file, device, pipe, etc. Of course a files metadata could not be\n# zero size, however this information is stored in the relevant inode. The reason why either directory (and any subdirectories) is/are \n# 4096 bytes a piece, is because that is the minimum overhead size of an inode (as it points to a single data block). Neither test case \n# exceeds the ability of a single data block, thus resulting in the similarity in size of directories. \n#\n# UPDATE: After running the script on both a personal WSL environment vs. UNR's ubuntu webserver, it appears that the inode size \n# on the webserver is tuned differently. Some directories with the same amount of blank files are slightly different in size, in what\n# I'm interpreting as the webserver having much smaller size data blocks, thus capturing (instead of aliasing) the differences in filename\n# lengths, protections, indirections, etc. All directories went from exactly 4096 bytes in my personal WSL environment to roughly around 200 \n# bytes on the webserver.\n#\n# The traversal time tends to lean towards SL, especially after changing the implementation to remove time bloat from ancillary functionality.\n# This is due to the less indirection in searching an SL vs. a HL filesystem\n# \n# In a simple SL filesystem with arbitrarily long filenames and an arbitrary number of files, an emulation of filepaths would use a\n# delimiting character to denote subdirectories. Using '#' as an example, a SL filesystem could emulate a desktop subdirectory by making\n# desktop-intended files denoted through a delimited path: root#user#stehfyn#desktop#file.txt\n\nimport os, sys, subprocess\nimport re, stat\n\nfrom typing import List\nfrom time import process_time\n\ndef main():\n \n single = init_single_level_directory(100)\n hierarchical = init_hierarchical_level_directory(10, 10)\n \n ss, hs = single.get_statistics(), hierarchical.get_statistics()\n print(ss), print(hs)\n\n write_tableu(single.path + single.name, \"singleLevelFiles.txt\", single)\n write_tableu(hierarchical.path + hierarchical.name, \"hierarchicalFiles.txt\", hierarchical)\n\n #force_delete_dir(single)\n #force_delete_dir(hierarchical)\n\nclass Statistics:\n\n def __init__(self, _n, _f, _d, _tfs, _tds, _tt):\n\n self.data = {}\n self.keys = [\"Name\",\n \"Number of Files\",\n \"Number of Directories\",\n \"Average File Size\",\n \"Average Directory Size (bytes)\",\n \"Traversal Time (ms)\"]\n\n #process_time() yields fractional second, thus t*1000 = # of ms\n vals = [_n, _f, _d, _tfs/_f if _f != 0 else 0, _tds/_d if _d != 0 else 0, round(_tt*1000, 8)] \n \n for i, x in enumerate(self.keys):\n self.data.update({x:vals[i]})\n\n def __str__(self):\n s = ''\n s += self.data.get('Name') + '\\n\\n'\n for x in range(1, len(self.keys)):\n s += self.keys[x] + ': ' + f'{self.data.get(self.keys[x]):2}' + '\\n'\n return s\n\nclass File:\n\n def __init__(self, _path, _name):\n self.path = ''\n self.name = ''\n\n self.path = os.path.abspath(_path) + '/'\n self.name = _name\n \n subprocess.getstatusoutput(\"touch \" + self.path + self.name)\n\nclass Directory:\n\n def __init__(self, _path, _name):\n self.path = ''\n self.name = ''\n self.files = []\n self.directories = []\n self.tableu = []\n\n self.path = os.path.abspath(_path) + '/'\n self.name = _name\n\n if os.path.isdir(self.path + self.name):\n force_delete_dir(self)\n\n os.mkdir(self.path + self.name)\n \n def add_file(self, _file :str):\n self.files.append(File(self.path + self.name, _file))\n \n def make_directory(self, _dir :str):\n self.directories.append(Directory(self.path + self.name, _dir))\n\n def tableu_to_str(self):\n s = ''\n for dirs, sizes, files in self.tableu:\n if dirs != self.path + self.name:\n s += '\\t'\n s += '{0:2} {1:3}'.format(dirs + '/', str(sizes))\n s += '\\n'\n for f, sz in files:\n s += '\\t\\t' + '{0:2} {1:3}'.format(f, str(sz))\n s += '\\n'\n return s\n\n def get_tableu(self):\n if len(self.tableu) == 0:\n self.get_statistics()\n return self.tableu\n\n def get_statistics(self):\n name, files, dirs, total_file_size, total_dir_size = \"\", 0, 0, 0, 0\n self.tableu.clear()\n\n start = process_time()\n for dirpath, dirnames, filenames in os.walk(self.path + self.name):\n file_and_size = []\n\n #sorted() here eats traversal time, a future impl would sort after\n #also, single level is greatly more likely eat time at scale, as\n #statistically speaking its bin size is 0 compared to hl's 10 in this use case!\n\n #for f in sorted(filenames, key=alpha_num_order):\n\n for f in filenames:\n fp = os.path.join(dirpath, f)\n if not os.path.islink(fp):\n s = os.path.getsize(fp)\n total_file_size += s\n file_and_size.append((f,s))\n files += 1\n \n dir_size = os.path.getsize(dirpath)\n\n if dirpath != self.path + self.name:\n self.tableu.append((os.path.basename(dirpath), dir_size, file_and_size))\n total_dir_size += dir_size\n dirs += 1\n else:\n self.tableu.append((dirpath, dir_size, file_and_size))\n end = process_time()\n\n if dirs == 0:\n name = \"Single Level File System\"\n else:\n name = \"Hierarchical File System\"\n return Statistics(name, files, dirs, total_file_size, total_dir_size, end-start)\n\ndef alpha_num_order(s :str):\n return ''.join([format(int(x), '05d') if x.isdigit()\n else x for x in re.split(r'(\\d+)', s)])\n \ndef init_single_level_directory(_files :int) -> Directory:\n single = Directory(os.environ['HOME'], 'singleRoot')\n for x in range(_files):\n single.add_file(\"file\" + str(x+1) + \".txt\")\n return single\n \ndef init_hierarchical_level_directory(_dirs :int, _files :int) -> Directory:\n hierarchical = Directory(os.environ['HOME'], 'hierarchicalRoot')\n split = _files\n for d in range(_dirs):\n r = range((d+1)*split-(split-1), (d+1)*split + 1)\n dir_name = \"files\" + str(list(r)[0]) + '-' + str(list(r)[len(list(r))-1])\n hierarchical.make_directory(dir_name)\n for x in r:\n hierarchical.directories[d].add_file(\"file\" + str(x) + \".txt\")\n return hierarchical\n\ndef write_tableu(_path :str, _name :str, _dir :Directory) -> None:\n s = _dir.tableu_to_str()\n clearFile(_path, _name)\n outputToFile(_path, _name, s)\n\ndef force_delete_dir(_dir :Directory):\n cmd = \"rm -rf \" + _dir.path + _dir.name\n return subprocess.getstatusoutput(cmd)\n\ndef outputToFile(_path :str, _out_file: str, _str :str) -> None:\n fout = open(_path + '/' + _out_file, 'a')\n fout.write(_str)\n fout.close()\n\ndef clearFile(_path :str, _out_file :str) -> None:\n fout = open(_path + '/' + _out_file, 'w')\n fout.write('')\n fout.close()\n\nif __name__=='__main__':\n try:\n main(), exit(0)\n except Exception as inst:\n print(inst), exit(1)","repo_name":"Stehfyn/cs446","sub_path":"Assignment-3/fileSystemComparison.py","file_name":"fileSystemComparison.py","file_ext":"py","file_size_in_byte":8189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19231817349","text":"# AUTHOR : SAYAN BHATTACHARJEE\n# EMAIL : aero.sayan@gmail.com\n# LICENSE: DEFAULT, and will remain so.\n# FILE : blitzer_linked_list.py\n# INFO : linked list module for competitive programming.\n# STYLE : smaller case with underscore for speed\n\n#===============================================================================\n# MEMBERS\n#===============================================================================\n# node class\nclass node:\n \"\"\"Node class for creating linked lists and designed for\n competetive programming.\n \"\"\"\n #----------------------------------------\n # creating the object\n def __init__(self,data):\n self.data = data # assign data\n self.next = None # set next as null\n return\n #----------------------------------------\n#end class node\n\n# linked list class\nclass lnklst:\n \"\"\"Linked list class for creating linked lists and designed\n for competitive programming\n \"\"\"\n #----------------------------------------\n # Constructor\n def __init__(self):\n self.head = None # set the head of the linked list as null\n self.tail = None # set the last of the linked list as null\n self.size = 0 # set linked list size as 0\n return\n #----------------------------------------\n # Print the full list\n def print_all(self):\n node = self.head\n while(node):\n # at end of list\n if(node.next == None):\n print(node.data) # we print data and go to new line\n node = node.next # iterator\n else:\n print(node.data),\n node = node.next #iterator\n # end while\n return\n #----------------------------------------\n # Find and updata self.tail\n def update_tail(self):\n # incase tail is not already set\n if(self.tail == None):\n self.tail = self.head\n #then\n # and update varaible if necessary\n tail = self.tail\n # incase tail is already set\n while(tail.next):\n tail = tail.next #iterator\n #end while\n self.tail = tail\n return\n #----------------------------------------\n # Insert a new node at the begining\n def prepend(self,new_node):\n # ensure linked list size calculation is done to get correct sizes later\n self.get_size()\n # first point the head to the end of the new node\n new_node.next = self.head\n # then assign the head as new node\n self.head = new_node\n # if we are at the end then we have essentially performed an append\n # thus update last node\n if(new_node.next.next == None):\n self.tail = new_node.next\n\n # update size\n self.size = self.size + 1\n return\n #----------------------------------------\n # Insert after an object of the given data key\n def insert_after_key(self,data_key,new_data):\n # ensure linked list size calculation is done to get correct sizes later\n self.get_size()\n new_node = node(new_data) # call constructor to node class\n prev_node = None # placeholder\n\n _node = self.head # temp node variable\n\n while(_node.next): # run till tail\n if(_node.data == data_key):\n prev_node = _node\n break\n _node = _node.next\n # end if\n # end while\n\n # insert the new node after prev node\n new_node.next = prev_node.next\n prev_node.next = new_node\n\n # if we are at the end then we have essentially performed an append\n # thus update last node\n if(new_node.next == None):\n self.tail = new_node\n\n # update size\n self.size += 1\n return\n #----------------------------------------\n # Insert after a certain node object\n def insert_after_node(self,prev_node,new_node):\n # ensure linked list size calculation is done to get correct sizes later\n self.get_size()\n # put the next node after new node assuming prev_node is present in list\n new_node.next = prev_node.next\n # put the new node after prev node\n prev_node.next = new_node\n\n # if we are at the end then we have essentially performed an append\n # thus update last node\n if(new_node.next == None):\n self.tail = new_node\n\n # update size\n self.size = self.size + 1\n return\n #----------------------------------------\n # Add a node at the end in O(1)\n def append(self,new_node):\n # ensure linked list size calculation is done to get correct sizes later\n self.get_size()\n # similar to vector\n if(self.head == None): # if zero nodes are present\n self.head = new_node\n self.tail = new_node\n else:\n # compare with self.tail and if it contains a next node then we have\n # appended something to the linked list and it contains more\n # than one node now; thus, go to the end\n self.update_tail()\n tail = self.tail\n while(tail.next):\n tail = tail.next #iterator\n # end while\n\n # at the end add the new node and update self.tail to point to it\n tail.next = new_node\n self.tail = new_node\n # end if else\n # update size\n self.size = self.size + 1\n return\n #----------------------------------------\n # Delete node with the data same as passed dataKey\n def delete(self,data_key):\n # if linked list is empty\n if(self.head == None):\n return\n\n # otherwise traverse over the full list to find the first occurence\n node = self.head\n if(node.data == data_key): # deleting head\n self.head = node.next # update new head\n node.next = None # delete old head\n self.size -= 1 # decrease size count\n # if only head is present\n if(self.head and self.head.next == None):\n self.tail = None\n\n n = node\n while(node.next): # complexity O(n)\n n = node # current node\n node = node.next # next node # iterator\n # if we find the node with the same data key then remove it\n if(node.data is not None and node.data == data_key):\n # link current node with the node after the node with datakey\n n.next = node.next\n if(n.next == None): # we have only head left\n self.tail = None\n\n # remove all links with the next node with data key\n node.next = None\n # update size count\n self.size -= 1\n return\n #end while\n\n #----------------------------------------\n # Delete the linked list\n def delete_all(self):\n self.head = None\n self.tail = None\n self.size = 0\n\n #----------------------------------------\n # Get the size of the singly linked link list\n def get_size(self,force_recount = False):\n # return the stored size if not forced with O(1) complexity\n if(self.size > 0 and force_recount == False):\n return self.size\n else:\n print(\"INF : pre forced calculation self.size : \" + str(self.size))\n print(\"INF : performing linked list forced size count...\")\n #else do forced recount with O(n) complexity\n node = self.head\n count = 0\n while(node): # node is not None\n count += 1\n node = node.next\n # end while\n # update size value if force_recount == false\n self.size = count\n return count\n #----------------------------------------\n # Search and return if we find an object with the same passed data key\n def search(self,data_key):\n # if head is null\n if(self.head == None):\n return False\n node = self.head\n while(node.next):\n if(node.data == data_key):\n return True\n else:\n node = node.next\n # end while\n return False\n #----------------------------------------\n # Go to nth position and get node\n def at(self,n):\n node = self.head\n i = 0 # accessor\n I = 0 # iterator\n while(I <= n and node):\n i = I\n I += 1\n if(i == n): # since zero indexed\n return node\n if(node): # if node is not None\n node = node.next\n # end while\n\n print(\"ERR : link list is smaller than required position \" + str(n))\n print(\"ERR : asserting false to stop execution...\")\n assert(False)\n #----------------------------------------\n # Go to nth position from the last\n def at_rev(self,n):\n # if n == 1 then return tail\n if(n == 1): # complexity O(1)\n return self.tail\n else: # complexity O(n)\n node = self.head\n i = 0 # accessor\n I = 0 # iterator\n len = self.get_size() # size of the linked list\n while(I < len-n):\n i = I\n I += 1\n node = node.next\n # end while\n return node\n # end if else\n print(\"ERR : link list is smaller than required reverse position \" + str(n))\n print(\"ERR : asserting false to stop execution...\")\n assert(False)\n #----------------------------------------\n # Floyd's cycle finding algorithm to detect loops in linked list\n def is_loop(self):\n # we use a fast and slow node\n slow_node = self.head\n fast_node = self.head\n # traverse over the linked list and try to detect loop\n while(slow_node and fast_node and fast_node.next):\n slow_node = slow_node.next\n fast_node = fast_node.next.next\n if( slow_node == fast_node):\n return True,slow_node\n # end while\n return False,None\n #----------------------------------------\n # Get loop size\n def get_loop_size(self,loop_start):\n # we iterate the loop and find the loop size\n if (loop_start == None):\n return 0\n count = 1 # we are starting count at 1 since we will not come\n # back to loop_start in the while loop\n node = loop_start.next\n print(loop_start.data),\n while(node is not loop_start ):\n count += 1 # update count\n print(node.data),\n node = node.next # go to next node\n # end while\n print(loop_start.data),\n print(\"\")\n return count\n #----------------------------------------\n # Reverse the full linked list\n def reverse(self):\n old_head = self.head # save the current head\n prev_node = None # previous node\n curr_node = self.head # current node\n next_node = None # next node\n\n # traverse the full list and reverse it\n while(curr_node): # Complexity of O(n)\n next_node = curr_node.next # set next_node\n curr_node.next = prev_node # break link and rotate it 90 deg\n prev_node = curr_node # move prev_node to curr_node\n curr_node = next_node # move curr_node to next_node\n #end while\n self.head = prev_node # set the last element as head\n self.tail = old_head # set the first element as tail\n return\n #----------------------------------------\n # Print reverse without using any more space\n def print_reverse(self, node):\n if(node is None):\n return # return control back\n # end if\n self.print_reverse(node.next) # call recursively next level\n print(node.data), # print in one line\n return\n #----------------------------------------\n # Swap nodes with the given dataKeys\n def swap(self,data_key_1,data_key_2):\n node = self.head\n node1 = None\n node2 = None\n prev_node = None\n prev_node1 = None\n prev_node2 = None\n # find both of the nodes\n while(node): # complexity O(n)\n # if one or both of them are not found\n if(node1 == None or node2 == None):\n if(node.data == data_key_1):\n node1 = node # the first node encountered\n prev_node1 = prev_node # the previous node of node1\n elif(node.data == data_key_2):\n node2 = node # the second node encountered\n prev_node2 = prev_node # the previous node of node2\n else: # if both of them are found\n node = self.tail # go to end , casue here node.next == None\n #end if\n prev_node = node\n node = node.next\n #print(\"DBG : changed node\")\n # end while\n\n # error checking\n if(self.get_size() <= 1):\n print(\"ERR : can not swap with link list size <=1 ... \")\n print(\"INF : asserting false... \")\n assert(false)\n # end if\n if(node1 == None or node2 == None ):\n print(\"INF : nodes not found to swap with data keys...\")\n print(\"INF : data_key_1 : \" + str(data_key_1)),\n print(\"\\t | data_key_2 : \" + str(data_key_2))\n print(\"INF : cancelling swap...\")\n return\n elif( node1 == self.head ):\n print(\"DBG : swapping node1, which is self.head ....\")\n next1 = node1.next\n next2 = node2.next\n # swap front to back\n self.head = node2 # bring node2 to front # TODO : looped lists ?\n prev_node2.next = node1 # send node1 ot back\n node2.next = next1 # link next of node1\n node1.next = next2 # link next of node2\n return\n elif( node2 == self.tail):\n print(\"DBG : swapping node2, which is self.tail ....\")\n next1 = node1.next\n next2 = node2.next # probably null but not necessarily\n # swap front to back\n prev_node1.next = node2\n prev_node2.next = node1\n node2.next = next1\n node1.next = next2\n return\n elif(prev_node1 and prev_node2): # swap the nodes if prev_node is found\n next1 = node1.next\n next2 = node2.next\n # swap front to back\n prev_node1.next = node2\n prev_node2.next = node1\n node2.next = next1\n node1.next = next2\n else: # we have error\n print(\"ERR : all swap tests failed...\")\n assert(False)\n #----------------------------------------\n # Swap head and tail\n def swap_ends(self):\n if(self.get_size() <=1): # compelexity O(1) or in very small cases O(n)\n print(\"ERR : can not swap with link list size <=1 ... \")\n print(\"INF : asserting false... \")\n assert(false)\n\n # we traverse list to find the node before tail\n prev_node = self.head\n while(prev_node.next is not self.tail): # causes complexity O(n)\n prev_node = prev_node.next\n # temporary variables\n node1 = self.head\n node2 = self.tail\n next1 = self.head.next\n next2 = self.tail.next\n # swap head and tail from front to back\n self.tail = node1\n self.head = node2\n # now we fix swapped connections,be very careful\n self.head.next = next1 # previously tail\n self.tail.next = next2 # previously head\n # most importantly point the prev_node.next to the new tail\n prev_node.next = self.tail\n return\n #----------------------------------------\n # Join two different linked lists\n def join(self,other):\n if(other.__class__.__name__ is not \"lnklst\"):\n raise TypeError(\"ERR : lnklst.join(self,other) :\"\n + \" other needs to be object of lnklst class\")\n # end if\n self.tail.next = other.head # simply link them\n self.update_tail() # udpate tail to be correct\n self.get_size(force_recount = True) # update size to be correct\n return\n #----------------------------------------\n # Are the two linked lists identical?\n def is_identical(self,other):\n if(other.__class__.__name__ is not \"lnklst\"):\n raise TypeError(\"ERR : lnklst.is_identical(self,other) :\"\n + \" other needs to be object of lnklst class\")\n # end if\n\n n = self.get_size() # hopefully O(1) or worst O(n)\n m = other.get_size() # hopefully O(1) or worst O(n)\n\n if (n != m): # first simple test hoping O(1)\n return False\n else: # n == m # run test on both of the lists\n node1 = self.head\n node2 = other.head\n # traverse both linked lists\n while(node1 and node2):\n if(node1.data != node2.data):\n return False\n node1 = node1.next\n node2 = node2.next\n # end while\n\n return True # if all tests fail means\n #----------------------------------------\n","repo_name":"aerosayan/BLITZER","sub_path":"src/py27/blitzer_linked_list.py","file_name":"blitzer_linked_list.py","file_ext":"py","file_size_in_byte":17818,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39628804311","text":"from __future__ import print_function\r\n\r\n# Script used to export these data files from binja.\r\n#\r\n# In binja's python console:\r\n#\r\n# >>> import exphp_export; exphp_export.run(bv)\r\n\r\nimport os\r\nimport json\r\nimport glob\r\nfrom collections import defaultdict\r\nimport contextlib\r\nimport typing as tp\r\nfrom binaryninja import log\r\nimport binaryninja as bn\r\nfrom pathlib import Path\r\n\r\nfrom .common import TypeTree, TAG_KEYWORD, PathLike, lookup_named_type_definition, resolve_actual_enum_values\r\nfrom .config import SymbolFilters, DEFAULT_FILTERS, TypeOrigin\r\nfrom .export_types import _create_types_file_json, TypeToTTreeConverter, structure_to_cereal_v1, enum_to_cereal_v1, union_to_cereal_v1, enum_to_bitfields_cereal_v1\r\nfrom .importing import _import_symbols_from_json_v1\r\n\r\n# re-exports\r\nfrom .importing import import_funcs_from_json, import_statics_from_json, import_structs_from_json, import_bitfields_from_json, import_enums_from_json\r\nfrom .export_types import create_types_file_json\r\nfrom .test import run_tests\r\n\r\nBNDB_DIR = r\"E:\\Downloaded Software\\Touhou Project\"\r\nJSON_DIR = r\"F:\\asd\\clone\\th16re-data\\data\"\r\nMD5SUMS_FILENAME = 'md5sums.json'\r\nCOMMON_DIRNAME = '_common' # FIXME: rename to _modules\r\nSHARED_DIRNAME = '_shared'\r\nGAMES = [\r\n \"th06.v1.02h\",\r\n \"th07.v1.00b\",\r\n \"th08.v1.00d\",\r\n \"th09.v1.50a\",\r\n \"th095.v1.02a\",\r\n \"th10.v1.00a\",\r\n \"th11.v1.00a\",\r\n \"th12.v1.00b\",\r\n \"th125.v1.00a\",\r\n \"th128.v1.00a\",\r\n \"th13.v1.00c\",\r\n \"th14.v1.00b\",\r\n \"th143.v1.00a\",\r\n \"th15.v1.00b\",\r\n \"th16.v1.00a\",\r\n \"th165.v1.00a\",\r\n \"th17.v1.00b\",\r\n \"th18.v1.00a\",\r\n \"th185.v1.00a\",\r\n # NEWHU: 185\r\n]\r\nJsonFormatVersion = int # tp.Literal[1, 2] # needs python 3.8\r\n\r\nK = tp.TypeVar('K')\r\nV = tp.TypeVar('V')\r\nG = tp.TypeVar('G')\r\n\r\ndef export(bv, path, common_types={}, version=2, filters=DEFAULT_FILTERS):\r\n return _export(bv, path, common_types, version, filters)\r\n\r\ndef _export(bv: bn.BinaryView, path: PathLike, common_types, version: JsonFormatVersion, filters: SymbolFilters):\r\n path = Path(path)\r\n _export_symbols(bv, path=path, filters=filters, version=version)\r\n _export_types(bv, path=path, common_types=common_types, filters=filters, version=version)\r\n\r\ndef open_bv(path: PathLike, **kw):\r\n # Note: This is now a context manager, hurrah!\r\n return bn.BinaryViewType.get_view_of_file(str(path), **kw)\r\n\r\ndef _compute_md5(path: PathLike):\r\n import hashlib\r\n return hashlib.md5(open(path,'rb').read()).hexdigest()\r\n\r\ndef dict_get_path(d, parts, default=None):\r\n for part in parts:\r\n if part not in d:\r\n return default\r\n d = d[part]\r\n return d\r\n\r\ndef export_all(\r\n games = GAMES,\r\n bndb_dir: PathLike = BNDB_DIR,\r\n json_dir: PathLike = JSON_DIR,\r\n force: bool = False,\r\n version: JsonFormatVersion = 2,\r\n emit_status: tp.Callable = print,\r\n update_analysis: bool = False,\r\n filters: SymbolFilters = DEFAULT_FILTERS,\r\n):\r\n # we will autocreate some subdirs, but for safety against mistakes\r\n # we won't create anything above the output dir itself\r\n _require_dir_exists(Path(json_dir).parent)\r\n\r\n old_md5sums = {} if force else _read_md5s_file(json_dir)\r\n\r\n common_types = _read_common_types(json_dir, version=version)\r\n\r\n for game in games:\r\n bndb_path = os.path.join(bndb_dir, f'{game}.bndb')\r\n json_subdir = os.path.join(json_dir, f'{game}')\r\n if _compute_md5(bndb_path) == _lookup_md5(old_md5sums, game, 'bndb', version=version):\r\n emit_status(f\"{game}: up to date\")\r\n continue\r\n\r\n emit_status(f\"{game}: exporting...\")\r\n with open_bv(bndb_path, update_analysis=update_analysis) as bv:\r\n os.makedirs(json_subdir, exist_ok=True)\r\n _export(bv, path=json_subdir, common_types=common_types, filters=filters, version=version)\r\n\r\n _update_md5s(games=[game], keys=all_md5_keys(version), bndb_dir=bndb_dir, json_dir=json_dir, version=version)\r\n emit_status(\"done\")\r\n\r\ndef export_all_common(bv, json_dir=JSON_DIR, force=False, emit_status=print, filters=DEFAULT_FILTERS):\r\n \"\"\" Update the json files in the _common directory, acquiring types from the given BV. \"\"\"\r\n _require_dir_exists(os.path.dirname(json_dir))\r\n os.makedirs(os.path.join(json_dir, COMMON_DIRNAME), exist_ok=True)\r\n\r\n # We want to make sure everything actually updates, or else we could be left with inconsistencies.\r\n get_types_path = lambda name: os.path.join(json_dir, COMMON_DIRNAME, name, 'types-ext.json')\r\n invalidated_dirs = [name for name in os.listdir(json_dir) if os.path.exists(get_types_path(name))]\r\n\r\n things_to_update = {}\r\n for type_library in bv.type_libraries:\r\n if not type_library.named_types:\r\n continue # empty, don't bother\r\n dirname = type_library.name.rsplit('.', 1)[0]\r\n # the outer closure (an IIFE) is to create a permanent binding to the current value of 'type_library';\r\n # otherwise, all closures would be for the last type library in the BV\r\n things_to_update[dirname] = (lambda lib: lambda: _export_types_from_type_library(bv, get_types_path(dirname), lib, filters))(type_library)\r\n\r\n things_to_update[bv.platform.name] = lambda: _export_types_from_dict(bv, get_types_path(bv.platform.name), bv.platform.types, {}, filters)\r\n\r\n names_unable_to_update = [name for name in invalidated_dirs if name not in things_to_update]\r\n if names_unable_to_update:\r\n err_msg = f'unable to update: {names_unable_to_update}. Perhaps this is only available in another BV?'\r\n log.log_error(err_msg)\r\n if not force:\r\n raise RuntimeError(err_msg)\r\n\r\n for key, func in things_to_update.items():\r\n print(get_types_path(key))\r\n os.makedirs(os.path.join(json_dir, COMMON_DIRNAME, key), exist_ok=True)\r\n func()\r\n\r\nclass SymbolsToWrite:\r\n \"\"\" All exportable symbols from an exe in a format independent of JSON database version. \"\"\"\r\n class Static(tp.NamedTuple):\r\n address: int\r\n name: str\r\n bn_type: bn.Type\r\n comment: tp.Optional[str]\r\n\r\n class Func(tp.NamedTuple):\r\n address: int\r\n name: str\r\n comment: tp.Optional[str]\r\n\r\n class Case(tp.NamedTuple):\r\n address: int\r\n name: str\r\n\r\n statics: tp.List[Static]\r\n funcs: tp.List[Func]\r\n cases: tp.Mapping[str, tp.List[Case]]\r\n\r\n def __init__(self, statics, funcs, cases):\r\n self.statics = statics\r\n self.funcs = funcs\r\n self.cases = cases\r\n\r\ndef _export_symbols(bv, path, version: JsonFormatVersion, filters: SymbolFilters):\r\n symbols = _get_exported_symbols(bv, filters)\r\n _write_symbols_files(bv, path, symbols=symbols, version=version)\r\n\r\ndef _get_exported_symbols(bv, filters: SymbolFilters):\r\n # precompute expensive properties\r\n bv_data_vars = bv.data_vars\r\n bv_symbols = bv.symbols\r\n\r\n statics = []\r\n funcs = []\r\n cases = defaultdict(list)\r\n for name, symbol in bv_symbols.items():\r\n if isinstance(symbol, list):\r\n symbol = symbol[0] # FIXME: document why\r\n address = symbol.address\r\n if symbol.type == bn.SymbolType.DataSymbol:\r\n case_data = filters.as_case_label(name)\r\n if case_data:\r\n cases[case_data.table_name].append(SymbolsToWrite.Case(address, case_data.case))\r\n continue\r\n\r\n try:\r\n t = bv_data_vars[address].type\r\n except KeyError:\r\n continue\r\n\r\n export_name = filters.as_useful_static_symbol(name)\r\n if export_name is None:\r\n continue\r\n comment = bv.get_comment_at(address) or None # note: bn returns '' for no comment\r\n statics.append(SymbolsToWrite.Static(address, export_name, t, comment))\r\n\r\n elif symbol.type == bn.SymbolType.FunctionSymbol:\r\n export_name = filters.as_useful_func_symbol(name)\r\n if export_name is None:\r\n continue\r\n comment = bv.get_comment_at(address) or None\r\n funcs.append(SymbolsToWrite.Func(address, export_name, comment))\r\n\r\n statics.sort(key=lambda x: x.address)\r\n funcs.sort(key=lambda x: x.address)\r\n for v in cases.values():\r\n v.sort(key=lambda x: x.address)\r\n return SymbolsToWrite(statics=statics, funcs=funcs, cases=cases)\r\n\r\ndef _write_symbols_files(bv, path, version: JsonFormatVersion, symbols: SymbolsToWrite):\r\n return {\r\n 1: lambda: _write_symbols_files_v1(bv, path, symbols),\r\n 2: lambda: _write_symbols_files_v2(bv, path, symbols),\r\n }[version]()\r\n\r\ndef _write_symbols_files_v2(bv, path, symbols: SymbolsToWrite):\r\n ttree_converter = TypeToTTreeConverter(bv)\r\n\r\n def strip_missing_comment(d):\r\n if d['comment'] is None:\r\n del d['comment']\r\n return d\r\n\r\n def transform_static(data: SymbolsToWrite.Static):\r\n return strip_missing_comment(dict(\r\n addr=hex(data.address),\r\n name=data.name,\r\n type=ttree_converter.to_ttree(data.bn_type),\r\n comment=data.comment,\r\n ))\r\n\r\n def transform_func(data: SymbolsToWrite.Func):\r\n return strip_missing_comment(dict(\r\n addr=hex(data.address),\r\n name=data.name,\r\n comment=data.comment,\r\n ))\r\n\r\n def transform_case(data: SymbolsToWrite.Case):\r\n return dict(\r\n addr=hex(data.address),\r\n label=data.name,\r\n )\r\n\r\n schema: tp.Any # mypy memes, in any better language the 'schema' vars would be block-scoped\r\n\r\n with open_output_json_with_validation(os.path.join(path, 'statics.json')) as f:\r\n schema = {'@type': 'block-array'}\r\n nice_json(f, list(map(transform_static, symbols.statics)), schema)\r\n\r\n with open_output_json_with_validation(os.path.join(path, 'funcs.json')) as f:\r\n schema = {'@type': 'block-array'}\r\n nice_json(f, list(map(transform_func, symbols.funcs)), schema)\r\n\r\n with open_output_json_with_validation(os.path.join(path, 'labels.json')) as f:\r\n schema = {'@type': 'block-mapping', 'element': {'@type': 'block-array'}}\r\n json = {k: list(map(transform_case, v)) for (k, v) in symbols.cases.items()}\r\n nice_json(f, json, schema)\r\n\r\ndef _write_symbols_files_v1(bv, path, symbols: SymbolsToWrite):\r\n def transform_static(data: SymbolsToWrite.Static):\r\n return dict(\r\n addr=hex(data.address),\r\n name=data.name,\r\n type=str(data.bn_type),\r\n comment=data.comment,\r\n )\r\n\r\n def transform_func(data: SymbolsToWrite.Func):\r\n return dict(\r\n addr=hex(data.address),\r\n name=data.name,\r\n comment=data.comment,\r\n )\r\n\r\n def transform_case(data: SymbolsToWrite.Case):\r\n return (hex(data.address), data.name)\r\n\r\n schema: tp.Any # mypy memes, in any better language the 'schema' vars would be block-scoped\r\n\r\n with open_output_json_with_validation(os.path.join(path, 'statics.json')) as f:\r\n schema = {'@type': 'block-array'}\r\n nice_json(f, list(map(transform_static, symbols.statics)), schema)\r\n\r\n with open_output_json_with_validation(os.path.join(path, 'funcs.json')) as f:\r\n schema = {'@type': 'block-array'}\r\n nice_json(f, list(map(transform_func, symbols.funcs)), schema)\r\n\r\n with open_output_json_with_validation(os.path.join(path, 'labels.json')) as f:\r\n schema = {'@type': 'block-mapping', '@line-sep': 1, 'element': {'@type': 'block-array'}}\r\n json = {k: list(map(transform_case, v)) for (k, v) in symbols.cases.items()}\r\n nice_json(f, json, schema)\r\n\r\ndef _export_types(bv, path: Path, common_types: tp.Dict[str, TypeTree], version: JsonFormatVersion, filters: SymbolFilters):\r\n \"\"\" Writes all type-related json files for a bv to a directory. \"\"\"\r\n if version == 1:\r\n return _export_types_v1(bv, path, filters)\r\n elif version == 2:\r\n return _export_types_v2(bv, path, common_types, filters)\r\n else:\r\n assert False, version\r\n\r\ndef _export_types_v2(bv: bn.BinaryView, path: Path, common_types: tp.Dict[str, TypeTree], filters: SymbolFilters):\r\n \"\"\" Writes all type-related json files for a bv to a directory. \"\"\"\r\n types_by_origin = split_dict(bv.types, lambda name, ty: filters.classify_type_origin(name))\r\n\r\n export_version_props(bv, path)\r\n _export_types_from_dict(bv, path / 'types-own.json', types_by_origin[TypeOrigin.OURS], common_types, filters)\r\n _export_types_from_dict(bv, path / 'types-ext.json', types_by_origin[TypeOrigin.EXTERNAL], common_types, filters)\r\n\r\ndef _export_types_from_type_library(bv, path, type_library: bn.TypeLibrary, filters: SymbolFilters):\r\n \"\"\" Write a single file like ``types-own.json`` containing all types from a type library. \"\"\"\r\n # Here's the annoying thing:\r\n # - BinaryView is a central part of our type serialization\r\n # - A BinaryView will only lazily load types from a type library as they are needed\r\n # through certain API functions.\r\n # - We want to export all of the types in the library, since we can't tell ahead of time\r\n # which types are used by OTHER games.\r\n\r\n # We don't just want to tell the current BV to load all the types from the library because this\r\n # will have the effect of making all of the types permanently appear in the GUI's type list.\r\n #\r\n # So we make a new BV.\r\n original_bv = bv\r\n bv = bn.BinaryView()\r\n\r\n # TypeLibraries do not include platform types.\r\n # Luckily, bv.platform appears to settable.\r\n bv.platform = original_bv.platform\r\n\r\n # Import the types from the type library\r\n bv.add_type_library(type_library)\r\n for name in type_library.named_types:\r\n bv.import_library_type(name)\r\n\r\n _export_types_from_dict(bv, path, type_library.named_types, common_types={}, filters=filters)\r\n\r\ndef _export_types_from_dict(\r\n bv: bn.BinaryView,\r\n path: Path,\r\n types_to_export: tp.Mapping[bn.QualifiedName, bn.Type],\r\n common_types: tp.Dict[str, TypeTree],\r\n filters: SymbolFilters,\r\n):\r\n \"\"\" Write a single file like ``types-own.json`` for the given types. \"\"\"\r\n types = _create_types_file_json(bv, types_to_export, common_types, filters=filters)\r\n with open_output_json_with_validation(path) as f:\r\n nice_json(f, types, {\r\n '@type': 'block-mapping',\r\n '@line-sep': 1,\r\n 'element': {\r\n '@type': 'object-variant',\r\n '@tag': TAG_KEYWORD,\r\n 'struct': {\r\n '@type': 'block-object',\r\n 'members': {'@type': 'block-array'},\r\n },\r\n 'enum': {\r\n '@type': 'block-object',\r\n 'values': {'@type': 'block-array'}\r\n },\r\n 'union': {\r\n '@type': 'block-object',\r\n 'members': {'@type': 'block-array'}\r\n },\r\n 'bitfields': {\r\n '@type': 'block-object',\r\n 'members': {'@type': 'block-array'}\r\n },\r\n 'typedef': {\r\n '@type': 'inline',\r\n },\r\n },\r\n })\r\n\r\ndef _read_common_types(json_dir, version: JsonFormatVersion):\r\n return {\r\n 1: lambda: {},\r\n 2: lambda: _read_common_types_v2(json_dir),\r\n }[version]()\r\n\r\ndef _read_common_types_v2(json_dir):\r\n types = {}\r\n for path in glob.glob(os.path.join(json_dir, '_common', '*', 'types*.json')):\r\n types.update(json.load(open(path)))\r\n return types\r\n\r\ndef export_version_props(bv: bn.BinaryView, path):\r\n props = {'pointer-size': bv.arch.address_size}\r\n with open_output_json_with_validation(os.path.join(path, 'version-props.json')) as f:\r\n nice_json(f, props, {'@type': 'block-object'})\r\n\r\ndef _export_types_v1(bv: bn.BinaryView, path: Path, filters: SymbolFilters):\r\n enums = {}\r\n unions = {}\r\n structs = {}\r\n typedefs = {}\r\n bitfields = {}\r\n for type_name, ty in bv.types.items():\r\n type_name = str(type_name)\r\n\r\n classification, extra_payload = lookup_named_type_definition(bv, type_name)\r\n if classification == 'struct':\r\n structs[type_name] = structure_to_cereal_v1(ty, filters, _name_for_debug=type_name)\r\n elif classification == 'union':\r\n unions[type_name] = union_to_cereal_v1(ty, _name_for_debug=type_name)\r\n elif classification == 'enum':\r\n enums[type_name] = enum_to_cereal_v1(ty)\r\n elif classification == 'bitfields':\r\n bitfields[type_name] = enum_to_bitfields_cereal_v1(ty)\r\n elif classification == 'typedef':\r\n typedef_target = extra_payload\r\n typedefs[type_name] = {'def': str(typedef_target), 'size': typedef_target.width}\r\n\r\n structs_by_origin = split_dict(structs, lambda name, ty: filters.classify_type_origin(str(name)))\r\n\r\n with open_output_json_with_validation(path / 'type-enums.json') as f:\r\n nice_json(f, enums, {\r\n '@type': 'block-mapping',\r\n '@line-sep': 1,\r\n 'element': {'@type': 'block-array'},\r\n })\r\n\r\n with open_output_json_with_validation(path / 'type-bitfields.json') as f:\r\n nice_json(f, bitfields, {\r\n '@type': 'block-mapping',\r\n '@line-sep': 1,\r\n 'element': {'@type': 'block-array'},\r\n })\r\n\r\n with open_output_json_with_validation(path / 'type-unions.json') as f:\r\n nice_json(f, unions, {\r\n '@type': 'block-mapping',\r\n '@line-sep': 1,\r\n 'element': {'@type': 'block-array'},\r\n })\r\n\r\n with open_output_json_with_validation(path / 'type-aliases.json') as f:\r\n nice_json(f, typedefs, {\r\n '@type': 'block-mapping',\r\n '@line-sep': 0,\r\n })\r\n\r\n struct_schema = {\r\n '@type': 'block-mapping',\r\n '@line-sep': 1,\r\n 'element': {'@type': 'block-array'},\r\n }\r\n for origin, fname in [\r\n (TypeOrigin.OURS, 'type-structs-own.json'),\r\n (TypeOrigin.EXTERNAL, 'type-structs-ext.json'),\r\n ]:\r\n if origin in structs_by_origin:\r\n with open_output_json_with_validation(path / fname) as f:\r\n nice_json(f, structs_by_origin[origin], struct_schema)\r\n\r\n\r\ndef split_dict(input: tp.Dict[K, V], key: tp.Callable[[K, V], G], use_defaultdict=False) -> tp.Mapping[G, tp.Dict[K, V]]:\r\n \"\"\" Turn a dict into a nested dict that groups the original entries according to a key function. \"\"\"\r\n out = defaultdict(dict)\r\n for k, v in input.items():\r\n group_key = key(k, v)\r\n out[group_key][k] = v\r\n\r\n return out if use_defaultdict else dict(out)\r\n\r\n# =================================================\r\n\r\ndef import_all_functions(games=GAMES, bndb_dir=BNDB_DIR, json_dir=JSON_DIR, version=1, emit_status=print):\r\n return _import_all_symbols(\r\n games=games, bndb_dir=bndb_dir, json_dir=json_dir, version=version, emit_status=emit_status,\r\n json_filename='funcs.json', symbol_type=bn.SymbolType.FunctionSymbol,\r\n )\r\n\r\ndef import_all_statics(games=GAMES, bndb_dir=BNDB_DIR, json_dir=JSON_DIR, version=1, emit_status=print):\r\n return _import_all_symbols(\r\n games=games, bndb_dir=bndb_dir, json_dir=json_dir, version=version, emit_status=emit_status,\r\n json_filename='statics.json', symbol_type=bn.SymbolType.DataSymbol,\r\n )\r\n\r\n# NOTE: Old and not used in a while.\r\n# The thought was that if people submit Pull Requests to th-re-data I should be able to merge them into\r\n# my local databases with this function. But only one person has ever done that, and instead normally\r\n# I just manually add contributions by tossing a list into 'import_funcs_from_json' instead.\r\ndef _import_all_symbols(games, bndb_dir, json_dir, json_filename, symbol_type, version, emit_status):\r\n assert version == 1 # importing of version 2 not supported\r\n\r\n old_md5sums = _read_md5s_file(json_dir)\r\n\r\n for game in games:\r\n bndb_path = os.path.join(bndb_dir, f'{game}.bndb')\r\n json_path = os.path.join(json_dir, f'{game}', json_filename)\r\n try:\r\n with open(json_path) as f:\r\n funcs_json = json.load(f)\r\n except (IOError, json.decoder.JSONDecodeError) as e:\r\n emit_status(f'{game}: {e}')\r\n continue\r\n\r\n if _compute_md5(json_path) == _lookup_md5(old_md5sums, game, json_filename, version=version):\r\n emit_status(f\"{game}: up to date\")\r\n continue\r\n\r\n emit_status(f\"{game}: checking...\")\r\n with open_bv(bndb_path, update_analysis=False) as bv:\r\n if _import_symbols_from_json_v1(bv, funcs_json, symbol_type, emit_status=lambda s: emit_status(f'{game}: {s}')):\r\n emit_status(f'{game}: saving...')\r\n bv.save_auto_snapshot()\r\n\r\n _update_md5s(games=[game], keys=['bndb', json_filename], bndb_dir=bndb_dir, json_dir=json_dir, version=version)\r\n emit_status(\"done\")\r\n\r\n# =================================================\r\n\r\ndef nice_json(file, value, schema, final_newline=True, starting_indent=0, indent=2):\r\n \"\"\"\r\n A recursive json formatter which uses a schema to allow the caller to specify which\r\n things should be formatted block-style versus inline.\r\n \"\"\"\r\n _NiceJsonContext(file=file, indent_step=indent).format_value(value=value, schema=schema, indent=starting_indent)\r\n if final_newline:\r\n print(file=file)\r\n\r\nclass _NiceJsonContext:\r\n def __init__(self, file, indent_step):\r\n self.file = file\r\n self.indent_step = indent_step\r\n\r\n def format_value(self, value, schema, indent):\r\n if schema is None:\r\n schema = {'@type': 'inline'}\r\n\r\n if schema['@type'] == 'inline':\r\n json.dump(value, self.file)\r\n\r\n elif schema['@type'] == 'block-array':\r\n # Homogenous list\r\n assert isinstance(value, (list, tuple)), (value, schema)\r\n def do_item(item):\r\n self.format_value(item, schema.get('element', None), indent + self.indent_step)\r\n self.format_block('[', ']', indent, schema.get('@line-sep', 0), list(value), do_item)\r\n\r\n elif schema['@type'] == 'block-object':\r\n # Heterogenous dict\r\n assert isinstance(value, dict), (value, schema)\r\n def do_key(key):\r\n print(json.dumps(key) + ': ', end='', file=self.file)\r\n self.format_value(value[key], schema.get(key, None), indent + self.indent_step)\r\n self.format_block('{', '}', indent, schema.get('@line-sep', 0), list(value), do_key)\r\n\r\n elif schema['@type'] == 'block-mapping':\r\n # Homogenous dict\r\n assert isinstance(value, dict), (value, schema)\r\n def do_key(key):\r\n print(json.dumps(key) + ': ', end='', file=self.file)\r\n self.format_value(value[key], schema.get('element', None), indent + self.indent_step)\r\n self.format_block('{', '}', indent, schema.get('@line-sep', 0), list(value), do_key)\r\n\r\n elif schema['@type'] == 'object-variant':\r\n assert isinstance(value, dict), (value, schema)\r\n tag = schema['@tag']\r\n variant_name = value[tag]\r\n sub_schema = schema.get(variant_name)\r\n if not sub_schema:\r\n if '@default' not in schema:\r\n assert False, f'object variant schema missing schema for {repr(sub_schema)}'\r\n sub_schema = schema['@default']\r\n self.format_value(value, schema[variant_name], indent=indent)\r\n\r\n else:\r\n assert False, schema\r\n\r\n def format_block(self, open: str, close: str, indent: int, line_sep: int, items: tp.List, do_item: tp.Callable):\r\n if not items:\r\n print(' ' * indent + f'{open}{close}', end='', file=self.file)\r\n return\r\n first = True\r\n for item in items:\r\n print(file=self.file)\r\n print(' ' * indent + (f'{open} ' if first else ', '), end='', file=self.file)\r\n first = False\r\n do_item(item)\r\n print('\\n' * line_sep, end='', file=self.file)\r\n print('\\n' + ' ' * indent + close, end='', file=self.file)\r\n\r\n#============================================================================\r\n\r\ndef all_md5_keys(version: JsonFormatVersion):\r\n return {\r\n 1: [\r\n 'bndb',\r\n 'funcs.json',\r\n 'labels.json',\r\n 'statics.json',\r\n 'type-structs-own.json',\r\n 'type-structs-ext.json',\r\n 'type-aliases.json',\r\n 'type-bitfields.json',\r\n 'type-enums.json',\r\n 'type-unions.json',\r\n ],\r\n 2: [\r\n 'bndb',\r\n 'funcs.json',\r\n 'labels.json',\r\n 'statics.json',\r\n 'types-own.json',\r\n 'types-ext.json',\r\n ],\r\n }[version]\r\n\r\ndef _read_md5s_file(json_dir=JSON_DIR):\r\n md5sum_path = os.path.join(json_dir, MD5SUMS_FILENAME)\r\n try:\r\n with open(md5sum_path) as f:\r\n return json.load(f)\r\n except IOError: return {}\r\n except json.decoder.JSONDecodeError: return {}\r\n\r\ndef _update_md5s(games, keys, bndb_dir, json_dir, version: JsonFormatVersion):\r\n md5s = _read_md5s_file(json_dir)\r\n\r\n path_funcs = {\r\n # files not in json_dir\r\n 'bndb': (lambda game: os.path.join(bndb_dir, f'{game}.bndb')),\r\n }\r\n for filename in all_md5_keys(version):\r\n if filename not in path_funcs:\r\n path_funcs[filename] = lambda game: os.path.join(json_dir, game, filename)\r\n\r\n assert set(path_funcs) == set(all_md5_keys(version))\r\n for game in games:\r\n if game not in md5s:\r\n md5s[game] = {}\r\n for key in keys:\r\n md5s[game][key] = _compute_md5(path_funcs[key](game))\r\n\r\n with open(os.path.join(json_dir, MD5SUMS_FILENAME), 'w') as f:\r\n nice_json(f, md5s, {'@type': 'block-mapping'})\r\n\r\ndef _lookup_md5(md5s_dict, game, key, version: JsonFormatVersion):\r\n assert key in all_md5_keys(version) # protection against typos\r\n print(game, key)\r\n return md5s_dict.get(game, {}).get(key, None)\r\n\r\n@contextlib.contextmanager\r\ndef open_output_json_with_validation(path: PathLike):\r\n \"\"\" Open a file for writing json. Once the 'with' block is exited, the file will be\r\n reopened for reading to validate the JSON. \"\"\"\r\n with open(path, 'w') as f:\r\n yield f\r\n\r\n with open(path) as f:\r\n json.load(f) # this will fail if the JSON is invalid\r\n\r\n#============================================================================\r\n\r\ndef _require_dir_exists(path: PathLike):\r\n if not Path(path).exists:\r\n raise IOError(f\"{path}: No such directory\")\r\n\r\n#============================================================================\r\n\r\n# Check if any of the given named tpyes have inconsistent definitions\r\n# between all of the version types files\r\ndef check_all_structs(names, root_name=None):\r\n ds = {}\r\n for child in Path(JSON_DIR).iterdir():\r\n fpath = child / 'types-ext.json'\r\n if fpath.exists:\r\n version = child.name\r\n ds[version] = json.load(open(fpath))\r\n\r\n versions = list(ds)\r\n if root_name:\r\n versions = [v for v in versions if root_name in ds[v]]\r\n print(versions)\r\n\r\n for name in names:\r\n first = None\r\n for version in versions:\r\n if (not root_name) and name not in ds[version]:\r\n continue\r\n if first is None:\r\n first = ds[version][name]\r\n else:\r\n if ds[version][name] != first:\r\n print('==================')\r\n print(version, name, first)\r\n print(version, name, ds[version][name])\r\n\r\ndef all_game_bvs(games=GAMES):\r\n bvs = []\r\n for game in games:\r\n print(game)\r\n bndb_path = Path(BNDB_DIR) / f'{game}.bndb'\r\n bvs.append(open_bv(bndb_path, update_analysis=False))\r\n return bvs\r\n\r\n#============================================================================\r\n\r\ndef make_c_header_zip(bvs, games, outpath: PathLike = Path(JSON_DIR) / 'th-re-c-defs.zip'):\r\n from .export_to_c import make_c_header_zip as impl\r\n impl(bvs, games, outpath)\r\n\r\n#============================================================================\r\n# things used at least once in the past to perform mass changes to my db to fix consistency/integrity errors and etc.\r\n#\r\n# some of these are pretty specific to my DB. They're only here in __init__ because I use them\r\n# directly from the repl.\r\n\r\ndef fix_label_names(bvs: tp.List[bn.BinaryView]):\r\n \"\"\" Add missing '__case_' infixes to special case labels. (hack for personal use) \"\"\"\r\n for bv in bvs:\r\n print(bv)\r\n # gather all label groups\r\n symbols = [v[0] for v in bv.symbols.values() if v[0].type == bn.SymbolType.DataSymbol]\r\n group_prefixes = set()\r\n is_valid_case_name = lambda name: '__case_' in name or '__cases_' in name\r\n for symbol in symbols:\r\n name = str(symbol.name) # in case of QualifiedName\r\n if is_valid_case_name(name):\r\n group_prefixes.add(name[:name.index('__case')])\r\n\r\n for symbol in symbols:\r\n name = str(symbol.name) # in case of QualifiedName\r\n if is_valid_case_name(name):\r\n continue\r\n parts = name.split('__', 1)\r\n if len(parts) > 1 and parts[0] in group_prefixes:\r\n new_name = parts[0] + '__case_' + parts[1]\r\n bv.define_user_symbol(bn.Symbol(bn.SymbolType.DataSymbol, symbol.address, new_name))\r\n\r\n# def fix_vtable_names(bvs, names_to_consider):\r\n# for bv in bvs:\r\n# for k in names_to_consider:\r\n# typ = bv.get_type_by_name(k)\r\n# if typ is not None and isinstance(typ, bn.StructureType):\r\n# if typ.members and typ.members[0].name == 'lpVtbl':\r\n# # print('-', k, bv)\r\n# fix_vtable_name(bv, k)\r\n\r\n# def fix_super_names(bvs, names_to_consider):\r\n# for bv in bvs:\r\n# for k in names_to_consider:\r\n# typ = bv.get_type_by_name(k)\r\n# if typ is not None and isinstance(typ, bn.StructureType):\r\n# if typ.members and typ.members[0].name == 'parent':\r\n# # print('-', k, bv)\r\n# fix_super_name(bv, k)\r\n\r\n# def fix_iunknown_types(bvs, names_to_consider):\r\n# for bv in bvs:\r\n# for k in names_to_consider:\r\n# typ = bv.get_type_by_name(k)\r\n# if typ is not None and isinstance(typ, bn.StructureType):\r\n# if typ.members and typ.members[0].name == 'parent':\r\n# # print('-', k, bv)\r\n# fix_super_name(bv, k)\r\n\r\n# def fix_vtable_name(bv: bn.BinaryView, name):\r\n# typ = bv.get_type_by_name(name)\r\n# assert isinstance(typ, bn.StructureType)\r\n# structure = typ.mutable_copy()\r\n# assert structure.members[0].name == 'lpVtbl'\r\n# structure.replace(0, structure.members[0].type, 'vtable')\r\n# bv.define_user_type(name, structure)\r\n\r\n\r\n# def fix_super_name(bv: bn.BinaryView, name):\r\n# typ = bv.get_type_by_name(name)\r\n# assert isinstance(typ, bn.StructureType)\r\n# structure = typ.mutable_copy()\r\n# assert structure.members[0].name == 'parent'\r\n# structure.replace(0, structure.members[0].type, 'super')\r\n# bv.define_user_type(name, structure)\r\n\r\n# def fix_all_object_sizes(bvs):\r\n# for bv in bvs:\r\n# for name, ty in bv.types.items():\r\n# if ty.alignment == 4 and ty.width == 5:\r\n# if not (isinstance(ty, bn.StructureType) and ty.members and ty.members[0].name == 'vtable'):\r\n# print('skipping', name)\r\n# continue\r\n\r\n# struct = ty.mutable_copy()\r\n# assert struct.members[1].type.width == 1\r\n# struct.replace(1, bn.Type.int(4), name='__make_struct_bigger_than_a_dword_so_binja_sees_when_vtable_is_read')\r\n# bv.define_user_type(name, struct)\r\n\r\n# def fix_struct_sizes_for_alignment(bv: bn.BinaryView):\r\n# for name, ty in bv.types.items():\r\n# if ty.width % ty.alignment == 0:\r\n# continue\r\n# print(name)\r\n# struct = ty.mutable_copy()\r\n# new_width = (ty.width - (ty.width % ty.alignment)) + ty.alignment\r\n\r\n# assert new_width >= struct.width\r\n# assert new_width - struct.alignment < struct.width\r\n# struct.width = new_width\r\n# assert struct.width % struct.alignment == 0\r\n\r\n# bv.define_user_type(name, struct)\r\n\r\n# def fff(r, bvs):\r\n# for (i,g) in enumerate(GAMES):\r\n# #if g != 'th14.v1.00b'# and bvs[i].symbols['Direct3DCreate9']:\r\n# print(g)\r\n# if 'IUnknown' in bvs[i].types:\r\n# continue\r\n# print('DO DEFS')\r\n# for k, v in bvs[i].parse_types_from_string('''\r\n# struct IUnknown;\r\n# struct IUnknownVtbl {\r\n# int32_t (* QueryInterface)(struct IUnknown*, GUID*, void**);\r\n# uint32_t (* AddRef)(struct IUnknown*);\r\n# uint32_t (* Release)(struct IUnknown*);\r\n# };\r\n\r\n# struct IUnknown {\r\n# struct IUnknownVtbl* vtable;\r\n# char __make_struct_bigger_than_a_dword_so_binja_sees_when_vtable_is_read;\r\n# };\r\n# ''').types.items():\r\n# bvs[i].define_user_type(k, v)\r\n# # try:\r\n# # r.import_type_from_bv(bvs[i], bvs[GAMES.index('th14.v1.00b')], 'IUnknown', exist_ok=True)\r\n# # except:\r\n# # print(g)\r\n# # pass\r\n","repo_name":"exphp-share/bnplugins","sub_path":"exphp_export/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":33941,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8461170418","text":"from pysmt.shortcuts import Symbol, Not, And, Or, Implies, Ite, BVAdd, BV, EqualsOrIff, BVNot, BVSub\nfrom pysmt.shortcuts import is_sat, is_unsat, Solver, TRUE\nfrom pysmt.typing import BOOL, BVType\nfrom pysmt.shortcuts import Interpolator, simplify\nfrom pysmt.logics import QF_BV\n\nfrom utilfunc import _get_var, _get_cubes_with_more_var, _get_cubes_with_fewer_var\nfrom cegpbe import CexGuidedPBE\nfrom opextract import OpExtractor\nfrom sts import TransitionSystem\n\nimport heapq\n\n\n#----------- Basic Parameters -------------------\nConfig_Max_Frame = 10000000\nConfig_use_itp_in_pushing = False\nConfig_analyze_use_itp_in_pushing = True\nConfig_debug = True\nConfig_partial_model = True\nConfig_simplify_itp = True\nConfig_rm_cex_in_prev = True\nConfig_push_facts = True\nConfig_push_facts_sanity_check = False\n#----------- Heuristics -------------------\nConfig_enhance_giveup_threshold = (2, 3) # (8,10)\nConfig_cex_invalid_itp_guess_threshold = (4,5) # (18, 20)\nConfig_try_drop_cex = (5,5) # (30, 50) # after 30 frames, per 50\n\n\ndef next_var(v):\n \"\"\"Returns the 'next' of the given variable\"\"\"\n return Symbol(\"%s_prime\" % v.symbol_name(), v.symbol_type())\n\ndef pause():\n if Config_debug:\n input()\n\n\n\nclass BaseAddrCnt(TransitionSystem):\n def __init__(self, nbits):\n self.nbits = nbits # save the number of bits\n self.mask = 2**(nbits)-1\n\n base = Symbol('base', BVType(nbits))\n addr = Symbol('addr', BVType(nbits))\n cnt = Symbol('cnt', BVType(nbits))\n inp = Symbol('inp', BVType(nbits))\n lden = Symbol('lden', BVType(1))\n\n self.base = base \n self.addr = addr \n self.cnt = cnt \n self.inp = inp \n self.lden = lden \n\n\n variables = [base, addr, cnt, inp, lden]\n prime_variables = [TransitionSystem.get_prime(v) for v in variables]\n init = base.Equals(0) & addr.Equals(0) & cnt.Equals(0)\n trans= TransitionSystem.get_prime(base).Equals( \\\n Ite(lden.Equals(1), inp, base )) & \\\n TransitionSystem.get_prime(addr).Equals( \\\n Ite(lden.Equals(1), inp, BVAdd(addr, BV(1, nbits) ) )) & \\\n TransitionSystem.get_prime(cnt).Equals( \\\n Ite(lden.Equals(1), BV(0, nbits), BVAdd(cnt, BV(1, nbits) ) ))\n \n TransitionSystem.__init__(self, \\\n variables = variables, \\\n prime_variables = prime_variables, \\\n init = init, trans = trans )\n\n def neq_property(self, base, addr, cnt):\n addr = addr & self.mask\n base = base & self.mask\n cnt = cnt & self.mask\n\n assert ( addr != ((base+cnt) & self.mask) )\n\n return Not( self.addr.Equals(addr) & self.base.Equals(base) & self.cnt.Equals(cnt) )\n\n\nclass TwoCnt(TransitionSystem):\n def __init__(self, nbits, zero_init = False):\n self.nbits = nbits # save the number of bits\n self.mask = 2**(nbits)-1\n\n self.c1 = Symbol('c1', BVType(nbits))\n self.c2 = Symbol('c2', BVType(nbits))\n self.inp = Symbol('inp', BVType(nbits))\n self.lden = Symbol('lden', BVType(1))\n\n variables = [self.c1, self.c2, self.inp, self.lden]\n prime_variables = [TransitionSystem.get_prime(v) for v in variables]\n if zero_init:\n init = self.c1.Equals(0) & self.c2.Equals(self.mask)\n else:\n init = self.c1.Equals(self.inp) & self.c2.Equals(BVNot(self.inp))\n trans= TransitionSystem.get_prime(self.c1).Equals( \\\n Ite(self.lden.Equals(1), self.inp, BVAdd(self.c1, BV(1, nbits) ))) & \\\n TransitionSystem.get_prime(self.c2).Equals( \\\n Ite(self.lden.Equals(1), BVNot(self.inp), BVSub(self.c2, BV(1, nbits) )))\n \n TransitionSystem.__init__(self, \\\n variables = variables, \\\n prime_variables = prime_variables, \\\n init = init, trans = trans )\n\n def neq_property(self, c1, c2):\n c1 = c1 & self.mask\n c2 = c2 & self.mask\n\n assert ( c1 + c2 != self.mask)\n\n return Not( self.c1.Equals(c1) & self.c2.Equals(c2) )\n\n def false_property(self, c1, c2):\n c1 = c1 & self.mask\n c2 = c2 & self.mask\n\n assert ( c1 + c2 == self.mask)\n\n return Not( self.c1.Equals(c1) & self.c2.Equals(c2) )\n\n\nclass TwoCntNoload(TransitionSystem):\n def __init__(self, nbits, zero_init = False):\n self.nbits = nbits # save the number of bits\n self.mask = 2**(nbits)-1\n\n self.c1 = Symbol('c1', BVType(nbits))\n self.c2 = Symbol('c2', BVType(nbits))\n self.inp = Symbol('inp', BVType(nbits))\n\n variables = [self.c1, self.c2, self.inp]\n prime_variables = [TransitionSystem.get_prime(v) for v in variables]\n if zero_init:\n init = self.c1.Equals(0) & self.c2.Equals(self.mask)\n else:\n init = self.c1.Equals(self.inp) & self.c2.Equals(BVNot(self.inp))\n trans= TransitionSystem.get_prime(self.c1).Equals( \\\n BVAdd(self.c1, BV(1, nbits) )) & \\\n TransitionSystem.get_prime(self.c2).Equals( \\\n BVSub(self.c2, BV(1, nbits) ))\n \n TransitionSystem.__init__(self, \\\n variables = variables, \\\n prime_variables = prime_variables, \\\n init = init, trans = trans )\n\n def neq_property(self, c1, c2):\n c1 = c1 & self.mask\n c2 = c2 & self.mask\n\n assert ( c1 + c2 != self.mask)\n\n return Not( self.c1.Equals(c1) & self.c2.Equals(c2) )\n\n def false_property(self, c1, c2):\n c1 = c1 & self.mask\n c2 = c2 & self.mask\n\n assert ( c1 + c2 == self.mask)\n\n return Not( self.c1.Equals(c1) & self.c2.Equals(c2) )\n\n# keep_vars and remove_vars are primal var list/set\n\nclass PDR(object):\n def __init__(self, system):\n self.system = system\n self.frames = [ [system.init], [] ] # list of list of clauses\n \n if Config_partial_model:\n self.solver = Solver(name = 'z3') # use z3 for partial model\n else:\n self.solver = Solver()\n\n self.itp_solver = Interpolator(logic=QF_BV)\n self.prime_map = dict([(v, TransitionSystem.get_prime(v)) for v in self.system.variables])\n self.primal_map = dict([(TransitionSystem.get_prime(v), v) for v in self.system.variables])\n self.cexs_blocked = {} # : n -> list of cex, maybe blocked already\n self.unblockable_fact = {} # : n -> list of ex, unblocked, used to syn\n\n\n self.cexs_pushed_idxs_map = {} # n->idx+1 tried\n self.frames_pushed_idxs_map = {} # n->idx+1 tried\n self.facts_pushed_idxs_map = {} # n->idx+1 tried\n self.min_cex_frames_changed = Config_Max_Frame\n\n # map: v --> next_v\n # itp and cex number mapping\n self.lemma_to_cex_map_perframe = {} # >\n self.cex_pushed_status = {} # \n self.cex_origin = {} # >\n self.cex_covered_by_pushed_lemmas = {} # \n\n # statistics\n self.cex_to_itp_enhance_fail = {}\n self.cex_to_itp_push_fail = {}\n #canonicalize_cex\n\n def dump_frames(self, toStr = False):\n retS = []\n def _printStr(*argl, **argd):\n if (toStr):\n retS.append( ''.join ( argl ) )\n else:\n print(*argl, **argd)\n\n _printStr ('---------- Frames DUMP ----------')\n for fidx,f in enumerate(self.frames):\n _printStr ('Frame : %d'%fidx)\n for lidx, lemma in enumerate(f):\n ptr = '*' if self.frames_pushed_idxs_map.get(fidx,0) == lidx else ' '\n blocked_cexsIdx = self.lemma_to_cex_map_perframe.get(fidx, dict()).get(lidx, set())\n _printStr (' %s l%d: ' % (ptr,lidx) , lemma.serialize(), '| blockes:', str(blocked_cexsIdx))\n if self.frames_pushed_idxs_map.get(fidx,0) == lidx + 1:\n _printStr (' all tried to push')\n\n if fidx in self.cexs_blocked:\n _printStr (' CEX blocked # : %d'% len(self.cexs_blocked[fidx]) , '| CEX covered : ', str(self.cex_covered_by_pushed_lemmas.get(fidx,set())))\n for cidx, cex in enumerate(self.cexs_blocked[fidx]):\n ptr = '*' if self.cexs_pushed_idxs_map.get(fidx,0) == cidx else ' ' # push pointer position\n cvr = '+' if cidx in self.cex_covered_by_pushed_lemmas.get(fidx,set()) else ' ' # covered by pushed lemmas\n pushed_status_list = self.cex_pushed_status.get(fidx, [])\n pushed_status = pushed_status_list[cidx] if cidx < len(pushed_status_list) else 'Unknown'\n origin = self.cex_origin.get(fidx, dict()).get(cidx, 'Unknown')\n hashkey = self._canonicalize_cex(cex)\n itp_push_status = self.cex_to_itp_push_fail.get(hashkey,(0,0))\n itp_repr_status = self.cex_to_itp_enhance_fail.get(hashkey,(0,0))\n _printStr (' %s%s c%d ' % (ptr,cvr, cidx), '|', \\\n str(itp_push_status), str(itp_repr_status), '|:', \\\n self.print_cube(cex), '| PS:', str(pushed_status), '| O:', str(origin))\n if self.cexs_pushed_idxs_map.get(fidx,0) == cidx + 1:\n _printStr (' all tried to push')\n if fidx in self.unblockable_fact:\n _printStr (' facts # : %d'% len(self.unblockable_fact[fidx]) )\n for cidx, fact in enumerate(self.unblockable_fact[fidx]):\n _printStr (' f%d: ' % cidx, self.print_cube(fact) )\n _printStr ('---------- END Frames DUMP ----------')\n return '\\n'.join(retS)\n\n def _canonicalize_cex(self, cex):\n \"\"\"cex to a hashable thing\"\"\"\n cex_str = [(v.symbol_name(), val) for v, val in cex ]\n return tuple(sorted(cex_str, key = lambda x: x[0]))\n\n def _add_cex(self, cex, fidx, origin = None):\n if fidx not in self.cexs_blocked:\n self.cexs_blocked[fidx] = []\n assert (cex not in self.cexs_blocked[fidx])\n\n if cex not in self.cexs_blocked[fidx]: # do you need check duplicity?\n self.cexs_blocked[fidx].append(cex)\n self.min_cex_frames_changed = min(self.min_cex_frames_changed, fidx)\n cexIdx=len(self.cexs_blocked[fidx])-1\n else:\n cexIdx=self.cexs_blocked[fidx].index(cex)\n\n if fidx not in self.cex_origin:\n self.cex_origin[fidx] = dict()\n if self.cex_origin[fidx].get(cexIdx, None) is None:\n self.cex_origin[fidx][cexIdx] = origin\n\n return cexIdx\n\n def _add_lemma(self, lemma, fidx, cidxs):\n \"\"\"cidxs should be a set\"\"\"\n assert (lemma not in self.frames[fidx])\n if lemma not in self.frames[fidx]:\n self.frames[fidx].append(lemma)\n self.min_cex_frames_changed = min(self.min_cex_frames_changed, fidx)\n lidx = len(self.frames[fidx])-1\n else:\n lidx = self.frames[fidx].index(lemma)\n if fidx not in self.lemma_to_cex_map_perframe:\n self.lemma_to_cex_map_perframe[fidx] = dict()\n self.lemma_to_cex_map_perframe[fidx][lidx] = self.lemma_to_cex_map_perframe[fidx].get(lidx, set()).union(cidxs)\n\n def _add_fact(self, fact, fidx):\n if fidx not in self.unblockable_fact:\n self.unblockable_fact[fidx] = []\n if fact not in self.unblockable_fact[fidx]: # TODO: not efficient\n self.unblockable_fact[fidx].append(fact)\n\n def _add_lemma_to_all_prev_frame(self, end_frame_id, lemma):\n for idx in range(1,end_frame_id+1):\n if lemma not in self.frames[idx]:\n self.frames[idx].insert(0, lemma)\n pushed_idx = self.frames_pushed_idxs_map.get(idx, 0)\n pushed_idx += 1\n self.frames_pushed_idxs_map[idx] = pushed_idx\n # fix the lemma_to_cex_map_perframe\n lidx_to_cidxs_map = list(self.lemma_to_cex_map_perframe.get(idx, dict()).items())\n self.lemma_to_cex_map_perframe[idx] = dict()\n for lidx, cidxs in lidx_to_cidxs_map:\n self.lemma_to_cex_map_perframe[idx][lidx+1] = cidxs\n\n\n def check_init_failed(self, prop, remove_vars, keep_vars):\n init_cex = self.solve(self.frames[0] + [ Not(prop) ] )\n print (\"[Checking init] F0 and not P\")\n if init_cex is not None:\n print(\"[Checking init] Property failed at INIT\")\n print(\"[Checking init] CEX: \", self.print_cube(init_cex))\n return True\n print (\"[Checking init] F0 and T and not P'\")\n init_cex = self.get_bad_state_from_property_invalid_after_trans(\n prop = prop, idx = 0, use_init = True, remove_vars = remove_vars, keep_vars = keep_vars)\n if init_cex is not None:\n print(\"[Checking init] Property failed at F1\")\n print(\"[Checking init] CEX @F0: \", self.print_cube(init_cex))\n return True\n print (\"[Checking init] Done\")\n return False\n\n\n\n def check_property(self, prop, remove_vars = [], keep_vars = None):\n \"\"\"Property Directed Reachability approach without optimizations.\"\"\"\n print(\"[Checking property] Property: %s.\" % prop)\n\n if self.check_init_failed(prop, remove_vars, keep_vars):\n return False\n\n while True:\n self.sanity_check_frame_monotone()\n self.sanity_check_imply()\n self.dump_frames()\n print ('Total Frames: %d, L %d , C %d ' %( len(self.frames) , len(self.frames[-1]), len(self.cexs_blocked.get(len(self.frames)-1,[]))))\n pause ()\n\n # frame[-1] /\\ T -> not (prop)\n cube = self.get_bad_state_from_property_invalid_after_trans( \\\n prop = prop, idx = len(self.frames)-1, use_init = False, remove_vars = remove_vars, keep_vars = keep_vars)\n\n print ('[Checking property] Get cube: ', cube , ' @F%d' % (len(self.frames)-1))\n # cube is list of (var, assignments)\n if cube is not None:\n # Blocking phase of a bad state\n if not self.recursive_block(cube, len(self.frames)-1, remove_vars, keep_vars, cex_origin = 'prop' ):\n print(\"[Checking property] Bug found at step %d\" % (len(self.frames)))\n return False\n else:\n print(\"[Checking property] Cube blocked '%s'\" % self.print_cube(cube))\n else:\n # Checking if the last two frames are equivalent i.e., are inductive\n if self.is_last_two_frames_inductive():\n print(\"[Checking property] The system is safe, frame : %d\" % len(self.frames) )\n return True\n else:\n print(\"[Checking property] Adding frame %d...\" % (len(self.frames)))\n self.frames.append([])\n self.push_lemma_from_the_lowest_frame(remove_vars, keep_vars) # TODO\n if self.is_last_two_frames_inductive():\n print(\"[Checking property] The system is safe, frame : %d\" % len(self.frames) )\n return True\n\n # you should try to push existing clauses\n \n # TODO: problem : INIT -> next frame ????\n # put too few in the \n def push_lemma_from_the_lowest_frame(self, remove_vars, keep_vars):\n if self.min_cex_frames_changed == Config_Max_Frame:\n self.min_cex_frames_changed = 1\n start_frame = self.min_cex_frames_changed\n # do not push from the initial frame\n print ('[pushes] F%d to F%d' % (start_frame, len(self.frames)-2))\n self.min_cex_frames_changed = len(self.frames)-1\n for fidx in range(start_frame, len(self.frames)-1):\n self.push_lemma_from_frame(fidx, remove_vars, keep_vars)\n\n def get_pre_post_state_from_property_invalid_after_trans(self, prop, fidx, T, variables, remove_vars, keep_vars ):\n prevF = self.frames[fidx]\n print (' [pre_post_p_trans] Property:', prop.serialize())\n print (' [pre_post_p_trans] var will => prime')\n #print (' [pre_post_p_trans] prevF:', prevF)\n\n pre_ex = []\n post_ex = []\n\n if self.solver.solve( prevF + [T, Not( prop.substitute(self.prime_map))] ):\n model = self.solver.get_model()\n for v, val in model:\n if v in variables: # pre_ex\n if v in remove_vars:\n continue\n if isinstance(keep_vars, list) and len(keep_vars) > 0 and v not in keep_vars:\n continue\n pre_ex.append((v,val))\n else:\n v_primal = self.primal_map[v]\n if v_primal in remove_vars:\n continue\n if isinstance(keep_vars, list) and len(keep_vars) > 0 and v_primal not in keep_vars:\n continue\n post_ex.append((v_primal,val))\n assert (len(pre_ex) > 0 and len(post_ex) > 0)\n return pre_ex, post_ex\n #\n return None, None # pre/post ex: None\n\n def shrink_var_cexs(self, cexs, fidx, varset, remove_vars, keep_vars):\n\n print (' [shrink_var_cexs on F%d] get %d before shrink' % (fidx,len(cexs)))\n small_cexs = []\n set_idx_of_cex_blocked = set()\n\n for cidx, cube in enumerate(cexs):\n if _get_var(cube).issubset(varset):\n small_cexs.append(dict(cube))\n\n small_cube = []\n for v, val in cube:\n if v in varset:\n small_cube.append((v, val))\n assert (len(small_cube) > 0)\n\n cex_origin = self.cex_origin.get(fidx,dict()).get(cidx,None)\n if self.recursive_block(small_cube, fidx, remove_vars = remove_vars, keep_vars = keep_vars, cex_origin = cex_origin):\n small_cexs.append(dict(small_cube))\n set_idx_of_cex_blocked.add(cidx)\n\n if (self.cexs_blocked[fidx][-1] == small_cube):\n #self.dump_frames()\n #print ('fidx:',fidx, '| cexs:', cexs, '| varset:', varset)\n #print ('small_cube: ', str(small_cube))\n set_idx_of_cex_blocked.add(len(self.cexs_blocked[fidx]) - 1) # subsume\n\n print (' [shrink_var_cexs on F%d] get %d/%d after shrink' % (fidx,len(small_cexs), len(cexs)))\n return small_cexs, set_idx_of_cex_blocked\n\n def get_cex_idx(self, cex, fidx):\n if cex not in self.cexs_blocked[fidx]:\n return '*subsume*'\n return (self.cexs_blocked[fidx].index(cex))\n\n\n def push_lemma_from_frame(self, fidx, remove_vars, keep_vars):\n\n #... think about push facts ??? \n assert (len(self.frames) > fidx+1)\n\n assert (len(self.frames[fidx]) > 0 )\n\n start_lemma_idx = self.frames_pushed_idxs_map.get(fidx, 0)\n end_lemma_idx = len(self.frames[fidx]) # we can decide if we want to update this\n # iterate over the lemmas and the cex they blocked, tried to push \n\n if (len(self.cexs_blocked.get(fidx,[])) == 0): # else no cex to push\n print (' [push_lemma from F%d] no cex to push from F%d'%(fidx,fidx))\n pause ()\n #assert (fidx in self.cexs_blocked)\n\n if Config_push_facts:\n if fidx in self.unblockable_fact:\n start_fact_idx = self.facts_pushed_idxs_map.get(fidx, 0)\n end_fact_idx = len(self.unblockable_fact[fidx])\n for factIdx in range(start_fact_idx, end_fact_idx):\n fact = self.unblockable_fact[fidx][factIdx]\n # once a fact always a fact\n if Config_push_facts_sanity_check:\n assert (not self.recursive_block(fact, fidx+1, remove_vars, keep_vars, cex_origin = 'push_facts'))\n if fact not in self.unblockable_fact.get(fidx+1,[]):\n self._add_fact(fact = fact, fidx = fidx + 1)\n\n \n if fidx in self.cexs_blocked:\n\n start_cexs_idx = self.cexs_pushed_idxs_map.get(fidx,0)\n end_cex_idx = len(self.cexs_blocked[fidx])\n\n if fidx not in self.cex_pushed_status:\n self.cex_pushed_status[fidx] = []\n assert (start_cexs_idx == len(self.cex_pushed_status[fidx]))\n\n for cexIdx in range(start_cexs_idx,end_cex_idx):\n cex = self.cexs_blocked[fidx][cexIdx]\n print (' [push_lemma F%d] cex to try: c%d :'%(fidx, cexIdx), self.print_cube(cex))\n if self.recursive_block(cex, fidx+1, remove_vars, keep_vars, cex_origin = cexIdx):\n print (' [push_lemma F%d] cex is pushed: '%fidx, self.print_cube(cex))\n self.cex_pushed_status[fidx].append( self.get_cex_idx(cex,fidx+1) )\n else:\n self.cex_pushed_status[fidx].append(None)\n\n self.cexs_pushed_idxs_map[fidx] = end_cex_idx # we will push all the cexs at the early time\n\n # if len(self.cexs_blocked[fidx]) > end_cex_idx: there are now more cexs to try pushing\n # there could be more cexs to push (we can decide if we want to add a loop here)\n\n unpushed_lemmas = [] # list of (lidx, lemma, prev_ex, post_ex )\n\n for lemmaIdx in range(start_lemma_idx, end_lemma_idx):\n lemma = self.frames[fidx][lemmaIdx]\n print (' [push_lemma F%d] Try pushing lemma l%d to F%d: ' % (fidx, lemmaIdx, fidx+1) , (lemma.serialize()))\n\n \n while True: # try push\n\n prev_ex, post_ex = \\\n self.get_pre_post_state_from_property_invalid_after_trans(prop = lemma, fidx = fidx, \\\n T = self.system.trans, variables = self.system.variables, \\\n remove_vars = remove_vars, keep_vars = keep_vars )\n\n if prev_ex is None: # post_ex should be none also\n assert (post_ex is None)\n print (' [push_lemma F%d] Succeed in pushing l%d!'%(fidx, lemmaIdx))\n if Config_use_itp_in_pushing:\n print (' [push_lemma F%d] And we add its ITP!'%fidx) # do we really do this?\n if lemma not in self.frames[fidx+1]:\n # get the cidxs in the next frame\n # find the push cex list\n blocked_cexIdx_in_current_frame = self.lemma_to_cex_map_perframe.get(fidx, dict()).get(lemmaIdx, set())\n blocked_cexIdx_in_next_frame = set()\n for cidx in blocked_cexIdx_in_current_frame:\n nxt_idx = self.cex_pushed_status.get(fidx,[])[cidx]\n assert (nxt_idx is not None) \n if nxt_idx == '*subsume*':\n continue # do not add subsumed cex\n # it must have been pushed successfully, otherwise, how could the itp pushed succesfully\n blocked_cexIdx_in_next_frame.add(nxt_idx)\n\n # deal with lemma cex-idx map in the next frame (should be in the add_lemma part?)\n self._add_lemma(lemma = lemma, fidx = fidx + 1, cidxs = blocked_cexIdx_in_next_frame)\n\n # update statistics of cex--lemma\n if len(blocked_cexIdx_in_current_frame) == 1:\n for cidx in blocked_cexIdx_in_current_frame:\n hashkey = self._canonicalize_cex( self.cexs_blocked[fidx][cidx] )\n n_fail, n_total = self.cex_to_itp_push_fail.get(hashkey, (0,0))\n self.cex_to_itp_push_fail[hashkey] = (n_fail, n_total+1)\n\n # deal with cex_covered_by_pushed_lemmas\n if fidx not in self.cex_covered_by_pushed_lemmas:\n self.cex_covered_by_pushed_lemmas[fidx] = set()\n self.cex_covered_by_pushed_lemmas[fidx] = self.cex_covered_by_pushed_lemmas[fidx].union(\\\n self.lemma_to_cex_map_perframe.get(fidx, dict()).get(lemmaIdx, set()) )\n\n break\n\n print (' [push_lemma F%d] Get pre cex:'%(fidx), prev_ex)\n # prev_ex is not None\n # try recursive block\n if prev_ex not in self.unblockable_fact.get(fidx,[]):\n if self.recursive_block(prev_ex, fidx, remove_vars, keep_vars, cex_origin = 'push_lemma' ):\n print (' [push_lemma F%d] cex blocked:'%(fidx))\n continue # try in next round\n # else recursive block failed\n # put it in the fact\n print (' [push_lemma F%d] fail due to pre-fact :'%fidx , self.print_cube(prev_ex))\n print (' [push_lemma F%d] post-fact :'%fidx , self.print_cube(post_ex))\n self._add_fact(fact=prev_ex, fidx=fidx) # add pre fact only if not in fact\n # always add post fact\n self._add_fact(fact=post_ex, fidx=fidx+1)\n\n unpushed_lemmas.append((lemmaIdx, lemma, prev_ex, post_ex))\n break \n # now handle the unpushed altogether\n\n for lemmaIdx, lemma, prev_ex, post_ex in unpushed_lemmas:\n # check if we really want to push this\n # if it has been covered by pushed lemmas, then we should be fine\n cexIdxs = self.lemma_to_cex_map_perframe.get(fidx, dict()).get(lemmaIdx, set())\n if len(cexIdxs) == 0:\n print (' [push_lemma F%d] skip l%d :'%(fidx, lemmaIdx) , lemma.serialize(), ' no cex value of it is known, skip')\n continue\n assert len(cexIdxs) != 0 , \"we should not push this kind of lemma\"\n \n status_list=self.cex_pushed_status.get(fidx,[])\n allSubsumed = True\n for cidx in cexIdxs:\n if cidx < len(status_list):\n if status_list[cidx] != '*subsume*':\n allSubsumed = False\n break\n if allSubsumed:\n print (' [push_lemma F%d] skip l%d :'%(fidx, lemmaIdx) , lemma.serialize(), ' its cex has been subsumed.')\n input ()\n continue\n\n if cexIdxs.issubset( self.cex_covered_by_pushed_lemmas.get(fidx, set()) ):\n print (' [push_lemma F%d] skip l%d :'%(fidx, lemmaIdx) , lemma.serialize(), ' as it has been covered by other successful pushes')\n input ()\n continue\n\n # update statistics of cex--lemma relation\n # after all previous update\n if len(cexIdxs) == 1:\n skip_this_lemma = False\n for cidx in cexIdxs:\n hashkey = self._canonicalize_cex( self.cexs_blocked[fidx][cidx] )\n n_fail, n_total = self.cex_to_itp_push_fail.get(hashkey, (0,0))\n if n_fail+1 > Config_cex_invalid_itp_guess_threshold[0] * (n_total +1)/Config_cex_invalid_itp_guess_threshold[1] and n_total +1 > Config_cex_invalid_itp_guess_threshold[1]:\n skip_this_lemma = True\n break\n self.cex_to_itp_push_fail[hashkey] = (n_fail+1, n_total+1) # once reach the limit we will not update it\n\n n_fail, n_total = self.cex_to_itp_enhance_fail.get(hashkey, (0,0))\n if n_fail > Config_enhance_giveup_threshold[0]*n_total/Config_enhance_giveup_threshold[1] and n_total > Config_enhance_giveup_threshold[1]:\n skip_this_lemma = True\n break\n\n if skip_this_lemma:\n print (' [push_lemma F%d] skip l%d :'%(fidx, lemmaIdx) , lemma.serialize(), ' too many failed itp/repair, skip')\n continue\n\n print (' [push_lemma F%d] start repair l%d :'%(fidx, lemmaIdx) , lemma.serialize())\n \n # or it is in the fact\n # then we know this lemma is a bad one\n # so let's repair it\n\n # IMPROVEMENT: variable set change below\n\n opextract = OpExtractor() # work on itp \n opextract.walk(lemma)\n lemma_var_set = opextract.Symbols\n post_ex_var_set = _get_var(post_ex)\n\n inv_var_set = lemma_var_set.union(post_ex_var_set)\n sorted_inv_var_set = sorted(list(inv_var_set), key = lambda x: x.symbol_name())\n # IMPROVEMENT: this is not right!!!\n blocked_cexs = self.cexs_blocked.get(fidx+1,[]) # fidx+1 is fewer cex\n facts = self.unblockable_fact[fidx+1] # facts should be more facts\n facts_on_inv_vars = _get_cubes_with_more_var(facts, inv_var_set)\n\n # IMPROVEMENT: you may not want to use all cex, \n # 1. probably just the unblocked ones\n # 2. probably just the one it blocks\n # 3. probably rule out those that are hard to block...\n # 4. probably you can try many different times with different ...\n # 5. but facts must be taken into consideration any way!!!\n cexs_on_inv_vars, blocked_c_idxs = self.shrink_var_cexs(cexs = blocked_cexs, \\\n fidx = fidx + 1, varset = inv_var_set, \\\n remove_vars = remove_vars, keep_vars = keep_vars) \n #cexs_on_inv_vars = _get_cubes_with_fewer_var(blocked_cexs, inv_var_set)\n sorted_allvars = sorted(self.system.variables, key = lambda x: x.symbol_name())\n sorted_prime_vars = sorted(self.system.prime_variables, key = lambda x: x.symbol_name())\n\n self.dump_frames()\n print (' [push_lemma F%d] Invoke SyGuS Now:'%(fidx))\n print ('----------------\\nvarset:\\n',inv_var_set)\n print ('----------------\\ncex:\\n', cexs_on_inv_vars)\n print ('----------------\\nfacts:\\n', facts_on_inv_vars)\n if (len(cexs_on_inv_vars) == 0 or len(facts_on_inv_vars) == 0):\n print (' [push_lemma F%d] WARNING: no cex! skip sygus'%(fidx))\n input ()\n continue\n\n\n\n cex_guided_pbe = CexGuidedPBE( \\\n primal_vars = self.system.variables,\n prime_vars = self.system.prime_variables,\n primal_map = self.primal_map, # next_v --> v\n prime_map = self.prime_map, # v --> next_v\n T = self.system.trans,\n F_idx_minus2 = self.frames[fidx],\n Init = self.system.init, # IMPROVEMENT: Use init\n inv_var_set = inv_var_set, # we can change this if necessary\n facts_on_inv_vars = facts_on_inv_vars,\n cexs_on_inv_vars = cexs_on_inv_vars,\n sorted_inv_var_set = sorted_inv_var_set,\n sorted_allvars = sorted_allvars,\n sorted_prime_vars = sorted_prime_vars,\n op_obj = opextract \\\n )\n\n # lemma /\\ F /\\ T => lemma'\n itp = cex_guided_pbe.syn_lemma_F_T_implies_lemma_prime(fidx = fidx, lidx = lemmaIdx, itp = lemma, \\\n frame_dump = self.dump_frames(toStr = True))\n\n if itp is None:\n print (' [push_lemma F%d] Repair lemma l%d failed: ' % (fidx, lemmaIdx))\n if len(cexIdxs) == 1:\n for cidx in cexIdxs:\n hashkey = self._canonicalize_cex( self.cexs_blocked[fidx][cidx] )\n n_fail, n_total = self.cex_to_itp_enhance_fail.get(hashkey, (0,0))\n self.cex_to_itp_enhance_fail[hashkey] = (n_fail+1, n_total+1)\n continue # syn failed: try next\n\n itp_prime_var = itp.substitute(cex_guided_pbe.prime_map)\n #md = self.solve(Not(Implies(And(self.frames[fidx] + [self.system.trans, itp]), itp_prime_var ) ) )\n #if md is not None:\n # print (md)\n\n # assert (init -> lemma)\n assert (self.solve(Not(Implies(self.system.init, itp))) is None)\n # assert (lemma /\\ F /\\ T => lemma')\n assert (self.solve(Not(Implies(And(self.frames[fidx] + [self.system.trans, itp]), itp_prime_var ) ) ) is None )\n # if not (F[fidx-1]) => itp\n # add to all previous frames\n self._add_lemma(lemma = itp, fidx = fidx+1, cidxs = blocked_c_idxs)\n\n # deal with cex_covered_by_newly_pushed_lemmas\n blocked_cex_in_prev_frame = set()\n for cIdx in blocked_c_idxs:\n prev_cex_idx = self.cex_origin.get(fidx, dict()).get(cIdx, None)\n # if it has an origin\n if isinstance(prev_cex_idx,int):\n blocked_cex_in_prev_frame.add( prev_cex_idx )\n\n self.lemma_to_cex_map_perframe[fidx][lemmaIdx] = self.lemma_to_cex_map_perframe[fidx].get(lemmaIdx, set()).union(\\\n blocked_cex_in_prev_frame) # update the current lemma as it blocks a lot more now than it was\n self.cex_covered_by_pushed_lemmas[fidx] = self.cex_covered_by_pushed_lemmas.get(fidx,set()).union(\\\n blocked_cex_in_prev_frame) # and now we have some more covered\n\n #if (self.solve(Not(Implies(And(self.frames[fidx-1]), itp))) is not None):\n print (' [push_lemma F%d] Add to all prev frame '%(fidx) )\n self.frames[fidx][lemmaIdx] = And(lemma, itp) # we don't want to touch the lemma Idx will mess things up\n self._add_lemma_to_all_prev_frame(end_frame_id = fidx-1, lemma = itp)\n # end of the for loop for repairing lemmas\n\n self.frames_pushed_idxs_map[fidx] = end_lemma_idx\n # if len(self.frames[fidx]) > end_lemma_idx : we have unpushed lemmas\n # how hard to try?\n print (' [push_lemma F%d] push lemma finished, press any key to continue'%fidx)\n pause()\n\n\n\n def is_last_two_frames_inductive(self):\n \"\"\"Checks if last two frames are equivalent (no need to change variable to prime)\"\"\"\n if len(self.frames) > 1 and \\\n self.solve(Not(Implies(And(self.frames[-1]), And(self.frames[-2]) ))) is None:\n return True\n return False\n\n # used in push_lemma, check_property, check_init_failed\n def get_bad_state_from_property_invalid_after_trans(self, prop, idx, use_init, remove_vars = [], keep_vars = None):\n \"\"\"Extracts a reachable state that intersects the negation\n of the property and the last current frame\"\"\"\n assert (idx >= 0)\n print (' [F%d -> prop]' % idx)\n md, itp = self.solveTrans(self.frames[idx], \\\n T = self.system.trans, prop = prop, \\\n init = self.system.init if use_init else None,\n variables = self.system.variables, \\\n remove_vars = remove_vars, keep_vars = keep_vars, findItp = True )\n\n if md is None and (idx + 1) < len(self.frames):\n if Config_use_itp_in_pushing:\n print (' [F%d -> prop] add ITP to F%d: ' % (idx, idx+1), itp.serialize())\n if itp not in self.frames[idx+1]:\n self._add_lemma(lemma = itp, fidx = idx + 1, cidxs = set()) # we don't know the cex, in this case should we try push?\n if self.solve( Not(Implies(And(self.frames[idx]), itp) )) is not None:\n self._add_lemma_to_all_prev_frame( end_frame_id = idx, lemma = itp )\n print (' [F%d -> prop] add ITP to F1 ->>- F%d: ' % (idx, idx), itp.serialize())\n\n if Config_analyze_use_itp_in_pushing:\n if prop == itp:\n print (' [F%d -> prop] compare ITP @ F%d: repeated ITP, no use' % (idx, idx+1))\n elif self.solve(Not(EqualsOrIff(itp, prop))) is not None:\n print (' [F%d -> prop] compare ITP @ F%d: itp =/= prop, strictly stronger' % (idx, idx+1))\n else:\n print (' [F%d -> prop] compare ITP @ F%d: itp == prop, no use' % (idx, idx+1))\n\n #pause()\n return md\n\n\n def solve(self, formula, remove_vars = [], keep_vars = None):\n \"\"\"Provides a satisfiable assignment to the state variables that are consistent with the input formula\"\"\"\n # you should know to drop variables here\n # plus tenary simulation ? ast-walker\n if not isinstance(formula, list):\n formula = [formula]\n if self.solver.solve(formula):\n retL = []\n for v, val in self.solver.get_model():\n if v in remove_vars:\n continue\n if (isinstance(keep_vars, list) or isinstance(keep_vars, set) ) and len(keep_vars) > 0 and v not in keep_vars:\n continue\n retL.append((v,val))\n #retL.append(EqualsOrIff(v, val))\n assert (len(retL) > 0) # otherwise we are removing too many variables!\n #return And(retL)\n return retL\n return None\n\n\n # you may want to have the interpolant here\n # used in recursive_block and get_bad_state_from_property_invalid_after_trans\n def solveTrans(self, prevF, T, prop , variables, init, remove_vars = [], keep_vars = None, findItp = False):\n # prevF /\\ T(p, prime) --> not prop, if sat\n print (' [solveTrans] Property:', prop.serialize())\n print (' [solveTrans] var will => prime')\n #print (' [solveTrans] prevF:', prevF)\n print (' [solveTrans] use Init:', init is not None)\n\n if init is None:\n f = prevF + [T, Not( prop.substitute(self.prime_map))]\n else:\n f = [Or(And(prevF+[T]), init.substitute(self.prime_map) ) , Not( prop.substitute(self.prime_map))]\n #print (f)\n\n if self.solver.solve(f):\n model = self.solver.get_model()\n retL = []\n for v, val in model:\n if v not in variables: # if it is prime variable\n continue # ignore it\n if v in remove_vars:\n continue\n if isinstance(keep_vars, list) and len(keep_vars) > 0 and v not in keep_vars:\n continue\n retL.append((v,val))\n assert (len(retL) > 0) # otherwise we are removing too many variables!\n #return And(retL)\n return retL, None\n Itp = None\n if findItp:\n if init is None:\n a = And(prevF + [T])\n b = Not( prop.substitute(self.prime_map))\n else:\n a = f[0]\n b = f[1]\n Itp = self.itp_solver.binary_interpolant( a = a, b = b)\n Itp = And(Itp)\n Itp = Itp.substitute(self.primal_map)\n if Config_simplify_itp:\n Itp = simplify(Itp)\n print (' [solveTrans] get itp: ', Itp.serialize())\n #pause()\n return None, Itp\n\n\n\n # ---------------------------------------------------------------------------------\n def get_inv(self):\n return And(self.frames[-1])\n\n def sanity_check_inductive_inv(self, prop ):\n T = self.system.trans\n inv = self.get_inv()\n inv_prime = inv.substitute(self.prime_map)\n assert ( self.solve(Not(Implies(self.system.init,inv))) is None)\n assert ( self.solve(Not(Implies(And(inv, T), inv_prime))) is None)\n assert ( self.solve(Not(Implies(inv, prop))) is None)\n\n def sanity_check_imply(self):\n assert (len(self.frames) > 1)\n T = self.system.trans\n for fidx in range(1,len(self.frames)):\n next_frame = And(self.frames[fidx])\n next_frame = next_frame.substitute(self.prime_map)\n model = self.solve(Not(Implies(And(self.frames[fidx-1] + [T]), next_frame)))\n if model is not None:\n print ('Bug, F%d and T -/-> F%d' % (fidx-1, fidx))\n assert (False)\n\n\n\n def sanity_check_frame_monotone(self):\n assert (len(self.frames) > 1)\n for fidx in range(1,len(self.frames)):\n model = self.solve(Not(Implies(And(self.frames[fidx-1]), And(self.frames[fidx]))))\n if model is not None:\n self.dump_frames()\n print (' model : ')\n self.dump_model(model)\n print ('Bug, not monotone, F%d -> F%d' % (fidx-1, fidx))\n\n print ('Bug lemmas in F%d' % fidx)\n for lemmaIdx, lemma in enumerate(self.frames[fidx]):\n model = self.solve(Not(Implies(And(self.frames[fidx-1]), lemma)))\n if model is not None:\n print (' l%d : ' % lemmaIdx, lemma.serialize())\n\n assert (False)\n\n def dump_model(self, model):\n print (model)\n\n @staticmethod\n def print_cube(c):\n return ( '(' + ( ' && '.join([v.symbol_name() + ' = ' + str(val) for v, val in c]) ) + ')' ) \n\n\n # ---------------------------------------------------------------------------------\n \n def recursive_block(self, cube, idx, remove_vars = [], keep_vars = None, cex_origin = None):\n priorityQueue = []\n print (' [block] Try @F%d' % idx, self.print_cube(cube) )\n\n prop = Not(And([EqualsOrIff(v,val) for v,val in cube]))\n if self.solve(self.frames[idx] + [Not( prop )] ) is None:\n print (' [block] already blocked by F%d' % idx)\n return True\n\n heapq.heappush(priorityQueue, (idx, cube))\n while len(priorityQueue) > 0:\n fidx, cex = heapq.nsmallest(1, priorityQueue)[0]\n\n if fidx == 0:\n model_init_frame = self.solve( \\\n [self.system.init] + [EqualsOrIff(v,val) for v,val in cex])\n assert (model_init_frame is not None)\n print (' [block] CEX found!')\n return False\n\n prop = Not(And([EqualsOrIff(v,val) for v,val in cex]))\n \n # Question: too old itp? useful or not?\n # push on older frames also? for new ITP?\n print (' [block] check at F%d -> F%d : ' % (fidx-1, fidx), str(prop) )\n #if Config_rm_cex_in_prev:\n # if (self.solve( \\\n # [self.system.init] + [EqualsOrIff(v,val) for v,val in cex]) is not None):\n # print (' [block] CEX is reachable -- direct init!')\n # return False\n \n model, itp = self.solveTrans(self.frames[fidx-1] + ([prop] if Config_rm_cex_in_prev else []), \\\n T = self.system.trans, prop = prop, \\\n variables = self.system.variables, \\\n init = self.system.init, \\\n remove_vars = remove_vars, keep_vars = keep_vars, findItp = True )\n\n if model is None:\n if isinstance(cex_origin, int):\n cex_origin_idx = cex_origin if idx == fidx else None\n elif isinstance(cex_origin, str):\n cex_origin_idx = cex_origin\n else:\n assert (cex_origin is None)\n cex_origin_idx = cex_origin\n\n cidx = self._add_cex(fidx = fidx, cex = cex, origin = cex_origin_idx)\n\n self._add_lemma(lemma = itp, fidx = fidx, cidxs = {cidx} )\n if self.solve( Not(Implies(And(self.frames[fidx-1]), itp) )) is not None:\n self._add_lemma_to_all_prev_frame( end_frame_id = fidx-1, lemma = itp )\n print (' [block] add ITP to F1 ->>- F%d: ' % (fidx-1), itp.serialize())\n # add cex to all previous ones and this will block it \n # or, maybe you don't need it because it is already pushed before the current frame\n # and should not interfere with the not yet pushed lemma.\n\n heapq.heappop(priorityQueue) # pop this cex\n\n else:\n # model is not None\n print (' [block] push to queue, F%d' % (fidx-1), self.print_cube(model))\n heapq.heappush(priorityQueue, (fidx-1, model))\n # TODO: \n print (' [block] Succeed, return.')\n return True\n\n # for the CTG, see if we can block it or not?\n\n\ndef test_naive_pdr():\n width = 16\n cnt = BaseAddrCnt(width)\n prop = cnt.neq_property(1 << (width-1),1,1)\n pdr = PDR(cnt)\n pdr.check_property(prop)\n pdr.sanity_check_imply()\n pdr.sanity_check_frame_monotone()\n pdr.sanity_check_inductive_inv(prop)\n pdr.dump_frames()\n print ('inv: ', simplify(pdr.get_inv()).serialize())\n\n\n\ndef test_naive_pdr_2cnt():\n width = 16\n cnt = TwoCnt(width, zero_init = True)\n #prop_good = cnt.false_property(65536-1001,1000)\n prop = cnt.neq_property(65536-1000,1000)\n pdr = PDR(cnt)\n pdr.check_property(prop)\n pdr.sanity_check_imply()\n pdr.sanity_check_frame_monotone()\n pdr.sanity_check_inductive_inv(prop)\n pdr.dump_frames()\n print ('inv: ', simplify(pdr.get_inv()).serialize())\n\n\ndef test_naive_pdr_2cnt_noload():\n width = 16\n cnt = TwoCntNoload(width, zero_init = True)\n #prop_good = cnt.false_property(65536-1001,1000)\n prop = cnt.neq_property(65536-1000,1000)\n pdr = PDR(cnt)\n pdr.check_property(prop)\n pdr.sanity_check_imply()\n pdr.sanity_check_frame_monotone()\n pdr.sanity_check_inductive_inv(prop)\n pdr.dump_frames()\n print ('inv: ', simplify(pdr.get_inv()).serialize())\n\n\nif __name__ == '__main__':\n test_naive_pdr_2cnt()\n","repo_name":"zhanghongce/pdr-prototype-tests","sub_path":"pdr-python/sygus-pdr-v2/pdr.py","file_name":"pdr.py","file_ext":"py","file_size_in_byte":45962,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11637030061","text":"\"\"\"\nTo do's:\n[x]\tRead data\n[x]\tExamine data\n[x]\tTrim Data\n[x]\tAugment Data\n[x]\tPreprocess Data\n[x]\tDefine Hyperparameters\n[x]\tDefine Model\n[x]\tTrain model\n\"\"\"\n##Load Data\n\nimport csv\nimport numpy as np\nimport os\nimport cv2\nimport matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\n#Path to driving_log\nimage_folder=\".\\\\data\"\nudacity_dataset= \".\\\\data\\\\driving_log.csv\"\n\n\ndef separate_steering(packed_data):\n\t\"Convert steering to float from string\"\n\tim_names=[]\n\tsteer_val=[]\n\tfor item in packed_data:\n\t\tim_names.append(item[0:3])\n\t\tsteer_val.append(float(item[3]))\n\treturn im_names, steer_val\n\ndef read_datafile(file_name):\n\t\"Packed data: [center_image, left_image, right_image, steer]\"\n\twith open(file_name, 'r') as csv_file:\n\t\treader =csv.reader(csv_file, skipinitialspace=True)\n\t\tpacked_data=[(x[0:4]) for x in reader][1:]\n\t\tnames, values= separate_steering(packed_data)\n\treturn names, values\n\ndef complete_path(images_array, up_dir):\n\timages=[]\n\tfor trio in images_array:\n\t\ttrios=[]\n\t\tfor image in trio:\n\t\t\ttrios.append(os.path.join(up_dir,image))\n\t\timages.append(trios)\n\treturn images\n\ndef extract_zeros(strings, values, limit= .1, keep_ratio=0.1):\n\tzeros_im=[]\n\tzeros=[]\n\t#Split zero steering\n\tim=[]\n\tval=[]\n\tfor images, wheel in zip(strings, values):\n\t\tif wheel<-limit or wheel>limit:\n\t\t\tzeros_im.append(images)\n\t\t\tzeros.append(wheel)\n\t\telse:\n\t\t\tim.append(images)\n\t\t\tval.append(wheel)\n\n\t#Select porcentage of zero_steer data to keep\n\tindex=list(range(len(zeros)))\n\tindex=np.random.choice(index,int(keep_ratio*len(zeros)), replace=False)\n\t\n\tfor i in index:\n\t\tim.append(zeros_im[i])\n\t\tval.append(zeros[i])\n\n\t#Reapend to data\n\treturn im, val\n\t\ndef use_sides(images, values, correction=.25):\n\tim=[]\n\tval=[]\n\tfor trio, wheel in zip(images, values):\n\t\tim.append(trio[0])\n\t\tval.append(wheel)\n\t\tim.append(trio[1])\n\t\tif wheel+ correction> 1:\n\t\t\tval.append(1.)\n\t\telse: \n\t\t\tval.append(wheel+correction)\n\t\tim.append(trio[2])\n\t\tif wheel-correction< -1:\n\t\t\tval.append(-1.)\n\t\telse:\n\t\t\tval.append(wheel-correction)\n\treturn im, val\n\ndef generator(samples, vals, batch_size=8):\n\tnum_samples=len(samples)\n\t#Recurrent generator\n\twhile 1:\n\t\tsamples, vals = shuffle(samples, vals)\n\t\tfor offset in range(0, num_samples, batch_size):\n\t\t\tbatch_samples= samples[offset:offset+batch_size]\n\t\t\tbatch_angles= vals[offset:offset+batch_size]\n\t\t\timages=[]\n\t\t\tangles=[]\n\t\t\tfor sample, sample_ang in zip(batch_samples, batch_angles):\n\t\t\t\timage=mpimg.imread(sample)\n\t\t\t\timages.append(image)\n\t\t\t\tangles.append(sample_ang)\n\t\t\t\t#Flip image\n\t\t\t\timages.append(np.fliplr(image))\n\t\t\t\tangles.append(-sample_ang)\n\n\t\t\timages=np.array(images)\n\t\t\tangles=np.array(angles)\n\t\t\tyield images, angles\n\nimage_folder=os.path.join(os.getcwd(),image_folder)\n\nimages, steer_vals= read_datafile(udacity_dataset)\nprint(\"Driving log readed\")\nimages=complete_path(images, image_folder)\n\nprint(\"Total data: {}\".format([len(images),len(steer_vals)]))\n#print(images[0], steer_vals[0])\nprint(\"\")\n\n##Augment Data\n\"\"\"\n[X] Append side cameras\n[X] Load own_data with sharp turns\n[x] Flip images (on generator)\n\"\"\"\n\nimages, steer_vals= use_sides(images, steer_vals)\nprint(\"Added sides: {}\".format([len(images),len(steer_vals)]))\n\n##Trim Data\nimages, steer_vals=extract_zeros(images, steer_vals)\nprint(\"Total trimmed data: {}\".format([len(images),len(steer_vals)]))\n\n\nown_dataset= \".\\\\own_data\\\\driving_log.csv\"\nown_images, own_steer_vals= read_datafile(own_dataset)\nown_images, own_steer_vals= use_sides(own_images, steer_vals)\nown_images, own_steer_vals=extract_zeros(own_images, own_steer_vals)\nprint(\"Own_data: {}\".format([len(own_images),len(own_steer_vals)]))\n\nimages=np.append(np.array(images), np.array(own_images))\nsteer_vals=np.append(np.array(steer_vals), np.array(own_steer_vals))\nprint(\"Mixed datasets: {}\".format([len(images),len(steer_vals)]))\n\nX_train, y_train = images, steer_vals\ndummy_train=False\ndel images\ndel steer_vals\nX_train, y_train = shuffle(X_train, y_train)\nif dummy_train:\n\tX_train, y_train = X_train[:1000], y_train[:1000]\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1)\nprint(\"Shuffling done\")\nprint(\"Training set: {}\".format([len(X_train),len(y_train)]))\nprint(\"Validation set: {}\".format([len(X_val),len(y_val)]))\nprint(X_train[0],y_train[0])\nprint(X_val[-1],y_val[-1])\n\n\n##Preprocess data\n\n##Define Hyperparameters\n\"\"\"\n[x]\tEpochs, Batch\n[x]\tGenerators (Training, validation)\n\"\"\"\nepochs=10\nbatch_size=512\n#Generators\ntrain_gen=generator(X_train, y_train, batch_size)\nval_gen=generator(X_val, y_val, batch_size)\n\n##Define Model\ndef resize(image):\n\timport tensorflow as tf\n\treturn tf.image.resize_images(image, (32, 160))\n\nimport tensorflow as tf\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, SpatialDropout2D, ELU\nfrom keras.layers import Convolution2D, MaxPooling2D, Cropping2D\nfrom keras.layers.core import Lambda, Reshape\nfrom keras.optimizers import Adam\n\nmodel =Sequential()\nmodel.add(Cropping2D(cropping=((70,24),(0,0)), input_shape=(160,320,3)))\nmodel.add(Lambda(resize))\n#Commaai steering model\n#https://github.com/commaai/research/blob/master/train_steering_model.py\nmodel.add(Lambda (lambda x: (x/255.) -0.5))\nmodel.add(Convolution2D(16, 8, 8, subsample=(4,4), border_mode='same'))\nmodel.add(ELU())\nmodel.add(Convolution2D(32, 5, 5, subsample=(2,2), border_mode='same'))\nmodel.add(ELU())\nmodel.add(Convolution2D(64, 5, 5, subsample=(2,2), border_mode='same'))\nmodel.add(Flatten())\n#model.add(Dropout(.2))\nmodel.add(ELU())\nmodel.add(Dense(512))\n#model.add(Dropout(.5))\nmodel.add(ELU())\nmodel.add(Dense(1))\n\nadam = Adam(lr=0.0001)\nmodel.compile(optimizer=adam, loss=\"mse\", metrics=['accuracy'])\nprint(\"Model Summary:\")\nmodel.summary()\n\n\n##Train model\nmodel.fit_generator(train_gen,\n\tsamples_per_epoch=2*len(X_train),\n\tvalidation_data=val_gen,\n\tnb_val_samples=2*len(X_val),\n\tnb_epoch=epochs)\n\nmodel_json= model.to_json()\nwith open(\"model-4b.json\", \"w\") as json_file:\n json_file.write(model_json)\n \nmodel.save(\"model.h5\")\nprint(\"Saved model to disk\")","repo_name":"KiqueGar/CarND-Behavioral-Cloning-P3","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24838361171","text":"#!/usr/bin/python3\nimport argparse\n\ndef reverse(string):\n char_array = list(string) # e.g. ['H', 'e', 'l', 'l', 'o']\n string_length = len(char_array) # e.g. 5\n new_string = []\n while string_length > 0:\n string_length -= 1\n new_string.append(char_array[string_length])\n return ''.join(new_string)\n\ndef main():\n parser = argparse.ArgumentParser(description='Reverses contents of a '\n 'given string.')\n parser.add_argument('--string', type=str, help='String to be reversed.')\n arg = parser.parse_args()\n if not arg.string:\n raise Exception('Function cannot accept null or empty string')\n rev_str = reverse(arg.string)\n print (rev_str)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"perryl/daftpython","sub_path":"reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11152617635","text":"from road_vehicle import Tanker, ElectricRoadVehicle\n\nconsist = Tanker(id='catchcan_tanker',\n base_numeric_id=810,\n name='Catchcan',\n tram_type='ELRL',\n vehicle_life=40,\n intro_date=1902)\n\nconsist.add_unit(type=ElectricRoadVehicle,\n capacity=30,\n vehicle_length=8,\n effects=['EFFECT_SPRITE_ELECTRIC, 0, 0, 10'],\n repeat=2)\n","repo_name":"andythenorth/road-hog","sub_path":"src/vehicles/catchcan_tanker.py","file_name":"catchcan_tanker.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"16045012004","text":"import engine\nimport random\nimport util\ndef create_enemy_map1(position_list):\n cpu_1 = {\n \"cpu1_icon\" : \"m\",\n \"x\" : 1,\n \"y\" : 9,\n \"cpu_health\" : 8,\n \"max_health\" : 8,\n \"attack_power\": 5,\n \"defence\": 0}\n engine.check_position(position_list,cpu_1)\n position_list.append((cpu_1[\"y\"],cpu_1[\"x\"]))\n return cpu_1\ndef enemy1_change_position(cpu_1):\n cpu_1[\"x\"]= 1\n cpu_1[\"y\"]= 9\n cpu_1[\"cpu_health\"] = 20\n cpu_1[\"attack_power\"] = 7\n return cpu_1\ndef enemy2_change_position(cpu_2):\n cpu_2[\"x\"]= 23\n cpu_2[\"y\"]= 20\n cpu_2[\"cpu_health\"] = 13\n cpu_2[\"attack_power\"] = 5\n return cpu_2\ndef enemy3_change_position(cpu_3):\n cpu_3[\"x\"]= 3\n cpu_3[\"y\"]= 21\n cpu_3[\"cpu_health\"] = 20\n cpu_3[\"attack_power\"] = 5\n return cpu_3\ndef enemy4_change_position(cpu_4):\n cpu_4[\"x\"]= 1\n cpu_4[\"y\"]= 9\n cpu_4[\"cpu_health\"] = 20\n cpu_4[\"attack_power\"] = 7\n cpu_4[\"defense\"] = 7\n return cpu_4\n\ndef put_cpu1_on_board(board, cpu_1):\n board[cpu_1[\"y\"]][cpu_1[\"x\"]] = cpu_1[\"cpu1_icon\"]\n return board\n\ndef create_enemy2_map1(position_list):\n cpu_2 = {\n \"cpu2_icon\" : \"g\",\n \"x\" : 1,\n \"y\" : 22,\n \"cpu_health\" : 5,\n \"max_health\" : 5,\n \"attack_power\":5,\n \"defence\": 0}\n engine.check_position(position_list,cpu_2)\n position_list.append((cpu_2[\"y\"],cpu_2[\"x\"]))\n return cpu_2\n\ndef put_cpu2_on_board(board, cpu_2):\n board[cpu_2[\"y\"]][cpu_2[\"x\"]] = cpu_2[\"cpu2_icon\"]\n return board\n\ndef create_enemy3_map1(position_list):\n cpu_3 = {\n \"cpu3_icon\" : \"G\",\n \"x\" : 1,\n \"y\" : 22,\n \"cpu_health\" : 8,\n \"max_health\" : 12,\n \"attack_power\": 10,\n \"defence\": 2}\n engine.check_position(position_list,cpu_3)\n position_list.append((cpu_3[\"y\"],cpu_3[\"x\"]))\n return cpu_3\n\ndef put_cpu3_on_board(board, cpu_3):\n board[cpu_3[\"y\"]][cpu_3[\"x\"]] = cpu_3[\"cpu3_icon\"]\n return board\n\ndef create_enemy4_map1(position_list):\n cpu_4 = {\n \"cpu4_icon\" : \"M\",\n \"x\" : 23,\n \"y\" : 23,\n \"cpu_health\" : 12,\n \"max_health\" : 16,\n \"attack_power\": 8,\n \"defence\": 4}\n engine.check_position(position_list,cpu_4)\n position_list.append((cpu_4[\"y\"],cpu_4[\"x\"]))\n return cpu_4\n\ndef put_cpu4_on_board(board, cpu_4):\n board[cpu_4[\"y\"]][cpu_4[\"x\"]] = cpu_4[\"cpu4_icon\"]\n return board\n\ndef mob_max_hp(cpu):\n cpu[\"cpu_health\"] = cpu[\"max_health\"]\n return cpu\n\ndef create_boss(position_list):\n \n size_boss = 5\n boss_x_place = [7,8]\n boss_y_place = [7,8]\n\n boss = {\n \"boss_icon\" : 'B',\n \"x\" : random.choice(boss_x_place),\n \"y\" : random.choice(boss_y_place),\n \"cpu_health\" : 200,\n \"attack_power\": 155,\n \"defence\": 100\n }\n \n size_boss = 5\n\n for c in range(size_boss):\n for r in range(size_boss):\n print(boss['boss_icon'], end='') \n print()\n \n \n \n engine.check_position(position_list,boss)\n position_list.append((boss[\"y\"],boss[\"x\"]))\n \n return boss\n\ndef put_boss_on_board(board, boss):\n board[boss[\"y\"]][boss[\"x\"]] = boss[\"boss_icon\"]\n return board\n\ndef boss_movement(board, boss,keys):\n \n if keys == \"w\":\n if board[boss['y'] - 1][boss['x']] != '#':\n boss['y'] -=1\n elif keys == \"a\":\n if board[boss['y'] + 1][boss['x']] != '#':\n boss['y'] +=1\n elif keys == \"s\":\n if board[boss['y']][boss['x'] - 1] != '#':\n boss['x'] -=1\n elif keys == \"d\":\n if board[boss['y']][boss['x'] + 1] != '#':\n boss['x'] +=1\n \n \n return board,boss\n\n\ndef create_vertical_boss(board, x_start, y, x_end):\n\n while x_end != x_start:\n board[x_start][y] = 'B'\n x_start += 1\n \ndef create_horizontal_boss(board, y_start, x, y_end):\n while y_end != y_start:\n board[x][y_start] = 'B'\n y_start += 1\n\ndef create_empty_boss(board, y_start, x, y_end):\n while y_end != y_start:\n board[x][y_start] = ' '\n y_start += 1","repo_name":"RafalGontarski/Roguelike","sub_path":"mobs.py","file_name":"mobs.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14349722988","text":"import sys\nclass Parent(object):\n def __init__(self):\n self.children = []\n def add(self, ch):\n self.children.append(ch)\n ch.parent = self\n\nclass Child(object):\n def __init__(self):\n self.parent = None\n\np = Parent()\np.add(Child())\nprint(p)\np.children\nprint(sys.getrefcount(p))\nprint(sys.getrefcount(p.children[0]))\n","repo_name":"MoriMorou/GB_Python","sub_path":"Python2_HomeWork/Lesson_6/Memory/Object.py","file_name":"Object.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"388942924","text":"from flask import Flask, render_template, request\nfrom discord_webhook import DiscordWebhook, DiscordEmbed\nimport socket\nimport requests\nimport os\nfrom colorama import Style, Fore, Back\n\ntry:\n os.remove(\"data_save.txt\")\nexcept:\n print(\"An Error occured\")\n# Put your webhook url here \ndiscord_webhookURL = DiscordWebhook(\" YOUR WEBHOOK HERE \")\n\n__data__ = Flask(__name__)\n\n@__data__.route('/dashboard')\ndef home():\n return render_template('home.html')\n\n@__data__.route('/dashboard/webhook')\ndef initializeWebhook():\n discord_webhook()\n return render_template('sent-webhook.html')\n\n@__data__.route('/dashboard/lookup')\ndef searchUser():\n return render_template('lookup.html')\n\n@__data__.route('/dashboard/lookup', methods=['POST'])\ndef lookup_value():\n username_value = request.form['Username']\n\n # Website list, feel free to add yours\n Instagam = ['Instagram', f\"https://www.instagram.com/{username_value}\"]\n Twitter = ['Twitter', f'https://www.twitter.com/{username_value}']\n Youtube = ['Youtube', f'https://www.youtube.com/{username_value}']\n Github = ['Github', f'https://www.github.com/{username_value}']\n Facebook = ['Facebook', f'https://www.facebook.com/{username_value}']\n Roblox = ['Roblox', f'https://www.roblox.com/search/users?keyword={username_value}']\n Paypal = ['Paypal', f'https://www.paypal.com/paypalme/{username_value}']\n Steam = ['Steam', f'https://steamcommunity.com/id/{username_value}']\n\n # List of all website (might need to add sum but lazy)\n STATUS_POSITIVE_LIST = [\n Instagam, \n Twitter, \n Youtube, \n Github,\n Facebook,\n Roblox,\n Paypal,\n Steam,\n ]\n\n __count__ = 0\n __matching__ = True\n\n # Append website that contains the username in it\n # STATUS_REMOVE_FROM_LIST = []\n\n for i in STATUS_POSITIVE_LIST:\n r = requests.get(i[1])\n if r.status_code == 200:\n if __matching__ == True:\n __matching__ == False\n # print(f\"{i[1]} - {r.status_code} - OK\")\n if username_value in r.text:\n print(\"[+] POSITIVE {}\".format(i[1]))\n with open(\"data_save.txt\", \"a\") as f:\n f.write(f'{i[1]} \\n')\n else:\n print(\"[-] NO MATCH {}\".format(i[1]))\n # If username is not in the r.text, so remove it from the list\n STATUS_POSITIVE_LIST.remove(i)\n # Get the total positiv list\n __count__ += 1\n # Get Len of LIST\n total_len = len(STATUS_POSITIVE_LIST)\n\n # print(STATUS_REMOVE_FROM_LIST)\n return render_template('lookup.html', lenPOS=total_len, LIST=STATUS_POSITIVE_LIST, UsernameText=username_value)\n\ndef discord_webhook():\n # Send result by Discord webhook\n \n DC_LIST = []\n NEW_DC_LIST_CLEAR = []\n CLEARPARA = []\n\n readFile = \"data_save.txt\"\n\n rFile = open(readFile, 'r')\n\n for __txtValue__ in rFile:\n DC_LIST.append(__txtValue__)\n\n for i in DC_LIST:\n NEW_DC_LIST_CLEAR.append(i.replace(\"\\n\" , \"\"))\n\n for i in NEW_DC_LIST_CLEAR:\n CLEARPARA.append(i.replace(\"'\", \"\"))\n\n\n embed = DiscordEmbed(description=f'> {CLEARPARA}', color='1b1b22')\n embed.set_author(name='Layton - Website List')\n embed.set_footer(text='Layton - Python By Zaqo')\n embed.set_thumbnail(url='https://i.ibb.co/sC4gmcJ/Background-15.png')\n discord_webhookURL.add_embed(embed)\n reponse = discord_webhookURL.execute() \n rFile.close()\n os.remove(\"data_save.txt\")\n print(f'[{Fore.GREEN}+{Style.RESET_ALL}] - Webhook Successfully Sent !')\n\n\n","repo_name":"malcolmQLF/layton-osint","sub_path":"layton-deployment/backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"16616112370","text":"from sqlalchemy import false, true\nfrom CarsideOrder import CarsideInfo\nfrom DeliveryOrder import DeliveryInfo\nimport UserInterface\n\nclass Account():\n \n def __init__(self):\n self.guest = True\n self.name = ''\n self.showDesription = False\n self.carsideInfo = []\n self.deliveryInfo = []\n\n\n def LogIn(self):\n print(\"Logging in user\")\n self.guest = False\n self.showDesription = False\n self.name = 'Tim'\n self.carsideInfo = [CarsideInfo(False, 'Blue', 'Honda', 'Civic'), CarsideInfo(False, 'White', 'Checy', 'Prism')]\n self.deliveryInfo = [DeliveryInfo(False)]\n\n def TabInterface(self):\n if(self.guest):\n print(\"No accounts found\")\n if(UserInterface.askYesNo('Would you like to create an account')):\n self.createAccount()\n else:\n print('Sending back to home page')\n else:\n self.editAccount()\n\n def createAccount(self): \n self.enterBasicInfo() \n self.guest = False\n if(UserInterface.askYesNo('Do you want to add order info now')):\n while(True):\n num = UserInterface.enterNumber('Which order type?', ['Carside', 'Delivery'])\n if(num == 1):\n self.enterCarsideInfo()\n elif(num == 2):\n self.enterDeliveryInfo()\n else:\n break\n print()\n\n\n def editAccount(self):\n self.showAccountInfo()\n while(True):\n num = UserInterface.enterNumber('Would you like to edit your account?', ['Delete Account', 'Edit Basic Info', 'Edit Cars', 'Edit Addresses'])\n if(num == 1):\n self.__init__()\n break\n elif(num == 2):\n self.enterBasicInfo()\n elif(num == 3):\n self.enterCarsideInfo()\n elif(num == 4):\n self.enterDeliveryInfo()\n else:\n break\n\n def showAccountInfo(self):\n print('Basic Info')\n print('\\tName: {}'.format(self.name))\n print('\\tShow Discriptions: {}'.format(self.showDesription))\n if(self.carsideInfo == []):\n print('No cars added')\n else:\n print('Cars')\n for car in self.carsideInfo:\n print('\\t{}'.format(car))\n if(self.deliveryInfo == []):\n print('No Addresses')\n else:\n print('Addresses')\n for addr in self.deliveryInfo:\n print('\\t{}'.format(addr))\n\n \n def enterBasicInfo(self):\n if(self.guest):\n print('Collecting Basic info')\n self.name = UserInterface.GetValidString('Enter Name')\n self.showDesription = UserInterface.askYesNo('Would you like the description of items to be shown')\n return #Remove if user should immeditiately be able to edit\n\n while(True):\n options = ['Edit Name ({})'.format(self.name)]\n if(self.showDesription):\n options.append('Stop showing descriptions')\n else:\n options.append('Show descriptions')\n num = UserInterface.enterNumber('Select an option', options)\n if(num == 1):\n self.name = UserInterface.GetValidString('Enter new name')\n elif(num == 2):\n self.showDesription = not self.showDesription\n else:\n return\n\n def enterCarsideInfo(self):\n if(self.carsideInfo == []):\n print('Please add a car')\n self.carsideInfo.append(CarsideInfo())\n \n while(True):\n options = ['New Car'] + list(map(str, self.carsideInfo))\n num = UserInterface.enterNumber('Add a new car or edit an existing one', options)\n if(num == 1):\n self.carsideInfo.append(CarsideInfo())\n elif(num > 1):\n num -= 2\n if(UserInterface.askYesNo('Do you want to delete this car')):\n del self.carsideInfo[num]\n print('Deleted Car')\n else:\n self.carsideInfo[num].EditCar()\n else:\n break\n\n def enterDeliveryInfo(self):\n if(self.deliveryInfo == []):\n print('Please add an address')\n self.deliveryInfo.append(DeliveryInfo())\n \n while(True):\n options = ['New Address'] + list(map(str, self.carsideInfo))\n num = UserInterface.enterNumber('Add a new address or edit an existing one', options)\n if(num == 1):\n self.carsideInfo.append(CarsideInfo())\n elif(num > 1):\n num -= 2\n if(UserInterface.askYesNo('Do you want to delete this address')):\n del self.deliveryInfo[num]\n print('Deleted address')\n else:\n self.deliveryInfo[num].Edit()\n else:\n break\n\n","repo_name":"tmagargee1/SWDV630-FinalProject","sub_path":"Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15810395501","text":"import time\n\n #Calculates Net Cash\ncompany_cash = (input(\"Enter company cash (cash and cash equivalents + marketable securities) : \"))\ncompany_cash = float(company_cash)\ndebt = (input(\"Enter long term debt : \"))\ndebt = float(debt)\nnet_cash = company_cash - debt\nshares_outstanding = (input(\"Enter shares outstanding : \"))\nshares_outstanding = float(shares_outstanding)\nprint(\"Net cash per share : \", net_cash / shares_outstanding)\ntime.sleep(5)\n\n#Calculates debt-equity\nequity = (input(\"Enter company equity : \"))\nequity = float(equity)\ntotal = debt + equity\nprint(\"Percent of Equity: \", (equity / total)*100)\ntime.sleep(5)\n\n#calculates book value per share \nbook_value = (input(\"Book Value : \"))\nbook_value = float(book_value)\nbook_value = book_value / shares_outstanding\nprint(\"Book Value per share : \", book_value)\ntime.sleep(5)\n\n#calculates free cash flow per share\nfree_cash_flow = (input(\"Enter Free Cash Flow : \"))\nfree_cash_flow = float(free_cash_flow)\nfree_cash_flow = free_cash_flow / shares_outstanding\nprint(\"Free Cash Flow per share : \", free_cash_flow)\ntime.sleep(5)\n\n#checks inventories \ninv_year1 = (input(\"Enter inventories for current year : \"))\ninv_year1 = float(inv_year1)\ninv_year2 = (input(\"Enter inventories for previous year : \"))\ninv_year2 = float(inv_year2)\ninv_year3 = (input(\"Enter inventories for year before previous year : \"))\ninv_year3 = float(inv_year3)\ntime.sleep(2)\nif inv_year1 < inv_year2 < inv_year3:\n print(\"Company Inventory Decreasing - Good \")\nelse:\n print(\"Inventory stable or increasing - Not so Good\")\ntime.sleep(5)\n\n#checks ROE\nROE = input(\"Enter increase in ROE for company (decimal) : \")\nROE = float(ROE)\nindustry = input(\"Enter increase in ROE for industry (decimal) : \")\nindustry = float(industry)\ntime.sleep(2)\nif ROE > industry:\n print(\"Very Good, it is better than industry by : \", (ROE - industry) * 100, \"%\")\nelse:\n print(\"Could be bad\")\ntime.sleep(5)\n\n#Calculates Current Ratio\ncurrent_assets = (input(\"Enter current assets : \"))\ncurrent_assets = float(current_assets)\ncurrent_liabilities = int(input(\"Enter current liabilities : \"))\ncurrent_liabilities = float(current_liabilities)\ncurrent_ratio = current_assets / current_liabilities\ntime.sleep(2)\nif current_ratio > 2:\n print(\"Company May be undervalued as current ratio is \", current_ratio)\nelse:\n print(\"Company may be undervalued or fairvalued or overvalued as current ratio is \", current_ratio)\ntime.sleep(5)\n\n#calculates pe/growth (keep pe as decimal lol)\ngrowth_rate = input(\"Enter company growth rate in decimal : \")\ngrowth_rate = float(growth_rate)\npe = input(\"Enter P/E ratio : \")\npe = float(pe)\nif growth_rate / pe >= 2:\n print(\"Great as growth rate by pe is : \", growth_rate / pe)\nelif growth_rate / pe >= 1.5:\n print(\"Okay as growth rate by pe is : \", growth_rate / pe)\nelse:\n print(\"Not so good as growth rate by pe is : \", growth_rate / pe)\ntime.sleep(5)\n\n#PB*PE calculation\nprice = input(\"Enter stock price : \")\nprice = float(price)\npb = price / book_value\nif pb * pe <= 22.5:\n print(\"PB * PE is \", pb * pe, \" - Great\")\nelse:\n print(\"Okay, it is PB*PE is \", pb * pe, \" Not the best\")\ntime.sleep(5)\n\n#calculates graham number \neps = input(\"Enter eps : \")\neps = float(eps)\nif (eps * book_value * 22.5) **0.5 > price:\n print(\"GOOD, the Graham Number is \", (eps * book_value * 22.5) **0.5)\nelse:\n print(\"This may not be a value stock according to Graham's number - \", (eps * book_value * 22.5) **0.5)\ntime.sleep(5)\n\n#calaculates net net value\ninv_year1 = inv_year1 * 0.5\ncompany_cash = float(company_cash)\naccounts = input(\"Enter accounts receivable : \")\naccounts = float(accounts)\naccounts = accounts * 0.75\ntotal_liabilities = input(\"Enter current liabilities : \")\ntotal_liabilities = float(total_liabilities)\nnet_net = company_cash + accounts + inv_year1 - total_liabilities\nnet_net = net_net / shares_outstanding\nprint(\"Net Net per share value is : \", net_net)\ntime.sleep(5)\n\n# calculates intrinsic value\nround_1 = input(\"Enter growth rate of cash flow for first 3 years : \")\nround_1 = float(round_1)\nround_1 = round_1 + 1\ndiscount = input(\"Enter discount rate : \")\ndiscount = float(discount)\ndiscount = discount + 1\nfree_cash_flow = free_cash_flow * shares_outstanding\nyear1 = (free_cash_flow * round_1) / discount\nyear2 = (year1 * round_1) / discount\nyear3 = (year2 * round_1) / discount\nfirst_3 = year3 + year1 + year2\nround_2 = input(\"Enter growth rate for next 3 years : \")\nround_2 = float(round_2)\nround_2 = round_2 + 1\nyear4 = (year3 * round_2) / discount\nyear5 = (year4 * round_2) / discount\nyear6 = (year5 * round_2) / discount\nnext_3 = year4 + year5 + year6\nround_3 = input(\"Enter growth rate for last 3 years : \")\nround_3 = float(round_3)\nround_3 = round_3 + 1\nyear7 = (year6 * round_3) / discount\nyear8 = (year7 * round_3) / discount\nyear9 = (year8 * round_3) / discount\nlast_3 = year7 + year8 + year9\nsell_of_value = year9 * 12\ncash = input(\"Enter cash and cash equivalents : \")\ncash = float(cash)\nDCF = sell_of_value + free_cash_flow + first_3 + next_3 + last_3 + cash\nIV = DCF / shares_outstanding\nif IV > price:\n print(\"The company's intrinsic value per share is \", IV)\nelse:\n print(\"The company's intrinsic value is below stock price, it is \", IV)\ntime.sleep(5)\n\n#calculates risk reward ratio\nshares = int(input(\"Enter num of shares you may buy for risk reward calculation : \"))\nreward = IV - price\nreward = reward * shares\nprint()\nmin_price = input(\"Enter minimum price of company if it falls for 1 year(must be below share price) : \")\nmin_price = float(min_price)\nmin_loss = price - min_price\nmin_loss = min_loss * shares\nratio = reward / min_loss\nprint(\"The risk-reward ratio is \", ratio, \":1\")\ntime.sleep(5)\n\n#calculates the kelly formula\nprofit = input(\"Enter percentage profit possible in 3 years (in decimal) : \")\nprofit = float(profit)\nodds1 = input(\"Enter the odds of this profit (in decimal) : \")\nodds1 = float(odds1)\nbreak_even_odds = input(\"Enter odds of breaking even in 3 years (in decimal) : \")\nbreak_even_odds = float(break_even_odds)\nodds_of_loss = input(\"Enter odds of 15% or less return in 3 years (in decimal) : \")\nodds_of_loss = float(odds_of_loss)\nodds_of_total_loss = input(\"Enter odds of total loss in investment (in decimal) : \")\nodds_of_total_loss = float(odds_of_total_loss)\nedge = (odds1 * (profit + 1)) + (break_even_odds * 0) + (odds_of_loss * -0.015 + odds_of_total_loss * -1)\nodds = odds1 * (profit + 1)\nkelly = edge / odds\nkelly = kelly * 100\ntime.sleep(5)\nprint(\"The percentage rate of success according to the kelly formula is : \", kelly, \"%\")\ntime.sleep(3)\nprint()\nprint()\nprint(\"Financials calculation finished! Yay! \")\n","repo_name":"hradayjhala/code-python","sub_path":"Advanced&Algoritms/financial anaysis/Investing_Financials.py","file_name":"Investing_Financials.py","file_ext":"py","file_size_in_byte":6643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40591625161","text":"from torch import nn, zeros, FloatTensor, cat, cuda\nimport torch\nfrom torch.autograd import Variable\nimport numpy as np\n\nimport config as cfg\nfrom model.AttNet import AttNet\nfrom model.CharNet import CharNet\nfrom model.LMnet import LMnet\nfrom model.utils import to_scalar, TimeDistributed\n\n\nclass SeqNet(nn.Module):\n def __init__(self, emb_mat, isCrossEnt=True, char_level=\"None\", pos_feat=\"No\", dep_rel_feat=\"No\", dep_word_feat=\"No\"):\n super().__init__()\n self.emb_mat_tensor = Variable(cuda.FloatTensor(emb_mat))\n assert self.emb_mat_tensor.size(1) == cfg.EMBEDDING_DIM\n self.vocab_size = self.emb_mat_tensor.size(0)\n self.emb_dim = self.emb_mat_tensor.size(1)\n self.hidden_size = cfg.LSTM_HIDDEN_SIZE\n self.batch_size = 1 # we can only do batch size 1.\n self.num_layers = 1\n self.num_dir = 2\n self.out_size = cfg.CATEGORIES\n self.pf_dim = cfg.PF_EMBEDDING_DIM\n self.char_emb_dim = cfg.EMBEDDING_DIM\n self.pos_feat = pos_feat\n self.dep_rel_feat = dep_rel_feat\n self.dep_word_feat = dep_word_feat\n self.char_level = char_level\n\n # init embedding layer, with pre-trained embedding matrix : emb_mat\n print(\"word embeddings are being trained using the following strategy: {0}\".format(cfg.TRAIN_WORD_EMB))\n\n if cfg.TRAIN_WORD_EMB == \"pre_and_post\":\n self.emb_lookup = nn.Embedding(self.vocab_size, self.emb_dim)\n self.emb_lookup.weight = nn.Parameter(cuda.FloatTensor(emb_mat))\n\n elif cfg.TRAIN_WORD_EMB == \"pre_only\":\n self.emb_lookup = Embedding(self.emb_mat_tensor)\n\n elif cfg.TRAIN_WORD_EMB == \"random\":\n self.emb_lookup = nn.Embedding(self.vocab_size, self.emb_dim)\n\n tensor = self.__random_tensor(-0.01, 0.01, (self.vocab_size, self.emb_dim))\n self.emb_lookup.weight = nn.Parameter(tensor)\n\n self.char_net = CharNet(cfg.CHAR_EMB_DIM, cfg.CHAR_RECURRENT_SIZE, out_size=cfg.EMBEDDING_DIM)\n\n if pos_feat == \"Yes\":\n self.pos_emb = nn.Embedding(cfg.POS_VOCAB, cfg.POS_EMB_DIM)\n # initialize weights\n tensor = self.__random_tensor(-0.01, 0.01, (cfg.POS_VOCAB, cfg.POS_EMB_DIM))\n self.pos_emb.weight = nn.Parameter(tensor)\n if dep_rel_feat == \"Yes\":\n self.rel_emb = nn.Embedding(cfg.REL_VOCAB, cfg.REL_EMB_DIM)\n # initialize weights\n tensor = self.__random_tensor(-0.01, 0.01, (cfg.REL_VOCAB, cfg.REL_EMB_DIM))\n self.rel_emb.weight = nn.Parameter(tensor)\n\n self.att_net = AttNet(cfg.EMBEDDING_DIM, cfg.EMBEDDING_DIM, cfg.EMBEDDING_DIM)\n\n inp_size = self.emb_dim\n\n if self.char_level == \"Input\":\n inp_size += self.char_emb_dim\n\n if self.pos_feat == \"Yes\":\n inp_size += cfg.POS_EMB_DIM\n\n if self.dep_rel_feat == \"Yes\":\n inp_size += cfg.REL_EMB_DIM\n\n if self.dep_word_feat == \"Yes\":\n inp_size += self.emb_dim\n\n self.lstm = nn.LSTM(input_size=inp_size, batch_first=True,\n num_layers=self.num_layers,\n hidden_size=self.hidden_size,\n bidirectional=True)\n\n self.lm_forward = TimeDistributed(LMnet(input_size=self.hidden_size,\n out_size=min(self.vocab_size + 1, cfg.LM_MAX_VOCAB_SIZE),\n hidden_size=cfg.LM_HIDDEN_SIZE), batch_first=True)\n\n self.lm_backward = TimeDistributed(LMnet(input_size=self.hidden_size,\n out_size=min(self.vocab_size + 1, cfg.LM_MAX_VOCAB_SIZE),\n hidden_size=cfg.LM_HIDDEN_SIZE), batch_first=True)\n\n self.lstm_linear = nn.Linear(self.hidden_size * 2, cfg.LSTM_OUT_SIZE)\n\n self.linear = nn.Linear(cfg.LSTM_OUT_SIZE,\n self.out_size)\n\n # self.time_linear = TimeDistributed(self.linear, batch_first=True)\n self.init_state()\n if not isCrossEnt:\n self.log_softmax = nn.LogSoftmax()\n\n self.isCrossEnt = isCrossEnt\n\n @staticmethod\n def __random_tensor(r1, r2, size):\n return (r1 - r2) * torch.rand(size) + r2\n\n def init_state(self):\n \"\"\"Get cell states and hidden states.\"\"\"\n h0_encoder_bi = Variable(zeros(self.num_layers * self.num_dir, self.batch_size, self.hidden_size))\n c0_encoder_bi = Variable(zeros(self.num_layers * self.num_dir, self.batch_size, self.hidden_size))\n\n self.hidden_state = (h0_encoder_bi.cuda(), c0_encoder_bi.cuda())\n\n self.char_net.init_state()\n\n def forward(self, sent_idx_seq, char_idx_seq, pos, rel, dep_word):\n cfg.ver_print(\"Sent Index sequence\", sent_idx_seq)\n\n seq_len = sent_idx_seq.size(1)\n\n emb = self.emb_lookup(sent_idx_seq)\n\n if self.char_level == \"Input\":\n char_emb = self.char_net(char_idx_seq)\n inp = cat([emb, char_emb], dim=2)\n\n elif self.char_level == \"Attention\":\n char_emb = self.char_net(char_idx_seq)\n inp = self.att_net(emb, char_emb)\n else:\n inp = emb\n\n if self.pos_feat == \"Yes\":\n pos_emb = self.pos_emb(pos)\n inp = cat([inp, pos_emb], dim=2)\n if self.dep_rel_feat == \"Yes\":\n rel_emb = self.rel_emb(rel)\n inp = cat([inp, rel_emb], dim=2)\n if self.dep_word_feat == \"Yes\":\n dep_emb = self.emb_lookup(dep_word).data.clone()\n dep_emb = Variable(dep_emb)\n inp = cat([inp, dep_emb], dim=2)\n\n # emb is now of size(1 x seq_len x EMB_DIM)\n cfg.ver_print(\"Embedding for the Sequence\", inp)\n\n lstm_out, hidden_state = self.lstm(inp, self.hidden_state)\n # lstm_out is of size (1 x seq_len x 2*EMB_DIM)\n\n lstm_forward, lstm_backward = lstm_out[:, :, :cfg.LSTM_HIDDEN_SIZE], lstm_out[:, :, -cfg.LSTM_HIDDEN_SIZE:]\n\n # making sure that you got the correct lstm_forward and lstm_backward.\n assert to_scalar(torch.sum(lstm_forward[:, seq_len - 1, :] - hidden_state[0][0, :, :])) == 0\n assert to_scalar(torch.sum(lstm_backward[:, 0, :] - hidden_state[0][1, :, :])) == 0\n\n lm_f_out = self.lm_forward(lstm_forward[:, :-1, :])\n\n lm_b_out = self.lm_backward(lstm_backward[:, 1:, :])\n\n cfg.ver_print(\"Language Model Forward pass out\", lm_f_out)\n cfg.ver_print(\"Language Model Backward pass out\", lm_b_out)\n\n lstm_out = self.lstm_linear(lstm_out.squeeze())\n\n lstm_out = torch.sigmoid(lstm_out)\n\n lstm_out = lstm_out.unsqueeze(dim=0)\n\n label_out = lstm_out\n\n linear_out = self.linear(label_out.view(seq_len, -1))\n if self.isCrossEnt:\n out = linear_out\n else:\n out = self.log_softmax(linear_out)\n\n cfg.ver_print(\"LINEAR OUT\", linear_out)\n cfg.ver_print(\"FINAL OUT\", out)\n\n if self.char_level == \"Attention\":\n return lm_f_out, lm_b_out, out, emb, char_emb\n else:\n return lm_f_out, lm_b_out, out\n\n\nclass Embedding(nn.Module):\n def __init__(self, emb_mat):\n super().__init__()\n self.emb_mat = emb_mat\n\n def forward(self, x):\n v_l = []\n cfg.ver_print(\"input to embedding layer\", x)\n # x is of size (1 x seq_len)\n seq_len = x.size(1)\n\n n = x[0].cpu().data.numpy()\n\n for i in n.tolist():\n v = self.emb_mat[i]\n # v is of size (EMB_DIM)\n # cfg.ver_print(\"v\", v)\n\n v_l.append(v)\n v = torch.stack(v_l, dim=0)\n # v is of size (seq_len x EMB_DIM)\n\n v = v.view(1, seq_len, -1)\n # v is now of size(1 x seq_len x EMB_DIM)\n\n # cfg.ver_print(\"Embedding out\", v)\n\n return v\n","repo_name":"chaitanya2334/WLP-Parser","sub_path":"model/SeqNet.py","file_name":"SeqNet.py","file_ext":"py","file_size_in_byte":7875,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"12817867517","text":"import sys, heapq\n\ndef solve():\n global n, k, arr\n\n arr.sort()\n\n subs = []\n for i in range(n-1):\n heapq.heappush(subs, arr[i+1] - arr[i])\n\n\n ans = 0\n for _ in range(n-k):\n ans += abs(heapq.heappop(subs))\n\n print(ans)\n\n\n\nn, k = map(int, sys.stdin.readline().strip().split(\" \"))\narr = list(map(int, sys.stdin.readline().strip().split(\" \")))\nsolve()\n","repo_name":"galid1/Algorithm","sub_path":"python/baekjoon/2.algorithm/greedy/13164.행복 유치원.py","file_name":"13164.행복 유치원.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11613083592","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/27 11:06\n# @Author : XiaTian\n# @File : 习题.py\n\n\n\n\"\"\"\n1、简述计算机操作系统中的“中断”的作用?\n 中断是程序在执行过程中遇到优先级非常高的程序,就会保存程序当前状态,立��终止现程序的运行,自动转入相应的处理程序,\n 待处理完成后,再返回来接着执行。\n 作用:提高了系统效率,维持系统可靠性和安全性,满足实时处理要求,提供故障现场处理手段。\n\n2、简述计算机内存中的“内核态”和“用户态”;\n 内核态:当一个程序因为系统调用陷入内核代码中执行时处于内核态,内核态程序可以访问CPU所有数据\n 用户态:当一个进程执行用户自己的代码时处于用户态,用户态程序之内访问受限制的内存,且不允许访问外部设备,cpu资源可以被别的程序获取\n 用户态的应用程序可以通过三种方式来访问内核态的资源:\n 1)系统调用\n 2)库函数\n 3)Shell脚本\n 用户态到内核态的切换:\n 1.系统调用 用户程序主动发起的 软中断 os.fork() process\n 2.异常 被动的 当CPU正在执行运行在用户态的程序时,突然发生某些预\n3、什么是进程?\n 进程是一个正在执行的过程或者程序\n\n4、什么是线程?\n 是操作系统能够进行运算调度的最小单位,是进程中的实际执行单位\n\n4.1、进程线程区别?\n 1、同一进程内的所有线程共享该进程的地址资源\n 2、创建线程的开销远远小于创建进程\n\n5、简述程序的执行过程;\n \n\n6、什么是“系统调用”?\n 运行于用户态,为应用程序员写的程序提供调用接口,本质是应用程序请求os内核完成某一功能时的一种过程调用,是通过中断实现的。\n\n7、threading模块event和condition的区别;\n Event:是线程间通信的方式,相当于信号,一个线程可以给另外一个线程发送信号后让其执行\n Condition:可以再某些事件触发或者到达特定条件后才处理数据,使得线程等待,本质上是特殊的锁\n\n8、进程间通信方式有哪些?\n 1、管道:是一块共享的内存\n 2、队列:是基于管道+锁实现的,只有一把锁,程序并发执行\n 3、信号量:可以设置多把锁,多个进程可以同时运行,可以实现并行\n 4、内存共享:效率低,需要自己加锁处理\n 5、scoket套接字通信\n 6、消息对列(用于多台机,大型通信)\n\n\n9、简述你对管道、队列的理解;\n 队列和管道都是通过一块共享的内存来实现进程之间通信的\n 管道:只能是父子或者兄弟进程之间进行通信,数据只能在一个方向上流动,数据没有加锁处理不安全,数据不可反复读取了\n\n 队列:是管道+锁实现的,可以认为是一个全局链表,可以实现不同进程间双向通信,存放的数据大小和数量都有限制,加锁处理数据更加安全\n 队列是面向记录的,其中的消息具有特定的格式以及特定的优先级,消息队列可以实现消息随机查询。\n 队列独立于发送与接收进程。进程终止时,消息队列及其内容不会被删除。\n \n10、请简述你对join、daemon方法的理解,举出它们在生产环境中的使用场景;\n join:阻塞主进程,待子进程结束后在放开阻塞\n 应用主进程执行到某一阶段后能够让主进程检测到子进程的运行是否完成,在继续执行环境\n daemon:主进程代码执行完成后守护进程就结束,守护进程内无法再开启子进程\n 用于主进程执行不用检测子进程的状态,并且主进程执行完成后,子进程不用在进行执行的场景\n\n\n11、请简述IO多路复用模型的工作原理;\n 原理:通过select/epoll这个函数不断轮询所负责的所有套接字,当某个套接字有数据,就通知用户进程去操作数据\n\n12、threading中Lock和RLock的相同点和不同点;\n Lock:一把锁,只能被获得一次\n RLock:一把锁,可以锁多次,每获得一次加1,释放一次减一\n\n13、什么是select,请简述它的工作原理,简述它的优缺点;\n select是一个套接字的代理函数,select工作时会遍历它所监测的fd_set内的所有文件描述符,调用其对应的poll方法,然后返回一个bitmask告诉select\n 当前资源哪些可用。当select循环遍历完所有fd_set内指定的文件描述符对应的poll函数后,如果没有一个资源可用(即没有一个文件可供操作),\n 则select让该进程睡眠,一直等到有资源可用为止,进程被唤醒(或者timeout)继续往下执行。\n 优缺点:\n 占用资源少,不消耗太多CPU,能同时为多个客户端服务,适用于多个连接\n 代理套接字过多性能明显下降,效率变低,跨平台能力弱\n\n\n14、什么是epoll,请简述它的工作原理,简述它的优缺点;\n 原理:1、在调用epoll_create后,内核创建一个eventpoll红黑树结构和一个list双向链表,在内核态准备���受储存的需要监控的fd\n 2、在调用epoll_ctr后,直接向内核态的eventpoll进行add/mod/del对应的fd\n 3、在epoll_ctr执行的时候,除了会向eventpoll添加修改之外,还会在内核中断函数处理程序中注册一个回调函数,告诉内核,当\n 这个fd就绪之后,将其放到list里面去\n 4、在epoll_wait调用的时候,会遍历list中的数据,然后直接处理\n 优点:不需要遍历整个对列,只需要遍历epoll_wait就绪对列;效率高,节省cpu开销\n\n15、简述select和epoll的区别;\n select需要轮询整个代理的消息对列,当代理的数量过大时,轮询消耗时间就变长\n epoll不需要轮询所代理的消息对列,当代理的对列里面有数据准备好后,就会将其状态发送到就绪列表中,epoll只需要轮询就绪列表\n\n16、简述多线程和多进程的使用场景;\n 多线程用于I/O密集型\n 多进程用于计算密集型\n\n17、请分别简述threading.Condition、threading.event、threading.semaphore、的使用场景;\n Condition用于当线程运行到某一阶段时需要满足条件时才能继续执行场景\n Event用于当一个线程运行到某一阶段时需要获取到另外的线程的状态才能继续运行场景\n Semaphore用于需要多个线程同时运行\n\n\n18、假设有一个名为threading_test.py的程序里有一个li = [1, 2, 3, 4]的列表,另有a,b两个函数分别往该列表中增加元素,\na函数需要修改li之前需要获得threading.Lock对象,b函数不需要,请问当线程t1执行a函数获取到Lock对象之后并没有release该对象的情况下,\n线程t2执行b函是否可以修改li,为什么?\n 可以修改,a,b两个线程在同一个进程里面运行的,同一进程里面的多个线程共享进程的内存空间\n\n\n19、简述你对Python GIL的理解;\n GIL本质上是一把锁,它和其他锁不同的地方在于GIL是解释器级别的锁,所有线程在执行时都必须先拿到GIL锁才能执行,将程序变成串行执行\n\n20、请列举你知道的线程间通信方式;\n event\n 信号量\n 互斥锁\n Condition\n\n21、什么是同步I/O,什么是异步I/O?\n 同步I/O:在做I/O操作时会将进程阻塞\n 异步I/O:在做I/O操作时不会将进程阻塞\n\n22、什么是管道,如果两个进程尝试从管道的同一端读写数据,会出现什么情况?\n 管道:是特殊类型的文件,是进行进程间通信的特殊类型的文件,需要通信的两个进程在管道的两端,进程利用管道传递信息\n 后读写的进程会将前面一个进程写入文件中的内容覆盖掉\n \n\n23、为什么要使用线程池/进程池?\n 因为使用的计算机内存的限制,同时开启的进程和线程不能无限大,开启的进程和线程过多会降低系统运行效率\n\n\n24、如果多个线程都在等待同一个锁被释放,请问当该锁对象被释放的时候,哪一个线程将会获得该锁对象?\n 排在前一个线程后面的线程先拿到锁\n\n\n25、import threading;s = threading.Semaphore(value=-1)会出现什么情况?\n 报错\n\n26、请将二进制数10001001转化为十进制;\n int('10001001',2)=137\n\n27、某进程在运行过程中需要等待从磁盘上读入数据,此时该进程的状态将发生什么变化?\n 该进程将由运行态转变成阻塞态\n\n28、请问selectors模块中DefaultSelector类的作用是什么;\n 自动选择当前环境中最有效的selector\n\n29、简述异步I/O的原理;\n 异步I/O\n \n\n30、请问multiprocessing模块中的Value、Array类的作用是什么?举例说明它们的使用场景\n Value、Array是用来进行进程间内存共享的\n Value是创建一个变量大小的共享内存,而Array则是创建一个数组大小的共享内存\n \n\n31、请问multiprocessing模块中的Manager类的作用是什么?与Value和Array类相比,Manager的优缺点是什么?\n Manager类实现共享内存的,类似于服务器与客户之间的通信,Manager能共享字典和列表\n Manager 网络的方式,共享的数据类型多\n Value和Array共享内存\n 可以通过使用Value或者Array把数据存储在一个共享的内存表中;\n Manager()返回一个manager类型,控制一个server process,可以允许其它进程通过代理复制一些python objects \n Manager类的作用共享资源,manger的的优点是可以在pool进程池中使用,缺点是windows环境下性能比较差\n\n32、请说说你对multiprocessing模块中的Queue().put(), Queue.put_nowait(), Queue.get(), Queue.get_nowait()的理解;\n Queue.put_nowait()如果队列满了会立即抛出异常\n Queue.get_nowait()如果队列空了会立即抛出异常\n Queue().put()和Queue.get()不会抛出异常,当队列满了或者空了会一直卡住直到队列有空或者队列有数据\n \n\n33、什么是协程?使用协程与使用线程的区别是什么?\n 协程是单线程下的并发,是一种用户态轻量级线程,由用户自己控制调度的。\n 协程是用户自己控制调度的,线程是由操作系统内核控制调度的\n 特点:\n 协程切换开销小,属于程序级别的切换,单线程内就可以实现并发。最大限度的利用CPU\n 但是无法利用多核,如果协程阻塞整个线程就会阻塞\n\n34、asyncio的实现原理是什么?\n\n\"\"\"\"\"\n\n\"\"\"\n1、请写一个包含10个线程的程序,主线程必须等待每一个子线程执行完成之后才结束执行,每一个子线程执行的时候都需要打印当前线程名、\n当前活跃线程数量以及当前线程名称;\n\n2、请写一个包含10个线程的程序,并给每一个子线程都创建名为\"name\"的线程私有变量,变量值为“Alex”;\n\n3、请使用协程写一个消费者生产者模型;\n\n4、写一个程序,包含十个线程,子线程必须等待主线程sleep 10秒钟之后才执行,并打印当前时间;\n\n5、写一个程序,包含十个线程,同时只能有五个子线程并行执行;\n\n6、写一个程序 ,包含一个名为hello的函数,函数的功能是打印字符串“Hello, World!”,该函数必须在程序执行30秒之后才开始执行(不能使用time.sleep());\n\n7、写一个程序,利用queue实现进程间通信;\n\n8、写一个程序,利用pipe实现进程间通信;\n\n9、使用selectors模块创建一个处理客户端消息的服务器程序;\n\n10、使用socketserver创建服务器程序时,如果使用fork或者线程服务器,一个潜在的问题是,恶意的程序可能会发送大量的请求导致服务器崩溃,\n请写一个程序,避免此类问题;\n\n11、请使用asyncio实现一个socket服务器端程序;\n\"\"\"\n\n\"\"\"\nMySQL\n1、数据库介绍、类型、特性\n2、MySQL数据库安装、连接、启动、停止\n3、表字段类型介绍、主键约束、表创建语句\n4、常用增删改查语句、分组、聚合\n5、外键管理、unique字段、表结构修改语法\n6、跨表查询,inner join、left join、right join、full join语法\n7、复杂SQL语句如group by、子查询、函数的使用\n8、索引原理及作用、普通索引、多列索引、唯一索引、全文索引等\n9、基于hash&b+树索引的实现原理,索引的优缺点剖析\n10、事务原理,ACID特性,应用场景讲解\n11、事务回滚\n12、触发器的特性,应用场景\n13、触发器的增删改查方法\n14、存储过程的作用及应用场景\n15、创建存储过程,参数传递,流程控制语句if\\while\\repeat\\loop等,动态SQL的创建\n16、视图的作用及使用场景,视图的增删改查\n17、数据库权限管理,用户管理\n18、数据库备份命令及工具讲解\n19、基于不同业务的数据库表结构设计、性能优化案例\n20、pymysql模块介绍和使用\n\n\"\"\"\n\n\"\"\"\n1、说说你所知道的MySQL数据库存储引擎,InnoDB存储引擎和MyISM存储引擎的区别?\n 主要有\n MyISM:MyISAM存储引擎:不支持事务、也不支持外键,优势是访问速度快,对事务完整性没有要求或者以select,insert为主的应用\n 基本上可以用这个引擎来创建表\n InnoDB:支持事务\n Memory:Memory存储引擎使用存在于内存中的内容来创建表。每个memory表只实际对应一个磁盘文件,格式是.frm。memory类型的表访问非常的快,\n 因为它的数据是放在内存中的,并且默认使用HASH索引,但是一旦服务关闭,表中的数据就会丢失掉。\n Merge:Merge存储引擎是一组MyISAM表的组合,这些MyISAM表必须结构完全相同,merge表本身并没有数据,对merge类型的表可以进行查询,更新,\n 删除操作,这些操作实际上是对内部的MyISAM表进行的。\n\n MyISM和InnoDB的区别\n InnoDB支持事务,而MyISM不支持事务\n InnoDB支持行级锁,而MyISM支持表级锁\n InnoDB支持外键,而MyISM不支持\n InnoDB支持全文索引,而MyISM不支持\n InnoDB是索引组织表,MyISM是堆表 (堆表的数据是随机插入的,索引组织表的数据是有序的)\n\n2、MySQL中char和varchar的区别,varchar(50)和char(50)分别代表什么意思?\n char:定长 char(50)代表存储字符的长度是50\n varchar:变长 varchar(50)代表最多存储50个字符\n\n3、MySQL中int类型存储多少个字节?\n int存储4字节,最小值-2147483648,最大值21477483647\n \n4、主键具有什么特征?\n 唯一且非空\n \n5、简述你对inner join、left join、right join、full join的理解;\n inner join:只连接匹配行\n left join:左连接,优先显示左表的全部记录 \n right join:右连接,优先显示右表的全部记录\n full join:全外连接,显示两个表的全部记录\n \n \n6、concat, group_concat函数的作用是什么?\n concat:作用是自定义查询后显示的格式,即将多个字符串拼接成一个字符串\n group_concat:作用是将分组后的每组数据内容显示出来\n\n\n7、请介绍事务的实现原理;\n ACID:原子性,一致性,隔离性,持久性\n \n8、索引的本质是什么?索引有什么优点,缺点是什么?\n 索引是帮助MySQL高效获取数据的数据结构。因此,索引的本质是一种数据结构。\n 在数据之外,数据库系统还可以维护满足特定查找算法的数据结构,这些数据结构以某种方式指向真实数据,这样就可以在这些数据结构上\n 实现高级查找算法,这种数据结构就是索引。\n\n 优点:\n 1、提高数据检索效率,降低数据库的IO成本;\n 2、通过索引对数据进行排序,降低了数据排序的成本,降低了CPU的利用率;\n\n 缺点:\n 1、索引实际上也是一张表,索引会占用一定的存储空间;\n 2、更新数据表的数据时,需要同时维护索引表,因此,会降低insert、update 、delete的速度;\n \n9、哪些情况下需要创建索引,哪些情况下不需要创建索引?\n 1、主键自动创建唯一非空索引;\n 2、频繁作为查询条件的字段应该创建索引;\n 3、频繁更新的字段不适合简历索引,因为每次更新不仅仅更新数据表同时还会更新索引表;\n 4、查询中经常排序的字段,可以考虑创建索引;\n 5、如果某个字段的重复数据较多,不适合创建普通索引;\n \n10、请分别介绍ACID代表的意思,什么业务场景需要支持事务,什么业务场景不需要支持事务?\n ACID分别代表事务的四种特性,分别是:\n 原子性:即整体性和不可分割性,被认为是一个不可分割的单元,原子性执行是一个全部发生或者全部失败的过程。\n 一致性:无论事务是成功还是失败,但是系统处于一致的状态,一致性保证数据库从不返回一个未处理事务\n 隔离性:即每个事务在自己的隔离空间发生,与其他发生在系统中的事务隔离,而且事务的结果只有在完全被执行时才能看到\n 当系统在多个用户同时连接时,系统必须遵守隔离性原则,保证事务与事务之间不会相互冲突。\n 持久性:事务处理结束后,对数据的修改就是永久的,即便系统故障也不会丢失\n \n 用于数据处理操作量大,复杂度高的场景\n\n11、什么是触发器,请简述触发器的使用场景?\n 触发器是一种特殊的存储过程,主要是通过对表的增、删、改操作触发而被执行,不是主动调用执行的\n 用于监视表内的变化\n\n12、什么是存储过程,存储过程的作用是什么?\n 存储过程就是一种在数据库中存储复杂程序,以便外部程序调用的一种数据库对象。是为了完成特定功能的sql语句集合\n 作用:封装重用sql语言代码,并给外部调用提供接口\n 优点:存储过程可封装,并隐藏复杂的商业逻辑;存储过程可以回传值,并可以接受参数。\n 存储过程无法使用 SELECT 指令来运行,因为它是子程序,与查看表,数据表或用户定义函数不同\n \n\n13、什么是视图,简单介绍视图的作用和使用场景?\n 视图是虚拟表,本质是根据sql语句获取动态数据集\n 视图对sql语句进行了封装,提高了sql语句的安全性,减少重复sql语句的使用,提高开发效率。\n \n \n14、如何查看SQL语句的执行计划?\n 用explain+sql语句可以查看\n\n\n15、在你本地数据库中查看select * from student的执行计划,并解释每个字段分别代表什么意思?\n+----+-------------+----------+------+---------------+------+---------+------+------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+----------+------+---------------+------+---------+------+------+-------+\n| 1 | SIMPLE | EMPLOYEE | ALL | NULL | NULL | NULL | NULL | 18 | NULL |\n+----+-------------+----------+------+---------------+------+---------+------+------+-------+\nid : 查询标识符,数字越大越优先执行,如果说数字一样大,那么就从上往下依次执行,id列为null的就表是这是一个结果集,不需要使用它来进行查询。\n \nselect_type : 查询类型 \n A:simple:表示不需要union操作或者不包含子查询的简单select查询。有连接查询时,外层的查询为simple,且只有一个\n B:primary:一个需要union操作或者含有子查询的select,位于最外层的单位查询的select_type即为primary。且只有一个\n C:union:union连接的两个select查询,第一个查询是dervied派生表,除了第一个表外,第二个以后的表select_type都是union\n D:dependent union:与union一样,出现在union 或union all语句中,但是这个查询要受到外部查询的影响\n E:union result:包含union的结果集,在union和union all语句中,因为它不需要参与查询,所以id字段为null\n F:subquery:除了from字句中包含的子查询外,其他地方出现的子查询都可能是subquery\n G:dependent subquery:与dependent union类似,表示这个subquery的查询要受到外部表查询的影响\n H:derived:from字句中出现的子查询,也叫做派生表,其他数据库中可能叫做内联视图或嵌套select\n \ntable : 查询的表名,如果查询使用了别名,那么这里显示的是别名,如果不涉及对数据表的操作,那么这显示为null,\n 如果显示为尖括号括起来的就表示这个是临时表,后边的N就是执行计划中的id,表示结果来自于这个查询产生。\n 如果是尖括号括起来的,与类似,也是一个临时表,表示这个结果来自于union查询的id为M,N的结果集。\n \n\ntype : 连接类型,依次从好到差:system,const,eq_ref,ref,fulltext,ref_or_null,unique_subquery,index_subquery,range,\nindex_merge,index,ALL,除了all之外,其他的type都可以使用到索引,除了index_merge之外,其他的type只可以用到一个索引。\n A:system:表中只有一行数据或者是空表,且只能用于myisam和memory表。如果是Innodb引擎表,type列在这个情况通常都是all或者index\n B:const:使用唯一索引或者主键,返回记录一定是1行记录的等值where条件时,通常type是const。其他数据库也叫做唯一索引扫描\n C:eq_ref:出现在要连接过个表的查询计划中,驱动表只返回一行数据,且这行数据是第二个表的主键或者唯一索引,且必须为not null,\n 唯一索引和主键是多列时,只有所有的列都用作比较时才会出现eq_ref\n D:ref:不像eq_ref那样要求连接顺序,也没有主键和唯一索引的要求,只要使用相等条件检索时就可能出现,常见与辅助索引的等值查找。\n 或者多列主键、唯一索引中,使用第一个列之外的列作为等值查找也会出现,总之,返回数据不唯一的等值查找就可能出现。\n E:fulltext:全文索引检索,要注意,全文索引的优先级很高,若全文索引和普通索引同时存在时,mysql不管代价,优先选择使用全文索引\n F:ref_or_null:与ref方法类似,只是增加了null值的比较。实际用的不多。\n G:unique_subquery:用于where中的in形式子查询,子查询返回不重复值唯一值\n H:index_subquery:用于in形式子查询使用到了辅助索引或者in常数列表,子查询可能返回重复值,可以使用索引将子查询去重。\n I:range:索引范围扫描,常见于使用>,<,is null,between ,in ,like等运算符的查询中。\n J:index_merge:表示查询使用了两个以上的索引,最后取交集或者并集,常见and ,or的条件使用了不同的索引,\n 官方排序这个在ref_or_null之后,但是实际上由于要读取所个索引,性能可能大部分时间都不如range\n K:index:索引全表扫描,把索引从头到尾扫一遍,常见于使用索引列就可以处理不需要读取数据文件的查询、可以使用索引排序或者分组的查询。\n L:all:这个就是全表扫描数据文件,然后再在server层进行过滤返回符合要求的记录。\n \npossible_keys : 可能用到的索引 \n \nkey : 实际用的索引,select_type为index_merge时,这里可能出现两个以上的索引,其他的select_type这里只会出现一个\n \nkey_len : 用于处理查询的索引长度,如果是单列索引,那就整个索引长度算进去,如果是多列索引,那么查询不一定都能使用到所有的列,\n具体使用到了多少个列的索引,这里就会计算进去,没有使用到的列,这里不会计算进去。留意下这个列的值,算一下你的多列索引总长度就\n知道有没有使用到所有的列了。要注意,mysql的ICP特性使用到的索引不会计入其中。另外,key_len只计算where条件用到的索引长度,\n而排序和分组就算用到了索引,也不会计算到key_len中。\n\nref : 如果是使用的常数等值查询,这里会显示const,如果是连接查询,被驱动表的执行计划这里会显示驱动表的关联字段,如果是条件使用了\n 表达式或者函数,或者条件列发生了内部隐式转换,这里可能显示为func\nrows : 这里是执行计划中估算的扫描行数,不是精确值\n\nfiltered : 根据查询条件过滤了百分多少的数据,使用explain extended时会出现这个列,5.7之后的版本默认就有这个字段,\n不需要使用explain extended了。这个字段表示存储引擎返回的数据在server层过��后,剩下多少满足查询的记录数量的比例,注意是百分比,\n不是具体记录数。\n\nExtra : 附加信息\n A:distinct:在select部分使用了distinc关键字\n B:no tables used:不带from字句的查询或者From dual查询\n C:使用not in()形式子查询或not exists运算符的连接查询,这种叫做反连接。即,一般连接查询是先查询内表,再查询外表,\n 反连接就是先查询外表,再查询内表。\n D:using filesort:排序时无法使用到索引时,就会出现这个。常见于order by和group by语句中\n E:using index:查询时不需要回表查询,直接通过索引就可以获取查询的数据。\n F:using join buffer(block nested loop),using join buffer(batched key accss):\n 5.6.x之后的版本优化关联查询的BNL,BKA特性。主要是减少内表的循环数量以及比较顺序地扫描查询。\n G:using sort_union,using_union,using intersect,using sort_intersection:\n using intersect:表示使用and的各个索引的条件时,该信息表示是从处理结果获取交集\n using union:表示使用or连接各个使用索引的条件时,该信息表示从处理结果获取并集\n using sort_union和using sort_intersection:与前面两个对应的类似,只是他们是出现在用and和or查询信息量大时,先查询主键,\n 然后进行排序合并后,才能读取记录并返回。\n H:using temporary:表示使用了临时表存储中间结果。临时表可以是内存临时表和磁盘临时表,执行计划中看不出来,需要查看status变量,\n used_tmp_table,used_tmp_disk_table才能看出来。\n I:using where:表示存储引擎返回的记录并不是所有的都满足查询条件,需要在server层进行过滤。查询条件中分为限制条件和检查条件,\n 5.6之前,存储引擎只能根据限制条件扫描数据并返回,然后server层根据检查条件进行过滤再返回真正符合查询的数据。\n 5.6.x之后支持ICP特性,可以把检查条件也下推到存储引擎层,不符合检查条件和限制条件的数据,直接不读取,这样就大大减少了存储引擎\n 扫描的记录数量。extra列显示using index condition\n J:firstmatch(tb_name):5.6.x开始引入的优化子查询的新特性之一,常见于where字句含有in()类型的子查询。如果内表的数据量比较大,\n 就可能出现这个\n K:loosescan(m..n):5.6.x之后引入的优化子查询的新特性之一,在in()类型的子查询中,子查询返回的可能有重复记录时,就可能出现这个\n\n16、数据备份分为哪几种类型?增量备份和差异备份的区别是什么?\n 完全备份:完全备份指的是备份整个数据集( 即整个数据库 )\n 部分备份:部分备份指的是备份部分数据集(例如: 只备份一个表),部分备份又分为增量备份和差异备份\n 增量备份:增量备份指的是备份自上一次备份以来(增量或完全)以来变化的数据; 特点: 节约空间、还原麻烦\n 差异备份:差异备份指的是备份自上一次完全备份以来变化的数据 特点: 浪费空间、还原比增量备份简单\n \n\n17、请介绍select语句的执行顺序;\n 首先执行from找到需要查询的表,第二需要连表的要执行on,根据后面的过滤条件来查找对应的数据,带上已执行添加外部行,即执行join确定连表的\n 类型;第四执行where后面的过滤条件,第五执行group by语句来对符合where过滤条件的数据进行分组,第六执行having过滤条件,第六执行select\n 关键字,找到需要查询的结果,第七执行distinct来对查询的结果进行去重,第八执行order by来对查找的结果进行排序,第九执行limit来确定查询\n 结果打印的条数。\n \n\n18、请问存储引擎MyISM和InnoDB的适合什么样的使用场景?\n MyISM:不支持事务和主键,索引,访问速度快,是堆表\n InnoDB:支持索引和事务,是索引组织表\n\n19、请举出MySQL中常用的几种数据类型;\n 整型:选择了整型后,其后面的长度不是表示整型数据的长度,而是其显示的长度,mysql中整型长度是固定的11位,其他数据类型后面的长度是表示最大长度\n 浮点型:float double decimal (float和double表示的小数点后最大位数都是30位,double的精度比float高,decimal由于是按照字符串存储的,\n 表示的是小数的精确值,其整数部分和小数部分加起来最多能表示65位,小数部分最大能表示30位)\n 字符类型:char varchar\n 日期类型:分为year(年),time(时分秒),date(年月日),datetime(包含所有)\n 枚举类型和集合类型\n\n20、什么情况下会产生笛卡尔乘积,如何避免?\n SELECT * FROM 表名,表名会出现笛卡尔积(交叉相���)\n\n21、请列举MySQL中常用的函数;\n 数学函数:\n ROUND(x,y):返回参数x的四舍五入的有y位小数的值\n ABS(x):求x的绝对值\n FLOOR(x):返回不大于x的整数值\n RAND():返回0到1内的随机值\n PI():返回圆周率值\n TRUNCATE(x,y):返回x,并保留y为小数\n SQRT(x):返回非负数x的二次方根\n AVG(col):返回指定列的平均值\n COUNT(col):返回指定列的不为空的个数\n MIN(col):返回指定列的最小值\n MAX(col):返回指定列的最大值\n SUM(col):返回指定列的所有值和\n GROUP_CONCAT(col):返回由属于一组的列值连接组合而成的结果 \n 字符串函数:\n CHAR_LENGTH(str):返回值为字符串str 的长度,长度的单位为字符。一个多字节字符算作一个单字符\n CONCAT(str1,str2,...):字符串拼接\n CONCAT_WS(separator,str1,str2,...):字符串拼接(自定义连接符)\n CONV(N,from_base,to_base):进制转换,如SELECT CONV('a',16,2); 表示将 a 由16进制转换为2进制字符串表示\n FORMAT(x,D)将数字x的格式写为'#,###,###.###',以四舍五入的方式保留小数点后D位,并将结果以字符串形式返回\n INSERT(str,pos,len,newstr):在str的指定位置插入字符串 pos:要替换的位置,len:替换长度,newstr:新字符串\n UPPER:变大写\n UCASE:\n LEFT(str,len):返回字符串str从开始的len位置的子序列字符\n RTRIM\n SUBSTRING(str,pos),SUBSTRING(str FROM pos),SUBSTRING(str,pos,len),SUBSTRING(str FROM pos FOR len) \n 不带有len参数的格式从字符串str返回一个字符串,起始于位置pos。带有len的参数格式字符串str返回一个长度同len相同\n 的字符串,起始于位置pos。使用FROM的格式为SQL的标准语法。也可能对pos使用一个负值,负值代表子字符串的位置起始于子字符串\n 结尾的pos字符,而不是字符串的开头位置\n REVERSE\n FIELD\n LOCATE\n POSITION\n INSTR\n 日期函数:\n CURDATE, CURRENT_DATE:返回当前的日期 \n CURTIME,CURRENT_TIME:返回当前的时间\n NOW():返回当前的时间和日期\n DATEDIFF\n ADDDATE\n SUBDATE\n QUARTER(date):返回当前日期的季度\n FROM_UNIXTIME(ts,fmt):根据指定的fmt格式,格式化ts的时间戳\n DAYOFYEAR(date):一年的第几天\n 控制流函数:\n CASE WHEN[条件] THEN[结果]....ELSE[结果或者默认值] END\n 如果条件为真返回then后面结果,否则返回else后面结果\n CASE [条件一] WHEN [条件二] THEN [结果] ..... ELSE[结果] END\n 如果条件一和条件二相等则返回then,否则返回else\n IF(test,t,f) \n 如果test为真,则返回他t,否则返回f\n IFNULL(arg1,arg2)\n 如果arg1不为空,返回arg1,否则返回arg2\n NULLIF(arg1,arg2) \n 如果arg1=arg2返回NULL;否则返回arg1\n 加密函数:\n MD5() \n 计算字符串str的MD5校验和\n PASSWORD(str) \n 返回字符串str的加密版本,这个加密过程是不可逆转的,和UNIX密码加密过程使用不同的算法。\n\n22、请说明group by的使用场景;\n 用于需要对表进行分组操作的场景\n\n23、请介绍hash索引和B+树索引的实现原理;\n 索引原理:本质都是通过不断缩小想要查找数据的范围来筛选出来最终想要的结果,同时把随机的事件变成顺序事件,也就是说有了索引我们总是可以\n 用同一种方式来锁定数据。索引本质是数据结构\n \n 哈希索引基于哈希表实现,只有精确匹配索引的所有列的查询才有效。对于每一行数据,存储引擎都会对所有的索引列计算一个哈希码,\n 哈希码是一个较小的值,并且不同键值的行计算出来的哈希码也不一样。哈希索引将所有的哈希码存储在索引中,同时在哈希表中保存指向每个\n 数据行的指针。也就是说,由于哈希查找比起B-Tree索引,其本身对于单行查询的时间复杂度更低,有了哈希索引后明显可加快单行查询速度。\n\n 但是哈希索引也有它自己的限制:\n 哈希索引只包含哈希值和行指针,而不存储字段值,所以不能使用索引中的值来避免读取行。不过,访问内存中的行的速度很快,所以大部分情况\n 下这一点对性能的影响并不明显。哈希索引数据并不是按照索引值顺序存储的,所以也就无法用于排序。\n 哈希索引也不支持部分索引列匹配查找,因为哈希索引始终是使用索引列的全部内容来计算哈希值的。例如,在数据列(A, B)上建立哈希索引,\n 如果查询只有数据列A,则无法使用该索引。哈希索引只支持等值比较查询,包括=、in()、<=>。不支持任何范围查询,例如where price > 100。\n 访问哈希索引的数据非常快,除非有很多哈希冲突。如果哈希冲突很多的话,一些索引维护操作的代价也很高。\n\n B+树索引是B树索引的变体,本质上也是多路平衡查找树\n B+树特点:数据项从左到右依次增大,非子叶节点的子树指针与关键字个数相同;内部节点并不存储真正的信息,而是保存其叶子节点的最小值作为索引\n\"\"\"\n\n\"\"\"\n1、创建一个表student,包含ID(学生学号),sname(学生姓名),gender(性别),credit(信用卡号),四个字段,要求:ID是主键,且值自动递增,\nsname是可变长字符类型,gender是枚举类型, credit是可变长字符类型;\n\n2、在上面的student表中增加一个名为class_id的外键,外键引用class表的cid字段;\n 先建class表格,在向student表中增加class_id字段,然后在添加外键\n 语法:\n alter table student add constraint foreign key(class_id) references class(cid);\n \n3、向该表新增一条数据,ID为1,学生姓名为alex,性别女,修改ID为1的学生姓名为wupeiqi,删除该数据;\n \n \n4、查询student表中,每个班级的学生数;\n\n5、修改credit字段为unique属性;\n\n6、请使用命令在你本地数据库中增加一个用户,并给该用户授予创建表的权限;\n\n7、请使用pymsql模块连接你本地数据库,并向student表中插入一条数据;\n\n8、请使用mysqldump命令备份student表;\n\n9、创建一张名为student_insert_log的表,要求每次插入一条新数据到student表时,都向student_insert_log表中插入一条记录,记录student_id, insert_time;\n\n10、创建一张名为student_update_log的表,要求每次更新student表中的记录时,都向student_update_log表中插入一条记录,记录student_id, update_time;\n\"\"\"\n\n\nimport pymysql\n\n\nconn = pymysql.connect(\n host = 'localhost',\n port = 3306,\n user = 'root',\n password = '123456',\n db = 'db1',\n charset = 'utf8'\n)\n\ncourser = conn.cursor()\nname = input('姓名:').strip()\ngender = input('性别:').strip()\ncredit = input('credit:').strip()\nclass_id = input('班级:').strip()\nsql = 'INSERT db1.student(sname,gender,credit,class_id) VALUES(%s,%s,%s,%s)'\ncourser.execute(sql,(name,gender,credit,class_id))\n\ncourser.execute('SELECT * FROM student',)\nprint(courser.fetchall())\nconn.commit()\ncourser.close()\nconn.close()\n","repo_name":"summer5625/Mygit","sub_path":"第四模块_网络编程进阶_数据库开发/复习/习题.py","file_name":"习题.py","file_ext":"py","file_size_in_byte":38123,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"198020263","text":"from django.urls import path, include\nfrom rest_framework import routers\n\nfrom spray.api.v1.schedule import views\n\n# ----------------------------------------------------------------------- #\n# ----------------------------------------------------------------------- #\n\nrouter = routers.DefaultRouter()\nrouter.register('available-times', views.AvailableTimesViewSet, basename='available-time')\nrouter.register('available-valet', views.AvailableValetView, basename='available-valet')\nrouter.register('valet-schedule', views.ValetScheduleViewSet, basename='valet-schedule')\nrouter.register('additional-time', views.ValetScheduleAdditionalTimeView, basename='additional-time')\n\nurlpatterns = [\n path('', include(router.urls)),\n]\n","repo_name":"Akhtyrtsev/spray_refactored","sub_path":"spray/api/v1/schedule/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7932251854","text":"import torch\nimport numpy as np \nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .bairu_decoder import BairuDecoder\nfrom .bairu_config import BairuConfig\nfrom torch.nn import LSTMCell, LSTM\nfrom transformers import BertModel\n\nclass LSTMCrossAttention(nn.Module):\n def __init__(self, config:BairuConfig):\n super().__init__()\n self.decoder_transform = nn.Linear(config.decoder_hidden_size, config.hidden_size)\n \n if config.hidden_size != config.decoder_hidden_size:\n self.encoder_transform = nn.Linear(config.hidden_size, config.decoder_hidden_size,)\n else:\n self.encoder_transform = None\n\n def forward(self, decoder_hidden_state, encoder_out, encoder_padding_mask = None):\n '''\n decoder_hidden_state: [batch_size, decoder_hidden_dim] ONLY one time step!\n encoder_out: [enc_seq_len, batch_size , encoder_output_dim] batch_first = False!\n encoder_padding_mask: [enc_seq_len, batch_size, encoder_output_dim] batch_first = False!\n '''\n x = self.decoder_transform(decoder_hidden_state)\n weight = (x.unsqueeze(0) * encoder_out).sum(dim = 2)\n if encoder_padding_mask != None:\n weight = weight.float().masked_fill_(encoder_padding_mask, -10000)\n \n attention_score = torch.unsqueeze(F.softmax(weight, dim = 0), dim = 2) ## seq_len batch_size 1\n x = (attention_score * encoder_out).sum(0)\n if self.encoder_transform is not None:\n x = self.output_proj(x) + decoder_hidden_state ## something like residual connection\n else:\n x = x + decoder_hidden_state\n return x\n\n\nclass BairuLSTMDecoder(BairuDecoder):\n def __init__(self, config: BairuConfig, dictionary, token_embedding = None):\n super().__init__(dictionary)\n num_tokens = dictionary.num_tokens\n self.padding_idx = config.pad_token_id\n self.hidden_size = config.decoder_hidden_size\n self.hidden_layer = config.decoder_hidden_layer\n self.embedding_dim = config.decoder_embedding_dim\n self.num_layers = config.decoder_hidden_layer\n self.batch_first = config.batch_first\n self.input_feed_size = config.decoder_hidden_size\n self.decoder_init = config.decoder_init\n if token_embedding is None:\n self.token_embedding = nn.Embedding(num_embeddings = num_tokens, embedding_dim = self.embedding_dim, padding_idx = self.padding_idx, )\n else:\n self.token_embedding = token_embedding\n self.LSTMLayers = nn.ModuleList(\n [\n LSTMCell(input_size = config.embedding_dim + self.input_feed_size, hidden_size = config.decoder_hidden_size)\n if layer == 0 else LSTMCell(input_size = config.decoder_hidden_size , hidden_size = config.decoder_hidden_size)\n for layer in range(config.decoder_hidden_layer)\n ]\n )\n self.dropout = nn.Dropout(p = config.hidden_dropout_prob)\n self.LSTMAttention = LSTMCrossAttention(config,)\n self.output_projection = nn.Linear(config.decoder_hidden_size, num_tokens)\n \n\n self.residual = config.decoder_residual\n if config.layernorm_embedding:\n self.layernorm_embedding = torch.nn.LayerNorm(self.embedding_dim)\n else:\n self.layernorm_embedding = None\n \n\n def forward_embedding(self, prev_output_tokens,):\n x = embed = self.token_embedding(prev_output_tokens)\n if self.layernorm_embedding is not None:\n x = self.layernorm_embedding(x)\n x = self.dropout(x)\n return x, embed\n\n def forward(self, prev_output_tokens, encoder_out = None, **kwargs):\n x, extra = self.extract_features(prev_output_tokens, encoder_out, **kwargs)\n res = self.output_layer(x,)\n net_output = {\n 'output':res,\n 'extra':extra\n }\n return net_output\n \n def extract_features(self, prev_output_tokens, encoder_out = None, **kwargs):\n encoder_output = encoder_out['encoder_out']\n encoder_padding_mask = encoder_out['encoder_padding_mask']\n\n batch_size, seq_len = prev_output_tokens.size()\n x, embed = self.forward_embedding(prev_output_tokens)\n if not self.batch_first:\n x = x.transpose(0, 1)\n encoder_output = encoder_output.transpose(0,1)\n encoder_padding_mask = encoder_padding_mask.transpose(0,1)\n if self.decoder_init == 'enc':\n if self.batch_first:\n enc_init = torch.mean(encoder_output, dim = 1)\n else:\n enc_init = torch.mean(encoder_output, dim = 0)\n h0 = [enc_init for _ in range(self.hidden_layer)]\n c0 = [enc_init for _ in range(self.hidden_layer)] \n elif self.decoder_init == 'none':\n zero_state = x.new_zeros(batch_size, self.hidden_size)\n h0 = [zero_state for _ in range(self.hidden_layer)]\n c0 = [zero_state for _ in range(self.hidden_layer)]\n else:\n raise Exception()\n ## Please refer to paper Effective Approaches to Attention-based Neural Machine Translation for the input feed operation \n prev_hidden = x.new_zeros(batch_size, self.hidden_size)\n\n\n outs = []\n for j in range(seq_len):\n input_x = torch.cat([x[j,:,:], prev_hidden], dim = 1)\n for i, lstm_cell in enumerate(self.LSTMLayers):\n h, c = lstm_cell(input_x,(h0[i], c0[i]))\n\n input_x = self.dropout(h)\n if self.residual:\n input_x = input_x + h0[i]\n h0[i] = h\n c0[i] = c\n\n ## Attention\n out = self.dropout(self.LSTMAttention(h, encoder_output, encoder_padding_mask))\n outs.append(out)\n prev_hidden = out\n x = torch.stack(outs, dim = 0)\n if not self.batch_first:\n x = x.transpose(0, 1)\n return x, []\n # return {\n # 'output':x,\n # 'others':[]\n # }\n\n def output_layer(self, features, **kwargs):\n x = self.output_projection(features)\n return x\n \n\n","repo_name":"hbr690188270/cs291k_hw","sub_path":"hw2/hw2/models/lstm_decoder.py","file_name":"lstm_decoder.py","file_ext":"py","file_size_in_byte":6216,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27930844254","text":"from collections import deque\r\nimport sys\r\n\r\ninput = sys.stdin.readline\r\n\r\nt = int(input().strip())\r\n\r\nfor _ in range(t):\r\n n, m = map(int, input().split())\r\n queue = deque(enumerate(map(int, input().split())))\r\n \r\n count = 0\r\n while True:\r\n max_value = max(queue, key=lambda x: x[1])[1]\r\n front = queue.popleft()\r\n \r\n if front[1] == max_value:\r\n count += 1\r\n if front[0] == m:\r\n print(count)\r\n break\r\n else:\r\n queue.append(front)\r\n","repo_name":"kyunghyunHan/algorithm_backjun","sub_path":"백준/Silver/1966. 프린터 큐/프린터 큐.py","file_name":"프린터 큐.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19247077805","text":"import math\n\n# 1-1\n\n\ndef getFuel(mass):\n return math.floor(mass / 3) - 2\n\n# 1-2\n\n\ndef getTotalFuel(mass):\n extraFuel = math.floor(mass / 3) - 2\n if extraFuel > 0:\n return extraFuel + getTotalFuel(extraFuel)\n else:\n return 0\n\n\ntotal_fuel = 0\n\nwith open('modules.txt', 'r') as open_file:\n for module in open_file:\n total_fuel += getTotalFuel(int(module))\n\nprint(total_fuel)\n","repo_name":"dculp40/adventOfCode2019","sub_path":"1-1.py","file_name":"1-1.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20827105706","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#from selenium.webdriver.common.keys import Keys\nimport time\nfrom PIL import Image\nfrom io import BytesIO\nimport base64\nimport numpy as np\nimport cv2\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport copy\n\nclass Game():\n def __init__(self, game_url, chrome_driver_path, init_script, cam_visualization=False):\n init_script = \"document.getElementsByClassName('runner-canvas')[0].id = 'runner-canvas'\"\n self.getbase64Script = \"canvasRunner = document.getElementById('runner-canvas'); \\\n return canvasRunner.toDataURL().substring(22)\" \n chrome_options = Options()\n chrome_options.add_argument('headless') # not showing browser is faster\n chrome_options.add_argument(\"disable-infobars\")\n chrome_options.add_argument(\"--mute-audio\")\n # self.driver = webdriver.Chrome(executable_path=chrome_driver_path, options=chrome_options)\n self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)\n self.driver.set_window_position(x=-10,y=0)\n # print(self.driver.get_window_size()) # print the size of browser\n self.driver.set_window_size(1450, 1080)\n self.driver.get(game_url)\n self.driver.execute_script(\"Runner.config.ACCELERATION=0\") # no ACCELERATION and birds for the game, easy mode, \n time.sleep(1) # wait the html\n self.driver.execute_script(init_script) # set id for the canvas\n self.CV_display = self.show_img() # show the state using opencv instead of the browser\n self.CV_display.__next__() # initiliaze the display coroutine\n self.cam_visualization = cam_visualization\n \n def screen_shot(self):\n image_b64 = self.driver.execute_script(self.getbase64Script)\n np_img = np.array(Image.open(BytesIO(base64.b64decode(image_b64))))\n np_img = cv2.cvtColor(np_img, cv2.COLOR_BGR2GRAY) # change 4 channels to 1 gray channel\n self.canvas_image = copy.deepcopy(np_img)\n np_img = cv2.resize(np_img, (80,80)) # resize the image to smaller\n #np_img = Image.fromarray(np_img)\n #np_img = np_img.save('./img/'+str(i)+'.png')\n return np_img\n\n def show_img(self, graphs = False):\n while True:\n screen = (yield)\n window_title = \"logs\" if graphs else \"game_play\"\n cv2.namedWindow(window_title, cv2.WINDOW_NORMAL)\n imS = cv2.resize(screen, (200, 130)) # the size of the cv2 window\n cv2.imshow(window_title, imS)\n if (cv2.waitKey(1) & 0xFF == ord('q')):\n cv2.destroyAllWindows()\n break\n \n def save_gif(self):\n pass\n \n # get current state\n def get_state(self,actions, grayscale_cam=None):\n ''' grayscale_cam: the cam result to be visualized during testing '''\n reward = 0.1\n is_over = False #game over\n if actions[1] == 1:\n self.press_up()\n '''elif actions[1] == 2:\n self.press_down()'''\n image = self.screen_shot()\n \n self.CV_display.send(image)\n \n\n if self.get_crashed():\n reward = -1\n is_over = True\n \n return image, reward, is_over #return the Experience tuple\n\n def get_crashed(self):\n return self.driver.execute_script(\"return Runner.instance_.crashed\")\n\n def get_playing(self):\n return self.driver.execute_script(\"return Runner.instance_.playing\")\n\n def restart(self):\n self.driver.execute_script(\"Runner.instance_.restart()\")\n\n def press_up(self):\n self.driver.find_element_by_tag_name(\"body\").send_keys(Keys.ARROW_UP)\n\n def press_down(self):\n self.driver.find_element_by_tag_name(\"body\").send_keys(Keys.ARROW_DOWN)\n\n def get_score(self):\n score_array = self.driver.execute_script(\"return Runner.instance_.distanceMeter.digits\")\n score = ''.join(score_array) # the javascript object is of type array with score in the formate[1,0,0] which is 100.\n return int(score)\n\n def pause(self):\n return self.driver.execute_script(\"return Runner.instance_.stop()\")\n\n def resume(self):\n return self.driver.execute_script(\"return Runner.instance_.play()\")\n\n def end(self):\n self.driver.close()","repo_name":"SamYuen101234/chrome_dino_RL","sub_path":"utils/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8747359337","text":"'''\nFunctions to access values from Nuke Nodes\n'''\n\nimport os\nimport re\nimport nuke\nimport getseq\n\nimport dd.xplatform\n\nfrom dd.runtime.api import relativeImport, load\nfrom dd.runtime import info\nload('ddlogger')\nimport ddlogger\nLOGGER = ddlogger.getLogger('getfromnode')\n\nload('nukepipeline')\nif info.getVersionToBeLoaded(\"nukepipeline\") >= \"3.1.0\":\n relativeImport('matchnode', 'nukepipeline/common/utils')\nelse:\n relativeImport('matchnode', 'common/utils')\nfrom matchnode import byClass\n\n\ndef filePath(node=None, proxy=False, regex=None, force_match=True):\n \n \"\"\"\n Retrieves the file path of any node that has one associated with it.\n regex can be used to filter only to nodes with file knobs whose\n Class() fits the pattern\n \"\"\"\n \n result = None\n\n # check node, use selected Node in dag if no arg\n if not node:\n node = nuke.selectedNode()\n \n # check for regex, eliminate non-matching node\n if regex:\n if not byClass(node, regex, force_match):\n node = None\n \n # check for node elimination\n if node:\n try:\n my_knob = node.knob('file')\n try:\n # attempt to get file knob from linked (gizmos < 5.2v1)\n result = my_knob.getLinkedKnob().getValue()\n except AttributeError:\n # attempt to get file knob value directly (gizmos >= 5.2v1)\n result = my_knob.getValue()\n # end try\n except AttributeError:\n try:\n # grab filename directly from node with nuke.filename\n result = nuke.filename(node)\n except NameError:\n # do nothing if nuke.filename errors out (earlier Nuke version)\n pass\n # end try\n except:\n raise\n # end try\n \n # check if proxy enabled, if so return Proxy knob instead of File\n if proxy:\n if nuke.root().proxy():\n if 'proxy' in node.knobs():\n try:\n # attempt to get proxy knob from linked (gizmos < 5.2v1)\n if node.getLinkedKnob().knob('proxy').value():\n result = node.getLinkedKnob().knob('proxy').value()\n except AttributeError:\n # attempt to get proxy knob value directly (gizmos >= 5.2v\n if node.knob('proxy').value():\n result = node.knob('proxy').value()\n # end if\n\n # check if a TCL expression might exist in the result (ie: containts [{($)}])\n\n expression_check = re.search('[\\[\\{\\(\\]\\}\\)\\$]', str(result))\n # if an expression might exist, attempt to evaluate\n if expression_check:\n # make a copy of the result to process\n eval_result = result\n\n # create a tmp write node to do the evaluation in\n # if you can figure out a better way to evaluate as Nuke does, be my guest\n tmp = nuke.createNode('Write', inpanel=False)\n\n try:\n # LOGIC (IF ANY) BEHIND THE FOLLOWING:\n # knob.evaluate() always evaluates fully, so %V is replaced with the\n # full view name, %v is always replaced with the lowercase first\n # letter of the view, and the %d range string (ie %04d, %03d) is\n # always replaced with the then-current frame value.\n # This is not desireable for most uses, but it is still desireable\n # to evaluate any internal TCL expressions before returning the\n # filePath (otherwise you get the lengthy tcl gibberish instead\n # of a meaningful value) ... hence what follows.\n # NOTE: If someone is actually trying to include the View or\n # Range variable characters inside their pre-evaluation expression,\n # we're hosed.\n\n # we need the %v or %V variable to remain unevaluated\n view_test = re.search('(%[V|v])', eval_result)\n # if it exists, log old value and replace with !VIEW! placeholder\n if view_test:\n old_view = view_test.groups()[0]\n eval_result = re.sub(old_view, '!VIEW!', eval_result)\n\n # we need the %d frame range variable to remain unevaluated\n range_test = re.search('(%[0-9]+d)', eval_result)\n # if it exists, log old value and replace with !RANGE! placeholder\n if range_test:\n old_range = range_test.groups()[0]\n eval_result = re.sub(old_range, '!RANGE!', eval_result)\n\n # let nuke do the actual evaluation work\n tmp.knob('file').setValue(eval_result)\n eval_result = tmp.knob('file').evaluate()\n\n # put the stored range variable back\n if range_test:\n eval_result = re.sub('!RANGE!', old_range, eval_result)\n\n # put the stored view variable back\n if view_test:\n eval_result = re.sub('!VIEW!', old_view, eval_result)\n\n # evaluation succeeded\n result = eval_result\n except:\n # evaluation failed, leave result alone and let the gods sort it out\n pass\n finally:\n # one way or another, clean up the tmp node\n nuke.delete(tmp)\n\n if result != None:\n result = dd.xplatform.xpath(os.path.normpath(result))\n LOGGER.debug('Discovered path %s for node %s' % (\n result, node.knob('name').value()))\n return result\n else:\n LOGGER.debug('Discovered no path for node %s' % node.knob('name').value())\n return None\n# end filePath\n \n\ndef filePathWithRange(node=None, proxy=False, regex=None, force_match=True):\n \n \"\"\"\n Retrieves the file path of any node that has one associated with it.\n regex can be used to filter only to nodes with file knobs whose\n Class() fits the pattern.\n \"\"\"\n \n result = None\n\n # check node, use selected Node in DAG if no arg\n if not node:\n node = nuke.selectedNode()\n\n # check node again (in case user has no selection made)\n # get file path from node\n if node:\n path = filePath(node, proxy, regex, force_match)\n # if file path found, append frame range data\n # use getseq instad of root range\n # makes more sense eh? #61881 / #64178\n if path:\n first_frame, last_frame = getseq.getRange(path)\n LOGGER.debug('Discovered range of %s-%s' % (first_frame, last_frame))\n result = '%s %s-%s' % (path, first_frame, last_frame)\n\n # return the path and range discovered\n return result\n# end filePathWithRange\n\n\ndef filePaths(nodes=None, proxy=False, regex=None, force_match=True):\n \n \"\"\"\n Returns a list of the file paths (if any) associated with the nodes in the\n nodes. Filter using regex to restrict the results to \n nodes whose Class() matches the pattern.\n \"\"\"\n \n result = []\n\n # check nodes, use selected Nodes in DAG if no arg\n if not nodes:\n nodes = nuke.selectedNodes()\n\n # loop through nodes and get path for each Node\n for i in nodes:\n try:\n result.append(filePath(i, proxy, regex, force_match))\n except AttributeError:\n pass\n \n return result\n# end filePaths\n\n\ndef filePathsWithRanges(nodes=None, proxy=False, regex=None, force_match=True):\n \n \"\"\"\n Returns a list of the file paths (if any) associated with the nodes in the\n nodes. Filter using regex to restrict the results to \n nodes whose Class() matches the pattern.\n \"\"\"\n \n result = []\n\n # check nodes, use selected Nodes in DAG if no arg\n if not nodes:\n nodes = nuke.selectedNodes()\n\n # loop through nodes and get path and range for each Node\n for i in nodes:\n try:\n range = filePathWithRange(i, proxy, regex, force_match)\n if range:\n result.append(range)\n except AttributeError:\n pass\n \n return result\n# end filePaths\n\ndef fileType(node):\n \"\"\"\n Returns the file extension of the node given\n \"\"\"\n result = os.path.splitext(filePath(node))[1].lstrip('.')\n LOGGER.debug('Filetype for node %s is %s' % (node.knob('name').value(), result))\n return result\n# end fileType\n\ndef format(node):\n \n \"\"\"\n Returns the format of the specified Node, if in the nuke.formats() list\n \"\"\"\n \n my_format = None\n \n # check for node; default to selected Node in DAG if no arg\n if not node:\n node = nuke.selectedNode()\n # endif\n\n # check for Node again (see if user has failed to make selection)\n if node:\n # grab height from node\n my_height = node.height()\n \n # grab width from node\n my_width = node.width()\n \n # grab pixel aspect ratio from node as float\n my_pixel_aspect = float(nuke.value('%s.pixel_aspect' % node.fullName()))\n \n # this is the format to search for\n my_format = (my_height, my_width, my_pixel_aspect)\n \n # scan nuke.formats for matching format\n for i in nuke.formats():\n thisFormat = (i.height(), i.width(), i.pixelAspect())\n # if matching format found, assign my_format to the match\n if thisFormat == my_format:\n my_format = i\n break\n \n # return whatever is the current value of my_format\n LOGGER.debug('Format for node %s is %s' % (node.knob('name').value(), my_format))\n return my_format\n# end format\n\n\n# end getfromnode\n","repo_name":"syurskyi/Python_Topics","sub_path":"333_nuke/example/useful_small_function/getfromnode.py","file_name":"getfromnode.py","file_ext":"py","file_size_in_byte":9810,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39942377427","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n# vim: set fdm=marker :\n# This code is PEP8-compliant. See http://www.python.org/dev/peps/pep-0008.\n\"\"\"\nUnit tests for alex.util.fs.\n\n\"\"\"\n\nimport os\nimport os.path\nimport tempfile\nimport unittest\nfrom fs import normalise_path, find\n\n\nclass TestFind(unittest.TestCase):\n\n def setUp(self):\n #{{{\n \"\"\"\n Creates a playground of a directory tree.\n It looks like this:\n /\n - a/\n - aa/\n - ab/\n - ac/\n - aca/\n - acaa/\n - acab -> baaaa\n - b/\n - ba/\n - baa/\n - baaa/\n - baaaa -> daaa\n - baaab/\n - baaaba/\n - baaabaa/\n - baaabab -> ca\n - c/\n - ca/\n - caa/\n - cab/\n - caba/\n - cac -> db\n - d/\n - da/\n - daa/\n - daaa -> acab\n - db -> baaaba\n\n \"\"\"\n self.testroot = tempfile.mkdtemp()\n # Make the directory structure.\n # list of all the dirs {{{\n dirs = [\n (self.testroot, 'a',),\n (self.testroot, 'a', 'aa'),\n (self.testroot, 'a', 'ab'),\n (self.testroot, 'a', 'ac'),\n (self.testroot, 'a', 'ac', 'aca'),\n (self.testroot, 'a', 'ac', 'aca', 'acaa'),\n (self.testroot, 'b',),\n (self.testroot, 'b', 'ba'),\n (self.testroot, 'b', 'ba', 'baa'),\n (self.testroot, 'b', 'ba', 'baa', 'baaa'),\n (self.testroot, 'b', 'ba', 'baa', 'baaa', 'baaab'),\n (self.testroot, 'b', 'ba', 'baa', 'baaa', 'baaab', 'baaaba'),\n (self.testroot, 'b', 'ba', 'baa', 'baaa', 'baaab', 'baaaba',\n 'baaabaa'),\n (self.testroot, 'c',),\n (self.testroot, 'c', 'ca'),\n (self.testroot, 'c', 'ca', 'caa'),\n (self.testroot, 'c', 'ca', 'cab'),\n (self.testroot, 'c', 'ca', 'cab', 'caba'),\n (self.testroot, 'd',),\n (self.testroot, 'd', 'da'),\n (self.testroot, 'd', 'da', 'daa')\n ]\n # }}}\n for dir_ in dirs:\n os.mkdir(os.path.join(*dir_))\n # Make the symlinks.\n #{{{\n symlinks = [\n (self._pathto('acab'), self._pathto('baaaa')),\n (self._pathto('baaaa'), self._pathto('daaa')),\n (self._pathto('baaabab'), self._pathto('ca')),\n (self._pathto('cac'), self._pathto('db')),\n (self._pathto('daaa'), self._pathto('acab')),\n (self._pathto('db'), self._pathto('baaaba'))\n ]\n for symlink in symlinks:\n os.symlink(symlink[1], symlink[0])\n #}}}\n #}}}\n\n def tearDown(self):\n #{{{\n \"\"\"Deletes the mock-up directory tree.\"\"\"\n for root, dirs, files in os.walk(self.testroot, topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n path = os.path.join(root, name)\n if os.path.islink(path):\n os.unlink(path)\n else:\n os.rmdir(path)\n #}}}\n\n def test_depth(self):\n \"\"\"Tests mindepth and maxdepth.\"\"\"\n #{{{\n self.assertEqual(\n find(self.testroot, '*', 0, 1), self._format_result(\n '.', 'a', 'b', 'c', 'd'))\n self.assertEqual(\n find(self._pathto('ac'), '*', 0, 1), self._format_result(\n 'ac', 'aca'))\n self.assertEqual(\n find(self._pathto('ac'), '*', 0, 0), self._format_result(\n 'ac',))\n self.assertEqual(\n find(self._pathto('ac'), '*', 0, -1), set())\n #}}}\n\n def test_symlinks1(self):\n \"\"\"Basic test for symlinks.\"\"\"\n #{{{\n self.assertEqual(\n find(self._pathto('ac'), '*', 0, 2), self._format_result(\n 'ac','aca','acaa','acab'))\n self.assertEqual(\n find(self._pathto('baaab'), '*', 2, 4), self._format_result(\n 'baaabaa', 'ca',\n 'caa', 'cab', 'cac',\n 'caba'))\n #}}}\n\n\n def test_wrong_args(self):\n \"\"\"Test for handling wrong arguments.\"\"\"\n #{{{\n self.assertEqual(\n find(self._pathto('baaaba'), '*', 41, 35), set())\n #}}}\n\n def test_globs(self):\n \"\"\"Tests processing of the selection glob.\"\"\"\n #{{{\n self.assertEqual(\n find(self._pathto('ac'), '*b', 0, 2), self._format_result(\n 'acab'))\n self.assertEqual(\n find(self._pathto('ac'), 'aca?', 0, 2), self._format_result(\n 'acaa', 'acab'))\n self.assertEqual(\n find(self._pathto('b'), '[!b]*', 4, 7), self._format_result(\n 'ca', 'caa', 'cab'))\n self.assertEqual(\n find(self._pathto('b'), '??[bc]', 4, 7), self._format_result(\n 'cab'))\n #}}}\n\n def test_cycles(self):\n \"\"\"Test the processing of cycles in the directory structure.\"\"\"\n self.assertEqual(\n find(self._pathto('b'), 'ca??', 0, None), self._format_result(\n 'caba'))\n self.assertEqual(\n find(self._pathto('b'), 'c?', 0, None), self._format_result(\n 'ca'))\n\n def test_ignore_globs(self):\n \"\"\"Test the functionality of ignore globs.\"\"\"\n self.assertEqual(\n find(self._pathto('ac'), '*', 0, 2, ['aca?']),\n self._format_result('ac','aca'))\n self.assertEqual(\n find(self._pathto('ac'), '*', 0, 2, ['ac','ac?a']),\n set())\n self.assertEqual(\n find(self._pathto('baaab'), '*', 2, 4, ['*b']),\n self._format_result('baaabaa', 'ca', 'caa', 'cac'))\n\n # TODO Test other arguments of the function.\n\n def _pathto(self, fname):\n \"\"\"\n Returns the absolute path to one of the created test directories (or\n links). The root can be specified by the name '.'.\n \"\"\"\n #{{{\n if fname == '.':\n return self.testroot\n dirs = [self.testroot] +\\\n [fname[:preflen] \\\n for preflen in xrange(1, len(fname) + 1)]\n return os.path.join(*dirs)\n #}}}\n\n def _format_result(self, *fnames):\n return set(map(\n lambda fname: normalise_path(self._pathto(fname)),\n fnames))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"UFAL-DSG/alex","sub_path":"alex/utils/test_fs.py","file_name":"test_fs.py","file_ext":"py","file_size_in_byte":6719,"program_lang":"python","lang":"en","doc_type":"code","stars":180,"dataset":"github-code","pt":"52"} +{"seq_id":"26120092274","text":"\"\"\" This module houses commonly used functions / tools\"\"\"\nimport os\nimport sys\nimport time\n\n\ndef display_clear():\n # This is the URL that this code was found on:\n # http://www.delftstack.com/howto/python/python-clear-console/\n \"\"\"\n clears console\n \"\"\"\n command = 'clear'\n if os.name in ('nt', 'dos'):\n command = 'cls'\n os.system(command)\n\n\ndef type_slowly(text):\n # This is the URL that this code was found on:\n # https://stackoverflow.com/a/10390877\n \"\"\"\n allows text to by typed out slowly\n instead of all appearing at once\n \"\"\"\n for i in text:\n sys.stdout.write(i)\n sys.stdout.flush()\n time.sleep(0.02)\n","repo_name":"cwallacebailey/Project3_battleships_template","sub_path":"python/general_functions.py","file_name":"general_functions.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42054783410","text":"import os\nimport sys\nimport json\nimport numpy as np\nfrom PIL import Image\nfrom pycocotools.coco import COCO\nfrom skimage.draw import polygon\nimport argparse\n\n\ndef get_coco_labels_dict(coco: COCO):\n\n # Get all categories\n cat_ids = coco.getCatIds()\n categories = coco.loadCats(cat_ids)\n\n # Initialize a dictionary to store the labels and their indices\n labels_dict = {}\n\n # Iterate over each category\n for category in categories:\n labels_dict[category['name']] = category['id']\n\n # Print the dictionary\n return labels_dict\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--annotations_file\", type=str, default=\"/disk2/nadav/COCO/annotations/instances_train2017.json\", help=\"path of COCO annotations file\",\n)\nparser.add_argument(\n \"--images_dir\", type=str, default=\"/disk2/nadav/rula/dataset/coco_stuff/train_img\", help=\"path of COCO images directory\",\n)\nparser.add_argument(\n \"--output_dir\", type=str, default=\"_objects_and_masks\", help=\"path of output directory\",\n)\nparser.add_argument(\n \"--max_obj\", type=int, default=100, help=\"maximum number of objects to generate\",\n)\nparser.add_argument(\n \"--max_frames\", type=int, default=None, help=\"maximum number of frames to process\",\n)\nparser.add_argument(\n \"--min_crop\", type=int, default=1000, help=\"minimum size of object bbox to crop\",\n)\nparser.add_argument(\n \"--label\", type=str, default=\"motorcycle\", help=\"label to crop\",\n)\nopt, unknown = parser.parse_known_args()\n\nannotations_file = opt.annotations_file\nimages_base_path = opt.images_dir\noutput_dir = opt.output_dir\nmaximum_number_of_objects = opt.max_obj\nmaximum_number_of_frames = opt.max_frames\nminimum_crop_size = opt.min_crop\n\nos.makedirs(output_dir, exist_ok=True)\n\n\ncoco = COCO(annotations_file)\ncoco_labels_dict = get_coco_labels_dict(coco)\n\nselected_categories = [opt.label]\nselected_categories_ids = [coco_labels_dict[label] for label in selected_categories]\n\ncats = coco.loadCats(selected_categories_ids)\nimgIds = coco.getImgIds(catIds=coco.getCatIds(cats))\nif maximum_number_of_frames is None:\n maximum_number_of_frames = len(imgIds)\n\ntotal_number_of_objects = 0\nfor ix, img_id in enumerate(imgIds[:maximum_number_of_frames]):\n\n # Load the image\n filename = coco.loadImgs(img_id)[0]['file_name']\n img_path = os.path.join(\n images_base_path,\n filename\n )\n\n img = Image.open(img_path).convert(\"RGB\")\n orig_img = np.array(img)\n\n # Get annotations for the image\n ann_ids = coco.getAnnIds(imgIds=img_id)\n annotations = coco.loadAnns(ann_ids)\n\n # Crop objects and masks by category\n output_ann_id = 0\n for ann_i, ann in enumerate(annotations):\n if type(ann[\"segmentation\"]) == list:\n if \"segmentation\" in ann and ann['category_id'] in selected_categories_ids:\n masked_img = np.zeros_like(orig_img)\n\n for seg_i, seg in enumerate(ann[\"segmentation\"]):\n poly = np.array(seg).reshape((int(len(seg) / 2), 2))\n rr, cc = polygon(poly[:, 1] - 1, poly[:, 0] - 1)\n masked_img[rr, cc, :] = 1\n\n\n obj = np.where(masked_img, orig_img, masked_img)\n mask = np.where(masked_img, 255, masked_img)\n\n rows, cols, _ = np.where(mask == 255)\n min_x, max_x = min(cols), max(cols)\n min_y, max_y = min(rows), max(rows)\n\n obj = obj[min_y:max_y, min_x:max_x, :]\n mask = mask[min_y:max_y, min_x:max_x, :]\n if obj.shape[0]*obj.shape[1]= maximum_number_of_objects:\n break\n\n\n","repo_name":"NadavOrzech/RGBImageComposition","sub_path":"scripts/coco_crop_objects_by_cat_id.py","file_name":"coco_crop_objects_by_cat_id.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24138503865","text":"from django.urls import path\nfrom . import views\nfrom .views import HomeView, DetailPostView, AddPostView, EditPostView, DeletePostView, CategoryView, LikeView, \\\n AddCommentView, AddCategoryView\n\nurlpatterns = [\n path('', HomeView.as_view(), name='home'),\n path('article//', DetailPostView.as_view(), name='detail-post'),\n path('add-post/', AddPostView.as_view(), name='add-post'),\n path('add-category/', AddCategoryView.as_view(), name='add-category'),\n path('article/edit//', EditPostView.as_view(), name='edit-post'),\n path('article/delete//', DeletePostView.as_view(), name='delete-post'),\n path('categories//', CategoryView, name='categories'),\n path('like//', LikeView, name='like-post'),\n path('article//comment/', AddCommentView.as_view(), name='add-comment'),\n]\n","repo_name":"Arminpanahpour/blog","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2324077807","text":"from PIL import Image,ImageDraw\nimport cv2\nfrom pickle import dump, load\nimport os\n\nstats_dir = \"statistics/\"\nmean_file = stats_dir+\"mean.jpg\"\nsd_file = stats_dir+\"sd.jpg\"\nz_dir = \"z_pics/\"\nz_pickle = 'zscore.pickle'\npoints_file = 'statistics/mouse_location'\nchambers_file = 'statistics/mouse_chamber'\n\n# Only analyze 1 out of every skip frames for speed\nskip=100\n# Depends on the video\nfps=30\n\ndef setup():\n if not os.path.isdir(stats_dir):\n os.mkdir(stats_dir)\n if not os.path.isdir(z_dir):\n os.mkdir(z_dir)\n\n\ndef avg_video(video):\n if os.path.isfile(mean_file):\n return Image.open(mean_file)\n vidcap = cv2.VideoCapture(video)\n success,frame=vidcap.read()\n frame=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n frames = 0\n px1 = [[(0,0,0) for _ in range(frame.size[1])] for _ in range(frame.size[0])]\n mean = Image.new('RGB',frame.size, (0,0,0))\n px = mean.load()\n \n while success:\n if frames%skip == 0:\n print(frames)\n success,frame = vidcap.read()\n if not success:\n break\n frame=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n frames+=1\n if frames%skip !=0:\n continue\n px2 = frame.load()\n for i in range(frame.size[0]):\n for j in range(frame.size[1]):\n px1[i][j] = tuple([x+y for (x,y) in zip(px1[i][j],px2[i,j])])\n for i in range(mean.size[0]):\n for j in range(mean.size[1]):\n px[i,j] = tuple([v//(frames//skip) for v in px1[i][j]])\n mean.save(mean_file, \"JPEG\")\n return mean \n\n\ndef stddev_video(video):\n if os.path.isfile(sd_file):\n return Image.open(sd_file)\n mean = avg_video(video) \n meanpx = mean.load()\n vidcap = cv2.VideoCapture(video)\n success,frame=vidcap.read()\n frame=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n frames = 0\n px1 = [[(0,0,0) for _ in range(frame.size[1])] for _ in range(frame.size[0])]\n sd = Image.new('RGB',frame.size, (0,0,0))\n px = sd.load()\n while success:\n if frames%skip == 0:\n print(frames)\n success,frame = vidcap.read()\n if not success:\n break\n frame=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n frames+=1\n if frames%skip !=0:\n continue\n px2 = frame.load()\n for i in range(frame.size[0]):\n for j in range(frame.size[1]):\n px1[i][j] = tuple([x+(y-z)**2 for (x,y,z) in zip(px1[i][j],px2[i,j],meanpx[i,j])])\n for i in range(sd.size[0]):\n for j in range(sd.size[1]):\n px[i,j] = tuple([v//(frames//skip) for v in px1[i][j]])\n \n sd.save(sd_file)\n return sd\n\n\ndef z_video(video):\n mean = avg_video(video)\n sd = stddev_video(video)\n mean_px = mean.load()\n sd_px = sd.load()\n zs = []\n vidcap = cv2.VideoCapture(video)\n success,frame=vidcap.read()\n frame=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n frames = 0\n while success:\n if frames%skip == 0:\n print(frames)\n success,frame = vidcap.read()\n if not success:\n break\n frame=Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n frames+=1\n if frames%skip !=0:\n continue\n px2 = frame.load()\n z = [[(0,0,0) for _ in range(frame.size[1])] for _ in range(frame.size[0])]\n z_image = Image.new('RGB',frame.size, (0,0,0))\n z_px = z_image.load()\n for i in range(frame.size[0]):\n for j in range(frame.size[1]):\n z[i][j] = tuple([max(0, int((m-x))) if s!=0 else 0 for (m,s,x) in zip(mean_px[i,j],sd_px[i,j],px2[i,j])])\n z_px[i,j] = tuple([min(255,4*max(0,(int((m-x))))) if s!=0 else 0 for (m,s,x) in zip(mean_px[i,j],sd_px[i,j],px2[i,j])])\n zs.append(z)\n z_image.save(z_dir+\"z_%d.jpg\"%frames, \"JPEG\")\n return zs\n\n\ndef cz_video(video):\n if os.path.isfile(z_pickle):\n f = open(z_pickle, \"rb\")\n zs = load(f)\n else:\n zs = z_video(video)\n f = open(z_pickle, 'wb')\n dump(zs, f)\n f.close()\n out = open(points_file, \"w\")\n last = None\n for z in zs:\n X,Y = 0,0\n w = 0\n for i in range(len(z)):\n for j in range(len(z[0])):\n if last is not None:\n if abs(i-last[0])>120 or abs(j-last[1])>120:\n continue\n a, b, c = z[i][j]\n wi = a**4 + b**4 + c**4\n w+= wi \n X+=i*wi\n Y+=j*wi\n last = (X/w,Y/w)\n out.write(\"(\" +str(X/w)+ \", \"+str(Y/w)+\")\")\n out.close()\n\n\ndef which_chamber(video):\n out = open(chambers_file, \"w\")\n if not os.path.isfile(points_file):\n cz_video(video)\n f = open(points_file)\n for line in f:\n x = float(line.split(\", \")[0][1:]) \n \n #Wall locations hard coded for now \n if x < 210:\n out.write (\"0\\n\")\n if x >= 210 and x < 405:\n out.write (\"1\\n\")\n if x >= 405:\n out.write(\"2\\n\")\n out.close()\n\n\ndef time_chamber(video):\n setup()\n if not os.path.isfile(chambers_file):\n which_chamber(video)\n f = open(chambers_file)\n counts = [0,0,0]\n for line in f:\n chamber = int(line)\n counts[chamber]+=skip/fps\n print(counts)\n\n \n \n \n \n \n \n \n \n \n \n","repo_name":"rhianb/threechamber","sub_path":"threechamber.py","file_name":"threechamber.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"20136233004","text":"from problem_utils import *\n\nclass RectangleCoveringEasy:\n def solve(self, holeH, holeW, boardH, boardW):\n input_int0 = holeH\n input_int1 = holeW\n input_int2 = boardH\n input_int3 = boardW\n # There is a rectangular hole in the ground.\n # You are given the dimensions of this rectangle: ints holeH and holeW .\n # You have a rectangular board.\n # You are given its dimensions: ints boardH and boardW .\n # You would like to use the board to cover the hole.\n # There are some rules you must follow when covering the hole: You may rotate the board, but you must place it so that the sides of the board are parallel to the sides of the hole.\n may(rotate(board))\n # The board must cover the entire hole.\n # All corners of the board must be strictly outside the hole.\n # ROOT-0(root=be-7(nsubj=corners-2(det=All-1, prep_of=board-5(det=the-4)), aux=must-6, advmod=strictly-8, prep_outside=hole-11(det=the-10)))\n def can(): root=be(corners(det=All, prep_of=board), aux=must, advmod=strictly, prep_outside=hole) \n # (That is, they are not allowed to lie on the boundary of the hole.)\n # If you can cover the hole using the board you have, return 1.\n return 1 if can else -1\n # Otherwise, return -1.\n\n\n\ndef example0():\n\tcls = RectangleCoveringEasy()\n\tinput0 = 1\n\tinput1 = 1\n\tinput2 = 1\n\tinput3 = 1\n\treturns = -1\n\tresult = cls.solve(input0, input1, input2, input3)\n\treturn result == returns\n\n\ndef example1():\n\tcls = RectangleCoveringEasy()\n\tinput0 = 3\n\tinput1 = 5\n\tinput2 = 4\n\tinput3 = 6\n\treturns = 1\n\tresult = cls.solve(input0, input1, input2, input3)\n\treturn result == returns\n\n\ndef example2():\n\tcls = RectangleCoveringEasy()\n\tinput0 = 10\n\tinput1 = 20\n\tinput2 = 25\n\tinput3 = 15\n\treturns = 1\n\tresult = cls.solve(input0, input1, input2, input3)\n\treturn result == returns\n\n\ndef example3():\n\tcls = RectangleCoveringEasy()\n\tinput0 = 3\n\tinput1 = 10\n\tinput2 = 3\n\tinput3 = 12\n\treturns = 1\n\tresult = cls.solve(input0, input1, input2, input3)\n\treturn result == returns\n\n\n\nif __name__ == '__main__':\n\tprint(example0())","repo_name":"jvalansi/word2code","sub_path":"word2code/res/translations/RectangleCoveringEasy.py","file_name":"RectangleCoveringEasy.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30476224393","text":"from flask import current_app, url_for, jsonify\r\nimport redis\r\nimport time\r\n\r\ndef is_redis_available():\r\n r = redis.from_url(current_app.config['CELERY_BROKER_URL'])\r\n try:\r\n r.ping()\r\n return True\r\n except redis.exceptions.ConnectionError:\r\n return False\r\n\r\nclass Scraper:\r\n def __init__(self, name, task_func):\r\n self.name = name\r\n self.task_id = None\r\n self.task_func = task_func\r\n\r\n def assign_worker(self):\r\n # TODO: replace this with a more definite check for whether or not a worker is available\r\n task = self.task_func.apply_async()\r\n retries = 0\r\n while True:\r\n time.sleep(0.2)\r\n try:\r\n task.info.get('current', 0) # This succeeds if a worker picked up the task, and fails otherwise\r\n self.task_id = task.id # task_id is only set if a worker is confirmed to have picked up the task\r\n return self.task_id\r\n except AttributeError:\r\n retries += 1\r\n if retries > 15:\r\n return None\r\n\r\n def start_task(self):\r\n \"\"\"starts the task and returns basic info\"\"\"\r\n\r\n if not is_redis_available():\r\n return jsonify({}), 500, {'message-body': \"Could not make connection to Redis\"}\r\n\r\n if self.task_id:\r\n if self.status()['state'] != \"PENDING\" and self.status()['state'] != \"PROGRESS\":\r\n self.task_id = None # remove id if task is stale\r\n if self.task_id == None:\r\n if self.assign_worker():\r\n return jsonify({}), 202, {'Location': url_for('scraping.check_status', scraper_name=self.name)}\r\n else:\r\n return jsonify({}), 500, {'message-body': \"Redis is running, but a worker could not be assigned \"\r\n \"to the task\"}\r\n\r\n def is_running(self):\r\n # TODO: add a harder check on whether or not this is running\r\n if not self.task_id:\r\n return False\r\n\r\n # if the task pending or in progress, leave it and indicate that it is running\r\n # otherwise, the task is dead, so the task_id should be deleted\r\n if self.status()['state'] == \"PENDING\" or self.status()['state'] == \"PROGRESS\":\r\n return True\r\n else:\r\n self.task_id = None\r\n return False\r\n\r\n # TODO: in cases where the task_id is updated to None, there should be some additional confirmation or step taken\r\n # TODO: in order to confirm the task is shut down and not lingering\r\n def status(self):\r\n \"\"\"checks task status and returns info\"\"\"\r\n try:\r\n task = self.task_func.AsyncResult(self.task_id)\r\n # will result in ValueError is task_id is None\r\n except ValueError as e:\r\n return {'state': \"NOT RUNNING\"}\r\n\r\n response = {\r\n 'state': task.state,\r\n 'current': task.info.get('current', 0),\r\n 'total': task.info.get('total', 1),\r\n 'successes': task.info.get('successes', 0),\r\n 'failures': task.info.get('failures', 0),\r\n 'sleeptime': task.info.get('sleeptime', 0),\r\n 'current_url': task.info.get('current_url', \"\"),\r\n 'next_url': task.info.get('next_url', \"\"),\r\n 'status': task.info.get('status', \"\")\r\n }\r\n\r\n if task.state == 'PENDING':\r\n response['status'] = 'Pending...'\r\n elif task.state == 'PROGRESS':\r\n pass\r\n elif task.state == 'SUCCESS':\r\n self.task_id = None\r\n response['current'] = 1\r\n response['total'] = 1\r\n elif task.state == 'FAILURE':\r\n self.task_id = None\r\n if 'result' in task.info:\r\n response['result'] = task.info['result']\r\n else:\r\n self.task_id = None\r\n # something went wrong in the background job\r\n response['status'] = str(task.info) # this is the exception raised\r\n\r\n return response\r\n\r\n def kill_task(self):\r\n try:\r\n task = self.task_func.AsyncResult(self.task_id)\r\n except ValueError:\r\n return None\r\n task.revoke(terminate=True)\r\n self.task_id = None","repo_name":"MelonFaceDOOM/DNMS","sub_path":"app/scraping/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74020025126","text":"import pathlib\nimport struct\n\ndef main():\n script_path = pathlib.Path(__file__).parent\n output_folder = \"./\"\n\n # ---------------------------------- Set properties here\n\n # All named values from the offsets table in the next section can be set here.\n # Values usually are expected to be strings unless documented otherwise.\n # Certain values are mandatory, others can be omitted.\n data = {\n \"id\" : \"plac\",\n \"class\" : \"A\",\n \"pursuit\" : \"No\",\n \"serial number\" : 11,\n\n \"car acceleration\" : 7,\n \"car top speed\" : 9,\n \"car handling\" : 15,\n \"car braking\" : 18,\n\n \"manufacturer\" : \"Placeholder\",\n \"model\" : \"A\",\n \"car name\" : \"Placeholder A\",\n \"price\" : \"$3,000\",\n \"status\" : \"selfmade\",\n \"transmission type\" : \"manual\",\n \"history line1\" : \"Placeholder\",\n \"history line2\" : \"Placeholder\",\n \"history line3\" : \"Placeholder\",\n \"history line4\" : \"Placeholder\",\n \"history line5\" : \"Placeholder\",\n \"history line6\" : \"Placeholder\",\n \"history line7\" : \"Placeholder\",\n \"history line8\" : \"Placeholder\",\n \"color1\" : \"Red\",\n \"color2\" : \"Silver\",\n \"color3\" : \"Deepblue\",\n \"color4\" : \"Grey\",\n \"color5\" : \"Beige\",\n \"color6\" : \"Seagreen\",\n \"color7\" : \"\",\n # \"color8\" : \"\",\n \"color9\" : None,\n \"color10\" : None,\n }\n\n # ---------------------------------- Do not change anything below\n fname = \"fedata.\"\n fendings = [ \"bri\", \"eng\", \"fre\", \"ger\", \"ita\", \"spa\", \"swe\" ]\n\n hdr_offset = 0xcf\n # Assumes dtype == str unless mentioned otherwise\n offsets = [\n \"id\",\n 0x09,\n 0x00,\n 0x01,\n \"class\",\n 0x03,\n 0x00,\n \"pursuit\",\n 0x00,\n 0x00,\n 0x80,\n \"serial number\", # int\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, # 0x0026\n\n \"car acceleration\", # int # 0x0028\n \"car top speed\", # int\n \"car handling\", # int\n \"car braking\", # int\n 0x5,\n\n 0x28,\n\n \"manufacturer\",\n \"model\",\n \"car name\",\n \"price\",\n \"status\",\n \"weight\",\n \"weight dist\",\n \"length\",\n \"width\",\n \"height\",\n \"engine\",\n \"displacement\",\n \"hp\",\n \"torque\",\n \"max engine speed\",\n \"brakes\",\n \"tires\",\n \"top speed\",\n \"time 0-60\",\n \"time 0-100\",\n \"transmission type\",\n \"num gears\",\n \"history line1\",\n \"history line2\",\n \"history line3\",\n \"history line4\",\n \"history line5\",\n \"history line6\",\n \"history line7\",\n \"history line8\",\n \"color1\",\n \"color2\",\n \"color3\",\n \"color4\",\n \"color5\",\n \"color6\",\n \"color7\",\n \"color8\",\n \"color9\",\n \"color10\",\n ]\n\n # Create Fedata3\n assert len(offsets) == 65\n header = [0] * len(offsets)\n ptr = hdr_offset\n ofs = 0 + 0x2f # debug\n for i in range(len(offsets)):\n key = offsets[i]\n if i <= 24:\n if isinstance(key, int):\n header[i] = offsets[i]\n elif key in data:\n if key == \"id\":\n header[i] = data[key]\n elif key == \"class\":\n if data[key] == \"A\" or data[key] == 0x1:\n header[i] = 0x00 # A\n elif data[key] == \"B\" or data[key] == 0x1:\n header[i] = 0x1 # B\n else:\n header[i] = 0x2 # C\n elif key == \"pursuit\":\n if data[key] == \"Yes\" or data[key] == 0x1:\n header[i] = 0x1 # Yes\n else:\n header[i] = 0x0 # No\n elif key in [ \"serial number\",\n \"car acceleration\",\n \"car top speed\",\n \"car handling\",\n \"car braking\" ]:\n header[i] = data[key]\n else:\n print(\"unknown error:\", key)\n else:\n header[i] = ptr\n print(i, \"\", hex(ofs), \" \", ptr, f\"0x{ptr:04x}\", key, key in data)\n ofs += 4 # debug\n\n if key in data and data[key] is not None:\n if isinstance(data[key], int):\n ptr += 4\n elif isinstance(data[key], float):\n ptr += 4\n else:\n ptr += len(str(data[key])) + 1\n else:\n ptr += 1\n\n print(hdr_offset)\n print(header[24])\n print(header)\n\n # verbose: print encoded header items\n for item in header:\n if isinstance(item, str):\n for c in item:\n print(c, bytes(c.encode(\"ascii\", \"ignore\")), ord(c),\n c.encode(\"ascii\", \"ignore\"))\n \"\"\"\n else:\n print(\n str(hex(item)),\n bytes( str(item).encode(\"ascii\", \"ignore\"), )\n )\n print(\n f\"{item:04x}\",\n type(f\"{item:04x}\"),\n ord(str(9)),\n chr(9),\n \"foo\",\n f\"{item:04x}\"[::-1],\n str(9),\n struct.pack(\"= LIFUTILS_REQUIRED_VERSION:\n required_version_installed=True\n return required_version_installed, installed_version\n#\n# check and display messages of lifutils\n#\ndef check_errormessages(parent,ret):\n msg= ret.stderr.decode()\n if msg == \"\":\n return\n#\n# truncate message if length > 150 \n#\n if len(msg) >150:\n msg=msg[:75] + '.. (truncated)'\n#\n# display an error if returncode !=0 otherwise a warning\n#\n if ret.returncode == 0:\n reply=QtWidgets.QMessageBox.warning(parent,'Warning',msg,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n else:\n reply=QtWidgets.QMessageBox.critical(parent,'Error',msg,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n return\n#\n# exec single command\n#\ndef exec_single(parent,cmd):\n try:\n ret=subprocess.run(cmd,stderr=subprocess.PIPE)\n check_errormessages(parent,ret)\n except OSError as e:\n reply=QtWidgets.QMessageBox.critical(parent,'Error',e.strerror,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n finally:\n return\n#\n# exec single command, return output\n#\ndef exec_single_export(parent,cmd):\n returnvalue=None\n try:\n ret= subprocess.run(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n check_errormessages(parent,ret)\n if ret.returncode==0:\n returnvalue= ret.stdout\n#\n# catch errors\n#\n except OSError as e:\n reply=QtWidgets.QMessageBox.critical(parent,'Error',e.strerror,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n finally:\n return returnvalue\n\n#\n# exec piped command, read input from file, return True if success, False otherwise\n#\ndef exec_double_import(parent,cmd1,cmd2,inputfile):\n\n tmpfile=None\n try:\n if isWINDOWS():\n fd= os.open(inputfile, os.O_RDONLY | os.O_BINARY )\n else:\n fd= os.open(inputfile, os.O_RDONLY)\n#\n# create temporary file\n#\n tmpfile=tempfile.TemporaryFile()\n#\n# execute first command\n#\n ret= subprocess.run(cmd1,stdin=fd,stdout=tmpfile,stderr=subprocess.PIPE)\n check_errormessages(parent,ret)\n os.close(fd)\n if ret.returncode!=0:\n tempfile.close()\n return\n#\n# execute second command\n#\n tmpfile.seek(0)\n if not cls_chk_import.execute(tmpfile.fileno(), None):\n tmpfile.close()\n return\n tmpfile.seek(0)\n ret= subprocess.run(cmd2,stdin=tmpfile,stderr=subprocess.PIPE)\n check_errormessages(parent,ret)\n#\n# catch errors\n#\n except OSError as e:\n reply=QtWidgets.QMessageBox.critical(parent,'Error',e.strerror,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n finally:\n if tmpfile is not None:\n tmpfile.close()\n return\n#\n# exec piped command, write output to file or stdout\n#\ndef exec_double_export(parent,cmd1,cmd2,outputfile):\n tmpfile=None\n returnvalue= None\n try:\n fd=None\n if outputfile != \"\":\n#\n# open output file if specified\n#\n if os.access(outputfile,os.W_OK):\n reply=QtWidgets.QMessageBox.warning(parent,'Warning',\"Do you really want to overwrite file \"+outputfile,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Cancel)\n if reply== QtWidgets.QMessageBox.Cancel:\n return\n if isWINDOWS():\n fd= os.open(outputfile, os.O_WRONLY | os.O_BINARY | os.O_TRUNC | os.O_CREAT, 0o644)\n else:\n fd= os.open(outputfile, os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o644)\n#\n# create temporary file\n#\n tmpfile=tempfile.TemporaryFile()\n#\n# execute first command\n#\n ret= subprocess.run(cmd1,stdout=tmpfile,stderr=subprocess.PIPE)\n check_errormessages(parent,ret)\n if ret.returncode!=0:\n tmpfile.close()\n if fd is not None:\n os.close(fd)\n return None\n#\n# execute second command\n#\n tmpfile.seek(0)\n if outputfile != \"\":\n ret= subprocess.run(cmd2,stdin=tmpfile,stdout=fd,stderr=subprocess.PIPE)\n else:\n ret= subprocess.run(cmd2,stdin=tmpfile,stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if ret.returncode==0:\n returnvalue= ret.stdout\n check_errormessages(parent,ret)\n#\n# catch errors\n#\n except OSError as e:\n reply=QtWidgets.QMessageBox.critical(parent,'Error',e.strerror,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n finally:\n if tmpfile is not None:\n tmpfile.close()\n if fd is not None:\n os.close(fd)\n return returnvalue\n\n#\n# validator checks for valid lif label or file names, converts to capital lettes\n#\nclass cls_LIF_validator(QtGui.QValidator):\n\n def validate(self,string,pos):\n self.regexp = QtCore.QRegularExpression('[A-Za-z][A-Za-z0-9]*')\n self.validator = QtGui.QRegularExpressionValidator(self.regexp)\n result=self.validator.validate(string,pos)\n return result[0], result[1].upper(), result[2]\n#\n# pack lif image file dialog\n#\nclass cls_lifpack(QtWidgets.QDialog):\n\n def __init__(self,parent= None):\n super().__init__()\n\n @staticmethod\n def execute(lifimagefile):\n d=cls_lifpack()\n reply = QtWidgets.QMessageBox.question(d, 'Message', 'Do you really want to pack the LIF image file', QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)\n if reply == QtWidgets.QMessageBox.Yes:\n exec_single(d,[add_path(\"lifpack\"),lifimagefile])\n#\n# custom class for text item\n#\nclass cls_textItem(QtWidgets.QGraphicsItem):\n\n def __init__(self,text):\n super().__init__()\n self.text=text\n self.font= QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont)\n self.font.setStyleHint(QtGui.QFont.TypeWriter)\n self.font.setPointSize(2)\n metrics= QtGui.QFontMetrics(self.font)\n self.font_h= metrics.height()\n self.font_w= metrics.width(\"A\")\n self.spacing=20\n self.h= self.font_h+self.spacing*2\n self.w= len(text)* self.font_w\n self.rect= QtCore.QRectF(0,0,self.w,self.h)\n\n def setPos(self,x,y):\n super().setPos(x,y-self.h)\n\n def boundingRect(self):\n return self.rect\n\n def paint(self,painter,option,widget):\n posx=0\n posy=self.font_h\n painter.setFont(self.font)\n painter.drawText(posx,posy,self.text)\n#\n# custom class for barcode\n#\nclass cls_barcodeItem(QtWidgets.QGraphicsItem):\n\n def __init__(self,barcode_title,barcode_row, barcode_height, barcode_narrow_w, barcode_wide_w, barcode_spacing):\n super().__init__()\n self.font=QtGui.QFont()\n self.font.setPointSize(2)\n metrics= QtGui.QFontMetrics(self.font)\n self.font_h= metrics.height()\n self.spacing=20\n self.h= self.font_h+barcode_height+self.spacing*3\n self.w= len(barcode_row)*(barcode_wide_w+barcode_spacing)*8+(barcode_wide_w+barcode_spacing)*4\n self.barcode_title= barcode_title\n self.barcode_row= barcode_row\n self.barcode_height= barcode_height\n self.barcode_narrow_w= barcode_narrow_w\n self.barcode_wide_w= barcode_wide_w\n self.barcode_spacing= barcode_spacing\n self.rect= QtCore.QRectF(0,0,self.w,self.h)\n \n def setPos(self,x,y):\n super().setPos(x,y-self.h)\n\n def boundingRect(self):\n return self.rect\n\n def paint(self,painter,option,widget):\n posx=0\n posy=self.font_h\n#\n# header text\n#\n painter.setFont(self.font)\n painter.drawText(posx,posy,self.barcode_title)\n posy+=self.spacing\n#\n# barcodes\n#\n painter.fillRect(posx,posy,self.barcode_narrow_w,self.barcode_height,QtCore.Qt.black)\n posx+= self.barcode_narrow_w+self.barcode_spacing\n painter.fillRect(posx,posy,self.barcode_narrow_w,self.barcode_height,QtCore.Qt.black)\n posx+= self.barcode_narrow_w+self.barcode_spacing\n\n for i in range(len(self.barcode_row)):\n for k in reversed(range(8)):\n if self.barcode_row[i] & (1 << k):\n painter.fillRect(posx,posy,self.barcode_wide_w,self.barcode_height,QtCore.Qt.black)\n posx+= self.barcode_wide_w+self.barcode_spacing\n else:\n painter.fillRect(posx,posy,self.barcode_narrow_w,self.barcode_height,QtCore.Qt.black)\n posx+= self.barcode_narrow_w+self.barcode_spacing\n painter.fillRect(posx,posy,self.barcode_wide_w,self.barcode_height,QtCore.Qt.black)\n posx+= self.barcode_wide_w+self.barcode_spacing\n painter.fillRect(posx,posy,self.barcode_narrow_w,self.barcode_height,QtCore.Qt.black)\n posx+= self.barcode_narrow_w+self.barcode_spacing\n return\n#\n# output barcode dialog\n#\nclass cls_lifbarcode(QtWidgets.QDialog):\n \n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n def execute (lifimagefile, liffilename, ft,papersize):\n d= cls_lifbarcode()\n#\n# get output file name\n#\n flist= cls_pdfprinter.get_pdfFilename()\n if flist is None:\n return\n output_filename= flist[0]\n#\n# generate binary barcode data from lifutils prog41bar or sdatabar\n#\n if ft== 0xE080:\n output=exec_double_export(d,[add_path(\"lifget\"),\"-r\",lifimagefile,liffilename],[add_path(\"prog41bar\")],\"\")\n title=\"Barcodes for HP-41 program file: \"+liffilename\n else:\n output=exec_double_export(d,[add_path(\"lifget\"),\"-r\",lifimagefile,liffilename],[add_path(\"sdatabar\")],\"\")\n title=\"Barcodes for HP-41 data file: \"+liffilename\n if output is None:\n return\n\n#\n# initialize pdf printer\n#\n pdfprinter=cls_pdfprinter(papersize,PDF_ORIENTATION_PORTRAIT, output_filename,title,True,1)\n pdfprinter.begin()\n#\n# process binary barcode data and generate PDF file\n#\n i=0\n row=0\n while i < len(output):\n# Process barcode, print title\n#\n row+=1\n length=(output[i] &0xF)+1\n barcode_row= []\n i+=1\n for k in range(length):\n if i== len(output):\n return\n barcode_row.append(output[i])\n i+=1\n barcode_header=\"Row: \"+str(row)\n barcode_item= cls_barcodeItem(barcode_header,barcode_row,BARCODE_HEIGHT, BARCODE_NARROW_W, BARCODE_WIDE_W, BARCODE_SPACING)\n pdfprinter.print_item(barcode_item)\n#\n pdfprinter.end()\n\n#\n# purge file dialog\n#\nclass cls_lifpurge(QtWidgets.QDialog):\n\n def __init__(self,parent= None):\n super().__init__()\n\n @staticmethod\n def execute(lifimagefile,liffile):\n d=cls_lifpurge()\n reply = QtWidgets.QMessageBox.question(d, 'Message', 'Do you really want to purge '+liffile, QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)\n if reply == QtWidgets.QMessageBox.Yes:\n exec_single(d,[add_path(\"lifpurge\"),lifimagefile, liffile])\n\n#\n# rename file dialog\n#\nclass cls_lifrename (QtWidgets.QDialog):\n\n def __init__(self,lifimagefile,filename,parent= None):\n super().__init__()\n self.lifimagefile=lifimagefile\n self.oldfilename=filename\n self.setWindowTitle(\"Rename File\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.lbl=QtWidgets.QLabel(\"Rename file:\")\n self.vlayout.addWidget(self.lbl)\n self.leditFileName=QtWidgets.QLineEdit(self)\n self.leditFileName.setText(filename)\n self.leditFileName.setMaxLength(10)\n self.leditFileName.textChanged.connect(self.do_checkenable)\n self.validator = cls_LIF_validator()\n self.leditFileName.setValidator(self.validator)\n self.vlayout.addWidget(self.leditFileName)\n\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.vlayout.addWidget(self.buttonBox)\n\n#\n# check, if the OK button can be enabled\n#\n def do_checkenable(self):\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n if (self.leditFileName.text() != \"\"):\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n return\n\n# \n# ok rename file\n#\n def do_ok(self):\n newfilename=self.leditFileName.text()\n if newfilename != \"\":\n exec_single(self,[add_path(\"lifrename\"),self.lifimagefile,self.oldfilename,newfilename])\n super().accept()\n\n#\n# cancel do nothing\n#\n def do_cancel(self):\n super().reject()\n\n @staticmethod\n def execute(lifimagefile,liffile):\n d=cls_lifrename(lifimagefile,liffile)\n result= d.exec()\n#\n# export file dialog\n#\nclass cls_lifexport (QtWidgets.QDialog):\n\n def __init__(self,lifimagefile,liffilename,liffiletype,workdir,parent= None):\n super().__init__()\n self.lifimagefile= lifimagefile\n self.liffiletype= liffiletype\n self.liffilename= liffilename\n self.workdir=workdir\n self.setWindowTitle(\"Export File\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.gBox0=QtWidgets.QGroupBox(\"File to be exported to file system\")\n self.lblLifFilename=QtWidgets.QLabel(self.liffilename+\" (type: \"+self.liffiletype+\")\")\n self.vbox0=QtWidgets.QVBoxLayout()\n self.vbox0.addWidget(self.lblLifFilename)\n self.vbox0.addStretch(1)\n self.gBox0.setLayout(self.vbox0)\n self.vlayout.addWidget(self.gBox0)\n \n self.gBox1=QtWidgets.QGroupBox(\"Postprocessing options\")\n self.radioLifAscii= QtWidgets.QRadioButton(\"convert LIF-Text to ASCII\")\n self.radioLifAscii.clicked.connect(self.do_radio)\n self.radioLifAscii.setEnabled(False)\n self.radioTxt75Ascii= QtWidgets.QRadioButton(\"convert HP-75 text file to ASCII, omit line numbers\")\n self.radioTxt75Ascii.clicked.connect(self.do_radio)\n self.radioTxt75Ascii.setEnabled(False)\n self.radioTxt75AsciiNumbers= QtWidgets.QRadioButton(\"convert HP-75 text file to ASCII, retain line numbers\")\n self.radioTxt75AsciiNumbers.clicked.connect(self.do_radio)\n self.radioTxt75AsciiNumbers.setEnabled(False)\n self.radioEramco= QtWidgets.QRadioButton(\"unpack Eramco MLDL-OS ROM file\")\n self.radioEramco.clicked.connect(self.do_radio)\n self.radioEramco.setEnabled(False)\n self.radioHepax= QtWidgets.QRadioButton(\"unpack HEPAX HP41 SDATA ROM file\")\n self.radioHepax.setEnabled(False)\n self.radioHepax.clicked.connect(self.do_radio)\n self.radioRaw= QtWidgets.QRadioButton(\"remove LIF header, create RAW file\")\n self.radioRaw.clicked.connect(self.do_radio)\n self.radioNone= QtWidgets.QRadioButton(\"None\")\n self.radioNone.clicked.connect(self.do_radio)\n\n if self.liffiletype== \"TEXT\":\n self.radioLifAscii.setEnabled(True)\n self.radioLifAscii.setChecked(True)\n self.outputextension=\".txt\"\n elif self.liffiletype== \"TXT75\":\n self.radioTxt75Ascii.setEnabled(True)\n self.radioTxt75Ascii.setChecked(True)\n self.radioTxt75AsciiNumbers.setEnabled(True)\n self.outputextension=\".txt\"\n elif self.liffiletype== \"X-M41\":\n self.radioEramco.setEnabled(True)\n self.radioEramco.setChecked(True)\n self.outputextension=\".rom\"\n elif self.liffiletype== \"SDATA\":\n self.radioNone.setChecked(True)\n self.radioHepax.setEnabled(True)\n self.outputextension=\".lif\"\n else:\n self.radioNone.setChecked(True)\n self.outputextension=\".lif\"\n\n self.vbox=QtWidgets.QVBoxLayout()\n self.vbox.addWidget(self.radioLifAscii)\n self.vbox.addWidget(self.radioTxt75Ascii)\n self.vbox.addWidget(self.radioTxt75AsciiNumbers)\n self.vbox.addWidget(self.radioEramco)\n self.vbox.addWidget(self.radioHepax)\n self.vbox.addWidget(self.radioRaw)\n self.vbox.addWidget(self.radioNone)\n self.vbox.addStretch(1)\n self.gBox1.setLayout(self.vbox)\n\n self.vlayout.addWidget(self.gBox1)\n\n self.gBox2=QtWidgets.QGroupBox(\"Output file\")\n self.hbox=QtWidgets.QHBoxLayout()\n self.outputfile=os.path.join(self.workdir, self.liffilename.lower()+self.outputextension)\n self.lblFilename=QtWidgets.QLabel(self.outputfile)\n self.hbox.addWidget(self.lblFilename)\n self.hbox.addStretch(1)\n self.butChange= QtWidgets.QPushButton(\"Change\")\n self.butChange.clicked.connect(self.do_filenameChanged)\n self.hbox.addWidget(self.butChange)\n self.gBox2.setLayout(self.hbox)\n\n self.vlayout.addWidget(self.gBox2)\n\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.vlayout.addWidget(self.buttonBox)\n#\n# Radio button clicked, adjust file type\n#\n def do_radio(self):\n if self.radioLifAscii.isChecked():\n self.outputextension=\".txt\"\n elif self.radioTxt75Ascii.isChecked():\n self.outputextension=\".txt\"\n elif self.radioTxt75AsciiNumbers.isChecked():\n self.outputextension=\".txt\"\n elif self.radioHepax.isChecked():\n self.outputextension=\".rom\"\n elif self.radioEramco.isChecked():\n self.outputextension=\".rom\"\n elif self.radioRaw.isChecked():\n self.outputextension=\".raw\"\n else:\n self.outputextension=\".lif\"\n self.outputfile=os.path.join(self.workdir, self.liffilename.lower()+self.outputextension)\n self.lblFilename.setText(self.outputfile)\n#\n# enter output file name dialog\n#\n def get_outputFilename(self):\n dialog=QtWidgets.QFileDialog()\n dialog.setWindowTitle(\"Select Output File\")\n dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)\n dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)\n dialog.setNameFilters( [\"All Files (*)\"] )\n dialog.selectFile(self.liffilename.lower()+self.outputextension)\n dialog.setOptions(QtWidgets.QFileDialog.DontUseNativeDialog)\n if dialog.exec():\n return dialog.selectedFiles()\n#\n# callback\n#\n#\n# change output file name\n#\n\n def do_filenameChanged(self):\n flist= self.get_outputFilename()\n if flist is None:\n return\n self.outputfile=flist[0]\n self.lblFilename.setText(self.outputfile)\n#\n# export\n#\n def do_ok(self):\n if self.outputfile != \"\":\n\n if self.radioLifAscii.isChecked():\n exec_double_export(self,[add_path(\"lifget\"),\"-r\",self.lifimagefile,self.liffilename],add_path(\"liftext\"),self.outputfile)\n elif self.radioTxt75Ascii.isChecked():\n exec_double_export(self,[add_path(\"lifget\"),\"-r\",self.lifimagefile,self.liffilename],add_path(\"liftext75\"),self.outputfile)\n elif self.radioTxt75AsciiNumbers.isChecked():\n exec_double_export(self,[add_path(\"lifget\"),\"-r\",self.lifimagefile,self.liffilename], [add_path(\"liftext75\"),\"-n\"],self.outputfile)\n elif self.radioEramco.isChecked():\n exec_double_export(self,[add_path(\"lifget\"),\"-r\",self.lifimagefile,self.liffilename],add_path(\"er41rom\"),self.outputfile)\n elif self.radioHepax.isChecked():\n exec_double_export(self,[add_path(\"lifget\"),\"-r\",self.lifimagefile,self.liffilename],add_path(\"hx41rom\"),self.outputfile)\n elif self.radioRaw.isChecked():\n exec_single(self,[add_path(\"lifget\"),\"-r\",self.lifimagefile,self.liffilename,self.outputfile])\n elif self.radioNone.isChecked():\n exec_single(self,[add_path(\"lifget\"),self.lifimagefile,self.liffilename,self.outputfile])\n super().accept()\n#\n# cancel: do nothing\n#\n def do_cancel(self):\n super().reject()\n\n @staticmethod\n def execute(lifimagefile,liffilename,liffiletype,workdir):\n d=cls_lifexport(lifimagefile,liffilename,liffiletype,workdir)\n result= d.exec()\n\n#\n# label lif image file dialog\n#\nclass cls_liflabel (QtWidgets.QDialog):\n\n def __init__(self,lifimagefile,oldlabel,parent= None):\n super().__init__()\n self.lifimagefile=lifimagefile\n self.setWindowTitle(\"Label LIF image file\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.lbl=QtWidgets.QLabel(\"Label:\")\n self.vlayout.addWidget(self.lbl)\n self.leditLabel=QtWidgets.QLineEdit(self)\n self.leditLabel.setText(oldlabel)\n self.leditLabel.setMaxLength(6)\n self.validator = cls_LIF_validator()\n self.leditLabel.setValidator(self.validator)\n self.vlayout.addWidget(self.leditLabel)\n\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.vlayout.addWidget(self.buttonBox)\n\n def do_ok(self):\n newlabel=self.leditLabel.text()\n if newlabel != \"\":\n exec_single(self,[add_path(\"liflabel\"),self.lifimagefile, newlabel])\n else:\n exec_single(self,[add_path(\"liflabel\"),\"-c\",self.lifimagefile])\n super().accept()\n\n def do_cancel(self):\n super().reject()\n\n @staticmethod\n def execute(lifimagefile,oldlabel):\n d=cls_liflabel(lifimagefile,oldlabel)\n result= d.exec()\n#\n# import file dialog\n#\nclass cls_lifimport (QtWidgets.QDialog):\n\n def __init__(self,lifimagefile,workdir,parent= None):\n super().__init__()\n self.inputfile=\"\"\n self.lifimagefile=lifimagefile\n self.workdir= workdir\n self.liffilename=\"\"\n\n self.setWindowTitle(\"Import File\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.gBox0=QtWidgets.QGroupBox(\"Input file\")\n self.hbox=QtWidgets.QHBoxLayout()\n self.lblFilename=QtWidgets.QLabel(self.inputfile)\n self.hbox.addWidget(self.lblFilename)\n self.hbox.addStretch(1)\n self.butChange= QtWidgets.QPushButton(\"Change\")\n self.butChange.clicked.connect(self.do_filenameChanged)\n self.hbox.addWidget(self.butChange)\n self.gBox0.setLayout(self.hbox)\n self.vlayout.addWidget(self.gBox0)\n\n self.gBox1=QtWidgets.QGroupBox(\"Preprocessing options\")\n self.bGroup=QtWidgets.QButtonGroup()\n self.radioLif41= QtWidgets.QRadioButton(\"convert from ASCII to LIF-Text (HP-41)\")\n self.radioLif71= QtWidgets.QRadioButton(\"convert from ASCII to LIF-Text (HP-71)\")\n self.radioTxt75= QtWidgets.QRadioButton(\"convert from ASCII to HP-75 text, create new line numbers\")\n self.radioTxt75Numbers= QtWidgets.QRadioButton(\"convert from ASCII to HP-75 text, take existing line numbers\")\n self.radioHepax= QtWidgets.QRadioButton(\"convert HP-41 rom file to SDATA file (HEPAX)\")\n self.radioEramco= QtWidgets.QRadioButton(\"convert HP-41 rom file to XM-41 file (Eramco MLDL-OS)\")\n self.radioFocal= QtWidgets.QRadioButton(\"add LIF header to HP41 FOCAL raw file\")\n self.radioNone= QtWidgets.QRadioButton(\"None\")\n self.radioNone.setChecked(True)\n self.bGroup.addButton(self.radioLif41) \n self.bGroup.addButton(self.radioLif71)\n self.bGroup.addButton(self.radioTxt75)\n self.bGroup.addButton(self.radioTxt75Numbers)\n self.bGroup.addButton(self.radioHepax)\n self.bGroup.addButton(self.radioEramco)\n self.bGroup.addButton(self.radioFocal)\n self.bGroup.addButton(self.radioNone)\n self.bGroup.buttonClicked.connect(self.do_butclicked)\n\n self.vbox=QtWidgets.QVBoxLayout()\n self.vbox.addWidget(self.radioLif41)\n self.vbox.addWidget(self.radioLif71)\n self.vbox.addWidget(self.radioTxt75)\n self.vbox.addWidget(self.radioTxt75Numbers)\n self.vbox.addWidget(self.radioHepax)\n self.vbox.addWidget(self.radioEramco)\n self.vbox.addWidget(self.radioFocal)\n\n self.hbox2=QtWidgets.QHBoxLayout()\n self.lbl=QtWidgets.QLabel(\"LIF Filename:\")\n self.hbox2.addWidget(self.lbl)\n self.leditFileName=QtWidgets.QLineEdit(self)\n self.leditFileName.setText(self.liffilename)\n self.leditFileName.setMaxLength(10)\n self.validator = cls_LIF_validator()\n self.leditFileName.setValidator(self.validator)\n self.leditFileName.setEnabled(False)\n self.leditFileName.textChanged.connect(self.do_checkenable)\n self.hbox2.addWidget(self.leditFileName)\n self.vbox.addLayout(self.hbox2)\n self.gBox1.setLayout(self.vbox)\n self.gBox1.setEnabled(False)\n self.vlayout.addWidget(self.gBox1)\n self.vbox.addWidget(self.radioNone)\n self.vbox.addStretch(1)\n\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.vlayout.addWidget(self.buttonBox)\n#\n# dialog to enter input file name\n#\n def get_inputFilename(self):\n dialog=QtWidgets.QFileDialog()\n dialog.setWindowTitle(\"Select Input File\")\n dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)\n dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)\n dialog.setNameFilters( [\"All Files (*)\"] )\n dialog.setOptions(QtWidgets.QFileDialog.DontUseNativeDialog)\n if dialog.exec():\n return dialog.selectedFiles()\n\n#\n# callbacks\n#\n\n#\n# change filename button\n#\n def do_filenameChanged(self):\n flist= self.get_inputFilename()\n if flist is None:\n return\n self.inputfile=flist[0]\n self.lblFilename.setText(self.inputfile)\n self.gBox1.setEnabled(True)\n self.do_checkenable()\n#\n# any radio button clicked, enable/disable lif filename entry, check ok button\n#\n def do_butclicked(self,id):\n if id== self.radioNone:\n self.leditFileName.setEnabled(False)\n else:\n self.leditFileName.setEnabled(True)\n self.do_checkenable()\n\n#\n# check, if the OK button can be enabled\n#\n def do_checkenable(self):\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n if self.radioNone.isChecked():\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n else:\n if self.leditFileName.text() != \"\":\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n return\n\n#\n# OK button callback import file\n#\n def do_ok(self):\n if self.inputfile != \"\":\n if self.radioNone.isChecked():\n if cls_chk_import.execute(None, self.inputfile):\n exec_single(self,[add_path(\"lifput\"),self.lifimagefile,self.inputfile])\n else:\n self.liffilename=self.leditFileName.text()\n if self.radioLif41.isChecked():\n exec_double_import(self,[add_path(\"textlif\"),\"-r 0\",self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n elif self.radioLif71.isChecked():\n exec_double_import(self,[add_path(\"textlif\"),self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n elif self.radioTxt75.isChecked():\n exec_double_import(self,[add_path(\"textlif75\"),self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n elif self.radioTxt75Numbers.isChecked():\n exec_double_import(self,[add_path(\"textlif75\"),\"-n\",self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n elif self.radioHepax.isChecked():\n exec_double_import(self,[add_path(\"rom41hx\"),self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n elif self.radioEramco.isChecked():\n exec_double_import(self,[add_path(\"rom41er\"),self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n elif self.radioFocal.isChecked():\n exec_double_import(self,[add_path(\"raw41lif\"),self.liffilename],[add_path(\"lifput\"),self.lifimagefile],self.inputfile)\n super().accept()\n\n#\n# cancel\n#\n def do_cancel(self):\n super().reject()\n\n @staticmethod\n def execute(lifimagefile,workdir):\n d=cls_lifimport(lifimagefile,workdir)\n result= d.exec()\n#\n# check import dialog, ensure that we import a valid LIF transport file\n#\nclass cls_chk_import(QtWidgets.QDialog):\n def __init__(self,fd,inputfile,parent=None):\n super().__init__()\n self.filename=\"\"\n self.ftype_num=0\n self.blocks=0\n self.retval=False\n self.setWindowTitle(\"Import File to LIF Image file\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n self.vlayout.addWidget(QtWidgets.QLabel(\"Import this file?\"))\n self.grid=QtWidgets.QGridLayout()\n self.grid.addWidget(QtWidgets.QLabel(\"Filename:\"),0,0)\n self.grid.addWidget(QtWidgets.QLabel(\"Filetype:\"),1,0)\n self.grid.addWidget(QtWidgets.QLabel(\"Filesize (Blocks):\"),2,0)\n self.lblFilename=QtWidgets.QLabel(\"\")\n self.grid.addWidget(self.lblFilename,0,1)\n self.lblFiletype=QtWidgets.QLabel(\"\")\n self.grid.addWidget(self.lblFiletype,1,1)\n self.lblFilesize=QtWidgets.QLabel(\"\")\n self.grid.addWidget(self.lblFilesize,2,1)\n\n self.vlayout.addLayout(self.grid)\n self.lblMessage=QtWidgets.QLabel(\"\")\n self.vlayout.addWidget(self.lblMessage)\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.vlayout.addWidget(self.buttonBox)\n#\n# examine header information, if inputfile is None then we have a file descriptor\n#\n try:\n if inputfile is not None:\n if isWINDOWS():\n fd= os.open(inputfile, os.O_RDONLY | os.O_BINARY )\n else:\n fd= os.open(inputfile, os.O_RDONLY)\n b=os.read(fd,32)\n if len(b) <32:\n self.lblMessage.setText(\"File is too short\")\n else:\n self.filename=getLifString(b,0,10)\n self.ftype_num=getLifInt(b,10,2)\n self.blocks=getLifInt(b,16,4)\n self.filetype=get_finfo_type(self.ftype_num)\n if self.filetype is None:\n self.filetype=\"Unknown\"\n else:\n self.filetype= self.filetype[0]\n self.lblFilename.setText(self.filename)\n self.lblFiletype.setText(self.filetype)\n self.lblFilesize.setText(str(self.blocks))\n if inputfile is not None:\n os.close(fd)\n#\n# Check valid header\n#\n if self.blocks < 1:\n self.lblMessage.setText(\"Illegal file length\")\n return\n if self.filetype==\"Unknown\":\n self.lblMessage.setText(\"Unknown file type\")\n return\n self.regexp = QtCore.QRegularExpression('[A-Z][A-Z0-9]*')\n self.validator = QtGui.QRegularExpressionValidator(self.regexp)\n result=self.validator.validate(self.filename,0)[0]\n if result != QtGui.QValidator.Acceptable:\n self.lblMessage.setText(\"Illegal file name\")\n return\n self.lblMessage.setText(\"Ready to import\")\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n \n except OSError as e:\n self.lblMessage.setText(\"Error while examining file\")\n\n def do_ok(self):\n self.retval=True\n super().accept()\n\n def do_cancel(self):\n super().reject()\n\n def get_retval(self):\n return self.retval\n\n\n @staticmethod\n def execute(fd,inputfile):\n d=cls_chk_import(fd,inputfile)\n result= d.exec()\n return d.get_retval()\n#\n# check xroms dialog\n#\nclass cls_chkxrom(QtWidgets.QDialog):\n\n def __init__(self,parent=None):\n super().__init__()\n self.call=[add_path(\"decomp41\")]\n\n self.setWindowTitle(\"Check ROM Modules\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.cardrdr= QtWidgets.QCheckBox(\"Card Reader\")\n self.vlayout.addWidget(self.cardrdr)\n self.printer= QtWidgets.QCheckBox(\"Printer\")\n self.vlayout.addWidget(self.printer)\n self.wand= QtWidgets.QCheckBox(\"Wand\")\n self.vlayout.addWidget(self.wand)\n self.hpil= QtWidgets.QCheckBox(\"HP-IL\")\n self.vlayout.addWidget(self.hpil)\n self.hpil.setChecked(True)\n self.xfunc= QtWidgets.QCheckBox(\"X-Function\")\n self.vlayout.addWidget(self.xfunc)\n self.xfunc.setChecked(True)\n self.time= QtWidgets.QCheckBox(\"Time\")\n self.vlayout.addWidget(self.time)\n self.hepax= QtWidgets.QCheckBox(\"HEPAX\")\n self.vlayout.addWidget(self.hepax)\n self.xio= QtWidgets.QCheckBox(\"Extended IO\")\n self.vlayout.addWidget(self.xio)\n self.devil= QtWidgets.QCheckBox(\"HP-IL Devel\")\n self.vlayout.addWidget(self.devil)\n self.plotter= QtWidgets.QCheckBox(\"Plotter\")\n self.vlayout.addWidget(self.plotter)\n\n self.exitButton= QtWidgets.QPushButton(\"Exit\")\n self.exitButton.setFixedWidth(60)\n self.exitButton.clicked.connect(self.do_exit)\n self.hlayout= QtWidgets.QHBoxLayout()\n self.hlayout.addWidget(self.exitButton)\n self.vlayout.addLayout(self.hlayout)\n#\n# exit, return the parameters of the selected modules\n#\n def do_exit(self):\n if self.cardrdr.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"cardrdr\")\n if self.printer.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"printer\")\n if self.wand.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"wand\")\n if self.hpil.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"hpil\")\n if self.xfunc.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"xfn\")\n if self.time.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"time\")\n if self.hepax.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"hepax\")\n if self.xio.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"xio\")\n if self.devil.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"devil\")\n if self.plotter.isChecked():\n self.call.append(\"-x\")\n self.call.append(\"plotter\")\n super().accept()\n\n def get_call(self):\n return self.call\n\n @staticmethod\n def execute():\n d=cls_chkxrom()\n result= d.exec()\n return d.get_call()\n#\n# view file dialog\n#\nclass cls_lifview(QtWidgets.QDialog):\n\n def __init__(self,workdir,parent= None):\n super().__init__()\n self.workdir=workdir\n self.outputfile=\"\"\n\n self.setWindowTitle(\"View File\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.viewer=QtWidgets.QTextEdit()\n self.viewer.setMinimumWidth(600)\n self.viewer.setMinimumHeight(600)\n self.viewer.setReadOnly(True)\n self.font=QtGui.QFont(FONT)\n self.font.setPixelSize(12)\n self.viewer.setFont(self.font)\n\n self.vlayout.addWidget(self.viewer)\n self.saveButton= QtWidgets.QPushButton(\"Save\")\n self.saveButton.setFixedWidth(60)\n self.saveButton.clicked.connect(self.do_save)\n self.exitButton= QtWidgets.QPushButton(\"Exit\")\n self.exitButton.setFixedWidth(60)\n self.exitButton.clicked.connect(self.do_exit)\n self.hlayout= QtWidgets.QHBoxLayout()\n self.hlayout.addWidget(self.saveButton)\n self.hlayout.addWidget(self.exitButton)\n self.vlayout.addLayout(self.hlayout)\n\n def set_text(self,output):\n self.viewer.setText(output)\n return\n#\n# enter output file name dialog\n#\n def get_outputFilename(self):\n dialog=QtWidgets.QFileDialog()\n dialog.setWindowTitle(\"Select Output File\")\n dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)\n dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)\n dialog.setNameFilters( [\"All Files (*)\"] )\n dialog.setOptions(QtWidgets.QFileDialog.DontUseNativeDialog)\n if dialog.exec():\n return dialog.selectedFiles()\n#\n# save content to file\n#\n def do_save(self):\n flist= self.get_outputFilename()\n if flist is None:\n return\n outputfile=flist[0]\n if os.access(self.outputfile,os.W_OK):\n reply=QtWidgets.QMessageBox.warning(self,'Warning',\"Do you really want to overwrite file \"+self.outputfile,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Cancel)\n if reply== QtWidgets.QMessageBox.Cancel:\n return\n try:\n if isWINDOWS() and PILCONFIG.get(\"pyilper\",\"usebom\"):\n outfile=open(outputfile,\"a\",encoding=\"UTF-8-SIG\")\n else:\n outfile=open(outputfile,\"a\",encoding=\"UTF-8\")\n\n outfile.write(str(self.viewer.toPlainText()))\n outfile.close()\n except OSError as e:\n reply=QtWidgets.QMessageBox.critical(self,'Error',\"Cannot write to file: \"+ e.strerror,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)\n return\n\n#\n# exit, do nothing\n#\n def do_exit(self):\n super().accept()\n\n#\n# get file and pipe it to filter program, show output in editor window\n#\n @staticmethod\n def execute(lifimagefile, liffilename, liffiletype,workdir,charset):\n d=cls_lifview(workdir)\n ft=get_finfo_name(liffiletype)\n call= get_finfo_type(ft)[1]\n#\n# decomp41 needs additional parameters (xmoms)\n#\n if call == \"decomp41\":\n call= cls_chkxrom.execute()\n#\n# liftext75 has the option to show line numbers\n#\n elif call == \"liftext75\":\n call= add_path(call)\n reply=QtWidgets.QMessageBox.question(None,'',\"Show line numbers?\",QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.No)\n if reply== QtWidgets.QMessageBox.Yes:\n call= [ add_path(call), \"-n\"]\n#\n# all other lifutil progs\n#\n else:\n call= add_path(call)\n output=exec_double_export(d,[add_path(\"lifget\"),\"-r\",lifimagefile,liffilename],call,\"\")\n#\n# convert and show the file content\n#\n if output is None:\n return\n d.set_text(barrconv(output,charset))\n result= d.exec()\n#\n# Init LIF image file dialog\n# \nclass cls_lifinit (QtWidgets.QDialog):\n\n def __init__(self,workdir,parent= None):\n super().__init__()\n self.lifimagefile=\"\"\n self.workdir= workdir\n self.mt=\"hdrive1\"\n\n self.setWindowTitle(\"Initialize LIF Image File\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.gBox0=QtWidgets.QGroupBox(\"LIF image file\")\n self.hbox=QtWidgets.QHBoxLayout()\n self.lblFilename=QtWidgets.QLabel(self.lifimagefile)\n self.hbox.addWidget(self.lblFilename)\n self.hbox.addStretch(1)\n self.butChange= QtWidgets.QPushButton(\"Change\")\n self.butChange.clicked.connect(self.do_filenameChanged)\n self.hbox.addWidget(self.butChange)\n\n self.gBox0.setLayout(self.hbox)\n self.vlayout.addWidget(self.gBox0)\n\n self.gBox1=QtWidgets.QGroupBox(\"Medium type\")\n self.bGroup=QtWidgets.QButtonGroup()\n self.radio1= QtWidgets.QRadioButton(\"HP 82161A cassette\")\n self.radio2= QtWidgets.QRadioButton(\"HP 9114B double sided disk \")\n self.radio3= QtWidgets.QRadioButton(\"HDRIVE1 640 KB\")\n self.radio4= QtWidgets.QRadioButton(\"HDRIVE1 2 MB\")\n self.radio5= QtWidgets.QRadioButton(\"HDRIVE1 4 MB\")\n self.radio6= QtWidgets.QRadioButton(\"HDRIVE1 8 MB\")\n self.radio7= QtWidgets.QRadioButton(\"HDRIVE1 16 MB\")\n self.radio3.setChecked(True)\n self.bGroup.addButton(self.radio1) \n self.bGroup.addButton(self.radio2)\n self.bGroup.addButton(self.radio3)\n self.bGroup.addButton(self.radio4)\n self.bGroup.addButton(self.radio5)\n self.bGroup.addButton(self.radio6)\n self.bGroup.addButton(self.radio7)\n self.bGroup.buttonClicked.connect(self.do_butclicked)\n\n self.vbox=QtWidgets.QVBoxLayout()\n self.vbox.addWidget(self.radio1)\n self.vbox.addWidget(self.radio2)\n self.vbox.addWidget(self.radio3)\n self.vbox.addWidget(self.radio4)\n self.vbox.addWidget(self.radio5)\n self.vbox.addWidget(self.radio6)\n self.vbox.addWidget(self.radio7)\n\n self.hbox1=QtWidgets.QHBoxLayout()\n self.lbl1=QtWidgets.QLabel(\"Directory size:\")\n self.hbox1.addWidget(self.lbl1)\n self.leditDirSize=QtWidgets.QLineEdit(self)\n self.leditDirSize.setText(\"500\")\n self.leditDirSize.setMaxLength(4)\n self.regexpDirSize = QtCore.QRegularExpression('[1-9][0-9]*')\n self.validatorDirSize = QtGui.QRegularExpressionValidator(self.regexpDirSize)\n self.leditDirSize.setValidator(self.validatorDirSize)\n self.leditDirSize.textChanged.connect(self.do_checkenable)\n self.hbox1.addWidget(self.leditDirSize)\n self.vbox.addLayout(self.hbox1)\n\n self.hbox2=QtWidgets.QHBoxLayout()\n self.lbl2=QtWidgets.QLabel(\"LIF Label:\")\n self.hbox2.addWidget(self.lbl2)\n self.leditLabel=QtWidgets.QLineEdit(self)\n self.leditLabel.setText(\"\")\n self.leditLabel.setMaxLength(6)\n self.validatorLabel = cls_LIF_validator()\n self.leditLabel.setValidator(self.validatorLabel)\n self.hbox2.addWidget(self.leditLabel)\n self.vbox.addLayout(self.hbox2)\n\n self.gBox1.setLayout(self.vbox)\n self.gBox1.setEnabled(False)\n self.vlayout.addWidget(self.gBox1)\n self.vbox.addStretch(1)\n\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.vlayout.addWidget(self.buttonBox)\n#\n# dialog to enter input file name\n#\n def get_inputFilename(self):\n dialog=QtWidgets.QFileDialog()\n dialog.setWindowTitle(\"Select LIF Image File\")\n dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)\n dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)\n dialog.setNameFilters( [\"All Files (*)\"] )\n dialog.setOptions(QtWidgets.QFileDialog.DontUseNativeDialog)\n if dialog.exec():\n return dialog.selectedFiles()\n#\n# callbacks\n#\n\n#\n# change filename button\n#\n def do_filenameChanged(self):\n flist= self.get_inputFilename()\n if flist is None:\n return\n self.lifimagefile=flist[0]\n self.lblFilename.setText(self.lifimagefile)\n self.gBox1.setEnabled(True)\n self.do_checkenable()\n#\n# radio button clicked, set default directory size\n#\n def do_butclicked(self):\n\n if self.radio1.isChecked():\n self.leditDirSize.setText(\"150\")\n self.mt=\"cass\"\n if self.radio2.isChecked():\n self.leditDirSize.setText(\"500\")\n self.mt=\"disk\"\n if self.radio3.isChecked():\n self.leditDirSize.setText(\"500\")\n self.mt=\"hdrive1\"\n if self.radio4.isChecked():\n self.leditDirSize.setText(\"1000\")\n self.mt=\"hdrive2\"\n if self.radio5.isChecked():\n self.leditDirSize.setText(\"2000\")\n self.mt=\"hdrive4\"\n if self.radio6.isChecked():\n self.leditDirSize.setText(\"2000\")\n self.mt=\"hdrive8\"\n if self.radio7.isChecked():\n self.leditDirSize.setText(\"2000\")\n self.mt=\"hdrive16\"\n self.do_checkenable()\n#\n# check, if the OK button can be enabled\n#\n def do_checkenable(self):\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n if (self.leditDirSize.text() != \"\" and self.lifimagefile != \"\"):\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n return\n\n#\n# OK button, initialize file\n#\n def do_ok(self):\n if self.lifimagefile != \"\":\n if os.access(self.lifimagefile,os.W_OK):\n reply=QtWidgets.QMessageBox.warning(self,'Warning',\"Do you really want to overwrite file \"+self.lifimagefile,QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Cancel)\n if reply== QtWidgets.QMessageBox.Cancel:\n return\n exec_single(self,[add_path(\"lifinit\"),\"-m\",self.mt,self.lifimagefile,self.leditDirSize.text()])\n if self.leditLabel.text() != \"\":\n exec_single(self,[add_path(\"liflabel\"),self.lifimagefile,self.leditLabel.text()])\n super().accept()\n\n#\n# cancel\n#\n def do_cancel(self):\n super().reject()\n\n @staticmethod\n def execute(workdir):\n d=cls_lifinit(workdir)\n result= d.exec()\n#\n# fix LIF header dialog\n#\nclass cls_liffix (QtWidgets.QDialog):\n\n def __init__(self,workdir,parent= None):\n super().__init__()\n self.lifimagefile=\"\"\n self.workdir= workdir\n self.mt=\"hdrive1\"\n\n self.setWindowTitle(\"Fix header of LIF Image File\")\n self.vlayout= QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n\n self.gBox0=QtWidgets.QGroupBox(\"LIF image file\")\n self.hbox=QtWidgets.QHBoxLayout()\n self.lblFilename=QtWidgets.QLabel(self.lifimagefile)\n self.hbox.addWidget(self.lblFilename)\n self.hbox.addStretch(1)\n self.butChange= QtWidgets.QPushButton(\"Change\")\n self.butChange.clicked.connect(self.do_filenameChanged)\n self.hbox.addWidget(self.butChange)\n\n self.gBox0.setLayout(self.hbox)\n self.vlayout.addWidget(self.gBox0)\n\n self.gBox1=QtWidgets.QGroupBox(\"Medium type\")\n self.bGroup=QtWidgets.QButtonGroup()\n self.radio1= QtWidgets.QRadioButton(\"HP 82161A cassette\")\n self.radio2= QtWidgets.QRadioButton(\"HP 9114B double sided disk \")\n self.radio3= QtWidgets.QRadioButton(\"HDRIVE1 640 KB\")\n self.radio4= QtWidgets.QRadioButton(\"HDRIVE1 2 MB\")\n self.radio5= QtWidgets.QRadioButton(\"HDRIVE1 4 MB\")\n self.radio6= QtWidgets.QRadioButton(\"HDRIVE1 8 MB\")\n self.radio7= QtWidgets.QRadioButton(\"HDRIVE1 16 MB\")\n self.radio3.setChecked(True)\n self.bGroup.addButton(self.radio1) \n self.bGroup.addButton(self.radio2)\n self.bGroup.addButton(self.radio3)\n self.bGroup.addButton(self.radio4)\n self.bGroup.addButton(self.radio5)\n self.bGroup.addButton(self.radio6)\n self.bGroup.addButton(self.radio7)\n self.bGroup.buttonClicked.connect(self.do_butclicked)\n\n self.vbox=QtWidgets.QVBoxLayout()\n self.vbox.addWidget(self.radio1)\n self.vbox.addWidget(self.radio2)\n self.vbox.addWidget(self.radio3)\n self.vbox.addWidget(self.radio4)\n self.vbox.addWidget(self.radio5)\n self.vbox.addWidget(self.radio6)\n self.vbox.addWidget(self.radio7)\n\n self.vbox.addStretch(1)\n self.vlayout.addLayout(self.vbox)\n\n self.buttonBox = QtWidgets.QDialogButtonBox(self)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\n self.buttonBox.setCenterButtons(True)\n self.buttonBox.accepted.connect(self.do_ok)\n self.buttonBox.rejected.connect(self.do_cancel)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.vlayout.addWidget(self.buttonBox)\n#\n# dialog to enter input file name\n#\n def get_inputFilename(self):\n dialog=QtWidgets.QFileDialog()\n dialog.setWindowTitle(\"Select LIF Image File\")\n dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen)\n dialog.setFileMode(QtWidgets.QFileDialog.ExistingFile)\n dialog.setNameFilters( [\"All Files (*)\"] )\n dialog.setOptions(QtWidgets.QFileDialog.DontUseNativeDialog)\n if dialog.exec():\n return dialog.selectedFiles()\n#\n# callbacks\n#\n\n#\n# change filename button\n#\n def do_filenameChanged(self):\n flist= self.get_inputFilename()\n if flist is None:\n return\n self.lifimagefile=flist[0]\n self.lblFilename.setText(self.lifimagefile)\n self.gBox1.setEnabled(True)\n self.do_checkenable()\n#\n# radio button clicked, set default directory size\n#\n def do_butclicked(self):\n\n if self.radio1.isChecked():\n self.mt=\"cass\"\n if self.radio2.isChecked():\n self.mt=\"disk\"\n if self.radio3.isChecked():\n self.mt=\"hdrive1\"\n if self.radio4.isChecked():\n self.mt=\"hdrive2\"\n if self.radio5.isChecked():\n self.mt=\"hdrive4\"\n if self.radio6.isChecked():\n self.mt=\"hdrive8\"\n if self.radio7.isChecked():\n self.mt=\"hdrive16\"\n self.do_checkenable()\n#\n# check, if the OK button can be enabled\n#\n def do_checkenable(self):\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n if self.lifimagefile != \"\":\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n return\n\n#\n# OK button, initialize file\n#\n def do_ok(self):\n if self.lifimagefile != \"\":\n exec_single(self,[add_path(\"liffix\"),\"-m\",self.mt,self.lifimagefile])\n super().accept()\n#\n# cancel\n#\n def do_cancel(self):\n super().reject()\n\n @staticmethod\n def execute(workdir):\n d=cls_liffix(workdir)\n result= d.exec()\n#\n# Check installation of LIFUTILS dialog\n#\nclass cls_installcheck(QtWidgets.QDialog):\n\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Status of LIFUTILS installation')\n self.vlayout = QtWidgets.QVBoxLayout()\n self.setLayout(self.vlayout)\n self.view = QtWidgets.QLabel()\n self.view.setFixedWidth(500)\n self.view.setWordWrap(True)\n self.button = QtWidgets.QPushButton('OK')\n self.button.setFixedWidth(60)\n self.button.clicked.connect(self.do_exit)\n self.vlayout.addWidget(self.view)\n self.hlayout = QtWidgets.QHBoxLayout()\n self.hlayout.addWidget(self.button)\n self.vlayout.addLayout(self.hlayout)\n required_version_installed, installed_version= check_lifutils()\n\n text=\"This version of pyILPER requires at least version \"+decode_version(LIFUTILS_REQUIRED_VERSION)+\" of the LIFUTILS installed.\"\n\n if required_version_installed:\n text+=\" Version \"+decode_version(installed_version)+\" was found on this system. File management controls are enabled.\"\n else:\n if installed_version !=0:\n text+=\" Version \"+decode_version(installed_version)+\" was found of this system. Please upgrade to the latest version of LIFUTILS and restart pyILPER.\"\n else:\n text+=\" No version of LIFUTILS was found on this system or the installed version is too old to report a version number. Please install the latest version of LIFUTILS and restart pyILPER.\"\n text+=\" File management controls are disabled.\"\n self.view.setText(text)\n\n def do_exit(self):\n super().accept()\n\n @staticmethod\n def execute():\n d=cls_installcheck()\n result= d.exec()\n","repo_name":"bug400/pyilper","sub_path":"pyilper/lifexec.py","file_name":"lifexec.py","file_ext":"py","file_size_in_byte":58080,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"52"} +{"seq_id":"26624459122","text":"from modules.DataAndVisualization.vizualiser import (\n plot_scatter as scatter,\n plot_parallel as parallel,\n)\nfrom modules.utils import load\n# Visualizing the two bar truss problem\n\n# You can use the parallel plot with any dimension but the scatter will only work with 2 and 3 dimension.\n\n# objectives as a reminder:\n# weight, stress, buckling stress and deflection\n\n# First load the solution. For more details on on the solution check the readme file in modules/DataAndVisualization\nobj, var, nadir, ideal = load(\"tb4\")\n\n# This problem is 3 dimensional as it is only optimizing weight, stress and buckling stress\n# so we can use a scatter or a parallel plot to visualize it. We will use a scatter plot\n\n# Set the axis names accordingly\naxis_names = [\"weight\", \"Stress\", \"buckling stress\"]\n\n# (3D) Scatter plot\nscatter(obj, axis_names)\n\n\n# An example on parallel plots\n\n# Parallel plot will open a new browser window and display the plot there. \n# Only 1000 random samples are chosen for the plot\n# You can choose an axis ranges to highlight solutions that fall in those ranges interactively\n\n# Load the problem\nobj2, var2, nadir2, ideal2 = load(\"tb1\")\n\n# Set axis names\naxis_names = [\"weight\", \"stress\", \"buckling stress\", \"deflection\"]\n\n# Set dimensions for each axis, rows should match objectives.\n# (This will filter objectives with values that break the dimensions thus they wont be shown on the plot. None will be converted to -/+ np.inf)\ndimensions = [\n [10,None],\n [0,5],\n [None,None],\n [0,1]\n]\n\n# Plot\nparallel(obj2, axis_names, dimensions)","repo_name":"phoopies/DesignOptimizationCourse","sub_path":"visualizeTwoBarTruss.py","file_name":"visualizeTwoBarTruss.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42925474533","text":"import numpy as np\r\n\r\nclass Connect4(object):\r\n def __init__(self, player_x, player_o):\r\n self.row_size = 5\r\n self.column_size = 6\r\n self.window_length = 4\r\n\r\n self.player_x, self.player_o = player_x, player_o\r\n\r\n self.PLAYER_PIECE = 1\r\n self.OPPONENT_PIECE = -1\r\n self.EMPTY = 0\r\n\r\n self.player_x_turn = True\r\n\r\n self.board = self.create_board()\r\n\r\n def create_board(self):\r\n board = np.zeros((self.row_size, self.column_size))\r\n return board\r\n\r\n def set_move(self, row, col, piece):\r\n self.board[row][col] = piece\r\n\r\n def is_valid_location(self, col):\r\n return self.board[self.row_size - 1][col] == 0\r\n\r\n def get_available_row(self, col):\r\n # return first available row\r\n for r in range(self.row_size):\r\n if self.board[r][col] == 0:\r\n return r\r\n\r\n def draw_board(self):\r\n print(np.flip(self.board, 0))\r\n\r\n def player_wins(self, piece):\r\n # Check vertical\r\n for c in range(self.column_size):\r\n for r in range(self.row_size - 3):\r\n if self.board[r][c] == piece and self.board[r + 1][c] == piece and self.board[r + 2][c] == piece and \\\r\n self.board[r + 3][c] == piece:\r\n return True\r\n\r\n # Check positively sloped\r\n for c in range(self.column_size - 3):\r\n for r in range(self.row_size - 3):\r\n if self.board[r][c] == piece and self.board[r + 1][c + 1] == piece and \\\r\n self.board[r + 2][c + 2] == piece and self.board[r + 3][c + 3] == piece:\r\n return True\r\n\r\n # Check negatively sloped\r\n for c in range(self.column_size - 3):\r\n for r in range(3, self.row_size):\r\n if self.board[r][c] == piece and self.board[r - 1][c + 1] == piece and \\\r\n self.board[r - 2][c + 2] == piece and self.board[r - 3][c + 3] == piece:\r\n return True\r\n\r\n # Check horizontal locations for win\r\n for c in range(self.column_size - 3):\r\n for r in range(self.row_size):\r\n if self.board[r][c] == piece and self.board[r][c + 1] == piece and self.board[r][c + 2] == piece and \\\r\n self.board[r][c + 3] == piece:\r\n return True\r\n\r\n def is_terminal_node(self):\r\n return self.player_wins(self.PLAYER_PIECE) or self.player_wins(self.OPPONENT_PIECE) or len(\r\n self.get_valid_locations()) == 0\r\n\r\n def get_valid_locations(self):\r\n valid_locations = []\r\n for col in range(self.column_size):\r\n if self.is_valid_location(col):\r\n valid_locations.append(col)\r\n return valid_locations\r\n\r\n def play_game(self, train=True):\r\n if not train:\r\n print('\\nNew game!')\r\n print('Play 1: X, Player 2: O')\r\n\r\n while True:\r\n if self.player_x_turn:\r\n player, piece, other_player = self.player_x, self.PLAYER_PIECE, self.player_o\r\n else:\r\n player, piece, other_player = self.player_o, self.OPPONENT_PIECE, self.player_x\r\n\r\n move = player.move(self.board)\r\n self.set_move(move[0], move[1], piece)\r\n\r\n if self.player_wins(piece):\r\n player.reward(1, self.board)\r\n other_player.reward(-1, self.board)\r\n if piece == self.PLAYER_PIECE:\r\n if not train:\r\n print(\"X wins!\")\r\n return 1\r\n elif piece == self.OPPONENT_PIECE:\r\n if not train:\r\n print(\"O wins!\")\r\n return -1\r\n\r\n if len(self.get_valid_locations()) == 0:\r\n player.reward(0.5, self.board)\r\n other_player.reward(0.5, self.board)\r\n if not train:\r\n print('Draw!')\r\n return 0\r\n\r\n self.player_x_turn = not self.player_x_turn","repo_name":"Pookii/Coursework","sub_path":"CS7IS2-202223_AI/Assignment2/connect4/game/Connect4.py","file_name":"Connect4.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19648266925","text":"import socket\r\nimport time\r\nfrom colorama import init, Fore, Style\r\nfrom datetime import datetime\r\n\r\n\r\ndef print_green(text):\r\n print(Fore.GREEN + text + Style.RESET_ALL)\r\n\r\n\r\ndef print_red(text):\r\n print(Fore.RED + text + Style.RESET_ALL)\r\n\r\n\r\ninit()\r\n\r\ntarget_ip = input(\"Enter target IP address: \")\r\nport = int(input(\"Enter port number: \"))\r\n\r\nprint(f\"Testing connection to {target_ip}:{port} >> v24\")\r\n\r\nwhile True:\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n sock.settimeout(2)\r\n\r\n try:\r\n sock.connect((target_ip, port))\r\n timestamp = datetime.now().strftime(\"%H:%M:%S\")\r\n print_green(f\"{timestamp} - The port {port} is open on {target_ip}.>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\r\n except (socket.timeout, ConnectionRefusedError):\r\n timestamp = datetime.now().strftime(\"%H:%M:%S\")\r\n print_red(f\"{timestamp} - The port {port} is closed on {target_ip}.\")\r\n finally:\r\n sock.close()\r\n\r\n time.sleep(1)\r\n","repo_name":"vega0024/portchecker","sub_path":"portchecker.py","file_name":"portchecker.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71603584484","text":"from question_model import Question\nfrom data import question_data\nfrom quiz_brain import QuizBrain\n\nquestion_bank = []\n\nfor index in question_data:\n data_text = index[\"text\"]\n data_answer = index[\"answer\"]\n new_question = Question(data_text, data_answer)\n question_bank.append(new_question)\n\nquiz = QuizBrain(question_bank)\n\nwhile quiz.still_has_questions():\n quiz.next_question()\n\nprint(\"You have completed the Quiz !\")\nprint(f\"Your final score is: {quiz.score}/{quiz.question_number}\\n\")\n","repo_name":"calebeandrade93/100_Days_Python_Projects","sub_path":"Quizz OOP/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39732826431","text":"import socket \nimport sys \n\n\nlocal_port = 8282 \nsrv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \nsrv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) \nsrv.bind( ('', local_port) ) \nsrv.listen(1) \nprint (\"Listening on port: %s \" %local_port) \nwhile True: \n try: \n connection, addr = srv.accept() \n print ('Connected by %s:%s'\n % (addr[0], addr[1])) \n except KeyboardInterrupt: \n break \n except socket.error as msg: \n print ('%s' % (msg,)) \n ","repo_name":"kulukamal/Lab","sub_path":"SPLab/addrReUse.py","file_name":"addrReUse.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33935395098","text":"import time, random\nimport utility\n\n\nclass Solver:\n \"\"\"\n This class can solve every Sudoku puzzle. The problem is a classic Constraints Satisfaction Problem (CSP).\n To model this problem, we have the following notations:\n Rows are represented as: 'ABCDEFGHI'\n Cols are represented as: '123456789'\n Each square of the 81 squares can be represented as a combination of row number of column number, e.g., 'A1'\n The value of each square can be a number from 1 to 9, or 0 for unsolved square.\n\n A1 A2 A3| A4 A5 A6| A7 A8 A9 4 0 0 |0 0 0 |8 0 5 4 1 7 |3 6 9 |8 2 5\n B1 B2 B3| B4 B5 B6| B7 B8 B9 0 3 0 |0 0 0 |0 0 0 6 3 2 |1 5 8 |9 4 7\n C1 C2 C3| C4 C5 C6| C7 C8 C9 0 0 0 |7 0 0 |0 0 0 9 5 8 |7 2 4 |3 1 6\n ---------+---------+--------- ------+------+------ ------+------+------\n D1 D2 D3| D4 D5 D6| D7 D8 D9 0 2 0 |0 0 0 |0 6 0 8 2 5 |4 3 7 |1 6 9\n E1 E2 E3| E4 E5 E6| E7 E8 E9 0 0 0 |0 8 0 |4 0 0 7 9 1 |5 8 6 |4 3 2\n F1 F2 F3| F4 F5 F6| F7 F8 F9 0 0 0 |0 1 0 |0 0 0 3 4 6 |9 1 2 |7 5 8\n ---------+---------+--------- ------+------+------ ------+------+------\n G1 G2 G3| G4 G5 G6| G7 G8 G9 0 0 0 |6 0 3 |0 7 0 2 8 9 |6 4 3 |5 7 1\n H1 H2 H3| H4 H5 H6| H7 H8 H9 5 0 0 |2 0 0 |0 0 0 5 7 3 |2 9 1 |6 8 4\n I1 I2 I3| I4 I5 I6| I7 I8 I9 1 0 4 |0 0 0 |0 0 0 1 6 4 |8 7 5 |2 9 3\n\n Each square has exactly 3 units, which are the row collection, the column collection and the box of the same square.\n The peers of a square are the elements that share the same units with the square.\n E.g. 'C2' has the following units and peers:\n\n A2 | | | | A1 A2 A3| |\n B2 | | | | B1 B2 B3| |\n C2 | | C1 C2 C3| C4 C5 C6| C7 C8 C9 C1 C2 C3| |\n ---------+---------+--------- ---------+---------+--------- ---------+---------+---------\n D2 | | | | | |\n E2 | | | | | |\n F2 | | | | | |\n ---------+---------+--------- ---------+---------+--------- ---------+---------+---------\n G2 | | | | | |\n H2 | | | | | |\n I2 | | | | | |\n\n\n We use a dictionary data structure to represent the possible values of each square. E.g.{'A1':'12349', 'A2':'8', ...}\n\n A common way to solve it is to use recursive back-tracking search, plus forward checking. There are two rules of thumb can be\n used for forward checking:\n (1) If a square has only one possible value, then eliminate that value from the square's peers.\n (2) If a unit has only one possible place for a value, then put the value there.\n \"\"\"\n\n\n def __init__(self, grid):\n \"\"\"\n Initialization: convert grid from a string to a dictionary data structure to represent the possible values of\n each square. E.g.{'A1':'12349', 'A2':'8', ...}. For each unsolved element in grid, '0' or '.', they have\n '123456789' as possible values initially.\n :param grid: A string of 81 chars representing the values for each square, '0' or '.' for unsolved squares\n \"\"\"\n\n # Class constants\n self.DIGITS = '123456789'\n self.ROWS = 'ABCDEFGHI'\n self.COLS = self.DIGITS\n self.SQUARES = utility.cross(self.ROWS, self.COLS)\n\n self.UNITLISTS = ([utility.cross(self.ROWS, c) for c in self.COLS] +\n [utility.cross(r, self.COLS) for r in self.ROWS] +\n [utility.cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI') for cs in ('123', '456', '789')])\n\n self.UNITS = dict((square, [unit for unit in self.UNITLISTS if square in unit]) for square in self.SQUARES)\n self.PEERS = dict((square, set(sum(self.UNITS[square], [])) - set([square])) for square in self.SQUARES)\n\n self.possible_values = self.initialize_possible_values(grid)\n self.init_values = self.grid_values(grid)\n self.final_values = {}\n\n\n def initialize_possible_values(self, grid):\n \"\"\"\n Initialize the grid string into a dictionary format for the solver\n :param grid:\n :return: Initialized dictionary of possible values.\n \"\"\"\n possible_values = dict((square, self.DIGITS) for square in self.SQUARES)\n partial_sol = self.grid_values(grid)\n for square, d in partial_sol.items():\n if d not in '0.':\n possible_values[square] = d\n return possible_values\n\n\n def grid_values(self, grid):\n \"\"\"\n Convert grid into a dict of {square: char} with '0' or '.' for empties.\n :param grid: A string of 81 chars representing the values for each square, '0' or '.' for unsolved squares\n \"\"\"\n chars = [c for c in grid if c in self.DIGITS or c in '0.']\n assert len(chars) == 81\n return dict(zip(self.SQUARES, chars))\n\n\n def display(self, values):\n \"\"\"\n Helper function to display these values as a 2-D grid.\n E.g.:\n 1 3 5 |2 9 7 |8 6 4\n 9 8 2 |4 1 6 |7 5 3\n 7 6 4 |3 8 5 |1 9 2\n ------+------+------\n 2 1 8 |7 3 9 |6 4 5\n 5 9 7 |8 6 4 |2 3 1\n 6 4 3 |1 5 2 |9 7 8\n ------+------+------\n 4 2 6 |5 7 1 |3 8 9\n 3 5 9 |6 2 8 |4 1 7\n 8 7 1 |9 4 3 |5 2 6\n\n If values is None, it will print some warning message\n \"\"\"\n if values is None:\n print('There is no possible solution for this puzzle')\n return\n\n width = 1 + max(len(values[square]) for square in self.SQUARES)\n line = '+'.join(['-' * (width * 3)] * 3)\n for r in self.ROWS:\n print(''.join(values[r + c].center(width) + ('|' if c in '36' else '')\n for c in self.COLS))\n if r in 'CF':\n print(line)\n #print()\n\n\n def forward_check(self, possible_values):\n \"\"\"\n Forward checking of CSP. Call first_strategy and second\n :param possible_values:\n :return: Updated possible values with potential lots of values eliminated\n \"\"\"\n\n init_possible_values = possible_values.copy()\n init_possible_values = self.first_strategy(init_possible_values)\n\n if init_possible_values == False:\n return False\n possible_values, changed = self.second_strategy(init_possible_values.copy())\n\n # If some more values are eliminated using second strategy, must use first strategy again to see if even more\n # values can be eliminated\n while changed:\n init_possible_values = possible_values.copy()\n init_possible_values = self.first_strategy(init_possible_values)\n if init_possible_values == False:\n return False\n possible_values, changed = self.second_strategy(init_possible_values.copy())\n\n\n return possible_values\n\n\n def first_strategy(self, possible_values):\n \"\"\"\n 1st strategy to rule out impossible values: If a square has only one possible value, then eliminate that value\n from the square's peers.\n\n :param possible_values:\n :return:Updated possible values with potential lots of values eliminated\n \"\"\"\n\n for square, d in possible_values.items():\n if len(d) == 0:\n return False\n elif len(d) == 1:\n for s2 in self.PEERS[square]:\n new_possible_vals = set(possible_values[s2]).difference(set(d))\n new_possible_vals = ''.join(new_possible_vals)\n if len(new_possible_vals) > 0:\n possible_values[s2] = new_possible_vals\n else:\n return False\n\n return possible_values\n\n def second_strategy(self, possible_values):\n \"\"\"\n 2nd strategy to rule out impossible values: If a unit has only one possible place for a value, then put the\n value there.\n\n :param possible_values:\n :return:Updated possible values with potential lots of values eliminated\n \"\"\"\n changed = False\n for square in self.SQUARES:\n for unit in self.UNITS[square]:\n unit_values = {d for s2 in unit if s2 != square for d in possible_values[s2]}\n remaining_value_for_s = set(possible_values[square]).difference(unit_values)\n if len(remaining_value_for_s) == 1:\n if len(remaining_value_for_s) != len(possible_values[square]):\n changed = True\n possible_values[square] = remaining_value_for_s.pop()\n return possible_values, changed\n\n\n\n def backtracking_search(self,possible_values):\n \"\"\"\n Use back-tracking search to search a solution.\n :param possible_values:\n :return: False if no solution, or final values otherwise\n \"\"\"\n possible_values = self.forward_check(possible_values)\n\n if possible_values == False:\n return False\n\n values = self.recursive_backtracking(possible_values)\n return values\n\n\n def recursive_backtracking(self, possible_values):\n \"\"\"\n Recursive backtracking\n :param possible_values:\n :return: False if no solution, or final values otherwise\n \"\"\"\n\n if possible_values == False:\n return False\n\n if all(len(possible_values[square]) == 1 for square in self.SQUARES):\n return possible_values # solved\n\n # use minimum remaining value square as next candidate to try\n n,square = min((len(possible_values[square]), square) for square in self.SQUARES if len(possible_values[square]) > 1)\n\n for d in possible_values[square]:\n possible_values_copy = possible_values.copy()\n possible_values_copy[square] = d\n possible_values_copy = self.forward_check(possible_values_copy)\n if possible_values_copy != False:\n possible_values_copy = self.recursive_backtracking(possible_values_copy)\n\n if possible_values_copy != False: # If stuck in this way, back track to search other ways\n return possible_values_copy\n\n possible_values_copy = possible_values\n\n return False\n\n\n\n def solve(self):\n \"\"\"\n Solve the puzzle!!!\n :return: Final assignment of values for each square\n \"\"\"\n start = time.clock()\n self.final_values = self.backtracking_search(self.possible_values)\n t = time.clock()-start # Record the time it takes to solve\n if self.solved(self.final_values):\n self.display(self.init_values)\n print('#####################')\n self.display(self.final_values)\n print('(%.2f seconds)\\n' % t)\n return (t, self.final_values)\n\n return (t, False)\n\n\n def solved(self, values):\n \"\"\"\n A puzzle is solved if each unit is a permutation of the digits 1 to 9.\n :param values:\n :return: True if it is solved, False otherwise\n \"\"\"\n def unitsolved(unit): return set(values[square] for square in unit) == set(self.DIGITS)\n return values is not False and all(unitsolved(unit) for unit in self.UNITLISTS)\n\n\n\n## References used:\n## http://www.scanraid.com/BasicStrategies.htm\n## http://www.sudokudragon.com/sudokustrategy.htm\n## http://norvig.com/sudoku.html\n","repo_name":"xy008areshsu/Sudoku","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":11941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42679839877","text":"import collections\nimport inspect\nimport itertools\nimport unittest\n\nimport dimod\nimport numpy as np\nimport networkx as nx\nimport parameterized\n\nfrom dwave.samplers.tree import TreeDecompositionSampler\n\n\nclass TestConstruction(unittest.TestCase):\n def test_construction(self):\n sampler = TreeDecompositionSampler()\n dimod.testing.assert_sampler_api(sampler)\n\n # check that the args exposed by parameters is consistent with the\n # sampler inputs\n args = {arg for arg in inspect.getfullargspec(sampler.sample).args\n if arg != 'self' and arg != 'bqm'}\n self.assertEqual(set(sampler.parameters), args)\n\n self.assertEqual(sampler.properties, {'max_treewidth': 25})\n\n@dimod.testing.load_sampler_bqm_tests(TreeDecompositionSampler())\nclass TestSample(unittest.TestCase):\n def test_empty(self):\n bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)\n\n sampleset = TreeDecompositionSampler().sample(bqm)\n dimod.testing.assert_response_energies(sampleset, bqm)\n\n def test_empty_num_reads(self):\n bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)\n\n sampleset = TreeDecompositionSampler().sample(bqm, num_reads=10)\n self.assertEqual(len(sampleset), 10)\n dimod.testing.assert_response_energies(sampleset, bqm)\n\n def test_consistent_dtype_empty(self):\n bqm_empty = dimod.BinaryQuadraticModel.empty(dimod.BINARY)\n bqm = dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1, (0, 1): 1})\n\n sampleset_empty = TreeDecompositionSampler().sample(bqm_empty)\n sampleset = TreeDecompositionSampler().sample(bqm)\n\n self.assertEqual(sampleset_empty.record.sample.dtype,\n sampleset.record.sample.dtype)\n self.assertEqual(sampleset_empty.record.energy.dtype,\n sampleset.record.energy.dtype)\n\n def test_consistent_info(self):\n bqm_empty = dimod.BinaryQuadraticModel.empty(dimod.BINARY)\n bqm = dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1, (0, 1): 1})\n\n sampleset_empty = TreeDecompositionSampler().sample(bqm_empty)\n sampleset = TreeDecompositionSampler().sample(bqm)\n\n self.assertEqual(set(sampleset.info), set(sampleset_empty.info))\n\n def test_consistent_info_with_marginals(self):\n bqm_empty = dimod.BinaryQuadraticModel.empty(dimod.BINARY)\n bqm = dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1, (0, 1): 1})\n\n sampleset_empty = TreeDecompositionSampler().sample(bqm_empty, marginals=True)\n sampleset = TreeDecompositionSampler().sample(bqm, marginals=True)\n\n self.assertEqual(set(sampleset.info), set(sampleset_empty.info))\n\n def test_single_variable(self):\n bqm = dimod.BinaryQuadraticModel.from_ising({'a': -1}, {})\n\n samples = TreeDecompositionSampler().sample(bqm, num_reads=1)\n\n self.assertEqual(len(samples), 1)\n dimod.testing.assert_response_energies(samples, bqm)\n\n def test_single_interaction(self):\n bqm = dimod.BinaryQuadraticModel.from_ising({'a': -1}, {'ab': 1})\n\n samples = TreeDecompositionSampler().sample(bqm, num_reads=1)\n\n self.assertEqual(len(samples), 1)\n dimod.testing.assert_response_energies(samples, bqm)\n\n def test_larger_problem(self):\n bqm = dimod.BinaryQuadraticModel.from_ising({'a': -1}, {'ab': 1, 'bc': -1, 'cd': +1})\n\n samples = TreeDecompositionSampler().sample(bqm, num_reads=1)\n\n self.assertEqual(len(samples), 1)\n dimod.testing.assert_response_energies(samples, bqm)\n\n\n@parameterized.parameterized_class([\n dict(bqm=dimod.BinaryQuadraticModel.from_ising({'a': -1}, {})),\n dict(bqm=dimod.BinaryQuadraticModel.from_ising({'a': +1}, {})),\n dict(bqm=dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1})),\n dict(bqm=dimod.BinaryQuadraticModel.from_qubo({(0, 0): +1})),\n dict(bqm=dimod.BinaryQuadraticModel.from_ising({'a': -1}, {}, .5)),\n dict(bqm=dimod.BinaryQuadraticModel.from_qubo({(0, 0): -1}, offset=.5)),\n dict(bqm=dimod.BinaryQuadraticModel.from_ising({}, {'ab': -1})),\n dict(bqm=dimod.BinaryQuadraticModel.from_ising({}, {'ab': 1})),\n dict(bqm=dimod.BinaryQuadraticModel.from_ising({}, {'ab': .69, 'bc': 1, 'ac': .5})),\n dict(bqm=dimod.BinaryQuadraticModel.from_qubo({'ab': .69, 'bc': 1, 'ac': .5})),\n dict(bqm=dimod.BinaryQuadraticModel.from_qubo({'ab': .69, 'bc': 1})),\n dict(bqm=dimod.AdjDictBQM({'a': 6.0, 0: 1}, {('a', 0): -3, (0, 'c'): 10}, 0, 'BINARY')),\n])\nclass TestMarginals(unittest.TestCase):\n def test_spin_log_partition_function(self):\n bqm = self.bqm\n\n exact = dimod.ExactSolver().sample(bqm)\n\n for beta in [.5, 1., 1.5, 2]:\n with self.subTest(beta=beta):\n sampleset = TreeDecompositionSampler().sample(bqm, num_reads=10, beta=beta)\n\n logZ = sampleset.info['log_partition_function']\n\n # use the exactsolver to get all of the samples/energies\n calculated_logZ = np.log(np.sum(np.exp(-beta*exact.record.energy)))\n\n self.assertAlmostEqual(logZ, calculated_logZ)\n\n with self.subTest(beta='default'):\n sampleset = TreeDecompositionSampler().sample(bqm, num_reads=10)\n\n logZ = sampleset.info['log_partition_function']\n\n # use the exactsolver to get all of the samples/energies\n calculated_logZ = np.log(np.sum(np.exp(-1*exact.record.energy)))\n\n self.assertAlmostEqual(logZ, calculated_logZ)\n\n def test_variable_marginals_analytic(self):\n bqm = self.bqm\n\n exact = dimod.ExactSolver().sample(bqm)\n\n # for each variable, we need the sum over all energies when variable\n # is low or high\n energies = {}\n for v in bqm.variables:\n idx = exact.variables.index(v)\n\n hien = exact.record[exact.record.sample[:, idx] > 0].energy\n\n energies[v] = hien\n\n # dev note: when migrating to python 3.4+ these should become subtests\n for beta in [.5, 1., 1.5, 2]:\n sampleset = TreeDecompositionSampler().sample(bqm,\n marginals=True, num_reads=1,\n beta=beta)\n\n logZ = sampleset.info['log_partition_function']\n variable_marginals = sampleset.info['variable_marginals']\n\n Z = np.exp(logZ) # we're only doing small ones so this is ok\n\n for v, p in variable_marginals.items():\n hien = energies[v] # energies associated with v > 0\n\n self.assertAlmostEqual(p, np.sum(np.exp(-beta*hien)) / Z)\n\n def test_variable_marginals_empirical(self):\n # check that the actual samples match the marginals\n bqm = self.bqm\n\n # dev note: when migrating to python 3.4+ these should become subtests\n for beta in [.5, 1., 1.5, 2]:\n # we only need one sample to get the marginals\n single_sample = TreeDecompositionSampler().sample(bqm,\n marginals=True, num_reads=1,\n beta=beta)\n\n variable_marginals = single_sample.info['variable_marginals']\n\n n = 22500\n\n sampleset = TreeDecompositionSampler().sample(bqm, marginals=True, num_reads=n,\n beta=beta)\n\n for v, p in variable_marginals.items():\n p_observed = np.sum(sampleset.samples()[:, v] > 0) / len(sampleset)\n\n self.assertAlmostEqual(p, p_observed, places=1)\n\n def test_interaction_marginals_analytic(self):\n bqm = self.bqm\n\n exact = dimod.ExactSolver().sample(bqm)\n\n for beta in [.5, 1., 1.5, 2]:\n sampleset = TreeDecompositionSampler().sample(self.bqm, num_reads=1, beta=beta,\n marginals=True)\n\n logZ = sampleset.info['log_partition_function']\n interaction_marginals = sampleset.info['interaction_marginals']\n\n Z = np.exp(logZ) # we're only doing small ones so this is ok\n\n total_p = 0 # for sanity check\n\n # calculate the marginals analytically from the energies\n analytic_marginals = {pair: collections.defaultdict(float)\n for pair in interaction_marginals}\n for sample, energy in exact.data(['sample', 'energy']):\n\n # probability for this sample\n p = np.sum(np.exp(-beta*energy)) / Z\n total_p += p\n\n for (u, v) in analytic_marginals:\n config = (sample[u], sample[v])\n\n analytic_marginals[(u, v)][config] += p\n\n self.assertAlmostEqual(total_p, 1) # sanity check\n\n # check that analytic and orang's are the same\n for pair, combos in interaction_marginals.items():\n for config, p in combos.items():\n self.assertAlmostEqual(p, analytic_marginals[pair][config])\n","repo_name":"dwavesystems/dwave-samplers","sub_path":"tests/test_tree_sampler.py","file_name":"test_tree_sampler.py","file_ext":"py","file_size_in_byte":9122,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"12752032455","text":"import argparse\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport sys\n\n\ndef main():\n parser = argparse.ArgumentParser(description=('Builds command_buffer_gles2 '\n 'library and copies it'))\n parser.add_argument('-c', '--chrome-dir', required=True, help=\n 'path to Chromium checkout (directory containing .gclient)')\n parser.add_argument('-o', '--output-dir', required=True,\n help='path to copy the command buffer shared library to. Typically this '\n 'is out/Debug or out/Release in a Skia repository')\n parser.add_argument('--make-output-dir', default=False, action='store_true',\n help='Makes the output directory if it does not already exist.')\n parser.add_argument('--chrome-out-dir', default='CommandBufferForSkia',\n help='Type of name of the gn output directory (e.g. Debug or Release). '\n 'This is relative to the Chromium src/out directory. Note that this '\n 'script will reset the gn args in this directory on each run.')\n parser.add_argument('--extra-gn-args', default='',\n help=('Extra GN arguments to use for the output directory used to build'\n 'the command buffer'))\n parser.add_argument('--extra-ninja-args', default='',\n help=('Extra arguments to pass to ninja when building the command '\n 'buffer shared library'))\n parser.add_argument('--chrome-revision', default='origin/lkgr',\n help='Revision (hash, branch, tag) of Chromium to use.')\n parser.add_argument('--no-sync', action='store_true', default=False,\n help='Don\\'t run git fetch or gclient sync in the Chromium tree')\n parser.add_argument('--no-hooks', action='store_true', default=False,\n help='Don\\'t run gclient runhooks in the Chromium tree. Implies '\n '--no-sync')\n args = parser.parse_args()\n\n args.chrome_dir = os.path.abspath(args.chrome_dir)\n args.output_dir = os.path.abspath(args.output_dir)\n\n if args.no_hooks:\n args.no_sync = True\n\n if os.path.isfile(args.chrome_dir):\n sys.exit(args.chrome_dir + ' exists but is a file.')\n\n if os.path.isfile(args.output_dir):\n sys.exit(args.output_dir + ' exists but is a file.')\n\n chrome_src_dir = os.path.join(args.chrome_dir, 'src')\n\n if not os.path.isdir(chrome_src_dir):\n sys.exit(chrome_src_dir + ' is not a directory.')\n\n if os.path.isfile(args.output_dir):\n sys.exit(args.output_dir + ' exists but is a file.')\n elif not os.path.isdir(args.output_dir):\n if args.make_output_dir:\n os.makedirs(args.output_dir)\n else:\n sys.exit(args.output_dir + ' does not exist (specify --make-output-dir '\n 'to create).')\n\n chrome_target_dir_rel = os.path.join('out', args.chrome_out_dir)\n\n # The command buffer shared library will have a different name on Linux,\n # Mac, and Windows. Also, the name of the gclient executable we call out to\n # has a .bat file extension on Windows.\n platform = sys.platform\n if platform == 'cygwin':\n platform = 'win32'\n\n shared_lib_name = 'libcommand_buffer_gles2.so'\n gclient = 'gclient'\n if platform == 'darwin':\n shared_lib_name = 'libcommand_buffer_gles2.dylib'\n elif platform == 'win32':\n shared_lib_name = 'command_buffer_gles2.dll'\n gclient = 'gclient.bat'\n\n if not args.no_sync:\n try:\n subprocess.check_call(['git', 'fetch'], cwd=chrome_src_dir)\n except subprocess.CalledProcessError as error:\n sys.exit('Error (ret code: %s) calling \"%s\" in %s' % (error.returncode,\n error.cmd, chrome_src_dir))\n\n try:\n subprocess.check_call(['git', 'checkout', args.chrome_revision],\n cwd=chrome_src_dir)\n except subprocess.CalledProcessError as error:\n sys.exit('Error (ret code: %s) calling \"%s\" in %s' % (error.returncode,\n error.cmd, chrome_src_dir))\n\n try:\n os.environ['GYP_GENERATORS'] = 'ninja'\n subprocess.check_call([gclient, 'sync', '--reset', '--force',\n '--nohooks'],\n cwd=chrome_src_dir)\n except subprocess.CalledProcessError as error:\n sys.exit('Error (ret code: %s) calling \"%s\" in %s' % (error.returncode,\n error.cmd, chrome_src_dir))\n\n if not args.no_hooks:\n try:\n subprocess.check_call([gclient, 'runhooks'], cwd=chrome_src_dir)\n except subprocess.CalledProcessError as error:\n sys.exit('Error (ret code: %s) calling \"%s\" in %s' % (\n error.returncode, error.cmd, chrome_src_dir))\n\n gn = 'gn'\n platform = 'linux64'\n if sys.platform == 'darwin':\n platform = 'mac'\n elif sys.platform == 'win32':\n platform = 'win'\n gn = 'gn.exe'\n gn = os.path.join(chrome_src_dir, 'buildtools', platform, gn)\n try:\n gnargs = 'is_component_build=false is_debug=false ' + args.extra_gn_args\n subprocess.check_call([gn, 'gen', chrome_target_dir_rel, '--args='+gnargs],\n cwd=chrome_src_dir)\n except subprocess.CalledProcessError as error:\n sys.exit('Error (ret code: %s) calling \"%s\" in %s' % (\n error.returncode, error.cmd, chrome_src_dir))\n\n try:\n subprocess.check_call(['ninja'] + shlex.split(args.extra_ninja_args) +\n ['-C', chrome_target_dir_rel, 'command_buffer_gles2'],\n cwd=chrome_src_dir)\n except subprocess.CalledProcessError as error:\n sys.exit('Error (ret code: %s) calling \"%s\" in %s' % (error.returncode,\n error.cmd, chrome_src_dir))\n\n shared_lib_src_dir = os.path.join(chrome_src_dir, chrome_target_dir_rel)\n\n shared_lib_src = os.path.join(shared_lib_src_dir, shared_lib_name)\n shared_lib_dst = os.path.join(args.output_dir, shared_lib_name)\n\n if not os.path.isfile(shared_lib_src):\n sys.exit('Command buffer shared library not at expected location: ' +\n shared_lib_src)\n\n shutil.copy2(shared_lib_src, shared_lib_dst)\n\n if not os.path.isfile(shared_lib_dst):\n sys.exit('Command buffer library not copied to ' + shared_lib_dst)\n\n print('Command buffer library copied to ' + shared_lib_dst)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"kiwibrowser/src","sub_path":"third_party/skia/tools/build_command_buffer.py","file_name":"build_command_buffer.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"11443492715","text":"class UnionFind :\n def __init__ (self,n):\n self.parent = [node for node in range(0, n)]\n self.size=[1 for node in range(0,n)]\n \n def Find(self,n):\n if self.parent[n]==n:\n return n\n \n return self.Find(self.parent[n])\n \n def Union(self, a, b) :\n x=self.Find(a)\n y=self.Find(b)\n \n if x==y :\n return False\n \n elif self.size[x] >= self.size[y] :\n self.parent[y]=x\n self.size[x]+=self.size[y]\n \n else :\n self.parent[x]=y\n self.size[y]+=self.size[x]\n \n def Check_union(self, a, b) :\n x=self.Find(a)\n y=self.Find(b)\n \n if x==y :\n return True\n return False \n\n\nclass Solution: \n def earliestAcq(self, logs: List[List[int]], n: int) -> int:\n \n U=UnionFind(n)\n logs.sort()\n \n for data in logs :\n U.Union(data[1],data[2])\n count=0\n for i in range(0,n) :\n if not U.Check_union(data[1],i) :\n break\n count+=1\n if count == n :\n return data[0] \n return -1\n \n \n \n \n \n ","repo_name":"kwilliam777/CodingTestStudy","sub_path":"weekly assingment/week1/y_1101_2_t.py","file_name":"y_1101_2_t.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"34519848705","text":"# mlp classifier\n\nclass InputLayer:\n def __init__(self, inputs):\n self.Inputs = inputs\n self.Outputs = inputs\n\n\nclass HiddenLayer:\n def __init__(self, inputs, numberNodes, weights):\n self.Inputs = inputs\n self.NumberNodes = numberNodes\n self.Weights = weights\n self.Outputs = []\n\n\ndef Activation(input):\n if input > 0:\n return 1\n else:\n return 0\n\n\ndef calculate(InputLayer, HiddenLayer):\n return Activation(HiddenLayer.Weights[0] + HiddenLayer.Weights[1]*InputLayer.Outputs[0] +\n HiddenLayer.Weights[2]*InputLayer.Outputs[1])\n\n\ndef calculateOutputs(inputs, HiddenLayer):\n return Activation(HiddenLayer.Weights[0] + HiddenLayer.Weights[1]*inputs[0] + HiddenLayer.Weights[2]*inputs[1])\n\n\n# inputs = [[0, 0], [0, 1], [1, 0], [1, 1]]\nWeights = [-1, 1, 1]\n\nuser = []\nuser.append(input(\"AND gate inputs: \"))\ninputs = []\nfor element in user:\n for char in element:\n if char != \" \":\n inputs.append(int(char))\n\ndef ANDgate(inputs, weights):\n\n inp = InputLayer(inputs)\n hid = HiddenLayer(inp.Outputs, 2, weights)\n hid.Outputs.append(calculate(inp, hid))\n hid.Outputs.append(calculate(inp, hid))\n\n out = HiddenLayer(hid.Outputs, 1, weights)\n out.Outputs.append(calculateOutputs(hid.Outputs, out))\n x = [str(x) for x in inputs]\n print(f\"The output for {', '.join(x)} is: {str(out.Outputs[0])}\")\n\nANDgate(inputs, Weights)\n# input 0 0, with a space in between\n","repo_name":"talasleman/Comp472-MiniProject2","sub_path":"neural_network_from_scratch.py","file_name":"neural_network_from_scratch.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40165547896","text":"from PIL import Image\nimport socket\nimport sys\nimport pickle\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nserver = \"35.163.41.116\"\nport = 5555\n\ntry:\n s.connect((server, port))\nexcept socket.error as e:\n print(str(e))\n\nimage = s.recv(4096)\n\nimage.decode('utf-8')\nprint(image)\n#image = Image.frombytes(\"RGB\", (500,500), image)\n#image.save(\"%d.png\" % 123, \"PNG\")\n#with open(\"test.ppk\", \"wb\") as f:\n# f.write(image)\n \n","repo_name":"MVHSIgnition/EasyMeal","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44523232317","text":"# Arrays in python are Lists\n# There are 4 types of lists\n# The first is of course a list\n# The syntax for a list is List_Name = [variables]\n# Lists are ordered, changeable, and allow duplicate values.\n# List items are indexed, the first item has index [0], the second item has index [1] etc.\n# The second is a Tuple\n# The syntax for a tuple is Tuple_Name = (Variables)\n# Tuples are a collection which is ordered and unchangeable.\n# The third is a Set\n# The syntax for a set is Set_Name = {Variables}\n# A set is a collection which is unordered, unchangeable, and unindexed\n# The last type are Dictionaries\n# A dictionary is a collection which is ordered, changeable, and do not allow duplicates.\n# The syntax for a dictionary is Dictionary_Name = {\n# \"Variable name\": Variable_Value\n# }\n\nchoice = True\nPersonList = []\n\n\ndef createDictionary(FirstName, LastName, Age, Height, PhoneNumber):\n DictName = {\n \"FirstName\": FirstName,\n \"LastName\": LastName,\n \"Age\": Age,\n \"height\": Height,\n \"PhoneNumber\": PhoneNumber\n }\n return DictName\n\n\nPersonList.append(createDictionary(\"Omar\", \"Alabdalla\", \"17\", \"510\", \"1351241243\"))\nPersonList.append(createDictionary(\"Eli\", \"Maffry\", \"18\", '''6'9\"''', \"9133336858\"))\nPersonList.append(createDictionary(\"Monish\", \"Chittampalli\", \"18\", \"510\", \"9132307340\"))\n\nwhile choice is True:\n\n userInput = str(input(\n \"Please input (1) if you would like to create a new list or (2) if you would like to view the created ones \"\n \"\\nYou can also input (3) if you want to search for a specific list \"))\n\n if userInput == str(1):\n firstName = str(input(\"Please input your first name \"))\n lastName = str(input(\"Please input your last Name \"))\n age = str(input(\"Please input your age \"))\n height = str(input(\"Please input your height \"))\n phoneNumber = str(input(\"Please input your phone number \"))\n PersonList.append(createDictionary(firstName, lastName, age, height, phoneNumber))\n\n for i in PersonList:\n print(i)\n elif userInput == str(2):\n for i in PersonList:\n print(f\"\\n`{i} \\n\")\n elif userInput == str(3):\n aInput = str(input(\"Please input some variable from the list to see the whole thing \"))\n print(\"\\n\")\n for i in PersonList:\n if aInput in i.values():\n print(i)\n","repo_name":"Omar-Alabdalla/Programming-Fundamentals","sub_path":"Array Project.py","file_name":"Array Project.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"607925059","text":"class Solution(object):\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n lo, hi = 0, len(nums)-1\n # step1 find real beginning\n while lonums[hi]: # all unique\n lo = mid+1\n else:\n hi = mid\n\n #step 2 nornal binary search with shift\n # 三个pointer全部都是一样的shift,所以全部原操作\n l, h = 0, len(nums)-1\n while l<=h: # length为1,一般情况下不要等\n mid = (l+h)//2\n real_m = (mid+lo)%len(nums)\n if nums[real_m]==target:\n return real_m\n if nums[real_m]>target:\n h = mid-1\n else:\n l = mid+1\n\n return -1\n\n\n # 有重复元素\n def search(self, nums, target):\n if not nums: return False\n lo, hi = 0, len(nums)-1\n while lonums[hi]:\n lo = mid+1\n elif nums[mid]>1\n real_m = (m+lo)%len(nums)\n if nums[real_m]==target:\n return True\n if nums[real_m] b1, b2 (current_var)\n# b1为取值为1的分支,b2为取值为0的分支,类型为str或bool\nclass INFExpr:\n\n index = 0 # 表明当前的current_var在所有相同变量的下标顺序\n highlighted = False # 是否高亮\n\n def __init__(self, t='t', a='', current_var=None, b1=None, b2=None,\n tree_position=None):\n self.t = t\n if isinstance(a, str):\n self.a = a\n\n if isinstance(current_var, str):\n self.current_var = current_var\n\n self.b1 = b1\n self.b2 = b2\n\n self.tree_position = tree_position\n\n def highlight(self):\n self.highlighted = True\n\n @property\n def is_highlighted(self):\n return self.highlighted\n\n def to_str(self):\n s = self.t + self.a + ' -> '\n if isinstance(self.b1,bool):\n s += str(int(self.b1))\n else:\n s += 't' + self.b1\n\n s += ','\n\n if isinstance(self.b2,bool):\n s += str(int(self.b2))\n else:\n s += 't' + self.b2\n\n s += ' (' + self.current_var + ')'\n return s\n\n def equals(self, inf_expr):\n if self.current_var == inf_expr.current_var and self.b1 == inf_expr.b1 and self.b2 == inf_expr.b2:\n return True\n else:\n return False\n\nclass BoolExprToInf:\n variables = {}\n var_list = []\n result_table = {}\n bool_expr = ''\n\n inf_list = [] # INF范式\n decision_tree = None # 决策树\n simplified_inf_list = [] # 简化后的INF范式\n simplified_inf_dict = {} # 根据a得到INF范式的字典{'001': INFExpr,...}\n obdd_tree = None # OBDD\n obdd_node = {} # 根据变量名得到OBDD节点坐标列表\n a_to_node = {} # 根据a得到变量节点及下标顺序\n\n def __init__(self, canvas=None, var_list=None,\n default_var='t', bool_expr='',\n variables=None,\n root_center=None):\n self.canvas = canvas\n self.var_list = var_list\n self.variables = variables\n self.default_var = default_var\n self.bool_expr = bool_expr\n self.root_center = root_center\n\n self.p = AntlrFacility()\n self.generate_result_table() # 得到真值表\n # print('真值表:')\n # print(self.result_table)\n\n # '{'x1'=1,x2=0'}' <==> '10'\n def dict_to_str(self, variables):\n s = ''\n for i in variables:\n s += str(int(variables[i]))\n return s\n\n # '10' <==> '{'x1'=1,'x2'=0}'\n def str_to_dict(self, str):\n variables = {}\n if len(str) == len(self.var_list):\n for index, ch in enumerate(str):\n variables[self.var_list[index]] = int(ch)\n return variables\n\n # 6 => '110'\n def num_to_str(self, num):\n l = len(self.var_list)\n return str(bin(num).zfill(l + 2)).replace('b', '')[1:]\n\n # 2 => '{'x1'=1,'x2'=0}'\n def num_to_dict(self, num):\n s = self.num_to_str(num)\n return self.str_to_dict(s)\n\n def generate_result_table(self):\n l = len(self.var_list)\n for i in range(2 ** l):\n variables = self.num_to_dict(i)\n result = self.p.get_parse_result(text=self.bool_expr, variables=variables)\n self.result_table[self.num_to_str(i)] = result\n\n def get_inf_list(self, generate_decision_tree=True, debug=False):\n self.generate_raw_inf_list(generate_decision_tree=generate_decision_tree,\n debug=debug)\n self.simplify_inf_list(debug=debug) # 得到简化后的INF\n return self.simplified_inf_list\n\n def get_inf_dict(self, generate_decision_tree=True, debug=False):\n self.generate_raw_inf_list(generate_decision_tree=generate_decision_tree,\n debug=False)\n self.simplify_inf_list(debug=debug) # 得到简化后的INF\n return self.simplified_inf_dict\n\n def generate_raw_inf_list(self, generate_decision_tree=True, debug=False):\n self.inf_list.clear()\n decay = 10\n if generate_decision_tree is True:\n root_node = Node(canvas=self.canvas, center=self.root_center,\n text=self.var_list[0],\n d=60, h=60)\n init_obj = Obj(a='', current_var=self.var_list[0], node=root_node)\n else:\n init_obj = Obj(a='', current_var=self.var_list[0])\n\n if debug is True:\n print(\"INF范式:\")\n q = queue.Queue()\n q.put(init_obj)\n\n while not q.empty():\n cur_obj = q.get()\n l = self.create_inf_bfs(a=cur_obj.a, current_var=cur_obj.current_var)\n\n if generate_decision_tree is True:\n # len(l) 说明两子节点都非终端节点,若l[0]l[1]都为bool则都为终端节点\n if len(l):\n # '1' high\n if l[0] is not False and l[0] is not True:\n cur_obj.node.create_child_node(direc='high', text=l[0][1],\n decay=decay)\n child_node = cur_obj.node.high_child\n obj = Obj(a=l[0][0], current_var=l[0][1], node=child_node)\n q.put(obj)\n else:\n cur_obj.node.create_child_node(direc='high', text=str(int(l[0])),\n decay=decay, isLeaf=True)\n # '0' low\n if l[1] is not False and l[1] is not True:\n cur_obj.node.create_child_node(direc='low', text=l[1][1],\n decay=decay)\n child_node = cur_obj.node.low_child\n obj = Obj(a=l[1][0], current_var=l[1][1], node=child_node)\n q.put(obj)\n else:\n cur_obj.node.create_child_node(direc='low', text=str(int(l[1])),\n decay=decay, isLeaf=True)\n else:\n # len(l) 说明两子节点都非终端节点,若l[0]l[1]都为bool则都为终端节点\n if len(l):\n # '1' high\n if l[0] is not False and l[0] is not True:\n obj = Obj(a=l[0][0], current_var=l[0][1])\n q.put(obj)\n\n # '0' low\n if l[1] is not False and l[1] is not True:\n obj = Obj(a=l[1][0], current_var=l[1][1])\n q.put(obj)\n\n if debug is True:\n for i in self.inf_list:\n print(i.to_str())\n\n def simplify_inf_list(self, debug=False):\n self.simplified_inf_list.clear()\n if len(self.inf_list) <= 1: # 若只有一条INF,则无需简化\n self.simplified_inf_list = self.inf_list\n return\n index = len(self.inf_list) - 1\n\n tmp = self.inf_list\n while index > 0:\n for i in range(index - 1, -1, -1): # 从尾部扫描到头部\n # print('index: '+ str(index) + ', ' + 'i: ' + str(i))\n if tmp[index].equals(tmp[i]) and index != i: # 若相同,保留数字小的,比如\"001\"\"111\"保留前者\n smaller_one = tmp[index].a\n bigger_one = tmp[i].a\n if int(tmp[index].a) > int(tmp[i].a):\n smaller_one = tmp[i].a\n bigger_one = tmp[index].a\n tmp.remove(tmp[index])\n else:\n tmp.remove(tmp[i])\n for each in tmp:\n if each.b1 == bigger_one:\n each.b1 = smaller_one\n if each.b2 == bigger_one:\n each.b2 = smaller_one\n index -= 1 # 因为删去了一个,所以index减1\n index -= 1\n self.simplified_inf_list = tmp\n\n for inf in self.simplified_inf_list:\n self.simplified_inf_dict[inf.a] = inf\n\n if debug is True:\n print('简化后的INF:')\n for inf in self.simplified_inf_list:\n print(inf.to_str())\n\n # 从前向后再进行简化\n while True:\n is_simplified = True\n for index, inf in enumerate(self.simplified_inf_list):\n if inf.b1 == inf.b2: # 高低端子节点相同\n is_simplified = False\n break\n if is_simplified is True:\n break\n for index, inf in enumerate(self.simplified_inf_list):\n to_replace = ''\n replaced_by = ''\n if inf.b1 == inf.b2: # 高低端子节点相同\n to_replace = inf.a\n replaced_by = inf.b1\n self.simplified_inf_list.remove(inf)\n for j in range(index):\n tmp_inf = self.simplified_inf_list[j]\n if tmp_inf.b1 == to_replace:\n tmp_inf.b1 = replaced_by\n if tmp_inf.b2 == to_replace:\n tmp_inf.b2 = replaced_by\n\n if debug is True:\n print('简化后的INF:')\n for inf in self.simplified_inf_list:\n print(inf.to_str())\n\n\n # l = [ [a,next_var]|bool, [a,next_var]|bool]\n # 若为bool则表明该子节点为终端节点\n def create_inf_bfs(self, a='', current_var=None):\n l = [[a, current_var], [a, current_var]]\n branch = [a + '1', a + '0']\n for index, i in enumerate(branch):\n if len(i) == len(self.var_list):\n branch[index] = self.result_table[i]\n else:\n all = [j for j in self.result_table if j[:len(i)] == i]\n # 是否其余变量的所有取值对应的结果都相同\n if len(all):\n flag = True\n for other in all:\n if self.result_table[other] != self.result_table[all[0]]:\n flag = False\n if flag:\n branch[index] = self.result_table[all[0]]\n inf = INFExpr(a=a, current_var=current_var,\n b1=branch[0], b2=branch[1])\n self.inf_list.append(inf)\n\n if len(a) == len(self.var_list) - 1:\n return [branch[0], branch[1]]\n\n next_var = ''\n for index, var in enumerate(self.var_list):\n if var == current_var and index < len(self.var_list) - 1:\n next_var = self.var_list[index + 1]\n\n l[0][0] = branch[0]\n l[0][1] = next_var\n l[1][0] = branch[1]\n l[1][1] = next_var\n\n if branch[0] is False or branch[0] is True:\n l[0] = branch[0]\n if branch[1] is False or branch[1] is True:\n l[1] = branch[1]\n return l\n\n # 对inf_list根据变量取值进行高亮\n def highlight_inf_and_node(self, variables=None):\n if len(self.simplified_inf_list) == 0: # INF列表为空则退出\n return\n tmp_inf = self.simplified_inf_list[0]\n\n # 对高亮节点所在的式子进行高亮\n while True:\n tmp_inf.highlight()\n val = variables[tmp_inf.current_var]\n if isinstance(tmp_inf.b1, bool) and isinstance(tmp_inf.b2, bool):\n break\n if val is True: # 指向b1\n if isinstance(tmp_inf.b1, bool): # 若指向0或1的终端节点,则退出\n break\n tmp_inf = self.simplified_inf_dict[tmp_inf.b1]\n elif val is False: # 指向b2\n if isinstance(tmp_inf.b2, bool): # 若指向0或1的终端节点,则退出\n break\n tmp_inf = self.simplified_inf_dict[tmp_inf.b2]\n else:\n continue\n for i in self.simplified_inf_list:\n if i.is_highlighted:\n this_node = self.obdd_node[i.current_var][i.index] # 找出当前节点\n this_node.highlight()\n\n # 如果指向尾端0或1节点,对其进行高亮\n if variables[i.current_var]: # 指向b1\n if isinstance(i.b1, bool):\n self.obdd_node[str(int(i.b1))][0].highlight()\n elif variables[i.current_var] is False: # 指向b2\n if isinstance(i.b2, bool):\n self.obdd_node[str(int(i.b2))][0].highlight()\n else:\n continue\n\nif __name__ == '__main__':\n b = BoolExprToInf(bool_expr='(x1<=>y1)∧(x2<=>y2)',\n var_list=['x1','y1','x2','y2'],\n variables={\n 'x1':False,\n 'y1':False,\n 'x2':False,\n 'y2':False\n })\n inf_list = b.get_inf_list()\n for i in inf_list:\n print(i.to_str())","repo_name":"Xingkai98/bdd-visualizer","sub_path":"algorithms/bool_expr_to_inf.py","file_name":"bool_expr_to_inf.py","file_ext":"py","file_size_in_byte":13332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36082378066","text":"#!/usr/bin/python3\n\n\"\"\"\nThis script is meant to produce various performance curves of convolutional\nneural networks. It reads all .csv files from a specified folder, plots a curve,\nand writes it to an interactive .html file.\n\nEach .csv file is a result of a single model evaluated on a dataset.\n\nThe naming of a .csv should include the following two elements, in any order:\n- The \"net_\" keyword, followed by a string identifying the neural network model.\n- The \"set_\" keywork, followed by a string identifying the dataset.\n\nThe column structure of the .csv files should be:\n- recall, fp, confidence, precision\nin this order, where fp denotes the ammount of false positives.\n\nSee detection_parser.py\n\"\"\"\n\nimport os\nimport argparse\nimport random\nimport datetime\nimport scipy.signal\nimport textwrap\nimport plotly.graph_objects as go\nimport plotly as py\nimport pandas as pd\nimport numpy as np\nfrom sys import exit\nfrom os import path\nfrom itertools import cycle\nfrom scipy import interpolate\nfrom pprint import pprint\n\nEPSILON = 1e-2\n\ndef main():\n args = parseArguments()\n\n contents = os.listdir(args.indir)\n contents = [ path.join(args.indir,content) for content in contents ]\n files = [ content for content in contents if isCsvFile(content) ]\n def fileOrderComparison(file):\n file = path.basename(path.splitext(file)[0])\n specified,net,set,skip = parseName(file,False)\n return (set,net) if specified else (file,\"\")\n files.sort(key=fileOrderComparison)\n\n assert files, \"no tests to show\"\n\n if args.precision: # draw precision-recall curves\n fig = createFigure(\n xaxis_title=\"recall\",\n yaxis_title=\"precision\"+(\" & confidence\" if args.confidence else \"\"),\n xaxis={\"range\":(0-EPSILON,1+EPSILON),\"gridcolor\":\"lightGray\",\"gridwidth\":1,\"zerolinecolor\":\"black\",\"zerolinewidth\":1},\n yaxis={\"range\":(0-EPSILON,1+EPSILON),\"gridcolor\":\"lightGray\",\"gridwidth\":1,\"zerolinecolor\":\"black\",\"zerolinewidth\":1}\n )\n\n recallMaxes = {}\n for i, file in enumerate(files):\n df = pd.read_csv(file,sep=unescape(args.delimiter),header=None,names=(\"recall\",\"fp\",\"confidence\",\"precision\"))\n\n test = path.basename(path.splitext(file)[0])\n specified,net,set,skip = parseName(test,args.scales)\n if skip:\n continue\n\n if set in recallMaxes:\n recallMaxes[set] = min( recallMaxes[set], df[\"recall\"].max() )\n else:\n recallMaxes[set] = df[\"recall\"].max()\n\n for i, file in enumerate(files):\n df = pd.read_csv(file,sep=unescape(args.delimiter),header=None,names=(\"recall\",\"fp\",\"confidence\",\"precision\"))\n\n test = path.basename(path.splitext(file)[0])\n specified,net,set,skip = parseName(test,args.scales)\n if skip:\n continue\n\n df = (\n df.groupby((\"recall\"),as_index=False,sort=False)\n .agg({\"fp\":np.min,\"confidence\":np.max,\"precision\":np.max})\n .sort_values(by=(\"recall\"),ascending=False)\n )\n\n df[\"precision\"] = df[\"precision\"].cummax()\n df[\"confidence\"] = df[\"confidence\"].cummax()\n\n df = df.iloc[::-1]\n\n x = df[ df[\"recall\"] <= recallMaxes[set] ][\"recall\"].to_numpy()\n y = df[ df[\"recall\"] <= recallMaxes[set] ][\"precision\"].to_numpy()\n x_ = np.linspace(0,1,num=11)\n\n # f = interpolate.interp1d(x, y, fill_value=\"extrapolate\")\n # y_ = f(x_)\n if x.size:\n y_ = np.interp(x_, x, y, right=0)\n averagePrecision = np.mean(y_,dtype=np.float64)\n else:\n averagePrecision = 0\n\n areaUnderCurve = np.trapz(y,x)\n\n addScatterTrace(\n fig=fig,\n x=df[\"recall\"],\n y=df[\"precision\"],\n name=(\n (\"set: {:}
net:
{:}\".format(cutLonger(set),cutLonger(net)) if specified else \"{:}\".format(cutLonger(test)))\n + \"
auc/ap: {:.3f}/{:.3f}\".format(areaUnderCurve,averagePrecision)\n ),\n hovertemplate=(\n \"set: {:}
net:
{:}
\".format(set,net)\n + \"recall %{x}
precision: %{y:.3f}
confidence %{text:.3f}\"\n ),\n text=df[\"confidence\"]\n )\n\n if args.confidence:\n addScatterTrace(\n fig=fig,\n x=df[\"recall\"],\n y=df[\"confidence\"],\n name=\"confidence\",\n dash=\"dash\"\n )\n\n addScatterTrace(\n fig=fig,\n x=(0,1),\n y=(1,0),\n name=\"guide1\",\n color=\"black\",\n dash=\"dashdot\"\n )\n\n addScatterTrace(\n fig=fig,\n x=(0,1),\n y=(0,1),\n name=\"guide2\",\n color=\"black\",\n dash=\"dashdot\"\n )\n\n else: # draw ROC curves\n fig = createFigure(\n xaxis_title=\"fp\",\n yaxis_title=\"recall\"+(\" & confidence\" if args.confidence else \"\"),\n xaxis={\"range\":None,\"gridcolor\":\"lightGray\",\"gridwidth\":1,\"zerolinecolor\":\"black\",\"zerolinewidth\":1},\n yaxis={\"range\":(0-EPSILON,1+EPSILON),\"gridcolor\":\"lightGray\",\"gridwidth\":1,\"zerolinecolor\":\"black\",\"zerolinewidth\":1}\n )\n\n for i, file in enumerate(files):\n df = pd.read_csv(file,sep=unescape(args.delimiter),header=None,names=(\"recall\",\"fp\",\"confidence\",\"precision\"))\n\n test = path.basename(path.splitext(file)[0])\n specified,net,set,skip = parseName(test,args.scales)\n if skip:\n continue\n\n df = (\n df.groupby([\"fp\"],as_index=False,sort=False)\n .agg({\"recall\":np.max,\"confidence\":np.min,\"precision\":np.max})\n )\n\n addScatterTrace(\n fig=fig,\n x=df[\"fp\"],\n y=df[\"recall\"],\n name=(\n (\"set: {:}
net:
{:}\".format(cutLonger(set),cutLonger(net)) if specified else \"{:}\".format(cutLonger(test)))\n ),\n hovertemplate=(\n \"set: {:}
net:
{:}
\".format(set,net)\n + \"fp %{x}
recall: %{y:.3f}
confidence %{text:.3f}\"\n ),\n text=df[\"confidence\"]\n )\n\n if args.confidence:\n addScatterTrace(\n fig=fig,\n x=df[\"fp\"],\n y=df[\"confidence\"],\n name=\"confidence\",\n dash=\"dash\"\n )\n\n if args.outfile is None:\n outName = path.basename( os.getcwd() )\n else:\n outName = args.outfile\n\n outName += (\"_pr\" if args.precision else \"_roc\")\n outName += (\"_scales\" if args.scales else \"\")\n outName += (\"_confidence\" if args.confidence else \"\")\n outName += \"_\" + datetime.datetime.now().strftime(\"%y%m%d_%H%M%S_%f\")\n outName += \".html\"\n\n py.offline.plot(fig,filename=outName)\n\ndef parseName(test,scales):\n skip = False\n\n if \"net\" in test and \"set\" in test:\n specified = True\n testSplit = test.split(\".\")\n test = testSplit[0]\n net = test.split(\"net_\")[1].split(\"_set_\")[0]\n set = test.split(\"set_\")[1].split(\"_net_\")[0]\n if len(testSplit) > 1:\n if scales:\n if testSplit[1] == \"all\":\n skip = True\n set += \"_\" + (\".\".join(testSplit[1:])).upper()\n elif testSplit[1] != \"all\":\n skip = True\n\n else:\n specified = False\n net = test\n set = test\n\n return specified,net,set,skip\n\ndef isCsvFile(file):\n return path.isfile(file) and path.splitext(file)[1] == \".csv\"\n\ndef createFigure(xaxis_title,yaxis_title,xaxis,yaxis):\n return go.Figure(layout=go.Layout(\n height=None,\n plot_bgcolor=\"white\",\n xaxis_title=xaxis_title,\n yaxis_title=yaxis_title,\n xaxis=xaxis,\n yaxis=yaxis,\n legend={\"tracegroupgap\":15},\n margin={\"r\":500,\"autoexpand\":False}\n ))\n\ndef addScatterTrace(fig,x,y,name,hovertemplate=None,text=None,color=None,dash=None):\n fig.add_trace(go.Scatter(\n x=x,\n y=y,\n name=name,\n mode=\"lines\",\n hovertemplate=hovertemplate,\n line={\"color\":color,\"width\":1.5,\"dash\":dash},\n line_shape=\"linear\",\n text=text\n ))\n\ndef unescape(s):\n return bytes(s, \"utf-8\").decode(\"unicode_escape\")\n\ndef parseArguments():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-i\", \"--indir\", default=\".\")\n parser.add_argument(\"-o\", \"--outfile\", default=None)\n parser.add_argument(\"-p\", \"--precision\", action=\"store_true\")\n parser.add_argument(\"-s\", \"--scales\", action=\"store_true\")\n parser.add_argument(\"-c\", \"--confidence\", action=\"store_true\")\n parser.add_argument(\"-r\", \"--random_color\", action=\"store_true\")\n parser.add_argument(\"-d\", \"--delimiter\",default=\"\\t\")\n\n return parser.parse_args()\n\ndef htmlWrap(s,width=15):\n return \"
\".join(textwrap.wrap(s,width=width))\n\ndef cutLonger(s,n=50):\n return s if len(s) <= n else s[:n//2]+\"...\"+s[-n//2:]\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jben-hun/scripts","sub_path":"detector_evaluation_legacy/curve_plotter.py","file_name":"curve_plotter.py","file_ext":"py","file_size_in_byte":9520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30866411670","text":"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . import views\n\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path(\"\",views.index,name='index'),\n path(\"alltires/\",views.alltires,name='alltires'),\n path(\"productDetails/\",views.productDetails,name='productDetails'),\n path(\"learn/\",views.learn,name='learn'),\n path(\"search/\",views.search,name='search'),\n path(\"login/\",views.loginUser,name='login'),\n path(\"register/\",views.registerUser,name='register'),\n path('logout/',views.logoutUser,name=\"logout\"),\n path('profile/',views.profile,name=\"profile\"),\n path('address/',views.address,name=\"address\"),\n path('map/',views.map,name=\"map\"),\n path('cart/', views.cart, name='cart'),\n path('showcart/', views.showcart, name='showcart'),\n path('pluscart/', views.pluscart, name='pluscart'),\n path('minuscart/', views.minuscart, name='minuscart'),\n path('removecart/', views.removecart, name='removecart'),\n path('checkout/', views.checkout, name='checkout'),\n path('paymentdone/', views.paymentdone, name='paymentdone'),\n path('orders/', views.orders, name='orders'),\n path('contact/', views.contact, name='contact'),\n path(\"postComment\",views.postComment,name=\"postComment\"),\n path(\"filters/\",views.filters,name=\"filters\"),\n path(\"tiresize/\",views.TireSize,name=\"TireSize\"),\n path(\"vehicle/\",views.Vehicle,name=\"Vehicle\"),\n\n]\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)","repo_name":"kamranBaloch1/TireDjango","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14131945969","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the viralAdvertising function below.\ndef viralAdvertising(n):\n total_liked = 0\n curr = 5\n \n for _ in range(1,n+1):\n total_liked += math.floor(curr/2)\n curr = math.floor(curr/2)*3\n \n return total_liked\n \n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n result = viralAdvertising(n)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"ShanjinurIslam/HackerRank","sub_path":"viral_adverting.py","file_name":"viral_adverting.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"11676562389","text":"import os\nimport json\nimport platform\nimport datetime\nfrom pprint import pprint\nfrom libraries.gen_class import Class\nfrom PyQt5 import QtCore, QtGui\n\n##################################################################################################\n# Assign all the attriubtes from other settings files to the settings Class \n# Custom settings over written after all asignements \n##################################################################################################\n\nsettings = Class()\nlist_of_extra_settings = []\n\nfor extra_settings in list_of_extra_settings:\n for attribute in dir(extra_settings):\n if '__' not in attribute:\n setattr(settings, attribute, getattr(extra_settings, attribute))\n\n\n##################################################################################################\n# Defaults (likely overwritten by custom setting)\n##################################################################################################\n\nsettings.experiments = {'LB': 'LiteBRID', 'SA': 'Simons Array', 'SO': 'Simons Observatory'}\nsettings.loaded_experiment = 'SA'\n\nif 'Linux' in platform.platform():\n settings.platform = 'Linux'\n settings.load_still_image_as_camera = True\n settings.user = os.path.expanduser('~').split('/')[-1]\nelif 'Windows' in platform.platform():\n settings.platform = 'Windows'\n settings.user = os.path.expanduser('~').split('\\\\')[-1]\n\n# Query Stuff\ntoday = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')\nsettings.today = datetime.datetime.now()\n\n# Layout Stuff\nsettings.title = 'BoloCalc Gui'\nsettings.small_font = QtGui.QFont(\"Times\", 8)\nsettings.med_font = QtGui.QFont(\"Times\", 11)\nsettings.large_font = QtGui.QFont(\"Times\", 14)\nsettings.larger_font = QtGui.QFont(\"Times\", 16)\nsettings.huge_font = QtGui.QFont(\"Times\", 24)\nsettings.giant_font = QtGui.QFont(\"Times\", 32)\n\n\n# DICTIONARIES \n########################################################################################################################\n##################################################################################################\n# Custom settings over written after all asignements \n##################################################################################################\nif os.path.exists('./all_settings/custom_settings.py'):\n from .custom_settings import custom_settings\n for attribute in dir(custom_settings):\n if hasattr(settings, attribute) and not '__' in attribute:\n setattr(settings, attribute, getattr(custom_settings, attribute))\n","repo_name":"chill90/BoloCalc","sub_path":"bcg/bcg_gui_settings/all_settings.py","file_name":"all_settings.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"3060753231","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nDo a rolling restart based on the status of the instances:\n\nFields to consider:\n\n u'configStalenessStatus': u'STALE'\n u'type': u'NODEMANAGER'\n u'maintenanceMode': False\n u'roleState': u'STARTED'\n u'entityStatus': u'GOOD_HEALTH'\n u'healthSummary': u'GOOD'\n u'name': u'yarn-NODEMANAGER-708c5c3ed00070ee1d7cf9b2a39fa0d0'\n\n\"\"\"\nfrom __future__ import print_function\nimport requests\nimport re\nimport time\nimport sys\nimport argparse\n\n# Disable Unverified HTTPS request warnings\nimport urllib3\nurllib3.disable_warnings()\n\n\nAPI_URL = 'https://:7183/api/v31'\nUSER = ''\nPASSWD = ''\nDEFAULT_DELAY = 30\n\n\ndef extract_node_identifier(host):\n \"\"\"Extract the node identifier part in a way it can be used to sort them\"\"\"\n m = re.search(r'c(\\d+)-(\\d+)', host)\n if m:\n rack = m.group(1)\n node = m.group(2)\n return int('{:02d}{:02d}'.format(int(rack), int(node)))\n else:\n raise ValueError('Incorrect hostname: {}'.format(host))\n\n\ndef get_instance_information(instance):\n r = requests.get(\n '{}/clusters/cluster/services/{}/roles/{}'.format(\n API_URL, instance['serviceRef']['serviceName'], instance['name']),\n verify=False, auth=(USER, PASSWD))\n return r.json()\n\n\ndef is_healthy(instance):\n status = get_instance_information(instance)\n if (status['configStalenessStatus'] == 'FRESH' and\n status['roleState'] == 'STARTED' and\n status['entityStatus'] == 'GOOD_HEALTH' and\n status['healthSummary'] == 'GOOD'):\n return True\n else:\n return False\n\n\ndef restart(instance):\n \"\"\"Restart a given role instance\"\"\"\n r = requests.post('{}/clusters/cluster/services/{}/roleCommands/restart'\n .format(API_URL, instance['serviceRef']['serviceName']),\n verify=False,\n auth=(USER, PASSWD),\n json={\"items\": [instance['name']]})\n return r.json()\n\n\ndef restart_instances(instances, state='healthy', delay=DEFAULT_DELAY):\n \"\"\"Restart the given instances that are not in maintainance mode\n\n By default only healthy instances are restarted, this behaviour can be\n changed using the state parameter.\n\n :param state: it can have the following values:\n 'healthy': only instances thar are healthy are restarted (default)\n 'stale': only healthy instances with stale configurations are restarted\n 'all': all instances are restarted\n :param delay: seconds to wait between instance restarts\n \"\"\"\n # We want to restart the cluster using hostname order\n nodes = sorted(instances, key=extract_node_identifier)\n\n print('Restarting role {} instances'.format(state))\n for node in nodes:\n instance = instances[node]\n if (check_instance_state(instance, state)):\n print('Restarting', node)\n result = restart(instance)\n if len(result['errors']) != 0:\n print('Error restarting instance on', node)\n print('This is the error message returned by the command:')\n print(result['errors'])\n sys.exit(1)\n while not is_healthy(instance):\n print('Waiting for {} to be ready'.format(node))\n time.sleep(30)\n print('{} is now ready waiting additional {} seconds'\n .format(node, delay))\n time.sleep(delay)\n else:\n print('Skipping', node)\n\n\ndef check_instance_state(instance, state):\n \"\"\"Check if the given instance is in the given state\n\n :param state: it can have the following values:\n 'healthy': only instances thar are healthy are restarted (default)\n 'stale': only healthy instances with stale configurations are restarted\n 'all': all instances are restarted\n \"\"\"\n if state == 'healthy':\n state_condition = (\n instance['maintenanceMode'] is False and\n instance['roleState'] == 'STARTED' and\n instance['entityStatus'] == 'GOOD_HEALTH' and\n instance['healthSummary'] == 'GOOD'\n )\n elif state == 'stale':\n state_condition = (\n instance['configStalenessStatus'] == 'STALE' and\n instance['maintenanceMode'] is False and\n instance['roleState'] == 'STARTED' and\n instance['entityStatus'] == 'GOOD_HEALTH' and\n instance['healthSummary'] == 'GOOD'\n )\n elif state == 'all':\n state_condition = (instance['maintenanceMode'] is False)\n return state_condition\n\n\ndef list_services():\n \"\"\"List the available services in the cluster\"\"\"\n response = requests.get(API_URL + '/clusters/cluster/services/',\n verify=False, auth=(USER, PASSWD)).json()\n services = [s['name'] for s in response['items']]\n return services\n\n\ndef list_types(service):\n \"\"\"List the available types in a given service\"\"\"\n response = requests.get('{}/clusters/cluster/services/{}/roles/'.format(API_URL, service),\n verify=False, auth=(USER, PASSWD)).json()\n types = set([s['type'] for s in response['items']])\n return types\n\n\ndef parse_args():\n \"\"\"Parse command arguments\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('service', choices=list_services(),\n help='Service to restart')\n parser.add_argument('-d', '--delay', default=DEFAULT_DELAY,\n help='Delay between instance restarts')\n parser.add_argument('-s', '--staled', action='store_true',\n help='Restart only instances with staled configuration')\n parser.add_argument('-f', '--force', action='store_true',\n help='Restart all instances even if they are unhealthy')\n parser.add_argument('-t', '--type', default=None,\n help='Instance type to restart for the given service')\n parser.add_argument('-l', '--list-types', action='store_true',\n help='List instace types for the given service')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parse_args()\n\n service = args.service\n\n instance_type = args.type\n\n delay = float(args.delay)\n\n if args.list_types:\n types = list_types(service)\n print('\\n'.join(types))\n sys.exit(0)\n\n if not args.type:\n print('For the given service specify the instance type that you want to restart.')\n types = list_types(service)\n print('\\n'.join(types))\n sys.exit(0)\n\n # Service\n service = requests.get('{}/clusters/cluster/services/{}/roles/'.format(API_URL, service),\n verify=False, auth=(USER, PASSWD)).json()\n # All role instances of this service\n instances = service['items']\n\n # Selected role instances to restart based on type of instance\n if instance_type:\n selected = [i for i in instances if i['type'] == instance_type]\n else:\n selected = instances\n # Associate instance and host\n selected_by_host = {i['hostRef']['hostname']: i for i in selected}\n # We assume that no host has more than one role instance\n assert len(selected) == len(selected_by_host)\n\n if args.staled:\n restart_instances(selected_by_host, state='staled', delay=delay)\n elif args.force:\n restart_instances(selected_by_host, state='all', delay=delay)\n else:\n restart_instances(selected_by_host, state='healthy', delay=delay)\n","repo_name":"javicacheiro/cdh-rolling-restart","sub_path":"rolling_restart.py","file_name":"rolling_restart.py","file_ext":"py","file_size_in_byte":7526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"33342518922","text":"from collections import Counter\n\nimport numpy as np\nfrom imblearn.over_sampling import SMOTE\nfrom imblearn.base import BaseSampler\n\n\nclass StaticSMOTE(BaseSampler):\n \"\"\"\n Static SMOTE implementation:\n\n Reference:\n Fernández-Navarro, F., Hervás-Martínez, C., Gutiérrez, P.A.: A dynamic over-sampling\n procedure based on sensitivity for multi-class problems. Pattern Recognit. 44, 1821–1833\n (2011)\n \"\"\"\n def __init__(self):\n super().__init__()\n self._sampling_type = 'over-sampling'\n\n def _fit_resample(self, X, y):\n \"\"\"\n Performs resampling\n\n :param X:\n two dimensional numpy array (number of samples x number of features) with float numbers\n :param y:\n one dimensional numpy array with labels for rows in X\n :return:\n Resampled X and y as numpy arrays\n \"\"\"\n cnt = Counter(y)\n min_class = min(cnt, key=cnt.get)\n X_original, y_original = X.copy(), y.copy()\n X_resampled, y_resampled = X.copy(), y.copy()\n\n M = len(list(cnt.keys()))\n for _ in range(M):\n sm = SMOTE(sampling_strategy={min_class: cnt[min_class] * 2})\n X_smote, y_smote = sm.fit_resample(X_original, y_original)\n X_added_examples = X_smote[y_smote == min_class][cnt[min_class]:, :]\n X_resampled = np.vstack([X_resampled, X_added_examples])\n y_resampled = np.hstack([y_resampled, y_smote[y_smote == min_class][cnt[min_class]:]])\n cnt = Counter(y_resampled)\n min_class = min(cnt, key=cnt.get)\n\n return X_resampled, y_resampled\n","repo_name":"damian-horna/multi-imbalance","sub_path":"multi_imbalance/resampling/static_smote.py","file_name":"static_smote.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"52"} +{"seq_id":"70685967204","text":"from pprint import pprint\nfrom PyPDF2 import PdfReader\nfrom Utilities.Utils import *\nimport json\n\nclass SunYearbook:\n \"\"\"\n Class to simplify the SUN yearbook download process\n \"\"\"\n\n def __init__(self, url, path, faculty):\n self.url = url\n self.faculty = faculty\n self.filename = os.path.join(path, faculty + \".pdf\")\n\n def fileExists(self):\n \"\"\"\n Checks if the file exists\n\n :return: True if the file exists, False otherwise\n \"\"\"\n\n return os.path.isfile(self.filename)\n\n def download(self):\n \"\"\"\n Downloads the yearbook for the given faculty\n \"\"\"\n\n downloadFile(self._buildDownloadUrl(), self.filename, 1024)\n\n def _buildDownloadUrl(self):\n \"\"\"\n Builds the download url for the given faculty\n :return: The download url\n \"\"\"\n\n return self.url + self.faculty + \".pdf\"\n\n def getOutline(self):\n \"\"\"\n Gets the outline of the yearbook as a nested list of titles\n\n :return: The outline of the yearbook\n \"\"\"\n\n pdf = PdfReader(self.filename)\n\n outlines = pdf.getOutlines()\n\n return self._parseOutline(outlines)\n\n def _parseOutline(self, outline):\n \"\"\"\n Parses the outline of the yearbook into a dictionary or destinations and page numbers\n\n :param outline: The outline of the yearbook\n :return: The parsed outline\n \"\"\"\n\n parsed_outline = []\n\n for item in outline:\n if isinstance(item, list):\n parsed_outline.append(self._parseOutline(item))\n else:\n parsed_outline.append(item.title)\n\n return parsed_outline\n \n\n# Tester\nif __name__ == \"__main__\":\n\n\n from Data.HemisDBManager import HemisDBManager\n HemisDB = HemisDBManager(\"Data/HemisDB.json\")\n\n pprint(HemisDB.degrees)\n\n # find the required modules for a degree from the calendar\n degree = \"BSc\"\n major = \"Computer Science\"\n minor = \"Data Science\"\n faculty = \"Science\"\n","repo_name":"DylanKirbs/Academic-Committee","sub_path":"SunYearbooks.py","file_name":"SunYearbooks.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31603078839","text":"from .dimension_value_details import DimensionValueDetails\nfrom oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass StaticDimensionValue(DimensionValueDetails):\n \"\"\"\n Static type of dimension value (passed as-is).\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new StaticDimensionValue object with values from keyword arguments. The default value of the :py:attr:`~oci.sch.models.StaticDimensionValue.kind` attribute\n of this class is ``static`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param kind:\n The value to assign to the kind property of this StaticDimensionValue.\n Allowed values for this property are: \"jmesPath\", \"static\"\n :type kind: str\n\n :param value:\n The value to assign to the value property of this StaticDimensionValue.\n :type value: str\n\n \"\"\"\n self.swagger_types = {\n 'kind': 'str',\n 'value': 'str'\n }\n\n self.attribute_map = {\n 'kind': 'kind',\n 'value': 'value'\n }\n\n self._kind = None\n self._value = None\n self._kind = 'static'\n\n @property\n def value(self):\n \"\"\"\n **[Required]** Gets the value of this StaticDimensionValue.\n The data extracted from the specified dimension value (passed as-is). Unicode characters only.\n For information on valid dimension keys and values, see :func:`metric_data_details`.\n\n\n :return: The value of this StaticDimensionValue.\n :rtype: str\n \"\"\"\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"\n Sets the value of this StaticDimensionValue.\n The data extracted from the specified dimension value (passed as-is). Unicode characters only.\n For information on valid dimension keys and values, see :func:`metric_data_details`.\n\n\n :param value: The value of this StaticDimensionValue.\n :type: str\n \"\"\"\n self._value = value\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/sch/models/static_dimension_value.py","file_name":"static_dimension_value.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"71409108006","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'crosswordPuzzle' function below.\n#\n# The function is expected to return a STRING_ARRAY.\n# The function accepts following parameters:\n# 1. STRING_ARRAY crossword\n# 2. STRING words\n#\ndef position_finder(crossword, word):\n\n n = len(crossword)\n m = len(crossword[0])\n for i in range(n):\n for j in range(m):\n if crossword[i][j] == word[0] or crossword[i][j] == '-': #either empty or filled\n l = len(word)\n does_it_fit = True\n for k in range(1, l): # first look horizontally\n if j+k < m and (crossword[i][j+k] == '-' or crossword[i][j+k] ==word[k]):\n continue\n else:\n does_it_fit = False\n \n if does_it_fit and j+l<=m:\n return [i,j,'h']\n \n does_it_fit = True\n for k in range(1, l): # now vertically:\n if i+k < n and (crossword[i+k][j] == '-' or crossword[i+k][j] == word[k]):\n continue\n else:\n does_it_fit = False\n\n if does_it_fit and i+l<=n:\n return [i,j,'v']\n\n return [-1,-1,'n']\n\ndef is_filled(crossword):\n \n n = len(crossword)\n m = len(crossword[0])\n # print(crossword)\n for i in range(n):\n for j in range(m):\n if crossword[i][j] == '+':\n return False\n \n return True\ndef print_crossword(crossword):\n n = len(crossword)\n m = len(crossword[0])\n # print(crossword)\n for i in range(n):\n print(crossword[i])\n \ndef fill_the_puzzle(words, crossword, filled_words):\n\n print(filled_words)\n if len(filled_words) == len(words):\n print(\"x\")\n return True\n else:\n for i in range(len(words)):\n if words[i] not in filled_words:\n x,y,direction = position_finder(crossword, words[i])\n print(x,y, direction)\n if x != -1:\n \n l = len(words[i])\n prev = []\n if direction == 'h':\n for j in range(l):\n prev.append(crossword[x][y+j])\n crossword[x][y+j] = words[i][j]\n else:\n for j in range(l):\n prev.append(crossword[x+j][y])\n crossword[x+j][y] = words[i][j]\n # print_crossword(crossword)\n filled_words.append(words[i])\n \n if fill_the_puzzle(words, crossword, filled_words):\n return True\n \n filled_words.pop()\n \n if direction == 'h':\n for j in range(l):\n crossword[x][y+j] = prev[j]\n else:\n for j in range(l):\n crossword[x+j][y] = prev[j]\n return False\n\n \ndef crosswordPuzzle(crossword, words):\n # Write your code here\n \n # start from a word look for -'s up or down\n crossword = [list(crossword[i]) for i in range(len(crossword)) ]\n \n words = words.split(\";\")\n fill_the_puzzle(words, crossword, [])\n print_crossword(crossword)\n crossword = [\"\".join(crossword[i]) for i in range(len(crossword))]\n return crossword\n# example \n# crossword = [list(\"+-++++++++\"),\n# list(\"+-++++++++\"),\n# list(\"+-++++++++\"),\n# list(\"+-----++++\"),\n# list(\"+-+++-++++\"),\n# list(\"+-+++-++++\"),\n# list(\"+++++-++++\"),\n# list(\"++------++\"),\n# list(\"+++++-++++\"),\n# list(\"+++++-++++\")]\n# words = \"LONDON;DELHI;ICELAND;ANKARA\".split(\";\")\n\n# crosswordPuzzle(crossword, words)\n \nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n crossword = []\n\n for _ in range(10):\n crossword_item = input()\n crossword.append(crossword_item)\n\n words = input()\n\n result = crosswordPuzzle(crossword, words)\n\n fptr.write('\\n'.join(result))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"aneessh18/mission_intern","sub_path":"cross_words.py","file_name":"cross_words.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30796100449","text":"# Get set up\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nimg = cv2.imread(\"Capture3.JPG\")\r\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Fixes color read issue\r\n\r\nav3 = cv2.blur(img,(3,3))\r\nav5 = cv2.blur(img,(5,5))\r\n\r\n# Plot the image. This code is excluded for the rest of the article.\r\nplt.gcf().set_size_inches(25,25)\r\nplt.subplot(131),plt.imshow(img),plt.title('Original')\r\nplt.xticks([]), plt.yticks([])\r\nplt.subplot(132),plt.imshow(av3),plt.title('Averaging - 3x3')\r\nplt.xticks([]), plt.yticks([])\r\nplt.subplot(133),plt.imshow(av5),plt.title('Averaging - 5x5')\r\nplt.xticks([]), plt.yticks([])\r\nplt.show()\r\n\r\ndef noisy(image):\r\n\r\n row,col,ch = image.shape\r\n s_vs_p = 0.0005\r\n amount = 0.04\r\n out = np.copy(image)\r\n # Salt mode\r\n num_salt = np.ceil(amount * image.size * s_vs_p)\r\n coords = [np.random.randint(0, i - 1, int(num_salt))\r\n for i in image.shape]\r\n for i in coords:\r\n print(i)\r\n out[i] = [np.random.randint(0,245),np.random.randint(0,245),np.random.randint(0,245)]\r\n \r\n # Pepper mode\r\n num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))\r\n coords = [np.random.randint(0, i - 1, int(num_pepper))\r\n for i in image.shape]\r\n for i in coords:\r\n print(i)\r\n out[i] = [np.random.randint(0,245),np.random.randint(0,245),np.random.randint(0,245)]\r\n return out\r\n\r\nimg = cv2.imread(\"Capture3.JPG\")\r\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n\r\nfrom wand.image import Image\r\n \r\n# Read image using Image() function\r\nwith Image(filename =\"koala.jpeg\") as img:\r\n \r\n # Generate noise image using noise() function\r\n img.noise(\"laplacian\", attenuate = 1.0)\r\nnoisy_img = noisy(img)\r\nmedian = cv2.medianBlur(img,5)\r\n\r\nplt.gcf().set_size_inches(25,25)\r\nplt.subplot(131),plt.imshow(noisy_img),plt.title('Original')\r\nplt.xticks([]), plt.yticks([])\r\nplt.subplot(132),plt.imshow(median),plt.title('median')\r\nplt.xticks([]), plt.yticks([])\r\nplt.show()\r\n\r\n\r\n","repo_name":"Ahmed-Ihsan/Computer-Vision","sub_path":"B1.py","file_name":"B1.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"39620782731","text":"'''\nexperiment.py: part of expfactory package\nFunctions to work with javascript experiments\n\n'''\n\nfrom expfactory.utils import find_directories, remove_unicode_dict\nfrom glob import glob\nimport filecmp\nimport json\nimport re\nimport os\n\n\ndef get_validation_fields():\n '''get_validation_fields\n Returns a list of tuples (each a field)\n\n ..note:: \n\n specifies fields required for a valid json\n (field,value,type)\n field: the field name\n value: indicates minimum required entires\n 0: not required, no warning\n 1: required, not valid\n 2: not required, warning \n type: indicates the variable type\n\n '''\n return [(\"run\",1,list),\n (\"name\",2,str), \n (\"contributors\",0,str),\n (\"time\",1,int), \n (\"notes\",0,str),\n (\"reference\",2,str), \n (\"exp_id\",1,str),\n (\"cognitive_atlas_task_id\",2,str),\n (\"experiment_variables\",0,list),\n (\"publish\",1,str),\n (\"deployment_variables\",0,str),\n (\"template\",1,str)]\n\ndef notvalid(reason):\n print(reason)\n return False\n\ndef dowarning(reason):\n print(reason)\n\ndef get_valid_templates():\n return ['jspsych','survey','phaser','custom']\n\ndef get_acceptable_values(package_name):\n acceptable_values = dict()\n acceptable_values[\"jspsych\"] =[\"display_element\",\n \"on_finish\",\n \"on_trial_start\",\n \"on_trial_finish\",\n \"on_data_update\",\n \"show_progress_bar\",\n \"max_load_time\",\n \"skip_load_check\",\n \"fullscreen\",\n \"default_iti\"]\n acceptable_values[\"survey\"] = [\"fullscreen\"]\n\n return acceptable_values[package_name]\n\n\ndef validate(experiment_folder=None,warning=True):\n '''validate\n :param experiment_folder: full path to experiment folder with config.json\n :param warning: issue a warning for empty fields with level 2 (warning)\n\n ..note::\n\n takes an experiment folder, and looks for validation based on:\n \n - config.json\n - files existing specified in config.json\n\n All fields should be defined, but for now we just care about run scripts\n \n '''\n if experiment_folder==None:\n experiment_folder=os.path.abspath(os.getcwd())\n\n try:\n meta = load_experiment(experiment_folder)\n if meta == False:\n return notvalid(\"%s is not an experiment.\" %(experiment_folder))\n experiment_name = os.path.basename(experiment_folder)\n except:\n return notvalid(\"%s: config.json is not loadable.\" %(experiment_folder))\n\n if len(meta)>1:\n return notvalid(\"%s: config.json has length > 1, not valid.\" %(experiment_folder))\n fields = get_validation_fields()\n valid_templates = get_valid_templates()\n\n for field,value,ftype in fields:\n\n # Field must be in the keys if required\n if field not in meta[0].keys() and value == 1:\n return notvalid(\"%s: config.json is missing required field %s\" %(experiment_name,field))\n else:\n if value == 2:\n if warning == True:\n dowarning(\"WARNING: config.json is missing field %s: %s\" %(field,experiment_name))\n\n if field == \"exp_id\":\n # Tag must correspond with folder name\n if meta[0][field] != experiment_name:\n return notvalid(\"%s: exp_id parameter %s does not match folder name.\" %(experiment_name,meta[0][field]))\n\n # name cannot have special characters, only _ and letters/numbers\n if not re.match(\"^[a-z0-9_]*$\", meta[0][field]): \n return notvalid(\"%s: exp_id parameter %s has invalid characters, only lowercase [a-z],[0-9], and _ allowed.\" %(experiment_name,meta[0][field]))\n\n # Check if experiment is production ready\n if field == \"publish\":\n if meta[0][field] == \"False\":\n return notvalid(\"%s: config.json specifies not production ready.\" %experiment_name)\n\n # Run must be a list of strings\n if field == \"run\":\n # Is it a list?\n if not isinstance(meta[0][field],ftype):\n return notvalid(\"%s: field %s must be %s\" %(experiment_name,field,ftype))\n # Is an experiment.js defined\n # Is each script in the list a string?\n for script in meta[0][field]:\n # If we have a single file, is it in the experiment folder?\n if len(script.split(\"/\")) == 1:\n if not os.path.exists(\"%s/%s\" %(experiment_folder,script)):\n return notvalid(\"%s: %s is specified in config.json but missing.\" %(experiment_name,script))\n # Do we have an external script? It must be https\n if re.search(\"http\",script) and not re.search(\"https\",script):\n return notvalid(\"%s: external script %s must be https.\" %(experiment_name,script))\n \n\n # Below is for required parameters\n if value == 1:\n if meta[0][field] == \"\":\n return notvalid(\"%s: config.json must be defined for field %s\" %(experiment_name,field))\n # Field value must have minimum of value entries\n if not isinstance(meta[0][field],list):\n tocheck = [meta[0][field]]\n else:\n tocheck = meta[0][field]\n if len(tocheck) < value:\n return notvalid(\"%s: config.json must have >= %s for field %s\" %(experiment_name,value,field))\n \n # Below is for warning parameters\n elif value == 2:\n if meta[0][field] == \"\":\n if warning == True:\n dowarning(\"WARNING: config.json is missing value for field %s: %s\" %(field,experiment_name))\n\n # Check the experiment template, currently valid are jspsych and survey\n if field == \"template\":\n if meta[0][field] not in valid_templates:\n return notvalid(\"%s: we currently only support %s experiments.\" %(experiment_name,\",\".join(valid_templates)))\n\n # Jspsych javascript experiment\n if meta[0][field] == \"jspsych\":\n if \"run\" in meta[0]:\n if \"experiment.js\" not in meta[0][\"run\"]:\n return notvalid(\"%s: experiment.js is not defined in run\" %(experiment_name))\n else:\n return notvalid(\"%s: config.json is missing required field run\" %(experiment_name))\n\n # Material Design light survey\n elif meta[0][field] == \"survey\":\n if not os.path.exists(\"%s/survey.tsv\" %(experiment_folder)):\n return notvalid(\"%s: required survey.tsv for template survey not found.\" %(experiment_name))\n\n # Phaser game\n elif meta[0][field] == \"phaser\":\n if not os.path.exists(\"%s/Run.js\" %(experiment_folder)):\n return notvalid(\"%s: required Run.js main game file not found.\" %(experiment_name))\n if \"run\" not in meta[0][\"deployment_variables\"]:\n return notvalid(\"%s: 'run' (code) is required in deployment_variables\" %(experiment_name))\n\n # Validation for deployment_variables\n if field == \"deployment_variables\":\n if \"deployment_variables\" in meta[0]:\n if \"jspsych_init\" in meta[0][field]:\n check_acceptable_variables(experiment_name,meta[0][field],\"jspsych\",\"jspsych_init\")\n \n elif \"survey\" in meta[0][field]:\n check_acceptable_variables(experiment_name,meta[0][field],\"survey\",\"material_design\")\n\n return True\n\n\ndef check_acceptable_variables(experiment_name,field_dict,template,field_dict_key):\n '''check_acceptable_variables takes a field (eg, meta[0][field]) that has a dictionary, and some template key (eg, jspsych) and makes sure the keys of the dictionary are within the allowable for the template type (the key).\n :param experiment_name: the name of the experiment\n :param field_dict: the field value from the config.json, a dictionary\n :param field_dict_key: a key to look up in the field_dict, which should contain a dictionary of {\"key\":\"value\"} variables\n :param template: the key name, for looking up acceptable values using get_acceptable_values\n '''\n acceptable_values = get_acceptable_values(template)\n for acceptable_var,acceptable_val in field_dict[field_dict_key].items():\n if acceptable_var not in acceptable_values:\n return notvalid(\"%s: %s is not an acceptable value for %s.\" %(experiment_name,acceptable_var,field_dict_key))\n\n # Jspsych specific validation\n if template == \"jspsych\":\n # Variables that must be boolean\n if acceptable_var in [\"show_progress_bar\",\"fullscreen\",\"skip_load_check\"]:\n check_boolean(experiment_name,acceptable_val,acceptable_var) \n\n # Variables that must be numeric\n if acceptable_var in [\"default_iti\",\"max_load_time\"]:\n if isinstance(acceptable_val,str) or isinstance(acceptable_val,bool):\n return notvalid(\"%s: %s is not an acceptable value for %s in %s. Must be numeric.\" %(experiment_name,acceptable_val,acceptable_var,field_dict_key))\n\n elif template == \"survey\":\n # Variables that must be boolean\n if acceptable_var in [\"show_progress_bar\",\"fullscreen\",\"skip_load_check\"]:\n check_boolean(experiment_name,acceptable_val,acceptable_var) \n\ndef check_boolean(experiment_name,value,variable_name):\n '''check_boolean checks if a value is boolean\n :param experiment_name: the name of the experiment\n :param value: the value to check\n :param variable_name: the name of the variable (the key being indexed in the dictionary)\n '''\n if value not in [True,False]:\n return notvalid(\"%s: %s is not an acceptable value for %s. Must be true/false.\" %(experiment_name,value,varialbe_name))\n\n\ndef get_experiments(experiment_repo, load=False, warning=True, repo_type=\"experiments\"):\n '''get_experiments\n return loaded json for all valid experiments from an experiment folder\n :param experiment_repo: full path to the experiments repo\n :param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to the experiments\n :param repo_type: tells the user what kind of task is being parsed, default is \"experiments,\" but can also be \"surveys\" when called by get_surveys\n '''\n experiments = find_directories(experiment_repo)\n valid_experiments = [e for e in experiments if validate(e,warning)]\n print(\"Found %s valid %s\" %(len(valid_experiments),repo_type))\n if load == True:\n valid_experiments = load_experiments(valid_experiments)\n return valid_experiments\n\n\ndef load_experiments(experiment_folders):\n '''load_experiments\n a wrapper for load_experiment to read multiple experiments\n :param experiment_folders: a list of experiment folders to load, full paths\n '''\n experiments = []\n if isinstance(experiment_folders,str):\n experiment_folders = [experiment_folders]\n for experiment_folder in experiment_folders:\n exp = load_experiment(experiment_folder)\n experiments.append(exp)\n return experiments\n\n\ndef load_experiment(experiment_folder):\n '''load_experiment:\n reads in the config.json for an\n :param experiment folder: full path to experiment folder\n '''\n fullpath = os.path.abspath(experiment_folder)\n configjson = \"%s/config.json\" %(fullpath)\n if not os.path.exists(configjson):\n return notvalid(\"config.json could not be found in %s\" %(experiment_folder))\n try: \n with open(configjson,\"r\") as filey:\n meta = json.load(filey)\n meta = remove_unicode_dict(meta[0])\n return [meta]\n except ValueError as e:\n print(\"Problem reading config.json, %s\" %(e))\n raise\n\ndef find_changed(new_repo,comparison_repo,return_experiments=True,repo_type=\"experiments\"):\n '''find_changed returns a list of changed files or experiments between two repos\n :param new_repo: the updated repo - any new files, or changed files, will be returned\n :param comparison_repo: the old repo to compare against. A file changed or missing in this repo in the new_repo indicates it should be tested\n :param return_experiments: return experiment folders. Default is True. If False, will return complete file list\n ''' \n # First find all experiment folders in current repo\n experiment_folders = get_experiments(new_repo,load=False,warning=False,repo_type=repo_type)\n file_list = []\n # Find all files\n for experiment_folder in experiment_folders:\n for root, dirnames, filenames in os.walk(experiment_folder):\n for filename in filenames:\n file_list.append(os.path.join(root, filename))\n # Compare against master\n changed_files = []\n for contender_file in file_list:\n old_file = contender_file.replace(\"%s/expfactory-%s\" %(os.environ[\"HOME\"],repo_type),comparison_repo)\n # If the old file exists, check if it's changed\n if os.path.exists(old_file):\n if not filecmp.cmp(old_file,contender_file):\n changed_files.append(contender_file)\n # If it doesn't exist, we check\n else:\n changed_files.append(contender_file)\n\n # Find differences with compare\n print(\"Found files changed: %s\" %(\",\".join(changed_files)))\n\n if return_experiments == True:\n return list(set([os.path.dirname(x.strip(\"\\n\")) for x in changed_files if os.path.dirname(x.strip(\"\\n\")) != \"\"]))\n \n return changed_files\n\n\ndef make_lookup(experiment_list,key_field):\n '''make_lookup\n returns dict object to quickly look up query experiment on exp_id\n :param experiment_list: a list of query (dict objects)\n :param key_field: the key in the dictionary to base the lookup key (str)\n :returns lookup: dict (json) with key as \"key_field\" from query_list \n '''\n lookup = dict()\n for single_experiment in experiment_list:\n lookup_key = single_experiment[0][key_field]\n lookup[lookup_key] = single_experiment[0]\n return lookup\n","repo_name":"expfactory/expfactory-python","sub_path":"expfactory/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":14570,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"14384499310","text":"import os\nimport sys\nimport copy\nimport logging\nimport subprocess\nimport string\nimport random\n\nfrom pgpipe.vcf_reader_func import checkFormat\nfrom pgpipe.bcftools import check_bcftools_for_errors\nfrom pgpipe.misc import confirm_executable\n\ndef log_vcftools_reference ():\n\n # Write the log header\n logging.info('Please Reference alongside the PPP:\\n')\n\n # Write the reference\n logging.info('Danecek, P. et al. The variant call format and VCFtools. '\n 'Bioinformatics 27, 2156-2158 (2011).')\n\ndef check_for_vcftools_output (vcftools_output):\n '''\n Checks for the previous vcftools output\n\n Confirms that neither a previous vcftools log or output file exists.\n\n Parameters\n ----------\n vcftools_output : str\n Specifies the output filename to be checked\n\n Raises\n ------\n IOError\n If the vcftools output file exists\n IOError\n If the vcftools log file exists\n\n '''\n # Check if output file already exists\n if os.path.isfile(vcftools_output):\n raise IOError('VCF output file already exists')\n\n logging.info('Output file assigned')\n\n # Check if log file already exists\n if os.path.isfile(vcftools_output + '.log'):\n raise IOError('Log file already exists')\n\n logging.info('Log file assigned')\n\ndef assign_vcftools_unique_prefix (output_prefix, output_format, random_seed = None, string_size = 6, string_limit = 10, assignment_limit = 100):\n\n '''\n Assigns a unique vcftools filename prefix\n\n Used to assign a unique filename prefix for vcftools jobs. If an\n output file with the same prefix and suffix, either from previous \n or ongoing jobs, this function will generate a unique prefix. This \n function is only used if no prefix has been specified by the user.\n\n Parameters\n ----------\n output_prefix : str\n Specifies the filename prefix\n output_format : str\n Specifies the file format suffix\n random_seed : int, str, optional\n Specifies the random seed\n string_size : int, optional\n Specifies the number of character in the random string\n string_limit : int, optional\n Specifies the character limit of the random string\n assignment_limit : int, optional\n Specifies a limit the number of assignment attempts\n\n Returns\n -------\n updated_prefix: str\n Specifies the unqiue prefix\n\n\n Raises\n ------\n Exception\n If unable to assign a unique filename\n\n '''\n\n # Assign the random seed, with a string or int\n random.seed(random_seed)\n\n # Assign the assignment counter, used to avoid infinite loops\n assignment_counter = 0\n\n # Generate a random string\n random_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for digit in range(string_size))\n\n # Holds the updated prefix that will be returned when unique\n updated_prefix = output_prefix + '.' + random_string\n\n # Loop until a unique filename is created\n while os.path.isfile(updated_prefix + output_format):\n\n # Add to the assignment counter\n assignment_counter += 1\n\n # Check if assignment counter has reached it's limit\n if assignment_counter > assignment_limit:\n\n # Set the assignment counter to zero\n assignment_counter = 0\n\n # Add to the string size\n string_size += 1\n\n # Check if string size has reached it's limit and report the error\n if string_size > string_limit:\n raise Exception('Unable to assign unique intermediate output')\n\n # Generate a random string\n random_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for digit in range(string_size))\n\n # Holds the updated prefix that will be returned when unique\n updated_prefix = output_prefix + '.' + random_string\n\n # Return the intermediate output filename\n return updated_prefix\n\ndef assign_vcftools_filename_prefix (output_prefix, output_format, output_filename):\n\n '''\n Assigns a vcftools prefix using a filename\n\n Used to assign a unique prefix for vcftools jobs using the user\n specified filename. This is to avoid output file with the same \n prefix, either from previous or ongoing jobs. This function is \n only used if no prefix has been specified by the user.\n\n Parameters\n ----------\n output_prefix : str\n Specifies the filename prefix\n output_format : str\n Specifies the file format suffix\n output_filename : str\n Specifies the filename specified by the user\n\n Returns\n -------\n unique_prefix: str\n Specifies the unqiue prefix\n\n Raises\n ------\n Exception\n If unable to assign a unique filename\n\n '''\n\n # List to hold the complete file path\n file_path_list = []\n\n # Split the filename\n split_file_path = os.path.split(output_filename)\n\n while split_file_path[1]:\n\n # Add the split path section to the file path list\n file_path_list = [split_file_path[1]] + file_path_list\n\n # Split the filename\n split_file_path = os.path.split(split_file_path[0])\n\n # Save the updated prefix\n updated_prefix = ''.join(file_path_list).replace('.','')\n\n # Check if the file already exists \n if os.path.isfile(updated_prefix + output_format):\n raise Exception('Unable to assign prefix output. %s already exists' % (updated_prefix + output_format))\n\n return updated_prefix\n\ndef check_vcftools_for_errors (vcftools_stderr):\n '''\n Checks the vcftools stderr for errors\n\n Parameters\n ----------\n vcftools_stderr : str\n vcftools stderr\n\n Raises\n ------\n IOError\n If vcftools stderr returns an error\n '''\n\n # Returns True if the job completed without error\n if 'Run Time' in str(vcftools_stderr):\n pass\n\n # Print output for vcftools if error is detected\n elif 'Error' in str(vcftools_stderr):\n # Splits log into list of lines\n vcftools_stderr_lines = vcftools_stderr.splitlines()\n # Prints the error(s)\n raise Exception('\\n'.join((output_line for output_line in vcftools_stderr_lines if output_line.startswith('Error'))))\n\n # Print output if not completed and no error found. Unlikely to be used, but included.\n else:\n raise Exception(vcftools_stderr)\n\ndef produce_vcftools_output (output, filename, append_mode = False, strip_header = False):\n '''\n Creates the vcftools output file\n\n This function will create an output file from the vcftools stdout.\n Please run `check_vcftools_for_errors` prior to check that vcftools\n finished without error.\n\n Parameters\n ----------\n output : str\n vcftools stdout\n filename : str\n Specifies the filename for the output file\n append_mode : bool\n Used to create a single output file from multiple calls\n strip_header : bool\n Used to remove the header if not needed\n\n Returns\n -------\n output : file\n vcftools output file\n\n '''\n\n # Check if the header should be stripped\n if strip_header:\n output = ''.join(output.splitlines(True)[1:])\n\n # Check if single log file is required from multiple calls\n if append_mode:\n vcftools_log_file = open(filename,'a')\n else:\n vcftools_log_file = open(filename,'w')\n\n vcftools_log_file.write(str(output))\n vcftools_log_file.close()\n\ndef produce_vcftools_log (output, filename, append_mode = False):\n '''\n Creates the vcftools log file\n\n This function will create a log file from the vcftools stderr. Please\n run `check_vcftools_for_errors` prior to check that vcftools finished\n without error.\n\n Parameters\n ----------\n output : str\n vcftools stderr\n filename : str\n Specifies the filename for the log file\n append_mode : bool\n Used to create a single log file from multiple calls\n\n Returns\n -------\n output : file\n vcftools log file\n\n '''\n # Check if single log file is required from multiple calls\n if append_mode:\n vcftools_log_file = open(filename + '.log','a')\n else:\n vcftools_log_file = open(filename + '.log','w')\n\n vcftools_log_file.write(str(output))\n vcftools_log_file.close()\n\ndef assign_vcftools_input_arg (filename):\n '''\n Confirms file format for vcftools\n\n Parameters\n ----------\n filename : str\n Specifies the input filename of unknown format\n\n Returns\n -------\n list\n Returns vcftools input command for `filename`\n\n Raises\n ------\n IOError\n If filename is an unknown file format\n '''\n\n # True if file extensions is recognized by vcftools\n if filename.endswith('.vcf') or filename.endswith('.vcf.gz') or filename.endswith('.bcf'):\n # Assign the associated input command\n if filename.endswith('.vcf'):\n return ['--vcf', filename]\n elif filename.endswith('.vcf.gz'):\n return ['--gzvcf', filename]\n elif filename.endswith('.bcf'):\n return ['--bcf', filename]\n\n # True if file extension is unknown or not recognized\n else:\n\n # Checks if the file is unzipped, bgzipped, or gzipped\n vcfname_format = checkFormat(filename)\n\n # Assign the associated input command, or return an error.\n if vcfname_format == 'vcf':\n return ['--vcf', filename]\n elif vcfname_format == 'bgzip':\n return ['--gzvcf', filename]\n elif vcfname_format == 'bcf':\n return ['--bcf', filename]\n else:\n raise Exception('Unknown VCF file format')\n\ndef check_bgzip_for_errors (bgzip_stderr):\n '''\n Checks the bgzip stderr for errors\n\n Parameters\n ----------\n bgzip_stderr : str\n bgzip stderr\n\n Raises\n ------\n IOError\n If bgzip stderr returns an error\n '''\n\n if bgzip_stderr:\n raise IOError('Error occured while compressing the vcf file')\n\ndef bgzip_decompress_vcfgz (vcfgz_filename, out_prefix = None, keep_original = False):\n '''\n Converts a vcf.gz to vcf\n\n The function automates bgzip to decompress a vcf.gz file into a vcf\n\n Parameters\n ----------\n vcfgz_filename : str\n The file name of the vcf.gz file to be decompressed\n out_prefix : str\n Output file prefix (i.e. filename without extension)\n keep_original : bool\n Specifies if the original file should be kept\n\n Raises\n ------\n IOError\n Error in creating the compressed file\n '''\n\n # Run bgzip with stdout piped to file\n if keep_original or out_prefix:\n\n if out_prefix:\n\n # Assign the bgzip filename\n vcf_filename = out_prefix + '.vcf'\n\n else:\n\n # Seperate into path and filename\n split_path, split_filename = os.path.split(vcfgz_filename)\n\n # Remove any file extensions\n vcf_basename = split_filename.split(os.extsep)[0] + '.vcf'\n\n # Join path and filename\n vcf_filename = os.path.join(split_path, vcf_basename)\n\n # Create the output file\n vcf_file = open(vcf_filename, 'w')\n\n # bgzip subprocess call\n bgzip_call = subprocess.Popen(['bgzip', '-dc', vcfgz_filename], stdout = vcf_file, stderr = subprocess.PIPE)\n\n # Run bgzip normally\n else:\n\n # bgzip subprocess call\n bgzip_call = subprocess.Popen(['bgzip', '-d', vcfgz_filename], stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n\n # Save the stdout and stderr from bgzip\n bgzip_out, bgzip_err = bgzip_call.communicate()\n\n # Check that output file was compressed correctly\n check_bgzip_for_errors(bgzip_err)\n\n # Delete input when also using an output prefix\n if out_prefix and not keep_original:\n os.remove(vcfgz_filename)\n\ndef bgzip_compress_vcf (vcf_filename, out_prefix = '', keep_original = False):\n '''\n Converts a vcf to vcf.gz\n\n The function automates bgzip to compress a vcf file into a vcf.gz\n\n Parameters\n ----------\n vcf_filename : str\n The file name of the vcf file to be compressed\n keep_original : bool\n Specifies if the original file should be kept\n\n Raises\n ------\n IOError\n Error in creating the compressed file\n '''\n\n # Confirm where the specifed executable is located\n bgzip_path = confirm_executable('bgzip')\n\n # Check if the executable was found\n if not bgzip_path:\n raise IOError('bgzip not found. Please confirm the executable is installed')\n\n # Compress and keep the original file\n if keep_original or out_prefix:\n\n if out_prefix:\n\n # Assign the filename\n vcfgz_filename = out_prefix + '.vcf.gz'\n\n else:\n\n # Seperate into path and filename\n split_path, split_filename = os.path.split(vcfgz_filename)\n\n # Remove any file extensions\n vcfgz_basename = split_filename.split(os.extsep)[0] + '.vcf.gz'\n\n # Join path and filename\n vcfgz_filename = os.path.join(split_path, vcfgz_basename)\n\n\n # Create the output file\n vcfgz_file = open(vcfgz_filename, 'w')\n\n # bgzip subprocess call\n bgzip_call = subprocess.Popen([bgzip_path, '-c', vcf_filename], stdout = vcfgz_file, stderr = subprocess.PIPE)\n\n # Compress and do not keep the original file\n else:\n\n # bgzip subprocess call\n bgzip_call = subprocess.Popen([bgzip_path, vcf_filename], stdout = subprocess.PIPE, stderr = subprocess.PIPE)\n\n # Save the stdout and stderr from bgzip\n bgzip_out, bgzip_err = bgzip_call.communicate()\n\n # Check that output file was compressed correctly\n check_bgzip_for_errors(bgzip_err)\n\ndef cvt_vcftools_site_to_bed (vcftools_out_str):\n # Check if str in the header\n if 'CHROM' not in vcftools_out_str or 'POS' not in vcftools_out_str:\n # Split the line into a list\n vcftools_out_data = vcftools_out_str.strip().split('\\t')\n # Calc chromEnd\n chrom_end = copy.deepcopy(vcftools_out_data[1])\n # Convert the chromStart to chromStart0\n vcftools_out_data[1] = int(vcftools_out_data[1]) - 1\n # Add chrom_end to the list\n vcftools_out_data = vcftools_out_data + [chrom_end]\n # Return the list as a string (with newline element)\n return '\\t'.join(map(str, vcftools_out_data)) + '\\n'\n else:\n # Remove the header\n return ''\n\ndef pipe_vcftools_to_bed_file (vcftools_call_args, output_filename):\n\n '''\n Pipes site-file output of vcftools to a bed formmated file\n\n The purpose of this function is to avoid creating large uncompressed\n vcf files by directly piping the output of vcftools to bgzip. This\n results in creating a vcf.gz file without any intermediates.\n\n Parameters\n ----------\n vcftools_call_args : list\n vcftools arguments\n output_filename : str\n Filename of the bed file\n\n '''\n\n # Confirm where the specifed executable is located\n vcftools_path = confirm_executable('vcftools')\n\n # Check if the executable was found\n if not vcftools_path:\n raise IOError('vcftools not found. Please confirm the executable is installed')\n\n # Open vcftools pipe\n vcftools_call = subprocess.Popen([vcftools_path, '--stdout'] + list(map(str, vcftools_call_args)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # Create the bed file\n bed_output = open(output_filename, 'w')\n\n try:\n # Iterate the vcftools stdout unless error occurs\n for vcftools_stdout_line in iter(vcftools_call.stdout.readline, b''):\n bed_output.write(cvt_vcftools_site_to_bed(vcftools_stdout_line))\n # Close the bed file\n bed_output.close()\n except:\n # Close the bed file\n bed_output.close()\n # Delete the file\n os.remove(output_filename)\n\n # Wait for vctools to finish\n vcftools_call.wait()\n\n # Close the vcftools stdout\n vcftools_call.stdout.close()\n\n # Read the vcftools stderr\n vcftools_stderr = vcftools_call.stderr.read()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n vcftools_stderr = vcftools_stderr.decode()\n\n # Check that the log file was created correctly\n check_vcftools_for_errors(vcftools_stderr)\n\n logging.info('vcftools call complete')\n\n return vcftools_stderr\n\ndef pipe_vcftools_bgzip (vcftools_call_args, output_filename):\n '''\n Pipes the output of vcftools to bgzip\n\n The purpose of this function is to avoid creating large uncompressed\n vcf files by directly piping the output of vcftools to bgzip. This\n results in creating a vcf.gz file without any intermediates.\n\n Parameters\n ----------\n vcftools_call_args : list\n vcftools arguments\n output_filename : str\n Filename of the compressed vcf file\n\n '''\n\n # Confirm where the specifed executable is located\n vcftools_path = confirm_executable('vcftools')\n\n # Check if the executable was found\n if not vcftools_path:\n raise IOError('vcftools not found. Please confirm the executable is installed')\n\n vcftools_call = subprocess.Popen([vcftools_path, '--stdout'] + list(map(str, vcftools_call_args)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # Create bgzip output file\n bgzip_output = open(output_filename, 'wb')\n\n # Confirm where the specifed executable is located\n bgzip_path = confirm_executable('bgzip')\n\n # Check if the executable was found\n if not bgzip_path:\n raise IOError('bgzip not found. Please confirm the executable is installed')\n\n # bgzip subprocess call\n bgzip_call = subprocess.Popen([bgzip_path], stdin = vcftools_call.stdout, stdout = bgzip_output, stderr = subprocess.PIPE)\n\n # Wait for vctools to finish\n vcftools_call.wait()\n\n # Close the vcftools stdout\n vcftools_call.stdout.close()\n\n # Read the vcftools stderr\n vcftools_stderr = vcftools_call.stderr.read()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n vcftools_stderr = vcftools_stderr.decode()\n\n # Check that the log file was created correctly\n check_vcftools_for_errors(vcftools_stderr)\n\n # Wait for bgzip to finish\n bgzip_call.wait()\n\n # Close the compressed vcf file\n bgzip_output.close()\n\n # Save the stderr from bgzip, stdout = None\n bgzip_stdout, bgzip_stderr = bgzip_call.communicate()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n bgzip_stderr = bgzip_stderr.decode()\n\n # Check that output file was compressed correctly\n check_bgzip_for_errors(bgzip_stderr)\n\n logging.info('vcftools and bgzip calls complete')\n\n return vcftools_stderr\n\ndef pipe_vcftools_bcftools (vcftools_call_args, output_filename):\n '''\n Pipes the output of vcftools to bcftools\n\n The purpose of this function is to avoid the vcftools command\n --recode-bcf that may result in malformed BCF files. To avoid large\n uncompressed intermediates, this function pipes the stdout of vcftools\n to bcftools.\n\n Parameters\n ----------\n vcftools_call_args : list\n vcftools arguments\n output_filename : str\n Filename of the BCF file\n\n '''\n\n # Confirm where the specifed executable is located\n vcftools_path = confirm_executable('vcftools')\n\n # Check if the executable was found\n if not vcftools_path:\n raise IOError('vcftools not found. Please confirm the executable is installed')\n\n vcftools_call = subprocess.Popen([vcftools_path, '--stdout'] + list(map(str, vcftools_call_args)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # Holds the arguments to convert to BCF format\n convert_args = ['view', '-O', 'b']\n\n # Create bgzip output file\n bcftools_output = open(output_filename, 'wb')\n\n # Confirm where the specifed executable is located\n bcftools_path = confirm_executable('bcftools')\n\n # Check if the executable was found\n if not bcftools_path:\n raise IOError('bcftools not found. Please confirm the executable is installed')\n\n # bcftools subprocess call\n bcftools_call = subprocess.Popen([bcftools_path] + convert_args, stdin = vcftools_call.stdout, stdout = bcftools_output, stderr = subprocess.PIPE)\n\n # Wait for vctools to finish\n vcftools_call.wait()\n\n # Close the vcftools stdout\n vcftools_call.stdout.close()\n\n # Read the vcftools stderr\n vcftools_stderr = vcftools_call.stderr.read()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n vcftools_stderr = vcftools_stderr.decode()\n\n # Check that the log file was created correctly\n check_vcftools_for_errors(vcftools_stderr)\n\n # Wait for bgzip to finish\n bcftools_call.wait()\n\n # Save the stderr from bgzip, stdout = None\n bcftools_stdout, bcftools_stderr = bcftools_call.communicate()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n bcftools_stderr = bcftools_stderr.decode()\n\n # Check that output file was compressed correctly\n check_bcftools_for_errors(bcftools_stderr)\n\n logging.info('vcftools and bcftools calls complete')\n\n return vcftools_stderr\n\ndef pipe_vcftools_to_file (vcftools_call_args, output_filename, append_output = False):\n '''\n Pipes file output of vcftools to a standard file\n\n The function calls vcftools. Returns the stderr of vcftools to\n create log file of the call. The function may be used to append multiple\n calls to vcftools to a single file\n\n Parameters\n ----------\n vcftools_call_args : list\n vcftools arguments\n append_output : bool\n The output file should be written in append mode\n\n Returns\n -------\n vcftools_err : str\n vcftools log output\n\n Raises\n ------\n Exception\n If vcftools stderr returns an error\n '''\n\n # Confirm where the specifed executable is located\n vcftools_path = confirm_executable('vcftools')\n\n # Check if the executable was found\n if not vcftools_path:\n raise IOError('vcftools not found. Please confirm the executable is installed')\n\n # Open vcftools pipe\n vcftools_call = subprocess.Popen([vcftools_path, '--stdout'] + list(map(str, vcftools_call_args)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # Check if the output should be opened in append mode\n if append_output:\n # Create the output file (in append mode)\n output_file = open(output_filename, 'a')\n else:\n # Create the output file (in write mode)\n output_file = open(output_filename, 'w')\n\n try:\n # Create iterator of the vcftools stdout\n stdout_iter = iter(vcftools_call.stdout.readline, b'')\n\n # Check if the output is being appended and the file is empty\n if append_output and os.stat(output_filename).st_size != 0:\n # Skip the header if the file isn't empty and appending\n next(stdout_iter)\n\n # Iterate the vcftools stdout\n for vcftools_stdout_line in stdout_iter:\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n vcftools_stdout_line = vcftools_stdout_line.decode()\n\n output_file.write(vcftools_stdout_line)\n\n # Close the bed file\n output_file.close()\n\n except:\n # Close the bed file\n output_file.close()\n # Delete the file\n os.remove(output_filename)\n\n raise Exception('vcftools to python pipe error')\n\n # Wait for vctools to finish\n vcftools_call.wait()\n\n # Close the vcftools stdout\n vcftools_call.stdout.close()\n\n # Read the vcftools stderr\n vcftools_stderr = vcftools_call.stderr.read()\n\n # Close the vcftools stderr\n vcftools_call.stderr.close()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n vcftools_stderr = vcftools_stderr.decode()\n\n # Check that the log file was created correctly\n check_vcftools_for_errors(vcftools_stderr)\n\n logging.info('vcftools call complete')\n\n return vcftools_stderr\n\ndef standard_vcftools_call (vcftools_call_args):\n '''\n Calls vcftools\n\n The function calls vcftools. Returns the stderr of vcftools to\n create log file of the call.\n\n Parameters\n ----------\n vcftools_call_args : list\n vcftools arguments\n\n Returns\n -------\n vcftools_out : str\n vcftools call output\n vcftools_err : str\n vcftools log output\n\n Raises\n ------\n Exception\n If vcftools stderr returns an error\n '''\n\n # Confirm where the specifed executable is located\n vcftools_path = confirm_executable('vcftools')\n\n # Check if the executable was found\n if not vcftools_path:\n raise IOError('vcftools not found. Please confirm the executable is installed')\n\n # vcftools subprocess call without stdout\n vcftools_call = subprocess.Popen([vcftools_path] + list(map(str, vcftools_call_args)), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n # Wait for vcftools to finish\n vcftools_stdout, vcftools_stderr = vcftools_call.communicate()\n\n # Check if code is running in python 3\n if sys.version_info[0] == 3:\n # Convert bytes to string\n vcftools_stderr = vcftools_stderr.decode()\n\n logging.info('vcftools call complete')\n\n # Check that the log file was created correctly\n check_vcftools_for_errors(vcftools_stderr)\n\n return vcftools_stderr\n\ndef call_vcftools (vcftools_call_args, output_format = None, output_filename = None, append_mode = False):\n '''\n Calls vcftools\n\n The function calls vcftools. Returns the stderr of vcftools to\n create log file of the call.\n\n Parameters\n ----------\n vcftools_call_args : list\n vcftools arguments\n output_format : str, optional\n Allows for specific formats to be given which may result in\n the stdout of vcftools being piped to another script or \n program\n output_filename : str, optional\n The output filename to be assigned if the stdout of vcftools \n is piped\n append_mode : bool, optional\n Allows for vcftools stdout to append a file. Currently \n incompatible with output_format\n\n Returns\n -------\n vcftools_err : str\n vcftools log output\n\n Raises\n ------\n Exception\n If vcftools stderr returns an error\n ''' \n\n # Check if an output format was specified\n if output_format and output_filename: \n\n # Check if the output is a bgzipped vcf\n if output_format == 'vcf.gz':\n\n # Pipe vcftools stdout to bgzip to create a bgzipped vcf\n vcftools_err = pipe_vcftools_bgzip(vcftools_call_args, output_filename)\n\n # Check if the output is a bcf\n elif output_format == 'bcf':\n\n # Pipe vcftools stdout to bgzip to create a bgzipped vcf\n vcftools_err = pipe_vcftools_bcftools(vcftools_call_args, output_filename)\n\n # Check if the output is a bed-based file\n elif output_format in ['removed_bed','kept_bed']:\n\n # Pipe vcftools stdout to bed file\n vcftools_err = pipe_vcftools_to_bed_file(vcftools_call_args, output_filename)\n\n # Check if the output is another format, that does not require a pipe\n else:\n \n # Pipe the vcftools stdout to a standard file\n vcftools_err = pipe_vcftools_to_file(vcftools_call_args, output_filename)\n\n # Check if a filename but no format was specified \n elif output_filename:\n\n # Check if the output should be written in append mode\n if append_mode:\n\n # Pipe the vcftools stdout to a standard file and allow appending\n vcftools_err = pipe_vcftools_to_file(vcftools_call_args, output_filename, append_output = True)\n\n else:\n\n # Pipe the vcftools stdout to a standard file\n vcftools_err = pipe_vcftools_to_file(vcftools_call_args, output_filename)\n\n # If no format or filename is given, run vcftools with just the passed arguments\n else:\n\n # Call vcftools under standard conditions, if not \n vcftools_err = standard_vcftools_call(vcftools_call_args)\n\n # Return the log\n return vcftools_err\n\n","repo_name":"jaredgk/PPP","sub_path":"pgpipe/vcftools.py","file_name":"vcftools.py","file_ext":"py","file_size_in_byte":29755,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"35346386088","text":"import requests\nimport json\nimport os\n\n\nimage_path = os.path.join(os.getcwd(), \"img1.png\")\n\nENDPOINT = \"http://127.0.0.1:8000/api/status/\"\n\n# def do(method='get', data={}, id=41, is_json=True):\ndef do(method='get', data={}, is_json=True):\n\theaders = {}\n\tif is_json:\n\t\theaders['content-type']=\"application/json\"\n\t\tdata=json.dumps(data)\t\t\n\t# r =requests.request(method, ENDPOINT + \"?id=\" +str(id), data=data)\n\tr =requests.request(method, ENDPOINT , data=data, headers=headers)\n\tprint(r.text)\n\treturn r\n\n\ndef do_img(method='get', data={}, is_json=True, img_path=None):\n\theaders = {}\n\tif is_json:\n\t\theaders['content-type']=\"application/json\"\n\t\tdata=json.dumps(data)\t\t\n\t# r =requests.request(method, ENDPOINT + \"?id=\" +str(id), data=data)\n\tif img_path is not None:\n\t\twith open(image_path, 'rb') as image:\n\t\t\tfile_data = {\"image\":image}\t#----> since to match the field in serializer\n\t\t\tr =requests.request(method, ENDPOINT , data=data, headers=headers, files=file_data)\n\tr =requests.request(method, ENDPOINT , data=data, headers=headers)\n\tprint(r.text)\n\treturn r\t\n\n\n# do(data={\"id\":37})\t\n\n# do(method='delete' ,data={\"id\":35})\n\n\n# do(method='put', data={\"id\":35 , \"content\":\"Some new content\", \"user\":1 })\n\n\n# do(method='post', data={ \"content\":\"Some new content by post\", \"user\":1 })\n\ndo_img(method='post', data={ \"content\":\"Some new content by post\", \"user\":1 }, is_json=False, img_path=image_path) #--->since image is derived from file \n\n\n","repo_name":"abhilashajay-dev/cfeapi","sub_path":"scripts/cfe_rest_framework_api.py","file_name":"cfe_rest_framework_api.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41386487966","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2023/4/24 22:24\n# @Author : 刘秉星\n# @Site :\n# @File : main.py\n# @Software: PyCharm\nimport torch\nfrom torch import nn\nimport torch.optim as optim\nfrom lenet5 import LeNet5\nfrom dataset import get_data_loaders,get_data_loaders_VGG\nfrom train_test import train, test\nimport matplotlib.pyplot as plt\nimport torchvision.models as models\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n\n'''\n# 加载预训练的ResNet模型\nmodel = models.resnet50(pretrained=True)\n# 修改最后的全连接层以适应19个类别\nnum_features = model.fc.in_features\nmodel.fc = torch.nn.Linear(num_features, 19)\nmodel = model.to(device)\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\ntrain_loader, test_loader = get_data_loaders('train', 'test')\n'''\n\n\n# 加载预训练的VGGNet模型\nmodel = models.vgg16_bn(pretrained=True)\n\n# 修改最后的全连接层以适应19个类别\nnum_features = model.classifier[6].in_features\nmodel.classifier[6] = torch.nn.Linear(num_features, 19)\n\nmodel = model.to(device)\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\n\ntrain_loader, test_loader = get_data_loaders_VGG('train', 'test')\n\n\n'''\n使用LeNet5的\nmodel = LeNet5().to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)\ntrain_loader, test_loader = get_data_loaders('./train', './test')\n'''\n\n\nnum_epochs = 50\ntrain_losses = []\ntrain_accuracies = []\ntest_losses = []\ntest_accuracies = []\n\nfor epoch in range(num_epochs):\n train_loss, train_acc = train(model, train_loader, criterion, optimizer, device)\n test_loss, test_acc = test(model, test_loader, criterion, device)\n train_losses.append(train_loss)\n train_accuracies.append(train_acc)\n test_losses.append(test_loss)\n test_accuracies.append(test_acc)\n print(f'Epoch {epoch + 1}/{num_epochs}: Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}, Test Loss: {test_loss:.4f}, Test Acc: {test_acc:.4f}')\n\ntorch.save(model.state_dict(), 'vggnet_model.pth')\n\n# 绘制准确度和损失曲线\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(range(1, num_epochs + 1), train_losses, label=\"Train Loss\")\nplt.plot(range(1, num_epochs + 1), test_losses, label=\"Test Loss\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss VGG\")\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(range(1, num_epochs + 1), train_accuracies, label=\"Train Acc\")\nplt.plot(range(1, num_epochs + 1), test_accuracies, label=\"Test Acc\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy VGG\")\nplt.legend()\n\nplt.show()","repo_name":"ZenithNUC/MTC2023-train","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5900658770","text":"#!/usr/bin/env python\n\nfrom AdventOfCode import read_data\n\n\ndef day_v1(data):\n \"\"\" Find the shortest path from the start location to the end location. \"\"\"\n # This v1 solution uses an A* search algorithm adapted from a previous Advent of Code solution.\n\n def neighbors(point, height_map):\n \"\"\" Returns the neighbor points that are directly reachable from 'point'. \"\"\"\n x, y = point\n map_width = len(height_map[0])\n map_height = len(height_map)\n\n current_height = height_map[y][x]\n\n neighs = []\n if x + 1 < map_width:\n if height_map[y][x + 1] <= (current_height + 1):\n neighs.append((x + 1, y))\n if x - 1 >= 0:\n if height_map[y][x - 1] <= (current_height + 1):\n neighs.append((x - 1, y))\n if y + 1 < map_height:\n if height_map[y + 1][x] <= (current_height + 1):\n neighs.append((x, y + 1))\n if y - 1 >= 0:\n if height_map[y - 1][x] <= (current_height + 1):\n neighs.append((x, y - 1))\n return neighs\n\n def get_shortest_distance(start_location, end_location, height_map):\n # Start of A* search algorithm.\n came_from = {\n start_location: None} # Dict of which location was the previous on the best currently known path to the key node.\n visible = set([start_location]) # Which nodes are visible and need to be scanned.\n cost_from_start = {} # Value of each item is the so-far best found cost to that node from the start.\n cost_total_est = {} # Value of each item is the best estimated cost of a path through that node.\n cost_from_start[start_location] = 0\n cost_total_est[start_location] = 1\n\n while visible:\n current = min(visible, key=lambda x: cost_total_est[x])\n if current == end_location:\n # Found our way to end.\n break\n\n visible.remove(current)\n for neigh in neighbors(current, height_map):\n relative_g = cost_from_start[current] + 1\n if neigh not in cost_from_start or relative_g < cost_from_start[neigh]:\n # We found a better path to this point. Update the stats.\n cost_from_start[neigh] = relative_g\n cost_total_est[neigh] = relative_g + 1\n came_from[neigh] = current\n # Add it to the list of points to be scanned.\n visible.add(neigh)\n\n best_distance = None\n if end_location in cost_from_start:\n best_distance = cost_from_start[end_location]\n return best_distance\n\n # Read in the map. a-z is the height, S and E are the start and end locations.\n height_map = []\n possible_starts = []\n for y, line in enumerate(data):\n row = []\n for x, char in enumerate(line):\n if char == 'S':\n start_location = x, y\n height = 0\n elif char == 'E':\n end_location = x, y\n height = 25\n else:\n assert char in \"abcdefghijklmnopqrstuvwxyz\"\n height = ord(char) - ord('a')\n if char == 'a':\n possible_starts.append((x, y))\n row.append(height)\n height_map.append(tuple(row))\n height_map = tuple(height_map)\n\n best = get_shortest_distance(start_location, end_location, height_map)\n print(f\"Answer for {__name__[1:5]} day {__name__[9:]} part 1: {best}\")\n\n for start_location in possible_starts:\n path_distance = get_shortest_distance(start_location, end_location, height_map)\n if path_distance is not None:\n best = min(best, path_distance)\n print(f\"Answer for {__name__[1:5]} day {__name__[9:]} part 2: {best}\")\n\n\ndef day_v2(data):\n \"\"\" Find the shortest path from the start location to the end location. \"\"\"\n # This v2 version replaces the A* search with a distance map created from an exhaustive backwards walk from the end\n # location. This is faster even for part1 of the puzzle.\n\n def neighbors_that_reach(point, height_map):\n \"\"\" Return list of adjacent points which can reach the specified point. \"\"\"\n x, y = point\n current_height = height_map[y][x]\n neighbors = []\n for dx, dy in [(0, -1), (-1, 0), (1, 0), (0, 1)]:\n if 0 <= x+dx < len(height_map[0]) and 0 <= y+dy < len(height_map):\n neighbor_height = height_map[y+dy][x+dx]\n if neighbor_height + 1 >= current_height:\n neighbors.append((x+dx, y+dy))\n return neighbors\n\n def mark_distances(start, height_map):\n \"\"\" Return a dict of all locations which can reach the specified point, where the value is the distance.\"\"\"\n # This is a breadth-first search of all possible points that can reach 'point'. It starts from point and walks\n # backwards to see which neighbors can reach point.\n known_distances = {start: 0}\n current_distance = 0\n\n visible = neighbors_that_reach(start, height_map)\n while visible:\n next_visible = []\n current_distance += 1\n\n # Mark all points currently visible with their distance.\n for point in visible:\n if point in known_distances:\n continue\n # Because this is a breadth-first search, the shortest distance will be the first time we see the point.\n known_distances[point] = current_distance\n their_neighbors = neighbors_that_reach(point, height_map)\n next_visible.extend(their_neighbors)\n visible = next_visible\n return known_distances\n\n # Read in the map. a-z is the height, S and E are the start and end locations.\n height_map = []\n possible_starts = []\n for y, line in enumerate(data):\n row = []\n for x, char in enumerate(line):\n if char == 'S':\n start_location = x, y\n height = 0\n elif char == 'E':\n end_location = x, y\n height = 25\n else:\n assert char in \"abcdefghijklmnopqrstuvwxyz\"\n height = ord(char) - ord('a')\n if char == 'a':\n possible_starts.append((x, y))\n row.append(height)\n height_map.append(tuple(row))\n height_map = tuple(height_map)\n\n # Do all the mapping.\n distances = mark_distances(end_location, height_map)\n\n answer1 = distances[start_location]\n # print(f\"Answer for {__name__[1:5]} day {__name__[9:]} part 1: {distances[start_location]}\")\n\n best = answer1\n for point in possible_starts:\n best = min(best, distances.get(point, best))\n # print(f\"Answer for {__name__[1:5]} day {__name__[9:]} part 2: {best}\")\n\n return answer1, best\n\n\ndef main():\n data = read_data(__file__)\n return day_v2(data)\n\n\nexpected_answers = 425, 418\n","repo_name":"ViridisWolf/AdventOfCode","sub_path":"y2022/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":7029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23754310000","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('age', models.IntegerField()),\n ('email', models.EmailField(max_length=75)),\n ('branch', models.CharField(max_length=30)),\n ('about', models.TextField()),\n ('profile_pic', models.ImageField(upload_to=b'login/photos/')),\n ('cover_pic', models.ImageField(upload_to=b'login/photos/')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"thewisebro/django_assignment","sub_path":"login/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73615921124","text":"from bot import config\n\n\ndef validate_config():\n assert config.environment in {\"live\", \"sandbox\"}\n\n assert isinstance(\n config.database, str\n ), f\"database must be a string, got {type(config.database)}\"\n\n assert isinstance(\n config.database_connection_string, str\n ), f\"database_connection_string must be a string, got {type(config.database_connection_string)}\"\n\n for range_key, value in config.stop_limit_step.items():\n assert value > 0, f\"stop_limit_step for {range_key} must be positive\"\n\n min_dca_amount = 2.5\n assert (\n config.dca_amount_per_transaction >= min_dca_amount\n ), f\"dca_amount must be greater than {min_dca_amount}\"\n\n assert (\n config.monthly_reserved_amount_for_dca > 0\n ), \"monthly_reserved_amount_for_dca must be positive\"\n\n assert (\n config.limit_order_budget_per_month\n ), \"limit_order_budget_per_month must be positive\"\n\n for currency_key in config.limit_order_amount_per_transaction:\n ascending_limit_order_amount_per_transaction_keys = sorted(\n config.limit_order_amount_per_transaction[currency_key].keys()\n )\n last_value = float(\"inf\")\n for range_key in ascending_limit_order_amount_per_transaction_keys:\n limit_at_range = config.limit_order_amount_per_transaction[currency_key][\n range_key\n ]\n assert (\n limit_at_range < last_value\n ), f\"{range_key} must be lesser than {last_value} for currency {currency_key}\"\n last_value = limit_at_range\n\n for range_key, value in config.max_limit_order_price.items():\n assert value > 0, f\"max_limit_order_price for {range_key} must be positive\"\n\n for range_key, value in config.min_limit_order_price.items():\n assert value >= 0, f\"min_limit_order_price for {range_key} must be non-negative\"\n\n for range_key, value in config.tkn_pair_min_order_amount.items():\n assert value > 0, f\"tkn_pair_min_order_amount for {range_key} must be positive\"\n\n assert (\n config.limit_order_multiplier_for_stop_limit_step_adjustment_below_market_price\n > 0\n ), \"limit_order_multiplier_for_stop_limit_step_adjustment_below_market_price must be positive\"\n\n assert (\n config.max_tkn_b_market_price_in_tkn_a > 0\n ), \"max_tkn_b_market_price_in_tkn_a must be positive\"\n\n assert isinstance(\n config.max_tkn_b_market_price_in_tkn_a, (int, float)\n ), \"max_tkn_b_market_price_in_tkn_a must be int or float\"\n\n assert (\n config.market_order_price_percentage_delta_to_highest_limit_order > 1\n ), \"market_order_price_percentage_delta_to_highest_limit_order must be greater than 1\"\n\n assert (\n config.market_order_price_percentage_delta_to_last_trade_price > 1\n ), \"market_order_price_percentage_delta_to_last_trade_price must be greater than 1\"\n\n assert (\n config.market_order_aggressiveness_factor > 1\n ), \"market_order_aggressiveness_factor must be greater than 1\"\n\n assert isinstance(config.client_order_id, str), \"client_order_id must be a string\"\n print(\"Config values validated successfully\")\n","repo_name":"foorenxiang/gemini-hybrid-dca-dip-buying-bot","sub_path":"bot/validate_config.py","file_name":"validate_config.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"24699462932","text":"import json\nfrom pydoc_data.topics import topics\nfrom sys import api_version\nimport pymongo\nimport threading\nimport sensor_data\nfrom pydoc import doc\n\n\nclient = \"mongodb://ias_mongo_user:ias_password@cluster0-shard-00-00.doy4v.mongodb.net:27017,cluster0-shard-00-01.doy4v.mongodb.net:27017,cluster0-shard-00-02.doy4v.mongodb.net:27017/ias_database?ssl=true&replicaSet=atlas-ybcxil-shard-0&authSource=admin&retryWrites=true&w=majority\"\ndb_name = \"ias_database\"\nclient = pymongo.MongoClient(client)\nmydb = client[db_name]\ninstancesdb = mydb[\"SensorInstances\"]\n\n\n# client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n# mydb = client[\"SensorDatabase\"]\n# instancesdb = mydb[\"SensorInstances\"]\n# types = mydb[\"SensorTypes\"]\n\n# Deprecated\n# def register_sensor_type(sensor_type):\n# types = mydb[\"SensorTypes\"]\n# types.insert_one(sensor_type)\n\n################################ DATABASE CREATION and DROPPING ################################\n\ndef databaseExists():\n databases = client.list_database_names()\n # if 'SensorDatabase' in databases:\n if db_name in databases:\n # return True\n for collection in mydb.list_collection_names():\n if collection == 'SensorInstances':\n return True\n # else:\n return False\n # register_sensors_from_json('sensor_config.json')\n\n\ndef drop_db():\n instancesdb.drop()\n # client.drop_database(\"SensorDatabase\")\n client.drop_database(mydb)\n\n\ndef getCount(collectionObj):\n '''Returns no.of documents in the given collection object'''\n return collectionObj.count_documents({})\n\n################################ REGISTRATION OF SENSORS ########################################\n\ndef register_sensor_instance(sensor_instance):\n '''Stores the given sensor_instance in the collection'''\n count = getCount(instancesdb)\n sensor_instance['_id'] = count+1\n instancesdb.insert_one(sensor_instance)\n topic_name = sensor_instance[\"sensor_type\"] + '_' + str(sensor_instance['_id'])\n return topic_name\n\n################################# RETRIEVING DETAILS OF ALL SENSORS ######################\n\ndef get_all_sensor_types():\n sensor_types = set()\n for document in instancesdb.find():\n sensor_types.add(document['sensor_type'])\n sensor_types = list(sensor_types)\n return sensor_types\n\n\ndef get_all_sensor_instances():\n sensor_instances = []\n for document in instancesdb.find():\n # instance = {\"sensor_type\": document['sensor_type'], \"id\": document['_id']}\n sensor_instances.append(document)\n return sensor_instances\n\n############################### RETRIEVING BASED ON LOCATION ############################\n\ndef get_sensor_types(sensor_location):\n sensor_types = set()\n for document in instancesdb.find():\n if document['sensor_location'] == sensor_location:\n sensor_types.add(document['sensor_type'])\n sensor_types = list(sensor_types)\n return sensor_types\n \n\ndef get_sensor_instances(sensor_type, sensor_location):\n sensor_instances = []\n for document in instancesdb.find():\n if document['sensor_type'] == sensor_type and document['sensor_location'] == sensor_location:\n sensor_name = document['sensor_type'] + '_' + str(document['_id'])\n sensor_instances.append(sensor_name)\n return sensor_instances\n\n#################################################################################################\n\n# drop_db()\n# register_sensors_from_json('sensor_config.json')\n","repo_name":"Adigoo/IAS-Project-Group-5","sub_path":"sensor_manager/sensor_db.py","file_name":"sensor_db.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72225061606","text":"import cv2\nimport mediapipe as mp\n\ndef face_detect(img):\n ans =[0]\n\t## the input image is a format with cv2 read\n mp_face_detection = mp.solutions.face_detection\n mp_drawing = mp.solutions.drawing_utils\t\n with mp_face_detection.FaceDetection(\n min_detection_confidence=0.5) as face_detection:\n\t\t# Convert the BGR image to RGB and process it with MediaPipe Face Detection.\n results = face_detection.process(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n\n if not results.detections:\n return ans\n detection = results.detections[0]\n nose_tip = mp_face_detection.get_key_point(\n detection, mp_face_detection.FaceKeyPoint.NOSE_TIP)\n print('nose tip ', nose_tip)\n ans.append(0.5);ans.append(0.5)\n return ans\n\n\n\"\"\"\n\nfile_list=['/home/zhen/Projects/img_samples/2.jpg']\nimage = cv2.imread(file_list[0]);print('img shape in py ', image.shape)\nans = face_detect(image)\n\n\nmp_face_detection = mp.solutions.face_detection\nmp_drawing = mp.solutions.drawing_utils\nfile_list=['/home/zhen/Projects/img_samples/2.jpg']\n# For static images:\nwith mp_face_detection.FaceDetection(\n min_detection_confidence=0.5) as face_detection:\n for idx, file in enumerate(file_list):\n image = cv2.imread(file)\n # Convert the BGR image to RGB and process it with MediaPipe Face Detection.\n results = face_detection.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))\n\n # Draw face detections of each face.\n if not results.detections:\n continue\n annotated_image = image.copy()\n \n for detection in results.detections:\n print('Nose tip:')\n nt = mp_face_detection.get_key_point(\n detection, mp_face_detection.FaceKeyPoint.NOSE_TIP)\n print(nt)\n mp_drawing.draw_detection(annotated_image, detection)\n cv2.imwrite('/home/zhen/Projects/img_samples/out/annotated_image' + str(idx) + '.png', annotated_image)\n\"\"\"\n","repo_name":"xmuszq/Call-Python-API-from-Cpp","sub_path":"src/dl_model.py","file_name":"dl_model.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42386516988","text":"import sys\n\ninput = sys.stdin.readline\n\nn = int(input())\nm = int(input())\narr = list(map(int, input().split()))\narr.sort()\n\nans, ia, ib = 0, 0, n-1\n\nwhile ia < ib:\n S = arr[ia] + arr[ib]\n if S > m: ib-=1\n elif S < m: ia+=1\n else:\n ib-=1\n ia+=1\n ans+=1\n \nprint(ans)","repo_name":"chaaaning/Coding_Test","sub_path":"boj/투포인터/주몽.py","file_name":"주몽.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28031256578","text":"#!/usr/bin/env python3\n\n# -*- coding: UTF-8 -*-\nimport sys\nimport os\nfrom copy import deepcopy\n\nclass Solution(object):\n def defangIPaddr(self, address):\n \"\"\"\n :type address: str\n :rtype: str\n \"\"\"\n \n address = address.replace('.', '[.]')\n return address\n\n\n\n\ndef main():\n#{{{ \n\n sol = Solution()\n\n\n\n\n address0 = \"1.1.1.1\"\n ans0 = \"1[.]1[.]1[.]1\"\n\n sol0 = sol.defangIPaddr(address0)\n\n print(ans0)\n assert(ans0 == sol0)\n\n\n #\n address1 = \"255.100.50.0\"\n ans1 = \"255[.]100[.]50[.]0\"\n\n sol1 = sol.defangIPaddr(address1)\n\n print(ans1)\n assert(ans1 == sol1)\n\n#}}} \n\n\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"mjtsai/leetcode","sub_path":"1108_defanging_an_ip_address.py","file_name":"1108_defanging_an_ip_address.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3465687088","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# --------------------------------------------------------\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Chao CHEN (chaochancs@gmail.com)\n# Created On: 2017-06-08\n# --------------------------------------------------------\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\ndef cosine_similarity(x1, x2, dim=1, eps=1e-8):\n r\"\"\"Returns cosine similarity between x1 and x2, computed along dim.\n\n Args:\n x1 (Variable): First input.\n x2 (Variable): Second input (of size matching x1).\n dim (int, optional): Dimension of vectors. Default: 1\n eps (float, optional): Small value to avoid division by zero. Default: 1e-8\n\n Shape:\n - Input: :math:`(\\ast_1, D, \\ast_2)` where D is at position `dim`.\n - Output: :math:`(\\ast_1, \\ast_2)` where 1 is at position `dim`.\n \"\"\"\n w12 = torch.sum(x1 * x2, dim)\n w1 = torch.norm(x1, 2, dim)\n w2 = torch.norm(x2, 2, dim)\n return (w12 / (w1 * w2).clamp(min=eps)).squeeze()\n\ndef cos_distance(self, a, b):\n return torch.dot(a, b)/(torch.norm(a)*torch.norm(b))\n\nclass TripletMarginLoss(nn.Module):\n def __init__(self, margin, use_ohem=False, ohem_bs=128, dist_type = 0):\n super(TripletMarginLoss, self).__init__()\n self.margin = margin\n self.dist_type = dist_type\n self.use_ohem = use_ohem\n self.ohem_bs = ohem_bs\n #print('Use_OHEM : ',self.use_ohem)\n\n def forward(self, anchor, positive, negative):\n #eucl distance\n #dist = torch.sum( (anchor - positive) ** 2 - (anchor - negative) ** 2, dim=1)\\\n # + self.margin\n\n if self.dist_type == 0:\n dist_p = F.pairwise_distance(anchor ,positive)\n dist_n = F.pairwise_distance(anchor ,negative)\n if self.dist_type == 1:\n dist_p = cosine_similarity(anchor, positive)\n disp_n = cosine_similarity(anchor, negative)\n \n \n dist_hinge = torch.clamp(dist_p - dist_n + self.margin, min=0.0)\n if self.use_ohem:\n v, idx = torch.sort(dist_hinge,descending=True)\n loss = torch.mean(v[0:self.ohem_bs])\n else:\n loss = torch.mean(dist_hinge)\n\n return loss\n","repo_name":"huaijin-chen/pytorch-PersonReID","sub_path":"module/TripletLoss.py","file_name":"TripletLoss.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"52"} +{"seq_id":"23409059166","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[75]:\n\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\nhtml = urlopen('https://search.sina.com.cn/?q=%E7%99%BE%E5%BA%A6&c=news&from=channel&ie=utf-8')\nbs = BeautifulSoup(html.read(), 'html.parser')\nheads=bs.findAll('h2')\nnewsData = OrderedDict()\nfor head in heads:\n titleinfo=head.find('a')\n title=titleinfo.get_text()\n url=titleinfo['href']\n otherinfo=head.find('span',{'class':'fgray_time'}).get_text()\n source,date,time=otherinfo.split()\n newsData[title] = [date, source, url]\nfor ky in newsData:\n print('\\001'.join([ky] + newsData[ky])) # \"\\001\" as separator\n \n\n\n# In[ ]:\n\n\n\n\n\n# In[64]:\n\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nhtml = urlopen('https://search.sina.com.cn/?q=%E7%99%BE%E5%BA%A6&c=news&from=channel&ie=utf-8')\nbs = BeautifulSoup(html.read(), 'html.parser')\ndivs = bs.findAll('h2')\nfor div in divs:\n titleinfo =div.find('a')\n title = titleinfo.get_text()\n print(title)\n url = titleinfo['href']\n print(url)\n\n\n# In[86]:\n\n\nimport logging\nimport requests\nimport sys\nimport urllib\n\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\nfrom urllib.parse import urlencode\ndef get_list(comp, page):\n href = 'http://search.sina.com.cn/?%s&range=title&c=news&num=20&col=1_7&page=%s' % (comp, page)\n html = requests.get(href)\n bs = BeautifulSoup(html.content, 'html.parser')\n heads=bs.findAll('h2')\n newsData = OrderedDict()\n for head in heads:\n titleinfo=head.find('a')\n title=titleinfo.get_text()\n url=titleinfo['href']\n otherinfo=head.find('span',{'class':'fgray_time'}).get_text()\n source,date,time=otherinfo.split()\n newsData[title] = [date, source, url]\n return newsData\ncompRawStr = '沃尔玛'\ncomp = compRawStr.encode('gbk')\nd = {'q': comp}\npname = urlencode(d)\nfor page in range(5)[1:]:\n newsData = get_list(pname, page)\nfor ky in newsData:\n print('\\001'.join([ky] + newsData[ky])) # \"\\001\" as separator\n\n","repo_name":"feng-li/tools-for-data-science-course","sub_path":"2019spring/2017310901/L5Scraping.py","file_name":"L5Scraping.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"52"} +{"seq_id":"192298544","text":"import enum\n\nfrom mealie.schema._mealie import MealieModel\n\n\nclass SupportedMigrations(str, enum.Enum):\n nextcloud = \"nextcloud\"\n chowdown = \"chowdown\"\n copymethat = \"copymethat\"\n paprika = \"paprika\"\n mealie_alpha = \"mealie_alpha\"\n tandoor = \"tandoor\"\n plantoeat = \"plantoeat\"\n\n\nclass DataMigrationCreate(MealieModel):\n source_type: SupportedMigrations\n","repo_name":"mealie-recipes/mealie","sub_path":"mealie/schema/group/group_migration.py","file_name":"group_migration.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":3977,"dataset":"github-code","pt":"52"} +{"seq_id":"74508954723","text":"# 중복조합\nfrom itertools import combinations_with_replacement as combi\nn = int(input())\ndic = {\"I\":1, \"V\":5, \"X\":10, \"L\":50 }\narr = [\"I\", \"V\", \"X\", \"L\"]\nanswer = 0\nnum_arr = []\nanswer_arr = []\nlength = len(arr)#4\n#for res in(list(combi(arr,n))):\n# number = 0\n# for i in res:\n# number += dic[i]\n# num_arr.append(number)\n#print(len(list(set(num_arr))))\n\ndef dfs(start,box):\n if len(box) == n:\n num_arr.append(box)\n return\n for i in range(start,length):\n dfs(i,box+[arr[i]])\ndfs(0,[])\nfor ar in num_arr:\n number = 0\n for i in ar:\n number+=dic[i]\n answer_arr.append(number)\nprint(len(list(set(answer_arr))))\n\n\n\n","repo_name":"young0264/hellopycharm","sub_path":"백준/16922_로마숫자만들기.py","file_name":"16922_로마숫자만들기.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1818403537","text":"\ndef fibonacci_number(number):\n n = number\n if number == 0:\n return 0\n if number <= 2:\n return 1\n else:\n numbers = [1] * (number +1)\n numbers[0] = 0\n i = 2\n while number >= 2:\n numbers[i] = numbers[i-1] + numbers[i-2]\n number -= 1\n i += 1\n return numbers[n]\n\n\n\nif __name__ == '__main__':\n n = int(input())\n print(fibonacci_number(n))","repo_name":"patell11/DataStructuresAndAlgorithms_SanDiego","sub_path":"Practice/Coursera_Problems/fibonacci_number.py","file_name":"fibonacci_number.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30698571897","text":"import codecs\nimport string\nfrom xml.dom.minidom import parse\nimport os\n\n\n#os.chdir('/path/to/project')\n\ndef get_version_from_pom(directory):\n pom_file = os.path.join(directory, 'pom.xml')\n dom = parse(pom_file)\n project = dom.getElementsByTagName('project')[0]\n for node in project.childNodes:\n if node.nodeType == node.ELEMENT_NODE and node.tagName == 'version':\n full_version_string = node.firstChild.nodeValue\n return string.replace(full_version_string, '-SNAPSHOT', '')\n\n for node in project.childNodes:\n if node.nodeType == node.ELEMENT_NODE and node.tagName == 'parent':\n for parent_node in node.childNodes:\n if parent_node.nodeType == parent_node.ELEMENT_NODE and parent_node.tagName == 'version':\n full_version_string = parent_node.firstChild.nodeValue\n return string.replace(full_version_string, '-SNAPSHOT', '')\n\n\ndef add_entry_to_changelog_in(project_dir, version):\n file_name = os.path.join(project_dir, 'changelog.txt')\n\n f = codecs.open(file_name, 'r', 'utf-8')\n old_changelog_content = f.read()\n f.close()\n\n line_to_add = '==VERSION: ' + version + '=='\n\n if old_changelog_content.startswith(line_to_add):\n print('Changelog seems to be up-to-date')\n else:\n f = codecs.open(file_name, 'w', 'utf-8')\n f.write(line_to_add + \"\\n\")\n f.write(old_changelog_content)\n f.close()\n\nfor project_dir in os.listdir(os.getcwd()):\n if os.path.isdir(project_dir):\n directory_contents = os.listdir(project_dir)\n if 'pom.xml' in directory_contents and 'changelog.txt' in directory_contents:\n print()\n print('Project:', project_dir)\n project_version = get_version_from_pom(project_dir)\n add_entry_to_changelog_in(project_dir, project_version)\n","repo_name":"akkomar/yadda-python-tools","sub_path":"update_changelogs.py","file_name":"update_changelogs.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29053650257","text":"x = 0\na, b = list(map(int, input().split()))\nl = []\nfor i in range(a):\n lst = list(map(int, input().split()))\n l.append(lst)\n\nfor y in range(b):\n maxi = 0\n for k in range(len(l)):\n i = l[k][0]\n j = l[k][1]\n if j <= 2*i and maxi02d}\".format(H if hh==0 else hh , ww))\n","repo_name":"wbkifun/baekjoon","sub_path":"09.math1/10250_ACM_hotel.py","file_name":"10250_ACM_hotel.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38325324453","text":"\n# This doesn't work\nimport pdb\nclass NumMatrix:\n\n def __init__(self, matrix):\n \"\"\"\n :type matrix: List[List[int]]\n \"\"\"\n \n if not matrix:\n return\n \n self.R = len(matrix)\n self.C = len(matrix[0])\n \n self.sumR = self.R + 1\n self.sumC = self.C + 1\n \n # Deep copy the matrix\n self.matrix = [[matrix[i][j] for j in range(self.C)] for i in range(self.R)]\n self.sums = [[0 for _ in range(self.sumC)] for _ in range(self.sumR)]\n \n #for r in range(self.R):\n self.update_sum(0, 0)\n \n def update_sum(self, row, col):\n for r in range(row+1, self.sumR):\n for c in range(col+1, self.sumC):\n self.sums[r][c] = self.matrix[r-1][c-1] + self.sums[r][c-1] + self.sums[r-1][c]\n\n def update(self, row, col, val):\n \"\"\"\n :type row: int\n :type col: int\n :type val: int\n :rtype: void\n \"\"\"\n if row < 0 or row >= self.R or col < 0 or col >= self.C:\n return\n self.matrix[row][col] = val\n self.update_sum(row, col)\n \n\n def sumRegion(self, row1, col1, row2, col2):\n \"\"\"\n :type row1: int\n :type col1: int\n :type row2: int\n :type col2: int\n :rtype: int\n \"\"\"\n pdb.set_trace()\n if not 0 <= row1 < self.R or not 0 <= row2 < self.R or not 0 <= col1 < self.C or not 0 <= col2 < self.C:\n return 0\n\n row1, row2, col1, col2 = row1 + 1, row2+1, col1+1, col2+1\n s = 0\n s = self.sums[row2][col2] + self.sums[row1-1][col1-1] - self.sums[row1-1][col2] - self.sums[row2][col1-1] \n return s\n\nmatrix = [[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]]\na = NumMatrix(matrix)\nprint(a.sumRegion(2,1,4,3))\n\n","repo_name":"vkumar62/practice","sub_path":"leetcode/308_range_sum.py","file_name":"308_range_sum.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75210785443","text":"# Solves the optimal growth model. Code from Quantecon: https://python.quantecon.org/optgrowth.html\nimport numpy as np\nimport torch\nfrom scipy.interpolate import interp1d\nfrom scipy.optimize import minimize_scalar\nfrom dataclasses import dataclass\n\n\n# Utility to hold parameters for VFI algorithm\n@dataclass\nclass VFIParameters:\n tol: float\n max_iter: int\n k_grid_size: int\n c_solver_tol: float\n k_min_multiplier: float\n k_max_multiplier: float\n interpolation_kind: str\n\n\n# simple, slow VFI algorithm\ndef solve_growth_model_vfi(\n k_grid,\n f,\n beta,\n delta,\n g,\n vfi_tol=1e-9,\n max_iter=1000,\n c_solver_tol=1e-9,\n min_c=1e-9,\n interpolation_kind=\"cubic\",\n):\n min_k = k_grid[0]\n\n # The Bellman operator as a closure\n def T_growth(v):\n v_new = np.empty_like(v)\n k_prime = np.empty_like(v)\n c = np.empty_like(v)\n\n # value function used within optimization step\n v_interp = interp1d(\n k_grid, v, fill_value=\"extrapolate\", kind=interpolation_kind\n )\n\n for j in np.arange(0, len(k_grid)):\n kt = k_grid[j]\n max_c = f(kt) + (1 - delta) * kt - min_k\n # Maximize RHS of Bellman equation\n\n def v_objective_min(c): # reorganized to be a minimization problem\n ktp1 = (f(kt) + (1 - delta) * kt - c) / (1 + g) # use LOM\n\n val = np.log(c) + beta * v_interp(ktp1)\n\n return -val # converted to minimization problem\n\n result = minimize_scalar(\n v_objective_min,\n bounds=(min_c, max_c),\n method=\"bounded\",\n options={\"xatol\": c_solver_tol},\n )\n c[j], v_max = result.x, -result.fun\n v_new[j] = v_max\n k_prime[j] = (f(kt) + (1 - delta) * kt - c[j]) / (1 + g)\n\n return k_prime, c, v_new\n\n v = np.zeros(len(k_grid))\n\n # Fixed point iteration on the bellman operator\n i = 0\n error = vfi_tol + 1\n while i < max_iter and error > vfi_tol:\n k_prime, c, v_new = T_growth(v) # i.e. find v \\approx T(v)\n\n error = np.mean(np.power(v - v_new, 2))\n i += 1\n v = v_new\n\n if i == max_iter:\n raise RuntimeError(f\"Convergence failed after {i} iterations\")\n\n # return back closures which rescale by the \"z\"\n k_prime_interp_np = interp1d(\n k_grid, k_prime, fill_value=\"extrapolate\", kind=interpolation_kind\n )\n k_prime_interp = (\n lambda z, k: (1 + g) * z * k_prime_interp_np(k / z)\n ) # homogeneity of degree 1, k'(k,z) = z' * \\hat{k}'(k/z)\n\n c_interp_np = interp1d(k_grid, c, fill_value=\"extrapolate\", kind=interpolation_kind)\n c_interp = lambda z, k: z * c_interp_np(\n k / z\n ) # homogeneity of degree 1, c(k,z) = z * \\hat{c}(k/z)\n\n return k_prime_interp, c_interp\n","repo_name":"HighDimensionalEconLab/transversality","sub_path":"growth_vfi.py","file_name":"growth_vfi.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2669199610","text":"import mysql.connector\nimport json\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return 'Bienvenido a la conversión de monedas'\n\n\n\n@app.route('/convertir///')\ndef convertir(cantidad, de_moneda, a_moneda):\n # Conectarse a la base de datos\n conn = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\", \n database=\"conversiones\"\n )\n\n cursor = conn.cursor()\n\n # Obtener la tasa de cambio de la base de datos\n cursor.execute('SELECT tasa_cambio FROM tasas_cambio WHERE moneda_origen = %s AND moneda_destino = %s', (de_moneda.upper(), a_moneda.upper()))\n row = cursor.fetchone()\n\n # Verificar si se encontró una tasa de cambio\n if row is None:\n # Crear un diccionario con el mensaje de error\n message = {'error': 'No se encontró una tasa de cambio para la conversión especificada'}\n else:\n # Calcular la cantidad convertida\n tasa_cambio = row[0]\n cantidad_convertida = cantidad * tasa_cambio\n\n # Crear un diccionario con el mensaje de respuesta\n message = {\n 'cantidad': cantidad,\n 'moneda_origen': de_moneda.upper(),\n 'cantidad_convertida': cantidad_convertida,\n 'moneda_destino': a_moneda.upper()\n }\n\n # Cerrar la conexión a la base de datos\n conn.close()\n\n # Devolver la respuesta\n return jsonify(message)\n\n@app.route('/convertirweb///')\ndef convertirW(cantidad2, de_moneda2, a_moneda2):\n # Conectarse a la base de datos\n conn2 = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\", \n database=\"conversiones\"\n )\n\n cursor2 = conn2.cursor()\n\n # Obtener la tasa de cambio de la base de datos\n cursor2.execute('SELECT tasa_cambio FROM tasas_cambio WHERE moneda_origen = %s AND moneda_destino = %s', (de_moneda2.upper(), a_moneda2.upper()))\n row = cursor2.fetchone()\n\n # Verificar si se encontró una tasa de cambio\n if row is None:\n # Crear un diccionario con el mensaje de error\n message = {'error': 'No se encontró una tasa de cambio para la conversión especificada'}\n else:\n # Calcular la cantidad convertida\n tasa_cambio2 = row[0]\n cantidad_convertida2 = cantidad2 * tasa_cambio2\n\n # Crear un diccionario con el mensaje de respuesta\n message = {\n 'cantidad': cantidad2,\n 'moneda_origen': de_moneda2.upper(),\n 'cantidad_convertida': cantidad_convertida2,\n 'moneda_destino': a_moneda2.upper()\n }\n\n # Cerrar la conexión a la base de datos\n conn2.close()\n\n # Devolver la respuesta #return str(cantidad2) + ' ' + de_moneda2.upper() + ' equivale a ' + str(cantidad_convertida2) + ' ' + a_moneda2.upper()\n response = jsonify(message)\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response\n\n\nif __name__ == '__main__':\n CORS(app, resources={r\"/*\": {\"origins\": \"*\"}}, supports_credentials=True)\n app.run(host='0.0.0.0')\n #CORS(app)\n \n","repo_name":"OmaRodriguez-13/Proyecto-5-Servicio-Web---ConvertidorMonedas","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31590798989","text":"from oci.encryption.encryption import (\n encrypt,\n decrypt,\n create_encryption_stream,\n create_decryption_stream,\n)\n\nfrom oci.encryption.key_providers import KMSMasterKeyProvider, KMSMasterKey, MasterKeyProvider, MasterKey\nfrom oci.encryption.models import CryptoResult, CryptoResultStream\n\n\n__all__ = (\n \"encrypt\",\n \"decrypt\",\n \"create_encryption_stream\",\n \"create_decryption_stream\",\n \"KMSMasterKeyProvider\",\n \"KMSMasterKey\",\n \"MasterKeyProvider\",\n \"MasterKey\",\n \"CryptoResult\",\n \"CryptoResultStream\"\n)\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/encryption/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"31444083702","text":"# -*- coding:utf-8 -*-\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport operator\nimport time\n\nclass LSTM_Theano:\n\tdef __init__(self, feature_dim, output_dim, hidden_dim=128, bptt_truncate=-1):\n\n\t\t#初始化参数\n\t\tself.feature_dim = feature_dim\n\t\tself.output_dim = output_dim\n\t\tself.hidden_dim = hidden_dim\n\t\tself.bptt_truncate = bptt_truncate\n\n\t\t#E = np.random.uniform(-np.sqrt(1.0/word_dim), np.sqrt(1.0/word_dim), (hidden_dim, word_dim))\n\t\tU = np.random.uniform(-np.sqrt(1.0/hidden_dim), np.sqrt(1.0/hidden_dim), (4, hidden_dim, feature_dim))\n\t\tW = np.random.uniform(-np.sqrt(1.0/hidden_dim), np.sqrt(1.0/hidden_dim), (4, hidden_dim, hidden_dim))\n\t\tV = np.random.uniform(-np.sqrt(1.0/hidden_dim), np.sqrt(1.0/hidden_dim), (output_dim, hidden_dim))\n\t\tb = np.zeros((4, hidden_dim))\n\t\tc = np.zeros(output_dim)\n\n\t\t# shared variables\n\t\t#self.E = theano.shared(value=E.astype(theano.config.floatX), name='E')\n\t\tself.U = theano.shared(value=U.astype(theano.config.floatX), name='U')\n\t\tself.W = theano.shared(value=W.astype(theano.config.floatX), name='W')\n\t\tself.V = theano.shared(value=V.astype(theano.config.floatX), name='V')\n\t\tself.b = theano.shared(value=b.astype(theano.config.floatX), name='b')\n\t\tself.c = theano.shared(value=c.astype(theano.config.floatX), name='c')\n\n\t\t# SGD\n\t\t#self.mE = theano.shared(value=np.zeros(E.shape).astype(theano.config.floatX), name='mE')\n\t\tself.mU = theano.shared(value=np.zeros(U.shape).astype(theano.config.floatX), name='mU')\n\t\tself.mV = theano.shared(value=np.zeros(V.shape).astype(theano.config.floatX), name='mV')\n\t\tself.mW = theano.shared(value=np.zeros(W.shape).astype(theano.config.floatX), name='mW')\n\t\tself.mb = theano.shared(value=np.zeros(b.shape).astype(theano.config.floatX), name='mb')\n\t\tself.mc = theano.shared(value=np.zeros(c.shape).astype(theano.config.floatX), name='mc')\n\t\tself.theano = {}\n\t\tself.__theano_build__()\n\n\n\tdef __theano_build__(self):\n\t\tU, W, V, b, c = self.U, self.W, self.V, self.b, self.c\n\t\tx = T.dmatrix('x')\n\t\ty = T.dmatrix('y')\n\t\t#y = T.dvector('y')\n\n\t\t# feed forword\n\t\tdef forword_prop_step(x_t, s_prev, c_prev):\n\n\t\t\tx_e = T.transpose(x_t)\n\n\t\t\t# lstm layer\n\t\t\ti = T.nnet.hard_sigmoid(U[0].dot(x_e) + W[0].dot(s_prev) + b[0])\n\t\t\tf = T.nnet.hard_sigmoid(U[1].dot(x_e) + W[1].dot(s_prev) + b[1])\n\t\t\to = T.nnet.hard_sigmoid(U[2].dot(x_e) + W[2].dot(s_prev) + b[2])\n\t\t\tg = T.tanh(U[3].dot(x_e) + W[3].dot(s_prev) + b[3])\n\t\t\tc_t = c_prev * f + g * i\n\t\t\ts_t = T.tanh(c_t) * o\n\n\t\t\t#output\n\t\t\t#o_t = V.dot(s_t) + c\n\t\t\t#o_t = T.maximum(0, V.dot(s_t) + c)\n\t\t\t#o_t = T.tanh(V.dot(s_t) + c) #\n\t\t\to_t = T.nnet.softmax(V.dot(s_t) + c)\n\t\t\treturn [o_t, s_t, c_t]\n\n\n\t\t[o, s, c_o], updates = theano.scan(\n\t\t\tforword_prop_step,\n\t\t\tsequences=x,\n\t\t\ttruncate_gradient=self.bptt_truncate,\n\t\t\toutputs_info=[None,\n\t\t\t\t\t\t dict(initial=T.zeros(self.hidden_dim)),\n\t\t\t\t\t\t dict(initial=T.zeros(self.hidden_dim))]\n\t\t)\n\n\t\to = T.reshape(o, (o.shape[0], self.output_dim))\n\t\tprediction = T.argmax(o, axis=1)\n\t\t#MSE\n\t\t#o_error = T.sum(T.sqrt(T.sum(T.square(o - y), axis=0)))\n\t\t#CE\n\t\to_error = -T.mean(T.sum(y * T.log(o), axis=1))\n\t\t#o_error = T.sum(T.nnet.categorical_crossentropy(o, y))\n\t\tcost = o_error\n\n\t\t# calculate gradient\n\t\t#dE = T.grad(cost, E)\n\t\tdU = T.grad(cost, U)\n\t\tdW = T.grad(cost, W)\n\t\tdV = T.grad(cost, V)\n\t\tdb = T.grad(cost, b)\n\t\tdc = T.grad(cost, c)\n\n\t\tself.predict = theano.function([x], o)\n\t\tself.hidden_layer = theano.function([x], s)\n\t\tself.predict_class = theano.function([x], prediction)\n\t\tself.ce_error = theano.function([x, y], cost)\n\t\tself.bptt = theano.function([x, y], [dU, dW, db, dV, dc])\n\n\n\t\t# parameter for SGD\n\t\tlearning_rate = T.scalar('learning_rate')\n\t\tdecay = T.scalar('decay')\n\t\t# update\n\t\t#mE = decay * self.mE + (1 - decay) * dE**2\n\t\tmU = decay * self.mU + (1 - decay) * dU**2\n\t\tmW = decay * self.mW + (1 - decay) * dW**2\n\t\tmb = decay * self.mb + (1 - decay) * db**2\n\t\tmV = decay * self.mV + (1 - decay) * dV**2\n\t\tmc = decay * self.mc + (1 - decay) * dc**2\n\n\t\tself.sgd_step = theano.function(\n\t\t\t[x, y, learning_rate, theano.Param(decay, default=0.9)],\n\t\t\t[],\n\t\t\tupdates=[\n\t\t\t\t\t (U, U - learning_rate * dU / T.sqrt(mU + 1e-6)),\n\t\t\t\t\t (V, V - learning_rate * dV / T.sqrt(mV + 1e-6)),\n\t\t\t\t\t (b, b - learning_rate * db / T.sqrt(mb + 1e-6)),\n (c, c - learning_rate * dc / T.sqrt(mc + 1e-6)),\n\t\t\t\t\t (self.mU, mU),\n\t\t\t\t\t (self.mW, mW),\n (self.mV, mV),\n (self.mb, mb),\n (self.mc, mc)]\n\t\t\t#allow_input_downcast=True\n\t\t)\n\n\tdef calculate_total_loss(self, X, Y):\n\t\treturn np.sum([self.ce_error(x, y) for x, y in zip(X, Y)])\n\n\tdef calculate_loss(self, X, Y):\n\t\tnum_words = np.sum([len(y) for y in Y])\n\t\treturn self.calculate_total_loss(X, Y) / float(num_words)\n\n\t#def calculate_MSE(self, x, y):\n\n\n\n","repo_name":"bancheng/Stock-market","sub_path":"测试代码/theano/binbin/lstm_pm.py","file_name":"lstm_pm.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74290956004","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 14 14:55:33 2015\n@author: bruno\n\"\"\"\n\nimport numpy as np\nfrom pylab import *\n\n#define the delta function\ndef dd1(n):\n if n:\n return 0\n return 1\n\n#define the step function\ndef step(n):\n if n < 0:\n return 0\n return 1\n \n#define the number of samples\nn = np.arange(-5,5)\n\n#declare a vector with 10 spaces but empty values\nimpseq = np.empty((len(n),), dtype = int)\n\n#define the values of impseq\nfor i in range(len(n)):\n impseq[i] = dd1(n[i])\n\n\n#plot the stick grapph\nfigure(1)\nmarkerline, stemlines, baseline = stem(n,impseq,linefmt='b')\naxis([-5,4,-2,2])\ngrid()\nsetp(stemlines, 'linewidth','2.0')\nxlabel('n')\nylabel('x[n]=u[n-n0]')\ntitle('Step Sequence Response')\n\n\n#declare a vector with 10 spaces but empty values\nstepseq = np.empty((len(n),), dtype = int)\n\n\n#define the values of impseq\nfor i in range(len(n)):\n stepseq[i] = step(n[i])\n\n#plot the stick grapph\nfigure(2)\nmarkerline, stemlines, baseline = stem(n,impseq,linefmt='b')\naxis([-5,4,-2,2])\ngrid()\nsetp(stemlines, 'linewidth','2.0')\nxlabel('n')\nylabel('x[n]=u[n-n0]')\ntitle('Step Sequence Response')\n\n\nconv = np.convolve(stepseq, stepseq)\nnconv =np.arange(-len(n),len(n)-1)\n\n#plot the stick grapph\nfigure(3)\nmarkerline, stemlines, baseline = stem(nconv,conv,linefmt='b')\naxis([-10,10,-2,6])\ngrid()\nsetp(stemlines, 'linewidth','2.0')\nxlabel('n')\nylabel('x[n]=u[n-n0]')\ntitle('Step Sequence Response')","repo_name":"brunoliveira8/aulas-sinais-ipython","sub_path":"aula1.py","file_name":"aula1.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74050925606","text":"from keras.layers import Conv2D, AveragePooling2D, Flatten, Dense, Input, Activation, BatchNormalization\nfrom keras import Model\nfrom BatchNorm import CustomBatchNorm\n\n\ndef build_lenet(batch_norm=None):\n x_in = Input((28, 28, 1))\n x = Conv2D(filters=6, kernel_size=(3, 3))(x_in)\n if batch_norm: x = batch_norm()(x)\n x = Activation('relu')(x)\n x = AveragePooling2D()(x)\n x = Conv2D(filters=16, kernel_size=(3, 3))(x)\n if batch_norm: x = batch_norm()(x)\n x = Activation('relu')(x)\n x = AveragePooling2D()(x)\n x = Flatten()(x)\n x = Dense(units=120)(x)\n if batch_norm: x = batch_norm()(x)\n x = Activation('relu')(x)\n x = Dense(units=84)(x)\n if batch_norm: x = batch_norm()(x)\n x = Activation('relu')(x)\n x = Dense(units=10, activation='softmax')(x)\n return Model(inputs=x_in, outputs=x, name='LeNet')\n\ndef get_models():\n models = [build_lenet(CustomBatchNorm), build_lenet(BatchNormalization), build_lenet()]\n for model in models: model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return models\n","repo_name":"dksakkos/BatchNorm","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"33480744567","text":"import os\nimport argparse # (1)conda create -n JackPRENET=3.6\nimport numpy as np # (2)pip install numpy\nimport torch # 注意3.28官网不给10.2的源码下载了,哈哈哈vision tPorchau,还好俺们有清华源,将cu113 改为 cu102 即可,因为我电脑是10.2的cuda,装113会使得无法使用gpu!\n# pip3 install torch torchdio --extra-index-url https://download.pytorch.org/whl/cu102 -i https://pypi.tuna.tsinghua.edu.cn/simple BUG emmm,好像无法写入,有个小BUG, 那就自己换conda命令吧\n# (3)conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch 成功~ (通道没加清华源就 末尾加 -c pytorch 用官网的)\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.utils as utils\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom tensorboardX import SummaryWriter # (4)pip install tensorboardX\nfrom DerainDataset import *\nfrom utils import *\nfrom torch.optim.lr_scheduler import MultiStepLR\nfrom SSIM import SSIM\nfrom networks import *\n\nparser = argparse.ArgumentParser(description=\"PReNet_train\")\nparser.add_argument(\"--preprocess\", type=bool, default=True, help='run prepare_data or not')\nparser.add_argument(\"--batch_size\", type=int, default=6, help=\"Training batch size\") # batch_size 设置为 18,为了测试方便,这里改为6\nparser.add_argument(\"--epochs\", type=int, default=20, help=\"Number of training epochs\") # 为了快速得到结果,减少epoch 100 变为 20\nparser.add_argument(\"--milestone\", type=int, default=[30,50,80], help=\"When to decay learning rate\")\nparser.add_argument(\"--lr\", type=float, default=1e-3, help=\"initial learning rate\")\nparser.add_argument(\"--save_path\", type=str, default=\"/home/huangjh/Project/DeRain/JackCode/PreNet_Demo_copy/logs/PreNet_test/\", help='path to save models and log files') # 3.28 BUG 防止add path时,斜杠不一致\nparser.add_argument(\"--save_freq\",type=int,default=1,help='save intermediate model')\nparser.add_argument(\"--test_data_path\",type=str, default=\"/home/huangjh/Data/ProjectData/RainData/TraditionalData/test/Rain100H/\",help='path to training data') # 4.25 训练100H目录下的雨条纹图像\n# parser.add_argument(\"--data_path\",type=str, default=\"/home/huangjh/Data/ProjectData/RainData/TraditionalData/train/Rain12600/\",help='path to training data') # 3.28 BUG 防止add path时,斜杠不一致\nparser.add_argument(\"--data_path\",type=str, default=\"/home/huangjh/Data/ProjectData/RainData/X2Data/Train/Light/\",help='path to training data') # 4.25 训练100H目录下的雨条纹图像\nparser.add_argument(\"--use_gpu\", type=bool, default=True, help='use GPU or not')\nparser.add_argument(\"--gpu_id\", type=str, default=\"0\", help='GPU id')\nparser.add_argument(\"--recurrent_iter\", type=int, default=6, help='number of recursive stages')\nopt = parser.parse_args(args=[])\n\n# import sys\n# Logsave_path = sys.argv[1]\n\nif opt.use_gpu:\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = opt.gpu_id\n\ndef main():\n\n Loss = Acc = TestLoss = TestPsnr = []\n Note = open('/home/huangjh/Project/DeRain/JackCode/PreNet_Demo_copy/logs/Result/DerainLog.txt','a') \n Note.truncate(0) # 初始化txt\n\n print('Loading dataset ...\\n')\n dataset_train = Dataset(data_path=opt.data_path)\n loader_train = DataLoader(dataset=dataset_train, num_workers=0, batch_size=opt.batch_size, shuffle=True)\n dataset_test = Dataset(data_path=opt.test_data_path)\n loader_test = DataLoader(dataset=dataset_test, num_workers=0, batch_size=opt.batch_size,shuffle=False) # 0线程,10的size,打乱抽样(shuffle在dataset时操作了,这里不需要再操作)\n print(\"# of training samples: %d\\n\" % int(len(dataset_train)))\n\n # Build model\n # model = PReNet(recurrent_iter=opt.recurrent_iter, use_GPU=opt.use_gpu)\n model = AMCC2(recurrent_iter=opt.recurrent_iter, use_GPU=opt.use_gpu)\n print_network(model)\n \n # loss function\n # criterion = nn.MSELoss(size_average=False)\n criterion = SSIM()\n\n # Move to GPU\n if opt.use_gpu:\n model = model.cuda() # BUG CUDA driver initialization failed, you might not have a CUDA gpu.\n criterion.cuda()\n\n # Optimizer\n optimizer = optim.Adam(model.parameters(), lr=opt.lr)\n scheduler = MultiStepLR(optimizer, milestones=opt.milestone, gamma=0.2) # learning rates\n\n # record training\n writer = SummaryWriter(opt.save_path)\n\n # load the lastest model\n initial_epoch = findLastCheckpoint(save_dir=opt.save_path)\n if initial_epoch > 0:\n print('resuming by loading epoch %d' % initial_epoch)\n model.load_state_dict(torch.load(os.path.join(opt.save_path, 'net_epoch%d.pth' % initial_epoch)))\n\n # start training\n step = 0 \n # Note=open('/home/huangjh/Project/PDAnalysis/Result/'+Logsave_path,'a')\n # Note.truncate(0) # 初始化txt\n\n for epoch in range(initial_epoch, opt.epochs):\n scheduler.step(epoch)\n for param_group in optimizer.param_groups:\n print('learning rate %f' % param_group[\"lr\"]) # learning rate 0.001000\n\n ## epoch training start\n for i, (input_train, target_train) in enumerate(loader_train, 0):\n model.train() # nn.Module.train的继承\n model.zero_grad()\n optimizer.zero_grad()\n \n input_train, target_train = Variable(input_train), Variable(target_train)\n\n if opt.use_gpu:\n input_train, target_train = input_train.cuda(), target_train.cuda()\n \n out_train, _ = model(input_train)\n pixel_metric = criterion(target_train, out_train) # target_train.size()---torch.Size([2, 3, 100, 100]); out_train.size()---torch.Size([2, 3, 100, 100])\n loss = -pixel_metric \n\n loss.backward()\n optimizer.step() # BUG 2022.07.22 将step放在每个epoch训练完以后\n \n # training curve\n model.eval()\n out_train, _ = model(input_train)\n out_train = torch.clamp(out_train, 0., 1.) # 将输入input张量每个元素的夹紧到区间 [min,max][0,1],并返回结果到一个新张量\n psnr_train = batch_PSNR(out_train, target_train, 1.)\n print(\"[epoch %d][%d/%d] loss: %.4f, pixel_metric: %.4f, PSNR: %.4f\" %\n (epoch+1, i+1, len(loader_train), loss.item(), pixel_metric.item(), psnr_train))\n #====记录数据\n # Note=open('/home/huangjh/Project/PDAnalysis/Result/'+Logsave_path,'a')\n # Note.write(\"[epoch %d][%d/%d] loss: %.4f, pixel_metric: %.4f, PSNR: %.4f\" %\n # (epoch+1, i+1, len(loader_train), loss.item(), pixel_metric.item(), psnr_train))\n\n if step % 10 == 0:\n # Log the scalar values\n writer.add_scalar('loss', loss.item(), step)\n writer.add_scalar('PSNR on training data', psnr_train, step)\n step += 1\n\n # 5. 输出测试结果\n # model.eval() 2022.08.14 BUG 此处无需再加入这个,因为在eval函数中已加入\n # epoch_test_loss, epoch_test_psnr = eval(model, epoch,loader_test,criterion) # 2022.08.14 测试时输出的是一次性的,取 patches 进行test不太行\n ## epoch training end\n\n # log the images\n model.eval()\n out_train, _ = model(input_train)\n out_train = torch.clamp(out_train, 0., 1.)\n im_target = utils.make_grid(target_train.data, nrow=8, normalize=True, scale_each=True)\n im_input = utils.make_grid(input_train.data, nrow=8, normalize=True, scale_each=True)\n im_derain = utils.make_grid(out_train.data, nrow=8, normalize=True, scale_each=True)\n writer.add_image('clean image', im_target, epoch+1)\n writer.add_image('rainy image', im_input, epoch+1)\n writer.add_image('deraining image', im_derain, epoch+1)\n\n # save model\n torch.save(model.state_dict(), os.path.join(opt.save_path, 'net_latest.pth'))\n if epoch % opt.save_freq == 0:\n torch.save(model.state_dict(), os.path.join(opt.save_path, 'net_epoch%d.pth' % (epoch+1)))\n\nif __name__ == \"__main__\":\n if opt.preprocess:\n if opt.data_path.find('RainTrainH') != -1:\n print(opt.data_path.find('RainTrainH'))\n prepare_data_RainTrainH(data_path=opt.data_path, patch_size=100, stride=80)\n elif opt.data_path.find('RainTrainL') != -1:\n prepare_data_RainTrainL(data_path=opt.data_path, patch_size=100, stride=80)\n elif opt.data_path.find('Rain12600') != -1:\n prepare_data_Rain12600(data_path=opt.data_path, patch_size=100, stride=100)\n elif opt.data_path.find('X2Data') != -1:\n prepare_data_RainTrainH(data_path=opt.test_data_path, patch_size=96, stride=100)\n prepare_data_X2Data(data_path=opt.data_path, patch_size=96, stride=100) # 设置100会导致KPN上下采样不兼容\n else:\n print('unkown datasets: please define prepare data function in DerainDataset.py')\n main()\n\n","repo_name":"ffdffd/Derain","sub_path":"train_PReNet.py","file_name":"train_PReNet.py","file_ext":"py","file_size_in_byte":9050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23765817636","text":"import math\nfrom pprint import pprint\n\ndtmf = [697, 770, 852, 941, 1209, 1336, 1477, 1633]\n\n# Sampling frequency (Hz)\n# f_samp = 8_000\nf_samp = 20_000\n\n\ndef calc_bin(N):\n\n bins = []\n for f in dtmf:\n # Binned value (decimal)\n kf = N * f / f_samp\n k_down, k_up = math.floor(kf), math.ceil(kf)\n err_down, err_up = abs(f - k_down * f_samp / N), abs(f - k_up * f_samp / N)\n if err_down < err_up:\n k = k_down\n else:\n k = k_up\n\n bins.append(k)\n\n if len(set(bins)) == len(dtmf):\n\n print(f\"Sample freq. = {f_samp}\")\n print(f\"N = {N}\")\n err_sum = 0\n for (f, bin) in zip(dtmf, bins):\n err = f - bin * f_samp / N\n err_sum += err**2\n print(f\"{f} Hz: \\t{bin}\\t{err}\")\n\n return err_sum\n\n return False\n\n\nif __name__ == \"__main__\":\n # calc_bin(205)\n # calc_bin(105)\n calc_bin(283)\n\n ok = []\n n = 1\n while n < 500:\n # err = calc_bin(n)\n # if err != False:\n # ok.append((err, n))\n\n if calc_bin(n):\n break\n\n n += 1\n\n # pprint(sorted(ok))\n","repo_name":"ltzehan/EE2026-Project","sub_path":"scripts/dtmf.py","file_name":"dtmf.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"72340907046","text":"import logging\nimport os\nimport datetime\n\nBLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)\n\nCOLORS = {\n 'WARNING': YELLOW,\n 'INFO': WHITE,\n 'DEBUG': BLUE,\n 'CRITICAL': YELLOW,\n 'ERROR': RED,\n 'RED': RED,\n 'GREEN': GREEN,\n 'YELLOW': YELLOW,\n 'BLUE': BLUE,\n 'MAGENTA': MAGENTA,\n 'CYAN': CYAN,\n 'WHITE': WHITE,\n}\n\nRESET_SEQ = \"\\033[0m\"\nCOLOR_SEQ = \"\\033[1;%dm\"\nBOLD_SEQ = \"\\033[1m\"\n\n\nclass ColorFormatter(logging.Formatter):\n\n def __init__(self, *args, **kwargs):\n # can't do super(...) here because Formatter is an old school class\n logging.Formatter.__init__(self, *args, **kwargs)\n\n def format(self, record):\n levelname = record.levelname\n color = COLOR_SEQ % (30 + COLORS[levelname])\n message = logging.Formatter.format(self, record)\n message = message.replace(\"$RESET\", RESET_SEQ) \\\n .replace(\"$BOLD\", BOLD_SEQ) \\\n .replace(\"$COLOR\", color)\n for k, v in COLORS.items():\n message = message.replace(\"$\" + k, COLOR_SEQ % (v + 30)) \\\n .replace(\"$BG\" + k, COLOR_SEQ % (v + 40)) \\\n .replace(\"$BG-\" + k, COLOR_SEQ % (v + 40))\n return message + RESET_SEQ\n\n\ndef init_mylogger(*, debug_level=r'DEBUG',\n # log_file_name='', log_folder_name='',\n string_format=r'%(levelname)s %(asctime)s %(funcName)s: %(message)s',\n color_string_format=r'$COLOR%(levelname)s $RESET %(relativeCreated)d %(funcName)s: %(message)s'):\n\n # if len(log_file_name) == 0:\n # log_file_name = datetime.datetime.now().strftime(\"-%Y%m%d-%H%M%S\") + \".log\"\n #\n # if not os.path.exists(log_folder_name):\n # os.mkdir(log_folder_name)\n\n # my_logger_path = os.path.join(log_folder_name, log_file_name)\n\n # my_logger = logging.getLogger(my_logger_path)\n my_logger = logging.getLogger('my_logger')\n\n if not my_logger.hasHandlers():\n level = debug_level\n\n my_logger.setLevel(level)\n\n my_logger.propagate = False\n\n # logger_file_handler = logging.FileHandler(my_logger_path)\n\n # logger_file_handler.setLevel(level)\n\n logger_console_handler = logging.StreamHandler()\n logger_console_handler.setLevel(level)\n\n logger_console_handler.setFormatter(ColorFormatter(color_string_format))\n # logger_file_handler.setFormatter(ColorFormatter(string_format))\n\n my_logger.addHandler(logger_console_handler)\n # my_logger.addHandler(logger_file_handler)\n\n return my_logger\n\n\nmylog: logging.Logger = init_mylogger(\n # log_folder_name='logs'\n)\n\n","repo_name":"vbasov007/speech_srt_generator","sub_path":"mylogger/mylogger.py","file_name":"mylogger.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"876411446","text":"import sys\n\nif(len(sys.argv) != 3):\n\tprint(\"USAGE: python3 prependpc inpath outpath\")\nelse:\n infile_path = sys.argv[1]\n outfile_path = sys.argv[2] \n\n outfile = open(outfile_path,\"w+\")\n with open(infile_path,\"r\") as infile:\n content = infile.readlines()\n outfile.write(\"LEGEND: \\n (REGISTER) = x\\\" VALUE \\\", \\n @{_func} ... function call, {_func} ... function execution \\n\\n\")\n outfile.write(\"[PC*4] actualpc : instr ; assembly | description\\n\")\n for line in content:\n pc_str = line[:8]\n pc = int(pc_str,16)\n pc = pc * 4\n outfile.write(\"[\"+'{0:04X}'.format(pc)+\"] \" + line)\n \n outfile.close()","repo_name":"Oidlichtnwoada/MinimalMipsProcessor","sub_path":"other_files/prependpc.py","file_name":"prependpc.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19503044759","text":"#7-8\nsandwich_orders = ['pastrami','chicken','pastrami','corned-beff','pastrami']\nfinished_sandwiches = []\nfor sandwich_order in sandwich_orders:\n print(\"I made your \"+sandwich_order+\" sandwich\")\n finished_sandwiches.append(sandwich_order)\nfor finished_sandwiche in finished_sandwiches:\n print(finished_sandwiche+\" sandwich\")\n#7-9\nmessage = \"Sorry, pastrami has been sold out.\"\nprint(message)\nwhile 'pastrami' in sandwich_orders:\n sandwich_orders.remove('pastrami')\nprint(sandwich_orders)\n#7-10\nplace = input(\"If you could visit one place in the world, where woule you go?(input 'quit' to quit) \")\nplaces = []\nwhile place != 'quit':\n places.append(place)\n place = input(\"If you could visit one place in the world, where woule you go?(input 'quit' to quit) \")\nfor place in places :\n print(place.upper().ljust(20),end = \"\")\nprint()","repo_name":"2648226350/Python_learn","sub_path":"pych-seven/7_8to7_10.py","file_name":"7_8to7_10.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4770630207","text":"# script to create a table\r\n# importing sqlite3 database \r\nimport sqlite3 as sql\r\nconn = sql.connect( \"database1.db\" )\r\n#read and write the content\r\ncurs = conn.cursor()\r\ntry:\r\n curs.execute( \"create table employee(idno number,name text,salary real )\" )\r\n print( \"table is created\" )\r\n#exception if table is available\r\nexcept sql.OperationalError as oe:\r\n print(oe)\r\n\r\nfinally:\r\n conn.close()\r\nprint( \"thanks\" )\r\n","repo_name":"ZumeITInc/Naresh","sub_path":"Database Programe.py","file_name":"Database Programe.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40985920066","text":"\"\"\"\nFunctions of average meter, logger, guidedfilter, and result output\n\"\"\"\nimport logging\nfrom cv2.ximgproc import guidedFilter\nimport numpy as np\n\n\nclass AverageMeter(object):\n \"\"\"Compute and store the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n \ndef get_logger(filename, verbosity=1, name=None):\n \"\"\"Get logger\"\"\"\n level_dict = {0: logging.DEBUG, 1: logging.INFO, 2: logging.WARNING}\n formatter = logging.Formatter(\n \"[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s\"\n )\n logger = logging.getLogger(name)\n logger.setLevel(level_dict[verbosity])\n \n fh = logging.FileHandler(filename, \"w\")\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n \n sh = logging.StreamHandler()\n sh.setFormatter(formatter)\n logger.addHandler(sh)\n \n return logger\n\n\ndef gf(mask, img):\n \"\"\"Apply guidedfilter\"\"\"\n return guidedFilter(mask, img, 4, 0.2, -1)\n\n\ndef output_result(out, mask):\n \"\"\"Prepare data and apply guidedfilter to depth map\"\"\"\n mask = np.float32(mask)\n img=out.detach().cpu().numpy()\n img_resized=img.reshape(240,320)\n max_item = max(max(row) for row in img_resized)\n img_resized = img_resized / max_item * 255\n\n result = gf(mask, img_resized)\n \n return result\n\n","repo_name":"uf-robopi/UDepth","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"52"} +{"seq_id":"37018869291","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\services\\flightControls.py\r\nimport geo2\r\nimport math\r\nimport blue\r\nimport util\r\nimport service\r\nimport uthread\r\nimport destiny\r\nimport trinity\r\nimport evecamera\r\nimport collections\r\nfrom eveexceptions.exceptionEater import ExceptionEater\r\nfrom carbonui.uicore import uicorebase as uicore\r\nimport carbonui.const as uiconst\r\n\r\nclass FlightControls(service.Service):\r\n __guid__ = 'svc.flightControls'\r\n __dependencies__ = ['michelle', 'machoNet']\r\n __notifyevents__ = ['OnBallparkSetState',\r\n 'OnSessionChanged',\r\n 'DoBallsAdded',\r\n 'OnMapShortcut',\r\n 'OnRestoreDefaultShortcuts',\r\n 'DoSimClockRebase',\r\n 'OnActiveCameraChanged']\r\n\r\n def Run(self, *args):\r\n service.Service.Run(self, *args)\r\n self.controls = KeyboardControls()\r\n self.simulation = FlightSimulation(callback=self.OnGotoDirection, controls=self.controls, throttle=self.GetThrottle())\r\n self.statistics = FlightControlStatistics(self.controls)\r\n self.simulation.Start()\r\n self.statistics.Start()\r\n\r\n def GetThrottle(self):\r\n return int(self.machoNet.GetGlobalConfig().get('flightControlsThrottle', 400)) / float(1000) * const.SEC\r\n\r\n def OnGotoDirection(self, direction):\r\n remote = self.michelle.GetRemotePark()\r\n if remote:\r\n remote.CmdSteerDirection(*direction)\r\n self.statistics.Increment()\r\n\r\n def AttachShip(self):\r\n self.controls.PrimeKeys()\r\n ballpark = self.michelle.GetBallpark()\r\n if ballpark and session.shipid:\r\n self.simulation.AttachShip(ballpark.GetBall(session.shipid))\r\n else:\r\n self.simulation.DetachShip()\r\n\r\n def DoSimClockRebase(self, times):\r\n self.simulation.AdjustTimes(times[1] - times[0])\r\n self.controls.Reset()\r\n\r\n def OnBallparkSetState(self):\r\n self.AttachShip()\r\n self.controls.Reset()\r\n\r\n def OnSessionChanged(self, isRemote, session, change):\r\n self.AttachShip()\r\n self.controls.Reset()\r\n\r\n def DoBallsAdded(self, balls):\r\n with ExceptionEater('FlightControls.DoBallsAdded'):\r\n if any([ ball for ball, item in balls if item.itemID == session.shipid ]):\r\n self.AttachShip()\r\n self.controls.Reset()\r\n\r\n def OnMapShortcut(self, *args):\r\n self.controls.PrimeKeys()\r\n\r\n def OnRestoreDefaultShortcuts(self, *args):\r\n self.controls.PrimeKeys()\r\n\r\n def OnActiveCameraChanged(self, cameraID):\r\n self.simulation.SetWorldRelative(cameraID != evecamera.CAM_SHIPPOV)\r\n\r\n\r\nclass FlightSimulation(object):\r\n ENGAGE_TIME = 6.0\r\n RELEASE_TIME = 4.0\r\n\r\n def __init__(self, callback, controls, throttle = None):\r\n self.callback = callback\r\n self.controls = controls\r\n self.throttle = throttle or 0\r\n self.ballpark = blue.classes.CreateInstance('destiny.Ballpark')\r\n self.ballpark.tickInterval = 100\r\n self.ball = self.ballpark.AddBall(1, 1.0, 0.0, 0, True, False, False, False, False, 0, 0, 0, 0, 0, 0, 0, 0)\r\n self.ballpark.ego = 1\r\n self.ship = None\r\n self.thread = None\r\n self.controlling = False\r\n self.direction = None\r\n self.lastCalled = 0\r\n self.worldRelative = True\r\n self.curve = trinity.Tr2QuaternionLerpCurve()\r\n\r\n def Start(self):\r\n if self.thread is None:\r\n self.ballpark.Start()\r\n self.thread = uthread.new(self.Update)\r\n self.thread.context = 'FlightSimulation::Update'\r\n\r\n def Stop(self):\r\n if self.thread is not None:\r\n self.ballpark.Pause()\r\n self.thread.kill()\r\n self.thread = None\r\n\r\n def SetWorldRelative(self, relative):\r\n self.worldRelative = relative\r\n\r\n def AdjustTimes(self, delta):\r\n self.lastCalled += delta\r\n self.ballpark.AdjustTimes(delta)\r\n\r\n def AttachShip(self, ship):\r\n if ship is None or self.ship != ship:\r\n self.DetachShip(self.ship)\r\n self.ship = ship\r\n self.controlling = False\r\n if getattr(self, 'localModel', None):\r\n self.DisableDebug()\r\n self.EnableDebug()\r\n\r\n def DetachShip(self, ship = None):\r\n if ship in (self.ship, None):\r\n if self.ship and getattr(self.ship, 'model', None):\r\n self.ship.model.rotationCurve = self.ship\r\n self.ship = None\r\n self.controlling = False\r\n\r\n def Update(self):\r\n while True:\r\n blue.synchro.Yield()\r\n if self.ship and self.controls and self.callback:\r\n with util.ExceptionEater('FlightSimulation'):\r\n self.AttachBalls()\r\n self.ProcessInput()\r\n self.UpdateDirection()\r\n self.TriggerCallback()\r\n\r\n def AttachBalls(self):\r\n self.ballpark.tickInterval = 100\r\n if getattr(self.ship, 'model', None) and self.ship.model.rotationCurve != self.curve:\r\n self.ship.model.rotationCurve = self.curve\r\n velocity = self.ship.GetVectorDotAt(blue.os.GetSimTime())\r\n self.ballpark.SetBallVelocity(self.ball.id, velocity.x, velocity.y, velocity.z)\r\n self.curve.startCurve = self.ball\r\n self.curve.endCurve = self.ship\r\n self.curve.start = 0\r\n self.curve.length = 1\r\n\r\n def CanControl(self):\r\n return self.ship.mode in (destiny.DSTBALL_ORBIT, destiny.DSTBALL_FOLLOW, destiny.DSTBALL_GOTO)\r\n\r\n def ProcessInput(self):\r\n if self.CanControl():\r\n yaw, pitch = self.controls.GetYawPitch()\r\n else:\r\n yaw, pitch = (0, 0)\r\n currentYaw, currentPitch, currentRoll = self.curve.GetQuaternionAt(blue.os.GetSimTime()).GetYawPitchRoll()\r\n if self.worldRelative:\r\n currentPitch = max(-math.pi / 2.0, min(math.pi / 2.0, currentPitch + pitch))\r\n current = geo2.QuaternionRotationSetYawPitchRoll(currentYaw, currentPitch, 0)\r\n rotation = geo2.QuaternionRotationSetYawPitchRoll(yaw, 0, 0)\r\n else:\r\n current = geo2.QuaternionRotationSetYawPitchRoll(currentYaw, currentPitch, currentRoll)\r\n rotation = geo2.QuaternionRotationSetYawPitchRoll(yaw, pitch, 0)\r\n result = geo2.QuaternionMultiply(rotation, current)\r\n self.direction = geo2.QuaternionTransformVector(result, (0, 0, 1))\r\n if not self.controlling:\r\n self.controlling = bool(yaw or pitch)\r\n\r\n def UpdateDirection(self):\r\n self.ball.x, self.ball.y, self.ball.z = self.ship.x, self.ship.y, self.ship.z\r\n self.ballpark.SetBallMass(self.ball.id, self.ship.mass)\r\n self.ballpark.SetBallAgility(self.ball.id, self.ship.Agility)\r\n self.ballpark.SetBallRadius(self.ball.id, self.ship.radius)\r\n self.ballpark.SetMaxSpeed(self.ball.id, self.ship.maxVelocity)\r\n self.ballpark.SetSpeedFraction(self.ball.id, self.ship.speedFraction)\r\n if self.controlling:\r\n self.ballpark.GotoDirection(self.ball.id, self.direction[0], self.direction[1], self.direction[2])\r\n if self.curve.endCurve != self.ball:\r\n self.curve.startCurve = self.ship\r\n self.curve.endCurve = self.ball\r\n self.curve.length = self.ENGAGE_TIME\r\n self.curve.start = blue.os.GetSimTime() - long(max(0, self.curve.start + self.ENGAGE_TIME * const.SEC - blue.os.GetSimTime()))\r\n else:\r\n if blue.os.GetSimTime() - self.lastCalled > self.RELEASE_TIME * const.SEC and self.curve.endCurve != self.ship:\r\n if self.curve.endCurve != self.ship:\r\n self.curve.startCurve = self.ball\r\n self.curve.endCurve = self.ship\r\n self.curve.length = self.ENGAGE_TIME\r\n self.curve.start = blue.os.GetSimTime() - long(max(0, self.curve.start + self.ENGAGE_TIME * const.SEC - blue.os.GetSimTime()))\r\n if self.curve.endCurve == self.ship:\r\n velocity = self.ship.GetVectorDotAt(blue.os.GetSimTime())\r\n self.ballpark.GotoDirection(self.ball.id, velocity.x, velocity.y, velocity.z)\r\n\r\n def TriggerCallback(self):\r\n if self.controlling and self.lastCalled + self.throttle < blue.os.GetSimTime():\r\n self.lastCalled = blue.os.GetSimTime()\r\n self.callback(self.direction)\r\n self.controlling = False\r\n\r\n def EnableDebug(self):\r\n scaling = [(self.ship.radius + 20) * 2, (self.ship.radius + 20) * 2, (self.ship.radius + 20) * 2]\r\n self.localModel = trinity.EveRootTransform()\r\n self.localGfx = trinity.Load('res:/model/global/gridSphere.red')\r\n self.localGfx.scaling = geo2.Vec3Scale(scaling, 1.0)\r\n self.localModel.name = 'FlightSimulationLocal'\r\n self.localModel.translationCurve = self.ball\r\n self.localModel.rotationCurve = self.ball\r\n self.localModel.children.append(self.localGfx)\r\n sm.GetService('sceneManager').GetRegisteredScene('default').objects.append(self.localModel)\r\n self.remoteModel = trinity.EveRootTransform()\r\n self.remoteGfx = trinity.Load('res:/model/global/gridSphere.red')\r\n self.remoteGfx.scaling = geo2.Vec3Scale(scaling, 1.5)\r\n color = self.remoteGfx.mesh.additiveAreas[0].effect.parameters[1].value\r\n self.remoteGfx.mesh.additiveAreas[0].effect.parameters[1].value = (color[0],\r\n color[2],\r\n color[1],\r\n color[3])\r\n self.remoteModel.name = 'FlightSimulationRemote'\r\n self.remoteModel.translationCurve = self.ship\r\n self.remoteModel.rotationCurve = self.ship\r\n self.remoteModel.children.append(self.remoteGfx)\r\n sm.GetService('sceneManager').GetRegisteredScene('default').objects.append(self.remoteModel)\r\n self.curveModel = trinity.EveRootTransform()\r\n self.curveGfx = trinity.Load('res:/model/global/gridSphere.red')\r\n self.curveGfx.scaling = geo2.Vec3Scale(scaling, 1.25)\r\n color = self.curveGfx.mesh.additiveAreas[0].effect.parameters[1].value\r\n self.curveGfx.mesh.additiveAreas[0].effect.parameters[1].value = (color[2],\r\n color[1],\r\n color[0],\r\n color[3])\r\n self.curveModel.name = 'FlightSimulationRemote'\r\n self.curveModel.translationCurve = self.ball\r\n self.curveModel.rotationCurve = self.curve\r\n self.curveModel.children.append(self.curveGfx)\r\n sm.GetService('sceneManager').GetRegisteredScene('default').objects.append(self.curveModel)\r\n\r\n def DisableDebug(self):\r\n sm.GetService('sceneManager').GetRegisteredScene('default').objects.fremove(self.localModel)\r\n self.localModel = None\r\n sm.GetService('sceneManager').GetRegisteredScene('default').objects.fremove(self.remoteModel)\r\n self.remoteModel = None\r\n sm.GetService('sceneManager').GetRegisteredScene('default').objects.fremove(self.curveModel)\r\n self.curveModel = None\r\n\r\n def ToggleDebug(self):\r\n if getattr(self, 'localModel', None):\r\n self.DisableDebug()\r\n else:\r\n self.EnableDebug()\r\n\r\n\r\nclass KeyboardControls(object):\r\n DECAY = 1.2\r\n ACCEL = 1\r\n MAX = 1.3\r\n\r\n def __init__(self):\r\n self.keyUp = []\r\n self.keyDown = []\r\n self.keyLeft = []\r\n self.keyRight = []\r\n self.Reset()\r\n\r\n def Reset(self):\r\n self.yaw = 0.0\r\n self.pitch = 0.0\r\n self.time = 0\r\n\r\n def PrimeKeys(self):\r\n self.keyUp = uicore.cmd.GetShortcutByFuncName('CmdFlightControlsUp') or []\r\n self.keyDown = uicore.cmd.GetShortcutByFuncName('CmdFlightControlsDown') or []\r\n self.keyLeft = uicore.cmd.GetShortcutByFuncName('CmdFlightControlsLeft') or []\r\n self.keyRight = uicore.cmd.GetShortcutByFuncName('CmdFlightControlsRight') or []\r\n\r\n def GetYawPitch(self):\r\n now = blue.os.GetSimTime()\r\n delta = (now - self.time) / float(const.SEC)\r\n self.time = now\r\n if self.yaw > 0:\r\n self.yaw = max(0, self.yaw - self.DECAY * delta)\r\n else:\r\n self.yaw = min(0, self.yaw + self.DECAY * delta)\r\n if self.pitch > 0:\r\n self.pitch = max(0, self.pitch - self.DECAY * delta)\r\n else:\r\n self.pitch = min(0, self.pitch + self.DECAY * delta)\r\n if trinity.app.IsActive() and uicore.registry.GetFocus() == uicore.desktop:\r\n if self.KeysAreDown(self.keyUp):\r\n self.pitch = max(-self.MAX, self.pitch - (self.ACCEL + self.DECAY) * delta)\r\n if self.KeysAreDown(self.keyDown):\r\n self.pitch = min(self.MAX, self.pitch + (self.ACCEL + self.DECAY) * delta)\r\n if self.KeysAreDown(self.keyRight):\r\n self.yaw = max(-self.MAX, self.yaw - (self.ACCEL + self.DECAY) * delta)\r\n if self.KeysAreDown(self.keyLeft):\r\n self.yaw = min(self.MAX, self.yaw + (self.ACCEL + self.DECAY) * delta)\r\n return (self.yaw, self.pitch)\r\n\r\n def KeysAreDown(self, mapping):\r\n if mapping and all([ uicore.uilib.Key(key) for key in mapping ]):\r\n if all([ not uicore.uilib.Key(key) for key in uiconst.MODKEYS if key not in mapping ]):\r\n return True\r\n return False\r\n\r\n\r\nclass FlightControlStatistics(object):\r\n\r\n def __init__(self, controls):\r\n self.ships = {}\r\n self.counters = collections.defaultdict(int)\r\n self.thread = None\r\n self.controls = controls\r\n\r\n def Start(self):\r\n if self.thread is None:\r\n self.thread = uthread.new(self.Update)\r\n self.thread.context = 'FlightControlStatistics::Update'\r\n\r\n def Stop(self):\r\n if self.thread is not None:\r\n self.thread.kill()\r\n self.thread = None\r\n\r\n def Update(self):\r\n while True:\r\n with ExceptionEater('FlightControlStatistics::Update'):\r\n self.Flush()\r\n blue.synchro.Sleep(self.GetInterval())\r\n\r\n def GetInterval(self):\r\n return int(sm.GetService('machoNet').GetGlobalConfig().get('flightControlStatisticsInterval', 300)) * 1000\r\n\r\n def Increment(self):\r\n self.counters[(session.solarsystemid, session.shipid)] += 1\r\n self.SaveShip()\r\n\r\n def SaveShip(self):\r\n with ExceptionEater('FlightControlStatistics::SaveShip'):\r\n if session.shipid and session.shipid not in self.ships:\r\n self.ships[session.shipid] = sm.GetService('godma').GetItem(session.shipid).typeID\r\n\r\n def Flush(self):\r\n for (solarSystemID, shipID), counter in self.counters.iteritems():\r\n with ExceptionEater('eventLog'):\r\n if solarSystemID and shipID and counter:\r\n sm.ProxySvc('eventLog').LogClientEvent('flightControls', ['solarSystemID',\r\n 'shipTypeID',\r\n 'counter',\r\n 'keyUp',\r\n 'keyDown',\r\n 'keyLeft',\r\n 'keyRight'], 'Counter', solarSystemID, self.ships.get(shipID), counter, '+'.join([ uicore.cmd.GetKeyNameFromVK(key) for key in self.controls.keyUp ]), '+'.join([ uicore.cmd.GetKeyNameFromVK(key) for key in self.controls.keyDown ]), '+'.join([ uicore.cmd.GetKeyNameFromVK(key) for key in self.controls.keyLeft ]), '+'.join([ uicore.cmd.GetKeyNameFromVK(key) for key in self.controls.keyRight ]))\r\n\r\n self.counters.clear()\r\n self.ships.clear()\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/eve/client/script/ui/services/flightControls.py","file_name":"flightControls.py","file_ext":"py","file_size_in_byte":15623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13841619472","text":"import os\nimport sys\nimport numpy as np\nimport cv2\nimport glob\nimport argparse\n\nhome_dir = home = os.path.expanduser(\"~\")\n\nlib_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')\n\nssd_detectors_dir = os.path.join(lib_dir, 'ssd_detectors')\nsys.path.append(ssd_detectors_dir)\n\nfrom tbpp_model import TBPP512, TBPP512_dense\nfrom utils.model_utils import load_weights, calc_memory_usage\nfrom ssd_data import preprocess\nfrom tbpp_utils import PriorUtil\nfrom utils.bboxes import rbox3_to_polygon\n\nsys.path.append(os.path.join(lib_dir, 'cascaded-faster-rcnn', 'evaluation'))\nfrom util import rotate_image, adjust_image_size\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--output_dir\", help=\"output dir\", default=os.path.join(home_dir, 'sean', 'output', 'tbpp', 'np_preds'))\nparser.add_argument(\"--weights_file\", help=\"file with model weights\", default=os.path.join(home_dir, 'sean', 'ssd_detectors', 'checkpoints', '201807091503_dsodtbpp512fl_synthtext', 'weights.018.h5'))\nparser.add_argument(\"--images_dir\", help=\"map images directory\", default=os.path.join(home_dir, 'data', 'maps'))\nparser.add_argument(\"--preprocess\", help=\"whether or not to preform same preprocess as done in original implementations (background removal, etc...)\")\nparser.add_argument(\"--test_only\", help=\"whether or not to only evaluate test images\")\nparser.add_argument(\"--test_split\", help=\"file from torch_phoc with test split\", default=os.path.join(home_dir, 'torch-phoc', 'splits', 'test_files.txt'))\nparser.add_argument(\"--confidence\", help=\"confidence threshold for predictions\", type=float, default=0.8)\nparser.add_argument(\"--rotate\", help=\"whether or not to rotate image\")\n\noptions = parser.parse_args()\n\nweights_path = options.weights_file\noutput_dir = options.output_dir\nmap_images_dir = options.images_dir\ndo_preprocess = bool(options.preprocess)\ntest_only = bool(options.test_only)\ntest_split_file = options.test_split\nconfidence_threshold = options.confidence\ndo_rotate_image = bool(options.rotate)\n\n# TextBoxes++ + DenseNet\nmodel = TBPP512_dense(softmax=False)\n\nload_weights(model, weights_path)\n\nprior_util = PriorUtil(model)\n\ntest_filenames = []\nif test_only:\n with open(test_split_file) as f:\n test_filenames = [line.replace(\"\\n\", \"\") for line in f.readlines()]\n\ncrop_h = 512\ncrop_w = 512\nstep = 400\n\nangles = range(-90, 95, 5) if do_rotate_image else [0]\n\nfor filepath in glob.glob(os.path.join(map_images_dir, 'D*')):\n filename = filepath.split('/')[-1]\n\n if test_only:\n if filename.split('.')[0] not in test_filenames:\n continue\n\n print(filepath)\n map_img = cv2.imread(filepath)\n original_shape = map_img.shape\n\n preds = []\n confs = []\n for angle in angles:\n rot_img, rot_mat, bounds = rotate_image(map_img, angle, original_shape)\n height = rot_img.shape[0]\n width = rot_img.shape[1]\n current_x = 0; current_y = 0\n\n while current_y + crop_h < height:\n while current_x + crop_w < width:\n \n crop_img = rot_img[current_y:current_y+crop_h, current_x:current_x+crop_w]\n \n if do_preprocess:\n crop_img = preprocess(crop_img, (512, 512))\n \n model_output = model.predict(np.array([crop_img]), batch_size=1, verbose=0)\n \n res = prior_util.decode(model_output[0], confidence_threshold, fast_nms=False)\n bboxes = res[:,0:4]\n quades = res[:,4:12]\n rboxes = res[:,12:17]\n conf = res[:,17:]\n\n for j in range(len(rboxes)):\n # convert rbox\n polygon = rbox3_to_polygon(rboxes[j])*512\n\n # translate to full image location\n polygon[:, 0] += current_x\n polygon[:, 1] += current_y\n\n # rotate to orientation when image is not rotated\n image_center = (original_shape[1] // 2, original_shape[0] // 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, -1*angle, scale=1.0)\n\n # add col for rotation\n polygon = np.concatenate([polygon, np.ones([polygon.shape[0], 1])], axis=1)\n\n # rotate\n transformed_points = rot_mat.dot(polygon.T).T\n\n preds.append( transformed_points[:, :2].astype(int) )\n confs.append( conf[j][0] )\n\n current_x += step\n\n current_x = 0\n current_y += step\n \n print(\"Found\", str(len(rboxes)), \"boxes for angle\", str(angle))\n\n np.save(os.path.join(output_dir, filename+'.npy'), preds)\n np.save(os.path.join(output_dir, filename+'_scores.npy'), confs)\n","repo_name":"seangtkelley/icken-and-chegg","sub_path":"python_scripts/generate_tbpp_preds.py","file_name":"generate_tbpp_preds.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29901667376","text":"#Set the percentage of cuda cores (1 = 100%)\n\nimport tensorflow as T\n\nfraction = 0.90\n\ndef set_gpu_fraction(sess=None, gpu_fraction=fraction):\n \"\"\"Set the GPU memory fraction for the application.\n\n Parameters\n ----------\n sess : a session instance of TensorFlow\n TensorFlow session\n gpu_fraction : a float\n Fraction of GPU memory, (0 ~ 1]\n\n References\n ----------\n - `TensorFlow using GPU `_\n \"\"\"\n print(\" tensorlayer: GPU MEM Fraction %f\" % gpu_fraction)\n gpu_options = T.compat.v1.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n sess = T.compat.v1.Session(config = T.compat.v1.ConfigProto(gpu_options = gpu_options))\n return sess \n\n\nset_gpu_fraction(None,fraction)\nprint(\"Num GPUs Available: \", len(T.config.list_physical_devices('GPU')))","repo_name":"LabChem/Multitask-Learning","sub_path":"utils/GPU.py","file_name":"GPU.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18708076950","text":"import random\nprint(\"You have 10 lifes in this game\\n\",\"You entered in the snake water gun game\\n\")\ni=1\nmyList=[\"S\",\"W\",\"G\"]\narr=[0,0]\ndef win():\n print(\"Congratulations you win\")\ndef lose():\n print(\"You lose.Better luck next time\")\nwhile i<=10:\n print(\"Round\",i)\n c=random.choice(myList)\n i=i+1\n user=input(\"S or W or G.Enter your choice.\\n\")\n if user==c:\n print(\"It's a tie\")\n arr[0] = arr[0] + 1\n arr[1] = arr[1] + 1\n elif user==\"S\" and c==\"W\":\n win()\n arr[0] = arr[0] + 1\n elif user==\"S\" and c==\"G\":\n lose()\n arr[1] = arr[1] + 1\n elif user==\"W\" and c==\"S\":\n lose()\n arr[1] = arr[1] + 1\n elif user==\"W\" and c==\"G\":\n win()\n arr[0] = arr[0] + 1\n elif user==\"G\" and c==\"S\":\n win()\n arr[0] = arr[0] + 1\n else:\n lose()\n arr[1] = arr[1] + 1\n\n\nprint(\"User:\",arr[0],\"\\nComputer:\",arr[1])\nif arr[0]==arr[1]:\n print(\"The game tied\")\nelif arr[0]>arr[1]:\n print(\"Congratulations you win the game YAAY!!!\")\nelse:\n print(\"You lose the game :( Try Again\")\n\n\n","repo_name":"MihirVora1053/Python","sub_path":"Projects/exercise6.py","file_name":"exercise6.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9663328553","text":"# Convert XML files to CSV (for traffic sign model using Colab) \n# $ python xml_to_csv.py -d data\n# Date: Sep 1, 2021\n# Jeongkyu Lee\n\nimport os\nimport glob\nimport pandas as pd\nimport xml.etree.ElementTree as ET\nimport random\nimport argparse\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--dir\", default = 'data',\n help=\"path for the training file directory, e.g., -d data\")\nargs = vars(ap.parse_args())\ndir_name = args[\"dir\"]\n\ndef xml_to_csv(path):\n xml_list = []\n record_list = ['TEST'] * 1 + ['TRAIN'] * 4 + ['VALIDATION'] * 1\n \n xml_files = glob.glob(path + '/*.xml')\n\n for xml_file in glob.glob(path + '/*.xml'):\n record_type = random.choice(record_list)\n tree = ET.parse(xml_file)\n root = tree.getroot()\n for member in root.findall('object'):\n value = (record_type,\n '/content/'+dir_name+'/'+root.find('filename').text,\n member[0].text,\n int(member[4][0].text)/int(root.find('size')[0].text),\n int(member[4][1].text)/int(root.find('size')[1].text),\n None,\n None,\n int(member[4][2].text)/int(root.find('size')[0].text),\n int(member[4][3].text)/int(root.find('size')[1].text),\n None,\n None\n )\n xml_list.append(value)\n column_name = ['type','filename', 'class', 'xmin', 'ymin', 'xr', 'yr', 'xmax', 'ymax', 'xl', 'yl']\n xml_df = pd.DataFrame(xml_list, columns=column_name)\n return xml_df\n\n\ndef main():\n image_path = os.path.join(os.getcwd(), dir_name)\n print(image_path)\n xml_df = xml_to_csv(image_path)\n xml_df.to_csv(dir_name+'/traffic_labels.csv', index=None)\n print('Successfully converted xml to csv.')\n\n\nmain()\n","repo_name":"jaykay0408/dmcar-student","sub_path":"model_traffic_sign/xml_to_csv.py","file_name":"xml_to_csv.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"33748961864","text":"# Name: date_Merge.py\r\n# By: Euan Traynor\r\n# Date: 13/05/19\r\n# Version: 1.2.3\r\n\r\nfrom datetime import date\r\ntoday = date.today() #gets date from computer database\r\ndate = today.strftime(\"%m/%d\") #sets structure/ look of date format\r\n\r\n# This creates function which can be recalled later (or specific elements can be recalled)\r\ndef mergeSort(family_List): # import family_List from bottom of code which is not defined in the function\r\n #print(\"Splitting \",family_List) # to show viewer the process on the terminal line. #the first time it will print the whole list\r\n if len(family_List)>1: #identifies how many objects are in the list and if greater then one, it will do the following code.\r\n mid = len(family_List)//2 #identifies number of objects in list and then uses pythons own version of interger division which identifies how many numbers are on left or right of middle number/s.\r\n lefthalf = family_List[:mid] # variable defines left side of the middle\r\n righthalf = family_List[mid:] # variable defines right side of the middle\r\n\r\n mergeSort(lefthalf) # tells function to recall lefthalf and operates it.\r\n mergeSort(righthalf) # tells function to recall righthalf and operates it.\r\n\r\n #these values will be recalled later to make sure that the code (if statements) will eventially end\r\n valueI=0\r\n valueX=0\r\n valueY=0\r\n\r\n while valueX < len(lefthalf) and valueY < len(righthalf): # if values X and Y are less than length of family_List lefthalf and righthalf, do the following code\r\n if lefthalf[valueX] < righthalf[valueY]: # check if lefthalf is smaller than right (append valueX to store the new half of the main list/array). \r\n family_List[valueI]=lefthalf[valueX] # If smaller, split list into two lists.\r\n valueX = valueX + 1 # add one to value X in order to eventially stop the loop\r\n else: # if it is not smaller, it will split the right half into two\r\n family_List[valueI]=righthalf[valueY]\r\n valueY = valueY + 1 # add one to value Y in order to eventially stop the loop\r\n valueI = valueI + 1 # and 1 to value I to eventially stop the while loop\r\n\r\n while valueX < len(lefthalf): # once new arrays have been made, start to split them.\r\n family_List[valueI]=lefthalf[valueX]\r\n valueX = valueX + 1\r\n valueI = valueI + 1\r\n\r\n while valueY < len(righthalf):\r\n family_List[valueI]=righthalf[valueY]\r\n valueY = valueY + 1\r\n valueI = valueI + 1\r\n #print(\"Merging \",family_List) # once completed merege the lefthalf and righthalf together\r\n # once all values are equal to length of family_List, finish\r\n\r\n#tells user that program has started without any errors in the Merge sort\r\nprint(\"START\")\r\nfamily_List = []\r\n\r\ndef startMerge(family_List):\r\n #input to choose what function you would like to run\r\n choice = int(input(\"\\nAdd TO DO item [1]\\nRemove TO DO item [2]\\nManual Merge [3]\\nList Objects [4]\\nExit [5]\\nChoice: \"))\r\n #if the choice is equal to the following digit, it will do the following\r\n if choice == 1:\r\n times(theEND)\r\n if choice == 2:\r\n remove()\r\n if choice == 3:\r\n mergeEND(family_List, date)\r\n if choice == 4:\r\n mergeEND(family_List, date)\r\n elif choice == 5:\r\n exit()\r\n else:\r\n print(\"NOT valid ../\")\r\n startMerge(family_List)\r\n\r\ndef mergeEND(family_List, date):\r\n #saves information to data document to allow merge algorithm to access values of Objects later.\r\n output = open(\"./dates.txt\", \"r\") # open this document\r\n \r\n lines = output.readlines() #Identifies and reads the lines which is store in variable lines\r\n for i in range(len(lines)): #identifies how many objects are in document accroding to each line\r\n lines[i]=lines[i].replace('\\n','') # creates a list to store values which will be merged later.\r\n output.close() # close document in case of error.\r\n\r\n #writes lines on data document with a new line per each object\r\n with open(\"./dates.txt\", \"w\") as output:\r\n #for item in alist:\r\n # output.write(\"%s\\n\" % item)\r\n output.writelines(\"%s\\n\" % num for num in lines)\r\n\r\n nums = []\r\n\r\n #adding items in data document to list\r\n with open('./dates.txt', 'r') as filehandle: \r\n filecontents = filehandle.readlines()\r\n\r\n for line in filecontents:\r\n # remove linebreak which is the last character of the string\r\n lines = line[:-1]\r\n\r\n # add item to the list\r\n nums.append(lines)\r\n family_List = nums\r\n\r\n #print final copy of list and restart main menu\r\n output.close()\r\n end(family_List)\r\n # if choice == 3:\r\n # end(family_List)\r\n # if choice == 4:\r\n # cleanList(family_List)\r\n # else:\r\n # print(\"Error \\n- Reloading data\")\r\n # mergeEND(family_List, date, choice)\r\n \r\n\r\ndef end(family_List):\r\n newAdd = date + \" {(TODAY)}\"\r\n family_List.append(newAdd)\r\n index = family_List.index(newAdd) - 1\r\n # listLen = len(family_List)\r\n # index = (listLen - index)\r\n if newAdd in family_List:\r\n print(\"\\n | Current Date: \" + date)\r\n print(\" | Pos:\", index)\r\n \r\n print(\"\\nOriginal Array:\")\r\n #starts merge algorithm\r\n mergeSort(family_List)\r\n print(family_List)\r\n print(\"\\nNew Array:\")\r\n mid = index\r\n lefthalf = family_List[:mid]\r\n righthalf = family_List[mid:]\r\n finalDates = righthalf + lefthalf\r\n index = finalDates.index(newAdd)\r\n finalDates.pop(index)\r\n print(finalDates)\r\n startMerge(family_List)\r\n else:\r\n print(\"Error\\n - Reloading\")\r\n startMerge(family_List)\r\n\r\n#convert the list into string\r\ndef convert(theEND):\r\n # initialization of string to \"\" \r\n newEND = \"\" \r\n # traverse in the string \r\n for x in theEND: \r\n newEND += x + \"\\n\"\r\n # return string\r\n return newEND\r\n\r\ndef times(theEND):\r\n #set score at begining to zero\r\n total = 0\r\n #gets name of new To Do\r\n nameList = []\r\n name = input(\"\\nNAME (no numbers or symbols): \")\r\n nameList.append(name)\r\n\r\n #asks what type of job it is.\r\n Type = input(\"Type\\n[1]Homework\\n[2]Assignment\\n[3]Test Revision\\n[4]Chore\\nPLEASE INSERT NUMBER: \")\r\n Type = int(Type)\r\n #depending on importance of job, it is given a value to its total value.\r\n #The lower the number, the more important it is.\r\n if Type == 1:\r\n total = total + 3\r\n elif Type == 2:\r\n total = total + 2\r\n elif Type == 3: \r\n total = total + 1\r\n elif Type == 4:\r\n total = total + 4\r\n\r\n #identifies difficulty of the task, it is given a value to its total value.\r\n #The lower the number, the more important it is.\r\n diff = input(\"DIIFICULTY\\n[1, 2 or 3]: \")\r\n diff = int(diff)\r\n if diff == 1:\r\n total = total + 3\r\n elif diff == 2:\r\n total = total + 2\r\n elif diff == 3: \r\n total = total + 1\r\n\r\n #Date sorter\r\n askDate(total, name)\r\n\r\ndef askDate(total, name):\r\n dueDate = input(\"Due Date (dd/MM): \")\r\n #check if letter is in due date input\r\n\r\n if len(dueDate) != 5:\r\n print(\"Invalid...\")\r\n askDate(total, name)\r\n else:\r\n dueDate = dueDate.replace(\"/\", \"\")\r\n mid = len(dueDate)//2 #identifies number of objects in list and then uses pythons own version of interger division which identifies how many numbers are on left or right of middle number/s.\r\n lefthalf = str(dueDate[:mid]) # variable defines left side of the middle\r\n righthalf = str(dueDate[mid:]) # variable defines right side of the middle\r\n dueDate = (righthalf + \"/\" + lefthalf)\r\n dueDateChecker(dueDate, total, name)\r\n\r\ndef ifDouble(total, name):\r\n #gets the data stored in data document and inserts it into the main list so that\r\n #when data from document is reset, the data can be saved and re-inserted after merge.\r\n before = []\r\n with open('./dates.txt', 'r') as filehandle: \r\n filecontents = filehandle.readlines()\r\n\r\n for line in filecontents:\r\n # remove linebreak which is the last character of the string\r\n lines = line[:-1]\r\n\r\n # add item to the list\r\n before.append(lines)\r\n theEND = before\r\n \r\n #Re-insert list with previous and new values back into data document,\r\n #data seperated with new line\r\n with open('./dates.txt', 'w') as output: \r\n for listitem in theEND:\r\n output.write('%s\\n' % listitem)\r\n\r\n #merge sort final new input with list \r\n #and go back to main menu\r\n mergeEND(family_List, date)\r\n\r\n#allows user to remove object from data stored. \r\ndef remove():\r\n #name of object you would like to remove\r\n nameObject = input(\"\\nName of TO DO: \")\r\n #open data file and seek all lines.\r\n with open(\"./dates.txt\",\"r+\") as f:\r\n new_f = f.readlines()\r\n f.seek(0)\r\n for line in new_f: #for each individual line in data document\r\n if nameObject not in line: #if the input is in that line, it will break loop and...\r\n f.write(line) #replace the line with a blank line\r\n f.truncate()\r\n\r\n #go back to main menu\r\n startMerge(family_List)\r\n\r\ndef cleanList(family_List):\r\n newAdd = date + \" {(TODAY)}\"\r\n family_List.append(newAdd)\r\n index = family_List.index(newAdd)\r\n listLen = len(family_List)\r\n indexMid = (listLen - index) - 1\r\n #starts merge algorithm\r\n mergeSort(family_List)\r\n mid = indexMid\r\n lefthalf = family_List[:mid]\r\n righthalf = family_List[mid:]\r\n finalDates = righthalf + lefthalf\r\n index = finalDates.index(newAdd)\r\n finalDates.pop(index)\r\n listObjects(family_List, index)\r\n\r\n#to list objects downwards\r\ndef listObjects(family_List, index):\r\n print(\"\\n\")\r\n mid = index\r\n lefthalf = family_List[:mid]\r\n righthalf = family_List[mid:]\r\n family_List = righthalf + lefthalf\r\n family_List.pop(index)\r\n for x in family_List: \r\n print(x)\r\n startMerge(family_List)\r\n\r\ndef dueDateChecker(dueDate, total, name):\r\n #gets the data stored in data document and inserts it into the main list so that\r\n #when data from document is reset, the data can be saved and re-inserted after merge.\r\n before = []\r\n with open('./dates.txt', 'r') as filehandle: \r\n filecontents = filehandle.readlines()\r\n\r\n for line in filecontents:\r\n # remove linebreak which is the last character of the string\r\n lines = line[:-1]\r\n\r\n # add item to the list\r\n before.append(lines)\r\n theEND = before\r\n\r\n #print total and name of Object\r\n dueDate = str(dueDate)\r\n total = str(total)\r\n dueDate = dueDate + \" {\" + total +\"(\" + name + \")}\"\r\n theEND.append(dueDate)\r\n\r\n #convert the list into string\r\n print(\"\\n\" + convert(theEND))\r\n \r\n #Re-insert list with previous and new values back into data document,\r\n #data seperated with new line\r\n with open('./dates.txt', 'w') as output: \r\n for listitem in theEND:\r\n output.write('%s\\n' % listitem)\r\n \r\n ifDouble(total, name)\r\n\r\n\r\n#declaring main list and start variable\r\ntheEND = []\r\nstart = 0\r\n#starting main menu function\r\nstartMerge(family_List)\r\n","repo_name":"efalloon/Smart-To-Do-List","sub_path":"date_Merge.py","file_name":"date_Merge.py","file_ext":"py","file_size_in_byte":11453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72790417445","text":"# %%\nimport torch # Import the torch library\nimport torch.nn as nn # Import the torch.nn module\nimport torchvision.models as models # Import the models module from torchvision\nimport torch.nn.functional as F # Import the torch.nn.functional module\nfrom torch.nn.functional import adaptive_avg_pool2d # Import the adaptive_avg_pool2d function from torch.nn.functional\n\n# %%\nclass Generator(nn.Module):\n def __init__(self, ngpu, latent_dim, ngf=64, img_channels=3):\n super(Generator, self).__init__()\n self.ngpu = ngpu\n self.latent_dim = latent_dim\n self.bias = True\n\n # Define the transposed convolution layers\n self.tconv1 = nn.Sequential(\n nn.ConvTranspose2d(latent_dim, ngf*4, kernel_size=4, stride=1, padding=0, bias=self.bias),\n nn.LeakyReLU(0.2, inplace=True),\n )\n # state size: (ngf*4) x 4 x 4\n\n self.tconv2 = nn.Sequential(\n nn.ConvTranspose2d(ngf*4, ngf*2, kernel_size=4, stride=2, padding=1, bias=self.bias),\n nn.LeakyReLU(0.2, inplace=True),\n )\n # state size: (ngf*2) x 8 x 8\n\n self.tconv3 = nn.Sequential(\n nn.ConvTranspose2d(ngf*2, ngf, kernel_size=4, stride=2, padding=1, bias=self.bias),\n nn.LeakyReLU(0.2, inplace=True),\n )\n # state size: (ngf) x 16 x 16\n\n self.tconv4 = nn.Sequential(\n nn.ConvTranspose2d(ngf, img_channels, kernel_size=4, stride=2, padding=1, bias=self.bias),\n nn.Tanh()\n )\n # state size: (img_channels) x 32 x 32\n\n def forward(self, input, reverse=True):\n fc1 = input.view(input.size(0), input.size(1), 1, 1)\n # Reshape the input tensor\n\n tconv1_output = self.tconv1(fc1)\n # Apply the first transposed convolution layer\n\n tconv2_output = self.tconv2(tconv1_output)\n # Apply the second transposed convolution layer\n\n tconv3_output = self.tconv3(tconv2_output)\n # Apply the third transposed convolution layer\n\n output = self.tconv4(tconv3_output)\n # Apply the fourth transposed convolution layer\n\n if reverse:\n output = grad_reverse(output)\n # Reverse the gradient of the output (custom function)\n\n return output\n\n# %% [markdown]\n# 1. The `Generator` class is defined as a subclass of `nn.Module`, which is the base class for all neural network modules in PyTorch.\n# \n# 2. In the `__init__` method, the constructor initializes the generator by specifying the number of GPUs (`ngpu`), the dimension of the input noise vector (`latent_dim`), the number of filters in the generator's convolutional layers (`ngf`), and the number of channels in the output image (`img_channels`).\n# \n# 3. The generator uses transposed convolution layers (`nn.ConvTranspose2d`) to upsample the input noise and generate images. The transposed convolution layers are defined and initialized in the constructor.\n# - `self.tconv1` is the first transposed convolution layer that takes the input noise and produces feature maps with `ngf*4` channels. It uses a kernel size of 4, stride of 1, and no padding. It is followed by a leaky ReLU activation function (`nn.LeakyReLU`).\n# - `self.tconv2` is the second transposed convolution layer that takes the output of `self.tconv1` and produces feature maps with `ngf*2` channels. It uses a kernel size of 4, stride of 2, and padding of 1. It is also followed by a leaky ReLU activation function.\n# - `self.tconv3` is the third transposed convolution layer that takes the output of `self.tconv2` and produces feature maps with `ngf` channels. It uses the same configuration as `self.tconv2`.\n# - `self.tconv4` is the final transposed convolution layer that takes the output of `self.tconv3` and produces the final output image. It uses a kernel size of 4, stride of 2, and padding of 1. It is followed by a hyperbolic tangent (`nn.Tanh`) activation function to ensure the output values are within the range [-1, 1].\n# \n# 4. The `forward` method implements the forward pass of the generator. It takes an input tensor (`input`) and a boolean flag (`reverse`) to indicate whether to reverse the gradient of the output.\n# - The input tensor is reshaped (`view`) to have dimensions (batch_size, latent_dim, 1, 1), where `latent_dim` is the dimension of the input noise vector.\n# - The reshaped tensor is passed through each transposed convolution layer (`self.tconv1`, `self.tconv2`, `self.tconv3`, `self.tconv4`) sequentially.\n# - If the `reverse` flag is `True`, the gradient of the output tensor is reversed using a custom function called `grad_reverse` (not defined in the provided code). This is often used in domain adaptation tasks to fool the discriminator by making the generator's output look more like the target domain.\n# - The final output tensor is returned.\n# \n# Overall, this code defines the architecture of a generator model for a GAN, which generates synthetic images from random noise.\n\n# %%\nclass GradReverse(torch.autograd.Function):\n @staticmethod\n def forward(self, x):\n # The forward pass returns the input tensor as is\n return x.view_as(x)\n\n @staticmethod\n def backward(self, grad_output):\n # The backward pass multiplies the gradient output by -1\n return (grad_output * -1)\n\ndef grad_reverse(x):\n # Apply the gradient reversal operation using the custom GradReverse function\n return GradReverse.apply(x)\n\n# %% [markdown]\n# 1. The code defines a custom autograd function called `GradientReverse`. This function will be used to reverse the gradient during the backpropagation process.\n# \n# 2. The `forward` method of `GradientReverse ` takes an input tensor `x ` and returns it as is, without any modifications. This is the identity operation.\n# \n# 3. The `backward ` method of `GradientReverse ` takes the gradient of the output with respect to the forward pass and multiplies it by -1. This effectively reverses the gradient direction.\n# \n# 4. The `grad_reverse ` function is defined to apply the gradient reversal operation. It calls the `apply ` method of `GradientReverse ` to perform the operation on the input tensor `x `.\n# \n# By using the `grad_reverse ` function, you can reverse the gradients during the backpropagation process, which can be useful for tasks such as domain adaptation in adversarial learning setups.\n\n# %%\nclass Flatten(torch.nn.Module):\n def forward(self, input):\n # Retrieve the batch size from the input tensor\n batch_size = input.shape[0]\n\n # Reshape the input tensor to have shape (batch_size, -1)\n flattened_input = input.view(batch_size, -1)\n\n # Return the flattened input tensor\n return flattened_input\n\n# %% [markdown]\n# 1. The code defines a custom module called `Flatten `, which inherits from `torch.nn.Module `. This module is responsible for flattening the input tensor.\n# \n# 2. The `forward ` method of `Flatten ` is overridden to define the forward pass operation.\n# \n# 3. Inside the `forward ` method, the batch size is obtained from the input tensor using `x.shape[0] `. This represents the number of samples in the batch.\n# \n# 4. The input tensor is then reshaped using `x.view(batch_size, -1) `. The `view ` function is used to reshape the tensor, where `batch_size ` represents the number of samples in the batch, and `1 ` infers the correct size for the remaining dimensions.\n# \n# 5. The flattened input tensor is returned as the output of the forward pass.\n# \n# The purpose of the `Flatten ` module is to flatten multi-dimensional input tensors into a 2D representation, which is commonly required when transitioning from convolutional layers to fully connected layers in neural networks.\n\n# %%\nclass Discriminator(nn.Module):\n def __init__(self, ngpu, latent_dim, ndf=64, img_channels=3, dropout_prob=0.0):\n super(Discriminator, self).__init__()\n self.ngpu = ngpu\n self.ndf = ndf\n self.bias = True\n\n # Input size: (img_channels) x 32 x 32\n self.conv1 = nn.Sequential(\n nn.Conv2d(img_channels, ndf, kernel_size=4, stride=2, padding=1, bias=self.bias),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n # Output size: (ndf) x 16 x 16\n self.conv2 = nn.Sequential(\n nn.Conv2d(ndf, ndf*2, kernel_size=4, stride=2, padding=1, bias=self.bias),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n # Output size: (ndf*2) x 8 x 8\n self.conv3 = nn.Sequential(\n nn.Conv2d(ndf*2, ndf*4, kernel_size=4, stride=2, padding=1, bias=self.bias),\n nn.LeakyReLU(0.2, inplace=True),\n )\n\n # Output size: (latent_dim) x 4 x 4\n self.conv4 = nn.Sequential(\n nn.Conv2d(ndf * 4, latent_dim, kernel_size=4, stride=2, padding=0, bias=self.bias),\n Flatten()\n )\n\n # Output size: 1 x 1\n self.dis = nn.Sequential(\n nn.Conv2d(ndf * 4, 1, kernel_size=4, stride=2, padding=0, bias=self.bias),\n Flatten()\n )\n\n # Sigmoid activation function\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, input):\n # Pass input through the convolutional layers\n conv1 = self.conv1(input)\n conv2 = self.conv2(conv1)\n conv3 = self.conv3(conv2)\n\n # Perform the real/fake classification\n fc_dis = self.sigmoid(self.dis(conv3))\n\n # Extract the encoded feature representation\n fc_enc = self.conv4(conv3)\n\n # Reshape the real/fake classification tensor\n realfake = fc_dis.view(-1, 1).squeeze(1)\n\n return fc_enc, realfake\n\n\n# %% [markdown]\n# 1. The code defines a discriminator model for a GAN. The discriminator takes an input image and outputs both an encoded feature representation and a real/fake classification.\n# \n# 2. The `Discriminator ` class inherits from `nn.Module ` and defines the discriminator architecture.\n# \n# 3. The constructor ( `__init__ ` method) initializes the discriminator by specifying the number of GPUs ( `ngpu `), the dimension of the encoded feature representation ( `latent_dim `), the number of filters in the discriminator's convolutional layers ( `ndf `), the number of channels in the input image ( `img_channels `), and the dropout probability ( `dropout_prob `).\n# \n# 4. The discriminator uses convolutional layers ( `nn.Conv2d `) followed by leaky ReLU activation functions ( `nn.LeakyReLU `) to process the input image and extract features.\n# \n# 5. The discriminator has four convolutional layers ( `self.conv1 `, `self.conv2 `, `self.conv3 `, `self.conv4 `) that progressively downsample the input image.\n# \n# 6. The `self.dis ` layer performs a convolution followed by flattening to output the real/fake classification.\n# \n# 7. The `self.conv4 ` layer performs a convolution followed by flattening to output the encoded feature representation.\n\n# %%\nclass OutputClassifier(nn.Module):\n def __init__(self, input_size, hidden_size=32, num_classes=10):\n super(OutputClassifier, self).__init__()\n\n # Define the fully connected layer for classification\n self.fc_classifier = nn.Sequential(\n nn.Linear(input_size, num_classes, bias=True),\n )\n\n # Softmax activation function for class probabilities\n self.softmax = nn.Softmax()\n\n def forward(self, input):\n # Perform classification using the fully connected layer\n classes = self.fc_classifier(input)\n\n return classes\n\n# %% [markdown]\n# 1. The code defines an output classifier model that takes an input and predicts the class labels.\n# \n# 2. The `OutputClassifier ` class inherits from `nn.Module ` and defines the classifier architecture.\n# \n# 3. The constructor ( `__init__ ` method) initializes the classifier by specifying the input size ( `input_size `), the size of the hidden layer ( `hidden_size `), and the number of classes ( `num_classes `).\n# \n# 4. The classifier consists of a single fully connected layer ( `nn.Linear `) that maps the input to the number of classes. This layer performs the classification task.\n# \n# 5. The `self.softmax ` layer applies the softmax activation function to the output of the classifier. This converts the output logits into class probabilities.\n# \n# 6. The forward pass is implemented in the `forward ` method. It takes an input, performs classification using the fully connected layer, and returns the predicted classes.\n# \n# Please note that the `softmax ` function is typically not applied within the model, as it is usually incorporated in the loss function or evaluation metric outside the model.\n\n# %%\nclass InputClassifier(nn.Module):\n def __init__(self, input_dim, num_classes=10):\n super(InputClassifier, self).__init__()\n\n # Define the fully connected layer for classification\n self.fc_classifier = nn.Sequential(\n nn.Linear(input_dim, num_classes, bias=True),\n )\n\n def forward(self, input):\n # Reshape the input from batch_size x 28 x 28 to batch_size x (28*28)\n out = input.view(input.size(0), -1)\n\n # Perform classification using the fully connected layer\n out = self.fc_classifier(out)\n\n return out\n\n# %% [markdown]\n# 1. The code defines an input classifier model that takes an input and predicts the class labels.\n# \n# 2. The `InputClassifier ` class inherits from `nn.Module ` and defines the classifier architecture.\n# \n# 3. The constructor ( `__init__ ` method) initializes the classifier by specifying the input dimension ( `input_dim `) and the number of classes ( `num_classes `).\n# \n# 4. The classifier consists of a single fully connected layer ( `nn.Linear `) that maps the input to the number of classes. This layer performs the classification task.\n# \n# 5. The forward pass is implemented in the `forward ` method. It takes an input and reshapes it from batch_size x 28 x 28 to batch_size x (28*28). This flattens the input image into a 1D vector.\n# \n# 6. The flattened input is then passed through the fully connected layer ( `self.fc_classifier `), which applies the linear transformation (input * A + b) where A and b are learnable parameters of the linear layer.\n# \n# 7. The output `out ` represents the logits or scores for each class. The final predicted class can be obtained by applying a softmax activation function or using an appropriate loss function during training.\n# \n# Please note that the code assumes the input shape to be batch_size x 28 x 28, which is a common representation for images in MNIST-like datasets.\n\n# %%\nclass InceptionV3(nn.Module):\n \"\"\"Pretrained InceptionV3 network returning feature maps\"\"\"\n\n DEFAULT_BLOCK_INDEX = 3 # Index of default block of inception to return\n\n # Maps feature dimensionality to their output block indices\n BLOCK_INDEX_BY_DIM = {\n 64: 0, # First max pooling features\n 192: 1, # Second max pooling features\n 768: 2, # Pre-aux classifier features\n 2048: 3 # Final average pooling features\n }\n\n def __init__(self, output_blocks=[DEFAULT_BLOCK_INDEX], resize_input=True, normalize_input=True, requires_grad=False):\n super(InceptionV3, self).__init__()\n\n self.resize_input = resize_input\n self.normalize_input = normalize_input\n self.output_blocks = sorted(output_blocks)\n self.last_needed_block = max(output_blocks)\n\n assert self.last_needed_block <= 3, 'Last possible output block index is 3'\n\n self.blocks = nn.ModuleList()\n\n # Load the pretrained InceptionV3 model\n inception = models.inception_v3(pretrained=True)\n\n # Block 0: input to maxpool1\n block0 = [\n inception.Conv2d_1a_3x3,\n inception.Conv2d_2a_3x3,\n inception.Conv2d_2b_3x3,\n nn.MaxPool2d(kernel_size=3, stride=2)\n ]\n self.blocks.append(nn.Sequential(*block0))\n\n # Block 1: maxpool1 to maxpool2\n if self.last_needed_block >= 1:\n block1 = [\n inception.Conv2d_3b_1x1,\n inception.Conv2d_4a_3x3,\n nn.MaxPool2d(kernel_size=3, stride=2)\n ]\n self.blocks.append(nn.Sequential(*block1))\n\n # Block 2: maxpool2 to aux classifier\n if self.last_needed_block >= 2:\n block2 = [\n inception.Mixed_5b,\n inception.Mixed_5c,\n inception.Mixed_5d,\n inception.Mixed_6a,\n inception.Mixed_6b,\n inception.Mixed_6c,\n inception.Mixed_6d,\n inception.Mixed_6e,\n ]\n self.blocks.append(nn.Sequential(*block2))\n\n # Block 3: aux classifier to final avgpool\n if self.last_needed_block >= 3:\n block3 = [\n inception.Mixed_7a,\n inception.Mixed_7b,\n inception.Mixed_7c,\n nn.AdaptiveAvgPool2d(output_size=(1, 1))\n ]\n self.blocks.append(nn.Sequential(*block3))\n\n # Set the requires_grad property of parameters\n for param in self.parameters():\n param.requires_grad = requires_grad\n\n def forward(self, input):\n \"\"\"Get Inception feature maps\"\"\"\n output = []\n x = input\n\n if self.resize_input:\n x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False)\n\n if self.normalize_input:\n x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1)\n\n for idx, block in enumerate(self.blocks):\n x = block(x)\n if idx in self.output_blocks:\n output.append(x)\n\n if idx == self.last_needed_block:\n break\n\n return\n\n\n# %% [markdown]\n# The code defines a PyTorch module called `InceptionV3`, which represents a pretrained InceptionV3 network returning feature maps.\n# \n# The key components and functionalities of the code are as follows:\n# \n# 1. The class variable `DEFAULT_BLOCK_INDEX` is set to 3, representing the index of the default block of the Inception network to return.\n# \n# 2. The dictionary `BLOCK_INDEX_BY_DIM` maps feature dimensionality to their respective output block indices.\n# \n# 3. The `__init__` method initializes the `InceptionV3` module. It takes several parameters:\n# - `output_blocks`: A list of output block indices to return. The default is the `DEFAULT_BLOCK_INDEX` (3).\n# - `resize_input`: A boolean indicating whether to resize the input. The default is `True`.\n# - `normalize_input`: A boolean indicating whether to normalize the input. The default is `True`.\n# - `requires_grad`: A boolean indicating whether the model's parameters require gradient computation. The default is `False`.\n# \n# 4. The method loads the pretrained InceptionV3 model using `models.inception_v3(pretrained=True)`.\n# \n# 5. The different blocks of the InceptionV3 model are constructed and stored in `self.blocks` using `nn.Sequential`.\n# - Block 0 corresponds to the input to maxpool1 and consists of several convolutional layers and a max pooling layer.\n# - Block 1 corresponds to maxpool1 to maxpool2 and consists of convolutional layers and a max pooling layer.\n# - Block 2 corresponds to maxpool2 to the auxiliary classifier and consists of several mixed layers.\n# - Block 3 corresponds to the auxiliary classifier to the final average pooling layer.\n# \n# 6. The `forward` method performs the forward pass of the InceptionV3 network. It takes an input tensor `input` and returns a list of feature maps corresponding to the selected output blocks.\n# - The input tensor is resized and normalized if specified.\n# - The input tensor is passed through the blocks sequentially, and the output feature maps are stored in the `output` list.\n# - The method breaks the loop when it reaches the last needed block.\n# \n# Overall, this code allows you to use the pretrained InceptionV3 model to extract specific feature maps based on the desired output blocks.\n\n\n","repo_name":"thaaoliveira1/Results-Learning-Cortical-Representations-Trough-Perturbed-and-Adversarial-Dreaming","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":20064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38224465416","text":"\"\"\"\nCOMP20008 Elements of Data Processing\n2022 Semester 1\nAssignment 1\n\nSolution to Task 7\n\"\"\"\nimport json\nimport os\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom utils import (\n read_articles, # Returns a list of articles\n)\n\n\ndef task7():\n\n # Read the articles\n articles = read_articles()\n\n # Read the tokenised articles\n assert os.path.isfile(\"task6.json\"), \"Task 6's JSON output not found.\"\n with open(\"task6.json\", \"r\") as f:\n token_to_articles = json.load(f)\n\n # Read the merged data frame for articles and reviews\n assert os.path.isfile(\"task2.csv\"), \"Task 2's CSV output not found.\"\n merged_df = pd.read_csv(\"task2.csv\", index_col=\"news_id\")\n\n num_real = merged_df[merged_df.rating >= 3].shape[0]\n num_fake = merged_df[merged_df.rating < 3].shape[0]\n num_articles = merged_df.shape[0]\n assert num_real + num_fake == num_articles\n\n def count_real_fake(news_ids):\n \"\"\"\n Take a list of news IDs and return the count of\n real and fake articles\n \"\"\"\n sub_df = merged_df.loc[news_ids]\n num_real = sub_df[sub_df.rating >= 3].shape[0]\n num_fake = sub_df[sub_df.rating < 3].shape[0]\n assert num_real + num_fake == len(news_ids)\n return num_real, num_fake\n\n # Count the number of real and fake articles containing each word\n real_fake_tally = pd.DataFrame(columns=[\"real\", \"fake\"], index=[],\n dtype=np.float32)\n for token, news_ids in token_to_articles.items():\n\n # Remove word that appear in fewer than 10 articles and those that\n # appear in all articles\n if len(news_ids) < 10 or len(news_ids) >= num_articles:\n continue\n\n real, fake = count_real_fake(news_ids)\n\n # Remove words that are exclusive to real or fake articles\n if real <= 0 or fake <= 0:\n continue\n\n real_fake_tally.loc[token, \"real\"] = real\n real_fake_tally.loc[token, \"fake\"] = fake\n\n # Log odds ratio\n p_f = real_fake_tally[\"fake\"] / num_fake\n o_f = p_f / (1 - p_f)\n p_r = real_fake_tally[\"real\"] / num_real\n o_r = p_r / (1 - p_r)\n log_odds_ratios = pd.Series(data=np.log10(o_f / o_r),\n index=real_fake_tally.index,\n name=\"log_odds_ratio\")\n log_odds_ratios.index.name = \"word\"\n log_odds_ratios = log_odds_ratios.sort_values()\n\n # Save to csv\n log_odds_ratios.sort_index().round(5).to_csv(\"task7a.csv\")\n\n plt.figure(figsize=(5, 5))\n plt.axvline(x=log_odds_ratios.mean(), c=\"red\", alpha=0.8)\n plt.hist(log_odds_ratios, bins=50, alpha=0.6,\n weights=np.ones_like(log_odds_ratios) / len(log_odds_ratios))\n plt.xlabel(\"$log_{10}$ odds ratio (fake / real)\", size=20)\n plt.xticks(size=10)\n plt.ylabel(\"Probability\", size=20)\n plt.yticks(size=10)\n plt.annotate(xy=(0, 0.1),\n text=f\"$\\mu = {log_odds_ratios.mean() : .2f}$\\n\"\n f\"$\\sigma = {log_odds_ratios.std() : .2f}$\",\n size=15, va=\"center\", ha=\"left\")\n plt.savefig(\"task7b.png\", bbox_inches=\"tight\")\n plt.close()\n\n num_words = 15\n df = log_odds_ratios[:num_words]\n df = pd.concat([df, log_odds_ratios[-num_words:]])\n\n ax = df.plot.barh(y=\"or\", figsize=(6, 8),\n color=(df > 0).map({True: 'r', False: 'b'}),\n legend=None)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n plt.xlabel(\"$log_{10}$ odds ratio (fake vs. real news)\", size=15)\n plt.ylabel(\"\")\n plt.xticks(size=12)\n plt.yticks(size=12)\n plt.grid(\"y\", alpha=0.3)\n colors = {\"Fake news\": \"r\", \"Real news\": \"b\"}\n handles = [plt.Rectangle((0, 0), 1, 1, color=colors[label])\n for label in colors]\n plt.legend(handles, colors.keys(), prop={'size': 13},\n bbox_to_anchor=(0.4, 0.5))\n\n labels = ax.get_yticklabels()\n for label in labels:\n text = label.get_text()\n _, y = label.get_position()\n alignment = \"right\" if df[text] > 0 else \"left\"\n hspace = 0.02 * (1 if alignment == \"left\" else -1)\n ax.text(x=0 + hspace, y=y, s=text, ha=alignment, va=\"center\", size=12)\n\n ax.set_yticks([])\n\n plt.savefig(\"task7c.png\", bbox_inches=\"tight\")\n plt.close()\n\n","repo_name":"ilndht/data-proccessing","sub_path":"task7.py","file_name":"task7.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9342158782","text":"# we need to break down the IntersectPolygons method into smaller functions. I am experiencing too many bugs\n\n# the objective today will be to break the method into 5 parts\n # 1. Read in the annotation data and return a list of dictionaries\n # 2. Pass the list of dictionaries to a readIMage function, read in an image from the filename key\n # 3. Padd the image and tile the image. Return a list of coordinates for the bounding boxes\n # 4. Iterate over each of the segmentations in the image and intersect them with the tile bounding boxes\n # 5. If the segmentation intersects the tile, add it to a list of objects\n # 6. Iterate over the list of objects and add them to the dataset_dicts\n\ndef convertPoints(anno):\n points = [[]]\n \n for x_coordinate in range(0,len(anno[\"all_points_x\"]),2):\n points.append([anno[\"all_points_x\"][x_coordinate],anno[\"all_points_y\"][x_coordinate]])\n \n # remove empyt lists from the list of points\n points = [x for x in points if x]\n \n return points\n\n\n\ndef intersectBoundingBox(points,xmin,ymin,xmax,ymax):\n converted_points = []\n\n for p in points:\n if p[0]>=xmin and p[0]<=xmax and p[1]>=ymin and p[1]<=ymax:\n p[0]=p[0]-xmin\n p[1]=p[1]-ymin\n converted_points.append(p)\n \n #print(converted_points)\n\n return converted_points\n\n\n\ndef readAnnotation(img_dir):\n '''\n :param img_dir:\n :return list of dictionaries:\n\n '''\n anno_file=os.path.join(img_dir,\"regiondata.csv\")\n annotab=pd.read_csv(anno_file,delimiter=\",\")\n files=annotab['filename'].unique()\n\n\n\n return annotab, files\n\ndef readImage(img_dir,filename):\n '''\n :param img_dir:\n :param filename:\n :return image:\n '''\n img_file=os.path.join(img_dir,filename)\n img=cv2.imread(img_file)\n height = img.shape[0]\n width = img.shape[1]\n \n # padd the image to be divisible by 512\n # padd the image\n pad_h=(512 - (height % 512)) % 512\n pad_w=(512 - (width % 512)) % 512\n # pad the image\n img=cv2.copyMakeBorder(img,0,pad_h,0,pad_w,cv2.BORDER_CONSTANT,value=[0,0,0])\n\n\n\n return img\n\ndef tileImage(img):\n '''\n :param img:\n :return list of coordinates:\n :rtype list:\n\n Objective: output a list of coordinates for the bounding boxes of the tiles\n\n '''\n tiles=[[]]\n for i in range(0,img.shape[0],512):\n for j in range(0,img.shape[1],512):\n #print(i,j)\n tile=img[i:i+512,j:j+512]\n xmin=j\n ymin=i\n xmax=j+512\n ymax=i+512\n tiles[0].append([xmin,ymin,xmax,ymax])\n \n\n return tiles\n\ndef IntersectSegmentations(img_dir,output_dir, tiles, img, annotab, file):\n '''\n :param tiles:\n :paramtype list:\n :param img:\n :paramtype numpy array:\n :param annotab:\n :paramtype pandas dataframe:\n :param files:\n :paramtype list:\n :return dataset_dicts:\n :rtype list:\n\n Objective: iterate over each of the segmentations in the image and intersect them with the tile bounding boxes\n '''\n filename=os.path.join(img_dir,file)\n records=[]\n # iterate over the tile coordinates\n for tile in tiles[0]:\n record = {}\n \n # get the coordinate over the tile image\n xmin=tile[0]\n ymin=tile[1]\n xmax=tile[2]\n ymax=tile[3]\n \n #print(xmin,ymin,xmax,ymax)\n #subset the image to the tile coordinates\n subimg=img[xmin:xmax,ymin:ymax]\n\n # make a tile id using the UUID\n uid = str(uuid.uuid4())\n\n # write the image tile to a file using the UID as the name\n \n\n \n\n # begin building the record by adding the information for the COCO dataset\n record[\"filename\"] = uid + '.jpg'\n record[\"height\"] = 512\n record[\"width\"] = 512\n # make an empty list of objects for record annotation\n record[\"annotations\"] = []\n \n subtab = annotab[annotab['filename'] == file]\n objs =[]\n for anno_i in range(subtab.shape[0]):\n \n tab_rec=subtab.iloc[anno_i]\n \n # get the catagory id\n category_id=classes.index(tab_rec['region_attributes'])\n # convert the category id to the class name by using the classes array\n className=classes[category_id]\n anno=json.loads(tab_rec[\"region_shape_attributes\"])\n if len(anno)==0:\n continue\n #print(anno)\n\n points=convertPoints(anno)\n # this is the problem line\n converted_points=intersectBoundingBox(points,xmin,ymin,xmax,ymax)\n \n if len(converted_points) > 1:\n \n Sxmin=min(converted_points,key=lambda x:x[0])[0]\n Symin=min(converted_points,key=lambda x:x[1])[1]\n Sxmax=max(converted_points,key=lambda x:x[0])[0]\n Symax=max(converted_points,key=lambda x:x[1])[1]\n converted_points=[item for sublist in converted_points for item in sublist]\n Segbbox = [Sxmin,Symin,Sxmax,Symax]\n\n obj = {\n 'original_file': filename,\n \"tile_coordinates\": [xmin,ymin,xmax,ymax],\n \"image_id\": uid,\n 'file_name': uid + '.jpg',\n 'height': 512,\n 'width': 512,\n \"category_id\": className,\n \"bbox\": Segbbox,\n \"segmentation\": converted_points,\n \"bbox_mode\": 'BoxMode.XYXY_ABS',\n \"iscrowd\":0,\n }\n objs.append(obj)\n # append the object to the list of objects \n\n record[\"annotations\"] = objs\n records.append(record)\n # if the img is not empty, then write the image to a file\n if len(subimg)>0:\n cv2.imwrite(os.path.join(output_dir,uid + '.jpg'),subimg)\n\n return records\n\n \ndef writeRegionDataSet(dataset_dicts):\n '''\n :param dataset_dicts:\n :return:\n \n # Objective: Iterate over the dataset_dicts, each record will consist of filename, image_id, height, width, and annotations.\n We want to iterate over the annotations and write each annotation to a line in the csv file where the header line of the file\n will be the keys of the annotations dict.\n '''\n import csv\n with open(output_dir+\"regiondata.csv\", \"w\") as csvfile:\n \n fieldnames = ['original_file', 'tile_coordinates', 'image_id', 'file_name', 'height', 'width', 'category_id' , \n 'bbox', 'segmentation', 'bbox_mode', 'iscrowd']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for record in dataset_dicts:\n for obj in record[\"annotations\"]:\n writer.writerow(obj) \n \n pass\n \n \n \n#img = readImage(img_dir,files[0])\n#iles = tileImage(img)\n#IntersectSegmentations(img_dir,output_dir, tiles, img, annotab, files[0])\n# RUNNER\nannotab, files = readAnnotation(img_dir)\ndataset_dicts = []\nfor stained_image in files:\n img = readImage(img_dir,stained_image)\n tiles = tileImage(img)\n record = IntersectSegmentations(img_dir,output_dir, tiles, img, annotab, stained_image)\n dataset_dicts.extend(record)\n\n\nwriteRegionDataSet(dataset_dicts)\n \n\n\n\n\n\n\n\n\n\n","repo_name":"michaelSkaro/image_preprocessing","sub_path":"ImageTiling.py","file_name":"ImageTiling.py","file_ext":"py","file_size_in_byte":7453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26928001590","text":"class emp:\n company=\"google\"\n\n def getsalary(self):#if self not added throws error\n print(f'the guy in {self.company} makes {self.salary}')\n @staticmethod\n def greet():#-->no need to put self in static ,\n print ('hello sir')\n#we can make static methods as many as we want\n\nnitin=emp()\nnitin.salary= \"110 k \"\n\nnitin.getsalary() #--> Emp.getsalary(nitin)\n\nnitin.greet()\n\n\n\n\n\n\n","repo_name":"HarshalAtre/My-codes","sub_path":"python/ch10/07--static method.py","file_name":"07--static method.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5104868093","text":"import pyttsx3\nimport speech_recognition as sr\nimport datetime\nimport wikipedia\nimport webbrowser\nimport os\nimport random\n# import smtplib\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty('voices')\n#you can change voice by changing the array index of voices 0 is for guy and 1 is for girl.\n# print(voices[2].id)\nengine.setProperty('voice', voices[2].id)\n\ndef speak(speech):\n engine.say(speech)\n engine.runAndWait()\n\ndef wishMe():\n hour = int(datetime.datetime.now().hour)\n if hour>=0 and hour<12:\n speak(\"Good Morning mister Siris\")\n elif hour>=12 and hour<18:\n speak(\"Good Afternoon mister Siris\")\n else:\n speak(\"Good Evening mister Siris\")\n \n speak(\"Give me your command.\")\n\ndef takeCommand():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening...\")\n r.pause_threshold = 1\n audio = r.listen(source)\n \n try:\n print(\"Recognizing...\")\n query = r.recognize_google(audio, language='en-in')\n print(f\"User said: {query} \\n\")\n\n except Exception as e:\n print(\"Something went wrong, Please speak again.\")\n return \"None\"\n return query\n\n# def sendEmail(to,content):\n# server = smtplib.SMTP('smtp.gmail.com', 587)\n# server.ehlo()\n# server.starttls()\n# server.login('youremail@gmail.com', 'your-password')\n# server.sendmail('youremail@gmail.com', to, content)\n# server.close()\n\n\nif __name__ == \"__main__\":\n wishMe()\n while True:\n query = takeCommand().lower()\n try:\n if \"wikipedia\" in query:\n speak(\"Searching wikipedia...\")\n query = query.replace(\"wikipedia\",\"\")\n results = wikipedia.summary(query, sentences = 2)\n print(results)\n speak(results)\n\n elif \"open youtube\" in query:\n webbrowser.open(\"youtube.com\")\n\n elif \"open google\" in query:\n webbrowser.open(\"google.com\")\n\n elif \"open stackoverflow\" in query:\n webbrowser.open(\"stackoverflow.com\")\n\n elif \"play music\" in query:\n music_folder = \"C:\\\\Users\\\\user\\\\Music\"\n songs = os.listdir(music_folder)\n print(songs)\n randomSong= random.randint(1,len(songs)+1)\n print(songs[randomSong])\n os.startfile(os.path.join(music_folder, songs[randomSong]))\n \n elif \"open code\" in query:\n codepath = 'C:\\\\Users\\\\user\\\\AppData\\\\Local\\\\Programs\\\\Microsoft VS Code\\\\Code.exe'\n os.startfile(codepath)\n\n # elif \"email siris\" in query:\n # try:\n # speak(\"What should i say\")\n # content = takeCommand()\n # tonaruto = \"narutohero12345@gmail.com\"\n # sendEmail(tonaruto,content)\n # speak(\"Email has been sent.\")\n # except:\n # print(f\"{e} : Something wrong occured there.\")\n\n elif \"quit the program\" in query:\n exit()\n\n except Exception as e:\n print(f\"{e}: An error has occured\")","repo_name":"Siris546/Desktop-Assistant","sub_path":"assistant.py","file_name":"assistant.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12930250336","text":"'''\n File name: mlisle_wrapper.py\n Author: Matt\n Date created: 11/4/2018\n'''\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom helpers import rgb2gray\nfrom helpers import generate_output_frame\nfrom getFeatures import getFeatures\nfrom calculateError import calculateError\nfrom estimateAllTranslation import estimateAllTranslation\nfrom applyGeometricTransformation import applyGeometricTransformation\n\nimgs = np.array([])\ncap = cv2.VideoCapture(\"Easy.mp4\")\nret, img1 = cap.read()\nimg1 = img1[...,::-1]\nh, w, d = img1.shape\nk_pad = 2\nparams = [4, 1, 3, 1, 1.5]\n# For now, manually draw the bounding box and forget about cv2.boundingRect()\nbox1 = np.array([287, 187, 397, 187, 397, 264, 287, 264]).reshape(4, 2)\nbox2 = np.array([227, 127, 279, 127, 279, 172, 227, 172]).reshape(4, 2)\nbbox = np.array([box1, box2])\n# bbox = np.array([box1])\norig_box = np.copy(bbox)\ncenters = np.zeros((len(bbox), 2))\n\norig_box = np.copy(bbox)\ncenters = np.zeros((len(bbox), 2))\ntrajectory_indexer = np.zeros((h, w), dtype=bool)\n\n# Get the features from inside the bounding box\nx, y = getFeatures(rgb2gray(img1), bbox)\n\nnewXs = np.copy(x)\nnewYs = np.copy(y)\n\nf = 0\nframe = generate_output_frame(np.copy(img1), bbox, np.copy(trajectory_indexer), np.copy(newXs), np.copy(newYs))\nframe = Image.fromarray(frame)\nframe.save(\"easy_frame%d.jpg\" % f)\n\na = 0\nwhile True:\n\tf += 1\n\ta += 1\n\tif bbox.size:\n\t\tif bbox.size < 2:\n\t\t\tprint(bbox.size)\n\t\tif not f % 8:\n\t\t\tprint(\"Frame: \", f)\n\t\t\ta = 1\n\t\t\tfor i in range(len(bbox)):\n\t\t\t\torig_box = np.copy(bbox)\n\t\t\tx, y = getFeatures(rgb2gray(img1), bbox)\n\t\t\tnewXs = np.copy(x)\n\t\t\tnewYs = np.copy(y)\n\n\t\tthresh = .1 + .02 * a\n\n\t\tret, img2 = cap.read()\n\t\tif not ret:\n\t\t\tbreak\n\t\timg2 = img2[...,::-1]\n\n\t\t# Get the new feature locations in the next frame\n\t\tupdatex, updatey, x, y = estimateAllTranslation(np.copy(newXs), np.copy(newYs), np.copy(x), np.copy(y), np.copy(img1), np.copy(img2), np.copy(bbox), params)\n\n\t\tfor k in range(len(bbox)):\n\t\t\tcenters[k] = np.array([np.mean(bbox[k, :, 0]), np.mean(bbox[k, :, 1])]).astype(int)\n\n\t\t# Warp the image for the next iteration\n\t\tnewXs, newYs, bbox = applyGeometricTransformation(np.copy(x), np.copy(y), updatex, updatey, np.copy(orig_box), np.copy(img1), np.copy(img2), k_pad)\n\n\t\tindexer = np.ones(len(bbox), dtype=bool)\n\t\tfor k in range(len(bbox)):\n\t\t\tif not np.any(bbox[k]) or len(newXs[k]) < 2:\n\t\t\t\tindexer[k] = False\n\n\t\tbbox = bbox[indexer]\n\t\torig_box = orig_box[indexer]\n\t\tnewXs = newXs[indexer]\n\t\tnewYs = newYs[indexer]\n\t\tx = x[indexer]\n\t\ty = y[indexer]\n\t\tcenters = centers[indexer]\n\n\t\tfor k in range(len(bbox)):\n\t\t\txcen = int(np.mean(bbox[k, :, 0]))\n\t\t\tycen = int(np.mean(bbox[k, :, 1]))\n\t\t\tif xcen < w - 2 and xcen > 2 and ycen < h - 2 and ycen > 2:\n\t\t\t\tnum = int(max([abs(xcen - centers[k, 0]), abs(ycen - centers[k, 1])]))\n\t\t\t\tcenterx = np.linspace(centers[k, 0], xcen + 1, num).astype(int)\n\t\t\t\tcentery = np.linspace(centers[k, 1], ycen + 1, num).astype(int)\n\t\t\t\tif centerx.size > 0 and centery.size > 0:\n\t\t\t\t\ttrajectory_indexer[centery, centerx] = True\n\t\t\t\t\ttrajectory_indexer[centery + 1, centerx] = True\n\t\t\t\t\ttrajectory_indexer[centery, centerx + 1] = True\n\t\t\t\t\ttrajectory_indexer[centery + 1, centerx + 1] = True\n\t\t\t\telse:\n\t\t\t\t\ttrajectory_indexer[ycen, xcen] = True\n\t\t\t\t\ttrajectory_indexer[ycen + 1, xcen] = True\n\t\t\t\t\ttrajectory_indexer[ycen, xcen + 1] = True\n\t\t\t\t\ttrajectory_indexer[ycen + 1, xcen + 1] = True\n\n\t\tframe = generate_output_frame(np.copy(img2), bbox, np.copy(trajectory_indexer), np.copy(newXs), np.copy(newYs))\n\t\tframe = Image.fromarray(frame)\n\t\tframe.save(\"easy_frame%d.jpg\" % f)\n\telse:\n\t\tret, img2 = cap.read()\n\t\tif not ret:\n\t\t\tbreak\n\t\timg2 = img2[...,::-1]\n\t\tframe = Image.fromarray(img2)\n\t\tframe.save(\"easy_frame%d.jpg\" % f)\n\n\timg1 = np.copy(img2)\n\ncap.release()","repo_name":"mattlisle/optical-flow","sub_path":"mlisle_wrapper_3.py","file_name":"mlisle_wrapper_3.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29835256747","text":"#!/usr/bin/python\n\n# works as of 4/19/2016\n\nimport csv, requests, time\nfrom pprint import pprint\n\n#############################\n###### EDIT THIS STUFF ######\n#############################\n\naccess_token = '' # your access token\nmodules_csv = 'modules.csv' # name of file storing module names\nlog_file = 'log.txt' # a log file. it will log things\nbaseUrl = 'https://myschool.instructure.com/api/v1/courses/' # change to domain of your Canvas account\nheader = {'Authorization' : 'Bearer ' + access_token}\npayload = {}\n\n##############################################################################\n## ONLY update the code below if you are experimenting with other API calls ##\n##############################################################################\n\ndef main():\n\n # add time stamp to log file\n log_time = str(time.asctime(time.localtime(time.time())))\n write_to_log(log_time) \n\n # do that updating thang\n create_modules()\n \n # add time stamp to log file\n log_time = str(time.asctime(time.localtime(time.time())))\n write_to_log(log_time) \n write_to_log(\"\\n--DONE--\\n\\n\")\n \n\ndef create_modules():\n\n with open(modules_csv, 'rU') as csvFile:\n csvReader = csv.reader(csvFile, delimiter = ',')\n csvReader.next() # skip the header\n\n for row in csvReader:\n course_id = row[0]\n title = row[1]\n url = baseUrl + '%s/modules?module[name]=%s' %(course_id,title)\n write_to_log(course_id + title)\n r = requests.post(url, headers = header, data = payload)\n write_to_log(r.text) \n\ndef write_to_log(message):\n\n with open(log_file, 'a') as log:\n log.write(message + \"\\n\")\n pprint(message)\n\n\n\nif __name__ == \"__main__\": main()\n\n","repo_name":"unsupported/canvas","sub_path":"api/prepopulate_modules/python/prepopulate_modules.py","file_name":"prepopulate_modules.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"52"} +{"seq_id":"3068575746","text":"from ctypes import util\nfrom scipy.signal import savgol_filter\nimport sys\nimport os\ncurrent = os.path.dirname(os.path.realpath(__file__))\nparent = os.path.dirname(current)\nsys.path.append(parent)\n\nfrom utils_lib.utils import Utils\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nutils = Utils()\n\n\ndef create_dir(path_dir):\n\tif not os.path.exists(path_dir):\n\t\tos.makedirs(path_dir)\ncreate_dir(\"./figures/A2C\")\ncreate_dir(\"./figures/PPO\")\ncreate_dir(\"./figures/DQN\")\ncreate_dir(\"./figures/DDPG\")\ncreate_dir(\"./figures/SAC\")\ncreate_dir(\"./figures/TD3\")\n\nplt.rcParams[\"figure.figsize\"] = (10,8)\n\ndef get_path(policie_name,env_name,fe_k,fev_l,index=0):\n global util\n #util.all_feature_extractor[]\n return os.path.join(os.path.dirname(__file__), (\"../result/log_json/\" +\n policie_name+ \"/\" +\n env_name+\"/\"+\n utils.all_feature_extractor[fe_k][\"name\"] + \"_v\" +\n str(utils.all_feature_extractor[fe_k][\"order\"][fev_l]) + \"_i\" +\n str(index) +\".json\"\n ))\n\ndef plot_one_file_by_index(\n plot_target,\n policy_i=None,\n env_j=None,\n fe_k=None,\n fe_v_k=None,\n label_plot=\"\",\n color=None,\n marker=None,\n index=0):\n plot_one_file(\n plot_target,\n utils.all_policies[policy_i],\n utils.all_envs[env_j],\n fe_k,\n fe_v_k,\n label_plot,\n color,\n marker,\n index)\n\ndef plot_one_file(plot_target,policy=None,env=None,fe_k=None,fe_v_k=None,label_plot=\"\",color=None,marker=None,index=0):\n path_log = get_path(\n policie_name=policy[\"name\"],\n env_name=env[\"name\"],\n fe_k=fe_k,\n fev_l=fe_v_k,\n index=index)\n #print(path_log)\n\n #path_log=\"../test.json\"\n #print(path_log)\n data = []\n time = []\n if os.path.exists(path_log):\n print(\"found\")\n print(path_log)\n\n with open(path_log, 'r') as fd:\n lines = fd.read().split('\\n')\n for l in lines:\n split_array=l.split(\",\")\n if len(split_array)==5:\n #print(len(split_array))\n time.append(float(split_array[0]))\n data.append(float(split_array[2]))\n\n data = np.array(data)\n time = np.array(time)\n # print(data)\n if not(len(data) < 40 or len(time) <40):\n ti_li = savgol_filter(time, 40, 1)\n data_li = savgol_filter(data, 40, 1)\n #plt.legend()\n plot_target.plot(ti_li,data_li,label=label_plot,c=color, marker=marker,)\n else:\n print(\"not_found\")\n print(path_log)\n #plot_target.plot(time,data)\n\ndef index_to_tuple(index):\n #print((int(index/3),index%3))\n return (int(index/3),index%3)\n\ndef init_plot():\n fig, axs = plt.subplots(2, 3)\n print(axs)\n for i,policy in enumerate(utils.all_policies[:6]):\n axs[index_to_tuple(i)].set_title(policy[\"name\"])\n #print(policy[\"name\"])\n\n for ax in axs.flat:\n ax.set(xlabel='timestep', ylabel='reward')\n\n # Hide x labels and tick labels for top plots and y ticks for right plots.\n for ax in axs.flat:\n ax.label_outer()\n\n return (fig, axs)\n\n\n\n\n\ndef plot_env_fe_by_fe(env_j=0,index=1002):\n\n #fig.title(\"lol\")\n for fev in range(len(utils.all_feature_extractor)):\n fig, axs = init_plot()\n fig.suptitle(utils.all_envs[env_j][\"env\"],fontweight =\"bold\")\n for po in range(len(utils.all_policies)):\n for fev_k in range(len(utils.all_feature_extractor[fev][\"order\"])):\n color = None\n marker = None\n if utils.all_feature_extractor[fev][\"order\"][fev_k] in [8,16,64,256]:\n #color = \"r\"\n marker=\"*\"\n plot_one_file_by_index(\n plot_target=axs[index_to_tuple(po)],\n policy_i=po,\n env_j=env_j,\n fe_k=fev,\n fe_v_k=fev_k,\n label_plot=utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]),\n color=color,\n marker=marker,\n index=index\n )\n print(utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]))\n # mng = plt.get_current_fig_manager()\n # mng.frame.Maximize(True)\n #plt.legend()\n plt.show()\n # for ax in axs.flat:\n # ax.set(xlabel='timestep', ylabel='reward')\n # # Hide x labels and tick labels for top plots and y ticks for right plots.\n # for ax in axs.flat:\n # ax.label_outer()\n\n\n\n# plot_env_fe_by_fe()\n\ndef plot_env_fe_by_fight_index(env_j=0,index=88):\n array_color = [\"#0f0\",\"#f00\",\"#0ff\",\"#f00\",\"#0f0\",\"#00f\"]\n\n index_to_fight = [1000,1001,1002,1003]\n\n #fig.title(\"lol\")\n for fev in range(len(utils.all_feature_extractor)):\n fig, axs = init_plot()\n fig.suptitle('Ant problem',fontweight =\"bold\")\n for iii,index_fight in enumerate(index_to_fight):\n for po in range(len(utils.all_policies)):\n for fev_k in range(len(utils.all_feature_extractor[fev][\"order\"])):\n plot_one_file_by_index(\n plot_target=axs[index_to_tuple(po)],\n policy_i=po,\n env_j=env_j,\n fe_k=fev,\n fe_v_k=fev_k,\n label_plot=utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]),\n color=array_color[iii],\n index=index_fight\n )\n\n plt.show()\n for ax in axs.flat:\n ax.set(xlabel='timestep', ylabel='reward')\n\n # Hide x labels and tick labels for top plots and y ticks for right plots.\n for ax in axs.flat:\n ax.label_outer()\n# for i in range(17):\n# plot_env_fe_by_fight_index(env_j=i)\n\n# axs[0, 0].set_title('DQN')\n# axs[0, 1].set_title('SAC')\n# axs[1, 0].set_title('DDPG')\n# axs[1, 1].set_title('PPO')\n\n\n\n\n\n\ndef plot_env_fe_all_multi(env_j=0,index=11011,aaa=0,fig=None):\n fig.suptitle(utils.all_envs[env_j][\"env\"],fontweight =\"bold\")\n #plt.title(\"lol\")\n for fev in range(len(utils.all_feature_extractor)):\n for po in [aaa]:#range(len(utils.all_policies)):\n for fev_k in range(len(utils.all_feature_extractor[fev][\"order\"])):\n color = None\n marker = None\n if fev not in [0,48,49]:\n # if fev not in [0,29,30,31,32,33,34]:#,25,26,27,28,\n break\n if fev in [0]:\n color = \"#000\"\n marker=\"1\"\n if fev in [49,30,25,]:\n color = \"#f00\"\n if fev in [31,32,27]:\n color = \"#0f0\"\n if fev in [33,48,26]:\n color = \"#00f\"\n if fev in [28]:\n color = \"#f0f\"\n\n \n plot_one_file_by_index(\n plot_target=axs[index_to_tuple(po)],\n policy_i=po,\n env_j=env_j,\n fe_k=fev,\n fe_v_k=fev_k,\n label_plot=utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]),\n color=color,\n marker=marker,\n index=index\n )\n print(utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]))\n \n#fig, axs = init_plot()\n\n\nfor i in range(17):\n fig, axs = init_plot()\n print(axs)\n for j in range(6):\n print(str(i)+\"___\"+str(j))\n plot_env_fe_all_multi(env_j=i,aaa=j,fig=fig)\n #plt.legend()\n plt.show()\n\n\n\n# def plot_env_fe_all_solo(env_j=0,index=11011,policie=0):\n# #fig.suptitle(utils.all_envs[env_j][\"env\"],fontweight =\"bold\")\n# plt.title(utils.all_envs[env_j][\"env\"]+\"_\"+utils.all_policies[policie][\"name\"])\n# for fev in range(len(utils.all_feature_extractor)):\n# for po in [policie]:#range(len(utils.all_policies)):\n# for fev_k in range(len(utils.all_feature_extractor[fev][\"order\"])):\n# color = None\n# marker = None\n# if fev not in [0,39,40,41,42]:\n# # if fev not in [0,29,30,31,32,33,34]:#,25,26,27,28,\n# break\n# if fev in [0]:\n# color = \"#000\"\n# marker=\"1\"\n# if fev in [29,30,39,]:\n# color = \"#f00\"\n# if fev in [31,32,40]:\n# color = \"#0f0\"\n# if fev in [33,34,41]:\n# color = \"#00f\"\n# if fev in [28]:\n# color = \"#f0f\"\n\n \n# plot_one_file_by_index(\n# plot_target=plt,\n# policy_i=po,\n# env_j=env_j,\n# fe_k=fev,\n# fe_v_k=fev_k,\n# label_plot=utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]),\n# color=color,\n# marker=marker,\n# index=index\n# )\n# plt.savefig(\"./figures/\"+utils.all_policies[policie][\"name\"]+\"/\"+utils.all_envs[env_j][\"env\"]+\"_\"+utils.all_policies[policie][\"name\"]+'.pdf')\n\n# print(utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]))\n\n# for i in range(17):\n \n# for j in range(6):\n# plt.figure(i*12+j)\n# print(str(i)+\"___\"+str(j))\n# plot_env_fe_all_solo(env_j=i,policie=j)\n# plt.legend()\n# plt.show()\n\n\ndef plot_and_save_all(index=101):\n for env_i in len(utils.all_envs):\n for po_j in len(utils.all_policies):\n fig = plt.figure(4)\n for fe_k in len(utils.all_feature_extractor):\n for fev_l in len(utils.all_feature_extractor[fe_k]):\n plot_one_file_by_index(\n plot_target=fig,\n policy_i=po_j,\n env_j=env_i,\n fe_k=fe_k,\n fe_v_k=fev_l,\n label_plot=\"\",\n color=None,\n index=index\n )\n plt.savefig(\"./figures/\"+str(env_i)+\"_\"+str(po_j)+'.pdf')\n plt.show()\n plt.close()\n\n\ndef fake_plot(axs):\n for i in range(6):\n\n plot_one_file(axs[index_to_tuple(i)])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# def plot_env_fe_by_fight(env_j=9,index=88):\n# array_color = [\"#0ff\",\"#f00\",\"#0f0\",\"#00f\",\"#ff0\",\"#f0f\"]\n\n\n# all_vs_all = [\n\n# [1,11,21,32,42],\n# [2,12,22,33,43],\n# [3,13,23,34,44],\n# [4,14,24,35,45],\n# [5,15,25,36,46],\n# [6,16,26,37,47],\n# [7,17,27,38,48],\n# [8,18,28,39,49],\n# [9,19,29,40,50],\n# [10,20,30,41,51],\n# ]\n# cos_vs_sin = [\n# [11,21],\n# [12,22],\n# [13,23],\n# [14,24],\n# [15,25],\n# [16,26],\n# [17,27],\n# [18,28],\n# [19,29],\n# [20,30],\n# ]\n# norm_vs_oss_1 = [\n# [1,32],\n# [2,33],\n# [3,34],\n# [4,35],\n# [5,36],\n# [6,37],\n# [7,38],\n# [8,39],\n# [9,40],\n# [10,41],\n# ]\n# norm_vs_oss_2 = [\n# [21,42],\n# [22,43],\n# [23,44],\n# [24,45],\n# [25,46],\n# [26,47],\n# [27,48],\n# [28,49],\n# [29,50],\n# [30,51],\n# ]\n# array_fe = all_vs_all\n\n# #fig.title(\"lol\")\n# for fev_i,fe_tab in enumerate(array_fe):\n# print(fe_tab)\n# fig, axs = init_plot()\n# fig.suptitle('Ant problem',fontweight =\"bold\")\n# for fi_i,fev in enumerate(fe_tab):\n# for fev_k in range(len(utils.all_feature_extractor[fev][\"order\"])):\n\n\n# for po in range(len(utils.all_policies)):\n\n# plot_one_file_by_index(\n# plot_target=axs[index_to_tuple(po)],\n# policy_i=po,\n# env_j=env_j,\n# fe_k=fev,\n# fe_v_k=fev_k,\n# #label_plot=utils.all_feature_extractor[fev][\"name\"]+\"_\"+str(utils.all_feature_extractor[fev][\"order\"][fev_k]),\n# color=array_color[fi_i],\n# index=index\n# )\n# # mng = plt.get_current_fig_manager()\n# # mng.frame.Maximize(True)\n# #plt.legend()\n# plt.show()\n\n\n# for ax in axs.flat:\n# ax.set(xlabel='timestep', ylabel='reward')\n# # Hide x labels and tick labels for top plots and y ticks for right plots.\n# for ax in axs.flat:\n# ax.label_outer()\n","repo_name":"clement-chupin/BenchNeuralNework","sub_path":"log_lib/view_result.py","file_name":"view_result.py","file_ext":"py","file_size_in_byte":13111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16495713442","text":"import contextlib\nimport traceback\ntry:\n import urllib2\nexcept ImportError:\n from urllib import request as urllib2\n\nfrom earthreader.web import app\n\n\n# See also http://wiki.whatwg.org/wiki/Validator.nu_Web_Service_Interface\nVALIDATOR_URL = 'http://validator.nu/?out=text'\n\nwith app.test_client() as client:\n response = client.get('/')\n content_type = response.headers['content-type']\n body = response.data\n\nrequest = urllib2.Request(\n VALIDATOR_URL,\n data=body,\n headers={'Content-Type': content_type}\n)\n\ntry:\n with contextlib.closing(urllib2.urlopen(request)) as response:\n message = response.read()\n failed = message.rstrip().endswith(b'There were errors.')\n print(message)\n raise SystemExit(int(failed))\nexcept IOError:\n traceback.print_exc()\n","repo_name":"earthreader/web","sub_path":"tests/html5lint.py","file_name":"html5lint.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"52"} +{"seq_id":"11729197524","text":"#-*- encoding:utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function, unicode_literals)\n\n\"\"\"\n@author: docutone\n\n\"\"\"\nimport sys\nimport jieba\nimport jieba.posseg as pseg\nimport codecs\n\nfrom six import string_types\n\nsys.path.append(\"../\")\n\nfrom docutone.utils import util\n\n'''\n分词\n'''\nclass Segmentation(object):\n \n\n def __init__(self, stopwords_file=None, delimiters=None):\n\n \"\"\"\n \n stopwords_file : stop words file name\n\n\n \n delimiters : delimiters the sentence\n \n \"\"\"\n \n self.delimiters = delimiters\n \n self.load_stop_words(stopwords_file)\n \n \n\n def set_library(self, extdict=None, idfdict=None, stopdict=None):\n \"\"\"\n arguments :\n \n extdict :\n \n idfdict :\n \n stopdict :\n \n \"\"\"\n \n if type(extdict) is str:\n jieba.load_userdict(extdict)\n else :\n jieba.load_userdict(\"./data/dict/dict.txt.big\")\n \"\"\" \n if type(idfdict) is str:\n jieba.analyse.set_idf_path(idfdict);\n else :\n jieba.analyse.set_idf_path(\"./data/dict/idf.txt.big\");\n \n if type(stopdict) is str:\n jieba.analyse.set_stop_words(stopdict)\n else :\n jieba.analyse.set_stop_words(\"./data/dict/stop_words.txt\")\n \"\"\"\n \n \n def load_stop_words(self, stopwords_file):\n \"\"\"\n Argument :\n\n stopwords_file : stop words file name\n \n \n loading stop words\n \n \"\"\"\n\n self.stop_words = set()\n if type(stopwords_file) is str:\n filename = stopwords_file\n else :\n filename = util.get_default_stop_words_file()\n \n for word in codecs.open(filename, 'r', 'utf-8', 'ignore'):\n word = util.normalize_sentence(word.strip())\n\n if len(word) :\n self.stop_words.add(word)\n \n\n def load_suggest_words(self, suggestwords_file=None):\n \"\"\"\n Argument :\n\n suggestwords_file : suggest words file name\n \n \n loading suggest words\n \n \"\"\"\n\n if type(suggestwords_file) is str:\n filename = suggestwords_file\n else :\n filename = util.get_default_suggest_words_file()\n\n f = codecs.open(filename, 'r', 'utf-8')\n for word in f : \n word = util.normalize_sentence(word.strip())\n if len(word) :\n if '\\t' in word :\n w = word.split('\\t')\n jieba.suggest_freq((w[0].strip(), w[1].strip()), True)\n else :\n jieba.suggest_freq(word.strip(), True)\n \n\n def split_sentences(self, document):\n \"\"\"\n arguments :\n \n document : a document\n \n\n return : split sentences \n \"\"\"\n \n document = util.as_text(document)\n if self.delimiters != None :\n res = [document]\n for sep in self.delimiters:\n document, res = res, []\n for seq in document:\n res += seq.split(sep)\n sentences = [s.strip() for s in res if len(s.strip()) > 0]\n else :\n sentences = document.split('\\n')\n ss = [self.normalize_sentence(s.strip()) for s in sentences]\n sentences = [s for s in ss if len(s) > 0]\n return sentences \n\n\n\n def segment(self, sentences, wlen=0):\n \n \"\"\"\n arguments :\n \n sentences : all sentences of a document \n \n return sentences, words, words_no_stop, word_all_filters \n \n \"\"\"\n \n words_no_filter = []\n words_no_stop_words = []\n words_all_filters = []\n \n for s in sentences :\n if isinstance(s, string_types) :\n sentence = s\n else :\n sentence = s[0] # document sentence format [text, number, type]\n \n sentence = sentence.strip()\n if len(sentence) < 2 :\n continue\n jieba_result = pseg.cut(sentence, HMM=False)\n jieba_result = [w for w in jieba_result]\n\n\n w_word_list = [w for w in jieba_result]\n word_list = [w.word.strip() for w in w_word_list if len(w.word.strip())>wlen]\n words_no_filter.append(word_list)\n \n # 去除 stop words\n word_list = [w for w in word_list if w not in self.stop_words]\n words_no_stop_words.append(word_list)\n\n # 去除 w.flag!='x'\n \n word_list = [w.word.strip() for w in w_word_list if w.flag!='x' and w.flag!='eng' and w.word not in self.stop_words]\n if len(word_list) > 0 :\n words_all_filters.append(word_list)\n\n\n\n return words_no_filter, words_no_stop_words, words_all_filters\n \n def segment_words(self, sentences, wlen=0):\n \n \"\"\"\n arguments :\n \n sentences : all sentences of a document \n \n return sentences, words, words_no_stop, word_all_filters \n \n \"\"\"\n \n words_no_filter = []\n words_no_stop_words = []\n words_all_filters = []\n \n for s in sentences :\n if isinstance(s, string_types) :\n sentence = s\n else :\n sentence = s[0] # document sentence format [text, number, type]\n \n sentence = sentence.strip()\n jieba_result = pseg.cut(sentence, HMM=False)\n jieba_result = [w for w in jieba_result]\n\n\n word_list = [w for w in jieba_result]\n word_list = [w for w in word_list if len(w.word.strip())>wlen]\n words_no_filter.append(word_list)\n \n # 去除 stop words\n word_list = [w for w in word_list if w.word not in self.stop_words]\n words_no_stop_words.append(word_list)\n\n # 去除 w.flag = 'x', w.flag = 'eng'\n \n word_list = [w for w in word_list if w.flag!='x' and w.flag!='eng']\n if len(word_list) > 0 :\n words_all_filters.append(word_list)\n\n\n\n return words_no_filter, words_no_stop_words, words_all_filters\n\n \n def segment_ws(self, sentences):\n \n \"\"\"\n arguments :\n \n sentences : all sentences of a document \n \n return words\n \n \"\"\"\n \n words = []\n\n for sentence in sentences :\n \n jieba_result = pseg.cut(sentence, HMM=False)\n jieba_result = [w for w in jieba_result]\n word_list = [w for w in jieba_result if len(w.word.strip())>0]\n words.append(word_list)\n\n\n return words\n \n\n \n \n \n ","repo_name":"minlogiciel/docutone","sub_path":"smart/python/src/com/docutone/core/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":6919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32578228050","text":"from django.test import LiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport unittest\nfrom selenium.common.exceptions import StaleElementReferenceException\nimport sys\nfrom contextlib import contextmanager\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.expected_conditions import staleness_of\nimport time\n\nclass NewVisitorTest(LiveServerTestCase):\n\n def setUp(self):\n self.browser = webdriver.Firefox(executable_path='/Users/soojin/Downloads/geckodriver')\n # self.browser.implicitly_wait(10)\n\n @contextmanager\n def wait_for_page_load(self, timeout=30):\n old_page = self.browser.find_element_by_tag_name(\"html\")\n yield WebDriverWait(self.browser, timeout).until(\n staleness_of(old_page)\n )\n\n def test_layout_and_styling(self):\n self.browser.get(self.live_server_url)\n self.browser.set_window_size(1024, 768)\n\n\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('testing\\n')\n self.assertAlmostEqual(\n inputbox.location['x'] + inputbox.size['width'] / 2,\n 512,\n delta=10\n )\n\n # @classmethod\n # def setUpClass(cls):\n # for arg in sys.argv :\n # if 'liveserver' in arg:\n # cls.server_url = 'http://' + arg.split('=')[1]\n # cls.live_server_url = ''\n # return\n # super().setUpClass()\n # cls.server_url = cls.live_server_url\n #\n # def tearDown(self):\n # self.browser.quit()\n #\n # @classmethod\n # def tearDownClass(cls):\n # if cls.server_url == cls.live_server_url:\n # super().tearDownClass()\n\n def stale_aware_for_action(self, action):\n while(True):\n try:\n action()\n break\n except StaleElementReferenceException:\n continue\n\n def check_for_row_in_list_table(self, row_text):\n table = self.browser.find_element_by_id('id_list_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(row_text, [row.text for row in rows])\n\n #목록 저장하고 있는지 궁금\n\n\n def test_can_start_a_list_and_retrieve_it_later(self):\n self.browser.get(self.live_server_url)\n # self.assertIn('To-Do', self.browser.title)\n # header_text = self.browser.find_element_by_tag_name('h1').text\n # self.assertIn('To-Do', header_text)\n\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertEqual(\n inputbox.get_attribute('placeholder'),\n '작업 아이템 입력'\n )\n inputbox.send_keys('공작 깃털 사기')\n inputbox.send_keys(Keys.ENTER)\n time.sleep(1)\n with self.wait_for_page_load(timeout=1):\n self.check_for_row_in_list_table('1: 공작 깃털 사기')\n edith_list_url = self.browser.current_url\n self.assertRegex(edith_list_url, '/lists/.+')\n\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('깃털 모아서 날기')\n inputbox.send_keys(Keys.ENTER)\n time.sleep(1)\n with self.wait_for_page_load(timeout=1):\n self.check_for_row_in_list_table('1: 공작 깃털 사기')\n self.check_for_row_in_list_table('2: 깃털 모아서 날기')\n\n self.browser.quit()\n self.browser = webdriver.Firefox(executable_path='/Users/soojin/Downloads/geckodriver')\n self.browser.get(self.live_server_url)\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('공작 깃털 사기', page_text)\n self.assertNotIn('깃털 모아서 날기', page_text)\n\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('우유 사기')\n inputbox.send_keys(Keys.ENTER)\n\n francis_list_url = self.browser.current_url\n self.assertRegex(francis_list_url, '/lists/')\n self.assertNotEqual(francis_list_url, edith_list_url)\n\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('공작 깃털 사기', page_text)\n self.assertIn('우유 사기', page_text)\n # def check_for_first_item():\n # # def check_for_second_item():\n # # def check_for_row_in_list_table(self, row_text):\n # # table = self.browser.find_element_by_id('id_list_table')\n # # rows = table.find_elements_by_tag_name('tr')\n # # self.assertIn(row_text, [row.text for row in rows])\n # #\n # # with self.wait_for_page_load(timeout=10):\n # # self.check_for_row_in_list_table('2: 깃털 모아서 날���')\n # #\n # # def insert_second_item_to_inputbox():\n # # inputbox2 = self.browser.find_element_by_id('id_new_item')\n # # self.assertEqual(\n # # inputbox2.get_attribute('placeholder'),\n # # '작업 아이템 입력'\n # # )\n # # inputbox2.send_keys('깃털 모아서 날기')\n # # inputbox2.send_keys(Keys.ENTER)\n\n #\n # self.stale_aware_for_action(check_for_first_item)\n #\n # self.stale_aware_for_action(insert_second_item_to_inputbox)\n #\n # self.stale_aware_for_action(check_for_second_item)\n # self.stale_aware_for_action(check_for_first_item)\n\n\n\n\n self.fail('Finish the Test!')\n\n\n\n\n #\n # import time\n #time.sleep(6)\n\n #self.assertTrue(\n #any(row.text == '1: 공작 깃털 사기' for row in rows),\n # \"신규 작업이 테이블에 표시되지 않는다 -- 해당 텍스트 :\\n%s\" % (\n # table.text,\n # )\n #)\n\n\n\n # if __name__ == '__main__':\n # unittest.main(warnings='ignore')\n#\n# browser = webdriver.Firefox(executable_path='/Users/soojin/Downloads/geckodriver')\n# browser.get('http://localhost:8000')\n# assert 'To-Do' in browser.title\n# executable_path='/Users/soojin/Downloads/geckodriver","repo_name":"Ella77/djangoproject","sub_path":"functional_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71442293604","text":"\"\"\"Base victim class.\"\"\"\n\nimport torch\n\nfrom .models import get_model\nfrom .training import get_optimizers, run_step\nfrom ..hyperparameters import training_strategy\nfrom ..utils import average_dicts\nfrom ..consts import BENCHMARK, SHARING_STRATEGY\ntorch.backends.cudnn.benchmark = BENCHMARK\ntorch.multiprocessing.set_sharing_strategy(SHARING_STRATEGY)\n\n\nFINETUNING_LR_DROP = 0.001\n\n\nclass _VictimBase:\n \"\"\"Implement model-specific code and behavior.\n\n Expose:\n Attributes:\n - model\n - optimizer\n - scheduler\n - criterion\n\n Methods:\n - initialize\n - train\n - retrain\n - validate\n - iterate\n\n - compute\n - gradient\n - eval\n\n Internal methods that should ideally be reused by other backends:\n - _initialize_model\n - _step\n\n \"\"\"\n\n def __init__(self, args, setup=dict(device=torch.device('cpu'), dtype=torch.float)):\n \"\"\"Initialize empty victim.\"\"\"\n self.args, self.setup = args, setup\n if self.args.ensemble < len(self.args.net):\n raise ValueError(f'More models requested than ensemble size.'\n f'Increase ensemble size or reduce models.')\n self.loss_fn = torch.nn.CrossEntropyLoss()\n self.initialize(pretrain=True if self.args.pretrain_dataset is not None else False)\n\n def gradient(self, images, labels):\n \"\"\"Compute the gradient of criterion(model) w.r.t to given data.\"\"\"\n raise NotImplementedError()\n return grad, grad_norm\n\n def compute(self, function):\n \"\"\"Compute function on all models.\n\n Function has arguments: model, ...\n \"\"\"\n raise NotImplementedError()\n\n def distributed_control(self, inputs, labels, poison_slices, batch_positions):\n \"\"\"Control distributed poison brewing, no-op in single network training.\"\"\"\n randgen = None\n return inputs, labels, poison_slices, batch_positions, randgen\n\n def sync_gradients(self, input):\n \"\"\"Sync gradients of given variable. No-op for single network training.\"\"\"\n return input\n\n def reset_learning_rate(self):\n \"\"\"Reset scheduler object to initial state.\"\"\"\n raise NotImplementedError()\n\n \"\"\" Methods to initialize and modify a model.\"\"\"\n\n def initialize(self, seed=None):\n raise NotImplementedError()\n\n def reinitialize_last_layer(self, seed=None):\n raise NotImplementedError()\n\n def freeze_feature_extractor(self):\n raise NotImplementedError()\n\n def save_feature_representation(self):\n raise NotImplementedError()\n\n def load_feature_representation(self):\n raise NotImplementedError()\n\n\n \"\"\" METHODS FOR (CLEAN) TRAINING AND TESTING OF BREWED POISONS\"\"\"\n\n def train(self, kettle, max_epoch=None):\n \"\"\"Clean (pre)-training of the chosen model, no poisoning involved.\"\"\"\n print('Starting clean training ...')\n stats_clean = self._iterate(kettle, poison_delta=None, max_epoch=max_epoch,\n pretraining_phase=True if self.args.pretrain_dataset is not None else False)\n if not self.args.retrain_scenario == None:\n self.save_feature_representation()\n\n if self.args.scenario in ['transfer', 'finetuning']:\n self.save_feature_representation()\n if self.args.scenario == 'transfer':\n self.freeze_feature_extractor()\n self.eval()\n print('Features frozen.')\n if self.args.pretrain_dataset is not None:\n # Train a clean finetuned model/head\n if self.args.scenario == 'transfer':\n self.reinitialize_last_layer(reduce_lr_factor=1.0, seed=self.model_init_seed)\n else:\n self.reinitialize_last_layer(reduce_lr_factor=FINETUNING_LR_DROP, seed=self.model_init_seed, keep_last_layer=False)\n # Finetune from base model\n print(f'Training clean {self.args.scenario} model on top of {self.args.pretrain_dataset} base model.')\n stats_clean = self._iterate(kettle, poison_delta=None, max_epoch=max_epoch)\n\n return stats_clean\n\n def retrain(self, kettle, poison_delta, max_epoch=None):\n \"\"\"Check poison on the initialization it was brewed on.\"\"\"\n if self.args.scenario == 'from-scratch':\n self.initialize(seed=self.model_init_seed)\n print('Model re-initialized to initial seed.')\n elif self.args.scenario == 'transfer':\n self.load_feature_representation()\n self.reinitialize_last_layer(reduce_lr_factor=1.0, seed=self.model_init_seed)\n print('Linear layer reinitialized to initial seed.')\n elif self.args.scenario == 'finetuning':\n self.load_feature_representation()\n self.reinitialize_last_layer(reduce_lr_factor=FINETUNING_LR_DROP, seed=self.model_init_seed, keep_last_layer=False)\n # print('Linear layer reinitialized to initial seed.')\n print('Completely warmstart finetuning!')\n return self._iterate(kettle, poison_delta=poison_delta, max_epoch=max_epoch)\n\n def validate(self, kettle, poison_delta, val_max_epoch=None):\n \"\"\"Check poison on a new initialization(s), depending on the scenario.\"\"\"\n run_stats = list()\n\n for runs in range(self.args.vruns):\n if self.args.scenario == 'from-scratch':\n self.initialize()\n print('Model reinitialized to random seed.')\n elif self.args.scenario == 'transfer':\n self.load_feature_representation()\n self.reinitialize_last_layer(reduce_lr_factor=1.0)\n print('Linear layer reinitialized to initial seed.')\n elif self.args.scenario == 'finetuning':\n self.load_feature_representation()\n self.reinitialize_last_layer(reduce_lr_factor=FINETUNING_LR_DROP, keep_last_layer=True)\n # print('Linear layer reinitialized to initial seed.')\n print('Completely warmstart finetuning!')\n\n # Train new model\n run_stats.append(self._iterate(kettle, poison_delta=poison_delta, max_epoch=val_max_epoch))\n return average_dicts(run_stats)\n\n def eval(self, dropout=True):\n \"\"\"Switch everything into evaluation mode.\"\"\"\n raise NotImplementedError()\n\n def _iterate(self, kettle, poison_delta):\n \"\"\"Validate a given poison by training the model and checking source accuracy.\"\"\"\n raise NotImplementedError()\n\n def _adversarial_step(self, kettle, poison_delta, step, poison_sources, true_classes):\n \"\"\"Step through a model epoch to in turn minimize source loss.\"\"\"\n raise NotImplementedError()\n\n def _initialize_model(self, model_name, pretrain=False):\n if pretrain and self.args.pretrain_dataset is not None:\n dataset = self.args.pretrain_dataset\n else:\n dataset = self.args.dataset\n\n model = get_model(model_name, dataset, pretrained=self.args.pretrained_model)\n model.frozen = False\n # Define training routine\n defs = training_strategy(model_name, self.args)\n optimizer, scheduler = get_optimizers(model, self.args, defs)\n\n return model, defs, optimizer, scheduler\n\n\n def _step(self, kettle, poison_delta, epoch, stats, model, defs, optimizer, scheduler, pretraining_phase=False):\n run_step(kettle, poison_delta, epoch, stats, model, defs, optimizer, scheduler,\n loss_fn=self.loss_fn, pretraining_phase=pretraining_phase)\n","repo_name":"hsouri/Sleeper-Agent","sub_path":"forest/victims/victim_base.py","file_name":"victim_base.py","file_ext":"py","file_size_in_byte":7593,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"52"} +{"seq_id":"28044233053","text":"#uses files\n#18_test.py\n#files/troiki.txt\n#files/operations_3_4.txt\n\nfrom random import randint,shuffle,choice\nimport hashlib\nimport sys\nfrom time import time\ndef rantime(n):\n if 25:\n try:\n diff=int(input('Выберите сложность от 1 до 5 (1 самый лёгкий)'))\n except ValueError:\n continue\n\nminimtimefortask=60\ndeltatime=randint(0,99)/100\ntmrnd=0\nwronganswer=thinkmore=True#timelogger\n\nnumvar=4#number of variants\ntest=0#test number\nrightnum=0#right answers number\ntypo=0#misprints number\nanswers='|'#table of marks\n\nwhile True:\n sortby=randint(0,1)\n numch=numchoice[min(int(sc),min(3,diff)*2)]\n numvar=4+(int(sc)+diff*2+randint(0,5))//18\n req=[i for i in range(numch)]#choice requests\n tr=choice(tro).split()\n good=0\n while not good:\n shuffle(req)\n good=1\n for i in range(numvar):\n for j in range(numvar):\n good*=int(opr[req[i]].split(':')[1][req[j]])\n answls=[]\n#logbegin\n tmnow=time()\n #print(tmnow,tmrnd+minimtimefortask+deltatime)\n if tmnow>tmrnd+minimtimefortask+deltatime:\n rantime(6)\n deltatime=randint(0,99)/100\n elif wronganswer:\n if thinkmore:\n print('Предлагаю Вам подумать подольше')\n thinkmore=False\n continue\n tmrnd=tmnow\n thinkmore=True\n#logend \n print('#%i'%(test+1))\n print('В таблице приведены запросы к поисковому серверу. Для каждого запроса указан его код — соответствующая буква от %s до %s. Расположите коды запросов слева направо в порядке %s количества страниц, которые нашёл поисковый сервер по каждому запросу. По всем запросам было найдено разное количество страниц. Для обозначения логической операции «ИЛИ» в запросе используется символ «|», а для логической операции «И» — «&»:'%(abc[0],abc[numvar-1],sorting[sortby]))\n print(' Код : Запрос')\n for i in range(numvar):\n reqout=opr[req[i]].split(':')[0]\n reqout=reqout.replace('a',tr[0])\n reqout=reqout.replace('b',tr[1])\n reqout=reqout.replace('c',tr[2])\n reqout=reqout.replace('d',tr[3])\n print(' %s : %s'%(abc[i],reqout))\n answls.append([int(opr[req[i]].split(':')[2]),abc[i]])\n answls.sort()\n right=''#right answer\n for i in range(numvar):\n right+=answls[i][1]\n right=right[::2*sortby-1]\n print('Ваш ответ (без пробелов):',end='')\n ##validation \n answer=input().strip().upper()\n #print(answer)\n test+=1\n if answer==right:\n rightnum+=1\n print('Правильно. ')\n wronganswer=False#timeroption\n answers+=str(test)+'|'\n sc+=1\n else:\n answer=input('Неправильно. Попробуйте ещё раз:').strip().upper()\n sc=sc*(0.96-0.01*diff)\n if answer==right:\n rightnum+=1\n typo+=1\n print('Правильно. ')\n wronganswer=False#timeroption\n answers+=':%i:|'%test\n sc+=1\n else:\n print('Неправильно. Правильный ответ:',right)\n wronganswer=True#timeroption\n answers+='*|'\n sc=sc*(0.94-0.02*diff)\n #print(rightnum)\n pright(rightnum,typo,test)\n print(answers)\n print('балл = %g (сложность %i)'%(sc,diff))\n","repo_name":"ferolen/kimpy_files","sub_path":"18_test.py","file_name":"18_test.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39303098931","text":"import math\nimport os\nimport sys\nimport time\nfrom ast import literal_eval\nfrom datetime import datetime\n\nimport clip\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.datasets as Datasets\nimport torchvision.models as models\nimport torchvision.transforms as T\nimport torchvision.utils as vutils\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.utils import make_grid\nfrom tqdm.notebook import trange, tqdm\n\nfrom vgg19 import VGG19\n\n# torch.manual_seed(0)\nclip_model = None\n# ---------------------------------------------------------------\ndate_time_obj = datetime.now()\ntimestamp_str = date_time_obj.strftime(\"%Y-%m-%d_%H.%M.%S\")\nprint('Current Timestamp : ', timestamp_str)\nstart_time_total = time.perf_counter()\n# ---------------------------------------------------------------\n# Parameter you can change\n\n\nbatch_size = 32\ntest_batch = 32\ntest_size = 128\nnum_epoch = 25\nsave_model_every = 5\n# Available datasets: celeba_small, celeba, celeba_resize\ndataset = \"celeb\" # < --------------change this!\n\nlatent_dim = 128 # < --------------change this!\n# \"../conditional_VAE/src/embeddings.csv\" or \"./embeddings_128.csv\"\nembedding_file = \"./embeddings_128_random.csv\"\n# ---------------------------------------------------------------\n# !! no \"pt\"\n# set to None if you do not want to load a checkpoint\n#\nload_checkpoint = \"CNN_VAE_celeba_resize_2022-08-07_01.36.18_epoch24\"\nrun_train = False # < --------------change this!\n\n# ---------------------------------------------------------------\n# logging\nif run_train and load_checkpoint:\n print(\"Train with pretrained model...\", load_checkpoint)\nelif run_train and load_checkpoint is None:\n print(\"Train from scratch...\")\nelif load_checkpoint is not None and not run_train:\n print(\"Only load pretrained model, do not train...\", load_checkpoint)\nelif load_checkpoint is None and not run_train:\n # print(\"Set run_train to True or give a checkpoint\")\n raise SystemExit(\"!Set run_train to True or give a checkpoint...\")\n\n# ---------------------------------------------------------------\n# Parameters you may NOT want to change\ncondition_dim = 512\nimage_size = 64\nlr = 1e-4\nstart_epoch = 0\ndataset_root = \"./input/\"\nsave_dir = os.getcwd()\nbeta = 0.1\n\n# ---------------------------------------------------------------\nuse_cuda = torch.cuda.is_available()\nGPU_indx = 0\ndevice = torch.device(GPU_indx if use_cuda else \"cpu\")\n\n# ---------------------------------------------------------------\nif load_checkpoint:\n model_name = load_checkpoint\nelse:\n model_name = f\"CNN_VAE_{dataset}_{timestamp_str}\" # \"STL10_8\" #\"STL10_8\" #STL10_8_64.pt\n\nif model_name == \"CNN_VAE_celeba_2022-08-05_01.49.10\":\n from RES_VAE3 import VAE\n # latent_dim = 512\n\nelif model_name in [\"CNN_VAE_celeba_2022-08-05_03.20.52\", \"CNN_VAE_celeba_2022-08-05_11.31.54\"]:\n from RES_VAE2 import VAE\n # latent_dim = 512\n\nelif model_name in [\"CNN_VAE_celeba_2022-08-04_23.22.32\",\n \"CNN_VAE_celeba_2022-08-04_23.22.32_epoch20.pt\"]: # best model not crop face\n from RES_VAE2 import VAE\n # latent_dim = 128\n\nelif model_name in [\"CNN_VAE_celeba_resize_2022-08-07_01.36.18_epoch24\"]: # best model trained on crop face\n from RES_VAE2 import VAE\n # dataset = \"celeba_resize\"\n\nelif model_name in [\"CNN_VAE_celeba_2022-08-05_14.32.29\"]:\n from RES_VAE4 import VAE\n\nelse:\n from RES_VAE2 import VAE\n\nif \"CNN_VAE_celeba_resize\" in model_name:\n dataset = \"celeba_resize\"\n\nelif \"CNN_VAE_celeba\" in model_name:\n dataset = \"celeba\"\nprint(\"dataset = \", dataset)\n\n\n# ---------------------------------------------------------------\nclass CelebA_CLIP(Datasets.ImageFolder):\n def __init__(\n self,\n root,\n transform,\n image_folder,\n clip_embeddings_csv\n ):\n super(CelebA_CLIP, self).__init__(\n root=root,\n transform=transform\n )\n\n self.clip_embeddings = clip_embeddings_csv\n self.samples = self.make_dataset_(root, None, None, None)\n self.root = os.path.join(root, image_folder)\n\n def __len__(self) -> int:\n return len(self.samples)\n\n def make_dataset_(self, root, class_to_idx, extensions, is_valid_file):\n df = pd.read_csv(self.clip_embeddings, index_col=0,\n converters={'embeddings': literal_eval})\n im_names = df['image_id'].values\n # img_embed = zip(df['image_id'].values, df[\"embeddings\"].values)\n # img_embed = tuple(zip(range(len(im_names)), im_names, df[\"embeddings\"].values))\n targets = df[\"embeddings\"].values # #(batch,)\n img_embed = tuple(zip(im_names, targets))\n\n return list(img_embed)\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (sample, target) where target is class_index of the target class.\n \"\"\"\n # print(len(self.samples))\n # print(\"index,\", index)\n path, target = self.samples[index]\n # print(\"path\", path)\n path = os.path.join(self.root, path)\n # print(\"path\", path)\n\n sample = self.loader(path)\n if self.transform is not None:\n sample = self.transform(sample)\n\n target = torch.tensor(target)\n\n return sample, target\n\n\n# ---------------------------------------------------------------\ndef get_data_STL10(transform, batch_size, download=True, root=\"./input\"):\n print(\"Loading trainset...\")\n trainset = Datasets.STL10(root=root, split='unlabeled', transform=transform, download=download)\n\n trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2)\n\n print(\"Loading testset...\")\n testset = Datasets.STL10(root=root, split='test', download=download, transform=transform)\n\n testloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2)\n print(\"Done!\")\n\n return trainloader, testloader\n\n\ndef get_data_celebA(transform, batch_size, embedding_file):\n # data_root = \"../../datasets/celeba_small/celeba/\"\n data_root = \"../datasets/celeba/\"\n training_data = CelebA_CLIP(root=data_root,\n transform=transform,\n image_folder=\"img_align_celeba\",\n clip_embeddings_csv=embedding_file) # \"../conditional_VAE/src/embeddings.csv\"\n print(\"dataset size\", len(training_data)) # 202599\n\n train_size = len(training_data) - test_size\n trainset, testset = torch.utils.data.random_split(training_data, [train_size, test_size])\n testloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)\n if train_size > 0:\n trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8)\n return trainloader, testloader, train_size\n else:\n\n return None, testloader, train_size\n print(\"Done load dataset\")\n\n\ndef get_data_celebA_resized(transform, batch_size, embedding_file):\n # data_root = \"../../datasets/celeba_small/celeba/\"\n # \"../datasets/resized_celebA3_128/ \"celebA\"\n data_root = \"../datasets/resized_celebA3/\"\n training_data = CelebA_CLIP(root=data_root,\n transform=transform,\n image_folder=\"celebA\",\n clip_embeddings_csv=embedding_file)\n print(\"dataset size\", len(training_data)) # 202599\n\n train_size = len(training_data) - test_size\n trainset, testset = torch.utils.data.random_split(training_data, [train_size, test_size])\n testloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)\n if train_size > 0:\n trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8)\n return trainloader, testloader, train_size\n else:\n\n return None, testloader, train_size\n print(\"Done load dataset\")\n\n\ndef get_data_celebA_small(transform, batch_size):\n data_root = \"../datasets/celeba_small/celeba/\"\n training_data = CelebA_CLIP(root=data_root,\n transform=transform,\n image_folder=\"img_align_celeba\",\n clip_embeddings_csv=\"./embeddings_128.csv\")\n\n print(\"dataset size\", len(training_data)) # 128\n\n train_size = len(training_data) - test_size\n trainset, testset = torch.utils.data.random_split(training_data, [train_size, test_size])\n testloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)\n if train_size > 0:\n trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=8)\n return trainloader, testloader, train_size\n else:\n\n return None, testloader, train_size\n print(\"Done load dataset\")\n\n\ndef get_test_set():\n data_root = \"../datasets/resized_celebA3/\"\n testset = CelebA_CLIP(root=data_root,\n transform=transform,\n image_folder=\"celebA\",\n clip_embeddings_csv=embedding_file)\n print(\"dataset size\", len(testset)) # 202599\n testloader = DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=8)\n return testloader\n\n\n# ---------------------------------------------------------------\nif dataset == \"celeba\":\n transform = T.Compose([T.CenterCrop(178), T.Resize((image_size, image_size)), T.ToTensor()])\n # transform = T.Compose([T.Resize((image_size,image_size)), T.ToTensor()])\n # transform = T.Compose([T.Resize(image_size), T.ToTensor()])\n # transform = T.Compose([T.ToTensor()])\n trainloader, testloader, train_size = get_data_celebA(transform, batch_size, embedding_file)\n\n\nelif dataset == \"celeba_resize\":\n # transform = T.Compose([T.CenterCrop(178),T.Resize((image_size,image_size)), T.ToTensor()])\n # transform = T.Compose([T.Resize((image_size,image_size)), T.ToTensor()])\n # transform = T.Compose([T.Resize(image_size), T.ToTensor()])\n transform = T.Compose([T.ToTensor()])\n trainloader, testloader, train_size = get_data_celebA_resized(transform, batch_size, embedding_file)\n\nelif dataset == \"celeba_small\":\n transform = T.Compose([T.CenterCrop(178), T.Resize((image_size, image_size)), T.ToTensor()])\n trainloader, testloader, train_size = get_data_celebA_small(transform, batch_size)\n\n\nelif dataset == \"STL10\":\n transform = T.Compose([T.Resize(image_size), T.ToTensor()])\n trainloader, testloader = get_data_STL10(transform, batch_size, download=True, root=dataset_root)\n\nelse:\n print(\"dataset name is wrong\")\n sys.exit()\n\n# ---------------------------------------------------------------\n# get a test image batch from the testloader to visualise the reconstruction quality\ntestloader = get_test_set()\ndataiter = iter(testloader)\ntest_images, test_labels = dataiter.next()\nprint(\"load test batch\")\nprint(\"image input shape\", test_images.shape)\nprint(\"condition shape\", test_labels.shape) # torch.Size([16, 1, 512])\n\n\n# ---------------------------------------------------------------\n# OLD way of getting features and calculating loss - Not used\n\n# create an empty layer that will simply record the feature map passed to it.\nclass GetFeatures(nn.Module):\n def __init__(self):\n super(GetFeatures, self).__init__()\n self.features = None\n\n def forward(self, x):\n self.features = x\n return x\n\n\n# download the pre-trained weights of the VGG-19 and append them to an array of layers .\n# we insert a GetFeatures layer after a relu layer.\n# layers_deep controls how deep we go into the network\ndef get_feature_extractor(layers_deep=7):\n C_net = models.vgg19(pretrained=True).to(device)\n C_net = C_net.eval()\n\n layers = []\n for i in range(layers_deep):\n layers.append(C_net.features[i])\n if isinstance(C_net.features[i], nn.ReLU):\n layers.append(GetFeatures())\n return nn.Sequential(*layers)\n\n\n# this function calculates the L2 loss (MSE) on the feature maps copied by the layers_deep\n# between the reconstructed image and the origional\ndef feature_loss(img, recon_data, feature_extractor):\n img_cat = torch.cat((img, torch.sigmoid(recon_data)), 0)\n out = feature_extractor(img_cat)\n loss = 0\n for i in range(len(feature_extractor)):\n if isinstance(feature_extractor[i], GetFeatures):\n loss += (feature_extractor[i].features[:(img.shape[0])] - feature_extractor[i].features[\n (img.shape[0]):]).pow(2).mean()\n return loss / (i + 1)\n\n\n# Linear scaling the learning rate down\ndef lr_Linear(epoch_max, epoch, lr):\n lr_adj = ((epoch_max - epoch) / epoch_max) * lr\n set_lr(lr=lr_adj)\n\n\ndef set_lr(lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef vae_loss(recon, x, mu, logvar):\n recon_loss = F.binary_cross_entropy_with_logits(recon, x)\n KL_loss = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp()).mean()\n loss = recon_loss + 0.01 * KL_loss\n return loss\n\n\n# ---------------------------------------------------------------\n\n# Create the feature loss module\n\n# load the state dict for vgg19\nstate_dict = torch.hub.load_state_dict_from_url('https://download.pytorch.org/models/vgg19-dcbb9e9d.pth')\n# manually create the feature extractor from vgg19\nfeature_extractor = VGG19(channel_in=3)\n\n# loop through the loaded state dict and our vgg19 features net,\n# loop will stop when net.parameters() runs out - so we never get to the \"classifier\" part of vgg\nfor ((name, source_param), target_param) in zip(state_dict.items(), feature_extractor.parameters()):\n target_param.data = source_param.data\n target_param.requires_grad = False\n\nfeature_extractor = feature_extractor.to(device)\n\n# ---------------------------------------------------------------\n\n# Create the save directory if it does note exist\nif not os.path.isdir(save_dir + \"/Models\"):\n os.makedirs(save_dir + \"/Models\")\nif not os.path.isdir(save_dir + \"/Results\"):\n os.makedirs(save_dir + \"/Results\")\n\nresult_folder = os.path.join(save_dir, \"Results\", f\"result_{model_name}\")\nif not os.path.exists(result_folder):\n os.mkdir(result_folder)\n\n# ---------------------------------------------------------------\n# Load / Initialize the model\nmodel_save_path = os.path.join(save_dir, \"Models\", model_name + \".pt\")\n\nif load_checkpoint:\n\n if model_name == \"CNN_VAE_celeba_2022-08-04_18.05.43\":\n batch_size = 128\n condition_dim = 512\n latent_dim = 512\n checkpoint = torch.load(save_dir + \"/Models/\" + model_name + \".pt\", map_location=\"cpu\")\n print(\"Checkpoint loaded\")\n vae_net = VAE(channel_in=3 + condition_dim, ch=64, z=latent_dim, condition_dim=condition_dim).to(device)\n optimizer = optim.Adam(vae_net.parameters(), lr=lr, betas=(0.5, 0.999))\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n vae_net.load_state_dict(checkpoint['model_state_dict'])\n start_epoch = checkpoint[\"epoch\"]\n loss_log = checkpoint[\"loss_log\"]\n\n else:\n vae_net = torch.load(model_save_path)\n\nelif run_train:\n # If checkpoint does exist raise an error to prevent accidental overwriting\n if os.path.isfile(model_save_path):\n # raise ValueError(\"Warning Checkpoint exists\")\n print(\"Warning Checkpoint exists\")\n\n # Create VAE network\n # z = latent dim, ch = out channel\n print(\"Initialize VAE net ...\")\n vae_net = VAE(channel_in=3 + condition_dim, ch=64, z=latent_dim, condition_dim=condition_dim).to(device)\n\n# setup optimizer\noptimizer = optim.Adam(vae_net.parameters(), lr=lr, betas=(0.5, 0.999))\n# Loss function\nBCE_Loss = nn.BCEWithLogitsLoss()\n\n\n# ---------------------------------------------------------------\n\n\ndef convert_batch_to_image_grid(image_batch, dim=64):\n print(\"image_batch\", image_batch.shape)\n # torch.Size([16, 3, 64, 64])\n reshaped = (image_batch.reshape(4, 8, dim, dim, 3)\n .transpose(0, 2, 1, 3, 4)\n .reshape(4 * dim, 8 * dim, 3))\n return reshaped\n\n\ndef save_image_grid(img_tensor, save_path, title=None):\n if torch.is_tensor(img_tensor):\n img_tensor = img_tensor.cpu()\n\n grid_img = make_grid(img_tensor, scale_each=True)\n plt.figure(figsize=(10, 10))\n plt.imshow(grid_img.permute(1, 2, 0))\n if title:\n plt.title(title, fontsize=20, pad=5)\n plt.axis('off')\n plt.show()\n plt.savefig(os.path.join(save_path), dpi=100, bbox_inches='tight')\n\n\ndef save_each_image(img_tensor):\n img_tensor = img_tensor.detach()\n for i in range(img_tensor.shape[0]):\n img = img_tensor[i].permute(1, 2, 0)\n plt.imshow(img.numpy())\n im_name = 'img_{}.png'.format(i)\n plt.savefig(os.path.join(save_dir, \"Results\", im_name), dpi=200, bbox_inches='tight')\n\n\ndef image_generation_clip(target_attr=None, save_folder=None):\n \"\"\"\n Generates and plots a batch of images with specific attributes (if given).\n\n - list target_attr : list of desired attributes [default None]\n \"\"\"\n global clip_model\n if clip_model is None:\n clip_model, preprocess = clip.load(\"ViT-B/32\", device=device)\n clip_model.cuda().eval()\n print(\"Load clip\")\n batch = test_batch\n # Vector of user-defined attributes.\n if target_attr:\n\n text = clip.tokenize([target_attr]).to(device)\n\n with torch.no_grad():\n text_features = clip_model.encode_text(text)\n # labels = text_features.repeat_interleave(batch, dim=0).to(device)\n labels = text_features.repeat(batch, 1)\n\n # labels_ = np.tile(text_features.cpu(), reps=[batch, 1])\n # print(labels == labels_ )\n print(\"Generation with attributes: \", target_attr)\n\n # Vector of attributes taken from the test set.\n else:\n # batch_gen = batch_generator(test_data['batch_size'], test_data['test_img_ids'], model_name='Conv')\n labels = test_labels.to(device)\n print(\"Generation with fixed attributes.\")\n target_attr = \"no attribute given\"\n\n # vae_net.train()\n latent_dim = vae_net.latent_dim\n # mu = torch.zeros(batch, latent_dim, 1, 1) + 1.0\n # log_var = torch.zeros(batch, latent_dim, 1, 1) + 0.3\n # # print(mu.shape)\n # image_embed = torch.reshape(labels, [-1, 512, 1, 1])\n # ones = torch.ones(batch, 512, 1, 1).to(device)\n # condition = ones * image_embed # [16, 32, 64, 64]\n # z = vae_net.sample(mu.to(device), log_var.to(device)) ####\n #\n condition = torch.reshape(labels, [batch, vae_net.condition_dim, 1, 1])\n\n # generate z (method1)\n # sample both initial input and condition\n # mu = torch.zeros(batch, latent_dim, 1, 1) + 1.0\n # log_var = torch.zeros(batch, latent_dim, 1, 1) + 0.3\n #\n # # z = [16, 3, 64, 64]\n # z = vae_net.sample(mu.to(device), log_var.to(device))\n # ------------------------------------------------------------#\n\n # generate z (method2)\n z_mean = 1.0\n z_log_var = 0.3\n\n # eps = torch.randn(batch, latent_dim, 1, 1)\n # torch.normal(mean=0.5, std=torch.arange(1., 6.))\n eps = torch.normal(mean=0.0, std=1.0, size=(batch, latent_dim, 1, 1))\n z = z_mean + math.exp(z_log_var * .5) * eps\n z = z.to(device)\n # ------------------------------------------------------------#\n\n # generate z (method3)\n # z_list = []\n # for _ in range(batch):\n # z_mean = random.uniform(0.0, 1.0)\n # z_log_var = random.uniform(0.0, 1.0)\n # eps = torch.normal(mean=0.0, std=1.0, size=(latent_dim, 1, 1))\n # z = z_mean + math.exp(z_log_var * .5) * eps\n # z_list.append(z)\n #\n # z = torch.stack(z_list, dim=0) #[16, 512, 1, 1]\n # z = z.to(device)\n # ------------------------------------------------------------#\n\n # print(\"z\", z.shape)\n # print(\"condition\", condition.shape)\n z_cond = torch.cat((z, condition), dim=1)\n logits = vae_net.decoder(z_cond)\n generated = torch.sigmoid(logits)\n prompt = target_attr.replace(' ', '_')\n save_path = os.path.join(save_folder, \"generation_\" + prompt + \".png\")\n\n # vutils.save_image(generated, save_path)\n # print(\"save image at\", save_path)\n save_image_grid(generated, save_path, title=prompt)\n print(\"save image at\", save_path)\n\n\ndef image_generation_clip_interpolation(target_attr, num_images=1):\n \"\"\"\n Generates and plots a batch of images with specific attributes (if given).\n\n - list target_attr : list of desired attributes [default None]\n \"\"\"\n global clip_model\n if clip_model is None:\n clip_model, preprocess = clip.load(\"ViT-B/32\", device=device)\n clip_model.cuda().eval()\n print(\"Load clip\")\n\n result_batch = []\n if num_images < (test_images.shape[0]):\n num = num_images # range(images.shape[0])\n else:\n num = test_images.shape[0]\n\n for i in range(num):\n # reconstructed_images = []\n modified_images = []\n img = test_images[i][np.newaxis, ...]\n label = test_labels[i][np.newaxis, ...]\n vae_net.eval()\n for beta in reversed(range(0, 10)):\n image_embed_factor = beta * 0.1\n recon_data, img_z, var = vae_net(img.to(device), label.to(device))\n\n # print(\"img_z\", img_z.shape) # img_z torch.Size([1, 128, 1, 1])\n # reconstructed_images.append(model_output['recon_img'].numpy()[0, :, :, :])\n if target_attr is None:\n raise ValueError('target_attr can not be None')\n sys.exit()\n else:\n text = clip.tokenize([target_attr]).to(device)\n with torch.no_grad():\n text_features = clip_model.encode_text(text)\n # labels_ = np.expand_dims(labels[i], axis=0) # (1, 512) -- not needed\n # type(labels[i] # of shape (512,)\n # condition with input image embeddings + given text embeddings\n # modified_label = (test_labels[i] * image_embed_factor) + (\n # text_features.cpu().detach().numpy() * (1.0 - image_embed_factor)) # (1, 512)\n\n modified_label = (label.to(device) * image_embed_factor) + (\n text_features * (1.0 - image_embed_factor)) # (1, 512)\n modified_label = modified_label.unsqueeze(2).unsqueeze(3)\n\n # print(\"modified_label\", modified_label.shape) #modified_label torch.Size([1, 512])\n # condition with only input image embeddings\n # modified_label = text_features.cpu()\n\n # modified_label = (1, 512)\n z_cond = torch.cat((img_z, modified_label), dim=1)\n logits = vae_net.decoder(z_cond)\n generated = torch.sigmoid(logits).detach().cpu().numpy()\n modified_images.append(generated[0, :, :, :])\n # result = np.asarray(modified_images, dtype='float32') # (10, 64, 64, 3)\n modified_images = np.array(modified_images)\n result = torch.tensor(modified_images)\n result_batch.append(result)\n # break\n return result_batch\n\n\ndef save_image_grid_interpolation(img_tensor, save_path, title):\n if torch.is_tensor(img_tensor):\n img_tensor = img_tensor.cpu()\n\n grid_img = make_grid(img_tensor, scale_each=True, nrow=5)\n plt.figure(figsize=(10, 10))\n plt.imshow(grid_img.permute(1, 2, 0))\n if title:\n plt.title(title, fontsize=20, pad=5)\n plt.axis('off')\n plt.show()\n plt.savefig(os.path.join(save_path), dpi=100, bbox_inches='tight')\n print(f\"image is saved as {save_path}\")\n\n\ndef plot_interpolation(target_attr, num_images=1, save_folder=None):\n batch_result_list = image_generation_clip_interpolation(target_attr=target_attr, num_images=num_images)\n for i, result in enumerate(batch_result_list):\n file_name = f\"modified_images_{target_attr}_{i}.png\"\n if save_folder:\n save_path = os.path.join(save_folder, file_name)\n else:\n save_path = os.path.join(result_folder, file_name)\n\n save_image_grid_interpolation(result, save_path, title=target_attr)\n\n\ndef reconstruct_images(save_folder=None, save_recon_and_ori_together=False):\n recon_data, mu, var = vae_net(test_images.to(device), test_labels.to(device))\n if save_folder:\n save_folder_ = save_folder\n else:\n save_folder_ = result_folder\n\n if save_recon_and_ori_together:\n recon_images = torch.cat((torch.sigmoid(recon_data).cpu(), test_images.cpu()), 2)\n\n save_path = os.path.join(save_folder_, \"recon.png\")\n save_image_grid(recon_images, save_path)\n print(\"save image at\", save_path)\n else:\n recon_images = torch.sigmoid(recon_data).cpu()\n\n save_path = os.path.join(save_folder_, \"recon.png\")\n save_image_grid(recon_images, save_path)\n print(\"save image at\", save_path)\n\n save_path = os.path.join(save_folder_, \"ori.png\")\n save_image_grid(test_images.cpu(), save_path)\n print(\"save image at\", save_path)\n\n\ndef attribute_manipulation(target_attr=None, image_embed_factor=0.5, save_folder=None):\n global clip_model\n if clip_model is None:\n clip_model, preprocess = clip.load(\"ViT-B/32\", device=device)\n clip_model.cuda().eval()\n\n reconstructed_images = []\n modified_images = []\n new_attr_factor = 1 - image_embed_factor\n for i in range(test_images.shape[0]):\n img = test_images[i][np.newaxis, ...] # [1, 3, 64, 64]\n label = test_labels[i][np.newaxis, ...] # [1, 512]\n vae_net.eval()\n recon_data, img_z, var = vae_net(img.to(device), label.to(device))\n recon_im = torch.sigmoid(recon_data)\n recon_im = recon_im.cpu().detach()[0, :, :, :]\n\n reconstructed_images.append(recon_im)\n\n if target_attr is None:\n\n modified_label = label\n modified_label = modified_label.unsqueeze(2).unsqueeze(3)\n\n else:\n text = clip.tokenize([target_attr]).to(device)\n with torch.no_grad():\n text_features = clip_model.encode_text(text)\n modified_label = (label.to(device) * image_embed_factor) + (\n text_features * new_attr_factor)\n\n modified_label = modified_label.unsqueeze(2).unsqueeze(3)\n\n z_cond = torch.cat((img_z, modified_label), dim=1)\n logits = vae_net.decoder(z_cond)\n generated = torch.sigmoid(logits)\n modified_images.append(generated.detach().cpu()[0, :, :, :])\n\n print(\"modified_images\", modified_images[0].shape)\n str_target_attr = str(target_attr).replace(' ', '_')\n str_target_attr_factors = f\"{str_target_attr}_{image_embed_factor}_{new_attr_factor}\"\n file_name = f\"modified_images_{str_target_attr_factors}.png\"\n\n if save_folder:\n save_path = os.path.join(save_folder, file_name)\n else:\n save_path = os.path.join(result_folder, file_name)\n\n save_image_grid(modified_images, save_path)\n print(\"save image at\", save_path)\n\n file_name = f\"recon_images_{str_target_attr_factors}.png\"\n if save_folder:\n save_path = os.path.join(save_folder, file_name)\n else:\n save_path = os.path.join(result_folder, file_name)\n save_image_grid(reconstructed_images, save_path)\n print(\"save image at\", save_path)\n\n\n# ---------------------------------------------------------------\ndef train():\n loss_log = []\n\n # save log\n with open(os.path.join(result_folder, \"params.txt\"), \"w\") as f:\n f.write(f\"epoch = {num_epoch}\\n\")\n f.write(f\"learning_rate = {lr}\\n\")\n f.write(f\"train_size = {train_size}\\n\")\n f.write(f\"batch_size = {batch_size} \\n\")\n f.write(f\"label_dim = {condition_dim}\\n\")\n f.write(f\"image_size = {image_size}\\n\")\n f.write(f\"latent_dim = {latent_dim}\\n\")\n f.write(f\"beta = {beta}\\n\")\n f.write(f\"model checkpoint = {model_save_path}\\n\\n\")\n\n for epoch in trange(start_epoch, num_epoch, leave=False):\n start_time_epoch = time.perf_counter()\n lr_Linear(num_epoch, epoch, lr)\n vae_net.train()\n for i, (images, condition) in enumerate(tqdm(trainloader, leave=False)):\n images = images.to(device)\n condition = condition.to(device) # [batch, 512]\n # recon_data = [batch, 3 + 512, 64, 64]\n recon_data, mu, logvar = vae_net(images, condition)\n trained_mu, trained_logvar = mu, logvar\n # VAE loss\n loss = vae_loss(recon_data, images, mu, logvar)\n\n # Perception loss\n loss += feature_extractor(torch.cat((torch.sigmoid(recon_data), images), 0))\n\n loss_log.append(loss.item())\n vae_net.zero_grad()\n loss.backward()\n optimizer.step()\n\n # In eval mode the model will use mu as the encoding instead of sampling from the distribution\n print(\"epoch\", epoch)\n exec_time_epoch = time.perf_counter() - start_time_epoch\n\n print(f\"time epoch = {exec_time_epoch} sec ({exec_time_epoch / 60.0} min )\\n\")\n with open(os.path.join(result_folder, \"params.txt\"), \"a\") as f:\n f.write(f\"\\nepoch {epoch}, time epoch = {exec_time_epoch} sec ({exec_time_epoch / 60.0} min )\\n\")\n\n result_folder_epoch = os.path.join(result_folder, f\"{epoch}\")\n if not os.path.exists(result_folder_epoch):\n os.mkdir(result_folder_epoch)\n\n vae_net.eval()\n with torch.no_grad():\n recon_data, _, _ = vae_net(test_images.to(device), test_labels.to(device))\n images = torch.cat((torch.sigmoid(recon_data.cpu()), test_images), 2)\n save_path = os.path.join(result_folder_epoch, \"recon\" + \"_\" + str(epoch) + \".png\")\n # save_path = \"%s/%s/%s_%d_%d.png\" % (save_dir, \"Results\", model_name, image_size, epoch)\n # print(images.shape) # [128, 3, 128, 64]\n print(\"save image at\", save_path)\n vutils.save_image(images, save_path)\n image_generation_clip(target_attr=\"sad\", save_folder=result_folder_epoch)\n image_generation_clip(target_attr=\"wearing glasses\", save_folder=result_folder_epoch)\n\n # Save a checkpoint\n if (epoch + 1) % save_model_every == 0:\n print(\"true\")\n model_save_path_epoch = os.path.join(save_dir, \"Models\", f\"{model_name}_epoch{epoch}.pt\")\n torch.save(vae_net, model_save_path_epoch)\n # torch.save({\n # 'epoch': epoch,\n # 'loss_log': loss_log,\n # 'model_state_dict': vae_net.state_dict(),\n # 'optimizer_state_dict': optimizer.state_dict()\n #\n # }, model_save_path)\n # torch.save(vae_net, model_save_path)\n print(\"Save checkpoint at\", model_save_path_epoch)\n\n exec_time_total = time.perf_counter() - start_time_total\n print(f\"time total = {exec_time_total} sec ({exec_time_total / 60.0} min )\\n\")\n with open(os.path.join(result_folder, \"params.txt\"), \"a\") as f:\n f.write(f\"\\ntime total = {exec_time_total} sec ({exec_time_total / 60.0} min )\\n\")\n\n\n# ---------------------------------------------------------------\nif __name__ == \"__main__\":\n if run_train:\n train()\n result_folder = \"./Results/temp\"\n\n # 3) attribute manipulation\n attribute_manipulation(target_attr=\"wear reading glasses\", image_embed_factor=0.5, save_folder=result_folder)\n plot_interpolation(target_attr=\"smiling\", num_images=2, save_folder=None)\n\n # 1) text-to-image\n image_generation_clip(target_attr=\"wear glasses\", save_folder=result_folder)\n # 2) image-to-image\n image_generation_clip(target_attr=None, save_folder=result_folder)\n\n # image reconstruction\n reconstruct_images(save_folder=result_folder)\n","repo_name":"meanna/CVAE_VGG19","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":31915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18848489744","text":"import telebot\nfrom datetime import datetime\nimport openpyxl as xl\nimport re\nimport schedule\nfrom schedule import every, repeat, run_pending\nimport time\n\n\nbot = telebot.TeleBot(\"TOKEN\", parse_mode=None)\n\n\ndef BirthdayNotification():\n\n\n path = r'FILE PATH'\n wb = xl.load_workbook(filename=path, read_only=True)\n ws = wb['Sheet']\n\n current_datetime = datetime.now()\n current_date = current_datetime.date()\n date = str(current_date)[5:10] # Формат строки YYYY-MM-DD, после среза MM-DD\n\n #val = ws.cell(row=173, column=3).value\n\n\n for row in ws.rows:\n for cell in row:\n if re.match(date, str(cell.value)[5:10]):\n msg = \" Сегодня празднует свой день рождения \" + \"\\n\" + row[3].internal_value + \"\\n\" + row[2].internal_value + \"\\n\"\n # для отображения сожержимого строки с рядом стоящей искомой ячейкой надо изменить параметр row, где значение параметра будет номер столбца\n\n\n bot.send_message(chat_id=1717876558 ,text=msg)\n bot.infinity_polling()\n\nschedule.every().day.at(\"15:25\").do(BirthdayNotification)\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n","repo_name":"gray-mouse/birthday_bot_excel","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8575140341","text":"import rasterio\nfrom rasterio.windows import Window\n\n\ndef geoimage_simple_load(img_path, band_indices):\n \"\"\"\n load a geo image in numpy array of shape C * W * H\n\n \"\"\"\n\n with rasterio.open(img_path) as src:\n img_array = src.read(indexes=band_indices)\n\n if img_array.ndim == 2:\n img_array = img_array[np.newaxis, ...]\n\n return img_array\n\n\ndef geoimage_load_tile(img_path, band_indices, window):\n \"\"\"\n\n windows : tuple with col_off, row_off, width, height\n \"\"\"\n\n with rasterio.open(img_path) as src:\n img_array = src.read(window=Window(*window), indexes=band_indices)\n\n if img_array.ndim == 2:\n img_array = img_array[np.newaxis, ...]\n\n return img_array\n","repo_name":"ndavid/EOTorchLoader","sub_path":"src/eotorchloader/backend/rasterio.py","file_name":"rasterio.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"11379744924","text":"#!/usr/bin/python3\n\n'''\ndef roman_to_int(roman_string):\n if not roman_string:\n return 0\n\n if not isinstance(roman_string, str):\n return 0\n\n roman_string = roman_string.upper()\n roman_values = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n total = 0\n\n prev = roman_values[roman_number[0]]\n\n for i in roman_string:\n if i in list(roman_values.keys()):\n total += roman_values[i]\n if prev < roman_values[i]:\n total -= prev * 2\n prev = roman_values[i]\n else:\n return 0\n return total\n'''\n\n\ndef subract_(list_):\n to_sub = 0\n max_ = max(list_)\n\n for n in list_:\n if max_ > n:\n to_sub += n\n\n return (max_ - to_sub)\n\n\ndef roman_to_int(roman_string):\n if not roman_string:\n return 0\n\n if not isinstance(roman_string, str):\n return 0\n\n rom_n = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n }\n list_keys = list(rom_n.keys())\n\n num = 0\n last_rom = 0\n list_num = [0]\n\n for i in roman_string:\n for r_num in list_keys:\n if r_num == i:\n if rom_n.get(i) <= last_rom:\n num += subract_(list_num)\n list_num = [rom_n.get(i)]\n else:\n list_num.append(rom_n.get(i))\n\n last_rom = rom_n.get(i)\n\n num += subract_(list_num)\n\n return (num)\n","repo_name":"imoleBytes/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/12-roman_to_int.py","file_name":"12-roman_to_int.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19245259368","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# for implementing image transmission\n# import matplotlib.image as mpimg\n\nSAMPLE_RATE = 0.25e6\nBIT_LENGTH = 50\n\ndef write_floats(filename, tx_data):\n \"\"\"\n Writes a binary file with type Float32 with input data\n \n INPUT\n filename: string path of the output file to be written\n tx_data: data to be written with form tuple of 2 arrays (real, imag)\n \"\"\"\n real_data = np.array(tx_data[0])\n imag_data = np.array(tx_data[1])\n\n data = np.zeros(2*len(real_data), dtype=np.float32)\n data[0::2] = real_data\n data[1::2] = imag_data\n\n data.tofile(filename)\n\n return data\n\ndef arr_gen(input_arr):\n out_arr = []\n for i in range(len(input_arr)):\n out_arr.extend([input_arr[i]]*BIT_LENGTH)\n out_arr = 0.9*np.array(out_arr)\n return out_arr\n\nif __name__ == '__main__':\n zero_pad = 1e5\n in_arr = [1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]\n in_arr = in_arr*500\n in_arr = np.array(in_arr)\n in_arr = in_arr*2 - 1\n x_real = arr_gen(in_arr)\n # pad with zeros\n x_real = np.hstack((np.zeros(zero_pad/2), x_real, np.zeros(zero_pad/2)))\n plt.plot(x_real)\n plt.show()\n x_imag = np.zeros(len(x_real))\n test_data = (x_real, x_imag)\n write_floats('sent.dat', test_data)\n","repo_name":"Pratool/Learning-OFDM","sub_path":"transmitter.py","file_name":"transmitter.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12508681605","text":"import base64\nimport os\nimport hashlib\nimport json\n\nEXPECTED_CRX_MAGIC_NUM = 'Cr24'\nEXPECTED_CRX_VERSION = 2\n\ndef HexToInt(hex_chars):\n \"\"\" Convert bytes like \\xab -> 171 \"\"\"\n val = 0\n for i in xrange(len(hex_chars)):\n val += pow(256, i) * ord(hex_chars[i])\n return val\n\ndef HexToMPDecimal(hex_chars):\n \"\"\" Convert bytes to an MPDecimal string. Example \\x00 -> \"aa\"\n This gives us the AppID for a chrome extension.\n \"\"\"\n result = ''\n base = ord('a')\n for i in xrange(len(hex_chars)):\n value = ord(hex_chars[i])\n dig1 = value / 16\n dig2 = value % 16\n result += chr(dig1 + base)\n result += chr(dig2 + base)\n return result\n\ndef HexTo256(hex_chars):\n \"\"\" Convert bytes to pairs of hex digits. E.g., \\x00\\x11 -> \"{0x00, 0x11}\"\n The format is taylored for copy and paste into C code:\n const uint8 sha256_hash[] = { ... }; \"\"\"\n result = []\n for i in xrange(len(hex_chars)):\n value = ord(hex_chars[i])\n dig1 = value / 16\n dig2 = value % 16\n result.append('0x' + hex(dig1)[2:] + hex(dig2)[2:])\n return '{%s}' % ', '.join(result)\n\ndef GetPublicKeyPacked(f):\n magic_num = f.read(4)\n if magic_num != EXPECTED_CRX_MAGIC_NUM:\n raise Exception('Invalid magic number: %s (expecting %s)' %\n (magic_num,\n EXPECTED_CRX_MAGIC_NUM))\n version = f.read(4)\n if not version[0] != EXPECTED_CRX_VERSION:\n raise Exception('Invalid version number: %s (expecting %s)' %\n (version,\n EXPECTED_CRX_VERSION))\n pub_key_len_bytes = HexToInt(f.read(4))\n f.read(4)\n return f.read(pub_key_len_bytes)\n\ndef GetPublicKeyFromPath(filepath, is_win_path=False):\n # Normalize the path for windows to have capital drive letters.\n # We intentionally don't check if sys.platform == 'win32' and just\n # check if this looks like drive letter so that we can test this\n # even on posix systems.\n if (len(filepath) >= 2 and\n filepath[0].islower() and\n filepath[1] == ':'):\n filepath = filepath[0].upper() + filepath[1:]\n\n # On Windows, filepaths are encoded using UTF-16, little endian byte order,\n # using \"wide characters\" that are 16 bits in size. On POSIX systems, the\n # encoding is generally UTF-8, which has the property of being equivalent to\n # ASCII when only ASCII characters are in the path.\n if is_win_path:\n filepath = filepath.encode('utf-16le')\n\n return filepath\n\ndef GetPublicKeyUnpacked(f, filepath):\n manifest = json.load(f)\n if 'key' not in manifest:\n # Use the path as the public key.\n # See Extension::GenerateIdForPath in extension.cc\n return GetPublicKeyFromPath(filepath)\n else:\n return base64.standard_b64decode(manifest['key'])\n\ndef HasPublicKey(filename):\n if os.path.isdir(filename):\n with open(os.path.join(filename, 'manifest.json'), 'rb') as f:\n manifest = json.load(f)\n return 'key' in manifest\n return False\n\ndef GetPublicKey(filename, from_file_path, is_win_path=False):\n if from_file_path:\n return GetPublicKeyFromPath(\n filename, is_win_path=is_win_path)\n\n pub_key = ''\n if os.path.isdir(filename):\n # Assume it's an unpacked extension\n f = open(os.path.join(filename, 'manifest.json'), 'rb')\n pub_key = GetPublicKeyUnpacked(f, filename)\n f.close()\n else:\n # Assume it's a packed extension.\n f = open(filename, 'rb')\n pub_key = GetPublicKeyPacked(f)\n f.close()\n return pub_key\n\ndef GetCRXHash(filename, from_file_path=False, is_win_path=False):\n pub_key = GetPublicKey(filename, from_file_path, is_win_path=is_win_path)\n pub_key_hash = hashlib.sha256(pub_key).digest()\n return HexTo256(pub_key_hash)\n\ndef GetCRXAppID(filename, from_file_path=False, is_win_path=False):\n pub_key = GetPublicKey(filename, from_file_path, is_win_path=is_win_path)\n pub_key_hash = hashlib.sha256(pub_key).digest()\n # AppID is the MPDecimal of only the first 128 bits of the hash.\n return HexToMPDecimal(pub_key_hash[:128/8])\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/telemetry/telemetry/internal/backends/chrome/crx_id.py","file_name":"crx_id.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"4639395872","text":"\"\"\" MongoDB watcher using change streams. \"\"\"\nimport decimal\nimport json\nimport logging\nimport os\n\nimport boto3\nimport pymongo\nfrom bson.json_util import dumps\nfrom bson.objectid import ObjectId\nfrom pymongo import MongoClient\nfrom pymongo.collection import Collection\nfrom pymongo.database import Database\nfrom typing import AnyStr, Optional, Dict, Generator\n\nLOG = None\n\n\ndef watch_and_push() -> None:\n # Setup logging\n global LOG\n LOG = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')\n handler.setFormatter(formatter)\n LOG.addHandler(handler)\n LOG.setLevel(os.environ.get('LOG_LEVEL', 'INFO'))\n\n LOG.info('------------------------ STARTING WATCHER ------------------------')\n\n mongodb_uri = os.environ['MONGODB_URI']\n mongodb_username = os.environ['MONGODB_USERNAME']\n mongodb_password = os.environ['MONGODB_PASSWORD']\n mongodb_database = os.environ['MONGODB_DATABASE']\n mongodb_collection = os.environ['MONGODB_COLLECTION']\n out_kinesis_stream = os.environ['OUT_KINESIS_STREAM']\n kinesis_put_retries = int(os.environ.get('KINESIS_PUT_RETRIES', '3'))\n dynamodb_table_name = os.environ.get('DYNAMODB_TABLE_NAME', None)\n\n watcher = Watcher(\n uri=mongodb_uri,\n username=mongodb_username,\n password=mongodb_password,\n db=mongodb_database,\n collection=mongodb_collection,\n dynamodb_table_name=dynamodb_table_name\n )\n\n # Confirm we can talk to MongoDB before starting threads (excepts on auth failure)\n LOG.info(watcher.mongodb_client.server_info())\n\n # Create publisher\n publisher = Publisher(mongodb_collection)\n\n for d_doc in watcher.watch():\n try:\n publisher.publish(d_doc, out_kinesis_stream, kinesis_put_retries)\n except:\n LOG.exception('Failed to publish record: ')\n break\n # ------ Mark the doc successful at the end ------ #\n watcher.mark(d_doc)\n\n watcher.close()\n LOG.info('------------------------ STOPPING WATCHER ------------------------')\n\n\nclass Watcher(object):\n \"\"\"\n Watcher uses MongoDB change stream to watch for changes in MongoDB collection.\n \"\"\"\n\n def __init__(self, uri: AnyStr, username: AnyStr, password: AnyStr,\n db: AnyStr, collection: AnyStr, dynamodb_table_name: Optional[AnyStr] = None) -> None:\n self._uri = uri\n self._username = username\n self._password = password\n self._db = db\n self._collection = collection\n self._mongodb_client = None\n self._ddb = None\n self._dynamodb_table_name = dynamodb_table_name\n if dynamodb_table_name:\n self._ddb = boto3.resource('dynamodb', region_name=os.environ['AWS_DEFAULT_REGION'])\n else:\n self._ddb = None\n\n @property\n def mongodb_client(self) -> MongoClient:\n if self._mongodb_client is None:\n self._mongodb_client = pymongo.MongoClient(\n self._uri,\n username=self._username,\n password=self._password\n )\n return self._mongodb_client\n\n @property\n def db(self) -> Database:\n return self.mongodb_client.get_database(self._db)\n\n @property\n def collection(self) -> Collection:\n return self.db.get_collection(self._collection)\n\n @property\n def resume_token(self) -> Optional[AnyStr]:\n if self._ddb:\n d_key = {'collectionName': '{db}.{c}'.format(db=self._db, c=self._collection)}\n d_res = self._ddb.Table(self._dynamodb_table_name).get_item(Key=d_key)\n if 'Item' in d_res:\n d_item = json.loads(json.dumps(d_res['Item'], cls=DecimalEncoder))\n LOG.debug(\"get_item for key: %s in table '%s' returned attributes : %s\", d_key, self._dynamodb_table_name, d_item)\n return d_item['_id']\n return None\n\n def watch(self) -> Generator[Dict, None, None]:\n try:\n with self.collection.watch(full_document='updateLookup', resume_after=self.resume_token) as stream:\n for change in stream:\n yield change\n except pymongo.errors.PyMongoError:\n # The ChangeStream encountered an unrecoverable error or the\n # resume attempt failed to recreate the cursor.\n LOG.exception('Error while watching collection: ')\n\n def mark(self, d_doc: Dict) -> None:\n if self._ddb:\n d_key = {'collectionName': '{db}.{c}'.format(db=self._db, c=self._collection)}\n d_res = self._ddb.Table(self._dynamodb_table_name).update_item(\n Key=d_key,\n UpdateExpression='SET #id=:id',\n ExpressionAttributeValues={':id': d_doc['_id']},\n ExpressionAttributeNames={'#id': '_id'}, # Required to create a key name starting with underscore\n ReturnValues='UPDATED_NEW'\n )\n LOG.debug(\"update_item for key: %s in table '%s' successfully updated attributes: %s\",\n d_key, self._dynamodb_table_name, d_res['Attributes'])\n\n def close(self) -> None:\n self.mongodb_client.close()\n\n\nclass Publisher(object):\n \"\"\"\n Publisher writes raw records to Kinesis stream.\n \"\"\"\n\n def __init__(self, collection: AnyStr) -> None:\n self.client = boto3.client('kinesis')\n self._coll = collection\n\n def publish(self, d_record: Dict, kinesis_stream: AnyStr, max_retry_count: int) -> None:\n retry_count = max_retry_count\n while retry_count > 0:\n res = None\n str_record = dumps(d_record)\n try:\n res = self.client.put_record(StreamName=kinesis_stream,\n Data=str_record,\n PartitionKey='1')\n except Exception as e:\n LOG.warning('Failed to put record to kinesis stream %s, ERROR: %s', kinesis_stream, e)\n retry_count -= 1\n if res and res['SequenceNumber']:\n LOG.info('(Processed) coll:%s id:%s seq:%s',\n self._coll, self._objectid_to_str(d_record['documentKey']['_id']), res['SequenceNumber'])\n LOG.debug('%s', str_record)\n return res['SequenceNumber']\n\n # If control reaches here, put_record() has exhausted all the retries. Raise exception.\n raise Exception('Kinesis put_record failed even after retires')\n\n @staticmethod\n def _objectid_to_str(oid) -> AnyStr:\n return str(oid) if isinstance(oid, ObjectId) else oid\n\n\n# Helper class to convert a DynamoDB item to JSON.\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n if o % 1 > 0:\n return float(o)\n else:\n return int(o)\n return super(DecimalEncoder, self).default(o)\n\n\nif __name__ == '__main__':\n watch_and_push()\n","repo_name":"d66pak/mongodb-change-stream","sub_path":"mongo_watcher.py","file_name":"mongo_watcher.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"5642163313","text":"'''\nGiven an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.\n\nInput:\nThe first line of input contains an integer T denoting the number of test cases. Then T test cases follow. \nEach test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum.\nThe second line of each test case contains N space separated integers denoting the array elements.\n\nOutput:\nFor each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.\n'''\nstring = \"135 101 170 125 79 159 163 65 106 146 82 28 162 92 196 143 28 37 192 5 103 154 93 183 22 117 119 96 48 127 172 139 70 113 68 100 36 95 104 12 123 134\"\n\narr = [int(x) for x in string.split()]\ns = 468\n# print(len(arr))\nprint(arr[36])\n\n\ndef subarray(s, arr):\n sum = arr[0]\n i = 0\n j = 1\n # Loop through the fast pointer so as to end the loop once the length of array is reached.\n while j <= len(arr):\n # If sum is greater the s then subtract the starting value\n while sum > s:\n sum = sum - arr[i]\n i += 1\n print(\"Sum greater: sum: \"+str(sum)+\" i: \"+str(i) + \" j: \"+str(j))\n # Return if values are same\n if sum == s:\n return str(i+1) + \" \" + str(j)\n # Sum up all the values in the list\n if j < len(arr):\n sum = sum + arr[j]\n print(\"Summing up the values. Sum: \"+str(sum))\n j += 1\n return -1\n\n\nres = subarray(s, arr)\nprint(res)\n# testcases = int(input())\n# for i in range(0, testcases):\n# inp = [int(x) for x in input().split()]\n# arr = [int(x) for x in input().split()]\n# res = subarray(inp[1], arr)\n# print(res)\n","repo_name":"Ravi-Rsankar/cracking-interview-challenges","sub_path":"company-wise/google/Subarray_with_given_sum.py","file_name":"Subarray_with_given_sum.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41094840765","text":"import requests\nimport csv\nimport os\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nfrom google.cloud import texttospeech\nfrom google.oauth2 import service_account\n\n# 言語ごとの設定変数\nLANGUAGE_CODE = \"zh\"\nTTS_LANGUAGE_CODE = \"cmn-CN\"\nTTS_NAME = \"cmn-CN-Wavenet-C\"\nTTS_SSML_GENDER = texttospeech.SsmlVoiceGender.MALE\n\nload_dotenv(verbose=True)\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\nTOKEN = os.environ.get(\"LingQ_API_KEY\")\nAPI_URL = f'https://www.lingq.com/api/v2/{LANGUAGE_CODE}/cards/'\nAPI_HEADER = {'Authorization':f'token {TOKEN}'}\n\nCREDENTIAL_PATH = os.environ.get(\"TTS_CREDENTIAL_PATH\")\nANKI_AUDIO_DIR = os.environ.get(\"ANKI_AUDIO_DIR\")\n\ndef tts(client, text, filename, voice, audio_config): \n audio_path = join(ANKI_AUDIO_DIR, filename)\n if os.path.exists(audio_path):\n print(f\"{filename} exists\")\n return\n\n input_text = texttospeech.SynthesisInput(text=text)\n \n response = client.synthesize_speech(request={\"input\": input_text, \"voice\": voice, \"audio_config\": audio_config})\n\n with open(audio_path, 'wb') as out:\n out.write(response.audio_content)\n print(f'Audio content written to file {filename}')\n\ndef main():\n # TTS の設定\n credentials = service_account.Credentials.from_service_account_file(CREDENTIAL_PATH)\n client = texttospeech.TextToSpeechClient(credentials=credentials)\n voice = texttospeech.VoiceSelectionParams(\n language_code=TTS_LANGUAGE_CODE,\n name=TTS_NAME,\n ssml_gender=TTS_SSML_GENDER ,\n )\n audio_config = texttospeech.AudioConfig(\n audio_encoding=texttospeech.AudioEncoding.MP3\n )\n\n r = requests.get(API_URL, headers=API_HEADER).json()\n results = r[\"results\"]\n\n words = []\n\n for result in results:\n word = result[\"hints\"][0]\n text = word[\"term\"]\n replaced_text = text.replace('.', '')\n filename = f'lingq_{LANGUAGE_CODE}_{replaced_text}.mp3'\n\n tts(client, text, filename, voice, audio_config)\n # 言語ごとの設定 id, term, pinyin, japanese, phrase, audio\n pinyin = \" \".join(result[\"transliteration\"])\n words.append([word[\"id\"], text, pinyin, word[\"text\"], result[\"fragment\"], f\"[sound:{filename}]\"])\n\n with open(f'../csv/LingQ {LANGUAGE_CODE}.csv', 'w') as f:\n writer = csv.writer(f)\n writer.writerows(words)\n\nif __name__ == '__main__':\n main()\n","repo_name":"tomoino/LingQ2Anki","sub_path":"src/lingq_zh.py","file_name":"lingq_zh.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24897872040","text":"'''\nGiven an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number.\nExamples :\n\nInput: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33\nOuptut: Sum found between indexes 2 and 4\nExplanation: Sum of elements between indices\n2 and 4 is 20 + 3 + 10 = 33\n\nInput: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7\nOuptut: Sum found between indexes 1 and 4\nExplanation: Sum of elements between indices\n1 and 4 is 4 + 0 + 0 + 3 = 7\n\nInput: arr[] = {1, 4}, sum = 0\nOutput: No subarray found\nExplanation: There is no subarray with 0 sum\n'''\n\ndef findsubArray(a, s):\n n = len(a)\n minlen = n + 1\n \n for i in range(0, n):\n currSum = a[i]\n if currSum > s:\n return 1\n for j in range(i+1, n):\n currSum += a[j]\n print(currSum)\n if currSum > s and (j - i + 1) < minlen:\n minlen = (j - i + 1)\n print(minlen)\n return minlen\n\nif __name__ == \"__main__\":\n a = [1, 4, 20, 3, 10, 5]\n s = 33\n print(findsubArray(a, s))\n","repo_name":"mgokani/pythonPractise","sub_path":"findsubArray.py","file_name":"findsubArray.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17351951288","text":"# Michael Hofbauer ~ hofbauer@uab.edu\n\n# Let X_1,..., X_n ~ N(0,1) and Y_1,...,Y_n ~ Cauchy.\n# We plot f_X(n) = \\bar{X_n} f_Y(n) = \\bar{Y_n},\n# where f_X(n), f_Y(n) are the sample means,\n# to illustrate that f_X(n) converges to 0,\n# but due to the thick tails of the Cauchy distribution,\n# f_Y(n) diverges (i.e. Cauchy distribution has infinite moments \n# and therefore does not satisfy the preassumptions for the LLN).\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import cauchy, norm\n\nnormal_sample_mean_list = []\ncauchy_sample_mean_list = []\n\ndef plot_sm(n,r):\n ticks_raw = np.linspace(1, n, num = r)\n ticks_n = [int(np.ceil(x)) for x in ticks_raw]\n for j in ticks_n:\n std_normals = norm.rvs(size = j)\n cauchy_sample = cauchy.rvs(size = j)\n normal_sample_mean_list.append((1/j)*np.sum(std_normals))\n cauchy_sample_mean_list.append((1/j)*np.sum(cauchy_sample))\n # Begin with plot\n plt.figure(figsize = (18,15))\n plt.title('Comparision of normal N(0,1) and Cauchy distributed sample mean sequences', fontsize = 22)\n plt.plot(ticks_n, normal_sample_mean_list, marker = 'p', color = 'b', label = 'Normal sample mean')\n plt.plot(ticks_n, cauchy_sample_mean_list, '^r', label = 'Cauchy sample mean')\n plt.xlabel('Sample size', fontsize = 22)\n plt.ylabel('Sample mean values', fontsize = 22)\n # plt.xlim(0,30)\n plt.grid(True)\n plt.legend(loc = 'best', fontsize = 'xx-large')\n plt.show()\n","repo_name":"tsiflakos/probability-and-statistics","sub_path":"Cauchy_distr_lln.py","file_name":"Cauchy_distr_lln.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9596675820","text":"from pathlib import Path\nimport sys\nparent = Path(__file__).parents\npath_root = parent[1]\nsys.path.append(str(path_root))\nfrom argparse import Namespace\nimport logging\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport torchvision.transforms.functional as TF\nfrom torch import optim\nfrom torch.utils.data import DataLoader, random_split\nfrom tqdm import tqdm\nimport yaml\n\nimport wandb\nfrom models.preproccess.evaluate import evaluate\nfrom models.preproccess.unet import UNet\nfrom models.preproccess.utils.data_loading import BasicDataset, CarvanaDataset\nfrom models.preproccess.utils.dice_score import dice_loss\n\n\ndef train_model(\n model,\n device,\n epochs: int = 5,\n batch_size: int = 1,\n learning_rate: float = 1e-5,\n val_percent: float = 0.1,\n save_checkpoint: bool = True,\n img_scale: float = 0.5,\n amp: bool = False,\n weight_decay: float = 1e-8,\n momentum: float = 0.999,\n gradient_clipping: float = 1.0,\n):\n # 1. Create dataset\n try:\n dataset = CarvanaDataset(dir_img, dir_mask, img_scale)\n except (AssertionError, RuntimeError, IndexError):\n dataset = BasicDataset(dir_img, dir_mask, img_scale)\n\n # 2. Split into train / validation partitions\n n_val = int(len(dataset) * val_percent)\n n_train = len(dataset) - n_val\n train_set, val_set = random_split(dataset, [n_train, n_val], generator=torch.Generator().manual_seed(0))\n\n # 3. Create data loaders\n loader_args = dict(batch_size=batch_size, num_workers=os.cpu_count(), pin_memory=True)\n train_loader = DataLoader(train_set, shuffle=True, **loader_args)\n val_loader = DataLoader(val_set, shuffle=False, drop_last=True, **loader_args)\n\n # (Initialize logging)\n experiment = wandb.init(project='U-Net', resume='allow', anonymous='must')\n experiment.config.update(\n dict(epochs=epochs, batch_size=batch_size, learning_rate=learning_rate,\n val_percent=val_percent, save_checkpoint=save_checkpoint, img_scale=img_scale, amp=amp)\n )\n\n logging.info(f'''Starting training:\n Epochs: {epochs}\n Batch size: {batch_size}\n Learning rate: {learning_rate}\n Training size: {n_train}\n Validation size: {n_val}\n Checkpoints: {save_checkpoint}\n Device: {device.type}\n Images scaling: {img_scale}\n Mixed Precision: {amp}\n ''')\n\n # 4. Set up the optimizer, the loss, the learning rate scheduler and the loss scaling for AMP\n optimizer = optim.RMSprop(model.parameters(),\n lr=learning_rate, weight_decay=weight_decay, momentum=momentum, foreach=True)\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'max', patience=5) # goal: maximize Dice score\n grad_scaler = torch.cuda.amp.GradScaler(enabled=amp)\n criterion = nn.CrossEntropyLoss() if model.n_classes > 1 else nn.BCEWithLogitsLoss()\n global_step = 0\n\n # 5. Begin training\n for epoch in range(1, epochs + 1):\n model.train()\n epoch_loss = 0\n with tqdm(total=n_train, desc=f'Epoch {epoch}/{epochs}', unit='img') as pbar:\n for batch in train_loader:\n images, true_masks = batch['image'], batch['mask']\n\n assert images.shape[1] == model.n_channels, \\\n f'Network has been defined with {model.n_channels} input channels, ' \\\n f'but loaded images have {images.shape[1]} channels. Please check that ' \\\n 'the images are loaded correctly.'\n\n images = images.to(device=device, dtype=torch.float32, memory_format=torch.channels_last)\n true_masks = true_masks.to(device=device, dtype=torch.long)\n\n with torch.autocast(device.type if device.type != 'mps' else 'cpu', enabled=amp):\n masks_pred = model(images)\n if model.n_classes == 1:\n loss = criterion(masks_pred.squeeze(1), true_masks.float())\n loss += dice_loss(F.sigmoid(masks_pred.squeeze(1)), true_masks.float(), multiclass=False)\n else:\n loss = criterion(masks_pred, true_masks)\n loss += dice_loss(\n F.softmax(masks_pred, dim=1).float(),\n F.one_hot(true_masks, model.n_classes).permute(0, 3, 1, 2).float(),\n multiclass=True\n )\n\n optimizer.zero_grad(set_to_none=True)\n grad_scaler.scale(loss).backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), gradient_clipping)\n grad_scaler.step(optimizer)\n grad_scaler.update()\n\n pbar.update(images.shape[0])\n global_step += 1\n epoch_loss += loss.item()\n experiment.log({\n 'train loss': loss.item(),\n 'step': global_step,\n 'epoch': epoch\n })\n pbar.set_postfix(**{'loss (batch)': loss.item()})\n\n # Evaluation round\n division_step = (n_train // (5 * batch_size))\n if division_step > 0:\n if global_step % division_step == 0:\n histograms = {}\n for tag, value in model.named_parameters():\n tag = tag.replace('/', '.')\n if not (torch.isinf(value) | torch.isnan(value)).any():\n histograms['Weights/' + tag] = wandb.Histogram(value.data.cpu())\n if not (torch.isinf(value.grad) | torch.isnan(value.grad)).any():\n histograms['Gradients/' + tag] = wandb.Histogram(value.grad.data.cpu())\n\n val_score = evaluate(model, val_loader, device, amp)\n scheduler.step(val_score)\n\n logging.info('Validation Dice score: {}'.format(val_score))\n try:\n experiment.log({\n 'learning rate': optimizer.param_groups[0]['lr'],\n 'validation Dice': val_score,\n 'images': wandb.Image(images[0].cpu()),\n 'masks': {\n 'true': wandb.Image(true_masks[0].float().cpu()),\n 'pred': wandb.Image(masks_pred.argmax(dim=1)[0].float().cpu()),\n },\n 'step': global_step,\n 'epoch': epoch,\n **histograms\n })\n except:\n pass\n\n if save_checkpoint:\n Path(dir_checkpoint).mkdir(parents=True, exist_ok=True)\n state_dict = model.state_dict()\n state_dict['mask_values'] = dataset.mask_values\n torch.save(state_dict, str(dir_checkpoint / 'checkpoint_epoch{}.pth'.format(epoch)))\n logging.info(f'Checkpoint {epoch} saved!')\n\n\ndef setParameters(params):\n data = {\n \"epochs\": int(params[\"epochs\"]),\n \"batch_size\": int(params[\"batch_size\"]),\n \"lr\": float(params[\"lr\"]),\n \"load\": params[\"load\"] if os.path.isfile(params[\"load\"]) else False,\n \"scale\": 0.5,\n \"val\": 10.0,\n \"amp\": True,\n \"bilinear\": False,\n \"classes\": 2\n }\n \n return data\n\n\nif __name__ == '__main__':\n # parameters inititalization\n # param_yaml_file = sys.argv[1]\n param_yaml_file = \"/home/naserwin/hamze/fingerprint_segment_restore/params.yaml\"\n params = yaml.safe_load(open(param_yaml_file))[\"preproccess_train\"]\n data = setParameters(params)\n args = Namespace(**data)\n dir_img = params[\"dir_img\"]\n dir_mask = params[\"dir_mask\"]\n assert args.epochs > 0, f\"epochs should be upper than 0 ut is {args.epochs}\"\n assert args.batch_size > 0, f\"batch_size should be upper than 0 ut is {args.batch_size}\"\n assert os.path.isdir(dir_img), f\"dir_img value is '{dir_img}' which is not valid directory path\"\n assert os.path.isdir(dir_mask), f\"dir_mask value is '{dir_mask}' which is not valid directory path\"\n\n dir_img = Path(dir_img)\n dir_mask = Path(dir_mask)\n dir_checkpoint = Path(os.path.join(parent[1].as_posix(), \"checkpoints\", \"preproccess\"))\n os.makedirs(dir_checkpoint.as_posix(), exist_ok=True)\n # logger inititializer\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(f'Using device {device}')\n\n # Change here to adapt to your data\n # n_channels=3 for RGB images\n # n_classes is the number of probabilities you want to get per pixel\n \n if args.load:\n model = UNet(n_channels=3, n_classes=args.classes, bilinear=args.bilinear)\n else:\n print(\"==========LOADING PRETRAINED UNET MODEL==========\")\n model = torch.hub.load('milesial/Pytorch-UNet', 'unet_carvana', pretrained=True, scale=0.5)\n \n # model.load_state_dict(state_loaded)\n model = model.to(memory_format=torch.channels_last)\n logging.info(f'Network:\\n'\n f'\\t{model.n_channels} input channels\\n'\n f'\\t{model.n_classes} output channels (classes)\\n'\n f'\\t{\"Bilinear\" if model.bilinear else \"Transposed conv\"} upscaling')\n\n if args.load:\n state_dict = torch.load(args.load, map_location=device)\n del state_dict['mask_values']\n model.load_state_dict(state_dict)\n logging.info(f'Model loaded from {args.load}')\n\n model.to(device=device)\n try:\n train_model(\n model=model,\n epochs=args.epochs,\n batch_size=args.batch_size,\n learning_rate=args.lr,\n device=device,\n img_scale=args.scale,\n val_percent=args.val / 100,\n amp=args.amp\n )\n except:\n # except torch.cuda.OutOfMemoryError:\n logging.error('Detected OutOfMemoryError! '\n 'Enabling checkpointing to reduce memory usage, but this slows down training. '\n 'Consider enabling AMP (--amp) for fast and memory efficient training')\n torch.cuda.empty_cache()\n model.use_checkpointing()\n train_model(\n model=model,\n epochs=args.epochs,\n batch_size=args.batch_size,\n learning_rate=args.lr,\n device=device,\n img_scale=args.scale,\n val_percent=args.val / 100,\n amp=args.amp\n )\n\"\"\"\ndvc stage add -n preproccess_train \\\n -d data/fingerprint \\\n -d src/preprocess_train.py \\\n -p preproccess_train.dir_img,preproccess_train.dir_mask,preproccess_train.load,preproccess_train.epochs,preproccess_train.batch_size \\\n -o checkpoints/preproccess \\\n python src/preprocess_train.py params.yaml\n Run summary:\nwandb: epoch 50\nwandb: learning rate 0.0\nwandb: step 89950\nwandb: train loss 0.47034\nwandb: validation Dice 0.38721\nwandb: \n\"\"\"\n","repo_name":"Hamzeluie/fingerprint_segment_restore","sub_path":"src/preprocess_train.py","file_name":"preprocess_train.py","file_ext":"py","file_size_in_byte":11435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24541336747","text":"import datetime\r\nimport pyttsx3\r\nimport win32api\r\nimport requests\r\nfrom bs4 import BeautifulSoup as bs, Tag\r\n\r\ndef print_and_speak(text):\r\n\ttts = pyttsx3.init()\r\n\ttts.setProperty('voice', tts.getProperty('voices')[2].id)\r\n\r\n\tprint(text)\r\n\ttts.say(text)\r\n\r\n\ttts.runAndWait()\r\n\ttts.stop()\r\n\r\ndef get_articles(date, opinions_only=False):\r\n\tprint_and_speak(f\"\\nFetching articles from TheHindu newspaper published on {date.strftime('%d %B, %Y')}\")\r\n\r\n\turl = f\"https://www.thehindu.com/archive/print/{date.strftime('%Y/%m/%d')}/\"\r\n\thtml = requests.get(url).text\r\n\tsoup = bs(html, \"html.parser\")\r\n\r\n\r\n\tarticles = soup.select_one('h2#opinion').parent.parent.parent.select('div.section-container ul.archive-list li a') if opinions_only else soup.select(\"ul.archive-list li a\")\r\n\r\n\tprint_and_speak(f'\\nFound {len(articles)} articles...')\r\n\tfor ind, op in enumerate(articles):\r\n\t\t#print_and_speak(f'[{ind+1}] {op.text}')\r\n\t\tprint(f'[{ind+1}] {op.text}')\r\n\r\n\treturn articles\r\n\r\ndef get_choice(articles):\r\n\tprint_and_speak('\\nSelect the article to read')\r\n\tchoice = int(input('[number] : '))\r\n\r\n\tif choice in range(1, len(articles)+1):\r\n\t\treturn articles[choice-1]['href']\r\n\telse:\r\n\t\tprint_and_speak('\\nSorry! Invalid choice.')\r\n\t\tget_choice(articles)\r\n\r\ndef read_article(url):\r\n\tprint_and_speak(\"\\nFetching the article...\")\r\n\r\n\tarticle_html = requests.get(url).text\r\n\tsoup = bs(article_html, \"html.parser\")\r\n\r\n\tarticle = soup.select_one('div.article')\r\n\tintro = article.select_one('h2.intro')\r\n\r\n\ttitle_text = article.select_one('h1.title').text\r\n\tauthors_text = ', '.join([auth.text.strip() for auth in article.select('div.author-container a.auth-nm.lnk')]).replace('\\n', '')\r\n\tintro_text = intro.text if intro is not None else ''\r\n\tarticle_paras = article.select('div[id^=content-body-] p')\r\n\r\n\tprint_and_speak(title_text)\r\n\tprint_and_speak(\"Written by \"+authors_text if len(authors_text.strip()) > 0 else '')\r\n\tprint_and_speak(intro_text)\r\n\r\n\tfor para in article_paras:\r\n\t\tprint_and_speak(u'\\n'.join(para.findAll(text=True)) if isinstance(para, Tag) else para)\r\n\r\ndef start_reader():\r\n\tprint_and_speak('This program will read you articles from TheHindu.com')\r\n\r\n\tprint_and_speak('\\nGet opinions only? (otherwise full newspaper)')\r\n\top_only = True if input(\"[y|n] : \").lower() == 'y' else False\r\n\r\n\tprint_and_speak('\\nEnter the date of publication')\r\n\r\n\ttry:\r\n\t\tdate = datetime.datetime.strptime(input(\"[DD/MM/YYYY] : \"), \"%d/%m/%Y\").date()\r\n\texcept:\r\n\t\tprint_and_speak(f'\\nERROR : Invalid Date!')\r\n\telse:\r\n\t\tread_article(get_choice(get_articles(date, op_only)))\r\n\tfinally:\r\n\t\tprint_and_speak('\\nProgram complete! Press any key to exit...')\r\n\t\tx = input()\r\n\r\n# ___________________________________________________\r\n\r\nif __name__ == \"__main__\":\r\n\tstart_reader()","repo_name":"shivck13/the_hindu_article_reader","sub_path":"read-arcticles.py","file_name":"read-arcticles.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11347532344","text":"from django.urls import path\nfrom dash_app import views\n\n\nurlpatterns = [\n path(\"dashboard\", views.dashboard),\n path(\"login\", views.login),\n path(\"register\", views.register),\n path(\"quote\", views.quote),\n path(\"\", views.index),\n]\n","repo_name":"strammel1/stock-dashboard","sub_path":"dash_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36336063985","text":"from datetime import datetime, timedelta\nimport humanize\nimport logging\nfrom openerp import models, fields, api, _\nfrom openerp import sql_db\nimport requests\nfrom urlparse import urljoin\n\n\nlogger = logging.getLogger(__name__)\n\nDISPOSITION_TYPES = (\n ('NO ANSWER', 'No answer'),\n ('FAILED', 'Failed'),\n ('BUSY', 'Busy'),\n ('ANSWERED', 'Answered'),\n ('CONGESTION', 'Congestion'),\n)\n\n\n\nclass Cdr(models.Model):\n _name = 'asterisk.cdr'\n _description = 'Call Detail Record'\n _order = 'started desc'\n\n accountcode = fields.Char(size=20, string='Account code', index=True)\n src = fields.Char(size=80, string='Src', index=True)\n dst = fields.Char(size=80, string='Dst', index=True)\n dcontext = fields.Char(size=80, string='Dcontext')\n clid = fields.Char(size=80, string='Clid', index=True)\n channel = fields.Char(size=80, string='Channel', index=True)\n dstchannel = fields.Char(size=80, string='Dst channel', index=True)\n lastapp = fields.Char(size=80, string='Last app')\n lastdata = fields.Char(size=80, string='Last data')\n started = fields.Datetime(index=True, oldname='start')\n answered = fields.Datetime(index=True, oldname='answer')\n ended = fields.Datetime(index=True, oldname='end')\n duration = fields.Integer(string='Duration', index=True)\n billsec = fields.Integer(string='Billsec', index=True)\n disposition = fields.Char(size=45, string='Disposition', index=True)\n amaflags = fields.Integer(string='AMA flags')\n userfield = fields.Char(size=255, string='Userfield')\n uniqueid = fields.Char(size=150, string='Uniqueid', index=True)\n peeraccount = fields.Char(size=20, string='Peer account', index=True)\n linkedid = fields.Char(size=150, string='Linked id')\n sequence = fields.Integer(string='Sequence')\n recording_filename = fields.Char()\n recording_widget = fields.Char(compute='_get_recording_widget')\n recording_download = fields.Char(compute='_get_recording_download')\n # QoS\n ssrc = fields.Char(string='Our SSRC')\n themssrc = fields.Char(string='Other SSRC')\n lp = fields.Integer(string='Local Lost Packets')\n rlp = fields.Integer(string='Remote Lost Packets')\n rxjitter = fields.Float(string='RX Jitter')\n txjitter = fields.Float(string='TX Jitter')\n rxcount = fields.Integer(string='RX Count')\n txcount = fields.Integer(string='TX Count')\n rtt = fields.Float(string='Round Trip Time')\n\n\n @api.model\n def grant_asterisk_access(self):\n cr = sql_db.db_connect(self.env.cr.dbname).cursor()\n sql = \"GRANT ALL on asterisk_cdr to asterisk\"\n cr.execute(sql)\n sql = \"GRANT ALL on asterisk_cdr_id_seq to asterisk\"\n cr.execute(sql)\n cr.commit()\n cr.close()\n\n\n @api.multi\n def _get_recording_widget(self):\n for rec in self:\n rec.recording_widget = '