diff --git "a/6340.jsonl" "b/6340.jsonl" new file mode 100644--- /dev/null +++ "b/6340.jsonl" @@ -0,0 +1,717 @@ +{"seq_id":"5268390411","text":"n=input()\nn=int(n)\narr = [0]*10\ncheck = [1]*10\n\ndef rPrint():\n for i in range (1,n+1):\n print(arr[i], end='')\n print()\n\ndef rHandle(i):\n for j in range(1,n+1):\n if(check[j]==1):\n arr[i]=j\n if(i==n): rPrint()\n else:\n check[j]=0\n rHandle(i+1)\n check[j]=1\n\nrHandle(1)\n","repo_name":"autumn16/Project","sub_path":"quaylui1.py","file_name":"quaylui1.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24788273186","text":"from __future__ import annotations\n\nimport math\nimport string\n\nimport pytest\n\nimport ibis\nimport ibis.common.exceptions as exc\nfrom ibis import udf, util\nfrom ibis.backends.trino.tests.conftest import (\n TRINO_HOST,\n TRINO_PASS,\n TRINO_PORT,\n TRINO_USER,\n)\n\n\n@pytest.fixture\ndef tmp_name(con):\n name = ibis.util.gen_name(\"test_trino\")\n yield name\n con.drop_table(name, force=True)\n\n\ndef test_table_properties(tmp_name):\n con = ibis.trino.connect(database=\"hive\", schema=\"default\")\n schema = ibis.schema(dict(a=\"int\"))\n t = con.create_table(\n tmp_name,\n schema=schema,\n properties={\n \"format\": \"ORC\",\n \"bucketed_by\": [\"a\"],\n \"bucket_count\": 42,\n \"extra_properties\": {\n \"any\": \"property\",\n \"you\": \"want\",\n },\n },\n )\n assert t.schema() == schema\n with con.begin() as c:\n ddl = c.exec_driver_sql(f\"SHOW CREATE TABLE {tmp_name}\").scalar()\n assert \"ORC\" in ddl\n assert \"bucketed_by\" in ddl\n\n\ndef test_hive_table_overwrite(tmp_name):\n con = ibis.trino.connect(database=\"hive\", schema=\"default\")\n schema = ibis.schema(dict(a=\"int\"))\n\n t = con.create_table(tmp_name, schema=schema)\n assert tmp_name in con.list_tables()\n assert t.schema() == schema\n\n t = con.create_table(tmp_name, schema=schema, overwrite=True)\n assert tmp_name in con.list_tables()\n assert t.schema() == schema\n\n\ndef test_list_catalogs(con):\n assert {\"hive\", \"memory\", \"system\", \"tpch\", \"tpcds\"}.issubset(con.list_databases())\n\n\ndef test_list_schemas(con):\n assert {\"information_schema\", \"sf1\"}.issubset(con.list_schemas(database=\"tpch\"))\n\n\n@pytest.mark.parametrize((\"source\", \"expected\"), [(None, \"ibis\"), (\"foo\", \"foo\")])\ndef test_con_source(source, expected):\n con = ibis.trino.connect(\n user=TRINO_USER,\n host=TRINO_HOST,\n port=TRINO_PORT,\n password=TRINO_PASS,\n database=\"hive\",\n schema=\"default\",\n source=source,\n )\n assert con.con.url.query[\"source\"] == expected\n\n\n@pytest.mark.parametrize(\n (\"schema\", \"table\"),\n [\n # tables known to exist\n (\"system.metadata\", \"table_comments\"),\n (\"tpcds.sf1\", \"store\"),\n (\"tpch.sf1\", \"nation\"),\n ],\n)\ndef test_cross_schema_table_access(con, schema, table):\n t = con.table(table, schema=schema)\n assert t.count().execute()\n\n\ndef test_builtin_scalar_udf(con, snapshot):\n @udf.scalar.builtin\n def bar(x: float, width: int) -> str:\n \"\"\"Render a single bar of length `width`, with `x` percent filled.\"\"\"\n\n expr = bar(0.25, 40)\n result = con.execute(expr)\n snapshot.assert_match(result, \"result.txt\")\n\n\ndef test_builtin_agg_udf(con):\n @udf.agg.builtin\n def geometric_mean(x) -> float:\n \"\"\"Geometric mean of a series of numbers.\"\"\"\n\n t = con.table(\"diamonds\")\n expr = t.agg(n=t.count(), geomean=geometric_mean(t.price))\n result_n, result = expr.execute().squeeze().tolist()\n\n with con.begin() as c:\n expected_n, expected = c.exec_driver_sql(\n \"SELECT COUNT(*), GEOMETRIC_MEAN(price) FROM diamonds\"\n ).one()\n\n # check the count\n assert result_n > 0\n assert expected_n > 0\n assert result_n == expected_n\n\n # check the value\n assert result is not None\n assert expected is not None\n assert math.isfinite(result)\n assert result == expected\n\n\ndef test_create_table_timestamp():\n con = ibis.trino.connect(database=\"memory\", schema=\"default\")\n schema = ibis.schema(\n dict(zip(string.ascii_letters, map(\"timestamp({:d})\".format, range(10))))\n )\n table = util.gen_name(\"trino_temp_table\")\n t = con.create_table(table, schema=schema)\n try:\n rows = con.raw_sql(f\"DESCRIBE {table}\").fetchall()\n result = ibis.schema((name, typ) for name, typ, *_ in rows)\n assert result == schema\n assert result == t.schema()\n finally:\n con.drop_table(table)\n assert table not in con.list_tables()\n\n\ndef test_table_access_from_connection_without_catalog_or_schema():\n con = ibis.trino.connect()\n # can't use the `system` catalog to test here, because the trino sqlalchemy\n # dialect defaults to `system` if no catalog is passed, so it wouldn't be a\n # useful test\n assert con.current_database != \"tpch\"\n assert con.current_schema is None\n\n t = con.table(\"region\", schema=\"tpch.sf1\")\n\n assert con.current_database != \"tpch\"\n assert con.current_schema is None\n\n assert t.count().execute()\n\n\ndef test_table_access_database_schema(con):\n t = con.table(\"region\", schema=\"sf1\", database=\"tpch\")\n assert t.count().execute()\n\n with pytest.raises(exc.IbisError, match=\"Cannot specify both\"):\n con.table(\"region\", schema=\"tpch.sf1\", database=\"tpch\")\n\n with pytest.raises(exc.IbisError, match=\"Cannot specify both\"):\n con.table(\"region\", schema=\"tpch.sf1\", database=\"system\")\n","repo_name":"ibis-project/ibis","sub_path":"ibis/backends/trino/tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","stars":3246,"dataset":"github-code","pt":"52"} +{"seq_id":"20578404360","text":"from datetime import datetime\nfrom io import TextIOWrapper\nimport pandas as pd\nfrom const import COLUMNS\n\n# датадок|во|nдок|коррсчет|коррсчет.1|бик|счет|дебет|кредит|инн|названиеконтрагента|основаниедокумента\n# COLUMNS = [\"clientID\", \"clientBIC\", \"clientBank\", \"clientAcc\", \"clientTaxCode\", \"clientName\", \"stmtDate\", \"stmtFrom\", \"stmtTo\",\n# \"openBalance\", \"totalDebet\", \"totalCredit\", \"closingBalance\",\n# \"entryDate\", \"cpBIC\", \"cpBank\", \"cpAcc\", \"cpTaxCode\", \"cpName\", \"Debet\", \"Credit\", \"Comment\",\n# \"__header\", \"__hdrclientBIC\", \"__hdrclientAcc\", \"__hdrclientTaxCode\",\n# \"__hdropenBalance\",\n# \"toIgnore\", \"filename\", 'processdate']\n\n\ndef BankStatement_61_process(\n header: pd.DataFrame,\n data: pd.DataFrame,\n footer: pd.DataFrame,\n inname: str,\n clientid: str,\n params: dict,\n sheet: str,\n logf: TextIOWrapper,\n) -> pd.DataFrame:\n df = pd.DataFrame(columns=COLUMNS)\n\n df[\"entryDate\"] = data[\"датадок\"]\n df[\"cpBIC\"] = data[\"бик\"]\n df[\"cpAcc\"] = data[\"счет\"]\n df[\"cpTaxCode\"] = data[\"инн\"]\n df[\"cpName\"] = data[\"названиеконтрагента\"]\n\n df[\"Debet\"] = data[\"дебет\"]\n df[\"Credit\"] = data[\"кредит\"]\n df[\"Comment\"] = data[\"основаниедокумента\"]\n\n return df\n","repo_name":"gbvolkov/statements_recognition","sub_path":"BankStatement_61_process.py","file_name":"BankStatement_61_process.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74477380005","text":"import asyncio\n \n@asyncio.coroutine\ndef just_print_messages():\n \"\"\"\n This method prints a message and then sleeps for three seconds\n \"\"\"\n while True:\n print('Just printing a new message every three seconds')\n yield from asyncio.sleep(3)\n \ndef main():\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(just_print_messages())\n finally:\n loop.close()\n \nif __name__ == '__main__':\n main()\n","repo_name":"dgquintas/my-code-samples","sub_path":"python/asyncio/print_message.py","file_name":"print_message.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"6331185290","text":"# coding: utf-8\n\n\"\"\"\n Apteco API\n\n An API to allow access to Apteco Marketing Suite resources # noqa: E501\n\n The version of the OpenAPI document: v2\n Contact: support@apteco.com\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom apteco_api.configuration import Configuration\n\n\nclass Breakpoint(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'breakpoint': 'str',\n 'x': 'int',\n 'y': 'int',\n 'size': 'Size',\n 'notes_alignment': 'NotesAlignment'\n }\n\n attribute_map = {\n 'breakpoint': 'breakpoint',\n 'x': 'x',\n 'y': 'y',\n 'size': 'size',\n 'notes_alignment': 'notesAlignment'\n }\n\n def __init__(self, breakpoint=None, x=None, y=None, size=None, notes_alignment=None, local_vars_configuration=None): # noqa: E501\n \"\"\"Breakpoint - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._breakpoint = None\n self._x = None\n self._y = None\n self._size = None\n self._notes_alignment = None\n self.discriminator = None\n\n self.breakpoint = breakpoint\n self.x = x\n self.y = y\n self.size = size\n self.notes_alignment = notes_alignment\n\n @property\n def breakpoint(self):\n \"\"\"Gets the breakpoint of this Breakpoint. # noqa: E501\n\n The target breakpoint size # noqa: E501\n\n :return: The breakpoint of this Breakpoint. # noqa: E501\n :rtype: str\n \"\"\"\n return self._breakpoint\n\n @breakpoint.setter\n def breakpoint(self, breakpoint):\n \"\"\"Sets the breakpoint of this Breakpoint.\n\n The target breakpoint size # noqa: E501\n\n :param breakpoint: The breakpoint of this Breakpoint. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and breakpoint is None: # noqa: E501\n raise ValueError(\"Invalid value for `breakpoint`, must not be `None`\") # noqa: E501\n allowed_values = [\"xs\", \"sm\", \"md\", \"lg\", \"xl\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and breakpoint not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `breakpoint` ({0}), must be one of {1}\" # noqa: E501\n .format(breakpoint, allowed_values)\n )\n\n self._breakpoint = breakpoint\n\n @property\n def x(self):\n \"\"\"Gets the x of this Breakpoint. # noqa: E501\n\n The target breakpoint x location # noqa: E501\n\n :return: The x of this Breakpoint. # noqa: E501\n :rtype: int\n \"\"\"\n return self._x\n\n @x.setter\n def x(self, x):\n \"\"\"Sets the x of this Breakpoint.\n\n The target breakpoint x location # noqa: E501\n\n :param x: The x of this Breakpoint. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and x is None: # noqa: E501\n raise ValueError(\"Invalid value for `x`, must not be `None`\") # noqa: E501\n\n self._x = x\n\n @property\n def y(self):\n \"\"\"Gets the y of this Breakpoint. # noqa: E501\n\n The target breakpoint y location # noqa: E501\n\n :return: The y of this Breakpoint. # noqa: E501\n :rtype: int\n \"\"\"\n return self._y\n\n @y.setter\n def y(self, y):\n \"\"\"Sets the y of this Breakpoint.\n\n The target breakpoint y location # noqa: E501\n\n :param y: The y of this Breakpoint. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and y is None: # noqa: E501\n raise ValueError(\"Invalid value for `y`, must not be `None`\") # noqa: E501\n\n self._y = y\n\n @property\n def size(self):\n \"\"\"Gets the size of this Breakpoint. # noqa: E501\n\n\n :return: The size of this Breakpoint. # noqa: E501\n :rtype: Size\n \"\"\"\n return self._size\n\n @size.setter\n def size(self, size):\n \"\"\"Sets the size of this Breakpoint.\n\n\n :param size: The size of this Breakpoint. # noqa: E501\n :type: Size\n \"\"\"\n if self.local_vars_configuration.client_side_validation and size is None: # noqa: E501\n raise ValueError(\"Invalid value for `size`, must not be `None`\") # noqa: E501\n\n self._size = size\n\n @property\n def notes_alignment(self):\n \"\"\"Gets the notes_alignment of this Breakpoint. # noqa: E501\n\n\n :return: The notes_alignment of this Breakpoint. # noqa: E501\n :rtype: NotesAlignment\n \"\"\"\n return self._notes_alignment\n\n @notes_alignment.setter\n def notes_alignment(self, notes_alignment):\n \"\"\"Sets the notes_alignment of this Breakpoint.\n\n\n :param notes_alignment: The notes_alignment of this Breakpoint. # noqa: E501\n :type: NotesAlignment\n \"\"\"\n if self.local_vars_configuration.client_side_validation and notes_alignment is None: # noqa: E501\n raise ValueError(\"Invalid value for `notes_alignment`, must not be `None`\") # noqa: E501\n\n self._notes_alignment = notes_alignment\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Breakpoint):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, Breakpoint):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"Apteco/apteco-api","sub_path":"pkg/apteco_api/models/breakpoint.py","file_name":"breakpoint.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18008647362","text":"\"\"\"Tests for normalize_address.\"\"\"\nimport re\n\nfrom transformations.normalize_address import normalize_address_wrapper\n\n\ndef test_normalize_address_wrapper():\n \"\"\"Test normalize address custom.\"\"\"\n address_with_address2 = '8405 PERSHING DRIVE UNIT 500'\n expected_dict = {\n 'address_line_1': '8405 PERSHING DR',\n 'address_line_2': 'UNIT 500',\n 'city': None,\n 'state': None,\n 'postal_code': None,\n }\n assert normalize_address_wrapper(address_with_address2) == expected_dict\n\n address_without_address2 = '1 LMU DRIVE'\n expected_dict = {\n 'address_line_1': '1 LMU DR',\n 'address_line_2': None,\n 'city': None,\n 'state': None,\n 'postal_code': None,\n }\n assert normalize_address_wrapper(address_without_address2) == expected_dict\n\n address_with_none = None\n expected_dict = {\n 'address_line_1': None,\n 'address_line_2': None,\n 'city': None,\n 'state': None,\n 'postal_code': None,\n }\n assert normalize_address_wrapper(address_with_none) == expected_dict\n\n address_with_error = '1 WORLD TRADE CENTER FLOOR 24'\n expected_dict = {\n 'address_line_1': '1 WORLD TRADE CENTER FLOOR 24',\n 'address_line_2': None,\n 'city': None,\n 'state': None,\n 'postal_code': None,\n }\n\n assert normalize_address_wrapper(address_with_error) == expected_dict\n\n address_with_exempt = re.sub('^0+', '', '08405 PERSHING DRIVE UNIT 500')\n expected_dict = {\n 'address_line_1': '8405 PERSHING DR',\n 'address_line_2': 'UNIT 500',\n 'city': None,\n 'state': None,\n 'postal_code': None,\n }\n assert normalize_address_wrapper(address_with_exempt) == expected_dict\n","repo_name":"hackforla/data-science","sub_path":"LAANE/tests/test_normalize_address.py","file_name":"test_normalize_address.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"} +{"seq_id":"74509067363","text":"#오름차순/\nn = int(input())\narr = [0]+list(map(int,input().split()))\n\ndef heapify(arr,i,n):\n largest,left, right = i,i*2, i*2+1\n\n if left <= n and arr[largest] < arr[left]:\n largest = left\n\n if right <= n and arr[largest] < arr[right]:\n largest = right\n\n if largest != i:\n tmp = arr[i]\n arr[i] = arr[largest]\n arr[largest] = tmp\n heapify(arr,largest,n)\n\n\ndef heap_sort(arr,n):\n #maxheap 만들어주고\n for i in range(n//2,0,-1):\n heapify(arr,i,n)\n\n for i in range(n,1,-1):\n tmp = arr[i] #swap\n arr[i] = arr[1]\n arr[1] = tmp\n heapify(arr,1,i-1)\n\nheap_sort(arr,n)\nprint(*arr[1:])\n","repo_name":"young0264/hellopycharm","sub_path":"알고리즘/정렬/HeapSort.py","file_name":"HeapSort.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74118554084","text":"\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport traceback\nimport gspread\nimport sys\n\n\nclass Google:\n\n def __init__(self, gdrive_key):\n\n self.gdrive_key = gdrive_key\n self.authorize_key(self.gdrive_key)\n\n def authorize_key(self, key):\n\n if hasattr(self, 'gc'):\n del self.gc\n\n scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(key, scope)\n\n self.gc = gspread.authorize(credentials)\n\n def select_worksheet(self, worksheet_name=None, worksheet_number=None, all_worksheets=False):\n\n if worksheet_name:\n self.worksheet = self.sheet.worksheet(worksheet_name)\n\n if worksheet_number:\n self.worksheet = self.sheet.get_worksheet(worksheet_number)\n\n if all_worksheets:\n self.worksheet = self.sheet.worksheets()\n\n if not worksheet_name and worksheet_number and all_worksheets:\n\n print('You have not provided a worksheet selection parameter.')\n sys.exit(666)\n\n return self.worksheet\n\n def retrieve_worksheet(self, worksheet_name=None, worksheet_number=None):\n\n retry_count = 0\n while retry_count <=5:\n try:\n worksheet = self.select_worksheet(worksheet_name, worksheet_number).get_all_records()\n return worksheet\n\n except gspread.exceptions.APIError as e:\n\n if 'Request had invalid authentication credentials' in str(e):\n\n self.authorize_key(self.gdrive_key)\n\n else:\n raise gspread.exceptions.APIError(traceback.format_exc())\n\n raise gspread.exceptions.APIError(f'Retries maxed for obtaining spreadsheet with name \"{self.sheet.title}\" and worksheet \"{worksheet_name if worksheet_name else worksheet_number}\".')\n\n def create_worksheet(self, title, row_num, col_num):\n\n resp = self.sheet.add_worksheet(title, row_num, col_num)\n\n return resp\n\n def update_cell(self, cell, new_value, worksheet_name=None, worksheet_number=None):\n\n sheet = self.select_worksheet(worksheet_name, worksheet_number)\n sheet.update_acell(cell, new_value)\n\n def get_cell_value(self, cell, worksheet_name=None, worksheet_number=None):\n\n sheet = self.select_worksheet(worksheet_name, worksheet_number)\n value = sheet.acell(cell).value\n\n return value\n\n def get_row_or_column(self, index, row=False, column=False, worksheet_name=None, worksheet_number=None):\n\n sheet = self.select_worksheet(worksheet_name, worksheet_number)\n\n if row:\n values = sheet.row_values(index)\n\n elif column:\n values = sheet.col_values(index)\n\n else:\n print('You have not specified whether you want to select a row/column.')\n sys.exit(666)\n\n return values\n\n def share_spreadsheet(self, email):\n\n self.sheet.share(email, perm_type='user', role='writer')\n\n def add_target_spreadsheet(self, spreadsheet_url):\n\n self.spreadsheet_url = spreadsheet_url\n self.sheet = self.gc.open_by_url(spreadsheet_url)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n","repo_name":"danamlewis/open-aps-streaming","sub_path":"open-humans-etl/utils/google_api.py","file_name":"google_api.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20162944616","text":"from flask import Flask, render_template, url_for, redirect, request , Response , send_file, abort, flash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import UserMixin, login_user, LoginManager, login_required, logout_user , current_user\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, SubmitField\nfrom wtforms.validators import InputRequired, Length, ValidationError\nfrom flask_bcrypt import Bcrypt\nfrom werkzeug.utils import secure_filename\n# from flask_admin import Admin\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\nfrom io import BytesIO\nimport sqlite3\nfrom base64 import b64encode\nimport os\n# from db import intialDb,db\n\n#References \n# Cloud Deployment Link : https://ssshare.azurewebsites.net/ \n# https://flask-admin.readthedocs.io/en/latest/introduction/\n# https://danidee10.github.io/2016/11/14/flask-by-example-7.html\n# https://www.youtube.com/watch?v=71EU8gnZqZQ&ab_channel=ArpanNeupane\n# https://github.com/arpanneupane19/Python-Flask-Authentication-Tutorial\n# https://tutorial101.blogspot.com/2021/04/python-flask-upload-and-display-image.html\n# https://stackoverflow.com/questions/44926465/upload-image-in-flask\n# https://flask-bcrypt.readthedocs.io/en/1.0.1/\n# https://www.rithmschool.com/courses/intermediate-flask/hashing-passwords-flask\n# https://stackoverflow.com/questions/31358578/display-image-stored-as-binary-blob-in-template\n# https://www.youtube.com/watch?v=I9BBGulrOmo&t=369s&ab_channel=Cairocoders\n# https://www.youtube.com/watch?v=JDKmLB_HpTQ&t=258s&ab_channel=DawoodIddris\n# https://www.youtube.com/watch?v=UIJKdCIEXUQ&t=1794s&ab_channel=CoreySchafer\n# https://www.youtube.com/watch?v=gHfUt-N2_Jw&t=637s&ab_channel=CodeJana\n# https://stackoverflow.com/questions/37031399/change-model-representation-in-flask-admin-without-modifying-model\n# https://flask-admin.readthedocs.io/en/latest/introduction/#getting-started\n# https://ckraczkowsky.medium.com/building-a-secure-admin-interface-with-flask-admin-and-flask-security-13ae81faa05\n# https://stackoverflow.com/questions/20431572/how-to-reference-a-modelview-in-flask-admin\n# https://www.youtube.com/watch?v=iIhAfX4iek0&t=661s&ab_channel=TechWithTim\n# https://www.youtube.com/watch?v=FEyNt9iFPGc&ab_channel=PrettyPrinted\n# https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/\n# https://github.com/Alexmod/Flask-User-and-Flask-admin\n# https://www.youtube.com/watch?v=pPSZpCVRbvQ\n# https://stackoverflow.com/questions/11017466/flask-to-return-image-stored-in-database\n\n# instantiating the flask name\napp = Flask(__name__)\nUPLOAD_FOLDER = 'static/uploads/'\ndb = SQLAlchemy(app)\nbcrypt = Bcrypt(app)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'\napp.config['SECRET_KEY'] = 'city6528'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n#Intiating an Admin View\nadmin = Admin(app)\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'login'\n#Allowed Extensions\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n#reference used : https://tutorial101.blogspot.com/2021/04/python-flask-upload-and-display-image.html\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n# USER MODEL DATABASE with id , username and passowrd\nclass User(db.Model, UserMixin):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(20), nullable=False, unique=True)\n password = db.Column(db.String(80), nullable=False)\n is_admin = db.Column(db.Boolean,default = False)\n\n# class UserGroup(db.Model, UserMixin):\n# id = db.Column(db.Integer)\n# username = db.Column(db.String(20),nullable=False, unique=True)\n# is_text = db.Column(db.Boolean,default = False)\n\n\n#overiding model view controller to check if the user is an admin or not\n# reference used : https://flask-admin.readthedocs.io/en/latest/introduction/\nclass Controller(ModelView):\n def is_accessible(self):\n print(\"hello\",current_user.is_admin)\n if current_user.is_admin == True:\n print(\"hello world\",current_user.is_authenticated)\n return current_user.is_authenticated\n else:\n return abort(404)\n\n def not_auth(self):\n return \"Access Denied\"\n\n#Adding admin view to the website and creating a session\nadmin.add_view(Controller(User,db.session))\n\n#Register Form Model with column name, username,passoword\nclass RegisterForm(FlaskForm):\n name = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={\"placeholder\": \"Please enter your name\"})\n username = StringField(validators=[InputRequired(), Length(min=4, max=20)], render_kw={\"placeholder\": \"Please enter your username(email Id)\",\"pattern\":\"[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$\"})\n password = PasswordField(validators=[InputRequired(), Length(min=8, max=20)], render_kw={\"placeholder\": \"Plese Type in your password\"})\n submit = SubmitField('Register')\n # https://github.com/arpanneupane19/Python-Flask-Authentication-Tutorial\n def check_user(self, username):\n existing_user = User.query.filter_by(username=username.data).first()\n if existing_user:\n ValidationError('That username already exists. Please choose a different one.')\n return redirect(url_for('login'))\n\n#loginform model with column username password and submit\nclass LoginForm(FlaskForm):\n username = StringField(validators=[InputRequired(), Length(min=4, max=30)], render_kw={\"placeholder\": \"Username\" })\n password = PasswordField(validators=[InputRequired(), Length(min=8, max=20)], render_kw={\"placeholder\": \"Password\"})\n submit = SubmitField('Login')\n\n# class imageUpload(db.Model):\n# id = db.Column(db.Integer, primary_key=True)\n# img = db.Column(db.Text, unique=True, nullable=False)\n# name = db.Column(db.Text, nullable=False)\n# mimetype = db.Column(db.Text, nullable=False)\n\n#Upload model with id , filename and data , data is stored as blob data\nclass Upload(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n filename = db.Column(db.String(50))\n data = db.Column(db.LargeBinary)\n\n# home route \n@app.route('/')\ndef home():\n return render_template('home.html')\n\n#login endpoint\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n if request.method == 'POST':\n\n # form2 = RegisterForm()\n uname=form.username.data\n print(uname)\n if form.validate_on_submit():\n #quering the user model to get the user details from the database\n user = User.query.filter_by(username=form.username.data).first()\n if user:\n #check password \n if bcrypt.check_password_hash(user.password, form.password.data):\n login_user(user)\n #return render_template('dashboard.html',name = uname)\n return redirect(url_for('dashboard'))\n else:\n #jsonify({'internal server error': 'return back to login page'}), HTTP_500_INTERNAL_SERVER_ERROR\n flash(\"Wrong Username or password Try Again!!!!\")\n return render_template('login.html', form=form)\n\n \n\n@app.route('/dashboard', methods=['GET', 'POST'])\n@login_required\ndef dashboard():\n return render_template('dashboard.html')\n\n@app.route('/imguploadPage',methods = ['GET','POST'])\n@login_required\ndef imguploadPage():\n return render_template('imguploadPage.html')\n\n@app.route('/imageupload',methods = ['POST','GET'])\n@login_required\ndef imageupload():\n if request.method == 'GET':\n return render_template('imguploadPage.html')\n if request.method == 'POST':\n # print(\"hellow world\")\n image = request.files['image']\n print(image)\n if not image: \n return 'Please enter a valid Photo'\n # file_name = secure_filename(image.filename)\n # mimetype = image.mimetype\n # if not file_name or not mimetype:\n # return \"Bad file type\"\n #checking the file type only if the file type is valid it will be uploaded into the database\n if image and allowed_file(image.filename):\n upload = Upload(filename=image.filename, data=image.read())\n db.session.add(upload)\n db.session.commit()\n return redirect(url_for('imageGroup'))\n else :\n return abort(404)\n # flash(\"Upload a Image file only\")\n # return redirect(url_for('imageupload'))\n # return render_template('imgdownload.html')\n\n\n@app.route('/createGroup',methods = ['POST','GET'])\n@login_required\ndef createGroup():\n if request.method == 'GET':\n return render_template('createGroup.html')\n if request.method == 'POST':\n # fetching all the details of the group\n groupName = request.form[\"groupName\"]\n groupDesc = request.form['groupDesc']\n userName = current_user.username\n print(\"groupName\",groupName)\n print(\"group Desc\",groupDesc)\n print(\"userName\",userName)\n conn= sqlite3.connect(\"database.db\")\n c = conn.cursor()\n c.execute(\"INSERT into grp (groupName,groupDesc,userName) VALUES (?,?,?)\",[groupName,groupDesc,userName])\n conn.commit()\n return render_template('dashboard.html')\n\n@app.route('/viewGroup',methods =['POST','GET'])\n@login_required\ndef viewGroup():\n grp = []\n if request.method == 'GET':\n conn = sqlite3.connect(\"database.db\")\n c = conn.cursor()\n userName = current_user.username\n c.execute(\"select * from grp where (userName) = (?)\" ,[userName])\n rs = c.fetchall()\n print(\"hellp\",rs)\n if rs == []:\n flash('Please create a group or join group')\n return render_template('dashboard.html') \n else :\n for i in rs:\n groupName=i[0]\n groupDesc=i[1]\n username = i[2]\n print(groupName,groupDesc,username)\n grp.append([groupName,groupDesc,username])\n return render_template('showGroup.html',groupDetails = grp)\n if request.method == 'POST' :\n selectGroup = request.form[\"groupSelected\"]\n print(selectGroup)\n if selectGroup == 'Image':\n return redirect(url_for('imageGroup'))\n else :\n flash('Please select image to enter into image group other groups will be implemented later')\n return render_template('dashboard.html')\n\n@app.route('/joinGroup',methods = ['POST','GET'])\n@login_required\ndef joinGroup():\n grpDetails = []\n if request.method == 'GET':\n conn = sqlite3.connect(\"database.db\")\n c = conn.cursor()\n userName = current_user.username\n c.execute(\"select * from grp\")\n rs = c.fetchall()\n for i in rs: \n groupName=i[0]\n groupDesc=i[1]\n username = i[2]\n print(groupName,groupDesc,username)\n grpDetails.append([groupName,groupDesc,username])\n print(\"groups available\",grpDetails)\n return render_template('joingroup.html',grp = grpDetails)\n if request.method == 'POST':\n groupName = request.form[\"groupSelected\"]\n conn = sqlite3.connect(\"database.db\")\n c = conn.cursor()\n user_name = current_user.username\n c.execute(\"INSERT into grp (groupName,userName) VALUES (?,?)\",[groupName,user_name])\n conn.commit()\n return render_template('dashboard.html')\n\n\n@app.route('/download', methods=[\"GET\", \"POST\"])\n@login_required\ndef download():\n imageDetails = []\n if request.method == 'GET':\n conn = sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"select id,filename from upload\")\n rs = cursor.fetchall()\n for i in rs : \n id=i[0]\n filename=i[1]\n print(id,filename)\n imageDetails.append([id,filename])\n return render_template('downloadImage.html',imgDetails = imageDetails)\n if request.method == \"POST\":\n imageSelected = request.form['imageSelected']\n print(imageSelected)\n conn = sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"select * from upload where id = ?\",[imageSelected])\n rs = cursor.fetchall()\n print(rs)\n print(\"IN DATABASE FUNCTION \")\n # c = cursor.execute(\"\"\" SELECT * FROM upload where id \"\"\")\n # rs = c.fetchall()\n # print(rs)\n for i in rs:\n id=i[0]\n filename=i[1]\n data = i[2]\n print(id)\n conn.commit()\n # https://stackoverflow.com/questions/11017466/flask-to-return-image-stored-in-database\n return send_file(BytesIO(data), attachment_filename=filename, as_attachment=True)\n\n\n return render_template(\"viewImg.html\",rs=rs)\n\n@app.route('/viewImg/',methods=['GET','POST'])\n@login_required\ndef viewImg(id):\n # obj = Upload.query(Upload.id == id).fetch(1)[0]\n conn= sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n print(id)\n cursor.execute(\"SELECT * FROM upload WHERE id = ?\",(id,))\n for x in cursor.fetchall():\n filename=x[1]\n data=x[2]\n break\n # https://stackoverflow.com/questions/31358578/display-image-stored-as-binary-blob-in-template\n\n image = b64encode(data).decode(\"utf-8\")\n return render_template(\"viewImg.html\", image=image)\n\n\n# @app.route('/')\n# def viewimage(id):\n# img = Upload.query.filter_by(id=id).first()\n# if not img:\n# return 'Img Not Found!', 404\n\n# return Response(img.filename)\n\n@app.route('/logout', methods=['GET', 'POST'])\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('login'))\n\n\n@ app.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm()\n if request.method == 'POST':\n if form.validate_on_submit():\n #hashing the password to store it in database\n hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')\n new_user = User(username=form.username.data, password=hashed_password)\n # adding user to database as well as creating a session to that user. \n db.session.add(new_user)\n db.session.commit()\n return redirect(url_for('login'))\n else:\n flash('Please enter username as a email and check minimum length of password is 8')\n return render_template('register.html', form=form)\n\n# Done for reference not required to run the project \n# @app.route('/imageUpload',methods = ['POST','GET'])\n# @login_required\n# def imageUpload():\n# if request.method == 'GET':\n# return render_template('imageUpload.html')\n# if request.method == 'POST':\n# if 'file' not in request.files:\n# flash('No file part')\n# return render_template('imageUpload.html')\n# file = request.files['file']\n# if file.filename == '':\n# flash('No image selected for uploading')\n# return render_template('imageUpload.html')\n# if file and allowed_file(file.filename):\n# print(\"hello world\",file)\n# filename = secure_filename(file.filename)\n# file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n# flash('Image successfully uploaded')\n# print(\"file uploaded successfully\")\n# return render_template('imageUpload.html')\n# else:\n# flash('Accepted image types are - png, jpg, jpeg, gif')\n# # return redirect(request.url)\n\n@app.route('/imageGroup',methods = ['POST','GET'])\n@login_required\ndef imageGroup():\n users = []\n if request.method == 'GET':\n conn= sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"select username from grp\")\n rs = cursor.fetchall()\n for x in rs:\n username=x[0]\n users.append(username)\n print(\"list of users in the group\",users)\n return render_template('ImageGroup.html',user = users)\n if request.method == \"POST\":\n pass\n\n@app.route('/showimage',methods = ['POST','GET'])\n@login_required\ndef showimage():\n imageDetails = []\n if request.method == 'GET':\n conn = sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"select id,filename from upload\")\n rs = cursor.fetchall()\n print(rs)\n for i in rs : \n id=i[0]\n filename=i[1]\n print(id,filename)\n imageDetails.append([id,filename])\n return render_template('showimage.html',imgDetails = imageDetails)\n if request.method == 'POST':\n imageSelected = request.form['imageSelected']\n print(imageSelected)\n conn = sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"select data from upload where id = ?\",[imageSelected])\n rs = cursor.fetchall()\n for i in rs:\n imageData = i[0]\n break\n image = b64encode(imageData).decode(\"utf-8\")\n return render_template(\"viewImg.html\", image=image)\n\n\n@app.route('/deleteImg',methods = ['POST','GET'])\n@login_required\ndef deleteImg():\n imageDetails = []\n if request.method == 'GET':\n conn = sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"select id,filename from upload\")\n rs = cursor.fetchall()\n print(rs)\n for i in rs : \n id=i[0]\n filename=i[1]\n print(id,filename)\n imageDetails.append([id,filename])\n return render_template('deleteImg.html',imgDetails = imageDetails)\n if request.method == 'POST':\n imageSelected = request.form['imageSelected']\n print(imageSelected)\n conn = sqlite3.connect(\"database.db\")\n cursor = conn.cursor()\n cursor.execute(\"delete from upload where id = ?\",[imageSelected])\n conn.commit()\n \n # rs = cursor.fetchall()\n # for i in rs:\n # imageData = i[0]\n # break\n # image = b64encode(imageData).decode(\"utf-8\")\n # return render_template(\"imageGroup.html\",user=imageDetails)\n return redirect(url_for('imageGroup'))\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"sujitrajt/ssshare","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":18513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30754889647","text":"from django.shortcuts import render\nfrom searches import tfidf, boolean, transformer, fasttext_search, elastic_search, classification, clustering\nfrom searches.preprocess import all_foods\nfrom searches.spell_correction import correct_spelling\n\n\ndef index(request, approach, text):\n text = ' '.join(correct_spelling(word) for word in text.split())\n if approach == \"boolean\":\n rank = boolean.search_boolian_text(text)\n elif approach == \"tf-idf\":\n rank = tfidf.search_td_text(text)\n elif approach == \"transformer\":\n rank = transformer.search_transformer_text(text)\n elif approach == \"fast-text\":\n rank = fasttext_search.search_fasttext_text(text)\n elif approach == \"elastic-search\":\n rank = elastic_search.search_text(text)\n elif approach == \"clustering\":\n rank = clustering.get_cluster(text)\n elif approach == \"classification\":\n rank = classification.classify_transformer_text(text)\n else:\n raise ValueError\n\n if approach != \"classification\":\n names = [all_foods[id]['name'] for score, id in rank]\n ids = [id for score, id in rank]\n else:\n names = [rank]\n ids = [0]\n\n return render(request, \"show_result.html\", {\"data\": zip(names, ids), \"search\": text, \"approach\": approach})\n","repo_name":"IR1401-Spring-Final-Projects/cookbook1401-6_9","sub_path":"ShowResults/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26259541964","text":"def solve():\n left_side = {'c': 3, 'm': 3}\n right_side = {'c': 0, 'm': 0}\n boat_left = True\n cache = {\n f'left: {left_side}, right: {right_side}, boat_left: {boat_left}': True}\n moves = [f'left: {left_side}, right: {right_side}, boat_left: {boat_left}']\n\n def invariant_violation(left_side, right_side):\n if left_side['m'] and left_side['c'] > left_side['m']:\n return True\n if right_side['m'] and right_side['c'] > right_side['m']:\n return True\n\n return False\n\n boat_fills = [[1, 0], [2, 0], [1, 1], [0, 1], [0, 2]]\n\n iterat = 0\n\n def helper(left_side, right_side, boat_left):\n nonlocal iterat\n iterat += 1\n\n # exit condition\n if right_side['c'] == 3 and right_side['m'] == 3:\n return moves\n\n # determine legal actions based on current state\n # try each action and call helper recursively\n # if success, return result, else continue\n boat_m = left_side['m'] if boat_left else right_side['m']\n boat_c = left_side['c'] if boat_left else right_side['c']\n\n for send_m, send_c in [pair for pair in boat_fills if pair[0] <= boat_m and pair[1] <= boat_c]:\n\n left_possibility = left_side.copy()\n right_possibility = right_side.copy()\n if boat_left:\n source = left_possibility\n target = right_possibility\n else:\n source = right_possibility\n target = left_possibility\n\n source['m'] -= send_m\n target['m'] += send_m\n source['c'] -= send_c\n target['c'] += send_c\n new_boat_left = not boat_left\n\n id = f'left: {left_possibility}, right: {right_possibility}, boat_left: {new_boat_left}'\n try:\n cache[id]\n except KeyError:\n cache[id] = True\n moves.append(id)\n\n if not invariant_violation(\n left_possibility, right_possibility\n ) and helper(\n left_possibility, right_possibility, new_boat_left\n ):\n return moves\n else:\n moves.pop()\n\n return False\n\n return helper(left_side, right_side, boat_left)\n\n\nresult = solve()\nfor line in result:\n print(line)\n","repo_name":"kamry-bowman/python_problem_solving_dsalgos","sub_path":"chapter_4/cannibals.py","file_name":"cannibals.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73208297444","text":"from data_structures_and_algorithms.data_structures.hashtable.hashtable import HashTable\n\ndef test_add_key_info():\n table = HashTable()\n table.add('adding','Add key and value')\n assert table.map[table.hash('adding')].head.info == ('adding','Add key and value')\n\ndef test_get_info_and_key():\n table = HashTable()\n table.add('Fruit','Mango')\n assert table.map[table.hash('Fruit')].head.info[0] == 'Fruit'\n assert table.map[table.hash('Fruit')].head.info[1] == 'Mango'\n\ndef test_get_info_from_key():\n table = HashTable()\n table.add('contain','listen')\n assert table.get('contain') == 'listen'\n\ndef test_get_info_not_in_table():\n table = HashTable()\n assert table.get('test') == 'Not in the table'\n\ndef test_handle_collision():\n table = HashTable()\n table.add('left','the building')\n table.add('felt','excited')\n hashed_key = table.hash('left')\n assert table.map[hashed_key].head.info == ('left','the building')\n assert table.map[hashed_key].head.next.info == ('felt','excited')\n\ndef test_retrieve_info_with_collision():\n table = HashTable()\n table.add('left','the building')\n table.add('felt','excited')\n assert table.get('left') == 'the building'\n assert table.get('felt') == 'excited'\n","repo_name":"Basma23/data-structures-and-algorithms-python","sub_path":"tests/data_structures/test_hashtable.py","file_name":"test_hashtable.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1633296569","text":"import argparse\nimport os\nimport sys\n\nfrom eq_translations.entrypoints import handle_extract_template\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Extract translation template from json schema\"\n )\n\n parser.add_argument(\n \"SCHEMA_PATH\",\n help=\"The path to the source schema from which data will be extracted\",\n )\n\n parser.add_argument(\n \"OUTPUT_DIRECTORY\",\n help=\"The destination directory for the translation template\",\n )\n\n args = parser.parse_args()\n\n if not os.path.isdir(args.OUTPUT_DIRECTORY):\n print(\"Output directory does not exist\")\n sys.exit(2)\n\n handle_extract_template(args.SCHEMA_PATH, args.OUTPUT_DIRECTORY)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ONSdigital/eq-translations","sub_path":"eq_translations/cli/extract_template.py","file_name":"extract_template.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39814077881","text":"'''\n347. Top K Frequent Elements\nLink: https://leetcode.com/problems/top-k-frequent-elements/\n\nGiven a non-empty array of integers, return the k most frequent elements.\n\nExample 1:\nInput: nums = [1, 1, 1, 2, 2, 3], k = 2\nOutput: [1, 2]\n\nExample 2:\nInput: nums = [1], k = 1\nOutput: [1]\n'''\n\n\nimport heapq\n\n\ndef top_K_frequent(nums, k):\n freqs = {}\n n = len(nums)\n\n for num in nums:\n freqs[num] = freqs.get(num, 0) + 1\n\n bucket = [[] for _ in range(n + 1)]\n for key, val in freqs.items():\n bucket[val].append(key)\n\n res = []\n for i in range(n, -1, -1):\n res.extend(bucket[i])\n\n return res[:k]\n\n\nassert top_K_frequent([1, 1, 1, 2, 2, 3], 2) == [1, 2]\nassert top_K_frequent([1], 1) == [1]\n\n\ndef top_K_frequent_v2(nums, k):\n res, freqs = [], {}\n\n for num in nums:\n freqs[num] = freqs.get(num, 0) + 1\n\n freqs = [(-v, k) for k, v in freqs.items()]\n heapq.heapify(freqs)\n\n for _ in range(k):\n _, k = heapq.heappop(freqs)\n res.append(k)\n\n return res\n\n\nassert top_K_frequent_v2([1, 1, 1, 2, 2, 3], 2) == [1, 2]\nassert top_K_frequent_v2([1], 1) == [1]\n","repo_name":"ErickMwazonga/sifu","sub_path":"heaps/kth_frequent_elems.py","file_name":"kth_frequent_elems.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"27864584175","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\ndriver = webdriver.Firefox()\n\ndriver.get(\"http://www.seleniumhq.org\")\n\nelement_q_id = driver.find_element(By.ID, \"selenium_logo\")\nprint(f\"My element_q (id) is: \\n {element_q_id}\")\n\n# element_q_name = driver.find_element(By.NAME, \"Selenium IDE\")\n# print(f\"My element_q (name) is: \\n {element_q_name}\")\n\nelement_class = driver.find_element(By.CLASS_NAME, \"selenium-button\")\nprint(f\"My search by class element (class name) is: \\n {element_class}\")\n\ndriver.close()","repo_name":"Houston2812/python-selenium","sub_path":"chapter2/challenge1.py","file_name":"challenge1.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41226104695","text":"from PyQt5 import uic, QtWidgets\r\nimport mysql.connector\r\nfrom reportlab.pdfgen import canvas\r\n\r\nnumero_id = 0\r\n\r\nbanco = mysql.connector.connect(\r\n host='localhost', database='cadastro_teste', \r\n user='root', password='')\r\n\r\nif banco.is_connected():\r\n db_info = banco.get_server_info()\r\n print(\"Conectado ao servidor MySQL versão:\", db_info)\r\n cursor = banco.cursor()\r\n cursor.execute('select database();')\r\n linha = cursor.fetchone()\r\n print(\"Conectado ao banco de dados \", linha)\r\n \r\n\"\"\"\"\r\nif banco.is_connected():\r\n cursor.close()\r\n banco.close()\r\n print(\"Conexão ao MySQL foi encerrada\")\r\n\"\"\"\r\n\r\ndef salvar_dados_editados():\r\n #pega o numeor do id\r\n global numero_id\r\n \r\n # valor diigitado no campo de edicoes\r\n codigo = tela_editar.codigo_edit.text()\r\n descricao = tela_editar.produto_edit.text()\r\n preco = tela_editar.preco_edit.text()\r\n categoria = tela_editar.categoria_edit.text()\r\n \r\n # atualizar os dados no banco de dados\r\n cursor = banco.cursor()\r\n cursor.execute(\"UPDATE produtos SET codigo = '{}', descricao = '{}', preco = '{}', categoria = '{}' WHERE id = {}\" .format(codigo, descricao, preco, categoria, numero_id))\r\n banco.commit()\r\n \r\n #atualizar as janelas\r\n tela_editar.close()\r\n lista_produtos.close()\r\n listagem_produtos()\r\n \r\n \r\ndef editar_dados():\r\n global numero_id\r\n editar = lista_produtos.tableWidget.currentRow()\r\n \r\n cursor = banco.cursor()\r\n cursor.execute(\"SELECT id FROM produtos\")\r\n dados_lidos = cursor.fetchall()\r\n valor_id = dados_lidos[editar][0]\r\n cursor.execute(f\"SELECT * FROM produtos WHERE id={str(valor_id)}\")\r\n produto = cursor.fetchall()\r\n tela_editar.show()\r\n \r\n numero_id = valor_id\r\n \r\n tela_editar.id_edit.setText(str(produto[0][0]))\r\n tela_editar.codigo_edit.setText(str(produto[0][1]))\r\n tela_editar.produto_edit.setText(str(produto[0][2]))\r\n tela_editar.preco_edit.setText(str(produto[0][3]))\r\n tela_editar.categoria_edit.setText(str(produto[0][4]))\r\n \r\n \r\ndef excluir_dados(): # EXCLUIR DADOS\r\n excluir = lista_produtos.tableWidget.currentRow()\r\n lista_produtos.tableWidget.removeRow(excluir)\r\n \r\n cursor = banco.cursor()\r\n cursor.execute(\"SELECT id FROM produtos\")\r\n dados_lidos = cursor.fetchall()\r\n valor_id = dados_lidos[excluir][0]\r\n cursor.execute(f\"DELETE FROM produtos WHERE id= {str(valor_id)}\")\r\n banco.commit() # EXCLUIR NO BANCO DE DADOS\r\n \r\ndef gerar_pdf(): # GERADOR DO PDF\r\n cursor = banco.cursor()\r\n comando_SQL = \"SELECT * FROM produtos\"\r\n cursor.execute(comando_SQL)\r\n dados_lidos = cursor.fetchall()\r\n y = 0\r\n pdf = canvas.Canvas(\"cadastro_produtos.pdf\")\r\n pdf.setFont(\"Times-Bold\", 18)\r\n pdf.drawString(200,800, \"Produtos cadastrados:\")\r\n pdf.setFont(\"Times-Bold\", 13)\r\n \r\n pdf.drawString(10,750, \"ID\")\r\n pdf.drawString(110,750, \"Código\")\r\n pdf.drawString(210,750, \"Produto\")\r\n pdf.drawString(310,750, \"Preço\")\r\n pdf.drawString(410,750, \"Categoria\")\r\n \r\n for i in range(0, len(dados_lidos)):\r\n y = y + 50\r\n pdf.drawString(10,750 - y, str(dados_lidos[i][0]))\r\n pdf.drawString(110,750 - y, str(dados_lidos[i][1]))\r\n pdf.drawString(210,750 - y, str(dados_lidos[i][2]))\r\n pdf.drawString(310,750 - y, str(dados_lidos[i][3]))\r\n pdf.drawString(410,750 - y, str(dados_lidos[i][4]))\r\n\r\n pdf.save()\r\n print(\"PDF foi gerado com sucesso!\")\r\n \r\n \r\ndef listagem_produtos(): # SEGUNDA TELA (LISTA DE PRODUTOS CADASTRADOS)\r\n lista_produtos.show()\r\n \r\n # MOSTRAR LISTA DE PRODUTOS \r\n cursor = banco.cursor() \r\n comando_SQL = \"SELECT * FROM produtos\"\r\n cursor.execute(comando_SQL)\r\n dados_lidos = cursor.fetchall() \r\n \r\n lista_produtos.tableWidget.setRowCount(len(dados_lidos))\r\n lista_produtos.tableWidget.setColumnCount(5)\r\n \r\n for i in range(0, len(dados_lidos)): # FOR PARA MOSTAR OS DADOS LIDOS\r\n for j in range(0, 5):\r\n lista_produtos.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(dados_lidos[i][j])))\r\n \r\n \r\n \r\n \r\ndef funcao_principal():\r\n linha1 = cadastro.codigo_box.text()\r\n linha2 = cadastro.descricao_box.text()\r\n linha3 = cadastro.preco_box.text()\r\n categoria = ''\r\n \r\n if cadastro.informatica.isChecked():\r\n print(\"Categoria: Informática\")\r\n categoria = \"Informática\"\r\n \r\n elif cadastro.alimentos.isChecked():\r\n print(\"Categoria: Alimentos\")\r\n categoria = \"Alimento\"\r\n \r\n elif cadastro.eletronico.isChecked():\r\n print(\"Categoria: Eletrônico\")\r\n categoria = \"Eletrônico\"\r\n \r\n else:\r\n print(\"Nenhuma Categoria Selecionada\")\r\n categoria = \"Não Selecionada\"\r\n \r\n print(\"Código:\", linha1)\r\n print(\"Descrição:\", linha2)\r\n print(\"Preço:\", linha3)\r\n \r\n cursor = banco.cursor()\r\n comando_SQL = \"INSERT INTO produtos (codigo,descricao,preco,categoria) VALUES (%s,%s,%s,%s)\"\r\n dados = (str(linha1), str(linha2), str(linha3), categoria)\r\n cursor.execute(comando_SQL, dados)\r\n banco.commit()\r\n cadastro.codigo_box.setText(\"\") # LIMPAR CAMPO CODIGO\r\n cadastro.descricao_box.setText(\"\") # LIMPAR CAMPO DESCRICAO\r\n cadastro.preco_box.setText(\"\") # LIMPAR CAMPO PREÇO\r\n \r\napp = QtWidgets.QApplication([])\r\ncadastro = uic.loadUi(\"cadastro01.ui\")\r\nlista_produtos = uic.loadUi(\"lista_produtos.ui\")\r\ntela_editar = uic.loadUi(\"editar.ui\")\r\ncadastro.pushButton.clicked.connect(funcao_principal) # BOTAO SALVAR DADOS NA TABELA\r\ncadastro.pushButton_2.clicked.connect(listagem_produtos) # ABRIR TELA LISTA DE PRODUTOS\r\nlista_produtos.pdf_button.clicked.connect(gerar_pdf) # BOTAO GERADOR DE PDF\r\nlista_produtos.excluir_button.clicked.connect(excluir_dados) # BOTAO EXCLUIR DADOS DA TABELA\r\nlista_produtos.editar_button.clicked.connect(editar_dados) # BOTAO EDITAR DADOS DA TABELA\r\ntela_editar.salvar_edit.clicked.connect(salvar_dados_editados) # SALVAR OS DADOS QUE FORAM EDITADOS NA TELA EDICAO\r\n\r\ncadastro.show()\r\napp.exec()\r\n\r\n","repo_name":"brunagtmaia/sistema-de-gest-o-escolar-","sub_path":"controle.py","file_name":"controle.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17664303234","text":"import unittest\n\nimport numpy as np\nfrom AnyQt.QtCore import QItemSelectionModel\nfrom Orange.widgets.tests.base import WidgetTest\nfrom Orange.data import StringVariable, Domain\nfrom scipy.sparse import csr_matrix\n\nfrom orangecontrib.text.corpus import Corpus\nfrom orangecontrib.text.topics import Topic\nfrom orangecontrib.text.widgets.owwordcloud import OWWordCloud\n\n\nclass TestWordCloudWidget(WidgetTest):\n def setUp(self):\n self.widget = self.create_widget(OWWordCloud)\n self.corpus = Corpus.from_file('deerwester')\n\n self.topic = self.create_topic()\n\n def create_topic(self):\n words = [[f\"a{i}\"] for i in range(10)]\n weights = list(range(10))\n t = Topic.from_numpy(\n Domain([], metas=[\n StringVariable(\"Topic 1\")\n ]),\n X=np.empty((10, 0)),\n metas=np.array(words),\n W=weights #np.array(weights).reshape(-1, 1)\n )\n t.attributes[\"topic-method-name\"] = \"LsiModel\"\n return t\n\n def test_data(self):\n \"\"\"\n Just basic test.\n GH-244\n \"\"\"\n self.send_signal(self.widget.Inputs.corpus, self.corpus)\n self.send_signal(self.widget.Inputs.corpus, None)\n self.wait_until_finished()\n\n def test_empty_data(self):\n \"\"\"\n Widget crashes when receives zero length data.\n GH-244\n \"\"\"\n self.send_signal(self.widget.Inputs.corpus, self.corpus)\n self.send_signal(self.widget.Inputs.corpus, self.corpus[:0])\n self.wait_until_finished()\n\n def test_bow_features(self):\n \"\"\"\n When bag of words features are at the input word cloud must be made\n based on BOW weights.\n \"\"\"\n data = self.corpus[:3]\n data = data.extend_attributes(\n csr_matrix([[3, 2, 0], [0, 3, 6], [0, 1, 0]]),\n [\"Word1\", \"Word2\", \"Word3\"])\n for v in data.domain.attributes:\n v.attributes[\"bow-feature\"] = True\n\n self.send_signal(self.widget.Inputs.corpus, data)\n self.wait_until_finished()\n weights = list(zip(*sorted(self.widget.corpus_counter.items())))[1]\n # due to computation error in computing mean use array_almost_equal\n np.testing.assert_array_almost_equal(weights, [1, 2, 2])\n\n output = self.get_output(self.widget.Outputs.word_counts)\n np.testing.assert_array_almost_equal([2, 2, 1], output.X.flatten())\n np.testing.assert_array_equal(\n [\"Word3\", \"Word2\", \"Word1\"], output.metas.flatten())\n self.assertTupleEqual(\n (\"Word3\", \"Word2\", \"Word1\"),\n list(zip(*self.widget.tablemodel[:]))[1])\n np.testing.assert_array_almost_equal(\n [2, 2, 1],\n list(zip(*self.widget.tablemodel[:]))[0])\n\n # try with one word not bow-feature\n data = self.corpus[:3]\n data = data.extend_attributes(\n csr_matrix([[3, 2, 0], [0, 3, 6], [0, 1, 0]]),\n [\"Word1\", \"Word2\", \"Word3\"])\n for v in data.domain.attributes[:2]:\n v.attributes[\"bow-feature\"] = True\n\n self.send_signal(self.widget.Inputs.corpus, data)\n self.wait_until_finished()\n weights = list(zip(*sorted(self.widget.corpus_counter.items())))[1]\n np.testing.assert_array_almost_equal(weights, [1, 2])\n\n output = self.get_output(self.widget.Outputs.word_counts)\n np.testing.assert_array_almost_equal([2, 1], output.X.flatten())\n np.testing.assert_array_equal(\n [\"Word2\", \"Word1\"], output.metas.flatten())\n self.assertTupleEqual(\n (\"Word2\", \"Word1\"),\n list(zip(*self.widget.tablemodel[:]))[1])\n np.testing.assert_array_almost_equal(\n [2, 1],\n list(zip(*self.widget.tablemodel[:]))[0])\n\n def test_bow_info(self):\n \"\"\"\n Widget shows info when bow-features used. This test tests this info.\n \"\"\"\n data = self.corpus[:3]\n\n # no data no info\n self.assertFalse(self.widget.Info.bow_weights.is_shown())\n self.send_signal(self.widget.Inputs.corpus, data)\n self.wait_until_finished()\n self.assertFalse(self.widget.Info.bow_weights.is_shown())\n self.send_signal(self.widget.Inputs.corpus, None)\n self.wait_until_finished()\n self.assertFalse(self.widget.Info.bow_weights.is_shown())\n\n # send bow data\n data = data.extend_attributes(\n csr_matrix([[3, 2, 0], [0, 3, 6], [0, 1, 0]]),\n [\"Word1\", \"Word2\", \"Word3\"])\n for v in data.domain.attributes:\n v.attributes[\"bow-feature\"] = True\n self.send_signal(self.widget.Inputs.corpus, data)\n self.wait_until_finished()\n self.assertTrue(self.widget.Info.bow_weights.is_shown())\n self.send_signal(self.widget.Inputs.corpus, None)\n self.wait_until_finished()\n self.assertFalse(self.widget.Info.bow_weights.is_shown())\n\n def test_topic(self):\n self.send_signal(self.widget.Inputs.topic, self.topic)\n\n self.assertIsNotNone(self.widget.topic)\n self.assertEqual(\"a0\", self.widget.wordlist[0][0])\n self.assertEqual(10, self.widget.wordlist[0][1])\n self.assertEqual(\"a9\", self.widget.wordlist[9][0])\n self.assertEqual(40, self.widget.wordlist[9][1])\n\n self.assertListEqual(\n self.topic.metas[:, 0].tolist(), self.widget.shown_words.tolist())\n np.testing.assert_array_almost_equal(self.topic.W, self.widget.shown_weights)\n\n def test_no_tokens(self):\n \"\"\"\n In some very rare cases (when all text strings empty) word cloud all\n token lists empty. Widget must work in those cases.\n \"\"\"\n with self.corpus.unlocked():\n self.corpus.metas = np.array([[\" \"]] * len(self.corpus))\n self.send_signal(self.widget.Inputs.corpus, self.corpus)\n self.wait_until_finished()\n\n def test_select_words_output(self):\n self.send_signal(self.widget.Inputs.corpus, self.corpus)\n self.assertIsNone(self.get_output(self.widget.Outputs.selected_words))\n\n mode = QItemSelectionModel.Rows | QItemSelectionModel.Select\n view = self.widget.tableview\n view.clearSelection()\n view.selectionModel().select(self.widget.tablemodel.index(2, 0), mode)\n view.selectionModel().select(self.widget.tablemodel.index(3, 0), mode)\n\n output = self.get_output(self.widget.Outputs.selected_words)\n self.assertEqual(2, len(output))\n self.assertEqual(\"words\", output.domain[\"Words\"].attributes[\"type\"])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/widgets/tests/test_owwordcloud.py","file_name":"test_owwordcloud.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"15452854326","text":"from telebot import *\nfrom credentials import bot_credentials\nimport json\nimport pokebase \nfrom pokebase import cache\ncache.API_CACHE\n\n# Inizializzazione del bot \npokebot = telebot.TeleBot(bot_credentials[\"token\"])\n\n@pokebot.message_handler(commands=['start'])\ndef send_welcome(message):\n pokebot.reply_to(\n message, \"Avvio in corso ... bibubububbip ... scrivi /help per gli aiuti ai comandi\")\n\n\n@pokebot.message_handler(commands=['help'])\ndef help(message):\n markup = types.InlineKeyboardMarkup()\n button_img = types.InlineKeyboardButton(\n text='/poke - Per cercare un pokemon', callback_data=\"/poke \")\n markup.add(button_img)\n button_src = types.InlineKeyboardButton(\n text='/rdmpoke - Per cercare un pokemon random', callback_data=\"/rdmpoke \")\n markup.add(button_src)\n pokebot.send_message(\n message.chat.id, \"Di segutio i comandi\", reply_markup=markup)\n\n\n@pokebot.message_handler(commands=['poke'])\ndef img(message):\n json_result = pixivCrawler.illust_ranking('day')\n len_illust = len(json_result.illusts)\n illustN = random.randint(0, len_illust)\n pokebot.reply_to(message, json_result.illusts[illustN].image_urls.medium)\n\n\n@pokebot.message_handler(commands=['rdmpoke'])\ndef src(message):\n sent_msg = pokebot.send_message(\n message.chat.id, \"Cerco un pokemon random ...\")\n sent_msg = pokebot.send_message(getPokemon())\n\n\ndef getPokemon(p_pokemon = None):\n if p_pokemon == None:\n pokemon = pokebase.pokemon(\"pickachu\")\n else:\n pokemon = pokebase.pokemon(p_pokemon)\n return pokemon.natural_gift_type.name\n\npokebot.infinity_polling()\n\n","repo_name":"Acelith/pokebot","sub_path":"main.py","file_name":"main.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":"15533344421","text":"duration_days = int(input())\ndaily_plunder = int(input())\nto_reach = float(input())\nwinnings = 0\n\nfor d in range(1, duration_days + 1):\n winnings += daily_plunder\n if d % 3 == 0:\n winnings += .5 * daily_plunder\n if d % 5 == 0:\n winnings = winnings * .7\nif winnings >= to_reach:\n print(f\"Ahoy! {winnings:.2f} plunder gained.\")\nelse:\n percentage = winnings * 100 / to_reach\n print(f\"Collected only {percentage:.2f}% of the plunder.\")","repo_name":"karalkal/SoftUni_Python_Fundamentals","sub_path":"prev_mid_exams/06. Programming Fundamentals Mid Exam Retake - 6 August 2019/1_black_flag.py","file_name":"1_black_flag.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34984142533","text":"import asyncio\n\nimport pytest\n\nfrom lnbits.utils.cache import Cache\nfrom tests.conftest import pytest_asyncio\n\nkey = \"foo\"\nvalue = \"bar\"\n\n\n@pytest_asyncio.fixture\nasync def cache():\n cache = Cache(interval=0.1)\n\n task = asyncio.create_task(cache.invalidate_forever())\n yield cache\n task.cancel()\n\n\n@pytest.mark.asyncio\nasync def test_cache_get_set(cache):\n cache.set(key, value)\n assert cache.get(key) == value\n assert cache.get(key, default=\"default\") == value\n assert cache.get(\"i-dont-exist\", default=\"default\") == \"default\"\n\n\n@pytest.mark.asyncio\nasync def test_cache_expiry(cache):\n # gets expired by `get` call\n cache.set(key, value, expiry=0.01)\n await asyncio.sleep(0.02)\n assert not cache.get(key)\n\n # gets expired by invalidation task\n cache.set(key, value, expiry=0.1)\n await asyncio.sleep(0.2)\n assert key not in cache._values\n assert not cache.get(key)\n\n\n@pytest.mark.asyncio\nasync def test_cache_pop(cache):\n cache.set(key, value)\n assert cache.pop(key) == value\n assert not cache.get(key)\n assert cache.pop(key, default=\"a\") == \"a\"\n\n\n@pytest.mark.asyncio\nasync def test_cache_coro(cache):\n called = 0\n\n async def test():\n nonlocal called\n called += 1\n return called\n\n await cache.save_result(test, key=\"test\")\n result = await cache.save_result(test, key=\"test\")\n assert result == called == 1\n","repo_name":"lnbits/lnbits","sub_path":"tests/core/test_cache.py","file_name":"test_cache.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":882,"dataset":"github-code","pt":"52"} +{"seq_id":"30478244664","text":"from baselines.POEM import DatasetReader\nimport math\nimport numpy\nimport numpy.random\nimport scipy.sparse\nfrom baselines.POEM import Skylines\nimport sys\n\n\nclass DataStream:\n def __init__(self, dataset, verbose):\n self.verbose = verbose\n\n self.originalFeatures = dataset.trainFeatures.copy()\n self.originalLabels = dataset.trainLabels.copy()\n \n numSamples = numpy.shape(self.originalFeatures)[0]\n permute = numpy.random.permutation(numSamples)\n self.permutedFeatures = self.originalFeatures[permute, :]\n self.permutedLabels = self.originalLabels[permute, :]\n\n if self.verbose:\n print(\"DataStream: [Message] Initialized with permutation over [n_samples]: \", numSamples)\n sys.stdout.flush()\n\n def generateStream(self, subsampleFrac, replayCount):\n numSamples = numpy.shape(self.permutedFeatures)[0]\n numSubsamples = math.ceil(subsampleFrac*numSamples)\n subsampleFeatures = self.permutedFeatures[0:numSubsamples,:]\n subsampleLabels = self.permutedLabels[0:numSubsamples,:]\n if self.verbose:\n print(\"DataStream: [Message] Selected subsamples [n_subsamples, n_samples]: \", numSubsamples, numSamples)\n sys.stdout.flush()\n\n if replayCount <= 1: \n return subsampleFeatures, subsampleLabels\n else:\n replicator = numpy.ones((replayCount, 1))\n repeatedFeatures = scipy.sparse.kron(replicator, subsampleFeatures, format='csr')\n repeatedLabels = numpy.kron(replicator, subsampleLabels)\n\n if self.verbose:\n print(\"DataStream: [Message] Replay samples \", numpy.shape(repeatedFeatures)[0])\n sys.stdout.flush()\n return repeatedFeatures, repeatedLabels\n\n def freeAuxiliaryMatrices(self):\n del self.originalFeatures\n del self.originalLabels\n del self.permutedFeatures\n del self.permutedLabels\n \n if self.verbose:\n print(\"Datastream: [Message] Freed matrices\")\n sys.stdout.flush()\n\n\nclass Logger:\n def __init__(self, dataset, loggerC, stochasticMultiplier, verbose):\n self.verbose = verbose\n crf = Skylines.CRF(dataset = dataset, tol = 1e-5, minC = loggerC, maxC = loggerC, verbose = self.verbose, parallel = True)\n crf.Name = \"LoggerCRF\"\n crf.validate()\n if not(stochasticMultiplier == 1):\n for i in range(len(crf.labeler)):\n if crf.labeler[i] is not None:\n crf.labeler[i].coef_ = stochasticMultiplier * crf.labeler[i].coef_\n\n self.crf = crf\n if self.verbose:\n print(\"Logger: [Message] Trained logger crf. Weight-scale: \", stochasticMultiplier)\n sys.stdout.flush()\n\n def freeAuxiliaryMatrices(self):\n del self.crf\n\n def generateLog(self, dataset):\n numSamples, numFeatures = numpy.shape(dataset.trainFeatures)\n numLabels = numpy.shape(dataset.trainLabels)[1]\n\n sampledLabels = numpy.zeros((numSamples, numLabels), dtype = numpy.int)\n logpropensity = numpy.zeros(numSamples, dtype = numpy.longdouble)\n for i in range(numLabels):\n if self.crf.labeler[i] is not None:\n regressor = self.crf.labeler[i]\n predictedProbabilities = regressor.predict_log_proba(dataset.trainFeatures)\n\n randomThresholds = numpy.log(numpy.random.rand(numSamples).astype(numpy.longdouble))\n sampledLabel = randomThresholds > predictedProbabilities[:,0]\n sampledLabels[:, i] = sampledLabel.astype(int)\n\n probSampledLabel = numpy.zeros(numSamples, dtype=numpy.longdouble)\n probSampledLabel[sampledLabel] = predictedProbabilities[sampledLabel, 1]\n remainingLabel = numpy.logical_not(sampledLabel)\n probSampledLabel[remainingLabel] = predictedProbabilities[remainingLabel, 0]\n logpropensity = logpropensity + probSampledLabel\n\n diffLabels = sampledLabels != dataset.trainLabels\n sampledLoss = diffLabels.sum(axis = 1, dtype = numpy.longdouble) - numLabels\n\n if self.verbose:\n averageSampledLoss = sampledLoss.mean(dtype = numpy.longdouble)\n print(\"Logger: [Message] Sampled historical logs. [Mean train loss, numSamples]:\", averageSampledLoss, numpy.shape(sampledLabels)[0])\n print(\"Logger: [Message] [min, max, mean] inv propensity\", logpropensity.min(), logpropensity.max(), logpropensity.mean())\n sys.stdout.flush()\n return sampledLabels, logpropensity, sampledLoss\n\n","repo_name":"sgiguere/RobinHood-NeurIPS-2019","sub_path":"Python/baselines/POEM/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"9852736921","text":"from flask_restx import Resource, marshal\nfrom ..models.ApiModel import Cast_fields,Movie_fields\nfrom ..services.movie_service import MoiveService\n\ndef movie_routes(movie_ns):\n @movie_ns.route('/movie')\n class CreateMovie(Resource):\n @movie_ns.doc(\n description = '달에 한번 csv를 통한 영화 DB 저장.',\n responses={\n 500: \"Failed to create movies\"\n })\n def post(self):\n # Movie 먼저 생성\n resultMovie = MoiveService.create_movie()\n \n if resultMovie:\n # Movie 생성이 성공했을 경우에만 Cast 생성\n resultCast = MoiveService.create_cast()\n \n if resultCast:\n return {'message': 'Movies and Cast created successfully'}, 200\n else:\n return {'message': 'Failed to create Cast'}, 500\n else:\n return {'message': 'Failed to create Movies'}, 500\n\n @movie_ns.route('/')\n class ReadMovie(Resource):\n @movie_ns.doc(\n description = '영화 리스트 불러오기.',\n responses={\n 500: \"Failed to get movies\"\n })\n def get(self):\n result = MoiveService.get_movie()\n if result:\n return {'result': result}, 200\n else:\n return {'message': 'Failed to get movies'}, 500\n \n @movie_ns.route('/')\n class ReadOneMovie(Resource):\n @movie_ns.doc(\n description = '영화 1개 불러오기.',\n responses={\n 500: \"Failed to get movie\"\n })\n def get(self,movie_id):\n result = MoiveService.get_movie_one(movie_id)\n if result:\n return {'result': marshal(result, Movie_fields)}, 200\n else:\n return {'message': 'Failed to get movie'}, 500\n \n @movie_ns.route('/cast')\n class ReadMovie(Resource):\n @movie_ns.doc(\n description = '캐스트 리스트 불러오기.',\n responses={\n 500: \"Failed to get casts\"\n })\n def get(self):\n result = MoiveService.get_cast()\n if result:\n return {'result': result}, 200\n else:\n return {'message': 'Failed to get casts'}, 500\n \n @movie_ns.route('/cast/')\n class ReadMovie(Resource):\n @movie_ns.doc(\n description = '캐스트 1개 불러오기.',\n responses={\n 500: \"Failed to get cast\"\n })\n def get(self, movie_id):\n result = MoiveService.get_cast_one(movie_id)\n if result:\n return {'result': marshal(result, Cast_fields)}, 200\n else:\n return {'message': 'Failed to get cast'}, 500","repo_name":"Oh-Kang94/Season4_Main-project-Server","sub_path":"app/routes/movie_routes.py","file_name":"movie_routes.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72579444325","text":"#!/usr/bin/env python\n\n# -----------------------------------------------------------------------\n# insert_restaurant.py\n# Author: Piers Ozuah\n# Debugger: Justice Chukwuma\n# -----------------------------------------------------------------------\n\nfrom sys import argv, stderr, exit\nfrom psycopg2 import connect\nimport psycopg2\n\n\ndef insert_restaurant():\n \"\"\" Insert our test restaurants\"\"\"\n\n commands = [\n \"\"\"\n INSERT INTO restaurants ( name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n '1911 Smokehouse BBQ',\n '11 W Front St, Trenton, NJ 08608',\n 'Monday 11:00 AM - 3:30 PM, Tuesday 11:00 AM - 3:30 PM, Wednesday 11:00 AM - 10:30 PM, Thursday 11:00 AM - 10:30 PM, Friday 11:00 AM - 10:30 PM, Saturday 1:00 PM - 10:30PM, Sunday 1:00 PM - 10:30 PM',\n FALSE,\n 'http://places.singleplatform.com/1911-smoke-house-barbeque/menu?ref=google',\n 'https://1911bbq.com',\n 'BBQ',\n 0,\n 0,\n 'BBQ, Grill, American',\n 'Fast Food',\n 'Moderate $$', 'https://hiddentrenton.com/wp-content/uploads/2015/10/smoked-salmon-on-salad.jpg' );\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants ( name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Bamboo Grill Jamaican Restaurant',\n '1005 Chambers St, Trenton, NJ 08611',\n 'Monday 10:00 AM - 7:00 PM, Tuesday 10:00 AM - 7:00 PM, Wednesday 10:00 AM - 7:00 PM, Thursday 10:00 AM - 7:00 PM, Friday 10:00 AM - 8:00 PM, Saturday 10:00 AM - 8:00 PM, Sunday Closed',\n TRUE,\n 'None',\n 'None',\n 'Jamaican, Grill',\n 0,\n 0,\n 'BBQ, Grill, Jamaican',\n 'Fast Food',\n 'Moderate $$',\n 'https://cdn.usarestaurants.info/assets/uploads/5d0e3573a5822a6c84c9c4c5645632e0_-united-states-new-jersey-mercer-county-trenton-bamboo-grill-jamaican-restaurant-mini-mart-542551htm.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Ila Mae''s Restaurant',\n '313 Market St, Trenton, NJ 08611',\n 'Monday Closed, Tuesday 9:00 AM - 8:00 PM, Wednesday 9:00 AM - 8:00 PM, Thursday 9:00 AM - 8:00 PM, Friday 9:00 AM - 8:00 PM, Saturday 9:00 AM - 8:00 PM, Sunday Closed', FALSE,\n 'http://places.singleplatform.com/ila-maes-restaurant/menu?ref=google',\n 'None',\n 'Soul',\n 0,\n 0,\n 'Soul',\n 'Casual',\n 'Moderate $$',\n 'https://b.zmtcdn.com/data/reviews_photos/ae0/5e409171385c4b3f360eb7fe0ad87ae0_1449862294.jpg?fit=around|771.75:416.25&crop=771.75:416.25;*,*');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants ( name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Blue Danube Restaurant',\n '538 Adeline St, Trenton, NJ 08611',\n 'Monday Closed, Tuesday 11:30 AM - 7:30 PM, Wednesday 11:30 AM - 7:30 PM, Thursday 11:30 AM - 7:30 PM, Friday 11:30 AM - 8:00 PM, Saturday 3:00 - 8:00 PM, Sunday 3:00 PM - 7:30 PM',\n TRUE,\n 'http://www.bluedanuberestaurant.net/menu.php',\n 'http://www.bluedanuberestaurant.net/about.php',\n 'Eastern European' ,\n 0,\n 0,\n 'Eastern European',\n 'Casual',\n 'Moderate $$',\n 'https://vrconcierge.com/wp-content/uploads/2021/07/blue-danube-restaurant-trenton-nj-exterior-1.jpg' );\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants ( name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'The Big Easy of Trenton Restaurant',\n '111 S Warren St, Trenton, NJ 08608',\n 'Monday 12:00 PM - 7:00 PM, Tuesday 12:00 PM - 7:00 PM, Wednesday 12:00 PM - 7:00 PM, Thursday 12:00 PM - 7:00 PM, Friday 12:00 PM - 7:00 PM, Saturday 9:00 AM - 5:00 PM, Sunday Closed', FALSE,\n 'None',\n 'None',\n 'Dine-in' ,\n 0,\n 0,\n 'Dine-in, Soul',\n 'Casual',\n 'Moderate $$',\n 'https://hiddentrenton.com/wp-content/uploads/2018/05/the-buffet.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants ( name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Don Julio''s Bar and Grill',\n '900 Liberty St, Trenton, NJ 08611',\n 'Monday 11:00 AM - 2:00 AM, Tuesday 11:00 AM - 2:00 AM, Wednesday 11:00 AM - 2:00 AM, Thursday 11:00 AM - 2:00 AM, Friday 11:00 AM - 2:00 AM, Saturday 11:00 AM - 2:00 AM, Sunday 12:00 PM - 2:00 AM',\n TRUE,\n 'None',\n 'None',\n 'Bar & Grill' ,\n 0,\n 0,\n 'Bar & Grill',\n 'Casual',\n 'Moderate $$',\n 'https://resizer.otstatic.com/v2/photos/wide-huge/1/41970639.png'\n );\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'The Hummingbird Restaurant',\n '29 S Warren St, Trenton, NJ 08608',\n 'Monday 10:00 AM - 7:00 PM, Tuesday 10:00 AM - 7:00 PM, Wednesday 10:00 AM - 7:00 PM, Thursday 10:00 AM - 7:00 PM, Friday 10:00 AM - 6:00 PM, Saturday 10:00 AM - 6:00 PM, Sunday Closed',\n FALSE,\n 'None',\n 'None',\n 'Jamaican' ,\n 0,\n 0,\n 'Jamaican',\n 'Casual',\n 'Moderate $$',\n 'https://hiddentrenton.com/wp-content/uploads/2010/03/hummingbird1.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Sabor Latino',\n '293 Ashmore Ave, Trenton, NJ 08611',\n 'Monday 10:00 AM - 12:00 AM, Tuesday 10:00 AM - 12:00 AM, Wednesday Closed, Thursday 10:00 AM - 12:00 AM, Friday 10:00 AM - 2:00 AM, Saturday 10:00 AM - 2:00 AM, Sunday 10:00 AM - 12:00 AM',\n TRUE,\n 'None',\n 'None',\n 'Dominican' ,\n 0,\n 0,\n 'Dominican, Mexican',\n 'Casual',\n 'Moderate $$',\n 'https://www.trentondaily.com/wp-content/uploads/2019/07/sabor.png');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Trentini''s',\n '635 S Clinton Ave, Trenton, NJ 08611',\n 'Monday 10:00 AM - 10:00 PM, Tuesday 10:00 AM - 10:00 PM, Wednesday 10:00 AM - 10:00 PM, Thursday 10:00 AM - 10:00 PM, Friday 10:00 AM - 10:00 PM, Saturday 10:00 AM - 10:00 PM, Sunday 10:00 AM - 10:00 PM',\n FALSE,\n 'https://trentinismenu.com/menu.html',\n 'https://trentinismenu.com/index.html',\n 'Italian' ,\n 0,\n 0,\n 'Italian, Mediterranean, Spanish',\n 'Casual',\n 'Inexpensive $',\n 'https://www.trentondaily.com/wp-content/uploads/2019/05/trentinis.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Mama D Soul Food 2',\n '312 S Broad St, Trenton, NJ 08609',\n 'Monday Closed, Tuesday Closed, Wednesday 12:00 PM - 7:00 PM, Thursday 12:00 PM - 7:00 PM, Friday 12:00 PM - 7:00 PM, Saturday 9:00 AM - 7:00 PM, Sunday 1:00 PM - 7:00 PM',\n TRUE,\n 'None',\n 'None',\n 'Soul' ,\n 0,\n 0,\n 'Soul',\n 'Fast Food',\n 'Inexpensive $',\n 'https://blackenlightenmentapp.com/wp-content/uploads/2018/09/mamad-e1576679700857.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Cooper''s Riverview',\n '50 Riverview Plaza, Trenton, NJ 08611',\n 'Monday Closed, Tuesday 12:00 PM - 2:00 AM, Wednesday 12:00 PM - 2:00 AM, Thursday 12:00 PM - 2:00 AM, Friday 12:00 PM - 2:00 AM, Saturday 12:00 PM - 2:00 AM, Sunday 11:30 AM - 11:00 PM',\n FALSE,\n 'coopersnj.com',\n 'None',\n 'English' ,\n 0,\n 0,\n 'English',\n 'Fine Dining',\n 'Pricey $$$',\n 'https://www.nj.com/resizer/6CK6XH7YNlcxanJteQtof44WHtc=/800x0/smart/arc-anglerfish-arc2-prod-advancelocal.s3.amazonaws.com/public/6RLSBPHNOJCB7KK2NOXOGRFYXE.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Mi Ranchito Pizza and Tacos',\n '911 Chambers St, Trenton, NJ 08611',\n 'Monday 10:00 AM - 10:00 PM, Tuesday 10:00 AM - 10:00 PM, Wednesday Closed, Thursday 10:00 AM - 10:00 PM, Friday 10:00 AM - 10:00 PM, Saturday 10:00 AM - 10:00 PM, Sunday 10:00 AM - 10:00 PM',\n TRUE,\n 'None',\n 'None',\n 'Tacos' ,\n 0,\n 0,\n 'Mexican, Tacos',\n 'Casual',\n 'Inexpensive $',\n 'https://cdn.usarestaurants.info/assets/uploads/7a258e9a8dabd09a7e415256cd08757d_-united-states-new-jersey-mercer-county-trenton-mi-ranchito-pizza-and-tacos-609-498-0174htm.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'El Potrillo',\n '541 Roebling Ave, Trenton, NJ 08611',\n 'Monday 10:00 AM - 10:00 PM, Tuesday Closed, Wednesday 10:00 AM - 10:00 PM, Thursday 10:00 AM - 10:00 PM, Friday 10:00 AM - 10:00 PM, Saturday 10:00 AM - 10:00 PM, Sunday 10:00 AM - 10:00 PM',\n FALSE,\n 'http://places.singleplatform.com/el-potrillo-mexican-restaurant-7/menu?ref=google',\n 'None',\n 'Mexican' ,\n 0,\n 0,\n 'Mexican',\n 'Casual',\n 'Moderate $$',\n 'https://hiddentrenton.com/wp-content/uploads/2015/03/El_Potrillo.jpg');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Chencha y Chole',\n '865 S Broad St, Trenton, NJ 08611',\n 'Monday 11:00 AM - 10:00 PM, Tuesday 11:00 AM - 10:00 PM, Wednesday 11:00 AM - 10:00 PM, Thursday 11:00 AM - 10:00 PM, Friday 11:00 AM - 10:00 PM, Saturday 11:00 AM - 10:00 PM, Sunday 11:00 AM - 10:00 PM',\n TRUE,\n 'None',\n 'None',\n 'Mexican' ,\n 0,\n 0,\n 'Mexican',\n 'Casual',\n 'Inexpensive $',\n 'https://media-cdn.grubhub.com/image/upload/d_search:browse-images:default.jpg/w_1200,h_800,f_auto,fl_lossy,q_80,c_fit/xgqbyondwd2syksoznsj');\n \"\"\",\n\n \"\"\"\n INSERT INTO restaurants (name, address, hours,\n open_closed, menu, media, tags, review_count, stars,\n cuisine, type, price, image)\n VALUES (\n 'Casablanca Restaurant',\n '140 Washington St, Trenton, NJ 08611',\n 'Monday 11:00 AM - 2:00 AM, Tuesday 11:00 AM - 2:00 AM, Wednesday 11:00 AM - 2:00 AM, Thursday 11:00 AM - 2:00 AM, Friday 11:00 AM - 2:00 AM, Saturday 11:00 AM - 2:00 AM, Sunday 11:00 AM - 2:00 AM',\n FALSE,\n 'None',\n 'None',\n 'Spanish' ,\n 0,\n 0,\n 'Spanish',\n 'Casual',\n 'Moderate $$',\n 'https://hiddentrenton.com/wp-content/uploads/2017/12/Exterior.jpg');\n \"\"\",\n \"\"\"\n INSERT INTO administrators (email)\n VALUES (\n 'sd20@princeton.edu');\n \"\"\",\n \"\"\"\n INSERT INTO administrators (email)\n VALUES (\n 'pjozuah@princeton.edu');\n \"\"\",\n \"\"\"\n INSERT INTO administrators (email)\n VALUES (\n 'soumyag@princeton.edu');\n \"\"\",\n \"\"\"\n INSERT INTO administrators (email)\n VALUES (\n 'chukwuma@princeton.edu');\n \"\"\",\n \"\"\"\n INSERT INTO administrators (email)\n VALUES (\n 'anatk@princeton.edu');\n \"\"\",\n \"\"\"\n INSERT INTO administrators (email)\n VALUES (\n 'kao3@princeton.edu');\n \"\"\"]\n try:\n # with connect(\n # host='localhost', port=5432, user='rmd', password='trentoneats333',\n # database='trentoneats') as connection:\n with connect(host='ec2-3-229-161-70.compute-1.amazonaws.com', port=5432, user='jazlvqafdamomp', password='6bc2f9e25e0ab4a2e167d5aed92096137eaacd1667e2863a6659e019dbb7e81a',\n database=\"dequ5ope4nuoit\") as connection:\n\n with connection.cursor() as cursor:\n # # create table one by one\n for command in commands:\n cursor.execute(command)\n\n # close communication with the PostgreSQL database server\n cursor.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n\n\nif __name__ == '__main__':\n insert_restaurant()\n","repo_name":"stephendongg/trentoneats","sub_path":"database/insert_restaurant.py","file_name":"insert_restaurant.py","file_ext":"py","file_size_in_byte":13497,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20880009852","text":"import smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\nimport tripnsale.settings as settings\nimport django.template.loader as templates\nfrom util.exc import TsExc\nimport re\n\nimport dkim\n\nHEADER_TAG = (\"<
>\", \"<
>\",)\nCONTENT_TAG = (\"<>\", \"<>\",)\n\nclass MailErr (TsExc):\n def __init__(self, msg):\n super().__init__(msg)\n\nclass InvalidTagErr (MailErr):\n def __init__(self, msg):\n super().__init__(msg)\n\nclass InvalidTagsNumber (MailErr):\n def __init__(self, msg):\n super().__init__(msg)\n\ndef _ExtractTags(text, tag, exactlyOne=False):\n pos = 0\n ret = []\n while True:\n if len(ret) > 1 and exactlyOne:\n raise InvalidTagsNumber(\"Expected exactly one tags, got more\")\n if tag[0] in text[pos:] or tag[1] in text[pos:]:\n if tag[0] not in text[pos:] or tag[1] not in text[pos:]:\n raise InvalidTagErr(\"Invalid tag: {} ({}, {})\".format(str(tag), tag[0] not in text[pos:], tag[1] not in text[pos:]))\n begpos = text.find(tag[0], pos) + len(tag[0])\n endpos = text.find(tag[1], pos)\n ret.append(text[begpos:endpos])\n pos = endpos + len(tag[1])\n else:\n break\n\n if exactlyOne and len(ret) == 1:\n return ret[0]\n elif exactlyOne:\n return None\n else:\n return ret\n\nclass NoMailContent (MailErr):\n def __init__(self, msg):\n super().__init__(msg)\n\ndef SendMail(to, template, params={}, templateFromFile=True, dkimKeys=None, dkimSelector=None):\n \"\"\"\n sends email to @to\n if @templateFromFile == True message will be taken from @template _file_ and\n from @template as a string else.\n template should have header and content section\n (separated with mail.utils.HEADER_TAG, mail.utils.CONTENT_TAG). For example:\n {% load email_tags %}\n {% email_header %} # will be replaced with mail.utils.HEADER_TAG[0]\n Subject: foo\n To: foo@tripnsale.com\n From: bar@tripnsale.com\n {% email_endheader %} # mail.utils.HEADER_TAG[1]\n {% email_content %} # mail.utils.CONTENT_TAG[0]\n blahblahblah\n {% email_endcontent %} # mail.utils.CONTENT_TAG[1]\n @params are used tor rendering the template\n @dkimKeys is a pair (private=priv_key, public=pub_key).\n if None, settings.EMAIL_DKIM_KEYS will be taken.\n if there aren't such keys, the mail won't be signed with dkim!\n @dkimSelector is a selector for dkim. if None, settings.EMAIL_DKIM_SELECTOR will be taken\n \"\"\"\n if not settings.ENABLE_EMAIL:\n return\n\n fr = \"info@tripnsale.com\"\n params.update({ \"to_email\": to,\n \"fr_email\": fr,\n \"hostAddr\": settings.CURRENT_HOST })\n if templateFromFile:\n rawmsg = templates.render_to_string(template, params)\n else:\n t = templates.Template(template)\n rawmsg = t.render(templates.Context(params))\n\n rawmsg = rawmsg.replace(\"\\r\\n\", \"\\n\")\n\n rawheaders = _ExtractTags(rawmsg, HEADER_TAG, exactlyOne=True)\n if rawheaders:\n headers = {}\n for rawh in rawheaders.split(\"\\n\"):\n if rawh.strip() == \"\":\n continue\n header = rawh.split(\": \")\n if len(header) != 2:\n raise MailErr(\"Something wrong with header: got {} tokens: {}\".format(len(header), header))\n headers[header[0].strip()] = header[1].strip()\n else:\n headers = {}\n\n content = _ExtractTags(rawmsg, CONTENT_TAG, exactlyOne=True)\n if not content:\n raise NoMailContent(\"Content is empty\")\n\n msg = MIMEText(content)\n for hname, hval in headers.items():\n msg[hname] = hval\n\n if dkimKeys:\n rsaKeys = dkimKeys\n elif settings.EMAIL_DKIM_KEYS:\n rsaKeys = settings.EMAIL_DKIM_KEYS\n else:\n rsaKeys = None\n\n if rsaKeys:\n dkimmsg = dkim.DKIM(str(msg).encode(\"utf-8\"))\n if dkimSelector:\n dkimsel = dkimSelector\n else:\n dkimsel = settings.EMAIL_DKIM_SELECTOR\n dkimsel = dkimsel.encode(\"utf-8\")\n\n dkimdomain = settings.EMAIL_DKIM_DOMAIN.encode(\"utf-8\")\n dkimkey = rsaKeys.private.encode(\"utf-8\")\n\n sig = dkimmsg.sign(dkimsel, dkimdomain, dkimkey).decode('ascii')\n sigh, sigc = tuple(sig.split(': ', 1))\n msg[sigh] = sigc\n\n sm = smtplib.SMTP(\"localhost\")\n sm.sendmail(fr, to, str(msg))\n sm.quit()\n","repo_name":"boomeer/tripnsale","sub_path":"mail/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31766528708","text":"from tmlib.workflow.args import BatchArguments\nfrom tmlib.workflow.args import SubmissionArguments\nfrom tmlib.workflow.args import Argument\nfrom tmlib.workflow import register_step_batch_args\nfrom tmlib.workflow import register_step_submission_args\n\n\n@register_step_batch_args('imextract')\nclass ImextractBatchArguments(BatchArguments):\n\n batch_size = Argument(\n type=int, default=100, flag='batch-size', short_flag='b',\n help='number of image acquisition sites to process per job',\n )\n\n delete = Argument(\n type=bool, default=False,\n help='''\n delete microscope files after pixel data got extracted\n (Warning: You won't be able to rerun jobs afterwards!)\n '''\n )\n\n\n@register_step_submission_args('imextract')\nclass ImextractSubmissionArguments(SubmissionArguments):\n\n pass\n","repo_name":"TissueMAPS/TissueMAPS","sub_path":"tmlibrary/tmlib/workflow/imextract/args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"37510230073","text":"# Author: Kelvin Abrokwa-Johnson\n# Calculates the grade needed for a minimum grade based on grade category weighting\n\nimport sys\n\ndef verifyWeights():\n\ttotal_percentage = 0\n\tfor value in weight_dict.values():\n\t\ttotal_percentage += value\n\tif int(total_percentage) != 100:\n\t\tprint(\"\\nThe weightings don't add up to 100%. This program will now end.\\n\\n\\n\")\n\t\tsys.exit()\n\ndef addGrade(category, new_grade):\n\t\"\"\"Creates a list of grades for each category\"\"\"\n\tif grade_dict[category]:\n\t\tgrade_dict[category].append(new_grade)\n\telse:\n\t\tgrade_dict[category] = [new_grade]\n\ndef getAverage(list_of_grades):\n\t\"\"\"Calculate Average of all grades in a category, input must be a list. Input is a list of grades.\"\"\"\n\ttotal = 0\n\tfor i in list_of_grades:\n\t\ttotal += i\n\taverage = total / len(list_of_grades)\n\treturn average\n\n# These dictionaries are essentially minified MapReduce (I'm probably just throwing buzzwords around)\nweight_dict = {}\ngrade_dict = {}\navg_dict = {}\n\n# Menu for categories and weighting\nprint(\"\")\nnew_cat = 'null'\nwhile new_cat.lower() != '':\n\tnew_cat = input(\"Enter a new category or just press \\\"enter\\\" to finish: \")\n\tif new_cat.lower() == '':\n\t\tbreak\n\tnew_weight = input(\"Enter its weigth: \")\n\t# To make sure they enter a number\n\ttry:\n\t\tnew_weight = int(new_weight)\n\texcept ValueError:\n\t\tnew_weight = int(input(\"That isn't a number. Please enter an integer: \"))\n\tweight_dict[new_cat] = int(new_weight)\n\nverifyWeights()\n\nprint(\"\")\nprint(\"=\"*30)\nprint(\"%-15s %-5s %s\" % (\"Categories\", \"|\", \"Weights\"))\nprint(\"-\"*30)\nfor key, value in weight_dict.items():\n\tvalue = int(value)\n\tprint(\"%-15s %-5s %d\" % (key, \"|\", value))\n\n\n# Menu for lists of grades\nprint(\"=\"*30, \"\\n\")\nprint(\"And now to enter you grades!\\n\")\nprint(\"When prompted for each category, enter each grade\") \nprint(\"receieved one at a time, followed by the enter key.\\n\")\nprint(\"When you are finished, simply press \\\"enter\\\" for the next category.\\n\")\n\nfor key in weight_dict.keys():\n\tgrade_dict[key] = []\n\tnew_grade = 0\n\tprint(key.upper())\n\twhile new_grade != \"q\":\n\t\tnew_grade = input(\"Enter a grade or just press \\\"enter\\\" to move on to the next category: \")\n\t\tif new_grade == \"\":\n\t\t\tbreak\n\t\tgrade_dict[key].append(int(new_grade))\n\tprint(\"\\nHere are your grades for\", key, \": \")\n\tfor i in grade_dict[key]:\n\t\tprint(i)\n\tprint(\"\\n\")\n\n# Giving category averages\nfor key in grade_dict.keys():\n\tavg_dict[key] = getAverage(grade_dict[key])\n\tprint(key, \"average:\", getAverage(grade_dict[key]))\n\n# Calculating current class average\nclass_average = 0\nfor key in avg_dict.keys():\n\tpartial = avg_dict[key] * (weight_dict[key] / 100)\n\tclass_average += partial\nprint(\"\\nCurrent class average:\", class_average, \"\\n\")\n\ntarget_grade = input(\"Please enter your target grade as a percentage: \")\nprint(\"\\n\")\n\nprint(\"Choose type the category of your as it appears in the following list\\n\")\n\nnumber = 0\nfor key in weight_dict.keys():\n\tnumber += 1\n\tprint(number, end=\"\")\n\tprint(\".\", key)\n\nprint(\"\")\nchoice = input(\"--> \")\n\n# The magical, middle school algebra formula, ladies and gents\noutput = ( float(target_grade) - ( float(class_average) - float(avg_dict[choice] * (weight_dict[choice]) / 100)) ) * \t\\\n\t\t\\\n\t\t\t( ( float(len(grade_dict[choice])) + 1.0 ) / float(weight_dict[choice] / 100.0)) - \t\t\\\n\t\t\\\n\t\t\t( float(avg_dict[choice]) * float(len(grade_dict[choice])) )\n\nprint(\"\\nYou need a\", output, \"in order to get a\", target_grade)\nprint(\"\\nThanks for using our program!\")\nprint(\"Goodbye\")","repo_name":"kelvinabrokwa/wm-stats-blog","sub_path":"grade_calc/grades.py","file_name":"grades.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37034853362","text":"from queue import Queue\n\nimport cocotb\nfrom cocotb.triggers import Timer, RisingEdge\n\nfrom cocotblib.misc import randSignal, assertEquals, BoolRandomizer\n\n\nclass Packet:\n def __init__(self,a,b):\n self.a = a\n self.b = b\n\n\n@cocotb.coroutine\ndef cmd(dut,queue):\n validRandomizer = BoolRandomizer()\n dut.io_slave0_valid <= 0\n while True:\n yield RisingEdge(dut.io_clkA)\n if int(dut.io_slave0_valid) == 1 and int(dut.io_slave0_ready) == 1:\n queue.put(Packet(int(dut.io_slave0_payload_a),int(dut.io_slave0_payload_b)))\n dut.io_slave0_valid <= validRandomizer.get()\n randSignal(dut.io_slave0_payload_a)\n randSignal(dut.io_slave0_payload_b)\n\n\n\n@cocotb.coroutine\ndef rsp(dut,queue):\n readyRandomizer = BoolRandomizer()\n dut.io_master0_ready <= 0\n for i in range(0,1000):\n while True:\n yield RisingEdge(dut.io_clkB)\n dut.io_master0_ready <= readyRandomizer.get()\n if int(dut.io_master0_valid) == 1 and int(dut.io_master0_ready) == 1:\n break\n pop = queue.get()\n assertEquals(pop.a, dut.io_master0_payload_a,\"io_master0_payload_a\")\n assertEquals(pop.b, dut.io_master0_payload_b, \"io_master0_payload_b\")\n\n\n\n\n\n@cocotb.coroutine\ndef clockProcess(dut):\n randomizer = BoolRandomizer()\n dut.io_clkA <= 0\n dut.io_clkB <= 0\n dut.io_resetB <= 1\n dut.io_resetA <= 1\n yield Timer(1000)\n dut.io_resetA <= 0\n dut.io_resetB <= 0\n while True:\n dut.io_clkA <= 0\n dut.io_clkB <= 0\n yield Timer(500)\n if randomizer.get():\n dut.io_clkA <= 1\n else:\n dut.io_clkB <= 1\n yield Timer(500)\n\n\n\n@cocotb.test()\ndef test1(dut):\n dut.log.info(\"Cocotb test boot\")\n from cocotblib.misc import cocotbXHack\n cocotbXHack()\n #random.seed(0)\n\n queue = Queue()\n\n cocotb.fork(clockProcess(dut))\n cocotb.fork(cmd(dut,queue))\n yield rsp(dut,queue)\n\n dut.log.info(\"Cocotb test done\")\n","repo_name":"SpinalHDL/SpinalHDL","sub_path":"tester/src/test/python/spinal/MultiClockTester/MultiClockTester.py","file_name":"MultiClockTester.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":1406,"dataset":"github-code","pt":"52"} +{"seq_id":"14470732547","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport re\nimport pickle\nfrom typing import Optional\nfrom fastapi import FastAPI\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom pydantic import BaseModel\n\n\n# In[6]:\n\n\n\n\n\n# In[7]:\n\n\nloaded_model = pickle.load(open(\"stock.pkl\", \"rb\"))\ntfvector = pickle.load(open(\"tfvector.pkl\", \"rb\"))\n\n\n# In[8]:\n\n\napp = FastAPI()\n\nclass Headline(BaseModel):\n text:str\n\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n\n@app.post(\"/predict\")\ndef predict(headline:Headline):\n new_headline = headline.text\n new_headline = re.sub('[^a-zA-Z]', ' ', new_headline)\n new_headline = new_headline.lower()\n new_headline = new_headline.split()\n lemmatizer = WordNetLemmatizer()\n new_headline = [lemmatizer.lemmatize(word) for word in new_headline if not word in stopwords.words('english')]\n new_headline = ' '.join(new_headline)\n new_corpus = [new_headline]\n new_X_test = tfvector.transform(new_corpus).toarray()\n new_y_pred = loaded_model.predict(new_X_test)\n if(new_y_pred[0]==1):\n return{\"Prediction\" : \"the stock price increased\"}\n else :\n return{\"Prediction\" :\"the stock price stayed the same or decreased\"}\n\n","repo_name":"7289161/Stock-sentiment-analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14646171654","text":"import os\n\nfrom celery import Celery\n\n# Set the default Django settings module for the 'celery' program.\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'greenwood.settings')\n\napp = Celery('greenwood',broker='redis://127.0.0.1:6379/0')\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object('django.conf:settings', namespace='CELERY')\n\n# Load task modules from all registered Django apps.\napp.autodiscover_tasks()\n\n\napp.conf.beat_schedule={\n 'renew_data_base':{'task':'homepage.tasks.create_data','schedule':60.00*60*3},\n 'select_listings_for_catalog':{'task':'homepage.tasks.select_listings_for_catalog','schedule':60*60.00},\n 'select_listings_for_hp':{'task':'homepage.tasks.select_listings_for_hp','schedule':200.00},\n'test_task':{'task':'homepage.tasks.test_task','schedule':60.00},\n}\n","repo_name":"AlexFreemann/Greenwood_Django_Project","sub_path":"greenwood/greenwood/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70438580964","text":"'''\nWrite a loop to print all elements in hourly_temperature. Separate elements with a -> surrounded by spaces. Sample output for the given program:\n90 -> 92 -> 94 -> 95 \nNote: 95 is followed by a space, then a newline. \n'''\n\nhourly_temperature = [90, 92, 94, 95]\n\noutput = \"\"\nfor temp in hourly_temperature:\n output += str(temp)\n output += ' -> '\n\noutput = output[:-3]\nprint(output)","repo_name":"tonysulfaro/CSE-331","sub_path":"Exercises/Chapter 8 - Lists and Dictionaries/8.3 List Iteration/8.3.3 hourly_temp_reporting.py","file_name":"8.3.3 hourly_temp_reporting.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40943915624","text":"from app.transfer_locators import Transfer_Locators\nfrom app.login import Login\nfrom common.utility import wait_for_element_load, wait\n\n\nclass Transfer(Login):\n \"\"\"\n Page object for Transfer web page\n \"\"\"\n\n def __init__(self, user, password):\n \"\"\"\n constructor method where Transfer page will be navigated\n \"\"\"\n super().__init__()\n self.login(user, password)\n\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.TRANSFER_LINK_LOCATOR):\n transfer_link = self.driver.find_element(\n *Transfer_Locators.TRANSFER_LINK_LOCATOR)\n wait(1)\n transfer_link.click()\n\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.TRANSFER_LINK_LOCATOR))\n\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.TRANSFER_BET_ACCOUNTS_LOCATOR):\n transfer_bet_accounts = self.driver.find_element(\n *Transfer_Locators.TRANSFER_BET_ACCOUNTS_LOCATOR)\n transfer_bet_accounts.click()\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.TRANSFER_BET_ACCOUNTS_LOCATOR))\n\n def select_a_user(self, user):\n \"\"\"\n method to select a user\n user str: user to be selected\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.SELECT_USER_LOCATOR):\n combo_box = self.driver.find_element(\n *Transfer_Locators.SELECT_USER_LOCATOR)\n combo_box.click()\n wait(1)\n self.driver.find_element(\n Transfer_Locators.USER_OPTION_LOCATOR[0], Transfer_Locators.USER_OPTION_LOCATOR[1].format(user)).click()\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.SELECT_USER_LOCATOR))\n\n def select_available_debit_account(self, index=0):\n \"\"\"\n select an available account for debit, default is first\n index int: index at which debit account to be selected\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.ACCOUNT_FROM_LOCATOR):\n select_debit_acct = self.driver.find_element(\n *Transfer_Locators.ACCOUNT_FROM_LOCATOR)\n select_debit_acct.click()\n wait(1)\n for indexing, option in enumerate(select_debit_acct.find_elements(*Transfer_Locators.OPTION_LOCATOR)):\n if index == indexing:\n option.click()\n break\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.ACCOUNT_FROM_LOCATOR))\n\n def select_available_credit_account(self, index=1):\n \"\"\"\n method to select a credit account, defaults to index 1 so that it's different from debit account\n index int: index at which credit account to be selected\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.ACCOUNT_TO_LOCATOR):\n select_credit_acct = self.driver.find_element(\n *Transfer_Locators.ACCOUNT_TO_LOCATOR)\n select_credit_acct.click()\n wait(1)\n for indexing, option in enumerate(select_credit_acct.find_elements(*Transfer_Locators.OPTION_LOCATOR)):\n if index == indexing:\n option.click()\n break\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.ACCOUNT_TO_LOCATOR))\n\n def enter_amount_to_transfer(self, amount):\n \"\"\"\n method to enter amount to be transferred\n amount float: amount to be transferred\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.AMOUNT_LOCATOR):\n enter_amount = self.driver.find_element(\n *Transfer_Locators.AMOUNT_LOCATOR)\n enter_amount.send_keys(amount)\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.AMOUNT_LOCATOR))\n\n def enter_description(self, description):\n \"\"\"\n method to enter description\n description str: description to be added\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.DESCRIPTION_LOCATOR):\n description_elem = self.driver.find_element(\n *Transfer_Locators.DESCRIPTION_LOCATOR)\n description_elem.send_keys(description)\n wait(1)\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.DESCRIPTION_LOCATOR))\n\n def continue_transfer(self):\n \"\"\"\n method to continue transfer\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.CONTINUE_BUTTON_LOCATOR):\n continue_transfer = self.driver.find_element(\n *Transfer_Locators.CONTINUE_BUTTON_LOCATOR)\n continue_transfer.click()\n wait(1)\n else:\n raise Exception(\"Element: {} not found\".format(\n Transfer_Locators.CONTINUE_BUTTON_LOCATOR))\n\n def confirm_transfer(self):\n \"\"\"\n method to confirm\n return : None\n \"\"\"\n if wait_for_element_load(self.driver, self.timeout, Transfer_Locators.CONFIRM_BUTTON_LOCATOR):\n confirm_transfer = self.driver.find_element(\n *Transfer_Locators.CONFIRM_BUTTON_LOCATOR)\n confirm_transfer.click()\n wait(1)\n\n def verify_success(self):\n \"\"\"\n method to verify that\n \"\"\"\n return wait_for_element_load(\n self.driver, self.timeout, Transfer_Locators.SUCCESS_LOCATOR)\n\n def verify_error_message(self, error):\n \"\"\"\n method to verify error message\n \"\"\"\n wait(1)\n return error in self.driver.page_source\n","repo_name":"shubhbit/demo-ebanq-TAF","sub_path":"app/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27135642691","text":"import re\nimport json\nfrom bson import ObjectId\nfrom flask import request, jsonify, Blueprint\nfrom server.utils import token_required\nfrom server.models import Patient, HealthOfficial, Record, PatientNotifications\nfrom flask_cors import CORS\n\nhealthOfficial = Blueprint(\"healthOfficial\", __name__)\n# CORS(healthOfficial)\n\n\n@healthOfficial.route(\"/api/healthOfficial/patients\", methods=[\"GET\", \"POST\"])\n@token_required\ndef addPatient(_id):\n if request.method == \"POST\":\n email = request.json[\"email\"]\n try:\n healthOfficial = HealthOfficial.objects(_id=ObjectId(_id)).first()\n patient = Patient.objects(email=email).first()\n\n healthOfficial.patients.append(patient._id)\n healthOfficial.save()\n\n return jsonify({\"message\": \"Patient has been added.\"}), 201\n\n except:\n return jsonify({\"message\": \"Invalid request\"}), 400\n\n if request.method == \"GET\":\n healthOfficial = HealthOfficial.objects(_id=ObjectId(_id)).first()\n patientData = list()\n for oid in healthOfficial.patients:\n data_dict = dict()\n data_dict[\"id\"] = str(oid)\n patient = Patient.objects(_id=oid).first()\n data_dict[\"name\"] = patient.name\n data_dict[\"email\"] = patient.email\n patientData.append(data_dict)\n\n return jsonify(patientData), 200\n\n\n@healthOfficial.route(\"/api/healthOfficial/patients/\", methods=[\"GET\"])\n@token_required\ndef getPatientRecords(_id, pid):\n patient = Patient.objects(_id=ObjectId(pid)).first()\n recordList = list()\n for record in patient.records:\n rdict = dict()\n rdict[\"id\"] = str(record._id)\n rdict[\"name\"] = record.name\n rdict[\"category\"] = record.category\n rdict[\"doctor\"] = record.doctor\n rdict[\"description\"] = record.description\n rdict[\"attachments\"] = record.attachments\n rdict[\"isApproved\"] = False\n\n if ObjectId(_id) in record.healthOfficials:\n rdict[\"isApproved\"] = True\n\n recordList.append(rdict)\n\n return (\n jsonify(\n {\n \"id\": str(patient._id),\n \"name\": patient.name,\n \"email\": patient.email,\n \"records\": recordList,\n }\n ),\n 200,\n )\n\n\n@healthOfficial.route(\n \"/api/healthOfficial/patients//records/\", methods=[\"GET\"]\n)\n@token_required\ndef getRecords(_id, pid, rid):\n patient = Patient.objects(_id=ObjectId(pid)).first()\n rdict = dict()\n for record in patient.records:\n if record._id == ObjectId(rid):\n rdict[\"id\"] = str(record._id)\n rdict[\"name\"] = record.name\n rdict[\"category\"] = record.category\n rdict[\"doctor\"] = record.doctor\n rdict[\"description\"] = record.description\n rdict[\"attachments\"] = record.attachments\n rdict[\"isApproved\"] = False\n\n if ObjectId(_id) in record.healthOfficials:\n rdict[\"isApproved\"] = True\n\n break\n\n return jsonify(rdict), 200\n\n\n@healthOfficial.route(\"/api/healthOfficial/patients//records\", methods=[\"POST\"])\n@token_required\ndef addPatientRecord(_id, pid):\n data = request.json\n name = data[\"name\"]\n category = data[\"category\"]\n doctor = data[\"doctor\"]\n description = data[\"description\"]\n attachment = data[\"file\"]\n\n try:\n record = Record(\n name=name,\n category=category,\n doctor=doctor,\n description=description,\n attachments=[attachment],\n )\n patient = Patient.objects(_id=ObjectId(pid)).first()\n patient.records.append(record)\n\n patient.save()\n # record.save()\n\n return jsonify({\"message\": \"Record added successfully.\"}), 200\n\n except:\n return jsonify({\"message\": \"Unable to create the record.\"}), 400\n\n\n@healthOfficial.route(\"/api/healthOfficial/consultations/get\", methods=[\"GET\"])\n@token_required\ndef getRequests(_id):\n req_id = request.args.get(\"req_id\", default=None, type=str)\n healthOfficial = HealthOfficial.objects(_id=ObjectId(_id)).first()\n consultationRequests = healthOfficial.consultationRequests\n # try:\n if req_id is None: # response with all requests\n resp = []\n for crequest in consultationRequests:\n crequest = json.loads(crequest.to_json())\n resp.append(crequest)\n return jsonify(resp), 200\n\n else: # response with given req_id\n for crequest in consultationRequests:\n if crequest._id == ObjectId(req_id):\n resp = json.loads(crequest.to_json())\n return jsonify(resp), 200\n\n # except:\n return jsonify({\"message\": \"Unexpected error occurred.\"}), 500\n\n\n@healthOfficial.route(\"/api/healthOfficial/consultations/delete\", methods=[\"POST\"])\n@token_required\ndef deleteRequest(_id):\n data = request.json\n req_id = data[\"req_id\"]\n p_id = data[\"p_id\"]\n approved = data[\"approved\"]\n healthOfficial = HealthOfficial.objects(_id=ObjectId(_id)).first()\n crequests = []\n for crequest in healthOfficial.consultationRequests:\n if crequest._id == ObjectId(req_id):\n pass\n else:\n crequests.append(crequest)\n\n healthOfficial.consultationRequests = crequests\n pnotif = PatientNotifications(healthOfficial=ObjectId(_id), rtype=\"consult\")\n\n # create new patient notification\n # type = consultation\n if approved == \"True\":\n healthOfficial.patients.append(ObjectId(p_id))\n pnotif.approved = True\n\n patient = Patient.objects(_id=ObjectId(p_id)).first()\n patient.notifs.append(pnotif)\n\n patient.save()\n healthOfficial.save()\n return jsonify({\"message\": \"Request executed successfully.\"})\n","repo_name":"007vedant/Elixir-1","sub_path":"server/healthOfficial/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34230805424","text":"\"\"\"\nGet matchlists from summoner ids\n\"\"\"\n\nimport pandas as pd\nfrom riotwatcher import RiotWatcher, ApiError\nfrom pathlib import Path\n\ndf = pd.read_pickle('data/summoners.pkl')\n\nAPI_KEY = open('API-KEY')\nwatcher = RiotWatcher(API_KEY)\nregion = 'euw1'\n\nlimit = 4300000000\nprint(range(limit,0))\nfor i in range(limit,0,-1):\n try:\n match_info = watcher.match.by_id(region,i)\n print(match_info)\n except ApiError as err:\n if err.response.status_code == 429:\n # The 429 status code indicates that the user has sent too many requests\n # in a given amount of time (\"rate limiting\").\n print('Try in {} seconds.'.format(err.response.headers['Retry-After']))\n print('this retry-after is handled by default by the RiotWatcher library')\n print('future requests wait until the retry-after time passes')\n elif err.response.status_code == 404:\n print('match id not found')\n else:\n raise\n\nmatch_info = watcher.match.by_id(region,3933336270)\nprint(type(match_info))\n# print(match_info[0])\n# print(len(match_info))\nprint(match_info.keys())\nprint(match_info['participants'])\n# print(midf.shape)\n# print(midf.columns)\n# print(midf.index)\n# print(midf['gameMode'])","repo_name":"kepler471/hextech-compositor","sub_path":"get_matchlists.py","file_name":"get_matchlists.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18698589406","text":"from django.http.response import HttpResponse\nfrom django.utils.encoding import smart_str\nfrom django.views.generic.list import ListView\n\n\nclass DownloadBaseView(ListView):\n\n def get(self, request, *args, **kwargs):\n queryset = self.model.apply_search_filters(request=request)\n if request.GET.get(\"template\", None):\n download_headers = self.model.get_download_template_headers()\n download_data = self.model.prepare_download_template_data(queryset=queryset)\n else:\n download_headers = self.model.get_download_headers()\n download_data = self.model.prepare_download_data(queryset=queryset)\n\n downloader_class = self.model.get_downloader_class()\n\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(\n self.model.get_download_file_name() + \".xlsx\")\n\n downloader = downloader_class(writer=self.model.get_writter_class())\n response = downloader.download(data=download_data, headers=download_headers, response=response)\n if response:\n return response\n return HttpResponse(\"Download Failed\")","repo_name":"codenginebd/obr","sub_path":"bradmin/views/download_base_view.py","file_name":"download_base_view.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8416564664","text":"n=int(input())\ns=0\nr=0\nk=n\nwhile n>0:\n d=n%10\n s=s+d\n n=n//10\ntemp=s\n#print(temp)\nwhile s>0:\n m=s%10\n r=r*10+m\n s=s//10\ntemp1=r\n#print(temp1)\nif temp==temp1:\n print(\"YES\")\nelse:\n print(\"NO\")\n","repo_name":"AishwaryaKaminiRajendran/hunter","sub_path":"40.py","file_name":"40.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27752846959","text":"#!/usr/bin/python\nimport os\nfrom re import S\nimport sys\npyFileDir = os.path.dirname(os.path.abspath(__file__))+\"/\"\nsys.path.append(pyFileDir)\nfrom commonfun import *\nfrom projectInI import *\nfrom analyze_dbc_file import *\n\nclass Analyze(object):\n def __init__(self,dbc_dir=None) :\n self.AnalyzeDict={}\n self.AnalyzeDictlist=[]\n for (dirpath,dirnames,filenames) in os.walk(dbc_dir):\n for oriName in filenames:\n if \".dbc\" in oriName and dirpath == dbc_dir:\n dbc_file = f'{dirpath}/{oriName}'\n oriBaseName = oriName.split(\".\")[0]\n can_Channel = oriBaseName.split(\"_\")[0]\n dbc = AnalyzeFile(dbc_file,can_Channel)\n self.AnalyzeDict[can_Channel] = dbc\n if can_Channel == main_can:\n self.AnalyzeDictlist.insert(0,dbc)\n else:\n self.AnalyzeDictlist.append(dbc)\n\n def getAnalyzeSingleByName(self,sigName,sender=\"\"):\n existdbc=None\n for dbc in self.AnalyzeDictlist:\n assert isinstance(dbc,AnalyzeFile)\n if dbc.sigExist(sigName):\n existdbc = dbc\n if sender==\"\" or dbc.sender(sigName) == sender:\n return dbc\n if existdbc != None:\n return existdbc\n dbc = self.AnalyzeDictlist[0]\n return dbc\n\n def getAnalyzeSingleByMessageId(self,mesId):\n for dbc in self.AnalyzeDictlist:\n assert isinstance(dbc,AnalyzeFile)\n if dbc.getMessage(mesId) != None:\n return dbc\n dbc = self.AnalyzeDictlist[0]\n return dbc\n\n def getAnalyzeSingleBySigInfo(self,sig):\n assert isinstance(sig,SigInfo)\n can_Channel = SubNet_Channel.get(sig.subNet,SubNet_Channel.get(\"Other\"))\n dbc = self.AnalyzeDict.get(can_Channel,None)\n if dbc == None:\n printYellow(f\"{sig.name}没有对应的dbc,can_Channel为{can_Channel} {self.AnalyzeDictlist}\")\n dbc = self.AnalyzeDictlist[0]\n else:\n assert isinstance(dbc,AnalyzeFile)\n return dbc\n\n def GetChannelSig(self,*sigs):\n channelSig={}\n allSigs=[]\n for sig in sigs:\n if type(sig) == tuple:\n for childSig in sig:\n if type(childSig) == list:\n allSigs.extend(list(childSig))\n else:\n allSigs.append(childSig)\n else:\n allSigs.append(sig)\n\n for sig in allSigs:\n if type(sig) == SigInfo:\n assert isinstance(sig,SigInfo)\n dbc = self.getAnalyzeSingleBySigInfo(sig)\n sigInfo = sig\n else:\n dbc = self.getAnalyzeSingleByName(sig)\n sigInfo = dbc.getSig(sig)\n if dbc not in channelSig:\n channelSig[dbc] = []\n channelSig[dbc].append(sigInfo)\n return channelSig\n\n def getAnalyzeSingleByMsgInfo(self,msg):\n assert isinstance(msg,MessageInfo)\n can_Channel = SubNet_Channel.get(msg.subNet,SubNet_Channel.get(\"Other\"))\n print(can_Channel, self.AnalyzeDict)\n dbc = self.AnalyzeDict.get(can_Channel,None)\n assert isinstance(dbc,AnalyzeFile)\n return dbc\n\n def GetChannelMsg(self,channel=\"\",*msgs):\n channelSig={}\n allMags=[]\n for msg in msgs:\n if type(msg) == tuple:\n for childMsg in msg:\n if type(childMsg) == list:\n allMags.extend(list(childMsg))\n else:\n allMags.append(childMsg)\n else:\n allMags.append(msg)\n\n for msg in allMags:\n if type(msg) == MessageInfo:\n assert isinstance(msg,MessageInfo)\n dbc = self.getAnalyzeSingleByMsgInfo(msg)\n msgInfo = msg\n else:\n dbc=None\n if len(channel) != 0:\n dbc = self.AnalyzeDict.get(channel,None)\n if dbc == None:\n dbc = self.getAnalyzeSingleByMessageId(msg)\n msgInfo = dbc.getMessage(msg)\n if msgInfo == None:\n continue\n assert isinstance(msgInfo,MessageInfo)\n if dbc not in channelSig:\n channelSig[dbc] = []\n channelSig[dbc].append(msgInfo)\n return channelSig,allMags\n\n def getSig(self,sigName,sender=\"\"):\n dbc = self.getAnalyzeSingleByName(sigName,sender)\n if dbc != None:\n return dbc.getSig(sigName)\n return None\n \n def sigExist(self,sigName):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.sigExist(sigName)\n return False\n\n def sender(self,sigName):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.sender(sigName)\n return ''\n\n def getMessage_Id_BySig(self,sigName):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.getMessage_Id_BySig(sigName)\n return ''\n\n def getAllMessage(self):\n msgInfos = {}\n for can_Channel in self.AnalyzeDict:\n dbc = self.AnalyzeDict[can_Channel]\n assert isinstance(dbc,AnalyzeFile)\n msgInfos[can_Channel] = dbc.getAllMessage()\n return msgInfos\n \n #得到所有的msginfo,不区分can_Channel\n def getAllMessageInfo(self):\n msgInfos = []\n for can_Channel in self.AnalyzeDict:\n dbc = self.AnalyzeDict[can_Channel]\n assert isinstance(dbc,AnalyzeFile)\n msgInfos.extend(dbc.getAllMessage().values())\n return msgInfos\n\n #通过msgId获取所有的dbc中信号\n def getSigsByMsgId(self,msgId):\n singInfos = []\n for can_Channel in self.AnalyzeDict:\n dbc = self.AnalyzeDict[can_Channel]\n assert isinstance(dbc,AnalyzeFile)\n singInfos.extend(dbc.getSigsByMessageId(msgId))\n return singInfos\n\n def getMessage_Id_Sig(self,sigName):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.getMessage_Id_Sig(sigName)\n return ''\n\n def getSigDataType(self,sigName):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.getSigDataType(sigName)\n return ''\n \n def physicalValueVaild(self,sigName,value):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.physicalValueVaild(sigName,value)\n return False\n \n def writeSig(self,sig,msg):\n dbc = self.getAnalyzeSingleBySigInfo(sig)\n if dbc != None: \n return dbc.writeSig(sig,msg)\n return WriteDBCResult.NoMessage\n \n def repalceSigEnum(self,*sigs):\n channelSig= self.GetChannelSig(sigs)\n for dbc in channelSig.keys():\n if dbc != None:\n assert isinstance(dbc,AnalyzeFile)\n dbc.repalceSigEnum(channelSig[dbc])\n \n def repalceSig(self,*sigs,msg):\n channelSig= self.GetChannelSig(sigs)\n for dbc in channelSig.keys():\n if dbc != None:\n assert isinstance(dbc,AnalyzeFile)\n dbc.repalceSig(channelSig[dbc],msg)\n\n def removeSig(self,*sigs):\n channelSig= self.GetChannelSig(sigs)\n for dbc in channelSig.keys():\n if dbc != None:\n assert isinstance(dbc,AnalyzeFile)\n dbc.removeSig(channelSig[dbc])\n\n def removeMessage(self,channal,*mags):\n channelMsg,mags= self.GetChannelMsg(channal,mags)\n for dbc in channelMsg.keys():\n if dbc != None:\n assert isinstance(dbc,AnalyzeFile)\n dbc.removeMessage(channelMsg[dbc])\n\n def repalceMessage(self,*msgs):\n channelMsg,msgs= self.GetChannelMsg(\"\",msgs)\n for dbc,dbcMsg in channelMsg.items():\n if dbc != None:\n assert isinstance(dbc,AnalyzeFile)\n dbc.repalceMessage(list(dbcMsg))\n\n def isLocateSend(self,sigName):\n dbc = self.getAnalyzeSingleByName(sigName)\n if dbc != None:\n return dbc.isLocateSend(sigName)\n return False","repo_name":"zcx01/Achievement","sub_path":"pythonscript/analyze_dbc/analyze_dbc.py","file_name":"analyze_dbc.py","file_ext":"py","file_size_in_byte":8425,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"19892206877","text":"import django_filters\nfrom django_filters import DateFilter, CharFilter\nfrom django.db import models\nfrom django import forms\nfrom studentinfo.models import StudentBasicInfo\nfrom .models import DeleteRecords\n\nimport datetime\ndef get_session():\n years = []\n for year in range(2016, (datetime.datetime.now().year+1)):\n years.append((str(year)+'-'+str(year+1),str(year)+'-'+str(year+1)))\n return years\n\n\nclass RecordFilter(django_filters.FilterSet):\n \n #session = forms.ChoiceField(choices=get_session(),widget =forms.Select(attrs={'class':'form-control'}))\n class Meta:\n model = StudentBasicInfo\n fields = ['session','department_name','semester']\n filter_overrides = {\n models.CharField: {\n 'filter_class': django_filters.ChoiceFilter,\n 'extra': lambda f: {\n 'choices':get_session(),\n 'widget':forms.Select(attrs={'class':'form-control'}) \n },\n },\n }\n \nclass DeleteFilter(django_filters.FilterSet):\n name=CharFilter(field_name='name',lookup_expr='icontains')\n \n\n","repo_name":"Bidyut316/Student-Information-Management-System","sub_path":"AdminTask/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7843250344","text":"# Project Euler Problem 3\nimport numpy as np\n\ndef is_prime(n):\n if n % 2 == 0 and n > 2:\n return False\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n if n % i == 0:\n return False\n return True\n\ndef sieve(limit):\n primes = []\n multiples = set()\n for i in range(2, limit+1):\n if i not in multiples:\n primes.append(i)\n multiples.update(range(i*i, limit+1, i))\n\n return primes\n\ndef primeFactor(n):\n primes = []\n if n < 2:\n return primes\n for p in sieve(int(np.sqrt(n))):\n if p * p > n:\n break\n while n % p == 0:\n primes.append(p)\n n //= p\n if n > 1:\n primes.append(n)\n\n return primes\n\ndef primeFactor2(n):\n primes = []\n while n % 2 == 0:\n primes.append(2)\n n /= 2\n\n for i in range(3, int(np.floor(np.sqrt(n))), 2):\n while n % i == 0:\n primes.append(i)\n n /= i\n\n if n > 2:\n primes.append(n)\n\n return primes\n\n\n\nprint(primeFactor2(600851475143)[-1])\n","repo_name":"sgeller98/project_euler","sub_path":"Solved/Problem_003.py","file_name":"Problem_003.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17663886284","text":"import unittest\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom numpy.testing import assert_array_equal\nfrom scipy.sparse import csc_matrix\n\nfrom orangecontrib.text.util import chunks, np_sp_sum, Sparse2CorpusSliceable\n\n\nclass ChunksTest(unittest.TestCase):\n\n def test_results(self):\n self.assertEqual(list(chunks([], 10)), [])\n self.assertEqual(list(chunks([1, 2], 3)), [[1, 2]])\n self.assertEqual(list(chunks([1, 2], 1)), [[1], [2]])\n\n def test_size(self):\n for chunk in chunks(range(10), 2):\n self.assertEqual(len(chunk), 2)\n\n for chunk in chunks(range(10), 3):\n pass\n self.assertEqual(len(chunk), 1)\n\n\nclass TestNpSpSum(unittest.TestCase):\n def test_np_sp_sum(self):\n for data in [np.eye(10), sp.csr_matrix(np.eye(10))]:\n self.assertEqual(np_sp_sum(data), 10)\n np.testing.assert_equal(np_sp_sum(data, axis=1), np.ones(10))\n np.testing.assert_equal(np_sp_sum(data, axis=0), np.ones(10))\n\n\nclass TestSparse2CorpusSliceable(unittest.TestCase):\n def setUp(self) -> None:\n self.orig_array = np.array([[1, 2, 3], [4, 5, 6]])\n self.s2c = Sparse2CorpusSliceable(csc_matrix(self.orig_array))\n\n def test_slice(self):\n assert_array_equal(self.s2c[:2].sparse.toarray(), self.orig_array[:, :2])\n assert_array_equal(self.s2c[1:3].sparse.toarray(), self.orig_array[:, 1:3])\n\n def test_index(self):\n assert_array_equal(self.s2c[1].sparse.toarray(), self.orig_array[:, [1]])\n\n def test_list_of_indices(self):\n assert_array_equal(\n self.s2c[[1, 2]].sparse.toarray(), self.orig_array[:, [1, 2]]\n )\n assert_array_equal(self.s2c[[1]].sparse.toarray(), self.orig_array[:, [1]])\n\n def test_ndarray(self):\n assert_array_equal(\n self.s2c[np.array([1, 2])].sparse.toarray(), self.orig_array[:, [1, 2]]\n )\n assert_array_equal(\n self.s2c[np.array([1])].sparse.toarray(), self.orig_array[:, [1]]\n )\n\n def test_range(self):\n assert_array_equal(\n self.s2c[range(1, 3)].sparse.toarray(), self.orig_array[:, [1, 2]]\n )\n assert_array_equal(\n self.s2c[range(1, 2)].sparse.toarray(), self.orig_array[:, [1]]\n )\n\n def test_elipsis(self):\n assert_array_equal(self.s2c[...].sparse.toarray(), self.orig_array)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"34078920050","text":"\"\"\"\r\nWatchtower Web Server\r\n\"\"\"\r\n\r\n__author__ = 'Enis Simsar'\r\n\r\nimport json\r\n\r\nfrom models.Invitation import InvitationSchema\r\nfrom models.News import NewsSchema\r\nfrom models.Topic import TopicSchema\r\nfrom models.Tweet import TweetSchema\r\nfrom models.User import UserSchema, User, hash_password\r\n\r\nimport tornado.ioloop\r\nfrom tornado.options import options\r\nimport tornado.web\r\n\r\nfrom decouple import config\r\nfrom settings import app_settings\r\n\r\nfrom urls import url_patterns\r\nfrom logging import handlers\r\nimport logging\r\nfrom mongoengine import connect, DoesNotExist\r\nimport time\r\nimport os\r\n\r\nfrom apispec import APISpec\r\nfrom apispec.ext.tornado import TornadoPlugin\r\nfrom apispec.ext.marshmallow import MarshmallowPlugin\r\n\r\nos.makedirs('./logs', exist_ok=True)\r\n\r\nlog_file = \"./logs/daily_\" + time.strftime(\"%d-%m-%Y\") + \".log\"\r\n\r\ndaily_handler = handlers.TimedRotatingFileHandler(\r\n log_file,\r\n when='midnight',\r\n interval=1,\r\n backupCount=7\r\n)\r\n\r\nlogging.basicConfig(\r\n level=logging.INFO,\r\n format=\"[%(levelname)s %(asctime)s %(pathname)s@%(funcName)s:%(lineno)s] %(message)s\",\r\n datefmt=\"%d/%m/%Y %H:%M:%S\",\r\n handlers=[\r\n daily_handler,\r\n logging.StreamHandler()\r\n ],\r\n)\r\n\r\nspec = APISpec(\r\n title='WatchTower News API',\r\n version='1.0.0',\r\n openapi_version='2.0',\r\n plugins=(\r\n TornadoPlugin(),\r\n MarshmallowPlugin(),\r\n ),\r\n info=dict(\r\n description='Default api token is \"welcome_to_watchtower_news_api\" Please, add this token to your header '\r\n 'X-API-Key: \"welcome_to_watchtower_news_api\" '\r\n ),\r\n securityDefinitions=dict(\r\n apiKey={\r\n 'type': 'apiKey',\r\n 'name': 'X-API-Key',\r\n 'in': 'header',\r\n 'description': 'API Key for Authorization'\r\n }\r\n ),\r\n options={\r\n 'consumes': ['application/json'],\r\n 'produces': ['application/json']\r\n }\r\n)\r\n\r\n# spec.definition('User', schema=UserSchema)\r\nspec.definition('Topic', schema=TopicSchema)\r\n# spec.definition('Invitation', schema=InvitationSchema)\r\nspec.definition('News', schema=NewsSchema)\r\n# spec.definition('Tweet', schema=TweetSchema)\r\n\r\nfor url_path in url_patterns:\r\n if 'api' in url_path[0]:\r\n spec.add_path(urlspec=url_path)\r\n continue\r\n\r\nwith open('./static/data.json', 'w') as outfile:\r\n json.dump(spec.to_dict(), outfile)\r\n\r\n\r\ndef add_admin_user():\r\n data = {\r\n 'username': 'admin',\r\n 'password': hash_password('123456'),\r\n 'api_token': 'welcome_to_watchtower_news_api'\r\n }\r\n try:\r\n user = User(**data)\r\n user.save()\r\n except Exception as e:\r\n logging.error(\"exception: {0}\".format(str(e)))\r\n\r\n\r\nclass WatchtowerNewsApp(tornado.web.Application):\r\n def __init__(self, testing=False):\r\n super(WatchtowerNewsApp, self).__init__(url_patterns, **app_settings, autoreload=not testing)\r\n\r\n\r\ndef main():\r\n options.parse_command_line()\r\n\r\n logging.getLogger('tornado.access').disabled = True\r\n\r\n app = WatchtowerNewsApp()\r\n app.listen(app_settings[\"port\"])\r\n\r\n connect(\r\n config('MONGODB_DB'),\r\n username=config('MONGODB_USER'),\r\n password=config('MONGODB_PASSWORD'),\r\n host=config('MONGODB_HOST'),\r\n port=config('MONGODB_PORT', cast=int),\r\n authentication_source='admin',\r\n connect=False\r\n )\r\n\r\n try:\r\n u = User.objects.filter(username='admin')\r\n if not len(u):\r\n add_admin_user()\r\n except DoesNotExist:\r\n add_admin_user()\r\n except Exception as e:\r\n pass\r\n\r\n tornado.ioloop.IOLoop.current().start()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"openmaker-eu/watchtower-news","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"70764462884","text":"import pandas as pd\nimport numpy as np\n\n#Membaca data train dan data uji dari file excel\ntrain_data = pd.read_excel(\"abalone.xlsx\")\ntest_data = pd.read_excel(\"data_uji.xlsx\")\n\n# Memisahkan fitur (atribut) dan label dari data train dan data uji\nX_train = train_data.iloc[:, :-1].values\ny_train = train_data.iloc[:, -1].values\nX_test = test_data.iloc[:, :-1].values\ny_test = test_data.iloc[:, -1].values\n\n# Menentukan jumlah tetangga terdekat (k) yang akan digunakan dalam model KNN\nk = 59\n\n# Function untuk menghitung jarak antara data uji dan data train\ndef compute_distance(x1, x2):\n distance = np.sqrt(np.sum((x1 - x2)**2))\n return distance\n\n# Membuat list untuk menyimpan hasil prediksi\ny_pred = []\n\n# Loop untuk setiap data uji\nfor i in range(len(X_test)):\n # Membuat list untuk menyimpan jarak antara data uji dan data train\n distances = []\n # Loop untuk setiap data train\n for j in range(len(X_train)):\n # Menghitung jarak antara data uji dan data train\n distance = compute_distance(X_test[i], X_train[j])\n distances.append([distance, j])\n # Mengurutkan jarak dari yang terkecil\n distances = sorted(distances)\n # Membuat list untuk menyimpan kelas dari k tetangga terdekat\n classes = []\n # Loop untuk k tetangga terdekat\n for j in range(k):\n # Menambahkan kelas dari tetangga ke dalam list\n classes.append(y_train[distances[j][1]])\n # Menentukan kelas dari data uji berdasarkan kelas dari k tetangga terdekat\n y_pred.append(max(set(classes), key = classes.count))\n\n# Menghitung akurasi\ncorrect = 0\nfor i in range(len(y_test)):\n if y_test[i] == y_pred[i]:\n correct += 1\naccuracy = correct / len(y_test)\nprint(\"Accuracy: \", accuracy)\n# print((len(X_test)))","repo_name":"bdrsmsdn/KNN-Implementation","sub_path":"kn4.py","file_name":"kn4.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44894153728","text":"# -*- mode: python -*-\n\nblock_cipher = None\n\n\na = Analysis(['timetable_universal.py'],\n pathex=[''],\n binaries=None,\n datas=None,\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher)\n\na.datas += [('icons/left-arrow.png', 'icons/left-arrow.png', 'DATA')]\na.datas += [('icons/right-arrow.png', 'icons/right-arrow.png', 'DATA')]\na.datas += [('style.qss', 'style.qss', 'DATA')]\n\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n name='timetable_universal',\n debug=False,\n strip=False,\n upx=True,\n console=False )\napp = BUNDLE(exe,\n name='timetable_universal.app',\n icon=None,\n bundle_identifier=None)\n","repo_name":"Giannie/Timetable-Parser","sub_path":"timetable_universal_example.spec","file_name":"timetable_universal_example.spec","file_ext":"spec","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12251557870","text":"from flask import Flask, render_template, request, redirect, jsonify\nimport hashlib, sqlite3, base64\n\napp = Flask(__name__)\n\nname = \"URL Shortening Service\"\n\n\n@app.route(\"/shortner\")\ndef url_shortner():\n url = request.args.get('url')\n #We have to check if its already exists in database\n lastID = last()\n integer_bytes = lastID.to_bytes((lastID.bit_length() + 7) // 8, byteorder='big')\n base64_encoded = base64.b64encode(integer_bytes).decode('utf-8')\n\n connect = sqlite3.connect('database.db')\n connect.execute('INSERT into data(url,shortenURL )VALUES(?, ?)', (url, base64_encoded))\n connect.commit()\n\n return \"http://localhost:5000?url=\"+base64_encoded\n\n\n@app.route(\"/\")\ndef index():\n base64 = request.args.get('url')\n if base64:\n #Fetching original url\n connect = sqlite3.connect('database.db')\n cursor = connect.execute('SELECT url FROM data WHERE shortenURL = ?', (base64,))\n url = cursor.fetchone()\n connect.close()\n \n return redirect('http://'+url[0])\n #render_template(\"index.html\", name=url[0])\n else:\n return render_template(\"index.html\") \n \n \n\n\n\n@app.route(\"/show\")\ndef show():\n connect = sqlite3.connect('database.db')\n cursor = connect.execute(\"SELECT * FROM data\")\n rows = cursor.fetchall()\n connect.close()\n return render_template(\"show.html\", rows=rows) \n\n\ndef last():\n connect = sqlite3.connect('database.db')\n cursor = connect.execute(\"SELECT COUNT(*) from data\")\n rows = cursor.fetchall()\n connect.close()\n return rows[0][0]\n","repo_name":"Poras-oss/URL-Shortner","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2628112458","text":"# Aditya Casturi, Henry Zhu, Honors Precalculus, 26 May 2023\n# A program to evaluate trignometric functions using the polynomial derivate of sin(x)\n\nfrom numpy import pi as PI\n\n\ndef fitAngleToRange(angle):\n \"\"\"\n Maps an angle value to an equivalent angle value within the range of 0 to PI/4.\n\n Args:\n angle (float): The angle value to be mapped.\n\n Returns:\n float: The equivalent angle value within the range of 0 to PI/4.\n \"\"\"\n angle = angle % (2 * PI)\n if 0 <= angle <= PI / 4:\n return angle\n if PI / 4 < angle <= PI / 2:\n return PI / 2 - angle\n if PI / 2 < angle <= 3 * PI / 4:\n return angle - PI / 2\n if 3 * PI / 4 < angle <= PI:\n return PI - angle\n if PI < angle <= 5 * PI / 4:\n return angle - PI\n if 5 * PI / 4 < angle <= 3 * PI / 2:\n return 3 * PI / 2 - angle\n if 3 * PI / 2 < angle <= 7 * PI / 4:\n return angle - 3 * PI / 2\n if 7 * PI / 4 < angle <= 2 * PI:\n return 2 * PI - angle\n\n\ndef adjustSine(angle, sinValue):\n \"\"\"\n Maps a sine value back to the original sine value before it was transformed by the fitAngleToRange function.\n\n Args:\n angle (float): The original angle value before it was transformed by the fitAngleToRange function.\n sinValue (float): The sine value to be mapped back to the original sine value.\n\n Returns:\n float: The original sine value before it was transformed by the fitAngleToRange function.\n \"\"\"\n theta = angle % (2 * PI)\n if 0 <= theta <= PI / 4:\n return sinValue\n if PI / 4 < theta <= PI / 2:\n return cos(angle, sinValue)\n if PI / 2 < theta <= 3 * PI / 4:\n return -cos(angle, sinValue)\n if 3 * PI / 4 < theta <= PI:\n return sinValue\n if PI < theta <= 5 * PI / 4:\n return -sinValue\n if 5 * PI / 4 < theta <= 3 * PI / 2:\n return cos(angle, sinValue)\n if 3 * PI / 2 < theta <= 7 * PI / 4:\n return -cos(angle, sinValue)\n if 7 * PI / 4 < theta <= 2 * PI:\n return -sinValue\n\n\ndef sin(angle):\n \"\"\"\n Calculates the sine of an angle value using a polynomial expression.\n\n Args:\n angle (float): The angle value in radians.\n\n Returns:\n float: The sine of the angle value.\n \"\"\"\n inputAngle = fitAngleToRange(angle)\n assert inputAngle is not None\n result = 0\n\n for n in range(15):\n term = (-1) ** n\n term *= inputAngle ** (1 + 2 * n)\n term /= factorial(1 + 2 * n)\n result += term\n\n return adjustSine(angle, result)\n\n\ndef cos(angle, sinValue):\n \"\"\"\n Calculates the cosine of an angle value using the sine value and the quadrant of the angle.\n\n Args:\n angle (float): The angle value in radians.\n sinValue (float): The sine of the angle value.\n\n Returns:\n float: The cosine of the angle value.\n \"\"\"\n angle = angle % (2 * PI)\n\n if PI / 2 < angle < 3 * PI / 2:\n cos = -(1 - sinValue ** 2) ** (1 / 2)\n else:\n cos = (1 - sinValue ** 2) ** (1 / 2)\n\n return cos\n\n\ndef tan(angle):\n \"\"\"\n Calculates the tangent of an angle value using the sine and cosine functions.\n\n Args:\n angle (float): The angle value in radians.\n\n Returns:\n float: The tangent of the angle value.\n \"\"\"\n return sin(angle) / cos(angle, sin(angle))\n\n\ndef factorial(n):\n \"\"\"\n Calculates the factorial of a non-negative integer.\n\n Args:\n n (int): The non-negative integer to calculate the factorial of.\n\n Returns:\n int: The factorial of the input integer.\n \"\"\"\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\n\ndef evaluateAndPrintOutput(angle, functionChoice):\n \"\"\"\n Evaluates the trigonometric function specified by the input `functionChoice` for the given `angle`, and prints the result.\n\n Args:\n angle (float): The angle value in radians.\n functionChoice (int): The integer value representing the trigonometric function to evaluate. \n 1 for sine, 2 for cosine, 3 for tangent.\n\n Returns:\n None\n \"\"\"\n if (functionChoice == 1):\n print(\"\\nsin(x) = \", sin(angle))\n elif (functionChoice == 2):\n print(\"\\ncos(x) = \", cos(angle, sin(angle)))\n else:\n if round(cos(angle, sin(angle)), 5) == 0:\n print(\"\\ntan(x) = undefined\")\n else:\n print(\"\\ntan(x) = \", tan(angle))\n\n\ndef main():\n \"\"\"\n Prompts the user to enter an angle value and a trigonometric function choice, \n and evaluates and prints the result of the selected function for the given angle.\n\n Args:\n None\n\n Returns:\n None\n \"\"\"\n print(\"This program finds the values of trigonometric functions. \\n1. sin(x) \\n2. cos(x) \\n3. tan(x)\\n\")\n\n functionChoice = int(\n input(\"Enter the number of the function you want to evaluate: \"))\n while functionChoice > 3 or functionChoice < 1:\n functionChoice = int(input(\"Invalid input; try again: \"))\n angle = float(input(\"\\nEnter the angle x in radians: \"))\n\n evaluateAndPrintOutput(angle, functionChoice)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"aditya-casturi/ApproximatingTrigFunctions","sub_path":"ApproximatingTrigFunctions.py","file_name":"ApproximatingTrigFunctions.py","file_ext":"py","file_size_in_byte":5151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75352205284","text":"import random\n\nc = int(input(\"Cantidad de casos de test\\n\"))\nnombre = input(\"Nombre de archivo\\n\")\n\nwith open(f\"./{nombre}.txt\", \"w\") as archivo:\n lineas = [f\"{c}\\n\"]\n\n n_usado = set()\n for i in range(c):\n\n while True:\n N = random.randint(1, 20000)\n if N not in n_usado:\n n_usado.add(N)\n break\n\n lineas.append(\"{}\\n\".format(N))\n\n for j in range(N):\n inicio = random.randint(1, 2*N-1)\n fin = random.randint(inicio, 2*N-1)\n lineas.append(\"{} {}\\n\".format(inicio, fin))\n\n archivo.writelines(lineas)","repo_name":"LeoBrasileo/AyED3-TPS","sub_path":"TP1/Ej3/Experimentos/inputs/generar_random.py","file_name":"generar_random.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14811821857","text":"#!/usr/bin/env python\nimport os\nimport json\n# Terraform modules\nfrom constructs import Construct\nfrom cdktf import App, TerraformStack, RemoteBackend, NamedRemoteWorkspace, TerraformOutput\nfrom cdktf_cdktf_provider_aws.provider import AwsProvider\n# Dynamodb modules\nfrom cdktf_cdktf_provider_aws.dynamodb_table import DynamodbTable\n# Lambda function modules\nfrom cdktf_cdktf_provider_aws.lambda_function import LambdaFunction, LambdaFunctionEnvironment\nfrom cdktf_cdktf_provider_aws.lambda_event_source_mapping import LambdaEventSourceMapping\n# Opensearch modules\nfrom cdktf_cdktf_provider_aws.opensearch_domain import OpensearchDomain, OpensearchDomainDomainEndpointOptions, OpensearchDomainEbsOptions\n# IAM modules\nfrom cdktf_cdktf_provider_aws.iam_role import IamRole\nfrom cdktf_cdktf_provider_aws.iam_policy import IamPolicy\nfrom cdktf_cdktf_provider_aws.iam_role_policy_attachment import IamRolePolicyAttachment\n# Monitoring modules\nfrom cdktf_cdktf_provider_aws.cloudwatch_metric_alarm import CloudwatchMetricAlarm\nfrom cdktf_cdktf_provider_aws.cloudwatch_log_group import CloudwatchLogGroup\n\n\n# AWS variables\nAWS_REGION = os.environ.get(\"AWS_REGION\", \"us-east-1\")\nAccount_ID = os.environ.get(\"ACCOUNT_ID\", \"865227664036\")\n\n# IAM variables\nwith open(os.path.abspath('policy.json')) as policy_doc:\n Policy_doc = json.load(policy_doc)\nwith open(os.path.abspath('lambda_assume_policy.json')) as policy_doc:\n Assume_policy = json.load(policy_doc)\nwith open(os.path.abspath('opensearch_policy.json')) as policy_doc:\n Opensearch_policy = json.load(policy_doc)\n\nIAM_resource_ID = \"lambda-opensearch-dynamdb\"\nIAM_policy_name = f\"{IAM_resource_ID}-iam\"\nIAM_role_name = f\"{IAM_resource_ID}-role\"\n\n# Vpc variables\nVpc_configs_lambda = {\n \"subnet_ids\": [\"subnet-01623eca4025f6072\"],\n \"security_group_ids\": [\"sg-0985519ebe26980da\"]\n}\nVpc_configs_opensearch = {\n \"subnet_ids\": [\"subnet-01623eca4025f6072\"],\n \"security_group_ids\": [\"sg-0d62ff1ebe26cd0d5\"]\n}\n\n# DynamoDB varialbes\nDynamoDB_Table = \"GameScores\"\nDynamoDB_Billing = \"PAY_PER_REQUEST\"\nDynamoDB_Partion_Key = 'UserId'\nDynamoDB_Sortkey = 'GameTitle'\nDynamoDB_Attribute_Type = 'S'\n\n# Lambda function vars\nLambda_Function_Name = \"dynamodbStreamFunction\"\nLambda_Function_Handler = \"sample.handler\"\nLambda_Function_Payload = \"lambda-opensearch.zip\"\nLambda_Function_Timeout = 30\nLambda_log_retention = 3\nLambda_Function_Log_Group = f\"/aws/lambda/{Lambda_Function_Name}\"\n\n\n# Opensearch variables\nOpensearch_domain = \"gamescores-domain\"\nOpensearch_version = \"OpenSearch_2.3\"\nOpensearch_instance_type = \"t3.small.search\"\nOpensearch_data_node_count = 1\nOpnesearch_dedicated_master_count = 0\nOpensearch_dedicated_master_enabled = False\nOpensearch_zone_awareness_enabled = False\nOpensearch_ebs_enabled = True\nOpensearch_volume_size = 10\nOpensearch_enable_https = True\nOpensearch_ttl_policy = \"Policy-Min-TLS-1-2-2019-07\"\nOpensearch_cluster_config = {\n \"dedicated_master_count\": Opnesearch_dedicated_master_count,\n \"dedicated_master_enabled\": Opensearch_dedicated_master_enabled,\n \"instance_count\": Opensearch_data_node_count,\n \"instance_type\": Opensearch_instance_type,\n \"zone_awareness_enabled\": Opensearch_zone_awareness_enabled\n }\n# Cloudwatch varialbes\nOS_CW_free_storage_space_alert_threshold = int(\n max(Opensearch_volume_size - (Opensearch_volume_size * 70 / 100), 0))\n\n# def apply_opensearch_policy(opensearch_domain_arn, iam_role_arn):\n# Opensearch_policy[\"Statement\"][0][\"Resource\"] = f\"{opensearch_domain_arn}/*\"\n# Opensearch_policy[\"Statement\"][0][\"Principal\"][\"AWS\"] = iam_role_arn\n# return json.dumps(Opensearch_policy)\n\n\nclass MyStack(TerraformStack):\n def __init__(self, scope: Construct, ns: str):\n super().__init__(scope, ns)\n AwsProvider(self, \"AWS\", region=AWS_REGION)\n\n # IAM Resources\n iam_policy = IamPolicy(self,\n IAM_policy_name,\n name=IAM_policy_name,\n description='lambda to handle dynamodb stream and opensearch',\n policy=json.dumps(Policy_doc)\n )\n iam_role = IamRole(self,\n IAM_role_name,\n name=IAM_role_name,\n description='Role to give permission for lambda to access different resources',\n assume_role_policy=json.dumps(Assume_policy)\n )\n IamRolePolicyAttachment(self, \"Role-policy-attachment\",\n role=iam_role.name,\n policy_arn=iam_policy.arn\n )\n\n # Cloudwatch log group creation\n cloudwatch_log_group = CloudwatchLogGroup(\n self, \"LogGroup\", name=Lambda_Function_Log_Group, retention_in_days=Lambda_log_retention)\n\n # DynamoDB Table\n dynamodb_table = DynamodbTable(self, \"dynamodb\",\n name=DynamoDB_Table,\n billing_mode=DynamoDB_Billing,\n hash_key=DynamoDB_Partion_Key,\n range_key=DynamoDB_Sortkey,\n server_side_encryption={\n \"enabled\": True\n },\n attribute=[\n {\n \"name\": DynamoDB_Partion_Key,\n \"type\": DynamoDB_Attribute_Type\n },\n {\n \"name\": DynamoDB_Sortkey,\n \"type\": DynamoDB_Attribute_Type\n },\n ],\n stream_enabled=True,\n stream_view_type=\"NEW_AND_OLD_IMAGES\"\n )\n\n # OpenSearch Domain creation\n opensearch_domain = OpensearchDomain(self, Opensearch_domain,\n domain_name=Opensearch_domain,\n engine_version=Opensearch_version,\n vpc_options=Vpc_configs_opensearch,\n cluster_config=Opensearch_cluster_config,\n access_policies=json.dumps(\n Opensearch_policy),\n domain_endpoint_options=OpensearchDomainDomainEndpointOptions(\n enforce_https=Opensearch_enable_https,\n tls_security_policy=Opensearch_ttl_policy),\n ebs_options=OpensearchDomainEbsOptions(\n ebs_enabled=Opensearch_ebs_enabled, volume_size=Opensearch_volume_size),\n encrypt_at_rest={\n \"enabled\": True\n }\n )\n OS_CW_free_storage_space_alert = CloudwatchMetricAlarm(self, \"OS_CW_free_storage_space_too_low\",\n metric_name=\"FreeStorageSpace\",\n namespace=\"AWS/ES\",\n alarm_name=\"Opensearch_node_free_storage_space_too_low\",\n comparison_operator=\"LessThanOrEqualToThreshold\",\n evaluation_periods=1,\n period=60,\n datapoints_to_alarm=1,\n statistic=\"Minimum\",\n depends_on=[\n opensearch_domain],\n threshold=OS_CW_free_storage_space_alert_threshold,\n dimensions={\n \"DomainName\": opensearch_domain.domain_name\n },\n actions_enabled=True,\n alarm_actions=[\n \"arn:aws:sns:us-east-1:865227664036:Default_CloudWatch_Alarms_Topic\"],\n ok_actions=[\n \"arn:aws:sns:us-east-1:865227664036:Default_CloudWatch_Alarms_Topic\"],\n alarm_description=f\"Minimum free disk space on a single node under above 70%. Current space: {OS_CW_free_storage_space_alert_threshold} GB\")\n\n DDB_CW_table_throttle_alert = CloudwatchMetricAlarm(self, \"DDB_CW_table_throttle_\",\n alarm_name=f\"{dynamodb_table.name}_throttle\",\n alarm_description=f\"Requests are being throttled to the {dynamodb_table.name} table\",\n metric_name=\"ThrottledRequests\",\n namespace=\"AWS/DynamoDB\",\n comparison_operator=\"GreaterThanThreshold\",\n evaluation_periods=1,\n period=60,\n statistic=\"Sum\",\n depends_on=[\n dynamodb_table\n ],\n threshold=0,\n dimensions={\n \"TableName\": dynamodb_table.name\n },\n actions_enabled=True,\n alarm_actions=[\n \"arn:aws:sns:us-east-1:865227664036:Default_CloudWatch_Alarms_Topic\"],\n ok_actions=[\n \"arn:aws:sns:us-east-1:865227664036:Default_CloudWatch_Alarms_Topic\"]\n )\n\n # Lambda function creation\n lambda_function = LambdaFunction(self, Lambda_Function_Name,\n function_name=Lambda_Function_Name,\n runtime=\"python3.8\",\n handler=Lambda_Function_Handler,\n filename=os.path.abspath(\n Lambda_Function_Payload),\n role=iam_role.arn,\n environment=LambdaFunctionEnvironment(\n variables={\n \"ENDPOINT\": f\"https://{opensearch_domain.endpoint}\"\n }\n ),\n publish=True,\n timeout=Lambda_Function_Timeout,\n depends_on=[opensearch_domain],\n vpc_config=Vpc_configs_lambda,\n )\n\n # DynamoDB Stream event source mapping\n dynamdb_stream_lambda = LambdaEventSourceMapping(self, \"lambd_function_stream_trigger\",\n function_name=lambda_function.function_name,\n event_source_arn=dynamodb_table.stream_arn,\n starting_position=\"LATEST\"\n )\n \n # Add dynamdb arn and opensearch arn to policy\n Policy_doc['Statement'][1]['Resource'].append(\n f\"{opensearch_domain.arn}/*\")\n Policy_doc['Statement'][1]['Resource'].append(\n dynamodb_table.stream_arn)\n Policy_doc['Statement'][2]['Resource'] = f\"{cloudwatch_log_group.arn}:*\"\n iam_policy.policy = json.dumps(Policy_doc)\n\n\napp = App()\nstack = MyStack(app, \"learn-cdktf-dynamdb\")\n\n# RemoteBackend(stack,\n# hostname='app.terraform.io',\n# organization='example-org-8df812',\n# workspaces=NamedRemoteWorkspace('learn-cdktf-dynamdb')\n# )\n\napp.synth()\n","repo_name":"agentblacksmith/Terraform-CDK","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25342345939","text":"\"\"\"Component 2 of price comparison -\nPrice comparing of the cheapest and expensive coffee\nCreated by Francis Torcuato\n\"\"\"\n\nname = input(\"Please enter your name:\")\nprint(f\"hello {name}! - Welcome to price comparison \")\n\n# Budget of the user\nbudget = input(\"Please enter your budget: \")\nprint(f\"Your budget for coffee is ${budget}\")\n\nattempt = \"\"\nwhile not attempt != \"X\":\n unit = input(\"Enter unit to be compared:\")\n product = input(\"Please enter the product name:\")\n unit_number = input(\"Enter the number of units:\")\n price = input(\"Enter price:\")\n\n attempt = input(\"Enter 'x' if you want to compare: \")\n\ncoffee = \\\n [[\"Greggs\", 7],\n [\"Moconna\", 10.49],\n [\"Nescafe\", 7.79]]\n\ncoffee.sort()\n\ncoffee.sort(key=lambda x: x[1])\n\nfor x in coffee:\n print(f\"{coffee}\")\n","repo_name":"francis1102/Price_comparison","sub_path":"03_coffee.py","file_name":"03_coffee.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36374999139","text":"# File : PR11B_2272028.py\r\n# Penulis : Nathaniel Valentino Robert\r\n# Deskripsi :\r\n# Buatlah program yang akan menerima input\r\n# satu bilangan decimal kemudian program akan\r\n# menampilkan biner dari decimal tersebut.\r\n\r\n# Kamus Lokal\r\n# bin = var deklarasi string kosong\r\n# dec = var bilangan desimal (int)\r\ndef printBinary(dec):\r\n bin = \"\"\r\n while dec > 0:\r\n bin = str(dec % 2) + bin\r\n dec = dec // 2\r\n bin = '0' * (8 - len(bin)) + bin\r\n\r\n for i in range (0,len(bin),1):\r\n print(bin[i], end=\" \")\r\n\r\n# Kamus Lokal\r\n# dec = var input angka desimal (int)\r\ndef main():\r\n dec = int(input(\"Masukkan bilangan desimal: \"))\r\n printBinary(dec)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"nathaniel-valen/daspro","sub_path":"Pertemuan 12/PR11B_2272028.py","file_name":"PR11B_2272028.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13090100895","text":"from __future__ import print_function\nimport argparse\nimport os\nimport os.path\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport time\n\nfrom simpleperf_report_lib import *\nfrom utils import *\n\n\nclass BinaryCacheBuilder(object):\n \"\"\"Collect all binaries needed by perf.data in binary_cache.\"\"\"\n def __init__(self, config):\n config_names = ['perf_data_path', 'symfs_dirs']\n for name in config_names:\n if name not in config:\n log_exit('config for \"%s\" is missing' % name)\n\n self.perf_data_path = config.get('perf_data_path')\n if not os.path.isfile(self.perf_data_path):\n log_exit(\"can't find file %s\" % self.perf_data_path)\n self.symfs_dirs = config.get('symfs_dirs')\n for symfs_dir in self.symfs_dirs:\n if not os.path.isdir(symfs_dir):\n log_exit(\"symfs_dir '%s' is not a directory\" % symfs_dir)\n self.adb = AdbHelper(enable_switch_to_root=not config['disable_adb_root'])\n self.readelf_path = find_tool_path('readelf')\n if not self.readelf_path and self.symfs_dirs:\n log_warning(\"Debug shared libraries on host are not used because can't find readelf.\")\n self.binary_cache_dir = 'binary_cache'\n if not os.path.isdir(self.binary_cache_dir):\n os.makedirs(self.binary_cache_dir)\n\n\n def build_binary_cache(self):\n self._collect_used_binaries()\n self._copy_binaries_from_symfs_dirs()\n self._pull_binaries_from_device()\n self._pull_kernel_symbols()\n\n\n def _collect_used_binaries(self):\n \"\"\"read perf.data, collect all used binaries and their build id (if available).\"\"\"\n # A dict mapping from binary name to build_id\n binaries = dict()\n lib = ReportLib()\n lib.SetRecordFile(self.perf_data_path)\n lib.SetLogSeverity('error')\n while True:\n sample = lib.GetNextSample()\n if sample is None:\n lib.Close()\n break\n symbols = [lib.GetSymbolOfCurrentSample()]\n callchain = lib.GetCallChainOfCurrentSample()\n for i in range(callchain.nr):\n symbols.append(callchain.entries[i].symbol)\n\n for symbol in symbols:\n dso_name = symbol.dso_name\n if dso_name not in binaries:\n binaries[dso_name] = lib.GetBuildIdForPath(dso_name)\n self.binaries = binaries\n\n\n def _copy_binaries_from_symfs_dirs(self):\n \"\"\"collect all files in symfs_dirs.\"\"\"\n if not self.symfs_dirs:\n return\n\n # It is possible that the path of the binary in symfs_dirs doesn't match\n # the one recorded in perf.data. For example, a file in symfs_dirs might\n # be \"debug/arm/obj/armeabi-v7a/libsudo-game-jni.so\", but the path in\n # perf.data is \"/data/app/xxxx/lib/arm/libsudo-game-jni.so\". So we match\n # binaries if they have the same filename (like libsudo-game-jni.so)\n # and same build_id.\n\n # Map from filename to binary paths.\n filename_dict = dict()\n for binary in self.binaries:\n index = binary.rfind('/')\n filename = binary[index+1:]\n paths = filename_dict.get(filename)\n if paths is None:\n filename_dict[filename] = paths = []\n paths.append(binary)\n\n # Walk through all files in symfs_dirs, and copy matching files to build_cache.\n for symfs_dir in self.symfs_dirs:\n for root, _, files in os.walk(symfs_dir):\n for file in files:\n paths = filename_dict.get(file)\n if paths is not None:\n build_id = self._read_build_id(os.path.join(root, file))\n if not build_id:\n continue\n for binary in paths:\n expected_build_id = self.binaries.get(binary)\n if expected_build_id == build_id:\n self._copy_to_binary_cache(os.path.join(root, file),\n expected_build_id, binary)\n\n\n def _copy_to_binary_cache(self, from_path, expected_build_id, target_file):\n if target_file[0] == '/':\n target_file = target_file[1:]\n target_file = target_file.replace('/', os.sep)\n target_file = os.path.join(self.binary_cache_dir, target_file)\n if (os.path.isfile(target_file) and self._read_build_id(target_file) == expected_build_id\n and self._file_has_symbol_table(target_file)):\n # The existing file in binary_cache can provide more information, so no\n # need to copy.\n return\n target_dir = os.path.dirname(target_file)\n if not os.path.isdir(target_dir):\n os.makedirs(target_dir)\n log_info('copy to binary_cache: %s to %s' % (from_path, target_file))\n shutil.copy(from_path, target_file)\n\n\n def _pull_binaries_from_device(self):\n \"\"\"pull binaries needed in perf.data to binary_cache.\"\"\"\n for binary in self.binaries:\n build_id = self.binaries[binary]\n if binary[0] != '/' or binary == \"//anon\" or binary.startswith(\"/dev/\"):\n # [kernel.kallsyms] or unknown, or something we can't find binary.\n continue\n binary_cache_file = binary[1:].replace('/', os.sep)\n binary_cache_file = os.path.join(self.binary_cache_dir, binary_cache_file)\n self._check_and_pull_binary(binary, build_id, binary_cache_file)\n\n\n def _check_and_pull_binary(self, binary, expected_build_id, binary_cache_file):\n \"\"\"If the binary_cache_file exists and has the expected_build_id, there\n is no need to pull the binary from device. Otherwise, pull it.\n \"\"\"\n need_pull = True\n if os.path.isfile(binary_cache_file):\n need_pull = False\n if expected_build_id:\n build_id = self._read_build_id(binary_cache_file)\n if expected_build_id != build_id:\n need_pull = True\n if need_pull:\n target_dir = os.path.dirname(binary_cache_file)\n if not os.path.isdir(target_dir):\n os.makedirs(target_dir)\n if os.path.isfile(binary_cache_file):\n os.remove(binary_cache_file)\n log_info('pull file to binary_cache: %s to %s' % (binary, binary_cache_file))\n self._pull_file_from_device(binary, binary_cache_file)\n else:\n log_info('use current file in binary_cache: %s' % binary_cache_file)\n\n\n def _read_build_id(self, file):\n \"\"\"read build id of a binary on host.\"\"\"\n if not self.readelf_path:\n return \"\"\n output = subprocess.check_output([self.readelf_path, '-n', file])\n output = bytes_to_str(output)\n result = re.search(r'Build ID:\\s*(\\S+)', output)\n if result:\n build_id = result.group(1)\n if len(build_id) < 40:\n build_id += '0' * (40 - len(build_id))\n build_id = '0x' + build_id\n return build_id\n return \"\"\n\n\n def _file_has_symbol_table(self, file):\n \"\"\"Test if an elf file has symbol table section.\"\"\"\n if not self.readelf_path:\n return False\n output = subprocess.check_output([self.readelf_path, '-S', file])\n output = bytes_to_str(output)\n return '.symtab' in output\n\n\n def _pull_file_from_device(self, device_path, host_path):\n if self.adb.run(['pull', device_path, host_path]):\n return True\n # In non-root device, we can't pull /data/app/XXX/base.odex directly.\n # Instead, we can first copy the file to /data/local/tmp, then pull it.\n filename = device_path[device_path.rfind('/')+1:]\n if (self.adb.run(['shell', 'cp', device_path, '/data/local/tmp']) and\n self.adb.run(['pull', '/data/local/tmp/' + filename, host_path])):\n self.adb.run(['shell', 'rm', '/data/local/tmp/' + filename])\n return True\n log_warning('failed to pull %s from device' % device_path)\n return False\n\n\n def _pull_kernel_symbols(self):\n file = os.path.join(self.binary_cache_dir, 'kallsyms')\n if os.path.isfile(file):\n os.remove(file)\n if self.adb.switch_to_root():\n self.adb.run(['shell', '\"echo 0 >/proc/sys/kernel/kptr_restrict\"'])\n self.adb.run(['pull', '/proc/kallsyms', file])\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\n\"\"\"Pull binaries needed by perf.data from device to binary_cache directory.\"\"\")\n parser.add_argument('-i', '--perf_data_path', default='perf.data', help=\n\"\"\"The path of profiling data.\"\"\")\n parser.add_argument('-lib', '--native_lib_dir', nargs='+', help=\n\"\"\"Path to find debug version of native shared libraries used in the app.\"\"\",\n action='append')\n parser.add_argument('--disable_adb_root', action='store_true', help=\n\"\"\"Force adb to run in non root mode.\"\"\")\n args = parser.parse_args()\n config = {}\n config['perf_data_path'] = args.perf_data_path\n config['symfs_dirs'] = flatten_arg_list(args.native_lib_dir)\n config['disable_adb_root'] = args.disable_adb_root\n\n builder = BinaryCacheBuilder(config)\n builder.build_binary_cache()\n\n\nif __name__ == '__main__':\n main()","repo_name":"kiwibrowser/src","sub_path":"third_party/android_ndk/simpleperf/binary_cache_builder.py","file_name":"binary_cache_builder.py","file_ext":"py","file_size_in_byte":9491,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"72778505444","text":"import csv\r\ndef energy():\r\n with open('resources/energy.csv', mode='r') as infile:\r\n reader = csv.reader(infile)\r\n mydict = {rows[0]:rows[1] for rows in reader}\r\n u1,u2 = input(\"Enter the conversion to be done : \").split()\r\n in2 = float(input(\"Enter the numeric value : \"))\r\n u1 = u1.lower()\r\n u2 = u2.lower()\r\n try:\r\n if u1=='j':\r\n in1 = u1 + \" to \" + u2 \r\n cf =float(mydict[in1])\r\n print(in2*cf, u2)\r\n elif u2 == 'j':\r\n in1 = \"j to \" + u1\r\n cf = float(mydict[in1])\r\n print(in2*(1/cf), u2)\r\n else:\r\n in1 = \"j to \" + u1\r\n cf1 = float(mydict[in1])\r\n tv = in2*(1/cf1)\r\n in3 = \"j to \" + u2\r\n cf2 = float(mydict[in3])\r\n print(tv*cf2, u2)\r\n except:\r\n print(\"Conversion not Possible\")\r\n","repo_name":"Krish2208/Unit-Converter","sub_path":"files/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40831118638","text":"import sys\nimport pandas as pd\nimport argparse\n\ndef parse_args():\n # Create argument parser\n parser = argparse.ArgumentParser()\n\n # Positional mandatory arguments\n parser.add_argument(\"kmer_freq\", help=\"File containing k-mer frequency vectors for reads (read, length, kmer1, kmer2, etc).\", type=str)\n parser.add_argument(\"summary\", help=\"Sequencing summary file corresponding to reads\", type=str)\n\n # Optional arguments\n parser.add_argument(\"-o\", \"--output\", help=\"Output file name [kmer_freq.qs.tsv]\", type=str, default=\"kmer_freq.qs.tsv\")\n\n # Parse arguments\n args = parser.parse_args()\n\n return args\n\ndef main(args):\n freq = pd.read_csv(args.kmer_freq, sep=\"\\t\")\n summ = pd.read_csv(args.summary, sep=\"\\t\", quoting=3)\n\n # Sometimes these summary files have quotation marks around each row entry\n if type(summ.iloc[0,0])==str:\n if summ.iloc[0,0].find(\"\\\"\")>-1:\n summ.columns = summ.columns.map(lambda x: x.strip(\"\\\"\"))\n summ.iloc[:,0] = summ.iloc[:,0].str.strip(\"\\\"\")\n summ.iloc[:,-1] = summ.iloc[:,-1].str.strip(\"\\\"\").astype(\"float\")\n\n # Adjust the column names as necessary for 1Dsq reads\n qscore = 'mean_qscore_template'\n if \"sequence_length_2d\" in summ.columns:\n qscore = qscore.replace('template', '2d')\n\n summ = summ.rename(index=str, columns={qscore: \"qscore\", \"read_id\": \"read\"})\n\n summ = summ.set_index(\"read\")\n freq = freq.set_index(\"read\")\n\n motifs = list(freq.columns.values[2:])\n\n freq = freq.join(summ[\"qscore\"], how=\"left\").reset_index()\n\n all_cols = [\"read\", \"qscore\", \"length\"] + motifs\n freq.loc[:,all_cols].to_csv(args.output, sep=\"\\t\", index=False)\n\nif __name__==\"__main__\":\n args = parse_args()\n\n main(args)","repo_name":"nanoporetech/DTR-phage-pipeline","sub_path":"scripts/add_qscore_to_kmer_freq.py","file_name":"add_qscore_to_kmer_freq.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"} +{"seq_id":"73688871205","text":"from wkhtmltopdf.views import PDFTemplateView\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import get_template\nfrom django.views import View\nfrom django.utils.translation import gettext_lazy as _\nfrom django.db.models import F\n\nfrom .models import Person, Role, Hosted_Centres, Appointment, Availability, Slot, Child_Case_Data, \\\n teacher_occupied_slots, Intervention, Assessment_psy, Pre_Evaluation, Skill_English_Pre, Skill_Arabic_Pre, \\\n Evaluation_regular, Skill_English, Skill_Arabic, Arabic_Letter, Cognitive_assessment, Intervention_Cancelled, \\\n All_Intervention, Test, Session, Homeworks\nfrom django.contrib import messages\nfrom .forms import login_form, register_form, register_centre_form, add_appointment_form, child_case_form, child_case_f\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import authenticate\nfrom django.utils import timezone\nimport datetime\nfrom django.core.mail import send_mail\nfrom django.core import serializers\n\n# Create your views here.\nfrom .utils import render_to_pdf\n\ncurrent_time = timezone.now() + timezone.timedelta(hours=5)\n\n\n# def home(request):\n# super = Person.objects.get(is_superuser=True)\n# if request.user.email != super.email:\n# return render(request, 'static_files/login.html')\n# else:\n# return render(request, 'static_files/index.html')\n#\n#\n# def login(request):\n# email = request.POST.get('email')\n# password = request.POST.get('password')\n# super = Person.objects.get(is_superuser=True)\n# if email and password:\n# x = Person.objects.filter(email=email)\n# y = False\n# if x:\n# x = Person.objects.get(email=email)\n# y = x.check_password(password)\n# if y:\n# if x.email == super.email:\n# return render(request, 'static_files/index.html')\n# else:\n# messages.warning(request, 'Enter Correct Credentials')\n# return redirect(login)\n# else:\n# messages.warning(request, 'Enter Correct Credentials')\n# return redirect(login)\n# return render(request, 'static_files/login.html')\n\n\ndef empty(request):\n return redirect(index)\n\n\ndef login(request):\n if request.method == \"POST\":\n lf = login_form(request.POST)\n if lf.is_valid():\n username = lf.cleaned_data[\"username\"]\n password = lf.cleaned_data[\"password\"]\n print(username, password)\n user = authenticate(username=username, password=password)\n print(user)\n if user:\n if user.role:\n if user.role.name == \"Receptionist\":\n return redirect(receptionist_dashboard)\n else:\n return redirect(index)\n elif Person.objects.filter(username=username).count() == 0:\n messages.warning(request, message=\"Wrong Credentials, Check again\")\n return redirect(login)\n elif not Person.objects.get(username=username).check_password(password):\n messages.warning(request, message=\"Wrong Credentials, Check again\")\n return redirect(login)\n else:\n messages.warning(request, message=\"Wrong Credentials, Check again\")\n return redirect(login)\n else:\n lf = login_form()\n return render(request, 'static_files/login.html', {'form': lf})\n\n\n@login_required(login_url='login')\ndef language_choose(request):\n return render(request, 'registration/language.html')\n\n\n@login_required(login_url='login')\ndef index(request):\n if request.user.role.name == \"Teacher\":\n return redirect(todays_intervention)\n elif request.user.role.name == \"Parent\":\n return redirect(select_student, 'recep')\n else:\n return redirect(todays_appoint_list)\n\n\ndef register(request):\n if request.method == \"POST\":\n rf = register_form(request.POST, request.FILES)\n if rf.is_valid():\n first_name = rf.cleaned_data['first_name']\n last_name = rf.cleaned_data['last_name']\n username = rf.cleaned_data['username']\n gender = rf.cleaned_data['gender']\n dob = rf.cleaned_data['dob']\n profile_picture = rf.cleaned_data['profile_picture']\n # profile_picture = request.FILES['profile_picture']\n street = rf.cleaned_data['street']\n block = rf.cleaned_data['block']\n city = rf.cleaned_data['city']\n state = rf.cleaned_data['state']\n country = rf.cleaned_data['country']\n postal_code = rf.cleaned_data['postalcode']\n qualification = rf.cleaned_data['qualification']\n institution = rf.cleaned_data['institution']\n mobile = rf.cleaned_data['mobile']\n email = rf.cleaned_data['email']\n\n Person.objects.create(first_name=first_name, last_name=last_name, gender=gender, dob=dob,\n profile_pic=profile_picture, username=username, country=country, state=state,\n city=city,\n street=street, block=block, postal_code=postal_code, qualification=qualification,\n institute=institution, mobile_number=mobile, email=email)\n messages.success(request, message=\"Individual Registered, Waiting for Approval From Admin\")\n return redirect(register)\n else:\n print(rf.errors)\n return HttpResponse(rf.errors)\n else:\n rf = register_form()\n return render(request, 'static_files/register.html', {'form': rf})\n\n\ndef register_centre(request):\n rf = ''\n if request.method == \"POST\":\n rf = register_centre_form(request.POST, request.FILES)\n if rf.is_valid():\n centre_name = rf.cleaned_data['centre_name']\n hc_logo = rf.cleaned_data['hc_logo']\n hc_document = rf.cleaned_data['hc_document']\n qualification = rf.cleaned_data['qualification']\n institution = rf.cleaned_data['institution']\n first_name = rf.cleaned_data['first_name']\n last_name = rf.cleaned_data['last_name']\n profile_picture = rf.cleaned_data['profile_picture']\n # profile_picture = request.FILES['profile_picture']\n street = rf.cleaned_data['street']\n block = rf.cleaned_data['block']\n city = rf.cleaned_data['city']\n state = rf.cleaned_data['state']\n country = rf.cleaned_data['country']\n postal_code = rf.cleaned_data['postalcode']\n spoc_mobile_number = rf.cleaned_data['spoc_mobile_number']\n spoc_email = rf.cleaned_data['spoc_email']\n spoc_extension = rf.cleaned_data['spoc_extension']\n spoc_office_number = rf.cleaned_data['spoc_office_number']\n centre_mobile_number_1 = rf.cleaned_data['centre_mobile_number_1']\n centre_mobile_number_2 = rf.cleaned_data['centre_mobile_number_2']\n centre_office_number = rf.cleaned_data['centre_office_number']\n centre_extension_number = rf.cleaned_data['centre_extension_number']\n centre_email = rf.cleaned_data['centre_email']\n centre_web_address = rf.cleaned_data['centre_web_address']\n\n Hosted_Centres.objects.create(centre_name=centre_name, hc_logo=hc_logo, hc_document=hc_document,\n qualification=qualification, institute=institution, spoc_f_name=first_name,\n spoc_l_name=last_name, spoc_profile_pic=profile_picture, country=country,\n state=state, city=city, street=street, block=block, postal_code=postal_code,\n spoc_email=spoc_email, spoc_mobile_number=spoc_mobile_number,\n spoc_extension_number=spoc_extension, spoc_office_number=spoc_office_number,\n centre_mobile_number_1=centre_mobile_number_1,\n centre_mobile_number_2=centre_mobile_number_2,\n centre_office_number=centre_office_number,\n centre_extension_number=centre_extension_number, centre_email=centre_email,\n centre_web_address=centre_web_address)\n messages.success(request, message=\"Centre Registered. Waiting For Approval From Admin!\")\n return redirect(register_centre)\n else:\n print(rf.errors)\n return HttpResponse(rf.errors)\n else:\n rf = register_centre_form()\n return render(request, 'static_files/register_centre.html', {'form': rf})\n\n\n@login_required(login_url='login')\ndef receptionist_dashboard(request):\n user = request.user\n user = Person.objects.get(id=user.id)\n return render(request, 'static_files/dashboard_receptionist.html', {'user': user})\n\n\n@login_required(login_url='login')\ndef appointment_list(request):\n appoin_list = ''\n children = set()\n psychologists = set()\n if request.user.role.name == \"Physiologist\":\n appoin_list = Appointment.objects.filter(psychologist=request.user).order_by('appointment_date')\n elif request.user.role.name == \"Receptionist\":\n appoin_list = Appointment.objects.filter().order_by('appointment_date')\n if request.method == \"POST\":\n s_by_name = request.POST['s_by_name']\n p_by_name = ''\n if request.user.role.name == \"Receptionist\":\n p_by_name = request.POST['p_by_name']\n if s_by_name:\n appoin_list = appoin_list.filter(child__username=s_by_name)\n if p_by_name:\n appoin_list = appoin_list.filter(psychologist__username=p_by_name)\n else:\n for appoint in appoin_list:\n children.add(appoint.child)\n psychologists.add(appoint.psychologist)\n return render(request, 'static_files/appointment_list.html', {'objs': appoin_list, 'children': children,\n 'psychologists': psychologists})\n\n\nweekdays = {'0': 'm', '1': 'tu', '2': 'w', '3': 'th', '4': 'f', '5': 'sa',\n '6': 'su'}\n\n\n@login_required(login_url='login')\ndef add_appointment(request):\n if request.method == \"POST\":\n af = add_appointment_form(request.POST)\n if af.is_valid():\n appointment_date = af.cleaned_data['appointment_date']\n if request.user.role.name == \"Receptionist\":\n psychologist_id = request.POST['psy']\n else:\n psychologist_id = request.user.id\n child_id = request.POST['child']\n\n if not psychologist_id or not child_id:\n messages.warning(request, message=\"Fill All fields Please\")\n return redirect(add_appointment)\n\n psy = Person.objects.get(id=psychologist_id)\n child = Person.objects.get(id=child_id)\n\n d = appointment_date.split('/')\n datee = datetime.datetime(int(d[2]), int(d[1]), int(d[0]))\n if datee.date() < datetime.datetime.now().date():\n messages.warning(request, message=\"Add date Ahead of today\")\n return redirect(add_appointment)\n if datee.date().weekday() == 4:\n messages.warning(request, message=\"Friday is OFF\")\n return redirect(add_appointment)\n return redirect(check_slots, psy.id, child.id, datee.date())\n else:\n messages.warning(request, message=af.errors)\n return redirect(add_appointment)\n af = add_appointment_form()\n p = Person.objects.filter(role__name=\"Physiologist\")\n students = Person.objects.filter(role__name=\"Student\")\n return render(request, 'static_files/add_appointment.html', {'form': af, 'psys': p, 'students': students})\n\n\ntime_slots_r_p = {'08:00:00': '0', '10:00:00': '1', '12:00:00': '2', '14:00:00': '3', '16:00:00': '4',\n '18:00:00': '5'}\n\ntime_slots_p = {'0': '08:00:00', '1': '10:00:00', '2': '12:00:00', '3': '14:00:00', '4': '16:00:00',\n '5': '18:00:00'}\n\n\n@login_required(login_url='login')\ndef check_slots(request, id1, id2, date):\n da = date.split('-')\n daat = datetime.datetime(int(da[0]), int(da[1]), int(da[2])).date()\n weekday = daat.weekday()\n # delete_old_slots(current_time.date())\n psy = Person.objects.get(id=id1)\n child = Person.objects.get(id=id2)\n content = []\n content2 = []\n ava = Availability.objects.filter(psychologist=psy).first()\n\n if request.method == \"POST\":\n for n in range(6):\n if str(n) in request.POST:\n if weekday == 0:\n s_time = time_slots_p[str(n + int((int(str(ava.m_available_time_from).split(':')[0]) - 8) / 2))]\n return redirect(confirm_appointment, id1, id2, date, s_time)\n elif weekday == 1:\n s_time = time_slots_p[str(n + int((int(str(ava.tu_available_time_from).split(':')[0]) - 8) / 2))]\n return redirect(confirm_appointment, id1, id2, date, s_time)\n elif weekday == 2:\n s_time = time_slots_p[str(n + int((int(str(ava.w_available_time_from).split(':')[0]) - 8) / 2))]\n return redirect(confirm_appointment, id1, id2, date, s_time)\n elif weekday == 3:\n s_time = time_slots_p[str(n + int((int(str(ava.th_available_time_from).split(':')[0]) - 8) / 2))]\n return redirect(confirm_appointment, id1, id2, date, s_time)\n elif weekday == 5:\n s_time = time_slots_p[str(n + int((int(str(ava.sa_available_time_from).split(':')[0]) - 8) / 2))]\n return redirect(confirm_appointment, id1, id2, date, s_time)\n elif weekday == 6:\n s_time = time_slots_p[str(n + int((int(str(ava.su_available_time_from).split(':')[0]) - 8) / 2))]\n return redirect(confirm_appointment, id1, id2, date, s_time)\n else:\n if ava:\n if weekday == 0:\n content = {'s': range(int((int(str(ava.m_available_time_from).split(':')[0]) - 8) / 2)),\n 'd': range(int((int(str(ava.m_available_time_to).split(':')[0]) -\n int(str(ava.m_available_time_from).split(':')[0])) / 2)),\n 'e': range(int((20 - int(str(ava.m_available_time_to).split(':')[0])) / 2))\n }\n content2 = [\n int(time_slots_r_p[str(x.appointment_s_time)]) - int((int(str(ava.m_available_time_from).split(\n ':')[0]) - 8) / 2) for x in\n Appointment.objects.filter(psychologist=psy, child=child, appointment_date=daat)]\n elif weekday == 1:\n content = {'s': range(int((int(str(ava.tu_available_time_from).split(':')[0]) - 8) / 2)),\n 'd': range(int((int(str(ava.tu_available_time_to).split(':')[0]) -\n int(str(ava.tu_available_time_from).split(':')[0])) / 2)),\n 'e': range(int((20 - int(str(ava.tu_available_time_to).split(':')[0])) / 2))\n }\n content2 = [\n int(time_slots_r_p[str(x.appointment_s_time)]) - int((int(str(ava.tu_available_time_from).split(\n ':')[0]) - 8) / 2) for x in\n Appointment.objects.filter(psychologist=psy, child=child, appointment_date=daat)]\n elif weekday == 2:\n content = {'s': range(int((int(str(ava.w_available_time_from).split(':')[0]) - 8) / 2)),\n 'd': range(int((int(str(ava.w_available_time_to).split(':')[0]) -\n int(str(ava.w_available_time_from).split(':')[0])) / 2)),\n 'e': range(int((20 - int(str(ava.w_available_time_to).split(':')[0])) / 2))\n }\n content2 = [\n int(time_slots_r_p[str(x.appointment_s_time)]) - int((int(str(ava.w_available_time_from).split(\n ':')[0]) - 8) / 2) for x in\n Appointment.objects.filter(psychologist=psy, child=child, appointment_date=daat)]\n elif weekday == 3:\n content = {'s': range(int((int(str(ava.th_available_time_from).split(':')[0]) - 8) / 2)),\n 'd': range(int((int(str(ava.th_available_time_to).split(':')[0]) -\n int(str(ava.th_available_time_from).split(':')[0])) / 2)),\n 'e': range(int((20 - int(str(ava.th_available_time_to).split(':')[0])) / 2))\n }\n content2 = [\n int(time_slots_r_p[str(x.appointment_s_time)]) - int((int(str(ava.th_available_time_from).split(\n ':')[0]) - 8) / 2) for x in\n Appointment.objects.filter(psychologist=psy, child=child, appointment_date=daat)]\n elif weekday == 5:\n content = {'s': range(int((int(str(ava.sa_available_time_from).split(':')[0]) - 8) / 2)),\n 'd': range(int((int(str(ava.sa_available_time_to).split(':')[0]) -\n int(str(ava.sa_available_time_from).split(':')[0])) / 2)),\n 'e': range(int((20 - int(str(ava.sa_available_time_to).split(':')[0])) / 2))\n }\n content2 = [\n int(time_slots_r_p[str(x.appointment_s_time)]) - int((int(str(ava.sa_available_time_from).split(\n ':')[0]) - 8) / 2) for x in\n Appointment.objects.filter(psychologist=psy, child=child, appointment_date=daat)]\n elif weekday == 6:\n content = {'s': range(int((int(str(ava.su_available_time_from).split(':')[0]) - 8) / 2)),\n 'd': range(int((int(str(ava.su_available_time_to).split(':')[0]) -\n int(str(ava.su_available_time_from).split(':')[0])) / 2)),\n 'e': range(int((20 - int(str(ava.su_available_time_to).split(':')[0])) / 2))\n }\n content2 = [\n int(time_slots_r_p[str(x.appointment_s_time)]) - int((int(str(ava.su_available_time_from).split(\n ':')[0]) - 8) / 2) for x in\n Appointment.objects.filter(psychologist=psy, child=child, appointment_date=daat)]\n else:\n messages.warning(request, message='Please Set Availability for the Psychologist')\n return redirect(add_appointment)\n\n # slotss = Slot.objects.filter(psychologist_id=id1, day=date)\n # x = current_time + timezone.timedelta(hours=2)\n # two_hours = int(str(x.time()).split(':')[0])\n # if slotss:\n # slotss = Slot.objects.filter(psychologist_id=id1, day=date, available=True)\n # if str(current_time.date()) == str(date):\n # for slot in slotss:\n # slot_time = int(str(slot.s_time).split(':')[0])\n # print(slot_time, two_hours)\n # if slot_time < two_hours or two_hours == 0 or two_hours == 1:\n # slotss = slotss.exclude(id=slot.id)\n # else:\n # d = date.split('-')\n # datee = datetime.datetime(int(d[0]), int(d[1]), int(d[2]))\n # weekday = datee.date().weekday()\n # create_slots(id1, weekday=weekday, day=date)\n # slotss = Slot.objects.filter(psychologist_id=id1, day=date, available=True)\n # if current_time.date() == date:\n # for slot in slotss:\n # slot_time = int(str(slot.s_time).split(':')[0])\n # if slot_time < two_hours:\n # slotss = slotss.exclude(id=slot.id)\n\n return render(request, 'static_files/check_slots.html', {'psy': psy, 'date': daat, 'child': child,\n 'true_date': date, 'content': content,\n 'content2': content2, 'weekday': weekday})\n\n\ndef success(request):\n return render(request, 'static_files/success.html')\n\n\n@login_required(login_url='login')\ndef search_psy(request):\n psys = ''\n if request.method == \"POST\":\n id = request.POST['search_by_id']\n name = request.POST['search_by_name']\n if id:\n psys = Person.objects.filter(role__name=\"Physiologist\", id=id)\n elif name:\n name = name.split(\" \")\n for n in name:\n psys = Person.objects.filter(role__name=\"Physiologist\", first_name__icontains=n)\n if not psys:\n psys = Person.objects.filter(role__name=\"Physiologist\", last_name__icontains=n)\n else:\n psys = Person.objects.filter(role__name=\"Physiologist\")\n return render(request, 'static_files/search_psy.html', {'psys': psys})\n\n\n@login_required(login_url='login')\ndef availability(request, id):\n p = Person.objects.get(id=id)\n ava, created = Availability.objects.get_or_create(psychologist=p)\n return render(request, 'static_files/availability_psy.html', {'ava': ava, 'psy': p})\n\n\n@login_required(login_url='login')\ndef availability_edit(request, id):\n dic = {}\n p = Person.objects.get(id=id)\n ava = Availability.objects.get(psychologist=p)\n dic['m_from'] = str(ava.m_available_time_from)\n dic['m_to'] = str(ava.m_available_time_to)\n dic['tu_from'] = str(ava.tu_available_time_from)\n dic['tu_to'] = str(ava.tu_available_time_to)\n dic['w_from'] = str(ava.w_available_time_from)\n dic['w_to'] = str(ava.w_available_time_to)\n dic['th_from'] = str(ava.th_available_time_from)\n dic['th_to'] = str(ava.th_available_time_to)\n # dic['f_from'] = str(ava.f_available_time_from)\n # dic['f_to'] = str(ava.f_available_time_to)\n dic['sa_from'] = str(ava.sa_available_time_from)\n dic['sa_to'] = str(ava.sa_available_time_to)\n dic['su_from'] = str(ava.su_available_time_from)\n dic['su_to'] = str(ava.su_available_time_to)\n\n if request.method == \"POST\":\n m_from = request.POST['1-stime']\n m_to = request.POST['1-ftime']\n tu_from = request.POST['2-stime']\n tu_to = request.POST['2-ftime']\n w_from = request.POST['3-stime']\n w_to = request.POST['3-ftime']\n th_from = request.POST['4-stime']\n th_to = request.POST['4-ftime']\n # f_from = request.POST['5-stime']\n # f_to = request.POST['5-ftime']\n sa_from = request.POST['6-stime']\n sa_to = request.POST['6-ftime']\n su_from = request.POST['7-stime']\n su_to = request.POST['7-ftime']\n\n if m_from: ava.m_available_time_from = m_from\n if m_to: ava.m_available_time_to = m_to\n if tu_from: ava.tu_available_time_from = tu_from\n if tu_to: ava.tu_available_time_to = tu_to\n if w_from: ava.w_available_time_from = w_from\n if w_to: ava.w_available_time_to = w_to\n if th_from: ava.th_available_time_from = th_from\n if th_to: ava.th_available_time_to = th_to\n # if f_from: ava.f_available_time_from = f_from\n # if f_to: ava.f_available_time_to = f_to\n if sa_from: ava.sa_available_time_from = sa_from\n if sa_to: ava.sa_available_time_to = sa_to\n if su_from: ava.su_available_time_from = su_from\n if su_to: ava.su_available_time_to = su_to\n ava.save()\n\n return redirect(availability, id)\n return render(request, 'static_files/availability_psy_edit.html', {'dic': dic, 'psy': p})\n\n\ndef create_slots(id, weekday, day):\n slots = []\n ava = Availability.objects.get(psychologist_id=id)\n f = f'{weekdays[str(weekday)]}_available_time_from'\n t = f'{weekdays[str(weekday)]}_available_time_to'\n from_time = getattr(ava, f)\n to_time = getattr(ava, t)\n r = to_time.hour - from_time.hour\n y = from_time.hour\n for x in range(int(r / 2)):\n if y < 10:\n if y + 2 < 10:\n slots.append(f'0{y}:00-0{y + 2}:00')\n else:\n slots.append(f'0{y}:00-{y + 2}:00')\n else:\n slots.append(f'{y}:00-{y + 2}:00')\n y += 2\n for slot in slots:\n Slot.objects.create(psychologist_id=id, day=day, s_time=slot.split('-')[0], e_time=slot.split('-')[1],\n available=True)\n return '0'\n\n\ndef delete_old_slots(date):\n slots = Slot.objects.filter(day__lt=date)\n for slot in slots:\n slot.delete()\n # appoints = Appointment.objects.filter(appointment_date__lt=date)\n # for appoint in appoints:\n # appoint.delete()\n\n\n@login_required(login_url='login')\ndef confirm_appointment(request, id1, id2, date, time_s):\n child = Person.objects.get(id=id2)\n # children = Person.objects.filter(role__name=\"Student\").exclude(id=id2)\n psy = Person.objects.get(id=id1)\n da = date.split('-')\n daat = datetime.datetime(int(da[0]), int(da[1]), int(da[2])).date()\n e_hour = int(time_s.split(':')[0]) + 2\n time_e = f'{e_hour}:00:00'\n if request.method == \"POST\":\n appoint = Appointment.objects.filter(child_id=id2, psychologist_id=id1,\n appointment_date__gte=current_time.date()).first()\n if not appoint:\n Appointment.objects.create(psychologist_id=id1, child_id=id2, appointment_date=daat,\n appointment_s_time=time_s,\n appointment_e_time=time_e, status='true')\n return redirect(appointment_list)\n else:\n appoint.appointment_date = daat\n appoint.appointment_s_time = time_s\n appoint.appointment_e_time = time_e\n appoint.save()\n return redirect(appointment_list)\n\n return render(request, 'static_files/confirm_appointment.html', {'child': child, 'psy': psy,\n 'date': daat, 'time_s': time_s, 'time_e': time_e})\n\n\n@login_required(login_url='login')\ndef delete_appointment(request, id):\n appoin = Appointment.objects.get(id=id)\n appoin.delete()\n return redirect(appointment_list)\n\n\n@login_required(login_url='login')\ndef rescheudle(request, id):\n appoin = Appointment.objects.get(id=id)\n psy = Person.objects.filter(role__name=\"Physiologist\").exclude(id=appoin.psychologist_id)\n if request.method == \"POST\":\n appointment_date = request.POST['appointment_date']\n psy_name = request.POST['psy']\n full_name_psy = psy_name.split(' ')\n psy = Person.objects.get(first_name=full_name_psy[0])\n\n if not appointment_date:\n messages.warning(request, message=\"Kindly Select the date\")\n return redirect(rescheudle, id)\n\n d = appointment_date.split('/')\n datee = datetime.datetime(int(d[2]), int(d[1]), int(d[0]))\n if datee.date() < datetime.datetime.now().date():\n messages.warning(request, message=\"Add date Ahead of today\")\n return redirect(rescheudle, id)\n if datee.date().weekday() == 4:\n messages.warning(request, message=\"Friday is OFF\")\n return redirect(rescheudle, id)\n return redirect(check_slots, psy.id, appoin.child.id, datee.date())\n\n return render(request, 'static_files/reshedule.html', {'appointment': appoin, 'psy': psy})\n\n\ndef is_none(field):\n if field is None:\n return True\n else:\n return False\n\n\ndef format_date_model(date):\n splitted = date.split('/')\n return f'{splitted[2]}-{splitted[1]}-{splitted[0]}'\n\n\ndef format_date_html(date):\n splitted = str(date).split('-')\n return f'{splitted[2]}/{splitted[1]}/{splitted[0]}'\n\n\ndef child_case(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n count = Child_Case_Data.objects.filter(child_id=id).count()\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n civil_number = child_form.cleaned_data['civil_number']\n school_name = child_form.cleaned_data['school_name']\n dob = child_form.cleaned_data['dob']\n place_of_birth = child_form.cleaned_data['place_of_birth']\n nationality = child_form.cleaned_data['nationality']\n grade = request.POST['grade']\n gender = request.POST['gender']\n\n father_name = child_form.cleaned_data['father_name']\n age_f = child_form.cleaned_data['age_f']\n nationality_f = child_form.cleaned_data['nationality_f']\n education_level_f = child_form.cleaned_data['education_level_f']\n phone_f = child_form.cleaned_data['phone_f']\n current_occupation_f = child_form.cleaned_data['current_occupation_f']\n residence_address_f = child_form.cleaned_data['residence_address_f']\n email_f = request.POST['email_f']\n\n mother_name = child_form.cleaned_data['mother_name']\n age_m = child_form.cleaned_data['age_m']\n nationality_m = child_form.cleaned_data['nationality_m']\n phone_m = child_form.cleaned_data['phone_m']\n education_level_m = child_form.cleaned_data['education_level_m']\n current_occupation_m = child_form.cleaned_data['current_occupation_m']\n residence_address_m = child_form.cleaned_data['residence_address_m']\n email_m = request.POST['email_m']\n\n guardian_name = child_form.cleaned_data['guardian_name']\n education_level_g = child_form.cleaned_data['education_level_g']\n relation_to_child = child_form.cleaned_data['relation_to_child']\n phone_g = child_form.cleaned_data['phone_g']\n current_occupation_g = child_form.cleaned_data['current_occupation_g']\n residence_address_g = child_form.cleaned_data['residence_address_g']\n email_g = request.POST['email_g']\n\n relation_btw_parents = request.POST['relation_btw_parents']\n martial_status_parents = request.POST['martial_status_parents']\n parent_passed_away = request.POST['parent_passed_away']\n child_living_with = child_form.cleaned_data['child_living_with']\n father_married_before = request.POST['father_married_before']\n mother_married_before = request.POST['mother_married_before']\n when_was_married = request.POST['when_was_married']\n second_marriage = request.POST['second_marriage']\n nationality_second_marriage = child_form.cleaned_data['nationality_second_marriage']\n number_of_family_members = child_form.cleaned_data['number_of_family_members']\n number_of_brothers = child_form.cleaned_data['number_of_brothers']\n number_of_sisters = child_form.cleaned_data['number_of_sisters']\n number_of_brothers_from_father = child_form.cleaned_data['number_of_brothers_from_father']\n number_of_sisters_from_father = child_form.cleaned_data['number_of_sisters_from_father']\n number_of_brothers_from_mother = child_form.cleaned_data['number_of_brothers_from_mother']\n number_of_sisters_from_mother = child_form.cleaned_data['number_of_sisters_from_mother']\n order_sibling = child_form.cleaned_data['order_sibling']\n others_living_in_house = child_form.cleaned_data['others_living_in_house']\n lives_with = child_form.cleaned_data['lives_with']\n\n if count == 0:\n child = Person.objects.get(id=id)\n Child_Case_Data.objects.create(child=child, civil_number=civil_number, school_name=school_name,\n dob=format_date_model(dob), place_of_birth=place_of_birth,\n nationality=nationality, grade=grade, gender=gender, f_name=father_name,\n f_age=age_f, f_nationality=nationality_f, f_phone=phone_f,\n f_education_level=education_level_f, f_occupation=current_occupation_f,\n f_address=residence_address_f, f_email=email_f, m_name=mother_name,\n m_age=age_m, m_nationality=nationality_m, m_phone=phone_m,\n m_education_level=education_level_m, m_occupation=current_occupation_m,\n m_address=residence_address_m, m_email=email_m, g_name=guardian_name,\n g_education_level=education_level_g, g_relation_child=relation_to_child,\n g_phone=phone_g, g_occupation=current_occupation_g,\n g_address=residence_address_g, g_email=email_g,\n relation_btw_parents=relation_btw_parents,\n martial_status=martial_status_parents, passed_away=parent_passed_away,\n living_in_case=child_living_with, father_married=father_married_before,\n mother_married=mother_married_before, married_when=when_was_married,\n second_marriage=second_marriage,\n nationality_sec_m=nationality_second_marriage,\n number_of_fam=number_of_family_members,\n number_of_bros=number_of_brothers,\n number_of_sis=number_of_sisters,\n number_of_bros_f=number_of_brothers_from_father,\n number_of_sis_f=number_of_sisters_from_father,\n number_of_bros_m=number_of_brothers_from_mother,\n number_of_sis_m=number_of_sisters_from_mother,\n order_sib=order_sibling, other_people_house=others_living_in_house,\n lives_current=lives_with\n )\n else:\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.civil_number = civil_number\n cc.school_name = school_name\n cc.dob = format_date_model(dob)\n cc.place_of_birth = place_of_birth\n cc.nationality = nationality\n cc.grade = grade\n cc.gender = gender\n cc.f_name = father_name\n cc.f_age = age_f\n cc.f_nationality = nationality_f\n cc.f_phone = phone_f\n cc.f_education_level = education_level_f\n cc.f_occupation = current_occupation_f\n cc.f_address = residence_address_f\n cc.f_email = email_f\n cc.m_name = mother_name\n cc.m_age = age_m\n cc.m_nationality = nationality_m\n cc.m_phone = phone_m\n cc.m_education_level = education_level_m\n cc.m_occupation = current_occupation_m\n cc.m_address = residence_address_m\n cc.m_email = email_f\n cc.g_name = guardian_name\n cc.g_education_level = education_level_g\n cc.g_relation_child = relation_to_child\n cc.g_phone = phone_g\n cc.g_occupation = current_occupation_g\n cc.g_address = residence_address_g\n cc.g_email = email_g\n cc.relation_btw_parents = relation_btw_parents\n cc.martial_status = martial_status_parents\n cc.passed_away = parent_passed_away\n cc.living_in_case = child_living_with\n cc.father_married = father_married_before\n cc.mother_married = mother_married_before\n cc.second_marriage = second_marriage\n cc.nationality_sec_m = nationality_second_marriage\n cc.number_of_fam = number_of_family_members\n cc.number_of_bros = number_of_brothers\n cc.number_of_sis = number_of_sisters\n cc.number_of_bros_f = number_of_brothers_from_father\n cc.number_of_sis_f = number_of_sisters_from_father\n cc.number_of_bros_m = number_of_brothers_from_mother\n cc.number_of_sis_m = number_of_sisters_from_mother\n cc.order_sib = order_sibling\n cc.other_people_house = others_living_in_house\n cc.lives_current = lives_with\n\n cc.save()\n\n if 'next' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n\n else:\n print(child_form.errors)\n else:\n child_form = child_case_form()\n if count != 0:\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.dob = format_date_html(cc.dob)\n\n return render(request, 'static_files/child-case.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_child_history(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n state_of_mind_preg = child_form.cleaned_data['state_of_mind_preg']\n age_during_preg = child_form.cleaned_data['age_during_preg']\n health_psy_preg = child_form.cleaned_data['health_psy_preg']\n preg_bleeding = request.POST['preg_bleeding']\n preg_poisoning = request.POST['preg_poisoning']\n preg_infection = request.POST['preg_infection']\n preg_accident = request.POST['preg_accident']\n kind_of_accident_preg = child_form.cleaned_data['kind_of_accident_preg']\n medicines_drugs_preg = child_form.cleaned_data['medicines_drugs_preg']\n prob_disease_preg = child_form.cleaned_data['prob_disease_preg']\n duration_preg = request.POST['duration_preg']\n preg_month = request.POST['preg_month']\n birth_type = request.POST['birth_type']\n umbilical_cord_neck = request.POST['umbilical_cord_neck']\n skin_yellow = request.POST['skin_yellow']\n skin_blue = request.POST['skin_blue']\n twin_triplet = request.POST['twin_triplet']\n oxygen_deficiency = request.POST['oxygen_deficiency']\n colic_cramps = request.POST['colic_cramps']\n dropsy_edema_hydrops = request.POST['dropsy_edema_hydrops']\n\n baby_weight_birth = child_form.cleaned_data['baby_weight_birth']\n prob_birth = child_form.cleaned_data['prob_birth']\n complications_birth = child_form.cleaned_data['complications_birth']\n\n health_psy_post_b = child_form.cleaned_data['health_psy_post_b']\n baby_incubator = request.POST['baby_incubator']\n period_incubator = child_form.cleaned_data['period_incubator']\n surgery_baby = child_form.cleaned_data['surgery_baby']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.state_of_m = state_of_mind_preg\n cc.p_m_age = age_during_preg\n cc.m_health = health_psy_preg\n cc.p_bleeding = preg_bleeding\n cc.p_poisoning = preg_poisoning\n cc.p_infection = preg_infection\n cc.p_accident = preg_accident\n cc.p_accident_detail = kind_of_accident_preg\n cc.p_medicines = medicines_drugs_preg\n cc.p_problems = prob_disease_preg\n cc.p_duration = duration_preg\n cc.p_month = preg_month\n cc.type_birth = birth_type\n cc.umbilical_cord = umbilical_cord_neck\n cc.skin_yellow = skin_yellow\n cc.skin_blue = skin_blue\n cc.twin_trip = twin_triplet\n cc.needed_oxy = oxygen_deficiency\n cc.colic_cramps = colic_cramps\n cc.dropsy = dropsy_edema_hydrops\n cc.baby_weight = baby_weight_birth\n cc.b_problems = prob_birth\n cc.b_complications = complications_birth\n cc.health_m_pb = health_psy_post_b\n cc.incubator = baby_incubator\n cc.incubator_period = period_incubator\n cc.b_surgery = surgery_baby\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(child_case, id)\n elif 'next' in request.POST:\n return redirect(cc_condition, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc_development_of_child.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_condition(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n extremely_high_temp_age = child_form.cleaned_data['extremely_high_temp_age']\n extremely_high_temp_dur = child_form.cleaned_data['extremely_high_temp_dur']\n ear_problems_age = child_form.cleaned_data['ear_problems_age']\n ear_problems_dur = child_form.cleaned_data['ear_problems_dur']\n vision_problems_age = child_form.cleaned_data['vision_problems_age']\n vision_problems_dur = child_form.cleaned_data['vision_problems_dur']\n juandice_age = child_form.cleaned_data['juandice_age']\n juandice_dur = child_form.cleaned_data['juandice_dur']\n asthma_age = child_form.cleaned_data['asthma_age']\n asthma_dur = child_form.cleaned_data['asthma_dur']\n allergy_age = child_form.cleaned_data['allergy_age']\n allergy_dur = child_form.cleaned_data['allergy_dur']\n poisoning_age = child_form.cleaned_data['poisoning_age']\n poisoning_dur = child_form.cleaned_data['poisoning_dur']\n surgical_age = child_form.cleaned_data['surgical_age']\n surgical_dur = child_form.cleaned_data['surgical_dur']\n surgery = child_form.cleaned_data['surgery']\n accident_age = child_form.cleaned_data['accident_age']\n accident_dur = child_form.cleaned_data['accident_dur']\n accident = child_form.cleaned_data['accident']\n not_mentioned_disease = child_form.cleaned_data['not_mentioned_disease']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.extremely_high_temp_age = extremely_high_temp_age\n cc.extremely_high_temp_dur = extremely_high_temp_dur\n cc.ear_problems_age = ear_problems_age\n cc.ear_problems_dur = ear_problems_dur\n cc.vision_problems_age = vision_problems_age\n cc.vision_problems_dur = vision_problems_dur\n cc.juandice_age = juandice_age\n cc.juandice_dur = juandice_dur\n cc.asthma_age = asthma_age\n cc.asthma_dur = asthma_dur\n cc.allergy_age = allergy_age\n cc.allergy_dur = allergy_dur\n cc.poisoning_age = poisoning_age\n cc.poisoning_dur = poisoning_dur\n cc.surgical_age = surgical_age\n cc.surgical_dur = surgical_dur\n cc.surgery = surgery\n cc.accident_age = accident_age\n cc.accident_dur = accident_dur\n cc.accident = accident\n cc.not_mentioned_disease = not_mentioned_disease\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_child_history, id)\n elif 'next' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc_condition.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_stages_of_growth(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n breastfeeding = request.POST['breastfeeding']\n weaning_age = child_form.cleaned_data['weaning_age']\n age_tooth_start = child_form.cleaned_data['age_tooth_start']\n age_commune = child_form.cleaned_data['age_commune']\n age_simple_words = child_form.cleaned_data['age_simple_words']\n age_speech = child_form.cleaned_data['age_speech']\n age_sentence = child_form.cleaned_data['age_sentence']\n age_bottle_carry = child_form.cleaned_data['age_bottle_carry']\n age_love = child_form.cleaned_data['age_love']\n age_sat = child_form.cleaned_data['age_sat']\n age_stop = child_form.cleaned_data['age_stop']\n age_walk = child_form.cleaned_data['age_walk']\n age_wore_help = child_form.cleaned_data['age_wore_help']\n age_wore_self = child_form.cleaned_data['age_wore_self']\n age_shoes = child_form.cleaned_data['age_shoes']\n age_feed = child_form.cleaned_data['age_feed']\n age_urination = child_form.cleaned_data['age_urination']\n age_bathroom_train = child_form.cleaned_data['age_bathroom_train']\n visual_probs = request.POST['visual_probs']\n use_glasses = request.POST['use_glasses']\n age_glasses = child_form.cleaned_data['age_glasses']\n hearing_probs = request.POST['hearing_probs']\n hearing_aid = request.POST['hearing_aid']\n age_hearing_aid = child_form.cleaned_data['age_hearing_aid']\n speaking_difficulty = request.POST['speaking_difficulty']\n treated_speech_centres = request.POST['treated_speech_centres']\n age_speech_centre = child_form.cleaned_data['age_speech_centre']\n hand = request.POST['hand']\n leg = request.POST['leg']\n both_hand = request.POST['both_hand']\n stop_left_hand = request.POST['stop_left_hand']\n age_stop_left_hand = child_form.cleaned_data['age_stop_left_hand']\n involuntary_urination = request.POST['involuntary_urination']\n cause_involuntary_urination = request.POST['cause_involuntary_urination']\n age_involutary_urination = child_form.cleaned_data['age_involutary_urination']\n medicines_bool = request.POST['medicines_bool']\n medicine_name = child_form.cleaned_data['medicine_name']\n medicine_reason = child_form.cleaned_data['medicine_reason']\n appetite = child_form.cleaned_data['appetite']\n fav_food = child_form.cleaned_data['fav_food']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.breastfeeding = breastfeeding\n cc.age_weaning = weaning_age\n cc.age_teething = age_tooth_start\n cc.age_commune = age_commune\n cc.age_pronouncing = age_simple_words\n cc.age_speech = age_speech\n cc.age_full_sentence = age_sentence\n cc.age_bottle_milk = age_bottle_carry\n cc.age_love = age_love\n cc.age_sat_self = age_sat\n cc.age_stop_self = age_stop\n cc.age_walking = age_walk\n cc.age_wearing_help = age_wore_help\n cc.age_wearing_self = age_wore_self\n cc.age_shoes = age_shoes\n cc.age_feeding = age_feed\n cc.age_urination = age_urination\n cc.age_bathroom = age_bathroom_train\n cc.visual_prob = visual_probs\n cc.use_glasses = use_glasses\n cc.age_glasses = age_glasses\n cc.hearing_prob = hearing_probs\n cc.use_hearing_aid = hearing_aid\n cc.age_hearing_aid = age_hearing_aid\n cc.diff_speaking = speaking_difficulty\n cc.treated_speech = treated_speech_centres\n cc.age_treated_speech = age_speech_centre\n cc.hand_writing = hand\n cc.leg_kicking = leg\n cc.both_hands = both_hand\n cc.stop_left_hand = stop_left_hand\n cc.age_stop_left_hand = age_stop_left_hand\n cc.involuntary_urination = involuntary_urination\n cc.cause_involuntary_urination = cause_involuntary_urination\n cc.age_involuntary_urination = age_involutary_urination\n cc.medicines_bool = medicines_bool\n cc.medicines_name = medicine_name\n cc.medicine_reason = medicine_reason\n cc.eating_habits = appetite\n cc.fav_food = fav_food\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_condition, id)\n elif 'next' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc_stages_of_growth.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_family_history(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n hyperinactivity = child_form.cleaned_data['hyperinactivity']\n reading = child_form.cleaned_data['reading']\n writing_dictating = child_form.cleaned_data['writing_dictating']\n calculating = child_form.cleaned_data['calculating']\n concentration = child_form.cleaned_data['concentration']\n pronouncing = child_form.cleaned_data['pronouncing']\n hearing = child_form.cleaned_data['hearing']\n visual = child_form.cleaned_data['visual']\n mobility = child_form.cleaned_data['mobility']\n intellectual = child_form.cleaned_data['intellectual']\n down_syndrome = child_form.cleaned_data['down_syndrome']\n autism = child_form.cleaned_data['autism']\n other_problems = child_form.cleaned_data['other_problems']\n child_hereditary = request.POST['child_hereditary']\n age_discovered = child_form.cleaned_data['age_discovered']\n effecting_child = child_form.cleaned_data['effecting_child']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.hyperinactivity = hyperinactivity\n cc.reading_diff = reading\n cc.writing_dictating_diff = writing_dictating\n cc.calculating_diff = calculating\n cc.concentration_diff = concentration\n cc.pronouncing_diff = pronouncing\n cc.impaired_hearing = hearing\n cc.visual_impairment = visual\n cc.impaired_mobility = mobility\n cc.intellectual_disability = intellectual\n cc.down_syn = down_syndrome\n cc.autism = autism\n cc.other_prob = other_problems\n cc.child_hereditary = child_hereditary\n cc.age_problem = age_discovered\n cc.prob_effect = effecting_child\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'next' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc_family_history.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_social_development(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n friends = child_form.cleaned_data['friends']\n siblings = child_form.cleaned_data['siblings']\n parents = child_form.cleaned_data['parents']\n adults = child_form.cleaned_data['adults']\n maid = child_form.cleaned_data['maid']\n maid_rel_age = child_form.cleaned_data['maid_rel_age']\n fam_auth = child_form.cleaned_data['fam_auth']\n link_fam = child_form.cleaned_data['link_fam']\n punishment_reward = request.POST['punishment_reward']\n punisher = child_form.cleaned_data['punisher']\n punishment = request.POST['punishment']\n spending_time = child_form.cleaned_data['spending_time']\n hobbies_child = child_form.cleaned_data['hobbies_child']\n m_lang = child_form.cleaned_data['m_lang']\n o_lang = child_form.cleaned_data['o_lang']\n dialects = request.POST['dialects']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.friends = friends\n cc.siblings = siblings\n cc.parents = parents\n cc.adults = adults\n cc.maid = maid\n cc.age_maid = maid_rel_age\n cc.fam_auth = fam_auth\n cc.fam_close = link_fam\n cc.punishment_sys = punishment_reward\n cc.punisher = punisher\n cc.punishment = punishment\n cc.spent_time_in = spending_time\n cc.fav_hobby = hobbies_child\n cc.main_lang = m_lang\n cc.other_lang = o_lang\n cc.dilects = dialects\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_family_history, id)\n elif 'next' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc-social-development.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_child_beh(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n mental_illness = request.POST['mental_illness']\n mental_illnesses = child_form.cleaned_data['mental_illnesses']\n time_alone = request.POST['time_alone']\n specific_friend = request.POST['specific_friend']\n diff_friend = request.POST['diff_friend']\n quarrel_friends = request.POST['quarrel_friends']\n o_like_play = request.POST['o_like_play']\n o_avoid_play = request.POST['o_avoid_play']\n f_older = request.POST['f_older']\n f_younger = request.POST['f_younger']\n attention_seeker = request.POST['attention_seeker']\n confi_ability = request.POST['confi_ability']\n quite = request.POST['quite']\n impulsive = request.POST['impulsive']\n activity_normal = request.POST['activity_normal']\n cooperative = request.POST['cooperative']\n lies = request.POST['lies']\n moody = request.POST['moody']\n bored = request.POST['bored']\n comp_tasks = request.POST['comp_tasks']\n sad = request.POST['sad']\n cheerful = request.POST['cheerful']\n aggressive = request.POST['aggressive']\n avoid_competition = request.POST['avoid_competition']\n compete_others = request.POST['compete_others']\n lazy = request.POST['lazy']\n leadership = request.POST['leadership']\n autonomy = request.POST['autonomy']\n time_task = request.POST['time_task']\n anxious = request.POST['anxious']\n feel_afraid = request.POST['feel_afraid']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.mental_illness_bool = mental_illness\n cc.mental_illness = mental_illnesses\n cc.spends_time_alone = time_alone\n cc.no_friend = specific_friend\n cc.diff_friend = diff_friend\n cc.quarrels_friend = quarrel_friends\n cc.like_to_play = o_like_play\n cc.avoid_to_play = o_avoid_play\n cc.older_friend = f_older\n cc.younger_friend = f_younger\n cc.seeker_attention = attention_seeker\n cc.confidence_ability = confi_ability\n cc.quite = quite\n cc.impulsive = impulsive\n cc.normal_activity = activity_normal\n cc.cooperative = cooperative\n cc.lies = lies\n cc.moody = moody\n cc.gets_bored = bored\n cc.completes_tasks = comp_tasks\n cc.sad = sad\n cc.cheerful = cheerful\n cc.aggressive = aggressive\n cc.avoid_competition = avoid_competition\n cc.compete_others = compete_others\n cc.lazy = lazy\n cc.leadership = leadership\n cc.self_reliance = autonomy\n cc.long_time_tasks = time_task\n cc.anxious = anxious\n cc.afraid = feel_afraid\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_social_development, id)\n elif 'next' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n\n\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc_child_beh.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_school_history(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n s_name_1 = child_form.cleaned_data['s_name_1']\n s_enroll_1 = child_form.cleaned_data['s_enroll_1']\n s_beh_1 = child_form.cleaned_data['s_beh_1']\n s_name_2 = child_form.cleaned_data['s_name_2']\n s_enroll_2 = child_form.cleaned_data['s_enroll_2']\n s_beh_2 = child_form.cleaned_data['s_beh_2']\n s_name_3 = child_form.cleaned_data['s_name_3']\n s_enroll_3 = child_form.cleaned_data['s_enroll_3']\n s_beh_3 = child_form.cleaned_data['s_beh_3']\n\n first_stage = child_form.cleaned_data['first_stage']\n stages_failed = request.POST['stages_failed']\n failure_class = child_form.cleaned_data['failure_class']\n failure_subjs = child_form.cleaned_data['failure_subjs']\n private_tutors = request.POST['private_tutors']\n advantage = child_form.cleaned_data['advantage']\n diff_teaching = request.POST['diff_teaching']\n teachers_note = child_form.cleaned_data['teachers_note']\n supervision_teaching = request.POST['supervision_teaching']\n achievement = child_form.cleaned_data['achievement']\n motivation = child_form.cleaned_data['motivation']\n enthusiasm = child_form.cleaned_data['enthusiasm']\n time_punctuality = child_form.cleaned_data['time_punctuality']\n fav_articles = child_form.cleaned_data['fav_articles']\n least_fav_material = child_form.cleaned_data['least_fav_material']\n rel_teachers = child_form.cleaned_data['rel_teachers']\n desire_school = child_form.cleaned_data['desire_school']\n absent_reasons = child_form.cleaned_data['absent_reasons']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.school_name_1 = s_name_1\n if s_enroll_1:\n cc.enroll_date_1 = format_date_model(s_enroll_1)\n else:\n cc.enroll_date_1 = None\n cc.attitude_school_1 = s_beh_1\n cc.school_name_2 = s_name_2\n if s_enroll_2:\n cc.enroll_date_2 = format_date_model(s_enroll_2)\n else:\n cc.enroll_date_2 = None\n cc.attitude_school_2 = s_beh_2\n cc.school_name_3 = s_name_3\n if s_enroll_3:\n cc.enroll_date_3 = format_date_model(s_enroll_3)\n else:\n cc.enroll_date_3 = None\n cc.attitude_school_3 = s_beh_3\n cc.first_stage = first_stage\n cc.failed = stages_failed\n cc.failed_class = failure_class\n cc.failed_subjs = failure_subjs\n cc.private_tutors = private_tutors\n cc.take_advantage = advantage\n cc.difficult_teaching = diff_teaching\n cc.teachers_note = teachers_note\n cc.supervision = supervision_teaching\n cc.academic_achievement = achievement\n cc.motivation = motivation\n cc.enthusiasm = enthusiasm\n cc.time_punctual = time_punctuality\n cc.fav_articles = fav_articles\n cc.least_fav_material = least_fav_material\n cc.rel_teachers = rel_teachers\n cc.desire_school = desire_school\n cc.reason_absent = absent_reasons\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'next' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n if cc.enroll_date_1:\n cc.enroll_date_1 = format_date_html(cc.enroll_date_1)\n else:\n cc.enroll_date_1 = ''\n if cc.enroll_date_2:\n cc.enroll_date_2 = format_date_html(cc.enroll_date_2)\n else:\n cc.enroll_date_2 = ''\n if cc.enroll_date_3:\n cc.enroll_date_3 = format_date_html(cc.enroll_date_3)\n else:\n cc.enroll_date_3 = ''\n return render(request, 'static_files/cc_school_history.html', {'obj': appoin, 'child': child, 'form': child_form,\n 'cc': cc})\n\n\ndef cc_diff_info(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n reading_d = request.POST['reading_d']\n dictating_d = request.POST['dictating_d']\n writing_d = request.POST['writing_d']\n remembering_nearby_d = request.POST['remembering_nearby_d']\n recog_time = request.POST['recog_time']\n recog_days = request.POST['recog_days']\n recog_dir = request.POST['recog_dir']\n work_on_time = request.POST['work_on_time']\n focus_attention = request.POST['focus_attention']\n understanding = request.POST['understanding']\n remembering_remote_d = request.POST['remembering_remote_d']\n relationships = request.POST['relationships']\n expressing = request.POST['expressing']\n remembering_d = request.POST['remembering_d']\n blackboard = request.POST['blackboard']\n printed = request.POST['printed']\n flip = request.POST['flip']\n numbers_letters = request.POST['numbers_letters']\n verbal_ins = request.POST['verbal_ins']\n listening = request.POST['listening']\n repeat = request.POST['repeat']\n dis_numbers = request.POST['dis_numbers']\n multiplication = request.POST['multiplication']\n phone_numbers_m = request.POST['phone_numbers_m']\n counting = request.POST['counting']\n add_subt = request.POST['add_subt']\n maths_sym = request.POST['maths_sym']\n size = request.POST['size']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.reading = reading_d\n cc.dictating = dictating_d\n cc.writing = writing_d\n cc.remembering_nearby = remembering_nearby_d\n cc.recog_time = recog_time\n cc.recog_days = recog_days\n cc.recog_directions = recog_dir\n cc.completing_work = work_on_time\n cc.focus_attention = focus_attention\n cc.understanding = understanding\n cc.remembering_remote = remembering_remote_d\n cc.relationships = relationships\n cc.expressing_ideas = expressing\n cc.remembering_skills = remembering_d\n cc.moving_blackboard = blackboard\n cc.copying_printed = printed\n cc.flip_words = flip\n cc.confuses_numbers = numbers_letters\n cc.understanding_verbal = verbal_ins\n cc.learning_listening = listening\n cc.repeat_instruction = repeat\n cc.distinguish_numbers = dis_numbers\n cc.memorizing_multiplication = multiplication\n cc.memorizing_phone = phone_numbers_m\n cc.counting_up = counting\n cc.performing_add_subt = add_subt\n cc.understanding_mathematical = maths_sym\n cc.distinguish_size = size\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_school_history, id)\n elif 'next' in request.POST:\n return redirect(cc_other_info, id)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step10' in request.POST:\n return redirect(cc_other_info, id)\n else:\n print(child_form.errors)\n\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n return render(request, 'static_files/cc_diff_info.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\ndef cc_other_info(request, id):\n appoin = Appointment.objects.filter(child_id=id).last()\n child = Person.objects.get(id=id)\n cc = ''\n if request.method == \"POST\":\n child_form = child_case_form(request.POST)\n if child_form.is_valid():\n # Get data\n follow_up = request.POST['follow_up']\n reason_1 = request.POST['reason_1']\n reason_2 = request.POST['reason_2']\n reason_3 = request.POST['reason_3']\n reason_4 = request.POST['reason_4']\n reason_5 = request.POST['reason_5']\n iq_test = request.POST['iq_test']\n date_last_a = child_form.cleaned_data['date_last_a']\n place_last_a = child_form.cleaned_data['place_last_a']\n other_info = request.POST['other_info']\n\n cc = Child_Case_Data.objects.get(child_id=id)\n cc.parents_cooperation = follow_up\n cc.reason_1 = reason_1\n cc.reason_2 = reason_2\n cc.reason_3 = reason_3\n cc.reason_4 = reason_4\n cc.reason_5 = reason_5\n cc.prev_iq = iq_test\n if date_last_a:\n cc.date_last_assessment = format_date_model(date_last_a)\n else:\n cc.date_last_assessment = None\n cc.place_last_assessment = place_last_a\n cc.other_info = other_info\n\n cc.save()\n\n if 'prev' in request.POST:\n return redirect(cc_diff_info, id)\n elif 'next' in request.POST:\n return redirect(appointment_list)\n elif 'step1' in request.POST:\n return redirect(child_case, id)\n elif 'step2' in request.POST:\n return redirect(cc_child_history, id)\n elif 'step3' in request.POST:\n return redirect(cc_condition, id)\n elif 'step4' in request.POST:\n return redirect(cc_stages_of_growth, id)\n elif 'step5' in request.POST:\n return redirect(cc_family_history, id)\n elif 'step6' in request.POST:\n return redirect(cc_social_development, id)\n elif 'step7' in request.POST:\n return redirect(cc_child_beh, id)\n elif 'step8' in request.POST:\n return redirect(cc_school_history, id)\n elif 'step9' in request.POST:\n return redirect(cc_diff_info, id)\n else:\n print(child_form.errors)\n\n else:\n child_form = child_case_form()\n cc = Child_Case_Data.objects.get(child_id=id)\n if cc.date_last_assessment:\n cc.date_last_assessment = format_date_html(cc.date_last_assessment)\n else:\n cc.date_last_assessment = ''\n return render(request, 'static_files/cc_other_info.html',\n {'obj': appoin, 'child': child, 'form': child_form, 'cc': cc})\n\n\n@login_required(login_url='login')\ndef send_link_form(request, id, language):\n child = Appointment.objects.get(id=id).child\n if child.email:\n form_link = f'http://40.89.138.111/ar/child-case-form/{child.id}/'\n print(language)\n if language == 'en':\n message = f\"Welcome,\\n To enter the data for the case form of {child.first_name} {child.parent.first_name} {child.last_name}, Please Click the following link:\\n\" + form_link + \\\n '\\n\\n With Regards \\n Kuwait Dyslexia Association.'\n elif language == 'ar':\n message = f' مرحبا بكم \\n لادخال بيانات استمارة الحالة {child.first_name} {child.parent.first_name} {child.last_name}, يرجى الضغط على الرابط التالي :\\n' + form_link + '\\nمع تحيات\\n الجمعية الكويتية للدسلكسيا\\n'\n else:\n message = ''\n send_mail('From KDA', message, \"info@q8da.com\", [child.email, 'portal@q8da.com'], fail_silently=False)\n # send_mail('From KDA', message, \"info@q8da.com\", ['hamza.zaid29@yahoo.com'], fail_silently=False)\n messages.success(request, message=\"Email sent.\")\n else:\n messages.success(request, message=\"No Email Found.\")\n\n return redirect(appointment_list)\n\n\n@login_required(login_url='login')\ndef add_intervention(request, id):\n if request.method == \"POST\":\n if 'sub' in request.POST:\n teacher_username = request.POST['teacher']\n teacher_id = Person.objects.get(username=teacher_username).id\n student_id = id\n if not teacher_username:\n messages.warning(request, message='Kindly Fill the Fields before Proceeding')\n return redirect(add_intervention, id)\n return redirect(check_intervention, student_id, teacher_id)\n # return redirect(weekly_grid, student_username, teacher_username)\n else:\n student = Person.objects.get(id=id)\n subjs = []\n teachers = []\n intvs = Intervention.objects.filter(student=student)\n for intv in intvs:\n subjs.append(intv.teacher.subject_teaching)\n if intv.teacher not in teachers:\n teachers.append(intv.teacher)\n all_teachers = Person.objects.filter(role__name='Teacher')\n for t in all_teachers:\n if t.subject_teaching not in subjs:\n teachers.append(t)\n return render(request, 'static_files/add_intervention.html', {'student': student, 'teachers': teachers})\n\n\n@login_required(login_url='login')\ndef check_intervention(request, student_id, teacher_id):\n intervention = Intervention.objects.filter(teacher_id=teacher_id,\n student_id=student_id).first()\n if intervention:\n back = False\n sessions = Session.objects.filter(intervention=intervention, is_active=True)\n sessions_count = sessions.count()\n if sessions_count >= 6:\n back = True\n return render(request, 'static_files/check_intervention.html',\n {'intervention': intervention, 'sessions': sessions,\n 'sessions_count': sessions_count, 'back': back})\n else:\n student = Person.objects.get(id=student_id)\n teacher = Person.objects.get(id=teacher_id)\n return render(request, 'static_files/check_intervention.html', {'student': student, 'teacher': teacher})\n\n\n@login_required(login_url='login')\ndef reschedule_session(request, id):\n if request.method == \"POST\":\n teacher_username = request.POST['teacher']\n teacher_id = Person.objects.get(username=teacher_username).id\n # student_username = request.POST['student']\n return redirect(weekly_grid, id, teacher_id)\n else:\n session = Session.objects.get(id=id)\n teachers = Person.objects.filter(role__name='Teacher',\n subject_teaching=session.intervention.teacher.subject_teaching)\n return render(request, 'static_files/add_intervention.html',\n {'teachers': teachers, 'student': session.intervention.student.full_name,\n 'session': session})\n\n\n@login_required(login_url='login')\ndef search_teacher(request):\n teachers = ''\n subjects = []\n if request.method == \"POST\":\n teachers = Person.objects.filter(role__name='Teacher')\n for teacher in teachers:\n subjects.append(teacher.subject_teaching)\n subj = request.POST['subject']\n name = request.POST['search_by_name']\n if subj:\n teachers = Person.objects.filter(role__name=\"Teacher\", subject_teaching__iexact=subj)\n elif name:\n name = name.split(\" \")\n for n in name:\n teachers = Person.objects.filter(role__name=\"Teacher\", first_name__icontains=n)\n if not teachers:\n teachers = Person.objects.filter(role__name=\"Teacher\", last_name__icontains=n)\n else:\n teachers = Person.objects.filter(role__name='Teacher')\n for teacher in teachers:\n if teacher.subject_teaching not in subjects:\n subjects.append(teacher.subject_teaching)\n\n return render(request, 'static_files/search_teacher.html', {'teachers': teachers, 'subjects': subjects})\n\n\ntime_slots_r = {'0800-0830': '0', '0830-0900': '1', '0900-0930': '2', '0930-1000': '3', '1000-1030': '4',\n '1030-1100': '5', '1100-1130': '6', '1130-1200': '7', '1200-1230': '8', '1230-1300': '9',\n '1300-1330': '10', '1330-1400': '11', '1400-1430': '12', '1430-1500': '13', '1500-1530': '14',\n '1530-1600': '15', '1600-1630': '16', '1630-1700': '17', '1700-1730': '18', '1730-1800': '19',\n '1800-1830': '20', '1830-1900': '21', '1900-1930': '22', '1930-2000': '23'}\n\n\n@login_required(login_url='login')\ndef weekly_grid(request, student_id, teacher_id):\n ava = Availability.objects.get(psychologist_id=teacher_id)\n if request.method == \"POST\":\n for x in range(24):\n if f'{x}-mon' in request.POST:\n a = (int(str(ava.m_available_time_from).split(':')[0]) - 8) * 2\n b = int((int(str(ava.m_available_time_from).split(':')[1])) / 30)\n start_time = a + b\n return redirect(confirm_slot, student_id, teacher_id, f'{x + start_time}-m')\n elif f'{x}-tue' in request.POST:\n a = (int(str(ava.tu_available_time_from).split(':')[0]) - 8) * 2\n b = int((int(str(ava.tu_available_time_from).split(':')[1])) / 30)\n start_time = a + b\n return redirect(confirm_slot, student_id, teacher_id, f'{x + start_time}-tu')\n elif f'{x}-wed' in request.POST:\n a = (int(str(ava.w_available_time_from).split(':')[0]) - 8) * 2\n b = int((int(str(ava.w_available_time_from).split(':')[1])) / 30)\n start_time = a + b\n return redirect(confirm_slot, student_id, teacher_id, f'{x + start_time}-w')\n elif f'{x}-th' in request.POST:\n a = (int(str(ava.th_available_time_from).split(':')[0]) - 8) * 2\n b = int((int(str(ava.th_available_time_from).split(':')[1])) / 30)\n start_time = a + b\n return redirect(confirm_slot, student_id, teacher_id, f'{x + start_time}-th')\n elif f'{x}-sat' in request.POST:\n a = (int(str(ava.sa_available_time_from).split(':')[0]) - 8) * 2\n b = int((int(str(ava.sa_available_time_from).split(':')[1])) / 30)\n start_time = a + b\n return redirect(confirm_slot, student_id, teacher_id, f'{x + start_time}-sa')\n elif f'{x}-sun' in request.POST:\n a = (int(str(ava.su_available_time_from).split(':')[0]) - 8) * 2\n b = int((int(str(ava.su_available_time_from).split(':')[1])) / 30)\n start_time = a + b\n return redirect(confirm_slot, student_id, teacher_id, f'{x + start_time}-su')\n else:\n content = {'s_mon': range(((int(str(ava.m_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.m_available_time_from).split(':')[1])) / 30)),\n 'mon': range(((int(str(ava.m_available_time_to).split(':')[0]) -\n int(str(ava.m_available_time_from).split(':')[0])) * 2) +\n int((int(str(ava.m_available_time_to).split(':')[1])) / 30) -\n int((int(str(ava.m_available_time_from).split(':')[1])) / 30)),\n 'e_mon': range(((20 - int(str(ava.m_available_time_to).split(':')[0])) * 2) -\n int((int(str(ava.m_available_time_to).split(':')[1])) / 30)),\n 's_tue': range(((int(str(ava.tu_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.tu_available_time_from).split(':')[1])) / 30)),\n 'tue': range(((int(str(ava.tu_available_time_to).split(':')[0]) -\n int(str(ava.tu_available_time_from).split(':')[0])) * 2) +\n int((int(str(ava.tu_available_time_to).split(':')[1])) / 30) -\n int((int(str(ava.tu_available_time_from).split(':')[1])) / 30)),\n 'e_tue': range(((20 - int(str(ava.tu_available_time_to).split(':')[0])) * 2) -\n int((int(str(ava.tu_available_time_to).split(':')[1])) / 30)),\n 's_wed': range(((int(str(ava.w_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.w_available_time_from).split(':')[1])) / 30)),\n 'wed': range(((int(str(ava.w_available_time_to).split(':')[0]) -\n int(str(ava.w_available_time_from).split(':')[0])) * 2) +\n int((int(str(ava.w_available_time_to).split(':')[1])) / 30) -\n int((int(str(ava.w_available_time_from).split(':')[1])) / 30)),\n 'e_wed': range(((20 - int(str(ava.w_available_time_to).split(':')[0])) * 2) -\n int((int(str(ava.w_available_time_to).split(':')[1])) / 30)),\n 's_th': range(((int(str(ava.th_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.th_available_time_from).split(':')[1])) / 30)),\n 'th': range(((int(str(ava.th_available_time_to).split(':')[0]) -\n int(str(ava.th_available_time_from).split(':')[0])) * 2) +\n int((int(str(ava.th_available_time_to).split(':')[1])) / 30) -\n int((int(str(ava.th_available_time_from).split(':')[1])) / 30)),\n 'e_th': range(((20 - int(str(ava.th_available_time_to).split(':')[0])) * 2) -\n int((int(str(ava.th_available_time_to).split(':')[1])) / 30)),\n 's_sat': range(((int(str(ava.sa_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.sa_available_time_from).split(':')[1])) / 30)),\n 'sat': range(((int(str(ava.sa_available_time_to).split(':')[0]) -\n int(str(ava.sa_available_time_from).split(':')[0])) * 2) +\n int((int(str(ava.sa_available_time_to).split(':')[1])) / 30) -\n int((int(str(ava.sa_available_time_from).split(':')[1])) / 30)),\n 'e_sat': range(((20 - int(str(ava.sa_available_time_to).split(':')[0])) * 2) -\n int((int(str(ava.sa_available_time_to).split(':')[1])) / 30)),\n 's_sun': range(((int(str(ava.su_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.su_available_time_from).split(':')[1])) / 30)),\n 'sun': range(((int(str(ava.su_available_time_to).split(':')[0]) -\n int(str(ava.su_available_time_from).split(':')[0])) * 2) +\n int((int(str(ava.su_available_time_to).split(':')[1])) / 30) -\n int((int(str(ava.su_available_time_from).split(':')[1])) / 30)),\n 'e_sun': range(((20 - int(str(ava.su_available_time_to).split(':')[0])) * 2) -\n int((int(str(ava.su_available_time_to).split(':')[1])) / 30))}\n\n intv_m = [int(time_slots_r[x.time]) - (((int(str(ava.m_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.m_available_time_from).split(':')[1])) / 30)) for x in\n Session.objects.filter(intervention__teacher_id=teacher_id, day=\"Monday\",\n intervention__status=\"Active\", is_active=True)]\n intv_tu = [int(time_slots_r[x.time]) - (((int(str(ava.tu_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.tu_available_time_from).split(':')[1])) / 30)) for x in\n Session.objects.filter(intervention__teacher_id=teacher_id, day=\"Tuesday\",\n intervention__status=\"Active\", is_active=True)]\n intv_w = [int(time_slots_r[x.time]) - (((int(str(ava.w_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.w_available_time_from).split(':')[1])) / 30)) for x in\n Session.objects.filter(intervention__teacher_id=teacher_id, day=\"Wednesday\",\n intervention__status=\"Active\", is_active=True)]\n intv_th = [int(time_slots_r[x.time]) - (((int(str(ava.th_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.th_available_time_from).split(':')[1])) / 30)) for x in\n Session.objects.filter(intervention__teacher_id=teacher_id, day=\"Thursday\",\n intervention__status=\"Active\", is_active=True)]\n intv_sa = [int(time_slots_r[x.time]) - (((int(str(ava.sa_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.sa_available_time_from).split(':')[1])) / 30)) for x in\n Session.objects.filter(intervention__teacher_id=teacher_id, day=\"Saturday\",\n intervention__status=\"Active\", is_active=True)]\n intv_su = [int(time_slots_r[x.time]) - (((int(str(ava.su_available_time_from).split(':')[0]) - 8) * 2) +\n int((int(str(ava.su_available_time_from).split(':')[1])) / 30)) for x in\n Session.objects.filter(intervention__teacher_id=teacher_id, day=\"Sunday\",\n intervention__status=\"Active\", is_active=True)]\n\n content2 = {'mon': intv_m, 'tue': intv_tu, 'wed': intv_w,\n 'th': intv_th, 'sat': intv_sa, 'sun': intv_su, 'ava': ava}\n return render(request, 'static_files/weekly_grid.html', {'content': content, 'content2': content2})\n\n\nweek = {'m': 'Monday', 'tu': 'Tuesday', 'w': 'Wednesday', 'th': 'Thursday', 'sa': 'Saturday',\n 'su': 'Sunday'}\ntime_slots = {'0': '0800-0830', '1': '0830-0900', '2': '0900-0930', '3': '0930-1000', '4': '1000-1030',\n '5': '1030-1100', '6': '1100-1130', '7': '1130-1200', '8': '1200-1230', '9': '1230-1300',\n '10': '1300-1330', '11': '1330-1400', '12': '1400-1430', '13': '1430-1500', '14': '1500-1530',\n '15': '1530-1600', '16': '1600-1630', '17': '1630-1700', '18': '1700-1730', '19': '1730-1800',\n '20': '1800-1830', '21': '1830-1900', '22': '1900-1930', '23': '1930-2000'}\n\n\n@login_required(login_url='login')\ndef confirm_slot(request, student_id, teacher_id, slot):\n teacher = Person.objects.get(id=teacher_id)\n stu = Person.objects.filter(id=student_id).first()\n session = None\n if not stu:\n session = Session.objects.get(id=student_id)\n stu = session.intervention.student\n slot1 = slot.split('-')\n start_date = ''\n if request.method == \"POST\":\n total_sessions = request.POST['total_sessions']\n intervention = Intervention.objects.filter(teacher=teacher, student=stu).first()\n if intervention:\n if not session:\n Session.objects.create(intervention=intervention, day=week[slot1[1]],\n time=f'{time_slots[slot1[0]]}')\n else:\n session.day = week[slot1[1]]\n session.time = f'{time_slots[slot1[0]]}'\n session.save()\n intervention.total_sessions = total_sessions\n intervention.save()\n else:\n # if Intervention.objects.filter(student=student, teacher=teacher).count() == 0:\n start_date = request.POST['start_date']\n s = start_date.split('/')\n st = datetime.date(int(s[2]), int(s[1]), int(s[0]))\n if daysname[str(st.weekday())] != week[slot1[1]] or st < current_time.date():\n messages.warning(request, message=f\"Enter Any Future date of {week[slot1[1]]}\")\n return redirect(confirm_slot, student_id, teacher_id, slot)\n # diff = current_time.date() - st\n # c_weeks = int(int(diff.days) / 7) + 1\n intervention = Intervention.objects.create(teacher=teacher, student=stu,\n status=\"Active\", start_date=st, total_sessions=total_sessions)\n session = Session.objects.create(intervention=intervention, day=week[slot1[1]],\n time=f'{time_slots[slot1[0]]}')\n # x = st\n # for c in range(c_weeks):\n # All_Intervention.objects.create(intervention=intervention, date=x)\n # x = x + datetime.timedelta(days=7)\n return redirect(search_intervention)\n # else:\n # intervention = Intervention.objects.get(student=student, teacher=teacher)\n # intervention.teacher = teacher\n # intervention.day = week[slot1[1]]\n # intervention.time = f'{time_slots[slot1[0]]}'\n # intervention.save()\n # return redirect(search_intervention)\n # return redirect(confirm_slot, student.username, username, slot)\n else:\n already = False\n total_sessions = None\n weekday = week[slot1[1]]\n timeslot = f'{time_slots[slot1[0]]}'\n students = Person.objects.filter(role__name=\"Student\")\n intervention = Intervention.objects.filter(teacher=teacher, student=stu).first()\n if intervention:\n already = True\n start_date = intervention.start_date\n total_sessions = intervention.total_sessions\n return render(request, 'static_files/confirm_slot_teacher.html', {'weekday': weekday, 'time_slot': timeslot,\n 'students': students, 'teacher': teacher,\n 'stu': stu, 'start_date': start_date,\n 'already': already,\n 'total_sessions': total_sessions})\n\n\n@login_required(login_url='login')\ndef search_intervention(request):\n if request.user.role.name == 'Receptionist':\n interventions = Intervention.objects.filter(status='Active').order_by('start_date')\n else:\n interventions = Intervention.objects.filter(teacher=request.user, status=\"Active\").order_by('start_date')\n if request.method == \"POST\":\n sname = request.POST['search_by_sname']\n if request.user.role.name == 'Receptionist':\n tname = request.POST['search_by_tname']\n subj = request.POST['search_by_s']\n else:\n tname = ''\n subj = ''\n if subj:\n interventions = interventions.filter(teacher__subject_teaching=subj)\n if sname:\n interventions = interventions.filter(student__username=sname)\n if tname:\n interventions = interventions.filter(teacher__username=sname)\n\n all = []\n teachers = set()\n students = set()\n for intv in interventions:\n teachers.add(intv.teacher)\n students.add(intv.student)\n all.append(\n {'teacher': intv.teacher, 'student': intv.student, 'total_sessions': intv.total_sessions, 'id': intv.id,\n 'start_date': intv.start_date,\n 'sessions': [x for x in Session.objects.filter(intervention=intv, is_active=True)],\n 'count': Session.objects.filter(intervention=intv, is_active=True).count(),\n 'conducted': All_Intervention.objects.filter(session__intervention=intv,\n status='attended').count()})\n subjs = {x.subject_teaching for x in teachers}\n return render(request, 'static_files/search_intervention.html', {'interventions': all, 'teachers': teachers,\n 'students': students, 'subjs': subjs})\n\n\ndaysname_reverse = {'Monday': '0', 'Tuesday': '1', 'Wednesday': '2', 'Thursday': '3', 'Friday': '4', 'Saturday': '5',\n 'Sunday': '6'}\n\n\n@login_required(login_url='login')\ndef detail_intervention(request, id):\n intv = Intervention.objects.get(id=id)\n start_date = intv.start_date\n week_day_number_s = intv.start_date.weekday()\n difference_week_number = max(int(week_day_number_s) - int(daysname_reverse[intv.day]),\n int(daysname_reverse[intv.day]) - int(week_day_number_s))\n start_date = start_date + timezone.timedelta(difference_week_number)\n dates = [format_date_html(start_date)]\n difference_weeks = int((int((timezone.now().date() - intv.start_date).days)) / 7)\n for x in range(difference_weeks):\n start_date = start_date + timezone.timedelta(days=7)\n dates.append(format_date_html(start_date))\n return render(request, 'static_files/detail_intervention.html', {'intervention': intv, 'dates': dates})\n\n\n@login_required(login_url='login')\ndef delete_intervention(request, id):\n intv = Intervention.objects.get(id=id)\n intv.delete()\n\n return redirect(search_intervention)\n\n\n@login_required(login_url='login')\ndef status_intervention(request, id):\n intv = Intervention.objects.get(id=id)\n intv.status = \"Closed\"\n intv.save()\n\n return redirect(search_intervention)\n\n\n@login_required(login_url='login')\ndef search_assessment(request):\n if request.method == \"POST\":\n child_id = Person.objects.get(username=request.POST['child']).id\n if request.user.role.name == 'Receptionist':\n psy_id = Person.objects.get(username=request.POST['psy']).id\n else:\n psy_id = request.user.id\n return redirect(assess_tests, child_id, psy_id)\n else:\n children = Person.objects.filter(role__name=\"Student\")\n psys = Person.objects.filter(role__name=\"Physiologist\")\n return render(request, 'static_files/assessment_search.html', {'children': children, 'psys': psys})\n\n\n@login_required(login_url='login')\ndef assess_tests(request, id1, id2):\n child = Person.objects.get(id=id1)\n psy = Person.objects.get(id=id2)\n appointment = Appointment.objects.filter(child=child, psychologist=psy).last()\n if not appointment:\n messages.warning(request, message='There is no such appointment for the given child and psychologist!')\n return redirect(search_assessment)\n content = ''\n cog = ''\n if request.method == \"POST\":\n test = request.POST['test']\n if test == 'iq':\n count = Assessment_psy.objects.filter(appointment=appointment, test_name='iq').count()\n list_subs = ''\n if count != 0:\n assess = Assessment_psy.objects.filter(appointment=appointment, test_name='iq')\n list_subs = [x.sub_test_name for x in assess]\n content = {'test': test, 'subtests': ['IQ'], 'list_subs': list_subs}\n elif test == 'acops':\n count = Assessment_psy.objects.filter(appointment=appointment, test_name='acops').count()\n list_subs = ''\n if count != 0:\n assess = Assessment_psy.objects.filter(appointment=appointment, test_name='acops')\n list_subs = [x.sub_test_name for x in assess]\n content = {'test': test,\n 'subtests': ['Rabbits', 'Zoid Friends', 'Zoid Letter Names', 'Zoid Letters',\n 'Wock', 'Ryhms', 'Races', 'Toybox'], 'list_subs': list_subs}\n elif test == 'junior':\n count = Assessment_psy.objects.filter(appointment=appointment, test_name='junior').count()\n list_subs = ''\n if count != 0:\n assess = Assessment_psy.objects.filter(appointment=appointment, test_name='junior')\n list_subs = [x.sub_test_name for x in assess]\n content = {'test': test, 'subtests': ['Spelling', 'Reading', 'Single Word Reading', 'Mobile',\n 'Funny Words', 'Segment', 'Cave'], 'list_subs': list_subs}\n elif test == 'secondary':\n count = Assessment_psy.objects.filter(appointment=appointment, test_name='secondary').count()\n list_subs = ''\n if count != 0:\n assess = Assessment_psy.objects.filter(appointment=appointment, test_name='secondary')\n list_subs = [x.sub_test_name for x in assess]\n content = {'test': test, 'subtests': ['Spelling', 'Reading', 'Single Word Reading', 'Mobile',\n 'Funny Words', 'Segment', 'Cave'], 'list_subs': list_subs}\n elif test == 'standford':\n count = Assessment_psy.objects.filter(appointment=appointment, test_name='standford').count()\n list_subs = ''\n if count != 0:\n assess = Assessment_psy.objects.filter(appointment=appointment, test_name='standford')\n list_subs = [x.sub_test_name for x in assess]\n content = {'test': test, 'subtests': ['Stanford'], 'list_subs': list_subs}\n elif test == 'weksler':\n count = Assessment_psy.objects.filter(appointment=appointment, test_name='weksler').count()\n list_subs = ''\n if count != 0:\n assess = Assessment_psy.objects.filter(appointment=appointment, test_name='weksler')\n list_subs = [x.sub_test_name for x in assess]\n content = {'test': test, 'subtests': ['Vocabulary IQ', 'Practical IQ', 'Total IQ'],\n 'list_subs': list_subs}\n count = Cognitive_assessment.objects.filter(appointment=appointment, test_name=test).count()\n if count != 0:\n cog = Cognitive_assessment.objects.get(appointment=appointment, test_name=test)\n cog.cognitive_date = format_date_html(cog.cognitive_date)\n if 'cognitive' in request.POST:\n if request.POST['cognitive_date']:\n if count == 0:\n cog = Cognitive_assessment.objects.create(appointment=appointment, test_name=test,\n cognitive_date=format_date_model(\n request.POST['cognitive_date']),\n cognitive_result=request.POST['cognitive_result'],\n recommendations=request.POST['recommendations'],\n notice=request.POST['notice'])\n cog.cognitive_date = format_date_html(cog.cognitive_date)\n else:\n cog = Cognitive_assessment.objects.get(appointment=appointment, test_name=test)\n cog.cognitive_date = format_date_model(request.POST['cognitive_date'])\n cog.cognitive_result = request.POST['cognitive_result']\n cog.recommendations = request.POST['recommendations']\n cog.notice = request.POST['notice']\n cog.save()\n cog.cognitive_date = format_date_html(cog.cognitive_date)\n # appoints = Appointment.objects.filter(child=child, psychologist=psy, appointment_date__=)\n appoints = ''\n return render(request, 'static_files/assess_tests.html',\n {'child': child, 'content': content, 'cog': cog, 'psy': psy, 'appoints': appoints})\n\n\ntest_dict = {'iq': 'IQ', 'acops': 'ACOPS', 'junior': 'Junior', 'secondary': 'Secondary', 'standford': 'Standford',\n 'weksler': 'Weksler'}\n\n\n@login_required(login_url='login')\ndef assessment(request, id1, id2, test, subtest):\n appointment = Appointment.objects.filter(child_id=id1, psychologist_id=id2).last()\n assess = ''\n count = Assessment_psy.objects.filter(appointment=appointment, test_name=test,\n sub_test_name=subtest).count()\n if Cognitive_assessment.objects.filter(appointment=appointment, test_name=test).count() != 0:\n cog = Cognitive_assessment.objects.get(appointment=appointment, test_name=test)\n else:\n cog = ''\n if request.method == \"POST\":\n if count == 0:\n if test == \"weksler\":\n assess = Assessment_psy.objects.create(appointment=appointment, test_name=test,\n sub_test_name=subtest, sub_score_float=request.POST['sub_score'],\n sub_percentage=request.POST['sub_percent'],\n test_date=format_date_model(request.POST['test_date']))\n elif test == 'junior' or test == 'secondary' or test == 'acops':\n assess = Assessment_psy.objects.create(appointment=appointment, test_name=test,\n sub_test_name=subtest, sub_score=request.POST['sub_score'],\n sub_time=request.POST['sub_time'],\n sub_grade=request.POST['sub_grade'],\n test_date=format_date_model(request.POST['test_date']))\n else:\n assess = Assessment_psy.objects.create(appointment=appointment, test_name=test,\n sub_test_name=subtest, sub_score=request.POST['sub_score'],\n sub_time=request.POST['sub_time'],\n sub_grade=request.POST['sub_grade'],\n test_date=format_date_model(request.POST['test_date']), )\n if cog:\n assess.cognitive = cog\n else:\n assess = Assessment_psy.objects.get(appointment=appointment, test_name=test,\n sub_test_name=subtest)\n if test == \"weksler\":\n assess.sub_score_float = request.POST['sub_score']\n assess.sub_percentage = request.POST['sub_percent']\n assess.test_date = format_date_model(request.POST['test_date'])\n elif test == 'junior' or test == 'secondary' or test == 'acops':\n assess.sub_score = request.POST['sub_score']\n assess.sub_time = request.POST['sub_time']\n assess.sub_grade = request.POST['sub_grade']\n assess.test_date = format_date_model(request.POST['test_date'])\n else:\n assess.sub_score = request.POST['sub_score']\n assess.sub_time = request.POST['sub_time']\n assess.sub_grade = request.POST['sub_grade']\n assess.test_date = format_date_model(request.POST['test_date'])\n if cog:\n assess.cognitive = cog\n assess.save()\n return redirect(assess_tests, id1, id2)\n else:\n child = Person.objects.get(id=id1)\n if count != 0:\n assess = Assessment_psy.objects.get(appointment=appointment, test_name=test,\n sub_test_name=subtest)\n assess.test_date = format_date_html(assess.test_date)\n assess.sub_time = str(assess.sub_time)\n assess.sub_score = str(assess.sub_score)\n # assess.cognitive_date = format_date_html(assess.cognitive_date)\n return render(request, 'static_files/assessment.html', {'child': child, 'assess': assess,\n 'Test': test_dict[test], 'subtest': subtest,\n 'number': range(21)})\n\n\n@login_required(login_url='login')\ndef search_teacher_pre(request):\n if request.method == \"POST\":\n t_username = request.POST['teacher']\n teacher_id = Person.objects.get(username=t_username).id\n return redirect(pre_evaluation_search, teacher_id)\n teachers = Person.objects.filter(role__name=\"Teacher\")\n return render(request, 'static_files/select_teacher_assess.html', {'teachers': teachers})\n\n\n@login_required(login_url='login')\ndef pre_evaluation_search(request, teacher_id):\n teacher = Person.objects.get(id=teacher_id)\n # if request.method == \"POST\":\n # # student = Person.objects.get(username=request.POST['student'])\n # for stu in Person.objects.filter(role__name=\"Student\"):\n # if stu.username in request.POST:\n # if teacher.subject_teaching == \"English\":\n # return redirect(pre_evaluation, t_username, stu.id)\n # elif teacher.subject_teaching == \"Arabic\":\n # return redirect(pre_evaluation_arabic, t_username, stu.id)\n intvs = Intervention.objects.filter(teacher_id=teacher_id)\n students = []\n pre_eva_counts = []\n for intv in intvs:\n students.append(Person.objects.get(id=intv.student.id))\n # pre_eva_counts.update({f'{intv.student.id}': Pre_Evaluation.objects.filter(teacher_id=7, student_id=intv.student.id).count()})\n if Pre_Evaluation.objects.filter(intervention=intv).count() != 0:\n pre_eva_counts.append(intv.student.id)\n return render(request, 'static_files/pre_eva_search.html', {'students': students, 'pre_eva_counts': pre_eva_counts,\n 'teacher': teacher, 'intvs': intvs})\n\n\n@login_required(login_url='login')\ndef pre_evaluation(request, id):\n intervention = Intervention.objects.get(id=id)\n skill_english = ''\n count = Pre_Evaluation.objects.filter(intervention=intervention).count()\n if request.method == \"POST\":\n reading = request.POST['reading']\n writing = request.POST['writing']\n if count == 0:\n obj = Pre_Evaluation.objects.create(intervention=intervention)\n Skill_English_Pre.objects.create(pre_eva=obj, one=reading, two=writing)\n else:\n pre_eva = Pre_Evaluation.objects.get(intervention=intervention)\n skill_english = Skill_English_Pre.objects.get(pre_eva=pre_eva)\n skill_english.one = reading\n skill_english.two = writing\n skill_english.save()\n\n return redirect(pre_evaluation_search, intervention.teacher.id)\n else:\n if count != 0:\n pre_eva = Pre_Evaluation.objects.get(intervention=intervention)\n skill_english = Skill_English_Pre.objects.get(pre_eva=pre_eva)\n return render(request, 'static_files/pre_evaluation.html',\n {'intervention': intervention, 'skill_english': skill_english,\n 'subj': 'English'})\n\n\n@login_required(login_url='login')\ndef pre_evaluation_arabic(request, id):\n intervention = Intervention.objects.get(id=id)\n skill_arabic = ''\n count = Pre_Evaluation.objects.filter(intervention=intervention).count()\n if request.method == \"POST\":\n one = request.POST['one']\n two = request.POST['two']\n three = request.POST['three']\n four = request.POST['four']\n five = request.POST['five']\n six = request.POST['six']\n seven = request.POST['seven']\n eight = request.POST['eight']\n if count == 0:\n obj = Pre_Evaluation.objects.create(intervention=intervention)\n Skill_Arabic_Pre.objects.create(pre_eva=obj, one=one, two=two, three=three, four=four, five=five, six=six,\n seven=seven, eight=eight)\n else:\n pre_eva = Pre_Evaluation.objects.get(intervention=intervention)\n skill_arabic = Skill_Arabic_Pre.objects.get(pre_eva=pre_eva)\n skill_arabic.one = one\n skill_arabic.two = two\n skill_arabic.three = three\n skill_arabic.four = four\n skill_arabic.five = five\n skill_arabic.six = six\n skill_arabic.seven = seven\n skill_arabic.eight = eight\n skill_arabic.save()\n\n return redirect(pre_evaluation_search, intervention.teacher.id)\n else:\n if count != 0:\n pre_eva = Pre_Evaluation.objects.get(intervention=intervention)\n skill_arabic = Skill_Arabic_Pre.objects.get(pre_eva=pre_eva)\n return render(request, 'static_files/pre_evaluation.html',\n {'intervention': intervention, 'skill_arabic': skill_arabic,\n 'subj': 'Arabic'})\n\n\ndaysname = {'0': 'Monday', '1': 'Tuesday', '2': 'Wednesday', '3': 'Thursday', '4': 'Friday', '5': 'Saturday',\n '6': 'Sunday'}\n\n\n@login_required(login_url='login')\ndef select_teacher_assess(request):\n if request.method == \"POST\":\n teacher = request.POST['teacher']\n teacher_id = Person.objects.get(username=teacher).id\n # teacher = Person.objects.get(username=teacher)\n return redirect(session_evaluation_search, teacher_id)\n else:\n teachers = Person.objects.filter(role__name=\"Teacher\")\n return render(request, 'static_files/select_teacher_assess.html', {'teachers': teachers})\n\n\n@login_required(login_url='login')\ndef session_evaluation_search(request, teacher_id):\n intvs = Intervention.objects.filter(teacher_id=teacher_id, status='Active')\n students = []\n for intv in intvs:\n students.append(Person.objects.get(id=intv.student.id))\n if request.method == \"POST\":\n student = int(request.POST['student'])\n intv = intvs.get(student_id=student)\n all_intv = All_Intervention.objects.filter(session__intervention=intv, status='attended')\n if 'next' in request.POST:\n return redirect(session_evaluation, request.POST['date'])\n return render(request, 'static_files/session_evaluation_search.html', {'students': students, 'stu': student,\n 'all_intvs': all_intv, 'display': True})\n else:\n return render(request, 'static_files/session_evaluation_search.html', {'students': students})\n\n\n@login_required(login_url='login')\ndef session_evaluation(request, id):\n a_intervention = All_Intervention.objects.get(id=id)\n intervention = Intervention.objects.get(session__all_intv=a_intervention)\n\n if a_intervention.session.intervention.teacher.subject_teaching == \"English\":\n skills_english_objs = Skill_English.objects.filter(a_intervention__session__intervention=intervention)\n\n skills_english = {'cvc2': '', 'letter': '', 'cvc4': '', 'syllable': '', 'spelling': '', 'cvcd': '', 'vccv': '',\n 'iblends': '', 'fblends': '', 'review92': '', 'vcccv': '', 'ngnk': '', 'suffix': '',\n 'magic': '', 'magic_e': '', 'cvce_test': '', 'magic2e': '', 'smagice': '', 'vcv': '',\n 'ph': '', 'ck': '', 'vowel': '', 'kkck': '', 'erir': '', 'owou': '', 'igh': '', 'ble': '',\n 'le': '', 'yvy': '', 'ild': '', 'aror': '', 'oo': '', 'y_vowel': '', 'soft_c': '',\n 'soft_g': '', 'gedge': '', 'gc': '', 'auaw': '', 'tch': '', 'ing': '', 'vcv_spelling': '',\n 'three_s': '', 'schwa': ''}\n\n if request.method == \"POST\":\n\n for skill in skills_english.keys():\n v = skills_english_objs.filter(skill_name=skill).first()\n if v:\n skills_english[skill] = v.grade\n if skill in request.POST:\n s = Skill_English.objects.create(skill_name=skill, grade=request.POST[skill],\n a_intervention=a_intervention)\n\n skills_english[skill] = s.grade\n return render(request, 'static_files/session_evaluation.html',\n {'a_intv': a_intervention, 'skills': skills_english})\n\n else:\n for skill in skills_english.keys():\n v = skills_english_objs.filter(skill_name=skill).first()\n if v:\n skills_english[skill] = v.grade\n print(skills_english)\n return render(request, 'static_files/session_evaluation.html',\n {'a_intv': a_intervention, 'skills': skills_english})\n else:\n skills_arabic_objs = Skill_Arabic.objects.filter(a_intervention__session__intervention=intervention)\n general = ['1', '2', '3', '4', '5', '6', '7', '9', '10', '11', '12', '13', '15', '16', '17', '18', '19', '20',\n '21', '29', '30', '31', '32', '33', '34', '35', '36', '37']\n\n if request.method == \"POST\":\n letter_number = request.POST.get('letter_number', '')\n letter = Arabic_Letter.objects.get(letter_number=letter_number)\n skills_arabic = []\n if letter_number in general:\n skills_arabic = ['f%one', 'f%two', 'f%three', 'f%four', 'f%five', 'f%six', 'f%seven', 'l%eight']\n elif letter_number == '8':\n skills_arabic = ['f%a_one', 'l%a_two']\n elif letter_number == '14':\n skills_arabic = ['l%b_one']\n elif letter_number == '22':\n skills_arabic = ['f%c_one', 'l%c_two']\n elif letter_number == '23':\n skills_arabic = ['f%d_one', 'f%d_two', 'f%d_three', 'l%d_four']\n elif letter_number == '24':\n skills_arabic = ['l%e_one']\n elif letter_number == '25':\n skills_arabic = ['l%f_one']\n elif letter_number == '26':\n skills_arabic = ['f%g_one', 'l%g_two']\n elif letter_number == '27':\n skills_arabic = ['f%h_one', 'l%h_two']\n elif letter_number == '28':\n skills_arabic = ['l%i_one']\n\n for skill in skills_arabic:\n if skill in request.POST:\n skil = skill.split('%')\n n_of_letters = skills_arabic_objs.count()\n if not skills_arabic_objs.filter(letter=letter).first():\n skills = Skill_Arabic.objects.create(a_intervention=a_intervention, letter=letter)\n x = skills._meta.get_field(skil[1])\n y = (str(x).split('.'))[2]\n setattr(skills, y, request.POST[skill])\n skills.save()\n else:\n skills = skills_arabic_objs.filter(letter=letter).first()\n skills.a_intervention = a_intervention\n x = skills._meta.get_field(skil[1])\n y = (str(x).split('.'))[2]\n setattr(skills, y, request.POST[skill])\n skills.save()\n if skil[0] == 'l':\n if int(letter_number) == 37:\n messages.success(request, message='All Letters Finished')\n return redirect(search_assessment)\n else:\n letter = Arabic_Letter.objects.get(letter_number=int(letter_number) + 1)\n Skill_Arabic.objects.create(a_intervention=a_intervention, letter=letter)\n return redirect(session_evaluation, id)\n\n return render(request, 'static_files/session_evaluation_arabic.html', {'a_intv': a_intervention,\n 'letter_number': letter_number,\n 'skills': skills,\n 'n_of_letters': n_of_letters,\n 'general': general})\n\n n_of_letters = skills_arabic_objs.count()\n if not skills_arabic_objs.filter(letter=letter).first():\n skills = Skill_Arabic.objects.create(a_intervention=a_intervention, letter=letter)\n else:\n skills = Skill_Arabic.objects.filter(a_intervention__session__intervention=intervention)\n return render(request, 'static_files/session_evaluation_arabic.html', {'a_intv': a_intervention,\n 'skills': skills,\n 'letter_number': letter_number,\n 'n_of_letters': n_of_letters,\n 'general': general})\n\n else:\n n_of_letters = skills_arabic_objs.count()\n if n_of_letters == 0:\n n_of_letters = 1\n # if count != 0:\n # reg_eva = Evaluation_regular.objects.get(intervention=a_intervention)\n # n_of_letters = Skill_Arabic.objects.filter(evaluation_regular=reg_eva).count()\n return render(request, 'static_files/session_evaluation_arabic.html', {'a_intv': a_intervention,\n 'letter_number': 0,\n 'n_of_letters': n_of_letters,\n 'general': general})\n\n\n@login_required(login_url='login')\ndef registration_student(request):\n if request.method == \"POST\":\n f_name = request.POST['f_name']\n l_name = request.POST['l_name']\n gender = request.POST['gender']\n dob = request.POST['dob']\n nationality = request.POST['nationality']\n language = request.POST['language']\n profile_pic = request.FILES.get('profile_pic', None)\n id_pic = request.FILES.get('id_pic', None)\n g_f_name = request.POST['g_f_name']\n g_l_name = request.POST['g_l_name']\n country_code = request.POST['country_code']\n mobile_number = request.POST['mobile']\n email = request.POST['email']\n school_name = request.POST['school_name']\n class_name = request.POST['class_name']\n s_language = request.POST['s_language']\n\n parent = Person.objects.filter(first_name=g_f_name, last_name=g_l_name, country_code=country_code,\n mobile_number=mobile_number).first()\n if not parent:\n role = Role.objects.get(name='Parent')\n parent = Person.objects.create(first_name=g_f_name, last_name=g_l_name, country_code=country_code,\n mobile_number=mobile_number)\n # g_f_name = ''.join(parent.first_name.split(' '))\n # g_l_name = ''.join(parent.last_name.split(' '))\n parent.username = f'{parent.mobile_number}'\n parent.role = role\n parent.save()\n student = Person(email=email, first_name=f_name, last_name=l_name, gender=gender,\n dob=format_date_model(dob), profile_pic=profile_pic, register_id=id_pic,\n mobile_number=mobile_number,\n country_code=country_code,\n school=school_name, class_name=class_name, nationality=nationality, language=language,\n s_language=s_language)\n f_name = ''.join(student.first_name.split(' '))\n l_name = ''.join(student.last_name.split(' '))\n student.username = f'{f_name}{l_name}{student.id}'\n # student.username = ''.join(student.username.split(' '))\n role = Role.objects.get(name=\"Student\")\n student.role = role\n student.approved = True\n student.parent = parent\n student.save()\n student.username = f'{student.id}'\n student.save()\n\n return redirect(search_student)\n return render(request, 'static_files/registration_student.html')\n\n\n@login_required(login_url='login')\ndef edit_student(request, id):\n student = Person.objects.get(id=id)\n\n if request.method == \"POST\":\n student.nationality = request.POST['nationality']\n student.language = request.POST['language']\n student.country_code = request.POST['country_code']\n student.mobile_number = request.POST['mobile']\n student.school = request.POST['school_name']\n student.class_name = request.POST['class_name']\n student.s_language = request.POST['s_language']\n\n g_f_name = request.POST['g_f_name']\n g_l_name = request.POST['g_l_name']\n parent = Person.objects.filter(first_name__icontains=g_f_name, last_name__icontains=g_l_name,\n country_code=request.POST['country_code'],\n mobile_number=request.POST['mobile']).first()\n if not parent and g_f_name:\n role = Role.objects.get(name='Parent')\n parent = Person.objects.create(first_name=g_f_name, last_name=g_l_name,\n country_code=request.POST['country_code'],\n mobile_number=request.POST['mobile'])\n # g_f_name = ''.join(parent.first_name.split(' '))\n # g_l_name = ''.join(parent.last_name.split(' '))\n parent.username = f'{parent.mobile_number}'\n parent.role = role\n parent.save()\n\n student.email = request.POST['email']\n student.save()\n\n return redirect(search_student)\n\n return render(request, 'static_files/registration_student.html', {'student': student, 'edit': True})\n\n\n@login_required(login_url='login')\ndef todays_appoint_list(request):\n children = set()\n psychologists = set()\n if request.user.role.name == 'Receptionist':\n appoin_list = Appointment.objects.filter(appointment_date=datetime.datetime.now().date())\n else:\n appoin_list = Appointment.objects.filter(psychologist=request.user,\n appointment_date=datetime.datetime.now().date())\n if request.method == \"POST\":\n s_by_name = request.POST['s_by_name']\n p_by_name = ''\n if request.user.role.name == \"Receptionist\":\n p_by_name = request.POST['p_by_name']\n if s_by_name:\n appoin_list = appoin_list.filter(child__username=s_by_name)\n if p_by_name:\n appoin_list = appoin_list.filter(psychologist__username=p_by_name)\n else:\n for appoint in appoin_list:\n children.add(appoint.child)\n psychologists.add(appoint.psychologist)\n return render(request, 'static_files/appointment_list.html', {'objs': appoin_list, 'today': True,\n 'children': children, 'psychologists': psychologists})\n\n\n@login_required(login_url='login')\ndef todays_intervention(request):\n status = ''\n students = set()\n teachers = set()\n subjs = set()\n if request.user.role.name == 'Receptionist':\n sessions = Session.objects.filter(day=daysname[str(datetime.datetime.now().weekday())],\n intervention__status='Active', is_active=True)\n else:\n sessions = Session.objects.filter(intervention__teacher=request.user,\n day=daysname[str(datetime.datetime.now().weekday())],\n intervention__status='Active', is_active=True)\n if request.method == \"POST\":\n sname = request.POST['search_by_sname']\n if request.user.role.name == 'Receptionist':\n tname = request.POST['search_by_tname']\n subj = request.POST['search_by_s']\n else:\n tname = ''\n subj = ''\n if subj:\n sessions = sessions.filter(intervention__teacher__subject_teaching=subj)\n if sname:\n sessions = sessions.filter(intervention__student__username=sname)\n if tname:\n sessions = sessions.filter(intervention__teacher__username=sname)\n\n cancelled_ids = {}\n f_reason = {'attended': 'Attended', 's_absent': 'Student Absent', 't_absent': 'Teacher Absent',\n 'cancelled': 'Cancelled'}\n for i in sessions:\n reason = All_Intervention.objects.get(session=i, date=current_time.date()).status\n cancelled_ids.update({i.id: f_reason[reason]})\n else:\n for session in sessions:\n students.add(session.intervention.student)\n teachers.add(session.intervention.teacher)\n subjs.add(session.intervention.teacher.subject_teaching)\n if All_Intervention.objects.filter(session=session, date=current_time.date()).count() == 0:\n All_Intervention.objects.create(session=session, date=current_time.date())\n cancelled_ids = {}\n f_reason = {'attended': 'Attended', 's_absent': 'Student Absent', 't_absent': 'Teacher Absent',\n 'cancelled': 'Cancelled'}\n for i in sessions:\n reason = All_Intervention.objects.get(session=i, date=current_time.date()).status\n cancelled_ids.update({i.id: f_reason[reason]})\n return render(request, 'static_files/todays_intervention.html', {'interventions': sessions, 'today': True,\n 'status': status, 'c_ids': cancelled_ids,\n 'students': students, 'teachers': teachers,\n 'subjs': subjs})\n\n\n@login_required(login_url='login')\ndef todays_status(request, id, reason):\n count = All_Intervention.objects.filter(session_id=id, date=current_time.date()).count()\n if count == 0:\n if Intervention.objects.get(id=id).status == 'Active':\n All_Intervention.objects.create(session_id=id, date=current_time.date(), reason=reason)\n else:\n obj = All_Intervention.objects.get(session_id=id, date=current_time.date())\n obj.status = reason\n obj.save()\n\n return redirect(todays_intervention)\n\n\n@login_required(login_url='login')\ndef search_student(request):\n students = ''\n if request.method == \"POST\":\n students = Person.objects.filter(role__name='Student')\n name = request.POST['search_by_name']\n if name:\n name = name.split(\" \")\n for n in name:\n students = Person.objects.filter(role__name=\"Student\", first_name__icontains=n)\n if not students:\n students = Person.objects.filter(role__name=\"Student\", last_name__icontains=n)\n else:\n students = Person.objects.filter(role__name='Student')\n\n return render(request, 'static_files/search_student.html', {'students': students})\n\n\n@login_required(login_url='login')\ndef report_all_appointments(request):\n appointments = Appointment.objects.all()\n psys = []\n children = []\n for appointment in appointments:\n if appointment.psychologist not in psys:\n psys.append(appointment.psychologist)\n if appointment.child not in children:\n children.append(appointment.child)\n if request.method == \"POST\":\n if 'range' in request.POST:\n fromm = request.POST['fromm']\n too = request.POST['to']\n if fromm and too:\n fromm = fromm.split('/')\n too = too.split('/')\n fromm = datetime.date(int(fromm[2]), int(fromm[1]), int(fromm[0]))\n too = datetime.date(int(too[2]), int(too[1]), int(too[0]))\n appoints = Appointment.objects.filter(appointment_date__gte=fromm, appointment_date__lte=too)\n assessments = []\n for p in appoints:\n if Assessment_psy.objects.filter(appointment=p).count() != 0:\n assessments.append(p)\n return render(request, 'static_files/report_all_appointments.html', {'psys': psys, 'display': 'dates',\n 'appoints': appoints,\n 'fromm': format_date_html(fromm),\n 'too': format_date_html(too),\n 'assessments': assessments})\n else:\n messages.warning(request, message=\"Kindly fill the range of dates\")\n return redirect(report_all_appointments)\n\n if 'psy_btn' in request.POST:\n psy = request.POST['psy']\n p = Person.objects.get(username=psy)\n assessments = []\n past_appoints = Appointment.objects.filter(psychologist__username=psy,\n appointment_date__lt=current_time.date())\n for pp in past_appoints:\n if Assessment_psy.objects.filter(appointment=pp).count() != 0:\n assessments.append(pp)\n current_appoints = Appointment.objects.filter(psychologist__username=psy,\n appointment_date__gte=current_time.date())\n return render(request, 'static_files/report_all_appointments.html', {'psys': psys, 'display': 'psy',\n 'psyy': p, 'p_appoints': past_appoints,\n 'c_appoints': current_appoints,\n 'assessments': assessments})\n if 'child_btn' in request.POST:\n child = request.POST['child']\n p = Person.objects.get(username=child)\n assessments = []\n past_appoints = Appointment.objects.filter(child__username=child,\n appointment_date__lt=current_time.date())\n for pp in past_appoints:\n if Assessment_psy.objects.filter(appointment=pp).count() != 0:\n assessments.append(pp)\n current_appoints = Appointment.objects.filter(child__username=child,\n appointment_date__gte=current_time.date())\n return render(request, 'static_files/report_all_appointments.html',\n {'children': children, 'display': 'child',\n 'ch': p, 'p_appoints': past_appoints,\n 'c_appoints': current_appoints,\n 'assessments': assessments})\n else:\n return render(request, 'static_files/report_all_appointments.html', {'psys': psys, 'children': children,\n 'display': 'all'})\n\n\n@login_required(login_url='login')\ndef report_all_sessions(request):\n intvs = Intervention.objects.all()\n teachers = []\n students = []\n for intv in intvs:\n if intv.teacher not in teachers:\n teachers.append(intv.teacher)\n if intv.student not in students:\n students.append(intv.student)\n student = ''\n if request.method == \"POST\":\n if 'range' in request.POST:\n fromm = (request.POST['fromm']).split('/')\n too = (request.POST['to']).split('/')\n fromm = datetime.date(int(fromm[2]), int(fromm[1]), int(fromm[0]))\n too = datetime.date(int(too[2]), int(too[1]), int(too[0]))\n sessions = All_Intervention.objects.filter(date__gte=fromm, date__lte=too)\n return render(request, 'static_files/report_all_sessions.html', {'teachers': teachers, 'display': 'dates',\n 'sessions': sessions,\n 'fromm': format_date_html(fromm),\n 'too': format_date_html(too)})\n past_sessions = ''\n t = ''\n p_sessions_dict = {}\n if 'teach' in request.POST:\n teacher = request.POST['teacher']\n t = Person.objects.get(username=teacher)\n past_sessions = All_Intervention.objects.filter(date__lte=current_time.date(),\n session__intervention__teacher=t)\n students = []\n for p in past_sessions:\n if p.session.intervention.student not in students:\n students.append(p.session.intervention.student)\n\n if 'stud_btn' in request.POST:\n stu_username = request.POST['student']\n s = Person.objects.get(username=stu_username)\n past_sessions = All_Intervention.objects.filter(date__lte=current_time.date(),\n session__intervention__student=s)\n\n return render(request, 'static_files/report_all_sessions.html', {'display': 'student',\n 'stud': s, 'p_sessions': past_sessions,\n 'students': students})\n\n if 'search' in request.POST:\n student = request.POST['student']\n teacher = request.POST['teacher']\n t = Person.objects.get(username=teacher)\n past_sessions = All_Intervention.objects.filter(date__lte=current_time.date(),\n session__intervention__teacher__username=teacher,\n session__intervention__student__username=student)\n if 'report' in request.POST:\n student = request.POST['student']\n teacher = request.POST['teacher']\n student_id = Person.objects.get(username=student).id\n teacher_id = Person.objects.get(username=teacher).id\n return redirect(report_session, teacher_id, student_id)\n return render(request, 'static_files/report_all_sessions.html', {'teachers': teachers, 'display': 'teacher',\n 'teacherr': t, 'p_sessions': past_sessions,\n 'students': students, 'stu': student, })\n else:\n sessions = Session.objects.filter(day=daysname[str(datetime.datetime.now().weekday())],\n intervention__status='Active', is_active=True)\n for session in sessions:\n if All_Intervention.objects.filter(session=session, date=current_time.date()).count() == 0:\n if session.intervention.status == 'Active':\n All_Intervention.objects.create(session=session, date=current_time.date())\n return render(request, 'static_files/report_all_sessions.html', {'teachers': teachers, 'display': 'all',\n 'students': students})\n\n\n@login_required(login_url='login')\ndef assessment_graph(request, id):\n objs = Assessment_psy.objects.filter(appointment_id=id)\n print(objs)\n appointment = objs.first().appointment\n child = appointment.child\n psy = appointment.psychologist\n\n singles = [0, 0, 0]\n singles_t = [0, 0, 0]\n acops = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n acops_t = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n junior = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n junior_t = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n secondary = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n secondary_t = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n for obj in objs:\n if obj.test_name == \"iq\":\n singles[0] = obj.sub_score\n singles_t[0] = obj.sub_time\n if obj.test_name == \"standford\":\n singles[1] = obj.sub_score\n singles_t[1] = obj.sub_time\n if obj.test_name == \"weksler\":\n if obj.sub_test_name == \"Total IQ\":\n singles[2] = float(obj.sub_score_float)\n if obj.test_name == \"acops\":\n if obj.sub_test_name == \"Rabbits\":\n acops[1] = obj.sub_score\n acops_t[1] = obj.sub_time\n if obj.sub_test_name == \"Zoid Friends\":\n acops[2] = obj.sub_score\n acops_t[2] = obj.sub_time\n if obj.sub_test_name == \"Zoid Letter Names\":\n acops[3] = obj.sub_score\n acops_t[3] = obj.sub_time\n if obj.sub_test_name == \"Zoid Letters\":\n acops[4] = obj.sub_score\n acops_t[4] = obj.sub_time\n if obj.sub_test_name == \"Wock\":\n acops[5] = obj.sub_score\n acops_t[5] = obj.sub_time\n if obj.sub_test_name == \"Ryhms\":\n acops[6] = obj.sub_score\n acops_t[6] = obj.sub_time\n if obj.sub_test_name == \"Races\":\n acops[7] = obj.sub_score\n acops_t[7] = obj.sub_time\n if obj.sub_test_name == \"Toybox\":\n acops[8] = obj.sub_score\n acops_t[8] = obj.sub_time\n if obj.test_name == \"junior\":\n if obj.sub_test_name == \"Spelling\":\n junior[1] = obj.sub_score\n junior_t[1] = obj.sub_time\n if obj.sub_test_name == \"Reading\":\n junior[2] = obj.sub_score\n junior_t[2] = obj.sub_time\n if obj.sub_test_name == \"Single Word Reading\":\n junior[3] = obj.sub_score\n junior_t[3] = obj.sub_time\n if obj.sub_test_name == \"Mobile\":\n junior[4] = obj.sub_score\n junior_t[4] = obj.sub_time\n if obj.sub_test_name == \"Funny Words\":\n junior[5] = obj.sub_score\n junior_t[5] = obj.sub_time\n if obj.sub_test_name == \"Segment\":\n junior[6] = obj.sub_score\n junior_t[6] = obj.sub_time\n if obj.sub_test_name == \"Cave\":\n junior[7] = obj.sub_score\n junior_t[7] = obj.sub_time\n if obj.test_name == \"secondary\":\n if obj.sub_test_name == \"Spelling\":\n secondary[1] = obj.sub_score\n secondary_t[1] = obj.sub_time\n if obj.sub_test_name == \"Reading\":\n secondary[2] = obj.sub_score\n secondary_t[2] = obj.sub_time\n if obj.sub_test_name == \"Single Word Reading\":\n secondary[3] = obj.sub_score\n secondary_t[3] = obj.sub_time\n if obj.sub_test_name == \"Mobile\":\n secondary[4] = obj.sub_score\n secondary_t[4] = obj.sub_time\n if obj.sub_test_name == \"Funny Words\":\n secondary[5] = obj.sub_score\n secondary_t[5] = obj.sub_time\n if obj.sub_test_name == \"Segment\":\n secondary[6] = obj.sub_score\n secondary_t[6] = obj.sub_time\n if obj.sub_test_name == \"Cave\":\n secondary[7] = obj.sub_score\n secondary_t[7] = obj.sub_time\n print(acops)\n return render(request, 'static_files/assessments_graph.html', {'singles': singles, 'singles_t': singles_t,\n 'child': child, 'psy': psy,\n 'acops': acops, 'acops_t': acops_t,\n 'junior': junior, 'junior_t': junior_t,\n 'secondary': secondary, 'secondary_t': secondary_t})\n\n\n@login_required(login_url='login')\ndef report_session(request, teacher_id, student_id):\n teacher = Person.objects.get(id=teacher_id)\n student = Person.objects.get(id=student_id)\n intervention = Intervention.objects.filter(student=student, teacher=teacher, status='Active').last()\n intv = All_Intervention.objects.filter(session__intervention=intervention)\n t_count = intv.count()\n attended = intv.filter(status='attended').count()\n cancelled = intv.filter(status='cancelled').count()\n s_absent = intv.filter(status='s_absent').count()\n t_absent = intv.filter(status='t_absent').count()\n counts = [t_count, attended, cancelled, s_absent, t_absent]\n\n percent_complete = ((attended) / (intervention.total_sessions)) * 100\n return render(request, 'static_files/report_session.html',\n {'intervention': intervention, 'teacher': teacher, 'student': student, 'counts': counts,\n 'percent_complete': percent_complete})\n\n\nclass GeneratePDF(View):\n def get(self, request, *args, **kwargs):\n # template = get_template('static_files/pdf.html')\n cc = Child_Case_Data.objects.get(child__username='student1')\n form = child_case_f(instance=cc)\n ss = serializers.serialize('json', [cc, ])\n pp = json.loads(ss)\n x = pp[0]['fields']\n context = {\n 'form': form.fields,\n 'obj': x\n }\n # html = template.render(context)\n pdf = render_to_pdf('pdfs/file1/page1.html', context)\n if pdf:\n response = HttpResponse(pdf, content_type='application/pdf')\n filename = \"Invoice_%s.pdf\" % \"12341231\"\n content = \"inline; filename='%s'\" % filename\n download = request.GET.get(\"download\")\n if download:\n content = \"attachment; filename='%s'\" % filename\n response['Content-Disposition'] = content\n return response\n return HttpResponse(\"Not found\")\n\n\n@login_required(login_url='login')\ndef english_session_report(request, id):\n a_intervention = All_Intervention.objects.get(id=id)\n intervention = Intervention.objects.get(session__all_intv=a_intervention)\n marks = {'mastery': 4, 'n_mastery': 2}\n eng = Skill_English.objects.filter(a_intervention__session__intervention=intervention).order_by('id')\n # eng = Skill_English.objects.filter(a_intervention=a_intervention).order_by('id')\n result = [0] * 45\n if eng:\n # z = 0\n # for x in eng._meta.get_fields():\n # y = (str(x).split('.'))[2]\n # if getattr(eng, y):\n # if getattr(eng, y) in marks.keys():\n # result[z] = marks[getattr(eng, y)]\n # z += 1\n z = 0\n for i in eng:\n result[z] = marks[i.grade]\n z += 1\n # result = result[2:]\n result1 = [0] + result[0:9]\n result2 = [0] + result[9:18]\n result3 = [0] + result[18:27]\n result4 = [0] + result[27:36]\n result5 = [0] + result[36:45]\n\n return render(request, 'static_files/english_session_report.html', {'a_intervention': a_intervention,\n 'result1': result1, 'result2': result2,\n 'result3': result3, 'result4': result4,\n 'result5': result5})\n\n\n@login_required(login_url='login')\ndef arabic_session_report(request, id):\n a_intervention = All_Intervention.objects.get(id=id)\n student = a_intervention.session.intervention.student\n teacher = a_intervention.session.intervention.teacher\n intervention = Intervention.objects.get(session__all_intv=a_intervention)\n n_of_letters = Skill_Arabic.objects.filter(a_intervention__session__intervention=intervention).count()\n if request.method == \"POST\":\n letter_number = request.POST['letter']\n letter = Arabic_Letter.objects.get(letter_number=letter_number)\n marks = {'acceptable': 2, 'good': 4, 'vgood': 6, 'excellent': 8}\n # eva_regular = Evaluation_regular.objects.filter(intervention=a_intervention).first()\n arabic = Skill_Arabic.objects.get(a_intervention__session__intervention=intervention,\n letter=letter)\n result = [0]\n general = ['1', '2', '3', '4', '5', '6', '7', '9', '10', '11', '12', '13', '15', '16', '17', '18', '19', '20',\n '21', '29', '30', '31', '32', '33', '34', '35', '36', '37']\n skills_arabic = []\n labels = []\n if letter_number in general:\n skills_arabic = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']\n labels = [\"\", \"يميز الصوت المكرر في الجملة العلاجية شفهياً\", \"يحدد مكان الحرف كتابياً.\",\n \"يميز بين صوت الحرف المعالج القصير والطويل\", \"يكتب الحرف المعالج بصوتيه الطويل والقصير.\",\n \"يحدد المقطع الساكن\", \"يقرأ جمل مكونة من كلمات مكونة من أصوات سبق دراستها.\",\n \"يميز بين الكلمات المتشابهة بوضع دائرة حول الكلمة التي توافق\",\n \"يكتب ما يملى عليه من كلمات مكونة من حروف سبق دراستها\"]\n elif letter_number == '8':\n skills_arabic = ['a_one', 'a_two']\n labels = [\"\", \"يميز بين أنواع التنوين الثلاثة\", \"يقرأ جمل محتوية على كلمات منونة\"]\n elif letter_number == '14':\n skills_arabic = ['b_one']\n labels = [\"\", \"يميز بين التاء المربوطة والمفتوحة\"]\n elif letter_number == '22':\n skills_arabic = ['c_one', 'c_two']\n labels = [\"\", \"يميز بين همزتي الوصل والقطع قراءةً\", \"يميز بين همزتي الوصل والقطع كتابةً\"]\n elif letter_number == '23':\n skills_arabic = ['d_one', 'd_two', 'd_three', 'd_four']\n labels = [\"\", \"يكتب كلمات محتوية على همزة متوسطة على ألف\", \"يكتب كلمات محتوية على همزة متوسطة على واو\",\n \"يكتب كلمات محتوية على همزة متوسطة على ياء\", \"يكتب كلمات محتوية على همزة متوسطة على السطر\"]\n elif letter_number == '24':\n skills_arabic = ['e_one']\n labels = [\"\", \"يميز بين اشكال الهمزة آخر الكلمة المسبوقة بفتحة وضمة وكسرة\"]\n elif letter_number == '25':\n skills_arabic = ['f_one']\n labels = [\"\", \"يميز بين الألف المتطرفة الممدودة والتي تكتب على شكل الياء المقصورة\"]\n elif letter_number == '26':\n skills_arabic = ['g_one', 'g_two']\n labels = [\"\", \"يميز المقطع المشددة قراءةً\", \"يميز المقطع المشدد كتابةً\"]\n elif letter_number == '27':\n skills_arabic = ['h_one', 'h_two']\n labels = [\"\", \"يميز بين اللام القمرية واللام الشمسية قراءةً\",\n \"يميز بين اللام القمرية واللام الشمسية كتابةً\"]\n elif letter_number == '28':\n skills_arabic = ['i_one']\n labels = [\"\",\n \"يجيد كتابة كلمات محتوية على ال التعريف دخل عليها حرف من حروف الجر ( بـ , كـ , لـ ) او حرف الفاء\"]\n\n for skill in skills_arabic:\n a = getattr(arabic, skill)\n if a:\n result.append(marks[a])\n else:\n result.append(0)\n\n return render(request, 'static_files/arabic_session_report.html', {'student': student, 'teacher': teacher,\n 'letter_number': letter_number,\n 'result': result, 'intv': a_intervention,\n 'n_of_letters': n_of_letters,\n 'labels': labels})\n return render(request, 'static_files/arabic_session_report.html', {'student': student, 'teacher': teacher,\n 'intv': a_intervention,\n 'n_of_letters': n_of_letters})\n\n\n@login_required(login_url='login')\ndef select_psy(request):\n if request.method == \"POST\":\n psy = request.POST['psy']\n psy_id = Person.objects.get(username=psy).id\n return redirect(dashboard_psy, psy_id)\n else:\n psys = Person.objects.filter(role__name='Physiologist')\n return render(request, 'static_files/select_psy.html', {'psys': psys})\n\n\n@login_required(login_url='login')\ndef dashboard_psy(request, psy_id):\n psy = Person.objects.get(id=psy_id)\n if request.method == \"POST\":\n if 's_child_btn' in request.POST:\n child_username = request.POST['s_child']\n if child_username:\n child = Person.objects.get(username=child_username)\n assessments = []\n past_appoints = Appointment.objects.filter(psychologist_id=psy_id,\n child__username=child_username,\n appointment_date__lt=current_time.date())\n for pp in past_appoints:\n if Assessment_psy.objects.filter(appointment=pp).count() != 0:\n assessments.append(pp)\n current_appoints = Appointment.objects.filter(psychologist_id=psy_id,\n child__username=child_username,\n appointment_date__gte=current_time.date())\n return render(request, 'static_files/dashboard_psy.html',\n {'psy': psy, 'display': 's_name', 'p_appoints': past_appoints,\n 'c_appoints': current_appoints, 'assessments': assessments, 'child': child})\n else:\n messages.warning(request, message=\"Kindly select a child before applying filter\")\n return redirect(dashboard_psy, psy.id)\n\n if 's_date_btn' in request.POST:\n selected_date = request.POST['s_date']\n if selected_date:\n selected_date = format_date_model(selected_date)\n assessments = []\n all_appointments = Appointment.objects.filter(psychologist_id=psy_id,\n appointment_date=selected_date)\n for pp in all_appointments:\n if Assessment_psy.objects.filter(appointment=pp).count() != 0:\n assessments.append(pp)\n return render(request, 'static_files/dashboard_psy.html',\n {'psy': psy, 'display': 's_date', 'appoints': all_appointments,\n 'assessments': assessments,\n 'ss_date': format_date_html(selected_date)})\n else:\n messages.warning(request, message=\"Kindly select a date before applying filter\")\n return redirect(dashboard_psy, psy.id)\n if 'range' in request.POST:\n from_date = request.POST['from_date']\n to_date = request.POST['to_date']\n if from_date and to_date:\n from_date = format_date_model(from_date)\n to_date = format_date_model(to_date)\n assessments = []\n all_appointments = Appointment.objects.filter(psychologist_id=psy_id,\n appointment_date__gte=from_date,\n appointment_date__lte=to_date)\n for pp in all_appointments:\n if Assessment_psy.objects.filter(appointment=pp).count() != 0:\n assessments.append(pp)\n return render(request, 'static_files/dashboard_psy.html',\n {'psy': psy, 'display': 'r_dates', 'appoints': all_appointments,\n 'assessments': assessments,\n 'f_date': format_date_html(from_date),\n 't_date': format_date_html(to_date)})\n else:\n messages.warning(request, message=\"Kindly select a date before applying filter\")\n return redirect(dashboard_psy, psy.id)\n else:\n all_appoints = Appointment.objects.filter(psychologist=psy)\n children = []\n for a in all_appoints:\n if a.child not in children:\n children.append(a.child)\n assessments = []\n past_appoints = Appointment.objects.filter(psychologist=psy, appointment_date__lt=current_time.date())\n pa_count = past_appoints.count()\n for pp in past_appoints:\n if Assessment_psy.objects.filter(appointment=pp).count() != 0:\n assessments.append(pp)\n current_appoints = Appointment.objects.filter(psychologist=psy,\n appointment_date__gte=current_time.date())\n ca_count = current_appoints.count()\n return render(request, 'static_files/dashboard_psy.html',\n {'psy': psy, 'display': 'all', 'p_appoints': past_appoints,\n 'c_appoints': current_appoints, 'assessments': assessments,\n 'children': children, 'pa_count': pa_count,\n 'ca_count': ca_count})\n\n\n@login_required(login_url='login')\ndef select_teacher(request):\n if request.method == \"POST\":\n teacher = request.POST['teacher']\n teacher_id = Person.objects.get(username=teacher).id\n return redirect(dashboard_teacher, teacher_id)\n else:\n teachers = Person.objects.filter(role__name='Teacher')\n return render(request, 'static_files/select_teacher.html', {'teachers': teachers})\n\n\n@login_required(login_url='login')\ndef dashboard_teacher(request, teacher_id):\n teacher = Person.objects.get(id=teacher_id)\n intvs = Session.objects.filter(intervention__teacher=teacher, intervention__status='Active', is_active=True)\n monday = {}\n tuesday = {}\n wednesday = {}\n thursday = {}\n saturday = {}\n sunday = {}\n for x in range(24):\n monday.update({x: ''})\n tuesday.update({x: ''})\n wednesday.update({x: ''})\n thursday.update({x: ''})\n saturday.update({x: ''})\n sunday.update({x: ''})\n\n for intv in intvs:\n if intv.day == 'Monday':\n monday.update({int(time_slots_r[intv.time]): intv})\n if intv.day == 'Tuesday':\n tuesday.update({int(time_slots_r[intv.time]): intv})\n if intv.day == 'Wednesday':\n wednesday.update({int(time_slots_r[intv.time]): intv})\n if intv.day == 'Thursday':\n thursday.update({int(time_slots_r[intv.time]): intv})\n if intv.day == 'Saturday':\n saturday.update({int(time_slots_r[intv.time]): intv})\n if intv.day == 'Sunday':\n sunday.update({int(time_slots_r[intv.time]): intv})\n\n from_date = ''\n to_date = ''\n if request.method == 'POST':\n from_date = format_date_model(request.POST['from_date'])\n to_date = format_date_model(request.POST['to_date'])\n\n all_intvs = All_Intervention.objects.filter(session__intervention__teacher=teacher, status='attended',\n date__gte=from_date, date__lte=to_date)\n else:\n all_intvs = All_Intervention.objects.filter(session__intervention__teacher=teacher)\n for all_intv in all_intvs:\n if all_intv.session.intervention.teacher_change_date:\n if all_intv.session.intervention.teacher_change_date >= all_intv.date:\n all_intvs.exclude(id=all_intv.id)\n\n on_going = Intervention.objects.filter(teacher=teacher, status='Active').count()\n concluded = all_intvs.count()\n attended = all_intvs.filter(status='attended').count()\n stu_absents = all_intvs.filter(status='s_absent').count()\n teacher_absents = all_intvs.filter(status='t_absent').count()\n cancelled = all_intvs.filter(status='cancelled').count()\n\n return render(request, 'static_files/dashboard_teacher.html', {'teacher': teacher, 'monday': monday,\n 'tuesday': tuesday, 'wednesday': wednesday,\n 'thursday': thursday, 'saturday': saturday,\n 'sunday': sunday, 'all_intvs': all_intvs,\n 'on_going': on_going, 'concluded': concluded,\n 'attended': attended, 'stu_absents': stu_absents,\n 'teacher_absents': teacher_absents,\n 'cancelled': cancelled, 'loop': range(24),\n 'from_date': '' if from_date == '' else format_date_html(\n from_date),\n 'to_date': '' if to_date == '' else format_date_html(\n to_date)})\n\n\n@login_required(login_url='login')\ndef select_student(request, fromm):\n if request.method == \"POST\":\n student_id = request.POST['student']\n # student_id = Person.objects.get(id=student).id\n if fromm == 'recep':\n return redirect(dashboard_student, student_id)\n elif fromm == 'intervention':\n return redirect(add_intervention, student_id)\n else:\n if request.user.role.name == \"Parent\":\n students = Person.objects.filter(parent=request.user, role__name='Student')\n else:\n students = Person.objects.filter(role__name='Student')\n return render(request, 'static_files/select_student.html', {'students': students, 'fromm': fromm})\n\n\n@login_required(login_url='login')\ndef dashboard_student(request, student_id):\n if request.method == \"POST\":\n if 'English' in request.POST:\n intervention = Intervention.objects.filter(student_id=student_id,\n teacher__subject_teaching='English').last()\n if request.FILES.get('homework_file'):\n Homeworks.objects.create(file=request.FILES.get('homework_file'), intervention=intervention)\n messages.success(request, message='Uploaded Successfully')\n elif 'Arabic' in request.POST:\n intervention = Intervention.objects.filter(student_id=student_id,\n teacher__subject_teaching='Arabic').last()\n if request.FILES.get('homework_file'):\n Homeworks.objects.create(file=request.FILES.get('homework_file'), intervention=intervention)\n messages.success(request, message='Uploaded Successfully')\n student = Person.objects.get(id=student_id)\n sessions = Intervention.objects.filter(student=student)\n subjs = {}\n all_interventions = []\n for s in sessions:\n subjs.update({s.teacher.subject_teaching: s})\n if s.pending_s_date:\n f_date = s.pending_s_date + datetime.timedelta(days=14)\n print(f_date)\n if current_time.date() > f_date:\n s.status = 'Not_Active'\n s.pending_s_date = None\n s.save()\n all_interventions.append({'teacher': s.teacher, 'student': s.student, 'total_sessions': s.total_sessions,\n 'start_date': s.start_date, 'status': s.status, 'id': s.id,\n 'sessions': [x for x in Session.objects.filter(intervention=s, is_active=True)],\n 'count': Session.objects.filter(intervention=s, is_active=True).count(),\n 'conducted': All_Intervention.objects.filter(session__intervention=s,\n status='attended').count()})\n assessment = Assessment_psy.objects.filter(appointment__child=student).first()\n all_intvs = All_Intervention.objects.filter(session__intervention__student=student)\n on_going = Intervention.objects.filter(student=student, status='Active').count()\n concluded = all_intvs.count()\n attended = all_intvs.filter(status='attended').count()\n stu_absents = all_intvs.filter(status='s_absent').count()\n teacher_absents = all_intvs.filter(status='t_absent').count()\n cancelled = all_intvs.filter(status='cancelled').count()\n child_case = Child_Case_Data.objects.filter(child_id=student_id).first()\n stanford = Assessment_psy.objects.filter(appointment__child=student, test_name='standford')\n secondary = Assessment_psy.objects.filter(appointment__child=student, test_name='secondary')\n junior = Assessment_psy.objects.filter(appointment__child=student, test_name='junior')\n acops = Assessment_psy.objects.filter(appointment__child=student, test_name='acops')\n parent = Person.objects.filter(children__id=student_id).first()\n if concluded > 0:\n attendance = 100 - ((stu_absents / (concluded - teacher_absents - cancelled)) * 100)\n else:\n attendance = 0\n return render(request, 'static_files/dashboard_student.html', {'student': student, 'subjs': subjs,\n 'assessment': assessment, 'all_intvs': all_intvs,\n 'all_interventions': all_interventions,\n 'on_going': on_going, 'concluded': concluded,\n 'attended': attended, 'stu_absents': stu_absents,\n 'teacher_absents': teacher_absents,\n 'cancelled': cancelled, 'attendance': attendance,\n 'child_case': child_case, 'stanford': stanford,\n 'secondary': secondary, 'junior': junior,\n 'parent': parent, 'acops': acops\n })\n\n\nskill_name = {'cvc2': 'Reviewing CVC words (2-3 letters)', 'letter': 'The letter sound',\n 'cvc4': 'Review Test CVC Words (2-4 letters)', 'syllable': 'Two-Syllable Compound Words',\n 'spelling': 'Spelling Rule –ff-ll-ss-zz ', 'cvcd': 'Spelling Rule –ff-ll-ss-zz ',\n 'vccv': 'Syllabication –Method VC/CV', 'iblends': 'Initial Blends', 'fblends': 'Final Consonant Blends',\n 'review92': 'Page 92 Review Test', 'vcccv': 'Multisyllabic words with Blends (VC/CV, VCCCV)',\n 'ngnk': 'ng and nk Endings ', 'suffix': 'Suffix: ed as /id/ ;/d/; /t/', 'magic': 'Magic E',\n 'magic_e': 'Review Test for Magic e Words', 'cvce_test': 'Review Test- CVC and CVCe Contrasts',\n 'magic2e': 'Review Test- CVC and CVCe Contrasts', 'smagice': 'Syllable Magic e',\n 'vcv': 'Syllable Magic e', 'ph': 'ph Digraph', 'ck': '-ck',\n 'vowel': 'Pre test Vowel Digraphs ea, oa, ai, ee, ay, oe Introduce Vowel Digraphs not mastered',\n 'kkck': 'Spellings for /k/: k, ck, or ke', 'erir': 'r-Controlled Vowels – er, ir, ,ur',\n 'owou': 'Dipthongs ow; ou', 'igh': '-igh',\n 'ble': 'Consonant le Endings (-ble; -fle; -tle; -dle; -gle; -kle; -ple; -zle)',\n 'le': 'Doubling Rule Consonant-le',\n 'yvy': 'Consonant-y Endings (y, vy, by, dy, ty, ry, ny, py, sy, my; -l y)',\n 'ild': 'Word endings in –ild; -old; -ind-; olt, ost', 'aror': 'r-Controlled Vowels – ar, or,',\n 'oo': 'Oo', 'y_vowel': 'y as a vowel', 'soft_c': 'Hard and Soft c', 'soft_g': 'Hard and Soft g',\n 'gedge': 'Hard and Soft g', 'gc': 'Hard and Soft g', 'auaw': 'The Three (au)s - aw -au -a',\n 'tch': 'Oi and oy, tch', 'ing': 'ing as an Ending',\n 'vcv_spelling': 'VCV Spelling Rule ( Alternative Spelling and Pronunciation)',\n 'three_s': 'Three Syllable Words', 'schwa': 'Schwa Sound'}\n\nletter_name = {1: 'الراء', 2: 'الباء', 3: 'العين', 4: 'الدال', 5: 'السين', 6: 'الميم', 7: 'النون', 8: 'التنوين',\n 9: 'الصاد', 10: 'الزاي', 11: 'الكاف', 12: 'الهاء', 13: 'النون', 14: 'التاء المربوطة', 15: 'الحاء',\n 16: 'الواو', 17: 'الفاء', 18: 'الياء', 19: 'الضاد', 20: 'اللام', 21: 'الألف', 22: 'همزتا الوصل والقطع',\n 23: 'الهمزة المتوسطة', 24: 'الهمزة آخر الكلمة', 25: 'الألف المتطرفة', 26: 'الشدة', 27: 'الـ التعريف',\n 28: 'مهارة دخول حرف على الكلمة المبدوءة بـ ال', 29: 'القاف', 30: 'الجيم', 31: 'التاء', 32: 'الطاء',\n 33: 'الغين', 34: 'الشين', 35: 'الذال', 36: 'الخاء', 37: 'الطاء'}\n\nskills_arabic = {'one': 'يميز الصوت المكرر في الجملة العلاجية', 'two': 'يضع دائة حول الحرف المعالج',\n 'three': 'يميز بين صوت الحرف المعالج القصير والطويل',\n 'four': 'يكتب الحرف المعالج بأشكاله بحسب موقعه بالجملة', 'five': 'يحدد المقطع الساكن',\n 'six': 'يركب كلمات من مقاطع مد', 'seven': 'يقرأ جمل مكونة من كلمات محتوية على أصوات سبق دراستها',\n 'eight': 'يكتب ما يملى عليه'}\n\ngrade = {'mastery': 4, 'n_mastery': 2}\ngrade_arabic = {'acceptable': 1, 'good': 2, 'vgood': 3, 'excellent': 4}\nmonths = {'1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June',\n '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'}\n\n\n@login_required(login_url='login')\ndef monitor_performance(request, student_id, subj):\n student = Person.objects.get(id=student_id)\n intv = Intervention.objects.get(student=student, teacher__subject_teaching=subj)\n if subj == \"English\":\n skill_objs = Skill_English.objects.filter(a_intervention__session__intervention=intv).order_by('id')\n percent_complete = ((skill_objs.count()) / 43) * 100\n skills = []\n sum_of_marks = 0\n # skill_names = [] # For Graph\n skill_month = [] # For Graph\n n = 1\n for skill in skill_objs:\n skill_month.append({'x': skill.a_intervention.date, 'y': n})\n n = n + 1\n skills.append({'skill_name': skill_name[skill.skill_name], 'date': skill.a_intervention.date,\n 'percentage': ((grade[skill.grade]) / 4) * 100})\n sum_of_marks = sum_of_marks + grade[skill.grade]\n # skill_month1 = [0] + skill_month[0:9]\n # skill_month2 = [0] + skill_month[9:18]\n # skill_month3 = [0] + skill_month[18:27]\n # skill_month4 = [0] + skill_month[27:36]\n # skill_month5 = [0] + skill_month[36:45]\n\n if skill_objs.count() != 0:\n overall_percentage = (sum_of_marks / (skill_objs.count() * 4)) * 100\n else:\n overall_percentage = 0\n return render(request, 'static_files/monitor_performance.html', {'student': student, 'subj': subj,\n 'percent_complete': percent_complete,\n 'skills': skills,\n 'skill_months': skill_month,\n 'overall': overall_percentage,\n })\n else:\n letter_objs = Skill_Arabic.objects.filter(a_intervention__session__intervention=intv)\n percent_complete = ((letter_objs.count()) / 37) * 100\n letters = []\n tt_count = 0\n tt_marks = 0\n letters_months = []\n grouped_skills = {'one': [0, 0], 'two': [0, 0], 'three': [0, 0], 'four': [0, 0], 'five': [0, 0], 'six': [0, 0],\n 'seven': [0, 0], 'eight': [0, 0]}\n n = 1\n for letter in letter_objs:\n t_count = 0\n t_marks = 0\n for field in letter._meta.get_fields():\n y = (str(field).split('.'))[2]\n if y != 'id' and y != 'a_intervention' and y != 'letter':\n if getattr(letter, y):\n if y in grouped_skills.keys():\n grouped_skills[y][0] = grouped_skills[y][0] + grade_arabic[getattr(letter, y)]\n grouped_skills[y][1] = grouped_skills[y][1] + 1\n t_marks = t_marks + grade_arabic[getattr(letter, y)]\n t_count = t_count + 1\n letters_months.append({'x': letter.a_intervention.date, 'y': n})\n n = n + 1\n letters.append({'letter_name': letter_name[letter.letter.letter_number], 'date': letter.a_intervention.date,\n 'percentage': 0 if t_count == 0 else (t_marks / (t_count * 4)) * 100})\n tt_marks = tt_marks + (0 if t_count == 0 else (t_marks / (t_count * 4)) * 100)\n tt_count = tt_count + 1\n\n # letters_month.pop()\n # letters_month1 = [0] + letters_month[0:9]\n # letters_month2 = [0] + letters_month[9:18]\n # letters_month3 = [0] + letters_month[18:27]\n # letters_month4 = [0] + letters_month[27:37]\n\n if tt_count != 0:\n overall_percentage = (tt_marks / tt_count)\n else:\n overall_percentage = 0\n skills = {}\n # if letters_month1 == [0]:\n # letters_month1 = [0]*10\n # if letters_month2 == [0]:\n # letters_month2 = [0]*10\n # if letters_month3 == [0]:\n # letters_month3 = [0]*10\n # if letters_month4 == [0]:\n # letters_month4 = [0]*11\n for skill, value in grouped_skills.items():\n if value[1] != 0:\n skills.update({skills_arabic[skill]: ((value[0]) / (value[1] * 4)) * 100})\n return render(request, 'static_files/monitor_performance.html', {'student': student, 'subj': subj,\n 'percent_complete': percent_complete,\n 'letters': letters,\n 'overall': overall_percentage,\n 'grouped_skills': skills,\n 'letters_months': letters_months,\n })\n\n\n@login_required(login_url='login')\ndef assign_parent(request, student_id):\n student = Person.objects.get(id=student_id)\n parents = Person.objects.filter(role__name='Parent')\n parent = Person.objects.filter(children__id=student_id).first()\n if request.method == \"POST\":\n parent_username = request.POST['parent']\n parent = Person.objects.get(username=parent_username)\n\n student.parent = parent\n student.save()\n\n return redirect(dashboard_student, student_id)\n return render(request, 'static_files/choose_parent.html', {'student': student, 'parents': parents,\n 'par': parent})\n\n\n@login_required(login_url='login')\ndef add_parent(request, student_id):\n student = Person.objects.get(id=student_id)\n if request.method == \"POST\":\n f_name = request.POST['f_name']\n l_name = request.POST['l_name']\n country_code = request.POST['country_code']\n mobile = request.POST['mobile']\n role = Role.objects.get(name='Parent')\n parent = Person.objects.create(first_name=f_name, last_name=l_name, username='aa', role=role,\n country_code=country_code, mobile_number=mobile)\n\n uf_name = ''.join(f_name.split(' '))\n ul_name = ''.join(l_name.split(' '))\n # username = f'{uf_name}{ul_name}{parent.id}'\n parent.username = f'{parent.mobile_number}'\n student.parent = parent\n\n student.save()\n parent.save()\n\n return redirect(dashboard_student, student_id)\n\n return render(request, 'static_files/add_parent.html', {'student': student})\n\n\ndef str_to_date(date_string):\n date_array = date_string.split('/')\n date = int(date_array[0])\n month = int(date_array[1])\n year = int(date_array[2])\n\n new_date = datetime.date(year, month, date)\n\n return new_date\n\n\n@login_required(login_url='login')\ndef change_status_student(request, id):\n intervention = Intervention.objects.get(id=id)\n current_status = intervention.status\n if request.method == 'POST':\n status = request.POST['status']\n intervention.status = status\n if status == 'Pending' or status == 'Not_Active':\n if status == 'Pending':\n intervention.pending_s_date = current_time.date()\n else:\n intervention.pending_s_date = None\n sessions = Session.objects.filter(intervention=intervention, is_active=True)\n for session in sessions:\n session.is_active = False\n session.save()\n intervention.save()\n else:\n intervention.pending_s_date = None\n intervention.save()\n if current_status == 'Pending':\n return redirect(check_intervention, intervention.student.id, intervention.teacher.id)\n elif current_status == 'Not_Active':\n return redirect(select_teacher_status_change, intervention.id)\n\n return redirect(dashboard_student, intervention.student.id)\n return render(request, 'static_files/change_status_student.html', {'intervention': intervention})\n\n\n@login_required(login_url='login')\ndef select_teacher_status_change(request, id):\n intervention = Intervention.objects.get(id=id)\n teachers = Person.objects.filter(role__name='Teacher',\n subject_teaching=intervention.teacher.subject_teaching).exclude(\n id=intervention.teacher.id)\n if request.method == 'POST':\n teacher_username = request.POST['teacher']\n teacher = Person.objects.get(username=teacher_username)\n intervention.teacher = teacher\n intervention.teacher_change_date = current_time.date()\n intervention.save()\n\n sessions = Session.objects.filter(intervention=intervention, is_active=True)\n for session in sessions:\n session.is_active = False\n session.save()\n\n return redirect(check_intervention, intervention.student.id, intervention.teacher.id)\n return render(request, 'static_files/select_teacher.html', {'teachers': teachers, 'status_change': True})\n\n\n@login_required(login_url='login')\ndef registration_psy(request):\n if request.method == \"POST\":\n f_name = request.POST['f_name']\n l_name = request.POST['l_name']\n email = request.POST['email']\n language = request.POST['language']\n country_code = request.POST['country_code']\n mobile_number = request.POST['mobile']\n id_pic = request.FILES.get('id_pic')\n username = request.POST['username']\n password = request.POST['password']\n\n person = Person.objects.filter(email=email).first()\n if person:\n messages.warning(request, message=\"Email Already Registered\")\n return redirect(registration_psy)\n person = Person.objects.filter(username=username).first()\n if person:\n messages.warning(request, message=\"Username Already in use. Try another!\")\n return redirect(registration_psy)\n\n psy = Person(first_name=f_name, last_name=l_name, register_id=id_pic, mobile_number=mobile_number,\n country_code=country_code,\n email=email, username=username, language=language, )\n role = Role.objects.get(name=\"Physiologist\")\n psy.role = role\n psy.approved = True\n psy.set_password(password)\n psy.save()\n\n for x in request.POST.getlist('checks'):\n Test.objects.get(test_name=x).psychologist.add(psy)\n\n return redirect(search_psy)\n return render(request, 'static_files/registration_psy.html')\n\n\n@login_required(login_url='login')\ndef change_password(request, id):\n person = Person.objects.get(id=id)\n if request.method == \"POST\":\n password = request.POST['password']\n person.set_password(password)\n person.save()\n\n messages.success(request, message=\"Password Changed\")\n if person.role.name == \"Teacher\":\n return redirect(search_teacher)\n elif person.role.name == \"Physiologist\":\n return redirect(search_psy)\n else:\n return redirect(search_student)\n return render(request, 'static_files/change_password.html', {'person': person})\n\n\n@login_required(login_url='login')\ndef test_lists(request, id):\n psy = Person.objects.get(id=id)\n tests = Test.objects.filter(psychologist=psy)\n\n return render(request, 'static_files/test_list.html', {'psy': psy, 'tests': tests})\n\n\n@login_required(login_url='login')\ndef registration_teacher(request):\n if request.method == \"POST\":\n f_name = request.POST['f_name']\n l_name = request.POST['l_name']\n email = request.POST['email']\n language = request.POST['language']\n country_code = request.POST['country_code']\n mobile_number = request.POST['mobile']\n id_pic = request.FILES.get('id_pic')\n qualification = request.POST['qualification']\n course = request.POST['course']\n certificate = request.FILES.get('certificate')\n username = request.POST['username']\n password = request.POST['password']\n\n person = Person.objects.filter(email=email).first()\n if person:\n messages.warning(request, message=\"Email Already Registered\")\n return redirect(registration_psy)\n person = Person.objects.filter(username=username).first()\n if person:\n messages.warning(request, message=\"Username Already in use. Try another!\")\n return redirect(registration_psy)\n\n teacher = Person(first_name=f_name, last_name=l_name, register_id=id_pic, mobile_number=mobile_number,\n country_code=country_code,\n email=email, username=username, language=language, qualification=qualification,\n subject_teaching=course, certificate=certificate)\n role = Role.objects.get(name=\"Teacher\")\n teacher.role = role\n teacher.approved = True\n teacher.set_password(password)\n teacher.save()\n\n return redirect(search_teacher)\n return render(request, 'static_files/registration_teacher.html')\n\n\nimport convertapi\n\nconvertapi.api_secret = 'IqqTZPI6mCvzto4E'\n\n\ndef test_pdf(request):\n # page1\n child = Person.objects.get(id=5)\n cc = Child_Case_Data.objects.get(child=child)\n appoint = Appointment.objects.filter(child=child).last()\n a = Assessment_psy.objects.filter(appointment__child=child, test_name='standford').first()\n\n reading = Assessment_psy.objects.filter(appointment__child_id=5, test_name='secondary',\n sub_test_name='Reading').last()\n spelling = Assessment_psy.objects.filter(appointment__child_id=5, test_name='junior',\n sub_test_name='Spelling').last()\n mobile = Assessment_psy.objects.filter(appointment__child_id=5, test_name='junior', sub_test_name='Mobile').last()\n funny = Assessment_psy.objects.filter(appointment__child_id=5, test_name='junior',\n sub_test_name='Funny Words').last()\n segment = Assessment_psy.objects.filter(appointment__child_id=5, test_name='junior', sub_test_name='Segment').last()\n cave = Assessment_psy.objects.filter(appointment__child_id=5, test_name='junior', sub_test_name='Cave').last()\n\n # acops\n rabbits = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Rabbits').last()\n zoid_friends = Assessment_psy.objects.filter(appointment__child=child, test_name='acops',\n sub_test_name='Zoid Friends').last()\n zoid_letter_names = Assessment_psy.objects.filter(appointment__child=child, test_name='acops',\n sub_test_name='Zoid Letter Names').last()\n zoid_letters = Assessment_psy.objects.filter(appointment__child=child, test_name='acops',\n sub_test_name='Zoid Letters').last()\n ryhms = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Ryhms').last()\n races = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Races').last()\n wock = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Wock').last()\n toybox = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Toybox').last()\n\n cognitive = Cognitive_assessment.objects.filter(appointment__child_id=5, test_name='acops').last()\n\n history = 'تبلغ ' + child.full_name + 'من العمر' + str(child.age_in_years) + 'سنة و' + str(child.age_in_months) + \\\n 'شهراً , وهي الإبنة '\n\n return render(request, 'pdfs/file1/acops.html', {'reading': reading, 'spelling': spelling, 'mobile': mobile,\n 'funny': funny, 'segment': segment,\n 'cave': cave, 'cognitive': cognitive, 'child': child,\n 'c': cc, 'appoint': appoint, 'a': a,\n 'rabbits': rabbits, 'zoid_friends': zoid_friends,\n 'zoid_letter_names': zoid_letter_names,\n 'zoid_letters': zoid_letters, 'ryhms': ryhms,\n 'races': races, 'wock': wock, 'toybox': toybox,\n 'history': history\n })\n\n\ndef Child_Case_PDF(request, id):\n cc = Child_Case_Data.objects.get(child_id=id)\n appoint = Appointment.objects.filter(child_id=id).first()\n\n return render(request, 'pdfs/file1/page1.html', {'c': cc, 'appoint': appoint})\n\n\ndef Stanford_PDF(request, id):\n child = Person.objects.get(id=id)\n cc = Child_Case_Data.objects.get(child=child)\n a = Assessment_psy.objects.filter(appointment__child=child, test_name='standford').last()\n cognitive = Cognitive_assessment.objects.filter(appointment__child=child).last()\n return render(request, 'pdfs/file1/stanford.html', {'a': a, 'child': child, 'cognitive': cognitive, 'c': cc})\n\n\ndef Weksler_PDF(request, id):\n child = Person.objects.get(id=id)\n cc = Child_Case_Data.objects.get(child=child)\n a = Assessment_psy.objects.filter(appointment__child=child, test_name='weksler').last()\n cognitive = Cognitive_assessment.objects.filter(appointment__child=child).last()\n return render(request, 'pdfs/file1/weksler.html', {'a': a, 'child': child, 'cognitive': cognitive, 'c': cc})\n\n\ndef Secondary_PDF(request, id):\n child = Person.objects.get(id=id)\n cc = Child_Case_Data.objects.get(child=child)\n reading = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary',\n sub_test_name='Reading').last()\n spelling = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary',\n sub_test_name='Spelling').last()\n mobile = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary',\n sub_test_name='Mobile').last()\n single = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary',\n sub_test_name='Single Word Reading').last()\n funny = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary',\n sub_test_name='Funny Words').last()\n segment = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary',\n sub_test_name='Segment').last()\n cave = Assessment_psy.objects.filter(appointment__child=child, test_name='secondary', sub_test_name='Cave').last()\n cognitive = Cognitive_assessment.objects.filter(appointment__child=child, test_name='secondary').last()\n\n return render(request, 'pdfs/file1/secondary.html', {'reading': reading, 'spelling': spelling, 'mobile': mobile\n , 'single': single, 'funny': funny, 'segment': segment,\n 'cave': cave, 'cognitive': cognitive, 'child': child, 'c': cc})\n\n\ndef Junior_PDF(request, id):\n child = Person.objects.get(id=id)\n cc = Child_Case_Data.objects.get(child=child)\n reading = Assessment_psy.objects.filter(appointment__child=child, test_name='junior',\n sub_test_name='Reading').last()\n spelling = Assessment_psy.objects.filter(appointment__child=child, test_name='junior',\n sub_test_name='Spelling').last()\n mobile = Assessment_psy.objects.filter(appointment__child=child, test_name='junior', sub_test_name='Mobile').last()\n funny = Assessment_psy.objects.filter(appointment__child=child, test_name='junior',\n sub_test_name='Funny Words').last()\n segment = Assessment_psy.objects.filter(appointment__child=child, test_name='junior',\n sub_test_name='Segment').last()\n cave = Assessment_psy.objects.filter(appointment__child=child, test_name='junior', sub_test_name='Cave').last()\n\n cognitive = Cognitive_assessment.objects.filter(appointment__child=child, test_name='junior').last()\n\n return render(request, 'pdfs/file1/junior.html', {'reading': reading, 'spelling': spelling, 'mobile': mobile,\n 'funny': funny, 'segment': segment,\n 'cave': cave, 'cognitive': cognitive, 'child': child, 'c': cc})\n\n\ndef ACOPS_PDF(request, id):\n child = Person.objects.get(id=id)\n cc = Child_Case_Data.objects.get(child=child)\n rabbits = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Rabbits').last()\n zoid_friends = Assessment_psy.objects.filter(appointment__child=child, test_name='acops',\n sub_test_name='Zoid Friends').last()\n zoid_letter_names = Assessment_psy.objects.filter(appointment__child=child, test_name='acops',\n sub_test_name='Zoid Letter Names').last()\n zoid_letters = Assessment_psy.objects.filter(appointment__child=child, test_name='acops',\n sub_test_name='Zoid Letters').last()\n ryhms = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Ryhms').last()\n races = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Races').last()\n wock = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Wock').last()\n toybox = Assessment_psy.objects.filter(appointment__child=child, test_name='acops', sub_test_name='Toybox').last()\n\n cognitive = Cognitive_assessment.objects.filter(appointment__child=child, test_name='acops').last()\n\n return render(request, 'pdfs/file1/acops.html', {'rabbits': rabbits, 'zoid_friends': zoid_friends,\n 'zoid_letter_names': zoid_letter_names,\n 'zoid_letters': zoid_letters, 'ryhms': ryhms,\n 'races': races, 'wock': wock, 'toybox': toybox,\n 'cognitive': cognitive, 'child': child, 'c': cc})\n\n\n@login_required(login_url='login')\ndef view_tests(request, id):\n appointment = Appointment.objects.get(id=id)\n return render(request, 'tests/view_tests.html', {'appointment': appointment})\n\n\n@login_required(login_url='login')\ndef rabbits(request, id):\n appointment = Appointment.objects.get(id=id)\n assessment = Assessment_psy.objects.filter(appointment_id=id, sub_test_name='Rabbits').last()\n if appointment.child.age_in_number < 7:\n below_age = True\n else:\n below_age = False\n\n if request.method == 'POST':\n comp_order1 = request.POST['comp_order1']\n player_order1 = request.POST['player_order1']\n start_time1 = request.POST['start_time1']\n end_time1 = request.POST['end_time1']\n\n # print(comp_order)\n # print(player_order)\n # diff = int(end_time) - int(start_time)\n\n # diff = diff / 1000\n #\n # print(f'{diff} seconds')\n # messages.success(request, message=request.POST)\n # print(request.POST)\n\n return redirect(rabbits, id)\n\n return render(request, 'tests/rabbits.html', {'appointment': appointment, 'assessment': assessment,\n 'below_age': below_age})\n\n\n@login_required(login_url='login')\ndef toybox(request, id):\n appointment = Appointment.objects.get(id=id)\n assessment = Assessment_psy.objects.filter(appointment_id=id, sub_test_name='Rabbits').last()\n\n if appointment.child.age_in_number < 7:\n below_age = 1\n else:\n below_age = 0\n\n return render(request, 'tests/toybox.html', {'appointment': appointment, 'assessment': assessment,\n 'below_age': below_age})\n\n\n\n@login_required(login_url='login')\ndef races(request, id):\n appointment = Appointment.objects.get(id=id)\n assessment = Assessment_psy.objects.filter(appointment_id=id, sub_test_name='Rabbits').last()\n\n if appointment.child.age_in_number < 7:\n below_age = 1\n else:\n below_age = 0\n\n return render(request, 'tests/races.html', {'appointment': appointment, 'assessment': assessment,\n 'below_age': below_age})","repo_name":"findsah/kda-portal","sub_path":"KDA_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":200385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"279183031","text":"from Crypto.Cipher import AES\nimport base64\nimport random\nimport string\n\n\nBLOCK_SIZE = 32\nPADDING = \"{\"\n\npad = lambda s: str(s) + (BLOCK_SIZE - len(str(s)) % BLOCK_SIZE ) * PADDING\nenc = lambda c, m: base64.b64encode(c.encrypt(pad(m).encode()))\ndec = lambda c, e: c.decrypt(base64.b64decode(e)).decode().rstrip(PADDING)\n\ndef randomkey(byteanzahl):\n return bytes(\"\".join(random.choice(string.ascii_letters + string.digits + \"@#[]{}!@|$^?/&\")\n for _ in range(byteanzahl)), \"utf-8\")\n\ndef randomName():\n return \"\".join(random.choice(string.ascii_letters + string.digits) for _ in range(3))\n\n\ndef randomAscii():\n return \"\".join(random.choice(string.ascii_letters) for _ in range(3))\n\nkey = randomkey(32)\niv = randomkey(16) #Initialisierungsvektor\n\n# cipher = AES.new(key, AES.MODE_ECB, iv)\ncipher = AES.new(key, AES.MODE_OFB, iv)\n\n\n# encrypted = cipher.encrypt(\"Hello World aaaa\".encode())\n# print(encrypted)\n# decrypted = cipher.decrypt(encrypted)\n# print(decrypted.decode())\n\n\ninput = open(\"VokTrainer.py\").readlines()\noutput = open(\"VokTrainer_encrypted.py\", \"w\")\n# output = open(\"Test_env.py\", \"w\")\n \nimports = list()\nlines = list()\n \nfor line in input:\n if not line.startswith(\"#\"):\n if \"import\" in line:\n imports.append(line.strip())\n else:\n lines.append(line)\n \nenced = enc(cipher, \"\".join(lines))\n\nb64name = randomAscii() + randomName()\naesName = randomAscii() + randomName()\n \nimports.append(\"from base64 import b64decode as \" + b64name)\nimports.append(\"from Crypto.Cipher import AES as \" + aesName)\nrandom.shuffle(imports)\noutput.write(\";\".join(imports) + \"\\n\")\n\ncmd = \"exec(%s.new(\\\"%s\\\".encode(), %s.MODE_OFB, \\\"%s\\\".encode()).decrypt(%s(\\\"%s\\\".encode())).decode().rstrip(\\\"{\\\"))\\n\" %(aesName, key.decode(), aesName, iv.decode(), b64name, enced.decode())\n \noutput.write(\"exec({}(\\\"{}\\\".encode()))\".format(b64name, base64.b64encode(cmd.encode()).decode()))\noutput.close()","repo_name":"DasCodeMonster/LearningPython-new","sub_path":"encryptFile_py3.py","file_name":"encryptFile_py3.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1376950418","text":"import argparse\nimport json\nimport os\nfrom pathlib import Path\nimport typing\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom lm_survey.samplers import AutoSampler\nfrom lm_survey.survey import DependentVariableSample, Survey\n\n\ndef parse_model_name(model_name: str) -> str:\n if model_name.startswith(\"/\") and model_name.endswith(\"/\"):\n model_name = model_name.split(\"/\")[-2]\n elif model_name.startswith(\"/\"):\n model_name = model_name.split(\"/\")[-1]\n else:\n model_name = model_name.replace(\"/\", \"-\")\n\n return model_name\n\n\ndef get_commit_hash():\n commit_hash = os.popen(\"git rev-parse HEAD\").read().strip()\n return commit_hash\n\n\ndef save_experiment(\n model_name: str,\n experiment_dir: Path,\n dependent_variable_samples: typing.List[DependentVariableSample],\n prompt_name: str,\n n_samples_per_dependent_variable: typing.Optional[int] = None,\n):\n parsed_model_name = parse_model_name(model_name)\n\n results = [\n question_sample.to_dict() for question_sample in dependent_variable_samples\n ]\n\n metadata = {\n \"model_name\": model_name,\n \"n_samples_per_dependent_variable\": n_samples_per_dependent_variable,\n \"commit_hash\": get_commit_hash(),\n \"prompt_name\": prompt_name,\n }\n\n experiment_metadata_dir = experiment_dir / parsed_model_name\n\n if not experiment_metadata_dir.exists():\n experiment_metadata_dir.mkdir(parents=True)\n\n with open(experiment_metadata_dir / \"metadata.json\", \"w\") as file:\n json.dump(\n metadata,\n file,\n indent=4,\n )\n\n with open(experiment_metadata_dir / \"results.json\", \"w\") as file:\n json.dump(\n results,\n file,\n indent=4,\n )\n\n\ndef calculate_accuracy(\n dependent_variable_samples: typing.List[DependentVariableSample],\n) -> float:\n scores = [\n dependent_variable_sample.completion.is_completion_correct\n for dependent_variable_sample in dependent_variable_samples\n if dependent_variable_sample.completion.are_completion_log_probs_set()\n ]\n\n return np.mean(scores)\n\n\ndef calculate_baseline(\n dependent_variable_samples: typing.List[DependentVariableSample],\n) -> float:\n scores = [\n 1 / len(dependent_variable_sample.completion.possible_completions)\n for dependent_variable_sample in dependent_variable_samples\n if dependent_variable_sample.completion.are_completion_log_probs_set()\n ]\n\n return np.mean(scores)\n\n\ndef main(\n model_name: str,\n survey_name: str,\n experiment_name: str,\n prompt_name: str,\n n_samples_per_dependent_variable: typing.Optional[int] = None,\n) -> None:\n data_dir = Path(\"data\", survey_name)\n experiment_dir = Path(\"experiments\", experiment_name, survey_name)\n\n with open(Path(experiment_dir, \"config.json\"), \"r\") as file:\n config = json.load(file)\n\n # If there is a variables file in the experiment directory, use that.\n variables_filename = experiment_dir / \"variables.json\"\n\n # Otherwise, use the default variables file for the survey.\n if not variables_filename.exists():\n variables_filename = Path(\"variables\", survey_name, \"variables.json\")\n\n survey = Survey(\n name=survey_name,\n data_filename=Path(data_dir, \"data.csv\"),\n variables_filename=variables_filename,\n independent_variable_names=config[\"independent_variable_names\"],\n dependent_variable_names=config[\"dependent_variable_names\"],\n )\n\n sampler = AutoSampler(model_name=model_name)\n\n dependent_variable_samples = list(\n survey.iterate(\n n_samples_per_dependent_variable=n_samples_per_dependent_variable,\n prompt_name=prompt_name,\n )\n )\n\n loop = tqdm(dependent_variable_samples)\n accuracy = 0.0\n\n for dependent_variable_sample in loop:\n completion_log_probs = sampler.rank_completions(\n prompt=dependent_variable_sample.prompt,\n completions=dependent_variable_sample.completion.possible_completions,\n )\n dependent_variable_sample.completion.set_completion_log_probs(\n completion_log_probs\n )\n\n accuracy = calculate_accuracy(dependent_variable_samples)\n baseline = calculate_baseline(dependent_variable_samples)\n\n loop.set_description(\n f\"Accuracy: {accuracy * 100:.2f}%, Baseline: {baseline * 100:.2f}%\"\n )\n\n print(\n f\"Accuracy: {accuracy * 100:.2f}% ({len(dependent_variable_samples)} samples)\"\n )\n\n save_experiment(\n model_name=model_name,\n experiment_dir=experiment_dir,\n dependent_variable_samples=dependent_variable_samples,\n prompt_name=prompt_name,\n n_samples_per_dependent_variable=n_samples_per_dependent_variable,\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"-m\",\n \"--model_name\",\n type=str,\n required=True,\n )\n parser.add_argument(\n \"-s\",\n \"--survey_name\",\n type=str,\n default=\"roper\",\n )\n parser.add_argument(\n \"-n\",\n \"--n_samples_per_dependent_variable\",\n type=int,\n )\n parser.add_argument(\n \"-e\",\n \"--experiment_name\",\n type=str,\n default=\"default\",\n )\n parser.add_argument(\n \"-p\",\n \"--prompt_name\",\n type=str,\n default=\"first_person_natural_language_context\",\n )\n\n args = parser.parse_args()\n\n # To prevent overbilling OpenAI.\n if (\n args.model_name.startswith(\"gpt3\")\n and args.n_samples_per_dependent_variable is None\n ):\n args.n_samples_per_dependent_variable = 100\n\n main(\n model_name=args.model_name,\n survey_name=args.survey_name,\n experiment_name=args.experiment_name,\n n_samples_per_dependent_variable=args.n_samples_per_dependent_variable,\n prompt_name=args.prompt_name,\n )\n","repo_name":"BYU-PCCL/lm-survey","sub_path":"run_survey.py","file_name":"run_survey.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"43326652980","text":"from typing import DefaultDict\n\n\nclass Day():\n def __init__(self, data_path):\n self.data = DefaultDict()\n\n with open(data_path, \"r\") as file:\n for row, line in enumerate(file):\n for col, number in enumerate(line.strip()):\n self.data[(row, col)] = int(number)\n \n self.rows = max(self.data.keys())[0]\n self.cols = max(self.data.keys())[1]\n\n def get_neighbors(self, coordinates):\n neighbors = []\n \n if coordinates[0] < self.rows: # Bottom border check\n neighbors.append((coordinates[0] + 1, coordinates[1]))\n if coordinates[0] > 0: # Top border check\n neighbors.append((coordinates[0] - 1, coordinates[1]))\n if coordinates[1] < self.cols: # Right border check\n neighbors.append((coordinates[0], coordinates[1] + 1))\n if coordinates[1] > 0: # Left border check\n neighbors.append((coordinates[0], coordinates[1] - 1))\n \n return neighbors\n\n def part1(self):\n sum = 0\n\n for point in self.data:\n is_minimum = True\n for neighbor in self.get_neighbors(point):\n if self.data[point] >= self.data[neighbor]:\n is_minimum = False\n break\n if is_minimum:\n sum += 1 + self.data[point]\n\n return sum\n\n def get_basin(self, point, visited):\n size = 1\n\n for neighbor in self.get_neighbors(point):\n if neighbor not in visited:\n visited.append(neighbor)\n if self.data[neighbor] != 9:\n size += self.get_basin(neighbor, visited)\n\n return size\n\n\n def part2(self):\n sizes = []\n visited = []\n\n for point in self.data:\n is_minimum = True\n for neighbor in self.get_neighbors(point):\n if self.data[point] >= self.data[neighbor]:\n is_minimum = False\n break\n if is_minimum:\n visited.append(point)\n sizes.append(self.get_basin(point, visited))\n \n sizes.sort()\n\n return sizes[-3] * sizes[-2] * sizes[-1]\n \n\n\nif __name__ == \"__main__\":\n DATA_INPUT_LOCATION = \"data.in\"\n\n day = Day(DATA_INPUT_LOCATION)\n print(day.part1())\n print(day.part2())","repo_name":"theleteron/advent-of-code","sub_path":"2021/Day 9/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42659274915","text":"#!/usr/bin/env python3\nimport os\nimport subprocess\nfrom Bio import SeqIO\n\nmitoprot='/home/kika/programs/mitoprotII/mitoprot'\nos.chdir('/home/kika/MEGAsync/diplonema/metabolism/')\ninfile = SeqIO.parse('diplo_all.fa', 'fasta')\n\nwith open('diplo_all.mitoprot.txt', 'a') as out:\n\tfor seq in infile:\n\t\tprint(seq.description)\n\t\tsubprocess.call('{} -o {} {}'.format(mitoprot, out, seq.seq), shell=True)\n","repo_name":"kikinocka/ngs","sub_path":"py_scripts/run_program/mitoprot.py","file_name":"mitoprot.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38959981538","text":"import re\nimport os\nimport pandas as pd\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\n\n# get the description of the element\ndef get_description(item, locator, id, term):\n description = \"\"\n try:\n element = item.find_element(locator, id)\n\n if term == \"id\":\n description = element.id\n else:\n description = element.text\n\n except:\n description = \"\"\n\n return description\n\n\n# Count the number of search phrases in the title and description\ndef count_phrases(title: str, description: str, phrase: str):\n return len(re.findall(phrase.upper(), title.upper() + description.upper()))\n\n\n# Check if the title or description contains any amount of money\ndef has_money(title: str, description: str):\n try:\n match = re.search(\n r\"\\$\\d+(,\\d{3})*(\\.\\d{2})?|\\d+ dollars? (USD|usd)\", title + description\n )\n except Exception as e:\n print(e)\n\n return True if match else False\n\n\n# generate date range from today to N months\ndef get_date_range(term=0):\n try:\n if term == 0:\n Number_months = 1\n else:\n Number_months = term\n\n today = datetime.now()\n final_date = today.strftime(\"%m/%d/%Y\")\n past = today + relativedelta(months=-Number_months)\n ini_date = past.strftime(\"%m/%d/%Y\")\n\n return ini_date, final_date\n except Exception as e:\n print(e)\n\n\n# downloads all news in excel format\ndef download_excel(data, directory):\n try:\n # Convert the list of data to a Pandas DataFrame\n df = pd.DataFrame(\n data,\n columns=[\n \"Title\",\n \"Date\",\n \"Description\",\n \"Has Money\",\n \"Count of Phrases\",\n \"Picture Name\",\n ],\n )\n\n if directory != \"\":\n path = os.path.join(directory, \"news.xlsx\")\n # Write the data to an Excel file\n df.to_excel(path, index=False)\n\n except Exception as e:\n print(e)\n\n\n# validate if the directory exist if not, create a new one\ndef create_directory():\n path = \"\"\n today = datetime.now()\n new_directory = today.strftime(\"%m-%d-%Y-%H-%M-%S\")\n parent_dir = \"./Downloads/\"\n\n if not os.path.exists(parent_dir):\n dir = os.path.join(\"./\", \"Downloads\")\n os.mkdir(dir)\n\n try:\n # Path\n path = os.path.join(parent_dir, new_directory)\n os.mkdir(path)\n except OSError as error:\n print(error)\n\n finally:\n return path\n","repo_name":"lam1391/Fresh_News","sub_path":"fresh_news/modules/operations/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14495093192","text":"# 1.1 Вывести список уникальных чисел (встречаются только один раз)\n\n# 1.2 Вывести список чисел <= 40, не встречающихся в исходном списке\n\n# 1.3 Вывести данные в формате: (num: num_count), (num: num_count),\n# num_count - кол-во num в списке.\n# Отсортировать по убыванию num_count, при равенстве num_count по убыванию num.\n\n# 1.4 Рассчитать среднеквадратичное отклонение.\n\n\nfrom math import sqrt\n\n\ndata = [13, 29, 37, 49, 29, 7, 25, 5, 50, 2, 18, 0, 14, 16, 14, 4, 6, 14, 2, 5, 41, 27, 10, 11, 33, 6, 7, 47, 35, 35,\n 48, 0, 38, 1, 41, 15, 26, 46, 4, 23, 5, 32, 45, 37, 2, 33, 20, 30, 46, 20, 10, 14, 44, 25, 3, 27, 6, 22, 9, 20,\n 18, 43, 5, 33, 27, 41, 38, 20, 6, 2, 18, 29, 34, 40, 41, 8, 44, 30, 21, 10, 6, 1, 12, 0, 22, 28, 47, 4, 5, 1,\n 11, 21, 1, 44, 24, 42, 42, 41, 14, 24]\n\n\ndef form_list_unique_numbers(numbers_list): # Task 1.1\n final_list = []\n\n max_number = max(numbers_list)\n min_number = min(numbers_list)\n for number in range(min_number, max_number + 1):\n if numbers_list.count(number) == 1:\n final_list.append(number)\n\n return final_list\n\n\ndef form_list_non_occurring_numbers(numbers_list): # Task 1.2\n final_list = []\n\n max_number = 40\n min_number = 0\n for number in range(min_number, max_number + 1):\n if not (number in numbers_list):\n final_list.append(number)\n\n return final_list\n\n\ndef form_sorted_dict(numbers_list): # Task 1.3\n final_dict = {}\n\n max_number = max(numbers_list)\n min_number = min(numbers_list)\n for number in range(min_number, max_number + 1):\n final_dict[number] = numbers_list.count(number)\n\n return sorted(final_dict.keys())\n\n\ndef calculate_standard_deviation(numbers_list): # Task 1.4\n return sqrt(sum((x - sum(numbers_list) / len(numbers_list)) ** 2 for x in numbers_list) / (len(numbers_list)))\n\n\nsorted_data = data.copy()\nsorted_data.sort()\n\nprint(form_list_unique_numbers(sorted_data))\nprint(form_list_non_occurring_numbers(sorted_data))\nprint(form_sorted_dict(sorted_data))\nprint(calculate_standard_deviation(sorted_data))\n","repo_name":"chertkov-nikita/Tasks","sub_path":"stepik_courses/Task_1(list).py","file_name":"Task_1(list).py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26200238224","text":"from usuario import Usuario\r\nfrom funcionario import Funcionario\r\nfrom gerente import Gerente\r\nfrom diretor import Diretor\r\nfrom secretario import Secretario\r\nfrom presidente import Presidente\r\nfrom conta_bancaria import Conta\r\n\r\n\r\ndef main():\r\n print(\"--------------------\")\r\n print(\"----- CITIBANK -----\")\r\n print(\"--------------------\")\r\n print(\"OLÁ! SEJA BEM VINDO (A) \")\r\n\r\n \r\n tipo_conta = input(\"Informe o tipo de conta (usuario, funcionario, gerente, diretor, secretario, presidente): \")\r\n if tipo_conta == \"usuario\":\r\n usuario = Usuario('Fernanda', '000.000.000-00', 1500.00, 'fernanda@email.com', '123')\r\n usuario.Autentica()\r\n print(\"ESCOLHA O SERVIÇO: \")\r\n print(\"[1] DADOS CONTA\")\r\n print(\"[2] EXTRATO\")\r\n print(\"[3] SAQUE\")\r\n print(\"[4] PIX\")\r\n print(\"[5] SALDO\")\r\n print(\"[6] PAGAMENTO\")\r\n print(\"[7] EMPRÉSTIMO\")\r\n print(\"[8] DEPÓSITO\")\r\n \r\n opcao = int(input(\"Digite uma opção: \"))\r\n c1 = Conta('Fernanda', '000.000.000-00', 1500.00, 'fernanda@email.com', '123', '123-4', '10856-0', 300.00, 100)\r\n \r\n if (opcao == 1):\r\n return c1.Dados_Conta()\r\n elif (opcao == 2):\r\n return c1.Extrato_Conta()\r\n elif (opcao == 3): \r\n return c1.Saque_Conta()\r\n elif (opcao == 4):\r\n return c1.Pix_Conta()\r\n elif (opcao == 5):\r\n return c1.Saldo_Conta()\r\n elif (opcao == 6):\r\n return c1.Pagamento_Conta()\r\n elif (opcao == 7):\r\n return c1.Emprestimo_Conta()\r\n elif (opcao == 8):\r\n return c1.Depositar_Conta()\r\n else:\r\n print(\"Opção inválida!\")\r\n \r\n elif tipo_conta == \"funcionario\":\r\n funcionario = Funcionario('Maria', '111.111.111-11', 2500.00, 'funcionario@email.com', '123456')\r\n funcionario.Autentica()\r\n \r\n elif tipo_conta == \"gerente\":\r\n gerente = Gerente('José', '222.222.222-22', 3500.00, 'gerente@email.com', '123456789', 10)\r\n gerente.Autentica()\r\n \r\n elif tipo_conta == \"diretor\":\r\n diretor = Diretor('Marcos', '333.333.333-33', 4500.00, 'diretor@email.com', '1234')\r\n diretor.Autentica()\r\n \r\n elif tipo_conta == \"secretario\":\r\n secretario = Secretario('Josefa', '444.444.444-44', 2000.00,'secretario@email.com', '12345')\r\n secretario.Autentica()\r\n \r\n elif tipo_conta == \"presidente\":\r\n presidente = Presidente('Paulo', '555.555.555-55', 10000.00, 'presidente@email.com', '1234567')\r\n presidente.Autentica()\r\n else:\r\n print(\"Tipo de conta inválido.\") \r\n print(\"--------------------\")\r\n\r\nif __name__ == \"__main__\":\r\n \r\n main()\r\n\r\n","repo_name":"fernandamelreis/projeto_conta_bancaria","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"6370774021","text":"def Check_Pangram(str1):\r\n str1=str1.upper()\r\n list1=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\r\n\r\n for i in str1:\r\n if i in list1:\r\n list1.remove(i)\r\n\r\n if list1==[]:\r\n return True\r\n else:\r\n return False\r\n\r\nstr1=input(\"Enter the string.\\n\")\r\nif Check_Pangram(str1)==True:\r\n print(\"It is Pangram\")\r\nelse:\r\n print(\"It is NOT Pangram\")","repo_name":"Suraj-Mohite/python-programming-practice","sub_path":"Pangram.py","file_name":"Pangram.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33357895134","text":"from os import system, startfile\r\nfrom appJar import gui\r\nimport configparser\r\n\r\nconfig = configparser.ConfigParser()\r\napp = gui()\r\n\r\n#function to open the program using ForceBindIP\r\ndef OPEN(self):\r\n \r\n forcebindIP = 'cd \"' + config['DEFAULT'].get('location') + '\" && forcebindip64.exe ' + config['DEFAULT'].get('IP') + ' '\r\n #checks which button you clicked, if other asks for location\r\n if self == 'Other': \r\n file = app.openBox(title='Select program to start')\r\n ADD = app.yesNoBox('Save?', 'Add to config file?\\nThis will reload the program.')\r\n #adds location of new program to config file, then opens a new instance of the this program, and closes the existing one\r\n if ADD:\r\n ButtonName = app.textBox('Button name', 'Enter the name for the new button:')\r\n \r\n if ADD and ButtonName != None:\r\n config[ButtonName] = {}\r\n config[ButtonName]['file'] = file\r\n with open('config.ini', 'w') as configfile:\r\n config.write(configfile)\r\n startfile(__file__)\r\n app.stop()\r\n \r\n system(forcebindIP + file)\r\n else:\r\n system(forcebindIP + config[self].get('file'))\r\n\r\nconfigExist = config.read('config.ini')\r\n\r\n#checks if the config file exists, if not, prompts to build it\r\nif configExist == []:\r\n app.errorBox('Error', 'Press OK to select location for ForceBindIP64.exe')\r\n\r\n FBLocation = app.directoryBox(title='Select location for ForceBindIP64.exe')\r\n IPAdd = app.textBox('IP Address', 'Enter the IP address for the connection you want to use:')\r\n config['DEFAULT'] = {}\r\n config['DEFAULT']['location'] = FBLocation\r\n config['DEFAULT']['IP'] = IPAdd\r\n with open('config.ini', 'w') as configfile:\r\n config.write(configfile)\r\n startfile(__file__)\r\n app.stop()\r\n#builds the GUI\r\nelse:\r\n for section in config.sections():\r\n if section != 'DEFAULT':\r\n app.addButton(section, OPEN)\r\n\r\n app.addButton('Other', OPEN)\r\n \r\napp.go()\r\n","repo_name":"rieldeal/Force-Bind-IP-GUI","sub_path":"ForcebindIP Launcher 1.0.pyw","file_name":"ForcebindIP Launcher 1.0.pyw","file_ext":"pyw","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"12508633185","text":"import os\nimport tempfile\nimport unittest\n\nfrom telemetry.internal.backends import browser_backend\nfrom telemetry.testing import options_for_unittests\nimport mock\n\n\nclass BrowserBackendLogsUploadingUnittest(unittest.TestCase):\n def testUploadingToCLoudStorage(self):\n temp_file = tempfile.NamedTemporaryFile(delete=False)\n temp_file_name = temp_file.name\n try:\n temp_file.write('This is a\\ntest log file.\\n')\n temp_file.close()\n\n # pylint: disable=abstract-method\n class FakeBrowserBackend(browser_backend.BrowserBackend):\n @property\n def supports_uploading_logs(self):\n return True\n\n @property\n def log_file_path(self):\n return temp_file_name\n\n options = options_for_unittests.GetCopy()\n options.browser_options.logging_verbosity = (\n options.browser_options.VERBOSE_LOGGING)\n options.browser_options.logs_cloud_bucket = 'ABC'\n options.browser_options.logs_cloud_remote_path = 'def'\n\n b = FakeBrowserBackend(\n platform_backend=None, browser_options=options.browser_options,\n supports_extensions=False, tab_list_backend=None)\n self.assertEquals(b.GetLogFileContents(), 'This is a\\ntest log file.\\n')\n with mock.patch('py_utils.cloud_storage.Insert') as mock_insert:\n b.UploadLogsToCloudStorage()\n mock_insert.assert_called_with(\n bucket='ABC', remote_path='def', local_path=temp_file_name)\n finally:\n os.remove(temp_file_name)\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/telemetry/telemetry/internal/backends/browser_backend_unittest.py","file_name":"browser_backend_unittest.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"41663315773","text":"import numpy as np\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch\nimport pdb\nimport time\nimport string\n\nto_gpu = False\ndef gpu(m):\n if to_gpu:\n return m.cuda()\n return m\n\ndef ints_to_tensor(ints):\n return gpu(torch.tensor(ints).long().transpose(1, 0))\n\n# build the model using the pytorch nn module\nclass CharLSTM(nn.Module):\n def __init__(self, vocab_size, hidden_dim, batch_size, embedding_dim):\n super(CharLSTM, self).__init__()\n \n # init the meta parameters\n self.hidden_dim = hidden_dim\n self.batch_size = batch_size\n self.vocab_size = vocab_size\n self.embedding_dim = embedding_dim\n \n self.emb = nn.Embedding(vocab_size, embedding_dim)\n \n self.lstm_1 = nn.LSTMCell(input_size=embedding_dim, hidden_size=hidden_dim)\n self.lstm_2 = nn.LSTMCell(input_size=hidden_dim, hidden_size=hidden_dim) \n \n self.dropout = nn.Dropout(p=0.5)\n\n # fully connected layer to connect the output of the LSTM cell to the output\n self.fc = nn.Linear(in_features=hidden_dim, out_features=vocab_size)\n \n def forward(self, x, hc, return_hc=False):\n seq_len = x.shape[0]\n batch_size = x.shape[1]\n \n # empty tensor for the output of the lstm\n output_seq = torch.empty((seq_len, batch_size, self.vocab_size))\n output_seq = gpu(output_seq)\n hc1, hc2 = hc, hc\n\n # for every step in the sequence\n for t in range(seq_len):\n out_t, hc1, hc2 = self.feed_one_x_t(x[t], hc1, hc2)\n output_seq[t] = out_t\n \n if return_hc:\n return output_seq, hc1, hc2\n return output_seq\n \n def init_hidden(self, bs=None):\n if bs is None:\n bs = self.batch_size\n # initialize the and the to zeros\n return (gpu(torch.zeros(bs, self.hidden_dim)), gpu(torch.zeros(bs, self.hidden_dim)))\n \n def feed_one_x_t(self, x_t, hc1, hc2):\n # convert batch of single ints to batch of embeddings\n xt_emb = self.emb(x_t) # returns (batch_size, embedding_dim)\n\n # get the hidden and cell states from the first layer cell\n hc1 = self.lstm_1(xt_emb, hc1)\n h1, c1 = hc1 # unpack the hidden and the cell states from the first layer\n\n # pass the hidden state from the first layer to the cell in the second layer\n hc2 = self.lstm_2(h1, hc2)\n h2, c2 = hc2 # unpack the hidden and cell states from the second layer cell\n\n # form the output of the fc\n out_t = self.fc(self.dropout(h2))\n \n return out_t, hc1, hc2\n \n def feed_one_char(self, char, hc1, hc2):\n ints = [self.char2int[char]] # sequence of ints \n ints = [ints] # a 1-batch of seqs\n x = ints_to_tensor(ints) # shape of (seq_len, batch_size)\n x_t = x[0] # take the first (single) part of the sequence\n \n return self.feed_one_x_t(x_t, hc1, hc2)\n \n def warm_up(self, base_str):\n hc = self.init_hidden(bs=1)\n ints = [self.char2int[c] for c in base_str] # sequence of ints \n ints = [ints] # a 1-batch of seqs\n x = ints_to_tensor(ints) # shape of (seq_len, batch_size)\n \n out, hc1, hc2 = self.forward(x, hc, return_hc=True)\n return out, hc1, hc2\n \n def sample_char(self, out_t, top_k=5):\n # apply the softmax to the output to get the probabilities of the characters\n out_t = F.softmax(out_t, dim=1)\n\n # out_t now holds the vector of predictions (1, vocab_size)\n # we want to sample 5 top characters\n p, top_char = out_t.topk(top_k) # returns tuple (top_values, top_indices)\n\n # get the top k characters by their probabilities\n top_char = top_char.cpu().squeeze().numpy()\n\n # sample a character using its probability\n p = p.detach().cpu().squeeze().numpy()\n char_int = np.random.choice(top_char, p = p/p.sum())\n \n return self.int2char[char_int]\n \n def predict(self, base_str, top_k=5, seq_len=128):\n self.eval()\n\n res = np.empty(seq_len+len(base_str), dtype=\"object\")\n for i, c in enumerate(base_str):\n res[i] = c\n \n out_warm, hc1, hc2 = self.warm_up(base_str)\n out_t = out_warm[-1]\n\n for i in range(seq_len):\n char = self.sample_char(out_t, top_k)\n out_t, hc1, hc2 = self.feed_one_char(char, hc1, hc2)\n res[i + len(base_str)] = char\n \n return ''.join(res)\n \n\ndef load():\n state = torch.load(\"save_2\", map_location=\"cpu\")\n net = state[\"net\"]\n char2int = state[\"char2int\"]\n int2char = state[\"int2char\"]\n net.char2int = char2int\n net.int2char = int2char\n return state\n\ndef save(state):\n torch.save(state, \"save_2\")\n","repo_name":"hofesh/ml_play","sub_path":"char_LSTM/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9027998971","text":"\n# coding: utf-8\n\n# In[26]:\nimport os\nimport time\n\nimport quantarhei as qr\n\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\n\nprint(qr.Manager().version)\n\n\n# In[27]:\n\npre_out = \"out\"\n#frac = qr.load(\"fraction_40_4_CT_unbuilt.hdf5\")\n#frac_electronic = qr.load(\"fraction_40_4_CT_unbuilt.hdf5\")\n\nfrac = qr.load_parcel(os.path.join(pre_out, \"fraction_eff_40_4_CT_unbuilt.qrp\"))\nfrac_electronic = qr.load_parcel(os.path.join(pre_out, \"fraction_40_4_CT_unbuilt.qrp\"))\n\n\n# In[28]:\n\n\n#\n# Get molecules\n#\nPM = frac.get_Molecule_by_name(\"PM\")\nPL = frac.get_Molecule_by_name(\"PL\")\nBL = frac.get_Molecule_by_name(\"BL\")\n\ninclude_second_B = False \nvib_at_second_B = False \n\nif include_second_B:\n BM = frac.get_Molecule_by_name(\"BM\")\n\n\n# In[29]:\n\n\n#\n# Here we add vibrational modes\n#\n\nomega_B = 572\nomega_P = 572 #572\nwith qr.energy_units(\"1/cm\"):\n mod_PM = qr.Mode(omega_P)\n mod_PL = qr.Mode(omega_P)\n mod_BM = qr.Mode(omega_B)\n mod_BL = qr.Mode(omega_B)\n\nNmax_e = 1 \nNmax_g = 1 \n\nHRF = 0.0111\nvib_P = False \nvib_B = True \n\nif vib_P:\n PM.add_Mode(mod_PM)\n mod_PM.set_nmax(0, Nmax_g)\n mod_PM.set_nmax(1, Nmax_e)\n mod_PM.set_HR(1, HRF)\n\n PL.add_Mode(mod_PL)\n mod_PL.set_nmax(0, Nmax_g)\n mod_PL.set_nmax(1, Nmax_e)\n mod_PL.set_HR(1, HRF)\n\nif vib_B:\n BL.add_Mode(mod_BL)\n mod_BL.set_nmax(0, Nmax_g)\n mod_BL.set_nmax(1, Nmax_e)\n mod_BL.set_HR(1, HRF)\n\n if include_second_B and vib_at_second_B:\n BM.add_Mode(mod_BM)\n mod_BM.set_nmax(0, Nmax_g)\n mod_BM.set_nmax(1, Nmax_e)\n mod_BM.set_HR(1, HRF)\n\n\n\n\n# In[30]:\n\n\nprint(BL)\n\n\n# In[31]:\n\n\n#frac.save(\"fraction_45_2_vibrations_CT_unbuilt.hdf5\")\nqr.save_parcel(frac, os.path.join(pre_out, \"fraction_45_2_vibrations_CT_unbuilt.qrp\"))\n\n\n# In[32]:\n\n\n#\n# Building the aggregate with approximations in vibrational manifold\n#\nfrac.build(vibgen_approx=\"NPA\", Nvib=2, mult=2) # NPA with Nvib=2 is equivalent to vibgen_approx=\"TPA\"\nfrac_electronic.build(mult=2)\n\n\n# In[33]:\n\n\nprint(\"Total number of states:\", frac.Ntot)\nprint(\"Dim :\", frac.get_Hamiltonian().data.shape)\nprint(\"Total number of electronic states:\", frac.Nel, frac_electronic.Ntot)\n\n\n# In[34]:\n\n\n#\n# Internals of the aggregates have to be converted to excitonic basis\n#\nimport time\nt1 = time.time()\nfrac.diagonalize()\nt2 = time.time()\nprint(\"Diagonalized in \", t2-t1, \"sec\")\nt3 = time.time()\nfrac_electronic.diagonalize()\nprint(\"Diagonalized in \", t3-t2, \"sec\")\n\n\n# In[35]:\n\n\n#\n# Now we can look at the excitonic composition of all states\n#\nfrac_electronic.report_on_expansion(1, N=4)\n\n#\n# State 1 is a clear P(-)\n#\n\n\n# In[36]:\n\n\nfrac_electronic.report_on_expansion(2, N=4)\n\n#\n# State 2 is a clear symmetric mixture of P(+) and B\n#\n\n\n# In[37]:\n\n\nfrac_electronic.report_on_expansion(3, N=4)\n\n#\n# State 3 is a clear anti-symmetric mixture of P(+) and B\n#\n\n\n# In[38]:\n\n\nN1 = frac_electronic.Nbe[1]\nprint(\"Energies in 1/cm:\")\nprint([qr.convert(frac_electronic.HH[i,i],\"int\",\"1/cm\") for i in range(1, N1+1)])\n\n\n# In[39]:\n\n\n#\n# Transition dipoles square\n#\nprint(\"Transition dipoles square:\")\nprint(frac_electronic.D2[1:N1+1,0])\n\n\n# In[40]:\n\n\n#frac.save(\"fraction_45_2_vibrations_CT_built.hdf5\")\nqr.save_parcel(frac, os.path.join(pre_out, \"fraction_45_2_vibrations_CT_built.qrp\"))\n\n\n# In[41]:\n\n\nfrac.Nb\n\n\n# In[42]:\n\n\nfrac.report_on_expansion(20)\n\n\n# In[43]:\n\n\ndef criterium(lst):\n\n if lst[1] > 0.01:\n return True\n\n return False\n\nwith qr.energy_units(\"1/cm\"):\n frac.exciton_report(start=6, criterium=criterium)\n\n\n# # In[44]:\n#\n#\n# #frac_B = qr.load(\"fraction_40_4_B_unbuilt.hdf5\")\n# #print(frac_B)\n# frac_B = qr.load_parcel(os.path.join(pre_out, \"fraction_40_4_B_unbuilt.qrp\"))\n#\n#\n# # In[45]:\n#\n#\n# BL = frac_B.get_Molecule_by_name(\"BL\")\n# BM = frac_B.get_Molecule_by_name(\"BM\")\n#\n#\n# # In[46]:\n#\n# \n# omega_B = 572\n#\n# with qr.energy_units(\"1/cm\"):\n# mod_BM = qr.Mode(omega_B)\n# mod_BL = qr.Mode(omega_B)\n#\n# Nmax_e = 2\n# Nmax_g = 2\n#\n# HRF = 0.01\n#\n# vib_B = True\n# if vib_B:\n# BL.add_Mode(mod_BL)\n# mod_BL.set_nmax(0, Nmax_g)\n# mod_BL.set_nmax(1, Nmax_e)\n# mod_BL.set_HR(1, HRF)\n#\n# BM.add_Mode(mod_BM)\n# mod_BM.set_nmax(0, Nmax_g)\n# mod_BM.set_nmax(1, Nmax_e)\n# mod_BM.set_HR(1, HRF)\n#\n#\n# # In[47]:\n#\n#\n# #frac_B.save(\"fraction_45_2_vibrations_B_unbuilt.hdf5\")\n# qr.save_parcel(frac_B, os.path.join(pre_out, \"fraction_45_2_vibrations_B_unbuilt.qrp\"))\n#\n#\n# # In[48]:\n#\n#\n# #\n# # Building the aggregate with approximations in vibrational manifold\n# #\n# frac_B.build(vibgen_approx=\"NPA\", Nvib=2, mult=2) # NPA with Nvib=2 is equivalent to vibgen_approx=\"TPA\"\n#\n#\n# # In[49]:\n#\n#\n# #\n# # Internals of the aggregates have to be converted to excitonic basis\n# #\n# import time\n# t1 = time.time()\n# frac_B.diagonalize()\n# t2 = time.time()\n# print(\"Diaginalized in \", t2-t1, \"sec\")\n# t3 = time.time()\n#\n#\n# # In[50]:\n#\n#\n# #frac_B.save(\"fraction_45_2_vibrations_B_built.hdf5\")\n# qr.save_parcel(frac_B, os.path.join(pre_out, \"fraction_45_2_vibrations_B_built.qrp\"))\n# #qr.check_parcel(\"fraction_45_2_vibrations_B_built.qrp\")\n","repo_name":"tmancal74/quantarhei","sub_path":"examples/rc/model2/model_vib.py","file_name":"model_vib.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"23220931417","text":"# Exercise 11: Date to Holiday Name\r\n\r\ndef datetoholiday(in1,in2):\r\n if(in1 == 'January' and in2 == 1):\r\n print(\"The holiday on the given date is New year's day.\")\r\n if(in1 == 'July' and in2 == 1):\r\n print(\"The holiday on the given date is Canada day.\")\r\n if(in1 == 'December' and in2 == 25):\r\n print(\"The holiday on the given date is Christmas day.\")\r\n\r\nmonth = input(\"Please enter a month of the year: \")\r\nday = int(input(\"Please enter a day of the month you provided: \"))\r\n\r\ndatetoholiday(month,day)\r\n","repo_name":"harrisonpearson18/Python-Projects","sub_path":"2021 Intro to Prog Files from Home/Problem Set 5 - Harrison Pearson/PB11 - Harrison Pearson.py","file_name":"PB11 - Harrison Pearson.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34507463853","text":"import coffee_data\r\n\r\nmenu = coffee_data.MENU\r\nresources = coffee_data.resources\r\n\r\n\r\ndef sum_total(c1, c2, c3, c4, c5):\r\n \"\"\"Takes an input of number of coins and returns the summed value\"\"\"\r\n return (c1 * 2.0) + (c2 * 1.0) + (c3 * 0.5) + (c4 * 0.2) + (c5 * 0.1)\r\n\r\n\r\ndef check_resources(ingredients):\r\n \"\"\"Checks resources and returns False if there aren't enough left\"\"\"\r\n for i in ingredients:\r\n if ingredients[i] > resources[i]:\r\n print(f\"Insufficient {i} remaining\")\r\n return False\r\n return True\r\n\r\n\r\ncoffee_machine_on = True\r\n\r\nwhile coffee_machine_on:\r\n\r\n print(\"What would you like?\")\r\n print(\"1: Espresso\")\r\n print(\"2: Latte\")\r\n print(\"3: Cappuccino\")\r\n user_choice = input(\"\")\r\n\r\n # print(resources)\r\n\r\n # Print report of resources if the user types 'report'\r\n # Assign the user choice to the dictionary key\r\n if user_choice.lower() == 'off':\r\n print(\"Shutting down...\")\r\n coffee_machine_on = False\r\n break\r\n elif user_choice.lower() == 'report':\r\n for resource in resources:\r\n print(f\"Remaining {resource}: {resources[resource]}\")\r\n continue\r\n elif user_choice == '1':\r\n coffee = 'espresso'\r\n elif user_choice == '2':\r\n coffee = 'latte'\r\n elif user_choice == '3':\r\n coffee = 'cappuccino'\r\n else:\r\n print(\"Invalid input\")\r\n coffee_machine_on = False\r\n break\r\n\r\n # Check resources are sufficient when a user orders a drink\r\n if check_resources(menu[coffee][\"ingredients\"]):\r\n\r\n # Process different types of coin (£2, £1, 50p, 20p, 10p)\r\n cost = menu[coffee][\"cost\"]\r\n print(f\"Please pay £{cost:.2f}. Insert coins:\")\r\n two_pounds = int(input(\"Number of £2 coins: \"))\r\n one_pounds = int(input(\"Number of £1 coins: \"))\r\n fifty_pences = int(input(\"Number of 50p coins: \"))\r\n twenty_pences = int(input(\"Number of 20p coins: \"))\r\n ten_pences = int(input(\"Number of 10p coins: \"))\r\n\r\n money_paid = sum_total(two_pounds, one_pounds, fifty_pences, twenty_pences, ten_pences)\r\n print(f\"Total paid: £{money_paid:.2f}\")\r\n\r\n # Check if there is enough money\r\n # Deplete resources while making coffee\r\n if money_paid >= menu[coffee][\"cost\"]:\r\n print(\"Making coffee...\")\r\n print(f\"Here is your {coffee} ☕. Enjoy!\")\r\n for resource in resources:\r\n if resource in menu[coffee][\"ingredients\"]:\r\n resources[resource] -= menu[coffee][\"ingredients\"][resource]\r\n print(f'Your change: £{money_paid - menu[coffee][\"cost\"]:.2f}')\r\n else:\r\n print(\"Not enough money.\")\r\n continue\r\n\r\n else:\r\n coffee_machine_on = False\r\n","repo_name":"Machzie/100-Days-of-Code-Course-udemy-","sub_path":"Day 15/Day15_main.py","file_name":"Day15_main.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8676526257","text":"# Climbing Stairs\n# Question: You are climbing a stair case. It takes n steps to reach to the top.\n# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n# Solutions:\n\nclass Solution:\n def climbStairs(n):\n dp = [0] * (n + 1)\n dp[0] = dp[1] = 1\n for x in range(2, n + 1):\n dp[x] = dp[x - 1] + dp[x - 2]\n return dp[n]\n\nSolution.climbStairs(10)","repo_name":"syurskyi/Python_Topics","sub_path":"125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 10 - Climbing Stairs.py","file_name":"Coding Challenge No. 10 - Climbing Stairs.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"36974180409","text":"from PIL import Image\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nimage = np.array(Image.open(\"cat.jpg\"))\nedge = cv2.Canny(image,50,110)\n\nplt.imshow(edge)\nplt.show()\ncv2.imwrite(\"cat_edge.jpg\", edge)\n\n\nimage_n = np.array(Image.open(\"noise.jpg\"))\nedge = cv2.Canny(image_n,50,110)\n\nplt.imshow(edge)\nplt.show()\ncv2.imwrite(\"cat_edge_noise.jpg\", edge)","repo_name":"marokazu/pbl2","sub_path":"3_Handling_data/画像データ/find_edges.py","file_name":"find_edges.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42380687665","text":"M = []\ni = 0\n\nfor num_linha in range(4):\n linha = []\n for num_coluna in range(2):\n linha.append(int(input('Digite o elemento da linha %d e coluna %d: ' % (num_linha,num_coluna))))\n M.append(linha)\n\nprint('Matriz original:')\nfor linha in range(len(M)):\n for coluna in range(len(M[linha])):\n print('%3d' % M[linha][coluna], end=' ')\n print()\nprint()\nfor linha in range(len(M)):\n for coluna in range(len(M[linha])):\n if M[linha][coluna] > 10:\n print('%d é maior que 10!' % M[linha][coluna])\n i += 1\nprint('No total, %d elementos são maiores que 10!' % i)\n\nprint('\\nMatriz sem os números maiores que 10:')\nfor linha in range(len(M)):\n for coluna in range(len(M[linha])):\n if M[linha][coluna] > 10:\n M[linha][coluna] = 0\n print('%3d' % M[linha][coluna], end=' ')\n print()","repo_name":"Vicenzops/Exercicios_Alogritmos","sub_path":"Exercicios-Lab/Lab7-Matrizes/Lab7-ex4.py","file_name":"Lab7-ex4.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21747031994","text":"def is_value_in_int32(x):\n\treturn -(2**31) <= x <2**31-1\nclass Solution:\n\tdef reverse(self, x):\n\t\t\"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n\t\tif not is_value_in_int32(x):\n\t\t\tprint(\"intput number x not in int32 : x = \",x)\n\t\t\treturn 0\n\t\tsign = [-1,1][x>0] #判断x的正负\n\t\trx = sign*int(str(abs(x))[::-1]) # int->str->反转-->int\n\t\t\n\t\tif not is_value_in_int32(rx):\n\t\t\tprint(\"result number rx not in int32 : rx = \",rx)\n\t\t\treturn 0\n\t\treturn rx\nif __name__ == '__main__':\n s = Solution()\n print(s.reverse(9876543210))\n print(s.reverse(-123))\n print(s.reverse(1234567899))\n","repo_name":"grb2015/leetcode","sub_path":"7_reverse_integer.py","file_name":"7_reverse_integer.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37167376119","text":"# coding=utf-8\nimport math\n\nfrom tornado.web import RequestHandler\nfrom tornado import gen\n\nfrom . import BaseHandler\nfrom models import BlogClass, BlogSubClass, Blog\n\n\nclass CommonBaseHandler(BaseHandler):\n\n @gen.coroutine\n def get_blog_classes(self):\n _blog_classes = yield self.async_do(BlogClass.get_blog_classes, \n self.db_session, lazy=False)\n \n for _blog_class in _blog_classes[:]:\n for _blog_subclass in _blog_class.subclasses[:]:\n if _blog_subclass.protected:\n _blog_class.subclasses.remove(_blog_subclass)\n if len(_blog_class.subclasses) == 0:\n _blog_classes.remove(_blog_class)\n return _blog_classes\n\n @gen.coroutine\n def prepare(self):\n yield super().prepare()\n self.blog_classes = yield self.get_blog_classes()\n\n def get_template_namespace(self):\n \"\"\"\n NOTE: In the common pages, we need to genarate dynamic navbar,\n so we need to pass blog_classes variable repeatedly when render template!\n This is very inconvenient, we add it into template namespace and use it\n directly.\n \"\"\"\n namespace = super().get_template_namespace()\n namespace['blog_classes'] = self.blog_classes\n return namespace\n\n\nclass DashboardView(CommonBaseHandler):\n\n @gen.coroutine\n def get(self):\n self.render('common/dashboard.html')\n\n\nclass BlogSubClassIndexView(CommonBaseHandler):\n \n BLOGS_PER_PAGE = 10\n \n @gen.coroutine\n def get_blogs(self, blog_query, page_id):\n total = yield self.async_do(blog_query.count)\n offset = (page_id - 1) * self.BLOGS_PER_PAGE\n blogs = yield self.async_do(\n blog_query.order_by(Blog.updated_at.desc()).\n offset(offset).\n limit(self.BLOGS_PER_PAGE).all)\n return blogs, total\n \n @gen.coroutine\n def get(self, subclass_id, page_id):\n blog_subclass = yield self.async_do(BlogSubClass.get_blog_subclass, \n self.db_session, subclass_id)\n if not blog_subclass:\n self.write_error(404)\n else:\n try:\n page_id = int(page_id)\n except ValueError:\n page_id = 1\n print('page_id', page_id)\n blogs, total = yield self.get_blogs(blog_subclass.blog_query, \n page_id)\n pages=math.ceil(total / self.BLOGS_PER_PAGE)\n \n self.render('common/blog_subclass_index.html', \n blogs=blogs,\n pages=pages,\n page=page_id,\n subclass_name=blog_subclass.name,\n class_name=blog_subclass.cls.name)\n\n\nclass BlogReaderView(CommonBaseHandler):\n \n @gen.coroutine\n def get_blog_content(self, blog):\n \"\"\" We defer the load of the blog's content,\n when we access a blog's content attribute,\n it will lead to a sql query and maybe block \n tornado's main thread!\n \"\"\"\n def get_content():\n return blog.content\n content = yield self.async_do(get_content)\n return content\n \n @gen.coroutine\n def get(self, blog_id):\n blog = yield self.async_do(Blog.get_blog, self.db_session, blog_id)\n print('blog_id', blog_id)\n if not blog:\n self.write_error(404)\n content = yield self.get_blog_content(blog)\n self.render('common/blog_reader.html', blog=blog)","repo_name":"garenchan/edge-blog","sub_path":"views/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"15009160344","text":"from subprocess import run\nimport pathlib\n\nCONFIG_REPO_URL=\"https://www.github.com/brainsaysno/nvim_conf.git\"\n\ndef main():\n HOME_DIR = pathlib.Path.home()\n NVIM_CONF_DIR = HOME_DIR / \".config/nvim\"\n # Backup nvim config if exists\n run([\"mv\", \".config/nvim\", \".config/nvim.bak\"], cwd=HOME_DIR)\n\n # Backup nvim folders\n run([\"mv\", \".local/share/nvim\", \".local/share/nvim\"], cwd=HOME_DIR)\n\n # Clone astronvim\n run([\"git\", \"clone\", \"--depth\", \"1\", \"https://www.github.com/AstroNvim/AstroNvim\", \".config/nvim\"], cwd=HOME_DIR)\n\n # Clone config repo\n run([\"git\", \"clone\", CONFIG_REPO_URL, \"lua/user\"], cwd=NVIM_CONF_DIR)\n run([\"ln\", \"-s\", \"lua/user/ftplugin\", \"ftplugins\"], cwd=NVIM_CONF_DIR)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"brainsaysno/nvim_conf","sub_path":"copyconf.py","file_name":"copyconf.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12217634275","text":"import re\n\n# class that will count Assessments lexicons\nclass Priority:\n\n #constructor\n def __init__(self):\n self.ngrams = [\n r'important',\n r'crucial',\n r'key',\n r'essential',\n r'critical',\n r'fundamental',\n r'key',\n r'major',\n r'vital',\n r'first and foremost',\n r'(now )?remember (that)?',\n r'keep in mind (that)?',\n r'don\\'t forget (that)?',\n r'let\\'s not forget',\n r'let\\'s keep in mind',\n r'let\\'s remember'\n ]\n\n\n\n # function to count Assessments n-grams from text\n def analyse(self,text):\n result = 0\n for ngram in self.ngrams:\n r = re.compile(ngram, flags=re.I)\n result += re.subn(r,'',text)[1]\n return result\n\n","repo_name":"colinzhaoust/debate_related_prediction","sub_path":"arglex-master/Priority.py","file_name":"Priority.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"13405613595","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.views import View\nfrom django.views.generic import ListView, DetailView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.core.exceptions import ValidationError\nfrom django.urls import reverse_lazy, reverse\nfrom django.contrib import messages\nfrom .models import Screen\nfrom .forms import HTMLContentForm, ImageContentForm, URLContentForm\n\n\nclass ScreenList(ListView):\n model = Screen\n context_object_name = 'screens'\n\n\nclass ScreenDetail(DetailView):\n model = Screen\n context_object_name = 'screen'\n\n def get_object(self, queryset=None):\n obj = super(ScreenDetail, self).get_object(queryset)\n try:\n obj.fetch_current()\n except:\n pass\n return obj\n\n\nclass ScreenCreate(CreateView):\n model = Screen\n fields = ['name', 'ipaddress', 'password']\n success_url = reverse_lazy('screen-list')\n\n\nclass ScreenUpdate(UpdateView):\n model = Screen\n fields = ['name', 'ipaddress', 'password']\n success_url = reverse_lazy('screen-list')\n\n\nclass ScreenContentUpdate(View):\n _clsmap = {\n 'html': HTMLContentForm,\n 'image': ImageContentForm,\n 'url': URLContentForm,\n }\n\n def get(self, request):\n if 'screen' not in request.GET:\n messages.info(request, \"No screens selected.\")\n return HttpResponseRedirect(reverse('screen-list'))\n screenlist = ','.join(request.GET.getlist('screen'))\n\n if 'action' not in request.GET:\n messages.warning(request, \"No content action specified.\")\n return HttpResponseRedirect(reverse('screen-list'))\n\n formcls = self._clsmap.get(request.GET['action'], None)\n if formcls is None:\n messages.warning(request, \"Bad content action.\")\n return HttpResponseRedirect(reverse('screen-list'))\n\n screennamelist = []\n for sid in request.GET.getlist('screen'):\n screennamelist.append(Screen.objects.get(pk=int(sid)).name)\n\n form = formcls(initial={'content_type': request.GET['action']})\n form.content_type = request.GET['action']\n\n context = {'form': form,\n 'screen': screenlist,\n 'screennames': screennamelist,\n 'action': request.GET['action']}\n return render(request,\n \"screens/screen_content_update.html\",\n context=context)\n\n def post(self, request):\n if 'action' not in request.POST:\n messages.warning(request, \"No content action specified.\")\n return HttpResponseRedirect(reverse('screen-list'))\n if 'screen' not in request.POST:\n messages.warning(request, \"No screens specified for update.\")\n return HttpResponseRedirect(reverse('screen-list'))\n formcls = self._clsmap.get(request.POST['action'], None)\n if formcls is None:\n messages.warning(request, \"Bad content action.\")\n return HttpResponseRedirect(reverse('screen-list'))\n\n form = formcls(request.POST, request.FILES)\n if form.is_valid():\n if 'html_assets' in request.FILES:\n html_assets = request.FILES.getlist('html_assets')\n form.cleaned_data['html_assets'] = html_assets\n\n faillist = []\n successlist = []\n for sid in request.POST['screen']:\n s = Screen.objects.get(pk=sid)\n try:\n success, mesg = s.add_content(request.POST['action'],\n form.cleaned_data)\n except ValidationError as ve:\n smsg = f\"Screen {s.name} update failed: {ve}\"\n faillist.append(smsg)\n else:\n if success:\n smsg = f\"Screen {s.name} update successful: {mesg}\"\n successlist.append(smsg)\n else:\n smsg = f\"Screen {s.name} update failed: {mesg}\"\n faillist.append(smsg)\n if faillist:\n messages.warning(request, \", \".join(faillist))\n if successlist:\n messages.success(request, \", \".join(successlist))\n return HttpResponseRedirect(reverse('screen-detail', args=[s.id]))\n else:\n messages.warning(request, \"Invalid form content.\")\n context = {'form': form,\n 'screen': request.POST['screen'],\n 'action': request.POST['action']}\n return render(request,\n \"screens/screen_content_update.html\",\n context=context)\n\n\nclass ScreenDelete(DeleteView):\n model = Screen\n success_url = reverse_lazy('screen-list')\n\n\nclass ScreenContentDelete(DetailView):\n model = Screen\n\n def post(self, request, *args, **kwargs):\n pk = kwargs.get('pk', None)\n if pk is None:\n raise Http404(\"Screen does not exist\")\n obj = Screen.objects.get(pk=pk)\n name = kwargs.get('name', None)\n if name is None:\n raise Http404(\"Content name not found in request\")\n try:\n response = obj.delete_content(name)\n if response['status'] == 'success':\n messages.success(request, response['reason'].capitalize())\n else:\n messages.warning(request, response['reason'].capitalize())\n except Exception as e:\n messages.warning(request, f\"Content not deleted: {e}\")\n return HttpResponseRedirect(reverse('screen-detail',\n args=[obj.id]))\n","repo_name":"ColgateUniversityComputerScience/csscreen","sub_path":"controller/screens/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"75000837285","text":"#----------------------------------------------\n# DirFunc\n# una lista de funciones con su tipo, direccion y lsta de variables\n#----------------------------------------------\n\n\nclass DirFunc:\n def __init__(self):\n self.functions = []\n\n\nclass Func:\n def __init__(self, id, type, dir):\n self.type = type\n self.id = id\n self.type = type\n self.dir = dir\n self.globDir = None\n self.varTable = []\n\n def __str__(self):\n res = str(self.id)\n res += \" \" + str(self.type)\n res += \" \" + str(self.dir)\n return res\n\nclass Var:\n def __init__(self, id, type, dir):\n self.id = id\n self.type = type\n self.dir = dir\n self.dim = []\n\n def __str__(self):\n res = str(self.id)\n res += \" \" + str(self.type)\n res += \" \" + str(self.dir)\n #res += \" \" + str(self.dim)\n return res\n\nclass DimNode:\n def __init__(self, d, m):\n self.d\n self.m\n self.nextNode\n","repo_name":"Armolp/Compilador","sub_path":"dirFunc.py","file_name":"dirFunc.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19964586891","text":"from datetime import datetime\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom gensim.models.doc2vec import TaggedDocument\r\nfrom tqdm import tqdm\r\nfrom konlpy.tag import Mecab\r\nfrom gensim.models import doc2vec\r\n\r\n#이 데이터에는 책의 주요 정보가 담겨 있어야 함\r\n#author, publisher, title, isbn, Cn_1, Cn_2, Cn_3, Cn_4\r\ndata = pd.read_csv('.../3.csv')\r\n\r\n#작가, 출판사 카테고리 전처리\r\ndata['author'] = data['author'].str.replace(\"[^ㄱ-ㅎㅏ-ㅣ가-힣 ]\",\"\")\r\ndata['publisher'] = data['publisher'].str.replace(\"[^ㄱ-ㅎㅏ-ㅣ가-힣 ]\",\"\")\r\n\r\nfor i in range(1,5):\r\n c = \"Cn_\"+str(i)\r\n data[c] = data[c].str.replace(\"[^ㄱ-ㅎㅏ-ㅣ가-힣 ]\",\"\")\r\n\r\n#전처리 된 데이터프레임\r\nnew_data = data.dropna(subset=['Cn_3','Cn_2', 'Cn_1', 'Cn_4'], inplace=False)\r\nnew_data = new_data.reset_index(drop=True)\r\n\r\n#로그에서 출판사와 작가 모두 가진 행이 많이 없어서 어쩔 수 없이 두 열을 합쳐서 진행\r\nnew_data['author_publisher'] = new_data['author'] + new_data['publisher']\r\nnew_data = new_data.drop(['author', 'publisher', 'id'], axis=1)\r\nnew_data = new_data.dropna()\r\nnew_data = new_data.reset_index(drop=True)\r\n\r\n#최종적으로 사용할 데이터프레임\r\ndf = new_data\r\n\r\n#윈도우에서 진행할 경우에 C 드라이브에서 mecab 딕셔너리나 사용자 정의 딕셔너리를 설치해서 불러 올 수 있다.\r\nmecab = Mecab('C:\\\\mecab\\\\mecab-ko-dic')\r\n#만약에 리눅스에서 할 경우\r\n#mecab = Mecab()\r\n\r\n#각 책의 주요 정보의 단어 딕셔너리 작업하는 시간 확인용, 보통 오래 걸리지 않음\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\n#카테고리 1의 딕셔너리 만드는 작업\r\ndepth1_list = []\r\n\r\nfor index, row in tqdm(df.iterrows(), total=len(df)):\r\n text = row['Cn_1']\r\n tag = row['title']\r\n depth1_list.append(TaggedDocument(tags=[tag], words=mecab.morphs(text)))\r\n\r\nprint('문서의 수 :', len(depth1_list))\r\n\r\n\r\n#카테고리 2\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\ndepth2_list = []\r\n\r\nfor index, row in tqdm(df.iterrows(), total=len(df)):\r\n text4 = row['Cn_2']\r\n tag = row['title']\r\n depth2_list.append(TaggedDocument(tags=[tag], words=mecab.morphs(text4)))\r\n\r\nprint('문서의 수 :', len(depth2_list))\r\n\r\n#카테고리 3\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\ndepth3_list = []\r\n\r\nfor index, row in tqdm(df.iterrows(), total=len(df)):\r\n text5 = row['Cn_3']\r\n tag = row['title']\r\n depth3_list.append(TaggedDocument(tags=[tag], words=mecab.morphs(text5)))\r\n\r\nprint('문서의 수 :', len(depth3_list))\r\n\r\n\r\n#카테고리 4\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\ndepth4_list = []\r\n\r\nfor index, row in tqdm(df.iterrows(), total=len(df)):\r\n text6 = row['Cn_4']\r\n tag = row['title']\r\n depth4_list.append(TaggedDocument(tags=[tag], words=mecab.morphs(text6)))\r\n\r\nprint('문서의 수 :', len(depth4_list))\r\n\r\n#출판사+작가\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\ntagged_corpus_list2 = []\r\n\r\nfor index, row in tqdm(df.iterrows(), total=len(df)):\r\n text2 = row['author_publisher']\r\n tag2 = row['title']\r\n tagged_corpus_list2.append(TaggedDocument(tags=[tag2], words=mecab.morphs(text2)))\r\n\r\n\r\n#책 전체 Doc2Vec 임베딩 진행\r\n#책의 정보를 따로 Doc2Vec으로 학습 시킨 후에 하나로 합침(concat)\r\n#더미용으로 카테고리 1 사용, 사용할 전체 책의 벡터값의 크기 여기서는 100으로 임베딩\r\n#이렇게 진행하는 이유는 따로 임베딩한 후 그 벡터값들을 합친 Doc2Vec 결과가 좋게 나왔음\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\nmodel = doc2vec.Doc2Vec(vector_size=100, alpha=0.025, min_alpha=0.025, workers=8, window=8)\r\n\r\n# Vocabulary 빌드\r\nmodel.build_vocab(depth1_list)\r\n\r\n# Doc2Vec 학습\r\nmodel.train(depth1_list, total_examples=model.corpus_count, epochs=50)\r\n\r\n# 모델 저장\r\nmodel.save('concat.doc2vec')\r\nprint('finish 1')\r\n\r\n#카테고리 1 Doc2Vec 임베딩 진행\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\nmodel2 = doc2vec.Doc2Vec(vector_size=20, alpha=0.025, min_alpha=0.025, workers=8, window=8)\r\nmodel2.build_vocab(depth1_list)\r\nmodel2.train(depth1_list, total_examples=model2.corpus_count, epochs=50)\r\nmodel2.save('d1.doc2vec')\r\n\r\nprint('finish 2')\r\n\r\n#카테고리 2 Doc2Vec 임베딩 진행\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\nmodel5 = doc2vec.Doc2Vec(vector_size=20, alpha=0.025, min_alpha=0.025, workers=8, window=8)\r\nmodel5.build_vocab(depth2_list)\r\nmodel5.train(depth2_list, total_examples=model5.corpus_count, epochs=50)\r\nmodel5.save('d2.doc2vec')\r\n\r\nprint('finish 3')\r\n\r\n\r\n#카테고리 3 Doc2Vec 임베딩 진행\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\nmodel6 = doc2vec.Doc2Vec(vector_size=20, alpha=0.025, min_alpha=0.025, workers=8, window=8)\r\nmodel6.build_vocab(depth3_list)\r\nmodel6.train(depth3_list, total_examples=model6.corpus_count, epochs=50)\r\nmodel6.save('d3.doc2vec')\r\n\r\nprint('finish 4')\r\n\r\n#카테고리 4 Doc2Vec 임베딩 진행\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\nmodel7 = doc2vec.Doc2Vec(vector_size=20, alpha=0.025, min_alpha=0.025, workers=8, window=8)\r\nmodel7.build_vocab(depth4_list)\r\nmodel7.train(depth4_list, total_examples=model7.corpus_count, epochs=50)\r\nmodel7.save('d4.doc2vec')\r\n\r\nprint('finish 5')\r\n\r\n\r\n#출판사+작가 Doc2Vec 임베딩 진행\r\ns = datetime.now().strftime('%H:%M:%S')\r\nprint(s)\r\n\r\nmodel4 = doc2vec.Doc2Vec(vector_size=20, alpha=0.025, min_alpha=0.025, workers=8, window=8)\r\nmodel4.build_vocab(tagged_corpus_list2)\r\nmodel4.train(tagged_corpus_list2, total_examples=model4.corpus_count, epochs=50)\r\nmodel4.save('dart_4.doc2vec')\r\n\r\nprint('finish 6')\r\n\r\n#각 Doc2Vec 모델로부터 벡터값들을 추출해서 사용할 준비\r\nvector = np.zeros((len(df), 20)).astype(np.float32)\r\n\r\nfor i in range(len(df)):\r\n vector[i] = model2.docvecs[df.iloc[i]['title']]\r\n\r\nvector2 = np.zeros((len(df), 20)).astype(np.float32)\r\n\r\nfor i in range(len(df)):\r\n vector2[i] = model5.docvecs[df.iloc[i]['title']]\r\n\r\nvector3 = np.zeros((len(df), 20)).astype(np.float32)\r\n\r\nfor i in range(len(df)):\r\n vector3[i] = model6.docvecs[df.iloc[i]['title']]\r\n\r\nvector4 = np.zeros((len(df), 20)).astype(np.float32)\r\n\r\nfor i in range(len(df)):\r\n vector4[i] = model7.docvecs[df.iloc[i]['title']]\r\n\r\nvector5 = np.zeros((len(df), 20)).astype(np.float32)\r\n\r\nfor i in range(len(df)):\r\n vector5[i] = model4.docvecs[df.iloc[i]['title']]\r\n\r\n#벡터값들을 하나로 concat\r\nvector_merge = np.hstack((vector, vector2, vector3, vector4, vector5))\r\n\r\n#합쳐진 벡터값들의 임시 데이터프레임\r\ntemp_dataframe = pd.DataFrame(vector_merge)\r\n\r\nlist_1 = []\r\nfor i in range(100):\r\n list_1.append('Book_vec_'+str(i))\r\n\r\ntemp_dataframe.columns = list_1\r\n\r\n#벡턱값들과 책의 정보를 가로로 결합\r\ndf_concat = pd.concat([df, temp_dataframe], axis=1)\r\n\r\ndf_concat.to_csv('1m_vectors_category.csv', index= False, encoding = 'utf-8')","repo_name":"GNBproject/Neural-CF","sub_path":"Doc2Vec_comments.py","file_name":"Doc2Vec_comments.py","file_ext":"py","file_size_in_byte":6951,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25394997401","text":"#programa6.3 - apresentação de números\n#programa lê 5 numeros , armazena-os em uma lista e depois solicita ao usuário que escolha um numero a mostrar\n\nnumero = [0, 0, 0, 0, 0]\nx=0\nwhile x < 5:\n numero[x] = int(input(f\"digite um numero {x+1}: \"))\n x+=1\nwhile True:\n escolhido = int(input(\"que posição vc qie imprimir (0 para sair): \"))\n if escolhido == 0:\n break\n else:\n print(f\"vc escolheu o número: {numero[escolhido - 1]}\")\n","repo_name":"GaybsGimenez/python_exercises","sub_path":"cap6/programa6.3 - apresentação de números.py","file_name":"programa6.3 - apresentação de números.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22324168631","text":"\"\"\"\nРеализовать генератор с помощью функции с ключевым словом yield, создающим\nочередное значение. При вызове функции должен создаваться объект-генератор.\nФункция должна вызываться следующим образом: for el in fibo_gen().\nФункция отвечает за получение факториала числа, а в цикле необходимо\nвыводить только первые 15 чисел.\nImplement the generator using a function with the yield keyword that creates\nthe next value. When calling the function, a generator object must be created.\nThe function should be called as follows: for el in fibo_gen(). The function\nis responsible for getting the factorial of a number, and only the first 15\nnumbers must be output in the loop.\n\"\"\"\n\n\nfrom math import *\nfrom itertools import count\n\n\ndef m_func():\n for i in count(1):\n yield factorial(i)\n\n\nfact = m_func()\nn = 0\nfor m in fact:\n if n == 15:\n break\n else:\n n += 1\n print(m)\n","repo_name":"freebrains/Python_basics","sub_path":"Lesson_4.7.py","file_name":"Lesson_4.7.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":"24094893407","text":"import random\n\ncount0=0\ncount1=0\nal=0\n\nfor i in range(0,100):\n rand=random.randrange(2)\n al+=1\n if rand == 1:\n count1+=1\n else:\n count0+=1\n\np0=count0/al\np1=count1/al\n\nprint('Выпало орлов ',count0, '\\nВероятность выпадения орла ', p0,'\\n')\nprint('Выпало решек ',count1,'\\nВероятность выпадения решки ', p1,'\\n')\n\ninput()\n","repo_name":"star-yar/pythonGit","sub_path":"chapter3_moneta.py","file_name":"chapter3_moneta.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37677330358","text":"\"\"\"Desireds Serializer Class.\"\"\"\nfrom django.db.models import Q\nfrom rest_framework import serializers\nfrom ecommerce.models import Product\nfrom ecommerce.models import Desired\nfrom ecommerce.exceptions import ServerErrorOnCreate\n\n\nclass DesiredSerializer(serializers.ModelSerializer):\n \"\"\"Desired List and detail serialzier.\n\n Products desired from user.\n \"\"\"\n\n product = serializers.SlugRelatedField(\n slug_field='id',\n many=False,\n queryset=Product.objects.all().filter(Q(stock__gt=0)))\n\n def create(self, validated_data):\n \"\"\"Create new realation between connected user and product.\"\"\"\n owner = validated_data.pop('owner')\n product = validated_data.pop('product')\n try:\n return Desired.objects.create(owner=owner, product=product)\n except TypeError:\n raise ServerErrorOnCreate()\n\n class Meta:\n \"\"\"Metadata of serializer.\"\"\"\n\n model = Desired\n fields = (\n 'owner',\n 'product',\n )\n read_only_fields = ('owner',)\n","repo_name":"amebalibre/django_test_electroexpress","sub_path":"django_test_electroexpress/ecommerce/serializers/DesiredSerializer.py","file_name":"DesiredSerializer.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20357923980","text":"import math\nimport random\n\nimport numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable as V\nfrom torchvision import transforms as T\n\nfrom itertools import count\nfrom collections import namedtuple\n\nuse_cuda = torch.cuda.is_available()\nFloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\nLongTensor = torch.cuda.LongTensor if use_cuda else torch.LongTensor\nByteTensor = torch.cuda.ByteTensor if use_cuda else torch.ByteTensor\nDoubleTensor = torch.cuda.DoubleTensor if use_cuda else torch.DoubleTensor\nTensor = FloatTensor\nprint(f'use_cuda: {use_cuda}')\n\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward'))\n\n\nclass DQN(nn.Module):\n def __init__(self, n_actions):\n super().__init__()\n self.conv1 = nn.Conv2d(4, 16, kernel_size=5, stride=2, padding=2)\n self.bn1 = nn.BatchNorm2d(16)\n\n self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2, padding=2)\n self.bn2 = nn.BatchNorm2d(32)\n\n self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2, padding=2)\n self.bn3 = nn.BatchNorm2d(32)\n self.head = nn.Linear(32*8*8, n_actions)\n\n def forward(self, x):\n x = F.relu(self.bn1(self.conv1(x)))\n x = F.relu(self.bn2(self.conv2(x)))\n x = F.relu(self.bn3(self.conv3(x)))\n\n return self.head(x.view(x.size(0), -1))\n\n\nclass ReplayMemory:\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n\n\nBATCH_SIZE = 4\nGAMMA = 0.99\nEPS_START = 0.9\nEPS_END=0.1\nEPS_DECAY = 200\n\nqnet = DQN(6)\nqnet.cuda()\n\ntarget_qnet = DQN(6)\ntarget_qnet.load_state_dict(qnet.state_dict())\ntarget_qnet.eval()\ntarget_qnet.cuda()\n\n\noptimizer = optim.RMSprop(qnet.parameters())\nmemory = ReplayMemory(1000000)\n\nsteps_done = 0\ndef select_action(state):\n global steps_done\n sample = random.random()\n eps_thresh = EPS_END + (EPS_START - EPS_END) * math.exp(-1 * steps_done / EPS_DECAY)\n steps_done += 1\n if sample > eps_thresh:\n return qnet(\n V(state, volatile=True).type(FloatTensor)\n ).data.max(1)[1].view(1,1)\n else:\n return LongTensor([[random.randrange(6)]])\n\n\ndef optimize_model():\n if len(memory) < BATCH_SIZE:\n return\n transitions = memory.sample(BATCH_SIZE)\n\n batch = Transition(*zip(*transitions))\n non_final_mask = ByteTensor(tuple(map(lambda s: s is not None,\n batch.next_state)))\n\n non_final_next_states = V(torch.cat([s for s in batch.next_state if s is not None]), volatile=True)\n\n state_batch = V(torch.cat(batch.state))\n action_batch = V(torch.cat(batch.action))\n reward_batch = V(torch.cat(batch.reward))\n\n state_action_values = qnet(state_batch).gather(1, action_batch)\n\n next_state_values = V(torch.zeros(BATCH_SIZE).type(Tensor))\n next_state_values[non_final_mask] = target_qnet(non_final_next_states).max(1)[0]\n expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n expected_state_action_values = V(expected_state_action_values.data)\n\n loss = F.mse_loss(state_action_values, expected_state_action_values)\n optimizer.zero_grad()\n loss.backward()\n for param in qnet.parameters():\n param.grad.data.clamp_(-1, 1)\n optimizer.step()\n\n\ndef main():\n num_ep = 2\n for i_ep in range(num_ep):\n data = torch.from_numpy(np.zeros((1, 4, 64, 64))).type(FloatTensor)\n\n for t in count():\n action = select_action(data)\n\n reward, done = (torch.from_numpy(np.array([random.random()])).type(FloatTensor), (random.random() > 0.5))\n memory.push(data, action, data, reward)\n print(reward, done)\n if t > 12:\n break\n optimize_model()\n pass\n\nif __name__ == '__main__':\n main()","repo_name":"outterback/MarioBot","sub_path":"lab/ml/conv_net/torch_lab.py","file_name":"torch_lab.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40481859801","text":"\"\"\"Tokenizer.\"\"\"\nimport os\n\nimport sentencepiece as spm\n\n\ndef train_tokenizer(\n textfile: str = \"train.txt\",\n vocab_size: int = 32000,\n modelfile: str = \"tokenizer\"\n):\n \"\"\"Train and save a sentencepiece tokenizer model.\"\"\"\n spm.SentencePieceTrainer.train(\n input=textfile,\n model_prefix=modelfile,\n vocab_size=vocab_size,\n character_coverage=1.0,\n split_digits=True,\n model_type='bpe',\n num_threads=os.cpu_count(),\n input_format = \"text\",\n allow_whitespace_only_pieces=True,\n byte_fallback=True,\n unk_surface=r\" \\342\\201\\207 \",\n normalization_rule_name=\"identity\"\n )\n\n\ndef load_tokenizer(modelfile: str = \"tokenizer\") -> spm.SentencePieceProcessor:\n tokenizer = spm.SentencePieceProcessor()\n tokenizer.load(f\"{modelfile}.model\")\n return tokenizer\n","repo_name":"benman1/small_transformers","sub_path":"small_transformer/model/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18252256537","text":"import re\nimport sys\n\nWORD_RE = re.compile(r'\\w+')\n\nindex = {}\nwith open(sys.argv[1], encoding='utf-8') as fp:\n for line_no, line in enumerate(fp, 1):\n for match in WORD_RE.finditer(line):\n word = match.group()\n column_no = match.start() + 1\n location = (line_no, column_no)\n if word not in index:\n index[word] = []\n index[word].append(location)\n","repo_name":"ranog/fluent_python","sub_path":"chapter-03-dictionaries-and-sets/without_setdefault.py","file_name":"without_setdefault.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":"31417592580","text":"n, m = map(int, input().split())\nparents = [i for i in range(n+1)]\nroads = [[] for _ in range(n+1)]\n\ndef find_parent(parents, x):\n if parents[x] != x:\n parents[x] = find_parent(parents, parents[x])\n return parents[x]\n\ndef union_parent(parents, x, y):\n a = find_parent(parents, x)\n b = find_parent(parents, y)\n\n if (a < b):\n parents[b] = a\n else:\n parents[a] = b\n\n\nfor i in range(n):\n li = list(map(int, input().split()))\n for j in range(n):\n if li[j] == 1:\n union_parent(parents, i+1, j+1)\n\nway = list(map(int, input().split()))\nprint(way)\nres = \"YES\"\nfor i in range(1,len(way)):\n if parents[way[i-1]] != parents[way[i]]:\n res = \"NO\"\n\nprint(res)","repo_name":"oaoong/code_example","sub_path":"quiz2/Q41.py","file_name":"Q41.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":"3968152188","text":"from django.urls import path\nfrom .import views\n\nurlpatterns = [\n \n# AUTHNTICATION ROUTES\n \n path('setCookie',views.setCookie, name='setCookie'),\n path('set_currency_to_session',views.set_currency_to_session,name='set_currency_to_session'),\n path('get_selected_currency',views.get_selected_currency,name='get_selected_currency'),\n\n \n\n path('', views.login_page, name='login_page'),\n path('signup_page', views.signup_page, name='signup_page'),\n path('login_page', views.login_page, name='login_page'),\n path('logout_page', views.logout_page, name='logout_page'),\n \n \n# HOME PAGES ROUTES\n\n path('index',views.index,name='index'),\n path('layout2',views.layout2,name='layout2'),\n path('layout3',views.layout3,name='layout3'),\n path('layout4',views.layout4,name='layout4'),\n path('layout5',views.layout5,name='layout5'),\n path('electronics',views.electronics,name='electronics'),\n path('vegetable',views.vegetable,name='vegetable'),\n path('furniture',views.furniture,name='furniture'),\n path('cosmetic',views.cosmetic,name='cosmetic'),\n path('kids',views.kids,name='kids'),\n path('tools',views.tools,name='tools'),\n path('grocery',views.grocery,name='grocery'),\n path('pets',views.pets,name='pets'),\n path('farming',views.farming,name='farming'),\n path('digital_marketplace',views.digital_marketplace,name='digital_marketplace'),\n \n \n \n \n \n# SHOP PAGES ROUTES\n \n path('shop_left_sidebar', views.shop_left_sidebar, name='shop_left_sidebar'),\n path('shop_right_sidebar', views.shop_right_sidebar, name='shop_right_sidebar'),\n path('shop_no_sidebar', views.shop_no_sidebar, name='shop_no_sidebar'),\n path('shop_sidebar_popup', views.shop_sidebar_popup, name='shop_sidebar_popup'),\n path('shop_metro', views.shop_metro, name='shop_metro'),\n path('shop_full_width', views.shop_full_width, name='shop_full_width'),\n path('shop_infinite_scroll', views.shop_infinite_scroll, name='shop_infinite_scroll'),\n path('shop_3grid', views.shop_3grid, name='shop_3grid'),\n path('shop_6grid', views.shop_6grid, name='shop_6grid'),\n path('shop_list_view', views.shop_list_view, name='shop_list_view'),\n\n]\n","repo_name":"WebiotsBhautik/bigdeal-django","sub_path":"bigdealapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33648019531","text":"from django import forms\nfrom .models import VendorPlanner\n\n\nclass VendorMeetingForm(forms.Form):\n first_name = forms.CharField(label='First Name', max_length=100)\n last_name = forms.CharField(label='Last Name', max_length=100)\n company_name = forms.CharField(label='Company Name', max_length=100)\n email = forms.EmailField(label='Email', max_length=100)\n vendors = forms.ModelMultipleChoiceField(\n queryset=VendorPlanner.objects.filter(is_active=True),\n label='Select at least 20 vendors',\n widget=forms.CheckboxSelectMultiple(),\n help_text='You can select multiple vendors by holding down the Ctrl key (Windows) or the Command key (Mac).'\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['vendors'].required = True\n self.fields['vendors'].error_messages['required'] = 'Please select at least 20 vendors.'\n\n\nclass VendorMeetingFormBootstrap(VendorMeetingForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n for name, field in self.fields.items():\n widget_class = 'form-control'\n\n if isinstance(field.widget, forms.CheckboxSelectMultiple):\n widget_class = 'form-check-input'\n elif isinstance(field.widget, forms.CheckboxInput):\n widget_class = 'form-check-input'\n elif isinstance(field.widget, forms.RadioSelect):\n widget_class = 'form-check-input'\n elif isinstance(field.widget, forms.Select):\n widget_class = 'form-select'\n\n field.widget.attrs.update({\n 'class': widget_class,\n 'placeholder': field.label,\n 'aria-label': field.label,\n })\n","repo_name":"dwpinsider/dwp-meeting-choice","sub_path":"vendor/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22666654141","text":"import datetime\n\nunix_time = 1625280000 # Replace this with your Unix time\n\n# Convert Unix time to a datetime object\ntimestamp = datetime.datetime.fromtimestamp(unix_time)\n\n# Convert datetime object to a readable string\nreadable_time = timestamp.strftime('%Y-%m-%d %H:%M:%S')\n\nprint(readable_time)\n","repo_name":"strayByte2022/league-data-crawling","sub_path":"unit_test/test-file.py","file_name":"test-file.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":"74818200803","text":"from django.urls import path\nfrom book.views import goods,content,method,response,index\nfrom book.views import Cookie,set_session,get_session,login\nfrom book.views import LoginView\nfrom django.urls import converters\nfrom django.urls.converters import register_converter\n# 1. 定义转换器\nclass MobileConverter:\n # 验证数据的关键是: 正则\n regex = '1[3-9]\\d{9}'\n\n # 验证没有问题的数据,给视图函数\n def to_python(self,value):\n return value\n\n # def to_url(self,values):\n # # 将匹配结果用于反向解析传值是使用(了解)\n # return value\n# 2.先注册转换器,才能在第三步中使用\n# converter 转换器类\n# type_name 转换器的名字\nregister_converter(MobileConverter,'phone')\n\n\nurlpatterns = [\n path('index/',index),\n # <转换器名字:变量名>\n # 转换器会对变量数据进行 正则验证\n path('//',goods),\n path('content/',content),\n path('method/',method),\n path('response/',response),\n path('Cookie/',Cookie),\n path('set_session',set_session),\n path('get_session',get_session),\n path('login',login),\n path('loginview',LoginView.as_view())\n]","repo_name":"xu678/Djiango","sub_path":"book_django02/book/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12388287966","text":"\"\"\"\n参考链接:\nhttps://www.cnblogs.com/gavanwanggw/p/7337227.html\n\"\"\"\nimport numpy as np\n\n\ndef nmf(v, n_topics, max_iters=100, epsilon=1e-5):\n k = n_topics\n m, n = np.shape(v)\n w = np.array(np.random.random((m, k)))\n h = np.array(np.random.random((k, n)))\n for i in range(max_iters):\n v_pred = np.dot(w, h)\n loss = np.sum(np.power(v_pred - v, 2))\n # print(f\"iter: {i}, loss: {loss}\")\n if loss < epsilon:\n break\n # 乘性更新\n matrix_h = np.dot(w.T, v) / np.dot(np.dot(w.T, w), h)\n h = h * matrix_h\n matrix_w = np.dot(v, h.T) / np.dot(np.dot(w, h), h.T)\n w = w * matrix_w\n return w, h\n\n\nif __name__ == '__main__':\n w0 = np.array([[1, 0],\n [0, 1]])\n h0 = np.array([[0.3, 0.4, 0.5, 0.6, 0.7, 0.7, 0.1, 0.1, 0.2, 0.1],\n [0.4, 0.3, 0.2, 0.1, 0.1, 0.2, 0.5, 0.6, 0.2, 0.8]])\n v0 = np.dot(w0, h0)\n # print(v0)\n w1, h1 = nmf(v0, 2, max_iters=1000, epsilon=1e-9)\n v1 = np.dot(w1, h1)\n print(w1)\n # print(h1)\n # print(v1)\n","repo_name":"tianxing1994/MachineLearning","sub_path":"算法实现/非负矩阵分解/非负矩阵分解.py","file_name":"非负矩阵分解.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"71992524006","text":"import os\r\nfrom PIL import Image\r\nimport numpy as np\r\n\r\n\r\n# 5000 images storing the surrounding\r\nsurr_image_dir = os.path.join(\"./Data\", \"A_5000\")\r\n# Images storing top and down of the antique\r\ntop_bottom_image_dir = os.path.join(\"./Data\", \"top_and_bottom\")\r\n\r\nsurr_images_paths = [os.path.join(surr_image_dir, file_name) for file_name in os.listdir(surr_image_dir)]\r\ntop_bottom_image_paths = [os.path.join(top_bottom_image_dir, file_name)\r\n for file_name in os.listdir(top_bottom_image_dir)]\r\n\r\n# Step 1: Load Images into numpy array\r\nimgs = []\r\n\r\nfor i in range(len(surr_images_paths)):\r\n path = surr_images_paths[i]\r\n\r\n if i % 8 == 0:\r\n img = Image.open(path)\r\n imgs.append(np.asarray(img))\r\n img.close()\r\n\r\n\r\n# Step 2: Load base image\r\n# display(image)\r\nbase = imgs[0]\r\n\r\n\r\n# Step 3: Glue the images into one flattened feature map\r\n# Using the middle 4 pixel vectors for the feature map\r\n# O(n^2) algorithm to glue the images\r\nwindow = None\r\nindx = 0\r\nmerge = base[105:2010, 578:1078]\r\n\r\nwhile indx < len(imgs):\r\n # Get the next window to merge\r\n # Get the middle of the base vase as the starting window\r\n if window is None:\r\n window = base[105:2010, 1078:1082]\r\n rightmost = window[:, -1, :]\r\n # Compute difference of the rightmost vector of the base window and leftmost vectors of windows\r\n # of all the vases. Take the window having the smallest difference.\r\n else:\r\n distance = []\r\n for img in imgs[indx:]:\r\n # Crop the image and convert it to numpy\r\n data = img[105:2010, 1078:1082]\r\n # Get the left most vector\r\n leftmost = data[:, 0, :]\r\n distance.append(np.sum((rightmost - leftmost) * (rightmost - leftmost)))\r\n\r\n indx += np.argmin(distance)\r\n window = imgs[indx][105:2010, 1078:1082]\r\n # Update rightmost vector\r\n rightmost = window[:, -1, :]\r\n\r\n merge = np.concatenate((merge, window), axis=1)\r\n print(f\"Pasted image {indx}\")\r\n indx += 1\r\n# Paste the right side of the vase\r\nmerge = np.concatenate((merge, imgs[indx-1][105:2010, 1082:1560]), axis=1)\r\n\r\nImage.fromarray(merge).show()\r\nImage.fromarray(merge).save(\"./glued_surr.jpg\")\r\n\r\n# Combine with top and bottom images to obtain the feature map\r\ntop_bottom = [Image.open(path) for path in top_bottom_image_paths]\r\ntop_bottom = [np.asarray(img.resize((1905, 1905))) for img in top_bottom]\r\ntop_bottom = np.concatenate(top_bottom, axis=1)\r\nglued_all = np.concatenate((merge, top_bottom), axis=1)\r\n\r\nImage.fromarray(glued_all).show()\r\nImage.fromarray(glued_all).save(\"./glued_all.jpg\")\r\n","repo_name":"howardchanth/antique_2021","sub_path":"Archive/b_glue_photos.py","file_name":"b_glue_photos.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43829454509","text":"from threading import Thread, Lock\nimport timeit\nfrom pytomic.multithreading import AtomicUInt, AtomicUIntUnsafe\n\nNUM_INC = int(1e5)\nNUM_THREAD = 4\nREPEAT = 5\n\n# Lock-based solution\ncounter = 0\nlock = Lock()\ndef lock_inc():\n global counter, lock\n for i in range(NUM_INC):\n with lock:\n counter += 1\n\natomic = AtomicUInt(0)\ndef atomic_inc():\n global atomic\n for i in range(NUM_INC):\n atomic.preinc()\n\natomic_unsafe = AtomicUIntUnsafe(0)\ndef atomic_unsafe_inc():\n global atomic_unsafe\n for i in range(NUM_INC):\n atomic_unsafe.preinc()\n\ndef run(target):\n threads = []\n for i in range(NUM_THREAD):\n t = Thread(target=target)\n t.start()\n threads.append(t)\n for t in threads:\n t.join()\n\ndef bench(fn_target):\n bench_time = timeit.timeit(f\"run({fn_target.__name__})\", number=REPEAT, globals=globals())\n print(f\"{fn_target.__name__} solution | num_threads = {NUM_THREAD} | inc_count = {NUM_INC :,} | repeat = {REPEAT} | done after {bench_time :.4f} | avg ops = {NUM_INC*NUM_THREAD*REPEAT / bench_time :,.0f} ops/s\")\n\nbench(lock_inc)\nbench(atomic_inc)\nbench(atomic_unsafe_inc)","repo_name":"ThamZoo/pytomic","sub_path":"__bench__/bench_multithreading.py","file_name":"bench_multithreading.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"15176139410","text":"\"\"\"This module contains functions for cleaning text data.\"\"\"\n\nimport logging\nimport re\nimport string\nimport tensorflow as tf\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef tag_punct_remover(input_text):\n \"\"\"Does the following to a string:\n - lower case\n - remove punctuations\n - remove HTML tags\n\n Parameters\n ----------\n input_text : str\n String of characters.\n\n Returns\n -------\n tf.tensor\n Processed string converted into a tensor.\n \"\"\"\n lowercase_text = tf.strings.lower(input_text)\n strip_html_text = tf.\\\n strings.regex_replace(lowercase_text,\n \"<[^>]+>\", \" \")\n no_punct_text = tf.\\\n strings.regex_replace(strip_html_text,\n \"[%s]\" % re.escape(string.punctuation), \" \")\n\n no_sing_charac_text = tf.\\\n strings.regex_replace(no_punct_text,\n \"\\s+[a-zA-Z]\\s+\", \" \")\n\n sing_wspaced_text = tf.\\\n strings.regex_replace(no_sing_charac_text,\n \"\\s+\", \" \")\n\n return sing_wspaced_text\n\n\ndef process_file(file_path):\n \"\"\"Reads in a text file and processes the text within it.\n\n Parameters\n ----------\n file_path : str\n String of characters.\n\n Returns\n -------\n tf.tensor\n Processed string converted into a tensor.\n \"\"\"\n logger.debug(\"Reading text file: {}\".format(file_path))\n with open(file_path, \"r\") as file:\n curr_txt = file.read()\n edit_text = tag_punct_remover(curr_txt)\n\n return edit_text\n","repo_name":"aisingapore/ml-project-cookiecutter-gcp","sub_path":"{{cookiecutter.repo_name}}/src/{{cookiecutter.src_package_name}}/data_prep/process_text.py","file_name":"process_text.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"30712352592","text":"import time\nimport os\nimport numpy as np\nimport cv2\nimport win32api\nimport win32con\nimport win32gui\nimport mss\nimport mss.tools\nfrom PIL import Image\n\n\n#FIXME\n#Front slash breaks single quote despite rawstring...\nPATH = r'D:\\github\\GTA5AutonomusPlane'\nFILENAME = r'\\data'\nFILENAME_COUNTER = 1\n\n#Correction margins (appropriate screen capture)\nCORR_LEFT = 8\nCORR_TOP = 35\nCORR_WIDTH = -20\nCORR_HEIGHT = -45\n\nPAUSED = False\n\n#Countdown delay in seconds\nDELAY = 5\n\n#For \"Extended\" multi-screen mode, choose 0, others - select number of monitor\nMONITOR_NUM = 0\n\n#Number of frames + keys combinations per file\nFILE_SIZE = 200\nRESIZE = (180, 120)\n\n\n#Do not touch, frame counter\nCOUNTER = 0\n\ndef capture_screenshot(monitorNum: int, dimensions: tuple):\n with mss.mss() as sct:\n mon = sct.monitors[monitorNum]\n rect = {\n \"left\": mon['left'] + dimensions[0] + CORR_LEFT,\n \"top\": mon['top'] + dimensions[1] + CORR_TOP,\n \"width\": dimensions[2] - dimensions[0] + CORR_WIDTH,\n \"height\": dimensions[3] - dimensions[1] + CORR_HEIGHT,\n \"mon\": monitorNum\n }\n \n sct_img = sct.grab(rect)\n\n # Convert to PIL/Pillow Image\n return Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'RGBX')\n #return np.array(sct_img)\n\n#TODO\n#Add key list generator\n\ndef getKey():\n keys = [0, 0, 0, 0, 0, 0, 0, 0]\n if win32api.GetAsyncKeyState(ord('W')):\n keys[0] = 1\n if win32api.GetAsyncKeyState(ord('A')):\n keys[1] = 1\n if win32api.GetAsyncKeyState(ord('S')):\n keys[2] = 1\n if win32api.GetAsyncKeyState(ord('D')):\n keys[3] = 1\n if win32api.GetAsyncKeyState(win32con.VK_NUMPAD8):\n keys[4] = 1\n if win32api.GetAsyncKeyState(win32con.VK_NUMPAD4):\n keys[5] = 1\n if win32api.GetAsyncKeyState(win32con.VK_NUMPAD5):\n keys[6] = 1\n if win32api.GetAsyncKeyState(win32con.VK_NUMPAD6):\n keys[7] = 1\n if win32api.GetAsyncKeyState(ord('R')):\n return False\n return keys\n\n\nwhile os.path.isfile(f'{PATH}{FILENAME}{FILENAME_COUNTER}.npz'):\n print(f'{PATH}{FILENAME}{FILENAME_COUNTER}.npz exists')\n FILENAME_COUNTER += 1\n\nprint('Open GTA V, enter game and press \"R\" when ready to begin frames recording!')\nprint('Press \"R\" again to pause recording')\n\nwhile True:\n if getKey() == False:\n print(getKey())\n break\n time.sleep(0.2)\n\n\nWINDOW_DIMS = win32gui.GetWindowRect(win32gui.GetForegroundWindow())\nprint('[*]window captured')\n#print(WINDOW_DIMS)\n\nprint(f'Recording to file beginning from {FILENAME}{FILENAME_COUNTER}.npz')\n\ncollectedData = []\nwhile True:\n if not PAUSED:\n tmp = time.time()\n frame = capture_screenshot(\n monitorNum=MONITOR_NUM,\n dimensions=WINDOW_DIMS\n )\n frame = frame.resize(RESIZE)\n frame = np.array(frame)\n\n cv2.imshow(\"test\", frame)\n cv2.waitKey(1)\n\n keys = getKey()\n print(keys)\n print(time.time()-tmp)\n if not keys:\n print(\"-- PAUSED! --\")\n PAUSED = True\n continue\n\n #Saving data into numpy array\n # [[frame1_keys, frame1_image], [frame2_keys, frame2_image], [frame3_keys, frame3_image], ...]\n collectedData.append([frame, keys])\n\n COUNTER += 1\n if COUNTER % FILE_SIZE == 0:\n np.savez_compressed(fr\"{PATH}{FILENAME}{FILENAME_COUNTER}\", collectedData)\n print(rf'========== SAVED to {PATH}{FILENAME}{FILENAME_COUNTER}! ==================')\n collectedData = []\n COUNTER = 0\n FILENAME_COUNTER += 1\n else:\n time.sleep(0.2)\n keys = getKey()\n if not keys:\n print(\"-- resumed! --\")\n PAUSED = False\n","repo_name":"marekzytko/GTA5AutonomousPlane","sub_path":"getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21701783326","text":"from flask import Flask\nfrom datetime import datetime\nimport threading \nimport time \nimport requests\n\napp = Flask(__name__)\n\n\n\ndef keepalive():\n print(\"THRED STARTED\")\n while True:\n time.sleep(60)\n p=requests.get(\"https://ddl39.herokuapp.com/ping\")\n print(\"KEEP ALIVE\")\n\n@app.route('/')\ndef homepage():\n print(\"-------LOG---------\")\n return \"\"\"HELLO WORLD\"\"\"\n\n@app.route('/ping')\ndef ping():\n return \"\"\"HI\"\"\"\n\n@app.route('/log')\ndef log():\n f=open(\"log.txt\", \"r\")\n return \"\"\"{data}\"\"\".format(data=f.read())\n\n@app.route('/thread')\ndef thread():\n print(\"MAIN\")\n t = threading.Thread(target=keepalive)\n t.start() \n\n\n\n \n\nif __name__ == '__main__':\n app.run(debug=True, use_reloader=True)\n\n","repo_name":"ssd39/heroku-zerofreez-flask-","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39215160141","text":"import argparse\n\nclass Configuration:\n\n def __init__(self, config_str):\n self.name, self.config = config_str.split(\";\")\n\n # value of the --configuration option\n self.config_param = \"\"\n\n self.parse_config()\n\n def parse_config(self):\n\n self.params = {}\n\n for param in self.config.split():\n if \"--stats\" in param or \"--quiet=2\" in param:\n continue\n\n if \"=\" in param:\n split = param.split(\"=\")\n name, val = split[0], \"=\".join(split[1:])\n self.params[name] = val\n\n if \"--configuration\" in name:\n self.config_param = val\n\n @property\n def param_names(self):\n return set(self.params.keys())\n\n def get_val(self, param_name):\n if param_name in self.params:\n return self.params[param_name]\n else:\n return \"\"\n\n def compare_param(self, param, val):\n\n if param == \"--configuration\":\n return \"same\"\n\n if param in self.params:\n if val != self.params[param]:\n return \"replace\"\n \n return \"same\"\n\ndef compare_configs(base_config, other_config, params=None):\n # compare other config to base config using params\n # returns a list with the value of the parameter + the result of comparison\n\n if params is None:\n params = set()\n params.update(base_config.param_names)\n params.update(other_config.param_names)\n params = sorted(list(params))\n\n line_base = []\n line_other = []\n for param in params:\n val_base = base_config.get_val(param)\n val_other = other_config.get_val(param)\n\n line_base.append(val_base)\n\n overwrite = base_config.compare_param(param, val_other)\n line_other.append(val_other+\"|\"+overwrite)\n\n\n return compared_list_to_str(base_config.name, line_base), \\\n compared_list_to_str(other_config.name, line_other), \\\n compared_list_to_str(\"\", params)\n\ndef compared_list_to_str(name, comp_list):\n return \"{};\".format(name) + \";\".join(comp_list) + \"\\n\"\n\ndef compare_configs_strings(base_config_str, other_config_str, params=None):\n\n return compare_configs(Configuration(base_config_str),\n Configuration(other_config_str), \n params)\n\ndef compare_configs_by_number(parameter_file, to_compare, out_file):\n\n\n with open(parameter_file, \"r\") as f:\n configs = f.readlines()\n\n with open(out_file, \"w\") as f:\n\n for base, other in to_compare:\n line_base, line_other, params = compare_configs_strings(configs[base], configs[other])\n\n f.write(\"Comparing configs {} and {}\".format(base, other))\n f.write(params)\n f.write(line_base)\n f.write(line_other)\n f.write(\"\\n\\n\")\n\ndef compare_to_default_config(parameter_file, out_file):\n\n # make it a set to have unique values\n all_params = set()\n\n with open(parameter_file, \"r\") as f:\n configs = []\n for c in f.readlines():\n configs.append(Configuration(c))\n\n all_params.update(configs[-1].param_names)\n\n #convert to list so it is ordered\n all_params = sorted(list(all_params))\n\n with open(out_file, \"w\") as f:\n f.write(compared_list_to_str(\"name\", all_params))\n\n for c in configs:\n line_base, line_other, params = compare_configs(default_configs[c.config_param], c)\n f.write(line_other)\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-f\", \"--file\", help=\"File with configurations to compare\")\n parser.add_argument(\"-o\", \"--out\", help=\"Output file name\")\n\n parser.add_argument(\"--self\", action=\"store_true\", help=\"Compare the configuration's options to the default options given by the config in '--configuration'\")\n\n parser.add_argument(\"--by-number\", default=None, help=\"Compare the configurations in the lines given. Input is a tuple separate by a ,. Each tuple is separated by a ; Input format example: 1,2;4,9;1,6\")\n\n args = parser.parse_args()\n\n\n default_configs = {}\n default_configs[\"tweety\"] = Configuration(\"tweety;--eq=3 --trans-ext=dynamic --heuristic=Vsids,92 --restarts=L,60 --deletion=basic,50 --del-max=2000000 --del-estimate=1 --del-cfl=+,2000,100,20 --del-grow=0 --del-glue=2,0 --strengthen=recursive,all --otfs=2 --init-moms --score-other=all --update-lbd=less --save-progress=160 --init-watches=least --local-restarts --loops=shared\")\n default_configs[\"trendy\"] = Configuration(\"trendy;--sat-prepro=2,20,25,240 --trans-ext=dynamic --heuristic=Vsids --restarts=D,100,0.7 --deletion=basic,50 --del-init=3.0,500,19500 --del-grow=1.1,20.0,x,100,1.5 --del-cfl=+,10000,2000 --del-glue=2 --strengthen=recursive --update-lbd=less --otfs=2 --save-progress=75 --counter-restarts=3,1023 --reverse-arcs=2 --contraction=250 --loops=common\")\n default_configs[\"frumpy\"] = Configuration(\"frumpy;--eq=5 --heuristic=Berkmin --restarts=x,100,1.5 --deletion=basic,75 --del-init=3.0,200,40000 --del-max=400000 --contraction=250 --loops=common --save-progress=180 --del-grow=1.1 --strengthen=local --sign-def-disj=pos\")\n default_configs[\"crafty\"] = Configuration(\"crafty;--sat-prepro=2,10,25,240 --trans-ext=dynamic --backprop --heuristic=Vsids --save-progress=180 --restarts=x,128,1.5 --deletion=basic,75 --del-init=10.0,1000,9000 --del-grow=1.1,20.0 --del-cfl=+,10000,1000 --del-glue=2 --otfs=2 --reverse-arcs=1 --counter-restarts=3,9973 --contraction=250\")\n default_configs[\"jumpy\"] = Configuration(\"jumpy;--sat-prepro=2,20,25,240 --trans-ext=dynamic --heuristic=Vsids --restarts=L,100 --deletion=basic,75,mixed --del-init=3.0,1000,20000 --del-grow=1.1,25,x,100,1.5 --del-cfl=x,10000,1.1 --del-glue=2 --update-lbd=glucose --strengthen=recursive --otfs=2 --save-progress=70\")\n default_configs[\"handy\"] = Configuration(\"handy;--sat-prepro=2,10,25,240 --trans-ext=dynamic --backprop --heuristic=Vsids --restarts=D,100,0.7 --deletion=sort,50,mixed --del-max=200000 --del-init=20.0,1000,14000 --del-cfl=+,4000,600 --del-glue=2 --update-lbd=less --strengthen=recursive --otfs=2 --save-progress=20 --contraction=600 --loops=distinct --counter-restarts=7,1023 --reverse-arcs=2\")\n default_configs[\"auto\"] = Configuration(\"auto; \")\n\n\n if args.self:\n compare_to_default_config(args.file, args.out)\n\n if args.by_number is not None:\n pairs = [t.split(\",\") for t in args.by_number.split(\";\")]\n pairs = [(int(v),int(m)) for v,m in pairs]\n compare_configs_by_number(args.file, pairs, args.out)\n\n","repo_name":"kstrauch94/acclingo-tools","sub_path":"eval/comparing_tool.py","file_name":"comparing_tool.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36437649238","text":"import os\nimport sys\nimport cv2\nimport csv\nimport numpy as np\nfrom PIL import Image\nsys.path.append(\"/home/zhangchi/transpicker/Transpicker/src/transpicker\")\nsys.path.append(os.path.dirname(sys.path[0]))\n\nfrom utils import BoundBox\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)\n\n\ndef write_box(path, boxes, write_star=True):\n \"\"\"\n Write box or star files.\n :param path: filepath or filename of the box file to write.\n :param boxes: boxes to write\n :param write_star: if true, a star file will be written.\n :return: None\n \"\"\"\n if write_star:\n path = path[:-3] + 'star'\n write_star_file(path, boxes)\n else:\n write_eman_boxfile(path, boxes)\n\n\ndef write_star_file(path, boxes):\n with open(path, \"w\") as boxfile:\n boxwriter = csv.writer(\n boxfile, delimiter='\\t', quotechar=\"|\", quoting=csv.QUOTE_NONE\n )\n boxwriter.writerow([])\n boxwriter.writerow([\"data_\"])\n boxwriter.writerow([])\n boxwriter.writerow([\"loop_\"])\n boxwriter.writerow([\"_rlnCoordinateX #1 \"])\n boxwriter.writerow([\"_rlnCoordinateY #2 \"])\n boxwriter.writerow([\"_rlnClassNumber #3 \"])\n boxwriter.writerow([\"_rlnAnglePsi #4\"])\n boxwriter.writerow([\"_rlnAutopickFigureOfMerit #5\"])\n for box in boxes:\n boxwriter.writerow([box.x + box.w / 2, box.y + box.h / 2, -9999, -9999.00000, -9999.000000])\n\n\ndef write_eman_boxfile(path, boxes):\n with open(path, \"w\") as boxfile:\n boxwriter = csv.writer(\n boxfile, delimiter='\\t', quotechar=\"|\", quoting=csv.QUOTE_NONE\n )\n for box in boxes:\n # box.x, box,y = lower left corner\n boxwriter.writerow([box.x, box.y, box.w, box.h])\n\n\ndef write_cbox_file(path, boxes):\n with open(path, \"w\") as boxfile:\n boxwriter = csv.writer(\n boxfile, delimiter='\\t', quotechar=\"|\", quoting=csv.QUOTE_NONE\n )\n for box in boxes:\n est_w = box.meta[\"boxsize_estimated\"][0]\n est_h = box.meta[\"boxsize_estimated\"][1]\n boxwriter.writerow([box.x, box.y, box.w, box.h, est_w, est_h])\n\n\ndef get_star_file_header(file_name):\n \"\"\"\n load the header information of star file.\n :param file_name:\n :return: list of head names, rows that are occupied by the header.\n \"\"\"\n start_header = False\n header_names = []\n idx = None\n\n with open(file_name, \"r\") as read:\n for idx, line in enumerate(read.readlines()):\n if line.startswith(\"_\"):\n if start_header:\n header_names.append(line.strip().split()[0])\n else:\n start_header = True\n header_names.append(line.strip().split()[0])\n elif start_header:\n break\n if not start_header:\n raise IOError(f\"No header information found in {file_name}\")\n\n return header_names, idx\n\n\n# read box file or star file or txt file\ndef read_eman_boxfile(path):\n \"\"\"\n Read a box file in EMAN box format.\n :param path: the path of box file\n :return: List of bounding boxes.\n \"\"\"\n boxes = []\n if os.path.getsize(path) == 0:\n print(path, \" has no bbox.\")\n else:\n boxreader = np.atleast_2d(np.genfromtxt(path))\n boxes = [BoundBox(x=box[0], y=box[1], w=box[2], h=box[3]) for box in boxreader]\n\n return boxes\n\n\ndef read_txt_file(path, box_width):\n boxreader = np.atleast_2d(np.genfromtxt(path))\n boxes = []\n for box in boxreader:\n bound_box = BoundBox(x=box[0] - box_width / 2, y=box[1] - box_width / 2, w=box_width, h=box_width)\n boxes.append(bound_box)\n return boxes\n\n\ndef read_star_file(path, box_width):\n header_names, skip_indices = get_star_file_header(path)\n boxreader = np.atleast_2d(np.genfromtxt(path, skip_header=skip_indices))\n boxes = []\n for box in boxreader:\n bound_box = BoundBox(x=box[0] - box_width / 2, y=box[1] - box_width / 2, w=box_width, h=box_width)\n boxes.append(bound_box)\n return boxes\n\n# just for test how label percent affect the prediction results.\ndef read_percent_star_file(path, box_width, percent=100):\n from random import sample\n header_names, skip_indices = get_star_file_header(path)\n boxreader = np.atleast_2d(np.genfromtxt(path, skip_header=skip_indices))\n boxes = []\n for box in boxreader:\n bound_box = BoundBox(x=box[0] - box_width / 2, y=box[1] - box_width / 2, w=box_width, h=box_width)\n boxes.append(bound_box)\n box_num = int(len(boxes) * percent * 0.01)\n print(f'Before sample: {len(boxes)} boxes total.')\n boxes = sample(boxes, box_num)\n print(f'After sample: {len(boxes)} boxes are chosen.')","repo_name":"JachyLikeCoding/Transpicker","sub_path":"src/transpicker/coord_io.py","file_name":"coord_io.py","file_ext":"py","file_size_in_byte":4781,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"73913025764","text":"import numpy as np\n\nx0 = 0\ny0 = 0\nz0 = 0.9\n\nyp = -0.18\nxp = -0.8\nzp = 0.3\n\n#What is the lenght of the vectors from experimental data?\nprint(\"Length of x_0: \", np.sqrt(x0**2 + y0**2 + z0**2))\nprint(\"Length of x_-: \", np.sqrt(xp**2 + yp**2 + zp**2))\n\nsx = np.array([[0, 1], [1, 0]])\nsy = np.array([[0, -1j], [1j, 0]])\nsz = np.array([[1, 0], [0, -1]])\n\nid = np.array([[1, 0], [0, 1]])\n\n# Define the state from experiment\nrho_0 = 0.5 * (id + x0 * sx + y0 * sy + z0 * sz)\nrho_plus = 0.5 * (id + xp * sx + yp * sy + zp * sz)\n\n#What do they look like?\nprint(\"rho_0: \", rho_0)\nprint(\"rho_minus: \", rho_plus)\n\n#The states we should get:\npsi_0 = np.array([[1], [0]])\npsi_plus = 1/(np.sqrt(2)) * np.array([[1], [-1]])\n\n#These density matrices look like:\nprint(\"rho_0_expected: \", np.outer(psi_0, psi_0))\nprint(\"rho_minus_expected: \", np.outer(psi_plus, psi_plus))\n\nF_0 = np.transpose(psi_0) @ rho_0 @ psi_0\nF_plus = np.transpose(psi_plus) @ rho_plus @ psi_plus\n\nprint(\"Fidelity of 0: \", F_0)\nprint(\"Fidelity of minus (antidiagonal because we went with the wrong axis in the QWP): \", F_plus)","repo_name":"JasenLiuCoding/IQIS","sub_path":"fidelity.py","file_name":"fidelity.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24728011813","text":"from rtgym import RealTimeGymInterface, DEFAULT_CONFIG_DICT, DummyRCDrone\nimport gymnasium.spaces as spaces\nimport numpy as np\nimport cv2\nimport torch\nfrom torch.optim import Adam\nfrom copy import deepcopy\n\nfrom threading import Thread\n\nfrom tmrl.networking import Server, RolloutWorker, Trainer\nfrom tmrl.util import partial, cached_property\nfrom tmrl.envs import GenericGymEnv\n\nfrom tmrl.actor import TorchActorModule\nfrom tmrl.util import prod\n\nimport tmrl.config.config_constants as cfg\nfrom tmrl.training_offline import TorchTrainingOffline\nfrom tmrl.training import TrainingAgent\nfrom tmrl.custom.utils.nn import copy_shared, no_grad\n\n\nCRC_DEBUG = False\n\n# === Networking parameters ============================================================================================\n\nsecurity = None\npassword = cfg.PASSWORD\n\nserver_ip = \"127.0.0.1\"\nserver_port = 6666\n\n\n# === Server ===========================================================================================================\n\nif __name__ == \"__main__\":\n my_server = Server(security=security, password=password, port=server_port)\n\n\n# === Environment ======================================================================================================\n\n# rtgym interface:\n\nclass DummyRCDroneInterface(RealTimeGymInterface):\n\n def __init__(self):\n self.rc_drone = None\n self.target = np.array([0.0, 0.0], dtype=np.float32)\n self.initialized = False\n self.blank_image = np.ones((500, 500, 3), dtype=np.uint8) * 255\n self.rendering_thread = Thread(target=self._rendering_thread, args=(), kwargs={}, daemon=True)\n\n def _rendering_thread(self):\n from time import sleep\n while True:\n sleep(0.1)\n self.render()\n\n def get_observation_space(self):\n pos_x_space = spaces.Box(low=-1.0, high=1.0, shape=(1,))\n pos_y_space = spaces.Box(low=-1.0, high=1.0, shape=(1,))\n tar_x_space = spaces.Box(low=-0.5, high=0.5, shape=(1,))\n tar_y_space = spaces.Box(low=-0.5, high=0.5, shape=(1,))\n return spaces.Tuple((pos_x_space, pos_y_space, tar_x_space, tar_y_space))\n\n def get_action_space(self):\n return spaces.Box(low=-2.0, high=2.0, shape=(2,))\n\n def get_default_action(self):\n return np.array([0.0, 0.0], dtype='float32')\n\n def send_control(self, control):\n vel_x = control[0]\n vel_y = control[1]\n self.rc_drone.send_control(vel_x, vel_y)\n\n def reset(self, seed=None, options=None):\n if not self.initialized:\n self.rc_drone = DummyRCDrone()\n self.rendering_thread.start()\n self.initialized = True\n pos_x, pos_y = self.rc_drone.get_observation()\n self.target[0] = np.random.uniform(-0.5, 0.5)\n self.target[1] = np.random.uniform(-0.5, 0.5)\n return [np.array([pos_x], dtype='float32'),\n np.array([pos_y], dtype='float32'),\n np.array([self.target[0]], dtype='float32'),\n np.array([self.target[1]], dtype='float32')], {}\n\n def get_obs_rew_terminated_info(self):\n pos_x, pos_y = self.rc_drone.get_observation()\n tar_x = self.target[0]\n tar_y = self.target[1]\n obs = [np.array([pos_x], dtype='float32'),\n np.array([pos_y], dtype='float32'),\n np.array([tar_x], dtype='float32'),\n np.array([tar_y], dtype='float32')]\n rew = -np.linalg.norm(np.array([pos_x, pos_y], dtype=np.float32) - self.target)\n terminated = rew > -0.01\n info = {}\n return obs, rew, terminated, info\n\n def wait(self):\n pass\n\n def render(self):\n image = self.blank_image.copy()\n pos_x, pos_y = self.rc_drone.get_observation()\n image = cv2.circle(img=image,\n center=(int(pos_x * 200) + 250, int(pos_y * 200) + 250),\n radius=10,\n color=(255, 0, 0),\n thickness=1)\n image = cv2.circle(img=image,\n center=(int(self.target[0] * 200) + 250, int(self.target[1] * 200) + 250),\n radius=5,\n color=(0, 0, 255),\n thickness=-1)\n cv2.imshow(\"Dummy RC drone\", image)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n return\n\n\n# rtgym configuration dictionary:\n\nmy_config = DEFAULT_CONFIG_DICT.copy()\nmy_config[\"interface\"] = DummyRCDroneInterface\nmy_config[\"time_step_duration\"] = 0.05\nmy_config[\"start_obs_capture\"] = 0.05\nmy_config[\"time_step_timeout_factor\"] = 1.0\nmy_config[\"ep_max_length\"] = 100\nmy_config[\"act_buf_len\"] = 4\nmy_config[\"reset_act_buf\"] = False\nmy_config[\"benchmark\"] = True\nmy_config[\"benchmark_polyak\"] = 0.2\n\n\n# Environment class:\n\nenv_cls = partial(GenericGymEnv, id=\"real-time-gym-v1\", gym_kwargs={\"config\": my_config})\n\n\n# Observation and action space:\n\ndummy_env = env_cls()\nact_space = dummy_env.action_space\nobs_space = dummy_env.observation_space\n\nprint(f\"action space: {act_space}\")\nprint(f\"observation space: {obs_space}\")\n\n\n# === Worker ===========================================================================================================\n\nimport torch.nn.functional as F\n\n# ActorModule:\n\nLOG_STD_MAX = 2\nLOG_STD_MIN = -20\n\n\ndef mlp(sizes, activation, output_activation=torch.nn.Identity):\n layers = []\n for j in range(len(sizes) - 1):\n act = activation if j < len(sizes) - 2 else output_activation\n layers += [torch.nn.Linear(sizes[j], sizes[j + 1]), act()]\n return torch.nn.Sequential(*layers)\n\n\nclass MyActorModule(TorchActorModule):\n \"\"\"\n Directly adapted from the Spinup implementation of SAC\n \"\"\"\n def __init__(self, observation_space, action_space, hidden_sizes=(256, 256), activation=torch.nn.ReLU):\n super().__init__(observation_space, action_space)\n dim_obs = sum(prod(s for s in space.shape) for space in observation_space)\n dim_act = action_space.shape[0]\n act_limit = action_space.high[0]\n self.net = mlp([dim_obs] + list(hidden_sizes), activation, activation)\n self.mu_layer = torch.nn.Linear(hidden_sizes[-1], dim_act)\n self.log_std_layer = torch.nn.Linear(hidden_sizes[-1], dim_act)\n self.act_limit = act_limit\n\n def forward(self, obs, test=False, with_logprob=True):\n net_out = self.net(torch.cat(obs, -1))\n mu = self.mu_layer(net_out)\n log_std = self.log_std_layer(net_out)\n log_std = torch.clamp(log_std, LOG_STD_MIN, LOG_STD_MAX)\n std = torch.exp(log_std)\n pi_distribution = torch.distributions.normal.Normal(mu, std)\n if test:\n pi_action = mu\n else:\n pi_action = pi_distribution.rsample()\n if with_logprob:\n logp_pi = pi_distribution.log_prob(pi_action).sum(axis=-1)\n logp_pi -= (2 * (np.log(2) - pi_action - F.softplus(-2 * pi_action))).sum(axis=1)\n else:\n logp_pi = None\n pi_action = torch.tanh(pi_action)\n pi_action = self.act_limit * pi_action\n pi_action = pi_action.squeeze()\n return pi_action, logp_pi\n\n def act(self, obs, test=False):\n with torch.no_grad():\n a, _ = self.forward(obs, test, False)\n return a.cpu().numpy()\n\n\nactor_module_cls = partial(MyActorModule)\n\n\n# Sample compression\n\ndef my_sample_compressor(prev_act, obs, rew, terminated, truncated, info):\n \"\"\"\n Compresses samples before sending over network.\n\n This function creates the sample that will actually be stored in local buffers for networking.\n This is to compress the sample before sending it over the Internet/local network.\n Buffers of such samples will be given as input to the append() method of the memory.\n When you implement such compressor, you must implement a corresponding decompressor.\n This decompressor is the append() or get_transition() method of the memory.\n\n Args:\n prev_act: action computed from a previous observation and applied to yield obs in the transition\n obs, rew, terminated, truncated, info: outcome of the transition\n Returns:\n prev_act_mod: compressed prev_act\n obs_mod: compressed obs\n rew_mod: compressed rew\n terminated_mod: compressed terminated\n truncated_mod: compressed truncated\n info_mod: compressed info\n \"\"\"\n prev_act_mod, obs_mod, rew_mod, terminated_mod, truncated_mod, info_mod = prev_act, obs, rew, terminated, truncated, info\n obs_mod = obs_mod[:4] # here we remove the action buffer from observations\n return prev_act_mod, obs_mod, rew_mod, terminated_mod, truncated_mod, info_mod\n\n\nsample_compressor = my_sample_compressor\n\n\n# Device\n\ndevice = \"cpu\"\n\n\n# Networking\n\nmax_samples_per_episode = 1000\n\n\n# Model files\n\nmy_run_name = \"tutorial\"\nweights_folder = cfg.WEIGHTS_FOLDER\n\nmodel_path = str(weights_folder / (my_run_name + \".tmod\"))\nmodel_path_history = str(weights_folder / (my_run_name + \"_\"))\nmodel_history = 10\n\n\n# Instantiation of the RolloutWorker object:\n\nif __name__ == \"__main__\":\n my_worker = RolloutWorker(\n env_cls=env_cls,\n actor_module_cls=actor_module_cls,\n sample_compressor=sample_compressor,\n device=device,\n server_ip=server_ip,\n server_port=server_port,\n password=password,\n max_samples_per_episode=max_samples_per_episode,\n model_path=model_path,\n model_path_history=model_path_history,\n model_history=model_history,\n crc_debug=CRC_DEBUG)\n\n # my_worker.run(test_episode_interval=10) # this would block the script here!\n\n\n# === Trainer ==========================================================================================================\n\n# --- Networking and files ---\n\nweights_folder = cfg.WEIGHTS_FOLDER # path to the weights folder\ncheckpoints_folder = cfg.CHECKPOINTS_FOLDER\nmy_run_name = \"tutorial\"\n\nmodel_path = str(weights_folder / (my_run_name + \"_t.tmod\"))\ncheckpoints_path = str(checkpoints_folder / (my_run_name + \"_t.tcpt\"))\n\n# --- TrainingOffline ---\n\n# Dummy environment:\n\nenv_cls = partial(GenericGymEnv, id=\"real-time-gym-v1\", gym_kwargs={\"config\": my_config})\n# env_cls = (observation_space, action_space)\n\n\n# Memory:\n\nfrom tmrl.memory import TorchMemory\n\n\nclass MyMemory(TorchMemory):\n def __init__(self,\n act_buf_len=None,\n device=None,\n nb_steps=None,\n sample_preprocessor: callable = None,\n memory_size=1000000,\n batch_size=32,\n dataset_path=\"\"):\n\n self.act_buf_len = act_buf_len # length of the action buffer\n\n super().__init__(device=device,\n nb_steps=nb_steps,\n sample_preprocessor=sample_preprocessor,\n memory_size=memory_size,\n batch_size=batch_size,\n dataset_path=dataset_path,\n crc_debug=CRC_DEBUG)\n\n def append_buffer(self, buffer):\n \"\"\"\n buffer.memory is a list of compressed (act_mod, new_obs_mod, rew_mod, terminated_mod, truncated_mod, info_mod) samples\n \"\"\"\n\n # decompose compressed samples into their relevant components:\n\n list_action = [b[0] for b in buffer.memory]\n list_x_position = [b[1][0] for b in buffer.memory]\n list_y_position = [b[1][1] for b in buffer.memory]\n list_x_target = [b[1][2] for b in buffer.memory]\n list_y_target = [b[1][3] for b in buffer.memory]\n list_reward = [b[2] for b in buffer.memory]\n list_terminated = [b[3] for b in buffer.memory]\n list_truncated = [b[4] for b in buffer.memory]\n list_info = [b[5] for b in buffer.memory]\n\n # append to self.data in some arbitrary way:\n\n if self.__len__() > 0:\n self.data[0] += list_action\n self.data[1] += list_x_position\n self.data[2] += list_y_position\n self.data[3] += list_x_target\n self.data[4] += list_y_target\n self.data[5] += list_reward\n self.data[6] += list_terminated\n self.data[7] += list_info\n self.data[8] += list_truncated\n else:\n self.data.append(list_action)\n self.data.append(list_x_position)\n self.data.append(list_y_position)\n self.data.append(list_x_target)\n self.data.append(list_y_target)\n self.data.append(list_reward)\n self.data.append(list_terminated)\n self.data.append(list_info)\n self.data.append(list_truncated)\n\n # trim self.data in some arbitrary way when self.__len__() > self.memory_size:\n\n to_trim = self.__len__() - self.memory_size\n if to_trim > 0:\n self.data[0] = self.data[0][to_trim:]\n self.data[1] = self.data[1][to_trim:]\n self.data[2] = self.data[2][to_trim:]\n self.data[3] = self.data[3][to_trim:]\n self.data[4] = self.data[4][to_trim:]\n self.data[5] = self.data[5][to_trim:]\n self.data[6] = self.data[6][to_trim:]\n self.data[7] = self.data[7][to_trim:]\n self.data[8] = self.data[8][to_trim:]\n\n def __len__(self):\n if len(self.data) == 0:\n return 0 # self.data is empty\n result = len(self.data[0]) - self.act_buf_len - 1\n if result < 0:\n return 0 # not enough samples to reconstruct the action buffer\n else:\n return result # we can reconstruct that many samples\n\n def get_transition(self, item):\n \"\"\"\n Args:\n item: int: indice of the transition that the Trainer wants to sample\n Returns:\n full transition: (last_obs, new_act, rew, new_obs, terminated, truncated, info)\n \"\"\"\n idx_last = item + self.act_buf_len - 1 # index of previous observation\n idx_now = item + self.act_buf_len # index of new observation\n\n # rebuild the action buffer of both observations:\n actions = self.data[0][item:(item + self.act_buf_len + 1)]\n last_act_buf = actions[:-1] # action buffer of previous observation\n new_act_buf = actions[1:] # action buffer of new observation\n\n # rebuild the previous observation:\n last_obs = (self.data[1][idx_last], # x position\n self.data[2][idx_last], # y position\n self.data[3][idx_last], # x target\n self.data[4][idx_last], # y target\n *last_act_buf) # action buffer\n\n # rebuild the new observation:\n new_obs = (self.data[1][idx_now], # x position\n self.data[2][idx_now], # y position\n self.data[3][idx_now], # x target\n self.data[4][idx_now], # y target\n *new_act_buf) # action buffer\n\n # other components of the transition:\n new_act = self.data[0][idx_now] # action\n rew = np.float32(self.data[5][idx_now]) # reward\n terminated = self.data[6][idx_now] # terminated signal\n truncated = self.data[8][idx_now] # truncated signal\n info = self.data[7][idx_now] # info dictionary\n\n return last_obs, new_act, rew, new_obs, terminated, truncated, info\n\n\nmemory_cls = partial(MyMemory,\n act_buf_len=my_config[\"act_buf_len\"])\n\n\n# Training agent:\n\n\nclass MyCriticModule(torch.nn.Module):\n def __init__(self, observation_space, action_space, hidden_sizes=(256, 256), activation=torch.nn.ReLU):\n super().__init__()\n obs_dim = sum(prod(s for s in space.shape) for space in observation_space)\n act_dim = action_space.shape[0]\n self.q = mlp([obs_dim + act_dim] + list(hidden_sizes) + [1], activation)\n\n def forward(self, obs, act):\n x = torch.cat((*obs, act), -1)\n q = self.q(x)\n return torch.squeeze(q, -1)\n\n\nclass MyActorCriticModule(torch.nn.Module):\n def __init__(self, observation_space, action_space, hidden_sizes=(256, 256), activation=torch.nn.ReLU):\n super().__init__()\n self.actor = MyActorModule(observation_space, action_space, hidden_sizes, activation) # our ActorModule :)\n self.q1 = MyCriticModule(observation_space, action_space, hidden_sizes, activation) # Q network 1\n self.q2 = MyCriticModule(observation_space, action_space, hidden_sizes, activation) # Q network 2\n\n\nimport itertools\n\n\nclass MyTrainingAgent(TrainingAgent):\n\n model_nograd = cached_property(lambda self: no_grad(copy_shared(self.model)))\n\n def __init__(self,\n observation_space=None,\n action_space=None,\n device=None,\n model_cls=MyActorCriticModule, # an actor-critic module, encapsulating our ActorModule\n gamma=0.99, # discount factor\n polyak=0.995, # exponential averaging factor for the target critic\n alpha=0.2, # fixed (SAC v1) or initial (SAC v2) value of the entropy coefficient\n lr_actor=1e-3, # learning rate for the actor\n lr_critic=1e-3, # learning rate for the critic\n lr_entropy=1e-3, # entropy autotuning coefficient (SAC v2)\n learn_entropy_coef=True, # if True, SAC v2 is used, else, SAC v1 is used\n target_entropy=None): # if None, the target entropy for SAC v2 is set automatically\n super().__init__(observation_space=observation_space,\n action_space=action_space,\n device=device)\n model = model_cls(observation_space, action_space)\n self.model = model.to(device)\n self.model_target = no_grad(deepcopy(self.model))\n self.gamma = gamma\n self.polyak = polyak\n self.alpha = alpha\n self.lr_actor = lr_actor\n self.lr_critic = lr_critic\n self.lr_entropy = lr_entropy\n self.learn_entropy_coef=learn_entropy_coef\n self.target_entropy = target_entropy\n self.q_params = itertools.chain(self.model.q1.parameters(), self.model.q2.parameters())\n self.pi_optimizer = Adam(self.model.actor.parameters(), lr=self.lr_actor)\n self.q_optimizer = Adam(self.q_params, lr=self.lr_critic)\n if self.target_entropy is None:\n self.target_entropy = -np.prod(action_space.shape).astype(np.float32)\n else:\n self.target_entropy = float(self.target_entropy)\n if self.learn_entropy_coef:\n self.log_alpha = torch.log(torch.ones(1, device=self.device) * self.alpha).requires_grad_(True)\n self.alpha_optimizer = torch.optim.Adam([self.log_alpha], lr=self.lr_entropy)\n else:\n self.alpha_t = torch.tensor(float(self.alpha)).to(self.device)\n\n def get_actor(self):\n return self.model_nograd.actor\n\n def train(self, batch):\n o, a, r, o2, d, _ = batch # ignore the truncated signal\n pi, logp_pi = self.model.actor(o)\n loss_alpha = None\n if self.learn_entropy_coef:\n alpha_t = torch.exp(self.log_alpha.detach())\n loss_alpha = -(self.log_alpha * (logp_pi + self.target_entropy).detach()).mean()\n else:\n alpha_t = self.alpha_t\n if loss_alpha is not None:\n self.alpha_optimizer.zero_grad()\n loss_alpha.backward()\n self.alpha_optimizer.step()\n q1 = self.model.q1(o, a)\n q2 = self.model.q2(o, a)\n with torch.no_grad():\n a2, logp_a2 = self.model.actor(o2)\n q1_pi_targ = self.model_target.q1(o2, a2)\n q2_pi_targ = self.model_target.q2(o2, a2)\n q_pi_targ = torch.min(q1_pi_targ, q2_pi_targ)\n backup = r + self.gamma * (1 - d) * (q_pi_targ - alpha_t * logp_a2)\n loss_q1 = ((q1 - backup)**2).mean()\n loss_q2 = ((q2 - backup)**2).mean()\n loss_q = loss_q1 + loss_q2\n self.q_optimizer.zero_grad()\n loss_q.backward()\n self.q_optimizer.step()\n for p in self.q_params:\n p.requires_grad = False\n q1_pi = self.model.q1(o, pi)\n q2_pi = self.model.q2(o, pi)\n q_pi = torch.min(q1_pi, q2_pi)\n loss_pi = (alpha_t * logp_pi - q_pi).mean()\n self.pi_optimizer.zero_grad()\n loss_pi.backward()\n self.pi_optimizer.step()\n for p in self.q_params:\n p.requires_grad = True\n with torch.no_grad():\n for p, p_targ in zip(self.model.parameters(), self.model_target.parameters()):\n p_targ.data.mul_(self.polyak)\n p_targ.data.add_((1 - self.polyak) * p.data)\n ret_dict = dict(\n loss_actor=loss_pi.detach().item(),\n loss_critic=loss_q.detach().item(),\n )\n if self.learn_entropy_coef:\n ret_dict[\"loss_entropy_coef\"] = loss_alpha.detach().item()\n ret_dict[\"entropy_coef\"] = alpha_t.item()\n return ret_dict\n\n\ntraining_agent_cls = partial(MyTrainingAgent,\n model_cls=MyActorCriticModule,\n gamma=0.99,\n polyak=0.995,\n alpha=0.2,\n lr_actor=1e-3,\n lr_critic=1e-3,\n lr_entropy=1e-3,\n learn_entropy_coef=True,\n target_entropy=None)\n\n\n# Training parameters:\n\nepochs = 10 # maximum number of epochs, usually set this to np.inf\nrounds = 10 # number of rounds per epoch\nsteps = 1000 # number of training steps per round\nupdate_buffer_interval = 100\nupdate_model_interval = 100\nmax_training_steps_per_env_step = 2.0\nstart_training = 400\ndevice = None\n\n\n# Trainer instance:\n\ntraining_cls = partial(\n TorchTrainingOffline,\n env_cls=env_cls,\n memory_cls=memory_cls,\n training_agent_cls=training_agent_cls,\n epochs=epochs,\n rounds=rounds,\n steps=steps,\n update_buffer_interval=update_buffer_interval,\n update_model_interval=update_model_interval,\n max_training_steps_per_env_step=max_training_steps_per_env_step,\n start_training=start_training,\n device=device)\n\nif __name__ == \"__main__\":\n my_trainer = Trainer(\n training_cls=training_cls,\n server_ip=server_ip,\n server_port=server_port,\n password=password,\n model_path=model_path,\n checkpoint_path=checkpoints_path) # None for not saving training checkpoints\n\n\n# Separate threads for running the RolloutWorker and Trainer:\n\n\ndef run_worker(worker):\n worker.run(test_episode_interval=10)\n\n\ndef run_trainer(trainer):\n trainer.run()\n\n\nif __name__ == \"__main__\":\n daemon_thread_worker = Thread(target=run_worker, args=(my_worker, ), kwargs={}, daemon=True)\n daemon_thread_worker.start() # start the worker daemon thread\n\n run_trainer(my_trainer)\n\n # the worker daemon thread will be killed here.\n","repo_name":"trackmania-rl/tmrl","sub_path":"tmrl/tuto/tuto.py","file_name":"tuto.py","file_ext":"py","file_size_in_byte":22980,"program_lang":"python","lang":"en","doc_type":"code","stars":337,"dataset":"github-code","pt":"52"} +{"seq_id":"21968236075","text":"import sys\nimport csv\nimport os\n\nCLIENT_TABLE = '.clients.csv'\nCLIENT_SCHEMA = ['name', 'company', 'email', 'position']\nclients = []\n\n# Abrir la tabla para leer los datos\ndef _initialize_clients_from_storage():\n with open(CLIENT_TABLE, mode='r') as f:\n reader = csv.DictReader(f, fieldnames=CLIENT_SCHEMA)\n\n for row in reader:\n clients.append(row)\n\n\n# Guardar los cambios realizados a la tabla\ndef _save_clients_to_storage():\n tmp_table_name = f'{CLIENT_TABLE}.tmp'\n with open(tmp_table_name, mode='w') as f:\n writer = csv.DictWriter(f, fieldnames=CLIENT_SCHEMA)\n writer.writerows(clients)\n\n os.remove(CLIENT_TABLE)\n os.rename(tmp_table_name, CLIENT_TABLE)\n\n\n# Crear Clientes\ndef create_client(client):\n global clients # Para tomar variables globales\n\n if client not in clients:\n clients.append(client)\n else:\n print(\"Client already is in the client's list\")\n\n\n# Mostrar a los Clientes\ndef read_clients():\n for i, client in enumerate(clients):\n print(f\"{i} | {client['name']} | {client['company']} | {client['email']} | {client['position']}\")\n\n\n# Actualizar clientes\ndef update_client(client_id, updated_client):\n global clients\n\n if len(clients) - 1 >= client_id:\n clients[client_id] = updated_client\n else:\n print('Client not in client\\'s list')\n\n\n# Borrar clientes\ndef delete_client(client_id):\n global clients\n\n for idx, client in enumerate(clients):\n if idx == client_id:\n del clients[idx] \n break\n\n\n# Buscar Cliente\ndef search_client(client_name):\n \n for client in clients:\n if client['name'] != client_name:\n continue # No ejecutar nada mas en el loop e ir a la siguiente iteración\n else:\n return True\n\n\ndef _get_client_field(field_name, message='What is the client {}? '):\n field = None\n\n while not field:\n field = input(message.format(field_name))\n\n return field\n\n\ndef _get_client_from_user():\n client = {\n 'name': _get_client_field('name'),\n 'company': _get_client_field('company'),\n 'email': _get_client_field('email'),\n 'position': _get_client_field('position'),\n }\n\n return client\n\n\n\n# Función de Menú\ndef _print_welcome():\n print()\n print('*' * 50)\n print('WELCOME TO PLATZI VENTAS')\n print('*' * 50)\n print('What would you like to do today?')\n print()\n print('[C]reate client')\n print('[R]ead client')\n print('[U]pdate client')\n print('[D]elete client')\n print('[S]earch client')\n print()\n\n\nif __name__ == '__main__':\n _initialize_clients_from_storage()\n _print_welcome()\n\n command = input()\n command = command.upper() # Lo vuelve mayúscula\n\n if command == 'C':\n client = _get_client_from_user()\n create_client(client)\n\n elif command == 'R':\n read_clients()\n\n elif command == 'U':\n client_id = int(_get_client_field('id'))\n updated_client = _get_client_from_user()\n update_client(client_id, updated_client)\n\n elif command == 'D':\n client_id = int(_get_client_field('id'))\n delete_client(client_id)\n\n elif command == 'S':\n client_name = _get_client_field('name')\n found = search_client(client_name)\n\n if found:\n print('The client is in the client\\'s list')\n else:\n print(f'The client: {client_name} is not in our client\\'s list')\n else:\n print('Invalid command')\n\n\n _save_clients_to_storage()\n\n\n\n\ndef funcion():\n '''Documentar función'''\n pass\n\n","repo_name":"isabelyb/CRUD_Python","sub_path":"00_main_function.py","file_name":"00_main_function.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29350653249","text":"import os\nimport openai\nimport pypdf\nimport streamlit as st\nfrom streamlit_chat import message\nfrom langchain.vectorstores import FAISS\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.chains import ChatVectorDBChain\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.embeddings.openai import OpenAIEmbeddings\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n SystemMessagePromptTemplate,\n HumanMessagePromptTemplate,\n)\n\n# QA template and general prompt \nsystem_template=\"\"\"Use the following pieces of context to answer the users question. \nIf you don't know the answer, just say that you don't know, don't try to make up an answer.\n----------------\n{context}\"\"\"\nmessages = [\n SystemMessagePromptTemplate.from_template(system_template),\n HumanMessagePromptTemplate.from_template(\"{question}\")\n]\nprompt = ChatPromptTemplate.from_messages(messages)\n\n@st.cache_data\ndef split_pdf(fpath,chunk_chars=4000,overlap=50):\n \"\"\"\n Pre-process PDF into chunks\n Some code from: https://github.com/whitead/paper-qa/blob/main/paperqa/readers.py\n \"\"\"\n st.info(\"`Reading and splitting doc ...`\")\n pdfReader = pypdf.PdfReader(fpath)\n splits = []\n split = \"\"\n pages = []\n for i, page in enumerate(pdfReader.pages):\n pages.append(str(i + 1))\n split += page.extract_text()\n if len(split) > chunk_chars:\n splits.append(split[:chunk_chars])\n split = split[chunk_chars - overlap:]\n return splits\n\n@st.cache_resource\ndef create_ix(splits,_general_prompt):\n \"\"\" \n Create vector DB index of PDF w/ new qa chain and chat history\n \"\"\"\n st.info(\"`Building index ...`\")\n embeddings = OpenAIEmbeddings()\n ix = FAISS.from_texts(splits,embeddings)\n # Use ChatGPT with index QA chain\n llm = ChatOpenAI(temperature=0)\n qa = ChatVectorDBChain.from_llm(llm,ix,qa_prompt=_general_prompt)\n chat_history = []\n return qa, chat_history\n\n# Auth\nst.sidebar.image(\"Img/reading.jpg\")\napi_key = st.sidebar.text_input(\"`OpenAI API Key:`\", type=\"password\")\nst.sidebar.write(\"`By:` [@RLanceMartin](https://twitter.com/RLanceMartin)\")\nos.environ[\"OPENAI_API_KEY\"] = api_key\nchunk_chars = st.sidebar.radio(\"`Choose chunk size for splitting`\", (2000, 3000, 4000), index=1)\nst.sidebar.info(\"`Larger chunk size can produce better answers, but may high ChatGPT context limit (4096 tokens)`\")\n\n# App \nst.header(\"`doc-gpt-chatbot`\")\nst.info(\"`Hello! I am a ChatGPT connected to whatever document you upload.`\")\nuploaded_file_pdf = st.file_uploader(\"`Upload PDF File:` \", type = ['pdf'] , accept_multiple_files=False)\n\n# Re-set history w/ new doc\nif 'generated' not in st.session_state:\n st.session_state['generated'] = []\nif 'past' not in st.session_state:\n st.session_state['past'] = []\n\nif uploaded_file_pdf and api_key:\n\n # Split text and create index\n d=split_pdf(uploaded_file_pdf,chunk_chars)\n qa,chat_history=create_ix(d,prompt)\n \n # Query\n query = st.text_input(\"`Please ask a question:` \",\"What is this document about?\")\n\n # Run\n try:\n\n # Get response\n result = qa({\"question\": query, \"chat_history\": chat_history})\n output = result[\"answer\"]\n\n # Update history\n chat_history.append((query, output))\n st.session_state.past.append(query)\n st.session_state.generated.append(output)\n\n # Visualize chat history \n if st.session_state['generated']:\n for i in range(len(st.session_state['generated'])-1, -1, -1):\n message(st.session_state[\"generated\"][i], key=str(i),avatar_style=\"bottts\",seed=130) \n message(st.session_state['past'][i], is_user=True, key=str(i) + '_user',avatar_style=\"pixel-art\",seed=124) \n\n except openai.error.InvalidRequestError:\n # 4096 token ChatGPT context length https://github.com/acheong08/ChatGPT/discussions/649\n st.warning('Error with model request, often due to context length. Try reducing chunk size.', icon=\"⚠️\")\n\nelse:\n st.info(\"`Please enter OpenAI Key and upload pdf file`\")","repo_name":"rlancemartin/doc-gpt-chatbot","sub_path":"doc-gpt-chat.py","file_name":"doc-gpt-chat.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"31766388828","text":"import os\nimport numpy as np\nimport logging\nimport itertools\nfrom cached_property import cached_property\nfrom sqlalchemy import Column, String, Integer, Text, ForeignKey, Boolean\nfrom sqlalchemy.orm import relationship, Session\nfrom sqlalchemy import UniqueConstraint\n\nfrom tmlib.models.base import MainModel, DirectoryModel, DateMixIn\nfrom tmlib.models import ExperimentSession\nfrom tmlib.readers import YamlReader\nfrom tmlib.writers import YamlWriter\nfrom tmlib.models.utils import remove_location_upon_delete\nfrom tmlib.models.plate import SUPPORTED_PLATE_FORMATS\nfrom tmlib.models.plate import SUPPORTED_PLATE_AQUISITION_MODES\nfrom tmlib.workflow.dependencies import get_workflow_type_information\nfrom tmlib.workflow.illuminati.stitch import guess_stitch_dimensions\nfrom tmlib.workflow.description import WorkflowDescription\nfrom tmlib.workflow.metaconfig import SUPPORTED_MICROSCOPE_TYPES\nfrom tmlib.utils import autocreate_directory_property\n\nlogger = logging.getLogger(__name__)\n\n#: Format string for experiment locations.\nEXPERIMENT_LOCATION_FORMAT = 'experiment_{id}'\n\n\n@remove_location_upon_delete\nclass ExperimentReference(MainModel, DateMixIn):\n\n '''A reference to an *experiment*, which is stored in a separate database.\n\n All data associated with an experiment are stored in separate,\n experiment-specific databases.\n\n Attributes\n ----------\n submissions: List[tmlib.models.submission.Submission]\n submissions belonging to the experiment\n\n See also\n --------\n :class:`tmlib.models.experiment.Experiment`\n '''\n\n __tablename__ = 'experiment_references'\n\n __table_args__ = (UniqueConstraint('name', 'user_id'), )\n\n #: str: name given by the user\n name = Column(String, index=True)\n\n #: str: description provided by the user\n description = Column(Text)\n\n #: absolute path to the directory where experiments are located\n root_directory = Column(String)\n\n #: int: ID of the owner\n user_id = Column(Integer, ForeignKey('users.id'), index=True)\n\n #: tmlib.models.user.User: user that owns the experiment\n user = relationship('User', back_populates='experiments')\n\n def __init__(self, name, user_id, root_directory, description=''):\n '''\n Parameters\n ----------\n name: str\n name of the experiment\n microscope_type: str\n microscope that was used to acquire the images\n plate_format: int\n number of wells in the plate, e.g. 384\n plate_acquisition_mode: str\n the way plates were acquired with the microscope\n user_id: int\n ID of the :class:`User ` that owns the\n experiment\n root_directory: str\n absolute path to root directory on disk where experiment should\n be created in\n description: str, optional\n description of the experimental setup\n\n '''\n self.name = name\n self.user_id = user_id\n self.description = description\n self.root_directory = root_directory\n\n @autocreate_directory_property\n def location(self):\n '''str: location of the experiment,\n e.g. absolute path to a directory on disk\n '''\n if self.id is None:\n raise AttributeError(\n 'Experiment \"%s\" doesn\\'t have an entry in the database yet. '\n 'Therefore, its location cannot be determined.' % self.name\n )\n return os.path.join(\n os.path.expandvars(self.root_directory),\n EXPERIMENT_LOCATION_FORMAT.format(id=self.id)\n )\n\n def belongs_to(self, user):\n '''Determines whether the experiment belongs to a given `user`.\n\n Parameters\n ----------\n user: tmlib.user.User\n `TissueMAPS` user\n\n Returns\n -------\n bool\n whether experiment belongs to `user`\n '''\n return self.user_id == user.id\n\n def can_be_accessed_by(self, user_id, permission='write'):\n '''Checks whether a user has the permissions to access the referenced\n experiment.\n\n Parameters\n ----------\n user_id: int\n ID of :class:`User ` for which permissions\n should be checked\n permission: str, optional\n whether user must have ``\"read\"`` or ``\"write\"`` permission\n (default: ``\"write\"``)\n\n Returns\n -------\n bool\n ``True`` if the user can access the referenced experiment and\n ``False`` otherwise\n '''\n if self.user_id == user_id:\n return True\n else:\n session = Session.object_session(self)\n shares = session.query(ExperimentShare.user_id).\\\n filter_by(experiment_id=self.id).\\\n all()\n if permission == 'read':\n return user_id in [s.user_id for s in shares]\n elif permission == 'write':\n return user_id in [s.user_id for s in shares if s.write_access]\n else:\n raise ValueError(\n 'Argument \"permission\" must be either \"read\" or \"write\".'\n )\n\n def __repr__(self):\n return '' % (self.id, self.name)\n\n\nclass ExperimentShare(MainModel):\n\n '''Relationship between a :class:`User `\n that should be shared\n user_id: int\n ID of the :class:`User ` with whom the\n experiment should be shared\n write_access: bool, optional\n whether the user will have write access to the shared experiment\n (default: ``False``)\n '''\n self.experiment_id = experiment_id\n self.user_id = user_id\n self.write_access = write_access\n\n\n@remove_location_upon_delete\nclass Experiment(DirectoryModel):\n\n '''An *experiment* is the main organizational unit of `TissueMAPS`.\n It represents a set of images and associated data.\n\n Attributes\n ----------\n plates: List[tmlib.models.plate.Plate]\n plates belonging to the experiment\n cycles: List[tmlib.model.cycle.Cycle]\n cycles belonging to the plate\n channels: List[tmlib.models.channel.Channel]\n channels belonging to the experiment\n mapobject_types: List[tmlib.models.mapobject.MapobjectType]\n mapobject types belonging to the experiment\n '''\n\n __tablename__ = 'experiment'\n\n #: str: microscope that was used to acquire the images\n microscope_type = Column(String, index=True, nullable=False)\n\n #: str: workflow type\n workflow_type = Column(String, index=True, nullable=False)\n\n #: int: number of wells in the plate, e.g. 384\n plate_format = Column(Integer, nullable=False)\n\n #: str: the order in which plates were acquired via the microscope\n plate_acquisition_mode = Column(String, nullable=False)\n\n #: int: number of pixels along *y*-axis of the pyramid at highest zoom level\n pyramid_height = Column(Integer)\n\n #: int: number of pixels along *x*-axis of the pyramid at highest zoom level\n pyramid_width = Column(Integer)\n\n #: int: number of zoom levels of the pyramid\n pyramid_depth = Column(Integer)\n\n #: int: zoom factor between pyramid levels\n zoom_factor = Column(Integer, nullable=False)\n\n #: displacement of neighboring sites within a well along the\n #: vertical axis in pixels\n vertical_site_displacement = Column(Integer, nullable=False)\n\n #: displacement of neighboring sites within a well along the\n #: horizontal axis in pixels\n horizontal_site_displacement = Column(Integer, nullable=False)\n\n #: int: gap introduced between neighbooring wells in pixels\n well_spacer_size = Column(Integer, nullable=False)\n\n def __init__(self, id, microscope_type, plate_format, plate_acquisition_mode,\n location, workflow_type='canonical', zoom_factor=2,\n well_spacer_size=500, vertical_site_displacement=0,\n horizontal_site_displacement=0):\n '''\n Parameters\n ----------\n id: int\n ID that should be assigned to the experiment\n microscope_type: str\n microscope that was used to acquire the images\n plate_format: int\n number of wells in the plate, e.g. 384\n plate_acquisition_mode: str\n the way plates were acquired with the microscope\n location: str\n absolute path to the location of the experiment on disk\n workflow_type: str, optional\n name of an implemented workflow type (default: ``\"canonical\"``)\n zoom_factor: int, optional\n zoom factor between pyramid levels (default: ``2``)\n well_spacer_size: int\n gab between neighboring wells in pixels (default: ``500``)\n vertical_site_displacement: int, optional\n displacement of neighboring sites within a well along the\n vertical axis in pixels (default: ``0``)\n horizontal_site_displacement: int, optional\n displacement of neighboring sites within a well along the\n horizontal axis in pixels (default: ``0``)\n\n See also\n --------\n :attr:`tmlib.workflow.metaconfig.SUPPORTED_MICROSCOPE_TYPES`\n :attr:`tmlib.models.plate.SUPPORTED_PLATE_AQUISITION_MODES`\n :attr:`tmlib.models.plate.SUPPORTED_PLATE_FORMATS`\n '''\n self.id = id\n self._location = location\n self.zoom_factor = zoom_factor\n self.well_spacer_size = well_spacer_size\n # TODO: we may be able to calculate this automatically from OMEXML\n self.vertical_site_displacement = vertical_site_displacement\n self.horizontal_site_displacement = horizontal_site_displacement\n if microscope_type not in SUPPORTED_MICROSCOPE_TYPES:\n raise ValueError(\n 'Unsupported microscope type! Supported are: \"%s\"'\n % '\", \"'.join(SUPPORTED_MICROSCOPE_TYPES)\n )\n self.microscope_type = microscope_type\n\n if plate_format not in SUPPORTED_PLATE_FORMATS:\n raise ValueError(\n 'Unsupported plate format! Supported are: %s'\n % ', '.join(map(str, SUPPORTED_PLATE_FORMATS))\n )\n self.plate_format = plate_format\n\n if plate_acquisition_mode not in SUPPORTED_PLATE_AQUISITION_MODES:\n raise ValueError(\n 'Unsupported acquisition mode! Supported are: \"%s\"'\n % '\", \"'.join(SUPPORTED_PLATE_AQUISITION_MODES)\n )\n self.plate_acquisition_mode = plate_acquisition_mode\n\n implemented_workflow_types = get_workflow_type_information()\n if workflow_type not in implemented_workflow_types:\n raise ValueError(\n 'Unsupported workflow type! Supported are: \"%s\"'\n % '\", \"'.join(implemented_workflow_types)\n )\n self.workflow_type = workflow_type\n\n @property\n def location(self):\n '''str: location of the experiment'''\n return self._location\n\n @autocreate_directory_property\n def plates_location(self):\n '''str: location where plates data are stored'''\n return os.path.join(self.location, 'plates')\n\n @autocreate_directory_property\n def channels_location(self):\n '''str: location where channel data are stored'''\n return os.path.join(self.location, 'channels')\n\n @cached_property\n def plate_spacer_size(self):\n '''int: gap between neighboring plates in pixels'''\n return self.well_spacer_size * 2\n\n @cached_property\n def plate_grid(self):\n '''numpy.ndarray[int]: IDs of plates arranged according to\n their relative position of the plate within the experiment overview\n image (sorted row-wise by plate names)\n '''\n n = len(self.plates)\n dimensions = guess_stitch_dimensions(n)\n cooridinates = itertools.product(\n range(dimensions[1]), range(dimensions[0])\n )\n grid = np.zeros(dimensions, dtype=int)\n plates = sorted(self.plates, key=lambda p: p.id)\n for i, (x, y) in enumerate(cooridinates):\n try:\n grid[y, x] = plates[i].id\n except IndexError:\n continue\n return grid\n\n @autocreate_directory_property\n def workflow_location(self):\n '''str: location where workflow data are stored'''\n return os.path.join(self.location, 'workflow')\n\n @autocreate_directory_property\n def tools_location(self):\n '''str: location where tool data are stored'''\n return os.path.join(self.location, 'tools')\n\n @property\n def _workflow_descriptor_file(self):\n return os.path.join(\n self.workflow_location, 'workflow_description.yaml'\n )\n\n @property\n def workflow_description(self):\n '''tmlib.workflow.tmaps.description.WorkflowDescription: description\n of the workflow\n\n Note\n ----\n When no description is available from file, a default description is\n provided. The type of the workflow will be determined based on\n :attr:`workflow_type `.\n '''\n if not os.path.exists(self._workflow_descriptor_file):\n logger.warn('no persistent workflow description found')\n with ExperimentSession(self.id) as session:\n exp = session.query(Experiment).get(self.id)\n workflow_type = exp.workflow_type\n logger.info('create workflow of type \"%s\"', workflow_type)\n workflow_description = WorkflowDescription(workflow_type)\n self.persist_workflow_description(workflow_description)\n\n with YamlReader(self._workflow_descriptor_file) as f:\n description = f.read()\n if not isinstance(description, dict):\n raise TypeError('Description must be a mapping.')\n if 'type' not in description:\n raise KeyError('Workflow description must have key \"type\".')\n if 'stages' not in description:\n raise KeyError('Workflow description must have key \"stages\".')\n\n workflow_description = WorkflowDescription(**description)\n def update_choices(arguments):\n for arg in arguments.iterargs():\n if getattr(arg, 'get_choices', None):\n arg.choices = arg.get_choices(self)\n\n for stage in workflow_description.stages:\n for step in stage.steps:\n update_choices(step.batch_args)\n update_choices(step.submission_args)\n\n return workflow_description\n\n def persist_workflow_description(self, description):\n '''Persists the workflow description and updates `workflow_type`.\n\n Parameters\n ----------\n description: tmlib.workflow.tmaps.description.WorkflowDescription\n description of the workflow\n '''\n self.workflow_type = description.type\n with YamlWriter(self._workflow_descriptor_file) as f:\n f.write(description.to_dict())\n\n def get_mapobject_type(self, name):\n '''Returns a mapobject type belonging to this experiment by name.\n\n Parameters\n ----------\n name : str\n the name of the mapobject_type to be returned\n\n Returns\n -------\n tmlib.models.MapobjectType\n\n Raises\n ------\n sqlalchemy.orm.exc.MultipleResultsFound\n when multiple mapobject types with this name were found\n sqlalchemy.orm.exc.NoResultFound\n when no mapobject type with this name was found\n\n '''\n from tmlib.models import MapobjectType\n session = Session.object_session(self)\n return session.query(MapobjectType).\\\n filter_by(name=name, experiment_id=self.id).\\\n one()\n","repo_name":"TissueMAPS/TissueMAPS","sub_path":"tmlibrary/tmlib/models/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":17106,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"39505333213","text":"try:\n\timport os,sys,socket,subprocess,Networking,time,zipfile\nexcept Exception as e:\n\tprint(e)\n\tsys.exit(1)\nfinally:\n print(\"Imports Complete\")\n#return the uncompressed version of the data\ndef decompress(filenm,dir):\n t=os.getcwd()\n os.chdir(dir)\n z=zipfile.ZipFile(filenm)\n z.extractall()\n z.close()\n os.chdir(t)\ndef compress(lst,name):\n\tfile = zipfile.ZipFile(name, \"w\")\n\tif type(lst)==list:\n\t\tfor i in lst:\n\t\t\tfile.write(i,os.path.basename(i),zipfile.ZIP_DEFLATED)\n\telse:\n\t\tfile.write(lst,os.path.basename(lst),zipfile.ZIP_DEFLATED)\n\tfile.close() \nclass client():\n def __init__(self,port,ip,secret,path):\n self.port=port\n self.host=ip\n self.path=path\n self.secret=secret\n try:\n self.sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.connect((ip,port))\n except Exception as e:\n print(e)\n os._exit(0)\n finally:\n print(\"Slave is now Running\")\n def sendmsg(self,msg):\n try:\n self.sock.sendall(msg.encode('utf-8'))\n except Exception as e:\n print(e)\n os._exit(0)\n def recvmsg(self):\n return self.sock.recv(65656).decode('utf-8')\n def start(self):\n self.sendmsg(self.secret)\n if self.recvmsg()==\"Authenitcated\":\n print(\"Slave Authenitcated\")\n if self.recvmsg()==\"READY\":\n self.sendmsg(\"ACK\")\n print(\"Setting Recieving Server. \")\n try:\n ip,port,filenm=self.recvmsg().split()\n t=os.getcwd()\n os.chdir(self.path)\n serv=Networking.server(host=ip,port=int(port),packetsize=65536,filenm=filenm,sever_directory=self.path) \n except e as Exception:\n print(e)\n nf=True\n self.sendmsg(\"ERROR\")\n finally:\n self.sendmsg(\"ACK\")\n print(\"Server Set, Waiting For Data\")\n serv.handshake(self.secret)\n self.sendmsg(\"ACK\")\n decompress(filenm=filenm,dir=os.getcwd())\n subprocess.run((\"rm \"+filenm).split())\n ls=os.listdir()\n ls.remove('code.py')\n print(os.getcwd())\n for i in ls:\n subprocess.run((\"python code.py \"+ str(i)).split())\n subprocess.run((\"rm \"+str(i)).split())\n subprocess.run((\"rm code.py\").split())\n ls=os.listdir()\n compress(ls,\"output\")\n input(\"enter\")\n c=Networking.client(host=self.host,port=int(port)+1,filenm='output',secret=self.secret)\n c.begin(os.getcwd()+'/')\n for i in os.listdir():\n try:\n subprocess.call(\"rm \"+str(i))\n except:\n try:\n subprocess.call(\"rm -r\"+str(i))\n except:\n pass \n os.chdir(t)\n if self.recvmsg()==\"ACK\":\n print(\"Output recieved. Slave Shutting Down\")\n else:\n self.sendmsg(\"ERROR\") \nif __name__==\"__main__\":\n port=9927\n ip='10.42.0.180'\n secret='shivam'\n path='/home/shivam/Work/Projects/test/slave/'\n client(port,ip,secret,path).start()\n os.chdir(path) \n print(os.listdir()) \n\n","repo_name":"Shivam60/PDON","sub_path":"slave.py","file_name":"slave.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69898504485","text":"#!/usr/bin/env python\n\n# This helper script creates or updates po files from all available pot files.\n# Script expects list of languages - when missing, all available languages will be updated.\n\n# default input directory\npotFilesPath = \"locales\"\n\n# default output directory; used as source for poDeploy.py which will compile and move files from here to the final destination\noutputPath = \"locales\"\n\nimport os\nimport sys\nimport filecmp\nimport shutil\nimport getopt\nimport subprocess\nimport re\n\n# defaults, can be overriden using script parameters\ninteractive = 0\nlanguageList = []\n\n# parse command line\nopts, args = getopt.getopt(sys.argv[1:], \"i\", [\"interactive\"]) \nfor opt, arg in opts:\n\tif (opt in ('-i','--interactive')):\n\t\tinteractive = 1\nif (len(args) > 0):\n\tlanguageList = args\n\nprint(\"--------------------------------------------------\")\nprint(\"1/5 Checking presence of pot directory...\")\nprint(\"--------------------------------------------------\")\nif (not os.path.exists(potFilesPath)):\n\tprint(\"Pot directory `\"+potFilesPath+\"` doesn't exists\")\n\tsys.exit(1)\nprint(\" -> done.\")\n\nprint(\"--------------------------------------------------\")\nprint(\"2/5 Searching for pot files...\")\nprint(\"--------------------------------------------------\")\npotFiles = []\npotDirectoryFiles = os.listdir(potFilesPath)\nfor fileName in potDirectoryFiles:\n\tif (fileName.endswith(\".pot\")):\n\t\tpotFiles.append(fileName[:-len(\".pot\")])\nif (len(potFiles) == 0):\n\tprint(\"No pot files found\")\n\tsys.exit(1)\nelse:\t\t\t\n\tfor potFile in potFiles:\n\t\tprint(potFile)\nprint(\" -> done.\")\n\nprint(\"--------------------------------------------------\")\nprint(\"3/5 Enumerating list of languages...\")\nprint(\"--------------------------------------------------\")\nif (len(languageList) == 0):\n\tdirectories = os.listdir(outputPath)\n\tfor dir in directories:\n\t\tif (os.path.isdir(os.path.join(outputPath, dir))):\n\t\t\tif (dir != \"pot\"):\n\t\t\t\tlanguageList.append(dir)\nif (len(languageList) == 0):\n\tprint(\"No language defined\")\n\tsys.exit(1)\nelse:\n\tprint(\"Pot files will be applied for following languages:\")\n\tfor language in languageList:\n\t\tprint(language)\nprint(\" -> done.\")\n\nprint(\"--------------------------------------------------\")\nprint(\"4/5 Applying language files... \")\nprint(\"--------------------------------------------------\")\nkeepGoing = 1 \nif (interactive):\n\tprint(\"Specified languages will be update with found pot files.\")\n\tstrtmp = raw_input(\"Would you like to continue? [Y,n]: \")\n\tif ((strtmp == 'y') or (strtmp == \"Y\") or (strtmp == \"\")):\n\t\tkeepGoing = 1\n\telse:\n\t\tkeepGoing = 0\ndirectoriesMissingCount = 0\nfilesNewCount = 0\nfilesUpdateCount = 0\nif (keepGoing):\t\n\tfor language in languageList:\n\t\tlanguageDir = os.path.join(outputPath, language, \"LC_MESSAGES\")\n\t\tif (not os.path.exists(languageDir)):\n\t\t\tos.makedirs(languageDir)\n\t\t\tdirectoriesMissingCount += 1\n\t\tfor potFile in potFiles:\n\t\t\tpoFileName = potFile+\".po\"\n\t\t\tpotFileName = potFile+\".pot\"\n\t\t\tpoLanguageFile = os.path.join(languageDir, poFileName)\n\t\t\tpotLanguageFile = os.path.join(potFilesPath, potFileName)\n\t\t\tretval = 0\n\t\t\tif (os.path.exists(poLanguageFile)):\n\t\t\t\tprint(\"Update \"+potLanguageFile+\" -> \"+poLanguageFile)\n\t\t\t\tretval = subprocess.call([\"msgmerge\", \"--update\", \"--backup=off\", poLanguageFile, potLanguageFile])\n\t\t\t\tfilesUpdateCount += 1\n\t\t\t\tif (retval != 0):\n\t\t\t\t\tprint(\"Error invoking msgmerge application\")\n\t\t\t\t\tsys.exit(1)\n\t\t\telse:\n\t\t\t\tprint(\"New \"+potLanguageFile+\" -> \"+poLanguageFile)\n\t\t\t\told = subprocess.check_output([\"msginit\", \"--no-translator\", \"-l\", language, \"-i\", potLanguageFile, \"-o\", \"-\"])\n\n\t\t\t\t# replace charset ASCII for UTF-8 in newly created POT file (DBE 2017-06-14)\n\t\t\t\toutput = open(poLanguageFile, 'w')\n\t\t\t\tnew = re.sub(r'text/plain; charset=ASCII', 'text/plain; charset=UTF-8', old)\n\t\t\t\toutput.write(new)\n\t\t\t\toutput.close()\n\t\t\t\t\n\t\t\t\tfilesNewCount += 1\t\t\t\n\t\t\t# print(\"Stripping POT creation date for better revision control\")\n\t\t\twith open(poLanguageFile, \"r+\") as pof:\n\t\t\t\tnew_f = pof.readlines()\n\t\t\t\tpof.seek(0)\n\t\t\t\tfor line in new_f:\n\t\t\t\t\tif \"POT-Creation-Date\" not in line:\n\t\t\t\t\t\tpof.write(line)\n\t\t\t\tpof.truncate()\n\t\t\t# remove all comments referencing the source location and set all messages non-obsolete.\n\t\t\tsubprocess.call([\"msgattrib\", \"--no-location\", \"--clear-obsolete\", \"-o\", poLanguageFile, poLanguageFile])\n\t\t\t#Set all messages non-obsolete.\n\t\t\t#subprocess.call([\"msgattrib\", \"--clear-obsolete\", \"-o\", poLanguageFile, poLanguageFile])\nelse:\n\tsys.exit()\nprint(\" -> done.\")\n\nprint(\"--------------------------------------------------\")\nprint(\"5/5 Statistics... \")\nprint(\"--------------------------------------------------\")\nprint(\"Directories created: %d\" % (directoriesMissingCount, ))\nprint(\"New files: %d\" % (filesNewCount, ))\nprint(\"Updated files: %d\" % (filesUpdateCount, ))\nprint(\" -> done.\")\nprint(\"Stripped POT creation date from all po files for better revision control.\")\n\nprint(\"\")\nif (interactive):\n\traw_input(\"Press Enter to Exit\")\n","repo_name":"jupsoleil/RunAsAdmin","sub_path":"pot2po.py","file_name":"pot2po.py","file_ext":"py","file_size_in_byte":4920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7360043128","text":"import sys, os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\nfrom jsonHandler import *\n\ndef defineVariables():\n\t#Load info\n\tproData = load_json(\"processedData.json\")\n\n\t#Grab import information\n\tichimoku = proData[\"ichimoku\"]\n\tlength = len(ichimoku)\n\n\t#SpanA line\n\tcurrSpanA = ichimoku[-1][\"spanA\"]\n\tpastSpanA = ichimoku[-2][\"spanA\"]\n\n\t#SpanB line\n\tcurrSpanB = ichimoku[-1][\"spanB\"]\n\tpastSpanB = ichimoku[-2][\"spanB\"]\n\n\t#Cloud color\n\tcurrCloud = ichimoku[-1][\"cloudColor\"]\n\tpastCloud = ichimoku[-2][\"cloudColor\"]\n\n\t#Conversion line\n\tcurrConversion = ichimoku[-1][\"conversionLine\"]\n\tpastConversion = ichimoku[-2][\"conversionLine\"]\n\n\t##Price\n\tcurrPrice = proData[\"Price\"][-1]\n\tpastPrice = proData[\"Price\"][-2]\n\n\treturn ichimoku, length, currSpanA, pastSpanA, currSpanB, pastSpanB, currCloud, pastCloud, currConversion, pastConversion, currPrice, pastPrice\n\n#Price breaks through the cloud\ndef ichimokuCloudDecision ():\n\tichimoku, length, currSpanA, pastSpanA, currSpanB, pastSpanB, currCloud, pastCloud, currConversion, pastConversion, currPrice, pastPrice = defineVariables()\n\tmove = 0\n\n\t#If price just broke out of the cloud while rising\n\t#Buy, 1\n\tif (currCloud == \"red\"):\n\t\tif (pastPrice < pastSpanB and currPrice > currSpanB):\n\t\t\tmove = 1\n\t#Sell, -1\n\t#If price just broke out of the cloud while falling\n\telif (currCloud == \"green\"):\n\t\tif (pastPrice > pastSpanB and currPrice < currSpanB):\n\t\t\tmove = -1\n\t#Hold\n\telse:\n\t\tmove = 0\n\n\treturn move\n\n#Price crosses conversion line\ndef ichiConverDecision ():\n\tichimoku, length, currSpanA, pastSpanA, currSpanB, pastSpanB, currCloud, pastCloud, currConversion, pastConversion, currPrice, pastPrice = defineVariables()\n\tmove = 0\n\n\t#If price crossed conversion line while rising\n\t#Buy, 1\n\tif (pastPrice < pastConversion and currPrice > currConversion):\n\t\tmove = 1\n\n\t#If price crossed conversion line while falling\n\t#Sell, -1\n\telif (pastPrice > pastConversion and currPrice < currConversion):\n\t\tmove = -1\n\t#Hold\n\telse:\n\t\tmove = 0\n\n\treturn move\n\t","repo_name":"sampocs/UW-ATC","sub_path":"deps/policies/IchimokuPolicy.py","file_name":"IchimokuPolicy.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"18324811215","text":"import time\nfrom pathlib import Path\n\nfrom aiogram.types import Message, FSInputFile\nfrom loguru import logger\n\nfrom TG_bot.setup import bot\nfrom TG_bot.src.telegram.messages.user_msg import ProcessActions\nfrom Tiktok import run_thread_tt\nfrom database.query.btns_main_menu import db_get_not_uploaded_videos, db_update_uploaded_video, \\\n db_upd_status_autoposting_tt, db_get_status_autopsting, db_get_tt_name_by_tg_id\nfrom database.tables import TikTokUser, TikTokVideo\n\n\nasync def send_msg_from_db_to_chat(group_chat_id: int):\n obj_for_send: list[TikTokVideo] = db_get_not_uploaded_videos()\n\n for obj_video in obj_for_send:\n video_from_pc = FSInputFile(obj_video.path_video)\n\n await bot.send_video(\n chat_id=group_chat_id, video=video_from_pc,\n caption=obj_video.name_video + \"\\n\\n Powered by @MessHub_bot\"\n )\n\n db_update_uploaded_video(obj_video)\n Path(obj_video.path_video).unlink() # del video from folder /tiktok_video\n\n\nasync def autoposting_tt_inline_btn_task(obj_tiktok_user: TikTokUser, group_chat_id: int):\n \"\"\"\n Run autoposting task for every tiktok user.\n Open browser every 5 minutes and check new one video,\n download video if number of video not in db , send to telegram chat\n \"\"\"\n\n autoposting = True\n\n logger.info(\"start autoposting tt inline btn task\")\n db_upd_status_autoposting_tt(obj_tiktok_user, autoposting)\n\n while autoposting:\n logger.info(f\"autoposting run for {obj_tiktok_user.username}\")\n # run browser and add downloaded video to db\n msg = await run_thread_tt(obj_tiktok_user)\n\n if msg == ProcessActions['sent_success']:\n logger.info(\"new video was sent to chat\")\n # send video to telegram chat\n await send_msg_from_db_to_chat(group_chat_id)\n await bot.send_message(chat_id=group_chat_id, text=ProcessActions['sent_success'])\n\n logger.info(f\"autoposting sleep for {obj_tiktok_user.username}\")\n time.sleep(60 * 5) # 5 min\n\n autoposting = db_get_status_autopsting(obj_tiktok_user)\n logger.info(f\"autoposting status {autoposting} for {obj_tiktok_user.username}\")\n\n\nasync def stop_autoposting_tt_inline_btn_task(group_chat_id):\n \"\"\" Change status autoposting to False in db \"\"\"\n autoposting = False\n logger.info(\"stop autoposting tt inline btn task\")\n\n obj_tiktok_user = db_get_tt_name_by_tg_id(group_chat_id)\n db_upd_status_autoposting_tt(obj_tiktok_user, autoposting)\n\n","repo_name":"ArtDanger/posting_insta_to_tg_group","sub_path":"TG_bot/src/telegram/handlers/user_handlers/act_by_hanler/action_tt_to_tg.py","file_name":"action_tt_to_tg.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6109330318","text":"#封装\n# 需求\n# 小明体重75.0公斤\n# 小明每次跑步减肥0.5公斤\n# 小明每次吃东西增加1公斤\nclass Person:\n def __init__(self,name,weight):\n self.name=name\n self.weight=weight\n def __str__(self):\n return \"我叫%s,我现在的体重有%.2f\"%(self.name,self.weight)\n def run(self):\n self.weight-=0.5\n print(\"%s刚刚跑步后的体重:%0.2f\"%(self.name,self.weight))\n def eat(self):\n self.weight+=1\n print(\"%s刚刚吃饭后的体重:%.2f\" % (self.name,self.weight))\n\nXiaoming=Person(\"小明\",86.0)\nXiaoming.run()\nXiaoming.eat()\nprint(Xiaoming)\nXiaomei=Person(\"小美\",45.0)\nXiaomei.run()\nXiaomei.eat()\nprint(Xiaomei)","repo_name":"doaremon/Python","sub_path":"Day3/面向对象_03封装.py","file_name":"面向对象_03封装.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12323878520","text":"# -*- coding:utf-8 -*-\n# 代码文件:ch07/ch7_5.py\n\n# 一篇文章文本\nwordstring = \"\"\"\n it was the best of times it was the worst of times.\n it was the age of wisdom it was the age of foolishness.\n \"\"\"\n# 将标点符号替换\nwordstring = wordstring.replace('.', '')\n\n# 分割单词\nwordlist = wordstring.split()\n\nwordfreq = []\nfor w in wordlist:\n # 统计单词出现个数\n wordfreq.append(wordlist.count(w))\n\nprint(wordlist)\nprint(wordfreq)\n\nd = dict(zip(wordlist, wordfreq))\nprint(d)\n","repo_name":"vvright/LearningPython","sub_path":"tutorial/comic_py/ch07/ch7_5.py","file_name":"ch7_5.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41957214418","text":"from flask import Flask, Blueprint, render_template, redirect, request\nimport repositories.book_repository as book_repository\nimport repositories.author_repository as author_repository\nfrom models.book import Book\nfrom models.author import Author\n\n\n\nbooks_blueprint = Blueprint(\"books\", __name__)\n\n@books_blueprint.route(\"/books\")\ndef books():\n books = book_repository.select_all()\n return render_template('books/index.html', books=books)\n\n@books_blueprint.route(\"/books/\")\ndef show_book(id):\n book = book_repository.select(id)\n return render_template(\"/books/show.html\", book=book)\n\n@books_blueprint.route(\"/books//delete\", methods = ['POST'])\ndef delete_book(id):\n book_repository.delete(id)\n return redirect(\"/books\")\n\n\n@books_blueprint.route(\"/books/new\")\ndef new_book():\n authors = author_repository.select_all()\n return render_template(\"books/new.html\", authors=authors)\n\n@books_blueprint.route(\"/books\", methods=['POST'])\ndef create_book():\n title = request.form['title']\n genre = request.form['genre']\n author_id =request.form['author_id']\n author = author_repository.select(author_id)\n new_book = Book(title, author, genre)\n book_repository.save(new_book)\n return redirect(\"/books\")\n\n@books_blueprint.route(\"/books//edit\")\ndef edit_book(id):\n book = book_repository.select(id)\n authors = author_repository.select_all()\n return render_template(\"books/edit.html\", book=book, authors=authors)\n\n@books_blueprint.route(\"/books/\", methods=['POST'])\ndef update_book(id):\n title = request.form[\"title\"]\n genre = request.form[\"genre\"]\n author_id = request.form[\"author_id\"]\n author = author_repository.select(author_id)\n book = Book(title, author, genre, id)\n book_repository.update(book)\n return redirect(\"/books\")","repo_name":"duncancryan/library","sub_path":"controllers/book_controller.py","file_name":"book_controller.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19395509226","text":"# arm class with fucntionality required for this project (rest is stripped)\n# ----------------------------------------------------------------------------\nimport numpy as np\nimport time \n\n# ROS\nimport rospy\nfrom tf.transformations import quaternion_from_euler, euler_from_quaternion\nfrom kortex_driver.srv import *\nfrom kortex_driver.msg import *\n# ----------------------------------------------------------------------------\n\nclass Arm:\n def __init__(self, name):\n try:\n self.HOME_ACTION_IDENTIFIER = 2\n\n self.action_topic_sub = None\n self.all_notifs_succeeded = True\n\n self.all_notifs_succeeded = True\n\n # Get node params\n self.robot_name = rospy.get_param('~robot_name', name)\n self.degrees_of_freedom = rospy.get_param(\"/\" + self.robot_name + \"/degrees_of_freedom\", 7)\n self.is_gripper_present = rospy.get_param(\"/\" + self.robot_name + \"/is_gripper_present\", False)\n\n rospy.loginfo(\"Using robot_name \" + self.robot_name + \" , robot has \" + str(self.degrees_of_freedom) + \" degrees of freedom and is_gripper_present is \" + str(self.is_gripper_present))\n\n # setup defult translation and orientation speed \n # when moving in cartesian space\n self.cartesian_speed = CartesianSpeed()\n self.cartesian_speed.translation = .1 # m/s\n self.cartesian_speed.orientation = 15 # deg/s\n\n # Init the action topic subscriber\n self.action_topic_sub = rospy.Subscriber(\"/\" + self.robot_name + \"/action_topic\", ActionNotification, self.cb_action_topic)\n self.last_action_notif_type = None\n\n # Init the services\n clear_faults_full_name = '/' + self.robot_name + '/base/clear_faults'\n rospy.wait_for_service(clear_faults_full_name)\n self.clear_faults = rospy.ServiceProxy(clear_faults_full_name, Base_ClearFaults)\n\n read_action_full_name = '/' + self.robot_name + '/base/read_action'\n rospy.wait_for_service(read_action_full_name)\n self.read_action = rospy.ServiceProxy(read_action_full_name, ReadAction)\n\n execute_action_full_name = '/' + self.robot_name + '/base/execute_action'\n rospy.wait_for_service(execute_action_full_name)\n self.execute_action = rospy.ServiceProxy(execute_action_full_name, ExecuteAction)\n\n set_cartesian_reference_frame_full_name = '/' + self.robot_name + '/control_config/set_cartesian_reference_frame'\n rospy.wait_for_service(set_cartesian_reference_frame_full_name)\n self.set_cartesian_reference_frame = rospy.ServiceProxy(set_cartesian_reference_frame_full_name, SetCartesianReferenceFrame)\n\n activate_publishing_of_action_notification_full_name = '/' + self.robot_name + '/base/activate_publishing_of_action_topic'\n rospy.wait_for_service(activate_publishing_of_action_notification_full_name)\n self.activate_publishing_of_action_notification = rospy.ServiceProxy(activate_publishing_of_action_notification_full_name, OnNotificationActionTopic)\n\n send_gripper_command_full_name = '/' + self.robot_name + '/base/send_gripper_command'\n rospy.wait_for_service(send_gripper_command_full_name)\n self.send_gripper_command = rospy.ServiceProxy(send_gripper_command_full_name, SendGripperCommand)\n\n get_product_configuration_full_name = '/' + self.robot_name + '/base/get_product_configuration'\n rospy.wait_for_service(get_product_configuration_full_name)\n self.get_product_configuration = rospy.ServiceProxy(get_product_configuration_full_name, GetProductConfiguration)\n\n validate_waypoint_list_full_name = '/' + self.robot_name + '/base/validate_waypoint_list'\n rospy.wait_for_service(validate_waypoint_list_full_name)\n self.validate_waypoint_list = rospy.ServiceProxy(validate_waypoint_list_full_name, ValidateWaypointList)\n\n self.clear_faults()\n self.set_cartesian_reference_frame()\n self.subscribe_to_a_robot_notification()\n\n except:\n self.is_init_success = False\n else:\n self.is_init_success = True\n\n def set_cartesian_velocity(self, values):\n \"\"\"\n Sends a carteian velocity command\n\n ---------\n values: list or np array of the form: [x,y,z, x-twist, y-twist, z-twist, w-twist]\n\n \"\"\"\n cartesian_vel_publisher = rospy.Publisher(\"/my_gen3_lite/in/cartesian_velocity\", TwistCommand, queue_size=10, latch=True)\n stop_publisher = rospy.Publisher(\"/my_gen3_lite/in/stop\", std_msgs.msg.Empty, queue_size=10, latch=True)\n empty_message = std_msgs.msg.Empty()\n cartesian_command = TwistCommand()\n\n twists = euler_from_quaternion((values[3:]))\n cartesian_command.twist.linear_x = values[0]\n cartesian_command.twist.linear_y = values[1]\n cartesian_command.twist.linear_z = values[2]\n cartesian_command.twist.angular_x = twists[0]\n cartesian_command.twist.angular_y = twists[1]\n cartesian_command.twist.angular_z = twists[2]\n\n cartesian_vel_publisher.publish(cartesian_command)\n # this sleep is necessary to process the sleep before the next potential command\n time.sleep(0.3)\n # TODO reduce this duration to 0.00000001 for video of case where gaze is confusing\n # stop_publisher.publish(empty_message)","repo_name":"AABL-Lab/gaze_op","sub_path":"src/arm_stripped.py","file_name":"arm_stripped.py","file_ext":"py","file_size_in_byte":5200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12920047170","text":"\"\"\"\n`dacman.core.change`\n====================================\n\n.. currentmodule:: dacman.core.change\n\n:platform: Unix, Mac\n:synopsis: Module to capture changes between datasets\n\n.. moduleauthor:: Devarshi Ghoshal \n\n\"\"\"\n\ntry:\n from os import scandir, walk\nexcept ImportError:\n from scandir import scandir, walk\n\nimport yaml\nimport sys\nimport os\nimport uuid\nimport shutil\n\nimport dacman.core.scanner as scanner\nimport dacman.core.indexer as indexer\nimport dacman.core.comparator as comparator\nfrom dacman.core.utils import cprint, get_hash_id\nimport dacman.core.utils as dacman_utils\n\nimport logging\n\n__modulename__ = 'change'\n\n'''\nbase class that captures change in terms of number of objects added, deleted, modified, unchanged\n'''\nclass Change():\n def __init__(self, added, deleted, modified, unchanged):\n self._added = added\n self._deleted = deleted\n self._modified = modified\n self._unchanged = unchanged\n '''\n the degree of total change in the dataset\n '''\n self._degree = 0.0\n\n @property\n def old_path(self):\n return self._old_path\n\n @property\n def new_path(self):\n return self._new_path\n\n @property\n def old_nfiles(self):\n return self._old_nfiles\n\n @property\n def new_nfiles(self):\n return self._new_nfiles\n\n @property\n def added(self):\n return self._added\n\n @property\n def deleted(self):\n return self._deleted\n\n @property\n def modified(self):\n return self._modified\n\n @property\n def unchanged(self):\n return self._unchanged\n\n @property\n def degree(self):\n return self._degree\n\n def calculate_degree(self):\n total_change = len(self.added) + len(self.deleted) + len(self.modified)\n total_original_data = len(self.deleted) + len(self.modified) + len(self.unchanged)\n\n if total_original_data > 0:\n self._degree = total_change * 1.0 / total_original_data\n else:\n self._degree = 100.0\n return self._degree\n\n def get_change_map(self):\n change_map = {'modified': len(self._modified),\n 'deleted': len(self._deleted),\n 'added': len(self._added),\n 'unchanged': len(self._unchanged)} \n return change_map\n\n#################\n\nclass FilesystemChange(Change):\n def __init__(self, old_path, new_path, stagingdir):\n Change.__init__(self, [], [], [], [])\n self._old_path = old_path\n self._new_path = new_path\n self._old_nfiles = 0\n self._new_nfiles = 0\n self._stagingdir = stagingdir\n self._metachange = []\n\n '''\n def __get_nfiles__(self, path):\n print(path)\n scan_file = os.path.join(self._stagingdir, 'indexes', get_hash_id(path), 'FILEPATHS')\n with open(scan_file) as f:\n nlines = sum(1 for line in f)\n return nlines\n\n def set_path_files(self, path):\n self._old_nfiles = self.__get_nfiles__(self._old_path)\n self._new_nfiles = self.__get_nfiles__(self._new_path)\n '''\n\n def add_changes(self, added=[], deleted=[], modified=[], unchanged=[], metachange=[]):\n self._added = added\n self._deleted = deleted\n self._modified = modified\n self._unchanged = unchanged\n self._metachange = metachange\n\n @property\n def old_path(self):\n return self._old_path\n\n @property\n def new_path(self):\n return self._new_path\n\n @property\n def old_nfiles(self):\n return self._old_nfiles\n\n @property\n def new_nfiles(self):\n return self._new_nfiles\n\n @old_nfiles.setter\n def old_nfiles(self, old_nfiles):\n self._old_nfiles = old_nfiles\n\n @new_nfiles.setter\n def new_nfiles(self, new_nfiles):\n self._new_nfiles = new_nfiles\n\n @property\n def metachange(self):\n return self._metachange\n\n def calculate_degree(self):\n total_change = len(self.added) + len(self.deleted) + len(self.modified)\n total_original_data = len(self.deleted) + len(self.modified) +\\\n len(self.metachange) + len(self.unchanged)\n\n if total_original_data > 0:\n self._degree = total_change * 1.0 / total_original_data\n else:\n self._degree = 100.0\n return self._degree\n\n def get_change_map(self):\n change_map = {'modified': len(self._modified),\n 'deleted': len(self._deleted),\n 'added': len(self._added),\n 'metaonly': len(self._metachange),\n 'unchanged': len(self._unchanged)} \n return change_map\n\n\nclass CacheStatus(object):\n ALL_CACHED = 0\n NEW_PARENT_CACHED = 1\n OLD_PARENT_CACHED = 2\n BOTH_PARENTS_CACHED = 3\n NOT_CACHED = 4\n\n######################################################################################\n'''\nutility function to find directory entries\n'''\ndef find_direntries(dir):\n entries = {}\n if not os.path.exists(dir):\n cprint(__modulename__, 'Directory {} does not exist'.format(dir))\n sys.exit()\n\n for entry in scandir(dir):\n entries[entry.name] = entry\n return entries\n \n'''\nThis will be the future way of invoking change calculation.\nThe module function will be removed \n'''\nclass ChangeManager(object):\n\n def __init__(self, old_datapath, new_datapath, force=False, custom_stagingdir=None):\n self._old_datapath = old_datapath\n self._new_datapath = new_datapath\n self._force = force\n if not custom_stagingdir:\n self._stagingdir = dacman_utils.DACMAN_STAGING_LOC\n else:\n self._stagingdir = custom_stagingdir\n\n self._cachedir = os.path.join(self._stagingdir, 'cache')\n self._cache_entries = os.path.join(self._cachedir, 'ENTRIES')\n\n\n @property\n def old_datapath(self):\n return self._old_datapath\n\n @property\n def new_datapath(self):\n return self._new_datapath\n\n @property\n def force(self):\n return self._force\n \n @property\n def stagingdir(self):\n return self._stagingdir\n \n @property\n def cachedir(self):\n return self._cachedir\n \n @property\n def cache_entries(self):\n return self._cache_entries\n \n '''\n get cache status: check where in the cache is the change stored\n '''\n def get_cached_paths(self):\n logger = logging.getLogger(__name__)\n\n if self.old_datapath == self.new_datapath:\n logger.error('Comparison paths are the same')\n sys.exit()\n\n is_subdir_oldpath = False\n is_subdir_newpath = False\n cached_old_path = self.old_datapath\n cached_new_path = self.new_datapath\n \n status = CacheStatus.NOT_CACHED\n logger.info('Checking cache status.')\n\n '''\n This is the caching logic where change information is saved and subsequently retrieved\n If no high-level diff exists for the data, then do a comparison\n - do the comparison for the all the indexed data\n - at runtime, decide if the comparison is between any subdirectories of the total diff\n '''\n if os.path.exists(self.cache_entries):\n logger.info('Cache exists... checking cache entries.')\n '''\n if the high-level diff exists,\n then check if it exists for the two data versions provided here\n '''\n with open(self.cache_entries, 'r') as f:\n cache = yaml.safe_load(f)\n '''\n if changes for the newpath are in cache, then\n check if they are for the compared oldpath \n '''\n if self.new_datapath in cache:\n '''\n if the diff paths are already compared, then get the corresponding directory;\n else, do the comparisons/diff\n '''\n if self.old_datapath in cache[self.new_datapath]:\n '''\n if both oldpath and newpath are in the cache\n '''\n logger.info('Changes are present in cache...')\n status = CacheStatus.ALL_CACHED\n else:\n '''\n check if the oldpath is a subdirectory of a cached path change\n '''\n for o in cache[self.new_datapath]:\n parent_path = o + os.sep\n if self.old_datapath.startswith(parent_path):\n logger.info('Changes can be derived from the cache.')\n status = CacheStatus.OLD_PARENT_CACHED\n cached_old_path = os.path.abspath(parent_path)\n break\n else:\n '''\n if changes for the original newpath are not in cache,\n check if any parent directory changes are in cache\n '''\n d = os.path.dirname(self.new_datapath)\n '''\n check if any parent dir changes are calculated and cached\n '''\n while d != '/' and d not in cache:\n d = os.path.dirname(d)\n \n '''\n if changes for a matching parent are found,\n then check if oldpath changes are cached \n '''\n if d != '/':\n if self.old_datapath in cache[d]:\n status = CacheStatus.NEW_PARENT_CACHED\n cached_new_path = d\n else:\n for o in cache[d]:\n parent_path = o + os.sep\n if self.old_datapath.startswith(parent_path):\n logger.info('Subdirectory changes can be derived from cache.')\n status = CacheStatus.BOTH_PARENTS_CACHED\n cached_old_path = os.path.abspath(parent_path)\n cached_new_path = d\n break\n\n return status, cached_old_path, cached_new_path\n\n\n '''\n find the high-level changes between two paths\n - if indexed and compared, then just fetch the comparison data\n - else scan and index all the data sets (files/directories) recursively\n '''\n def get_changes(self, cache_status, cached_old_path, cached_new_path):\n logger = logging.getLogger(__name__)\n\n is_subdir_oldpath = False\n is_subdir_newpath = False\n\n logger.info('Checking for changes between %s and %s', self.old_datapath, self.new_datapath)\n\n if cache_status == CacheStatus.NOT_CACHED:\n change_dir = comparator.compare(self.old_datapath, self.new_datapath, self.stagingdir)\n else:\n with open(self.cache_entries, 'r') as f:\n cache = yaml.safe_load(f)\n change_dir = cache[cached_new_path][cached_old_path]\n\n if cached_old_path != self.old_datapath:\n is_subdir_oldpath = True\n \n if cached_new_path != self.new_datapath:\n is_subdir_newpath = True\n \n logger.info('Retrieving changes between %s and %s', self.old_datapath, self.new_datapath)\n \n change = FilesystemChange(cached_old_path, cached_new_path, self.stagingdir)\n\n if is_subdir_newpath:\n indexdir = os.path.join(self.stagingdir, 'indexes', get_hash_id(cached_new_path))\n subdir_nfiles = get_subdir_nfiles(self.new_datapath, indexdir)\n change.new_nfiles = subdir_nfiles\n\n if is_subdir_oldpath:\n indexdir = os.path.join(self.stagingdir, 'indexes', get_hash_id(cached_old_path))\n subdir_nfiles = get_subdir_nfiles(self.old_datapath, indexdir)\n change.old_nfiles = subdir_nfiles\n\n change_data_dir = os.path.join(self.cachedir, change_dir)\n if not (is_subdir_oldpath or is_subdir_newpath):\n set_change_from_cache(change, change_data_dir)\n else:\n compare_hash = dacman_utils.hash_comparison_id(self.old_datapath, self.new_datapath)\n change_data_subdir = os.path.join(self.cachedir, compare_hash)\n if os.path.exists(change_data_subdir):\n set_change_from_cache(change, change_data_subdir)\n else:\n save_subdir_changes_to_cache(change, self.stagingdir,\n cached_old_path, cached_new_path,\n self.old_datapath, self.new_datapath,\n is_subdir_oldpath, is_subdir_newpath,\n change_data_dir, change_data_subdir)\n\n logger.info('Updating change cache entries')\n change_id = dacman_utils.hash_comparison_id(self.old_datapath, self.new_datapath)\n change_info = {self.new_datapath : {self.old_datapath: change_id}}\n dacman_utils.update_yaml(change_info, self.cache_entries)\n\n logger.info('Change retrieval completed')\n\n return change\n\n######################################################################################\n\n'''\nfind the high-level changes between two paths\n- if indexed and compared, then just fetch the comparison data\n- else scan and index all the data sets (files/directories) recursively\n'''\n## deprecated\ndef changes(old_datapath, new_datapath, force=False, custom_stagingdir=None):\n logger = logging.getLogger(__name__)\n\n #old_datapath = os.path.abspath(old_path)\n #new_datapath = os.path.abspath(new_path)\n\n if old_datapath == new_datapath:\n logger.error('Comparison paths are the same')\n sys.exit()\n\n if not custom_stagingdir:\n stagingdir = dacman_utils.DACMAN_STAGING_LOC\n else:\n stagingdir = custom_stagingdir\n\n is_subdir_oldpath = False\n is_subdir_newpath = False\n cached_old_path = old_datapath\n cached_new_path = new_datapath\n\n cachedir = os.path.join(stagingdir, 'cache')\n cache_entries = os.path.join(cachedir, 'ENTRIES')\n\n logger.info('Checking for changes between %s and %s', old_datapath, new_datapath)\n\n '''\n This is the caching logic where change information is saved and subsequently retrieved\n If no high-level diff exists for the data, then do a comparison\n - do the comparison for the all the indexed data\n - at runtime, decide if the comparison is between any subdirectories of the total diff\n '''\n if not os.path.exists(cache_entries) or force:\n logger.info('Cache is empty... starting dataset comparison')\n change_dir = comparator.compare(old_datapath, new_datapath, stagingdir)\n else:\n logger.info('Checking for pre-calculated and cached changes.')\n '''\n if the high-level diff exists, then check if it exists for the two data versions provided here\n '''\n with open(cache_entries, 'r') as f:\n cache = yaml.safe_load(f)\n '''\n if changes for the newpath are in cache, then\n check if they are for the compared oldpath \n '''\n if new_datapath in cache:\n '''\n if the diff paths are already compared, then get the corresponding directory;\n else, do the comparisons/diff\n '''\n if old_datapath in cache[new_datapath]:\n '''\n if both oldpath and newpath are in the cache\n '''\n logger.info('Changes are present in cache... fetching change information.')\n change_dir = cache[new_datapath][old_datapath]\n else:\n '''\n check if the oldpath is a subdirectory of a cached path change\n '''\n for o in cache[new_datapath]:\n parent_path = o + os.sep\n if old_datapath.startswith(parent_path):\n logger.info('Changes can be derived from the cache.')\n change_dir = cache[new_datapath][o]\n cached_old_path = os.path.abspath(parent_path)\n break\n '''\n if the oldpath is neither in cache nor is a subdir of a cache entry,\n then it's a new comparison\n '''\n else:\n logger.info('Changes are not cached... initiating dataset comparison.')\n change_dir = comparator.compare(old_datapath, new_datapath, stagingdir)\n else:\n '''\n if changes for the original newpath are not in cache,\n check if any parent directory changes are in cache\n '''\n d = os.path.dirname(new_datapath)\n '''\n check if any parent dir changes are calculated and cached\n '''\n while d != '/' and d not in cache:\n d = os.path.dirname(d)\n \n '''\n if changes for a matching parent are found,\n then check if oldpath changes are cached \n '''\n if d != '/':\n if old_datapath in cache[d]:\n change_dir = cache[d][old_datapath]\n cached_new_path = d\n else:\n for o in cache[d]:\n parent_path = o + os.sep\n if old_datapath.startswith(parent_path):\n logger.info('Subdirectory changes can be derived from cache.')\n change_dir = cache[d][o]\n cached_old_path = os.path.abspath(parent_path)\n cached_new_path = d\n break\n else:\n logger.info('Changes are not pre-calculated... initiating dataset comparison.')\n change_dir = comparator.compare(old_datapath, new_datapath, stagingdir)\n else:\n '''\n if changes are not present in the cache, then compare\n '''\n logger.info('Changes are not pre-calculated... initiating dataset comparison.')\n change_dir = comparator.compare(old_datapath, new_datapath, stagingdir)\n\n if cached_old_path != old_datapath:\n is_subdir_oldpath = True\n\n if cached_new_path != new_datapath:\n is_subdir_newpath = True\n\n logger.info('Retrieving changes between %s and %s', old_datapath, new_datapath)\n\n #change = FilesystemChange(old_datapath, new_datapath, stagingdir)\n change = FilesystemChange(cached_old_path, cached_new_path, stagingdir)\n\n if is_subdir_newpath:\n indexdir = os.path.join(stagingdir, 'indexes', get_hash_id(cached_new_path))\n subdir_nfiles = get_subdir_nfiles(new_datapath, indexdir)\n change.new_nfiles = subdir_nfiles\n\n if is_subdir_oldpath:\n indexdir = os.path.join(stagingdir, 'indexes', get_hash_id(cached_old_path))\n subdir_nfiles = get_subdir_nfiles(old_datapath, indexdir)\n change.old_nfiles = subdir_nfiles\n\n change_data_dir = os.path.join(cachedir, change_dir)\n #print(change_data_dir)\n if not (is_subdir_oldpath or is_subdir_newpath):\n set_change_from_cache(change, change_data_dir)\n else:\n compare_hash = dacman_utils.hash_comparison_id(old_datapath, new_datapath)\n change_data_subdir = os.path.join(cachedir, compare_hash)\n if os.path.exists(change_data_subdir):\n set_change_from_cache(change, change_data_subdir)\n else:\n save_subdir_changes_to_cache(change, stagingdir,\n cached_old_path, cached_new_path,\n old_datapath, new_datapath,\n is_subdir_oldpath, is_subdir_newpath,\n change_data_dir, change_data_subdir)\n\n logger.info('Updating change cache entries')\n change_id = dacman_utils.hash_comparison_id(old_datapath, new_datapath)\n change_file = os.path.join(cachedir, 'ENTRIES')\n change_info = {new_datapath : {old_datapath: change_id}}\n dacman_utils.update_yaml(change_info, change_file)\n\n logger.info('Change retrieval completed')\n\n return change\n\n\ndef get_subdir_nfiles(datapath, indexdir):\n paths_file = os.path.join(indexdir, 'FILEPATHS')\n datapath_file = os.path.join(indexdir, 'DATAPATH')\n parent_path = ''\n with open(datapath_file) as f:\n parent_path = f.readline().strip()\n\n nfiles = 0\n with open(paths_file) as f:\n for path in f:\n abspath = os.path.join(parent_path, path)\n if abspath.startswith(datapath):\n nfiles += 1\n\n return nfiles\n\n\n'''\nif change is already calculated, just retrieve it\n'''\ndef set_change_from_cache(change, change_dir):\n change_types = {'ADDED': list, 'DELETED': list, \n 'MODIFIED': dict, 'METACHANGE': dict,\n 'UNCHANGED': list}\n change_data = {}\n for change_type in change_types:\n change_file = os.path.join(change_dir, change_type)\n if change_types[change_type] == list:\n with open(change_file, 'r') as f:\n lines = f.readlines()\n change_data[change_type] = [line.strip() for line in lines]\n else:\n with open(change_file, 'r') as f:\n change_dict = {}\n for line in f:\n kv = line.split(':')\n change_dict[kv[0]] = kv[1].strip()\n change_data[change_type] = change_dict\n\n change.add_changes(change_data['ADDED'], change_data['DELETED'],\n change_data['MODIFIED'], change_data['UNCHANGED'],\n change_data['METACHANGE'])\n change.calculate_degree()\n\n metainfo = dacman_utils.load_yaml(os.path.join(change_dir, 'META_INFO'))\n change.old_nfiles = metainfo['base']['nfiles']\n change.new_nfiles = metainfo['revision']['nfiles']\n \n\ndef display(change):\n print(\"File changes in the dataset:\")\n print(\"\\t Additions: {}, Deletions: {}, Modifications: {}, Metadata changes: {}, Unchanged: {}\".\n format(len(change.added),\n len(change.deleted),\n len(change.modified),\n len(change.metachange),\n len(change.unchanged)))\n\n\n'''\nderives subdirectory-level changes from cached parent directory changes\n'''\ndef save_subdir_changes_to_cache(change, stagingdir,\n cached_old_path, cached_new_path,\n old_datapath, new_datapath,\n is_subdir_oldpath, is_subdir_newpath,\n change_dir, change_subdir):\n change_data = {'ADDED': [], 'DELETED': [],\n 'MODIFIED': {}, 'METACHANGE': {},\n 'UNCHANGED': []}\n\n if is_subdir_oldpath and not is_subdir_newpath:\n '''\n if oldpath is a subdir of an indexed path, then mark all the files that are\n not in oldpath as added w.r.t the newpath\n '''\n for change_type in change_data:\n base_change_file = os.path.join(change_dir, change_type)\n if change_type == 'ADDED':\n with open(base_change_file) as f:\n lines = f.readlines()\n change_data[change_type] = [line.strip() for line in lines]\n elif change_type == 'DELETED':\n with open(base_change_file) as f:\n for line in f:\n path = os.path.join(cached_old_path, line.strip())\n if path.startswith(old_datapath):\n rel_subpath = os.path.relpath(path, old_datapath) \n change_data[change_type].append(rel_subpath)\n lines = f.readlines()\n change_data[change_type] = [line.strip() for line in lines]\n elif change_type == 'UNCHANGED':\n with open(base_change_file) as f:\n for line in f:\n path = os.path.join(cached_old_path, line.strip())\n if path.startswith(old_datapath):\n '''\n there's nothing unchanged anymore, everything is metachange\n because the directory depths have changed and so have the relative\n file paths\n '''\n rel_subpath = os.path.relpath(path, old_datapath) \n change_data['METACHANGE'][line.strip()] = rel_subpath\n else:\n change_data['ADDED'].append(line.strip())\n elif change_type == 'METACHANGE':\n with open(base_change_file) as f:\n for line in f:\n kv = line.split(':')\n path = os.path.join(cached_old_path, kv[1].strip())\n if path.startswith(old_datapath):\n rel_subpath = os.path.relpath(path, old_datapath)\n if kv[0] == rel_subpath: # if the filepath is now at the same level, then unchanged\n change_data['UNCHANGED'].append(rel_subpath)\n else:\n change_data[change_type][kv[0]] = rel_subpath\n else:\n change_data['ADDED'].append(kv[0]) \n else:\n with open(base_change_file) as f:\n for line in f:\n kv = line.split(':')\n path = os.path.join(cached_old_path, kv[1].strip())\n if path.startswith(old_datapath):\n rel_subpath = os.path.relpath(path, old_datapath)\n change_data[change_type][kv[0]] = rel_subpath\n else:\n change_data['ADDED'].append(kv[0])\n elif not is_subdir_oldpath and is_subdir_newpath:\n '''\n if newpath is a subdir of an indexed path, then mark all the files that are\n not in newpath as deleted\n '''\n for change_type in change_data:\n base_change_file = os.path.join(change_dir, change_type)\n if change_type == 'ADDED':\n with open(base_change_file) as f:\n for line in f:\n path = os.path.join(cached_new_path, line.strip())\n if path.startswith(new_datapath):\n rel_subpath = os.path.relpath(path, new_datapath) \n change_data[change_type].append(rel_subpath) \n elif change_type == 'DELETED':\n with open(base_change_file) as f:\n lines = f.readlines()\n change_data[change_type] = [line.strip() for line in lines]\n elif change_type == 'UNCHANGED':\n with open(base_change_file) as f:\n for line in f:\n orig_path = line.strip()\n path = os.path.join(cached_new_path, orig_path)\n if path.startswith(new_datapath):\n #change_data[change_type].append(rel_subpath)\n rel_subpath = os.path.relpath(path, new_datapath)\n change_data['METACHANGE'][rel_subpath] = orig_path\n else:\n change_data['DELETED'].append(orig_path)\n elif change_type == 'METACHANGE':\n with open(base_change_file) as f:\n for line in f:\n kv = line.split(':')\n path = os.path.join(cached_new_path, kv[0])\n old_path = kv[1].strip()\n if path.startswith(new_datapath):\n rel_subpath = os.path.relpath(path, new_datapath)\n if rel_subpath == old_path:\n change_data['UNCHANGED'].append(rel_subpath)\n else:\n change_data[change_type][rel_subpath] = old_path\n else:\n change_data['DELETED'].append(old_path) \n else:\n with open(base_change_file) as f:\n for line in f:\n kv = line.split(':')\n path = os.path.join(cached_new_path, kv[0])\n if path.startswith(new_datapath):\n rel_subpath = os.path.relpath(path, new_datapath)\n change_data[change_type][rel_subpath] = kv[1].strip()\n else:\n change_data['DELETED'].append(kv[1].strip())\n else:\n '''\n if both oldpath and newpath are subdirs, then only compare the\n files that match both the paths\n '''\n for change_type in change_data:\n base_change_file = os.path.join(change_dir, change_type)\n if change_type == 'ADDED':\n with open(base_change_file) as f:\n for line in f:\n path = os.path.join(cached_new_path, line.strip())\n if path.startswith(new_datapath):\n rel_subpath = os.path.relpath(path, new_datapath)\n change_data[change_type].append(rel_subpath)\n elif change_type == 'DELETED':\n with open(base_change_file) as f:\n for line in f:\n path = os.path.join(cached_old_path, line.strip())\n if path.startswith(old_datapath):\n rel_subpath = os.path.relpath(path, new_datapath)\n change_data[change_type].append(rel_subpath)\n elif change_type == 'UNCHANGED':\n with open(base_change_file) as f:\n for line in f:\n orig_path = line.strip()\n path = os.path.join(cached_new_path, orig_path)\n old_path = os.path.join(cached_old_path, orig_path)\n if path.startswith(new_datapath): # if the path is in new_datapath\n rel_subpath = os.path.relpath(path, new_datapath)\n if old_path.startswith(old_datapath): # if the path is in old_datapath\n rel_old_subpath = os.path.relpath(old_path, old_datapath)\n # if the two relative paths are same, then unchanged\n if rel_subpath == rel_old_subpath: \n change_data[change_type].append(rel_subpath) \n else:\n change_data['METACHANGE'][rel_subpath] = rel_old_subpath\n else:\n change_data['ADDED'].append(rel_subpath)\n elif old_path.startswith(old_datapath): # if the path is not in new_datapath, but in old_datapath\n rel_old_subpath = os.path.relpath(old_path, old_datapath)\n change_data['DELETED'].append(rel_old_subpath)\n elif change_type == 'METACHANGE':\n with open(base_change_file) as f:\n for line in f:\n kv = line.split(':')\n orig_new_path = kv[0]\n orig_old_path = kv[1].strip()\n path = os.path.join(cached_new_path, orig_new_path)\n old_path = os.path.join(cached_old_path, orig_old_path)\n if path.startswith(new_datapath):\n rel_subpath = os.path.relpath(path, new_datapath)\n if old_path.startswith(old_datapath):\n rel_old_subpath = os.path.relpath(old_path, old_datapath)\n if rel_subpath == rel_old_subpath:\n change_data['UNCHANGED'].append(rel_subpath)\n else:\n change_data[change_type][rel_subpath] = rel_old_subpath\n else:\n change_data['ADDED'].append(rel_subpath)\n elif old_path.startswith(old_datapath):\n rel_old_subpath = os.path.relpath(old_path, old_datapath)\n change_data['DELETED'].append(rel_old_subpath)\n else:\n with open(base_change_file) as f:\n for line in f:\n kv = line.split(':')\n orig_new_path = kv[0]\n orig_old_path = kv[1].strip()\n path = os.path.join(cached_new_path, orig_new_path)\n old_path = os.path.join(cached_old_path, orig_old_path)\n if path.startswith(new_datapath):\n rel_subpath = os.path.relpath(path, new_datapath)\n if old_path.startswith(old_datapath):\n rel_old_subpath = os.path.relpath(old_path, old_datapath) \n change_data[change_type][rel_subpath] = rel_old_subpath\n else:\n change_data['ADDED'].append(rel_subpath)\n elif old_path.startswith(old_datapath):\n rel_old_subpath = os.path.relpath(old_path, old_datapath)\n change_data['DELETED'].append(rel_old_subpath)\n \n _ufile = os.path.join(change_subdir, 'UNCHANGED')\n _afile = os.path.join(change_subdir, 'ADDED')\n _dfile = os.path.join(change_subdir, 'DELETED')\n _mfile = os.path.join(change_subdir, 'MODIFIED')\n _mcfile = os.path.join(change_subdir, 'METACHANGE')\n \n #print(\"CHANGEDIR: {}, CHANGESUBDIR: {}\".format(change_dir, change_subdir))\n os.mkdir(change_subdir)\n\n dacman_utils.list_to_file(change_data['UNCHANGED'], _ufile)\n dacman_utils.list_to_file(change_data['ADDED'], _afile)\n dacman_utils.list_to_file(change_data['DELETED'], _dfile)\n dacman_utils.dict_to_file(change_data['MODIFIED'], _mfile)\n dacman_utils.dict_to_file(change_data['METACHANGE'], _mcfile)\n\n _meta_info = {'base': {'dataset_id': old_datapath,\n 'nfiles': change.old_nfiles},\n 'revision': {'dataset_id': new_datapath,\n 'nfiles': change.new_nfiles}}\n _metafile = os.path.join(change_subdir, 'META_INFO')\n dacman_utils.dump_yaml(_meta_info, _metafile)\n\n change.add_changes(change_data['ADDED'], change_data['DELETED'],\n change_data['MODIFIED'], change_data['UNCHANGED'],\n change_data['METACHANGE'])\n change.calculate_degree()\n\n \ndef main(args):\n oldpath = os.path.abspath(args.oldpath)\n newpath = os.path.abspath(args.newpath)\n stagingdir = args.stagingdir\n force = args.force\n\n #change = changes(oldpath, newpath, force, stagingdir)\n changeManager = ChangeManager(oldpath, newpath, force, stagingdir)\n status, cached_old_path, cached_new_path = changeManager.get_cached_paths()\n change = changeManager.get_changes(status, cached_old_path, cached_new_path)\n display(change)\n\ndef s_main(args):\n oldpath = args['oldpath']\n newpath = args['newpath']\n stagingdir = args['stagingdir']\n\n change = changes(oldpath, newpath, stagingdir)\n display(change)\n\nif __name__ == '__main__':\n args = {'oldpath': sys.argv[1], 'newpath': sys.argv[2]}\n\n s_main(args)\n","repo_name":"deduce-dev/dac-man","sub_path":"dacman/core/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":34859,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"25549527054","text":"# -*- coding: utf-8 -*-\nfrom resource_management.core.logger import Logger\nfrom resource_management.core.resources.system import Execute\nfrom resource_management.libraries.functions import format\nfrom resource_management.libraries.functions.check_process_status import check_process_status\nfrom jupyter_base import JupyterBase\n\n\nclass JupyterHub(JupyterBase):\n # Call setup.sh to install the service\n def install(self, env):\n\n # Install packages listed in metainfo.xml\n self.install_jupyter(env)\n\n def configure(self, env):\n self.configure_jupyter(env)\n\n # Call start.sh to start the service\n def start(self, env):\n self.configure(env)\n\n import params\n env.set_params(params)\n Execute('echo \"Ready to start jupyterhub\"')\n ## run jupyterhub background\n Execute(format(\"sudo mkdir -p {jupyterhub_pid_path} && username=`whoami` && sudo chown -R $username:$username {jupyter_install_path}\"))\n cmd = format(\"source /etc/profile && cd {jupyter_install_path} && nohup conda run -n {conda_jupyter_env_name} jupyterhub --config {jupyterhub_conf_path}/{jupyterhub_conf_name} > /dev/null 2>&1 &\")\n Execute('echo \"Running cmd: ' + cmd + '\"')\n Execute(cmd)\n Execute('echo \"Start jupyterhub finish\"')\n\n # Called to stop the service using the pidfile\n def stop(self, env):\n import params\n env.set_params(params)\n Execute('echo \"Ready to stop jupyterhub\"')\n cmd = format(\"test -e {jupyterhub_pid_path}/{jupyterhub_pid_name} && cat {jupyterhub_pid_path}/jupyterhub.pid | xargs --no-run-if-empty kill -9\")\n cmd = format(\"ps -ef | grep '{conda_jupyter_env_name}'\") + \" | grep -v grep | awk '{print $2}' | xargs --no-run-if-empty kill -9\"\n Execute(cmd)\n cmd = format(\"ps -ef | grep '{configurable_http_proxy_name}'\") + \" | grep -v grep | awk '{print $2}' | xargs --no-run-if-empty kill -9\"\n Execute(cmd)\n Execute('echo \"Stop jupyterhub finish\"')\n\n # Called to get status of the service using the pidfile\n def status(self, env):\n check_process_status(\"/home/modules/jupyterhub/pid/jupyterhub.pid\")\n\nif __name__ == \"__main__\":\n JupyterHub().execute()\n","repo_name":"smiecj/AmbariStack","sub_path":"JUPYTER/package/scripts/jupyter-hub.py","file_name":"jupyter-hub.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2248510422","text":"from wsgiref.simple_server import make_server\nfrom wsgiref.headers import Headers\n\ndef echo_wsgi_app(environ, start_response):\n try:\n request_body_size = int(environ.get('CONTENT_LENGTH', 0))\n except ValueError:\n request_body_size = 0\n \n request_body = environ['wsgi.input'].read(request_body_size)\n\n start_response('200 OK', [('Content-Type', 'text/plain')])\n return [request_body]\n\nclass APIKeyAuthenticationMiddleware:\n API_KEY = 'test123'\n API_KEY_HEADER = 'X-APIKey'\n \n def __init__(self, app):\n self.app = app\n self.headers = []\n\n def __call__(self, environ, start_response):\n self.parse_headers(environ)\n\n if not self.is_authorized():\n start_response('401 Unauthorized', [])\n return []\n\n return self.app(environ, start_response)\n\n def parse_headers(self, environ):\n self.headers = Headers([])\n for k, v in environ.items():\n if 'HTTP' in k:\n key = k.replace('HTTP_', '').lower().replace('_', '-')\n self.headers[key] = v\n \n def is_authorized(self):\n return self.API_KEY_HEADER in self.headers and self.headers[self.API_KEY_HEADER] == self.API_KEY\n\nif __name__ == \"__main__\":\n server = make_server('localhost', 1337, APIKeyAuthenticationMiddleware(echo_wsgi_app))\n server.serve_forever()","repo_name":"emdeha/advanced-python-training","sub_path":"practice-3.2/echo_server.py","file_name":"echo_server.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"73317346085","text":"from flask import Blueprint, request, jsonify, abort\n\nfrom ..models.commentaire import Commentaire\nfrom ..models.personne import Personne\nfrom ..models.publication import Publication\n\ncommentaire_bp = Blueprint(\"commentaire_bp\", __name__, url_prefix=\"/commentaires\")\n\n\n@commentaire_bp.route('/', methods=['POST'])\ndef create():\n body = request.get_json()\n\n texte_com = body.get('texteCom', None)\n lien_photo = body.get('lienPhoto', None)\n client_id = body.get('client_id', None)\n publication_id = body.get('publication_id', None)\n checked_person = Personne.query.get(client_id)\n checked_post = Publication.query.get(publication_id)\n\n if checked_person is None and checked_post is None:\n return jsonify({\n \"status\": 404,\n \"message\": \"Person or Publication was not found\"\n })\n\n commentaire = Commentaire(client=client_id, publication=publication_id, commentaire=texte_com, photo=lien_photo)\n\n commentaire.insert()\n\n return jsonify(\n {\n 'status': 200,\n 'commentaire': commentaire.commentaire_format()\n }\n )\n\n\n@commentaire_bp.route(\"//update\", methods=['PATCH'])\ndef update(id):\n commentaire = Commentaire.query.get(id)\n if commentaire is None:\n abort(404)\n else:\n try:\n body = request.get_json()\n commentaire.texteCom = body.get('texteCom')\n commentaire.lienPhoto = body.get('lienPhoto')\n commentaire.update()\n\n return jsonify(\n {\n 'commentaire': commentaire.commentaire_format()\n }\n )\n except:\n abort(406)\n\n\n@commentaire_bp.route(\"//delete\", methods=['DELETE'])\ndef delete(id):\n commentaire = Commentaire.query.get(id)\n if commentaire is None:\n abort(404)\n else:\n commentaire.delete()\n return {\n 'message': 'Commentaire supprimé avec succès'\n }\n","repo_name":"DarkBrain-LP/oevenement-flask","sub_path":"o_evmt/routes/commentaire.py","file_name":"commentaire.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30247332471","text":"from typing import Sequence\n\nfrom torch import Tensor, nn\n\nfrom vital.metrics.train.functional import (\n differentiable_dice_score,\n monotonic_regularization_loss,\n ntxent_loss,\n rbf_kernel,\n)\n\n\nclass DifferentiableDiceCoefficient(nn.Module):\n \"\"\"Computes a differentiable version of the dice coefficient.\"\"\"\n\n def __init__(\n self,\n include_background: bool = False,\n nan_score: float = 0.0,\n no_fg_score: float = 0.0,\n reduction: str = \"elementwise_mean\",\n ):\n \"\"\"Initializes class instance.\n\n Args:\n include_background: Whether to also compute dice for the background.\n nan_score: Score to return, if a NaN occurs during computation (denom zero).\n no_fg_score: Score to return, if no foreground pixel was found in target.\n reduction: Method for reducing metric score over labels.\n Available reduction methods:\n - ``'elementwise_mean'``: takes the mean (default)\n - ``'none'``: no reduction will be applied\n \"\"\"\n super().__init__()\n self.include_background = include_background\n self.nan_score = nan_score\n self.no_fg_score = no_fg_score\n assert reduction in (\"elementwise_mean\", \"none\")\n self.reduction = reduction\n\n def forward(self, input: Tensor, target: Tensor) -> Tensor:\n \"\"\"Actual metric calculation.\n\n Args:\n input: (N, C, H, W), Raw, unnormalized scores for each class.\n target: (N, H, W), Groundtruth labels, where each value is 0 <= targets[i] <= C-1.\n\n\n Return:\n (1,) or (C,), Calculated dice coefficient, averaged or by labels.\n \"\"\"\n return differentiable_dice_score(\n input=input,\n target=target,\n bg=self.include_background,\n nan_score=self.nan_score,\n no_fg_score=self.no_fg_score,\n reduction=self.reduction,\n )\n\n\nclass MonotonicRegularizationLoss(nn.Module):\n \"\"\"Computes a regularization loss that enforces a monotonic relationship between the input and target.\n\n Notes:\n - This is a generalization of the attribute regularization loss proposed by the AR-VAE\n (link to the paper: https://arxiv.org/pdf/2004.05485.pdf)\n \"\"\"\n\n def __init__(self, delta: float):\n \"\"\"Initializes class instance.\n\n Args:\n delta: Hyperparameter that decides the spread of the posterior distribution.\n \"\"\"\n super().__init__()\n self.delta = delta\n\n def forward(self, input: Tensor, target: Tensor) -> Tensor:\n \"\"\"Actual metric calculation.\n\n Args:\n input: Input values to regularize so that they have a monotonic relationship with the `target` values.\n target: Values used to determine the target monotonic ordering of the values.\n\n Returns:\n (1,), Calculated monotonic regularization loss.\n \"\"\"\n return monotonic_regularization_loss(input, target, self.delta)\n\n\nclass NTXent(nn.Module):\n \"\"\"Computes the NT-Xent loss for contrastive learning.\"\"\"\n\n def __init__(self, temperature=1.0):\n \"\"\"Initializes class instance.\n\n Args:\n temperature: Scaling factor of the similarity metric.\n \"\"\"\n super().__init__()\n self.temperature = temperature\n\n def forward(self, z_i: Tensor, z_j: Tensor):\n \"\"\"Actual metric calculation.\n\n Args:\n z_i: (N, E), Embedding of one view of the input data.\n z_j: (N, E), Embedding of the other view of the input data.\n\n Return:\n (1,), Calculated NT-Xent loss.\n \"\"\"\n return ntxent_loss(z_i, z_j, temperature=self.temperature)\n\n\nclass RBFKernel(nn.Module):\n \"\"\"Computes the Radial Basis Function kernel (aka Gaussian kernel).\"\"\"\n\n def __init__(self, length_scale: float | Sequence[float] | Tensor = 1):\n \"\"\"Initializes class instance.\n\n Args:\n length_scale: length_scale: (1,) or (E,), The length-scale of the kernel. If a float, an isotropic kernel is\n used. If a Sequence or Tensor, an anisotropic kernel is used to define the length-scale of each feature\n dimension.\n \"\"\"\n super().__init__()\n self.length_scale = length_scale\n\n def forward(self, x1: Tensor, x2: Tensor = None) -> Tensor:\n \"\"\"Actual kernel calculation.\n\n Args:\n x1: (M, E), Left argument of the returned kernel k(x1,x2).\n x2: (N, E), Right argument of the returned kernel k(x1,x2). If None, uses `x2=x1`,\n which ends up evaluating k(x1,x1).\n\n Returns:\n (N, M), The kernel k(x1,x2).\n \"\"\"\n return rbf_kernel(x1, x2=x2, length_scale=self.length_scale)\n","repo_name":"vitalab/vital","sub_path":"vital/metrics/train/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"1922111108","text":"import random\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import accuracy_score\r\n\r\ndef assgin(flower):\r\n data = pd.read_csv('Iris/iris.csv', header=None)\r\n y = []\r\n x = []\r\n \r\n # FLOWER INPUT WILL BE ASSIGNED AS 1, THE REST WILL BE ASSIGNED AS 0\r\n for i in range(0, len(data)):\r\n arr = [data[0][i], data[1][i], data[2][i], data[3][i]]\r\n x.append(arr)\r\n if data[4][i] == flower:\r\n y.append([1])\r\n else:\r\n y.append([0])\r\n\r\n attributes = np.array(x)\r\n labels = np.array(y)\r\n\r\n return attributes, labels\r\n\r\nclass NeuralNetwork:\r\n def __init__(self, layers,flower):\r\n self.x, self.y = assgin(flower)\r\n self.layers = layers \r\n self.W = []\r\n self.b = []\r\n\r\n # GENERATE WEIGHT AND BIAS\r\n for i in range(0, len(self.layers)-1):\r\n w_ = np.random.randn(self.layers[i], self.layers[i+1])\r\n b_ = np.ones((self.layers[i+1], 1))\r\n self.W.append(w_/self.layers[i])\r\n self.b.append(b_)\r\n\r\n def sigmoid(self, z):\r\n return 1/(1 + np.exp(-z))\r\n\r\n def feedFoward(self, preLayer, i):\r\n return self.sigmoid(np.dot(preLayer, self.W[i]) + (self.b[i].T))\r\n\r\n def derivative(self,x):\r\n return x*(1-x)\r\n\r\n # LOSS FUNCTION\r\n def calculate_loss(self, X, y):\r\n y_predict = self.predict(X)\r\n return -(np.sum(y*np.log(y_predict) + (1-y)*np.log(1-y_predict))) \r\n\r\n def train(self, X, y, lr):\r\n data = [X]\r\n\r\n # FEEDFORWARD\r\n oldLayer = data[0]\r\n for i in range(0, len(self.layers) - 1):\r\n newLayer = self.feedFoward(oldLayer, i)\r\n data.append(newLayer)\r\n oldLayer = newLayer\r\n\r\n # BACKPROPAGATION \r\n dL = [-(y/data[-1] - (1-y)/(1-data[-1]))] #Đạo Hàm Loss\r\n dW = []\r\n db = []\r\n\r\n for i in reversed(range(0, len(self.layers)-1)):\r\n dw_ = np.dot((data[i]).T, dL[-1] * self.derivative(data[i+1]))\r\n db_ = (np.sum(dL[-1] * self.derivative(data[i+1]), 0)).reshape(-1,1)\r\n dL_ = np.dot(dL[-1] * self.derivative(data[i+1]), self.W[i].T)\r\n dW.append(dw_)\r\n db.append(db_)\r\n dL.append(dL_)\r\n \r\n # Đảo ngược dW, db\r\n dW = dW[::-1]\r\n db = db[::-1]\r\n \r\n\t\t# Gradient descent\r\n for i in range(0, len(self.layers)-1):\r\n self.W[i] = self.W[i] - lr * dW[i]\r\n self.b[i] = self.b[i] - lr * db[i]\r\n \r\n def start(self, epochs, lr):\r\n for _ in range(epochs):\r\n self.train(self.x, self.y, lr) \r\n \r\n\r\n # PREDICT OUTPUT\r\n def predict(self, X):\r\n for i in range(0, len(self.layers) - 1):\r\n X = self.feedFoward(X, i)\r\n return X\r\n\r\n def accuracy(self):\r\n res = []\r\n for i in range(len(self.predict(self.x))):\r\n if self.predict(self.x)[i] >= 0.5:\r\n res.append([1])\r\n else:\r\n res.append([0])\r\n res = np.array(res)\r\n return round(accuracy_score(res,self.y)*100, 3)\r\n\r\n def accuracy2(self):\r\n res = 0\r\n for i in range(len(self.predict(self.x))):\r\n if int(self.predict(self.x)[i] + 0.5) == self.y[i]:\r\n res += 1\r\n return round(res/len(self.y), 4) * 100\r\n\r\n\r\n\r\n\r\n","repo_name":"Hieu087/Iris-classification","sub_path":"Classes/neuralnetwork.py","file_name":"neuralnetwork.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34382736718","text":"import sys, time, os\nimport numpy as np\nimport pytest\nimport mock\n\n#sys.path.append(os.path.join(os.path.dirname(__file__), '../../src'))\n\nfrom libensemble.libE import check_inputs, libE\nimport libensemble.tests.unit_tests.setup as setup\nfrom mpi4py import MPI\n\nal = {}\nlibE_specs = {'comm':MPI.COMM_WORLD}\nfname_abort = 'libE_history_at_abort_0.npy'\n\n\ndef test_manager_exception():\n try:\n os.remove(fname_abort)\n except OSError as e:\n pass\n with mock.patch('libensemble.libE.manager_main') as managerMock:\n managerMock.side_effect = Exception\n with mock.patch('libensemble.libE.comms_abort') as abortMock:\n abortMock.side_effect = Exception\n with pytest.raises(Exception, message='Expected exception'):\n libE({'out':[('f',float)]},{'out':[('x',float)]},{'sim_max':1},libE_specs={'comm': MPI.COMM_WORLD})\n # Check npy file dumped\n assert os.path.isfile(fname_abort), \"History file not dumped\"\n os.remove(fname_abort)\n\n\ndef test_exception_raising_manager():\n # Intentionally running without sim_specs['in'] to test exception raising (Fails)\n with mock.patch('libensemble.libE.comms_abort') as abortMock:\n abortMock.side_effect = Exception\n with pytest.raises(Exception, message='Expected exception'):\n H,_,_ = libE({'out':[('f',float)]},{'out':[('x',float)]},{'sim_max':1},libE_specs={'comm': MPI.COMM_WORLD})\n\n\n# def test_exception_raising_worker():\n# # Intentionally running without sim_specs['in'] to test exception raising (Fails)\n# H,_,_ = libE({'out':[('f',float)]},{'out':[('x',float)]},{'sim_max':1},libE_specs={'comm': MPI.COMM_WORLD})\n# assert H==[]\n\ndef test_checking_inputs():\n\n # Don't take more points than there is space in history.\n sim_specs, gen_specs, exit_criteria = setup.make_criteria_and_specs_0()\n\n H0 = np.zeros(3,dtype=sim_specs['out'] + gen_specs['out'] + [('returned',bool)])\n # Should fail because H0 has points with 'return'==False\n try:\n check_inputs(libE_specs,al, sim_specs, gen_specs, exit_criteria,H0)\n except AssertionError:\n assert 1\n else:\n assert 0\n\n # Should not fail\n H0['returned']=True\n check_inputs(libE_specs,al, sim_specs, gen_specs, exit_criteria,H0)\n\n # Removing 'returned' and then testing again.\n H0 = rmfield( H0, 'returned')\n check_inputs(libE_specs,al, sim_specs, gen_specs, exit_criteria,H0)\n\n # Should fail because H0 has fields not in H\n H0 = np.zeros(3,dtype=sim_specs['out'] + gen_specs['out'] + [('bad_name',bool),('bad_name2',bool)])\n try:\n check_inputs(libE_specs,al, sim_specs, gen_specs, exit_criteria,H0)\n except AssertionError:\n assert 1\n else:\n assert 0\n\ndef rmfield( a, *fieldnames_to_remove ):\n return a[ [ name for name in a.dtype.names if name not in fieldnames_to_remove ] ]\n\nif __name__ == \"__main__\":\n test_manager_exception()\n test_exception_raising_manager()\n test_checking_inputs()\n","repo_name":"rsln-s/libensemble_var","sub_path":"libensemble/tests/unit_tests/test_libE_main.py","file_name":"test_libE_main.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7075562088","text":"# Uses python3\nimport sys\n\ndef get_change(m):\n denominations = [10, 5, 1]\n\n change = 0\n\n for deno in denominations:\n\n remain = m//deno\n change += remain\n m = m - (remain*deno)\n return change\n\nif __name__ == '__main__':\n m = int(872365)\n print(get_change(m))\n","repo_name":"Saij84/AlgorithmicToolbox","sub_path":"toolbox/week3_greedy_algorithms/1_money_change/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70028892324","text":"from scipy.signal import savgol_filter\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom FTIR_Pretreatment import sg\r\n\r\n#The result shows that window_size=51, polynomial_order=3 works well\r\n\r\nfilename = 'D://正常细胞与癌细胞分类//光谱法//实验数据//FTIR//FTIR总数据//A549//X-A-5.CSV'\r\ndf1 = pd.read_csv(filename,header=None,names=['wave','Absorb'])\r\n\r\nY0 = df1['wave']\r\nX0 = df1['Absorb']\r\nx=np.array(Y0)\r\ny=np.array(X0)\r\n\r\nfor window_size in range(9,99,2):\r\n for polynomial_order in range(1,4,1):\r\n zs1=sg(y, window_size, polynomial_order)\r\n plt.figure()\r\n plt.plot(x,y,color='red',lw=0.5)\r\n plt.title('Savitzky-Golay'+'-'+str(window_size)+'-'+str(polynomial_order))\r\n plt.plot(x,zs1,color='green',lw=0.5)\r\n # plt.show()\r\n plt.savefig('D://正常细胞与癌细胞分类//光谱法//实验数据//FTIR//FTIR总数据//SG平滑实验结果//'+'Savitzky-Golay'+\\\r\n '-'+str(window_size)+'-'+str(polynomial_order)+'.jpg')","repo_name":"tiankongnanhai/FTIL-FL-algorithm","sub_path":"SG_smoothing_experiment.py","file_name":"SG_smoothing_experiment.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"32684036601","text":"import numpy as np\n\ndef diagLog(D, c):\n \"\"\"\n Computes log of a diagonal matrix\n Add constant displacement c if necessary\n \"\"\"\n \n if c is None:\n c = 0\n \n M, N = D.shape\n \n L = np.zeros(D.shape)\n \n m = np.minimum(M, N)\n \n L[0:m, 0:m] = np.diag(np.log(np.diag(D) + c))\n \n return L\n","repo_name":"svmakarychev/GMML_project","sub_path":"SPDNet/spdnet/utils/diagLog.py","file_name":"diagLog.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"533654159","text":"\nclass Node:\n\tdef __init__(self, valor):\n\t\tself.valor = valor\n\t\tself.esquerda = None\n\t\tself.direita = None\n\t\tself.color = None\n\nclass AVL:\n\n\tdef __init__(self, *args):\n\t\tself.node = None\n\t\n\tdef redefineSubArvores(self, esquerda, direita):\n\t\tself.node.esquerda = esquerda\n\t\tself.node.direita = direita\n\n\tdef inserirRB(self, valor):\n\t\tno = Node(valor)\n\t\tif not self.node:\n\t\t\tself.node = no\n\t\t\tself.node.esquerda = AVL()\n\t\t\tself.node.direita = AVL()\n\t\telif self.node.valor > valor:\n\t\t\tself.node.esquerda.inserirRB(valor)\n\t\telse:\n\t\t\tself.node.direita.inserirRB(valor)\t\n\n\tdef buscaRB(self, busca):\n\t\tif not self.node:\n\t\t\tprint(\"Valor não foi encontrado\")\n\t\t\treturn None\t\n\t\telif self.node.valor > busca:\n\t\t\tself.node.esquerda.buscaRB(busca)\n\t\telif self.node.valor < busca :\n\t\t\tself.node.direita.buscaRB(busca)\n\t\telse:\n\t\t\tprint(\"Valor foi encontrado\")\n\t\t\treturn self\t\t\n\n\tdef encontraNovoValor(self, node):\n\t\tif self.node.esquerda.node == None:\n\t\t\treturn node\n\t\telse:\n\t\t\tnode = self.node.esquerda.node\n\t\t\treturn node\t\t\t\t\n\n\tdef removeRB(self, valor):\n\t\tif self.node is None:\n\t\t\tprint(\"Valor não foi encontrado para remoção\")\n\t\t\treturn None\t\n\t\telif self.node.valor > valor:\n\t\t\tself.node.esquerda.removeRB(valor)\n\t\telif self.node.valor < valor:\n\t\t\tself.node.direita.removeRB(valor)\n\t\telse:\n\t\t\tprint(\"Valor foi encontrado... removendo...\")\n\t\t\tif self.node.direita.node is None and self.node.esquerda.node is None:\n\t\t\t\tself.node = None\n\t\t\telif not self.node.direita.node:\n\t\t\t\tself.node= self.node.esquerda.node\n\t\t\telif not self.node.esquerda.node:\n\t\t\t\tself.node = self.node.direita.node\n\t\t\telse:\n\t\t\t\ttemp = self.encontraNovoValor(self.node)\n\t\t\t\tprint(temp.valor)\n\t\t\t\tif temp:\n\t\t\t\t\tself.node.valor = temp.valor\t\n\t\t\t\tself.node.esquerda.removeRB(temp.valor)\n\n\tdef fator(self):\n\t\tpEsq = 0\n\t\tpDir = 0\n\t\tif self.node:\n\t\t\tpEsq = self.node.esquerda.calculaProfundidade()\n\t\t\tpDir = self.node.direita.calculaProfundidade()\n\t\treturn pDir - pEsq\n\n\tdef calculaProfundidade(self):\n\t\tpEsq = 0\n\t\tpDir = 0\n\t\tif self.node:\n\t\t\tpEsq = self.node.esquerda.calculaProfundidade()\n\t\t\tpDir = self.node.direita.calculaProfundidade()\n\t\tresultado = max(pEsq, pDir) + 1\n\t\treturn resultado\n\n\tdef executaBalanceamento(self):\n\t\tbal = self.fator()\n\n\t\tif bal > 1:\n\t\t\tif self.node.esquerda.fator() < 0:\n\t\t\t\tprint(\"Rotacionando à esquerda\\n\")\n\t\t\t\tself.RE()\n\t\t\telse:\n\t\t\t\tprint(\"Rotacionando duplamente à esquerda\\n\")\n\t\t\t\tself.RDE()\n\t\telif bal < -1:\n\t\t\tif self.node.direita.fator() > 0:\n\t\t\t\tprint(\"Rotacionando à direita\\n\")\n\t\t\t\tself.RD()\n\t\t\telse:\n\t\t\t\tprint(\"Rotacionando duplamente à direita\\n\")\n\t\t\t\tself.RDD()\n\t\t\n\t\tbal = self.fator()\n\t\t\t\t\n\t\tif bal > 1:\n\t\t\tself.executaBalanceamento()\n\t\tif bal < -1:\n\t\t\tself.executaBalanceamento()\t\t\n\n\tdef RE(self):\n\t\tanteriorEsq = self.node.esquerda\n\t\tself.node.valor, self.node.direita.node.valor = self.node.direita.node.valor, self.node.valor\n\t\tself.redefineSubArvores(self.node.direita, self.node.direita.node.direita)\n\t\tself.node.esquerda.redefineSubArvores(anteriorEsq, self.node.esquerda.node.esquerda)\n\n\tdef RD(self):\n\t\tanteriorDir = self.node.direita\n\t\tself.node.valor, self.node.esquerda.node.valor = self.node.esquerda.node.valor, self.node.valor\n\t\tself.redefineSubArvores(self.node.esquerda.node.esquerda, self.node.esquerda)\n\t\tself.node.direita.redefineSubArvores(self.node.direita.node.direita, anteriorDir)\n\n\tdef RDE(self):\n\t\tself.node.direita.RD()\n\t\tself.RE()\n\n\tdef RDD(self): \n\t\tself.node.esquerda.RE()\n\t\tself.RD()\n\n\tdef imprimir(self, espaco = 0): # Imprime uma árvore rotacionada 90º no sentido anti-horário\n\t\tif self.node:\n\t\t\tself.node.direita.imprimir(espaco + 2)\n\t\t\tprint(\" \" * espaco + str(self.node.valor))\n\t\t\tself.node.esquerda.imprimir(espaco + 2)\n\n\tdef remocao(self, valor):\n\t\tself.removeRB(valor)\n\t\tself.executaBalanceamento()\n\n\tdef colorirArvore(self, raiz):\n\t\tif self.node.valor == raiz:\n\t\t\tself.node.color = \"N\"\n\t\telif self.node.esquerda.node and self.node.esquerda.node.color == \"R\":\n\t\t\tself.node.color = \"N\"\t\t\n\t\telif self.node.direita.node and self.node.direita.node.color == \"R\":\n\t\t\tself.node.color = \"N\"\n\t\telse :\n\t\t\tself.node.color = \"R\"\t\n\t\t\n\t\tif self.node.esquerda.node:\n\t\t\tself.node.esquerda.colorirArvore(raiz)\n\t\tif self.node.direita.node:\n\t\t\tself.node.direita.colorirArvore(raiz)\n\t\n\n\n\tdef imprimirRB(self, espaco = 0): # Imprime uma árvore pintada rotacionada 90º no sentido anti-horário\n\t\tif self.node:\n\t\t\tself.node.direita.imprimirRB(espaco + 2)\n\t\t\tprint(\" \" * espaco + str(self.node.color))\n\t\t\tself.node.esquerda.imprimirRB(espaco + 2)\n\ndef main():\n\tavl = AVL()\n\traiz = 5\n\tavl.inserirRB(raiz)\n\tavl.inserirRB(3)\n\tavl.inserirRB(1)\n\tavl.inserirRB(2)\n\tavl.inserirRB(-1)\n\tavl.inserirRB(0)\n\tavl.inserirRB(7)\n\tavl.inserirRB(9)\n\tavl.inserirRB(8)\t\n\n\tavl.imprimir()\n\tprint(\"----------------------------------------------\")\n\tavl.colorirArvore(raiz)\n\tavl.colorirArvore(raiz)\n\tavl.imprimirRB()\n\t\n\t\"\"\"print(\"\\n\")\n\t\t\t\tprint(\"--------------------Balanceamento------------------\")\n\t\t\t\tprint(\"\\n\")\n\t\t\t\n\t\t\t\tavl.executaBalanceamento()\n\t\t\t\tavl.imprimir()\"\"\"\n\t\n\t\"\"\"print(\"\\n\")\n\t\t\t\tprint(\"-----------------------Busca-----------------------\")\n\t\t\t\tprint(\"\\n\")\n\t\t\t\t\n\t\t\t\tteclado = int(input(\"Buscando qual elemento?\\n\"))\n\t\t\t\tavl.buscaRB(teclado)\n\t\t\t\"\"\"\n\t\"\"\"print(\"\\n\")\n\t\t\t\tprint(\"---------------------Remoção------------------------\")\n\t\t\t\tprint(\"\\n\")\n\t\t\t\t\n\t\t\t\tteclado = int(input(\"Apagar algum número? \\n\"))\n\t\t\t\tavl.remocao(teclado)\n\t\t\t\tavl.imprimir()\"\"\"\n\nmain()\n","repo_name":"CrazyRural/Trabalhos","sub_path":"Arvores e Heap/rbtree.py","file_name":"rbtree.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"696227176","text":"from data import *\nfrom Algorithm import getPerefList,getCourses\nfrom studentRegistration import studentRegistration,getEligibility\n\n# This function return preferences given by student [course,center_id]\ndef getPreferenceList(student_data):\n\tpreference_data = pull('data-files/preferences.csv')\n\n\tpreference_dict = dict()\n\n\tfor row in student_data:\n\t\ttemp = []\n\n\t\tfor pref_row in preference_data:\n\t\t\tif row[\"form_no\"] == pref_row[\"form_no\"]:\n\t\t\t\ttemp.append([pref_row['course'],pref_row['center_id']])\n\t\tif len(temp)!=0:\n\t\t\tpreference_dict[row['form_no']] = temp\n\n\treturn preference_dict\n\ndef menu():\n\tprint(\"\\n0. SIGN OUT\\n1. LIST COURSES\\n2. LIST CENTERS\\n3. GIVE PREFERENCES\\n4. SEE ALLOCATED CENTER COURSES\\n5. UPDATE PAYMENT DETAILS\")\n\top = int(input(\"Enter your choice : \"))\n\treturn op\n\n\ndef getChoice():\n\tprint(\"\\n0. EXIT\\n1. REGISTER STUDENT\\n2. SIGN IN\")\n\n\tch = int(input(\"ENTER YOUR CHOICE : \"))\n\treturn ch\n\n\n# Validating Student\n\ndef isValid(student_data):\n\tflag = 0\n\tdata = 0\n\tform_no = int(input(\"Enter Form Number : \"))\n\tname = input(\"Enter Name : \")\n\tfor row in student_data:\n\t\tif row['form_no'] == str(form_no):\n\t\t\tflag = 1\n\t\t\tdata = row\n\t\t\tbreak\n\n\tif flag:\n\t\tif data['name'] == name:\n\t\t\treturn student_data.index(data)\n\t\telse:\n\t\t\traise Exception(\"Invalid Name\")\n\telse:\n\t\traise Exception(\"Invalid Form Number\")\n\ndef student_menu():\n\tprint(\"\\n\\t\\tSTUDENT SYSTEM\\t\\t\\n\")\n\t# THIS IS USED TO GET STUDENT RECORD\n\tstudent_data = pull(\"data-files/students.csv\")\n\t# THIS IS USED FOR APPENDING PREFERENCES GIVEN BY STUDENT\n\tpreference_data = pull(\"data-files/preferences.csv\")\n\t# THIS IS FOR GETTING LIST OF CENTER\n\tcenter_data = pull('data-files/centers.csv')\n\t# THIS IS FOR GETTING COURSES DATA\n\tcourse_data = pull(\"data-files/courses.csv\")\n\n\n\tpreference_list = getPerefList()\n\tcourse_list = getCourses()\n\teligibility_data = getEligibility()\n\tform_number = len(student_data)\n\tform_number +=1\n\tch = getChoice()\n\twhile(ch):\n\t\tif ch == 1:\n\t\t\tprint(' \\n'.center(55,'='))\n\t\t\tprint(\"Student Registration\\n\".center(45,' '))\n\t\t\tnew_student_data = dict()\n\t\t\tnewStudent = studentRegistration(form_number,eligibility_data)\n\t\t\ttry:\n\t\t\t\tnewStudent.accept()\n\t\t\t\tnew_student_data = newStudent.getRecord()\n\t\t\texcept Exception as ex:\n\t\t\t\tprint(ex)\n\t\t\t\n\t\t\tif len(new_student_data)!=0:\n\t\t\t\tstudent_data.append(new_student_data)\n\t\t\t\tprint(\"New Student Registered Successfully!\")\n\t\t\t\tform_number+=1\n\t\t\tprint('\\n '.center(55,'='))\n\t\telif ch == 2:\n\t\t\t# Validating Student\n\t\t\ttry:\n\t\t\t\tindex = isValid(student_data)\n\t\t\t\tif index>=0:\n\t\t\t\t\t# print(data)\n\t\t\t\t\top = menu()\n\t\t\t\t\twhile(op):\n\t\t\t\t\t\tif op == 1:\n\t\t\t\t\t\t\t# THIS OF GETTING LIST OF COURSES\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcourses = eligibility_data.get(student_data[index]['degree'])\n\t\t\t\t\t\t\tcourses = courses[1]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tprint(\"================================================\")\n\t\t\t\t\t\t\tprint(\"\\t\\tAVAILABLE COURSES ACCORDING TO YOUR DEGREE\\t\\t\\n\")\n\t\t\t\t\t\t\tfor row in course_data:\n\t\t\t\t\t\t\t\tif row['name'] in courses:\n\t\t\t\t\t\t\t\t\tprint(f'Course Name : {row[\"name\"]}\\nFees : {row[\"fees\"]}\\nSection Rank Required : {row[\"section\"]}\\n\\n')\n\t\t\t\t\t\t\tprint(\"================================================\")\n\n\n\t\t\t\t\t\telif op == 2:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tprint(\"================================================\")\n\t\t\t\t\t\t\tprint(\"\\t\\tAVAILABLE CENTERS\\t\\t\\n\")\n\t\t\t\t\t\t\tfor row in center_data:\n\t\t\t\t\t\t\t\tprint(f'Center Name : {row[\"center_name\"]}\\nCenter Co-ordinator : {row[\"coordinator\"]}\\nAddress : {row[\"address\"]}\\n\\n')\n\t\t\t\t\t\t\tprint(\"================================================\")\n\n\n\t\t\t\t\t\telif op == 3:\n\t\t\t\t\t\t\tflag = 1\n\t\t\t\t\t\t\tpref_list = preference_list.get(student_data[index]['form_no'],[])\n\t\t\t\t\t\t\tcnt = len(pref_list)\n\t\t\t\t\t\t\teligible_courses = eligibility_data.get(student_data[index]['degree'])\n\t\t\t\t\t\t\teligible_courses = eligible_courses[1]\n\t\t\t\t\t\t\tcnt+=1\n\t\t\t\t\t\t\tavailable_preferences = []\n\t\t\t\t\t\t\tsections = ['A','B','C']\n\n\t\t\t\t\t\t\tfor rank in sections:\n\t\t\t\t\t\t\t\tcourses = course_list.get(rank,-1)\n\t\t\t\t\t\t\t\tif courses!=-1 and int(student_data[index][rank]) > 0 :\n\t\t\t\t\t\t\t\t\tflag = 0\n\t\t\t\t\t\t\t\t\tfor center_row in center_data:\n\t\t\t\t\t\t\t\t\t\tfor course in courses:\n\t\t\t\t\t\t\t\t\t\t\tif course in eligible_courses:\n\t\t\t\t\t\t\t\t\t\t\t\tif [course,center_row['center_id']] not in pref_list:\n\t\t\t\t\t\t\t\t\t\t\t\t\tavailable_preferences.append([course,center_row['center_id']])\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif flag != 1:\n\t\t\t\t\t\t\t\tprint(\"====================================================\")\n\t\t\t\t\t\t\t\tprint(\"\\t\\tGIVE YOUR PREFERENCE\\t\\t\\n\")\n\t\t\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\t\t\tif cnt>10:\n\t\t\t\t\t\t\t\t\t\tprint(\"10 preferences are already given\")\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tprint(\"0. EXIT\")\n\t\t\t\t\t\t\t\t\tidx = 1\n\t\t\t\t\t\t\t\t\tfor row in available_preferences:\n\t\t\t\t\t\t\t\t\t\tprint(f'{idx}. {row[0]} {row[1\t]}')\n\t\t\t\t\t\t\t\t\t\tidx+=1\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tpref_no = int(input(\"Enter Your Preference Number : \"))\n\t\t\t\t\t\t\t\t\tif pref_no == 0:\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telif pref_no>=1 and pref_no <= idx:\n\t\t\t\t\t\t\t\t\t\tdata = available_preferences.pop(pref_no - 1)\n\t\t\t\t\t\t\t\t\t\tprint({'form_no' : student_data[index]['form_no'],'preference_no' : str(cnt),'course' : data[0],'center_id' : data[1]})\n\t\t\t\t\t\t\t\t\t\tpreference_data.append({'form_no' : student_data[index]['form_no'],'preference_no' : str(cnt),'course' : data[0],'center_id' : data[1]})\n\t\t\t\t\t\t\t\t\t\tcnt+=1\n\t\t\t\t\t\t\t\t\t\tprint(\"Your Preference Saved...\")\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tprint(\"Please Enter valid preference number...!\")\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tch = input(\"Do you want to continue...(y/n)\")\n\t\t\t\t\t\t\t\t\tif ch == 'n':\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(\"==========================================================\")\n\t\t\t\t\t\t\t\tprint(\"Their is no valid rank for giving preferences!\")\n\t\t\t\t\t\t\t\tprint('==========================================================')\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tpreference_data = sorted(preference_data,key = lambda row : int(row['form_no']))\n\n\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\telif op == 4:\n\t\t\t\t\t\t\t# For giving acknowledgement to student about their allocation\n\t\t\t\t\t\t\tdata = student_data[index]\n\n\t\t\t\t\t\t\tif int(data['allocated_preference']) <= 0:\n\t\t\t\t\t\t\t\tprint(f'Sorry {data[\"name\"]}! There is no center allocated to you.')\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(f'Hello {data[\"name\"]}, your allocated center is {data[\"allocated_center_id\"]} for {data[\"allocated_course_name\"]}.')\n\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\telif op == 5:\n\t\t\t\t\t\t\tif int(student_data[index]['allocated_preference']) <= 0:\n\t\t\t\t\t\t\t\tprint(f'Sorry {student_data[index][\"name\"]}! There is no center allocated to you.')\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(f'Hello {student_data[index][\"name\"]}, your allocated center is {student_data[index][\"allocated_center_id\"]} for {student_data[index][\"allocated_course_name\"]}.')\n\t\t\t\t\t\t\t\tif student_data[index]['payment'] == '0':\n\t\t\t\t\t\t\t\t\tprint(\"Your first installment of 11800rs is still pending!\")\n\t\t\t\t\t\t\t\t\tip = input(\"Do you want to make payment?(y/n) : \")\n\t\t\t\t\t\t\t\t\tif ip == 'y':\n\t\t\t\t\t\t\t\t\t\tstudent_data[index]['payment'] = '11800'\n\t\t\t\t\t\t\t\t\t\tprint(\"Payment Successful!!!\")\n\n\n\t\t\t\t\t\t\t\telif student_data[index]['payment'] == '11800':\n\t\t\t\t\t\t\t\t\tfee = 0\n\t\t\t\t\t\t\t\t\tfor row in course_data:\n\t\t\t\t\t\t\t\t\t\tif row['name'] == student_data[index]['allocated_course_name']:\n\t\t\t\t\t\t\t\t\t\t\tfee = row['fees']\n\t\t\t\t\t\t\t\t\tprint(f'Your Second installment of {fee}rs is still pending!')\n\t\t\t\t\t\t\t\t\tip = input(\"Do you want to make payment?(y/n) : \")\n\t\t\t\t\t\t\t\t\tif ip == 'y':\n\t\t\t\t\t\t\t\t\t\tstudent_data[index]['payment'] = str(int(student_data[index]['payment'])+int(fee)) \n\t\t\t\t\t\t\t\t\t\tprint(\"Payment Successful!!!\")\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprint(\"Your payment was already done!\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"Invalid input\");\n\t\t\t\t\t\top = menu()\n\n\t\t\texcept Exception as ex:\n\t\t\t\tprint(ex)\n\t\telse:\n\t\t\tprint(\"INVALID INPUT\")\n\t\tch = getChoice()\n\tpushF(\"data-files/students.csv\",student_data)\n\tpushF(\"data-files/preferences.csv\",preference_data)\n\n","repo_name":"Vaibhav0863/Hackathon2","sub_path":"student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":7617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"26806903080","text":"from flask import Flask, request\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef hello():\n name = 'World'\n if request.method == 'POST':\n name = request.form.get('name', 'World')\n return '''\n

Hello {name}!

\n
\n\n\n
\n '''.format(name=name)\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"aculquicondor/HttpUdp","sub_path":"hello_server.py","file_name":"hello_server.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"38267459776","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef sigmoid(x, derivative=False):\n if derivative:\n return sigmoid(x) * (1 - sigmoid(x))\n return 1/(1 + np.exp(-x))\n\ndef softmax(x, derivative=False):\n # Numerically stable with large exponentials\n exps = np.exp(x - x.max())\n if derivative:\n return exps / np.sum(exps, axis=0) * (1 - exps / np.sum(exps, axis=0))\n return exps / np.sum(exps, axis=0)\n\ndef ReLU(X, derivative=False):\n if derivative:\n return np.greater(X, 0).astype(int)\n return np.maximum(0,X)\n\nclass MNIST_dataset():\n\n def __init__(self, csv_path):\n \"\"\"\n MNIST_dataset - (csv_path)\n - Loads from comma separated values file\n \"\"\"\n df = pd.read_csv(csv_path)\n data = df.to_numpy()\n\n a = data[:,0]\n\n one_hot = np.zeros((a.size, a.max()+1))\n one_hot[np.arange(a.size),a] = 1\n self.classes = one_hot\n #Normalize\n self.images = data[:,1:]\n self.images = self.images.astype('float64')/255\n def __len__(self):\n return len(self.images)\n\n def out_feat(self):\n return len(np.unique(self.classes))\n\n def in_feat(self):\n return 784\n\n def __getitem__(self,idx):\n return {'image': self.images[idx],'class': self.classes[idx]}\n\n def plot(self, idx):\n f = plt.figure()\n sp = f.add_subplot(111)\n\n #gather data from row\n data = self.__getitem__(idx)\n label = data['class']\n pixels = data['image']\n\n #interpret one dimensional array as image\n pixels = pixels.reshape((28,28))\n\n #set label, show image\n sp.set_title(f'Label is {label}')\n sp.imshow(pixels)#cmap ='gray')\n\n return f\n\n\n# Class to represent a nueral network \nclass NueralNetwork():\n\n def __init__(self,sizes):\n np.random.seed(22)\n self.sizes = sizes\n self.biases = []\n\n self.params = []\n\n for i in range(len(sizes)-1):\n weights = np.random.rand( sizes[i+1], sizes[i] )\n bias = np.random.rand(sizes[i+1])\n self.params.append(weights)\n self.biases.append(bias)\n\n print(self.params)\n print(self.biases)\n \n def __str__(self):\n return str(self.params)\n\n def forward(self, x):\n '''\n Forward Pass of Nueral network, returns activation or \"output\"\n '''\n params = self.params\n self.inputs = []\n self.activations = []\n\n activation = x\n self.activations.append(x)\n\n for index, layer in enumerate(params[:-1]):\n _input = np.dot( layer, activation) + self.biases[index]\n self.inputs.append( _input )\n activation = sigmoid(_input)\n self.activations.append(activation)\n\n final_input = np.dot( params[-1] , activation) + self.biases[-1]\n self.inputs.append(final_input)\n activation = softmax( final_input, derivative=False )\n self.activations.append(activation)\n\n return activation\n\n def backward(self, y, output):\n '''\n Backward Pass of Nueral network, returns change to params\n '''\n #for each set of weights, calculate error BACKWARDS\n deltas = []\n\n #print(y, output)\n\n error = (output - y) \n\n #print(error)\n\n #print(softmax(self.inputs[-1], derivative=True))\n\n error = error * softmax(self.inputs[-1], derivative=True)\n\n #print(error)\n\n deltas.append( np.outer( error , self.activations[-2]))\n\n #print('final delta')\n #print(np.outer( error , self.activations[-2]).shape)\n\n #print('Activations')\n #for act in self.activations:\n # print(act.shape)\n\n\n for index in reversed(range(len(self.params[1:]))):\n #print(index)\n #print(np.dot(self.params[index + 1].T, error))\n error = np.dot(self.params[index + 1].T, error) * ReLU( self.inputs[ index ], derivative=True)\n #print(\"is this small\")\n #print(np.outer( error , self.activations[index]).shape)\n deltas.insert(0, np.outer( error , self.activations[index]))\n\n #print('deltas')\n #for de in deltas:\n # print(de.shape)\n\n #print(error)\n \n return deltas \n \n def update(self, deltas, lr):\n '''\n Update weights of nueral network, no return \n '''\n for index,layer in enumerate(self.params):\n self.params[index] = layer - lr * deltas[index]\n\n\n def predict(self, x):\n '''\n Make a prediction \n '''\n return np.argmax( self.forward(x) )\n\n def train(self, epochs, lr, dataset):\n\n for epoch in range(epochs):\n\n #print(self.params[0])\n \n # could to random indices batches, OOOOOO NORMAL or gaussian here?\n for index in range(len(dataset)):\n\n output = self.forward(dataset[index]['image'])\n\n delta = self.backward(dataset[index]['class'], output)\n\n self.update(delta, lr)\n\n #print(delta)\n\n acc = self.accuracy(dataset)\n\n print(acc)\n\n #print(self.params[1])\n\n #break\n\n def accuracy(self, dataset):\n\n acc = []\n\n for index in range(len(dataset)):\n #gather data from row\n label = dataset[index]['class']\n pixels = dataset[index]['image']\n\n pred = self.predict(pixels)\n acc.append( np.argmax(label) == pred )\n\n return np.mean(acc)","repo_name":"cgarchbold/Multilayer_Perceptrons","sub_path":"nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15876957041","text":"import openai\nimport textwrap\n\n\nopenai.api_key = \"your_openai_api_key\"\n\ndef audio_to_text(audio_path):\n audio_file = open(audio_path, \"rb\")\n transcript = openai.Audio.transcribe(\"whisper-1\", audio_file)\n return transcript\n\ndef call_chat_completion(system_prompt, user_prompt):\n messages = [\n {\"role\": \"system\", \"content\": system_prompt},\n {\"role\": \"user\", \"content\": user_prompt}\n ]\n\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=messages,\n )\n\n return response\n\ndef transcript_to_meeting_minutes(meeting_text, chunk_size=10000):\n \"\"\"\n Generate meeting minutes from a meeting transcript using an iterative approach.\n \n This function breaks the transcript into chunks, creates meeting minutes from the first chunk,\n and then iteratively modifies the meeting minutes based on the subsequent chunks.\n \n Args:\n meeting_text (str): The meeting transcript text.\n chunk_size (int, optional): The size of the chunks the transcript is broken into. Defaults to 10000.\n\n Returns:\n str: The generated meeting minutes.\n \"\"\"\n # Split the meeting text into chunks\n meeting_chunks = textwrap.wrap(meeting_text, chunk_size)\n\n # normal call to gpt for first chunk\n first_chunk = meeting_chunks[0]\n system_prompt = \"You are an AI that generates meeting minutes from given meeting text.\"\n user_prompt = f\"\"\"Please generate meeting minutes from the following meeting text:\\n\\n{first_chunk}\\n\\n\n The meeting minutes should include the following sections:\\n- Agenda\\n- Attendees\\n- Key Points\\n- Decisions\\n- Action Items\n \"\"\"\n response = call_chat_completion(system_prompt, user_prompt)\n meeting_minutes = response['choices'][0]['message']['content']\n\n # call with another prompt with instruction to modify meeting minutes according to new chunk. notice different prompts\n system_prompt = \"You are an AI that updates meeting minutes based on additional chunks of a meeting transcript.\"\n for chunk in meeting_chunks[1:]:\n user_prompt = f\"\"\"Here are the current meeting minutes:\\n\\n{meeting_minutes}\\n\\n\n Please update the meeting minutes based on the following chunk of the meeting transcript:\\n\\n{chunk}\\n\\n\n The meeting minutes should include these sections:\\n- Agenda\\n- Attendees\\n- Key Points\\n- Decisions\\n- Action Items\n \"\"\"\n response = call_chat_completion(system_prompt, user_prompt)\n meeting_minutes = response['choices'][0]['message']['content']\n\n return meeting_minutes\n","repo_name":"PyaePhyoKhant/meeting_minutes_generator","sub_path":"ml_functions.py","file_name":"ml_functions.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11216088101","text":"import random\nimport numpy as np\n\nclass UCBAgent:\n # Optimal Settings:\n # exploration=12, opp_reward=0.6, warmup=1, choose='max'\n # exploration=0.1, opp_reward=0.1, warmup=3, choose='random'\n def __init__(self, exploration=0.2, opp_reward=0.2, warmup=2, winrate=0.8, choose='max', verbose=False):\n self.exploration = exploration\n self.choose = choose\n self.opp_reward = opp_reward\n self.warmup = warmup\n self.winrate = winrate\n self.verbose = verbose\n self.history = None\n self.state = None\n\n \n def init_state(self, observation, configuration, force=False):\n if self.state is None or force:\n self.history = {\n \"actions\": [],\n \"opponent\": [],\n \"reward\": [],\n }\n self.state = {\n \"our_rewards\": np.zeros(configuration.banditCount, dtype=np.float),\n \"opp_rewards\": np.zeros(configuration.banditCount, dtype=np.float),\n \"our_visits\": np.zeros(configuration.banditCount, dtype=np.float),\n \"opp_visits\": np.zeros(configuration.banditCount, dtype=np.float), \n \"total_visits\": np.zeros(configuration.banditCount, dtype=np.float), \n } \n \n \n def update_state(self, observation, configuration):\n if self.state is None:\n self.init_state(observation, configuration)\n \n self.history['reward'].append( observation.reward )\n if len(self.history['actions']):\n # observation.reward is cumulative reward\n our_reward = int(self.history['reward'][-1] > self.history['reward'][-2])\n our_last_action = self.history['actions'][-1]\n if len( set(observation.lastActions) ) == 1:\n opp_last_action = our_last_action\n else:\n opp_last_action = list( set(observation.lastActions) - {our_last_action} )[0]\n self.history['opponent'].append(opp_last_action)\n\n self.state['our_rewards'][ our_last_action ] += our_reward\n self.state['opp_rewards'][ opp_last_action ] += self.opp_reward\n self.state['our_visits'][ our_last_action ] += 1\n self.state['opp_visits'][ opp_last_action ] += 1\n self.state['total_visits'][ our_last_action ] += 1\n self.state['total_visits'][ opp_last_action ] += 1\n \n \n \n def scores(self, observation, configuration):\n total_visits = np.sum(self.state['our_visits']) + 1\n our_visits = np.max([ self.state['our_visits'], np.ones(len(self.state['our_visits'])) ])\n scores = (\n (self.state['our_rewards'] + self.state['opp_rewards']) / our_visits \n + np.sqrt( self.exploration * np.log(total_visits) / our_visits )\n )\n scores *= configuration.decayRate ** self.state['total_visits']\n return scores\n\n \n # observation {'remainingOverageTime': 60, 'step': 1, 'reward': 1, 'lastActions': [54, 94]}\n # configuration {'episodeSteps': 2000, 'actTimeout': 0.25, 'runTimeout': 1200, 'banditCount': 100, 'decayRate': 0.97, 'sampleResolution': 100}\n def agent(self, observation, configuration):\n\n self.update_state(observation, configuration)\n\n scores = self.scores(observation, configuration)\n\n winners = np.argwhere( (self.state['our_visits'] != 0) \n & ( \n (self.state['our_visits'] <= self.state['our_rewards'] + (self.warmup - 1)) \n | (\n np.nan_to_num(self.state['our_rewards'] / self.state['our_visits']) \n >= self.winrate * configuration.decayRate ** (observation.step/configuration.banditCount)\n )\n )\n ).flatten()\n untried = np.argwhere( self.state['our_visits'] == 0).flatten()\n \n if self.warmup and len(winners):\n action = np.random.choice(winners) # keep trying winners until we lose\n elif self.warmup and len(untried):\n action = np.random.choice(untried)\n else:\n if self.choose == 'random':\n action = random.choices( population=np.arange(len(scores)), weights=scores, k=1 )[0] \n elif self.choose == 'max':\n action = np.argmax(scores)\n else:\n assert False, self.choose \n \n if self.verbose:\n if True or observation.step < configuration.banditCount:\n print()\n print('observation = ', observation)\n print(f'scores = {list(scores.round(2))}')\n for key, values in self.state.items():\n print(f'self.state[\"{key}\"] = {list(values)}')\n print(f'action = {action}')\n\n self.history['actions'].append(action)\n return int(action)\n\n \n def __call__(self, observation, configuration):\n return self.agent(observation, configuration)\n \nucb_instance = UCBAgent() \ndef ucb_agent(observation, configuration):\n return ucb_instance.agent(observation, configuration)","repo_name":"sergmiller/bandits","sub_path":"kernels/optimized_ucb.py","file_name":"optimized_ucb.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73252686564","text":"import numpy as np\nimport json\n\nfrom query import *\n\ndef timeline_json(events, dates, query):\n \"\"\"\n \"\"\"\n tl_json = { \"events\": [] }\n num = 0\n\n for event in events:\n\n num = num+1\n d_start = dates[event[0]-1]\n d_end = dates[event[1]-1]\n\n # Ajout de l'article marquant de l'intervalle\n tmp = {}\n res_req = query_articles(query, d_start, d_end)\n\n tmp[\"start\"] = res_req[\"hits\"][\"hits\"][0][\"_source\"][\"date_art\"]\n tmp[\"title\"] = num\n tmp[\"description\"] = res_req[\"hits\"][\"hits\"][0][\"_source\"][\"article\"].replace('\\t','\\n')\n tmp[\"link\"] = \"http://localhost:5601/app/kibana#/doc/spliine/spliine/article?id=\" + res_req[\"hits\"][\"hits\"][0][\"_source\"][\"id_art\"]\n\n tl_json['events'].append(tmp)\n\n # Ajout de l'intervalle\n tmp = {}\n tmp[\"start\"] = d_start\n tmp[\"end\"] = d_end\n tmp[\"title\"] = \"\"\n tmp[\"durationEvent\"] = 'true'\n tmp[\"description\"] = \"Evenement entre \" + d_start + \" et \" + d_end\n tmp[\"link\"] = \"\"\n\n tl_json['events'].append(tmp)\n\n return json.dumps(tl_json)\n\n # Sauvegarde du `js`\n # f = open('results.json', 'w')\n # json.dump(tl_json, f, indent=1)\n","repo_name":"jcrouzet/temporal-search-engine","sub_path":"src/timeline_json.py","file_name":"timeline_json.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15371861029","text":"#!/usr/bin/python\nimport os\nimport logging\nimport json\nimport sys\nimport pickle\nfrom pprint import pprint\nimport time\nimport datetime\nimport phonenumbers\n\nDEBUG = int(os.environ.get(\"DEBUG\", \"0\"))\nDATADIR = os.environ.get(\"DATADIR\", \"/data\")\nPICKLENAME = os.path.join(DATADIR, 'users.pkl')\nFORMAT = '%(asctime)-15s %(levelname)-8s %(message)s'\nPHOTO_DIR = os.path.join(DATADIR, 'photos')\nTARGETFILE = os.path.join(DATADIR, 'users.json')\nFLATFILE = os.path.join(DATADIR, 'users.flat')\n\n\ndef strip_suffix(candidate, suffix):\n if candidate.endswith(suffix):\n return candidate[:-len(suffix)]\n return candidate\n\n\ndef sanitize_phone(candidate):\n t = candidate.translate(None, ' -!()')\n if len(t) == 0:\n return t\n try:\n x = phonenumbers.parse(t, None)\n return phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL).encode('ascii', 'ignore')\n except phonenumbers.phonenumberutil.NumberParseException as e:\n logging.error(\"Failed to parse phone number \\\"%s\\\"\" % candidate)\n except Exception as e:\n logging.exception(e)\n return t\n\n\ndef str_to_utc(datestring):\n if len(datestring.strip()) == 0:\n return 0\n try:\n datestring = datestring.split()[0].strip()\n dt = datetime.datetime.strptime(datestring, \"%Y%m%d%H%M%S.0Z\")\n utc = time.mktime(dt.timetuple())\n return utc\n except Exception as e:\n return 0\n\n\ndef transform_users(ldap_results):\n users = []\n for candidate in ldap_results:\n new = {}\n attributes = candidate[1]\n new['email'] = attributes.get('mail', [''])[0].lower()\n new['username'] = attributes.get('sAMAccountName', [''])[0].lower()\n new['fullname'] = \" \".join(reversed([x.strip() for x in attributes.get('displayName', [''])[0].split(', ')]))\n new['path'] = attributes.get('distinguishedName', [''])[0]\n new['title'] = attributes.get('title', [''])[0]\n new['company'] = attributes.get('company', [''])[0]\n new['photo'] = attributes.get('thumbnailPhoto', [''])[0]\n new['manager'] = attributes.get('manager', [''])[0]\n new['managername'] = ''\n new['reports'] = attributes.get('directReports', [''])\n new['description'] = attributes.get('description', [''])[0]\n new['address'] = strip_suffix(\"%s, %s %s, %s\" % (\n attributes.get('streetAddress', [''])[0],\n attributes.get('l', [''])[0],\n attributes.get('postalCode', [''])[0],\n attributes.get('c', [''])[0]), \", \")\n new['phone'] = sanitize_phone(attributes.get('telephoneNumber', [''])[0])\n new['eid'] = attributes.get('employeeNumber', [''])[0]\n new['office'] = attributes.get('physicalDeliveryOfficeName', [''])[0]\n new['notes'] = ''\n new['tags'] = ['']\n\n timestr = attributes.get('whenCreated', [''])[0]\n new['hiredate'] = str_to_utc(timestr)\n\n users.append(new)\n\n users.sort(key=lambda x: x['fullname'])\n return users\n\n\ndef save_and_update_photos(output_dir, records):\n \"\"\"\n Iterates over a list of records and saves the images in a flat\n directory in output_dir\n \"\"\"\n logging.info(\"Saving photos of users...\")\n count = 0\n for record in records:\n photo = record['photo']\n name = record['username']\n del record['photo']\n if len(photo) == 0:\n continue\n count = count + 1\n logging.debug('Found a photo for %s' % name)\n\n filename = os.path.join(output_dir, name + '.jpg')\n open(filename, 'w').write(photo)\n logging.info(\"Saved %d photos\" % count)\n\n\ndef count_reports(lookup, username, seen):\n \"\"\"\n Given a particular username, counts the total reports underneath in\n the org.\n \"\"\"\n seen.add(username)\n\n reports = lookup.get(username, [])\n\n count = len(reports)\n for report in reports:\n if report in seen:\n continue\n count += count_reports(lookup, report, seen)\n return count\n\n\ndef collect_cumulative_reports(records):\n \"\"\"\n Go through all the users and recursivly sum up how many reports are in\n the organization below.\n \"\"\"\n lookup = dict()\n for record in records:\n username = record['username']\n reports = record['reports']\n lookup[username] = reports\n\n for record in records:\n username = record['username']\n total = count_reports(lookup, username, set())\n record['totalreports'] = total\n\n\ndef transform_paths(records):\n \"\"\"\n Translate all the LDAP paths to just be usernames\n \"\"\"\n default_manager = 'CN=Manager\\\\, Default,OU=TIBCO,OU=Apps,DC=activision,DC=com'\n lookup = dict()\n lookup[''] = ''\n id2name = dict()\n id2name[''] = ''\n for record in records:\n path = record['path']\n username = record['username']\n lookup[path] = username\n fullname = record['fullname']\n id2name[username] = fullname\n\n for record in records:\n try:\n record['manager'] = lookup[record['manager']]\n except KeyError:\n if record['manager'] != default_manager:\n logging.warning('Could not find manager: %s. Manager entry set to empty.' % record['manager'])\n record['manager'] = ''\n\n try:\n record['managername'] = id2name[record['manager']]\n except KeyError:\n logging.warning('Failed to lookup manager id %s for user %s' % (record['manager'], record['username']))\n record['managername'] = ''\n\n translated = []\n for x in record['reports']:\n try:\n translated.append(lookup[x])\n except KeyError:\n logging.warning('Could not find employee: %s. Skipping as a report for %s' % (x, record['username']))\n record['reports'] = [x for x in translated if len(x.strip()) > 0]\n\n\ndef debug():\n \"\"\"\n Debugging function with random stuff\n \"\"\"\n logging.info(\"Loading pickle stream from %s!\" % PICKLENAME)\n data = pickle.load(open(PICKLENAME + '.small'))\n logging.info(\"Loaded %d items\" % len(data))\n attributes = data[32][1]\n\n pprint(attributes)\n\n photo = attributes.get('thumbnailPhoto', [''])[0]\n\n print(\"Now trying to decode this: \")\n pprint(photo)\n open(os.path.join(DATADIR, 'image.jpg'), 'w').write(photo)\n\n\ndef render_json(filename, users):\n jsondata = json.dumps(users, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))\n\n logging.info('Saving json data to %s' % filename)\n open(filename, 'w').write(jsondata)\n\n\ndef render_flat(filename, users):\n line = '#username:fullname:email:title:manager:company:phone'\n lines = [line]\n for user in users:\n line = '%(username)s:%(fullname)s:%(email)s:%(title)s:%(manager)s:%(company)s:%(phone)s' % user\n lines.append(line)\n\n flatfile = '\\n'.join(lines)\n open(filename, 'w').write(flatfile)\n\n\ndef main():\n if DEBUG:\n debug()\n return 0\n\n logging.info(\"Loading pickle stream from %s\" % PICKLENAME)\n data = pickle.load(open(PICKLENAME))\n logging.info(\"Loaded %d items\" % len(data))\n\n users = transform_users(data)\n\n if not os.path.isdir(PHOTO_DIR):\n os.makedirs(PHOTO_DIR)\n save_and_update_photos(PHOTO_DIR, users)\n transform_paths(users)\n\n collect_cumulative_reports(users)\n\n render_json(TARGETFILE, users)\n render_flat(FLATFILE, users)\n\n return 0\n\n\nif __name__ == '__main__':\n if DEBUG:\n logging.basicConfig(format=FORMAT, level=logging.DEBUG)\n else:\n logging.basicConfig(format=FORMAT, level=logging.INFO)\n\n sys.exit(main())\n","repo_name":"jtilander/whois","sub_path":"backend/scripts/ldapmunge.py","file_name":"ldapmunge.py","file_ext":"py","file_size_in_byte":7655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1293603548","text":"import sys\nprint(len(sys.argv))\nif len(sys.argv) <= 1:\n with open('bakery.csv', 'r') as bakery:\n for line in bakery:\n print(line[:-1])\nelif len(sys.argv) == 2:\n with open('bakery.csv', 'r') as bakery:\n count = 0\n for line in bakery:\n count += 1\n if int(sys.argv[1]) == count:\n print(line[:-1])\nelse:\n with open('bakery.csv', 'r') as bakery:\n count = 0\n _temp_list = []\n for line in bakery:\n count += 1\n if int(sys.argv[2]) >= count and int(sys.argv[1]) <= count:\n _temp_list.append(line)\n for element in _temp_list:\n print(element[:-1])","repo_name":"ikuklos/home_work","sub_path":"task_6_6_show.py","file_name":"task_6_6_show.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31055028996","text":"from selenium import webdriver\r\nimport time\r\nimport unittest\r\n\r\nclass imageTest(unittest.TestCase):\r\n def setUp(self) :\r\n self.driver=webdriver.Chrome()\r\n self.driver.maximize_window()\r\n self.url=\"http://192.168.107.128:9898/admin.html\"\r\n\r\n def tearDown(self):\r\n self.driver,quit()\r\n\r\n def test_delete_dish(self):\r\n driver = self.driver\r\n driver.get(self.url)\r\n driver.implicitly_wait(10)\r\n\r\n driver.find_element_by_xpath('//*[@id=\"tables\"]/div/div/table/tbody/tr[5]/td[3]/button').click()\r\n time.sleep(3)\r\n alert = driver.switch_to.alert\r\n alert.accept()\r\n time.sleep(3)\r\n\r\n def test_insert_dish(self):\r\n driver = self.driver\r\n driver.get(self.url)\r\n driver.implicitly_wait(10)\r\n\r\n driver.find_element_by_xpath('//*[@id=\"tables\"]/div/div/div/span[2]/button').click()\r\n time.sleep(3)\r\n driver.find_element_by_xpath('//*[@id=\"tables\"]/div/div/table/tfoot/tr/th[1]/input').send_keys(\"麻婆豆腐\")\r\n time.sleep(3)\r\n\r\n driver.find_element_by_xpath('//*[@id=\"tables\"]/div/div/table/tfoot/tr/th[2]/input').clear()\r\n driver.find_element_by_xpath('//*[@id=\"tables\"]/div/div/table/tfoot/tr/th[2]/input').send_keys(\"15\")\r\n time.sleep(3)\r\n\r\n driver.find_element_by_xpath('//*[@id=\"tables\"]/div/div/table/tfoot/tr/th[3]/button').click()\r\n time.sleep(3)\r\n\r\n if __name__==\"__main__\":\r\n unittest.main(verbosity=0)","repo_name":"Zcx1805/progect","sub_path":"progect_sysorder/sys_order/test/server_compatibility.py","file_name":"server_compatibility.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74762529124","text":"#!/usr/bin/python3\n\"\"\"Module for minOperations method.\n\"\"\"\n\n\ndef minOperations(n):\n \"\"\"Calculates the fewest number of operations needed to result in\n exactly n H characters in the file.\n \"\"\"\n if n <= 1:\n return 0\n i = 2\n ops = 0\n while n > 1:\n if n % i == 0:\n ops += i\n n /= i\n else:\n i += 1\n return ops\n","repo_name":"bashthat/holbertonschool-interview","sub_path":"0x02-minimum_operations/0-minoperations.py","file_name":"0-minoperations.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12566971129","text":"def hackerlandRadioTransmitters(x, k):\n x.sort()\n print(x)\n count = 1 # number of radio stations\n start = x[0] # radio coverage start\n radio = x[0] # radio station location\n for house in x:\n # if start is within range from current house, \n # move the radio location to current house\n if house-start <= k: radio = house\n # if current house is out of range, add a radio station\n elif house-radio > k:\n count += 1\n start = house\n radio = house\n \n return count\n","repo_name":"eladsadeh/code-challenges","sub_path":"python/radio_transmitters.py","file_name":"radio_transmitters.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19359958105","text":"# -*- coding: utf-8 -*-\n\nfrom scrapy import Request\nfrom news_all.spider_models import NewsRSpider\nimport re\n\n\nclass qingnianSpider(NewsRSpider):\n \"\"\"中国青年 app\"\"\"\n name = 'qingnian_app'\n mystart_urls = { # todo 用PyExecJS解析。只有http://m.youth.cn/是实际dom 其他都是js dataList.push\n 'http://m.youth.cn/': 2926, # APP端-中央媒体移动端-中国青年-要闻\n 'http://m.youth.cn/gqt/': 2927, # APP端-中央媒体移动端-中国青年-共青团\n 'http://m.youth.cn/p/': 2928, # APP端-中央媒体移动端-中国青年-图片\n 'http://m.youth.cn/pl/': 2929, # APP端-中央媒体移动端-中国青年-评论\n 'http://m.youth.cn/f/': 2930, # APP端-中央媒体移动端-中国青年-娱乐\n 'http://m.youth.cn/s/': 2931, # APP端-中央媒体移动端-中国青年-社会\n 'http://m.youth.cn/jy/': 2932, # APP端-中央媒体移动端-中国青年-教育\n 'http://m.youth.cn/ydsp/': 2933, # APP端-中央媒体移动端-中国青年-短视频\n 'http://m.youth.cn/dfyw/': 2934, # APP端-中央媒体移动端-中国青年-地方\n }\n custom_settings = {\n 'DEPTH_LIMIT': 5, # 翻页需要设置深度为0 或者 >1\n }\n \n def parse(self, response):\n if response.url == 'http://m.youth.cn/ydsp/':\n return self.parse_video(response)\n \n con = response.xpath('//ul[@class=\"thumb\"]/li[@class=\"thumb-item\"]').extract()\n if con == []:\n return self.parse_3(response)\n \n for i in response.xpath('//ul[@class=\"thumb\"]/li[@class=\"thumb-item\"]').extract():\n news_url = re.search('a href=\"(.*?)\" target=\"_blank\">', i).group(1)\n news_url = 'https://t.m.youth.cn/transfer/index/url/' + news_url\n title = re.search('a.*?>(.*?)', i).group(1)\n origin_name = re.search('(.*?)', i).group(1)\n print(news_url)\n yield Request(\n url=news_url,\n callback=self.parse_item,\n meta={'source_id': response.meta['source_id'], 'title': title,\n 'start_url_time': response.meta.get('start_url_time'), 'schedule_time': response.meta.get('schedule_time'), 'origin_name': origin_name})\n \n def parse_3(self, response): # http://m.youth.cn/gqt/\n con = re.findall('dataList\\.push\\((.*?})', response.text)\n for i in con:\n i = eval(i)\n news_url = i['link']\n if response.url != 'http://m.youth.cn/p/':\n news_url = 'https://t.m.youth.cn/transfer/index/url/' + news_url\n title = i['title']\n origin_name = i['source']\n callback = self.parse_item\n if response.url == 'http://m.youth.cn/p/':\n callback = self.parse_image\n news_url = 'https://t.m.youth.cn/transfer/index/url/' + news_url # 重新生成url方便访问客户端,统一解析\n print(news_url)\n try:\n yield Request(\n url=news_url,\n callback=callback,\n meta={'source_id': response.meta['source_id'], 'title': title,\n 'start_url_time': response.meta.get('start_url_time'), 'schedule_time': response.meta.get('schedule_time'),\n 'origin_name': origin_name})\n except:\n yield Request(\n url='http:' + news_url,\n callback=callback,\n meta={'source_id': response.meta['source_id'], 'title': title,\n 'start_url_time': response.meta.get('start_url_time'), 'schedule_time': response.meta.get('schedule_time'),\n 'origin_name': origin_name})\n \n def parse_image(self, response):\n try:\n rs = response.xpath('//div[@class=\"content1\"]').extract()\n title = response.xpath('//h1[@id=\"title\"]/text()')[0].extract()\n pubtime = response.xpath('//span[@id=\"pubtime\"]/text()')[0].extract().replace(' ', '')\n # 时效性检查\n \n origin_name = response.xpath('//span[@id=\"source\"]/text()')[0].extract()\n content, media, _, _ = self.content_clean(rs, kill_xpaths=['//ul[@class=\"page_ggw mt15\"]',\n '//ul[@class=\"page_pic\"]'])\n\n except:\n return self.produce_debugitem(response, \"xpath error\")\n return self.produce_item(\n response=response,\n title=title,\n pubtime=pubtime,\n origin_name=origin_name,\n content=content,\n media=media,\n )\n \n def parse_video(self, response): # http://m.youth.cn/ydsp/,短视频没有新闻内容,只有视频\n video = response.xpath('//div[@class=\"video_youth\"]')\n for i in video:\n try:\n title = i.xpath('./h3/text()')[0].extract()\n video_url = i.xpath('./div[@class=\"video_k\"]//source/@src')[0].extract()\n pubtime = i.xpath('./div[@class=\"laiyuan\"]/span[2]/text()')[0].extract()\n videos = {'1': {'src': video_url}}\n content = '
#{{1}}#
'\n except:\n return self.produce_debugitem(response, \"xpath error\")\n yield self.produce_item(\n response=response,\n title=title,\n pubtime=pubtime,\n content=content,\n videos=videos\n )\n \n def parse_item(self, response):\n try:\n rs = response.xpath('//div[@class=\"content1\"]').extract()\n title = response.xpath('//h1[@id=\"title\"]/text()')[0].extract()\n pubtime = response.xpath('//span[@id=\"pubtime\"]/text()')[0].extract().replace(' ', '')\n origin_name = response.xpath('//span[@id=\"source\"]/text()')[0].extract()\n content, media, _, _ = self.content_clean(rs, kill_xpaths=['//ul[@class=\"page_ggw mt15\"]',\n '//ul[@class=\"page_pic\"]'])\n except:\n return self.produce_debugitem(response, \"xpath error\")\n return self.produce_item(\n response=response,\n title=title,\n pubtime=pubtime,\n origin_name=origin_name,\n content=content,\n media=media,\n )\n","repo_name":"Pintrue/news_all","sub_path":"news_all/spiders_wap/qingnian.py","file_name":"qingnian.py","file_ext":"py","file_size_in_byte":6507,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"192960284","text":"from mealie.repos.repository_factory import AllRepositories\nfrom mealie.schema.recipe.recipe import Recipe\nfrom mealie.schema.recipe.recipe_ingredient import RecipeIngredient, SaveIngredientFood\nfrom tests.utils.factories import random_string\nfrom tests.utils.fixture_schemas import TestUser\n\n\ndef test_food_merger(database: AllRepositories, unique_user: TestUser):\n slug1 = random_string(10)\n\n food_1 = database.ingredient_foods.create(\n SaveIngredientFood(\n name=random_string(10),\n group_id=unique_user.group_id,\n )\n )\n\n food_2 = database.ingredient_foods.create(\n SaveIngredientFood(\n name=random_string(10),\n group_id=unique_user.group_id,\n )\n )\n\n recipe = database.recipes.create(\n Recipe(\n name=slug1,\n user_id=unique_user.group_id,\n group_id=unique_user.group_id,\n recipe_ingredient=[\n RecipeIngredient(note=\"\", food=food_1), # type: ignore\n RecipeIngredient(note=\"\", food=food_2), # type: ignore\n ],\n ) # type: ignore\n )\n\n # Santiy check make sure recipe got created\n assert recipe.id is not None\n\n for ing in recipe.recipe_ingredient:\n assert ing.food.id in [food_1.id, food_2.id] # type: ignore\n\n database.ingredient_foods.merge(food_2.id, food_1.id)\n\n recipe = database.recipes.get_one(recipe.slug)\n\n for ingredient in recipe.recipe_ingredient:\n assert ingredient.food.id == food_1.id # type: ignore\n","repo_name":"mealie-recipes/mealie","sub_path":"tests/unit_tests/repository_tests/test_food_repository.py","file_name":"test_food_repository.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":3977,"dataset":"github-code","pt":"52"} +{"seq_id":"19860529527","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom ast2000tools.space_mission import SpaceMission\nimport ast2000tools.utils as utils\nfrom ast2000tools.constants import *\nfrom ast2000tools.solar_system import SolarSystem\nfrom ast2000tools.shortcuts import SpaceMissionShortcuts\nimport atmos_part7\n#utils.check_for_newer_version()\n# Construct SpaceMission instance for my mission\nseed = utils.get_seed('Sgfrette')\nmission = SpaceMission(seed)\nsystem = SolarSystem(seed)\n\nrho = atmos_part7.density_func\n\n#Kalkuler luftmotsand\ndef Fd(r,v,A):\n h = np.linalg.norm(r) #finn avstand\n\n \"\"\"Hvis vi er lengre ut enn den interpolerte lufttettheten,\n så settes den til 0\"\"\"\n if h> system.radii[1]*1000 +15000000:\n return np.asarray([0,0,0])\n\n #Finn vår relative hastighet relativt til atmosfæren\n rel_vel = v -(h*2*np.pi/(system.rotational_periods[1]*day))\\\n * np.asarray([-r[1]/h,r[0]/h,0])\n a = -1/2 * rho(h)*A*np.linalg.norm(rel_vel)*rel_vel\n\n #Hvis akselerasjonen er for stor stopper koden, skal tilsvare at fallskjermen ryker\n assert np.linalg.norm(a)<250000,'a={}, height = {}'.format(np.linalg.norm(a),\\\n np.linalg.norm(r)-system.radii[1]*1000)\n return a\n\n#Gravitasjon fra planeten\ndef grav_planet(r,m_ship):\n a = -G*m_ship*system.masses[1]*m_sun*(r/np.linalg.norm(r)**3)\n return a\n#Lander booster, hvis raketten er over eller under grensa vi satt returnerer den\n# enten 0 eller det vi velger i radiell retning fra planeten til raketten\ndef thrusters(r,d,thruster_boost,v):\n if np.linalg.norm(r)> system.radii[1]*1000+d:\n return np.asarray([0,0,0])\n if np.linalg.norm(r)< system.radii[1]*1000+d:\n return thruster_boost*(r/np.linalg.norm(r))\n\n#Simuler selve landingsprosessen\ndef falling(initial_pos,initial_vel,dt_length,tot_crossec,mass,\\\n d,nr,thruster_boost):\n #Sett parametre, konstanter og init-verdier\n m_ship = mass#kg\n A = tot_crossec\n dt = dt_length\n x = np.zeros((1,3),float)\n x[0,:] = initial_pos\n v = initial_vel\n t = 0\n initial_time=0\n a_i = (grav_planet(x[0,:],mass) + Fd(x[0,:],v,A))/m_ship\n j = 0\n\n #Loop over posisjon til raketten med leapfrog\n while (np.linalg.norm(x[j])-(system.radii[1]*1000)>0):\n t+=dt\n #Dersom falling brukes flere ganger gjennom landingen legges posisjons\n #arrayene sammen til en array\n x = np.append(x,[x[j,:]+v*dt + 0.5*a_i*dt**2],axis=0)\n\n #Hvis posisjonen til raketten er mindre enn 0, returner siste posisjon,\n #med hastighet og tid\n if ((np.linalg.norm(x[j+1])-system.radii[1]*1000)<0):\n return x[:-1],v,t\n\n #Nr er posisjon til fallskjermutslippen, settes til 0 etter første gang\n #den brukes\n if np.linalg.norm(x[j+1])<(system.radii[1]*1000+nr) and nr>0:\n return x[:-1],v,t\n a_iplus1 = (grav_planet(x[j+1],mass) + Fd(x[j+1],v,A) + thrusters(x[j+1],d,thruster_boost,v))\\\n /m_ship\n #print(a_iplus1)\n v = v + 0.5*( a_i + a_iplus1 )*dt\n a_i = a_iplus1\n j +=1\n\n #print avstand og radiell hastighet til raketten\n distanse = np.linalg.norm(x[j,:])-system.radii[1]*1000\n vr = np.dot(v,-x[j,:]/np.linalg.norm(x[j,:]))\n\n print(\"x = {:.5e} moh vr = {:.5f} m/s\" .format(distanse,vr))\n return x[:-1],v,t\nif __name__ == '__main__':\n\n \"\"\" mission = mission.load('mission_after_part_6.pickle')\n\n # Initiate the landing sequence\n landing_sequence = mission.begin_landing_sequence()\n time0, pos_act, vel = landing_sequence.orient()\"\"\" #s,m,m/s\n x,v,t = falling(np.asarray([9472707.88605198,6375196.26580251,0]),\\\n np.asarray([-2398.29145663,3563.54792079,0.]),20000,1,0.3,mission.lander_mass,20)\n fig, ax = plt.subplots()\n ax.plot(x[:,0],x[:,1],label='lander')\n r = system.radii[1]*1000 +1\n circle = plt.Circle((0,0),system.radii[1]*1000, color='peru')\n ax.add_artist(circle)\n\n plt.show()\n\n \n","repo_name":"marithso/AST2000","sub_path":"Prosjekt/Part7/Falling.py","file_name":"Falling.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32549630837","text":"import json\n\nclass Book:\n \"\"\"\n This class represents a book.\n\n All attributes are set in the converter functions.\n It only provides some utility methods like repr and str\n \"\"\"\n\n @classmethod\n def from_json(cls, byte_string):\n d = json.loads(byte_string)\n self = cls()\n for key, value in d.items():\n setattr(self, key, value)\n self._json = byte_string\n return self\n\n @classmethod\n def from_database(cls, db_book):\n return cls.from_json(db_book.content)\n\n def __str__(self):\n r = \"Book:\\n\"\n for key, value in vars(self).items():\n r += f\"{key}: {value}\\n\"\n return r\n\n def __repr__(self):\n return f\"Book({dir(self)})\"\n","repo_name":"AlexanderKosik/software_design_solution","sub_path":"python/domain/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36357414518","text":"#\n# Lacerda@UFSC - 30/Ago/2016\n#\nimport numpy as np\nimport matplotlib as mpl\nfrom .lines import Lines\nfrom .functions import debug_var\nfrom matplotlib import pyplot as plt\nfrom .functions import find_confidence_interval\n\n\ndef stats_med12sigma(x, y, bin_edges, prc=[5, 16, 50, 84, 95]):\n bin_edges = np.array(bin_edges)\n bin_center = (bin_edges[:-1] + bin_edges[1:]) / 2.0\n N_R = len(bin_center)\n yMean = np.ma.masked_all(bin_center.shape, dtype='float')\n npts = np.zeros(bin_center.shape, dtype='int')\n prc_stats = []\n for iR in range(N_R):\n left = bin_edges[iR]\n right = bin_edges[iR + 1]\n msk = np.bitwise_and(np.greater(x, left), np.less_equal(x, right))\n if msk.astype(int).sum():\n yTmp = y[msk]\n yMean[iR] = np.mean(yTmp)\n npts[iR] = len(yTmp)\n if prc is not None:\n prc_stats.append(np.percentile(y[msk], prc))\n else:\n prc_stats.append(None)\n else:\n if prc is not None:\n prc_stats.append([np.nan for i in range(len(prc))])\n else:\n prc_stats.append(None)\n # print(iR, prc_stats[-1], np.asarray(prc_stats).shape, np.asarray(prc_stats).T.shape)\n return yMean, np.asarray(prc_stats).T, bin_center, npts\n\n\ndef cmap_discrete(colors=[(1, 0, 0), (0, 1, 0), (0, 0, 1)], n_bins=None, cmap_name='myMap'):\n if n_bins == None:\n n_bins = len(colors)\n cm = mpl.colors.LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins)\n return cm\n\n\ndef plot_scatter_histo(x, y, xlim, ylim, xbins=30, ybins=30, xlabel='', ylabel='',\n c=None, cmap=None, figure=None, axScatter=None, axHistx=None, axHisty=None,\n scatter=True, histox=True, histoy=True, s=1, histtype='barstacked'):\n from matplotlib.ticker import NullFormatter\n nullfmt = NullFormatter() # no labels\n if axScatter is None:\n f = figure\n left, width = 0.1, 0.8\n # left, width = 0.1, 0.65\n bottom, height = 0.1, 0.8\n # bottom, height = 0.1, 0.65\n if histox:\n height = 0.65\n if histoy:\n width = 0.65\n rect_scatter = [left, bottom, width, height]\n axScatter = f.add_axes(rect_scatter)\n if histox:\n bottomx = bottom + height + 0.02\n rect_histx = [left, bottomx, width, 0.2]\n axHistx = f.add_axes(rect_histx)\n if histoy:\n lefty = left + width + 0.02\n rect_histy = [lefty, bottom, 0.2, height]\n axHisty = f.add_axes(rect_histy)\n if scatter:\n if isinstance(x, list):\n for X, Y, C in zip(x, y, c):\n axScatter.scatter(X, Y, rasterized=True, c=C, s=s, cmap=cmap, marker='o', edgecolor='none')\n else:\n axScatter.scatter(x, y, c=c, s=s, rasterized=True, cmap=cmap, marker='o', edgecolor='none')\n axScatter.set_xlim(xlim)\n axScatter.set_ylim(ylim)\n axScatter.set_xlabel(xlabel)\n axScatter.set_ylabel(ylabel)\n if histox:\n axHistx.hist(x, bins=xbins, range=xlim, color=c, histtype=histtype)\n axHistx.xaxis.set_major_formatter(nullfmt) # no labels\n axHistx.set_xlim(xlim)\n if histoy:\n axHisty.hist(y, bins=ybins, range=ylim, orientation='horizontal', color=c, histtype=histtype)\n axHisty.yaxis.set_major_formatter(nullfmt) # no labels\n plt.setp(axHisty.xaxis.get_majorticklabels(), rotation=270)\n axHisty.set_ylim(ylim)\n # axHisty.set_xlim(axScatter.get_ylim())\n return axScatter, axHistx, axHisty\n\n\ndef plotWHAN(ax, N2Ha, WHa, z=None, cmap='viridis', mask=None, labels=True, N=False, cb_label=r'R [HLR]', vmax=None, vmin=None, dcontour=True):\n from .functions import ma_mask_xyz\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n if mask is None:\n mask = np.zeros_like(N2Ha, dtype=np.bool_)\n extent = [-1.6, 0.8, -1, 2.5]\n bottom, top, left, right = 0.18, 0.95, 0.08, 0.9\n if z is None:\n bins = [30, 30]\n xm, ym = ma_mask_xyz(N2Ha, np.ma.log10(WHa), mask=mask)\n if dcontour:\n density_contour(xm.compressed(), ym.compressed(), bins[0], bins[1], ax, range=[extent[0:2], extent[2:4]], colors=['b', 'y', 'r'])\n sc = ax.scatter(xm, ym, marker='o', c='0.5', s=10, edgecolor='none', alpha=0.4)\n ax.set_xlim(extent[0:2])\n ax.set_ylim(extent[2:4])\n else:\n xm, ym, z = ma_mask_xyz(N2Ha, np.ma.log10(WHa), z, mask=mask)\n # print(xm, ym, z)\n sc = ax.scatter(xm, ym, c=z, cmap=cmap, vmin=vmin, vmax=vmax, marker='o', s=1, edgecolor='none')\n ax.set_xlim(extent[0:2])\n ax.set_ylim(extent[2:4])\n # ax.set_aspect('equal', 'box')\n # the_divider = make_axes_locatable(ax)\n # color_axis = the_divider.append_axes('right', size='5%', pad=0)\n # cb = plt.colorbar(sc, cax=color_axis)\n # # cb = plt.colorbar(sc, ax=ax, ticks=[0, .5, 1, 1.5, 2, 2.5, 3], pad=0)\n # cb.set_label(cb_label)\n cb_ax = f.add_axes([right, bottom, 0.02, top-bottom])\n cb = plt.colorbar(sc, cax=cb_ax)\n cb.set_label(r'$\\log\\ {\\rm W}_{{\\rm H}\\alpha}$', fontsize=fs+4)\n cb_ax.tick_params(direction='in')\n cb.locator = MaxNLocator(4)\n cb.update_ticks()\n if labels:\n xlabel = r'$\\log [NII]/H\\alpha$'\n ylabel = r'$\\log WH\\alpha$'\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n if not N:\n N = xm.count()\n c = ''\n if (xm.compressed() < extent[0]).any():\n c += 'x-'\n if (xm.compressed() > extent[1]).any():\n c += 'x+'\n if (ym.compressed() < extent[2]).any():\n c += 'y-'\n if (ym.compressed() > extent[3]).any():\n c += 'y+'\n # plt.axis(extent)\n # plt.axis(extent)\n plot_text_ax(ax, '%d %s' % (N, c), 0.01, 0.99, 20, 'top', 'left', 'k')\n ax.plot((-0.4, -0.4), (np.log10(3), 3), 'k-')\n ax.plot((-0.4, extent[1]), np.ma.log10([6, 6]), 'k-')\n ax.axhline(y=np.log10(3), c='k')\n p = [np.log10(0.5/5.0), np.log10(0.5)]\n xini = (np.log10(3.) - p[1]) / p[0]\n ax.plot((xini, 0.), np.polyval(p, [xini, 0.]), 'k:')\n ax.plot((0, extent[1]), np.log10([0.5, 0.5]), 'k:')\n ax.text(-1.4, 0.75, 'SF')\n ax.text(0.07, 0.9, 'sAGN')\n ax.text(0.05, 0.55, 'wAGN')\n ax.text(0.25, 0.0, 'RG')\n ax.text(-0.8, 0, 'PG')\n return ax\n\n\ndef plotBPT(ax, N2Ha, O3Hb, z=None, cmap='viridis', mask=None, labels=True, N=False, cb_label=r'R [HLR]', vmax=None, vmin=None, dcontour=True):\n from .functions import ma_mask_xyz\n from mpl_toolkits.axes_grid1 import make_axes_locatable\n if mask is None:\n mask = np.zeros_like(O3Hb, dtype=np.bool_)\n extent = [-1.5, 1, -1.5, 1.5]\n if z is None:\n bins = [30, 30]\n xm, ym = ma_mask_xyz(N2Ha, O3Hb, mask=mask)\n if dcontour:\n density_contour(xm.compressed(), ym.compressed(), bins[0], bins[1], ax, range=[extent[0:2], extent[2:4]], colors=['b', 'y', 'r'])\n sc = ax.scatter(xm, ym, marker='o', c='0.5', s=10, edgecolor='none', alpha=0.4)\n ax.set_xlim(extent[0:2])\n ax.set_ylim(extent[2:4])\n else:\n xm, ym, z = ma_mask_xyz(N2Ha, O3Hb, z, mask=mask)\n sc = ax.scatter(xm, ym, c=z, cmap=cmap, vmin=vmin, vmax=vmax, marker='o', s=10, edgecolor='none')\n ax.set_xlim(extent[0:2])\n ax.set_ylim(extent[2:4])\n ax.set_aspect('equal', 'box')\n the_divider = make_axes_locatable(ax)\n color_axis = the_divider.append_axes('right', size='5%', pad=0)\n cb = plt.colorbar(sc, cax=color_axis)\n # cb = plt.colorbar(sc, ax=ax, ticks=[0, .5, 1, 1.5, 2, 2.5, 3], pad=0)\n cb.set_label(cb_label)\n if labels:\n ax.set_xlabel(r'$\\log\\ [NII]/H\\alpha$')\n ax.set_ylabel(r'$\\log\\ [OIII]/H\\beta$')\n L = Lines()\n if not N:\n N = xm.count()\n c = ''\n if (xm.compressed() < extent[0]).any():\n c += 'x-'\n if (xm.compressed() > extent[1]).any():\n c += 'x+'\n if (ym.compressed() < extent[2]).any():\n c += 'y-'\n if (ym.compressed() > extent[3]).any():\n c += 'y+'\n plot_text_ax(ax, '%d %s' % (N, c), 0.01, 0.99, 20, 'top', 'left', 'k')\n plot_text_ax(ax, 'S06', 0.30, 0.02, 20, 'bottom', 'left', 'k')\n plot_text_ax(ax, 'K03', 0.53, 0.02, 20, 'bottom', 'left', 'k')\n plot_text_ax(ax, 'K01', 0.85, 0.02, 20, 'bottom', 'right', 'k')\n plot_text_ax(ax, 'CF10', 0.92, 0.98, 20, 'top', 'right', 'k', rotation=38) # 44.62)\n ax.plot(L.x['S06'], L.y['S06'], 'k-', label='S06')\n ax.plot(L.x['K03'], L.y['K03'], 'k-', label='K03')\n ax.plot(L.x['K01'], L.y['K01'], 'k-', label='K01')\n ax.plot(L.x['CF10'], L.y['CF10'], 'k-', label='CF10')\n L.fixCF10('S06')\n return ax\n\n\ndef add_subplot_axes(ax, rect, facecolor='w'):\n fig = plt.gcf()\n box = ax.get_position()\n width = box.width\n height = box.height\n inax_position = ax.transAxes.transform(rect[0:2])\n transFigure = fig.transFigure.inverted()\n infig_position = transFigure.transform(inax_position)\n x = infig_position[0]\n y = infig_position[1]\n width *= rect[2]\n height *= rect[3]\n subax = fig.add_axes([x, y, width, height], facecolor=facecolor)\n x_labelsize = subax.get_xticklabels()[0].get_size()\n y_labelsize = subax.get_yticklabels()[0].get_size()\n x_labelsize *= rect[2] ** 0.5\n y_labelsize *= rect[3] ** 0.5\n subax.xaxis.set_tick_params(labelsize=x_labelsize)\n subax.yaxis.set_tick_params(labelsize=y_labelsize)\n return subax\n\n# ex:\n# density_contour(xm.compressed(), ym.compressed(), binsx, binsy, ax, range=[extent[0:2], extent[2:4]], colors=['b', 'y', 'r'])\ndef density_contour(xdata, ydata, binsx, binsy, ax=None, levels_confidence=[0.68, 0.95, 0.99], range=None, **contour_kwargs):\n \"\"\" Create a density contour plot.\n Parameters\n ----------\n xdata : numpy.ndarray\n ydata : numpy.ndarray\n binsx : int\n Number of bins along x dimension\n binsy : int\n Number of bins along y dimension\n ax : matplotlib.Axes (optional)\n If supplied, plot the contour to this axis. Otherwise, open a new figure\n contour_kwargs : dict\n kwargs to be passed to pyplot.contour()\n \"\"\"\n import scipy.optimize as so\n # nbins_x = len(binsx) - 1\n # nbins_y = len(binsy) - 1\n H, xedges, yedges = np.histogram2d(xdata, ydata, bins=[binsx, binsy], range=range, normed=True)\n x_bin_sizes = (xedges[1:] - xedges[:-1])\n y_bin_sizes = (yedges[1:] - yedges[:-1])\n pdf = (H * (x_bin_sizes * y_bin_sizes))\n levels = [so.brentq(find_confidence_interval, 0., 1., args=(pdf, lvl)) for lvl in levels_confidence]\n # one_sigma = so.brentq(find_confidence_interval, 0., 1., args = (pdf, 0.68))\n # two_sigma = so.brentq(find_confidence_interval, 0., 1., args = (pdf, 0.95))\n # three_sigma = so.brentq(find_confidence_interval, 0., 1., args = (pdf, 0.99))\n # levels = [one_sigma, two_sigma, three_sigma]\n X, Y = 0.5 * (xedges[1:] + xedges[:-1]), 0.5 * (yedges[1:] + yedges[:-1])\n Z = pdf.T\n if ax is None:\n contour = plt.tricontour(X, Y, Z, levels=levels[::-1], origin=\"lower\", **contour_kwargs)\n else:\n # contour = ax.contour(X, Y, Z, levels=levels, origin=\"lower\", **contour_kwargs)\n contour = ax.contour(X, Y, Z, levels=levels[::-1], origin=\"lower\", **contour_kwargs)\n return contour\n\n\ndef plot_spearmanr_ax(ax, x, y, pos_x=0.01, pos_y=0.99, fontsize=10, verticalalignment='top', horizontalalignment='left', more_stats=False):\n from scipy.stats import spearmanr\n rhoSpearman, pvalSpearman = spearmanr(x, y)\n if more_stats:\n txt = ':%.3f - (y/x) median:%.3f - $\\sigma(y/x)$:%.3f - Rs: %.2f' % (np.mean(y / x), np.ma.median((y / x)), np.ma.std(y / x), rhoSpearman)\n else:\n txt = 'Rs: %.2f' % (rhoSpearman)\n plot_text_ax(ax, txt, pos_x, pos_y, fontsize, verticalalignment, horizontalalignment)\n\n\ndef plot_OLSbisector_ax(ax, x, y, **kwargs):\n from .functions import OLS_bisector\n pos_x = kwargs.get('pos_x', 0.99)\n pos_y = kwargs.get('pos_y', 0.00)\n fontsize = kwargs.get('fontsize', kwargs.get('fs', 10))\n color = kwargs.get('color', kwargs.get('c', 'r'))\n rms = kwargs.get('rms', True)\n txt = kwargs.get('text', True)\n kwargs_plot = dict(c=color, ls='-', lw=1.5, label='')\n kwargs_plot.update(kwargs.get('kwargs_plot', {}))\n label = kwargs_plot['label']\n x_rms = kwargs.get('x_rms', x)\n y_rms = kwargs.get('y_rms', y)\n OLS = kwargs.get('OLS', None)\n va = kwargs.get('verticalalignment', kwargs.get('va', 'bottom'))\n ha = kwargs.get('horizontalalignment', kwargs.get('ha', 'right'))\n plotOLS = kwargs.get('plotOLS', True)\n if OLS is None:\n a, b, sigma_a, sigma_b = OLS_bisector(x, y)\n else:\n a = x\n b = y\n sigma_a = None\n sigma_b = sigma_a\n Yrms_str = ''\n if rms:\n Yrms = (y_rms - (a * x_rms + b)).std()\n Yrms_str = r'(rms:%.3f)' % Yrms\n if plotOLS:\n ax.plot(ax.get_xlim(), a * np.asarray(ax.get_xlim()) + b, **kwargs_plot)\n if b > 0:\n txt_y = r'$y_{OLS}$ = %.2f$x$ + %.2f %s' % (a, b, Yrms_str)\n else:\n txt_y = r'$y_{OLS}$ = %.2f$x$ - %.2f %s' % (a, b * -1., Yrms_str)\n debug_var(True, y_OLS=txt_y)\n if txt:\n txt_y = '%s (%.3f, %.3f, %.3f)' % (label, a, b, Yrms)\n plot_text_ax(ax, txt_y, pos_x, pos_y, fontsize, va, ha, color=color)\n else:\n print(txt_y)\n return a, b, sigma_a, sigma_b\n\n\ndef plot_text_ax(ax, txt, xpos=0.99, ypos=0.01, fontsize=10, va='bottom', ha='right', color='k', **kwargs):\n xpos = kwargs.get('pos_x', xpos)\n ypos = kwargs.get('pos_y', ypos)\n fontsize = kwargs.get('fontsize', kwargs.get('fs', fontsize))\n va = kwargs.get('verticalalignment', kwargs.get('va', va))\n ha = kwargs.get('horizontalalignment', kwargs.get('ha', ha))\n color = kwargs.get('color', kwargs.get('c', color))\n alpha = kwargs.get('alpha', 1.)\n textbox = dict(boxstyle='round', facecolor='wheat', alpha=0.)\n transform = kwargs.get('transform', True)\n rot = kwargs.get('rotation', 0)\n if transform is True:\n ax.text(xpos, ypos, txt, fontsize=fontsize, color=color,\n transform=ax.transAxes,\n verticalalignment=va, horizontalalignment=ha,\n bbox=textbox, alpha=alpha, rotation=rot)\n else:\n ax.text(xpos, ypos, txt, fontsize=fontsize, color=color,\n verticalalignment=va, horizontalalignment=ha,\n bbox=textbox, alpha=alpha, rotation=rot)\n\n\ndef plot_histo_stats_txt(x, first=False, dataset_name=None, range=None, use_range_stats=False):\n if use_range_stats:\n xm = np.ma.masked_array(x, mask=~((x >= range[0]) & (x <= range[1])))\n x = xm.compressed()\n if first:\n txt = [r'$N(x)$: %d' % len(x),]\n # r'$$: %.3f' % np.mean(x), r'med($x$): %.3f' % np.median(x),\n # r'$\\sigma(x)$: %.3f' % np.std(x), r'max$(x)$: %.3f' % np.max(x),\n # r'min$(x)$: %.3f' % np.min(x)]\n first = False\n else:\n if len(x) > 0:\n txt = ['%d' % len(x), ]\n # '%.3f' % np.mean(x), '%.3f' % np.median(x),\n # '%.3f' % np.std(x), '%.3f' % np.max(x), '%.3f' % np.min(x)]\n else:\n txt = ['0', ] # '0', '0', '0', '0', '0']\n if dataset_name is not None:\n txt.insert(0, dataset_name)\n return txt, first\n\n\ndef plot_histo_ax(ax, x_dataset, **kwargs):\n first = kwargs.get('first', False)\n va = kwargs.get('verticalalignment', kwargs.get('va', 'top'))\n ha = kwargs.get('horizontalalignment', kwargs.get('ha', 'right'))\n fs = kwargs.get('fontsize', kwargs.get('fs', 8))\n stats_txt = kwargs.get('stats_txt', True)\n pos_x = kwargs.get('pos_x', 0.98)\n y_v_space = kwargs.get('y_v_space', 0.08)\n y_h_space = kwargs.get('y_h_space', 0.1)\n ini_pos_y = kwargs.get('ini_pos_y', 0.96)\n kwargs_histo = dict(bins=30, range=None, color='b', align='mid', alpha=0.6, histtype='bar', normed=False)\n kwargs_histo.update(kwargs.get('kwargs_histo', {}))\n c = kwargs.get('c', kwargs_histo.get('color', 'b'))\n histo = kwargs.get('histo', True)\n use_range_stats = kwargs.get('use_range_stats', False)\n dataset_names = kwargs.get('dataset_names', None)\n return_text_list = kwargs.get('return_text_list', False)\n return_histo_vars = kwargs.get('return_histo_vars', False)\n text_list = []\n if histo:\n _n, _bins, _patches = ax.hist(x_dataset, **kwargs_histo)\n n_elem = 1\n if dataset_names is not None:\n n_elem += 1\n pos_y = [ini_pos_y - (i * y_v_space) for i in xrange(n_elem)]\n if isinstance(x_dataset, list):\n for i, x in enumerate(x_dataset):\n if dataset_names is None:\n txt, first = plot_histo_stats_txt(x, first, use_range_stats=use_range_stats, range=kwargs_histo['range'])\n else:\n txt, first = plot_histo_stats_txt(x, first, dataset_names[i], use_range_stats=use_range_stats, range=kwargs_histo['range'])\n text_list.append(txt)\n if stats_txt:\n for j, pos in enumerate(pos_y):\n plot_text_ax(ax, txt[j], **dict(pos_x=pos_x, pos_y=pos, fs=fs, va=va, ha=ha, c=c[i]))\n pos_x -= y_h_space\n else:\n txt, first = plot_histo_stats_txt(x_dataset, first, dataset_names, use_range_stats=use_range_stats, range=kwargs_histo['range'])\n text_list.append(txt)\n if stats_txt:\n for i, pos in enumerate(pos_y):\n plot_text_ax(ax, txt[i], **dict(pos_x=pos_x, pos_y=pos, fs=fs, va=va, ha=ha, c=c))\n if return_text_list:\n if return_histo_vars:\n return ax, text_list, _n, _bins, _patches\n else:\n return ax, text_list\n if return_histo_vars:\n return ax, _n, _bins, _patches\n return ax\n\n\ndef next_row_col(row, col, N_rows, N_cols):\n if col == (N_cols - 1):\n col = 0\n row += 1\n if (row == N_rows):\n row = 0\n else:\n col += 1\n return row, col\n\n\ndef plot_percentiles_ax(ax, x, y, **kwargs):\n median_kwargs = kwargs.pop('median_kwargs', kwargs)\n ax.plot(x, np.median(y), **median_kwargs)\n ax.plot(x, np.percentile(y, 5), **kwargs)\n ax.plot(x, np.percentile(y, 16), **kwargs)\n ax.plot(x, np.percentile(y, 84), **kwargs)\n ax.plot(x, np.percentile(y, 95), **kwargs)\n","repo_name":"elacerda/pytu","sub_path":"src/pytu/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":18398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4814460981","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 13 11:38:28 2020\r\n\r\n@author: matth\r\n\r\nThis script should load a master data set of Co, Cs, Ir data,\r\ndivide into isotope specific data sets,\r\nand allow for training/testing on various combinations using\r\na stratified k fold split\r\n\r\nDataset is stored locally at the defined Path\r\n\"\"\"\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn import neighbors\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\nfrom sklearn.utils import shuffle\r\nfrom sklearn.model_selection import StratifiedShuffleSplit,StratifiedKFold\r\nimport os\r\n#%% Load data\r\npath = \"E:\\\\MattD\\\\NSS_DD\"\r\nos.chdir(path)\r\nprint(\"Loading data...\")\r\nsim_data = np.load('dataset_CoCsIr.npy')\r\nib_l, ib_u = 0, 10 # input features for isotope\r\ndb_l, db_u = 10, 14 # input features for detector totals\r\nab = -2 # angle \r\nrb = 3 # radius\r\n\r\n#%% Create Isotope specific data\r\n\"\"\"\r\nThe main dataset has 10,000 trials each of Co, Cs, Ir, each with\r\nthe same labels (angles). Thus 3 xa's are created, and only one ya.\r\n\"\"\"\r\nxa_co = sim_data[:10000,db_l:db_u]/np.sum(sim_data[:10000,db_l:db_u], axis=1)[:, None]\r\nxa_cs = sim_data[10000:20000,db_l:db_u]/np.sum(sim_data[10000:20000,db_l:db_u], axis=1)[:, None]\r\nxa_ir = sim_data[20000:,db_l:db_u]/np.sum(sim_data[20000:,db_l:db_u], axis=1)[:, None]\r\nya = np.round(sim_data[:10000,ab])\r\nra = sim_data[:10000,rb]\r\n\r\n#%% KNN - Stratified K Fold\r\nnfold_a = 5\r\nknn_a = neighbors.KNeighborsClassifier(n_neighbors=5, n_jobs=-1)\r\nskf_a = StratifiedKFold(n_splits=nfold_a, shuffle=True)\r\n\r\n# Train on Co, test on Co\r\nprint(\"Train/test: Co/Co\")\r\nfor fno, (train_index, test_index) in enumerate(skf_a.split(xa_co, ya)):\r\n print(\"folding\", fno+1, \"/\", nfold_a)\r\n xa_tr, ya_tr, ra_tr = xa_co[train_index], ya[train_index], ra[train_index]\r\n xa_ts, ya_ts, ra_ts = xa_co[test_index], ya[test_index], ra[test_index]\r\n knn_a.fit(xa_tr, ya_tr)\r\n pred_a = knn_a.predict(xa_ts)\r\n acc_a = accuracy_score(ya_ts, pred_a)\r\n print(\"Accuracy: \", acc_a)\r\n \r\n# Train on Co, test on Cs\r\nprint(\"Train/test: Co/Cs\")\r\nfor fno, (train_index, test_index) in enumerate(skf_a.split(xa_co, ya)):\r\n print(\"folding\", fno+1, \"/\", nfold_a)\r\n xa_tr, ya_tr, ra_tr = xa_co[train_index], ya[train_index], ra[train_index]\r\n xa_ts, ya_ts, ra_ts = xa_cs[test_index], ya[test_index], ra[test_index]\r\n knn_a.fit(xa_tr, ya_tr)\r\n pred_a = knn_a.predict(xa_ts)\r\n acc_a = accuracy_score(ya_ts, pred_a)\r\n print(\"Accuracy: \", acc_a)\r\n","repo_name":"matthewdurbin/MattDD","sub_path":"KNN_By_Isotope.py","file_name":"KNN_By_Isotope.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29507719481","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated by Yuki Sumi on Jan 23 2023\r\n\"\"\"\r\n# installing modules\r\n\r\n# numpy https://numpy.org\r\n# To install,\r\n# pip install numpy\r\n# or\r\n# conda install numpy\r\n\r\n# pandas https://pandas.pydata.org\r\n# To install,\r\n# pip install pandas\r\n# or\r\n# conda install -c conda-forge pandas\r\n\r\n# tensorflow https://www.tensorflow.org/?hl=en\r\n# To install,\r\n# pip install tensorflow==2.10.0\r\n\r\n# tensorflow.js https://www.tensorflow.org/js?hl=en\r\n# To install,\r\n# pip install tensorflowjs==3.21.0\r\n\r\n# Matplotlib https://matplotlib.org\r\n# To install,\r\n# pip install matplotlib\r\n# conda install -c conda-forge matplotlib\r\n\r\n# scikit-learn https://scikit-learn.org/stable/\r\n# To install,\r\n# pip install -U scikit-learn \r\n# or\r\n# conda install -c conda-forge matplotlib\r\n\r\n# imbalanced-learn https://imbalanced-learn.org/stable/index.html\r\n# To install,\r\n# pip install -U imbalanced-learn\r\n# or\r\n# conda install -c conda-forge imbalanced-learn\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom tensorflow.keras.layers import Dense, LeakyReLU, BatchNormalization\r\nfrom tensorflow.keras.models import Sequential\r\n\r\n# the number of test data for the metrics\r\nnumber_of_test = 10\r\n\r\n# read the Mostgraph measurement results of respiratory normal subjects\r\n# Column of csv file consist of \"diagnosis\", \"gender\", \"R5in\", \"R5ex\", \"R20in\", \"R20ex\", \"X5in\", \"X5ex\", \"Fresin\", \"Fresex\", \"ALXin\", \"ALXex\"\r\nmostgraphdata = pd.read_csv(\"female,male_controldata_smart.csv\", encoding=\"utf-8\")\r\n# pandas -> numpy\r\nmostgraph_total_data_numpy = mostgraphdata.values\r\n# the number of data read\r\nnumber_of_normal_mostgraphdata = mostgraph_total_data_numpy.shape[0]\r\n# shuffle to make sequence random\r\nnp.random.shuffle(mostgraph_total_data_numpy)\r\n# extract test data\r\nmostgraph_normal_test_data_numpy = mostgraph_total_data_numpy[0:number_of_test]\r\n# extract train and validation data\r\nmostgraph_normal_train_data_numpy = mostgraph_total_data_numpy[number_of_test:number_of_normal_mostgraphdata]\r\n# apply oversampling to the respiratory normal subject\r\nmostgraph_normal_train_data_numpy_extended=np.tile(mostgraph_normal_train_data_numpy,(5, 1))\r\n\r\n# read the Mostgraph measurement results of asthmatics subjects\r\nmostgraphdata = pd.read_csv(\"female,male_patientsdata_smart.csv\", encoding=\"utf-8\")\r\n# pandas -> numpy\r\nmostgraph_total_data_numpy = mostgraphdata.values\r\n# shuffle to make sequence random\r\nnp.random.shuffle(mostgraph_total_data_numpy)\r\n# the number of data read\r\nnumber_of_abnormal_mostgraphdata = mostgraph_total_data_numpy.shape[0]\r\n# extract test data\r\nmostgraph_abnormal_test_data_numpy = mostgraph_total_data_numpy[0:number_of_test]\r\n# extract train and validation data\r\nmostgraph_abnormal_train_data_numpy = mostgraph_total_data_numpy[number_of_test:number_of_abnormal_mostgraphdata]\r\n\r\n# combine respiratory normal and asthmatics subjects of train and validation data\r\nmostgraph_train_data_numpy = np.concatenate([mostgraph_normal_train_data_numpy_extended, mostgraph_abnormal_train_data_numpy])\r\n# shuffle to make sequence random\r\nnp.random.shuffle(mostgraph_train_data_numpy)\r\n\r\n#Correct for data imbalance\r\nnumber_of_normal_mostgraphdata_extended = mostgraph_normal_train_data_numpy_extended.shape[0]\r\nnumber_of_normal_mostgraphdata = number_of_normal_mostgraphdata_extended - number_of_test\r\nnumber_of_abnormal_mostgraphdata = number_of_abnormal_mostgraphdata - number_of_test\r\ninitial_bias = np.log([number_of_abnormal_mostgraphdata / number_of_normal_mostgraphdata])\r\nprint(\"Initial bias: {:.5f}\".format(initial_bias[0]))\r\nnumber_of_total_train_mostgraphdata = number_of_normal_mostgraphdata + number_of_abnormal_mostgraphdata\r\nweight_for_0 = (1 / number_of_normal_mostgraphdata) * (number_of_total_train_mostgraphdata) / 2.0\r\nweight_for_1 = (1 / number_of_abnormal_mostgraphdata) * (number_of_total_train_mostgraphdata) / 2.0\r\nclass_weight = {0: weight_for_0, 1: weight_for_1}\r\nprint(\"Weight for class 0: {:.2f}\".format(weight_for_0))\r\nprint(\"Weight for class 1: {:.2f}\".format(weight_for_1))\r\n\r\n# \"diagnosis\"\r\nlabels_train = mostgraph_train_data_numpy[ : , 0:1]\r\n# \"gender\", \"R5in\", \"R5ex\", \"R20in\", \"R20ex\", \"X5in\", \"X5ex\", \"Fresin\", \"Fresex\", \"ALXin\", \"ALXex\"\r\ndata_train = mostgraph_train_data_numpy[ : , 1:12]\r\n\r\n# define deep learning model\r\nmodel = Sequential()\r\nmodel.add(Dense(units=128, input_shape=(11,)))\r\nmodel.add(BatchNormalization())\r\nmodel.add(LeakyReLU(alpha=0.2))\r\nmodel.add(Dense(units=64))\r\nmodel.add(BatchNormalization())\r\nmodel.add(LeakyReLU(alpha=0.2))\r\nmodel.add(Dense(units=32))\r\nmodel.add(BatchNormalization())\r\nmodel.add(LeakyReLU(alpha=0.2))\r\nmodel.add(Dense(units=16))\r\nmodel.add(BatchNormalization())\r\nmodel.add(LeakyReLU(alpha=0.2))\r\nmodel.add(Dense(1, activation='sigmoid'))\r\nmodel.compile(loss='binary_crossentropy', optimizer='Adam', metrics=[\"accuracy\"])\r\nmodel.summary() \r\n\r\n# train the model\r\nmodel_history = model.fit(data_train, labels_train, class_weight=class_weight, batch_size = 32, epochs = 2500, validation_split = 0.05)\r\n\r\n# display trainig statistics\r\nhistory_dict = model_history.history\r\n# load Loss\r\nloss_values = history_dict['loss']\r\nval_loss_values = history_dict['val_loss']\r\n# load Accaracy\r\nacc = history_dict['accuracy']\r\nval_acc = history_dict['val_accuracy']\r\n# make list from 1 to epoch\r\nepochlist = range(1, len(loss_values) +1)\r\n# write graph\r\nplt.plot(epochlist, acc, 'go', label='Accuracy at training')\r\nplt.plot(epochlist, val_acc, 'b', label='Accuracy at validation')\r\nplt.plot(epochlist, loss_values, 'mo', label='Loss at training')\r\nplt.plot(epochlist, val_loss_values, 'r', label='Loss at validation')\r\n# title\r\nplt.title('Training and Validation')\r\nplt.xlabel('Epochs')\r\nplt.legend()\r\n# display and save\r\nplt.savefig(\"Training.jpg\", dpi=2400)\r\nplt.show()\r\n\r\n\r\n# test the model for \r\nlabels_test = mostgraph_normal_test_data_numpy[ : , 0:1]\r\ndata_test = mostgraph_normal_test_data_numpy[ : , 1:14]\r\nloss, accuracy = model.evaluate(data_test, labels_test)\r\nprint(\"Accuracy for normal= {:.2f}\".format(accuracy))\r\npredicted = model.predict(data_test)\r\nprint(\"predicted for normal:\", predicted)\r\n#print(data_test)\r\n\r\nlabels_test = mostgraph_abnormal_test_data_numpy[ : , 0:1]\r\ndata_test = mostgraph_abnormal_test_data_numpy[ : , 1:14]\r\nloss, accuracy = model.evaluate(data_test, labels_test)\r\nprint(\"Accuracy for abnormal= {:.2f}\".format(accuracy))\r\npredicted = model.predict(data_test)\r\nprint(\"predicted for abnormal:\", predicted)\r\n#print(data_test)\r\n\r\n# save the trained model for python\r\nmodel.save(\"deeplearing_model\")\r\n# save the trained model for javascript\r\n#import tensorflowjs as tfjs\r\n#tfjs.converters.save_keras_model(model, \"./mostgraph_model\")\r\n","repo_name":"sumi-yuki/mostgraph","sub_path":"deeplearning-mostgraph.py","file_name":"deeplearning-mostgraph.py","file_ext":"py","file_size_in_byte":6685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40701196930","text":"# coding=utf8\n\nimport os\nimport codecs\nimport logging\n\nimport l20n.format.ast as FTL\nfrom l20n.format.parser import FTLParser\nfrom l20n.format.serializer import FTLSerializer\nfrom l20n.util import fold\ntry:\n from compare_locales.parser import getParser\nexcept ImportError:\n def getParser(path):\n raise RuntimeError('compare-locales required')\n\nfrom .cldr import get_plural_categories\nfrom .transforms import SOURCE\nfrom .merge import merge_resource\nfrom .util import get_entity\n\n\nclass MergeContext(object):\n \"\"\"Stateful context for merging translation resources.\n\n `MergeContext` must be configured with the target language and the\n directory locations of the input data.\n\n The transformation takes four types of input data:\n\n - The en-US FTL reference files which will be used as templates for\n message order, comments and sections.\n\n - The current FTL files for the given language.\n\n - The legacy (DTD, properties) translation files for the given\n language. The translations from these files will be transformed\n into FTL and merged into the existing FTL files for this language.\n\n - A list of `FTL.Entity` objects some of whose nodes are special\n operation nodes: CONCAT, EXTERNAL, LITERAL, LITERAL_FROM, PLURALS,\n PLURALS_FROM, REPLACE, REPLACE_FROM, SOURCE.\n \"\"\"\n\n def __init__(self, lang, reference_dir, localization_dir):\n self.ftl_parser = FTLParser()\n self.ftl_serializer = FTLSerializer()\n\n # An iterable of plural category names relevant to the context's\n # language. E.g. ('one', 'other') for English.\n self.plural_categories = get_plural_categories(lang)\n\n # Paths to directories with input data, relative to CWD.\n self.reference_dir = reference_dir\n self.localization_dir = localization_dir\n\n # Parsed input resources stored by resource path.\n self.reference_resources = {}\n self.localization_resources = {}\n\n # An iterable of `FTL.Entity` objects some of whose nodes can be the\n # transform operations.\n self.transforms = {}\n\n # A dict whose keys are `(path, key)` tuples corresponding to target\n # FTL translations, and values are sets of `(path, key)` tuples\n # corresponding to localized entities which will be migrated.\n self.dependencies = {}\n\n def read_ftl_resource(self, path):\n \"\"\"Read an FTL resource and parse it into an AST.\"\"\"\n f = codecs.open(path, 'r', 'utf8')\n try:\n contents = f.read()\n finally:\n f.close()\n\n ast, errors = self.ftl_parser.parse(contents)\n\n if len(errors):\n logger = logging.getLogger('migrate')\n for err in errors:\n logger.warn(u'Syntax error in {}: {}'.format(path, err))\n\n return ast\n\n def read_legacy_resource(self, path):\n \"\"\"Read a legacy resource and parse it into a dict.\"\"\"\n parser = getParser(path)\n parser.readFile(path)\n # Transform the parsed result which is an iterator into a dict.\n return {entity.key: entity.val for entity in parser}\n\n def add_reference(self, path, realpath=None):\n \"\"\"Add an FTL AST to this context's reference resources.\"\"\"\n fullpath = os.path.join(self.reference_dir, realpath or path)\n try:\n ast = self.read_ftl_resource(fullpath)\n except IOError as err:\n logger = logging.getLogger('migrate')\n logger.error(u'Missing reference file: {}'.format(path))\n raise err\n except UnicodeDecodeError as err:\n logger = logging.getLogger('migrate')\n logger.error(u'Error reading file {}: {}'.format(path, err))\n raise err\n else:\n self.reference_resources[path] = ast\n\n def add_localization(self, path):\n \"\"\"Add an existing localization resource.\n\n If it's an FTL resource, add an FTL AST. Otherwise, it's a legacy\n resource. Use a compare-locales parser to create a dict of (key,\n string value) tuples.\n \"\"\"\n fullpath = os.path.join(self.localization_dir, path)\n if fullpath.endswith('.ftl'):\n try:\n ast = self.read_ftl_resource(fullpath)\n except IOError:\n logger = logging.getLogger('migrate')\n logger.warn(u'Missing localization file: {}'.format(path))\n except UnicodeDecodeError as err:\n logger = logging.getLogger('migrate')\n logger.warn(u'Error reading file {}: {}'.format(path, err))\n else:\n self.localization_resources[path] = ast\n else:\n try:\n collection = self.read_legacy_resource(fullpath)\n except IOError:\n logger = logging.getLogger('migrate')\n logger.warn(u'Missing localization file: {}'.format(path))\n else:\n self.localization_resources[path] = collection\n\n def add_transforms(self, path, transforms):\n \"\"\"Define transforms for path.\n\n Each transform is an extended FTL node with `Transform` nodes as some\n values. Transforms are stored in their lazy AST form until\n `merge_changeset` is called, at which point they are evaluated to real\n FTL nodes with migrated translations.\n\n Each transform is scanned for `SOURCE` nodes which will be used to\n build the list of dependencies for the transformed message.\n \"\"\"\n def get_sources(acc, cur):\n if isinstance(cur, SOURCE):\n acc.add((cur.path, cur.key))\n return acc\n\n for node in transforms:\n # Scan `node` for `SOURCE` nodes and collect the information they\n # store into a set of dependencies.\n dependencies = fold(get_sources, node, set())\n # Set these sources as dependencies for the current transform.\n self.dependencies[(path, node.id.name)] = dependencies\n\n path_transforms = self.transforms.setdefault(path, [])\n path_transforms += transforms\n\n def get_source(self, path, key):\n \"\"\"Get an entity value from the localized source.\n\n Used by the `SOURCE` transform.\n \"\"\"\n if path.endswith('.ftl'):\n resource = self.localization_resources[path]\n return get_entity(resource.entities(), key)\n else:\n resource = self.localization_resources[path]\n return resource.get(key, None)\n\n def merge_changeset(self, changeset=None):\n \"\"\"Return a generator of FTL ASTs for the changeset.\n\n The input data must be configured earlier using the `add_*` methods.\n if given, `changeset` must be a set of (path, key) tuples describing\n which legacy translations are to be merged.\n\n Given `changeset`, return a dict whose keys are resource paths and\n values are `FTL.Resource` instances. The values will also be used to\n update this context's existing localization resources.\n \"\"\"\n\n if changeset is None:\n # Merge all known legacy translations.\n changeset = {\n (path, key)\n for path, strings in self.localization_resources.iteritems()\n for key in strings.iterkeys()\n }\n\n for path, reference in self.reference_resources.iteritems():\n current = self.localization_resources.get(path, FTL.Resource())\n transforms = self.transforms.get(path, [])\n\n def in_changeset(ident):\n \"\"\"Check if entity should be merged.\n\n If at least one dependency of the entity is in the current\n set of changeset, merge it.\n \"\"\"\n message_deps = self.dependencies.get((path, ident), None)\n\n # Don't merge if we don't have a transform for this message.\n if message_deps is None:\n return False\n\n # As a special case, if a transform exists but has no\n # dependecies, it's a hardcoded `FTL.Node` which doesn't\n # migrate any existing translation but rather creates a new\n # one. Merge it.\n if len(message_deps) == 0:\n return True\n\n # If the intersection of the dependencies and the current\n # changeset is non-empty, merge this message.\n return message_deps & changeset\n\n # Merge legacy translations with the existing ones using the\n # reference as a template.\n snapshot = merge_resource(\n self, reference, current, transforms, in_changeset\n )\n\n # If none of the transforms is in the given changeset, the merged\n # snapshot is identical to the current translation. We compare\n # JSON trees rather then use filtering by `in_changeset` to account\n # for translations removed from `reference`.\n if snapshot.toJSON() == current.toJSON():\n continue\n\n # Store the merged snapshot on the context so that the next merge\n # already takes it into account as the existing localization.\n self.localization_resources[path] = snapshot\n\n # The result for this path is a complete `FTL.Resource`.\n yield path, snapshot\n\n def serialize_changeset(self, changeset):\n \"\"\"Return a dict of serialized FTLs for the changeset.\n\n Given `changeset`, return a dict whose keys are resource paths and\n values are serialized FTL snapshots.\n \"\"\"\n\n return {\n path: self.ftl_serializer.serialize(snapshot.toJSON())\n for path, snapshot in self.merge_changeset(changeset)\n }\n\n\nlogging.basicConfig()\n","repo_name":"l20n/python-l20n","sub_path":"l20n/migrate/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":9912,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"70954964005","text":"from math import factorial, sqrt\r\nimport time\r\n\r\n\r\nclass Number():\r\n def __init__(self, n, runtime=False):\r\n self.type = None\r\n self.n = None\r\n self.change_number(n)\r\n self.runtime = runtime\r\n self.start_time = 0\r\n self.end_time = 1\r\n\r\n def change_number(self, n):\r\n if type(n) == list:\r\n self.type = \"list\"\r\n ret = n\r\n\r\n elif type(n) == int:\r\n self.type = \"int\"\r\n ret = n\r\n\r\n elif type(n) == str:\r\n try:\r\n ret = int(n)\r\n self.type = \"int\"\r\n except ValueError:\r\n print(\"not a valid input\")\r\n ret = None\r\n\r\n self.n = ret\r\n\r\n def number_function(self, function):\r\n if self.n != None:\r\n if self.runtime:\r\n self.start_time = time.time()\r\n\r\n if self.type == \"int\":\r\n ret = getattr(self, function)(self.n)\r\n\r\n elif self.type == \"list\":\r\n if len(self.n) == 1:\r\n ret = getattr(self, function)(self.n[0])\r\n elif len(self.n) > 1:\r\n ret = [getattr(self, function)(i) for i in self.n]\r\n\r\n if self.runtime:\r\n self.end_time = time.time()\r\n print(f\"-----\\nTIME ELAPSED : {self.end_time - self.start_time} s\\n-----\")\r\n\r\n return ret\r\n else:\r\n return (\"The number is not valid\")\r\n\r\n def catalan_number(self, n):\r\n return factorial(2 * n) // (factorial(n + 1) * factorial(n))\r\n\r\n def prime_number(self, n):\r\n if n == 1:\r\n return False\r\n for i in range(2, round(sqrt(n))):\r\n if n % i == 0:\r\n return False\r\n return True\r\n\r\n def parity(self, n):\r\n if int(repr(n)[-1]) in [0, 2, 4, 6, 8]:\r\n return (\"even\")\r\n else:\r\n return (\"odd\")\r\n\r\n def is_factorial(self, n):\r\n if n > 1:\r\n i = 1\r\n j = 1\r\n while i < n:\r\n j += 1\r\n i = i * j\r\n if i == n:\r\n return f\"{j}!\"\r\n\r\n return f\"{j - 1}! < {n} < {j}!\"\r\n\r\n elif n == 0:\r\n return False\r\n elif n == 1:\r\n return \"0!\"\r\n\r\n def is_perfect_square(self, n):\r\n return round(sqrt(n)) ** 2 == n\r\n\r\n def is_fibbonaci(self, n):\r\n if self.is_perfect_square(5 * (n ** 2) + 4) or self.is_perfect_square(5 * (n ** 2) - 4):\r\n return True\r\n else:\r\n return False\r\n","repo_name":"ArtiskOnGit/numbers","sub_path":"basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73971907686","text":"'''\r\n5001 Final Project Puzzle Game\r\nRuochen Liu\r\nProf K\r\n'''\r\nfrom turtle import *\r\nfrom Tile import Tile \r\nimport os\r\nimport math\r\nfrom Utility import *\r\nfrom Counter import Counter\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport time\r\n# import modules and classes\r\nt = Turtle() # set turtle to draw board\r\nscreen = Screen() # set screen \r\nCWD = os.getcwd() # get directory of the file\r\n\r\n\r\ndef setup():\r\n '''\r\n Function setup() is used to show the splash screen\\\r\n and the username and the moves user sets\r\n Parameter not needed\r\n Return two strings, username and moves\r\n '''\r\n screen.screensize(970,970)\r\n '''\r\n on my screen if I use screen.setup, the turtle screen will move\\\r\n to the top of my computer screen.\r\n After discussing it in the lab session with 2 TAs, I was suggested\\\r\n to use screensize instead. It may result to scrolling all the time\\\r\n But at least it works.\r\n '''\r\n splash = CWD + \"/Resources/splash_screen.gif\"\r\n screen.register_shape(splash)\r\n screen.delay(3000)\r\n t.shape(splash)\r\n screen.clear()\r\n t.clear()\r\n username = get_user_name()\r\n moves = get_steps()\r\n return username, moves\r\n\r\ndef puzzleboard():\r\n '''\r\n Function puzzleboard is used to create three boards\\\r\n and load symbols\r\n Parameter not needed\r\n Return None\r\n '''\r\n t.up() # hide the turtle's motion\r\n t.goto(-415, 415) # make sure the retangle is on the left \r\n t.down()# reshow the turtle\r\n t.color('black') # set the color\r\n t.pensize(3) # line thickness\r\n t.forward(430) # side 1\r\n t.right(90) \r\n t.forward(550) # side 2\r\n t.right(90)\r\n t.forward(430) # side 3\r\n t.right(90)\r\n t.forward(550) # side 4\r\n t.right(90)\r\n t.up() # hide the turtle's motion\r\n t.goto(30, 415)\r\n t.down()# reshow the turtle\r\n t.color('blue') # set the color\r\n t.pensize(3) # line thickness\r\n t.forward(300) # side 1\r\n t.right(90) \r\n t.forward(550) # side 2\r\n t.right(90)\r\n t.forward(300) # side 3\r\n t.right(90)\r\n t.forward(550) # side 4\r\n t.right(90)\r\n t.up() # hide the turtle's motion\r\n t.goto(-415, -250) # make sure the retangle is on the left \r\n t.down()# reshow the turtle\r\n t.color('black') # set the color\r\n t.pensize(3) # line thickness\r\n t.forward(745) # side 1\r\n t.right(90) \r\n t.forward(100) # side 2\r\n t.right(90)\r\n t.forward(745) # side 3\r\n t.right(90)\r\n t.forward(100) # side 4\r\n t.right(90)\r\n leader() \r\n load_winners()\r\n reset_symbol()\r\n load_symbol()\r\n quit_symbol()\r\n \r\n\r\ndef get_user_name():\r\n '''\r\n Function get_user_name is used to get username\r\n Parameter not needed\r\n Return user name\r\n '''\r\n return screen.textinput(\"CS5001 Puzzle Slider\", \"Your Name: \")\r\n \r\ndef get_steps():\r\n '''\r\n Function get_steps is used to get max moves the user wants\r\n Parameter not needed\r\n Return moves the user sets\r\n '''\r\n return screen.numinput(\"CS5001 Puzzle Slider-Moves\", \"Enter the moves(5 to 200): \",\\\r\n 5, minval=5, maxval=200)\r\n \r\n\r\ndef leader():\r\n '''\r\n Function leader is used to write leaders\r\n Parameter not needed\r\n Return None\r\n '''\r\n t.pencolor(\"black\")\r\n t.pensize(3)\r\n t.up()\r\n t.goto(50, 390)\r\n style = (\"Times New Roman\", 15, \"bold\")\r\n t.write(\"Leaders: \", font = style, align = \"left\")\r\n t.down()\r\n \r\n \r\ndef quit_symbol():\r\n '''\r\n Function quit_symbol is used to load quit button\r\n Parameter not needed\r\n Return None\r\n '''\r\n quit_symbol = CWD + \"/Resources/quitbutton.gif\"\r\n screen.register_shape(quit_symbol)\r\n quit_t = Turtle()\r\n quit_t.up()\r\n quit_t.goto(230, -300)\r\n quit_t.shape(quit_symbol)\r\n quit_t.down()\r\n\r\ndef load_symbol():\r\n '''\r\n Function load_symbol is used to load load button\r\n Parameter not needed\r\n Return None\r\n '''\r\n load_symbol = CWD + \"/Resources/loadbutton.gif\"\r\n screen.register_shape(load_symbol)\r\n load_t = Turtle()\r\n load_t.up()\r\n load_t.goto(130, -300)\r\n load_t.shape(load_symbol)\r\n load_t.down()\r\n\r\ndef reset_symbol():\r\n '''\r\n Function reset_symbol is used to load reset button\r\n Parameter not needed\r\n Return None\r\n '''\r\n reset_symbol = CWD + \"/Resources/resetbutton.gif\"\r\n screen.register_shape(reset_symbol)\r\n reset_t = Turtle()\r\n reset_t.up()\r\n reset_t.goto(30, -300)\r\n reset_t.shape(reset_symbol)\r\n reset_t.down()\r\n \r\ndef load_winners():\r\n '''\r\n Function load_winners is used to load winner name\\\r\n and their moves. It will only load the latest 4 winners\r\n '''\r\n t.up()\r\n t.goto(50, 330)\r\n t.down()\r\n style = (\"Times New Roman\", 15, \"bold\")\r\n content = []\r\n try:\r\n with open(\"leaderboard.txt\", \"r\") as in_file:\r\n for each in in_file:\r\n content.append(each)\r\n for i in content[-4:]:\r\n t.write(i, font = style, align = \"left\")\r\n t.up()\r\n t.right(90)\r\n t.forward(30)\r\n t.left(90)\r\n t.down()\r\n t.hideturtle()\r\n except IOError: # exception handling \r\n lead_error = CWD + \"/Resources/leaderboard_error.gif\"\r\n screen.register_shape(lead_error)\r\n leadturtle = Turtle()\r\n screen.delay(3000)\r\n leadturtle.shape(lead_error)\r\n screen.delay(0)\r\n leadturtle.hideturtle()\r\n with open(\"5001_puzzle.err\", \"a\") as out_file:\r\n # err file create or append to it \r\n out_file.write(f\"{time.ctime()}:Error: \" +\\\r\n f\"Could not open leaderboard.txt\"\\\r\n + f\" LOCATION: load_winners()\" + \"\\n\")\r\n \r\n \r\n \r\ndef main():\r\n username, moves = setup() # set up username and moves\r\n puzzleboard()# set up game board\r\n content, size, thumbnail = load_tile(\"mario.puz\")\r\n # load in puzzles\r\n size = int(size)\r\n set_original(content,size)\r\n # set tile original coordinates\r\n load_shuffled(content, size)\r\n # load tiles onto turtle screen\r\n thumbnail.set_position(275,415)\r\n # load thumbnail tiles\r\n thumbnail.stamp_image()\r\n totalmoves = Counter(moves) # create counters for totalmoves\r\n usermoves = Counter() # create usermoves counter\r\n t_shape = Turtle()\r\n t_moves = Turtle()\r\n t_moves.hideturtle()\r\n t_moves.up()\r\n t_moves.goto(-400, -317)# set turtle to the player move position\r\n t_moves.down()\r\n screenclick(content, thumbnail, totalmoves, username, \\\r\n usermoves, size, t_shape, t_moves, screen)\r\n # pull in screenclick effect\r\nif __name__ == \"__main__\":\r\n main()\r\n \r\n \r\n","repo_name":"villaliu/Python-Project","sub_path":"puzzle_game.py","file_name":"puzzle_game.py","file_ext":"py","file_size_in_byte":6724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35949594466","text":"from django.conf.urls import url, include\nfrom . import views\n\napp_name = 'plot'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^new/?$', views.create_plot, name='create'),\n url(r'^search/?$', views.search_plot, name='search'),\n url(r'^(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/?',\n include([\n url(r'^$', views.view_plot, name='details'),\n url(r'^edit/?$', views.edit_plot, name='edit'),\n url(r'^delete/?$', views.delete_plot, name='delete'),\n ])),\n]\n","repo_name":"eniehack/PylotHub","sub_path":"plot/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73803342246","text":"\r\n# cee lo simulation\r\nimport random\r\nfrom tqdm import tqdm\r\n\r\ndice = [1,2,3,4,5,6]\r\n\r\nwinner = []\r\n\r\nfor i in tqdm(range(10000000)):\r\n\r\n # get a valid roll\r\n while True:\r\n roll_1 = sorted(random.choices(dice,k=3)) \r\n if roll_1[0]!=roll_1[1]!=roll_1[2] and roll_1 not in [[1,2,3],[4,5,6]]: continue\r\n else: break\r\n\r\n # check for auto win\r\n if roll_1 in [[4,5,6],[1,1,6],[2,2,6],[3,3,6],[4,4,6],[5,5,6],[6,6,6]]:\r\n winner.append('bank')\r\n continue\r\n\r\n # check for auto loss\r\n if roll_1 in [[1,2,3],[1,1,1],[2,2,1],[3,3,1],[4,4,1],[5,5,1],[6,6,1]]:\r\n winner.append('player')\r\n continue\r\n \r\n if len(set(roll_1))==1:\r\n roll_1_point = roll_1[0]\r\n else:\r\n roll_1_point = [i for i in roll_1 if roll_1.count(i)==1][0]\r\n \r\n\r\n # get a valid player 2 roll\r\n while True:\r\n roll_2 = sorted(random.choices(dice,k=3)) \r\n if roll_2[0]!=roll_2[1]!=roll_2[2] and roll_2 not in [[1,2,3],[4,5,6]]: continue\r\n else: break\r\n\r\n # check for auto win\r\n if roll_2 in [[4,5,6],[1,1,6],[2,2,6],[3,3,6],[4,4,6],[5,5,6],[6,6,6]]:\r\n winner.append('player')\r\n continue\r\n\r\n # check for auto loss\r\n if roll_2 in [[1,2,3],[1,1,1],[2,2,1],[3,3,1],[4,4,1],[5,5,1],[6,6,1]]:\r\n winner.append('bank')\r\n continue\r\n\r\n # score the points\r\n if len(set(roll_2))==1:\r\n roll_2_point = roll_1[0]\r\n else:\r\n roll_2_point = [i for i in roll_2 if roll_2.count(i)==1][0]\r\n\r\n # get the winner\r\n if roll_2_point>roll_1_point:\r\n winner.append('player')\r\n else:\r\n winner.append('bank')\r\n\r\n\r\nprint(sum([1 for i in winner if i=='bank'])/len(winner)) \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":"negfrequency/ProbabilitySimulations","sub_path":"Cee Lo Simulation.py","file_name":"Cee Lo Simulation.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34021353960","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nTarbell project configuration\n\"\"\"\n\nfrom flask import Blueprint, g, render_template\n# import os.path # for testing for images\nimport jinja2 #for context-getting\n\nfrom itertools import ifilter # For the route\nfrom tarbell.hooks import register_hook #for the route, too\n\nimport archie # For refreshing archieml\n\nimport sys\nfrom os import path\nsys.path.append( path.dirname( path.abspath(__file__) ) )\nimport archie\n\n######### Specifically for the ArchieML\n\nimport htmlmin # to minify html\n\nimport codecs, archieml\nfrom subprocess import call\nfrom apiclient import errors\n\n# imports bc copied blueprint functions #\nfrom clint.textui import colored\n# import p2p\nfrom tarbell.utils import puts\nfrom tarbell.oauth import get_drive_api\n\n# To generate the urls with or without links\nfrom flask_frozen import Freezer, walk_directory\n\n# For the sidebar keyword search/replace\nimport re\n\n# Google document key for the stories. If not specified, the Archie stuff is skipped\nDOC_KEY = \"1NNNFdLZvKiSzG3t2NJ0Ls4YIGPaSq1oM5QhiMd-bYFM\"\n\n# Google spreadsheet key\nSPREADSHEET_KEY = \"1SQ_N8fyaimSvjMs62HyATD1CsnssDD7fVWKp14Ta7eQ\"\n\n\nblueprint = Blueprint('cps_abuse', __name__)\n\n# This is so we don't need to make physical html files for each one. \n\n@blueprint.route('//index.html')\n@blueprint.route('/')\n@blueprint.route('//')\ndef cps_abuse_story(slug):\n \"\"\"\n Make a page for each bar (side or main), based on the unique slug.\n \"\"\"\n site = g.current_site\n\n # get our production bucket for URL building\n bucket = site.project.S3_BUCKETS.get('production', '')\n data = site.get_context()\n rows = data.get('stories', [])\n\n # get the row we want, defaulting to an empty dictionary\n row = next(ifilter(lambda r: r['slug'] == slug, rows), {})\n\n print (\"fetching content for {}\".format(slug))\n \n if row != {}: \n if slug == \"student-offenders\":\n archie.get_drive_api_stuff(site, site.project.DOC_KEY)\n stories = archie.get_extra_context()\n return render_template('templates/_student-offenders.html', bucket=bucket, slug=slug, story_info=row, abuses=stories, **data)\n elif row[\"student_offenders\"] == 1:\n return render_template('templates/_student-offenders-sidebar-base.html', bucket=bucket, slug=slug, story_info=row,**data)\n else:\n return render_template('templates/_abuse-sidebar-base.html', bucket=bucket, slug=slug, story_info=row,**data)\n elif slug == \"404.html\":\n return render_template('404.html', bucket=bucket,**data)\n elif slug == \"ad-iframe.html\":\n return render_template('ad-iframe.html', bucket=bucket,foo=\"bar\", **data)\n elif slug == \"index.html\":\n return render_template('index.html', bucket=bucket,**data)\n else:\n return render_template('404.html', bucket=bucket,**data)\n\ndef story_urls():\n # \"Generate a URL for every story\"\n site = g.current_site\n data = site.get_context()\n stories = data.get('stories', [])\n \n for s in stories:\n yield(\"cps_abuse.cps_abuse_story\", {\"slug\": s['slug']})\n\n@register_hook('generate')\ndef register_stories(site, output_root, extra_context):\n # \"This runs before tarbell builds the static site\"\n site.freezer.register_generator(story_urls)\n\n\n\"\"\"\n################################################################\nFILTERS & FUNCTIONS //// #######################################\n################################################################\n\"\"\"\n\n@blueprint.app_template_filter('get_credits_list')\n# @jinja2.contextfilter\ndef get_authors(credits, credits_category):\n \"\"\"\n Takes the list of people who worked on the project and filters the list down to just those \n who particiapted on the particular aspect at hand (writing, design, etc.). It then sorts the\n list by display order (to appease editors) and within that, alpha by last name.\n \"\"\"\n # Sort the list by last-name alpha\n sorted_credits=sorted(credits, key=lambda i: i['name_last'])\n credits_to_use=[]\n\n for credit in sorted_credits:\n if credits_category in credit:\n # If the person is credited in this category by having any value at all\n credits_to_use.append(credit)\n \n # Now sort the credits to use by the ranking. \n # If they all have the same rank then the alpha \n # order will be preserved\n retval = sorted(credits_to_use, key=lambda i: i[credits_category])\n\n return retval\n\n\n@blueprint.app_template_filter('get_authors')\n@jinja2.contextfilter\ndef get_authors(context, slug):\n stories = context['stories']\n people = context['credits']\n\n story_authors = \"\"\n for story in stories:\n if story['slug'] == slug:\n try:\n # Try to nab the bylines\n story_authors = story['bylines'].split(',')\n except: \n # If this doesn't work, then skip this altogether\n # The macro will cease if it encounters false\n return False\n\n # Cycle through the plucked people in the order they are entered into the spreadsheet\n retval=[]\n # For each of the specififed authors ...\n for author in story_authors:\n # ... look through the list of credits for that person ...\n for person in people:\n # ... if we have a match, push the person.\n if author.strip() == person['id']:\n retval.append(person)\n return retval\n\n\n@blueprint.app_template_filter('get_story_info')\n# @jinja2.contextfilter\ndef get_story_info(stories, slug):\n \"\"\"\n Takes a slug and pulls the info for the story.\n \"\"\"\n for story in stories:\n if story['slug'] == slug:\n return story\n\n@blueprint.app_template_filter('find_sidebar_keywords')\n@jinja2.contextfilter\ndef find_sidebar_keywords(context, text):\n \"\"\"\n Searches a blob of text for arbitrary keywords, turns them into links to downpage sidebars based on the related story slug\n \"\"\"\n # print \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\"\n\n stories = context['stories']\n new_text = text # This will be the retval\n svg=\"\"\n for story in stories:\n\n try:\n slug = story['slug']\n keywords = story['sidebar_link_keywords'].split(',')\n\n for k in keywords:\n # Now loop through keywords looking for them in the story text\n link_label = \"Read more about {}\".format(k)\n link_opener = \" except the HREF \n k = k.strip()\n # print \"Now looking for {}\".format(k)\n new_text = re.sub(k, \"{} href='#{}'>{}{}\".format(link_opener, slug, k, svg), new_text)\n\n except:\n # Likely cause for error here is missing keywords, which is fine. Move along.\n pass\n \n return new_text\n\n@blueprint.app_template_filter('get_bylines')\n@jinja2.contextfilter\ndef get_bylines(context, byline_slugs):\n \"\"\"\n takes a list of reporter IDs and pulls byline info from the credits tab\n \"\"\"\n bylines = byline_slugs.split(',')\n retval = []\n for byline in bylines:\n for credit in context['credits']:\n if byline.strip() == credit['id']:\n retval.append(credit)\n return retval\n\n\n# Exclude these files from publication\nEXCLUDES = ['img/header/src','scripts', '*.md', 'img/src','img/svgs', 'requirements.txt', 'node_modules', '.scss', 'sass', 'base-sass', 'js/src', '*.ai', 'package.json', 'package-lock.json', 'Gruntfile.js', 'out_drive.html', 'out_parsed.txt']\n\n# Spreadsheet cache lifetime in seconds. (Default: 4)\n# SPREADSHEET_CACHE_TTL = 4\n\n# Create JSON data at ./data.json, disabled by default\n# CREATE_JSON = True\n\n# Get context from a local file or URL. This file can be a CSV or Excel\n# spreadsheet file. Relative, absolute, and remote (http/https) paths can be \n# used.\n# CONTEXT_SOURCE_FILE = \"\"\n\n# EXPERIMENTAL: Path to a credentials file to authenticate with Google Drive.\n# This is useful for for automated deployment. This option may be replaced by\n# command line flag or environment variable. Take care not to commit or publish\n# your credentials file.\n# CREDENTIALS_PATH = \"\"\n\n# S3 bucket configuration\nS3_BUCKETS = {\n # Provide target -> s3 url pairs, such as:\n # \"mytarget\": \"mys3url.bucket.url/some/path\"\n # then use tarbell publish mytarget to publish to it\n \n \"production\": \"graphics.chicagotribune.com/chicago-public-schools-sexual-abuse\",\n \"staging\": \"apps.beta.tribapps.com/cps-abuse\",\n \"ryan\": \"apps.beta.tribapps.com/cps-abuse-ryan-beta\",\n}\n\n# Default template variables\nDEFAULT_CONTEXT = {\n 'OMNITURE': { 'domain': 'chicagotribune.com',\n 'section': 'news',\n 'sitename': 'Chicago Tribune',\n 'subsection': 'local',\n 'subsubsection': '',\n 'type': 'dataproject'},\n 'name': 'cps-abuse',\n 'title': 'CPS Abuse'\n}","repo_name":"ryanbmarx/chicago-public-schools-sexual-abuse","sub_path":"tarbell_config.py","file_name":"tarbell_config.py","file_ext":"py","file_size_in_byte":9061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11320847456","text":"#Maximum 69 Number\n\n\"\"\"You are given a positive integer num consisting only of digits 6 and 9.\n\nReturn the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).\"\"\"\n\nclass Solution:\n def maximum69Number (self, num: int) -> int:\n nd = [i for i in str(num)]\n if \"6\" in nd:\n fs = nd.index(\"6\")\n nd[fs] = \"9\"\n return int(\"\".join(nd))\n","repo_name":"shrutityagi4102/myleetcodesolutions","sub_path":"191.py","file_name":"191.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73950432805","text":"import unittest\n\n\nfrom cassandra import ConsistencyLevel\nfrom cassandra.cqlengine.models import Model\nfrom cassandra.cqlengine import columns, connection, models\nfrom cassandra.cqlengine.management import sync_table\nfrom cassandra.cluster import ExecutionProfile, _clusters_for_shutdown, _ConfigMode, EXEC_PROFILE_DEFAULT\nfrom cassandra.policies import RoundRobinPolicy\nfrom cassandra.query import dict_factory\n\nfrom tests.integration import CASSANDRA_IP, PROTOCOL_VERSION, execute_with_long_wait_retry, local, TestCluster\nfrom tests.integration.cqlengine.base import BaseCassEngTestCase\nfrom tests.integration.cqlengine import DEFAULT_KEYSPACE, setup_connection\n\n\nclass TestConnectModel(Model):\n\n id = columns.Integer(primary_key=True)\n keyspace = columns.Text()\n\n\nclass ConnectionTest(unittest.TestCase):\n def tearDown(self):\n connection.unregister_connection(\"default\")\n\n @local\n def test_connection_setup_with_setup(self):\n connection.setup(hosts=None, default_keyspace=None)\n self.assertIsNotNone(connection.get_connection(\"default\").cluster.metadata.get_host(\"127.0.0.1\"))\n\n @local\n def test_connection_setup_with_default(self):\n connection.default()\n self.assertIsNotNone(connection.get_connection(\"default\").cluster.metadata.get_host(\"127.0.0.1\"))\n\n def test_only_one_connection_is_created(self):\n \"\"\"\n Test to ensure that only one new connection is created by\n connection.register_connection\n\n @since 3.12\n @jira_ticket PYTHON-814\n @expected_result Only one connection is created\n\n @test_category object_mapper\n \"\"\"\n number_of_clusters_before = len(_clusters_for_shutdown)\n connection.default()\n number_of_clusters_after = len(_clusters_for_shutdown)\n self.assertEqual(number_of_clusters_after - number_of_clusters_before, 1)\n\n\nclass SeveralConnectionsTest(BaseCassEngTestCase):\n\n @classmethod\n def setUpClass(cls):\n connection.unregister_connection('default')\n cls.keyspace1 = 'ctest1'\n cls.keyspace2 = 'ctest2'\n super(SeveralConnectionsTest, cls).setUpClass()\n cls.setup_cluster = TestCluster()\n cls.setup_session = cls.setup_cluster.connect()\n ddl = \"CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}\".format(cls.keyspace1, 1)\n execute_with_long_wait_retry(cls.setup_session, ddl)\n ddl = \"CREATE KEYSPACE {0} WITH replication = {{'class': 'SimpleStrategy', 'replication_factor': '{1}'}}\".format(cls.keyspace2, 1)\n execute_with_long_wait_retry(cls.setup_session, ddl)\n\n @classmethod\n def tearDownClass(cls):\n execute_with_long_wait_retry(cls.setup_session, \"DROP KEYSPACE {0}\".format(cls.keyspace1))\n execute_with_long_wait_retry(cls.setup_session, \"DROP KEYSPACE {0}\".format(cls.keyspace2))\n models.DEFAULT_KEYSPACE = DEFAULT_KEYSPACE\n cls.setup_cluster.shutdown()\n setup_connection(DEFAULT_KEYSPACE)\n models.DEFAULT_KEYSPACE\n\n def setUp(self):\n self.c = TestCluster()\n self.session1 = self.c.connect(keyspace=self.keyspace1)\n self.session1.row_factory = dict_factory\n self.session2 = self.c.connect(keyspace=self.keyspace2)\n self.session2.row_factory = dict_factory\n\n def tearDown(self):\n self.c.shutdown()\n\n def test_connection_session_switch(self):\n \"\"\"\n Test to ensure that when the default keyspace is changed in a session and that session,\n is set in the connection class, that the new defaul keyspace is honored.\n\n @since 3.1\n @jira_ticket PYTHON-486\n @expected_result CQLENGINE adopts whatever keyspace is passed in vai the set_session method as default\n\n @test_category object_mapper\n \"\"\"\n\n connection.set_session(self.session1)\n sync_table(TestConnectModel)\n TCM1 = TestConnectModel.create(id=1, keyspace=self.keyspace1)\n connection.set_session(self.session2)\n sync_table(TestConnectModel)\n TCM2 = TestConnectModel.create(id=1, keyspace=self.keyspace2)\n connection.set_session(self.session1)\n self.assertEqual(1, TestConnectModel.objects.count())\n self.assertEqual(TestConnectModel.objects.first(), TCM1)\n connection.set_session(self.session2)\n self.assertEqual(1, TestConnectModel.objects.count())\n self.assertEqual(TestConnectModel.objects.first(), TCM2)\n\n\nclass ConnectionModel(Model):\n key = columns.Integer(primary_key=True)\n some_data = columns.Text()\n\n\nclass ConnectionInitTest(unittest.TestCase):\n def test_default_connection_uses_legacy(self):\n connection.default()\n conn = connection.get_connection()\n self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY)\n\n def test_connection_with_legacy_settings(self):\n connection.setup(\n hosts=[CASSANDRA_IP],\n default_keyspace=DEFAULT_KEYSPACE,\n consistency=ConsistencyLevel.LOCAL_ONE\n )\n conn = connection.get_connection()\n self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY)\n\n def test_connection_from_session_with_execution_profile(self):\n cluster = TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)})\n session = cluster.connect()\n connection.default()\n connection.set_session(session)\n conn = connection.get_connection()\n self.assertEqual(conn.cluster._config_mode, _ConfigMode.PROFILES)\n\n def test_connection_from_session_with_legacy_settings(self):\n cluster = TestCluster(load_balancing_policy=RoundRobinPolicy())\n session = cluster.connect()\n session.row_factory = dict_factory\n connection.set_session(session)\n conn = connection.get_connection()\n self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY)\n\n def test_uncommitted_session_uses_legacy(self):\n cluster = TestCluster()\n session = cluster.connect()\n session.row_factory = dict_factory\n connection.set_session(session)\n conn = connection.get_connection()\n self.assertEqual(conn.cluster._config_mode, _ConfigMode.LEGACY)\n\n def test_legacy_insert_query(self):\n connection.setup(\n hosts=[CASSANDRA_IP],\n default_keyspace=DEFAULT_KEYSPACE,\n consistency=ConsistencyLevel.LOCAL_ONE\n )\n self.assertEqual(connection.get_connection().cluster._config_mode, _ConfigMode.LEGACY)\n\n sync_table(ConnectionModel)\n ConnectionModel.objects.create(key=0, some_data='text0')\n ConnectionModel.objects.create(key=1, some_data='text1')\n self.assertEqual(ConnectionModel.objects(key=0)[0].some_data, 'text0')\n\n def test_execution_profile_insert_query(self):\n cluster = TestCluster(execution_profiles={EXEC_PROFILE_DEFAULT: ExecutionProfile(row_factory=dict_factory)})\n session = cluster.connect()\n connection.default()\n connection.set_session(session)\n self.assertEqual(connection.get_connection().cluster._config_mode, _ConfigMode.PROFILES)\n\n sync_table(ConnectionModel)\n ConnectionModel.objects.create(key=0, some_data='text0')\n ConnectionModel.objects.create(key=1, some_data='text1')\n self.assertEqual(ConnectionModel.objects(key=0)[0].some_data, 'text0')\n","repo_name":"datastax/python-driver","sub_path":"tests/integration/cqlengine/connections/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":7435,"program_lang":"python","lang":"en","doc_type":"code","stars":1354,"dataset":"github-code","pt":"52"} +{"seq_id":"34378626399","text":"\n\ndef add(x,y):\n c=x+y\n print(c)\n\ndef arthimaticOperatins(p,q):\n c1=p+q\n c2=p-q\n c3=p/q\n c4=p*q\n return c1,c2,c3,c4\nadd(4,1)\nd1,d2,d3,d4=arthimaticOperatins(9,3)\nprint(d1,d2,d3,d4)\n\n","repo_name":"nagu1417/DemoPyGit","sub_path":"FunctionsExample1.py","file_name":"FunctionsExample1.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21739529406","text":"from openerp.osv import fields, osv\nfrom openerp.tools.translate import _\nfrom werkzeug.datastructures import FileStorage\n\nimport base64\nimport os\nimport uuid\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass ir_attachment(osv.Model):\n \n def _file_write(self, cr, uid, value):\n \"\"\" extend file write to support streams \"\"\"\n \n # check if it is a string\n if isinstance(value, basestring):\n return super(ir_attachment,self)._file_write(cr, uid, value)\n \n # create temp file\n full_temp = self._full_path(cr, uid, \"tmp_%s\" % uuid.uuid4())\n fname = None\n try:\n # save stream as temp file\n if isinstance(value, FileStorage):\n value.save(full_temp)\n else:\n with open(file_path,\"wb\") as f:\n for chunk in iter(lambda: value.read(16384), b\"\"):\n f.write(chunk)\n \n # check for rename, and create path\n # if the same file exist, take the existing file\n fname, full_path = self._get_path(cr, uid, None, file_path=full_temp)\n if not os.path.isfile(full_path) and full_path != full_temp:\n os.rename(full_temp, full_path) \n \n finally:\n # remove temp file\n if os.path.isfile(full_temp):\n try:\n os.unlink(full_temp)\n except Exception as e:\n _logger.exception(\"unable to unlink temp file %s\" % full_temp, e)\n \n return fname\n \n def _file_open(self, cr, uid, attachment, context=None):\n location = self._storage(cr, uid, context)\n if location == \"db\":\n return None\n if not attachment.store_fname:\n return None\n \n file_path = self._full_path(cr, uid, attachment.store_fname)\n if not os.path.isfile(file_path):\n return None\n return open(file_path,\"rb\")\n \n def _save_file(self, cr, uid, oid, values, context=None):\n assert values\n\n store_fname = values[\"store_fname\"]\n location = self._storage(cr, uid, context)\n full_path = self._full_path(cr, uid, store_fname)\n file_size = os.path.getsize(full_path) \n \n # check store_fname for delete\n fname_to_delete = None\n \n # open file \n if location == \"db\":\n with open(full_path) as fp:\n buf = StringIO()\n base64.encode(fp, buf)\n \n next_values = {\"db_datas\":buf.getvalue()}\n next_values.update(values)\n next_values.pop(\"store_fname\")\n values = next_values\n\n # update file \n if oid: \n fname_to_delete = self.read(cr, uid, oid, [\"store_fname\"], context=context)[\"store_fname\"]\n self.write(cr, uid, oid, values, context=context)\n # write new file\n else:\n oid = self.create(cr, uid, values, context=context)\n \n # After de-referencing the file in the database, check whether we need\n # to garbage-collect it on the filesystem\n if fname_to_delete:\n self._file_delete(cr, uid, fname_to_delete)\n \n # update file size\n # have to be called additional, because on default file was written in function field\n # ... and for security reasons, odoo developer remove the file attribute in the values\n cr.execute(\"UPDATE ir_attachment SET file_size=%s WHERE id=%s\", (file_size, oid))\n return oid\n \n \n _name = \"ir.attachment\"\n _inherit = \"ir.attachment\"\n _columns = {\n \"origin\" : fields.char(\"Origin\")\n } \n ","repo_name":"funkring/fdoo","sub_path":"addons-funkring/at_base/ir_attachment.py","file_name":"ir_attachment.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31860772945","text":"import webbrowser\n\nimport folium\n\nfrom coordinates.coordinates_for_path import *\n\nm5 = folium.Map(location=[28.644800, 77.216721], tiles='cartodbpositron', zoom_start=14)\n\n\nline_1 = folium.vector_layers.PolyLine(coords_1, popup='Path of Vehicle_1', tooltip='Vehicle_1', color='blue', weight=10)\nline_2 = folium.vector_layers.PolyLine(coords_2, popup='Path of Vehicle_2', tooltip='Vehicle_2', color='red', weight=10)\nline_3 = folium.vector_layers.PolyLine(coords_3, popup='Path of Vehicle_3', tooltip='Vehicle_3', color='green', weight=10)\n\nline_1.add_to(m5)\nline_2.add_to(m5)\nline_3.add_to(m5)\n\nfolium.LayerControl().add_to(m5)\n\nm5.save('map_india.html')\nwebbrowser.open('map_india.html')\n","repo_name":"AndriiHomeniuk/folium-plotting-map","sub_path":"india_route_path.py","file_name":"india_route_path.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31717194106","text":"\"\"\"\nThe base models module\n\"\"\"\nfrom django.conf import settings\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django_extensions.db.models import TimeStampedModel\n\nfrom .fields import LanguageField\nfrom .managers import SettingsManager\n\n\nclass CommonInfo(models.Model):\n \"\"\"\n The abstract model with common info\n \"\"\"\n\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n null=True,\n blank=True,\n db_index=True,\n on_delete=models.SET_NULL,\n verbose_name=_('created by'),\n related_name=\"%(app_label)s_%(class)s_created_by\")\n modified_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n null=True,\n blank=True,\n db_index=True,\n on_delete=models.SET_NULL,\n editable=False,\n verbose_name=_('modified by'),\n related_name=\"%(app_label)s_%(class)s_modified_by\")\n is_enabled = models.BooleanField(default=True,\n db_index=True,\n verbose_name=_('is enabled'))\n\n def __str__(self):\n default = '{} #{}'.format(type(self).__name__, str(self.id))\n return getattr(self, 'name', getattr(self, 'title', default))\n\n class Meta:\n abstract = True\n\n\nclass CachedModel(models.Model):\n \"\"\"\n The cached model mixin\n \"\"\"\n\n class Meta:\n abstract = True\n\n\nclass Settings(CachedModel, CommonInfo, TimeStampedModel): # type: ignore\n \"\"\"\n The class with user settings\n \"\"\"\n\n objects = SettingsManager()\n\n language = LanguageField(\n null=True,\n blank=True,\n verbose_name=_('language'),\n help_text=_('target language for translations'),\n )\n attempts_to_remember = models.PositiveIntegerField(\n default=settings.NC_ATTEMPTS_TO_REMEMBER,\n verbose_name=_('attempts to remember'),\n help_text=_('number of correct answers to remember the card'),\n validators=[MinValueValidator(3),\n MaxValueValidator(50)])\n cards_per_lesson = models.PositiveIntegerField(\n default=settings.NC_CARDS_PER_LESSON,\n verbose_name=_('cards per lesson'),\n help_text=_('number of cards to study per the lesson'),\n validators=[MinValueValidator(1),\n MaxValueValidator(50)])\n cards_to_repeat = models.PositiveIntegerField(\n default=settings.NC_CARDS_TO_REPEAT,\n verbose_name=_('cards to repeat'),\n help_text=_('number of cards to repeat per the lesson'),\n validators=[MinValueValidator(0),\n MaxValueValidator(50)])\n lesson_latest_days = models.PositiveIntegerField(\n default=settings.NC_LESSON_LATEST_DAYS,\n verbose_name=_('lesson latest days'),\n help_text=_('number of days for getting the latest added cards'),\n validators=[MinValueValidator(5),\n MaxValueValidator(50)])\n lessons_per_day = models.PositiveIntegerField(\n default=settings.NC_LESSONS_PER_DAY,\n verbose_name=_('lessons per day'),\n help_text=_('number of lessons to complete per day'),\n validators=[MinValueValidator(0),\n MaxValueValidator(50)])\n play_audio_on_open = models.BooleanField(\n default=True,\n db_index=True,\n help_text=_('play audio when the card is opening'),\n verbose_name=_('play audio on open'))\n\n @property\n def attempts_per_day(self) -> int:\n \"\"\"\n Returns attempts per day\n \"\"\"\n return self.lessons_per_day * (\n self.cards_per_lesson * settings.NC_CARDS_REPEAT_IN_LESSON +\n self.cards_to_repeat)\n\n def __str__(self):\n return \"{}'s settings\".format(self.created_by)\n\n class Meta:\n ordering = ['-created']\n verbose_name_plural = _('settings')\n","repo_name":"webmalc/nativecards-server","sub_path":"nativecards/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"70995858084","text":"from flask_restx import Namespace, Resource, reqparse\n\nfrom mutalyzer.algebra import compare\n\nfrom .common import errors\n\nns = Namespace(\"/\")\n\n_args = reqparse.RequestParser()\n_args.add_argument(\n \"reference\",\n type=str,\n help=\"Reference id or sequence\",\n required=False,\n)\n_args.add_argument(\n \"reference_type\",\n type=str,\n help=\"Reference type\",\n required=False,\n)\n_args.add_argument(\n \"lhs\",\n type=str,\n help=\"Left hand side operator\",\n required=True,\n)\n_args.add_argument(\n \"lhs_type\",\n type=str,\n help=\"Left hand side operator type\",\n required=True,\n)\n_args.add_argument(\n \"rhs\",\n type=str,\n help=\"Right hand side operator\",\n required=True,\n)\n_args.add_argument(\n \"rhs_type\",\n type=str,\n help=\"Right hand side operator type\",\n required=True,\n)\n\n\n@ns.route(\"/compare/\")\nclass Compare(Resource):\n @ns.expect(_args)\n @errors\n def get(self):\n \"\"\"Compute the relation between variants.\"\"\"\n return compare(**_args.parse_args())\n","repo_name":"mutalyzer/api","sub_path":"mutalyzer_api/endpoints/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36311205699","text":"import sys\nimport os\nimport csv\n\nPACKAGE_PARENT = '../../'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nfrom alphaslime.approx.linearq import LinearQApprox\nfrom alphaslime.agents.selfplay.sarsa import SarsaSP\n\n\nimport numpy as np\n\n\nif __name__ == '__main__':\n alpha = 3e-4 # step size\n epsilon = 1\n gamma = 0.99\n training_episodes = 1000\n champion_trails = 10\n\n q_hat = LinearQApprox()\n agent = SarsaSP(alpha=alpha, epsilon=epsilon, gamma=gamma, q_hat=q_hat)\n agent.train(episodes=training_episodes, num_champions_train=champion_trails)\n\n # get weights of latest champion\n weights = agent.champion.w\n print('-'*99)\n print('final training data')\n print('self.w = {}'.format(\n agent.w.shape))\n\n print('epsilon = {}'.format(agent.epsilon))\n print('-'*99)\n\n with open('./train/selfplay/sarsa/weight.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.writer(f)\n\n # write the header\n # writer.writerow(header)\n\n # write multiple rows\n writer.writerows(weights)\n\n","repo_name":"j0ker404/skripsie2021","sub_path":"train/selfplay/sarsa_sp_train.py","file_name":"sarsa_sp_train.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24471281075","text":"from tkinter import *\r\nimport random\r\nimport time\r\nimport math\r\n\r\nw = 800\r\nh = 600\r\ncount = 0\r\nmiss = 0\r\ncolor = \"#FFFF00\"\r\nsize = 50\r\ntime_start = 0\r\nx = w/2\r\ny = h/2\r\nresult_t = 0\r\nresult_a = 0\r\n\r\ndef draw_circle(size, color):\r\n global x\r\n global y\r\n \r\n canvas.create_arc(x-size/2, y-size/2, x+size/2, y+size/2, start=0, extent=359, style=CHORD, fill=color)\r\n\r\ndef on_click(event):\r\n global x\r\n global y\r\n global count\r\n global miss\r\n global time_start\r\n global result_t\r\n global result_a\r\n\r\n canvas.delete(\"all\")\r\n\r\n if time_start == 0:\r\n time_start = time.time()\r\n\r\n if (size/2)*(size/2) >= (event.x-x)*(event.x-x) + (event.y-y)*(event.y-y):\r\n count = count + 1\r\n if count == i_count:\r\n result_t = round(time.time()-time_start, 3)\r\n result_a = round((count/(count+miss))*100, 3)\r\n else:\r\n miss = miss + 1\r\n\r\n if count >= i_count:\r\n canvas.create_text(10, 10, text=f\"経過時間: {result_t}秒\", anchor=\"w\")\r\n canvas.create_text(10, 20, text=f\"精度: {result_a}%\", anchor=\"w\")\r\n\r\n x = size/2 + math.floor(random.random()*(w-size))\r\n y = size/2 + math.floor(random.random()*(h-size))\r\n\r\n draw_circle(size, color)\r\n\r\nwhile True:\r\n\r\n try:\r\n i_count = int(input(\"回数を入力 > \"))\r\n break\r\n except:\r\n print(\"不正な値\\n\")\r\n\r\nwhile True:\r\n\r\n try:\r\n i_size = int(input(\"大きさ(px)を入力 > \"))\r\n size = i_size\r\n break\r\n except:\r\n print(\"不正な値\\n\")\r\n\r\n\r\ntk = Tk()\r\ncanvas = Canvas(tk, width=w, height=h, bg=\"white\")\r\ncanvas.pack()\r\n\r\ndraw_circle(size, color)\r\n\r\ncanvas.bind(\"\", on_click)\r\n","repo_name":"Minkasy/aimtrainer.py","sub_path":"pyaimtrainer.py","file_name":"pyaimtrainer.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42473982247","text":"from typing import Literal, TypedDict\n\nfrom typing_extensions import NotRequired\n\n# A variable name.\nIdent = str\n\n# Primitive types.\nPrimType = Literal[\"int\", \"bool\", \"float\", \"char\"]\n\n# Value types.\nType = PrimType | dict[Literal[\"ptr\"], \"Type\"]\nParamType = dict[Literal[\"ptr\"], Type]\n\n# An (always optional) source code position.\nPosition = dict[str, int]\n\n# Common fields in any operation.\nclass Op(TypedDict):\n args: NotRequired[list[Ident]]\n funcs: NotRequired[list[Ident]]\n labels: NotRequired[list[Ident]]\n pos: NotRequired[Position]\n\n\n# The valid opcodes for value-producing instructions.\nValueOpCode = Literal[\n \"add\",\n \"mul\",\n \"sub\",\n \"div\",\n \"id\",\n \"nop\",\n \"eq\",\n \"lt\",\n \"gt\",\n \"ge\",\n \"le\",\n \"not\",\n \"and\",\n \"or\",\n \"call\",\n \"load\",\n \"ptradd\",\n \"alloc\",\n \"fadd\",\n \"fmul\",\n \"fsub\",\n \"fdiv\",\n \"feq\",\n \"flt\",\n \"fle\",\n \"fgt\",\n \"fge\",\n \"ceq\",\n \"clt\",\n \"cle\",\n \"cgt\",\n \"cge\",\n \"char2int\",\n \"int2char\",\n \"phi\",\n]\n\n# The valid opcodes for effecting operations.\nEffectOpCode = Literal[\n \"br\",\n \"jmp\",\n \"print\",\n \"ret\",\n \"call\",\n \"store\",\n \"free\",\n \"speculate\",\n \"guard\",\n \"commit\",\n]\n\n\n# An instruction that does not produce any result.\nclass EffectOperation(Op):\n op: EffectOpCode\n\n\n# An operation that produces a value and places its result in the\n# destination variable.\nclass ValueOperation(Op):\n op: ValueOpCode\n dest: Ident\n type: Type\n\n\n# The type of Bril values that may appear in constants.\nValue = int | bool | str\n\n# An instruction that places a literal value into a variable.\nclass Constant(TypedDict):\n op: Literal[\"const\"]\n value: Value\n dest: Ident\n type: Type\n pos: NotRequired[Position]\n\n\n# Operations take arguments, which come from previously-assigned identifiers.\nOperation = EffectOperation | ValueOperation\n\n# Instructions can be operations (which have arguments) or constants (which\n# don't). Both produce a value in a destination variable.\nInstruction = Operation | Constant\n\n# Both constants and value operations produce results.\nValueInstruction = Constant | ValueOperation\n\n# All valid operation opcodes.\nOpCode = ValueOpCode | EffectOpCode\n\n# Jump labels just mark a position with a name.\nclass Label(TypedDict):\n label: Ident\n pos: NotRequired[Position]\n\n\n# An argument has a name and a type.\nclass Argument(TypedDict):\n name: Ident\n type: Type\n\n\n# A function consists of a sequence of instructions.\nclass Function(TypedDict):\n name: Ident\n args: NotRequired[list[Argument]]\n instrs: NotRequired[list[Instruction | Label]]\n type: NotRequired[Type]\n pos: NotRequired[Position]\n\n\n# A program consists of a set of functions, one of which must be named \"main\".\nclass Program(TypedDict):\n functions: list[Function]\n","repo_name":"keikun555/bloke","sub_path":"src/brili/bril.py","file_name":"bril.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12323590687","text":"import os\nfrom .constants import YowConstants\nimport codecs, sys\nimport logging\nimport tempfile\nimport base64\nimport hashlib\nimport os.path, mimetypes\nimport uuid\nfrom consonance.structs.keypair import KeyPair\nfrom appdirs import user_config_dir\n\nfrom .optionalmodules import PILOptionalModule, FFVideoOptionalModule\n\nlogger = logging.getLogger(__name__)\n\nclass Jid:\n @staticmethod\n def normalize(number):\n if '@' in number:\n return number\n elif \"-\" in number:\n return \"%s@%s\" % (number, YowConstants.WHATSAPP_GROUP_SERVER)\n return \"%s@%s\" % (number, YowConstants.WHATSAPP_SERVER)\n\nclass HexTools:\n decode_hex = codecs.getdecoder(\"hex_codec\")\n @staticmethod\n def decodeHex(hexString):\n result = HexTools.decode_hex(hexString)[0]\n if sys.version_info >= (3,0):\n result = result.decode('latin-1')\n return result\n\nclass WATools:\n @staticmethod\n def generateIdentity():\n return os.urandom(20)\n\n @classmethod\n def generatePhoneId(cls):\n \"\"\"\n :return:\n :rtype: str\n \"\"\"\n return str(cls.generateUUID())\n\n @classmethod\n def generateDeviceId(cls):\n \"\"\"\n :return:\n :rtype: bytes\n \"\"\"\n return cls.generateUUID().bytes\n\n @classmethod\n def generateUUID(cls):\n \"\"\"\n :return:\n :rtype: uuid.UUID\n \"\"\"\n return uuid.uuid4()\n\n @classmethod\n def generateKeyPair(cls):\n \"\"\"\n :return:\n :rtype: KeyPair\n \"\"\"\n return KeyPair.generate()\n\n @staticmethod\n def getFileHashForUpload(filePath):\n sha1 = hashlib.sha256()\n f = open(filePath, 'rb')\n try:\n sha1.update(f.read())\n finally:\n f.close()\n b64Hash = base64.b64encode(sha1.digest())\n return b64Hash if type(b64Hash) is str else b64Hash.decode()\n\n\nclass StorageTools:\n NAME_CONFIG = \"config.json\"\n\n @staticmethod\n def constructPath(*path):\n path = os.path.join(*path)\n fullPath = os.path.join(user_config_dir(YowConstants.YOWSUP), path)\n if not os.path.exists(os.path.dirname(fullPath)):\n os.makedirs(os.path.dirname(fullPath))\n return fullPath\n\n @staticmethod\n def getStorageForProfile(profile_name):\n if type(profile_name) is not str:\n profile_name = str(profile_name)\n return StorageTools.constructPath(profile_name)\n\n @staticmethod\n def writeProfileData(profile_name, name, val):\n logger.debug(\"writeProfileData(profile_name=%s, name=%s, val=[omitted])\" % (profile_name, name))\n path = os.path.join(StorageTools.getStorageForProfile(profile_name), name)\n logger.debug(\"Writing %s\" % path)\n\n with open(path, 'w' if type(val) is str else 'wb') as attrFile:\n attrFile.write(val)\n\n @staticmethod\n def readProfileData(profile_name, name, default=None):\n logger.debug(\"readProfileData(profile_name=%s, name=%s)\" % (profile_name, name))\n path = StorageTools.getStorageForProfile(profile_name)\n dataFilePath = os.path.join(path, name)\n if os.path.isfile(dataFilePath):\n logger.debug(\"Reading %s\" % dataFilePath)\n with open(dataFilePath, 'rb') as attrFile:\n return attrFile.read()\n else:\n logger.debug(\"%s does not exist\" % dataFilePath)\n\n return default\n\n @classmethod\n def writeProfileConfig(cls, profile_name, config):\n cls.writeProfileData(profile_name, cls.NAME_CONFIG, config)\n\n @classmethod\n def readProfileConfig(cls, profile_name, config):\n return cls.readProfileData(profile_name, cls.NAME_CONFIG)\n\n\nclass ImageTools:\n @staticmethod\n def scaleImage(infile, outfile, imageFormat, width, height):\n with PILOptionalModule() as imp:\n Image = imp(\"Image\")\n im = Image.open(infile)\n #Convert P mode images\n if im.mode != \"RGB\":\n im = im.convert(\"RGB\")\n im.thumbnail((width, height))\n im.save(outfile, imageFormat)\n return True\n return False\n\n @staticmethod\n def getImageDimensions(imageFile):\n with PILOptionalModule() as imp:\n Image = imp(\"Image\")\n im = Image.open(imageFile)\n return im.size\n\n @staticmethod\n def generatePreviewFromImage(image):\n fd, path = tempfile.mkstemp()\n\n preview = None\n if ImageTools.scaleImage(image, path, \"JPEG\", YowConstants.PREVIEW_WIDTH, YowConstants.PREVIEW_HEIGHT):\n fileObj = os.fdopen(fd, \"rb+\")\n fileObj.seek(0)\n preview = fileObj.read()\n fileObj.close()\n os.remove(path)\n return preview\n\nclass MimeTools:\n MIME_FILE = os.path.join(os.path.dirname(__file__), 'mime.types')\n mimetypes.init() # Load default mime.types\n try:\n mimetypes.init([MIME_FILE]) # Append whatsapp mime.types\n except exception as e:\n logger.warning(\"Mime types supported can't be read. System mimes will be used. Cause: \" + e.message)\n\n @staticmethod\n def getMIME(filepath):\n mimeType = mimetypes.guess_type(filepath)[0]\n if mimeType is None:\n raise Exception(\"Unsupported/unrecognized file type for: \"+filepath);\n return mimeType\n\nclass VideoTools:\n @staticmethod\n def getVideoProperties(videoFile):\n with FFVideoOptionalModule() as imp:\n VideoStream = imp(\"VideoStream\")\n s = VideoStream(videoFile)\n return s.width, s.height, s.bitrate, s.duration #, s.codec_name\n\n @staticmethod\n def generatePreviewFromVideo(videoFile):\n with FFVideoOptionalModule() as imp:\n VideoStream = imp(\"VideoStream\")\n fd, path = tempfile.mkstemp('.jpg')\n stream = VideoStream(videoFile)\n stream.get_frame_at_sec(0).image().save(path)\n preview = ImageTools.generatePreviewFromImage(path)\n os.remove(path)\n return preview\n","repo_name":"tgalal/yowsup","sub_path":"yowsup/common/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","stars":6953,"dataset":"github-code","pt":"52"} +{"seq_id":"5057712475","text":"\r\n'''\r\n This will be the format of the output of the mineral classifier so that\r\n it may be more easily used within the gui.\r\n'''\r\n\r\nimport numpy\r\nimport matplotlib\r\nimport PIL\r\n\r\nif __package__ is '':\r\n\r\n #module is at the root of /classifiers/\r\n import sys\r\n from os import path\r\n \r\n sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )\r\n \r\n from layer import Layer\r\n\r\nelse:\r\n\r\n #module is at the root of the project\r\n from classifiers.layer import Layer\r\n\r\nclass ClassificationMap:\r\n\r\n #expects a prediction matrix of labels and a CRISMImage\r\n def __init__(self, predicted_labels, original_image):\r\n\r\n '''\r\n finding a method to calculate these in a way that was distinct enough was extremely hard\r\n we hard code these because even if a method like that existed it would be computationally\r\n intensive\r\n '''\r\n self.distinct_colors = [\r\n \"#FF0000\", \"#0000FF\", \"#00FF00\", \"#FFFF00\", \"#1CE6FF\", \"#FF34FF\", \"#FF4A46\", \"#008941\",\r\n \"#FFDBE5\", \"#7A4900\", \"#0000A6\", \"#63FFAC\", \"#B79762\", \"#004D43\", \"#8FB0FF\", \"#997D87\",\r\n \"#5A0007\", \"#809693\", \"#FF0000\", \"#1B4400\", \"#4FC601\", \"#3B5DFF\", \"#4A3B53\", \"#FF2F80\",\r\n \"#61615A\", \"#BA0900\", \"#6B7900\", \"#00C2A0\", \"#FFAA92\", \"#FF90C9\", \"#B903AA\", \"#D16100\",\r\n \"#DDEFFF\", \"#000035\", \"#7B4F4B\", \"#A1C299\", \"#300018\", \"#0AA6D8\", \"#013349\", \"#00846F\",\r\n \"#372101\", \"#FFB500\", \"#C2FFED\", \"#A079BF\", \"#CC0744\", \"#C0B9B2\", \"#C2FF99\", \"#001E09\",\r\n \"#00489C\", \"#6F0062\", \"#0CBD66\", \"#EEC3FF\", \"#456D75\", \"#B77B68\", \"#7A87A1\", \"#788D66\",\r\n \"#885578\", \"#FAD09F\", \"#FF8A9A\", \"#D157A0\", \"#BEC459\", \"#456648\", \"#0086ED\", \"#886F4C\",\r\n\r\n \"#34362D\", \"#B4A8BD\", \"#00A6AA\", \"#452C2C\", \"#636375\", \"#A3C8C9\", \"#FF913F\", \"#938A81\",\r\n \"#575329\", \"#00FECF\", \"#B05B6F\", \"#8CD0FF\", \"#3B9700\", \"#04F757\", \"#C8A1A1\", \"#1E6E00\",\r\n \"#7900D7\", \"#A77500\", \"#6367A9\", \"#A05837\", \"#6B002C\", \"#772600\", \"#D790FF\", \"#9B9700\",\r\n \"#549E79\", \"#201625\", \"#72418F\", \"#BC23FF\", \"#99ADC0\", \"#3A2465\", \"#922329\", \"#012C58\",\r\n \"#5B4534\", \"#FDE8DC\", \"#404E55\", \"#0089A3\", \"#CB7E98\", \"#A4E804\", \"#324E72\", \"#6A3A4C\",\r\n \"#83AB58\", \"#001C1E\", \"#D1F7CE\", \"#004B28\", \"#C8D0F6\", \"#A3A489\", \"#806C66\", \"#222800\",\r\n \"#BF5650\", \"#E83000\", \"#66796D\", \"#DA007C\", \"#FF1A59\", \"#8ADBB4\", \"#1E0200\", \"#5B4E51\",\r\n \"#C895C5\", \"#320033\", \"#FF6832\", \"#66E1D3\", \"#CFCDAC\", \"#D0AC94\", \"#006FA6\", \"#A30059\",\r\n \"#7ED379\",\r\n ]\r\n \r\n #the predictions from the classifier double[][]\r\n self.predictions = predicted_labels\r\n\r\n #the image without any overlay\r\n self.original_image = original_image\r\n\r\n #what we currently believe the display of the \r\n self.current_view = self.original_image.raw_image\r\n\r\n #the unique predicted labels int[]\r\n self.labels = numpy.unique(self.predictions)\r\n\r\n #the individial layers afer get_map is run, Layer[]\r\n self.layers = [None]*len(self.labels)\r\n\r\n self.make_map()\r\n\r\n '''\r\n Overlay the classification map onto the image\r\n\r\n Params: None\r\n Returns:\r\n numpy[][][3], representing the image with the layers overlayed\r\n \r\n '''\r\n def overlay(self):\r\n\r\n self.current_view = numpy.zeros((self.original_image.rows, self.original_image.columns, 4))\r\n self.current_view = self.current_view.astype(numpy.uint8)\r\n\r\n visible_layers = -1\r\n\r\n #for each layer generate an image matrix for that layer\r\n for i in range(len(self.layers)):\r\n \r\n #only make the layer if it is currently visible\r\n if(self.layers[i].is_visible):\r\n\r\n visible_layers += 1\r\n\r\n self.layers[i].color = self.get_color(visible_layers)\r\n\r\n #we need to generate the image we want to blend\r\n image = numpy.zeros((self.predictions.shape[0], self.predictions.shape[1], 4))\r\n\r\n #get the bool prediction matrix for the layer we are looking at \r\n prediction_matrix = numpy.squeeze(self.layers[i].prediction_matrix)\r\n\r\n #set the rgba values\r\n image[:, :, 0] = prediction_matrix * self.layers[i].color[0]\r\n image[:, :, 1] = prediction_matrix * self.layers[i].color[1]\r\n image[:, :, 2] = prediction_matrix * self.layers[i].color[2]\r\n image[:, :, 3] = prediction_matrix * 255\r\n \r\n image = image.astype(numpy.uint8)\r\n\r\n #add the layer\r\n self.current_view = numpy.add(self.current_view, image)\r\n\r\n return self.current_view\r\n\r\n '''\r\n Produces the layered classification map\r\n\r\n Params: None\r\n Return: None\r\n Side Effect: self.layers is now initialized\r\n '''\r\n def make_map(self):\r\n\r\n for label in range(len(self.labels)):\r\n\r\n layer = self.predictions == self.labels[label]\r\n label_num = self.labels[label]\r\n\r\n self.layers[label] = Layer(layer, label_num)\r\n\r\n '''\r\n Produces evenly spaced colors for use when displaying the individual layers\r\n\r\n Params: int, the index of the layer\r\n Return: \r\n NOTE: return is a 3x1 tuple\r\n r, int the red value\r\n g, int the green value\r\n b, int the blue value\r\n '''\r\n def get_color(self, number):\r\n\r\n hex_value = self.distinct_colors[number]\r\n\r\n #remove the #\r\n hex_value = hex_value.split('#')[1]\r\n\r\n #pad with 0's if needed\r\n hex_value = hex_value.ljust(6, '0')\r\n\r\n #convert back to decimal\r\n r = int(hex_value[0:2], 16)\r\n g = int(hex_value[2:4], 16)\r\n b = int(hex_value[4:6], 16)\r\n\r\n return r, g, b\r\n\r\n '''\r\n A method designed just for testing the gui. This will generate dummy data\r\n formatted as output from the classifier when fed the rows, columns and a number\r\n\r\n Params:\r\n rows, int, a number of rows to generate random predictions for\r\n columns, int, a number of columns to generate random predictions for\r\n num_labels, int, the number of labels/layers to generate\r\n '''\r\n def make_random_map(self, rows, columns, num_labels):\r\n\r\n combined_map = numpy.random.randint(0, num_labels, size=(rows, columns))\r\n \r\n self.labels = numpy.arange(0, num_labels)\r\n self.layers = [None]*len(self.labels)\r\n self.predictions = combined_map\r\n\r\n self.make_map()\r\n \r\n\r\nif __name__ == \"__main__\":\r\n\r\n from imagereader import ImageReader\r\n import os\r\n import matplotlib\r\n\r\n test_mat = numpy.random.rand(1)\r\n\r\n imr = ImageReader(\"HRL000040FF_07_IF183L_TRR3_BATCH_CAT_corr.img\")\r\n\r\n img = imr.get_raw_image()\r\n\r\n #get the path to the image\r\n path = os.path.abspath(__file__)\r\n path = os.path.split(path)[0]\r\n path = os.path.split(path)[0]\r\n path = os.path.join(path, 'display.png')\r\n\r\n classification_map = ClassificationMap(test_mat, img)\r\n classification_map.make_random_map(480, 320, 25)\r\n\r\n classification_map.layers[2].is_visible = True\r\n classification_map.layers[0].is_visible = True\r\n classification_map.layers[1].is_visible = True\r\n\r\n classification_map.overlay()\r\n\r\n matplotlib.pyplot.imshow(classification_map.current_view)\r\n matplotlib.pyplot.show()\r\n\r\n \r\n\r\n","repo_name":"bpoep72/CRISM-Capstone","sub_path":"classifiers/classificationmap.py","file_name":"classificationmap.py","file_ext":"py","file_size_in_byte":7481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20530444435","text":"# 2525. Categorize Box According to Criteria\nclass Solution:\n def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:\n \n def check(l, w, h, m):\n bulk = False\n heavy = False\n if l >= 10 ** 4 or w >= 10**4 or h >= 10**4 or l * w * h >= 10**9:\n bulk = True\n if m >= 100:\n heavy = True\n \n if bulk and heavy:\n return 'Both'\n elif bulk: \n return 'Bulky'\n elif heavy:\n return 'Heavy'\n return 'Neither'\n \n return check(length, width, height, mass)","repo_name":"zerobcpp/Code-practices","sub_path":"2525.py","file_name":"2525.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72302462565","text":"import time\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# url test\nhtml = urlopen(\"https://www.youtube.com/playlist?list=PLUav54rc5MQAJpXKjiRDbbTW_uVX1Fl2B\")\n\n# html = open(\"./youtube_playlist.html\")\n\nbsObj = BeautifulSoup(html.read(), \"html.parser\")\n\nvideo_link = []\n\nfor link in bsObj.find_all('a'):\n\tif \"/watch\" in link.get(\"href\"):\n\t\tvideo_link.append(\"https://www.youtube.com/\" + link.get('href'))\n\nvideo_link = list(set(video_link))\n\nprint(video_link)\nprint(len(video_link))\n\n# file open test\n# video = []\n# with open(\"./youtube_list.txt\", 'r') as f:\n# \tfor l in f:\n# \t\tvideo.append(l.replace(\"\\n\", \"\"))\n\n","repo_name":"Accent-/auto-youtube-downloader","sub_path":"youtube_url.py","file_name":"youtube_url.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30810042720","text":"import logging\nfrom typing import Type\nfrom tkinter import Tk, Frame\n\nfrom LabExT.View.Controls.CustomTable import CustomTable\nfrom LabExT.Wafer.Chip import Chip\n\n\nclass DeviceTable(Frame):\n \"\"\"\n Frame which contains a table to select a device from the loaded chip file.\n \"\"\"\n\n def __init__(self, parent, chip: Type[Chip]):\n \"\"\"\n Constructor\n\n Parameters\n ----------\n parent : Tk\n Window in which frame will be placed.\n chip : Chip\n Instance of current imported Chip.\n \"\"\"\n super(DeviceTable, self).__init__(parent)\n\n self.logger = logging.getLogger()\n\n self._devices = chip.devices.copy()\n\n self.logger.debug('Found %d devices.', len(self._devices))\n\n self.__setup__()\n\n def __setup__(self):\n \"\"\"\n Setup the CustomTable containing all devices\n \"\"\"\n\n # setup columns so that they contains all parameters\n def_columns = [\"ID\", \"In\", \"Out\", \"Type\"]\n columns = set()\n for device in self._devices.values():\n for param in device.parameters:\n columns.add(str(param))\n\n self.logger.debug('Columns in table: %s', (def_columns + list(columns)))\n\n # fill parameters in devices as empty values if not specified\n devs = list()\n for d in self._devices.values():\n tup = (d.id, d.in_position, d.out_position, d.type)\n for param in columns:\n val = d.parameters.get(param, '')\n # we unpack the tuple, append the value of the new parameter\n # and make a tuple again, if parameter not specified on device\n # its just empty\n tup = (*tup, val)\n devs.append(tup)\n\n self.logger.debug('Number of rows in table: %d', len(devs))\n # make new table\n self._device_table = CustomTable(self, (def_columns + list(columns)), devs, 20, 'browse')\n\n def get_selected_device(self):\n \"\"\"\n Return the currently selected device object.\n \"\"\"\n selected_iid = self._device_table._tree.focus()\n self.logger.debug('Selected iid: %s', selected_iid)\n if not selected_iid:\n return None\n dev_id = self._device_table._tree.set(selected_iid, 0)\n self.logger.debug('Selected device ID: %s', dev_id)\n selection = self._devices[dev_id]\n self.logger.debug('Device selected: %s', selection)\n return selection\n\n def set_selected_device(self, device_id):\n \"\"\"\n Set the current selected entry by the device id.\n \"\"\"\n self._device_table.select_by_id(device_id)\n","repo_name":"LabExT/LabExT","sub_path":"LabExT/View/Controls/DeviceTable.py","file_name":"DeviceTable.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"28110003724","text":"# Back Traking\n# 14888번. 연산자 끼워넣기\n\ndef backTraking(index, sum):\n global minAns\n global maxAns\n # 백트래킹의 핵심\n if index == N - 1:\n if minAns > sum : minAns = sum\n if maxAns < sum : maxAns = sum\n return\n\n for i in range(4): # 연산자 개수만큼\n temp = sum\n if operator[i] == 0: continue\n if i == 0: sum += numArr[index + 1]\n elif i == 1: sum -= numArr[index + 1]\n elif i == 2: sum *= numArr[index + 1]\n else:\n if sum < 0: sum = abs(sum) // numArr[index + 1] * -1\n else: sum //= numArr[index + 1]\n\n operator[i] -= 1 # operator[i] = 0이면 연산자를 모두 사용한 것임\n backTraking(index + 1, sum)\n operator[i] += 1\n sum = temp\n\nN = int(input())\nnumArr = list(map(int, input().split()))\noperator = list(map(int, input().split()))\n\n# 무한으로 설정\nminAns = float('Inf')\nmaxAns = float('-Inf')\n\nbackTraking(0, numArr[0])\nprint(maxAns)\nprint(minAns)\n","repo_name":"SujinKim-sj/BaekJoon-Online-Judge","sub_path":"완전탐색/BOJ_14888.py","file_name":"BOJ_14888.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4130159953","text":"import os\nfrom os import getenv\n\nimport environ\nimport django_heroku\nimport dj_database_url\n\non_heroku = False\nif 'DYNO' in os.environ:\n on_heroku = True\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nMODE = 'development'\nif not on_heroku:\n env = environ.Env()\n environ.Env.read_env()\n SECRET_KEY = env('SECRET_KEY')\n MODE = env('SERVER_MODE')\n\nDEBUG = MODE == 'development'\nDEVELOPMENT = DEBUG\n\nif DEVELOPMENT:\n ALLOWED_HOSTS = ['104.236.146.247', '127.0.0.1', 'localhost', 'planner.com', '.planner.com']\n\n# Application definition\n\nSHARED_APPS = [\n 'django_tenants',\n 'customers',\n\n 'django.contrib.contenttypes',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'letsencrypt',\n]\n\nTENANT_APPS = [\n 'django.contrib.contenttypes',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'webpack_loader',\n 'frontend',\n 'knox',\n 'solo',\n 'phone_field',\n 'backend',\n 'leads',\n 'eav',\n 'gm2m',\n]\n\nINSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]\n\nTENANT_MODEL = \"customers.PlannerClient\" # app.Model\n\nTENANT_DOMAIN_MODEL = \"customers.Domain\" # app.Model\n\nPUBLIC_SCHEMA_NAME = 'public'\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',)\n}\n\nMIDDLEWARE = [\n 'django_tenants.middleware.main.TenantMainMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'planner.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')]\n ,\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.request',\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\nWSGI_APPLICATION = 'planner.wsgi.application'\n\nif not on_heroku:\n DATABASES = {\n 'default': env.db(engine='django_tenants.postgresql_backend'),\n }\n\nDATABASE_ROUTERS = (\n 'django_tenants.routers.TenantSyncRouter',\n)\n\n# Password validation\n# https://docs.djangoproject.com/en/2.2/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# Internationalization\n# https://docs.djangoproject.com/en/2.2/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.2/howto/static-files/\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')\n\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'static')\n]\n\nWEBPACK_LOADER = {\n 'DEFAULT': {\n 'CACHE': not DEBUG,\n 'BUNDLE_DIR_NAME': 'frontend/', # must end with slash\n 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'),\n 'POLL_INTERVAL': 0.1,\n 'TIMEOUT': None,\n 'IGNORE': [r'.+\\.hot-update.js', r'.+\\.map']\n }\n}\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nif on_heroku:\n # DEBUG = False\n ALLOWED_HOSTS = ['*']\n SECURE_SSL_REDIRECT = True\n # Activate Django-Heroku without database setup.\n config = locals()\n django_heroku.settings(config, databases=False)\n # Manual configuration of database\n conn_max_age = config.get('CONN_MAX_AGE', 600) # Used in django-heroku\n config['DATABASES'] = {\n 'default': dj_database_url.parse(os.environ['DATABASE_URL'], engine='django_tenants.postgresql_backend',\n conn_max_age=conn_max_age, ssl_require=True\n )\n }\n","repo_name":"brendanowens/Planline","sub_path":"planner/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41072769317","text":"\"\"\"\nReverse a linked list \nEasy Accuracy: 48.93% Submissions: 100k+ Points: 2\nGiven a linked list of N nodes. The task is to reverse this list.\n\nExample 1:\n\nInput:\nLinkedList: 1->2->3->4->5->6\nOutput: 6 5 4 3 2 1\nExplanation: After reversing the list, \nelements are 6->5->4->3->2->1.\nExample 2:\n\nInput:\nLinkedList: 2->7->8->9->10\nOutput: 10 9 8 7 2\nExplanation: After reversing the list,\nelements are 10->9->8->7->2.\nYour Task:\nThe task is to complete the function reverseList() with head reference as the only argument and should return new head after reversing the list.\n\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1).\n\nConstraints:\n1 <= N <= 104\n\nlink --> https://practice.geeksforgeeks.org/problems/reverse-a-linked-list/1#\n\"\"\"\n\n# Node Class\n\nclass node:\n def __init__(self, val):\n self.data = val\n self.next = None\n\n\nclass Solution:\n #Function to reverse a linked list.\n def reverseList(self, head):\n if not head:\n return None\n pre = None\n cur = head\n while cur:\n nxt= cur.next\n cur.next = pre\n pre = cur\n cur = nxt\n head = pre\n return head\n\n\n# recursive approach (https://www.youtube.com/watch?v=MRe3UsRadKw&ab_channel=IDeserve)\n \ndef reverse(self, head):\n \n # If head is empty or has reached the list end\n if head is None or head.next is None:\n return head\n\n # Reverse the rest list\n cur = self.reverse(head.next)\n\n # Put first element at the end\n head.next.next = head\n head.next = None\n\n # Fix the header pointer\n return cur","repo_name":"MaqOwais/miscell","sub_path":"gfg_rev_py_java/linked lists/Reverse a linked list /Reverse a linked list.py","file_name":"Reverse a linked list.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28199515993","text":"\"\"\"\nstep2022 -week4-\n”Google”から”渋谷”をたどる経路を、DFSで探す\n\"\"\"\nimport sys\nsys.setrecursionlimit(100000) #再起の上限を100000回に設定する\n\nid_to_title = {}\nid_to_nextIDs = defaultdict(list)\nvisited = set() #探索済みnodeを入れる集合\n\n#Depth-First Search\ndef dfs(startID, targetID):\n \"\"\"\n Return the DSF path between two points.\n Args:\n startID: the start title ID\n targetID: the goal title ID\n\n Returns: the path from goal to start if it exists, none otherwise\n \"\"\"\n visited.add(startID) #探索済みにする\n\n if startID == targetID:\n return [targetID]\n\n if startID in id_to_nextIDs: #アクセスできるnodeがあったら\n for nextID in id_to_nextIDs[startID]: #そのnodeを全て見る\n if nextID not in visited: #まだ未探索だったら\n try:\n ans = dfs(nextID, targetID) #再起してさらに深く見ていく\n except RecursionError : #再起の上限に到達したら\n return None #それ以上の探索をやめる\n if ans is not None: #ansがNoneではなかったら = 探索先でgoalにたどり着いていたら\n ans.append(startID) #リストに自分を付け加えて返す\n return ans\n\n return None\n\n\ndef input_page(printword):\n \"\"\"\n Input the page title and return the ID.\n\n Args:\n printword: \"START\" or \"GOAL\"\n\n Returns: the page title and the ID\n \"\"\"\n while True:\n page = input(\"%s : \" %printword)\n for k, v in id_to_title.items():\n if page == v:\n break\n else:\n print(\"The page \\\"%s\\\" does not exists.\" %start)\n continue\n break\n return page, k\n\n\ndef main():\n #Set your path.\n pages_data = \"data/pages.txt\"\n links_data = \"data/links.txt\"\n\n print(\"Now Loading...\")\n\n #Create a dictionary that maps ID to title.\n with open(pages_data) as f:\n for data in f.read().splitlines():\n page = data.split(\"\\t\")\n id_to_title[page[0]] = page[1]\n\n #Create a dictionary that maps ID to the list of accessible nodes.\n with open(links_data) as f:\n for data in f.read().splitlines():\n link = data.split(\"\\t\")\n id_to_nextIDs[link[0]].append(link[1])\n\n # Input start and goal words.\n start, startID = input_page(\"START\")\n goal, targetID = input_page(\"GOAL\")\n\n print(\"Searching path from \\\"%s\\\" to \\\"%s\\\"\" %(start, goal))\n ans = dfs(startID, targetID)\n if ans is None:\n print(\"From \\\"%s\\\" to \\\"%s\\\" can not be reached.\" %(start, goal))\n else:\n print(\" -> \".join([id_to_title[id_] for id_ in ans[::-1]]))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"llannasatoll/step2022","sub_path":"week4/wikipedia_dfs.py","file_name":"wikipedia_dfs.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"891921895","text":"import os\nimport time\nimport re\n\n\ndef deszyfruj(napis):\n zdeszyfrowany = \"\"\n for i in range(len(napis)):\n if ((ord(napis[i]) >= 97) and (ord(napis[i]) <= 122)):\n if ((ord(napis[i]) - KLUCZ) < 97):\n zdeszyfrowany += chr(ord(napis[i]) - KLUCZ + 26)\n else:\n zdeszyfrowany += chr(ord(napis[i]) - KLUCZ)\n elif ((ord(napis[i]) >= 65) and (ord(napis[i]) <= 90)):\n if ((ord(napis[i]) - KLUCZ) < 65):\n zdeszyfrowany += chr(ord(napis[i]) - KLUCZ + 26)\n else:\n zdeszyfrowany += chr(ord(napis[i]) - KLUCZ)\n else:\n zdeszyfrowany += napis[i]\n return zdeszyfrowany\n\nx = 1\nwhile x==1:\n try:\n dir_path2 = input(\"Wprowadź ścieżkę do katalogu: \")\n pliki = os.listdir(dir_path2)\n if (bool(pliki)==False):\n print(\"W podanym katalogu nie ma plików\")\n else:\n break\n except:\n print(\"Podany katalog nie istnieje\")\n\n\nfor i in range(len(pliki)):\n plik = str(pliki[i])\n try:\n temp = (re.search(\"plik_zaszyfrowany%._\", plik)).group(0)\n KLUCZ = int(temp[18])\n os.chdir(dir_path2)\n f = open(plik, \"r\")\n napis = f.read()\n f.close()\n napis_deszyfrowany = deszyfruj(napis)\n\n rok = time.strftime(\"%Y\", time.localtime())\n miesiac = time.strftime(\"%m\", time.localtime())\n dzien = time.strftime(\"%d\", time.localtime())\n\n dir_path3 = (\"plik_deszyfrowany%\" + str(KLUCZ) + \"_\" + \"%\" + str(rok) + \"%\" + str(miesiac) + \"%\" + str(dzien) + \".txt\")\n f = open(dir_path3, \"w\")\n f.write(napis_deszyfrowany)\n f.close()\n except:\n pass","repo_name":"wojciechroman/JSP2019","sub_path":"lista_8/zadanie2.py","file_name":"zadanie2.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38782342008","text":"import asyncio\nfrom concurrent.futures import ThreadPoolExecutor\nfrom time import time\n\nimport requests\nfrom requests.exceptions import InvalidSchema, MissingSchema, InvalidURL\n\nfrom timing import async_timed\n\nurls = [\n 'https://www.google.com.ua/?hl=uk',\n 'https://www.python.org/',\n 'https://goit.global/ua/',\n 'https://duckduckgo.com/',\n 'https://github.com/',\n 'https://www.codewars.com/',\n 'https://www.python.org/qwerty',\n 'ws://test.com',\n 'test.com.23'\n]\n\n\ndef get_preview(url: str) -> (str, str):\n r = requests.get(url)\n return url, r.text[:25]\n\n\n@async_timed()\nasync def main():\n loop = asyncio.get_running_loop()\n with ThreadPoolExecutor(10) as executor:\n futures = [loop.run_in_executor(executor, get_preview, url) for url in urls]\n r = await asyncio.gather(*futures, return_exceptions=True)\n return r\n\n\nif __name__ == '__main__':\n r = asyncio.run(main())\n print(r)\n for el in r:\n print(isinstance(el, Exception))\n\n # start = time()\n # results = []\n # for url in urls:\n # try:\n # results.append(get_preview(url))\n # except (InvalidSchema, MissingSchema) as err:\n # print(err)\n #\n # print(results)\n # print(time() - start)\n\n\n\n\n\n\n\n","repo_name":"GoIT-Python-Web/Py10Web","sub_path":"m10_05_01/08_io_bound.py","file_name":"08_io_bound.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"104776785","text":"#2014313508 박천욱\nimport csv\n\ninp = []\ncnt = 0\nmax_size=[5,10,3,5]\ndept =[]\ndeptlist=[[],[],[],[]] #5 10 3 5\ndeptrest=[]\nanswer=0\n\ndef calcM(): #M 계산함수\n M=0\n for m in range(5):\n M = M+dept[m][1]\n for m in range(5,15):\n M = M+dept[m][2]\n for m in range(15,18):\n M = M+dept[m][3]\n for m in range(18,23):\n M = M+dept[m][4]\n return M\n\nf = open('data_dp.csv', 'r') #파일열어서 inp 리스트로 받음 101명의 데이터가 있음\nrdr = csv.reader(f)\nfor line in rdr:\n inp.append(line)\n for j in range(1,6):\n inp[cnt][j] = int(inp[cnt][j])\n cnt += 1\nf.close()\n\nn = int(input(\"지원자는 몇명인가요?: (단, 100명 이하, 23명 이상)\")) #inp로 읽어온 데이터 중 몇명까지 사용할지 입력받음\ninp = inp[:n] #리스트 슬라이싱으로 사용할 데이터 셋 완성\n\n#이제 서류 인성 적성 면접 개발 점수를 토대로 점수를 만들어보자.\nfor i in range(n):\n H = inp[i][2] #인사부 점수 -> 인성점수 100%\n P = inp[i][5] #개발부 점수 -> 개발점수 100%\n S = inp[i][1]*0.15 + inp[i][2]*0.15 + inp[i][3]*0.2 + inp[i][4]*0.1 + inp[i][5]*0.4 #전략&기획부서 점수\n F = inp[i][1]*0.2 + inp[i][2]*0.2 + inp[i][3]*0.4 + inp[i][4]*0.2 #재경부서 점수\n inp[i] = [inp[i][0], H, P, S, F] #inp를 조정된 값으로 수정\n\n # inp에는 ['이름', H, P, S, F] 의 형태로 저장되어 있으므로, inp[i][1:]로 슬라이싱하여 [H, P, S, F]의 값들에 집중해보자.\n # 아래는 HPSF중 가장 작은 값을 가지는 인덱스 부터 큰 값을 가지는 녀석의 인덱스 순으로 정렬했다.\n # 예) [27, 77, 56, 43] 이라면 index=[0, 3, 2, 1]으로 정렬함.\n index = sorted(range(len(inp[i][1:])), key=lambda a: inp[i][1:][a])\n deptlist[index[3]].append(inp[i])\n\n\n#정렬. 자기 부서에서 필요한 점수대 기준으로 내림차순\nfor i in range(4):\n deptlist[i] = sorted(deptlist[i], reverse= True, key=lambda x:x[i+1])\n\nfor i in range(4): #범위를 넘어가는 애들은 일단 잘라내둠.\n if len(deptlist[i]) > max_size[i]:\n deptlist[i] = deptlist[i][:(max_size[i])]\n\n\n#아직 deptlist에 포함되지 못한애들은 일단 deptrest 리스트로\ntmp=[]\nfor i in range(4):\n for j in range(len(deptlist[i])):\n tmp.append(deptlist[i][j])\n\nfor i in inp:\n if i not in tmp:\n deptrest.append(i)\n\n\n#deptrest에서 일단 각 영역별 점수 높은 애들을 해당 부서로 넣어 줌\nfor i in range(4):\n if len(deptlist[i]) < max_size[i]:\n for j in range(max_size[i]-len(deptlist[i])): # 몇개가 더 들어가야 하는지 계산해서 그만큼 추가해줌\n deptlist[i].append(sorted(deptrest, reverse= True, key=lambda x:x[i+1])[j])\n\n\nfor i in range(4): #이제 초기화 된 dept 생성\n for j in deptlist[i]:\n dept.append(j)\n\nprint(\"그리디하게 초기화한 결과\")\nprint(dept) #초기화 된 dept 출력\nanswer = calcM()\nprint(answer) #초기화 된 dept의 M 계산 결과 출력\nprint()\n\ndeptrest.clear() #deptrest에 아직 못들어간 애들을 일단 다 넣어둠\nfor i in inp:\n if i not in dept:\n deptrest.append(i)\n\n# 이제 비교해보자\nfor i in range(n):\n if inp[i] not in dept:\n for j in range(23):\n flag = 0\n temp = dept[j] #잠시 보관\n dept[j] = inp[i]\n for a in range(22):\n for b in range(a+1, 23):\n dept[a],dept[b] =dept[b],dept[a]\n if calcM() <= answer:\n dept[a], dept[b] = dept[b], dept[a]\n else:\n flag = 1\n answer = calcM()\n\n if flag != 1:\n dept[j] = temp\n\n if inp[i] in dept:\n for a in range(22):\n for b in range(a + 1, 23):\n dept[a], dept[b] = dept[b], dept[a]\n if calcM() <= answer:\n dept[a], dept[b] = dept[b], dept[a]\n else:\n answer = calcM()\nprint(\"최종 입사자 명단\")\nprint(dept)\nprint(answer)\n\n\n\n\n\n\n\n\n\n\n\n\n'''\n #inp에는 ['이름', H, P, S, F] 의 형태로 저장되어 있으므로, inp[i][1:]로 슬라이싱하여 [H, P, S, F]의 값들에 집중해보자.\n #아래는 HPSF중 가장 작은 값을 가지는 인덱스 부터 큰 값을 가지는 녀석의 인덱스 순으로 정렬했다.\n # 예) [27, 77, 56, 43] 이라면 index=[0, 3, 2, 1]으로 정렬함.\n index = sorted(range(len(inp[i][1:])), key=lambda a: inp[i][1:][a])\n\n if len(answer[index[3]]) < max_size[index[3]]:\n answer[index[3]].append(inp[i])\n elif\n'''\n\n'''\n#인사부부터 넣어보자\nh_base = sorted(inp, reverse = True, key=lambda x:(x[2]))\nfor i in range(5):\n hlist.append(h_base[i])\n h_base.pop(0)\n\n#개발부\np_base = sorted(inp, reverse = True, key=lambda x:(x[5]))\nfor i in range(5):\n plist.append(p_base[i])\n p_base.pop(0)\n '''\n","repo_name":"guard1000/Everyday-coding","sub_path":"dp_HOY_recruit.py","file_name":"dp_HOY_recruit.py","file_ext":"py","file_size_in_byte":5063,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8669470387","text":"#=======================================================================================================================\n\nclass Customer:\n \"\"\"client\"\"\"\n\n def __init__(self, name):\n self.__name = name\n self.__num = 0\n self.__clinics = None\n\n def getName(self):\n return self.__name\n\n def register(self, system):\n system.pushCustomer(self)\n\n def setNum(self, num):\n self.__num = num\n\n def getNum(self):\n return self.__num\n\n def setClinic(self, clinic):\n self.__clinics = clinic\n\n def getClinic(self):\n return self.__clinics\n\n\nclass NumeralIterator:\n \"\"\"Iterator\"\"\"\n\n def __init__(self, data):\n self.__data = data\n self.__curIdx = -1\n\n def next(self):\n \"\"\"Move to next element\"\"\"\n if (self.__curIdx < len(self.__data) - 1):\n self.__curIdx += 1\n return True\n else:\n return False\n\n def current(self):\n \"\"\"Get the current element\"\"\"\n return self.__data[self.__curIdx] if (self.__curIdx < len(self.__data) and self.__curIdx >= 0) else None\n\n\nclass NumeralSystem:\n \"\"\"Ranking system\"\"\"\n\n __clinics = (\"Screening Room No. 1\", \"Screening Room 2\", \"Screening Room 3\")\n\n def __init__(self, name):\n self.__customers = []\n self.__curNum = 0\n self.__name = name\n\n def pushCustomer(self, customer):\n customer.setNum(self.__curNum + 1)\n click = NumeralSystem.__clinics[self.__curNum % len(NumeralSystem.__clinics)]\n customer.setClinic(click)\n self.__curNum += 1\n self.__customers.append(customer)\n print(\"%s Hello! You are already %s Registered successfully, serial number:%04d, please wait patiently!\"\n % (customer.getName(), self.__name, customer.getNum()) )\n\n def getIterator(self):\n return NumeralIterator(self.__customers)\n\n\n def visit(self):\n for customer in self.__customers:\n print(\"Next patient %04d(%s) Please go %s See a doctor.\"\n % (customer.getNum(), customer.getName(), customer.getClinic()) )\n\n\n# Version 2.0\n#=======================================================================================================================\n# 代码框架\n#==============================\nclass BaseIterator:\n \"\"\"Iterator\"\"\"\n\n def __init__(self, data):\n self.__data = data\n self.toBegin()\n\n def toBegin(self):\n \"\"\"Move the pointer to the starting position\"\"\"\n self.__curIdx = -1\n\n def toEnd(self):\n \"\"\"Move the pointer to the end\"\"\"\n self.__curIdx = len(self.__data)\n\n def next(self):\n \"\"\"Move to next element\"\"\"\n if (self.__curIdx < len(self.__data) - 1):\n self.__curIdx += 1\n return True\n else:\n return False\n\n def previous(self):\n \"Move to previous element\"\n if (self.__curIdx > 0):\n self.__curIdx -= 1\n return True\n else:\n return False\n\n def current(self):\n \"\"\"Get the current element\"\"\"\n return self.__data[self.__curIdx] if (self.__curIdx < len(self.__data) and self.__curIdx >= 0) else None\n\n\n# 基于框架的实现\n#==============================\n\n\n# Test\n#=======================================================================================================================\n\ndef testHospital():\n numeralSystem = NumeralSystem(\"Registration desk\")\n lily = Customer(\"Lily\")\n lily.register(numeralSystem);\n pony = Customer(\"Pony\")\n pony.register(numeralSystem)\n nick = Customer(\"Nick\")\n nick.register(numeralSystem)\n tony = Customer(\"Tony\")\n tony.register(numeralSystem)\n print()\n\n iterator = numeralSystem.getIterator()\n while(iterator.next()):\n customer = iterator.current()\n print(\"Next patient %04d(%s) Please go %s See a doctor.\"\n % (customer.getNum(), customer.getName(), customer.getClinic()) )\n\n # numeralSystem.visit()\n\n\n\ndef testBaseIterator():\n print(\"Traverse: \")\n iterator = BaseIterator(range(0, 10))\n while(iterator.next()):\n customer = iterator.current()\n print(customer, end=\"\\t\")\n print()\n\n print(\"Traverse from back to front: \")\n iterator.toEnd()\n while (iterator.previous()):\n customer = iterator.current()\n print(customer, end=\"\\t\")\n\n\ndef testLoop():\n arr = [0, 1, 2, 3, 4, 5, 6, 7 ,8 , 9];\n for e in arr:\n print(e, end=\"\\t\")\n\n\n# Method 1: Use () to define the generator\ngen = (x * x for x in range(10))\n\n# Method 2: Define the generator function using yield\ndef fibonacci(maxNum):\n \"\"\"Fibonacci generator\"\"\"\n a = b = 1\n for i in range(maxNum):\n yield a\n a, b = b, a + b\n\ndef testIterable():\n print(\"Method one, the square of 0-9:\")\n for e in gen:\n print(e, end=\"\\t\")\n print()\n\n print(\"Method two, Fibonacci sequence: \")\n fib = fibonacci(10)\n for n in fib:\n print(n, end=\"\\t\")\n print()\n\n print(\"The for loop of the built-in container:\")\n arr = [x * x for x in range(10)]\n for e in arr:\n print(e, end=\"\\t\")\n print()\n\n print()\n print(type(gen))\n print(type(fib))\n print(type(arr))\n\n\nfrom collections import Iterable, Iterator\n# Introducing Iterable and Iterator\n\ndef testIsIterator():\n print(\"Whether it is an Iterable object:\")\n print(isinstance([], Iterable))\n print(isinstance({}, Iterable))\n print(isinstance((1, 2, 3), Iterable))\n print(isinstance(set([1, 2, 3]), Iterable))\n print(isinstance(\"string\", Iterable))\n print(isinstance(gen, Iterable))\n print(isinstance(fibonacci(10), Iterable))\n print(\"Whether it is an Iterator object: \")\n print(isinstance([], Iterator))\n print(isinstance({}, Iterator))\n print(isinstance((1, 2, 3), Iterator))\n print(isinstance(set([1, 2, 3]), Iterator))\n print(isinstance(\"string\", Iterator))\n print(isinstance(gen, Iterator))\n print(isinstance(fibonacci(10), Iterator))\n\n\ndef testNextItem():\n print(\"Turn Iterable object into Iterator object: \")\n l = [1, 2, 3]\n itrL = iter(l)\n print(next(itrL))\n print(next(itrL))\n print(next(itrL))\n\n print(\"next() The function iterates over the iterator elements:\")\n fib = fibonacci(4)\n print(next(fib))\n print(next(fib))\n print(next(fib))\n print(next(fib))\n # print(next(fib))\n\n\nclass NumberSequence:\n \"\"\"Generate a series of numbers spaced in steps\"\"\"\n\n def __init__(self, init, step, max = 100):\n self.__data = init\n self.__step = step\n self.__max = max\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if(self.__data < self.__max):\n tmp = self.__data\n self.__data += self.__step\n return tmp\n else:\n raise StopIteration\n\n\ndef NumberSequence():\n numSeq = NumberSequence(0, 5, 20)\n print(isinstance(numSeq, Iterable))\n print(isinstance(numSeq, Iterator))\n for n in numSeq:\n print(n, end=\"\\t\")\n\n\n# testHospital()\n# testBaseIterator()\n# testLoop()\n# testIterable()\ntestIsIterator()\n# testNextItem()\n# testNumberSequence()\n\n","repo_name":"syurskyi/Python_Topics","sub_path":"120_design_patterns/016_iterator/examples/Iterator_008.py","file_name":"Iterator_008.py","file_ext":"py","file_size_in_byte":7147,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"18215989961","text":"def init_game():\n game = {}\n game['game_over'] = False\n game['no_space'] = False\n game['board'] = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n game['current_player'] = ''\n game['players'] = {'player1': {'symbol':'', 'name':'', 'played': {'onboard':(), 'num':''}}, 'player2': {'symbol':'', 'name':'', 'played':{'onboard':(), 'num':''}}}\n return game\n\ndef print_board(board):\n clear_screen()\n print('>>>>positions<<<<<'+'\\tI\\t'+'=====THE GAME=====')\n print(' '+str(1)+' | '+str(2)+' | '+str(3)+' '+'\\tI\\t'+' '+board[0][0]+' | '+board[0][1]+' | '+board[0][2]+' ')\n print(' ---'+'-'+'---'+'-'+'--- '+'\\tI\\t'+' ---'+'-'+'---'+'-'+'--- ')\n print(' '+str(4)+' | '+str(5)+' | '+str(6)+' '+'\\tI\\t'+' '+board[1][0]+' | '+board[1][1]+' | '+board[1][2]+' ')\n print(' ---'+'-'+'---'+'-'+'--- '+'\\tI\\t'+' ---'+'-'+'---'+'-'+'--- ')\n print(' '+str(7)+' | '+str(8)+' | '+str(9)+' '+'\\tI\\t'+' '+board[2][0]+' | '+board[2][1]+' | '+board[2][2]+' ')\n print('>>>>positions<<<<<'+'\\tI\\t'+'==================')\n \n print('')\n\n\ndef clear_screen():\n print('\\n'*100)\n\ndef read_players(players):\n symbols = ['x','o']\n player_name = input(\"Please type the Player1's name:\")\n players['player1']['name'] = player_name\n player_symbol = input(player_name+\" do you want to be X or O?\").lower()\n while(player_symbol not in symbols):\n player_symbol = input(\"Invalid input, please select 'X' or 'O'\").lower()\n players['player1']['name'] = player_name\n players['player1']['symbol'] = player_symbol.lower()\n \n player_name = input(\"Please type the Player2's name:\")\n players['player2']['name'] = player_name\n if player_symbol == 'x':\n player_symbol = 'o'\n else:\n player_symbol = 'x'\n players['player2']['symbol'] = player_symbol.lower()\n\ndef read_turn(game):\n current_player = game['players'][game['current_player']]\n valid_input = False\n while(not valid_input):\n player_input = input(current_player['name']+\", please select an empty valid position (1 ~ 9):\")\n if player_input in ['1','2','3','4','5','6','7','8','9']:\n board_position = map_input_to_board(player_input)\n if game['board'][board_position[0]][board_position[1]] == ' ':\n game['board'][board_position[0]][board_position[1]] = current_player['symbol']\n current_player['played']['onboard'] = board_position\n current_player['played']['num'] = player_input\n valid_input = True\n\n\ndef map_input_to_board(player_input):\n n = 0\n for i in range(0,3):\n for j in range(0,3):\n n+=1\n if str(n) == player_input:\n return (i,j)\n\ndef select_current_player(game):\n if game['current_player'] == 'player1':\n game['current_player'] = 'player2'\n elif game['current_player'] == 'player2':\n game['current_player'] = 'player1'\n elif game['current_player'] == '':\n game['current_player'] = 'player2'\n\ndef check_game_over(game):\n current_player = game['players'][game['current_player']]\n symbol = current_player['symbol']\n position = current_player['played']['onboard']\n l = position[0]\n c = position[1]\n board = game['board']\n line = 0\n col = 0\n diag1 = 0\n diag2 = 0\n has_space = False\n for i in range(0,3):\n if board[l][i] == symbol:\n line+=1\n if board[i][c] == symbol:\n col+=1\n if l == c and board[i][i] == symbol:\n diag1+=1\n if position in [(2,0), (0,2), (1,1)] and board[i][2-i] == symbol:\n diag2+=1\n if(' ' in board[i]):\n has_space = True\n if line == 3 or col == 3 or diag1 == 3 or diag2 == 3:\n game['game_over'] = True\n if not has_space:\n game['no_space'] = True\n\n\ndef check_new_game(game):\n if game['game_over']:\n print_board(game['board'])\n print(game['players'][game['current_player']]['name']+\" won!!!\")\n read_play_again()\n if game['no_space']:\n print_board(game['board'])\n print(\" GAME OVER \")\n read_play_again()\n\ndef read_play_again():\n new_game = ''\n while(new_game.lower() not in ['y','n']):\n new_game = input(\"Play another round? (y/n)\")\n if new_game.lower() == 'y':\n reset_game(game)\n else:\n print(\"Thanks for playing! :)\")\n game['game_over'] = True\n\ndef reset_game(game):\n game['game_over'] = False\n game['no_space'] = False\n game['board'] = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n\ngame = init_game()\nread_players(game['players'])\nplaying = True\nwhile(playing):\n print_board(game['board'])\n select_current_player(game)\n read_turn(game)\n map_input_to_board(game)\n check_game_over(game)\n check_new_game(game)\n playing = not game['game_over']\n","repo_name":"ewertonramos/tic_tac_toe","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21469432071","text":"import sys\r\n\r\nn, m = map(int, sys.stdin.readline().split())\r\nword_set = {}\r\n\r\nfor _ in range(n):\r\n word = sys.stdin.readline().strip()\r\n\r\n if len(word) >= m:\r\n if word in word_set:\r\n word_set[word] += 1\r\n else:\r\n word_set[word] = 1\r\n\r\nword_dict = sorted(word_set.items(),key=lambda x:(-x[1],-len(x[0]),x[0]))\r\nfor word in word_dict:\r\n print(word[0])\r\n\r\n\r\n","repo_name":"tngus4334/BOJ-Programmers","sub_path":"백준/Silver/20920. 영단어 암기는 괴로워/영단어 암기는 괴로워.py","file_name":"영단어 암기는 괴로워.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":"37271847826","text":"\"\"\"\nSuite de testes para serializers.py\nComo o objetivo do desafio era criar endpoints para agendamento de mensagem, foram implementados\napenas testes para MensagemSerializer. No futuro, como forma de aprendizado pessoal, serão\nimplementados para as outras ViewSets definidas em serializers.py\n\"\"\"\n\nfrom django.urls import reverse\nimport pytest\nfrom .models import Destinatario, Mensagem, ModoEnvio\nfrom .serializers import MensagemSerializer\nfrom mixer.backend.django import mixer\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nimport json\nimport io\nimport datetime\n\npytestmark = pytest.mark.django_db\n\nclass TesteMensagemSerializer:\n \"\"\"\n Classe para teste de MensagemSerializer\n \"\"\"\n\n def setup(self):\n \"\"\"\n Definição de setup para testes\n \"\"\"\n #criando instância de Destinatario com id=3\n self.dest = mixer.blend(Destinatario, id=3, email=\"teste@django.com\")\n #criando instância de ModoEnvio id=1\n self.modoEnvio = mixer.blend(ModoEnvio, id=1)\n #setando data atual\n self.data = datetime.date.today()\n #setando hora para daqui 30 minutos\n self.hora = datetime.datetime.now() + datetime.timedelta(minutes=30)\n self.agendamento = mixer.blend(Mensagem, destinatario= self.dest, modo = self.modoEnvio, data_envio = self.data, \n hora_envio = self.hora)\n\n def test_mensagem_count_fields(self):\n \"\"\"\n Função para verificar se a quantidade de campos está de acordo com a definida em MensagemSerializer (serializers.py)\n \"\"\"\n serializer = MensagemSerializer(self.agendamento)\n\n assert len(serializer.data.keys()) == 8 \n\n def test_mensagem_fields(self):\n \"\"\"\n Função para verificar se os campos estão de acordo com o definido em MensagemSerializer (serializers.py)\n \"\"\"\n serializer = MensagemSerializer(self.agendamento)\n\n assert set(serializer.data.keys()) == set(['id','titulo', 'texto', 'data_envio', 'hora_envio','modo','enviado','destinatario'])\n \n def test_mensagem_hora_invalida(self):\n \"\"\"\n Função para verificar se mensagem com horário incorreto é inválida\n \"\"\"\n agendamento = mixer.blend(Mensagem, destinatario= self.dest, modo = self.modoEnvio, data_envio = self.data, \n hora_envio = datetime.datetime.now().time())\n \n serializer = MensagemSerializer(data=agendamento)\n assert not serializer.is_valid()\n\n\n def test_mensagem_data_invalida(self):\n \"\"\"\n Função para verificar se mensagem com horário incorreto é inválida\n \"\"\"\n agendamento = mixer.blend(Mensagem, destinatario= self.dest, modo = self.modoEnvio, data_envio = '2020-01-01', \n hora_envio = self.hora)\n \n serializer = MensagemSerializer(data=agendamento)\n assert not serializer.is_valid()\n assert serializer.error_messages == \"Horário inválido! Cadastrastre horários a partir de horário atual.\"\n\n def test_mensagem_data_invalida(self):\n \"\"\"\n Função para verificar se mensagem com data incorreta é inválida\n \"\"\"\n agendamento = mixer.blend(Mensagem, destinatario= self.dest, modo = self.modoEnvio, data_envio = '2020-01-01', \n hora_envio = self.hora)\n \n serializer = MensagemSerializer(data=agendamento)\n assert not serializer.is_valid()\n\n def test_mensagem_titulo_email(self):\n \"\"\"\n Função para verificar se mensagem de E-mail ou Push sem título é inválida\n \"\"\"\n #criando mensagem com valores aleatórios, com Destinatario especificado, com título (Modo: E-mail)\n agendamento = mixer.blend(Mensagem, titulo = \"\", destinatario = self.dest, modo = self.modoEnvio, \n data_envio = self.data, hora_envio = datetime.datetime.now().time())\n\n \n serializer = MensagemSerializer(data=agendamento)\n assert not serializer.is_valid()\n\n modo = mixer.blend(ModoEnvio, id=4)\n #criando segunda mensagem com valores aleatórios, com Destinatario especificado, com título (Modo: Push)\n agendamento2 = mixer.blend(Mensagem, titulo = \"\", destinatario = self.dest, modo = modo, \n data_envio = self.data, hora_envio = datetime.datetime.now().time())\n\n serializer = MensagemSerializer(data=agendamento2)\n assert not serializer.is_valid()\n","repo_name":"danembaum/com_api","sub_path":"luiza_api/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73317951844","text":"import pyglet\r\nfrom pyglet.window import key\r\nfrom pyglet import resource\r\nfrom game import resources\r\n\r\nclass Player(pyglet.sprite.Sprite):\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n self.vx = 0\r\n self.vy = 0\r\n self.keyHandler = key.KeyStateHandler()\r\n self.falling = False\r\n self.standing = True\r\n self.moving = False\r\n self.jumpCooled = True\r\n self.left = False\r\n self.right = False\r\n self.squash = False\r\n #previous state = unknown\r\n\r\n def update(self, dt):\r\n left = self.keyHandler[key.LEFT] or self.keyHandler[key.A]\r\n right = self.keyHandler[key.RIGHT] or self.keyHandler[key.D]\r\n up = self.keyHandler[key.UP] or self.keyHandler[key.W]\r\n down = self.keyHandler[key.DOWN] or self.keyHandler[key.S]\r\n\r\n if self.squash and not (self.left or self.right or up):\r\n self.image = resources.playerSquashImage\r\n elif not (left or right or down or self.squash):\r\n self.image = resources.playerImage\r\n\r\n if left:\r\n if not self.left and self.squash:\r\n self.image = resources.playerLeftSquashImage\r\n elif not self.left:\r\n self.image = resources.playerLeftImage\r\n self.left = True\r\n self.right = False\r\n elif right:\r\n if not self.left and self.squash:\r\n self.image = resources.playerRightSquashImage\r\n elif not self.left:\r\n self.image = resources.playerRightImage\r\n self.right = True\r\n self.left = False\r\n else:\r\n self.left = False\r\n self.right = False\r\n #if self.moving == True:\r\n # self.moving = False\r\n # self.image = resources.playerImage\r\n if up:\r\n if not self.falling and self.jumpCooled:\r\n self.squash = False\r\n self.jumpCooled = False\r\n pyglet.clock.schedule_once(self.coolJump, 0.1)\r\n self.vy += 600\r\n if not self.left or self.right or left or right:\r\n self.image = resources.playerImage\r\n #if self.standing:\r\n # print(\"This condition reduces comparisions, but is it necessary?\")\r\n #if not self.standing and left:\r\n # self.image = resources.playerLeftImage\r\n #elif not self.standing and right:\r\n # self.image = resources.playerRightImage\r\n #else:\r\n # self.image = resources.playerImage\r\n if down:\r\n self.standing = False\r\n self.image = resources.playerSquashImage\r\n pyglet.clock.schedule_once(self.getUp, 0.5)\r\n\r\n self.y += self.vy * dt\r\n\r\n def fall(self, dt):\r\n self.falling = True\r\n if self.vy > -600:\r\n self.vy = self.vy - 1200 * dt\r\n\r\n def landed(self, yPosition):\r\n self.falling = False\r\n self.standing = False\r\n self.squash = True\r\n self.y = yPosition\r\n self.vy = 0\r\n #if self.keyHandler[key.LEFT] or self.keyHandler[key.A]:\r\n # self.image = resources.playerLeftSquashImage\r\n #elif self.keyHandler[key.RIGHT] or self.keyHandler[key.D]:\r\n # self.image=resources.playerRightSquashImage\r\n #else:\r\n # self.image = resources.playerSquashImage\r\n pyglet.clock.schedule_once(self.getUp, 0.5)\r\n \r\n\r\n def getUp(self, dt):\r\n self.standing = True\r\n self.moving = False\r\n self.squash = False\r\n\r\n def coolJump(self, dt):\r\n self.jumpCooled = True\r\n\r\n\r\n","repo_name":"T-Muha/Slime_Platform_Game","sub_path":"version1/game/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11481303359","text":"# def Urlify(str):\n# result = []\n# for i, char(str):\n# print(char[i])\n\n\n\n\n# Urlify('hey steve man ');\n\n\ndef isUinque(string):\n # Assuming character set is ASCII (128 characters)\n letters = {}\n for letter in string:\n if letter in letters:\n return False\n letters[letter] = True\n return True\n\nisUinque('heya')\n\ndef isPerm(str1, str2):\n word1 = str1","repo_name":"Maxjoeld/Algos","sub_path":"ctci/Solutions in py/chap1.py","file_name":"chap1.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1365227398","text":"import pandas as pd\nimport os\nimport numpy as np\nimport sys\n\ndef merge_stars(data_folder):\n \"\"\"\n This function merges the data from the negative and positive direction STARS data by taking the data corresponding to the values with the highest p-value.\n\n :param data_folder: full path to folder containing combined STARS data (postivie and negative directions appended together)\n :return: saves the merged data over the original data so that all genes appear once and have one corresponding STARS score.\n \"\"\"\n files = os.listdir(data_folder)\n\n for f in files:\n if not f.startswith(\".\") and not os.path.isdir(os.path.join(data_folder, f)):\n path = os.path.join(data_folder, f)\n all_data = pd.read_csv(path, sep = \"\\t\")\n merged_data = pd.DataFrame()\n print(f\"On file {f}\")\n for gene in all_data['Gene.Symbol'].unique():\n gene_data = all_data.loc[all_data['Gene.Symbol'] == gene]\n\n max_index = gene_data[\"p.value\"].idxmax()\n min_index = gene_data[\"p.value\"].idxmin()\n \n # Taking greater p-value unless one of them is signifcant with\n # an FDR of less than 0.25\n if all_data.iloc[min_index][\"p.value\"] < 0.05 and all_data.iloc[min_index][\"FDR\"] < 0.25:\n merged_data = merged_data.append(all_data.iloc[min_index])\n\n else:\n merged_data = merged_data.append(all_data.iloc[max_index])\n\n\n merged_data = merged_data[[\"Gene.Symbol\", \"STARS.Score\", \"p.value\", \"FDR\", \"q.value\"]].sort_values(\"STARS.Score\", ascending = False).reset_index(drop = True)\n merged_data.to_csv(os.path.join(data_folder, f), sep = \"\\t\", index = False)\n\n return\n\ndef read_csv(csv_file):\n \"\"\"\n This function reads in any number of csv files (list or one) and returns a dictionary of all of the data in the individual csv files. The key is the name of the file and the value is a pandas data frame.\n\n :param csv_file: single or list of full file paths to csv files\n :return: dictionary of pandas data frames with keys as file names and values as the corresponding data from the csv file\n \"\"\"\n if type(csv_file) == str:\n return pd.read_csv(csv_file, sep = \"\\t\")\n\n elif len(csv_file) > 1:\n data = {}\n for file in list(csv_file):\n fname = os.path.basename(file)\n data[fname] = pd.read_csv(file, sep = \"\\t\")\n\n return data\n \n elif csv_file:\n return pd.read_csv(csv_file[0], sep = \"\\t\")\n\n else:\n print(\"Issue with file locations.\")\n sys.exit()\n\ndef data_extract(dataframe, keys):\n cols = dataframe.columns.tolist()\n gene_col = [x for x in cols if \"gene\" in x.lower()]\n gene_col = gene_col[0]\n return dataframe.loc[dataframe[gene_col].isin(keys)].sort_values(by = [gene_col]).set_index(gene_col)\n\ndef add_lfc(data_path, reference_path):\n \"\"\"\n This function takes in the STARS files with a STARS score, p.value, fdr, and q.value for each gene and then appends the median LFC from the reference file provided by reference_path.\n\n :param data_path: full file path to the location containing the STARS files.\n :param reference_path: full file path to the reference log fold change data.\n\n :return: a copy of each of the STARS files with the appended median LFC from the reference_file.\n \"\"\"\n stars_files = os.listdir(data_path)\n stars_files = [os.path.join(data_path, file) for file in stars_files if (\n not file.startswith(\".\") and not os.path.isdir(os.path.join(data_path, file)))]\n data = read_csv(stars_files)\n normalized_lfc = read_csv(reference_path)\n\n for key in data:\n merged_data = data[key].sort_values(by=\"Gene.Symbol\")\n m_d_genes = merged_data[\"Gene.Symbol\"].tolist()\n filtered_data = data_extract(normalized_lfc, m_d_genes)\n sample_name = key[key.rfind(\"-\")+1:key.rfind(\".\")]\n median_lfc = filtered_data.groupby(\n \"GeneID\").agg({sample_name: np.median})\n merged_data[sample_name] = median_lfc.values\n merged_data.to_csv(os.path.join(data_path, f\"STARS-with-Median-LFC-{sample_name}.csv\"), \n index=False)\n\n return\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description='Merge STARS data')\n parser.add_argument('DataPath', metavar='Y', type=str, \n help='The full file path to the merged STARS data')\n parser.add_argument('ReferenceData', metavar='Y', type=str,\n help='The full file path to the reference log fold change data to extract the median LFC from')\n args = parser.parse_args()\n\n merge_stars(args.DataPath)\n add_lfc(args.DataPath, args.ReferenceData)\n","repo_name":"kkapner/Biancur-CellMetabolism-2020","sub_path":"code/py/MergeSTARS.py","file_name":"MergeSTARS.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"13256856508","text":"import django.urls as u\nfrom django.conf.urls import url\n\nfrom . import views\nfrom .views import ListAnimalCard, AnimalCardUpdate, ListParentCard, ParentCardUpdate, ListAdopted, AdoptedUpdate\n\nurlpatterns = [\n u.path('animals/', views.show_animal_card, name='show-animal'), # показать карту животного\n u.path('new_animal_card', views.create_animal_card, name='new-animal-card'), # создать карту животного\n u.path('animals/list_animal_card', ListAnimalCard.as_view(), name='list-animal-card'), # показать список карт животных\n u.path('animals/delete_animal_card/', views.delete_animal_card, name='delete_animal_card'), # удалить карту животного\n u.path('animals/update_animal_card/', AnimalCardUpdate.as_view(), name='update_animal_card'), # изменить карту животного\n # u.path('animals/adopted_animal/', views.adopted_animal, name='adopted_animal'), # усыновить животного\n\n u.path('parents/', views.show_parent_card, name='show-parent'), # показать карту родителя\n u.path('new_parent_card', views.create_parent_card, name='new-parent-card'), # создать карту родителя\n u.path('parents/list_parent_card', ListParentCard.as_view(), name='list-parent-card'), # показать список карт родителей\n u.path('parents/delete_parent_card/', views.delete_parent_card, name='delete_parent_card'), # удалить карту родителя\n u.path('parents/update_parent_card/', ParentCardUpdate.as_view(), name='update_parent_card'), # изменить карту родителя\n\n u.path('adopted/', views.show_adopted, name='show-adopted'), # показать информацию об усыновлении\n u.path('new_adopted', views.create_adopted, name='new-adopted'), # усыновить животное\n u.path('adopted/list_adopted', ListAdopted.as_view(), name='list-adopted'), # показать список усыновленных\n u.path('adopted/delete_adopted/', views.delete_adopted, name='delete_adopted'), # удалить информацию об усыновлении\n u.path('adopted/update_adopted/', AdoptedUpdate.as_view(), name='update_adopted'), # изменить информацию об усыновлении\n]\n","repo_name":"medvedevanatalya/django_project","sub_path":"animal_shelter/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70564596964","text":"# stdlib\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Union\n\n# third party\nfrom google.protobuf.reflection import GeneratedProtocolMessageType\nfrom nacl.signing import VerifyKey\n\n# syft absolute\nimport syft as sy\n\n# relative\nfrom ..... import lib\nfrom .....logger import traceback_and_raise\nfrom .....proto.core.node.common.action.run_function_or_constructor_pb2 import (\n RunFunctionOrConstructorAction as RunFunctionOrConstructorAction_PB,\n)\nfrom .....util import inherit_tags\nfrom ....common.serde.serializable import serializable\nfrom ....common.uid import UID\nfrom ....io.address import Address\nfrom ....pointer.pointer import Pointer\nfrom ....store.storeable_object import StorableObject\nfrom ...abstract.node import AbstractNode\nfrom ..util import listify\nfrom .common import ImmediateActionWithoutReply\n\n\n@serializable()\nclass RunFunctionOrConstructorAction(ImmediateActionWithoutReply):\n \"\"\"\n When executing a RunFunctionOrConstructorAction, a :class:`Node` will run\n a function defined by the action's path attribute and keep the returned value\n in its store.\n\n Attributes:\n path: the dotted path to the function to call\n args: args to pass to the function. They should be pointers to objects\n located on the :class:`Node` that will execute the action.\n kwargs: kwargs to pass to the function. They should be pointers to objects\n located on the :class:`Node` that will execute the action.\n \"\"\"\n\n def __init__(\n self,\n path: str,\n args: Union[Tuple[Any, ...], List[Any]],\n kwargs: Dict[Any, Any],\n id_at_location: UID,\n address: Address,\n msg_id: Optional[UID] = None,\n is_static: Optional[bool] = False,\n ):\n super().__init__(address=address, msg_id=msg_id)\n self.path = path\n self.args = listify(args) # args need to be editable for plans\n self.kwargs = kwargs\n self.id_at_location = id_at_location\n self.is_static = is_static\n\n @staticmethod\n def intersect_keys(\n left: Union[Dict[VerifyKey, UID], None], right: Dict[VerifyKey, UID]\n ) -> Dict[VerifyKey, UID]:\n # TODO: duplicated in run_class_method_action.py\n # get the intersection of the dict keys, the value is the request_id\n # if the request_id is different for some reason we still want to keep it,\n # so only intersect the keys and then copy those over from the main dict\n # into a new one\n if left is None:\n return right\n intersection = left.keys() & right.keys()\n # left and right have the same keys\n return {k: left[k] for k in intersection}\n\n def execute_action(self, node: AbstractNode, verify_key: VerifyKey) -> None:\n method = node.lib_ast(self.path)\n result_read_permissions: Union[None, Dict[VerifyKey, UID]] = None\n\n resolved_args = list()\n tag_args = []\n for arg in self.args:\n if not isinstance(arg, Pointer):\n traceback_and_raise(\n ValueError(\n f\"args attribute of RunFunctionOrConstructorAction should only contain Pointers. \"\n f\"Got {arg} of type {type(arg)}\"\n )\n )\n\n r_arg = node.store[arg.id_at_location]\n result_read_permissions = self.intersect_keys(\n result_read_permissions, r_arg.read_permissions\n )\n resolved_args.append(r_arg.data)\n tag_args.append(r_arg)\n\n resolved_kwargs = {}\n tag_kwargs = {}\n for arg_name, arg in self.kwargs.items():\n if not isinstance(arg, Pointer):\n traceback_and_raise(\n ValueError(\n f\"kwargs attribute of RunFunctionOrConstructorAction should only contain Pointers. \"\n f\"Got {arg} of type {type(arg)}\"\n )\n )\n\n r_arg = node.store[arg.id_at_location]\n result_read_permissions = self.intersect_keys(\n result_read_permissions, r_arg.read_permissions\n )\n resolved_kwargs[arg_name] = r_arg.data\n tag_kwargs[arg_name] = r_arg\n\n # upcast our args in case the method only accepts the original types\n (\n upcasted_args,\n upcasted_kwargs,\n ) = lib.python.util.upcast_args_and_kwargs(resolved_args, resolved_kwargs)\n\n # execute the method with the newly upcasted args and kwargs\n result = method(*upcasted_args, **upcasted_kwargs)\n\n # to avoid circular imports\n if lib.python.primitive_factory.isprimitive(value=result):\n # Wrap in a SyPrimitive\n result = lib.python.primitive_factory.PrimitiveFactory.generate_primitive(\n value=result, id=self.id_at_location\n )\n else:\n if hasattr(result, \"id\"):\n result._id = self.id_at_location\n\n # If we have no permission (None or {}) we add some default permissions based on a permission list\n if result_read_permissions is None:\n result_read_permissions = {}\n\n if not isinstance(result, StorableObject):\n result = StorableObject(\n id=self.id_at_location,\n data=result,\n read_permissions=result_read_permissions,\n )\n\n inherit_tags(\n attr_path_and_name=self.path,\n result=result,\n self_obj=None,\n args=tag_args,\n kwargs=tag_kwargs,\n )\n\n node.store[self.id_at_location] = result\n\n def __repr__(self) -> str:\n method_name = self.path.split(\".\")[-1]\n arg_names = \",\".join([a.__class__.__name__ for a in self.args])\n kwargs_names = \",\".join(\n [f\"{k}={v.__class__.__name__}\" for k, v in self.kwargs.items()]\n )\n return f\"RunClassMethodAction {method_name}({arg_names}, {kwargs_names})\"\n\n def _object2proto(self) -> RunFunctionOrConstructorAction_PB:\n \"\"\"Returns a protobuf serialization of self.\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms the current object into the corresponding\n Protobuf object so that it can be further serialized.\n\n :return: returns a protobuf object\n :rtype: RunFunctionOrConstructorAction_PB\n\n .. note::\n This method is purely an internal method. Please use serialize(object) or one of\n the other public serialization methods if you wish to serialize an\n object.\n \"\"\"\n return RunFunctionOrConstructorAction_PB(\n path=self.path,\n args=[sy.serialize(x, to_bytes=True) for x in self.args],\n kwargs={k: sy.serialize(v, to_bytes=True) for k, v in self.kwargs.items()},\n id_at_location=sy.serialize(self.id_at_location),\n address=sy.serialize(self.address),\n msg_id=sy.serialize(self.id),\n )\n\n @staticmethod\n def _proto2object(\n proto: RunFunctionOrConstructorAction_PB,\n ) -> \"RunFunctionOrConstructorAction\":\n \"\"\"Creates a ObjectWithID from a protobuf\n\n As a requirement of all objects which inherit from Serializable,\n this method transforms a protobuf object into an instance of this class.\n\n :return: returns an instance of RunFunctionOrConstructorAction\n :rtype: RunFunctionOrConstructorAction\n\n .. note::\n This method is purely an internal method. Please use deserialize()\n if you wish to deserialize an object.\n \"\"\"\n\n return RunFunctionOrConstructorAction(\n path=proto.path,\n args=tuple(sy.deserialize(blob=x, from_bytes=True) for x in proto.args),\n kwargs={\n k: sy.deserialize(blob=v, from_bytes=True)\n for k, v in proto.kwargs.items()\n },\n id_at_location=sy.deserialize(blob=proto.id_at_location),\n address=sy.deserialize(blob=proto.address),\n msg_id=sy.deserialize(blob=proto.msg_id),\n )\n\n @staticmethod\n def get_protobuf_schema() -> GeneratedProtocolMessageType:\n \"\"\"Return the type of protobuf object which stores a class of this type\n\n As a part of serialization and deserialization, we need the ability to\n lookup the protobuf object type directly from the object type. This\n static method allows us to do this.\n\n Importantly, this method is also used to create the reverse lookup ability within\n the metaclass of Serializable. In the metaclass, it calls this method and then\n it takes whatever type is returned from this method and adds an attribute to it\n with the type of this class attached to it. See the MetaSerializable class for details.\n\n :return: the type of protobuf object which corresponds to this class.\n :rtype: GeneratedProtocolMessageType\n\n \"\"\"\n\n return RunFunctionOrConstructorAction_PB\n\n def remap_input(self, current_input: Any, new_input: Any) -> None:\n \"\"\"Redefines some of the arguments of the function\"\"\"\n for i, arg in enumerate(self.args):\n if arg.id_at_location == current_input.id_at_location:\n self.args[i] = new_input\n\n for k, v in self.kwargs.items():\n if v.id_at_location == current_input.id_at_location:\n self.kwargs[k] = new_input\n","repo_name":"datax-io/pysyft-parcel","sub_path":"packages/syft/src/syft/core/node/common/action/function_or_constructor_action.py","file_name":"function_or_constructor_action.py","file_ext":"py","file_size_in_byte":9618,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"32713002520","text":"import argparse\n\n\n\ndef hash_to_frequency(input_hash):\n byte_array = bytearray.fromhex(input_hash)\n frequencies = []\n \n\n for byte in byte_array:\n frequency = byte*20 # mapping each byte of RICK to a frequency\n frequencies.append(frequency)\n\n return ' '.join(map(str, frequencies))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Convert morty raw hex to a frequency')\n parser.add_argument('input_hash', type=str, help='inputhexheremorty')\n args = parser.parse_args()\n print(hash_to_frequency(args.input_hash))\n","repo_name":"evilmortyyy/morty2freq","sub_path":"morty2hz.py","file_name":"morty2hz.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73811859366","text":"import sys\r\nimport toml\r\n\r\nclass TomlHandler:\r\n\r\n objToml = None\r\n\r\n def __init__(self,fileNameToml=None) -> None:\r\n self.initialization()\r\n\r\n if fileNameToml is not None:\r\n self.objToml = self.getTomlObject(fileNameToml=fileNameToml)\r\n\r\n def __del__(self) -> None:\r\n pass\r\n\r\n def initialization(self):\r\n self.objToml = None\r\n\r\n def getTable(self,keyTable=None):\r\n return self.objToml[keyTable]\r\n \r\n def getValue(self,keyTable=None,keyList=None,indexList=None):\r\n dict = self.getTable(keyTable=keyTable)\r\n\r\n if indexList is None:\r\n valueList = []\r\n for i in range(len(keyList)):\r\n value = dict[keyList[i]]\r\n valueList.append(value)\r\n else:\r\n valueList = []\r\n for i in range(len(keyList)):\r\n value = dict[indexList[i]][keyList[i]]\r\n valueList.append(value)\r\n\r\n return tuple(valueList)\r\n\r\n @staticmethod\r\n def displayContents(fileNameToml):\r\n with open(fileNameToml) as f:\r\n obj = toml.load(f)\r\n print(obj)\r\n data = toml.dumps(obj) \r\n print(data)\r\n\r\n @staticmethod\r\n def getTomlObject(fileNameToml):\r\n try:\r\n with open(fileNameToml) as f:\r\n obj = toml.load(f)\r\n return obj\r\n except:\r\n return None\r\n\r\n @staticmethod\r\n def addNewItem(obj=None,key=None,value=None):\r\n obj[key] = value\r\n \r\n @staticmethod\r\n def save(obj=None,fileNameToml=None):\r\n with open(fileNameToml, 'w') as f:\r\n f.write(toml.dumps(obj))\r\n\r\nif __name__ == '__main__':\r\n\r\n fileNameToml = sys.argv[1]\r\n\r\n #[01] Display All Contents of TOML\r\n TomlHandler.displayContents(fileNameToml=fileNameToml)\r\n\r\n #[02] Get Object of TOML\r\n obj = TomlHandler.getTomlObject(fileNameToml=fileNameToml)\r\n\r\n #[03] Add New Item to TOML Object\r\n TomlHandler.addNewItem(obj=obj,key='new',value='HOGE')\r\n\r\n #[04] Do something by using TOML\r\n if obj['app']=='AutoScience':\r\n print(\"This Toms data is for AutoScience\")\r\n\r\n if obj['configuration']['type']=='log':\r\n print(\"This Toms data is for Log\")\r\n \r\n print(obj)\r\n\r\n #[05] Save File\r\n TomlHandler.save(obj,fileNameToml=\"output.toml\")\r\n","repo_name":"bluedack-space/PythonLibs","sub_path":"tomlHandler/TomlHandler.py","file_name":"TomlHandler.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22163645570","text":"import yaml\n\n# at some point, needs to be generalized to all files\nlang_pairs = [('bul', 'rus'), ('ces', 'pol'), ('rus', 'bul'), ('pol', 'ces')]\nlang_map = {'bul': 'BG', 'ces': 'CS', 'pol': 'PL', 'rus': 'RU'}\nraw_data_dir = 'data/raw/'\nprocessed_data_dir = 'data/processed/'\n\nfor pair in lang_pairs:\n\tlang1, lang2 = pair[0], pair[1]\n\tandrea_lang1, andrea_lang2 = lang_map[lang1], lang_map[lang2]\n\tin_file = raw_data_dir + andrea_lang1 + '-' + andrea_lang2 + '_reconstructed.yaml'\n\tout_file = processed_data_dir + 'clusters_reconstructed.' + lang1 + '.' + lang2\n\twith open(in_file) as f, open(out_file, 'w+') as out:\n\t\tdata = yaml.load(f)\n\t\tfor head, alignments in data.items():\n\t\t\tfor alignment in alignments:\n\t\t\t\tleft_word, right_word = '', ''\n\t\t\t\tfor left, right in alignment:\n\t\t\t\t\tleft_word += ''.join(left)\n\t\t\t\t\tright_word += ''.join(right)\n\t\t\t\t# direction of recon not consistent across recon files\n\t\t\t\tif lang1 == 'ces' or lang1 == 'rus': # ces and rus have left to right recon\n\t\t\t\t\tout.write(left_word + ' ' + right_word + '\\n')\n\t\t\t\telse: # bul and pol have right to left\n\t\t\t\t\tout.write(right_word + ' ' + left_word + '\\n')\n\n\t\t\t","repo_name":"trenslow/thesis","sub_path":"code/data_acq_and_proc/recons.py","file_name":"recons.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70365607525","text":"#this function runs a full drive\n\nimport numpy as np\nimport pandas as p\n\n#helper function that prints current state in pretty way\ndef print_status(S1, y):\n if S1[2] > 50:\n print(\"YTG: \", S1[0], \" Down: \", S1[1], \" LOS: own \", 100-S1[2], \" Yards gained: \", y) #the states are not saved!\n elif S1[2] == 50:\n print(\"YTG: \", S1[0], \" Down: \", S1[1], \" LOS: \", S1[2], \" Yards gained: \", y)\n elif S1[2] < 50 and S1[2] > 20:\n print(\"YTG: \", S1[0], \" Down: \", S1[1], \" LOS: opponent's \", S1[2], \" Yards gained: \", y)\n else:\n print(\"RED ZONE ALERT!!! YTG: \", S1[0], \" Down: \", S1[1], \" LOS: opponent's \", S1[2], \" Yards gained: \", y)\n\ndef turnover_on_downs_print_status(y):\n #y is in terms of your team's last possession. So to get it in terms of your opponents position\n #we need to take 100-y\n x = 100 - y\n s1 = \"Sorry, you have lost possession on downs. Your opponent gets the ball on \"\n s2 = \"their own \" + str(100-x)\n s3 = \" yard line.\"\n if x == 50:\n s2 = \"the 50\"\n elif x < 50:\n s2 = \"your \" + str(x)\n print(s1 + s2 + s3)\n\n#full drive function takes in a starting state and simulates a full drive that either: ends in a \"touchdown\"\n# worth 7 points, or ends in a loss of possession on downs.\n\ndef full_drive(S):\n S1 = list(S)\n is_not_done = True\n k = 0 #this allows us to gracefully kick out of a bad while loop. Not needed in production\n #but in case you miscode something while running a while loop, it's always good to not have to kill the kernel.\n\n drive_result = {'score':None, 'end_yard':None}\n # drive_result = list(score = NA, end_yard = NA) #we don't really need to declare this here, I'm just being inefficient\n # drive_results [score, end_yard]\n\n #this is the meat of the drive. Basically, we either score or run out of downs. NOthing else.\n while is_not_done:\n\n y = int(np.random.normal(loc=3, scale=1))\n\n # y = makePlay(S1)\n\n # y = floor(rnorm(1, mean=3, sd=1)) #how many yards do you gain. This is a silly way to sample yards. Should\n #definitely be replaced with a smarter sampling function, and one that is\n #estimated from the data!\n\n #print current state\n print_status(S1, y)\n\n # A = yards remaining in down\n # B = down counter\n # C = yards remaining to goal\n C_new = S1[2] - y\n B_new = S1[1] + 1\n A_new = S1[0] - y\n if(A_new <= 0):\n B_new = 1\n A_new = 10\n if C_new <= 0: # c_new == 0 means reach goal (score)\n is_not_done = False\n drive_result['score'] = 7\n break\n elif B_new >= 5: #bnew==turnoveronddowns\n # print('turnover on downs')\n is_not_done = False\n drive_result['end_yard'] = C_new\n turnover_on_downs_print_status(C_new)\n break\n else:\n k = k+1\n S1[0] = A_new\n S1[1] = B_new\n S1[2] = C_new\n # print(S1)\n if k > 100:\n is_not_done = False\n drive_result['end_yard'] = C_new\n break\n\n return drive_result #return drive result which is (score, end_yard). One of those will always be NA.\n\n","repo_name":"jerrylu17/statproject","sub_path":"run_full_drive.py","file_name":"run_full_drive.py","file_ext":"py","file_size_in_byte":3062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40599237862","text":"import matplotlib.pyplot as plt\nimport csv\nfrom datetime import datetime\nfrom more_itertools import chunked\n\ntimestamp = []\nsensor_temp = []\nsup_temp = []\npt_temp = []\ntime = []\ndiff = []\ntime_gap = 10\n\nnow = str(datetime.now().strftime(\"%m%d_%H%M\"))\nfile_name = \"../Data/0610_0046_surf_temp_1150_calib.csv\"\nwith open(file_name, 'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n for row in plots:\n timestamp.append(str(row[0]))\n sensor_temp.append(float(row[8]))\n pt_temp.append(float(row[-2]))\n sup_temp.append(float(row[-1]))\n diff.append(float(row[8]) - float(row[-2]))\n for i in range(0, int(600/time_gap)):\n time.append(i)\n\n temp_1150_t10s_arv = [sum(x) / len(x) for x in chunked(sensor_temp, time_gap)]\n\nfig, ax1 = plt.subplots()\nax1.plot(sensor_temp, label='Sensor_Temp')\nax1.plot(sup_temp, label='VL-Temp')\nax1.plot(pt_temp, label='PT1000_Wand_Temp')\nax1.set_ylabel('Temperatur')\nax1.set_ylim(32,35)\nax1.legend(loc='upper right')\n\nax2 = ax1.twinx()\nax2.set_ylabel('Temperaturdifferenz in K')\nax2.plot(diff, label='Diff_Sensor-PT', color=\"red\")\nax2.set_ylim(0, 1)\nax2.legend(loc='upper left')\n#plt.ylim((34, 38))\n\nplt.show()\n","repo_name":"Schwarz-XU/MA_IR-Kamera","sub_path":"raspi-mlx90640/testbench_PLC/plot_surf_calib.py","file_name":"plot_surf_calib.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10141723535","text":"#!/usr/bin/env python\n'''\n Node to get the destination for the robot to travel to\n Convert it to x and y co-ordinates and send it move base\n through the action server\n Publishes - MoveBaseClient service\n Subscribes - /goToPoint\n Author: Siddharth Srivatsa\n'''\n\nimport rospy\nfrom nav_msgs.msg import Odometry\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nfrom geometry_msgs.msg import *\nimport actionlib\nimport move_base_msgs\n\ndef odomcallback(data):\n MoveBaseClient = actionlib.SimpleActionClient('move_base', move_base_msgs.msg.MoveBaseAction)\n MoveBaseClient.wait_for_server()\n goal = MoveBaseGoal()\n\n # we'll send a goal to the robot to move 1 meter forward\n goal.target_pose.header.frame_id = \"map\";\n goal.target_pose.header.stamp = rospy.Time.now()\n\n goal.target_pose.pose.position.x = data.position.x\n goal.target_pose.pose.position.y = data.position.y\n goal.target_pose.pose.position.z = data.position.z\n goal.target_pose.pose.orientation.w = data.orientation.w\n goal.target_pose.pose.orientation.x = data.orientation.x\n goal.target_pose.pose.orientation.y = data.orientation.y\n goal.target_pose.pose.orientation.z = data.orientation.z\n\n MoveBaseClient.send_goal(goal)\n MoveBaseClient.wait_for_result()\n\n sub_once.unregister()\n \ndef destinationPoint():\n rospy.init_node('destinationPoint', anonymous=True)\n global sub_once\n sub_once = rospy.Subscriber('/goToPoint', Pose, odomcallback)\n\n rospy.spin()\n\nif __name__ == '__main__':\n destinationPoint()\n","repo_name":"srsidd/CIS700_Squirtle","sub_path":"squirtle_navigation/src/destinationPoint.py","file_name":"destinationPoint.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3751085236","text":"import torch\nimport torch.nn as nn\nfrom config import device\n\n\nclass MoCo(nn.Module):\n \"\"\"\n Build a MoCo model with: a query encoder, a key encoder, and a queue\n https://arxiv.org/abs/1911.05722\n \"\"\"\n\n def __init__(self, dim=2048, K=64, m=0.999, T=0.07):\n \"\"\"\n dim: feature dimension (default: 128)\n K: queue size; number of negative keys (default: 65536)\n m: moco momentum of updating key encoder (default: 0.999)\n T: softmax temperature (default: 0.07)\n \"\"\"\n super(MoCo, self).__init__()\n\n self.K = K\n self.m = m\n self.T = T\n\n # create the queue\n self.register_buffer(\"queue\", torch.randn(dim, K))\n self.queue = nn.functional.normalize(self.queue, dim=0)\n\n self.register_buffer(\"queue_ptr\", torch.zeros(1, dtype=torch.long))\n\n @torch.no_grad()\n def _dequeue_and_enqueue(self, keys):\n batch_size = keys.shape[0]\n ptr = int(self.queue_ptr)\n\n if self.K % batch_size != 0 or self.K - (ptr + 1) < batch_size:\n return\n\n assert self.K % batch_size == 0 # for simplicity\n\n # replace the keys at ptr (dequeue and enqueue)\n self.queue[:, ptr:ptr + batch_size] = keys.T\n ptr = (ptr + batch_size) % self.K # move pointer\n\n self.queue_ptr[0] = ptr\n\n def forward(self, query, k):\n \"\"\"\n Input:\n im_q: a batch of query images\n im_k: a batch of key images\n Output:\n logits, targets\n \"\"\"\n\n # Do not store gradients wrt keys\n k = k.detach()\n\n query = nn.functional.normalize(query, dim=1)\n k = nn.functional.normalize(k, dim=1)\n\n # compute logits\n # Einstein sum is more intuitive\n # positive logits: Nx1\n l_pos = torch.einsum('nc,nc->n', [query, k]).unsqueeze(-1)\n # negative logits: NxK\n l_neg = torch.einsum('nc,ck->nk', [query, self.queue.clone().detach()])\n\n # logits: Nx(1+K)\n logits = torch.cat([l_pos, l_neg], dim=1)\n\n # apply temperature\n logits /= self.T\n\n # labels: positive key indicators\n labels = torch.zeros(logits.shape[0], dtype=torch.long).to(device)\n\n # dequeue and enqueue\n self._dequeue_and_enqueue(k)\n\n return logits, labels\n","repo_name":"abhrac/trd","sub_path":"src/losses/moco.py","file_name":"moco.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36369909479","text":"import maya.cmds as cmds\n\ndef getJointWP(joint):\n cmds.spaceLocator()\n locator = cmds.ls(sl=True)[0]\n cmds.matchTransform(locator, joint)\n jointWP = cmds.xform(locator, q=True, t=True)\n cmds.delete(locator)\n return jointWP\n\ndef getDirection():\n\n joint1 = getJointWP('joint1')\n joint2 = getJointWP('joint2')\n\n number = []\n for i, j in zip(joint2, joint1):\n number.append(abs(i - j))\n\n for i in number:\n if i == max(number):\n if number.index(i) == 0:\n print('Directon is X')\n return 1\n elif number.index(i) == 1:\n print('Directon is Y')\n return 2\n elif number.index(i) == 2:\n print('Directon is Z')\n return 3\n\ndef findNub(): # This function checks whether the joint that needs to be orientated is at the end of the chain, as in, it has no children\n # If it has no children, it will be oriented to the world (meaning it will inherit orientation from the parent joint)\n for each in orient: # thus automatically aligning correctly\n if cmds.listRelatives(each) is None:\n cmds.joint(each, e=True, oj='none', ch=True, zso=True)\n else:\n cmds.joint(each, e=True, oj=allAxis, sao=secAxis, ch=True, zso=True)\n\n direction = getDirection()\nxyz = ['xyz', 'xzy', 'yxz', 'yzx', 'zxy', 'zyx'] # List with all possible combinations for primary axis orientation\na = ['x', 'y', 'z']\nb = ['up', 'down']\n\nr1 = 3\nr2 = 2\nr3 = 3\nr4 = 1\n\nsel = a[r1 - 1] + a[r2 - 1] # Querying the radio buttons and setting the desired axis from list 'a'\nallAxis = '' # The radio buttons produce integers that correspond to the letters of each radio button\nfor i in xyz: # The corresponding letters are then taken from list 'a', concatenated and compared against\n if sel in i[:2]: # list 'xyz'. The matching string is assigned to 'allAxis', which defines the orientation\n allAxis = i # of the primary axis\n\nsecAxis = a[r3 - 1] + b[r4 - 1] # Querying r3 and b to establish orientation for the secondary axis\nprint(secAxis)\ncmds.select('joint1')\ncmds.select(hi=True) # Selecting all joints in the hierarchy\norient = cmds.ls(sl=True) # and storing their names in here\nfindNub()\nc = [] # that is created (the thumb), which is wrong in the case of the hand. Rather, it needs to\ny = []\nfor each in orient: # be aligned with the elbow (the world) - that can only happen if it has no children.\n c.append(cmds.joint(each, q=True, o=True)) # Creating the joints and a list with their orientations\nfor i in c: # if any of the xyz orientations equals 180, it means the joint has flipped\n for j in i: # the following code corrects that with setting the appropriate secondary axis orientation\n y.append(round(abs(j)))\nfor i in y:\n if i == 180:\n if r3 == direction:\n if direction == 1:\n secAxis = a[r3 - 2] + b[r4 - 1]\n elif direction == 2:\n secAxis = a[r3] + b[r4 - 1]\n elif direction == 3:\n secAxis = a[r3 - 3] + b[r4 - 1]\nprint(secAxis)\nfindNub()\n","repo_name":"n00bcybot/AutoRigging","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17561010021","text":" #!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom flask import Flask, Response,request, render_template\nfrom main import Nix_Parser, mutex, cur_text\nimport sys\nfrom threading import Thread, Event,Lock\n\nimport time\n\napp = Flask(__name__)\n\nthread = Thread()\nthread_stop_event = Event()\n\nresult_file_name = 'result.xml'\nparsing_over = False\n\nclass ParsingThread(Thread):\n is_daily = False\n timeout = 0\n is_logging=False\n socket = None\n parser = None\n def __init__(self,daily,timeout_,is_logging_):\n self.delay = 1\n super(ParsingThread, self).__init__()\n self.is_daily=daily\n self.timeout = timeout_\n self.is_logging = is_logging_\n self._stop_event = Event()\n self.parser = Nix_Parser('https://www.nix.ru', 'https://www.nix.ru/price/index.html',\n self.timeout, self.is_logging)\n\n def stopped(self):\n return self._stop_event.is_set()\n\n def run_parser(self):\n global parsing_over\n parsing_over = False\n print(\"Start task\")\n try:\n self.parser.parse_catalog()\n print(\"Finished parsing\")\n self.parser.write_to_txml(result_file_name)\n parsing_over = True\n except:\n parsing_over=True\n print(\"Eror while parsing\")\n\n def stop(self):\n self._stop_event.set()\n\n def run(self):\n if self.is_daily:\n while True and not self.stopped():\n self.run_parser()\n time.sleep(86400) #sleep a day\n else:\n self.run_parser()\n\nclass Tee(object):\n def write(self, obj):\n global cur_text\n cur_text += str(obj)\n #with app.app_context():\n # return render_template('parser.html',output=cur_text)\n #socketio.emit('newText',{'text':cur_text},namespace='/')\n\n@app.route('/result')\ndef open_file():\n with open(result_file_name,'rb') as result:\n return Response(result.read(), mimetype='text/plain')\n\n\n@app.route('/close')\ndef close():\n sys.exit(0)\n\n@app.route('/',methods = ['POST', 'GET'])\ndef index():\n sys.stdout = Tee()\n if request.method == 'GET':\n return render_template('parser.html', output=cur_text) # render a template\n\n timeout = int(request.form['timeout'])\n is_logging = None\n if 'is_logging' in request.form:\n if request.form['is_logging']=='on':\n is_logging = True\n else:\n is_logging = False\n is_daily=None\n if 'is_daily' in request.form:\n if request.form['is_daily']==\"on\":\n is_daily = True\n else:\n is_daily = True\n print(\"Start parsing\")\n global thread\n if thread.isAlive():\n thread.stop()\n thread=ParsingThread(is_daily,timeout,is_logging)\n thread.start()\n return render_template('parser.html', output=cur_text)\n\nif __name__ == '__main__':\n #app.run(host='0.0.0.0', port=5001)\n #app.run(debug=True)\n parser = Nix_Parser('https://www.nix.ru', 'https://www.nix.ru/price/index.html', 0, True,1000)\n try:\n parser.parse_catalog()\n print(\"Finished parsing\")\n parser.write_to_txml('result_file.xml')\n except Exception as e:\n print(\"Error parsing\")\n print(e)\n parser.write_to_txml('result_file_error.xml')\n\n","repo_name":"5yato4ok/web_parser","sub_path":"nix/html_gui.py","file_name":"html_gui.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8644453387","text":"#!/usr/bin/python\n\nimport psycopg2\nfrom config import config\n\ndef delete_part(part_id):\n \"\"\" delete part by part id \"\"\"\n conn = None\n rows_deleted = 0\n try:\n # read database configuration\n params = config()\n # connect to the PostgreSQL database\n conn = psycopg2.connect(**params)\n # create a new cursor\n cur = conn.cursor()\n # execute the UPDATE statement\n cur.execute(\"DELETE FROM parts WHERE part_id = %s\", (part_id,))\n # get the number of updated rows\n rows_deleted = cur.rowcount\n # Commit the changes to the database\n conn.commit()\n # Close communication with the PostgreSQL database\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\n return rows_deleted\n\nif __name__ == '__main__':\n deleted_rows = delete_part(2)\n print('The number of deleted rows: ', deleted_rows)\n","repo_name":"syurskyi/Python_Topics","sub_path":"100_databases/002_posgresql/examples/PostgreSQL Python postgresqltutorial/009_Delete Data from Tables/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"14669235811","text":"import binascii\nimport serial\nimport json\nimport os\nimport sys\nimport re\nimport sbep\n\nclass xtscontroller(object):\n ''' XTS3000 Controller Class '''\n # Radio Information\n model = ''\n\n radiovalues = {} # from the maps file\n memmap = {} # Stores previously read memory\n\n def openradio(self, devfile):\n ''' Open the Radio '''\n try:\n self.device = serial.Serial(devfile)\n except serial.serialutil.SerialException:\n print(\"Unable to open %s.\" % devfile, file=sys.stderr)\n print(\"This may be a permissions issue. If you are on a Unix system, \" \\\n \"give read/write access to %s.\" % devfile, file=sys.stderr)\n sys.exit(0)\n self.device.baudrate = 9600\n self.device.stopbits = 1\n self.device.parity = serial.PARITY_NONE\n self.device.bytesize = serial.EIGHTBITS\n self.device.timeout = 1 # 1 seconds seems reasonable, eh?\n self.device.flush()\n self.device.dtr = True\n self.device.rts = True\n\n def initialize(self, devfile):\n ''' Initialize the radio '''\n self.openradio(devfile)\n \n self.device.flush()\n self.rtsdtr_off()\n self.cmd_tstmod()\n self.cmd_epreq()\n self.rtsdtr_off()\n self.device.close()\n self.openradio(devfile)\n\n def rtsdtr_off(self):\n ''' Turn off rts/dtr '''\n self.device.dtr = False\n self.device.rts = False\n\n def rtsdtr_on(self):\n ''' Turn on rts/dtr '''\n self.device.dtr = True\n self.device.rts = True\n\n def cmd_tstmod(self):\n ''' Send the TSTMOD packet '''\n tstmod = sbep.TSTMOD + sbep.sbCRC(sbep.TSTMOD)\n\n self.rtsdtr_on()\n self.device.flush()\n\n self.device.write(tstmod)\n b = self.device.read(size=5)\n if b != tstmod:\n print(\"Error 1: The device failed to return the same bits back.\", file=sys.stderr)\n print(\"This may be a connection issue or the device is malfunctioning. \" \\\n \"Try turning it off and back on.\", file=sys.stderr)\n sys.exit()\n\n self.rtsdtr_off()\n\n def cmd_epreq(self):\n ''' Send the EPREQ packet '''\n epreq = sbep.EPREQ + sbep.sbCRC(sbep.EPREQ)\n\n self.rtsdtr_on()\n self.device.flush()\n self.device.write(epreq)\n b = self.device.read(size=5)\n if b != epreq:\n print(\"Error 2: The device failed to return the same bits back\")\n sys.exit()\n self.rtsdtr_off()\n\n def get_deviceinfo(self):\n ''' Get the device model number '''\n ### This value is hard-coded, necessary to determine which map file to use \n memory = self.getmemory(b'\\x00\\x00\\x00')[3:]\n self.radiovalues['model'] = memory[14:26].decode()\n\n def memdump(self):\n ''' Dump full device memory, debugging feature '''\n for x in range(0,1048576,32):\n mem_loc = x.to_bytes(3, byteorder='big')\n data = self.getmemory(mem_loc)\n print(\"%s: %s\" % (binascii.b2a_hex(mem_loc).decode(), data))\n\n def getmemory(self, location):\n ''' Generic function to get device data '''\n\n if location in self.memmap:\n return self.memmap[location]\n\n self.device.flush()\n combined = sbep.READ_DATA_REQ + b'\\x20' + location\n crc_code = sbep.checksum(sbep.READ_DATA_REQ + b'\\x20' + location)\n msg_crc = sbep.READ_DATA_REQ + b'\\x20' + location + crc_code\n\n self.device.write(msg_crc)\n b = self.device.read(size=7)\n if b != msg_crc:\n print(\"Error 4: The device failed to return the same bits back\")\n sys.exit()\n\n b = self.device.read(size=1)\n if b != sbep.ACK:\n print(\"Error 5a: ACK not received\")\n sys.exit()\n\n b = self.device.read(size=2)\n if b != b'\\xFF\\x80':\n print(\"Error 6: READ_DATA_REPLY not received\")\n sys.exit()\n b = self.device.read(size=2)\n readsize = b[1]\n radioinfo = self.device.read(size=readsize)\n\n self.memmap[location] = radioinfo[3:]\n\n return radioinfo\n\n def getvar(self, varname):\n offset = self.radiovalues[varname]['offset']\n start = self.radiovalues[varname]['start']\n end = self.radiovalues[varname]['end']\n\n memory = self.getmemory(bytes.fromhex(offset))\n\n if self.radiovalues[varname]['type'] == 'string':\n return memory[start:end].decode()\n elif self.radiovalues[varname]['type'] == 'bit':\n if ord(memory[start:end]) & ord(bytes.fromhex(self.radiovalues[varname]['bitand'])) == 0:\n return False\n else:\n return True\n else:\n print(\"Unset type, exiting.\")\n print(self.radiovalues[varname]['type'])\n sys.exit()\n\n def get_all_settings(self):\n for v in self.radiovalues:\n self.radiovalues[v] = self.getvar(v)\n\n def loadmap(self):\n ''' Load the appropriate memory map file located in $PWD/maps '''\n\n _start = 0\n\n try:\n fp = open('maps/%s.json' % self.radiovalues['model'])\n self.radiovalues = json.load(fp)['map']\n fp.close()\n except IOError:\n print(\"Unable to open maps/%s.json!\", file=sys.stderr)\n print(\"Your XTS3000 model might not be available yet.\", file=sys.stderr)\n print(\"Contact Farhan Khan (KM4WRZ) at khanzf@gmail.com for support.\", file=sys.stderr)\n sys.exit(0)\n","repo_name":"khanzf/xts3000","sub_path":"xtscontroller.py","file_name":"xtscontroller.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"20568225574","text":"from marshmallow import fields, Schema, validate, ValidationError\nfrom models import StoreModel\n\nmessages = {\n 'name': {\n 'invalid': 'O nome da loja não foi enviado corretamente',\n 'required': 'Necessário enviar o nome da loja',\n },\n 'store': {\n 'invalid': 'O id da loja informada não existe',\n 'required': 'Necessário enviar o id da loja',\n }\n}\n\ndef validate_store_exists(id_store: int):\n ''' Verifica se a loja existe no sistema '''\n store = StoreModel.query.filter(StoreModel.id == id_store).first()\n if not store:\n raise ValidationError('O id da loja enviada não existe no sistema.')\n\nclass StoreSchema(Schema):\n id = fields.Int(validate=validate_store_exists, required=True, error_messages=messages['store'])\n nome = fields.Str(required=True)\n\nclass StorePostSchema(Schema):\n nome = fields.Str(validate=validate.Length(min=2) ,required=True, error_messages=messages['name'])\n\nclass StoreDelSchema(Schema):\n id = fields.Int(validate=validate_store_exists, required=True, error_messages=messages['store'])","repo_name":"plimo263/restapi_supermercado","sub_path":"schemas/store_schema.py","file_name":"store_schema.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"5888392373","text":"from bson.json_util import dumps\nfrom flask import Flask, request\nfrom pymongo import MongoClient\n\napp = Flask(__name__)\n\nclient = MongoClient('mongodb://localhost:27017/')\ndb = client['to-do-list']\ncollection = db['to-do-list']\n\n\n@app.route('/', methods=['GET'])\ndef hello_world():\n return 'Welcome, this is my todo list!'\n\n\n@app.route('/todo', methods=['POST'])\ndef create():\n req_data = request.get_json()\n req_data['seq'] = collection.count()\n collection.insert_one(req_data)\n return \"inserted\"\n\n\n@app.route('/todo', methods=['GET'])\ndef getall():\n results = []\n for x in collection.find({}, {'_id': 0}):\n results.append(x)\n return dumps(results)\n\n\n@app.route('/todo/', methods=['GET'])\ndef get(index):\n coll = collection.find({\"seq\": index}, {'_id': 0})\n if coll.count() > 0:\n return dumps(coll)\n else:\n return '404'\n\n\n@app.route('/todo/', methods=['PUT'])\ndef update(index):\n word = request.get_json()\n coll = collection.find({\"seq\": index})\n if coll.count() > 0:\n collection.find_one_and_update({\"seq\": index}, {\"$set\": {\"data\": word}})\n return dumps(collection.find_one({\"seq\": index}))\n else:\n return '404'\n\n\n@app.route('/todo/', methods=['DELETE'])\ndef delete(index):\n coll = collection.find({\"seq\": index})\n if coll.count() > 0:\n collection.delete_one({\"seq\": index})\n return \"deleted\"\n else:\n return '404'\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"little-lily-17/todolist","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"28885498451","text":"import csv\n\nfrom dagster import (\n EventMetadataEntry,\n ExpectationResult,\n Field,\n Output,\n Selector,\n String,\n TypeCheck,\n dagster_type,\n execute_pipeline,\n input_hydration_config,\n pipeline,\n solid,\n)\n\n\ndef less_simple_data_frame_type_check(value):\n if not isinstance(value, list):\n return TypeCheck(\n success=False,\n description=(\n 'LessSimpleDataFrame should be a list of dicts, got '\n '{type_}'\n ).format(type_=type(value)),\n )\n\n fields = [field for field in value[0].keys()]\n\n for i in range(len(value)):\n row = value[i]\n if not isinstance(row, dict):\n return TypeCheck(\n success=False,\n description=(\n 'LessSimpleDataFrame should be a list of dicts, '\n 'got {type_} for row {idx}'\n ).format(type_=type(row), idx=(i + 1)),\n )\n row_fields = [field for field in row.keys()]\n if fields != row_fields:\n return TypeCheck(\n success=False,\n description=(\n 'Rows in LessSimpleDataFrame should have the same fields, '\n 'got {actual} for row {idx}, expected {expected}'\n ).format(actual=row_fields, idx=(i + 1), expected=fields),\n )\n\n return TypeCheck(\n success=True,\n description='LessSimpleDataFrame summary statistics',\n metadata_entries=[\n EventMetadataEntry.text(\n str(len(value)),\n 'n_rows',\n 'Number of rows seen in the data frame',\n ),\n EventMetadataEntry.text(\n str(len(value[0].keys()) if len(value) > 0 else 0),\n 'n_cols',\n 'Number of columns seen in the data frame',\n ),\n EventMetadataEntry.text(\n str(list(value[0].keys()) if len(value) > 0 else []),\n 'column_names',\n 'Keys of columns seen in the data frame',\n ),\n ],\n )\n\n\n@input_hydration_config(Selector({'csv': Field(String)}))\ndef less_simple_data_frame_input_hydration_config(context, selector):\n with open(selector['csv'], 'r') as fd:\n lines = [row for row in csv.DictReader(fd)]\n\n context.log.info('Read {n_lines} lines'.format(n_lines=len(lines)))\n return LessSimpleDataFrame(lines)\n\n\n@dagster_type(\n name='LessSimpleDataFrame',\n description='A more sophisticated data frame that type checks its structure.',\n type_check=less_simple_data_frame_type_check,\n input_hydration_config=less_simple_data_frame_input_hydration_config,\n)\nclass LessSimpleDataFrame(list):\n pass\n\n\ndef expect_column_to_be_integers(\n data_frame: LessSimpleDataFrame, column_name: str\n) -> ExpectationResult:\n bad_values = []\n for idx in range(len(data_frame)):\n line = data_frame[idx]\n if not isinstance(line[column_name], int):\n bad_values.append((idx, str(line[column_name])))\n return ExpectationResult(\n success=(not bad_values),\n label='col_{column_name}_is_int'.format(column_name=column_name),\n description=(\n 'Check whether type of column {column_name} in '\n 'LessSimpleDataFrame is int'\n ).format(column_name=column_name),\n metadata_entries=[\n EventMetadataEntry.json(\n {'index': idx, 'bad_value': value},\n 'bad_value',\n 'Bad value in column {column_name}'.format(\n column_name=column_name\n ),\n )\n for (idx, value) in bad_values\n ],\n )\n\n\n@solid\ndef sort_by_calories(context, cereals: LessSimpleDataFrame):\n yield expect_column_to_be_integers(cereals, 'calories')\n sorted_cereals = sorted(cereals, key=lambda cereal: cereal['calories'])\n context.log.info(\n 'Least caloric cereal: {least_caloric}'.format(\n least_caloric=sorted_cereals[0]['name']\n )\n )\n context.log.info(\n 'Most caloric cereal: {most_caloric}'.format(\n most_caloric=sorted_cereals[-1]['name']\n )\n )\n yield Output(sorted_cereals)\n\n\n@pipeline\ndef custom_type_pipeline():\n sort_by_calories()\n\n\nif __name__ == '__main__':\n execute_pipeline(\n custom_type_pipeline,\n {\n 'solids': {\n 'sort_by_calories': {\n 'inputs': {'cereals': {'csv': 'cereal.csv'}}\n }\n }\n },\n )\n","repo_name":"konradmalik/tech-sandbox","sub_path":"Dagster/data/airline-demo/dagster_examples/intro_tutorial/custom_types_5.py","file_name":"custom_types_5.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"42589918561","text":"# https://www.acmicpc.net/problem/29792\n\nimport sys\n\n\nreadline = lambda: sys.stdin.readline().rstrip()\n\nN, M, K = map(int, readline().split())\nD = [int(readline()) for _ in range(N)]\n\ntimes = []\nmesos = []\nfor k in range(K):\n P, meso = map(int, readline().split())\n\n times.append([])\n mesos.append(meso)\n\n for i in range(N):\n times[k].append(P//D[i] + int(P%D[i] != 0))\n\nprofits = []\nfor i in range(N):\n dp = [float('-inf')] * (60 * 15 + 1)\n dp[0] = 0\n\n for k in range(K):\n for t in reversed(range(len(dp))):\n if t + times[k][i] < len(dp):\n dp[t + times[k][i]] = max(dp[t + times[k][i]], dp[t] + mesos[k])\n\n profits.append(max(dp))\n\nprint(sum(sorted(profits, reverse=True)[:M]))\n","repo_name":"meo-s/coding-test","sub_path":"29000/700/29792_규칙적인_보스돌이/BJ_29792_규칙적인_보스돌이.py","file_name":"BJ_29792_규칙적인_보스돌이.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"20540623311","text":"from discord.ext import commands\nfrom discord import Embed\nfrom datetime import datetime\nimport os\nimport pytz\nimport json\n\n\nDATEFORMAT = \"%Y-%m-%d / %H:%M UTC +9\"\n\ndef to_korean_time(ts):\n dt = datetime.strptime(ts, \"%Y-%m-%dT%H:%M:%S.%fZ\")\n tz = pytz.timezone('Asia/Seoul')\n return dt.astimezone(tz)\n\ndef rank_to_emoji(rank):\n ranks = {\n \"x\": \"<:rankX:845092185052413952>\",\n \"u\": \"<:rankU:845092171438882866>\",\n \"ss\": \"<:rankSS:845092157139976192>\",\n \"s+\": \"<:rankSplus:845092140471418900>\",\n \"s\": \"<:rankS:845092120662376478>\",\n \"s-\": \"<:rankSminus:845092009101230080>\",\n \"a+\": \"<:rankAplus:845091973248581672>\",\n \"a\": \"<:rankA:845091931994587166>\",\n \"a-\": \"<:rankAminus:845091885286424596>\",\n \"b+\": \"<:rankBplus:845091818911301634>\",\n \"b\": \"<:rankB:845089923089825812>\",\n \"b-\": \"<:rankBminus:845089882698154044>\",\n \"c+\": \"<:rankCplus:845088318509285416>\",\n \"c\": \"<:rankC:845088262611533844>\",\n \"c-\": \"<:rankCminus:845088252322775041>\",\n \"d+\": \"<:rankDplus:845088230588284959>\",\n \"d\": \"<:rankD:845088198966640640>\",\n \"d-\": \"<:rankDminus:845105375015600138>\",\n \"z\": \"<:unranked:845092197346443284>\",\n }\n return ranks[rank]\n\n\ndef kr_rank_to_rank(rank):\n ranks = {\n \"엑스\": \"x\",\n \"유\": \"u\",\n \"에스에스\": \"ss\",\n \"에스플러스\": \"s+\",\n \"에스\": \"s\",\n \"에스마이너스\": \"s-\",\n \"에이플러스\": \"a+\",\n \"에이\": \"a\",\n \"에이마이너스\": \"a-\",\n \"비플러스\": \"b+\",\n \"비\": \"b\",\n \"비마이너스\": \"b-\",\n \"씨플러스\": \"c+\",\n \"씨\": \"c\",\n \"씨마이너스\": \"c-\",\n \"디플러스\": \"d+\",\n \"디\": \"d\",\n \"디마이너스\": \"d-\"\n }\n try:\n return ranks[rank]\n except:\n return rank\n\ndef ranks_to_embed(ranks):\n updated = datetime.strptime(ranks[\"date\"], \"%Y-%m-%d %H:%M:%S UTC\").astimezone(pytz.timezone('Asia/Seoul')).strftime(DATEFORMAT)\n e = Embed(title=f\"랭크 등급컷\")\n e.set_footer(text=f\"마지막 업데이트 {updated}\")\n description = []\n for rank in ranks[\"thresholds\"]:\n emoji = rank_to_emoji(rank[\"rank\"])\n description.append(f\"{emoji} **{rank['threshold']:.2f}TR** ({rank['percentage']}% / {rank['playerCount']} 유저)\")\n e.description = \"\\n\".join(description)\n return e\n\nclass Ranks(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.delimiters = [\" 와 \", \" 과 \", \" 또 \", \" 그리고 \", \" 랑 \", \" and \", \" | \", \"; \", \", \", \",\", \";\", \"와\", \"과\", \"또\", \"그리고\", \"랑\", \"|\"]\n\n def split_choices(self, msg):\n for delimiter in self.delimiters:\n msg = \"|\".join(msg.split(delimiter))\n return msg.split(\"|\")\n\n @commands.command(name=\"ranks\", aliases=[\"rank\", \"랭크컷\", \"랭크\"])\n async def ranks(self, ctx, * rank):\n \"\"\"Shows info of TR requirements for each rank. Specify a rank to only show that.\n Example: ?랭크 x 와 u\"\"\"\n if os.path.exists(\"badbot/scripts/thresholds.json\"):\n with open(\"badbot/scripts/thresholds.json\", 'r') as f:\n data = json.load(f)\n if len(rank) > 0:\n targets = []\n target_ranks = [kr_rank_to_rank(x) for x in self.split_choices(\"|\".join(rank).lower())]\n for rank in data['thresholds']:\n if rank['rank'] in target_ranks:\n targets.append(rank)\n data[\"thresholds\"] = targets\n await ctx.send(embed=ranks_to_embed(data))\n else:\n await ctx.send(\"Rank data hasn't been received yet :(\")\n\n\ndef setup(bot):\n bot.add_cog(Ranks(bot))\n","repo_name":"chinatsu/badtetriobot","sub_path":"badbot/cogs/ranks.py","file_name":"ranks.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27929717061","text":"__all__ = [\"SparqlClient\", \"SPARQL_RESULTS_XML\", \"SPARQL_RESULTS_JSON\"]\n\nimport httplib2\nimport urllib\n\nSPARQL_RESULTS_XML = \"application/sparql-results+xml\"\nSPARQL_RESULTS_JSON = \"application/sparql-results+json\"\n\nSYMMETRIC_BOUNDED_DESCRIPTION = \"\"\"CONSTRUCT {?uri ?p ?o . ?s ?p2 ?uri .} WHERE { {?uri ?p ?o .} UNION {?s ?p2 ?uri .} }\"\"\"\n\nLABELLED_BOUNDED_DESCRIPTION = \"\"\"PREFIX rdfs: \nCONSTRUCT {\n ?uri ?p ?o . \n ?o rdfs:label ?label . \n ?o rdfs:comment ?comment . \n ?o ?plabel . \n ?o rdfs:seeAlso ?seealso.\n} WHERE {\n ?uri ?p ?o . \n OPTIONAL { \n ?o rdfs:label ?label .\n } \n OPTIONAL {\n ?o ?plabel . \n } \n OPTIONAL {\n ?o rdfs:comment ?comment . \n } \n OPTIONAL { \n ?o rdfs:seeAlso ?seealso.\n }\n}\"\"\"\n\nSYMMETRIC_LABELLED_BOUNDED_DESCRIPTION = \"\"\"PREFIX rdfs: \nCONSTRUCT {\n ?uri ?p ?o . \n ?o rdfs:label ?label . \n ?o rdfs:comment ?comment . \n ?o rdfs:seeAlso ?seealso. \n ?s ?p2 ?uri . \n ?s rdfs:label ?label . \n ?s rdfs:comment ?comment . \n ?s rdfs:seeAlso ?seealso.\n} WHERE { \n { ?uri ?p ?o . \n OPTIONAL { \n ?o rdfs:label ?label .\n } \n OPTIONAL {\n ?o rdfs:comment ?comment .\n } \n OPTIONAL {\n ?o rdfs:seeAlso ?seealso.\n } \n } \n UNION {\n ?s ?p2 ?uri . \n OPTIONAL {\n ?s rdfs:label ?label .\n }\n OPTIONAL {\n ?s rdfs:comment ?comment .\n }\n OPTIONAL {\n ?s rdfs:seeAlso ?seealso.\n }\n }\n}\"\"\"\n\nDESCRIPTIONS = {\n \"cbd\" : \"DESCRIBE ?uri\",\n \"scbd\" : SYMMETRIC_BOUNDED_DESCRIPTION,\n \"lcbd\" : LABELLED_BOUNDED_DESCRIPTION,\n \"slcbd\" : SYMMETRIC_LABELLED_BOUNDED_DESCRIPTION,\n}\n\nclass SparqlClient:\n endpoint = None\n client = None\n output_parameter_name = None\n graphs = None\n named_graphs = None\n supports_rdf_json = False\n supports_sparql_json = True\n \n def __init__(self, endpoint, client=httplib2.Http()):\n self.endpoint = endpoint\n self.client = client\n \n def add_default_graph(self, graph_uri):\n if self.graphs is None:\n self.graphs = []\n self.graphs.append(graph_uri)\n \n def add_named_graph(self, graph_uri):\n if self.named_graphs is None:\n self.named_graphs = []\n self.named_graphs.append(graph_uri)\n \n def query(self, sparql, format=None, graphs=None, named_graphs=None):\n params = []\n params.append((\"query\", sparql))\n if graphs != None:\n for graph in graphs:\n params.append((\"default-graph-uri\", graph))\n elif self.graphs != None:\n for graph in self.graphs:\n params.append((\"default-graph-uri\", graph))\n if named_graphs != None:\n for named_graph in named_graphs:\n params.append((\"named-graph-uri\", named_graph))\n elif self.named_graphs != None:\n for named_graph in self.named_graphs:\n params.append((\"named-graph-uri\", named_graph))\n headers = {}\n if format != None:\n if self.output_parameter_name != None:\n params[self.output_parameter_name] = format\n else:\n headers[\"Accept\"] = format\n return self.client.request(self.endpoint, \"GET\", urllib.urlencode(params), headers)\n \n def describe_uri(self, uri, format=\"application/rdf+xml\", type=\"cbd\"):\n try:\n template = DESCRIPTIONS[type]\n except KeyError:\n raise \"Unknown description type\"\n query = template.replace(\"?uri\", \"<%s>\" % uri)\n return self.describe(query, format)\n \n def describe(self, query, format=\"application/rdf+xml\"):\n return self.query(query, format)\n\n def multi_describe(self, uris, format=\"application/rdf+xml\"):\n query = \"DESCRIBE\" + \" \".join([\"<%s>\" % u for u in uris])\n return self.query(query, format)\n \n def construct(self, query, format=\"application/rdf+xml\"):\n return self.query(query, format)\n \n def ask(self, query, format=SPARQL_RESULTS_XML):\n return self.query(query, format)\n \n def select(self, query, format=SPARQL_RESULTS_XML):\n return self.query(query, format)\n\ndef merge(sparql_client, store, query):\n headers, data = sparql_client.query(query, \"application/rdf+xml\")\n if headers[\"status\"] != \"200\":\n raise \"Unable to execute query. Response: %s\" % headers[\"status\"]\n resp = store.store_data(data)\n return resp\n","repo_name":"iand/pynappl","sub_path":"src/pynappl/sparql_client.py","file_name":"sparql_client.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30270291615","text":"import sys\nfrom utils import *\n\nfrom rank_svm_model import run_bash_command, prepare_svmr_model_data, turn_df_to_feature_str_for_model, split_to_train_test, get_trec_prepared_df_form_res_df, create_sinificance_df, create_fold_list_for_cv\n\n\ndef run_lambdamart_model(test_file, model_file, predictions_folder):\n predictions_file = os.path.join(predictions_folder, 'Prdictions.txt' )\n command = \"java -jar /mnt/bi-strg3/v/zivvasilisky/ziv/env/ranklib/RankLib-2.14.jar -load \" + model_file + \" -rank \" + test_file + \" -score \" + predictions_file\n print(\"##Running command: \"+command+\"##\")\n out = run_bash_command(command)\n print(\"Output of ranking command: \"+str(out))\n sys.stdout.flush()\n return predictions_file\n\n\ndef learn_lambdamart_model(train_file, models_folder, tree_num, leaf_num):\n model_file = os.path.join(models_folder , \"model.txt\")\n command = \"java -jar /mnt/bi-strg3/v/zivvasilisky/ziv/env/ranklib/RankLib-2.14.jar -train \" + train_file + \" -ranker 6 -metric2t NDCG@5 -save \" + model_file\n command += \" -tree \" + str(tree_num) + \" -leaf \" +str(leaf_num)\n out = run_bash_command(command)\n print(out)\n sys.stdout.flush()\n return model_file\n\n\ndef get_predictions_list(\n predictions_filename):\n\n with open(predictions_filename, 'r') as f:\n predications = f.read()\n\n predications_list = []\n for row in predications.split('\\n'):\n if row != \"\":\n predications_list.append(row.split('\\t')[2])\n\n return predications_list\n\ndef run_backward_elimination(\n base_res_folder,\n train_df,\n valid_df,\n feature_list,\n tree_num,\n leaf_num,\n qrel_filepath,\n curr_map_score):\n\n new_feat_list = feature_list[:]\n for i in range(len(feature_list)):\n rmv_feature = None\n for feature in new_feat_list:\n curr_feat_list = new_feat_list[:]\n curr_feat_list.remove(feature)\n res_dict = get_result_for_feature_set(\n base_res_folder=base_res_folder,\n train_df=train_df,\n valid_df=valid_df,\n curr_feature_list=curr_feat_list,\n tree_num=tree_num,\n leaf_num=leaf_num,\n qrel_filepath=qrel_filepath)\n\n if float(res_dict['NDCG@X']) > curr_map_score:\n curr_map_score = float(res_dict['NDCG@X'])\n rmv_feature = feature\n if rmv_feature is not None:\n new_feat_list.remove(rmv_feature)\n else:\n break\n print('Removed these features: ' + str(set(feature_list) - set(new_feat_list)))\n sys.stdout.flush()\n return new_feat_list\n\n\ndef get_result_for_feature_set(\n base_res_folder,\n train_df,\n valid_df,\n curr_feature_list,\n tree_num,\n leaf_num,\n qrel_filepath):\n\n with open(os.path.join(base_res_folder, 'train.dat'), 'w') as f:\n f.write(turn_df_to_feature_str_for_model(train_df, feature_list=curr_feature_list))\n\n with open(os.path.join(base_res_folder, 'valid.dat'), 'w') as f:\n f.write(turn_df_to_feature_str_for_model(valid_df, feature_list=curr_feature_list))\n\n model_filename = learn_lambdamart_model(\n train_file=os.path.join(base_res_folder, 'train.dat'),\n models_folder=base_res_folder,\n tree_num=tree_num,\n leaf_num=leaf_num)\n\n predictions_filename = run_lambdamart_model(\n test_file=os.path.join(base_res_folder, 'valid.dat'),\n model_file=model_filename,\n predictions_folder=base_res_folder)\n\n predications = get_predictions_list(predictions_filename)\n\n valid_df['ModelScore'] = predications\n valid_df['ModelScore'] = valid_df['ModelScore'].apply(lambda x: float(x))\n curr_res_df = get_trec_prepared_df_form_res_df(\n scored_docs_df=valid_df,\n score_colname='ModelScore')\n curr_file_name = 'Curr_valid_res.txt'\n with open(os.path.join(base_res_folder, curr_file_name), 'w') as f:\n f.write(convert_df_to_trec(curr_res_df))\n\n res_dict = calc_ndcg_at_x_for_file(\n file_path=base_res_folder,\n filename=curr_file_name,\n qrel_filepath=qrel_filepath)\n\n return res_dict\n\n\ndef train_and_test_model_on_config(\n base_feature_filename,\n snapshot_limit,\n feature_list,\n start_test_q,\n end_test_q,\n feature_groupname,\n normalize_method,\n qrel_filepath,\n snap_chosing_method=None,\n snap_calc_limit=None,\n backward_elimination=False,\n snap_num_as_hyper_param=False,\n is_new_server=False,\n trial_num=0):\n\n base_res_folder = '/mnt/bi-strg3/v/zivvasilisky/ziv/results/lambdamart_res/'\n if is_new_server == True:\n base_res_folder = '/lv_local/home/zivvasilisky/ziv/results/lambdamart_res/'\n\n model_inner_folder = base_feature_filename.replace('All_features_', '').replace('with_meta.tsv', '')+ 'SNL' + str(snapshot_limit)\n feature_folder = feature_groupname.replace('XXSnap','XS')\n # if normalize_relevance == True:\n feature_folder += '_' + normalize_method\n fold_folder = str(start_test_q) + '_' + str(end_test_q) #+ \"_\" + str(snap_chosing_method)\n\n for hirarcy_folder in [model_inner_folder, feature_folder, fold_folder]:\n base_res_folder = os.path.join(base_res_folder, hirarcy_folder)\n if not os.path.exists(base_res_folder):\n os.mkdir(base_res_folder)\n\n\n best_snap_num = snap_calc_limit\n\n feat_df = prepare_svmr_model_data(\n base_feature_filename=base_feature_filename,\n snapshot_limit=int(snapshot_limit),\n feature_list=feature_list,\n normalize_method=normalize_method,\n limited_snaps_num=best_snap_num,\n lambdamart=True)\n\n print(\"Model Data Prepared...\")\n sys.stdout.flush()\n train_df, test_df, valid_df, seed = split_to_train_test(\n start_test_q=start_test_q,\n end_test_q=end_test_q,\n feat_df=feat_df,\n base_feature_filename=base_feature_filename,\n trial_num=trial_num)\n\n\n valid_df_cp = valid_df.copy()\n with open(os.path.join(base_res_folder, 'train.dat'), 'w') as f:\n f.write(turn_df_to_feature_str_for_model(train_df, feature_list=feature_list))\n\n with open(os.path.join(base_res_folder, 'valid.dat'), 'w') as f:\n f.write(turn_df_to_feature_str_for_model(valid_df, feature_list=feature_list))\n\n num_tree_optional_list = [250, 500]\n num_leaf_optional_list = [3, 2, 5]\n best_map = 0.0\n\n for tree_num in num_tree_optional_list:\n for leaf_num in num_leaf_optional_list:\n print(\"Running validation tree num: \" + str(tree_num)) + \" leaf num: \" + str(leaf_num)\n model_filename = learn_lambdamart_model(\n train_file=os.path.join(base_res_folder, 'train.dat'),\n models_folder=base_res_folder,\n tree_num=tree_num,\n leaf_num=leaf_num)\n\n predictions_filename = run_lambdamart_model(\n test_file=os.path.join(base_res_folder, 'valid.dat'),\n model_file=model_filename,\n predictions_folder=base_res_folder)\n\n predications = get_predictions_list(predictions_filename)\n\n valid_df['ModelScore'] = predications\n valid_df['ModelScore'] = valid_df['ModelScore'].apply(lambda x: float(x))\n curr_res_df = get_trec_prepared_df_form_res_df(\n scored_docs_df=valid_df,\n score_colname='ModelScore')\n curr_file_name = 'Curr_valid_res.txt'\n with open(os.path.join(base_res_folder, curr_file_name), 'w') as f:\n f.write(convert_df_to_trec(curr_res_df))\n\n res_dict = calc_ndcg_at_x_for_file(\n file_path=base_res_folder,\n filename=curr_file_name,\n qrel_filepath=qrel_filepath)\n\n if float(res_dict['NDCG@X']) > best_map:\n best_map = float(res_dict['NDCG@X'])\n best_tree_num = tree_num\n beat_leaf_num = leaf_num\n\n if backward_elimination == True:\n new_feature_list = run_backward_elimination(\n base_res_folder=base_res_folder,\n train_df=train_df,\n valid_df=valid_df,\n feature_list=feature_list,\n tree_num=best_tree_num,\n leaf_num=beat_leaf_num,\n qrel_filepath=qrel_filepath,\n curr_map_score=best_map)\n else:\n new_feature_list = feature_list[:]\n\n if (snap_num_as_hyper_param == True) and ('XXSnap' in feature_groupname):\n round_num = int(base_feature_filename.split('Round')[1].split('_')[0])\n optional_snap_limit = list(range(2, round_num))\n if len(optional_snap_limit) <= 1:\n best_snap_num = snap_calc_limit\n else:\n optional_snap_limit[-1] = 'All'\n optional_snap_limit = list(reversed(optional_snap_limit))\n curr_map_score = best_map\n tree_num = best_tree_num\n leaf_num = beat_leaf_num\n for snap_lim in optional_snap_limit:\n print(\"Optimizing snap limit: \" + str(snap_lim))\n sys.stdout.flush()\n feat_df = prepare_svmr_model_data(\n base_feature_filename=base_feature_filename,\n snapshot_limit=int(snapshot_limit),\n feature_list=new_feature_list,\n normalize_method=normalize_method,\n limited_snaps_num=snap_lim,\n lambdamart=True)\n\n train_df, test_df, valid_df, seed = split_to_train_test(\n start_test_q=start_test_q,\n end_test_q=end_test_q,\n feat_df=feat_df,\n base_feature_filename=base_feature_filename,\n seed=seed)\n\n res_dict = get_result_for_feature_set(\n base_res_folder=base_res_folder,\n train_df=train_df,\n valid_df=valid_df,\n curr_feature_list=new_feature_list,\n tree_num=tree_num,\n leaf_num=leaf_num,\n qrel_filepath=qrel_filepath)\n\n if float(res_dict['NDCG@X']) > curr_map_score:\n curr_map_score = float(res_dict['NDCG@X'])\n best_snap_num = snap_lim\n\n train_df = train_df.append(valid_df_cp, ignore_index=True)\n train_df.sort_values('QueryNum', inplace=True)\n\n with open(os.path.join(base_res_folder, 'train.dat'), 'w') as f:\n f.write(turn_df_to_feature_str_for_model(train_df, feature_list=new_feature_list))\n\n best_params_str = 'SnapLim: ' + str(best_snap_num) + '\\n' + \"TreeNum: \" +str(best_tree_num) +'\\n' +\"LeafNum: \" +str(beat_leaf_num)\n with open(os.path.join(base_res_folder, 'hyper_params.txt'), 'w') as f:\n f.write(best_params_str)\n\n with open(os.path.join(base_res_folder, 'test.dat'), 'w') as f:\n f.write(turn_df_to_feature_str_for_model(test_df, feature_list=new_feature_list))\n\n print(\"Strating Train : \" + model_inner_folder + ' ' + feature_folder + ' ' + fold_folder)\n sys.stdout.flush()\n model_filename = learn_lambdamart_model(\n train_file=os.path.join(base_res_folder, 'train.dat'),\n models_folder=base_res_folder,\n tree_num=best_tree_num,\n leaf_num=beat_leaf_num)\n\n print(\"Strating Test : \" + model_inner_folder + ' ' + feature_folder + ' ' + fold_folder)\n sys.stdout.flush()\n\n predictions_filename = run_lambdamart_model(\n test_file=os.path.join(base_res_folder, 'test.dat'),\n model_file=model_filename,\n predictions_folder=base_res_folder)\n\n predications = get_predictions_list(predictions_filename)\n\n test_df['ModelScore'] = predications\n test_df['ModelScore'] = test_df['ModelScore'].apply(lambda x: float(x))\n\n params_list = [best_tree_num, beat_leaf_num]\n hyper_params = ['Tree', 'Leaf']\n if best_snap_num is not None:\n hyper_params.append('SnapLimit')\n params_list.append(best_snap_num)\n params_df = pd.DataFrame(columns=['Fold'] + hyper_params)\n params_df.loc[0] = [str(start_test_q) + '_' + str(end_test_q)] + params_list\n\n return test_df, params_df\n\ndef run_cv_for_config(\n base_feature_filename,\n snapshot_limit,\n feature_groupname,\n retrieval_model,\n normalize_method,\n qrel_filepath,\n snap_chosing_method,\n train_leave_one_out,\n snap_calc_limit,\n backward_elimination,\n snap_num_as_hyper_param,\n is_new_server,\n with_bert_as_feature,\n feature_for_ablation,\n limited_features_list,\n trial_num):\n\n k_fold, fold_list = create_fold_list_for_cv(\n base_feature_filename=base_feature_filename,\n train_leave_one_out=train_leave_one_out)\n\n feature_list = []\n broken_feature_groupname = feature_groupname.split('_')\n len_handled = 0\n # base_feature_list = ['Boolean.AND', 'Boolean.OR', 'CoverQueryNum', 'CoverQueryRatio', 'Ent', 'FracStops',\n # 'IDF', 'Len', 'LMIR.ABS', 'LMIR.DIR', 'LMIR.JM', 'StopCover', 'TFSum', 'TFMin', 'TFMax',\n # 'TFMean', 'TFStd',\n # 'TFIDFSum', 'TFIDFMin', 'TFIDFMax', 'TFIDFMean', 'TFIDFStd', 'TFNormSum', 'TFNormMin',\n # 'TFNormMax',\n # 'TFNormMean', 'TFNormStd', 'VSM', 'SimClueWeb', 'BM25Score']\n\n base_feature_list = ['CoverQueryNum', 'CoverQueryRatio', 'Ent', 'FracStops',\n 'IDF', 'Len', 'LMIR.DIR', 'LMIR.JM', 'StopCover', 'TFSum', 'TFMin', 'TFMax',\n 'TFMean', 'TFStd','TFIDFSum', 'TFIDFMin', 'TFIDFMax', 'TFIDFMean', 'TFIDFStd', 'TFNormSum', 'TFNormMin',\n 'TFNormMax','TFNormMean', 'TFNormStd', 'SimClueWeb', 'BM25Score']\n\n if with_bert_as_feature == True:\n base_feature_list.append('BERTScore')\n\n mm_feature_list = [\n 'JMPrevWinner', 'JMPrev2Winners', 'JMPrev3Winners',\n 'JMPrevBestImprove','JMPrev2BestImprove','JMPrev3BestImprove',\n 'DIRPrevWinner', 'DIRPrev2Winners', 'DIRPrev3Winners',\n 'DIRPrevBestImprove','DIRPrev2BestImprove','DIRPrev3BestImprove',\n 'JMPrevWinnerK1', 'JMPrevBestImproveK1',\n 'DIRPrevWinnerK1', 'DIRPrevBestImproveK1',\n 'JMPrevWinnerK3', 'JMPrevBestImproveK3',\n 'DIRPrevWinnerK3', 'DIRPrevBestImproveK3',\n 'JMPrevWinnerRand', 'JMPrevBestImproveRand',\n 'DIRPrevWinnerRand', 'DIRPrevBestImproveRand',\n 'JMOnlyReservoir', 'DIROnlyReservoir',\n 'ED_KL', 'ED_LM', 'RHS_BM25', 'RHS_LM',\n 'LTS_MA', 'LTS_LR', 'LTS_ARMA',\n 'Fuse_LM', 'Fuse_BM25'\n ]\n mm_features = []\n if limited_features_list is not None:\n base_feature_list = limited_features_list\n for feature in limited_features_list[:]:\n if feature in mm_feature_list:\n base_feature_list.remove(feature)\n mm_features.append(feature)\n\n if 'Static' in broken_feature_groupname:\n feature_list.extend(base_feature_list + mm_features)\n len_handled += 1\n\n if 'M' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_M')\n len_handled += 1\n if 'STD' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_STD')\n len_handled += 1\n if 'RMG' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_RMG')\n len_handled += 1\n if 'MG' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_MG')\n len_handled += 1\n if 'LG' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_LG')\n len_handled += 1\n\n if 'RMGXXSnap' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_RMGXXSnaps')\n len_handled += 1\n if 'MGXXSnap' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_MGXXSnaps')\n len_handled += 1\n if 'MXXSnap' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_MXXSnaps')\n len_handled += 1\n if 'STDXXSnap' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_STDXXSnaps')\n len_handled += 1\n if 'MinXXSnap' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_MinXXSnaps')\n len_handled += 1\n if 'MaxXXSnap' in broken_feature_groupname:\n for base_feat in base_feature_list:\n feature_list.append(base_feat + '_MaxXXSnaps')\n len_handled += 1\n\n feature_groups_num = len(broken_feature_groupname)\n if snap_calc_limit is not None:\n feature_groups_num = feature_groups_num - 1\n if len_handled != feature_groups_num:\n raise Exception('Undefined feature group!')\n\n test_score_df = pd.DataFrame({})\n if 'XXSnap' in feature_groupname:\n feature_groupname += 'By' + snap_chosing_method\n\n if feature_for_ablation is not None:\n if feature_for_ablation in feature_list:\n feature_list.remove(feature_for_ablation)\n else:\n raise Exception(feature_for_ablation + \" for ablation NOT in feature list!\")\n\n for i in range(k_fold):\n init_q = fold_list[i][0]\n end_q = fold_list[i][1]\n fold_test_df, fold_params_df = train_and_test_model_on_config(\n base_feature_filename=base_feature_filename,\n snapshot_limit=snapshot_limit,\n feature_list=feature_list,\n start_test_q=init_q,\n end_test_q=end_q,\n feature_groupname=feature_groupname + '_' + retrieval_model,\n normalize_method=normalize_method,\n qrel_filepath=qrel_filepath,\n snap_chosing_method=snap_chosing_method,\n snap_calc_limit=snap_calc_limit,\n backward_elimination=backward_elimination,\n snap_num_as_hyper_param=snap_num_as_hyper_param,\n is_new_server=is_new_server,\n trial_num=trial_num)\n if i == 0:\n params_df = fold_params_df\n else:\n params_df = params_df.append(fold_params_df, ignore_index=True)\n test_score_df = test_score_df.append(fold_test_df, ignore_index=True)\n return test_score_df, params_df\n\n\ndef run_grid_search_over_params_for_config(\n base_feature_filename,\n snapshot_limit,\n retrieval_model,\n normalize_method,\n snap_chosing_method,\n tarin_leave_one_out,\n feat_group_list,\n calc_ndcg_mrr,\n backward_elimination,\n snap_num_as_hyper_param,\n snap_choosing_config,\n is_new_server,\n with_bert_as_feature,\n limited_features_list = None,\n feature_for_ablation = None):\n\n # optional_c_list = [0.2, 0.1, 0.01, 0.001]\n ## num 1\n # optional_feat_groups_list = ['All','Static','MG','LG','M','RMG','Static_LG','Static_MG'\n # ,'Static_M', 'Static_RMG']\n ## num 2\n # optional_feat_groups_list = ['Static','MGXXSnap', 'MXXSnap','RMGXXSnap','Static_MGXXSnap'\n # ,'Static_MXXSnap', 'Static_RMGXXSnap','MGXXSnap_MXXSnap_RMGXXSnap']\n ## num 3\n if feat_group_list is None:\n optional_feat_groups_list = ['Static',\n # 'Static_MXXSnap_STDXXSnap_MinXXSnap_MaxXXSnap_MGXXSnap_RMGXXSnap',\n\n\n # 'Static_MXXSnap_STDXXSnap_MinXXSnap_MaxXXSnap',\n # 'Static_MXXSnap_STDXXSnap_MinXXSnap_MaxXXSnap_MGXXSnap',\n # 'Static_MGXXSnap',\n\n\n # 'Static_RMGXXSnap'\n ]\n else:\n optional_feat_groups_list = feat_group_list\n save_folder = '/mnt/bi-strg3/v/zivvasilisky/ziv/results/lambdamart_res/ret_res/'\n save_summary_folder = '/mnt/bi-strg3/v/zivvasilisky/ziv/results/lambdamart_res/'\n if is_new_server == True:\n save_folder = '/lv_local/home/zivvasilisky/ziv/results/lambdamart_res/ret_res/'\n save_summary_folder = '/lv_local/home/zivvasilisky/ziv/results/lambdamart_res/'\n if '2008' in base_feature_filename:\n qrel_filepath = \"/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/qrels.adhoc\"\n elif 'ASRC' in base_feature_filename:\n qrel_filepath = \"/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/documents.rel\"\n elif 'BOT' in base_feature_filename:\n qrel_filepath = \"/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/documents_fixed.relevance\"\n elif 'HERD_CONTROL' in base_feature_filename:\n qrel_filepath = \"/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/control.rel\"\n elif 'UNITED' in base_feature_filename:\n qrel_filepath = '/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/united.rel'\n elif 'COMP2020' in base_feature_filename:\n qrel_filepath = '/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/curr_comp.rel'\n else:\n qrel_filepath = \"/mnt/bi-strg3/v/zivvasilisky/ziv/results/qrels/qrels_cw12.adhoc\"\n\n if snap_chosing_method == 'Months':\n snap_limit_options = [\n # '3M', '6M', '9M', '1Y', '1.5Y',\n snap_choosing_config]\n elif snap_chosing_method == 'SnapNum':\n snap_limit_options = [\n # 3, 5, 7, 10, 15,\n snap_choosing_config]\n else:\n raise Exception(\"Unknown snap_chosing_method!\")\n\n model_base_filename = base_feature_filename.replace('All_features_with_meta.tsv', '') + 'SNL' + str(\n snapshot_limit) + \"_\" + retrieval_model + \"_By\" + snap_chosing_method + '_' + str(snap_choosing_config)\n\n retrieval_model_addition = \"\"\n if tarin_leave_one_out == True:\n model_base_filename += '_LoO'\n retrieval_model_addition += '_LoO'\n if backward_elimination == True:\n model_base_filename += '_BElim'\n retrieval_model_addition += '_BElim'\n if snap_num_as_hyper_param == True:\n model_base_filename += '_SnapLim'\n retrieval_model_addition += '_SnapLim'\n if with_bert_as_feature == True:\n model_base_filename += '_Bert'\n retrieval_model_addition += '_Bert'\n if feature_for_ablation is not None:\n model_base_filename += '_Ablation'\n retrieval_model_addition += '_' + feature_for_ablation\n if limited_features_list is not None:\n model_base_filename += create_feature_list_shortcut_string(limited_features_list)\n retrieval_model_addition += create_feature_list_shortcut_string(limited_features_list)\n\n if not os.path.exists(os.path.join(save_folder, model_base_filename)):\n os.mkdir(os.path.join(save_folder, model_base_filename))\n save_folder = os.path.join(save_folder, model_base_filename)\n\n model_base_filename += '_' + normalize_method\n additional_measures = []\n if calc_ndcg_mrr == True:\n additional_measures = ['NDCG@1', 'NDCG@3', 'MRR', 'nMRR']\n model_summary_df = pd.DataFrame(columns=['FeatureGroup', 'Map', 'P@5', 'P@10'] +additional_measures)\n next_idx = 0\n per_q_res_dict = {}\n feat_group_list_str = \"\"\n params_df = pd.DataFrame({})\n # for optional_c in optional_c_list:\n for trial_num in range(1,6):\n for curr_feat_group in optional_feat_groups_list:\n feat_group_list_str += \"__\" + curr_feat_group.replace('XXSnap','')\n if 'XXSnap' in curr_feat_group:\n snap_limit_list = snap_limit_options\n else:\n snap_limit_list = [snap_choosing_config]\n for snap_limit in snap_limit_list:\n if snap_limit is None:\n feat_group = curr_feat_group\n else:\n feat_group = curr_feat_group + \"_\" + str(snap_limit)\n\n test_res_df, tmp_params_df = run_cv_for_config(\n base_feature_filename=base_feature_filename,\n snapshot_limit=snapshot_limit,\n feature_groupname=feat_group,\n retrieval_model=retrieval_model + retrieval_model_addition,\n normalize_method=normalize_method,\n qrel_filepath=qrel_filepath,\n snap_chosing_method=snap_chosing_method,\n train_leave_one_out=tarin_leave_one_out,\n snap_calc_limit=snap_limit,\n backward_elimination=backward_elimination,\n snap_num_as_hyper_param=snap_num_as_hyper_param,\n is_new_server=is_new_server,\n with_bert_as_feature=with_bert_as_feature,\n feature_for_ablation=feature_for_ablation,\n limited_features_list=limited_features_list,\n trial_num=trial_num)\n\n tmp_params_df['FeatGroup'] = feat_group\n if 'XXSnap' in feat_group:\n feat_group = feat_group.replace('XXSnap','') + 'By' + snap_chosing_method\n\n # if next_idx == 0 and feature_for_ablation is None:\n # curr_res_df = get_trec_prepared_df_form_res_df(\n # scored_docs_df=test_res_df,\n # score_colname=retrieval_model + 'Score')\n # insert_row = [retrieval_model]\n # curr_file_name = model_base_filename + '_' + retrieval_model + '_' + str(trial_num) + '.txt'\n # with open(os.path.join(save_folder, curr_file_name), 'w') as f:\n # f.write(convert_df_to_trec(curr_res_df))\n #\n # res_dict = get_ranking_effectiveness_for_res_file_per_query(\n # file_path=save_folder,\n # filename=curr_file_name,\n # qrel_filepath=qrel_filepath,\n # calc_ndcg_mrr=calc_ndcg_mrr)\n # for measure in ['Map', 'P_5', 'P_10']+additional_measures:\n # insert_row.append(res_dict['all'][measure])\n # per_q_res_dict[retrieval_model] = res_dict\n # model_summary_df.loc[next_idx] = insert_row\n # next_idx += 1\n # params_df = tmp_params_df\n # else:\n # params_df = params_df.append(tmp_params_df, ignore_index=True)\n\n curr_res_df = get_trec_prepared_df_form_res_df(\n scored_docs_df=test_res_df,\n score_colname='ModelScore')\n insert_row = [feat_group.replace('_', '+')]\n curr_file_name = model_base_filename + '_' + feat_group + '_' + str(trial_num) +'.txt'\n if feature_for_ablation is not None:\n curr_file_name = curr_file_name.replace('_Ablation', '_Abla_' + feature_for_ablation)\n with open(os.path.join(save_folder, curr_file_name), 'w') as f:\n f.write(convert_df_to_trec(curr_res_df))\n\n res_dict = get_ranking_effectiveness_for_res_file_per_query(\n file_path=save_folder,\n filename=curr_file_name,\n qrel_filepath=qrel_filepath,\n calc_ndcg_mrr=calc_ndcg_mrr)\n for measure in ['Map', 'P_5', 'P_10']+additional_measures:\n insert_row.append(res_dict['all'][measure])\n per_q_res_dict[feat_group.replace('_', '+')] = res_dict\n model_summary_df.loc[next_idx] = insert_row\n next_idx += 1\n\n # if feature_for_ablation is None:\n # significance_df = create_sinificance_df(per_q_res_dict, calc_ndcg_mrr)\n # model_summary_df = pd.merge(\n # model_summary_df,\n # significance_df,\n # on=['FeatureGroup'],\n # how='inner')\n #\n # model_summary_df.to_csv(os.path.join(save_summary_folder, model_base_filename + feat_group_list_str + '.tsv'), sep='\\t', index=False)\n # params_df.to_csv(os.path.join(save_summary_folder, model_base_filename + feat_group_list_str + '_Params.tsv'), sep='\\t', index=False)\n\n\nif __name__ == '__main__':\n operation = sys.argv[1]\n\n if operation == 'GridSearchParams':\n base_feature_filename = sys.argv[2]\n snapshot_limit = int(sys.argv[3])\n retrieval_model = sys.argv[4]\n normalize_method = sys.argv[5]\n snap_chosing_method = sys.argv[6]\n tarin_leave_one_out = ast.literal_eval(sys.argv[7])\n feat_group_list = ast.literal_eval(sys.argv[8])\n calc_ndcg_mrr = ast.literal_eval(sys.argv[9])\n backward_elimination = ast.literal_eval(sys.argv[10])\n snap_num_as_hyper_param = ast.literal_eval(sys.argv[11])\n snap_choosing_config = sys.argv[12]\n is_new_server = ast.literal_eval(sys.argv[13])\n with_bert_as_feature = ast.literal_eval(sys.argv[14])\n limited_features_list = ast.literal_eval(sys.argv[15])\n\n run_grid_search_over_params_for_config(\n base_feature_filename=base_feature_filename,\n snapshot_limit=snapshot_limit,\n retrieval_model=retrieval_model,\n normalize_method=normalize_method,\n snap_chosing_method=snap_chosing_method,\n tarin_leave_one_out=tarin_leave_one_out,\n feat_group_list=feat_group_list,\n calc_ndcg_mrr=calc_ndcg_mrr,\n backward_elimination=backward_elimination,\n snap_num_as_hyper_param=snap_num_as_hyper_param,\n snap_choosing_config=snap_choosing_config,\n is_new_server=is_new_server,\n with_bert_as_feature=with_bert_as_feature,\n limited_features_list=limited_features_list)\n\n if operation == 'AblationTest':\n base_feature_filename = sys.argv[2]\n snapshot_limit = 1\n retrieval_model = 'BM25'\n normalize_method = 'MinMax'\n snap_chosing_method = 'Months'\n tarin_leave_one_out = True\n feat_group_list = ast.literal_eval(sys.argv[3])#['Static_MXXSnap_STDXXSnap_MinXXSnap_MaxXXSnap']\n calc_ndcg_mrr = True\n backward_elimination = False\n snap_num_as_hyper_param = False\n snap_choosing_config = 'All'\n is_new_server = False\n with_bert_as_feature = False\n feature_for_ablation_list = ast.literal_eval(sys.argv[4])\n limited_features_list = ast.literal_eval(sys.argv[5])\n\n for feature_for_ablation in feature_for_ablation_list:\n run_grid_search_over_params_for_config(\n base_feature_filename=base_feature_filename,\n snapshot_limit=snapshot_limit,\n retrieval_model=retrieval_model,\n normalize_method=normalize_method,\n snap_chosing_method=snap_chosing_method,\n tarin_leave_one_out=tarin_leave_one_out,\n feat_group_list=feat_group_list,\n calc_ndcg_mrr=calc_ndcg_mrr,\n backward_elimination=backward_elimination,\n snap_num_as_hyper_param=snap_num_as_hyper_param,\n snap_choosing_config=snap_choosing_config,\n is_new_server=is_new_server,\n with_bert_as_feature=with_bert_as_feature,\n feature_for_ablation=feature_for_ablation,\n limited_features_list=limited_features_list)","repo_name":"ziv0808/clueweb_history","sub_path":"lambdamart_model_ltr.py","file_name":"lambdamart_model_ltr.py","file_ext":"py","file_size_in_byte":31965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34185607960","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 25 15:20:59 2022\n\n@author: jpeacock\n\"\"\"\n# =============================================================================\n# Imports\n# =============================================================================\nfrom collections import OrderedDict\nimport numpy as np\n\nfrom mt_metadata.base.helpers import write_lines\nfrom mt_metadata.base import get_schema, Base\nfrom mt_metadata.timeseries import TimePeriod\nfrom mt_metadata.transfer_functions.processing.fourier_coefficients import (\n Decimation,\n)\nfrom .standards import SCHEMA_FN_PATHS\nfrom mt_metadata.utils.list_dict import ListDict\n\n# =============================================================================\nattr_dict = get_schema(\"fc\", SCHEMA_FN_PATHS)\nattr_dict.add_dict(TimePeriod()._attr_dict, \"time_period\")\n\n\n# =============================================================================\nclass FC(Base):\n __doc__ = write_lines(attr_dict)\n\n def __init__(self, **kwargs):\n\n self.time_period = TimePeriod()\n self.levels = ListDict()\n\n super().__init__(attr_dict=attr_dict, **kwargs)\n\n def __len__(self):\n return len(self.levels)\n\n def __add__(self, other):\n if isinstance(other, FC):\n self.levels.extend(other.levels)\n self.update_time_period()\n\n return self\n else:\n msg = f\"Can only merge ch objects, not {type(other)}\"\n self.logger.error(msg)\n raise TypeError(msg)\n\n def update(self, other, match=[]):\n \"\"\"\n Update attribute values from another like element, skipping None\n\n :param other: DESCRIPTION\n :type other: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n if not isinstance(other, type(self)):\n self.logger.warning(\n \"Cannot update %s with %s\", type(self), type(other)\n )\n for k in match:\n if self.get_attr_from_name(k) != other.get_attr_from_name(k):\n msg = \"%s is not equal %s != %s\"\n self.logger.error(\n msg,\n k,\n self.get_attr_from_name(k),\n other.get_attr_from_name(k),\n )\n raise ValueError(\n msg,\n k,\n self.get_attr_from_name(k),\n other.get_attr_from_name(k),\n )\n for k, v in other.to_dict(single=True).items():\n if hasattr(v, \"size\"):\n if v.size > 0:\n self.set_attr_from_name(k, v)\n else:\n if v not in [None, 0.0, [], \"\", \"1980-01-01T00:00:00+00:00\"]:\n self.set_attr_from_name(k, v)\n\n ## Need this because decimation_levels are set when setting decimation_levels_recorded\n ## and it initiates an empty decimation_level, but we need to fill it with\n ## the appropriate metadata.\n for dl in other.levels:\n self.add_decimation_level(dl)\n\n @property\n def decimation_levels(self):\n \"\"\"list of decimation levels\"\"\"\n dl_list = []\n for dl in self.levels:\n dl_list.append(dl.decimation_level)\n dl_list = sorted(set([cc for cc in dl_list if cc is not None]))\n if self._decimation_levels == []:\n return dl_list\n\n elif dl_list == []:\n return self._decimation_levels\n\n elif len(self._decimation_levels) != dl_list:\n return dl_list\n\n @decimation_levels.setter\n def decimation_levels(self, value):\n if isinstance(value, np.ndarray):\n value = value.tolist()\n\n if value in [None, \"None\", \"none\", \"NONE\", \"null\"]:\n return\n elif isinstance(value, (list, tuple)):\n self._decimation_levels = value\n\n elif isinstance(value, (str)):\n value = value.split(\",\")\n self._decimation_levels = value\n\n else:\n raise TypeError(\n \"'channels_recorded' must be set with a list not \"\n f\"{type(value)}.\"\n )\n\n @property\n def channels_estimated(self):\n \"\"\"list of decimation levels\"\"\"\n dl_list = []\n for dl in self.levels:\n dl_list += dl.channels_estimated\n dl_list = sorted(set([cc for cc in dl_list if cc is not None]))\n if self._channels_estimated == []:\n return dl_list\n\n elif dl_list == []:\n return self._channels_estimated\n\n elif len(self._channels_estimated) != dl_list:\n return dl_list\n\n @channels_estimated.setter\n def channels_estimated(self, value):\n if isinstance(value, np.ndarray):\n value = value.tolist()\n\n if value in [None, \"None\", \"none\", \"NONE\", \"null\"]:\n return\n elif isinstance(value, (list, tuple)):\n self._channels_estimated = value\n\n elif isinstance(value, (str)):\n value = value.split(\",\")\n self._channels_estimated = value\n\n else:\n raise TypeError(\n \"'channels_recorded' must be set with a list not \"\n f\"{type(value)}.\"\n )\n\n def has_decimation_level(self, level):\n \"\"\"\n Check to see if the decimation_level already exists\n\n :param level: decimation_level level to look for\n :type level: string\n :return: True if found, False if not\n :rtype: boolean\n\n \"\"\"\n\n if level in self.decimation_levels:\n return True\n return False\n\n def decimation_level_index(self, level):\n \"\"\"\n get index of the decimation_level in the decimation_level list\n \"\"\"\n if self.has_decimation_level(level):\n return self.levels.keys().index(str(level))\n return None\n\n def get_decimation_level(self, level):\n \"\"\"\n Get a decimation_level\n\n :param level: decimation_level level to look for\n :type level: string\n :return: decimation_level object based on decimation_level type\n :rtype: :class:`mt_metadata.timeseries.decimation_level`\n\n \"\"\"\n\n if self.has_decimation_level(level):\n return self.levels[str(level)]\n\n def add_decimation_level(self, decimation_level_obj):\n \"\"\"\n Add a decimation_level to the list, check if one exists if it does overwrite it\n\n :param decimation_level_obj: decimation_level object to add\n :type decimation_level_obj: :class:`mt_metadata.transfer_functions.processing.fourier_coefficients.decimation_level`\n\n \"\"\"\n if not isinstance(decimation_level_obj, (Decimation)):\n msg = f\"Input must be metadata.decimation_level not {type(decimation_level_obj)}\"\n self.logger.error(msg)\n raise ValueError(msg)\n\n if self.has_decimation_level(decimation_level_obj.decimation_level):\n self.levels[decimation_level_obj.decimation_level].update(\n decimation_level_obj\n )\n self.logger.debug(\n f\"ch {decimation_level_obj.level} already exists, updating metadata\"\n )\n\n else:\n self.levels.append(decimation_level_obj)\n\n self.update_time_period()\n\n def remove_decimation_level(self, decimation_level_id):\n \"\"\"\n remove a ch from the survey\n\n :param level: decimation_level level to look for\n :type level: string\n\n \"\"\"\n\n if self.has_decimation_level(decimation_level_id):\n self.levels.remove(decimation_level_id)\n else:\n self.logger.warning(\n f\"Could not find {decimation_level_id} to remove.\"\n )\n\n self.update_time_period()\n\n @property\n def levels(self):\n \"\"\"List of decimation_levels in the ch\"\"\"\n return self._levels\n\n @levels.setter\n def levels(self, value):\n \"\"\"set the decimation_level list\"\"\"\n\n if not isinstance(value, (list, tuple, dict, ListDict, OrderedDict)):\n msg = (\n \"input dl_list must be an iterable, should be a list or dict \"\n f\"not {type(value)}\"\n )\n self.logger.error(msg)\n raise TypeError(msg)\n\n fails = []\n self._levels = ListDict()\n if isinstance(value, (dict, ListDict, OrderedDict)):\n value_list = value.values()\n\n elif isinstance(value, (list, tuple)):\n value_list = value\n\n for ii, decimation_level in enumerate(value_list):\n try:\n dl = Decimation()\n if hasattr(decimation_level, \"to_dict\"):\n decimation_level = decimation_level.to_dict()\n dl.from_dict(decimation_level)\n self._levels.append(dl)\n except Exception as error:\n msg = \"Could not create decimation_level from dictionary: %s\"\n fails.append(msg % error)\n self.logger.error(msg, error)\n\n if len(fails) > 0:\n raise TypeError(\"\\n\".join(fails))\n\n @property\n def n_decimation_levels(self):\n return self.__len__()\n\n def update_time_period(self):\n \"\"\"\n update time period from ch information\n \"\"\"\n start = []\n end = []\n for dl in self.levels:\n if dl.time_period.start != \"1980-01-01T00:00:00+00:00\":\n start.append(dl.time_period.start)\n if dl.time_period.start != \"1980-01-01T00:00:00+00:00\":\n end.append(dl.time_period.end)\n if start:\n if self.time_period.start == \"1980-01-01T00:00:00+00:00\":\n self.time_period.start = min(start)\n else:\n if self.time_period.start > min(start):\n self.time_period.start = min(start)\n if end:\n if self.time_period.end == \"1980-01-01T00:00:00+00:00\":\n self.time_period.end = max(end)\n else:\n if self.time_period.end < max(end):\n self.time_period.end = max(end)\n","repo_name":"kujaku11/mt_metadata","sub_path":"mt_metadata/transfer_functions/processing/fourier_coefficients/fc.py","file_name":"fc.py","file_ext":"py","file_size_in_byte":10136,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"73140843045","text":"import pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom helpers import find_type_cols\n\n# load raw data\nplayers = pd.read_csv(\"raw_data/players.csv\")\nraw_roles = pd.read_csv(\"raw_data/nbastats.csv\")\n\n# select role played for max number of season\nroles = raw_roles[['ID', 'Player', 'Pos']]\nroles = roles.groupby(by=['ID', 'Pos', 'Player'])[['Player']].count().rename(columns={'Player': 'n_season'}).reset_index()\n# some players have multiple roles with max value of n_season.. I'll deal with it later\nroles = roles.groupby(['ID'])[['Player', 'Pos']].max().reset_index()\nplayers = players.merge(roles, how='left', on='Player')\n\n# deal with NA values\nmissing_players = pd.isna(players['ID']) | pd.isna(players['Pos'])\nmerge_cols = [col for col in list(players.columns) if (col in list(raw_roles.columns)) and (col not in ['Pos', 'ID', 'Player'])]\nright_df = raw_roles[['Pos', 'ID'] + merge_cols].drop_duplicates()\nnew_vals = players[missing_players][['Player'] + merge_cols].merge(right_df, how='left', on=merge_cols)\nnew_vals.set_index(players[missing_players].index, inplace=True)\nplayers.fillna(value=new_vals[['ID', 'Pos']], inplace=True)\n\n# create 2p attempt stats\nplayers['2PA'] = players['FGA'] - players['3PA']\nplayers['2PM'] = players['FGM'] - players['3PM']\nplayers['2P_pc'] = players['2PM'] / players['2PA']\n\n\nscaler = MinMaxScaler()\nftrs = players[find_type_cols(players)]\n# scale variables to best compare variability of the data: some of them have a big magnitude with respect to the other\nscl_ftrs = pd.DataFrame(scaler.fit_transform(ftrs), columns=list(ftrs.columns), index=players['ID'])\n\n\n# save csv to use in shiny app\nplayers.to_csv(\"data/players_post_input.csv\", index=False)\nscl_ftrs.reset_index().to_csv(\"data/scaled_features_post_input.csv\", index=False)\n","repo_name":"Davide-bll/soccerment_nba","sub_path":"pre_process_raw_data.py","file_name":"pre_process_raw_data.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12818884337","text":"from collections import defaultdict, deque\n\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites):\n if not prerequisites:\n return True\n\n graph = self.make_graph(prerequisites)\n dependencies = self.make_dependencies(prerequisites)\n\n queue = deque(self.find_no_dependencies(dependencies))\n while queue:\n cur = queue.pop()\n\n for link in graph[cur]:\n dependencies[link].remove(cur)\n\n if not dependencies[link]:\n queue.append(link)\n\n return self.is_clear(dependencies)\n\n def is_clear(self, dependencies:dict):\n for v in dependencies.values():\n if v:\n return False\n\n return True\n\n\n def find_no_dependencies(self, dependencies:dict):\n no_dependencies = []\n for k, v in dependencies.items():\n if not v:\n no_dependencies.append(k)\n\n return no_dependencies\n\n def make_graph(self, prerequisites):\n graph = defaultdict(list)\n for f, t in prerequisites:\n graph[t].append(f)\n if f not in graph.keys():\n graph[f] = []\n\n return graph\n\n def make_dependencies(self, prerequisites):\n dependencies = defaultdict(set)\n for f, t in prerequisites:\n dependencies[f].add(t)\n if t not in dependencies.keys():\n dependencies[t] = set()\n\n return dependencies\n\n\ns = Solution()\n# numCourses = 2\n# prerequisites = [[1, 0]]\n# numCourses = 2\n# prerequisites = [[1,0],[0,1]]\nnumCourses = 5\nprerequisites = [[1,4],[2,4],[3,1],[3,2]]\nprint(s.canFinish(numCourses, prerequisites))","repo_name":"galid1/Algorithm","sub_path":"python/leetcode/bfs/207. Course Schedule.py","file_name":"207. Course Schedule.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"16254404296","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 21 20:00:08 2020\n\n@author: rundo\n\"\"\"\nimport numpy as np\nimport scipy as sp\nfrom scipy import special\nfrom matplotlib import pyplot as plt\nfrom Lab2_Q2b_function import *\n\n######################## b i #################################################\nx = np.arange(0, 20, 0.1) #plot from 0 to 20 with 0.1 interval\ny0 = [] #initiate arraysfor J0, J1, J2\ny1 = []\ny2 = []\n\nfor i in x: #Calculate values for J0\n y0.append(J(0, i))\n \nfor i in x: #Calculate values for J0\n y1.append(J(1, i))\n\nfor i in x: #Calculate values for J0\n y2.append(J(2, i))\n\n#plot\nplt.figure(1)\nplt.plot(x, y0, label = '$J_0$')\nplt.plot(x, y1, label = '$J_1$')\nplt.plot(x, y2, label = '$J_2$')\nplt.xlabel('$x$')\nplt.ylabel('$J_m(x)$')\nplt.legend()\nplt.title('Q2b, plot of $J_0$, $J_1$, and $J_2$, textbood Ex5.4(a)')\n##############################################################################\n\n######################## b ii ################################################\nx = np.arange(0, 0.25, 0.001)\ny0 = []\ny1 = []\n\n\nfor i in x: #Calculate values for J0, with my own bessel func.\n y0.append(J(0, i))\n\n\n#Plot with scipy.special.jv(0,x)\nplt.figure(2)\nplt.plot(x, special.jv(0, x), label = 'scipy.special.jv(0,x)') #calculate & plot with scipy special func.\nplt.plot(x, y0, label = 'My function J(0,x)')\nplt.xlabel('$x$')\nplt.ylabel('$J_0(x)$')\nplt.legend()\nplt.title('Comparison between my bessel and scipy.special.jv, for $J_0(x)$')\nplt.show()\n\nfor i in x: #Calculate values for J1, with my own bessel func.\n y1.append(J(1, i))\n\n#Plot with scipy.special.jv(1,x)\nplt.figure(3)\nplt.plot(x, special.jv(1, x), label = 'scipy.special.jv(1,x)') #calculate & plot with scipy special func.\nplt.plot(x, y1, label = 'My function J(1,x)')\nplt.xlabel('$x$')\nplt.ylabel('$J_1(x)$')\nplt.legend()\nplt.title('Comparison between my bessel and scipy.special.jv, for $J_1(x)$')\nplt.show()\n\n#Calculate the actual difference between my bessel and scipy.special.jv\nprint('-------------Q2b-------------')\nprint('Difference between my Bessel and scipy.special.jv with m=0, x=0:', \n J(0,0) - special.jv(0,0))\nprint('Difference between my Bessel and scipy.special.jv with m=2, x=2:', \n J(2,2) - special.jv(2,2))\nprint('Difference between my Bessel and scipy.special.jv with m=1, x=2.5:', \n J(1,2.5) - special.jv(1,2.5))\nprint('-----------------------------\\n')\n\n##############################################################################\n\n\n########################### b iii ############################################\n#set parameters' unit in meter\nlam = 500e-9\nk = 2 * np.pi / lam\n\n#calculate light insensity from r = 0nm to r = 1500nm\nr = np.arange(0,1500)\nI_r = [0.25] #set the value for r = 0 manually, since program does not perform well for limits\nfor i in range(1, 1500):\n I_r.append((J(1, k*i*1e-9) / (k*i*1e-9)) ** 2)\n\n\n#generate the mesh grid\nP = np.ones([2001,2001], float)*0 #initiate a 2001 by 2001 matrix, so it can cover -1um to 1um\nfor i in range(0,2001):\n for j in range(0,2001):\n radius = int(np.sqrt((i-1000)**2 + (j-1000)**2)) #calculate the radius for each point on the grid\n P[i][j] = I_r[radius] #simply assign light intensity to the point according to the radius\n #because of symmetry. tones of times saved!\n \n\n#plot with pcolormesh()\nplt.figure(figsize = (10,8)) \nx = np.arange(-1000, 1001, 1) #create axies for the plot\ny = np.arange(-1000, 1001, 1) \nplt.pcolormesh(x, y, P, vmax = 0.01, shading='nearest') #set max intensity at 0.01 for best sensitivity\nplt.colorbar(label = 'Light Intensity')\nplt.xlabel('$nm$', fontsize = 15)\nplt.ylabel('$nm$', fontsize = 15)\nplt.title('Q2b Diffraction Plot with pcolormesh')\nplt.show()\n\n#plot with imshow()\nplt.figure(figsize = (10,8))\nplt.imshow(P, vmax = 0.01, extent = [-1000 , 1000, -1000 , 1000], cmap = 'inferno')\nplt.colorbar(label = 'Light Intensity')\nplt.title('Q2b Diffraction Plot with imshow')\nplt.xlabel('$nm$', fontsize = 15)\nplt.ylabel('$nm$', fontsize = 15)\nplt.title('Q2b Diffraction Plot with imshow')\nplt.show()\n","repo_name":"rundong-zhou/PHY407-Projects","sub_path":"Lab2/Submission/Lab2_Q2b.py","file_name":"Lab2_Q2b.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30277328654","text":"# coding:utf-8\nimport os\nimport cv2\nimport tensorflow as tf\n\nsess = tf.InteractiveSession()\npath=r'E:\\dataset\\yuanshi\\sfew\\train'\nout_path=r'E:\\dataset\\sfew\\balance\\aug_yuanshi\\train'\ndir_list=os.listdir(path)\nfor list in dir_list:\n if list == 'angry':\n f = os.path.join(path,list)\n o = os.path.join(out_path,list)\n elif list == 'disgust':\n f = os.path.join(path, list)\n o = os.path.join(out_path, list)\n elif list == 'happy':\n f = os.path.join(path, list)\n o = os.path.join(out_path, list)\n elif list == 'neutral':\n f = os.path.join(path, list)\n o = os.path.join(out_path, list)\n else:\n print(\"get error.......\\n\")\n continue\n# 定义图片生成器\n# f = r\"E:\\dataset\\jiaoyu\\yuanshi\\SFEW2.0\\train\\angry\"\n# o=r\"E:\\dataset\\jiaoyu\\aug_yuanshi\\SFEW2.0\\train\"\n fs = os.listdir(f)\n for f1 in fs:\n tmp_path = os.path.join(f, f1)\n img = cv2.imread(tmp_path)\n img = cv2.resize(img, (64, 64))\n cropped_image = tf.random_crop(img, (56, 56, 3))\n for i in range(10):\n cv2.imwrite(os.path.join(o,str(i)+f1),cropped_image.eval())\nsess.close()\n","repo_name":"Silky-man/tools","sub_path":"随机裁剪.py","file_name":"随机裁剪.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"3936698018","text":"\"\"\"\nhttps://leetcode.com/problems/reformat-the-string/\n\nGiven alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).\n\nYou have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.\n\nReturn the reformatted string or return an empty string if it is impossible to reformat the string.\n\n \n\nExample 1:\n\nInput: s = \"a0b1c2\"\nOutput: \"0a1b2c\"\nExplanation: No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.\nExample 2:\n\nInput: s = \"leetcode\"\nOutput: \"\"\nExplanation: \"leetcode\" has only characters so we cannot separate them by digits.\nExample 3:\n\nInput: s = \"1229857369\"\nOutput: \"\"\nExplanation: \"1229857369\" has only digits so we cannot separate them by characters.\nExample 4:\n\nInput: s = \"covid2019\"\nOutput: \"c2o0v1i9d\"\nExample 5:\n\nInput: s = \"ab123\"\nOutput: \"1a2b3\"\n\"\"\"\n\n\nclass Solution:\n def reformat(self, s: str) -> str:\n if len(s) == 1:\n return s\n letters = []\n digits = []\n for si in s:\n if si.isdigit():\n digits.append(si)\n else:\n letters.append(si)\n if abs(len(digits) - len(letters)) > 1:\n return \"\"\n if len(letters) > len(digits):\n first = letters\n second = digits\n else:\n first = digits\n second = letters\n res = \"\"\n for i in range(len(second)):\n res += first[i]\n res += second[i]\n if i < len(first) - 1:\n res += first[i + 1]\n return res\n\n\ns = \"1229857369\"\nS = Solution()\nprint(S.reformat(s))\n","repo_name":"wenjiaaa/Leetcode","sub_path":"P1001_P1500/1417-reformat-the-string.py","file_name":"1417-reformat-the-string.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"19546735652","text":"# -- coding:utf-8 --\nimport pandas as pd\nimport numpy as np\nimport os\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\nfrom utils_features_selection import *\nfrom mpl_toolkits import mplot3d\n\nfrom xgboost import plot_tree\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import linear_model\nfrom sklearn.ensemble import RandomForestClassifier,RandomForestRegressor\nfrom sklearn import svm\nfrom sklearn import tree\nimport math\nfrom sklearn.neural_network import MLPClassifier, MLPRegressor\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom sklearn import preprocessing\n\n\n## features selection part\ndef features_selection():\n ## Read 100 data\n X_data_all_features,Y_data,x_col = data_read_and_split()\n\n # Construct a dataframe to store the importance information of features\n import_feature = pd.DataFrame()\n import_feature['col'] = x_col\n import_feature['xgb'] = 0\n model = xgb.XGBRegressor(\n max_depth=4,\n learning_rate=0.2,\n reg_lambda=1,\n n_estimators=150,\n subsample=0.9,\n colsample_bytree=0.9)\n # Repeat the test 100 times\n for i in range(100): # 50,150\n #Each experiment randomly divides 100 data into 0.7 training set and 0.3 test set, pay attention to random random_state=i\n ## The reason for this method is that because of the small sample size available, in order to generate different\n # training sample sets, the ranking of the importance of the features is more stable, so I chose such a method.\n ## Different samples are generated by different random seeds each time, so that the influence of the\n # abnormality of a small number of samples on the importance of features can be suppressed to a certain extent.\n min_max_scaler = preprocessing.MinMaxScaler()\n x_train, x_test, y_train, y_test = train_test_split(X_data_all_features, Y_data, test_size=0.3, random_state=i)\n x_train= min_max_scaler.fit_transform(x_train)\n x_test = min_max_scaler.fit_transform(x_test)\n #Define model hyperparameters\n\n model = xgb.XGBRegressor(\n max_depth=4,\n learning_rate=0.2,\n reg_lambda=1,\n n_estimators=150,\n subsample = 0.9,\n colsample_bytree = 0.9)\n\n #\n model.fit(x_train, y_train)\n #print(\"Accuracy: %.2f\" %model.score(x_test,y_test))\n print(\"RMSE: %.2f\"% math.sqrt(np.mean((model.predict(x_test) - y_test) ** 2)))\n #Cumulative feature importance\n import_feature['xgb'] = import_feature['xgb']+model.feature_importances_/100\n # Sort by feature importance in descending order\n import_feature = import_feature.sort_values(axis=0, ascending=False, by='xgb')\n print('Top 3 features:')\n print(import_feature.head())\n # Sort feature importances from GBC model trained earlier\n # Location information according to feature importance\n indices = np.argsort(import_feature['xgb'].values)[::-1]\n #Get the top 3 important feature locations\n Num_f = 5\n indices = indices[:Num_f]\n \n # Visualise these with a barplot\n # plt.subplots(dpi=400,figsize=(12, 10))\n plt.subplots(figsize=(6, 5))\n # g = sns.barplot(y=list(name_dict.values())[:Num_f], x = import_feature.iloc[:Num_f]['xgb'].values[indices], orient='h') #import_feature.iloc[:Num_f]['col'].values[indices]\n g = sns.barplot(y=import_feature.iloc[:Num_f]['col'].values[indices], x = import_feature.iloc[:Num_f]['xgb'].values[indices], orient='h') #import_feature.iloc[:Num_f]['col'].values[indices]\n g.set_xlabel(\"Relative importance\",fontsize=12)\n g.set_ylabel(\"Features\",fontsize=12)\n g.tick_params(labelsize=10)\n sns.despine() \n # plt.savefig('feature_importances_v3.png')\n plt.show()\n # g.set_title(\"The mean feature importance of XGB models\");\n # Get the importance value of the top 10 important features\n import_feature_cols= import_feature['col'].values\n\n # Draw feature pyramid\n num_i = 1\n val_score_old = 10000\n val_score_new = 10000\n while val_score_new <= val_score_old:\n val_score_old = val_score_new\n # Special order in order of importance\n x_col = import_feature_cols[:num_i]\n print(x_col)\n X_data = X_data_all_features[x_col]#.values\n min_max_scaler = preprocessing.MinMaxScaler()\n x_data = min_max_scaler.fit_transform(X_data.values)\n\n\n ## Cross-validation\n print('5-Fold CV:')\n rmse_train, rmse_val, rmse_train_std, rmse_val_std = StratifiedKFold_func_with_features_sel(X_data.values,Y_data.values)\n print(\"Train RMSE-score is %.4f ; Validation RMSE-score is %.4f\" % (rmse_train,rmse_val))\n print(\"Train RMSE-score-std is %.4f ; Validation RMSE-score-std is %.4f\" % (rmse_train_std,rmse_val_std))\n val_score_new = rmse_val\n num_i += 1\n \n print('Selected features:',x_col[:-1])\n \n return list(x_col[:-1])\n\n\ndef Compare_with_other_method(sub_cols=['Yarn Count (tex)','Stitch density (loops/cm2)']):\n ## Read 351 data set (remove all samples with empty sub_cols from 375)\n X_data_all_features, Y_data, x_col = data_read_and_split()\n x_np = X_data_all_features[sub_cols]\n\n #Figure 4 for si illustrates the problem. If it is 50% off, SI cannot be drawn. Figure 4\n X_train, X_val, y_train, y_val = train_test_split(x_np, Y_data, test_size=0.3, random_state=6)\n\n min_max_scaler = preprocessing.MinMaxScaler()\n\n X_train_normalized = min_max_scaler.fit_transform(X_train)\n X_val_normalized = min_max_scaler.fit_transform(X_val)\n Num_iter = 10\n #fig = plt.figure(figsize=(16, 8))\n labels_names = []\n\n '''\n #Define the comparison method under full features\n xgb_n_clf = xgb.XGBClassifier(\n max_depth=4\n ,learning_rate=0.2\n ,reg_lambda=1\n ,n_estimators=150\n ,subsample = 0.9\n ,colsample_bytree = 0.9\n ,random_state=0)\n tree_clf = tree.DecisionTreeClassifier(random_state=0,max_depth=4) #random_state=0,之前没加\n RF_clf1 = RandomForestClassifier(random_state=0,n_estimators=150,max_depth=4,)\n LR_clf = linear_model.LogisticRegression(random_state=0,C=1,solver='lbfgs')\n LR_reg_clf = linear_model.LogisticRegression(random_state=0,C=0.1, solver='lbfgs')\n \n \n\n \n \n i = 0\n \n Moodel_name = ['Multi-tree XGBoost with all features',\n 'Decision tree with all features',\n 'Random Forest with all features',\n 'Logistic regression with all features with regularization parameter = 1 (by default)',\n 'Logistic regression with all features with regularization parameter = 10',]\n for model in [xgb_n_clf,tree_clf,RF_clf1,LR_clf,LR_reg_clf]:\n print('Model:'+Moodel_name[i])\n #K-fold with f1 evaluation\n acc_train, acc_val, acc_train_std, acc_val_std = StratifiedKFold_func(x_np.values, y_np.values,Num_iter,model, score_type ='f1')\n print('F1-score of Train:%.6f with std:%.4f \\nF1-score of Validation:%.4f with std:%.6f '%(acc_train,acc_train_std,acc_val,acc_val_std))\n # K discount based on auc evaluation method\n acc_train, acc_val, acc_train_std, acc_val_std = StratifiedKFold_func(x_np.values, y_np.values,Num_iter,model, score_type ='auc')\n print('AUC of Train:%.6f with std:%.4f \\nAUC of Validation:%.6f with std:%.4f '%(acc_train,acc_train_std,acc_val,acc_val_std))\n\n #To draw si picture 4\n model.fit(X_train,y_train)\n pred_train_probe = model.predict_proba(X_train)[:,1]\n pred_val_probe = model.predict_proba(X_val)[:,1]\n #plot_roc(y_val, pred_val_probe,Moodel_name[i],fig,labels_names,i) # 为了画si图4中的test\n #plot_roc(y_train, pred_train_probe,Moodel_name[i],fig,labels_names,i) # 为了画si图4 train\n print('AUC socre:',roc_auc_score(y_val, pred_val_probe))\n \n i = i+1\n '''\n ## Comparison of three-character single-tree models\n #x_np_sel = x_np[sub_cols] #选择三特征\n ## The data set is divided for a single training of a single tree and an AUC graph is generated.\n # The division method is the same as before.\n # X_train, X_val, y_train, y_val = train_test_split(x_np_sel, y_np, test_size=0.3, random_state=6)\n\n #For comparison of three-feature models\n xgb_clf = xgb.XGBRegressor(max_depth=4,\n learning_rate=0.2,\n reg_lambda=1,\n n_estimators=100,\n subsample = 0.9,\n colsample_bytree = 0.9)\n tree_clf = tree.DecisionTreeRegressor(random_state=0,max_depth=3)\n RF_clf2 = RandomForestRegressor(random_state=0,n_estimators=10,max_depth=3,)\n #added by me\n LR_clf = linear_model.LinearRegression()\n LR_reg_clf = linear_model.LinearRegression()\n svm_clf = svm.SVR()\n svm_clf2 = svm.NuSVR()\n nn_clf = MLPRegressor(hidden_layer_sizes=(5,2),alpha=1e-5)\n\n i = 0\n Moodel_name = ['XGBoost',\n 'DT',\n 'RF',\n 'LR with RP = 1',\n 'LR with RP=10',\n 'MLP',\n 'SVM',\n 'SVM2']\n for model in [xgb_clf,tree_clf,RF_clf2,LR_clf,LR_reg_clf,nn_clf,svm_clf,svm_clf2]:\n print('Model '+Moodel_name[i])\n # f1 results\n # acc_train, acc_val, acc_train_std, acc_val_std = StratifiedKFold_func(x_np_sel.values, y_np.values,Num_iter,model, score_type ='f1')\n # print('F1-score of Train:%.6f with std:%.4f \\nF1-score of Validation:%.4f with std:%.6f '%(acc_train,acc_train_std,acc_val,acc_val_std))\n # auc results\n #acc_train, acc_val, acc_train_std, acc_val_std = StratifiedKFold_func(x_np_sel.values, y_np.values,Num_iter,model, score_type ='auc')\n #print('AUC of Train:%.6f with std:%.4f \\nAUC of Validation:%.6f with std:%.4f '%(acc_train,acc_train_std,acc_val,acc_val_std))\n\n model.fit(X_train_normalized,y_train)\n pred_train = model.predict(X_train_normalized)\n print(\"RMSE-train : \", math.sqrt(np.mean(pred_train - y_train) ** 2))\n print(\"MAE-train :\", mean_absolute_error(y_train, pred_train))\n print(\"MSE-train \", mean_squared_error(y_train, pred_train))\n pred_val = model.predict(X_val_normalized)\n print(\"RMSE-test : \", math.sqrt(np.mean(pred_val-y_val)**2))\n print(\"MAE-test :\", mean_absolute_error(y_val,pred_val))\n print(\"MSE-test \",mean_squared_error(y_val,pred_val))\n #pred_score = model.score(X_val,y_val)\n #print(\" R = \", pred_score)\n drow_scatter_plot(X_train.values[:,0],X_train.values[:,1],y_train,pred_train,Moodel_name[i])\n\n #plot 3dimensional scatter\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n ax.scatter3D(X_val.values[:,0],X_val.values[:,1], y_val, color='red',marker ='x',label='Actual')\n ax.scatter3D(X_val.values[:,0],X_val.values[:,1], pred_val, color='green',marker ='^', label='Predicted')\n #plt.title(\"simple 3D scatter plot\")\n plt.legend(loc='upper right')\n ax.set_xlabel('Yarn Count')\n ax.set_ylabel('Stitch density')\n ax.set_zlabel('Air Permeability')\n plt.savefig(Moodel_name[i]+' test')\n plt.show()\n #plot_roc(y_val, pred_val_probe,Moodel_name[i],fig,labels_names,i)\n # plot_roc(y_train, pred_train_probe,Moodel_name[i-5],fig,labels_names,i)\n #print('AUC socre:',roc_auc_score(y_val, pred_val))\n i = i+1\n\n\ndef Compare_methods(sub_cols=['Yarn Count (tex)', 'Stitch density (loops/cm2)']):\n ## Read 351 data set (remove all samples with empty sub_cols from 375)\n X_data_all_features, Y_data, x_col = data_read_and_split()\n x_np = X_data_all_features[sub_cols]\n\n min_max_scaler = preprocessing.MinMaxScaler()\n x_data = min_max_scaler.fit_transform(x_np.values)\n\n\n # For comparison of three-feature models\n xgb_clf = xgb.XGBRegressor(max_depth=4,\n learning_rate=0.2,\n reg_lambda=1,\n n_estimators=150,\n subsample=0.9,\n colsample_bytree=0.9)\n tree_clf = tree.DecisionTreeRegressor(random_state=0, max_depth=3)\n RF_clf2 = RandomForestRegressor(random_state=0, n_estimators=1, max_depth=3, )\n # added by me\n LR_clf = linear_model.LinearRegression()\n LR_reg_clf = linear_model.LinearRegression()\n svm_clf = svm.SVR()\n svm_clf2 = svm.NuSVR()\n nn_clf = MLPRegressor(hidden_layer_sizes=(5, 2), alpha=1e-5)\n\n Model_name = ['XGBoost',\n 'DT',\n 'RF',\n 'LR with RP = 1',\n 'LR with RP=10',\n 'MLP',\n 'SVM',\n 'SVM2']\n idx =0\n for model in [xgb_clf, tree_clf, RF_clf2, LR_clf, LR_reg_clf, nn_clf, svm_clf, svm_clf2]:\n #print('Model ' + Model_name[idx])\n rmse_train, rmse_val, rmse_train_std, rmse_val_std=Compare_StratifiedKFold(x_data,Y_data,100,model)\n print(\"Train RMSE-score is %.4f ; Validation RMSE-score is %.4f\" % (rmse_train,rmse_val))\n print(\"Train RMSE-score-std is %.4f ; Validation RMSE-score-std is %.4f\" % (rmse_train_std,rmse_val_std))\n idx=idx+1\n '''\n # plot 3dimensional scatter\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n ax.scatter3D(X_val.values[:, 0], X_val.values[:, 1], y_val, c=y_val, cmap='Greens')\n ax.scatter3D(X_val.values[:, 0], X_val.values[:, 1], pred_val, c=pred_val, cmap='Blues')\n plt.title(\"simple 3D scatter plot\")\n ax.set_xlabel('Yarn Count', fontweight='bold')\n ax.set_ylabel('Stitch density', fontweight='bold')\n ax.set_zlabel('Air Permeability', fontweight='bold')\n plt.savefig(Model_name[i])\n plt.show()\n '''\n\n\n#if __name__ == '__main__':\n \n ## 特征筛选\nselected_cols = features_selection()\n#single_tree()\n ## Compare Method\nprint('Compare with other methods')\nCompare_with_other_method()\n#Compare_methods()","repo_name":"faisalahm3d/AirPermeabilityPrediction","sub_path":"main_of_features_selection.py","file_name":"main_of_features_selection.py","file_ext":"py","file_size_in_byte":14132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16135307242","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport logging\r\nfrom MyFunctions import *\r\nfrom MyOptimizers import *\r\nimport json\r\nimport os\r\nimport math\r\n\r\n\r\ndef ELM_rand( X_train, X_test, T_train, T_test, ELM_hparameters):\r\n \"\"\"Build Deep Random Vector Functional Link (DRVFL)\"\"\"\r\n # define variables\r\n P = X_train.shape[0]\r\n n1 = ELM_hparameters[\"n1\"]\r\n \r\n # create a necessary directory\r\n parameters_path = \"./parameters/\"\r\n create_directory(parameters_path)\r\n\r\n N_train = X_train.shape[1]\r\n N_test = X_test.shape[1]\r\n X_train = np.concatenate((X_train, np.ones((1, N_train))), axis=0)\r\n X_test = np.concatenate((X_test, np.ones((1, N_test))), axis=0)\r\n Yi = X_train\r\n Yi_test=X_test\r\n P = Yi.shape[0]\r\n\r\n Ri = 2 * np.random.rand(n1, P) - 1\r\n\r\n Yi = activation(np.dot(Ri, Yi))\r\n Yi_test = activation(np.dot(Ri, Yi_test))\r\n Yi = Yi / np.linalg.norm(Yi, axis=0)\r\n Yi_test = Yi_test / np.linalg.norm(Yi_test, axis=0)\r\n\r\n Oi = ADMM_LS(Yi, T_train, ELM_hparameters)\r\n\r\n T_hati = np.dot(Oi, Yi) \r\n T_hati_test = np.dot(Oi, Yi_test)\r\n\r\n train_accuracy = calculate_accuracy(T_hati, T_train)\r\n test_accuracy = calculate_accuracy(T_hati_test, T_test)\r\n \r\n return train_accuracy, test_accuracy\r\n","repo_name":"Polgrauj/DTs_in_RandomizedNN","sub_path":"ELM_rand.py","file_name":"ELM_rand.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7499516940","text":"from REINFORCE import REINFORCE\nfrom collections import deque\nfrom matplotlib import pyplot as plt\nfrom kernel import kernel\nimport gym\nimport tensorflow as tf \nimport numpy as np \nimport sklearn\nimport sklearn.preprocessing\nimport DHMP\n\nenv = gym.make('MountainCarContinuous-v0')\nenv.seed(1)\n\nstate_dim = env.observation_space.shape[0]\nactions_dim = env.action_space.shape[0] \naction_bound = [env.action_space.low, env.action_space.high]\n\nstate_space_samples = np.array([env.observation_space.sample() for x in range(10000)])\nscaler = sklearn.preprocessing.StandardScaler()\nscaler.fit(state_space_samples)\n\ndef scale_state(state): \n scaled = scaler.transform([state])\n return scaled\n\nsess = tf.Session()\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-3)\n\ndef policy_network(states):\n\n layer1 = tf.layers.dense(\n inputs=states,\n # inputs=tf.nn.l2_normalize(self.tf_states),\n units=128,\n activation=tf.nn.tanh, # relu activation\n kernel_initializer=tf.random_normal_initializer(),\n bias_initializer=tf.constant_initializer(0),\n name='fc1'\n )\n\n layer2 = tf.layers.dense(\n inputs=layer1,\n # inputs=tf.nn.l2_normalize(self.tf_states),\n units=128,\n activation=tf.nn.tanh, # relu activation\n kernel_initializer=tf.random_normal_initializer(),\n bias_initializer=tf.constant_initializer(0),\n name='fc2'\n )\n\n mu = tf.layers.dense(\n inputs=layer2,\n # inputs=tf.nn.l2_normalize(self.tf_states),\n units=actions_dim,\n activation=tf.nn.tanh, # relu activation\n kernel_initializer=tf.random_normal_initializer(),\n bias_initializer=tf.constant_initializer(0),\n name='out'\n )\n\n sigma = tf.layers.dense(\n inputs=layer2,\n units=actions_dim,\n activation=tf.nn.sigmoid,\n kernel_initializer=tf.random_normal_initializer(),\n bias_initializer=tf.constant_initializer(0.1),\n name='fc4_sigma'\n )\n\n sigma = tf.nn.softplus(sigma) + 1e-5\n \n return mu, sigma\n\npg_reinforce = REINFORCE(session = sess, \n optimizer = optimizer,\n policy_network = policy_network,\n state_dim = state_dim,\n actions_dim = actions_dim,\n action_bound = action_bound,\n #init_exp=0.5, # initial exploration prob\n #final_exp=0.0, # final exploration prob\n #anneal_steps=10000, # N steps for annealing exploration\n discount_factor=0.99, # discount future rewards\n #reg_param=0.001, # regularization constants\n #max_gradient=5, # max gradient norms\n summary_writer=None,\n summary_every=100)\n\ntheta = np.random.uniform(low=0, high = 1, size=state_dim+actions_dim+1+state_dim)\nnoise_prior = np.sqrt(theta[-state_dim:])\nnoise_prior = np.diagflat(noise_prior)\ntheta = theta[0:-state_dim]\nkeps = 1e-5\nB = np.eye(state_dim)\n\ns_test = []\ny_test = []\nSMSE = []\nSMSE_POG = []\norder = []\n\nT = 200\nT_test = 500\n\n\n# get test data\ns_test = np.zeros((T_test, state_dim+actions_dim))\ny_test = np.zeros((T_test, state_dim))\nstate = env.reset()\nfor i in range(T_test):\n state = scale_state(state)\n state=np.squeeze(state)\n\n action = pg_reinforce.sampleAction(state)\n next_state, reward, done, _ = env.step(action)\n\n if next_state[0] >= 0.5:\n c_reward = 10\n #c_reward = reward\n elif next_state[0] > -0.4:\n c_reward = (1+next_state[0])**2 #+ (next_state[1])\n #c_reward = reward\n else:\n #c_reward = (1-next_state[0])**2\n c_reward = reward\n\n pg_reinforce.storeRollout(state, action, c_reward)\n\n if (i%10 == 9):\n pg_reinforce.updateModel()\n\n\n s_test[i] = np.concatenate([state, action])\n y_test[i] = next_state\n\n state = next_state\n\n# mean-center\ny_test = y_test - np.mean(y_test, axis=0)\n\n\n#start training\npg_reinforce.cleanUp()\ns = np.zeros((1, state_dim + actions_dim))\ny = np.zeros((1, state_dim))\ns_comp = np.zeros((1, state_dim + actions_dim))\ny_comp = np.zeros((1, state_dim))\n\nstate = env.reset()\nfor i in range(T):\n #env.render()\n state = scale_state(state)\n state = np.squeeze(state)\n \n action = pg_reinforce.sampleAction(state)\n next_state, reward, done, _ = env.step(action)\n\n if next_state[0] >= 0.5:\n c_reward = 10\n #c_reward = reward\n elif next_state[0] > -0.4:\n c_reward = (1+next_state[0])**2 #+ (next_state[1])\n #c_reward = reward\n else:\n #c_reward = (1-next_state[0])**2\n c_reward = reward\n\n pg_reinforce.storeRollout(state, action, c_reward)\n\n if (i%10 == 9):\n pg_reinforce.updateModel()\n\n # Dense GP\n if i > 0:\n D = s[1:]\n yy = y[1:]\n yy = yy-np.mean(yy, axis=0)\n yy_flatten = yy.flatten()\n\n # get training label variance, prepared for SMSE\n if i==1:\n v = 1\n else:\n v = (yy - np.mean(yy, axis=0))**2\n v = np.sum(v, axis=1)\n v = np.sum(v)/yy.shape[0]\n\n\n mu_test_posterior = []\n sigma_test_posterior = []\n standard_error = []\n\n for j in range(T_test):\n\n if i == 1:\n KDD = kernel(theta, D, D, X_vector=True, Y_vector=True)\n KDD = np.kron(KDD, B)\n KxtestD = kernel(theta, D, s_test[j], X_vector=True, Y_vector=True)\n KxtestD = np.kron(KxtestD, B)\n elif i > 1:\n KDD = kernel(theta, D, D, X_vector=False, Y_vector=False)\n KDD = np.kron(KDD, B)\n KxtestD = kernel(theta, D, s_test[j], X_vector=False, Y_vector=True)\n KxtestD = np.kron(KxtestD, B)\n\n mu_pos = KxtestD.T.dot(np.linalg.inv(KDD+np.kron(noise_prior**2, np.eye(D.shape[0])))).dot(yy_flatten)\n mu_test_posterior.append(mu_pos)\n\n Ktest = kernel(theta, s_test[j], s_test[j], X_vector=True, Y_vector=True)\n Ktest = np.kron(Ktest, B)\n sigma_pos = Ktest - KxtestD.T.dot(np.linalg.inv(KDD+np.kron(noise_prior**2, np.eye(D.shape[0])))).dot(KxtestD) + noise_prior**2\n sigma_test_posterior.append(sigma_pos)\n\n error = np.sum((y_test[j]-mu_pos)**2)/v\n standard_error.append(error)\n\n # get SMSE\n mean_error = np.mean(np.array(standard_error))\n SMSE.append(mean_error)\n\n print('step {}'.format(i))\n print('SMSE: {}'.format(mean_error))\n\n\n # POG\n if i > 0:\n if i == 1:\n s_comp = s_comp[1:]\n y_comp = y_comp[1:]\n # mean-center the training data\n yy_comp = y_comp\n yy_comp = yy_comp - np.mean(yy_comp, axis=0)\n yy_comp_flatten = yy_comp.flatten()\n\n # get training variance\n if i==1:\n v_comp = 1\n else:\n v_comp = (yy_comp - np.mean(yy_comp, axis=0))**2\n v_comp = np.sum(v_comp, axis=1)\n v_comp = np.sum(v_comp)/yy_comp.shape[0]\n\n standard_error_comp = []\n\n for k in range(T_test):\n if i == 1:\n KDD_comp = kernel(theta, s_comp, s_comp, X_vector=True, Y_vector=True)\n KDD_comp = np.kron(KDD_comp, B)\n KxtestD_comp = kernel(theta, s_comp, s_test[k], X_vector=True, Y_vector=True)\n KxtestD_comp = np.kron(KxtestD_comp, B)\n else:\n KDD_comp = kernel(theta, s_comp, s_comp, X_vector=False, Y_vector=False)\n KDD_comp = np.kron(KDD_comp, B)\n KxtestD_comp = kernel(theta, s_comp, s_test[k], X_vector=False, Y_vector=True)\n KxtestD_comp = np.kron(KxtestD_comp, B)\n\n mu_pos_comp = KxtestD_comp.T.dot(np.linalg.inv(KDD_comp+np.kron(noise_prior**2, np.eye(s_comp.shape[0])))).dot(yy_comp_flatten)\n \n Ktest_comp = kernel(theta, s_test[k], s_test[k], X_vector=True, Y_vector=True)\n Ktest_comp = np.kron(Ktest_comp, B)\n sigma_pos_comp = Ktest_comp - KxtestD_comp.T.dot(np.linalg.inv(KDD_comp+np.kron(noise_prior**2, np.eye(s_comp.shape[0])))).dot(KxtestD_comp) + noise_prior**2\n\n err_comp = np.sum((y_test[k]-mu_pos_comp)**2)/v_comp\n standard_error_comp.append(err_comp)\n\n mean_error_comp = np.mean(np.array(standard_error_comp))\n SMSE_POG.append(mean_error_comp)\n\n print('POG SMSE: {}'.format(mean_error_comp))\n\n # DHMP step\n newx = np.concatenate([state, action])\n I = DHMP.dhmp(s_comp, y_comp, newx, theta, keps, noise_prior, xvec=False)\n s_comp = s_comp[I]\n y_comp = y_comp[I]\n m = len(I) + 1\n order.append(m)\n\n temp_s = np.concatenate([state, action]).reshape(1,-1)\n s = np.concatenate([s, temp_s], axis=0)\n s_comp = np.concatenate([s_comp, temp_s], axis=0)\n temp_y = next_state.reshape(1,-1)\n y = np.concatenate([y, temp_y], axis=0)\n y_comp = np.concatenate([y_comp, temp_y], axis=0)\n state = next_state\n\n\nwith open('POG_with_order7.csv', 'w') as ofile:\n for j in range(1,len(SMSE)):\n line = str(SMSE[j]) + ',' + str(SMSE_POG[j]) + ',' + str(order[j]) + '\\n'\n ofile.write(line)\n\nplt.plot(range(1,len(SMSE)), SMSE[1:], label = 'Dense PG')\nplt.plot(range(1,len(SMSE_POG)), SMSE_POG[1:], label = 'POG')\nplt.xlabel(\"Number of Trajectories\")\nplt.ylabel(\"SMSE\")\nplt.legend()\nplt.title('Dense PG vs. POG')\nplt.savefig(\"POG7.png\")\n\nplt.figure()\nplt.plot(range(len(order)), order, label = 'POG')\nplt.plot(range(len(order)), range(len(order)), label = 'Dense PG')\nplt.xlabel(\"Number of Trajectories\")\nplt.ylabel(\"Model Order\")\nplt.legend()\nplt.savefig(\"order7.png\")\n\n\n \n\n\n \n \n\n\n\n\n\n\n\n\n\n\n","repo_name":"wbj218/RL-GP","sub_path":"POG.py","file_name":"POG.py","file_ext":"py","file_size_in_byte":9925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71105492644","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 13 12:09:54 2022\n\n@author: Mahmoud Saeed\n\"\"\"\n\"\"\"\nproblem link :\n\n \nhttps://www.codingninjas.com/codestudio/guided-paths/data-structures-algorithms/\ncontent/118509/offering/1376558\n\"\"\"\n\ndef findTriplets(arr, n, k):\n found = False\n r = []\n arr.sort()\n for i in range(n):\n s = i+1\n e = n-1\n t = k - arr[i]\n while s < e:\n if arr[s] + arr[e] < t:\n s += 1\n elif arr[s] + arr[e] > t:\n e -= 1\n else:\n # f = arr[s]\n # b = arr[e]\n r.append([arr[i] , arr[s] , arr[e]])\n while (s < e) and (arr[s] == arr[s+1]): s += 1\n while (s < e) and (arr[e] == arr[e-1]): e -= 1\n s +=1\n e -= 1\n print(s , e)\n \n \n while (i+1 < n) and (arr[i] == arr[i+1]): i += 1\n print(i)\n return r\n \n \narr = [1 ,2 ,3 ,1, 2 ,3]\nn = len(arr)\nk = 6\nr = findTriplets(arr, n, k)\nprint(r)\n\n\n ","repo_name":"mahmoudsaeed99/CodeStudioProblems-coding-ninjas-","sub_path":"python/3sum.py","file_name":"3sum.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40384992893","text":"import random, asyncio\nfrom .ws_client import websocket_client\nimport logging\nfrom discord_tron_client.classes import log_format\nfrom discord_tron_client.classes.image_manipulation.diffusion import (\n DiffusionPipelineManager,\n)\nfrom discord_tron_client.classes.app_config import AppConfig\nfrom discord_tron_client.classes.api_client import ApiClient\n\nconfig = AppConfig()\nconfig.set_pipeline_manager(DiffusionPipelineManager())\n\n\ndef main():\n try:\n # Detect an expired token.\n logging.info(\"Inspecting auth ticket...\")\n from discord_tron_client.classes.auth import Auth\n\n current_ticket = config.get_auth_ticket()\n auth = Auth(\n config,\n current_ticket[\"access_token\"],\n current_ticket[\"refresh_token\"],\n current_ticket[\"expires_in\"],\n current_ticket[\"issued_at\"],\n )\n auth.get()\n api_client = ApiClient(auth=auth, config=config)\n AppConfig.set_api_client(api_client)\n # Start the WebSocket client in the background\n startup_sequence = []\n from discord_tron_client.classes.message import WebsocketMessage\n\n # Add any startup sequence here\n from discord_tron_client.classes.hardware import HardwareInfo\n from discord_tron_client.classes.image_manipulation.resolution import (\n ResolutionManager,\n )\n\n hardware_info = HardwareInfo()\n machine_info = hardware_info.get_machine_info()\n identifier = HardwareInfo.get_identifier()\n register_data = hardware_info.get_register_data(worker_id=identifier)\n register_data[\"hardware\"] = hardware_info.get_simple_hardware_info()\n register_data[\n \"available_resolutions\"\n ] = ResolutionManager.get_resolutions_with_extra_data()\n hello_world_message = WebsocketMessage(\n message_type=\"hello_world\",\n module_name=\"worker\",\n module_command=\"register\",\n arguments=register_data,\n )\n startup_sequence.append(hello_world_message)\n hardware_info_message = WebsocketMessage(\n message_type=\"hardware_info\",\n module_name=\"system\",\n module_command=\"update\",\n arguments=machine_info,\n )\n startup_sequence.append(hardware_info_message)\n main_loop = asyncio.get_event_loop()\n # Add the main loop to the central Config object.\n AppConfig.set_loop(main_loop)\n main_loop.run_until_complete(\n websocket_client(config, startup_sequence, auth=auth)\n )\n\n # Start the Flask server\n from discord_tron_client.app_factory import create_app\n\n app = create_app()\n app.run()\n except KeyboardInterrupt:\n logging.info(\"Shutting down...\")\n exit(0)\n except Exception as e:\n import traceback\n\n logging.error(f\"Stack trace: {traceback.format_exc()}\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bghira/discord-tron-client","sub_path":"discord_tron_client/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13408322516","text":"import sqlite3\n\nfrom importers.Line import ActivityLine\nimport gestionBD\n\ninsertQueryA = \"INSERT INTO Activite(numero, nom) VALUES (?, ?)\"\ninsertQueryI = \"INSERT INTO Installation(numero, nom, adresse, code_postal, ville, latitude, longitude) VALUES (?, ?, ?, ?, ?, ?, ?)\"\ninsertQueryE = \"INSERT INTO Equipement(numero, nom, numero_installation) VALUES (?, ?, ?)\"\ninsertQueryE_A = \"INSERT INTO equipement_activite(numero_equipement, numero_activite) VALUES (?, ?)\"\n\n\"\"\"\nMethode qui servent a inserer les donnees dans la base\n\"\"\"\n\ndef insertActivity(activity):\n connec = sqlite3.connect('projet.db')\n curs = connec.cursor()\n curs.execute(insertQueryA, (activity.numero, activity.nom))\n gestionBD.deconnection\n\ndef insertInstallation(installation):\n connec = sqlite3.connect('projet.db')\n curs = connec.cursor()\n curs.execute(insertQueryI, (installation.numero, installation.nom, installation.adresse, installation.code_postal, installation.ville, installation.latitude, installation.longitude))\n gestionBD.deconnection\n\ndef insertEquipement(equipement):\n connec = sqlite3.connect('projet.db')\n curs = connec.cursor()\n curs.execute(insertQueryE, (equipement.numero, equipement.nom, equipement.numero_installation))\n gestionBD.deconnection\n \ndef insertEquip_Acti(Equip_Activ):\n connec = sqlite3.connect('projet.db')\n curs = connec.cursor()\n curs.execute(insertQueryE_A, (Equip_Activ.numero_equipement, Equip_Activ.numero_activite))\n gestionBD.deconnection\n \n","repo_name":"DaAbgrall/Tech_Prod_Log_Abgrall_Auzou","sub_path":"importers/Creator.py","file_name":"Creator.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17543011051","text":"# -*- coding:utf-8 -*-\n# Create by 27\n# @Time : 2020/4/2 03:45\n__author__ = '27'\n\n\ndef averager():\n total = 0.0\n count = 0\n average = None\n while True: # 这个无限循环表明,只要调用方不断把值发给这个协程,它就会一直接收值,然后生成结果。仅当调用方在协程上调用 .close() 方法,或者没有对协程的引用而被垃圾回收程序回收时,这个协程才会终止。\n term = yield average # 这里的 yield 表达式用于暂停执行协程,把结果发给调用方;还用于接收调用方后面发给协程的值,恢复无限循环。\n total += term\n count += 1\n average = total / count\n\n\ncoro_avg = averager() # 创建协程对象\nprint(next(coro_avg)) # 调用 next 函数,预激协程。\nprint(coro_avg.send(10)) # 计算移动平均值:多次调用 .send(...) 方法,产出当前的平均值。\nprint(coro_avg.send(30))\nprint(coro_avg.send(5))\n","repo_name":"wnz27/Coding-Daily","sub_path":"content/Python_Generate/python语言总结回顾/协程(流畅的python学习)/16-3.py","file_name":"16-3.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41235328624","text":"from pathlib import Path\nimport os\n\n#Creates a file path using file name, directoy and Home \nfileName = 'MyFile.txt'\nfileDirectory = 'Files/Programming/Python'\\\n\t+ '/Automate the Boring Stuff with Python'\nfilePath = Path.home() / fileDirectory/ fileName;\n\n#Open file with writing privliges\nfile = open(filePath, 'w')\n\n#write to file\nfile.write(\"This work?\")\n\n#close the file\nfile.close()\n\nprint('Process Complete')\n","repo_name":"CarlozSanchez/Python-Practice","sub_path":"Automate_the_Boring_Stuff_with_Python/Chapter9 _ReadWrite.py","file_name":"Chapter9 _ReadWrite.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3129746437","text":"\"\"\"CV Code for gathering data from tests to later be developed\nAllows for switching between video feed modes\nWritten by Brett Hockey\"\"\"\n\nimport cv2\nimport numpy as np\nfrom CVfunctions import init_Camera\n\ndef vidCapture(save, windows, raw):\n \"\"\"Main function which switches between raw and normal feeds\n Is used to save videos to the computer for post-processing\"\"\"\n run = True\n raw = True\n while run:\n # Read the raw Y16 data from the camera\n cap = init_Camera(raw, windows)\n if save:\n fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X') # Unsure what this does atm but may be needed for Rasberry Pi\n if raw:\n out = cv2.VideoWriter('RawVid.mp4', fourcc, 20.0, (640,512))\n else:\n out = cv2.VideoWriter('NormVid.mp4', fourcc, 20.0, (640,512))\n\n while cap.isOpened():\n ret, frame = cap.read()\n if not ret:\n break\n\n if save:\n out.write(frame)\n # Show the frame in the window\n cv2.imshow('Norm', frame)\n \n # Close the script if q is pressed.\n # Note that the delay in cv2.waitKey affects how quickly the video will play on screen.\n if cv2.waitKey(10) & 0xFF == ord('q'):\n run = False\n break\n # Switch from Y16 to normal and vice versa when 's' key is pressed\n if cv2.waitKey(10) & 0xFF == ord('s'):\n raw = not raw\n break\n # Release the video file, and close the GUI.\n cap.release()\n if save:\n out.release()\n\n\n cv2.destroyAllWindows()\n ","repo_name":"bsh75/CV","sub_path":"VideoCapture.py","file_name":"VideoCapture.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30720616274","text":"## Created by Nicolas Farley 03/17/2023\n## Chat GPT Client using OPEN AI's API, Python, and PyQT5.\n\nimport sys\nimport os\nimport openai\nfrom PyQt5.QtGui import QIcon, QPixmap, QTextOption\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QTextEdit, QLabel, QVBoxLayout, QHBoxLayout, QWidget, \\\n QScrollArea, QPushButton\n\n# Change these files to whatever you choose. filename is for API key, and results save a log of the questions, and answers.\nfilename = './chatgptapikey.txt'\ngptresults = './gptresults.txt'\n\n# check if file exists\nif os.path.isfile(filename):\n with open(filename, 'r') as f:\n oapikey = f.read().strip()\nelse:\n # create a new file\n with open(filename, 'w') as f:\n f.write('')\n oapikey = ''\n\nif os.path.isfile(gptresults):\n with open(gptresults, 'r') as f:\n gpttext = f.read().strip()\nelse:\n # create a new file\n with open(gptresults, 'w') as f:\n f.write('')\n gpttext = ''\n\n\nclass SearchAnswer(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n # Create the API key box\n api_key_box = QHBoxLayout()\n api_key_label = QLabel(\"API Key:\")\n self.api_key_textbox = QLineEdit()\n self.api_key_textbox.setText(oapikey)\n api_key_box.addWidget(api_key_label)\n api_key_box.addWidget(self.api_key_textbox)\n\n # Create the search bar\n self.search_bar = QTextEdit()\n search_label = QLabel(\"Ask: \")\n\n # Create the answer box\n self.answer_box = QTextEdit()\n self.answer_box.setText(gpttext)\n self.answer_box.setReadOnly(True)\n self.answer_box.setWordWrapMode(QTextOption.WordWrap)\n answer_label = QLabel(\"Chat:\")\n self.clear_button = QPushButton(\"Clear All Chat Logs\")\n self.clear_button.clicked.connect(self.clear_answer_box)\n # Create the import all chat logs button\n self.import_button = QPushButton(\"Import All Chat Logs\")\n self.import_button.clicked.connect(self.import_chat_logs)\n # Create the label\n verify_label = QLabel(\"Please Verify information is accurate before using!\")\n verify_label.setStyleSheet(\"color: red\")\n\n # Create the vertical layout for the search bar and answer box\n v_layout = QVBoxLayout()\n\n # Add the label to the vertical layout\n v_layout.addWidget(verify_label)\n\n # Add the API key box to the vertical layout\n v_layout.addLayout(api_key_box)\n\n # Create the horizontal layout for the search bar\n h_layout_search = QHBoxLayout()\n h_layout_search.addWidget(search_label)\n h_layout_search.addWidget(self.search_bar)\n v_layout.addLayout(h_layout_search)\n\n # Create the horizontal layout for the answer box\n h_layout_answer = QHBoxLayout()\n h_layout_answer.addWidget(answer_label)\n\n # Create the scroll area for the answer box\n scroll_area = QScrollArea()\n scroll_area.setWidget(self.answer_box)\n scroll_area.setWidgetResizable(True)\n h_layout_answer.addWidget(scroll_area)\n\n # Create the send button\n self.send_button = QPushButton(\"Send\")\n self.send_button.clicked.connect(self.make_request)\n # Add the send button to the vertical layout\n v_layout.addWidget(self.send_button)\n\n # Add the answer box and send button to the vertical layout\n v_layout.addLayout(h_layout_answer)\n # Add the clear button to the vertical layout\n v_layout.addWidget(self.clear_button)\n # Add the import button to the vertical layout\n v_layout.addWidget(self.import_button)\n # Create the central widget and set its layout\n central_widget = QWidget()\n central_widget.setLayout(v_layout)\n self.setCentralWidget(central_widget)\n\n # Set the window title and size\n self.setWindowTitle(\"Virtual Assistant Chat\")\n self.resize(640, 480)\n\n # Create the ChatGPT icon\n icon = QIcon(QPixmap(\"./openai.png\"))\n self.setWindowIcon(icon)\n\n # Autoscroll the answer box to the bottom\n scroll_bar = self.answer_box.verticalScrollBar()\n scroll_bar.setValue(scroll_bar.maximum())\n\n # Define the clear_answer_box method\n def clear_answer_box(self):\n self.answer_box.clear()\n # with open(gptresults, 'w') as f:\n # f.seek(0)\n # f.truncate()\n\n # Define the import_chat_logs method\n def import_chat_logs(self):\n with open(gptresults, 'r') as f:\n gpttext = f.read().strip()\n self.answer_box.setText(gpttext)\n\n def make_request(self):\n # Get the text from the API key text box\n oapikey = self.api_key_textbox.text()\n openai.api_key = f'{oapikey}'\n\n # Write the new API key to the file\n with open(filename, \"r\") as f:\n content = f.read()\n if content != oapikey:\n with open(filename, 'w') as file:\n file.write(oapikey)\n\n # Get the text from the search bar\n search_text = self.search_bar.toPlainText()\n\n message = (search_text)\n messages = [{\"role\": \"user\", \"content\": message}]\n response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=messages\n )\n\n reply = response[\"choices\"][0][\"message\"][\"content\"]\n self.answer_box.append(\"\\n\" + \"YOU: \" + search_text + \"\\n\" + \"ANSWER: \" + reply + \"\\n \\n\")\n with open(f'{gptresults}', 'a') as f:\n f.write(\"YOU: \" + search_text + \"\\n\" + \"ANSWER: \" + reply + \"\\n \\n\")\n\n # Clear the search bar\n self.search_bar.clear()\n\n # Autoscroll the answer box to the bottom\n scroll_bar = self.answer_box.verticalScrollBar()\n scroll_bar.setValue(scroll_bar.maximum())\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = SearchAnswer()\n window.show()\n sys.exit(app.exec_())\n","repo_name":"nicarley/ChatGPTPythonQTClient","sub_path":"MainChat.py","file_name":"MainChat.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"28962289786","text":"# -*- coding: utf-8 -*-\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program. If not, see .\r\n\r\n# This module is based on the character statistics system from PARPG\r\n\r\n\"\"\"This system manages the fields.\r\n\r\n.. module:: fields\r\n :synopsis: Manages the fields\r\n.. moduleauthor:: Karsten Bock \r\n\"\"\"\r\n\r\n\r\n\r\nimport yaml\r\n\r\nfrom fife_rpg.systems import Base\r\nfrom fife_rpg.components.agent import Agent\r\n\r\nfrom pixel_farm.components.field import Field\r\n\r\n\r\nclass Fields(Base):\r\n\r\n \"This system manages the fields.\"\r\n\r\n def __init__(self):\r\n self.map = None\r\n self.layer = None\r\n self.vert_start = None\r\n self.vert_size = None\r\n self.horz_start = None\r\n self.horz_size = None\r\n self.fields = {}\r\n\r\n # testing\r\n self.first = True\r\n field_1 = self.fields[\"field_1\"] = {}\r\n field_1[\"map\"] = \"farm\"\r\n field_1[\"layer\"] = \"fields\"\r\n field_1[\"vert_start\"] = -10\r\n field_1[\"vert_size\"] = 15\r\n field_1[\"horz_start\"] = -8\r\n field_1[\"horz_size\"] = 15\r\n\r\n @classmethod\r\n def register(cls, name=\"fields\"):\r\n \"\"\"Registers the class as a system\r\n\r\n Args:\r\n name: The name under which the class should be registered\r\n\r\n Returns:\r\n True if the system was registered, False if not.\r\n \"\"\"\r\n return super(Fields, cls).register(name)\r\n\r\n def load_config(self, filepath=\"fields.yaml\"):\r\n \"\"\"Loads the config of this system from a yaml file\r\n\r\n Args:\r\n\r\n filepath: The path to the config file\r\n \"\"\"\r\n stream = file(filepath, \"r\")\r\n self.fields = yaml.load(stream)[\"fields\"]\r\n\r\n def setup_field(self, field_name, field_data):\r\n \"\"\"Sets up a single field\r\n\r\n Args:\r\n\r\n field_name: The identifier of the field\r\n\r\n fields: The data of the field\r\n \"\"\"\r\n agent_c_name = Agent.registered_as\r\n field_c_name = Field.registered_as\r\n if self.world.is_identifier_used(\"%s_0_0\" % field_name):\r\n return\r\n\r\n for i in range(field_data[\"vert_size\"]):\r\n identifier = \"%s_border_left_%d\" % (field_name, i)\r\n comp_data = {}\r\n agent_data = comp_data[agent_c_name] = {}\r\n agent_data[\"map\"] = field_data[\"map\"]\r\n agent_data[\"layer\"] = field_data[\"layer\"]\r\n agent_data[\"namespace\"] = \"LPC\"\r\n agent_data[\"gfx\"] = \"grass/soil\"\r\n agent_data[\"rotation\"] = 270\r\n v_pos = field_data[\"vert_start\"] + i\r\n h_pos = field_data[\"horz_start\"] - 1\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"behaviour_type\"] = \"Base\"\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n h_pos = field_data[\"horz_start\"] + field_data[\"horz_size\"]\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"rotation\"] = 90\r\n identifier = \"%s_border_right_%d\" % (field_name, i)\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n\r\n comp_data = {}\r\n agent_data = comp_data[agent_c_name] = {}\r\n agent_data[\"map\"] = field_data[\"map\"]\r\n agent_data[\"layer\"] = field_data[\"layer\"]\r\n agent_data[\"namespace\"] = \"LPC\"\r\n agent_data[\"gfx\"] = \"grass/soil\"\r\n agent_data[\"behaviour_type\"] = \"Base\"\r\n\r\n identifier = \"%s_border_top_right\" % (field_name)\r\n v_pos = field_data[\"vert_start\"] - 1\r\n h_pos = field_data[\"horz_start\"] + field_data[\"horz_size\"]\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"rotation\"] = 45\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n\r\n identifier = \"%s_border_bottom_right\" % (field_name)\r\n v_pos = field_data[\"vert_start\"] + field_data[\"vert_size\"]\r\n h_pos = field_data[\"horz_start\"] + field_data[\"horz_size\"]\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"rotation\"] = 135\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n\r\n identifier = \"%s_border_bottom_left\" % (field_name)\r\n v_pos = field_data[\"vert_start\"] + field_data[\"vert_size\"]\r\n h_pos = field_data[\"horz_start\"] - 1\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"rotation\"] = 225\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n\r\n identifier = \"%s_border_top_left\" % (field_name)\r\n v_pos = field_data[\"vert_start\"] - 1\r\n h_pos = field_data[\"horz_start\"] - 1\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"rotation\"] = 315\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n\r\n for i in range(field_data[\"horz_size\"]):\r\n identifier = \"%s_border_top_%d\" % (field_name, i)\r\n comp_data = {}\r\n agent_data = comp_data[agent_c_name] = {}\r\n agent_data[\"map\"] = field_data[\"map\"]\r\n agent_data[\"layer\"] = field_data[\"layer\"]\r\n agent_data[\"namespace\"] = \"LPC\"\r\n agent_data[\"gfx\"] = \"grass/soil\"\r\n agent_data[\"rotation\"] = 0\r\n v_pos = field_data[\"vert_start\"] - 1\r\n h_pos = field_data[\"horz_start\"] + i\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"behaviour_type\"] = \"Base\"\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n v_pos = field_data[\"vert_start\"] + field_data[\"vert_size\"]\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"rotation\"] = 180\r\n identifier = \"%s_border_bottom_%d\" % (field_name, i)\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n\r\n for i in range(field_data[\"vert_size\"]):\r\n for j in range(field_data[\"horz_size\"]):\r\n identifier = \"%s_%d_%d\" % (field_name, i, j)\r\n if self.world.is_identifier_used(identifier):\r\n continue\r\n comp_data = {}\r\n agent_data = comp_data[agent_c_name] = {}\r\n agent_data[\"map\"] = field_data[\"map\"]\r\n agent_data[\"layer\"] = field_data[\"layer\"]\r\n agent_data[\"namespace\"] = \"LPC\"\r\n agent_data[\"gfx\"] = \"soil:01\"\r\n v_pos = field_data[\"vert_start\"] + i\r\n h_pos = field_data[\"horz_start\"] + j\r\n agent_data[\"position\"] = [h_pos, v_pos]\r\n agent_data[\"behaviour_type\"] = \"Base\"\r\n field_c_data = comp_data[field_c_name] = {}\r\n field_c_data[\"plowed\"] = False\r\n self.world.get_or_create_entity(identifier, comp_data)\r\n self.world.application.update_agents(field_data[\"map\"])\r\n\r\n def step(self, dt):\r\n Base.step(self, dt)\r\n for field_name in self.fields.keys():\r\n field_data = self.fields[field_name]\r\n self.setup_field(field_name, field_data)\r\n for i in range(field_data[\"vert_size\"]):\r\n for j in range(field_data[\"horz_size\"]):\r\n field_c_name = Field.registered_as\r\n agent_c_name = Agent.registered_as\r\n identifier = \"%s_%d_%d\" % (field_name, i, j)\r\n entity = self.world.get_entity(identifier)\r\n field = getattr(entity, field_c_name)\r\n field_agent = getattr(entity, agent_c_name)\r\n try:\r\n is_plowed = field.plowed\r\n except AttributeError:\r\n print(identifier)\r\n is_watered = field.water > 0\r\n if is_plowed:\r\n if is_watered:\r\n field_agent.gfx = \"plowed_soil_watered\"\r\n else:\r\n field_agent.gfx = \"plowed_soil\"\r\n else:\r\n if is_watered:\r\n field_agent.gfx = \"soil_watered\"\r\n else:\r\n field_agent.gfx = \"soil:01\"\r\n","repo_name":"Beliar83/pfp","sub_path":"pixel_farm/systems/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":8697,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"19203284432","text":"# 1. Напишите функцию для транспонирования матрицы\nfrom random import randint\n\n\ndef create_random_matrix(min_=2, max_=5):\n rows = randint(min_, max_)\n cols = randint(min_, max_)\n matrix = [[randint(0, 9) for _ in range(cols)] for _ in range(rows)]\n return matrix\n\n\n# VAR_1 ====================================================\ndef matrix_transposition(matrix: list[list]) -> list[list]:\n # создаем нулевую матрицу, обратную исходной:\n matrix_t = [[0 for i in range(len(matrix))] for j in range(len(matrix[0]))]\n\n # транспонируем в нулевую матрицу исходную:\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n matrix_t[j][i] = matrix[i][j]\n\n return matrix_t\n\n\n# VAR_2 ====================================================\ndef trans_for(matrix):\n temp = []\n for i in range(len(matrix[0])):\n temp.append([])\n for j in range(len(matrix)):\n temp[i].append(matrix[j][i])\n return temp\n\n\n# VAR_3 ====================================================\ndef trans_zip(matrix):\n return list(zip(*matrix))\n\n\ndef print_matrix(matrix):\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n print(matrix[i][j], end=' ')\n print()\n\n\nprint('Исходная матрица:')\nmatrix_init = create_random_matrix()\nprint_matrix(matrix_init)\n\nprint('Транспонированая матрица:')\nmatrix_transpos = matrix_transposition(matrix_init)\nprint_matrix(matrix_transpos)\nprint('---------------------')\ntrans_for = trans_for(matrix_init)\nprint_matrix(trans_for)\nprint('---------------------')\ntrans_zip = trans_zip(matrix_init)\nprint_matrix(trans_zip)\n","repo_name":"yakdd/python_web_seminars","sub_path":"homework_4/hw_task_1.py","file_name":"hw_task_1.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15117962605","text":"import datetime\nimport json\nimport os\nfrom shutil import copyfile\nimport time\nfrom functools import reduce\n\nimport pandas as pd\n\ndef get_variable_names():\n # Define variable names\n variables = [\n 'Bawang Merah',\n 'Bawang Putih',\n 'Beras',\n 'Cabai Merah',\n 'Cabai Rawit',\n 'Daging Ayam',\n 'Daging Sapi',\n 'Gula Pasir',\n 'Minyak Goreng',\n 'Telur Ayam'\n ]\n\n return variables\n\ndef get_food_weights():\n # Load aggregated index weights for each food\n weights_csv_path = os.path.join('input', 'food_weight.csv')\n return pd.read_csv(weights_csv_path)\n\ndef get_province_id_dict():\n # Load geojson data\n province_json_path = os.path.join('input', 'indonesia-prov.json')\n province_data = json.load(open(province_json_path))['features']\n\n # Get the ID for every province\n province_ids = {}\n for province in province_data:\n province_properties = province['properties']\n\n province_name = province_properties['Propinsi'].lower()\n province_ids[province_name] = province_properties['ID']\n\n # Set special ID for national data\n province_ids['semua provinsi'] = -1\n return province_ids\n\ndef get_month_shorthand(month_number):\n shorthand_names = month_dict = {\n '1': 'JAN',\n '2': 'FEB',\n '3': 'MAR',\n '4': 'APR',\n '5': 'MEI',\n '6': 'JUN',\n '7': 'JUL',\n '8': 'AUG',\n '9': 'SEP',\n '10': 'OKT',\n '11': 'NOV',\n '12': 'DES'\n }\n\n return shorthand_names[str(int(month_number))]\n\ndef load_food_data(xlsx_path, food_name):\n # Read data\n df = pd.read_excel(\n xlsx_path\n )\n\n # Rename columns\n df.columns = ['Tanggal', 'Harga', 'Provinsi']\n\n # Remove rows where the value is missing\n df = df.loc[\n df['Harga'] != '-'\n ].reset_index(drop=True)\n df['Harga'] = df['Harga'].astype(float)\n\n # Remove whitespace from province name\n df['Provinsi'] = df['Provinsi'].apply(lambda x: x.strip())\n\n # Split date into three columns\n df['Bulan'] = pd.to_datetime(df['Tanggal'], format='%d/%m/%Y').apply(lambda x: int(x.month))\n df['Tahun'] = pd.to_datetime(df['Tanggal'], format='%d/%m/%Y').apply(lambda x: int(x.year))\n df['Tanggal'] = pd.to_datetime(df['Tanggal'], format='%d/%m/%Y').apply(lambda x: int(x.day))\n\n # Sort values by date and province\n df = df.sort_values(\n by=['Tahun', 'Bulan', 'Tanggal', 'Provinsi']\n )\n\n # Reorder the columns and rename column `Harga` to the variable's name\n df = df[[\n 'Tahun', 'Bulan', 'Tanggal', 'Provinsi', 'Harga'\n ]]\n df = df.rename(columns={'Harga': food_name})\n df = df.reset_index(drop=True)\n\n # Calculate monthly average price\n df = df.groupby(['Tahun', 'Bulan', 'Provinsi']).mean().reset_index()\n df = df.drop('Tanggal', axis=1)\n\n return df\n\ndef load_food_excels(dir_path):\n variables = get_variable_names()\n\n # Load dataframe for each food variable \n food_dfs = []\n for name in variables:\n data_path = os.path.join(dir_path, f'{name}.xlsx')\n food_dfs.append(load_food_data(data_path, name))\n\n return food_dfs\n\ndef merge_food_dfs(food_dfs):\n # Merge the dataframes for each food variable into one\n merged_food_df = reduce(pd.merge, food_dfs)\n return merged_food_df\n\ndef calculate_prev_month(food_df):\n # Calculate previous month number\n food_df['Prev Bulan'] = food_df.apply(\n lambda row: row['Bulan'] - 1 if row['Bulan'] > 1 else 12, axis=1\n )\n \n # Calculate previous month's year\n food_df['Prev Tahun'] = food_df.apply(\n lambda row:row['Tahun'] if row['Prev Bulan'] != 12 else row['Tahun'] - 1,\n axis=1\n )\n\n return food_df\n\ndef calculate_row_food_index(row, weights):\n # Calculate aggregate MtM index for the row\n Pn = 0\n Po = 0\n for food in pd.unique(weights['food']):\n food_weight = weights.loc[weights['food'] == food]['weight'].values[0]\n Pn += row[food + '_x'] * food_weight\n Po += row[food + '_y'] * food_weight\n \n index = Pn / Po * 100\n return index - 100\n\ndef calculate_food_index_col(food_df):\n # Calculate previous month and year for each row\n food_df = calculate_prev_month(food_df)\n\n # Merge data to get previous month's data on the same row\n food_df = pd.merge(\n food_df, food_df,\n left_on=['Prev Tahun', 'Prev Bulan', 'Provinsi'],\n right_on=['Tahun', 'Bulan', 'Provinsi']\n )\n\n # Remove merging variables\n food_df = food_df.drop(\n ['Tahun_y', 'Prev Tahun_x', 'Prev Tahun_y', 'Prev Bulan_x', 'Prev Bulan_y'],\n axis=1\n )\n\n # Calculate aggregative index for each row\n food_index_weight = get_food_weights()\n food_df['index'] = food_df.apply(\n calculate_row_food_index, axis=1, weights=food_index_weight\n )\n\n # Drop previous month's data\n food_names = get_variable_names()\n columns_to_drop = [name + '_y' for name in food_names]\n food_df = food_df.drop(columns_to_drop, axis=1)\n\n # Remove _x suffix from column names\n food_df.columns = [\n col[:-2] if col[-2:] == '_x' else col for col in food_df.columns\n ]\n\n return food_df\n\ndef load_cache_data(cache_path):\n # Load cached data\n return pd.read_csv(cache_path)\n\ndef backup_cache(cache_path, backup_dir):\n backup_path = os.path.join(backup_dir, f'{datetime.datetime.now()}.csv')\n copyfile(cache_path, backup_path)\n\ndef update_cache(new_data, cache_path):\n # Load cache and update with new data\n cache = load_cache_data(cache_path)\n cache = cache.set_index(['Tahun', 'Bulan', 'Provinsi'])\n new_data = new_data.set_index(['Tahun', 'Bulan', 'Provinsi'])\n cache.update(new_data)\n cache = cache.reset_index()\n new_data = new_data.reset_index()\n cache = cache.append(new_data).reset_index(drop=True)\n cache = cache.drop_duplicates()\n cache = cache.sort_values(by=['Tahun', 'Bulan', 'Provinsi'])\n cache['Tahun'] = cache['Tahun'].astype(int)\n cache['Bulan'] = cache['Bulan'].astype(int)\n\n # Save new cache\n cache.to_csv(cache_path, index=False)\n\ndef generate_period_dict(period_data):\n # Create a dictionary of prices for each location\n period_dict = {}\n for location in pd.unique(period_data['Provinsi']):\n location_data = period_data.loc[period_data['Provinsi'] == location]\n\n location_dict = {}\n\n food_names = get_variable_names()\n for name in food_names:\n location_dict[name] = float(location_data[name].values[0])\n \n location_dict['index'] = float(location_data['index'].values[0])\n period_dict[str(location)] = location_dict\n\n return period_dict\n\ndef generate_json_data(cache_path, json_path):\n # Load food data from cache\n data = load_cache_data(cache_path)\n\n # Convert all province names to lowercase and replace with its ID\n province_ids = get_province_id_dict()\n data['Provinsi'] = data['Provinsi'].apply(lambda x : x.lower())\n data['Provinsi'] = data['Provinsi'].replace(province_ids)\n\n # Convert months from numbers into three letter strings\n data['Bulan'] = data['Bulan'].apply(get_month_shorthand)\n\n # Create label for json indexing\n data['label'] = data['Bulan'] + '-' + data['Tahun'].apply(str)\n\n # Create per-province dictionary of prices for each period\n json_dict = {}\n for period in pd.unique(data['label']):\n period_data = data.loc[data['label'] == period].reset_index(drop=True)\n\n period_dict = generate_period_dict(period_data)\n json_dict[period] = period_dict\n\n with open(json_path, 'w') as f:\n json.dump(json_dict, f)\n\ndfs = load_food_excels('update')\nnew_df = merge_food_dfs(dfs)\nnew_df = calculate_food_index_col(new_df)\n\nbackup_cache('update/cache.csv', 'backup/')\nupdate_cache(new_df, 'update/cache.csv')\ngenerate_json_data('update/cache.csv', 'output/data.json')","repo_name":"jonathan-alvaro/dashboard-daya-beli","sub_path":"data/harga_pangan/update_monthly_data.py","file_name":"update_monthly_data.py","file_ext":"py","file_size_in_byte":7915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37602265818","text":"'''\nRLE compression offers a fast way to do efficient on-the-fly compression and \ndecompression of strings. The idea is simple - encoding successive repeated characters by the \nrepitition count and the character. For example, the RLE of \"aaaabcccaa\" is \"4a1b3c2a\".\nThe decoding of \"3e4f2e\" returns \"eeeffffee\"\n\nAssume the string to be encoded consists of letters of the alphabet, with no digits,\nand the string to be decoded is a valid encoding.\n'''\n\ndef runLengthEncode(code):\n ans = \"\"\n curr_char = code[0]\n count = 0\n for i in range(len(code)):\n char = code[i]\n if char == curr_char:\n count+=1\n else:\n ans += str(count) + curr_char\n curr_char = char\n count = 1\n if i == len(code)-1:\n if count > 0:\n ans += str(count)+curr_char\n return ans\nprint(runLengthEncode(\"eeeffffeef\"))\ndef runLengthDecode(code):\n n = 0\n decode = \"\"\n for char in code:\n if ord(char) >= ord(\"a\") and ord(char) <= ord(\"z\"):\n for i in range(n):\n decode+=char\n else:\n n = int(char)\n return decode\n\nprint(runLengthDecode(\"3e4f2e1f\"))\n","repo_name":"RicardoTlatelpa/Algorithms-DataStructures","sub_path":"epi/strings/decoding.py","file_name":"decoding.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15583370440","text":"from deus.activities.solvers.evaluators import EvaluationScriptHandler\r\n\r\n\r\nclass DSScoreEvalScriptHandler(EvaluationScriptHandler):\r\n def __init__(self, info, eval_method, eval_options, data_handler):\r\n super().__init__(info, eval_method)\r\n self.eval_options = eval_options\r\n self.data_handler = data_handler\r\n\r\n def _evaluation_script(self):\r\n if self.eval_method == \"serial\":\r\n script = self._serial_script()\r\n\r\n elif self.eval_method == \"mppool\":\r\n script = self._mppool_script()\r\n\r\n elif self.eval_method == \"mpi\":\r\n assert False, \"not implemented yet.\"\r\n\r\n return script\r\n\r\n # Serial Evaluation\r\n def _serial_script(self):\r\n script = self._serial_script_header()\r\n script += self._2blank_lines\r\n\r\n data_fne = self.data_handler.get_data_fne()\r\n script += super()._data_pickle_reading(data_fne, indent=\"\")\r\n script += self._2blank_lines\r\n\r\n script += self._serial_dsscore_evaluation(indent=\"\")\r\n script += self._2blank_lines\r\n\r\n script += super()._data_pickle_writing(indent=\"\") + \"\\n\"\r\n return script\r\n\r\n def _serial_script_header(self):\r\n atxt = \"import numpy as np\\n\"\r\n atxt += super()._eval_script_header()\r\n return atxt\r\n\r\n def _serial_dsscore_evaluation(self, indent=\"\"):\r\n must_store_g = self.eval_options['store_constraints']\r\n\r\n atxt = indent + \"d_mat = data['in']\\n\"\r\n atxt += indent + \"p_best = np.array([data['p_best']])\" \\\r\n + self._blank_line\r\n\r\n atxt += indent + \"d_shape = np.shape(d_mat)\\n\"\r\n atxt += indent + \"if len(d_shape) == 1:\\n\"\r\n atxt += indent + self._tab + \"d_num, d_dim = 1, d_shape\\n\"\r\n atxt += indent + \"else:\\n\"\r\n atxt += indent + self._tab + \"d_num, d_dim = d_shape\\n\"\r\n\r\n atxt += indent + \"g_list = \" + self.ufunc_name + \"(d_mat, p_best)\\n\"\r\n\r\n atxt += indent + \"score_values = np.ndarray(d_num)\\n\"\r\n atxt += indent + \"for i, g_vec in enumerate(g_list):\\n\"\r\n atxt += indent + self._tab + \"score = 0.0\\n\"\r\n atxt += indent + self._tab + \"if np.all(g_vec >= 0.0):\\n\"\r\n atxt += indent + self._2tabs + \"score = 1.0\\n\"\r\n atxt += indent + self._tab + \"score_values[i] = score\" +\\\r\n self._blank_line\r\n\r\n atxt += indent + \"data['out'] = score_values\\n\"\r\n if must_store_g:\r\n atxt += indent + \"data['g_list'] = g_list\"\r\n\r\n return atxt\r\n\r\n # Multiprocess Pool Evaluation\r\n def _mppool_script(self):\r\n script = self._mppool_script_header()\r\n script += self._2blank_lines\r\n\r\n data_fne = self.data_handler.get_data_fne()\r\n script += super()._data_pickle_reading(data_fne, indent=\"\")\r\n script += self._2blank_lines\r\n\r\n script += self._mppool_global_data()\r\n script += self._2blank_lines\r\n\r\n script += self._mppool_chunks_evaluation_func()\r\n script += self._2blank_lines\r\n\r\n script += self._guard()\r\n script += self._blank_line\r\n\r\n script += self._mppool_chunks_and_pool_creation(indent=self._tab)\r\n script += self._2blank_lines\r\n\r\n script += self._mpool_chunks_collection()\r\n script += self._2blank_lines\r\n\r\n script += super()._data_pickle_writing(indent=self._tab) + \"\\n\"\r\n return script\r\n\r\n def _mppool_script_header(self):\r\n atxt = \"from multiprocessing import Pool, cpu_count\\n\"\r\n atxt += \"import numpy as np\\n\"\r\n atxt += super()._eval_script_header()\r\n return atxt\r\n\r\n def _mppool_global_data(self):\r\n atxt = \"p_best = np.array([data['p_best']])\"\r\n return atxt\r\n\r\n def _mppool_chunks_evaluation_func(self):\r\n must_store_g = self.eval_options['store_constraints']\r\n\r\n atxt = \"def calculate_output_for(ichunk):\\n\"\r\n atxt += \\\r\n self._tab + \"g_list = \" + self.ufunc_name + \"(ichunk, p_best)\\n\" +\\\r\n self._tab + \"ochunk = []\\n\" +\\\r\n self._tab + \"for i, g_vec in enumerate(g_list):\\n\" +\\\r\n self._2tabs + \"score = 0.0\\n\" +\\\r\n self._2tabs + \"if np.all(g_vec >= 0.0):\\n\" +\\\r\n self._3tabs + \"score = 1.0\\n\"\r\n\r\n if must_store_g:\r\n atxt += self._2tabs + \"item = {'score': score, 'g_vec': g_vec}\\n\"\r\n else:\r\n atxt += self._2tabs + \"item = {'score': score}\\n\"\r\n\r\n atxt += self._2tabs + \"ochunk.append(item)\\n\" + \\\r\n self._tab + \"return ochunk\"\r\n\r\n return atxt\r\n\r\n def _mppool_chunks_and_pool_creation(self, indent=\"\"):\r\n n_pool_processes = self.eval_options['pool_size']\r\n\r\n atxt = indent + \"inputs = data['in']\\n\"\r\n if n_pool_processes == -1:\r\n pool_size = \"cpu_count()\"\r\n else:\r\n pool_size = str(n_pool_processes)\r\n atxt += indent + \"n_processes = \" + pool_size + \"\\n\"\r\n\r\n atxt +=\\\r\n indent + \"n_inputs = int(len(inputs))\\n\" +\\\r\n indent + \"chunk_size = int(n_inputs/n_processes)\\n\" +\\\r\n indent + \"input_chunks = [inputs[i*chunk_size:(i+1)*chunk_size] \" \\\r\n \"for i in range(n_processes-1)]\\n\" +\\\r\n indent + \"input_chunks.append(inputs[(n_processes-1)*chunk_size:])\\n\" +\\\r\n indent + \"with Pool(n_processes) as the_pool:\\n\" + \\\r\n indent + self._tab + \"output_chunks = the_pool.map(\" \\\r\n \"calculate_output_for, input_chunks)\"\r\n return atxt\r\n\r\n def _mpool_chunks_collection(self):\r\n must_store_g = self.eval_options['store_constraints']\r\n\r\n atxt = \\\r\n self._tab + \"outputs = []\\n\" +\\\r\n self._tab + \"for chunk in output_chunks:\\n\" +\\\r\n self._2tabs + \"outputs.extend(chunk)\" +\\\r\n self._blank_line + \\\r\n self._tab + \"data['out'] = [item['score'] for item in outputs]\\n\"\r\n\r\n if must_store_g:\r\n atxt += self._tab + \"data['g_list'] = [item['g_vec'] \"\\\r\n \"for item in outputs]\"\r\n else:\r\n atxt += self._tab + \"data['g_list'] = []\"\r\n\r\n return atxt","repo_name":"omega-icl/deus","sub_path":"src/deus/activities/solvers/evaluators/dsscore_script_handler.py","file_name":"dsscore_script_handler.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"26712930704","text":"import time\nimport serial\n\nser = serial.Serial()\n\nser.port = \"/dev/ttyACM1\"\nser.baudrate = 115200\n\nser.open()\n\nlog = open('logs/log.csv', 'w')\nwhile True:\n line = str(time.time()) + \";\" + ser.readline().decode() \n log.write(line)\n print(line, end='')\n","repo_name":"mattebit/chimera-sensors","sub_path":"Tools/serial_logger.py","file_name":"serial_logger.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17238807199","text":"# coding=utf-8\nfrom models import Client\nfrom models.order import ON_THE_WAY\nfrom models.push import OrderPush\n\n__author__ = 'dvpermyakov'\n\n\ndef send_to_courier(order, namespace, courier):\n order.status = ON_THE_WAY\n order.courier = courier.key\n order.put()\n\n client = Client.get(order.client_id)\n text = u\"%s, заказ №%s был послан курьеру.\" % (client.name, order.number)\n OrderPush(text, order, namespace).send()\n","repo_name":"lopatinsky/automation-gae","sub_path":"methods/orders/courier.py","file_name":"courier.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":"70782312806","text":"import cPickle as pickle\nimport fatiando as ft\nimport numpy as np\n\nlog = ft.log.tofile(ft.log.get(), 'invert.log')\nlog.info(ft.log.header())\n\ndata = np.loadtxt('/home/leo/dat/boa6/ftg/rawdata/BOA6_FTG.XYZ', unpack=True)\n# Remove the coordinates from the raw data\ndata[0] -= data[0].min()\ndata[1] -= data[1].min()\narea1 = [7970, 12877, 10650, 17270]\ny, x, scalars = ft.grd.cut(data[0], data[1], data[2:], area1)\n# The x and y components are switched because the coordinates are mixed up\n# (my x is their y)\nheight, z, gyy, gxy, gyz, gxx, gxz, gzz = scalars\n# Remove the coordinates from the cut data\nx -= x.min()\ny -= y.min()\n# Convert altitude into z coordinates\nz *= -1\n\nbounds = (x.min(), x.max(), y.min(), y.max(), -height.max(), -200)\nmesh = ft.msh.ddd.PrismMesh(bounds, (23, 100, 135))\nmesh.carvetopo(x, y, height)\n\ndms = ft.pot.harvester.wrapdata(mesh, x, y, z, gyz=gyz, gzz=gzz)\n\nseeds = ft.pot.harvester.sow(ft.pot.harvester.loadseeds('seeds.json'), mesh,\n mu=0.1, delta=0.0001)\n\nft.vis.figure3d()\nft.vis.prisms([s.get_prism() for s in seeds], 'density')\nft.vis.axes3d(ft.vis.outline3d(bounds), fmt='%.1f', nlabels=3,\n ranges=[b*0.001 for b in bounds])\nft.vis.wall_bottom(bounds)\nft.vis.wall_north(bounds)\nft.vis.show3d()\n\nestimate, goals, misfits = ft.pot.harvester.harvest(dms, seeds)\nmesh.addprop('density', estimate['density'])\npredicted = dms[0].get_predicted()\n\nwith open('result.pickle', 'w') as f:\n pickle.dump(mesh, f)\nwith open('seeds.pickle', 'w') as f:\n pickle.dump([s.get_prism() for s in seeds], f)\noutput = [x, y]\noutput.extend([dm.get_predicted() for dm in dms])\nnp.savetxt('predicted.txt', np.transpose(output))\n\nshape = (100, 100)\nfor dm in dms:\n ft.vis.figure()\n ft.vis.title(\"True: color | Inversion: contour\")\n ft.vis.axis('scaled')\n levels = ft.vis.contourf(y, x, dm.data, shape, 15, interp=True)\n ft.vis.colorbar()\n ft.vis.contour(y, x, dm.get_predicted(), shape, levels, color='k',\n interp=True)\n ft.vis.xlabel('East (km)')\n ft.vis.ylabel('North (km)')\n ft.vis.m2km()\nft.vis.show()\n\nft.vis.figure3d()\nft.vis.prisms([s.get_prism() for s in seeds], 'density')\nft.vis.prisms(mesh, 'density')\n#ft.vis.prisms(ft.msh.ddd.vremove(0, 'density', mesh), 'density')\nft.vis.axes3d(ft.vis.outline3d(bounds), fmt='%.1f', nlabels=3,\n ranges=[b*0.001 for b in bounds])\nft.vis.wall_bottom(bounds)\nft.vis.wall_north(bounds)\nft.vis.show3d()\n","repo_name":"leouieda/gghs2012","sub_path":"results/boa6/invert.py","file_name":"invert.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"25292963100","text":"from flask import Flask, jsonify, g\nimport pymysql\n\n\napp = Flask(__name__)\n\n\n@app.before_request\ndef before_request():\n conn = pymysql.connect(host='127.0.0.1', user='root', passwd='WOSHIWEIWEI44', db='SocialMedia')\n g.db = conn\n\n\n@app.after_request\ndef after_request(response):\n if g.db:\n g.db.close()\n return response\n\n\n@app.route('/follow//', methods=['GET', 'POST'])\ndef follow(follower, followee):\n sql1 = \"select users_id from users where name = %s;\"\n sql2 = \"select users_id from users where name = %s;\"\n sql3 = \"insert follow_relationship values (%s,%s);\"\n c = g.db.cursor()\n c.execute(sql1, (followee,))\n followee_id = c.fetchone()[0]\n c.execute(sql2, (follower,))\n follower_id = c.fetchone()[0]\n\n c.execute(sql3, (follower_id, followee_id))\n g.db.commit()\n return 'successful follow'\n\n\n@app.route('/unfollow//', methods=['GET', 'DELETE'])\ndef unfollow(follower, followee):\n sql1 = \"select users_id from users where name = %s;\"\n sql2 = \"select users_id from users where name = %s;\"\n sql3 = \"delete from follow_relationship where follower=%s and followee=%s;\"\n c = g.db.cursor()\n c.execute(sql1, (followee,))\n followee_id = c.fetchone()[0]\n c.execute(sql2, (follower,))\n follower_id = c.fetchone()[0]\n\n c.execute(sql3, (follower_id, followee_id))\n g.db.commit()\n return 'successful unfollow'\n\n# https://pymysql.readthedocs.io/en/latest/modules/cursors.html\n@app.route('/get_follower/', methods=['GET'])\ndef get_follower(user_name):\n sql1 = \"select users_id from users where name = %s;\"\n sql2 = \"select name from users where users_id in (select follower from follow_relationship where followee = %s);\"\n c = g.db.cursor()\n c.execute(sql1, (user_name,))\n followee_id = c.fetchone()\n\n # print(type(followee_id), followee_id)\n c.execute(sql2, followee_id)\n follower = c.fetchall()\n return jsonify(follower)\n\n\n@app.route('/get_following//', methods=['GET'])\ndef get_following(user_name, page=0): # page number starts from 0\n sql1 = \"select users_id from users where name = %s;\"\n sql2 = \"select name from users where users_id in (select followee from follow_relationship where follower = %s) order by name;\"\n c = g.db.cursor()\n c.execute(sql1, (user_name,))\n follower_id = c.fetchone()\n\n c.execute(sql2, follower_id)\n following = c.fetchall()\n return jsonify(following[page * 20:page * 20 + 20])\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"Isaac51743/SocialMedia","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22573975567","text":"from collections import deque\n\ndx = [0, 0, -1, 1]\ndy = [-1, 1, 0, 0]\n\ndef bfs():\n cnt = 0\n while q:\n cnt += 1\n for m in range(len(q)):\n x, y = q.pop()\n for z in range(4):\n m_x = x+dx[z]\n m_y = y+dy[z]\n if 0 > m_x or m_x >= N or 0 > m_y or m_y >= N:\n continue\n if frame[m_x][m_y] == frame[x][y]+1 and visited[m_x][m_y] != 1:\n q.append((m_x, m_y))\n visited[m_x][m_y] = 1\n return cnt\n\nT = int(input())\n\nfor ts in range(1, T+1):\n print('#%d'%ts, end=' ')\n N = int(input())\n frame = [[] for _ in range(N)]\n maxn = -2147000000\n ans = 2147000000\n \n for i in range(N):\n frame[i] = list(map(int, input().split()))\n\n for i in range(N):\n for j in range(N):\n visited = [[0]*N for _ in range(N)]\n visited[i][j] = 1\n q = deque()\n q.append((i,j))\n temp = bfs()\n print(temp)\n if maxn <= temp and frame[i][j] < ans:\n maxn = temp\n ans = frame[i][j]\n\n print(ans, maxn)","repo_name":"1002ever/algorithm_sol","sub_path":"swexpert/1861_squareroom.py","file_name":"1861_squareroom.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42242572217","text":"import sys\n\ndef constructGraph(input, numberOfNodes, specialEdges):\n \"\"\"Constructs information about the graph.\"\"\"\n\n # Construct the edge discionary skeleton\n edges = {edge:[] for edge in range(numberOfNodes)}\n\n # Dictionary that stores the statuses of the edges (keys are edge tuples)\n edgeStatuses = {}\n\n # The list of special edges\n specialEdgesList = []\n\n for i in range(1, len(input)):\n nodes = input[i].split(\" \")\n\n # Nodes are order 1 to n, this will work better with arrays\n nodeFrom = min(int(nodes[0]), int(nodes[1])) - 1\n nodeTo = max(int(nodes[0]), int(nodes[1])) - 1\n\n # Status code for special edge is 1 and 0 for unexplored edge\n if specialEdges > 0:\n # Add the edge both ways\n edges[nodeFrom].append(nodeTo)\n edges[nodeTo].append(nodeFrom)\n\n # Add it as a special edge to edgeStatuses\n edgeStatuses[(nodeFrom, nodeTo)] = 1\n specialEdgesList.append((nodeFrom, nodeTo))\n specialEdges -= 1\n else:\n # Add the edge both ways\n edges[nodeFrom].append(nodeTo)\n edges[nodeTo].append(nodeFrom)\n\n # Add it as an untraversed edge to edgeStatuses\n edgeStatuses[(nodeFrom, nodeTo)] = 0\n\n return [edges, edgeStatuses, specialEdgesList]\n\ndef dfs(edges, edgeStatuses, currentNode, endNode, exploredNodes):\n \"\"\"DFS seaches the edge dictionary. The status codes are as follows:\n 0: untraversed\n 1: special\n 2: traversed\n 3: special traversed\n \"\"\"\n\n # For all of the neighbours of the current node:\n for i in range(0, len(edges[currentNode])):\n neighbour = edges[currentNode][i]\n edge = (min(currentNode, neighbour), max(currentNode, neighbour))\n status = edgeStatuses[edge]\n\n # Change the status of the edges\n if status == 3: # We can't traverse a traversed special edge\n continue\n elif status == 0: # Change untraversed to traversed\n edgeStatuses[edge] = 2\n status = 2\n elif status == 2: # Change traversed to untraversed\n edgeStatuses[edge] = 0\n status = 0\n elif status == 1: # Change special untraversed to special traversed\n edgeStatuses[edge] = 3\n status = 3\n\n # If we reached the end, return True\n if neighbour == endNode:\n return True\n\n # If the node wasn't explored yet\n if not exploredNodes[neighbour]:\n # Explore it and go down the rabbit hole\n exploredNodes[neighbour] = True\n result = dfs(edges, edgeStatuses, neighbour, endNode, exploredNodes)\n\n # If we found the end, return True\n if result:\n return True\n\n # Roll-back the status that we just changed\n if status == 3: # Un-traverse a special traversed edge\n edgeStatuses[edge] = 1\n elif status == 0: # Change untraversed to traversed\n edgeStatuses[edge] = 2\n elif status == 2: # Change traversed to untraversed\n edgeStatuses[edge] = 0\n\n # If this is a dead end, return False\n return False\n\n# Read from stdin\ninput = []\nfor line in sys.stdin:\n input.append(line)\n\n# Information about the graph\ngraphInfo = input[0].split(\" \")\nnumberOfNodes = int(graphInfo[0])\nnumberOfSpecialEdges = int(graphInfo[2])\n\n# Generated information about the graph\nedgeInformation = constructGraph(input, numberOfNodes, numberOfSpecialEdges)\nedges = edgeInformation[0] # The dictionary of all edges\nedgeStatuses = edgeInformation[1] # The dictionary of the status of edges\nspecialEdges = edgeInformation[2] # A list of all the special edges\n\nfor specialEdge in specialEdges:\n # If it's already added, ignore it\n if edgeStatuses[specialEdge] == 3:\n continue\n\n # Create array so dfs doesn't go in loops\n exploredNodes = [False] * numberOfNodes\n exploredNodes[specialEdge[0]] = True\n\n # Make the current special edge explored, so we have to find a cycle\n edgeStatuses[specialEdge] = 3\n\n\n startNode, endNode = specialEdge[0], specialEdge[1]\n result = dfs(edges, edgeStatuses, startNode, endNode, exploredNodes)\n\n # If it can't be added\n if not result:\n print(-1)\n quit()\n\n# Add all of the unexplored edges to the list (we want to demolish those)\nlist = []\nfor k, v in edgeStatuses.items():\n if v == 0:\n list.append(k)\n\n# Print the edges to demolish (and how many of them are there)\nprint(len(list))\nfor tuple in list:\n print(str(tuple[0] + 1)+\" \"+str(tuple[1] + 1))\n","repo_name":"xiaoxiae/MO-P-68","sub_path":"Praktické/Úloha 1/uloha1.py","file_name":"uloha1.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42384948537","text":"if __name__ == \"__main__\":\n S = input()\n\n # 1로 만들기\n one_count = 0\n one_flag = True\n for i in range(len(S)):\n if int(S[i]) == 0 and one_flag: # 이전 값이 1이고 현재 값이 0인 경우\n one_flag = False # 현재 값이 0을 나타내고 있다.\n else:\n if not one_flag: # 현재 값이 0인 경우\n if int(S[i]) == 1:\n one_count += 1\n one_flag = True\n else:\n continue\n if not one_flag:\n one_count += 1\n # 0으로 만들기\n zero_count = 0\n zero_flag = True\n for i in range(len(S)):\n if int(S[i]) == 1 and zero_flag: # 이전 값이 0이고 현재 값이 1인 경우\n zero_flag = False # 현재 값이 1을 나타내고 있다.\n else:\n if not zero_flag: # 현재 값이 1인 경우\n if int(S[i]) == 0:\n zero_count += 1\n zero_flag = True\n else:\n continue\n if not zero_flag:\n zero_count += 1\n # 더 작은 값을 출력\n print(min(one_count, zero_count))","repo_name":"jjangsungwon/python-for-coding-test","sub_path":"그리디/문자열뒤집기.py","file_name":"문자열뒤집기.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14109037748","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom PIL import Image\nfrom .models import StoreImage\nimport base64\nfrom io import BytesIO\nimport cv2\nimport os\nimport random\nimport shutil\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom keras.preprocessing.image import ImageDataGenerator\nimport xml.etree.ElementTree as ET\nfrom keras import layers\nfrom keras.utils import Sequence\n\n\n# Create your views here.\n\ndef home(request):\n return render(request, \"HomePage/index.html\")\n\ndef is_image(file):\n try:\n with Image.open(file) as img:\n return img.format is not None\n except:\n return False\n\ndef upload_image(request):\n if request.method == 'POST':\n uploaded_file = request.FILES['image']\n\n if uploaded_file:\n try:\n if is_image(uploaded_file):\n # Get the uploaded file's name\n uploaded_file_name = uploaded_file.name\n #return HttpResponse({uploaded_file_name})\n \n # loads and read an image from path to file\n img = cv2.imread('C:/Users/gteja/Documents/Tejal docs/OBU - SEM3/Code/Dataset/4/'+uploaded_file_name)\n gray_image = cv2.cvtColor(img, cv2.IMREAD_GRAYSCALE)\n if img is not None:\n # Create an instance of the Image model and set the image field\n image_instance = StoreImage(image=uploaded_file)\n\n # Save the image instance to the database\n image_instance.save()\n\n #kernel = [(15, 0)] # (Kernel size, Sigma)\n kernel_size = 15\n sigma = 0 \n edges = cv2.GaussianBlur(gray_image, (kernel_size, kernel_size), sigma)\n\n # Apply Canny edge detection\n canny = cv2.Canny(edges, threshold1=50, threshold2=150) # Adjust thresholds as needed\n \n _, ori_img_data = cv2.imencode('.jpg', img)\n ori_img_base64 = base64.b64encode(ori_img_data).decode()\n\n _, canny_img_data = cv2.imencode('.png', canny)\n canny_img_base64 = base64.b64encode(canny_img_data).decode()\n\n # Pass the image URL to the template context\n context1 = {\n 'image_url1': 'data:image/jpg;base64,' + ori_img_base64\n }\n \n # Pass the image URL to the template context\n context2 = {\n 'image_url2': 'data:image/png;base64,' + canny_img_base64\n }\n merged_context = {**context1, **context2}\n #merged_context = {context1}\n\n #model_result = cnnmodel(request)\n\n # Render the template with the image\n return render(request, 'HomePage/upload.html', merged_context)\n #return render(request, 'HomePage/upload.html', context1)\n else:\n return HttpResponse('Failed to process the uploaded image.')\n except Exception as e:\n return HttpResponse(f'Error processing the image: {str(e)}')\n else:\n return HttpResponse('The uploaded file is not an image.')\n else:\n return HttpResponse('No image file was selected.')\n \n return render(request, 'index.html')\n\n\ndef explore_view(request):\n all_images = StoreImage.objects.all()\n return render(request, 'HomePage/explore.html', {'all_images': all_images})\n\nclass cnnmodel(Sequence):\n def get(self, request):\n\n # Retrieve edge-detected images from the database\n all_images = StoreImage.objects.all()\n # Create a list to store the canny field you want to access from each object\n edge_images = []\n\n # Loop through the StoreImage objects and access the specific field\n for obj in all_images:\n canny_field = obj.cannyimg # Replace 'your_field_name' with the actual field name\n edge_images.append(canny_field)\n \n \n # Load annotations from a local file repository (replace with your logic)\n annotation_folder = 'C:/Users/gteja/Documents/Tejal docs/OBU - SEM3/Code/Dataset/label5'\n annotation_files = os.listdir(annotation_folder)\n annotations = {}\n for filename in annotation_files:\n #with open(os.path.join(annotation_folder, filename), 'r') as file:\n # annotations[filename] = file.read()\n\n if filename.endswith('.xml'):\n xml_path = os.path.join(annotation_folder, filename)\n tree = ET.parse(xml_path)\n root = tree.getroot()\n # Parse all elements in the XML file\n annotation = {}\n for elem in root.iter():\n annotation[elem.tag] = elem.text\n annotations[filename] = annotation\n\n\n # Combine edge images and annotations for CNN training (replace with your training logic)\n training_data = []\n for edge_image in edge_images:\n image_path = edge_image.cannyimg.path\n image_filename = os.path.basename(image_path)\n annotation = annotations.get(image_filename, {})\n training_data.append({'image_path': image_path, 'annotation': annotation})\n # Define your CNN model\n \n num_classes = 15\n model = keras.Sequential([\n # Convolutional Block 1\n layers.Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(512, 256, 1)),\n layers.Conv2D(64, (3, 3), activation='relu', padding='same'),\n layers.MaxPooling2D((2, 2)),\n \n # Convolutional Block 2\n layers.Conv2D(128, (3, 3), activation='relu', padding='same'),\n layers.Conv2D(128, (3, 3), activation='relu', padding='same'),\n layers.MaxPooling2D((2, 2)),\n \n # Convolutional Block 3\n layers.Conv2D(256, (3, 3), activation='relu', padding='same'),\n layers.Conv2D(256, (3, 3), activation='relu', padding='same'),\n layers.Conv2D(256, (3, 3), activation='relu', padding='same'),\n layers.MaxPooling2D((2, 2)),\n \n # Flatten and Fully Connected Layers\n layers.Flatten(),\n layers.Dense(256, activation='relu'),\n layers.Dropout(0.5), # Dropout layer for regularization\n layers.Dense(num_classes, activation='softmax') # Replace 'num_classes' with the actual number of classes\n ])\n\n # Compile the model\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n # Summary of the model architecture\n model.summary() \n\n # Evaluate the model on your custom data generator\n test_loss, test_accuracy = model.evaluate(custom_data_generator)\n print(f'Test Loss: {test_loss:.4f}')\n print(f'Test Accuracy: {test_accuracy:.4f}')\n\n # Perform CNN training with the training_data\n \n \n \n \n \n \n return render(request, 'your_template.html', {'training_data': training_data})","repo_name":"TejGitH/TECH7009","sub_path":"Accessible/HomePage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40628214540","text":"#!/usr/bin/env python\n\nimport urllib, urllib2\nimport xml.dom.minidom as minidom\nimport re\n\ndef simbadResolve(name = 'm31'):\n web = 'http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oxpi/SNVA?'\n res = urllib2.urlopen(web + urllib.urlencode([('obj', name)]).split('=')[1]).read()\n\n try:\n xml = minidom.parseString(res)\n\n r = xml.getElementsByTagName('Resolver')[0]\n\n name = r.getElementsByTagName('oname')[0].childNodes[0].nodeValue\n ra = float(r.getElementsByTagName('jradeg')[0].childNodes[0].nodeValue)\n dec = float(r.getElementsByTagName('jdedeg')[0].childNodes[0].nodeValue)\n\n return name, ra, dec\n except:\n return \"\", 0, 0\n\ndef parseSexadecimal(string):\n value = 0\n\n m = (re.search(\"^\\s*([+-])?\\s*(\\d{1,3})\\s+(\\d{1,2})\\s+(\\d{1,2}\\.?\\d*)\\s*$\", string) or\n re.search(\"^\\s*([+-])?\\s*(\\d{1,3})\\:(\\d{1,2})\\:(\\d{1,2}\\.?\\d*)\\s*$\", string))\n if m:\n value = float(m.group(2)) + float(m.group(3))/60 + float(m.group(4))/3600\n\n if m.group(1) == '-':\n value = -value\n\n return value\n\ndef resolve(string = ''):\n \"\"\"\n Resolve the object name (or coordinates string) into proper coordinates on the sky\n \"\"\"\n name = ''\n ra = 0\n dec = 0\n\n m = re.search(\"^\\s*(\\d+\\.?\\d*)\\s+([+-]?\\d+\\.?\\d*)\\s*$\", string)\n if m:\n name = 'degrees'\n ra = float(m.group(1))\n dec = float(m.group(2))\n else:\n m = (re.search(\"^\\s*(\\d{1,2})\\s+(\\d{1,2})\\s+(\\d{1,2}\\.?\\d*)\\s+([+-])?\\s*(\\d{1,3})\\s+(\\d{1,2})\\s+(\\d{1,2}\\.?\\d*)\\s*$\", string) or\n re.search(\"^\\s*(\\d{1,2})\\:(\\d{1,2})\\:(\\d{1,2}\\.?\\d*)\\s+([+-])?\\s*(\\d{1,3})\\:(\\d{1,2})\\:(\\d{1,2}\\.?\\d*)\\s*$\", string))\n if m:\n name = 'sexadecimal'\n ra = (float(m.group(1)) + float(m.group(2))/60 + float(m.group(3))/3600)*15\n dec = (float(m.group(5)) + float(m.group(6))/60 + float(m.group(7))/3600)\n\n if m.group(4) == '-':\n dec = -dec\n else:\n name, ra, dec = simbadResolve(string)\n\n return name, ra, dec\n","repo_name":"karpov-sv/crossmatch","sub_path":"resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"5875824690","text":"n = int(input())\narray = list(map(int, input().split()))\narray.sort()\n\nm = int(input())\nm_array = list(map(int, input().split()))\n\n\ndef binary_search(array, target, start, end):\n\n while start <= end:\n mid = (start + end) // 2\n if array[mid] == target:\n return 1\n elif array[mid] > target:\n end = mid - 1\n else:\n start = mid + 1\n\n return 0\n\nfor idx in m_array:\n print(binary_search(array, idx, 0, n-1))","repo_name":"sejeong-park/Study-Algoritm","sub_path":"이것이 코딩테스트이다&백준/이진탐색/1920-수찾기.py","file_name":"1920-수찾기.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27329494851","text":"for _ in range(int(input())):\n n = int(input())\n s = input()\n t = input()\n count = 0\n temp = []\n flag = 0\n for i in range(n):\n if s[i]!=t[i]:\n count+=1\n temp.append([s[i],t[i]])\n if count>2:\n flag = 1\n break\n if flag==1:\n print(\"No\")\n elif count==2:\n if temp[0][0]==temp[1][0] and temp[0][1]==temp[1][1]:\n print(\"Yes\")\n else:\n print(\"No\")\n else:\n print(\"No\")\n","repo_name":"arjunbangari/Problem-Solving","sub_path":"codeforces/1243/B1.py","file_name":"B1.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"27238839159","text":"from security_engine.engine import SecurityEngineCore\nfrom examples.custom_runtime.context import get_context\nfrom security_engine.handlers.rule.rule_load_handler import GithubRepoRuleLoadHandler\nfrom security_engine.handlers.log.log_handler import StreamLogHandler\nfrom security_engine.models.action import get_action\n\ndef main():\n \n repo_list = [\n {\n 'url': 'https://github.com/RabbyHub/web3-security-rules',\n 'commit_hash': 'a72d4c8b669bf8493d772f5b4097e82db85c4318',\n 'origin': 'common',\n },\n {\n 'url': 'https://github.com/RabbyHub/example-dapp-security-rule',\n 'commit_hash': '928e2c8cb41864c81c2c65a69b000c3761c8306c',\n 'origin': 'http://debank.com',\n },\n {\n 'url': 'https://github.com/RabbyHub/example-common-security-rule',\n 'commit_hash': '73cad96c6f08294e0fd907f0f225c175e9a1c6b5',\n 'origin': 'common',\n },\n ]\n \n engine = SecurityEngineCore()\n rule_load_handler = GithubRepoRuleLoadHandler(repo_list, 'demo token')\n engine.add_handler(rule_load_handler)\n\n # Add default log handler\n log_handler = StreamLogHandler()\n engine.add_handler(log_handler)\n\n engine.load()\n print('load successfuly.')\n\n \n params = [\n {\n \"transaction\": {\n \"chainId\": 42161, \n \"data\": \"0x\", \n \"from\": \"0x34799a3314758b976527f8489e522e835ed8d0d2\", \n \"gas\": \"0x5208\", \n \"gasPrice\": \"0x1dcd65000\", \n \"nonce\": \"0x0\", \n \"to\": \"0x5853ed4f26a3fcea565b3fbc698bb19cdf6deb85\", \n \"value\": \"0x5efe7ec8b12d9c8\"\n },\n \"origin\": \"https://debank.com/\"\n },\n {\n \"text\": '''Please sign to let us verify that you are the owner of this address 0x133ad1b948badb72ea0cfbb5a724b5b77c9b6311.\n[2022-07-20 06:15:02]''',\n \"chain_id\": 1,\n \"origin\": \"https://debank.com/\"\n },\n {\n \"text\": '''Spam text signature''',\n \"chain_id\": 1,\n \"origin\": \"https://debank.com/\"\n },\n {\n \"typed_data\": {\n \"types\": {\n \"EIP712Domain\": [\n {\n \"name\": \"name\",\n \"type\": \"string\"\n },\n {\n \"name\": \"version\",\n \"type\": \"string\"\n },\n {\n \"name\": \"chainId\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"verifyingContract\",\n \"type\": \"address\"\n }\n ],\n \"Permit\": [\n {\n \"name\": \"owner\",\n \"type\": \"address\"\n },\n {\n \"name\": \"spender\",\n \"type\": \"address\"\n },\n {\n \"name\": \"value\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"nonce\",\n \"type\": \"uint256\"\n },\n {\n \"name\": \"deadline\",\n \"type\": \"uint256\"\n }\n ]\n },\n \"domain\": {\n \"name\": \"USD Coin\",\n \"version\": \"2\",\n \"verifyingContract\": \"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\",\n \"chainId\": 1\n },\n \"primaryType\": \"Permit\",\n \"message\": {\n \"owner\": \"0x5853eD4f26A3fceA565b3FBC698bb19cdF6DEB85\",\n \"spender\": \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\",\n \"value\": \"1000000\",\n \"nonce\": 7,\n \"deadline\": 1658834549\n }\n },\n \"origin\": \"https://debank.com/\"\n }\n ] \n\n for param in params:\n action = get_action(param)\n if not action:\n print('invalid param')\n return\n context = get_context(action)\n result = engine.run(context)\n\n print('hits=%s' % result.hits)\n print('.................')\n\nif __name__ == '__main__':\n main()\n","repo_name":"RabbyHub/web3-security-engine-core","sub_path":"examples/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"41447190334","text":"month_dict = {\n '01': 'января', '02': 'февраля', '03': 'марта', '04': 'апреля',\n '05': 'мая', '06': 'июня', '07': 'июля', '08': 'августа',\n '09': 'сентября', '10': 'октября', '11': 'ноября', '12': 'декабря'\n}\n\nweekday_dict = {0: 'Пн', 1: 'Вт', 2: 'Ср', 3: 'Чт', 4: 'Пт', 5: 'Сб', 6: 'Вс'}\n\n\ndef days_word(d):\n if d % 10 == 1 and d % 100 != 11:\n return 'Остался', 'день'\n if 2 <= d <= 4:\n return 'Осталось', 'дня'\n else:\n return 'Осталось', 'дней'\n\n\ndef hours_word(d):\n if d % 10 == 1 and d % 100 != 11:\n return 'Остался', 'час'\n if 2 <= d <= 4:\n return 'Осталось', 'часа'\n else:\n return 'Осталось', 'часов'\n","repo_name":"KosarevPV/zakupka_bot","sub_path":"date_func.py","file_name":"date_func.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39651077510","text":"import numpy as np\r\n\r\ndef OutlierSignalDetection_ZScoreFiltered(y, lag, threshold, influence):\r\n signals = np.zeros(len(y))\r\n filteredY = np.array(y)\r\n avgFilter = np.zeros(len(y))\r\n stdFilter = np.zeros(len(y))\r\n avgFilter[lag - 1] = np.mean(y[0:lag])\r\n stdFilter[lag - 1] = np.std(y[0:lag])\r\n \r\n for i in range(lag, len(y)):\r\n if abs(y[i] - avgFilter[i-1]) > threshold * stdFilter [i-1]:\r\n if y[i] > avgFilter[i-1]:\r\n signals[i] = 1\r\n else:\r\n signals[i] = -1\r\n\r\n filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1]\r\n avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1])\r\n stdFilter[i] = np.std(filteredY[(i-lag+1):i+1])\r\n else:\r\n signals[i] = 0\r\n filteredY[i] = y[i]\r\n avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1])\r\n stdFilter[i] = np.std(filteredY[(i-lag+1):i+1])\r\n\r\n return dict(signals = np.asarray(signals),\r\n avgFilter = np.asarray(avgFilter),\r\n stdFilter = np.asarray(stdFilter))\r\n\r\n\r\n\r\ndef OutlierSignalDetection_RobustZScore(y, threshold):\r\n signals = np.zeros(len(y))\r\n \r\n #need at least 3 points to calculate. Set range to begin at 4.\r\n for i in range(4,len(y)):\r\n idx_window_start = 0\r\n idx_window_end = i\r\n \r\n y_window = y[idx_window_start:idx_window_end]\r\n \r\n #begin outlier calculation\r\n \r\n #calculate median without last value as the last value will be analyzed for outlier.\r\n median = np.median(y_window[:-1])\r\n d = abs(y_window-median)\r\n MAD = np.median(d)\r\n Mi = (0.6745*(y_window-median))/MAD\r\n \r\n #get the last item's score\r\n lastPointScore = Mi[i-1]\r\n \r\n if lastPointScore>threshold:\r\n signals[i-1] = 1\r\n if lastPointScore<-threshold:\r\n signals[i-1] = -1\r\n \r\n if 1==0:\r\n print(i+1,idx_window_start,idx_window_end,median,y[i],Mi[i-1])\r\n print(y_window)\r\n print(Mi) \r\n print(signals) \r\n #median = np.median(filteredY[(i-lag+1):i+1])\r\n\r\n return signals\r\n\r\n\r\n\r\ndef OutlierSignalDetection_RobustZScore_NOWINDOW(y, threshold):\r\n y_window = y\r\n median = np.median(y_window)\r\n\r\n d = abs(y_window-median)\r\n MAD = np.median(d)\r\n\r\n Mi = (0.6745*(y_window-median))/MAD\r\n\r\n signals = np.zeros(len(y_window))\r\n for i, v in enumerate(Mi):\r\n if v>=threshold:\r\n signals[i]=1\r\n if v<=-threshold:\r\n signals[i]=-1\r\n \r\n return signals\r\n","repo_name":"hackdeploy/changedetector","sub_path":"SignificantChangeDetection/ChangeDetector/Detectors.py","file_name":"Detectors.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17664332824","text":"import os\nimport unittest\nfrom unittest.mock import patch, ANY\n\nfrom orangecontrib.text.corpus import get_sample_corpora_dir\nfrom orangecontrib.text.widgets.utils import FileWidget, QFileDialog\nfrom orangewidget.tests.base import GuiTest\n\n\nclass TestFileWidget(GuiTest):\n @patch.object(QFileDialog, \"getOpenFileName\", return_value=(\"path\", \"\"))\n def test_start_dir(self, mock):\n file_widget = FileWidget(\n recent_files=[],\n icon_size=(16, 16),\n dialog_title=\"Open Orange Document Corpus\",\n reload_label=\"Reload\",\n browse_label=\"Browse\",\n allow_empty=False,\n minimal_width=250,\n )\n file_widget.browse()\n mock.assert_called_with(ANY, ANY, \"~/\", ANY)\n\n file_widget.recent_files = [\"book-excerpts.tab\"]\n file_widget.browse()\n mock.assert_called_with(ANY, ANY, get_sample_corpora_dir(), ANY)\n\n cur_dir = os.path.dirname(__file__)\n file_widget.recent_files.insert(0, os.path.join(cur_dir, \"file.tab\"))\n file_widget.browse()\n mock.assert_called_with(ANY, ANY, cur_dir, ANY)\n\n # dir doesn't exit case\n file_widget.recent_files.insert(0, \"/non/exiting/dir/file.tab\")\n file_widget.browse()\n mock.assert_called_with(ANY, ANY, \"~/\", ANY)\n\n # if browse have start_dir argument use this path\n file_widget.browse(\"/sample/path\")\n mock.assert_called_with(ANY, ANY, \"/sample/path\", ANY)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"biolab/orange3-text","sub_path":"orangecontrib/text/widgets/utils/tests/test_widgets.py","file_name":"test_widgets.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"52"} +{"seq_id":"32475704166","text":"import mysql.connector\nimport tweepy \nimport json\nimport wget\nimport os\nimport io\nimport shutil\nimport google.cloud\nimport PIL.Image as Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nfrom google.cloud import vision\nfrom google.cloud.vision import types\n\n#Twitter API credentials\n\nconsumer_key = \"Enter your consumer key\"\nconsumer_secret = \"Enter your consumer secret\"\naccess_key = \"Enter your access_key\"\naccess_secret = \"Enter your access_secret\"\n\n\nusername=input(\"Please input your mysql username: \")\npassword =input(\"Please input your mysql password: \")\n\n\ndef connect_to_mysql():\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=username,\n passwd=password,\n database=\"twitterdb\"\n )\n return mydb\n\ndef create_tables():\n sql_table_images = \"CREATE TABLE images_data (image_id varchar(30) NOT NULL, twitter_user varchar(255) NOT NULL, image_url varchar(255) NOT NULL, image_name varchar(255) NOT NULL, PRIMARY KEY (image_id), UNIQUE (image_id))\"\n sql_table_tags = \"CREATE TABLE tags_data (tag_id varchar(30) NOT NULL, tag_content varchar(30) NOT NULL, image_id varchar(30) NOT NULL, PRIMARY KEY (tag_id), FOREIGN KEY (image_id) REFERENCES images_data(image_id), UNIQUE (tag_id))\"\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n \n mycursor.execute(\"SHOW TABLES\")\n myresult = mycursor.fetchall()\n for result in myresult:\n if result[0] == \"images_data\" or \"tags_data\":\n print(\"Tables already exist!\")\n rebuild = input(\"Do you want to rebuild the tables? y/n \")\n if (rebuild == \"y\" or rebuild ==\"Y\" or rebuild == \"yes\"):\n mycursor.execute(\"DROP TABLE tags_data\")\n mycursor.execute(\"DROP TABLE images_data\")\n break\n else:\n return\n \n\n mycursor.execute(sql_table_images)\n mycursor.execute(sql_table_tags)\n \n mycursor.execute(\"DESC images_data\")\n myresult = mycursor.fetchall()\n print(\"image_data table structure:\")\n for result in myresult:\n print(result)\n\n\n mycursor.execute(\"DESC tags_data\")\n myresult = mycursor.fetchall()\n print(\"tags_data table structure:\")\n for result in myresult:\n print(result)\n\ndef get_photo_tweets(screen_name):\n \n #Connect to Database\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n \n #based on twitter api sample\n \n #Twitter only allows access to a users most recent 3240 tweets with this method\n #authorize twitter, initialize tweepy\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n api = tweepy.API(auth)\n #initialize a list to hold all the tweepy Tweets\n alltweets = [] \n #make initial request for most recent tweets (200 is the maximum allowed count)\n \n \n new_tweets = api.user_timeline(screen_name = screen_name,count=30)\n #save most recent tweets\n alltweets.extend(new_tweets)\n #save the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n \n #keep grabbing tweets until there are no tweets left to grab\n if len(new_tweets) == 0:\n return\n \n while len(new_tweets) > 0:\n #all subsiquent requests use the max_id param to prevent duplicates\n new_tweets = api.user_timeline(screen_name = screen_name,count=10,max_id=oldest)\n #save most recent tweets\n alltweets.extend(new_tweets)\n #update the id of the oldest tweet less one\n oldest = alltweets[-1].id - 1\n if(len(alltweets) > 15):\n break\n \n #save the photo tweets into photos list as url\n photos=[]\n \n #use twitter media object under tweet entities (media array), and the media_url parameter from the media array\n #Based on: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/entities-object.html#entitiesobject\n #append media_url to the photos list\n for tweet in alltweets:\n tmp = tweet.entities.get('media', [])\n if(len(tmp) > 0):\n photos.append(tmp[0]['media_url'])\n \n #print(photos)\n \n # sql format for images_data\n sql_image = \"INSERT INTO images_data (image_id, twitter_user, image_url, image_name) VALUES (%s, %s, %s, %s)\"\n \n \n #download photo with urls in the photos list using wget module\n #to the photo_folder\n mypath = os.getcwd()\n mypath = mypath+\"/photo_folder\"\n if not os.path.isdir(mypath):\n os.makedirs(mypath)\n #try:\n mycursor.execute(\"SELECT * FROM images_data\")\n image_id = mycursor.rowcount\n \n \n if image_id < 0:\n image_id = 0\n \n images_file = {}\n \n for photo in photos:\n wget.download(photo, out=mypath)\n for file in os.listdir(\"photo_folder\"):\n if file not in images_file:\n im = file\n images_file[file] = 1\n image_id = image_id + 1\n mycursor.execute(sql_image, (str(image_id), screen_name, photo, im))\n mydb.commit()\n #except:\n # print(\"Image data have been recorded.\")\n mydb.close()\n \n \n \ndef detect_labels():\n #Connect to Database\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n \n #load google credentials.json to os environment\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]= \"mystical-axiom-216914-4e58d00e5897.json\"\n client = vision.ImageAnnotatorClient()\n\n \n mypath = os.getcwd()+\"/photo_folder\"\n imgs = os.listdir(mypath)\n count = 1\n for img in imgs:\n #based on google vision label use sample:\n #https://cloud.google.com/vision/docs/detecting-labels#vision-label-detection-python\n #open the img and add labels of the img\n file_name = os.path.join(mypath, img)\n #'img's path')\n with io.open(file_name, 'rb') as image_file:\n content = image_file.read()\n image = types.Image(content=content)\n response = client.label_detection(image=image)\n labels = response.label_annotations\n \n #add label.description for every label to a description list \n #and convert to a string(ready to text on img)\n description =[]\n for label in labels:\n description.append(label.description)\n #sep = \"\\n\", change line for every label\n sql_tags = \"INSERT INTO tags_data (tag_id, tag_content, image_id) VALUES (%s, %s, %s)\"\n \n #print(img)\n #sql = \"SELECT image_id FROM images_data WHERE image_name = {}\".format(img)\n #ima = str(img)\n #print(ima)\n #mycursor.execute(sql)\n \n mycursor.execute(\"SELECT image_id FROM images_data WHERE image_name = '\"+img+\"'\")\n #print(\"****\")\n myresult = mycursor.fetchall()\n image_ids = []\n for result in myresult:\n image_ids.append(int(result[0]))\n image_ids.sort()\n\n img_id = str(image_ids[-1])\n \n #mg_id = mycursor.fetchone()\n #print(\"*****\"+img_id)\n mycursor.execute(\"SELECT * FROM tags_data\")\n t_id = mycursor.rowcount\n if t_id < 0:\n t_id = 0\n for tag in description:\n t_id = t_id + 1\n ta_id = str(t_id)\n mycursor.execute(sql_tags, (ta_id, tag, img_id))\n mydb.commit()\n \n string=\"\\n\".join(description)\n \n \n #Usign pillow module, draw text on imgs and save them with %d.jpg format\n #pillow sample from pillow draw module tutorial\"https://pillow.readthedocs.io/en/3.0.x/reference/ImageDraw.html\"\n #define font of the text\n font = ImageFont.truetype('arial.ttf', 50)\n #define position to start drawing text\n (x, y) = (0, 0)\n im = Image.open(file_name).convert('RGB')\n draw = ImageDraw.Draw(im)\n #draw string text on the img, with rgb color (255,255,0,0)\n draw.text((x, y), string, (255,255,0,0), font = font)\n im.save('photo_folder/'+str('%d'%count)+'.jpg', 'JPEG')\n count+=1\n mydb.close()\n \ndef img_to_video():\n \n os.system('ffmpeg -r 1/3 -f image2 -i photo_folder\\%d.jpg -s 1200x900 photos.mp4')\n #ffmpeg parameters:\n #-r pics per sec, here is 1 pic per 3 secs\n #-f input format\n #-i input source\n #-s size 1200x900\n #output to a photos.mp4\n\ndef show_database(twitter_name, show_db=False):\n if show_db == True or \"y\" or \"Y\" or \"Yes\" or \"yes\" or \"YES\":\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n ## show images_data\n print(\"Data in images_data Table: \"+\"\\n\")\n mycursor.execute(\"SELECT * FROM images_data WHERE twitter_user= '\"+twitter_name+\"'\")\n\n myresult = mycursor.fetchall()\n #print(myresult)\n for result in myresult:\n print(result)\n\n\n\n mycursor.execute(\"SELECT image_id FROM images_data WHERE twitter_user= '\"+twitter_name+\"'\")\n\n myresult = mycursor.fetchall()\n #print(myresult)\n image_ids = []\n for result in myresult:\n image_ids.append(result[0])\n\n #print(image_ids)\n print(\"\\n\"+\"Data in tags_data Table: \"+\"\\n\")\n for im_id in image_ids:\n mycursor.execute(\"SELECT * FROM tags_data WHERE image_id= '\"+im_id+\"'\")\n print(\"image_id = \"+ im_id+\"\\n\")\n myresult = mycursor.fetchall()\n for result in myresult:\n print(result)\n print(\"\\n\")\n mydb.close()\n \ndef search_api():\n search = input(\"Do you want to search by tag or twitter_user? tag/user \")\n\n if search == \"tag\":\n tag_name = input(\"Please input the tag you want to find: \")\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n ## show images_data\n\n mycursor.execute(\"SELECT image_id FROM tags_data WHERE tag_content= '\"+tag_name+\"'\")\n\n myresult = mycursor.fetchall()\n if len(myresult) == 0:\n print(\"No image with this tag found.\")\n else:\n print(\"\\n\"+\"Images with this tag: \"+\"\\n\")\n image_ids = []\n for result in myresult:\n image_ids.append(result[0])\n for image in image_ids:\n mycursor.execute(\"SELECT * FROM images_data WHERE image_id= '\"+image+\"'\")\n print(\"image_id = \"+ image+\"\\n\")\n myresult = mycursor.fetchall()\n for result in myresult:\n print(result)\n print(\"\\n\")\n elif search == \"user\" or \"twitter_user\" or \"User\":\n user_name = input(\"Please input the twitter_user you want to find: \")\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n ## show images_data\n\n mycursor.execute(\"SELECT * FROM images_data WHERE twitter_user= '\"+user_name+\"'\")\n\n\n myresult = mycursor.fetchall()\n if len(myresult) == 0:\n print(\"No image of this user found.\")\n else:\n print(\"\\n\"+\"Images of this user: \"+\"\\n\")\n for result in myresult:\n print(result)\n mydb.close()\n \ndef show_database_info():\n mydb = connect_to_mysql()\n mycursor = mydb.cursor(buffered=True)\n ### For images_data Table:\n #### 1. Number of all images\n mycursor.execute(\"SELECT * FROM images_data\")\n image_number = mycursor.rowcount\n print(str(image_number)+\" images in the images_data Table.\"+\"\\n\") \n\n #### 2. Number of images of every twitter_user\n user_uni = set()\n mycursor.execute(\"SELECT twitter_user FROM images_data\")\n\n myresult = mycursor.fetchall()\n\n for result in myresult:\n user_uni.add(result)\n\n for user_name in user_uni:\n mycursor.execute(\"SELECT * FROM images_data WHERE twitter_user= '\"+user_name[0]+\"'\")\n image_number_user = mycursor.rowcount\n print(str(image_number_user)+\" images in the images_data Table\"+\"from \"+user_name[0]+\".\\n\") \n\n ### For tags_data Table:\n #### 1. Number of all tags\n mycursor.execute(\"SELECT tag_content FROM tags_data\")\n tag_number = mycursor.rowcount\n print(str(tag_number)+\" tags in the tags_data Table.\"+\"\\n\") \n\n #### 2. The most frequent tags\n\n max_frequent_tag = {}\n tags=mycursor.fetchall()\n\n for tag in tags:\n max_frequent_tag[tag[0]] = max_frequent_tag.get(tag[0], 0) + 1\n #print(max_frequent_tag)\n tags_sorted=sorted(max_frequent_tag.items(), key=lambda x: x[1], reverse=True)\n print(\"The most frequent tag is: \" + tags_sorted[0][0]+\". It is on \"+str(tags_sorted[0][1])+\" images.\")\n\n\nif __name__ == '__main__':\n #get photos from twitter account with twitter api\n \n create_tables()\n twitter_name = input(\"Please input the twitter name: \")\n \n twitter_name = \"@\"+twitter_name\n try:\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n api = tweepy.API(auth)\n api.get_user(screen_name=twitter_name)\n if \"photo_folder\" in os.listdir():\n shutil.rmtree(\"photo_folder\")\n get_photo_tweets(twitter_name)\n try:\n detect_labels()\n if 'photos.mp4' in os.listdir():\n os.remove(\"photos.mp4\")\n img_to_video()\n os.system('photos.mp4')\n print(\"\\n\")\n show_db=input(\"Do you want to show database of this twitter user? y/n \")\n show_database(twitter_name, show_db)\n search_api() \n show_database_info()\n except:\n print(\"No image tweets found or has error.\")\n\n except:\n print(\"User Not Found or has error.\")\n\n \n\n","repo_name":"helibu/twitter-user-post-api","sub_path":"database to store user info/mysql/mysql_twitterapi_He_Li.py","file_name":"mysql_twitterapi_He_Li.py","file_ext":"py","file_size_in_byte":13672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73810712166","text":"import os, re, json, argparse, sys, jinja2\nfrom subprocess import Popen, PIPE\nfrom pathlib import Path\n\n\ndef trail(filename):\n return filename[:-2]\n\n\ndef get_file_library(filename):\n p = Popen(('find', '.', '-name', trail(filename) + '*', '-printf', '%h'), stdout=PIPE)\n output = p.communicate()[0] \n return output.decode(\"utf-8\")[2:] \n\n\ndef get_deps(directory, filename, dependencies_file):\n text = \"\"\n with open(dependencies_file, \"r\") as rf:\n text = rf.read()\n \n pattern = \"{}\\.o :(.*)\".format(filename[:-4])\n matches = re.findall(pattern, text)\n if matches:\n deps = matches[0].strip().split(\" \")\n deps = list(map(get_file_library, deps))\n\n dir_dep = set(deps)\n directory[\"deps\"] = dir_dep\n \n\ndef parse_directory(dictionary, directory, dependencies, parent=None):\n if parent is not None:\n path = parent + \"/\" + directory[\"name\"]\n else:\n path = directory[\"name\"]\n dictionary.append({\"name\": directory[\"name\"], \"path\": path, \"files\": [], \"deps\": set(), \"directories\": []})\n current_directory = dictionary[-1]\n \n for content in directory[\"contents\"]:\n if content[\"type\"] == \"file\" and content[\"name\"].endswith((\"f90\", \"inc\", \"h\")):\n current_directory[\"files\"].append(content[\"name\"])\n get_deps(current_directory, content[\"name\"], dependencies)\n \n if content[\"type\"] == \"directory\":\n current_directory[\"directories\"].append(content[\"name\"])\n parse_directory(dictionary, content, dependencies, parent=current_directory[\"name\"])\n\n\ndef print_cmake(struc):\n templateLoader = jinja2.FileSystemLoader(searchpath=\"./\")\n templateEnv = jinja2.Environment(loader=templateLoader, trim_blocks=True, lstrip_blocks=True)\n TEMPLATE_FILE = \"cmake.template\"\n template = templateEnv.get_template(TEMPLATE_FILE)\n\n for lib in struct:\n fullpath = os.path.join(lib[\"path\"], \"CMakeLists.txt\")\n\n outputText = template.render(\n lib_name=lib[\"name\"],\n sources=lib[\"files\"],\n subdirectories=lib[\"directories\"],\n link_libraries=[ x for x in lib[\"deps\"] if x != lib[\"name\"]]\n )\n\n filename = Path(fullpath)\n filename.touch(exist_ok=True)\n with open(filename, \"w\") as f:\n print(\"Escribiendo {}\".format(fullpath))\n f.write(outputText)\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--deps', required=True, help='Archivo con listas de dependencias generadas con fort_depend.py')\n parser.add_argument('--tree', required=True, help='Árbol de directorios y archivos, generado con tree -J')\n\n args = parser.parse_args()\n\n struct = []\n with open(args.tree) as tree:\n data = json.load(tree)\n\n for d in data[0][\"contents\"]:\n if d[\"type\"] == \"directory\":\n parse_directory(struct, d, args.deps)\n\n print_cmake(struct)\n","repo_name":"jerebenitez/IFE-simpact-openfoam","sub_path":"src/reqs.py","file_name":"reqs.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29922149127","text":"from typing import List\nfrom tqdm import tqdm\nimport os\nimport shutil\n\n\ndef move2results(out_root, to_root: List, end: str, split_tate=None):\n if split_tate is None:\n split_tate = [0.7, 0.3]\n\n train_len = int(len(os.listdir(out_root)) * split_tate[0])\n val_end_len = int(len(os.listdir(out_root)))\n # test_end_len = int(len(os.listdir(out_root)))\n for i in tqdm(range(1, train_len + 1)):\n out_path = os.path.join(out_root, str(i) + end)\n shutil.copy(out_path, to_root[0])\n for i in tqdm(range(train_len + 1, val_end_len + 1)):\n out_path = os.path.join(out_root, str(i) + end)\n shutil.copy(out_path, to_root[1])\n # for i in tqdm(range(val_end_len + 1, test_end_len + 1)):\n # out_path = os.path.join(out_root, str(i) + end)\n # shutil.copy(out_path, to_root[2])\n\n\nimgs_out_root = 'test_data\\\\img_results'\nimgs_to_root = ['test_data/data/train/images/', 'test_data/data/val/images/', 'test_data/data/test/images/']\n\nlabels_out_root = 'test_data\\\\label_results'\nlabels_to_root = ['test_data/data/train/masks/', 'test_data/data/val/masks/', 'test_data/data/test/masks/']\n\nmove2results(imgs_out_root, imgs_to_root, end=str('.jpg'))\nmove2results(labels_out_root, labels_to_root, end=str('.png'))\n","repo_name":"ABCnutter/Segmentation_Web","sub_path":"utils/process/copydata.py","file_name":"copydata.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30324422489","text":"'''\n 프로그래머스 : 가장 가까운 같은 글자\n https://school.programmers.co.kr/tryouts/85914/challenges?language=python3\n'''\n\ndef solution(s):\n answer = []\n word_dict = {}\n \n for i in range(len(s)):\n if s[i] not in word_dict:\n answer.append(-1)\n else:\n answer.append(i-word_dict[s[i]])\n word_dict[s[i]] = i # 가까운 것으로 갱신\n \n return answer\n\ns = \"banana\"\nprint(solution(s))\n# [-1, -1, -1, 2, 2, 2]\n\n'''\nGolang\n\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nfunc solution(s string) []int {\n var answer []int\n word_dict := make(map[rune]int)\n\n for i, word := range s {\n if idx, w := word_dict[word]; !w {\n answer = append(answer, -1)\n } else {\n answer = append(answer, i - idx)\n }\n word_dict[word] = i\n }\n return answer\n}\n\nfunc main() {\n\ts := \"banana\"\n result := solution(s)\n fmt.Println(result)\n}\n\n'''","repo_name":"kimkihyun1/TIL","sub_path":"CodingTest/2309/230928.py","file_name":"230928.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1616898505","text":"#!/usr/bin/python3\n\nimport re\n\ndef getPattern(padrao):\n result = \"\"\n for p in padrao.split(\" \"):\n result += rf\"(\\w+) \\w+ {p}\\n\"\n return result\n\ndef match(txt,padrao):\n solution = []\n pattern = getPattern(padrao)\n for res in re.findall(pattern,txt):\n solution.append(\" \".join(res))\n return solution\n","repo_name":"alves-luis/ipln-practical_assignment","sub_path":"tp3/rafa.py","file_name":"rafa.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30324395589","text":"'''\n 프로그래머스 : 로또의 최고 순위와 최저 순위\n https://school.programmers.co.kr/tryouts/85904/challenges?language=python3\n'''\n\ndef solution(lottos, win_nums):\n answer = []\n count = 0\n if sum(lottos) == 0:\n return [1, 6]\n for i in lottos:\n if i in win_nums:\n count += 1\n zero_num = lottos.count(0)\n rank = {6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6, 0: 6}\n answer = [rank[count+zero_num], rank[count]]\n \n return answer\n\nlottos = [44, 1, 0, 0, 31, 25]\nwin_nums = [31, 10, 45, 1, 6, 19]\nprint(solution(lottos, win_nums))\n# [3, 5]\n\n'''\nGolang\n\npackage main\n\nimport \"fmt\"\n\nfunc solution(lottos []int, winNums []int) []int {\n answer := make([]int, 2)\n count := 0\n\n // 모든 로또 번호가 0이면 [1, 6]을 반환\n if sum(lottos) == 0 {\n return []int{1, 6}\n }\n\n for _, num := range lottos {\n if contains(winNums, num) {\n count++\n }\n }\n\n zeroCount := countZero(lottos)\n rank := map[int]int{6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6, 0: 6}\n\n answer[0] = rank[count+zeroCount]\n answer[1] = rank[count]\n\n return answer\n}\n\nfunc sum(nums []int) int {\n total := 0\n for _, num := range nums {\n total += num\n }\n return total\n}\n\nfunc contains(arr []int, target int) bool {\n for _, num := range arr {\n if num == target {\n return true\n }\n }\n return false\n}\n\nfunc countZero(nums []int) int {\n count := 0\n for _, num := range nums {\n if num == 0 {\n count++\n }\n }\n return count\n}\n\nfunc main() {\n lottos := []int{44, 1, 0, 0, 31, 25}\n winNums := []int{31, 10, 45, 1, 6, 19}\n result := solution(lottos, winNums)\n fmt.Println(result) // 출력 결과: [3 5]\n}\n\n'''","repo_name":"kimkihyun1/TIL","sub_path":"CodingTest/2309/230914.py","file_name":"230914.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70257904804","text":"# %%\nimport csv\n\nreadings = []\nwith open('day7-data.csv') as csvfile:\n csvreader = csv.reader(csvfile)\n readings = list(csvreader)[0]\n\nreadings = [int(i) for i in readings] \n\ntest_input = [16,1,2,0,4,2,7,1,2,14]\n# %%\nres = {}\nfor i in range(0,max(readings)):\n running_total = 0\n for j in readings:\n running_total += abs(j - i)\n res[i] = running_total\n# %%\n","repo_name":"ldmichae/AdventOfCode-2021","sub_path":"Day 7/Day7_Part1.py","file_name":"Day7_Part1.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71670655844","text":"import json\nfrom pathlib import Path\nfrom pymongo import UpdateOne\nimport pytest\nfrom moncoll2 import MC, BulkItemNotIdError, to_bulklist\n\n\n@pytest.fixture()\ndef settings():\n settings_path = Path.home() / '.config/mongos/test_settings.json'\n if settings_path.exists():\n return json.loads(settings_path.read_text())\n else:\n return {\n \"username\": \"testuser\",\n \"password\": \"testpass\",\n \"host\": \"localhost\",\n \"port\": 12345,\n \"coll_name\": \"test_collection\",\n \"db_name\": \"test_db\"\n }\n\n\ndef test_hard_1(settings):\n with MC(settings) as coll:\n assert coll.full_name == 'test_db.test_collection'\n coll.insert_one({\"a\": 1})\n res = coll.find_one()\n assert res['a'] == 1\n coll.drop()\n\n\ndef test_hard_1_2(settings):\n with MC(settings) as coll:\n assert coll.full_name == 'test_db.test_collection'\n coll.insert_one({\"a\": 1})\n res = coll.find_one()\n assert res['a'] == 1\n with MC(settings) as coll:\n assert coll.full_name == 'test_db.test_collection'\n coll.insert_one({\"b\": 2})\n res = coll.find_one({'b': {'$exists': True}})\n assert res['b'] == 2\n coll.drop()\n\n\ndef test_hard_2(settings):\n li = to_bulklist([\n {\"name\": \"Karin\", \"gender\": \"female\"},\n {\"name\": \"Decker\", \"gender\": \"male\"}\n ], 'name')\n with MC(settings) as coll:\n res = coll.bulk_write(li)\n assert res.upserted_count == 2\n assert coll.find_one({\"gender\": \"male\"}) == {\n \"_id\": \"Decker\",\n \"name\": \"Decker\",\n \"gender\": \"male\"\n }\n coll.drop()\n\n\nclass TestToBulklist:\n def test_not_id(self):\n li = [\n {\"name\": \"Karin\", \"gender\": \"female\"},\n {\"name\": \"Decker\", \"gender\": \"male\"}\n ]\n assert to_bulklist(li, \"name\") == [\n UpdateOne(\n {\"_id\": \"Karin\"},\n {\"$set\": {\"name\": \"Karin\", \"gender\": \"female\", \"_id\": \"Karin\"}},\n True,\n None,\n None,\n None,\n ),\n UpdateOne(\n {\"_id\": \"Decker\"},\n {\"$set\": {\"name\": \"Decker\", \"gender\": \"male\", \"_id\": \"Decker\"}},\n True,\n None,\n None,\n None,\n ),\n ]\n\n def test_with_id(self):\n data = [\n {\"_id\": \"5fc3af959f9e4b17a00d15f5\", \"name\": \"Mosley\", \"gender\": \"male\"},\n {\"_id\": \"5fc3af9584542f2b3fb85bdf\", \"name\": \"Kelly\", \"gender\": \"male\"},\n ]\n assert to_bulklist(data) == [\n UpdateOne(\n {\"_id\": \"5fc3af959f9e4b17a00d15f5\"},\n {\n \"$set\": {\n \"_id\": \"5fc3af959f9e4b17a00d15f5\",\n \"name\": \"Mosley\",\n \"gender\": \"male\",\n }\n },\n True,\n None,\n None,\n None,\n ),\n UpdateOne(\n {\"_id\": \"5fc3af9584542f2b3fb85bdf\"},\n {\n \"$set\": {\n \"_id\": \"5fc3af9584542f2b3fb85bdf\",\n \"name\": \"Kelly\",\n \"gender\": \"male\",\n }\n },\n True,\n None,\n None,\n None,\n ),\n ]\n\n def test_bulk_item_not_id_error(self):\n li = [{\"name\": \"Karin\", \"gender\": \"female\"}, {\"name\": \"Decker\", \"gender\": \"male\"}]\n with pytest.raises(BulkItemNotIdError) as e:\n to_bulklist(li)\n assert \"_id property does not exist: {'name': 'Karin', 'gender': 'female'}\" in str(e)\n\n def test_bulk_invalid_type(self):\n with pytest.raises(TypeError) as e:\n to_bulklist({'a': 1})\n assert \"must be a list\" in str(e)\n","repo_name":"atu4403/moncoll2","sub_path":"tests/test_moncoll2.py","file_name":"test_moncoll2.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28037575480","text":"from django.db import transaction\n\nfrom ..models import Membership\nfrom ..models import Project\nfrom ..models import User\nfrom ..models import Version\nfrom ..models import database_qs\nfrom ..schema import MembershipListSchema\nfrom ..schema import MembershipDetailSchema\n\nfrom ._base_views import BaseListView\nfrom ._base_views import BaseDetailView\nfrom ._permissions import ProjectFullControlPermission\n\n\ndef _serialize_memberships(memberships):\n membership_data = database_qs(memberships)\n for idx, membership in enumerate(memberships):\n membership_data[idx][\"permission\"] = str(membership.permission)\n membership_data[idx][\"username\"] = membership.user.username\n membership_data[idx][\"first_name\"] = membership.user.first_name\n membership_data[idx][\"last_name\"] = membership.user.last_name\n membership_data[idx][\"email\"] = membership.user.email\n membership_data[idx][\"default_version\"] = (\n membership.default_version.pk if membership.default_version else None\n )\n membership_data.sort(\n key=lambda membership: membership[\"last_name\"].lower()\n if membership[\"last_name\"]\n else membership[\"username\"].lower()\n )\n return membership_data\n\n\nclass MembershipListAPI(BaseListView):\n \"\"\"Create or retrieve a list of project memberships.\n\n Memberships specify a permission level of a user to a project. There are currently\n five cumulative permission levels. `View Only` can only view a project and not change\n any data. `Can Edit` can create, modify, and delete annotations. `Can Transfer` can\n upload and download media. `Can Execute` can launch algorithm workflows. `Full Control`\n can change project settings, including inviting new members, project name, and\n project metadata schema.\n \"\"\"\n\n schema = MembershipListSchema()\n permission_classes = [ProjectFullControlPermission]\n http_method_names = [\"get\", \"post\"]\n\n def _get(self, params):\n members = Membership.objects.filter(project=params[\"project\"])\n return _serialize_memberships(members)\n\n def _post(self, params):\n project = params[\"project\"]\n user = params[\"user\"]\n permission = params[\"permission\"]\n default_version = params.get(\"default_version\")\n if permission == \"View Only\":\n permission = \"r\"\n elif permission == \"Can Edit\":\n permission = \"w\"\n elif permission == \"Can Transfer\":\n permission = \"t\"\n elif permission == \"Can Execute\":\n permission = \"x\"\n elif permission == \"Full Control\":\n permission = \"a\"\n else:\n raise ValueError(\n f\"Permission must have one of the following values: View Only, \"\n \"Can Edit, Can Transfer, Can Execute, Full Control.\"\n )\n existing = Membership.objects.filter(project=project, user=user)\n if existing.exists():\n raise RuntimeError(f\"Membership already exists for project {project}, user {user}!\")\n project = Project.objects.get(pk=project)\n user = User.objects.get(pk=user)\n if default_version is not None:\n default_version = Version.objects.get(pk=default_version)\n membership = Membership.objects.create(\n project=project,\n user=user,\n permission=permission,\n default_version=default_version,\n )\n membership.save()\n return {\"message\": f\"Membership of {user} to {project} created!\", \"id\": membership.id}\n\n def get_queryset(self):\n project_id = self.kwargs[\"project\"]\n members = Membership.objects.filter(project__id=project_id)\n return members\n\n\nclass MembershipDetailAPI(BaseDetailView):\n \"\"\"Interact with an individual project membership.\n\n Memberships specify a permission level of a user to a project. There are currently\n five cumulative permission levels. `View Only` can only view a project and not change\n any data. `Can Edit` can create, modify, and delete annotations. `Can Transfer` can\n upload and download media. `Can Execute` can launch algorithm workflows. `Full Control`\n can change project settings, including inviting new members, project name, and\n project metadata schema.\n \"\"\"\n\n schema = MembershipDetailSchema()\n permission_classes = [ProjectFullControlPermission]\n lookup_field = \"id\"\n http_method_names = [\"get\", \"patch\", \"delete\"]\n\n def _get(self, params):\n memberships = Membership.objects.filter(pk=params[\"id\"])\n return _serialize_memberships(memberships)[0]\n\n @transaction.atomic\n def _patch(self, params):\n membership = Membership.objects.select_for_update().get(pk=params[\"id\"])\n if \"permission\" in params:\n membership.permission = params[\"permission\"]\n if \"default_version\" in params:\n membership.default_version = Version.objects.get(pk=params[\"default_version\"])\n membership.save()\n return {\"message\": f\"Membership {params['id']} successfully updated!\"}\n\n def _delete(self, params):\n Membership.objects.get(pk=params[\"id\"]).delete()\n return {\"message\": f'Membership {params[\"id\"]} successfully deleted!'}\n\n def get_queryset(self):\n return Membership.objects.all()\n","repo_name":"cvisionai/tator","sub_path":"api/main/rest/membership.py","file_name":"membership.py","file_ext":"py","file_size_in_byte":5315,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"52"} +{"seq_id":"6191864898","text":"from django.contrib.auth import authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.views import login\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.urls import reverse\n\nfrom account.forms import LoginForm, RegistrationForm, UserForm, UserInfoForm\n\n\nfrom account.models import UserInfo, Follow\n\n# 用户登录\nfrom article.models import Collection\n\n\ndef user_login(request):\n if request.method ==\"POST\":\n login_form = LoginForm(request.POST)\n if login_form.is_valid():\n cd = login_form.cleaned_data\n user = authenticate(username=cd['username'], password=cd['password'])\n if user:\n login(request, user)\n return HttpResponseRedirect(reverse(\"home\"))\n else:\n return HttpResponseRedirect(reverse(\"user_login\"))\n\n if request.method == \"GET\":\n login_form = LoginForm()\n return render(request, \"account/login.html\", {\"form\": login_form})\n\n\n# 用户注册\ndef user_register(request):\n if request.method == \"POST\":\n user_form = RegistrationForm(request.POST)\n if user_form.is_valid():\n new_user = user_form.save(commit=False)\n new_user.set_password(user_form.cleaned_data['password'])\n new_user.save()\n UserInfo.objects.create(user=new_user)\n return HttpResponseRedirect(reverse(\"user_login\"))\n else:\n return HttpResponse(\"注册失败\")\n else:\n user_form = RegistrationForm()\n return render(request, \"account/register.html\", {\"form\": user_form})\n\n# 用户个人信息显示\n@login_required(login_url='/account/login/')\ndef myinfo(request):\n user =User.objects.get(username=request.user.username)\n userinfo = UserInfo.objects.get(user=user)\n return render(request, \"account/user_info.html\", {\"user\": user, \"userinfo\": userinfo})\n\n# 修改个人信息\n@login_required(login_url=\"/account/login/\")\ndef edit_myinfo(request):\n user = User.objects.get(username=request.user.username)\n userinfo = UserInfo.objects.get(user=request.user)\n\n if request.method == \"POST\":\n user_form = UserForm(request.POST)\n userinfo_form = UserInfoForm(request.POST)\n if user_form.is_valid() * userinfo_form.is_valid():\n user_cd = user_form.cleaned_data\n userinfo_cd = userinfo_form.cleaned_data\n user.email = user_cd['email']\n userinfo.phone = userinfo_cd['phone']\n userinfo.birth = userinfo_cd['birth']\n userinfo.school = userinfo_cd['school']\n userinfo.company = userinfo_cd['company']\n userinfo.profession = userinfo_cd['profession']\n userinfo.address = userinfo_cd['address']\n userinfo.aboutme = userinfo_cd['aboutme']\n user.save()\n userinfo.save()\n return HttpResponseRedirect('/account/myinfo/')\n else:\n user_form = UserForm(instance=request.user)\n userinfo_form = UserInfoForm(initial={\"phone\": userinfo.phone, \"birth\": userinfo.birth, \"school\": userinfo.school, \"company\": userinfo.company, \"profession\": userinfo.profession, \"address\": userinfo.address, \"aboutme\": userinfo.aboutme})\n\n return render(request, \"account/edit_myinfo.html\", {\"user_form\": user_form, \"userinfo_form\": userinfo_form, \"userinfo\":userinfo})\n\n# 头像上传\ndef myphoto(request):\n if request.method == \"POST\":\n img = request.POST['img']\n userinfo = UserInfo.objects.get(user=request.user.id)\n userinfo.photo = img\n userinfo.save()\n return HttpResponse(\"1\")\n else:\n return render(request, \"account/myphoto.html\",)","repo_name":"wjcml/blog-python","sub_path":"MyBlog/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23911881951","text":"from aifc import Error\nimport base64\nimport shutil\nimport os\nimport requests\nimport sys, getopt\nimport json\n\ndef main(argv):\n\tinputfile = ''\n\trefresh_token=''\n\tconsumerSecret=''\n\tconsumerKey=''\n\tcompressonly=False\n\tversion=''\n\thelpMsg='upload_conv.py -i -r -s -k -v -c [Optional. Compress Only]'\n\ttry:\n\t\topts, args = getopt.getopt(argv,\"hi:v:r:s:k:c\",[\"help\",\"ifile=\",\"version=\",\"refresh_token=\",\"consumer_secret=\",\"consumer_key=\",\"compress\"])\n\texcept getopt.GetoptError as err:\n\t\tprint(err)\n\t\tprint(helpMsg)\n\t\tsys.exit(2)\n\tfor opt, arg in opts:\n\t\tif opt == '-h':\n\t\t\tprint('upload_conv.py -i ')\n\t\t\tsys.exit()\n\t\telif opt in (\"-i\", \"--ifile\"):\n\t\t\tinputfile = arg\n\t\telif opt in (\"-r\", \"--refresh_token\"):\n\t\t\trefresh_token = arg\n\t\telif opt in (\"-s\", \"--consumer_secret\"):\n\t\t\tconsumerSecret = arg\n\t\telif opt in (\"-k\", \"--consumer_key\"):\n\t\t\tconsumerKey = arg\n\t\telif opt in (\"-c\", \"--compress_only\"):\n\t\t\tcompressonly = True\n\t\telif opt in (\"-v\", \"--version\"):\n\t\t\tversion = arg\n\tif version == '' or not os.path.isdir(inputfile):\n\t\tprint(helpMsg)\n\telse:\n\t\tsetVersion(version,inputfile)\n\tif compressonly and inputfile != '':\n\t\tzip_compression_tree('./{}'.format(inputfile),inputfile)\n\telif inputfile == '' or refresh_token == '' or consumerKey == '' or consumerSecret=='':\n\t\tprint(helpMsg)\n\t\tsys.exit(2)\n\telse:\n\t\tif os.path.isdir(inputfile):\n\t\t\tzipfile = '{}.zip'.format(inputfile)\n\t\t\tzip_compression_tree('./{}'.format(inputfile),inputfile)\n\t\t\tupload_conv(zipfile,consumerKey,consumerSecret,refresh_token)\n\t\telse:\n\t\t\tupload_conv(inputfile,consumerKey,consumerSecret,refresh_token)\n\tsys.exit()\n\ndef upload_conv(inputfile,consumerKey,consumerSecret,refresh_token):\n\t#decode zip file to base64_string\n\twith open(inputfile, \"rb\") as f:\n\t\tbytes = f.read()\n\t\tencoded = base64.b64encode(bytes)\n\t\tbase64_string = encoded.decode('utf-8')\n\n\t#POST base64_string to targetted org \n\theaders = {'Authorization': 'Bearer ' + salesforceConnect(True,consumerKey,consumerSecret,refresh_token)['access_token']}\n\tdata = {'base64' : base64_string}\n\tendpoint = os.environ.get('SALESFORCE_ENDPOINT')\n\tresponse = requests.post(endpoint, json=data, headers=headers)\n\tprint(response.json())\n\ndef setVersion(version, conversation_folder):\n\tconversationJsonPath = '{}/Conversation.json'.format(conversation_folder)\n\tif os.path.exists(conversationJsonPath):\n\t\twith open(conversationJsonPath,'r') as conversationFile:\n\t\t\tjson_data = json.load(conversationFile)\t\n\t\t\tconversationFile.close()\n\t\t\tjson_data[0]['delpha__Customer_Version_ID__c'] = version\n\t\t\twith open(conversationJsonPath,'w+') as conversationFile:\n\t\t\t\tjson.dump(json_data,conversationFile, indent=4)\t\n\t\t\t\tconversationFile.close()\t\n\ndef salesforceConnect(isSandbox,consumerKey,consumerSecret,refresh_token):\n\tDOMAIN = 'test' if isSandbox else 'login'\n\tr = requests.post('https://{}.salesforce.com/services/oauth2/token'.format(DOMAIN), data = {\n 'grant_type': 'refresh_token',\n 'client_id': consumerKey,\n 'client_secret': consumerSecret,\n 'refresh_token': refresh_token\n\t})\n\n\tprint('Status salesforce connection:', r.status_code)\n\tresult = r.json()\n\treturn result\n\ndef zip_compression_tree(input_dir, output_filename):\n\tshutil.make_archive(output_filename,'zip',input_dir)\n\nif __name__ == \"__main__\":\n\tmain(sys.argv[1:])\n","repo_name":"Delpha-Assistant/import_conversations_script","sub_path":"upload_conv.py","file_name":"upload_conv.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36987434037","text":"\"\"\"\nПрактическая №10 №2\nИз предложенного текстового файла (text18-19.txt) вывести на экран его содерж��мое, количество символов, принадлежащих\nк группе букв. Сформировать новый файл, в который поместить текст в стихотворной форме предварительно заменив символы\nверхнего регистра на нижний.\n\"\"\"\nimport string\n\n\n# новый файл с текстом в нижнем регистре\nprint(open('text18-19.txt', encoding=\"utf8\").read().lower(), file=open('new_file.txt', 'w'))\n\n\ntext = open('text18-19.txt', encoding=\"utf8\").read() # чтение текста из файла и трансляция его в консоль\nprint(text)\n\nfor p in string.punctuation + '\\n': # удаление пунктуации для последующего подсчета букв\n if p in text:\n text = text.replace(p, '')\n\nkeys = list(set(text.lower().replace(\" \", \"\"))) # список букв для подсчета их повторов\ncount = dict()\n\nfor i in keys: # в словарь заносятся ключи - буквы и значения - количество повторов ключа-буквы в тексте\n count[i] = text.count(i)\n\n\nprint('Количество символов, принадлежащих к группе букв', sum(count.values()))\n","repo_name":"vsaprykina/Proj_1sem_Saprykina","sub_path":"PZ_10/PZ_10_2.py","file_name":"PZ_10_2.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40687736172","text":"from log_notify import notify\n\nfrom imp import reload\nimport match_odds_uploader\nreload(match_odds_uploader)\nfrom match_odds_uploader import downloader\n\nnotify = notify()\n\nsport = 'tennis'#input('Enter Sport (lower case): ')\nrefresh = 10#int(input('Enter refresh: '))\nhours = 8#int(input('Enter hours: '))\ndelay = 5#int(input('Enter delay: '))\nmatched_lower_bound = 10000#int(input('Enter min matched: '))\n\n\n\n\n\ndownloader = downloader(sport)\n\n\ntry:\n downloader.download(refresh,hours,delay,matched_lower_bound)\nexcept Exception as e:\n notify.send_message(e,'odds_data')\n\n\n\n#also wanna make this kick off the score downloader for the sport","repo_name":"betting-betting/public-odds-data","sub_path":"betfair_run.py","file_name":"betfair_run.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74199042405","text":"#!/usr/bin/env python3\r\n\"\"\"\"\r\nModel that takes groups of equivalence classes, keeps active molecules separated.\r\nOn each active molecule applies equivalence class in that way, that e.g.\r\nclasses: [[a, b, c], [d, e]] and we have got a, b, a, ,e g, g, h, then we will\r\nkeep a, d, g, g, h. That means that we keep only 1 occurence of the group and\r\nit is first value.\r\nThen we do the same thing to all test molecules and we compute max-fusion\r\nsimilarity.\r\ninput model_configuration could like e.g like this:\r\n {\"model_name\": \"delete_index_group_model\", \"fragments\": \"ecfp.6\", \"groups\": [[num1, num2, num3], [num4, num5, num6]]}}\r\n\"\"\"\r\n\r\nimport json\r\n\r\nfrom model_interface import IModel\r\nfrom model_factory import register_model\r\nimport inputoutput_utils\r\n\r\n\r\nclass DeleteIndexGroupModel(IModel):\r\n model_name = \"delete_index_group_model\"\r\n\r\n def name(self):\r\n return self.model_name\r\n\r\n def create_model(self, active_fragments: str, inactive_fragments: str,\r\n active_descriptors: str, inactive_descriptors: str,\r\n model_configuration: dict) -> dict:\r\n molecules_indexes = []\r\n with open(active_fragments, \"r\", encoding=\"utf-8\") as input_stream:\r\n for new_line in input_stream:\r\n line = json.loads(new_line)\r\n molecule_indexes = []\r\n for fragment in line[\"fragments\"]:\r\n index = fragment[\"index\"]\r\n for group in model_configuration[\"groups\"]:\r\n if index in group:\r\n index = group[0]\r\n break\r\n if index not in molecule_indexes:\r\n molecule_indexes.append(index)\r\n molecules_indexes.append(molecule_indexes) \r\n\r\n model = {\r\n \"configuration\": {\r\n \"model_name\": model_configuration[\"model_name\"],\r\n \"groups\": model_configuration[\"groups\"]\r\n },\r\n \"data\": {\r\n \"active\": molecules_indexes\r\n }\r\n }\r\n return model\r\n\r\n def save_to_json_file(self, output_file: str, model: dict):\r\n inputoutput_utils.save_to_json_file(output_file, model)\r\n\r\n def score_model(self, model_configuration: dict, fragments_file: str,\r\n descriptors_file: str, output_file: str):\r\n inputoutput_utils.create_parent_directory(output_file)\r\n first_line = True\r\n with open(output_file, \"w\", encoding=\"utf-8\") as output_stream:\r\n with open(fragments_file, \"r\", encoding=\"utf-8\") as input_stream:\r\n for new_line in input_stream:\r\n line = json.loads(new_line)\r\n test_active_indexes = []\r\n for fragment in line[\"fragments\"]:\r\n index = fragment[\"index\"]\r\n for group in model_configuration[\"configuration\"][\"groups\"]:\r\n if index in group:\r\n index = group[0]\r\n break\r\n if index not in test_active_indexes:\r\n test_active_indexes.append(index)\r\n max_sim = max([_compute_sim(item, test_active_indexes) for item in\r\n model_configuration[\"data\"][\"active\"]])\r\n score = {\r\n \"name\": line[\"name\"],\r\n \"score\": max_sim\r\n }\r\n if first_line:\r\n first_line = False\r\n else:\r\n output_stream.write(\"\\n\")\r\n json.dump(score, output_stream)\r\n\r\n\r\ndef _compute_sim(active_fragments: list, test_fragments: list) -> list:\r\n summary = 0\r\n for item in test_fragments:\r\n if item in active_fragments:\r\n summary += 1\r\n sim = summary / (len(active_fragments) + len(test_fragments) - summary)\r\n return sim\r\n\r\n\r\nregister_model(DeleteIndexGroupModel.model_name, lambda: DeleteIndexGroupModel())\r\n","repo_name":"LamprechtMatyas/MolecularSimilarity","sub_path":"model/delete_index_group_model.py","file_name":"delete_index_group_model.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12534368415","text":"from __future__ import print_function\n\nimport collections\nimport contextlib\nimport datetime\nimport itertools\nimport json\nimport os\nimport pprint\nimport re\nimport sys\nimport time\nfrom xml.etree import ElementTree\nfrom xml.dom import minidom\n\nfrom chromite.cbuildbot import lkgm_manager\nfrom chromite.cbuildbot import manifest_version\nfrom chromite.cbuildbot import patch_series\nfrom chromite.cbuildbot import repository\nfrom chromite.cbuildbot import trybot_patch_pool\nfrom chromite.cbuildbot import validation_pool\nfrom chromite.cbuildbot.stages import generic_stages\nfrom chromite.cbuildbot.stages import build_stages\nfrom chromite.lib import buildbucket_lib\nfrom chromite.lib import build_requests\nfrom chromite.lib import clactions\nfrom chromite.lib import clactions_metrics\nfrom chromite.lib import config_lib\nfrom chromite.lib import constants\nfrom chromite.lib import commandline\nfrom chromite.lib import cq_config\nfrom chromite.lib import cros_build_lib\nfrom chromite.lib import cros_logging as logging\nfrom chromite.lib import failures_lib\nfrom chromite.lib import git\nfrom chromite.lib import metrics\nfrom chromite.lib import osutils\nfrom chromite.lib import patch as cros_patch\nfrom chromite.lib import timeout_util\nfrom chromite.lib import tree_status\nfrom chromite.scripts import cros_mark_android_as_stable\nfrom chromite.scripts import cros_mark_chrome_as_stable\n\n\nsite_config = config_lib.GetConfig()\n\n\nPRE_CQ = validation_pool.PRE_CQ\n\nPRECQ_LAUNCH_TIMEOUT_MSG = (\n 'We were not able to launch a %s trybot for your change within '\n '%s minutes.\\n\\n'\n 'This problem can happen if the trybot waterfall is very '\n 'busy, or if there is an infrastructure issue. Please '\n 'notify the sheriff and mark your change as ready again. If '\n 'this problem occurs multiple times in a row, please file a '\n 'bug.')\nPRECQ_INFLIGHT_TIMEOUT_MSG = (\n 'The %s trybot for your change timed out after %s minutes.'\n '\\n\\n'\n 'This problem can happen if your change causes the builder '\n 'to hang, or if there is some infrastructure issue. If your '\n 'change is not at fault you may mark your change as ready '\n 'again. If this problem occurs multiple times please notify '\n 'the sheriff and file a bug.')\nPRECQ_EXPIRY_MSG = (\n 'The pre-cq verification for this change expired after %s minutes. No '\n 'action is required on your part.'\n '\\n\\n'\n 'In order to protect the CQ from picking up stale changes, the pre-cq '\n 'status for changes are cleared after a generous timeout. This change '\n 'will be re-tested by the pre-cq before the CQ picks it up.')\n\n\n# Default limit for the size of Pre-CQ configs to test for unioned options\n# TODO(nxia): make this configurable in the COMMIT-QUEUE.ini\nDEFAULT_UNION_PRE_CQ_LIMIT = 15\n\n\nclass ExceedUnionPreCQLimitException(Exception):\n \"\"\"Exception raised when unioned Pre-CQ config size exceeds the limit.\"\"\"\n\n def __init__(self, pre_cq_configs, limit, message=''):\n \"\"\"Initialize a ExceedUnionPreCQLimitException.\n\n Args:\n pre_cq_configs: A set of Pre-CQ configs (strings) which exceeds the limit.\n limit: The limit for the size of the Pre-CQ configs.\n message: An error message (optional).\n \"\"\"\n Exception.__init__(self, message)\n self.pre_cq_configs = pre_cq_configs\n self.limit = limit\n\n\nclass UnknownPreCQConfigRequestedError(Exception):\n \"\"\"Raised when a config file asked for a config that doesn't exist.\"\"\"\n\n def __init__(self, pre_cq_configs):\n super(UnknownPreCQConfigRequestedError, self).__init__(\n 'One of the requested pre-cq configs is invalid or nonexistant: %s'\n % pre_cq_configs)\n self.pre_cq_configs = pre_cq_configs\n\n\nclass PatchChangesStage(generic_stages.BuilderStage):\n \"\"\"Stage that patches a set of Gerrit changes to the buildroot source tree.\"\"\"\n\n def __init__(self, builder_run, patch_pool, **kwargs):\n \"\"\"Construct a PatchChangesStage.\n\n Args:\n builder_run: BuilderRun object.\n patch_pool: A TrybotPatchPool object containing the different types of\n patches to apply.\n \"\"\"\n super(PatchChangesStage, self).__init__(builder_run, **kwargs)\n self.patch_pool = patch_pool\n\n @staticmethod\n def _CheckForDuplicatePatches(_series, changes):\n conflicts = {}\n duplicates = []\n for change in changes:\n if change.id is None:\n logging.warning(\n \"Change %s lacks a usable ChangeId; duplicate checking cannot \"\n \"be done for this change. If cherry-picking fails, this is a \"\n \"potential cause.\", change)\n continue\n conflicts.setdefault(change.id, []).append(change)\n\n duplicates = [x for x in conflicts.itervalues() if len(x) > 1]\n if not duplicates:\n return changes\n\n for conflict in duplicates:\n logging.error(\n \"Changes %s conflict with each other- they have same id %s., \"\n .join(map(str, conflict)), conflict[0].id)\n\n cros_build_lib.Die(\"Duplicate patches were encountered: %s\", duplicates)\n\n def _PatchSeriesFilter(self, series, changes):\n return self._CheckForDuplicatePatches(series, changes)\n\n def _ApplyPatchSeries(self, series, patch_pool, **kwargs):\n \"\"\"Applies a patch pool using a patch series.\"\"\"\n kwargs.setdefault('frozen', False)\n # Honor the given ordering, so that if a gerrit/remote patch\n # conflicts w/ a local patch, the gerrit/remote patch are\n # blamed rather than local (patch ordering is typically\n # local, gerrit, then remote).\n kwargs.setdefault('honor_ordering', True)\n kwargs['changes_filter'] = self._PatchSeriesFilter\n\n _applied, failed_tot, failed_inflight = series.Apply(\n list(patch_pool), **kwargs)\n\n failures = failed_tot + failed_inflight\n if failures:\n self.HandleApplyFailures(failures)\n\n def HandleApplyFailures(self, failures):\n cros_build_lib.Die(\"Failed applying patches: %s\",\n \"\\n\".join(map(str, failures)))\n\n def PerformStage(self):\n class NoisyPatchSeries(patch_series.PatchSeries):\n \"\"\"Custom PatchSeries that adds links to buildbot logs for remote trys.\"\"\"\n\n def ApplyChange(self, change):\n if isinstance(change, cros_patch.GerritPatch):\n logging.PrintBuildbotLink(str(change), change.url)\n elif isinstance(change, cros_patch.UploadedLocalPatch):\n logging.PrintBuildbotStepText(str(change))\n\n return patch_series.PatchSeries.ApplyChange(self, change)\n\n # If we're an external builder, ignore internal patches.\n helper_pool = patch_series.HelperPool.SimpleCreate(\n cros_internal=self._run.config.internal, cros=True)\n\n # Limit our resolution to non-manifest patches.\n patches = NoisyPatchSeries(\n self._build_root,\n helper_pool=helper_pool,\n deps_filter_fn=lambda p: not trybot_patch_pool.ManifestFilter(p))\n\n self._ApplyPatchSeries(patches, self.patch_pool)\n\n\nclass BootstrapStage(PatchChangesStage):\n \"\"\"Stage that patches a chromite repo and re-executes inside it.\n\n Attributes:\n returncode - the returncode of the cbuildbot re-execution. Valid after\n calling stage.Run().\n \"\"\"\n option_name = 'bootstrap'\n\n def __init__(self, builder_run, patch_pool, **kwargs):\n super(BootstrapStage, self).__init__(\n builder_run, trybot_patch_pool.TrybotPatchPool(), **kwargs)\n\n self.patch_pool = patch_pool\n self.returncode = None\n self.tempdir = None\n\n def _ApplyManifestPatches(self, patch_pool):\n \"\"\"Apply a pool of manifest patches to a temp manifest checkout.\n\n Args:\n patch_pool: The pool to apply.\n\n Returns:\n The path to the patched manifest checkout.\n\n Raises:\n Exception, if the new patched manifest cannot be parsed.\n \"\"\"\n checkout_dir = os.path.join(self.tempdir, 'manfest-checkout')\n repository.CloneGitRepo(checkout_dir,\n self._run.config.manifest_repo_url)\n\n patches = patch_series.PatchSeries.WorkOnSingleRepo(\n checkout_dir, tracking_branch=self._run.manifest_branch)\n self._ApplyPatchSeries(patches, patch_pool)\n\n # Verify that the patched manifest loads properly. Propagate any errors as\n # exceptions.\n manifest = os.path.join(checkout_dir, self._run.config.manifest)\n git.Manifest.Cached(manifest, manifest_include_dir=checkout_dir)\n return checkout_dir\n\n @staticmethod\n def _FilterArgsForApi(parsed_args, api_minor):\n \"\"\"Remove arguments that are introduced after an api version.\"\"\"\n def filter_fn(passed_arg):\n return passed_arg.opt_inst.api_version <= api_minor\n\n accepted, removed = commandline.FilteringParser.FilterArgs(\n parsed_args, filter_fn)\n\n if removed:\n logging.warning(\"The following arguments were removed due to api: '%s'\"\n % ' '.join(removed))\n return accepted\n\n @classmethod\n def FilterArgsForTargetCbuildbot(cls, buildroot, cbuildbot_path, options):\n _, minor = cros_build_lib.GetTargetChromiteApiVersion(buildroot)\n args = [cbuildbot_path]\n args.append(options.build_config_name)\n args.extend(cls._FilterArgsForApi(options.parsed_args, minor))\n\n # Only pass down --cache-dir if it was specified. By default, we want\n # the cache dir to live in the root of each checkout, so this means that\n # each instance of cbuildbot needs to calculate the default separately.\n if minor >= 2 and options.cache_dir_specified:\n args += ['--cache-dir', options.cache_dir]\n\n if minor >= constants.REEXEC_API_TSMON_TASK_NUM:\n # Increment the ts-mon task_num so the metrics don't collide.\n args.extend(['--ts-mon-task-num', str(options.ts_mon_task_num + 1)])\n\n return args\n\n @classmethod\n def BootstrapPatchesNeeded(cls, builder_run, patch_pool):\n \"\"\"See if bootstrapping is needed for any of the given patches.\n\n Does NOT determine if they have already been applied.\n\n Args:\n builder_run: BuilderRun object for this build.\n patch_pool: All patches to be applied this run.\n\n Returns:\n boolean True if bootstrapping is needed.\n \"\"\"\n chromite_pool = patch_pool.Filter(project=constants.CHROMITE_PROJECT)\n if builder_run.config.internal:\n manifest_pool = patch_pool.FilterIntManifest()\n else:\n manifest_pool = patch_pool.FilterExtManifest()\n\n return bool(chromite_pool or manifest_pool)\n\n def HandleApplyFailures(self, failures):\n \"\"\"Handle the case where patches fail to apply.\"\"\"\n if self._run.config.pre_cq:\n # Let the PreCQSync stage handle this failure. The PreCQSync stage will\n # comment on CLs with the appropriate message when they fail to apply.\n #\n # WARNING: For manifest patches, the Pre-CQ attempts to apply external\n # patches to the internal manifest, and this means we may flag a conflict\n # here even if the patch applies cleanly. TODO(davidjames): Fix this.\n logging.PrintBuildbotStepWarnings()\n logging.error('Failed applying patches: %s\\n'.join(map(str, failures)))\n else:\n PatchChangesStage.HandleApplyFailures(self, failures)\n\n def _PerformStageInTempDir(self):\n # The plan for the builders is to use master branch to bootstrap other\n # branches. Now, if we wanted to test patches for both the bootstrap code\n # (on master) and the branched chromite (say, R20), we need to filter the\n # patches by branch.\n filter_branch = self._run.manifest_branch\n if self._run.options.test_bootstrap:\n filter_branch = 'master'\n\n # Filter all requested patches for the branch.\n branch_pool = self.patch_pool.FilterBranch(filter_branch)\n\n # Checkout the new version of chromite, and patch it.\n chromite_dir = os.path.join(self.tempdir, 'chromite')\n reference_repo = os.path.join(constants.CHROMITE_DIR, '.git')\n repository.CloneGitRepo(chromite_dir, constants.CHROMITE_URL,\n reference=reference_repo)\n git.RunGit(chromite_dir, ['checkout', filter_branch])\n\n chromite_pool = branch_pool.Filter(project=constants.CHROMITE_PROJECT)\n if chromite_pool:\n patches = patch_series.PatchSeries.WorkOnSingleRepo(\n chromite_dir, filter_branch)\n self._ApplyPatchSeries(patches, chromite_pool)\n\n # Re-exec into new instance of cbuildbot, with proper command line args.\n cbuildbot_path = constants.PATH_TO_CBUILDBOT\n if not os.path.exists(os.path.join(self.tempdir, cbuildbot_path)):\n cbuildbot_path = 'chromite/cbuildbot/cbuildbot'\n cmd = self.FilterArgsForTargetCbuildbot(self.tempdir, cbuildbot_path,\n self._run.options)\n\n extra_params = ['--sourceroot', self._run.options.sourceroot]\n extra_params.extend(self._run.options.bootstrap_args)\n if self._run.options.test_bootstrap:\n # We don't want re-executed instance to see this.\n cmd = [a for a in cmd if a != '--test-bootstrap']\n else:\n # If we've already done the desired number of bootstraps, disable\n # bootstrapping for the next execution. Also pass in the patched manifest\n # repository.\n extra_params.append('--nobootstrap')\n if self._run.config.internal:\n manifest_pool = branch_pool.FilterIntManifest()\n else:\n manifest_pool = branch_pool.FilterExtManifest()\n\n if manifest_pool:\n manifest_dir = self._ApplyManifestPatches(manifest_pool)\n extra_params.extend(['--manifest-repo-url', manifest_dir])\n\n cmd += extra_params\n result_obj = cros_build_lib.RunCommand(\n cmd, cwd=self.tempdir, kill_timeout=30, error_code_ok=True)\n self.returncode = result_obj.returncode\n\n def PerformStage(self):\n with osutils.TempDir(base_dir=self._run.options.bootstrap_dir) as tempdir:\n self.tempdir = tempdir\n self._PerformStageInTempDir()\n self.tempdir = None\n\n\nclass SyncStage(generic_stages.BuilderStage):\n \"\"\"Stage that performs syncing for the builder.\"\"\"\n\n option_name = 'sync'\n output_manifest_sha1 = True\n\n def __init__(self, builder_run, **kwargs):\n super(SyncStage, self).__init__(builder_run, **kwargs)\n self.repo = None\n self.skip_sync = False\n\n # TODO(mtennant): Why keep a duplicate copy of this config value\n # at self.internal when it can always be retrieved from config?\n self.internal = self._run.config.internal\n self.buildbucket_client = self.GetBuildbucketClient()\n\n def _GetManifestVersionsRepoUrl(self, internal=None, test=False):\n if internal is None:\n internal = self._run.config.internal\n\n if internal:\n if test:\n return site_config.params.MANIFEST_VERSIONS_INT_GOB_URL_TEST\n else:\n return site_config.params.MANIFEST_VERSIONS_INT_GOB_URL\n else:\n if test:\n return site_config.params.MANIFEST_VERSIONS_GOB_URL_TEST\n else:\n return site_config.params.MANIFEST_VERSIONS_GOB_URL\n\n def Initialize(self):\n self._InitializeRepo()\n\n def _InitializeRepo(self):\n \"\"\"Set up the RepoRepository object.\"\"\"\n self.repo = self.GetRepoRepository()\n\n def GetNextManifest(self):\n \"\"\"Returns the manifest to use.\"\"\"\n return self._run.config.manifest\n\n def ManifestCheckout(self, next_manifest):\n \"\"\"Checks out the repository to the given manifest.\"\"\"\n self._Print('\\n'.join(['BUILDROOT: %s' % self.repo.directory,\n 'TRACKING BRANCH: %s' % self.repo.branch,\n 'NEXT MANIFEST: %s' % next_manifest]))\n\n if not self.skip_sync:\n self.repo.Sync(next_manifest)\n\n print(self.repo.ExportManifest(mark_revision=self.output_manifest_sha1),\n file=sys.stderr)\n\n def RunPrePatchBuild(self):\n \"\"\"Run through a pre-patch build to prepare for incremental build.\n\n This function runs though the InitSDKStage, SetupBoardStage, and\n BuildPackagesStage. It is intended to be called before applying\n any patches under test, to prepare the chroot and sysroot in a state\n corresponding to ToT prior to an incremental build.\n\n Returns:\n True if all stages were successful, False if any of them failed.\n \"\"\"\n suffix = ' (pre-Patch)'\n try:\n build_stages.InitSDKStage(\n self._run, chroot_replace=True, suffix=suffix).Run()\n for builder_run in self._run.GetUngroupedBuilderRuns():\n for board in builder_run.config.boards:\n build_stages.SetupBoardStage(\n builder_run, board=board, suffix=suffix).Run()\n build_stages.BuildPackagesStage(\n builder_run, board=board, suffix=suffix).Run()\n except failures_lib.StepFailure:\n return False\n\n return True\n\n def WriteChangesToMetadata(self, changes):\n \"\"\"Write the changes under test into the metadata.\n\n Args:\n changes: A list of GerritPatch instances.\n \"\"\"\n changes_list = self._run.attrs.metadata.GetDict().get('changes', [])\n changes_list = changes_list + [c.GetAttributeDict() for c in set(changes)]\n changes_list = sorted(changes_list,\n key=lambda x: (x[cros_patch.ATTR_GERRIT_NUMBER],\n x[cros_patch.ATTR_PATCH_NUMBER],\n x[cros_patch.ATTR_REMOTE]))\n self._run.attrs.metadata.UpdateWithDict({'changes': changes_list})\n change_ids = []\n change_gerrit_ids = []\n change_gerrit_numbers = []\n for c in changes_list:\n change_ids.append(c[cros_patch.ATTR_CHANGE_ID])\n gerrit_number = c[cros_patch.ATTR_GERRIT_NUMBER]\n gerrit_id = '/'.join([c[cros_patch.ATTR_REMOTE], gerrit_number,\n c[cros_patch.ATTR_PATCH_NUMBER]])\n change_gerrit_ids.append(gerrit_id)\n change_gerrit_numbers.append(gerrit_number)\n tags = {\n 'change_ids': change_ids,\n 'change_gerrit_ids': change_gerrit_ids,\n 'change_gerrit_numbers': change_gerrit_numbers,\n }\n self._run.attrs.metadata.UpdateKeyDictWithDict(constants.METADATA_TAGS,\n tags)\n\n @failures_lib.SetFailureType(failures_lib.InfrastructureFailure)\n def PerformStage(self):\n self.Initialize()\n with osutils.TempDir() as tempdir:\n # Save off the last manifest.\n fresh_sync = True\n if os.path.exists(self.repo.directory) and not self._run.options.clobber:\n old_filename = os.path.join(tempdir, 'old.xml')\n try:\n old_contents = self.repo.ExportManifest()\n except cros_build_lib.RunCommandError as e:\n logging.warning(str(e))\n else:\n osutils.WriteFile(old_filename, old_contents)\n fresh_sync = False\n\n # Sync.\n self.ManifestCheckout(self.GetNextManifest())\n\n # Print the blamelist.\n if fresh_sync:\n logging.PrintBuildbotStepText('(From scratch)')\n elif self._run.options.buildbot:\n lkgm_manager.GenerateBlameList(self.repo, old_filename)\n\n # Incremental builds request an additional build before patching changes.\n if self._run.config.build_before_patching:\n pre_build_passed = self.RunPrePatchBuild()\n if not pre_build_passed:\n logging.PrintBuildbotStepText('Pre-patch build failed.')\n\n\nclass LKGMSyncStage(SyncStage):\n \"\"\"Stage that syncs to the last known good manifest blessed by builders.\"\"\"\n\n output_manifest_sha1 = False\n\n def GetNextManifest(self):\n \"\"\"Override: Gets the LKGM.\"\"\"\n # TODO(sosa): Should really use an initialized manager here.\n if self.internal:\n mv_dir = site_config.params.INTERNAL_MANIFEST_VERSIONS_PATH\n else:\n mv_dir = site_config.params.EXTERNAL_MANIFEST_VERSIONS_PATH\n\n manifest_path = os.path.join(self._build_root, mv_dir)\n manifest_repo = self._GetManifestVersionsRepoUrl()\n manifest_version.RefreshManifestCheckout(manifest_path, manifest_repo)\n return os.path.join(manifest_path, self._run.config.lkgm_manifest)\n\n\nclass ManifestVersionedSyncStage(SyncStage):\n \"\"\"Stage that generates a unique manifest file, and sync's to it.\"\"\"\n\n # TODO(mtennant): Make this into a builder run value.\n output_manifest_sha1 = False\n\n def __init__(self, builder_run, **kwargs):\n # Perform the sync at the end of the stage to the given manifest.\n super(ManifestVersionedSyncStage, self).__init__(builder_run, **kwargs)\n self.repo = None\n self.manifest_manager = None\n\n # If a builder pushes changes (even with dryrun mode), we need a writable\n # repository. Otherwise, the push will be rejected by the server.\n self.manifest_repo = self._GetManifestVersionsRepoUrl()\n\n # 1. Our current logic for calculating whether to re-run a build assumes\n # that if the build is green, then it doesn't need to be re-run. This\n # isn't true for canary masters, because the canary master ignores the\n # status of its slaves and is green even if they fail. So set\n # force=True in this case.\n # 2. If we're running with --debug, we should always run through to\n # completion, so as to ensure a complete test.\n self._force = self._run.config.master or self._run.options.debug\n\n def HandleSkip(self):\n \"\"\"Initializes a manifest manager to the specified version if skipped.\"\"\"\n super(ManifestVersionedSyncStage, self).HandleSkip()\n if self._run.options.force_version:\n self.Initialize()\n self.ForceVersion(self._run.options.force_version)\n\n def ForceVersion(self, version):\n \"\"\"Creates a manifest manager from given version and returns manifest.\"\"\"\n logging.PrintBuildbotStepText(version)\n return self.manifest_manager.BootstrapFromVersion(version)\n\n def VersionIncrementType(self):\n \"\"\"Return which part of the version number should be incremented.\"\"\"\n if self._run.manifest_branch == 'master':\n return 'build'\n\n return 'branch'\n\n def RegisterManifestManager(self, manifest_manager):\n \"\"\"Save the given manifest manager for later use in this run.\n\n Args:\n manifest_manager: Expected to be a BuildSpecsManager.\n \"\"\"\n self._run.attrs.manifest_manager = self.manifest_manager = manifest_manager\n\n def Initialize(self):\n \"\"\"Initializes a manager that manages manifests for associated stages.\"\"\"\n\n dry_run = self._run.options.debug\n\n self._InitializeRepo()\n\n # If chrome_rev is somehow set, fail.\n assert not self._chrome_rev, \\\n 'chrome_rev is unsupported on release builders.'\n\n _, db = self._run.GetCIDBHandle()\n self.RegisterManifestManager(manifest_version.BuildSpecsManager(\n source_repo=self.repo,\n manifest_repo=self.manifest_repo,\n manifest=self._run.config.manifest,\n build_names=self._run.GetBuilderIds(),\n incr_type=self.VersionIncrementType(),\n force=self._force,\n branch=self._run.manifest_branch,\n dry_run=dry_run,\n config=self._run.config,\n metadata=self._run.attrs.metadata,\n db=db,\n buildbucket_client=self.buildbucket_client))\n\n def _SetAndroidVersionIfApplicable(self, manifest):\n \"\"\"If 'android' is in |manifest|, write version to the BuilderRun object.\n\n Args:\n manifest: Path to the manifest.\n \"\"\"\n manifest_dom = minidom.parse(manifest)\n elements = manifest_dom.getElementsByTagName(lkgm_manager.ANDROID_ELEMENT)\n\n if elements:\n android_version = elements[0].getAttribute(\n lkgm_manager.ANDROID_VERSION_ATTR)\n logging.info(\n 'Android version was found in the manifest: %s', android_version)\n # Update the metadata dictionary. This is necessary because the\n # metadata dictionary is preserved through re-executions, so\n # UprevAndroidStage can read the version from the dictionary\n # later. This is easier than parsing the manifest again after\n # the re-execution.\n self._run.attrs.metadata.UpdateKeyDictWithDict(\n 'version', {'android': android_version})\n\n def _SetChromeVersionIfApplicable(self, manifest):\n \"\"\"If 'chrome' is in |manifest|, write the version to the BuilderRun object.\n\n Args:\n manifest: Path to the manifest.\n \"\"\"\n manifest_dom = minidom.parse(manifest)\n elements = manifest_dom.getElementsByTagName(lkgm_manager.CHROME_ELEMENT)\n\n if elements:\n chrome_version = elements[0].getAttribute(\n lkgm_manager.CHROME_VERSION_ATTR)\n logging.info(\n 'Chrome version was found in the manifest: %s', chrome_version)\n # Update the metadata dictionary. This is necessary because the\n # metadata dictionary is preserved through re-executions, so\n # SyncChromeStage can read the version from the dictionary\n # later. This is easier than parsing the manifest again after\n # the re-execution.\n self._run.attrs.metadata.UpdateKeyDictWithDict(\n 'version', {'chrome': chrome_version})\n\n def GetNextManifest(self):\n \"\"\"Uses the initialized manifest manager to get the next manifest.\"\"\"\n assert self.manifest_manager, \\\n 'Must run GetStageManager before checkout out build.'\n\n build_id = self._run.attrs.metadata.GetDict().get('build_id')\n\n to_return = self.manifest_manager.GetNextBuildSpec(build_id=build_id)\n previous_version = self.manifest_manager.GetLatestPassingSpec()\n target_version = self.manifest_manager.current_version\n\n # Print the Blamelist here.\n url_prefix = 'https://crosland.corp.google.com/log/'\n url = url_prefix + '%s..%s' % (previous_version, target_version)\n logging.PrintBuildbotLink('Blamelist', url)\n # The testManifestVersionedSyncOnePartBranch interacts badly with this\n # function. It doesn't fully initialize self.manifest_manager which\n # causes target_version to be None. Since there isn't a clean fix in\n # either direction, just throw this through str(). In the normal case,\n # it's already a string anyways.\n logging.PrintBuildbotStepText(str(target_version))\n\n return to_return\n\n @contextlib.contextmanager\n def LocalizeManifest(self, manifest, filter_cros=False):\n \"\"\"Remove restricted checkouts from the manifest if needed.\n\n Args:\n manifest: The manifest to localize.\n filter_cros: If set, then only checkouts with a remote of 'cros' or\n 'cros-internal' are kept, and the rest are filtered out.\n \"\"\"\n if filter_cros:\n with osutils.TempDir() as tempdir:\n filtered_manifest = os.path.join(tempdir, 'filtered.xml')\n doc = ElementTree.parse(manifest)\n root = doc.getroot()\n for node in root.findall('project'):\n remote = node.attrib.get('remote')\n if remote and remote not in site_config.params.GIT_REMOTES:\n root.remove(node)\n doc.write(filtered_manifest)\n yield filtered_manifest\n else:\n yield manifest\n\n def _GetMasterVersion(self, master_id, timeout=5 * 60):\n \"\"\"Get the platform version associated with the master_build_id.\n\n Args:\n master_id: Our master build id.\n timeout: How long to wait for the platform version to show up\n in the database. This is needed because the slave builders are\n triggered slightly before the platform version is written. Default\n is 5 minutes.\n \"\"\"\n # TODO(davidjames): Remove the wait loop here once we've updated slave\n # builders to only get triggered after the platform version is written.\n def _PrintRemainingTime(remaining):\n logging.info('%s until timeout...', remaining)\n\n def _GetPlatformVersion():\n return db.GetBuildStatus(master_id)['platform_version']\n\n # Retry until non-None version is returned.\n def _ShouldRetry(x):\n return not x\n\n _, db = self._run.GetCIDBHandle()\n return timeout_util.WaitForSuccess(_ShouldRetry,\n _GetPlatformVersion,\n timeout,\n period=constants.SLEEP_TIMEOUT,\n side_effect_func=_PrintRemainingTime)\n\n def _VerifyMasterId(self, master_id):\n \"\"\"Verify that our master id is current and valid.\n\n Args:\n master_id: Our master build id.\n \"\"\"\n _, db = self._run.GetCIDBHandle()\n if db and master_id:\n assert not self._run.options.force_version\n master_build_status = db.GetBuildStatus(master_id)\n latest = db.GetBuildHistory(\n master_build_status['build_config'], 1,\n milestone_version=master_build_status['milestone_version'])\n if latest and latest[0]['id'] != master_id:\n raise failures_lib.MasterSlaveVersionMismatchFailure(\n 'This slave\\'s master (id=%s) has been supplanted by a newer '\n 'master (id=%s). Aborting.' % (master_id, latest[0]['id']))\n\n @failures_lib.SetFailureType(failures_lib.InfrastructureFailure)\n def PerformStage(self):\n self.Initialize()\n\n self._VerifyMasterId(self._run.options.master_build_id)\n version = self._run.options.force_version\n if self._run.options.master_build_id:\n version = self._GetMasterVersion(self._run.options.master_build_id)\n\n next_manifest = None\n if version:\n next_manifest = self.ForceVersion(version)\n else:\n self.skip_sync = True\n try:\n next_manifest = self.GetNextManifest()\n except validation_pool.TreeIsClosedException as e:\n logging.warning(str(e))\n\n if not next_manifest:\n logging.info('Found no work to do.')\n if self._run.attrs.manifest_manager.DidLastBuildFail():\n raise failures_lib.StepFailure('The previous build failed.')\n else:\n raise failures_lib.ExitEarlyException(\n 'ManifestVersionedSyncStage finished and exited early.')\n\n # Log this early on for the release team to grep out before we finish.\n if self.manifest_manager:\n self._Print('\\nRELEASETAG: %s\\n' % (\n self.manifest_manager.current_version))\n\n self._SetAndroidVersionIfApplicable(next_manifest)\n self._SetChromeVersionIfApplicable(next_manifest)\n # To keep local trybots working, remove restricted checkouts from the\n # official manifest we get from manifest-versions.\n with self.LocalizeManifest(\n next_manifest, filter_cros=self._run.options.local) as new_manifest:\n self.ManifestCheckout(new_manifest)\n\n\nclass MasterSlaveLKGMSyncStage(ManifestVersionedSyncStage):\n \"\"\"Stage that generates a unique manifest file candidate, and sync's to it.\n\n This stage uses an LKGM manifest manager that handles LKGM\n candidates and their states.\n \"\"\"\n # If we are using an internal manifest, but need to be able to create an\n # external manifest, we create a second manager for that manifest.\n external_manager = None\n MAX_BUILD_HISTORY_LENGTH = 10\n MilestoneVersion = collections.namedtuple(\n 'MilestoneVersion', ['milestone', 'platform'])\n\n def __init__(self, builder_run, **kwargs):\n super(MasterSlaveLKGMSyncStage, self).__init__(builder_run, **kwargs)\n # lkgm_manager deals with making sure we're synced to whatever manifest\n # we get back in GetNextManifest so syncing again is redundant.\n self._android_version = None\n self._chrome_version = None\n\n def _GetInitializedManager(self, internal):\n \"\"\"Returns an initialized lkgm manager.\n\n Args:\n internal: Boolean. True if this is using an internal manifest.\n\n Returns:\n lkgm_manager.LKGMManager.\n \"\"\"\n increment = self.VersionIncrementType()\n return lkgm_manager.LKGMManager(\n source_repo=self.repo,\n manifest_repo=self._GetManifestVersionsRepoUrl(internal=internal),\n manifest=self._run.config.manifest,\n build_names=self._run.GetBuilderIds(),\n build_type=self._run.config.build_type,\n incr_type=increment,\n force=self._force,\n branch=self._run.manifest_branch,\n dry_run=self._run.options.debug,\n config=self._run.config,\n metadata=self._run.attrs.metadata,\n buildbucket_client=self.buildbucket_client)\n\n def Initialize(self):\n \"\"\"Override: Creates an LKGMManager rather than a ManifestManager.\"\"\"\n self._InitializeRepo()\n self.RegisterManifestManager(self._GetInitializedManager(self.internal))\n if self._run.config.master and self._GetSlaveConfigs():\n assert self.internal, 'Unified masters must use an internal checkout.'\n MasterSlaveLKGMSyncStage.external_manager = \\\n self._GetInitializedManager(False)\n\n def ForceVersion(self, version):\n manifest = super(MasterSlaveLKGMSyncStage, self).ForceVersion(version)\n if MasterSlaveLKGMSyncStage.external_manager:\n MasterSlaveLKGMSyncStage.external_manager.BootstrapFromVersion(version)\n\n return manifest\n\n def _VerifyMasterId(self, master_id):\n \"\"\"Verify that our master id is current and valid.\"\"\"\n super(MasterSlaveLKGMSyncStage, self)._VerifyMasterId(master_id)\n if not self._run.config.master and not master_id:\n raise failures_lib.StepFailure(\n 'Cannot start build without a master_build_id. Did you hit force '\n 'build on a slave? Please hit force build on the master instead.')\n\n def GetNextManifest(self):\n \"\"\"Gets the next manifest using LKGM logic.\"\"\"\n assert self.manifest_manager, \\\n 'Must run Initialize before we can get a manifest.'\n assert isinstance(self.manifest_manager, lkgm_manager.LKGMManager), \\\n 'Manifest manager instantiated with wrong class.'\n assert self._run.config.master\n\n build_id = self._run.attrs.metadata.GetDict().get('build_id')\n logging.info('Creating new candidate manifest, including chrome version '\n '%s.', self._chrome_version)\n if self._android_version:\n logging.info('Adding Android version to new candidate manifest %s.',\n self._android_version)\n manifest = self.manifest_manager.CreateNewCandidate(\n android_version=self._android_version,\n chrome_version=self._chrome_version,\n build_id=build_id)\n if MasterSlaveLKGMSyncStage.external_manager:\n MasterSlaveLKGMSyncStage.external_manager.CreateFromManifest(\n manifest, build_id=build_id)\n\n return manifest\n\n def GetLatestAndroidVersion(self):\n \"\"\"Returns the version of Android to uprev.\"\"\"\n return cros_mark_android_as_stable.GetLatestBuild(\n constants.ANDROID_BUCKET_URL, self._run.config.android_import_branch,\n cros_mark_android_as_stable.MakeBuildTargetDict(\n self._run.config.android_import_branch))[0]\n\n def GetLatestChromeVersion(self):\n \"\"\"Returns the version of Chrome to uprev.\"\"\"\n return cros_mark_chrome_as_stable.GetLatestRelease(\n constants.CHROMIUM_GOB_URL)\n\n def GetLastChromeOSVersion(self):\n \"\"\"Fetching ChromeOS version from the last run.\n\n Fetching the chromeos version from the last run that published a manifest\n by querying CIDB. Master builds that failed before publishing a manifest\n will be ignored.\n\n Returns:\n A namedtuple MilestoneVersion,\n e.g. MilestoneVersion(milestone='44', platform='7072.0.0-rc4')\n or None if failed to retrieve milestone and platform versions.\n \"\"\"\n build_id, db = self._run.GetCIDBHandle()\n\n if db is None:\n return None\n\n builds = db.GetBuildHistory(\n build_config=self._run.config.name,\n num_results=self.MAX_BUILD_HISTORY_LENGTH,\n ignore_build_id=build_id)\n full_versions = [b.get('full_version') for b in builds]\n old_version = next(itertools.ifilter(bool, full_versions), None)\n if old_version:\n pattern = r'^R(\\d+)-(\\d+.\\d+.\\d+(-rc\\d+)*)'\n m = re.match(pattern, old_version)\n if m:\n milestone = m.group(1)\n platform = m.group(2)\n return self.MilestoneVersion(\n milestone=milestone, platform=platform)\n return None\n\n @failures_lib.SetFailureType(failures_lib.InfrastructureFailure)\n def PerformStage(self):\n \"\"\"Performs the stage.\"\"\"\n if self._android_rev and self._run.config.master:\n self._android_version = self.GetLatestAndroidVersion()\n logging.info('Latest Android version is: %s', self._android_version)\n\n if (self._chrome_rev == constants.CHROME_REV_LATEST and\n self._run.config.master):\n # PFQ master needs to determine what version of Chrome to build\n # for all slaves.\n logging.info('I am a master running with CHROME_REV_LATEST, '\n 'therefore getting latest chrome version.')\n self._chrome_version = self.GetLatestChromeVersion()\n logging.info('Latest chrome version is: %s', self._chrome_version)\n\n ManifestVersionedSyncStage.PerformStage(self)\n\n # Generate blamelist\n cros_version = self.GetLastChromeOSVersion()\n if cros_version:\n old_filename = self.manifest_manager.GetBuildSpecFilePath(\n cros_version.milestone, cros_version.platform)\n if not os.path.exists(old_filename):\n logging.error('Could not generate blamelist, '\n 'manifest file does not exist: %s', old_filename)\n else:\n logging.debug('Generate blamelist against: %s', old_filename)\n lkgm_manager.GenerateBlameList(self.repo, old_filename)\n\nclass CommitQueueSyncStage(MasterSlaveLKGMSyncStage):\n \"\"\"Commit Queue Sync stage that handles syncing and applying patches.\n\n Similar to the MasterSlaveLKGMsync Stage, this stage handles syncing\n to a manifest, passing around that manifest to other builders.\n\n What makes this stage different is that the CQ master finds the\n patches on Gerrit which are ready to be committed, apply them, and\n includes the patches in the new manifest. The slaves sync to the\n manifest, and apply the patches written in the manifest.\n \"\"\"\n\n # The amount of time we wait before assuming that the Pre-CQ is down and\n # that we should start testing changes that haven't been tested by the Pre-CQ.\n PRE_CQ_TIMEOUT = 2 * 60 * 60\n\n def __init__(self, builder_run, **kwargs):\n super(CommitQueueSyncStage, self).__init__(builder_run, **kwargs)\n\n # The pool of patches to be picked up by the commit queue.\n # - For the master commit queue, it's initialized in GetNextManifest.\n # - For slave commit queues, it's initialized in _SetPoolFromManifest.\n #\n # In all cases, the pool is saved to disk.\n self.pool = None\n\n def HandleSkip(self):\n \"\"\"Handles skip and initializes validation pool from manifest.\"\"\"\n super(CommitQueueSyncStage, self).HandleSkip()\n filename = self._run.options.validation_pool\n if filename:\n self.pool = validation_pool.ValidationPool.Load(\n filename, builder_run=self._run)\n else:\n self._SetPoolFromManifest(self.manifest_manager.GetLocalManifest())\n\n def _ChangeFilter(self, _pool, changes, non_manifest_changes):\n # First, look for changes that were tested by the Pre-CQ.\n changes_to_test = []\n\n _, db = self._run.GetCIDBHandle()\n if db:\n actions_for_changes = db.GetActionsForChanges(changes)\n for change in changes:\n status = clactions.GetCLPreCQStatus(change, actions_for_changes)\n if status == constants.CL_STATUS_PASSED:\n changes_to_test.append(change)\n else:\n logging.warning(\"DB not available, unable to filter for PreCQ passed.\")\n\n # Allow Commit-Ready=+2 changes to bypass the Pre-CQ, if there are no other\n # changes.\n if not changes_to_test:\n changes_to_test = [x for x in changes if x.HasApproval('COMR', '2')]\n\n # If we only see changes that weren't verified by Pre-CQ, and some of them\n # are really old changes, try all of the changes. This ensures that the CQ\n # continues to work (albeit slowly) even if the Pre-CQ is down.\n if changes and not changes_to_test:\n oldest = min(x.approval_timestamp for x in changes)\n if time.time() > oldest + self.PRE_CQ_TIMEOUT:\n # It's safest to try all changes here because some of the old changes\n # might depend on newer changes (e.g. via CQ-DEPEND).\n changes_to_test = changes\n\n return changes_to_test, non_manifest_changes\n\n def _SetPoolFromManifest(self, manifest):\n \"\"\"Sets validation pool based on manifest path passed in.\"\"\"\n # Note that this function is only called after the repo is already\n # sync'd, so AcquirePoolFromManifest does not need to sync.\n self.pool = validation_pool.ValidationPool.AcquirePoolFromManifest(\n manifest=manifest,\n overlays=self._run.config.overlays,\n repo=self.repo,\n build_number=self._run.buildnumber,\n builder_name=self._run.GetBuilderName(),\n buildbucket_id=self._run.options.buildbucket_id,\n is_master=self._run.config.master,\n dryrun=self._run.options.debug,\n builder_run=self._run)\n\n def _GetLKGMVersionFromManifest(self, manifest):\n manifest_dom = minidom.parse(manifest)\n elements = manifest_dom.getElementsByTagName(lkgm_manager.LKGM_ELEMENT)\n if elements:\n lkgm_version = elements[0].getAttribute(lkgm_manager.LKGM_VERSION_ATTR)\n logging.info(\n 'LKGM version was found in the manifest: %s', lkgm_version)\n return lkgm_version\n\n def GetNextManifest(self):\n \"\"\"Gets the next manifest using LKGM logic.\"\"\"\n assert self.manifest_manager, \\\n 'Must run Initialize before we can get a manifest.'\n assert isinstance(self.manifest_manager, lkgm_manager.LKGMManager), \\\n 'Manifest manager instantiated with wrong class.'\n assert self._run.config.master\n\n build_id = self._run.attrs.metadata.GetDict().get('build_id')\n\n try:\n # In order to acquire a pool, we need an initialized buildroot.\n if not git.FindRepoDir(self.repo.directory):\n self.repo.Initialize()\n\n query = constants.CQ_READY_QUERY\n if self._run.options.cq_gerrit_override:\n query = (self._run.options.cq_gerrit_override, None)\n\n self.pool = validation_pool.ValidationPool.AcquirePool(\n overlays=self._run.config.overlays,\n repo=self.repo,\n build_number=self._run.buildnumber,\n builder_name=self._run.GetBuilderName(),\n buildbucket_id=self._run.options.buildbucket_id,\n query=query,\n dryrun=self._run.options.debug,\n check_tree_open=(not self._run.options.debug or\n self._run.options.mock_tree_status),\n change_filter=self._ChangeFilter, builder_run=self._run)\n except validation_pool.TreeIsClosedException as e:\n logging.warning(str(e))\n return None\n\n # We must extend the builder deadline before publishing a new manifest to\n # ensure that slaves have enough time to complete the builds about to\n # start.\n build_id, db = self._run.GetCIDBHandle()\n if db:\n db.ExtendDeadline(build_id, self._run.config.build_timeout)\n\n logging.info('Creating new candidate manifest.')\n manifest = self.manifest_manager.CreateNewCandidate(\n validation_pool=self.pool, build_id=build_id)\n if MasterSlaveLKGMSyncStage.external_manager:\n MasterSlaveLKGMSyncStage.external_manager.CreateFromManifest(\n manifest, build_id=build_id)\n\n return manifest\n\n def ManifestCheckout(self, next_manifest):\n \"\"\"Checks out the repository to the given manifest.\"\"\"\n # Sync to the provided manifest on slaves. On the master, we're\n # already synced to this manifest, so self.skip_sync is set and\n # this is a no-op.\n super(CommitQueueSyncStage, self).ManifestCheckout(next_manifest)\n\n if self._run.config.build_before_patching:\n assert not self._run.config.master\n pre_build_passed = self.RunPrePatchBuild()\n logging.PrintBuildbotStepName('CommitQueueSync : Apply Patches')\n if not pre_build_passed:\n logging.PrintBuildbotStepText('Pre-patch build failed.')\n\n # On slaves, initialize our pool and apply patches. On the master,\n # we've already done that in GetNextManifest, so this is a no-op.\n if not self._run.config.master:\n # Print the list of CHUMP changes since the LKGM, then apply changes and\n # print the list of applied changes.\n self.manifest_manager.GenerateBlameListSinceLKGM()\n self._SetPoolFromManifest(next_manifest)\n self.pool.ApplyPoolIntoRepo()\n\n @failures_lib.SetFailureType(failures_lib.InfrastructureFailure)\n def PerformStage(self):\n \"\"\"Performs normal stage and prints blamelist at end.\"\"\"\n if self._run.options.force_version:\n self.HandleSkip()\n else:\n ManifestVersionedSyncStage.PerformStage(self)\n\n self.WriteChangesToMetadata(self.pool.applied)\n\n\nclass PreCQSyncStage(SyncStage):\n \"\"\"Sync and apply patches to test if they compile.\"\"\"\n\n def __init__(self, builder_run, patches, **kwargs):\n super(PreCQSyncStage, self).__init__(builder_run, **kwargs)\n\n # As a workaround for crbug.com/432706, we scan patches to see if they\n # are already being merged. If they are, we don't test them in the PreCQ.\n self.patches = [p for p in patches if not p.IsBeingMerged()]\n\n if patches and not self.patches:\n cros_build_lib.Die('No patches that still need testing.')\n\n # The ValidationPool of patches to test. Initialized in PerformStage, and\n # refreshed after bootstrapping by HandleSkip.\n self.pool = None\n\n def HandleSkip(self):\n \"\"\"Handles skip and loads validation pool from disk.\"\"\"\n super(PreCQSyncStage, self).HandleSkip()\n filename = self._run.options.validation_pool\n if filename:\n self.pool = validation_pool.ValidationPool.Load(\n filename, builder_run=self._run)\n\n def PerformStage(self):\n super(PreCQSyncStage, self).PerformStage()\n self.pool = validation_pool.ValidationPool.AcquirePreCQPool(\n overlays=self._run.config.overlays,\n build_root=self._build_root,\n build_number=self._run.buildnumber,\n builder_name=self._run.config.name,\n buildbucket_id=self._run.options.buildbucket_id,\n dryrun=self._run.options.debug_forced,\n candidates=self.patches,\n builder_run=self._run)\n self.pool.ApplyPoolIntoRepo()\n\n if len(self.pool.applied) == 0 and self.patches:\n cros_build_lib.Die('No changes have been applied.')\n\n changes = self.pool.applied or self.patches\n self.WriteChangesToMetadata(changes)\n\n\nclass PreCQLauncherStage(SyncStage):\n \"\"\"Scans for CLs and automatically launches Pre-CQ jobs to test them.\"\"\"\n\n # The number of minutes we wait before launching Pre-CQ jobs. This measures\n # the idle time of a given patch series, so, for example, if a user takes\n # 20 minutes to mark a series of 20 patches as ready, we won't launch a\n # tryjob on any of the patches until the user has been idle for 2 minutes.\n LAUNCH_DELAY = 2\n\n # The number of minutes we allow before considering a launch attempt failed.\n LAUNCH_TIMEOUT = 90\n\n # The number of minutes we allow before considering an in-flight job failed.\n INFLIGHT_TIMEOUT = 240\n\n # The number of minutes we allow before expiring a pre-cq PASSED or\n # FULLY_VERIFIED status. After this timeout is hit, a CL's status will be\n # reset to None. This prevents very stale CLs from entering the CQ.\n STATUS_EXPIRY_TIMEOUT = 60 * 24 * 7\n\n # The maximum number of patches we will allow in a given trybot run. This is\n # needed because our trybot infrastructure can only handle so many patches at\n # once.\n MAX_PATCHES_PER_TRYBOT_RUN = 50\n\n # The maximum derivative of the number of tryjobs we will launch in a given\n # cycle of ProcessChanges. Used to rate-limit the launcher when reopening the\n # tree after building up a large backlog.\n MAX_LAUNCHES_PER_CYCLE_DERIVATIVE = 20\n\n # Delta time constant for checking buildbucket. Do not check status or\n # cancel builds which were launched >= BUILDBUCKET_DELTA_TIME_HOUR ago.\n BUILDBUCKET_DELTA_TIME_HOUR = 4\n\n # Delay between launches of sanity-pre-cq builds for the same build config\n PRE_CQ_SANITY_CHECK_PERIOD_HOURS = 5\n\n # How many days to look back in build history to check for sanity-pre-cq\n PRE_CQ_SANITY_CHECK_LOOK_BACK_HISTORY_DAYS = 1\n\n def __init__(self, builder_run, **kwargs):\n super(PreCQLauncherStage, self).__init__(builder_run, **kwargs)\n self.skip_sync = True\n self.last_cycle_launch_count = 0\n\n\n def _HasTimedOut(self, start, now, timeout_minutes):\n \"\"\"Check whether |timeout_minutes| has elapsed between |start| and |now|.\n\n Args:\n start: datetime.datetime start time.\n now: datetime.datetime current time.\n timeout_minutes: integer number of minutes for timeout.\n\n Returns:\n True if (now-start) > timeout_minutes.\n \"\"\"\n diff = datetime.timedelta(minutes=timeout_minutes)\n return (now - start) > diff\n\n @staticmethod\n def _PrintPatchStatus(patch, status):\n \"\"\"Print a link to |patch| with |status| info.\"\"\"\n items = (\n status,\n os.path.basename(patch.project),\n str(patch),\n )\n logging.PrintBuildbotLink(' | '.join(items), patch.url)\n\n def _GetPreCQConfigsFromOptions(self, change, union_pre_cq_limit=None):\n \"\"\"Get Pre-CQ configs from CQ config options.\n\n If union-pre-cq-sub-configs flag is True in the default config file, get\n unioned Pre-CQ configs from the sub configs; else, get Pre-CQ configs from\n the default config file.\n\n Args:\n change: The instance of cros_patch.GerritPatch to get Pre-CQ configs.\n union_pre_cq_limit: The limit size for unioned Pre-CQ configs if provided.\n Default to None.\n\n Returns:\n A set of valid Pre-CQ configs (strings) or None.\n \"\"\"\n try:\n cq_config_parser = cq_config.CQConfigParser(self._build_root, change,\n forgiving=False)\n pre_cq_configs = None\n if cq_config_parser.GetUnionPreCQSubConfigsFlag():\n pre_cq_configs = self._ParsePreCQsFromOption(\n cq_config_parser.GetUnionedPreCQConfigs())\n if (union_pre_cq_limit is not None and pre_cq_configs and\n len(pre_cq_configs) > union_pre_cq_limit):\n raise ExceedUnionPreCQLimitException(pre_cq_configs,\n union_pre_cq_limit)\n\n return pre_cq_configs\n else:\n return self._ParsePreCQsFromOption(\n cq_config_parser.GetPreCQConfigs())\n except (UnknownPreCQConfigRequestedError,\n cq_config.MalformedCQConfigException):\n logging.exception('Exception encountered when parsing pre-cq options '\n 'for change %s. Falling back to default set.', change)\n m = 'chromeos/cbuildbot/pre-cq/bad_pre_cq_options_count'\n metrics.Counter(m).increment()\n return None\n\n def _ConfiguredVerificationsForChange(self, change):\n \"\"\"Determine which configs to test |change| with.\n\n This method returns only the configs that are asked for by the config\n file. It does not include special-case logic for adding additional bots\n based on the type of the repository (see VerificationsForChange for that).\n\n Args:\n change: GerritPatch instance to get configs-to-test for.\n\n Returns:\n A set of configs to test.\n \"\"\"\n configs_to_test = None\n # If a pre-cq config is specified in the commit message, use that.\n # Otherwise, look in appropriate COMMIT-QUEUE.ini. Otherwise, default to\n # constants.PRE_CQ_DEFAULT_CONFIGS\n lines = cros_patch.GetOptionLinesFromCommitMessage(\n change.commit_message, constants.CQ_CONFIG_PRE_CQ_CONFIGS_REGEX)\n if lines is not None:\n try:\n configs_to_test = self._ParsePreCQsFromOption(lines)\n except UnknownPreCQConfigRequestedError:\n logging.exception('Unknown config requested in commit message '\n 'for change %s. Falling back to default set.',\n change)\n\n configs_from_options = None\n try:\n configs_from_options = self._GetPreCQConfigsFromOptions(\n change, union_pre_cq_limit=DEFAULT_UNION_PRE_CQ_LIMIT)\n except ExceedUnionPreCQLimitException as e:\n pre_cq_configs = list(e.pre_cq_configs)\n pre_cq_configs.sort()\n configs_from_options = pre_cq_configs[:DEFAULT_UNION_PRE_CQ_LIMIT]\n logging.info('Unioned Pre-CQs %s for change %s exceed the limit %d. '\n 'Will launch the following Pre-CQ configs: %s',\n e.pre_cq_configs, change.PatchLink(),\n DEFAULT_UNION_PRE_CQ_LIMIT, configs_from_options)\n\n configs_to_test = configs_to_test or configs_from_options\n return set(configs_to_test or constants.PRE_CQ_DEFAULT_CONFIGS)\n\n def VerificationsForChange(self, change):\n \"\"\"Determine which configs to test |change| with.\n\n Args:\n change: GerritPatch instance to get configs-to-test for.\n\n Returns:\n A set of configs to test.\n \"\"\"\n configs_to_test = self._ConfiguredVerificationsForChange(change)\n\n # Add the BINHOST_PRE_CQ to any changes that affect an overlay.\n if '/overlays/' in change.project:\n configs_to_test.add(constants.BINHOST_PRE_CQ)\n\n return configs_to_test\n\n def _ParsePreCQsFromOption(self, pre_cq_configs):\n \"\"\"Parse Pre-CQ configs got from option.\n\n Args:\n pre_cq_configs: A list of Pre-CQ configs got from option, or None.\n\n Returns:\n A valid Pre-CQ config list, or None.\n \"\"\"\n if pre_cq_configs:\n configs_to_test = set(pre_cq_configs)\n\n # Replace 'default' with the default configs.\n if 'default' in configs_to_test:\n configs_to_test.discard('default')\n configs_to_test.update(constants.PRE_CQ_DEFAULT_CONFIGS)\n\n # Verify that all of the configs are valid.\n if all(c in self._run.site_config for c in configs_to_test):\n return configs_to_test\n else:\n raise UnknownPreCQConfigRequestedError(configs_to_test)\n\n return None\n\n def ScreenChangeForPreCQ(self, change):\n \"\"\"Record which pre-cq tryjobs to test |change| with.\n\n This method determines which configs to test a given |change| with, and\n writes those as pending tryjobs to the cidb.\n\n Args:\n change: GerritPatch instance to screen. This change should not yet have\n been screened.\n \"\"\"\n actions = []\n configs_to_test = self.VerificationsForChange(change)\n for c in configs_to_test:\n actions.append(clactions.CLAction.FromGerritPatchAndAction(\n change, constants.CL_ACTION_VALIDATION_PENDING_PRE_CQ,\n reason=c))\n actions.append(clactions.CLAction.FromGerritPatchAndAction(\n change, constants.CL_ACTION_SCREENED_FOR_PRE_CQ))\n\n build_id, db = self._run.GetCIDBHandle()\n db.InsertCLActions(build_id, actions)\n\n def CanSubmitChangeInPreCQ(self, change):\n \"\"\"Look up whether |change| is configured to be submitted in the pre-CQ.\n\n Args:\n change: Change to examine.\n\n Returns:\n Boolean indicating if this change is configured to be submitted in the\n pre-CQ.\n \"\"\"\n cq_config_parser = cq_config.CQConfigParser(self._build_root, change)\n return cq_config_parser.CanSubmitChangeInPreCQ()\n\n def GetConfigBuildbucketIdMap(self, output):\n \"\"\"Convert tryjob json output into a config:buildbucket_id map.\n\n Config is the config-name of a pre-cq triggered by the pre-cq-launcher.\n buildbucket_id is the request id of the pre-cq build.\n \"\"\"\n # List of dicts containing 'build_config', 'buildbucket_id', 'url'\n tryjob_output = json.loads(output)\n return {t['build_config']: t['buildbucket_id'] for t in tryjob_output}\n\n def _LaunchTrybots(self, pool, configs, plan=None,\n sanity_check_build=False, swarming=True):\n \"\"\"Launch tryjobs on the configs with patches if provided.\n\n Args:\n pool: An instance of ValidationPool.validation_pool.\n configs: A list of pre-cq config names to launch.\n plan: A list of patches to test in the pre-cq tryjob, default to None.\n sanity_check_build: Boolean indicating whether to run the tryjobs as\n sanity-check-build.\n swarming: Boolean indicating jobs should running as swarming builds.\n\n Returns:\n A dict mapping from build_config (string) to the buildbucket_id (string)\n of the launched Pre-CQs. An empty dict if any configuration target doesn't\n exist.\n \"\"\"\n # Verify the configs to test are in the cbuildbot config list.\n for config in configs:\n if config not in self._run.site_config:\n logging.error('No such configuraton target: %s.', config)\n\n if plan is not None:\n for change in plan:\n logging.error('Skipping trybots on nonexistent config %s for '\n '%s %s', config, str(change), change.url)\n pool.HandleNoConfigTargetFailure(change, config)\n\n return {}\n\n cmd = ['cros', 'tryjob', '--yes', '--json',\n '--timeout', str(self.INFLIGHT_TIMEOUT * 60)] + configs\n\n if sanity_check_build:\n cmd += ['--sanity-check-build']\n\n if swarming:\n cmd += ['--swarming']\n\n if plan is not None:\n for patch in plan:\n cmd += ['-g', cros_patch.AddPrefix(patch, patch.gerrit_number)]\n self._PrintPatchStatus(patch, 'testing')\n\n config_buildbucket_id_map = {}\n if self._run.options.debug:\n logging.debug('Would have launched tryjob with %s', cmd)\n else:\n result = cros_build_lib.RunCommand(\n cmd, cwd=self._build_root, capture_output=True)\n if result and result.output:\n logging.info('output: %s' % result.output)\n config_buildbucket_id_map = self.GetConfigBuildbucketIdMap(\n result.output)\n\n return config_buildbucket_id_map\n\n def LaunchPreCQs(self, build_id, db, pool, configs, plan):\n \"\"\"Launch Pre-CQ tryjobs on the configs with patches.\n\n Args:\n build_id: build_id (string) of the pre-cq-launcher build.\n db: An instance of cidb.CIDBConnection.\n pool: An instance of ValidationPool.validation_pool.\n configs: A list of pre-cq config names to launch.\n plan: The list of patches to test in the pre-cq tryjob.\n \"\"\"\n logging.info('Launching Pre-CQs for configs %s with changes %s',\n configs, cros_patch.GetChangesAsString(plan))\n config_buildbucket_id_map = self._LaunchTrybots(pool, configs, plan=plan)\n\n if not config_buildbucket_id_map:\n return\n\n # Update cidb clActionTable.\n actions = []\n for config in configs:\n if config in config_buildbucket_id_map:\n for patch in plan:\n actions.append(clactions.CLAction.FromGerritPatchAndAction(\n patch, constants.CL_ACTION_TRYBOT_LAUNCHING, config,\n buildbucket_id=config_buildbucket_id_map[config]))\n\n db.InsertCLActions(build_id, actions)\n\n def LaunchSanityPreCQs(self, build_id, db, pool, configs):\n \"\"\"Launch Sanity-Pre-CQ tryjobs on the configs.\n\n Args:\n build_id: build_id (string) of the pre-cq-launcher build.\n db: An instance of cidb.CIDBConnection or None.\n pool: An instance of ValidationPool.validation_pool.\n configs: A set of pre-cq config names to launch.\n \"\"\"\n logging.info('Launching Sanity-Pre-CQs for configs %s.', configs)\n config_buildbucket_id_map = self._LaunchTrybots(\n pool, configs, sanity_check_build=True)\n\n if not config_buildbucket_id_map:\n return\n\n if db:\n launched_build_reqs = []\n for config in configs:\n launched_build_reqs.append(build_requests.BuildRequest(\n None, build_id, config, None, config_buildbucket_id_map[config],\n build_requests.REASON_SANITY_PRE_CQ, None))\n\n if launched_build_reqs:\n db.InsertBuildRequests(launched_build_reqs)\n\n def GetDisjointTransactionsToTest(self, pool, progress_map):\n \"\"\"Get the list of disjoint transactions to test.\n\n Side effect: reject or retry changes that have timed out.\n\n Args:\n pool: The validation pool.\n progress_map: See return type of clactions.GetPreCQProgressMap.\n\n Returns:\n A list of (transaction, config) tuples corresponding to different trybots\n that should be launched.\n \"\"\"\n # Get the set of busy and passed CLs.\n busy, _, verified = clactions.GetPreCQCategories(progress_map)\n\n screened_changes = set(progress_map)\n\n # Create a list of disjoint transactions to test.\n manifest = git.ManifestCheckout.Cached(self._build_root)\n logging.info('Creating disjoint transactions.')\n plans, failed = pool.CreateDisjointTransactions(\n manifest, screened_changes,\n max_txn_length=self.MAX_PATCHES_PER_TRYBOT_RUN)\n logging.info('Created %s disjoint transactions.', len(plans))\n\n # Note: |failed| is a list of cros_patch.PatchException instances.\n logging.info('Failed to apply %s CLs. Marked them as failed.', len(failed))\n for f in failed:\n pool.UpdateCLPreCQStatus(f.patch, constants.CL_STATUS_FAILED)\n\n for plan in plans:\n # If any of the CLs in the plan is not yet screened, wait for them to\n # be screened.\n #\n # If any of the CLs in the plan are currently \"busy\" being tested,\n # wait until they're done before starting to test this plan.\n #\n # Similarly, if all of the CLs in the plan have already been validated,\n # there's no need to launch a trybot run.\n plan = set(plan)\n if not plan.issubset(screened_changes):\n logging.info('CLs waiting to be screened: %s',\n cros_patch.GetChangesAsString(\n plan.difference(screened_changes)))\n elif plan.issubset(verified):\n logging.info('CLs already verified: %s',\n cros_patch.GetChangesAsString(plan))\n elif plan.intersection(busy):\n logging.info('CLs currently being verified: %s',\n cros_patch.GetChangesAsString(plan.intersection(busy)))\n if plan.difference(busy):\n logging.info('CLs waiting on verification of dependencies: %r',\n cros_patch.GetChangesAsString(plan.difference(busy)))\n # TODO(akeshet): Consider using a database time rather than gerrit\n # approval time and local clock for launch delay.\n elif any(x.approval_timestamp + self.LAUNCH_DELAY * 60 > time.time()\n for x in plan):\n logging.info('CLs waiting on launch delay: %s',\n cros_patch.GetChangesAsString(plan))\n else:\n pending_configs = clactions.GetPreCQConfigsToTest(plan, progress_map)\n for config in pending_configs:\n yield (plan, config)\n\n def _ProcessRequeuedAndSpeculative(self, change, action_history):\n \"\"\"Detect if |change| was requeued by developer, and mark in cidb.\n\n Args:\n change: GerritPatch instance to check.\n action_history: List of CLActions.\n \"\"\"\n action_string = clactions.GetRequeuedOrSpeculative(\n change, action_history, not change.IsMergeable())\n if action_string:\n build_id, db = self._run.GetCIDBHandle()\n action = clactions.CLAction.FromGerritPatchAndAction(\n change, action_string)\n db.InsertCLActions(build_id, [action])\n logging.info('Record change %s with action %s build_id %s.',\n change, action_string, build_id)\n\n def _ProcessExpiry(self, change, status, timestamp, pool, current_time):\n \"\"\"Enforce expiry of a PASSED or FULLY_VERIFIED status.\n\n Args:\n change: GerritPatch instance to process.\n status: |change|'s pre-cq status.\n timestamp: datetime.datetime for when |status| was achieved.\n pool: The current validation pool.\n current_time: datetime.datetime for current database time.\n \"\"\"\n if not timestamp:\n return\n timed_out = self._HasTimedOut(timestamp, current_time,\n self.STATUS_EXPIRY_TIMEOUT)\n verified = status in (constants.CL_STATUS_PASSED,\n constants.CL_STATUS_FULLY_VERIFIED)\n if timed_out and verified:\n msg = PRECQ_EXPIRY_MSG % self.STATUS_EXPIRY_TIMEOUT\n build_id, db = self._run.GetCIDBHandle()\n if db:\n pool.SendNotification(change, '%(details)s', details=msg)\n action = clactions.CLAction.FromGerritPatchAndAction(\n change, constants.CL_ACTION_PRE_CQ_RESET)\n db.InsertCLActions(build_id, [action])\n\n def _ProcessTimeouts(self, change, progress_map, pool, current_time):\n \"\"\"Enforce per-config launch and inflight timeouts.\n\n Args:\n change: GerritPatch instance to process.\n progress_map: See return type of clactions.GetPreCQProgressMap.\n pool: The current validation pool.\n current_time: datetime.datetime timestamp giving current database time.\n \"\"\"\n timeout_statuses = (constants.CL_PRECQ_CONFIG_STATUS_LAUNCHED,\n constants.CL_PRECQ_CONFIG_STATUS_INFLIGHT)\n config_progress = progress_map[change]\n for config, pre_cq_progress_tuple in config_progress.iteritems():\n if not pre_cq_progress_tuple.status in timeout_statuses:\n continue\n launched = (pre_cq_progress_tuple.status ==\n constants.CL_PRECQ_CONFIG_STATUS_LAUNCHED)\n timeout = self.LAUNCH_TIMEOUT if launched else self.INFLIGHT_TIMEOUT\n msg = (PRECQ_LAUNCH_TIMEOUT_MSG if launched\n else PRECQ_INFLIGHT_TIMEOUT_MSG) % (config, timeout)\n\n if self._HasTimedOut(pre_cq_progress_tuple.timestamp, current_time,\n timeout):\n pool.SendNotification(change, '%(details)s', details=msg)\n pool.RemoveReady(change, reason=config)\n pool.UpdateCLPreCQStatus(change, constants.CL_STATUS_FAILED)\n\n def _CancelPreCQIfNeeded(self, db, old_build_action):\n \"\"\"Cancel the pre-cq if it's still running.\n\n Args:\n db: CIDB connection instance.\n old_build_action: Old patch build action.\n \"\"\"\n buildbucket_id = old_build_action.buildbucket_id\n get_content = self.buildbucket_client.GetBuildRequest(\n buildbucket_id, dryrun=self._run.options.debug)\n\n status = buildbucket_lib.GetBuildStatus(get_content)\n if status in [constants.BUILDBUCKET_BUILDER_STATUS_SCHEDULED,\n constants.BUILDBUCKET_BUILDER_STATUS_STARTED]:\n logging.info('Cancelling old build buildbucket_id: %s, '\n 'current status: %s.', buildbucket_id, status)\n\n cancel_content = self.buildbucket_client.CancelBuildRequest(\n buildbucket_id, dryrun=self._run.options.debug)\n cancel_status = buildbucket_lib.GetBuildStatus(cancel_content)\n if cancel_status:\n logging.info('Cancelled old build buildbucket_id: %s, '\n 'current status: %s', buildbucket_id, cancel_status)\n metrics.Counter(constants.MON_BB_CANCEL_PRE_CQ_BUILD_COUNT).increment()\n\n if db:\n old_build = db.GetBuildStatusWithBuildbucketId(buildbucket_id)\n if old_build is not None:\n cancel_action = old_build_action._replace(\n action=constants.CL_ACTION_TRYBOT_CANCELLED)\n db.InsertCLActions(old_build['id'], [cancel_action])\n else:\n # If the old pre-cq build already completed, CANCEL response will\n # give 200 returncode with error reasons.\n logging.info('Failed to cancel build buildbucket_id: %s, reason: %s',\n buildbucket_id,\n buildbucket_lib.GetErrorReason(cancel_content))\n\n def _ProcessOldPatchPreCQRuns(self, db, change, action_history):\n \"\"\"Process Pre-cq runs for change with old patch numbers.\n\n Args:\n db: CIDB connection instance.\n change: GerritPatch instance to process.\n action_history: List of CLActions.\n \"\"\"\n min_timestamp = datetime.datetime.now() - datetime.timedelta(\n hours=self.BUILDBUCKET_DELTA_TIME_HOUR)\n old_pre_cq_build_actions = clactions.GetOldPreCQBuildActions(\n change, action_history, min_timestamp)\n for old_build_action in old_pre_cq_build_actions:\n try:\n self._CancelPreCQIfNeeded(db, old_build_action)\n except buildbucket_lib.BuildbucketResponseException as e:\n # Do not raise if it's buildbucket_lib.BuildbucketResponseException.\n logging.error('Failed to cancel the old pre cq run through Buildbucket.'\n ' change: %s buildbucket_id: %s error: %r',\n change, old_build_action.buildbucket_id, e)\n\n def _GetFailedPreCQConfigs(self, action_history):\n \"\"\"Get failed Pre-CQ build configs from action history.\n\n Args:\n action_history: A list of clactions.CLAction.\n\n Returns:\n A set of failed Pre-CQ build configs.\n \"\"\"\n failed_build_configs = set()\n for action in action_history:\n build_config = action.build_config\n if (build_config not in failed_build_configs and\n site_config.get(build_config) is not None and\n site_config[build_config].build_type == constants.PRE_CQ_TYPE and\n action.action == constants.CL_ACTION_PICKED_UP and\n action.status == constants.BUILDER_STATUS_FAILED):\n failed_build_configs.add(build_config)\n\n return failed_build_configs\n\n def _FailureStreakCounterExceedsThreshold(self, build_config, build_history):\n \"\"\"Check whether the consecutive failure counter exceeds the threshold.\n\n Args:\n db: CIDBConnection instance.\n build_config: The build config to check.\n build_history: A sorted list of dict containing build information. See\n Return types of cidb.CIDBConnection.GetBuildsHistory.\n\n Returns:\n A boolean indicating whether the consecutive failure counter of\n build_config exceeds its sanity_check_threshold.\n \"\"\"\n sanity_check_threshold = site_config[build_config].sanity_check_threshold\n\n if sanity_check_threshold <= 0:\n return False\n\n streak_counter = 0\n for build in build_history:\n if build['status'] == constants.BUILDER_STATUS_PASSED:\n return False\n elif build['status'] == constants.BUILDER_STATUS_FAILED:\n streak_counter += 1\n\n if streak_counter >= sanity_check_threshold:\n return True\n\n return False\n\n def _GetBuildConfigsToSanityCheck(self, db, build_configs):\n \"\"\"Get build configs to sanity check.\n\n Args:\n db: An instance of cidb.CIDBConnection.\n build_configs: A list of build configs (strings) to check whether to\n sanity check.\n\n Returns:\n A list of build_configs (strings) to sanity check.\n \"\"\"\n start_date = datetime.datetime.now().date() - datetime.timedelta(\n days=self.PRE_CQ_SANITY_CHECK_LOOK_BACK_HISTORY_DAYS)\n builds_history = db.GetBuildsHistory(\n build_configs, db.NUM_RESULTS_NO_LIMIT, start_date=start_date,\n final=True)\n build_history_by_build_config = cros_build_lib.GroupByKey(\n builds_history, 'build_config')\n\n start_time = datetime.datetime.now() - datetime.timedelta(\n hours=self.PRE_CQ_SANITY_CHECK_PERIOD_HOURS)\n builds_requests = db.GetBuildRequestsForBuildConfigs(\n build_configs, start_time=start_time)\n build_requests_by_build_config = cros_build_lib.GroupNamedtuplesByKey(\n builds_requests, 'request_build_config')\n\n sanity_check_build_configs = set()\n for build_config in build_configs:\n build_history = build_history_by_build_config.get(build_config, [])\n build_reqs = build_requests_by_build_config.get(build_config, [])\n if (build_history and\n not build_reqs and\n self._FailureStreakCounterExceedsThreshold(\n build_config, build_history)):\n sanity_check_build_configs.add(build_config)\n\n return list(sanity_check_build_configs)\n\n def _LaunchSanityCheckPreCQsIfNeeded(self, build_id, db, pool,\n action_history):\n \"\"\"Check the Pre-CQs of changes and launch Sanity-Pre-CQs if needed.\n\n Args:\n build_id: build_id (string) of the pre-cq-launcher build.\n db: An instance of cidb.CIDBConnection.\n pool: An instance of ValidationPool.validation_pool.\n action_history: A list of clactions.CLActions.\n \"\"\"\n failed_build_configs = self._GetFailedPreCQConfigs(action_history)\n\n if not failed_build_configs:\n return\n\n sanity_check_build_configs = self._GetBuildConfigsToSanityCheck(\n db, failed_build_configs)\n\n if sanity_check_build_configs:\n self.LaunchSanityPreCQs(build_id, db, pool, sanity_check_build_configs)\n\n def _ProcessVerified(self, change, can_submit, will_submit):\n \"\"\"Process a change that is fully pre-cq verified.\n\n Args:\n change: GerritPatch instance to process.\n can_submit: set of changes that can be submitted by the pre-cq.\n will_submit: set of changes that will be submitted by the pre-cq.\n\n Returns:\n A tuple of (set of changes that should be submitted by pre-cq,\n set of changes that should be passed by pre-cq)\n \"\"\"\n # If this change and all its dependencies are pre-cq submittable,\n # and none of them have yet been marked as pre-cq passed, then\n # mark them for submission. Otherwise, mark this change as passed.\n if change in will_submit:\n return set(), set()\n\n if change in can_submit:\n logging.info('Attempting to determine if %s can be submitted.', change)\n patches = patch_series.PatchSeries(self._build_root)\n try:\n plan = patches.CreateTransaction(change, limit_to=can_submit)\n return plan, set()\n except cros_patch.DependencyError:\n pass\n\n # Changes that cannot be submitted are marked as passed.\n return set(), set([change])\n\n def UpdateChangeStatuses(self, changes, status):\n \"\"\"Update |changes| to |status|.\n\n Args:\n changes: A set of GerritPatch instances.\n status: One of constants.CL_STATUS_* statuses.\n \"\"\"\n if changes:\n build_id, db = self._run.GetCIDBHandle()\n a = clactions.TranslatePreCQStatusToAction(status)\n actions = [clactions.CLAction.FromGerritPatchAndAction(c, a)\n for c in changes]\n db.InsertCLActions(build_id, actions)\n\n def _LaunchPreCQsIfNeeded(self, pool, changes):\n \"\"\"Find ready changes and launch Pre-CQs.\n\n Args:\n pool: An instance of ValidationPool.validation_pool.\n changes: GerritPatch instances.\n \"\"\"\n build_id, db = self._run.GetCIDBHandle()\n\n action_history, _, status_map = (\n self._GetUpdatedActionHistoryAndStatusMaps(db, changes))\n\n # Filter out failed speculative changes.\n changes = [c for c in changes if status_map[c] != constants.CL_STATUS_FAILED\n or c.HasReadyFlag()]\n\n progress_map = clactions.GetPreCQProgressMap(changes, action_history)\n\n # Filter out changes that have already failed, and aren't marked trybot\n # ready or commit ready, before launching.\n launchable_progress_map = {\n k: v for k, v in progress_map.iteritems()\n if k.HasReadyFlag() or status_map[k] != constants.CL_STATUS_FAILED}\n\n is_tree_open = tree_status.IsTreeOpen(throttled_ok=True)\n launch_count = 0\n cl_launch_count = 0\n launch_count_limit = (self.last_cycle_launch_count +\n self.MAX_LAUNCHES_PER_CYCLE_DERIVATIVE)\n\n launches = {}\n for plan, config in self.GetDisjointTransactionsToTest(\n pool, launchable_progress_map):\n launches.setdefault(frozenset(plan), []).append(config)\n\n for plan, configs in launches.iteritems():\n if not is_tree_open:\n logging.info('Tree is closed, not launching configs %r for plan %s.',\n configs, cros_patch.GetChangesAsString(plan))\n elif launch_count >= launch_count_limit:\n logging.info('Hit or exceeded maximum launch count of %s this cycle, '\n 'not launching configs %r for plan %s.',\n launch_count_limit, configs,\n cros_patch.GetChangesAsString(plan))\n else:\n self.LaunchPreCQs(build_id, db, pool, configs, plan)\n launch_count += len(configs)\n cl_launch_count += len(configs) * len(plan)\n\n metrics.Counter(constants.MON_PRECQ_LAUNCH_COUNT).increment_by(\n launch_count)\n metrics.Counter(constants.MON_PRECQ_CL_LAUNCH_COUNT).increment_by(\n cl_launch_count)\n metrics.Counter(constants.MON_PRECQ_TICK_COUNT).increment()\n\n self.last_cycle_launch_count = launch_count\n\n def _GetUpdatedActionHistoryAndStatusMaps(self, db, changes):\n \"\"\"Get updated action_history and Pre-CQ status for changes.\n\n Args:\n db: cidb.CIDBConnection instance.\n changes: GerritPatch instances to process.\n\n Returns:\n (The current CLAction list of the changes, the current map from changes to\n (status, timestamp) tuple, the current map from changes to status).\n \"\"\"\n action_history = db.GetActionsForChanges(changes)\n\n status_and_timestamp_map = {\n c: clactions.GetCLPreCQStatusAndTime(c, action_history)\n for c in changes}\n status_map = {c: v[0] for c, v in status_and_timestamp_map.items()}\n\n status_str_map = {c.PatchLink(): s for c, s in status_map.iteritems()}\n logging.info('Processing status_map: %s', pprint.pformat(status_str_map))\n\n return action_history, status_and_timestamp_map, status_map\n\n def ProcessChanges(self, pool, changes, _non_manifest_changes):\n \"\"\"Process a list of changes that were marked as Ready.\n\n From our list of changes that were marked as Ready, we create a\n list of disjoint transactions and send each one to a separate Pre-CQ\n trybot.\n\n Non-manifest changes are just submitted here because they don't need to be\n verified by either the Pre-CQ or CQ.\n \"\"\"\n build_id, db = self._run.GetCIDBHandle()\n\n action_history = db.GetActionsForChanges(changes)\n\n self._LaunchSanityCheckPreCQsIfNeeded(build_id, db, pool, action_history)\n\n if self.buildbucket_client is not None:\n for change in changes:\n self._ProcessOldPatchPreCQRuns(db, change, action_history)\n\n for change in changes:\n self._ProcessRequeuedAndSpeculative(change, action_history)\n\n action_history, status_and_timestamp_map, status_map = (\n self._GetUpdatedActionHistoryAndStatusMaps(db, changes))\n\n # Filter out failed speculative changes.\n changes = [c for c in changes if status_map[c] != constants.CL_STATUS_FAILED\n or c.HasReadyFlag()]\n\n progress_map = clactions.GetPreCQProgressMap(changes, action_history)\n busy, inflight, verified = clactions.GetPreCQCategories(progress_map)\n logging.info('Changes in busy: %s.\\nChanges in inflight: %s.\\nChanges in '\n 'verified: %s.',\n cros_patch.GetChangesAsString(busy),\n cros_patch.GetChangesAsString(inflight),\n cros_patch.GetChangesAsString(verified))\n\n current_db_time = db.GetTime()\n\n to_process = set(c for c in changes\n if status_map[c] != constants.CL_STATUS_PASSED)\n\n # Mark verified changes verified.\n to_mark_verified = [c for c in verified.intersection(to_process) if\n status_map[c] != constants.CL_STATUS_FULLY_VERIFIED]\n self.UpdateChangeStatuses(to_mark_verified,\n constants.CL_STATUS_FULLY_VERIFIED)\n # Send notifications to the fully verified changes.\n if to_mark_verified:\n pool.HandlePreCQSuccess(to_mark_verified)\n\n # Changes that can be submitted, if their dependencies can be too. Only\n # include changes that have not already been marked as passed.\n can_submit = set(c for c in (verified.intersection(to_process)) if\n c.IsMergeable() and self.CanSubmitChangeInPreCQ(c))\n\n self.SendChangeCountStats(status_map)\n\n # Changes that will be submitted.\n will_submit = set()\n # Changes that will be passed.\n will_pass = set()\n\n for change in inflight:\n if status_map[change] != constants.CL_STATUS_INFLIGHT:\n build_ids = [x.build_id for x in progress_map[change].values()]\n # Change the status to inflight.\n self.UpdateChangeStatuses([change], constants.CL_STATUS_INFLIGHT)\n build_dicts = db.GetBuildStatuses(build_ids)\n lines = []\n for b in build_dicts:\n url = tree_status.ConstructLegolandBuildURL(b['buildbucket_id'])\n lines.append('(%s) : %s ' % (b['build_config'], url))\n\n # Send notifications.\n pool.HandleApplySuccess(change, build_log=('\\n' + '\\n'.join(lines)))\n\n for change in to_process:\n # Detect if change is ready to be marked as passed, or ready to submit.\n if change in verified and change.IsMergeable():\n to_submit, to_pass = self._ProcessVerified(change, can_submit,\n will_submit)\n will_submit.update(to_submit)\n will_pass.update(to_pass)\n continue\n\n # Screen unscreened changes to determine which trybots to test them with.\n if not clactions.IsChangeScreened(change, action_history):\n self.ScreenChangeForPreCQ(change)\n continue\n\n self._ProcessTimeouts(change, progress_map, pool, current_db_time)\n\n # Mark passed changes as passed\n self.UpdateChangeStatuses(will_pass, constants.CL_STATUS_PASSED)\n\n # Expire any very stale passed or fully verified changes.\n for c, v in status_and_timestamp_map.items():\n self._ProcessExpiry(c, v[0], v[1], pool, current_db_time)\n\n # Submit changes that are ready to submit, if we can.\n if tree_status.IsTreeOpen(throttled_ok=True):\n pool.SubmitNonManifestChanges(check_tree_open=False,\n reason=constants.STRATEGY_NONMANIFEST)\n submit_reason = constants.STRATEGY_PRECQ_SUBMIT\n will_submit = {c:submit_reason for c in will_submit}\n submitted, _ = pool.SubmitChanges(will_submit, check_tree_open=False)\n\n # Record stats about submissions in monarch.\n if db:\n submitted_change_actions = db.GetActionsForChanges(submitted)\n strategies = {m: constants.STRATEGY_PRECQ_SUBMIT for m in submitted}\n clactions_metrics.RecordSubmissionMetrics(\n clactions.CLActionHistory(submitted_change_actions), strategies)\n\n self._LaunchPreCQsIfNeeded(pool, changes)\n\n # Tell ValidationPool to keep waiting for more changes until we hit\n # its internal timeout.\n return [], []\n\n def SendChangeCountStats(self, status_map):\n \"\"\"Sends metrics of the CL counts to Monarch.\n\n Args:\n status_map: A map from CLs to statuses.\n \"\"\"\n # Separately count and log the number of mergable and speculative changes in\n # each of the possible pre-cq statuses (or in status None).\n POSSIBLE_STATUSES = clactions.PRE_CQ_CL_STATUSES | {None}\n status_counts = {}\n for count_bin in itertools.product((True, False), POSSIBLE_STATUSES):\n status_counts[count_bin] = 0\n for c, status in status_map.iteritems():\n count_bin = (c.IsMergeable(), status)\n status_counts[count_bin] += 1\n for (is_mergable, status), count in sorted(status_counts.items()):\n subtype = 'mergeable' if is_mergable else 'speculative'\n metrics.Gauge('chromeos/cbuildbot/pre-cq/cl-count').set(\n count, {'status': str(status), 'subtype': subtype})\n\n @failures_lib.SetFailureType(failures_lib.InfrastructureFailure)\n def PerformStage(self):\n # Setup and initialize the repo.\n super(PreCQLauncherStage, self).PerformStage()\n\n query = constants.PRECQ_READY_QUERY\n if self._run.options.cq_gerrit_override:\n query = (self._run.options.cq_gerrit_override, None)\n\n # Loop through all of the changes until we hit a timeout.\n validation_pool.ValidationPool.AcquirePool(\n overlays=self._run.config.overlays,\n repo=self.repo,\n build_number=self._run.buildnumber,\n builder_name=self._run.GetBuilderName(),\n buildbucket_id=self._run.options.buildbucket_id,\n query=query,\n dryrun=self._run.options.debug,\n check_tree_open=False, change_filter=self.ProcessChanges,\n builder_run=self._run)\n","repo_name":"kiwibrowser/src","sub_path":"third_party/chromite/cbuildbot/stages/sync_stages.py","file_name":"sync_stages.py","file_ext":"py","file_size_in_byte":83398,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"21740201906","text":"from openerp.osv import osv,fields\n\nclass correct_time_wizard(osv.osv_memory):\n \n def _sale_line_get(self,cr,uid,task,context):\n #correct procurement\n procurement = task.procurement_id\n if procurement:\n sale_line_obj = self.pool.get(\"sale.order.line\") \n sale_line_ids = sale_line_obj.search(cr,uid,[(\"procurement_id\",\"=\",procurement.id)])\n if len(sale_line_ids)==1 :\n sale_line = sale_line_obj.browse(cr,uid,sale_line_ids[0],context)\n if sale_line.state in (\"draft\",\"confirmed\"):\n return sale_line \n return None\n \n \n def default_get(self, cr, uid, fields_list, context=None): \n res = {}\n active_id = context and context.get(\"active_id\") or None\n if active_id:\n task_obj = self.pool.get(\"project.task\")\n \n task = task_obj.browse(cr,uid,active_id,context)\n res[\"task_id\"]=task.id\n res[\"planned_hours\"]=task.planned_hours\n \n sale_line=self._sale_line_get(cr, uid, task, context)\n if sale_line:\n res[\"offered_hours\"]=sale_line.product_uom_qty\n res[\"correct_offered_hours\"]=True\n else:\n res[\"offered_hours\"]=0.0\n res[\"correct_offered_hours\"]=False \n \n return res\n \n \n def do_correction(self, cr, uid, ids, context=None):\n for obj in self.browse(cr, uid, ids,context=context):\n task = obj.task_id\n if task and task.state != \"done\":\n #correct task \n task_obj = self.pool.get(\"project.task\") \n task_obj.write(cr,uid,task.id,{\"planned_hours\" : obj.task_hours},context)\n \n #correct sale line\n if obj.correct_offered_hours:\n sale_line_obj = self.pool.get(\"sale.order.line\")\n sale_line = self._sale_line_get(cr, uid, task, context)\n if sale_line:\n sale_line_obj.write(cr,uid,sale_line.id,{\"product_uom_qty\" : obj.task_hours },context)\n sale_line_obj.write(cr,uid,sale_line.id,{\"product_uos_qty\" : obj.task_hours },context)\n \n return { \"type\" : \"ir.actions.act_window_close\" }\n \n \n _name = \"at_project_sale.correct_time_wizard\"\n _columns = {\n \"task_id\" : fields.many2one(\"project.task\",\"Task\"),\n \"task_hours\" : fields.float(\"Task Hours Correction\"),\n \"planned_hours\" : fields.float(\"Planned Hours\",readonly=True),\n \"offered_hours\" : fields.float(\"Offered Hours\",readonly=True),\n \"correct_offered_hours\" : fields.boolean(\"Correct offered Hours\")\n } ","repo_name":"funkring/fdoo","sub_path":"addons-funkring/at_project_sale/wizard/correct_time_wizard.py","file_name":"correct_time_wizard.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14508005192","text":"'''\nDay: 20\nFile: jurassic_jigsaw.py\nAuthor: Rishabh Ranjan\nLast Modified: 12/25/2020\n'''\n\ndef find_corners(edges, unique_edges, corners):\n product = 1\n for id in edges:\n num_uniques_edges = 0\n top_edge_unique = True\n right_edge_unique = True\n bottom_edge_unique = True\n left_edge_unique = True\n for tile_id in edges:\n if id != tile_id:\n for edge in edges[tile_id]:\n if edges[id][0] == edge or edges[id][0] == edge[::-1]:\n top_edge_unique = False\n if edges[id][1] == edge or edges[id][1] == edge[::-1]:\n right_edge_unique = False\n if edges[id][2] == edge or edges[id][2] == edge[::-1]:\n bottom_edge_unique = False\n if edges[id][3] == edge or edges[id][3] == edge[::-1]:\n left_edge_unique = False\n if top_edge_unique:\n num_uniques_edges += 1\n if id in unique_edges:\n unique_edges[id].append(0)\n else:\n unique_edges[id] = [0]\n if right_edge_unique:\n num_uniques_edges += 1\n if id in unique_edges:\n unique_edges[id].append(1)\n else:\n unique_edges[id] = [1]\n if bottom_edge_unique:\n num_uniques_edges += 1\n if id in unique_edges:\n unique_edges[id].append(2)\n else:\n unique_edges[id] = [2]\n if left_edge_unique:\n num_uniques_edges += 1\n if id in unique_edges:\n unique_edges[id].append(3)\n else:\n unique_edges[id] = [3]\n if num_uniques_edges == 2:\n product *= id\n corners.add(id)\n return edges, unique_edges, corners, product\n\ndef rotate_90_degrees(image):\n new_image = image.copy()\n for i in range(len(image[0])):\n for j in range(len(image)):\n new_image[i] = new_image[i][:j] + image[j][len(image) - 1 - i] + new_image[i][j + 1:]\n return new_image\n\ndef flip(image):\n new_image = image.copy()\n for i in range(len(image)):\n new_image[i] = image[i][::-1]\n return new_image\n\ndef insert_in_image(image, image_to_insert, row, col):\n for i in range(len(image_to_insert)):\n image[row + i] = image[row + i][:col] + image_to_insert[i] + image[row + i][col + len(image_to_insert[i]):]\n return image\n\ndef get_edges(tile):\n left_edge = \"\"\n right_edge = \"\"\n for i in range(len(tile)):\n left_edge += tile[i][0]\n right_edge += tile[i][9]\n return (tile[0], right_edge, tile[9][::-1], left_edge[::-1])\n\ndef match_to_right(image, current_tile_id, current_tile, current_tile_with_edges, current_tile_pos, edges, tiles, tiles_with_edges):\n current_tile_edges = get_edges(current_tile_with_edges)\n matching_tile_id = 0\n for id in edges:\n if id != current_tile_id:\n if edges[id][0] == current_tile_edges[1] or edges[id][0] == current_tile_edges[1][::-1]:\n matching_tile_id = id\n break\n if edges[id][1] == current_tile_edges[1] or edges[id][1] == current_tile_edges[1][::-1]:\n matching_tile_id = id\n break\n if edges[id][2] == current_tile_edges[1] or edges[id][2] == current_tile_edges[1][::-1]:\n matching_tile_id = id\n break\n if edges[id][3] == current_tile_edges[1] or edges[id][3] == current_tile_edges[1][::-1]:\n matching_tile_id = id\n break\n matching_tile = tiles[matching_tile_id]\n matching_tile_with_edges = tiles_with_edges[matching_tile_id]\n matching_tile_edges = get_edges(matching_tile_with_edges)\n num = 0\n while current_tile_edges[1] != matching_tile_edges[3][::-1]:\n if num == 3:\n matching_tile = flip(matching_tile)\n matching_tile_with_edges = flip(matching_tile_with_edges)\n else:\n matching_tile = rotate_90_degrees(matching_tile)\n matching_tile_with_edges = rotate_90_degrees(matching_tile_with_edges)\n matching_tile_edges = get_edges(matching_tile_with_edges)\n num += 1\n image = insert_in_image(image, matching_tile, current_tile_pos[0], current_tile_pos[1] + 8)\n current_tile_id = matching_tile_id\n current_tile = matching_tile\n current_tile_with_edges = matching_tile_with_edges\n current_tile_pos = (current_tile_pos[0], current_tile_pos[1] + 8)\n return image, current_tile_id, current_tile, current_tile_with_edges, current_tile_pos\n\ndef match_to_bottom(image, current_tile_id, current_tile, current_tile_with_edges, current_tile_pos, edges, tiles, tiles_with_edges):\n current_tile_edges = get_edges(current_tile_with_edges)\n matching_tile_id = 0\n for id in edges:\n if id != current_tile_id:\n if edges[id][0] == current_tile_edges[2] or edges[id][0] == current_tile_edges[2][::-1]:\n matching_tile_id = id\n break\n if edges[id][1] == current_tile_edges[2] or edges[id][1] == current_tile_edges[2][::-1]:\n matching_tile_id = id\n break\n if edges[id][2] == current_tile_edges[2] or edges[id][2] == current_tile_edges[2][::-1]:\n matching_tile_id = id\n break\n if edges[id][3] == current_tile_edges[2] or edges[id][3] == current_tile_edges[2][::-1]:\n matching_tile_id = id\n break\n matching_tile = tiles[matching_tile_id]\n matching_tile_with_edges = tiles_with_edges[matching_tile_id]\n matching_tile_edges = get_edges(matching_tile_with_edges)\n num = 0\n while current_tile_edges[2] != matching_tile_edges[0][::-1]:\n if num == 3:\n matching_tile = flip(matching_tile)\n matching_tile_with_edges = flip(matching_tile_with_edges)\n else:\n matching_tile = rotate_90_degrees(matching_tile)\n matching_tile_with_edges = rotate_90_degrees(matching_tile_with_edges)\n matching_tile_edges = get_edges(matching_tile_with_edges)\n num += 1\n image = insert_in_image(image, matching_tile, current_tile_pos[0] + 8, current_tile_pos[1])\n current_tile_id = matching_tile_id\n current_tile = matching_tile\n current_tile_with_edges = matching_tile_with_edges\n current_tile_pos = (current_tile_pos[0] + 8, current_tile_pos[1])\n return image, current_tile_id, current_tile, current_tile_with_edges, current_tile_pos\n\ndef count_sea_monsters(image, sea_monster):\n count = 0\n for i in range(len(image) - len(sea_monster) + 1):\n for j in range(len(image[0]) - len(sea_monster[0]) + 1):\n sea_monster_present = True\n for k in range(len(sea_monster)):\n for l in range(len(sea_monster[0])):\n if sea_monster[k][l] == '#' and image[i + k][j + l] != '#':\n sea_monster_present = False\n if sea_monster_present:\n count += 1\n return count\n\ndef main():\n f = open('day_20_input.txt', 'r')\n input = f.read().splitlines()\n f.close()\n edges = {}\n tiles = {}\n tiles_with_edges = {}\n unique_edges = {}\n corners = set()\n for i in range(len(input)):\n if input[i].startswith(\"Tile\"):\n left_edge = \"\"\n right_edge = \"\"\n for j in range(1, 11):\n left_edge += input[i + j][0]\n right_edge += input[i + j][9]\n edges[int(input[i][5:9])] = (input[i + 1], right_edge, input[i + 10][::-1], left_edge[::-1])\n tiles[int(input[i][5:9])] = [input[i + j][1:9] for j in range(2, 10)]\n tiles_with_edges[int(input[i][5:9])] = [input[i + j] for j in range(1, 11)]\n edges, unique_edges, corners, product = find_corners(edges, unique_edges, corners)\n print(\"Part 1 Answer: \", product)\n corner_id = next(iter(corners))\n corner = tiles[corner_id]\n corner_with_edges = tiles_with_edges[corner_id]\n if 0 in unique_edges[corner_id] and 1 in unique_edges[corner_id]:\n corner = rotate_90_degrees(corner)\n corner_with_edges = rotate_90_degrees(corner_with_edges)\n elif 1 in unique_edges[corner_id] and 2 in unique_edges[corner_id]:\n corner = rotate_90_degrees(corner)\n corner = rotate_90_degrees(corner)\n corner_with_edges = rotate_90_degrees(corner_with_edges)\n corner_with_edges = rotate_90_degrees(corner_with_edges)\n elif 2 in unique_edges[corner_id] and 3 in unique_edges[corner_id]:\n corner = rotate_90_degrees(corner)\n corner = rotate_90_degrees(corner)\n corner = rotate_90_degrees(corner)\n corner_with_edges = rotate_90_degrees(corner_with_edges)\n corner_with_edges = rotate_90_degrees(corner_with_edges)\n corner_with_edges = rotate_90_degrees(corner_with_edges)\n image_line = \"\"\n for i in range(12):\n image_line += \"........\"\n image = [image_line for i in range(96)]\n image = insert_in_image(image, corner, 0, 0)\n current_tile_id = corner_id\n current_tile = corner\n current_tile_with_edges = corner_with_edges\n current_tile_pos = (0, 0)\n for i in range(12):\n leftmost_current_tile_id = current_tile_id\n leftmost_current_tile = current_tile\n leftmost_current_tile_with_edges = current_tile_with_edges\n leftmost_current_tile_pos = current_tile_pos\n for j in range(11):\n image, current_tile_id, current_tile, current_tile_with_edges, current_tile_pos = match_to_right(image,\n current_tile_id, current_tile, current_tile_with_edges, current_tile_pos, edges, tiles, tiles_with_edges)\n if i == 11:\n break\n image, current_tile_id, current_tile, current_tile_with_edges, current_tile_pos = match_to_bottom(image,\n leftmost_current_tile_id, leftmost_current_tile, leftmost_current_tile_with_edges, leftmost_current_tile_pos, edges, tiles, tiles_with_edges)\n sea_monster = [\" # \", \"# ## ## ###\", \" # # # # # # \"]\n sea_monster_count = count_sea_monsters(image, sea_monster)\n num = 0\n while sea_monster_count <= 0:\n if num == 3:\n image = flip(image)\n else:\n image = rotate_90_degrees(image)\n sea_monster_count = count_sea_monsters(image, sea_monster)\n num += 1\n hashtag_count = 0\n for line in image:\n for item in line:\n if item == '#':\n hashtag_count += 1\n print(\"Part 2 Answer: \", hashtag_count - sea_monster_count * 15)\n\nif __name__ == '__main__':\n main()\n","repo_name":"rranjan11/Advent-of-Code-2020","sub_path":"jurassic_jigsaw.py","file_name":"jurassic_jigsaw.py","file_ext":"py","file_size_in_byte":10732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11891170502","text":"import json\nimport os\nimport re\n\nall_exts = ['.bam', '.bedgraph', '.bin', '.bw', '.csv', '.fastq', '.json', '.log', '.pdf', '.sam', '.tab', '.txt']\n\ndef parse_fastq_filename(fname, regex=r'.+_([R,I][1,2,3])\\.f'):\n m = re.match(regex, fname)\n if m:\n return m.group(1)\n else:\n return None\n\ndef get_fastqs_per_end(path_seq, paired=False, fastq_exts=None, read_regexs=None):\n if fastq_exts is None:\n fastq_exts = ['.fastq']\n if read_regexs is None:\n if paired:\n read_regexs = [r'.+_(R1)(\\.f|_)', r'.+_(R2)(\\.f|_)']\n else:\n read_regexs = [r'.+_(R1)(\\.f|_)']\n fastqs = [[] for i in range(len(read_regexs))]\n for path, dirs, files in os.walk(path_seq, followlinks=True):\n for fname in files:\n if any([fname.endswith(e) for e in fastq_exts]):\n for i, read_regex in enumerate(read_regexs):\n m = parse_fastq_filename(fname, read_regex)\n if m is not None:\n fastqs[i].append(os.path.join(path, fname))\n return fastqs\n\ndef write_report(fname, report):\n json.dump(report, open(fname+'.json', 'w'), sort_keys=True, indent=4, separators=(',', ': '))\n\ndef label2var(label):\n if label is None:\n return None\n else:\n return label.replace(' ', '_').replace('-', '_').replace('%', 'p').replace('/', '_')\n\ndef get_first_key(l, d):\n for k in l:\n if k in d:\n return d[k]\n","repo_name":"vejnar/LabxPipe","sub_path":"src/labxpipe/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"21666751547","text":"import string\nfrom turtle import Turtle\n\n\nclass Scoreboard(Turtle):\n def __init__(self) -> None:\n super().__init__()\n self.color(\"white\")\n self.penup()\n self.hideturtle()\n self.speed(\"fastest\")\n self.l_score = 0\n self.r_score = 0\n\n def write_score(self):\n self.clear()\n # Right score:\n self.goto(100, 175)\n self.write(self.r_score, align=\"center\",\n font=(\"Courier\", 80, \"normal\"))\n\n # Left score:\n self.goto(-100, 175)\n self.write(self.l_score, align=\"center\",\n font=(\"Courier\", 80, \"normal\"))\n\n def increase_score_for(self, l_or_r: string):\n if l_or_r.lower() == \"left\":\n self.l_score += 1\n elif l_or_r.lower() == \"right\":\n self.r_score += 1\n\n self.write_score()\n","repo_name":"arbenkryemadhi/100-days-of-code-python","sub_path":"Exercises/22 The Pong Game/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"40944555939","text":"def nobel_int(A):\r\n # A is the list\r\n # sorting the list\r\n A.sort()\r\n # traversing the list\r\n for i in range(0,len(A)-1):\r\n # in case of duplicates values\r\n if A[i] == A[i+1]:\r\n continue\r\n if A[i] == len(A) - i - 1:\r\n return True\r\n if A[-1] == 0:\r\n return True\r\n return False\r\n\r\n# checking the test case\r\nA = [2,3,4]\r\nans = nobel_int(A)\r\nprint(ans)\r\n\r\n\r\n","repo_name":"Ranjit007ai/InterviewBit-ArrayBasedSolutions","sub_path":"Array_based_problems/Nobel_Integer/solution.py","file_name":"solution.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":"70962878885","text":"import copy\nimport fold_evaluator as feval\n\n\nclass cross_validation:\n def __init__(self, model, gt_fname, folds, test=True, tune=False):\n self.performances = []\n self.dev_pers = []\n self.model = model\n # self.model_paras = model_paras\n self.folds = folds\n self.gt_fname = gt_fname\n self.test = test\n self.tune = tune\n self.evaluators = []\n self.dev_evas = []\n if self.test:\n for i in range(self.folds):\n fname = self.gt_fname.replace('.csv', 'fold' + str(i) + '.csv')\n self.evaluators.append(feval.fold_evaluator(fname))\n if self.tune:\n for i in range(self.folds):\n fname = self.gt_fname.replace('.csv', 'fold' + str(i) + '_comp.csv')\n self.dev_evas.append(feval.fold_evaluator(fname))\n\n def validate(self):\n if self.test:\n del self.performances[:]\n generated_ranking = self.model.ranking()\n for i in range(self.folds):\n self.performances.append(self.evaluators[i].evaluate(generated_ranking))\n if self.tune:\n del self.dev_pers[:]\n generated_ranking = self.model.ranking()\n for i in range(self.folds):\n self.dev_pers.append(self.dev_evas[i].evaluate(generated_ranking))\n\n def testing(self, model_paras_folds):\n assert len(model_paras_folds) == self.folds, '#folds not equals to #model_paras given'\n del self.performances[:]\n for i in range(self.folds):\n self.model.model_para = model_paras_folds[i]\n generated_ranking = self.model.ranking()\n self.performances.append(self.evaluators[i].evaluate(generated_ranking))","repo_name":"fulifeng/cur","sub_path":"code/cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"14480586014","text":"import os\nimport sys\n\nparentdir = os.path.dirname(os.getcwd())\nsys.path.insert(0, parentdir)\n\nfrom insta_post_processor.post_handler import PostHandler\n\nfrom bag_creator import BagCreator\nfrom text_preparer import TextPreparer\n\nclass NLPPostHandler(PostHandler):\n def __init__(self, text_preparer, bag_creators):\n self.text_preparer = text_preparer\n self.bag_creators = bag_creators\n\n def process(self, data):\n words = self.text_preparer.text_conversion(data[1])\n bags = list()\n for category in data[2]:\n creator = self.bag_creators.get(category, None)\n if creator:\n bag = creator.bag_create(words)\n bags.append(bag)\n return data[0], bags\n","repo_name":"IvanFitiskin/nlp_processor","sub_path":"nlp_post_handler.py","file_name":"nlp_post_handler.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36188498655","text":"# -*- coding: utf-8 -*-\nfrom flow import Flow\n\n# values = {'A': [4, 12, 5], 'B': [7, 10, 9], 'C': [7, 7, 10]}\n# utilities = {'A': [4, 12, 5], 'B': [7, 10, 9], 'C': [7, 7, 10]}\n# prices = [0, 0, 0]\n#\n# seedData = {'X': {'A', 'B', 'C'}, 'Y': {1, 2, 3}, 'values': values, 'utilities': utilities}\n\ndef getMarketEquilibrium(seedData, prices):\n # initialize the graph and find the constritcted set of items\n testGraph = Flow(seedData, prices, True)\n constSet = testGraph.findConstrictedSet()\n # print(constSet)\n prices = prices\n while len(constSet) > 0:\n # raise the price by 1 for every item in the constricted set\n for y in constSet:\n currentPrice = prices[y - 1]\n newPrice = currentPrice + 1\n prices[y - 1] = newPrice\n if min(prices) > 0:\n downShiftedPrices = [p - 1 for p in prices]\n # print('SHIFTING', prices, downShiftedPrices)\n prices = downShiftedPrices\n testGraph = Flow(seedData, prices, True)\n constSet = testGraph.findConstrictedSet()\n return testGraph.findPerfectMatching()\n # print(prices)\n\n# getMarketEquilibrium(seedData, prices)\n","repo_name":"nmadd/nm_hw3","sub_path":"market_equilib.py","file_name":"market_equilib.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36726399127","text":"import numpy as np\nimport cv2\n\n\ndef filter_region(image, verticles):\n \"\"\"\n\n :param image:\n :param verticles:\n :return:\n \"\"\"\n mask = np.zeros_like(image)\n if len(mask.shape) == 2:\n cv2.fillPoly(mask, verticles, 255)\n else:\n cv2.fillPoly(mask, verticles, (255, )*mask.shape[2])\n\n return cv2.bitwise_and(image, mask)\n\n\ndef select_region(image):\n \"\"\"\n\n :param image:\n :return:\n \"\"\"\n\n rows, cols = image.shape[:2]\n bottom_left = [cols*0.1, rows*0.92] # [cols*0.1, rows*0.95]\n top_left = [cols*0.35, rows*0.6] # [cols*0.3, rows*0.6]\n bottom_right = [cols*0.9, rows*0.92] # [cols*0.9, rows*0.95]\n top_right = [cols*0.65, rows*0.6] # [cols*0.6, rows*0.6]\n\n verticles = np.array([[bottom_left, top_left, top_right, bottom_right]], dtype=np.int32)\n\n return filter_region(image, verticles)\n\n\ndef average_slope_intercept(lines):\n left_lines = [] # (slope, intercept)\n left_weights = [] # (length,)\n right_lines = [] # (slope, intercept)\n right_weights = [] # (length,)\n\n for line in lines:\n for x1, y1, x2, y2 in line:\n if x2 == x1:\n continue # ignore a vertical line\n slope = (y2 - y1) / (x2 - x1)\n intercept = y1 - slope * x1\n length = np.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)\n if slope < 0: # y is reversed in image\n left_lines.append((slope, intercept))\n left_weights.append((length))\n else:\n right_lines.append((slope, intercept))\n right_weights.append((length))\n\n # add more weight to longer lines\n left_lane = np.dot(left_weights, left_lines) / np.sum(left_weights) if len(left_weights) > 0 else None\n right_lane = np.dot(right_weights, right_lines) / np.sum(right_weights) if len(right_weights) > 0 else None\n\n return left_lane, right_lane # (slope, intercept), (slope, intercept)\n\n\ndef make_line_points(y1, y2, line, line_prev):\n \"\"\"\n Convert a line represented in slope and intercept into pixel points\n \"\"\"\n if line is None:\n return None\n\n slope, intercept = line\n slope_prev, intercept_prev = line_prev\n\n slope = (slope + slope_prev)/2\n intercept = (intercept + intercept_prev)/2\n\n ALOT = 1e6\n\n # make sure everything is integer as cv2.line requires it\n x1 = max(min((y1 - intercept) / slope, ALOT), -ALOT) # limit values before we try to convert them to integer\n x1 = int(x1)\n x2 = max(min((y2 - intercept) / slope, ALOT), -ALOT)\n x2 = int(x2)\n y1 = int(y1)\n y2 = int(y2)\n\n return ((x1, y1), (x2, y2))\n\n\n# cap = cv2.VideoCapture('Driving - 800.mp4')\ncap = cv2.VideoCapture('Self Driving Car_ Vehicle Detection.mp4')\nleft_line_prev = np.array([0, 0])\nright_line_prev = np.array([0, 0])\n\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n\n if ret:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n kernel_size = 9\n blurred = cv2.GaussianBlur(gray, (kernel_size, kernel_size), 0)\n\n edges = cv2.Canny(blurred, 45, 100) # (blurred, 50, 150)\n\n area = select_region(edges)\n\n lines = cv2.HoughLinesP(area, rho=1, theta=np.pi/180, threshold=30, minLineLength=20, maxLineGap=200)\n # lines = cv2.HoughLinesP(area, rho=1, theta=np.pi / 180, threshold=30, minLineLength=20, maxLineGap=200)\n\n if lines is not None:\n left_lane, right_lane = average_slope_intercept(lines)\n\n if left_lane is not None:\n np_left_lane = np.array(left_lane)\n left_line_prev = (np_left_lane + left_line_prev)/2\n\n left_lane = left_line_prev.tolist()\n\n if right_lane is not None:\n np_right_lane = np.array(right_lane)\n right_line_prev = (np_right_lane + right_line_prev) / 2\n\n right_lane = right_line_prev.tolist()\n\n y1 = gray.shape[0] # bottom of the image\n y2 = y1 * 0.6 # slightly lower than the middle\n\n left_line = make_line_points(y1, y2, left_lane, left_line_prev)\n right_line = make_line_points(y1, y2, right_lane, right_line_prev)\n\n # print(left_line)\n # print(right_line)\n\n lines = [left_line, right_line]\n\n try:\n for line in lines:\n X, Y = line\n cv2.line(frame, X, Y, (0, 255, 0), 2)\n except:\n pass\n\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"janlehky/Robotik","sub_path":"video/Open_CV_lines_video.py","file_name":"Open_CV_lines_video.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23799579833","text":"\n\"\"\"\nChapter 3: 모델링 - Normal Equation\n\n행렬 연산을 통한 최소제곱법을 구현하기 위해 Normal Equation의 연산 과정을 모듈로 만들어 보겠습니다.\nModel 클래스를 상속받아 사용하겠습니다.\n주어진 라이브러리 이외에 다른 라이브러리는 사용하지 않습니다.\n\n1. normal_eq : Model 클래스를 통해 입력받은 데이터에 대해 회귀모형을 적합하고, 예측값과 회귀계수를 반환합니다.\n\"\"\"\n\nimport numpy as np\nfrom model import Model\nimport pandas as pd\n\nclass LSE(Model): ### 클래스의 부모 클래스로 Model 사용을 위함 -> 이를 상속이라고 한다.\n # 1. Model 클래스가 LSE 클래스의 부모 클래스가 될 수 있도록 코드를 작성해 주세요. (HINT: 괄호 안에 코드를 작성하세요.)\n def __init__(self ,X_mat ,Y_mat):\n super().__init__(X_mat, Y_mat) \n # super().__init__()이라는 코드가 다른 클래스의 속성 및 메소드를 자동으로 불러와 해당 클래스에서도 사용이 가능하도록 도와준다.\n\n\n def normal_eq(self):\n \"\"\"\n :return: self.theta, self.train_pred\n \"\"\"\n # 2. X의 전치행렬과 X를 곱한 후 그 역행렬을 구하여 inverse 객체에 저장하세요 (HINT: np.matmul, np.linalg.inv를 사용하세요.)\n ## 전치행렬과 기본 행렬의 곱\n transpose = np.matmul((self.X_mat).T,self.X_mat)\n ## 역행렬을 구하기 -> inverse에 담기\n inverse_mat = np.linalg.inv(transpose)\n ## 역행렬과 x의 전치 행렬 곱하기\n semi = np.matmul(inverse_mat, (self.X_mat).T)\n ### Y와 곱해서 회귀 계수를 구하기\n self.theta = np.matmul(semi, self.Y_mat)\n self.theta = list(pd.DataFrame(self.theta.tolist())[0])\n # 4. X와 회귀계수를 곱하여 얻은 예측값을 self.train_pred 객체에 저장\n self.train_pred = np.matmul(self.X_mat, self.theta)\n self.train_pred = list(pd.DataFrame(self.train_pred.tolist())[0])\n ## return으로 던져주기\n return self.theta, self.train_pred\n\n \n \n \n \n \n \n \n ","repo_name":"JunseoKim0103/PSAT_Package_python","sub_path":"psat_week1/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25298732967","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 14 17:49:41 2019\n\n@author: Arnold\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\n\nfrom keras.models import Model\nfrom keras.layers import Input, Embedding, Flatten, Dense, Concatenate\nfrom keras.layers import Dropout, BatchNormalization, Activation\nfrom keras.regularizers import l2\nfrom keras.optimizers import SGD, Adam\n\n# load in the data\ndata = pd.read_csv('user_business_preprocess.csv', index_col = 0)\n\nrow_no = sum(data.count())\nN = data.shape[0] # number of users\nM = data.shape[1] # number of busniesses\n\n# store columns and rows name\ncolumns_name = list(data.columns.values)\nrows_name = list(data.index)\n\n# build column_no by 3 matrix \nmatrix = np.empty((row_no, 3), dtype= float)\n\ndata = data.fillna(0)\nk = 0\n#data.iloc[0].name \n#data.columns[1]\nfor i in range(0,data.shape[0]):\n for j in range(0, data.shape[1]):\n if data[data.columns[j]][data.iloc[i].name] != 0:\n matrix[k][0] = rows_name.index(data.iloc[i].name) + 1\n matrix[k][1] = columns_name.index(data.columns[j]) + 1\n matrix[k][2] = data[data.columns[j]][data.iloc[i].name]\n k += 1\n \nmatrix = pd.DataFrame(matrix)\nmatrix.columns = ['User', 'Business', 'Rating']\n\"\"\"\nmatrix.to_csv('user_business_rating_matrix.csv', sep = \",\")\ndata_nn = pd.read_csv('user_business_rating_matrix.csv', sep = \",\", index_col = 0)\n\"\"\"\n# split into train and test\ndata_nn = shuffle(matrix)\ncutoff = int(0.8*len(data_nn))\ndata_train = data_nn.iloc[:cutoff]\ndata_test = data_nn.iloc[cutoff:]\n\ndata_test.User.values\n\n# initialize variables\nK = 10 # latent dimensionality\nmu = data_train.Rating.mean()\nepochs = 15\nreg = 0.0001 # regularization penalty\n\n\n# keras model\nu = Input(shape=(1,))\nm = Input(shape=(1,))\nu_embedding = Embedding(N, K, embeddings_regularizer = l2(reg))(u) # (N, 1, K)\nm_embedding = Embedding(M, K, embeddings_regularizer = l2(reg))(m) # (N, 1, K)\nu_embedding = Flatten()(u_embedding) # (N, K)\nm_embedding = Flatten()(m_embedding) # (N, K)\nx = Concatenate()([u_embedding, m_embedding]) # (N, 2K)\n\n# the neural network\nx = Dense(400)(x)\n# x = BatchNormalization()(x)\nx = Activation('relu')(x)\n# x = Dropout(0.5)(x)\n# x = Dense(100)(x)\n# x = BatchNormalization()(x)\n# x = Activation('relu')(x)\nx = Dense(1)(x)\n\nmodel = Model(inputs=[u, m], outputs=x)\nmodel.compile(\n loss='mse',\n # optimizer='adam',\n # optimizer=Adam(lr=0.01),\n optimizer=SGD(lr=0.08, momentum=0.9),\n metrics=['mse'],\n)\n\nr = model.fit(\n x=[data_train.User.values, data_train.Business.values],\n y=data_train.Rating.values - mu,\n epochs=epochs,\n batch_size=128,\n validation_data=(\n [data_test.User.values, data_test.Business.values],\n data_test.Rating.values - mu\n )\n)\n\nr.history\n\n# plot losses\nplt.plot(r.history['loss'], label=\"train loss\")\nplt.plot(r.history['val_loss'], label=\"test loss\")\nplt.legend()\nplt.show()\n\n# plot mse\nplt.plot(r.history['mean_squared_error'], label=\"train mse\")\nplt.plot(r.history['val_mean_squared_error'], label=\"test mse\")\nplt.legend()\nplt.show()\n\n\nbusiness = pd.read_csv('business_preprocess_filtered.csv')\n\ndef calculateReleventR(dict_, N):\n\n sorted_x = sorted(dict_.items(), key=lambda kv: kv[1], reverse = True)\n if len(sorted_x) >= N:\n a11 = sorted_x[:N]\n else:\n a11 = sorted_x\n list_ = {}\n for i in range(0,len(a11)):\n list_[a11[i][0]] = i\n \n result = [0] * N\n for row in business.iterrows():\n if row[1]['business_id'] in list_:\n if row[1]['stars'] >= 3.5:\n result[list_[row[1]['business_id']]] = 1\n return result\n\ndef averagePercision( list_):\n m = sum(list_)\n if m == 0:\n return 0\n k = len(list_)\n ap = 0.0\n for i in range(0,k):\n ap += float(sum(list_[0:i+1]))/float(len(list_[0:i+1]))*list_[i]\n return ap/float(m)\n \ndef averageRecall(list_):\n \n m = sum(list_)\n if m == 0:\n return 0\n k = len(list_)\n ar = 0.0\n for i in range(0,k):\n ar += float(sum(list_[0:i+1]))/float(m)*list_[i]\n \n return ar/float(m)\n\n# build user-business dictionary\n\n\ndict_ = {}\nfor k in range(0,N):\n dict_[k] = {}\n u_b = np.zeros((M,2),dtype = int)\n for i in range(0, M):\n u_b[i][0] = k+1\n u_b[i][1] = i+1\n u_b = pd.DataFrame(u_b)\n u_b.columns = ['User', 'Business']\n predict_ = model.predict(x = [u_b.User.values, u_b.Business.values])\n predict_ = pd.DataFrame(predict_)\n predict_.columns = ['Rating']\n final_result = pd.concat([u_b,predict_], axis = 1)\n for i in range(0,M):\n dict_[k][columns_name[final_result['Business'][i]-1]] = final_result['Rating'][i] + mu\n\nsum_ap = 0\nsum_ar = 0\n \nfor k, v in dict_.items():\n result = calculateReleventR(v,10)\n ap = averagePercision(result)\n ar = averageRecall(result)\n sum_ap += ap\n sum_ar += ar\n\n# sum_ap = 15827.652876984112\n# sum_ar = 8690.000000001228\nmeanap = sum_ap / float(data.shape[0]) #0.9887339378425857\nmeanar = sum_ar / float(data.shape[0]) #0.54285357321347\n\nprint(\"MAP@10: %f\" %meanap)\nprint(\"MAR@10: %f\" %meanar)\n\n\n\n\n\n\n\n# predict \"'-318sKiQDgbjLzF4FCU1XA'\"\nindex_user = rows_name.index(\"'-318sKiQDgbjLzF4FCU1XA'\")\nu_b_array = np.zeros((M,2),dtype = int)\nfor i in range(0,M):\n u_b_array[i][0] = index_user+1\n u_b_array[i][1] = i+1\nu_b_array = pd.DataFrame(u_b_array)\nu_b_array.columns = ['User', 'Business']\npredict_y = model.predict(x = [u_b_array.User.values, u_b_array.Business.values])\npredict_y = pd.DataFrame(predict_y)\npredict_y.columns = ['Rating']\nfinal_result = pd.concat([u_b_array,predict_y], axis = 1)\nfinal_result = final_result.sort_values(by = ['Rating'], ascending=False)\n\n# Store business id \ndict_ = {}\nfor i in range(0,10):\n dict_[i+1] = columns_name[final_result.iloc[i].name]\n\n# print the top 10 results \n \nsorted_x = sorted(dict_.items(), key=lambda kv: kv[1], reverse = True)\nif len(sorted_x) >= 10:\n a11 = sorted_x[:10]\nelse:\n a11 = sorted_x\n# store the top 10 buisness_id\nlist_ = {}\nfor i in range(0,len(a11)):\n list_[a11[i][1]] = a11[i][0]\n \nfor row in business.iterrows():\n if row[1]['business_id'] in list_:\n list_[row[1]['business_id']] = (list_[row[1]['business_id']] ,row[1]['name'] + row[1]['address'] + row[1]['city']+ row[1]['state'] + row[1]['postal_code']) \n \ndict4 = {}\nfor k,v in list_.items():\n dict4[v[0]] = v[1]\nfor k in sorted(dict4.keys()):\n print(k, dict4[k])\n \n\n\n","repo_name":"jyu13/Recommendation-System-on-Yelp-Dataset","sub_path":"5.MF and NN/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":6570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37750589643","text":"from rest_framework import viewsets, permissions\nfrom rest_framework.response import Response\nfrom .models import Warmups\nfrom django.db import connection\nfrom django.http import JsonResponse\nfrom django.core import serializers\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view\nfrom accounts.models import NewUser\nfrom django.db import connection\nimport json\nfrom rest_framework.permissions import AllowAny\nfrom django.core.serializers.json import DjangoJSONEncoder\nimport itertools\nfrom http import HTTPStatus\nfrom rest_framework.exceptions import ValidationError, ParseError\n\n\n# --------------------- Delete WarmUps ----------------------------#\n\n@csrf_exempt\n@api_view(['POST', ])\ndef SaveWarmUps_view(request):\n\n permission_classes = (permissions.IsAuthenticated,)\n\n if request.data['is_staff'] ==0:\n return Response(status=HTTPStatus.HTTP_406_NOT_ACCEPTABLE)\n else:\n try:\n cursor = connection.cursor()\n cursor.execute('''INSERT INTO rbkbackend.warmups\n (mark,notes,day_id,staff_name_id,student_name_id,week_id,cohort_id)\n VALUES \n ( %s, %s, %s, %s, %s, %s, %s);''',\n [\n request.data[\"mark\"],\n request.data[\"notes\"],\n request.data[\"day_id\"],\n request.data[\"staff_id\"],\n request.data[\"student_id\"],\n request.data[\"week_id\"],\n request.data[\"cohort_id\"],\n ])\n\n desc = cursor.description\n return Response({\n \"mark\": request.data[\"mark\"],\n \"notes\": request.data[\"notes\"],\n \"day_id\": request.data[\"day_id\"],\n \"staff_id\": request.data[\"staff_id\"],\n \"student_id\": request.data[\"student_id\"],\n \"week_id\": request.data[\"week_id\"],\n \"cohort_id\": request.data[\"cohort_id\"]\n })\n except :\n return Response(status=HTTPStatus.BAD_REQUEST)\n\n\n\n# --------------------- Delete WarmUps ----------------------------#\n\n@csrf_exempt\n@api_view(['POST', ])\ndef DeleteWarmUps_view(request):\n\n permission_classes = (permissions.IsAuthenticated,)\n\n if request.data['is_staff'] ==0:\n return Response(status=HTTPStatus.BAD_REQUEST)\n else:\n try:\n \n cursor = connection.cursor()\n cursor.execute('''DELETE FROM rbkbackend.warmups\n WHERE rbkbackend.warmups.id in (%s)\n ''',[request.data[\"ArrayOfWarmUpsIds\"]])\n\n desc = cursor.description\n return Response(request.data[\"ArrayOfWarmUpsIds\"])\n except :\n return Response(status=HTTPStatus.BAD_REQUEST)\n\n\n# --------------------- Update WarmUps ----------------------------#\n\n@csrf_exempt\n@api_view(['POST', ])\ndef UpdateWarmUps_view(request):\n permission_classes = (permissions.IsAuthenticated,)\n\n if request.data['is_staff'] ==0:\n return Response(status=HTTPStatus.BAD_REQUEST)\n else :\n try:\n \n cursor = connection.cursor()\n cursor.execute('''UPDATE rbkbackend.warmups\n SET\n mark = %s,\n notes = %s\n WHERE id = %s; \n ''',[request.data[\"mark\"],request.data[\"notes\"],request.data[\"id\"]])\n\n desc = cursor.description\n return Response({\"mark\":request.data[\"mark\"],\"notes\":request.data[\"mark\"],\"id\":request.data[\"id\"]})\n except :\n return Response(status=HTTPStatus.BAD_REQUEST)\n\n \n\n\n@csrf_exempt\n@api_view(['POST', ])\ndef getAllWarmUps_view(request):\n \n permission_classes = (permissions.IsAuthenticated,)\n try:\n if request.data[\"cohort_id\"] :\n cursor = connection.cursor()\n cursor.execute('''SELECT \n rbkbackend.warmups.id,\n rbkbackend.cohort.name as cohort_name,\n rbkbackend.warmups.notes,\n rbkbackend.warmups.mark,\n \n rbkbackend.days.text as daytitle\n \n , rbkbackend.weeks.text as weektitle,\n \n concat( g.first_name ,\" \" ,g.Last_name) as staff_name,\n concat( d.first_name,\" \" ,d.Last_name) as student_name \n \n FROM rbkbackend.warmups\n right join rbkbackend.cohort on rbkbackend.warmups.cohort_id = rbkbackend.cohort.id\n right join rbkbackend.days on rbkbackend.days.id = rbkbackend.warmups.day_id\n right join rbkbackend.weeks on rbkbackend.weeks.id = rbkbackend.warmups.week_id\n right join rbkbackend.accounts_newuser as g on g.id = rbkbackend.warmups.staff_name_id\n right join rbkbackend.accounts_newuser as d on d.id = rbkbackend.warmups.student_name_id\n where rbkbackend.warmups.cohort_id=%s order by \n rbkbackend.warmups.cohort_id ASC,rbkbackend.warmups.week_id ASC,rbkbackend.warmups.day_id ASC, rbkbackend.warmups.student_name_id ASC ;;\n ''',[int(request.data['cohort_id']),])\n\n desc = cursor.description\n column_names = [col[0] for col in desc]\n data = [dict(zip(column_names, row))\n for row in cursor.fetchall()]\n return Response(data)\n else :\n raise ValidationError\n\n except NewUser.DoesNotExist:\n return Response(status=HTTPStatus.BAD_REQUEST)\n\n return Response(status=HTTPStatus.FORBIDDEN)\n \n\n\n \n \n \n ","repo_name":"RBKAndBootstrapWebsite/RBK-FULLAPP","sub_path":"RBK_BACKEND_SIT/RBK_BACKEND_SIT/Warmups/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17688077546","text":"from tkinter import *\nimport urllib.parse\nimport urllib.request\nimport requests\n\n'=============================FIRST WINDOW FUNCTION==============================='\n\n\ndef find_books_results():\n search_word = textinput1.get()\n url = ('https://www.googleapis.com/books/v1/volumes?&' + urllib.parse.urlencode({'q': search_word}) + '\\\n&OrderBy=relevance&maxResults=10&printType=books')\n apiresult = requests.get(url)\n parseddoc = apiresult.json()\n\n print(parseddoc)\n\n x = 1\n for thing in parseddoc['items']:\n title = thing['volumeInfo']['title']\n try:\n desc = thing['volumeInfo']['description']\n except KeyError:\n desc = \"None\"\n try:\n subtitle = thing['volumeInfo']['subtitle']\n except KeyError:\n subtitle = 'None'\n try:\n category = thing['volumeInfo']['categories'][0]\n except KeyError:\n category = 'None'\n try:\n authors = thing['volumeInfo']['authors'][0]\n except KeyError:\n authors = 'None'\n final_str = '%d. \\nTitle: %s \\nSubtitle: %s\\nCategory: %s\\nAuthor: %s\\n' % \\\n (x, title, subtitle, category, authors)\n label.insert(END, final_str + '\\n')\n x = x + 1\n\n\n'===============================FIRST WINDOW VARIABLES==============================='\n\nwindow = Tk()\nwindow.title(\"Bonder™️ - Find Your Book!\")\nwindow.iconbitmap(r'icon.ico')\n\nvar = StringVar()\nvar.set('thisisnothing')\n\ncanvas = Canvas(window, height=830, width=600)\ncanvas.pack()\n\nbackground_image = PhotoImage(file='landscape.png')\nbackground_label = Label(window, image=background_image)\nbackground_label.place(relwidth=1, relheight=1)\n\n'==================================================================================='\n\ntextinput1 = StringVar()\n\nframe = Frame(window, bg='#80c1ff', bd=5)\nframe.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.05, anchor='n')\n\ninput1 = Entry(frame, bg='white', cursor='dot', font=40, textvariable=textinput1)\ninput1.place(relwidth=0.65, relheight=1)\n\nbutton = Button(frame, text=\"Press me nigga\", font=40, command=find_books_results)\nbutton.place(relx=0.7, relwidth=0.3, relheight=1)\n\n'==================================================================================='\n\nlower_frame = Frame(window, bg='#80c1ff', bd=10)\nlower_frame.place(relx=0.5, rely=0.2, relwidth=0.75, relheight=0.6, anchor='n')\n\nlabel = Text(lower_frame, bg='white')\nlabel.place(relwidth=1, relheight=1)\n\n'=================================FIRST WINDOW===================================='\n\n\ndef create_window():\n\n '============================SECOND WINDOW FUNCTION============================'\n\n def find_prod_results():\n key = 'Yesuudei-NCTUComp-PRD-5bddb6120-7f94bd0e'\n\n wear = clicked.get()\n choice_prod = choice.get()\n search_word1 = textinput1.get()\n maxprice_res = maxprice.get()\n num_res = num.get()\n\n if wear == 'New':\n wear = 1000\n wear = str(wear)\n elif wear == 'New with Defects':\n wear = 1750\n wear = str(wear)\n elif wear == 'Manufacturer refurbished':\n wear = 2000\n wear = str(wear)\n elif wear == 'Used':\n wear = 3000\n wear = str(wear)\n elif wear == 'Very Good':\n wear = 4000\n wear = str(wear)\n elif wear == 'Good':\n wear = 5000\n wear = str(wear)\n elif wear == 'Acceptable':\n wear = 6000\n wear = str(wear)\n\n url = ('https://www.googleapis.com/books/v1/volumes?&' + urllib.parse.urlencode({'q': search_word1}) + '\\\n&OrderBy=relevance&maxResults=10&printType=books')\n apiresult = requests.get(url)\n parseddoc = apiresult.json()\n\n y = 0\n for thing in parseddoc['items']:\n if y == choice_prod:\n break\n try:\n full_title = thing['volumeInfo']['title'] + \" \" + thing['volumeInfo']['subtitle']\n if len(full_title) > 98:\n try:\n full_title = thing['volumeInfo']['title'] + \" \" + thing['volumeInfo']['authors'][0]\n except KeyError:\n full_title = thing['volumeInfo']['title']\n\n except KeyError:\n try:\n full_title = thing['volumeInfo']['title'] + \" \" + thing['volumeInfo']['authors'][0]\n y = y + 1\n except KeyError:\n full_title = thing['volumeInfo']['title']\n y = y + 1\n continue\n\n y = y + 1\n if y == choice_prod:\n break\n\n print(full_title)\n\n search_word = full_title\n\n url = ('http://svcs.ebay.com/services/search/FindingService/v1\\\n?OPERATION-NAME=findItemsByKeywords\\\n&sortOrder=PricePlusShippingLowest\\\n&buyerPostalCode=92128&SERVICE-VERSION=1.13.0\\\n&SECURITY-APPNAME=' + key + '\\\n&RESPONSE-DATA-FORMAT=JSON\\\n&REST-PAYLOAD\\\n&CategoryName=Books\\\n&aspectFilter.aspectName=Books\\\n&itemFilter(0).name=Condition\\\n&itemFilter(0).value=' + wear + '\\\n&itemFilter(1).name=MaxPrice\\\n&itemFilter(1).value=' + maxprice_res + '\\\n&itemFilter(1).paramName=Currency\\\n&itemFilter(1).paramValue=USD\\\n&keywords=' + search_word)\n\n apiresult = requests.get(url)\n parseddoc = apiresult.json()\n\n json_status = parseddoc['findItemsByKeywordsResponse'][0]['ack'][0]\n Items_found = parseddoc['findItemsByKeywordsResponse'][0]['searchResult'][0]['@count']\n\n divider = '============================================================================================================'\n Items_found_str = '%s Items Found!\\n%s\\n\\n' % (Items_found, divider)\n\n label3.insert(END, Items_found_str )\n\n x = 0\n title_prev = 'thisisnothing'\n repeat = 'no'\n a = 1\n try:\n piece = parseddoc[\"findItemsByKeywordsResponse\"][0][\"searchResult\"][0][\"item\"]\n for item in piece:\n title = item[\"title\"][0]\n bookLink = item['viewItemURL'][0]\n if repeat == 'no':\n if title == title_prev:\n continue\n\n price = item['sellingStatus'][0][\"convertedCurrentPrice\"][0]['__value__']\n\n final_str = '%d.\\n%s [%s$]\\neBay Link: %s\\n' % (a, title, price, bookLink)\n label3.insert(END, final_str + '\\n')\n\n title_prev = title\n x = x + 1\n if x == num_res:\n break\n a = a + 1\n except KeyError:\n b = 'Unfortunately, there are no books with the parameters you have specified.\\n\\n' \\\n 'Please restart your variables by pressing [Click to Proceed!] in the window: Part I\\n\\n' \\\n 'If this keeps happening please consider a different book, because the book you are looking ' \\\n 'for may not be available at the moment.\\n\\n' \\\n 'Press [Click to Exit!] and search for another amazing book!\\n\\n'\n label3.insert(END, b)\n\n '===============================FIRST WINDOW VARIABLES==============================='\n\n def close_window():\n window.destroy()\n window2.destroy()\n\n '==================================SECOND WINDOW===================================='\n\n global button3\n global background_image2\n global background_label2\n\n '===================================================================================='\n\n window2 = Toplevel()\n window2.title(\"Bonder™️ - Find Your Book!\")\n window2.iconbitmap(r'icon.ico')\n\n canvas2 = Canvas(window2, height=830, width=1000)\n canvas2.pack()\n\n background_image2 = PhotoImage(file='landscape.png')\n background_label2 = Label(window2, image=background_image2)\n background_label2.place(relwidth=1, relheight=1)\n\n '===================================================================================='\n\n choice = IntVar()\n\n frame_half = Frame(window2, bg='#80c1ff', bd=5)\n frame_half.place(relx=0.27, rely=0.1, relwidth=0.43, relheight=0.05, anchor='n')\n\n label_half = Label(frame_half, text='Choose the Book You Like', bg='white', font='Sans 11')\n label_half.place(relwidth=0.65, relheight=1)\n\n input_half = Entry(frame_half, bg='white', cursor='dot', font=40, textvariable=choice)\n input_half.place(relx=0.7, relwidth=0.3, relheight=1)\n\n '===================================================================================='\n\n num = IntVar()\n\n frame2 = Frame(window2, bg='#80c1ff', bd=5)\n frame2.place(relx=0.73, rely=0.1, relwidth=0.43, relheight=0.05, anchor='n')\n\n label2a = Label(frame2, text='Enter Number of Books to be Displayed', bg='white', font='Sans 11')\n label2a.place(relwidth=0.65, relheight=1)\n\n input2 = Entry(frame2, bg='white', cursor='dot', font=40, textvariable=num)\n input2.place(relx=0.7, relwidth=0.3, relheight=1)\n\n '===================================================================================='\n\n maxprice = StringVar()\n\n frame3 = Frame(window2, bg='#80c1ff', bd=5)\n frame3.place(relx=0.27, rely=0.17, relwidth=0.43, relheight=0.05, anchor='n')\n\n label3 = Label(frame3, text='Enter How Much Money You Have', bg='white', font='Sans 11')\n label3.place(relwidth=0.65, relheight=1)\n\n input3 = Entry(frame3, bg='white', cursor='dot', font=40, textvariable=maxprice)\n input3.place(relx=0.7, relwidth=0.3, relheight=1)\n\n label3a = Label(input3, text='$', bg='white', font='Sans 11')\n label3a.place(relx=0.8, relwidth=0.2, relheight=1)\n\n '==================================================================================='\n\n frame4 = Frame(window2, bg='#80c1ff', bd=5)\n frame4.place(relx=0.73, rely=0.17, relwidth=0.43, relheight=0.05, anchor='n')\n\n button3 = Button(frame4, text=\"Search\", font=40, command=find_prod_results)\n button3.place(relx=0.7, relwidth=0.3, relheight=1)\n\n options = [\n \"New\",\n \"New with Defects\",\n \"Manufacturer refurbished\",\n \"Used\",\n \"Very Good\",\n \"Good\",\n \"Acceptable\"\n ]\n\n clicked = StringVar()\n clicked.set(\"Choose The Wear of Your Book\")\n\n drop = OptionMenu(frame4, clicked, *options)\n drop.place(relwidth=0.65, relheight=1)\n\n '==================================================================================='\n\n frame5 = Frame(window2, bg='#80c1ff', bd=10)\n frame5.place(relx=0.5, rely=0.24, relwidth=0.89, relheight=0.58, anchor='n')\n\n label3 = Text(frame5, bg='white')\n label3.place(relwidth=1, relheight=1)\n # label3.config(fg='blue')\n # Print results in here\n\n '==================================================================================='\n\n button4 = Button(window2, text=\"Click to Exit!\", font=40, command=close_window)\n button4.place(relx=0.5, rely=0.89, relwidth=0.89, relheight=0.05, anchor='s')\n\n\n'===============================END OF SECOND WINDOW=================================='\n\n# For first window, not second!\nbutton2 = Button(window, text=\"Click to Proceed!\", font=40, command=create_window)\nbutton2.place(relx=0.5, rely=0.89, relwidth=0.75, relheight=0.05, anchor='s')\n\n\nmainloop()\n\n","repo_name":"DmytroIvakhnenkov/GamerSight","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":11311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70144400164","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom .models import No_of_guest, OnlineBooking\n\n\nclass ModelsTest(TestCase):\n\n def setUp(self):\n self.user = User.objects.create_user(username='testuser',\n password='testpassword')\n self.no_of_guest = No_of_guest.objects.create(guest=2)\n self.booking = OnlineBooking.objects.create(\n user=self.user,\n first_name='Maria',\n last_name='Arnesson',\n no_of_guest=self.no_of_guest,\n date='2023-07-13',\n time='10 AM - 12 AM',\n occassion='Birthday',\n table='Family table',\n special_request='Some special request',\n approved=False,\n )\n\n def test_no_of_guest_model(self):\n self.assertEqual(str(self.no_of_guest), '2')\n\n def test_online_booking_model(self):\n self.assertEqual(str(self.booking.date), '2023-07-13')\n self.assertEqual(str(self.booking.user), 'testuser')\n self.assertEqual(self.booking.approved, False)\n","repo_name":"mariaarnesson/restaurant_booking_system","sub_path":"reservation/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40502666951","text":"import findspark\nfindspark.init()\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.window import Window\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\n# from pyspark.sql.functions import *\n\nfrom convertTronAddressToEvmAddress import convertTronAddresstoEvmAddress\n\nif __name__=='__main__':\n spark_session = SparkSession \\\n .builder \\\n .appName(\"convertLabeledAddress\") \\\n .config(\"spark.driver.extraJavaOptions\", \"-Djava.io.tmpdir=/mnt/blockchain03/findFullData/tmpdata\") \\\n .config(\"spark.executor.extraJavaOptions\", \"-Djava.io.tmpdir=/mnt/blockchain03/findFullData/tmpdata\") \\\n .config(\"spark.driver.memory\", \"100g\") \\\n .getOrCreate()\n spark_session.sparkContext.setLogLevel(\"Error\")\n blackAddressLoc=\"file:///mnt/blockchain02/tronLab/labeled_address.csv\"\n blackAddress=spark_session.read.csv(blackAddressLoc,header=True, inferSchema=True)\n blackAddress=blackAddress.select(\"address\")\n transform_udf = udf(convertTronAddresstoEvmAddress, StringType())\n blackAddressWithEvmAddress = blackAddress.withColumn(\"aaaa\", transform_udf(\"address\"))\n blackAddressWithEvmAddress.show()\n blackAddressWithEvmAddress.write.option(\"header\", \"true\").csv(\"file:///mnt/blockchain02/tronLab/123.csv\")\n\n\n\n\n\n spark_session.stop()","repo_name":"5yh/tronLab","sub_path":"convertLabeledAddress.py","file_name":"convertLabeledAddress.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4542052836","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('home', views.home, name= 'home'),\n\n # * Personal data\n path('yourPersonalData', views.seePersonalData, name= 'yourPersonalData'),\n\n # * Messages\n path('yourMessages', views.seeMessages, name= 'yourMessages'),\n\n # * Class panel\n path('manageClass', views.manageClass, name= 'manageClass'),\n\n path('classManager', views.classManager, name= 'classManager'),\n\n path('addStudentToClass', views.addStudentToClass, name= 'addStudentToClass'),\n\n]\n","repo_name":"Workata/BD2","sub_path":"teachersOsos/urls.py","file_name":"urls.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":"72584396325","text":"from discord.ext import commands\nfrom meowth.context import Context\n\nclass MeowthBot(commands.AutoShardedBot):\n \"\"\"Custom Discord Bot class for Kyogre\"\"\"\n\n async def process_commands(self, message):\n \"\"\"Processes commands that are registed with the bot and it's groups.\n\n Without this being run in the main `on_message` event, commands will\n not be processed.\n \"\"\"\n if message.author.bot:\n return\n if message.content.startswith('!'):\n message.content = message.content.lower()\n if message.content[1] == \" \":\n message.content = message.content[0] + message.content[2:]\n ctx = await self.get_context(message, cls=Context)\n if not ctx.command:\n return\n await self.invoke(ctx)\n","repo_name":"KyogreBot/Kyogre","sub_path":"meowth/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"5239583285","text":"import json\nimport orjson\nfrom datetime import datetime\nimport just\nimport pandas as pd\n\nfrom nostalgia.times import datetime_from_timestamp\n\nfrom auto_extract import parse_article\n\nfrom nostalgia.cache import get_cache\nfrom nostalgia.ndf import NDF\n\nfrom nostalgia.utils import normalize_name\n\nCACHE = get_cache(\"linked_person\")\n\n\ndef getter(dc, key, default=None):\n res = dc.get(key, default)\n if isinstance(res, list):\n res = res[0]\n elif isinstance(res, dict):\n res = json.dumps(res)\n return res\n\n\ndef get_linked_data_jd(art):\n data = None\n try:\n jdata = art.jsonld\n except json.JSONDecodeError:\n return None\n for y in jdata:\n if not y:\n continue\n if isinstance(y, list):\n y = y[0]\n if isinstance(y, str) and y[0] == \"{\":\n y = orjson.loads(y)\n if y.get(\"@type\") != \"Person\":\n continue\n return {\n \"description\": getter(y, \"description\"),\n \"startDate\": getter(y, \"startDate\"),\n \"endDate\": getter(y, \"endDate\"),\n \"location\": getter(y, \"location\"),\n \"source\": \"jsonld\",\n }\n\n\ndef get_linked_data_md(art):\n data = None\n for y in art.microdata:\n props = y.get(\"properties\")\n if props is None:\n continue\n tp = str(y.get(\"type\", \"\"))\n if not tp.endswith(\"/Person\"):\n continue\n return {\n \"startDate\": getter(props, \"startDate\"),\n \"endDate\": getter(props, \"endDate\"),\n \"description\": getter(props, \"description\"),\n \"name\": \"\".join(getter(props, \"name\", \"\")),\n \"location\": getter(props, \"location\"),\n \"source\": \"md\",\n }\n\n\ndef get_linked_data(x):\n path = x[\"path\"]\n if path in CACHE:\n return CACHE[path]\n try:\n html = just.read(path)\n except EOFError:\n CACHE[path] = None\n return None\n if not html.strip():\n CACHE[path] = None\n return None\n art = parse_article(html, x[\"url\"])\n linked_data = get_linked_data_md(art)\n if linked_data is None:\n linked_data = get_linked_data_jd(art)\n CACHE[path] = linked_data\n return linked_data\n\n\nclass Person(NDF):\n @classmethod\n def object_to_row(cls, obj):\n row = get_linked_data(obj)\n if row is not None:\n row[\"time\"] = datetime_from_timestamp(float(obj[\"time\"]))\n row[\"url\"] = obj[\"url\"]\n row[\"path\"] = obj[\"path\"]\n row[\"keywords\"] = \"\"\n return row\n\n @classmethod\n def load(cls, file_path=\"~/nostalgia_data/meta.jsonl\", nrows=None, **kwargs):\n person = cls.load_object_per_newline(file_path, nrows)\n return cls(person)\n\n\nif __name__ == \"__main__\":\n person = Person.load(nrows=5)\n\n # https://schema.org/Blog\n # \"http://schema.org/blogPost\"\n # http://schema.org/WebPage # http://schema.org/BlogPosting\n\n # exlclude http://schema.org/QAPage\n\n it = 0\n imo = 0\n nice = 0\n wrong = 0\n from collections import Counter\n import just\n\n c = Counter()\n\n for x in just.iread(\"/home/pascal/nostal_tmp/person.jsonl\"):\n if \"/Person\" in (str(x.get(\"microdata\"))):\n it += 1\n y = x\n score = 0\n mc_count = 0\n for mc in y[\"microdata\"]:\n if mc.get(\"type\") in [\n \"http://schema.org/ImageObject\",\n \"http://schema.org/QAPage\",\n \"http://schema.org/Movie\",\n \"http://schema.org/videoObject\",\n \"http://schema.org/Organization\",\n \"http://schema.org/VideoObject\",\n \"http://schema.org/Question\",\n \"http://schema.org/CreativeWork\",\n \"http://schema.org/Code\",\n ]:\n continue\n mc_count += 1\n for opt in [\n 'mc[\"properties\"][\"author\"]',\n 'mc[\"properties\"][\"author\"][\"properties\"][\"name\"]',\n 'mc[\"properties\"][\"author\"][\"value\"]',\n 'mc[\"properties\"][\"author\"][0][\"value\"]',\n 'mc[\"properties\"][\"author\"][0][\"properties\"][\"name\"]',\n 'mc[\"properties\"][\"author\"][\"properties\"][\"author\"][\"properties\"][\"name\"][0]',\n 'mc[\"properties\"][\"creator\"][\"properties\"][\"name\"]',\n 'mc[\"properties\"][\"author\"][0][\"value\"]',\n 'mc[\"properties\"][\"mainEntity\"][\"properties\"][\"author\"][\"properties\"][\"name\"]',\n 'mc[\"properties\"][\"blogPost\"][\"properties\"][\"author\"][\"properties\"][\"name\"]',\n ]:\n try:\n x = eval(opt).strip()\n if not x or x.startswith(\"http\") or \"\\n\" in x:\n continue\n print(x)\n score += 1\n c[mc[\"type\"].split(\"/\")[-1]] += 1\n break\n except KeyboardInterrupt:\n \"a\" + 1\n except:\n pass\n if mc_count and score == 0:\n if len(y[\"microdata\"]) == 1 and list(y[\"microdata\"][0]) == [\"value\"]:\n continue\n wrong += 1\n continue\n if score:\n nice += 1\n","repo_name":"nostalgia-dev/nostalgia","sub_path":"nostalgia/sources/web/linked_person.py","file_name":"linked_person.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"52"} +{"seq_id":"70624820965","text":"valido=False\n\nemail=input(\"Introduce email: \")\n\nfor i in range(len(email)): #range() crea una lista, en este caso con las posiciones que dé len()\n\tif email[i]==\"@\":\n\n\t\tvalido=True\n\nif valido:\n\n\tprint(\"Email correcto\")\n\nelse:\n\n\tprint(\"Email incorrecto\")\n\n","repo_name":"dasafo/Python","sub_path":"bucles_for_6_IV.py","file_name":"bucles_for_6_IV.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41063179463","text":"import tensorflow as tf\nimport numpy as np\nimport math\nimport sys\nmnist = tf.keras.datasets.mnist\n\n#=================\n# Input parameters\n#=================\nlearningRate = 0.5\nfc1_size = 1024\nbatch_size = 100 # new: work with batches\n\n#===========\n# Load data\n#===========\n\n(x_train,y_train),(x_test,y_test) = mnist.load_data()\nwith tf.Session() as sess:\n y_train = sess.run(tf.one_hot(y_train,10))\n y_test = sess.run(tf.one_hot(y_test,10))\n\nx_train = x_train/255\nx_test = x_test/255\n\nimsize = x_train[0].shape\nN_labels = 10\nN_samples_train = len(x_train)\n# overall number of training samples\n\n#=============\n# Create model\n#=============\n\nX = tf.placeholder(tf.float32, shape = [None, imsize[0], imsize[1]])\ny = tf.placeholder(tf.float32, shape = [None,N_labels])\n\n#Hidden layer\nwith tf.variable_scope('fully_connected1') as scope:\n xdata = tf.reshape(X,[-1,imsize[0]*imsize[1]])\n W = tf.get_variable('weights',[imsize[0]*imsize[1],fc1_size],initializer=tf.truncated_normal_initializer())\n b = tf.get_variable('biases',[fc1_size],initializer=tf.truncated_normal_initializer())\n fc1 = tf.nn.sigmoid(tf.matmul(xdata,W) + b)\n \n#Output layer\nwith tf.variable_scope('output') as scope:\n W = tf.get_variable('weights',[fc1_size,N_labels],initializer=tf.truncated_normal_initializer())\n b = tf.get_variable('biases',[N_labels],initializer=tf.truncated_normal_initializer())\n yhat = tf.squeeze(tf.matmul(fc1,W) + b)\n # note that N_labels has changed from 1 to 10, to account for the\n # one-hot-vectors\n\n#Loss calculation\nwith tf.name_scope('loss'):\n loss = tf.losses.sigmoid_cross_entropy(y,yhat)\n\n#Optimization\noptimizer = tf.train.GradientDescentOptimizer(learningRate).minimize(loss)\n\n#=====================\n# Training and testing\n#=====================\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n items = np.arange(N_samples_train)\n # items == array([0,1,...,N_samples_train-1])\n \n np.random.shuffle(items)\n # now items == array([ ... shuffled version of items ...])\n \n N_batches = math.ceil(N_samples_train/batch_size)\n # N_batches is the number of batches\n \n idx_start = 0\n for bat in range(N_batches-1):\n # now train with every batch, accordingly load training data into X and y\n \n x_train_batch = x_train[items[idx_start:idx_start+batch_size]]\n y_train_batch = y_train[items[idx_start:idx_start+batch_size]]\n \n _, loss_train = sess.run([optimizer, loss], feed_dict={X:x_train_batch,y:y_train_batch})\n # now load the training batch into X and y, and train\n \n idx_start += batch_size\n # iterate, and train on every batch\n \n x_train_batch = x_train[items[idx_start:]]\n y_train_batch = y_train[items[idx_start:]]\n # last batch, which may not be of size 100\n \n _, loss_train = sess.run([optimizer, loss], feed_dict={X:x_train_batch,y:y_train_batch})\n # train also on last batch\n \n print('Training loss: '+str(loss_train))\n\n yhat_,loss_test = sess.run([yhat,loss], feed_dict={X:x_test,y:y_test})\n print('Test loss: '+str(loss_test))\n\n # this is one epoch, but with the batches results should be a bit improved\n","repo_name":"jangerrith/deep_learning","sub_path":"code/tutorial_2.py","file_name":"tutorial_2.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38776647191","text":"import functools as ft\nimport typing as tp\nimport types\nfrom collections import defaultdict\n\nimport libcst as cst\nimport libcst.matchers as m\nfrom libcst import CSTNode, CSTNodeT, RemovalSentinel, FlattenSentinel\n\n\nfrom ast_tools.utils import BiMap\n\nclass _NodeTrackerMixin:\n node_tracking_table: BiMap[CSTNode, CSTNode]\n\n def __init__(self, *args, **kwargs) -> None:\n super().__init__(*args, **kwargs)\n self.node_tracking_table = BiMap()\n self.new = set()\n\n def on_leave(self,\n original_node: CSTNodeT,\n updated_node: tp.Union[CSTNodeT, RemovalSentinel, FlattenSentinel[CSTNodeT]]\n ) -> tp.Union[CSTNodeT, RemovalSentinel, FlattenSentinel[CSTNodeT]]:\n final_node = super().on_leave(original_node, updated_node)\n self.track_with_children(original_node, final_node)\n return final_node\n\n\n def _track(self,\n original_node: CSTNode,\n updated_node: cst.CSTNode) -> None:\n if original_node in self.node_tracking_table.i:\n # original_node has a origin, track back\n for o_node in self.node_tracking_table.i[original_node]:\n self._track(o_node, updated_node)\n return\n\n if updated_node in self.node_tracking_table:\n # updated_node is an origin, skip it\n for u_node in self.node_tracking_table[updated_node]:\n self._track(original_node, u_node)\n return\n assert updated_node not in self.node_tracking_table, (original_node, updated_node)\n assert original_node not in self.node_tracking_table.i, (original_node, updated_node)\n self.node_tracking_table[original_node] = updated_node\n\n def _track_with_children(self,\n original_nodes: tp.Iterable[CSTNode],\n updated_nodes: tp.Iterable[CSTNode]) -> None:\n\n for o_node in original_nodes:\n for u_node in updated_nodes:\n if u_node not in self.node_tracking_table.i or u_node in self.new:\n # u_node has not been explained or has multiple origins\n self.new.add(u_node)\n self._track(o_node, u_node)\n self._track_with_children(original_nodes, u_node.children)\n\n def track(self,\n original_node: tp.Union[CSTNode, tp.Iterable[CSTNode]],\n updated_node: tp.Union[CSTNode, RemovalSentinel, tp.Iterable[CSTNode]]) -> None:\n\n if isinstance(updated_node, CSTNode):\n updated_node = updated_node,\n\n if isinstance(updated_node, RemovalSentinel) or not updated_node:\n return\n\n if isinstance(original_node, CSTNode):\n original_node = original_node,\n\n for o_node in original_nodes:\n for u_node in updated_nodes:\n self._track(o_node, u_node)\n\n\n def track_with_children(self,\n original_node: tp.Union[CSTNode, tp.Iterable[CSTNode]],\n updated_node: tp.Union[CSTNode, RemovalSentinel, tp.Iterable[CSTNode]]) -> None:\n\n if isinstance(updated_node, CSTNode):\n updated_node = updated_node,\n\n if isinstance(updated_node, RemovalSentinel) or not updated_node:\n return\n\n if isinstance(original_node, CSTNode):\n original_node = original_node,\n\n self._track_with_children(original_node, updated_node)\n self.new = set()\n\n def trace_origins(self, prev_table: BiMap[CSTNode, CSTNode]) -> BiMap[CSTNode, CSTNode]:\n new_table = BiMap()\n for update, origins in self.node_tracking_table.i.items():\n for o in origins:\n for oo in prev_table.i.get(o, []):\n new_table[oo] = update\n\n for origin, updates in prev_table.items():\n for u in updates:\n for uu in self.node_tracking_table.get(u, [u]):\n new_table[origin] = uu\n\n\n return new_table\n\n\nclass NodeTrackingTransformer(\n _NodeTrackerMixin,\n cst.CSTTransformer): pass\n\n\nclass NodeTrackingMatcherTransformer(\n _NodeTrackerMixin,\n m.MatcherDecoratableTransformer): pass\n\n\ndef with_tracking(transformer: tp.Type[cst.CSTTransformer]) -> tp.Type[cst.CSTTransformer]:\n \"\"\" Helper function than adds tracking to a transformer type \"\"\"\n return type(transformer.__name__, (_NodeTrackerMixin, transformer), {})\n","repo_name":"leonardt/ast_tools","sub_path":"ast_tools/transformers/node_tracker.py","file_name":"node_tracker.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"} +{"seq_id":"33791886286","text":"from rest_framework import serializers\n\nfrom accounts.api.serializers import UserMainSerializers\n\nfrom ..models import Answer, Ticket\n\n\nclass TicketSerializer(serializers.ModelSerializer):\n body = serializers.CharField(write_only=True)\n user = serializers.SerializerMethodField()\n\n class Meta:\n model = Ticket\n fields = (\n \"id\",\n \"user\",\n \"title\",\n \"type\",\n \"status\",\n \"closed_at\",\n \"code\",\n \"body\",\n )\n read_only_fields = (\n \"id\",\n \"user\",\n \"status\",\n \"closed_at\",\n \"code\",\n )\n\n def create(self, validated_data):\n body = validated_data.pop(\"body\")\n user = self.context[\"request\"].user\n ticket = Ticket.objects.create(user=user, **validated_data)\n Answer.objects.create(body=body, from_who=\"user\", ticket=ticket)\n return ticket\n\n def get_user(self, obj):\n return UserMainSerializers(obj.user).data\n\n\nclass AnswerSerializer(serializers.ModelSerializer):\n class Meta:\n model = Answer\n fields = (\n \"ticket\",\n \"from_who\",\n \"body\",\n \"created\",\n )\n read_only_fields = (\n \"ticket\",\n \"from_who\",\n \"created\",\n )\n","repo_name":"elyashedayat10/irandat1","sub_path":"tickets/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74531700323","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport django.core.validators\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0001_initial'),\n ('contenttypes', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('password', models.CharField(verbose_name='password', max_length=128)),\n ('last_login', models.DateTimeField(verbose_name='last login', default=django.utils.timezone.now)),\n ('is_superuser', models.BooleanField(verbose_name='superuser status', default=False, help_text='Designates that this user has all permissions without explicitly assigning them.')),\n ('username', models.CharField(max_length=30, verbose_name='username', validators=[django.core.validators.RegexValidator('^[\\\\w.@+-]+$', 'Enter a valid username.', 'invalid')], unique=True, help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.')),\n ('first_name', models.CharField(verbose_name='first name', max_length=30, blank=True)),\n ('last_name', models.CharField(verbose_name='last name', max_length=30, blank=True)),\n ('email', models.EmailField(verbose_name='email address', max_length=75, blank=True)),\n ('is_staff', models.BooleanField(verbose_name='staff status', default=False, help_text='Designates whether the user can log into this admin site.')),\n ('is_active', models.BooleanField(verbose_name='active', default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')),\n ('date_joined', models.DateTimeField(verbose_name='date joined', default=django.utils.timezone.now)),\n ('phone', models.TextField(max_length=40)),\n ('security_question', models.TextField(max_length=200)),\n ('security_answer', models.TextField(max_length=200)),\n ('requires_reset', models.BooleanField(default=False)),\n ('organization_name', models.TextField(blank=True, max_length=200, null=True)),\n ('organization_type', models.TextField(blank=True, max_length=40, null=True)),\n ('date_appointed_agent', models.DateField(blank=True, null=True)),\n ('relationship', models.TextField(blank=True, max_length=200, null=True)),\n ('emergency_contact', models.TextField(blank=True, max_length=200, null=True)),\n ('emergency_phone', models.TextField(blank=True, max_length=200, null=True)),\n ('emergency_relationship', models.TextField(blank=True, max_length=200, null=True)),\n ],\n options={\n 'verbose_name': 'user',\n 'abstract': False,\n 'verbose_name_plural': 'users',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Address',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('street1', models.TextField(max_length=200)),\n ('street2', models.TextField(blank=True, max_length=200, null=True)),\n ('city', models.TextField(max_length=100)),\n ('state', models.TextField(max_length=20)),\n ('zip_code', models.TextField(max_length=20)),\n ('country', models.TextField(max_length=100)),\n ],\n options={\n 'verbose_name_plural': 'addresses',\n 'ordering': ['state', 'city', 'zip_code', 'street1', 'street2'],\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Area',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('name', models.TextField(max_length=200)),\n ('description', models.TextField(max_length=1000)),\n ('place_number', models.PositiveIntegerField()),\n ('coordinator', models.ForeignKey(related_name='coordinates', null=True, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='CartLineItem',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('quantity', models.PositiveIntegerField()),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('description', models.TextField(max_length=200)),\n ],\n options={\n 'verbose_name_plural': 'categories',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ConfigurationParameters',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('sales_tax_rate', models.DecimalField(decimal_places=4, max_digits=5)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='DamageFee',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('amount', models.DecimalField(decimal_places=2, max_digits=10)),\n ('waived', models.BooleanField(default=False)),\n ('description', models.TextField()),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('name', models.TextField(max_length=200)),\n ('description', models.TextField(max_length=1000)),\n ('start_date', models.DateTimeField()),\n ('end_date', models.DateTimeField()),\n ('map_file_name', models.TextField(max_length=200)),\n ('venue_name', models.TextField(max_length=200, null=True)),\n ('address', models.ForeignKey(related_name='+', null=True, to='homepage.Address')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='LateFee',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('amount', models.DecimalField(decimal_places=2, max_digits=10)),\n ('waived', models.BooleanField(default=False)),\n ('days_late', models.PositiveIntegerField()),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('order_date', models.DateTimeField()),\n ('phone', models.TextField()),\n ('date_packed', models.DateTimeField()),\n ('date_paid', models.DateTimeField(null=True)),\n ('date_shipped', models.DateTimeField(null=True)),\n ('tracking_number', models.TextField(max_length=50, null=True)),\n ('customer', models.ForeignKey(related_name='orders', to=settings.AUTH_USER_MODEL)),\n ('handled_by', models.ForeignKey(related_name='handledby_set', null=True, blank=True, to=settings.AUTH_USER_MODEL)),\n ('packed_by', models.ForeignKey(related_name='packedby_set', null=True, blank=True, to=settings.AUTH_USER_MODEL)),\n ('payment_processed_by', models.ForeignKey(related_name='paymentprocessedby_set', null=True, blank=True, to=settings.AUTH_USER_MODEL)),\n ('shipped_by', models.ForeignKey(related_name='shippedby_set', null=True, blank=True, to=settings.AUTH_USER_MODEL)),\n ('ships_to', models.ForeignKey(related_name='+', to='homepage.Address')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ParticipantRole',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('name', models.TextField(max_length=200)),\n ('type', models.TextField(max_length=40)),\n ('area', models.ForeignKey(to='homepage.Area')),\n ('participant', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Photograph',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('date_taken', models.DateTimeField()),\n ('place_taken', models.TextField(blank=True, max_length=200, null=True)),\n ('description', models.TextField(blank=True, max_length=1000, null=True)),\n ('image', models.TextField(null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ProductSpecification',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('name', models.TextField(max_length=200)),\n ('price', models.DecimalField(decimal_places=2, max_digits=10)),\n ('description', models.TextField()),\n ('manufacturer', models.TextField(max_length=80)),\n ('average_cost', models.DecimalField(decimal_places=2, max_digits=10)),\n ('sku', models.TextField(max_length=20)),\n ('order_form_name', models.TextField(max_length=200, null=True)),\n ('production_time', models.TextField(max_length=200, null=True)),\n ('category', models.ForeignKey(related_name='+', to='homepage.Category')),\n ('photo', models.OneToOneField(null=True, to='homepage.Photograph')),\n ('vendor', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='RentalItem',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('amount', models.DecimalField(decimal_places=2, max_digits=10)),\n ('date_out', models.DateTimeField(auto_now_add=True)),\n ('date_in', models.DateTimeField()),\n ('date_due', models.DateTimeField()),\n ('discount_percent', models.DecimalField(decimal_places=2, max_digits=3)),\n ('order', models.ForeignKey(to='homepage.Order')),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SaleItem',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('amount', models.DecimalField(decimal_places=2, max_digits=10)),\n ('quantity', models.IntegerField()),\n ('order', models.ForeignKey(to='homepage.Order')),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='StockedProduct',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('quantity_on_hand', models.IntegerField(null=True)),\n ('shelf_location', models.TextField(max_length=40, null=True)),\n ('order_file', models.TextField(null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SerializedProduct',\n fields=[\n ('stockedproduct_ptr', models.OneToOneField(auto_created=True, serialize=False, parent_link=True, primary_key=True, to='homepage.StockedProduct')),\n ('serial_number', models.TextField(max_length=100, unique=True, null=True)),\n ('type', models.TextField(max_length=100)),\n ('date_acquired', models.DateField(auto_now_add=True)),\n ('cost', models.DecimalField(decimal_places=2, max_digits=10, null=True)),\n ('for_sale', models.BooleanField(default=True)),\n ('condition_new', models.BooleanField(default=True)),\n ('notes', models.TextField()),\n ('size', models.TextField(max_length=40, null=True)),\n ('size_modifier', models.TextField(max_length=40, null=True)),\n ('gender', models.TextField(max_length=40, null=True)),\n ('color', models.TextField(max_length=40, null=True)),\n ('pattern', models.TextField(max_length=40, null=True)),\n ('start_year', models.PositiveIntegerField(null=True)),\n ('end_year', models.PositiveIntegerField(null=True)),\n ('note', models.TextField(null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=('homepage.stockedproduct',),\n ),\n migrations.CreateModel(\n name='RentalProduct',\n fields=[\n ('serializedproduct_ptr', models.OneToOneField(auto_created=True, serialize=False, parent_link=True, primary_key=True, to='homepage.SerializedProduct')),\n ('times_rented', models.IntegerField()),\n ('price_per_day', models.DecimalField(decimal_places=2, max_digits=10)),\n ('replacement_price', models.DecimalField(decimal_places=2, max_digits=10)),\n ],\n options={\n 'abstract': False,\n },\n bases=('homepage.serializedproduct',),\n ),\n migrations.AddField(\n model_name='stockedproduct',\n name='photo',\n field=models.ForeignKey(to='homepage.Photograph', null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='stockedproduct',\n name='polymorphic_ctype',\n field=models.ForeignKey(editable=False, null=True, related_name='polymorphic_homepage.stockedproduct_set', to='contenttypes.ContentType'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='stockedproduct',\n name='product_specification',\n field=models.ForeignKey(related_name='+', null=True, to='homepage.ProductSpecification'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='serializedproduct',\n name='owner',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='saleitem',\n name='product',\n field=models.ForeignKey(related_name='+', to='homepage.StockedProduct'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='rentalitem',\n name='rental_product',\n field=models.ForeignKey(related_name='+', to='homepage.RentalProduct'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='latefee',\n name='order',\n field=models.ForeignKey(to='homepage.Order'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='latefee',\n name='rental_item',\n field=models.ForeignKey(related_name='+', to='homepage.RentalItem'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='damagefee',\n name='order',\n field=models.ForeignKey(to='homepage.Order'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='damagefee',\n name='rental_item',\n field=models.ForeignKey(related_name='+', to='homepage.RentalItem'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cartlineitem',\n name='stocked_product',\n field=models.ForeignKey(to='homepage.StockedProduct'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='cartlineitem',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='area',\n name='event',\n field=models.ForeignKey(to='homepage.Event'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='area',\n name='participants',\n field=models.ManyToManyField(through='homepage.ParticipantRole', to=settings.AUTH_USER_MODEL, null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='area',\n name='photo',\n field=models.ForeignKey(to='homepage.Photograph', null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='area',\n name='supervisor',\n field=models.ForeignKey(related_name='supervises', null=True, to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='user',\n name='address',\n field=models.ForeignKey(related_name='+', null=True, to='homepage.Address'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='user',\n name='groups',\n field=models.ManyToManyField(verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', blank=True, related_name='user_set', related_query_name='user', to='auth.Group'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='user',\n name='photo',\n field=models.ForeignKey(related_name='+', null=True, blank=True, to='homepage.Photograph'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='user',\n name='user_permissions',\n field=models.ManyToManyField(verbose_name='user permissions', help_text='Specific permissions for this user.', blank=True, related_name='user_set', related_query_name='user', to='auth.Permission'),\n preserve_default=True,\n ),\n ]\n","repo_name":"StevenDewey/colonial-project","sub_path":"homepage/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":20095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44461047496","text":"# Exercícios com funções\n\n# Crie uma função que fala se um número é par ou ímpar.\n# Retorne se o número é par ou ímpar.\n\n\ndef par_impar(num):\n if num % 2 == 0:\n return f'O número {num} é PAR.'\n return f'O número {num} é ÍMPAR.'\n\n\nprint(par_impar(2))\nprint(par_impar(3))\n","repo_name":"cesar-augusto-costa/Python_Avancado_Udemy","sub_path":"Python_Avancado_Udemy/Projeto/aula072c.py","file_name":"aula072c.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38538280822","text":"from ratelimit import limits, RateLimitException, sleep_and_retry\nfrom backoff import on_exception, expo\nfrom concurrent.futures import ThreadPoolExecutor as PoolExecutor, thread\nimport logging\nimport cloudinary.api\nimport cloudinary.uploader\nimport re\nimport argparse\n\n################################ Script Setup ######################################\n# modify the values below for processing your account, if needed\n# this script processes either images or videos in one run\n####################################################################################\nRESOURCE_TYPE='image'\n#RESOURCE_TYPE='video'\nTYPE = 'upload'\nPATTERN = re.compile(r'^(?:.+/)?(?:[a-zA-Z]{2,3})?(\\d+)_([^\\_]+)\\_([^\\_]+)')\nPOSITION = {\n 'a': 1,\n 'b': 2,\n 'da': 3,\n 'db': 4,\n 'dc': 5,\n 'ea': 6,\n 'eb': 7,\n 'eda': 8,\n 'edb': 9,\n 'eea': 10,\n 'eeb': 11,\n 'eec': 12,\n 'el': 13,\n 'esw': 14,\n 'l': 15,\n 'sw': 16\n }\n####################### Script Setup Ends ##############################\n########################################################################\n\n\ndef extract_metadata(public_id):\n '''\n Helper function that extracts based on PATTERN\n Currently, it assumes 3 parameters:\n 1. Product ID\n 2. Color/Colour Code\n 3. Display Position\n\n Returns a formatted string that can be directly used in the API call\n ''' \n result = ''\n\n matches = PATTERN.search(public_id)\n\n # only if we have the right components in the file name, proceed\n if matches!=None and len(matches.groups())==3:\n result = f'product_id={matches.group(1)}|color_code={matches.group(2)}'\n display_position_code = matches.group(3) \n \n # ensure that the lookup for position works, else log the error\n if display_position_code in POSITION:\n result += f'|display_position={POSITION[display_position_code]}'\n else:\n logging.error(f'{public_id},{display_position_code},display not found')\n else:\n logging.error(f'{public_id},N/A,Did not match the regex')\n \n return result\n \n\n\ndef update_metadata(public_id):\n '''\n Update one resource at a time by adding the metadata and context values\n The function uses \"explicit\" Upload API\n Details: https://cloudinary.com/documentation/image_upload_api_reference#explicit\n '''\n metadata = extract_metadata(public_id)\n \n # update the resource only if we have some metadata \n if metadata != '':\n try:\n resp = cloudinary.uploader.explicit(\n public_id,\n type=TYPE,\n resource_type=RESOURCE_TYPE,\n metadata = metadata,\n context = metadata\n )\n logging.debug(f'{public_id},{metadata}')\n except Exception as e:\n logging.error(f'{public_id},{e},{metadata}')\n \n \n# default rate limit is 5,000/hour = 83.33 calls/min\nONE_MINUTE = 60\nMAX_CALLS_PER_MINUTE = 83\n\n@sleep_and_retry\n@limits(calls=MAX_CALLS_PER_MINUTE, period=ONE_MINUTE)\ndef list_resources(folder, next_cursor=None): \n '''\n Function that makes the Admin API Resource call (https://cloudinary.com/documentation/admin_api#get_resources)\n Fetches a max of 500 resources in one operation\n\n Using a concurrency of 50 threads, updates the resources\n \n Admin API is rate limited to 5,000 calls/hour. Using a library, we are forcing the rate limits.\n '''\n total_resources = 0\n # initialize a pool of threads to do our updating job later\n with PoolExecutor(max_workers=50) as executor:\n while(1):\n resources = []\n resources_in_loop = 0\n try:\n # make an Admin API call to get the list of resources across all folders\n if folder==None:\n resp = cloudinary.api.resources(\n type = TYPE,\n resource_type = RESOURCE_TYPE,\n max_results = 500,\n next_cursor = next_cursor \n )\n else:\n # make an Admin API call to get the list of resources from a specific folder\n resp = cloudinary.api.resources(\n type = TYPE,\n resource_type = RESOURCE_TYPE,\n prefix = folder,\n max_results = 500, \n next_cursor = next_cursor \n )\n \n # loop and pull the public ids\n for _ in resp['resources']: \n # ensure this is not a soft-deleted resource\n if _['bytes'] > 0 and 'placeholder' in _ and _['placeholder']==True:\n resources.append(_['public_id'])\n resources_in_loop+= 1\n \n total_resources += resources_in_loop\n # now update the metadata for these resources\n for _ in executor.map(update_metadata, resources):\n pass\n\n # finally check if we have more resources - if so, use pagination\n # and fetch the next set and repeat. Else exit.\n if 'next_cursor' not in resp or resp['next_cursor']==None:\n break \n except Exception as e:\n logging.error(f'Unable to fetch resources: {e} objects.')\n logging.info(f'Processed {total_resources}')\n \n\nif __name__==\"__main__\":\n # Allow 2 optional parameters to set the log file and the report file names.\n parser = argparse.ArgumentParser(\n description=\"Script to parse file name and add metadata.\",\n usage=\"python3 update_metadata.py --folder <> --log <>\"\n )\n \n parser.add_argument(\n '--folder', \n default=None, \n required=False, \n help=\"Update metadata for objects in a fixed folder. Default=None (ie, process all objects in the account)\"\n )\n\n parser.add_argument(\n '--log', \n default=\"log.csv\", \n required=False, \n help=\"File name for report. default = \\\"report.csv\\\"\"\n )\n\n args = parser.parse_args()\n\n # logging setup\n # we will be writing to a file named 'log.csv' to capture the output of this operation\n logging.basicConfig(level=logging.INFO,\n format='%(levelname)s,%(message)s',\n filename=args.log,\n filemode='w')\n logging.getLogger(\"urllib3\").setLevel(logging.CRITICAL)\n logging.getLogger(\"cloudinary\").setLevel(logging.CRITICAL)\n logging.getLogger(\"backoff\").setLevel(logging.CRITICAL)\n logging.getLogger(\"boto3\").setLevel(logging.CRITICAL)\n \n list_resources(folder = args.folder) ","repo_name":"akshay-ranganath/metadata_management","sub_path":"update_metadata.py","file_name":"update_metadata.py","file_ext":"py","file_size_in_byte":7013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41180038357","text":"import matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport sys\n\nfilename = sys.argv[1]\n\nsm_num = 15\nlines_per_kernel = 6 * sm_num + 1\nmod_num = 7\nshared_mem_per_block = 4 # KB\n\nif shared_mem_per_block == 0:\n max_support_kernel_id = 31\nelse:\n max_support_kernel_id = min(96 / shared_mem_per_block - 1, 31)\n\nstart_time_list = []\nstop_time_list = []\nkernel_id_list = []\nblock_id_list = []\n\nsm_line_list = []\n \nfor i in range (sm_num):\n start_time_list.append([])\n stop_time_list.append([])\n kernel_id_list.append([])\n block_id_list.append([])\n sm_line_list.append([])\n\nwith open(filename) as f:\n for kernel_line_num, line in enumerate(f):\n if 'Kernel number' in line:\n a, b = line.split(\":\")\n kernel_num = int(b)\n \nwith open(filename) as f:\n for sm_line_num, line in enumerate(f):\n if 'SM id: 0' in line:\n sm_line_list[0].append(sm_line_num)\n if 'SM id: 1' in line and 'SM id: 10' not in line and 'SM id: 11' not in line and 'SM id: 12' not in line and 'SM id: 13' not in line and 'SM id: 14' not in line:\n sm_line_list[1].append(sm_line_num)\n if 'SM id: 2' in line:\n sm_line_list[2].append(sm_line_num)\n if 'SM id: 3' in line:\n sm_line_list[3].append(sm_line_num)\n if 'SM id: 4' in line:\n sm_line_list[4].append(sm_line_num)\n if 'SM id: 5' in line:\n sm_line_list[5].append(sm_line_num)\n if 'SM id: 6' in line:\n sm_line_list[6].append(sm_line_num)\n if 'SM id: 7' in line:\n sm_line_list[7].append(sm_line_num)\n if 'SM id: 8' in line:\n sm_line_list[8].append(sm_line_num)\n if 'SM id: 9' in line:\n sm_line_list[9].append(sm_line_num)\n if 'SM id: 10' in line:\n sm_line_list[10].append(sm_line_num)\n if 'SM id: 11' in line:\n sm_line_list[11].append(sm_line_num)\n if 'SM id: 12' in line:\n sm_line_list[12].append(sm_line_num)\n if 'SM id: 13' in line:\n sm_line_list[13].append(sm_line_num)\n if 'SM id: 14' in line:\n sm_line_list[14].append(sm_line_num)\n\n# for row in range(sm_num):\n# cols = len(sm_line_list[row])\n# print(\"\\n Row\", row, \"has\", cols, \"columns: \", end=\"\")\n# for col in range(cols):\n# print(sm_line_list[row][col], \" \", end=\"\")\n\nfor i in range(sm_num - 1):\n idx = 0\n with open(filename) as f:\n for ln, tl in enumerate(f):\n if idx >= len(sm_line_list[i]):\n break\n if ln == sm_line_list[i][idx] - 2: # block id\n a, b = tl.split(\":\")\n b = int(b)\n block_id_list[i].append(b)\n if ln == sm_line_list[i][idx] - 1: # kernel id\n a, b = tl.split(\":\")\n b = int(b)\n kernel_id_list[i].append(b)\n if ln == sm_line_list[i][idx] + 1: # start_time @smid = 0\n a, b = tl.split(\":\")\n b = int(b)\n start_time_list[i].append(b)\n if ln == sm_line_list[i][idx] + 2: # stop_time @smid = 0\n a, b = tl.split(\":\")\n b = int(b)\n stop_time_list[i].append(b)\n idx += 1\n\n# now we get the start/stop time of each block @smid = 0\n# plot\nheight = max_support_kernel_id + 1\nu_shift = 0.3\n# plt.figure()\nfor i in range (sm_num-1):\n# for i in range (13, 14):\n plt.figure()\n plt.title('smid' + str(i))\n # plt.subplot(3, 1, i+1)\n cnt_0 = 0\n cnt_1 = 0 \n cnt_2 = 0\n cnt_3 = 0\n cnt_4 = 0\n cnt_5 = 0\n cnt_6 = 0\n for j in range (len(start_time_list[i])):\n y_h = kernel_num - kernel_id_list[i][j]\n # y_h = height\n xmin_h = start_time_list[i][j]\n xmax_h = stop_time_list[i][j]\n x_t = (stop_time_list[i][j]+start_time_list[i][j])/2 \n y_t = y_h + 0.05 # 0.25\n s_t = 'K'+str(kernel_id_list[i][j])+': '+str(block_id_list[i][j])\n if kernel_id_list[i][j] > max_support_kernel_id:\n # m = int(kernel_id_list[i][j] / max_support_kernel_id)\n y_h = (kernel_num - kernel_id_list[i][j]) + max_support_kernel_id + 2# + 1 - 0.3\n y_t = y_h + 0.1\n if kernel_id_list[i][j] % mod_num == 0:\n offset = u_shift * cnt_0\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='r', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_0 += 1\n # plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(formatter))\n # plt.barh(range(len(start_time_list[i])), int(stop_time_list[i][j]) - int(start_time_list[i][j]), left=int(start_time_list[i][j]), color='r')\n # plt.yticks(range(len(start_time_list[i])), str(kernel_id_list[i][j]))\n elif int(kernel_id_list[i][j]) % mod_num == 1:\n offset = u_shift * cnt_1\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='y', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_1 += 1\n elif int(kernel_id_list[i][j]) % mod_num == 2:\n offset = u_shift * cnt_2\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='g', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_2 += 1\n elif int(kernel_id_list[i][j]) % mod_num == 3:\n offset = u_shift * cnt_3\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='b', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_3 += 1\n elif int(kernel_id_list[i][j]) % mod_num == 4:\n offset = u_shift * cnt_4\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='c', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_4 += 1\n elif int(kernel_id_list[i][j]) % mod_num == 5:\n offset = u_shift * cnt_5\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='m', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_5 += 1\n elif int(kernel_id_list[i][j]) % mod_num == 6:\n offset = u_shift * cnt_6\n plt.hlines(y=y_h-offset, xmin=xmin_h, xmax=xmax_h, colors='k', lw=6)\n plt.text(x=x_t, y=y_t-offset, s=s_t, horizontalalignment='center')\n plt.text(x=start_time_list[i][j], y=y_t-offset, s=str(start_time_list[i][j]), horizontalalignment='left')\n plt.text(x=stop_time_list[i][j], y=y_t-offset, s=str(stop_time_list[i][j]), horizontalalignment='right')\n cnt_6 += 1\n\n # height -= 1\n # if height == 0:\n # height = max_support_kernel_id + 1\n\nplt.show()","repo_name":"yidiwang21/ee217","sub_path":"final_project/draw_blocks_timeline.py","file_name":"draw_blocks_timeline.py","file_ext":"py","file_size_in_byte":8282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71261969765","text":"\nfrom collections import deque #bfs를 위한 deque\n\nN, M, V = map(int, input().split())\n\n#처음 0번째 추가\ngraph = []\nfor _ in range(N+1):\n graph.append([0]*(N+1))\n \nfor _ in range(M):\n m1, m2 = map(int, input().split())\n graph[m1][m2] = graph[m2][m1] = 1 #간선 정보 기입\n\ndef dfs(start, visited = []):\n visited.append(start)\n print(start, end=' ')\n \n #start 노드를 기준으로 간선 체크\n for w in range(len(graph[start])):\n if(graph[start][w] == 1 and (w not in visited)): #w정보가 visited에 없으면\n dfs(w, visited) #해당되는 w, 현재 visited 정보\n \ndef bfs(start):\n visited = [start] #처음 노드 넣기\n queue = deque() #bfs를 위한 큐 만들기\n queue.append(start)\n \n while queue:\n v = queue.popleft() #큐에서 빼기\n print(v, end= ' ')\n \n for w in range(len(graph[v])):\n if(graph[v][w] == 1 and (w not in visited)):\n visited.append(w) #방문처리\n queue.append(w) #큐에 넣기\n \ndfs(V)\nprint()\nbfs(V)","repo_name":"hwi1018/CodingTest_Python","sub_path":"dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34742604828","text":"import numpy as np\n\nimg_data = [int(x) for x in open(\"input.txt\").read().strip(\"\\n\")]\nw = 25\nh = 6\n\nimg_data = np.array(img_data).reshape((-1, w, h))\n\ndigits = []\nfor layer in img_data:\n num_zero = (layer == 0).sum()\n num_one = (layer == 1).sum()\n num_two = (layer == 2).sum()\n digits.append([num_zero, num_one, num_two])\n\nprint(min(digits)[1] * min(digits)[2])\n","repo_name":"brisutom/AoC2019","sub_path":"08/part1.py","file_name":"part1.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":"73075977126","text":"# data\nimport pandas as pd\nfrom stockfish import Stockfish\nimport chess.pgn\nimport chess.engine\nimport numpy as np\nimport io\nimport time\nimport multiprocessing\n\nif __name__ == '__main__':\n engine = chess.engine.SimpleEngine.popen_uci(\"./stockfish-11-win/Windows/stockfish_20011801_x64_modern\")\n print(engine.ping)\n print(\"START OF DOCUMENT\")\n\n # read the pgn of game data\n df = pd.read_csv('../chessEngine/util/partially_processed_standard_2020/expanded/expanded_2020_3_0.csv')\nmyTemp = pd.DataFrame()\n\n# get the board from the PGN representation\ndef getBoard(pgnPos) :\n pgnPos = pgnPos[:len(pgnPos)]\n pgnStr = io.StringIO(pgnPos)\n pgnGame = chess.pgn.read_game(pgnStr)\n board = pgnGame.board()\n for move in pgnGame.mainline_moves():\n board.push(move)\n if(len(board.move_stack) == 0):\n return None\n return board\n# get the FEN representation of the board for Stockfish evaluation\ndef getFen(board):\n return board.board_fen()\n# traceback the moves for each game and append them to the dataframe\ncounte = 0\ndef expandGame(board):\n global x\n global counte\n global myTemp\n print(counte)\n counte = counte + 1\n x = len(board.move_stack)\n if(x < 2):\n return None\n y = board.copy()\n y.pop()\n myTemp = myTemp.append({'board' : y, \"FEN\" : y.board_fen()}, ignore_index = True)\n expandGame(y)\ndef expandWhiteGames(board):\n global df\n global x\n if(x < 2):\n return None\n if(not board.turn): \n y = board.copy()\n y.pop()\n expandWhiteGames(y)\n x = len(board.move_stack)\n y = board.copy()\n y.pop()\n df = df.append({'board' : y, \"FEN\" : y.board_fen()}, ignore_index = True)\n expandWhiteGames(y)\n# evaluate the board with the stockfish engine imported via python chess\ncount = 0\ndef evalBoard(board):\n global count\n print(count)\n count += 1\n k = engine.analyse(board, chess.engine.Limit(time=0.05))['score'].relative.__str__()\n print(k)\n return k\n# replace all scores involving forced mates with +/- 10000\ndef replaceForcedMate(x):\n if x[0] == \"#\" :\n if x[2] == '0' :\n if x[1] == \"+\" :\n return 10000 - 10 * int(x[2])\n else :\n return -10000 + 10 * int(x[2])\n else : \n if x[1] == \"+\" :\n return +10000\n else:\n return -10000\n else:\n return x\nbithash = {\n \".\" : np.array([0,0,0,0,0,0, 0,0,0,0,0,0]),\n \"r\" : np.array([0,0,0,1,0,0, 0,0,0,0,0,0]),\n \"b\" : np.array([0,0,1,0,0,0, 0,0,0,0,0,0]),\n \"q\" : np.array([0,0,0,0,1,0, 0,0,0,0,0,0]),\n \"k\" : np.array([0,0,0,0,0,1, 0,0,0,0,0,0]),\n \"n\" : np.array([0,1,0,0,0,0, 0,0,0,0,0,0]),\n \"p\" : np.array([1,0,0,0,0,0, 0,0,0,0,0,0]),\n \"R\" : np.array([0,0,0,0,0,0, 0,0,0,1,0,0]),\n \"B\" : np.array([0,0,0,0,0,0, 0,0,1,0,0,0]),\n \"Q\" : np.array([0,0,0,0,0,0, 0,0,0,0,1,0]),\n \"K\" : np.array([0,0,0,0,0,0, 0,0,0,0,0,1]),\n \"N\" : np.array([0,0,0,0,0,0, 0,1,0,0,0,0]),\n \"P\" : np.array([0,0,0,0,0,0, 1,0,0,0,0,0]),\n}\ndef boardToString(x):\n x = chess.Board(x)\n x=x.__str__()\n return x\ndef fenToNPArray(x):\n x = chess.Board(x)\n x=x.__str__()\n x = x.split(\"\\n\")\n for n in range(len(x)):\n x[n] = np.array(x[n].split()).reshape(8,1)\n newTemp = []\n for i in range(len(x[n])) :\n# print(x[n][i][0])\n newTemp.append(bithash[x[n][i][0]])\n x[n] = newTemp\n return np.array(x)\ndef addEvalToDataFrame(r, i):\n # evaluate every board with stockfish and add it to the Dataframe\n r['stockfish_eval'] = r['board'].apply(lambda x : evalBoard(x))\n # remove the boards\n r = r.drop(\"board\", axis=1)\n r.to_csv(f\"temp_{i}.csv\")\n # replace checkmating values\n r['stockfish_eval'] = r['stockfish_eval'].apply(lambda x : replaceForcedMate(x))\ndef reverseTurn(board):\n board.turn = not board.turn\n if(board.is_check()):\n return board\n else :\n board.turn = not board.turn\n return board\n \n# prep for multiprocessing\nfrom multiprocessing import Pool\nfrom functools import partial\nimport numpy as np\n\ndef parallelize(data, func, num_of_processes=6):\n data_split = np.array_split(data, num_of_processes)\n print(\"PARALLELIZING\")\n if __name__ == \"__main__\" :\n pool = Pool(num_of_processes)\n data= pd.concat(pool.map(func, data_split))\n print(\"FINISHED\")\n pool.close()\n print(\"POOL CLOSED\")\n # pool.join()\n # print(\"POOL JOINED\")\n return data\n\ndef run_on_subset(func, data_subset):\n print(\"RUNNING ON SUBSET\")\n print(len(data_subset))\n return data_subset.apply(func)\n\ndef parallelize_on_rows(data, func, num_of_processes=multiprocessing.cpu_count()):\n return parallelize(data, partial(run_on_subset, func), num_of_processes)\n\nif __name__ == '__main__':\n # extract board pd.Series\n df['board'] = df['FEN'].apply(lambda x : chess.Board(x))\n # df['board'] = df['board'].apply(lambda x : reverseTurn(x))\n y = df['board']\n x = len(y)\n # evaluate every board with stockfish and add it to the Dataframe\n start = time.time()\n df['stockfish_eval'] = parallelize_on_rows(y, evalBoard)\n end = time.time()\n print(\"Evaluating the boards took \" + str((end - start)/60.0) + \" minutes\")\n # replace checkmating values\n if(df['stockfish_eval'][0] is not None) :\n print(df.head(5))\n df.drop(\"board\", axis=1).to_csv(\"compiled_2020_mates_3_0.csv\", index=False)\n df['stockfish_eval'] = df['stockfish_eval'].apply(lambda x : replaceForcedMate(x))\n # remove the boards\n df = df.drop(\"board\", axis=1)\n # save the dataframe as a csv\n df.to_csv(\"compiled_2020_3_0.csv\", index=False)","repo_name":"abagel21/BagelChess","sub_path":"evalGames.py","file_name":"evalGames.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18979334036","text":"import serial\nimport struct\n\ndef Checksum(dataList):\n checksum = 0xFF - (sum(dataList) & 0xFF)\n return checksum\n\ndef constructPacket():\n header = 0x7E\n length = 0x000E\n frameType = 0x10\n frameID = 0x01\n longAddressHigh = 0x0013A200\n longAddressLow = 0x40C14304\n shortAddress = 0xFFFE\n broadcastRadius = 0x00\n options = 0x00\n configureData = [frameType, frameID, longAddressHigh, longAddressLow,\n shortAddress, broadcastRadius, options]\n dataPayload = ['H', 'e', 'l', 'l', 'o', '6'] #\n dataPayloadHex = [ord(x) for x in dataPayload]\n length = length + len(dataPayload)\n checksumDataPre = configureData + dataPayloadHex\n checksumDataStr = struct.pack('>BBIIHBB%dB' % len(dataPayload), *checksumDataPre)\n checksumData = list(struct.unpack('>%dB' % length, checksumDataStr))\n # print(checksumData)\n checksum = Checksum(checksumData)\n # print(checksum)\n allData = [header, length] + checksumDataPre + [checksum]\n byteStr = struct.pack('>BHBBIIHBB%dBB' % len(dataPayload), *allData)\n packet = byteStr\n return packet\n\ndef parsePacket(packet):\n data = []\n for byte in packet:\n data.append(hex(byte))\n print(data)\n\ndef main():\n packet = constructPacket()\n # print(packet)\n # with serial.Serial('/dev/tty.SLAB_USBtoUART', 115200, timeout=1) as ser:\n with serial.Serial('/dev/tty.usbserial-AL00FMGX', 115200, timeout=1) as ser:\n ser.write(packet)\n allReadData = ser.readline()\n parsePacket(allReadData)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"liutairan/ZigBee-Communication-Tool-Python","sub_path":"src/SerialWriteTransmitRequest.py","file_name":"SerialWriteTransmitRequest.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":"16540722429","text":"# EXERCISE 109 : Magic dates\nfrom ex_106 import leap_year\n\n# From exercise 106\n\"\"\"def leap_year(year):\n if year % 400 == 0 or year % 4 == 0:\n return True\n elif year % 100 == 0:\n return False\n else:\n return False\"\"\"\n\n\ndef days_in_month(month, year):\n if 1 >= month >= 12:\n print(\"Error\")\n quit()\n\n if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:\n return 31\n elif month == 4 or month == 6 or month == 9 or month == 11:\n return 30\n elif month == 2:\n if leap_year(year):\n return 29\n else:\n return 28\n\n\ndef is_magic_date(day, month, year):\n if day * month == year % 100:\n return True\n\n return False\n\n\n# Find and display all of the magic dates in 1900s\ndef main():\n for year in range(1900, 2000):\n for month in range(1, 13):\n for day in range(1, days_in_month(month, year) + 1):\n if is_magic_date(day, month, year):\n print(f\"{day}/{month}/{year} is a magic date\")\n\n\nmain()\n","repo_name":"AndreaOrlando23/the-python-workbook","sub_path":"Cap_4_Functions/ex_109.py","file_name":"ex_109.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34031124039","text":"from sqlite3 import Error\r\nimport os\r\nimport xlrd\r\nfrom sql_func import execute_query, create_connection, convertTime\r\nimport time\r\nfile = r'C:\\Users\\brinpy\\Downloads\\AlarmsHistory.xls'\r\nwb = xlrd.open_workbook(file) \r\nsheet = wb.sheet_by_index(0) \r\n\r\ndbpath = r\"C:\\Users\\brinpy\\Documents\\sql\\alarms.db\"\r\ndbpath = r\"\\\\ant\\dept-na\\FTW1\\Support\\Facilities\\z_Alarms\\alarms.db\"\r\nconnection = create_connection(dbpath)\r\nrow = 9\r\ncur = connection.cursor()\r\ncountme = 0\r\nrunagain = True\r\nlasttime = int(time.time() * 1000)\r\nwhile runagain:\r\n if countme % 100 == 0:\r\n countme += 1\r\n print(\"Processed \" + str(countme) + \" records in \" + str((time.time()*1000) - lasttime) + \" ms\")\r\n lasttime = int(time.time() * 1000)\r\n\r\n else:\r\n countme += 1\r\n if sheet.cell_value(row, 0) == sheet.cell_value(-1, 0):\r\n runagain = False\r\n print(\"END OF FILE\")\r\n tag = sheet.cell_value(row, 10)\r\n tag = tag.split('_')\r\n tagcompare = list(tag[0])[0]\r\n if (tagcompare == 'U') or (list(tag[0])[0]) == 'C' or (list(tag[0])[0] == 'R'):\r\n #print(\"Allowable tag\")\r\n tblename = tag[0]\r\n tag.pop(0)\r\n alarm_type_str = '_'\r\n alarm_type_str = alarm_type_str.join(tag)\r\n #print(tag)\r\n time_val = sheet.cell_value(row, 0)\r\n duration_ms = int(sheet.cell_value(row, 1) * 1000)\r\n area_str = sheet.cell_value(row, 7)\r\n description_str = sheet.cell_value(row, 3)\r\n #print(list(alarm_type_str))\r\n #if row > 10:\r\n create_alarm_table = \"CREATE TABLE IF NOT EXISTS \" + tblename + \" (time FLOAT(23), duration_ms INTEGER, alarm_type varchar(50), area varchar(50), description varchar(255));\"\r\n \r\n lis = list(description_str.split(\"'\"))\r\n \r\n description_str2 = ''.join(lis)\r\n create_alarm = \"INSERT INTO \" + tblename + \" (time, duration_ms, alarm_type, area, description) VALUES ('\" + str(time_val) + \"', \" + str(duration_ms) + \", '\" + alarm_type_str + \"', '\" + area_str + \"', '\" + description_str2 + \"');\"\r\n if row < 0:\r\n print(create_alarm_table)\r\n print(create_alarm)\r\n print(row)\r\n execute_query(connection, create_alarm_table)\r\n\r\n selectable = \"SELECT * FROM \" + tblename + \" WHERE time = \" + str(time_val) + \";\"\r\n cur.execute(selectable)\r\n possibleduplicate = cur.fetchall()\r\n runquery = True\r\n for i in possibleduplicate:\r\n if (int(i[1]) == duration_ms) and (i[4] == description_str):\r\n runquery = False\r\n break\r\n\r\n \r\n if runquery: \r\n execute_query(connection, create_alarm)\r\n #print(\"completed query\")\r\n row += 1\r\n \r\n \r\n\r\n\r\n\r\n\r\n \r\n#execute_query(connection, create_alarm_table)\r\n#execute_query(connection, create_alarm)\r\nos.remove(file)","repo_name":"brinpy/visualization","sub_path":"sql_feeder.py","file_name":"sql_feeder.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3175600176","text":"from typing import Any\nfrom template import template, impl\nfrom pinManager import PinManager\nfrom codeManager import CodeManager\nfrom translation.opcode import OCCPU, len2\nimport math\n\nimport sys\nimport pathlib\nsys.path.insert(0, str(pathlib.Path().parent.absolute()))\nfrom utils import castTuple, flatten\n\nclass Gate:\n defaultShape = {'b': 1}\n\n def __new__(cls, *args, shape=None, channel='compile', **kwargs):\n if shape is None:\n shape = cls.defaultShape\n return cls._template_call(channel, *args, shape=shape, **kwargs)\n \n @classmethod\n def parallelTemplate(cls, *args, b=1):\n l = castTuple(cls(*[arg[:len(arg) // 2] for arg in args], shape={'b': b // 2}))\n r = castTuple(cls(*[arg[len(arg) // 2:] for arg in args], shape={'b': b - b // 2}))\n if len(l) == 1:\n return l[0] + r[0]\n return tuple(l[i] + r[i] for i in range(len(l)))\n\n\ndef implio(shape={}, ival=(), oval=()):\n def decorate(fun):\n def i(*args, **kwargs):\n return [eval(i, kwargs) for i in ival]\n impl(shape, 'i')(i)\n def o(*args, **kwargs):\n return [eval(o, kwargs) for o in oval]\n impl(shape, 'o')(o)\n return impl(shape, 'compile')(fun)\n return decorate\n\n\ndef ZERO():\n pin = PinManager.requestPin()\n CodeManager.code.append(f'pins[{pin[0]}] = 0;')\n return pin\n\ndef ONE():\n pin = PinManager.requestPin()\n CodeManager.code.append(f'pins[{pin[0]}] = 1;')\n return pin\n\ndef COPY(pins):\n res = []\n for pin in pins:\n res += PinManager.requestPin()\n CodeManager.code.append(f'pins[{res[-1]}] = pins[{pin}];')\n return res\n\ndef DEBUGOUTPUT(pins, message=''):\n if message != '':\n CodeManager.code.append(f'std::cout << \"{message}\" << \" \";')\n CodeManager.code.append(f'std::cout << {\" << \".join([f\"int(pins[{pin}])\" for pin in pins])} << std::endl;')\n\n@template\nclass NAND(Gate):\n @implio({'b': Any,}, ('b', 'b'), ('b'))\n def parallel(l, r, b):\n return NAND.parallelTemplate(l, r, b=b)\n \n @implio({'b': 1,}, ('1', '1'), ('1'))\n def compile(l, r, b):\n o = PinManager.requestPin()\n CodeManager.code.append(f'pins[{o[0]}] = (pins[{l[0]}] & pins[{r[0]}]) ^ 1;')\n return o\n\n@template\nclass NOT(Gate):\n @implio({'b': Any,}, ('b'), ('b'))\n def parallel(i, b):\n return NOT.parallelTemplate(i, b=b)\n \n @implio({'b': 1,}, ('1'), ('1'))\n def compile(i, b):\n return NAND(i, i)\n\n@template\nclass DOUBLER(Gate):\n @implio({'b': Any,}, ('b'), ('b', 'b'))\n def parallel(i, b):\n return DOUBLER.parallelTemplate(i, b=b)\n \n @implio({'b': 1,}, ('1'), ('2'))\n def compile(i, b):\n return i, i\n\n@template\nclass AND(Gate):\n @implio({'w': Any}, ('w',), ('1',))\n def wide(input, w):\n last = COPY([input[0]])\n for i in range(w - 1):\n new = AND(last, [input[i + 1]])\n PinManager.freePin(last)\n last = new\n return last\n\n @implio({'b': Any,}, ('b', 'b'), ('b'))\n def parallel(l, r, b):\n return AND.parallelTemplate(l, r, b=b)\n \n @implio({'b': 1,}, ('1', '1'), ('1'))\n def compile(l, r, b):\n nand = NAND(l, r)\n nt = NOT(nand)\n PinManager.freePin(nand)\n return nt\n\n@template\nclass OR(Gate):\n @implio({'w': Any}, ('w',), ('1',))\n def wide(input, w):\n last = COPY([input[0]])\n for i in range(w - 1):\n new = OR(last, [input[i + 1]])\n PinManager.freePin(last)\n last = new\n return last \n\n @implio({'b': Any,}, ('b', 'b'), ('b'))\n def parallel(l, r, b):\n return OR.parallelTemplate(l, r, b=b)\n \n @implio({'b': 1,}, ('1', '1'), ('1'))\n def compile(l, r, b):\n nt1 = NOT(l)\n nt2 = NOT(r)\n nand = NAND(nt1, nt2)\n PinManager.freePin(nt1, nt2)\n return nand\n\n@template\nclass NOR(Gate):\n @implio({'b': Any,}, ('b', 'b'), ('b'))\n def parallel(l, r, b):\n return NOR.parallelTemplate(l, r, b=b)\n \n @implio({'b': 1,}, ('1', '1'), ('1'))\n def compile(l, r, b):\n or_ = OR(l, r)\n nt = NOT(or_)\n PinManager.freePin(or_)\n return nt\n\n@template\nclass XOR(Gate):\n @implio({'b': Any,}, ('b', 'b'), ('b'))\n def parallel(l, r, b):\n return XOR.parallelTemplate(l, r, b=b)\n \n @implio({'b': 1,}, ('1', '1'), ('1'))\n def compile(l, r, b):\n m = NAND(l, r)\n l = NAND(l, m)\n r = NAND(m, r)\n PinManager.freePin(m)\n ret = NAND(l, r)\n PinManager.freePin(l, r)\n return ret\n\n@template\nclass XNOR(Gate):\n @implio({'b': Any,}, ('b', 'b'), ('b'))\n def parallel(l, r, b):\n return XNOR.parallelTemplate(l, r, b=b)\n \n @implio({'b': 1,}, ('1', '1'), ('1'))\n def compile(l, r, b):\n xor = XOR(l, r)\n nt = NOT(xor)\n PinManager.freePin(xor)\n return nt\n\n@template\nclass HADD(Gate):\n @implio({'b': Any,}, ('b', 'b'), ('b', '1'))\n def parallel(l, r, b):\n sum1, carry = HADD(l[:b // 2], r[:b // 2], shape={'b':b // 2})\n sum2, carry2 = FADD(l[b // 2:], r[b // 2:], carry, shape={'b': b - b // 2})\n PinManager.freePin(carry)\n return sum1 + sum2, carry2\n \n @implio({'b': 1,}, ('1', '1'), ('1', '1'))\n def compile(l, r, b):\n sum = XOR(l, r)\n carry = AND(l, r)\n return sum, carry\n\n@template\nclass FADD(Gate):\n @implio({'b': Any,}, ('b', 'b', '1'), ('b', '1'))\n def parallel(l, r, carry, b):\n sum1, carry = FADD(l[:b // 2], r[:b // 2], carry, shape={'b':b // 2})\n sum2, carry2 = FADD(l[b // 2:], r[b // 2:], carry, shape={'b': b - b // 2})\n PinManager.freePin(carry)\n return sum1 + sum2, carry2\n \n @implio({'b': 1,}, ('1', '1', '1'), ('1', '1'))\n def compile(l, r, carry, b):\n xor1 = XOR(l, r)\n sum = XOR(xor1, carry)\n and1 = AND(l, r)\n and2 = AND(xor1, carry)\n PinManager.freePin(xor1)\n carry = OR(and1, and2)\n PinManager.freePin(and1, and2)\n return sum, carry\n\n@template\nclass HINC(Gate):\n @implio({'b': Any,}, ('b',), ('b', '1'))\n def parallel(input, b):\n sum1, carry = HINC(input[:b // 2], shape={'b':b // 2})\n sum2, carry2 = FINC(input[b // 2:], carry, shape={'b': b - b // 2})\n PinManager.freePin(carry)\n return sum1 + sum2, carry2\n \n @implio({'b': 1,}, ('1', '1'), ('1', '1'))\n def compile(input, b):\n return FINC(input, ONE())\n\n@template\nclass FINC(Gate):\n @implio({'b': Any,}, ('b',), ('b', '1'))\n def parallel(input, carry, b):\n sum1, carry = FINC(input[:b // 2], carry, shape={'b':b // 2})\n sum2, carry2 = FINC(input[b // 2:], carry, shape={'b': b - b // 2})\n PinManager.freePin(carry)\n return sum1 + sum2, carry2\n \n @implio({'b': 1,}, ('1', '1'), ('1', '1'))\n def compile(input, carry, b):\n return HADD(input, carry)\n\n@template\nclass MUX(Gate):\n defaultShape = {'s': 1}\n\n @implio({'s': Any, 'b': Any})\n def width(select, *input, s, b):\n mux1 = MUX(select[:-1], *(input[:2**(s - 1)]), shape={'s': s - 1, 'b': b})\n mux2 = MUX(select[:-1], *(input[2**(s - 1):]), shape={'s': s - 1, 'b': b})\n mux3 = MUX([select[-1]], mux1, mux2, shape={'s': 1, 'b': b})\n PinManager.freePin(mux1, mux2)\n return mux3\n\n @implio({'s': 1, 'b': Any})\n def parallel(select, l, r, s=0, b=0):\n return flatten(MUX(select, [l[i]], [r[i]]) for i in range(b))\n\n @implio({'s': 1,}, ('1', '1', '1'), ('1'))\n def compile(select, l, r, s=0):\n nt = NOT(select)\n and1 = AND(l, nt)\n PinManager.freePin(nt)\n and2 = AND(r, select)\n or_ = OR(and1, and2)\n PinManager.freePin(and1, and2)\n return or_\n\n@template\nclass MUXP(Gate):\n @implio({'s': Any, 'b': Any}, ('s', 'b*2**s'), ('b',))\n def decorate(select, input, s, b):\n unpacked = [input[i * b:(i + 1) * b] for i in range(2**s)]\n return flatten(castTuple(MUX(select, *unpacked, shape={'s':s, 'b':b})))\n\n@template\nclass DEMUX(Gate):\n defaultShape = {'s': 1}\n\n @implio({'s': Any, 'b': Any})\n def width(select, input, s, b):\n demux1i, demux2i = DEMUX([select[-1]], input, shape={'s': 1, 'b': b})\n demux1 = DEMUX(select[:-1], demux1i, shape={'s': s - 1, 'b': b})\n demux2 = DEMUX(select[:-1], demux2i, shape={'s': s - 1, 'b': b})\n PinManager.freePin(demux1i, demux2i)\n return demux1 + demux2\n \n @implio({'s': 1, 'b': Any})\n def parallel(select, input, s, b):\n ll, rr = [], []\n for i in range(b):\n l, r = DEMUX(select, [input[i]])\n ll, rr = ll + l, rr + r\n return ll, rr\n \n @implio({'s': 1,}, ('1', '1'), ('2'))\n def compile(select, input, s):\n nt = NOT(select)\n and1 = AND(input, nt)\n PinManager.freePin(nt)\n and2 = AND(input, select)\n return and1, and2\n\n@template\nclass ADEMUX(Gate):\n @implio({'s': Any, 'b': Any})\n def compile(select, input, *regs, s=0, b=0):\n nregs = DEMUX(select, input, shape={'s': s, 'b': b})\n one = ONE()\n nselect = DEMUX(select, one, shape={'s': s, 'b': 1})\n nnregs = ()\n PinManager.freePin(one)\n for i in range(len(regs)):\n nreg = MUX(nselect[i], regs[i], nregs[i], shape={'s': 1, 'b': b})\n PinManager.freePin(nselect[i], nregs[i])\n nnregs += (nreg,)\n \n return nnregs\n\n@template\nclass DEMUXP(Gate):\n @implio({'s': Any, 'b': Any}, ('s', 'b'), ('b*2**s',))\n def decorate(select, input, s, b):\n return flatten(DEMUX(select, input, shape={'s': s, 'b': b}))\n\n@template\nclass BSL(Gate):\n @implio({'b': Any}, ('2**b', 'b'), ('2**b',))\n def compile(register, shift, b):\n zero = ZERO()\n register = COPY(register)\n for i in range(b):\n alternate = zero * 2**i + register[:-2**i]\n nregister = MUX([shift[i]], register, alternate, shape={'s': 1, 'b': 2**b})\n PinManager.freePin(register)\n register = nregister\n PinManager.freePin(zero)\n return register\n\n@template\nclass BSR(Gate):\n @implio({'b': Any}, ('2**b', 'b'), ('2**b',))\n def compile(register, shift, b):\n zero = ZERO()\n register = COPY(register)\n for i in range(b):\n alternate = register[2**i:] + zero * 2**i\n nregister = MUX([shift[i]], register, alternate, shape={'s': 1, 'b': 2**b})\n PinManager.freePin(register)\n register = nregister\n PinManager.freePin(zero)\n return register\n\n@template\nclass ALU(Gate):\n @implio({'b': Any}, ('b', 'b', '7'), ('b', '3'))\n def compile(microcode, A, B, b):\n nota = NOT(A, shape={'b': b})\n A = MUX([microcode[0]], A, nota, shape={'s': 1, 'b': b})\n PinManager.freePin(nota)\n \n inca, carrya = HINC(A, shape={'b': b})\n A = MUX([microcode[1]], A, inca, shape={'s': 1, 'b': b})\n PinManager.freePin(inca, carrya)\n\n notb = NOT(B, shape={'b': b})\n B = MUX([microcode[2]], B, notb, shape={'s': 1, 'b': b})\n PinManager.freePin(notb)\n \n incb, carryb = HINC(B, shape={'b': b})\n B = MUX([microcode[3]], B, incb, shape={'s': 1, 'b': b})\n PinManager.freePin(incb, carryb)\n\n add, carryFlag = HADD(A, B, shape={'b': b})\n bsl = BSL (A, B, shape={'b': round(math.log(b, 2))})\n bsr = BSR (A, B, shape={'b': round(math.log(b, 2))})\n and_ = AND (A, B, shape={'b': b})\n or_ = OR (A, B, shape={'b': b})\n xor = XOR (A, B, shape={'b': b})\n \n ret = MUX(microcode[4:7], A, B, add, bsl, bsr, and_, or_, xor, shape={'s': 3, 'b': b})\n PinManager.freePin(add, bsl, bsr, and_, or_, xor)\n\n nonzeroFlag = OR(ret, shape={'w': b})\n zeroFlag = NOT(nonzeroFlag)\n negativeFlag = [ret[b - 1]]\n positiveFlag = NOT(negativeFlag)\n \n return ret, carryFlag + zeroFlag + nonzeroFlag + positiveFlag + negativeFlag\n\n@template\nclass RAM(Gate):\n @implio({'b': Any, 's': Any, 'init': 1})\n def init(b, s, init):\n CodeManager.defines.append(f'std::bitset<{b*2**s}> RAM;')\n CodeManager.code.append('size_t RAMINDEX = 0;')\n\n @implio({'b': Any, 's': Any, 'r': 1}, ('s',), ('b',))\n def read(ptr, b, s, r):\n CodeManager.code.append(f'RAMINDEX = {\" + \".join([f\"(pins[{ptr[i]}] << {i})\" for i in range(s)])};')\n ret = []\n for i in range(b):\n ret += PinManager.requestPin()\n CodeManager.code.append(f'pins[{ret[-1]}] = RAM[{b} * RAMINDEX + {i}];')\n return ret\n \n @implio({'b': Any, 's': Any, 'w': 1}, ('s', 'b',), ())\n def write(ptr, val, b, s, w):\n CodeManager.code.append(f'RAMINDEX = {\" + \".join([f\"(pins[{ptr[i]}] << {i})\" for i in range(s)])};')\n [CodeManager.code.append(f'RAM[{b} * RAMINDEX + {i}] = pins[{val[i]}];') for i in range(b)]\n\n@template\nclass CPUMicrocodeLookup(Gate):\n @implio({'init': 1}, (), ())\n def init(init):\n CPUMicrocodeLookup.codes = [OCCPU[i] for i in range(len(OCCPU))]\n cppcodes = ', '.join([f'0b{code[::-1]}' for code in CPUMicrocodeLookup.codes])\n CodeManager.defines.append(f'std::bitset<{len(CPUMicrocodeLookup.codes[0])}> CPUMicrocodeLookup[{len(CPUMicrocodeLookup.codes)}] = {\"{\"}{cppcodes}{\"}\"};')\n CodeManager.defines.append('size_t CPUMicrocodeLookupIndex = 0;')\n\n oshape = (s if type(s) == int else sum(s) for s in OCCPU._shape())\n \n @implio({'b': Any,}, ('b',), (str(l) for l in oshape))\n def compile(opcode, b):\n CodeManager.code.append(f'CPUMicrocodeLookupIndex = {\" + \".join([f\"(pins[{opcode[i]}] << {i})\" for i in range(b)])};')\n pinret = []\n for i in range(len(CPUMicrocodeLookup.codes[0])):\n pinret += PinManager.requestPin()\n CodeManager.code.append(f'pins[{pinret[-1]}] = CPUMicrocodeLookup[CPUMicrocodeLookupIndex][{i}];')\n ret = ()\n i = 0\n for l in CPUMicrocodeLookup.oshape:\n ret += (pinret[i:i + l],)\n i += l\n return ret\n\n@template\nclass CPUALUIN(Gate):\n @implio({'b': Any, 'reg': Any, 'opcodeLen': Any})\n def compile(microcode, command, command2, regs, b, reg, opcodeLen):\n zero = ZERO()\n\n Aind = command[opcodeLen:opcodeLen + reg]\n Aind = MUX(microcode, Aind, Aind, zero * reg, Aind, shape={'s': 2, 'b': reg})\n Areg = MUX(Aind, *regs, shape={'s': reg, 'b': b})\n\n Bind = command[opcodeLen + reg:opcodeLen + 2 * reg]\n Breg_ = MUX(Bind, *regs, shape={'s': reg, 'b': b})\n Breg = MUX(microcode, Breg_, command[opcodeLen + reg:] + zero * (opcodeLen + reg), command[opcodeLen:] + zero * opcodeLen, command2, shape={'s': 2, 'b': b})\n\n PinManager.freePin(zero, Breg_)\n return Aind, Areg, Bind, Breg\n\n@template\nclass CPURAMIN(Gate):\n @implio({'b': Any, 'ram': Any})\n def compile(microcode, Areg, Breg, trash, b, ram):\n zero = ZERO()\n A = RAM(Areg, shape={'b': b, 's': ram, 'r': 1})\n B = RAM(Breg, shape={'b': b, 's': ram, 'r': 1})\n ret = MUX(microcode, trash, A, B, zero * b, shape={'s': 2, 'b': b})\n PinManager.freePin(A, B)\n return ret\n\n@template\nclass CPUALUOUT(Gate):\n @implio({'b': Any, 'reg': Any})\n def compile(microcode, ret, Aind, regs, b, reg):\n zero = ZERO()\n regVal = MUX(Aind, *regs, shape={'s': reg, 'b': b})\n retCarry = MUX([regs[CPU.flagInd][0]], regVal, ret, shape={'s': 1, 'b': b})\n retZero = MUX([regs[CPU.flagInd][1]], regVal, ret, shape={'s': 1, 'b': b})\n retNonZero = MUX([regs[CPU.flagInd][2]], regVal, ret, shape={'s': 1, 'b': b})\n retPositive = MUX([regs[CPU.flagInd][3]], regVal, ret, shape={'s': 1, 'b': b})\n retNegative = MUX([regs[CPU.flagInd][4]], regVal, ret, shape={'s': 1, 'b': b})\n regVal = MUX(microcode, regVal, ret, retCarry, retZero, retNonZero, retPositive, retNegative, zero * b, shape={'s': 3, 'b': b})\n PinManager.freePin(zero, retCarry, retZero, retNonZero, retPositive, retNegative)\n regs = ADEMUX(Aind, regVal, *regs, shape={'s': reg, 'b': b})\n PinManager.freePin(regVal)\n return regs\n\n@template\nclass CPURAMOUT(Gate):\n @implio({'b': Any, 'ram': Any,})\n def compile(microcode, trash, Areg, Breg, b, ram):\n zero = ZERO()\n ptr = MUX(microcode, zero * b, zero * b, Areg, Breg, shape={'s': 2, 'b': b})\n pram = RAM(ptr, shape={'b': b, 's': ram, 'r': 1})\n\n val = MUX(microcode, pram, zero * b, trash, trash, shape={'s': 2, 'b': b})\n\n RAM(ptr, val, shape={'b': b, 's': ram, 'w': 1})\n\n PinManager.freePin(zero, ptr, pram, val)\n\n@template\nclass CPUPCINC(Gate):\n @implio({'b': Any})\n def compile(microcode, pc, b):\n zero = ZERO()\n ret, _ = HADD(pc, microcode + zero * (b - len(microcode)), shape={'b': b})\n PinManager.freePin(zero, _)\n return ret\n\n@template\nclass CPU(Gate):\n opCodeLen = len2(OCCPU)\n pcInd = 0\n trashInd = 1\n flagInd = 2\n\n @implio({'b': Any, 'reg': Any, 'ram': Any})\n def compile(regs, b, reg, ram):\n\n RAM(shape={'b': b, 's': ram, 'init': 1})\n CPUMicrocodeLookup(shape={'init': 1})\n\n pc = regs[CPU.pcInd]\n pcinc_, _ = HINC(pc, shape={'b': b})\n PinManager.freePin(_)\n command = RAM(pc [:ram], shape={'b': b, 's': ram, 'r': 1})\n command2 = RAM(pcinc_[:ram], shape={'b': b, 's': ram, 'r': 1})\n\n aluin, ramin, alu, aluout, ramout, pcinc = CPUMicrocodeLookup(command[:CPU.opCodeLen], shape={'b': CPU.opCodeLen})\n\n Aind, Areg, Bind, Breg = CPUALUIN(aluin, command, command2, regs, shape={'b': b, 'reg': reg, 'opcodeLen': CPU.opCodeLen})\n\n regs[CPU.trashInd] = CPURAMIN(ramin, Areg, Breg, regs[CPU.trashInd], shape={'b': b, 'ram': ram})\n \n PinManager.freePin(Areg, Bind, Breg, ramin)\n Aind, Areg, Bind, Breg = CPUALUIN(aluin, command, command2, regs, shape={'b': b, 'reg': reg, 'opcodeLen': CPU.opCodeLen})\n PinManager.freePin(aluin)\n\n aluret, flags = ALU(alu, Areg, Breg, shape={'b': b})\n regs[CPU.flagInd][:len(flags)] = flags\n PinManager.freePin(alu)\n\n nregs = list(CPUALUOUT(aluout, aluret, Aind, regs, shape={'b': b, 'reg': reg}))\n PinManager.freePin(aluout, Aind, regs[CPU.trashInd], regs[CPU.flagInd])\n regs = nregs\n\n CPURAMOUT(ramout, regs[CPU.trashInd], Areg, Breg, shape={'b': b, 'ram': ram})\n PinManager.freePin(ramout, Areg, Breg)\n\n regs[CPU.pcInd] = CPUPCINC(pcinc, regs[CPU.pcInd], shape={'b': b})\n \n return regs\n\n@template\nclass CPUP(Gate):\n @implio({'b': Any, 'reg': Any, 'ram': Any}, ('b*2**reg',), (('b*2**reg',)))\n def compile(regs, b, reg, ram):\n regs = list(regs[b * i: b * (i + 1)] for i in range(2**reg))\n regs = CPU(regs, shape={'b': b, 'reg': reg, 'ram': ram})\n return flatten(regs)\n","repo_name":"vasilykuzmin/emu2","sub_path":"translation/gate.py","file_name":"gate.py","file_ext":"py","file_size_in_byte":19045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27985537430","text":"\r\nfrom casadi import MX, fabs, hcat, horzcat, vertcat, Opti, Function, nlpsol, sum1, qpsol, vcat, integrator\r\nfrom scipy.integrate import solve_ivp\r\nfrom casadi import sqrt as csqrt\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom data.parameters import Parameters, Lim_c\r\nfrom data.param import *\r\nfrom data.bcs_envelope import BcsEnvelope\r\n\r\n\r\nclass BCS_model(object):\r\n def __init__(self, nu, nx, ny, Ts, umin, umax, dumax):\r\n self.par = Parameters()\r\n self.Ts, self.umin, self.umax, self.dumax = Ts, umin, umax, dumax\r\n self.J = None\r\n self.pm = 20e5\r\n self.pr = 1.26e7\r\n self.ny = ny\r\n # self.nu=r.shape[0]\r\n self.nu = nu\r\n self.nx = nx\r\n self.ny = ny\r\n self.x = MX.sym(\"x\", self.nx) # Estados\r\n self.u = MX.sym(\"u\", self.nu) # Exogena\r\n self.eq_estado = None\r\n\r\n self.y = None\r\n self.sol = None\r\n self.estacionario = None\r\n self.matrizes_ekf = None\r\n self.sea_nl = None\r\n self.xss=np.vstack([8311024.82175957, 2990109.06207437,\r\n 0.00995042241351780, 50, 50])\r\n self.uss = np.vstack([50, 50])\r\n self.yss = np.vstack([6000142.88550200, 592.126490003812])\r\n self.y_sc=np.vstack([12e6,1300]) # output scale factor\r\n self.BCS_equation()\r\n self.dudt_max = MX.sym(\"dudt_max\", 2) # Exogena\r\n\r\n self.envelope = BcsEnvelope()\r\n \r\n\r\n def norm_x(self, x):\r\n \"\"\"Normalize x \r\n Args:\r\n x (_type_): Column array\r\n Returns:\r\n _type_: Column array\r\n \"\"\"\r\n if x.shape[1] != 1:\r\n raise ValueError\r\n if x.shape[0]==3:\r\n xn = (x-self.par.x0[0:3])/self.par.xc[0:3]\r\n else: \r\n xn = (x-self.par.x0)/self.par.xc\r\n return xn\r\n \r\n def desnorm_x(self, xn):\r\n \"\"\"Desnormalize x \r\n Args:\r\n xn (_type_): Column array\r\n Returns:\r\n _type_: Column array\r\n \"\"\"\r\n if xn.shape[1] != 1:\r\n raise ValueError\r\n if xn.shape[0]==3:\r\n x = (xn*self.par.xc[0:3]+self.par.x0[0:3])\r\n else:\r\n x = (xn*self.par.xc+self.par.x0)\r\n return x\r\n def update_BCS(self,pm,pr):\r\n self.pr=pr\r\n self.pm=pm\r\n self.BCS_equation()\r\n\r\n def BCS_equation(self):\r\n x = self.x # Estados\r\n u = self.u # Exogena\r\n # estados\r\n pbh = x[0]\r\n pwh = x[1]\r\n q = x[2]\r\n q=q.attachAssert(q>0, \"Negative flow detected!\")\r\n fq = x[3]*self.par.xc[3]\r\n zc = x[4]*self.par.xc[3]\r\n # Entradas\r\n fqref = u[0]\r\n zcref = u[1]\r\n pm = self.pm\r\n pr = self.pr\r\n # pm=u[2]\r\n # pr=u[3]\r\n\r\n # Calculo do HEAD e delta de press�o\r\n q0 = ((q*self.par.qc+self.par.qmin) / Cq * (f0 / fq))\r\n H0 = -1.2454e6 * q0 ** 2 + 7.4959e3 * q0 + 9.5970e2\r\n H = (CH * H0 * (fq / f0) ** 2) # Head\r\n # Pp = rho * g * H # Delta de press�o\r\n\r\n # Calculo da Potencia e corrente da bomba\r\n P0 = -2.3599e9 * q0 ** 3 - 1.8082e7 * q0 ** 2 + 4.3346e6 * q0 + 9.4355e4\r\n P = Cp * P0 * (fq / f0) ** 3 # Potencia\r\n I = Inp * P / Pnp # Corrente\r\n\r\n # Calculo da press�o de intake\r\n F1 = (0.158 * ((rho * L1 * ((q*self.par.qc+self.par.qmin)) ** 2) / (D1 * A1 ** 2))\r\n * (mu / (rho * D1 * ((q*self.par.qc+self.par.qmin)))) ** (1 / 4))\r\n F2 = 0.158 * ((rho * L2 * ((q*self.par.qc+self.par.qmin)) ** 2) / (D2 * A2 ** 2)\r\n ) * (mu / (rho * D2 * ((q*self.par.qc+self.par.qmin)))) ** (1 / 4)\r\n pin = (pbh*self.par.pbc+self.par.pbmin - rho * g * h1 - F1)\r\n #pin = (pbh*self.par.pbc+self.par.pbmin - rho * g * h1 - F1)\r\n # Vazao do reservatorio e vazao na choke\r\n qr = PI * (pr - (pbh*self.par.pbc+self.par.pbmin))\r\n qch = (zc/100)*Cc * csqrt(fabs(pwh*self.par.pwc+self.par.pwmin - pm))\r\n F1c = Lim_c(self.par.F1lim)\r\n F2c = Lim_c(self.par.F2lim)\r\n Hc = Lim_c(self.par.H_lim)\r\n qcc = Lim_c(self.par.qch_lim)\r\n # Normalizar termos não lineares\r\n ##########################\r\n qch = (qch-self.par.qch_lim[0])/qcc\r\n F1 = ((F1-self.par.F1lim[0])/F1c)\r\n F2 = ((F2-self.par.F2lim[0])/F2c)\r\n\r\n H = (H-self.par.H_lim[0])/Hc\r\n ###########################\r\n\r\n dpbhdt = (1/self.par.pbc)*b1/V1*(qr - (q*self.par.qc+self.par.qmin))\r\n dpwhdt = (1/self.par.pwc)*b2/V2 * \\\r\n ((q*self.par.qc+self.par.qmin) - (qcc*qch+self.par.qch_lim[0]))\r\n dqdt = ((1/(self.par.qc*M))*(pbh*self.par.pbc+self.par.pbmin - (pwh*self.par.pwc+self.par.pwmin) - rho *\r\n g*hw - (F1c*F1+self.par.F1lim[0]) - (F2c*F2+self.par.F2lim[0]) + rho * g * (H*Hc+self.par.H_lim[0])))\r\n dfqdt = (fqref - fq)/tp[0]\r\n dzcdt = (zcref - zc)/tp[1]\r\n self.dxdt = vertcat(dpbhdt, dpwhdt, dqdt, dfqdt, dzcdt)\r\n yp = vertcat(pin, (H*Hc+self.par.H_lim[0]))\r\n self.c_eq_medicao = Function('c_eq_medicao', [x], [yp], ['xn'], ['yp'])\r\n self.eq_estado = Function('eq_estado', [x, u], [\r\n self.dxdt], ['x', 'u'], ['dxdt'])\r\n dxdt_0 = self.eq_estado(x, u)\r\n self.J = sum1(dxdt_0**2)\r\n\r\n # EDO\r\n # -------------------------------------------------\r\n\r\n opt = {\r\n 'ipopt': {\r\n 'print_level': 0,\r\n 'acceptable_tol': 1e-8,\r\n 'acceptable_obj_change_tol': 1e-6,\r\n 'max_iter': 50\r\n },\r\n 'print_time': 0,\r\n }\r\n\r\n MMQ = {'x': x, 'f': self.J, 'p': u}\r\n self.solver = nlpsol('solver', 'ipopt', MMQ, opt)\r\n \r\n args = {\r\n 'lbx': np.zeros((self.nx, 1)),\r\n # m�ximo\r\n 'ubx': np.full((self.nx, 1), np.inf)\r\n }\r\n # CVODES from the SUNDIALS suite\r\n # CVODES from the SUNDIALS suite\r\n dae = {'x':x, 'p':u, 'ode':self.dxdt, 'quad':self.J}\r\n opts = {'tf':self.Ts, 'expand':True}\r\n self.F = integrator('F', 'cvodes', dae, opts)\r\n \r\n # # Evaluate at a test point\r\n # print(\"Steadystate evaluation\")\r\n # print(self.xss.T)\r\n # Fk = self.F(x0=self.norm_x(self.xss),p=self.uss)\r\n # print(self.desnorm_x(Fk['xf']))\r\n\r\n\r\n\r\n def eq_medicao(self, x):\r\n pbh = x[0]\r\n q = x[2]\r\n fq = x[3]\r\n # Calculo do HEAD e delta de press�o\r\n q0 = q / Cq * (f0 / fq)\r\n H0 = -1.2454e6 * q0 ** 2 + 7.4959e3 * q0 + 9.5970e2\r\n H = CH * H0 * (fq / f0) ** 2 # Head\r\n # Calculo da Potencia e corrente da bomba\r\n P0 = -2.3599e9 * q0 ** 3 - 1.8082e7 * q0 ** 2 + 4.3346e6 * q0 + 9.4355e4\r\n P = Cp * P0 * (fq / f0) ** 3 # Potencia\r\n # Calculo da press�o de intake\r\n F1 = 0.158 * ((rho * L1 * (q) ** 2) / (D1 * A1 ** 2)) * \\\r\n (mu / (rho * D1 * q)) ** (1 / 4)\r\n pin = pbh - rho * g * h1 - F1\r\n return vertcat([pin, H])\r\n\r\n def integrator_ode(self, xss, uss):\r\n xssn = (xss-self.par.x0)/self.par.xc\r\n #array([0.656882 , 0.58981816, 0.41643043])\r\n sol = self.solver(x0=xssn, p=uss)\r\n a = sol['x']\r\n xn = np.array(sol['x'])\r\n x = (xn*self.par.xc+self.par.x0)\r\n return x\r\n\r\n def bcs_model(self, t, x, u):\r\n # estados\r\n pbh = x[0]\r\n pwh = x[1]\r\n q = x[2]\r\n fq = x[3]\r\n zc = x[4]\r\n # Entradas\r\n fqref = u[0]\r\n zcref = u[1]\r\n pm = self.pm\r\n pr = 1.26e7\r\n # pm=u[2]\r\n # pr=u[3]\r\n\r\n # Calculo do HEAD e delta de press�o\r\n q0 = (q*self.par.qc+self.par.qmin) / Cq * (f0 / fq)\r\n H0 = -1.2454e6 * q0 ** 2 + 7.4959e3 * q0 + 9.5970e2\r\n H = CH * H0 * (fq / f0) ** 2 # Head\r\n # Pp = rho * g * H # Delta de press�o\r\n\r\n # Calculo da Potencia e corrente da bomba\r\n P0 = -2.3599e9 * q0 ** 3 - 1.8082e7 * q0 ** 2 + 4.3346e6 * q0 + 9.4355e4\r\n P = Cp * P0 * (fq / f0) ** 3 # Potencia\r\n I = Inp * P / Pnp # Corrente\r\n\r\n # Calculo da press�o de intake\r\n F1 = 0.158 * ((rho * L1 * ((q*self.par.qc+self.par.qmin)) ** 2) / (D1 * A1 ** 2)\r\n ) * (mu / (rho * D1 * ((q*self.par.qc+self.par.qmin)))) ** (1 / 4)\r\n F2 = 0.158 * ((rho * L2 * ((q*self.par.qc+self.par.qmin)) ** 2) / (D2 * A2 ** 2)\r\n ) * (mu / (rho * D2 * ((q*self.par.qc+self.par.qmin)))) ** (1 / 4)\r\n pin = pbh*self.par.pbc+self.par.pbmin - rho * g * h1 - F1\r\n # Vazao do reservatorio e vazao na choke\r\n qr = PI * (pr - (pbh*self.par.pbc+self.par.pbmin))\r\n qch = (zc/100)*Cc * math.sqrt(abs(pwh*self.par.pwc+self.par.pwmin - pm))\r\n\r\n # Termos não lineares\r\n # #menor q implica em menor F\r\n # funcH=Function('funcH',[self.x,self.u],[H])\r\n # funcF1=Function('funcF1',[self.x],[F1])\r\n # funcF2=Function('funcF2',[self.x],[F2])\r\n # #F1lim=(funcF1([0,0,self.par.qlim[0]]),funcF1([0,0,self.par.qlim[1]]))\r\n # #F2lim=(funcF2([0,0,self.par.qlim[0]]),funcF2([0,0,self.par.qlim[1]]))\r\n F1c = Lim_c(self.par.F1lim)\r\n F2c = Lim_c(self.par.F2lim)\r\n Hc = Lim_c(self.par.H_lim)\r\n qcc = Lim_c(self.par.qch_lim)\r\n # Normalizar termos não lineares\r\n ##########################\r\n qch = (qch-self.par.qch_lim[0])/qcc\r\n F1 = (F1-self.par.F1lim[0])/F1c\r\n F2 = (F2-self.par.F2lim[0])/F2c\r\n H = (H-self.par.H_lim[0])/Hc\r\n ###########################\r\n\r\n dpbhdt = (1/self.par.pbc)*b1/V1*(qr - (q*self.par.qc+self.par.qmin))\r\n dpwhdt = (1/self.par.pwc)*b2/V2 * \\\r\n ((q*self.par.qc+self.par.qmin) - (qcc*qch+self.par.qch_lim[0]))\r\n dqdt = (1/(self.par.qc*M))*(pbh*self.par.pbc+self.par.pbmin - (pwh*self.par.pwc+self.par.pwmin) - rho *\r\n g*hw - (F1c*F1+self.par.F1lim[0]) - (F2c*F2+self.par.F2lim[0]) + rho * g * (H*Hc+self.par.H_lim[0]))\r\n dfqdt = (fqref - fq)/tp[0]\r\n dzcdt = (zcref - zc)/tp[1]\r\n dudt_max = [dfq_max, dzc_max]\r\n dudt = np.zeros((1, 2))\r\n if abs(dfqdt) > dudt_max[0]:\r\n dudt[0] = np.sign(dfqdt)*dudt_max[0]\r\n else:\r\n dudt[0] = dfqdt\r\n if (abs(dzcdt) > dudt_max[1]):\r\n dudt[1] = np.sign(dzcdt)*dudt_max[1]\r\n else:\r\n dudt[1] = dzcdt\r\n dxdt = np.vstack(dpbhdt, dpwhdt, dqdt, dudt[0], dudt[1])\r\n return dxdt\r\n\r\n def open_loop_sim(self, x0m, du, uk_1, pm):\r\n y = []\r\n for k in range(self.Hp):\r\n uk_1 = uk_1 + du[(k)*self.nu:2+k*self.nu, :]\r\n xk = self.integrator_ode(x0m, uk_1)\r\n x0m = xk\r\n ymk = self.eq_medicao(x0m) # dimension ny\r\n y.append(ymk) # dimension Hp*ny\r\n y = vcat(y)\r\n return y\r\n # def c_open_loop_sim(self,x0m,du,uk_1,pm):\r\n # y=[]\r\n # for k in range(self.Hp):\r\n # uk_1 = uk_1 + du[(k)*self.nu:2+k*self.nu,:]\r\n # xk=self.integrator_ode(x0m,uk_1)\r\n # x0m = xk\r\n # ymk = self.c_eq_medicao(x0m); # dimension ny\r\n # y.append(ymk) # dimension Hp*ny\r\n # y=vertcat(y)\r\n # return y\r\n \r\n\r\n \r\n\r\n def RK_integrator(self, x, u):\r\n sol = solve_ivp(self.bcs_model, [0, self.Ts], [x, u], method='RK45')\r\n sol.y[0]\r\n\r\n def eq_medicao(self, x):\r\n pbh = x[0]\r\n q = x[2]\r\n fq = x[3]\r\n # Calculo do HEAD e delta de press�o\r\n q0 = q / Cq * (f0 / fq)\r\n H0 = -1.2454e6 * q0 ** 2 + 7.4959e3 * q0 + 9.5970e2\r\n H = CH * H0 * (fq / f0) ** 2 # Head\r\n # Calculo da Potencia e corrente da bomba\r\n P0 = -2.3599e9 * q0 ** 3 - 1.8082e7 * q0 ** 2 + 4.3346e6 * q0 + 9.4355e4\r\n P = Cp * P0 * (fq / f0) ** 3 # Potencia\r\n # Calculo da press�o de intake\r\n F1 = 0.158 * ((rho * L1 * (q) ** 2) / (D1 * A1 ** 2)) * \\\r\n (mu / (rho * D1 * q)) ** (1 / 4)\r\n pin = pbh - rho * g * h1 - F1\r\n return vertcat(pin, H)\r\n","repo_name":"tanielfranklin/NMPC_PINN","sub_path":"data/BCS_casadi.py","file_name":"BCS_casadi.py","file_ext":"py","file_size_in_byte":12235,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"28908753498","text":"from typing import List\n\n# class Solution:\n# def rob(self, nums: List[int]) -> int:\n# \"\"\"\n# 2 7 9 3 1\n\n# 2\n# 7\n# max(2+9,7)\n# 不取9,取9\n# \"\"\"\n# # dp[i]: 0-i 所能获得的最大金钱\n# # dp[i] = max(dp[i-2]+nums[i], dp[i-1])\n# if len(nums) <= 1:\n# return nums[0]\n# dp = [0 for _ in nums]\n# dp[0] = nums[0]\n# dp[1] = max(nums[0], nums[1])\n# for i in range(2, len(nums)):\n# dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\n# return dp[len(nums) - 1]\n\n\nclass Solution:\n def rob(self, nums: List[int]) -> int:\n if len(nums) <= 1:\n return nums[0]\n # 状态压缩\n dp_0 = nums[0]\n dp_1 = max(nums[0], nums[1])\n for i in range(2, len(nums)):\n dp_0, dp_1 = dp_1, max(dp_0 + nums[i], dp_1)\n return dp_1\n\n\nif __name__ == \"__main__\":\n assert Solution().rob([1]) == 1\n assert Solution().rob([1, 2, 3, 1]) == 4\n assert Solution().rob([2, 7, 9, 3, 1]) == 12\n","repo_name":"wsgggws/leetcode","sub_path":"leetcode75/day27_198.py","file_name":"day27_198.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"52"} +{"seq_id":"5822355562","text":"def get_lines_from_text(text, trim_lines):\r\n lines = []\r\n line = ''\r\n lastVk = None\r\n for a in text:\r\n if ord(a) in [10, 13]:\r\n if lastVk is not None:\r\n if lastVk != a:\r\n lastVk = None\r\n continue\r\n else:\r\n lines += ['']\r\n else:\r\n ln = line\r\n if trim_lines:\r\n ln = ln.strip()\r\n lines += [ln]\r\n line = ''\r\n lastVk = a\r\n else:\r\n lastVk = None\r\n line += a\r\n\r\n if trim_lines:\r\n line = line.strip()\r\n if line != '':\r\n lines += [line]\r\n\r\n res = []\r\n pre = []\r\n top = True\r\n for l in lines:\r\n if l == '':\r\n if top:\r\n continue\r\n else:\r\n pre += [l]\r\n else:\r\n if top:\r\n top = False\r\n else:\r\n res += pre\r\n pre = []\r\n res += [l]\r\n\r\n if len(res) == 0:\r\n res += ['']\r\n return res\r\n \r\ndef trim_by_lines(text):\r\n return get_lines_from_text(text, trim_lines=True)\r\n","repo_name":"nikabc555/humanValues","sub_path":"hv/txt_funcs.py","file_name":"txt_funcs.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21056595080","text":"from pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession\n\n# Ref: https://blog.csdn.net/a5685263/article/details/102265838\nconf = SparkConf().set(\"spark.executor.memory\", \"64g\").set(\"spark.executor.cores\", \"16\")\nconf.set(\"spark.driver.memory\", \"16g\") # 这里是增加jvm的内存\nconf.set(\"spark.driver.maxResultSize\", \"16g\") # 这里是最大显示结果,这里是提示我改的。\nconf.setMaster('local[*]')\n\nsc = SparkContext(conf=conf)\nspark = SparkSession.builder.config(conf=conf).getOrCreate()","repo_name":"wenke727/GBA_tranportation","sub_path":"src/utils/spark_helper.py","file_name":"spark_helper.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"45806542456","text":"### Challenge\n# 1. 또 다른 구직 웹사이트에 대한 job extractor 만들기\n# 2. 더 많은 page에서 data 수집하기\nfrom extractors.wwr import wwr_extractor\nfrom extractors.indeed import indeed_extractor\nfrom fileCreator import save_to_file\nfrom flask import Flask, render_template, request, redirect, send_file\n\ndb={}\n\napp = Flask(\"JobScrapper\")\n#syntatic sugar\n@app.route(\"/\") #decorator: 해당 경로로 접속하면 바로 아래의 코드가 실행되도록 약속\ndef home():\n return render_template(\"home.html\") # Flask는 default로 templates라는 폴더를 탐색한다\n@app.route(\"/search\")\ndef search():\n keyword = request.args.get(\"keyword\")\n if (keyword == None) or (keyword == \"\"):\n return redirect(\"/\")\n if keyword in db:\n jobs=db[keyword]\n else:\n wwr = wwr_extractor(keyword)\n indeed = indeed_extractor(keyword)\n jobs = wwr+indeed\n db[keyword]=jobs\n return render_template(\"search.html\", keyword=keyword, jobs=jobs)\n@app.route(\"/export\")\ndef export():\n keyword = request.args.get(\"keyword\")\n if (keyword == None) or (keyword == \"\"):\n return redirect(\"/\")\n if keyword not in db:\n return redirect(f\"/search?keyword={keyword}\")\n jobs = db[keyword]\n save_to_file(keyword, jobs)\n return send_file(f\"{keyword}.csv\", as_attachment=True)\n# It Allows You to Execute Code When the File Runs as a Script, but Not When It’s Imported as a Module\nif __name__==\"__main__\":\n app.run(\"127.0.0.1\", debug=True)\n\n","repo_name":"engulfedInFlames/python-web_scrapper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3979132589","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom .views import *\n\napp_name = 'leaves'\n\nrouter = DefaultRouter()\nrouter.register('', LeaveViewset, basename='leave')\n\n\nurlpatterns = [\n path('', include(router.urls)),\n path('employee', LeaveRetrieveView.as_view(), name='leave-retrieve'),\n path('list-own', LeaveListSpecificView.as_view(), name='leave-list-own'),\n path('list-requests', LeaveListRequestsView.as_view(), name='leave-list-requests')\n]","repo_name":"Minedomain/hris_backend","sub_path":"hris/apps/leaves/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11314458623","text":"import xarray as xr\nimport numpy\nfrom matplotlib import colors\nfrom matplotlib import cm\n\nfrom geometric_features import FeatureCollection\n\nfrom mpas_tools.ocean.transects import get_outline_segments\n\nfrom mpas_analysis.shared.plot import plot_vertical_section_comparison, \\\n savefig, add_inset\n\nfrom mpas_analysis.shared import AnalysisTask\n\nfrom mpas_analysis.shared.html import write_image_xml\n\nfrom mpas_analysis.shared.climatology import compute_climatology, \\\n get_remapped_mpas_climatology_file_name\n\nfrom mpas_analysis.shared.constants import constants\n\n\nclass PlotTransectSubtask(AnalysisTask):\n \"\"\"\n An analysis task for plotting 2D model fields against observations.\n\n Attributes\n ----------\n season : str\n A season (key in ``shared.constants.monthDictionary``) to be\n plotted.\n\n transectName : str\n The name of the transect to plot\n\n computeTransectsSubtask : ``ComputeTransectsSubtask``\n The subtask for computing the MPAS climatology that this subtask\n will plot\n\n plotObs : bool, optional\n Whether to plot against observations.\n\n controlconfig : mpas_tools.config.MpasConfigParser\n Configuration options for a control run (if any), ignored if\n ``plotObs == True``\n\n horizontalBounds : [float, float]\n The distance in km of the left- and right-hand edges of the plot,\n chosen automatically by default or if the list is empty\n\n outFileLabel : str\n The prefix on each plot and associated XML file\n\n fieldNameInTitle : str\n The name of the field being plotted, as used in the plot title\n\n mpasFieldName : str\n The name of the variable in the MPAS timeSeriesStatsMonthly output\n\n diffTitleLabel : str, optional\n the title of the difference subplot\n\n unitsLabel : str\n the units of the plotted field, to be displayed on color bars\n\n imageCaption : str\n the caption when mousing over the plot or displaying it full\n screen\n\n galleryGroup : str\n the name of the group of galleries in which this plot belongs\n\n groupSubtitle : str\n the subtitle of the group in which this plot belongs (or blank\n if none)\n\n groupLink : str\n a short name (with no spaces) for the link to the gallery group\n\n galleryName : str\n the name of the gallery in which this plot belongs\n\n configSectionName : str\n the name of the section where the color map and range is defined\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis, Greg Streletz\n\n def __init__(self, parentTask, season, transectName, fieldName,\n computeTransectsSubtask, plotObs=True,\n controlConfig=None, horizontalBounds=None):\n\n \"\"\"\n Construct one analysis subtask for each plot (i.e. each season and\n comparison grid) and a subtask for computing climatologies.\n\n Parameters\n ----------\n parentTask : ``AnalysisTask``\n The parent (main) task for this subtask\n\n season : str\n A season (key in ``shared.constants.monthDictionary``) to be\n plotted.\n\n transectName : str\n The name of the transect to plot\n\n fieldName : str\n The name of the field to plot (for use in the subtask name only)\n\n computeTransectsSubtask : ``ComputeTransectsSubtask``\n The subtask for computing the MPAS climatology that this subtask\n will plot\n\n plotObs : bool, optional\n Whether to plot against observations.\n\n controlconfig : mpas_tools.config.MpasConfigParser, optional\n Configuration options for a control run (if any), ignored if\n ``plotObs == True``\n\n horizontalBounds : [float, float], optional\n The distance in km of the left- and right-hand edges of the plot,\n chosen automatically by default or if the list is empty\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n self.season = season\n self.transectName = transectName\n self.computeTransectsSubtask = computeTransectsSubtask\n self.plotObs = plotObs\n self.controlConfig = controlConfig\n if horizontalBounds is not None and len(horizontalBounds) == 2:\n self.horizontalBounds = horizontalBounds\n else:\n self.horizontalBounds = None\n subtaskName = 'plot{}_{}_{}'.format(season,\n transectName.replace(' ', '_'),\n fieldName)\n\n config = parentTask.config\n taskName = parentTask.taskName\n tags = parentTask.tags\n\n # call the constructor from the base class (AnalysisTask)\n super(PlotTransectSubtask, self).__init__(\n config=config, taskName=taskName, subtaskName=subtaskName,\n componentName='ocean', tags=tags)\n\n # this task should not run until the remapping subtasks are done, since\n # it relies on data from those subtasks\n self.run_after(computeTransectsSubtask)\n\n def set_plot_info(self, outFileLabel, fieldNameInTitle, mpasFieldName,\n refFieldName, refTitleLabel, unitsLabel,\n imageCaption, galleryGroup, groupSubtitle, groupLink,\n galleryName, configSectionName, verticalBounds,\n diffTitleLabel='Model - Observations'):\n\n \"\"\"\n Store attributes related to plots, plot file names and HTML output.\n\n Parameters\n ----------\n outFileLabel : str\n The prefix on each plot and associated XML file\n\n fieldNameInTitle : str\n The name of the field being plotted, as used in the plot title\n\n mpasFieldName : str\n The name of the variable in the MPAS timeSeriesStatsMonthly output\n\n refFieldName : str\n The name of the variable to use from the observations or reference\n file\n\n refTitleLabel : str\n the title of the observations or reference subplot\n\n unitsLabel : str\n the units of the plotted field, to be displayed on color bars\n\n imageCaption : str\n the caption when mousing over the plot or displaying it full\n screen\n\n galleryGroup : str\n the name of the group of galleries in which this plot belongs\n\n groupSubtitle : str\n the subtitle of the group in which this plot belongs (or blank\n if none)\n\n groupLink : str\n a short name (with no spaces) for the link to the gallery group\n\n galleryName : str\n the name of the gallery in which this plot belongs\n\n configSectionName : str\n the name of the section where the color map and range is defined\n\n verticalBounds : list\n the min and max for the vertical axis, or an emtpy list if the\n range automatically determined by matplotlib should be used\n\n diffTitleLabel : str, optional\n the title of the difference subplot\n\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n self.outFileLabel = outFileLabel\n self.fieldNameInTitle = fieldNameInTitle\n self.mpasFieldName = mpasFieldName\n self.refFieldName = refFieldName\n self.refTitleLabel = refTitleLabel\n self.diffTitleLabel = diffTitleLabel\n self.unitsLabel = unitsLabel\n\n # xml/html related variables\n self.imageCaption = imageCaption\n self.galleryGroup = galleryGroup\n self.groupSubtitle = groupSubtitle\n self.groupLink = groupLink\n self.galleryName = galleryName\n\n self.fieldNameInTitle = fieldNameInTitle\n self.thumbnailDescription = self.season\n\n self.configSectionName = configSectionName\n if len(verticalBounds) == 0:\n self.verticalBounds = None\n else:\n self.verticalBounds = verticalBounds\n\n def setup_and_check(self):\n \"\"\"\n Perform steps to set up the analysis and check for errors in the setup.\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis\n\n # first, call setup_and_check from the base class (AnalysisTask),\n # which will perform some common setup, including storing:\n # self.runDirectory , self.historyDirectory, self.plotsDirectory,\n # self.namelist, self.runStreams, self.historyStreams,\n # self.calendar\n super(PlotTransectSubtask, self).setup_and_check()\n\n config = self.config\n self.startYear = config.getint('climatology', 'startYear')\n self.endYear = config.getint('climatology', 'endYear')\n self.startDate = config.get('climatology', 'startDate')\n self.endDate = config.get('climatology', 'endDate')\n\n mainRunName = config.get('runs', 'mainRunName')\n\n self.xmlFileNames = []\n\n prefixPieces = []\n if self.outFileLabel != '':\n prefixPieces.append(self.outFileLabel)\n prefixPieces.append(self.transectName.replace(' ', '_'))\n prefixPieces.append(mainRunName)\n years = 'years{:04d}-{:04d}'.format(self.startYear, self.endYear)\n prefixPieces.extend([self.season, years])\n\n self.filePrefix = '_'.join(prefixPieces)\n\n self.xmlFileNames.append('{}/{}.xml'.format(self.plotsDirectory,\n self.filePrefix))\n\n def run_task(self):\n \"\"\"\n Plots a comparison of ACME/MPAS output to SST, MLD or SSS observations\n or a control run\n \"\"\"\n # Authors\n # -------\n # Xylar Asay-Davis, Greg Streletz\n\n season = self.season\n transectName = self.transectName\n self.logger.info(\"\\nPlotting {} over season {}\"\n \"...\".format(self.fieldNameInTitle,\n season))\n\n # first read the model climatology\n remappedFileName = \\\n self.computeTransectsSubtask.get_remapped_file_name(\n season=season, comparisonGridName=transectName)\n\n remappedModelClimatology = xr.open_dataset(remappedFileName)\n\n # now the observations or control run\n if self.plotObs:\n verticalComparisonGridName = \\\n self.computeTransectsSubtask.verticalComparisonGridName\n remappedFileName = \\\n self.computeTransectsSubtask.obsDatasets.get_out_file_name(\n transectName,\n verticalComparisonGridName)\n remappedRefClimatology = xr.open_dataset(remappedFileName)\n\n # if Time is an axis, take the appropriate average to get the\n # climatology\n if 'Time' in remappedRefClimatology.dims:\n monthValues = constants.monthDictionary[season]\n remappedRefClimatology = compute_climatology(\n remappedRefClimatology, monthValues, maskVaries=True)\n\n elif self.controlConfig is not None:\n climatologyName = self.computeTransectsSubtask.climatologyName\n remappedFileName = \\\n get_remapped_mpas_climatology_file_name(\n self.controlConfig, season=season,\n componentName=self.componentName,\n climatologyName=climatologyName,\n comparisonGridName=transectName)\n remappedRefClimatology = xr.open_dataset(remappedFileName)\n controlStartYear = self.controlConfig.getint('climatology',\n 'startYear')\n controlEndYear = self.controlConfig.getint('climatology',\n 'endYear')\n if controlStartYear != self.startYear or \\\n controlEndYear != self.endYear:\n self.refTitleLabel = '{}\\n(years {:04d}-{:04d})'.format(\n self.refTitleLabel, controlStartYear, controlEndYear)\n\n else:\n remappedRefClimatology = None\n\n self._plot_transect(remappedModelClimatology, remappedRefClimatology)\n\n remappedModelClimatology.close()\n\n if remappedRefClimatology is not None:\n remappedRefClimatology.close()\n\n def _plot_transect(self, remappedModelClimatology, remappedRefClimatology):\n\n \"\"\" plotting the transect \"\"\"\n\n season = self.season\n config = self.config\n configSectionName = self.configSectionName\n\n mainRunName = config.get('runs', 'mainRunName')\n\n remap = self.computeTransectsSubtask.remap\n\n if remap:\n x = 1e-3*remappedModelClimatology.x\n z = remappedModelClimatology.z\n\n # set lat and lon in case we want to plot versus these quantities\n lat = remappedModelClimatology.lat\n lon = remappedModelClimatology.lon\n\n if len(lat.dims) > 1:\n lat = lat[:, 0]\n\n if len(lon.dims) > 1:\n lon = lon[:, 0]\n\n # z is masked out with NaNs in some locations (where there is land)\n # but this makes pcolormesh unhappy so we'll zero out those\n # locations\n z = z.where(z.notnull(), 0.)\n\n else:\n x = 1e-3*remappedModelClimatology.dNode\n z = None\n lon = remappedModelClimatology.lonNode\n lat = remappedModelClimatology.latNode\n\n remappedModelClimatology['dNode'] = x\n\n # flatten the x, lon and lat arrays because this is what\n # vertical_section is expecting\n x = xr.DataArray(data=x.values.ravel(), dims=('nx',))\n lon = xr.DataArray(data=lon.values.ravel(), dims=('nx',))\n lat = xr.DataArray(data=lat.values.ravel(), dims=('nx',))\n\n # This will do strange things at the antemeridian but there's little\n # we can do about that.\n lon_pm180 = numpy.mod(lon + 180., 360.) - 180.\n\n if self.horizontalBounds is not None:\n mask = numpy.logical_and(\n x.values >= self.horizontalBounds[0],\n x.values <= self.horizontalBounds[1])\n inset_lon = lon_pm180.values[mask]\n inset_lat = lat.values[mask]\n else:\n inset_lon = lon_pm180.values\n inset_lat = lat.values\n\n fc = FeatureCollection()\n fc.add_feature(\n {\"type\": \"Feature\",\n \"properties\": {\"name\": self.transectName,\n \"author\": 'Xylar Asay-Davis',\n \"object\": 'transect',\n \"component\": 'ocean',\n \"tags\": ''},\n \"geometry\": {\n \"type\": \"LineString\",\n \"coordinates\": list(map(list, zip(inset_lon, inset_lat)))}})\n\n modelOutput = remappedModelClimatology[self.mpasFieldName]\n\n if remap:\n triangulation_args = None\n else:\n triangulation_args = self._get_ds_triangulation(\n remappedModelClimatology)\n\n if remappedRefClimatology is None:\n refOutput = None\n bias = None\n else:\n refOutput = remappedRefClimatology[self.refFieldName]\n bias = modelOutput - refOutput\n\n filePrefix = self.filePrefix\n outFileName = '{}/{}.png'.format(self.plotsDirectory, filePrefix)\n title = '{}\\n({}, years {:04d}-{:04d})'.format(\n self.fieldNameInTitle, season, self.startYear,\n self.endYear)\n\n xs = [x]\n xLabels = ['Distance (km)']\n yLabel = 'Depth (m)'\n\n # define the axis labels and the data to use for the upper\n # x axis or axes, if such additional axes have been requested\n\n upperXAxes = config.get('transects', 'upperXAxes')\n numUpperTicks = config.getint('transects', 'numUpperTicks')\n upperXAxisTickLabelPrecision = config.getint(\n 'transects',\n 'upperXAxisTickLabelPrecision')\n\n add_lat = False\n add_lon = False\n\n if upperXAxes in ['lat', 'both']:\n add_lat = True\n if upperXAxes in ['lon', 'both']:\n add_lon = True\n if upperXAxes == 'greatestExtent':\n if self._lat_greater_extent(lat, lon):\n add_lat = True\n else:\n add_lon = True\n elif upperXAxes == 'strictlyMonotonic':\n if self._strictly_monotonic(lat):\n add_lat = True\n elif self._strictly_monotonic(lon):\n add_lon = True\n else:\n raise ValueError('Neither lat nor lon is strictly monotonic.')\n elif upperXAxes == 'mostMonotonic':\n if self._lat_most_monotonic(lat, lon):\n add_lat = True\n else:\n add_lon = True\n elif upperXAxes == 'mostStepsInSameDirection':\n if self._lat_most_steps_in_same_direction(lat, lon):\n add_lat = True\n else:\n add_lon = True\n elif upperXAxes == 'fewestDirectionChanges':\n if self._lat_fewest_direction_changes(lat, lon):\n add_lat = True\n else:\n add_lon = True\n else:\n raise ValueError('invalid option for upperXAxes')\n\n if add_lat:\n xs.append(lat)\n xLabels.append('Latitude')\n if add_lon:\n xs.append(lon)\n xLabels.append('Longitude')\n\n # get the parameters determining what type of plot to use,\n # what line styles and line colors to use, and whether and how\n # to label contours\n\n if config.has_option(configSectionName,\n 'compareAsContoursOnSinglePlot'):\n compareAsContours = config.getboolean(\n configSectionName, 'compareAsContoursOnSinglePlot')\n else:\n compareAsContours = config.getboolean(\n 'transects', 'compareAsContoursOnSinglePlot')\n\n contourLineStyle = config.get('transects', 'contourLineStyle')\n comparisonContourLineStyle = config.get('transects',\n 'comparisonContourLineStyle')\n\n if compareAsContours:\n contourLineWidth = \\\n config.getfloat('transects', 'mainContourLineWidth')\n contourLineColor = None\n comparisonContourLineColor = None\n contourColormap = PlotTransectSubtask._get_contour_colormap()\n labelContours = config.getboolean(\n 'transects', 'labelContoursOnContourComparisonPlots')\n comparisonContourLineWidth = \\\n config.getfloat('transects', 'comparisonContourLineWidth')\n else:\n contourLineWidth = config.getfloat('transects', 'contourLineWidth')\n contourLineColor = config.get('transects', 'contourLineColor')\n comparisonContourLineColor = None\n contourColormap = None\n labelContours = config.getboolean('transects',\n 'labelContoursOnHeatmaps')\n comparisonContourLineWidth = None\n\n contourLabelPrecision = config.getint('transects',\n 'contourLabelPrecision')\n\n if config.has_option(configSectionName, 'titleFontSize'):\n titleFontSize = config.getint(configSectionName, 'titleFontSize')\n else:\n titleFontSize = None\n\n if config.has_option(configSectionName, 'defaultFontSize'):\n defaultFontSize = config.getint(configSectionName,\n 'defaultFontSize')\n else:\n defaultFontSize = None\n\n if config.has_option(configSectionName, 'axisFontSize'):\n axisFontSize = config.getint(configSectionName, 'axisFontSize')\n else:\n axisFontSize = None\n\n # construct a three-panel comparison plot for the transect, or a\n # single-panel contour comparison plot if compareAsContours is True\n\n fig, axes, suptitle = plot_vertical_section_comparison(\n config,\n modelOutput,\n refOutput,\n bias,\n configSectionName,\n xCoords=xs,\n zCoord=z,\n triangulation_args=triangulation_args,\n colorbarLabel=self.unitsLabel,\n xlabels=xLabels,\n ylabel=yLabel,\n title=title,\n modelTitle='{}'.format(mainRunName),\n refTitle=self.refTitleLabel,\n diffTitle=self.diffTitleLabel,\n numUpperTicks=numUpperTicks,\n upperXAxisTickLabelPrecision=upperXAxisTickLabelPrecision,\n invertYAxis=False,\n backgroundColor='#d9bf96',\n invalidColor='#d9bf96',\n outlineValid=False,\n xLim=self.horizontalBounds,\n yLim=self.verticalBounds,\n compareAsContours=compareAsContours,\n lineWidth=contourLineWidth,\n lineStyle=contourLineStyle,\n lineColor=contourLineColor,\n contourColormap=contourColormap,\n comparisonContourLineWidth=comparisonContourLineWidth,\n comparisonContourLineStyle=comparisonContourLineStyle,\n comparisonContourLineColor=comparisonContourLineColor,\n labelContours=labelContours,\n contourLabelPrecision=contourLabelPrecision,\n plotTitleFontSize=titleFontSize,\n defaultFontSize=defaultFontSize,\n axisFontSize=axisFontSize)\n\n # shift the super-title a little to the left to make room for the inset\n pos = suptitle.get_position()\n suptitle.set_position((pos[0] - 0.05, pos[1]))\n\n if not remap:\n # add open ocean or ice shelves\n d = remappedModelClimatology.dNode.values.ravel()\n ssh = remappedModelClimatology.ssh.values.ravel()\n if 'landIceFraction' in remappedModelClimatology:\n # plot ice in light blue\n color = '#e1eaf7'\n else:\n # plot open ocean in white\n color = 'white'\n mask = ssh < 0.\n for ax in axes:\n ax.fill_between(d, ssh, numpy.zeros(ssh.shape), where=mask,\n interpolate=True, color=color)\n\n # make a red start axis and green end axis to correspond to the dots\n # in the inset\n for ax in axes:\n ax.spines['left'].set_color('red')\n ax.spines['right'].set_color('green')\n ax.spines['left'].set_linewidth(4)\n ax.spines['right'].set_linewidth(4)\n\n if compareAsContours:\n add_inset(fig, fc, width=1., height=1., xbuffer=0.1, ybuffer=0.1)\n else:\n add_inset(fig, fc, width=1.5, height=1.5, xbuffer=0.1, ybuffer=0.1)\n\n savefig(outFileName, config, tight=False)\n\n caption = '{} {}'.format(season, self.imageCaption)\n write_image_xml(\n config,\n filePrefix,\n componentName='Ocean',\n componentSubdirectory='ocean',\n galleryGroup=self.galleryGroup,\n groupSubtitle=self.groupSubtitle,\n groupLink=self.groupLink,\n gallery=self.galleryName,\n thumbnailDescription=self.thumbnailDescription,\n imageDescription=caption,\n imageCaption=caption)\n\n def _lat_greater_extent(self, lat, lon):\n\n \"\"\"\n Returns True if lat has a greater extent (in degrees) than lon (or the\n same extent as lon), and False otherwise.\n\n Authors\n -------\n Greg Streletz, Xylar Asay-Davis\n \"\"\"\n lat_extent = numpy.max(lat) - numpy.min(lat)\n\n lon_diff = numpy.diff(lon)\n lon_jump = numpy.where(\n numpy.logical_or(lon_diff > 180, lon_diff < -180), True, False)\n\n if numpy.all(numpy.logical_not(lon_jump)):\n # transect does not cross periodic boundary\n\n lon_extent = numpy.max(lon) - numpy.min(lon)\n\n else:\n # transect crosses periodic boundary at least once, so min and\n # max cannot be used to calculate the longitudinal extent\n\n # calculate the indices at which the transect crosses the\n # right-hand periodic boundary and enters the leftmost region of\n # the domain\n lon_r = numpy.sort(numpy.nonzero(lon_diff < -180)[0] + 1)\n\n # calculate the indices at which the transect crosses the left-hand\n # periodic boundary and enters the rightmost region of the domain\n lon_l = numpy.sort(numpy.nonzero(lon_diff > 180)[0] + 1)\n\n mins = []\n maxes = []\n last_idx = 0\n\n while(len(lon_r) > 0 and len(lon_l) > 0):\n if lon_r[0] < lon_l[0]:\n mins.append(numpy.min(lon[last_idx:lon_r[0]]))\n last_idx = lon_r[0]\n lon_r = lon_r[1:]\n else:\n maxes.append(numpy.max(lon[last_idx:lon_l[0]]))\n last_idx = lon_l[0]\n lon_l = lon_l[1:]\n\n min = numpy.min(mins)\n max = numpy.max(maxes)\n\n if min > max:\n\n lon_extent = 360.0 - (min - max)\n\n # The transect has crossed the periodic boundary,\n # so unless the transect has covered the entire\n # longitudinal range (360 degrees), the \"leftmost\"\n # or \"min\" coordinate of the transect will have a\n # greater value (in degrees longitude) that the\n # \"rightmost\" or \"max\" coordinate of the transect,\n # and (min - max) is the size (in degrees longitude)\n # of the region *not* accessed by the transect. So,\n # the longitudinal extent of the transect is 360\n # degrees minus this value.\n\n else:\n # if max >= min, the transect has covered the\n # entire longitudinal range (360 degrees)\n\n lon_extent = 360.0\n\n if lat_extent >= lon_extent:\n return True\n else:\n return False\n\n def _strictly_monotonic(self, coord):\n\n \"\"\"Whether the coordinate is strictly monotonic\"\"\"\n # Authors\n # -------\n # Greg Streletz, Xylar Asay-Davis\n\n coord_diff = numpy.diff(coord.values)\n coord_diff = numpy.where(coord_diff > 180, coord_diff - 360, coord_diff)\n coord_diff = numpy.where(coord_diff < -180, coord_diff + 360,\n coord_diff)\n return numpy.all(coord_diff > 0) or numpy.all(coord_diff < 0)\n\n def _lat_most_monotonic(self, lat, lon):\n\n \"\"\"\n Returns True if lat is \"more monotonic\" than lon in terms of the\n difference between the total number of degrees traversed and the net\n number of degrees traversed (or if both are equally as monotonic in\n this sense), and False otherwise.\n \"\"\"\n # Authors\n # -------\n # Greg Streletz, Xylar Asay-Davis\n lat_diff = numpy.diff(lat)\n lat_score = numpy.sum(numpy.fabs(lat_diff)) - abs(numpy.sum(lat_diff))\n\n lon_diff = numpy.diff(lon)\n lon_diff = numpy.where(lon_diff > 180, lon_diff - 360, lon_diff)\n lon_diff = numpy.where(lon_diff < -180, lon_diff + 360, lon_diff)\n lon_score = numpy.sum(numpy.fabs(lon_diff)) - abs(numpy.sum(lon_diff))\n\n if lat_score <= lon_score:\n return True\n else:\n return False\n\n def _lat_most_steps_in_same_direction(self, lat, lon):\n\n \"\"\"\n Returns True if lat is has more steps in the same direction (either\n steps that increase the latitude or steps that decrease the latitude)\n than lon (or the same number as lon), and False otherwise.\n \"\"\"\n # Authors\n # -------\n # Greg Streletz, Xylar Asay-Davis\n\n lat_changes = numpy.diff(lat)\n lat_changes = lat_changes[lat_changes != 0.0] # ignore flat regions\n lat_changedirs = lat_changes / numpy.fabs(lat_changes)\n num_lat_positive = numpy.sum(numpy.where(lat_changedirs == 1, 1, 0))\n num_lat_negative = numpy.sum(numpy.where(lat_changedirs == -1, 1, 0))\n max_steps_lat = max(num_lat_positive, num_lat_negative)\n\n lon_changes = numpy.diff(lon)\n lon_changes = \\\n numpy.where(lon_changes > 180, lon_changes - 360, lon_changes)\n lon_changes = \\\n numpy.where(lon_changes < -180, lon_changes + 360, lon_changes)\n lon_changes = lon_changes[lon_changes != 0.0] # ignore flat regions\n lon_changedirs = lon_changes / numpy.fabs(lon_changes)\n num_lon_positive = numpy.sum(numpy.where(lon_changedirs == 1, 1, 0))\n num_lon_negative = numpy.sum(numpy.where(lon_changedirs == -1, 1, 0))\n max_steps_lon = max(num_lon_positive, num_lon_negative)\n\n if max_steps_lat >= max_steps_lon:\n return True\n else:\n return False\n\n def _lat_fewest_direction_changes(self, lat, lon):\n\n \"\"\"\n Returns True if lat is has fewer changes in direction (from increasing\n in value to decreasing in value, or vice versa) than lon (or if both\n have to same number of changes), and False otherwise.\n\n Authors\n -------\n Greg Streletz, Xylar Asay-Davis\n \"\"\"\n lat_changes = numpy.diff(lat)\n lat_changes = lat_changes[lat_changes != 0.0] # ignore flat regions\n lat_changedirs = lat_changes / numpy.fabs(lat_changes)\n lat_changedir_changes = numpy.diff(lat_changedirs)\n num_lat_dirchanges = \\\n len(lat_changedir_changes[lat_changedir_changes != 0.0])\n\n lon_changes = numpy.diff(lon)\n lon_changes = \\\n numpy.where(lon_changes > 180, lon_changes - 360, lon_changes)\n lon_changes = \\\n numpy.where(lon_changes < -180, lon_changes + 360, lon_changes)\n lon_changes = lon_changes[lon_changes != 0.0] # ignore flat regions\n lon_changedirs = lon_changes / numpy.fabs(lon_changes)\n lon_changedir_changes = numpy.diff(lon_changedirs)\n num_lon_dirchanges = \\\n len(lon_changedir_changes[lon_changedir_changes != 0.0])\n\n if num_lat_dirchanges <= num_lon_dirchanges:\n return True\n else:\n return False\n\n def _get_ds_triangulation(self, dsTransectTriangles):\n \"\"\"get matplotlib Triangulation from triangulation dataset\"\"\"\n\n nTransectTriangles = dsTransectTriangles.sizes['nTransectTriangles']\n dNode = dsTransectTriangles.dNode.isel(\n nSegments=dsTransectTriangles.segmentIndices,\n nHorizBounds=dsTransectTriangles.nodeHorizBoundsIndices)\n x = dNode.values.ravel()\n\n zTransectNode = dsTransectTriangles.zTransectNode\n y = zTransectNode.values.ravel()\n\n tris = numpy.arange(3 * nTransectTriangles).reshape(\n (nTransectTriangles, 3))\n triangulation_args = dict(x=x, y=y, triangles=tris)\n\n return triangulation_args\n\n @staticmethod\n def _get_contour_colormap():\n # https://stackoverflow.com/a/18926541/7728169\n\n cmap = cm.get_cmap('hot')\n cmap = colors.LinearSegmentedColormap.from_list(\n f'trunc_{cmap.name}', cmap(numpy.linspace(0.1, 0.85, 100)))\n\n return cmap\n","repo_name":"MPAS-Dev/MPAS-Analysis","sub_path":"mpas_analysis/ocean/plot_transect_subtask.py","file_name":"plot_transect_subtask.py","file_ext":"py","file_size_in_byte":31591,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"52"} +{"seq_id":"16885938290","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom numpy import savetxt\n\ndata_train = pd.read_csv(\"Data_Train.csv\")\ndata_test = pd.read_csv(\"Data_Test.csv\")\n\ndata_views = data_train[\"Views\"]\ny = np.matrix(data_views).transpose()\n\ndata_train.drop(\"Views\", axis=1, inplace=True)\n\nX = np.concatenate((data_train, data_test), axis=0)\n\nX = X.astype(np.str)\n\nX = np.delete(X, 3, axis=1)\n\nX = np.delete(X, 0, axis=1)\n\nX = np.delete(X, 2, axis=1)\n\nX = np.matrix(X)\n\nlabelencoder_name = LabelEncoder().fit(X[:, 0])\nX[:, 0] = np.matrix(labelencoder_name.transform(X[:, 0])).transpose()\n\nlabelencoder_genre = LabelEncoder().fit(X[:, 1])\nX[:, 1] = np.matrix(labelencoder_genre.transform(X[:, 1])).transpose()\n\ntime_stamp = np.char.split(X[:, 2], sep = ':')\n\nfor index in range(len(time_stamp)):\n time_x = np.char.split(X[index, 2], sep = ':')\n time_x = time_x.tolist()\n time_x = np.array(time_x)\n time_min = time_x[0]\n if \"-\" in time_min:\n t_m = float(time_x[1])\n t_s = float(time_x[2])\n X[index, 2] = str(t_m*60 + t_s)\n else:\n t_m = float(time_x[0])\n t_s = float(time_x[1])\n X[index, 2] = str(t_m*60 + t_s)\n \nX[:, 4] = np.char.replace(X[:, 4], ',', '')\n\nX[:, 4] = np.char.replace(X[:, 4], ',', '')\nX[:, 4] = np.char.replace(X[:, 4], 'K', '*1000')\nX[:, 4] = np.char.replace(X[:, 4], 'M', '*1000000')\n\nfor index in range(len(X[:, 4])):\n value = X[index, 4]\n if \"*\" in value:\n value_factor = np.char.split(value, sep = '*').tolist()\n f1 = float(value_factor[0])\n f2 = float(value_factor[1])\n v = f1*f2\n X[index, 4] = str(v)\n \nX[:, 5] = np.char.replace(X[:, 5], ',', '')\nX[:, 5] = np.char.replace(X[:, 5], 'K', '*1000')\n\nfor index in range(len(X[:, 5])):\n value = X[index, 5]\n if \"*\" in value:\n value_factor = np.char.split(value, sep = '*').tolist()\n f1 = float(value_factor[0])\n f2 = float(value_factor[1])\n v = f1*f2\n X[index, 5] = str(v)\n\n\n#X = X.astype(float)\n\n#savetxt('data1.csv', X, delimiter=',', fmt='%s')\n\nonehotencoder = OneHotEncoder(categorical_features=[0, 1])\nX = onehotencoder.fit_transform(X).toarray()\n\nX_train = X[0:len(data_train), :]\nX_test = X[len(data_train):, :]\n\nX_train, X_t, y_train, y_t = train_test_split(X_train, y, test_size = 0.2, random_state=0)\n\nfrom sklearn.preprocessing import StandardScaler\n\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.fit_transform(X_test)\nX_t = sc_X.transform(X_t)\n\nregressor = RandomForestRegressor()\nregressor.fit(X_train, y_train)\ny_pred = regressor.predict(X_t)\ny_predtest = regressor.predict(X_test)\n\nscore_gb = regressor.score(X_t, y_t)\nprint (score_gb)\n\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nrmse = sqrt(mean_squared_error(y_t, y_pred))\n\nprint (rmse)\n\nuid = data_test[\"Unique_ID\"]\nsolution = pd.DataFrame({'Unique_ID': uid, 'Views' : y_predtest})\nsolution.to_excel('Chartbusters_Prediction.xlsx', index = False)\n\n","repo_name":"caustav/machinehack_chartbusters_prediction","sub_path":"chartbusters_prediction.py","file_name":"chartbusters_prediction.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12039093684","text":"import pytest\n\nfrom speechbrain.utils.parallel import parallel_map\n\nsmall_test_input = [1, 2, 3, 4, 5, 6] * 5\nsmall_test_expected = [2, 4, 6, 8, 10, 12] * 5\n\n\ndef small_test_func(x):\n return x * 2\n\n\ndef raise_error(x):\n raise ValueError(\"dummy error\")\n\n\ndef test_parallel_map():\n # test different chunk sizes\n for test_chunk_size in [1, 2, 4, 8, 16, 32, 64, 128]:\n small_test_output = list(\n parallel_map(\n small_test_func,\n small_test_input,\n process_count=2,\n chunk_size=test_chunk_size,\n )\n )\n\n assert (\n small_test_output == small_test_expected\n ), f\"chunk_size={test_chunk_size}\"\n\n # test whether pbar off works properly\n small_test_output = list(\n parallel_map(small_test_func, small_test_input, progress_bar=False)\n )\n\n # test whether exceptions are forwarded properly\n with pytest.raises(ValueError):\n small_test_output = list(\n parallel_map(raise_error, small_test_input, progress_bar=False)\n )\n\n # test edge case: empty input\n assert list(parallel_map(small_test_func, [])) == []\n\n # trivial test for tqdm kwargs\n parallel_map(small_test_func, small_test_input, progress_bar_kwargs={})\n","repo_name":"speechbrain/speechbrain","sub_path":"tests/unittests/test_parallel.py","file_name":"test_parallel.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":6855,"dataset":"github-code","pt":"52"} +{"seq_id":"72708514405","text":"\n# Written(almost, excluding this comment) by ChatGPT, which is a little scary.\n\nimport re\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords, wordnet\nfrom nltk.stem import WordNetLemmatizer\nimport subprocess\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom collections import Counter\n\n# Create a lemmatizer object\nlemmatizer = WordNetLemmatizer()\n\n# Use subprocess to run the git log command and capture its output\nresult = subprocess.run(['git', 'log', '--pretty=format:%s'], stdout=subprocess.PIPE)\ntext = result.stdout.decode('utf-8')\n\n# Remove special characters using regex\ntext = re.sub(r'[^\\w\\s]', '', text)\n\n# Tokenize the text into words and lemmatize them\nwords = [lemmatizer.lemmatize(w, wordnet.VERB) for w in word_tokenize(text)]\n\n# Filter out stop words\nstop_words = set(stopwords.words('english'))\nfiltered_words = [w for w in words if w.lower() not in stop_words]\n\n# Count the occurrences of each word\nword_counts = Counter(filtered_words)\n\n# Sort the dictionary by frequency\nsorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)\n\n# Display the sorted list of words\nsorted_words_only = [x[0] for x in sorted_words]\n\n# Save sorted words to a text file\nwith open('sorted_words.txt', 'w') as f:\n f.write('The full list of words from the mint-fresh-notes commit messages, sorted from most common.\\n\\n')\n f.write('\\n'.join(sorted_words_only))\n\nsubprocess.run(['xdg-open', 'sorted_words.txt'])\n\n# Create a bar chart of the top 10 words\ndf = pd.DataFrame(sorted_words[:20], columns=['Word', 'Frequency'])\nsns.set_style('darkgrid')\nplt.style.use('grayscale')\nplt.figure(figsize=(12, 6))\nsns.barplot(x='Word', y='Frequency', data=df, color='#2E86C1')\nplt.title('Top 20 Words in mint-fresh-notes Commit Messages', fontweight='bold')\nplt.xlabel('Word', fontweight='bold')\nplt.ylabel('Frequency', fontweight='bold')\nplt.xticks()\nplt.tight_layout()\nplt.show()\n","repo_name":"spicata/archive","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"21858954737","text":"import os\nfrom re import S\nimport sys\n\nfrom components.Logger import Logger\nfrom flask import Flask, request\n\nfrom functions import extract\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap\nfrom pprint import pprint\n\nfrom utilities import *\nimport graph_util as gu\nimport requests\n\nfrom pykeen.pipeline import pipeline\nfrom pykeen.models import TransE\nfrom pykeen.triples import TriplesFactory\nimport torch\n\n\napp = Flask(__name__)\nlogger = Logger('app')\n\n\n@app.route('/api/extract', methods=['GET'])\ndef extract_entities_embeddings():\n source = request.args.get('source')\n source = 'dbpedia' if source is None else source\n max_depth = request.args.get('max_depth')\n max_depth = 4 if max_depth is None else int(max_depth)\n max_walks = request.args.get('max_walks')\n max_walks = 10 if max_walks is None else int(max_walks)\n walker = request.args.get('walker')\n walker = 1 if walker is None else int(walker)\n size = request.args.get('size')\n size = 100 if size is None else int(size)\n epochs = request.args.get('epochs')\n epochs = 1 if epochs is None else int(epochs)\n\n # query_and_write_entities_to_csv(source, path_to_write='results/LCPatients.csv', write_mode='wt')\n # entities, literals, embeddings = extract(source,\n # max_depth=max_depth,\n # max_walks=max_walks,\n # walker=walker,\n # size=size,\n # epochs=epochs, entities_path='results/LCPatients.csv')\n # write_vector_data_to_csv(embeddings, path='results/LCPatients_embeddings.csv')\n\n # entities = get_entities_from_csv('results/patients.csv')\n # embeddings = read_vector_data_from_csv('results/patients_embeddings.csv')\n # string_to_write = ''\n # for ent, emb in zip(entities, embeddings):\n # string_to_write += ent + ','\n # for e in emb:\n # string_to_write += str(e) + ','\n # string_to_write = string_to_write[:-1] + '\\r\\n'\n # with open('results/patients_entities_embeddings.csv', 'wt') as f:\n # f.write(string_to_write)\n\n # embeddings = read_vector_data_from_csv('results/male_embeddings.csv')\n # male2d = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/female_embeddings.csv')\n # female2d = PCA_analysis(embeddings)\n # fig = plt.figure()\n # ax = fig.add_subplot(1, 1, 1)\n # ax.scatter(male2d[:, 0], male2d[:, 1])\n # ax.scatter(female2d[:, 0], female2d[:, 1])\n # ax.grid()\n # ax.legend(['male', 'female'])\n # fig.savefig('results/PCA_analysis.png')\n\n # embeddings = read_vector_data_from_csv(path='results/smoker_embeddings.csv')\n # smoker2d = PCA_analysis(embeddings)\n # smokers2d = PCA_analysis(embeddings)\n # smoker2d = smokers2d[:400]\n # embeddings = read_vector_data_from_csv(path='results/pre-smoker_embeddings.csv')\n # pre_smoker2d = PCA_analysis(embeddings)\n # pre_smoker2d = smokers2d[400:800]\n # embeddings = read_vector_data_from_csv(path='results/no-smoker_embeddings.csv')\n # no_smoker2d = PCA_analysis(embeddings)\n # no_smoker2d = smokers2d[800:]\n # embeddings = read_vector_data_from_csv(path='results/male_embeddings.csv')\n # male2d = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv(path='results/female_embeddings.csv')\n # female2d = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv(path='results/older50_embeddings.csv')\n # older502d = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv(path='results/younger50_embeddings.csv')\n # younger502d = PCA_analysis(embeddings)\n # fig = plt.figure()\n # ax = fig.add_subplot(1, 1, 1)\n # ax.scatter(smoker2d[:, 0], smoker2d[:, 1])\n # ax.scatter(pre_smoker2d[:, 0], pre_smoker2d[:, 1])\n # ax.scatter(no_smoker2d[:, 0], no_smoker2d[:, 1], color='tab:green')\n # ax.scatter(male2d[:, 0], male2d[:, 1])\n # ax.scatter(female2d[:, 0], female2d[:, 1])\n # ax.scatter(older502d[:, 0], older502d[:, 1])\n # ax.scatter(younger502d[:, 0], younger502d[:, 1])\n # ax.legend(['smokers', 'pre-smokers', 'no-smokers', 'male', 'female', 'older50', 'younger50'])\n # ax.legend(['smokers', 'pre-smokers', 'no-smokers'])\n # ax.grid()\n # fig.savefig('results/PCA_analysis.png')\n\n # embeddings = read_vector_data_from_csv('results/SmokerMaleOlder50_embeddings.csv')\n # SMO = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/SmokerMaleYounger50_embeddings.csv')\n # SMY = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/SmokerFemaleOlder50_embeddings.csv')\n # SFO = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/Pre-smokerMaleOlder50_embeddings.csv')\n # PMO = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/Pre-smokerMaleYounger50_embeddings.csv')\n # PMY = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/Pre-smokerFemaleOlder50_embeddings.csv')\n # PFO = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/Pre-smokerFemaleYounger50_embeddings.csv')\n # PFY = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/No-smokerMaleOlder50_embeddings.csv')\n # NMO = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/No-smokerFemaleOlder50_embeddings.csv')\n # NFO = PCA_analysis(embeddings)\n # embeddings = read_vector_data_from_csv('results/No-smokerFemaleYounger50_embeddings.csv')\n # NFY = PCA_analysis(embeddings)\n # fig = plt.figure()\n # ax = fig.add_subplot(1, 1, 1)\n # ax.scatter(SMO[:, 0], SMO[:, 1])\n # ax.scatter(SMY[:, 0], SMY[:, 1])\n # ax.scatter(SFO[:, 0], SFO[:, 1])\n # ax.scatter(PMO[:, 0], PMO[:, 1])\n # ax.scatter(PMY[:, 0], PMY[:, 1])\n # ax.scatter(PFO[:, 0], PFO[:, 1])\n # ax.scatter(PFY[:, 0], PFY[:, 1])\n # ax.scatter(NMO[:, 0], NMO[:, 1])\n # ax.scatter(NFO[:, 0], NFO[:, 1])\n # ax.scatter(NFY[:, 0], NFY[:, 1])\n # ax.legend([\n # 'SmokerMaleOlder50',\n # 'SmokerMaleYounger50',\n # 'SmokerFemaleOlder50',\n # 'Pre-smokerMaleOlder50',\n # 'Pre-smokerMaleYounger50',\n # 'Pre-smokerFemaleOlder50',\n # 'Pre-smokerFemaleYounger50',\n # 'No-smokerMaleOlder50',\n # 'No-smokerFemaleOlder50',\n # 'No-smokerFemaleYounger50',\n # ])\n # ax.grid()\n # fig.savefig('results/PCA_analysis.png')\n\n # entities = get_entities_from_csv('results/LCPatients.csv')\n # embeds = read_vector_data_from_csv('results/LCPatients_embeddings.csv')\n # sim_mat = similarity_calculation(embeds)\n # savefig_sim_mat(sim_mat)\n # pca = PCA_analysis(embeds)\n # fig = plt.figure()\n # ax = fig.add_subplot(1, 1, 1)\n # ax.scatter(pca[:, 0], pca[:, 1])\n # ax.grid()\n # fig.savefig('results/PCA_analysis.png')\n # sim_mat_to_csv(sim_mat, entities)\n\n ################ pykeen ################\n # # train\n # tf = TriplesFactory.from_path('data/Clarify_Prediction_Biomarker/clarify.tsv')\n # training, testing = tf.split()\n # # pipeline_result = pipeline(\n # # training=training,\n # # testing=testing,\n # # model=TransE\n # # )\n # # pipeline_result.save_to_directory('results/Trans-models')\n\n # # load model\n # pykeen_model = torch.load('results/Trans-models/trained_model.pkl')\n\n # # get entities\n # entities = get_entities_from_csv('results/LCPatients.csv')\n\n # # as prefixes are not consistent\n # # change prefix \"http://research.tib.eu/clarify2020/entity/\" to \"http://clarify2020.eu/entity/\"\n # entities = ['' for e in entities]\n\n # # get id of entities\n # entity_ids = torch.as_tensor(tf.entities_to_ids(entities))\n \n # # get embeddings using id\n # entity_representation_modules: List['pykeen.nn.Representation'] = pykeen_model.entity_representations\n # entity_embeddings: pykeen.nn.Embedding = entity_representation_modules[0]\n # embeddings_tensor: torch.FloatTensor = entity_embeddings(indices=entity_ids)\n # embeddings: np.ndarray = embeddings_tensor.detach().cpu().numpy()\n ################ pykeen ################\n\n ################ generate files for METIS #################\n # entities = get_entities_from_csv('results/LCPatients.csv')\n # embeddings = read_vector_data_from_csv('results/LCPatients_embeddings.csv')\n # embeddings = embeddings[:]\n # sim_mat = similarity_calculation(embeddings)\n # save_sim_mat(sim_mat)\n # savefig_sim_mat(sim_mat)\n # sim_mat = read_sim_mat()\n # gu.sim_mat_to_graph(sim_mat)\n # gu.visualize_graph('results/sim_mat.gp')\n # gu.group_entities_into_csvfiles('results/sim_mat.gp.part.6', 'results/LCPatients.csv')\n # gu.communities_in_bar('/mnt/c/Users/SongZ/Downloads/repositories/RDF2vec-target-based/src/results/metis-results', top_n=10)\n ################ generate files for METIS #################\n\n ################# calculate structural indices of communities (METIS) #################\n entities = get_entities_from_csv('results/LCPatients.csv')\n # embeddings = read_vector_data_from_csv('results/LCPatients_embeddings.csv')\n # embeddings = embeddings[:]\n # sim_mat = similarity_calculation(embeddings)\n # save_sim_mat(sim_mat)\n # savefig_sim_mat(sim_mat)\n sim_mat = read_sim_mat()\n community_dir = '/mnt/c/Users/SongZ/Downloads/repositories/RDF2vec-target-based/src/results/metis-results'\n inv_conductance = 1 - gu.conductance_comm(entities, sim_mat, community_dir)\n coverage = gu.coverage_comm(entities, sim_mat, community_dir)\n modularity = (gu.modularity_comm(entities, sim_mat, community_dir) + 0.5) / 1.5\n inv_performance = 1 - gu.performance_comm(entities, sim_mat, community_dir)\n inv_ntc = 1 - gu.normalized_total_cut_comm(entities, sim_mat, community_dir)\n\n # plot radar chart\n structural_indices = [\n inv_conductance,\n coverage,\n modularity,\n inv_performance,\n inv_ntc\n ]\n indices_name = [\n 'Inv. Conductance',\n 'Coverage',\n 'Norm. Modularity',\n 'Inv. Performance',\n 'Inv. Norm. Total Cut'\n ]\n theta = gu.radar_factory(len(structural_indices), frame='polygon')\n fig, ax = plt.subplots(subplot_kw=dict(projection='radar'))\n ax.set_rgrids([0.2, 0.4, 0.6, 0.8])\n ax.plot(theta, structural_indices)\n ax.fill(theta, structural_indices)\n ax.set_varlabels(indices_name)\n plt.savefig('results/structural-indices.png')\n ################# calculate structural indices of communities (semEP) #################\n\n ################ generate files for semEP #################\n # entities = get_entities_from_csv('results/LCPatients.csv')\n # embeds = read_vector_data_from_csv('results/LCPatients_embeddings.csv')\n # entities = entities[:]\n # embeds = embeds[:]\n # vertices1 = entities[:int(len(entities)/2)]\n # embeds1 = embeds[:int(len(entities)/2)]\n # vertices2 = entities[int(len(entities)/2):]\n # embeds2 = embeds[int(len(entities)/2):]\n # edges = []\n # for i, v1 in enumerate(vertices1):\n # for j, v2 in enumerate(vertices2):\n # e1, e2 = np.array(embeds1[i]), np.array(embeds2[j])\n # e1_n, e2_n = e1 / np.sqrt(e1 @ e1.T), e2 / np.sqrt(e2 @ e2.T)\n # sim = np.abs(e1_n @ e2_n.T)\n # edges.append((v1, v2, sim))\n # print(v1, v2, sim)\n # generate_bigraph(vertices1, vertices2, edges, outdir='results', vec1=embeds1, vec2=embeds2)\n ################ generate files for semEP #################\n\n ################ plot communities generated by semEP #################\n # entities = get_entities_from_csv('results/LCPatients.csv')\n # embeds = read_vector_data_from_csv('results/LCPatients_embeddings.csv')\n # entities = entities[:]\n # embeds = embeds[:]\n # community_dir = '/mnt/c/Users/SongZ/Downloads/repositories/RDF2vec-target-based/src/results/semEP-results/bigraph-0.7500-0.7500-Clusters'\n # # plot_communities(entities, embeds, community_dir)\n # # print_communities(entities, community_dir, tofile='/mnt/c/Users/SongZ/Downloads/repositories/RDF2vec-target-based/src/results/semEP-results/CD.txt')\n # bar_communities(entities, community_dir, top_n=10)\n ################ plot communities generated by semEP #################\n\n ################# calculate structural indices of communities (semEP) #################\n # entities = get_entities_from_csv('results/LCPatients.csv')\n # # embeddings = read_vector_data_from_csv('results/LCPatients_embeddings.csv')\n # # embeddings = embeddings[:]\n # # sim_mat = similarity_calculation(embeddings)\n # # save_sim_mat(sim_mat)\n # # savefig_sim_mat(sim_mat)\n # sim_mat = read_sim_mat()\n # community_dir = '/mnt/c/Users/SongZ/Downloads/repositories/RDF2vec-target-based/src/results/semEP-results/bigraph-0.7500-0.7500-Clusters'\n # comm_coverage(entities, sim_mat, community_dir)\n ################# calculate structural indices of communities (semEP) #################\n\n\n return {\n 'entities': entities,\n # 'literals': literals,\n 'embeddings': embeddings\n }\n\n\n@app.route('/api/up', methods=['GET'])\ndef up():\n return {'msg': 'ok'}\n\n\ndef main(*args):\n\n if len(args) == 1:\n myhost = args[0]\n else:\n myhost = \"0.0.0.0\"\n\n debug = os.environ.get('APP_DEBUG', 'true').lower() == 'true'\n app.run(debug=debug, host=myhost, port=5000)\n\n\nif __name__ == '__main__':\n main(*sys.argv[1:])","repo_name":"SDM-TIB/RDF2vec","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31593903249","text":"from 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 Operations(object):\n \"\"\"\n Each patch operation object MUST have exactly one \\\"op\\\" member, whose value indicates the operation to perform and MAY be one of \\\"add\\\", \\\"remove\\\", or \\\"replace\\\". See `Section 3.5.2`__ for details.\n\n __ https://tools.ietf.org/html/draft-ietf-scim-api-19#section-3.5.2\n \"\"\"\n\n #: A constant which can be used with the op property of a Operations.\n #: This constant has a value of \"ADD\"\n OP_ADD = \"ADD\"\n\n #: A constant which can be used with the op property of a Operations.\n #: This constant has a value of \"REMOVE\"\n OP_REMOVE = \"REMOVE\"\n\n #: A constant which can be used with the op property of a Operations.\n #: This constant has a value of \"REPLACE\"\n OP_REPLACE = \"REPLACE\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new Operations object with values from keyword arguments.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param op:\n The value to assign to the op property of this Operations.\n Allowed values for this property are: \"ADD\", \"REMOVE\", \"REPLACE\"\n :type op: str\n\n :param path:\n The value to assign to the path property of this Operations.\n :type path: str\n\n :param value:\n The value to assign to the value property of this Operations.\n :type value: object\n\n \"\"\"\n self.swagger_types = {\n 'op': 'str',\n 'path': 'str',\n 'value': 'object'\n }\n\n self.attribute_map = {\n 'op': 'op',\n 'path': 'path',\n 'value': 'value'\n }\n\n self._op = None\n self._path = None\n self._value = None\n\n @property\n def op(self):\n \"\"\"\n **[Required]** Gets the op of this Operations.\n Defines the operation to be performed for this Patch. If op=remove, value is not required.\n\n Allowed values for this property are: \"ADD\", \"REMOVE\", \"REPLACE\"\n\n\n :return: The op of this Operations.\n :rtype: str\n \"\"\"\n return self._op\n\n @op.setter\n def op(self, op):\n \"\"\"\n Sets the op of this Operations.\n Defines the operation to be performed for this Patch. If op=remove, value is not required.\n\n\n :param op: The op of this Operations.\n :type: str\n \"\"\"\n allowed_values = [\"ADD\", \"REMOVE\", \"REPLACE\"]\n if not value_allowed_none_or_none_sentinel(op, allowed_values):\n raise ValueError(\n f\"Invalid value for `op`, must be None or one of {allowed_values}\"\n )\n self._op = op\n\n @property\n def path(self):\n \"\"\"\n **[Required]** Gets the path of this Operations.\n String containing an attribute path describing the target of the operation. The \\\"path\\\" attribute is OPTIONAL for \\\"add\\\" and \\\"replace\\\" and is REQUIRED for \\\"remove\\\" operations. See `Section 3.5.2`__ for details\n\n __ https://tools.ietf.org/html/draft-ietf-scim-api-19#section-3.5.2\n\n\n :return: The path of this Operations.\n :rtype: str\n \"\"\"\n return self._path\n\n @path.setter\n def path(self, path):\n \"\"\"\n Sets the path of this Operations.\n String containing an attribute path describing the target of the operation. The \\\"path\\\" attribute is OPTIONAL for \\\"add\\\" and \\\"replace\\\" and is REQUIRED for \\\"remove\\\" operations. See `Section 3.5.2`__ for details\n\n __ https://tools.ietf.org/html/draft-ietf-scim-api-19#section-3.5.2\n\n\n :param path: The path of this Operations.\n :type: str\n \"\"\"\n self._path = path\n\n @property\n def value(self):\n \"\"\"\n Gets the value of this Operations.\n The value could be either a simple value attribute e.g. string or number OR complex like map of the attributes to be added or replaced OR multivalues complex attributes.q1\n\n\n :return: The value of this Operations.\n :rtype: object\n \"\"\"\n return self._value\n\n @value.setter\n def value(self, value):\n \"\"\"\n Sets the value of this Operations.\n The value could be either a simple value attribute e.g. string or number OR complex like map of the attributes to be added or replaced OR multivalues complex attributes.q1\n\n\n :param value: The value of this Operations.\n :type: object\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/identity_domains/models/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"31579810339","text":"from __future__ import absolute_import\nimport configparser\nimport os\nimport re\nimport logging\nfrom oci._vendor import six\n\nfrom .exceptions import ConfigFileNotFound, ProfileNotFound, InvalidConfig, InvalidKeyFilePath\nfrom .auth import signers\nfrom .util import AUTHENTICATION_TYPE_FIELD_NAME, get_authentication_type_from_config, DELEGATION_TOKEN_FILE_FIELD_NAME, DELEGATION_TOKEN_WITH_INSTANCE_PRINCIPAL_AUTHENTICATION_TYPE\n\n__all__ = [\"DEFAULT_CONFIG\", \"from_file\", \"validate_config\"]\n\nDEFAULT_CONFIG = {\n \"log_requests\": False,\n \"additional_user_agent\": \"\",\n \"pass_phrase\": None\n}\nDEFAULT_LOCATION = os.path.join('~', '.oci', 'config')\nFALLBACK_DEFAULT_LOCATION = os.path.join('~', '.oraclebmc', 'config')\nDEFAULT_PROFILE = \"DEFAULT\"\nPATTERNS = {\n # Tenancy and user have the same shape\n \"tenancy\": re.compile(r\"^([0-9a-zA-Z-_]+[.:])([0-9a-zA-Z-_]*[.:]){3,}([0-9a-zA-Z-_]+)$\"),\n \"user\": re.compile(r\"^([0-9a-zA-Z-_]+[.:])([0-9a-zA-Z-_]*[.:]){3,}([0-9a-zA-Z-_]+)$\"),\n \"fingerprint\": re.compile(r\"^([0-9a-f]{2}:){15}[0-9a-f]{2}$\")\n}\nREQUIRED = {\n \"user\",\n \"tenancy\",\n \"fingerprint\",\n \"key_file\",\n \"region\"\n}\nREQUIRED_FALLBACKS = {\n \"key_file\": \"key_content\"\n}\nCONFIG_FILE_BLACKLISTED_KEYS = {\n \"key_content\"\n}\n\nCONFIG_FILE_PATH_ENV_VAR_NAME = \"OCI_CONFIG_FILE\"\nREGION_ENV_VAR_NAME = \"OCI_REGION\"\nREGION_KEY_NAME = \"region\"\nCONFIG_FILE_DEBUG_INFORMATION_LOG = \"For more info about config file and how to get required information, see https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdkconfig.htm\"\n\nlogger = logging.getLogger(__name__)\n\n\ndef _validate_delegation_token_with_instance_principal(config):\n # At this point we know we have the required fields for this authentication type, so we won't check that again\n delegation_token_file_path = config.get(DELEGATION_TOKEN_FILE_FIELD_NAME)\n if delegation_token_file_path is None:\n raise InvalidConfig('ERROR: Please specify the location of the delegation_token_file in the config.')\n\n expanded_delegation_token_file_path = os.path.expanduser(delegation_token_file_path)\n\n if not os.path.isfile(expanded_delegation_token_file_path):\n raise InvalidConfig(\"Delegation token file not found at {}\".format(expanded_delegation_token_file_path))\n\n\n# Map the validator function for each type\n# This can easily be extended to support other auth types\nAUTH_TYPE_TO_VALIDATION_FUNCTION_MAP = {\n DELEGATION_TOKEN_WITH_INSTANCE_PRINCIPAL_AUTHENTICATION_TYPE: _validate_delegation_token_with_instance_principal\n}\n\n\ndef from_file(file_location=DEFAULT_LOCATION, profile_name=DEFAULT_PROFILE):\n \"\"\"Create a config dict from a file.\n\n :param file_location: Path to the config file. Defaults to ~/.oci/config and with a fallback\n to environment variable OCI_CONFIG_FILE, then ~/.oraclebmc/config.\n :param profile_name: The profile to load from the config file. Defaults to \"DEFAULT\"\n :return: A config dict that can be used to create clients.\n \"\"\"\n expanded_file_location = _get_config_path_with_fallback(file_location)\n\n parser = configparser.ConfigParser(interpolation=None)\n if not parser.read(expanded_file_location):\n raise ConfigFileNotFound(\"Could not find config file at {}, please follow the instructions in the link to setup the config file https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/sdkconfig.htm\".format(expanded_file_location))\n\n if profile_name not in parser:\n raise ProfileNotFound(\"Profile '{}' not found in config file {} \".format(profile_name, expanded_file_location) + CONFIG_FILE_DEBUG_INFORMATION_LOG)\n\n config = dict(DEFAULT_CONFIG)\n config.update(parser[profile_name])\n config[\"log_requests\"] = _as_bool(config[\"log_requests\"])\n\n for key in CONFIG_FILE_BLACKLISTED_KEYS:\n if key in config:\n raise ValueError(\"'{}' cannot be specified in a config file for security reasons. To use this key you must add it to the config programmatically. \".format(key) + CONFIG_FILE_DEBUG_INFORMATION_LOG)\n\n invalid_key_file_path_checker(config, expanded_file_location, profile_name)\n\n return config\n\n\ndef validate_config(config, **kwargs):\n if 'signer' in kwargs:\n # InstancePrincipalsSecurityTokenSigner and SecurityTokenSigner are\n # self-sufficient and do not need to read the normally-required keys\n # in the config\n if isinstance(kwargs['signer'], signers.InstancePrincipalsSecurityTokenSigner) or isinstance(kwargs['signer'], signers.SecurityTokenSigner) or isinstance(kwargs['signer'], signers.KeyPairSigner):\n return\n\n if AUTHENTICATION_TYPE_FIELD_NAME in config:\n auth_type = get_authentication_type_from_config(config)\n validator_function = AUTH_TYPE_TO_VALIDATION_FUNCTION_MAP.get(auth_type)\n validator_function(config)\n return\n\n \"\"\"Raises ValueError if required fields are missing or malformed.\"\"\"\n errors = {}\n for required_key in REQUIRED:\n fallback_key = REQUIRED_FALLBACKS.get(required_key)\n if (required_key not in config or config[required_key] is None) and (fallback_key not in config or config[fallback_key] is None):\n # If region is not provided, check the env variable\n if required_key == REGION_KEY_NAME:\n logger.debug(\"Region not found in config, checking environment variable {}\".format(REGION_ENV_VAR_NAME))\n region_from_env_var = os.environ.get(REGION_ENV_VAR_NAME)\n if region_from_env_var:\n # If present, inject the region in config\n logger.debug(\"Setting region from environment variable {}\".format(REGION_ENV_VAR_NAME))\n config[REGION_KEY_NAME] = region_from_env_var\n else:\n errors[required_key] = \"missing\"\n else:\n errors[required_key] = \"missing\"\n\n for key, pattern in six.iteritems(PATTERNS):\n if key in errors:\n # key is missing, can't possibly match pattern\n continue\n if not pattern.match(config[key]):\n errors[key] = \"malformed\"\n if errors:\n raise InvalidConfig(errors)\n\n\ndef get_config_value_or_default(config, key):\n return config.get(key, DEFAULT_CONFIG.get(key))\n\n\ndef _as_bool(x):\n if x in [True, False]:\n return x\n if x.lower() in [\"1\", \"yes\", \"true\", \"on\"]:\n return True\n elif x.lower() in [\"0\", \"no\", \"false\", \"off\"]:\n return False\n else:\n raise ValueError(\"{!r} is not a valid alias for True/False\".format(x))\n\n\ndef _raise_on_errors(errors):\n # report all errors at once\n if len(errors) == 1:\n raise ValueError(\"Error in config: {}\".format(errors[0]))\n elif errors:\n raise ValueError(\"Found the following config errors: {!r}\".format(errors))\n\n\ndef _get_config_path_with_fallback(file_location):\n expanded_file_location = os.path.expanduser(file_location)\n expanded_fallback_default_file_location = os.path.expanduser(FALLBACK_DEFAULT_LOCATION)\n\n if (file_location != DEFAULT_LOCATION) or (file_location == DEFAULT_LOCATION and os.path.isfile(expanded_file_location)):\n logger.debug(\"Config file found at {}\".format(file_location))\n return expanded_file_location\n\n # If file location is not specified and the default file (~/.oci/config) does not exist\n # then try getting config file path from env var\n elif os.environ.get(CONFIG_FILE_PATH_ENV_VAR_NAME):\n logger.debug(\n \"No file location specified and default file does not exist. Getting path info from the environment variable {}\".format(\n CONFIG_FILE_PATH_ENV_VAR_NAME))\n expanded_file_location = os.path.expanduser(os.environ.get(CONFIG_FILE_PATH_ENV_VAR_NAME))\n return expanded_file_location\n\n # If we cannot determine the path from any other source and the fallback path (~/.oraclebmc/config) exists,\n # use that path\n elif os.path.isfile(expanded_fallback_default_file_location):\n expanded_file_location = expanded_fallback_default_file_location\n return expanded_file_location\n\n logger.debug(\"Config file found at {}\".format(expanded_file_location))\n return expanded_file_location\n\n\ndef invalid_key_file_path_checker(config, expanded_file_location, profile_name):\n if 'key_file' in config:\n key_file_path = os.path.expanduser(config.get('key_file'))\n if not os.path.isfile(key_file_path):\n line_number = get_linenum_from_file(config.get('key_file'), expanded_file_location, profile_name)\n line_message = \" at line {}\".format(line_number) if line_number else \"\"\n message = \"Config file {} is invalid: the key_file's value \\'{}\\'{} must be a valid file path. \".format(expanded_file_location, key_file_path, line_message) + CONFIG_FILE_DEBUG_INFORMATION_LOG\n raise InvalidKeyFilePath(message)\n\n\ndef get_linenum_from_file(key, filename, profile):\n with open(filename, 'r') as f:\n profile_found = False\n profile_token = \"[\" + profile + \"]\"\n for line_number, line in enumerate(f):\n line = line.strip()\n if len(line) >= 1:\n if line[0] == \"#\":\n continue\n if profile_token in line:\n profile_found = True\n if profile_found and key in line:\n return line_number + 1\n return None\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":9425,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"75202558884","text":"import os\nimport json\nimport argparse\nimport itertools\nimport math\nimport torch\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport torch.multiprocessing as mp\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.cuda.amp import autocast, GradScaler\n\nimport commons\nimport utils\nfrom data_utils import (\n TextAudioSpeakerLoader,\n TextAudioSpeakerCollate,\n DistributedBucketSampler\n)\nfrom models import (\n SynthesizerTrn,\n MultiPeriodDiscriminator,\n)\nfrom losses import (\n generator_loss,\n discriminator_loss,\n feature_loss,\n kl_loss\n)\nfrom mel_processing import mel_spectrogram_torch, spec_to_mel_torch\nfrom text.symbols import symbols\n\n\ntorch.backends.cudnn.benchmark = True\nglobal_step = 0\n\n#主函数\ndef main():\n \"\"\"Assume Single Node Multi GPUs Training Only\"\"\" # 这里是多卡的部分\n assert torch.cuda.is_available(), \"CPU training is not allowed.\"\n\n n_gpus = torch.cuda.device_count()\n os.environ['MASTER_ADDR'] = 'localhost'\n os.environ['MASTER_PORT'] = '80000'\n\n hps = utils.get_hparams()\n mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,))\n\n\ndef run(rank, n_gpus, hps):\n global global_step\n if rank == 0:\n logger = utils.get_logger(hps.model_dir)\n logger.info(hps)\n utils.check_git_hash(hps.model_dir)\n writer = SummaryWriter(log_dir=hps.model_dir)\n writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, \"eval\"))\n\n dist.init_process_group(backend='nccl', init_method='env://', world_size=n_gpus, rank=rank)\n torch.manual_seed(hps.train.seed)\n torch.cuda.set_device(rank)\n\n\n train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) #构造一个dataset,从名叫TextAudioSpeakerLoader的class(在data_utils中)实例化而来,这个class是读取文本、音频和speaker相关的,并且返回一个dataset。\n train_sampler = DistributedBucketSampler( #分布式的sampler,在data_utils中实现,TTS的任务数据长度变化可能很大(有些音频1秒,有些10秒),通过一个桶排序对数据进行排序,这样每一个batch分到的样本长度变化范围没那么大,有效的数目尽可能地接近,提升训练效率。\n train_dataset,\n hps.train.batch_size,\n [32,300,400,500,600,700,800,900,1000], # 这个长度指的是频谱的单位数\n num_replicas=n_gpus,\n rank=rank,\n shuffle=True)\n # bucket sampler 根据桶排序组batch,得到每个batch的样本的索引。\n\n collate_fn = TextAudioSpeakerCollate() # 主要是init和call两个方法\n # collate函数是对一个mini batch进行操作,会在dataload的时候去调用\n\n train_loader = DataLoader(train_dataset, num_workers=8, shuffle=False, pin_memory=True,\n collate_fn=collate_fn, batch_sampler=train_sampler) #把train_dataset、collate_fn和train_sampler传进去\n # 组mini batch的时候是sampler来组的,同时每组完一个mini batch之后都会经过collate_fn进行后处理(pad,把一个mini batch里的文本、频谱和音频各自pad成相应的长度),这样得到train_loader\n if rank == 0: # 如果是在主机eval的话,要去做验证,做验证集的时候,在一个GPA上跑,包括记日志、log等。\n eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data)\n eval_loader = DataLoader(eval_dataset, num_workers=8, shuffle=False,\n batch_size=hps.train.batch_size, pin_memory=True,\n drop_last=False, collate_fn=collate_fn)\n # rank不等于0的时候,只需要管训练\n\n # 定义生成器,SynthesizerTrn表示文本到音频的一整个模型\n net_g = SynthesizerTrn(\n len(symbols),\n hps.data.filter_length // 2 + 1,\n hps.train.segment_size // hps.data.hop_length,\n n_speakers=hps.data.n_speakers, # 与单speaker的区别(2/2)\n **hps.model).cuda(rank) #net_g被传到了cuda上\n\n # 定义了一个多周期的判别器,是一个混合的判别器,同样会被传到cuda上。 \n net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank)\n\n # 因为这是一个GAN的训练任务,所以定义了两套优化器\n optim_g = torch.optim.AdamW(\n net_g.parameters(), \n hps.train.learning_rate, \n betas=hps.train.betas, \n eps=hps.train.eps)\n optim_d = torch.optim.AdamW(\n net_d.parameters(),\n hps.train.learning_rate, \n betas=hps.train.betas, \n eps=hps.train.eps)\n # 由于这里是一个分布式的训练,所以用一个DDP把优化器包裹起来,包裹之后“net_g.model\"才是模型。\n net_g = DDP(net_g, device_ids=[rank])\n net_d = DDP(net_d, device_ids=[rank])\n\n # 如果在训练的时候,已经有现成的模型的话,那这里就会load一下,继续训练。这里写得非常自动化,不需要去指定load第几个pytorch文件,它会自动寻找最近的是哪一个模型文件进行读取。\n # 这种方法有优点也有缺点,优点是什么都不需要干,坏处是它默认了只读最后一个。\n try:\n _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, \"G_*.pth\"), net_g, optim_g)\n _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, \"D_*.pth\"), net_d, optim_d)\n global_step = (epoch_str - 1) * len(train_loader)\n except:\n epoch_str = 1\n global_step = 0\n # 这里定义的global_step是训练步数,是等于epoch乘以每个epoch里面batch_size的个数。\n\n # 这里定义了两个学习率的指数衰减的方案,分别是生成器的衰减方案和判别器的衰减方案,衰减方案是一样的。\n scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)\n scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str-2)\n\n # 因为用到了混合精度训练(AMP,自动的混合训练),训练的时候会用fp16去训练,这样可以在效率和性能上取得一个平衡。\n # 这里实例化了一个GradScaler的API,这个API是torch.cuda.amp里面的,用fp16训练的API,得到一个scaler\n scaler = GradScaler(enabled=hps.train.fp16_run)\n\n # 对epoch进行循环,每个epoch在里面做train_and_evaluate,如果是在主GPU上,logger, writer还有验证集传上去,如果不是主GPU,则只要负责训练就好了。\n # 完成以后,还要对刚刚定义的学习率的方案进行step,更新一下学习率。\n for epoch in range(epoch_str, hps.train.epochs + 1):\n if rank==0:\n train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, eval_loader], logger, [writer, writer_eval])\n else:\n train_and_evaluate(rank, epoch, hps, [net_g, net_d], [optim_g, optim_d], [scheduler_g, scheduler_d], scaler, [train_loader, None], None, None)\n scheduler_g.step()\n scheduler_d.step()\n\n\n# 每个周期里面都会运行train_and_evaluate函数,这个函数里面还有一层for循环,为了对data_loader进行遍历\ndef train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers):\n net_g, net_d = nets\n optim_g, optim_d = optims\n scheduler_g, scheduler_d = schedulers\n train_loader, eval_loader = loaders\n if writers is not None:\n writer, writer_eval = writers\n\n # 这里会把train_loader.batch_sampler设置epoch,控制桶排序的随机性。\n train_loader.batch_sampler.set_epoch(epoch)\n global global_step\n\n # net_g和net_d变成train的模式,这种模式会记录梯度,在抓包等的时候祈祷相应的作用。\n net_g.train()\n net_d.train()\n # 对train_loader进行枚举,每一个train_loader都会返回7个东西,分别是:文本、文本长度、频谱、频谱长度、音频、音频长度以及speaker的id。\n # 然后分别将这7个量分别拷贝到,cuda(GPU)上面。\n for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers) in enumerate(train_loader):\n x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True)\n spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True)\n y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True)\n speakers = speakers.cuda(rank, non_blocking=True) # 与单speaker的区别(2/2)\n\n # autocast中的enabled等于true,意思是会用fp16的精度去做训练,去做它的前向运算和算梯度。\n with autocast(enabled=hps.train.fp16_run):\n y_hat, l_length, attn, ids_slice, x_mask, z_mask,\\\n (z, z_p, m_p, logs_p, m_q, logs_q) = net_g(x, x_lengths, spec, spec_lengths, speakers)\n # 将x等7个量送到生成器里面,生成器运行一遍,得到预测的波形和长度。\n # 这个训练是采样式的训练,不是将所有的频谱送入解码器中得到波形,而是从里面采样一小段频谱来生成波形,这样训练所耗的内存会变小一些。\n # ids_slice就是采样后频谱的id\n\n # 把频谱(线性谱)转成梅尔谱,因为后面的一个重构loss需要梅尔谱,这里将线性谱转化成梅尔谱,作为重构loss的标签。\n mel = spec_to_mel_torch(\n spec, \n hps.data.filter_length, \n hps.data.n_mel_channels, \n hps.data.sampling_rate,\n hps.data.mel_fmin, \n hps.data.mel_fmax)\n\n # 这里slice_segments会取一部分梅尔谱,y_mel是真实的梅尔谱。\n y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length)\n # y_hat_mel是预测的梅尔谱。预测的梅尔谱只能从预测的音频波形中得到,从波形得到梅尔谱就需要调用mel_spectrogram_torch函数去计算梅尔频谱,得到y_hat_mel\n y_hat_mel = mel_spectrogram_torch(\n y_hat.squeeze(1), \n hps.data.filter_length, \n hps.data.n_mel_channels, \n hps.data.sampling_rate, \n hps.data.hop_length, \n hps.data.win_length, \n hps.data.mel_fmin, \n hps.data.mel_fmax\n )\n\n # 接下来要拿到真实的波形,因为判别器做判别的时候,需要以波形作为输入。刚刚生成的y_hat,不是原来的一整段音频,是从采样后的频谱里生成的,只是一小段音频。要得到y_hat的标签,也要从真实的y里面去取一小段音频。\n # 这里梅尔谱的ids_slice * hps.data.hop_length就是说:一个梅尔谱可能对应的256个波形点,所以hop_length就是256。这样就可以取到采样后的梅尔谱所对应的真实的音频y\n y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice \n\n # 这里将y(真实的波形)和预测的波形都送入到判别器中,就会得到真实的判别器的输出和生成的判别器的输出。\n # 然后会在autocast(enabled=False)里面计算它的loss,这部分是不走fp16的。\n # Discriminator\n y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach())\n with autocast(enabled=False):\n loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) #将判别器的真实的输出和预测的输出送入discriminator_loss中,分别得到判别器的总的损失loss_disc\n loss_disc_all = loss_disc\n # 更新判别器\n optim_d.zero_grad() # 对判别器的梯度置零\n scaler.scale(loss_disc_all).backward() # 把判别器的损失loss_disc_all送入scaler.scale()中进行backward(),这样可以计算判别器的每个参数的梯度\n scaler.unscale_(optim_d) # 对判别器的模型用scaler.unscale_还原一下,再截取梯度\n grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) # clip_grad_value对梯度的值进行截断\n scaler.step(optim_d) # 对判别器的参数进行更新\n # 以上是混合精度训练的代码,判别器的更新\n\n # 生成器部分\n with autocast(enabled=hps.train.fp16_run): # 依旧在用fp16的精度去做训练\n # Generator\n y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) # 算出一个对抗的loss(从判别器过来的),将真实的波形和预测的波形送入到discriminator中,得到中间特征的输出。\n with autocast(enabled=False):\n loss_dur = torch.sum(l_length.float()) # 时长loss\n loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel # 梅尔谱重构loss,对真实的梅尔谱和预测的梅尔谱做一个l1_loss。其中系数c_mel等于45(见论文)。\n loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl # 由文本的先验编码器所预测的复杂分布和频谱经过的后验编码器所得到的高斯分布两个之间计算kl散度,系数c_kl等于1(论文)。\n loss_fm = feature_loss(fmap_r, fmap_g) # 将真实波形和预测波形同时送入到判别器之中,去看判别器的中层值特征是否相近。\n loss_gen, losses_gen = generator_loss(y_d_hat_g) # 对抗loss\n loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl # 得到生成器的总loss\n optim_g.zero_grad()\n scaler.scale(loss_gen_all).backward()\n scaler.unscale_(optim_g)\n grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None)\n scaler.step(optim_g)\n scaler.update()\n #以上6行是对生成器进行更新\n\n # 在主GPU上对loss的值进行打印,保存相应的模型,并且写入到日志文件之中,对global_step进行更新。如果global_step等于eval_interval的整数倍,就会做一个evaluate验证\n if rank==0:\n if global_step % hps.train.log_interval == 0:\n lr = optim_g.param_groups[0]['lr']\n losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl]\n logger.info('Train Epoch: {} [{:.0f}%]'.format(\n epoch,\n 100. * batch_idx / len(train_loader)))\n logger.info([x.item() for x in losses] + [global_step, lr])\n \n scalar_dict = {\"loss/g/total\": loss_gen_all, \"loss/d/total\": loss_disc_all, \"learning_rate\": lr, \"grad_norm_d\": grad_norm_d, \"grad_norm_g\": grad_norm_g}\n scalar_dict.update({\"loss/g/fm\": loss_fm, \"loss/g/mel\": loss_mel, \"loss/g/dur\": loss_dur, \"loss/g/kl\": loss_kl})\n\n scalar_dict.update({\"loss/g/{}\".format(i): v for i, v in enumerate(losses_gen)})\n scalar_dict.update({\"loss/d_r/{}\".format(i): v for i, v in enumerate(losses_disc_r)})\n scalar_dict.update({\"loss/d_g/{}\".format(i): v for i, v in enumerate(losses_disc_g)})\n image_dict = { \n \"slice/mel_org\": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()),\n \"slice/mel_gen\": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()), \n \"all/mel\": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()),\n \"all/attn\": utils.plot_alignment_to_numpy(attn[0,0].data.cpu().numpy())\n }\n utils.summarize(\n writer=writer,\n global_step=global_step, \n images=image_dict,\n scalars=scalar_dict)\n\n if global_step % hps.train.eval_interval == 0:\n evaluate(hps, net_g, eval_loader, writer_eval)\n utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, \"G_{}.pth\".format(global_step)))\n utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, \"D_{}.pth\".format(global_step)))\n global_step += 1\n \n if rank == 0:\n logger.info('====> Epoch: {}'.format(epoch))\n\n \ndef evaluate(hps, generator, eval_loader, writer_eval):\n generator.eval()\n with torch.no_grad():\n for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers) in enumerate(eval_loader):\n x, x_lengths = x.cuda(0), x_lengths.cuda(0)\n spec, spec_lengths = spec.cuda(0), spec_lengths.cuda(0)\n y, y_lengths = y.cuda(0), y_lengths.cuda(0)\n speakers = speakers.cuda(0)\n\n # remove else\n x = x[:1]\n x_lengths = x_lengths[:1]\n spec = spec[:1]\n spec_lengths = spec_lengths[:1]\n y = y[:1]\n y_lengths = y_lengths[:1]\n speakers = speakers[:1]\n break\n y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, max_len=1000)\n y_hat_lengths = mask.sum([1,2]).long() * hps.data.hop_length\n\n mel = spec_to_mel_torch(\n spec, \n hps.data.filter_length, \n hps.data.n_mel_channels, \n hps.data.sampling_rate,\n hps.data.mel_fmin, \n hps.data.mel_fmax)\n y_hat_mel = mel_spectrogram_torch(\n y_hat.squeeze(1).float(),\n hps.data.filter_length,\n hps.data.n_mel_channels,\n hps.data.sampling_rate,\n hps.data.hop_length,\n hps.data.win_length,\n hps.data.mel_fmin,\n hps.data.mel_fmax\n )\n image_dict = {\n \"gen/mel\": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy())\n }\n audio_dict = {\n \"gen/audio\": y_hat[0,:,:y_hat_lengths[0]]\n }\n if global_step == 0:\n image_dict.update({\"gt/mel\": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())})\n audio_dict.update({\"gt/audio\": y[0,:,:y_lengths[0]]})\n\n utils.summarize(\n writer=writer_eval,\n global_step=global_step, \n images=image_dict,\n audios=audio_dict,\n audio_sampling_rate=hps.data.sampling_rate\n )\n generator.train()\n\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"Yeazy0w0/VITS-code-notes","sub_path":"vits-main/train_ms.py","file_name":"train_ms.py","file_ext":"py","file_size_in_byte":17646,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42863203817","text":"import csv\r\nimport pymysql\r\nfrom utils import get_use_months\r\nfrom utils import get_current_date\r\n\r\n# host='10.214.163.179'\r\n# user='dt_yc'\r\n# password='dt_yc123'\r\n# port=3306\r\n# database='dt_yc'\r\n\r\n# 根据预测结果进行数据聚合\r\ndef get_aggrs(threshold=0.5):\r\n conn = pymysql.connect(host='10.214.163.179', user='dt_yc', password='dt_yc123', port=3306, database='dt_yc')\r\n cursor = conn.cursor()\r\n\r\n current_date = get_current_date()\r\n\r\n # 从csv中读取得到current_date的预测结果\r\n csv_file = open('results/' + str(current_date) + '-result.csv', 'r')\r\n reader = csv.reader(csv_file)\r\n rows = list(reader)\r\n\r\n # 得到预测为高危的电梯集合\r\n high_risk_tranid_set = []\r\n for row in rows:\r\n if row[0] == 'tranid':\r\n continue\r\n if float(row[1]) >= threshold:\r\n high_risk_tranid_set.append(row[0])\r\n\r\n # 读取ele_info中的内容\r\n query = \"\"\"\r\n SELECT\r\n apply_location,\r\n use_start_date,\r\n tranid\r\n FROM dt_yc.ele_info\r\n WHERE use_start_date is not null\r\n AND use_unit_code is not null\r\n AND use_unit_code != '-'\r\n AND use_unit_code != '不详'\r\n AND make_unit_name is not null\r\n AND make_unit_name != '-'\r\n AND make_unit_name != '/'\r\n AND set_unit_name is not null\r\n AND set_unit_name != '-'\r\n AND set_unit_name != '/'\r\n AND insp_org_name is not null\r\n AND insp_org_name != '-'\r\n AND insp_org_name != '/'\r\n AND wb_unit_name is not null\r\n AND wb_unit_name != '/'\r\n AND wb_unit_name != '*'\r\n AND wb_unit_name != '0'\r\n AND wb_unit_name != '//'\r\n AND wb_unit_name != '-'\r\n AND wb_unit_name != '--'\r\n AND wb_unit_name != '**'\r\n AND wb_unit_name != '1'\r\n \"\"\"\r\n cursor.execute(query)\r\n rows = cursor.fetchall()\r\n\r\n ele_info = {}\r\n for row in rows:\r\n apply_location = row[0]\r\n use_start_date = str(row[1])\r\n tranid = row[2]\r\n\r\n use_months = get_use_months(current_date, use_start_date)\r\n ele_info[tranid] = [apply_location, use_months]\r\n\r\n # 高危电梯地区信息聚合(信息缺失,暂时无法聚合)\r\n\r\n # 高危电梯使用月数信息聚合(分别存储0-50,50-100,100-150,150-200,200-250,250-300,300以上的数据)\r\n use_months_aggr = [0, 0, 0, 0, 0, 0, 0]\r\n for high_risk_tranid in high_risk_tranid_set:\r\n info = ele_info.get(high_risk_tranid, [])\r\n if len(info) == 0:\r\n continue\r\n else:\r\n use_months = info[1]\r\n if use_months in range(0, 50):\r\n use_months_aggr[0] += 1\r\n elif use_months in range(50, 100):\r\n use_months_aggr[1] += 1\r\n elif use_months in range(100, 150):\r\n use_months_aggr[2] += 1\r\n elif use_months in range(150, 200):\r\n use_months_aggr[3] += 1\r\n elif use_months in range(200, 250):\r\n use_months_aggr[4] += 1\r\n elif use_months in range(250, 300):\r\n use_months_aggr[5] += 1\r\n elif use_months >= 300:\r\n use_months_aggr[6] += 1\r\n \r\n # 将聚合结果插入数据库中\r\n for i in range(len(use_months_aggr)):\r\n amount = use_months_aggr[i]\r\n lower_use_month = i * 50\r\n upper_use_month = (i + 1) * 50\r\n if i == 6:\r\n upper_use_month = 100000000\r\n\r\n insert = \"INSERT INTO dt_yc.model_use_months_aggr VALUES(DATE_FORMAT(%s, '%%Y-%%m-%%d'), %s, %s, %s)\"\r\n val = [current_date, lower_use_month, upper_use_month, amount]\r\n cursor.execute(insert, val)\r\n conn.commit()\r\n print('高危电梯使用月数信息聚合完毕')\r\n\r\n # 高危电梯投用场所信息聚合\r\n apply_loc_aggr = {}\r\n for high_risk_tranid in high_risk_tranid_set:\r\n info = ele_info.get(high_risk_tranid, [])\r\n if len(info) == 0:\r\n continue\r\n else:\r\n apply_location = info[0]\r\n if apply_loc_aggr.get(apply_location, -1) == -1:\r\n apply_loc_aggr[apply_location] = 1\r\n else:\r\n apply_loc_aggr[apply_location] += 1\r\n\r\n # 将聚合结果插入数据库中\r\n for apply_location in apply_loc_aggr:\r\n amount = apply_loc_aggr[apply_location]\r\n\r\n insert = \"INSERT INTO dt_yc.model_apply_loc_aggr VALUES(DATE_FORMAT(%s, '%%Y-%%m-%%d'), %s, %s)\"\r\n val = [current_date, apply_location, amount]\r\n cursor.execute(insert, val)\r\n conn.commit()\r\n print('高危电梯投用场所信息聚合完毕')\r\n\r\n print('高危电梯信息聚合完毕')\r\n print('------------------------------------------------------')\r\n print('------------------------------------------------------')\r\n\r\n cursor.close()\r\n conn.close()\r\n","repo_name":"CUINeo/elevator-fault-prediction-model","sub_path":"get_aggrs.py","file_name":"get_aggrs.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27583422780","text":"import datetime\nimport logging\nimport json \nimport requests\nimport os\nimport sys\nsys.path.append(os.path.abspath(\"\"))\n\nimport azure.functions as func\nfrom sharedcode import dbhelper as dbh\nfrom sharedcode import emailrequestmsg as emsg\n\ndef main(mytimer: func.TimerRequest) -> None:\n utc_timestamp = datetime.datetime.utcnow().replace(\n tzinfo=datetime.timezone.utc).isoformat()\n #if mytimer.past_due:\n # logging.warning('The timer is past due!')\n \n logging.getLogger().setLevel(logging.INFO)\n\n alert_full_list = []\n product_list = [\n \"619\",\"620\",\"621\",\"622\",\"623\",\"630\"\n ]\n\n alert_headlines = api_get_alert_headlines(os.environ['WEATHER_ADMIN_CODE'])['alerts']\n \n for prod in product_list:\n logging.warning(f\"Checking product code {prod}\") \n product_info = api_get_product_info(prod) \n feature_time = product_info[\"products\"][prod][\"time\"][0]\n feature_list = api_get_product_features(prod, feature_time)[\"features\"]\n logging.info(f\"Number of features for product {prod} : {len(feature_list)}\")\n \n for ah in alert_headlines:\n feature = get_feature_contains_alert(feature_list, ah['detailKey'])\n if feature == None:\n logging.info(f\"\\tNo feature with alert id {ah['identifier']} and area {ah['areaId']} found. Skipping...\")\n continue\n else:\n alert_detail = api_get_alert_details(feature[\"properties\"][\"detailKey\"]) \n\n #add alert detail info to the feature\n feature[\"properties\"][\"alert_detail_data\"] = alert_detail['alertDetail'] \n feature[\"properties\"][\"alert_detail_data\"]['buildings'] = []\n feature[\"properties\"][\"alert_detail_data\"]['Recommendations'] = []\n \n if not dbh.alert_already_sent(alert_detail['alertDetail']):\n #check if any building is in scope \n affected_buildings = dbh.get_buildings_in_polygon(feature[\"geometry\"][\"coordinates\"][0])\n at_least_one_building_affected = False\n for b in affected_buildings:\n at_least_one_building_affected = True\n logging.info(f\"\\t\\tFound building affected by alert: {b['id']} {b['Building Name']}\")\n #add affected building info to alert\n feature[\"properties\"][\"alert_detail_data\"]['buildings'].append(b)\n\n if at_least_one_building_affected:\n #add recommendations \n recommendations = dbh.get_alert_recommendations(feature['properties']['alert_detail_data']['phenomena'])\n for r in recommendations:\n feature[\"properties\"][\"alert_detail_data\"]['Recommendations'] = r['Recommendations']\n\n dbh.save_alert(feature[\"properties\"][\"alert_detail_data\"])\n #log_alert_detail(feature) \n alert_saved = True \n\n #send email request to queue\n email_request_msg = emsg.EmailRequestMessage.from_alert_detail_json(feature[\"properties\"][\"alert_detail_data\"])\n dbh.put_email_request_msg(email_request_msg) \n\n else:\n logging.info(f\"\\tNo buildings affected by alert: {ah['identifier']}; areaId = {ah['areaId']}\")\n \n else:\n logging.warning(f\"\\tAlert already sent: {ah['identifier']}; areaId = {ah['areaId']}\")\n\n#### Weather.com API handling\ndef api_get_alert_headlines(adminDistrictCode):\n url = f\"{os.environ['WEATHER_API_ENDPOINT']}/v3/alerts/headlines?adminDistrictCode={adminDistrictCode}&format=json&language=en-US&apiKey={os.environ['WEATHER_API_KEY']}\"\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n elif response.status_code == 204:\n return json.loads(\"{ }\")\n else:\n logging.error(f'Error calling api_get_alert_headlines: {response.text}')\n \n\ndef api_get_product_info(productCode, maxTimes = 1):\n url = f\"{os.environ['WEATHER_API_ENDPOINT']}/v2/vector-api/products/{productCode}/info?meta=true&max-times={maxTimes}&apiKey={os.environ['WEATHER_API_KEY']}\"\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n elif response.status_code == 204:\n return json.loads(\"{ }\")\n else:\n logging.error(f'Error calling api_get_feature_info: {response.text}')\n\ndef api_get_alert_details(alertid):\n url = f\"{os.environ['WEATHER_API_ENDPOINT']}/v3/alerts/detail?alertId={alertid}&format=json&language=en-US&apiKey={os.environ['WEATHER_API_KEY']}\"\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n elif response.status_code == 204:\n return None\n else:\n logging.error(f'Error calling api_get_alert_details: {response.text}')\n\ndef api_get_product_features(productCode, time, lod = 1, x = 0, y = 0, tilesize = 256):\n url = f\"{os.environ['WEATHER_API_ENDPOINT']}/v2/vector-api/products/{productCode}/features?time={time}&lod={lod}&x={x}&y={y}&tile-size={tilesize}&apiKey={os.environ['WEATHER_API_KEY']}\"\n response = requests.get(url)\n if response.status_code == 200:\n return response.json()\n elif response.status_code == 204:\n return json.loads(\"{ }\")\n else:\n logging.error(f'Error calling api_get_product_features: {response.text}')\n\n#### Building data\ndef notify_building_managers(building, weather_feature):\n if (building['O&M Responsibility'] != 'None'):\n logging.warning(f\"\\t\\tNotification sent to B# ({building['id']} {building['Building Name']}), notified person: {building['MSM']}\") \n \ndef log_alert_detail(weather_feature):\n logging.warning(f\"\\tAlert: {weather_feature['properties']['alert_detail_data']}\")\n \n#### Search function\ndef get_feature_contains_alert(feature_collection, alert_detail_key):\n for f in feature_collection:\n if f['properties']['detailKey'] == alert_detail_key:\n return f\n return None","repo_name":"marceloes/weatherappnotificationfunc","sub_path":"WeatherNotificationFunc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36312209160","text":"import requests\nimport json\nfrom datetime import datetime, timedelta\n\n\ndef parsing(t):\n File = list()\n a = t.strftime(\"%y-%m-%d %H:%M:%S\")\n dt = datetime.strptime(a, \"%y-%m-%d %H:%M:%S\")\n dt = dt - timedelta(hours=4)\n b = datetime.now()\n datreq = b.strftime('%d.%m.%Y')\n data = {}\n\n req = requests.get(\n f'http://budget.gov.ru/epbs/registry/grants/data?filterminstartdate={datreq}&filterminsum=100000000&blocks=info&pageSize=1')\n test = json.loads(req.text)\n recordCount = test['recordCount']\n req_new = requests.get(\n f'http://budget.gov.ru/epbs/registry/grants/data?filterminstartdate={datreq}&filterminsum=100000000&blocks=info&pageSize={recordCount}')\n file = json.loads(req_new.text)\n for key in file['data']:\n time = key['info']['loaddate']\n time = datetime.strptime(time[2:19], \"%y-%m-%d %H:%M:%S\")\n if time > dt:\n data['Регистрационный номер'] = key['info']['regNum']\n data['Наименование вида соглашения'] = key['info']['mfName']\n data['Размер субсидии, бюджетных инвестиций, межбюджетного трансферта (средств)'] = key['info']['currencySum'] + ' рублей'\n data['Дата заключения соглашения'] = key['info']['startDate'][:10]\n data['Дата окончания срока действия соглашения'] = key['info']['endDate'][:10]\n data['Время добавления'] = time\n File.append(data)\n data = {}\n\n return File\n\n","repo_name":"DanyaToshchakov/project81","sub_path":"pars.py","file_name":"pars.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12355983756","text":"image = cv.imread(r'C:\\Users\\Administrator\\PycharmProjects\\TensorFlow\\datasets\\cat.jpg')\nimage = np.array(image, dtype=np.float32)\nshape = image.shape\nimage = np.expand_dims(image, axis=0)\n\nfilter = tf.Variable(tf.ones([11, 11, 3, 1]))\n\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init)\n res = tf.nn.conv2d(image, filter, strides=[1, 2, 2, 1], padding=\"SAME\")\n res_image = sess.run(tf.reshape(res, (int(shape[0] / 2), int(shape[1] / 2))))\n res_image = res_image / res_image.max()\n\n show_image(res_image)","repo_name":"tianxing1994/TensorFlow","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14016243507","text":"\"\"\"\nThis file tests the BOPCheckboxQuestion and BOPMCQuestion classes.\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport pytest as pytest\nimport boptools.question\n\n\n@pytest.fixture\ndef poll_03_raw_data():\n FILENAMES = [\n 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTAHfGjhQpmRDxCogsvqUORaKiSc8PGCF4-UXY5W27WUfA9TSIBR8lClcUMgBBzQdoQnG4Yxy89Yo14/pub?gid=938058835&single=true&output=csv',\n 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ3MzWxGZBipj1tQsSq9cnIwvZMLybB4s9SoDt85wLVLju7yjMpYGV5TB9W5JC_eWtGK4cgqtr5cRxe/pub?gid=739468815&single=true&output=csv',\n 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTboCkU4YN4NOZMNJwuTGYtYub9lV5BJ5m4xKn3O74SjMbPGkZ_rgs6BPL8JIIfzWfVjCVlf2gm7h3M/pub?gid=782729277&single=true&output=csv']\n\n dfs = []\n for filename in FILENAMES:\n dfs.append(pd.read_csv(filename))\n return pd.concat(dfs, axis=0).reset_index(drop=True)\n\n\ndef test_multiple_choice_recode(poll_03_raw_data):\n weighting_variable = np.trunc(poll_03_raw_data['What graduation class are you?'])\n weighting_variable_values = weighting_variable.value_counts(normalize=True).to_dict()\n optimal_portion = 1 / len(weighting_variable_values)\n to_replace = []\n value = []\n for weighting_variable_value in weighting_variable_values:\n to_replace.append(weighting_variable_value)\n weight = optimal_portion / weighting_variable_values[weighting_variable_value]\n value.append(weight)\n weighting_variable = weighting_variable.replace(to_replace=to_replace, value=value).rename(\"weights\")\n\n smart_column = poll_03_raw_data[\"Should Brown require applicants to submit a standardized test score (ACT/SAT)?\"]\n mc_question = boptools.question.BOPMCQuestion(data=smart_column,\n weighting_variable=weighting_variable,\n output=\"/Users/arjunshanmugam/Desktop\")\n mc_question.recode()\n mc_question.plot_responses(weighted=True, moe=0)\n mc_question.plot_responses(weighted=False, moe=0)\n\n new_dorm_column = poll_03_raw_data[\"What do you call the dorms located on Vartan Gregorian Quad?\"]\n mc_question = boptools.question.BOPMCQuestion(data=new_dorm_column,\n weighting_variable=weighting_variable,\n output=\"/Users/arjunshanmugam/Desktop\")\n mc_question.recode(display_values={\"Greg\", \"New Dorm\", \"Vartan Gregorian Quad (A/B)\", \"Unsure\",\n \"Prefer not to answer\"})\n mc_question.plot_responses(weighted=True, moe=0)\n mc_question.plot_responses(weighted=False, moe=0)\n\n\ndef test_checkbox_recode(poll_03_raw_data):\n weighting_variable = np.trunc(poll_03_raw_data['What graduation class are you?'])\n weighting_variable_values = weighting_variable.value_counts(normalize=True).to_dict()\n optimal_portion = 1 / len(weighting_variable_values)\n to_replace = []\n value = []\n for weighting_variable_value in weighting_variable_values:\n to_replace.append(weighting_variable_value)\n weight = optimal_portion / weighting_variable_values[weighting_variable_value]\n value.append(weight)\n weighting_variable = weighting_variable.replace(to_replace=to_replace, value=value).rename(\"weights\")\n\n race_column = poll_03_raw_data['What race do you identify with?']\n checkbox_question = boptools.question.BOPCheckboxQuestion(data=race_column,\n weighting_variable=weighting_variable,\n output=\"/Users/arjunshanmugam/Desktop\")\n display_values = {\"White\", \"Asian\", \"Black\", \"Non-white Hispanic\", \"Prefer not to answer\",\n \"Native Hawaiian/Pacific Islander\", \"American Indian/Alaska Native\"}\n checkbox_question.recode(display_values=display_values)\n assert len(checkbox_question.data.columns) == 8\n assert checkbox_question.data['White'].mean() == pytest.approx(.5770, 0.005)\n assert checkbox_question.data['Asian'].mean() == pytest.approx(.3046, 0.005)\n assert checkbox_question.data['Black'].mean() == pytest.approx(.1049, 0.005)\n assert checkbox_question.data['Non-white Hispanic'].mean() == pytest.approx(.0474, 0.005)\n assert checkbox_question.data['Prefer not to answer'].mean() == pytest.approx(.0203, 0.005)\n assert checkbox_question.data['Native Hawaiian/Pacific Islander'].mean() == pytest.approx(.0135, 0.005)\n assert checkbox_question.data['American Indian/Alaska Native'].mean() == pytest.approx(.0118, 0.005)\n checkbox_question.plot_responses(weighted=False, moe=0)\n checkbox_question.plot_responses(weighted=True, moe=0)\n\n drug_column = poll_03_raw_data[\n '[CW: The following question refers to drug use] Which of the following drugs have you used recreationally in the past six months?'].fillna(\n \"None of the above\")\n checkbox_question = boptools.question.BOPCheckboxQuestion(data=drug_column,\n weighting_variable=weighting_variable,\n output=\"/Users/arjunshanmugam/Desktop\")\n major_values = {\"Alcohol\", \"Cocaine\", \"Inhalants (Poppers/Whip-its)\", \"LSD (Acid)\", \"Marijuana\",\n \"MDMA (Ecstasy/Molly)\", \"Nicotine\", \"Psilocybin (Psychedelic mushrooms)\", \"None of the above\",\n \"Unsure\", \"Prefer not to answer\"}\n checkbox_question.recode(display_values=major_values)\n assert len(checkbox_question.data.columns) == 12\n assert checkbox_question.data['Alcohol'].mean() == pytest.approx(0.7750, 0.005)\n assert checkbox_question.data['Marijuana'].mean() == pytest.approx(0.5042, 0.005)\n assert checkbox_question.data['Nicotine'].mean() == pytest.approx(0.1878, 0.005)\n assert checkbox_question.data['None of the above'].mean() == pytest.approx(0.1624, 0.005)\n assert checkbox_question.data['Psilocybin (Psychedelic mushrooms)'].mean() == pytest.approx(0.0880, 0.005)\n assert checkbox_question.data['Cocaine'].mean() == pytest.approx(0.0643, 0.005)\n assert checkbox_question.data['Inhalants (Poppers/Whip-its)'].mean() == pytest.approx(0.0609, 0.005)\n assert checkbox_question.data['LSD (Acid)'].mean() == pytest.approx(0.0372, 0.005)\n assert checkbox_question.data['Prefer not to answer'].mean() == pytest.approx(0.0271, 0.05)\n assert checkbox_question.data['MDMA (Ecstasy/Molly)'].mean() == pytest.approx(0.0186, 0.05)\n assert checkbox_question.data['Unsure'].mean() == pytest.approx(0.00340, 0.005)\n checkbox_question.plot_responses(weighted=False, moe=0)\n checkbox_question.plot_responses(weighted=True, moe=0)\n\n with pytest.raises(ValueError):\n drug_column = poll_03_raw_data[\n '[CW: The following question refers to drug use] Which of the following drugs have you used recreationally in the past six months?']\n checkbox_question = boptools.question.BOPCheckboxQuestion(data=drug_column,\n weighting_variable=weighting_variable,\n output='')\n checkbox_question.recode() # Should raise ValueError because this column contains missing data.\n","repo_name":"brownopinionproject/boptools","sub_path":"tests/test_question.py","file_name":"test_question.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2788928727","text":"import pygame\r\nimport random\r\n\r\n\r\nclass Wall(pygame.sprite.Sprite):\r\n def __init__(self, screen_width, screen_height):\r\n super().__init__()\r\n self.image = pygame.image.load('data/obstacles/BricksWall.png')\r\n self.rect = None\r\n self.size = 50, 50\r\n self.screen_width, self.screen_height = screen_width, screen_height\r\n self.update()\r\n\r\n def spawn(self, coords):\r\n self.set_image()\r\n x_values = set(range(110, 890))\r\n y_values = set(range(175, 790))\r\n for x_coord, y_coord in coords:\r\n x_values -= set(range(x_coord - self.size[0] // 2, x_coord + int(self.size[0] * 1.5) + 1))\r\n y_values -= set(range(y_coord - self.size[0] // 2, y_coord + int(self.size[0] * 1.5) + 1))\r\n self.rect.x = random.choice(list(x_values))\r\n self.rect.y = random.choice(list(y_values))\r\n\r\n def set_image(self):\r\n self.image = pygame.transform.scale(self.image, self.size)\r\n self.rect = self.image.get_rect()\r\n\r\n def get_pos(self):\r\n return self.rect.x, self.rect.y\r\n\r\n","repo_name":"petrsed/Snake-Game","sub_path":"Obstacles.py","file_name":"Obstacles.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"44684150812","text":"#!/usr/bin/env python\n# \n\nimport os, sys, re, copy, shutil\nimport click\nimport numpy as np\nfrom astropy.table import Table\n\n# code name and version\nCODE_NAME = 'util_convert_catalog_ra_dec_to_ds9_region.py'\nCODE_AUTHOR = 'Daizhong Liu'\nCODE_VERSION = '20230108'\nCODE_HOMEPAGE = ''\n\n# logging\n#import logging\n#logging.basicConfig(level=logging.INFO)\n#logger = logging.getLogger(CODE_NAME)\n#logger.setLevel(logging.DEBUG)\n\n\n\n@click.command()\n@click.argument('input_catalog_file', type=click.Path(exists=True))\n@click.argument('output_region_file', type=click.Path(exists=False))\n@click.option('--x-column', type=str, default='x', help='The column name for x coordinate.')\n@click.option('--y-column', type=str, default='y', help='The column name for y coordinate.')\n@click.option('--radius-column', type=str, default='', help='The column name for radius in pixels.')\n@click.option('--color', type=str, default='green')\n@click.option('--radius', type=float, default=5.0)\n@click.option('--index-base', type=click.Choice(['0', '1']), default='0', help='x y index base, 0 or 1. Deafult is 0.')\ndef main(\n input_catalog_file, \n output_region_file, \n x_column, \n y_column, \n radius_column, \n color, \n radius, \n index_base,\n ):\n \n table = Table.read(input_catalog_file)\n assert (x_column in table.colnames)\n assert (y_column in table.colnames)\n x_array = table[x_column]\n y_array = table[y_column]\n if radius_column != '':\n radius_array = table[radius_column]\n else:\n radius_array = np.full(x_array.shape, fill_value=radius)\n to_ds9_pixcoord = 0\n if int(index_base) == 0:\n to_ds9_pixcoord = 1\n with open(output_region_file, 'w') as fp:\n fp.write('# DS9 region file\\n')\n fp.write('global color={}\\n'.format(color))\n fp.write('image\\n')\n for i in range(len(table)):\n fp.write('circle({},{},{})\\n'.format(\n x_array[i] + to_ds9_pixcoord,\n y_array[i] + to_ds9_pixcoord,\n radius_array[i],\n ))\n print('Output to {!r}'.format(output_region_file))\n\n\n\nif __name__ == '__main__':\n \n main()\n\n\n\n","repo_name":"1054/Crab.Toolkit.JWST","sub_path":"bin/util_convert_catalog_x_y_to_ds9_region.py","file_name":"util_convert_catalog_x_y_to_ds9_region.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"36085070933","text":"from collections import defaultdict\nimport heapq\n\n\ndict1 = {'i love you': 5, 'island': 3, 'iroman': 2, 'i love leetcode': 2}\nheap_list = [(value, key) for key,value in dict1.items()]\nprint(heap_list)\n\nmax3 = heapq.nlargest(3, heap_list)\nprint(max3)\n\n\nnums = [1,2,3,4,5,7,9]\ntarget = 12\n\nnums.sort()\n\ndef twosum(nums, start, end, ):\n while start <= end:\n total = nums[start] + nums[end]\n if total == target:\n return start, end\n elif total < target:\n start += 1\n else:\n end -= 1\n\nresult = twosum(nums, 0, len(nums)-1)\nprint(result)\n","repo_name":"ajaygc95/DS-ALGO","sub_path":"Algorithms/Tree/default_dict.py","file_name":"default_dict.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":"45910933286","text":"#!/usr/bin/env python3\nfrom datetime import datetime\n\ns='''\n##########################################\n# Planner for classes and TODO list. #\n# Created by: Advay Makhija #\n# Github: https://github.com/rayquaza-69 #\n##########################################\n'''\nprint(s)\n\n\n### COLOURS ###\n\ncol_deepblue=\"#282a36\"\ncol_lighterblue=\"#44475a\"\ncol_foreground=\"#f8f8f2\"\ncol_lightestblue=\"#6272a4\"\ncol_cyan=\"#8be9fd\"\ncol_green=\"#50fa7b\"\ncol_orange=\"#ffb86c\"\ncol_pink=\"#ff79c6\"\ncol_purple=\"#bd93f9\"\ncol_red=\"#ff5555\"\ncol_yellow=\"#f1fa8c\"\n\n### FONT ###\nfontboi=\"Calibri\"\nprint('Font:',fontboi)\n\n### TT FILE ###\ntt_file='tt.txt'\nfrom os.path import exists\nif not exists(tt_file):\n with open(tt_file,'w') as f:\n None\nprint('Name of tt file:',tt_file)\n\n### DAY ###\nDay = datetime.now().strftime('%A')\nDate = datetime.now().strftime('%d/%m/%Y')\nprint(Day)\nprint(Date)\n\n### Tk window ###\nfrom tkinter import *\n\nroot = Tk()\nroot.title(\"Planner beby\")\nroot.geometry(\"800x500\")\nroot.configure(background=col_deepblue)\n\n### DRAWING CANVAS ###\nLab1=Label(text='',bg=col_yellow).place(x=0,y=250,height=250,width=400)\nLab1=Label(text='',bg=col_yellow).place(x=400,y=0,height=250,width=400)\n\n### DRAWING HEADINGS ###\n## Classes ##\nLab1=Label(root,text='Classes ['+Day+']',fg='#000000',bg=col_yellow,font=(fontboi,16),justify='center').place(x=400,y=0,height=30,width=400)\n## To do ##\nLab1=Label(root,text='To do',fg='#000000',bg=col_yellow,font=(fontboi,16),justify='center').place(x=0,y=250,height=30,width=400)\n## Keys ##\nLab1=Label(root,text='Usage',fg=col_yellow,bg=col_deepblue,font=(fontboi,16),justify='center').place(x=400,y=250,height=30,width=400)\n\n\n### READING THE CLASSES TEXT FILE ###\n\nday_list=['[Monday]','[Tuesday]','[Wednesday]','[Thursday]','[Friday]','[Saturday]','[Sunday]']\n\nclasses_file=\"classes.txt\"\nif not exists(classes_file):\n exit()\nwith open(classes_file) as f:\n class_list=f.readlines()\n\nclass_list_day=[]\nL=[]\nfor i in range(len(class_list)):\n if class_list[i]=='\\n':\n class_list_day.append(L)\n L=[]\n continue\n else:\n L.append(class_list[i].strip())\n\n\nclass_dict={}\nfor i in class_list_day:\n class_dict[i[0][1:-1]]=i[1:]\n\nfor i in class_dict:\n for j in range(len(class_dict[i])):\n class_dict[i][j]=tuple(class_dict[i][j].split())\n\n### PRINTING THE CLASSES ###\n\nclass_day=class_dict[Day]\nprint(class_day)\nLab_classtime=Label(root,text=\"Time\",bg=col_yellow,fg='#000000',justify='center',font=(fontboi,14)).place(x=400,y=40,height=20,width=200)\nLab_classtime=Label(root,text=\"Class\",bg=col_yellow,fg='#000000',justify='center',font=(fontboi,14)).place(x=600,y=40,height=20,width=200)\n\nclass_y=70\n\nfor i in class_day:\n Lab_class=Label(root,text=i[0],bg=col_yellow,fg='#000000',font=(fontboi,12)).place(x=400,y=class_y,height=20,width=200)\n Lab_class=Label(root,text=i[1][0].upper()+i[1][1:],bg=col_yellow,fg='#000000',font=(fontboi,12)).place(x=600,y=class_y,height=20,width=200)\n \n class_y+=25\n\n\n### EDIT BOX AND TO DO ###\n\n## Reading tt file ##\nwith open(tt_file) as f:\n tt_file_list=f.readlines()\nfor i in range(len(tt_file_list)):\n tt_file_list[i]=tt_file_list[i].strip()\n\n\ndef printer():\n ## Clearing screen ##\n Lab_yellow=Label(root,text='',bg=col_yellow).place(x=0,y=300,height=200,width=400)\n global tt_file_list\n todo_x,todo_y=0,300\n for i in range(len(tt_file_list)):\n Lab_todo=Label(root,text=' '*4+str(i+1)+') '+tt_file_list[i],fg='#000000',bg=col_yellow,font=(fontboi,14),anchor='w').place(x=todo_x,y=todo_y,height=20,width=400)\n todo_y+=25\nprinter()\n\n## Button functions ##\nfl=[0,'']\ndef click(a):\n global Entry_edit\n global fl\n print(Entry_edit.get())\n if a==1:\n tt_file_list.append(Entry_edit.get())\n Entry_edit.delete(0,END)\n elif a==2:\n if fl[0]==0:\n Button_add.config(state=DISABLED)\n Button_remove.config(state=DISABLED)\n word=tt_file_list[int(Entry_edit.get())-1]\n fl=[1,int(Entry_edit.get())-1]\n Entry_edit.delete(0,END)\n Entry_edit.insert(0,word)\n \n elif fl[0]==1:\n Button_add.config(state=NORMAL)\n Button_remove.config(state=NORMAL)\n tt_file_list[fl[1]]=Entry_edit.get()\n Entry_edit.delete(0,END)\n\n elif a==3:\n if Entry_edit.get().isdigit():\n tt_file_list.pop(int(Entry_edit.get())-1)\n else:\n tt_file_list.remove(Entry_edit.get())\n Entry_edit.delete(0,END)\n\n printer()\n with open(tt_file,'w') as f:\n for i in tt_file_list:\n f.write(i+'\\n')\n\n\n\n\n## Date ##\nLab_date=Label(root,text=Date,bg=col_purple,fg='#000000',font=(fontboi,16),anchor='center').place(x=0,y=0,height=20,width=400)\nEntry_edit=Entry(root,fg='#000000',bg=col_yellow)\nEntry_edit.place(x=80,y=95,height=30,width=240)\n\nButton_add=Button(root,text='Add',bg=col_green,fg='#000000',bd=0,command=lambda:click(1))\nButton_add.place(x=80,y=130,height=25,width=75)\n\nButton_edit=Button(root,text='Edit',bg=col_cyan,fg='#000000',bd=0,command=lambda:click(2))\nButton_edit.place(x=162.5,y=130,height=25,width=75)\n\nButton_remove=Button(root,text='Remove',bg=col_red,fg='#000000',bd=0,command=lambda:click(3))\nButton_remove.place(x=245,y=130,height=25,width=75)\n\n\n### USAGE ###\nusage='''\\u2022 To add an element, type the required element in the entry feild and press the 'Add' button.\n\n\\u2022 To remove an element, type the required element's index or the element itself in the entry feild and press the 'Remove' button.\n\n\\u2022 To edit an element, type the index of the element in the entry feild and press the 'Edit' button, the text will now be inserted in the entry feild and the other \\\nbuttons will be disabled. Edit the element and press the 'Edit' button again to commit the changes.\n\n\\u2022 For the class schedule, there should be a 'classes.txt' file in the same directory as this program. \\\nit's format can be viewed by clicking'''\nprint(usage)\n\ndef spawn():\n \n root2=Toplevel(root,bg=col_yellow)\n root2.geometry('250x550')\n \n s='''To be written in a file called 'classes.txt'\nin the same directory as this program.\n______________________________________\n\n[Monday]\n06:30-07:30 [class1]\n09:00-11:00 [class2]\n\n[Tuesday]\n01:00-02:00 [class1]\n02:00-03:00 [class2]\n\n[Wednesday]\n03:00-04:00 [class1]\n08:00-02:00 [class2]\n\n[Thursday]\n02:00-11:00 [class1]\n08:00-01:00 [class2]\n\n[Friday]\n01:00--2:00 [class1]\n08:00-10:00 [class2]\n\n[Satuday]\n09:30-14:30 [class1]\n\n[Sunday]\n09:30-04:00 [class1]\n'''\n Lab=Label(root2,text=s,bg=col_yellow,fg='#000000',justify='left',anchor='w').pack()\n\nLab_usage = Label(root,text=usage,bg=col_deepblue,fg=col_yellow,justify='left',anchor='n',font=(fontboi,10),wraplength=390)\nLab_usage.place(x=405,y=280,height=210,width=400)\n\nB_format=Button(root,text='this.',bg=col_deepblue,fg=col_orange,bd=0,highlightthickness=0,font=(fontboi,10),command=spawn)\nB_format.place(x=755,y=450,height=15,width=20)\n\n\nroot.mainloop()\n","repo_name":"biscuitrescue/dotfiles","sub_path":"scripts/python/planner/planner.py","file_name":"planner.py","file_ext":"py","file_size_in_byte":7007,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"37823798165","text":"from django.contrib.auth import get_user_model\nfrom django.db import models\n\nUser = get_user_model()\n\n\nclass Group(models.Model):\n title = models.CharField(\n 'Заголовок',\n max_length=200,\n help_text='Название группы'\n )\n slug = models.SlugField('Адрес', unique=True, help_text='Адрес группы')\n description = models.TextField(\n 'Описание', help_text='Описание группы')\n\n class Meta:\n verbose_name = 'Группа'\n verbose_name_plural = 'Группы'\n\n def __str__(self):\n return self.title\n\n\nclass Post(models.Model):\n text = models.TextField('Текст поста', help_text='Текст поста')\n pub_date = models.DateTimeField('Дата публикации', auto_now_add=True)\n author = models.ForeignKey(\n User,\n on_delete=models.PROTECT,\n related_name='posts'\n )\n group = models.ForeignKey(\n Group,\n related_name=\"group\",\n on_delete=models.SET_NULL,\n blank=True,\n null=True,\n help_text='Выберите группу'\n )\n\n class Meta:\n verbose_name = 'Пост'\n verbose_name_plural = 'Посты'\n ordering = ('-pub_date',)\n\n def __str__(self):\n return self.texts\n","repo_name":"Thx-Phila/hw03_forms","sub_path":"yatube/posts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30600195731","text":"import time\n\nimport tornado.escape\nimport tornado.web\nimport tornado.websocket\nfrom sqlalchemy import or_\nfrom tornado.web import Finish\nimport dal.models as models\nfrom celerywork.log_async_work import purchasing_dynamics\nfrom dal.db_configs import DBSession, statistic_DBSession, auth_redis, redis\nfrom dal.redis_keys import KEY_PURCHASING_DYNAMICS_NOTIFICATIONS\nfrom handlers.base.webbase import BaseHandler\nfrom settings import MP_APPID, APP_OAUTH_CALLBACK_URL, AUTH_COOKIE_DOMAIN, AUTH_COOKIE_EXPIRE_DAYS\n\n\n# 全局基类方法\nclass GlobalBaseHandler(BaseHandler):\n @property\n def session(self):\n if hasattr(self, \"_session\"):\n return self._session\n self._session = DBSession()\n return self._session\n\n @property\n def statistic_session(self):\n if hasattr(self, \"_statistic_session\"):\n return self._statistic_session\n self._statistic_session = statistic_DBSession()\n return self._statistic_session\n\n # 关闭数据库会话\n def on_finish(self):\n if hasattr(self, \"_session\"):\n self._session.close()\n if hasattr(self, \"_statistic_session\"):\n self._statistic_session.close()\n\n # 判断是否为微信浏览器\n def is_wexin_browser(self):\n if \"User-Agent\" in self.request.headers:\n ua = self.request.headers[\"User-Agent\"]\n else:\n ua = \"\"\n return \"MicroMessenger\" in ua\n\n # 判断是否为PC浏览器\n def is_pc_browser(self):\n if \"User-Agent\" in self.request.headers:\n ua = self.request.headers[\"User-Agent\"]\n else:\n ua = \"\"\n return not (\"Mobile\" in ua)\n\n # 判断是否是采购助手APP\n def is_caigou_app(self):\n if \"User-Agent\" in self.request.headers:\n ua = self.request.headers[\"User-Agent\"]\n else:\n ua = \"\"\n return \"senguo:cgapp\" in ua\n\n # 判断采购助手客户端操作系统\n def client_os(self):\n ua = self.request.headers.get(\"User-Agent\", \"\")\n if \"senguo:ioscgapp\" in ua:\n return \"ios\"\n elif \"senguo:androidcgapp\" in ua:\n return \"android\"\n else:\n return \"\"\n\n # 错误页面的处理\n def write_error(self, status_code, error_msg='', error_deal='', **kwargs):\n if status_code == 400:\n self.send_fail(\"参数错误: %s\" % error_msg, 400)\n elif status_code == 401:\n self.send_fail(error_msg or \"未授权调用\", 401)\n elif status_code == 404:\n self.send_fail(error_msg or \"地址错误\", 404)\n elif status_code == 500:\n from handlers.servererror import ServerAlarm\n ServerAlarm.send_server_error(self.request.uri, **kwargs)\n self.send_fail(error_msg or \"系统错误\", 500)\n elif status_code == 403:\n self.send_fail(error_msg or \"没有权限\", 403)\n else:\n super().write_error(status_code, **kwargs)\n\n # 导出csv文件\n def export_to_csv(self, data_content, file_name):\n import csv\n import io\n csv_file = io.StringIO()\n csv_writer = csv.writer(csv_file)\n csv_writer.writerows(data_content)\n filename = 'attachment; filename=\"%s\"' % (file_name + \".csv\")\n self.set_header('Content-Type', 'application/octet-stream;charset=UTF-8')\n self.set_header('Content-Disposition', filename.encode(\"utf-8\"))\n return self.write(csv_file.getvalue().encode(\"utf-8-sig\"))\n\n def export_xlsx(self, workbook, filename):\n from openpyxl.writer.excel import save_virtual_workbook\n virtual_workbook = save_virtual_workbook(workbook)\n filename = 'attachment; filename=\"%s\"' % (filename + \".xlsx\")\n self.set_header('Content-Type', 'application/vnd.ms-excel;charset=UTF-8')\n self.set_header('Content-Disposition', filename.encode(\"utf-8\"))\n return self.write(virtual_workbook)\n\n\n# 登录、账户等基类方法\nclass _AccountBaseHandler(GlobalBaseHandler):\n _wx_oauth_weixin = \"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo&state=onfuckweixin#wechat_redirect\"\n\n # overwrite this to specify which account is used\n __account_model__ = models.AccountInfo\n __account_cookie_name__ = \"passport\"\n __token_cookie_name__ = \"passport_hash\"\n __wexin_oauth_url_name__ = \"oauth\"\n\n # 获取当前用户(判断用户是否登录)\n def get_current_user(self):\n if not self.__account_model__ or not self.__account_cookie_name__:\n raise Exception(\"overwrite model to support authenticate.\")\n # 如果已登录,直接返回\n if hasattr(self, \"_user\"):\n return self._user\n # 检查account_cookie要存在,不存在则退出\n account_cookie = self.get_secure_cookie(self.__account_cookie_name__, max_age_days=int(AUTH_COOKIE_EXPIRE_DAYS))\n if not account_cookie:\n self.clear_current_user()\n return None\n # 检查account_cookie未过期,过期则退出\n passport_id, create_time = [int(i) for i in account_cookie.decode().split(\"|\")]\n if time.time() - create_time >= int(AUTH_COOKIE_EXPIRE_DAYS)*24*60*60:\n self.clear_current_user()\n return None\n # 检查hash,hash不存在退出\n passport_hash = self.get_secure_cookie(self.__token_cookie_name__, max_age_days=int(AUTH_COOKIE_EXPIRE_DAYS))\n if not passport_hash:\n self.clear_current_user()\n return None\n # hash有更新,也退出\n passport_hash = passport_hash.decode()\n real_hash = (auth_redis.get(\"passport_hash:{}\".format(passport_id)) or b\"\").decode()\n if real_hash and real_hash!=passport_hash:\n self.clear_current_user()\n return None\n # 查询用户\n current_user = self.__account_model__.get_by_passport_id(self.session, passport_id)\n if not current_user:\n self.clear_current_user()\n return None\n # 设置用户\n self._user = current_user\n return self._user\n\n # 设置当前用户\n _ARG_DEFAULT = []\n def set_current_user(self, user, domain=AUTH_COOKIE_DOMAIN):\n if not self.__account_model__ or not self.__account_cookie_name__:\n raise Exception(\"overwrite model to support authenticate.\")\n self.set_secure_cookie(\n self.__token_cookie_name__,\n self.__account_model__.calc_passport_hash(user.passport_id),\n domain=domain,\n expires_days=int(AUTH_COOKIE_EXPIRE_DAYS),\n )\n self.set_secure_cookie(\n self.__account_cookie_name__,\n str(user.passport_id) + \"|\" + str(int(time.time())),\n domain=domain,\n expires_days=int(AUTH_COOKIE_EXPIRE_DAYS),\n )\n\n # 清除当前用户\n def clear_current_user(self):\n if not self.__account_model__ or not self.__account_cookie_name__:\n raise Exception(\"overwrite model to support authenticate.\")\n self.clear_cookie(self.__account_cookie_name__, domain=AUTH_COOKIE_DOMAIN)\n self.clear_cookie(self.__token_cookie_name__, domain=AUTH_COOKIE_DOMAIN)\n\n # 平台设置中转站cookie\n def set_current_station_cookie(self, ph_station_id, domain=_ARG_DEFAULT):\n if domain is _AccountBaseHandler._ARG_DEFAULT:\n self.set_secure_cookie(\"ph_station_id\", str(ph_station_id))\n else:\n self.set_secure_cookie(\"ph_station_id\", str(ph_station_id), domain=domain)\n\n # 清除平台当前的中转站\n def clear_current_station_cookie(self, domain=_ARG_DEFAULT):\n if domain is _AccountBaseHandler._ARG_DEFAULT:\n self.clear_cookie(\"ph_station_id\")\n else:\n self.clear_cookie(\"ph_station_id\", domain=domain)\n\n # 门店订货设置中转站cookie\n def set_demand_station_cookie(self, demand_station_id, domain=_ARG_DEFAULT):\n if domain is _AccountBaseHandler._ARG_DEFAULT:\n self.set_secure_cookie(\"ph_demand_station_id\", str(demand_station_id))\n else:\n self.set_secure_cookie(\"ph_demand_station_id\", str(demand_station_id), domain=domain)\n\n # 清除门店订货中转站cookie\n def clear_demand_station_cookie(self, domain=_ARG_DEFAULT):\n if domain is _AccountBaseHandler._ARG_DEFAULT:\n self.clear_cookie(\"ph_demand_station_id\")\n else:\n self.clear_cookie(\"ph_demand_station_id\", domain=domain)\n\n # 设置店铺cookie\n def set_current_shop_cookie(self, ph_shop_id, domain=_ARG_DEFAULT):\n if domain is _AccountBaseHandler._ARG_DEFAULT:\n self.set_secure_cookie(\"ph_shop_id\", str(ph_shop_id))\n else:\n self.set_secure_cookie(\"ph_shop_id\", str(ph_shop_id), domain=domain)\n\n # 清除当前店铺\n def clear_current_shop_cookie(self, domain=_ARG_DEFAULT):\n if domain is _AccountBaseHandler._ARG_DEFAULT:\n self.clear_cookie(\"ph_shop_id\")\n else:\n self.clear_cookie(\"ph_shop_id\", domain=domain)\n\n # 获取服务号微信授权登录链接\n def get_wexin_oauth_link(self, next_url=\"\"):\n if not self.__wexin_oauth_url_name__:\n raise Exception(\"you have to complete this wexin oauth config.\")\n if next_url:\n para_str = \"?next=\"+tornado.escape.url_escape(next_url)\n else:\n para_str = \"\"\n # 微信中使用公众号授权\n if self.is_wexin_browser():\n if para_str:\n para_str += \"&\"\n else:\n para_str = \"?\"\n para_str += \"mode=mp\"\n redirect_uri = tornado.escape.url_escape(\n APP_OAUTH_CALLBACK_URL+\\\n self.reverse_url(self.__wexin_oauth_url_name__) + para_str)\n link = self._wx_oauth_weixin.format(appid=MP_APPID, redirect_uri=redirect_uri)\n return link\n\n def get_current_user_info(self):\n current_user = self.current_user\n user_info = {}\n if current_user:\n user_info[\"id\"] = current_user.id\n user_info[\"nickname\"] = current_user.nickname or current_user.realname\n user_info[\"imgurl\"] = current_user.head_imgurl_small or \"\"\n user_info[\"phone\"] = current_user.phone or \"\"\n return user_info\n\n\n# 中转站相关接口继承\nclass StationBaseHandler(_AccountBaseHandler):\n def __init__(self, application, request, **kwargs):\n self.current_station = None\n self.current_staff = None\n super().__init__(application, request, **kwargs)\n\n def should_check_identity(self):\n return True\n\n def prepare(self):\n if not self.current_user:\n self.write_error(401, \"请先登录再使用\")\n raise Finish()\n\n # 获取中转站和员工身份(优先从cookie中获取)\n station_id = self.get_secure_cookie(\"ph_station_id\")\n filters = list()\n if station_id:\n filters.append(models.TransferStation.id == station_id)\n staff_station = self.session.query(models.Staff, models.TransferStation)\\\n .join(models.TransferStation, models.TransferStation.id == models.Staff.station_id)\\\n .filter(*filters,\n models.TransferStation.status == 0,\n models.Staff.status == 0,\n models.Staff.account_id == self.current_user.id,\n or_(models.Staff.super_admin_status == 1,\n models.Staff.admin_status == 1))\\\n .first()\n\n # 如果没有中转站或员工身份\n if not staff_station:\n if self.should_check_identity():\n self.clear_current_user()\n self.clear_current_station_cookie()\n self.write_error(401, \"没有有效的管理员身份\")\n raise Finish()\n\n self.current_staff = staff_station[0] if staff_station else None\n self.current_station = staff_station[1] if staff_station else None\n\n\n# 订货助手相关接口继承\nclass DemandBaseHandler(_AccountBaseHandler):\n def prepare(self):\n if not self.current_user:\n self.write_error(401, \"请先登录再使用\")\n raise Finish()\n\n\n# 门店相关接口继承\nclass ShopBaseHandler(_AccountBaseHandler):\n def __init__(self, application, request, **kwargs):\n self.current_contact = None\n self.current_shop = None\n self.current_station = None\n self.current_staff = None\n super().__init__(application, request, **kwargs)\n\n def prepare(self):\n if not self.current_user:\n self.write_error(401, \"请先登录再使用\")\n raise Finish()\n\n # 获取门店、联系人和中转站身份(优先从cookie中获取)\n demand_station_id = self.get_secure_cookie(\"ph_demand_station_id\")\n shop_id = self.get_secure_cookie(\"ph_shop_id\")\n filters = list()\n if demand_station_id:\n filters.append(models.TransferStation.id == demand_station_id)\n if shop_id:\n filters.append(models.Shop.id == shop_id)\n contact_shop_station = self.session.query(models.ShopContact, models.Shop, models.TransferStation) \\\n .join(models.Shop, models.Shop.id == models.ShopContact.shop_id) \\\n .join(models.TransferStation, models.TransferStation.id == models.Shop.station_id) \\\n .filter(*filters,\n models.Shop.status == 0,\n models.ShopContact.status == 0,\n models.TransferStation.status == 0,\n models.ShopContact.account_id == self.current_user.id) \\\n .first()\n\n # 如果没有门店、联系人和中转站身份\n if not contact_shop_station:\n self.clear_current_user()\n self.clear_current_shop_cookie()\n self.clear_demand_station_cookie()\n self.write_error(401, \"没有访问订货单的权限\")\n raise Finish()\n\n self.current_contact = contact_shop_station[0] if contact_shop_station else None\n self.current_shop = contact_shop_station[1] if contact_shop_station else None\n self.current_station = contact_shop_station[2] if contact_shop_station else None\n\n\n# 采购端\nclass PurchaseBaseHandler(_AccountBaseHandler):\n def __init__(self, application, request, **kwargs):\n self.current_station = None\n self.current_staff = None\n super().__init__(application, request, **kwargs)\n\n def prepare(self):\n if not self.current_user:\n self.write_error(401, \"请先登录再使用\")\n raise Finish()\n\n # 获取中转站和采购员身份(优先从cookie中获取)\n station_id = self.get_secure_cookie(\"ph_station_id\")\n filters = list()\n if station_id:\n filters.append(models.TransferStation.id == station_id)\n staff_station = self.session.query(models.Staff, models.TransferStation) \\\n .join(models.TransferStation, models.TransferStation.id == models.Staff.station_id) \\\n .filter(*filters,\n models.TransferStation.status == 0,\n models.Staff.status == 0,\n models.Staff.account_id == self.current_user.id,\n models.Staff.purchaser_status == 1) \\\n .first()\n\n if not staff_station:\n self.clear_current_user()\n self.clear_current_station_cookie()\n self.write_error(401, \"没有有效的采购员权限\")\n raise Finish()\n\n self.current_staff = staff_station[0] if staff_station else None\n self.current_station = staff_station[1] if staff_station else None\n\n # 记录采购动态(用于采购小程序和平台之间的通信)\n def record_purchasing_dynamics(self, record_type, purchase_goods, **last_data_dict):\n # 记录采购动态\n purchase_goods_dict = purchase_goods.to_dict()\n\n # 当前操作用户\n purchase_goods_dict[\"creator_id\"] = self.current_user.id\n\n # 获取上一次的采购单价、数量、重量、小计\n purchase_goods_dict[\"last_price\"] = last_data_dict.get(\"last_price\")\n purchase_goods_dict[\"last_actual_amount\"] = last_data_dict.get(\"last_actual_amount\")\n purchase_goods_dict[\"last_actual_weight\"] = last_data_dict.get(\"last_actual_weight\")\n purchase_goods_dict[\"last_subtotal\"] = last_data_dict.get(\"last_subtotal\")\n\n # 上一次的商品名称\n purchase_goods_dict[\"last_goods_name\"] = last_data_dict.get(\"last_goods_name\")\n # 上一次的供货商id\n purchase_goods_dict[\"last_firm_id\"] = last_data_dict.get(\"last_firm_id\")\n\n purchasing_dynamics.delay(record_type, purchase_goods_dict)\n\n # 发送采购动态更新提醒\n staff_ids = self.session.query(models.Staff)\\\n .filter(models.Staff.purchaser_status == 1,\n models.Staff.station_id == self.current_station.id,\n models.Staff.status == 0)\\\n .all()\n for staff in staff_ids:\n redis.set(KEY_PURCHASING_DYNAMICS_NOTIFICATIONS\n .format(purchase_goods.purchase_order_id, staff.id, self.current_station.id), \"purchasing_dynamics\")\n","repo_name":"kaichenkai/peihuo.cc","sub_path":"source/handlers/base/pub_web.py","file_name":"pub_web.py","file_ext":"py","file_size_in_byte":17392,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"40524189456","text":"#%%\nfrom utils import mae_multi, root_mean_square_error, standard_deviation_error\nimport pandas as pd\nimport numpy as np\nimport os\nimport argparse,joblib, csv\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom matplotlib import dates \nimport datetime\n#%%\n# Initializing Parser\nparser = argparse.ArgumentParser(description ='Softex - PV Power Predection - Model Test')\n \n# Adding Argument\nparser.add_argument('--network',\n type = int,\n choices={0, 1},\n default=1,\n help ='Neural network topology which the dataset will be prepared for (0. MLP or 1. LSTM).')\n \nparser.add_argument('--layers_list',\n nargs='+', \n default=[120],\n help ='Number of neurons each hidden layer will have')\n\n\nparser.add_argument('--input_labels',\n nargs='+', \n default=[\"Radiacao_Avg\", \"Temp_Cel_Avg\", \"Potencia_FV_Avg\"],\n help ='Input features that will be used to make predictions. (TIMESTAMP, Radiacao_Avg,Temp_Cel_Avg, Temp_Amb_Avg,Tensao_S1_Avg,Corrente_S1_Avg, Potencia_S1_Avg, Tensao_S2_Avg, Corrente_S2_Avg, Potencia_S2_Avg, Potencia_FV_Avg, Demanda_Avg,FP_FV_Avg,Tensao_Rede_Avg')\n\nparser.add_argument('--output_labels',\n nargs='+', \n default=[\"Potencia_FV_Avg\"],\n help ='Output features to be predicted. (TIMESTAMP, Radiacao_Avg, Temp_Cel_Avg, Temp_Amb_Avg, Tensao_S1_Avg, Corrente_S1_Avg, Potencia_S1_Avg, Tensao_S2_Avg, Corrente_S2_Avg, Potencia_S2_Avg, Potencia_FV_Avg, Demanda_Avg, FP_FV_Avg, Tensao_Rede_Avg')\n\n\nparser.add_argument('--input_steps',\n type = int,\n default=120,\n help ='Number of minutes used in the input sequence.')\n\nparser.add_argument('--output_steps',\n type = int,\n default=5,\n help ='Number of minutes to be predicted.')\nparser.add_argument('-f')\n\nargs = parser.parse_args()\n\nif args.network == 0:\n network = 'mlp'\nelse:\n network = 'lstm'\nlayers_list = args.layers_list\ninput_labels = args.input_labels\noutput_labels = args.output_labels\nn_steps_in = args.input_steps\nn_steps_out = args.output_steps\nversion = 1\n\n#%%\n#Testing the model fully trained\n#Reading the test input data\ninput_test = pd.read_csv(r'./../db/data/testInputData.csv')\n#Getting the column values\ninput_test = input_test.values\n#Reading the training output data\noutput_test = pd.read_csv(r'./../db/data/testOutputData.csv')\noutput_test = output_test.values\n\nif network == 'lstm':\n in_l = len(input_labels)\n out_l = len(output_labels)\n input_test = input_test.reshape(input_test.shape[0], int(input_test.shape[1]/in_l), in_l)\n\n#%%\n#my_dir = os.path.join(\".\",\"..\",\"db\",\"models\",f\"{network}\", '_'.join(str(e) for e in layers_list), f\"{version}\")\nmy_dir = os.path.join(\".\",\"..\",\"db\",\"models\",f\"{network}\", \"kt_best_model\",\"model.h5\")\n\n\nmodel = tf.keras.models.load_model(my_dir)\n\npredictions = model.predict(input_test)\n\nnormalizator = joblib.load(r'./../db/norm/normPotencia_FV_Avg.save')\n\n#%%\nshift = 850\n\ny = normalizator.inverse_transform(output_test[0+shift:1440+shift])\ny_hat = normalizator.inverse_transform(predictions[0+shift:1440+shift]) \n\ny_true = np.array(y)\ny_pred = np.array(y_hat)\n\nplt.rcParams['font.family'] = 'serif'\nplt.rcParams['font.serif'] = ['Times New Roman']\nplt.rcParams.update({'font.size': 20})\n\nt = np.arange(0, len(y_true), 1)\ntimes=np.array([datetime.datetime(2022, 1, 3, int(p/60), int(p%60), int(0)) for p in t])\nfmtr = dates.DateFormatter(\"%H:%M\")\n\nplt.style.use('seaborn-whitegrid')\n\nplot_size = y_true.shape[1]\n#%%\nfor i in range(plot_size):\n minute = i + 1\n fig = plt.figure(figsize=(12,6))\n ax1=fig.add_subplot(1, 1, 1)\n ax1.plot(times,y_true[:,i],linestyle='-',color= 'red',label = 'Real', linewidth=1.5)\n ax1.plot(times,y_pred[:,i],linestyle='--', color= 'royalblue', label = 'Predito', linewidth=2.5,dashes=(1, 2))\n ax1.xaxis.set_major_formatter(fmtr)\n \n ax1.tick_params(axis='x', labelsize= 18)\n ax1.tick_params(axis='y', labelsize= 18)\n \n ax1.set_ylabel(\"Potência (W)\", fontsize = 20)\n ax1.set_xlabel(\"Hora\", fontsize = 20)\n #plt.title(\"Gráfico Real x Predito - Minuto \"+str(minute), fontsize = 18)\n plt.legend(fontsize = 'small', loc='upper right')\n #plt.grid(b=True)\n #plt.savefig(save_path, dpi=300)\n plt.savefig(f'previsao_{i+1}.pdf', format=\"pdf\", bbox_inches=\"tight\", dpi = 600)\n\n# %%\n","repo_name":"edge-softex/solar_power_forecasting","sub_path":"ai/plots/test_day_exemple.py","file_name":"test_day_exemple.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7896940049","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\ndef my_sort(lst):\n for i in range(N-1):\n mn_idx = i\n for j in range(i+1, N):\n if lst[mn_idx] > lst[j]:\n mn_idx = j\n lst[mn_idx], lst[i] = lst[i], lst[mn_idx]\n return lst\n\ndef solve():\n if M > customer[0]: # 처음 붕어빵을 만들기도 전에 첫 번째 손님이 입장하면 불가능\n return \"Impossible\"\n\n tmp = 0\n for i in range(M, len(cnt)):\n if i % M == 0: # M번째 시간에 해당될때마다 붕어빵은 K개 만큼 늘어남\n tmp += K\n for t in customer:\n if i == t: # 손님이 등장한 시간이면\n tmp -= 1 # 지금껏 만든 붕어빵에서 -1\n break\n if tmp < 0: # 손님에게 붕어빵을 주고난 후 음수가 된다면\n return \"Impossible\" # 해당 손님에게 붕어빵을 줄 수 없던 것 > 불가능\n break\n cnt[i] = tmp # 위 조건에서 걸러지지 않으면 지금까지 남은 붕어빵 개수 현재 시간에 추가\n return \"Possible\"\n\n\nT = int(input())\nfor tc in range(1, T+1):\n N, M, K = map(int, input().split()) # N: 예약 수 / M: 붕어빵 만드는 데 드는 시간 / K: M시간 일했을 때 산출되는 붕어빵 개수\n customer = my_sort(list(map(int, input().split()))) # 손님들이 입장하는 시간 (오름차순 정렬)\n cnt = [0]*(customer[-1]+1) # 시간에 따른 붕어빵 개수 기록 (마지막으로 입장하는 손님에 해당하는 시간까지 만들어주어야 함)\n\n ans = solve()\n\n print(f\"#{tc} {ans}\")\n\n'''\n4\n2 2 2\n3 4\n2 2 2\n1 2\n2 2 1\n4 2\n2 2 1\n3 2\n'''","repo_name":"Going777/Algorithm","sub_path":"SWEA/D3/1860_진기의 최고급 붕어빵.py","file_name":"1860_진기의 최고급 붕어빵.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14428607056","text":"import telebot\nfrom settings import token\nfrom request import req\n\ndef main():\n # Создаем экземпляр бота\n bot = telebot.TeleBot(token)\n\n # Функция, обрабатывающая команду /start\n @bot.message_handler(commands=[\"start\"])\n def start(m, res=False):\n bot.send_message(m.chat.id, 'Я на связи. Напиши мне что-нибудь )')\n # Получение сообщений от юзера\n @bot.message_handler(content_types=['text'])\n def get_text_messages(message):\n if message.text == \"Привет\":\n bot.send_message(message.from_user.id, \"Привет, чем я могу тебе помочь?\")\n elif message.text == \"/help\":\n bot.send_message(message.from_user.id, \"Напиши е1 для новостей\")\n elif message.text == \"е1\" or message.text == \"e1\":\n bot.send_message(message.from_user.id, \"Последние 10 новостей с сайта Е1:\")\n all_news = req()\n for news in all_news[:10]:\n bot.send_message(message.from_user.id, news)\n else:\n bot.send_message(message.from_user.id, \"Я тебя не понимаю. Напиши /help.\")\n\n # Запускаем бота\n bot.polling(none_stop=True, interval=0)","repo_name":"EvgenyT83/TelegramBot-ParserE1","sub_path":"Telegram_bot.py","file_name":"Telegram_bot.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13276345562","text":"try:\n accion=int(input(\"Elige una opcion: \"))\n\n while accion!=1 or accion!=2:\n if accion==1:\n print(\"Bienvenido al registro de usuarios!!!!\")\n nombre=input(\"Ingresa tu nombre: \")\n apellidos=input(\"ingresa tus apellidos: \")\n email=input(\"Ingresa tu email: \")\n contra=input(\"Ingresa tu contraseña: \")\n break\n elif accion==2:\n print(\"Bienvenido al sistema de login!!!!\")\n email=input(\"Ingresa tu email: \")\n contra=input(\"Ingresa tu contraseña: \")\n break\n else:\n accion=int(input(\"lo que has introducido no concuerda con las opciones\\nIntroduce una opcion valida: \"))\n\nexcept ValueError: print(\"!!!Error!!!! has ingresado caracteres\")","repo_name":"Crixis/study-and-practice-python","sub_path":"20-proyecto-python/extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7659227528","text":"\"\"\"\nLDM.py, 22/10/2022, Geoffrey R. Weal\n\nThis program is designed to perform Literature data mining. This program is designed to\n\n1. Scrap literature search websites like Google Scholar for literature.\n2. Download the papers for those literatures as PDFs\n3. Highlight relavant text in those PDFs\n\nThis program uses the `ScrapPaper` program that were originally developed by M. R. Rafsanjani. See https://github.com/rafsanlab/ScrapPaper and https://doi.org/10.1101/2022.03.08.483427\n\n\"\"\"\n\nimport os\nfrom time import sleep, time\n\nfrom selenium.webdriver import Chrome, ChromeOptions\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.alert import Alert\n\nmax_filename_length = 100\ntime_limit = 60.0\ndef download_pdf(URL_address, file_name, path_loc, waiting_time=10):\n\t\"\"\"\n\tThis method will open a firefox web browser and collect the full content from the site.\n\n\tParameters\n\t----------\n\tURL_address : str.\n\t\tThis is the tewaharoa URL to search.\n\n\tResults\n\t-------\n\twebsite : string\n\t\tThis is the content of the website\n\t\"\"\"\n\n\t# First, determine the number of files currently in the liteature pdf folder\n\toriginal_files = os.listdir(path_loc)\n\toriginal_number_of_files = len(original_files)\n\n\t# Second, load the Chrome driver\n\toptions = ChromeOptions()\n\tchrome_prefs = {\n\t \"download.prompt_for_download\": False,\n\t \"plugins.always_open_pdf_externally\": True,\n\t \"download.open_pdf_in_system_reader\": False,\n\t \"profile.default_content_settings.popups\": 0,\n\t \"download.default_directory\": path_loc\n\t}\n\toptions.add_experimental_option(\"prefs\", chrome_prefs)\n\tdriver = Chrome(ChromeDriverManager().install(), options=options)\n\n\t# Third, load the webpage to download the pdf\n\tdriver.get(URL_address)\n\n\t# Fourth, wait until the pdf file has downloaded\n\tfinished = False\n\tintial_time = time()\n\twhile ((time() - intial_time) <= time_limit):\n\t\ttry:\n\t\t\twhile ((time() - intial_time) <= time_limit):\n\t\t\t\tif len(os.listdir(path_loc)) > original_number_of_files:\n\t\t\t\t\tbreak\n\t\t\t\tsleep(1)\n\t\t\twhile ((time() - intial_time) <= time_limit):\n\t\t\t\tfor file in os.listdir(path_loc):\n\t\t\t\t\tif file.endswith('.crdownload'):\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\tfinished = True\n\t\texcept:\n\t\t\ttry:\n\t\t\t\talert = Alert(driver)\n\t\t\t\talert.dismiss()\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tprint('waiting')\n\t\t\tsleep(waiting_time)\n\t\tif finished:\n\t\t\tbreak\n\t\n\tif ((time() - intial_time) <= time_limit):\n\n\t\t# Fifth, wait for a bit and then close the driver\n\t\tsleep(1)\n\t\tdriver.close()\n\n\t\t# Sixth, rename the pdf file.\n\t\toriginal_filename = tuple(set(os.listdir(path_loc)) - set(original_files))\n\t\tif not (len(original_filename) == 1):\n\t\t\texit('issue, new pdf files: '+str(original_filename))\n\t\toriginal_filename = original_filename[0]\n\t\tsplit_title = []\n\t\tfor e in file_name:\n\t\t\tif e.isalnum():\n\t\t\t\tsplit_title.append(e)\n\t\t\telse:\n\t\t\t\tsplit_title.append('_')\n\t\tsplit_title = ''.join(split_title)\n\t\tsplit_title = [word for word in split_title.split('_') if (len(word) > 0)]\n\t\tnew_filename = '_'.join(split_title)\n\t\tnew_filename = (new_filename[:max_filename_length-4]) if (len(new_filename) > (max_filename_length-4)) else new_filename\n\t\tnew_filename = new_filename+'.pdf'\n\t\tos.rename(path_loc+'/'+original_filename, path_loc+'/'+new_filename)\n\n\t\t# Seventh, return pdf filename\n\t\treturn True, new_filename\n\n\telse:\n\n\t\toriginal_filenames = tuple(set(os.listdir(path_loc)) - set(original_files))\n\t\tfor original_filename in original_filenames:\n\t\t\tos.remove(path_loc+'/'+original_filename)\n\n\t\tdriver.close()\n\n\t\treturn False, None\n\n\n","repo_name":"geoffreyweal/LDM","sub_path":"LDM/LDM/download_pdf.py","file_name":"download_pdf.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12427475884","text":"import sys\nsys.stdin.readline()\n\nsummad = set()\neelmised = []\nfor n in sys.stdin.readline().split():\n ulesannete_arv = int(n)\n summad.add(ulesannete_arv)\n uued_summad = [ulesannete_arv]\n for eelmine_summa in eelmised:\n summad.add(ulesannete_arv + eelmine_summa)\n uued_summad.append(ulesannete_arv + eelmine_summa)\n eelmised = uued_summad\nfor reas_lahendatud in sys.stdin.readline().split():\n if int(reas_lahendatud) in summad:\n print(\"JAH\")\n else:\n print(\"EI\")","repo_name":"mihkelmartin/pythonProject","sub_path":"venv/har.py","file_name":"har.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8548011595","text":"from __future__ import annotations\n\nimport asyncio\nimport random\nimport re\nfrom contextlib import asynccontextmanager\nimport string\nfrom typing import Awaitable, Callable, Iterable, List, Optional, Sized, Union\n\nfrom loguru import logger\nfrom appdirs import user_data_dir\nfrom pyrogram import filters\nfrom pyrogram.enums import ChatMemberStatus\nfrom pyrogram.errors import UsernameNotOccupied, UserNotParticipant, FloodWait\nfrom pyrogram.handlers import EditedMessageHandler, MessageHandler\nfrom pyrogram.types import Message, User\n\nfrom ...utils import show_exception, to_iterable, truncate_str, AsyncCountPool\nfrom ..tele import Client\nfrom ..link import Link\n\n__ignore__ = True\n\n\nclass Session:\n \"\"\"回复检测会话, 用于检测跟随回复.\"\"\"\n\n def __init__(self, reply, follows=None, delays=None):\n self.reply = reply\n self.follows = follows\n self.delays = delays\n self.lock = asyncio.Lock()\n self.delayed = asyncio.Event()\n self.followed = asyncio.Event()\n self.canceled = asyncio.Event()\n if not self.follows:\n return self.followed.set()\n\n async def delay(self):\n if not self.delayed:\n return self.delayed.set()\n if isinstance(self.delays, Sized) and len(self.delays) == 2:\n time = random.uniform(*self.delays)\n else:\n time = self.delays\n await asyncio.sleep(time)\n self.delayed.set()\n\n async def follow(self):\n async with self.lock:\n self.follows -= 1\n if self.follows <= 0:\n self.followed.set()\n return self.follows\n\n async def wait(self, timeout=240):\n task = asyncio.create_task(self.delay())\n try:\n await asyncio.wait_for(asyncio.gather(self.delayed.wait(), self.followed.wait()), timeout=timeout)\n except asyncio.TimeoutError:\n return False\n else:\n return not self.canceled.is_set()\n\n async def cancel(self):\n self.canceled.set()\n self.delayed.set()\n self.followed.set()\n\n\nclass UniqueUsername(dict):\n \"\"\"独特名称类, 用于抢注.\"\"\"\n\n def __getitem__(self, user: User):\n if not user.id in self:\n self[user.id] = self.get_unique(user)\n return dict.__getitem__(self, user.id)\n\n @staticmethod\n def get_unique(user: User):\n \"\"\"获得一个独特名称, 该名称将在程序运行全周期一致.\"\"\"\n log = logger.bind(scheme=\"telemonitor\", username=user.name)\n if user.username:\n unique = user.username\n else:\n unique: str = user.name.lower()\n unique = re.sub(r\"[^A-Za-z0-9]\", \"\", unique)\n random_bits = 10 - len(unique)\n if random_bits:\n random_bits = \"\".join(random.choice(string.digits) for _ in range(random_bits))\n unique = unique + random_bits\n log.info(f'([magenta]默认[/]) 当监控到开注时, 将以用户名 \"{unique}\" 注册, 请[yellow]保证[/]具有一定独特性以避免注册失败.')\n return unique\n\n\nclass Monitor:\n \"\"\"监控器类, 可以检测某个人在某个群中发送了某种模式的信息, 并触发特定的动作 (回复/向机器人注册) 等, 用于答题/抢注等.\"\"\"\n\n group_pool = AsyncCountPool(base=1000)\n unique_cache = UniqueUsername()\n\n name: str = None # 监控器名称\n chat_name: Union[str, List[str]] = [] # 监控的群聊名称\n chat_allow_outgoing: bool = False # 是否支持自己发言触发\n chat_user: Union[str, List[str]] = [] # 仅被列表中用户的发言触发 (支持 username / userid)\n chat_keyword: Union[str, List[str]] = [] # 仅当消息含有列表中的关键词时触发, 支持 regex\n chat_probability: float = 1.0 # 发信概率 (0最低, 1最高)\n chat_delay: int = 0 # 发信延迟 (s)\n chat_follow_user: int = 0 # 需要等待 N 个用户发送 {chat_reply} 方可回复\n chat_reply: Union[\n str, Callable[[Message, Optional[Union[str, List[str]]]], Union[str, Awaitable[str]]]\n ] = None # 回复的内容, 可以为恒定字符串或函数或异步函数\n notify_create_name: bool = False # 启动时生成 unique name 并提示, 用于抢注\n allow_edit: bool = True # 编辑消息内容后也触发\n additional_auth: List[str] = [] # 额外认证要求\n\n def __init__(self, client: Client, nofail=True, basedir=None, proxy=None, config: dict = {}):\n \"\"\"\n 监控器类.\n 参数:\n client: Pyrogram 客户端\n nofail: 启用错误处理外壳, 当错误时报错但不退出\n basedir: 文件存储默认位置\n proxy: 代理配置\n config: 当前监控器的特定配置\n \"\"\"\n self.client = client\n self.nofail = nofail\n self.basedir = basedir or user_data_dir(__name__)\n self.proxy = proxy\n self.config = config\n self.log = logger.bind(scheme=\"telemonitor\", name=self.name, username=client.me.name)\n self.session = None\n self.failed = asyncio.Event()\n\n def get_filter(self):\n \"\"\"设定要监控的目标.\"\"\"\n filter = filters.all\n if self.chat_name:\n filter = filter & filters.chat(to_iterable(self.chat_name))\n if not self.chat_allow_outgoing:\n filter = filter & (~filters.outgoing)\n return filter\n\n def get_handlers(self):\n \"\"\"设定要监控的更新的类型.\"\"\"\n handlers = [MessageHandler(self._message_handler, self.get_filter())]\n if self.allow_edit:\n handlers.append(EditedMessageHandler(self._message_handler, self.get_filter()))\n return handlers\n\n @asynccontextmanager\n async def listener(self):\n \"\"\"执行监控上下文.\"\"\"\n group = await self.group_pool.append(self)\n handlers = self.get_handlers()\n for h in handlers:\n self.client.add_handler(h, group=group)\n yield\n for h in handlers:\n try:\n self.client.remove_handler(h, group=group)\n except ValueError:\n pass\n\n async def _start(self):\n \"\"\"监控器的入口函数的错误处理外壳.\"\"\"\n try:\n return await self.start()\n except asyncio.CancelledError:\n raise\n except Exception as e:\n if self.nofail:\n self.log.warning(f\"发生初始化错误, 监控停止.\")\n show_exception(e, regular=False)\n return False\n else:\n raise\n\n async def start(self):\n \"\"\"监控器的入口函数.\"\"\"\n chat_ids = []\n for cn in to_iterable(self.chat_name):\n while True:\n try:\n chat = await self.client.get_chat(cn)\n chat_ids.append(chat.id)\n except UsernameNotOccupied:\n self.log.warning(f'初始化错误: 群组 \"{self.chat_name}\" 不存在.')\n return False\n except KeyError as e:\n self.log.info(f\"初始化错误: 无法访问, 您可能已被封禁.\")\n show_exception(e)\n return False\n except FloodWait as e:\n self.log.info(f\"初始化信息: Telegram 要求等待 {e.value} 秒.\")\n if e.value < 360:\n await asyncio.sleep(e.value)\n else:\n self.log.info(f\"初始化信息: Telegram 要求等待 {e.value} 秒, 您可能操作过于频繁, 监控器将停止.\")\n return False\n else:\n break\n self.chat_name = chat_ids\n try:\n me = await chat.get_member(\"me\")\n except UserNotParticipant:\n self.log.info(f'跳过监控: 尚未加入群组 \"{chat.title}\".')\n return False\n if me.status in (ChatMemberStatus.LEFT, ChatMemberStatus.RESTRICTED):\n self.log.warning(f'初始化错误: 被群组 \"{chat.title}\" 禁言.')\n return False\n if self.additional_auth:\n for a in self.additional_auth:\n if not await Link(self.client).auth(a):\n self.log.info(f\"初始化错误: 权限校验不通过, 需要: {a}.\")\n return False\n if self.notify_create_name:\n self.unique_name = self.get_unique_name()\n spec = f\"[green]{chat.title}[/] [gray50](@{chat.username})[/]\"\n if await self.init():\n self.log.info(f\"开始监视: {spec}.\")\n async with self.listener():\n await self.failed.wait()\n self.log.error(f\"发生错误, 不再监视: {spec}.\")\n return False\n else:\n self.log.bind(notify=True).warning(f\"机器人状态初始化失败, 监控将停止.\")\n return False\n\n async def init(self):\n \"\"\"可重写的初始化函数, 在读取聊天后运行, 在执行监控前运行, 返回 False 将视为初始化错误.\"\"\"\n return True\n\n @classmethod\n def keys(cls, message: Message):\n \"\"\"提取信息中的 keys.\"\"\"\n sender = message.from_user\n if (\n sender\n and cls.chat_user\n and not any(i in to_iterable(cls.chat_user) for i in (sender.id, sender.username))\n ):\n return False\n text = message.text or message.caption\n if cls.chat_keyword:\n for k in to_iterable(cls.chat_keyword):\n if k is None or text is None:\n if k is None and text is None:\n yield None\n else:\n for m in re.findall(k, text, re.IGNORECASE):\n yield m\n else:\n yield text\n\n async def get_reply(self, message: Message, key: Union[str, List[str]]):\n \"\"\"根据 keys 生成回复内容.\"\"\"\n if callable(self.chat_reply):\n result = self.chat_reply(message, key)\n if asyncio.iscoroutinefunction(self.chat_reply):\n return await result\n else:\n return result\n else:\n return self.chat_reply\n\n @staticmethod\n def get_spec(keys):\n \"\"\"返回 keys 的简要表示.\"\"\"\n if keys is None:\n return \"<仅媒体消息>\"\n if isinstance(keys, Iterable) and not isinstance(keys, str):\n keys = \" \".join([str(k).strip() for k in keys])\n return truncate_str(keys.replace(\"\\n\", \" \").strip(), 30)\n\n async def _message_handler(self, client: Client, message: Message):\n \"\"\"消息处理入口函数的错误处理外壳.\"\"\"\n try:\n await self.message_handler(client, message)\n except OSError as e:\n self.log.info(f'发生错误: \"{e}\", 忽略.')\n except asyncio.CancelledError:\n raise\n except Exception as e:\n self.failed.set()\n if self.nofail:\n self.log.warning(f\"发生错误, 监控器将停止.\")\n show_exception(e, regular=False)\n else:\n raise\n finally:\n message.continue_propagation()\n\n async def message_handler(self, client: Client, message: Message):\n \"\"\"消息处理入口函数, 控制是否回复以及等待回复.\"\"\"\n for key in self.keys(message):\n spec = self.get_spec(key)\n self.log.debug(f\"监听到关键信息: {spec}.\")\n if random.random() >= self.chat_probability:\n self.log.info(f\"由于概率设置, 不予回应: {spec}.\")\n return False\n reply = await self.get_reply(message, key)\n if self.session:\n await self.session.cancel()\n if self.chat_follow_user:\n self.log.info(f\"将等待{self.chat_follow_user}个人回复: {reply}\")\n self.session = Session(reply, follows=self.chat_follow_user, delays=self.chat_delay)\n if await self.session.wait():\n self.session = None\n await self.on_trigger(message, key, reply)\n else:\n if self.session and not self.session.followed.is_set():\n text = message.text or message.caption\n if self.session.reply == text:\n now = await self.session.follow()\n self.log.info(\n f'从众计数 ({self.chat_follow_user - now}/{self.chat_follow_user}): \"{message.from_user.name}\"'\n )\n\n async def on_trigger(self, message: Message, key: Optional[Union[List[str], str]], reply: str):\n \"\"\"\n 可修改的回调函数.\n 参数:\n message: 引发回复的消息\n key:\n 当 chat_keyword 没有 capturing groups 时, 类型为 str, 内容为 regex 的 match\n 当 chat_keyword 仅有一个 capturing groups 时, 类型为 str, 内容为 regex 的唯一一个 capturing groups 的对应值\n 当 chat_keyword 有多个 capturing groups 时, 类型为 list(str), 内容为 regex 的各个 capturing groups 的对应值\n \"\"\"\n if reply:\n return await self.client.send_message(message.chat.id, reply)\n\n def get_unique_name(self):\n \"\"\"获取唯一性用户名, 用于注册.\"\"\"\n unique_name = self.config.get(\"unique_name\", None)\n if unique_name:\n self.log.info(f'根据您的设置, 当监控到开注时, 该站点将以用户名 \"{unique_name}\" 注册.')\n return unique_name\n else:\n return Monitor.unique_cache[self.client.me]\n","repo_name":"embykeeper/embykeeper","sub_path":"embykeeper/telechecker/monitor/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":13753,"program_lang":"python","lang":"en","doc_type":"code","stars":203,"dataset":"github-code","pt":"52"} +{"seq_id":"14762427992","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 11 11:58:37 2019\r\n\r\n@author: naveenn\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template, request\r\nimport os\r\nfrom werkzeug.utils import secure_filename\r\nimport numpy as np\r\nimport cv2\r\nfrom skimage.transform import resize\r\nfrom skimage.filters import threshold_local\r\nimport imutils\r\nfrom skimage import measure\r\nfrom skimage.measure import regionprops\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef session():\r\n return render_template('index.html')\r\n\r\n@app.route('/upload', methods = ['GET', 'POST'])\r\ndef upload_img():\r\n global file_path\r\n #if request.method == 'POST':\r\n f = request.files['image_uploads']\r\n\r\n # Save the file to ./uploads\r\n basepath = os.path.dirname(__file__)\r\n file_path = os.path.join(basepath, 'static/uploads', secure_filename(f.filename))\r\n f.save(file_path)\r\n \r\n return render_template('index.html', image = file_path)\r\n\r\n@app.route('/Get_number_plate', methods = ['GET', 'POST'])\r\ndef get_number_plate():\r\n os.chdir(r'C:\\Users\\Public\\Documents\\Python Scripts\\Number_plate_detection\\Flask')\r\n img_path = file_path\r\n\r\n from PIL import Image\r\n im1 = Image.open(img_path)\r\n width, height = im1.size\r\n if(width > 600):\r\n im1 = im1.resize((700,600), Image.NEAREST)\r\n im1.save(img_path)\r\n\r\n img = cv2.imread(img_path)\r\n#---- Image Processing\r\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n img_gray = cv2.bilateralFilter(img_gray,5,50,50) \r\n WHITE = [255, 255, 255]\r\n img_gray = cv2.copyMakeBorder(img_gray, 3, 3, 3, 3, cv2.BORDER_CONSTANT, value=WHITE)\r\n img_bw = cv2.threshold(img_gray, 140, 255, cv2.THRESH_BINARY)[1]\r\n \r\n#---- Getting connected regions \r\n label_image = measure.label(img_bw) \r\n plate_dimensions = (0.03*label_image.shape[0], 0.08*label_image.shape[0], 0.15*label_image.shape[1], 0.3*label_image.shape[1])\r\n plate_dimensions2 = (0.08*label_image.shape[0], 0.2*label_image.shape[0], 0.15*label_image.shape[1], 0.4*label_image.shape[1])\r\n min_height, max_height, min_width, max_width = plate_dimensions\r\n#---- Finding Plate\r\n plate_objects_cordinates = []\r\n plate_like_objects = []\r\n \r\n flag = 0\r\n for region in regionprops(label_image):\r\n if region.area < 50:\r\n continue\r\n\r\n min_row, min_col, max_row, max_col = region.bbox\r\n region_height = max_row - min_row\r\n region_width = max_col - min_col\r\n\r\n if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width and region_width > region_height:\r\n flag = 1\r\n plate_like_objects.append(img_bw[min_row:max_row, min_col:max_col])\r\n plate_objects_cordinates.append((min_row, min_col, max_row, max_col))\r\n \r\n if(flag==0):\r\n min_height, max_height, min_width, max_width = plate_dimensions2\r\n plate_objects_cordinates = []\r\n plate_like_objects = []\r\n \r\n for region in regionprops(label_image):\r\n if region.area < 50:\r\n continue\r\n min_row, min_col, max_row, max_col = region.bbox\r\n \r\n region_height = max_row - min_row\r\n region_width = max_col - min_col\r\n\r\n if region_height >= min_height and region_height <= max_height and region_width >= min_width and region_width <= max_width and region_width > region_height:\r\n plate_like_objects.append(img_bw[min_row:max_row, min_col:max_col])\r\n plate_objects_cordinates.append((min_row, min_col, max_row, max_col))\r\n\r\n#---- Getting cordinates \r\n if (len(plate_objects_cordinates)>1):\r\n for index,cordinates in enumerate(plate_objects_cordinates):\r\n first = cordinates[0]\r\n second = cordinates[2]\r\n third = cordinates[1]\r\n forth = cordinates[3]\r\n \r\n plate = img[first:second, third:forth] \r\n \r\n V = cv2.split(cv2.cvtColor(plate, cv2.COLOR_BGR2HSV))[2]\r\n T = threshold_local(V, 29, offset=15, method=\"gaussian\")\r\n thresh = (V > T).astype(\"uint8\") * 255\r\n thresh = cv2.bitwise_not(thresh)\r\n \r\n plate = imutils.resize(plate, width=350)\r\n thresh = imutils.resize(thresh, width=350)\r\n \r\n license_plate = thresh\r\n labelled_plate = measure.label(license_plate)\r\n \r\n character_dimensions = (0.40*license_plate.shape[0], 0.70*license_plate.shape[0], 0.05*license_plate.shape[1], 0.15*license_plate.shape[1])\r\n min_height, max_height, min_width, max_width = character_dimensions\r\n \r\n characters = []\r\n column_list = []\r\n for regions in regionprops(labelled_plate):\r\n y0, x0, y1, x1 = regions.bbox\r\n region_height = y1 - y0\r\n region_width = x1 - x0\r\n \r\n if region_height > min_height and region_height < max_height and region_width > min_width and region_width < max_width:\r\n roi = license_plate[y0:y1, x0:x1]\r\n \r\n resized_char = resize(roi, (30, 30))\r\n characters.append(resized_char)\r\n \r\n column_list.append(x0)\r\n \r\n if(len(characters) > 0):\r\n cv2.imwrite(os.path.join('static','Plate_img/number_plate.jpg'), plate)\r\n rectangle = cv2.rectangle(img, (third,first), (forth, second), (0,0,255), 2)\r\n cv2.imwrite(os.path.join('static','Plate_img/car_with_plate.jpg'), rectangle)\r\n break\r\n \r\n else:\r\n first = plate_objects_cordinates[0][0]\r\n second = plate_objects_cordinates[0][2]\r\n third = plate_objects_cordinates[0][1]\r\n forth = plate_objects_cordinates[0][3]\r\n \r\n plate = img[first:second, third:forth] \r\n cv2.imwrite(os.path.join('static','Plate_img/number_plate.jpg'), plate)\r\n rectangle = cv2.rectangle(img, (third,first), (forth, second), (0,0,255), 2)\r\n cv2.imwrite(os.path.join('static','Plate_img/car_with_plate.jpg'), rectangle)\r\n \r\n return render_template('index.html', plate_image = os.path.join('static','Plate_img/number_plate.jpg'))\r\n \r\n \r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n #app.run(host= '0.0.0.0', debug = True)\r\n","repo_name":"naveennnair/Number-Plate-detection","sub_path":"Flask_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25933801801","text":"from sqlalchemy.orm import Session\nfrom fastapi import HTTPException, status\nfrom datetime import datetime\nfrom settings import schemas, models\nfrom package.tools import log_message\n\n\ndef get_all(db: Session):\n try:\n delivers = db.query(models.Delivery).all()\n return delivers\n except:\n return {log_message}\n\n\ndef create(request: schemas.Delivery, db: Session):\n try:\n new_deliver = models.Delivery(delivery_quantity=request.delivery_quantity, delivery_locations=request.delivery_locations,\n amount_collected=request.amount_collected, delivery_date=request.delivery_date, user_id=request.user_id, ordered_id=request.ordered_id)\n\n if new_deliver.delivery_quantity > 0 and new_deliver.amount_collected >= 0:\n new_deliver.ordered_date = datetime.now()\n db.add(new_deliver)\n db.commit()\n db.refresh(new_deliver)\n return new_deliver\n else:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"****************** VEUILLEZ VERIFIER LES VALEURS SAISIES ! LA QUANTITE ET LE PRIX DOIVENT ETRE SUPERIEURE A 0 *************************\")\n except:\n return {log_message}\n\n\ndef show_deliver(idDelivery: int, db: Session):\n deliver = db.query(models.Delivery).filter(\n models.Delivery.idDelivery == idDelivery).first()\n if not deliver:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"deliver with the id {idDelivery} doesn't exist\")\n return deliver\n\n\ndef update(idDelivery: int, request: schemas.Ordered, db: Session):\n try:\n deliver = db.query(models.Delivery).filter(\n models.Delivery.idDelivery == idDelivery).first()\n\n if not deliver:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"order with the id {idDelivery} not found\")\n\n deliver.delivery_quantity = request.delivery_quantity\n deliver.amount_collected = request.amount_collected\n\n if deliver.delivery_quantity > 0 and deliver.amount_collected >= 0:\n db.commit()\n return \"updated\"\n else:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"****************** VEUILLEZ VERIFIER LES VALEURS SAISIES ! LA QUANTITE ET LE PRIX DOIVENT ETRE SUPERIEURE A 0 *************************\")\n except:\n return {log_message}\n\n\ndef delete(idDelivery: int, db: Session):\n db.query(models.Delivery).filter(models.Delivery.idDelivery ==\n idDelivery).delete(synchronize_session=False)\n db.commit()\n return {'done'}\n","repo_name":"arnaud2210/essivi-backend","sub_path":"repository/delivers.py","file_name":"delivers.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17385253396","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef fix_ner(input_file, output_file):\n try:\n with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:\n for line in infile:\n line = line.strip()\n if line:\n # Split the line into word and tag\n word, tag = line.split('\\t')\n\n # Check if the word is punctuation\n if word.strip() in ['.', ',', '!', '?', ';', ':', '...', '``', \"''\", '(', ')', '[', ']', '{', '}']:\n tag = '/O'\n\n # Write the fixed line to the output file\n outfile.write(f\"{word}\\t{tag}\\n\")\n else:\n # Empty line, write it as is\n outfile.write('\\n')\n\n print(f\"Tags in {input_file} have been fixed and saved to {output_file}\")\n except FileNotFoundError:\n print(f\"File not found: {input_file}\")\n except Exception as e:\n print(f\"An error occurred: {str(e)}\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: python fix-ner.py input_file output_file\")\n sys.exit(1)\n\n input_file = sys.argv[1]\n output_file = sys.argv[2]\n\n fix_ner(input_file, output_file)\n","repo_name":"SabinPrasai/Assignment1","sub_path":"fix-ner.py","file_name":"fix-ner.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26725075968","text":"import turtle as t\n\nt.bgcolor(\"black\")\ncolors = ['red','purple','blue','green']\nt.speed(0)\n\nx=30\ny=0\n\nwhile True:\n t.circle(x)\n t.pencolor(colors[y % 4])\n t.forward(x)\n t.right(90)\n\n x+=1\n y+=1\n\n if y == 100:\n break\nt.done()","repo_name":"NitulKalita/PythonTurtle","sub_path":"3ddesign.py","file_name":"3ddesign.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"37954661283","text":"import sys\nimport urllib.request\nimport json\nfrom packaging import version\n\ndef find_version_info(ver):\n versions_raw = urllib.request.urlopen(\"https://launchermeta.mojang.com/mc/game/version_manifest.json\").read()\n versions = json.loads(versions_raw)[\"versions\"]\n\n for version_info in filter(lambda x: x[\"type\"] == \"release\", versions):\n if version.parse(version_info[\"id\"]) == ver:\n version_info_raw = urllib.request.urlopen(version_info[\"url\"]).read()\n return json.loads(version_info_raw)\n\n sys.exit(1)\n\n\ndef get_java_version(ver):\n version_info = find_version_info(ver)\n java_version = version_info[\"javaVersion\"][\"majorVersion\"]\n print(java_version)\n\n\ndef get_server_url(ver):\n version_info = find_version_info(ver)\n server_url = version_info[\"downloads\"][\"server\"][\"url\"]\n print(server_url)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n raise Exception(\"Invalid arguments\")\n\n v = version.parse(sys.argv[2])\n if not isinstance(v, version.Version):\n sys.exit(1)\n\n if sys.argv[1] == \"server-url\":\n get_server_url(v)\n elif sys.argv[1] == \"java-version\":\n get_java_version(v)","repo_name":"officialrealTM/mcserver_installer","sub_path":"mcurlgrabber.py","file_name":"mcurlgrabber.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"} +{"seq_id":"24444612327","text":"import os\nimport datetime\nimport logging\nfrom textbase import bot, Message\nfrom textbase.models import LangchainBot\nfrom typing import List\nfrom langchain.document_loaders import UnstructuredURLLoader\nfrom langchain.text_splitter import CharacterTextSplitter\nimport pickle\nfrom langchain.vectorstores import FAISS\nfrom langchain.prompts import PromptTemplate\nfrom langchain.embeddings import SentenceTransformerEmbeddings\n\nfrom langchain import OpenAI as LangOpenAI\nfrom langchain.chains import RetrievalQA\nfrom langchain.memory import ConversationBufferWindowMemory\n\n\nos.environ[\"OPENAI_API_KEY\"] = \"api-key\"\n\n'''A chatbot with Integration of Langchain and OpenAI to do a domain specific task and get the latest \n data as required throught approapriate channels\n This also includes the usages of Faiss vector stores https://github.com/facebookresearch/faiss\n to perform the similarity search in accordance to the embedded vectors '''\n\n'''We can modify these urls according to our target topic and also make sure these websites are bot freindly\n Hereby choosing a finance oriented task to get the latest news on stocks or markets you are intereseted'''\n\nprompt_template = \"\"\"Use the latest yahoo data to answer the question and integrate it with some of your past intelligence\nto give insights and don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\n\"\"\"\nPROMPT = PromptTemplate(\n template=prompt_template, input_variables=[\"context\", \"question\"]\n)\n\n# Configure the logging settings\nlogging.basicConfig(filename='lanchain-bot.log', level=logging.INFO,\n format='%(asctime)s - %(levelname)s: %(message)s')\n\n#specify the url\nurls = ['https://finance.yahoo.com/news/']\nlogging.info(f\"Urls used {urls}\")\n\n''' Creating this function to avoid excessive usage of OpenAI service \n for free accounts & can modify according to paid plans '''\n\ndef process_url_and_save_embeddings(urls):\n logging.info(\"Data retreival , embedding and Vector store method called\")\n # Load files from the remote URL\n loaders = UnstructuredURLLoader(urls=urls)\n data = loaders.load()\n\n # Text Splitter\n text_splitter = CharacterTextSplitter(separator='\\n',\n chunk_size=1000,\n chunk_overlap=0)\n\n docs = text_splitter.split_documents(data)\n\n # Convert words into embeddings\n embeddings = SentenceTransformerEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n\n # Provides a function to search in them with L2 and/or dot product vector comparison\n vectorStore_openAI = FAISS.from_documents(docs, embeddings)\n logging.info(\"vectorstore updated\")\n\n # Save the embeddings to a pickle file\n with open(\"faiss_store_openai.pkl\", \"wb\") as f:\n pickle.dump(vectorStore_openAI, f)\n\n return vectorStore_openAI \n \n\n''' Updates Vector store at 7 am for fresh market updates '''\nnow = datetime.datetime.now()\nif now.hour == 7:\n VectorStore = process_url_and_save_embeddings(urls)\n logging.info(\"Data saved to pickle file at 7 am\")\n \n#load the file contents for Initial setup\nwith open(\"faiss_store_openai.pkl\", \"rb\") as f:\n VectorStore = pickle.load(f) \n\n@bot()\ndef on_message(message_history: List[Message], state: dict = None, prompt = PROMPT,vector = VectorStore.as_retriever()):\n\n # Generate GPT-3.5 Turbo response\n bot_response = LangchainBot.generate(\n prompt=prompt,\n message_history=message_history, # Assuming history is the list of user messages\n vector = vector\n )\n\n response = {\n \"data\": {\n \"messages\": [\n {\n \"data_type\": \"STRING\",\n \"value\": bot_response\n }\n ],\n \"state\": state\n },\n \"errors\": [\n {\n \"message\": \"\"\n }\n ]\n }\n\n return {\n \"status_code\": 200,\n \"response\": response\n }\n\n\n\n'''\nCode for the models.py\n\n\nfrom langchain import OpenAI as LangOpenAI\nfrom langchain.chains import RetrievalQA\nfrom langchain.memory import ConversationBufferWindowMemory\n\nclass LangchainBot:\n api_key = None\n #os.environ[\"OPENAI_API_KEY\"] = \"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\"\n @classmethod\n def generate(\n cls,\n message_history: list[Message],\n temperature=0.7, prompt = None ,vector = None\n ):\n assert cls.api_key is not None, \"OpenAI API key is not set.\"\n #LangOpenAI.api_key = cls.api_key\n\n #Creating model \n llm = LangOpenAI(temperature=temperature) \n\n #will store upto past 5 conversations, Imp feature for chatbots\n memory = ConversationBufferWindowMemory( k=5) \n\n #chain for outputs \n chain_type_kwargs = {\"prompt\": prompt }\n qa = RetrievalQA.from_chain_type(llm=llm, chain_type=\"stuff\", retriever= vector, memory = memory, chain_type_kwargs=chain_type_kwargs)\n\n query = message_history[-1][\"content\"][\"value\"]\n response = qa.run(query)\n \n return response \n \n '''","repo_name":"Soham7777/textbase","sub_path":"examples/langchain-bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"5975091072","text":"def hasCycle(head):\n s, f = head, head\n \n while f and f.next:\n s = s.next\n f = f.next.next\n \n if s == f:\n return True\n \n return False\n\n# TC: O(n)\n# SC: O(1)","repo_name":"mchae90/dsa","sub_path":"blind75/week1/has_cycle.py","file_name":"has_cycle.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19103049655","text":"import model\nimport tkinter\nimport hra\n\nclass GrafickeRozhrani:\n \"\"\"vykreslování pole a práce s grafickou stránkou\"\"\"\n def __init__(self, vyska, sirka, b):\n self.sirka = sirka\n self.vyska = vyska\n self.pocet_bomb = b\n self.viditelne_pole = [[\"?\" for i in range(self.sirka)] for j in range(self.vyska)]\n\n def set_viditelne_pole(self, x, y, znak):\n \"\"\"na danou pozici se dá ekvivalent z pole bomb a čísel\"\"\"\n self.viditelne_pole[x][y] = znak\n\n def set_akce(self, akce):\n \"\"\"tady není potřeba, ale pro opuštění podmínky se uloží\n a používá v advanced grafickému rozhraní\"\"\"\n self.akce = akce\n\n def get_znak_z_viditelneho(self, x, y):\n if x >= 0 and x < self.vyska and y >= 0 and y < self.sirka:\n return self.viditelne_pole[x][y]\n else:\n return None\n \n def set_kompletni_pole(self, pole):\n \"\"\"pro zviditelnění celého pole\"\"\"\n self.viditelne_pole = pole\n\n def tiskni_vyhru(self):\n print(\"\\n\",\"-\"*12,\"\\n\",\"|Vyhrál si!|\\n\",\"-\"*12,\"\\n\")\n\n def tiskni_prohru(self):\n print(\"\\n\",\"-\"*5,\"\\n\",\"|BUM|\\n\",\"-\"*5,\"\\n\")\n \n def vykresli(self, pocet_vlajek = 0):\n \"\"\"co se vykreslí po každé akci včetně počet bomb a volných vlajek\"\"\"\n print(\" \"*3, end = \"\")\n for i in range(self.sirka):\n print(chr(ord(\"A\")+i), end=\" \")\n print()\n for i in range(self.vyska):\n print(\" \"*2, end =\"\")\n print(\" -\"*self.sirka)\n print(\"%2d\" %(i+1),end=\"\")\n print(\"|\",end = \"\")\n print(\"|\".join(self.viditelne_pole[i]), end = \"\")\n print(\"|\")\n print(f\"Počet bomb: {self.pocet_bomb}\")\n print(f\"Počet volných vlajek: {pocet_vlajek}\")\n\nclass GrafickeRozhrani1(GrafickeRozhrani):\n \"\"\"nové prostředí pomocí tkinteru, generace tlačítek\n vše se mění tady až na akce v imaginárním poli,\n kde jsou uložené data bomb, to jde přes akci\"\"\"\n \n def tiskni_prohru(self):\n self.text3.config(text = \"BUM\")\n self.newgabt.grid(row = self.vyska+1, column = 4)\n self.vlajka.config(bg = \"grey\")\n self.odkryt.config(bg = \"grey\")\n self.pole.title(\"!!PROHRÁL SI!!\")\n\n def tiskni_vyhru(self):\n self.text3.config(text = \"VÝHRA\")\n self.newgabt.grid(row = self.vyska+1, column = 4)\n self.vlajka.config(bg = \"grey\")\n self.odkryt.config(bg = \"grey\")\n self.pole.title(\"!!VYHRÁL SI!!\")\n\n def vykresli(self,pocetvlajek):\n \"\"\"slovo se volá do akce, která je napojená\n a popřípadě se mění, přes tlačítka\"\"\"\n self.slovo = \"O\"\n\n def nova_hra():\n \"\"\"po zmáčknutí tlačítka pro start\n nové hry\"\"\"\n self.pole.destroy()\n h0 = hra.Hra()\n h0.set_grafika(\"A\")\n h0.start()\n\n def set_slovo(slovo):\n \"\"\"změna slova aby se provedla správná akce,\n popř. konec okna\"\"\"\n self.slovo = slovo\n if self.slovo == \"V\":\n self.vlajka.config(bg = \"yellow\")\n self.odkryt.config(bg = \"grey\")\n elif self.slovo == \"O\":\n self.vlajka.config(bg = \"grey\")\n self.odkryt.config(bg = \"yellow\")\n else:\n self.akce.obecna_akce(self.slovo,0,0)\n self.pole.destroy()\n\n\n def klik(i,j):\n \"\"\"provedení dané akce a vykreslení správných znaků\"\"\"\n if self.akce.get_konec() == False:\n self.akce.obecna_akce(self.slovo, i, j)\n self.pocet_vlajek.config(text = self.akce.get_pocet_vlajek())\n colors = [\"black\",\"blue\",\"green\",\"red\",\"dark blue\", \"dark green\", \"orange\", \"black\", \"dark red\"]\n for y,elem in enumerate(self.btn):\n for x,button in enumerate(elem):\n if str(self.viditelne_pole[y][x]) == \"0\":\n color = colors[0]\n button.config(text = \" \", fg = color)\n continue\n elif str(self.viditelne_pole[y][x]) == \"B\" or str(self.viditelne_pole[y][x]) == \"?\" \\\n or str(self.viditelne_pole[y][x]) == \"V\":\n color = \"black\"\n else:\n color = colors[int(self.viditelne_pole[y][x])]\n button.config(text = str(self.viditelne_pole[y][x]), fg = color)\n\n self.btn = []\n self.pole = tkinter.Tk()\n self.pole.title(\"Minesweeper\")\n\n prazdny_policko = tkinter.Label(text = \" \", width = 5)\n prazdny_policko.grid(row = 0, column = 0)\n\n #vytvoření elementů v okně\n for k in range(self.sirka):\n pismeno = tkinter.Label(text = chr(ord(\"A\")+k), width = 5)\n pismeno.grid(row = 0, column = k+1)\n for i in range(self.vyska):\n cislo = tkinter.Label(text = i+1, width = 5)\n cislo.grid(row = i+1, column = 0)\n temp = []\n for j in range(self.sirka):\n bt = tkinter.Button(text = \"?\", fg = \"black\", width = 5, command = lambda c = i, d = j: klik(c,d))\n temp.append(bt)\n bt.grid(row = i+1, column = j+1)\n self.btn.append(temp)\n \n self.vlajka = tkinter.Button(text = \"Vlajka\", command = lambda: set_slovo(\"V\"), bg = \"grey\")\n self.odkryt = tkinter.Button(text = \"Odkrýt\", command = lambda: set_slovo(\"O\"), bg = \"yellow\")\n self.konec = tkinter.Button(text = \"Konec\", command = lambda: set_slovo(\"K\"), bg = \"red\")\n self.newgabt = tkinter.Button(text = \"START\", bg = \"green\", command = lambda: nova_hra())\n\n self.text1 = tkinter.Label(text = \"Vlajky\")\n self.text2 = tkinter.Label(text = \"Bomby\")\n self.text3 = tkinter.Label(fg = \"red\")\n self.pocet_vlajek = tkinter.Label(text = self.akce.get_pocet_vlajek())\n self.pocet_bomb = tkinter.Label(text = self.pocet_bomb)\n\n self.vlajka.grid(row = self.vyska + 1, column = 1)\n self.odkryt.grid(row = self.vyska + 1, column = 2)\n self.konec.grid(row = self.vyska + 1, column = 3)\n self.text1.grid(row = self.vyska +1, column = 6)\n self.pocet_vlajek.grid(row = self.vyska +1, column = 7)\n self.text2.grid(row = self.vyska +1, column = 8)\n self.pocet_bomb.grid(row = self.vyska +1, column = 9)\n self.text3.grid(row = self.vyska +1, column = 5)\n\n self.pole.mainloop()\n\nclass Vlastnosti:\n \"\"\"ve vlastnostech se ze vstupu zadají data a předají do hry/pole\n včetně kontroly vstupu, aby byli hodnoty platné, popřípadě se změní na bližší hranici\"\"\" \n def __init__(self):\n self.vyska_horni_mez = 30\n self.vyska_dolni_mez = 3\n self.sirka_horni_mez = 26\n self.sirka_dolni_mez = 3\n self.minimum_bomb = 1\n self.maximum_bomb = 3\n\n def kontrolax(self, x):\n \"\"\"kontrola a popř změna výšky\"\"\"\n temp_x1 = min(x, self.vyska_horni_mez)\n temp_x2 = max(x, self.vyska_dolni_mez)\n if x != temp_x1 or x != temp_x2:\n if x < temp_x2:\n x = temp_x2\n else:\n x = temp_x1\n \n print(f\"Musel jsem změnit výšku na {x}.\")\n return x\n\n def kontrolay(self, y):\n \"\"\"-||- šířka\"\"\"\n temp_y1 = min(y, self.sirka_horni_mez)\n temp_y2 = max(y, self.sirka_dolni_mez)\n if y != temp_y1 or y != temp_y2:\n if y < temp_y2:\n y = temp_y2\n else:\n y = temp_y1\n print(f\"Musel jsem změnit šířku na {y}.\")\n return y\n\n def kontrolab(self, b):\n \"\"\"bomb\"\"\"\n if b > self.maximum_bomb or b < self.minimum_bomb:\n b = self.maximum_bomb//2\n print(f\"Změnil jsem počet bomb na průměr max/min {b}.\")\n return b\n\n def vstup(self):\n try:\n x = int(input(f\"Zadej výšku pole (rozmezí od {self.vyska_dolni_mez} do {self.vyska_horni_mez}): \"))\n x = self.kontrolax(x)\n except ValueError:\n print(\"Zadej číslo.\")\n return 0\n \n try:\n y = int(input(f\"Zadej šířku pole (rozmezí od {self.sirka_dolni_mez} do {self.sirka_horni_mez}): \"))\n y = self.kontrolay(y)\n except ValueError:\n print(\"Zadej číslo.\")\n return 0\n\n self.maximum_bomb = x*y\n\n try:\n b = int(input(f\"Zadej počet bomb (rozmezí od {self.minimum_bomb} do {self.maximum_bomb}): \"))\n b = self.kontrolab(b)\n except ValueError:\n print(\"Zadej číslo.\")\n return 0\n\n Pole0 = model.Pole(x,y,b)\n return Pole0\n\nclass Vlastnosti1(Vlastnosti):\n \"\"\"Pozměněný vstup pomocí grafické vizualizace skrz knihovnu tkinter\"\"\"\n def vstup(self):\n def uloz_vstup(event):\n \"\"\"použií vstupu od uživatele\"\"\"\n try:\n self.x = int(vyskatx.get())\n self.y = int(sirkatx.get())\n self.b = int(bombytx.get())\n self.x = self.kontrolax(self.x)\n self.y = self.kontrolay(self.y)\n self.maximum_bomb = self.x*self.y\n self.b = self.kontrolab(self.b)\n okno.destroy()\n except ValueError:\n print(\"Zadej čísla!\")\n \n def rychla_hra(event):\n \"\"\"přednastavené udáje na novou hru\"\"\"\n self.x = 20\n self.y = 20\n self.b = 40\n okno.destroy()\n\n \"\"\"vytvoření okna pomocí tkinteru\"\"\" \n okno = tkinter.Tk()\n okno.title(\"Hodnoty\")\n #vytvoření elementů\n vyskalb = tkinter.Label(okno, width = 25, text = \"Výška pole (3 - 30):\")\n sirkalb = tkinter.Label(okno, width = 25, text = \"Šířka pole (3 - 26):\")\n bombylb = tkinter.Label(okno, width = 25, text = \"Počet bomb (1 - obsah pole):\")\n vyskatx = tkinter.Entry(width = 15)\n sirkatx = tkinter.Entry(width = 15)\n bombytx = tkinter.Entry(width = 15)\n startbt = tkinter.Button(okno, text = \"START\", width = 15)\n faststart = tkinter.Button(okno, text = \"RYCHLÁ HRA (20|20|40)\", width = 25)\n #přidání na dané okno\n vyskalb.grid(row = 0, column = 0)\n vyskatx.grid(row = 0, column = 1)\n sirkalb.grid(row = 1, column = 0)\n sirkatx.grid(row = 1, column = 1)\n bombylb.grid(row = 2, column = 0)\n bombytx.grid(row = 2, column = 1)\n startbt.grid(row = 3, column = 1)\n faststart.grid(row = 3, column = 0)\n #navázání funkcí\n faststart.bind(\"\", rychla_hra)\n startbt.bind(\"\", uloz_vstup)\n\n okno.mainloop()\n\n pole0 = model.Pole(self.x, self.y, self.b, False)\n return pole0\n","repo_name":"metury/sandbox","sub_path":"Pysweeper/rozhrani.py","file_name":"rozhrani.py","file_ext":"py","file_size_in_byte":11039,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32712394582","text":"from machine import SoftI2C, I2C, Pin\nfrom lcd.machine_i2c_lcd import I2cLcd\n\ndef init_screen(pin_sda, pin_scl, conv_to_pin_obj=False, use_hw_i2c=False, hw_i2c_slot=0):\n if conv_to_pin_obj:\n pin_sda = Pin(pin_sda)\n pin_scl = Pin(pin_scl)\n\n if use_hw_i2c:\n i2c = I2C(hw_i2c_slot, sda=pin_sda, scl=pin_scl)\n else:\n i2c = SoftI2C(sda=pin_sda, scl=pin_scl)\n\n addr = i2c.scan()[0]\n\n return I2cLcd(i2c, addr, 2, 16)\n","repo_name":"linuxgemini/wiegandextended-micropy","sub_path":"src/lib/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"1454244795","text":"import cmd\nimport sys\nimport argparse\nfrom parse_input import parse_add\nfrom localstorage import LocalStrorage\n\n\nclass Run(cmd.Cmd):\n def __init__(self, storage):\n super().__init__()\n self.storage = storage\n\n def do_add(self, args):\n '''To add use quotes and syntax \"key\" = \"value\"'''\n pair = parse_add(args)\n if not pair:\n print('Incorrect input')\n return\n self.storage.add_key(pair)\n\n def do_get(self, args):\n '''Return value if key exists. Type key without quotes'''\n if not args:\n print('Incorrect input')\n return\n value = self.storage.get_key(args)\n print(value)\n\n def do_exists(self, args):\n '''Return True if key in storage, else False.\n Type key without quotes'''\n if not args:\n print('Incorrect input')\n return\n value = self.storage.is_exists(args)\n print(value)\n\n def do_delete(self, args):\n '''Remove key from storage. Type key without quotes'''\n if not args:\n print('Incorrect input')\n return\n self.storage.remove_key(args)\n\n def do_close(self, args):\n '''Proper way to close storage'''\n self.storage.close()\n sys.exit(0)\n\n def do_defragment(self, args):\n '''Simple defragmentator'''\n self.storage.defragmentation()\n\n def do_EOF(self, args):\n self.storage.close()\n return True\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='KV-Storage')\n parser.add_argument('name', type=str, help='Storage name')\n args_p = parser.parse_args()\n storage = LocalStrorage(args_p.name)\n run = Run(storage)\n run.prompt = '> '\n try:\n run.cmdloop()\n except KeyboardInterrupt:\n storage.close()\n","repo_name":"vvadik/KV-Storage","sub_path":"kvstorage.py","file_name":"kvstorage.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":"37824169301","text":"import pandas as pd\nimport uvicorn\nimport sklearn\nimport joblib\nfrom fastapi import FastAPI\n\napp = FastAPI()\nmodel = joblib.load(\"modelIRIS.pkl\")\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n\n# Using Post\n@app.get('/predict/{sepal_length}/{sepal_width}/{petal_length}/{petal_width}')\nasync def predict(sepal_length,sepal_width,petal_length,petal_width):\n irisX = pd.DataFrame({\n 'sepal_length': [float(sepal_length)],\n 'sepal_width': [float(sepal_width)],\n 'petal_length': [float(petal_length)],\n 'petal_width': [float(petal_width)]\n })\n Y_pred = model.predict_proba(irisX)[0]\n \n if Y_pred[0] > Y_pred[1] and Y_pred[0]> Y_pred[2]:\n return {\"orig_name\":'setosa',\"prediction\":Y_pred[0]}\n elif Y_pred[1] > Y_pred[0] and Y_pred[1]> Y_pred[2] :\n return {\"orig_name\":'versicolor',\"prediction\":Y_pred[1]}\n else :\n return {\"orig_name\":'virginica',\"prediction\":Y_pred[2]}\n \nif __name__ == '__main__' :\n uvicorn.run(app,host=\"127.0.0.1\",port=\"8000\")","repo_name":"Pisopen/python-data-1","sub_path":"tp3/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37725567437","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndef plot_building_and_weather_correlations():\n \"\"\"\n Plots two heatmaps :\n - one for the building features\n - another one for the weather features\n \"\"\"\n # Loading the datasets\n building_features = pd.read_csv(\"data/sanitized_complete.csv\")\n\n # Dropping the index and the labels\n building_features = building_features[['GASTW','GAREA','habit','b19','19-45','46-60','61-70','71-80','81-90','91-2000','a2000']]\n weather_features = pd.read_csv('data/Geneva.cli', sep='\\t', header=3)\n\n # Creating the figure instance and the two subplots\n fig = plt.figure(figsize = (40,40))\n ax1 = fig.add_subplot(1, 2, 1) # row, column, position\n ax2 = fig.add_subplot(1, 2, 2)\n\n # Using Pearson Correlation\n building_cor = building_features.corr()\n weather_cor = weather_features.corr()\n\n # We use ax parameter to tell seaborn which subplot to use for this plot\n sns.heatmap(data=building_cor, ax=ax1, cmap=plt.cm.Reds, square=True, cbar_kws={\"shrink\": 0.6}, annot=True, annot_kws={'fontsize': 4})\n sns.heatmap(data=weather_cor, ax=ax2, cmap=plt.cm.Reds, square=True, cbar_kws={\"shrink\": 0.6}, annot=True, annot_kws={'fontsize': 4})\n\n # Adjusting the heatmap sides\n bottom, top = ax1.get_ylim()\n ax1.set_ylim(bottom + 0.5, top - 0.5)\n bottom, top = ax2.get_ylim()\n ax2.set_ylim(bottom + 0.5, top - 0.5)\n\n # Rotating the axis labels\n ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, horizontalalignment='right', fontsize=5)\n ax1.set_yticklabels(ax1.get_yticklabels(), rotation=45, horizontalalignment='right', fontsize=5)\n ax2.set_xticklabels(ax2.get_xticklabels(), rotation=45, horizontalalignment='right', fontsize=5)\n ax2.set_yticklabels(ax2.get_yticklabels(), rotation=45, horizontalalignment='right', fontsize=5)\n\n # Adding titles\n ax1.set_title('Building features correlations', fontsize=10)\n ax2.set_title('Weather features correlations', fontsize=10)\n\n # Displaying the plots\n plt.show()\n","repo_name":"kenyukobayashi/Predicting-Building-Energy-Consumption","sub_path":"correlations.py","file_name":"correlations.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12135820530","text":"#! /usr/bin/env python3 \n\n# -*- coding: utf-8 -*-\n\"\"\"\nA tool to compare the prices of two Bitcoin exchanges. \n\nCreated on Thu Jun 8 08:18:45 2017\n\n@author: hilton\nFrom \n* https://docs.python.org/3.4/library/urllib.request.html#module-urllib.request\n* http://www.pythonforbeginners.com/python-on-the-web/how-to-use-urllib2-in-python/\n* https://www.mercadobitcoin.com.br/api-doc/\n* https://blinktrade.com/docs/\n\"\"\"\n\nimport sys # exit()\nimport math # trunc() \nimport time # time() \nimport json # loads() \nimport datetime # class Datetime \nimport urllib.request # class Request, urlopen()\n\nimport exchange # classes MercadoBitcoin, OkCoin\n\nclass Rates:\n def __init__ (self, dt, usd2brl, brl2usd, service):\n self.dt = dt\n self.usd2brl = usd2brl\n self.brl2usd = brl2usd\n self.service = service\n \n def getBrl2Usd (self):\n return self.brl2usd\n \n def getUsd2Brl (self):\n return self.usd2brl\n \n def getServiceName (self):\n return self.service\n \n def __str__ (self):\n result = ''\n\n service = self.service\n dt = self.dt\n usd2brl = self.usd2brl\n brl2usd = self.brl2usd\n ftupl = (service, dt, usd2brl, brl2usd)\n \n result = \"{0}: {1}: USD2BRL {2:.4f}, BRL2USD {3:.4f}\".format (*ftupl)\n\n return result \n \nclass XbtPrices:\n def __init__ (self, dt, sell, buy, high, low, exch, coin):\n self.dt = dt\n self.sell = sell\n self.buy = buy\n self.sell = sell\n self.high = high\n self.low = low\n self.exch = exch\n self.coin = coin\n \n def getDateTime (self):\n return self.dt\n \n def getBuy (self):\n return self.buy\n \n def getSell (self):\n return self.sell\n \n def getHigh (self):\n return self.high\n \n def getLow (self):\n return self.low\n \n def getExchangeName (self):\n return self.exch\n \n def getCoinName (self):\n return self.coin\n\n def __str__ (self):\n result = ''\n \n dt, sell, buy = self.dt, self.sell, self.buy\n high, low = self.high, self.low\n exch, coin = self.exch, self.coin\n ftpl = (exch, dt, sell, coin, buy)\n result = \"{0}: {1}: Sell {2:.4f} {3}, Buy {4:.4f} {3}\".format (*ftpl)\n ftpl = (low, coin, high)\n result += \"\\n\\tHigh {0:.4f} {1}, Low {2:.4f} {0}\".format (*ftpl)\n \n return result\n \nclass Differences:\n def __init__ (self, rates, mb, ok):\n self.rates = rates\n self.mb = mb\n self.ok = ok\n \n self.dmin = mb.getLow () - ok.getLow () \n self.dmax = mb.getHigh () - ok.getLow ()\n \n self.gmin = 100.0 * self.dmin / ok.getHigh ()\n self.gmax = 100.0 * self.dmax / ok.getLow ()\n \n def getMinDelta (self):\n return self.dmin\n \n def getMaxDelta (self): \n return self.dmax\n \n def getMinGain (self):\n return self.gmin\n \n def getMaxGain (self): \n return self.gmax\n \n def __str__ (self):\n result = \"\"\n \n oname = self.ok.getExchangeName ()\n mname = self.mb.getExchangeName ()\n sname = self.rates.getServiceName ()\n \n fmt = \"Calculation between {0} and {1} rates, with conversion from {2}\"\n result = fmt.format (oname, mname, sname)\n \n # TODO create evaluation for 24h and for the most recent sell/buy\n \n fmt = \"\\nLast: minimum {0:.4f}, maximum {1:.4f}\"\n result += fmt.format (self.getMinDelta (), self.getMaxDelta ())\n \n fmt = \"\\nGain: minimum {0:.4f} %, maximum {1:.4f} %\"\n result += fmt.format (self.getMinGain (), self.getMaxGain ())\n \n return result\n\n# \n# \n# Google section \n#\n\ndef get_google_rate (url):\n result = 0\n\n f = urllib.request.urlopen (url)\n \n line = f.readline ()\n while line != b'':\n ind = line.find (b'currency_converter')\n if ind != -1:\n \n fields = line.split ()\n rate = fields[5].split (b'>')[1]\n \n break\n \n line = f.readline ()\n \n result = float (rate)\n \n return result\n \ndef get_google_rates (urls):\n ts = math.trunc (time.time () + 0.5)\n dt = datetime.datetime.fromtimestamp (ts)\n \n # TODO round the seconds fraction\n \n usd2brl = urls[0]\n brl2usd = urls[1]\n \n usd = 0\n brl = 0\n \n usd = get_google_rate (usd2brl)\n brl = get_google_rate (brl2usd)\n \n result = (dt, usd, brl)\n \n return result\n \ndef get_x_rates (url):\n ts = math.trunc (time.time () + 0.5)\n dt = datetime.datetime.fromtimestamp (ts)\n \n # TODO round the seconds fraction\n \n # Adding a fake browser User-Agent to make site x-rates.com happy\n headers = {'User-Agent' : 'Mozilla 5.10'}\n \n # Create the Request, joining URL and User-Agent\n request = urllib.request.Request (url, headers = headers)\n\n # Open the URL as file\n f = urllib.request.urlopen (request)\n \n # Input over the file to get the rates\n line = None\n while line != b'':\n line = f.readline ()\n ind = line.find (b'BRL')\n if ind == -1:\n continue \n \n ind = line.find (b'rtRates')\n if ind == -1:\n continue \n \n if line.find (b'from=USD') != -1:\n fields = line.split (b'>')\n \n susd = fields[2].split (b'<')[0]\n usd = float (susd)\n \n elif line.find (b'from=BRL') != -1:\n fields = line.split (b'>')\n \n sbrl = fields[2].split (b'<')[0]\n brl = float (sbrl)\n \n result = (dt, usd, brl)\n \n return result\n\ndef get_mb_rates (url):\n f = urllib.request.urlopen (url)\n \n line = f.readline ()\n \n rv = json.loads (line.decode (encoding='utf-8'))\n \n ts = int (rv['ticker']['date'])\n buy = float (rv['ticker']['buy'])\n sell = float (rv['ticker']['sell'])\n high = float (rv['ticker']['high'])\n low = float (rv['ticker']['low'])\n \n dt = datetime.datetime.fromtimestamp (float (ts))\n \n result = (dt, sell, buy, high, low)\n \n return result\n\ndef get_ok_rates (url):\n f = urllib.request.urlopen (url)\n \n line = f.readline ()\n \n rv = json.loads (line.decode (encoding='utf-8'))\n \n ts = int (rv['date'])\n buy = float (rv['ticker']['buy'])\n sell = float (rv['ticker']['sell'])\n high = float (rv['ticker']['high'])\n low = float (rv['ticker']['low'])\n \n dt = datetime.datetime.fromtimestamp (float (ts))\n \n result = (dt, sell, buy, high, low)\n \n return result\n\ndef main ():\n # TODO parse command line \n\n u_usd2brl = 'https://www.google.com/finance/converter?a=1&from=USD&to=BRL'\n u_brl2usd = 'https://www.google.com/finance/converter?a=1&from=BRL&to=USD'\n# u_mb = 'https://www.mercadobitcoin.net/api/ticker/'\n u_xrates = 'http://www.x-rates.com/table/?from=USD&amount=1'\n# u_ok = 'https://www.okcoin.com/api/v1/ticker.do?symbol=btc_usd'\n \n urls = (u_usd2brl, u_brl2usd)\n \n dt, usd2brl, brl2usd = get_google_rates (urls)\n \n google = Rates (dt, usd2brl, brl2usd, \"Google\")\n \n print (\"{0}\\n\".format (google))\n \n #\n #\n # X-rates section \n # \n \n dt, brl2usd, usd2brl = get_x_rates (u_xrates)\n \n x_rates = Rates (dt, brl2usd, usd2brl, \"X-Rates\")\n \n print (\"{0}\\n\".format (x_rates))\n \n # TODO calculate avg USD2BRL rate\n \n #\n #\n # MercadoBitcoin section \n # \n \n mb = exchange.MercadoBitcoin () \n# mb_tupl = get_mb_rates (u_mb)\n mb_tupl = mb.get_ticker ()\n \n dt, sell, buy, high, low = mb_tupl\n \n mb = XbtPrices (dt, sell, buy, high, low, \"MercadoBitcoin\", \"BRL\")\n \n # print (\"MercadoBitcoin: {0}: Sell {1} BRL, Buy {2} BRL\".format (mb))\n print (mb)\n \n brl2usd = google.getUsd2Brl ()\n \n sell /= brl2usd\n buy /= brl2usd \n high /= brl2usd\n low /= brl2usd \n mb_usd = XbtPrices (dt, sell, buy, high, low, \"MercadoBitcoin\", \"USD\")\n print (\"{0}\\n\".format (mb_usd))\n \n #\n #\n # OkCoin section \n # \n \n\n ok = exchange.OkCoin () \n# ok_tupl = get_ok_rates (u_ok)\n ok_tupl = ok.get_ticker ()\n \n dt, sell, buy, high, low = ok_tupl\n \n ok = XbtPrices (dt, sell, buy, high, low, \"OkCoin\", \"USD\")\n \n # print (\"MercadoBitcoin: {0}: Sell {1} BRL, Buy {2} BRL\".format (mb))\n print (\"{0}\\n\".format (ok))\n \n \n diff = Differences (google, mb_usd, ok)\n \n print (diff)\n \n return 0\n \nif __name__ == '__main__':\n sys.exit (main ())","repo_name":"hgfernan/exch2exch","sub_path":"exch2exch.py","file_name":"exch2exch.py","file_ext":"py","file_size_in_byte":8860,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"32778299665","text":"import sys\ninput = sys.stdin.readline\n\nN = int(input())\ngraph = [[] for _ in range(N+1)]\npar = [0] * (N+1) # 자식노드를 index로 부모번호를 저장\npar_cnt = 0 # 구해진 부모노드의 갯수\nfor _ in range(N-1) :\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n\n# bfs\nq = [1] # 루트부터 너비우선탐색 시작.\nwhile q :\n i = q.pop(0)\n for w in graph[i] : # 인접된 노드 중\n if not par[w] : # 아직 부모노드를 찾지 못한 node가 있으면,(이미 부모노드가 들어가있는 노드는 내자식노드임.)\n par[w] = i # 그 노드가 내 자식노드.\n if w != 1 : # 루트 1을 제외하고 deque\n q.append(w)\n\nfor i in range(2, N+1) :\n print(par[i])","repo_name":"YEJIN012/TIL-Algorithm","sub_path":"2023/0220/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41709338902","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Mon Mar 13 15:40:43 2016\nThis script is to convert the txt annotation files to appropriate format needed by YOLO\n@author: Martin Hwang\nEmail: dhhwang89@gmail.com\n\"\"\"\n\nimport os\nfrom os import walk, getcwd\nfrom PIL import Image\nimport xml.etree.ElementTree as ET\nimport math\n\nclass color:\n BOLD = '\\033[1m'\n END = '\\033[0m'\n DEFAULT = '\\033[0;37;40m'\n RED = '\\033[91m'\n\ndef convert(size, box):\n dw = 1. / size[0]\n dh = 1. / 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 (round(x,3), round(y,3), round(w,3), round(h,3))\n\n# Custom define class\nclasses = [\"Skier\", \"Skigate\", \"Person\", \"Billboard\"]\n\n# Configure Paths\nannotation_path = \"/media/martin/My Passport/datasets/kitti/label/\"\nyolo_label_path = \"/media/martin/My Passport/datasets/z_darknet/\"\nimage_path = \"/media/martin/My Passport/datasets/kitti/JPEG/\"\n\n\nlist_file_name = \"ski\"\n\nwd = getcwd()\nlist_file = open('%s/%s_list.txt' % (wd, list_file_name), 'w')\n\n# Get input text file list\ntxt_name_list = []\n\n'''\nexample = \"example/kitti/000021.txt\"\ntxt_file = open(example, \"r\")\nl = []\nfor data in txt_file:\n l.append(data)\n'''\nfor (dirpath, dirnames, filenames) in walk(annotation_path):\n txt_name_list.extend(filenames)\n break\n\nprint(color.BOLD + \"txt file list : {}\".format(txt_name_list) + color.END + '\\n')\n\ntry:\n\n #Process\n for txt_name in txt_name_list:\n print('------------------------------------------------------------------------')\n # open txt file\n txt_path = annotation_path + txt_name\n txt_file = open(txt_path, \"r\")\n\n print(\"Input file : \" + txt_path)\n\n img_path = image_path + txt_name[0:-4] + \".jpg\"\n print(\"Image file : {}\".format(img_path))\n img = Image.open(img_path)\n\n img_width = int(img.size[0])\n img_height = int(img.size[1])\n\n print(\"Image width : {}, height : {}\".format(img_width, img_height))\n\n result_outpath = str(yolo_label_path + txt_name[:-3] + \"txt\")\n result_outfile = open(result_outpath, \"w\")\n print(\"Output:\" + result_outpath + '\\n')\n\n for data in txt_file:\n split = data.split(\" \")\n\n label = split[0]\n xmin = int(split[4])\n ymin = int(split[5])\n xmax = int(split[6])\n ymax = int(split[7])\n\n print('origin : {}'.format(split))\n print(\"xmin : {}, ymin : {}, xmax : {}, ymax : {}\".format(xmin, ymin, xmax, ymax))\n\n cls = label\n if cls == None:\n raise Exception(\"can't find name tag\")\n elif cls not in classes:\n raise Exception(\"name tag not involve this classes\")\n\n b = (float(xmin), float(xmax), float(ymin), float(ymax))\n bb = convert((img_width, img_height), b)\n\n cls_id = classes.index(cls)\n\n print('class name, index : ' + '(' + str(cls) + \", \" + str(cls_id) + ')')\n print(\"bndbox Size : \" + str(b))\n print(\"convert result : \" + str(bb) + '\\n')\n result_outfile.write(str(cls_id) + \" \" + \" \".join([str(a) for a in bb]) + '\\n')\n\n result_outfile.close()\n list_file.writelines('%s%s.jpg\\n' % ( image_path,os.path.splitext(txt_name)[0]))\n\n\n list_file.close()\n\n\n\nexcept Exception as e:\n\n print(color.BOLD + color.RED + \"ERROR : {}\".format(e) + color.END)\n\n if not result_outfile.closed:\n print(color.BOLD + color.RED + \"Close result_outfile\" + color.END)\n result_outfile.close()\n if os.path.exists(result_outpath):\n print(color.BOLD + color.RED + \"delete result outpath\" + color.END)\n os.remove(result_outfile)\n\n","repo_name":"yifanli8086/convert2Bo","sub_path":"kitti.py","file_name":"kitti.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"11945901235","text":"# reference https://github.com/ultralytics/yolov3\n\nimport os\nimport glob\nimport numpy as np\nfrom statistics import *\nimport cv2\nimport shutil\n\ndef get_iou(bb1, bb2, labelPath, predPath):\n \"\"\"\n Calculate the Intersection over Union (IoU) of two bounding boxes.\n\n Parameters\n ----------\n bb1 : dict\n Keys: {'x1', 'x2', 'y1', 'y2'}\n The (x1, y1) position is at the top left corner,\n the (x2, y2) position is at the bottom right corner\n bb2 : dict\n Keys: {'x1', 'x2', 'y1', 'y2'}\n The (x, y) position is at the top left corner,\n the (x2, y2) position is at the bottom right corner\n\n Returns\n -------\n float\n in [0, 1]\n \"\"\"\n assert bb1['x1'] < bb1['x2']\n assert bb1['y1'] < bb1['y2']\n assert bb2['x1'] < bb2['x2']\n assert bb2['y1'] < bb2['y2']\n\n # determine the coordinates of the intersection rectangle\n x_left = max(bb1['x1'], bb2['x1'])\n y_top = max(bb1['y1'], bb2['y1'])\n x_right = min(bb1['x2'], bb2['x2'])\n y_bottom = min(bb1['y2'], bb2['y2'])\n\n if x_right < x_left or y_bottom < y_top:\n print('hhhhh')\n print(labelPath)\n print(predPath)\n print('bb1', bb1)\n print('bb2', bb2)\n print('x_right, x_left, y_bottom, y_top', x_right, x_left, y_bottom, y_top)\n return 0\n\n # The intersection of two axis-aligned bounding boxes is always an\n # axis-aligned bounding box\n intersection_area = (x_right - x_left) * (y_bottom - y_top)\n\n # compute the area of both AABBs\n bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1'])\n bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1'])\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = intersection_area / float(bb1_area + bb2_area - intersection_area)\n assert iou >= 0.0\n assert iou <= 1.0\n return iou\n\n\ndef iou(path1, path2):\n txtList = os.listdir(path1)\n iouList = []\n for txt in txtList:\n labelPath = path1 + txt\n predPath = path2 + txt\n jpgPath = path2 + txt.replace('.txt', '.jpg')\n\n if os.path.exists(predPath):\n h, w, _ = cv2.imread(jpgPath).shape\n with open(labelPath, 'r') as f:\n # print(labelPath)\n x = np.array([x.split() for x in f.read().splitlines()], dtype=np.float32)\n box1 = x\n with open(predPath, 'r') as ff:\n # print(predPath)\n x = np.array([x.split() for x in ff.read().splitlines()], dtype=np.float32)\n box2 = x\n # print('\\n')\n if box1.shape[0] == 2 and box2.shape[0] == 2:\n b2_x1_flag, b2_x2_flag = int(box2[0][0]), int(box2[0][2])\n b2_x1_flag_prime, b2_x2_flag_prime = int(box2[1][0]), int(box2[1][2])\n\n if b2_x1_flag > b2_x1_flag_prime:\n b2_x1, b2_x2 = int(box2[1][0]), int(box2[1][2])\n b2_y1, b2_y2 = int(box2[1][1]), int(box2[1][3])\n\n b1_x1, b1_x2 = int(w * (box1[0][1])) - int(w * (box1[0][3]) / 2), int(w * (box1[0][1])) + int(\n w * (box1[0][3]) / 2)\n b1_y1, b1_y2 = int(h * (box1[0][2])) - int(h * (box1[0][4]) / 2), int(h * (box1[0][2])) + int(\n h * (box1[0][4]) / 2)\n\n bb1 = {'x1': b1_x1, 'x2': b1_x2, 'y1': b1_y1, 'y2': b1_y2}\n bb2 = {'x1': b2_x1, 'x2': b2_x2, 'y1': b2_y1, 'y2': b2_y2}\n iou = get_iou(bb1, bb2, labelPath, predPath)\n iouList.append(iou)\n ###########################################################\n b2_x1, b2_x2 = int(box2[0][0]), int(box2[0][2])\n b2_y1, b2_y2 = int(box2[0][1]), int(box2[0][3])\n\n b1_x1, b1_x2 = int(w * (box1[1][1])) - int(w * (box1[1][3]) / 2), int(w * (box1[1][1])) + int(\n w * (box1[1][3]) / 2)\n b1_y1, b1_y2 = int(h * (box1[1][2])) - int(h * (box1[1][4]) / 2), int(h * (box1[1][2])) + int(\n h * (box1[1][4]) / 2)\n\n bb1 = {'x1': b1_x1, 'x2': b1_x2, 'y1': b1_y1, 'y2': b1_y2}\n bb2 = {'x1': b2_x1, 'x2': b2_x2, 'y1': b2_y1, 'y2': b2_y2}\n iou = get_iou(bb1, bb2, labelPath, predPath)\n iouList.append(iou)\n\n\n else:\n b1_x1, b1_x2 = int(w * (box1[0][1])) - int(w * (box1[0][3]) / 2), int(w * (box1[0][1])) + int(\n w * (box1[0][3]) / 2)\n b1_y1, b1_y2 = int(h * (box1[0][2])) - int(h * (box1[0][4]) / 2), int(h * (box1[0][2])) + int(\n h * (box1[0][4]) / 2)\n b2_x1, b2_x2 = int(box2[0][0]), int(box2[0][2])\n b2_y1, b2_y2 = int(box2[0][1]), int(box2[0][3])\n\n bb1 = {'x1': b1_x1, 'x2': b1_x2, 'y1': b1_y1, 'y2': b1_y2}\n bb2 = {'x1': b2_x1, 'x2': b2_x2, 'y1': b2_y1, 'y2': b2_y2}\n iou = get_iou(bb1, bb2, labelPath, predPath)\n iouList.append(iou)\n ######################################################\n b1_x1, b1_x2 = int(w * (box1[1][1])) - int(w * (box1[1][3]) / 2), int(w * (box1[1][1])) + int(\n w * (box1[1][3]) / 2)\n b1_y1, b1_y2 = int(h * (box1[1][2])) - int(h * (box1[1][4]) / 2), int(h * (box1[1][2])) + int(\n h * (box1[1][4]) / 2)\n b2_x1, b2_x2 = int(box2[1][0]), int(box2[1][2])\n b2_y1, b2_y2 = int(box2[1][1]), int(box2[1][3])\n\n bb1 = {'x1': b1_x1, 'x2': b1_x2, 'y1': b1_y1, 'y2': b1_y2}\n bb2 = {'x1': b2_x1, 'x2': b2_x2, 'y1': b2_y1, 'y2': b2_y2}\n iou = get_iou(bb1, bb2, labelPath, predPath)\n iouList.append(iou)\n\n else:\n b1_x1, b1_x2 = int(w * (box1[0][1])) - int(w * (box1[0][3]) / 2), int(w * (box1[0][1])) + int(\n w * (box1[0][3]) / 2)\n b1_y1, b1_y2 = int(h * (box1[0][2])) - int(h * (box1[0][4]) / 2), int(h * (box1[0][2])) + int(\n h * (box1[0][4]) / 2)\n b2_x1, b2_x2 = int(box2[0][0]), int(box2[0][2])\n b2_y1, b2_y2 = int(box2[0][1]), int(box2[0][3])\n\n bb1 = {'x1': b1_x1, 'x2': b1_x2, 'y1': b1_y1, 'y2': b1_y2}\n bb2 = {'x1': b2_x1, 'x2': b2_x2, 'y1': b2_y1, 'y2': b2_y2}\n iou = get_iou(bb1, bb2, labelPath, predPath)\n iouList.append(iou)\n else:\n iouList.append(0)\n\n return iouList\n\n\n\n\niouList = iou(path1, path2)\n\nprint(mean(iouList))\nshutil.copy(jpgPath, path3)\n","repo_name":"opentja/HKAA-prediction-on-post-operative-X-ray-images","sub_path":"yolo_roi_extraction/iou.py","file_name":"iou.py","file_ext":"py","file_size_in_byte":6870,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"25510557196","text":"Test.Summary = '''\nServer static file as response body.\n'''\n\nr = Test.TxnBoxTestAndRun(\"Static file support\", \"static_file.replay.yaml\"\n , config_path='Auto', config_key=\"meta.txn-box.global\"\n , remap=[\n [ 'http://base.ex', ['--key=meta.txn-box.remap', 'static_file.replay.yaml']]\n ]\n )\nts = r.Variables.TS\nts.Setup.Copy(\"static_file.txt\", ts.Variables.CONFIGDIR)\nts.Disk.records_config.update({\n 'proxy.config.diags.debug.enabled': 1\n , 'proxy.config.diags.debug.tags' : 'txn_box|http'\n})\n","repo_name":"SolidWallOfCode/txn_box","sub_path":"test/autest/gold_tests/static_file/static_file.test.py","file_name":"static_file.test.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"20576602241","text":"import tensorflow as tf\n\n\nclass MathUtils:\n @staticmethod\n def calculate_loss(test_labels, predictions):\n categorical_cross_entropy = tf.keras.losses.CategoricalCrossentropy()\n return categorical_cross_entropy(test_labels, predictions).numpy()\n\n @staticmethod\n def calculate_accuracy(test_labels, predictions):\n categorical_accuracy = tf.keras.metrics.CategoricalAccuracy()\n categorical_accuracy.update_state(test_labels, predictions)\n return categorical_accuracy.result().numpy()\n\n @staticmethod\n def data_percentage_to_indices(data_len, data_parts):\n train_data_index_bound = int(data_len * data_parts[0])\n test_data_index_bound = int(train_data_index_bound + data_len * data_parts[1])\n return [train_data_index_bound, test_data_index_bound]\n","repo_name":"zygisau/CNN_cifar_10","sub_path":"math_utils.py","file_name":"math_utils.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40524603717","text":"import dateutil.relativedelta\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import timedelta, date\nfrom odoo import models\n\n\nclass CustomReport(models.AbstractModel):\n \"\"\"The CustomReport abstract Model is used to generate a top-selling\n products report based on various date options.\"\"\"\n _name = \"report.top_selling_product_report.top_selling_reports\"\n _description = \"Top selling products report\"\n\n def _get_report_values(self, docids, data=None):\n \"\"\"Generate the data for the top-selling products report.\n Args:\n data (dict): A dictionary containing the parameters for the report.\n Returns:\n dict: A dictionary containing the data and other details of the\n top-selling products report.\"\"\"\n limit_value = int(data['period']) if data['period'] else None\n date_option = data['date']\n date_selected_from = None\n date_selected = None\n date_selected_to = None\n other_details = {}\n company_id = data['company']\n warehouse_id = data['warehouse']\n\n from_date = date.today() - dateutil.relativedelta.relativedelta(\n years=100)\n to_date = date.today() + dateutil.relativedelta.relativedelta(days=1)\n\n if date_option == 'days':\n from_date = date.today() - dateutil.relativedelta.relativedelta(\n days=11)\n to_date = date.today() + dateutil.relativedelta.relativedelta(\n days=1)\n date_selected = \"Last 10 Days\"\n\n elif date_option == 'last_month':\n date_limit = date.today() - dateutil.relativedelta.relativedelta(\n months=1)\n from_date = date_limit.replace(day=1)\n to_date = (date_limit + relativedelta(months=1,\n day=1)) - timedelta(1)\n date_selected = \"Last Month\"\n\n elif date_option == 'curr_month':\n from_date = date.today().replace(day=1)\n to_date = date.today() + dateutil.relativedelta.relativedelta(\n days=1)\n date_selected = \"Current Month\"\n\n elif date_option == 'last_year':\n date_limit = date.today() - dateutil.relativedelta.relativedelta(\n years=1)\n from_date = date_limit.replace(day=1)\n to_date = (date_limit + relativedelta(months=12,\n day=1)) - timedelta(1)\n date_selected = \"Last Year\"\n\n elif date_option == 'curr_year':\n from_date = date.today().replace(month=1, day=1)\n to_date = date.today() + dateutil.relativedelta.relativedelta(\n days=1)\n date_selected = \"Current Year\"\n\n elif date_option == 'select_period':\n from_date = data['from_date']\n to_date = data['to_date']\n date_selected_from = from_date\n date_selected_to = to_date\n\n other_details.update({\n 'limit': limit_value,\n 'least': data['least'],\n 'range': date_selected,\n 'date_selected_from': date_selected_from,\n 'date_selected_to': date_selected_to,\n })\n sale_report_model = self.env['sale.report']\n states = sale_report_model._get_done_states()\n data_domain = [('state', 'in', states), ('date', '>=', from_date),\n ('date', '<=', to_date),\n ('company_id', 'in', company_id)]\n if warehouse_id:\n data_domain.append(('warehouse_id', 'in', warehouse_id))\n\n sale_data = sale_report_model.search(data_domain)\n product_dict = {}\n for record in sale_data:\n product_name = record.product_id.display_name\n if product_name in product_dict:\n product_dict[product_name][\n 'sold_quantity'] += record.product_uom_qty\n else:\n product_dict[product_name] = {\n 'product_name': product_name,\n 'sold_quantity': record.product_uom_qty,\n 'uom': record.product_uom.name,\n }\n sorted_products = sorted(product_dict.values(),\n key=lambda x: x['sold_quantity'],\n reverse=not data['least'])\n limit_products = sorted_products[:limit_value]\n return {\n 'data': limit_products,\n 'other': other_details,\n }\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"top_selling_product_report/report/top_selling_report.py","file_name":"top_selling_report.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"40991052411","text":"from django.db import models\nfrom django.core.validators import MaxValueValidator, MinValueValidator\n\nDAYS = [\n (\"Понедельник\", \"Понедельник\"),\n (\"Вторник\", \"Вторник\"),\n (\"Среда\", \"Среда\"),\n (\"Четверг\", \"Четверг\"),\n (\"Пятница\", \"Пятница\"),\n (\"Суббота\", \"Суббота\")\n]\n\n\nLITERAS = [\n (\"А\", \"А\"),\n (\"Б\", \"Б\"),\n (\"В\", \"В\"),\n (\"Г\", \"Г\"),\n (\"Д\", \"Д\"),\n (\"Е\", \"Е\"),\n (\"Ж\", \"Ж\"),\n (\"З\", \"З\")\n]\n\nGRADES = [\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (5, 5),\n (6, 6),\n (7, 7),\n (8, 8),\n (9, 9),\n (10, 10),\n (11, 11)\n]\n\n\nclass Grades(models.Model):\n number = models.IntegerField(choices=GRADES, verbose_name=\"Класс\")\n letter = models.CharField(max_length=1, choices=LITERAS, verbose_name=\"Литера\")\n\n class Meta:\n ordering = ['number', 'letter']\n verbose_name = \"Класс\"\n verbose_name_plural = \"Классы\"\n\n def __str__(self):\n return str(self.number) + self.letter\n\n\nclass Lessons(models.Model):\n connection = models.ForeignKey(Grades, on_delete=models.CASCADE, verbose_name=\"У какого класса урок\")\n day = models.CharField(max_length=11, choices=DAYS, verbose_name=\"День недели\")\n number = models.IntegerField(verbose_name=\"Номер урока\", validators=[MinValueValidator(0), MaxValueValidator(8)])\n start = models.TimeField(verbose_name=\"Начало урока\")\n end = models.TimeField(verbose_name=\"Конец урока\")\n subject = models.CharField(max_length=50, verbose_name=\"Предмет\")\n classroom = models.IntegerField(verbose_name=\"Кабинет\")\n \n \n class Meta:\n ordering = ['connection', 'day', 'number']\n verbose_name = \"Урок\"\n verbose_name_plural = \"Уроки\"\n\n def __str__(self):\n if self.day != \"Вторник\":\n return str(self.number) + \"й урок в \" + self.day.lower() + \" у \" + str(self.connection)\n else:\n return str(self.number) + \"й урок во \" + self.day.lower() + \" у \" + str(self.connection)","repo_name":"velutb/school-diary","sub_path":"school_diary/timetable/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37416061416","text":"import numpy as np\nimport scipy as sp\nimport scipy.ndimage\n\n\ndef box(img, r):\n \"\"\" O(1) box filter\n img - >= 2d image\n r - radius of box filter\n \"\"\"\n (rows, cols) = img.shape[:2]\n imDst = np.zeros_like(img)\n\n\n tile = [1] * img.ndim\n tile[0] = r\n imCum = np.cumsum(img, 0)\n imDst[0:r+1, :, ...] = imCum[r:2*r+1, :, ...]\n imDst[r+1:rows-r, :, ...] = imCum[2*r+1:rows, :, ...] - imCum[0:rows-2*r-1, :, ...]\n imDst[rows-r:rows, :, ...] = np.tile(imCum[rows-1:rows, :, ...], tile) - imCum[rows-2*r-1:rows-r-1, :, ...]\n\n tile = [1] * img.ndim\n tile[1] = r\n imCum = np.cumsum(imDst, 1)\n imDst[:, 0:r+1, ...] = imCum[:, r:2*r+1, ...]\n imDst[:, r+1:cols-r, ...] = imCum[:, 2*r+1 : cols, ...] - imCum[:, 0 : cols-2*r-1, ...]\n imDst[:, cols-r: cols, ...] = np.tile(imCum[:, cols-1:cols, ...], tile) - imCum[:, cols-2*r-1 : cols-r-1, ...]\n\n return imDst\n\ndef _gf_color(I, p, r, eps, s=None):\n \"\"\" Color guided filter\n I - guide image (rgb)\n p - filtering input (single channel)\n r - window radius\n eps - regularization (roughly, variance of non-edge noise)\n s - subsampling factor for fast guided filter\n \"\"\"\n fullI = I\n fullP = p\n if s is not None:\n I = sp.ndimage.zoom(fullI, [1/s, 1/s, 1], order=1)\n p = sp.ndimage.zoom(fullP, [1/s, 1/s], order=1)\n r = round(r / s)\n\n h, w = p.shape[:2]\n N = box(np.ones((h, w)), r)\n\n mI_r = box(I[:,:,0], r) / N\n mI_g = box(I[:,:,1], r) / N\n mI_b = box(I[:,:,2], r) / N\n\n mP = box(p, r) / N\n\n # mean of I * p\n mIp_r = box(I[:,:,0]*p, r) / N\n mIp_g = box(I[:,:,1]*p, r) / N\n mIp_b = box(I[:,:,2]*p, r) / N\n\n # per-patch covariance of (I, p)\n covIp_r = mIp_r - mI_r * mP\n covIp_g = mIp_g - mI_g * mP\n covIp_b = mIp_b - mI_b * mP\n\n # symmetric covariance matrix of I in each patch:\n # rr rg rb\n # rg gg gb\n # rb gb bb\n var_I_rr = box(I[:,:,0] * I[:,:,0], r) / N - mI_r * mI_r;\n var_I_rg = box(I[:,:,0] * I[:,:,1], r) / N - mI_r * mI_g;\n var_I_rb = box(I[:,:,0] * I[:,:,2], r) / N - mI_r * mI_b;\n\n var_I_gg = box(I[:,:,1] * I[:,:,1], r) / N - mI_g * mI_g;\n var_I_gb = box(I[:,:,1] * I[:,:,2], r) / N - mI_g * mI_b;\n\n var_I_bb = box(I[:,:,2] * I[:,:,2], r) / N - mI_b * mI_b;\n\n a = np.zeros((h, w, 3))\n for i in range(h):\n for j in range(w):\n sig = np.array([\n [var_I_rr[i,j], var_I_rg[i,j], var_I_rb[i,j]],\n [var_I_rg[i,j], var_I_gg[i,j], var_I_gb[i,j]],\n [var_I_rb[i,j], var_I_gb[i,j], var_I_bb[i,j]]\n ])\n covIp = np.array([covIp_r[i,j], covIp_g[i,j], covIp_b[i,j]])\n a[i,j,:] = np.linalg.solve(sig + eps * np.eye(3), covIp)\n\n b = mP - a[:,:,0] * mI_r - a[:,:,1] * mI_g - a[:,:,2] * mI_b\n\n meanA = box(a, r) / N[...,np.newaxis]\n meanB = box(b, r) / N\n\n if s is not None:\n meanA = sp.ndimage.zoom(meanA, [s, s, 1], order=1)\n meanB = sp.ndimage.zoom(meanB, [s, s], order=1)\n\n q = np.sum(meanA * fullI, axis=2) + meanB\n\n return q\n\n\ndef _gf_gray(I, p, r, eps, s=None):\n \"\"\" grayscale (fast) guided filter\n I - guide image (1 channel)\n p - filter input (1 channel)\n r - window raidus\n eps - regularization (roughly, allowable variance of non-edge noise)\n s - subsampling factor for fast guided filter\n \"\"\"\n if s is not None:\n Isub = sp.ndimage.zoom(I, 1/s, order=1)\n Psub = sp.ndimage.zoom(p, 1/s, order=1)\n r = round(r / s)\n else:\n Isub = I\n Psub = p\n\n\n (rows, cols) = Isub.shape\n\n N = box(np.ones([rows, cols]), r)\n\n meanI = box(Isub, r) / N\n meanP = box(Psub, r) / N\n corrI = box(Isub * Isub, r) / N\n corrIp = box(Isub * Psub, r) / N\n varI = corrI - meanI * meanI\n covIp = corrIp - meanI * meanP\n\n\n a = covIp / (varI + eps)\n b = meanP - a * meanI\n\n meanA = box(a, r) / N\n meanB = box(b, r) / N\n\n if s is not None:\n meanA = sp.ndimage.zoom(meanA, s, order=1)\n meanB = sp.ndimage.zoom(meanB, s, order=1)\n\n q = meanA * I + meanB\n return q\n\n\ndef _gf_colorgray(I, p, r, eps, s=None):\n \"\"\" automatically choose color or gray guided filter based on I's shape \"\"\"\n if I.ndim == 2 or I.shape[2] == 1:\n return _gf_gray(I, p, r, eps, s)\n elif I.ndim == 3 and I.shape[2] == 3:\n return _gf_color(I, p, r, eps, s)\n else:\n print(\"Invalid guide dimensions:\", I.shape)\n\n\ndef guided_filter(I, p, r, eps, s=None):\n \"\"\" run a guided filter per-channel on filtering input p\n I - guide image (1 or 3 channel)\n p - filter input (n channel)\n r - window raidus\n eps - regularization (roughly, allowable variance of non-edge noise)\n s - subsampling factor for fast guided filter\n \"\"\"\n if p.ndim == 2:\n p3 = p[:,:,np.newaxis]\n\n out = np.zeros_like(p3)\n for ch in range(p3.shape[2]):\n out[:,:,ch] = _gf_colorgray(I, p3[:,:,ch], r, eps, s)\n return np.squeeze(out) if p.ndim == 2 else out\n\n\ndef test_gf():\n import imageio\n cat = imageio.imread('cat.bmp').astype(np.float32) / 255\n tulips = imageio.imread('tulips.bmp').astype(np.float32) / 255\n\n r = 8\n eps = 0.05\n\n cat_smoothed = guided_filter(cat, cat, r, eps)\n cat_smoothed_s4 = guided_filter(cat, cat, r, eps, s=4)\n\n imageio.imwrite('cat_smoothed.png', cat_smoothed)\n imageio.imwrite('cat_smoothed_s4.png', cat_smoothed_s4)\n\n tulips_smoothed4s = np.zeros_like(tulips)\n for i in range(3):\n tulips_smoothed4s[:,:,i] = guided_filter(tulips, tulips[:,:,i], r, eps, s=4)\n imageio.imwrite('tulips_smoothed4s.png', tulips_smoothed4s)\n\n tulips_smoothed = np.zeros_like(tulips)\n for i in range(3):\n tulips_smoothed[:,:,i] = guided_filter(tulips, tulips[:,:,i], r, eps)\n imageio.imwrite('tulips_smoothed.png', tulips_smoothed)\n","repo_name":"swehrwein/python-guided-filter","sub_path":"gf.py","file_name":"gf.py","file_ext":"py","file_size_in_byte":5903,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"52"} +{"seq_id":"71464359844","text":"from django.contrib.auth.models import User\nfrom django.test import Client, TestCase\nfrom django.core.urlresolvers import resolve, reverse\n\nfrom ceeq.apps.projects.forms import ProjectForm, ProjectNewForm\nfrom ceeq.apps.projects.models import Project\n\n\nclass ProjectTemplateTests(TestCase):\n def setUp(self):\n self.client = Client()\n self.project = Project.objects.create(\n name='Test Project',\n jira_name='Test JIRA Name',\n jira_version='All Versions',\n score=5\n )\n self.response = self.client.get(reverse('projects'))\n\n def test_projects_view_return_status_code_200(self):\n self.assertEqual(self.response.status_code, 200)\n\n def test_projects_view_contains_correct_url_to_project(self):\n self.assertContains(self.response, reverse('project_detail',\n args=[str(self.project.id)]))\n\n def test_projects_view_contains_correct_url_to_defects_density(self):\n self.assertContains(self.response, reverse('project_defects_density',\n args=[str(self.project.id)]))\n\n def test_projects_view_contains_correct_url_to_update_score(self):\n self.assertContains(self.response, reverse('project_update_scores',\n args=[str(self.project.id)]))\n\n def test_projects_view_contains_correct_url_to_update_all_scores(self):\n self.assertContains(self.response, reverse('project_update_scores',\n args=[str(1000000)]))\n\n def test_projects_view_contains_correct_url_to_log_all_scores(self):\n self.assertContains(self.response, reverse('defects_density_log',\n args=[str(1000000)]))\n\n def test_projects_view_contains_correct_url_to_jira(self):\n self.assertContains(self.response, 'http://jira.west.com/browse/' + self.project.jira_name)\n\n\nclass ProjectFormTemplatesTests(TestCase):\n def setUp(self):\n self.client = Client()\n self.user_account_super_user = {\n 'username': 'superUserName',\n 'password': 'superUserPassword',\n 'email': ''\n }\n self.user_normaluser = User.objects.create_superuser(\n username=self.user_account_super_user['username'],\n password=self.user_account_super_user['password'],\n email=self.user_account_super_user['email']\n )\n self.client.login(\n username=self.user_account_super_user['username'],\n password=self.user_account_super_user['password']\n )\n self.project = Project.objects.create(\n name='Test Project',\n jira_name='Test JIRA Name',\n jira_version='All Versions',\n score=5\n )\n\n def test_project_detail_contains_form(self):\n\n response = self.client.get(reverse('project_detail',\n args=[str(self.project.id)]),\n follow=True)\n form = ProjectForm()\n for field in form:\n self.assertContains(response, field.html_name)\n\n def test_project_new_contains_form(self):\n response = self.client.get(reverse('project_new'),\n follow=True)\n form = ProjectNewForm()\n for field in form:\n self.assertContains(response, field.html_name)","repo_name":"jlpcri/ceeq","sub_path":"ceeq/apps/projects/tests/test_project_templates.py","file_name":"test_project_templates.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36166091044","text":"#!/usr/bin/env python\n\nimport os\nimport webapp2\nimport jinja2\nimport json\nimport logging\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\n\nfrom treebisect import BisectBT\n\n####################\ndef GetBTDesc(tree):\n #HACK overwriting id: \"tree\" id is always encoded as -1\n t = json.loads(tree.nodes)[\"nodes\"][\"tree\"]\n t[\"id\"] = str(tree.key().id())\n return t\n\ndef GetBTJson(tree):\n t = json.loads(tree.nodes)\n t[\"id\"] = str(tree.key().id())\n return t\n\n####################\ndef ListBT(type=None):\n tlist = BisectionTree.all().filter('is_public =', True).fetch(limit=100)\n return [GetBTDesc(t) for t in tlist]\n\ndef AddBT(user, req):\n userid = user.user_id() if user else None\n nodes = req.body\n is_public = True if req.get('is_public') is '' else False\n tree = BisectionTree(userid=userid, is_public=is_public, nodes=nodes)\n tree.put()\n tree_id = tree.key().id()\n logging.info('AddBT:%s', ','.join(map(str,(userid,is_public,tree_id))))\n return tree_id\n\ndef EditBT(req, tree_id):\n tree = BisectionTree.get_by_id(tree_id)\n if tree:\n if req.get('is_public') is not '':\n tree.is_public = True\n tree.nodes = req.body\n tree.put()\n return tree.key().id()\n else:\n return None\n\ndef DelBT(req, tree_id):\n tree = BisectionTree.get_by_id(tree_id)\n if tree:\n tree.delete()\n return tree_id\n else:\n return None\n\nclass BisectionTree(db.Model):\n userid = db.StringProperty(required=False)\n is_public = db.BooleanProperty(required=True)\n nodes = db.TextProperty(required=True)\n\n####################\ndef UserCanGetBT(user, tree_id):\n tree = BisectionTree.get_by_id(tree_id)\n if not tree:\n return None\n elif tree.is_public :\n return tree\n elif user and tree.userid is user.user_id() :\n return tree\n else:\n return None\n\ndef UserCanAddBT(user, tree_id=0):\n return True\n\ndef UserCanEditBT(user, tree_id):\n tree = BisectionTree.get_by_id(tree_id)\n logging.info(\"UserCanEditBT: U: %s T: %s\", user, tree.userid)\n if tree and tree.userid is None:\n return tree\n elif tree and user and tree.userid is user.user_id():\n return tree\n else:\n return None\n####################\ndef GetUserData():\n u = users.get_current_user()\n if u: u_url = users.create_logout_url(\"/tree\")\n else: u_url = users.create_login_url(\"/tree\")\n return (u, u_url)\n\ndef RenderTreeTmpl(u,u_url,tree,t_list):\n sep = (',',':')\n treelist = {\"desc\":\"Newest Bisections\",\"tlist\":t_list}\n return tree_tmpl.render({\n \"thistree\": json.dumps(tree,separators=sep),\n \"treelist\": json.dumps(treelist,separators=sep),\n \"user\": u.nickname() if u else None,\n \"uurl\": u_url\n })\n\ndef RenderTreeLsTmpl(u,u_url,tree_list):\n sep = (',',':')\n treelist = {\"desc\":\"Drag-n-Drop Log files to triage\",\"tlist\":tree_list}\n return tree_ls_tmpl.render({\n \"treelist\": json.dumps(treelist,separators=sep),\n \"user\": u.nickname() if u else None,\n \"uurl\": u_url\n })\n\n\n####################\nclass TreeListHandler(webapp2.RequestHandler):\n def get(self, tree_type):\n u,u_url = GetUserData()\n self.response.out.write(RenderTreeLsTmpl(u,u_url,ListBT(tree_type)))\n\n\nclass NewTreeHandler(webapp2.RequestHandler):\n def get(self):\n u,u_url = GetUserData()\n self.response.out.write(RenderTreeTmpl(u,u_url,None,ListBT()))\n\nclass TreeHandler(webapp2.RequestHandler):\n def get(self, tree_id):\n u,u_url = GetUserData()\n tree = UserCanGetBT(u, int(tree_id))\n if tree :\n self.response.out.write(RenderTreeTmpl(u,u_url,GetBTJson(tree),ListBT()))\n else:\n self.response.status_int = 401\n\n def put(self, tree_id):\n u = users.get_current_user()\n if UserCanEditBT(u, int(tree_id)):\n status = EditBT(self.request, int(tree_id))\n self.response.status_int = 202 if status else 404\n self.response.write(json.dumps(status))\n else:\n self.response.status_int = 403\n\n def post(self, tree_id):\n u,u_url = GetUserData()\n status = None\n if UserCanAddBT(u):\n tree_id = AddBT(u, self.request)\n self.response.status_int = 202\n self.response.write(json.dumps({\"id\":str(tree_id)}))\n else:\n self.response.status_int = 401\n\n def delete(self, tree_id):\n u = users.get_current_user()\n if UserCanEditBT(u, int(tree_id)):\n status = DelBT(self.request, int(tree_id))\n self.response.status_int = 202 if status else 404\n self.response.write(json.dumps(status))\n\nclass BisectHandler(webapp2.RequestHandler):\n def post(self, tree_id):\n u = users.get_current_user()\n tree = UserCanGetBT(u, int(tree_id))\n if tree :\n text = self.request.body\n result = BisectBT(json.loads(tree.nodes), text)\n self.response.write(json.dumps(result))\n else:\n self.response.status_int = 403\n\napp = webapp2.WSGIApplication([\n (r'/tree/(\\w*)', TreeHandler),\n (r'/ls/(\\w*)', TreeListHandler),\n (r'/bisect/(\\w+)',BisectHandler),\n ('/', NewTreeHandler),\n ], debug=True)\n\njenv = jinja2.Environment(loader=jinja2.FileSystemLoader(\n os.path.join(os.path.dirname(__file__), 'assets', 'tmpl')))\n\ntree_tmpl = jenv.get_template('first-banner.html')\n\ntree_ls_tmpl = jenv.get_template('tree-ls.html')\n\ndef main():\n logging.getLogger().setLevel(logging.DEBUG)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"saxena/bisect","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72502010724","text":"from itertools import permutations\n\ndef stringsRearrangement(inputArray):\n m = make_map(inputArray)\n\n perm = list(permutations(inputArray))\n\n for p in perm:\n b = True\n\n for j in range(len(p) - 1):\n if p[j + 1] not in m[p[j]]:\n b = False\n break\n\n if b == True:\n return True\n\n return False\n\n\n\ndef make_map(a):\n d = {}\n\n for j in a:\n d[j] = []\n\n for k in a:\n b = 0\n\n if j != k:\n for m in range(len(j)):\n if j[m] != k[m]:\n b += 1\n\n if b == 1:\n d[j].append(k)\n\n return d\n","repo_name":"kanglicheng/codefights","sub_path":"ArcadeUniverse/Intro/ThroughTheFog/StringsRearrangement.py","file_name":"StringsRearrangement.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18537794745","text":"# 싸이버개강총회 S2\nimport sys\n\ninput = sys.stdin.readline\ns, e, q = input().split()\n# 입력한 시간에서 :빼고 int로 형변환\ns = int(s[:2] + s[3:])\ne = int(e[:2] + e[3:])\nq = int(q[:2] + q[3:])\narr = set()\ncnt = 0\nwhile True:\n try:\n time, name = input().split()\n time = int(time[:2] + time[3:])\n if time <= s: # 시작전에 왔으면\n arr.add(name) # 입장\n elif e <= time <= q and name in arr: # 끝나고 스트리밍 끝날때까지, 입장한 사람이면\n arr.remove(name) # 퇴장\n cnt += 1 # 사람수 +1\n except:\n break\nprint(cnt)\n","repo_name":"kkm0406/AlgorithmBOJ","sub_path":"구현/19583.py","file_name":"19583.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"86587854273","text":"import pygame, random, os, json, requests, urllib, shutil, ast, math, base64, datetime\n# TODO:\n# Create 4 new sprites for item shop\n# fix release notes\n# fix home run not showing in play (fixed)\n# add new hit display to derby (done)\n# add buck collection after games (done)\n\nfolderpath = os.getcwd()\nversion = \"1.3\"\n# make sure version is the same as github tag\nITEM_SHOP_ENABLED = False\n# locks shop button and buck collection (except from bp cause it might ruin saves)\n\nforplayingscoring = 13\nderbyhomerunsscoring = 3.5\nhomerunsscoring = 2.8\nsinglesscoring = 1.8\ndoublesscoring = 2.7\nderbyhomerunsbucks = 5.2\nhomerunsbucks = 8.8\n\n\ndef weeks():\n\tyear, week, day = datetime.date.today().isocalendar(); week += 4\n\tfor i in range(year - 2022): week += 52\n\tfor i in range(day - 6): week += 1\n\tfor i in range(year - 2022): week += math.floor((365 / 7 - 52) * (round(year - 2020, 0) / 4))\n\treturn str(week).replace(\".0\", \"\")\n\n\n\n\ndef give(asset, list, level, unlocktier):\n\tif level >= unlocktier: \n\t\tif asset not in list: list.append(asset)\n\ndef givebucks(list, level, unlocktier, bucks, togive):\n\tif level >= unlocktier:\n\t\tif unlocktier not in list:\n\t\t\tlist.append(unlocktier)\n\t\t\tbucks += togive\n\treturn bucks\n\t\t\t\ndef buy(asset, bucks, cost, list):\n\tif bucks >= cost:\n\t\tif asset not in list: \n\t\t\tlist.append(asset)\n\t\t\treturn bucks-cost, list\n\treturn bucks, list\n\t\n\n\n\ndef opensave():\n\twith open(folderpath + \"\\\\gamefiles\\\\save.txt\", \"r\") as save:\n\t\tdata = save.read()\n\t\tsave.close()\n\tif data == [0, 0, 0] or data == \"[0, 0, 0]\":\n\t\tdata = [0, 0, 0, 0, 0, \"['ball']\", \"['bat']\", \"['field']\", \"[0]\"]\n\telif data != \"\" and data != None and data != \"b'WzAsIDAsIDAsIDBd'\":\n\t\tdata = data.strip(\"b''\")\n\t\twhile len(data)%4 != 0: data += \"=\"\n\t\tdata = base64.b64decode(data)\n\t\tdata = str(data, \"utf-8\")\n\t\tdata = ast.literal_eval(data)\n\telse: data = [0, 0, 0, 0, 0, \"['ball']\", \"['bat']\", \"['field']\", \"[0]\"]\n\treturn data\n\n\n\ndef save(list):\n\twith open(folderpath + \"\\\\gamefiles\\\\save.txt\", \"w\") as save:\n\t\tdata = str([ball, bat, field, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\t\tdata = base64.b64encode(data.encode(\"utf-8\"))\n\t\tdata = str(data, \"utf-8\")\n\t\tsave.write(data)\n\t\tsave.close()\n\treturn\n\n\n\nratelimit = False\nball, bat, field, xp, bucks, balllist, batlist, fieldlist, buckslist = opensave()\n\nballlist = ast.literal_eval(str(balllist))\nbatlist = ast.literal_eval(str(batlist))\nfieldlist = ast.literal_eval(str(fieldlist))\nbuckslist = ast.literal_eval(str(buckslist))\n\nif random.randint(0, 1) == 1: ABK = \"+\" + str(round(random.uniform(1.06, 4.24), 2)) + \"%\"\nelse: ABK = \"-\" + str(round(random.uniform(2.34, 0.16), 2)) + \"%\"\n\n\n\nsplashmessage = random.choice([\n\t\t\t\t\t\t\t\t#\"Battle Pass soon!\",\n\t\t\t\t\t\t\t\t\"Now on PS4!\",\n\t\t\t\t\t\t\t\t#\"Better than real baseball!\",\n\t\t\t\t\t\t\t\tweeks() + \" weeks!\",\n\t\t\t\t\t\t\t\t\"sponsored by Bayloadgs!\",\n\t\t\t\t\t\t\t\t\"Why are you playing this?\",\n\t\t\t\t\t\t\t\t\"ABK Stock \" + ABK,\n\t\t\t\t\t\t\t\t#\"\"\n\t\t\t\t\t\t\t\t#\"\"\n\t\t\t\t\t\t\t])\n\n\n\ninternet = True\nprint(\"cwd = \" + folderpath + \" W = \" + weeks())\n\n\ntry: os.remove(folderpath + \"\\\\Baseball.Game.zip\")\nexcept: pass\ntry: os.remove(folderpath + \"\\\\gamefiles\\\\Old_Baseball_game.exe\")\nexcept: pass\ntry: os.remove(folderpath + \"\\\\gamefiles\\\\customballs.txt\")\nexcept: pass\ntry: os.remove(folderpath + \"\\\\gamefiles\\\\custombats.txt\")\nexcept: pass\ntry: os.remove(folderpath + \"\\\\gamefiles\\\\customfields.txt\")\nexcept: pass\n\n# check updates\n\ntry: \n\tresponse = requests.get(\"https://api.github.com/repos/wowbaseballgamesocool/baseballgame/releases\")\n\tlatestversion = response.json()[0][\"tag_name\"].strip(\"v\")\n\tif latestversion == \"1.2.1\": raise Exception(\"Github returned wrong version\")\n\twith open(folderpath + \"/gamefiles/cache.txt\", \"w\") as file:\n\t\tfile.write(str(response.json())); file.close()\nexcept Exception as e:\n\tif \"Max retries exceeded with url\" in str(e):\n\t\tprint(\"Could not check for updated version (check internet connection) [Max retries exceeded]\")\n\telif str(e) == \"'tag_name'\" or str(e) == \"0\":\n\t\tprint(\"Could not check for updated version\\nError: API rate limit exceeded (Try again later)\")\n\t\tratelimit = True\t\n\telse: \n\t\tprint(\"Could not check for updated version\\nError: \" + str(e))\n\t\n\n\tinternet = False\nif internet == True:\n\tif str(version) != str(latestversion):\n\t\tfrom time import sleep\n\t\tprint(\"\\nNew update \" + str(version) + \" -> \" + str(latestversion))\n\t\tsleep(1.5)\n\t\tprint(\"downloading update...\")\n\t\t\n\t\turl = \"https://github.com/wowbaseballgamesocool/baseballgame/releases/download/\" + str(latestversion) + \"//Baseball.Game.zip\"\n\t\ttry:\n\t\t\turllib.request.urlretrieve(url, filename = folderpath + r\"//Baseball.Game.zip\")\n\t\texcept ConnectionAbortedError: raise Exception(\"Don't change your internet while file is downloading\")\n\t\tfrom zipfile import ZipFile\n\t\twith ZipFile(folderpath + \"\\\\Baseball.Game.zip\", 'r') as zip_ref:\n\t\t\tos.rename(folderpath + \"\\\\Baseball_game.exe\", folderpath + \"\\\\gamefiles\\\\Old_Baseball_game.exe\")\n\t\t\t\n\t\t\tzip_ref.extractall(folderpath + \"\\\\gamefiles\\\\updateunpack\")\n\t\t\tzip_ref.close()\n\t\tos.remove(folderpath + \"\\\\Baseball.Game.zip\")\n\t\t\n\t\t\n\t\tos.rename(folderpath + \"\\\\gamefiles\\\\updateunpack\\\\Baseball_game.exe\", folderpath + \"\\\\Baseball_game.exe\")\n\t\tif os.path.exists(folderpath + \"\\\\gamefiles\\\\save.txt\") == False:\n\t\t\tos.rename(folderpath + \"\\\\gamefiles\\\\updateunpack\\\\gamefiles\\\\save.txt\", folderpath + \"\\\\gamefiles\\\\save.txt\")\n\n\n\t\t#shutil.move(folderpath + \"\\\\gamefiles\\\\updateunpack\\\\gamefiles\\\\audio\", folderpath + \"\\\\gamefiles\\\\audio\")\n\t\t#os.rename(folderpath + \"\\\\gamefiles\\\\updateunpack\\\\gamefiles\\\\assets\", folderpath + \"\\\\gamefiles\\\\assets\")\n\t\tshutil.rmtree(folderpath + \"\\\\gamefiles\\\\audio\")\n\t\t\n\t\tshutil.move(folderpath + \"\\\\gamefiles\\\\updateunpack\\\\gamefiles\\\\audio\", folderpath + \"\\\\gamefiles\")\n\n\t\tshutil.rmtree(folderpath + \"\\\\gamefiles\\\\assets\")\n\n\t\tshutil.move(folderpath + \"\\\\gamefiles\\\\updateunpack\\\\gamefiles\\\\assets\", folderpath + \"\\\\gamefiles\")\n\t\t\n\t\t\n\t\t#os.remove(folderpath + \"\\\\gamefiles\\\\Old_Baseball_game.exe\")\n\t\tos.startfile(folderpath + \"\\\\Baseball_game.exe\")\n\t\texit()\n\telse: \n\t\t\n\t\tprint(\"playing on latest version (\" + str(version) + \")\")\n\n\n\nif os.path.exists(folderpath + \"\\\\gamefiles\\\\cache.txt\") == False:\n\tos.mkfile(folderpath + \"\\\\gamefiles\\\\cache.txt\")\nelse:\n\twith open(folderpath + \"\\\\gamefiles\\\\cache.txt\", \"r\") as cachefile:\n\t\tresponse = str(cachefile.read())\n\t\tcachefile.close()\nwith open(folderpath + \"\\\\gamefiles\\\\hplay.json\", \"r\") as hjson:\n\tfile = hjson.read()\n\thjson.close()\njsonfile = json.loads(file)\nhighhomeruns = int(jsonfile[\"play\"][\"homeruns\"])\nhighsingles = int(jsonfile[\"play\"][\"singles\"])\nhighdoubles = int(jsonfile[\"play\"][\"doubles\"])\nhighruns = int(jsonfile[\"play\"][\"runs\"])\n\nwith open(folderpath + \"\\\\gamefiles\\\\hderby.json\", \"r\") as hjson:\n\tfile = hjson.read()\n\thjson.close()\njsonfile = json.loads(file)\nhighderbyhomeruns = int(jsonfile[\"derby\"][\"homeruns\"])\n\nwith open(folderpath + \"\\\\gamefiles\\\\settings.json\", \"r\") as settings:\n\tfile = settings.read()\n\tsettings.close()\njsonfile = json.loads(file)\nvolume = int(jsonfile[\"settings\"][\"volume\"])\n\n\ndata = opensave()\n\n\nballlistnumber = data[0]\nbatlistnumber = data[1]\nfieldlistnumber = data[2]\nxp = data[3]\n\n\n\ntry:\n\tballlist[balllistnumber]\n\tbatlist[batlistnumber]\n\tfieldlist[fieldlistnumber]\nexcept: \n\tballlistnumber = 0\n\tbatlistnumber = 0\n\tfieldlistnumber = 0\n\n\ngrey = (50, 50, 50)\nwhite = (255, 255, 255)\nyellow = (215, 215, 102)\nblack = (0, 0, 0)\nred = (213, 50, 80)\ngreen = (0, 255, 0)\nblue = (50, 153, 213)\ndis_width = 600\ndis_height = 400\n\npygame.init()\nscreen = pygame.display.set_mode((dis_width, dis_height))\nreleasenotescroll = 0\n#message = \"\"; startticks = 2; time = 0\nfpslist = []\nsplashsize = 35\nsplashsizemode, page, shoppage = 1, 1, 1\nfps, averagefps = 0, 0\naltaltsplashmessage = \"\"\npygame.display.set_caption('Baseball Game')\nalreadyrendered = False\n\n# def refresh_sprites(): \n\nball_sprite = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha()\nball_sprite = pygame.transform.scale(ball_sprite, (40, 40)) #size of ball\nmenubg_sprite = pygame.image.load('gamefiles/assets/menubg.png').convert_alpha()\nout0_sprite = pygame.image.load('gamefiles/assets/outs/0outs.png').convert_alpha()\nout0_sprite = pygame.transform.scale(out0_sprite, (95, 30)) #size of text\nout1_sprite = pygame.image.load('gamefiles/assets/outs/1outs.png').convert_alpha()\nout1_sprite = pygame.transform.scale(out1_sprite, (95, 30)) #size of text\nout2_sprite = pygame.image.load('gamefiles/assets/outs/2outs.png').convert_alpha()\nout2_sprite = pygame.transform.scale(out2_sprite, (95, 30)) #size of text\nout3_sprite = pygame.image.load('gamefiles/assets/outs/3outs.png').convert_alpha()\nout3_sprite = pygame.transform.scale(out3_sprite, (95, 30)) #size of text\noptionsmenu_sprite = pygame.image.load('gamefiles/assets/optionsmenu.png').convert_alpha()\nassetsback_sprite = pygame.image.load('gamefiles/assets/assetsback.png').convert_alpha()\nback_sprite = pygame.image.load('gamefiles/assets/back.png').convert_alpha()\nreleasenotesbg = pygame.image.load('gamefiles/assets/releasenotesbg.png').convert_alpha()\nbattlepassboxpast = pygame.image.load('gamefiles/assets/battlepassboxpast.png').convert_alpha()\nbattlepassboxpresent = pygame.image.load('gamefiles/assets/battlepassboxpresent.png').convert_alpha()\nbattlepassboxfuture = pygame.image.load('gamefiles/assets/battlepassboxfuture.png').convert_alpha()\nxpicon = pygame.image.load('gamefiles/assets/xpicon.png').convert_alpha()\nbucksicon = pygame.image.load('gamefiles/assets/bucks.png').convert_alpha()\nbucksicon100 = pygame.image.load('gamefiles/assets/bucks100.png').convert_alpha()\nbucksicon75 = pygame.image.load('gamefiles/assets/bucks75.png').convert_alpha()\nright_arrow = pygame.image.load('gamefiles/assets/arrow.png').convert_alpha()\nbuy1 = pygame.image.load('gamefiles/assets/buy1.png').convert_alpha()\nbuy2 = pygame.image.load('gamefiles/assets/buy2.png').convert_alpha()\nleft_arrow = pygame.transform.rotate(right_arrow, 180)\nfield_sprite = pygame.image.load('gamefiles/assets/fields/' + fieldlist[fieldlistnumber] + '.png').convert_alpha()\nfield_sprite = pygame.transform.scale(field_sprite, (620, 420)) #size of field\nshopbox = pygame.transform.scale(battlepassboxfuture, (220, 180))\n\nfont = pygame.font.SysFont(None, 40)\ndef message_to_screen(msg, color, size, x, y):\n\n\tscreen_text = font.render(msg, True, color)\n\tscreen.blit(screen_text, [x, y])\n\n\nmed_font = pygame.font.SysFont(\"Mochiy Pop One\", 30)\nfont_style = pygame.font.SysFont(\"Mochiy Pop One\", 50)\nsmall_font = pygame.font.SysFont(\"Mochiy Pop One\", 20)\nbig_font = pygame.font.SysFont(\"Mochiy Pop One\", 40)\nverybig_font = pygame.font.SysFont(\"Mochiy Pop One\", 70)\n#mesg = font_style.render(\"\", True, red)\nspace2swing = small_font.render(\"Press space to swing\", True, black)\n#menuplace = 1\nstart, openreleasenotes = False, False\nclock = pygame.time.Clock()\nupdateevent = pygame.USEREVENT + 1\nsecondevent = pygame.USEREVENT + 2\npygame.time.set_timer(secondevent, 1000)\npygame.time.set_timer(updateevent, 750)\n\n\n\n\n\n\n\n\n\n\n\nwhile True:\n\ttry:\n\t\tlevel = math.floor(xp / 100) + 1\n\t\tgive(\"snowfield\", fieldlist, level, 2)\n\t\tgive(\"axebat\", batlist, level, 4)\n\t\tgive(\"sandfield\", fieldlist, level, 7)\n\t\tgive(\"coolbat\", batlist, level, 15)\n\t\tgive(\"hammerbat\", batlist, level, 19)\n\t\tgive(\"christmasball\", balllist, level, 10)\n\t\tgive(\"starball\", balllist, level, 17)\n\t\tgive(\"hockeybat\", batlist, level, 12)\n\t\tgive(\"waterfield\", fieldlist, level, 14)\n\t\tgive(\"roseball\", balllist, level, 6)\n\t\tif ITEM_SHOP_ENABLED:\n\t\t\tbucks = givebucks(buckslist, level, 16, bucks, 100)\n\t\t\tbucks = givebucks(buckslist, level, 11, bucks, 100)\n\t\t\tbucks = givebucks(buckslist, level, 9, bucks, 75)\n\t\t\tbucks = givebucks(buckslist, level, 8, bucks, 100)\n\t\tsave([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\texcept: pass\n\tpygame.mouse.set_visible(True) \n\tpygame.display.set_caption('Baseball Game -- Menu')\n\tmesg = \"\"\n\tendtimer,outs = 0, 0\n\tball_sprite = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha()\n\tball_sprite = pygame.transform.scale(ball_sprite, (40, 40)) #size of ball\n\tbat_sprite = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\tbat_sprite = pygame.transform.scale(bat_sprite, (20, 70)) #size of bat old: 15, 70\n\tasset = True\n\tbattlepass = True\n\toptionsmenu = False\n\tstartderby = False\n\tstartplay = False\n\thit = False\n\tfirstswing = True\n\tstrikes, runs, runner, singles, doubles, homeruns, hit_type = 0, 0, 0, 0, 0, 0, 0\n\tstart = False\n\tballx = 265\n\tbally = 100\n\tbatx = 260\n\tbaty = 310\n\twhile start == False:\n\t\t\n\n\n\n\t\tscreen.blit(menubg_sprite, (0, 0))\n\t\t#splashscreen\n\t\tif openreleasenotes == False:\n\t\t\tif \"*\" in splashmessage: altaltsplashmessage = splashmessage\n\t\t\tif splashsize >= 32: splashsizemode = 0\n\t\t\tif splashsize <= 25: splashsizemode = 1\n\t\t\tif splashsizemode == 0: splashsize -= 0.02\n\t\t\tif splashsizemode == 1: splashsize += 0.02\n\t\t\tsplash_font = pygame.font.SysFont(\"Mochiy Pop One\", int(round(splashsize, 0))) # 45\n\t\t\tif \"*\" in altaltsplashmessage:\n\t\t\t\tsplashmessage, altsplashmessage = altaltsplashmessage.split(\"*\")\n\t\t\t\t\n\t\t\t\taltsplash_text = splash_font.render(altsplashmessage, True, yellow)\n\t\t\t\taltsplash_text = pygame.transform.rotate(altsplash_text, 345)\n\t\t\t\tscreen.blit(altsplash_text, [310, 65])\n\t\t\t\n\t\t\t\n\t\t\tsplash_text = splash_font.render(splashmessage, True, yellow)\n\t\t\t\n\t\t\tsplash_text = pygame.transform.rotate(splash_text, 345)\n\t\t\t#pygame.transform.scale(bat_sprite, (20, 70))\n\t\t\tscreen.blit(splash_text, [320, 45])\n\n\n\t\t# print(alreadyrendered)\n\t\telif openreleasenotes:\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tif internet or response != \"\":\n\t\t\t\t\n\t\t\t\tpushdownupdateinfo = 0\n\t\t\t\tupdatelinecount = 0\n\t\t\t\tscreen.blit(releasenotesbg, [0, 0])\n\t\t\t\tscreen.blit(releasenotesbg, [0, 0])\n\t\t\t\t# if True:\n\t\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tresponse = ast.literal_eval(response)\n\t\t\t\texcept: pass\n\t\t\t\t\n\t\t\t\tfor i in range(15):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tupdatelinecount = 0\n\t\t\t\t\t\tupdatetitlething___ = response[i][\"name\"] + \" -- \" + response[i][\"tag_name\"]\n\t\t\t\t\t\tif str(response[i][\"tag_name\"]) == str(version): \n\n\t\t\t\t\t\t\tupdatetitlething___ += \" [ Latest ]\"\n\n\t\t\t\t\t\tupdateinfotitle = med_font.render(updatetitlething___, True, grey)\n\t\t\t\t\t\tupdateinfo = small_font.render(response[i][\"body\"], True, black)\n\t\t\t\t\t\tif dis_height - 330 + pushdownupdateinfo + releasenotescroll < 335 and dis_height - 330 + pushdownupdateinfo + releasenotescroll > 30:\n\t\t\t\t\t\t\tscreen.blit(updateinfotitle, [dis_width - 520, dis_height - 330 + pushdownupdateinfo + releasenotescroll])\n\t\t\t\t\t\tif \"\\n\" not in str(response[i][\"body\"]) and dis_height - 300 + pushdownupdateinfo + releasenotescroll < 335 and dis_height - 300 + pushdownupdateinfo + releasenotescroll > 30:\n\t\t\t\t\t\t\tscreen.blit(updateinfo, [dis_width / 2 - 250, dis_height - 300 + pushdownupdateinfo + releasenotescroll])\n\t\t\t\t\t\t\tpushdownupdateinfo += 30\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\ta = str(response[i][\"body\"])\n\t\t\t\t\t\t\t\tb = r\"\\r\\n\"\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tfor b in a:\n\t\t\t\t\t\t\t\t\t\tc = a.split(\"\\r\\n\")\n\t\t\t\t\t\t\t\t\t\td = c[updatelinecount]\n\t\t\t\t\t\t\t\t\t\td = small_font.render(d, True, black)\n\t\t\t\t\t\t\t\t\t\tif dis_height - 300 + pushdownupdateinfo + releasenotescroll < 335 and dis_height - 300 + pushdownupdateinfo + releasenotescroll > 30:\n\t\t\t\t\t\t\t\t\t\t\tscreen.blit(d, [dis_width / 2 - 250, dis_height - 290 + pushdownupdateinfo + releasenotescroll])\n\t\t\t\t\t\t\t\t\t\tpushdownupdateinfo += 20\n\t\t\t\t\t\t\t\t\t\tupdatelinecount += 1\n\t\t\t\t\t\t\t\texcept: pass\n\t\t\t\t\t\tpushdownupdateinfo += 55\n\t\t\t\t\t\t# alreadyrendered = True\n\t\t\t\t\texcept: pass\n\t\t\t\t\tpygame.display.update()\n\n\t\t\t\n\t\t\t\t\n\t\t\tif openreleasenotes:\n\t\t\t\t\n\t\t\t\tfor event in pygame.event.get():\n\t\t\t\t\tif event.type == pygame.QUIT: exit()\n\t\t\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif event.button >= 4:\n\t\t\t\t\t\t\talreadyrendered = False\n\t\t\t\t\t\t\tif \".0\" in str(event.button / 2):\n\t\t\t\t\t\t\t\tif releasenotescroll <= 50: releasenotescroll += 30\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif releasenotescroll >= -950: releasenotescroll -= 30\n\t\t\t\t\t\telse: openreleasenotes = False; alreadyrendered = False\n\t\t\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\t\t\topenreleasenotes = False\n\t\t\t\t\t\talreadyrendered = False\n\n\t\t\t\tpygame.display.update()\n\t\t\t\t\t\n\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\n\t\n\t\t\telse:\t# might have to move this error text if stats/settings were to go here\n\t\t\t\tupdateinfo = small_font.render(\"Try again later\", True, black)\n\t\t\t\tscreen.blit(updateinfo, [20, dis_height - 110])\n\n\n\n\n\t\t\n\t\tplayrect = pygame.Rect(210, dis_height - 170, 175, 45)\n\t\tderbyrect = pygame.Rect(220, dis_height - 125, 155, 40)\n\t\toptionsrect = pygame.Rect(225, dis_height - 85, 145, 40)\n\t\texitrect = pygame.Rect(245, dis_height - 45, 100, 25)\n\t\treleaserect = pygame.Rect(30, dis_height - 100, 100, 50)\n\n\n\n\n\t\t# if random.randint(1, 2) == 1:\n\t\t\t# pygame.draw.rect(screen,red,(playrect))\n\t\t\t# pygame.draw.rect(screen,red,(derbyrect))\n\t\t\t# pygame.draw.rect(screen,red,(optionsrect))\n\t\t\t# pygame.draw.rect(screen,red,(exitrect))\n\t\t\t# pygame.draw.rect(screen,red,(releaserect))\n\t\t\n\t\tfor event in pygame.event.get():\n\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t\n\t\t\t\tif exitrect.collidepoint(event.pos): exit()\n\t\t\t\tif optionsrect.collidepoint(event.pos):\n\t\t\t\t\t\n\t\t\t\t\tpygame.display.set_caption('Baseball Game -- Options')\n\t\t\t\t\t\n\t\t\t\t\tstart = True\n\t\t\t\t\toptionsmenu = True\n\t\t\t\tif derbyrect.collidepoint(event.pos):\n\t\t\t\t\t\n\t\t\t\t\tpygame.display.set_caption('Baseball Game -- Derby')\n\t\t\t\t\t\n\t\t\t\t\tstart_ticks = pygame.time.get_ticks()\n\t\t\t\t\tstart = True\n\t\t\t\t\tstartderby = True\n\t\t\t\tif playrect.collidepoint(event.pos):\n\t\t\t\t\t\n\t\t\t\t\tpygame.display.set_caption('Baseball Game -- Play')\n\t\t\t\t\tstart_ticks = pygame.time.get_ticks()\n\t\t\t\t\tstart = True\n\t\t\t\t\tstartplay = True\n\n\t\t\t\tif releaserect.collidepoint(event.pos):\n\t\t\t\t\topenreleasenotes = True\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\n\t\t\tif event.type == pygame.QUIT: exit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\texit()\n\t\tpygame.display.update()\n\twhile startplay == True:\n\n\n\t\t\n\n\t\tpygame.mouse.set_visible(False) #########\n\t\tscreen.blit(field_sprite, (0, 0))\n\t\t\n\t\tscreen.blit(space2swing, [dis_width / 6 + 260, dis_height / 3 + 250])\n\t\tscreen.blit(ball_sprite, (ballx, bally))\n\t\tscreen.blit(bat_sprite, (batx, baty))\n\t\tif mesg != \"\":\n\t\t\tmessage_to_screen(str(mesg), (0, 0, 0), \"sus\", 5, 340)\n\n\n\n\n\t\tif outs == 0:\n\t\t\tscreen.blit(out0_sprite, (0, 370))\n\t\telif outs == 1:\n\t\t\tscreen.blit(out1_sprite, (0, 370))\n\t\telif outs == 2:\n\t\t\tscreen.blit(out2_sprite, (0, 370))\n\t\twhile outs == 3:\n\t\t\tscreen.blit(field_sprite, (0, 0))\n\t\t\tscreen.blit(out3_sprite, (0, 370))\n\t\t\tendtimer += 1\n\t\t\tif endtimer >= 775: # 4500\n\t\t\t\txp += math.floor(int(singles) * singlesscoring)\n\t\t\t\txp += math.floor(int(doubles) * doublesscoring)\n\t\t\t\txp += math.floor(int(homeruns) * homerunsscoring)\n\t\t\t\txp += forplayingscoring\n\t\t\t\tif ITEM_SHOP_ENABLED: bucks += math.floor(int(homeruns) * homerunsbucks)\n\t\t\t\tsave([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\t\t\t\touts = 0\n\t\t\t\tstartplay = False\n\t\t\t\tstart = False\n\t\t\tbally, ballx, batx, baty = -10, -10, -10, -10\n\n\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == updateevent: \n\t\t\t\t\twith open(folderpath + \"//gamefiles//hplay.json\", \"r\") as playh:\n\t\t\t\t\t\tjsonfile = playh.read()\n\t\t\t\t\t\tplayh.close()\n\t\t\t\t\tjsonfile = json.loads(jsonfile)\n\t\t\t\t\n\t\t\t\t\tif int(highruns) < int(runs):\n\t\t\t\t\t\thighruns = runs\n\t\t\t\t\t\tjsonfile[\"play\"][\"runs\"] = runs\n\t\t\t\t\n\n\t\t\t\t\tif int(highsingles) < int(singles):\n\t\t\t\t\t\thighsingles = singles\n\t\t\t\t\t\tjsonfile[\"play\"][\"singles\"] = singles\n\t\t\t\t\tif int(highdoubles) < int(doubles):\n\t\t\t\t\t\thighdoubles = doubles\n\t\t\t\t\t\tjsonfile[\"play\"][\"doubles\"] = doubles\n\t\t\t\t\tif int(highhomeruns) < int(homeruns):\n\t\t\t\t\t\thighhomeruns = homeruns\n\t\t\t\t\t\tjsonfile[\"play\"][\"homeruns\"] = homeruns\n\n\n\n\t\t\t\t\twith open(folderpath + \"\\\\gamefiles\\\\hplay.json\", \"w\") as hplay:\n\t\t\t\t\n\t\t\t\t\t\thplay.write(json.dumps(jsonfile))\n\t\t\t\t\t\thplay.close()\n\n\n\n\t\t \n\t\t\t\n\t\t\n\t\t#screen.blit(mesg, [dis_width / 2 + 125, dis_height / 2])\n\t\t\n\t\t\n\t\tif hit == False:\n\t\t\tbally += 0.07\n\t\tif bally > 750:\n\t\t\tbally = 100\n\t\t\tstrikes += 1\n\t\t\tfirstswing = True\n\t\t\tif strikes == 3:\n\t\t\t\tstrikes = 0\n\t\t\t\touts += 1\n\t\t\tbat_sprite = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\t\t\tbat_sprite = pygame.transform.scale(bat_sprite, (20, 70)) #size of bat\n\t\tif bally <= 0:\n\t\t\tstrikes = 0\n\t\t\tif hit_type == 1:\n\t\t\t\t\n\t\t\t\thomeruns += 1\n\t\t\t\truns += 1\n\t\t\t\tmesg = \"Home Run!\"\n\t\t\t\tif runner != 0:\n\t\t\t\t\trunner = 0\n\t\t\t\t\truns += 1\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\tif hit_type == 2 or hit_type == 4:\n\t\t\t\trandhit2 = random.randint(1,5)\n\t\t\t\tif randhit2 == 1 or randhit2 == 2:\n\t\t\t\t\trunner += 2\n\t\t\t\t\tdoubles += 1\n\t\t\t\t\tif runner >= 4:\n\t\t\t\t\t\trunner = 0\n\t\t\t\t\t\truns += 1\n\t\t\t\t\t\t\n\t\t\t\t\tmesg = \"Double!\"\n\t\t\t\t\t#screen.blit(mesg, [dis_width / 6, dis_height / 3])\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif randhit2 == 3 or randhit2 == 4:\n\t\t\t\t\t\n\t\t\t\t\tmesg = \"Caught!\"\n\t\t\t\t\t#screen.blit(mesg, [dis_width / 6, dis_height / 3])\n\t\t\t\t\touts += 1\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\tif randhit2 == 5:\n\t\t\t\t\t\n\t\t\t\t\tmesg = \"Single!\"\n\t\t\t\t\t#screen.blit(mesg, [dis_width / 6, dis_height / 3])\n\t\t\t\t\trunner += 1\n\t\t\t\t\tsingles += 1\n\t\t\t\t\tif runner >= 4:\n\t\t\t\t\t\trunner = 0\n\t\t\t\t\t\truns += 1\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\tif hit_type == 3 or hit_type == 5:\n\t\t\t\t\n\t\t\t\tmesg = \"Caught!\"\n\t\t\t\t#screen.blit(mesg, [dis_width / 6, dis_height / 3])\n\t\t\t\touts += 1\n\t\t\tif hit_type == 7:\n\t\t\t\t\n\t\t\t\tstrikes += 1\n\t\t\t\tmesg = \"Foul!\"\n\t\t\t\t#screen.blit(mesg, [dis_width / 6, dis_height / 3])\n\t\t\t\t\n\n\t\t\tbally = 100\n\t\t\tballx = 265\n\t\t\tball_sprite = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha() # refresh ball cause it messed up\n\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (40, 40)) #size of ball\n\t\t\tbat_sprite = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\t\t\tbat_sprite = pygame.transform.scale(bat_sprite, (20, 70)) #size of bat\n\t\t\thit = False\n\t\t\tfirstswing = True\n\t\t\n\t\t\t#screen.blit(mesg, [dis_width / 6, dis_height / 3])\n\t\t\t\n\n\t\tif hit == True:\n\t\t\tif hit_type == 1:\n\n\t\t\t\tbally -= 0.1\n\t\t\t\n\t\t\t\tif bally < 75:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (25, 25)) #size of ball\n\t\t\t\t\tif bally < 35:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (10, 10)) #size of ball\n\t\t\tif hit_type == 2:\n\n\t\t\t\tbally -= 0.09\n\t\t\t\tballx -= 0.03\n\t\t\t\n\t\t\t\tif bally < 100:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (25, 25)) #size of ball\n\t\t\t\t\tif bally < 90:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (10, 10)) #size of ball\n\t\t\t\t\t\tif bally < 80:\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 3:\n\n\t\t\t\tbally -= 0.03\n\t\t\t\tballx -= 0.01\n\t\t\t\n\t\t\t\tif bally < 225:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (60, 60)) #size of ball\n\t\t\t\t\tif bally < 155:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (20, 20)) #size of ball\n\t\t\t\t\t\tif bally < 135:\n\t\t\t\t\t\t\tbally -= 0.04\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 4:\n\n\t\t\t\tbally -= 0.09\n\t\t\t\tballx += 0.03\n\t\t\t\n\t\t\t\tif bally < 100:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (25, 25)) #size of ball\n\t\t\t\t\tif bally < 90:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (10, 10)) #size of ball\n\t\t\t\t\t\tif bally < 80:\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 5:\n\n\t\t\t\tbally -= 0.03\n\t\t\t\tballx += 0.01\n\t\t\t\n\t\t\t\tif bally < 225:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (60, 60)) #size of ball\n\t\t\t\t\tif bally < 155:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (20, 20)) #size of ball\n\t\t\t\t\t\tif bally < 135:\n\t\t\t\t\t\t\tbally -= 0.04\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 7:\n\n\t\t\t\tbally -= 0.04\n\t\t\t\tballx += 0.06\n\t\t\t\n\t\t\t\t\n\n\t\t\t\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\n\t\t\t\texit()\n\t\t\t\t\t\t\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tstart = False\n\t\t\t\t\tstartplay = False\n\t\t\t\t\tbreak\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tif firstswing == True and hit == False:\n\t\t\t\t\t\tfirstswing = False\n\t\t\t\t\t\t\n\t\t\t\t\t\tbat_sprite = pygame.transform.rotate(bat_sprite, 150)\n\t\t\t\t\tif bally >= 298 and bally <= 304:\n\t\t\t\t\t\thit_type = 1\n\t\t\t\t\t\thit = True\n\t\t\t\t\tif bally >= 277 and bally <= 297:\n\t\t\t\t\t\trand23 = random.randint(1,3)\n\t\t\t\t\t\tif rand23 == 1:\n\t\t\t\t\t\t\thit_type = 3\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\thit_type = 2\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\tif bally >= 305 and bally <= 318:\n\t\t\t\t\t\trand23 = random.randint(1,7)\n\t\t\t\t\t\tif rand23 == 7:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\thit_type = 7\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\tif rand23 == 5 or rand23 == 6:\n\t\t\t\t\t\t\thit_type = 5\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\tif rand23 <= 4:\n\t\t\t\t\t\t\thit_type = 4\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\n\t\tpygame.display.update()\n\twhile startderby == True:\n\t\t#clock.tick(2200)\n\t\tseconds = pygame.time.get_ticks() - start_ticks# / 1000\n\t\tseconds /= 1000\n\t\tseconds = str(round(seconds, 1))\n\t\tfps += 1\n\t\t\n\t\tscreen.blit(field_sprite, (0, 0))\n\t\tif float(seconds) <= 60:\n\t\t\ttimertext = font_style.render(str(seconds), True, black)\n\t\t\tscreen.blit(timertext, [dis_width - 85, dis_height - 400])\n\t\twhile float(homeruns) > 350:\n\t\t\thomeruns -= 350\n\t\t\n\t\tif homeruns: message_to_screen(\"Home Run!\", (0, 0, 0), \"ignore\", 5, 340)\n\t\t#homeruntext = med_font.render(\"HomeRuns : \" + str(homeruns), True, black)\n\t\t#screen.blit(homeruntext, [dis_width - 600, dis_height - 400])\n\t\t#besthomeruntext = med_font.render(\"Best : \" + str(highderbyhomeruns), True, black)\n\t\t#screen.blit(besthomeruntext, [dis_width - 600, dis_height - 380])\n\t\tscreen.blit(space2swing, [dis_width / 6 + 260, dis_height / 3 + 250])\n\t\tscreen.blit(ball_sprite, (ballx, bally))\n\t\tscreen.blit(bat_sprite, (batx, baty))\n\t\tif float(seconds) >= 60:\n\t\t\tendtimer += 1\n\n\t\t\tif endtimer >= 70:\n\n\t\t\t\tstartderby = False\n\t\t\t\tstart = False\n\t\t\t\tfor i in fpslist:\n\t\t\t\t\taveragefps += i\n\t\t\t\taveragefps /= float(seconds)\n\n\t\t\t\txp += math.floor(int(homeruns) * derbyhomerunsscoring)\n\t\t\t\txp += forplayingscoring\n\t\t\t\tif ITEM_SHOP_ENABLED: bucks += math.floor(int(homeruns) * homerunsbucks)\n\t\t\t\tsave([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\n\t\t\ttimertext = font_style.render(\"60.00\", True, black)\n\t\t\tscreen.blit(timertext, [dis_width - 85, dis_height - 400])\n\t\t\tif int(highderbyhomeruns) < int(homeruns):\n\t\t\t\twith open(folderpath + \"//gamefiles//hderby.json\", \"r\") as derbyh:\n\t\t\t\t\tjsonfile = derbyh.read()\n\t\t\t\t\tderbyh.close()\n\t\t\t\t\tjsonfile = json.loads(jsonfile)\n\t\t\t\tjsonfile[\"derby\"][\"homeruns\"] = homeruns\n\n\t\t\t\twith open(folderpath + \"\\\\gamefiles\\\\hderby.json\", \"w\") as highscorehomeruns:\n\t\t\t\t\thomeruns = str(homeruns)\n\t\t\t\t\thighhomeruns = homeruns\n\t\t\t\t\thighscorehomeruns.write(json.dumps(jsonfile))\n\t\t\t\t\thighscorehomeruns.close()\n\t\t\tmesg1 = font_style.render(\"Game Over!\", True, black)\n\t\t\tscreen.blit(mesg1, [dis_width / 5, dis_height / 3])\n\t\t\tbally = -50\n\t\t\tballx = 0\n\t\t\tbatx = 0\n\t\t\tbaty = -50\n\t\t\t\n\t\t\n\t\t\n\t\t\n\t\tif hit == False:\n\t\t\tbally += 0.09 ### 0.07\n\t\tif bally > 600:\n\t\t\tbally = 100\n\t\t\tbat_sprite = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\t\t\tbat_sprite = pygame.transform.scale(bat_sprite, (20, 70)) #size of bat\n\t\t\thit = False\n\t\t\tfirstswing = True\n\t\tif bally <= 0:\n\t\t\t\n\t\t\tbally = 100\n\t\t\tballx = 265\n\t\t\tball_sprite = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha() # refresh ball cause it messed up\n\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (40, 40)) #size of ball\n\t\t\tbat_sprite = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\t\t\tbat_sprite = pygame.transform.scale(bat_sprite, (25, 70)) #size of bat\n\t\t\thit = False\n\t\t\tfirstswing = True\n\n\n\t\t\tif hit_type != 1:\n\t\t\t\tmesg = font_style.render(\"Home Run!\", False, red)\n\t\t\t\t\n\t\tif hit == True:\n\t\t\t\n\t\t\tif hit_type == 1:\n\n\t\t\t\tbally -= 0.1\n\t\t\t\n\t\t\t\tif bally < 75:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (25, 25)) #size of ball\n\t\t\t\t\tif bally < 35:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (10, 10)) #size of ball\n\t\t\t\t\t\t\n\t\t\t\t\t\thomeruns = int(homeruns) + 1\n\t\t\t\t\t\t\n\t\t\tif hit_type == 2:\n\n\t\t\t\tbally -= 0.09\n\t\t\t\tballx -= 0.03\n\t\t\t\n\t\t\t\tif bally < 100:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (25, 25)) #size of ball\n\t\t\t\t\tif bally < 90:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (10, 10)) #size of ball\n\t\t\t\t\t\tif bally < 80:\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 3:\n\n\t\t\t\tbally -= 0.03\n\t\t\t\tballx -= 0.01\n\t\t\t\n\t\t\t\tif bally < 225:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (60, 60)) #size of ball\n\t\t\t\t\tif bally < 155:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (20, 20)) #size of ball\n\t\t\t\t\t\tif bally < 135:\n\t\t\t\t\t\t\tbally -= 0.04\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 4:\n\n\t\t\t\tbally -= 0.09\n\t\t\t\tballx += 0.03\n\t\t\t\n\t\t\t\tif bally < 100:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (25, 25)) #size of ball\n\t\t\t\t\tif bally < 90:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (10, 10)) #size of ball\n\t\t\t\t\t\tif bally < 80:\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 5:\n\n\t\t\t\tbally -= 0.03\n\t\t\t\tballx += 0.01\n\t\t\t\n\t\t\t\tif bally < 225:\n\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (60, 60)) #size of ball\n\t\t\t\t\tif bally < 155:\n\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (20, 20)) #size of ball\n\t\t\t\t\t\tif bally < 135:\n\t\t\t\t\t\t\tbally -= 0.04\n\t\t\t\t\t\t\tball_sprite = pygame.transform.scale(ball_sprite, (0, 0)) #size of ball\n\t\t\tif hit_type == 7:\n\t\t\t\t\n\n\t\t\t\tbally -= 0.04\n\t\t\t\tballx += 0.06\n\t\t\t\t\n\t\t\t\t\n\t\t\n\t\t\t\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == secondevent:\n\t\t\t\t\n\t\t\t\tfpslist.append(fps)\n\t\t\t\tfps = 0\n\t\t\tif event.type == updateevent: \n\t\t\t\tpygame.mouse.set_visible(False)\n\t\t\t\t#pygame.display.set_caption('Baseball Game -- Derby ' + str(seconds) + \" \" + str(homeruns) + \" hrs\")\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\n\t\t\t\texit()\n\t\t\t\t\t\t\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tstart = False\n\t\t\t\t\tstartderby = False\n\t\t\t\t\t\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tif firstswing == True and hit == False:\n\t\t\t\t\t\tfirstswing = False\n\t\t\t\t\t\t\n\t\t\t\t\t\tbat_sprite = pygame.transform.rotate(bat_sprite, 150)\n\t\t\t\t\tif bally >= 298 and bally <= 304:\n\t\t\t\t\t\t\n\t\t\t\t\t\thit_type = 1\n\t\t\t\t\t\thit = True\n\t\t\t\t\tif bally >= 277 and bally <= 297:\n\t\t\t\t\t\trand23 = random.randint(1,3)\n\t\t\t\t\t\t\n\t\t\t\t\t\tif rand23 == 1:\n\t\t\t\t\t\t\thit_type = 3\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\thit_type = 2\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\tif bally >= 305 and bally <= 318:\n\t\t\t\t\t\t\n\t\t\t\t\t\trand23 = random.randint(1,7)\n\t\t\t\t\t\tif rand23 == 7:\n\t\t\t\t\t\t\thit_type = 7\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\tif rand23 == 5 or rand23 == 6:\n\t\t\t\t\t\t\thit_type = 5\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\tif rand23 <= 4:\n\t\t\t\t\t\t\thit_type = 4\n\t\t\t\t\t\t\thit = True\n\t\t\t\t\t\n\t\tpygame.display.update()\n\twhile optionsmenu == True:\n\t\tstatsback = True\n\t\tsettingsback = True\n\t\tshopback = True\n\t\tscreen.blit(optionsmenu_sprite, (0, 0))\n\t\t\n\t\t\n\t\tstatsrect = pygame.Rect(70, dis_height - 290, 130, 95)\n\t\tsettingsrect = pygame.Rect(210, dis_height - 350, 165, 130)\n\t\tbattlepassrect = pygame.Rect(120, dis_height - 170, 125, 85)\n\t\tassetrect = pygame.Rect(290, dis_height - 175, 220, 80)\n\t\tshoprect = pygame.Rect(350, dis_height - 265, 185, 75)\n\t\tbackrect = pygame.Rect(90, dis_height - 70, 410, 50)\n\t\t\n\t\t#if random.randint(1, 2) == 1:\n\t\t\t#pygame.draw.rect(screen,red,(statsrect))\n\t\t\t#pygame.draw.rect(screen,red,(settingsrect))\n\t\t\t#pygame.draw.rect(screen,red,(backrect))\n\t\t\t#pygame.draw.rect(screen,red,(assetrect))\n\t\t\t#pygame.draw.rect(screen,red,(shoprect))\n\t\t\t#pygame.draw.rect(screen,red,(battlepassrect))\n\t\tfor event in pygame.event.get():\n\t\t\t\n\t\t\tif event.type == pygame.KEYDOWN: \n\t\t\t\tif event.key == pygame.K_ESCAPE: optionsmenu = False; start = False\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif statsrect.collidepoint(event.pos): statsback = False\n\t\t\t\tif shoprect.collidepoint(event.pos): shopback = False; screen.fill(white)\n\t\t\t\tif battlepassrect.collidepoint(event.pos): \n\t\t\t\t\tbattlepass = False\n\t\t\t\t\tdata = opensave()\n\t\t\t\t\txp = data[3]\n\t\t\t\t\t\n\t\t\t\tif assetrect.collidepoint(event.pos): \n\t\t\t\t\tasset = False\n\t\t\t\t\tball, bat, field, xp, bucks, balllist, batlist, fieldlist, buckslist = opensave()\n\n\t\t\t\t\tballlist = ast.literal_eval(str(balllist))\n\t\t\t\t\tbatlist = ast.literal_eval(str(batlist))\n\t\t\t\t\tfieldlist = ast.literal_eval(str(fieldlist))\n\t\t\t\t\t\n\t\t\t\t\tfield_display = pygame.image.load('gamefiles/assets/fields/' + fieldlist[fieldlistnumber] + '.png').convert_alpha()\n\t\t\t\t\tball_display = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha()\n\t\t\t\t\tbat_display = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\t\t\t\t\n\t\t\t\tif backrect.collidepoint(event.pos): start = False; optionsmenu = False\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\texit()\n\t\tpygame.display.update()\n\n\t\twhile statsback == False:\n\t\t\tscreen.blit(back_sprite, (0, 0))\n\t\t\ttry:\n\t\t\t\twith open(folderpath + \"\\\\gamefiles\\\\hplay.json\", \"r\") as hjson:\n\t\t\t\t\tfile = hjson.read()\n\t\t\t\t\thjson.close()\n\t\t\texcept: pass\n\n\t\t\tjsonfile = json.loads(file)\n\t\t\t\n\t\t\t\n\t\t\thighhomeruns = str(jsonfile[\"play\"][\"homeruns\"])\n\t\t\thighruns = str(jsonfile[\"play\"][\"runs\"])\n\t\t\thighsingles = str(jsonfile[\"play\"][\"singles\"])\n\t\t\thighdoubles = str(jsonfile[\"play\"][\"doubles\"])\n\t\t\ttry:\n\t\t\t\twith open(folderpath + \"\\\\gamefiles\\\\hderby.json\", \"r\") as hjson:\n\t\t\t\t\tfile = hjson.read()\n\t\t\t\t\thjson.close()\n\t\t\texcept: pass\n\t\t\tjsonfile = json.loads(file)\n\t\t\thighderbyhomeruns = str(jsonfile[\"derby\"][\"homeruns\"])\n\t\t\t\n\t\t\tmesg = med_font.render(\"Best Runs : \" + highruns, True, black)\n\t\t\tscreen.blit(mesg, [dis_width - 595, dis_height - 395])\n\t\t\tmesg = med_font.render(\"Best Singles : \" + highsingles, True, black)\n\t\t\tscreen.blit(mesg, [dis_width - 595, dis_height - 375])\n\t\t\tmesg = med_font.render(\"Best Doubles : \" + highdoubles, True, black)\n\t\t\tscreen.blit(mesg, [dis_width - 595, dis_height - 355])\n\t\t\tmesg = med_font.render(\"Best Home Runs : \" + highhomeruns, True, black)\n\t\t\tscreen.blit(mesg, [dis_width - 595, dis_height - 335])\n\t\t\tmesg = big_font.render(\"Derby Scores\", True, black)\n\t\t\tscreen.blit(mesg, [dis_width - 300, dis_height - 395])\n\t\t\tmesg = med_font.render(\"Best Home Runs : \" + highderbyhomeruns, True, black)\n\t\t\tscreen.blit(mesg, [dis_width - 290, dis_height - 355])\n\t\t \n\t\t\thighderbyhomeruns = int(highderbyhomeruns)\n\t\t\t\n\n\n\t\t\tbackrect = pygame.Rect(360, 265, 110, 55)\n\t\t\t\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\texit()\n\t\t\t\n\t\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t\tif backrect.collidepoint(event.pos):\n\t\t\t\t\t\tstatsback = True\n\t\t\t\t\n\t\t\t\n\t\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif event.key == pygame.K_ESCAPE: statsback = True\n\t\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\t\tstatsback = True\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\tpygame.display.update()\n\t\t\t\t\n\t\twhile asset == False:\n\t\t\t\n\t\t\tscreen.fill(white)\n\n\t\t\tscreen.blit(right_arrow, [375, 25])\n\t\t\tscreen.blit(left_arrow, [100, 25])\n\t\t\t\n\t\t\tscreen.blit(right_arrow, [375, 150])\n\t\t\tscreen.blit(left_arrow, [100, 150])\n\n\t\t\tscreen.blit(right_arrow, [375, 275])\n\t\t\tscreen.blit(left_arrow, [100, 275])\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tscreen.blit(pygame.transform.scale(ball_display, (80, 80)), [240, 20])\n\t\t\tscreen.blit(pygame.transform.scale(bat_display, (40, 140)), [260, 125])\n\t\t\t\n\t\t\tscreen.blit(pygame.transform.scale(field_display, (150, 105)), [210, 275])\n\t\t\t\n\t\t\tscreen.blit(assetsback_sprite, [0, 0])\n\t\t\t\n\t\t\t\n\t\t\trightballrect = pygame.Rect(375, 25, 100, 100)\n\t\t\tleftballrect = pygame.Rect(100, 25, 100, 100)\n\n\t\t\trightbatrect = pygame.Rect(375, 150, 100, 100)\n\t\t\tleftbatrect = pygame.Rect(100, 150, 100, 100)\n\n\t\t\trightfieldrect = pygame.Rect(375, 275, 100, 100)\n\t\t\tleftfieldrect = pygame.Rect(100, 275, 100, 100)\n\n\t\t\tbackrect = pygame.Rect(480, 320, 100, 50)\n\t\t\t\n\t\t\tfor event in pygame.event.get():\n\n\t\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t\n\t\t\t\t\tif leftballrect.collidepoint(event.pos):\n\t\t\t\t\t\t\n\t\t\t\t\t\tballlistnumber -= 1\n\t\t\t\t\telif rightballrect.collidepoint(event.pos):\n\t\t\t\t\t\t\n\t\t\t\t\t\tballlistnumber += 1\n\t\t\t\t\telif leftfieldrect.collidepoint(event.pos):\n\t\t\t\t\t\t\n\t\t\t\t\t\tfieldlistnumber -= 1\n\t\t\t\t\telif rightfieldrect.collidepoint(event.pos):\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tfieldlistnumber += 1\n\t\t\t\t\telif leftbatrect.collidepoint(event.pos):\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tbatlistnumber -= 1\n\t\t\t\t\telif rightbatrect.collidepoint(event.pos):\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tbatlistnumber += 1\n\t\t\t\t\t\n\t\t\t\t\telif backrect.collidepoint(event.pos):\n\t\t\t\t\t\tasset = True\n\t\t\t\t\t\toptionsmenu = True\n\t\t\t\t\t\tmenuplace = 3\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif balllistnumber > len(balllist) - 1:\n\t\t\t\t\t\tballlistnumber = 0\n\t\t\t\t\tif batlistnumber < 0: balllistnumber = len(balllist) - 1\n\t\t\t\t\tif batlistnumber > len(batlist) - 1:\n\t\t\t\t\t\tbatlistnumber = 0\n\t\t\t\t\tif batlistnumber < 0: batlistnumber = len(batlist) - 1\n\t\t\t\t\tif fieldlistnumber > len(fieldlist) - 1:\n\t\t\t\t\t\tfieldlistnumber = 0\n\t\t\t\t\tif fieldlistnumber < 0: fieldlistnumber = len(fieldlist) - 1\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tfield_display = pygame.image.load('gamefiles/assets/fields/' + fieldlist[fieldlistnumber] + '.png').convert_alpha()\n\t\t\t\t\tball_display = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha()\n\t\t\t\t\tbat_display = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\n\t\t\t\t\t\n\n\t\t\t\t\tif balllistnumber > len(balllist) - 1:\n\t\t\t\t\t\tballlistnumber = 0\n\t\t\t\t\tif batlistnumber < 0: balllistnumber = len(balllist) - 1\n\t\t\t\t\tif batlistnumber > len(batlist) - 1:\n\t\t\t\t\t\tbatlistnumber = 0\n\t\t\t\t\tif batlistnumber < 0: batlistnumber = len(batlist) - 1\n\t\t\t\t\tif fieldlistnumber > len(fieldlist) - 1:\n\t\t\t\t\t\tfieldlistnumber = 0\n\t\t\t\t\tif fieldlistnumber < 0: fieldlistnumber = len(fieldlist) - 1\n\n\n\t\t\t\t\tdata = opensave()\n\t\t\t\t\t\n\n\t\t\t\t\t\n\t\t\t\t\tsave([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\t\t\t\t\t\n\t\t\t\t\tball_sprite = pygame.image.load('gamefiles/assets/balls/' + balllist[balllistnumber] + '.png').convert_alpha()\n\t\t\t\t\tbat_sprite = pygame.image.load('gamefiles/assets/bats/' + batlist[batlistnumber] + '.png').convert_alpha()\n\t\t\t\t\tfield_sprite = pygame.image.load('gamefiles/assets/fields/' + fieldlist[fieldlistnumber] + '.png').convert_alpha()\n\t\t\t\t\tfield_sprite = pygame.transform.scale(field_sprite, (620, 420)) #size of field\n\t\t\t\t\tbat_sprite = pygame.transform.scale(bat_sprite, (20, 70))\n\t\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif event.key == pygame.K_ESCAPE: asset = True; optionsmenu = True\n\t\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\t\tasset = True\n\t\t\t\t\t\toptionsmenu = True\n\t\t\t\t\t\t\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\texit()\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tpygame.display.update()\n\n\t\n\t\twhile shopback == False and ITEM_SHOP_ENABLED:\n\t\t\t\n\t\t\t#save([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\t\t\tscreen.blit(back_sprite, (-50, 50))\n\t\t\tif shoppage < 3:\n\t\t\t\tscreen.blit(right_arrow, [500, 300])\n\t\t\tif shoppage != 1:\n\t\t\t\tscreen.blit(left_arrow, [15, 300])\n\t\t\trightrect = pygame.Rect(500, 300, 100, 100)\n\t\t\tleftrect = pygame.Rect(15, 300, 100, 100)\n\t\t\tbackrect = pygame.Rect(310, 315, 110, 55)\n\t\t\t\n\t\t\tevenbuyrect = pygame.Rect(80, 210, 167, 65)\n\t\t\toddbuyrect = pygame.Rect(80 + 1 * 250, 210, 167, 65)\n\n\t\t\tscreen.blit(bucksicon, (150, 320))\n\t\t\tbucks_text = splash_font.render(str(opensave()[4]), True, yellow)\n\t\t\tscreen.blit(bucks_text, [175, 360])\n\t\t\tfor i in range(2):\n\n\t\t\t\ta = shoppage * 2 + i - 2\n\t\t\t\tscreen.blit(shopbox, [60 + i * 250, 35])\n\n\t\t\t\t\n\t\t\t\t#if random.randint(1, 2) == 1:\n\t\t\t\t\t#pygame.draw.rect(screen,red,(buyrect))\n\n\t\t\t\tif a == 0:\n\t\t\t\t\tsmileball = pygame.image.load('gamefiles/assets/balls/smileball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(smileball, (125, 120)), [105 + i * 250, 43])\n\t\t\t\t\tscreen.blit(bucksicon100, [135 + i * 250, 130])\n\t\t\t\t\tif \"smileball\" not in opensave()[5]: screen.blit(pygame.transform.scale(buy1, (167, 65)), [80 + i * 250, 210])\n\t\t\t\t\telse: screen.blit(pygame.transform.scale(buy2, (167, 65)), [80 + i * 250, 210])\n\t\t\t\tif a == 1:\n\t\t\t\t\tbaseballball = pygame.image.load('gamefiles/assets/balls/baseballball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(baseballball, (125, 120)), [105 + i * 250, 43])\n\t\t\t\t\tif \"baseballball\" not in opensave()[5]: screen.blit(pygame.transform.scale(buy1, (167, 65)), [80 + i * 250, 210])\n\t\t\t\t\telse: screen.blit(pygame.transform.scale(buy2, (167, 65)), [80 + i * 250, 210])\n\t\t\t\tif a == 2:\n\t\t\t\t\taxebat = pygame.image.load('gamefiles/assets/bats/axebat.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(axebat, (45, 120)), [140 + i * 250, 43])\n\t\t\t\t\tif \"axebat\" not in opensave()[6]: screen.blit(pygame.transform.scale(buy1, (167, 65)), [80 + i * 250, 210])\n\t\t\t\t\telse: screen.blit(pygame.transform.scale(buy2, (167, 65)), [80 + i * 250, 210])\n\t\t\t\tif a == 3:\n\t\t\t\t\troseball = pygame.image.load('gamefiles/assets/balls/roseball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(roseball, (125, 120)), [105 + i * 250, 43])\n\t\t\t\t\tif \"roseball\" not in opensave()[5]: screen.blit(pygame.transform.scale(buy1, (167, 65)), [80 + i * 250, 210])\n\t\t\t\t\telse: screen.blit(pygame.transform.scale(buy2, (167, 65)), [80 + i * 250, 210])\n\t\t\t\tif a == 5:\n\t\t\t\t\troseball = pygame.image.load('gamefiles/assets/balls/roseball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(roseball, (125, 120)), [105 + i * 250, 43])\n\t\t\t\t\tif \"roseball\" not in opensave()[5]: screen.blit(pygame.transform.scale(buy1, (167, 65)), [80 + i * 250, 210])\n\t\t\t\t\telse: screen.blit(pygame.transform.scale(buy2, (167, 65)), [80 + i * 250, 210])\n\t\t\t\tif a == 6:\n\t\t\t\t\troseball = pygame.image.load('gamefiles/assets/balls/roseball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(roseball, (125, 120)), [105 + i * 250, 43])\n\t\t\t\t\tif \"roseball\" not in opensave()[5]: screen.blit(pygame.transform.scale(buy1, (167, 65)), [80 + i * 250, 210])\n\t\t\t\t\telse: screen.blit(pygame.transform.scale(buy2, (167, 65)), [80 + i * 250, 210])\n\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif event.key == pygame.K_ESCAPE: shopback = True\n\t\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t\tif backrect.collidepoint(event.pos):\n\t\t\t\t\t\tshopback = True\n\t\t\t\t\tif rightrect.collidepoint(event.pos):\n\t\t\t\t\t\tif shoppage < 3: shoppage += 1; screen.fill(white)\n\t\t\t\t\tif leftrect.collidepoint(event.pos):\n\t\t\t\t\t\tif shoppage != 1: shoppage -= 1\n\t\t\t\t\tif evenbuyrect.collidepoint(event.pos):\n\t\t\t\t\t\tif shoppage == 1: bucks, balllist = buy(\"smileball\", bucks, 100, balllist)\n\t\t\t\t\t\tif shoppage == 2: bucks, batlist = buy(\"axebat\", bucks, 100, batlist)\n\t\t\t\t\t\tif shoppage == 3: bucks, batlist = buy(\"roseball\", bucks, 100, batlist)\n\t\t\t\t\t\tsave([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\t\t\t\t\tif oddbuyrect.collidepoint(event.pos):\n\t\t\t\t\t\tif shoppage == 1: bucks, balllist = buy(\"baseballball\", bucks, 100, balllist)\n\t\t\t\t\t\tif shoppage == 2: bucks, balllist = buy(\"roseball\", bucks, 100, balllist)\n\t\t\t\t\t\tif shoppage == 3: bucks, balllist = buy(\"roseball\", bucks, 100, balllist)\n\t\t\t\t\t\tsave([balllistnumber, batlistnumber, fieldlistnumber, xp, bucks, balllist, batlist, fieldlist, buckslist])\n\t\t\t\t\t\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\texit()\n\t\t\tpygame.display.update()\n\t\t\n\n\t\t#xp = 0\n\t\twhile battlepass == False:\n\t\t\tscreen.fill(white)\n\t\t\tscreen.blit(back_sprite, (-50, 50))\n\t\t\t\n\t\t\tfor i in range(1,5):\n\n\t\t\t\ta = page * 4 + i - 4\n\n\t\t\t\tlevel = math.floor(xp / 100) + 1\n\n\t\t\t\t# Giving is at start\n\n\n\t\t\t\tif a < level: screen.blit(battlepassboxpast, [-50 + i * 115, 50])\n\t\t\t\telif a > level: screen.blit(battlepassboxfuture, [-50 + i * 115, 50])\n\t\t\t\telse: screen.blit(battlepassboxpresent, [-50 + i * 115, 50])\n\n\t\t\t\tif a == 2:\n\t\t\t\t\t\n\t\t\t\t\tsnowfield = pygame.image.load('gamefiles/assets/fields/snowfield.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(snowfield, (90, 50)), [-35 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 4:\n\t\t\t\t\t\n\t\t\t\t\taxebat = pygame.image.load('gamefiles/assets/bats/axebat.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(axebat, (45, 120)), [-20 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 7:\n\t\t\t\t\t\n\t\t\t\t\tsandfield = pygame.image.load('gamefiles/assets/fields/sandfield.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(sandfield, (90, 50)), [-35 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 15:\n\n\t\t\t\t\tcoolbat = pygame.image.load('gamefiles/assets/bats/coolbat.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(coolbat, (45, 120)), [-20 + i * 115, 70])\n\t\t\t\n\t\t\t\tif a == 19:\n\t\t\t\t\t\n\t\t\t\t\thammerbat = pygame.image.load('gamefiles/assets/bats/hammerbat.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(hammerbat, (45, 120)), [-20 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 10:\n\t\t\t\t\t\n\t\t\t\t\tchristmasball = pygame.image.load('gamefiles/assets/balls/christmasball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(christmasball, (80, 80)), [-30 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 17:\n\t\t\t\t\t\n\t\t\t\t\tstarball = pygame.image.load('gamefiles/assets/balls/starball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(starball, (80, 80)), [-30 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 6:\n\t\t\t\t\t\n\t\t\t\t\troseball = pygame.image.load('gamefiles/assets/balls/roseball.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(roseball, (80, 80)), [-30 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 12:\n\t\t\t\t\t\n\t\t\t\t\thockeybat = pygame.image.load('gamefiles/assets/bats/hockeybat.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(hockeybat, (45, 120)), [-20 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 14:\n\t\t\t\t\t\n\t\t\t\t\twaterfield = pygame.image.load('gamefiles/assets/fields/waterfield.png').convert_alpha()\n\t\t\t\t\tscreen.blit(pygame.transform.scale(waterfield, (90, 50)), [-35 + i * 115, 70])\n\t\t\t\t\n\t\t\t\tif a == 16:\n\t\t\t\t\t\t\t\t\n\t\t\t\t\tscreen.blit(bucksicon100, [-35 + i * 120, 70])\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif a == 11:\n\t\t\t\t\t\n\t\t\t\t\tscreen.blit(bucksicon100, [-75 + i * 135, 70])\n\t\t\t\t\n\t\t\t\tif a == 9:\n\t\t\t\t\t\n\t\t\t\t\tscreen.blit(bucksicon75, [-35 + i * 135, 70])\n\t\t\t\t\t\n\t\t\t\tif a == 8:\n\t\t\t\t\t\n\t\t\t\t\tscreen.blit(bucksicon100, [-75 + i * 135, 70])\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tscreen.blit(xpicon, [180, 320])\n\t\t\t\txp_text = splash_font.render(str(xp), True, blue)\n\t\t\t\n\t\t\t\tscreen.blit(xp_text, [188, 305])\n\n\n\n\n\n\n\t\t\t\tab = verybig_font.render(str(a), True, grey)\n\t\t\t\tscreen.blit(ab, [-10 + i * 115, 230])\n\t\t\t\t\n\t\t\t\n\t\t\tif page != 5:\n\t\t\t\tscreen.blit(right_arrow, [500, 300])\n\t\t\tif page != 1:\n\t\t\t\tscreen.blit(left_arrow, [15, 300])\n\t\t\trightrect = pygame.Rect(500, 300, 100, 100)\n\t\t\tleftrect = pygame.Rect(15, 300, 100, 100)\n\t\t\tbackrect = pygame.Rect(310, 315, 110, 55)\n\n\n\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif event.key == pygame.K_ESCAPE: battlepass = True\n\t\t\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\t\t\t#screen.fill(white)\n\t\t\t\t\tif backrect.collidepoint(event.pos):\n\t\t\t\t\t\tbattlepass = True\n\t\t\t\t\tif rightrect.collidepoint(event.pos):\n\t\t\t\t\t\tif page < 5: page += 1 # max. 10 later\n\t\t\t\t\tif leftrect.collidepoint(event.pos):\n\t\t\t\t\t\tif page > 1: page -= 1\n\t\t\t\t\t\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\texit()\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tpygame.display.update()","repo_name":"wowbaseballgamesocool/baseballgame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":47075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39239268005","text":"#!/usr/bin/env python3\n############################################################\n# Repgen 4 -> 5 report converter #\n# Author: Daniel Osborne #\n############################################################\n# This attempts to convert an existing repgen_4 #\n# report script to the repgen_5 format. #\n# Output will require manual examination and editing. #\n############################################################\n\nimport sys\nimport re\nfrom datetime import datetime\nfrom typing import Match\n\n# Controls if #FORM data should be block-quoted, useful for debugging in an IDE and avoiding syntax errors in report definitions.\nBLOCKQUOTE_FORM = False\n\n# If True, any statements that were converted will be preserved in the output as comments (prepended with '#-')\nSHOW_PREVIOUS = False\n\n# The following is not recommended unless you know what you are doing.\n# These are flags, so multiple can be specified by adding them together (though not all are valid together).\n# A proper fix for this is to implement a custom datetime class in repgen which handles 2400 properly.\n# Values:\n# 0 = No date hacks (recommended)\n# 1 = Use 1μs before specified time (23:59:59.999999 instead of 24:00)\n# 2 = Don't add a day for the calculation adjustment (SPK's battery reports)\n# 4 = Increment the starting day of the month by one (SPK's battery & monthly reports)\nDATE_HACK = 0\n\n##############################################\n#### Careful changing anything below here ####\n##############################################\n\nHAS_RELATIVEDELTA = False\n# This isn't a fool-proof detection, but if you run this on the same machine/environment as repgen, it'll work.\ntry:\n # Relativedelta supports months and years, but is an external library\n from dateutil.relativedelta import relativedelta as timedelta\n HAS_RELATIVEDELTA = True\nexcept:\n pass\n\n#region Value\nclass Value:\n \"\"\"\n This represents a Value data object.\n Converts an optional explicit value, and a set of key=value pairs, into the proper Value() format for repgen5.\n \"\"\"\n PREDEFINED = [\"BTM\", \"BASDATE\", \"CURDATE\", \"CTM\"]\n\n def __init__( self, *args, **kwargs ):\n print(\"New Value %s\" % repr(args))\n\n self.value = None\n self.name = None\n self.parameters = {}\n self.predefined = False\n self.append = \"\"\n self.special_parameters = []\n\n if len(args) > 0:\n self.name = args[0]\n if len(args) > 1:\n self.value = args[1]\n\n if self.name in Value.PREDEFINED:\n print(\"Predefined\")\n self.predefined = True\n\n def __str__(self):\n result = \"\"\n\n if self.predefined:\n if self.name and self.value:\n if not (self.value.startswith(\".value\") or self.value.startswith(f\"{self.name}.value\")):\n result = f\"{self.name}\"\n if self.name not in Value.PREDEFINED:\n result = result + \".value\"\n result = result + \" = \"\n elif self.value.startswith(f\"{self.name}.value\"):\n result = f\"{self.name}\"\n if self.name in Value.PREDEFINED:\n result = result + \".value\"\n result = result + \" = \"\n\n if self.value:\n if self.value in Value.PREDEFINED:\n result = result + \"Value(\" + self.value + \")\\n\"\n else:\n result = result + self.value + \"\\n\"\n for key in self.parameters:\n result = result + f'{self.name}.{key.lower()} = {self.parameters[key]}\\n'\n if key != \"value\":\n result = result + f'Value.shared[\"{key.lower()}\"] = {self.parameters[key]}\\n'\n else:\n special_msg = \"\\t# The following labels (variables) are passed as a key=value pair string, not just a value.\\n\" + \\\n \"\\t# Python doesn't really handle this well, so this is what the result ends up as.\\n\"\n if self.name:\n result = f\"{self.name} = \"\n\n if self.value:\n if not re.match(r\"^Value\\s*[(]\", self.value, re.IGNORECASE):\n result = result + f\"Value({str(self.value)}\"\n\n if len(self.parameters) > 0:\n result = result + \",\\n\"\n\n for key in self.parameters:\n result = result + f\"\\t{key}={self.parameters[key]},\\n\"\n # special parameters are something like ^a in the report, where ^a contains the entire key=value pair string\n # These won't be added in the same order compared to regular parameters in the original report\n if len(self.special_parameters) > 0: result = result + special_msg\n for special in self.special_parameters:\n result = result + f\"\\t{special},\\n\"\n\n result = result + \")\\n\"\n else:\n result = result + str(self.value) + \"\\n\"\n for key in self.parameters:\n result = result + f'{self.name}.{key.lower()} = {self.parameters[key]}\\n'\n else:\n result = result + \"Value(\\n\"\n for key in self.parameters:\n result = result + f\"\\t{key}={self.parameters[key]},\\n\"\n\n if len(self.special_parameters) > 0: result = result + special_msg\n for special in self.special_parameters:\n result = result + f\"\\t{special},\\n\"\n\n result = result + \")\\n\"\n\n if self.append != \"\":\n result = result + \"\\n\" + self.append\n return result\n\n def addspecial(self, value: str):\n self.special_parameters.append(value)\n\n def __getitem__(self, key):\n return self.parameters[key]\n\n def __setitem__(self, key, value):\n print(f\"Adding: {key}=>{value}\")\n if key.lower() == \"value\":\n print(f\"Renaming: {key}=>missing\")\n key = \"missing\"\n self.parameters[key] = value\n\n def __contains__(self, key):\n return key in self.parameters\n#endregion\n\n# Write to stderr, but flush stdout so redirected output is in sync\ndef error(message: str):\n sys.stdout.flush()\n print(message, file=sys.stderr)\n\n#region Picture conversions\n# Long format specifiers need to be separate, to avoid ambiguity during lookup\nDATE_PICTURE_MAP_LONG = {\n r\"A{4,}\": \"%B\",\n \"YYYY\": \"%Y\",\n # These are special pictures, using generic 'N's for dates\n \"NN/NN/NN\": \"%m/%d/%y\",\n \"NN/NN\": \"%m/%d\",\n \"NN AAA NNNN\": \"%d %b %Y\",\n}\n\nDATE_PICTURE_MAP = {\n \"ZD\": \"%d\",\n \"DD\": \"%d\",\n \"ZM\": \"%m\",\n \"AAA\": \"%b\",\n \"ZZZY\": \"%Y\",\n \"YY\": \"%y\",\n \"ZY\": \"%y\",\n \"ZH\": \"%K\",\n \"HH\": \"%K\",\n \"ZT\": \"%M\",\n \"ZZ:ZT\": \"%K:%M\",\n \"ZZZT\": \"%K%M\",\n \"b\": \" \",\n '\"': \"\",\n}\n\ndef convert_picture_format(picture):\n count = 0\n decimal = False\n decimal_count = 0\n sign = False\n leading_zero = False\n first_zero_position = -1\n result = \"\"\n string = False\n current = \"\"\n triad_separator = \"\"\n prefix = \"\"\n extra = \"\"\n original_picture = picture\n picture = picture.strip()\n picture = re.sub(r'[Bb]', ' ', picture)\n\n result = picture\n\n while picture:\n #print(f\"Checking: {picture}\")\n # Some reports can use ZZZZ on a datetime to print only the hour minute, as HHMM.\n # Since this converter can't know the context of the picture; warn the user so they can check.\n if picture == \"ZZZZ\": error(\"WARNING: Possible ambiguous use of 'ZZZZ' format, check conversion!\")\n\n # For simplicity of code, we'll build up each item until it matches in the lookup table, then reset.\n no_more = False\n while not no_more:\n no_more = True\n for pic,after in DATE_PICTURE_MAP_LONG.items():\n match = re.match(r\"(\" + pic + r\")(\\s*)\", picture)\n if match:\n picture = picture.replace(match.group(0), '', 1)\n result = result.replace(match.group(1), after, 1)\n #result = result + after + match.group(2)\n no_more = False\n\n for pic,after in DATE_PICTURE_MAP.items():\n match = re.match(r\"(?!%)(\" + pic + r\")(\\s*)\", picture)\n if match:\n picture = picture.replace(match.group(0), '', 1)\n result = result.replace(match.group(1), after, 1)\n #result = result + after + match.group(2)\n no_more = False\n break # if we got a short one, always end early and restart at a long specifier check\n\n if picture:\n char = picture[0]\n picture = picture[1:]\n\n if char == \"S\": sign = True\n else:\n if char == 'N':\n count = count + 1\n\n if decimal:\n decimal_count = decimal_count + 1\n extra = \"\"\n elif count > 0 and char == '.':\n decimal = True\n\n if first_zero_position > 0 and first_zero_position < count:\n leading_zero = True\n\n count = count + 1 # Width specifier includes the decimal separator\n extra = \"\"\n elif count > 0 and char == ',':\n triad_separator = ','\n count = count + 1 # Width specifier includes the group separators, assume we have just one\n extra = \"\"\n elif char == 'Z':\n count = count + 1\n\n if not decimal and first_zero_position == -1:\n first_zero_position = count\n\n if decimal:\n decimal_count = decimal_count + 1\n extra = \"\"\n else:\n if count == 0 and decimal_count == 0:\n prefix = prefix + char\n else:\n extra = extra + char\n continue\n\n current = current + char\n\n if decimal_count > 0:\n result = result.replace(current, f\"%{count}{triad_separator}.{decimal_count}f\")\n elif count > 0:\n result = result.replace(current, f\"%{count}{triad_separator}.0f\")\n count = 0\n decimal_count = 0\n\n if \"AA\" in result: error(\"WARNING: Possible ambiguous use of 'A' format, check conversion!\")\n\n print(\"Picture converted '%s' -> '%s'\" % (original_picture, result))\n return result\n\ndef convert_picture(variable, picture):\n picture = convert_picture_format(picture)\n result = '%s.picture = \"%s\"' % (variable, picture)\n return result\n#endregion\n\n#region Math conversions\ndef map_ACCUM(*args):\n print(\"map_ACCUM( %s )\" % repr(args))\n dest = args[0]\n flag = args[1].strip('\"')\n source = args[2]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + 'Value.accum(%s, treat=\"%s\")' % (source, flag)\n return result\n\ndef map_DIFF(*args):\n print(\"map_DIFF( %s )\" % repr(args))\n dest = args[0]\n flag = args[1].strip('\"')\n source = args[2]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + 'Value.diff(%s, treat=\"%s\")' % (source, flag)\n return result\n\ndef map_SUM(*args):\n print(\"map_SUM( %s )\" % repr(args))\n dest = args[0]\n flag = args[1].strip('\"')\n source = \", \".join(args[2:])\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + 'Value.sum(%s, treat=\"%s\")' % (source, flag)\n return result\n\ndef map_MIN(*args):\n print(\"map_MIN( %s )\" % repr(args))\n dest = args[0]\n flag = args[1].strip('\"')\n source = \", \".join(args[2:])\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + 'Value.min(%s, treat=\"%s\")' % (source, flag)\n return result\n\ndef map_MAX(*args):\n print(\"map_MAX( %s )\" % repr(args))\n dest = args[0]\n flag = args[1].strip('\"')\n source = \", \".join(args[2:])\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + 'Value.max(%s, treat=\"%s\")' % (source, flag)\n return result\n\ndef map_AVERAGE(*args):\n print(\"map_AVERAGE( %s )\" % repr(args))\n dest = args[0]\n flag = args[1].strip('\"')\n source = \", \".join(args[2:])\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + 'Value.average(%s, treat=\"%s\")' % (source, flag)\n return result\n\ndef map_RNDPOS(*args):\n print(\"map_RNDPOS( %s )\" % repr(args))\n dest = args[0]\n source = args[1].strip('\"')\n places = args[2]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + '%s.roundpos(%s)' % (source, places)\n return result\n#endregion\n\n#region Date/Time conversions\n# Convert timezones to ones recognized by Python and Oracle\nZONE_MAP = {\n # \"PST8PDT\": \"America/Los_Angeles\",\n \"PST\": \"Etc/GMT+8\", # Special one, no DST; +8 is correct, see: https://en.wikipedia.org/wiki/Tz_database#Area\n # \"MST7MDT\": \"America/Denver\",\n # \"MST\": \"Etc/GMT+7\", # Maybe America/Phoenix instead?\n # \"CST6CDT\": \"America/Chicago\",\n # \"CST\": \"Etc/GMT+6\",\n # \"EST5EDT\": \"America/New_York\",\n # \"EST\": \"Etc/GMT+5\",\n}\n\ndef convert_timeop(dest, source, op, value, duration):\n DURATION_MAP = {\n \"M\": \"months\",\n \"MONTH\": \"months\",\n \"D\": \"days\",\n \"DAY\": \"days\",\n \"Y\": \"years\",\n \"YEAR\": \"years\",\n \"H\": \"hours\",\n \"HOUR\": \"hours\",\n \"MIN\": \"minutes\",\n \"MINUTE\": \"minutes\",\n }\n\n if not HAS_RELATIVEDELTA:\n # Relative delta isn't present, so we have to manipulate the arguments to estimate the same time range for months and years\n if duration.upper() == \"YEAR\" or duration.upper() == \"Y\":\n newduration = \"DAY\"\n newvalue = int(value) * 365\n error(f\"WARNING: dateutil module not present, estimating '{duration.upper()}={value}' as '{newduration.upper()}={newvalue}'\")\n duration = newduration\n value = newvalue\n if duration.upper() == \"MONTH\" or duration.upper() == \"M\":\n newduration = \"DAY\"\n newvalue = int(value) * 30\n error(f\"WARNING: dateutil module not present, estimating '{duration.upper()}={value}' as '{newduration.upper()}={newvalue}'\")\n duration = newduration\n value = newvalue\n else:\n # reports use DAY math for adding/subtracting years, which assumes no leap days exist\n # Python includes leap days in calculations, so account for that\n if duration.upper().startswith('D') and int(value) % 365 == 0:\n years = int(value) / 365\n leap_days = (years % 4) + 1 # not accurate every 100 years (e.g. 2000)\n duration = \"YEAR\"\n value = leap_days\n result = \"%s%ctimedelta(%s=%d)\" % (source, op, DURATION_MAP[duration.upper()], years)\n return result\n\n result = \"%s%ctimedelta(%s=%d)\" % (source, op, DURATION_MAP[duration.upper()], int(value))\n return result\n\ndef map_DATATIME(*args):\n print(\"map_DATATIME( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + \"%s.datatimes()\" % (source)\n return result\n\n\n# TIME is a no-op, since the data is already in time format\ndef map_TIME(*args):\n print(\"map_TIME( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + source\n return result\n\ndef map_SETTIME(*args, **kwargs):\n print(\"map_SETTIME( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n extra = None\n show_comment = True\n\n if source.startswith(\"%\"): source = source[1:]\n if dest.startswith(\"%\"): dest = dest[1:]\n\n if \"comment\" in kwargs: show_comment = bool(kwargs[\"comment\"])\n\n arguments = {}\n for x in range(2, len(args), 2):\n component = args[x]\n value = args[x + 1]\n\n ucomp = component.upper().strip()\n\n if ucomp == \"HOUR\":\n arguments[\"hour\"] = value\n if ucomp == \"MINUTE\":\n arguments[\"minute\"] = value\n if ucomp == \"SECOND\":\n arguments[\"second\"] = value\n arguments[\"microsecond\"] = 0 # Always clear the microseconds\n if ucomp == \"TIME\":\n arguments[\"hour\"] = value[:2]\n arguments[\"minute\"] = value[2:]\n arguments[\"second\"] = 0\n arguments[\"microsecond\"] = 0\n\n if ucomp == \"DAY\":\n # Hack to fix monthly reports\n if DATE_HACK & 4 and value == \"1\":\n arguments[\"day\"] = int(value) + 1\n else:\n arguments[\"day\"] = value\n if ucomp == \"MONTH\":\n arguments[\"month\"] = value\n if ucomp == \"YEAR\":\n arguments[\"year\"] = value\n if ucomp == \"DATE\":\n arguments[\"day\"] = value[:2]\n arguments[\"month\"] = datetime.strptime(\"%b\", value[2:5]).strftime(\"%d\")\n arguments[\"year\"] = value[5:]\n\n if \"hour\" in arguments and arguments[\"hour\"] == \"24\":\n # Python doesn't support 24 as a valid hour, so use 0, but set the date forward a day\n # Note, for month ranges, use the second block\n if DATE_HACK & 1:\n # This is sometimes needed for computing monthly or annual reports;\n # proper fix is to implement a custom datetime class\n arguments[\"hour\"] = 23\n arguments[\"minute\"] = 59\n arguments[\"second\"] = 59\n arguments[\"microsecond\"] = 999999\n else:\n arguments[\"hour\"] = 0\n arguments[\"minute\"] = 0\n arguments[\"second\"] = 0\n arguments[\"microsecond\"] = 0\n \n if DATE_HACK & 2 == 0:\n extra = \"+ timedelta(days=1)\"\n if show_comment: extra = extra + \" # Add a day to offset setting the time to 00, instead of 24\"\n\n for key, value in arguments.items():\n # Strip leading zeros\n if isinstance(value, str): arguments[key] = re.sub(r\"\\b(? %s\" % result)\n return result\n\n# Last hour is a specialized version of SETTIME\ndef map_LASTHOUR(*args):\n print(\"map_LASTHOUR( %s ) -> SETTIME\" % repr(args))\n return map_SETTIME(args[0], args[1], \"MINUTE\", 0, \"SECOND\", 0)\n\ndef map_DAYOFYR(*args):\n print(\"map_DAYOFYR( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + \"%s.value.timetuple().tm_yday\" % (source)\n return result\n\ndef map_MONOFYR(*args):\n print(\"map_MONOFYR( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + \"%s.value.timetuple().tm_mon\" % (source)\n return result\n\ndef map_YEAR(*args):\n print(\"map_YEAR( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + \"%s.value.timetuple().tm_year\" % (source)\n return result\n\ndef map_MONTH(*args):\n print(\"map_MONTH( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = f\"{source}.value.strftime('%B')\"\n return result\n\ndef map_DAY(*args):\n print(\"map_DAY( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + \"%s.value.timetuple().tm_mday\" % (source)\n return result\n\ndef map_NDAYS(*args):\n print(\"map_NDAYS( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = \"calendar.monthrange(%s.value.timetuple().tm_year, %s.value.timetuple().tm_mon)[1]\" % (source, source)\n return result\n\ndef map_EOM(*args):\n print(\"map_EOM( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = \"calendar.monthrange(%s.value.timetuple().tm_year, %s.value.timetuple().tm_mon)[1]\" % (source, source)\n # The object to be returned should be a date object, so pass through SETTIME\n # Since this is a function call mapping, the 'source' doesn't matter, as it's transitive.\n # The EOM is also assumed to be 2400 on the last day, so make sure that's explicitly set.\n return map_SETTIME(args[1], args[1], \"DAY\", result, \"HOUR\", \"24\", comment=False)\n\n# This assumes the values passed in are scalar Value types\ndef map_DMY2DATE(*args):\n print(\"map_DMY2DATE( %s )\" % repr(args))\n dest = args[0]\n day = args[1]\n month = args[2]\n year = args[3]\n\n if day.startswith(\"%\"): day = day[1:]\n if month.startswith(\"%\"): month = month[1:]\n if year.startswith(\"%\"): year = year[1:]\n\n if not day.isdigit():\n day = day + \".value\"\n if not month.isdigit():\n month = month + \".value\"\n if not year.isdigit():\n year = year + \".value\"\n\n # bump day forward since python doesn't support hour 24\n result = f\"datetime.datetime({year}, {month}, {day}) + timedelta(days=1)\"\n return result\n\ndef convert_timezone(timezone):\n match = re.search(r'\"?([A-Za-z0-9/_]+)\"?', timezone)\n if match is not None:\n zone = match.group(1)\n newzone = ZONE_MAP.get(zone, zone)\n if newzone != zone:\n print(\"Convert timezone: %s -> %s\" % (zone, newzone))\n\n timezone = timezone.replace(zone, newzone)\n return timezone\n#endregion\n\n#region Misc conversions\ndef map_GROUP(*args):\n print(\"map_GROUP( %s )\" % repr(args))\n dest = args[0]\n source = \", \".join(args[1:])\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + '[%s]' % source\n return result\n\ndef map_IGROUP(*args):\n print(\"map_IGROUP( %s )\" % repr(args))\n dest = args[0]\n index_str = args[1]\n start = args[2]\n end = args[3]\n index_var = args[4]\n\n result = \"\"\n arg_list = []\n\n # Since the index arguments can be variables, generate the code to build the list, instead of building it\n if index_var.startswith(\"%\"): index_var = index_var[1:]\n if start.startswith(\"%\"): start = start[1:]\n if end.startswith(\"%\"): end = end[1:]\n\n # If start or end indexes aren't numbers, then they're probably variables, so grab the direct value\n try: start = int(start)\n except ValueError: start = f'l[\"{start}\"].value'\n\n try: end = int(end)\n except ValueError: end = f'l[\"{end}\"].value'\n\n result = result + f'[l[re.sub(\"{index_str}\", str(idx), \"{index_var}\")] for l in (locals(),) for idx in range({start}, {end}+1)]'\n return result\n\ndef map_ELEMENT(*args):\n print(\"map_ELEMENT( %s )\" % repr(args))\n dest = args[0]\n source = args[1]\n seek = args[2]\n time = args[3]\n missval = args[4]\n result = \"\"\n\n if source.startswith(\"%\"): source = source[1:]\n\n result = result + f'{source}.element(\"{seek}\", {time}, \"{missval}\")'\n return result\n\n#endregion\n\ndef main(input: str, output: str):\n remapped_variables = {} # If any variables had to be renamed, keep track of this mapping\n\n def getName(name: str):\n \"\"\"Get a mapped name, if one exists. Returns argument if not mapped.\"\"\"\n match = re.match(r'([%$])?([0-9][A-Z0-9_]+)', name, re.IGNORECASE)\n if match:\n result = remapped_variables.get(match.group(2), match.group(2))\n if match.group(1):\n result = match.group(1) + result\n return result\n return remapped_variables.get(name, name)\n def mapName(name: str):\n \"\"\"Check if the passed in name is a valid identifier, if not, map it to a valid one in Python.\"\"\"\n match = re.match(r'[%$]?([0-9][A-Z0-9_]+)', name, re.IGNORECASE)\n if match:\n remapped_name = f\"_{match.group(1)}\"\n remapped_variables[name] = remapped_name\n print(f\"Mapping identifier '{match.group(1)}' -> {remapped_name}\")\n return remapped_name\n return name\n\n with open(input) as reader:\n with open(output, \"w\") as writer:\n newline = \"\"\n oldline = \"\"\n is_value_decl = False\n value_declared = False\n value_printed = False\n dest = \"\"\n pending_variables = {}\n processed_variables = {} # to avoid duplicate keys\n pending_picture = \"\"\n in_conditional = False # We are inside an IF/ELSE\n is_conditional = False # Current line is an IF/ELSE\n in_definition = False\n current_value = None\n indent_level = 0\n\n def cleanup(indent=False):\n nonlocal newline\n nonlocal oldline\n nonlocal is_value_decl\n nonlocal value_printed\n nonlocal value_declared\n nonlocal current_value\n\n if current_value:\n print(f\"Writing value: {current_value.name}; indent: {indent}; indent_level: {indent_level}\")\n output = str(current_value)\n\n # If preserving old statements as comments, write those before the new\n if SHOW_PREVIOUS and oldline != \"\":\n writer.write(oldline)\n oldline = \"\"\n\n if indent:\n # Python multiline matches CR and LF separately, so filter it out, if it exists\n output = re.sub(r\"^(.*)\\r?\\n\", '\\t' * indent_level + r\"\\1\\n\", output, flags=re.MULTILINE)\n\n writer.write(output)\n current_value = None\n\n # Flush anything else remaining\n if newline != \"\":\n writer.write(newline + \"\\n\")\n newline = \"\"\n\n # Regex for matching KEY=VALUE pairs for Value assignment\n regex = re.compile(r'''\n ([\\S]+)\\s*= # a key (any word followed by optional space and an equal sign)\n \\s* # then optional space in between\n ((?:\n \\s* # then optional space in between\n (?!\\S+\\s*=)\\S+ # then a value (any word not followed by an equal sign)\n )+) # match multiple values if present\n ''', re.VERBOSE)\n\n while True:\n line = reader.readline()\n if line == '': break\n\n curline = line = line.strip(\"\\r\\n\")\n curline = re.sub(\"^\" + \" \" * 8, \"\\t\", curline)\n stripped = curline.strip()\n #newline = stripped\n\n # Any comments, just pass through untouched\n if in_definition and not stripped.startswith(\"#\"):\n print(f\"Processing line: {curline}\")\n # Transform each line, then write it to the output\n if re.match(r\"![-~]FUNCTION\", curline): newline = \"#\" # FUNCTION line isn't necessary\n if re.match(r\"!ECHO\", curline): newline = \"#\" # ignore !ECHO\n\n # Loop through the line, grabbing tokens\n # Parsing order matters\n stripped = curline.strip()\n found_match = False\n\n # For name=value pairs, add a comma (,) to separate them\n # Also quote them if they aren't special (have %)\n result = \"\"\n matches = regex.findall(curline.strip())\n if stripped.startswith(\"%\"):\n cleanup(in_conditional)\n\n value_declared = False\n is_value_decl = True\n processed_variables = {}\n\n # Get the variable name\n match = re.match(r\"%([A-Z0-9_]+)\", stripped, re.IGNORECASE)\n dest = mapName(match.group(1))\n print(f\"Found variable name: {dest}; matches: {len(matches)}\")\n\n if not matches or len(matches) == 0:\n current_value = Value(dest)\n else:\n if curline.startswith(\"MISSTR\") or curline.startswith(\"UNDEF\"):\n match = matches.pop(0)\n pending_variables[match[0]] = match[1]\n if curline.startswith(\"VALUE\"):\n # Ignore VALUE lines\n match = matches.pop(0)\n newline = f'Value.shared[\"missing\"] = \"{match[1].upper()}\"'\n\n if len(matches) > 0:\n for match in matches:\n print(f\"Found KVP for '{dest}': {match}\")\n key = getName(match[0].upper())\n value = match[1]\n\n # Make sure any referenced identifiers are valid, replacing with mapped value, if present\n value = re.sub(r'%([A-Z0-9_]+)', lambda m: \"%\" + getName(m.group(1)), value)\n\n reference_value = value\n\n # variables with ^ prefix are special, convert those to _ for substitution\n if re.match(r\"[\\^]([a-z])\", value) or re.search(r'[%]', value):\n value = re.sub(r\"[\\^]\", \"_\", value)\n else:\n value = re.sub(r\"[\\^]([a-z])\", r\"{_\\1}\", value)\n\n # If _a variables are by themselves, leave them as-is;\n # but if they're mixed with other data, then wrap them in formatted strings (e.g. f\"{_a}\")\n if not re.search(r\"(?:[%$]|\\b_[a-z]\\b)\", value) and not re.match(r\"^\\s*[0-9.-]+\\s*$\", value):\n value = '\"' + value.strip('\"') + '\"'\n elif re.search(r\"[{}]\", value) and not re.search(r'[%\"\\']', value):\n value = 'f\"' + value.strip('\"') + '\"'\n\n # Simple picture assignment\n if key.upper() == \"PICTURE\":\n found_match = True\n pending_picture = convert_picture_format(match[1])\n value = f'\"{pending_picture}\"'\n\n # Time expression\n match = re.search(r\"%([A-Z0-9_]+)\\s*([-+])\\s*([0-9]+)([ADEHIMNORTUY]{1,6})(.*)\", reference_value, re.IGNORECASE)\n if match is not None:\n found_match = True\n value_declared = True\n source = re.sub(r\"[%$]\", \"\", match.group(1))\n operation = match.group(2)\n time_value = match.group(3)\n duration = match.group(4)\n extra = match.group(5)\n\n newvalue = convert_timeop(dest, source, operation, time_value, duration)\n reference_value = reference_value.replace(match.group(0), newvalue + extra, 1)\n value = value.replace(match.group(0), newvalue + extra)\n print(f\"Time expression: {match.group(0)} -> {newvalue}\")\n\n # Indexing operation\n while True:\n # First regex handles something like: \"%VARK( %01OCT-1D , %EOMOCT )\" second one handles something like: \"%OCTK(LAST) - %OCTK(1)\"\n index_regex = r\"%([A-Z0-9_]+)\\s*\\((.+\\)?)\\)\" if ',' in reference_value else r\"%([A-Z0-9_]+)\\s*\\((.+?\\)?)\\)\"\n match = re.search(index_regex, reference_value, re.IGNORECASE)\n if match is not None:\n found_match = True\n value_declared = True\n source = re.sub(\"%\", \"\", match.group(1))\n index = match.group(2)\n\n if index.upper() == \"END\" or index.upper() == \"LAST\": index = \".last()\"\n elif index.upper() == \"START\": index = \"[0]\"\n else:\n indexers = [x.strip() for x in index.split(',')]\n newindexers = []\n for index in indexers:\n if index.upper() == \"END\" or index.upper() == \"LAST\": index = 0\n elif index.upper() == \"START\": index = 1\n \n # Convert repgen4 1-based index to python's 0-based\n # Note, this doesn't touch variable indexors, only constants\n if isinstance(index, int) or (isinstance(index, str) and index.isnumeric()):\n index = str(int(index) - 1)\n\n newindexers.append(index)\n index = f\"[{':'.join(newindexers)}]\"\n\n reference_value = reference_value.replace(match.group(0), '', 1)\n value = value.replace(match.group(0), f\"{source}{index}\")\n print(f\"Indexing operation: {match.group(0)} -> {value}\")\n else:\n break\n\n # Function call\n while True:\n match = re.search(r\"(?!%)([A-Za-z0-9_]+)\\s*\\((.+?)(?:\\)(?!\\s*,))\", reference_value)\n if match is not None:\n print(f\"reference_value: {reference_value}\")\n found_match = True\n function = match.group(1).strip()\n arguments = match.group(2).strip()\n\n if function == \"timedelta\": break\n\n args = tuple(x.strip() for x in arguments.split(','))\n func = None\n\n try:\n func = globals()[f\"map_{function}\"] #FUNCTION_MAP.get(function, None)\n except KeyError:\n pass\n\n reference_value = reference_value.replace(match.group(0), '', 1)\n if func is not None:\n value = value.replace(match.group(0), func(dest, *args))\n print(f\"Function mapped: '{match.group(0)}' -> '{value}'\")\n else:\n error(f\"ERROR: Unable to map function: {function}\")\n else:\n break\n\n if key == \"COL\" or key == \"LINE\":\n # file column/line range, special value, just convert to string\n reference_value = reference_value.replace(value, '')\n value = f'\"{value}\"'\n\n # Special case, we need to convert DB= to dbtype=\n if key == \"DB\":\n if value == \"%DB\":\n key = \"dbtype\"\n value = '\"radar\"'\n error(f\"WARNING: Oracle connectivity is not supported. Use dbtype='radar' with RADAR.\")\n elif value.lower() == \"local\":\n error(f\"WARNING: LOCAL DB connectivity is not supported.\")\n else:\n error(f\"WARNING: DB option unsupported. Use dbtype='radar' with RADAR.\")\n elif key == \"STIME\":\n key = \"start\"\n elif key == \"ETIME\":\n key = \"end\"\n elif key == \"TYPE\":\n key = \"dbtype\"\n\n if \"TZ\" in curline:\n value = convert_timezone(value)\n\n if key != \"PICTURE\":\n value = re.sub(r\"(?<])\", r\"\\1=\", newline)\n newline = re.sub(\"<>\", \"!=\", newline)\n newline = re.sub(r\"\\s*[^<>!]=[^!<>]\\s*\", r\" == \", newline)\n\n for f in re.findall(r\"\\b(? '{newline}'\")\n elif stripped.upper().startswith(\"#ELSE\"):\n cleanup(in_conditional)\n if not in_conditional:\n # This condition usually means a broken report\n # Just ignore the conditionals and print the statements as if they weren't there\n error(f\"WARNING: Unmatched #ELSE: {stripped}\")\n newline = \"# REPGEN: Unmatched conditional\"\n else:\n is_conditional = True\n newline = '\\t' * (indent_level - 1) + \"else:\"\n elif stripped.upper().startswith(\"#ENDIF\"):\n cleanup(in_conditional)\n\n if not in_conditional:\n error(\"WARNING: Found unmatched #ENDIF\")\n\n indent_level = indent_level - 1\n if indent_level <= 0:\n indent_level = 0\n in_conditional = False\n\n newline = '\\t' * (indent_level + 1)\n elif curline == \"#ENDDEF\":\n in_definition = False\n cleanup(in_conditional)\n else:\n # Comment\n if current_value:\n newline = (newline + \"\\n\" + '\\t' * (indent_level) + stripped).strip()\n else:\n if curline == \"#DEF\":\n in_definition = True\n if HAS_RELATIVEDELTA: writer.write(\"# Generated with dateutil.relativedelta support.\\n\")\n elif BLOCKQUOTE_FORM:\n if curline == \"#FORM\":\n line = '\"\"\"' + line\n elif curline == \"#ENDFORM\":\n line = line + '\"\"\"'\n\n # If we're in the middle of a value declaration, print the comment immediately, and continue\n # Comments may end up out of order, but it prevents Value declarations from messing up.\n writer.write(line + \"\\n\")\n continue\n # The code below will fix comment order, but mess up Value declarations with comments inside\n # is_value_decl = False\n # value_printed = False\n # if len(oldline) > 0:\n # writer.write(oldline)\n # if len(newline) > 0:\n # writer.write(newline + \"\\n\")\n # newline = \"\"\n # oldline = \"\"\n\n #print(f\"in_conditional: {in_conditional}; is_conditional: {is_conditional}; line: {newline}\")\n if in_conditional and not is_conditional:\n #cleanup(in_conditional)\n if newline.strip() != \"\":\n newline = \"\\t\" + newline # Always indent if inside a conditional\n\n is_conditional = False\n #print(f\"found_match: {found_match}; newline: {newline}\")\n\n if current_value:\n if in_definition and not stripped.startswith('#') and newline != line:\n oldline = oldline + \"#-%s\\n\" % line\n elif in_definition and newline != \"\":\n if SHOW_PREVIOUS: writer.write(\"#-%s\\n\" % line)\n writer.write(newline + \"\\n\")\n newline = \"\"\n else:\n writer.write(line + \"\\n\")\n\n if newline != \"\":\n writer.write(newline + \"\\n\")\n print(f\"Saving to: {output}\")\n\nif __name__ == \"__main__\":\n input = sys.argv[1]\n output = sys.argv[2]\n main(input, output)\n \n# vim: ts=4 sw=4 expandtab\n","repo_name":"MikeNeilson/repgen5","sub_path":"converter/convert_report.py","file_name":"convert_report.py","file_ext":"py","file_size_in_byte":46667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"2587278346","text":"\"\"\" Setup file.\n\"\"\"\nimport os\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\nREADME = \"python cli\"\n\nrequires = [\n 'tensorflow'\n]\n\nsetup(name='cli',\n version=0.1,\n description='general description',\n long_description=README,\n classifiers=[\n \"Programming Language :: Python\",\n \"Topic :: Script :: Utils\",\n \"Topic :: Script :: Utils :: Application\"\n ],\n keywords=\"utils database postgres\",\n author='rraj',\n author_email='',\n url='',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=requires,\n entry_points=\"\"\"\\\n [console_scripts]\n skelcli = skelcli:main\n skeltest = skelcli.test:printHello\n \"\"\",\n)\n\n","repo_name":"roshanraj/pyskelcli","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12817856757","text":"import sys\n\n\ndef solve():\n global l, r\n\n if len(l) != len(r):\n return print(0)\n\n ans = 0\n for i in range(len(l)):\n if int(l[i]) < int(r[i]):\n return print(ans)\n\n if l[i] != '8':\n continue\n\n if int(r[i]) >= 9:\n return print(ans)\n\n ans += 1\n\n print(ans)\n\n\n\nl, r = sys.stdin.readline().strip().split(\" \")\nsolve()","repo_name":"galid1/Algorithm","sub_path":"python/baekjoon/2.algorithm/greedy/1105.팔.py","file_name":"1105.팔.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"70282961446","text":"# edit.py \n# twizzley \n\nimport logging\nfrom ancestor import *\nfrom base import Handler\nfrom helper import *\nfrom message import *\nfrom model import *\nfrom google.appengine.api import memcache\n\n\nclass Edit(Handler): # enter email, get links\n def get(self):\n self.render(\"edit.html\")\n\n def post(self):\n email = self.request.get(\"email\")\n if valid_email(email):\n user = UserModel.all().ancestor(user_key()).filter(\"email\", email).get()\n offer = SellModel.all().ancestor(sell_key()).filter(\"user\", user).get()\n if offer:\n code = get_code(email)\n sender = \"bot@trademealpoints.appspotmail.com\"\n receiver = email\n subject = \"Links for editing meal point offer\"\n\n body = link_message.format(email, email, code)\n mail.send_mail(sender, receiver, subject, body)\n self.render(\"edit.html\", stat='Check your email!')\n else:\n stat = \"You don't have any offers on the market.\"\n self.render(\"edit.html\", stat=stat)\n else:\n stat = \"(You used your wustl email)\"\n self.render(\"edit.html\", stat=stat)\n\n\nclass EditFinish(Handler): # edit personal offers\n def get(self):\n email = self.request.get('e')\n code = self.request.get('v')\n okaycode = VerifyModel.all().ancestor(verify_key()).filter('email', email).filter('code', code).get()\n\n if okaycode:\n user = UserModel.all().ancestor(user_key()).filter(\"email\", email).get()\n offer = list(SellModel.all().ancestor(sell_key()).filter('user', user).filter('fulfilled', False))\n offer.sort(key=lambda x: ((float)(x.amount), (float)(x.price)))\n self.render(\"editfinish.html\", offer=offer)\n\n else:\n self.redirect('/changeoffer')\n\n def post(self):\n\n edit_button = self.request.get('edit_button')\n email = self.request.get(\"e\")\n user = UserModel.all().filter(\"email\", email).get()\n offer = list(SellModel.all().ancestor(sell_key()).filter('user', user).filter('fulfilled', False).order('amount'))\n offer.sort(key=lambda x: (float(x.amount), float(x.price)))\n\n if edit_button:\n amount = self.request.get_all(\"amount\")\n price = self.request.get_all(\"price\")\n\n if len(offer) == len(amount) and len(offer) == len(price): # no blank fields\n change = False\n wrongamount = False\n wrongprice = False\n\n for x in range(0, len(offer)):\n if prettyamount(offer[x].amount) != prettyamount(amount[x]):\n change = True\n if valid_amount(prettyamount(amount[x])):\n offer[x].amount = prettyamount(amount[x])\n offer[x].put()\n else:\n wrongamount = True\n\n if prettyprice(offer[x].price) != prettyprice(price[x]):\n change = True\n if valid_price(prettyprice(price[x])):\n offer[x].price = prettyprice(price[x])\n offer[x].put()\n else:\n wrongprice = True\n\n if change:\n offer = list(SellModel.all().ancestor(sell_key()).filter('user', user).filter('fulfilled', False).order('amount'))\n offer.sort(key=lambda x: ((float)(x.amount), (float)(x.price)))\n\n if wrongamount: \n self.render(\"editfinish.html\", offer=offer,\n editstat=\"Wow. Such typing. Make sure your offer is between 150 and 2000 mp\")\n elif wrongprice:\n self.render(\"editfinish.html\", offer=offer, editstat=\"0.01 to 1.00 per mp\")\n\n else: # everything okay\n update_cached_offers()\n self.render(\"editfinish.html\", offer=offer, editstat=\"Updated successfully!\")\n\n elif not change:\n logging.error(\"NO CHANGE\")\n self.render(\"editfinish.html\", offer=offer, editstat=\"Updated successfully!\")\n\n else: # blank field\n self.render(\"editfinish.html\", offer=offer, editstat=\"Fill each box\")\n","repo_name":"lynhan/trademealpoints","sub_path":"python/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20411339223","text":"import numpy as np\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nimport utils\nfrom scipy import optimize\n\n###===================Part 1.1: Load and Visualizing Data ============================\ndata = loadmat(\"D:/TJH/ML03/machine-learning-ex5/machine-learning-ex5/ex5/ex5data1.mat\")\nX, y = data[\"X\"], data[\"y\"].ravel() ### X: (12,1)\nXtest, ytest = data[\"Xtest\"], data[\"ytest\"].ravel()\nXval, yval = data[\"Xval\"], data[\"yval\"].ravel()\n\nm = len(y)\n\n# plt.plot(X, y, \"ro\", ms=10, mec=\"k\", mew=1)\n# plt.xlabel(\"Change in water level(x)\")\n# plt.ylabel(\"Water flowing out of the dam(y)\")\n# plt.show()\n\n###===================Part 1.2 1.3 Regularized linear regression cost function and Gradient =============\n\ndef LinearRegCostFunction(X, y, theta, lambda_ =0.0):\n m = X.shape[0]\n h = np.dot(X,theta)\n theta_ = theta.copy()\n theta_[0] = 0\n J = (0.5/m) * ((h - y)**2).sum() + lambda_ * (0.5/m)*(theta_**2).sum()\n grad = (1./m)*np.dot(h-y,X) + lambda_ * (1/m) * theta_\n\n return J, grad\n\ninitial_theta = np.array([1,1])\nX_ = np.concatenate([np.ones((m, 1)), X], axis=1)\nJ ,grad = LinearRegCostFunction(X_, y, initial_theta, lambda_=1.0)\nprint(\"Cost is: {:.6f}\".format(J))\nprint(\"Gradient is: [{:.6f},{:.6f}]\".format(*grad)) ### passed!\n\n###===================Part 1.4 Fitting linear regression ===========================================\nX_ = np.concatenate([np.ones((m, 1)), X], axis=1)\noptimized_theta = utils.trainLinearReg(LinearRegCostFunction,X_,y,lambda_=0.)\n\n# plt.plot(X, y, \"ro\", ms=10, mec=\"k\", mew=1)\n# plt.plot(X,np.dot(X_,optimized_theta),\"--\",lw=2) ### passed!\n# plt.show()\n\n###=================== Part 2.1 Learning Curves ===================================================\ndef learningCurve(X, y, Xval, yval, lambda_=0):\n m = len(y)\n error_train = np.zeros(m)\n error_val = np.zeros(m)\n Xval_aug = np.concatenate([np.ones((Xval.shape[0],1)),Xval],axis=1)\n\n for i in range(m):\n X_i = X[:i+1]\n X_i_aug = np.concatenate([np.ones((X_i.shape[0],1)),X_i],axis=1)\n y_i = y[:i+1]\n theta_i = utils.trainLinearReg(LinearRegCostFunction,X_i_aug,y_i,lambda_=lambda_)\n error_train[i] = LinearRegCostFunction(X_i_aug,y_i,theta_i,lambda_=0)[0]\n if i==0:\n error_val[i] = np.nan\n else:\n error_val[i] = LinearRegCostFunction(Xval_aug,yval,theta_i,lambda_=0)[0]\n\n return error_train, error_val\n\nerror_train, error_val = learningCurve(X, y, Xval, yval, lambda_=0)\n# plt.plot(np.linspace(0,m-1,m),error_train)\n# plt.plot(np.linspace(0,m-1,m),error_val)\n# plt.show() #### passed!\n\n###=================== Part 3 Polynomial Regression ===================================================\ndef polyFeatures(X,p):\n X_poly = np.zeros((X.shape[0],p))\n for i in range(X.shape[0]):\n for j in range(p):\n X_poly[i,j] = (X[i])**(j+1)\n return X_poly\n\np = 8\nX_poly = polyFeatures(X,p)\nX_poly, mu, sigma = utils.featureNormalize(X_poly)\nX_poly = np.concatenate([np.ones((X_poly.shape[0],1)),X_poly],axis=1)\n\nX_poly_test = polyFeatures(Xtest,p)\nX_poly_test -= mu\nX_poly_test /= sigma\nX_poly_test = np.concatenate([np.ones((X_poly_test.shape[0],1)),X_poly_test],axis=1)\n\nX_poly_val = polyFeatures(Xval,p)\nX_poly_val -= mu\nX_poly_val /= sigma\nX_poly_val = np.concatenate([np.ones((X_poly_val.shape[0],1)),X_poly_val],axis=1)\n\nprint(X_poly[0,:])\n\n###=================== Part 3.1 Learning Polynomial Regression ==========================\nlambda_= 0.00\ntheta_lamda0 = utils.trainLinearReg(LinearRegCostFunction,X_poly,y,lambda_=lambda_)\nplt.plot(X, y, \"ro\", ms=10, mec=\"k\", mew=1)\nutils.plotFit(polyFeatures,np.min(X),np.max(X),mu,sigma,theta_lamda0,p)\nplt.ylim([-20, 50])\nplt.show()\n\nerror_train, error_val = learningCurve(X_poly, y, X_poly_val, yval, lambda_)\nplt.plot(np.linspace(0,m-1,m), error_train, np.linspace(0,m-1,m), error_val)\nplt.show()\n\n\n","repo_name":"tongjoyway/ML03","sub_path":"machine-learning-ex5/machine-learning-ex5/ex5/homework5.py","file_name":"homework5.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19666682838","text":"\n#!/usr/bin/env python\nimport keras, tensorflow as tf, numpy as np, sys, copy, argparse, random\nimport matplotlib.pyplot as plt\nimport math\nimport os\n\nnp.random.seed(10701)\ntf.set_random_seed(10701)\nrandom.seed(10701)\n\nclass QNetwork():\n\n\t# This class essentially defines the network architecture. \n\t# The network should take in state of the world as an input, \n\t# and output Q values of the actions available to the agent as the output. \n\n\tdef __init__(self, environment_name, networkname, trianable):\n\t\t# Define your network architecture here. It is also a good idea to define any training operations \n\t\t# and optimizers here, initialize your variables, or alternately compile your model here.\n\t\tif environment_name == 'grid':\n\t\t\tself.nObservation = 12\n\t\t\tself.nAction = 6\n\t\t\tself.learning_rate = 0.0001\n\t\t\tself.architecture = [32, 64, 32]\n\n\t\tkernel_init = tf.random_uniform_initializer(-0.5, 0.5)\n\t\tbias_init = tf.constant_initializer(0)\n\t\tself.input = tf.placeholder(tf.float32, shape=[None, self.nObservation], name='input')\n\t\twith tf.variable_scope(networkname):\n\t\t\tlayer1 = tf.layers.dense(self.input, self.architecture[0], tf.nn.relu, kernel_initializer=kernel_init, bias_initializer=bias_init, name='layer1', trainable=trianable)\n\t\t\tlayer2 = tf.layers.dense(layer1, self.architecture[1], tf.nn.relu, kernel_initializer=kernel_init, bias_initializer=bias_init, name='layer2', trainable=trianable)\n\t\t\tlayer3 = tf.layers.dense(layer2, self.architecture[2], tf.nn.relu, kernel_initializer=kernel_init, bias_initializer=bias_init, name='layer3', trainable=trianable)\n\t\t\tself.output = tf.layers.dense(layer3, self.nAction, kernel_initializer=kernel_init, bias_initializer=bias_init, name='output', trainable=trianable)\n\n\t\tself.targetQ = tf.placeholder(tf.float32, shape=[None, self.nAction], name='target')\n\t\tif trianable == True:\n\t\t\tself.loss = tf.losses.mean_squared_error(self.targetQ, self.output)\n\t\t\tself.opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.loss)\n\n\t\twith tf.variable_scope(networkname, reuse=True):\n\t\t\tself.w1 = tf.get_variable('layer1/kernel')\n\t\t\tself.b1 = tf.get_variable('layer1/bias')\n\t\t\tself.w2 = tf.get_variable('layer2/kernel')\n\t\t\tself.b2 = tf.get_variable('layer2/bias')\n\t\t\tself.w3 = tf.get_variable('layer3/kernel')\n\t\t\tself.b3 = tf.get_variable('layer3/bias')\n\t\t\tself.w4 = tf.get_variable('output/kernel')\n\t\t\tself.b4 = tf.get_variable('output/bias')\n\n\nclass Replay_Memory():\n\n\tdef __init__(self, memory_size=50000, burn_in=10000):\n\n\t\t# The memory essentially stores transitions recorder from the agent\n\t\t# taking actions in the environment.\n\n\t\t# Burn in episodes define the number of episodes that are written into the memory from the \n\t\t# randomly initialized agent. Memory size is the maximum size after which old elements in the memory are replaced. \n\t\t# A simple (if not the most efficient) was to implement the memory is as a list of transitions.\n\t\tself.memory = []\n\t\tself.is_burn_in = False\n\t\tself.memory_max = memory_size\n\t\tself.burn_in = burn_in\n\n\tdef sample_batch(self, batch_size=32):\n\t\t# This function returns a batch of randomly sampled transitions - i.e. state, action, reward, next state, terminal flag tuples. \n\t\t# You will feed this to your model to train.\n\t\tindex = np.random.randint(len(self.memory), size=batch_size)\n\t\tbatch = [self.memory[i] for i in index]\n\t\treturn batch\n\n\tdef append(self, transition):\n\t\t# Appends transition to the memory.\n\t\tself.memory.append(transition)\n\t\tif len(self.memory) > self.memory_max:\n\t\t\tself.memory.pop(0)\n\n\n\nclass DQN_Agent():\n\n\t# In this class, we will implement functions to do the following. \n\t# (1) Create an instance of the Q Network class.\n\t# (2) Create a function that constructs a policy from the Q values predicted by the Q Network. \n\t#\t\t(a) Epsilon Greedy Policy.\n\t# \t\t(b) Greedy Policy. \n\t# (3) Create a function to train the Q Network, by interacting with the environment.\n\t# (4) Create a function to test the Q Network's performance on the environment.\n\t# (5) Create a function for Experience Replay.\n\t\n\tdef __init__(self, environment_name, sess, gridgraph, render=False):\n\n\t\t# Create an instance of the network itself, as well as the memory. \n\t\t# Here is also a good place to set environmental parameters,\n\t\t# as well as training parameters - number of episodes / iterations, etc.\n\t\tself.epsilon = 0.05\n\t\t\n\t\tif environment_name == 'grid':\n\t\t\tself.gamma = 0.95\n\t\tself.max_episodes = 10000 #20000 #200\n\t\tself.batch_size = 32\n\t\tself.render = render\n\n\t\tself.qNetwork = QNetwork(environment_name, 'q', trianable=True)\n\t\tself.tNetwork = QNetwork(environment_name, 't', trianable=False)\n\t\tself.replay = Replay_Memory()\n\n\t\tself.gridgraph = gridgraph\n\n\t\tself.as_w1 = tf.assign(self.tNetwork.w1, self.qNetwork.w1)\n\t\tself.as_b1 = tf.assign(self.tNetwork.b1, self.qNetwork.b1)\n\t\tself.as_w2 = tf.assign(self.tNetwork.w2, self.qNetwork.w2)\n\t\tself.as_b2 = tf.assign(self.tNetwork.b2, self.qNetwork.b2)\n\t\tself.as_w3 = tf.assign(self.tNetwork.w3, self.qNetwork.w3)\n\t\tself.as_b3 = tf.assign(self.tNetwork.b3, self.qNetwork.b3)\n\t\tself.as_w4 = tf.assign(self.tNetwork.w4, self.qNetwork.w4)\n\t\tself.as_b4 = tf.assign(self.tNetwork.b4, self.qNetwork.b4)\n\n\n\t\tself.init = tf.global_variables_initializer()\n\n\t\tself.sess = sess\n\t\t# tf.summary.FileWriter(\"logs/\", self.sess.graph)\n\t\tself.sess.run(self.init)\n\t\tself.saver = tf.train.Saver(max_to_keep=20)\n\n\tdef epsilon_greedy_policy(self, q_values):\n\t\t# Creating epsilon greedy probabilities to sample from.\n\t\trnd = np.random.rand()\n\t\tif rnd <= self.epsilon:\n\t\t\treturn np.random.randint(len(q_values))\n\t\telse:\n\t\t\treturn np.argmax(q_values)\n\n\tdef greedy_policy(self, q_values):\n\t\t# Creating greedy policy for test time. \n\t\treturn np.argmax(q_values)\n\n\tdef network_assign(self):\n\t\t# pass the weights of evaluation network to target network\n\t\tself.sess.run([self.as_w1, self.as_b1, self.as_w2, self.as_b2, self.as_w3, self.as_b3, self.as_w4, self.as_b4])\n\n\tdef train(self,twoPinNum,twoPinNumEachNet,netSort,savepath,model_file=None):\n\t\t# ! savepath: \"../model_(train/test)\"\n\t\t# ! if model_file = None, training; if given, testing\n \t# ! if testing using training function, comment burn_in in Router.py\n\n\n\t\t# In this function, we will train our network. \n\t\t# If training without experience replay_memory, then you will interact with the environment \n\t\t# in this function, while also updating your network parameters. \n\n\t\t# If you are using a replay memory, you should interact with environment here, and store these \n\t\t# transitions to memory, while also updating your model.\n\n\t\t# the model will be saved to ../model/\n\t\t# the training/testing curve will be saved as a .npz file in ../data/\n\t\tif model_file is not None:\n\t\t\tself.saver.restore(self.sess, model_file)\n\n\t\treward_log = []\n\t\ttest_reward_log = []\n\t\ttest_episode = []\n\t\t# if not self.replay.is_burn_in:\n\t\t# \tself.burn_in_memory()\n\t\tsolution_combo = []\n\n\t\treward_plot_combo = []\n\t\treward_plot_combo_pure = []\n\t\tfor episode in np.arange(self.max_episodes*len(self.gridgraph.twopin_combo)):\n\n\n\t\t\t# n_node = len([n.name for n in tf.get_default_graph().as_graph_def().node])\n\t\t\t# print(\"No of nodes: \", n_node, \"\\n\")\n\n\t\t\t# print('Route:',self.gridgraph.route)\n\t\t\tsolution_combo.append(self.gridgraph.route)\n\n\t\t\tstate, reward_plot, is_best = self.gridgraph.reset()\n\t\t\treward_plot_pure = reward_plot-self.gridgraph.posTwoPinNum*100\n\t\t\t# print('reward_plot-self.gridgraph.posTwoPinNum*100',reward_plot-self.gridgraph.posTwoPinNum*100)\n\n\t\t\tif (episode) % twoPinNum == 0:\n\t\t\t\treward_plot_combo.append(reward_plot)\n\t\t\t\treward_plot_combo_pure.append(reward_plot_pure)\n\t\t\tis_terminal = False\n\t\t\trewardi = 0.0\n\t\t\tif episode % 100 == 0:\n\t\t\t\tself.network_assign()\n\n\t\t\trewardfortwopin = 0\n\t\t\twhile not is_terminal:\n\t\t\t\tobservation = self.gridgraph.state2obsv()\n\t\t\t\tq_values = self.sess.run(self.qNetwork.output, feed_dict={self.qNetwork.input: observation})\n\t\t\t\taction = self.epsilon_greedy_policy(q_values)\n\t\t\t\t# print(action)\n\t\t\t\tnextstate, reward, is_terminal, debug = self.gridgraph.step(action)\n\t\t\t\t# print(nextstate)\n\t\t\t\tobservation_next = self.gridgraph.state2obsv()\n\t\t\t\tself.replay.append([observation, action, reward, observation_next, is_terminal])\n\t\t\t\tstate = nextstate\n\t\t\t\trewardi = rewardi+reward\n\t\t\t\trewardfortwopin = rewardfortwopin + reward\n\n\t\t\t\tbatch = self.replay.sample_batch(self.batch_size)\n\t\t\t\tbatch_observation = np.squeeze(np.array([trans[0] for trans in batch]))\n\t\t\t\tbatch_action = np.array([trans[1] for trans in batch])\n\t\t\t\tbatch_reward = np.array([trans[2] for trans in batch])\n\t\t\t\tbatch_observation_next = np.squeeze(np.array([trans[3] for trans in batch]))\n\t\t\t\tbatch_is_terminal = np.array([trans[4] for trans in batch])\n\t\t\t\tq_batch = self.sess.run(self.qNetwork.output, feed_dict={self.qNetwork.input: batch_observation})\n\t\t\t\tq_batch_next = self.sess.run(self.tNetwork.output, feed_dict={self.tNetwork.input: batch_observation_next})\n\t\t\t\ty_batch = batch_reward+self.gamma*(1-batch_is_terminal)*np.max(q_batch_next, axis=1)\n\n\t\t\t\ttargetQ = q_batch.copy()\n\t\t\t\ttargetQ[np.arange(self.batch_size), batch_action] = y_batch\n\t\t\t\t_, train_error = self.sess.run([self.qNetwork.opt, self.qNetwork.loss], feed_dict={self.qNetwork.input: batch_observation, self.qNetwork.targetQ: targetQ})\n\t\t\treward_log.append(rewardi) #comment in test; do not save model test\n\n\t\t\tself.gridgraph.instantrewardcombo.append(rewardfortwopin)\n\n\t\t\t# print(episode, rewardi)\n\t\t\t\n\t\t\t# if is_best == 1:\n\t\t\t# \tprint('self.gridgraph.route',self.gridgraph.route)\n\t\t# \t\tprint('Save model')\n\t\t# # \t\ttest_reward = self.test()\n\t\t# # \t\ttest_reward_log.append(test_reward/20.0)\n\t\t# # \t\ttest_episode.append(episode)\n\t\t# \t\tsave_path = self.saver.save(self.sess, \"{}/model_{}.ckpt\".format(savepath,episode))\n\t\t# \t\tprint(\"Model saved in path: %s\" % savepath)\n\t\t\t### Change made\n\t\t\t# if rewardi >= 0:\n\t\t\t\t# print(self.gridgraph.route)\n\t\t\t\t# solution_combo.append(self.gridgraph.route)\n\n\t\t# solution = solution_combo[-twoPinNum:]\t\n\t\tscore = self.gridgraph.best_reward\t\n\t\tsolution = self.gridgraph.best_route[-twoPinNum:]\n\t\t\n\t\tsolutionDRL = []\n\n\t\tfor i in range(len(netSort)):\n\t\t\tsolutionDRL.append([])\n\n\t\tprint('twoPinNum',twoPinNum)\n\t\tprint('solution',solution)\n\n\t\tif self.gridgraph.posTwoPinNum == twoPinNum:\n\t\t\tdumpPointer = 0\n\t\t\tfor i in range(len(netSort)):\n\t\t\t\tnetToDump = netSort[i]\n\t\t\t\tfor j in range(twoPinNumEachNet[netToDump]):\n\t\t\t\t\t# for k in range(len(solution[dumpPointer])):\n\t\t\t\t\tsolutionDRL[netToDump].append(solution[dumpPointer])\n\t\t\t\t\tdumpPointer = dumpPointer + 1\n\t\t# print('best reward: ', score)\n\t\t# print('solutionDRL: ',solutionDRL,'\\n')\n\t\telse:\n\t\t\tsolutionDRL = solution\n\n\t\t## Generte solution\n\n\t\t# print ('solution_combo: ',solution_combo)\n\n\n\t\t#\n\t\t# print(test_reward_log)\n\t\t# train_episode = np.arange(self.max_episodes)\n\t\t# np.savez('../data/training_log.npz', test_episode=test_episode, test_reward_log=test_reward_log,\n\t\t# \t\t reward_log=reward_log, train_episode=train_episode)\n\n\t\tself.sess.close()\n\t\ttf.reset_default_graph()\n\n\t\treturn solutionDRL,reward_plot_combo,reward_plot_combo_pure,solution,self.gridgraph.posTwoPinNum\n\n\n\n\tdef test(self, model_file=None, no=20, stat=False):\n\t\t# Evaluate the performance of your agent over 100 episodes, by calculating cummulative rewards for the 100 episodes.\n\t\t# Here you need to interact with the environment, irrespective of whether you are using a memory. \n\t\t\n\t\t# uncomment this line below for videos\n\t\t# self.env = gym.wrappers.Monitor(self.env, \"recordings\", video_callable=lambda episode_id: True)\n\t\tif model_file is not None:\n\t\t\tself.saver.restore(self.sess, model_file)\n\t\treward_list = []\n\t\tcum_reward = 0.0\n\t\tfor episode in np.arange(no):\n\t\t\tepisode_reward = 0.0\n\t\t\tstate = self.gridgraph.reset()\n\t\t\tis_terminal = False\n\t\t\twhile not is_terminal:\n\t\t\t\tobservation = self.gridgraph.state2obsv()\n\t\t\t\tq_values = self.sess.run(self.qNetwork.output, feed_dict={self.qNetwork.input: observation})\n\t\t\t\taction = self.greedy_policy(q_values)\n\t\t\t\tnextstate, reward, is_terminal, debug = self.gridgraph.step(action)\n\t\t\t\tstate = nextstate\n\t\t\t\tepisode_reward = episode_reward+reward\n\t\t\t\tcum_reward = cum_reward+reward\n\t\t\treward_list.append(episode_reward)\n\t\tif stat:\n\t\t\treturn cum_reward, reward_list\n\t\telse:\n\t\t\treturn cum_reward\n\n\tdef burn_in_memory(self):\n\t\t# Initialize your replay memory with a burn_in number of episodes / transitions.\n\t\tprint('Start burn in...')\n\t\tstate = self.gridgraph.reset()\n\t\tfor i in np.arange(self.replay.burn_in):\n\t\t\tif i % 2000 == 0:\n\t\t\t\tprint('burn in {} samples'.format(i))\n\t\t\tobservation = self.gridgraph.state2obsv()\n\t\t\taction = self.gridgraph.sample()\n\t\t\tnextstate, reward, is_terminal, debug = self.gridgraph.step(action)\n\t\t\tobservation_next = self.gridgraph.state2obsv()\n\t\t\tself.replay.append([observation, action, reward, observation_next, is_terminal])\n\t\t\tif is_terminal:\n\t\t\t\t# print(self.gridgraph.current_step)\n\t\t\t\tstate = self.gridgraph.reset()\n\t\t\telse:\n\t\t\t\tstate = nextstate\n\t\tself.replay.is_burn_in = True\n\t\tprint('Burn in finished.')\n\n\tdef burn_in_memory_search(self,observationCombo,actionCombo,rewardCombo,\n observation_nextCombo,is_terminalCombo): # Burn-in with search\n\t\tprint('Start burn in with search algorithm...')\n\t\tfor i in range(len(observationCombo)):\n\t\t\tobservation = observationCombo[i]\n\t\t\taction = actionCombo[i]\n\t\t\treward = rewardCombo[i]\n\t\t\tobservation_next = observation_nextCombo[i]\n\t\t\tis_terminal = is_terminalCombo[i]\n\n\t\t\tself.replay.append([observation, action, reward, observation_next, is_terminal])\n\n\t\tself.replay.is_burn_in = True\n\t\tprint('Burn in with search algorithm finished.')\n\ndef parse_arguments():\n\tparser = argparse.ArgumentParser(description='Deep Q Network Argument Parser')\n\tparser.add_argument('--env',dest='env',type=str)\n\tparser.add_argument('--render',dest='render',type=int,default=0)\n\tparser.add_argument('--train',dest='train',type=int,default=1)\n\tparser.add_argument('--test',dest='test',type=int,default=0)\n\tparser.add_argument('--lookahead',dest='lookahead',type=int,default=0)\n\tparser.add_argument('--test_final',dest='test_final',type=int,default=0)\n\tparser.add_argument('--model_no',dest='model_file_no',type=str)\n\treturn parser.parse_args()\n\n\ndef main(args):\n\n\targs = parse_arguments()\n\tenvironment_name = args.env\n\n\t# Setting the session to allow growth, so it doesn't allocate all GPU memory. \n\tgpu_ops = tf.GPUOptions(allow_growth=True)\n\tconfig = tf.ConfigProto(gpu_options=gpu_ops)\n\tsess = tf.Session(config=config)\n\n\t# Setting this as the default tensorflow session. \n\tkeras.backend.tensorflow_backend.set_session(sess)\n\n\t# You want to create an instance of the DQN_Agent class here, and then train / test it. \n\tmodel_path = '../model/'\n\tdata_path = '../data/'\n\tif not os.path.exists(model_path):\n\t\tos.makedirs(model_path)\n\tif not os.path.exists(data_path):\n\t\tos.makedirs(data_path)\n\tagent = DQN_Agent(environment_name, sess, render=args.render)\n\tif args.train == 1:\n\t\tagent.train()\n\tif args.test == 1:\n\t\tprint(agent.test(model_file=\"../model/model_{}.ckpt\".format(args.model_file_no))/20.0)\n\tsess.close()\n\n\nif __name__ == '__main__':\n\tmain(sys.argv)\n\n","repo_name":"haiguanl/DQN_GlobalRouting","sub_path":"GlobalRoutingRL/DQN_Implementation.py","file_name":"DQN_Implementation.py","file_ext":"py","file_size_in_byte":14994,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"52"} +{"seq_id":"2440299437","text":"from origen.helpers.regressions.cli import CoreErrorMessages\n\nclass ErrorCases(CoreErrorMessages):\n ''' Error cases, messages, and generators too esoteric to be relevant to global origen package'''\n\n @classmethod\n def to_conflict_msg(cls, cmd, conflict):\n if not isinstance(conflict[0], str):\n cmd = conflict[0]\n conflict = conflict[1:]\n\n type = conflict[0]\n def tname(t, cap=False):\n if t in [\"lna\", \"repeated_lna\"]:\n n = \"long name alias\"\n elif t == \"ln\":\n n = \"long name\"\n elif t == \"iln\":\n n = \"inferred long name\"\n elif t in [\"sna\", \"repeated_sna\"]:\n n = \"short name alias\"\n elif t == \"sn\":\n n = \"short name\"\n else:\n raise RuntimeError(f\"Cannot get conflict name from conflict type {t}\")\n if cap:\n n = n.capitalize()\n return n\n\n prefix = f\"When processing command '{cmd.full_name}':\"\n if type in [\"lna\", \"ln\", \"sna\", \"sn\", \"iln\"]:\n with_type = conflict[1]\n offender_opt = conflict[2]\n with_opt = conflict[3]\n if type == \"iln\":\n if not isinstance(offender_opt, str):\n c = offender_opt.name\n else:\n c = offender_opt\n else:\n c = conflict[4]\n if with_opt is None:\n with_opt = offender_opt\n\n if (not isinstance(offender_opt, str)) and offender_opt.is_ext:\n if with_opt.is_ext:\n msg = f\"{tname(type, True)} '{c}' for extension option '{offender_opt.name}', from {offender_opt.displayed}, conflicts with {tname(with_type, False)} for extension '{with_opt.name}' provided by {with_opt.displayed}\"\n else:\n msg = f\"{tname(type, True)} '{c}' for extension option '{offender_opt.name}', from {offender_opt.displayed}, conflicts with {tname(with_type, False)} from command option '{with_opt.name}'\"\n else:\n if not isinstance(offender_opt, str):\n offender_opt = offender_opt.name\n msg = f\"{tname(type, True)} '{c}' for command option '{offender_opt}' conflicts with {tname(with_type, False)} from option '{with_opt.name}'\"\n elif type in [\"inter_ext_sna_sn\", \"inter_ext_lna_ln\", \"inter_ext_lna_iln\"]:\n offending_opt = conflict[1]\n if type == \"inter_ext_sna_sn\":\n type = \"sna\"\n with_type = \"sn\"\n name = conflict[2]\n elif type == \"inter_ext_lna_ln\":\n type = \"lna\"\n with_type = \"ln\"\n name = conflict[2]\n elif \"inter_ext_lna_iln\":\n type = \"lna\"\n with_type = \"iln\"\n name = offending_opt.name\n if offending_opt.is_ext:\n msg = f\"Option '{offending_opt.name}' extended from {offending_opt.displayed} specifies {tname(type, False)} '{name}' but it conflicts with the option's {tname(with_type, False)}\"\n else:\n msg = f\"Option '{offending_opt.name}' specifies {tname(type, False)} '{name}' but it conflicts with the option's {tname(with_type, False)}\"\n elif type in [\"repeated_sna\", \"repeated_lna\"]:\n offending_opt = conflict[1]\n if offending_opt.is_ext:\n offending_src = f\"extended from {conflict[1].displayed} \"\n else:\n offending_src = ''\n name = conflict[2]\n index = conflict[3]\n msg = f\"Option '{offending_opt.name}' {offending_src}repeats {tname(type, False)} '{name}' (first occurrence at index {index})\"\n elif type == \"reserved_prefix_arg_name\":\n offending_arg = conflict[1]\n msg = f\"Argument '{offending_arg}' uses reserved prefix 'ext_opt'. This option will not be available\"\n elif type == \"reserved_prefix_opt_name\":\n offending_opt = conflict[1]\n offending_src = conflict[2]\n if offending_src is None:\n msg = f\"Option '{offending_opt}' uses reserved prefix 'ext_opt'. This option will not be available\"\n else:\n msg = f\"Option '{offending_opt}' extended from {offending_src} uses reserved prefix 'ext_opt'. This option will not be available\"\n elif type in [\"reserved_prefix_ln\", \"reserved_prefix_lna\"]:\n offending_opt = conflict[1]\n name = conflict[2]\n if type == \"reserved_prefix_ln\":\n type = \"ln\"\n elif type == \"reserved_prefix_lna\":\n type = \"lna\"\n if offending_opt.is_ext:\n msg = f\"Option '{offending_opt.name}' extended from {offending_opt.displayed} uses reserved prefix 'ext_opt' in {tname(type, False)} '{name}' and will not be available as '--{name}'\"\n else:\n msg = f\"Option '{offending_opt.name}' uses reserved prefix 'ext_opt' in {tname(type, False)} '{name}' and will not be available as '--{name}'\"\n elif type == \"self_lna_iln\":\n offending_opt = conflict[1]\n msg = f\"Option '{offending_opt.name}' extended from {offending_opt.displayed} specifies long name alias '{offending_opt.name}' but it conflicts with the option's inferred long name. If this is intentional, please set this as the option's long name\"\n elif type == \"duplicate\":\n offending_opt = conflict[1]\n index = conflict[2]\n if offending_opt.is_ext:\n msg = f\"Option '{offending_opt.name}' extended from {offending_opt.displayed} is already present. Subsequent occurrences will be skipped (first occurrence at index {index})\"\n elif offending_opt.is_arg:\n msg = f\"Argument '{offending_opt.name}' is already present. Subsequent occurrences will be skipped (first occurrence at index {index})\"\n else:\n msg = f\"Option '{offending_opt.name}' is already present. Subsequent occurrences will be skipped (first occurrence at index {index})\"\n elif type == \"intra_cmd_not_placed\":\n msg = f\"Unable to place unique long name, short name, or inferred long name for command option '{conflict[1]}'. Please resolve any previous conflicts regarding this option or add/update this option's name, long name, or short name\"\n elif type == \"arg_opt_name_conflict\":\n msg = f\"Option '{conflict[1].name}' conflicts with Arg of the same name (Arg #{conflict[2]})\"\n else:\n raise RuntimeError(f\"Unrecognized conflict type {conflict[0]}\")\n msg = f\"{prefix} {msg}\"\n return msg","repo_name":"Origen-SDK/o2","sub_path":"test_apps/test_apps_shared_test_helpers/test_apps_shared_test_helpers/cli/error_cases.py","file_name":"error_cases.py","file_ext":"py","file_size_in_byte":6757,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"6900494194","text":"import random\nattemption = 0\nrand_number = random.randint(1, 5)\n\nwhile True:\n intput_number = input(\"Input number Alena: \")\n attemption += 1\n if intput_number == \"stop\":\n print(\"looser\")\n break\n elif rand_number == int(intput_number):\n print(\"You win\")\n print(str(attemption) + \" - count of attempts\")\n\n break\n elif int(intput_number) > rand_number:\n print (\"need less\")\n else: print(\"need more\")\n","repo_name":"alexwork13/progect","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21718851465","text":"import time\nimport pytest\nimport pymongo\nfrom cps2zmq.gather import MameServer, MameWorker\n\n# db_name = 'integration_test'\n\n# @pytest.fixture(scope=\"module\")\n# def db():\n# db_client = pymongo.MongoClient()\n# db = db_client[db_name]\n# yield db\n# db_client.drop_database(db_name)\n# db_client.close()\n\n# @pytest.mark.skip\n@pytest.mark.timeout(timeout=20, method='thread')\ndef test_pipeline(client):\n server = MameServer(\"tcp://127.0.0.1:5666\", \"tcp://127.0.0.1:5557\")\n workers = [MameWorker(str(num), \"tcp://127.0.0.1:5557\", b'mame') for num in range(2)]\n\n client.start()\n server.start()\n\n # love too test nonblocking code\n time.sleep(5)\n server.shutdown()\n\n assert server.frontstream is None\n assert server.backstream is None\n\n msgs_sum = 0\n for w in workers:\n w.close()\n msgs_sum += w.msgs_recv\n assert w.heartbeater is None\n assert w.frontstream is None\n\n assert server.msgs_recv == msgs_sum\n","repo_name":"goosechooser/cps2zmq","sub_path":"tests/integration_tests/gather_test.py","file_name":"gather_test.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73299019364","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\nfrom torch.nn.init import xavier_uniform, xavier_normal, orthogonal\n\n\nclass SubNet(nn.Module):\n '''\n The subnetwork that is used in TFN for video and audio in the pre-fusion stage\n '''\n\n def __init__(self, in_size, hidden_size, dropout):\n '''\n Args:\n in_size: input dimension\n hidden_size: hidden layer dimension\n dropout: dropout probability\n Output:\n (return value in forward) a tensor of shape (batch_size, hidden_size)\n '''\n super(SubNet, self).__init__()\n self.norm = nn.BatchNorm1d(in_size)\n self.drop = nn.Dropout(p=dropout)\n self.linear_1 = nn.Linear(in_size, hidden_size)\n self.linear_2 = nn.Linear(hidden_size, hidden_size)\n self.linear_3 = nn.Linear(hidden_size, hidden_size)\n\n def forward(self, x):\n '''\n Args:\n x: tensor of shape (batch_size, in_size)\n '''\n normed = self.norm(x)\n dropped = self.drop(normed)\n y_1 = F.relu(self.linear_1(dropped))\n y_2 = F.relu(self.linear_2(y_1))\n y_3 = F.relu(self.linear_3(y_2))\n\n return y_3\n\n\nclass TextSubNet(nn.Module):\n '''\n The LSTM-based subnetwork that is used in TFN for text\n '''\n\n def __init__(self, in_size, hidden_size, out_size, num_layers=1, dropout=0.2, bidirectional=False):\n '''\n Args:\n in_size: input dimension\n hidden_size: hidden layer dimension\n num_layers: specify the number of layers of LSTMs.\n dropout: dropout probability\n bidirectional: specify usage of bidirectional LSTM\n Output:\n (return value in forward) a tensor of shape (batch_size, out_size)\n '''\n super(TextSubNet, self).__init__()\n self.rnn = nn.LSTM(in_size, hidden_size, num_layers=num_layers, dropout=dropout, bidirectional=bidirectional, batch_first=True)\n self.dropout = nn.Dropout(dropout)\n self.linear_1 = nn.Linear(hidden_size, out_size)\n\n def forward(self, x):\n '''\n Args:\n x: tensor of shape (batch_size, sequence_len, in_size)\n '''\n _, final_states = self.rnn(x)\n h = self.dropout(final_states[0].squeeze())\n y_1 = self.linear_1(h)\n return y_1\n\n\nclass TFN(nn.Module):\n '''\n Implements the Tensor Fusion Networks for multimodal sentiment analysis as is described in:\n Zadeh, Amir, et al. \"Tensor fusion network for multimodal sentiment analysis.\" EMNLP 2017 Oral.\n '''\n\n def __init__(self, input_dims, hidden_dims, text_out, dropouts, post_fusion_dim):\n '''\n Args:\n input_dims - a length-3 tuple, contains (audio_dim, video_dim, text_dim)\n hidden_dims - another length-3 tuple, similar to input_dims\n text_out - int, specifying the resulting dimensions of the text subnetwork\n dropouts - a length-4 tuple, contains (audio_dropout, video_dropout, text_dropout, post_fusion_dropout)\n post_fusion_dim - int, specifying the size of the sub-networks after tensorfusion\n Output:\n (return value in forward) a scalar value between -3 and 3\n '''\n super(TFN, self).__init__()\n\n # dimensions are specified in the order of audio, video and text\n self.audio_in = input_dims[0]\n self.video_in = input_dims[1]\n self.text_in = input_dims[2]\n\n self.audio_hidden = hidden_dims[0]\n self.video_hidden = hidden_dims[1]\n self.text_hidden = hidden_dims[2]\n self.text_out= text_out\n self.post_fusion_dim = post_fusion_dim\n\n self.audio_prob = dropouts[0]\n self.video_prob = dropouts[1]\n self.text_prob = dropouts[2]\n self.post_fusion_prob = dropouts[3]\n\n # define the pre-fusion subnetworks\n self.audio_subnet = SubNet(self.audio_in, self.audio_hidden, self.audio_prob)\n self.video_subnet = SubNet(self.video_in, self.video_hidden, self.video_prob)\n self.text_subnet = TextSubNet(self.text_in, self.text_hidden, self.text_out, dropout=self.text_prob)\n\n # define the post_fusion layers\n self.post_fusion_dropout = nn.Dropout(p=self.post_fusion_prob)\n self.post_fusion_layer_1 = nn.Linear((self.text_out + 1) * (self.video_hidden + 1) * (self.audio_hidden + 1), self.post_fusion_dim)\n self.post_fusion_layer_2 = nn.Linear(self.post_fusion_dim, self.post_fusion_dim)\n self.post_fusion_layer_3 = nn.Linear(self.post_fusion_dim, 1)\n\n # in TFN we are doing a regression with constrained output range: (-3, 3), hence we'll apply sigmoid to output\n # shrink it to (0, 1), and scale\\shift it back to range (-3, 3)\n self.output_range = Parameter(torch.FloatTensor([6]), requires_grad=False)\n self.output_shift = Parameter(torch.FloatTensor([-3]), requires_grad=False)\n\n def forward(self, audio_x, video_x, text_x):\n '''\n Args:\n audio_x: tensor of shape (batch_size, audio_in)\n video_x: tensor of shape (batch_size, video_in)\n text_x: tensor of shape (batch_size, sequence_len, text_in)\n '''\n audio_h = self.audio_subnet(audio_x)\n video_h = self.video_subnet(video_x)\n text_h = self.text_subnet(text_x)\n batch_size = audio_h.data.shape[0]\n\n # next we perform \"tensor fusion\", which is essentially appending 1s to the tensors and take Kronecker product\n if audio_h.is_cuda:\n DTYPE = torch.cuda.FloatTensor\n else:\n DTYPE = torch.FloatTensor\n\n _audio_h = torch.cat((Variable(torch.ones(batch_size, 1).type(DTYPE), requires_grad=False), audio_h), dim=1)\n _video_h = torch.cat((Variable(torch.ones(batch_size, 1).type(DTYPE), requires_grad=False), video_h), dim=1)\n _text_h = torch.cat((Variable(torch.ones(batch_size, 1).type(DTYPE), requires_grad=False), text_h), dim=1)\n\n # _audio_h has shape (batch_size, audio_in + 1), _video_h has shape (batch_size, _video_in + 1)\n # we want to perform outer product between the two batch, hence we unsqueenze them to get\n # (batch_size, audio_in + 1, 1) X (batch_size, 1, video_in + 1)\n # fusion_tensor will have shape (batch_size, audio_in + 1, video_in + 1)\n fusion_tensor = torch.bmm(_audio_h.unsqueeze(2), _video_h.unsqueeze(1))\n \n # next we do kronecker product between fusion_tensor and _text_h. This is even trickier\n # we have to reshape the fusion tensor during the computation\n # in the end we don't keep the 3-D tensor, instead we flatten it\n fusion_tensor = fusion_tensor.view(-1, (self.audio_hidden + 1) * (self.video_hidden + 1), 1)\n fusion_tensor = torch.bmm(fusion_tensor, _text_h.unsqueeze(1)).view(batch_size, -1)\n\n post_fusion_dropped = self.post_fusion_dropout(fusion_tensor)\n post_fusion_y_1 = F.relu(self.post_fusion_layer_1(post_fusion_dropped))\n post_fusion_y_2 = F.relu(self.post_fusion_layer_2(post_fusion_y_1))\n post_fusion_y_3 = F.sigmoid(self.post_fusion_layer_3(post_fusion_y_2))\n output = post_fusion_y_3 * self.output_range + self.output_shift\n\n return output\n","repo_name":"declare-lab/multimodal-deep-learning","sub_path":"TensorFusionNetworks/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7386,"program_lang":"python","lang":"en","doc_type":"code","stars":570,"dataset":"github-code","pt":"52"} +{"seq_id":"73318892964","text":"from multiprocessing import Process\nimport os.path\n\nimport cv2\nimport numpy as np\nimport h5py\n\nimport config\n\n\ndef sketch(img):\n grey_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img_invert = cv2.bitwise_not(grey_img)\n blur_img=cv2.GaussianBlur(img_invert, (71,71),0)\n invblur_img=cv2.bitwise_not(blur_img)\n sketch_img=cv2.divide(grey_img,invblur_img, scale=256.0)\n return sketch_img\n\n\ndef resize(img):\n return cv2.resize(img, config.img_size, interpolation = cv2.INTER_AREA)\n\n\ndef check_size(img):\n if img.shape[0] < 100:\n return False\n return True\n\n\ndef save_as_h5(all_images, all_sketches, start):\n\n all_images_np = np.array(all_images)\n all_sketches_np = np.array(all_sketches)\n\n print(all_images_np[0])\n\n file = h5py.File(config.output + f\"{start//50000}_images.h5\", \"w\")\n\n real_images = file.create_dataset(\n \"images\", np.shape(all_images_np), h5py.h5t.STD_U8BE, data=all_images_np\n )\n\n sketches_images = file.create_dataset(\n \"sketches\", np.shape(all_sketches_np), h5py.h5t.STD_U8BE, data=all_sketches_np\n )\n\n file.close()\n print(f\"batch start at {start} finished: {len(all_images_np)} images\")\n\n\ndef create_data(start):\n images = []\n sketches = []\n\n end = start + 50000\n\n for i in range(start, end):\n\n if (i%10 == 0):\n print(f\"batch start at {start}: {i}/{end-1}\")\n\n f = config.input + f\"{i}\".rjust(6, \"0\") + \".jpg\"\n\n if os.path.exists(f):\n img = cv2.imread(f)\n\n if check_size(img):\n re_size = resize(img)\n sketch_img = sketch(re_size)\n images.append(re_size)\n sketches.append(sketch_img)\n \n save_as_h5(images, sketches, start)\n\n\ndef main():\n\n print(\"start\")\n\n process = [Process(target=create_data, args=(x, )) for x in range(0,265517,50000)]\n \n for p in process:\n p.start()\n for p in process:\n p.join()\n \n print(\"Happy ending\")\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n","repo_name":"SunWPS/s2f_model_senior_project","sub_path":"get_and_create_data/create_data/create_data.py","file_name":"create_data.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39896039663","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\nimport sys\r\nfrom PyQt4 import QtCore, QtGui\r\n\r\n\r\nclass MyWindow(QtGui.QMainWindow):\r\n def __init__(self):\r\n QtGui.QMainWindow.__init__(self)\r\n self.setWindowTitle('PyQt')\r\n self.resize(300, 200)\r\n label = QtGui.QLabel('label')\r\n label.setAlignment(QtCore.Qt.AlignCenter)\r\n self.setCentralWidget(label)\r\n button = QtGui.QPushButton('b1')\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QtGui.QApplication(sys.argv)\r\n MyWin = MyWindow()\r\n MyWin.show()\r\n app.exec_()\r\n","repo_name":"GIS90/python_base_use","sub_path":"PyQtDemo/Demo1.py","file_name":"Demo1.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7035136678","text":"import yadisk\nimport sys\nimport os\n\n\ndef auth():\n y = yadisk.YaDisk(\"7d9ca04e4fe848bbb1d1c6ba4916a5b4\", \"b7400bc636e144d988e749333afa388b\")\n url = y.get_code_url()\n print(\"Go to the following url: %s\" % url)\n code = input(\"Enter the confirmation code: \")\n\n try:\n response = y.get_token(code)\n except yadisk.exceptions.BadRequestError:\n print(\"Bad code\")\n sys.exit(1)\n\n y.token = response.access_token\n\n if y.check_token():\n return y.token\n else:\n return False\n\n\ndef get_token():\n base_path = os.path.dirname(__file__)\n\n print(base_path)\n\n try:\n f = open(base_path + '/../config/token.txt', 'r')\n token = f.read()\n f.close()\n except OSError:\n f = open(base_path + '/../config/token.txt', 'w')\n token = auth()\n f.write(token)\n f.close()\n\n return token\n\n\ndef reset_token():\n base_path = os.path.dirname(__file__)\n\n f = open(base_path + '/config/token.txt', 'w')\n token = auth()\n f.write(token)\n f.close()\n\n return token\n","repo_name":"anarbekb/screen","sub_path":"src/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2345417665","text":"#!/usr/bin/env python3\n\n# INPUT_FILE_NAME: str = \"test-input\"\nINPUT_FILE_NAME: str = \"input\"\n\n\ndef process(line: str) -> int:\n # print(f\"processing {line}\")\n i = 0\n uncompressed_length = 0\n\n while i < len(line):\n if line[i] == \"(\":\n # print(f\" marker at {i}\")\n marker_len = 0\n i += 1\n while line[i] != \"x\":\n marker_len = marker_len * 10 + int(line[i])\n i += 1\n # print(f\" marker_len: {marker_len}, i={i}\")\n i += 1\n marker_count = 0\n while line[i] != \")\":\n marker_count = marker_count * 10 + int(line[i])\n i += 1\n # print(f\" marker_count: {marker_count}, i={i}\")\n i += marker_len + 1\n uncompressed_length += marker_count * marker_len\n else:\n # print(f\" normal: {i} => {line[i]}\")\n uncompressed_length += 1\n i += 1\n\n return uncompressed_length\n\n\nwith open(INPUT_FILE_NAME, \"r\") as input_file:\n for line in input_file:\n print(process(line.strip()))\n","repo_name":"fejese/advent-of-code-2016","sub_path":"day-09/solv-1.py","file_name":"solv-1.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71929478566","text":"from __future__ import print_function\nimport random\nimport torch\nimport torch\nimport numpy as np\nfrom PIL import Image\nimport os\n\n\ndef tensor2im(input_image, imtype=np.uint8):\n \"\"\"\"Converts a Tensor array into a numpy image array.\n\n Parameters:\n input_image (tensor) -- the input image tensor array\n imtype (type) -- the desired type of the converted numpy array\n \"\"\"\n if not isinstance(input_image, np.ndarray):\n if isinstance(input_image, torch.Tensor): # get the data from a variable\n image_tensor = input_image.data\n else:\n return input_image\n image_numpy = image_tensor[0].cpu().float().numpy() # convert it into a numpy array\n if image_numpy.shape[0] == 1: # grayscale to RGB\n image_numpy = np.tile(image_numpy, (3, 1, 1))\n image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0 # post-processing: tranpose and scaling\n else: # if it is a numpy array, do nothing\n image_numpy = input_image\n return image_numpy.astype(imtype)\n\n\ndef diagnose_network(net, name='network'):\n \"\"\"Calculate and print the mean of average absolute(gradients)\n\n Parameters:\n net (torch network) -- Torch network\n name (str) -- the name of the network\n \"\"\"\n mean = 0.0\n count = 0\n for param in net.parameters():\n if param.grad is not None:\n mean += torch.mean(torch.abs(param.grad.data))\n count += 1\n if count > 0:\n mean = mean / count\n print(name)\n print(mean)\n\n\ndef save_image(image_numpy, image_path, aspect_ratio=1.0):\n \"\"\"Save a numpy image to the disk\n\n Parameters:\n image_numpy (numpy array) -- input numpy array\n image_path (str) -- the path of the image\n \"\"\"\n\n image_pil = Image.fromarray(image_numpy)\n h, w, _ = image_numpy.shape\n\n if aspect_ratio > 1.0:\n image_pil = image_pil.resize((h, int(w * aspect_ratio)), Image.BICUBIC)\n if aspect_ratio < 1.0:\n image_pil = image_pil.resize((int(h / aspect_ratio), w), Image.BICUBIC)\n image_pil.save(image_path)\n\n\ndef print_numpy(x, val=True, shp=False):\n \"\"\"Print the mean, min, max, median, std, and size of a numpy array\n\n Parameters:\n val (bool) -- if print the values of the numpy array\n shp (bool) -- if print the shape of the numpy array\n \"\"\"\n x = x.astype(np.float64)\n if shp:\n print('shape,', x.shape)\n if val:\n x = x.flatten()\n print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (\n np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))\n\n\ndef mkdirs(paths):\n \"\"\"create empty directories if they don't exist\n\n Parameters:\n paths (str list) -- a list of directory paths\n \"\"\"\n if isinstance(paths, list) and not isinstance(paths, str):\n for path in paths:\n mkdir(path)\n else:\n mkdir(paths)\n\n\ndef mkdir(path):\n \"\"\"create a single empty directory if it didn't exist\n\n Parameters:\n path (str) -- a single directory path\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n\nclass ImagePool():\n \"\"\"This class implements an image buffer that stores previously generated images.\n\n This buffer enables us to update discriminators using a history of generated images\n rather than the ones produced by the latest generators.\n \"\"\"\n\n def __init__(self, pool_size):\n \"\"\"Initialize the ImagePool class\n\n Parameters:\n pool_size (int) -- the size of image buffer, if pool_size=0, no buffer will be created\n \"\"\"\n self.pool_size = pool_size\n if self.pool_size > 0: # create an empty pool\n self.num_imgs = 0\n self.images = []\n\n def query(self, images):\n \"\"\"Return an image from the pool.\n\n Parameters:\n images: the latest generated images from the generator\n\n Returns images from the buffer.\n\n By 50/100, the buffer will return input images.\n By 50/100, the buffer will return images previously stored in the buffer,\n and insert the current images to the buffer.\n \"\"\"\n if self.pool_size == 0: # if the buffer size is 0, do nothing\n return images\n return_images = []\n for image in images:\n image = torch.unsqueeze(image.data, 0)\n if self.num_imgs < self.pool_size: # if the buffer is not full; keep inserting current images to the buffer\n self.num_imgs = self.num_imgs + 1\n self.images.append(image)\n return_images.append(image)\n else:\n p = random.uniform(0, 1)\n if p > 0.5: # by 50% chance, the buffer will return a previously stored image, and insert the current image into the buffer\n random_id = random.randint(0, self.pool_size - 1) # randint is inclusive\n tmp = self.images[random_id].clone()\n self.images[random_id] = image\n return_images.append(tmp)\n else: # by another 50% chance, the buffer will return the current image\n return_images.append(image)\n return_images = torch.cat(return_images, 0) # collect all the images and return\n return return_images","repo_name":"yue-zhongqi/tcm","sub_path":"cyclegan/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"52"} +{"seq_id":"74895014243","text":"import keras\nfrom keras.utils.np_utils import to_categorical # used for converting labels to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom sklearn.model_selection import train_test_split\nfrom scipy import stats\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np \nimport cv2\n\nfrom PIL import Image, ImageChops, ImageEnhance\nimport os\nimport itertools\n\ndef convert_to_ela_image(path, quality):\n temp_filename = 'temp_file.jpg'\n ela_filename = 'temp_ela_file.png'\n \n image = Image.open(path).convert('RGB')\n image.save(temp_filename, 'JPEG', quality = quality)\n temp_image = Image.open(temp_filename)\n \n ela_image = ImageChops.difference(image, temp_image)\n \n extrema = ela_image.getextrema()\n max_diff = max([ex[1] for ex in extrema])\n if max_diff == 0:\n max_diff = 1\n scale = 255.0 / max_diff\n \n ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)\n \n return ela_image\n\nimage_size = (128, 128)\n\ndef prepare_image(image_path):\n return np.array(convert_to_ela_image(image_path, 85).resize(image_size)).flatten() / 255.0\n\nX = [] # ELA converted images\nY = []\n\nimport random\ncount = 0\npath = 'D:\\minor project\\CASIA2\\Au'\nfor dirname, _, filenames in os.walk(path):\n for filename in filenames:\n# count+=1\n# if count < 1000:\n# pass\n if filename.endswith('jpg') or filename.endswith('png'):\n full_path = os.path.join(dirname, filename)\n X.append(prepare_image(full_path))\n Y.append(1) \n if len(Y) % 3000 == 0:\n print(f'Processing {len(Y)} images')\n break\n if len(Y) % 3000 == 0:\n break\n\nrandom.shuffle(X)\nprint(len(X), len(Y))\n\nx_t, y_t = [], []\n\npath = 'D:\\minor project\\CASIA2\\Tp'\ncount = 0\nfor dirname, _, filenames in os.walk(path):\n for filename in filenames:\n# count += 1\n# if count < 1000:\n# pass\n if filename.endswith('jpg') or filename.endswith('png'):\n full_path = os.path.join(dirname, filename)\n X.append(prepare_image(full_path))\n Y.append(0)\n if len(Y) % 2000 == 0:\n print(f'Processing {len(Y)} images')\n break\n if len(Y) % 2000 == 0:\n break\n\nfrom keras.utils.np_utils import to_categorical\n\nfrom sklearn.utils import shuffle\nfor i in range(10):\n X, Y = shuffle(X, Y, random_state=i)\n\nX = np.array(X)\nY = to_categorical(Y, 2)\nX = X.reshape(-1, 128, 128, 3)\n\nX_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size = 0.2, random_state=42)\n\nprint(len(X_train), len(Y_train))\nprint(len(X_val), len(Y_val))\n\ndef build_model():\n model = Sequential()\n model.add(Conv2D(filters = 32, kernel_size = (5, 5), padding = 'valid', activation = 'relu', input_shape = (128, 128, 3)))\n model.add(Conv2D(filters = 32, kernel_size = (5, 5), padding = 'valid', activation = 'relu', input_shape = (128, 128, 3)))\n model.add(MaxPool2D(pool_size = (2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(256, activation = 'relu'))\n model.add(Dropout(0.5))\n model.add(Dense(2, activation = 'softmax'))\n return model\n\nmodel1 = build_model()\nmodel1.summary()\n\n\nfrom keras.optimizers import Adam\n\ninit_lr = 1e-4\noptimizer = Adam(learning_rate = init_lr, decay = init_lr/50)\n\nmodel1.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n\nbatch_size = 16 \nepochs = 20 \n\nhistory = model1.fit(\n X_train, Y_train,\n epochs=epochs,\n batch_size = batch_size,\n validation_data=(X_val, Y_val),\n verbose=2)\n\nimport matplotlib.pyplot as plt\n\n# Plot training & validation accuracy values\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\nplt.show()\n\n\ntest_image_path = 'D:\\minor project\\CASIA2\\loo.PNG'\ntest_image_ela = prepare_image(test_image_path)\n\ntest_image_ela = test_image_ela.reshape(1, 128, 128, 3)\n\n\nprediction = model1.predict(test_image_ela)\n\n\npredicted_class = np.argmax(prediction)\n","repo_name":"wizva/Image_splicing","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22046864776","text":"import tensorflow as tf\nimport cv2\nimport os\nfrom os.path import exists\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport mediapipe as mp\nfrom typing import List\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM, Dense\nfrom tensorflow.keras.callbacks import TensorBoard\nfrom sklearn.metrics import accuracy_score\nfrom keras import optimizers\nfrom sklearn.metrics import multilabel_confusion_matrix, accuracy_score, confusion_matrix, ConfusionMatrixDisplay\nfrom sklearn import metrics\nimport HandModel, LoadModel\n\nmodel = LoadModel.load()\nmp_holistic = mp.solutions.holistic # Holistic model\nmp_drawing = mp.solutions.drawing_utils # Drawing utilities\n\n\ndef mediapipe_detection(image, model):\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # COLOR CONVERSION BGR 2 RGB\n image.flags.writeable = False # Image is no longer writeable\n results = model.process(image) # Make prediction\n image.flags.writeable = True # Image is now writeable\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # COLOR COVERSION RGB 2 BGR\n return image, results\n\n\ndef extract_keypoints(result):\n lh = np.array(HandModel.HandModel(np.zeros(21 * 3)).feature_vector).flatten()\n # [[r.x, r.y, r.z] for r in result.left_hand_landmarks.landmark]\n # if result.left_hand_landmarks else\n rh = np.array(HandModel.HandModel([[r.x, r.y, r.z] for r in result.right_hand_landmarks.landmark]\n if result.right_hand_landmarks else np.zeros(21 * 3)).feature_vector).flatten()\n return np.concatenate([lh, rh])\n\n\ncolors = [(0, 0, 0), (255, 0, 0), (173, 216, 230), (240, 248, 255), (255, 255, 0), (34, 139, 34)]\n\n\ndef prob_viz(res, actions, input_frame, colors):\n output_frame = input_frame.copy()\n for num, prob in enumerate(res):\n cv2.rectangle(output_frame, (0, 60 + num * 40), (int(prob * 100), 90 + num * 40), colors[num], -1)\n cv2.putText(output_frame, actions[num], (0, 85 + num * 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2,\n cv2.LINE_AA)\n\n return output_frame\n\n\n# 1. New detection variables\nsequence = []\nsentence = []\nthreshold = 0.95\nactions = np.array([\"Shutdown\", \"Red\", \"Light_Blue\", \"Bright\", \"Yellow\", \"Green\"])\nprint(actions)\ncap = cv2.VideoCapture(0)\n# Set mediapipe model\nwith mp_holistic.Holistic(min_detection_confidence=0.4, min_tracking_confidence=0.4) as hands:\n while cap.isOpened():\n ret, frame = cap.read()\n frame, results = mediapipe_detection(frame, hands)\n keypoints = extract_keypoints(results)\n sequence.append(keypoints)\n sequence = sequence[-200:]\n\n if len(sequence) == 200:\n res = model.predict(np.expand_dims(sequence, axis=0))[0]\n frame = prob_viz(res, actions, frame, colors)\n print(res[np.argmax(res)])\n if res[np.argmax(res)] > threshold:\n sentence.append(actions[np.argmax(res)])\n cv2.putText(frame, ' '.join(sentence), (60, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)\n cv2.imshow(\"image\", frame)\n sentence.clear()\n if cv2.waitKey(10) & 0xFF == ord('q'):\n break\n cap.release()\n cv2.destroyAllWindows()\n","repo_name":"Mokhtar1526/graduationProjectTest","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36254513860","text":"\"\"\"\n Date : 2021-04-07\n Source : https://www.hackerrank.com/challenges/diagonal-difference/problem\n\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'diagonalDifference' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts 2D_INTEGER_ARRAY arr as parameter.\n#\n\ndef diagonalDifference(arr):\n # Write your code here\n left = 0\n right = 0\n for k, v in enumerate(arr):\n for kk, vv in enumerate(arr):\n if k==kk:\n left += v[k]\n for k, v in enumerate(arr[::-1]):\n for kk, vv in enumerate(arr[::-1]):\n if k==kk:\n right += v[k]\n if right>=left:\n return right-left\n else:\n return left-right\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input().strip())\n\n arr = []\n\n for _ in range(n):\n arr.append(list(map(int, input().rstrip().split())))\n\n result = diagonalDifference(arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"spro1/WIL","sub_path":"Coding/hackerrank_easy_DiagonalDiff_spro1.py","file_name":"hackerrank_easy_DiagonalDiff_spro1.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"13964149061","text":"# find temperature in Fahrenheit\r\ndef convertFahr(f):\r\n c = (f * (9/5)) + 32\r\n return c\r\n\r\n\r\n# find temperature in Celsius\r\ndef convertCel(c): # user-defined function\r\n f = (c - 32) * (5/9)\r\n return f\r\n\r\n\r\n# select operation\r\nprint(\"Operation: for C to F enter 1, for F to C enter 2, for exit enter 3\")\r\nselect = int(input(\"Select operation: \"))\r\n\r\nwhile select != \"3\":\r\n if select == \"1\":\r\n # take inputs\r\n cel = float(input('Enter temperature in Celsius: '))\r\n\r\n # calling function and display result\r\n print('%0.1f degrees Celsius is equivalent to %0.1f degrees Fahrenheit' %(cel, convertFahr(cel)))\r\n select = input(\"Select operation: \")\r\n elif select == \"2\":\r\n # take inputs\r\n fahr = float(input('Enter temperature in Fahrenheit: '))\r\n\r\n # calling function and display result\r\n print('%0.1f degrees Fahrenheit is equivalent to %0.1f degrees Celsius' %(fahr, convertCel(fahr)))\r\n select = input(\"Select operations: \")\r\n else:\r\n break\r\n ","repo_name":"JamesBradleyBigCreative/Classroom_Exercises","sub_path":"Lionel Martinez-Batista/PythonApplication14/PythonApplication14/PythonApplication14.py","file_name":"PythonApplication14.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"71877748006","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Combinatorics\n\n\ncodonTable_DNA = {\n 'ATA': 'I', 'ATC': 'I', 'ATT': 'I', 'ATG': 'M',\n 'ACA': 'T', 'ACC': 'T', 'ACG': 'T', 'ACT': 'T',\n 'AAC': 'N', 'AAT': 'N', 'AAA': 'K', 'AAG': 'K',\n 'AGC': 'S', 'AGT': 'S', 'AGA': 'R', 'AGG': 'R',\n 'CTA': 'L', 'CTC': 'L', 'CTG': 'L', 'CTT': 'L',\n 'CCA': 'P', 'CCC': 'P', 'CCG': 'P', 'CCT': 'P',\n 'CAC': 'H', 'CAT': 'H', 'CAA': 'Q', 'CAG': 'Q',\n 'CGA': 'R', 'CGC': 'R', 'CGG': 'R', 'CGT': 'R',\n 'GTA': 'V', 'GTC': 'V', 'GTG': 'V', 'GTT': 'V',\n 'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A',\n 'GAC': 'D', 'GAT': 'D', 'GAA': 'E', 'GAG': 'E',\n 'GGA': 'G', 'GGC': 'G', 'GGG': 'G', 'GGT': 'G',\n 'TCA': 'S', 'TCC': 'S', 'TCG': 'S', 'TCT': 'S',\n 'TTC': 'F', 'TTT': 'F', 'TTA': 'L', 'TTG': 'L',\n 'TAC': 'Y', 'TAT': 'Y', 'TAA': '', 'TAG': '',\n 'TGC': 'C', 'TGT': 'C', 'TGA': '', 'TGG': 'W',\n}\n\n\ndef orf(sequence):\n pro_list = []\n for start in range(len(sequence)-3):\n sequence_pro = ''\n if codonTable_DNA[sequence[start:start+3]] == 'M':\n # 开始遍历翻译,ATG 是启动子\n for n in range(start, len(sequence), 3):\n if sequence[n:n+3] in codonTable_DNA.keys():\n sequence_pro += codonTable_DNA[sequence[n:n+3]]\n # 遍历直到终止密码子\n if codonTable_DNA[sequence[n:n+3]] == '':\n if sequence_pro != '':\n pro_list.append(sequence_pro)\n break\n return pro_list\n\ndef fun(file_name):\n f = open(file_name, \"rt\").read().split(\"\\n\")\n sequence_dna = ''\n for line in f:\n #print(line)\n line = line.rstrip().replace(\"\\n\", \"\")\n if line.startswith('>'):\n continue\n sequence_dna += line\n #print(sequence_dna)\n sequence_rev = sequence_dna[::-1].replace('C', 'g').replace('G','c')\\\n .replace('T', 'a').replace('A', 't').upper()\n proteins = set(orf(sequence_dna) + orf(sequence_rev))\n for one in proteins:\n print(one)\n\n\nif __name__ == '__main__':\n #fun(\"test.txt\")\n fun(\"rosalind_orf.txt\")\n\n\n\n\n","repo_name":"yxj17173/Rosalind","sub_path":"1 Bioinformatics Stronghold/18 Open Reading Frames.py","file_name":"18 Open Reading Frames.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"30814142191","text":"# -*- encoding: utf-8 -*-\nfrom openerp import fields, models, exceptions, api, _\nimport base64\nimport csv\nimport cStringIO\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning\n\n\nclass Notadebito(models.Model):\n _name = \"nota.debito.factura\"\n\n fecha_nota = fields.Date(string=\"Fecha de Inicio\", required=True)\n periodo_id = fields.Many2one('account.period', 'Periodo')\n journal_id = fields.Many2one('account.journal', 'Diario Nota de Debito', required=True, domain=[('type', '=', 'sale')])\n name = fields.Char(string=\"Motivo Nota de Debito\", required=True)\n amount = fields.Float(\"Monto aplicar\", required=True)\n invoice_number = fields.Char(\"# de Factura\", readonly=True)\n\n def _get_invoice_number(self, cr, uid, context=None):\n active_id = context and context.get('active_id', False)\n if active_id:\n inv = self.pool.get('account.invoice').browse(cr, uid, active_id, context=context)\n return inv.number\n else:\n raise except_orm(_('Advertencia'), _('.No esta validada la factura, no se puede crear notas de debito sin estar en estado Validada las facturas!!!'))\n\n _defaults = {\n 'invoice_number': _get_invoice_number,\n }\n\n @api.one\n def invoice_nota_debito(self):\n journal_id = self.env['account.journal'].search([('type', '=', 'sale')], limit=1)\n obj_debit=self.env[\"account.invoice\"]\n inv_line_obj = self.env['account.invoice.line']\n active_id = self._context.get('active_id')\n qty = 1\n number_dedit_note = journal_id.sequence_id.number_next_actual\n if active_id:\n inv = self.env['account.invoice'].browse(active_id)\n if inv.residual < 0:\n raise except_orm(_('Warning'), _('!! Amount must be greater than zero !!'))\n\n values={\n 'partner_id':inv.partner_id.id,\n 'date_invoice':self.fecha_nota,\n 'account_id': inv.partner_id.property_account_receivable.id,\n 'type': 'out_invoice',\n 'journal_id': self.journal_id.id,\n 'origin':self.invoice_number,\n 'nota_debito': True,\n 'state':'draft',\n }\n invoice_id = obj_debit.create(values)\n if invoice_id:\n vals={\n 'name': self.name,\n 'invoice_id':invoice_id.id,\n 'account_id': self.journal_id.default_debit_account_id.id,\n 'price_unit': self.amount,\n 'quantity': qty,\n }\n inv_line_id = inv_line_obj.create(vals)\n\n else:\n raise except_orm(_('Advertencia'), _('.No se puede crear nota de dedito, consulte el administrador del sistema!!'))\n\n","repo_name":"hondurasopen/delivery_cost","sub_path":"models/nota_debito.py","file_name":"nota_debito.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29087859077","text":"import requests\r\nfrom keras_preprocessing.sequence import pad_sequences\r\nfrom tensorflow.keras.preprocessing.text import Tokenizer\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.layers import Embedding\r\nfrom tensorflow.python.keras.layers import LSTM\r\nimport numpy as np\r\nfrom tensorflow.python.keras.models import Sequential\r\nfrom tensorflow.python.keras.utils.np_utils import to_categorical\r\n\r\n\r\ndef locatePATH(PATH):\r\n try:\r\n global lines\r\n lines = open(PATH).read().split('\\n')\r\n except ValueError:\r\n return None\r\n except FileNotFoundError:\r\n return None\r\n\r\n\r\ndef clean_text(doc):\r\n tokens = doc.split()\r\n tokens = [word for word in tokens if word.isalpha()] # leave only alpha characters\r\n tokens = [word.lower() for word in tokens] # make it lowercase\r\n\r\n return tokens\r\n\r\n\r\ndef generate_text(model, tokenizer, text_seq_length, seed_text, n_words):\r\n text = []\r\n\r\n for _ in range(n_words):\r\n encoded = tokenizer.texts_to_sequences([seed_text])[0]\r\n encoded = pad_sequences([encoded], maxlen=text_seq_length, truncating='pre')\r\n y_predict = model.predict_classes(encoded)\r\n\r\n\r\n predicted_word = ''\r\n for word, index in tokenizer.word_index.items():\r\n if index == y_predict:\r\n predicted_word = word\r\n break\r\n seed_text = seed_text + ' ' + predicted_word\r\n text.append(predicted_word)\r\n return ' '.join(text)\r\n\r\n\r\n# get a text to learn from\r\ntext = requests.get('http://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt')\r\ndata = text.text.split('\\n') # get info line by line\r\ndata = data[253:] # start from index 253\r\ndata = \" \".join(data) # join them so that it converts to text\r\n\r\nftokens = clean_text(data)\r\n\r\n# create data sequence\r\n# use 100 sets of words to predict the next word\r\nlength = 50 + 1 # +1 for output\r\nlines = []\r\n\r\nfor i in range(length, len(ftokens)):\r\n seq = ftokens[i-length:i] # start from 51\r\n line = ' '.join(seq)\r\n lines.append(line)\r\n if i > 300000: # cap it so it executes faster\r\n break\r\n\r\n# tokenization\r\ntokenizer = Tokenizer()\r\ntokenizer.fit_on_texts(lines) # fit lines on tokenization -> unique words will be embedded as an integer\r\nsequences = tokenizer.texts_to_sequences(lines)\r\n\r\n# convert to numpy array\r\nsequences = np.array(sequences)\r\n\r\n# prepare for training\r\nx = sequences[:, :-1] # [all except the last]\r\ny = sequences[:, -1] # [only last]\r\n\r\nvocab_size = len(tokenizer.word_index) + 1\r\ny = to_categorical(y, num_classes=vocab_size)\r\n\r\n# Build LSTM model\r\nmodel = Sequential()\r\nseq_len = x.shape[1]\r\nmodel.add(Embedding(input_dim=vocab_size, output_dim=50, input_length=seq_len))\r\nmodel.add(LSTM(units=100, return_sequences=True))\r\nmodel.add(LSTM(units=100))\r\nmodel.add(Dense(units=100, activation='relu'))\r\nmodel.add(Dense(units=vocab_size, activation='softmax')) # 73\r\n\r\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # multiclass\r\nmodel.fit(x, y, batch_size=256, epochs=500)\r\nmodel.save('LSTM_TextGeneration.h5')\r\n\r\n# predict\r\ntestLine = \"Sometimes I like to go to the\"\r\nresult = generate_text(model, tokenizer, seq_len, testLine, 10) # 10 indicates how many words we want to predict\r\nprint(result)","repo_name":"SimonaMnv/nlp101","sub_path":"NLP_TextGeneration.py","file_name":"NLP_TextGeneration.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17300276295","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\ninstall_requires = open('requirements.txt').read().split()\n\nsetup(\n name='Showcase',\n version='0.3.4',\n author='James Rutherford',\n author_email='jim@jimr.org',\n url='https://github.com/jimr/Showcase',\n description='Like SimpleHTTPServer, only worse',\n long_description=open('README.rst').read(),\n license=\"MIT\",\n packages=find_packages(exclude=['tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=install_requires,\n test_suite='tests',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n ],\n)\n","repo_name":"jimr/Showcase","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38536384374","text":"#!/usr/bin/env python3\n\n\n'''\n18. Write a Python program to find palindromes in a given list of strings using Lambda.\nOrginal list of strings:\n['php', 'w3r', 'Python', 'abcd', 'Java', 'aaa']\nList of palindromes:\n['php', 'aaa']\n'''\n\n\ns_list = ['php', 'w3r', 'Python', 'abcd', 'Java', 'aaa']\npalindrome = lambda s : True if s == s[::-1] else False\np_list = list(filter(palindrome, s_list))\n\n\nprint(f\"\"\"Orginal list of strings:\n{s_list}\nList of palindromes:\n{p_list}\"\"\")\n","repo_name":"Hoklifter/studies","sub_path":"Python/Lambdas/18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27829958586","text":"number_of_tests = int(input())\n\n\ndef special_num(num):\n count = 0\n for digit in str(num):\n count += int(digit)\n if count % 4 == 0:\n return num\n else:\n return special_num(num + 1)\n\n\nfor test in range(0, number_of_tests):\n number = int(input())\n result = special_num(number)\n\n print(result)\n","repo_name":"kirilyanev/Coding-Websites-Practice","sub_path":"HackerEarth/Basic Programming/A-special-number.py","file_name":"A-special-number.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74895331043","text":"import argparse\nimport logging\nimport traceback\nfrom pathlib import Path\nfrom typing import Union\n\n\nfrom .actions.calculate import calculate_tree\nfrom .actions.compare import compare_trees\nfrom .actions.update import update_copy\n\nlogger = logging.getLogger(__name__)\n\nPathOrStr = Union[Path, str]\n\n\ndef main(args):\n try:\n parser = argparse.ArgumentParser(\n description=\"Tool for collecting MD5 hashes of directory trees and selective copying\",\n epilog=\"Note: if you apply --calculate on a directory within a tree that has already been calculated, then\"\n + \" that directory will be recalculated from scratch and the result updated within the parent tree records,\"\n + \" unless --new is also used.\",\n )\n parser.add_argument(\n \"--calculate\", type=str, default=None, help=\"Calculate the MD5 hash of the specified path and tree\"\n )\n parser.add_argument(\n \"--new\",\n dest=\"start_new\",\n action=\"store_true\",\n help=\"Do not utilize existing calculations.\",\n )\n parser.add_argument(\n \"--continue\",\n dest=\"continue_previous\",\n action=\"store_true\",\n help=\"Perform calculation only on unfinished parts of previous calculation.\",\n )\n parser.add_argument(\n \"--compare\",\n type=str,\n nargs=2,\n default=None,\n metavar=(\"A\", \"B\"),\n help=\"Compare checksum records for two paths and identify differences.\",\n )\n parser.add_argument(\n \"--depth\",\n type=int,\n default=2,\n help=\"Maximum depth for comparing two trees.\",\n )\n parser.add_argument(\n \"--update\",\n type=str,\n nargs=2,\n default=None,\n metavar=(\"source\", \"destination\"),\n help=\"Update the tree from [source] to [destination] where MD5s do not match.\",\n )\n parser.add_argument(\n \"--dry-run\", action=\"store_true\", help=\"A listing of all changes will be produced but no changes made.\"\n )\n parser.add_argument(\n \"--detail-files\", action=\"store_true\", help=\"Capture detailed file listings in the record file.\"\n )\n parser.add_argument(\"--v\", action=\"store_true\", help=\"Increase verbosity.\")\n args = parser.parse_args(args)\n\n if args.v:\n for handler in logging.getLogger().handlers:\n if isinstance(handler, logging.StreamHandler):\n handler.setLevel(logging.DEBUG)\n logging.getLogger().setLevel(logging.DEBUG)\n logger.setLevel(logging.DEBUG)\n logger.debug(f\"Debug-level verbosity enabled.\")\n\n if args.calculate is not None:\n calculate_tree(Path(args.calculate), args.continue_previous, args.start_new, args.detail_files)\n elif args.update is not None:\n source, destination = args.update\n update_copy(Path(source), Path(destination), dry_run=args.dry_run)\n elif args.compare is not None:\n source, destination = args.compare\n compare_trees(Path(source), Path(destination), depth=args.depth)\n else:\n raise RuntimeError(\"No command was recognized on the command-line.\")\n\n except Exception as ex:\n print(str(ex))\n logger.error(traceback.format_exc())\n","repo_name":"WileEMan/tree-inventory","sub_path":"tree_inventory/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40186626827","text":"\nfrom odoo import models, fields, api,tools, _\nfrom odoo import tools\nimport logging\n_logger = logging.getLogger(__name__)\n\n\n\nclass IrUiMenu(models.Model):\n _inherit = \"ir.ui.menu\"\n\n\n \n def hide_ti_menus_to_user(self, menu_data):\n \"\"\" Return the ids of the menu items hide to the user. \"\"\"\n menu_ids = []\n \n if self.env.user.sudo().has_group('ti_accounting_group_customization.group_user_2'):\n try:\n \n accounting_menu = self.env.ref('account.menu_finance_entries').id\n dashboard_menu = self.env.ref('account.menu_board_journal_1').id\n reporting_menu = self.env.ref('account.menu_finance_reports').id\n configuration_menu = self.env.ref('account.menu_finance_configuration').id\n \n menu_ids.extend([dashboard_menu,accounting_menu,configuration_menu, reporting_menu])\n except Exception as e:\n _logger.info(\"~~~~~~~~~~Exception~~~~~~~~%r~~~~~~~~~~~~~~~~~\",e)\n pass\n return menu_ids\n\n\n\n @api.model\n @tools.ormcache('frozenset(self.env.user.groups_id.ids)', 'debug')\n def _visible_menu_ids(self, debug=False):\n \"\"\" Return the ids of the menu items visible to the user. \"\"\"\n res = super(IrUiMenu, self)._visible_menu_ids(debug=debug)\n\n to_remove_menu_ids = self.hide_ti_menus_to_user(menu_data=res)\n res = res - set(to_remove_menu_ids)\n\n return res\n\n\n\nclass MailThread(models.AbstractModel):\n _inherit = 'mail.thread'\n\n\n @tools.ormcache('self.env.uid', 'self.env.su')\n def _get_tracked_fields(self):\n \"\"\" Return the set of tracked fields names for the current model. \"\"\"\n if self.__class__.__name__=='product.template':\n remove_fields = ('write_date','message_unread','create_uid','__last_update','activity_exception_icon','activity_summary','create_date','activity_type_icon','message_is_follower','write_uid','message_follower_ids','message_unread_counter','activity_type_id','activity_state')\n \n fields = {\n name\n for name, field in self._fields.items()\n if name not in remove_fields\n }\n return fields and set(self.fields_get(fields))\n else:\n return super(MailThread, self)._get_tracked_fields()\n \n","repo_name":"viswadamsbio/AMSBIO-ERP","sub_path":"ti_accounting_group_customization/models/inherit_ir_ui_menu.py","file_name":"inherit_ir_ui_menu.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36379101213","text":"ZAPPA_FILE_NAME = 'zappa_settings.json'\nFLASK_FILE = 'flask_api.py'\nTHAMPI_APP_FILE = 'thampi-app.py'\nTHAMPI_APP = 'thampi-app.app'\nPROJECT_NAME = 'project_name'\nREGION = 'aws_region'\nTHAMPI = 'thampi'\nMODEL_FILE = 'model.pkl'\n\nPROPERTIES_FILE = THAMPI + '.json'\nZAPPA_BUCKET = 's3_bucket'","repo_name":"scoremedia/thampi","sub_path":"thampi/core/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"73247722405","text":"import numpy as np\nfrom scipy.ndimage import rotate\n\n# Image size\nsize = 1001\n# Gaussian sigma\nsigma = 2.5\n\n# Create data for matrix\nx = np.arange(0, size, 1, int)\ny = x[:, np.newaxis]\n# Data in center\nx0 = y0 = size // 2\n\n# 2D Gaussian function\ng = np.exp(-((x-x0)**2 + (y-y0)**2) / sigma**2)\n\n# Gaussian vector\nv = g[x0][:]\n# Scale vector\nv = (255*(v - np.min(v))/np.ptp(v)).astype(int)\n# Show vector\n# plt.plot(v)\n# plt.show()\n\ndata = []\nfor i in range(0, 11):\n # Use vector to create gaussian line across all image\n array = np.zeros((size, 1), dtype=v.dtype) + v\n # Rotate\n angle = i/2\n array = rotate(array, angle)\n array = array[0:1001, 0:1001]\n data.append(array)\n\nnp.save(\"test.npy\", data)\n\n\n","repo_name":"gjbergues/Dial","sub_path":"simuline.py","file_name":"simuline.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38856392327","text":"from django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.utils.html import strip_tags\n\nfrom rest_framework import status\n\nfrom fcm_django.models import FCMDevice\nfrom firebase_admin.messaging import (\n Message,\n Notification as FCMNotification,\n)\nfrom smtplib import SMTPAuthenticationError, SMTPConnectError\n\nfrom prosit.celery import app\nfrom prosit.settings import EMAIL_HOST_USER, PROSIT_ADMIN_EMAIL, STAGING_DOMAIN\n\nfrom apps.notification.models import UserNotification\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n@app.task(name=\"Send Push notification\")\ndef send_push_notification(users, **kwargs):\n \"\"\"Send Push Notification to users\"\"\"\n\n devices = FCMDevice.objects.filter(user__in=users, active=True)\n devices.send_message(\n Message(\n notification=FCMNotification(\n title=kwargs.get(\"title\", \"\"), body=kwargs.get(\"message\", \"\")\n ),\n data=kwargs.get(\"data\"),\n )\n )\n\n user_notifications = [\n UserNotification(\n user=user,\n title=kwargs.get(\"title\", \"\"),\n message=kwargs.get(\"message\", \"\"),\n )\n for user in users\n ]\n\n notifications = UserNotification.objects.bulk_create(user_notifications)\n\n return \"Notifications Sent to all the users.\"\n\n\n@app.task(name=\"Send Email Notification\")\ndef send_email_notificaton(data, *args, **kwargs) -> str:\n \n mail_msg = (\n f\"

Name:

{data['name']}
\"\n f\"

Contact Number:

{data['phone_number']}
\"\n f\"

Health Code:

{data['health_code']}
\"\n )\n html_msg = render_to_string(\n 'email.html',\n {\n \"message\": mail_msg,\n \"url\": f\"{STAGING_DOMAIN}/admin/users/user{data['id']}\"\n }\n )\n msg = strip_tags(html_msg)\n\n response = {\n \"message\": \"Error while sending message. Please contact Admin\"\n }\n code = status.HTTP_401_UNAUTHORIZED\n try:\n send_mail(\n subject=\"New User awaiting Diet Plan assignment\",\n message=msg,\n html_message=html_msg,\n recipient_list=PROSIT_ADMIN_EMAIL,\n from_email=EMAIL_HOST_USER,\n fail_silently=False\n )\n\n except SMTPAuthenticationError as smtpautherr:\n logger.exception(smtpautherr)\n except SMTPConnectError as smtpconnerr:\n logger.exception(smtpconnerr)\n except Exception as e:\n logger.exception(e)\n code = status.HTTP_500_INTERNAL_SERVER_ERROR\n else:\n response[\"message\"] = \"Email Sent Successfully\"\n code = status.HTTP_200_OK\n \n return response, code\n","repo_name":"aarsh-zartek/prosit","sub_path":"apps/notification/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8009543449","text":"import os\nfrom sets import Set\n\ndic = Set()\nlocation = \"../CS-STILO/HMM/flex_v5/trace/\"\ndirs = os.listdir(location);\nfor directory in dirs:\n\tprint(\"doing \"+directory)\n\ttraces = open(location + directory, 'r').readlines()\n\tfor call in traces:\n\t\tsign = call[0: call.find('(')]\n\t\tdic.add(sign)\noutfile = open(location+\"trace.dic\", 'w')\ncounter = 0\nfor item in dic:\n\toutfile.write(item + \" \" + str(counter) + '\\n')\n\tcounter += 1","repo_name":"slugger-17/Exploit-Study-with-System-Call-Traces","sub_path":"scripts/build_dic.py","file_name":"build_dic.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12958255930","text":"class Solution(object):\n def findOcurrences(self, text, first, second):\n \"\"\"\n :type text: str\n :type first: str\n :type second: str\n :rtype: List[str]\n \"\"\"\n\n third_word=[]\n list_text= text.split()\n for i in range(0, len(list_text)):\n\n if ((i+2)<= len(list_text)-1) and (list_text[i] == first) and (list_text[i+1] == second):\n third_word.append(list_text[i+2])\n\n return third_word\n\n\ns= Solution()\nprint(s.findOcurrences(text = \"ypkk lnlqhmaohv lnlqhmaohv lnlqhmaohv ypkk ypkk ypkk ypkk ypkk ypkk lnlqhmaohv lnlqhmaohv lnlqhmaohv lnlqhmaohv ypkk ypkk ypkk lnlqhmaohv lnlqhmaohv ypkk\",\n first = \"lnlqhmaohv\", second = \"ypkk\"))\n","repo_name":"NiharikaGoel12/algo-practice","sub_path":"python/1078_occurence_after_bigram.py","file_name":"1078_occurence_after_bigram.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32846700898","text":"class Solution:\n def threeSum(self, nums):\n n = len(nums)\n nums.sort()\n ans = list()\n\n # 枚举 a\n for first in range(n): #只是对第一个和第二个指针做循环,第三个通过条件判断增减\n # 需要和上一次枚举的数不相同\n if first > 0 and nums[first] == nums[first - 1]:\n continue #继续下个循环的意思,如果现在的和上一个值一样就不用再算一遍了,继续前进\n # c 对应的指针初始指向数组的最右端\n third = n - 1\n target = -nums[first] #给出target然后寻找两数之和\n # 枚举 b\n for second in range(first + 1, n):\n # 需要和上一次枚举的数不相同\n if second > first + 1 and nums[second] == nums[second - 1]:\n continue #继续下个循环的意思,如果现在的和上一个值一样就不用再算一遍了,继续前进\n # 需要保证 b 的指针在 c 的指针的左侧\n while second < third and nums[second] + nums[third] > target:\n third -= 1 #第三个指针左移,如果需要第二个指针右移则通过循环实现\n # 如果指针重合,随着 b 后续的增加\n # 就不会有满足 a+b+c=0 并且 b 0:\n p.append(num)\n elif num < 0:\n n.append(num)\n else:\n z.append(num)\n\n # 2. Create a separate set for negatives and positives for O(1) look-up times\n N, P = set(n), set(p)\n\n # 3. If there is at least 1 zero in the list, add all cases where -num exists in N and num exists in P\n # i.e. (-3, 0, 3) = 0\n if z:\n for num in P:\n if -1 * num in N:\n res.add((-1 * num, 0, num))\n\n # 3. If there are at least 3 zeros in the list then also include (0, 0, 0) = 0\n if len(z) >= 3:\n res.add((0, 0, 0))\n\n # 4. For all pairs of negative numbers (-3, -1), check to see if their complement (4)\n # exists in the positive number set\n for i in range(len(n)):\n for j in range(i + 1, len(n)):\n target = -1 * (n[i] + n[j])\n if target in P:\n res.add(tuple(sorted([n[i], n[j], target])))\n\n # 5. For all pairs of positive numbers (1, 1), check to see if their complement (-2)\n # exists in the negative number set\n for i in range(len(p)):\n for j in range(i + 1, len(p)):\n target = -1 * (p[i] + p[j])\n if target in N:\n res.add(tuple(sorted([p[i], p[j], target])))\n\n return res\n\n def threeSum2(self, nums):\n ans = []\n n = len(nums)\n nums.sort() # 很重要,之后去重的逻辑关键,譬如说nums[i],如果排序了,就只需要看nums[i]和nums[i-1]是否相等,\n # 不会出现乱序的话有可能nums[i]和再之前的相等\n for i in range(n):\n left = i + 1\n right = n - 1\n if nums[i] > 0: # 如果排好序,第一个就大于0,那之后就没可能,跳出循环,返回空ans\n break\n if i >= 1 and nums[i] == nums[i - 1]: # 这个一定写在判断left right之前,如果i和i-1是一样的,就走下个循环。\n # 如果写在下面while里,会死循环,因为if成立,left又小于right,出不来\n continue\n while left < right:\n total = nums[i] + nums[left] + nums[right]\n if total > 0:\n right -= 1\n elif total < 0:\n left += 1\n else:\n ans.append([nums[i], nums[left], nums[right]])\n while left != right and nums[left] == nums[left + 1]: left += 1 # 和之前去重i的逻辑一样\n while left != right and nums[right] == nums[right - 1]: right -= 1\n left += 1\n right -= 1\n return ans\n\nif __name__ == '__main__':\n nums = [-2, 10, -2, 10, 10, 0, 2]\n solution = Solution()\n res = solution.threeSum2(nums)\n print(res)\n\n","repo_name":"chenximei/LeetCode","sub_path":"15 3Sum.py","file_name":"15 3Sum.py","file_ext":"py","file_size_in_byte":4877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19848876449","text":"from mock import Mock\nfrom domb.character.character import Character\nfrom domb.vec2d import Vec2d\nfrom domb.character.attribute import Attribute\n\narea = Mock(name=\"area\")\n\npotion = Mock(name=\"potion\")\npotion.get_name.return_value = \"potion\"\n\n\ndef create_char_in_area():\n char = Character()\n char.pos = Vec2d(2, 2)\n char.place(area)\n return char\n\n\ndef test_character_move():\n char = create_char_in_area()\n\n char.move(Vec2d(1, 1))\n assert char.pos == Vec2d(3, 3)\n\n\ndef test_character_fail_to_pick_up_item():\n area.pick_up_item.return_value = None\n char = create_char_in_area()\n\n char.pick_up_item()\n assert len(char.get_items()) == 0\n\n\ndef test_character_ACTUALLY_pick_up_item():\n area.pick_up_item.return_value = potion\n char = create_char_in_area()\n\n char.pick_up_item()\n assert len(char.get_items()) == 1\n\n\ndef test_set_attributes():\n char = create_char_in_area()\n\n char.set_attributes(\"Str 3, Dex 15, Con 10, Int 2, Wis 12, Cha 7\")\n assert char.str == Attribute(3)\n assert char.dex == Attribute(15)\n assert char.con == Attribute(10)\n assert char.int == Attribute(2)\n assert char.wis == Attribute(12)\n assert char.cha == Attribute(7)\n","repo_name":"juanibiapina/domb","sub_path":"test/character/test_character.py","file_name":"test_character.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31504503882","text":"r\"\"\"\nContains the Permute template.\n\"\"\"\n\nfrom pennylane.operation import Operation, AnyWires\nfrom pennylane.ops import SWAP\n\n\nclass Permute(Operation):\n r\"\"\"Applies a permutation to a set of wires.\n\n Args:\n permutation (list): A list of wire labels that represents the new ordering of wires\n after the permutation. The list may consist of integers or strings, so long as\n they match the labels of ``wires``.\n wires (Iterable or Wires): Wires that the permutation acts on. Accepts an iterable\n of numbers or strings, or a Wires object.\n\n Raises:\n ValueError: if inputs do not have the correct format\n\n **Example**\n\n .. code-block:: python\n\n import pennylane as qml\n\n dev = qml.device('default.qubit', wires=5)\n\n @qml.qnode(dev)\n def apply_perm():\n # Send contents of wire 4 to wire 0, of wire 2 to wire 1, etc.\n qml.templates.Permute([4, 2, 0, 1, 3], wires=dev.wires)\n return qml.expval(qml.PauliZ(0))\n\n See \"Usage Details\" for further examples.\n\n .. details::\n :title: Usage Details\n\n As a simple example, suppose we have a 4-qubit device with wires labeled\n by the integers ``[0, 1, 2, 3]``. We apply a permutation to shuffle the\n order to ``[3, 2, 0, 1]`` (i.e., the qubit state that was previously on\n wire 3 is now on wire 0, the one from 2 is on wire 1, etc.).\n\n .. code-block:: python\n\n dev = qml.device('default.qubit', wires=4)\n\n @qml.qnode(dev)\n def apply_perm():\n qml.Permute([3, 2, 0, 1], dev.wires)\n return qml.expval(qml.PauliZ(0))\n\n >>> print(qml.draw(apply_perm, expansion_strategy=\"device\")())\n 0: ─╭SWAP─────────────┤ \n 1: ─│─────╭SWAP───────┤\n 2: ─│─────╰SWAP─╭SWAP─┤\n 3: ─╰SWAP───────╰SWAP─┤\n\n ``Permute`` can also be used with quantum tapes. For example, suppose we\n have a tape with 5 wires ``[0, 1, 2, 3, 4]``, and we'd like to reorder them\n so that wire 4 is moved to the location of wire 0, wire 2 is moved to the\n original location of wire 1, and so on.\n\n .. code-block:: python\n\n import pennylane as qml\n\n op = qml.Permute([4, 2, 0, 1, 3], wires=[0, 1, 2, 3, 4])\n tape = qml.tape.QuantumTape([op])\n\n >>> tape_expanded = qml.tape.tape.expand_tape(tape)\n >>> print(qml.drawer.tape_text(tape_expanded, wire_order=range(5)))\n 0: ─╭SWAP───────────────────┤\n 1: ─│─────╭SWAP─────────────┤\n 2: ─│─────╰SWAP─╭SWAP───────┤\n 3: ─│───────────│─────╭SWAP─┤\n 4: ─╰SWAP───────╰SWAP─╰SWAP─┤\n\n ``Permute`` can also be applied to wires with arbitrary labels, like so:\n\n .. code-block:: python\n\n wire_labels = [3, 2, \"a\", 0, \"c\"]\n\n dev = qml.device('default.qubit', wires=wire_labels)\n\n @qml.qnode(dev)\n def circuit():\n qml.Permute([\"c\", 3,\"a\",2,0], wires=wire_labels)\n return qml.expval(qml.PauliZ(\"c\"))\n\n The permuted circuit is:\n\n >>> print(qml.draw(circuit, expansion_strategy=\"device\")())\n 3: ─╭SWAP─────────────┤\n 2: ─│─────╭SWAP───────┤\n 0: ─│─────│─────╭SWAP─┤\n c: ─╰SWAP─╰SWAP─╰SWAP─┤ \n\n It is also possible to permute a subset of wires by\n specifying a subset of labels. For example,\n\n .. code-block:: python\n\n wire_labels = [3, 2, \"a\", 0, \"c\"]\n\n dev = qml.device('default.qubit', wires=wire_labels)\n\n @qml.qnode(dev)\n def circuit():\n # Only permute the order of 3 of them\n qml.Permute([\"c\", 2, 0], wires=[2, 0, \"c\"])\n return qml.expval(qml.PauliZ(\"c\"))\n\n will permute only the second, third, and fifth wires as follows:\n\n >>> print(qml.draw(circuit, expansion_strategy=\"device\", show_all_wires=True)())\n 3: ─────────────┤\n 2: ─╭SWAP───────┤\n a: ─│───────────┤\n 0: ─│─────╭SWAP─┤\n c: ─╰SWAP─╰SWAP─┤ \n\n \"\"\"\n\n num_wires = AnyWires\n grad_method = None\n\n def __init__(self, permutation, wires, id=None):\n if len(permutation) <= 1 or len(wires) <= 1:\n raise ValueError(\"Permutations must involve at least 2 qubits.\")\n\n # Make sure the lengths of permutation and wires are the same\n if len(permutation) != len(wires):\n raise ValueError(\"Permutation must specify outcome of all wires.\")\n\n # Permutation order must contain all unique values\n if len(set(permutation)) != len(permutation):\n raise ValueError(\"Values in a permutation must all be unique.\")\n\n # Make sure everything in the permutation has an associated label in wires\n for label in permutation:\n if label not in wires:\n raise ValueError(f\"Cannot permute wire {label} not present in wire set.\")\n\n self._hyperparameters = {\"permutation\": permutation}\n super().__init__(wires=wires, id=id)\n\n @property\n def num_params(self):\n return 0\n\n @staticmethod\n def compute_decomposition(wires, permutation): # pylint: disable=arguments-differ\n r\"\"\"Representation of the operator as a product of other operators.\n\n .. math:: O = O_1 O_2 \\dots O_n.\n\n\n\n .. seealso:: :meth:`~.Permute.decomposition`.\n\n Args:\n wires (Any or Iterable[Any]): wires that the operator acts on\n permutation (list[Any]): A list of wire labels that represents the new ordering of wires\n after the permutation.\n\n Returns:\n list[.Operator]: decomposition of the operator\n \"\"\"\n op_list = []\n\n # Temporary storage to keep track as we permute\n working_order = wires.tolist()\n\n # Go through the new order and shuffle things one by one\n for idx_here, here in enumerate(permutation):\n if working_order[idx_here] != here:\n # Where do we need to send the qubit at this location?\n idx_there = working_order.index(permutation[idx_here])\n\n # SWAP based on the labels of the wires\n op_list.append(SWAP(wires=wires.subset([idx_here, idx_there])))\n\n # Update the working order to account for the SWAP\n working_order[idx_here], working_order[idx_there] = (\n working_order[idx_there],\n working_order[idx_here],\n )\n return op_list\n","repo_name":"PennyLaneAI/pennylane","sub_path":"pennylane/templates/subroutines/permute.py","file_name":"permute.py","file_ext":"py","file_size_in_byte":7118,"program_lang":"python","lang":"en","doc_type":"code","stars":1965,"dataset":"github-code","pt":"52"} +{"seq_id":"3274597383","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('',views.home,name='home'),\n path('detail/',views.ProductDetailView.as_view(),name='detail'),\n path('category_product/',views.ProductOfCategoryListView.as_view(),name='category_product'),\n path('search/',views.search_product.as_view(),name='search'),\n \n]\n","repo_name":"alitsicode/bookshop","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15424041558","text":"import wx \nimport time \n\n\n# This is a test for a scrollable canvas, with some top and left sliding \n# sub-windows. Similar to the way a spreadsheet works... \n\nclass TriPaneWindow(wx.ScrolledWindow): \n \"\"\" \n This is the main frame holding the other windows and the top level of the \n application \n \"\"\" \n \n def __init__(self, *arguments, **keywords): \n \"\"\" \n Constructor \n \"\"\" \n wx.ScrolledWindow.__init__ (self, *arguments, **keywords) \n self.SetAutoLayout(True) \n self.SetSizer(self.buildSizer()) \n self.SetTargetWindow(self.mainPanel) \n self.SetScrollRate(20,20) \n\n #Events \n #wx.EVT_SIZE(self, self.OnSize) \n self.Bind(wx.EVT_SCROLLWIN, self.OnScrollWindowEvent) \n self.Bind(wx.EVT_LEFT_UP, self.OnClickEvent) \n \n def OnClickEvent(self, event): \n \"\"\" \n For Debug... \n \"\"\" \n print() \n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition())) \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize())) \n event.Skip() \n \n \n def buildSizer(self): \n \"\"\" \n Create the 3 sub windows and the sizer that holds them together. \n \"\"\" \n #Create the panels \n self.topPanel = MyCanvas(self, wx.RED, 40,40, 'Top', True, False) \n self.leftPanel = MyCanvas(self, wx.GREEN, 80,80, 'Left', False, True) \n self.mainPanel = MyCanvas(self, wx.WHITE, 100,100, 'Main', True, True) \n self.mainPanel.topPanel = self.topPanel \n self.mainPanel.leftPanel = self.leftPanel \n self.topPanel.mainPanel = self.mainPanel\n self.leftPanel.mainPanel = self.mainPanel\n self.mainPanel.mainPanel = self.mainPanel\n self.topPanel.parentPanel = self\n self.leftPanel.parentPanel = self\n self.mainPanel.parentPanel = self\n \n #Create the sizer \n sizer = wx.FlexGridSizer(2,2,0,0) \n \n #Add the panels to the sizers \n sizer.Add((100,30), 0, wx.EXPAND) \n sizer.Add(self.topPanel, 0, wx.EXPAND) \n sizer.Add(self.leftPanel, 0, wx.EXPAND) \n sizer.Add(self.mainPanel, 0, wx.EXPAND) \n sizer.AddGrowableCol(1) \n sizer.AddGrowableRow(1) \n \n return sizer \n \n def SetCanvasSize(self, width, height): \n \"\"\" \n Set the size of the 3 panes as follow: \n - main = width, height \n - top = width, 40 \n - left = 80, height \n \"\"\" \n self.mainPanel.SetVirtualSize(wx.Size(width,height)) \n (w,h) = self.topPanel.GetSize() \n self.topPanel.SetVirtualSize(wx.Size(width,h)) \n (w,h) = self.leftPanel.GetSize() \n self.leftPanel.SetVirtualSize(wx.Size(w,height)) \n \n \n def OnScrollWindowEvent(self, event): \n \"\"\" \n OnScrollWindow Event Callback. This should let the main panel scroll in \n both direction but transmit the vertical scrolling to the left panel \n and the horizontal scrolling to the top window \n \"\"\"\n sx,sy = self.GetScrollPixelsPerUnit()\n if event.GetOrientation() == wx.HORIZONTAL:\n dx = event.GetPosition()\n dy = self.GetScrollPos(wx.VERTICAL)\n else:\n dx = self.GetScrollPos(wx.HORIZONTAL)\n dy = event.GetPosition()\n \n pos = (dx ,dy) \n print(\"scrolling...\" + str(pos) + str(event.GetPosition()))\n # self.mainPanel.Scroll(dx, dy) \n # self.topPanel.Scroll(dx, 0) \n # self.leftPanel.Scroll(0, dy) \n event.Skip() \n\n\nclass MyCanvas(wx.ScrolledCanvas): \n \"\"\" \n Custom colored panel for testing \n \"\"\" \n def __init__(self, parent, colour, width, height, name = \"\", dx=True, dy=True): \n wx.ScrolledCanvas.__init__(self, parent, -1) \n self.SetBackgroundColour(colour) \n self.SetSize(wx.Size(width, height)) \n self.SetVirtualSize(wx.Size(width, height)) \n self.use_x = 1 if dx else 0\n self.use_y = 1 if dy else 0\n self.Bind(wx.EVT_LEFT_DOWN, self.OnClickEvent) \n self.Bind(wx.EVT_PAINT, self.OnPaint) \n self.Bind(wx.EVT_SIZE, self.on_size) \n\n def on_size(self, event ): \n \"\"\" \n OnSize event callback. Currently not used \n \"\"\" \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n size = self.GetSize()\n vsize = self.GetVirtualSize()\n if self.use_x and self.use_y:\n # main window, no adjustment\n pass\n elif self.use_x:\n # scrolls in X dir\n self.SetVirtualSize(vsize.x, size.y)\n else:\n self.SetVirtualSize(size.x, vsize.y)\n\n #self.Layout() \n\n def OnPaint(self, event):\n\n dc = wx.PaintDC(self)\n #self.parentPanel.PrepareDC(dc)\n size = self.GetVirtualSize()\n\n s = \"Size: %d x %d\"%(size.x, size.y)\n vbX, vbY = self.parentPanel.GetViewStart()\n posX, posY = self.parentPanel.CalcUnscrolledPosition (0, 0)\n vbX, vbY = vbX * self.use_x, vbY * self.use_y\n posX, posY = posX * self.use_x, posY * self.use_y\n # vbX, vbY = self.GetViewStart()\n # posX, posY = self.CalcUnscrolledPosition (0, 0) \n upd = wx.RegionIterator(self.GetUpdateRegion()) # get the update rect list\n r = []\n while upd.HaveRects():\n rect = upd.GetRect()\n\n # Repaint this rectangle\n #PaintRectangle(rect, dc)\n r.append(\"rect: %s\" % str(rect))\n upd.Next()\n print(s, (posX, posY), (vbX, vbY), \" \".join(r))\n dc.SetLogicalOrigin(posX, posY)\n\n dc.SetFont(wx.NORMAL_FONT)\n w, height = dc.GetTextExtent(s)\n height += 3\n dc.SetBrush(wx.WHITE_BRUSH)\n dc.SetPen(wx.WHITE_PEN)\n dc.DrawRectangle(0, 0, size.x, size.y)\n dc.SetPen(wx.LIGHT_GREY_PEN)\n dc.DrawLine(0, 0, size.x, size.y)\n dc.DrawLine(0, size.y, size.x, 0)\n dc.DrawText(s, (size.x-w)/2, (size.y-height*5)/2)\n \n def OnClickEvent(self, event): \n print() \n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition())) \n print(\"ViewStart \" + str(self.GetViewStart())) \n print(\"Size \" + str(self.GetSize())) \n print(\"VirtualSize \" + str(self.GetVirtualSize())) \n\n\nclass MyApp(wx.App): \n \"\"\" \n Simple Application class for testing \n \"\"\" \n def OnInit(self): \n \"\"\" \n Initialize the Application \n \"\"\" \n #This is the frame as I want to use it, with a tri-pane scroll window \n #However, the information sent to the sub-window is incorrect, so the \n #OnPaint callback draws the wrong area on screen... \n id = wx.NewId() \n frame = wx.Frame(None, id, \"Test Tri-pane frame\" ) \n scroll = TriPaneWindow(frame, wx.NewId()) \n scroll.SetCanvasSize(3000, 1000) \n scroll.SetScrollRate(20,20) \n frame.Show() \n # self.SetTopWindow(frame) \n \n print(\"wx.VERSION = \" + wx.VERSION_STRING) \n return True \n \n#For testing \nif __name__ == '__main__': \n app = MyApp(False) \n app.MainLoop() \n","repo_name":"robmcmullen/wx4demos","sub_path":"scrolltarget.py","file_name":"scrolltarget.py","file_ext":"py","file_size_in_byte":7288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26341955405","text":"class ListNode:\n def __init__(self, x):\n self.value = x\n self.next = None\n\n\nclass Solution:\n def mergeTwoLists(self, a, b):\n \"\"\"\n :param b:\n :param a:\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n if a and b:\n if a.value > b.value:\n a, b = b, a\n a.next = self.mergeTwoLists(a.next, b)\n return a or b\n","repo_name":"zqbinggong/LeetCode","sub_path":"top100liked/easy/MergeTwoSortedLists.py","file_name":"MergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32979812768","text":"import inspect\nfrom importlib import metadata\nfrom pathlib import Path\n\nfrom loguru import logger\nfrom PIL.Image import Image\n\nfrom music_bg.argparse import parse_args\nfrom music_bg.config import Config\nfrom music_bg.context import Context\nfrom music_bg.dbus.loop import run_loop\nfrom music_bg.logging import init_logger\n\n\ndef generate_config(config_path: Path) -> None:\n \"\"\"\n Generate default config file.\n\n :param config_path: path to config.\n \"\"\"\n if config_path.exists():\n print(f\"Config {config_path} already exists\")\n return\n Config().save(config_path)\n print(f\"Config successfully generated at {config_path}\")\n\n\ndef show_version() -> None:\n \"\"\"Show installed version of a Music Background.\"\"\"\n version = metadata.version(\"music_bg\")\n print(f\"Music background v{version}\")\n\n\ndef print_processors(context: Context) -> None: # noqa: WPS213, WPS210, WPS210, C901\n \"\"\"\n Print information about available image processors.\n\n :param context: music_bg context.\n \"\"\"\n print(\" Processors \".center(80, \"#\"))\n\n for name, func in context.processors_map.items():\n print(\"-\" * 80)\n print(f\"name: {name}\")\n print(\"type: processor\")\n args = inspect.signature(func)\n custom_args = []\n for parameter in args.parameters.values():\n if parameter.annotation != Image:\n custom_args.append(parameter)\n if custom_args:\n print()\n print(\" args \".center(20, \"=\"))\n for arg in custom_args:\n arg_info = f\"* {arg.name}\"\n if arg.annotation != arg.empty:\n arg_info = f\"{arg_info}: {arg.annotation}\"\n if arg.default == arg.empty:\n arg_info = f\"{arg_info} (required)\"\n print(arg_info)\n doc = inspect.getdoc(func)\n if doc is not None:\n print()\n print(\" doc \".center(20, \"=\"))\n print(doc)\n\n\ndef print_variables(context: Context) -> None:\n \"\"\"\n Print information about available variables.\n\n :param context: current mbg context.\n \"\"\"\n print(\" Variables \".center(80, \"#\"))\n\n for name, func in context.variables_providers.items():\n print(\"-\" * 80)\n print(f\"name: {name}\")\n print(\"type: variable\")\n doc = inspect.getdoc(func)\n if doc is not None:\n print()\n print(\" doc \".center(20, \"=\"))\n print(doc)\n\n\ndef show_info(\n context: Context,\n show_processors: bool = False,\n show_variables: bool = False,\n) -> None:\n \"\"\"\n Show information about current context.\n\n This function shows available processors\n and variable providers.\n\n :param context: mbg context.\n :param show_processors: show information about processors.\n :param show_variables: show information about variables.\n \"\"\"\n show_version()\n if show_processors:\n print()\n print_processors(context)\n if show_variables:\n print()\n print_variables(context)\n\n\ndef main() -> None:\n \"\"\"The main entrypoint of a program.\"\"\"\n logger.remove()\n args = parse_args()\n if args.version:\n show_version()\n return\n if args.subparser_name == \"gen\":\n generate_config(args.config_path)\n return\n context = Context(args.config_path, args.reload)\n if args.subparser_name == \"info\":\n show_info(\n context,\n show_processors=args.show_processors,\n show_variables=args.show_vars,\n )\n return\n init_logger(context.config.log_level)\n logger.debug(f\"Using config {args.config_path}\")\n try:\n run_loop(context)\n except KeyboardInterrupt:\n logger.info(\"Goodbye!\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"music-bg/music_bg","sub_path":"music_bg/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"13163336146","text":"'''\nCreated on Feb 17, 2013\n\n@author: jyotiPandey\n'''\n\nimport re\nfrom collections import Counter\n'''\nfile operations\nparam: array of file names\n'''\n\ndef addOneSmoothingUnigram(probability_list, vocab_length, corpus_length):\n return [(ngram[0], float(ngram[1] + 1) /\n (corpus_length + vocab_length)) \n for ngram in probability_list]\n \ndef addOneSmoothingBigram(unigram_dict, probability_list, vocab_length, corpus_length):\n return [(ngram[0], float(ngram[1] + 1.0) /\n (float(unigram_dict[ngram[0].split()[0]]) + vocab_length)) \n for ngram in probability_list]\n\ndef wittenBellSmoothingBigram(ngram_list, words, corpus_data):\n witten_smooth_prob = {}\n for data in corpus_data:\n if(corpus_data[data][3] == 0):\n witten_smooth_prob[data] = float(corpus_data[data][0] / float(corpus_data[data][1] + corpus_data[data][2]))\n else :\n witten_smooth_prob[data] = float(corpus_data[data][3] / float(corpus_data[data][1] + corpus_data[data][2]))\n return witten_smooth_prob\n \ndef file_operations(filenames):\n # process each file individually\n for filename in filenames:\n #open file in read mode\n \n lines = open(filename, 'r').read()\n sentences = re.compile(r'(?<=[.!?;])\\s*').split(lines)\n sentences_with_tag = '';\n \n for sentence in sentences:\n sentences_with_tag += ' '+sentence+' '\n # Split here for full stop and quotation marks\n words = sentences_with_tag.split()\n tempWordsList = sentences_with_tag.split()\n #Perform logic to save ---\n #1. T(wi-1) - Vocab after wi-1\n #2. N(wi-1) - Tokens after this\n #3. Z(wi-1) - Number of bigrams in current \n # data set starting with wi-1 that do not occur in the training data\n \n #********************Vocab after wi-1************************\n \n unigram_list = list(Counter(words).items())\n len_unigram = len(unigram_list)\n \n unigram_prob = unigram_list\n unigram_prob = [(unigram[0], float(unigram[1]/len_unigram)) for unigram in unigram_prob]\n print (\"******************ADD ONE SMOOTHING OF UNIGRAM***********************\")\n unigram_prob_smooth_1 = addOneSmoothingUnigram(unigram_prob, len_unigram, words.__len__())\n for unigram in unigram_prob_smooth_1:\n print (unigram[0], '\\t\\t' , unigram[1])\n \n index_r = 0\n bi_words = words\n while index_r < len(bi_words):\n if index_r + 1 < len(bi_words):\n bi_words[index_r] += \" \" + bi_words[index_r+1]\n index_r += 1\n \n bigram_list = list(Counter(bi_words).items())\n len_bigram = len(bigram_list)\n \n bigram_prob = bigram_list\n print (\"******************ADD ONE SMOOTHING OF BIGRAM***********************\")\n unigram_dict = {key: value for (key, value) in unigram_list}\n bigram_prob = [(bigram[0], bigram[1] / float(unigram_dict [bigram[0].split()[0]])) for bigram in bigram_prob]\n bigram_prob_smooth_1 = addOneSmoothingBigram(unigram_dict, bigram_prob, len_unigram, words.__len__())\n for bi in bigram_prob_smooth_1 :\n print (bi[0], '\\t\\t' , bi[1])\n \n print (\"**********SMOOTHING OF WITTEN AND BELL SMOOTHING**************\")\n list1 = {}\n n_vocab_length = len_unigram\n \n for i in range (0, len(words)):\n #Calculate the vocab after this word\n laterWords = list(Counter(tempWordsList).items())\n count = 0\n for first_word in bigram_list:\n if(first_word[0].split()[0] == words[i]):\n count = count + 1\n list1[words[i]] = len(words) - i, len(laterWords), count , first_word[1]\n \n tempWordsList.pop()\n print (wittenBellSmoothingBigram(bigram_list, tempWordsList, list1))\n \ndef main():\n file_operations(['small.txt'])\n \nmain()","repo_name":"heratgandhi/nlp-project","sub_path":"bell_witten.py","file_name":"bell_witten.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34847463626","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport time\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\n\n#브라우저 꺼짐 방지\nchrome_options = Options()\nchrome_options.add_experimental_option('detach', True)\n\n#기본 비어있는 리스트를 만듬. 여기에 값들을 저장할 예정\nli_task = []\nli_title = []\nli_notice = []\nli_demand = []\n\n\n\n#총 10페이지까지(1페이지에 10개, 10*10 100개를 크롤링할 예정)할 예정이라 for 문 돌림\n#이때 url을 살펴보면 페이지 넘버에 따라 뒤 숫자가 바뀌는 유형이었음. 만약에 페이지 넘버가 안바뀐다면? selenium의 click매소드를 활용해서 계속 페이지를 넘겨줬을 예정\nfor i in range(1, 31):\n url = f'https://www.g2b.go.kr:8101/ep/tbid/tbidList.do?area=&bidNm=%B0%F8%B0%A3%C1%A4%BA%B8&bidSearchType=1&fromBidDt=2023%2F01%2F07&fromOpenBidDt=&instNm=&maxPageViewNoByWshan=2&radOrgan=1®Yn=Y&searchDtType=1&searchType=1&taskClCds=&toBidDt=2023%2F07%2F10&toOpenBidDt=¤tPageNo={i}'\n\n response = requests.get(url)\n html = response.text\n soup = BeautifulSoup(html, 'html.parser')\n contents = soup.find_all('tbody') #tbody에 id나 class 정의가 없었음. 딱 1개여서.\n infos = contents[0].find_all('tr')\n\n for info in infos: #10개의 infos를 하나씩 분리하는 과정. 내가 필요한 것만 뽑았음. 다른것도 뽑을 수 있음\n task = info.select_one('td:nth-of-type(1)').text #업무 추출\n\n if task == '용역':\n title = info.select_one('td:nth-of-type(4)').text #공고명\n notice = info.select_one('td:nth-of-type(5)').text #공고기관\n demand = info.select_one('td:nth-of-type(6)').text #수요기관\n li_task.append(task) #빈 리스트에 업무 하나씩 넣기\n li_title.append(title) #빈 리스트에 공고명 하나씩 넣기\n li_notice.append(notice)#빈 리스트에 공고기관 하나씩 넣기\n li_demand.append(demand) #빈 리스트에 수요기관 하나씩 넣기\n else:\n break\n\n \n \n\n\n\n \n#끝났으니까 csv로 추출하기.\ndf = pd.DataFrame({\n '업무': li_task,\n '공고명': li_title,\n '공고기관': li_notice,\n '수요기관': li_demand\n})\n\ndf.to_csv('나라장터re.csv', encoding=\"utf-8-sig\",index = False)\n \n\n","repo_name":"Blockrixh/Crawling","sub_path":"나라장터_requests.py","file_name":"나라장터_requests.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1218525555","text":"\"\"\"Reading the Contents of a File (chained methods)\"\"\"\n\n\nfrom pathlib import Path\n\npath = Path(\n r'C:/Users/parsa/VSCode/PCC/Chapter_10/Reading from a File/pi_digits.txt')\n\ncontents = path.read_text().rstrip()\nprint(contents)\n\n# We can strip the trailing newline character when we read the contents of the file,\n# by applying the rstrip() method immediately after calling read_text():\n\n# contents = path.read_text().rstrip()\n","repo_name":"RunnerOnFoot/PCC","sub_path":"Chapter_10/Reading from a File/file_reader_2_without_blank_immediately.py","file_name":"file_reader_2_without_blank_immediately.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38418702254","text":"import sys\n\ndef fib(n):\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return fib(n-1) + fib(n-2)\n\nwith open(sys.argv[1], 'r') as f:\n print('\\n'.join(str(fib(int(line.strip()))) for line in f))\n","repo_name":"rjeli/code_eval_challenges","sub_path":"easy/fib_series.py3","file_name":"fib_series.py3","file_ext":"py3","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29276129486","text":"from __future__ import print_function\nimport argparse\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport pickle\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import StepLR\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\n\ndef test(args, model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=14, metavar='N',\n help='number of epochs to train (default: 14)')\n parser.add_argument('--lr', type=float, default=1.0, metavar='LR',\n help='learning rate (default: 1.0)')\n parser.add_argument('--gamma', type=float, default=0.7, metavar='M',\n help='Learning rate step gamma (default: 0.7)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n parser.add_argument('--save-test-marginals', action='store_true', default=False,\n help='For Saving the marginal scores of the Model on the test set')\n args = parser.parse_args()\n\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n train_loader = torch.utils.data.DataLoader(\n datasets.MNIST('./data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n test_set = datasets.MNIST('./data', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n test_loader = torch.utils.data.DataLoader(test_set, \n batch_size=args.test_batch_size, shuffle=True, **kwargs)\n\n model = Net().to(device)\n optimizer = optim.Adadelta(model.parameters(), lr=args.lr)\n\n scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)\n for epoch in range(1, args.epochs + 1):\n train(args, model, device, train_loader, optimizer, epoch)\n test(args, model, device, test_loader)\n scheduler.step()\n\n if args.save_model:\n torch.save(model.state_dict(), \"mnist_cnn.pt\")\n\n if args.save_test_marginals:\n img_logits = [[],[],[],[],[],[],[],[],[],[]]\n img_indces = [[],[],[],[],[],[],[],[],[],[]]\n test_loader = torch.utils.data.DataLoader(test_set, batch_size=1, shuffle=False)\n\n for idx, (data, target) in enumerate(test_loader):\n with torch.no_grad():\n label = target.data.numpy()[0]\n logits = model.forward(data)\n img_logits[label].append(-logits.data.numpy().squeeze())\n img_indces[label].append(idx)\n\n with open(\"MNIST_test_marginal\",\"wb\") as f:\n pickle.dump( img_logits , f)\n # restore with img_logits = pickle.load(open(\"MNIST_test_marginal\", \"rb\" ))\n with open(\"MNIST_test_indices\",\"wb\") as f:\n pickle.dump( img_indces , f)\n # restore with img_indces = pickle.load(open(\"MNIST_test_indices\", \"rb\" ))\n\n data = iter(torch.utils.data.DataLoader(test_set, batch_size=1, shuffle=False))\n images = list(map(lambda x: x[0].reshape(28,28), data))\n white = np.zeros((28,28))\n mpl.rcParams['toolbar'] = 'None' \n plt.style.use('dark_background')\n fig, axs = plt.subplots(9, 9,figsize=(5,5))\n for i in range(9):\n for j in range(9):\n axs[i][j].set_axis_off()\n if (i==j):\n axs[i][j].imshow(white,cmap=plt.get_cmap('Greys'))\n else:\n axs[i][j].imshow(images[i*9+j],cmap=plt.get_cmap('Greys'))\n fig.tight_layout(pad=0.2,h_pad=0.2,w_pad=0.2) \n plt.show()\n\nif __name__ == '__main__':\n main()\n","repo_name":"toulbar2/toulbar2","sub_path":"web/TUTORIALS/sudoku/MNIST_train.py","file_name":"MNIST_train.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"52"} +{"seq_id":"18986144936","text":"try:\n import random as rnd\n import os\n import glob\n\n # Импорт функций из подпапки \"FunctionalFolder\"\n import FunctionalFolder.Minimaze as Minimaze\n import FunctionalFolder.Output as Output\n import FunctionalFolder.Input as Input\n\n # Чистим min.log \n with open(\"min.log\", \"w\") as log_file:\n log_file.write(\"\")\n\n rnd.seed()\n\n Nframe, Nbest = Input.get_nframe_nbest()\n\n ediff = Input.get_ediff()\n\n path_remove = os.path.join(os.path.abspath(os.path.dirname(__file__)))\n\n prefix_in, prefix_out = Input.get_prefix()\n\n \n\n base_directory = os.path.join(path_remove, \"Result\")\n prefix_base = \"Result\"\n prefix_out = Input.get_next_available_prefix(base_directory, prefix_base)\n \n\n Input.copy_data(path_remove, prefix_in, prefix_out)\n\n pe_str = {}\n\n # Список для хранения имен файлов с исходными структурами\n in_structures = []\n for file in glob.glob(f'./{prefix_in}/*.vasp'): \n in_structures.append(file)\n\n # Подсчет количества структур и обработка каждой структуры\n count_structures = 0\n for name_structure in in_structures:\n count_structures += 1\n pe_str = Minimaze.check_structure(name_structure, count_structures, Nbest, pe_str, ediff, prefix_out)\n \n # Запись результатов и удаление старых файлов через каждые Nframe структур\n if count_structures % Nframe == 0:\n Output.write_energy_table(pe_str, prefix_out)\n Output.remove_files(pe_str, path_remove, prefix_out)\n Output.write_check_point(count_structures, prefix_out)\n\n # Запись окончательных результатов и удаление старых файлов\n Output.write_energy_table(pe_str, prefix_out)\n Output.remove_files(pe_str, path_remove, prefix_out)\n\n print('Расчет оптимизированых структур окончен')\n \n pass\nexcept KeyboardInterrupt:\n print(\"Программа прервана пользователем\")","repo_name":"SergeiNikolenko/DeepMD_crystal_generator","sub_path":"find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"10856618015","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\n\n#https://summerofcode.withgoogle.com/archive/2019/organizations/\nfrom bs4 import BeautifulSoup\nimport requests\nyear=str(input(\"Enter the year \"))\nurl=\"https://summerofcode.withgoogle.com/archive/{}/organizations/\".format(year)\nnametech=str(input(\"Enter Name of the technology that you want to see \"))\nr=requests.get(url)\n#print(r.url)\nsoup=BeautifulSoup(r.content,\"html.parser\")\n#r.content\norgs = soup.findAll('li', attrs = {\"class\": \"organization-card__container\"})\n#print(orgs)\ncount=1\ncount2=0\nfor org in orgs:\n nm=org.find(\"h4\",attrs={\"class\":\"organization-card__name\"})\n name=nm.text\n label=org.find(\"a\",attrs={\"class\":\"organization-card__link\"})\n link=label[\"href\"]\n \n link2=str(\"https://summerofcode.withgoogle.com\"+link)\n \n count+=1\n r2=requests.get(link2)\n soup2=BeautifulSoup(r2.content,\"html.parser\")\n techs=soup2.find(\"ul\",attrs={\"class\":\"org__tag-container\"})\n techused=techs.text\n# print(techused)\n# print(len(techused))\n list=[]\n list=techused.split()\n# #print(list)\n \n \n for j in list:\n if (j==nametech):\n \n# print(\"yes\")\n# print(\"Organization No \"+str(count))\n# print(name)\n# print(link2)\n# print(list)\n count2+=1\n with open(\"Gsoc_Tech_Used_{}_{}.txt\".format(year,nametech),\"a+\") as file: # Write binary file mode\n file.write(\"Organization No \"+str(count))\n file.write(\" | No of Organizations using this tech \"+ str(count2))\n file.write(\"\\n\")\n file.write(name)\n file.write(\"\\n\")\n file.write(link2)\n file.write(\"\\n\")\n for m in list:\n file.write(m)\n file.write(\"\\n\")\n file.write(\"\\n\")\n \n \n \n\n\n\n\n\n\n\n","repo_name":"nishitanand/GSoC-Organisation-Tech-Downloader","sub_path":"GSoC-Org-Tech-Downloader.py","file_name":"GSoC-Org-Tech-Downloader.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15800049761","text":"from __future__ import print_function\n\ntry:\n from PyQt5.QtWidgets import *\n from PyQt5.QtGui import *\n from PyQt5.QtCore import *\n\n Signal = pyqtSignal\nexcept ImportError:\n from PySide2.QtWidgets import *\n from PySide2.QtGui import *\n from PySide2.QtCore import *\n\n\nclass NodeShapeListView(QListView):\n # Signals\n itemDoubleClicked = Signal(QModelIndex)\n\n def __init__(self):\n super(NodeShapeListView, self).__init__()\n self.viewport().setContentsMargins(15, 15, 15, 15)\n self.setViewMode(QListView.IconMode)\n\n self.setUniformItemSizes(True)\n\n self.setResizeMode(QListView.Adjust)\n self.setDragDropMode(QAbstractItemView.NoDragDrop)\n self.setSelectionMode(QAbstractItemView.ExtendedSelection)\n\n self.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)\n self.verticalScrollBar().setSingleStep(30)\n\n self.setGridSize(QSize(100, 88))\n\n # Item Double Clicked\n self._item_double_clicked_signal_enabled = False\n self.doubleClicked.connect(self.__emitItemDoubleClicked)\n\n def resizeEvent(self, event):\n super(NodeShapeListView, self).resizeEvent(event)\n\n # Update grid size\n grid_size = self.gridSize()\n column_count = 7\n spacing = 5\n grid_size.setWidth(self.viewport().width() / column_count - spacing)\n self.setGridSize(grid_size)\n\n def doubleClickedSignalEnabled(self):\n return self._item_double_clicked_signal_enabled\n\n def enableDoubleClickedSignal(self, enable=True):\n self._item_double_clicked_signal_enabled = enable\n\n def __emitItemDoubleClicked(self):\n if not self._item_double_clicked_signal_enabled:\n return\n\n index = self.currentIndex()\n if index.isValid():\n self.itemDoubleClicked.emit(index)\n","repo_name":"anvdev/Houdini_TDK","sub_path":"python2.7libs/houdini_tdk/node_shape_list_view.py","file_name":"node_shape_list_view.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"52"} +{"seq_id":"31601655829","text":"from 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 WorkRequestSummary(object):\n \"\"\"\n The summary of a work request.\n \"\"\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"INSTALL_PACKAGES\"\n OPERATION_TYPE_INSTALL_PACKAGES = \"INSTALL_PACKAGES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"REMOVE_PACKAGES\"\n OPERATION_TYPE_REMOVE_PACKAGES = \"REMOVE_PACKAGES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_PACKAGES\"\n OPERATION_TYPE_UPDATE_PACKAGES = \"UPDATE_PACKAGES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_ALL_PACKAGES\"\n OPERATION_TYPE_UPDATE_ALL_PACKAGES = \"UPDATE_ALL_PACKAGES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_SECURITY\"\n OPERATION_TYPE_UPDATE_SECURITY = \"UPDATE_SECURITY\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_BUGFIX\"\n OPERATION_TYPE_UPDATE_BUGFIX = \"UPDATE_BUGFIX\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_ENHANCEMENT\"\n OPERATION_TYPE_UPDATE_ENHANCEMENT = \"UPDATE_ENHANCEMENT\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_OTHER\"\n OPERATION_TYPE_UPDATE_OTHER = \"UPDATE_OTHER\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_KSPLICE_KERNEL\"\n OPERATION_TYPE_UPDATE_KSPLICE_KERNEL = \"UPDATE_KSPLICE_KERNEL\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_KSPLICE_USERSPACE\"\n OPERATION_TYPE_UPDATE_KSPLICE_USERSPACE = \"UPDATE_KSPLICE_USERSPACE\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"ENABLE_MODULE_STREAMS\"\n OPERATION_TYPE_ENABLE_MODULE_STREAMS = \"ENABLE_MODULE_STREAMS\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"DISABLE_MODULE_STREAMS\"\n OPERATION_TYPE_DISABLE_MODULE_STREAMS = \"DISABLE_MODULE_STREAMS\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"SWITCH_MODULE_STREAM\"\n OPERATION_TYPE_SWITCH_MODULE_STREAM = \"SWITCH_MODULE_STREAM\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"INSTALL_MODULE_PROFILES\"\n OPERATION_TYPE_INSTALL_MODULE_PROFILES = \"INSTALL_MODULE_PROFILES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"REMOVE_MODULE_PROFILES\"\n OPERATION_TYPE_REMOVE_MODULE_PROFILES = \"REMOVE_MODULE_PROFILES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"SET_SOFTWARE_SOURCES\"\n OPERATION_TYPE_SET_SOFTWARE_SOURCES = \"SET_SOFTWARE_SOURCES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"LIST_PACKAGES\"\n OPERATION_TYPE_LIST_PACKAGES = \"LIST_PACKAGES\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"SET_MANAGEMENT_STATION_CONFIG\"\n OPERATION_TYPE_SET_MANAGEMENT_STATION_CONFIG = \"SET_MANAGEMENT_STATION_CONFIG\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"SYNC_MANAGEMENT_STATION_MIRROR\"\n OPERATION_TYPE_SYNC_MANAGEMENT_STATION_MIRROR = \"SYNC_MANAGEMENT_STATION_MIRROR\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_MANAGEMENT_STATION_SOFTWARE\"\n OPERATION_TYPE_UPDATE_MANAGEMENT_STATION_SOFTWARE = \"UPDATE_MANAGEMENT_STATION_SOFTWARE\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE\"\n OPERATION_TYPE_UPDATE = \"UPDATE\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"MODULE_ACTIONS\"\n OPERATION_TYPE_MODULE_ACTIONS = \"MODULE_ACTIONS\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"LIFECYCLE_PROMOTION\"\n OPERATION_TYPE_LIFECYCLE_PROMOTION = \"LIFECYCLE_PROMOTION\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"CREATE_SOFTWARE_SOURCE\"\n OPERATION_TYPE_CREATE_SOFTWARE_SOURCE = \"CREATE_SOFTWARE_SOURCE\"\n\n #: A constant which can be used with the operation_type property of a WorkRequestSummary.\n #: This constant has a value of \"UPDATE_SOFTWARE_SOURCE\"\n OPERATION_TYPE_UPDATE_SOFTWARE_SOURCE = \"UPDATE_SOFTWARE_SOURCE\"\n\n #: A constant which can be used with the status property of a WorkRequestSummary.\n #: This constant has a value of \"ACCEPTED\"\n STATUS_ACCEPTED = \"ACCEPTED\"\n\n #: A constant which can be used with the status property of a WorkRequestSummary.\n #: This constant has a value of \"IN_PROGRESS\"\n STATUS_IN_PROGRESS = \"IN_PROGRESS\"\n\n #: A constant which can be used with the status property of a WorkRequestSummary.\n #: This constant has a value of \"FAILED\"\n STATUS_FAILED = \"FAILED\"\n\n #: A constant which can be used with the status property of a WorkRequestSummary.\n #: This constant has a value of \"SUCCEEDED\"\n STATUS_SUCCEEDED = \"SUCCEEDED\"\n\n #: A constant which can be used with the status property of a WorkRequestSummary.\n #: This constant has a value of \"CANCELING\"\n STATUS_CANCELING = \"CANCELING\"\n\n #: A constant which can be used with the status property of a WorkRequestSummary.\n #: This constant has a value of \"CANCELED\"\n STATUS_CANCELED = \"CANCELED\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new WorkRequestSummary object with values from keyword arguments.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param operation_type:\n The value to assign to the operation_type property of this WorkRequestSummary.\n Allowed values for this property are: \"INSTALL_PACKAGES\", \"REMOVE_PACKAGES\", \"UPDATE_PACKAGES\", \"UPDATE_ALL_PACKAGES\", \"UPDATE_SECURITY\", \"UPDATE_BUGFIX\", \"UPDATE_ENHANCEMENT\", \"UPDATE_OTHER\", \"UPDATE_KSPLICE_KERNEL\", \"UPDATE_KSPLICE_USERSPACE\", \"ENABLE_MODULE_STREAMS\", \"DISABLE_MODULE_STREAMS\", \"SWITCH_MODULE_STREAM\", \"INSTALL_MODULE_PROFILES\", \"REMOVE_MODULE_PROFILES\", \"SET_SOFTWARE_SOURCES\", \"LIST_PACKAGES\", \"SET_MANAGEMENT_STATION_CONFIG\", \"SYNC_MANAGEMENT_STATION_MIRROR\", \"UPDATE_MANAGEMENT_STATION_SOFTWARE\", \"UPDATE\", \"MODULE_ACTIONS\", \"LIFECYCLE_PROMOTION\", \"CREATE_SOFTWARE_SOURCE\", \"UPDATE_SOFTWARE_SOURCE\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type operation_type: str\n\n :param status:\n The value to assign to the status property of this WorkRequestSummary.\n Allowed values for this property are: \"ACCEPTED\", \"IN_PROGRESS\", \"FAILED\", \"SUCCEEDED\", \"CANCELING\", \"CANCELED\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type status: str\n\n :param id:\n The value to assign to the id property of this WorkRequestSummary.\n :type id: str\n\n :param description:\n The value to assign to the description property of this WorkRequestSummary.\n :type description: str\n\n :param display_name:\n The value to assign to the display_name property of this WorkRequestSummary.\n :type display_name: str\n\n :param message:\n The value to assign to the message property of this WorkRequestSummary.\n :type message: str\n\n :param parent_id:\n The value to assign to the parent_id property of this WorkRequestSummary.\n :type parent_id: str\n\n :param children_id:\n The value to assign to the children_id property of this WorkRequestSummary.\n :type children_id: list[str]\n\n :param compartment_id:\n The value to assign to the compartment_id property of this WorkRequestSummary.\n :type compartment_id: str\n\n :param percent_complete:\n The value to assign to the percent_complete property of this WorkRequestSummary.\n :type percent_complete: float\n\n :param time_created:\n The value to assign to the time_created property of this WorkRequestSummary.\n :type time_created: datetime\n\n \"\"\"\n self.swagger_types = {\n 'operation_type': 'str',\n 'status': 'str',\n 'id': 'str',\n 'description': 'str',\n 'display_name': 'str',\n 'message': 'str',\n 'parent_id': 'str',\n 'children_id': 'list[str]',\n 'compartment_id': 'str',\n 'percent_complete': 'float',\n 'time_created': 'datetime'\n }\n\n self.attribute_map = {\n 'operation_type': 'operationType',\n 'status': 'status',\n 'id': 'id',\n 'description': 'description',\n 'display_name': 'displayName',\n 'message': 'message',\n 'parent_id': 'parentId',\n 'children_id': 'childrenId',\n 'compartment_id': 'compartmentId',\n 'percent_complete': 'percentComplete',\n 'time_created': 'timeCreated'\n }\n\n self._operation_type = None\n self._status = None\n self._id = None\n self._description = None\n self._display_name = None\n self._message = None\n self._parent_id = None\n self._children_id = None\n self._compartment_id = None\n self._percent_complete = None\n self._time_created = None\n\n @property\n def operation_type(self):\n \"\"\"\n **[Required]** Gets the operation_type of this WorkRequestSummary.\n Type of the work request.\n\n Allowed values for this property are: \"INSTALL_PACKAGES\", \"REMOVE_PACKAGES\", \"UPDATE_PACKAGES\", \"UPDATE_ALL_PACKAGES\", \"UPDATE_SECURITY\", \"UPDATE_BUGFIX\", \"UPDATE_ENHANCEMENT\", \"UPDATE_OTHER\", \"UPDATE_KSPLICE_KERNEL\", \"UPDATE_KSPLICE_USERSPACE\", \"ENABLE_MODULE_STREAMS\", \"DISABLE_MODULE_STREAMS\", \"SWITCH_MODULE_STREAM\", \"INSTALL_MODULE_PROFILES\", \"REMOVE_MODULE_PROFILES\", \"SET_SOFTWARE_SOURCES\", \"LIST_PACKAGES\", \"SET_MANAGEMENT_STATION_CONFIG\", \"SYNC_MANAGEMENT_STATION_MIRROR\", \"UPDATE_MANAGEMENT_STATION_SOFTWARE\", \"UPDATE\", \"MODULE_ACTIONS\", \"LIFECYCLE_PROMOTION\", \"CREATE_SOFTWARE_SOURCE\", \"UPDATE_SOFTWARE_SOURCE\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The operation_type of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._operation_type\n\n @operation_type.setter\n def operation_type(self, operation_type):\n \"\"\"\n Sets the operation_type of this WorkRequestSummary.\n Type of the work request.\n\n\n :param operation_type: The operation_type of this WorkRequestSummary.\n :type: str\n \"\"\"\n allowed_values = [\"INSTALL_PACKAGES\", \"REMOVE_PACKAGES\", \"UPDATE_PACKAGES\", \"UPDATE_ALL_PACKAGES\", \"UPDATE_SECURITY\", \"UPDATE_BUGFIX\", \"UPDATE_ENHANCEMENT\", \"UPDATE_OTHER\", \"UPDATE_KSPLICE_KERNEL\", \"UPDATE_KSPLICE_USERSPACE\", \"ENABLE_MODULE_STREAMS\", \"DISABLE_MODULE_STREAMS\", \"SWITCH_MODULE_STREAM\", \"INSTALL_MODULE_PROFILES\", \"REMOVE_MODULE_PROFILES\", \"SET_SOFTWARE_SOURCES\", \"LIST_PACKAGES\", \"SET_MANAGEMENT_STATION_CONFIG\", \"SYNC_MANAGEMENT_STATION_MIRROR\", \"UPDATE_MANAGEMENT_STATION_SOFTWARE\", \"UPDATE\", \"MODULE_ACTIONS\", \"LIFECYCLE_PROMOTION\", \"CREATE_SOFTWARE_SOURCE\", \"UPDATE_SOFTWARE_SOURCE\"]\n if not value_allowed_none_or_none_sentinel(operation_type, allowed_values):\n operation_type = 'UNKNOWN_ENUM_VALUE'\n self._operation_type = operation_type\n\n @property\n def status(self):\n \"\"\"\n **[Required]** Gets the status of this WorkRequestSummary.\n Status of the work request.\n\n Allowed values for this property are: \"ACCEPTED\", \"IN_PROGRESS\", \"FAILED\", \"SUCCEEDED\", \"CANCELING\", \"CANCELED\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The status of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"\n Sets the status of this WorkRequestSummary.\n Status of the work request.\n\n\n :param status: The status of this WorkRequestSummary.\n :type: str\n \"\"\"\n allowed_values = [\"ACCEPTED\", \"IN_PROGRESS\", \"FAILED\", \"SUCCEEDED\", \"CANCELING\", \"CANCELED\"]\n if not value_allowed_none_or_none_sentinel(status, allowed_values):\n status = 'UNKNOWN_ENUM_VALUE'\n self._status = status\n\n @property\n def id(self):\n \"\"\"\n **[Required]** Gets the id of this WorkRequestSummary.\n The OCID of the work request.\n\n\n :return: The id of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"\n Sets the id of this WorkRequestSummary.\n The OCID of the work request.\n\n\n :param id: The id of this WorkRequestSummary.\n :type: str\n \"\"\"\n self._id = id\n\n @property\n def description(self):\n \"\"\"\n Gets the description of this WorkRequestSummary.\n A short description about the work request.\n\n\n :return: The description of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"\n Sets the description of this WorkRequestSummary.\n A short description about the work request.\n\n\n :param description: The description of this WorkRequestSummary.\n :type: str\n \"\"\"\n self._description = description\n\n @property\n def display_name(self):\n \"\"\"\n Gets the display_name of this WorkRequestSummary.\n A short display name for the work request.\n\n\n :return: The display_name of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._display_name\n\n @display_name.setter\n def display_name(self, display_name):\n \"\"\"\n Sets the display_name of this WorkRequestSummary.\n A short display name for the work request.\n\n\n :param display_name: The display_name of this WorkRequestSummary.\n :type: str\n \"\"\"\n self._display_name = display_name\n\n @property\n def message(self):\n \"\"\"\n Gets the message of this WorkRequestSummary.\n A progress or error message, if there is any.\n\n\n :return: The message of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, message):\n \"\"\"\n Sets the message of this WorkRequestSummary.\n A progress or error message, if there is any.\n\n\n :param message: The message of this WorkRequestSummary.\n :type: str\n \"\"\"\n self._message = message\n\n @property\n def parent_id(self):\n \"\"\"\n Gets the parent_id of this WorkRequestSummary.\n The OCID of the parent work request.\n\n\n :return: The parent_id of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._parent_id\n\n @parent_id.setter\n def parent_id(self, parent_id):\n \"\"\"\n Sets the parent_id of this WorkRequestSummary.\n The OCID of the parent work request.\n\n\n :param parent_id: The parent_id of this WorkRequestSummary.\n :type: str\n \"\"\"\n self._parent_id = parent_id\n\n @property\n def children_id(self):\n \"\"\"\n Gets the children_id of this WorkRequestSummary.\n The list of OCIDs for the child work requests.\n\n\n :return: The children_id of this WorkRequestSummary.\n :rtype: list[str]\n \"\"\"\n return self._children_id\n\n @children_id.setter\n def children_id(self, children_id):\n \"\"\"\n Sets the children_id of this WorkRequestSummary.\n The list of OCIDs for the child work requests.\n\n\n :param children_id: The children_id of this WorkRequestSummary.\n :type: list[str]\n \"\"\"\n self._children_id = children_id\n\n @property\n def compartment_id(self):\n \"\"\"\n **[Required]** Gets the compartment_id of this WorkRequestSummary.\n The OCID of the compartment that contains the work request. Work requests should be scoped to\n the same compartment as the resource the work request affects. If the work request affects multiple resources,\n and those resources are not in the same compartment, it is up to the service team to pick the primary\n resource whose compartment should be used.\n\n\n :return: The compartment_id of this WorkRequestSummary.\n :rtype: str\n \"\"\"\n return self._compartment_id\n\n @compartment_id.setter\n def compartment_id(self, compartment_id):\n \"\"\"\n Sets the compartment_id of this WorkRequestSummary.\n The OCID of the compartment that contains the work request. Work requests should be scoped to\n the same compartment as the resource the work request affects. If the work request affects multiple resources,\n and those resources are not in the same compartment, it is up to the service team to pick the primary\n resource whose compartment should be used.\n\n\n :param compartment_id: The compartment_id of this WorkRequestSummary.\n :type: str\n \"\"\"\n self._compartment_id = compartment_id\n\n @property\n def percent_complete(self):\n \"\"\"\n Gets the percent_complete of this WorkRequestSummary.\n The percentage complete of the operation tracked by this work request.\n\n\n :return: The percent_complete of this WorkRequestSummary.\n :rtype: float\n \"\"\"\n return self._percent_complete\n\n @percent_complete.setter\n def percent_complete(self, percent_complete):\n \"\"\"\n Sets the percent_complete of this WorkRequestSummary.\n The percentage complete of the operation tracked by this work request.\n\n\n :param percent_complete: The percent_complete of this WorkRequestSummary.\n :type: float\n \"\"\"\n self._percent_complete = percent_complete\n\n @property\n def time_created(self):\n \"\"\"\n **[Required]** Gets the time_created of this WorkRequestSummary.\n The date and time the request was created - as described in\n `RFC 3339`__, section 14.29.\n\n __ https://tools.ietf.org/rfc/rfc3339\n\n\n :return: The time_created of this WorkRequestSummary.\n :rtype: datetime\n \"\"\"\n return self._time_created\n\n @time_created.setter\n def time_created(self, time_created):\n \"\"\"\n Sets the time_created of this WorkRequestSummary.\n The date and time the request was created - as described in\n `RFC 3339`__, section 14.29.\n\n __ https://tools.ietf.org/rfc/rfc3339\n\n\n :param time_created: The time_created of this WorkRequestSummary.\n :type: datetime\n \"\"\"\n self._time_created = time_created\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/os_management_hub/models/work_request_summary.py","file_name":"work_request_summary.py","file_ext":"py","file_size_in_byte":20735,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"74432119203","text":"# 2) Dado a sequência de Fibonacci, onde se inicia por 0 e 1 e o próximo valor sempre será a soma dos 2 valores anteriores \n# (exemplo: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...), escreva um programa na linguagem que desejar onde, informado um número, ele \n# calcule a sequência de Fibonacci e retorne uma mensagem avisando se o número informado pertence ou não a sequência.\n\n# IMPORTANTE:\n# Esse número pode ser informado através de qualquer entrada de sua preferência ou pode ser previamente definido no código;\n\n\ndef fibonacci(n):\n \"\"\"Calcula a sequência de Fibonacci até o número n.\"\"\"\n fib = [0, 1]\n while fib[-1] < n + 1:\n fib.append(fib[-1] + fib[-2])\n return fib[:-1]\n\ndef pertence_fibonacci(n):\n \"\"\"Verifica se o número n pertence à sequência de Fibonacci.\"\"\"\n fib = fibonacci(n)\n if n in fib:\n print(f\"{n} pertence à sequência de Fibonacci!\")\n else:\n print(f\"{n} não pertence à sequência de Fibonacci.\")\n\n# Exemplo de uso:\nwhile True:\n numero = int(input(\"Digite um número inteiro: \"))\n print(fibonacci(numero))\n pertence_fibonacci(numero)","repo_name":"KaiqueMends/AnswersPython","sub_path":"Fibonacci.py","file_name":"Fibonacci.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74981835045","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# http://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\nfrom scrapy.item import Item, Field\n\n\nclass TescoOfferItem(scrapy.Item):\n # define the fields for your item here like:\n # name = scrapy.Field()\n\tproductid = Field()\n\timgsrc90 = Field()\n\timgsrc110 = Field()\n\timgsrc540 = Field()\n\timgsrc225 = Field()\n\tproductdesc = Field()\n\tofferdesc = Field()\n\tvaliditydesc = Field()\n\tofferStart = Field()\n\tofferEnd = Field()\n\nclass SainsburysOfferItem(scrapy.Item):\n\tproductid = Field()\n\t#imgsrcs = Field()\n\t#imgsrcm = Field()\n\timgsrcl = Field()\n\tproductdesc = Field()\n\tofferdesc = Field()\n\tproducturl = Field()\n\nclass AsdaOfferItem(scrapy.Item):\n productdesc = Field()\n imgsrcl = Field()\n producturl = Field()\n productprice = Field()\n\nclass MorrisonsOfferItem(scrapy.Item):\n productdesc = Field()\n offerdesc = Field()\n offerurl = Field()\n imgurl = Field()\n producturl = Field()\n productprice = Field()\n","repo_name":"aravindc/offerscrape","sub_path":"offer/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3274826119","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ArcFaceLayer(nn.Module):\n def __init__(self, in_features, out_features, s = 10, m = 0.2):\n super().__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.s = s\n self.m = m\n self.weight = nn.Parameter(torch.FloatTensor(out_features, in_features))\n nn.init.xavier_normal_(self.weight)\n \n self.cos_m = math.cos(m)\n self.sin_m = math.sin(m)\n self.th = torch.tensor(math.cos(math.ph - m))\n self.mm = torch.tensor(math.sin(math.pi - m) * m)\n \n def forward(self, inputs, labels):\n cos_th = F.linear(F.normalize(inputs), F.normalize(self.weight))\n cos_th = cos_th.clamp(-1, 1)\n sin_th = torch.sqrt(1.0 - torch.pow(cos_th, 2))\n cos_th_m = cos_th * self.cos_m - sin_th * self.sin_m # cos(theta+m)\n cos_th_m = torch.where(cos_th > self.th, cos_th_m, cos_th - self.mm)\n \n cond_v = cos_th - self.th\n cond = cond_v <= 0\n cos_th_m[cond] = (cos_th - self.mm)[cond]\n \n if labels.dims() == 1:\n labels = labels.unsqueeze(-1)\n one_hot = torch.zeros(cos_th.size()).cuda()\n labels = labels.type(torch.LongTensor).cuda()\n one_hot.scatter_(1, labels, 1.0)\n outputs = one_hot * cos_th_m + (1.0 - one_hot) * cos_th\n outputs = outputs * self.s\n return outputs","repo_name":"jiyeoon/TIL","sub_path":"etc/ArcFace/arcface.py","file_name":"arcface.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"556963012","text":"from flask import Flask, request, render_template\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom stories import story\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = \"secretkey\"\n\ndebug = DebugToolbarExtension(app)\n\n@app.route(\"/\")\ndef show_form():\n \"\"\"renders the main page with madlib form\"\"\"\n\n prompts = story.prompts\n\n return render_template(\"base.html\", prompts = prompts )\n\n\n@app.route(\"/story\")\ndef show_story():\n \"\"\"Takes answers from submitted form on homepage and plugs them into story template and displays on page\"\"\"\n print(story)\n ans = request.args\n mad_story = story.generate(ans)\n return render_template(\"story.html\", story=mad_story)","repo_name":"trishajjohnson/flask-madlibs","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40152426079","text":"import logging\nfrom Transcribe import transcribe\nimport speech_recognition as sr\nfrom flask import Flask, render_template, request, redirect, url_for\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n text = \"\"\n if request.method == 'POST':\n language = request.form['language']\n file = request.files['audiofile']\n\n # Save the audio locally\n file.save(\"/tmp/\"+file.filename)\n\n text = transcribe(\"/tmp/\"+file.filename, language=language)\n return redirect(url_for('index', text=text))\n\n text = request.args.get('text', '')\n return render_template('index.html', text=text)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"karvanpy/audiotranscribe_web","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"36144011528","text":"from ebmdatalab import charts\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nimport numpy as np\n\ndef add_percentiles(df, period_column=None, column=None, show_outer_percentiles=True):\n \"\"\"For each period in `period_column`, compute percentiles across that\n range.\n Adds `percentile` column.\n \"\"\"\n deciles = np.arange(0.1, 1, 0.1)\n bottom_percentiles = np.arange(0.01, 0.1, 0.01)\n top_percentiles = np.arange(0.91, 1, 0.01)\n if show_outer_percentiles:\n quantiles = np.concatenate((deciles, bottom_percentiles, top_percentiles))\n else:\n quantiles = deciles\n df = df.groupby(period_column)[column].quantile(quantiles).reset_index()\n df = df.rename(index=str, columns={\"level_1\": \"percentile\"})\n # create integer range of percentiles\n df[\"percentile\"] = df[\"percentile\"].apply(lambda x: int(x * 100))\n return df\n\n\ndef deciles_chart(\n df,\n period_column=None,\n column=None,\n title=\"\",\n ylabel=\"\", interactive=True\n):\n \"\"\"period_column must be dates / datetimes\n \"\"\"\n\n df = add_percentiles(\n df,\n period_column=period_column,\n column=column,\n show_outer_percentiles=False,\n )\n\n if interactive:\n fig = go.Figure()\n\n \n\n for percentile in np.unique(df['percentile']):\n df_subset = df[df['percentile'] == percentile]\n if percentile == 50:\n fig.add_trace(go.Scatter(x=df_subset[period_column], y=df_subset[column], line={\n \"color\": \"blue\", \"dash\": \"solid\", \"width\": 1.2}, name=\"median\"))\n else:\n fig.add_trace(go.Scatter(x=df_subset[period_column], y=df_subset[column], line={\n \"color\": \"blue\", \"dash\": \"dash\", \"width\": 1}, name=f\"decile {int(percentile/10)}\"))\n\n # Set title\n fig.update_layout(\n title_text=title,\n hovermode='x',\n title_x=0.5,\n\n\n )\n\n fig.update_yaxes(title=ylabel)\n fig.update_xaxes(title=\"Date\")\n\n # Add range slider\n fig.update_layout(\n xaxis=go.layout.XAxis(\n rangeselector=dict(\n buttons=list([\n dict(count=1,\n label=\"1m\",\n step=\"month\",\n stepmode=\"backward\"),\n dict(count=6,\n label=\"6m\",\n step=\"month\",\n stepmode=\"backward\"),\n\n dict(count=1,\n label=\"1y\",\n step=\"year\",\n stepmode=\"backward\"),\n dict(step=\"all\")\n ])\n ),\n rangeslider=dict(\n visible=True\n ),\n type=\"date\"\n )\n )\n\n fig.show()\n else:\n\n charts.deciles_chart(\n df,\n period_column=period_column,\n column=column,\n title=title,\n ylabel=ylabel,\n show_outer_percentiles=False,\n show_legend=True,\n ) ","repo_name":"opensafely/mechanical-valve-anticoag","sub_path":"analysis/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42312127553","text":"#!/usr/bin/python3\n\nimport sys\n\nif __name__ == \"__main__\":\n # Exclude the script name from the argument\n argv = sys.argv[1:] \n\n # Convert the arguments to integers\n integers = [int(arg) for arg in argv]\n\n result = sum(integers)\n print(result)\n","repo_name":"addymwenda12/alx-higher_level_programming","sub_path":"0x02-python-import_modules/3-infinite_add.py","file_name":"3-infinite_add.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4261114534","text":"#Écrire dans un nouveau fichier shifumi.py, un programme \n#qui permettra de jouer à Pierre / Feuille / Ciseaux contre \n#l'ordinateur en 2 manches gagnantes [BO3].\n\nimport random\n\ndef jouer_shifumi():\n choix = [\"Pierre\", \"Feuille\", \"Ciseaux\"]\n manches_joueur = 0\n manches_ordinateur = 0\n\n while manches_joueur < 2 and manches_ordinateur < 2:\n print(\"Choisissez :\")\n print(\"1. Pierre\")\n print(\"2. Feuille\")\n print(\"3. Ciseaux\")\n choix_joueur = int(input(\"Entrez le numéro de votre choix : \")) - 1\n\n if choix_joueur < 0 or choix_joueur > 2:\n print(\"Choix invalide. Veuillez choisir à nouveau.\")\n continue\n\n choix_ordinateur = random.randint(0, 2)\n\n print(\"Vous avez choisi : \" + choix[choix_joueur])\n print(\"L'ordinateur a choisi : \" + choix[choix_ordinateur])\n\n\n if choix_joueur == choix_ordinateur:\n print(\"Égalité !\")\n elif (choix_joueur == 0 and choix_ordinateur == 2) or (choix_joueur == 1 and choix_ordinateur == 0) or (choix_joueur == 2 and choix_ordinateur == 1):\n print(\"Vous gagnez cette manche !\")\n manches_joueur += 1\n else:\n print(\"L'ordinateur gagne cette manche !\")\n manches_ordinateur += 1\n\n\n if manches_joueur > manches_ordinateur:\n print(\"Vous avez gagné le Best of 3 !\")\n else:\n print(\"L'ordinateur a gagné le Best of 3 !\")\n\nif __name__ == \"__main__\":\n jouer_shifumi()\n","repo_name":"AdrienAutef/python-course-m1il","sub_path":"course/shifumi.py","file_name":"shifumi.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35866833838","text":"from setuptools import setup\n\nwith open('README.md') as file:\n long_description = file.read()\n\nsetup(name='comtradehandlers',\n version='0.1.0',\n description='Support for IEEE COMTRADE readers and writers',\n long_description=long_description,\n url='',\n author='Liam Relihan',\n author_email='liam.relihan@resourcekraft.com',\n license='MIT',\n packages=['comtradehandlers'],\n package_dir={ 'comtradehandlers': 'src',\n 'examples':'examples'},\n keywords=['COMTRADE', 'smartgrid', 'oscilloscope','power quality','power']\n )\n","repo_name":"relihanl/comtradehandlers","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"43154649004","text":"from flask_restful import Api, Resource, reqparse\nimport pymongo\nfrom pymongo.collation import Collation\n\n\nclass HelloApiHandler(Resource):\n\n def __init__(self):\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017\")\n mydb = myclient[\"prof_search\"]\n self.prof_data = mydb[\"prof_data\"]\n self.inverted_index = mydb[\"inverted_index\"]\n\n\n\n def get(self):\n return {\n 'resultStatus': 'SUCCESS',\n 'message': \"Hello Api Handler\"\n }\n\n\n def search_research_interests(self,query):\n \n \n x = self.inverted_index.find({\"_id\":query})\n\n \n result=[]\n prof_ids=set()\n for item in x:\n for single_id in item['profs']:\n if single_id not in prof_ids:\n prof_ids.add(single_id)\n \n prof_details=[]\n for prof_id in prof_ids:\n a = self.prof_data.find({\"_id\":prof_id })\n prof_details.append(list(a)[0])\n\n \n prof_details.sort(key = lambda x:x['Score'],reverse=True)\n \n return prof_details\n\n def search_professor_name(self,query):\n result = self.prof_data.find({\"$text\": {\"$search\": query}}).sort([(\"Score\",pymongo.DESCENDING)])\n \n return list(result)\n\n def search_university_name(self,query):\n result = self.prof_data.find({\"Affiliation\":query}).collation(Collation(locale='en_US',strength=1)).sort([(\"Score\",pymongo.DESCENDING)])\n \n return list(result)\n\n def post(self):\n print(self)\n parser = reqparse.RequestParser()\n print(parser)\n # parser.add_argument('type', type=str)\n parser.add_argument('message', type=str)\n parser.add_argument('query_type', type=str)\n\n\n args = parser.parse_args()\n\n print(args)\n # note, the post req from frontend needs to match the strings here (e.g. 'type and 'message')\n\n # request_type = args['type']\n request_json = args['message']\n request_query_type =args['query_type']\n # ret_status, ret_msg = ReturnData(request_type, request_json)\n # currently just returning the req straight\n # ret_status = request_type\n ret_msg=[]\n if request_query_type=='research_interest':\n ret_msg = self.search_research_interests(request_json)\n \n elif request_query_type=='professor_name':\n ret_msg = self.search_professor_name(request_json)\n \n elif request_query_type=='university_name':\n ret_msg=self.search_university_name(request_json)\n\n \n # print(ret_msg)\n return ret_msg","repo_name":"mshamir11/profSearch","sub_path":"flask/api/HelloApiHandler.py","file_name":"HelloApiHandler.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":"1972301129","text":"# %% md\n# Excercises 1.C\n## Goal for this excercise:\n### Using the make circles library we would like to train a classifier that can make a classification of the dataset\n### We would like to use the following classifiers: SVM\n# %%\n# Imports\nfrom sklearn.datasets import make_circles\nfrom sklearn.svm import SVC\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# %%\n# To be able to create 3D plots we need to have a feature map that we can set out Z value to, this is done with the following functions\n# Inspiration take from SVM_1 Excercise\n# %%\ndef feature_map_1(X):\n return np.asarray((X[:, 0], X[:, 1], X[:, 0] ** 2 + X[:, 1] ** 2)).T\n\n\n# %%\ndef feature_map_3(X):\n return np.asarray((np.sqrt(2) * X[:, 0] * X[:, 1], X[:, 0] ** 2, X[:, 1] ** 2)).T\n\n\n# %%\n# Create dataset wiht the make circles library\n# %%\nX, y = make_circles(n_samples=1000, noise=0.1, factor=0.1)\nz = feature_map_1(X)\n# %%\n# Type in the dataset to see what it looks like\n# %%\n# 2D scatter plot\nfig = plt.figure(figsize=(16, 8))\nax = fig.add_subplot(1, 2, 1)\nax.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis')\nax.set_xlabel('$x_1$')\nax.set_ylabel('$x_2$')\nax.set_title('Original dataset')\n\n# 3D scatter plot\nax = fig.add_subplot(1, 2, 2, projection='3d')\nax.scatter3D(z[:, 0], z[:, 1], z[:, 2], c=y,\n cmap='viridis')\nax.set_xlabel('$z_1$')\nax.set_ylabel('$z_2$')\nax.set_zlabel('$z_3$')\nax.set_title('Transformed dataset')\n\nplt.show()\n\n\n# %%\n# Create a SVM classifier and fit it to the dataset with a linear kernel\n# %%\ndef displayKernel3D(kernel: SVC, X, y, h) -> None:\n # create a mesh to plot in 3D\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n\n # Apply the feature map to create the third dimension\n z = feature_map_1(np.c_[xx.ravel(), yy.ravel()])\n\n # Make predictions using the SVM kernel on the 3D meshgrid\n Z = kernel.predict(z)\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n\n # Create a 3D scatter plot of the transformed dataset\n fig = plt.figure(figsize=(12, 8))\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(X[:, 0], X[:, 1], c=y)\n ax.set_xlabel('Feature 1')\n ax.set_ylabel('Feature 2')\n ax.set_zlabel('Feature 3')\n ax.set_title(\"SVC with \" + kernel.kernel + \" kernel\")\n\n # Create a 3D contour plot\n ax.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)\n\n plt.show()\n\n\n# %%\n# Generel function to display different kernels\ndef displayKernel(kernel: SVC, X, y, h) -> None:\n # create a mesh to plot in\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h),\n np.arange(y_min, y_max, h))\n plt.subplot(1, 1, 1)\n plt.subplots_adjust(wspace=0.4, hspace=0.4)\n Z = kernel.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)\n\n # Plot also the training points\n plt.scatter(X[:, 0], X[:, 1], c=y)\n plt.xlabel('Sepal length')\n plt.ylabel('Sepal width')\n plt.title(\"SVC with\" + kernel.kernel + \"kernel\")\n\n plt.show()\n\n\n# %% md\n# Linear Kernel\n# %%\nC = 1 # SVM regularization parameter\nsvc = SVC(kernel='linear', C=C).fit(z, y)\n\n# Display Linear Kernel\n# displayKernel3D(svc, z, y, 0.1)\nZ = feature_map_3(X)\n\n# 2D scatter plot\nfig = plt.figure(figsize=(16, 8))\nax = fig.add_subplot(1, 2, 1)\nax.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis')\nax.set_xlabel('$x_1$')\nax.set_ylabel('$x_2$')\nax.set_title('Original data')\n\n# 3D scatter plot\nax = fig.add_subplot(1, 2, 2, projection='3d')\nax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2], c=y,\n cmap='viridis') # ,rstride = 5, cstride = 5, cmap = 'jet', alpha = .4, edgecolor = 'none' )\nax.set_xlabel('$z_1$')\nax.set_ylabel('$z_2$')\nax.set_zlabel('$z_3$')\nax.set_title('Transformed data: ')\nw = svc.coef_.flatten()\nb = svc.intercept_.flatten()\nprint('w=', w, 'b=', b)\n\n# create x,y\nxx, yy = np.meshgrid(np.linspace(-1, 1), np.linspace(0, 1))\n\n# calculate corresponding z\nboundary = (-w[0] * xx - w[1] * yy - b) * 1. / w[2]\n\n# plot the surface\n\nax.plot_surface(xx, yy, boundary, alpha=.3)\nax.set_ylim(.2, 1.2)\nax.set_zlim(-.9, 1.1)\n# %% md\n# RBF Kernel\n# %%\nrbf_svc = SVC(kernel='rbf', gamma=100, C=C).fit(z, y)\n# %%\n# Display RBF Kernel\ndisplayKernel3D(rbf_svc, z, y, 0.1)\n# %% md\n# Display poly kernel\n# %%\npoly_svc = SVC(kernel='poly', degree=7, C=C).fit(z, y)\ndisplayKernel3D(poly_svc, z, y, 0.1)","repo_name":"Immer77/MLAssignment","sub_path":"Excercise1/make_circles_svm.py","file_name":"make_circles_svm.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71475535204","text":"import os, json, shutil, re, base64\n#from injector import inject_to_tab, get_tab, tab_has_element, get_tabs\nimport logging\n\nInitialized = False\nthemeName = \"Wallpapers2\"\nthemeFolder = \"/home/deck/homebrew/themes\"\nsymLinkToHostDir = \"/home/deck/.local/share/Steam/steamui/themes_custom\"\nthemeBaseFolder = f\"/home/deck/homebrew/themes/{themeName}\"\nimagesFolder = \"/home/deck/wallpaperImages\"\ncssDir = \"generatedCSSFiles\"\nb64Dir = \"sharedB64Images\"\nfallbackCSSDir = \"fallbackCSS\"\nthemeTemplateFileName = \"themeTemplate.json\"\nautoGenHeader = \"/* This File was Auto-Generated Do Not Modify */\\n\\n\"\ncssVariableTemplate = f\"{autoGenHeader}:root{{\\n\\t--: var(--, radial-gradient(155.42% 100% at 0% 0%, #151f25 0 0%, #152533 100%));\\n}}\"\nfallbackCssVariableTemplate = f\"{autoGenHeader}:root{{\\n\\t--: radial-gradient(155.42% 100% at 0% 0%, #151f25 0 0%, #152533 100%) !important;\\n}}\"\nvalidExtensions = [\".jpg\", \".png\", \".svg\", \".gif\", \".jpeg\"]\n\ncssFileTypes = { \n b64Dir: f\"{autoGenHeader}:root{{\\n\\t--: !important;\\n}}\",\n fallbackCSSDir: fallbackCssVariableTemplate\n}\n\nimageCount = 0\n\ndef log(text : str):\n try:\n f = open(f\"/home/deck/homebrew/plugins/Wallpapers/log.txt\", \"a\")\n f.write(text + \"\\n\")\n f.close()\n except:\n pass\n\n#### Helper Functions\n\ndef getURLforFile(file):\n\n fileURL = \"\"\n\n file = os.path.basename(file)\n\n if os.path.exists(symLinkToHostDir):\n log(\"Sym Link is here\")\n fileURL = f\"url('/themes_custom/{themeName}/images/{file}')\"\n else:\n # fall back to b64\n log(\"Sym Link not here\")\n fileURL = \"url('data:image/;base64,')\"\n\n fileURL = fileURL.replace(\"\", getImgTypeTagForFile(file)).replace(\"\", getB64ForFile(file))\n\n return fileURL\n\ndef getB64ForFile(file):\n rv = \"\"\n try:\n if os.path.exists(file):\n with open(file, \"rb\") as image_file:\n raw = base64.b64encode(image_file.read())\n rv = raw.decode('utf-8')\n except:\n pass\n \n return rv\n\ndef getImgTypeTagForFile(file):\n rv = \"jpeg\"\n\n fileInfo = os.path.splitext(file)\n\n if len(fileInfo) == 2:\n fileExt = fileInfo[1].lower()\n\n if fileExt in validExtensions:\n if fileExt == \".jpg\" or fileExt == \".jpeg\":\n rv = \"jpeg\"\n elif fileExt == \".svg\":\n rv = \"svg+xml\"\n elif fileExt == \".gif\":\n rv = \"gif\"\n elif fileExt == \".png\":\n rv = \"png\" \n\n else:\n rv = \"jpeg\"\n\n return rv\n\ndef writeCSSType(type, filePath, varName):\n\n rv = True\n\n fileInfo = os.path.splitext(os.path.basename(filePath))\n try:\n if not type in cssFileTypes.keys() or len(fileInfo) != 2:\n raise ValueError(\"Not a Valid type or image path\") \n \n fileName = f\"{varName}.css\"\n \n variableName = \"WPRImage\" + varName.replace(\" \", \"\")\n\n if type == b64Dir:\n f = open(f\"{cssDir}/{type}/{fileName}\" , \"w\")\n tmpStr = cssFileTypes[type].replace(\"\", variableName).replace(\"\", getURLforFile(filePath))\n f.write(tmpStr)\n f.close()\n elif type == fallbackCSSDir:\n f = open(f\"{cssDir}/{type}/{fileName}\" , \"w\")\n tmpStr = cssFileTypes[type].replace(\"\", varName)\n f.write(tmpStr)\n f.close()\n else:\n f = open(f\"{cssDir}/{type}/{fileName}\" , \"w\")\n f.write(cssFileTypes[type].replace(\"\", variableName))\n f.close()\n except Exception as e:\n log(f\"Error writing type {type}: {str(e)}\")\n rv = False\n\n return rv\n\n\ndef copyThemeTemplate(srcDir, destDir):\n for file in os.listdir(srcDir):\n trueSrcFilePath = f\"{srcDir}/{file}\"\n trueDestFilePath = f\"{destDir}/{file}\"\n\n\n if file in [\"images\"]:\n # Symbolicly Link images to imageFolder\n if not os.path.exists(f\"{destDir}/images\"):\n os.system(f\"ln -s {imagesFolder} {destDir}/images\")\n else:\n if os.path.isdir(trueSrcFilePath):\n if os.path.isdir(trueDestFilePath):\n shutil.rmtree(trueDestFilePath)\n \n shutil.copytree(trueSrcFilePath, trueDestFilePath) \n else:\n shutil.copy2(trueSrcFilePath, trueDestFilePath)\n\n\ndef addThemeThemeAtPath(path):\n if os.path.isdir(path) and os.path.isdir(imagesFolder):\n os.chdir(path)\n global imageCount\n # Copy Template to Folder\n\n copyThemeTemplate((os.path.dirname(os.path.realpath(__file__)) + \"/WallpapersTemplate\"), path)\n\n if os.path.isdir(cssDir):\n shutil.rmtree(cssDir)\n \n jsonTemplate = open(f\"{themeTemplateFileName}\")\n themeJson = json.load(jsonTemplate)\n jsonTemplate.close()\n # Create Folder Structure\n os.mkdir(cssDir)\n os.mkdir(f\"{cssDir}/{b64Dir}\")\n os.mkdir(f\"{cssDir}/{fallbackCSSDir}\")\n\n for k,v in themeJson[\"patches\"].items():\n if v[\"type\"] == \"dropdown-image\":\n if \"css_variable\" in v.keys() and re.match(r\"[A-Za-z0-9_-]+\", v[\"css_variable\"]):\n tmpVar = v[\"css_variable\"]\n log(tmpVar)\n os.mkdir(f'{cssDir}/{tmpVar}')\n cssFileTypes[v[\"css_variable\"]] = cssVariableTemplate.replace(\"\", v[\"css_variable\"])\n\n if \"values\" in v.keys():\n v[\"values\"][\"None\"] = {f\"{fallbackCSSDir}/{v['css_variable']}.css\": [\"SP\"]}\n writeCSSType(fallbackCSSDir, \"\", v['css_variable'])\n if \"default\" in v.keys() and \"None\" != v[\"default\"]:\n v[\"default\"] = \"None\"\n\n else:\n raise ValueError(f'Invalid css variable name')\n\n\n\n\n for root, dirs, files in os.walk(f\"{path}/images\"):\n for file in files:\n fileInfo = os.path.splitext(file)\n if len(fileInfo) == 2 and ((fileInfo[1].lower()) in validExtensions):\n log(\"Creating CSS files for \" + file)\n imageImportedSuccessfully = True\n imageVarName = \"\"\n imageVarName = imageVarName.join(e for e in fileInfo[0].lower().title() if (e.isalnum() or e.isspace()))\n imageVarName = \" \".join(imageVarName.split())\n \n for cssType, cssTemplate in cssFileTypes.items():\n if imageImportedSuccessfully:\n if cssType != fallbackCSSDir:\n imageImportedSuccessfully = writeCSSType(cssType, os.path.join(root, file), imageVarName)\n \n if imageImportedSuccessfully:\n # Update Theme.json\n log(\"Success\")\n for k,v in themeJson[\"patches\"].items():\n if v[\"type\"] == \"dropdown-image\":\n log(f\"Adding {imageVarName} for var {v['css_variable']}\")\n if \"css_variable\" in v.keys() and re.match(r\"[A-Za-z0-9_-]+\", v[\"css_variable\"]):\n themeJson[\"patches\"][k][\"values\"][imageVarName] = { f\"{cssDir}/{b64Dir}/{imageVarName}.css\": [\"SP\"], f'{cssDir}/{v[\"css_variable\"]}/{imageVarName}.css': [\"SP\"]}\n else:\n # No Var replace Normal dropdown Patch\n v[\"type\"] = \"dropdown\"\n imageCount += 1\n\n \n else:\n log(\"Failed\")\n\n # Sanitize Extended Types\n for k,v in themeJson[\"patches\"].items():\n if \"css_variable\" in v.keys():\n del v[\"css_variable\"]\n if \"values\" in v.keys():\n v[\"values\"][\"None\"] = { }\n if \"type\" in v.keys() and v[\"type\"] == \"dropdown-image\":\n v[\"type\"] = \"dropdown\"\n\n\n f = open(f\"{path}/theme.json\" , \"w\")\n f.write(json.dumps(themeJson, indent=4))\n f.close()\n else:\n log(f\"Error Processing Theme at path {path}\")\n\n\ndef getExtendedThemesList():\n rv = []\n root = themeFolder\n\n for file in os.listdir(root):\n if os.path.isdir(F\"{root}/{file}\"):\n if themeTemplateFileName in os.listdir(f\"{root}/{file}\"):\n rv.append(f\"{root}/{file}\")\n\n return rv\n\n##################################################################################\n\n\n\nclass Plugin:\n\n\n async def isCSSLoaderInstalled(self):\n return os.path.exists(\"/home/deck/homebrew/themes\")\n\n async def parseExtensionsForThemes(self):\n # Handle Updates by backing up images and wiping template (get version from json)\n log(\"Parsing theme\")\n if not os.path.exists(imagesFolder):\n log(\"Initialized images Folder\")\n os.mkdir(imagesFolder)\n\n if os.path.isdir(themeFolder):\n if not os.path.isdir(themeBaseFolder):\n os.mkdir(themeBaseFolder)\n \n log(\"Theme Directory\")\n \n addThemeThemeAtPath(themeBaseFolder)\n else:\n log(\"No Theme Directory\")\n\n # Asyncio-compatible long-running code, executed in a task when the plugin is loaded\n async def _main(self):\n global Initialized\n if not Initialized:\n Initialized = True\n log(\"Initializing\")\n if not os.path.exists(imagesFolder):\n log(\"Initialized Directory\")\n os.mkdir(imagesFolder)\n else:\n return\n","repo_name":"joamjoamjoam/DeckWallpapers","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"7414106662","text":"from turtle import Vec2D\nimport numpy as np\nimport cv2\nimport os\n\n\ndef data_preparation():\n root_path = './train'\n output_root_path = './frame'\n actlist = os.listdir(root_path)\n for action in actlist:\n # print(action)\n\n subpath = os.path.join(root_path, action) # ./train/Drink\n\n videolist = os.listdir(subpath)\n for video_name in videolist:\n # print(video_name)\n output_subpath = os.path.join(output_root_path, 'v_' + action + '_g' + os.path.splitext(video_name)[0])\n os.mkdir(output_subpath)\n full_path = os.path.join(root_path, action, video_name)\n video2frame(full_path, output_subpath)\n\n\n\ndef video2frame(video_path, output_subpath):\n cap = cv2.VideoCapture(video_path)\n frame_num = 1\n while True:\n ret, frame = cap.read()\n # print(type(frame)) # numpy.ndarray\n # print(frame.shape) # (240,320,3)\n # frame_path = './video/' + str(frame_num) + '.png' # name like 1.png\n filename = 'frame' + str(frame_num).zfill(6) + '.jpg'\n\n output_path = os.path.join(output_subpath, filename)\n # validate_output_path = \n \n if not ret:\n break\n \n cv2.imwrite(output_path, frame)\n frame_num += 1\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n\ndef generate_mapping_list():\n f = open('mapping_table.txt', encoding = \"utf-8\")\n mapping_list = []\n\n line = f.readline()\n while line:\n mapping_list.append(line.split()[1])\n line = f.readline()\n f.close()\n\n return mapping_list\n\n\n\ndef validate_preparation(mapping_list):\n f = open('validate.txt', encoding = \"utf-8\")\n root_path = './validate'\n output_root_path = './validate_frame'\n os.mkdir(output_root_path)\n\n line = f.readline()\n while line:\n index = int(line.split()[1])\n action = mapping_list[index]\n video_name = line.split()[2]\n video_path = os.path.join(root_path, video_name)\n output_subpath = os.path.join(output_root_path, 'v_' + action + '_g' + os.path.splitext(video_name)[0])\n os.mkdir(output_subpath)\n video2frame(video_path, output_subpath)\n\n line = f.readline()\n\n f.close()\n\n\n\ndef test_preparation(mapping_list):\n f = open('test.txt', encoding = \"utf-8\")\n root_path = './test'\n output_root_path = './test_frame'\n os.mkdir(output_root_path)\n \n line = f.readline()\n while line:\n index = int(line.split()[1])\n action = mapping_list[index]\n video_name = line.split()[2]\n video_path = os.path.join(root_path, video_name)\n output_subpath = os.path.join(output_root_path, 'v_' + action + '_g' + os.path.splitext(video_name)[0])\n os.mkdir(output_subpath)\n video2frame(video_path, output_subpath)\n\n line = f.readline()\n\n f.close()\n\n\n\nif __name__ == '__main__':\n mapping_list = generate_mapping_list()\n\n # data_preparation() # train\n\n # validate_preparation(mapping_list) # validate\n\n # test_preparation(mapping_list) # test\n \n","repo_name":"rogerongzy/action_recognition_dark","sub_path":"video_data_fomating.py","file_name":"video_data_fomating.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70357713445","text":"__all__ = [\n \"__title__\", \"__summary__\", \"__uri__\", \"__version__\", \"__author__\",\n \"__email__\", \"__license__\", \"__copyright__\",\n]\n\n__title__ = \"ciscosparkbot\"\n__summary__ = \"Python Bot for Cisco Spark\"\n__uri__ = \"http://github.com/imapex/ciscosparkbot\"\n\n__version__ = \"0.6.3\"\n\n__author__ = \"Cisco Systems, Inc.\"\n__email__ = \"imapex-admin@cisco.com\"\n\n__license__ = \"Apache License, Version 2.0\"\n__copyright__ = \"2016 %s\" % __author__\n","repo_name":"imapex/ciscosparkbot","sub_path":"ciscosparkbot/__about__.py","file_name":"__about__.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"1531119702","text":"import os\nimport sys\nos.environ['USE_TORCH'] = '1'\nimport matplotlib.pyplot as plt\nfrom doctr.io import DocumentFile\nfrom doctr.models import ocr_predictor\n# Read the file\n\nimages = os.listdir(\"images\")\nimages = list(map(lambda x: x.replace(x, \"images/\" + x), images))\nprint(images)\ndoc = DocumentFile.from_images(images)\n# Instantiate a pretrained model\npredictor = ocr_predictor(pretrained=True)\nresult = predictor(doc)\n\n# JSON export\njson_export = result.export()\n#Processing\ntext = []\nfor page_index, page in enumerate(json_export[\"pages\"]):\n pagelines = []\n \n # Add image path to the page\n image_path = images[page_index]\n d_image = {\"imagePath\": image_path}\n pagelines.append(d_image)\n \n for block in page[\"blocks\"]:\n for line in block[\"lines\"]:\n sentence = \"\"\n for word in line[\"words\"]:\n sentence += word[\"value\"] + \" \"\n d_label = {\"labelText\": sentence}\n pagelines.append(d_label)\n \n \n d_page = {\"labels\": pagelines}\n text.append(d_page)\n\nd3 = {\"pages\": text}\n\n#Writing to json\nimport json\nwith open(\"docgen/src/labels.json\", \"w\") as f:\n json.dump(d3, f)","repo_name":"sanjay81098/FigmaToDoc","sub_path":"ocr/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8312779259","text":"# Mostly from: https://github.com/ylytkin/python-lasvm/blob/main/lasvm/lasvm.py\n\nfrom typing import List, Union, Tuple, Optional\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom lasvm.base_kernel_method import BaseKernelMethod\nfrom sail.models.native.base import BaseEstimator\n\n__all__ = [\n 'LaSVM'\n]\n\n\nclass LaSVM(BaseKernelMethod, BaseEstimator):\n \"\"\"The LaSVM online learning algorithm for binary classification\n as described here:\n https://leon.bottou.org/papers/bordes-ertekin-weston-bottou-2005\n\n Note that some positive and negative samples are needed to\n initialize the model.\n\n Example\n -------\n x = np.array([[ 1.84, -1.7 ],\n [-0.52, 0.27],\n [-0.23, -0.26],\n [-1.42, 0.17],\n [ 1. , -1. ],\n [ 0.01, 1.71],\n [-0.53, 1.7 ],\n [-0.27, 0.06]])\n\n y = np.array([1, 1, 0, 0, 1, 0, 0, 1])\n\n pos_samples = x[:2]\n neg_samples = x[2:4]\n\n lasvm = LaSVM(pos_samples, neg_samples)\n lasvm.fit(x, y)\n\n lasvm.score(x, y) # 0.875\n\n Parameters\n ----------\n pos_samples : numpy array\n positive samples, shape (n_vectors, n_features)\n neg_samples : numpy array\n negative samples, shape (n_vectors, n_features)\n c : float, default 1\n regularization parameter\n kernel : {'rbf', 'linear', 'poly'}, default 'rbf'\n kernel name\n gamma : 'scale' or float, default 'scale'\n rbf and polynomial kernel gamma parameter (ignored for linear\n kernel). If 'scale' is passed, the actual value of gamma is\n calculated on initialization as::\n 1 / x.shape[1] / x.var()\n degree : int, default 3\n polynomial kernel degree parameter (ignored for the rest of\n the kernels)\n coef0 : float, default 0\n polynomial kernel coef0 parameter (ignored for the rest of\n the kernels)\n tol : float\n tolerance parameter\n niter : int\n number of iterations on final step\n\n Attributes\n ----------\n c : float\n regularization parameter\n kernel : {'rbf', 'linear', 'poly'}\n kernel name\n gamma : 'scale' or float\n rbf and polynomial kernel gamma parameter\n gamma_ : float\n calculated gamma parameter\n degree : int, default 3\n polynomial kernel degree parameter\n coef0 : float, default 0\n polynomial kernel coef0 parameter\n tol : float\n tolerance parameter\n niter : int\n number of iterations on final step\n support_vectors : numpy array\n support vectors, shape (n_vectors, n_features)\n alpha : numpy array\n model coefficients, shape (n_vectors,)\n intercept : float\n model intercept\n target : numpy array\n support vector class labels, shape (n_vectors,)\n kernel_mx : numpy array\n pair-wise kernel values of support vectors,\n shape (n_vectors, n_vectors)\n gradient : numpy array\n gradient, shape (n_vectors,)\n a : numpy array\n lower bounds, shape (n_vectors,)\n b : numpy array\n upper bounds, shape (n_vectors,)\n delta : float\n current delta\n\n Methods\n -------\n partial_fit(x, y)\n partially fit the model on the training data\n finalize()\n finalize the training process after fitting is done\n fit(x, y)\n fit the model on the training data (equivalent to\n partial_fit with subsequent finalize)\n predict(x)\n predict class labels of the test data\n score(x, y)\n calculate model accuracy on the given data\n\n Properties\n ----------\n coef_ : numpy array\n coefficients of the separating hyperplane in the linear\n kernel case, shape (n_vectors,)\n \"\"\"\n\n ERR = 0.00001\n\n class GradientPairNotFoundError(Exception):\n def __init__(self):\n super().__init__('could not find a maximum gradient pair')\n\n def __init__(\n self,\n pos_samples: np.ndarray,\n neg_samples: np.ndarray,\n c: float = 1,\n kernel: str = 'rbf',\n gamma: Union[float, str] = 'scale',\n degree: int = 3,\n coef0: float = 0,\n tol: float = 0.0001,\n niter: int = 10000,\n ) -> None:\n super().__init__(kernel=kernel, gamma=gamma, degree=degree, coef0=coef0)\n\n self.c = c\n\n self.tol = tol\n\n self.target = np.empty(shape=(0,))\n self.kernel_mx = np.empty(shape=(0, 0))\n self.gradient = np.empty(shape=(0,))\n self.a = np.empty(shape=(0,))\n self.b = np.empty(shape=(0,))\n\n self.delta = None\n self.niter = niter\n\n self._initialize(pos_samples, neg_samples)\n\n def partial_fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n verbose: bool = False,\n shuffle: bool = False,\n ) -> 'LaSVM':\n \"\"\"Partially (incrementally) fit model to the given data.\n\n Array `x` must be 2-dimensional of shape (n_vectors, n_features).\n Array `y` must be 1-dimensional of shape (n_vectors,) and contain only\n class labels 0 or 1.\n\n Parameters\n ----------\n x : numpy array\n data, shape (n_vectors, n_features)\n y : numpy array\n class labels, shape (n_vectors,), valued 0 or 1\n shuffle : bool\n shuffle data before fitting\n verbose : bool\n set verbosity\n\n Returns\n -------\n self\n \"\"\"\n\n x = x.copy()\n y = self._prepare_targets(y)\n\n ids = np.arange(x.shape[0])\n\n if shuffle:\n np.random.shuffle(ids)\n\n for i in tqdm(ids, disable=not verbose):\n x0 = x[[i]]\n y0 = y[[i]]\n\n self._process(x=x0, y=y0)\n self._reprocess()\n\n return self\n\n def fit(\n self,\n x: np.ndarray,\n y: np.ndarray,\n verbose: bool = False,\n shuffle: bool = False,\n ) -> 'LaSVM':\n \"\"\"Fit model to the given data. Equivalent to partial_fit with\n subsequent finalize.\n\n Array `x` must be 2-dimensional of shape (n_vectors, n_features).\n Array `y` must be 1-dimensional of shape (n_vectors,) and contain only\n class labels 0 or 1.\n\n Parameters\n ----------\n x : numpy array\n data, shape (n_vectors, n_features)\n y : numpy array\n class labels, shape (n_vectors,), valued 0 or 1\n shuffle : bool\n shuffle data before fitting\n verbose : bool\n set verbosity\n\n Returns\n -------\n self\n \"\"\"\n\n self.partial_fit(x, y, shuffle=shuffle, verbose=verbose)\n\n if verbose:\n print('Finalizing')\n\n self.finalize(verbose=verbose)\n\n return self\n\n def finalize(self, niter: Optional[int] = None, verbose: bool = False) -> 'LaSVM':\n \"\"\"Perform the final step of learning (i.e. attempt to get delta\n below tau).\n\n Parameters\n ----------\n niter : int\n number of finalizing iterations\n verbose : bool\n set verbosity\n\n Returns\n -------\n self\n \"\"\"\n\n niter = niter or self.niter\n\n tqdm_bar = tqdm(total=niter) if verbose else None\n broke_loop = False\n\n for _ in range(niter):\n self._reprocess()\n\n if self.delta <= self.tol:\n broke_loop = True\n break\n\n if verbose:\n tqdm_bar.update(1)\n\n if not broke_loop:\n print(f'Warning: delta did not converge below tol in {niter} iterations')\n\n if verbose:\n tqdm_bar.update(tqdm_bar.total - tqdm_bar.n)\n tqdm_bar.close()\n\n return self\n\n def __repr__(self):\n return 'LaSVM()'\n\n def _initialize(self, pos_samples: np.ndarray, neg_samples: np.ndarray) -> 'LaSVM':\n \"\"\"Initialize model by adding some positive and negative samples as\n support vectors.\n\n Parameters\n ----------\n pos_samples : numpy array\n positive samples, shape (n_vectors, n_features)\n neg_samples : numpy array\n negative samples, shape (n_vectors, n_features)\n\n Returns\n -------\n self\n \"\"\"\n\n self._remove_all_support_vectors()\n\n pos_samples = pos_samples.copy()\n neg_samples = neg_samples.copy()\n\n if self.gamma == 'scale':\n self.gamma_ = self._scaled_gamma(np.vstack([pos_samples, neg_samples]))\n\n self.support_vectors = np.empty(shape=(0, pos_samples.shape[1]))\n\n self._add_support_vectors(pos_samples, y=np.ones(pos_samples.shape[0]))\n self._add_support_vectors(neg_samples, y=- np.ones(neg_samples.shape[0]))\n\n i, j = self._find_maximum_gradient_pair()\n self.intercept = (self.gradient[i] + self.gradient[j]) / 2\n self.delta = self.gradient[i] - self.gradient[j]\n\n return self\n\n def _add_support_vectors(self, x: np.ndarray, y: np.ndarray) -> None:\n \"\"\"Add support vectors with zero coefficients.\n\n Parameters\n ----------\n x : numpy array\n data, shape (n_vectors, n_features)\n y : numpy array\n class labels, shape (n_vectors, n_features)\n \"\"\"\n\n n_vectors = x.shape[0]\n\n self.support_vectors = np.vstack([self.support_vectors, x])\n self.alpha = np.append(self.alpha, np.zeros(n_vectors))\n self.target = np.append(self.target, y)\n\n new_kernel_values = self._kernel(x, self.support_vectors)\n\n self.kernel_mx = np.vstack([self.kernel_mx, new_kernel_values[:, :-n_vectors]])\n self.kernel_mx = np.hstack([self.kernel_mx, new_kernel_values.T])\n\n gradient = y - new_kernel_values.dot(self.alpha)\n self.gradient = np.append(self.gradient, gradient)\n\n a = y * self.c\n print(type(a))\n a[a > 0] = 0\n self.a = np.append(self.a, a)\n\n b = y * self.c\n b[b < 0] = 0\n self.b = np.append(self.b, b)\n\n def _remove_support_vectors(self, vector_ids: List[int]) -> None:\n \"\"\"Remove support vectors with given ids.\n\n Parameters\n ----------\n vector_ids : list\n ids of vectors to remove\n \"\"\"\n\n self.support_vectors = np.delete(self.support_vectors, vector_ids, axis=0)\n self.alpha = np.delete(self.alpha, vector_ids)\n self.kernel_mx = np.delete(self.kernel_mx, vector_ids, axis=0)\n self.kernel_mx = np.delete(self.kernel_mx, vector_ids, axis=1)\n self.target = np.delete(self.target, vector_ids)\n self.gradient = np.delete(self.gradient, vector_ids)\n self.a = np.delete(self.a, vector_ids)\n self.b = np.delete(self.b, vector_ids)\n\n def _remove_all_support_vectors(self) -> None:\n n_sv = self.support_vectors.shape[0]\n\n if n_sv == 0:\n return\n\n to_remove = list(range(n_sv))\n self._remove_support_vectors(to_remove)\n\n def _is_violating_pair(self, i: int, j: int) -> bool:\n return self.alpha[i] < self.b[i] \\\n and self.alpha[j] > self.a[j] \\\n and self.gradient[i] - self.gradient[j] > self.tol\n\n def _find_max_gradient_id(self) -> int:\n \"\"\"Find id of the vector with conditionally maximal gradient.\n\n Returns\n -------\n int\n vector id\n \"\"\"\n\n mask = self.alpha < self.b\n mask_ids = np.where(mask)[0]\n i = mask_ids[np.argmax(self.gradient[mask])]\n\n return i\n\n def _find_min_gradient_id(self) -> int:\n \"\"\"Find id of the vector with conditionally minimal gradient.\n\n Returns\n -------\n int\n vector id\n \"\"\"\n\n mask = self.alpha > self.a\n mask_ids = np.where(mask)[0]\n j = mask_ids[np.argmin(self.gradient[mask])]\n\n return j\n\n def _find_maximum_gradient_pair(self) -> Tuple[int, int]:\n return self._find_max_gradient_id(), self._find_min_gradient_id()\n\n def _update_parameters(self, i: int, j: int) -> None:\n lambda_ = min(\n (self.gradient[i] - self.gradient[j]) / (\n self.kernel_mx[i, i] + self.kernel_mx[j, j] - 2 * self.kernel_mx[i, j]),\n self.b[i] - self.alpha[i],\n self.alpha[j] - self.a[j],\n )\n\n self.alpha[i] = self.alpha[i] + lambda_\n self.alpha[j] = self.alpha[j] - lambda_\n\n self.gradient = self.gradient - lambda_ * (self.kernel_mx[i] - self.kernel_mx[j])\n\n def _process(self, x: np.ndarray, y: np.ndarray) -> None:\n \"\"\"Process an object-target pair.\n\n Parameters\n ----------\n x : numpy array\n feature vector, shape (1, n_features)\n y : numpy array\n class label, shape (1,)\n \"\"\"\n\n if (((self.support_vectors - x) ** 2).sum(axis=1) ** 0.5 < self.ERR).any():\n return\n\n self._add_support_vectors(x, y)\n\n if y[0] == 1:\n i = self.support_vectors.shape[0] - 1\n j = self._find_min_gradient_id()\n\n else:\n j = self.support_vectors.shape[0] - 1\n i = self._find_max_gradient_id()\n\n if not self._is_violating_pair(i, j):\n return\n\n self._update_parameters(i=i, j=j)\n\n def _reprocess(self) -> None:\n \"\"\"Reprocess.\n \"\"\"\n\n i, j = self._find_maximum_gradient_pair()\n\n if not self._is_violating_pair(i, j):\n return\n\n self._update_parameters(i=i, j=j)\n\n i, j = self._find_maximum_gradient_pair()\n to_remove = []\n\n for k in np.where(np.abs(self.alpha) < self.ERR)[0]:\n if (self.target[k] == -1 and self.gradient[k] >= self.gradient[i]) \\\n or (self.target[k] == 1 and self.gradient[k] <= self.gradient[j]):\n to_remove.append(k)\n\n self.intercept = (self.gradient[i] + self.gradient[j]) / 2\n self.delta = self.gradient[i] - self.gradient[j]\n\n self._remove_support_vectors(to_remove)\n\n","repo_name":"IBM/sail","sub_path":"src/sail/models/native/lasvm.py","file_name":"lasvm.py","file_ext":"py","file_size_in_byte":14132,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"} +{"seq_id":"70131402084","text":"from pdfminer.converter import PDFLayoutAnalyzer\nfrom pdfminer.utils import mult_matrix, apply_matrix_pt, get_bound\nfrom pdfminer.layout import LTFigure\nimport six\n\ndef add_wh(attr):\n attr.update({\n \"height\": attr[\"y1\"] - attr[\"y0\"],\n \"width\": attr[\"x1\"] - attr[\"x0\"],\n })\n return attr\n\ndef render_image(self, name, stream):\n srcsize = (stream.get_any((\"W\", \"Width\")),\n stream.get_any((\"H\", \"Height\")))\n imagemask = stream.get_any((\"IM\", \"ImageMask\"))\n bits = stream.get_any((\"BPC\", \"BitsPerComponent\"), 1)\n colorspace = stream.get_any((\"CS\", \"ColorSpace\"))\n if not isinstance(colorspace, list):\n colorspace = [colorspace]\n\n item = {\n \"name\": name,\n \"srcsize\": srcsize,\n \"imagemask\": imagemask,\n \"colorspace\": colorspace,\n \"bits\": bits,\n \"stream\": stream,\n \"x0\": self.cur_item.x0,\n \"y0\": self.cur_item.y0,\n \"x1\": self.cur_item.x1,\n \"y1\": self.cur_item.y1,\n \"object_type\": \"image\",\n }\n self.cur_item.add(add_wh(item))\n return\n\nPDFLayoutAnalyzer.render_image = render_image\n\ndef paint_path(self, gstate, stroke, fill, evenodd, path):\n shape = ''.join(x[0] for x in path)\n if shape == 'ml':\n # horizontal/vertical line\n (_, x0, y0) = path[0]\n (_, x1, y1) = path[1]\n (x0, y0) = apply_matrix_pt(self.ctm, (x0, y0))\n (x1, y1) = apply_matrix_pt(self.ctm, (x1, y1))\n if x0 == x1 or y0 == y1:\n x0, y0, x1, y1 = get_bound([ (x0, y0), (x1, y1) ])\n\n item = add_wh({\n \"x0\": x0,\n \"y0\": y0,\n \"x1\": x1,\n \"y1\": y1,\n \"object_type\": \"line\",\n })\n\n if self.interpreter.parse_styles:\n item.update({\n \"stroke_width\": 0 if stroke is False else gstate.linewidth,\n \"stroke\": None if stroke is False else (gstate.scolor_hex or \"#000000\"),\n \"fill\": None if fill is False else (gstate.ncolor_hex or \"#000000\"),\n \"dash\": gstate.dash,\n \"evenodd\": evenodd,\n })\n\n self.cur_item.add(item)\n return\n\n if shape == 'mlllh':\n # rectangle\n (_, x0, y0) = path[0]\n (_, x1, y1) = path[1]\n (_, x2, y2) = path[2]\n (_, x3, y3) = path[3]\n (x0, y0) = apply_matrix_pt(self.ctm, (x0, y0))\n (x1, y1) = apply_matrix_pt(self.ctm, (x1, y1))\n (x2, y2) = apply_matrix_pt(self.ctm, (x2, y2))\n (x3, y3) = apply_matrix_pt(self.ctm, (x3, y3))\n if ((x0 == x1 and y1 == y2 and x2 == x3 and y3 == y0) or\n (y0 == y1 and x1 == x2 and y2 == y3 and x3 == x0)):\n y_min = min(y0, y1, y2, y3)\n y_max = max(y0, y1, y2, y3)\n x_min = min(x0, x1, x2, x3)\n x_max = max(x0, x1, x2, x3)\n item = add_wh({\n \"x0\": x_min,\n \"y0\": y_min,\n \"x1\": x_max,\n \"y1\": y_max,\n \"object_type\": \"rect\",\n })\n if self.interpreter.parse_styles:\n item.update({\n \"stroke_width\": 0 if stroke is False else gstate.linewidth,\n \"stroke\": None if stroke is False else (gstate.scolor_hex or \"#000000\"),\n \"fill\": None if fill is False else (gstate.ncolor_hex or \"#000000\"),\n \"dash\": gstate.dash,\n \"evenodd\": evenodd,\n })\n self.cur_item.add(item)\n return\n # other shapes\n pts = []\n for p in path:\n for i in range(1, len(p), 2):\n pts.append(apply_matrix_pt(self.ctm, (p[i], p[i+1])))\n x0, y0, x1, y1 = get_bound(pts)\n\n item = add_wh({\n \"x0\": x0,\n \"y0\": y0,\n \"x1\": x1,\n \"y1\": y1,\n \"points\": pts,\n \"path\": path,\n \"object_type\": \"curve\"\n })\n\n if self.interpreter.parse_styles:\n item.update({\n \"stroke_width\": 0 if stroke is False else gstate.linewidth,\n \"stroke\": None if stroke is False else (gstate.scolor_hex or \"#000000\"),\n \"fill\": None if fill is False else (gstate.ncolor_hex or \"#000000\"),\n \"dash\": gstate.dash,\n \"evenodd\": evenodd,\n })\n\n self.cur_item.add(item)\n return\n\nPDFLayoutAnalyzer.paint_path = paint_path\n\ndef render_char(self, matrix, font, fontsize, scaling, rise, cid):\n try:\n text = font.to_unichr(cid)\n assert isinstance(text, six.text_type), text\n except PDFUnicodeNotDefined:\n text = self.handle_undefined_char(font, cid)\n\n textwidth = font.char_width(cid)\n textdisp = font.char_disp(cid)\n adv = textwidth * fontsize * scaling\n\n # compute the boundary rectangle.\n if font.is_vertical():\n # vertical\n width = font.get_width() * fontsize\n (vx, vy) = textdisp\n if vx is None:\n vx = width * 0.5\n else:\n vx = vx * fontsize * .001\n vy = (1000 - vy) * fontsize * .001\n tx = -vx\n ty = vy + rise\n bll = (tx, ty+self.adv)\n bur = (tx+width, ty)\n else:\n # horizontal\n height = font.get_height() * fontsize\n descent = font.get_descent() * fontsize\n ty = descent + rise\n bll = (0, ty)\n bur = (adv, ty+height)\n (a, b, c, d, e, f) = matrix\n upright = (0 < a*d*scaling and b*c <= 0)\n (x0, y0) = apply_matrix_pt(matrix, bll)\n (x1, y1) = apply_matrix_pt(matrix, bur)\n if x1 < x0:\n (x0, x1) = (x1, x0)\n if y1 < y0:\n (y0, y1) = (y1, y0)\n\n if font.is_vertical():\n size = x1 - x0\n else:\n size = y1 - y0\n\n # cf. \"Table 106 – Text rendering modes\" of PDF 1.7 spec\n gs = self.interpreter.graphicstate\n r = self.interpreter.textstate.render\n if r in (0, 2, 4, 6):\n fill = gs.ncolor_hex\n else:\n fill = None\n if r in (1, 2, 5, 6):\n stroke = gs.scolor_hex\n else:\n stroke = None\n\n item = add_wh({\n \"x0\": x0,\n \"y0\": y0,\n \"x1\": x1,\n \"y1\": y1,\n \"fontname\": font.fontname,\n \"size\": size,\n \"text\": text,\n \"object_type\": \"char\",\n })\n\n if self.interpreter.parse_styles:\n item.update({\n \"fill\": fill,\n \"stroke\": stroke,\n })\n\n self.cur_item.add(item)\n return adv\n\nPDFLayoutAnalyzer.render_char = render_char\n","repo_name":"zadahmed/wisdomapi","sub_path":"wisdomenv/lib/python3.6/site-packages/aborted-patches/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":6468,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"29693722222","text":"from odoo import http\nfrom odoo.http import request\nimport json\nimport time\n\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass Prismic(http.Controller):\n @http.route('/pga-manager/prismic', type='http', auth='none', cors='*', csrf='True')\n def prismic(self, **kw):\n result_size = 0\n results = []\n camps = request.env['camp'].sudo().search([])\n _logger.critical(camps)\n for camp in camps.read(['name', 'start_date', 'end_date', 'description', 'age_min', 'age_max']):\n _logger.critical(camp)\n camp_sku = {\n 'id': str(camp['id']),\n 'title': camp['name'],\n 'description': str(camp['description']),\n 'image_url': 'http://...',\n 'last_update': int(time.time()),\n 'blob': {\n 'sku': camp['id'],\n 'title': camp['name'],\n 'description': 'description of first item...',\n 'image_url': 'https://..'\n }\n }\n results.append(camp_sku)\n result_size += 1\n _logger.critical(results)\n result_json = {\n 'results_size': result_size,\n 'results': results\n }\n return json.dumps(result_json)\n","repo_name":"Preston-D/pga-odoo","sub_path":"addons/asm_odoo_camp_scheduler/controllers/prismic.py","file_name":"prismic.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20303680131","text":"from git import Repo\nfrom git import InvalidGitRepositoryError, NoSuchPathError\nfrom flask import current_app\nimport os\nimport time\n\n\ndef get_repo_list():\n path = current_app.config.get('REPO_ROOT', '')\n\n dirs = [(os.path.join(path, d), d) for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]\n res = []\n for p, f in dirs:\n try:\n repo = Repo(p)\n rep_info = {}\n if repo.refs:\n try:\n commit = repo.commit()\n rep_info[\"author\"] = commit.author\n rep_info[\"date\"] = time.strftime('%Y-%m-%d %H:%M:%S%z', time.gmtime(commit.committed_date))\n except ValueError:\n pass\n rep_info[\"name\"] = f\n rep_info[\"desc\"] = repo.description\n rep_info[\"path\"] = p\n\n res.append(rep_info)\n except (InvalidGitRepositoryError, NoSuchPathError) as e:\n print(e)\n return res\n\n\ndef get_repo_info(repo_name=''):\n res = []\n path = current_app.config.get('REPO_ROOT', '')\n\n try:\n repo = Repo(os.path.join(path, repo_name))\n res = repo.tree()\n except (InvalidGitRepositoryError, NoSuchPathError) as e:\n print(e)\n return res","repo_name":"Gloreus/projectors","sub_path":"app/data.py","file_name":"data.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":"9237189686","text":"import json\nimport logging\nimport os\nimport pathlib\nimport re\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple, Union\n\nimport torch\n\nfrom .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD\nfrom .model import CLIP, CustomTextCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict,\\\n resize_pos_embed, get_cast_dtype\nfrom .coca_model import CoCa\nfrom .loss import ClipLoss, DistillClipLoss, CoCaLoss\nfrom .openai import load_openai_model\nfrom .pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained, list_pretrained_tags_by_model, download_pretrained_from_hf\nfrom .transform import image_transform, AugmentationCfg\nfrom .tokenizer import HFTokenizer, tokenize\n\n\nHF_HUB_PREFIX = 'hf-hub:'\n_MODEL_CONFIG_PATHS = [Path(__file__).parent / f\"model_configs/\"]\n_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs\n\n\ndef _natural_key(string_):\n return [int(s) if s.isdigit() else s for s in re.split(r'(\\d+)', string_.lower())]\n\n\ndef _rescan_model_configs():\n global _MODEL_CONFIGS\n\n config_ext = ('.json',)\n config_files = []\n for config_path in _MODEL_CONFIG_PATHS:\n if config_path.is_file() and config_path.suffix in config_ext:\n config_files.append(config_path)\n elif config_path.is_dir():\n for ext in config_ext:\n config_files.extend(config_path.glob(f'*{ext}'))\n\n for cf in config_files:\n with open(cf, 'r') as f:\n model_cfg = json.load(f)\n if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')):\n _MODEL_CONFIGS[cf.stem] = model_cfg\n\n _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))}\n\n\n_rescan_model_configs() # initial populate of model config registry\n\n\ndef list_models():\n \"\"\" enumerate available model architectures based on config files \"\"\"\n return list(_MODEL_CONFIGS.keys())\n\n\ndef add_model_config(path):\n \"\"\" add model config path or file and update registry \"\"\"\n if not isinstance(path, Path):\n path = Path(path)\n _MODEL_CONFIG_PATHS.append(path)\n _rescan_model_configs()\n\n\ndef get_model_config(model_name):\n if model_name in _MODEL_CONFIGS:\n return deepcopy(_MODEL_CONFIGS[model_name])\n else:\n return None\n\n\ndef get_tokenizer(model_name):\n if model_name.startswith(HF_HUB_PREFIX):\n tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):])\n else:\n config = get_model_config(model_name)\n tokenizer = HFTokenizer(\n config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize\n return tokenizer\n\n\ndef load_state_dict(checkpoint_path: str, map_location='cpu'):\n checkpoint = torch.load(checkpoint_path, map_location=map_location)\n if isinstance(checkpoint, dict) and 'state_dict' in checkpoint:\n state_dict = checkpoint['state_dict']\n else:\n state_dict = checkpoint\n if next(iter(state_dict.items()))[0].startswith('module'):\n state_dict = {k[7:]: v for k, v in state_dict.items()}\n return state_dict\n\n\ndef load_checkpoint(model, checkpoint_path, strict=True):\n state_dict = load_state_dict(checkpoint_path)\n # detect old format and make compatible with new format\n if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'):\n state_dict = convert_to_custom_text_state_dict(state_dict)\n resize_pos_embed(state_dict, model)\n incompatible_keys = model.load_state_dict(state_dict, strict=strict)\n return incompatible_keys\n\n\ndef create_model(\n model_name: str,\n pretrained: Optional[str] = None,\n precision: str = 'fp32',\n device: Union[str, torch.device] = 'cpu',\n jit: bool = False,\n force_quick_gelu: bool = False,\n force_custom_text: bool = False,\n force_patch_dropout: Optional[float] = None,\n force_image_size: Optional[Union[int, Tuple[int, int]]] = None,\n pretrained_image: bool = False,\n pretrained_hf: bool = True,\n cache_dir: Optional[str] = None,\n output_dict: Optional[bool] = None,\n require_pretrained: bool = False,\n):\n has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX)\n if has_hf_hub_prefix:\n model_id = model_name[len(HF_HUB_PREFIX):]\n checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir)\n config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir)\n\n with open(config_path, 'r', encoding='utf-8') as f:\n config = json.load(f)\n pretrained_cfg = config['preprocess_cfg']\n model_cfg = config['model_cfg']\n else:\n model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names\n checkpoint_path = None\n pretrained_cfg = {}\n model_cfg = None\n\n if isinstance(device, str):\n device = torch.device(device)\n\n if pretrained and pretrained.lower() == 'openai':\n logging.info(f'Loading pretrained {model_name} from OpenAI.')\n model = load_openai_model(\n model_name,\n precision=precision,\n device=device,\n jit=jit,\n cache_dir=cache_dir,\n )\n\n # to always output dict even if it is clip\n if output_dict and hasattr(model, \"output_dict\"):\n model.output_dict = True\n else:\n model_cfg = model_cfg or get_model_config(model_name)\n if model_cfg is not None:\n logging.info(f'Loaded {model_name} model config.')\n else:\n logging.error(f'Model config for {model_name} not found; available models {list_models()}.')\n raise RuntimeError(f'Model config for {model_name} not found.')\n\n if force_quick_gelu:\n # override for use of QuickGELU on non-OpenAI transformer models\n model_cfg[\"quick_gelu\"] = True\n\n if force_patch_dropout is not None:\n # override the default patch dropout value\n model_cfg[\"vision_cfg\"][\"patch_dropout\"] = force_patch_dropout\n\n if force_image_size is not None:\n # override model config's image size\n model_cfg[\"vision_cfg\"][\"image_size\"] = force_image_size\n\n if pretrained_image:\n if 'timm_model_name' in model_cfg.get('vision_cfg', {}):\n # pretrained weight loading for timm models set via vision_cfg\n model_cfg['vision_cfg']['timm_model_pretrained'] = True\n else:\n assert False, 'pretrained image towers currently only supported for timm models'\n\n cast_dtype = get_cast_dtype(precision)\n is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {})\n custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model\n\n if custom_text:\n if is_hf_model:\n model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf\n if \"coca\" in model_name:\n model = CoCa(**model_cfg, cast_dtype=cast_dtype)\n else:\n model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype)\n else:\n model = CLIP(**model_cfg, cast_dtype=cast_dtype)\n\n pretrained_loaded = False\n if pretrained:\n checkpoint_path = ''\n pretrained_cfg = get_pretrained_cfg(model_name, pretrained)\n if pretrained_cfg:\n checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir)\n elif os.path.exists(pretrained):\n checkpoint_path = pretrained\n\n if checkpoint_path:\n logging.info(f'Loading pretrained {model_name} weights ({pretrained}).')\n load_checkpoint(model, checkpoint_path)\n else:\n error_str = (\n f'Pretrained weights ({pretrained}) not found for model {model_name}.'\n f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.')\n logging.warning(error_str)\n raise RuntimeError(error_str)\n pretrained_loaded = True\n elif has_hf_hub_prefix:\n logging.info(f'Loading pretrained {model_name} weights ({pretrained}).')\n load_checkpoint(model, checkpoint_path)\n pretrained_loaded = True\n\n if require_pretrained and not pretrained_loaded:\n # callers of create_model_from_pretrained always expect pretrained weights\n raise RuntimeError(\n f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.')\n\n model.to(device=device)\n if precision in (\"fp16\", \"bf16\"):\n convert_weights_to_lp(model, dtype=torch.bfloat16 if precision == 'bf16' else torch.float16)\n\n # set image / mean metadata from pretrained_cfg if available, or use default\n model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN\n model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD\n\n # to always output dict even if it is clip\n if output_dict and hasattr(model, \"output_dict\"):\n model.output_dict = True\n\n if jit:\n model = torch.jit.script(model)\n\n return model\n\n\ndef create_loss(args):\n if args.distill:\n return DistillClipLoss(\n local_loss=args.local_loss,\n gather_with_grad=args.gather_with_grad,\n cache_labels=True,\n rank=args.rank,\n world_size=args.world_size,\n use_horovod=args.horovod,\n )\n elif \"coca\" in args.model.lower():\n return CoCaLoss(\n caption_loss_weight=args.coca_caption_loss_weight,\n clip_loss_weight=args.coca_contrastive_loss_weight,\n local_loss=args.local_loss,\n gather_with_grad=args.gather_with_grad,\n cache_labels=True,\n rank=args.rank,\n world_size=args.world_size,\n use_horovod=args.horovod,\n )\n return ClipLoss(\n local_loss=args.local_loss,\n gather_with_grad=args.gather_with_grad,\n cache_labels=True,\n rank=args.rank,\n world_size=args.world_size,\n use_horovod=args.horovod,\n )\n\n\ndef create_model_and_transforms(\n model_name: str,\n pretrained: Optional[str] = None,\n precision: str = 'fp32',\n device: Union[str, torch.device] = 'cpu',\n jit: bool = False,\n force_quick_gelu: bool = False,\n force_custom_text: bool = False,\n force_patch_dropout: Optional[float] = None,\n force_image_size: Optional[Union[int, Tuple[int, int]]] = None,\n pretrained_image: bool = False,\n pretrained_hf: bool = True,\n image_mean: Optional[Tuple[float, ...]] = None,\n image_std: Optional[Tuple[float, ...]] = None,\n aug_cfg: Optional[Union[Dict[str, Any], AugmentationCfg]] = None,\n cache_dir: Optional[str] = None,\n output_dict: Optional[bool] = None,\n):\n model = create_model(\n model_name,\n pretrained,\n precision=precision,\n device=device,\n jit=jit,\n force_quick_gelu=force_quick_gelu,\n force_custom_text=force_custom_text,\n force_patch_dropout=force_patch_dropout,\n force_image_size=force_image_size,\n pretrained_image=pretrained_image,\n pretrained_hf=pretrained_hf,\n cache_dir=cache_dir,\n output_dict=output_dict,\n )\n\n image_mean = image_mean or getattr(model.visual, 'image_mean', None)\n image_std = image_std or getattr(model.visual, 'image_std', None)\n preprocess_train = image_transform(\n model.visual.image_size,\n is_train=True,\n mean=image_mean,\n std=image_std,\n aug_cfg=aug_cfg,\n )\n preprocess_val = image_transform(\n model.visual.image_size,\n is_train=False,\n mean=image_mean,\n std=image_std,\n )\n\n return model, preprocess_train, preprocess_val\n\n\ndef create_model_from_pretrained(\n model_name: str,\n pretrained: Optional[str] = None,\n precision: str = 'fp32',\n device: Union[str, torch.device] = 'cpu',\n jit: bool = False,\n force_quick_gelu: bool = False,\n force_custom_text: bool = False,\n force_image_size: Optional[Union[int, Tuple[int, int]]] = None,\n return_transform: bool = True,\n image_mean: Optional[Tuple[float, ...]] = None,\n image_std: Optional[Tuple[float, ...]] = None,\n cache_dir: Optional[str] = None,\n):\n model = create_model(\n model_name,\n pretrained,\n precision=precision,\n device=device,\n jit=jit,\n force_quick_gelu=force_quick_gelu,\n force_custom_text=force_custom_text,\n force_image_size=force_image_size,\n cache_dir=cache_dir,\n require_pretrained=True,\n )\n\n if not return_transform:\n return model\n\n image_mean = image_mean or getattr(model.visual, 'image_mean', None)\n image_std = image_std or getattr(model.visual, 'image_std', None)\n preprocess = image_transform(\n model.visual.image_size,\n is_train=False,\n mean=image_mean,\n std=image_std,\n )\n\n return model, preprocess\n","repo_name":"zideliu/StyleDrop-PyTorch","sub_path":"open_clip/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":13401,"program_lang":"python","lang":"en","doc_type":"code","stars":501,"dataset":"github-code","pt":"52"} +{"seq_id":"6073044730","text":"# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n#########################################################################\n\n@auth.requires_membership('user_3')\ndef manage():\n grid = SQLFORM.smartgrid(db.recipe)\n return dict(grid=grid)\ndef index():\n return locals()\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/bulk_register\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users\n \"\"\"\n return dict(form=auth())\n\n\n@cache.action()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\ndef list():\n id=int(request.vars.id)\n if id>0:\n back=id-1\n else:\n back=id\n #form=SQLFORM(db.recipe,fields=['category'])\n recipes = db().select(db.recipe.ALL, orderby=db.recipe.created_on, limitby=(id*10,id*10+10))\n return dict(recipes=recipes, k = id + 1, back = back)\n\n@auth.requires_login()\ndef upload():\n form = SQLFORM(db.recipe).process()\n return dict(form=form)\n\ndef show():\n recipe = db.recipe(request.args(0)) or redirect(URL('index'))\n recipe_id = request.args(0,cast=int)\n rec = db.recipe(recipe_id) or redirect(URL('index'))\n likes = db(db.recipe_likes.recipe == recipe_id).count()\n if auth.user_id:\n liked = db((db.recipe_likes.recipe == recipe_id) & (db.recipe_likes.liked_by == auth.user_id)).select()\n liked = True if len(liked) == 1 else False\n else:\n liked = False\n return locals()\n\n@auth.requires_login()\ndef myrecipe():\n if len(request.args): page=int(request.args[0])\n else: page=0\n items_per_page=10\n limitby=(page*items_per_page,(page+1)*items_per_page+1)\n recipe = db(db.recipe.user_id==auth.user_id).select(orderby=~db.recipe.created_on,limitby=limitby)\n return dict(recipe=recipe,page=page,items_per_page=items_per_page)\n\n@auth.requires_login()\ndef usermanage():\n query=db.recipe.user_id==db.auth_user(auth.user_id).id\n ##query = db.image.id>9\n grid = SQLFORM.grid(query)\n grid = SQLFORM.grid(query,user_signature=True,paginate=10,csv=False,maxtextlength=100)\n return dict(grid=grid)\n\n\n\n\n@auth.requires_login()\ndef like():\n recipe_id = request.args(0,cast=int)\n rec = db.recipe(recipe_id) or redirect(URL('index')) # Check recipe_id validity\n liked = db((db.recipe_likes.recipe == recipe_id) & (db.recipe_likes.liked_by == auth.user_id)).count()\n liked = True if liked == 1 else False\n if not liked:\n db.recipe_likes.insert(recipe=recipe_id, liked_by=auth.user_id)\n redirect(URL('show', args=request.args))\n return dict()\n\n@auth.requires_login()\ndef unlike():\n recipe_id = request.args(0,cast=int)\n rec = db.recipe(recipe_id) or redirect(URL('index')) # Check recipe_id validity\n liked = db((db.recipe_likes.recipe == recipe_id) & (db.recipe_likes.liked_by == auth.user_id)).select().first()\n if liked:\n del db.recipe_likes[liked.id]\n redirect(URL('show', args=request.args))\n return dict()\n","repo_name":"anubhabsen/cookbook","sub_path":"applications/CookPad_Working/controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"30570266792","text":"from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple\n\nfrom latex2mathml import commands\nfrom latex2mathml.exceptions import (\n DenominatorNotFoundError,\n DoubleSubscriptsError,\n DoubleSuperscriptsError,\n ExtraLeftOrMissingRightError,\n InvalidAlignmentError,\n InvalidStyleForGenfracError,\n InvalidWidthError,\n LimitsMustFollowMathOperatorError,\n MissingEndError,\n MissingSuperScriptOrSubscriptError,\n NoAvailableTokensError,\n NumeratorNotFoundError,\n)\nfrom latex2mathml.symbols_parser import convert_symbol\nfrom latex2mathml.tokenizer import tokenize\n\n\nclass Node(NamedTuple):\n token: str\n children: Optional[Tuple[Any, ...]] = None\n delimiter: Optional[str] = None\n alignment: Optional[str] = None\n text: Optional[str] = None\n attributes: Optional[Dict[str, str]] = None\n modifier: Optional[str] = None\n\n\ndef walk(data: str) -> List[Node]:\n tokens = tokenize(data)\n return _walk(tokens)\n\n\ndef _walk(tokens: Iterator[str], terminator: Optional[str] = None, limit: int = 0) -> List[Node]:\n group: List[Node] = []\n token: str\n has_available_tokens = False\n for token in tokens:\n has_available_tokens = True\n if token == terminator:\n delimiter = None\n if terminator == commands.RIGHT:\n delimiter = next(tokens)\n group.append(Node(token=token, delimiter=delimiter))\n break\n elif (token == commands.RIGHT != terminator) or (token == commands.MIDDLE and terminator != commands.RIGHT):\n raise ExtraLeftOrMissingRightError\n elif token == commands.LEFT:\n delimiter = next(tokens)\n children = tuple(_walk(tokens, terminator=commands.RIGHT)) # make \\right as a child of \\left\n if len(children) == 0 or children[-1].token != commands.RIGHT:\n raise ExtraLeftOrMissingRightError\n node = Node(token=token, children=children if len(children) else None, delimiter=delimiter)\n elif token == commands.OPENING_BRACE:\n children = tuple(_walk(tokens, terminator=commands.CLOSING_BRACE))\n if len(children) and children[-1].token == commands.CLOSING_BRACE:\n children = children[:-1]\n node = Node(token=commands.BRACES, children=children)\n elif token in (commands.SUBSCRIPT, commands.SUPERSCRIPT):\n try:\n previous = group.pop()\n except IndexError:\n previous = Node(token=\"\") # left operand can be empty if not present\n\n if token == previous.token == commands.SUBSCRIPT:\n raise DoubleSubscriptsError\n if (token == previous.token == commands.SUPERSCRIPT) and (\n previous.children is not None\n and len(previous.children) >= 2\n and previous.children[1].token != commands.PRIME\n ):\n raise DoubleSuperscriptsError\n\n modifier = None\n if previous.token == commands.LIMITS:\n modifier = commands.LIMITS\n try:\n previous = group.pop()\n if not previous.token.startswith(\"\\\\\"): # TODO: Complete list of operators\n raise LimitsMustFollowMathOperatorError\n except IndexError:\n raise LimitsMustFollowMathOperatorError\n\n if token == commands.SUBSCRIPT and previous.token == commands.SUPERSCRIPT and previous.children is not None:\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n node = Node(\n token=commands.SUBSUP,\n children=(previous.children[0], *children, previous.children[1]),\n modifier=previous.modifier,\n )\n elif (\n token == commands.SUPERSCRIPT and previous.token == commands.SUBSCRIPT and previous.children is not None\n ):\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n node = Node(token=commands.SUBSUP, children=(*previous.children, *children), modifier=previous.modifier)\n elif (\n token == commands.SUPERSCRIPT\n and previous.token == commands.SUPERSCRIPT\n and previous.children is not None\n and previous.children[1].token == commands.PRIME\n ):\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n\n node = Node(\n token=commands.SUPERSCRIPT,\n children=(\n previous.children[0],\n Node(token=commands.BRACES, children=(previous.children[1], *children)),\n ),\n modifier=previous.modifier,\n )\n else:\n try:\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n except NoAvailableTokensError:\n raise MissingSuperScriptOrSubscriptError\n if previous.token in (commands.OVERBRACE, commands.UNDERBRACE):\n modifier = previous.token\n node = Node(token=token, children=(previous, *children), modifier=modifier)\n elif token == commands.APOSTROPHE:\n try:\n previous = group.pop()\n except IndexError:\n previous = Node(token=\"\") # left operand can be empty if not present\n\n if (\n previous.token == commands.SUPERSCRIPT\n and previous.children is not None\n and len(previous.children) >= 2\n and previous.children[1].token != commands.PRIME\n ):\n raise DoubleSuperscriptsError\n\n if (\n previous.token == commands.SUPERSCRIPT\n and previous.children is not None\n and len(previous.children) >= 2\n and previous.children[1].token == commands.PRIME\n ):\n node = Node(token=commands.SUPERSCRIPT, children=(previous.children[0], Node(token=commands.DPRIME)))\n elif previous.token == commands.SUBSCRIPT and previous.children is not None:\n node = Node(\n token=commands.SUBSUP,\n children=(*previous.children, Node(token=commands.PRIME)),\n modifier=previous.modifier,\n )\n else:\n node = Node(token=commands.SUPERSCRIPT, children=(previous, Node(token=commands.PRIME)))\n elif token in commands.COMMANDS_WITH_TWO_PARAMETERS:\n attributes = None\n children = tuple(_walk(tokens, terminator=terminator, limit=2))\n if token in (commands.OVERSET, commands.UNDERSET):\n children = children[::-1]\n node = Node(token=token, children=children, attributes=attributes)\n elif token in commands.COMMANDS_WITH_ONE_PARAMETER or token.startswith(commands.MATH):\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n node = Node(token=token, children=children)\n elif token == commands.NOT:\n try:\n next_node = tuple(_walk(tokens, terminator=terminator, limit=1))[0]\n if next_node.token.startswith(\"\\\\\"):\n negated_symbol = r\"\\n\" + next_node.token[1:]\n symbol = convert_symbol(negated_symbol)\n if symbol:\n node = Node(token=negated_symbol)\n group.append(node)\n continue\n node = Node(token=token)\n group.extend((node, next_node))\n continue\n except NoAvailableTokensError:\n node = Node(token=token)\n elif token in (commands.XLEFTARROW, commands.XRIGHTARROW):\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n if children[0].token == commands.OPENING_BRACKET:\n children = (\n Node(\n token=commands.BRACES, children=tuple(_walk(tokens, terminator=commands.CLOSING_BRACKET))[:-1]\n ),\n *tuple(_walk(tokens, terminator=terminator, limit=1)),\n )\n node = Node(token=token, children=children)\n elif token in (commands.HSKIP, commands.HSPACE, commands.KERN, commands.MKERN, commands.MSKIP, commands.MSPACE):\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n if children[0].token == commands.BRACES and children[0].children is not None:\n children = children[0].children\n node = Node(token=token, attributes={\"width\": children[0].token})\n elif token == commands.COLOR:\n attributes = {\"mathcolor\": next(tokens)}\n children = tuple(_walk(tokens, terminator=terminator))\n sibling = None\n if len(children) and children[-1].token == terminator:\n children, sibling = children[:-1], children[-1]\n group.append(Node(token=token, children=children, attributes=attributes))\n if sibling:\n group.append(sibling)\n break\n elif token == commands.STYLE:\n attributes = {\"style\": next(tokens)}\n next_node = tuple(_walk(tokens, terminator=terminator, limit=1))[0]\n node = next_node._replace(attributes=attributes)\n elif token in (\n *commands.BIG.keys(),\n *commands.BIG_OPEN_CLOSE.keys(),\n commands.FBOX,\n commands.HBOX,\n commands.MBOX,\n commands.MIDDLE,\n commands.TEXT,\n commands.TEXTBF,\n commands.TEXTIT,\n commands.TEXTRM,\n commands.TEXTSF,\n commands.TEXTTT,\n ):\n node = Node(token=token, text=next(tokens))\n elif token == commands.HREF:\n attributes = {\"href\": next(tokens)}\n children = tuple(_walk(tokens, terminator=terminator, limit=1))\n node = Node(token=token, children=children, attributes=attributes)\n elif token in (\n commands.ABOVE,\n commands.ATOP,\n commands.ABOVEWITHDELIMS,\n commands.ATOPWITHDELIMS,\n commands.BRACE,\n commands.BRACK,\n commands.CHOOSE,\n commands.OVER,\n ):\n attributes = None\n delimiter = None\n\n if token == commands.ABOVEWITHDELIMS:\n delimiter = next(tokens).lstrip(\"\\\\\") + next(tokens).lstrip(\"\\\\\")\n elif token == commands.ATOPWITHDELIMS:\n attributes = {\"linethickness\": \"0\"}\n delimiter = next(tokens).lstrip(\"\\\\\") + next(tokens).lstrip(\"\\\\\")\n elif token == commands.BRACE:\n delimiter = \"{}\"\n elif token == commands.BRACK:\n delimiter = \"[]\"\n elif token == commands.CHOOSE:\n delimiter = \"()\"\n\n if token in (commands.ABOVE, commands.ABOVEWITHDELIMS):\n dimension_node = tuple(_walk(tokens, terminator=terminator, limit=1))[0]\n dimension = _get_dimension(dimension_node)\n attributes = {\"linethickness\": dimension}\n elif token in (commands.ATOP, commands.BRACE, commands.BRACK, commands.CHOOSE):\n attributes = {\"linethickness\": \"0\"}\n\n denominator = tuple(_walk(tokens, terminator=terminator))\n\n sibling = None\n if len(denominator) and denominator[-1].token == terminator:\n denominator, sibling = denominator[:-1], denominator[-1]\n\n if len(denominator) == 0:\n if token in (commands.BRACE, commands.BRACK):\n denominator = (Node(token=commands.BRACES, children=()),)\n else:\n raise DenominatorNotFoundError\n if len(group) == 0:\n if token in (commands.BRACE, commands.BRACK):\n group = [Node(token=commands.BRACES, children=())]\n else:\n raise NumeratorNotFoundError\n if len(denominator) > 1:\n denominator = (Node(token=commands.BRACES, children=denominator),)\n\n if len(group) == 1:\n children = (*group, *denominator)\n else:\n children = (Node(token=commands.BRACES, children=tuple(group)), *denominator)\n group = [Node(token=commands.FRAC, children=children, attributes=attributes, delimiter=delimiter)]\n if sibling is not None:\n group.append(sibling)\n break\n elif token == commands.SQRT:\n root_nodes = None\n next_node = tuple(_walk(tokens, limit=1))[0]\n if next_node.token == commands.OPENING_BRACKET:\n root_nodes = tuple(_walk(tokens, terminator=commands.CLOSING_BRACKET))[:-1]\n next_node = tuple(_walk(tokens, limit=1))[0]\n if len(root_nodes) > 1:\n root_nodes = (Node(token=commands.BRACES, children=root_nodes),)\n\n if root_nodes:\n node = Node(token=commands.ROOT, children=(next_node, *root_nodes))\n else:\n node = Node(token=token, children=(next_node,))\n elif token == commands.ROOT:\n root_nodes = tuple(_walk(tokens, terminator=r\"\\of\"))[:-1]\n next_node = tuple(_walk(tokens, limit=1))[0]\n if len(root_nodes) > 1:\n root_nodes = (Node(token=commands.BRACES, children=root_nodes),)\n if root_nodes:\n node = Node(token=token, children=(next_node, *root_nodes))\n else:\n node = Node(token=token, children=(next_node, Node(token=commands.BRACES, children=())))\n elif token in commands.MATRICES:\n children = tuple(_walk(tokens, terminator=terminator))\n sibling = None\n if len(children) and children[-1].token == terminator:\n children, sibling = children[:-1], children[-1]\n if len(children) == 1 and children[0].token == commands.BRACES and children[0].children:\n children = children[0].children\n if sibling is not None:\n group.extend([Node(token=token, children=children, alignment=\"\"), sibling])\n break\n else:\n node = Node(token=token, children=children, alignment=\"\")\n elif token == commands.GENFRAC:\n delimiter = next(tokens).lstrip(\"\\\\\") + next(tokens).lstrip(\"\\\\\")\n dimension_node, style_node = tuple(_walk(tokens, terminator=terminator, limit=2))\n dimension = _get_dimension(dimension_node)\n style = _get_style(style_node)\n attributes = {\"linethickness\": dimension}\n children = tuple(_walk(tokens, terminator=terminator, limit=2))\n group.extend(\n [Node(token=style), Node(token=token, children=children, delimiter=delimiter, attributes=attributes)]\n )\n break\n elif token == commands.SIDESET:\n left, right, operator = tuple(_walk(tokens, terminator=terminator, limit=3))\n left_token, left_children = _make_subsup(left)\n right_token, right_children = _make_subsup(right)\n attributes = {\"movablelimits\": \"false\"}\n node = Node(\n token=token,\n children=(\n Node(\n token=left_token,\n children=(\n Node(\n token=commands.VPHANTOM,\n children=(\n Node(token=operator.token, children=operator.children, attributes=attributes),\n ),\n ),\n *left_children,\n ),\n ),\n Node(\n token=right_token,\n children=(\n Node(token=operator.token, children=operator.children, attributes=attributes),\n *right_children,\n ),\n ),\n ),\n )\n elif token == commands.SKEW:\n width_node, child = tuple(_walk(tokens, terminator=terminator, limit=2))\n width = width_node.token\n if width == commands.BRACES:\n if width_node.children is None or len(width_node.children) == 0:\n raise InvalidWidthError\n width = width_node.children[0].token\n if not width.isdigit():\n raise InvalidWidthError\n node = Node(token=token, children=(child,), attributes={\"width\": f\"{0.0555 * int(width):.3f}em\"})\n elif token.startswith(commands.BEGIN):\n node = _get_environment_node(token, tokens)\n else:\n node = Node(token=token)\n\n group.append(node)\n\n if limit and len(group) >= limit:\n break\n if not has_available_tokens:\n raise NoAvailableTokensError\n return group\n\n\ndef _make_subsup(node: Node) -> Tuple[str, Tuple[Node, ...]]:\n # TODO: raise error instead of assertion\n assert node.token == commands.BRACES\n try:\n assert (\n node.children is not None\n and 2 <= len(node.children[0].children) <= 3\n and node.children[0].token\n in (\n commands.SUBSUP,\n commands.SUBSCRIPT,\n commands.SUPERSCRIPT,\n )\n )\n token = node.children[0].token\n children = node.children[0].children[1:]\n return token, children\n except IndexError:\n return \"\", ()\n\n\ndef _get_dimension(node: Node) -> str:\n dimension = node.token\n if node.token == commands.BRACES and node.children is not None:\n dimension = node.children[0].token\n return dimension\n\n\ndef _get_style(node: Node) -> str:\n style = node.token\n if node.token == commands.BRACES and node.children is not None:\n style = node.children[0].token\n if style == \"0\":\n return commands.DISPLAYSTYLE\n if style == \"1\":\n return commands.TEXTSTYLE\n if style == \"2\":\n return commands.SCRIPTSTYLE\n if style == \"3\":\n return commands.SCRIPTSCRIPTSTYLE\n raise InvalidStyleForGenfracError\n\n\ndef _get_environment_node(token: str, tokens: Iterator[str]) -> Node:\n # TODO: support non-matrix environments\n start_index = token.index(\"{\") + 1\n environment = token[start_index:-1]\n terminator = rf\"{commands.END}{{{environment}}}\"\n children = tuple(_walk(tokens, terminator=terminator))\n if len(children) and children[-1].token != terminator:\n raise MissingEndError\n children = children[:-1]\n alignment = \"\"\n\n if len(children) and children[0].token == commands.OPENING_BRACKET:\n children_iter = iter(children)\n next(children_iter) # remove BRACKET\n for c in children_iter:\n if c.token == commands.CLOSING_BRACKET:\n break\n elif c.token not in \"lcr|\":\n raise InvalidAlignmentError\n alignment += c.token\n children = tuple(children_iter)\n elif (\n len(children)\n and children[0].children is not None\n and (\n children[0].token == commands.BRACES\n or (environment.endswith(\"*\") and children[0].token == commands.BRACKETS)\n )\n and all(c.token in \"lcr|\" for c in children[0].children)\n ):\n alignment = \"\".join(c.token for c in children[0].children)\n children = children[1:]\n\n return Node(token=rf\"\\{environment}\", children=children, alignment=alignment)\n","repo_name":"roniemartinez/latex2mathml","sub_path":"latex2mathml/walker.py","file_name":"walker.py","file_ext":"py","file_size_in_byte":19969,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"52"} +{"seq_id":"43266865214","text":"from typing import TYPE_CHECKING\n\nimport PyQt5.QtGui as QtGui\nimport PyQt5.QtWidgets as QtWidgets\nimport PyQt5.QtCore as QtCore\n\nfrom electrum_ltc.i18n import _\nfrom electrum_ltc.util import bh2u, format_time\nfrom electrum_ltc.lnutil import format_short_channel_id, LOCAL, REMOTE, UpdateAddHtlc, Direction\nfrom electrum_ltc.lnchannel import htlcsum\nfrom electrum_ltc.lnaddr import LnAddr, lndecode\nfrom electrum_ltc.bitcoin import COIN\n\nif TYPE_CHECKING:\n from .main_window import ElectrumWindow\n\nclass HTLCItem(QtGui.QStandardItem):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setEditable(False)\n\nclass SelectableLabel(QtWidgets.QLabel):\n def __init__(self, text=''):\n super().__init__(text)\n self.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)\n\nclass LinkedLabel(QtWidgets.QLabel):\n def __init__(self, text, on_clicked):\n super().__init__(text)\n self.linkActivated.connect(on_clicked)\n\nclass ChannelDetailsDialog(QtWidgets.QDialog):\n def make_htlc_item(self, i: UpdateAddHtlc, direction: Direction) -> HTLCItem:\n it = HTLCItem(_('Sent HTLC with ID {}' if Direction.SENT == direction else 'Received HTLC with ID {}').format(i.htlc_id))\n it.appendRow([HTLCItem(_('Amount')),HTLCItem(self.format(i.amount_msat))])\n it.appendRow([HTLCItem(_('CLTV expiry')),HTLCItem(str(i.cltv_expiry))])\n it.appendRow([HTLCItem(_('Payment hash')),HTLCItem(bh2u(i.payment_hash))])\n return it\n\n def append_lnaddr(self, it: HTLCItem, lnaddr: LnAddr):\n invoice = HTLCItem(_('Invoice'))\n invoice.appendRow([HTLCItem(_('Remote node public key')), HTLCItem(bh2u(lnaddr.pubkey.serialize()))])\n invoice.appendRow([HTLCItem(_('Amount in sat')), HTLCItem(str(lnaddr.amount * COIN))]) # might have a comma because mSAT!\n invoice.appendRow([HTLCItem(_('Description')), HTLCItem(dict(lnaddr.tags).get('d', _('N/A')))])\n invoice.appendRow([HTLCItem(_('Date')), HTLCItem(format_time(lnaddr.date))])\n it.appendRow([invoice])\n\n def make_inflight(self, lnaddr, i: UpdateAddHtlc, direction: Direction) -> HTLCItem:\n it = self.make_htlc_item(i, direction)\n self.append_lnaddr(it, lnaddr)\n return it\n\n def make_model(self, htlcs) -> QtGui.QStandardItemModel:\n model = QtGui.QStandardItemModel(0, 2)\n model.setHorizontalHeaderLabels(['HTLC', 'Property value'])\n parentItem = model.invisibleRootItem()\n folder_types = {'settled': _('Fulfilled HTLCs'), 'inflight': _('HTLCs in current commitment transaction')}\n self.folders = {}\n self.keyname_rows = {}\n\n for keyname, i in folder_types.items():\n myFont=QtGui.QFont()\n myFont.setBold(True)\n folder = HTLCItem(i)\n folder.setFont(myFont)\n parentItem.appendRow(folder)\n self.folders[keyname] = folder\n mapping = {}\n num = 0\n\n invoices = dict(self.window.wallet.lnworker.invoices)\n for pay_hash, item in htlcs.items():\n chan_id, i, direction, status = item\n lnaddr = None\n if pay_hash in invoices:\n invoice = invoices[pay_hash][0]\n lnaddr = lndecode(invoice)\n if status == 'inflight':\n if lnaddr is not None:\n it = self.make_inflight(lnaddr, i, direction)\n else:\n it = self.make_htlc_item(i, direction)\n elif status == 'settled':\n it = self.make_htlc_item(i, direction)\n # if we made the invoice and still have it, we can show more info\n if lnaddr is not None:\n self.append_lnaddr(it, lnaddr)\n self.folders[status].appendRow(it)\n mapping[i.payment_hash] = num\n num += 1\n self.keyname_rows[keyname] = mapping\n return model\n\n def move(self, fro: str, to: str, payment_hash: bytes):\n assert fro != to\n row_idx = self.keyname_rows[fro].pop(payment_hash)\n row = self.folders[fro].takeRow(row_idx)\n self.folders[to].appendRow(row)\n dest_mapping = self.keyname_rows[to]\n dest_mapping[payment_hash] = len(dest_mapping)\n\n ln_payment_completed = QtCore.pyqtSignal(str, float, Direction, UpdateAddHtlc, bytes, bytes)\n htlc_added = QtCore.pyqtSignal(str, UpdateAddHtlc, LnAddr, Direction)\n\n @QtCore.pyqtSlot(str, UpdateAddHtlc, LnAddr, Direction)\n def do_htlc_added(self, evtname, htlc, lnaddr, direction):\n mapping = self.keyname_rows['inflight']\n mapping[htlc.payment_hash] = len(mapping)\n self.folders['inflight'].appendRow(self.make_inflight(lnaddr, htlc, direction))\n\n @QtCore.pyqtSlot(str, float, Direction, UpdateAddHtlc, bytes, bytes)\n def do_ln_payment_completed(self, evtname, date, direction, htlc, preimage, chan_id):\n self.move('inflight', 'settled', htlc.payment_hash)\n self.update_sent_received()\n\n def update_sent_received(self):\n self.sent_label.setText(str(self.chan.total_msat(Direction.SENT)))\n self.received_label.setText(str(self.chan.total_msat(Direction.RECEIVED)))\n\n @QtCore.pyqtSlot(str)\n def show_tx(self, link_text: str):\n funding_tx = self.window.wallet.db.get_transaction(self.chan.funding_outpoint.txid)\n self.window.show_transaction(funding_tx, tx_desc=_('Funding Transaction'))\n\n def __init__(self, window: 'ElectrumWindow', chan_id: bytes):\n super().__init__(window)\n\n # initialize instance fields\n self.window = window\n chan = self.chan = window.wallet.lnworker.channels[chan_id]\n self.format = lambda msat: window.format_amount_and_units(msat / 1000)\n\n # connect signals with slots\n self.ln_payment_completed.connect(self.do_ln_payment_completed)\n self.htlc_added.connect(self.do_htlc_added)\n\n # register callbacks for updating\n window.network.register_callback(self.ln_payment_completed.emit, ['ln_payment_completed'])\n window.network.register_callback(self.htlc_added.emit, ['htlc_added'])\n\n # set attributes of QDialog\n self.setWindowTitle(_('Channel Details'))\n self.setMinimumSize(800, 400)\n\n # add layouts\n vbox = QtWidgets.QVBoxLayout(self)\n form_layout = QtWidgets.QFormLayout(None)\n vbox.addLayout(form_layout)\n\n # add form content\n form_layout.addRow(_('Node ID:'), SelectableLabel(bh2u(chan.node_id)))\n form_layout.addRow(_('Channel ID:'), SelectableLabel(bh2u(chan.channel_id)))\n funding_label_text = f'{chan.funding_outpoint.txid}:{chan.funding_outpoint.output_index}'\n form_layout.addRow(_('Funding Outpoint:'), LinkedLabel(funding_label_text, self.show_tx))\n form_layout.addRow(_('Short Channel ID:'), SelectableLabel(format_short_channel_id(chan.short_channel_id)))\n self.received_label = SelectableLabel()\n form_layout.addRow(_('Received (mSAT):'), self.received_label)\n self.sent_label = SelectableLabel()\n form_layout.addRow(_('Sent (mSAT):'), self.sent_label)\n self.htlc_minimum_msat = SelectableLabel(str(chan.config[REMOTE].htlc_minimum_msat))\n form_layout.addRow(_('Minimum HTLC value accepted by peer (mSAT):'), self.htlc_minimum_msat)\n self.max_htlcs = SelectableLabel(str(chan.config[REMOTE].max_accepted_htlcs))\n form_layout.addRow(_('Maximum number of concurrent HTLCs accepted by peer:'), self.max_htlcs)\n self.max_htlc_value = SelectableLabel(self.window.format_amount_and_units(chan.config[REMOTE].max_htlc_value_in_flight_msat / 1000))\n form_layout.addRow(_('Maximum value of in-flight HTLCs accepted by peer:'), self.max_htlc_value)\n self.dust_limit = SelectableLabel(self.window.format_amount_and_units(chan.config[REMOTE].dust_limit_sat))\n form_layout.addRow(_('Remote dust limit:'), self.dust_limit)\n self.reserve = SelectableLabel(self.window.format_amount_and_units(chan.config[REMOTE].reserve_sat))\n form_layout.addRow(_('Remote channel reserve:'), self.reserve)\n\n # add htlc tree view to vbox (wouldn't scale correctly in QFormLayout)\n form_layout.addRow(_('Payments (HTLCs):'), None)\n w = QtWidgets.QTreeView(self)\n htlc_dict = chan.get_payments()\n w.setModel(self.make_model(htlc_dict))\n w.header().setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)\n vbox.addWidget(w)\n\n # initialize sent/received fields\n self.update_sent_received()\n","repo_name":"Toporin/electrum-ltc-satochip","sub_path":"electrum_ltc/gui/qt/channel_details.py","file_name":"channel_details.py","file_ext":"py","file_size_in_byte":8641,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"33997848650","text":"__author__ = [\"Lovkush-A\", \"mloning\", \"LuisZugasti\", \"AyushmaanSeth\"]\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.dummy import DummyRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.pipeline import make_pipeline\n\nfrom sktime.datasets import load_airline\nfrom sktime.forecasting.base import ForecastingHorizon\nfrom sktime.forecasting.compose import (\n DirectTabularRegressionForecaster,\n DirectTimeSeriesRegressionForecaster,\n DirRecTabularRegressionForecaster,\n DirRecTimeSeriesRegressionForecaster,\n MultioutputTabularRegressionForecaster,\n MultioutputTimeSeriesRegressionForecaster,\n RecursiveTabularRegressionForecaster,\n RecursiveTimeSeriesRegressionForecaster,\n make_reduction,\n)\nfrom sktime.forecasting.compose._reduce import _sliding_window_transform\nfrom sktime.forecasting.tests._config import TEST_OOS_FHS, TEST_WINDOW_LENGTHS_INT\nfrom sktime.performance_metrics.forecasting import mean_absolute_percentage_error\nfrom sktime.regression.base import BaseRegressor\nfrom sktime.regression.interval_based import TimeSeriesForestRegressor\nfrom sktime.split import SlidingWindowSplitter, temporal_train_test_split\nfrom sktime.split.tests.test_split import _get_windows\nfrom sktime.transformations.panel.reduce import Tabularizer\nfrom sktime.utils._testing.forecasting import make_forecasting_problem\nfrom sktime.utils.validation.forecasting import check_fh\n\nN_TIMEPOINTS = [13, 17]\nN_VARIABLES = [1, 3]\nSTRATEGIES = [\"recursive\", \"direct\", \"multioutput\", \"dirrec\"]\nFH = ForecastingHorizon(1)\n\n\n@pytest.mark.parametrize(\"n_timepoints\", N_TIMEPOINTS)\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\n@pytest.mark.parametrize(\"fh\", TEST_OOS_FHS)\n@pytest.mark.parametrize(\"scitype\", [\"tabular-regressor\", \"time-series-regressor\"])\ndef test_sliding_window_transform_against_cv(n_timepoints, window_length, fh, scitype):\n \"\"\"Test sliding window transform against cv.\"\"\"\n fh = check_fh(fh)\n y = pd.Series(_make_y(0, n_timepoints))\n cv = SlidingWindowSplitter(fh=fh, window_length=window_length)\n xa, ya = _get_windows(cv, y)\n yb, xb = _sliding_window_transform(y, window_length, fh, scitype=scitype)\n np.testing.assert_array_equal(ya, yb)\n if scitype == \"time-series-regressor\":\n xb = xb.squeeze(axis=1)\n\n np.testing.assert_array_equal(xa, xb)\n\n\ndef _make_y_X(n_timepoints, n_variables):\n # We generate y and X values so that the y should always be greater\n # than its lagged values and the lagged and contemporaneous values of the\n # exogenous variables X\n assert n_variables < 10\n base = np.arange(n_timepoints)\n y = pd.Series(base + n_variables / 10)\n\n if n_variables > 1:\n X = np.column_stack([base + i / 10 for i in range(1, n_variables)])\n X = pd.DataFrame(X)\n else:\n X = None\n\n return y, X\n\n\n@pytest.mark.parametrize(\"n_timepoints\", N_TIMEPOINTS)\n@pytest.mark.parametrize(\"n_variables\", N_VARIABLES)\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\n@pytest.mark.parametrize(\"fh\", TEST_OOS_FHS)\ndef test_sliding_window_transform_tabular(n_timepoints, window_length, n_variables, fh):\n \"\"\"Test sliding window transform tabular.\"\"\"\n y, X = _make_y_X(n_timepoints=n_timepoints, n_variables=n_variables)\n fh = check_fh(fh, enforce_relative=True)\n fh_max = fh[-1]\n effective_window_length = window_length + fh_max - 1\n\n yt, Xt = _sliding_window_transform(\n y, window_length=window_length, fh=fh, X=X, scitype=\"tabular-regressor\"\n )\n assert yt.shape == (n_timepoints - effective_window_length, len(fh))\n\n # Check y values for first step in fh.\n actual = yt[:, 0]\n start = window_length + fh[0] - 1\n end = start + n_timepoints - window_length - fh_max + 1\n expected = y[np.arange(start, end)]\n np.testing.assert_array_equal(actual, expected)\n\n # The transformed Xt array contains lagged values for each variable, excluding the\n # n_variables + 1 contemporaneous values for the exogenous variables.\n # assert Xt.shape == (yt.shape[0], (window_length * n_variables) + n_variables - 1)\n assert Xt.shape == (yt.shape[0], window_length * n_variables)\n assert np.all(Xt < yt[:, [0]])\n\n\n@pytest.mark.parametrize(\"n_timepoints\", N_TIMEPOINTS)\n@pytest.mark.parametrize(\"n_variables\", N_VARIABLES)\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\n@pytest.mark.parametrize(\"fh\", TEST_OOS_FHS)\ndef test_sliding_window_transform_panel(n_timepoints, window_length, n_variables, fh):\n \"\"\"Test sliding window transform panel.\"\"\"\n y, X = _make_y_X(n_timepoints=n_timepoints, n_variables=n_variables)\n fh = check_fh(fh, enforce_relative=True)\n fh_max = fh[-1]\n effective_window_length = window_length + fh_max - 1\n\n yt, Xt = _sliding_window_transform(\n y, window_length=window_length, X=X, fh=fh, scitype=\"time-series-regressor\"\n )\n assert yt.shape == (n_timepoints - effective_window_length, len(fh))\n\n # Check y values.\n actual = yt[:, 0]\n start = window_length + fh[0] - 1\n end = start + n_timepoints - window_length - fh_max + 1\n expected = y[np.arange(start, end)]\n np.testing.assert_array_equal(actual, expected)\n\n # Given the input data, all of the value in the transformed Xt array should be\n # smaller than the transformed yt target array.\n assert Xt.shape == (yt.shape[0], n_variables, window_length)\n assert np.all(Xt < yt[:, np.newaxis, [0]])\n\n\ndef test_sliding_window_transform_explicit():\n \"\"\"Test sliding window transform explicit.\n\n testing with explicitly written down expected outputs intended to help future\n contributors understand the transformation\n \"\"\"\n y = pd.Series(np.arange(9))\n X = pd.concat([y + 100, y + 200], axis=1)\n fh = ForecastingHorizon([1, 3], is_relative=True)\n window_length = 2\n\n yt_actual, Xt_tabular_actual = _sliding_window_transform(y, window_length, fh, X)\n _, Xt_time_series_actual = _sliding_window_transform(\n y, window_length, fh, X, scitype=\"time-series-regressor\"\n )\n\n yt_expected = np.array([[2.0, 4.0], [3.0, 5.0], [4.0, 6.0], [5.0, 7.0], [6.0, 8.0]])\n\n Xt_tabular_expected = np.array(\n [\n [0.0, 1.0, 100.0, 101.0, 200.0, 201.0],\n [1.0, 2.0, 101.0, 102.0, 201.0, 202.0],\n [2.0, 3.0, 102.0, 103.0, 202.0, 203.0],\n [3.0, 4.0, 103.0, 104.0, 203.0, 204.0],\n [4.0, 5.0, 104.0, 105.0, 204.0, 205.0],\n ]\n )\n\n Xt_time_series_expected = np.array(\n [\n [[0.0, 1.0], [100.0, 101.0], [200.0, 201.0]],\n [[1.0, 2.0], [101.0, 102.0], [201.0, 202.0]],\n [[2.0, 3.0], [102.0, 103.0], [202.0, 203.0]],\n [[3.0, 4.0], [103.0, 104.0], [203.0, 204.0]],\n [[4.0, 5.0], [104.0, 105.0], [204.0, 205.0]],\n ]\n )\n\n np.testing.assert_array_equal(yt_actual, yt_expected)\n np.testing.assert_array_equal(Xt_tabular_actual, Xt_tabular_expected)\n np.testing.assert_array_equal(Xt_time_series_actual, Xt_time_series_expected)\n\n\ndef _make_y(start, end, method=\"linear-trend\", slope=1):\n # generate test data\n if method == \"linear-trend\":\n y = np.arange(start, end) * slope\n else:\n raise ValueError(\"`method` not understood\")\n return y\n\n\n@pytest.mark.parametrize(\"fh\", TEST_OOS_FHS)\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\n@pytest.mark.parametrize(\"strategy\", STRATEGIES)\n@pytest.mark.parametrize(\n \"regressor, scitype\",\n [\n (LinearRegression(), \"tabular-regressor\"),\n (make_pipeline(Tabularizer(), LinearRegression()), \"time-series-regressor\"),\n ],\n)\n@pytest.mark.parametrize(\n \"method, slope\",\n [\n (\"linear-trend\", 1),\n (\"linear-trend\", -3),\n (\"linear-trend\", 0), # constant\n ],\n)\ndef test_linear_extrapolation_endogenous_only(\n fh, window_length, strategy, method, slope, regressor, scitype\n):\n \"\"\"Test linear extrapolation endogenous only.\"\"\"\n n_timepoints = 13\n y = _make_y(0, n_timepoints, method=method, slope=slope)\n y = pd.Series(y)\n fh = check_fh(fh)\n\n forecaster = make_reduction(\n regressor, scitype=scitype, window_length=window_length, strategy=strategy\n )\n forecaster.fit(y, fh=fh)\n actual = forecaster.predict()\n\n end = n_timepoints + max(fh) + 1\n expected = _make_y(n_timepoints, end, method=method, slope=slope)[fh.to_indexer()]\n np.testing.assert_almost_equal(actual, expected)\n\n\n@pytest.mark.parametrize(\"fh\", [1, 3, 5])\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\n@pytest.mark.parametrize(\"strategy\", STRATEGIES)\n@pytest.mark.parametrize(\"scitype\", [\"time-series-regressor\", \"tabular-regressor\"])\ndef test_dummy_regressor_mean_prediction_endogenous_only(\n fh, window_length, strategy, scitype\n):\n \"\"\"Test dummy regressor mean prediction endogenous_only.\n\n The DummyRegressor ignores the input feature data X, hence we can use it for testing\n reduction from forecasting to both tabular and time series regression. The\n DummyRegressor also supports the 'multioutput' strategy.\n \"\"\"\n y = make_forecasting_problem()\n fh = check_fh(fh)\n y_train, y_test = temporal_train_test_split(y, fh=fh)\n\n regressor = DummyRegressor(strategy=\"mean\")\n forecaster = make_reduction(\n regressor, scitype=scitype, window_length=window_length, strategy=strategy\n )\n forecaster.fit(y_train, fh=fh)\n actual = forecaster.predict()\n\n if strategy == \"recursive\":\n # For the recursive strategy, we always use the first-step ahead as the\n # target vector in the regression problem during training, regardless of the\n # actual forecasting horizon.\n effective_window_length = window_length\n else:\n # For the other strategies, we split the data taking into account the steps\n # ahead we want to predict.\n effective_window_length = window_length + max(fh) - 1\n\n # In the sliding-window transformation, the first values of the target series\n # make up the first window and are not used in the transformed target vector. So\n # the expected result should be the mean of the remaining values.\n expected = np.mean(y_train[effective_window_length:])\n np.testing.assert_array_almost_equal(actual, expected)\n\n\n_REGISTRY = [\n (\"tabular-regressor\", \"direct\", DirectTabularRegressionForecaster),\n (\"tabular-regressor\", \"recursive\", RecursiveTabularRegressionForecaster),\n (\"tabular-regressor\", \"multioutput\", MultioutputTabularRegressionForecaster),\n (\"tabular-regressor\", \"dirrec\", DirRecTabularRegressionForecaster),\n (\"time-series-regressor\", \"direct\", DirectTimeSeriesRegressionForecaster),\n (\"time-series-regressor\", \"recursive\", RecursiveTimeSeriesRegressionForecaster),\n (\"time-series-regressor\", \"multioutput\", MultioutputTimeSeriesRegressionForecaster),\n (\"time-series-regressor\", \"dirrec\", DirRecTimeSeriesRegressionForecaster),\n]\n\n\nclass _Recorder:\n # Helper class to record given data for later inspection.\n def fit(self, X, y):\n self.X_fit = X\n self.y_fit = y\n return self\n\n def predict(self, X):\n self.X_pred = X\n return np.ones(1)\n\n\nclass _TestTabularRegressor(BaseEstimator, RegressorMixin, _Recorder):\n pass\n\n\nclass _TestTimeSeriesRegressor(_Recorder, BaseRegressor):\n pass\n\n def _fit(self, X, y):\n \"\"\"Empty method to satisfy abstract parent.\n\n Needs refactoring.\n \"\"\"\n\n def _predict(self, X):\n \"\"\"Empty method to satisfy abstract parent.\n\n Needs refactoring.\n \"\"\"\n\n\n@pytest.mark.parametrize(\n \"estimator\", [_TestTabularRegressor(), _TestTimeSeriesRegressor()]\n)\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\n@pytest.mark.parametrize(\"strategy\", [\"recursive\", \"direct\", \"multioutput\"])\ndef test_consistent_data_passing_to_component_estimators_in_fit_and_predict(\n estimator, window_length, strategy\n):\n \"\"\"Test consistent data passing to component estimators in fit and predict.\n\n We generate data that represents time points in its values, i.e. an array of values\n that increase in unit steps for each time point.\n \"\"\"\n n_variables = 3\n n_timepoints = 10\n y, X = _make_y_X(n_timepoints, n_variables)\n y_train, y_test, X_train, X_test = temporal_train_test_split(y, X, fh=FH)\n\n forecaster = make_reduction(\n estimator, strategy=strategy, window_length=window_length\n )\n forecaster.fit(y_train, X_train, fh=FH)\n forecaster.predict(X=X_test)\n\n # Get recorded data.\n if strategy == \"direct\":\n estimator_ = forecaster.estimators_[0]\n else:\n estimator_ = forecaster.estimator_\n\n X_fit = estimator_.X_fit\n y_fit = estimator_.y_fit\n X_pred = estimator_.X_pred\n\n # Format feature data into 3d array if the data is not in that format already.\n X_fit = X_fit.reshape(X_fit.shape[0], n_variables, -1)\n X_pred = X_pred.reshape(X_pred.shape[0], n_variables, -1)\n\n # Format target data into 2d array.\n y_fit = y_fit.reshape(y_fit.shape[0], -1)\n\n # Check that both fit and predict data have unit steps between them.\n assert np.allclose(np.diff(X_fit), 1)\n assert np.allclose(np.diff(X_pred), 1)\n\n # Check that predict data is a step ahead from last row in fit data.\n np.testing.assert_array_equal(X_pred, X_fit[[-1]] + 1)\n\n # Check that y values are further ahead than X values.\n assert np.all(X_fit < y_fit[:, np.newaxis, :])\n\n\n@pytest.mark.parametrize(\"scitype, strategy, klass\", _REGISTRY)\n@pytest.mark.parametrize(\"window_length\", TEST_WINDOW_LENGTHS_INT)\ndef test_make_reduction_construct_instance(scitype, strategy, klass, window_length):\n \"\"\"Test make_reduction.\"\"\"\n estimator = DummyRegressor()\n forecaster = make_reduction(\n estimator, window_length=window_length, scitype=scitype, strategy=strategy\n )\n assert isinstance(forecaster, klass)\n assert forecaster.get_params()[\"window_length\"] == window_length\n\n\n@pytest.mark.parametrize(\n \"estimator, scitype\",\n [\n (LinearRegression(), \"tabular-regressor\"),\n (TimeSeriesForestRegressor(), \"time-series-regressor\"),\n ],\n)\ndef test_make_reduction_infer_scitype(estimator, scitype):\n \"\"\"Test make_reduction.\"\"\"\n forecaster = make_reduction(estimator, scitype=\"infer\")\n assert forecaster._estimator_scitype == scitype\n\n\ndef test_make_reduction_infer_scitype_for_sklearn_pipeline():\n \"\"\"Test make_reduction.\n\n The scitype of pipeline cannot be inferred here, as it may be used together with a\n tabular or time series regressor.\n \"\"\"\n estimator = make_pipeline(Tabularizer(), LinearRegression())\n forecaster = make_reduction(estimator, scitype=\"infer\")\n assert forecaster._estimator_scitype == \"tabular-regressor\"\n\n\n@pytest.mark.parametrize(\"fh\", TEST_OOS_FHS)\ndef test_multioutput_direct_equivalence_tabular_linear_regression(fh):\n \"\"\"Test multioutput and direct strategies with linear regression.\n\n Regressor should produce same predictions\n \"\"\"\n y, X = make_forecasting_problem(make_X=True)\n y_train, y_test, X_train, X_test = temporal_train_test_split(y, X, fh=fh)\n\n estimator = LinearRegression()\n direct = make_reduction(estimator, strategy=\"direct\")\n multioutput = make_reduction(estimator, strategy=\"multioutput\")\n\n y_pred_direct = direct.fit(y_train, X_train, fh=fh).predict(fh, X_test)\n y_pred_multioutput = multioutput.fit(y_train, X_train, fh=fh).predict(fh, X_test)\n\n np.testing.assert_array_almost_equal(\n y_pred_direct.to_numpy(), y_pred_multioutput.to_numpy()\n )\n\n\n# this expected value created by Lovkush Agarwal by running code locally in Mar 2021\nEXPECTED_AIRLINE_LINEAR_RECURSIVE = [\n 397.28122475088117,\n 391.0055770755232,\n 382.85931770491493,\n 376.75382498759643,\n 421.3439733242519,\n 483.7127665080476,\n 506.5011555360703,\n 485.95155173523494,\n 414.41328025499604,\n 371.2843322707713,\n 379.5680077722808,\n 406.146827316167,\n 426.48249271837176,\n 415.5337957767289,\n 405.48715913377714,\n 423.97150765765025,\n 472.10998764155966,\n 517.7763038626333,\n 515.6077989417864,\n 475.8615207069196,\n 432.47049089698646,\n 417.62468250043514,\n 435.3174101071012,\n 453.8693707695759,\n]\n\n# this expected value created by Lovkush Agarwal by running code locally in Mar 2021\nEXPECTED_AIRLINE_LINEAR_DIRECT = [\n 388.7894742436609,\n 385.4311737990922,\n 404.66760376792183,\n 389.3921653574014,\n 413.5415037170552,\n 491.27471550855756,\n 560.5985060880608,\n 564.1354313250545,\n 462.8049467298484,\n 396.8247623180332,\n 352.5416937680942,\n 369.3915756974357,\n 430.12889943026323,\n 417.13419789042484,\n 434.8091175980315,\n 415.33997516059355,\n 446.97711875155846,\n 539.6761098618977,\n 619.7204673400846,\n 624.3153932803112,\n 499.686252475341,\n 422.0658526180952,\n 373.3847171492921,\n 388.8020135264563,\n]\n\n\n@pytest.mark.parametrize(\n \"forecaster, expected\",\n [\n (\n DirectTabularRegressionForecaster(LinearRegression()),\n EXPECTED_AIRLINE_LINEAR_DIRECT,\n ),\n # multioutput should behave the same as direct with linear regression estimator\n # hence the reason for the same expected predictions\n (\n MultioutputTabularRegressionForecaster(LinearRegression()),\n EXPECTED_AIRLINE_LINEAR_DIRECT,\n ),\n (\n RecursiveTabularRegressionForecaster(LinearRegression()),\n EXPECTED_AIRLINE_LINEAR_RECURSIVE,\n ),\n (\n RecursiveTabularRegressionForecaster(LinearRegression(), pooling=\"global\"),\n EXPECTED_AIRLINE_LINEAR_RECURSIVE,\n ),\n (\n DirectTimeSeriesRegressionForecaster(\n make_pipeline(Tabularizer(), LinearRegression())\n ),\n EXPECTED_AIRLINE_LINEAR_DIRECT,\n ),\n # multioutput should behave the same as direct with linear regression estimator\n # hence the reason for the same expected predictions\n (\n MultioutputTimeSeriesRegressionForecaster(\n make_pipeline(Tabularizer(), LinearRegression())\n ),\n EXPECTED_AIRLINE_LINEAR_DIRECT,\n ),\n (\n RecursiveTimeSeriesRegressionForecaster(\n make_pipeline(Tabularizer(), LinearRegression())\n ),\n EXPECTED_AIRLINE_LINEAR_RECURSIVE,\n ),\n ],\n)\ndef test_reductions_airline_data(forecaster, expected):\n \"\"\"Test reduction forecasters.\n\n Test reduction forecasters by making prediction on airline dataset using linear\n estimators. Predictions compared with values calculated by Lovkush Agarwal on their\n local machine in Mar 2021\n \"\"\"\n y = load_airline()\n y_train, y_test = temporal_train_test_split(y, test_size=24)\n fh = ForecastingHorizon(y_test.index, is_relative=False)\n\n actual = forecaster.fit(y_train, fh=fh).predict(fh)\n\n np.testing.assert_almost_equal(actual, expected)\n\n\ndef test_dirrec_against_recursive_accumulated_error():\n \"\"\"Test recursive and dirrec regressor strategies.\n\n dirrec regressor should produce lower error due to less cumulative error\n \"\"\"\n y = load_airline()\n y_train, y_test = temporal_train_test_split(y, test_size=24)\n fh = ForecastingHorizon(y_test.index, is_relative=False)\n\n estimator = LinearRegression()\n recursive = make_reduction(\n estimator, scitype=\"tabular-regressor\", strategy=\"recursive\"\n )\n dirrec = make_reduction(estimator, scitype=\"tabular-regressor\", strategy=\"dirrec\")\n\n preds_recursive = recursive.fit(y_train, fh=fh).predict(fh)\n preds_dirrec = dirrec.fit(y_train, fh=fh).predict(fh)\n\n assert mean_absolute_percentage_error(\n y_test, preds_dirrec\n ) < mean_absolute_percentage_error(y_test, preds_recursive)\n\n\ndef test_direct_vs_recursive():\n \"\"\"Test reduction forecasters.\n\n Test reduction forecasters by making prediction on airline dataset using linear\n estimators. Wenn windows_identical = False, all observations should be considered\n (see documentation in make_reduction function), so results for direct and recursive\n forecasting should match for the first forecasting horizon. With the\n windows_identical\n \"\"\"\n y = load_airline()\n y_train, y_test = temporal_train_test_split(y, test_size=24)\n fh = ForecastingHorizon(y_test.index, is_relative=False)\n forecaster_dir_max = DirectTabularRegressionForecaster(\n LinearRegression(), windows_identical=False\n )\n forecaster_dir_spec = DirectTabularRegressionForecaster(\n LinearRegression(), windows_identical=True\n )\n forecaster_rec_max = RecursiveTabularRegressionForecaster(LinearRegression())\n forecaster_rec_spec = RecursiveTabularRegressionForecaster(LinearRegression())\n\n pred_dir_max = forecaster_dir_max.fit(y_train, fh=fh).predict(fh)\n pred_dir_spec = forecaster_dir_spec.fit(y_train, fh=fh).predict(fh)\n pred_rec_max = forecaster_rec_max.fit(y_train, fh=fh).predict(fh)\n pred_rec_spec = forecaster_rec_spec.fit(y_train, fh=fh).predict(fh)\n\n assert pred_dir_max.head(1).equals(pred_rec_max.head(1))\n assert pred_dir_max.head(1).equals(pred_rec_spec.head(1))\n assert not pred_dir_max.head(1).equals(pred_dir_spec.head(1))\n","repo_name":"sktime/sktime","sub_path":"sktime/forecasting/compose/tests/test_reduce.py","file_name":"test_reduce.py","file_ext":"py","file_size_in_byte":21415,"program_lang":"python","lang":"en","doc_type":"code","stars":7028,"dataset":"github-code","pt":"52"} +{"seq_id":"41773110903","text":"age=int(input(\"Age: \"))\r\nbirthPlace=str(input(\"Born in the U.S.? (Yes/No): \"))\r\nresidency=int(input(\"Years of Residency: \"))\r\n\r\nif age>=35 and birthPlace==\"Yes\" and residency>=14:\r\n print(\"You are eligible to run for president!\")\r\n\r\nelse:\r\n print(\"You are not eligible to run for president.\")\r\n if age<35:\r\n print(\"You are too young to run for president. You must be at least 35 years old.\")\r\n if birthPlace!=\"Yes\":\r\n print(\"You are not born in th U.S. You must be born in the U.S. to run for president.\")\r\n if residency<14:\r\n print(\"You have not been a resident for long enough. You must be a a resident of the U.S. for 14 years.\")","repo_name":"Kev-in123/ICS2O7","sub_path":"CodeHS/Conditionals/PresidentialEligibility-Extended.py","file_name":"PresidentialEligibility-Extended.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":"30225771941","text":"import numpy as np\n\nfrom abc import ABC, abstractmethod\n\nfrom .smc.initializer import Initializer\nfrom .smc.mutator import Mutator\nfrom .utils.storage import InMemoryStorage\nfrom .utils.mpi_utils import rank_zero_run_only\nfrom .utils.context_manager import ContextManager\n\n\nclass SamplerBase:\n\n def __init__(self, mcmc_kernel):\n self._mcmc_kernel = mcmc_kernel\n self._initializer = Initializer(self._mcmc_kernel)\n self._mutator = Mutator(self._mcmc_kernel)\n self._updater = None\n self._mutation_ratio = 1\n self._step_list = []\n self._phi_sequence = []\n\n try:\n self._result = ContextManager.get_context()\n except:\n self._result = InMemoryStorage()\n\n @property\n def phi_sequence(self):\n return np.array(self._phi_sequence)\n\n @property\n def step(self):\n return self._step\n\n @step.setter\n def step(self, step):\n if step is not None:\n self._save_step(step)\n self._step = step\n\n @abstractmethod\n def sample(self):\n '''\n Performs SMC sampling. Returns step list and estimates of marginal\n log likelihood at each step.\n '''\n raise NotImplementedError\n\n def _initialize(self, num_particles, proposal):\n if self._result and self._result.is_restart:\n self._step = self._result[-1]\n self._phi_sequence = self._result.phi_sequence\n return None\n elif proposal:\n return self._initializer.init_particles_from_samples(*proposal)\n return self._initializer.init_particles_from_prior(num_particles)\n\n def _do_smc_step(self, phi, delta_phi, num_mcmc_samples):\n particles = self._updater.update(self.step, delta_phi)\n mut_particles = self._mutator.mutate(particles, phi, num_mcmc_samples)\n self._compute_mutation_ratio(particles, mut_particles)\n self.step = mut_particles\n\n def _compute_mutation_ratio(self, old_particles, new_particles):\n mutated = ~np.all(new_particles.params == old_particles.params, axis=1)\n self._mutation_ratio = sum(mutated) / new_particles.params.shape[0]\n\n @rank_zero_run_only\n def _save_step(self, step):\n self._result.save_step(step)\n","repo_name":"nasa/SMCPy","sub_path":"smcpy/sampler_base.py","file_name":"sampler_base.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":78,"dataset":"github-code","pt":"52"} +{"seq_id":"34683970900","text":"# import\nimport discord\nimport time\nimport datetime\nimport platform\nimport sqlite3\n\t\t\n# set size of string by adding spaces\ndef set_string_size(string, len1):\n\tlen0 = len(string)\n\tif (len0 > len1):\n\t\treturn string\n\tfor a in range(len0, len1):\n\t\tstring = string + \" \"\n\treturn string\n\n# info cmds\nasync def cmds_info(message, umsg, startup, owners, client, conn, cur):\n\t\n\t# args/variables\n\targs = umsg.split(' ')\n\tchannel = message.channel\n\tmember = message.author\n\tbot_version = '0.1.0'\n\t\n\t# help\n\tif (args[0].lower() == 'help'):\n\t\t\n\t\t# contextual help\n\t\tif (len(args) > 1):\n\t\t\tif (args[1].lower() == 'help'):\n\t\t\t\tembed = discord.Embed(title='Help Command', type='rich', description='**Usage:**\\n`!help` - Shows the command list')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'about'):\n\t\t\t\tembed = discord.Embed(title='About Command', type='rich', description='**Usage:**\\n`!about` - Shows info about the bot')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'info'):\n\t\t\t\tembed = discord.Embed(title='Info Command', type='rich', description='**Usage:**\\n`!info` - Shows technical & bot information')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'get'):\n\t\t\t\tembed = discord.Embed(title='Get Command', type='rich', description='**Usage:**\\n`!get [level name/id]` - Retrieves the download link for a level with the given name or id')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'browse'):\n\t\t\t\tembed = discord.Embed(title='Browse Command', type='rich', description='**Usage:**\\n`!browse` - Lists all levels in default order (oldest-newest)\\n`!browse ` - Lists all levels in a given order\\n**Sort Types**\\n`oldest` - Sorts oldest-newest\\n`newest` - Sorts newest-oldest\\n`rating high` - Sorts highest-lowest rating\\n`rating low` - Sorts lowest-highest rating')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'rate'):\n\t\t\t\tembed = discord.Embed(title='Rate Command', type='rich', description='**Usage:**\\n`!rate [+/-] [level name/id]` - Rate a level with a given name or id')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'upload'):\n\t\t\t\tembed = discord.Embed(title='Upload Command', type='rich', description='**Usage:**\\n`!upload [level name]` - Upload a level and give it a specified name (must attach a .butt file)')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'delete'):\n\t\t\t\tembed = discord.Embed(title='Delete Command', type='rich', description='**Usage:**\\n`!delete [level name/id]` - Delete a level with a given name or id (provided you are a mod or the level owner)')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'changelog'):\n\t\t\t\tembed = discord.Embed(title='Changelog Command', type='rich', description='**Usage:**\\n`!changelog` - Displays the ESJBot changelog)')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telif (args[1].lower() == 'todo'):\n\t\t\t\tembed = discord.Embed(title='To-Do Command', type='rich', description='**Usage:**\\n`!todo` - Displays the current ESJBot to-do list)')\n\t\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\t\telse:\n\t\t\t\tawait client.send_message(channel, 'That command does not exist!')\n\t\t\n\t\t# command list\n\t\telse:\n\t\t\tembed = discord.Embed(title='ESJBot Help', type='rich', description='Use `!help ` for usage')\n\t\t\tembed.add_field(name='Command List:',value='`help` `get` `browse` `upload` `rate` `delete` `about` `info` `changelog` `todo`',inline=False)\n\t\t\tawait client.send_message(channel, content=None, embed=embed)\n\t\n\t# about\n\tif (args[0].lower() == 'about'):\n\t\tcur.execute('SELECT Count(*) FROM levels')\n\t\tt = cur.fetchone()\n\t\tlevel_count = list(t)\n\t\tembed = discord.Embed(title='About ESJBot', type='rich', description='Simple ESJ level browser, based on the original bot by Chratis\\n\\nCreated by Yuvira\\n\\n**Version:** ' + bot_version + '\\n**Levels:** ' + str(level_count[0]) + '\\n\\n[GitHub Repo](https://github.com/Yuvira/ESJBot)')\n\t\tembed.set_thumbnail(url=client.user.avatar_url)\n\t\tawait client.send_message(channel, content=None, embed=embed)\n\n\t# info\n\tif (args[0].lower() == 'info'):\n\t\tbefore = time.monotonic()\n\t\tawait (await client.ws.ping())\n\t\tafter = time.monotonic()\n\t\tping = (after - before) * 1000\n\t\tcur.execute('SELECT Count(*) FROM levels')\n\t\tt = cur.fetchone()\n\t\tlevel_count = list(t)\n\t\tt = time.time() - startup\n\t\tuptime = str(int(t/86400)) + 'd '\n\t\tt = t % 86400\n\t\tuptime = uptime + str(int(t/3600)) + 'h '\n\t\tt = t % 3600\n\t\tuptime = uptime + str(int(t/60)) + 'm '\n\t\tt = t % 60\n\t\tuptime = uptime + str(int(t)) + 's'\n\t\tmsg = \"```============[ Technical Info ]============\\n\"\n\t\tmsg += \"::DiscordPY Version :: \" + set_string_size(str(discord.__version__), 17) + \"::\\n\"\n\t\tmsg += \"::Python Version :: \" + set_string_size(str(platform.python_version()), 17) + \"::\\n\"\n\t\tmsg += \"::Websocket Ping :: \" + set_string_size(\"{0:.0f}ms\".format(ping), 17) + \"::\\n\"\n\t\tmsg += \"===============[ Bot Info ]===============\\n\"\n\t\tmsg += \"::Bot Version :: \" + set_string_size(str(bot_version), 17) + \"::\\n\"\n\t\tmsg += \"::Levels :: \" + set_string_size(str(level_count[0]), 17) + \"::\\n\"\n\t\tmsg += \"::Uptime :: \" + set_string_size(uptime, 17) + \"::\\n\"\n\t\tmsg += \"==========================================```\"\n\t\tawait client.send_message(channel, msg)\n\t\t\n\t# changelog\n\tif (args[0].lower() == 'changelog'):\n\t\tf = open('changelog.txt', 'r')\n\t\tawait client.send_message(channel, f.read())\n\t\t\n\t# to-do list\n\tif (args[0].lower() == 'todo'):\n\t\tf = open('todo.txt', 'r')\n\t\tawait client.send_message(channel, f.read())\n","repo_name":"Yuvira/ESJBot","sub_path":"cmds_info.py","file_name":"cmds_info.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9369222867","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 13 19:20:45 2015\n\n@author: GeneralTsao\n\"\"\"\n\nimport pickle\n\na = pickle.load(open(\"banner.p\",'rb'))\n\nfor combo in a:\n print(\"\".join(symbol*num for symbol, num in combo))","repo_name":"miketsao/PythonChallenge","sub_path":"Challenge5.py","file_name":"Challenge5.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16578229190","text":"import os\nimport subprocess\n\nCLUSTAL_PATH = os.environ.get(\"CLUSTAL_PATH\")\n\n\ndef cmd(command):\n process = subprocess.Popen(\n command,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True\n )\n out, error = process.communicate()\n print(out, error)\n return out, error\n\n\ndef run_clustal(inputfile, outputfile):\n cmd_line = CLUSTAL_PATH + 'clustalo -i ' + inputfile + \\\n ' --guidetree-out=' + outputfile + ' --force'\n out, error = cmd(cmd_line)\n return out\n","repo_name":"Amrithasuresh/BPPRC_v1","sub_path":"clustalanalysis/run_clustal.py","file_name":"run_clustal.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"44529083068","text":"import os\nimport cv2\nimport PIL\nfrom io import BytesIO\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nfrom django.core.exceptions import ValidationError\n\n\nclass FileUploadHelper:\n \"\"\"\n Helper class to validate uploaded files\n How to use:\n FileUploadHelper(uploaded_file, type=\"image\", ratio=None, webp=False).validate()\n Parameters:\n uploaded_file: Uploaded file object\n type: File type, either \"image\" or \"video\"\n ratio: Image aspect ratio (width:height), e.g. \"16:9\"\n webp: Convert image to WebP format\n \"\"\"\n\n def __init__(self, uploaded_file, type=\"image\", ratio=None, webp=False):\n self.uploaded_file = uploaded_file\n self.max_file_size = 5 * 1024 * 1024\n self.max_video_duration = 35\n self.max_video_size = 30 * 1024 * 1024\n self.type = type\n self.ratio = ratio\n self.webp = webp\n\n def validate(self):\n if self.uploaded_file is None:\n return None\n\n if self.type == \"image\":\n return self.validate_image()\n elif self.type == \"video\":\n return self.validate_video()\n else:\n raise ValidationError(\"Invalid file type\")\n\n def validate_image(self):\n # Check content type\n content_type = self.get_content_type()\n\n # Check file size\n if content_type in [\"image/jpeg\", \"image/png\"]:\n if self.get_file_size() > self.max_file_size:\n raise ValidationError(\n \"File size exceeds the maximum allowed size of 5 MB\"\n )\n\n if self.ratio:\n ratio = self.get_ratio()\n file_ratio = self.get_file_ratio()\n width, height = file_ratio\n\n if ratio != width / height:\n raise ValidationError(f\"Image aspect ratio must be {self.ratio}\")\n\n if width < 400 or height < 400:\n raise ValidationError(\"Image resolution must be at least 400x400\")\n\n if width > 2000 or height > 2000:\n raise ValidationError(\"Image resolution must be at most 2000x2000\")\n\n if self.webp:\n self.convert_to_webp()\n else:\n raise ValidationError(\"Unsupported file format\")\n\n return self.uploaded_file\n\n def validate_video(self):\n # Check content type\n content_type = self.get_content_type()\n\n if content_type in [\"video/mp4\", \"video/quicktime\"]:\n if self.get_file_size() > self.max_video_size:\n raise ValidationError(\n \"File size exceeds the maximum allowed size of 30 MB\"\n )\n\n try:\n # get the temporary path of the uploaded file\n video_path = self.get_file_path()\n\n # Analyze video file\n video_capture = cv2.VideoCapture(video_path)\n frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))\n fps = int(video_capture.get(cv2.CAP_PROP_FPS))\n video_duration = frame_count / fps\n\n # Release the video capture resource\n video_capture.release()\n\n except Exception as e:\n raise ValidationError(\"Error analyzing video file: \" + str(e))\n\n if video_duration > self.max_video_duration:\n raise ValidationError(\n \"Video duration exceeds the maximum allowed duration of 30 seconds\"\n )\n else:\n raise ValidationError(\"Unsupported video format\")\n\n return self.uploaded_file\n\n def get_content_type(self):\n return self.uploaded_file.content_type\n\n def get_file_size(self):\n return self.uploaded_file.size\n\n def get_file_name(self):\n return self.uploaded_file.name\n\n def get_file_path(self):\n if hasattr(self.uploaded_file, \"temporary_file_path\"):\n return self.uploaded_file.temporary_file_path()\n else:\n return self.uploaded_file.file\n\n def get_ratio(self):\n \"\"\"\n 1 inch = 96 pixels\n \"\"\"\n ratio = self.ratio.split(\":\")\n width_ratio = int(ratio[0]) * 96\n height_ratio = int(ratio[1]) * 96\n new_ratio = width_ratio / height_ratio\n return new_ratio\n\n def get_file_ratio(self):\n img = PIL.Image.open(self.get_file_path())\n return img.size\n\n def convert_to_webp(self):\n img = PIL.Image.open(self.get_file_path())\n img = img.convert(\"RGB\")\n\n # Save the image to a BytesIO object\n img_io = BytesIO()\n img.save(img_io, \"webp\", quality=85)\n img_io.seek(0)\n\n # Set the BytesIO object as the new file\n file_name = self.get_file_name() + \".webp\"\n self.uploaded_file = InMemoryUploadedFile(\n img_io,\n \"ImageField\",\n file_name,\n \"image/webp\",\n img_io.getbuffer().nbytes,\n None,\n )\n\n return self.uploaded_file\n","repo_name":"fokusuma/DjangoHelperCollection","sub_path":"file_upload/file_upload.py","file_name":"file_upload.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32561574259","text":"import random\n\n\nclass Lock:\n def __init__(self, lvl, magical=False, code=None):\n self.lvl = lvl\n self.magical = magical\n self.code = code\n self.jammed = False\n self.exp = 50\n\n def unlock(self, wins_dict, pc, lockpick=None, lockpick_mod=None):\n # checking for keys\n pc_keys = pc.char_sheet.inventory_search_by_id(14, level=self.lvl)\n if self.magical:\n wins_dict['realm'].spawn_realmtext('new_txt', \"The lock is unpickable!\", (0, 0), (0, -24), None, pc, None,\n 120, 'def_bold', 24)\n return False\n elif self.jammed:\n wins_dict['realm'].spawn_realmtext('new_txt', \"The lock is jammed!\", (0, 0), (0, -24), None, pc, None,\n 120, 'def_bold', 24)\n wins_dict['realm'].pygame_settings.audio.sound('mech_hard')\n return False\n elif lockpick is not None:\n lvl_dif = min(1, lockpick.props['lvl'] - self.lvl)\n skill = pc.char_sheet.profs['prof_picklock'] + lvl_dif * 250 + lockpick_mod # 25% per level penalty\n rnd_roll = random.randrange(0, 1001)\n if rnd_roll == 1000 or rnd_roll - skill >= 500:\n self.jammed = True\n wins_dict['realm'].spawn_realmtext('new_txt', \"I've jammed $n the lock!\", (0, 0), (0, -24), None, pc, None,\n 120, 'def_bold', 24)\n wins_dict['realm'].pygame_settings.audio.sound('lock_jam')\n lockpick.props['condition'] = 0\n return False\n if rnd_roll == 0 or skill >= rnd_roll:\n wins_dict['realm'].spawn_realmtext('new_txt', \"Easy as pie!\", (0, 0), (0, -24), None, pc, None, 120,\n 'def_bold', 24)\n\n exp = self.exp + self.exp * wins_dict['realm'].maze.EXP_SCALE_RATE * (self.lvl - 1)\n pc.char_sheet.experience_get(wins_dict, pc, self.lvl, exp)\n wins_dict['pools'].updated = True\n wins_dict['charstats'].updated = True\n wins_dict['realm'].pygame_settings.audio.sound('lock_operate')\n lockpick.props['condition'] -= round(self.lvl / lockpick.props['lvl'] * 100)\n return True\n else:\n wins_dict['realm'].spawn_realmtext('new_txt', \"Too hard!\", (0, 0), (0, -24), None, pc, None, 120,\n 'def_bold', 24)\n wins_dict['realm'].pygame_settings.audio.sound('mech_hard')\n lockpick.props['condition'] -= round(self.lvl / lockpick.props['lvl'] * 200)\n return False\n elif len(pc_keys) > 0:\n pc.char_sheet.inventory[pc.char_sheet.inventory.index(pc_keys[0])] = None\n wins_dict['inventory'].updated = True\n wins_dict['realm'].spawn_realmtext('new_txt', \"I have a key $n for this one!\", (0, 0), (0, -24),\n None, pc, None, 120, 'def_bold', 24)\n wins_dict['realm'].pygame_settings.audio.sound('lock_operate')\n wins_dict['realm'].pygame_settings.audio.sound(pc_keys[0].props['sound_pickup'])\n return True\n","repo_name":"Sprottenfraulein/tarnacodex","sub_path":"components/lock.py","file_name":"lock.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"39512728025","text":"'''\r\n题目描述\r\n牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?\r\n'''\r\n\r\n# -*- coding:utf-8 -*-\r\nclass Solution:\r\n def ReverseSentence(self, s):\r\n # write code here\r\n if len(s.strip()) == 0:\r\n return s\r\n res = ''\r\n s = s.split(' ')\r\n s.reverse()\r\n for i in s:\r\n res = res + ' ' + i\r\n return res.lstrip()","repo_name":"oscarhscc/algorithm-with-python","sub_path":"剑指offer/翻转单词顺序列.py","file_name":"翻转单词顺序列.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"38847953705","text":"data = [int(i) for i in open(\"17t/17-339.txt\")]\n\nmin_el = min([int(i) for i in data if int(i) > 0 and int(i)%19 == 0])\n\ndef checker(a,b):\n return (a+b) < min_el\n\ncount, array = 0, []\n\nfor i in range(len(data)-2):\n if checker(data[i],data[i+1]):\n count += 1\n array.append(data[i] + data[i+1])\n\nprint(count, abs(max(array)))\n# 4984 696","repo_name":"wBlackPrince/Problem-solutions","sub_path":"17/339.py","file_name":"339.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69928685926","text":"import tkinter\nimport requests\nfrom bs4 import BeautifulSoup\n\nLINK = \"https://coinmarketcap.com/currencies/solana/\"\n\n\ndef get_total_sol():\n total_sol = float(input_field.get())\n usd_label[\"text\"] = f\"${total_sol * sol_price} USD\"\n print(sol_price)\n\n\nresponse = requests.get(LINK)\npage_parse = BeautifulSoup(response.text, 'html.parser')\nsol_price = page_parse.find(\"div\", {\"class\": \"priceValue\"}).find(\"span\").text\nsol_price = float(sol_price[1:])\n\nwindow = tkinter.Tk()\nwindow.title(\"Solana to USD Converter\")\n\n\ninput_field = tkinter.Entry()\ninput_field.insert(\"end\", string=\"0\")\ninput_field.config(width=10)\ninput_field.focus()\ninput_field.grid(column=1, row=0)\n\nsolana_label = tkinter.Label(text=\"Solana\")\nsolana_label.grid(column=2, row=0)\n\nis_equal_label = tkinter.Label(text=\"is equal to\")\nis_equal_label.grid(column=0, row=1)\n\nconvert_button = tkinter.Button(text=\"Convert\", command=get_total_sol)\nconvert_button.grid(column=1, row=1)\n\nusd_label = tkinter.Label(text=\"$0.00 USD\")\nusd_label.grid(column=2, row=1)\n\n\nwindow.mainloop()\n","repo_name":"codingbiscuits/Python","sub_path":"sol-to-usd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37725311797","text":"from rest_framework import routers\nfrom .views import (\n PostModelViewSet,\n ProfileView,\n RegisterView,\n UserUpdate,\n ProfileUpdate,)\nfrom django.urls import path,include\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nroute = routers.DefaultRouter()\nroute.register('',PostModelViewSet,basename='post')\n\nurlpatterns=[\n path('',include(route.urls)),\n path('user/profile/',ProfileView.as_view(),name='profile'),\n path('user/login/',obtain_auth_token),\n path('user/register/',RegisterView.as_view()),\n path('user/update/',UserUpdate.as_view()),\n path('profile/update/',ProfileUpdate.as_view()),\n]","repo_name":"icerahi/tryreactjs","sub_path":"ReactDjangoblog/backend/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70666332965","text":"import flask\r\nfrom flask import current_app\r\nfrom clickhouse_driver import Client\r\n\r\nimport forms # noqa\r\nimport models # noqa\r\nimport auth # noqa\r\n\r\n\r\nbp = flask.Blueprint('api', __name__)\r\n\r\n\r\ndef get_clickhouse_data(query):\r\n clickhouse_client = Client(host=current_app.config['CLICKHOUSE_HOST'],\r\n password=current_app.config['CLICKHOUSE_PASS']) # ClickHouse config\r\n return clickhouse_client.execute(query)\r\n\r\n\r\n@bp.route('/users/info/', methods=['GET', 'POST'])\r\ndef get_info():\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n user_id = flask.request.args.get('user_id')\r\n if not token or not user_id or not auth.check_token(token):\r\n return {}, 403\r\n if flask.request.method == 'GET':\r\n info = models.Info.objects(user_id=user_id).first()\r\n weight = 0 if not info.weight else info.weight\r\n height = 0 if not info.height else info.height\r\n return {\"weight\": weight, \"height\": height, \"name\": info.name, \"surname\": info.surname,\r\n \"patronymic\": info.patronymic, \"email\": info.email, \"birthdate\": info.birth_date,\r\n \"phone_number\": info.phone}, 200\r\n else:\r\n data = flask.request.get_json()\r\n info = models.Info.objects(user_id=user_id).first()\r\n info.weight = data['weight']\r\n info.height = data['height']\r\n info.email = data['email']\r\n info.name = data['name']\r\n info.surname = data['surname']\r\n info.patronymic = data['patronymic']\r\n info.birth_date = data['birthdate']\r\n info.phone = data['phone_number']\r\n info.save()\r\n return {}, 200\r\n\r\n\r\n@bp.route('/users/allow/', methods=[\"POST\"])\r\ndef allow_operator():\r\n \"\"\"Allow access for concrete operator\"\"\"\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n user_id = flask.request.args.get('user_id')\r\n op_id = flask.request.args.get('operator_id')\r\n if not token or not user_id or not auth.check_token(token):\r\n return {}, 403\r\n op = models.Operators.objects.get_or_404(id=op_id)\r\n models.Info.objects(user_id=user_id).update_one(add_to_set__allowed=op.id)\r\n return {}, 200\r\n\r\n\r\n@bp.route('/devices/register/', methods=['POST'])\r\ndef register_device():\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n # FIXME: Дыра, любой зареганый пользователь может зарегать на другого девайс\r\n user_id = flask.request.args.get('user_id')\r\n if not token or not user_id or not auth.check_token(token):\r\n return {}, 403\r\n data = flask.request.get_json()\r\n device = models.Userdevices()\r\n device.user_id = user_id\r\n device.device_id = data['device_id']\r\n device.device_name = data['device_name']\r\n device.device_type = data['device_type']\r\n device.save()\r\n\r\n table_name = user_id + '_' + data['device_id'].replace(':', '')\r\n current_app.logger.info(\"TABLE %s\", table_name)\r\n obj = models.Devices.objects(device_type=data['device_type']).first()\r\n if not obj:\r\n return {}, 403\r\n\r\n create_str = obj.create_str.format(table_name)\r\n current_app.logger.info(\"CREATE %s\", create_str)\r\n\r\n clickhouse_client.execute(create_str)\r\n return {}, 200\r\n\r\n\r\n@bp.route('/devices/get/', methods=['GET'])\r\ndef get_user_devices():\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n user_id = flask.request.args.get('user_id')\r\n if not token or not user_id or not auth.check_token(token):\r\n return {}, 403\r\n objects = models.Userdevices.objects(user_id=user_id)\r\n user_devices = [\r\n {\"device_id\": obj.device_id, \"device_name\": obj.device_name, \"device_type\": obj.device_type}\r\n for obj in objects\r\n ]\r\n return flask.jsonify({\"devices\": user_devices}), 200\r\n\r\n\r\n@bp.route('/devices/types/', methods=['GET'])\r\ndef get_devices():\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n type_id = flask.request.args.get('id')\r\n if not token or not auth.check_token(token):\r\n return {'message': \"invalid token\", \"token\": token}, 403\r\n with open(f\"device_type_cfgs/{type_id}.toml\", 'rt') as f:\r\n return f.read()\r\n # return flask.send_from_directory('device_type_cfgs', f\"{type_id}.toml\") if type_id == '1' else flask.abort(404, f\"Config_id {type_id} not found\") # FIXME\r\n if type_id is str and type_id.isdecimal():\r\n models.Devices.objects()\r\n models.Devices.objects(id=type_id).first()\r\n devices_types = [\r\n {\"device_type\": obj.device_type, \"prefix\": obj.prefix}\r\n for obj in models.Devices.objects()\r\n ]\r\n for obj in models.Devices.objects():\r\n devices_types.append({\"device_type\": obj.device_type, \"prefix\": obj.prefix})\r\n return flask.jsonify({\"devices\": devices_types}), 200\r\n\r\n\r\n@bp.route('/devices/delete/', methods=['GET'])\r\ndef delete_device():\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n user_id = flask.request.args.get('user_id')\r\n device_id = flask.request.args.get('id')\r\n if not token or not user_id or not auth.check_token(token):\r\n return {}, 403\r\n d = models.Userdevices.objects(user_id=user_id, device_id=device_id).first()\r\n d.delete()\r\n return {}, 200\r\n\r\n\r\n@bp.route('/jwt/', methods=['GET'])\r\ndef jwt():\r\n token = flask.request.args.get('token') or flask.request.headers.get('Authorization').split()[1]\r\n if not token or not auth.check_token(token):\r\n return flask.jsonify({\"valid\": False})\r\n else:\r\n return flask.jsonify({\"valid\": True})\r\n","repo_name":"IoMT-LVK/iomt_backend","sub_path":"services/web/blueprints/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"8930061539","text":"# -*- coding: utf-8 -*-\n\"\"\"\n用于管理缓存的配置数据\n使用前必须先调用 init() 。\n\"\"\"\nimport copy\nimport json\nimport logging\nimport os\n\nfrom mootdx.consts import EX_HOSTS, GP_HOSTS, HQ_HOSTS\nfrom mootdx.utils import get_config_path\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['set', 'get', 'copy', 'update', 'settings']\n\nsettings = {\n 'SERVER': {\n 'HQ': HQ_HOSTS,\n 'EX': EX_HOSTS,\n 'GP': GP_HOSTS\n },\n 'BESTIP': {\n 'HQ': '',\n 'EX': '',\n 'GP': ''\n },\n 'TDXDIR': 'C:/new_tdx',\n}\n\nBASE = os.path.dirname(os.path.dirname(__file__))\nCONF = get_config_path('config.json')\n\n\ndef setup():\n \"\"\"\n 将 yaml 里的配置文件导入到 config.py 中\n :return: bool,true 表示数据导入成功。\n \"\"\"\n global settings\n\n try:\n options = json.load(open(CONF))\n settings.update(options)\n except Exception:\n logger.error(\n '未找到配置文件 config.json. 请在命令行运行 \"mootdx bestip -w -v\" 生成配置文件')\n\n return True if settings else False\n\n\ndef has(key, value):\n '''\n 通过 key 设置某一项值\n\n :param key:\n :param value:\n :return:\n '''\n return value in settings[key]\n\n\ndef set(key, value):\n '''\n 通过 key 设置某一项值\n :param key:\n :param value:\n :return:\n '''\n settings[key] = value\n\n\ndef get(key, default=None):\n '''\n 通过 key 获取值\n :param key:\n :param default:\n :return:\n '''\n key = key.split('.')\n cfg = settings.get(key[0])\n\n if len(key) > 1:\n for x in key[1:]:\n if cfg.get(x):\n cfg = cfg.get(x)\n else:\n cfg = cfg.get(x, default)\n break\n\n return cfg\n\n\ndef path(key, value=None):\n '''\n 通过 key 构建路径\n :param key:\n :param value:\n :return:\n '''\n path = settings.get(key)\n path = os.path.join(BASE, path, value)\n\n return path\n\n\ndef clone():\n '''\n 复制配置\n :return:\n '''\n return copy.deepcopy(settings)\n\n\ndef update(options):\n '''\n 全部替换配置\n :param options:\n :return:\n '''\n settings.update(options)\n","repo_name":"TianShengBingFeiNiuRen/moo-tdx-api","sub_path":"Lib/site-packages/mootdx/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"} +{"seq_id":"27603710759","text":"from datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom enum import Enum\nimport numpy as np\nfrom matplotlib.ticker import FormatStrFormatter\nimport matplotlib.dates as mdates\n\npd.set_option('display.max_columns', None)\npd.options.display.float_format = '{:.2f}'.format\n\nCEF_DATA_SOURCES = {\"ADX\": [\"data/adx_hist_prices.csv\", \"data/adx_hist_navs.csv\"],\n \"CII\": [\"data/cii_hist_prices.csv\", \"data/cii_hist_navs.csv\"],\n \"EOS\": [\"data/eos_hist_prices.csv\", \"data/eos_hist_navs.csv\"]}\n\nDATA_FILE_POSTFIX = \"_data.csv\"\nZ_SCORE_POSTFIX = \" Z-score\"\nRETURN_PREFIX = \"Return on \"\n\nDATA_PATH_PREFIX = \"data/\"\nDATE_COL_NAME = \"Date\"\nPRICE_COL_NAME = \"Price\"\nPRICE_RETURNS_COL_NAME = RETURN_PREFIX + PRICE_COL_NAME\nNAV_COL_NAME = \"NAV\"\nNAV_RETURNS_COL_NAME = RETURN_PREFIX + NAV_COL_NAME\nPREM_DISC_COL_NAME = \"Prem/Disc\"\nPREM_DISC_ZSCORE_COL_NAME = PREM_DISC_COL_NAME + Z_SCORE_POSTFIX\nRESIDUALS_COL_NAME = \"Res\"\nRESIDUAL_ZSCORE_COL_NAME = RESIDUALS_COL_NAME + str(Z_SCORE_POSTFIX)\nACTION_COL_NAME = \"Action\"\nPROFIT_DELTA_COL_NAME = \"P&L Delta $\"\nPROFIT_DELTA_PERC_COL_NAME = \"P&L Delta %\"\nCUMULATIVE_PROFIT_COL_NAME = \"Cum P&L $\"\nHOLDING_PERIOD_COL_NAME = \"HP (days)\"\nX_COL_NAME = \"Nav Returns\"\nY_COL_NAME = \"Actual Price Returns\"\nY_PREDICTED_COL_NAME = \"Predicted Price Returns\"\n\nCEF_TICKER = \"ADX\"\nREGRESSOR_COL_NAME = NAV_RETURNS_COL_NAME\nTRAIN_DATA_RATIO = 0.75\nPERIOD_3MONTHS = relativedelta(months=3)\nPERIOD_6MONTHS = relativedelta(months=6)\nPERIOD_1YEAR = relativedelta(years=1)\nPERIOD_2YEAR = relativedelta(years=2)\nAVERAGES_CALC_PERIOD = PERIOD_3MONTHS\nANALYSIS_DATA_PERIOD = PERIOD_1YEAR\n\n\nclass TradeAction(Enum):\n\tBUY_LONG = \"Buy Long\"\n\tCOVER_LONG = \"Cover Long\"\n\tSELL_SHORT = \"Sell Short\"\n\tCOVER_SHORT = \"Cover Short\"\n\n\nclass TradePosition(Enum):\n\tLONG = \"Long\"\n\tSHORT = \"Short\"\n\tNO_POSITION = \"No position\"\n\n\ndef read_raw_cef_data(cef_symbol):\n\t\"\"\"\n\tRead Closed-End Fund price and Net Asset Value (NAV) quotes from csv file format.\n\tCef tickers and file names are taken from user defined dict CEF_DATA_SOURCES\n\t:param cef_symbol: Ticker of the financial asset.\n\t:return: pandas DataFrame with cols: [DATE_COL_NAME, PRICE_COL_NAME, NAV_COL_NAME]\n\t\"\"\"\n\tcef = pd.read_csv(CEF_DATA_SOURCES[cef_symbol][0])\n\tcef = cef[[\"timestamp\", \"close\"]]\n\tcef.columns = [DATE_COL_NAME, PRICE_COL_NAME]\n\tcef[NAV_COL_NAME] = pd.read_csv(CEF_DATA_SOURCES[cef_symbol][1])[\"close\"]\n\tcef[DATE_COL_NAME] = pd.to_datetime(cef[DATE_COL_NAME])\n\tcef = cef.sort_values([DATE_COL_NAME])\n\treturn cef\n\n\ndef calculate_zscore(df, col_name, period_start_date, period_end_date):\n\t\"\"\"\n\tCalculating Z-score of the value in the cell [df[DATE_COL_NAME]==period_end_date, col_name]\n\tfrom period_start_date to period_end_date.\n\tDataFrame should contain column DATE_COL_NAME and col_name.\n\t\n\t:return: DataFrame with calculated z-score for 'period_end_date'\n\t\"\"\"\n\tdata = df.loc[\n\t\t(df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= period_end_date), col_name]\n\tcurr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0]\n\taverage_value = data.mean()\n\tstd = data.std()\n\tzscore = (curr_value - average_value) / std\n\tdf.loc[df[DATE_COL_NAME] == period_end_date, col_name + Z_SCORE_POSTFIX] = zscore\n\treturn df\n\n\ndef calculate_return(df, col_name, period_start_date, period_end_date):\n\t\"\"\"\n\tCalculating holding period return from period_start_date to period_end_date.\n\tDataFrame should contain column DATE_COL_NAME and col_name.\n\t\n\t:return: DataFrame with calculated return for 'period_end_date'\n\t\"\"\"\n\tbase_value = df.loc[df[DATE_COL_NAME] == period_start_date, col_name].values[0]\n\tcurr_value = df.loc[df[DATE_COL_NAME] == period_end_date, col_name].values[0]\n\tprice_return = (curr_value - base_value) / base_value * 100\n\tdf.loc[df[DATE_COL_NAME] == period_end_date, RETURN_PREFIX + col_name] = price_return\n\treturn df\n\n\ndef find_valid_period_start_date(dates, date, period):\n\t\"\"\"\n\tSelect an existing period begin date in ordered list of dates\n\t\"\"\"\n\t\n\tperiod_start_date = date - period\n\tperiod_dates = dates[dates >= period_start_date]\n\tfirst_date = period_dates.iloc[0]\n\treturn first_date\n\n\ndef calculate_trailing_residual_zscores(df_input, regressor_col_name, simulation_begin_date, calc_period):\n\t\"\"\"\n\tCalculating trailing calc_period z-scores for residuals = y - y_predicted\n\tfrom simulation_begin_date to last date, the regressand is always Price Returns.\n\t\n\t:return: DataFrame with calculated residual z-score column base on trailing history calc_period\n\t\"\"\"\n\tdf = df_input.copy()\n\tall_dates = df[DATE_COL_NAME]\n\tdates = df.loc[df[DATE_COL_NAME] >= simulation_begin_date, DATE_COL_NAME].reset_index(drop=True)\n\tfor date in dates:\n\t\tperiod_start_date = find_valid_period_start_date(all_dates, date, calc_period)\n\t\tdata = df[(df[DATE_COL_NAME] >= period_start_date) & (df[DATE_COL_NAME] <= date)].reset_index(drop=True)\n\t\tx = data[regressor_col_name].values.reshape(-1, 1)\n\t\ty = np.array(data[PRICE_RETURNS_COL_NAME].values)\n\t\t\n\t\tregress_model = LinearRegression().fit(x, y)\n\t\ty_predicted = regress_model.predict(x)\n\t\tresiduals = y - y_predicted\n\t\t\n\t\tcurr_val = residuals[len(residuals) - 1]\n\t\taverage_value = residuals.mean()\n\t\tstd = residuals.std()\n\t\tzscore = (curr_val - average_value) / std\n\t\tdf.loc[df[DATE_COL_NAME] == date, RESIDUAL_ZSCORE_COL_NAME] = zscore\n\t\n\tdf = df.loc[df[DATE_COL_NAME] >= simulation_begin_date].reset_index(drop=True)\n\treturn df\n\n\ndef calculate_factors(cef, start_date, period):\n\t\"\"\"\n\tCalculating price returns, nav returns and premium/discount z-scores\n\tbased on history 'period' for analyzing Closed End Fund performance.\n\n\t:return: DataFrame with calculated factors\n\t\"\"\"\n\tcef = cef[(cef[DATE_COL_NAME] >= start_date - period)]\n\tall_dates = cef[DATE_COL_NAME].reset_index(drop=True)\n\tcef[PREM_DISC_COL_NAME] = (cef[PRICE_COL_NAME] - cef[NAV_COL_NAME]) / cef[NAV_COL_NAME] * 100\n\t\n\tdates = cef.loc[cef[DATE_COL_NAME] >= start_date, DATE_COL_NAME].reset_index(drop=True)\n\tfor date in dates:\n\t\tperiod_start_date = find_valid_period_start_date(all_dates, date, period)\n\t\tcef = calculate_return(cef, PRICE_COL_NAME, period_start_date, date)\n\t\tcef = calculate_return(cef, NAV_COL_NAME, period_start_date, date)\n\t\tcef = calculate_zscore(cef, PREM_DISC_COL_NAME, period_start_date, date)\n\treturn cef\n\n\ndef calculate_cef_data(symbol, analysis_data_period, calc_period):\n\t\"\"\"\n\tProcessing raw input Cef data which may take some time. Calculating factors for conducting analysis\n\tand saving data to new csv file. This method should be called only if we made changes to TRAIN_DATA_RATIO,\n\tAVERAGES_CALC_PERIOD, START_DATE etc.\n\n\t\"\"\"\n\tprint(\"Processing data ... Please wait ... for 'Data processing finished!' indication below!\")\n\tdf = read_raw_cef_data(symbol)\n\tdates = df[DATE_COL_NAME].reset_index(drop=True)\n\tend_date = str(dates.values[-1]).split(\"T\")[0]\n\tend_date = datetime.strptime(end_date, \"%Y-%m-%d\")\n\tstart_date = find_valid_period_start_date(dates, end_date, analysis_data_period)\n\tdf = calculate_factors(df, start_date, calc_period).reset_index(drop=True)\n\tdf = df.loc[df[DATE_COL_NAME] >= start_date].reset_index(drop=True)\n\tfile_name = symbol.lower() + DATA_FILE_POSTFIX\n\tpath = DATA_PATH_PREFIX + file_name\n\tdf.to_csv(path)\n\tprint(\"Data processing finished!\")\n\n\ndef split_train_test_data(cef, split_data_coefficient):\n\t\"\"\"\n\tSplit explored data time series into two periods for training and testing based on coefficient.\n\t\"\"\"\n\ttrain_data_end_index = int((len(cef) - 1) * split_data_coefficient)\n\tcef_train_data = cef.loc[cef.index <= train_data_end_index]\n\tcef_test_data = cef.loc[cef.index > train_data_end_index].reset_index(drop=True)\n\treturn cef_train_data, cef_test_data\n\n\ndef analyze_regression(cef_ticker, cef_train_data, cef_test_data, regressor_col_name, regressand_col_name):\n\t\"\"\"\n\tApplying regression on train data and test the model on test data.\n\t\"\"\"\n\tregressor_train_data = cef_train_data[regressor_col_name].values.reshape(-1, 1)\n\tregressand_train_data = np.array(cef_train_data[regressand_col_name].values)\n\t\n\tregressor_test_data = cef_test_data[regressor_col_name].values.reshape(-1, 1)\n\tregressand_actual_test_data = np.array(cef_test_data[regressand_col_name].values)\n\t\n\tregress_model = LinearRegression().fit(regressor_train_data, regressand_train_data)\n\tintercept = regress_model.intercept_\n\tcoef = regress_model.coef_[0]\n\t\n\tr_sq_x_y = regress_model.score(regressor_train_data, regressand_train_data)\n\tregressand_predicted_test_data = regress_model.predict(regressor_test_data)\n\tresiduals = regressand_actual_test_data - regressand_predicted_test_data\n\tdates = cef_test_data[DATE_COL_NAME]\n\t\n\tcorr_train_data_x_y = cef_train_data[regressor_col_name].corr(cef_train_data[regressand_col_name])\n\tcorr_test_predicted_actual_y = np.corrcoef(regressand_predicted_test_data, regressand_actual_test_data)[0, 1]\n\t\n\tregress_data = pd.DataFrame.from_dict({DATE_COL_NAME: dates.values,\n\t RESIDUALS_COL_NAME: residuals,\n\t X_COL_NAME: list(regressor_test_data),\n\t Y_COL_NAME: regressand_actual_test_data,\n\t Y_PREDICTED_COL_NAME: regressand_predicted_test_data})\n\tregress_statistics = {\"cef_ticker\": cef_ticker,\n\t \"regressor\": regressor_col_name,\n\t \"intercept\": intercept,\n\t \"coef\": coef,\n\t \"R-square\": r_sq_x_y,\n\t \"Corr_x_y\": corr_train_data_x_y,\n\t \"Corr_pred_actual_y\": corr_test_predicted_actual_y}\n\t\n\treturn regress_data, regress_statistics\n\n\ndef read_processed_cef_data(cef_ticker):\n\t\"\"\"\n\tReading processed Cef data from file as DataFrame.\n\t\"\"\"\n\tpath = DATA_PATH_PREFIX + cef_ticker.lower() + DATA_FILE_POSTFIX\n\tcef = pd.read_csv(path, index_col=0)\n\tcef[DATE_COL_NAME] = pd.to_datetime(cef[DATE_COL_NAME])\n\tcef = cef[[DATE_COL_NAME, PRICE_COL_NAME, PRICE_RETURNS_COL_NAME, NAV_RETURNS_COL_NAME, PREM_DISC_ZSCORE_COL_NAME]]\n\treturn cef\n\n\ndef run_residual_trade_simulation(trade_simul_data, zscore_buy_long=-1.5, zscore_cover_long=-0.5, zscore_sell_short=1.5,\n zscore_cover_short=0.5):\n\t\"\"\"\n\tRunning trade simulation on the given time series based on residual z-score.\n\tSimulation takes long and short positions. One position at a time.\n\t:return: trades DataFrame and time series DataFrame of profits and losses.\n\t\"\"\"\n\tdata = trade_simul_data[[DATE_COL_NAME, PRICE_COL_NAME, RESIDUAL_ZSCORE_COL_NAME]]\n\ttrades = pd.DataFrame(\n\t\tcolumns=[DATE_COL_NAME, PRICE_COL_NAME, RESIDUAL_ZSCORE_COL_NAME, ACTION_COL_NAME, HOLDING_PERIOD_COL_NAME,\n\t\t PROFIT_DELTA_COL_NAME, CUMULATIVE_PROFIT_COL_NAME])\n\tdates = trade_simul_data[DATE_COL_NAME]\n\tcontinuos_profits = pd.DataFrame(\n\t\tcolumns=[DATE_COL_NAME, PRICE_COL_NAME, PROFIT_DELTA_COL_NAME, CUMULATIVE_PROFIT_COL_NAME])\n\tcontinuos_profits[DATE_COL_NAME] = dates\n\tcontinuos_profits[PRICE_COL_NAME] = trade_simul_data[PRICE_COL_NAME]\n\t\n\ttrade_position = TradePosition.NO_POSITION\n\tcum_realized_profit = 0\n\tcum_continous_profit = 0\n\tfor i in data.index.values:\n\t\trow = data.iloc[i]\n\t\tcurr_date = row[DATE_COL_NAME]\n\t\tcurr_price = row[PRICE_COL_NAME]\n\t\tresidual_zscore = row[RESIDUAL_ZSCORE_COL_NAME]\n\t\tdaily_profit_delta = 0\n\t\t\n\t\tif trade_position == TradePosition.NO_POSITION:\n\t\t\tholding_period = 0\n\t\t\trealized_profit_delta = 0\n\t\t\tif residual_zscore <= zscore_buy_long:\n\t\t\t\taction = TradeAction.BUY_LONG\n\t\t\t\ttrade_row = list(\n\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\ttrade_position = TradePosition.LONG\n\t\t\telif residual_zscore >= zscore_sell_short:\n\t\t\t\taction = TradeAction.SELL_SHORT\n\t\t\t\ttrade_row = list(\n\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\ttrade_position = TradePosition.SHORT\n\t\telse:\n\t\t\tprevious_day_price = data.iloc[i - 1, 1]\n\t\t\tentry_date = trades.iloc[-1, 0]\n\t\t\tholding_period = (curr_date - entry_date).days\n\t\t\tentry_price = trades.iloc[-1, 1]\n\t\t\tif trade_position == TradePosition.LONG:\n\t\t\t\tdaily_profit_delta = curr_price - previous_day_price\n\t\t\t\tif residual_zscore >= zscore_cover_long:\n\t\t\t\t\taction = TradeAction.COVER_LONG\n\t\t\t\t\trealized_profit_delta = curr_price - entry_price\n\t\t\t\t\tcum_realized_profit += realized_profit_delta\n\t\t\t\t\ttrade_row = list(\n\t\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\t\ttrade_position = TradePosition.NO_POSITION\n\t\t\telif trade_position == TradePosition.SHORT:\n\t\t\t\tdaily_profit_delta = previous_day_price - curr_price\n\t\t\t\tif residual_zscore <= zscore_cover_short:\n\t\t\t\t\taction = TradeAction.COVER_SHORT\n\t\t\t\t\trealized_profit_delta = entry_price - curr_price\n\t\t\t\t\tcum_realized_profit += realized_profit_delta\n\t\t\t\t\ttrade_row = list(\n\t\t\t\t\t\tnp.concatenate([row.values,\n\t\t\t\t\t\t [action, holding_period, realized_profit_delta,\n\t\t\t\t\t\t cum_realized_profit]]))\n\t\t\t\t\ttrades = append_row(trades, trade_row)\n\t\t\t\t\ttrade_position = TradePosition.NO_POSITION\n\t\t\tcum_continous_profit += daily_profit_delta\n\t\t\n\t\tcontinuos_profits.iloc[i, 2] = daily_profit_delta\n\t\tcontinuos_profits.iloc[i, 3] = cum_continous_profit\n\t\n\treturn trades, continuos_profits\n\n\ndef append_row(trades, trade_row):\n\ttrades = trades.append({DATE_COL_NAME: trade_row[0],\n\t PRICE_COL_NAME: trade_row[1],\n\t RESIDUAL_ZSCORE_COL_NAME: trade_row[2],\n\t ACTION_COL_NAME: trade_row[3].name,\n\t HOLDING_PERIOD_COL_NAME: trade_row[4],\n\t PROFIT_DELTA_COL_NAME: trade_row[5],\n\t CUMULATIVE_PROFIT_COL_NAME: trade_row[6]}, ignore_index=True)\n\treturn trades\n\n\ndef plot_trade_simulation(cef_ticker, trades, continuous_profits):\n\tdates = continuous_profits[DATE_COL_NAME]\n\tprices = continuous_profits[PRICE_COL_NAME]\n\tprofit_deltas = continuous_profits[PROFIT_DELTA_COL_NAME]\n\tcum_profit = continuous_profits[CUMULATIVE_PROFIT_COL_NAME]\n\tbuys = trades.loc[\n\t\t(trades[ACTION_COL_NAME] == TradeAction.BUY_LONG.name) | (\n\t\t\t\ttrades[ACTION_COL_NAME] == TradeAction.COVER_SHORT.name), [DATE_COL_NAME, PRICE_COL_NAME]]\n\tsells = trades.loc[\n\t\t(trades[ACTION_COL_NAME] == TradeAction.SELL_SHORT.name) | (\n\t\t\t\ttrades[ACTION_COL_NAME] == TradeAction.COVER_LONG.name), [DATE_COL_NAME, PRICE_COL_NAME]]\n\t\n\tfig, [ax1, ax2, ax3] = plt.subplots(1, 3, figsize=(15, 4))\n\t\n\tax1.plot(dates, prices, alpha=0.6)\n\tax1.scatter(buys[DATE_COL_NAME], buys[PRICE_COL_NAME], marker=\"^\", c=\"g\", label=\"Buy Prices\")\n\tax1.scatter(sells[DATE_COL_NAME], sells[PRICE_COL_NAME], marker=\"v\", c=\"r\", label=\"Sell Prices\")\n\tax1.xaxis.set_major_formatter(mdates.DateFormatter(\"%y/%m/%d\"))\n\tax1.yaxis.set_major_formatter(FormatStrFormatter(\"$%.2f\"))\n\tax1.set_xlabel(\"Dates\", fontsize=10)\n\tax1.set_ylabel(\"Prices\", fontsize=10)\n\tax1.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax1.set_title(\"Trade Simulation\", fontsize=12)\n\tax1.legend(loc=4, prop={\"size\": 8})\n\t\n\tax2.bar(dates, profit_deltas)\n\tax2.axhline(y=0, linewidth=1, color='k')\n\tax2.xaxis.set_major_formatter(mdates.DateFormatter(\"%y/%m/%d\"))\n\tax2.yaxis.set_major_formatter(FormatStrFormatter(\"$%.2f\"))\n\tax2.set_xlabel(\"Date\", fontsize=10)\n\tax2.set_ylabel(\"Profit Deltas\", fontsize=10)\n\tax2.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax2.set_title(\"Profit Daily Changes\", fontsize=12)\n\t\n\tax3.plot(dates, cum_profit)\n\tax3.axhline(y=0, linewidth=1, color='k')\n\tax3.xaxis.set_major_formatter(mdates.DateFormatter(\"%y/%m/%d\"))\n\tax3.yaxis.set_major_formatter(FormatStrFormatter(\"$%.2f\"))\n\tax3.set_xlabel(\"Dates\", fontsize=10)\n\tax3.set_ylabel(\"Profit/Loss In $\", fontsize=10)\n\tax3.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax3.set_title(\"Profit/Loss Dynamics\", fontsize=12)\n\tax3.legend(loc=3, prop={\"size\": 8})\n\t\n\tfig.suptitle(cef_ticker)\n\tplt.subplots_adjust(wspace=0.25)\n\tplt.show()\n\n\ndef plot_regress_result(regress_data, regress_statistics):\n\tdates = regress_data[DATE_COL_NAME]\n\tresiduals = regress_data[RESIDUALS_COL_NAME]\n\tx = regress_data[X_COL_NAME]\n\ty_predicted = regress_data[Y_PREDICTED_COL_NAME]\n\ty_actual = regress_data[Y_COL_NAME]\n\tcef_ticker = regress_statistics[\"cef_ticker\"]\n\tregressor = regress_statistics[\"regressor\"]\n\tintercept = regress_statistics[\"intercept\"]\n\tcoef = regress_statistics[\"coef\"]\n\tcorr_x_y = regress_statistics[\"Corr_x_y\"]\n\tr_sq = regress_statistics[\"R-square\"]\n\tcorr_pred_actual = regress_statistics[\"Corr_pred_actual_y\"]\n\ttext_ax1 = \"y = {0:.3f} + {1:.3f}.x\\n\" \\\n\t \"corr = {2:.3f}\\n\" \\\n\t \"r_sq = {3:.3f}\".format(intercept, coef, corr_x_y, r_sq)\n\ttext_ax2 = \"corr_pred_vs_actual = {0:.3f}\".format(corr_pred_actual)\n\t\n\tfig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2, figsize=(13, 10))\n\t\n\tax1.plot(x, y_predicted, label=\"Predicted Price Returns\", c=\"b\")\n\tax1.scatter(x, y_actual, c=\"y\", s=14, label=\"Actual Pice Returns\")\n\tax1.xaxis.set_major_formatter(FormatStrFormatter(\"%.2f%%\"))\n\tax1.yaxis.set_major_formatter(FormatStrFormatter(\"%.2f%%\"))\n\tax1.set_xlabel(regressor, fontsize=10)\n\tax1.set_ylabel(\"Price Returns\", fontsize=10)\n\tax1.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax1.text(0.05, 0.85, text_ax1, color=\"b\", ha='left', va='center', transform=ax1.transAxes, fontsize=12)\n\tax1.set_title(\"{0}-Price Returns Regression Model\".format(regressor), fontsize=12)\n\tax1.legend(loc=4, prop={\"size\": 8})\n\t\n\tax2.plot(dates, y_predicted, label=\"Predicted Price Returns\", c=\"b\")\n\tax2.plot(dates, y_actual, label=\"Actual Pice Returns\", c=\"y\")\n\tax2.axhline(y=0, linewidth=1, color='k')\n\tax2.xaxis.set_major_formatter(mdates.DateFormatter(\"%y/%m/%d\"))\n\tax2.yaxis.set_major_formatter(FormatStrFormatter(\"%.2f%%\"))\n\tax2.set_xlabel(\"Date\", fontsize=10)\n\tax2.set_ylabel(\"Price Returns\", fontsize=10)\n\tax2.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax2.text(0.05, 0.95, text_ax2, color=\"b\", ha='left', va='center', transform=ax2.transAxes, fontsize=11)\n\tax2.set_title(\"Predicted vs Actual Price Returns\", fontsize=12)\n\tax2.legend(loc=4, prop={\"size\": 8})\n\t\n\tax3.bar(dates, residuals)\n\tax3.axhline(y=0, linewidth=1, color='k')\n\tax3.xaxis.set_major_formatter(mdates.DateFormatter(\"%y/%m/%d\"))\n\tax3.yaxis.set_major_formatter(FormatStrFormatter(\"%.2f%%\"))\n\tax3.set_xlabel(\"Date\", fontsize=10)\n\tax3.set_ylabel(\"Residuals\", fontsize=10)\n\tax3.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax3.set_title(\"Predicted - Actual Price Returns (residuals)\", fontsize=12)\n\t\n\tax4.hist(residuals, bins=\"fd\")\n\tax4.xaxis.set_major_formatter(FormatStrFormatter(\"%.2f%%\"))\n\tax4.set_xlabel(\"Residuals\", fontsize=10)\n\tax4.set_ylabel(\"Count\", fontsize=10)\n\tax4.tick_params(axis='both', which='both', labelsize=8, rotation=30)\n\tax4.set_title(\"Residuals Distribution\", fontsize=12)\n\t\n\tfig.suptitle(cef_ticker)\n\tplt.subplots_adjust(hspace=0.3, top=0.93)\n\tplt.show()\n\n\ndef main():\n\t# calculate_cef_data(CEF_TICKER, ANALYSIS_DATA_PERIOD, AVERAGES_CALC_PERIOD)\n\tcef = read_processed_cef_data(CEF_TICKER)\n\tcef_train_data, cef_test_data = split_train_test_data(cef, TRAIN_DATA_RATIO)\n\n\tregress_data, regress_statistics = analyze_regression(CEF_TICKER, cef_train_data, cef_test_data, REGRESSOR_COL_NAME,\n\t PRICE_RETURNS_COL_NAME)\n\tplot_regress_result(regress_data, regress_statistics)\n\n\tsimulation_start_date = cef_test_data[DATE_COL_NAME].values[0]\n\tcef_simul_data = calculate_trailing_residual_zscores(cef, REGRESSOR_COL_NAME, simulation_start_date,\n\t AVERAGES_CALC_PERIOD)\n\n\ttrades, continuos_profits = run_residual_trade_simulation(cef_simul_data)\n\tplot_trade_simulation(CEF_TICKER, trades, continuos_profits)\n\n\tprint(trades)\n\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"HristoRaykov/ArtIntelligence-04.2019","sub_path":"MathConcepts/FinalProject/cef_regression.py","file_name":"cef_regression.py","file_ext":"py","file_size_in_byte":20202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1817529470","text":"class Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n for idx, num in enumerate(numbers) :\n expacted = target - num\n start_to_search = idx + 1\n find_point = bisect.bisect_left(numbers, expacted, lo=start_to_search)\n if find_point < len(numbers) and numbers[find_point] == expacted :\n return [idx+1, find_point+1]\n\n'''\nRuntime : 88 ms\nMemory : 14.8 MB\n'''\n","repo_name":"LeeHyeonKyu/Coding-Practice","sub_path":"LeetCode/(167) Two Sum II/3-Use_Bisect_Module.py","file_name":"3-Use_Bisect_Module.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30451976820","text":"#!/usr/bin/env python3\n# 52digest.py\n\nimport re\nimport sys\nimport math\n\n# Write a program that performs an EcoRI digest on the SARS-COV2 genome\n# The program should have 2 arguments\n# 1. The genome file\n# 2. The restriction pattern\n# The output should be the sizes of the restriction fragments\nsample = 'actagatcgatgactagctccgtcgattctcgatcgatcaagctcgat'\nsamplesite = 'ctag'\nbases = 'acgt'\n\nif len(sys.argv) != 3:\n\tprint('Insufficient or too much input')\n\tsys.exit()\n\n#locates restriction cutting sites, returns in an array\ndef findsites(sequence, site):\n\tsplices = []\n\tfor match in re.finditer(site, sequence):\n\t\tsplice = match.start()\n\t\tsplices.append(int(splice))\n\treturn splices\n\n#creates array of digest fragments from a sequence\n#and array of splice sites\ndef splicer(sequence, indeces):\n\tsegments = []\n\tprevioussite = 0\n\tfor i in range(len(indeces)):\n\t\tsegments.append(sequence[previoussite:indeces[i]])\n\t\tif i == len(indeces) - 1:\n\t\t\tsegments.append(sequence[indeces[i]:])\n\t\tprevioussite = indeces[i]\n\treturn segments\n\n#reads a .gb file and returns the DNA sequence in a string\ndef readgbdna(filename):\n\tdnaseq = ''\n\twith open(filename) as fp:\n\t\tstartingflag = False\n\t\tendingflag = False\n\t\tfor line in fp.readlines():\n\t\t\tlinetext = line.rstrip()\n\t\t\tif len(linetext) >= 6 and linetext[0:6] == 'ORIGIN':\n\t\t\t\tstartingflag = True\n\t\t\t\tcontinue\n\t\t\tif startingflag:\n\t\t\t\tfor char in linetext:\n\t\t\t\t\tif char in bases:\n\t\t\t\t\t\tdnaseq += char\n\treturn dnaseq\n\n#Sample\n\"\"\"\nsites = findsites(sample, samplesite)\nspliceddna = splicer(sample, sites)\nprint(spliceddna)\n\"\"\"\n\n#main program\n\ndna = readgbdna(sys.argv[1])\nsites = findsites(dna, sys.argv[2])\nspliceddna = splicer(dna, sites)\nfor segment in spliceddna:\n\tprint(len(segment))\n\n\"\"\"\npython3 52digest.py ../Data/sars-cov2.gb gaattc\n1160\n10573\n5546\n448\n2550\n2592\n3569\n2112\n1069\n\"\"\"\n","repo_name":"Roshan-Sen/Homework","sub_path":"52digest.py","file_name":"52digest.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9541762249","text":"from typing import Union\nimport logging\nimport shutil\nimport time\nfrom pprint import pprint\n\nimport pendulum\n\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator, PythonVirtualenvOperator\nfrom airflow.executors.debug_executor import DebugExecutor\n\n\n\ndef wheres_my_args_dude(*args, **kwargs):\n what_to_print = f\"\"\"\n \n=====\nARGS\n=====\n{args}\n\n=======\nKWARGS\n=======\n{kwargs}\n\n\"\"\"\n print(what_to_print)\n\n\n\ndef create_venv_operator(\n name: str, dag: DAG, use_virtualenv: bool, *args) -> Union[PythonVirtualenvOperator, PythonOperator]:\n\n\n # hello_world_operator = PythonOperator(dag=dag, task_id=\"hello_world\", python_callable=hello_world, op_args=[1, 2, 3])\n\n if use_virtualenv:\n oper = PythonVirtualenvOperator(\n dag=dag, task_id=name, requirements=[\"dill\"],\n python_callable=wheres_my_args_dude, op_args=args, use_dill=True)\n else:\n oper = PythonOperator(dag=dag, task_id=name, python_callable=wheres_my_args_dude)\n\n return oper\n\n\n\n\nif __name__ == \"__main__\":\n # Я знаю, что сейчас 2k22 год, и надо работать через контексты и декораторы. Это специально для простоты отладки.\n dag = DAG(\n dag_id='simple_python_dag_2',\n schedule_interval=\"@daily\",\n start_date=pendulum.datetime(2021, 1, 1, tz=\"UTC\"),\n catchup=False,\n tags=['example'],\n )\n\n venv_oper_1 = create_venv_operator(\"oper1\", dag, [1, 2, 3])\n venv_oper_2 = create_venv_operator(\"oper2\", dag, [4, 5, 6])\n\n venv_oper_1 >> venv_oper_2\n\n dag.clear()\n # лол, чтобы брякпоинты заработали (и чтобы принты заработали), надо запускать с новой датой...\n dag.run(start_date=pendulum.datetime(2021, 5, 1, tz=\"Europe/Moscow\"),\n end_date=pendulum.datetime(2021, 5, 2, tz=\"Europe/Moscow\"),\n executor=DebugExecutor(), run_at_least_once=True)\n","repo_name":"Felix-neko/airflow_sandbox","sub_path":"airflow_sandbox/dags/simple_python_dag_2.py","file_name":"simple_python_dag_2.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40832151598","text":"import numpy as np\nfrom glob import glob\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom pynextsim.nextsim_bin import NextsimBin\nfrom age_func import *\n\n#seasonal cycle of ice type and ice age (detectable and volumetric)\ninpath = '/input_obs_data/polona/FRASIL/age_datamor_long/'\noutpath = 'data/'\noutpath_plots = 'plots/'\n\n#get all daily files\nfl = sorted(glob(inpath+'field*T000000Z.bin'))\n\ndates = []\nvolume_myi = []\nvolume_age0 = []\nvolume_age1 = []\nvolume_age2 = []\nvolume_age3 = []\nvolume_age4 = []\nvolume_age0v = []\nvolume_age1v = []\nvolume_age2v = []\nvolume_age3v = []\nvolume_age4v = []\n\nfor fn in fl:\n print(fn)\n \n #get date\n tmp = fn.split('_')[-1].split('T')[0]\n date = datetime.strptime(tmp, \"%Y%m%d\")\n year = str(date.year)\n if int(year)<2014: continue\n\n dates.append(date)\n\n #get data\n nb = NextsimBin(fn)\n ea = nb.get_var('Element_area')/1e6 #from m^2 to km^2\n fyi = nb.get_var('Fyi_fraction')\n sic = nb.get_var('Concentration')\n sicthin = nb.get_var('Concentration_thin_ice')\n sit = nb.get_var('Thickness')/1000 #from m to km\n siad = nb.get_var('Age_d')/60/60/24/365 #from seconds to years\n sia = nb.get_var('Age')/60/60/24/365\n \n #make a sum of volume over the whole model domain\n #myi volume\n #myi = sic-sicthin-fyi #this does not work, but gives similar results\n myi = 1-fyi\n vmyi = np.sum(myi*sit*ea)/1e3\n #print(vmyi)\n #total_vol = np.sum(sit*ea)/1e3\n #print(total_vol)\n volume_myi.append(vmyi)\n \n #reclassify the age_d into myi\n #MYI: age>timedelta(today,15. Sept)\n if (date.month>9) | ((date.month==9) & (date.day>15)):\n pyr=date.year\n else:\n pyr=date.year-1\n diff = (date-datetime(pyr,9,15)).total_seconds()/60/60/24/356\n #print(diff)\n \n vmyi = np.sum(np.ma.array(sit*ea,mask=siaddiff) )/1e3 #FYI\n vage1 = np.sum(np.ma.array(sit*ea,mask=(siaddiff+1)))/1e3 #SYI\n vage2 = np.sum(np.ma.array(sit*ea,mask=(siaddiff+2)))/1e3 #3YI\n vage3 = np.sum(np.ma.array(sit*ea,mask=(siaddiff+3)))/1e3 #4YI\n vage4 = np.sum(np.ma.array(sit*ea,mask=siaddiff) )/1e3\n vage1v = np.sum(np.ma.array(sit*ea,mask=(siadiff+1)))/1e3\n vage2v = np.sum(np.ma.array(sit*ea,mask=(siadiff+2)))/1e3\n vage3v = np.sum(np.ma.array(sit*ea,mask=(siadiff+3)))/1e3\n vage4v = np.sum(np.ma.array(sit*ea,mask=sia List[str]:\n return [text.strip() for text in self.answers_spans.spans]\n\n def as_prompt(self, include_answer=True):\n prompt = self.passage.strip() + \" \" + self.question.strip()\n prompt += \"\\nAnswer:\"\n if include_answer:\n answer = self.get_answers()[0]\n prompt = f\"{prompt} {answer}\\n\\n\"\n return prompt\n\n\nclass DropData(BaseModel):\n samples: List[DropSample]\n\n @classmethod\n def load_from_huggingface(cls, path: str = \"drop\", split: str = \"validation\"):\n data = load_dataset(path, split=split)\n samples = [DropSample(**raw) for raw in tqdm(data, desc=str((path, split)))]\n return cls(samples=samples)\n\n @classmethod\n def load(cls, path: str):\n with open(path) as f:\n samples = [DropSample(**json.loads(line)) for line in f]\n return cls(samples=samples)\n\n def save(self, path: str):\n Path(path).parent.mkdir(exist_ok=True, parents=True)\n with open(path, \"w\") as f:\n for s in self.samples:\n print(s.json(), file=f)\n\n def analyze(self):\n info = dict(samples=len(self.samples))\n print(json.dumps(info, indent=2))\n\n def train_test_split(self, num_train: int, seed: int = 0):\n random.seed(seed)\n samples_train = random.sample(self.samples, k=num_train)\n texts_train = set(s.passage for s in samples_train)\n samples_test = [s for s in self.samples if s.passage not in texts_train]\n print(dict(samples_train=len(samples_train), samples_test=len(samples_test)))\n return DropData(samples=samples_train), DropData(samples=samples_test)\n\n\ndef test_data(path_out: str = \"data/drop.json\"):\n data = DropData.load_from_huggingface()\n data.analyze()\n data.save(path_out)\n\n\ndef gen_prompt(data: DropData, k=-1):\n prompt = \"\"\n if k == -1:\n k = len(data.samples)\n for sample in data.samples[:k]:\n prompt += sample.as_prompt()\n return prompt\n\n\ndef filter_dataset(data: DropData) -> DropData:\n samples = []\n for s in data.samples:\n spans = s.get_answers()\n if len(set(spans)) == 1:\n samples.append(s)\n\n print(dict(orig=len(data.samples), after_filter=len(samples)))\n return DropData(samples=samples)\n\n\ndef evaluate(model: EvalModel, data: DropData, ntrain: int) -> dict:\n data = filter_dataset(data)\n data_train, data_test = data.train_test_split(num_train=ntrain)\n is_correct = []\n score = 0\n\n progress = tqdm(data_test.samples)\n sample: DropSample\n for sample in progress:\n # get prompt and make sure it fits\n k = int(ntrain)\n prompt_end = sample.as_prompt(include_answer=False)\n train_prompt = gen_prompt(data_train, k)\n prompt = train_prompt + prompt_end\n\n while not model.check_valid_length(prompt) and k > 0:\n k -= 1\n train_prompt = gen_prompt(data_train, k)\n prompt = train_prompt + prompt_end\n\n label = sample.get_answers()[0]\n pred = model.run(prompt).strip()\n is_correct.append(pred.startswith(label))\n score = sum(is_correct) / len(is_correct)\n progress.set_postfix(score=score)\n print(dict(prompt=prompt, label=label, pred=pred))\n\n return dict(score=score)\n\n\ndef main(data_dir: str = \"drop\", ntrain: int = 3, **kwargs):\n model = select_model(max_input_length=2048, max_output_length=8, **kwargs)\n print(locals())\n\n all_results = []\n data = DropData.load_from_huggingface()\n result = evaluate(model, data, ntrain=ntrain)\n print(result)\n return result[\"score\"]\n\n\n\"\"\"\npython main.py drop --model_name seq_to_seq --model_path google/flan-t5-xl\n{'score': 0.5632458233890215}\n\npython main.py drop --model_name llama --model_path eachadea/vicuna-13b --load_8bit\n{'score': 0.3291964996022275}\n\npython main.py drop --model_name llama --model_path chavinlo/alpaca-native\n{'score': 0.2638027048528242}\n\npython main.py drop --model_name llama --model_path decapoda-research/llama-13b-hf --load_8bit\n{'score': 0.35338106603023073}\n\npython main.py drop --model_name llama --model_path TheBloke/koala-13B-HF --load_8bit\n{'score': 0.28353221957040575}\n\npython main.py drop --model_name llama --model_path decapoda-research/llama-7b-hf\n{'score': 0.27653142402545744}\n\npython main.py drop --model_name chatglm --model_path THUDM/chatglm-6b\n{'score': 0.44200477326968973}\n\npython main.py drop --model_name seq_to_seq --model_path declare-lab/flan-alpaca-gpt4-xl\n{'score': 0.28496420047732696}\n\npython main.py drop --model_name seq_to_seq --model_path google/flan-t5-xl --lora_path declare-lab/flan-alpaca-xl-lora\n{'score': 0.36945107398568017}\n\npython main.py drop --model_name llama --model_path TheBloke/wizardLM-7B-HF\n{'score': 0.2587112171837709}\n\npython main.py drop --model_name seq_to_seq --model_path google/flan-t5-xxl --load_8bit\n{'score': 0.6728719172633254}\n\npython main.py drop --model_name causal --model_path Salesforce/codegen-6B-mono\n{'score': 0.1280827366746221}\n\npython main.py drop --model_name seq_to_seq --model_path bigscience/T0pp --load_8bit\n{'score': 0.016070007955449484}\n\npython main.py drop --model_name llama --model_path TheBloke/OpenAssistant-SFT-7-Llama-30B-HF --load_8bit\n{'score': 0.46046141607000796}\n\npython main.py drop --model_name causal --model_path stabilityai/stablelm-tuned-alpha-7b\n{'score': 0.1271280827366746}\n\npython main.py drop --model_name causal --model_path bigscience/bloomz-7b1\n{'score': 0.23182179793158314}\n\npython main.py drop --model_name llama --model_path huggyllama/llama-30b --load_8bit\n{'score': 0.45425616547334924}\n\npython main.py drop --model_name causal --model_path facebook/opt-iml-30b --load_8bit\n{'score': 0.4758949880668258}\n\npython main.py drop --model_name seq_to_seq --model_path declare-lab/flan-alpaca-xxl --load_8bit\n{'score': 0.6233890214797136}\n\n\"\"\"\n\n\nif __name__ == \"__main__\":\n Fire()\n","repo_name":"declare-lab/instruct-eval","sub_path":"drop.py","file_name":"drop.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","stars":370,"dataset":"github-code","pt":"52"} +{"seq_id":"4637313812","text":"import FWCore.ParameterSet.Config as cms \n#PF2PAT\nfrom PhysicsTools.PatAlgos.patSequences_cff import *\n\n\nacceptedElectrons = cms.EDFilter(\"PATElectronSelector\",\n src = cms.InputTag(\"selectedPatElectronsPFlow\"),\n cut = cms.string(\"pt > 10 && abs(eta) < 3.0\"),\n #cut = cms.string(\"pt > 20 && abs(eta) < 2.5\"),\n #cut = cms.string(\"pt > 20 && abs(eta) < 2.5 && ecalDrivenSeed\")\n filter = cms.bool(False),\n)\nallConversions = cms.EDProducer(\"PATConversionProducer\",\n electronSource = cms.InputTag(\"acceptedElectrons\")\n # this should be your last selected electron collection name\n )\n\nacceptedGsfElectrons = cms.EDFilter(\"PATElectronSelector\",\n src = cms.InputTag(\"selectedPatElectrons\"),\n cut = cms.string(\"pt > 10 && abs(eta) < 3.0\"),\n #cut = cms.string(\"pt > 20 && abs(eta) < 2.5\"),\n #cut = cms.string(\"pt > 20 && abs(eta) < 2.5 && ecalDrivenSeed\")\n filter = cms.bool(False),\n)\n\nacceptedElectronFilter = cms.EDFilter(\"CandViewCountFilter\",\n src = cms.InputTag('acceptedElectrons'),\n minNumber = cms.uint32(1)\n)\nfrom TerraNova5322.CommonTools.eleSelectorPSet_cff import eleSelectorPSet\nMETsrcElectrons = cms.EDProducer(\n \"KyElectronSelector\",\n version = cms.untracked.int32( 13 ),# -1(no cut), 0(check cut, isocut pset), 1(WptCut) 13(medium pt 30) 14(medium pt 15)\n cut = cms.vstring(\"pt\",\"eta\",\"EcalGapCut\"),\n electronLabel = cms.InputTag(\"selectedPatElectronsPFlow\"),\n beamSpotLabel = cms.InputTag(\"offlineBeamSpot\"),\n vertexLabel = cms.InputTag('offlinePrimaryVertices'),\n rhoIsoLabel = cms.InputTag('kt6PFJets','rho'),\n conversionsInputTag = cms.InputTag(\"allConversions\"),\n eleIdSelector = eleSelectorPSet,\n saveTree = cms.untracked.bool(False),\n )\nacceptedMuons = cms.EDFilter(\"PATMuonSelector\",\n src = cms.InputTag(\"selectedPatMuonsPFlow\"),\n cut =cms.string(\"pt > 10 && abs(eta) < 2.5\"),\n #cut =cms.string(\"pt > 15 && abs(eta) < 2.5\"),\n filter = cms.bool(False),\n)\n\nacceptedMuonsFilter = cms.EDFilter(\"CandViewCountFilter\",\n src = cms.InputTag('acceptedMuons'),\n minNumber = cms.uint32(1)\n)\n\nfrom TerraNova5322.CommonTools.muonSelectorPSet_cff import muonSelectorPSet\nfrom TerraNova5322.CommonTools.muonIsoSelectorPSet_cff import muonIsoSelectorPSet\nMETsrcMuons = cms.EDProducer(\"KyMuonSelector\",\n # 6(pt>10, tight, for DiMu) 7(pt>27, tight for SingleMu)\n version = cms.untracked.int32( 6 ),# -1(no cut) 0(check cut, isocut pset)\n cut = cms.vstring(\"pt\"),\n isocut = cms.vstring(),\n muonLabel = cms.InputTag(\"selectedPatMuonsPFlow\"),\n beamSpotLabel = cms.InputTag(\"offlineBeamSpot\"),\n muonIdSelector = muonSelectorPSet,\n muonIsoSelector = muonIsoSelectorPSet,\n saveTree = cms.untracked.bool(False),\n )\nacceptedTaus = cms.EDFilter(\"PATTauSelector\",\n src = cms.InputTag(\"selectedPatTausPFlow\"),\n cut = cms.string(\"pt > 20 && abs(eta) < 2.3 && tauID('decayModeFinding')>0.5 && tauID('byMediumCombinedIsolationDeltaBetaCorr3Hits')>0.5\"),\n #cut = cms.string(\"pt > 10 && abs(eta) < 3.0\"),\n# filter = cms.bool(False),\n)\nMETsrcTaus = cms.EDFilter(\"PATTauSelector\",\n src = cms.InputTag(\"selectedPatTausPFlow\"),\n cut = cms.string(\"pt > 20 && abs(eta) < 2.3 && tauID('decayModeFinding')>0.5 && tauID('byMediumCombinedIsolationDeltaBetaCorr3Hits')>0.5\"),\n #cut = cms.string(\"pt > 10 && abs(eta) < 3.0\"),\n# filter = cms.bool(False),\n)\n\n\npatLeptonFilter = cms.EDFilter(\"MultiLeptonCountFilter\",\n leptons = cms.untracked.VInputTag('acceptedMuons','acceptedElectrons'),\n minCount = cms.untracked.uint32(0)\n)\npatMuEleTauFilter = cms.EDFilter(\"MultiObjectCountFilter\",\n leptons = cms.untracked.VInputTag('acceptedMuons','acceptedElectrons','acceptedTaus'),\n minCount = cms.untracked.uint32(1)\n)\n\n#Electron ID\n#from RecoEgamma.ElectronIdentification.cutsInCategoriesElectronIdentificationV06_cfi import *\n#from ElectroWeakAnalysis.WENu.simpleEleIdSequence_cff import *\n\n#patElectrons.electronIDSources = cms.PSet(\n# #CiC\n# eidVeryLooseMC = cms.InputTag(\"eidVeryLooseMC\"),\n# eidLooseMC = cms.InputTag(\"eidLooseMC\"),\n# eidMediumMC = cms.InputTag(\"eidMediumMC\"),\n# eidTightMC = cms.InputTag(\"eidTightMC\"),\n# eidSuperTightMC = cms.InputTag(\"eidSuperTightMC\"),\n# eidHyperTight1MC = cms.InputTag(\"eidHyperTight1MC\"),\n# #VBTF 2010\n# simpleEleId95relIso= cms.InputTag(\"simpleEleId95relIso\"),\n# simpleEleId90relIso= cms.InputTag(\"simpleEleId90relIso\"),\n# simpleEleId85relIso= cms.InputTag(\"simpleEleId85relIso\"),\n# simpleEleId80relIso= cms.InputTag(\"simpleEleId80relIso\"),\n# simpleEleId70relIso= cms.InputTag(\"simpleEleId70relIso\"),\n# simpleEleId60relIso= cms.InputTag(\"simpleEleId60relIso\"),\n#)\n\n#patElectronIDs = cms.Sequence(process.simpleEleIdSequence)\n#eidCiCSequence = cms.Sequence(\n# process.eidVeryLooseMC * process.eidLooseMC * process.eidMediumMC\n# * process.eidTightMC * process.eidSuperTightMC * process.eidHyperTight1MC\n#)\n\n\n##################################################################\nfrom TerraNova5322.NtupleMaker.wHLTfilter_cff import *\n\nnEventsTotal = cms.EDProducer(\"EventCountProducer\")\nnEventsNoscrap = cms.EDProducer(\"EventCountProducer\")\nnEventsHBHE = cms.EDProducer(\"EventCountProducer\")\n#EventsClean = cms.EDProducer(\"EventCountProducer\")\nnEventsHLT = cms.EDProducer(\"EventCountProducer\")\nnEventsFiltered = cms.EDProducer(\"EventCountProducer\")\n\n\n","repo_name":"d4space/TerraNova5322","sub_path":"NtupleMaker/python/pf2pat_template_MC_cfg.py","file_name":"pf2pat_template_MC_cfg.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9029239061","text":"import matplotlib.pyplot as plt\nimport csv\nimport json\n\ndef currencyFormatter(currencyValue):\n \"\"\"\n This function takes a decimal value and \n normalizes it to be a string representing currency.\n \"\"\"\n return \"${:,.2f}\".format(currencyValue)\n\ncsvFile = 'avocado.csv'\nbuckets = 20\nselectedRegion = 'TotalUS'\nselectedtype = 'organic'\n\n\nf = open(csvFile, 'r')\nreader = csv.DictReader(f)\npriceList=[]\nfor row in reader:\n region =row['region']\n type_ = row['type']\n price = float(row['AveragePrice'])\n if region == selectedRegion and type_ == selectedtype:\n priceList.append(price)\n \n# The following paragraph creates a tuple list of price ranges\nmaxPrice = max(priceList)\nminPrice = min(priceList)\npriceList=[]\nrangeLow = 1.15\nrangeHigh= 1.15\nfor i in range(buckets):\n if not rangeLow>maxPrice:\n separation = (maxPrice-minPrice)/buckets\n rangeHigh+= separation\n rangeHigh=round(rangeHigh, 2) # round up due to floating-point numbers calculation\n priceRange=(rangeLow, rangeHigh)\n priceList.append(priceRange)\n rangeLow+= separation\n rangeLow= round(rangeLow, 2)\nf.close()\n\ndictRegion={}\ndictAllData = {}\nf = open(csvFile, 'r')\nreader = csv.DictReader(f)\nsoldDictTotal={}# incluses 2015 - 2018\nsoldDictNum ={}\nfor row in reader:\n price = float(row['AveragePrice'])\n numSold=float(row['Total Volume'])\n type_ = row['type']\n region =row['region']\n date=row['Date']\n for low, high in priceList:\n if low<=price and price= 0:\n return self.eMBB_User_delay_requirement_revenue\n else:\n return (processing_delay_requirement - max(achieved_local_processing_delay,achieved_offload_processing_delay))\n \n def achieved_URLLC_User_reliability_requirement_revenue_or_penalty(self,URLLC_User):\n reliability_requirement = URLLC_User.QOS_requirement_for_transmission.max_allowable_reliability\n achieved_reliability = self.achieved_total_rate_URLLC_users\n\n if ((achieved_reliability-reliability_requirement)/self.num_arriving_URLLC_packets) >= 0:\n return self.eMBB_User_delay_requirement_revenue\n else:\n return ((achieved_reliability-reliability_requirement)/self.num_arriving_URLLC_packets)\n \n #def perform_timeslot_sequential_events(self,eMBB_Users,URLLC_Users,communication_channel):\n\n def set_properties(self):\n self.associated_users = []\n self.associated_URLLC_users = []\n self.associated_eMBB_users = []\n self.system_state_space = []\n self.num_arriving_URLLC_packets = 0\n self.eMBB_Users_packet_queue = []\n self.URLLC_Users_packet_queue = []\n self.achieved_total_system_energy_consumption = 0\n self.achieved_total_system_processing_delay = 0\n self.achieved_URLLC_reliability = 0\n self.achieved_total_rate_URLLC_users = 0\n self.achieved_total_rate_eMBB_users = 0\n self.achieved_system_energy_efficiency = 0\n self.achieved_system_reward = 0\n self.eMBB_User_delay_requirement_revenue = 5\n self.URLLC_User_reliability_requirement_revenue = 5\n self.clock_frequency = 2\n self.work_load = 0\n self.eMBB_UEs = []\n self.URLLC_UEs = []\n self.achieved_users_energy_consumption = 0\n self.achieved_users_channel_rate = 0\n self.fairness_index = 0\n self.energy_efficiency_rewards = 0\n self.energy_rewards = 0\n self.throughput_rewards = 0\n self.delay_rewards = 0\n\n def calculate_fairness(self,eMBB_Users):\n number_of_users = len(eMBB_Users)\n sum_throughputs = 0\n for eMBB_User in eMBB_Users:\n sum_throughputs += eMBB_User.achieved_channel_rate\n\n square_sum_throughput = math.pow(sum_throughputs,2)\n sum_square_throughput = self.square_sum(eMBB_Users)\n fairness_index = 0\n if sum_square_throughput > 0:\n fairness_index = square_sum_throughput/(number_of_users*sum_square_throughput)\n\n return fairness_index\n\n def square_sum(self,eMBB_Users):\n sum = 0\n for eMBB_User in eMBB_Users:\n sum+=math.pow(eMBB_User.achieved_channel_rate,2)\n\n return sum\n \n def calculate_fairness_(self,eMBB_Users, communication_channel):\n sum_square_error = 0\n for eMBB_user in eMBB_Users:\n square_error = math.pow(abs(len(eMBB_user.allocated_RBs)-communication_channel.num_of_RBs_per_User),2)\n sum_square_error+=square_error\n\n sum_square_error = math.pow(abs((len(eMBB_Users[0].allocated_RBs))-(len(eMBB_Users[1].allocated_RBs))),2)\n if sum_square_error == 0:\n sum_square_error = 1\n \n return 1/sum_square_error\n \n #def calculate_throughput_variance(self,eMBB_Users):\n #mean = \n\n \n\n\n\n\n\n\n\n","repo_name":"francmeister/Masters-Research-Project","sub_path":"Multi-User-MEC-System/Network_Env/SBS.py","file_name":"SBS.py","file_ext":"py","file_size_in_byte":11206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13864909582","text":"import streamlit as st\nfrom pygame import mixer\n\nst.set_page_config(page_title=\"Interface de gestion de prédication\", layout=\"wide\")\n\n\ntitle = \"Interface de gestion de prédication\"\nst.title(title)\nst.write(\"Bienvenue sur l'interface de gestion des prédications en ligne de l'ACY Port Bouet 2\")\nst.markdown(\"##\")\n# with st.container():\n# col1, col2,col3,col4 = st.columns((2,0.5,0.5,0.5))\n# with col3:\n# st.markdown(\"***Choose your genre:***\")\n# genre = st.radio(\n# \"\",\n# \"Test 2\", index=[1, 2])\n# with col1:\n# st.markdown(\"***Choose features to customize:***\")\n# start_year, end_year = st.slider(\n# 'Select the year range',\n# 1990, 2019, (2015, 2019)\n# )\n# acousticness = st.slider(\n# 'Acousticness',\n# 0.0, 1.0, 0.5)\n# danceability = st.slider(\n# 'Danceability',\n# 0.0, 1.0, 0.5)\n# energy = st.slider(\n# 'Energy',\n# 0.0, 1.0, 0.5)\n# instrumentalness = st.slider(\n# 'Instrumentalness',\n# 0.0, 1.0, 0.0)\n# valence = st.slider(\n# 'Valence',\n# 0.0, 1.0, 0.45)\n# tempo = st.slider(\n# 'Tempo',\n# 0.0, 244.0, 118.0)\n\n\n\n# from google.oauth2 import service_account\n# from google.cloud import storage\n\n# Create API client.\n# credentials = service_account.Credentials.from_service_account_info(\n# st.secrets[\"gcp_service_account\"]\n# )\n# client = storage.Client(credentials=credentials)\n\nmixer.init()\n\nmusic = st.file_uploader(\"Ajouter une prédication ...\")\n\ntry : \n mixer.music.load(music)\nexcept Exception : \n st.write(\"Ajouter une prédication svp ...\")\n\nif st.button(\"Play\") : \n mixer.music.play()\n\nif st.button(\"Pause\") : \n mixer.music.pause()\n \nif st.button(\"Stop\") : \n mixer.music.stop()\n\n\n","repo_name":"amaelDago/online-sermons-reading","sub_path":"api/app.py","file_name":"app.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":"29236107486","text":"import uuid\nfrom datetime import datetime\n\nimport pytest\nfrom app.domain import EventStatus, EventType\nfrom app.repositories.exceptions import (\n EventForeignKeyException,\n EventValidationErrorException,\n)\nfrom app.repositories.sport_repository import SportRepository\nfrom app.use_cases.event_use_cases import (\n CreateEventUsecase,\n ListEventUsecase,\n UpdateEventUsecase,\n)\nfrom slugify import slugify\n\n\nclass TestListEventsUsecase:\n def test_list_event(self, app, create_event):\n # Give\n use_case = ListEventUsecase()\n # Act\n events = use_case.execute()\n # Them\n assert len(events) == 5\n\n def test_get_events_by_slug(self, app, create_event):\n # Give\n filters = {\"slug\": create_event.slug}\n use_case = ListEventUsecase()\n # Act\n events = use_case.execute(filters)\n # Them\n assert events != None\n assert len(events) == 1\n\n def test_get_events_by_slug_and_active(self, app, create_event):\n # Give\n filters = {\"slug\": create_event.slug, \"active\": create_event.active}\n use_case = ListEventUsecase()\n # Act\n events = use_case.execute(filters)\n # Them\n assert events != None\n assert len(events) == 1\n\n def test_get_events_by_slug_and_active_false(self, app, create_event):\n # Give\n filters = {\"slug\": create_event.slug, \"active\": False}\n use_case = ListEventUsecase()\n # Act\n sports = use_case.execute(filters)\n # Them\n assert sports != None\n assert len(sports) == 0\n\n\nclass TestCreateEventUsecase:\n def test_create_event(self, app, create_sport):\n # Give\n use_case = CreateEventUsecase()\n name = \"Event Name\"\n data = {\n \"sport_uuid\": create_sport.uuid,\n \"name\": name,\n \"slug\": slugify(name),\n \"active\": True,\n \"event_type\": EventType.preplay,\n \"status\": EventStatus.pending,\n \"scheduled_at\": datetime.now(),\n \"start_at\": datetime.now(),\n }\n # Act\n event = use_case.execute(data)\n # Them\n assert event != None\n\n def test_create_event_without_slug(self, app, create_sport):\n # Give\n use_case = CreateEventUsecase()\n data = {\"sport_uuid\": create_sport.uuid, \"active\": True}\n # Act\n # Them\n with pytest.raises(EventValidationErrorException):\n use_case.execute(data)\n\n def test_create_event_without_nonexistent_sport(self, app, create_sport):\n # Give\n use_case = CreateEventUsecase()\n name = \"Event Name\"\n data = {\n \"sport_uuid\": uuid.uuid4(),\n \"name\": name,\n \"slug\": slugify(name),\n \"active\": True,\n \"event_type\": EventType.preplay,\n \"status\": EventStatus.pending,\n \"scheduled_at\": datetime.now(),\n \"start_at\": datetime.now(),\n }\n # Act\n # Them\n with pytest.raises(EventForeignKeyException):\n use_case.execute(data)\n\n\nclass TestInactivateEventUseCase:\n def test_inactivate_all_events(self, app, create_event):\n # Give\n sport = SportRepository().get_sport_by_id(create_event.sport_id)\n data = {\n \"sport_uuid\": sport.uuid,\n \"name\": \"New Event\",\n \"active\": False,\n \"event_type\": EventType.preplay.value,\n \"status\": EventStatus.pending.value,\n \"scheduled_at\": datetime.utcnow().isoformat(),\n \"start_at\": datetime.utcnow().isoformat(),\n }\n # Act\n UpdateEventUsecase().execute(create_event.uuid, data)\n # Them\n sport = SportRepository().get_sport_by_id(create_event.sport_id)\n assert sport.active == False\n","repo_name":"HandBoy/sport-book","sub_path":"app/tests/use_cases/test_event_use_cases.py","file_name":"test_event_use_cases.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24894216327","text":"\"\"\"\r\n1. Kare mi diye baksın bilinmeyen sayısı ile denklem sayısı aynı olmalı.\r\n2. x = |delta(x)| / |A| , y = |delta(y)| / |A|\r\n\"\"\"\r\nimport numpy as np\r\nfrom numpy import linalg\r\n\r\ndef yazdir(matris, c):\r\n for i in range(len(matris)):\r\n print(matris[i], \" |\", c[i])\r\n\r\nA = []\r\nB = []\r\nC = []\r\n\r\ndenklem = int(input(\"Denklem sayisi :\"))\r\nderece = int(input(\"Değişken sayisi :\"))\r\n\r\nif denklem != derece: # Kare mi kontrolü ?\r\n print(\"Bu denklemi Cremer ile çözemezsiniz. Bilinmeyen sayısı ile denklem sayısı aynı olmalı.\")\r\n exit()\r\n\r\nfor i in range(denklem): # girdiler alınıyor\r\n m_satir =[]\r\n print(\"{}. denklemin katsayilarini gir.\".format(i + 1))\r\n for j in range(derece):\r\n deger = float(input(\"{}. değer :\".format(j+1)))\r\n m_satir.append(deger)\r\n\r\n A.append(m_satir) # A = ana matris\r\n sonuc = float(input(\"{}. esitlik Sonuç :\".format(i+1)))\r\n B.append(sonuc) # B sonuç matrisi\r\n\r\n\"\"\"A = [[3.6, 2.4, -1.8],\r\n [4.2, -5.8, 2.1],\r\n [0.8, 3.5, 6.5]]\r\n\r\nB = [6.3, 7.5, 3.7]\"\"\"\r\n\r\nC =np.zeros( (denklem, derece)) # A nın bir kopyası olan C matrisi oluşturuluyor.\r\nfor i in range(denklem):\r\n for j in range(derece):\r\n C[i][j]=A[i][j]\r\n\r\nyazdir(A,B)\r\nprint()\r\n\r\nX = []\r\nfor i in range(0, len(B)):\r\n for j in range(0, len(B)):\r\n C[j][i] = B[j] # B yi araya sok\r\n if i > 0:\r\n C[j][i - 1] = A[j][i - 1] # Bozulan Bir önceki sütunu düzelt\r\n print(i, \". sütun B matrisi ile değiştirildi.\")\r\n yazdir(C, B)\r\n X.append(round(linalg.det(C)/linalg.det(A), 2)) #Formülü uygula determinantları böl sonucu bul\r\n print(\"det(C) / det(A) = \", linalg.det(C),\"/\", linalg.det(A),\"=\", X[i])\r\n print()\r\n\r\nfor i in X:\r\n print(\"{}.kök = {} \".format(X.index(i), i))\r\n","repo_name":"yunusemre002/YTU-Lessons","sub_path":"Numarical_Analysis_Methods/3_0_Cramer.py","file_name":"3_0_Cramer.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34446301325","text":"import numpy as np\nimport tensorflow as tf\nfrom pygsp.graphs.nngraphs.spherehealpix import SphereHealpix\nfrom . import healpy_layers_customized as hp_nn\n\n\nclass HealpyGCNN:\n \"\"\"\n A graph convolutional network.\n NOTE: when using subclassing of tf.keras.Models, summary() etc. are currently not available (TF <= 2.5), therefore\n we use the Keras functional API here.\n \"\"\"\n def __init__(self, which, params, index_dict):\n \"\"\"\n Initializes a graph convolutional neural network using the healpy pixelization scheme\n :param which: submodel, must be one of \"flux_fractions\" or \"histograms\"\n :param params: parameter dictionary\n :param index_dict: dictionary containing 'indexes', 'indexes_extended', and 'ind_holes_to_ex' for the ROI at\n each nside hierarchy level\n \"\"\"\n super(HealpyGCNN, self).__init__()\n\n self.which = which\n self._p = params\n self._inds = index_dict[\"indexes\"]\n self._inds_ex = index_dict[\"indexes_extended\"]\n self._ind_holes_to_ex = index_dict[\"ind_holes_to_ex\"]\n\n if which == \"flux_fractions\":\n dim_out = self._p.mod[\"n_models\"]\n if self._p.nn.ff[\"alea_covar\"]:\n dim_out += dim_out * (dim_out + 1) // 2 # aleatoric uncertainty covariance matrix\n elif self._p.nn.ff[\"alea_var\"]:\n dim_out += dim_out # aleatoric uncertainty variances\n elif which == \"histograms\":\n dim_out = self._p.nn[\"label_shape\"][1]\n else:\n raise NotImplementedError\n\n self.dim_out = dim_out\n self.dim_out_flat = np.product(dim_out)\n\n def compute_output(self, input_tensor, tau=None):\n \"\"\"\n Iteratively define the layers of the neural network.\n :param input_tensor: input tensor, can be tf.keras.Inputs\n :param tau: quantile levels for Earth Mover's pinball loss (only concerns SCD histograms)\n :return output dictionary, preprocessed input (can be reused)\n \"\"\"\n pa = self._p.nn.arch\n\n need_concat = False # flag indicating if 2nd(+) channel (which is NOT preprocessed!) needs to be concatenated\n\n # If t has no channel dimension: add dimension\n if len(input_tensor.shape) == 2:\n first_channel = tf.expand_dims(input_tensor, -1)\n else:\n # If 2nd channel: split up raw input (1st channel) as no preprocessing needs to be done for the rest\n if input_tensor.shape[2] > 1:\n first_channel, other_channels = input_tensor[:, :, :1], input_tensor[:, :, 1:]\n need_concat = True\n else:\n first_channel = input_tensor\n\n # Get total counts\n tot_counts = tf.reduce_sum(first_channel, axis=1, keepdims=True)\n\n # Relative counts (i.e., divide by total number of counts in the map)?\n rel_counts = self._p.nn.hist[\"rel_counts\"] if self.which == \"histograms\" else self._p.nn.ff[\"rel_counts\"]\n if rel_counts:\n first_channel = first_channel / tot_counts\n\n preprocessed_input = first_channel # store in a variable that will be returned (input for residual calculation)\n\n # Concatenate the other channels again\n if need_concat:\n t = tf.concat([preprocessed_input, other_channels], axis=2)\n else:\n t = preprocessed_input\n\n # Graph-convolutional blocks\n for il in range(len(pa[\"F\"])):\n\n # Get variables at current resolution\n current_nside = self._p.nn.arch[\"nsides\"][il]\n next_nside = self._p.nn.arch[\"nsides\"][il + 1]\n assert next_nside >= 1, \"NN is trying to reduce the resolution below nside=1! Aborting...\"\n current_indices = self._inds[il]\n\n # Chebyshev or monomial convolution?\n conv_layer = hp_nn.HealpyChebyshev if pa[\"conv\"] == \"chebyshev5\" else hp_nn.HealpyMonomial\n conv_layer_type = \"CHEBY\" if pa[\"conv\"] == \"chebyshev5\" else \"MONO\"\n\n # ResNet block\n if pa[\"is_resnet\"][il]:\n f_in = 1 if il == 0 else pa[\"F\"][il - 1]\n assert pa[\"F\"][il] == f_in, \\\n \"Changing the number of filters with a ResNet block is currently not supported!\"\n layer_spec = hp_nn.Healpy_ResidualLayer(layer_type=conv_layer_type,\n layer_kwargs={\"K\": pa[\"K\"][il], \"use_bias\": True,\n \"use_bn\": pa[\"batch_norm\"][il],\n \"activation\": pa[\"activation\"]})\n # Convolutional layer\n else:\n layer_spec = conv_layer(K=pa[\"K\"][il], Fout=pa[\"F\"][il], use_bias=True,\n use_bn=pa[\"batch_norm\"][il], activation=pa[\"activation\"])\n\n # for current_nside < 4: need to reduce n_neighbors and manually set kernel_width:\n if current_nside >= 4:\n n_neighbors = 8 # choose 8 neighbors for Healpix-discretized maps\n kwargs_d = {}\n elif current_nside == 2:\n n_neighbors = 3\n kwargs_d = {\"kernel_width\": 0.02500 * 16} # interpolated\n elif current_nside == 1:\n n_neighbors = 2\n kwargs_d = {\"kernel_width\": 0.02500 * 32} # interpolated\n else:\n raise NotImplementedError\n\n # Now, need to append the actual layer\n sphere = SphereHealpix(**kwargs_d, subdivisions=current_nside, indexes=current_indices, nest=True,\n k=n_neighbors, lap_type='normalized')\n current_laplacian = sphere.L\n t = layer_spec.get_layer(current_laplacian)(t)\n\n # Pooling layer\n if pa[\"pool\"] in [\"max\", \"avg\"]:\n # Determine the pooling factor\n pool_fac = int(np.log2(current_nside / next_nside))\n t = hp_nn.HealpyPoolWithHoles(p=pool_fac, i=il, inds=self._inds, inds_ex=self._inds_ex,\n ind_holes_to_ex=self._ind_holes_to_ex,\n pool_type=pa[\"pool\"].upper())(t)\n else:\n raise NotImplementedError\n\n # Flatten (or if convolutions don't go all the way down to a single pixel: average over the pixels\n t = tf.reduce_mean(t, axis=1, keepdims=False)\n\n # Append total counts?\n if pa[\"append_tot_counts\"] and rel_counts:\n t = tf.concat([t, tf.math.log(tf.squeeze(tot_counts, 1)) / 2.302], axis=1) # 2.3026 ~ log_e(10)\n\n # If Earth Mover's pinball loss: append tau at this point\n # We use the scaling proposed by\n # github.com/facebookresearch/SingleModelUncertainty/blob/master/aleatoric/regression/joint_estimation.py\n if tau is not None:\n t = tf.concat([t, (tau - 0.5) * 12], axis=1)\n\n # Fully-connected blocks\n # Note: batch norm is provided in a single array for conv. layers and FC layers!\n for il in range(len(pa[\"M\"])):\n t = hp_nn.FullyConnectedBlock(Fout=pa[\"M\"][il], use_bias=True,\n use_bn=pa['batch_norm'][len(pa[\"F\"]) + il],\n activation=pa[\"activation\"])(t)\n\n # Final fully-connected layer without activation\n t = tf.keras.layers.Dense(self.dim_out_flat, use_bias=False)(t)\n\n # For histograms: reshape to n_batch x n_bins x n_hist_templates\n if self.which == \"histograms\":\n t = tf.keras.layers.Lambda(lambda x: tf.reshape(x, [tf.shape(x)[0], *self.dim_out]))(t)\n\n # Final layer: will be taken care of when building the model\n out_dict = hp_nn.FinalLayer(which=self.which, params=self._p)(t)\n\n print(\"The resolution will be successively reduced from nside={:} to nside={:} during a forward pass.\".format(\n self._p.data[\"nside\"], self._p.nn.arch[\"nsides\"][-1]), flush=True)\n\n # Also store tau\n if tau is not None:\n out_dict[\"tau\"] = tau\n\n return out_dict, preprocessed_input\n","repo_name":"FloList/GCE_NN","sub_path":"GCE/nn/deepsphere/healpy_networks_customized.py","file_name":"healpy_networks_customized.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"28455337861","text":"from django.test import TestCase\nfrom .forms import OrderForm\n\n# form test on name input, for payment app in Orderform (Orderform / checkout)\n\nclass TestOrderform(TestCase):\n\n def test_can_create_an_item_with_a_name(self):\n \n form = OrderForm({'full_name' : 'Create Tests' , 'phone_number' : '12345678' , 'country' : 'country' , 'postcode' : '1234AA',\n 'town_or_city' : 'town', 'street_address1' : 'adres1' , 'street_address2' : 'adres2',\n 'county' : 'country'})\n \n self.assertTrue(form.is_valid())\n \n# form test on required fields in Orderform, for payment app (Orderform / checkout) \n \n def test_correct_message_for_missing_name(self):\n \n form = OrderForm({'form': ''})\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors['full_name'], [u'This field is required.'])","repo_name":"nikl881/food-delivery-app","sub_path":"checkout/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"52"} +{"seq_id":"11870191099","text":"from pitop.core.mixins import Recreatable, Stateful\nfrom pitop.pma.common.utils import Port\n\nfrom .ultrasonic_sensor_base import UltrasonicSensorMCU, UltrasonicSensorRPI\n\nvalid_analog_ports = [\"A1\", \"A3\"]\n\n\nclass UltrasonicSensor(Stateful, Recreatable):\n def __init__(\n self,\n port_name,\n queue_len=5,\n max_distance=3,\n threshold_distance=0.3,\n partial=False,\n name=\"ultrasonic\",\n ):\n assert port_name in Port\n self._pma_port = port_name\n self.name = name\n\n if port_name in valid_analog_ports:\n self.__ultrasonic_device = UltrasonicSensorMCU(\n port_name=port_name,\n queue_len=queue_len,\n max_distance=max_distance,\n threshold_distance=threshold_distance,\n partial=partial,\n name=name,\n )\n else:\n self.__ultrasonic_device = UltrasonicSensorRPI(\n port_name=port_name,\n queue_len=queue_len,\n max_distance=max_distance,\n threshold_distance=threshold_distance,\n partial=partial,\n name=name,\n )\n\n self._in_range_function = None\n self._out_of_range_function = None\n\n Stateful.__init__(self)\n Recreatable.__init__(\n self,\n {\n \"port_name\": port_name,\n \"queue_len\": queue_len,\n \"partial\": partial,\n \"name\": self.name,\n \"max_distance\": lambda: self.max_distance,\n \"threshold_distance\": lambda: self.threshold_distance,\n },\n )\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n @property\n def own_state(self):\n return {\n \"distance\": self.distance,\n }\n\n @property\n def max_distance(self):\n \"\"\"The maximum distance that the sensor will measure in meters.\n\n This value is specified in the constructor and is used to\n provide the scaling for the :attr:`~SmoothedInputDevice.value`\n attribute. When :attr:`distance` is equal to\n :attr:`max_distance`, :attr:`~SmoothedInputDevice.value` will be\n 1.\n \"\"\"\n return self.__ultrasonic_device.max_distance\n\n @max_distance.setter\n def max_distance(self, value):\n self.__ultrasonic_device.max_distance = value\n\n @property\n def threshold_distance(self):\n \"\"\"\n The distance, measured in meters, that will trigger the\n :attr:`when_in_range` and :attr:`when_out_of_range` events when\n crossed. This is simply a meter-scaled variant of the usual\n :attr:`~SmoothedInputDevice.threshold` attribute.\n \"\"\"\n return self.__ultrasonic_device.threshold_distance\n\n @threshold_distance.setter\n def threshold_distance(self, value):\n self.__ultrasonic_device.threshold_distance = value\n\n @property\n def distance(self):\n \"\"\"Returns the current distance measured by the sensor in meters.\n\n Note\n that this property will have a value between 0 and\n :attr:`max_distance`.\n \"\"\"\n return self.__ultrasonic_device.distance\n\n @property\n def value(self):\n \"\"\"Returns a value between 0, indicating that something is either\n touching the sensor or is sufficiently near that the sensor can't tell\n the difference, and 1, indicating that something is at or beyond the\n specified *max_distance*.\"\"\"\n return self.__ultrasonic_device.value\n\n @property\n def pin(self):\n return self.__ultrasonic_device.pin\n\n def close(self):\n \"\"\"Shut down the device and release all associated resources. This\n method can be called on an already closed device without raising an\n exception.\n\n This method is primarily intended for interactive use at the command\n line. It disables the device and releases its pin(s) for use by another\n device.\n\n You can attempt to do this simply by deleting an object, but unless\n you've cleaned up all references to the object this may not work (even\n if you've cleaned up all references, there's still no guarantee the\n garbage collector will actually delete the object at that point). By\n contrast, the close method provides a means of ensuring that the object\n is shut down.\n\n For example, if you have a buzzer connected to port D0, but then wish\n to attach an LED instead:\n\n >>> from pitop import Buzzer, LED\n >>> bz = Buzzer(\"D0\")\n >>> bz.on()\n >>> bz.off()\n >>> bz.close()\n >>> led = LED(\"D0\")\n >>> led.blink()\n\n :class:`Device` descendents can also be used as context managers using\n the :keyword:`with` statement. For example:\n\n >>> from pitop import Buzzer, LED\n >>> with Buzzer(\"D0\") as bz:\n ... bz.on()\n ...\n >>> with LED(\"D0\") as led:\n ... led.on()\n ...\n \"\"\"\n self.__ultrasonic_device.close()\n\n @property\n def in_range(self):\n return self.__ultrasonic_device.in_range\n\n @property\n def when_in_range(self):\n return self.__ultrasonic_device.when_deactivated\n\n @when_in_range.setter\n def when_in_range(self, function):\n if callable(function):\n self.__ultrasonic_device.when_deactivated = function\n\n @property\n def when_out_of_range(self):\n return self.__ultrasonic_device.when_activated\n\n @when_out_of_range.setter\n def when_out_of_range(self, function):\n if callable(function):\n self.__ultrasonic_device.when_activated = function\n\n def wait_for_in_range(self, timeout=None):\n self.__ultrasonic_device.wait_for_inactive(timeout=timeout)\n\n def wait_for_out_of_range(self, timeout=None):\n self.__ultrasonic_device.wait_for_active(timeout=timeout)\n","repo_name":"thymjan/pi-top-Python-SDK","sub_path":"packages/pma/pitop/pma/ultrasonic_sensor.py","file_name":"ultrasonic_sensor.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"8745051317","text":"import sys\nfrom PySide2.QtWidgets import QWidget, QMessageBox, QApplication\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n\n self.setGeometry(300, 300, 250, 150)\n self.setWindowTitle('Message box')\n self.show()\n\n def closeEvent(self, event):\n\n reply = QMessageBox.question(self, 'Message',\n \"Are you sure to quit?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n\nif __name__ == '__main__':\n import sys\n\n app = None\n try:\n import nuke\n except ImportError:\n app = QApplication(sys.argv)\n main = Example()\n main.show()\n\n if app is not None:\n app.exec_()","repo_name":"syurskyi/Python_Topics","sub_path":"140_gui/pyqt_pyside/examples/zetcode/001_First programs/005_Message Box.py","file_name":"005_Message Box.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"74663646243","text":"#\n# Simple Find the Attachment Name given input from a mime File\n# Modification of this code: https://www.w3schools.com/python/python_lists_loop.asp\n\n# Define the Variables\n# find common data interchange Extensions\nExtensions = [\".csv\", \".txt\", \".xlsx\"]\nfile_name = 'F:/python/5eopts4ig1e3ilh6eci9u8a5a6o0to7147j78ig1'\n\nattachment_name = 0\nattachments_found = 0\nattachment_names = []\n\n# opening a text file\nwith open(file_name, \"r\") as file1:\n for Extension in Extensions:\n # setting flag and index to 0\n flag = 0\n index = 0\n\n\n # Loop through the file line by line\n for line in file1:\n index += 1\n\n # checking string is present in line or not\n if Extension in line:\n flag = 1\n attachments_found += 1\n attachment_name = (line.split(\"=\")[1]).replace('\"','')\n attachment_names.append(attachment_name)\n break\nif attachment_name == 0:\n print(\"No Attachments Found\")\nelse:\n print(\"Attachments found:\", attachments_found)\n print(attachment_names)","repo_name":"itglueguy/100daysofcode","sub_path":"Day21_files/find_email_attachment_name_from_file.py","file_name":"find_email_attachment_name_from_file.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38265765170","text":"from numpy import add\nfrom optimix import Function\n\n\nclass SumMean(Function):\n \"\"\"\n Sum mean function, 𝐟₀ + 𝐟₁ + ….\n\n The mathematical representation is\n\n 𝐦 = 𝐟₀ + 𝐟₁ + …\n\n In other words, it is a sum of mean vectors.\n\n Example\n -------\n\n .. doctest::\n\n >>> from glimix_core.mean import OffsetMean, LinearMean, SumMean\n >>>\n >>> X = [[5.1, 1.0],\n ... [2.1, -0.2]]\n >>>\n >>> mean0 = LinearMean(X)\n >>> mean0.effsizes = [-1.0, 0.5]\n >>>\n >>> mean1 = OffsetMean(2)\n >>> mean1.offset = 2.0\n >>>\n >>> mean = SumMean([mean0, mean1])\n >>>\n >>> print(mean.value())\n [-2.6 -0.2]\n >>> g = mean.gradient()\n >>> print(g[\"SumMean[0].effsizes\"])\n [[ 5.1 1. ]\n [ 2.1 -0.2]]\n >>> print(g[\"SumMean[1].offset\"])\n [1. 1.]\n >>> mean0.name = \"A\"\n >>> mean1.name = \"B\"\n >>> mean.name = \"A+B\"\n >>> print(mean)\n SumMean(means=...): A+B\n LinearMean(m=2): A\n effsizes: [-1. 0.5]\n OffsetMean(): B\n offset: 2.0\n \"\"\"\n\n def __init__(self, means):\n \"\"\"\n Constructor.\n\n Parameters\n ----------\n means : list\n List of mean functions.\n \"\"\"\n self._means = [c for c in means]\n Function.__init__(self, \"SumMean\", composite=self._means)\n\n def value(self):\n \"\"\"\n Sum of mean vectors, 𝐟₀ + 𝐟₁ + ….\n\n Returns\n -------\n 𝐦 : ndarray\n 𝐟₀ + 𝐟₁ + ….\n \"\"\"\n return add.reduce([mean.value() for mean in self._means])\n\n def gradient(self):\n \"\"\"\n Sum of mean function derivatives.\n\n Returns\n -------\n ∂𝐦 : dict\n ∂𝐟₀ + ∂𝐟₁ + ….\n \"\"\"\n grad = {}\n for i, f in enumerate(self._means):\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 = \"{}(means=...)\".format(tname)\n if self.name is not None:\n msg += \": {}\".format(self.name)\n for m in self._means:\n spl = str(m).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/mean/_sum.py","file_name":"_sum.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"} +{"seq_id":"40488869757","text":"from odoo import models, fields, api\nfrom odoo.exceptions import ValidationError\n\n\nclass MrpProduction(models.Model):\n _inherit = 'mrp.production'\n\n def create_mrp_from_pos(self, products):\n product_ids = []\n if products:\n for product in products:\n if self.env['product.product'].browse(int(product['id'])).to_make_mrp:\n flag = 1\n if product_ids:\n for product_id in product_ids:\n if product_id['id'] == product['id']:\n product_id['qty'] += product['qty']\n flag = 0\n if flag:\n product_ids.append(product)\n for prod in product_ids:\n if prod['qty'] > 0:\n product = self.env['product.product'].search([('id', '=', prod['id'])])\n bom_count = self.env['mrp.bom'].search([('product_tmpl_id', '=', prod['product_tmpl_id'])])\n if bom_count:\n bom_temp = self.env['mrp.bom'].search([('product_tmpl_id', '=', prod['product_tmpl_id']),\n ('product_id', '=', False)])\n bom_prod = self.env['mrp.bom'].search([('product_id', '=', prod['id'])])\n if bom_prod:\n bom = bom_prod[0]\n elif bom_temp:\n bom = bom_temp[0]\n else:\n bom = []\n if bom:\n vals = {\n 'origin': 'POS-' + prod['pos_reference'],\n 'state': 'confirmed',\n 'product_id': prod['id'],\n 'product_tmpl_id': prod['product_tmpl_id'],\n 'product_uom_id': prod['uom_id'],\n 'product_qty': prod['qty'],\n 'bom_id': bom.id,\n }\n mrp_order = self.sudo().create(vals)\n list_value = []\n for bom_line in mrp_order.bom_id.bom_line_ids:\n list_value.append((0, 0, {\n 'raw_material_production_id': mrp_order.id,\n 'name': mrp_order.name,\n 'product_id': bom_line.product_id.id,\n 'product_uom': bom_line.product_uom_id.id,\n 'product_uom_qty': (bom_line.product_qty * mrp_order.product_qty)/self.env['mrp.bom'].search([(\"product_tmpl_id\", \"=\", prod['product_tmpl_id'])]).product_qty,\n 'picking_type_id': mrp_order.picking_type_id.id,\n 'location_id': mrp_order.location_src_id.id,\n 'location_dest_id': bom_line.product_id.with_company(self.company_id.id).property_stock_production.id,\n 'company_id': mrp_order.company_id.id,\n }))\n\n finished_vals = {\n 'product_id': prod['id'],\n 'product_uom_qty': prod['qty'],\n 'product_uom': prod['uom_id'],\n 'name': mrp_order.name,\n 'date_deadline': mrp_order.date_deadline,\n 'picking_type_id': mrp_order.picking_type_id.id,\n 'location_id': mrp_order.location_src_id.id,\n 'location_dest_id': mrp_order.location_dest_id.id,\n 'company_id': mrp_order.company_id.id,\n 'production_id': mrp_order.id,\n 'warehouse_id': mrp_order.location_dest_id.warehouse_id.id,\n 'origin': mrp_order.name,\n 'group_id': mrp_order.procurement_group_id.id,\n 'propagate_cancel': mrp_order.propagate_cancel,\n }\n mrp_order.update({'move_raw_ids': list_value,\n 'move_finished_ids': [\n (0, 0, finished_vals)]\n })\n return True\n\n\nclass ProductTemplate(models.Model):\n _inherit = 'product.template'\n\n to_make_mrp = fields.Boolean(string='To Create MRP Order',\n help=\"Check if the product should be make mrp order\")\n\n @api.onchange('to_make_mrp')\n def onchange_to_make_mrp(self):\n if self.to_make_mrp:\n if not self.bom_count:\n raise ValidationError('Please set Bill of Material for this product.')\n\n\nclass ProductProduct(models.Model):\n _inherit = 'product.product'\n\n @api.onchange('to_make_mrp')\n def onchange_to_make_mrp(self):\n if self.to_make_mrp:\n if not self.bom_count:\n raise Warning('Please set Bill of Material for this product.')\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"pos_mrp_order/models/point_of_sale_make_mrp.py","file_name":"point_of_sale_make_mrp.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"} +{"seq_id":"8305766251","text":"from .models import Client, Call, Deal, Reminder\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\n\n\nclass ClientForm(forms.ModelForm):\n class Meta:\n model = Client\n fields = ['company',\n 'contact_name',\n 'position',\n 'phone',\n 'email',\n 'address',\n 'commentary',\n 'publish']\n widgets = {\n 'company': forms.TextInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'Название клиента'\n }),\n 'contact_name': forms.TextInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'ФИО ЛПРа'\n }),\n 'position': forms.TextInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'Должность ЛПРа'\n }),\n 'phone': forms.TextInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'Тел. номер'\n }),\n 'email': forms.EmailInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'EMAIL'\n }),\n 'address': forms.TextInput(attrs={\n 'class': 'form-control',\n 'placeholder': 'Адрес производства'\n }),\n 'commentary': forms.Textarea(attrs={\n 'class': 'form-control',\n 'placeholder': 'Комментарии'\n }),\n 'publish': forms.DateTimeInput(attrs={\n 'class': 'form-control',\n }),\n\n }\n\n\nclass CallForm(forms.ModelForm):\n class Meta:\n model = Call\n fields = ['client',\n 'commentary',\n 'publish']\n widgets = {\n 'commentary': forms.Textarea(attrs={\n 'class': 'form-control',\n 'placeholder': 'Комментарии'\n }),\n 'publish': forms.DateInput(attrs={\n 'autocomplete': 'off',\n 'class': 'form-control',\n }),\n }\n\n\nclass ReminderForm(forms.ModelForm):\n class Meta:\n model = Reminder\n fields = ['client',\n 'event_type',\n 'commentary',\n 'deadline',\n ]\n widgets = {\n 'commentary': forms.Textarea(attrs={\n 'class': 'form-control',\n 'placeholder': 'Комментарии'\n }),\n 'deadline': forms.DateTimeInput(attrs={\n 'autocomplete': 'off',\n 'placeholder': 'Дата напоминания'\n }),\n }\n\n\nclass DealForm(forms.ModelForm):\n class Meta:\n model = Deal\n fields = ['client',\n 'commentary',\n 'publish',\n ]\n widgets = {\n 'commentary': forms.Textarea(attrs={\n 'class': 'form-control',\n 'placeholder': 'Комментарии'\n }),\n 'publish': forms.DateInput(attrs={\n 'autocomplete': 'off',\n 'class': 'form-control datetimepicker-input',\n 'data-target': '#datetimepicker1'\n }),\n }\n\n\nclass LoginForm(forms.Form):\n username = forms.CharField()\n password = forms.CharField(widget=forms.PasswordInput)\n\n\nclass RegistrationForm(UserCreationForm):\n username = forms.CharField(label='Логин', widget=forms.TextInput(attrs={'class': 'form-input'}))\n password1 = forms.CharField(label='Пароль', widget=forms.PasswordInput(attrs={'class': 'form-input'}))\n password2 = forms.CharField(label='Повтор пароля', widget=forms.PasswordInput(attrs={'class': 'form-input'}))\n email = forms.EmailInput()\n\n class Meta:\n model = User\n fields = ('username', 'email', 'password1', 'password2')\n\n\nclass DateForm(forms.Form):\n date = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'])\n","repo_name":"DzmitryMak/Django_CRM","sub_path":"crm/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72927568164","text":"import glob\nimport os\nimport sys\n\ndef main():\n directory = sys.argv[1]\n argument = sys.argv[2]\n output_filename= sys.argv[3]\n print(sys.argv)\n outputFile = open(output_filename, 'w')\n for j,filename in enumerate(glob.glob(directory+'*.conll')):\n if j > 0:\n outputFile.write(os.linesep+os.linesep)\n with open(filename) as iFile:\n data = iFile.read()\n items = data.split(os.linesep + os.linesep)\n total = len(items)\n for i,x in enumerate(items):\n new_item = 'O\\t0\\t0\\t<{}>'.format(argument)\n new_item = new_item+os.linesep+x\n tmp = new_item.splitlines()\n tmp_total = len(tmp)\n for k,line in enumerate(tmp):\n outputFile.write(line+\"\\t\"+filename)\n #new_item += os.linesep + os.linesep\n if k+1 < tmp_total:\n outputFile.write(os.linesep)\n if i+1 < total:\n outputFile.write(os.linesep+os.linesep)\n outputFile.close()\nmain()","repo_name":"Zephyr1022/SDOH-N2C2-UTSA","sub_path":"scripts/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"7136035892","text":"#Module construct_dna\r\n#Created by Aria Coraor\r\n#Written 6/6/23\r\n\r\nimport copy\r\nimport numpy as np\r\nimport mdtraj as md\r\nimport argparse\r\nimport warnings\r\nfrom vect_quat_util import *\r\nimport os\r\n\r\n\r\ndef main():\r\n \"\"\"Create a construct PDB by attaching Cy3 and Cy5 to the specified\r\n NA residues.\"\"\"\r\n #Assume cy3_dna.pdb and cy5_dna.pdb are in this directory! \r\n\r\n #Load input pdb\r\n pdb = md.load_pdb(args.file)\r\n xyz = pdb.xyz[0]\r\n top = pdb.top\r\n\r\n #Load cy3 and cy5 pdbs\r\n d_pdb = md.load_pdb(\"cy3_dna.pdb\")\r\n d_xyz = d_pdb.xyz[0]\r\n d_top = d_pdb.top\r\n \r\n a_pdb = md.load_pdb(\"cy5_dna.pdb\")\r\n a_xyz = a_pdb.xyz[0]\r\n a_top = a_pdb.top\r\n\r\n #Add dyes in the correct locations\r\n xyz, top = add_dyes(xyz, top, d_xyz, d_top, a_xyz, a_top, args.donor,\r\n args.acceptor)\r\n\r\n #Save new pdb\r\n pdb = md.formats.PDBTrajectoryFile(args.output,mode='w')\r\n pdb.write(10.*xyz,top)\r\n\r\n print(\"Labelled pdb written. Exiting...\")\r\n\r\ndef add_dyes(xyz, top, donor_xyz, donor_top, acceptor_xyz, acceptor_top,\r\n donor_ind, acceptor_ind):\r\n \"\"\"Remove the appropriate atoms of the DNA residue to replace. Reorient\r\n the donor and acceptor to the appropriate residue and add to the pdb.\r\n\r\n Parameters:\r\n xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the input DNA pdb.\r\n top: *mdtraj.topology*\r\n Topology of the input DNA pdb.\r\n donor_xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the Cy3 dye with linkers.\r\n donor_top: *mdtraj.topology*\r\n Topology of the Cy3 dye with linkers.\r\n acceptor_xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the Cy5 dye with linkers.\r\n acceptor_top: *mdtraj.topology*\r\n Topology of the Cy5 dye with linkers.\r\n donor_ind: *int*\r\n Index of the donor with respect to its strand, 5' direction.\r\n acceptor_ind: *int*\r\n Index of the acceptor with respect to its strand, 5' direction.\r\n Returns:\r\n labelled_xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the labelled DNA pdb.\r\n labelled_top: *mdtraj.topology*\r\n Topology of the labelled DNA pdb.\r\n \"\"\"\r\n #First: create a truncated version with all the appropriate residue \r\n #Atoms removed \r\n trunc_xyz, trunc_top = remove_dna_atoms(xyz, top, args.donor, \r\n args.acceptor)\r\n\r\n #Next: get the inlet and outlet phosphorus and oxygen positions\r\n d_phos_in, d_ox_in, d_ox_out, d_dna_com = get_phos_ox(xyz, top, \r\n donor_ind, is_donor=True) \r\n a_phos_in, a_ox_in, a_ox_out, a_dna_com = get_phos_ox(xyz, top, \r\n acceptor_ind, is_donor=False)\r\n\r\n #Rotate and translate the dye molecules to line up the phosphates\r\n affine_donor_xyz, affine_donor_top = affine_translate(d_phos_in,\r\n d_ox_in, d_ox_out, donor_xyz, donor_top,d_dna_com)\r\n affine_acceptor_xyz, affine_acceptor_top = affine_translate(a_phos_in,\r\n a_ox_in, a_ox_out, acceptor_xyz,acceptor_top,a_dna_com)\r\n\r\n #Combine xyzs and tops:\r\n #labelled_xyz = np.concatenate((trunc_xyz, affine_donor_xyz, affine_acceptor_xyz))\r\n \r\n #Manually construct new topology obeying proper sequencing\r\n labelled_top = md.Topology()\r\n labelled_xyz = []#Concatenate-able list of np.array\r\n\r\n #loop over all residues\r\n res_index = 0\r\n old_chains = [ch for ch in trunc_top.chains]\r\n for chain_i, chain in enumerate(old_chains):\r\n labelled_top.add_chain()\r\n curr_ch = labelled_top.chain(-1)\r\n for res_i, res in enumerate(chain.residues):\r\n #If you hit the dye residue, first add the dye\r\n if chain_i == 0 and res_i == donor_ind:\r\n donor_res = [r for r in affine_donor_top.residues][0]\r\n labelled_top.add_residue(name='C3N',chain=curr_ch)\r\n curr_res = labelled_top.residue(-1)\r\n for d_at in donor_res.atoms:\r\n labelled_top.add_atom(name=d_at.name,\r\n element=d_at.element, residue=curr_res)\r\n labelled_xyz += [affine_donor_xyz]\r\n elif chain_i == 1 and res_i == acceptor_ind:\r\n acc_res = [r for r in affine_acceptor_top.residues][0]\r\n labelled_top.add_residue(name='C5N',chain=curr_ch)\r\n curr_res = labelled_top.residue(-1)\r\n for acc_at in acc_res.atoms:\r\n labelled_top.add_atom(name=acc_at.name,\r\n element=acc_at.element, residue=curr_res)\r\n labelled_xyz += [affine_acceptor_xyz]\r\n \r\n #Now, add the normal residue and atoms\r\n labelled_top.add_residue(name=res.name,chain=curr_ch)\r\n curr_res = labelled_top.residue(-1)\r\n for at in res.atoms:\r\n labelled_top.add_atom(name=at.name,element=at.element,\r\n residue=curr_res)\r\n labelled_xyz += [np.reshape(trunc_xyz[at.index],(1,-1))]\r\n labelled_xyz = np.concatenate(labelled_xyz)\r\n return labelled_xyz, labelled_top\r\n print(\"Unreachable code! legacy version of same code.\")\r\n #Donor is on chain 0, acceptor is on chain 1\r\n labelled_top = copy.deepcopy(trunc_top)\r\n labelled_chains = [ch for ch in labelled_top.chains]\r\n \r\n #Loop through residues to add donor\r\n for don_r in affine_donor_top.residues:\r\n #Add residue\r\n labelled_top.add_residue(\"C3N\",labelled_chains[0])\r\n current_r = labelled_top.residue(-1)\r\n #Loop through atoms\r\n for don_atom in don_r.atoms:\r\n labelled_top.add_atom(don_atom.name,element=don_atom.element,\r\n residue=current_r)\r\n\r\n #Loop through residues to add acceptor\r\n for acc_r in affine_acceptor_top.residues:\r\n #Add residue\r\n labelled_top.add_residue(acc_r.name,labelled_chains[1])\r\n next_r = labelled_top.residue(-1)\r\n #Loop through atoms\r\n for acc_atom in acc_r.atoms:\r\n labelled_top.add_atom(acc_atom.name,element=acc_atom.element,\r\n residue=next_r)\r\n \r\n #Old-style joining, makes chain ends:\r\n #labelled_top = trunc_top.join(affine_donor_top)\r\n #labelled_top = labelled_top.join(affine_acceptor_top)\r\n\r\n return labelled_xyz, labelled_top\r\n\r\ndef remove_dna_atoms(xyz, top, donor_ind, acceptor_ind):\r\n \"\"\"Remove relevant atoms from each donor/acceptor residue in the\r\n pdb structure.\r\n\r\n Parameters:\r\n xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the input DNA pdb.\r\n top: *mdtraj.topology*\r\n Topology of the input DNA pdb.\r\n donor_ind: *int*\r\n Index of the donor with respect to its strand, 5' direction.\r\n acceptor_ind: *int*\r\n Index of the acceptor with respect to its strand, 5' direction.\r\n Returns:\r\n trunc_xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the truncated DNA pdb.\r\n trunc_top: *mdtraj.topology*\r\n Topology of the truncated DNA pdb.\r\n \"\"\"\r\n rm_inds = []\r\n\r\n all_atoms = [at for at in top.atoms]\r\n\r\n chains = [c for c in top.chains]\r\n ch1_res = [r for r in chains[0].residues]\r\n donor_residue = ch1_res[donor_ind]\r\n ch2_res = [r for r in chains[1].residues]\r\n acceptor_residue = ch2_res[acceptor_ind]\r\n\r\n for at in donor_residue.atoms:\r\n rm_inds.append(at.index)\r\n for at in acceptor_residue.atoms:\r\n rm_inds.append(at.index)\r\n\r\n keep_inds = [i for i in range(len(all_atoms)) if i not in set(rm_inds)]\r\n trunc_top = top.subset(keep_inds)\r\n trunc_xyz = xyz[keep_inds]\r\n \r\n pdb = md.formats.PDBTrajectoryFile('rmdna.pdb',mode='w')\r\n pdb.write(10.*trunc_xyz,trunc_top)\r\n\r\n return trunc_xyz, trunc_top\r\n\r\ndef get_phos_ox(xyz, top,index, is_donor):\r\n \"\"\"Get the positions of the inlet and outlet phosphates and O?3? to \r\n determine orientation of dyes.\r\n\r\n Parameters:\r\n xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the input DNA pdb.\r\n top: *mdtraj.topology*\r\n Topology of the input DNA pdb.\r\n index: *int*\r\n Index of the dye with respect to its strand, 5' direction.\r\n is_donor: *bool*\r\n Whether or not this is on the donor or the acceptor strand.\r\n Returns:\r\n phos_in: *np.array*, shape: (3)\r\n Position of the inlet phosphorus from the 3' direction.\r\n ox_in: *np.array*, shape: (3)\r\n Position of the inlet O3' from the 3' direction.\r\n ox_out: *np.array*, shape: (3)\r\n Position of the outlet O5' from the 5' direction.\r\n dna_com: *np.array*, shape: (3)\r\n Average position of the labelled DNA residue.\r\n \"\"\"\r\n #We seek to exactly overlay the incoming 3' phosphate, and its OP1\r\n\r\n #We rotate the molecule until this is matched, and then rotate until \r\n #The outlet O5' position is matched.\r\n chains = [ch for ch in top.chains]\r\n if is_donor:\r\n chain = chains[0]\r\n else:\r\n chain = chains[1]\r\n\r\n residues = [r for r in chain.residues]\r\n #outgoing_res = residues[index+1]\r\n dye_res = residues[index]\r\n #outgoing_atoms = [at for at in outgoing_res.atoms]\r\n dye_res_atoms = [at for at in dye_res.atoms]\r\n #for at in outgoing_atoms:\r\n # if at.name == \"P\":\r\n # phos_out = xyz[at.index]\r\n for at in dye_res_atoms:\r\n if at.name == \"P\":\r\n phos_in = xyz[at.index]\r\n if at.name == \"OP1\":\r\n ox_in = xyz[at.index]\r\n elif at.name == \"O5'\":\r\n ox_out = xyz[at.index]\r\n\r\n dna_com = np.average(xyz[[at.index for at in dye_res_atoms]],axis=0)\r\n\r\n return phos_in, ox_in, ox_out, dna_com\r\n\r\ndef affine_translate(phos_in, ox_in, ox_out,dye_xyz,dye_top,dna_com):\r\n \"\"\"Rotate the dye until it aligns with the appropriate phosphate in/out\r\n\r\n Parameters:\r\n phos_in: *np.array*, shape: (3)\r\n Position of the inlet phosphorus from the 3' direction.\r\n ox_in: *np.array*, shape: (3)\r\n Position of the inlet OP1 from the 3' direction.\r\n ox_out: *np.array*, shape: (3)\r\n Position of the outlet OP2 from the 5' direction.\r\n dye_xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the dye with linkers.\r\n dye_top: *mdtraj.topology*\r\n Topology of the dye pdb.\r\n dna_com: *np.array*, shape: (3)\r\n Average position of the labelled DNA residue.\r\n Returns:\r\n dye_xyz: *np.array*, shape: (n_atoms,3)\r\n Positions of particles in the rotated dye with linkers.\r\n \"\"\"\r\n fvu0 = np.eye(3)\r\n quat0 = tu2rotquat(1e-5,np.array([1,0,0]))\r\n quat = np.copy(quat0)\r\n\r\n #Translate dye to 0\r\n dye_xyz = dye_xyz - np.average(dye_xyz,axis=0)\r\n\r\n #Get relevant dye atoms\r\n dye_ats = [at for at in dye_top.atoms]\r\n for at in dye_ats:\r\n if at.name == \"P\":\r\n dye_P = dye_xyz[at.index]\r\n elif at.name == \"O5'\":\r\n dye_o5 = dye_xyz[at.index]\r\n elif at.name == \"O3'\":\r\n dye_o3 = dye_xyz[at.index]\r\n\r\n #Now: Calculate angle to rotate along PO vector to align O5\r\n p_O5_vect = dye_o5 - dye_P\r\n dna_p_O5_vect = ox_out - phos_in\r\n\r\n #Project dna vector onto the plane of rotation\r\n p_O5_vect /= np.linalg.norm(p_O5_vect)\r\n dna_p_O5_vect /= np.linalg.norm(dna_p_O5_vect)\r\n \r\n rot_axis = np.cross(p_O5_vect,dna_p_O5_vect)\r\n rot_axis /= np.linalg.norm(rot_axis)\r\n\r\n dotp = np.dot(p_O5_vect,dna_p_O5_vect)\r\n if np.abs(dotp) > 1:\r\n dotp = dotp/np.abs(dotp)\r\n theta = np.arccos(dotp)\r\n q = tu2rotquat(theta,rot_axis)\r\n\r\n #Rotate dye into place \r\n dye_xyz = np.array([quat_vec_rot(row, q) for row in dye_xyz])\r\n dye_ats = [at for at in dye_top.atoms]\r\n for at in dye_ats:\r\n if at.name == \"P\":\r\n dye_P = dye_xyz[at.index]\r\n elif at.name == \"O5'\":\r\n dye_o5 = dye_xyz[at.index]\r\n elif at.name == \"O3'\":\r\n dye_o3 = dye_xyz[at.index]\r\n \r\n p_O5_vect = dye_o5 - dye_P\r\n p_O5_vect /= np.linalg.norm(p_O5_vect)\r\n print(\"Final dot between p_O5 and DNA p_o5 vectors (should be 1):\",\r\n np.dot(p_O5_vect,dna_p_O5_vect))\r\n\r\n #Dye is now rotated so phos_in - ox_out axis is correct. now rotate\r\n #the COM to the outside.\r\n dye_com = np.average(dye_xyz,axis=0)\r\n p_dna_vect = (dna_com - phos_in)/np.linalg.norm(dna_com-phos_in)\r\n p_dna_perp = p_dna_vect - np.dot(p_dna_vect,dna_p_O5_vect)*dna_p_O5_vect\r\n p_dna_perp /= np.linalg.norm(p_dna_perp)\r\n \r\n p_dye_vect = (dye_com - dye_P)/np.linalg.norm(dye_com - dye_P)\r\n p_dye_perp = p_dye_vect - np.dot(p_dye_vect,dna_p_O5_vect)*dna_p_O5_vect\r\n p_dye_perp /= np.linalg.norm(p_dye_perp)\r\n \r\n dotp = np.dot(p_dye_perp,p_dna_perp)\r\n if np.abs(dotp) > 1:\r\n dotp = dotp/np.abs(dotp)\r\n theta = np.arccos(dotp)\r\n #Rotate p_dye_perp by theta+pi/2\r\n q = tu2rotquat(theta + np.pi,dna_p_O5_vect)\r\n\r\n dye_xyz = np.array([quat_vec_rot(row, q) for row in dye_xyz])\r\n dye_ats = [at for at in dye_top.atoms]\r\n for at in dye_ats:\r\n if at.name == \"P\":\r\n dye_P = dye_xyz[at.index]\r\n elif at.name == \"O5'\":\r\n dye_o5 = dye_xyz[at.index]\r\n elif at.name == \"O3'\":\r\n dye_o3 = dye_xyz[at.index]\r\n \r\n p_dye_vect = (dye_com - dye_P)/np.linalg.norm(dye_com - dye_P)\r\n p_dye_perp = p_dye_vect - np.dot(p_dye_vect,dna_p_O5_vect)*dna_p_O5_vect\r\n p_dye_perp /= np.linalg.norm(p_dye_perp)\r\n dotp = np.dot(p_dye_perp,p_dna_perp)\r\n if np.abs(dotp) > 1:\r\n dotp = dotp/np.abs(dotp)\r\n print(\"Final dot between p_dye_perp and p_dna_perp vectors (should be -1):\",\r\n np.dot(p_dye_perp,p_dna_perp))\r\n #If dotp > 0.5, rotate by pi\r\n if dotp > 0.9:\r\n print(\"Strange rotation error? Flipping dye COM.\")\r\n q = tu2rotquat(np.pi,dna_p_O5_vect)\r\n dye_xyz = np.array([quat_vec_rot(row, q) for row in dye_xyz])\r\n dye_ats = [at for at in dye_top.atoms]\r\n for at in dye_ats:\r\n if at.name == \"P\":\r\n dye_P = dye_xyz[at.index]\r\n elif at.name == \"O5'\":\r\n dye_o5 = dye_xyz[at.index]\r\n elif at.name == \"O3'\":\r\n dye_o3 = dye_xyz[at.index]\r\n \r\n\r\n\r\n #Finally: translate dye into place\r\n disp = phos_in - dye_P\r\n \r\n dye_xyz = dye_xyz + disp\r\n\r\n #Write just dye to PDB\r\n n_atoms = len([at for at in dye_top.atoms])\r\n is_donor = n_atoms < 73\r\n if is_donor:\r\n fn = \"affine_cy3.pdb\"\r\n else:\r\n fn = \"affine_cy5.pdb\"\r\n pdb = md.formats.PDBTrajectoryFile(fn,mode='w')\r\n pdb.write(10.*dye_xyz,dye_top)\r\n return dye_xyz, dye_top\r\n\r\ndef foo(bar):\r\n \"\"\"Init.\r\n\r\n Parameters:\r\n bar: *np.array*\r\n description\r\n Returns:\r\n biz: *np.arra*\r\n description\r\n \"\"\"\r\n pass\r\n\t\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-f','--file', type=str, default='input.pdb',\r\n help='Path to PDB of ideal DNA structure, with correct endings.')\r\n parser.add_argument('-o','--output', type=str, default='labelled_dna.pdb',\r\n help='Path to output labelled PDB.')\r\n parser.add_argument('-d','--donor', type=int, \r\n default=15, help='Index of Cy3 in donor (Ashort) strand. Default=15')\r\n parser.add_argument('-a','--acceptor', type=int, \r\n default=23, help='Index of Cy5 in Acceptor (B) strand. Default=23 (B10)')\r\n args = parser.parse_args()\r\n\r\n main()\r\n\r\n","repo_name":"ACoraor/OpenMM-Tools","sub_path":"construct_dna.py","file_name":"construct_dna.py","file_ext":"py","file_size_in_byte":15737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29891598708","text":"import PySimpleGUI as sg\nimport json\nimport os\nfrom fuct import *\n\n#Ler arquivo, se tiver o arquivo nao vai abrir nada e so executar\n\nchek1 = False\ntrade = True\n\nsg.SetGlobalIcon('favicon.ico')\n\ntry:\n with open('config.json', 'r') as f:\n config = json.load(f)\n print(config['direct'] + ' lendo')\n nome_dict = config['direct']\n\n\nexcept FileNotFoundError:\n\n config = {\n 'direct':None, \n 'stado':1,\n 'Codigo-':\"Codigo-\", \n 'Textos-':\"Textos-\", \n 'Pdf-': \"Pdf-\", \n 'Audios-':\"Audios-\", \n 'Images-':\"Images-\", \n 'Videos-':\"Videos-\", \n 'Zip-':\"Compactados-\",\n 'Word documents-':\"Word documents-\", \n 'Spreadsheets-':\"Spreadsheets-\", \n 'Presentation files-':\"Presentation files-\", \n 'Executaveis-':\"Executaveis-\"\n }\n\nprint(config['stado'])\n\nif config['stado'] == 1:\n\n def Apresent():\n sg.theme('Dark Blue2')\n layout = [\n [sg.Text('◄ Ola, seja bem vindo ►\\r\\rNesse app voce pode organizar uma pasta apenas escolhendo \\ro diretorio da pasta ', size=(0,4))],\n [sg.Text()],\n [sg.Button('Avançar', bind_return_key=True), sg.Button('Cancelar')],\n ]\n return sg.Window('Inicio', layout=layout, finalize=True)\n\n def tela1():\n sg.theme('Dark Blue2')\n layout2 = [\n [sg.Text('Aponte um diretorio pra começar a organizar \\ros arquivos.\\r',size=(0, 2))],\n [sg.T()],\n [sg.Text('Diretorio:')],\n [sg.Input(default_text=verif() , key='direct'), sg.FolderBrowse()],\n [sg.Button('Ok', bind_return_key=True), sg.Button('Cancelar')]\n ]\n return sg.Window('Organizar', layout=layout2, finalize=True) \n\n def tela2():\n sg.theme('Dark Blue2')\n if os.path.exists('config.json'):\n load_names()\n layout3 = [\n [sg.Text('◄ Finalização ►')],\n [sg.Text('Nome das pastas (fazer mudanças e extramamente opcional):')],\n [sg.Input(default_text=config[\"Images-\"], size=(20, 0), k='-nome1-')],\n [sg.Input(default_text=config[\"Videos-\"], size=(20, 0), k='-nome2-')],\n [sg.Input(default_text=config[\"Audios-\"], size=(20, 0), k='-nome3-')],\n [sg.Input(default_text=config[\"Codigo-\"], size=(20, 0), k='-nome4-')],\n [sg.Input(default_text=config[\"Textos-\"], size=(20, 0), k='-nome5-')],\n [sg.Input(default_text=config[\"Pdf-\"], size=(20, 0), k='-nome6-')],\n [sg.Input(default_text=config[\"Word documents-\"], size=(20, 0), k='-nome7-')],\n [sg.Input(default_text=config[\"Spreadsheets-\"], size=(20, 0), k='-nome8-')],\n [sg.Input(default_text=config[\"Presentation files-\"], size=(20, 0), k='-nome9-')],\n [sg.Input(default_text=config[\"Executaveis-\"], size=(20, 0), k='-nome10-')],\n [sg.Input(default_text=config[\"Zip-\"], size=(20, 0), k='-nome11-')],\n [sg.T()],\n [sg.T('◄( ALERTA )►')],\n [sg.Text('Essas janelas não serar reproduzidas nas priximas inicializações, a não ser que seja inicializado pelo seguinte () execultavel na pasta desse script', size=(34, 5))],\n [sg.Button('voltar'), sg.Button('finalizar')]\n ]\n\n return sg.Window('Nome das pastas', layout=layout3, finalize=True )\n\n #Açoes em nas janelas:\n\n janela1, janela2, janela3 = Apresent(), None, None \n loop = True\n while loop:\n\n window, event, values = sg.read_all_windows()\n \n #Eventos na janela 1 =============================:\n\n if window == janela1 and event == sg.WIN_CLOSED:\n loop = False\n\n elif window == janela1 and event == 'Cancelar':\n loop = False\n\n elif window == janela1 and event == 'Avançar':\n janela1.Close()\n janela2 = tela1()\n\n if window == janela2 and event == sg.WIN_CLOSED:\n loop = False\n\n if window == janela2 and event == 'Ok':\n janela2.hide()\n janela3 = tela2()\n if trade == True:\n config.update({'stado':2})\n config.update({'direct':values['direct'].replace(\"/\", \"\\\\\")})\n\n with open('config.json', 'w') as f:\n json.dump(config ,f)\n print(config['direct'] + ' salvo')\n\n elif window == janela2 and event == 'Cancelar':\n loop = False\n\n #Eventos na janela 2 =============================:\n\n elif window == janela3 and event == sg.WIN_CLOSED:\n loop = False\n\n elif window == janela3 and 'checks' == True:\n print('1')\n\n elif window == janela3 and event == 'voltar':\n janela3.hide()\n janela2.un_hide()\n\n elif window == janela3 and event == 'finalizar':\n sg.popup('hora de organizar', title='Ultima etapa', auto_close=True, auto_close_duration=5, icon='ima.ico', keep_on_top=True)\n\n config.update({\"Images-\":values['-nome1-']})\n config.update({\"Videos-\":values['-nome2-']})\n config.update({\"Audios-\":values['-nome3-']})\n config.update({\"Codigo-\":values['-nome4-']})\n config.update({\"Textos-\":values['-nome5-']})\n config.update({\"Pdf-\":values['-nome6-']})\n config.update({\"Word documents-\":values['-nome7-']})\n config.update({\"Spreadsheets-\":values['-nome8-']})\n config.update({\"Presentation files-\":values['-nome9-']})\n config.update({\"Executaveis-\":values['-nome10-']})\n config.update({\"Zip-\":values['-nome11-']})\n\n with open('config.json', 'w') as f:\n json.dump(config ,f)\n\n print(values['-nome1-'])\n print(values['-nome2-'])\n print(values['-nome3-'])\n print(values['-nome4-'])\n print(values['-nome5-'])\n print(values['-nome6-'])\n print(values['-nome7-'])\n print(values['-nome8-'])\n print(values['-nome9-'])\n print(values['-nome10-'])\n print(values['-nome11-'])\n janela2.Close()\n janela3.Close()\n loop = False\n\n\n","repo_name":"Gabriel-bits/File_Organizer","sub_path":"Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":6162,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29239435196","text":"import os\nimport numpy as np\nimport librosa\nfrom transforms import *\nfrom tqdm import tqdm\nimport pandas as pd\nfrom torchvision.transforms import *\nfrom dask import compute, delayed\nfrom functools import partial\n\ndef get_mel_for_file(file):\n data_aug_transform = Compose([LoadAudio(), FixAudioLength(30), ToMelSpectrogram(n_mels=80)])\n return data_aug_transform(file)\n\ndef process_file(dirpath, file, pbar):\n fname = os.path.basename(file).replace('wav', 'npy')\n fpath = os.path.join(dirpath, fname)\n if not os.path.exists(fpath):\n spec = get_mel_for_file(file)['mel_spectrogram']\n np.save(fpath, spec)\n else:\n spec = np.load(fpath)\n pbar.update()\n return spec.mean(), spec.std()\n\ndef dask_apply(process, dirpath, inputs):\n pbar = tqdm(total=len(inputs))\n process = partial(process, pbar=pbar)\n values = [delayed(process)(dirpath, x) for x in inputs]\n results = compute(*values, scheduler='threads')\n pbar.close()\n return results\n\ndef process_files(dirpath, files):\n results = dask_apply(process_file, dirpath, files)\n means, stds = zip(*results)\n return means, stds\n\nif __name__ == \"__main__\":\n root = \"/tts_data/kaggle/freesound/data\"\n labelled_dir = os.path.join(root, \"train_curated\")\n unlabelled_dir = os.path.join(root, \"train_noisy\")\n test_dir = os.path.join(root, \"test\")\n\n labelled_spec_dir = os.path.join(root, \"train_curated_spec\")\n unlabelled_spec_dir = os.path.join(root, \"train_noisy_spec\")\n test_spec_dir = os.path.join(root, \"test_spec\")\n\n os.makedirs(labelled_spec_dir, exist_ok=True)\n os.makedirs(unlabelled_spec_dir, exist_ok=True)\n\n labelled_train_df = pd.read_csv(os.path.join(root, \"train_curated.csv_train\"))\n labelled_val_df = pd.read_csv(os.path.join(root, \"train_curated.csv_test\"))\n labelled_dev_df = pd.read_csv(os.path.join(root, \"train_curated.csv_dev\"))\n unlabelled_df = pd.read_csv(os.path.join(root, \"train_noisy.csv\"))\n\n labelled_files_train = [os.path.join(labelled_dir, fname) for fname in labelled_train_df.fname.values]\n labelled_files_val = [os.path.join(labelled_dir, fname) for fname in labelled_val_df.fname.values]\n labelled_files_dev = [os.path.join(labelled_dir, fname) for fname in labelled_dev_df.fname.values]\n unlabelled_files = [os.path.join(unlabelled_dir, fname) for fname in unlabelled_df.fname.values]\n\n means_train, std_train = process_files(labelled_spec_dir, labelled_files_train + labelled_files_val + labelled_files_dev)\n means_noisy, std_noisy = process_files(unlabelled_spec_dir, unlabelled_files)\n\n print(f\"Mean: {np.mean(means_train + means_noisy)}, Std: {np.mean(std_train + std_noisy)}\")","repo_name":"viig99/mixmatch-freesound","sub_path":"utils/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"3063927428","text":"from lib import GoogleNet_Model, nn_Ops, HDML\nfrom flags.FLAGS_HDML_triplet import *\n\n\ndef inference(x_raw, is_Training):\n # CNN 分类器\n with tf.variable_scope('Classifier'):\n google_net_model = GoogleNet_Model.GoogleNet_Model()\n embedding = google_net_model.forward(x_raw) # 输入数据经过GoogleNet得到嵌入\n\n # 如果使用 hard-aware Negative Generation,则记录原始特征y(特征空间)\n if FLAGS.Apply_HDML:\n # Tensor(\"Classifier/Reshape_1:0\", shape=(?, 1024), dtype=float32)\n embedding_y_origin = embedding\n\n # Batch Normalization layer 1 批量归一化\n # Tensor(\"Classifier/BN1/batch_normalization/batchnorm/add_1:0\", shape=(?, 1024), dtype=float32)\n embedding = nn_Ops.bn_block(\n embedding, normal=FLAGS.normalize, is_Training=is_Training, name='BN1')\n # FC layer 1 全连接 得到嵌入空间中的Z Tensor(\"Classifier/fc1/add:0\", shape=(?, 128), dtype=float32)\n embedding_z = nn_Ops.fc_block(\n embedding, in_d=1024, out_d=FLAGS.embedding_size,\n name='fc1', is_bn=False, is_relu=False, is_Training=is_Training)\n\n # Embedding Visualization 嵌入可视化\n # 赋值op 和变量embedding_var\n # assignment, embedding_var = Embedding_Visualization.embedding_assign(\n # batch_size=256, embedding=embedding_z,\n # embedding_size=FLAGS.embedding_size, name='Embedding_of_fc1')\n\n # if HNG is applied 如果使用Hard Negative Mining\n if FLAGS.Apply_HDML:\n # 占位符\n # 插值生成Z^ Tensor(\"concat:0\", shape=(72, 128), dtype=float32)\n embedding_z_quta = HDML.Pulling(FLAGS.LossType, embedding_z, Javg)\n # Tensor(\"concat_1:0\", shape=(?, 128), dtype=float32)\n embedding_z_concate = tf.concat([embedding_z, embedding_z_quta], axis=0)\n\n # Generator 把z映射回y 128-->1024\n with tf.variable_scope('Generator'):\n # generator fc3\n embedding_y_concate = nn_Ops.fc_block(\n embedding_z_concate, in_d=FLAGS.embedding_size, out_d=512,\n name='generator1', is_bn=True, is_relu=True, is_Training=is_Training\n )\n\n # generator fc4 Tensor(\"Generator/generator2/add:0\", shape=(?, 1024), dtype=float32)\n embedding_y_concate = nn_Ops.fc_block(\n embedding_y_concate, in_d=512, out_d=1024,\n name='generator2', is_bn=False, is_relu=True, is_Training=is_Training\n )\n\n # Tensor(\"Generator/Slice:0\", shape=(16, 1024), dtype=float32)\n # Tensor(\"Generator/Slice_1:0\", shape=(72, 1024), dtype=float32)\n embedding_yp, embedding_yq = HDML.npairSplit(embedding_y_concate)\n\n # 用嵌入z z^训练和上面一样的分类层\n with tf.variable_scope('Classifier'):\n embedding_z_quta = nn_Ops.bn_block(\n embedding_yq, normal=FLAGS.normalize, is_Training=is_Training, name='BN1', reuse=True)\n\n embedding_z_quta = nn_Ops.fc_block( # (72,128)\n embedding_z_quta, in_d=1024, out_d=FLAGS.embedding_size,\n name='fc1', is_bn=False, is_relu=False, reuse=True, is_Training=is_Training\n )\n\n # 划分anchor neg\n # (8,128)\n embedding_zq_anc = tf.slice(\n input_=embedding_z_quta, begin=[0, 0], size=[int(FLAGS.batch_size / 2), int(FLAGS.embedding_size)])\n # (64,128) 生成的\n embedding_zq_negtile = tf.slice(\n input_=embedding_z_quta, begin=[int(FLAGS.batch_size / 2), 0],\n size=[int(np.square(FLAGS.batch_size / 2)), int(FLAGS.embedding_size)]\n )\n return embedding_z, embedding_y_origin, embedding_zq_anc, embedding_zq_negtile, embedding_yp, embedding_yq\n else:\n return embedding_z","repo_name":"YancyGuo/DAML","sub_path":"prostate_inference.py","file_name":"prostate_inference.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71658593444","text":"import brownie\nfrom brownie import accounts, Lupi\nimport pytest\n\n#-------------------------------------------------------------------------------\n# Fixtures\n#-------------------------------------------------------------------------------\n\n@pytest.fixture(scope='module', autouse=True)\ndef lupi(Lupi, accounts):\n yield Lupi.deploy({'from': accounts[0]})\n \n@pytest.fixture(autouse=True)\ndef isolation(fn_isolation):\n pass\n\n@pytest.fixture(scope='module')\ndef owner():\n return accounts[0]\n\n#-------------------------------------------------------------------------------\n# Tests\n#-------------------------------------------------------------------------------\n\ndef test_startGame(lupi, accounts, owner):\n assert lupi.getStatus() == 0\n lupi.startGame({'from': owner})\n assert lupi.getStatus() == 1\n assert lupi.getNumPlayers() == 0\n\ndef test_submitGuess_game_not_started_reverts(lupi, accounts):\n player1 = accounts[1]\n with brownie.reverts():\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n \ndef test_submitGuess_wrong_bet_reverts(lupi, accounts, owner):\n player1 = accounts[1]\n lupi.startGame({'from': owner})\n with brownie.reverts():\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount() - 1})\n \ndef test_submitGuess__multiple_calls_reverts(lupi, accounts, owner):\n player1 = accounts[1]\n lupi.startGame({'from': owner})\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n with brownie.reverts():\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n\ndef test_submitGuess__success(lupi, accounts, owner):\n player1 = accounts[1]\n lupi.startGame({'from': owner})\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n assert lupi.getNumPlayers() == 1\n assert lupi.getMyGuess({'from': player1}) == 1\n assert lupi.balance() == lupi.getBetAmount()\n \ndef test_updateGuess_called_before_submitGuess_reverts(lupi, accounts, owner):\n player1 = accounts[1]\n lupi.startGame({'from': owner})\n with brownie.reverts():\n lupi.updateGuess(1, {'from': player1})\n \ndef test_updateGuess_is_not_payable(lupi, accounts, owner):\n player1 = accounts[1]\n lupi.startGame({'from': owner})\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n with brownie.reverts():\n lupi.updateGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n \ndef test_updateGuess_success(lupi, accounts, owner):\n lupi.startGame({'from': owner})\n player1 = accounts[1]\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n lupi.updateGuess(2, {'from': player1})\n assert lupi.getMyGuess({'from': player1}) == 2\n \ndef test_endGame__success(lupi, accounts, owner):\n player1 = accounts[1]\n player2 = accounts[2]\n starting_balance = player1.balance()\n lupi.startGame({'from': owner})\n lupi.submitGuess(1, {'from': player1, 'amount': lupi.getBetAmount()})\n lupi.submitGuess(2, {'from': player2, 'amount': lupi.getBetAmount()})\n assert lupi.balance() == lupi.getBetAmount() * 2\n lupi.endGame({'from': owner})\n assert player1.balance() == starting_balance + 980\n assert player2.balance() == starting_balance - 1000\n assert owner.balance() == starting_balance + 20\n \ndef test_endGame__foo(lupi, accounts, owner):\n player1 = accounts[1]\n player2 = accounts[2]\n player3 = accounts[3]\n player4 = accounts[4]\n starting_balance = player1.balance()\n lupi.startGame({'from': owner})\n lupi.submitGuess(10, {'from': player1, 'amount': lupi.getBetAmount()})\n lupi.submitGuess(5, {'from': player2, 'amount': lupi.getBetAmount()})\n lupi.submitGuess(20, {'from': player3, 'amount': lupi.getBetAmount()})\n lupi.submitGuess(5, {'from': player4, 'amount': lupi.getBetAmount()})\n gg = lupi.getAllGuesses()\n # print(gg.call_trace())\n # print(gg.return_value)\n # import ipdb; ipdb.set_trace()","repo_name":"audleman/crypto","sub_path":"ethereum/brownie/tests/test_lupi.py","file_name":"test_lupi.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"41192872433","text":"\n# ---- 3.12\n\ndef in_bisect(e, t):\n n = len(t)\n if n <= 4:\n return e in t\n\n if e == t[n//2]:\n return True\n elif e < t[n//2]:\n return in_bisect(e, t[:n//2])\n else:\n return in_bisect(e, t[n//2:])\n\n\ndef is_interlocked(e, t, n):\n for i in range(n):\n if not in_bisect(e[i::2], t):\n return False\n return True\n\n\ndef interlocked_words(t, n):\n for word in t:\n if is_interlocked(word, t, n):\n for i in range(n):\n print(word[i::2], end=\",\")\n print(word)\n\n\n# ----\n\nfin = open(\"./exercises/resources/words.txt\")\n\nt = []\n\nfor line in fin:\n word = line.strip()\n t.append(word)\n\nprint(interlocked_words(t, 2))\nprint(interlocked_words(t, 3))\n","repo_name":"mnaR99/ThinkPython2","sub_path":"exercises/ch10/interlock.py","file_name":"interlock.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21002655024","text":"from model.route import Route\nfrom controller.controller import Controller\nfrom repository.repository import Repository\n\nclass Tester:\n def __init__(self):\n self.test()\n\n def test(self):\n x = Route(1,\"24b\",93,3)\n assert(x.getId() == 1)\n x.setId(2)\n assert(x.getId() == 2)\n assert(x.getRouteCode() == \"24b\")\n x.setRouteCode(\"24\")\n assert(x.getRouteCode() == \"24\")\n assert(x.getUsage() == 93)\n x.setUsage(95)\n assert(x.getUsage() == 95)\n assert(x.getBuses() == 3)\n x.setBuses(x.getBuses() + 1)\n assert(x.getBuses() == 4)\n x = Route(1,\"24b\",93,3)\n repo = Repository()\n repo.add(x)\n assert(repo.getRoutes() == [Route(1,\"24b\",93,3)])\n y = Route(13,\"25\",93,7)\n repo.add(y)\n assert(repo.getRoutes() == [Route(1,\"24b\",93,3), Route(13,\"25\",93,7)])\n repo.add(y)\n assert(repo.getRoutes() == [Route(1,\"24b\",93,3), Route(13,\"25\",93,7), Route(13,\"25\",93,7)])","repo_name":"rusucosmin/courses","sub_path":"ubb/fop/BusCompani_exam/tester/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"52"} +{"seq_id":"29879622916","text":"from scipy.misc import imread\nimport numpy as np\nfrom skimage.color import rgb2gray\nfrom scipy import signal\nimport scipy.ndimage.filters as filters\n\ndef read_image(filename, representation):\n \"\"\"\n reads an image file and converts it into a given representation\n :param filename: the filename of an image on disk (could be grayscale or RGB).\n :param representaion: representation code, either 1 or 2 defining\n whether the output should be a grayscaleimage (1) or an RGB image (2)\n :return: image\n \"\"\"\n if representation != 1 and representation != 2:\n raise Exception(\"bad representation\")\n im = imread(filename).astype(np.float64)\n im /= 255\n if representation == 1:\n im = rgb2gray(im)\n return im\n return im\n\ndef blur_spatial(im, kernel_size):\n \"\"\"\n performs image blurring using 2D convolution between the image f and a gaussian kernel g.\n :param im: is the input image to be blurred (grayscale float64 image).\n :param kernel_size: is the size of the gaussian kernel in each dimension (an odd integer).\n :return: The function returns the output blurry image (grayscale float64 image).\n \"\"\"\n\n return signal.convolve2d(im, create_gaussian_2D(kernel_size), mode='same')\n\n\ndef create_gaussian_2D(kernel_size):\n \"\"\"\n Binomial coefficients provide a\tcompact approximation of the gaussian coefficients using only integers.\n the simplest blur filter is [1,1].\n :return: gaussian_2D kernel\n \"\"\"\n if kernel_size == 1:\n return np.array([[1]])\n binomi_base1D = np.array([[1, 1]]).astype(np.float64)\n gaussian_copy_base = binomi_base1D.copy().astype(np.float64)\n num_iter = binomi_base1D.shape[1]\n while num_iter < kernel_size:\n # Convolotion with itself as number of the kernel size\n gaussian_copy_base = signal.convolve2d(gaussian_copy_base, binomi_base1D)\n num_iter += 1\n\n\n # Makes Matrix - filter\n gaussian_2D = np.outer(gaussian_copy_base, gaussian_copy_base)\n\n # Make sure the sum is 1\n gaussian_2D = gaussian_2D/np.sum(gaussian_2D)\n return gaussian_2D\n\n\n\ndef build_gaussian_pyramid(im, max_levels, filter_size):\n \"\"\"\n\n :param im: a grayscale image with double values in [0, 1]\n (e.g. the output of ex1’s read_image with the representationset to 1).\n :param max_levels: the maximal number of levels in the resulting pyramid.\n :param filter_size: the size of the Gaussian filter (an odd scalar that represents a squared filter) to be used\n in constructing the pyramid filter (e.g for filter_size = 3 you should get [0.25, 0.5, 0.25]).\n :return:1. pyramid pyr as a standard python array (i.e. not numpy’s array)\n with maximum length of max_levels, where each element of the array is a grayscale image.\n 2. filter_vec which is row vector of shape (1, filter_size) used\n for the pyramid construction. This filter should be built using a consequent 1D convolutions of [1 1]\n with itself in order to derive a row of the binomial coefficients which is a good approximation to\n the Gaussian profile. The filter_vec should be normalized.\n \"\"\"\n pyr = []\n pyr.append(im)\n filter_vec = create_gaussian_1D(filter_size).reshape((1, filter_size))\n for i in range(1, max_levels):\n reduced_im = reduce(pyr[-1], filter_vec)\n pyr.append(reduced_im)\n\n # checks if dimension is good, if the condition exist the next iteration the dim will be less than 16\n if min(reduced_im.shape[0], reduced_im.shape[1]) < 32: # todo change ?\n return pyr, filter_vec\n\n return pyr, filter_vec\n\n\ndef create_gaussian_1D(kernel_size):\n \"\"\"\n Binomial coefficients provide a\tcompact approximation of the gaussian coefficients using only integers.\n the simplest blur filter is [1,1].\n :return: gaussian_2D kernel\n \"\"\"\n if kernel_size == 1:\n return np.array([[1]])\n binomi_base1D = np.array([1, 1], dtype=np.uint64)\n gaussian_copy_base = binomi_base1D.copy()\n for i in range(kernel_size - 2):\n gaussian_copy_base = signal.convolve(gaussian_copy_base, binomi_base1D)\n gaussian = gaussian_copy_base / np.sum(gaussian_copy_base)\n return gaussian\n\n\n\ndef expand_im(im, filter_vec):\n \"\"\"\n\n :param im:\n :param filter_vec:\n :return:\n \"\"\"\n new_shape_row = 2*im.shape[0]\n new_shape_col =2*im.shape[1]\n expand_im_zeroes = np.zeros((new_shape_row, new_shape_col), dtype=im.dtype)\n expand_im_zeroes[::2, ::2] = im\n convolved_row = filter_vec.reshape((filter_vec.size, 1)) * 2\n convolved_col = convolved_row.transpose()\n blur = filters.convolve(expand_im_zeroes, convolved_row)\n blur = filters.convolve(blur, convolved_col)\n return blur\n\n\ndef laplacian_to_image(lpyr, filter_vec, coeff):\n \"\"\"\n\n :param lpyr: Laplacian pyramid\n :param filter_vec: which is row vector of shape (1, filter_size) used\n for the pyramid construction. This filter should be built using a consequent 1D convolutions of [1 1]\n with itself in order to derive a row of the binomial coefficients which is a good approximation to\n the Gaussian profile. The filter_vec should be normalized.\n :param coeff: python list. The list length is the same as the number of levels in the pyramid lpyr.\n :return:\n \"\"\"\n lpyrCoeff = lpyr * np.array(coeff)\n to_im = lpyrCoeff[-1]\n\n # pass all the L_n from top to bottom\n for i in range(len(lpyr)-1, 0 , -1):\n expanded_im = expand_im(to_im, filter_vec)\n to_im = expanded_im + lpyrCoeff[i - 1]\n\n return to_im\n\n\ndef build_laplacian_pyramid(im, max_levels, filter_size):\n \"\"\"\n\n :param im: a grayscale image with double values in [0, 1]\n (e.g. the output of ex1’s read_image with the representation set to 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 (an odd scalar that represents a squared filter) to be used in constructing the pyramid filter\n (e.g for filter_size = 3 you should get [0.25, 0.5, 0.25]).\n :return:1. pyramid pyr as a standard python array (i.e. not numpy’s array)\n with maximum length of max_levels, where each element of the array is a grayscale image.\n 2. filter_vec which is row vector of shape (1, filter_size) used\n for the pyramid construction. This filter should be built using a consequent 1D convolutions of [1 1]\n with itself in order to derive a row of the binomial coefficients which is a good approximation to\n the Gaussian profile. The filter_vec should be normalized.\n \"\"\"\n pyr = []\n pyr_gaussian, filter_vec = build_gaussian_pyramid(im, max_levels, filter_size)\n for i in range (1, len(pyr_gaussian)):\n expanded_im = expand_im(pyr_gaussian[i], filter_vec)\n substract_im = pyr_gaussian[i-1] - expanded_im\n pyr.append(substract_im)\n\n pyr.append(pyr_gaussian[-1])\n return pyr, filter_vec\n\n\ndef pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask):\n \"\"\"\n\n :param im1: grayscale image to be blended.\n :param im2: grayscale image to be blended.\n :param mask: is a boolean mask containing True and False representing which parts\n of im1 and im2 should appear in the resulting im_blend.\n :param max_levels: – is the max_levels parameter use when generating the Gaussian and Laplacian pyramids.\n :param filter_size_im: is the size of the Gaussian filter which defining the filter used\n in the construction of the Laplacian pyramids of im1 and im2.\n :param filter_size_mask: – is the size of the Gaussian filter which\n defining the filter used in the construction of the Gaussian pyramid of mask.\n :return:\n \"\"\"\n lap_im1, filter_vec1 = build_laplacian_pyramid(im1, max_levels, filter_size_im)\n lap_im2 , filter_vec2= build_laplacian_pyramid(im2, max_levels, filter_size_im)\n mask = mask.astype(np.float64)\n mask_gauss , filter_vec3 = build_gaussian_pyramid(mask, max_levels, filter_size_mask)\n\n laplacian_out = []\n for i in range(len(mask_gauss)):\n laplacian_out.append((mask_gauss[i]*lap_im1[i]) + ((1-mask_gauss[i])* lap_im2[i]))\n\n coeff = [1]*len(laplacian_out)\n im_blend = np.clip(laplacian_to_image(laplacian_out, filter_vec1, coeff), 0, 1)\n return im_blend\n\n\n\ndef reduce(im, filter_vec):\n \"\"\"\n\n :param im:\n :param filter_vec:\n :return:\n \"\"\"\n # Convolotion on both axis (row and col)\n\n blur_image = filters.convolve(im, filter_vec.reshape((filter_vec.size, 1)))\n blur_image = filters.convolve(blur_image, filter_vec.reshape((filter_vec.size, 1)).transpose())\n\n # taking only the even indices to resize the image\n return blur_image[::2, ::2]\n\n\n\n\n\n\n","repo_name":"danielafrimi/Image-Processing","sub_path":"sol4_utils.py","file_name":"sol4_utils.py","file_ext":"py","file_size_in_byte":8724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27791596317","text":"\"\"\"\nDAS query interface based on DAS command line tool by Valentin Kuznetsov\n\"\"\"\n__author__ = \"Nicolo Magini\"\n\nimport logging\nimport re\nimport time\nimport urllib\nimport urllib2\nimport platform\nimport json\n\nlogger = logging.getLogger(__name__)\n\nclass DASInterface:\n \"\"\"\n class to fetch records from DAS\n \"\"\"\n def __init__(self, debug=0):\n self._debug=debug\n if debug:\n hdlr = urllib2.HTTPHandler(debuglevel=1)\n self.opener = urllib2.build_opener(hdlr)\n else:\n self.opener = urllib2.build_opener()\n header='PopDB API/1.0 (CMS) %s/%s %s/%s (%s)' % (urllib2.__name__, urllib2.__version__, platform.system(), platform.release(), platform.processor())\n self.opener.addheaders = [('User-agent', header)]\n self._PidPattern = re.compile(r'^[a-z0-9]{32}')\n \n def isDasPid(self, data):\n if data and isinstance(data, str) and self._PidPattern.match(data) and len(data) == 32:\n return True\n return False\n\n def dasRequest(self, url):\n headers = {\"Accept\": \"application/json\"}\n req = urllib2.Request(url=url, headers=headers)\n fdesc = self.opener.open(req)\n data = fdesc.read()\n fdesc.close()\n return data\n\n def decodeDasData(self, data):\n try:\n dataDict=json.loads(data)\n except ValueError as err:\n logger.error(\"data from DAS could not be decoded to JSON\")\n logger.error(data)\n raise err\n try:\n queryStatus=dataDict['status']\n except KeyError as err:\n logger.error(\"no status key in DAS record\")\n logger.error(data)\n raise err\n if queryStatus == 'ok':\n try:\n if (dataDict['nresults']==0 or not dataDict['data']):\n logger.warning('query did not return any result')\n logger.warning(data)\n except KeyError as err:\n logger.error(\"missing key in DAS record\")\n logger.error(data)\n raise err\n return dataDict\n elif queryStatus == 'fail':\n msg='DAS query failed'\n logger.info(msg)\n logger.debug('DAS record:')\n logger.debug(data)\n try:\n msg+=' - Failure reason: \\n'+dataDict['reason']+'\\n'\n except KeyError:\n msg+='No reason provided'\n raise ValueError(msg)\n else:\n msg='Unrecognized DAS query status: %s' % queryStatus\n raise ValueError(msg)\n \n def get_das_data(self, host, query, idx=0, limit=0):\n \"\"\"Contact DAS server and retrieve data for given DAS query\"\"\"\n params = {'input':query, 'idx':idx, 'limit':limit}\n path = '/das/cache'\n pat = re.compile('http[s]{0,1}://')\n if not pat.match(host):\n msg = 'Invalid hostname: %s' % host\n raise Exception(msg)\n url = host + path\n encoded_data = urllib.urlencode(params, doseq=True)\n url += '?%s' % encoded_data\n\n data = self.dasRequest(url)\n \n if self.isDasPid(data):\n pid = data\n else:\n pid = None\n count = 5 # initial waiting time in seconds\n while pid:\n params.update({'pid':data})\n encoded_data = urllib.urlencode(params, doseq=True)\n url = host + path + '?%s' % encoded_data\n\n data = self.dasRequest(url)\n \n if self.isDasPid(data):\n pid = data\n else:\n pid = None\n time.sleep(count)\n if count < 30:\n count *= 2\n else:\n count = 30\n\n return self.decodeDasData(data)\n\n\n \n","repo_name":"dmwm/DDM","sub_path":"DataPopularity/popdb.web/lib/Apps/popCommon/utils/dasInterface/dasInterface.py","file_name":"dasInterface.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"32880148268","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2021/5/5 0:47\n# @Author : 10711\n# @File : Collection151.py\n# @Software: PyCharm\n\n\nfrom ..items import *\nfrom ..str_filter import *\nfrom ..auxiliary_files import Collection151_supporting\n\n\nclass Collection151(scrapy.Spider):\n name = \"Collection151\"\n allowed_domains = ['gzam.com.cn']\n start_urls = Collection151_supporting.Collection151Supporting.startUrl\n\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'mySpider.pipelines.CollectionPipeLine': 301,\n }\n }\n def parse(self, response, **kwargs):\n li_list = response.xpath(\"//*[@id='wrapper']/div[1]/div[1]/section/section/div[2]/article/dl/dd\")\n print(len(li_list))\n for li in li_list:\n item = CollectionItem()\n item[\"museumID\"] = 151\n item[\"museumName\"] = \"广州艺术博物院\"\n item['collectionImageLink'] = StrFilter.getDoamin(response) + str(\n li.xpath(\"./a/img/@src\").extract_first())\n url = StrFilter.getDoamin(response) + str(\n li.xpath(\"./a/@href\").extract_first())\n yield scrapy.Request(\n url,\n callback=self.parseAnotherPage,\n meta={\"item\": item}\n )\n\n def parseAnotherPage(self, response):\n item = response.meta[\"item\"]\n item['collectionName'] = StrFilter.filter(\n response.xpath(\"//*[@id='wrapper']/div[1]/div[1]/section/section/div[2]/article/div[2]/p[1]\").xpath('string(.)').extract_first())\n item['collectionIntroduction'] = StrFilter.filter(\n response.xpath(\"//*[@id='wrapper']/div[1]/div[1]/section/section/div[2]/article/div[2]\").xpath('string(.)').extract_first())\n if item['collectionName'] != 'None' and item['collectionName'] != '' and len(item['collectionName']) < 50:\n print(item)\n yield(item)","repo_name":"CS1803-SE/The-First-Subsystem","sub_path":"mySpider/spiders/Collection151.py","file_name":"Collection151.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37616998948","text":"from flask import Blueprint, request\nfrom schematics.exceptions import DataError\n\nfrom .request.types import VowelCountRequestApiType, SortWordsRequestApiType\nfrom .response.types import VowelCountResponseApiType, SortWordsResponseApiType\nfrom ..core.enums.http_status import HttpStatus\n\nbp = Blueprint('words', __name__)\n\n\n@bp.route('/vowel_count', methods=['POST'])\ndef vowel_count():\n payload = request.json\n\n try:\n result = VowelCountRequestApiType(payload).run()\n except DataError:\n return {}, HttpStatus.BAD_REQUEST.status_code\n\n response = VowelCountResponseApiType({'words': result})\n\n return response.to_response(), HttpStatus.OK.status_code\n\n\n@bp.route('/sort', methods=['POST'])\ndef sort_words():\n payload = request.json\n\n try:\n result = SortWordsRequestApiType(payload).run()\n except (DataError, ValueError):\n return {}, HttpStatus.BAD_REQUEST.status_code\n\n response = SortWordsResponseApiType({'words': result})\n\n return response.to_response(), HttpStatus.OK.status_code\n","repo_name":"maikyguanaes/cornerstone","sub_path":"cornerstone/words/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35512587735","text":"import tensorflow as tf\nimport numpy as np\nimport sys\nfrom tensorflow.python.keras.backend import set_session\nfrom keras import backend as K\nimport sharedLayers\n\ndef efficient_attention(input_, in_channels, key_channels, head_count, value_channels):\n\tn, c, h, w = input_.get_shape().as_list()\n\tinput_ = tf.transpose(input_, perm=[0,2,3,1])\n\n\tratio = np.sqrt(n/c)\n\trand = tf.compat.v1.keras.initializers.RandomUniform(minval=-ratio, maxval=ratio, seed=None)\n\tkeys = tf.keras.layers.Conv2D(key_channels, 1, \n\t\tkernel_initializer=rand, bias_initializer=rand)(input_)\n\tqueries = tf.keras.layers.Conv2D(key_channels, 1, \n\t\tkernel_initializer=rand, bias_initializer=rand)(input_)\n\tvalues = tf.keras.layers.Conv2D(value_channels, 1, \n\t\tkernel_initializer=rand, bias_initializer=rand)(input_)\n\n\t# keys = sharedLayers.conv2D(input_[1, 1, c, key_channels])\n\t# queries = sharedLayers.conv2D(input_[1, 1, c, key_channels])\n\t# keys = sharedLayers.conv2D(input_[1, 1, c, value_channels])\n\t\n\tkeys = tf.reshape(keys, [n, key_channels, h * w])\n\tqueries = tf.reshape(queries, [n, key_channels, h * w])\n\tvalues = tf.reshape(values, [n, value_channels, h * w])\n\n\thead_key_channels = key_channels // head_count\n\thead_value_channels = value_channels // head_count\n\n\tattended_values = []\n\tfor i in range(head_count):\n\t key = tf.nn.softmax(keys[:,i * head_key_channels: (i + 1) * head_key_channels, :], axis=2)\n\t query = tf.nn.softmax(queries[:, i * head_key_channels: (i + 1) * head_key_channels,:], axis=1)\n\t value = values[:, i * head_value_channels: (i + 1) * head_value_channels, :]\n\t \n\t context = key @ tf.transpose(value, perm=[0, 2, 1])\n\t attended_value = tf.reshape(\n\t tf.transpose(context, perm=[0, 2, 1]) @ query,\n\t [n, head_value_channels, h, w])\n\t attended_values.append(attended_value)\n\n\taggregated_values = tf.concat(attended_values, 1)\n\taggregated_values = tf.transpose(aggregated_values, perm=[0,2,3,1])\n\treprojected_value = tf.keras.layers.Conv2D(in_channels, 1, \n\t\tkernel_initializer=rand, bias_initializer=rand)(aggregated_values)\n\t\n\treprojected_value = tf.transpose(reprojected_value, perm=[0,3,1,2])\n\tinput_ = tf.transpose(input_, perm=[0,3,1,2])\n\tattention = reprojected_value + input_\n\treturn attention\n\nif __name__ == \"__main__\":\n\tx = tf.constant([[[[1, 5], [8, 10]]]], dtype=tf.float32)\n\tt = efficient_attention(x, 1, 2, 2, 4)\n\tsess = tf.keras.backend.get_session()\n\tprint(t.get_shape())\n\tprint(sess.run(t))\n\n","repo_name":"Lipai-1994/Real_time_self_adaptive_network","sub_path":"Nets/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73755550886","text":"#!/usr/bin/env python\nimport itertools\nimport os\nimport shutil\nimport sys\nfrom pathlib import Path\nfrom argparse import ArgumentParser, Namespace, ArgumentDefaultsHelpFormatter\nfrom importlib.metadata import Distribution\nfrom typing import Optional\nfrom concurrent.futures import ThreadPoolExecutor\nimport subprocess as sp\nfrom chris_plugin import chris_plugin, PathMapper\nfrom loguru import logger\n\n\n__pkg = Distribution.from_name(__package__)\n__version__ = __pkg.version\n\n\nDISPLAY_TITLE = r\"\"\"\n _ _____ _____ __ __ _ _ \n| | / __ \\| _ | / _| / _(_) | \n| | __ _ `' / /' \\ V / __ _ __ _ ___ _ _ _ __| |_ __ _ ___ ___ | |_ _| |_ \n| |/ _` | / / / _ \\ / _` |/ _` | / __| | | | '__| _/ _` |/ __/ _ \\ | _| | __|\n| | (_| |./ /___| |_| | (_| | (_| | \\__ \\ |_| | | | || (_| | (_| __/ | | | | |_ \n|_|\\__, |\\_____/\\_____/\\__, |\\__,_| |___/\\__,_|_| |_| \\__,_|\\___\\___| |_| |_|\\__|\n __/ | __/ | ______ \n |___/ |___/ |______| \n\n inwards surface_fit for <=28 GA fetal brains\n\n\"\"\"\n\nparser = ArgumentParser(description='surface_fit wrapper',\n formatter_class=ArgumentDefaultsHelpFormatter)\nparser.add_argument('--no-fail', dest='no_fail', action='store_true',\n help='Produce exit code 0 even if any subprocesses do not.')\nparser.add_argument('--strategy', type=str, default='plain',\n help='name of surface_fit parameter schedule strategy to use')\nparser.add_argument('-V', '--version', action='version',\n version=f'%(prog)s {__version__}')\n\n\n@chris_plugin(\n parser=parser,\n title='surface_fit experiment',\n category='Experimental',\n min_memory_limit='1Gi',\n min_cpu_limit='1000m',\n)\ndef main(options: Namespace, inputdir: Path, outputdir: Path):\n print(DISPLAY_TITLE, file=sys.stderr, flush=True)\n\n params = [\n '-strategy',\n options.strategy\n ]\n\n nproc = len(os.sched_getaffinity(0))\n logger.info('Using {} threads.', nproc)\n\n mapper = PathMapper.file_mapper(inputdir, outputdir, glob='**/*.mnc')\n with ThreadPoolExecutor(max_workers=nproc) as pool:\n results = pool.map(lambda t, p: run_surface_fit(*t, p), mapper, itertools.repeat(params))\n\n if not options.no_fail and not all(results):\n sys.exit(1)\n\n\ndef run_surface_fit(mask: Path, output_mask: Path, params: list[str]) -> bool:\n \"\"\"\n :return: True if successful\n \"\"\"\n surface = locate_surface_for(mask)\n if surface is None:\n logger.error('No starting surface found for {}', mask)\n return False\n\n shutil.copy(mask, output_mask)\n output_surf = output_mask.with_suffix('._81920.obj')\n cmd = ['surface_fit_script.pl', *params, output_mask, surface, output_surf]\n log_file = output_surf.with_name(output_surf.name + '.log')\n logger.info('Starting: {}', ' '.join(map(str, cmd)))\n with log_file.open('wb') as log_handle:\n job = sp.run(cmd, stdout=log_handle, stderr=log_handle)\n rc_file = log_file.with_suffix('.rc')\n rc_file.write_text(str(job.returncode))\n\n if job.returncode == 0:\n logger.info('Finished: {} -> {}', mask, output_surf)\n return True\n\n logger.error('FAILED -- check log file for details: {}', log_file)\n return False\n\n\ndef locate_surface_for(mask: Path) -> Optional[Path]:\n glob = mask.parent.glob('*.obj')\n first = next(glob, None)\n second = next(glob, None)\n if second is not None:\n return None\n return first\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"FNNDSC/ep-lt28ga-subplate-fit","sub_path":"lt28ga_surface_fit.py","file_name":"lt28ga_surface_fit.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14526213799","text":"import streamlit as st\r\nimport pandas as pd\r\nfrom sklearn.linear_model import LinearRegression\r\n\r\nst.subheader(\"\"\"\r\nSimple House Renovation App\r\n\"\"\")\r\n\r\nst.write(\"\"\"\r\nThis app predicts the price of a house renovation!\r\n\"\"\")\r\n\r\nst.sidebar.header('User Input Parameters')\r\n\r\ndef user_input_features():\r\n bedroom_input = st.sidebar.slider('Bedrooms', 0, 10, 3)\r\n bathroom_input = st.sidebar.slider('Bathrooms', 1, 5, 2)\r\n kitchen_input = st.sidebar.slider('Kitchen', 0, 1, 1)\r\n painting_input = st.sidebar.slider('Rooms Painted', 1, 10, 4)\r\n \r\n data = {'Bedrooms': bedroom_input,\r\n 'Bathrooms': bathroom_input,\r\n 'Kitchen': kitchen_input,\r\n 'Rooms Painted': painting_input\r\n }\r\n features = pd.DataFrame(data, index=[0])\r\n return features\r\n\r\ninput = user_input_features()\r\n\r\nst.subheader('User Input parameters')\r\nst.write(input)\r\n\r\ndf = pd.read_csv(r\"C:\\Users\\bbste\\Documents\\Coding\\Python\\Machine Learning\\Estimates Data.csv\")\r\nX = df[['Bedrooms', 'Bathrooms', 'Kitchen', 'Rooms Painted']]\r\nY = df['Price']\r\n\r\nmodel = LinearRegression()\r\nmodel.fit(X, Y)\r\n\r\nprediction = model.predict(input)\r\n\r\nst.subheader('Prediction')\r\nst.write(prediction)\r\n\r\n# st.subheader('Prediction')\r\n# st.write(df[prediction])\r\n# #st.write(prediction)\r\n\r\n# st.subheader('Prediction Probability')\r\n# st.write(prediction)","repo_name":"BSteiner1/Streamlit-App-Predictor","sub_path":"job-price-predictor.py","file_name":"job-price-predictor.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37644418033","text":"import numpy as np\nimport torch\n\n\nclass EarlyStopping(object):\n def __init__(self, args, checkpoint_dir: str, mode=\"min\"):\n self.patience = args.patience\n self.delta = args.delta\n self.checkpoint_dir = checkpoint_dir\n\n assert mode in (\"min\", \"max\"), \"mode should be 'min' or 'max'\"\n self.mode = mode\n self.best_eval_loss = np.Inf if mode == \"min\" else -np.Inf\n\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n\n def __call__(self, eval_loss, checkpoint):\n score = -eval_loss if self.mode == \"min\" else eval_loss\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(eval_loss, checkpoint)\n\n elif score < self.best_score + self.delta:\n self.counter += 1\n print(f\"EarlyStopping counter: {self.counter} out of {self.patience}\")\n if self.counter >= self.patience:\n self.early_stop = True\n else:\n print(f\"Validation loss decreased: {self.best_eval_loss:.5f} --> {eval_loss:.5f}\")\n self.best_score = score\n self.save_checkpoint(eval_loss, checkpoint)\n self.counter = 0\n return self.checkpoint_dir\n\n def save_checkpoint(self, eval_loss, checkpoint):\n print(\"Save trained model...\")\n\n torch.save(checkpoint, self.checkpoint_dir)\n self.best_eval_loss = eval_loss\n","repo_name":"ivoryRabbit/hrnn-pytorch","sub_path":"src/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"18032055824","text":"\nimport os\nimport pandas as pd\nimport requests\nstock_symbols = [i for i in os.environ.get(\"STOCKS\").split(\" \")]\n\n\ndef get_data(stock: str)->pd.Dataframe:\n r = requests.get(\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=SPY&apikey=\"+API_KEY)\n data_dict = r.json()['Time Series (Daily)']\n\n return 0\n\ndef calc_rsi(stock: str='JPM', start_date: dt.datetime=dt.datetime(2008,1,1), end_date : dt.datetime = dt.datetime(2009,12,31))->None:\n\n lookback = 20\n stock_data = get_data([stock], pd.date_range(start_date, end_date), addSPY=True)\n stock_data.drop(['SPY'], axis=1, inplace=True)\n stock_data.loc[1:,'daily_returns'] = stock_data[stock].iloc[1:].values - stock_data[stock].iloc[:-1].values\n stock_data.reset_index(inplace=True)\n stock_data.rename(columns={'index': 'Date'}, inplace=True)\n\n stock_data['up_gain'] = np.zeros(stock_data.shape[0], dtype=float)\n stock_data['down_loss'] = np.zeros(stock_data.shape[0], dtype=float)\n stock_data['rsi'] = np.zeros(stock_data.shape[0], dtype=float)\n\n for day in range(lookback, stock_data.shape[0]):\n\n stock_data['up_gain'] = stock_data.loc[day-lookback+1:day+1,'daily_returns'].where(stock_data['daily_returns']>=0).sum()\n stock_data['down_loss'] = -1*stock_data.loc[day-lookback+1:day+1,'daily_returns'].where(stock_data['daily_returns']<0).sum()\n\n if stock_data.loc[day, 'down_loss'] == 0:\n stock_data.loc[day, 'rsi'] = 100\n else:\n rs = (stock_data.loc[day, 'up_gain'] / lookback) / (stock_data.loc[day, 'down_loss'] / lookback)\n stock_data.loc[day, 'rsi'] = 100-(100/(1+rs))\n\n stock_data['rsi'].values[:lookback] = np.nan\n\n # Plot data\n ax = stock_data.plot(x='Date', y='rsi', title=f'{lookback} Day RSI for {stock}')\n ax.set_xlabel(\"Date\")\n ax.set_ylabel(\"RSI\")\n plt.plot((start_date, end_date), (70, 70), linestyle='-', color='red')\n plt.plot((start_date, end_date), (30, 30), linestyle='-', color='red')\n plt.savefig('./RSI')\n\n\ndef calc_momentum(stock: str='JPM', start_date: dt.datetime=dt.datetime(2008,1,1), end_date : dt.datetime = dt.datetime(2009,12,31)):\n\n lookback = 20\n stock_data = get_data([stock], pd.date_range(start_date, end_date), addSPY=True)\n stock_data.drop(['SPY'], axis=1, inplace=True)\n stock_data.loc[1:,'daily_returns'] = stock_data[stock].iloc[1:].values - stock_data[stock].iloc[:-1].values\n stock_data.reset_index(inplace=True)\n stock_data.rename(columns={'index': 'Date'}, inplace=True)\n\n stock_data['momentum'] = np.zeros(stock_data.shape[0], dtype=float)\n stock_data.loc[:lookback-1,'momentum'] = np.nan\n stock_data.loc[lookback:, 'momentum'] = (stock_data.loc[lookback:, stock] - stock_data[stock].values[:-20]) / stock_data[stock].values[:-20]\n\n # Plot data\n ax = stock_data.plot(x='Date', y='momentum', title=f'{lookback} Day Momentum for Stock {stock}')\n ax.set_xlabel(\"Date\")\n ax.set_ylabel(\"Momentum\")\n ax.axhline(color='black')\n plt.savefig('./Momentum')\n\n\ndef calc_volatility(stock: str='JPM', lookback: int=20, start_date: dt.datetime=dt.datetime(2008,1,1), end_date : dt.datetime = dt.datetime(2009,12,31)):\n\n stock_data = get_data([stock], pd.date_range(start_date, end_date), addSPY=True)\n stock_data.drop(['SPY'], axis=1, inplace=True)\n stock_data.loc[1:, 'daily_returns'] = stock_data[stock].iloc[1:].values - stock_data[stock].iloc[:-1].values\n stock_data.reset_index(inplace=True)\n stock_data.rename(columns={'index': 'Date'}, inplace=True)\n\n stock_data.loc[1:,'daily_returns'] = stock_data[stock].iloc[1:].values - stock_data[stock].iloc[:-1].values\n\n stock_data['volatility'] = np.zeros(stock_data.shape[0], dtype=float)\n stock_data['volatility'] = stock_data['daily_returns'].rolling(lookback).std()\n\n # Plot data\n ax = stock_data.plot(x='Date', y='volatility', title=f'{lookback} Day Volatility for Stock {stock}')\n ax.set_xlabel(\"Date\")\n ax.set_ylabel(\"Volatility Index\")\n plt.savefig('./Volatility')\n\n\ndef calc_stochastic_oscillator(stock: str='JPM', lookback: int=15, start_date: dt.datetime=dt.datetime(2008,1,1), end_date : dt.datetime = dt.datetime(2008,12,31)):\n\n stock_data = get_data([stock], pd.date_range(start_date, end_date), addSPY=True)\n stock_data.drop(['SPY'], axis=1, inplace=True)\n stock_data.loc[1:,'daily_returns'] = stock_data[stock].iloc[1:].values - stock_data[stock].iloc[:-1].values\n stock_data.reset_index(inplace=True)\n stock_data.rename(columns={'index': 'Date'}, inplace=True)\n\n stock_data['max_five_day'] = stock_data[stock].rolling(lookback).max()\n stock_data['min_five_day'] = stock_data[stock].rolling(lookback).min()\n stock_data['pct_k'] = 100 * (stock_data[stock] - stock_data['min_five_day']) / (stock_data['max_five_day'] - stock_data['min_five_day'])\n stock_data['pct_d'] = stock_data['pct_k'].rolling(3).mean()\n\n # plot k and d, with reference lines at 80 and 20\n ax = stock_data.plot(x='Date', y='pct_k', linestyle='-', title=f'{lookback} Day Stochastic Oscillator for Stock {stock}')\n stock_data.plot(x='Date', y='pct_d', linestyle=':' ,ax=ax)\n plt.plot((start_date, end_date), (80, 80), linestyle='-', color='red')\n plt.plot((start_date, end_date), (20, 20), linestyle='-', color='red')\n xs = np.arange(start_date, end_date, dt.timedelta(1))\n plt.fill_between(xs, 20, 80, color='red', alpha='0.5')\n ax.set_xlabel(\"Date\")\n ax.set_ylabel(\"Percent\")\n plt.savefig('./StochasticOscillator')\n\n\ndef test_code():\n\n # Call technical indicator functions\n calc_bb()\n calc_rsi()\n calc_momentum()\n calc_volatility()\n calc_stochastic_oscillator()\n\nif __name__ == '__main__':\n test_code()","repo_name":"solb0039/Airflow","sub_path":"indicators/technical_indicators.py","file_name":"technical_indicators.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34426395331","text":"#!/usr/bin/env python3\n# dnsmadeeasy hook for letsencrypt.sh\n# http://www.dnsmadeeasy.com/integration/pdf/API-Docv2.pdf\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom builtins import str\n\nfrom future import standard_library\nstandard_library.install_aliases()\n\nimport dns.exception\nimport dns.resolver\nimport logging\nimport os\nimport requests\nimport sys\nimport time\n\nfrom email.utils import formatdate\nfrom datetime import datetime\nfrom time import mktime\nimport hashlib, hmac\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.INFO)\n\n# Calculate RFC 1123 HTTP/1.1 date\nnow = datetime.now()\nstamp = mktime(now.timetuple())\nrequestDate = formatdate(\n timeval = stamp,\n localtime = False,\n usegmt = True\n)\n\ntry:\n DME_HEADERS = {\n 'x-dnsme-apiKey': os.environ['DME_API_KEY'],\n 'x-dnsme-hmac': hmac.new(os.environ['DME_SECRET_KEY'].encode('ascii'), requestDate.encode('ascii'), hashlib.sha1).hexdigest(),\n 'x-dnsme-requestDate': requestDate,\n 'Content-Type': 'application/json',\n }\nexcept KeyError:\n logger.error(\" + Unable to locate dnsmadeeasy credentials in environment!\")\n sys.exit(1)\n\ntry:\n DME_SERVER=os.environ['DME_SERVER']\nexcept:\n DME_SERVER='production'\n\nDME_API_BASE_URL = {\n 'production': 'https://api.dnsmadeeasy.com/V2.0/dns/managed',\n 'staging': 'http://api.sandbox.dnsmadeeasy.com/V2.0/dns/managed'\n}\n\ntry:\n dns_servers = os.environ['QUERY_DNS_SERVERS']\n dns_servers = dns_servers.split()\nexcept KeyError:\n dns_servers = False\n\ndef _has_dns_propagated(name, token):\n txt_records = []\n try:\n if dns_servers:\n custom_resolver = dns.resolver.Resolver(configure=False)\n custom_resolver.nameservers = dns_servers\n dns_response = custom_resolver.query(name, 'TXT')\n else:\n dns_response = dns.resolver.query(name, 'TXT')\n for rdata in dns_response:\n for txt_record in rdata.strings:\n txt_records.append(txt_record.decode())\n except dns.exception.DNSException as error:\n return False\n\n for txt_record in txt_records:\n if txt_record == bytearray(token, 'ascii'):\n return True\n\n return False\n\n# http://api.dnsmadeeasy.com/V2.0/dns/managed/id/{domainname}\ndef _get_zone_id(domain):\n # allow both tlds and subdomains hosted on DNSMadeEasy\n tld = domain[domain.find('.')+1:]\n url = DME_API_BASE_URL[DME_SERVER]\n r = requests.get(url, headers=DME_HEADERS)\n r.raise_for_status()\n for record in r.json()['data']:\n if (record['name'] == tld) or (\".\" + record['name'] in tld):\n return record['id']\n logger.error(\" + Unable to locate zone for {0}\".format(tld))\n sys.exit(1)\n\n# http://api.dnsmadeeasy.com/V2.0/dns/managed/id/{domainname}\ndef _get_zone_name(domain):\n # allow both tlds and subdomains hosted on DNSMadeEasy\n tld = domain[domain.find('.')+1:]\n url = DME_API_BASE_URL[DME_SERVER]\n r = requests.get(url, headers=DME_HEADERS)\n r.raise_for_status()\n for record in r.json()['data']:\n if (record['name'] == tld) or (\".\" + record['name'] in tld):\n return record['name']\n logger.error(\" + Unable to locate zone for {0}\".format(tld))\n sys.exit(1)\n\n\n# http://api.dnsmadeeasy.com/V2.0/dns/managed/{domain_id}/records?type=TXT&recordName={name}\ndef _get_txt_record_id(zone_id, name):\n url = DME_API_BASE_URL[DME_SERVER] + \"/{0}/records?type=TXT&recordName={1}\".format(zone_id, name)\n r = requests.get(url, headers=DME_HEADERS)\n r.raise_for_status()\n try:\n record_id = r.json()['data'][0]['id']\n except IndexError:\n logger.info(\" + Unable to locate record named {0}\".format(name))\n return\n\n return record_id\n\n\n# http://api.dnsmadeeasy.com/V2.0/dns/managed/{domain_id}/records\ndef create_txt_record(args):\n domain, token = args[0], args[2]\n zone_id = _get_zone_id(domain)\n name = \"{0}.{1}\".format('_acme-challenge', domain)\n short_name = \"{0}.{1}\".format('_acme-challenge', domain[0:-(len(_get_zone_name(domain))+1)])\n url = DME_API_BASE_URL[DME_SERVER] + \"/{0}/records\".format(zone_id)\n payload = {\n 'type': 'TXT',\n 'name': short_name,\n 'value': token,\n 'ttl': 5,\n }\n r = requests.post(url, headers=DME_HEADERS, json=payload)\n r.raise_for_status()\n record_id = r.json()['id']\n logger.debug(\" + TXT record created, ID: {0}\".format(record_id))\n\n # give it 10 seconds to settle down and avoid nxdomain caching\n logger.info(\" + Settling down for 10s...\")\n time.sleep(10)\n\n retries=2\n while(_has_dns_propagated(name, token) == False and retries > 0):\n logger.info(\" + DNS not propagated, waiting 30s...\")\n retries-=1\n time.sleep(30)\n\n if retries <= 0:\n logger.error(\"Error resolving TXT record in domain {0}\".format(domain))\n sys.exit(1)\n\n# http://api.dnsmadeeasy.com/V2.0/dns/managed/{domain_id}/records\ndef delete_txt_record(args):\n domain, token = args[0], args[2]\n if not domain:\n logger.info(\" + http_request() error in letsencrypt.sh?\")\n return\n\n zone_id = _get_zone_id(domain)\n name = \"{0}.{1}\".format('_acme-challenge', domain)\n short_name = \"{0}.{1}\".format('_acme-challenge', domain[0:-(len(_get_zone_name(domain))+1)])\n record_id = _get_txt_record_id(zone_id, short_name)\n\n logger.debug(\" + Deleting TXT record name: {0}\".format(name))\n url = DME_API_BASE_URL[DME_SERVER] + \"/{0}/records/{1}\".format(zone_id, record_id)\n r = requests.delete(url, headers=DME_HEADERS)\n r.raise_for_status()\n\n\ndef deploy_cert(args):\n domain, privkey_pem, cert_pem, fullchain_pem, chain_pem, timestamp = args\n logger.info(' + ssl_certificate: {0}'.format(fullchain_pem))\n logger.info(' + ssl_certificate_key: {0}'.format(privkey_pem))\n return\n\ndef main(argv):\n hook_name, args = argv[0], argv[1:]\n\n ops = {\n 'deploy_challenge': create_txt_record,\n 'clean_challenge' : delete_txt_record,\n 'deploy_cert' : deploy_cert,\n }\n\n if hook_name in ops.keys():\n logger.info(' + dnsmadeeasy hook executing: %s', hook_name)\n ops[hook_name](args)\n else:\n logger.debug(' + dnsmadeeasy hook not executing: %s', hook_name)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"petrgru/dehydrated","sub_path":"hooks/dnsmadeeasy/hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":6469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"300632997","text":"import unittest\nimport os\nfrom taglib import File\nfrom rfat import *\n\n\nclass TestTransliterate(unittest.TestCase):\n \"\"\"\n Class for testing transliterate function\n \"\"\"\n def test_ukrainian_symbols(self):\n \"\"\"\n Ukrainian symbols are properly transliterated\n \"\"\"\n string = \"Минає ніч від’їзду\"\n expected = \"Minaye nich vid’yizdu\"\n self.assertEqual(transliterate(string), expected)\n\n def test_empty_string(self):\n \"\"\"\n Empty string should return empty string\n \"\"\"\n string = \"\"\n expected = \"\"\n self.assertEqual(transliterate(string), expected)\n\n def test_no_cyrillic_string(self):\n \"\"\"\n If no cyrillic string should return string unchanged\n \"\"\"\n string = \"test\"\n expected = \"test\"\n self.assertEqual(transliterate(string), expected)\n\n\nclass TestRenamer(unittest.TestCase):\n \"\"\"\n Test filename translation\n \"\"\"\n\n def tearDown(self):\n \"\"\"\n Remove all mp3s\n \"\"\"\n audios = filter(lambda x: x.endswith(\".mp3\"), os.listdir())\n if audios:\n for audio in audios:\n os.remove(audio)\n\n def test_filename_transliterate(self):\n \"\"\"\n Given audio filename with cyrillic symbols shouldn't change extension\n \"\"\"\n string = \"тест.mp3\"\n expected = \"test.mp3\"\n self.assertEqual(transliterate(string), expected)\n\n def test_bunch_of_files(self):\n \"\"\"\n Bunch of files should be properly renamed\n \"\"\"\n bunch = [\"1.тест.mp3\", \"2.smash.mp3\", \"3.дdд.mp3\"]\n expected = [\"1.test.mp3\", \"2.smash.mp3\", \"3.ddd.mp3\"]\n for audio in bunch:\n f = open(audio, 'w+')\n f.close()\n audios = filter(lambda x: x.endswith(\".mp3\"), os.listdir())\n for audio in audios:\n rename_audio(audio)\n audios = filter(lambda x: x.endswith(\".mp3\"), os.listdir())\n for a, b in zip(audios, expected):\n print(a, b)\n for filename, expectation in zip(audios, expected):\n self.assertEqual(filename, expectation)\n\n\nclass TestTagsFiller(unittest.TestCase):\n \"\"\"\n Class for testing fill_tags\n \"\"\"\n def test_simple_tags_filling(self):\n \"\"\"\n \"\"\"\n filename = \"test.mp3\"\n tracknumber = 1\n f = open(filename, 'w+')\n f.close()\n audio = File(filename)\n audio.tags['TITLE'] = \"fill\"\n audio.tags['TRACKNUMBER'] = \"2\"\n audio.save()\n fill_tags(filename, tracknumber)\n audio = File(filename)\n self.assertEqual(audio.tags['TITLE'], [os.path.splitext(filename)[-1]])\n self.assertEqual(audio.tags['TRACKNUMBER'], [str(tracknumber)])\n with self.assertRaises(KeyError):\n audio.tags['ARTIST']\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"GriMel/RFAT","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74753468965","text":"# -*- coding: utf-8 -*-\r\nfrom .basefuncs import *\r\nfrom .classbit import Bit\r\n\r\nbiops = {\r\n '+': lambda a, b: a | b,\r\n '&': lambda a, b: a & b,\r\n '^': lambda a, b: a ^ b,\r\n '.': lambda a, b: a + b,\r\n '>>': lambda a, b: a >> b,\r\n '<<': lambda a, b: a << b,\r\n '!+': lambda a, b: ~(a | b),\r\n '!&': lambda a, b: ~(a & b),\r\n '!^': lambda a, b: ~(a ^ b),\r\n '@': lambda a, b: a[int(b)],\r\n '_': lambda a, b: a.mxl(b)\r\n}\r\n\r\nuniops = {\r\n '!': lambda x: ~x,\r\n '#': lambda x: x.hash(),\r\n '$': lambda x: x[0],\r\n '£': lambda x: x[-1]\r\n}\r\n\r\ninputs = {\r\n 'I>': 'Integer',\r\n 'S>': 'String',\r\n 'H>': 'Hex',\r\n '>': 'Binary'\r\n}\r\ninputf = {\r\n 'I>': lambda x: bin(int(x))[2:],\r\n 'S>': lambda st: ''.join(format(ord(x), 'b').zfill(8) for x in st),\r\n 'H>': lambda x: bin(int(x, 16))[2:],\r\n '>': lambda x: x\r\n}\r\noutputf = {\r\n 'I<': int,\r\n 'S<': lambda bits: int(bits).to_bytes((int(bits).bit_length() + 7) // 8, 'big').decode(),\r\n 'H<': lambda x: hex(int(x))[2:],\r\n '<': lambda x: x.st\r\n}\r\n\r\n\r\nclass vl(dict):\r\n def __getitem__(self, index):\r\n try:\r\n return dict.__getitem__(self, index)\r\n except KeyError:\r\n raiseErrN(\r\n 'ReferenceError: Variable \\'%s\\' referenced before assignment.' % (index))\r\n\r\n\r\ndef litEval(t):\r\n return Bit(t.value)\r\n\r\n\r\ndef idEval(t, varis):\r\n # print(t, varis)\r\n return varis[t.value]\r\n\r\n\r\ndef expEval(t, varlist):\r\n if t.tag == ID:\r\n return idEval(t, varlist)\r\n elif t.tag == LITERAL:\r\n return litEval(t)\r\n elif t.tag == 'BIOPEXP':\r\n t0 = expEval(t.args[0], varlist)\r\n t1 = expEval(t.args[1], varlist)\r\n return biops[t.value](t0, t1)\r\n elif t.tag == 'UNIOPEXP':\r\n arg = expEval(t.args, varlist)\r\n if t.value == \"'\":\r\n return arg[int(varlist['\"'])]\r\n else:\r\n return uniops[t.value](arg)\r\n\r\n\r\ndef stateRun(s, varlist):\r\n # print(s)\r\n if s.tag == 'ASOPS':\r\n varlist[s.value] = expEval(s.args, varlist)\r\n elif s.tag == 'IOSTATES':\r\n v = s.value\r\n if v[-1] == '>':\r\n a = inputf[v](input(inputs[v] + ': '))\r\n varlist[s.args.value] = Bit(a)\r\n else:\r\n print(outputf[v](expEval(s.args, varlist)))\r\n else:\r\n doCond(s, varlist)\r\n\r\n\r\ndef doCond(st, varl):\r\n # print(st)\r\n toch = expEval(st.args[0], varl)\r\n if st.value == '-':\r\n for q in range(len(toch)):\r\n varl['\"'] = Bit(bin(q)[2:])\r\n runStates(st.args[1:], varl)\r\n elif st.value == '?':\r\n if int(toch):\r\n runStates(st.args[1:], varl)\r\n else:\r\n for p in range(len(toch)):\r\n varl['\"'] = Bit(bin(len(toch) - p - 1)[2:])\r\n runStates(st.args[1:], varl)\r\n\r\n\r\ndef runStates(tls, varls=vl()):\r\n for t in tls:\r\n stateRun(t, varls)\r\n return varls\r\n","repo_name":"Genora51/Bitwise","sub_path":"blib/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"41690931314","text":"#importing classes\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn import linear_model\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.metrics import fbeta_score, make_scorer\r\nimport re\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom scipy.stats import pearsonr\r\nfrom AutoML import properties as pr\r\nimport pickle as p\r\nimport os,sys,inspect\r\n#end of importing\r\nmodel={}\r\nle = LabelEncoder()\r\ncolm_list=[]\r\n\r\ndef train_model(X,Y,report,n): #method to calculate the scores of different algorithms\r\n h=1\r\n report['Algorithms'] = {} #generating a report for the user to provide the results of each algorithm\r\n maxi=-9999999\r\n for reg_model in pr.reg:\r\n res=pr.reg[reg_model]()\r\n grid = GridSearchCV(res, pr.prg[reg_model], cv=2, scoring=None,refit=True)\r\n grid.fit(X, Y)\r\n s_score = grid.score(X, Y)\r\n report['Algorithms'][h] = {}\r\n report['Algorithms'][h]['Name'] = reg_model\r\n report['Algorithms'][h]['Score'] = s_score\r\n report['Algorithms'][h]['Hyperparameters Used'] = grid.best_params_\r\n\r\n h += 1\r\n if(s_score>maxi):\r\n maxi=s_score\r\n model['best_model'] = grid.best_estimator_\r\n return maxi\r\n\r\ndef test_columns(df,c_columns,report,n,target): #method to test the non-numerical columns for unique values\r\n unwanted=[]\r\n for c_column in c_columns:\r\n if(re.search('^[-+]?\\d+(\\.\\d+)?$',str(df[c_column][0]))):\r\n continue\r\n else:\r\n df[[c_column]]=le.fit_transform(df[[c_column]])\r\n uniqueness=len(df[c_column].unique())\r\n unique_ratio=uniqueness/n\r\n if(unique_ratio > pr.fea_eng['uniqueness'] and c_column!=target): #if uniqueness of values of a column is greater\r\n df.drop([c_column], inplace=True,axis=1) #than a threshold, discard the column\r\n unwanted.append(c_column)\r\n c1_columns = [c for c in c_columns if c not in unwanted]\r\n return c1_columns\r\n\r\n\r\ndef test_corr(df,c_columns,report,n,target):\r\n unwanted=[]#testing correlation between the columns\r\n for i in c_columns:\r\n for j in c_columns[c_columns.index(i)+1:len(c_columns)]:\r\n if(j not in c_columns):\r\n break\r\n if(i==target or j==target):\r\n break\r\n else:\r\n corr, _ = pearsonr(df[i],df[j])\r\n if(corr>pr.fea_eng['corr'] or corr<-pr.fea_eng['corr']): #if correlation between two columns is greater\r\n sc1=train_model(df[[i]],df[target],report,n) #than a threshold discard one of the columns\r\n sc2 = train_model(df[[j]], df[target],report,n)\r\n if(sc1 16):\n scroll_threads_running[line] = True\n thread = threading.Thread(target=scroll_text, args=(text, line, line))\n thread.start()\n else:\n lcd.move_to(0, line)\n lcd.putstr(text.ljust(16))\n scroll_threads_running[line] = False\n\n\ndef turn_on_led(led, seconds=0):\n led.on()\n\n if (seconds > 0):\n thread = threading.Timer(seconds, lambda: led.off())\n thread.start()\n\n\ndef is_json(string):\n try:\n json.loads(string)\n except ValueError as e:\n return False\n return True\n\n\ndef scan_item(code):\n global cart_items_count\n global total_price\n\n url = \"http://localhost/testApi/api.php?code=\" + code\n response = requests.get(url)\n\n if (not is_json(response.text) or not \"price\" in response.json() or not \"name\" in response.json()):\n turn_on_led(red_led, 2)\n display_text(\"\", 1)\n display_text(\"Code barre inconnu\", 0)\n return\n\n response_json = response.json()\n green_led.on()\n cart_items_count += 1\n total_price += response_json['price']\n\n turn_on_led(green_led, 2)\n\n # Insert scanned product to logs\n cursor = db.cursor()\n query = \"INSERT INTO scan_history (barcode, product_name, price) VALUES (%s, %s, %s)\"\n values = (code, response_json['name'], response_json['price'])\n cursor.execute(query, values)\n db.commit()\n\n display_text(response_json['name'][:16], 0)\n display_text(str(response_json['price']), 1)\n\n sleep(2)\n\n display_text('Nbr article : ' + str(cart_items_count), 0)\n display_text('Total : ' + str(round(total_price, 2)), 1)\n\n\n# Codes disponbles :\n# 258454125841\n# 465659887454\n# 3124480167026\n# 3398284433537\n# X000U80C67\n\n\nwhile True:\n scanned_code = input(\"Code barre du produit : \")\n scroll_threads_running = [False, False]\n\n scan_thread = threading.Thread(target=scan_item, args=(scanned_code,))\n scan_thread.start()\n","repo_name":"plntd-itakademy/iot-python","sub_path":"Scanner.py","file_name":"Scanner.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69940813604","text":"\"\"\"\nTests that the code can handle RC/FC evaluators that have both async and sync methods.\n\"\"\"\n\nimport inject\nimport pytest # type:ignore[import]\n\nfrom ahbicht.content_evaluation.evaluationdatatypes import EvaluatableData, EvaluatableDataProvider, EvaluationContext\nfrom ahbicht.content_evaluation.fc_evaluators import FcEvaluator\nfrom ahbicht.content_evaluation.rc_evaluators import RcEvaluator\nfrom ahbicht.content_evaluation.token_logic_provider import SingletonTokenLogicProvider, TokenLogicProvider\nfrom ahbicht.expressions.ahb_expression_evaluation import evaluate_ahb_expression_tree\nfrom ahbicht.expressions.condition_nodes import ConditionFulfilledValue, EvaluatedFormatConstraint\nfrom ahbicht.expressions.expression_resolver import parse_expression_including_unresolved_subexpressions\nfrom unittests.defaults import (\n default_test_format,\n default_test_version,\n empty_default_hints_provider,\n return_empty_dummy_evaluatable_data,\n)\n\n\nclass MixedSyncAsyncRcEvaluator(RcEvaluator):\n \"\"\"An RC evaluator that has both sync and async methods\"\"\"\n\n edifact_format = default_test_format\n edifact_format_version = default_test_version\n\n def _get_default_context(self):\n return None # type:ignore[return-value]\n\n def evaluate_1(self, evaluatable_data, context):\n assert isinstance(evaluatable_data, EvaluatableData)\n if context is not None:\n assert isinstance(context, EvaluationContext)\n return ConditionFulfilledValue.FULFILLED\n\n async def evaluate_2(self, evaluatable_data, context):\n assert isinstance(evaluatable_data, EvaluatableData)\n if context is not None:\n assert isinstance(context, EvaluationContext)\n return ConditionFulfilledValue.UNFULFILLED\n\n\nclass MixedSyncAsyncFcEvaluator(FcEvaluator):\n \"\"\"An FC Evaluator that has both sync and async methods\"\"\"\n\n edifact_format = default_test_format\n edifact_format_version = default_test_version\n\n def evaluate_901(self, _):\n return EvaluatedFormatConstraint(format_constraint_fulfilled=True, error_message=None)\n\n async def evaluate_902(self, _):\n return EvaluatedFormatConstraint(format_constraint_fulfilled=True, error_message=None)\n\n\nclass TestMixedSyncAsyncEvaluation:\n @pytest.mark.parametrize(\n \"expression, expected_rc_fulfilled, expected_fc_fulfilled\",\n [\n pytest.param(\"Muss ([1][901] X [2][902])\", True, True),\n pytest.param(\"Muss ([1][902] X [2][901])\", True, True),\n pytest.param(\"Muss ([2][902] X [2][901])\", False, True),\n ],\n )\n async def test_mixed_async_non_async(\n self, expression: str, expected_rc_fulfilled: bool, expected_fc_fulfilled: bool\n ):\n fc_evaluator = MixedSyncAsyncFcEvaluator()\n rc_evaluator = MixedSyncAsyncRcEvaluator()\n inject.clear_and_configure(\n lambda binder: binder.bind( # type:ignore[arg-type]\n TokenLogicProvider,\n SingletonTokenLogicProvider([rc_evaluator, fc_evaluator, empty_default_hints_provider]),\n ).bind_to_provider(EvaluatableDataProvider, return_empty_dummy_evaluatable_data)\n )\n tree = await parse_expression_including_unresolved_subexpressions(expression)\n evaluation_result = await evaluate_ahb_expression_tree(tree)\n assert (\n evaluation_result.requirement_constraint_evaluation_result.requirement_constraints_fulfilled\n is expected_rc_fulfilled\n )\n assert (\n evaluation_result.format_constraint_evaluation_result.format_constraints_fulfilled is expected_fc_fulfilled\n )\n # When mocker.spy ing on the evaluate_... the inspection inside the rc/fc evaluator fails\n # https://stackoverflow.com/questions/18869141/using-python-mock-to-spy-on-calls-to-an-existing-object\n","repo_name":"Hochfrequenz/ahbicht","sub_path":"unittests/test_mixed_sync_async_rc_fc_evaluation.py","file_name":"test_mixed_sync_async_rc_fc_evaluation.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"15273979994","text":"from flask import Blueprint\nfrom flask_restful import Resource, Api, reqparse, marshal\nfrom . import * \nfrom .model import Datareqs\nfrom flask_jwt_extended import jwt_required\nfrom blueprints import db, app, internal_required\n\n\nbp_datareq = Blueprint('datareq', __name__) \napi = Api(bp_datareq)\n\nclass DatareqResource(Resource):\n\n\n def __init__(self): # Hanya untuk menunjukkan bahwa ini class\n pass\n @jwt_required\n def get(self, id):\n qry = Datareqs.query.get(id)\n if qry is not None:\n return marshal(qry, Datareqs.response_fields), 200\n return {'status': 'NOT_FOUND'}, 404\n\n @jwt_required\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('page', location='json', required=True) # required means that system will return error message if it doesn'_internalt found this parameter\n parser.add_argument('per_page', location='json', required=True)\n parser.add_argument('keywords', location='json', required=True) # required bisa ada bisa juga ngga. Jika ada maka jika tidak diisi akan error\n args = parser.parse_args()\n\n client = Datareqs(args['page'], args['per_page'], args['keywords'])\n \n db.session.add(client)\n db.session.commit()\n\n app.logger.debug('DEBUG : %s', client)\n\n return marshal(client, Datareqs.response_fields), 200, {'Content-Type': 'application/json'}\n @jwt_required\n def put(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument('page', location='json', required=True) # required means that system will return error message if it doesn't found this parameter\n parser.add_argument('per_page', location='json', required=True)\n parser.add_argument('keywords', location='json', required=True) # required bisa ada bisa juga ngga. Jika ada maka jika tidak diisi akan error\n args = parser.parse_args()\n\n qry = Datareqs.query.get(id)\n if qry is None:\n return {'status': 'NOT_FOUND'}, 404\n \n qry.page = args['page']\n qry.per_page = args['per_page']\n qry.keywords = args['keywords']\n db.session.commit()\n\n return marshal(qry, Datareqs.response_fields), 200\n @jwt_required\n @internal_required\n def delete(self, id):\n qry = Datareqs.query.get(id)\n if qry is None:\n return {'status': 'NOT_FOUND'}, 404\n db.session.delete(qry)\n db.session.commit()\n\n return {'status': 'DELETED'}, 200\n\n def patch(self):\n return 'Not yet implemented', 501 \n\nclass DatareqList(Resource):\n\n def __init__(self):\n pass\n @jwt_required\n def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('p', type=int, location='args', default=1)\n parser.add_argument('rp', type=int, location='args', default=25)\n parser.add_argument('keywords', location='args', help='invalid status')\n args = parser.parse_args()\n\n offset = (args['p'] * args['rp']) - args['rp']\n\n qry = Datareqs.query\n\n if args['keywords'] is not None:\n qry = qry.filter(Datareqs.client_id.contains(args['keywords']))\n\n rows = []\n for row in qry.limit(args['rp']).offset(offset).all():\n rows.append(marshal(row, Datareqs.response_fields))\n \n return rows, 200\n\napi.add_resource(DatareqList, '', '/list')\napi.add_resource(DatareqResource, '', '/') ","repo_name":"zulyanor/project_rest_api","sub_path":"blueprints/datareq/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8084110343","text":"import jinja2\nfrom typing import List\n\nfrom minerl.herobraine.hero.handlers.translation import KeymapTranslationHandler, TranslationHandlerGroup\nimport minerl.herobraine.hero.mc as mc\nfrom minerl.herobraine.hero import spaces\nimport numpy as np\n\n__all__ = ['ObserveFromFullStats']\n\n\nclass ObserveFromFullStats(TranslationHandlerGroup):\n \"\"\"\n Includes the use_item statistics for every item in MC that can be used\n \"\"\"\n\n def xml_template(self) -> str:\n return str(\"\"\"\"\"\")\n\n def to_string(self) -> str:\n return self.stat_key\n\n def __init__(self, stat_key):\n if stat_key is None:\n self.stat_key = \"full_stats\"\n super(ObserveFromFullStats, self).__init__(\n handlers=[_FullStatsObservation(statKeys) for statKeys in mc.ALL_STAT_KEYS if len(statKeys) == 2]\n )\n else:\n self.stat_key = stat_key\n super(ObserveFromFullStats, self).__init__(\n handlers=[_FullStatsObservation(statKeys) for statKeys in mc.ALL_STAT_KEYS if stat_key in statKeys]\n )\n\n\nclass _FullStatsObservation(KeymapTranslationHandler):\n def to_hero(self, x) -> int:\n for key in self.hero_keys:\n x = x[key]\n return x\n\n def __init__(self, key_list: List[str], space=None, default_if_missing=None):\n if space is None:\n if 'achievement' == key_list[0]:\n space = spaces.Box(low=0, high=1, shape=(), dtype=int)\n else:\n space = spaces.Box(low=0, high=np.inf, shape=(), dtype=int)\n if default_if_missing is None:\n default_if_missing = np.zeros((), dtype=float)\n\n super().__init__(hero_keys=key_list, univ_keys=key_list, space=space,\n default_if_missing=default_if_missing)\n\n def xml_template(self) -> str:\n return str(\"\"\"\"\"\")\n","repo_name":"minerllabs/minerl","sub_path":"minerl/herobraine/hero/handlers/agent/observations/mc_base_stats.py","file_name":"mc_base_stats.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":587,"dataset":"github-code","pt":"52"} +{"seq_id":"25761361944","text":"import matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\ndef format_diagram_report(report:list):\n time = [time for time, _ in report]\n measurements = [measurement for _, measurement in report]\n pdf_name = 'report.pdf'\n with PdfPages(pdf_name) as pdf:\n\n plt.figure()\n plt.plot(time, measurements, color=\"Blue\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"CPU Percentage Load\")\n plt.title(\"CPU Report\")\n pdf.savefig()\n plt.close()\n return pdf_name\n\n\n\n\n","repo_name":"GMladen18/python","sub_path":"email_sender/CPU_reporter/report_formatter.py","file_name":"report_formatter.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":"27615202350","text":"from flask import Flask, request, render_template\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\napp = Flask(__name__)\n\n# Set up the Chrome driver with a Service object\nchrome_driver_path = r\"C:\\Users\\raghu\\PycharmProjects\\FP\\chromedriver.exe\" # Replace with the path to your chromedriver executable\nchrome_service = webdriver.chrome.service.Service(executable_path=chrome_driver_path)\nchrome_service.start()\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/process_url', methods=['POST'])\ndef process_url():\n url = request.form['url']\n browser = webdriver.Chrome(service=chrome_service)\n\n try:\n # Navigate to the user-specified URL\n browser.get(url)\n\n # wait for the search box to appear\n if(url==\"https://in.search.yahoo.com/\"):\n search_box = WebDriverWait(browser, 10).until(\n EC.presence_of_element_located((By.NAME, \"p\"))\n )\n elif(url==\"https://www.google.com/\"or url==\"https://openverse.org/\" or url==\"https://www.bing.com/\" or url==\"https://www.ecosia.org/?c=en\"):\n search_box = WebDriverWait(browser, 10).until(\n EC.presence_of_element_located((By.NAME, \"q\"))\n )\n else:\n search_box = WebDriverWait(browser, 10).until(\n EC.presence_of_element_located((By.NAME, \"search\"))\n )\n\n\n # interact with the search box\n search_box.send_keys('Techngium')\n search_box.submit()\n\n # get the page title\n title = browser.title\n\n except NoSuchElementException:\n title = 'Element not found'\n\n finally:\n # close the browser window\n browser.quit()\n\n return render_template('result.html', title=title)\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n chrome_service.stop()\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"lokeshb003/Flask-Selenium-Automation","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42914606941","text":"# User function to check if a2 is a subset of a1\r\ndef isSubset(a1, a2, n, m):\r\n # Create dictionaries to store the count of each element in a1 and a2\r\n count_a1 = {}\r\n count_a2 = {}\r\n\r\n # Count occurrences in a1\r\n for element in a1:\r\n count_a1[element] = count_a1.get(element, 0) + 1\r\n\r\n # Count occurrences in a2\r\n for element in a2:\r\n count_a2[element] = count_a2.get(element, 0) + 1\r\n\r\n # Check if all elements in a2 have counts less than or equal to their counts in a1\r\n for element, count in count_a2.items():\r\n if element not in count_a1 or count_a1[element] < count:\r\n return \"No\"\r\n\r\n return \"Yes\"\r\n \r\n \r\n\r\n\r\n\r\n#{ \r\n # Driver Code Starts\r\n#Initial Template for Python 3\r\n\r\n\r\ndef main():\r\n\r\n T = int(input())\r\n\r\n while(T > 0):\r\n sz = [int(x) for x in input().strip().split()]\r\n n, m = sz[0], sz[1]\r\n a1 = [int(x) for x in input().strip().split()]\r\n a2 = [int(x) for x in input().strip().split()]\r\n \r\n print(isSubset( a1, a2, n, m))\r\n\r\n T -= 1\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n# } Driver Code Ends","repo_name":"devyaanshdwivedi/GFG_SDE_SHEET","sub_path":"Array Subset of another array.py","file_name":"Array Subset of another array.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1547907902","text":"class Employee:\n raise_amt = 1.04\n num = 0\n\n def __init__(self, first, last, pay):\n self.first = first # Instance Variables\n self.last = last\n self.pay = pay\n self.email = first + \".\" + last + \"@company.com\"\n Employee.num += 1\n\n def fullname(self):\n return \"{} {}\".format(self.first, self.last)\n\n # def get_pay(self):\n # return self.pay\n\n def apply_raise_amt(self):\n self.pay = (self.pay * self.raise_amt)\n return self.pay\n\n @classmethod\n def set_raise_amt(cls,amount):\n cls.raise_amt = amount\n return cls.raise_amt\n\n @classmethod\n def set_new(cls,emp_str):\n first, last, pay = emp_str.split(\"-\")\n return cls(first, last, int(pay))\n\n\nemp_1 = Employee(\"Prakhar\", \"Kumar\", 50000) # They are the own unique instances of the employee class\nemp_2 = Employee(\"Yush\", \"Kumar\", 60000)\n\nprint (emp_1.fullname())\nprint (Employee.fullname(emp_2))\n# emp_1.apply_raise_amt()\n# print (emp_2.pay)\n# print(emp_1.pay)\n# print (Employee.set_raise_amt(1.10))\n\nemp_str_1 = \"John-Snow-65000\"\nemp_str_2 = \"Sansa-Stark-84000\"\n\nnew_emp_1 = Employee.set_new(emp_str_1)\nnew_emp_2 = Employee.set_new(emp_str_2)\n\nprint(new_emp_1.fullname())\nprint(new_emp_2.fullname())\n\nprint(new_emp_1.pay)\nprint(new_emp_2.pay)\n# print(type(new_emp_2.pay))\n\nprint(new_emp_1.apply_raise_amt())\nprint(new_emp_2.apply_raise_amt())\n\n","repo_name":"Pyk017/Python","sub_path":"OOPs/ClassMethods.py","file_name":"ClassMethods.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"35507083998","text":"import collections\nfrom multiprocessing import Process, Queue\nimport urllib\n\nimport requests\n\nfrom bos_consensus.common import Message\nfrom bos_consensus.util import logger\n\n\nMessageInfo = collections.namedtuple(\n 'MessageInfo',\n ('ip', 'port', 'message'),\n)\n\n\ndef send_message(message_info):\n assert isinstance(message_info, MessageInfo)\n\n log = logger.get_logger('client')\n log.debug('loaded message: %s', message_info)\n\n endpoint = 'http://%s:%s' % (message_info.ip, message_info.port)\n try:\n message = Message.new(message_info.message)\n response = requests.post(\n urllib.parse.urljoin(endpoint, '/send_message'),\n data=message.serialize(to_string=True),\n )\n response.raise_for_status()\n log.debug('message sent!')\n except Exception as e:\n log.error(\"ConnectionError occurred during client send message to '%s'!\" % endpoint)\n\n return\n\n return message\n\n\ndef _send_message_multiple_one(queue, message, endpoint):\n log = logger.get_logger('client')\n\n try:\n response = requests.post(\n endpoint.join('/send_message'),\n data=message.serialize(to_string=True),\n )\n response.raise_for_status()\n log.debug('sent message, %s to %s', message, endpoint)\n except Exception as e:\n log.error(\"failed to send message, %s to %s\", message, endpoint)\n\n queue.put(False)\n\n return\n\n queue.put(True)\n\n return\n\n\ndef _send_message_multiple(queue, message, endpoint):\n create_new_message = message is None\n messages = [message] if message is not None else list()\n\n number_of_messages = int(endpoint.get('m', 1))\n q = Queue(maxsize=number_of_messages)\n for i in range(number_of_messages):\n if create_new_message:\n messages.append(Message.new())\n\n p = Process(target=_send_message_multiple_one, args=(q, messages[-1], endpoint))\n p.start()\n\n while not q.full():\n pass\n\n queue.put(messages)\n\n return\n\n\ndef send_message_multiple(message, *endpoints):\n q = Queue(maxsize=len(endpoints))\n for endpoint in endpoints:\n p = Process(target=_send_message_multiple, args=(q, message, endpoint))\n p.start()\n\n while not q.full():\n pass\n\n messages = list()\n for i in endpoints:\n messages.extend(map(lambda x: (x, i), q.get()))\n\n return messages\n","repo_name":"leejames00/isaac-consensus-protocol","sub_path":"src/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"1688476545","text":"def solution(operations):\n\n import heapq\n\n heap_min = []\n heap_max = []\n\n for operation in operations:\n op_1, op_2 = operation.split()\n\n if op_1 == \"I\":\n heapq.heappush(heap_min, int(op_2))\n heapq.heappush(heap_max, (int(op_2) * -1, int(op_2)))\n\n else:\n if not heap_min:\n pass\n\n elif op_2 == \"1\":\n max_num = heapq.heappop(heap_max)[1]\n heap_min.remove(max_num)\n\n elif op_2 == \"-1\":\n min_num = heapq.heappop(heap_min)\n heap_max.remove((min_num * -1, min_num))\n\n if heap_min:\n answer = [heapq.heappop(heap_max)[1], heapq.heappop(heap_min)]\n else:\n answer = [0, 0]\n\n return answer\n\n\ndef solution_1(operations):\n\n import heapq\n\n heap_num = []\n\n for operation in operations:\n op_1, op_2 = operation.split()\n print(heap_num)\n if op_1 == \"I\":\n heapq.heappush(heap_num, int(op_2))\n\n else:\n if not heap_num:\n pass\n\n elif op_2 == \"1\":\n heap_num.pop()\n heapq.heapify(heap_num)\n\n elif op_2 == \"-1\":\n heapq.heappop(heap_num)\n\n\nif __name__ == '__main__':\n\n in_o = \t[\"I 16\", \"I -5643\", \"D -1\", \"D 1\", \"D 1\", \"I 123\", \"D -1\"]\n\n print(solution_1(in_o))\n","repo_name":"junho-devv/algorithm-study","sub_path":"PROGRAMMERSㅣ프로그래머스/고득점 KIT/힙ㅣHEAP/이중우선순위큐.py","file_name":"이중우선순위큐.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74659250084","text":"from typing import List, Set\n\nimport numpy as np\nimport numpy.typing as npt\n\n# Initial pheromones: Pn = zeros(n)\n\n# Visited cities can be represented with a\n# len(S) array. Where Vi = 1 if visited, 0 if not\n# This will keep track of S = S − {j} where j is the selected\n\n# Initial distances\n# randInt(3,3)\n\n\nEVAPORTAION_RATE = 0.5\n\n\ndef range_inc(start, stop):\n i = start\n while i < stop:\n yield i\n i += 1\n\n\nclass ArtificialAnt:\n def __init__(\n self,\n nCities: int,\n distances: npt.NDArray,\n pheromones: npt.NDArray,\n initialCity: int,\n ):\n self.initial = initialCity\n self.path = [initialCity]\n self.current = self.initial\n self.visited = self.initialize_visited(nCities)\n self.pheromones = pheromones\n self.distances = distances\n return\n\n def initialize_visited(self, nCities: int) -> npt.NDArray:\n return np.zeros(nCities)\n\n # def initialize_path(self, nCities: int) -> npt.NDArray:\n # return np.zeros(nCities)\n\n def select_next_node(self) -> int:\n av_idx = []\n for i in range(len(self.visited)):\n if self.visited[i] == 0:\n av_idx.append(i)\n\n if len(av_idx) == 1:\n return av_idx[0]\n\n ph_from_current = self.pheromones[self.current]\n sum_Tij = 0\n for i in av_idx:\n sum_Tij += ph_from_current[i]\n\n prob = []\n test_pij = 0\n for idx in av_idx:\n pij = ph_from_current[idx] / sum_Tij\n test_pij += pij\n prob.append(pij)\n ch = np.random.choice(av_idx, p=prob)\n return int(ch)\n\n def inc_pheromones(self, position: Set[int]):\n p = self.pheromones.item(position) + float(1)\n self.pheromones.itemset(position, p)\n\n def move(self, next_city: int):\n # A priori, no parece que haga falta incrementar pheromones\n # En el recorrido de la misma hormiga.\n # self.inc_pheromones((self.current, next_city))\n self.visited.itemset(self.current, 1)\n self.current = next_city\n self.path.append(self.current)\n\n def run(self):\n while len(self.path) < len(self.visited):\n next = self.select_next_node()\n self.move(next)\n\n # Will end the path going back to the initial\n self.move(self.initial)\n return self.path\n\n\nclass AntSystem:\n def __init__(self, noc: int, updt: int = 4, s: str = \"S\"):\n self.nCities = noc\n self.distances = self.initialize_distances(noc, strategy=s)\n self.pheromones = self.initialize_pheromones(noc)\n self.initial_pool = list(range_inc(0, self.nCities))\n self.shortest_path: dict = {\"d\": float(\"inf\"), \"p\": []}\n self.update_every = updt\n self.historic_distances = []\n return\n\n def initialize_distances(self, noc: int, strategy: str = \"S\"):\n \"\"\"\n strategy:\n S: Symetric distances. The problem will be STP\n A: Asymetric distances. The problem will be ASTP\n \"\"\"\n d = np.random.randint(0, 100, size=(noc, noc))\n if strategy == \"S\":\n m = np.tril(d, k=-1)\n n = m.transpose()\n return np.add(m, n)\n return d\n\n def calc_path_distance(self, path: List[int]) -> int:\n tot = 0\n for i in range(len(path) - 1):\n tot += self.distances.item((path[i], path[i + 1]))\n return tot\n\n def initialize_pheromones(self, noc: int):\n p = np.ones(shape=(noc, noc))\n for i in range(noc):\n p.itemset((i, i), 0)\n return p\n\n def evaporate(self):\n self.pheromones *= EVAPORTAION_RATE\n pass\n\n def save_shortest(self, path: List[int]):\n n_p = self.calc_path_distance(path)\n\n ## Will save all the values for the plot\n ## Is a test\n self.historic_distances.append(n_p)\n\n if n_p < self.shortest_path[\"d\"]:\n self.shortest_path[\"d\"] = n_p\n self.shortest_path[\"p\"] = path\n\n return\n\n def reset_shortest(self):\n self.shortest_path = {\"d\": float(\"inf\"), \"p\": []}\n\n def pheromone_intensification(self, idx):\n p = self.shortest_path[\"p\"]\n for i in range(len(p) - 1):\n position = (p[i], p[i + 1])\n updated = self.pheromones.item(position) + (1 / self.shortest_path[\"d\"])\n self.pheromones.itemset(position, updated)\n return\n\n def increment_pheromones(self, idx: int):\n # Cada 1/4 de las hormigas totales se actualiza\n p = self.shortest_path[\"p\"]\n for i in range(len(p) - 1):\n position = (p[i], p[i + 1])\n incremented = self.pheromones.item(position) + 1\n self.pheromones.itemset(position, incremented)\n return\n\n def run(self, iteration: int):\n for i in range(iteration):\n path = ArtificialAnt(\n initialCity=np.random.choice(self.initial_pool),\n nCities=self.nCities,\n distances=self.distances,\n pheromones=self.pheromones,\n ).run()\n self.save_shortest(path)\n if i % self.update_every == 0:\n self.evaporate()\n self.increment_pheromones(i)\n self.pheromone_intensification(i)\n self.reset_shortest()\n\n print(self.shortest_path)\n print(self.distances)\n return\n","repo_name":"Emmanuel-Guerreiro/Inv-MPP","sub_path":"ACO/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5450,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"26257908964","text":"'''This program reads each line,\nand prints the Rooms and Bathrooms values as key pair to the standard output\n'''\nimport sys\n\ncountLine = 0\n\nfor line in sys.stdin:\n data = line.strip().split(\"\\t\") #this remove any white space, and turns the rest into a list\n countLine += 1\n if len(data) == 49: #checks if it is the right input\n ID,BATHRM,HF_BATHRM,HEAT,AC,NUM_UNITS,ROOMS,BEDRM,AYB,YR_RMDL,EYB,STORIES,SALEDATE,PRICE,QUALIFIED,SALE_NUM,GBA,BLDG_NUM,STYLE,STRUCT,GRADE,CNDTN,EXTWALL,ROOF,INTWALL,KITCHENS,FIREPLACES,USECODE,LANDAREA,GIS_LAST_MOD_DTTM,SOURCE,CMPLX_NUM,LIVING_GBA,FULLADDRESS,CITY,STATE,ZIPCODE,NATIONALGRID,LATITUDE,LONGITUDE,ASSESSMENT_NBHD,ASSESSMENT_SUBNBHD,CENSUS_TRACT,CENSUS_BLOCK,WARD,SQUARE,X,Y,QUADRANT = data\n if countLine >= 2: #ignores the header\n if (int(ROOMS) == 0) or (int(BATHRM) == 0):#removes invalid data\n continue\n elif (int(ROOMS) < 10):#adds 0 to key value that helps with proper sorting later\n ROOMS = \"0\" + ROOMS\n print(\"{0}\\t{1}\\n\".format(ROOMS,BATHRM)) #print to stdin\n else:\n print(\"{0}\\t{1}\\n\".format(ROOMS,BATHRM))\n","repo_name":"Sumnimarana1/MapReduceProjectGroup4","sub_path":"neravetla/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"8095642458","text":"'''\nHelper script: re-order the string count features\n'''\nimport ConfigParser\nimport numpy as np\nimport sys\nimport os\nimport csv\n\nfilecount = 0\ntrain_label = []\npath_data = Config.get(\"Train\",\"feature_save\")\npath_label = Config.get(\"Train\",\"label\")\npath_save = Config.get(\"Train\",\"model\")\n\nlabel_count = 0 \nwith open(path_label) as f:\n for line in f:\n label_count+=1\n line = line.split(\".\")\n train_label.append(line[0].strip()) \n\ndata_name = []\ndata = []\nheader = []\n\nlinecount = 0\nwith open(os.path.join(path_data,\"strCount.csv\")) as ic:\n for line2 in ic:\n linecount += 1\n if(linecount==1):\n pass\n else:\n import_data = line2.split(\",\")\n data_name = import_data[0]\n data.append(import_data[1])\n\n\nlabel_idx = 0\nwritecount = 0\nfor label_idx in range(len(train_label)):\n name = train_label[label_idx]\n idx = data_name.index(name)\n to_write = data[idx]\n print(\"Lenth: \"+ str(len(to_write)))\n\n with open(os.path.join(path_save,\"organized_strCounts.csv\"),'wb+') as f:\n w = csv.writer(f)\n w.writerow(to_write)\n writecount+=1\n print(\"Finish organizing: \"+str(writecount)+\" \"+name + \" \"+data_name[idx])\n label_idx+=1\n \n","repo_name":"AmberYZ/malware","sub_path":"organize_str.py","file_name":"organize_str.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25926953061","text":"import pygame\nfrom .text import Text\nfrom .button import Button\n# from color_schemes import ColorScheme\n\n\nclass WinMenu():\n screen_h: float\n screen_w: float\n # colors: ColorScheme\n TITLE_Y = 0\n CONTROLS_Y = 0\n\n menu = pygame.sprite.Group()\n button: pygame.sprite.GroupSingle()\n\n def __init__(self, screen, colors):\n self.screen_h = screen.get_rect().height\n self.screen_w = screen.get_rect().width\n self.colors = colors\n\n self.TITLE_Y = self.screen_h * 0.2\n self.CONTROLS_Y = self.screen_h * 0.7\n\n self.menu.add(\n Text(\n colors.get_text(),\n 80,\n \"YOU WIN!\",\n pygame.Vector2(self.screen_w/2, self.TITLE_Y)\n ),\n # Text(\n # colors.get_text(),\n # 40,\n # \"-=CONTROLS=-\",\n # pygame.Vector2(self.screen_w/2, self.CONTROLS_Y)\n # )\n )\n\n self.button = pygame.sprite.GroupSingle()\n self.button.add(\n Button(\n colors.get_button_text(),\n colors.get_button_bg(),\n colors.get_button_hover(),\n colors.get_button_pressed(),\n colors.get_button_disabled(),\n False,\n \"Endless Mode: Keep Going\",\n 40,\n pygame.Vector2(self.screen_w/2, self.screen_h/2)\n )\n )\n","repo_name":"ArshvirGoraya/wall-defender","sub_path":"menus/win_menu.py","file_name":"win_menu.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31398399605","text":"n=int(input('Wpisz liczbę kółek= '))\r\n\r\nA=[]\r\nB=[]\r\nC=[]\r\nu=n\r\nA.append(n)\r\n\r\nwhile u>1:\r\n A.append(u-1)\r\n u=u-1\r\n\r\ndef hanoi(A,B,C,n):\r\n \r\n if n==1:\r\n C.append(A.pop())\r\n \r\n else:\r\n hanoi(A,C,B,n-1)\r\n print(A,B,C)\r\n \r\n C.append(A.pop())\r\n print(A,B,C)\r\n \r\n hanoi(B,A,C,n-1)\r\n print(A,B,C)\r\n\r\nhanoi(A,B,C,n)\r\n","repo_name":"0zana/funkcje-metody","sub_path":"def hanoi.py","file_name":"def hanoi.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6375301205","text":"#!/usr/bin/python\n#\n# This code is designed soley for the purposes of demonstrating the tools\n# for timeshifting.\n#\n\nfrom Kamaelia.Device.DVB.Core import DVB_Multiplex\nfrom Kamaelia.Chassis.Pipeline import Pipeline\nfrom Kamaelia.File.Writing import SimpleFileWriter\nimport dvb3\n\n# Transmitters for Wolverhampton:\n# The Wrekin\n# The WrekinB\n# Sutton Coldfields\n\nfreq = 850.166670\nfeparams = {\n \"inversion\" : dvb3.frontend.INVERSION_AUTO,\n \"constellation\" : dvb3.frontend.QAM_16,\n \"code_rate_HP\" : dvb3.frontend.FEC_3_4,\n \"code_rate_LP\" : dvb3.frontend.FEC_3_4,\n}\n\nPipeline(\n DVB_Multiplex(freq, [6210], feparams), # RADIO ONE\n SimpleFileWriter(\"RADIO_ONE.ts\")\n).run()\n","repo_name":"sparkslabs/kamaelia_","sub_path":"Sketches/MPS/Examples/LUGRadio/RadioOne.py","file_name":"RadioOne.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"} +{"seq_id":"10538259116","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom .models import Dojo, Ninja\n\ndef index(request):\n dojos = Dojo.objects.all()\n return render(request, \"index.html\", {\"dojos\": dojos})\n\ndef add_dojo(request):\n if request.method == \"POST\":\n name = request.POST[\"name\"]\n city = request.POST[\"city\"]\n state = request.POST[\"state\"]\n Dojo.objects.create(name=name, city=city, state=state)\n return redirect(reverse(\"index\"))\n\ndef add_ninja(request):\n if request.method == \"POST\":\n first_name = request.POST[\"first_name\"]\n last_name = request.POST[\"last_name\"]\n dojo = Dojo.objects.get(id=request.POST[\"dojo_id\"])\n Ninja.objects.create(first_name=first_name, last_name=last_name, dojo=dojo)\n return redirect(reverse(\"index\"))\n\ndef delete_dojo(request, dojo_id):\n dojo = Dojo.objects.get(id=int(dojo_id))\n dojo.delete()\n return redirect(reverse(\"index\"))\n","repo_name":"Emiliewu/Python_Studies","sub_path":"django/ORM/Dojo_Ninjas_Proj/dojo_ninjas_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20585159130","text":"'''\n백준 12852번\n1로 만들기2\n'''\nfrom copy import deepcopy\nimport sys\nfrom collections import deque\nsys.setrecursionlimit(10**6)\n\nN = int(input())\nINF = 10 ** 6\n \ndp = [[] for _ in range(N+1)]\nq = deque()\n\ndef bfs():\n q.append(N)\n dp[N].append(N)\n while True:\n num = q.pop()\n if num == 1:\n break\n \n nexts = []\n if num%3==0:\n nexts.append(num//3)\n if num%2==0:\n nexts.append(num//2)\n nexts.append(num-1)\n\n for n in nexts:\n if n < 1:\n continue\n if len(dp[n])!=0 and len(dp[n]) <= len(dp[num])+1:\n continue\n q.appendleft(n)\n copyed = deepcopy(dp[num])\n copyed.append(n)\n dp[n] = copyed\n \n \n\nbfs()\nprint(len(dp[1])-1)\nfor v in dp[1]:\n print(v,end=' ')","repo_name":"tjddls1124/Algorithm","sub_path":"baekjoon/baek12852.py","file_name":"baek12852.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37586375992","text":"\ndef aspParse2ASP(machine_count, jobs):\n\tallJobs = {}\t\t# key: subjob-index, value: (length, machine, job-index)\n\n\tprog = \"\"\n\tprog += \"machine(0..\" + str(machine_count-1) + \").\\n\"\n\tprog += \"time(0..\" + \"200).\\n\"\n\n\tcurrentJob = 0\n\tcurrentSubjob = 0\n\tfor job in jobs:\n\t\tcurrentJob += 1\n\t\tfor subjob in job:\n\t\t\tcurrentSubjob += 1\n\t\t\tprog += \"subjob({0}, {1}, {2}, {3}).\\n\".format(str(currentSubjob), str(subjob[1]), str(subjob[0]), currentJob)\n\t\t\tallJobs[currentSubjob] = (subjob[1], subjob[0], currentJob)\n\n\tprog += \"{exec(M, T, J) : time(T), subjob(J, _, M, _)}.\\n\"\n\n\tfor i in range(currentSubjob):\n\t\tprog += \"1{exec(M, T, \" + str(i+1) + \"):machine(M), time(T), subjob(\" + str(i+1) + \", _, M, _)}1.\\n\"\n\n\tprog += \":- exec(M, T1, I1), exec(M, T2, I2), subjob(I1, L, M, _), subjob(I2, _, M, _), I1 < I2, T1 + L > T2.\\n\"\n\tprog += \":- exec(_, T2, J2), exec(_, T1, J1), subjob(J1, L, _, N), subjob(J2, _, _, N), J1 < J2, T1+L > T2.\\n\"\n\tprog += \"#minimize { T, L : exec(_, T, J), subjob(J, L, _, _), time(T)}.\\n\"\n\tprog += \"#show exec/3.\\n\"\n\n\treturn prog, allJobs\n\n\n# IN: (machine_count, [job1, job2, job3, ...])\n#\t->\tjob... [(machineNr, time), (machineNr, time), ...]\n#\n# OUT: [jobs_on_machine1, jobs_on_machine2, jobs_on_machine3, ...]\n#\t->\tjob_on_machine... [(begin, length, jobNr), (begin, length, jobNr), (begin, length, jobNr)]\n\n\n# return jobs = [(subjob1, time), (subjob2, time), (subjob3, time), ....]\ndef aspParseFromASP(machineCount, allJobs, log):\n\tjobs = []\n\tlines = log.split(\"\\n\")\n\n\tlineOfInterest = \"\"\n\tfor i in range(len(lines)):\n\t\tif (\"OPTIMUM FOUND\" in lines[i]):\n\t\t\tlineOfInterest = lines[i-2]\n\t\n\tif (lineOfInterest == \"\"):\n\t\treturn []\n\n\tfor job in lineOfInterest.split(\" \"):\n\t\t# job has the form: \"exec(1,1,1)\"\n\t\tjobEdited = job.replace(\"exec(\", \"\").replace(\")\", \"\").split(\",\")\n\n\t\t# jobEdited has the form: [\"1\",\"1\",\"1\"]\n\t\tjobs.append((int(jobEdited[2]), int(jobEdited[1])))\n\n\t# jobs has form: [(subjob1, time), (subjob2, time), (subjob3, time), ...]\n\n\tsolution = [[] for m in range(machineCount)]\n\tfor job in jobs:\n\t\tfor key in allJobs.keys():\n\t\t\tif (job[0] == key):\t\t\t\t# match with subjob-key\n\t\t\t\tcurrentJob = allJobs[key]\n\t\t\t\tsolution[currentJob[1]].append((job[1], currentJob[0], currentJob[2]))\n\n\treturn solution\n","repo_name":"klaus94/ProbSolv_Search_AI_Project","sub_path":"aspParser.py","file_name":"aspParser.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31657177611","text":"# -*- coding: utf-8 -*-\n\n#
Convolutional Neural Networks
\n##
Benedek Dankó
\n\"\"\"\n\n# Commented out IPython magic to ensure Python compatibility.\n# load libraries:\nimport numpy as np\nimport seaborn as sns\nfrom google.colab import drive\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nfrom sklearn.metrics import confusion_matrix\n\n\nfrom tensorflow import keras\nfrom tensorflow.keras.layers import *\n\n# %matplotlib inline\n\n\"\"\"### 1. Load the MNIST dataset and create a CNN model\"\"\"\n\n# load data:\n(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\nx_train = x_train/255 # normalize data to fall between 0-1\nprint(x_test.shape)\nprint(x_train.shape)\nprint(y_test.shape)\nprint(y_train.shape)\n\n# convert data:\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\n\ny_train = keras.utils.to_categorical(y_train, 10)\ny_test = keras.utils.to_categorical(y_test, 10)\n\nx_train = x_train.reshape((x_train.shape[0], 28, 28, 1))\nx_test = x_test.reshape((x_test.shape[0], 28, 28, 1))\n\nplt.imshow(x_train[0][:,:,0], cmap='gray')\nplt.show() # 5\n\n# set up CNN:\ncnn_model = keras.models.Sequential()\ncnn_model.add(Conv2D(16, (3, 3), input_shape=x_train.shape[1:], padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(16, (3, 3), padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\n\ncnn_model.add(Conv2D(32, (3, 3), padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\ncnn_model.add(Flatten())\n\ncnn_model.add(Dense(10))\ncnn_model.add(Activation('softmax'))\n\n# check model summary:\ncnn_model.summary()\n\n\"\"\"You can observe the number of the parameters per layer in the last column.
\nTotal number of parameters: 21,498.\n\"\"\"\n\n# compile model with Adam optimizer, use categorical crossentropy as loss function:\ncnn_model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])\n\n# fit model:\ncnn_history = cnn_model.fit(x_train, y_train, batch_size=32,\n epochs=5, validation_data=(x_test, y_test))\n\nprint('Accuracy scores: {}'.format(cnn_history.history['val_accuracy']))\nprint('Categorical cross-entropy loss: {}'.format(cnn_history.history['val_loss']))\n\n\"\"\"The final validation accuracy is 99.27%, which is pretty good.\"\"\"\n\n# perform predictions: \ncnn_predictions = cnn_model.predict(x_test, batch_size=32)\n\n# plot confusion matrix:\nconf = confusion_matrix(y_pred=np.argmax(cnn_predictions, 1), y_true=np.argmax(y_test, 1))\nplt.figure(figsize=(10, 10))\nsns.heatmap(conf, annot=True, cmap='Reds', fmt='g', cbar=False, vmax=30)\nplt.title('Confusion matrix', fontsize=17)\nplt.xlabel('Predicted label', fontsize=14)\nplt.ylabel('Actual label', fontsize=14)\nplt.show()\n\n\"\"\"After all, the model reached 99.27% accuracy.
\nAs you can see, the model missed a few 5s, and 9s, and predicted them as 3s, and 4s.
\n\nComparing to the fully-connected NN, the CNN predicted for example the 3s and 4s more accurately.\n\n### 2. Download the Street View House Numbers (SVHN) Dataset\n\"\"\"\n\n# First, download data from http://ufldl.stanford.edu/housenumbers/.\n\ntest = loadmat('test_32x32.mat')\ntrain = loadmat('train_32x32.mat')\n\nprint(test.keys())\nprint(train.keys())\n\n# get training, test datasets:\ntrain_x = train['X']\ntrain_y = train['y']\n\ntest_x = test['X']\ntest_y = test['y']\n\nprint(train_x.shape)\nprint(test_x.shape)\nprint(train_y.shape)\nprint(test_y.shape)\n\n# 10 different labels:\nset([i[0] for i in list(train_y)])\n\n# unpack the y arrays:\ntrain_y = np.asanyarray([i[0]-1 for i in list(train_y)])\ntest_y = np.asanyarray([i[0]-1 for i in list(test_y)])\n\n# visualize 5 images randomly:\ndef show_train_imgs(n=8, m=1):\n for i in range(m):\n for j in range(n):\n idx = np.random.randint(len(y_train))\n plt.subplot(int('1' + str(n) + str(j+1)))\n plt.imshow(np.einsum('klij->jkli', train_x)[idx].astype('int'))\n plt.title('Label: {}'.format(train_y[idx]), fontsize=20)\n plt.axis('off')\n plt.show()\n\nplt.rcParams['figure.figsize'] = (15, 5)\nshow_train_imgs(5)\n\n# convert data, one-hot encoding of the labels:\ntrain_x = np.einsum('klij->jkli', train_x)\ntest_x = np.einsum('klij->jkli', test_x)\n\ntrain_y = keras.utils.to_categorical(train_y, 10)\ntest_y = keras.utils.to_categorical(test_y, 10)\n\n# required shapes of the data:\nprint(train_x.shape)\nprint(test_x.shape)\nprint(train_y.shape)\nprint(test_y.shape)\n\n\n\n\"\"\"We have 10 classes in this dataset.
\nFurthermore, we have 73257 train examples and 26032 test examples.
\nDimension of the images: 32 x 32 pixels with 3 color chanels.\n\n### 3. Train the CNN model seen in the 1st exercise for this dataset\n\"\"\"\n\n# set up CNN:\ncnn_model = keras.models.Sequential()\ncnn_model.add(Conv2D(16, (3, 3), input_shape=train_x.shape[1:], padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(16, (3, 3), padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\n\ncnn_model.add(Conv2D(32, (3, 3), padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='valid'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\ncnn_model.add(Flatten())\n\ncnn_model.add(Dense(10))\ncnn_model.add(Activation('softmax'))\n\ncnn_model.summary()\n\n\"\"\"You can observe the number of the parameters per layer in the last column.
\nTotal number of parameters: 24,666.\n\"\"\"\n\n# compile model with Adam optimizer, use categorical crossentropy as loss function:\ncnn_model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])\n\n# fit model:\ncnn_history = cnn_model.fit(train_x, train_y, batch_size=32,\n epochs=15, validation_data=(test_x, test_y))\n\nprint('Final accuracy score: {}'.format(cnn_history.history['val_accuracy'][-1]))\nprint('Final categorical cross-entropy loss: {}'.format(cnn_history.history['val_loss'][-1]))\n\n\"\"\"The same CNN model performed worse on this more complex dataset, with 88.31% final validation accuracy (in case of the MNIST dataset: 99.27% accuracy).\n\n### 4. Evaluate performance\n\"\"\"\n\n# plot training, validation loss:\nplt.plot(cnn_history.history['loss'], label='Training loss')\nplt.plot(cnn_history.history['val_loss'], label='Validation loss')\nplt.legend(loc='upper right')\nplt.xlim(0, 14)\nplt.title('Training vs. validation loss', fontsize=17)\nplt.xlabel('Epoch', fontsize=14)\nplt.ylabel('Categorical cross-entropy loss', fontsize=14)\nplt.grid()\nplt.show()\n\n# plot training, validation accuracy:\nplt.plot(cnn_history.history['accuracy'], label='Training accuracy')\nplt.plot(cnn_history.history['val_accuracy'], label='Validation accuracy')\nplt.legend(loc='lower right')\nplt.xlim(0, 14)\nplt.title('Training vs. validation accuracy', fontsize=17)\nplt.xlabel('Epoch', fontsize=14)\nplt.ylabel('Accuracy', fontsize=14)\nplt.grid()\nplt.show()\n\n\"\"\"It seems that we overfit, since the training loss is decreasing, but the validation loss starts to oscillate/to increase. \nHowever, if the validation accuracy is still increasing, then I guess it is OK.\n\"\"\"\n\n# perform predictions: \ncnn_predictions = cnn_model.predict(test_x, batch_size=32)\n\n# plot confusion matrix:\nconf = confusion_matrix(y_pred=np.argmax(cnn_predictions, 1), y_true=np.argmax(test_y, 1))\nplt.figure(figsize=(10, 10))\nsns.heatmap(conf, annot=True, cmap='Reds', fmt='g', cbar=False, vmax=500)\nplt.title('Confusion matrix', fontsize=17)\nplt.xlabel('Predicted label', fontsize=14)\nplt.ylabel('Actual label', fontsize=14)\nplt.show()\n\n\"\"\"The model missed sometimes (> 100) the pictures with labels 0 , 2, 3, 5, and 6.\n\n### 5. Train an other CNN\n\"\"\"\n\n# build CNN:\ncnn_model = keras.models.Sequential()\ncnn_model.add(Conv2D(16, (3, 3), input_shape=train_x.shape[1:], padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(16, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\n\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(MaxPooling2D(pool_size=(2,2)))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Conv2D(32, (3, 3), padding='same'))\ncnn_model.add(Activation('relu'))\ncnn_model.add(Flatten())\n\ncnn_model.add(Dense(10))\ncnn_model.add(Activation('softmax'))\n\n# compile model with Adam optimizer, use categorical crossentropy as loss function:\ncnn_model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])\n\n# fit model:\ncnn_history = cnn_model.fit(train_x, train_y, batch_size=32,\n epochs=10, validation_data=(test_x, test_y))\n\ncnn_model.summary()\n\n\"\"\"The model has 86,552 parameters in total.\"\"\"\n\n# plot training, validation loss:\nplt.plot(cnn_history.history['loss'], label='Training loss')\nplt.plot(cnn_history.history['val_loss'], label='Validation loss')\nplt.legend(loc='right')\nplt.xlim(0, 9)\nplt.title('Training vs. validation loss', fontsize=17)\nplt.xlabel('Epoch', fontsize=14)\nplt.ylabel('Categorical cross-entropy loss', fontsize=14)\nplt.grid()\nplt.show()\n\n# plot training, validation accuracy:\nplt.plot(cnn_history.history['accuracy'], label='Training accuracy')\nplt.plot(cnn_history.history['val_accuracy'], label='Validation accuracy')\nplt.legend(loc='lower right')\nplt.xlim(0, 9)\nplt.title('Training vs. validation accuracy', fontsize=17)\nplt.xlabel('Epoch', fontsize=14)\nplt.ylabel('Accuracy', fontsize=14)\nplt.grid()\nplt.show()\n\n\"\"\"As we can see, the model's accuracy reached it's maximum value in the 10th epoch (for both validation and train data).
\nHowever, the lowest validation loss value is reached in the 6th epoch.\n\"\"\"","repo_name":"dBenedek/machine_learning_course","sub_path":"code/10_cnn.py","file_name":"10_cnn.py","file_ext":"py","file_size_in_byte":10457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40514715282","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\nradius = 5\nlinearSpeed = 1.4\ncircumference = 2 * np.pi * radius\nperiod = circumference / linearSpeed\nw = (linearSpeed / radius)\ntime = np.arange(0, period, 0.1)\n\nx = radius * np.cos(time * w)\ny = radius * np.sin(time * w)\n\nprint(\"Circumference: \", circumference)\nprint(\"Period: \", period)\n\nfig, ax = plt.subplots()\n\nplt.title(str(radius) + \"m radius curve\")\nplt.scatter(x, y, label=\"curve\")\nplt.grid()\nax.set_aspect('equal', 'box')\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nplt.legend()\nplt.show()\n\n# open the file in the write mode\nf = open('C:/Users/vabicheq/Documents/mocap-evaluation/trajectory_' + str(radius) + '.csv', 'w', newline='')\n\n# create the csv writer\nwriter = csv.writer(f)\n\n# write a row to the csv file\nfor x, y in zip(x, y):\n writer.writerow([x, y])\n\n# close the file\nf.close()","repo_name":"vabichequer/MocapEvaluation","sub_path":"radius_plotter.py","file_name":"radius_plotter.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28974028858","text":"import csv # Used to output to the result.csv file.\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n# The dictionary used for numerical character comparison in-transit.\nALPHABETICAL_VALUE = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}\nALPHABETICAL_VALUE_REDUCED = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 1, 'k': 2, 'l': 3, 'm': 4, 'n': 5, 'o': 6, 'p': 7, 'q': 8, 'r': 9, 's': 1, 't': 2, 'u': 3, 'v': 4, 'w': 5, 'x': 6, 'y': 7, 'z': 8}\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndef main():\n \"\"\"\n Takes in input, and calls the computation and output functions.\n \"\"\"\n\n sentence = input(\"Sentence me, oh jury: \").lower() # Gathers input from the user and stores it as the variable sentence, and automatically lowers it.\n\n with open('result.csv', 'w+', newline='') as csvfile: # Opens a result.csv file for outputting the compuation to.\n outputfile = csv.writer(csvfile, delimiter=',', quotechar='\"') # Creates a writer function that is used to output to the result.csv file.\n word_length_total = 0 # Sets a variable to accumulate the total amount of characters in the sentence.\n sentence_total = 0 # Sets a variable for the total of each word converted character total.\n sentence_total_reduced = 0 # Sets a variable for the total of each word converted and reduced character total.\n first_letter_reduced_total = 0 # Sets a variable for the total of the converted reduced value of the first letter.\n sentence_total_deduced = 0 # Sets a variable for the total of each word converted and deduced character total.\n amount_of_words = 0 # Sets a variable to count the amount of words in the sentence.\n for word in sentence.split(): # For every word in the string variable sentence, gathered from the user:\n word_length, character_values, character_values_reduced, total_of_word, total_of_word_reduced, total_of_word_deduced = sentence_parse(word) # For each word, call the sentenceparse() function, and output the variable associated, along with adding to the variables above the appropriate values.\n word_length_total += word_length # Adds the word length to the variable word_length_total\n sentence_total += total_of_word # Adds the total converted character value to the variable sentence_total\n sentence_total_reduced += total_of_word_reduced # Adds the total converted and reduced character value to the variable sentence_total_reduced\n sentence_total_deduced += total_of_word_deduced # Adds the total converted and deduced character value to the variable sentence_total_deduced\n\n try: # Tries to add the first letter reduced total to the variable.\n first_letter_reduced_total += ALPHABETICAL_VALUE_REDUCED.get(word[:1]) # Adds the converted reduced chracter value to the variable first_letter_reduced_total\n except TypeError: # However, if there is a non-alphabetical character in the first letter place:\n print(\"Please do not have any non-alphabetical characters in the first character place value!\") # Scream at the user to fix their input.\n word_output(word_length, character_values, character_values_reduced, total_of_word, total_of_word_reduced, total_of_word_deduced, word, outputfile) # Call the output function to write to result.csv\n amount_of_words += 1 # Adds one to the variable amount_of_words for each word.\n\n total_output(word_length_total, sentence_total, sentence_total_reduced, first_letter_reduced_total, sentence_total_deduced, amount_of_words, outputfile) # Calls the total_output function\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndef sentence_parse(word):\n \"\"\"\n Parses the incoming sentence for its needed attributes for the table.\n \"\"\"\n\n character_values = [] # Creates a list for each individual word that has each character listed as a variable to compare to the dictionary ALPHABET.\n total_of_word = 0 # Sets the sum of the character values to zero, to be used later in the code.\n total_of_word_reduced = 0 # Sets a variable for the total of each word reduced.\n character_values_reduced = [] # Sets a list variable for the converted reduced chracter values.\n word_length = 0 # Sets a variable for the word length\n\n for character in word: # For each character in the word variable.\n if character not in ALPHABETICAL_VALUE: # If the character is not in the standard alphabet, then skip it.\n pass # Passes the value.\n else: # If the character is in the standard alphabet:\n character_values.append(ALPHABETICAL_VALUE.get(character)) # Appends the basic number value to the character_values list, storing that value in its place.\n character_values_reduced.append(ALPHABETICAL_VALUE_REDUCED.get(character)) # Appends the reduced number value to the character_values_reduced list, storing that value in its place.\n word_length = word_length + 1 # Adds one to the variable word_length\n\n for item in character_values: # For each number value in the list character_values:\n total_of_word += int(item) # Add that value to the sum of the word variable total_of_word.\n\n for item in character_values_reduced: # For each number value in the list character_values_reduced:\n total_of_word_reduced += int(item) # Add that value to the sum of the word variable total_of_word_reduced.\n\n if sum(map(int, list(str(total_of_word_reduced)))) > 9: # If the sum of both digits is greater than nine:\n total_of_word_deduced = sum(map(int, list(str(sum(map(int, list(str(total_of_word_reduced)))))))) # Redo the sum, which should make it less than 10 almost 90% of the time.\n else: # If it is already a one-digit numberL\n total_of_word_deduced = sum(map(int, list(str(total_of_word_reduced)))) # Sets a variable for the converted deduced word totals of each word.\n\n return(word_length, character_values, character_values_reduced, total_of_word, total_of_word_reduced, total_of_word_deduced) # Returns the computed values back to main()\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndef word_output(word_length, character_values, character_values_reduced, total_of_word, total_of_word_reduced, total_of_word_deduced, word, outputfile):\n \"\"\"\n Outputs the words, their character values, word character total, and reduced and deduced versions of those, if applicable.\n \"\"\"\n\n character_sum = equational_sum(character_values) # Calls the equational_sum function for the equational sum total of the list character_values.\n character_sum_reduced = equational_sum(character_values_reduced) # Calls the equational_sum function for the equational sum total of the list character_values_reduced.\n\n # Write all of the incoming information to the result file table.\n outputfile.writerow([word[:1].upper(), '=', ALPHABETICAL_VALUE_REDUCED.get(word[:1]), word_length, '1', word.upper(), character_sum, total_of_word, character_sum_reduced, total_of_word_reduced, total_of_word_deduced]) # Outputs the values to the result.csv file\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndef equational_sum(total):\n \"\"\"\n Takes in the number total and creates/returns the equational sum of that total.\n \"\"\"\n\n summerize = \"\" # summerization variable to be returned to the variable calling the function.\n\n if isinstance(total, int):\n if int(total) > 9: # If the variable sentence_total_deduced is less than 9 ( meaning that this isn't needed because it is already deduced):\n iterable = 0 # Create an iterable variable\n for digit in str(total): # For each individual number inside of the integer:\n if iterable == 0: # If this is the first individual number coming through:\n summerize = digit # Set the variable sentence_total_deduced_sum to that individual number:\n else: # if it is any other individual number:\n summerize = \"{}+{}\".format(summerize, digit) # Add the equational sum to the variable sentence_total_deduced_sum\n iterable = 1 # Set the iterable to 1, effectively telling the code to only use the else part of the conditional above when parsing digits after this.\n\n if isinstance(total, list):\n iterable = 0 # Creates an iterable variable.\n for item in total: # For each number value in the total:\n if iterable == 0: # If this is the first item:\n summerize = item # Make it the first item in the string.\n else: # If this isn't the first item:\n summerize = \"{}+{}\".format(summerize, item)\n iterable = 1 # Set the iterable to 1, effectively telling the code to only use the else part of the conditional above when parsing digits after this.\n\n return summerize\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndef total_output(word_length_total, sentence_total, sentence_total_reduced, first_letter_reduced_total, sentence_total_deduced, amount_of_words, outputfile):\n \"\"\"\n Outputs the original total, sentence totals, first letter totals, and the amount of words, along with the reduced and deduced versions of those, and their computational sums for easier reading.\n \"\"\"\n\n # First block of equational sum variables to be outputted in the \"ADD TO REDUCE\" row.\n first_letter_deduced_sum = equational_sum(first_letter_reduced_total) # Calls the equational_sum function for the equational sum total of the variable first_letter_reduced_total.\n word_length_sum = equational_sum(word_length_total) # Calls the equational_sum function for the equational sum total of the variable word_length_total.\n amount_of_words_sum = equational_sum(amount_of_words) # Calls the equational_sum function for the equational sum total of the variable amount_of_words.\n sentence_total_sum = equational_sum(sentence_total) # Calls the equational_sum function for the equational sum total of the variable sentence_total.\n sentence_total_reduced_sum = equational_sum(sentence_total_reduced) # Calls the equational_sum function for the equational sum total of the variable sentence_total_reduced.\n sentence_total_deduced_sum = equational_sum(sentence_total_deduced) # Calls the equational_sum function for the equational sum total of the variable sentence_total_deduced.\n\n # First block of totallities between the numbers of an integer, to be outputted in the \"SECOND TOTAL\" row.\n first_letter_deduced_total = sum(map(int, list(str(first_letter_reduced_total)))) # Sets a variable for the total of the converted deduced values for the first letter of every word.\n word_length_deduced_total = sum(map(int, list(str(word_length_total)))) # Sets a variable for the total of the deduced values of the word length.\n amount_of_words_total = sum(map(int, list(str(amount_of_words)))) # Sets a variable for the total of the amount of words when reduced.\n sentence_second_total = sum(map(int, list(str(sentence_total)))) # Sets a variable for the second combined total of the sentence (reduced total).\n sentence_reduced_second_total = sum(map(int, list(str(sentence_total_reduced)))) # Sets a variable for the second combined total of the reduced sentence total (second reduced total).\n sentence_deduced_second_total = sum(map(int, list(str(sentence_total_deduced)))) # Sets a variable for the second combined total of the deduced sentence total (second deduced total).\n\n # Second block of equational sum variables to be outputted in the \"REDUCE TO DEDUCE\" row.\n first_letter_essence_sum = equational_sum(first_letter_deduced_total) # Calls the equational_sum function for the equational sum total of the variable first_letter_deduced_total.\n word_length_essence_sum = equational_sum(word_length_deduced_total) # Calls the equational_sum function for the equational sum total of the variable word_length_deduced_total.\n amount_of_words_essence_sum = equational_sum(amount_of_words_total) # Calls the equational_sum function for the equational sum total of the variable amount_of_words_total.\n sentence_total_essence_sum = equational_sum(sentence_second_total) # Calls the equational_sum function for the equational sum total of the variable sentence_second_total.\n sentence_total_reduced_essence_sum = equational_sum(sentence_reduced_second_total) # Calls the equational_sum function for the equational sum total of the variable sentence_reduced_second_total.\n sentence_total_deduced_essence_sum = equational_sum(sentence_deduced_second_total) # Calls the equational_sum function for the equational sum total of the variable sentence_deduced_second_total.\n\n #Second block of totallities between the numbers of an integer, to be outputted in the \"ESSENCE OF NUMBER\" row.\n first_letter_essence_total = sum(map(int, list(str(first_letter_deduced_total)))) # Sets a variable for the essence total of the first letter column.\n word_length_essence_total = sum(map(int, list(str(word_length_deduced_total)))) # Sets a variable for the essence total of the word length column.\n amount_of_word_essence_total = sum(map(int, list(str(amount_of_words_total)))) # Sets a variable for the essence total of the amount of words column.\n sentence_essence_total = sum(map(int, list(str(sentence_second_total)))) # Sets a variable for the essence total of the sentence total column.\n sentence_total_reduced_essence = sum(map(int, list(str(sentence_reduced_second_total)))) # Sets a variable for the essence total of the sentence total reduced column.\n sentence_total_deduced_essence = sum(map(int, list(str(sentence_deduced_second_total)))) # Sets a variable for the essence total of the sentence total deduced column.\n\n # The line below outputs all of the variables/numbers associated with the \"First Total\"\n outputfile.writerow(['', '', first_letter_reduced_total, word_length_total, amount_of_words, 'FIRST TOTAL', '', sentence_total, '', sentence_total_reduced, sentence_total_deduced])\n # The line below outputs all the variables/numbers associated with \"Add to Reduce\"\n outputfile.writerow(['', '', first_letter_deduced_sum, word_length_sum, amount_of_words_sum, 'ADD TO REDUCE', '', sentence_total_sum, '', sentence_total_reduced_sum, sentence_total_deduced_sum])\n # The line below outputs all the variables/numbers associated with the \"Second Total\"\n outputfile.writerow(['', '', first_letter_deduced_total, word_length_deduced_total, amount_of_words_total, 'SECOND TOTAL', '', sentence_second_total, '', sentence_reduced_second_total, sentence_deduced_second_total])\n # The line below outputs all of the variables/numbers associated with \"Reduce to Deduce\"\n outputfile.writerow(['', '', first_letter_essence_sum, word_length_essence_sum, amount_of_words_essence_sum, 'REDUCE TO DEDUCE', '', sentence_total_essence_sum, '', sentence_total_reduced_essence_sum, sentence_total_deduced_essence_sum])\n # The line below outputs all of the variables/numbers associated with the \"Essence of Number\"\n outputfile.writerow(['', '', first_letter_essence_total, word_length_essence_total, amount_of_word_essence_total, 'ESSENCE OF NUMBER', '', sentence_essence_total, '', sentence_total_reduced_essence, sentence_total_deduced_essence])\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nmain() # Calls the main function.\n","repo_name":"Dersyx/Pythagorean-Numerology","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11465849310","text":"import discord\r\nimport math\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import has_permissions\r\nimport sqlite3\r\nfrom authentication import bot_token\r\nfrom datetime import datetime\r\nimport pytz\r\nimport random\r\nimport traceback\r\n\r\nnow = int(datetime.now(pytz.timezone(\"Singapore\")).timestamp())\r\n\r\nconn = sqlite3.connect('prefix.db', timeout=5.0)\r\nc = conn.cursor()\r\nconn.row_factory = sqlite3.Row\r\n\r\nstartup_extensions = ['merit', 'Shop']\r\nhelp_extensions = ['help']\r\n\r\nc.execute('''CREATE TABLE IF NOT EXISTS prefix (\r\n `guild_id` INT PRIMARY KEY,\r\n `prefix` TEXT)''')\r\n\r\nprefixDictionary = {}\r\n\r\nfor prefix in c.execute(f'SELECT guild_id, prefix FROM prefix'):\r\n prefixDictionary.update({prefix[0]: f\"{prefix[1]}\"})\r\n\r\n\r\nasync def determine_prefix(bot, message):\r\n prefixDictionary = {}\r\n\r\n for prefix in c.execute(f'SELECT guild_id, prefix FROM prefix'):\r\n prefixDictionary.update({prefix[0]: f\"{prefix[1]}\"})\r\n\r\n currentPrefix = prefixDictionary[message.guild.id]\r\n\r\n return commands.when_mentioned_or(currentPrefix)(bot, message)\r\n\r\n\r\nbot = commands.Bot(command_prefix=determine_prefix, help_command=None)\r\n\r\nif __name__ == \"__main__\":\r\n\r\n for extension in startup_extensions:\r\n\r\n try:\r\n\r\n bot.load_extension(extension)\r\n\r\n except Exception as e: #\r\n\r\n exc = f'{type(e).__name__}: {e}'\r\n print(f'Failed to load extension {extension}\\n{exc}')\r\n traceback.print_exc()\r\n\r\n\r\n@bot.command(help=\"Loads an extension. Bot Owner only!\")\r\n@commands.is_owner()\r\nasync def load(ctx, extension_name: str):\r\n \"\"\"Loads an extension.\"\"\"\r\n\r\n try:\r\n\r\n bot.load_extension(extension_name)\r\n\r\n except (AttributeError, ImportError) as e:\r\n\r\n await ctx.send(f\"```py\\n{type(e).__name__}: {str(e)}\\n```\")\r\n return\r\n\r\n await ctx.send(f\"{extension_name} loaded.\")\r\n\r\n\r\n@bot.command(help=\"Unloads an extension. Bot Owner only!\")\r\n@commands.is_owner()\r\nasync def unload(ctx,\r\n extension_name: str): # Used as a command on Discord to unload an extension script for maintenance. Same as load.\r\n\r\n \"\"\"Unloads an extension.\"\"\"\r\n\r\n bot.unload_extension(extension_name)\r\n\r\n await ctx.send(f\"{extension_name} unloaded.\")\r\n\r\n\r\n@bot.command()\r\n@has_permissions(manage_messages=True)\r\nasync def setprefix(ctx, new):\r\n guild = ctx.message.guild.id\r\n name = bot.get_guild(guild)\r\n c = conn.cursor()\r\n\r\n prefixDictionary.update({guild: f\"{new}\"})\r\n\r\n for key, value in c.execute('SELECT guild_id, prefix FROM prefix'):\r\n\r\n if key == guild:\r\n c.execute(''' UPDATE prefix SET prefix = ? WHERE guild_id = ? ''', (new, guild))\r\n conn.commit()\r\n embed = discord.Embed(description=f\"{name}'s Prefix has now changed to `{new}`.\")\r\n await ctx.send(embed=embed)\r\n\r\n c.close()\r\n\r\n\r\n@bot.command()\r\nasync def myprefix(ctx):\r\n guild = ctx.message.guild.id\r\n name = bot.get_guild(guild)\r\n currentPrefix = prefixDictionary[guild]\r\n embed = discord.Embed(description=f\"{name}'s Prefix currently is `{currentPrefix}`.\")\r\n await ctx.send(embed=embed)\r\n\r\n\r\n@bot.event\r\nasync def on_ready():\r\n print(\"Logging in as \" + str(bot.user))\r\n print(str(bot.user) + \" has connected to Discord!\")\r\n print(\"Current Discord Version: \" + discord.__version__)\r\n print(\"Number of servers currently connected to MeritBot:\")\r\n print(len([s for s in bot.guilds]))\r\n print(\"Number of players currently connected to MeritBot:\")\r\n m = sum(guild.member_count for guild in bot.guilds)\r\n print(m)\r\n\r\n guild_id_database = []\r\n\r\n for row in c.execute('SELECT guild_id FROM prefix'):\r\n guild_id_database.append(row[0])\r\n\r\n async for guild in bot.fetch_guilds(limit=150):\r\n\r\n if guild.id not in guild_id_database:\r\n c.execute(''' INSERT OR REPLACE INTO prefix VALUES (?, ?)''', (guild.id, '!'))\r\n conn.commit()\r\n print(f\"Created a prefix database for {guild.id}\")\r\n\r\n\r\n@bot.event\r\nasync def on_command_error(ctx, error):\r\n if isinstance(error, commands.CommandOnCooldown):\r\n\r\n seconds = error.retry_after\r\n minutes = seconds / 60\r\n hours = seconds / 3600\r\n\r\n if seconds / 60 < 1:\r\n\r\n embed = discord.Embed(\r\n description=f'Scram! You\\'re using this command too often! Try again in {str(int(seconds))} seconds!')\r\n await ctx.send(embed=embed)\r\n\r\n elif minutes / 60 < 1:\r\n\r\n embed = discord.Embed(\r\n description='Scram! You\\'re using this command too often! Try again in {0} minutes and {1} seconds!'.format(\r\n math.floor(minutes), (int(seconds) - math.floor(minutes) * 60)))\r\n await ctx.send(embed=embed)\r\n\r\n else:\r\n\r\n embed = discord.Embed(\r\n description='Scram! You\\'re using this command too often! Try again in {0} hours, {1} minutes, {2} seconds!'.format(\r\n math.floor(hours), (int(minutes) - math.floor(hours) * 60),\r\n int(seconds) - math.floor(minutes) * 60))\r\n await ctx.send(embed=embed)\r\n\r\n if isinstance(error, commands.CheckFailure):\r\n embed = discord.Embed(description='You do not have the permission to do this!')\r\n await ctx.send(embed=embed)\r\n\r\n if isinstance(error, commands.MissingRequiredArgument):\r\n embed = discord.Embed(description='Missing arguments on your command! Please check and retry again!')\r\n await ctx.send(embed=embed)\r\n raise error\r\n\r\n\r\n@bot.event\r\nasync def on_guild_join(guild):\r\n guild_id_database = []\r\n\r\n for row in c.execute('SELECT guild_id FROM prefix'):\r\n guild_id_database.append(row[0])\r\n\r\n if guild.id not in guild_id_database:\r\n c.execute(''' INSERT OR REPLACE INTO prefix VALUES (?, ?)''', (guild.id, '!'))\r\n conn.commit()\r\n print(f\"Joined a new server: created a prefix database for {guild.id}\")\r\n\r\n\r\n@bot.command()\r\nasync def ping(ctx):\r\n await ctx.send(f\"Latency: {bot.latency}s\")\r\n\r\n\r\nbot.remove_command('help')\r\n\r\nif __name__ == \"__main__\": # Loads all extension specified above on bot start-up.\r\n for extension in help_extensions:\r\n try:\r\n bot.load_extension(extension)\r\n except Exception as e:\r\n exc = f'{type(e).__name__}: {e}'\r\n print(f'Failed to load extension {extension}\\n{exc}')\r\n\r\nbot.run(f'{bot_token}', bot=True, reconnect=True)\r\n","repo_name":"gabinante/MeritBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2686821621","text":"from re import findall\n\nfrom js_parser.searcher_template import SearcherTemplate\n\n\nclass Searcher(SearcherTemplate):\n def __init__(self, search_string, clean_string=''):\n super().__init__(search_string, clean_string)\n\n def find_matches(self, input_str):\n self.matches = []\n self.js_input = input_str\n self.remove_comments_blocks_fixed()\n self.get_matches_override()\n if len(self.matches) > 0:\n return self.matches\n return None\n\n def get_matches_override(self):\n matches_raw = findall(self.search_criteria, self.js_input)\n matches_cleaned = set([])\n for match in matches_raw:\n matches_cleaned.add(match.replace(self.clean_string, ''))\n for cleaned_match in matches_cleaned:\n self.matches.append(cleaned_match)\n\n\n","repo_name":"ChironEvans/de321-Assignment2-2020","sub_path":"js_parser/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24258389009","text":"import json \nimport boto3\nimport time \nimport yaml\n\nclient = boto3.resource('dynamodb')\ntable = client.Table('yelp-restaurants')\n\n\nfiles = ['American.json','Indian.json','Italian.json','Japanese.json','Korean.json']\nfor file in files:\n data = yaml.safe_load(open(file))\n c=0\n for record in data:\n db_data = {\n \"id\": str(record['id']),\n \"Name\": record['name'].encode('utf-8'),\n \"Review_Count\":str(record['review_count']),\n \"Rating\":str(record['rating']),\n \"Address\":{\n \"city\":str(record['location']['city']),\n \"display_address\": record['location']['display_address']\n },\n \"inertAtTimeStamp\": str(time.time()),\n \"Coordinates\":{\n \"latitude\": str(record['coordinates']['latitude']),\n \"longitude\":str(record['coordinates']['longitude'])\n },\n \"zipcode\":str(record['location']['zip_code'])\n\n }\n table.put_item(Item =db_data)\n c+=1\n print(\"Data upload \",c)\n c=0","repo_name":"vishnudut/Dining-Chatbot-Concierge","sub_path":"Yelp/dbformat.py","file_name":"dbformat.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"69816761766","text":"from tkinter import *\nimport subprocess\nimport os\n\n###############################################################################\n######################## QUEL OPTIONS DE LANCEMENT ############################\n###############################################################################\n\n\ndef launchApp():\n if appButton.click == True:\n welcomeW.destroy()\n os.system(\"python3 FullApp/appTranslate.py\")\n appButton.click = False\n\n\ndef launchShell():\n if shellButton.click == True:\n welcomeW.destroy()\n os.system(\"python3 ShellApp/shellapp.py\")\n shellButton.click = False\n\n\n################################################################################\n###################### GENERATION DE L'APP, DEFINITION TAILLE ##################\n################################################################################\n\nwelcomeW = Tk()\nh = welcomeW.winfo_screenheight()/3.2\nw = welcomeW.winfo_screenwidth()/2\nwelcomeW.geometry(f'{int(w)}x{int(h)}')\nwelcomeW.title(\"Welcome Window\")\n\n\n################################################################################\n###################### GENERATION DES OPTIONS AVEC DESCRIPTIF###################\n################################################################################\n\ninLabel = LabelFrame(\n welcomeW, text=\"Traducteur V1.0\", padx=20, pady=20, fg=\"blue\", cursor=\"trek\")\ninLabel.pack(fill=\"both\", expand=\"no\", padx=30, pady=20)\ninLabel.columnconfigure(0, weight=1)\ninLabel.columnconfigure(1, weight=5)\ninLabel.columnconfigure(2, weight=1)\n\nLabel(inLabel, text=\"Bienvenue. Ceci est un traducteur d'ADN qui possèdes quelques fonctionnalités supplémentaire.\\nVous avez la possibilité de lancer ses fonctionnalités depuis un terminal, ou depuis l'application.\").grid(row=0, column=1)\n\nshellButton = Button(inLabel, text=\"Terminal Shell\",\n command=launchShell)\nshellButton.click = True\nshellButton.grid(row=1, column=0)\n\nappButton = Button(inLabel, text=\"Application\", command=launchApp)\nappButton.click = True\nappButton.grid(row=1, column=2)\n\n################################################################################\n########### GENERATION DU BOUTON QUITTER, ET DEVELOPPEURS LABEL ################\n################################################################################\n\n\nButton(inLabel, text=\"Quitter\", command=welcomeW.destroy).grid(row=2, column=1)\n\nsubLabel = LabelFrame(welcomeW, text=\"Développement\",\n padx=10, pady=10, fg=\"red\", cursor=\"trek\")\nsubLabel.pack(fill=\"none\", expand=\"no\", padx=15, pady=15)\nLabel(subLabel,\n text=\"Developpeurs :\\nAUBERT Lucas\\nGOUTTEBEL Pierre-Loïc\").pack()\n\n################################################################################\n##################### GENERATION TDU RESULTAT FINAL ! ##########################\n################################################################################\n\nwelcomeW.mainloop()\n","repo_name":"Ist4lri/python-project","sub_path":"welcomeApp.py","file_name":"welcomeApp.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39340089206","text":"import asyncio\nfrom dataclasses import dataclass\n\nimport pytest\n\nfrom python_aioarango import ArangoClient, formatter\nfrom python_aioarango.database import Database, StandardDatabase # noqa F401\nfrom python_aioarango.graph import Graph\nfrom python_aioarango.typings import Json\nfrom tests.executors import TestAsyncApiExecutor # noqa F401\nfrom tests.executors import TestBatchExecutor # noqa F401\nfrom tests.executors import TestTransactionApiExecutor # noqa F401\nfrom tests.helpers import generate_jwt # noqa F401\nfrom tests.helpers import (\n empty_collection,\n generate_col_name,\n generate_db_name,\n generate_graph_name,\n generate_string,\n generate_username,\n)\n\npytestmark = pytest.mark.asyncio\n\n\n@dataclass\nclass GlobalData:\n url: str = None\n username: str = None\n password: str = None\n db_name: str = None\n bad_db_name: str = None\n geo_index: Json = None\n col_name: str = None\n icol_name: str = None\n graph_name: str = None\n ecol_name: str = None\n fvcol_name: str = None\n tvcol_name: str = None\n cluster: bool = None\n complete: bool = None\n replication: bool = None\n enterprise: bool = None\n secret: str = None\n root_password: str = None\n\n\nglobal_data = GlobalData()\n\n\n@pytest.fixture(scope=\"session\")\ndef event_loop():\n \"\"\"Create an instance of the default event loop for each test case.\"\"\"\n loop = asyncio.get_event_loop_policy().new_event_loop()\n yield loop\n loop.close()\n\n\ndef pytest_addoption(parser):\n parser.addoption(\"--host\", action=\"store\", default=\"127.0.0.1\")\n parser.addoption(\"--port\", action=\"store\", default=\"8529\")\n parser.addoption(\"--passwd\", action=\"store\", default=\"openSesame\")\n parser.addoption(\"--complete\", action=\"store_true\")\n parser.addoption(\"--cluster\", action=\"store_true\")\n parser.addoption(\"--replication\", action=\"store_true\")\n parser.addoption(\"--enterprise\", action=\"store_true\")\n parser.addoption(\"--secret\", action=\"store\", default=\"secret\")\n\n\ndef pytest_configure(config):\n global_data.url = f\"http://{config.getoption('host')}:{config.getoption('port')}\"\n global_data.username = generate_username()\n global_data.password = generate_string()\n global_data.db_name = generate_db_name()\n global_data.bad_db_name = generate_db_name()\n global_data.col_name = generate_col_name()\n global_data.icol_name = generate_col_name()\n global_data.graph_name = generate_graph_name()\n global_data.ecol_name = generate_col_name()\n global_data.fvcol_name = generate_col_name()\n global_data.tvcol_name = generate_col_name()\n global_data.cluster = config.getoption(\"cluster\")\n global_data.complete = config.getoption(\"complete\")\n global_data.replication = config.getoption(\"replication\")\n global_data.enterprise = config.getoption(\"enterprise\")\n global_data.secret = config.getoption(\"secret\")\n global_data.root_password = config.getoption(\"passwd\")\n\n\n@pytest.fixture(autouse=True)\ndef mock_formatters(monkeypatch):\n def mock_verify_format(body, result):\n body.pop(\"error\", None)\n body.pop(\"code\", None)\n result.pop(\"edge\", None)\n if len(body) != len(result):\n before = sorted(body, key=lambda x: x.strip(\"_\"))\n after = sorted(result, key=lambda x: x.strip(\"_\"))\n raise ValueError(f\"\\nIN: {before}\\nOUT: {after}\")\n return result\n\n monkeypatch.setattr(formatter, \"verify_format\", mock_verify_format)\n\n\n@pytest.fixture(scope=\"session\")\nasync def client():\n client = ArangoClient(hosts=[global_data.url, global_data.url, global_data.url])\n yield client\n await client.close()\n\n\n@pytest.fixture(scope=\"session\")\nasync def sys_db(client):\n sys_db = await client.db(\n name=\"_system\",\n username=\"root\",\n password=global_data.root_password,\n # superuser_token=generate_jwt(global_data.secret),\n )\n\n # create test database\n await sys_db.create_database(\n name=global_data.db_name,\n users=[\n {\n \"active\": True,\n \"username\": global_data.username,\n \"password\": global_data.password,\n }\n ],\n )\n\n yield sys_db\n\n # Remove all test async jobs.\n await sys_db.clear_async_jobs()\n\n # Remove all test tasks.\n for task in await sys_db.tasks():\n task_name = task[\"name\"]\n if task_name.startswith(\"test_task\"):\n await sys_db.delete_task(task_name, ignore_missing=True)\n\n # Remove all test users.\n for user in await sys_db.users():\n username = user[\"username\"]\n if username.startswith(\"test_user\"):\n await sys_db.delete_user(username, ignore_missing=True)\n\n # Remove all test databases.\n for db_name in await sys_db.databases():\n if db_name.startswith(\"test_database\"):\n await sys_db.delete_database(db_name, ignore_missing=True)\n\n # Remove all test collections.\n for collection in await sys_db.collections():\n col_name = collection[\"name\"]\n if col_name.startswith(\"test_collection\"):\n await sys_db.delete_collection(col_name, ignore_missing=True)\n\n # # Remove all backups.\n if global_data.enterprise:\n for backup_id in (await sys_db.backup.get())[\"list\"].keys():\n await sys_db.backup.delete(backup_id)\n\n\n@pytest.fixture(scope=\"session\")\nasync def db(sys_db, client):\n tst_db = await client.db(\n global_data.db_name, global_data.username, global_data.password\n )\n\n # Create a standard collection for testing.\n tst_col = await tst_db.create_collection(global_data.col_name, edge=False)\n await tst_col.add_skiplist_index([\"val\"])\n await tst_col.add_fulltext_index([\"text\"])\n geo_index = await tst_col.add_geo_index([\"loc\"])\n global_data.geo_index = geo_index\n\n # Create a legacy edge collection for testing.\n await tst_db.create_collection(global_data.icol_name, edge=True)\n\n # Create test vertex & edge collections and graph.\n tst_graph = await tst_db.create_graph(global_data.graph_name)\n await tst_graph.create_vertex_collection(global_data.fvcol_name)\n await tst_graph.create_vertex_collection(global_data.tvcol_name)\n await tst_graph.create_edge_definition(\n edge_collection=global_data.ecol_name,\n from_vertex_collections=[global_data.fvcol_name],\n to_vertex_collections=[global_data.tvcol_name],\n )\n\n return tst_db\n\n\n@pytest.fixture(scope=\"session\")\nasync def bad_db(client):\n return await client.db(\n global_data.bad_db_name, global_data.username, global_data.password\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef conn(db):\n return getattr(db, \"_conn\")\n\n\n@pytest.fixture(scope=\"function\")\nasync def col(db: Database):\n collection = db.collection(global_data.col_name)\n await empty_collection(collection)\n return collection\n\n\n@pytest.fixture(scope=\"function\")\nasync def bad_col(bad_db: Database):\n return bad_db.collection(global_data.col_name)\n\n\n@pytest.fixture(scope=\"function\")\nasync def geo(db: Database):\n return global_data.geo_index\n\n\n@pytest.fixture(scope=\"function\")\nasync def icol(db: Database):\n collection = db.collection(global_data.icol_name)\n await empty_collection(collection)\n return collection\n\n\n@pytest.fixture(scope=\"function\")\nasync def graph(db: Database):\n return db.graph(global_data.graph_name)\n\n\n@pytest.fixture()\nasync def bad_graph(bad_db: Database):\n return bad_db.graph(global_data.graph_name)\n\n\n# noinspection PyShadowingNames\n@pytest.fixture()\nasync def fvcol(graph: Graph):\n collection = graph.vertex_collection(global_data.fvcol_name)\n await empty_collection(collection)\n return collection\n\n\n# noinspection PyShadowingNames\n@pytest.fixture()\nasync def tvcol(graph: Graph):\n collection = graph.vertex_collection(global_data.tvcol_name)\n await empty_collection(collection)\n return collection\n\n\n# noinspection PyShadowingNames\n@pytest.fixture()\nasync def bad_fvcol(bad_graph: Graph):\n return bad_graph.vertex_collection(global_data.fvcol_name)\n\n\n# noinspection PyShadowingNames\n@pytest.fixture()\nasync def ecol(graph: Graph):\n collection = graph.edge_collection(global_data.ecol_name)\n await empty_collection(collection)\n return collection\n\n\n# noinspection PyShadowingNames\n@pytest.fixture()\nasync def bad_ecol(\n bad_graph: Graph,\n):\n return bad_graph.edge_collection(global_data.ecol_name)\n\n\n@pytest.fixture()\ndef url():\n return global_data.url\n\n\n@pytest.fixture()\ndef username():\n return global_data.username\n\n\n@pytest.fixture()\ndef password():\n return global_data.password\n\n\n@pytest.fixture()\ndef cluster():\n return global_data.cluster\n\n\n@pytest.fixture()\ndef replication():\n return global_data.replication\n\n\n@pytest.fixture()\ndef secret():\n return global_data.secret\n\n\n@pytest.fixture()\ndef root_password():\n return global_data.root_password\n\n\n@pytest.fixture()\ndef enterprise():\n return global_data.enterprise\n\n\n@pytest.fixture()\ndef db_name():\n return global_data.db_name\n\n\n@pytest.fixture()\ndef docs():\n return [\n {\"_key\": \"1\", \"val\": 1, \"text\": \"foo\", \"loc\": [1, 1]},\n {\"_key\": \"2\", \"val\": 2, \"text\": \"foo\", \"loc\": [2, 2]},\n {\"_key\": \"3\", \"val\": 3, \"text\": \"foo\", \"loc\": [3, 3]},\n {\"_key\": \"4\", \"val\": 4, \"text\": \"bar\", \"loc\": [4, 4]},\n {\"_key\": \"5\", \"val\": 5, \"text\": \"bar\", \"loc\": [5, 5]},\n {\"_key\": \"6\", \"val\": 6, \"text\": \"bar\", \"loc\": [5, 5]},\n ]\n\n\n@pytest.fixture()\ndef fvdocs():\n return [\n {\"_key\": \"1\", \"val\": 1},\n {\"_key\": \"2\", \"val\": 2},\n {\"_key\": \"3\", \"val\": 3},\n ]\n\n\n@pytest.fixture()\ndef tvdocs():\n return [\n {\"_key\": \"4\", \"val\": 4},\n {\"_key\": \"5\", \"val\": 5},\n {\"_key\": \"6\", \"val\": 6},\n ]\n\n\n@pytest.fixture()\ndef edocs():\n fv = global_data.fvcol_name\n tv = global_data.tvcol_name\n return [\n {\"_key\": \"1\", \"_from\": f\"{fv}/1\", \"_to\": f\"{tv}/4\"},\n {\"_key\": \"2\", \"_from\": f\"{fv}/1\", \"_to\": f\"{tv}/5\"},\n {\"_key\": \"3\", \"_from\": f\"{fv}/6\", \"_to\": f\"{tv}/2\"},\n {\"_key\": \"4\", \"_from\": f\"{fv}/8\", \"_to\": f\"{tv}/7\"},\n ]\n","repo_name":"alexvanzyl/python-aioarango","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31584991279","text":"from .format_entry import FormatEntry\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 RandomDateFormatEntry(FormatEntry):\n \"\"\"\n The Random Date masking format generates random and unique dates within a range.\n The date range is defined by the startDate and endDate attributes. The start date\n must be less than or equal to the end date. When masking columns with uniqueness\n constraint, ensure that the date range is sufficient enough to generate unique\n values. To learn more, check Random Date in the Data Safe documentation.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new RandomDateFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.RandomDateFormatEntry.type` attribute\n of this class is ``RANDOM_DATE`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this RandomDateFormatEntry.\n Allowed values for this property are: \"DELETE_ROWS\", \"DETERMINISTIC_SUBSTITUTION\", \"DETERMINISTIC_ENCRYPTION\", \"DETERMINISTIC_ENCRYPTION_DATE\", \"FIXED_NUMBER\", \"FIXED_STRING\", \"LIBRARY_MASKING_FORMAT\", \"NULL_VALUE\", \"POST_PROCESSING_FUNCTION\", \"PRESERVE_ORIGINAL_DATA\", \"RANDOM_DATE\", \"RANDOM_DECIMAL_NUMBER\", \"RANDOM_DIGITS\", \"RANDOM_LIST\", \"RANDOM_NUMBER\", \"RANDOM_STRING\", \"RANDOM_SUBSTITUTION\", \"REGULAR_EXPRESSION\", \"SHUFFLE\", \"SQL_EXPRESSION\", \"SUBSTRING\", \"TRUNCATE_TABLE\", \"USER_DEFINED_FUNCTION\"\n :type type: str\n\n :param description:\n The value to assign to the description property of this RandomDateFormatEntry.\n :type description: str\n\n :param start_date:\n The value to assign to the start_date property of this RandomDateFormatEntry.\n :type start_date: datetime\n\n :param end_date:\n The value to assign to the end_date property of this RandomDateFormatEntry.\n :type end_date: datetime\n\n \"\"\"\n self.swagger_types = {\n 'type': 'str',\n 'description': 'str',\n 'start_date': 'datetime',\n 'end_date': 'datetime'\n }\n\n self.attribute_map = {\n 'type': 'type',\n 'description': 'description',\n 'start_date': 'startDate',\n 'end_date': 'endDate'\n }\n\n self._type = None\n self._description = None\n self._start_date = None\n self._end_date = None\n self._type = 'RANDOM_DATE'\n\n @property\n def start_date(self):\n \"\"\"\n **[Required]** Gets the start_date of this RandomDateFormatEntry.\n The lower bound of the range within which random dates should be generated.\n The start date must be less than or equal to the end date.\n\n\n :return: The start_date of this RandomDateFormatEntry.\n :rtype: datetime\n \"\"\"\n return self._start_date\n\n @start_date.setter\n def start_date(self, start_date):\n \"\"\"\n Sets the start_date of this RandomDateFormatEntry.\n The lower bound of the range within which random dates should be generated.\n The start date must be less than or equal to the end date.\n\n\n :param start_date: The start_date of this RandomDateFormatEntry.\n :type: datetime\n \"\"\"\n self._start_date = start_date\n\n @property\n def end_date(self):\n \"\"\"\n **[Required]** Gets the end_date of this RandomDateFormatEntry.\n The upper bound of the range within which random dates should be generated.\n The end date must be greater than or equal to the start date.\n\n\n :return: The end_date of this RandomDateFormatEntry.\n :rtype: datetime\n \"\"\"\n return self._end_date\n\n @end_date.setter\n def end_date(self, end_date):\n \"\"\"\n Sets the end_date of this RandomDateFormatEntry.\n The upper bound of the range within which random dates should be generated.\n The end date must be greater than or equal to the start date.\n\n\n :param end_date: The end_date of this RandomDateFormatEntry.\n :type: datetime\n \"\"\"\n self._end_date = end_date\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/data_safe/models/random_date_format_entry.py","file_name":"random_date_format_entry.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"} +{"seq_id":"21831013712","text":"stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam Sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', '’s-Hertogenbosch', 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']\n\n\ndef valid_station(station):\n if station in stations:\n return station\n else:\n print('Deze trein komt niet in ' + station)\n return False\n\n\ndef inlezen_beginstation():\n while True:\n station = input('Wat is je beginstation? ')\n if valid_station(station):\n return station\n\n\ndef inlezen_eindstation(beginstation):\n while True:\n eindstation = input('Wat is je eindstation? ')\n if valid_station(eindstation):\n if stations.index(beginstation) < stations.index(eindstation):\n return eindstation\n else:\n print('Uw eindstation moet verder zijn dan uw beginstation.')\n\n\ndef omroepen_reis(beginstation, eindstation):\n begin_index = stations.index(beginstation)\n end_index = stations.index(eindstation)\n diff = stations.index(eindstation) - stations.index(beginstation)\n\n print('\\nHet beginstation ' + beginstation + ' is het ' + str(begin_index + 1) + 'e station in het traject.')\n print('Het eindstation ' + eindstation + ' is het ' + str(end_index + 1) + 'e station in het traject.')\n print('De afstand bedraagt ' + str(diff) + ' station(s).')\n print('De prijs van het kaartje is ' + str(diff * 5) + ' euro.')\n\n print('\\nJij stapt in de trein in: ' + beginstation)\n for station in stations[begin_index + 1:end_index]:\n print('- ' + station)\n print('Jij stapt uit in: ' + eindstation)\n\n\nstart = inlezen_beginstation()\nend = inlezen_eindstation(start)\nomroepen_reis(start, end)\n","repo_name":"stefroes/Programming","sub_path":"10-containers-sets-chars/pe10_final.py","file_name":"pe10_final.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39303497224","text":"import os\nimport uuid\n\nimport dotenv\nimport fitz\nimport flask\nimport flask_login\nfrom flask import request, send_file, url_for, flash, redirect\nfrom flask_bcrypt import Bcrypt\nfrom flask_login import current_user\nfrom flask_migrate import Migrate\nfrom werkzeug.utils import secure_filename\n\nimport tools.file_orchestrator\nfrom tools.models import User, TemporaryDirectory, TemporaryLocation\nfrom tools.models import db # Import the SQLAlchemy db object\nfrom tools.verification_mail import EmailVerificator\n\ndotenv.load_dotenv()\n\napp = flask.Flask(__name__)\napp.config[\n \"SQLALCHEMY_DATABASE_URI\"\n] = r\"sqlite:///C:\\Users\\Flinn\\OneDrive\\Dokumente\\MusicStore\\database.db\"\n# = \"sqlite:////workspaces/MusicStore/database.db\"\n\n\napp.config[\"MAIL_SERVER\"] = os.getenv(\"MAIL_SERVER\")\napp.config[\"MAIL_PORT\"] = os.getenv(\"MAIL_PORT\")\napp.config[\"MAIL_USERNAME\"] = os.getenv(\"MAIL_USERNAME\")\napp.config[\"MAIL_PASSWORD\"] = os.getenv(\"MAIL_PASSWORD\")\napp.config[\"MAIL_USE_TLS\"] = os.getenv(\"MAIL_USE_TLS\")\napp.config[\"MAIL_USE_SSL\"] = os.getenv(\"MAIL_USE_SSL\")\n\napp.config[\"STORAGE_PATH\"] = os.getenv(\"STORAGE_PATH\")\n\nlogin_manager = flask_login.LoginManager()\n\napp.secret_key = os.getenv(\"APP_SECRET_KEY\")\n\nverificator = EmailVerificator(app)\nlogin_manager.init_app(app)\ndb.init_app(app)\nbcrypt = Bcrypt(app)\n\n\nmigrate = Migrate(app, db)\n\norchestrator = tools.file_orchestrator.FileOrchestrator(database=db)\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User.get(user_id)\n\n\n@app.route(\"/\")\ndef index():\n return flask.render_template(\n \"index.html\", ids=orchestrator.get_user_pieces(user=current_user)\n )\n\n\ndef allowed_file(filename: str):\n print(filename)\n return True\n\n\n@app.route(\"/upload_file\", methods=[\"POST\", \"Get\"])\ndef upload_file():\n if request.method == \"POST\":\n # check if the post request has the file part\n if \"file\" not in request.files:\n flash(\"No file part\")\n return redirect(request.url)\n\n files = request.files.to_dict(flat=False)\n piece_id = str(\n request.form.get(\"piece_id\")\n if request.form.get(\"piece_id\")\n else orchestrator.get_automatic_next_id()\n )\n # TODO: This is an AI Feature for name detection. You need to be able to disable this. But this is a very cool feature.\n # song_name = tools.ai_functionality.get_song_name_from_content(\n # files.get(\"file\")[0].stream.read()\n # )\n song_name = files.get(\"file\")[0].filename\n # os.mkdir(os.path.join(app.config[\"STORAGE_PATH\"], piece_id))\n\n # TODO: Add temporary storage for the files. The files should be saved in the right directory on submit in the\n # init song.html form\n print(\"Starting tempdir\")\n with TemporaryDirectory(delete=False) as tmpdir:\n print(\"created temporary directory\", tmpdir.path)\n print(tmpdir.id)\n\n location = TemporaryLocation(id=tmpdir.id, path=tmpdir.path)\n print(location)\n db.session.add(location)\n db.session.commit()\n\n for file in files.get(\"file\"):\n if file:\n filename = secure_filename(file.filename)\n filename = f\"{uuid.uuid4()}.{filename}\"\n file.save(os.path.join(tmpdir.path, filename))\n print(\"-------\")\n print(tmpdir.id)\n print(type(tmpdir.id))\n print(tmpdir.path)\n print(type(tmpdir.path))\n print(\"-------\")\n\n if filename.endswith(\".pdf\"):\n for index, page in enumerate(\n fitz.open(location.get_filepath(filename)) # noqa\n ):\n print(location.get_filepath(filename))\n print(filename)\n pix = page.get_pixmap()\n pix.save(\n f\"{tmpdir.path}/{filename.split('.')[0]}_page_{index}.png\"\n )\n return flask.render_template(\n \"init_song.html\",\n song_title=song_name,\n automatic_id=orchestrator.get_automatic_next_id(),\n stored_id=tmpdir.id,\n files=orchestrator.render_files_for_flask(tmpdir),\n )\n elif request.method == \"GET\":\n return flask.render_template(\n \"upload_file.html\", automatic_id=orchestrator.get_automatic_next_id()\n )\n\n\n@app.route(\"/load_preview\", methods=[\"GET\"])\ndef load_preview():\n folder_id: str = str(flask.request.args.get(\"folder_id\"))\n part_id: str = str(flask.request.args.get(\"part_id\"))\n\n print(f\"Requested {part_id} preview from {folder_id}\")\n print(orchestrator.get_filepath(folder_id, part_id, preview=True))\n return send_file(\n orchestrator.get_filepath(folder_id, part_id, preview=True),\n mimetype=\"image/png\",\n )\n\n\n@app.route(\"/finish_setup\", methods=[\"POST\"])\ndef finish_setup():\n data = request.json\n\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if flask.request.method == \"POST\":\n full_name = flask.request.form[\"full_name\"]\n username = flask.request.form[\"username\"]\n email = flask.request.form[\"email\"]\n password = flask.request.form[\"password\"]\n\n hashed_password = bcrypt.generate_password_hash(password).decode(\"utf-8\")\n\n # Create a new user\n user = User(\n full_name=full_name,\n username=username,\n email=email,\n password_hash=hashed_password,\n )\n db.session.add(user)\n db.session.commit()\n\n flask.flash(\"Registration successful. You can now log in.\", \"success\")\n return flask.redirect(flask.url_for(\"login\"))\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if flask.request.method == \"POST\":\n email = flask.request.form[\"email\"]\n password = flask.request.form[\"password\"]\n\n user = User.query.filter_by(email=email).first()\n\n if user and bcrypt.check_password_hash(user.password_hash, password):\n # Log in the user\n flask.flash(\"Login successful.\", \"success\")\n return flask.redirect(url_for(\"profile\"))\n else:\n flask.flash(\"Login failed. Please check your email and password.\", \"error\")\n\n return flask.render_template(\"login.html\")\n\n\n@app.route(\"/profile\")\ndef profile():\n # Implement your profile view here\n return \"User Profile\"\n\n\n@app.route(\"/create_table\")\ndef create_table_on_flask():\n db.create_all()\n return \"Ok\", 202\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"DiscoveryFox/MusicStore","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6750,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"20203875841","text":"import argparse\r\nimport torch\r\nimport os\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom MLP_Layer import MLPLayer\r\nfrom tqdm import tqdm\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport copy\r\nimport seaborn\r\nfrom mog import data_generator\r\nimport math\r\n\r\n# torch.manual_seed(123)\r\nc = 1e-5\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n\r\nparser = argparse.ArgumentParser(description='PyTorch MNIST WAE-GAN_server1')\r\nparser.add_argument('-batch_size', type=int, default= 100, metavar='N',help='input batch size for training (default: 100)')\r\nparser.add_argument('-sample_size', type=int, default=100, metavar='N',help='input batch size for training (default: 100)')\r\nparser.add_argument('-iterations', type=int, default=30000, help='number of epochs to train (default: 100)')\r\nparser.add_argument('-interval', type=int, default=5000)\r\nparser.add_argument('-lr', type=float, default= 1e-3, help='learning rate (default: 0.0001)')\r\nparser.add_argument('-dim_h', type=int, default=16 , help='hidden dimension (default: 128)')\r\nparser.add_argument('-n_z', type=int, default= 32, help='hidden dimension of z (default: 8)')\r\nparser.add_argument('-LAMBDA', type=float, default=1, help='regularization coef MMD term (default: 10)')\r\nparser.add_argument('-sigma_z', type=float, default=1, help='variance of hidden dimension (default: 1)')\r\nparser.add_argument('-sigma_prior', type=float, default=torch.tensor(np.exp(-3)).to(device))\r\nparser.add_argument('-n_mc', type=int, default=5)\r\nparser.add_argument('-n_input', type=int, default=2)\r\nparser.add_argument('-optim_betas', type=tuple, default=(0.5, 0.999))\r\nargs = parser.parse_args()\r\n\r\nplt.style.use('ggplot')\r\ndset = data_generator()\r\ndset.uniform_distribution()\r\nsample_dir = './wae_gaussian_z32_h16/'\r\nif not os.path.exists(sample_dir):\r\n os.makedirs(sample_dir)\r\n\r\n\r\ndef plot(points, title):\r\n plt.scatter(points[:, 0], points[:, 1], s=10, c='b', alpha=0.5)\r\n plt.scatter(dset.centers[:, 0], dset.centers[:, 1], s= 100, c='g', alpha=0.5)\r\n plt.title(title)\r\n plt.ylim(-5, 5)\r\n plt.xlim(-5, 5)\r\n plt.savefig( sample_dir + title + '.png')\r\n plt.clf()\r\n # plt.show()\r\n # plt.close()\r\n\r\n\r\ndef free_params(module: nn.Module):\r\n for p in module.parameters():\r\n p.requires_grad = True\r\n\r\n\r\ndef frozen_params(module: nn.Module):\r\n for p in module.parameters():\r\n p.requires_grad = False\r\n\r\n\r\nclass Encoder(nn.Module):\r\n def __init__(self, args):\r\n super(Encoder, self).__init__()\r\n\r\n self.dim_h = args.dim_h\r\n self.n_z = args.n_z\r\n self.input = args.n_input\r\n\r\n self.l1 = MLPLayer(self.input, self.dim_h, args.sigma_prior)\r\n self.l1_act = nn.Tanh()\r\n self.l2 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l2_act = nn.Tanh()\r\n self.l3 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l3_act = nn.Tanh()\r\n self.l4 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l4_act = nn.Tanh()\r\n self.l5 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l5_act = nn.Tanh()\r\n self.l6 = MLPLayer(self.dim_h, self.n_z, args.sigma_prior)\r\n\r\n def forward(self, x):\r\n output = self.l1_act(self.l1(x))\r\n output = self.l2_act(self.l2(output))\r\n output = self.l3_act(self.l3(output))\r\n output = self.l4_act(self.l4(output))\r\n output = self.l5_act(self.l5(output))\r\n output = self.l6(output)\r\n return output\r\n\r\n def get_lpw_lqw(self):\r\n lpw = self.l1.lpw + self.l2.lpw + self.l3.lpw + self.l4.lpw + self.l5.lpw + self.l6.lpw\r\n lqw = self.l1.lqw + self.l2.lqw + self.l3.lqw + self.l4.lqw + self.l5.lqw + self.l6.lqw\r\n return lpw, lqw\r\n\r\n\r\nclass Decoder(nn.Module):\r\n def __init__(self, args):\r\n super(Decoder, self).__init__()\r\n\r\n self.output = args.n_input\r\n self.dim_h = args.dim_h\r\n self.n_z = args.n_z\r\n\r\n self.l1 = MLPLayer(self.n_z, self.dim_h, args.sigma_prior)\r\n self.l1_act = nn.Tanh()\r\n self.l2 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l2_act = nn.Tanh()\r\n self.l3 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l3_act = nn.Tanh()\r\n self.l4 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l4_act = nn.Tanh()\r\n self.l5 = MLPLayer(self.dim_h, self.dim_h, args.sigma_prior)\r\n self.l5_act = nn.Tanh()\r\n self.l6 = MLPLayer(self.dim_h, self.output, args.sigma_prior)\r\n\r\n\r\n def forward(self, z):\r\n output = self.l1_act(self.l1(z))\r\n output = self.l2_act(self.l2(output))\r\n output = self.l3_act(self.l3(output))\r\n output = self.l4_act(self.l4(output))\r\n output = self.l5_act(self.l5(output))\r\n output = self.l6(output)\r\n return output\r\n\r\n def get_lpw_lqw(self):\r\n lpw = self.l1.lpw + self.l2.lpw + self.l3.lpw + self.l4.lpw + self.l5.lpw + self.l6.lpw\r\n lqw = self.l1.lqw + self.l2.lqw + self.l3.lqw + self.l4.lqw + self.l5.lqw + self.l6.lqw\r\n return lpw, lqw\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self, args):\r\n super(Discriminator, self).__init__()\r\n\r\n self.dim_h = args.dim_h\r\n self.n_z = args.n_z\r\n\r\n self.main = nn.Sequential(\r\n nn.Linear(self.n_z, self.dim_h),\r\n # nn.BatchNorm1d(self.dim_h),\r\n nn.LeakyReLU(0.2),\r\n nn.Linear(self.dim_h, self.dim_h),\r\n # nn.BatchNorm1d(self.dim_h),\r\n nn.LeakyReLU(0.2),\r\n nn.Linear(self.dim_h, self.dim_h),\r\n # nn.BatchNorm1d(self.dim_h),\r\n nn.LeakyReLU(0.2),\r\n nn.Linear(self.dim_h, self.dim_h),\r\n # nn.BatchNorm1d(self.dim_h),\r\n nn.LeakyReLU(0.2),\r\n nn.Linear(self.dim_h, 1),\r\n # nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x):\r\n x = self.main(x)\r\n return x\r\n\r\n\r\ndef forward_pass_samples(x, real_labels):\r\n enc_kl, dec_kl, enc_scores, sam_scores = torch.zeros(args.n_mc), torch.zeros(args.n_mc), torch.zeros(\r\n args.n_mc), torch.zeros(args.n_mc)\r\n enc_log_likelihoods, dec_log_likelihoods = torch.zeros(args.n_mc), torch.zeros(args.n_mc)\r\n for i in range(args.n_mc):\r\n z_enc = encoder(x)\r\n x_rec = decoder(z_enc)\r\n rec_loss = mse_sum(x_rec, x)\r\n d_enc = discriminator(z_enc)\r\n # div_loss = -args.LAMBDA * (torch.log(d_enc)).sum()\r\n div_loss = bcewl_sum(d_enc, real_labels)\r\n # print(\"rec_loss\",rec_loss.item())\r\n # print(\"div_loss\",div_loss.item())\r\n enc_log_likelihood = rec_loss * 10 + div_loss\r\n dec_log_likelihood = rec_loss * 10 + div_loss\r\n\r\n enc_log_pw, enc_log_qw = encoder.get_lpw_lqw()\r\n dec_log_pw, dec_log_qw = decoder.get_lpw_lqw()\r\n\r\n enc_kl[i] = enc_log_qw - enc_log_pw\r\n dec_kl[i] = dec_log_qw - dec_log_pw\r\n enc_log_likelihoods[i] = enc_log_likelihood\r\n dec_log_likelihoods[i] = dec_log_likelihood\r\n enc_scores[i] = d_enc.mean()\r\n # sam_scores[i] = d_sam.mean()\r\n\r\n return enc_kl.mean(), dec_kl.mean(), enc_log_likelihoods.mean(), dec_log_likelihoods.mean(), enc_scores.mean() # , sam_scores.mean()\r\n\r\n\r\nencoder, decoder, discriminator = Encoder(args).to(device), Decoder(args).to(device), Discriminator(args).to(device)\r\nmse = nn.MSELoss()\r\nmse_sum = nn.MSELoss(reduction= 'sum')\r\nbcewl = nn.BCEWithLogitsLoss()\r\nbcewl_sum = nn.BCEWithLogitsLoss(reduction= 'sum')\r\nbce = nn.BCELoss()\r\n\r\ndef criterion(kl, log_likelihood):\r\n # print(\"kl\" , kl.item())\r\n # print(\"likelihood\", log_likelihood.item())\r\n return kl / 1000 + log_likelihood\r\n\r\n\r\n\r\ndef dec_sample():\r\n with torch.no_grad():\r\n z_sam = (torch.randn(args.sample_size, args.n_z) * args.sigma_z).to(device)\r\n x_rec = decoder(z_sam)\r\n return x_rec.cpu().numpy()\r\n\r\ndef plot_samples(samples):\r\n xmax = 5\r\n rows = 3\r\n cols = math.ceil(len(samples)/rows)\r\n bg_color = seaborn.color_palette('Greens', n_colors=256)[0]\r\n #plt.figure(figsize=(3 * cols, * cols))\r\n for i, samps in enumerate(samples):\r\n if i == 0:\r\n ax = plt.subplot(rows, cols , 1)\r\n else:\r\n plt.subplot(rows, cols, i + 1, sharex=ax, sharey=ax)\r\n ax2 = seaborn.kdeplot(samps[:, 0], samps[:, 1], shaded=True, cmap='Greens', n_levels=20, clip=[[-xmax, xmax]] * 2)\r\n ax2.set_facecolor(bg_color)\r\n plt.xticks([])\r\n plt.yticks([])\r\n if i % 2 == 0 :\r\n plt.title('iteration %d' % (i/2 * args.interval))\r\n else :\r\n plt.title('ground truth')\r\n\r\n plt.gcf().tight_layout()\r\n plt.savefig(sample_dir + \"iterations.png\")\r\n\r\n\r\n\r\n\r\n\r\n# Optimizers\r\nenc_optim = optim.Adam(encoder.parameters(), lr=args.lr) # betas = args.optim_betas\r\ndec_optim = optim.Adam(decoder.parameters(), lr=args.lr)\r\ndis_optim = optim.Adam(discriminator.parameters(), lr= args.lr * 0.1)\r\n\r\n# enc_sch = StepLR(enc_optim, step_size= 9000, gamma= 0.1)\r\n# dec_sch = StepLR(dec_optim, step_size= 9000, gamma= 0.1)\r\n# dis_sch = StepLR(dis_optim, step_size= 9000, gamma= 0.1)\r\n\r\n\r\n\r\n\r\n#samples = []\r\nfor it in range(args.iterations):\r\n # enc_sch.step()\r\n # dec_sch.step()\r\n # dis_sch.step()\r\n x = torch.from_numpy(dset.sample(args.batch_size)).to(device)\r\n real_labels = torch.ones(args.batch_size, 1).to(device)\r\n fake_labels = torch.zeros(args.batch_size, 1).to(device)\r\n\r\n # ======== Train Generator ======== #\r\n free_params(decoder)\r\n free_params(encoder)\r\n frozen_params(discriminator)\r\n\r\n enc_kl, dec_kl, enc_log_likelihood, dec_log_likelihood, enc_scores = forward_pass_samples(x, real_labels)\r\n enc_loss = criterion(enc_kl, enc_log_likelihood)\r\n dec_loss = criterion(dec_kl, dec_log_likelihood)\r\n # enc_loss = enc_criterion_reW(enc_kl, (it + 1), enc_log_likelihood)\r\n # dec_loss = dec_criterion_reW(dec_kl, (it + 1), dec_log_likelihood)\r\n\r\n encoder.zero_grad()\r\n decoder.zero_grad()\r\n enc_loss.backward(retain_graph=True)\r\n enc_optim.step()\r\n\r\n encoder.zero_grad()\r\n decoder.zero_grad()\r\n dec_loss.backward(retain_graph=True)\r\n dec_optim.step()\r\n\r\n # ======== Train Discriminator ======== #\r\n frozen_params(decoder)\r\n frozen_params(encoder)\r\n free_params(discriminator)\r\n\r\n\r\n z_sam = (torch.randn(args.batch_size, args.n_z) * args.sigma_z).to(device) # images.size()[0] -> 100\r\n d_sam = discriminator(z_sam)\r\n d_loss_real = bcewl(d_sam, real_labels)\r\n\r\n z_enc = encoder(x)\r\n d_enc = discriminator(z_enc)\r\n d_loss_fake = bcewl(d_enc, fake_labels)\r\n # dis_loss = (-torch.log(d_sam).mean() - torch.log(1 - d_enc).mean())\r\n # dis_loss = args.LAMBDA * (-torch.log(d_sam + c).sum() + torch.log(d_enc + c).sum())\r\n dis_loss = d_loss_real + d_loss_fake\r\n # print(\"dis_loss\",dis_loss.item())\r\n encoder.zero_grad()\r\n decoder.zero_grad()\r\n discriminator.zero_grad()\r\n dis_loss.backward()\r\n dis_optim.step()\r\n\r\n if (it + 1) % args.interval == 0:\r\n x_rec = dec_sample()\r\n # samples.append(x_rec)\r\n # samples.append(x.cpu().numpy())\r\n plot(x_rec, title =' Iteration {}'.format(it + 1))\r\n print(\"iteration [{}/{}], enc_Loss: {:.4f} ,dec_Loss: {:.4f}, dis_Loss: {:.4f}, enc_kl: {:.4f}, dec_kl: {:.4f},\"\r\n .format(it + 1, args.iterations, enc_log_likelihood.item(), dec_log_likelihood.item(), dis_loss.item(), enc_kl.item(), dec_kl.item()))\r\n\r\n\r\n#plot_samples(samples)","repo_name":"NCTUMLlab/Chun-Lin-Kuo-Mixtures-of-Gaussian","sub_path":"vbgan_w_mog.py","file_name":"vbgan_w_mog.py","file_ext":"py","file_size_in_byte":11609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21162435726","text":"import os, sys, csv, subprocess\n\nfile_type = '.mp4'\nfile_types = ['.mp4', '.MXF', '.mxf']\n\n\ndef run_command(command, logfile=None, print_output=False, return_output=False):\n print(f'command: {command}')\n if logfile != None:\n command += ' |& tee ' + logfile\n output = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n executable='/bin/bash'\n ).stdout.read()\n if print_output:\n print(output)\n if return_output:\n return str(output)\n\n\n# list to store the names of the files\nmfiles_to_extract = []\nsource_roots = \"/dvmm-filer2/projects/Hearst/data_new\"\n# count how many .mp4, .mxf, .MXF are in the source root - don't count duplicates\nfile_counter = 0\nfor root, dirs, files in os.walk(source_roots):\n for file in files:\n # for ft in file_types:\n for f_type in file_types:\n if file.endswith(f_type) and file not in mfiles_to_extract:\n file_counter += 1\n file_name_w_path = os.path.join(root, file)\n print(file_name_w_path)\n mfiles_to_extract.append(file_name_w_path)\n\nprint(f'Total # of files that end with .mp4, .MXF, .mxf: {len(mfiles_to_extract)}. \\n')\n\n# extract\ndest_root = '/dvmm-filer2/projects/Hearst/keyframes/keyframes2_dec_20'\n\nunsuc = []\nfor i, filename in enumerate(mfiles_to_extract):\n dest_dir = filename.replace('/dvmm-filer2/projects/Hearst/data_new', dest_root)\n\n if os.path.exists(dest_dir):\n print('path exists - SKIPPING')\n continue\n\n print('extraction about to start in: ')\n print(dest_dir)\n run_command(f\"mkdir -p '{dest_dir}'\")\n out = run_command(\n f\"ffmpeg -i '{filename}' -vf select='eq(n\\,1)+gt(scene\\,0.2)' -vsync vfr '{dest_dir}/frame%05d.png'\",\n logfile=f\"'{dest_dir}/log.txt'\",\n return_output=True\n )\n if 'failed' in out:\n print(f'Processing {filename} failed.----*******-------')\n unsuc.append(filename)\n\n print(f'{i+1} out of {len(mfiles_to_extract)} videos processed.')\n\nwith open(os.path.join(dest_root, 'unsuc.txt'), 'w') as fout:\n for item in unsuc:\n fout.write(unsuc)\n fout.write('\\n')","repo_name":"gitskim/ObjectDetection","sub_path":"modified_extract_keyframes_12_20.py","file_name":"modified_extract_keyframes_12_20.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4628964135","text":"# Originally written by Kyle McCulloh\n# Ported to Python by Norton Pengra\nimport io\nimport os\n\ndef download116District():\n if not os.path.isdir(\"116_congressional_districts\"):\n os.mkdir(\"116_congressional_districts\")\n\n target = \"https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_cd116_20m.zip\"\n os.system(f\"wget -O temp.zip https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_cd116_20m.zip\")\n os.system(f\"unzip temp.zip -d 116_congressional_districts/\")\n os.system(f\"rm temp.zip\")\n\ndef main():\n with io.open(\"stateKeys.csv\") as handle:\n lines = handle.readlines()\n\n for line in lines:\n line = line.strip()\n fips, state_code, state_name, state_ns = line.split(',')\n\n if not os.path.isdir(state_name):\n print(f\"Creating Directory for {state_name}\")\n state_name = state_name.lower().replace(' ', '_')\n os.mkdir(f\"{state_name}\")\n else:\n print(f\"Directory already exists for {state_name}\")\n\n if not os.path.isfile(f\"{state_name}/{state_name}.csv\"):\n print(f\"Downloading 2010 {state_name.title()} Census Data\")\n os.system(f\"wget -O - http://censusdata.ire.org/{fips}/all_140_in_{fips}.P3.csv | gunzip > {state_name}/{state_name}.csv\")\n\n\n if not os.path.isdir(f\"{state_name}/vtd/\"):\n os.mkdir(f\"{state_name}/vtd\")\n print(f\"Downloading 2010 {state_name.title()} Census VTD shapefiles\")\n os.system(f\"wget -O {state_name}/temp.zip https://www2.census.gov/geo/tiger/TIGER2012/VTD/tl_2012_{fips}_vtd10.zip\")\n os.system(f\"unzip {state_name}/temp.zip -d {state_name}/vtd/\")\n os.system(f\"rm {state_name}/temp.zip\")\n\n if not os.path.isdir(f\"{state_name}/tracts/\"):\n os.mkdir(f\"{state_name}/tracts\")\n print(f\"Downloading 2018 {state_name.title()} Census Tract shapefiles\")\n os.system(f\"wget -O {state_name}/temp.zip https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_{fips}_tract_500k.zip\")\n os.system(f\"unzip {state_name}/temp.zip -d {state_name}/tracts/\")\n os.system(f\"rm {state_name}/temp.zip\")\n\n if not os.path.isdir(f\"{state_name}/votes\"):\n os.mkdir(f\"{state_name}/votes\")\n\nif __name__ == \"__main__\":\n download116District()\n # main()","repo_name":"project-rakan/bladecaller","sub_path":"data/downloadAll.py","file_name":"downloadAll.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"293402189","text":"import matplotlib.pyplot as plt\nfrom matplotlib.widgets import Cursor\n\nimg = plt.imread('../clases/figuras/imagen_flujo_gray.jpg')\nymax = img.max()\n\ndef seleccionar(event):\n \"\"\"Secuencia:\n 1. Encuentro el punto donde el mouse hizo 'click'\n 2. Le doy valores a la línea vertical\n 3. Le doy valores a la curva en el grafico de la derecha\n 4. y 5. Grafico los nuevos valores\n \"\"\"\n x0 = event.xdata\n n0 = int(x0)\n l1.set_data([[n0, n0], [0., 1.]])\n l2.set_data(range(img.shape[0]), img[:, n0])\n l1.figure.canvas.draw()\n l2.figure.canvas.draw()\n\n\n# Defino la figura\nfig, (ax1, ax2) = plt.subplots(figsize=(12, 4), ncols=2)\n\n# Mostramos la imagen como un mapa de grises\nax1.imshow(img, cmap='gray', interpolation='nearest')\nax1.axis('off')\n\n# Agrego la línea inicial en un valor inicial\nx0 = 100\nl1 = ax1.axvline(x0, color='r', ls='--', lw=3)\n\n# Grafico de la derecha\nl2, = ax2.plot(img[:, x0], 'r-', lw=2, label='corte')\nax2.set_ylim((0, ymax))\nax2.set_xlabel(u'posición en eje $y$ (pixels)')\nax2.set_ylabel('Intensidad')\nax2.legend(loc='best')\n\nfig.tight_layout()\n\n# Agrego el cursor y conecto la accion de presionar a la funcion click\ncursor = Cursor(ax1, horizOn=True, vertOn=True, useblit=True,\n color='blue', linewidth=1)\nfig.canvas.mpl_connect('motion_notify_event', seleccionar)\n\nplt.show()","repo_name":"fiolj/intro-python-IB","sub_path":"scripts/analizar_figura.py","file_name":"analizar_figura.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"es","doc_type":"code","stars":22,"dataset":"github-code","pt":"52"} +{"seq_id":"31570102304","text":"import xarray as xr\nimport geoutils.utils.time_utils as tu\nimport geoutils.tsa.time_series_analysis as tsa\n\nfrom importlib import reload\n\n# ############################ MJO #####################################\n\n\ndef get_mjo_index(time_range=['1981-01-01', '2020-01-01'],\n start_month='Jan', end_month='Dec'):\n # RMM Index\n rmm_index = xr.open_dataset('/home/strnad/data/MJO-RMM/rmm_index.nc')\n rmm_index = tu.get_time_range_data(rmm_index, time_range=time_range)\n rmm_index = tu.get_month_range_data(rmm_index,\n start_month=start_month,\n end_month=end_month)\n return rmm_index\n\n\ndef get_mjophase_tps(phase_number,\n time_range=['1981-01-01', '2020-01-01'],\n start_month='Jan', end_month='Dec',\n active=None,\n ):\n reload(tsa)\n reload(tu)\n rmm_index = get_mjo_index(time_range=time_range, start_month=start_month,\n end_month=end_month)\n ampl = rmm_index['amplitude']\n tps = tsa.get_tps4val(ts=rmm_index['phase'], val=phase_number)\n if active is not None:\n if active:\n tps = tu.get_sel_tps_ds(\n ds=tps, tps=ampl.where(ampl >= 1, drop=True).time)\n else:\n tps = tu.get_sel_tps_ds(\n ds=tps, tps=ampl.where(ampl < 1, drop=True).time)\n return tps\n\n# %%\nif __name__ == \"__main__\":\n # %%\n # RMM\n rmm_file1 = '/home/strnad/data/MJO-RMM/data1.nc'\n rmm_file2 = '/home/strnad/data/MJO-RMM/data2.nc'\n rmm_file_ampl = '/home/strnad/data/MJO-RMM/data_ampl.nc'\n rmm_file_phase = '/home/strnad/data/MJO-RMM/data_phase.nc'\n v1 = 'RMM1'\n v2 = 'RMM2'\n va = 'amplitude'\n vp = 'phase'\n rmm1_index_raw = xr.open_dataset(rmm_file1)\n rmm2_index_raw = xr.open_dataset(rmm_file2)\n rmm_ampl_index_raw = xr.open_dataset(rmm_file_ampl)\n rmm_phase_index_raw = xr.open_dataset(rmm_file_phase)\n\n # %%\n reload(tu)\n tps_mjo = tu.get_dates_of_time_range(\n time_range=['1974-06-01', '2022-02-21']) # Downloaded 23.02.2022\n\n rmm1_index = xr.DataArray(\n data=rmm1_index_raw[v1].data,\n dims=['time'],\n coords=dict(\n time=tps_mjo\n ),\n name=v1\n )\n savepath_rmm1 = '/home/strnad/data/MJO-RMM/rmm1.nc'\n rmm1_index.to_netcdf(savepath_rmm1)\n\n # %%\n rmm2_index = xr.DataArray(\n data=rmm2_index_raw[v2].data,\n dims=['time'],\n coords=dict(\n time=tps_mjo\n ),\n name=v2\n )\n savepath_rmm2 = '/home/strnad/data/MJO-RMM/rmm2.nc'\n rmm1_index.to_netcdf(savepath_rmm2)\n # %%\n # Ampl\n rmm_index_ampl = xr.DataArray(\n data=rmm_ampl_index_raw[va].data,\n dims=['time'],\n coords=dict(\n time=tps_mjo\n ),\n name=va\n )\n savepath_rmm_ampl = '/home/strnad/data/MJO-RMM/rmm_ampl.nc'\n rmm_index_ampl.to_netcdf(savepath_rmm_ampl)\n # %%\n # Phase\n rmm_index_phase = xr.DataArray(\n data=rmm_phase_index_raw[vp].data,\n dims=['time'],\n coords=dict(\n time=tps_mjo\n ),\n name=vp\n )\n savepath_rmm_phase = '/home/strnad/data/MJO-RMM/rmm_ampl.nc'\n rmm_index_phase.to_netcdf(savepath_rmm_phase)\n\n # %%\n rmm_index = xr.merge(\n [rmm1_index, rmm2_index, rmm_index_ampl, rmm_index_phase])\n savepath_rmm = '/home/strnad/data/MJO-RMM/rmm_index.nc'\n rmm_index.to_netcdf(savepath_rmm)\n # %%\n","repo_name":"fstrnad/geoutils","sub_path":"geoutils/indices/mjo_index.py","file_name":"mjo_index.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"11490411609","text":"import logging\nimport aiohttp\nimport aiofiles\nimport time\nimport os\n\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom aiogram.dispatcher.filters import Text\nfrom aiogram.types import InputFile, ReplyKeyboardRemove\nfrom aiogram.dispatcher.filters.state import StatesGroup, State\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\n\nfrom services.weather import weather_json_to_text\nfrom services.currency import get_acronyms\nfrom keyboards import default_keyboard, anon_keyboard\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\nAPI_TOKEN = os.environ.get(\"API_TOKEN\")\nWEATHER_TOKEN = os.environ.get(\"WEATHER_TOKEN\")\nCURRENCY_TOKEN = os.environ.get(\"CURRENCY_TOKEN\")\n\n# Конфигурация логирования\nlogging.basicConfig(level=logging.INFO)\n\n# Инициализация бота, хранилища и диспетчера\nbot = Bot(token=API_TOKEN)\nstorage = MemoryStorage()\ndp = Dispatcher(bot, storage=storage)\n\n\nclass UserState(StatesGroup):\n \"\"\"\n Класс предоставляет 5 состояний, от которых зависит поведение бота\n - weather для обработки запросов прогноза погоды\n - currency для обработки запросов конвертации валют\n - poll_anon для обработки указания типа голосования: публичный или анонимный\n - poll_topic для обработки указания названия голосования\n - poll_options для обработки вариантов ответа\n \"\"\"\n weather = State()\n currency = State()\n poll_anon = State()\n poll_topic = State()\n poll_options = State()\n\n\n@dp.message_handler(commands=[\"cancel\"], state=UserState.all_states)\nasync def cancel(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется для отмены текущей операции, отменяя текущее состояние\n :param message:\n :param state:\n :return:\n \"\"\"\n await state.finish()\n await message.answer(\"Вы отменили операцию\")\n await message.answer(\"Какой функцией бота вы хотите воспользоваться?\", reply_markup=default_keyboard)\n\n\n@dp.message_handler(commands=[\"state\"], state=\"*\")\nasync def check_state(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется для определения текущего состояния бота для дебага\n :param message:\n :param state:\n :return:\n \"\"\"\n state_name = await state.get_state()\n if state_name is None:\n state_name = \"Без состояния\"\n await message.answer(state_name)\n\n\n@dp.message_handler(commands=[\"start\", \"help\"])\nasync def send_welcome(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется для отправки приветственного меню\n :param message:\n :param state:\n :return:\n \"\"\"\n await state.finish()\n await message.answer(\"Какой функцией бота вы хотите воспользоваться?\", reply_markup=default_keyboard)\n\n\n@dp.message_handler(Text(equals=\"Картинка с котиком\", ignore_case=True))\nasync def send_cat(message: types.Message):\n \"\"\"\n Метод используется для загрузки, сохранения и отправки случайной картинки с кошками\n :param message:\n :return:\n \"\"\"\n time_now = time.time()\n user_id = message.from_user.id\n path = f\"static/{user_id}_{time_now}.png\"\n url = \"https://cataas.com/cat\"\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as resp:\n if resp.status == 200:\n f = await aiofiles.open(path, mode='wb')\n await f.write(await resp.read())\n await f.close()\n try:\n photo = InputFile(path)\n await bot.send_photo(message.chat.id, photo=photo, reply_markup=default_keyboard)\n except BaseException:\n await message.answer(\"Простите, сервер с котиками отвалился\", reply_markup=default_keyboard)\n\n\n@dp.message_handler(Text(equals=\"Погода\", ignore_case=True))\nasync def send_weather(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется, чтобы привести бота в состояние weather, чтобы дальнейшее сообщение пользователя\n регистрировалось как город, для которого требуется сделать запрос на прогноз погоды\n :param message:\n :param state:\n :return:\n \"\"\"\n await message.answer(\"Для отмены операции нажмите на шторку около поля ввода и выберите /cancel\")\n await message.answer(\"Введите ваш город\")\n await UserState.weather.set()\n\n\n@dp.message_handler(state=UserState.weather)\nasync def process_weather_state(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется, чтобы в состоянии weather обработать сообщение пользователя, в котором он отправит нужный город,\n и в ответ отправить погоду\n :param message:\n :param state:\n :return:\n \"\"\"\n url = f\"https://api.openweathermap.org/data/2.5/weather?q={message.text}&appid={WEATHER_TOKEN}&lang=ru&units=metric\"\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as resp:\n if resp.status == 200:\n response = await resp.json()\n refined_response = await weather_json_to_text(response)\n await state.finish()\n await message.answer(refined_response, reply_markup=default_keyboard)\n else:\n refined_response = \"Не удалось найти данные. Возможно, вы неверно указали название города...\\n\" \\\n \"Попробуйте снова\"\n await message.answer(refined_response)\n\n\n@dp.message_handler(commands=[\"codes\"], state=\"*\")\nasync def get_codes(message: types.Message, state: FSMContext):\n await message.answer(await get_acronyms())\n\n\n@dp.message_handler(Text(equals=\"Курс валют\", ignore_case=True))\nasync def send_currency(message: types.Message):\n \"\"\"\n Метод используется, чтобы привести бота в состояние currency, чтобы дальнейшее сообщение пользователя\n регистрировалось как запрос на конвертацию\n :param message:\n :return:\n \"\"\"\n await UserState.currency.set()\n await message.answer(\"Для отмены операции нажмите на шторку около поля ввода и выберите /cancel\")\n await message.answer(\"Пожалуйста, введите строку в формате:\\n<Из> <Количество> <В>\\nНапример: RUB 5000 USD\\n\"\n \"Со списком кодов валют вы можете ознакомиться с помощью команды /codes\")\n\n\n@dp.message_handler(state=UserState.currency)\nasync def process_currency_state(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется, чтобы в состоянии currency обработать сообщение пользователя, в котором он отправит строку\n по образцу, сделать запрос на API сервиса по конвертации и выдать результат пользователю\n :param message:\n :param state:\n :return:\n \"\"\"\n try:\n cur_from, amount, cur_to = message.text.split(\" \")\n url = f\"https://api.api-ninjas.com/v1/convertcurrency?want={cur_to}&have={cur_from}&amount={amount}\"\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as resp:\n if resp.status == 200:\n response = await resp.json()\n refined_response = f\"Из {amount} {cur_from} вы получите {response['new_amount']} {cur_to}\"\n await state.finish()\n await message.answer(refined_response, reply_markup=default_keyboard)\n else:\n refined_response = \"Конвертация не удалась. Возможно, вы неверно указали коды валют...\\n\" \\\n \"Попробуйте снова\"\n await message.answer(refined_response)\n except BaseException:\n await message.answer(\"Конвертация не удалась. Возможно, вы указали строку в неверном формате...\\n\"\n \"Попробуйте снова\")\n\n\n@dp.message_handler(Text(equals=\"Создать опрос\", ignore_case=True))\nasync def send_poll(message: types.Message):\n \"\"\"\n Метод используется, чтобы предложить пользователю создать опрос и привести бота в состояние, когда следующее\n сообщение будет определять тип опроса\n :param message:\n :return:\n \"\"\"\n await UserState.poll_anon.set()\n await message.answer(\"Для отмены операции нажмите на шторку около поля ввода и выберите /cancel\")\n await message.answer(\"Выберите тип опроса\", reply_markup=anon_keyboard)\n\n\n@dp.message_handler(state=UserState.poll_anon)\nasync def process_poll_anon_state(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется, чтобы определить тип опроса и привести бота в состояние, когда следующее сообщение будет\n определять заголовок опроса\n :param message:\n :param state:\n :return:\n \"\"\"\n if message.text.upper() in [\"АНОНИМНЫЙ\", \"ПУБЛИЧНЫЙ\"]:\n is_anonymous = True if message.text.upper() == \"АНОНИМНЫЙ\" else False\n await state.update_data(is_anonymous=is_anonymous)\n await UserState.poll_topic.set()\n await message.answer(\"Выберите заголовок опроса\", reply_markup=ReplyKeyboardRemove())\n else:\n await message.answer(\"Неверно указан тип опроса, попробуйте снова\")\n\n\n@dp.message_handler(state=UserState.poll_topic)\nasync def process_poll_topic_state(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется, чтобы определить заголовок опроса и привести бота в состояние, когда следующее сообщение будет\n определять варианты ответа\n :param message:\n :param state:\n :return:\n \"\"\"\n if message.text:\n await state.update_data(topic=message.text)\n await UserState.poll_options.set()\n await message.answer(\"Укажите варианты ответа: каждый вариант на новой строке\")\n else:\n await message.answer(\"Неправильно указано название опроса, попробуйте снова\")\n\n\n@dp.message_handler(state=UserState.poll_options)\nasync def process_poll_topic_state(message: types.Message, state: FSMContext):\n \"\"\"\n Метод используется, чтобы определить варианты ответа и выдать готовый опрос\n :param message:\n :param state:\n :return:\n \"\"\"\n if len(message.text.split(\"\\n\")) >= 2:\n options = message.text.split(\"\\n\")\n user_data = await state.get_data()\n await message.answer(\"Готово! Теперь вы можете переслать этот опрос!\")\n await message.answer_poll(question=user_data[\"topic\"], options=options, is_anonymous=user_data[\"is_anonymous\"],\n reply_markup=default_keyboard)\n await state.finish()\n await state.reset_data()\n else:\n await message.answer(\"Неправильно указаны варианты ответа, попробуйте снова\")\n\n\nif __name__ == '__main__':\n executor.start_polling(dp, skip_updates=True)\n","repo_name":"KdevK/tg-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":12898,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34253726834","text":"import streamlit as st\nimport page.classification as cla\nimport page.regression as reg\nimport page.clustering as clu\n \n\n\nif __name__==\"__main__\":\n type = st.sidebar.radio(\n \"Choose Machine Learning type\",\n (\"Classification\", \"Regression\", \"Clustering\")\n )\n if type == \"Classification\":\n cla.main_page()\n\n if type == \"Regression\":\n reg.main_page()\n\n if type == \"Clustering\":\n clu.main_page()\n","repo_name":"mochaji27/streamlit","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32674990214","text":"#!/usr/bin/env python3\n\nimport os\nimport platform\nimport subprocess\nimport sys\n\nif len(sys.argv) < 2:\n print(\"no message provided\")\n print(\"usage: run.py [message]\")\n exit(1)\n\nmessage = sys.argv[1]\nmessage_raw = bytes(message, \"UTF-8\")\nlength = len(message_raw)\nlength_raw = length.to_bytes(4, byteorder=sys.byteorder, signed=False)\n\nencoded_message = length_raw + message_raw\n\nprint(f\"message: {message}\")\nprint(f\"encoded message: {encoded_message}\")\n\nexe_name = \"yktotp-jsonapi.exe\" if platform.system() == \"Windows\" else \"yktotp-jsonapi\"\nexe_path = os.path.join(os.path.dirname(sys.argv[0]), \"../target/release/\", exe_name)\nprocess = subprocess.run(os.path.abspath(exe_path),\n text=True,\n input=encoded_message.decode(),\n capture_output=True)\nresponse_raw = bytes(process.stdout, \"UTF-8\")\n\nprint(f\"encoded response: {response_raw}\")\n\nresponse_length = int.from_bytes(response_raw[0:4], byteorder=sys.byteorder, signed=False)\nresponse = response_raw[4:4 + response_length].decode()\n\nprint(f\"response: {response}\")\n","repo_name":"nilsalex/yktotp-jsonapi","sub_path":"utils/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"7446739139","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('products', '0005_auto_20160806_1233'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='product',\n name='poduct_detail',\n field=models.TextField(verbose_name='product name', blank=True),\n ),\n ]\n","repo_name":"mehdi1361/E_Shop","sub_path":"products/migrations/0006_product_poduct_detail.py","file_name":"0006_product_poduct_detail.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10199875949","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nfrom __future__ import unicode_literals\nimport spacy\nimport sys\n\n# Create your models here.\nclass Clustering():\n nlp=None\n def __init__(self, lenguaje, modulo):\n if lenguaje == 'es':\n if modulo == 'md':\n self.nlp = spacy.load(\"es_core_news_md\")\n if modulo == 'sm':\n self.nlp = spacy.load(\"es_core_news_sm\")\n if lenguaje == 'en':\n if modulo == 'md':\n self.nlp = spacy.load(\"en_core_web_md\")\n if modulo == 'sm':\n self.nlp = spacy.load(\"en_core_web_sm\")\n \n def process_text(self, text):\n #newText = text #text.replace(\";\", \" \").replace(\"\\\"\", \"\")\n newText = text.replace(\";\", \" \").replace(\"\\\"\", \"\")\n doc = self.nlp(newText.lower())\n result = []\n for token in doc:\n if token.text in self.nlp.Defaults.stop_words:\n continue\n if token.is_punct:\n continue\n if token.lemma_ == '-PRON-':\n continue\n result.append(token.lemma_)\n # print(token.lemma_)\n return \" \".join(result)\n \n def find_similarity(self, text1, text2):\n # Raw text is processed to remove stopwords and others\n fixedText1 = self.process_text(text1)\n fixedText2 = self.process_text(text2)\n \n #print(\"fixedText1 = \"+fixedText1)\n #print(\"fixedText2 = \"+fixedText2)\n\n # Clean text is tokenized\n doc1 = self.nlp(fixedText1)\n doc2 = self.nlp(fixedText2)\n # Iterate over each word of text2 to compare with word in text1\n for token in doc2:\n doc3 = self.nlp(token.text)\n print(doc1.similarity(doc3))\n\nif __name__ == '__main__':\n clus = Clustering('en', 'md')\n clus.find_similarity(sys.argv[2],sys.argv[3])","repo_name":"borisrperezg/rebel","sub_path":"rebelapi/resources/semanticsimilarity_copy.py","file_name":"semanticsimilarity_copy.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43702427152","text":"# encoding: utf-8\n\"\"\"\n@author: sherlock\n@contact: sherlockliao01@gmail.com\n\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport torch\n\nfrom torch.backends import cudnn\n\nsys.path.append('.')\nfrom config import cfg\nfrom data import make_data_loader\nfrom engine.trainer import do_train, do_train_with_center\nfrom modeling import build_model\nfrom layers import make_loss, make_loss_with_center\nfrom solver import make_optimizer, make_optimizer_with_center, WarmupMultiStepLR\n\nfrom utils.logger import setup_logger\n\n\ndef train(cfg):\n # prepare dataset\n train_loader, val_loader, num_query, num_classes = make_data_loader(cfg)\n\n # prepare model\n model = build_model(cfg, num_classes)\n\n if cfg.MODEL.IF_WITH_CENTER == 'no':\n print('Train without center loss, the loss type is', cfg.MODEL.METRIC_LOSS_TYPE)\n optimizer = make_optimizer(cfg, model)\n # scheduler = WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,\n # cfg.SOLVER.WARMUP_ITERS, cfg.SOLVER.WARMUP_METHOD)\n\n loss_func = make_loss(cfg, num_classes) # modified by gu\n\n # Add for using self trained model\n if cfg.MODEL.PRETRAIN_CHOICE == 'self':\n start_epoch = eval(cfg.MODEL.PRETRAIN_PATH.split('/')[-1].split('.')[0].split('_')[-1])\n print('Start epoch:', start_epoch)\n path_to_optimizer = cfg.MODEL.PRETRAIN_PATH.replace('model', 'optimizer')\n print('Path to the checkpoint of optimizer:', path_to_optimizer)\n model.load_state_dict(torch.load(cfg.MODEL.PRETRAIN_PATH))\n optimizer.load_state_dict(torch.load(path_to_optimizer))\n scheduler = WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,\n cfg.SOLVER.WARMUP_ITERS, cfg.SOLVER.WARMUP_METHOD, start_epoch)\n elif cfg.MODEL.PRETRAIN_CHOICE == 'imagenet':\n start_epoch = 0\n scheduler = WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,\n cfg.SOLVER.WARMUP_ITERS, cfg.SOLVER.WARMUP_METHOD)\n else:\n print('Only support pretrain_choice for imagenet and self, but got {}'.format(cfg.MODEL.PRETRAIN_CHOICE))\n\n arguments = {}\n\n do_train(\n cfg,\n model,\n train_loader,\n val_loader,\n optimizer,\n scheduler, # modify for using self trained model\n loss_func,\n num_query,\n start_epoch # add for using self trained model\n )\n elif cfg.MODEL.IF_WITH_CENTER == 'yes':\n print('Train with center loss, the loss type is', cfg.MODEL.METRIC_LOSS_TYPE)\n loss_func, center_criterion = make_loss_with_center(cfg, num_classes) # modified by gu\n optimizer, optimizer_center = make_optimizer_with_center(cfg, model, center_criterion)\n # scheduler = WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,\n # cfg.SOLVER.WARMUP_ITERS, cfg.SOLVER.WARMUP_METHOD)\n\n arguments = {}\n\n # Add for using self trained model\n if cfg.MODEL.PRETRAIN_CHOICE == 'self':\n start_epoch = eval(cfg.MODEL.PRETRAIN_PATH.split('/')[-1].split('.')[0].split('_')[-1])\n print('Start epoch:', start_epoch)\n path_to_optimizer = cfg.MODEL.PRETRAIN_PATH.replace('model', 'optimizer')\n print('Path to the checkpoint of optimizer:', path_to_optimizer)\n path_to_center_param = cfg.MODEL.PRETRAIN_PATH.replace('model', 'center_param')\n print('Path to the checkpoint of center_param:', path_to_center_param)\n path_to_optimizer_center = cfg.MODEL.PRETRAIN_PATH.replace('model', 'optimizer_center')\n print('Path to the checkpoint of optimizer_center:', path_to_optimizer_center)\n model.load_state_dict(torch.load(cfg.MODEL.PRETRAIN_PATH))\n optimizer.load_state_dict(torch.load(path_to_optimizer))\n center_criterion.load_state_dict(torch.load(path_to_center_param))\n optimizer_center.load_state_dict(torch.load(path_to_optimizer_center))\n scheduler = WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,\n cfg.SOLVER.WARMUP_ITERS, cfg.SOLVER.WARMUP_METHOD, start_epoch)\n elif cfg.MODEL.PRETRAIN_CHOICE == 'imagenet':\n start_epoch = 0\n scheduler = WarmupMultiStepLR(optimizer, cfg.SOLVER.STEPS, cfg.SOLVER.GAMMA, cfg.SOLVER.WARMUP_FACTOR,\n cfg.SOLVER.WARMUP_ITERS, cfg.SOLVER.WARMUP_METHOD)\n else:\n print('Only support pretrain_choice for imagenet and self, but got {}'.format(cfg.MODEL.PRETRAIN_CHOICE))\n\n do_train_with_center(\n cfg,\n model,\n center_criterion,\n train_loader,\n val_loader,\n optimizer,\n optimizer_center,\n scheduler, # modify for using self trained model\n loss_func,\n num_query,\n start_epoch # add for using self trained model\n )\n else:\n print(\"Unsupported value for cfg.MODEL.IF_WITH_CENTER {}, only support yes or no!\\n\".format(cfg.MODEL.IF_WITH_CENTER))\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"ReID Baseline Training\")\n parser.add_argument(\n \"--config_file\", default=\"\", help=\"path to config file\", type=str\n )\n parser.add_argument(\"opts\", help=\"Modify config options using the command-line\", default=None,\n nargs=argparse.REMAINDER)\n\n args = parser.parse_args()\n\n num_gpus = int(os.environ[\"WORLD_SIZE\"]) if \"WORLD_SIZE\" in os.environ else 1\n\n if args.config_file != \"\":\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n output_dir = cfg.OUTPUT_DIR\n if output_dir and not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n logger = setup_logger(\"reid_baseline\", output_dir, 0)\n logger.info(\"Using {} GPUS\".format(num_gpus))\n logger.info(args)\n\n if args.config_file != \"\":\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n with open(args.config_file, 'r') as cf:\n config_str = \"\\n\" + cf.read()\n logger.info(config_str)\n logger.info(\"Running with config:\\n{}\".format(cfg))\n\n if cfg.MODEL.DEVICE == \"cuda\":\n os.environ['CUDA_VISIBLE_DEVICES'] = cfg.MODEL.DEVICE_ID # new add by gu\n cudnn.benchmark = True\n train(cfg)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"michuanhaohao/reid-strong-baseline","sub_path":"tools/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","stars":2151,"dataset":"github-code","pt":"52"} +{"seq_id":"11073343249","text":"class MyType:\n def __init__(self):\n self.__items = []\n self.__cur_index = 0\n\n def add(self, valor):\n self.__items.append(valor)\n\n def __setitem__(self, key, value):\n if not isinstance(key, int):\n raise TypeError\n if key >= len(self.__items):\n self.__items.append(value)\n else:\n self.__items[key] = value\n\n def __getitem__(self, key):\n if not isinstance(key, int):\n raise TypeError\n if key >= len(self.__items):\n raise IndexError\n\n return self.__items[key]\n\n def __delitem__(self, key):\n if not isinstance(key, int):\n raise TypeError\n del self.__items[key]\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.__cur_index < len(self.__items):\n item = self.__items[self.__cur_index]\n self.__cur_index += 1\n return item\n else:\n raise StopIteration\n\n def __str__(self):\n return f\"{__class__.__name__}{self.__items}\"\n\n\nmy_type = MyType()\n\nmy_type.add(12)\nmy_type.add(12)\nmy_type.add(12)\n\n\nfor v in my_type:\n print(v)\n","repo_name":"bruno-avs/curso_python_udemy","sub_path":"revisao/19_implementando_iterador.py","file_name":"19_implementando_iterador.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39200228125","text":"#!/usr/bin/env python\n__author__ = 'shivangi'\n\nimport os\nimport re\nimport requests\n\n\nif hasattr(requests.packages.urllib3, 'disable_warnings'):\n requests.packages.urllib3.disable_warnings()\n\n\ndef store_back_output(path, mode=\"w+\"):\n def outer_decorator(func):\n def inner_decorator(*args, **kwargs):\n _return = func(*args, **kwargs)\n with open(path, mode=mode) as fh:\n fh.write(_return)\n return _return\n return inner_decorator\n return outer_decorator\n\n\nclass Webpage(object):\n \"\"\"\n A specified URL class, which can perform few utility functions for an webpage associated.\n \"\"\"\n\n def __init__(self, url):\n self.url = url\n self._contents = None\n self.response = None\n\n @store_back_output(path=\"zdnet-security\")\n def get_contents(self, **kwargs):\n \"\"\"\n Makes the request to specified URL and get backs the contents.\n :return: HTML contents of the webpage. Throws Expection in case of failure in HTTP response.\n \"\"\"\n try:\n self.response = requests.get(url=self.url, verify=False)\n if self.response.status_code == requests.codes.ALL_OK:\n self._contents = self.response.content.replace(\"><\", \">\\n<\")\n else:\n self._contents = None\n raise requests.HTTPError(\"Got {0} page response\".format(self.response.status_code))\n except Exception as e:\n raise e.__class__(e.message)\n return self._contents\n\n def get_patterns(self, pattern, string=None):\n \"\"\"\n Takes in the Regular Expression Pattern to match with contents from Webpage or string specified.\n :param pattern: Regular expression string.\n :param string: Optional. String to match with RE.\n :return: All the found pattern in list. Throws Expection if not valid contents are found.\n \"\"\"\n pattern = r'{0}'.format(pattern)\n if string is None:\n string = self.get_contents()\n elif not self._contents:\n raise ValueError(\"No valid contents found to parse\")\n find_all = re.findall(pattern=pattern, string=string)\n return find_all\n\n def __repr__(self):\n return \"\".format(self.url)","repo_name":"jain-shivangi/webupdates","sub_path":"webupdates/_private/webpages.py","file_name":"webpages.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4032079865","text":"import numpy as np\nfrom BasicGraph import *\nfrom GraphPropertiesToolBox import *\nfrom GraphNodePairVal import *\n\nclass GraphOfEdgeArray(BasicGraph):\n def __init__(self, nodeNames, edges, directed, size):\n self.nodeNames = nodeNames\n self.edges = edges\n self.directed = directed\n self.size = size\n\n def GraphOfEdgeArray(self, e, direct, numNode):\n self.edges = e\n self.directed = direct\n self.size = numNode\n\n def GraphOfEdgeArray(self, e, direct, numNode, nodeName):\n self.nodeNames = nodeName\n self.edges = e\n self.directed = direct\n self.size = numNode\n\n def getDegreeSeq(self):\n return getInOutDegreeFromEdges(self.size, self.edges)\n\n def getDegreeFreq(self):\n return getJoinInOutFreqFromInOutDegree(getInOutDegreeFromEdges(self.size, self.edges))\n\n def getMotifFreq(self, motifSize):\n gnpv = GraphNodePairVal(self.size, self.directed, self.edges)\n return gnpv.getMotifFreq(motifSize)\n\n def getNodeMotifFreq(self, motifSize):\n res = np.matrix([], [])\n gnpv = GraphNodePairVal(self.size, self.directed, self.edges)\n return gnpv.getNodeMotifFreq(motifSize)\n\n def removeNullNodes(self):\n hm = {}\n newEdges = np.matrix([len(self.edges)], [2])\n for i in range(len(self.edges)):\n for j in range(2):\n if self.edges[i][j] not in hm:\n newEdges[i][j] = np.size(hm)\n hm.put(self.edges[i][j], newEdges[i][j])\n else:\n newEdges[i][j] = hm.get(self.edges[i][j])\n\n return GraphOfEdgeArray(newEdges, self.directed, np.size(hm))\n\n","repo_name":"droney1/Reddit-Machine-Learning-Project","sub_path":"graphs/GraphOfEdgeArray.py","file_name":"GraphOfEdgeArray.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13967151097","text":"# Alerts © 2022\n# Author: Ameen Ahmed\n# Company: Level Up Marketing & Software Development Services\n# Licence: Please refer to LICENSE file\n\n\nfrom .common import error\nfrom .alert import get_alerts_cache\n\n\ndef extend(bootinfo):\n try:\n bootinfo.alerts = get_alerts_cache(frappe.session.user)\n except Exception:\n error(_(\"An error has occurred while getting the cached alerts on boot.\"), False)\n","repo_name":"kid1194/frappe_alerts","sub_path":"alerts/utils/boot.py","file_name":"boot.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"52"} +{"seq_id":"30165965349","text":"from mpi4py import MPI\nfrom mpi4py.futures import MPIPoolExecutor\n\n\ndef task(item):\n return item * 2\n\n\nif __name__ == '__main__':\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n print(f\"Hello, world! from rank {rank} out of {size}\")\n count = 0\n\n result_sum = 0\n\n with MPIPoolExecutor(max_workers=4) as executor:\n\n items = range(1000)\n \n mapped = list(executor.map(task, items))\n\n for result in mapped:\n result_sum += result\n\n print(f'Sum(2*range(1000)) = {result_sum}', count)\n","repo_name":"Nkzono99/visualization-codes-for-EMSES","sub_path":"configuration-test/test-mpi4py-futures.py","file_name":"test-mpi4py-futures.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39632973807","text":"#!/usr/bin/python\n\nimport os\nimport sys\n\nif len(sys.argv) != 2:\n print('Usage: %s [plyfilename]' % sys.argv[0])\n sys.exit(1)\n\npath,fn = os.path.split(sys.argv[1])\nbn,ext = os.path.splitext(fn)\n\nassert ext == '.ply', 'Must specify .ply file'\n\nf = open(sys.argv[1]).read().split('\\n')\nassert f[0] == 'ply', 'Not valid ply'\nassert f[1] == 'format ascii 1.0', 'Not valid ply'\n\niHeader = 2\nhas = []\nwhile iHeader < len(f):\n if f[iHeader].startswith('comment '):\n iHeader += 1\n continue\n if f[iHeader] == 'end_header':\n iHeader += 1\n break\n if f[iHeader].startswith('element vertex '):\n vc = int(f[iHeader].split(' ')[2])\n if f[iHeader].startswith('element face '):\n fc = int(f[iHeader].split(' ')[2])\n if f[iHeader].startswith('property '):\n has += [f[iHeader].split(' ')[-1]]\n iHeader += 1\n\nassert 'x' in has and 'y' in has and 'z' in has, 'Could not find position'\nassert 'nx' in has and 'ny' in has and 'nz' in has, 'Could not find normal'\nassert 'red' in has and 'green' in has and 'blue' in has, 'Could not find color'\nassert 'vertex_indices' in has, 'Could not find indices'\n\nprint('Vertex count: %d\\nFace count: %d' % (vc,fc))\n\npos = []\nnorm = []\ncolor = []\n\nfor iFace in range(fc):\n lf = map(int, f[iHeader + vc + iFace].split(' '))\n if lf[0] == 3:\n vi = lf[1:]\n if lf[0] == 4:\n vi = [lf[1],lf[2],lf[3],lf[1],lf[3],lf[4]]\n for iVert in vi:\n lv = map(float, f[iHeader + iVert].split(' '))\n pos += [lv[0],lv[1],lv[2]]\n norm += [lv[3],lv[4],lv[5]]\n color += [lv[6]/255.0,lv[7]/255.0,lv[8]/255.0,1.0]\n\nassert len(pos)/3 == len(norm)/3\nassert len(pos)/3 == len(color)/4\nprint('Count: %d' % (len(pos)/3))\n\npos = map(str,pos)\nnorm = map(str,norm)\ncolor = map(str,color)\n\ndef write(f, arrayname, data, size):\n while data:\n size = min(size, len(data))\n dataset,data = data[:size],data[size:]\n f.write('%s.push(%s);\\n' % (arrayname,','.join(dataset)))\n\n\nf = open(os.path.join(path, '%s.js'%bn),'wt')\nf.write('function generate_%s() {\\n' % bn)\nf.write(' var data = {pos:[],norm:[],color:[],length:0};\\n');\nwrite(f,' data.pos', pos, 200*3)\nwrite(f,' data.norm', norm, 200*3)\nwrite(f,' data.color', color, 200*4)\nf.write(' data.length = %d;\\n' % (len(pos)/3));\nf.write(' return dataToObject(data);\\n');\nf.write('}\\n');","repo_name":"joshbontrager/P04_Final_Source","sub_path":"ply2js.py","file_name":"ply2js.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74783359205","text":"#==========================intersection method============================\r\n# to find roots between a and b\r\nimport math\r\ndef intersection(func,a,b):\r\n while 1:\r\n c=b-((func(b)*(b-a)))/(func(b)-func(a))\r\n if abs(c-b) < 10**-5:\r\n return c\r\n a=b\r\n b=c\r\n#=========================================================\r\ndef f(x):\r\n return math.pow(x,3)-2*x-5\r\nprint('input ur limits with space')\r\ns=[float(i) for i in input().split()]\r\nif(len(s)==2):\r\n print(intersection(f,s[0],s[1]))\r\nelse:\r\n print('invalid input')\r\n","repo_name":"gurnish-singh/algorithms-for-python","sub_path":"numerical analysis/intersection method.py","file_name":"intersection method.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34158866756","text":"import os, shutil\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\nimport argparse\nimport rapidjson\nimport fnmatch\nfrom pycocotools.coco import COCO\nfrom pycocotools.cocoeval import COCOeval\nimport math\n\ndef reverse_coco_category(category_id):\n '''\n convert continuous coco class id (0~79) to discontinuous coco category id\n '''\n if category_id >= 0+1 and category_id <= 10+1:\n category_id = category_id - 1\n elif category_id >= 11+2 and category_id <= 23+2:\n category_id = category_id - 2\n elif category_id >= 24+3 and category_id <= 25+3:\n category_id = category_id - 3\n elif category_id >= 26+5 and category_id <= 39+5:\n category_id = category_id - 5\n elif category_id >= 40+6 and category_id <= 59+6:\n category_id = category_id - 6\n elif category_id == 60+7:\n category_id = category_id - 7\n elif category_id == 61+9:\n category_id = category_id - 9\n elif category_id >= 62+10 and category_id <= 72+10:\n category_id = category_id - 10\n elif category_id >= 73+11 and category_id <= 79+11:\n category_id = category_id - 11\n else:\n raise ValueError('Invalid category id')\n return category_id\n\ndef find(pattern, path):\n result = ''\n for root, dirs, files in os.walk(path):\n for name in files:\n if fnmatch.fnmatch(name, pattern):\n result = os.path.join(name)\n return result\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--annotations', type=str, default='/data2/datasets/coco/coco2017/annotations/instances_val2017.json',\n required=False, help='path to the validation annotations')\n parser.add_argument('--images', type=str, default='/data2/datasets/coco/coco2017/images/val2017/',\n required=False, help='path to the validation annotations') \n parser.add_argument('--labels', type=str, default='/data2/datasets/coco/coco2017/labels/val2017/',\n required=False, help='path to the validation annotations') \n FLAGS = parser.parse_args()\n cnt = 0\n \n try:\n # Create target Directory\n os.mkdir(FLAGS.labels)\n print(\"Directory \" , FLAGS.labels , \" Created \") \n except FileExistsError:\n print(\"Directory \" , FLAGS.labels , \" already exists, cleaning...\")\n shutil.rmtree(FLAGS.labels)\n os.mkdir(FLAGS.labels)\n\n with open(FLAGS.annotations) as json_file:\n data = rapidjson.load(json_file)\n for i in data['annotations']:\n cnt=cnt+1\n print(cnt)\n bbox=i['bbox']\n category_id=str(reverse_coco_category(i['category_id']))\n left, top, width, height = bbox\n center_x = left + width / 2.0\n center_y = top + height / 2.0\n #find the image in the images directory and read it in to get the height and width\n image_id=str(i['image_id'])\n image_id = image_id.rjust(12, '0')\n image_file_name =image_id+'.jpg'\n filename = os.path.splitext(image_file_name)[0] #remove the extension to get just the filename\n image = cv2.imread((FLAGS.images + image_file_name),cv2.IMREAD_COLOR)\n image_h, image_w, _ = image.shape\n yolo_x = center_x / image_w\n yolo_y = center_y / image_h\n yolo_w = width / image_w\n yolo_h = height / image_h\n yolo_box = str(yolo_x) + ' ' + str(yolo_y) + ' ' + str(yolo_w) + ' ' + str(yolo_h)\n write_line = category_id + ' ' + yolo_box + '\\n'\n f=open(FLAGS.labels + filename + \".txt\", \"a+\")\n f.write(write_line)\n f.close()\n print(\"done\")\n ","repo_name":"Xilinx/Vitis-In-Depth-Tutorial","sub_path":"Machine_Learning/Design_Tutorials/07-yolov4-tutorial/scripts/gen_coco_annotations.py","file_name":"gen_coco_annotations.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"52"} +{"seq_id":"73537127844","text":"import unittest\n\nimport numpy as np\nimport torch\nimport torchaudio\nfrom encodec import EncodecModel\nfrom torch.utils.data import DataLoader\n\nfrom oscillate.data.load.dataset import TTADataset\nfrom oscillate.data.prepare.encoders.text.bpemb_encoder import BpembEncoder\nfrom oscillate.model.model.decoder import Decoder\nfrom oscillate.model.model.encoder import Encoder\nfrom oscillate.model.model.model import TTAModel\n\n\nclass TTAModelTest(unittest.TestCase):\n\n\tdef test_functionality(self):\n\t\tBLOCK_SIZE = 512\n\t\tENCODER_EMB_SIZE = 6\n\t\tDECODER_EMB_SIZE = 16\n\t\tDECODER_INPUT_EMB_SIZE = 8\n\t\tMHA_HEADS = 2\n\t\tBATCH_SIZE = 16\n\t\tDECODER_VOCAB_SIZE = 1024\n\n\t\tmodel = TTAModel(\n\t\t\tencoder=Encoder(\n\t\t\t\tblock_size=BLOCK_SIZE,\n\t\t\t\temb_size=ENCODER_EMB_SIZE,\n\t\t\t\tff_size=256,\n\t\t\t\tmha_heads=MHA_HEADS\n\t\t\t),\n\t\t\tdecoder=Decoder(\n\t\t\t\temb_size=DECODER_EMB_SIZE,\n\t\t\t\tinput_emb_size=DECODER_INPUT_EMB_SIZE,\n\t\t\t\tblock_size=BLOCK_SIZE,\n\t\t\t\tnum_heads=MHA_HEADS,\n\t\t\t\tff_size=256\n\t\t\t),\n\t\t\tdecoder_vocab_size=DECODER_VOCAB_SIZE\n\t\t)\n\n\t\tX_encoder = torch.rand((BATCH_SIZE, BLOCK_SIZE, ENCODER_EMB_SIZE))\n\t\tX_decoder = torch.randint(0, 1024, (BATCH_SIZE, BLOCK_SIZE, DECODER_INPUT_EMB_SIZE))\n\n\t\ty = model(X_encoder, X_decoder)\n\n\t\tself.assertEqual(y.shape, (X_decoder.shape[0], DECODER_INPUT_EMB_SIZE, DECODER_VOCAB_SIZE))\n\n\tdef test_load_and_run(self):\n\t\tdef get_X_enc(text):\n\t\t\tX = text_encoder.encode(\"Hello. How are you?\")\n\t\t\tX = np.pad(X, pad_width=((0, 512 - X.shape[0]), (0, 0)), mode=\"constant\", constant_values=0)\n\t\t\treturn torch.from_numpy(X).unsqueeze(0)\n\n\t\tENCODEC_BANDWIDTH = 3\n\t\tENCODEC_EOS_TOKEN = 0\n\t\tBPEMB_LANG = \"en\"\n\t\tBPEMB_EMB_SIZE = 50\n\t\tBLOCK_SIZE = 512\n\t\tENCODER_EMB_SIZE = 50\n\t\tDECODER_INPUT_EMB_SIZE = 4\n\t\tDECODER_EMB_SIZE = 256\n\t\tENCODER_HEADS = 50\n\t\tDECODER_HEADS = 128\n\t\tFF_SIZE = 1024\n\t\tDECODER_VOCAB_SIZE = 1024\n\n\t\tDTYPE = torch.float32\n\t\tNP_DTYPE = np.float32\n\n\t\ttext_encoder = BpembEncoder(lang=BPEMB_LANG, emb_size=BPEMB_EMB_SIZE)\n\t\tencodec_model = EncodecModel.encodec_model_24khz()\n\t\tencodec_model.set_target_bandwidth(ENCODEC_BANDWIDTH)\n\n\t\tX_enc = get_X_enc(\"The quick brown fox jumps over the lazy dog\")\n\t\tX_dec = torch.zeros((1, 512, DECODER_INPUT_EMB_SIZE))\n\n\t\tmodel = TTAModel(\n\t\t\tencoder=Encoder(\n\t\t\t\tblock_size=BLOCK_SIZE,\n\t\t\t\temb_size=ENCODER_EMB_SIZE,\n\t\t\t\tff_size=FF_SIZE,\n\t\t\t\tmha_heads=ENCODER_HEADS,\n\t\t\t\tdtype=DTYPE\n\t\t\t),\n\t\t\tdecoder=Decoder(\n\t\t\t\temb_size=DECODER_EMB_SIZE,\n\t\t\t\tinput_emb_size=DECODER_INPUT_EMB_SIZE,\n\t\t\t\tblock_size=BLOCK_SIZE,\n\t\t\t\tnum_heads=DECODER_HEADS,\n\t\t\t\tff_size=FF_SIZE,\n\t\t\t\tdtype=DTYPE,\n\t\t\t\tvocab_size=DECODER_VOCAB_SIZE\n\t\t\t),\n\t\t\tdtype=DTYPE,\n\t\t\tdecoder_vocab_size=DECODER_VOCAB_SIZE\n\t\t)\n\t\tmodel.load_state_dict(torch.load('/home/abreham/Projects/TeamProjects/Oscillate/temp/models/model.pth', map_location=torch.device('cpu')))\n\t\tmodel.eval()\n\t\tout = torch.zeros_like(X_dec)[0]\n\n\t\twith torch.no_grad():\n\t\t\tfor i in range(64):\n\t\t\t\ty = model(X_enc, X_dec)\n\t\t\t\tout[i] = torch.argmax(y, dim=-1)[0, -1]\n\t\t\t\tX_dec[0, 512-(i+1):] = out[:i+1]\n\t\t\t\t# out = torch.argmax(y, dim=-1)[0]\n\t\t\t\t# X_dec[0] = out\n\n\t\tX_np = out.detach().numpy()\n\t\tX_np = X_np[np.any(X_np != 0, axis=1)]\n\n\t\taudio_codes = [\n\t\t\t(\n\t\t\t\ttorch.from_numpy(\n\t\t\t\t\tnp.round(\n\t\t\t\t\t\tnp.transpose(\n\t\t\t\t\t\t\tX_np\n\t\t\t\t\t\t)\n\t\t\t\t\t).astype(int),\n\t\t\t\t).unsqueeze(0),\n\t\t\t\tNone\n\t\t\t)\n\t\t]\n\t\twith torch.no_grad():\n\t\t\taudio_values = encodec_model.decode(audio_codes)[0]\n\t\ttorchaudio.save(\"/home/abreham/Projects/TeamProjects/Oscillate/temp/Data/test.wav\", audio_values, encodec_model.sample_rate)\n","repo_name":"abreham-atlaw/oscillate","sub_path":"test/model/model/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11443740198","text":"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom . import views\nurlpatterns = [\n path('', views.home, name = 'home'),\n path('heart/', views.heart, name = 'heart'),\n path('kidney/', views.kidney, name = 'kidney'),\n path('diabetes/',views.diabetes, name = 'diabetes'),\n path('liver/',views.liver, name = 'liver'),\n path('heart/hpredict', views.hdpredictor, name = 'hpredict'),\n path('kidney/kpredict', views.kdpredictor, name = 'kpredict'),\n path('diabetes/dbpredict', views.dbpredictor, name = 'diabetes_pred'),\n path('liver/lpredict', views.lpredictor, name = 'lpredict'),\n]\n","repo_name":"itzzmesid/VirtuDoc","sub_path":"backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"29133946671","text":"\"\"\"A module for the Cube class.\"\"\"\n\nfrom math import factorial, comb\nfrom random import choice\nfrom typing import List, Tuple\n\nfrom src.puzzle.cube_face import CubeFace\n\n\nclass Cube:\n \"\"\"A class to store and manipulate a normal 3x3x3 Rubik's cube.\"\"\"\n\n # Neighbors, the affected line number, and -1 if the line should be\n # flipped for every possible turn.\n __turns = (((1, 0, 1), (2, 0, 1), (3, 0, 1), (4, 0, 1)),\n ((0, 3, 1), (4, 5, -1), (5, 3, 1), (2, 3, 1)),\n ((0, 2, -1), (1, 5, 1), (5, 0, 1), (3, 3, -1)),\n ((0, 5, 1), (2, 5, 1), (5, 5, 1), (4, 3, -1)),\n ((0, 0, -1), (3, 5, -1), (5, 2, 1), (1, 3, 1)),\n ((4, 2, 1), (3, 2, 1), (2, 2, 1), (1, 2, 1)))\n\n corner_order = [\"URF\", \"UFL\", \"ULB\", \"UBR\", \"DFR\", \"DLF\", \"DBL\", \"DRB\"]\n edge_order = [\"UR\", \"UF\", \"UL\", \"UB\", \"DR\", \"DF\",\n \"DL\", \"DB\", \"FR\", \"FL\", \"BL\", \"BR\"]\n\n move_pairs = {\"U\": \"D\", \"L\": \"R\", \"F\": \"B\", \"D\": \"U\", \"R\": \"L\", \"B\": \"F\"}\n\n corner_coords = { # (face, facelet)\n \"URF\": ((0, 8), (3, 0), (2, 2)),\n \"UFL\": ((0, 6), (2, 0), (1, 2)),\n \"ULB\": ((0, 0), (1, 0), (4, 2)),\n \"UBR\": ((0, 2), (4, 0), (3, 2)),\n \"DFR\": ((5, 2), (2, 8), (3, 6)),\n \"DLF\": ((5, 0), (1, 8), (2, 6)),\n \"DBL\": ((5, 6), (4, 8), (1, 6)),\n \"DRB\": ((5, 8), (3, 8), (4, 6))\n }\n\n edge_coords = {\n \"UR\": ((0, 5), (3, 1)),\n \"UF\": ((0, 7), (2, 1)),\n \"UL\": ((0, 3), (1, 1)),\n \"UB\": ((0, 1), (4, 1)),\n \"DR\": ((5, 5), (3, 7)),\n \"DF\": ((5, 1), (2, 7)),\n \"DL\": ((5, 3), (1, 7)),\n \"DB\": ((5, 7), (4, 7)),\n \"FR\": ((2, 5), (3, 3)),\n \"FL\": ((2, 3), (1, 5)),\n \"BL\": ((4, 5), (1, 3)),\n \"BR\": ((4, 3), (3, 5))\n }\n\n moves = [\n move + modifier\n for move in [\"U\", \"L\", \"F\", \"R\", \"B\", \"D\"]\n for modifier in [\"\", \"'\", \"2\"]\n ]\n\n def __init__(self):\n self.__faces = [CubeFace(i) for i in range(6)]\n\n def twist(self, face_number: int, clockwise: bool = True) -> None:\n \"\"\"A method to twist a single layer of the cube 90 degress clockwise or\n anticlockwise.\"\"\"\n self.__faces[face_number].rotate(clockwise)\n\n lines = []\n direction = 1 if clockwise else -1\n for i in range(4):\n face, line, flip = self.__turns[face_number][(i + direction) % 4]\n lines.append(self.__faces[face].get_line(line)[::flip])\n for i in range(4):\n face, line, flip = self.__turns[face_number][i]\n self.__faces[face].set_line(line, lines[i][::flip])\n\n def twist_by_notation(self, notation: str) -> None:\n \"\"\"A method to twist the cube one or multiple times based on a simple\n cube notation.\n\n Only supports the notation listed in the moves property of this class.\n This means that notations like 'X', 'Y', and 'Z' are not allowed.\"\"\"\n face = (\"U\", \"L\", \"F\", \"R\", \"B\", \"D\")\n if len(notation) < 1:\n return\n for move in notation.strip().split(\" \"):\n if len(move) == 1:\n self.twist(face.index(move))\n else:\n if move[1] == \"2\":\n self.twist(face.index(move[0]))\n self.twist(face.index(move[0]))\n else:\n self.twist(face.index(move[0]), False)\n\n def scramble(self, count: int = 20) -> str:\n \"\"\"A function to scramble the cube to any possible orientation.\"\"\"\n moves = [choice(self.moves) for _ in range(count)]\n notation = \" \".join(moves)\n self.twist_by_notation(notation)\n return notation\n\n def scramble_g1(self, count: int = 18) -> None:\n \"\"\"A function to scramble the cube to any possible orientation allowed\n by the turns possible on a Domino Cube (2x3x3).\"\"\"\n notes = [\"U\", \"U'\", \"U2\", \"D\", \"D'\", \"D2\", \"L2\", \"R2\", \"F2\", \"B2\"]\n moves = [choice(notes) for _ in range(count)]\n notation = \" \".join(moves)\n self.twist_by_notation(notation)\n return notation\n\n def reset(self) -> None:\n \"\"\"A function to reset the state of the cube. Kind of like just peeling\n and reapplying the stickers except a lot faster...\"\"\"\n self.__init__()\n\n def __str__(self) -> str:\n colors = ('W', 'R', 'B', 'O', 'G', 'Y')\n string = \"\"\n\n for row in self.__faces[0].facelets:\n string += f\"\\n {''.join([colors[color] for color in row])}\"\n\n for row_number in range(3):\n string += \"\\n\"\n for face_number in range(1, 5):\n row = self.__faces[face_number].facelets[row_number]\n string += ''.join([colors[color] for color in row])\n\n for row in self.__faces[5].facelets:\n string += f\"\\n {''.join([colors[color] for color in row])}\"\n\n return string[1:]\n\n @property\n def cube_string(self) -> str:\n \"\"\"A property to get the cube string representation of the cube.\n\n For example \"UUUUUUUUULLLLLLLLLFFFFFFFFFRRRRRRRRRBBBBBBBBBDDDDDDDDD\"\n for a solved cube or\n \"UDUDUDUDULRLRLRLRLFBFBFBFBFRLRLRLRLRBFBFBFBFBDUDUDUDUD\" for a\n checkerboard pattern.\"\"\"\n return \"\".join([face.cube_string for face in self.__faces])\n\n @property\n def corners(self) -> List[str]:\n \"\"\"List of all of the corners of the cube ordered by the position in\n order of the corner_order property of this class and oriented to be\n easier to recognize.\"\"\"\n corners = self.unoriented_corners\n for i, corner in enumerate(corners):\n if corner not in self.corner_coords:\n corners[i] = self.__fix_corner_name(corner)\n\n return corners\n\n @property\n def unoriented_corners(self) -> List[str]:\n \"\"\"List of all of the corners of the cube ordered by the position in\n order of the corner_order property of this class.\"\"\"\n corners = [\"\"]*8\n for i, corner in enumerate(self.corner_order):\n for face, facelet in self.corner_coords[corner]:\n corners[i] += self.__faces[face].get_facelet(facelet)\n\n return corners\n\n @property\n def edges(self) -> List[str]:\n \"\"\"List of all the edges of the cube ordered by the position in order\n of the edge_order property of this class.\"\"\"\n edges = self.unoriented_edges\n for i, edge in enumerate(edges):\n if edge not in self.edge_order:\n edges[i] = edge[::-1]\n return edges\n\n @property\n def unoriented_edges(self) -> List[str]:\n \"\"\"List of the edges of the cube in order without the name correction.\n\n This is used to calculate the edge orientation indexes.\"\"\"\n edges = [\"\"]*12\n for i, edge in enumerate(self.edge_order):\n for face, facelet in self.edge_coords[edge]:\n edges[i] += self.__faces[face].get_facelet(facelet)\n return edges\n\n @property\n def is_solved(self) -> bool: # Group G_2 {1}\n \"\"\"A property to check if the cube is a valid solved cube or not.\"\"\"\n for face in self.__faces:\n if not face.is_solved:\n return False\n return True\n\n @property\n def is_domino(self) -> bool: # Group G_1 \n \"\"\"A property to check if the cube can be solved with only moves\n possible on a Domino Cube. Assuming that the cube is valid at all.\"\"\"\n return self.__faces[0].is_domino and self.__faces[5].is_domino\n\n # Coordinates for Kociemba's phase 1\n @property\n def triple(self) -> Tuple[int, int, int]:\n \"\"\"A coordinate triple which is (0, 0, 0) if and only if the cube is\n solvable with the moves allowed on a Domino Cube and there has only\n been valid moves been made.\"\"\"\n corner_orientation = self.coordinate_corner_orientation\n edge_orientation = self.coordinate_edge_orientation\n ud_slice = self.coordinate_ud_slice\n\n return (corner_orientation, edge_orientation, ud_slice)\n\n @property\n def coordinate_corner_orientation(self) -> int:\n \"\"\"Corner orientation index coordinate for the phase 1 of Kociemba's\n algorithm.\n\n The value is always in range from 0 to 2186.\"\"\"\n coordinate, corners = 0, [\"\"]*8\n for i, corner in enumerate(self.corner_order[:-1]):\n for face, facelet in self.corner_coords[corner]:\n corners[i] += self.__faces[face].get_facelet(facelet)\n if corners[i] not in self.corner_coords:\n correct = self.__fix_corner_name(corners[i])\n if corners[i][0] == correct[2]:\n coordinate += 3**(6-i)\n elif corners[i][0] == correct[1]:\n coordinate += 2*3**(6-i)\n\n return coordinate\n\n @property\n def coordinate_edge_orientation(self) -> int:\n \"\"\"Edge orientation index coordinate for the phase 1 of Kociemba's\n algorithm.\n\n The value is always in range from 0 to 2047.\"\"\"\n edges, coordinate = [\"\"]*12, 0\n for i, edge in enumerate(self.edge_order):\n for face, facelet in self.edge_coords[edge]:\n edges[i] += self.__faces[face].get_facelet(facelet)\n if edges[i] not in self.edge_order:\n coordinate += i\n\n return coordinate\n\n @property\n def coordinate_ud_slice(self) -> int:\n \"\"\"UD Slice index coordinate for the phase 1 of Kociemba's algorithm.\n\n The value in always in range from 0 to 494.\"\"\"\n edges, k, coordinate = self.edges, 3, 0\n\n for i in reversed(range(12)):\n if edges[i] in self.edge_order[8:]:\n k -= 1\n else:\n coordinate += comb(i, k)\n if k < 0:\n break\n\n return coordinate\n\n # Coordinates for Kociemba's phase 2\n @property\n def triple2(self) -> Tuple[int, int, int]:\n \"\"\"A coordinate triple which is (0, 0, 0) if and only if the cube is\n solved.\"\"\"\n corner_permutation = self.coordinate_corner_permutation\n edge_permutation = self.coordinate_edge_permutation\n ud_slice_phase2 = self.coordinate_ud_slice_phase2\n\n return (corner_permutation, edge_permutation, ud_slice_phase2)\n\n @property\n def coordinate_corner_permutation(self) -> int:\n \"\"\"Corner permutation index coordinate for the phase 2 of Kociemba's\n algorithm.\n\n The value is always in range from 0 to 40319.\"\"\"\n coordinate, corners = 0, self.corners\n\n for i, corner in enumerate(corners[1:]):\n order, i = 0, i+1\n for other_corner in corners[:i]:\n index = self.corner_order.index(corner)+1\n if other_corner in self.corner_order[index:]:\n order += 1\n coordinate += order * factorial(i)\n\n return coordinate\n\n @property\n def coordinate_edge_permutation(self) -> int:\n \"\"\"Edge permutation index coordinate for the phase 2 of Kociemba's\n algorithm.\n\n The value is always in range from 0 to 40319.\"\"\"\n return self.__phase2_edge_coordinate(self.edges[:8])\n\n @property\n def coordinate_ud_slice_phase2(self) -> int: # 0..23\n \"\"\"UD Slice index coordinate for the phase 2 of Kociemba's algorithm.\n\n The value in always in range from 0 to 23.\"\"\"\n return self.__phase2_edge_coordinate(self.edges[8:])\n\n def __phase2_edge_coordinate(self, edges) -> int:\n coordinate = 0\n\n for i, edge in enumerate(edges[1:]):\n order, i = 0, i+1\n for other_edge in edges[:i]:\n index = self.edge_order.index(edge)+1\n if other_edge in self.edge_order[index:]:\n order += 1\n coordinate += order * factorial(i)\n\n return coordinate\n\n @classmethod\n def __fix_corner_name(cls, corner: str) -> str:\n for name in cls.corner_order:\n if sum([1 for char in corner if char in name]) == 3:\n return name\n return \"\"\n\n @classmethod\n def skip_move(cls, notes: List[str], move) -> bool:\n \"\"\"A function the check if the current move should be skipped based on\n previous moves to prevent searching through the same orientations\n multiple times.\"\"\"\n if len(notes) > 0:\n # Don't turn the same side twice in a row. E.g. don't allow F F\n if move[0] == notes[-1][0]:\n return True\n # Don't test for example both R L and L R\n if move[0] in list(cls.move_pairs)[:3]:\n if notes[-1][0] == cls.move_pairs[move[0]]:\n return True\n # Don't turn the same side if the side has not changed at all\n if len(notes) > 1:\n if move[0] == cls.move_pairs[notes[-1][0]] == notes[-2][0]:\n return True\n\n return False\n","repo_name":"Valokoodari/cube-solver","sub_path":"src/puzzle/cube.py","file_name":"cube.py","file_ext":"py","file_size_in_byte":12973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35206901603","text":"import pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\ndf = pd.read_csv(\"heart.csv\")\r\n# print(df.head())\r\n# print(df.isnull().sum())\r\n\r\nX = df.drop(\"target\", axis=1)\r\nY = df[\"target\"]\r\n\r\nXtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.2, random_state=40)\r\nsc = StandardScaler()\r\nXtrain = sc.fit_transform(Xtrain)\r\nXtest = sc.fit_transform(Xtest)\r\nmodel = LogisticRegression()\r\nmodel.fit(Xtrain, Ytrain)\r\nprint(model.score(Xtest, Ytest) * 100)\r\n","repo_name":"Aditya4670/Heart-Attack-Predictor","sub_path":"heart.py","file_name":"heart.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39131466174","text":"#!/usr/bin/env python3\n\n__day__ = 3\n\n__year__ = 2022\n\n__motd__ = '--- Year %s -- Day %s ---' % (__year__, __day__)\n\n__url__ = 'http://adventofcode.com/%s/day/%s' % (__year__, __day__)\n\nverbose = 0\n\n\nclass Rucksack:\n\n def __init__(self):\n pass\n\n def common_item(self, rucksack):\n \"\"\" find common item in both rucksack compartments \"\"\"\n half = int(len(rucksack)/2)\n compartment_a, compartment_b = rucksack[:half], rucksack[-half:]\n common = [ item for item in compartment_a if compartment_b.count(item) > 0 ]\n return ''.join(set(common))\n\n def chr_priority(self, c):\n \"\"\" calc item/character priority a-z -> 1-26 A-Z -> 27-52 \"\"\"\n if 'a' <= c <= 'z': return ord(c) - ord('a') + 1\n if 'A' <= c <= 'Z': return ord(c) - ord('A') + 27\n\n def group_label(self, group):\n \"\"\" group label is common in all rucksacks in the group \"\"\"\n label = None\n for g in group:\n label = set(g) if label is None else label.intersection(g)\n return list(label)[0]\n\n def task_a(self, input: list):\n \"\"\" task A \"\"\"\n common_items = [ self.common_item(rucksack) for rucksack in input ]\n common_items_priority = [ self.chr_priority(c) for c in common_items ]\n return sum(common_items_priority)\n\n def task_b(self, input: list):\n \"\"\" task B \"\"\"\n labels, group = [], []\n for rucksack in input:\n group.append(rucksack)\n if len(group) >= 3:\n label, group = self.group_label(group), []\n labels.append(label)\n labels_priority = [ self.chr_priority(l) for l in labels ]\n return sum(labels_priority)\n\n\ndef testcase_a(sut, input, result):\n \"\"\" testcase verifies if input returns result \"\"\"\n # read default input file\n if input is None:\n data = __file__.replace('.py', '.input')\n with open(data) as f:\n input = [ line.strip() for line in f ]\n #\n print(\"TestCase A using input:\", data if 'data' in vars() else input)\n # read multiline string as input\n if input.count('\\n') > 2:\n input = [ line.strip() for line in input.splitlines() ]\n # optional delete the first empty line\n if len(input[0]) == 0:\n input = input[1:]\n #\n print(\"\\t expected result:\", result)\n r = sut.task_a(input)\n print('\\t got:',r,'\\t','[ OK ]' if r == result else '[ ERR ]')\n print()\n\ndef testcase_b(sut, input, result):\n \"\"\" testcase verifies if input returns result \"\"\"\n # read default input file\n if input is None:\n data = __file__.replace('.py', '.input')\n with open(data) as f:\n input = [ line.strip() for line in f ]\n #\n print(\"TestCase B using input:\", data if 'data' in vars() else input)\n # read multiline string as input\n if input.count('\\n') > 2:\n input = [ line.strip() for line in input.splitlines() ]\n # optional delete the first empty line\n if len(input[0]) == 0:\n input = input[1:]\n #\n print(\"\\t expected result:\", result)\n r = sut.task_b(input)\n print('\\t got:',r,'\\t','[ OK ]' if r == result else '[ ERR ]')\n print()\n\n\n# ======\n# MAIN\n# ======\n\nprint()\nprint(__motd__, __url__)\nprint()\n\ntestdata = \"\"\"\nvJrwpWtwJgWrhcsFMMfFFhFp\njqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL\nPmmdzqPrVvPwwTWBwg\nwMqvLMZHhHMvwLHjbvcjnnSBnvTQFn\nttgJtRGJQctTZtZT\nCrZsJsPPZsGzwwsLwLmpwMDw\n\"\"\"\n\n# ========\n# Task A\n# ========\n\n# test cases\ntestcase_a(Rucksack(), testdata, 157)\n\n# 8252\ntestcase_a(Rucksack(), None, 8252)\n\n# ========\n# Task B\n# ========\n\n# test cases\ntestcase_b(Rucksack(), testdata, 70)\n\n# 2828\ntestcase_b(Rucksack(), None, 2828)\n","repo_name":"blue-sky-r/Advent-Of-Code","sub_path":"2022/03/u03.py","file_name":"u03.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29119520374","text":"#introduction to project\r\nprint(\"The Project undertaking at the six weeks python program at Igbogbo center\\\r\n Ikorodu lagos Nigeria\\nkudos and a big thank you to the facilitator, Mr Ben and the entire crew\\\r\n of the program\")\r\nprint(\"The Project is on Calculation of LOCAL TIME\")\r\n\r\n\r\nprint(\"kindly press A or B\")\r\ndisplay=str(input(\"A To calculate Distance in latitude on same longitude\\nB To calculate local time of places\\nResponse: \"))\r\nprint(display)\r\n\r\nn=\"north\"\r\ns=\"south\"\r\ne=\"east\"\r\nw=\"west\"\r\nd=\"degree\"\r\nx=111\r\nkm=\"kilo meters\"\r\na=4\r\nb=60\r\nc=1\r\nk=15\r\no=\"Greenwich meridien\"\r\nh=\"hours\"\r\ndef time():\r\n time=input(\"enter a time in the hh:mm format\")\r\n timeArray=time.split(\":\")\r\n hours=int(timeArray[0])\r\n minutes=int(timeArray[1])\r\n ampm=\"\"\r\n if hours==12:\r\n ampm=\"pm\"\r\n elif hours==0:\r\n ampm=\"am\"\r\n hours=12\r\n elif hours>=12:\r\n ampm=\"pm\"\r\n hours=hours-12\r\n else:\r\n ampm=\"am\"\r\n \r\n print(str(hours)+\":\"+str(minutes)+\"\"+ampm)\r\n\r\n\r\nt=time()\r\n\r\nif display.upper()==\"A\":\r\n print(\"\\t This is the Platform for the calculations of distance in latitude on same longitude:\\n \")\r\n \r\n print(\"To calculate latitude distance where both are north of the equator\")\r\n latitude1=int(input(\"Enter the first degree in latitude?: \"))\r\n latitude1_degree=str(input(\" north\\n south\\n east\\n west\\n response: \"))\r\n latitude1_location=input(\"enter the location of latitude1: \")\r\n latitude2=int(input(\"Enter the second degree in latitude?: \",))\r\n latitude2_degree=str(input(\" north\\n south\\n east\\n west\\n response: \"))\r\n latitude2_location=input(\"enter the location of latitude2: \")\r\n longitude1=int(input(\"Enter the degree inlongitude?: \"))\r\n print(\"The inputed latitude of location one is: \",latitude1,d, \\\r\n latitude1_degree, \"in\" ,latitude1_location)\r\n print(\"The inputed latitude of location one is: \", latitude2,d, \\\r\n latitude2_degree,\"in\",latitude2_location)\r\n print(\"The inputed longitude is: \",longitude1,d)\r\n latitude=input(\"1 for latitude where both locations are north\\n2 \\\r\nlatitude where both locations\\\r\n \\nare south\\n3 latitude on both north and south of the equator\\nresponse\")\r\n\r\n if latitude==\"1\":\r\n print(\"both locations are: \", n)\r\n if latitude1>latitude2:\r\n largest1=latitude1\r\n output1=largest1-latitude2\r\n output2=output1*x\r\n print(\"distance between the 2 latitudes is: \", output2,km)\r\n\r\n elif latitude2>latitude1:\r\n \r\n largest2=latitude2\r\n output1=largest2-latitude1\r\n output2=output1*x\r\n print(\"distance between the 2 latitudes is: \", output2,km)\r\n\r\n else:\r\n print()\r\n if latitude==\"2\":\r\n print(\"both locations are: \", s)\r\n if latitude1>latitude2:\r\n largest1=latitude1\r\n output1=largest1-latitude2\r\n output2=output1*x\r\n print(\"distance between the 2 latitudes is: \", output2,km)\r\n \r\n elif latitude2>latitude1:\r\n largest1=latitude2\r\n output1=largest1-latitude1\r\n output2=output1*x\r\n print(\"distance between the 2 latitudes is: \", output2,km)\r\n\r\n\r\n if latitude==\"3\":\r\n print(\"To calculate latitude distance where both are north\\\r\nand south of the equator\")\r\n print(\"different Hemishere\")\r\n \r\n output1=latitude1+latitude2\r\n print(output1)\r\n output2=output1*x\r\n print(\"distance between the 2 latitudes is: \", output2,km)\r\n\r\n \r\n else:\r\n print()\r\n \r\n\r\nelif display.upper()==\"B\":\r\n print(\"\\t This is the Platform is to calculate local time of \\\r\nplaces world wide:\\n \")\r\n longitude1=int(input(\"Enter the first degree in longitude?: \"))\r\n longitude1_degree=str(input(\" north\\n south\\n east\\n west\\n \\\r\nGreenwich meridien\\n response: \")) \r\n \r\n \r\n\r\n location1=input(\"enter the first location: \") \r\n longitude2=int(input(\"Enter the second degree in longitude?: \",))\r\n longitude2_degree=str(input(\" north\\n south\\n east\\n west\\n \\\r\nGreenwich meridien\\n response: \"))\r\n time2=float(input(\"kindly input time: \"))\r\n location2=input(\"enter the second location: \")\r\n\r\n print(\"The inputed data for location one is: \",longitude1,d, \\\r\n longitude1_degree, \"at\" ,t, location1)\r\n print(\"The inputed data for location two is: \",longitude2,d, \\\r\n longitude2_degree, \"at\" ,time2, location2)\r\n \r\n print(\"kindly press A or B\")\r\n display=str(input(\"1 To calculate time east from greenwich \\\r\nmeridien \\n2 To calculate time west of Greenwich meridien\\\r\n \\n3 to calculate time across the greenwich meridien \\nResponse: \"))\r\n print(display)\r\n\r\n if display==\"1\":\r\n print(\"both\", e,\"of\",o) \r\n if longitude1>longitude2:\r\n \r\n largest=longitude1\r\n output1=largest-longitude2\r\n output2=((output1*a)/b)*c\r\n print(location1, \"is\", output2, h,\"away\")\r\n output3=t-output2\r\n print(\"time in \",location2, \" is \", output3)\r\n else:\r\n longitude2>longitude1\r\n largest=longitude2\r\n output1=largest-longitude1\r\n output2=((output1*a)/b)*c\r\n print(location1, \"is\", output2, h,\"away\")\r\n output3=t-output2\r\n print(\"time in \",location2, \" is \", output3)\r\n \r\n\r\n if display==\"2\":\r\n print(\"both\", w,\"of\",o)\r\n \r\n \r\n if longitude1>longitude2:\r\n \r\n \r\n largest=longitude1\r\n output1=largest-longitude2\r\n output2=((output1*a)/b)*c\r\n print(location1, \"is\", output2, h,\"away\")\r\n output3=t-output2\r\n print(\"time in \",location2, \" is \", output3)\r\n else:\r\n longitude2>longitude1\r\n largest=longitude2\r\n output1=largest-longitude1\r\n output2=((output1*a)/b)*c\r\n print(location1, \"is\", output2, h,\"away\")\r\n output3=t-output2\r\n print(\"time in \",location2, \" is \", output3)\r\n \r\n\r\n if display==\"3\":\r\n print(\"both on different hemisphere: \")\r\n output1=longitude1+longitude2\r\n output2=(output1/k)*c\r\n print(location1, \"is\", output2, h,\"away\")\r\n output3=t+output2\r\n print(\"time is gained tending east: \",location2, \" is \", output3)\r\n","repo_name":"my-first-pr/hacktoberfest-2018","sub_path":"code/Project--Calculating local Time.py","file_name":"Project--Calculating local Time.py","file_ext":"py","file_size_in_byte":6513,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"52"} +{"seq_id":"1475057318","text":"#-----mensajes----#\nMENSAJESALUDO = \"buenos dias, vamos a ahorar juntos\"\nMENSAJEMISAHORROS = \"llevas ahorrado ...\"\nMENSAJEVALORCPU = \"cuanto vale el pc que deseas?\"\nMENSAJEAHORROS = \"cuanto tienes ahorrado\"\n\n#-----entradas----#\nprint (MENSAJESALUDO)\nvalor = float (input (MENSAJEVALORCPU))\nahorrado = float (input (MENSAJEAHORROS))\n\nwhile (valor > ahorrado):\n print (MENSAJEMISAHORROS, ahorrado, \"te faltan\", valor - ahorrado)\n ahorrado = ahorrado + 1000 \nprint (valor == ahorrado)","repo_name":"mavillegas04/introprogramacion-","sub_path":"clases/ciclowhile.py","file_name":"ciclowhile.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32684007012","text":"\r\nimport csv\r\nimport numpy as np\r\nfrom time import sleep\r\n\r\n\r\nclass Node:\r\n def __init__(self, parent, cost, position):\r\n self.parent = parent\r\n self.cost = cost\r\n self.position = position\r\n#convert mazeFile to mazeGrid\r\ndef convertMaze(mazeFile):\r\n maze = []\r\n with open(mazeFile, \"r\", newline=\"\") as f:\r\n reader = csv.reader(f)\r\n for row in reader:\r\n #row.pop()\r\n maze.append(row)\r\n \r\n # convert to ints\r\n for i in range(len(maze)):\r\n for j in range(len(maze[0])):\r\n maze[i][j] = int(maze[i][j])\r\n return maze\r\n#delete the node from the frontier\r\ndef deleteNodeFrontier(node, frontier):\r\n\r\n pos = node.position\r\n newFrontier = []\r\n for tile in frontier:\r\n if tile.position != pos:\r\n newFrontier.append(tile)\r\n return newFrontier\r\n\r\n#compute the node cost with euclidean heuristic\r\ndef nodeCost(position, goal):\r\n\r\n x, y = position\r\n xGoal, yGoal = goal\r\n cost = np.sqrt((xGoal-x)**2 + (yGoal-y)**2)\r\n return cost\r\n#check the tile coordinates in maze\r\ndef inMaze(step, dimension):\r\n (maxX, maxY) = dimension\r\n (x, y) = step\r\n\r\n inX = (x <= maxX) & (x >= 0)\r\n inY = (y <= maxY) & (y >= 0)\r\n return bool(inX * inY)\r\n\r\n#find possible current successors\r\ndef findSuccessors(currentNode, maze, seen):\r\n\r\n moves = [(1,0), (-1,0), (0,1), (0,-1)]\r\n x0, y0 = currentNode.position\r\n dimension = (len(maze)-1, len(maze[0])-1)\r\n successors = []\r\n finalCost=0\r\n\r\n for move in moves:\r\n dx, dy = (move[0], move[1])\r\n nextStep = (x0 + dx, y0 + dy)\r\n cond1 = inMaze(nextStep, dimension) # if is in maze\r\n if cond1:\r\n cond2 = maze[nextStep[0]][nextStep[1]] != 0 # if not wall\r\n cond3 = nextStep not in [tile.position for tile in seen] # dont go to any already seen\r\n cond4 = maze[nextStep[0]][nextStep[1]] != 6 # if not barrier\r\n if bool(cond2*cond3*cond4):\r\n cost = nodeCost(nextStep, dimension)\r\n finalCost=finalCost+cost\r\n newNode = Node(currentNode, cost, nextStep)\r\n successors.append(newNode)\r\n\r\n print (\"Current cost is: \",finalCost)\r\n if(finalCost==0):\r\n count=1\r\n return successors\r\n\r\n#select the min cost node for the next step\r\ndef selectNode(nodeList):\r\n\r\n if len(nodeList) == 1:\r\n currentNode = nodeList[0]\r\n return currentNode\r\n \r\n currentNode = Node(None, np.inf, (0,0))\r\n for node in nodeList:\r\n if node.cost <= currentNode.cost: # select least cost\r\n currentNode = node\r\n\r\n return currentNode\r\n#run the algorithm step by step untill find the goal\r\ndef computePath(maze, frontier, seen, currentNode,arrGoal,detect):\r\n\r\n # add parent to seen list\r\n seen.append(currentNode)\r\n \r\n # remove parent from frontier\r\n frontier = deleteNodeFrontier(currentNode, frontier)\r\n #temp=currentNode\r\n # given the node compute the successors\r\n successors = findSuccessors(currentNode, maze, seen)\r\n\r\n # add successors to the frontier\r\n for son in successors:\r\n frontier.append(son)\r\n\r\n\r\n # pick one of the successors\r\n currentCheck = {currentNode.position}\r\n currentNode = selectNode(successors)\r\n\r\n if currentCheck == {currentNode.position}:\r\n #if len(frontier) == 0:\r\n #print(\"NO SOLUTION!!!!!!!\")\r\n #sleep(120)\r\n #exit()\r\n detect=False\r\n x, y = currentNode.position\r\n return maze, frontier, seen, currentNode,detect\r\n\r\n\r\n # paint the grid with the new node position\r\n x, y = currentNode.position\r\n # grid[x][y] = 4 # paint blue\r\n #if(count==0):\r\n # detect=False\r\n #else:\r\n detect = True\r\n\r\n return maze, frontier, seen, currentNode,detect\r\n\r\n","repo_name":"aycagrlyk/Bil441_MazeSolver","sub_path":"aStarSearchFunctions.py","file_name":"aStarSearchFunctions.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"38063845700","text":"from random import randint\r\nmass = [randint(-100,100) for i in range(30)]\r\nmax_mass = max(mass)\r\nindex_of_max = mass.index(max_mass)\r\nprint(\"Max: \", max_mass, \"\\nIndex of max: \", index_of_max)\r\ndef odd(mass):\r\n temp_mass = []\r\n for i in range(len(mass)):\r\n if mass[i] % 2 != 0:\r\n temp_mass.insert(0, mass[i])\r\n return temp_mass\r\nmass = odd(mass)\r\nsorted_mass = sorted(mass, reverse = True)\r\nprint(\"Sorted array:\", sorted_mass)\r\n","repo_name":"C1oudwave/kn20","sub_path":"task0/12.py","file_name":"12.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":"36657357501","text":"# -*- coding: utf-8 -*-\n# @Author : FELIX\n# @Date : 2018/2/22 19:34\n\nclass Argvhandler(object):\n \"\"\"\n 接受用户参数,并调用相应的功能\n \"\"\"\n def __init__(self,sys_args):\n self.sys_argv=sys_args\n\n def help_msg(self,error_msg=''):\n \"\"\"打印帮助\"\"\"\n msgs=\"\"\"\n {}\n run 启动用户交互程序\n \"\"\".format(str(error_msg))\n print(msgs)\n exit(msgs)\n def call(self):\n \"\"\"\n 根据用户参数,调用对应的方法\n :return:\n \"\"\"\n if len(self.sys_argv)==1:\n self.help_msg()\n if hasattr(self,self.sys_argv[1]):\n func=getattr(self,self.sys_argv[1])\n func()\n else:\n self.help_msg('没有这个方法:%s'%self.sys_argv[1])\n\n def run(self):\n \"\"\"启动用户交互程序\"\"\"\n from backend.ssh_interactive import SshHandler\n obj=SshHandler(self)\n obj.interactive()\n","repo_name":"wangyitao/BestBastionHost","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37285520918","text":"#\n# @lc app=leetcode id=468 lang=python3\n#\n# [468] Validate IP Address\n#\n# https://leetcode.com/problems/validate-ip-address/description/\n#\n# algorithms\n# Medium (24.01%)\n# Likes: 350\n# Dislikes: 1760\n# Total Accepted: 79.5K\n# Total Submissions: 330.4K\n# Testcase Example: '\"172.16.254.1\"'\n#\n# Given a string IP. We need to check If IP is a valid IPv4 address, valid IPv6\n# address or not a valid IP address.\n# \n# Return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6\n# address or \"Neither\" if IP is not a valid IP of any type.\n# \n# A valid IPv4 address is an IP in the form \"x1.x2.x3.x4\" where 0 <= xi <= 255\n# and xi cannot contain leading zeros. For example, \"192.168.1.1\" and\n# \"192.168.1.0\" are valid IPv4 addresses but \"192.168.01.1\", \"192.168.1.00\" and\n# \"192.168@1.1\" are invalid IPv4 adresses.\n# \n# A valid IPv6 address is an IP in the form \"x1:x2:x3:x4:x5:x6:x7:x8\"\n# where:\n# \n# \n# 1 <= xi.length <= 4\n# xi is hexadecimal string whcih may contain digits, lower-case English letter\n# ('a' to 'f') and/or upper-case English letters ('A' to 'F').\n# Leading zeros are allowed in xi.\n# \n# \n# For example, \"2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and\n# \"2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses but\n# \"2001:0db8:85a3::8A2E:037j:7334\" and\n# \"02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses.\n# \n# \n# Example 1:\n# \n# \n# Input: IP = \"172.16.254.1\"\n# Output: \"IPv4\"\n# Explanation: This is a valid IPv4 address, return \"IPv4\".\n# \n# \n# Example 2:\n# \n# \n# Input: IP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\n# Output: \"IPv6\"\n# Explanation: This is a valid IPv6 address, return \"IPv6\".\n# \n# \n# Example 3:\n# \n# \n# Input: IP = \"256.256.256.256\"\n# Output: \"Neither\"\n# Explanation: This is neither a IPv4 address nor a IPv6 address.\n# \n# \n# Example 4:\n# \n# \n# Input: IP = \"2001:0db8:85a3:0:0:8A2E:0370:7334:\"\n# Output: \"Neither\"\n# \n# \n# Example 5:\n# \n# \n# Input: IP = \"1e1.4.5.6\"\n# Output: \"Neither\"\n# \n# \n# \n# Constraints:\n# \n# \n# IP consists only of English letters, digits and the characters '.' and ':'.\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def validIPAddress(self, IP: str) -> str:\n # Time complexity: O(1)\n # Space complexity: O(1)\n import re\n chunk_IPv4 = r'([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'\n patten_IPv4 = re.compile(r'^(' + chunk_IPv4 + r'\\.){3}' + chunk_IPv4 + r'$')\n\n chunk_IPv6 = r'([0-9a-fA-F]{1,4})'\n patten_IPv6 = re.compile(r'^(' + chunk_IPv6 + r'\\:){7}' + chunk_IPv6 + r'$')\n\n if patten_IPv4.match(IP):\n return \"IPv4\"\n return \"IPv6\" if patten_IPv6.match(IP) else \"Neither\"\n \n# @lc code=end\n\n","repo_name":"chenxu0602/LeetCode","sub_path":"468.validate-ip-address.py","file_name":"468.validate-ip-address.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"14105478884","text":"# Reverse a Linked List\n# Solve it as in-place solution with constant space complexity ( O(1))\n# Perform the traversal linearly ( O(n))\ndef reverse_linked_list(head):\n current = head\n previous = None\n nextnode = None\n\n while current: # Loop through the list until you have any nextnode available.\n # copy the value of nextnode reference to a temp variable before overriding as the previous node.\n nextnode = current.nextnode\n current.nextnode = previous\n previous = current\n current = nextnode\n return previous\n\n\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.nextnode = None\n\n\nif __name__ == \"__main__\":\n a = Node(1)\n b = Node(2)\n c = Node(3)\n d = Node(4)\n\n a.nextnode = b\n b.nextnode = c\n c.nextnode = d\n d.nextnode = None\n print(\"Original list::\")\n print(a.value)\n print(a.nextnode.value)\n print(b.nextnode.value)\n print(c.nextnode.value)\n\n reverse_linked_list(a)\n print(\"reverse list:::\")\n print(d.value)\n print(d.nextnode.value)\n print(c.nextnode.value)\n print(b.nextnode.value)\n","repo_name":"rameshwarsingh11/data-structure-practice","sub_path":"reverse_linked_list.py","file_name":"reverse_linked_list.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"24623930505","text":"#!/usr/bin/env /usr/bin/python\n\n\nimport os\nimport errno\n\n\n_fifo_ = \"/tmp/pipe1Liam\"\n\ntry:\n os.mkfifo(_fifo_)\nexcept OSError as e:\n if (\n (e.errno != errno.EEXIST)\n ):\n raise\n\nwith open(_fifo_, \"tr\") as _FDIn_:\n while True:\n _data_ = _FDIn_.read()\n\n if (\n (len(_data_) != 0)\n ):\n print(f\"\"\"Got a whoopty {_data_}\"\"\")\n\n\n#\n","repo_name":"ComfortableSoftware/masher","sub_path":"masher/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70518265125","text":"import sys\nfrom PySide6 import QtCore, QtWidgets, QtGui\n\nimport NineKey\n\nclass MainWidget(QtWidgets.QWidget):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.setWindowTitle('9 Key Decoder')\n\t\tself.inputBox = QtWidgets.QLineEdit('Input Here.')\n\t\tself.resultBox = QtWidgets.QTextEdit('Result.')\n\t\tself.resultBox.setReadOnly(True)\n\t\tself.button = QtWidgets.QPushButton('Decode')\n\n\t\tself.layout = QtWidgets.QVBoxLayout(self)\n\t\tself.layout.addWidget(self.inputBox)\n\t\tself.layout.addWidget(self.button)\n\t\tself.layout.addWidget(self.resultBox)\n\n\t\tself.button.clicked.connect(self.decode)\n\n\t@QtCore.Slot()\n\tdef decode(self):\n\t\tresult, err = NineKey.main(self.inputBox.text())\n\t\tif err != None:\n\t\t\tself.resultBox.setText(err)\n\t\telse:\n\t\t\tself.resultBox.setText(result)\n\n\nif __name__ == '__main__':\n\tprint('Initializing...')\n\n\tapp = QtWidgets.QApplication([])\n\n\twidget = MainWidget()\n\twidget.resize(800, 600)\n\twidget.show()\n\n\tprint('Running...')\n\tsys.exit(app.exec())\n","repo_name":"Orange23333/9key","sub_path":"NineKeyUI.py","file_name":"NineKeyUI.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21436161966","text":"from __future__ import annotations\n\nfrom setup_tests import run_request, test_dir, write_rpc_request\n\n\ndef test_hover():\n def hover_req(file_path: str, ln: int, col: int) -> str:\n return write_rpc_request(\n 1,\n \"textDocument/hover\",\n {\n \"textDocument\": {\"uri\": str(file_path)},\n \"position\": {\"line\": ln, \"character\": col},\n },\n )\n\n def check_return(result_array, checks):\n assert len(result_array) == len(checks)\n for i, check in enumerate(checks):\n assert result_array[i][\"contents\"][\"value\"] == check\n\n root_dir = test_dir / \"pp\"\n string = write_rpc_request(1, \"initialize\", {\"rootPath\": str(root_dir)})\n file_path = root_dir / \"preproc.F90\"\n string += hover_req(file_path, 5, 8) # user defined type\n string += hover_req(file_path, 7, 30) # variable\n string += hover_req(file_path, 7, 40) # multi-lin variable\n string += hover_req(file_path, 8, 7) # function with if conditional\n string += hover_req(file_path, 9, 7) # multiline function with if conditional\n string += hover_req(file_path, 10, 15) # defined without ()\n file_path = root_dir / \"preproc_keywords.F90\"\n string += hover_req(file_path, 6, 2) # ignores PP across Fortran line continuations\n file_path = root_dir / \"preproc_else.F90\"\n string += hover_req(file_path, 8, 12)\n string += hover_req(file_path, 18, 12)\n file_path = root_dir / \"preproc_elif.F90\"\n string += hover_req(file_path, 22, 15)\n string += hover_req(file_path, 24, 10)\n file_path = root_dir / \"preproc_elif_elif_skip.F90\"\n string += hover_req(file_path, 30, 23)\n file_path = root_dir / \"preproc_if_elif_else.F90\"\n string += hover_req(file_path, 30, 23)\n file_path = root_dir / \"preproc_if_elif_skip.F90\"\n string += hover_req(file_path, 30, 23)\n config = str(root_dir / \".pp_conf.json\")\n errcode, results = run_request(string, [\"--config\", config])\n assert errcode == 0\n\n # Reference solution\n ref_results = (\n \"```fortran90\\n#define PCType character*(80)\\n```\",\n \"```fortran90\\n#define PETSC_ERR_INT_OVERFLOW 84\\n```\",\n \"```fortran90\\n#define varVar 55\\n```\",\n (\n \"```fortran90\\n#define ewrite if (priority <= 3) write((priority),\"\n \" format)\\n```\"\n ),\n (\n \"```fortran90\\n#define ewrite2 if (priority <= 3) write((priority),\"\n \" format)\\n```\"\n ),\n \"```fortran90\\n#define SUCCESS .true.\\n```\",\n \"```fortran90\\nREAL, CONTIGUOUS, POINTER, DIMENSION(:) :: var1\\n```\",\n \"```fortran90\\nINTEGER :: var0\\n```\",\n \"```fortran90\\nREAL :: var1\\n```\",\n \"```fortran90\\nINTEGER :: var2\\n```\",\n \"```fortran90\\nINTEGER, INTENT(INOUT) :: var\\n```\",\n \"```fortran90\\nINTEGER, PARAMETER :: res = 0+1+0+0\\n```\",\n \"```fortran90\\nINTEGER, PARAMETER :: res = 0+0+0+1\\n```\",\n \"```fortran90\\nINTEGER, PARAMETER :: res = 1+0+0+0\\n```\",\n )\n assert len(ref_results) == len(results) - 1\n check_return(results[1:], ref_results)\n","repo_name":"fortran-lang/fortls","sub_path":"test/test_preproc.py","file_name":"test_preproc.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":182,"dataset":"github-code","pt":"52"} +{"seq_id":"73249919205","text":"#!/usr/bin/env python\n\nfrom argparse import ArgumentParser\nimport sys\n\nfrom vsc.atools.int_ranges import (int_ranges2set, set2int_ranges,\n InvalidRangeSpecError)\nfrom vsc.atools.log_parser import LogParser, InvalidLogEntryError\nfrom vsc.atools.work_analysis import (compute_items_todo,\n MissingSourceError)\nfrom vsc.atools.utils import SnifferError\n\n\nif __name__ == '__main__':\n arg_parser = ArgumentParser(description='Compute the array ID range')\n arg_parser.add_argument('--data', nargs='*',\n help='CSV files to use')\n arg_parser.add_argument('-t', help='array ID range to consider')\n arg_parser.add_argument('--log', nargs='*',\n help='log file to compute completed items from')\n arg_parser.add_argument('--redo', action='store_true',\n help='redo failed items')\n arg_parser.add_argument('--summary', action='store_true',\n help='print a summary of a job that is '\n 'running or completed')\n arg_parser.add_argument('--list_failed', action='store_true',\n help='list failed jobs when summarizing')\n arg_parser.add_argument('--list_completed', action='store_true',\n help='list completed jobs when summarizing')\n arg_parser.add_argument('--sniff', type=int, default=1024,\n help='number of bytes to sniff for CSV dialect')\n arg_parser.add_argument('--no_sniffer', action='store_true',\n help='do not use the sniffer for CSV dialect')\n arg_parser.add_argument('--conf', help='configuration file')\n options = arg_parser.parse_args()\n if options.summary and not options.log:\n msg = '### error: summary information requires log files\\n'\n sys.stderr.write(msg)\n sys.exit(1)\n try:\n todo, completed, failed = compute_items_todo(\n options.data, options.t, options.log, must_redo=options.redo,\n sniff=options.sniff, no_sniffer=options.no_sniffer\n )\n if options.summary:\n print('Summary:')\n print(' items completed: {0:d}'.format(len(completed)))\n print(' items failed: {0:d}'.format(len(failed)))\n print(' items to do: {0:d}'.format(len(todo)))\n if options.list_failed:\n print('failed: {0}'.format(set2int_ranges(failed)))\n if options.list_completed:\n print('completed: {0}'.format(set2int_ranges(completed)))\n else:\n if options.list_completed:\n print(set2int_ranges(completed))\n else:\n print(set2int_ranges(todo))\n except IOError as error:\n msg = '### IOError: {0}'.format(str(error))\n sys.stderr.write(msg)\n sys.exit(error.errno)\n except InvalidRangeSpecError as error:\n msg = '### error: {0}'.format(str(error))\n sys.stderr.write(msg)\n sys.exit(error.errno)\n except MissingSourceError as error:\n msg = '### error: {0}'.format(str(error))\n sys.stderr.write(msg)\n sys.exit(error.errno)\n except InvalidLogEntryError as error:\n msg = '### error: {0}'.format(str(error))\n sys.stderr.write(msg)\n sys.exit(error.errno)\n except SnifferError as error:\n msg = '### error: {0}'.format(str(error))\n sys.stderr.write(msg)\n sys.exit(error.errno)\n","repo_name":"gjbex/atools","sub_path":"lib/arange.py","file_name":"arange.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"2013224280","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# author ZhangLiang\r\nfrom textrank4zh import TextRank4Keyword, TextRank4Sentence\r\nimport settings\r\nimport jieba\r\n# 由于textrank4zh 使用的是结巴分词,为了在短文本更好的提取关键词\r\n# 加载用户自定义的词语,使得分词更准确。\r\njieba.load_userdict(settings.USER_DICT_DATA)\r\n\r\n\r\nclass TEXT_SUMMARY:\r\n def __init__(self, path):\r\n \"\"\"\r\n 初始化函数接口,加载停用词表\r\n :param path: 停用词表存储路径\r\n \"\"\"\r\n self.tr4w = TextRank4Keyword(stop_words_file=path)\r\n self.tr4s = TextRank4Sentence(stop_words_file=path)\r\n\r\n def get_key(self, cluster: list, words_num=-1, sentences_num=-1):\r\n \"\"\"\r\n 根据传入的聚类结果提取关键词,关键句\r\n :param cluster: 某一聚类类别的原始文本;格式类似['我喜欢吃烧烤。','新时代四大名著有哪些?']\r\n :param words_num: 从文本中提取的关键词个数;默认-1,不执行操作\r\n :param sentences_num: 从文本中提取的关键句个数;默认-1,不执行操作\r\n :return: 返回关键词列表,关键句列表\r\n \"\"\"\r\n # 将list聚合成一个文本\r\n # 注意:要求text必须是utf8编码的bytes或者str对象\r\n text = ''\r\n for c in cluster:\r\n if c[-1] not in ['!', '。', '?', \";\", \"!\"]:\r\n c = c+'。' # 用句号将不同的句子进行隔\r\n text = text+c\r\n keywords = []\r\n key_sentences = []\r\n if words_num > 0:\r\n # 分析文本\r\n self.tr4w.analyze(text=text, lower=True, window=2)\r\n # 提取关键词,关键词最少包含2个汉字\r\n for item in self.tr4w.get_keywords(num=words_num, word_min_len=2):\r\n keywords.append(item.word)\r\n if sentences_num > 0:\r\n # 分析文本\r\n self.tr4s.analyze(text=text, lower=True, source='all_filters')\r\n # 提取关键句;这里设定为关键句长度不能小于10\r\n for item in self.tr4s.get_key_sentences(num=sentences_num, sentence_min_len=10):\r\n key_sentences.append(item.sentence)\r\n return keywords, key_sentences\r\n\r\n\r\n\r\n","repo_name":"pppihf/streamEventCluster","sub_path":"Modules/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18513794565","text":"from collections import defaultdict\nfrom datetime import date\n\nimport db_handler\n\ndt = date.today()\ndata = db_handler.get_data_object_from_db(2019, '410')\n\nOFFICER_MAP = {'Club President': 'pres',\n 'Club Secretary': 'sec',\n 'Club Treasurer': 'treas',\n 'Club Membership Chairperson': 'mem_chair'}\n\ndef build_mailing_list(struct, officer, lines):\n with open(f'{dt:%y%m%d}_{struct}_{officer}_emails.txt', 'w') as fh:\n fh.write('\\n'.join(lines))\n\nall_emails = defaultdict(list)\nwhile data.next_district():\n emails = defaultdict(list)\n # PDGs\n emails['pdg'] = [f'{o.member.name} <{o.member.email}>' for o in data.get_past_dgs() + data.get_past_foreign_dgs() if o.member.email and o.member.is_active]\n all_emails['pdg'].extend(emails)\n\n # club officers\n for club in data.get_district_clubs():\n for off in club.officers:\n title = OFFICER_MAP.get(off.title, None)\n if title and off.member and off.member.email:\n emails[title].append(f'{off.member.name} <{off.member.email}>')\n all_emails[title].append(off.member.email)\n\n for (k,v) in emails.items():\n build_mailing_list(data.district.file_name, k, v)\n\nfor (k,v) in all_emails.items():\n build_mailing_list(data.struct.file_name, k, v)\n\n\n","repo_name":"kimvanwyk/md_directory_builder","sub_path":"app/build_mailing_lists.py","file_name":"build_mailing_lists.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10704382850","text":"def longest_common_seq(s1, s2):\n len1, len2 = len(s1), len(s2)\n\n res = [[0]*(len2+1) for _ in range((len1+1))]\n\n for j in range(1, len2+1):\n for i in range(1, len1+1):\n if s1[i-1] == s2[j-1]:\n res[i][j] = res[i-1][j-1] + 1\n else:\n res[i][j] = max(res[i-1][j], res[i][j-1])\n\n out = []\n while len1 > 0 and len2 > 0:\n if s1[len1-1] == s2[len2-1]:\n out.append(s1[len1-1])\n len1 -= 1\n len2 -= 1\n elif res[len1-1][len2] == res[len1][len2-1]:\n len2 -= 1\n elif res[len1-1][len2] > res[len1][len2-1]:\n len1 -= 1\n else:\n len2 -= 1\n\n out.reverse()\n return out\n\n\nif __name__ == \"__main__\":\n s1 = \"13456778\"\n s2 = \"357486782\"\n\n assert longest_common_seq(s1, s2) == ['3', '5', '7', '7', '8']\n","repo_name":"ne7ermore/playground","sub_path":"python/map/longest_common_seq.py","file_name":"longest_common_seq.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"} +{"seq_id":"7569109839","text":"\nfrom rediz.client import Rediz\nfrom rediz.collider_config_private import REDIZ_COLLIDER_CONFIG\nfrom pprint import pprint\n\n\nif __name__ == '__main__':\n rdz = Rediz(**REDIZ_COLLIDER_CONFIG)\n ownership = rdz.client.hgetall(rdz._OWNERSHIP)\n for name, write_key in ownership.items():\n for delay in rdz.DELAYS:\n samples_name = rdz._samples_name(name=name, delay=delay)\n sample_owners_name = rdz._sample_owners_name(name=name,delay=delay)\n rdz.client.delete(samples_name)\n rdz.client.delete(sample_owners_name)\n print('Deleted samples and owners for '+samples_name)\n\n promises = rdz.client.keys(pattern='*promised*')\n rdz.client.delete(*promises)\n print('Deleted promises')\n\n\n\n\n","repo_name":"microprediction/rediz","sub_path":"collider_admin/delete_samples_and_owners_and_promises.py","file_name":"delete_samples_and_owners_and_promises.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39802615788","text":"from oslo.config import cfg\n\nfrom neutron.api.v2 import attributes\nfrom neutron.common import constants as l3_const\nfrom neutron.common import exceptions as n_exc\nfrom neutron.common import utils as n_utils\nfrom neutron.db import l3_attrs_db\nfrom neutron.db import l3_db\nfrom neutron.db import l3_dvrscheduler_db as l3_dvrsched_db\nfrom neutron.db import models_v2\nfrom neutron.extensions import l3\nfrom neutron.extensions import portbindings\nfrom neutron.i18n import _LI\nfrom neutron import manager\nfrom neutron.openstack.common import log as logging\nfrom neutron.plugins.common import constants\n\n\nLOG = logging.getLogger(__name__)\n\nDEVICE_OWNER_DVR_INTERFACE = l3_const.DEVICE_OWNER_DVR_INTERFACE\nDEVICE_OWNER_DVR_SNAT = l3_const.DEVICE_OWNER_ROUTER_SNAT\nFLOATINGIP_AGENT_INTF_KEY = l3_const.FLOATINGIP_AGENT_INTF_KEY\nDEVICE_OWNER_AGENT_GW = l3_const.DEVICE_OWNER_AGENT_GW\nSNAT_ROUTER_INTF_KEY = l3_const.SNAT_ROUTER_INTF_KEY\n\n\nrouter_distributed_opts = [\n cfg.BoolOpt('router_distributed',\n default=False,\n help=_(\"System-wide flag to determine the type of router \"\n \"that tenants can create. Only admin can override.\")),\n]\ncfg.CONF.register_opts(router_distributed_opts)\n\n\nclass L3_NAT_with_dvr_db_mixin(l3_db.L3_NAT_db_mixin,\n l3_attrs_db.ExtraAttributesMixin):\n \"\"\"Mixin class to enable DVR support.\"\"\"\n\n router_device_owners = (\n l3_db.L3_NAT_db_mixin.router_device_owners +\n (DEVICE_OWNER_DVR_INTERFACE,))\n\n extra_attributes = (\n l3_attrs_db.ExtraAttributesMixin.extra_attributes + [{\n 'name': \"distributed\",\n 'default': cfg.CONF.router_distributed\n }])\n\n def _create_router_db(self, context, router, tenant_id):\n \"\"\"Create a router db object with dvr additions.\"\"\"\n router['distributed'] = is_distributed_router(router)\n with context.session.begin(subtransactions=True):\n router_db = super(\n L3_NAT_with_dvr_db_mixin, self)._create_router_db(\n context, router, tenant_id)\n self._process_extra_attr_router_create(context, router_db, router)\n return router_db\n\n def _validate_router_migration(self, context, router_db, router_res):\n \"\"\"Allow centralized -> distributed state transition only.\"\"\"\n if (router_db.extra_attributes.distributed and\n router_res.get('distributed') is False):\n LOG.info(_LI(\"Centralizing distributed router %s \"\n \"is not supported\"), router_db['id'])\n raise NotImplementedError()\n elif (not router_db.extra_attributes.distributed and\n router_res.get('distributed')):\n # Add a check for Services FWaaS and VPNaaS\n # This check below ensures that the legacy routers with\n # associated VPNaaS or FWaaS services are not allowed to\n # migrate.\n if (self.check_router_has_no_vpnaas(context, router_db) and\n self.check_router_has_no_firewall(context, router_db)):\n LOG.info(_LI(\"No Service associated, so safe to migrate: %s \"\n \"listed\"), router_db['id'])\n\n def check_router_has_no_firewall(self, context, router_db):\n \"\"\"Check if FWaaS is associated with the legacy router.\"\"\"\n fwaas_service = manager.NeutronManager.get_service_plugins().get(\n constants.FIREWALL)\n if fwaas_service:\n tenant_firewalls = fwaas_service.get_firewalls(\n context,\n filters={'tenant_id': [router_db['tenant_id']]})\n if tenant_firewalls:\n raise l3.RouterInUse(router_id=router_db['id'])\n return True\n\n def check_router_has_no_vpnaas(self, context, router_db):\n \"\"\"Check if VPNaaS is associated with the legacy router.\"\"\"\n vpn_plugin = manager.NeutronManager.get_service_plugins().get(\n constants.VPN)\n if vpn_plugin:\n vpn_plugin.check_router_in_use(context, router_db['id'])\n return True\n\n def _update_distributed_attr(\n self, context, router_id, router_db, data, gw_info):\n \"\"\"Update the model to support the dvr case of a router.\"\"\"\n if data.get('distributed'):\n old_owner = l3_const.DEVICE_OWNER_ROUTER_INTF\n new_owner = DEVICE_OWNER_DVR_INTERFACE\n for rp in router_db.attached_ports.filter_by(port_type=old_owner):\n rp.port_type = new_owner\n rp.port.device_owner = new_owner\n\n def _update_router_db(self, context, router_id, data, gw_info):\n with context.session.begin(subtransactions=True):\n router_db = super(\n L3_NAT_with_dvr_db_mixin, self)._update_router_db(\n context, router_id, data, gw_info)\n migrating_to_distributed = (\n not router_db.extra_attributes.distributed and\n data.get('distributed') is True)\n self._validate_router_migration(context, router_db, data)\n router_db.extra_attributes.update(data)\n self._update_distributed_attr(\n context, router_id, router_db, data, gw_info)\n if migrating_to_distributed:\n if router_db['gw_port_id']:\n # If the Legacy router is getting migrated to a DVR\n # router, make sure to create corresponding\n # snat interface ports that are to be consumed by\n # the Service Node.\n if not self.create_snat_intf_ports_if_not_exists(\n context.elevated(), router_db):\n LOG.debug(\"SNAT interface ports not created: %s\",\n router_db['id'])\n cur_agents = self.list_l3_agents_hosting_router(\n context, router_db['id'])['agents']\n for agent in cur_agents:\n self._unbind_router(context, router_db['id'],\n agent['id'])\n return router_db\n\n def _delete_current_gw_port(self, context, router_id, router, new_network,\n ext_ip_change):\n super(L3_NAT_with_dvr_db_mixin,\n self)._delete_current_gw_port(context, router_id,\n router, new_network, ext_ip_change)\n if router.extra_attributes.distributed:\n self.delete_csnat_router_interface_ports(\n context.elevated(), router)\n\n def _create_gw_port(self, context, router_id, router, new_network, ext_ips,\n ext_ip_change):\n super(L3_NAT_with_dvr_db_mixin,\n self)._create_gw_port(context, router_id, router, new_network,\n ext_ips, ext_ip_change)\n # Make sure that the gateway port exists before creating the\n # snat interface ports for distributed router.\n if router.extra_attributes.distributed and router.gw_port:\n snat_p_list = self.create_snat_intf_ports_if_not_exists(\n context.elevated(), router)\n if not snat_p_list:\n LOG.debug(\"SNAT interface ports not created: %s\", snat_p_list)\n\n def _get_device_owner(self, context, router=None):\n \"\"\"Get device_owner for the specified router.\"\"\"\n router_is_uuid = isinstance(router, basestring)\n if router_is_uuid:\n router = self._get_router(context, router)\n if is_distributed_router(router):\n return DEVICE_OWNER_DVR_INTERFACE\n return super(L3_NAT_with_dvr_db_mixin,\n self)._get_device_owner(context, router)\n\n def _get_interface_ports_for_network(self, context, network_id):\n router_intf_qry = context.session.query(l3_db.RouterPort)\n router_intf_qry = router_intf_qry.join(models_v2.Port)\n\n return router_intf_qry.filter(\n models_v2.Port.network_id == network_id,\n l3_db.RouterPort.port_type.in_(l3_const.ROUTER_INTERFACE_OWNERS)\n )\n\n def _update_fip_assoc(self, context, fip, floatingip_db, external_port):\n \"\"\"Override to delete the fip agent gw port on disassociate.\"\"\"\n fip_port = fip.get('port_id')\n unused_fip_agent_gw_port = (\n fip_port is None and floatingip_db['fixed_port_id'])\n if unused_fip_agent_gw_port:\n admin_ctx = context.elevated()\n self.clear_unused_fip_agent_gw_port(\n admin_ctx, floatingip_db)\n super(L3_NAT_with_dvr_db_mixin, self)._update_fip_assoc(\n context, fip, floatingip_db, external_port)\n\n def clear_unused_fip_agent_gw_port(\n self, context, floatingip_db):\n \"\"\"Helper function to check for fip agent gw port and delete.\n\n This function checks on compute nodes to make sure if there\n are any VMs using the FIP agent gateway port. If no VMs are\n using the FIP agent gateway port, it will go ahead and delete\n the FIP agent gateway port. If even a single VM is using the\n port it will not delete.\n \"\"\"\n fip_hostid = self.get_vm_port_hostid(\n context, floatingip_db['fixed_port_id'])\n if fip_hostid and self.check_fips_availability_on_host(\n context, fip_hostid):\n LOG.debug('Deleting the Agent GW Port on host: %s', fip_hostid)\n self.delete_floatingip_agent_gateway_port(context, fip_hostid)\n\n def delete_floatingip(self, context, id):\n floatingip = self._get_floatingip(context, id)\n if floatingip['fixed_port_id']:\n admin_ctx = context.elevated()\n self.clear_unused_fip_agent_gw_port(\n admin_ctx, floatingip)\n super(L3_NAT_with_dvr_db_mixin,\n self).delete_floatingip(context, id)\n\n def _get_floatingip_on_port(self, context, port_id=None):\n \"\"\"Helper function to retrieve the fip associated with port.\"\"\"\n fip_qry = context.session.query(l3_db.FloatingIP)\n floating_ip = fip_qry.filter_by(fixed_port_id=port_id)\n return floating_ip.first()\n\n def disassociate_floatingips(self, context, port_id, do_notify=True):\n \"\"\"Override disassociate floatingips to delete fip agent gw port.\"\"\"\n with context.session.begin(subtransactions=True):\n fip = self._get_floatingip_on_port(\n context, port_id=port_id)\n if fip:\n admin_ctx = context.elevated()\n self.clear_unused_fip_agent_gw_port(\n admin_ctx, fip)\n return super(L3_NAT_with_dvr_db_mixin,\n self).disassociate_floatingips(context,\n port_id,\n do_notify=do_notify)\n\n def add_router_interface(self, context, router_id, interface_info):\n add_by_port, add_by_sub = self._validate_interface_info(interface_info)\n router = self._get_router(context, router_id)\n device_owner = self._get_device_owner(context, router)\n\n if add_by_port:\n port = self._add_interface_by_port(\n context, router, interface_info['port_id'], device_owner)\n elif add_by_sub:\n port = self._add_interface_by_subnet(\n context, router, interface_info['subnet_id'], device_owner)\n\n with context.session.begin(subtransactions=True):\n router_port = l3_db.RouterPort(\n port_id=port['id'],\n router_id=router.id,\n port_type=device_owner\n )\n context.session.add(router_port)\n\n if router.extra_attributes.distributed and router.gw_port:\n self.add_csnat_router_interface_port(\n context.elevated(), router, port['network_id'],\n port['fixed_ips'][0]['subnet_id'])\n\n router_interface_info = self._make_router_interface_info(\n router_id, port['tenant_id'], port['id'],\n port['fixed_ips'][0]['subnet_id'])\n self.notify_router_interface_action(\n context, router_interface_info, 'add')\n return router_interface_info\n\n def remove_router_interface(self, context, router_id, interface_info):\n if not interface_info:\n msg = _(\"Either subnet_id or port_id must be specified\")\n raise n_exc.BadRequest(resource='router', msg=msg)\n\n port_id = interface_info.get('port_id')\n subnet_id = interface_info.get('subnet_id')\n router = self._get_router(context, router_id)\n device_owner = self._get_device_owner(context, router)\n\n if port_id:\n port, subnet = self._remove_interface_by_port(\n context, router_id, port_id, subnet_id, device_owner)\n elif subnet_id:\n port, subnet = self._remove_interface_by_subnet(\n context, router_id, subnet_id, device_owner)\n\n if router.extra_attributes.distributed and router.gw_port:\n self.delete_csnat_router_interface_ports(\n context.elevated(), router, subnet_id=subnet_id)\n\n router_interface_info = self._make_router_interface_info(\n router_id, port['tenant_id'], port['id'],\n port['fixed_ips'][0]['subnet_id'])\n self.notify_router_interface_action(\n context, router_interface_info, 'remove')\n return router_interface_info\n\n def get_snat_sync_interfaces(self, context, router_ids):\n \"\"\"Query router interfaces that relate to list of router_ids.\"\"\"\n if not router_ids:\n return []\n qry = context.session.query(l3_db.RouterPort)\n qry = qry.filter(\n l3_db.RouterPort.router_id.in_(router_ids),\n l3_db.RouterPort.port_type == DEVICE_OWNER_DVR_SNAT\n )\n\n # TODO(markmcclain): This is suboptimal but was left to reduce\n # changeset size since it is late in cycle\n ports = [rp.port.id for rp in qry]\n interfaces = self._core_plugin.get_ports(context, {'id': ports})\n LOG.debug(\"Return the SNAT ports: %s\", interfaces)\n if interfaces:\n self._populate_subnet_for_ports(context, interfaces)\n return interfaces\n\n def _build_routers_list(self, context, routers, gw_ports):\n # Perform a single query up front for all routers\n router_ids = [r['id'] for r in routers]\n snat_binding = l3_dvrsched_db.CentralizedSnatL3AgentBinding\n query = (context.session.query(snat_binding).\n filter(snat_binding.router_id.in_(router_ids))).all()\n bindings = dict((b.router_id, b) for b in query)\n\n for rtr in routers:\n gw_port_id = rtr['gw_port_id']\n # Collect gw ports only if available\n if gw_port_id and gw_ports.get(gw_port_id):\n rtr['gw_port'] = gw_ports[gw_port_id]\n if 'enable_snat' in rtr[l3.EXTERNAL_GW_INFO]:\n rtr['enable_snat'] = (\n rtr[l3.EXTERNAL_GW_INFO]['enable_snat'])\n\n binding = bindings.get(rtr['id'])\n if not binding:\n rtr['gw_port_host'] = None\n LOG.debug('No snat is bound to router %s', rtr['id'])\n continue\n\n rtr['gw_port_host'] = binding.l3_agent.host\n\n return routers\n\n def _process_routers(self, context, routers):\n routers_dict = {}\n for router in routers:\n routers_dict[router['id']] = router\n router_ids = [router['id']]\n if router['gw_port_id']:\n snat_router_intfs = self.get_snat_sync_interfaces(context,\n router_ids)\n LOG.debug(\"SNAT ports returned: %s \", snat_router_intfs)\n router[SNAT_ROUTER_INTF_KEY] = snat_router_intfs\n return routers_dict\n\n def _process_floating_ips(self, context, routers_dict, floating_ips):\n for floating_ip in floating_ips:\n router = routers_dict.get(floating_ip['router_id'])\n if router:\n router_floatingips = router.get(l3_const.FLOATINGIP_KEY, [])\n floatingip_agent_intfs = []\n if router['distributed']:\n floating_ip['host'] = self.get_vm_port_hostid(\n context, floating_ip['port_id'])\n LOG.debug(\"Floating IP host: %s\", floating_ip['host'])\n # if no VM there won't be an agent assigned\n if not floating_ip['host']:\n continue\n fip_agent = self._get_agent_by_type_and_host(\n context, l3_const.AGENT_TYPE_L3,\n floating_ip['host'])\n LOG.debug(\"FIP Agent : %s \", fip_agent['id'])\n floatingip_agent_intfs = self.get_fip_sync_interfaces(\n context, fip_agent['id'])\n LOG.debug(\"FIP Agent ports: %s\", floatingip_agent_intfs)\n router_floatingips.append(floating_ip)\n router[l3_const.FLOATINGIP_KEY] = router_floatingips\n router[l3_const.FLOATINGIP_AGENT_INTF_KEY] = (\n floatingip_agent_intfs)\n\n def get_fip_sync_interfaces(self, context, fip_agent_id):\n \"\"\"Query router interfaces that relate to list of router_ids.\"\"\"\n if not fip_agent_id:\n return []\n filters = {'device_id': [fip_agent_id],\n 'device_owner': [DEVICE_OWNER_AGENT_GW]}\n interfaces = self._core_plugin.get_ports(context.elevated(), filters)\n LOG.debug(\"Return the FIP ports: %s \", interfaces)\n if interfaces:\n self._populate_subnet_for_ports(context, interfaces)\n return interfaces\n\n def get_sync_data(self, context, router_ids=None, active=None):\n routers, interfaces, floating_ips = self._get_router_info_list(\n context, router_ids=router_ids, active=active,\n device_owners=l3_const.ROUTER_INTERFACE_OWNERS)\n # Add the port binding host to the floatingip dictionary\n for fip in floating_ips:\n fip['host'] = self.get_vm_port_hostid(context, fip['port_id'])\n routers_dict = self._process_routers(context, routers)\n self._process_floating_ips(context, routers_dict, floating_ips)\n self._process_interfaces(routers_dict, interfaces)\n return routers_dict.values()\n\n def get_vm_port_hostid(self, context, port_id, port=None):\n \"\"\"Return the portbinding host_id.\"\"\"\n vm_port_db = port or self._core_plugin.get_port(context, port_id)\n device_owner = vm_port_db['device_owner'] if vm_port_db else \"\"\n if (n_utils.is_dvr_serviced(device_owner) or\n device_owner == DEVICE_OWNER_AGENT_GW):\n return vm_port_db[portbindings.HOST_ID]\n\n def get_agent_gw_ports_exist_for_network(\n self, context, network_id, host, agent_id):\n \"\"\"Return agent gw port if exist, or None otherwise.\"\"\"\n if not network_id:\n LOG.debug(\"Network not specified\")\n return\n\n filters = {\n 'network_id': [network_id],\n 'device_id': [agent_id],\n 'device_owner': [DEVICE_OWNER_AGENT_GW]\n }\n ports = self._core_plugin.get_ports(context, filters)\n if ports:\n return ports[0]\n\n def check_fips_availability_on_host(self, context, host_id):\n \"\"\"Query all floating_ips and filter by particular host.\"\"\"\n fip_count_on_host = 0\n with context.session.begin(subtransactions=True):\n routers = self._get_sync_routers(context, router_ids=None)\n router_ids = [router['id'] for router in routers]\n floating_ips = self._get_sync_floating_ips(context, router_ids)\n # Check for the active floatingip in the host\n for fip in floating_ips:\n f_host = self.get_vm_port_hostid(context, fip['port_id'])\n if f_host == host_id:\n fip_count_on_host += 1\n # If fip_count greater than 1 or equal to zero no action taken\n # if the fip_count is equal to 1, then this would be last active\n # fip in the host, so the agent gateway port can be deleted.\n if fip_count_on_host == 1:\n return True\n return False\n\n def delete_floatingip_agent_gateway_port(self, context, host_id):\n \"\"\"Function to delete the FIP agent gateway port on host.\"\"\"\n # delete any fip agent gw port\n device_filter = {'device_owner': [DEVICE_OWNER_AGENT_GW]}\n ports = self._core_plugin.get_ports(context,\n filters=device_filter)\n for p in ports:\n if self.get_vm_port_hostid(context, p['id'], p) == host_id:\n self._core_plugin._delete_port(context, p['id'])\n return\n\n def create_fip_agent_gw_port_if_not_exists(\n self, context, network_id, host):\n \"\"\"Function to return the FIP Agent GW port.\n\n This function will create a FIP Agent GW port\n if required. If the port already exists, it\n will return the existing port and will not\n create a new one.\n \"\"\"\n l3_agent_db = self._get_agent_by_type_and_host(\n context, l3_const.AGENT_TYPE_L3, host)\n if l3_agent_db:\n LOG.debug(\"Agent ID exists: %s\", l3_agent_db['id'])\n f_port = self.get_agent_gw_ports_exist_for_network(\n context, network_id, host, l3_agent_db['id'])\n if not f_port:\n LOG.info(_LI('Agent Gateway port does not exist,'\n ' so create one: %s'), f_port)\n agent_port = self._core_plugin.create_port(\n context,\n {'port': {'tenant_id': '',\n 'network_id': network_id,\n 'mac_address': attributes.ATTR_NOT_SPECIFIED,\n 'fixed_ips': attributes.ATTR_NOT_SPECIFIED,\n 'device_id': l3_agent_db['id'],\n 'device_owner': DEVICE_OWNER_AGENT_GW,\n 'admin_state_up': True,\n 'name': ''}})\n if agent_port:\n self._populate_subnet_for_ports(context, [agent_port])\n return agent_port\n msg = _(\"Unable to create the Agent Gateway Port\")\n raise n_exc.BadRequest(resource='router', msg=msg)\n else:\n self._populate_subnet_for_ports(context, [f_port])\n return f_port\n\n def get_snat_interface_ports_for_router(self, context, router_id):\n \"\"\"Return all existing snat_router_interface ports.\"\"\"\n # TODO(markmcclain): This is suboptimal but was left to reduce\n # changeset size since it is late in cycle\n qry = context.session.query(l3_db.RouterPort)\n qry = qry.filter_by(\n router_id=router_id,\n port_type=DEVICE_OWNER_DVR_SNAT\n )\n\n ports = [rp.port.id for rp in qry]\n return self._core_plugin.get_ports(context, {'id': ports})\n\n def add_csnat_router_interface_port(\n self, context, router, network_id, subnet_id, do_pop=True):\n \"\"\"Add SNAT interface to the specified router and subnet.\"\"\"\n snat_port = self._core_plugin.create_port(\n context,\n {'port': {'tenant_id': '',\n 'network_id': network_id,\n 'mac_address': attributes.ATTR_NOT_SPECIFIED,\n 'fixed_ips': [{'subnet_id': subnet_id}],\n 'device_id': router.id,\n 'device_owner': DEVICE_OWNER_DVR_SNAT,\n 'admin_state_up': True,\n 'name': ''}})\n if not snat_port:\n msg = _(\"Unable to create the SNAT Interface Port\")\n raise n_exc.BadRequest(resource='router', msg=msg)\n\n with context.session.begin(subtransactions=True):\n router_port = l3_db.RouterPort(\n port_id=snat_port['id'],\n router_id=router.id,\n port_type=DEVICE_OWNER_DVR_SNAT\n )\n context.session.add(router_port)\n\n if do_pop:\n return self._populate_subnet_for_ports(context, [snat_port])\n return snat_port\n\n def create_snat_intf_ports_if_not_exists(self, context, router):\n \"\"\"Function to return the snat interface port list.\n\n This function will return the snat interface port list\n if it exists. If the port does not exist it will create\n new ports and then return the list.\n \"\"\"\n port_list = self.get_snat_interface_ports_for_router(\n context, router.id)\n if port_list:\n self._populate_subnet_for_ports(context, port_list)\n return port_list\n port_list = []\n\n int_ports = (\n rp.port for rp in\n router.attached_ports.filter_by(\n port_type=DEVICE_OWNER_DVR_INTERFACE\n )\n )\n LOG.info(_LI('SNAT interface port list does not exist,'\n ' so create one: %s'), port_list)\n for intf in int_ports:\n if intf.fixed_ips:\n # Passing the subnet for the port to make sure the IP's\n # are assigned on the right subnet if multiple subnet\n # exists\n snat_port = self.add_csnat_router_interface_port(\n context, router, intf['network_id'],\n intf['fixed_ips'][0]['subnet_id'], do_pop=False)\n port_list.append(snat_port)\n if port_list:\n self._populate_subnet_for_ports(context, port_list)\n return port_list\n\n def dvr_vmarp_table_update(self, context, port_dict, action):\n \"\"\"Notify the L3 agent of VM ARP table changes.\n\n Provide the details of the VM ARP to the L3 agent when\n a Nova instance gets created or deleted.\n \"\"\"\n # Check this is a valid VM port\n if (\"compute:\" not in port_dict['device_owner'] or\n not port_dict['fixed_ips']):\n return\n ip_address = port_dict['fixed_ips'][0]['ip_address']\n subnet = port_dict['fixed_ips'][0]['subnet_id']\n filters = {'fixed_ips': {'subnet_id': [subnet]}}\n ports = self._core_plugin.get_ports(context, filters=filters)\n for port in ports:\n if port['device_owner'] == DEVICE_OWNER_DVR_INTERFACE:\n router_id = port['device_id']\n router_dict = self._get_router(context, router_id)\n if router_dict.extra_attributes.distributed:\n arp_table = {'ip_address': ip_address,\n 'mac_address': port_dict['mac_address'],\n 'subnet_id': subnet}\n if action == \"add\":\n notify_action = self.l3_rpc_notifier.add_arp_entry\n elif action == \"del\":\n notify_action = self.l3_rpc_notifier.del_arp_entry\n notify_action(context, router_id, arp_table)\n return\n\n def delete_csnat_router_interface_ports(self, context,\n router, subnet_id=None):\n # Each csnat router interface port is associated\n # with a subnet, so we need to pass the subnet id to\n # delete the right ports.\n\n # TODO(markmcclain): This is suboptimal but was left to reduce\n # changeset size since it is late in cycle\n ports = (\n rp.port.id for rp in\n router.attached_ports.filter_by(port_type=DEVICE_OWNER_DVR_SNAT)\n if rp.port\n )\n\n c_snat_ports = self._core_plugin.get_ports(\n context,\n filters={'id': ports}\n )\n for p in c_snat_ports:\n if subnet_id is None:\n self._core_plugin.delete_port(context,\n p['id'],\n l3_port_check=False)\n else:\n if p['fixed_ips'][0]['subnet_id'] == subnet_id:\n LOG.debug(\"Subnet matches: %s\", subnet_id)\n self._core_plugin.delete_port(context,\n p['id'],\n l3_port_check=False)\n\n\ndef is_distributed_router(router):\n \"\"\"Return True if router to be handled is distributed.\"\"\"\n try:\n # See if router is a DB object first\n requested_router_type = router.extra_attributes.distributed\n except AttributeError:\n # if not, try to see if it is a request body\n requested_router_type = router.get('distributed')\n if attributes.is_attr_set(requested_router_type):\n return requested_router_type\n return cfg.CONF.router_distributed\n","repo_name":"projectcalico/calico-neutron","sub_path":"neutron/db/l3_dvr_db.py","file_name":"l3_dvr_db.py","file_ext":"py","file_size_in_byte":29207,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"} +{"seq_id":"21718994124","text":"from random import *\n\n\ncnt = 0\nfor customer in range(1, 51):\n print(customer)\n time = randrange(5,51) # 5 ~ 50분 소요시간\n if 5 <= time <=15: # 매칭 성공5~15분 이내 손님, 탑승 승객 수 증가 처리\n print(\"[O] {0}번째 손님 (소요시간 : {1}분)\".format(customer, time))\n cnt += 1\n else: #매칭 실패\n print(\"[ ] {0}번째 손님 (소요시간 : {1}분)\".format(customer, time))\nprint(\"총 탑승 승랙 : {0}명\".format(cnt))","repo_name":"KimKyeongJun/pyhon-basic","sub_path":"ControlStatement/practice-quiz.py","file_name":"practice-quiz.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32164266727","text":"#Working With Streamlit SideBar\n\nimport streamlit as st\nimport pandas as pd\nimport datetime as dt\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nst.set_page_config(layout='wide')\n\n\ntrees_df = pd.read_csv('trees.csv')\n\ntrees_df['age'] = (pd.to_datetime('today') - pd.to_datetime(trees_df['date'])).dt.days\n\nowners = st.sidebar.multiselect(\n label='Select Tree Caretaker',\n options=trees_df['caretaker'].unique()\n)\n\n\n\nst.title(\"San Francisco Trees\")\n\nst.write('This app analyses trees in San Francisco using'\n' a dataset kindly provided by SF DPW')\n\nst.write('The current analysis is of trees owned by {}'.\nformat(owners))\n\nif owners:\n tree_df = trees_df[trees_df['caretaker'].isin(owners)]\n\n\n#define multiple columns, add two graphs\ncol1, col2 = st.columns(2)\n\nwith col1:\n st.write('Trees by Width')\n fig_1, ax_1 = plt.subplots()\n ax_1 = sns.histplot(trees_df['dbh'])\n plt.xlabel('Tree Width')\n st.pyplot(fig_1)\n\nwith col2:\n st.write('Trees by Age')\n fig_2, ax_2 = plt.subplots()\n ax_2 = sns.histplot(trees_df['age'])\n plt.xlabel('Age (Days)')\n st.pyplot(fig_2)\n\nst.write('Trees by Location')\ntrees_df = trees_df.dropna(subset=['longitude', 'latitude'])\ntrees_df = trees_df.sample(n = 1000, replace=True)\nst.map(trees_df)\n\n\n\n\n\n\n\n\n\n","repo_name":"ramshadows/Streamlit_Playground","sub_path":"pretty_trees/pretty_tree_demo2.py","file_name":"pretty_tree_demo2.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8415706554","text":"'''\t\n@Author: Aishwarya\n@Date: 2021-11-27 \n@Title : Cncatenate string\n'''\n#########################################################################################\nif __name__=='__main__':\n try:\n print(\"----------------------\")\n string=input(\"Enter a word or a sentence :\")\n s=\"ing\"\n s1=\"ly\"\n if len(string)>=3 and s not in string:\n str1=string+s\n print(str1)\n elif len(string)>=3 and s in string: \n str2=string+s1\n print(str2)\n \n else:\n print(\"Please give longer word\") \n print()\n except Exception as e:\n print(\"Error :\",e)","repo_name":"AishRahatal/PythonDataStructure","sub_path":"String/Addsubstring.py","file_name":"Addsubstring.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29065155389","text":"import time\r\nimport random\r\nimport os\r\nos.system(\"cls\")\r\nMovie_list = [\"Shrek\",\"Finding Dory\",\"Inside Out\",\"Minions\",\"Brave\",\"Big Hero 6\",\"Wall E\",\"Ratatouille\",\"Toy Story 3\",\"Monsters University\",\"How to Train Your Dragon\",\"The Good Dinosaur\"]\r\nMovie_details = {}\r\ndef converter(movie):\r\n Answer = []\r\n for i in movie:\r\n if i == \" \":\r\n Answer.append(\" \")\r\n else:\r\n Answer.append(\"_\")\r\n return Answer\r\n\r\ndef printing(Answer):\r\n print(Movie_list)\r\n print(\"\\t****************************************\")\r\n print(\"\\t\\tWelcome to Hangman..!!\")\r\n print(\"\\t****************************************\")\r\n time.sleep(1)\r\n print(\" The Movie is an animated movie\")\r\n for i in range(len(Answer)):\r\n if i == 0:\r\n print(\"\\t\",Answer[i],end=\"\")\r\n else:\r\n print(Answer[i],end=\"\")\r\n\r\nMovie_ = random.choice(Movie_list)\r\n#movie_ = \"Shrek hi\"\r\nmovie = Movie_.lower()\r\n\r\nAnswer = converter(movie)\r\n\r\n#print(Answer)\r\n\r\nchances = 3\r\n\r\nwhile(\"_\" in Answer):\r\n printing(Answer)\r\n temp = 0\r\n temp2 = 0\r\n optn = input(\"\\nEnter your choice: \")\r\n optn = optn.lower()\r\n if len(optn) == 1:\r\n for i in range(len(movie)):\r\n if movie[i] == optn:\r\n Answer[i] = optn\r\n temp = 1\r\n else:\r\n if movie.count(optn) != 1:\r\n temp2 = 1\r\n if temp2 == 1:\r\n temp = 0\r\n else:\r\n for i in optn:\r\n for j in range(len(movie)):\r\n if movie[j] == i:\r\n Answer[j] = i\r\n temp = 1\r\n \r\n if temp == 0:\r\n print(\"Wrong choice..!!\")\r\n chances -= 1\r\n print(\"You have\",chances,\"chances left\")\r\n time.sleep(1)\r\n if chances == 0:\r\n time.sleep(1)\r\n break\r\n \r\n os.system(\"cls\")\r\n \r\n# break\r\nif chances == 0:\r\n os.system(\"cls\")\r\n print(\"You lost..!!!\")\r\n \r\nelse:\r\n print(\"The movie was:\",Movie_)\r\n print(\"You are the winner..!!!\")\r\n time.sleep(2)\r\nexit_ = input(\"Enter to exit\")\r\n","repo_name":"ParagDasAssam/Python-Small-Games","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5584605289","text":"#!/bin/python3\n\nimport os\nimport sys\nfrom collections import deque\n\n\nclass Node:\n def __init__(self, nodeId):\n self.nodeId = nodeId\n\n\nclass Graph:\n def __init__(self):\n self.nodeIdToNeighbors = {}\n\n def addNode(self, nodeID):\n self.nodeIdToNeighbors[nodeID] = set()\n\n def addEdge(self, startNodeId, endNodeID):\n self.nodeIdToNeighbors[startNodeId].add(endNodeID)\n\n def BFS(self, startNodeId):\n queue = deque()\n startNode = Node(startNodeId)\n queue.appendleft(startNode)\n visitedSet = set()\n\n while queue:\n currentNode = queue.pop()\n visitedSet.add(currentNode.nodeId)\n neighborNodes = self.nodeIdToNeighbors[currentNode.nodeId]\n for neighborId in neighborNodes:\n if neighborId not in visitedSet:\n neighborNode = Node(neighborId)\n queue.appendleft(neighborNode)\n visitedSet.add(neighborNode.nodeId)\n\n return visitedSet\n\n def getSmallestAndBiggestComponentsSizes(self):\n initialNodesList = list(self.nodeIdToNeighbors.keys())\n\n biggestComponent = 0\n smallestComponent = sys.maxsize\n\n while initialNodesList:\n currentlyVisitedNodeIDsSet = self.BFS(initialNodesList[0])\n currentlyVisitedNodesNum = len(currentlyVisitedNodeIDsSet)\n\n if currentlyVisitedNodesNum > biggestComponent:\n biggestComponent = currentlyVisitedNodesNum\n\n if 1 < currentlyVisitedNodesNum < smallestComponent:\n smallestComponent = currentlyVisitedNodesNum\n\n for item in currentlyVisitedNodeIDsSet:\n if item in initialNodesList:\n initialNodesList.remove(item)\n\n return [smallestComponent, biggestComponent]\n\n\ndef main():\n sys.stdin = open(\"ComponentsInAGraph_input.txt\")\n\n n = int(input())\n gb = []\n\n for _ in range(n):\n gb.append(list(map(int, input().rstrip().split())))\n\n allNodesInEdgesList = []\n for subList in gb:\n allNodesInEdgesList.extend(subList)\n\n graph = Graph()\n for nodeId in allNodesInEdgesList:\n graph.addNode(nodeId)\n\n for graphEdges in gb:\n graph.addEdge(graphEdges[0], graphEdges[1])\n graph.addEdge(graphEdges[1], graphEdges[0])\n\n smallestAndBiggestComponentList = graph.getSmallestAndBiggestComponentsSizes()\n print(smallestAndBiggestComponentList[0], smallestAndBiggestComponentList[1])\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"zseen/hackerrank-challenges","sub_path":"Python/GraphTheory/ComponentsInAGraph/ComponentsInAGraph.py","file_name":"ComponentsInAGraph.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74474313763","text":"alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\ncontinue_promt = True\nfrom caesar_cipher_art import logo\nwhile continue_promt == True:\n print(logo)\n while True:\n direction = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\n if direction not in (\"encode\",\"decode\"):\n print(\"Invalid input, try again.\")\n continue\n else: break\n\n text = input(\"Type your message:\\n\").lower()\n shift = int(input(\"Type the shift number:\\n\"))\n\n def caesar_text(start_text, shift_amount, cipher_direction):\n cipher_text = \"\"\n if cipher_direction == \"decode\":\n shift_amount *= -1\n for each_letter in start_text:\n if each_letter in alphabet:\n original_position = alphabet.index(each_letter)\n new_position = (original_position + shift_amount) \n while new_position > 25:\n new_position -= 26\n while new_position < 0:\n new_position += 26 \n new_letter = alphabet[new_position]\n else:\n new_letter = each_letter\n cipher_text += new_letter\n print(f\"The {cipher_direction}d text is {cipher_text}\")\n\n caesar_text(start_text=text, shift_amount=shift,cipher_direction=direction)\n while True:\n continue_question = input(\"Type 'yes' if you want to go again. Otherwise type 'no'. \").lower()\n if continue_question not in (\"yes\",\"no\"):\n print(\"Invalid input, try again.\")\n continue\n else: break\n if continue_question == \"no\":\n continue_promt = False","repo_name":"bb013/Python-Learning-General","sub_path":"100 Days of Code/Section 8/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73947253605","text":"n = int(input())\nans = []\n\ni = 1\nwhile i ** 2 <= n:\n if n % i == 0:\n print(i)\n if n // i != i:\n ans.append(n//i)\n i += 1\nfor i in ans[::-1]:\n print(i)\n\nif i == 1:\n print(1)\n","repo_name":"Haruka0522/AtCoder","sub_path":"ABC/ABC180-C.py","file_name":"ABC180-C.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42130372318","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nimport json\nimport time\nimport datetime\nimport requests\n\n# Telegram Bot 相關設定\nTELEGRAM_BOT_TOKEN = \"YOUR_TOKEN\"\nTELEGRAM_CHAT_ID = \"CAHT_ID\"\n\n# 設定 Chrome 選項\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_experimental_option(\"detach\", True)\n\n# 設定使用者代理,使程式更像真人\nuser_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36\"\nchrome_options.add_argument(f\"user-agent={user_agent}\")\n\n# 呼叫 Chrome 的套件並設定選項\nPATH = \"chromedriver.exe\" ### You have to download this first\ndriver = webdriver.Chrome(PATH, options=chrome_options)\n\n# 開啟指定網頁\ndriver.get(\"https://www.vmware.com/security/advisories.html\")\n\n# 最大化視窗\ndriver.maximize_window()\n\n# 等待結果載入\nWebDriverWait(driver, 30).until(\n EC.presence_of_element_located((By.ID, 'table_id'))\n)\n\n# 定位主要列表\ntab_pane = driver.find_element(By.XPATH, f'/html/body/div[4]/div/div/div[2]/section/div/div/div/div/div[2]/div[5]/table/tbody')\n\n# 點選嚴重度選單,選取\"critical\"\ndriver.find_element(By.XPATH, f'/html/body/div[4]/div/div/div[2]/section/div/div/div/div/div[2]/div[2]/div/div[2]/div[2]/div/button').click()\ndriver.find_element(By.ID, 'chkbox-Critical').click()\n\ntab_pane = driver.find_element(By.XPATH, f'//*[@id=\"table_id\"]/tbody')\n\n# 等待元素載入\ntime.sleep(3)\n\nadvisories = [] # 儲存所有的 Advisory 結果\n\nif tab_pane is not None:\n # 尋找該元素底下的所有具有 \"role=row\" 屬性的元素\n row_elements = tab_pane.find_elements(By.CSS_SELECTOR, '[role=row]')\n\n # 逐一處理每個 row 元素\n for row_element in row_elements:\n # 尋找內部的元素\n details_control = row_element.find_element(By.CLASS_NAME, \"details-control\")\n severity_block = row_element.find_element(By.CLASS_NAME, \"severity-block\")\n synopsis_block = row_element.find_element(By.CLASS_NAME, \"synopsis-block\")\n updated_date_block = row_element.find_element(By.CLASS_NAME, \"updatedDate-block\")\n\n # 取得內容及網址\n advisory_id = details_control.text.strip()\n level = severity_block.text.strip()\n description = synopsis_block.text.strip()\n update_date = updated_date_block.text.strip()\n link = details_control.find_element(By.TAG_NAME, \"a\").get_attribute(\"href\")\n\n # 取得當前年份\n current_year = datetime.datetime.now().year\n date_parts = update_date.split('-')\n\n # 解析日期並檢查是否為今年\n if len(date_parts) == 3:\n year = int(date_parts[2])\n # 僅印出今年的\n if year == current_year:\n advisory_info = {\n \"Advisory ID\": advisory_id,\n \"網址\": link,\n \"Level\": level,\n \"Description\": description,\n \"Updated Date\": update_date\n }\n advisories.append(advisory_info)\nelse:\n print(\"找不到元素\")\n\n# 關閉瀏覽器\ndriver.quit()\n\n# 格式化訊息\nmessage = \"======= VMware Advisories =======\\n\\n\"\nfor advisory in advisories:\n message += f\"Advisory ID: {advisory['Advisory ID']}\\n\"\n message += f\"Updated Date: {advisory['Updated Date']}\\n\"\n message += f\"Level: {advisory['Level']}\\n\"\n message += f\"網址: {advisory['網址']}\\n\"\n message += f\"Description: {advisory['Description']}\\n\\n\"\n \n\n# 透過 Telegram Bot 發送訊息\nurl = f\"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage\"\nparams = {\n \"chat_id\": TELEGRAM_CHAT_ID,\n \"text\": message\n}\nresponse = requests.get(url, params=params)\nif response.status_code == 200:\n print(\"訊息已發送至 Telegram\")\nelse:\n print(\"發送訊息至 Telegram 時發生錯誤\")\n","repo_name":"FoolApe/Python","sub_path":"VMWare-advisories.py","file_name":"VMWare-advisories.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20870659406","text":"import json\nimport os\nimport itertools\nimport random\n\nfrom tqdm import tqdm\nfrom moviepy.editor import VideoFileClip, ImageClip, concatenate_videoclips, AudioFileClip, CompositeVideoClip\n\n\nCLIPS_PATH = r'clips'\n\nwith open('tempo_data.json') as f:\n\tbeat_data = json.load(f)\n\naudio = AudioFileClip(r'assets\\example.mp3')\n\nprint('Reading clips... {}'.format(CLIPS_PATH))\nclips = [VideoFileClip(os.path.join(CLIPS_PATH, x), audio=False) for x in tqdm(os.listdir(CLIPS_PATH))]\n\nsubclips = []\n\nlast_beat = 0\n\nfor beat in tqdm(beat_data[:20]):\n\tclip = random.choice(clips)\n\tstart_point = random.randrange(0, max(1, int(clip.duration) - 1))\n\tsubclips.append(clip.subclip(start_point, start_point + beat - last_beat))\n\tlast_beat = beat\n\n\nprint('Concatanating...')\nfinal_clip = concatenate_videoclips(subclips)\nfinal_clip = final_clip.set_audio(audio)\nfinal_clip = final_clip.subclip(5, 10)\n\nfinal_clip.preview(fps=24)\n\nprint('Writing...')\nfinal_clip.write_videofile(\"my_concatenation.mp4\", fps=24)","repo_name":"ytanay/melodippers","sub_path":"video_editor.py","file_name":"video_editor.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72088008164","text":"def check_intersection(list, list2):\n # intersection = set(list2) & set(list)\n #\n # return tuple(intersection)\n\n\n new_line = {element for element in list if element in list2}\n\n\n\n return tuple(new_line)\n\n\n\nif __name__ == '__main__':\n list1 = [20, 30, 60, 65, 65, 75,65, 80, 85]\n list2 = [42, 30, 30, 80, 65, 68, 88, 95]\n\n print(check_intersection(list1,list2))\n\n\n","repo_name":"KevinEjiofor/python_practice","sub_path":"array/intersection.py","file_name":"intersection.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30982681625","text":"import sys\r\nimport os\r\nimport glob\r\nfrom split_sentence import load_sub, process_text\r\n\r\n\r\ndef main():\r\n dirname: str = sys.argv[1]\r\n\r\n ttmlfiles = glob.glob(f\"{dirname}/**/*.ja.ttml\", recursive=True)\r\n\r\n for file in ttmlfiles:\r\n texts = load_sub(file)\r\n processed_text = process_text(texts)\r\n\r\n name, _ = os.path.splitext(file)\r\n outputname = f\"{name}.txt\"\r\n with open(outputname, encoding=\"utf-8\", mode=\"w\") as f:\r\n f.write(\"\\n\".join(processed_text))\r\n\r\n print(f\"文字数:{sum(len(s) for s in processed_text)} {outputname}\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"nssuperx/yt-sub-format","sub_path":"format_all_sub_files.py","file_name":"format_all_sub_files.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"75307715684","text":"from typing import Dict, List\nfrom app.models.entities.comments import Comments\nfrom database.repository import save, delete, commit\n\n\ndef create_comment(data: Dict, garbage_id, cooperative_id=\"\", user_id=\"\") -> Comments or None:\n try:\n return save(Comments(\n message=data.get('message'),\n garbage_id=garbage_id,\n cooperative_id=cooperative_id,\n user_id=user_id,\n active=data.get('active')\n ))\n except (AttributeError, KeyError, TypeError):\n return\n\n\ndef update_comment(comment_id: str, data: Dict) -> Comments:\n comment: Comments = get_comment_by_id(comment_id)\n list_keys = list(data.keys())\n\n comment.message = data.get('message') if data.get('message') else comment.message\n comment.is_coop = data.get('is_coop') if data.get('is_coop') else comment.is_coop\n comment.user_id = data.get('user_id') if data.get('user_id') else comment.user_id\n comment.post_id = data.get('post_id') if list_keys.count('post_id') else comment.post_id\n comment.active = data.get('active') if list_keys.count('active') else comment.active\n\n commit()\n return comment\n\n\ndef delete_comment(comment_id: str) -> Comments:\n comment: Comments = get_comment_by_id(comment_id)\n delete(comment)\n commit()\n return comment\n\n\ndef get_comments() -> List[Comments]:\n list_comment = Comments.query.all()\n return list_comment\n\n\ndef get_comment_by_id(comment_id: str) -> Comments:\n return Comments.query.get(comment_id)\n\n\ndef get_comment_by_garbage_id(garbage_id: str) -> List[Comments]:\n return Comments.query.filter_by(garbage_id=garbage_id).all()\n\n\ndef get_comment_sort_by_up_votes() -> List[Comments]:\n comments = get_comments()\n for comment in comments:\n print(comment)\n","repo_name":"GustavoAV2/EcoHub-Hackathon","sub_path":"app/actions/comments_actions.py","file_name":"comments_actions.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"9808774251","text":"import logging\n\nfrom django.conf import settings\nfrom django.db.models import CharField, Value\nfrom django.db.models.functions import JSONObject\nfrom django.http import HttpResponse\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom drf_spectacular.types import OpenApiTypes\nfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import NotFound, PermissionDenied\nfrom rest_framework.mixins import CreateModelMixin, UpdateModelMixin\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_200_OK, HTTP_201_CREATED\nfrom rest_framework.viewsets import ReadOnlyModelViewSet\nfrom rest_framework_extensions.mixins import DetailSerializerMixin\n\nfrom signals.apps.api.filters import SignalFilterSet\nfrom signals.apps.api.generics.filters import FieldMappingOrderingFilter\nfrom signals.apps.api.generics.pagination import HALPagination, LinkHeaderPaginationForQuerysets\nfrom signals.apps.api.generics.permissions import (\n SignalCreateInitialPermission,\n SignalViewObjectPermission\n)\nfrom signals.apps.api.serializers import (\n AbridgedChildSignalSerializer,\n PrivateSignalSerializerDetail,\n PrivateSignalSerializerList\n)\nfrom signals.apps.api.serializers.email_preview import (\n EmailPreviewPostSerializer,\n EmailPreviewSerializer\n)\nfrom signals.apps.api.serializers.signal_history import HistoryLogHalSerializer\nfrom signals.apps.email_integrations.utils import trigger_mail_action_for_email_preview\nfrom signals.apps.history.models import Log\nfrom signals.apps.services.domain.pdf import PDFSummaryService\nfrom signals.apps.signals.models import Signal\nfrom signals.apps.signals.models.aggregates.json_agg import JSONAgg\nfrom signals.apps.signals.models.functions.asgeojson import AsGeoJSON\nfrom signals.auth.backend import JWTAuthBackend\n\nlogger = logging.getLogger(__name__)\n\n\n@extend_schema_view(\n list=extend_schema(responses={HTTP_200_OK: PrivateSignalSerializerList(many=True)},\n description='List of signals'),\n create=extend_schema(responses={HTTP_201_CREATED: PrivateSignalSerializerList},\n description='Create a new signal'),\n retrieve=extend_schema(responses={HTTP_200_OK: PrivateSignalSerializerDetail},\n description='Retrieve a signal'),\n update=extend_schema(responses={HTTP_200_OK: PrivateSignalSerializerDetail},\n description='Update a signal'),\n partial_update=extend_schema(responses={HTTP_200_OK: PrivateSignalSerializerDetail},\n description='Partial update a signal'),\n)\nclass PrivateSignalViewSet(DetailSerializerMixin, CreateModelMixin, UpdateModelMixin, ReadOnlyModelViewSet):\n \"\"\"Viewset for `Signal` objects in private API\"\"\"\n queryset = Signal.objects.select_related(\n 'location',\n 'status',\n 'category_assignment',\n 'reporter',\n 'priority',\n 'parent',\n 'type_assignment',\n ).prefetch_related(\n 'category_assignment__category__departments',\n 'children',\n 'attachments',\n 'notes',\n 'signal_departments',\n 'user_assignment',\n )\n\n # Geography queryset to reduce the complexity of the query\n geography_queryset = Signal.objects.select_related(\n 'location', # We only need the location for now\n ).filter(\n location__isnull=False # We can only show signals on a map that have a location\n ).only( # No need to select anything else than the id, created and the location for now\n 'id',\n 'created_at',\n 'location'\n ).all()\n\n serializer_class = PrivateSignalSerializerList\n serializer_detail_class = PrivateSignalSerializerDetail\n\n authentication_classes = [JWTAuthBackend]\n permission_classes = (SignalCreateInitialPermission, )\n object_permission_classes = (SignalViewObjectPermission, )\n\n filter_backends = (DjangoFilterBackend, FieldMappingOrderingFilter, )\n filterset_class = SignalFilterSet\n\n ordering = ('-created_at', )\n ordering_fields = (\n 'id',\n 'created_at',\n 'updated_at',\n 'stadsdeel',\n 'sub_category',\n 'main_category',\n 'status',\n 'priority',\n 'address',\n 'assigned_user_email',\n 'area_name',\n )\n ordering_field_mappings = {\n 'id': 'id',\n 'created_at': 'created_at',\n 'updated_at': 'updated_at',\n 'stadsdeel': 'location__stadsdeel',\n 'sub_category': 'category_assignment__category__slug',\n 'main_category': 'category_assignment__category__parent__slug',\n 'status': 'status__state',\n 'priority': 'priority__priority',\n 'address': 'location__address_text',\n 'assigned_user_email': 'user_assignment__user__email',\n 'area_name': 'location__area_name',\n }\n\n http_method_names = ['get', 'post', 'patch', 'head', 'options', 'trace']\n\n def get_queryset(self, *args, **kwargs):\n if self._is_request_to_detail_endpoint():\n return super().get_queryset(*args, **kwargs)\n else:\n qs = super().get_queryset(*args, **kwargs)\n return qs.filter_for_user(user=self.request.user)\n\n def check_object_permissions(self, request, obj):\n for permission_class in self.object_permission_classes:\n permission = permission_class()\n if not permission.has_object_permission(request, self, obj):\n self.permission_denied(\n request, message=getattr(permission, 'message', None)\n )\n\n @extend_schema(\n parameters=[OpenApiParameter('what', OpenApiTypes.STR, description='Filters a specific \"action\"')],\n responses={HTTP_200_OK: HistoryLogHalSerializer(many=True)}\n )\n @action(detail=True, url_path='history', filterset_class=None, filter_backends=(), pagination_class=None)\n def history(self, *args, **kwargs):\n \"\"\"\n History endpoint filterable by action.\n \"\"\"\n signal = self.get_object()\n history_log_qs = signal.history_log.all()\n\n what = self.request.query_params.get('what', None)\n if what:\n action = Log.translate_what_to_action(what)\n content_type = Log.translate_what_to_content_type(what)\n\n # TODO: Fix this properly\n if action == 'RECEIVE' and content_type == 'feedback':\n action = 'CREATE'\n\n history_log_qs = history_log_qs.filter(action__iexact=action, content_type__model__iexact=content_type)\n\n serializer = HistoryLogHalSerializer(history_log_qs, many=True)\n return Response(serializer.data)\n\n @extend_schema(\n responses={\n HTTP_200_OK: {\n 'type': 'object',\n 'properties': {\n 'type': {\n 'type': 'string',\n 'enum': [\n 'FeatureCollection'\n ],\n 'example': 'FeatureCollection'\n },\n 'features': {\n 'type': 'array',\n 'items': {\n 'type': 'object',\n 'properties': {\n 'type': {\n 'type': 'string',\n 'enum': [\n 'Feature'\n ],\n 'example': 'Feature'\n },\n 'geometry': {\n 'type': 'object',\n 'properties': {\n 'type': {\n 'type': 'string',\n 'enum': [\n 'Point'\n ]\n },\n 'coordinates': {\n 'type': 'array',\n 'items': {\n 'type': 'number'\n },\n 'example': [\n 4.890659,\n 52.373069\n ]\n }\n }\n },\n 'properties': {\n 'type': 'object',\n 'properties': {\n 'id': {\n 'type': 'integer',\n 'example': 1\n },\n 'created_at': {\n 'type': 'string',\n 'format': 'date-time',\n 'example': '2023-06-01T00:00:00.000000+00:00'\n }\n }\n }\n }\n }\n }\n }\n }\n },\n description='GeoJSON of all signals',\n )\n @action(detail=False, url_path='geography', filterset_class=SignalFilterSet)\n def geography(self, request):\n \"\"\"\n SIG-3988\n\n To speed up the generation of the GeoJSON we are now skipping DRF serializers and are constructing the response\n in the database using the same type of query as used in the PublicSignalMapViewSet.list method.\n\n However we are not creating a raw query, instead we are creating the query in Django ORM and\n annotating/aggregating the result in the database. This way we keep all the benefits of the SignalFilterSet and\n the 'filter_for_user' functionality AND gain all the performance by skipping DRF and letting the database\n generate the GeoJSON.\n \"\"\"\n # Annotate Signal queryset with GeoJSON features and filter it according\n # to \"Signalen\" project access rules:\n features_qs = self.filter_queryset(\n self.geography_queryset.annotate(\n feature=JSONObject(\n type=Value('Feature', output_field=CharField()),\n geometry=AsGeoJSON('location__geometrie'),\n properties=JSONObject(\n id='id',\n created_at='created_at',\n ),\n )\n ).filter_for_user(\n user=request.user\n )\n )\n\n # Paginate our queryset and turn it into a GeoJSON feature collection:\n headers = []\n feature_collection = {'type': 'FeatureCollection', 'features': []}\n paginator = LinkHeaderPaginationForQuerysets(page_query_param='geopage',\n page_size=settings.SIGNALS_API_GEO_PAGINATE_BY)\n page_qs = paginator.paginate_queryset(features_qs, self.request, view=self)\n\n if page_qs is not None:\n features = page_qs.aggregate(features=JSONAgg('feature'))\n feature_collection.update(features)\n headers = paginator.get_pagination_headers()\n\n return Response(feature_collection, headers=headers)\n\n @extend_schema(responses={HTTP_200_OK: AbridgedChildSignalSerializer(many=True)})\n @action(detail=True, url_path='children', filterset_class=None, filter_backends=())\n def children(self, request, pk=None):\n \"\"\"Show abridged version of child signals for a given parent signal.\"\"\"\n # Based on a user's department a signal may not be accessible.\n signal_exists = Signal.objects.filter(id=pk).exists()\n signal_accessible = Signal.objects.filter_for_user(request.user).filter(id=pk).exists()\n\n if signal_exists and not signal_accessible:\n raise PermissionDenied()\n\n # return an HTTP 404 if we ask for a child signal's children.\n signal = self.get_object()\n if signal.is_child:\n raise NotFound(detail=f'Signal {pk} has no children, it itself is a child signal.')\n elif not signal.is_parent:\n raise NotFound(detail=f'Signal {pk} has no children.')\n\n # Return the child signals for a parent signal in an abridged version\n # of the usual serialization.\n paginator = HALPagination()\n child_qs = signal.children.all()\n page = paginator.paginate_queryset(child_qs, self.request, view=self)\n\n if page is not None:\n serializer = AbridgedChildSignalSerializer(page, many=True, context=self.get_serializer_context())\n return paginator.get_paginated_response(serializer.data)\n\n serializer = AbridgedChildSignalSerializer(child_qs, many=True, context=self.get_serializer_context())\n return Response(serializer.data)\n\n @extend_schema(responses={HTTP_200_OK: EmailPreviewSerializer},\n description='Render the email preview before transitioning to a specific status.')\n @action(detail=True, url_path='email/preview', methods=['POST', ], serializer_class=EmailPreviewPostSerializer,\n serializer_detail_class=EmailPreviewPostSerializer, filterset_class=None)\n def email_preview(self, request, *args, **kwargs):\n \"\"\"\n Render the email preview before transitioning to a specific status.\n Required parameters: status\n Optional parameters: text\n \"\"\"\n signal = self.get_object()\n\n post_serializer = self.get_serializer(data=request.data)\n post_serializer.is_valid(raise_exception=True)\n\n status = post_serializer.validated_data.pop('status', None)\n text = post_serializer.validated_data.pop('text', None)\n email_override = post_serializer.validated_data.pop('email_override', None)\n\n status_data = {'state': status, 'text': text, 'send_email': True, 'email_override': email_override}\n subject, _, html_message = trigger_mail_action_for_email_preview(signal, status_data)\n\n context = self.get_serializer_context()\n context.update({'email_preview': {'subject': subject, 'html_message': html_message}})\n\n serializer = EmailPreviewSerializer(signal, context=context)\n return Response(serializer.data)\n\n @extend_schema(responses={HTTP_200_OK: None}, description='Download the Signal as a PDF.')\n @action(detail=True, url_path='pdf', methods=['GET'], url_name='pdf-download')\n def pdf(self, request, *args, **kwargs):\n signal = self.get_object()\n user = request.user\n\n pdf = PDFSummaryService.get_pdf(signal, user)\n pdf_filename = f'{signal.get_id_display()}.pdf'\n return HttpResponse(pdf, content_type='application/pdf', headers={\n 'Content-Disposition': f'attachment;filename=\"{pdf_filename}\"'\n })\n\n def create(self, request, *args, **kwargs):\n if isinstance(request.data, (list, )):\n serializer = self.get_serializer(data=request.data, many=True)\n else:\n serializer = self.get_serializer(data=request.data)\n\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=HTTP_201_CREATED, headers=headers)\n","repo_name":"Amsterdam/signals","sub_path":"app/signals/apps/api/views/signals/private/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":15827,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"} +{"seq_id":"11607117167","text":"#\n# @lc app=leetcode id=1888 lang=python\n#\n# [1888] Minimum Number of Flips to Make the Binary String Alternating\n#\n\n# @lc code=start\nclass Solution(object):\n def minFlips(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n # Brute O(n^2)\n\n # LEN = len(s)\n\n # patt1 = (\"01\" * LEN) + (\"0\" if LEN % 2 == 1 else \"\")\n # patt2 = (\"10\" * LEN) + (\"1\" if LEN % 2 == 1 else \"\")\n\n # p1Count = 10**5\n # p2Count = 10**5\n\n # i = 0\n # while i < LEN:\n # j = 0\n\n # currP1Count = 0\n # currP2Count = 0\n\n # while j < LEN:\n\n # if s[j] != patt1[j]:\n # currP1Count += 1\n\n # if s[j] != patt2[j]:\n # currP2Count += 1\n\n # j += 1\n # s = s[1:] + s[0]\n\n # p1Count = min(currP1Count, p1Count)\n # p2Count = min(currP2Count, p2Count)\n\n # i += 1\n\n # return min(p1Count, p2Count)\n\n # Optimized : O(n)\n LEN = len(s)\n\n patt1 = \"01\" * LEN\n patt2 = \"10\" * LEN\n\n patt1Count = 0\n patt2Count = 0\n\n i = 0\n while i < LEN:\n if patt1[i] != s[i]:\n patt1Count += 1\n\n if patt2[i] != s[i]:\n patt2Count += 1\n\n i += 1\n\n currPatt1Count = patt1Count\n currPatt2Count = patt2Count\n\n s += s[:LEN-1]\n\n print(s, patt1, patt2)\n\n i = LEN\n while i < len(s):\n\n # print(s[i], patt1[i], patt2[i])\n\n currPatt1Count -= 1\n currPatt2Count -= 1\n\n if s[i] != patt1[i]:\n currPatt1Count += 1\n\n if s[i] != patt2[i]:\n currPatt2Count += 1\n\n print(currPatt1Count, currPatt2Count)\n\n patt1Count = min(patt1Count, currPatt1Count)\n patt2Count = min(patt2Count, currPatt2Count)\n\n i += 1\n\n print(patt1Count, patt2Count)\n\n # LEN = len(s)\n # if len(set(s)) == 1:\n # return LEN // 2\n\n # if LEN == 2:\n # return 0\n\n # i = 0\n # while s[0] == s[1] and i < LEN:\n # s = s[1:] + s[0]\n # i += 1\n\n # count = 0\n # i = 2\n # while i <= LEN - 2:\n\n # if s[i] != (s[0] + s[1])[0]:\n # count += 1\n\n # if s[i+1] != (s[0] + s[1])[1]:\n # count += 1\n\n # i += 2\n\n # return count\n\n\n# @lc code=end\n# print(Solution().minFlips(\"01001001101\"))\n# print(Solution().minFlips(\"101\"))\nprint(Solution().minFlips(\"111000\"))\n","repo_name":"aryanjain28/Striver","sub_path":"1888.minimum-number-of-flips-to-make-the-binary-string-alternating.py","file_name":"1888.minimum-number-of-flips-to-make-the-binary-string-alternating.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10692076100","text":"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.parameter import Parameter\nfrom torchvision.models import inception_v3\n\nimport numpy as np\n\nfrom const import BOS, PAD\n\n\nclass Attention(nn.Module):\n def __init__(self, hsz):\n super().__init__()\n\n self.hsz = hsz\n\n self.sigma = nn.Linear(hsz, hsz)\n self.beta = nn.Linear(hsz, hsz, bias=False)\n\n self._reset_parameters()\n\n def _reset_parameters(self):\n stdv = 1. / math.sqrt(self.hsz)\n\n self.sigma.weight.data.uniform_(-stdv, stdv)\n self.beta.weight.data.uniform_(-stdv, stdv)\n\n def forward(self, hiddens, hidden):\n hiddens.append(hidden)\n sigma = torch.tanh(self.sigma(hidden))\n _hiddens = torch.stack(hiddens, dim=1)\n _betas = torch.sum(torch.exp(self.beta(_hiddens)), dim=1)\n beta = torch.exp(self.beta(sigma)) / _betas\n\n return (beta * hidden).unsqueeze(1)\n\n\nclass Actor(nn.Module):\n def __init__(self, vocab_size, dec_hsz, rnn_layers, bsz, max_len, dropout, use_cuda):\n super().__init__()\n\n self.torch = torch.cuda if use_cuda else torch\n self.dec_hsz = dec_hsz\n self.rnn_layers = rnn_layers\n self.bsz = bsz\n self.max_len = max_len\n self.vocab_size = vocab_size\n self.dropout = dropout\n\n self.enc = inception_v3(True)\n self.enc_out = nn.Linear(1000, dec_hsz)\n self.lookup_table = nn.Embedding(vocab_size, dec_hsz, padding_idx=PAD)\n self.rnn = nn.LSTM(dec_hsz + dec_hsz, dec_hsz, rnn_layers,\n batch_first=True,\n dropout=dropout)\n self.attn = Attention(dec_hsz)\n self.out = nn.Linear(self.dec_hsz, vocab_size)\n\n self._reset_parameters()\n\n def forward(self, hidden, labels=None):\n word = Variable(self.torch.LongTensor([[BOS]] * self.bsz))\n emb_enc = self.lookup_table(word)\n hiddens = [hidden[0].squeeze()]\n attn = torch.transpose(hidden[0], 0, 1)\n outputs, words = [], []\n\n for i in range(self.max_len):\n _, hidden = self.rnn(torch.cat([emb_enc, attn], -1), hidden)\n h_state = F.dropout(hidden[0], p=self.dropout)\n\n props = F.log_softmax(self.out(h_state[-1]), dim=-1)\n attn = self.attn(hiddens, h_state[-1])\n\n if labels is not None:\n emb_enc = self.lookup_table(labels[:, i]).unsqueeze(1)\n\n else:\n _props = props.data.clone().exp()\n word = Variable(_props.multinomial(1), requires_grad=False)\n words.append(word)\n\n emb_enc = self.lookup_table(word)\n\n outputs.append(props.unsqueeze(1))\n\n if labels is not None:\n return torch.cat(outputs, 1)\n\n else:\n return torch.cat(outputs, 1), torch.cat(words, 1)\n\n def encode(self, imgs):\n if self.training:\n enc = self.enc(imgs)[0]\n else:\n enc = self.enc(imgs)\n enc = self.enc_out(enc)\n return enc\n\n def feed_enc(self, enc):\n weight = next(self.parameters()).data\n c = Variable(weight.new(\n self.rnn_layers, self.bsz, self.dec_hsz).zero_())\n\n h = Variable(enc.data.\n unsqueeze(0).expand(self.rnn_layers, *enc.size()))\n\n return (h.contiguous(), c.contiguous())\n\n def _reset_parameters(self):\n stdv = 1. / math.sqrt(self.vocab_size)\n\n self.enc_out.weight.data.uniform_(-stdv, stdv)\n self.lookup_table.weight.data.uniform_(-stdv, stdv)\n self.out.weight.data.uniform_(-stdv, stdv)\n\n for p in self.enc.parameters():\n p.requires_grad = False\n\n def get_trainable_parameters(self):\n return filter(lambda m: m.requires_grad, self.parameters())\n\n\nclass Critic(nn.Module):\n def __init__(self, vocab_size, dec_hsz, rnn_layers, bsz, max_len, dropout, use_cuda):\n super().__init__()\n\n self.use_cuda = use_cuda\n self.dec_hsz = dec_hsz\n self.rnn_layers = rnn_layers\n self.bsz = bsz\n self.max_len = max_len\n self.vocab_size = vocab_size\n self.dropout = dropout\n\n self.lookup_table = nn.Embedding(vocab_size, dec_hsz, padding_idx=PAD)\n self.rnn = nn.LSTM(self.dec_hsz,\n self.dec_hsz,\n self.rnn_layers,\n batch_first=True,\n dropout=dropout)\n self.value = nn.Linear(self.dec_hsz, 1)\n\n self._reset_parameters()\n\n def feed_enc(self, enc):\n weight = next(self.parameters()).data\n c = Variable(weight.new(\n self.rnn_layers, self.bsz, self.dec_hsz).zero_())\n\n h = Variable(enc.data.\n unsqueeze(0).expand(self.rnn_layers, *enc.size()))\n return (h.contiguous(), c.contiguous())\n\n def forward(self, inputs, hidden):\n emb_enc = self.lookup_table(inputs.clone()[:, :-1])\n _, out = self.rnn(emb_enc, hidden)\n out = F.dropout(out[0][-1], p=self.dropout)\n\n return self.value(out).squeeze()\n\n def _reset_parameters(self):\n stdv = 1. / math.sqrt(self.vocab_size)\n\n self.lookup_table.weight.data.uniform_(-stdv, stdv)\n self.value.weight.data.uniform_(-stdv, stdv)\n","repo_name":"ne7ermore/torch-light","sub_path":"Image-Cap/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","stars":526,"dataset":"github-code","pt":"52"} +{"seq_id":"32044677309","text":"# Problem Name: Carvans \n# Problem Code: CARVANS\n\nfor _ in range(int(input())):\n n = int(input())\n cars = list(map(int, input().split()))\n r = 1\n for j in range(1, n):\n if cars[j] < cars[j - 1]:\n r += 1\n else:\n cars[j] = cars[j - 1]\n print(r)","repo_name":"Dhrumil-Zion/Competitive-Programming-Basics","sub_path":"Codechef/Complexity Analysis + Basics Warm Up/Carvans.py","file_name":"Carvans.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27791440297","text":"from __future__ import print_function\nimport socket\nimport sys\nimport time\nimport json\nimport calendar\nimport time \n\nHOST, PORT = socket.gethostname(), 9331\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nNmsg = 10\ntry:\n Nmsg = int(sys.argv[1])\nexcept:\n pass\n\nprint('num messages ', Nmsg)\nnum_retransmits = 0\nseed = calendar.timegm(time.gmtime())\nwhile(num_retransmits < Nmsg):\n num_retransmits += 1\n seed += 1\n data = {'read_vector_bytes': 133206046, \n 'site_name': 'T2_US_Purdue', \n 'read_vector_count_average': 21.411799999999999, \n 'user_dn': '/DC=ch/DC=cern/OU=Organic Units/OU=Users/CN=USER%s'% seed, \n 'file_lfn': '/store/fake/file_%s.root'% seed, \n 'read_bytes': 148607872, \n 'file_size': 27502730289, \n 'read_single_average': 3793.5500000000002, \n 'client_host': 'rossmann-a251', \n 'read_vector_average': 7835650.0, \n 'read_vector_sigma': 7081190.0, \n 'server_host': 'cmshdp-d019', \n 'read_vector_operations': 17, \n 'read_single_bytes': 15401826, \n 'app_info': 'something', \n 'client_domain': 'rcac.purdue.edu', \n 'start_time': 1395960729, \n 'read_vector_count_sigma': 56.063099999999999, \n 'read_single_sigma': 84703.899999999994, \n 'server_domain': 'rcac.purdue.edu', \n 'read_single_operations': 4060, \n 'read_bytes_at_close': 148607872, \n 'end_time': 1395960959, \n 'fallback': '-', \n 'unique_id': '60DC3A6D-02B6-E311-B2BD-0002C90B73D8-0%s'% seed\n } \n \n client_socket.sendto(json.dumps(data), (HOST, PORT))\nprint(\"sent all messages\")\n","repo_name":"dmwm/DDM","sub_path":"DataPopularity/popdb.cmssw/collector/lib/dashboard/popdb-cmssw/test/udpClient.py","file_name":"udpClient.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"18033026914","text":"import time\nfrom appium import webdriver\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom os import path\n\nCUR_DIR = path.dirname(path.abspath(__file__))\nAPP = path.join(CUR_DIR, 'TheApp.apk')\nAPPIUM = 'http://127.0.0.1:4723/wd/hub'\n\n\nCAPS = {\n 'platformName': 'Android',\n # 'platformVersion': '',\n 'deviceName': 'Android Emulator',\n # 'deviceName': 'Pixel 6',\n 'automationName': 'UIAutomator2',\n 'app': APP,\n}\n\n\ndriver = webdriver.Remote(\n command_executor=APPIUM, desired_capabilities=CAPS\n)\ntry:\n # wait = WebDriverWait(driver, 10)\n time.sleep(4)\n\n\nfinally:\n driver.quit()\n","repo_name":"Son1cPower/Python-Appium-Android","sub_path":"mobile/source_android.py","file_name":"source_android.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":"37003697781","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport argparse\nimport shutil\nimport subprocess\n\n# Python 2/3 support\nfrom six.moves import input, urllib\nfrom email.utils import parseaddr\n\n# Point this to a tag with the latest code.\nTEMPLATE_VERSION_TAG = '1.7'\n\n# Make sure you have Django 1.8.x installed in the appropriate Python version\n# you are using (either pip3 or pip).\n\n\ndef user_input():\n email = input('Please enter the email: ')\n\n email_is_valid = parseaddr(email)\n if '@' not in email_is_valid[1]:\n raise ValueError(\"Please enter a valid email\")\n\n domain = input('Please enter the domain: ')\n\n if not email or not domain:\n raise ValueError(\"Please enter the email and domain\")\n\n return email, domain\n\n\ndef fetch_latest_template(project_name, email, domain):\n tag_version = TEMPLATE_VERSION_TAG\n print('Using VERSION: {tag_version}'.format(**locals()))\n extension = 'py, yml, conf, sh'\n\n # Download forked django-startproject.py from\n # https://github.com/alfredo/django-startproject-plus in order to pass\n # extra-context variables.\n urllib.request.urlretrieve(\n 'https://raw.githubusercontent.com/psychok7/django-startproject-plus/'\n 'master/django-startproject.py', 'django-startproject.py'\n )\n\n template = (\n 'https://github.com/psychok7/django-yadpt-starter/archive/'\n 'v{tag_version}.zip'.format(**locals())\n )\n\n if sys.version_info >= (3, 0):\n python_version = 'python3'\n else:\n python_version = 'python'\n\n extra_context = '{\"EMAIL\": \"' + email + '\", \"DOMAIN\": \"' + domain + '\"}'\n\n generate_template = (\n '{python_version} django-startproject.py {project_name} '\n '--template={template} '\n '--extension=\"{extension}\" --settings=_config.dummy_settings'.format(**locals())\n )\n generate_template += \" --extra_context='\" + extra_context + \"'\"\n\n print('generate_template: {generate_template}'.format(**locals()))\n\n subprocess.call([generate_template], shell=True)\n\n\ndef generate_cerbot_certs(project_name, email, domain):\n generate_certs = (\n 'docker run -it --rm -v {project_name}_https_certs:/etc/letsencrypt '\n '-p 80:80 -p 443:443 palobo/certbot:1.1 certonly -t -n --standalone '\n '-d {domain} -m {email} --agree-tos'.format(**locals())\n )\n print('generate_certs: ', generate_certs)\n\n subprocess.call([generate_certs], shell=True)\n\n\ndef _cleanup(project_name):\n print('Cleaning...')\n if not os.path.exists(project_name):\n raise ValueError('Something went wrong')\n else:\n # Copy the sub-folder inside /minimal one level up and delete\n # unnecessary files.\n os.rename(project_name, 'temp')\n os.chdir('temp')\n os.rename('minimal', project_name)\n os.chdir('../')\n shutil.move('temp/' + project_name + '/', '.')\n shutil.rmtree('temp/')\n shutil.rmtree(project_name + '/_config/')\n os.remove(project_name + '/django-yadpt-starter.py')\n\n if os.path.exists('django-startproject.py'):\n os.remove('django-startproject.py')\n\n return True\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Django Project Template Startup Script')\n parser.add_argument(\n '-e', '--environment', help='Environment', required=True)\n parser.add_argument('project_name', nargs='?', type=str)\n\n args = vars(parser.parse_args())\n\n project_name = args['project_name']\n\n if args['environment'] == 'production' or args['environment'] == 'staging':\n email, domain = user_input()\n fetch_latest_template(\n project_name=project_name, email=email, domain=domain)\n _cleanup(project_name=project_name)\n print('Generating HTTPS certs...')\n print('Please ensure this machine owns the domain.')\n generate_cerbot_certs(\n project_name=project_name, email=email, domain=domain)\n\n elif args['environment'] == 'dev':\n tag_version = TEMPLATE_VERSION_TAG\n extension = 'py, yml, conf, sh'\n template = (\n 'https://github.com/psychok7/django-yadpt-starter/archive/'\n 'v{tag_version}.zip'.format(**locals())\n )\n generate_template = (\n 'django-admin startproject {project_name} --template={template} '\n '--extension=\"{extension}\"'.format(**locals())\n )\n\n print('generate_template dev: {generate_template}'.format(**locals()))\n\n subprocess.call([generate_template], shell=True)\n\n _cleanup(project_name=project_name)\n\n else:\n raise ValueError(\"environment not allowed\")\n","repo_name":"psychok7/django-yadpt-starter","sub_path":"minimal/django-yadpt-starter.py","file_name":"django-yadpt-starter.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"52"} +{"seq_id":"31150639669","text":"#!python\n\n\"\"\"Script for extracting mutational paths from BEAST ``.trees`` files.\n\nExtracts mutational paths from BEAST Markov Jumps ``.trees`` files.\n\nAlso creates a merged tree without branch annotations.\n\nWritten by Jesse Bloom.\n\"\"\"\n\n\nimport re\nimport os\nimport sys\nimport mutpath.sequtils\nimport mutpath.io\nimport mutpath.tree\nimport mutpath.parse_tree\n\n\n\ndef main():\n \"\"\"Main body of script.\"\"\"\n #\n # output is written to out, currently set to standard out\n out = sys.stdout\n statusinterval = 100 # print update after processing this many trees\n #\n # Read input file and parse arguments\n args = sys.argv[1 : ]\n if len(args) != 1:\n raise IOError(\"Script must be called with exactly one argument specifying the input file name.\")\n infilename = sys.argv[1]\n if not os.path.isfile(infilename):\n raise IOError(\"Failed to find infile %s\" % infilename)\n d = mutpath.io.ParseInfile(open(infilename))\n out.write('\\nRead input argments from %s\\n' % infilename)\n out.write('Read the following key / value pairs:\\n')\n for (key, value) in d.iteritems():\n out.write(\"%s %s\\n\" % (key, value))\n intreefiles = mutpath.io.ParseFileList(d, 'intreefiles')\n burnin = mutpath.io.ParseIntValue(d, 'burnin')\n mergedtreesfile = mutpath.io.ParseStringValue(d, 'mergedtreesfile')\n mutpathsfile = mutpath.io.ParseStringValue(d, 'mutpathsfile')\n fastafile = mutpath.io.ParseFileList(d, 'fastafile')\n if len(fastafile) != 1:\n raise IOError(\"More than one fastafile specified\")\n fastafile = fastafile[0]\n headers_seqs = dict([(header, seq.upper()) for (header, seq) in mutpath.sequtils.Read(fastafile)])\n seqtype = mutpath.io.ParseStringValue(d, 'seqtype').upper()\n if seqtype == 'DNA':\n allowambiguousmismatches = set(['-', 'N', 'R', 'W', 'Y', 'M', 'K', 'S', 'H', 'B', 'V', 'D'])\n elif seqtype == 'PROTEIN':\n allowambiguousmismatches = set(['-', 'X'])\n else:\n raise ValueError(\"Invalid seqtype of %s\" % seqtype)\n startseq = mutpath.io.ParseStringValue(d, 'startseq')\n endseq = mutpath.io.ParseStringValue(d, 'endseq')\n #\n # begin looping over trees\n # bamatch matches branch mutation annotations\n bamatch = re.compile('\\[\\&(history\\_all|h)\\=\\{\\{\\d+\\,\\d+\\.\\d+,[A-z],[A-z]\\}(\\,\\{\\d+\\,\\d+\\.\\d+,[A-z],[A-z]\\})*\\}\\]')\n treefilepreface = '' # information before trees lines\n ntreelines = 0\n out.write(\"\\nAll of the non-burnin trees will be written (without branch mutation annotations) to %s.\\n\" % mergedtreesfile)\n out.write(\"\\nAll of the non-burnin mutational paths will be written to %s.\\n\" % mutpathsfile)\n trees_out = open(mergedtreesfile, 'w')\n paths_out = open(mutpathsfile, 'w')\n ipath = 0\n for intreefile in intreefiles:\n out.write(\"\\nReading trees from %s...\\n\" % intreefile)\n numbers_to_strains = mutpath.parse_tree.ReadTreeTranslateBlock(intreefile)\n assert len(numbers_to_strains) == len(headers_seqs), \"%d in numbers_to_strains, %d in headers_seqs\" % (len(numbers_to_strains), len(headers_seqs))\n tipnames_dict = {}\n for (number, strain) in numbers_to_strains.iteritems():\n try:\n seq = headers_seqs[strain]\n except KeyError:\n raise ValueError(\"fastafile did not specify sequence for %s\" % strain)\n tipnames_dict[number] = {'strain':strain, 'sequence':seq}\n treestarted = fileended = False\n preface = []\n itree = 0\n for line in open(intreefile):\n if fileended:\n raise IOError(\"file %s has and 'End;' line before the end.\" % intreefile)\n if (not treestarted) and line[ : 10] == 'tree STATE':\n treestarted = True\n if treestarted:\n if line[ : 4] == 'End;':\n fileended = True\n continue\n itree += 1\n if itree < burnin:\n pass # burn in\n elif itree == burnin:\n out.write(\"Finished reading %d burnin trees from %s...\\n\" % (burnin, intreefile))\n out.flush()\n else:\n if (itree - burnin) % statusinterval == 0:\n out.write(\"Processed %d trees from %s...\\n\" % (itree - burnin, intreefile))\n out.flush()\n ntreelines += 1\n trees_out.write(re.sub(bamatch, '', line))\n # get the Newick string with mutations annotated by history_all key in branch_info \n newickstring = mutpath.parse_tree.GetTreeString(line.replace('&h=', '&history_all='))\n # create tree with 'strain' and 'sequence' keys in info attribute\n t = mutpath.tree.Tree(newickstring, tipnames_dict=tipnames_dict)\n mutpath.parse_tree.AssignMutations(t.GetRoot())\n mutpath.parse_tree.BuildSeqsFromMutsAndTips(t, allowambiguousmismatches)\n mutpath.tree.AssignTimes(t)\n path = mutpath.parse_tree.TraceMutationPath(t, startseq, endseq)\n ipath += 1\n paths_out.write(\"MUTPATH %d\\n%s\\n\\n\" % (ipath, path))\n else:\n preface.append(line)\n if not treefilepreface:\n trees_out.write(line)\n preface = ''.join(preface)\n if treefilepreface:\n if treefilepreface != preface:\n raise IOError(\"The preface lines in %s do not match that from the first *.tree file\" % intreefile)\n else:\n treefilepreface = preface\n if not fileended:\n raise IOError(\"Failed to find an 'End;' line at the end of %s\" % intreefile)\n out.write(\"\\nRead a total of %d trees from the %d intreefiles after removing the first %d burnin trees from each file.\\n\" % (ntreelines, len(intreefiles), burnin))\n\n trees_out.write('End;')\n trees_out.close()\n paths_out.close()\n out.write(\"\\nWrote %d trees to mergedtreesfile %s.\" % (ntreelines, mergedtreesfile))\n out.write(\"\\nWrote %d paths to mutpathsfile %s.\" % (ntreelines, mutpathsfile))\n out.write('\\nScript is complete.\\n')\n\n \n\nif __name__ == '__main__':\n main() # run the script\n","repo_name":"jbloom/mutpath","sub_path":"scripts/mutpath_get_paths.py","file_name":"mutpath_get_paths.py","file_ext":"py","file_size_in_byte":6287,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"43046578337","text":"import tensorflow\nfrom tensorflow.keras.models import load_model\nimport json\nimport numpy as np\nimport random\nimport pickle\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\nnltk.download('punkt')\nnltk.download('wordnet')\n\nintents = json.loads(open('intents.json', encoding='utf-8').read())\nwords = pickle.load(open('vocab.pkl', 'rb'))\nclasses = pickle.load(open('classes.pkl', 'rb'))\nmodel = load_model('chatbot_LogicLane.h5')\nlemmatizer = WordNetLemmatizer()\n\n\ndef clean_up_sentence(sentence: str) -> list:\n \"\"\"Function takes a string, it performs tokenization and lemmatization and then returns list of words\"\"\"\n sent_words = word_tokenize(sentence)\n sent_words = [lemmatizer.lemmatize(word).lower() for word in sent_words]\n return sent_words\n\ndef bag_of_words(sentence: str) -> np.array:\n \"\"\"Function takes a string, cleans it up and tranforms it in to a vector that can be classified by our model and returns it as np.array\"\"\"\n sent_words = clean_up_sentence(sentence)\n bag = [0] * len(words)\n for w in sent_words:\n for i, word in enumerate(words):\n if word == w:\n bag[i] = 1\n return np.array(bag)\n\ndef predict_class(sentence: str) -> list:\n \"\"\"Function takes string, transforms it into a vector, sends it to the model for prediction and returns list of predictions\"\"\"\n bow = bag_of_words(sentence)\n res = model.predict(np.array([bow]))[0]\n \n results = [[i, r] for i, r in enumerate(res)] \n results.sort(key=lambda x: x[1], reverse=True)\n return_list = []\n for r in results:\n return_list.append({'intent':classes[r[0]], 'probability': str(r[1])}) \n return return_list\n\ndef get_response(intents_list: list, intents_json: json) -> str:\n \"\"\"Function takes list of predictions, induces the intent from predictions and compares with the intents in json file. \n When it founds a match for the intent than it returns a response in string type \"\"\"\n tag = intents_list[0]['intent']\n probability = float(intents_list[0]['probability'])\n list_of_intents = intents_json['intents']\n for i in list_of_intents:\n if i['tag'] == tag and probability > 0.5:\n result=random.choice(i['responses'])\n break\n else:\n result = \"Sorry I dont understand. Can you please rephrase your question?\"\n return result\n\n\n\nprint(\"Chatbot Online......to end converastion write: /exit\")\nwhile True:\n message = input(\"\") \n \n if message == \"/exit\":\n break \n ints = predict_class(message)\n res = get_response(ints, intents)\n print(\"LogicLaneBot: \" + res)\n\n \n\nprint(\"DONE\")","repo_name":"IgorJonjic/LogicLaneBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24228451997","text":"#!/usr/bin/python3\n\"\"\"\ndefines the route /states\n\"\"\"\nfrom flask import Flask, render_template\nfrom models import storage\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef teardown(self):\n \"\"\"\n closes db session\n \"\"\"\n storage.close()\n\n\n@app.route('/states/', strict_slashes=False)\ndef states():\n \"\"\"route to all states\"\"\"\n states = storage.all('State').values()\n return render_template('9-states.html', states=states)\n\n\n@app.route('/states/', strict_slashes=False)\ndef states_by_id(id):\n \"\"\"displays a state with it's cities\"\"\"\n states = storage.all('State')\n unique_state = None\n for state in states.values():\n if state.id == id:\n unique_state = state\n break\n if unique_state:\n return render_template('9-states.html', state=unique_state)\n else:\n return render_template('9-states.html', error='Not Found!')\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"Tonyeseh/AirBnB_clone_v2","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"4311398704","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QMessageBox\nfrom crudClass import CRUD\nimport sqlite3\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(597, 536)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)\n self.tabWidget.setObjectName(\"tabWidget\")\n self.tab = QtWidgets.QWidget()\n self.tab.setObjectName(\"tab\")\n self.gridLayout = QtWidgets.QGridLayout(self.tab)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.lineEdit_Search = QtWidgets.QLineEdit(self.tab)\n self.lineEdit_Search.setObjectName(\"lineEdit_Search\")\n self.horizontalLayout_2.addWidget(self.lineEdit_Search)\n # Align text to center in LineEdit\n self.lineEdit_Search.setAlignment(QtCore.Qt.AlignCenter)\n self.comboBox_search = QtWidgets.QComboBox(self.tab)\n self.comboBox_search.setObjectName(\"comboBox_search\")\n self.comboBox_search.addItem(\"\")\n self.comboBox_search.addItem(\"\")\n self.comboBox_search.addItem(\"\")\n self.comboBox_search.addItem(\"\")\n self.comboBox_search.addItem(\"\")\n self.comboBox_search.addItem(\"\")\n self.horizontalLayout_2.addWidget(self.comboBox_search)\n# Search Button\n self.pushButton_Search = QtWidgets.QPushButton(self.tab)\n self.pushButton_Search.setObjectName(\"pushButton_Search\")\n self.horizontalLayout_2.addWidget(self.pushButton_Search)\n self.pushButton_Search.clicked.connect(self.search_onClick)\n# Load Button\n self.pushButton_Load = QtWidgets.QPushButton(self.tab)\n self.pushButton_Load.setObjectName(\"pushButton_Load\")\n self.pushButton_Load.clicked.connect(self.load_onClick)\n self.horizontalLayout_2.addWidget(self.pushButton_Load)\n self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)\n self.verticalLayout_3 = QtWidgets.QVBoxLayout()\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n self.tableWidget = QtWidgets.QTableWidget(self.tab)\n self.tableWidget.setRowCount(0)\n # Adjust the number of columns below\n self.tableWidget.setColumnCount(12)\n self.tableWidget.setObjectName(\"tableWidget\")\n # Below Sets the table header above each column \n self.tableWidget.setHorizontalHeaderLabels([\"ID\",\"First Name\",\"Last Name\",\"Email\",\"Phone\",\n \"Address Line 1\", \"Address Line 2\", \"Address Line 2\",\n \"Town/City\", \"Postcode\",\"Company\",\"Detail\"])\n \n self.verticalLayout_3.addWidget(self.tableWidget)\n self.gridLayout.addLayout(self.verticalLayout_3, 1, 0, 1, 1)\n self.tabWidget.addTab(self.tab, \"\")\n self.add_customer = QtWidgets.QWidget()\n self.add_customer.setObjectName(\"add_customer\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.add_customer)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.gridLayout_addcust = QtWidgets.QGridLayout()\n self.gridLayout_addcust.setObjectName(\"gridLayout_addcust\")\n \n self.label_last_name = QtWidgets.QLabel(self.add_customer)\n self.label_last_name.setObjectName(\"label_last_name\")\n self.gridLayout_addcust.addWidget(self.label_last_name, 2, 0, 1, 1)\n \n self.lineEdit_firstName = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_firstName.setObjectName(\"lineEdit_firstName\")\n self.gridLayout_addcust.addWidget(self.lineEdit_firstName, 1, 1, 1, 1)\n \n self.label_phone = QtWidgets.QLabel(self.add_customer)\n self.label_phone.setObjectName(\"label_phone\")\n self.gridLayout_addcust.addWidget(self.label_phone, 3, 0, 1, 1)\n \n self.checkBox_add3 = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_add3.setText(\"\")\n self.checkBox_add3.setObjectName(\"checkBox_add3\")\n self.gridLayout_addcust.addWidget(self.checkBox_add3, 8, 2, 1, 1)\n# Update Button\n self.pushButton_update = QtWidgets.QPushButton(self.add_customer)\n self.pushButton_update.setObjectName(\"pushButton_update\")\n self.pushButton_update.clicked.connect(self.update_onClick)\n self.gridLayout_addcust.addWidget(self.pushButton_update, 12, 2, 1, 1)\n \n self.checkBox_Phone = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_Phone.setText(\"\")\n self.checkBox_Phone.setObjectName(\"checkBox_Phone\")\n self.gridLayout_addcust.addWidget(self.checkBox_Phone, 3, 2, 1, 1)\n \n self.label_postcode = QtWidgets.QLabel(self.add_customer)\n self.label_postcode.setObjectName(\"label_postcode\")\n self.gridLayout_addcust.addWidget(self.label_postcode, 10, 0, 1, 1)\n \n self.label_towncity = QtWidgets.QLabel(self.add_customer)\n self.label_towncity.setObjectName(\"label_towncity\")\n self.gridLayout_addcust.addWidget(self.label_towncity, 9, 0, 1, 1)\n \n self.label_address2 = QtWidgets.QLabel(self.add_customer)\n self.label_address2.setObjectName(\"label_address2\")\n self.gridLayout_addcust.addWidget(self.label_address2, 7, 0, 1, 1)\n \n self.checkBox_add2 = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_add2.setText(\"\")\n self.checkBox_add2.setObjectName(\"checkBox_add2\")\n self.gridLayout_addcust.addWidget(self.checkBox_add2, 7, 2, 1, 1)\n# Add Customer Button\n self.pushButton_addCustomer = QtWidgets.QPushButton(self.add_customer)\n self.pushButton_addCustomer.setObjectName(\"pushButton_addCustomer\")\n self.pushButton_addCustomer.clicked.connect(self.add_onClick)\n self.gridLayout_addcust.addWidget(self.pushButton_addCustomer, 12, 1, 1, 1)\n \n self.lineEdit_lastName = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_lastName.setObjectName(\"lineEdit_lastName\")\n self.gridLayout_addcust.addWidget(self.lineEdit_lastName, 2, 1, 1, 1)\n \n self.lineEdit_phone = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_phone.setObjectName(\"lineEdit_phone\")\n self.gridLayout_addcust.addWidget(self.lineEdit_phone, 3, 1, 1, 1)\n \n self.lineEdit_id = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_id.setObjectName(\"lineEdit_id\")\n self.gridLayout_addcust.addWidget(self.lineEdit_id, 0, 1, 1, 1)\n self.label_first_name = QtWidgets.QLabel(self.add_customer)\n self.label_first_name.setObjectName(\"label_first_name\")\n self.gridLayout_addcust.addWidget(self.label_first_name, 1, 0, 1, 1)\n self.label_cust_id = QtWidgets.QLabel(self.add_customer)\n self.label_cust_id.setObjectName(\"label_cust_id\")\n self.gridLayout_addcust.addWidget(self.label_cust_id, 0, 0, 1, 1)\n self.checkBox_lastName = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_lastName.setText(\"\")\n self.checkBox_lastName.setObjectName(\"checkBox_lastName\")\n self.gridLayout_addcust.addWidget(self.checkBox_lastName, 2, 2, 1, 1)\n self.label_email = QtWidgets.QLabel(self.add_customer)\n self.label_email.setObjectName(\"label_email\")\n self.gridLayout_addcust.addWidget(self.label_email, 4, 0, 1, 1)\n#Company and Detail\n self.label_company = QtWidgets.QLabel(self.add_customer)\n self.label_company.setObjectName(\"label_company\")\n self.gridLayout_addcust.addWidget(self.label_company, 5, 0, 1, 1)\n self.lineEdit_company = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_company.setObjectName(\"lineEdit_company\")\n self.gridLayout_addcust.addWidget(self.lineEdit_company, 5, 1, 1, 1)\n self.checkBox_company = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_company.setText(\"\")\n self.checkBox_company.setObjectName(\"checkBox_company\")\n self.gridLayout_addcust.addWidget(self.checkBox_company, 5, 2, 1, 1)\n \n#Company and Detail\n self.label_detail = QtWidgets.QLabel(self.add_customer)\n self.label_detail.setObjectName(\"label_detail\")\n self.gridLayout_addcust.addWidget(self.label_detail, 11, 0, 1, 1)\n self.lineEdit_detail = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_detail.setObjectName(\"lineEdit_detail\")\n self.gridLayout_addcust.addWidget(self.lineEdit_detail, 11, 1, 1, 1)\n self.checkBox_detail = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_detail.setText(\"\")\n self.checkBox_detail.setObjectName(\"checkBox_detail\")\n self.gridLayout_addcust.addWidget(self.checkBox_detail, 11, 2, 1, 1)\n\n self.lineEdit_postcode = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_postcode.setObjectName(\"lineEdit_postcode\")\n self.gridLayout_addcust.addWidget(self.lineEdit_postcode, 10, 1, 1, 1)\n self.checkBox_postcode = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_postcode.setText(\"\")\n self.checkBox_postcode.setObjectName(\"checkBox_postcode\")\n self.gridLayout_addcust.addWidget(self.checkBox_postcode, 10, 2, 1, 1)\n self.lineEdit_address3 = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_address3.setObjectName(\"lineEdit_address3\")\n self.gridLayout_addcust.addWidget(self.lineEdit_address3, 8, 1, 1, 1)\n self.lineEdit_towncity = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_towncity.setObjectName(\"lineEdit_towncity\")\n self.gridLayout_addcust.addWidget(self.lineEdit_towncity, 9, 1, 1, 1)\n \n self.checkBox_firstName = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_firstName.setEnabled(True)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox_firstName.sizePolicy().hasHeightForWidth())\n self.checkBox_firstName.setSizePolicy(sizePolicy)\n self.checkBox_firstName.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.checkBox_firstName.setText(\"\")\n self.checkBox_firstName.setCheckable(True)\n self.checkBox_firstName.setObjectName(\"checkBox_firstName\")\n self.gridLayout_addcust.addWidget(self.checkBox_firstName, 1, 2, 1, 1)\n self.label_address3 = QtWidgets.QLabel(self.add_customer)\n self.label_address3.setObjectName(\"label_address3\")\n self.gridLayout_addcust.addWidget(self.label_address3, 8, 0, 1, 1)\n \n self.checkBox_towncity = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_towncity.setText(\"\")\n self.checkBox_towncity.setObjectName(\"checkBox_towncity\")\n self.gridLayout_addcust.addWidget(self.checkBox_towncity, 9, 2, 1, 1)\n\n self.checkBox_email = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_email.setText(\"\")\n self.checkBox_email.setObjectName(\"checkBox_email\")\n self.gridLayout_addcust.addWidget(self.checkBox_email, 4, 2, 1, 1)\n self.lineEdit_address1 = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_address1.setObjectName(\"lineEdit_address1\")\n self.gridLayout_addcust.addWidget(self.lineEdit_address1, 6, 1, 1, 1)\n self.label_address1 = QtWidgets.QLabel(self.add_customer)\n self.label_address1.setObjectName(\"label_address1\")\n self.gridLayout_addcust.addWidget(self.label_address1, 6, 0, 1, 1)\n self.lineEdit_address2 = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_address2.setObjectName(\"lineEdit_address2\")\n self.gridLayout_addcust.addWidget(self.lineEdit_address2, 7, 1, 1, 1)\n self.checkBox_add1 = QtWidgets.QCheckBox(self.add_customer)\n self.checkBox_add1.setText(\"\")\n self.checkBox_add1.setObjectName(\"checkBox_add1\")\n self.gridLayout_addcust.addWidget(self.checkBox_add1, 6, 2, 1, 1)\n \n self.lineEdit_email = QtWidgets.QLineEdit(self.add_customer)\n self.lineEdit_email.setObjectName(\"lineEdit_email\")\n self.gridLayout_addcust.addWidget(self.lineEdit_email, 4, 1, 1, 1)\n\n self.label_updateInfo = QtWidgets.QLabel(self.add_customer)\n self.label_updateInfo.setObjectName(\"label_updateInfo\")\n self.gridLayout_addcust.addWidget(self.label_updateInfo, 0, 2, 1, 1)\n self.verticalLayout_2.addLayout(self.gridLayout_addcust)\n self.tabWidget.addTab(self.add_customer, \"\")\n self.delete_cust = QtWidgets.QWidget()\n self.delete_cust.setObjectName(\"delete_cust\")\n self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.delete_cust)\n self.verticalLayout_4.setObjectName(\"verticalLayout_4\")\n self.gridLayout_2 = QtWidgets.QGridLayout()\n self.gridLayout_2.setContentsMargins(0, 0, 0, -1)\n self.gridLayout_2.setObjectName(\"gridLayout_2\")\n# Delete Customer Button\n self.pushButton_delete = QtWidgets.QPushButton(self.delete_cust)\n self.pushButton_delete.setObjectName(\"pushButton_delete\")\n self.pushButton_delete.clicked.connect(self.delete_onClick)\n \n self.gridLayout_2.addWidget(self.pushButton_delete, 3, 1, 1, 1)\n self.lineEdit_id_delete = QtWidgets.QLineEdit(self.delete_cust)\n self.lineEdit_id_delete.setObjectName(\"lineEdit_id_delete\")\n self.lineEdit_id_delete.setAlignment(QtCore.Qt.AlignCenter)\n self.gridLayout_2.addWidget(self.lineEdit_id_delete, 2, 1, 1, 1)\n self.checkBox_confirm = QtWidgets.QCheckBox(self.delete_cust)\n self.checkBox_confirm.setObjectName(\"checkBox_confirm\")\n self.gridLayout_2.addWidget(self.checkBox_confirm, 3, 2, 1, 1)\n self.label_enter_id = QtWidgets.QLabel(self.delete_cust)\n self.label_enter_id.setObjectName(\"label_enter_id\")\n self.gridLayout_2.addWidget(self.label_enter_id, 1, 1, 1, 1)\n spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.gridLayout_2.addItem(spacerItem, 0, 1, 1, 1)\n spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\n self.gridLayout_2.addItem(spacerItem1, 4, 1, 1, 1)\n self.verticalLayout_4.addLayout(self.gridLayout_2)\n self.tabWidget.addTab(self.delete_cust, \"\")\n self.verticalLayout.addWidget(self.tabWidget)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 597, 22))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.tabWidget.setCurrentIndex(0)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Little Black Book\"))\n self.comboBox_search.setItemText(0, _translate(\"MainWindow\", \"ID\"))\n self.comboBox_search.setItemText(1, _translate(\"MainWindow\", \"First Name\"))\n self.comboBox_search.setItemText(2, _translate(\"MainWindow\", \"Last Name\"))\n self.comboBox_search.setItemText(3, _translate(\"MainWindow\", \"Email\"))\n self.comboBox_search.setItemText(4, _translate(\"MainWindow\", \"Postcode\"))\n self.comboBox_search.setItemText(5, _translate(\"MainWindow\", \"Company\"))\n \n self.pushButton_Search.setText(_translate(\"MainWindow\", \"Search\"))\n self.pushButton_Load.setText(_translate(\"MainWindow\", \"Load\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate(\"MainWindow\", \"Main\"))\n self.label_last_name.setText(_translate(\"MainWindow\", \"Last Name:\"))\n self.label_phone.setText(_translate(\"MainWindow\", \"Phone Number:\"))\n self.pushButton_update.setText(_translate(\"MainWindow\", \"Update\"))\n self.label_postcode.setText(_translate(\"MainWindow\", \"Postcode\"))\n self.label_towncity.setText(_translate(\"MainWindow\", \"Town/City\"))\n self.label_address2.setText(_translate(\"MainWindow\", \"Address Line 2:\"))\n self.pushButton_addCustomer.setText(_translate(\"MainWindow\", \"Add Contact\"))\n self.label_first_name.setText(_translate(\"MainWindow\", \"First Name:\"))\n self.label_cust_id.setText(_translate(\"MainWindow\", \"Contact ID:\"))\n self.label_email.setText(_translate(\"MainWindow\", \"Email:\"))\n # WORKING ON NOW\n self.label_company.setText(_translate(\"MainWindow\", \"Company:\"))\n self.label_detail.setText(_translate(\"MainWindow\", \"Detail:\"))\n \n \n \n self.label_address3.setText(_translate(\"MainWindow\", \"Address Line 3:\"))\n self.label_address1.setText(_translate(\"MainWindow\", \"Address Line 1:\"))\n self.label_updateInfo.setText(_translate(\"MainWindow\", \"Enter ID & Select For Update\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.add_customer), _translate(\"MainWindow\", \"Add Contact\"))\n self.pushButton_delete.setText(_translate(\"MainWindow\", \"Delete\"))\n self.checkBox_confirm.setText(_translate(\"MainWindow\", \"Tick to Confirm before Delete\"))\n self.label_enter_id.setText(_translate(\"MainWindow\", \"Enter ID:\"))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.delete_cust), _translate(\"MainWindow\", \"Delete Contact\"))\n\n# Connections and Functions\n\n def add_onClick(self):\n if self.lineEdit_id.text() == \"\":\n return self.show_popup('Must Enter ID')\n \n file = CRUD('database.db')\n try:\n file.create_customerTable()\n except:\n try:\n cust_id = int(self.lineEdit_id.text())\n\n f_name = self.checkIfEmpty(self.lineEdit_firstName.text())\n l_name = self.checkIfEmpty(self.lineEdit_lastName.text())\n phone = self.checkIfEmpty(self.lineEdit_phone.text())\n email = self.checkIfEmpty(self.lineEdit_email.text())\n add1 = self.checkIfEmpty(self.lineEdit_address1.text())\n add2 = self.checkIfEmpty(self.lineEdit_address2.text())\n add3 = self.checkIfEmpty(self.lineEdit_address3.text())\n tcity = self.checkIfEmpty(self.lineEdit_towncity.text())\n postcode = self.checkIfEmpty(self.lineEdit_postcode.text())\n company = self.checkIfEmpty(self.lineEdit_company.text())\n detail = self.checkIfEmpty(self.lineEdit_detail.text())\n file.insert_customer(cust_id,f_name,l_name,email,phone,add1,add2,add3,tcity,postcode,company, detail)\n self._clear_afterClick()\n self.show_popup(\"Details Added Successfully\")\n except:\n self.show_popup(\"Id Already Used\")\n \n def delete_onClick(self):\n if self.checkBox_confirm.isChecked() != True:\n return self.show_popup('Please tick and confirm you want to delete')\n \n if self.lineEdit_id_delete.text() == \"\":\n return self.show_popup('Invalid Entry!')\n \n else:\n file = CRUD('database.db')\n file.create_connection()\n cust_id = self.lineEdit_id_delete.text()\n file.delete_table('contact',cust_id)\n self.lineEdit_id_delete.clear()\n self.checkBox_confirm.setCheckState(False) # Set the checkbox to untick\n self.show_popup('Delete Successful')\n \n \n def search_onClick(self):\n if self.lineEdit_Search.text() == \"\":\n return self.show_popup(\"Enter in Search\")\n comboSelect = self.checkComboBox(self.comboBox_search.currentText())\n searchValue = self.searchCheck(self.lineEdit_Search.text())\n conn = sqlite3.connect('database.db')\n c = conn.cursor()\n try:\n query = \"SELECT * FROM contact WHERE {} LIKE {}\".format(comboSelect,searchValue)\n #query = \"SELECT * FROM contact WHERE cust_id LIKE 1\"\n print(query)\n result = c.execute(query)\n self.tableWidget.setRowCount(0)\n for row_num, row_data in enumerate(result):\n self.tableWidget.insertRow(row_num)\n for col_num, data in enumerate(row_data):\n self.tableWidget.setItem(row_num, col_num,QtWidgets.QTableWidgetItem(str(data)))\n conn.close()\n except:\n self.show_popup('No Data')\n \n \n def update_onClick(self):\n try:\n file = CRUD('database.db')\n file.create_connection()\n cust_id = self.lineEdit_id.text()\n if cust_id == \"\":\n return self.show_popup('Enter ID To Update')\n # I Placed the checkbox and the lineEdit in an array so that I can loop through and confirm True or False\n check_arr = [(self.checkBox_firstName.isChecked(),'first_name', self.lineEdit_firstName.text()),\n (self.checkBox_lastName.isChecked(), 'last_name',self.lineEdit_lastName.text()),\n (self.checkBox_Phone.isChecked(), 'phone',self.lineEdit_phone.text()),\n (self.checkBox_email.isChecked(), 'email',self.lineEdit_email.text()),\n (self.checkBox_company.isChecked(), 'company',self.lineEdit_company.text()),\n (self.checkBox_add1.isChecked(), 'address1',self.lineEdit_address1.text()),\n (self.checkBox_add2.isChecked(), 'address2',self.lineEdit_address2.text()),\n (self.checkBox_add3.isChecked(), 'address3',self.lineEdit_address3.text()),\n (self.checkBox_towncity.isChecked(), 'towncity',self.lineEdit_towncity.text()),\n (self.checkBox_postcode.isChecked(), 'postcode',self.lineEdit_postcode.text()),\n (self.checkBox_detail.isChecked(), 'detail',self.lineEdit_detail.text())]\n \n # Loop through checkBox\n falseBoxCheck = 11\n for check in check_arr:\n if check[0] != True:\n falseBoxCheck -= 1\n else:\n file.update_table('contact',check[1],check[2],cust_id)\n if falseBoxCheck == 0:\n self.show_popup('Update Failed')\n else: \n self.show_popup('Update Successful')\n self._clear_afterClick()\n except:\n pass\n \n \n \n \n def load_onClick(self):\n conn = sqlite3.connect('database.db')\n c = conn.cursor()\n try:\n query = \"SELECT * FROM contact\"\n result = c.execute(query)\n self.tableWidget.setRowCount(0)\n for row_num, row_data in enumerate(result):\n self.tableWidget.insertRow(row_num)\n for col_num, data in enumerate(row_data):\n self.tableWidget.setItem(row_num, col_num,QtWidgets.QTableWidgetItem(str(data)))\n conn.close()\n except:\n self.show_popup('No Data')\n # Popup for warning messages\n def show_popup(self, message):\n msg = QMessageBox()\n msg.setWindowTitle('test')\n msg.setText(message)\n msg.exec_()\n \n \n def _clear_afterClick(self):\n self.lineEdit_id.clear()\n self.lineEdit_firstName.clear()\n self.checkBox_firstName.setCheckState(False)\n self.lineEdit_lastName.clear()\n self.checkBox_lastName.setCheckState(False)\n self.lineEdit_phone.clear()\n self.checkBox_Phone.setCheckState(False)\n self.lineEdit_email.clear()\n self.checkBox_email.setCheckState(False)\n self.lineEdit_company.clear()\n self.checkBox_company.setCheckState(False)\n self.lineEdit_detail.clear()\n self.checkBox_detail.setCheckState(False)\n \n self.lineEdit_address1.clear()\n self.checkBox_add1.setCheckState(False)\n self.lineEdit_address2.clear()\n self.checkBox_add2.setCheckState(False)\n self.lineEdit_address3.clear()\n self.checkBox_add3.setCheckState(False)\n self.lineEdit_towncity.clear()\n self.checkBox_towncity.setCheckState(False)\n self.lineEdit_postcode.clear()\n self.checkBox_postcode.setCheckState(False)\n \n def checkIfEmpty(self,var):\n if var == \"\":\n return \"Null\"\n return var\n # Converts the retrieved select from combo to column format\n def checkComboBox(self, select):\n choice = {\"ID\":\"cust_id\",\n \"First Name\":\"first_name\",\n \"Last Name\":\"last_name\",\n \"Email\":\"email\",\n \"Postcode\":\"postcode\",\n \"Company\":\"company\"}\n if select == \"ID\":\n return choice[select]\n else:\n return str(choice[select])\n \n def searchCheck(self,data):\n if type(data) == type(0):\n return data\n return \"'\" + data + \"%'\"\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","repo_name":"karlduggan/LittleBlackBookApp","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":25998,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"14306559249","text":"import os\nimport pprint\n# import openpyxl\nfrom openpyxl import load_workbook\n\ndocDir = r'C:\\Users\\rkeenan\\OneDrive - Aurora Cooperative\\Documents\\2020 Tableau Updates\\Al Perry'\n\nharvestWriteFile = (\n r'C:\\Users\\rkeenan\\OneDrive - Aurora Cooperative\\Documents\\2020 Tableau Updates\\Al Perry\\Test Plot(HARVEST).txt', 'w')\n\nreadFile = r'C:\\Users\\rkeenan\\OneDrive - Aurora Cooperative\\Documents\\2020 Tableau Updates\\Al Perry\\2020 Aaron Franson Test Plot.xlsx'\n\nwb = load_workbook(readFile, data_only=True)\nharvestSheet = wb['HARVEST FORM']\n\n\ndef topHarvestInfo():\n GROWER_NAME = harvestSheet['C3'].value\n GROWER_CITY = harvestSheet['C4'].value\n COUNTY = harvestSheet['C5'].value\n ACE_LOCATION = harvestSheet['C6'].value\n STATED_PLOT_ON = harvestSheet['C7'].value\n FLAT_LOCATION = harvestSheet['C8'].value\n GPS_LATITUDE = harvestSheet['C9'].value\n FUNGICIDE = harvestSheet['C10'].value\n if FUNGICIDE != None:\n FUNGICIDE = FUNGICIDE\n else:\n FUNGICIDE = \"None\"\n HARVEST_DATE = harvestSheet['C11'].value\n if HARVEST_DATE != None:\n HARVEST_DATE = HARVEST_DATE\n else:\n HARVEST_DATE = \"None\"\n CROP = harvestSheet['H3'].value\n PLANTING_DATE = harvestSheet['H4'].value\n SEEDING_RATE = harvestSheet['H5'].value\n PLANTING_DEPTH_IN = harvestSheet['H6'].value\n PLANTER_TYPE = harvestSheet['H7'].value\n ROW_WIDTH = harvestSheet['H8'].value\n GPS_LONGITUDE = harvestSheet['H9'].value\n HERBICIDE = harvestSheet['H10'].value\n if HERBICIDE != None:\n HERBICIDE = HERBICIDE\n else:\n HERBICIDE = \"None\"\n COMMODITY_PRICE = harvestSheet['H11'].value\n PLOT_TYPE = harvestSheet['L5'].value\n IRRIGATION_TYPE = harvestSheet['L6'].value\n PREVIOUS_CROP = harvestSheet['L7'].value\n TILLAGE_SYSTEM = harvestSheet['L8'].value\n SOIL_TEXTURE = harvestSheet['L9'].value\n INSECTICIDE_RATE = harvestSheet['L10'].value\n if INSECTICIDE_RATE != None:\n INSECTICIDE_RATE = INSECTICIDE_RATE\n else:\n INSECTICIDE_RATE = \"None\"\n DRYING_COST = harvestSheet['L11'].value\n FORM_TYPE = \"HARVEST FORM\"\n\n f1.write(GROWER_NAME + \"\\t\" + GROWER_CITY + \"\\t\" + COUNTY + \"\\t\" + ACE_LOCATION + \"\\t\" + STATED_PLOT_ON + \"\\t\" + FLAT_LOCATION + \"\\t\" + str(GPS_LATITUDE) + \"\\t\" + FUNGICIDE + \"\\t\" + HARVEST_DATE + \"\\t\" + CROP + \"\\t\" + str(PLANTING_DATE) + \"\\t\" + str(SEEDING_RATE) + \"\\t\" +\n str(PLANTING_DEPTH_IN) + \"\\t\" + PLANTER_TYPE + \"\\t\" + str(ROW_WIDTH) + \"\\t\" + str(GPS_LONGITUDE) + \"\\t\" + HERBICIDE + \"\\t\" + str(COMMODITY_PRICE) + \"\\t\" + PLOT_TYPE + \"\\t\" + IRRIGATION_TYPE + \"\\t\" + PREVIOUS_CROP + \"\\t\" + TILLAGE_SYSTEM + \"\\t\" + SOIL_TEXTURE + \"\\t\" + INSECTICIDE_RATE + \"\\t\" + str(DRYING_COST) + \"\\t\" + FORM_TYPE + \"\\t\")\n\n\ndef bottomHarvestInfo():\n for row in range(17, harvestSheet.max_row + 1):\n BRAND = harvestSheet['A' + str(row)].value\n if BRAND != None:\n BRAND = BRAND\n else:\n BRAND = 'None'\n PRODUCT = harvestSheet['C' + str(row)].value\n if PRODUCT != None:\n PRODUCT = PRODUCT\n else:\n PRODUCT = 'None'\n ROW_LENGTH = harvestSheet['F' + str(row)].value\n if ROW_LENGTH != None:\n ROW_LENGTH = ROW_LENGTH\n else:\n ROW_LENGTH = \"None\"\n WET_WEIGHT = harvestSheet['G' + str(row)].value\n if WET_WEIGHT != None:\n WET_WEIGHT = WET_WEIGHT\n else:\n WET_WEIGHT = \"None\"\n HARVEST_MOISTURE_PCT = harvestSheet['H' + str(row)].value\n if HARVEST_MOISTURE_PCT != None:\n HARVEST_MOISTURE_PCT = HARVEST_MOISTURE_PCT\n else:\n HARVEST_MOISTURE_PCT = \"None\"\n NUM_OF_ROWS = harvestSheet['I' + str(row)].value\n TEST_WEIGHT = harvestSheet['J' + str(row)].value\n if TEST_WEIGHT != None:\n TEST_WEIGHT = TEST_WEIGHT\n else:\n TEST_WEIGHT = \"None\"\n YIELD_PER_ACRE = harvestSheet['K' + str(row)].value\n if YIELD_PER_ACRE != None:\n YIELD_PER_ACRE = YIELD_PER_ACRE\n else:\n YIELD_PER_ACRE = \"None\"\n PCT_OF_PLOT_ADVANTAGE = harvestSheet['L' + str(row)].value\n if PCT_OF_PLOT_ADVANTAGE != None:\n PCT_OF_PLOT_ADVANTAGE = PCT_OF_PLOT_ADVANTAGE\n else:\n PCT_OF_PLOT_ADVANTAGE = \"None\"\n YIELD_PER_ACRE_RANK = harvestSheet['M' + str(row)].value\n if YIELD_PER_ACRE_RANK != None:\n YIELD_PER_ACRE_RANK = YIELD_PER_ACRE_RANK\n else:\n YIELD_PER_ACRE_RANK = \"None\"\n DOLLARS_PER_ACRE_RANK = harvestSheet['N' + str(row)].value\n if DOLLARS_PER_ACRE_RANK != None:\n DOLLARS_PER_ACRE_RANK = DOLLARS_PER_ACRE_RANK\n else:\n DOLLARS_PER_ACRE_RANK = \"None\"\n if ROW_LENGTH != 0 and NUM_OF_ROWS != 0:\n topHarvestInfo()\n f1.write(str(BRAND) + \"\\t\" + str(PRODUCT) + \"\\t\" + str(ROW_LENGTH) +\n \"\\t\" + str(WET_WEIGHT) + \"\\t\" + str(HARVEST_MOISTURE_PCT) + \"\\t\" + str(NUM_OF_ROWS) + \"\\t\" + str(TEST_WEIGHT) + \"\\t\" + str(YIELD_PER_ACRE) + \"\\t\" + str(PCT_OF_PLOT_ADVANTAGE) + \"\\t\" + str(YIELD_PER_ACRE_RANK) + \"\\t\" + str(DOLLARS_PER_ACRE_RANK) + \"\\n\")\n else:\n break\n\n print(\"Your Harvest Form data plot file is done!\")\n\n\nwith open(r'C:\\Users\\rkeenan\\OneDrive - Aurora Cooperative\\Documents\\2020 Tableau Updates\\Al Perry\\Test Plot(HARVEST).txt', 'w') as f1:\n bottomHarvestInfo()\n wb.close()\n","repo_name":"rkeenan-auroracoop/PlotData","sub_path":"Harvest Form.py","file_name":"Harvest Form.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37404375969","text":"import numpy as np\n\ndef run_length_encoder_noob(data, n):\n bit_length = int(np.log2(n+1))\n bol = False\n encoded = \"\"\n count = 0\n i = 0\n while i < len(data):\n if count==n:\n encoded += bin(count)[2:].zfill(bit_length)\n count = 0\n bol = not bol\n elif data[i] != str(int(bol)):\n encoded += bin(count)[2:].zfill(bit_length)\n count = 0\n bol = not bol\n else:\n count += 1\n i += 1\n encoded += bin(count)[2:].zfill(bit_length)\n return encoded\n\ns = \"1111111111111101\"\n\ndef run_length_decoder(data, n):\n bit_length = int(np.log2(n+1))\n bol = False\n decoded = \"\"\n for i in range(0, len(data), bit_length):\n decimal = int(data[i:i+bit_length],2)\n decoded += str(int(bol))*decimal\n bol = not bol\n return decoded\n\nprint(run_length_encoder_noob(s, 7))\nprint(run_length_decoder(run_length_encoder_noob(s, 7),7))","repo_name":"Mafa0987/Mestere-i-vitenskap","sub_path":"Multimedia Signalbehandling/Innlevering 1/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"73651615204","text":"import select\nimport socket\nfrom comm.communication.Communication import Communication\nfrom comm.comm_socket.Socket import Socket\nfrom comm.comm_socket.SocketType import SocketType\nfrom comm.comm_socket.utils import SOCKET_ACCEPT_TIMEOUT_SECONDS\nfrom typing import Optional\n\n\nclass TCPServer:\n def __init__(self, port: int, backlog: int = 5):\n self.port = port # type: int\n self.backlog = backlog # type: int\n self.socket = None # type: Optional[Socket]\n self.socketAcceptTimeout = SOCKET_ACCEPT_TIMEOUT_SECONDS # type: float\n self.initServerSocket()\n\n def cleanup(self):\n self.socket.cleanup()\n self.socket = None\n\n def acceptCommunication(self):\n try:\n read, _, _ = select.select([self.socket.getSocket()], [], [], self.socketAcceptTimeout)\n if read:\n comm = Communication()\n comm.setSocket(SocketType.TCP, self.socket.accept())\n return comm\n except socket.error as se:\n print(\"Socket Exception in Accept Communication:\", se.errno, se.strerror)\n self.initServerSocket()\n return None\n\n def initServerSocket(self):\n if self.socket is not None:\n self.socket.cleanup()\n self.socket.initialize(SocketType.TCP, None, self.port)\n else:\n self.socket = Socket.Socket(SocketType.TCP, None, self.port)\n self.listen()\n\n def listen(self):\n self.socket.getSocket().listen(self.backlog)\n","repo_name":"AndreiCostinescu/Comm","sub_path":"python/comm/communication/TCPServer.py","file_name":"TCPServer.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1308460330","text":"\"\"\"\nAuthor: Sean Strout (sps@cs.rit.edu)\nAuthor: ben k steele (bks@cs.rit.edu)\nAuthor: Amanda Ramos :)\n\nThis class represents the types of metal bars that Greedo can\nstore in his satchel. Each type of bar is a separate Metal\nobject. This module also has routines that work with metals,\ne.g. creation, reading from a file, and sorting based on \nvarious criteria.\n\nLanguage: Python 3\n\"\"\"\n\nfrom ranHW.rit_lib import * # rit_lib class\n\nclass Metal(struct):\n \"\"\"\n Represents a single metal type, composed of:\n :slot name (str): The name of the metal\n :slot totalBars (int): The total number of bars\n :slot weightPerBar (int): The weight of a single bar\n :slot valuePerBar (int): The value of a single bar\n :slot valuePerWeight (float): The value per weight of the metal\n :slot barsTaken (int): The number of bars added to the satchel\n \"\"\"\n _slots=((str, \"name\"),(int, \"totalBars\"),(int, \"weightPerBar\"),(int,\"valuePerBar\"),(float, \"valuePerWeight\"),(int,\"barsTaken\"))\n\n\ndef createMetal(name, totalBars, weightPerBar, valuePerBar):\n \"\"\"\n Create and return a new Metal object.\n :param name (str): The name of the metal\n :param totalBars (int): The total number of bars\n :param weightPerBar (int): The weight of a single bar\n :param valuePerBar (int): The value of a single bar\n :return: A newly initialized Metal object\n :rtype: Metal\n \"\"\"\n return Metal(name,totalBars,weightPerBar,valuePerBar,weightPerBar/valuePerBar,0)\n\ndef readMetals(fileName):\n \"\"\"\n Read the metals from a file whose format is:\n metalName totalBars weightPerBar valuePerBar\n :param fileName (str): The name of the file\n :return: A list of Metal objects\n :rtype: list\n \"\"\"\n lst=[]\n metals=open(fileName)\n for i in metals:\n i=i.split()\n lst.append(createMetal(i[0],int(i[1]),int(i[2]),int(i[3])))\n return lst\n\n\ndef sortMetalsByValuePerBar(metals):\n \"\"\"\n Sort the metals by value per bar using insertion sort. The list of\n metals is modified in place to be ordered by value per bar.\n :param metals (list of Metal): The list of metals\n :return: None\n :rtype: NoneType\n \"\"\"\n for m in range(len(metals)):\n for v in range(m):\n if metals[m].valuePerBar>metals[v].valuePerBar:\n temp=metals[v]\n metals[v]=metals[m]\n metals[m]=temp\n\ndef sortMetalsByValuePerWeight(metals):\n \"\"\"\n Sort the metals by value per weight using insertion sort. The list of\n metals is modified in place to be ordered by value per weight.\n :param metals (list of Metal): The list of metals\n :return: None\n :rtype: NoneType\n \"\"\"\n for m in range(len(metals)):\n for v in range(m):\n if metals[m].valuePerWeight>metals[v].valuePerWeight:\n temp=metals[v]\n metals[v]=metals[m]\n metals[m]=temp\n\ndef printMetals(metals):\n \"\"\"\n Display the metals to standard output.\n :param metals (list of Metal): The list of metals\n :return: None\n :rtype: NoneType\n \"\"\"\n for m in metals:\n print(\"\\t\",m)","repo_name":"SorenRose/Portfolio","sub_path":"Programs/source/source/metal.py","file_name":"metal.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28110038694","text":"# 분할정복\n# 2630번. 색종이 만들기\n\nimport sys\nn = int(sys.stdin.readline())\n\n# 종이 상태 입력 받기\ncolorPaper = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]\n\nwhite = 0\nblue = 0\n\ndef divideAndConquer(x, y, n):\n global blue, white\n sameColor = colorPaper[x][y] # 같은 색인지 확인하기 위한 기준변수\n\n for i in range(x, x + n):\n for j in range(y, y + n):\n if sameColor != colorPaper[i][j]:\n divideAndConquer(x, y, n // 2)\n divideAndConquer(x, y + n // 2, n // 2)\n divideAndConquer(x + n // 2, y, n // 2)\n divideAndConquer(x + n // 2, y + n // 2, n // 2)\n return\n\n if sameColor == 0:\n white += 1\n return\n else:\n blue += 1\n return\n\n\ndivideAndConquer(0, 0, n)\nprint(white)\nprint(blue)\n","repo_name":"SujinKim-sj/BaekJoon-Online-Judge","sub_path":"재귀와분할정복/BOJ_2630.py","file_name":"BOJ_2630.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"1580997681","text":"from collections import defaultdict\n\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n pair_map = defaultdict(int)\n\n for word in words:\n pair_map[word] += 1\n\n pldr_len = 0\n centre_gg = False\n # Distinguish \n for word in words:\n k1 = word\n k2 = word[::-1]\n \n if k1 == k2:\n pldr_len += pair_map[word] //2 *2 *2\n pair_map[word] = pair_map[word] %2\n if not centre_gg and pair_map[word] ==1:\n pldr_len += 2\n centre_gg = True\n else:\n pldr_len += min(pair_map[k1], pair_map[k2]) *2 *2\n pair_map[k1] = 0\n pair_map[k2] = 0\n \n return pldr_len\n ","repo_name":"chienhsiang-hung/LeetCode-Solutions","sub_path":"problems/longest_palindrome_by_concatenating_two_letter_words/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"15264503132","text":"import seaborn\nimport streamlit as st\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport glob, random\nimport matplotlib.image as mpimg\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nimport os\n\n\nCLASS_NAMES = ['Azadirachta Indica (Neem)',\n 'Carissa Carandas (Karanda)',\n 'Ficus Religiosa (Peepal Tree)']\nCLASS_NUMBER = 3\n\nIMAGE_SIZE = (150, 200)\nIMAGE_SHAPE = (150, 200, 3)\n\nSHUFFLE_SIZE = 10000\nBATCH_SIZE = 32\nTRAIN_SPLIT = 0.8\nTEST_SPLIT = 0.2\n# Layout\n\nst.set_page_config(layout=\"wide\")\ninput_col, AI_col = st.columns([1, 2])\ngood_tree = [\"Azadirachta Indica\",\"Carissa Carandas\", \"Ficus Religiosa\"]\n\nrandom_image = []\npick_img = []\n\n\n@st.cache()\ndef loadModel():\n # 1. First we load the datasets\n\n def image_parser(filename, label):\n image_str = tf.io.read_file(filename)\n image_decoded = tf.image.decode_jpeg(image_str, channels=3)\n image = tf.cast(image_decoded, tf.float32)\n image = tf.image.resize(image, IMAGE_SIZE)\n\n return image, label\n\n filenames = []\n labels = []\n df_size = 0\n\n for label_idx in range(len(CLASS_NAMES)):\n path = f'./leaf dataset/{CLASS_NAMES[label_idx]}'\n directory_finames = [os.path.join(path, image_file) for image_file in os.listdir(path)]\n\n filenames = filenames + directory_finames\n labels = labels + [tf.one_hot(label_idx, CLASS_NUMBER) for i in range(0, len(directory_finames))]\n\n print(label_idx, ':', CLASS_NAMES[label_idx], '->', tf.one_hot(label_idx, CLASS_NUMBER))\n\n df_size += len(directory_finames)\n\n dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))\n dataset = dataset.map(image_parser)\n\n dataset = dataset.shuffle(SHUFFLE_SIZE)\n\n train_size = int(TRAIN_SPLIT * df_size)\n\n train = dataset.take(train_size)\n test = dataset.skip(train_size)\n\n train = train.batch(BATCH_SIZE)\n test = test.batch(BATCH_SIZE)\n\n train = train.prefetch(buffer_size=tf.data.AUTOTUNE)\n test = test.prefetch(buffer_size=tf.data.AUTOTUNE)\n\n\n # 2. Create the model\n\n ## inputs and normalize\n inputs = layers.Input(shape=IMAGE_SHAPE)\n image = layers.Lambda(lambda img: img/255)(inputs)\n\n # conv1\n image = layers.Conv2D(32, (3, 3), \n activation='relu', \n kernel_initializer='he_uniform',\n padding='same')(image)\n image = layers.Conv2D(32, (3, 3), \n activation='relu', \n kernel_initializer='he_uniform',\n padding='same')(image)\n image = layers.MaxPooling2D((2, 2))(image)\n\n # conv2\n image = layers.Conv2D(64, (3, 3), \n activation='relu', \n kernel_initializer='he_uniform',\n padding='same')(image)\n image = layers.Conv2D(64, (3, 3), \n activation='relu', \n kernel_initializer='he_uniform',\n padding='same')(image)\n image = layers.MaxPooling2D((2, 2))(image)\n\n # flatten\n image = layers.Flatten()(image)\n\n # fully connected\n image = layers.Dense(128, activation='relu', kernel_initializer='he_uniform')(image)\n outputs = layers.Dense(CLASS_NUMBER, activation='softmax')(image)\n\n\n # 3. Train the model\n\n model = keras.Model(inputs, outputs)\n\n model.compile(\n optimizer=keras.optimizers.Adam(learning_rate=0.001),\n loss=keras.losses.CategoricalCrossentropy(),\n metrics=['accuracy']\n )\n\n model.fit(\n train,\n epochs=10,\n verbose=2,\n validation_data=test\n )\n\n return model\n\n\ndef getModelOutputClass(model, image):\n predictions = model.predict(image)\n\n return CLASS_NAMES[np.argmax(predictions)]\n\n\ndef pickRandImage():\n\ti = 1\n\twhile i < 10:\n\t\tfile_path_type = [\"./leaf dataset/Azadirachta Indica (Neem)/*.jpg\", \"./leaf dataset/Carissa Carandas (Karanda)/*.jpg\", \"./leaf dataset/Ficus Religiosa (Peepal Tree)/*jpg\"]\n\t\timages = glob.glob(random.choice(file_path_type))\n\t\trandom_image.insert(0, random.choice(images))\n\t\ti += 1\n\tpick_img = st.sidebar.radio(\"Which image?\", [x for x in range(1, len(random_image) + 1)])\n\ndef tree(witch_tree):\n if witch_tree == 'A':\n return(good_tree[0])\n if witch_tree == 'C':\n return(good_tree[1])\n if witch_tree == 'F':\n return(good_tree[2])\n\n\ndef main():\n model = loadModel()\n\n with input_col:\n pickRandImage()\n st.header('Input part')\n st.write('Select the picture to test')\n\t\n plt.axis('off')\n fig, ax = plt.subplots(nrows = 3, ncols = 3)\n\n for x in range(3):\n for y in range(3):\n img = mpimg.imread(random_image[y + x * 3])\n ax[x, y].imshow(img)\n #ax[x, y].set_title(y + x * 3 + 1)\n ax[x, y].axis('off')\n ax[x, y].text(0.5,-0.1, y + x * 3 + 1, size=12, ha=\"center\", \n transform=ax[x, y].transAxes)\n st.pyplot(fig)\n\n result = st.button('Test AI')\n\n if result:\n with AI_col:\n\n st.header('Result of the classification')\n st.write('For this picture:')\n st.image(random_image[pick_img - 1], width=200)\n witch_tree = random_image[pick_img - 1][15:16]\n st.write('Our AI deterined this tree:')\n ia_tree = \"\"\n st.write(ia_tree)\n st.write('The real result is :')\n real_tree = tree(witch_tree)\n st.write(real_tree)\n if ia_tree == real_tree:\n st.markdown('

the result is correct

', unsafe_allow_html=True)\n else:\n st.markdown('

the result isn t correct

', unsafe_allow_html=True)\n\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"eliaStrasbourg/deep_learning","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33997950870","text":"\"\"\"Tests for Croston estimator.\"\"\"\nimport numpy as np\nimport pytest\n\nfrom sktime.datasets import load_PBS_dataset\nfrom sktime.forecasting.croston import Croston\n\n\n@pytest.mark.parametrize(\n \"smoothing, fh, r_forecast\",\n [\n (0.1, np.array([10]), 0.8688921),\n (0.5, np.array([5]), 0.6754646),\n (0.05, np.array([15]), 1.405808),\n ],\n)\ndef test_Croston_against_r_implementation(smoothing, fh, r_forecast):\n \"\"\"Test Croston estimator against the R package implementing the same algorithm.\n\n Testing forecasted values estimated by the R package of the Croston's method\n against the Croston method in sktime.\n R code to generate the hardcoded value for fh=10:\n ('PBS_dataset.csv' contains the data from 'load_PBS_dataset()'):\n\n PBS_file <- read.csv(file = '/content/PBS_dataset.csv')[,c('Scripts')]\n y <- ts(PBS_file)\n demand=ts(y)\n forecast <- croston(y,h = 10)\n Output:\n 0.8688921\n \"\"\" # noqa: E501\n y = load_PBS_dataset()\n forecaster = Croston(smoothing)\n forecaster.fit(y)\n y_pred = forecaster.predict(fh=fh)\n np.testing.assert_almost_equal(y_pred, np.full(len(fh), r_forecast), decimal=5)\n","repo_name":"sktime/sktime","sub_path":"sktime/forecasting/tests/test_croston.py","file_name":"test_croston.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":7028,"dataset":"github-code","pt":"52"} +{"seq_id":"27331897017","text":"\"\"\"\n# static dataset test\n\"\"\"\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nimport torch as pt\nimport matplotlib.pyplot as pl\n#from bhmtorch_cpu import BHM2D_PYTORCH\n\ndef getPartitions(cell_max_min, nPartx1, nPartx2):\n \"\"\"\n :param cell_max_min: The size of the entire area\n :param nPartx1: How many partitions along the longitude\n :param nPartx2: How many partitions along the latitude\n :return: a list of all partitions\n \"\"\"\n width = cell_max_min[1] - cell_max_min[0]\n height = cell_max_min[3] - cell_max_min[2]\n cell_max_min_segs = []\n for x in range(nPartx1):\n for y in range(nPartx2):\n seg_i = (cell_max_min[0] + width / nPartx1 * x, cell_max_min[0] + width / nPartx1 * (x + 1), \\\n cell_max_min[2] + height / nPartx2 * y, cell_max_min[2] + height / nPartx2 * (y + 1))\n cell_max_min_segs.append(seg_i)\n\n return cell_max_min_segs\n\ndef load_parameters(case):\n parameters = \\\n {filename: \\\n ( os.path.abspath('../../Datasets/simulated/'+filename),\n (5, 5), #hinge point resolution\n (-100, 100, 0, 100), #area [x1_min, x1_max, x2_min, x2_max] #NOTE: chnaged the range\n None,\n None,\n 0.08, #gamma\n ),\n\n }\n\n return parameters[case]\n\n# Settings\ndtype = pt.float32\ndevice = pt.device(\"cpu\")\n# device = pt.device(\"cuda:0\") # Uncomment this to run on GPU\n\n# Get the filename to read data points from\nfilename = 'static_test1' #input(\"Input file: \")\n\n# Read the file\nfn_train, cell_resolution, cell_max_min, _, _, gamma = load_parameters(filename)\n\n# Partition the environment into to 4 areas\n# TODO: We can parallelize this\ncell_max_min_segments = getPartitions(cell_max_min, 1, 1) #NOTE: this is implemented to segment the environment and do mapping speperately. For now, let's consider that there's only one segment.\n\n# Read data\nprint('\\nReading '+fn_train+'.csv...')\ng = pd.read_csv(fn_train+'.csv', delimiter=', ').values[:, :]\n\n# Filter data\nlayer = g[:,0] <= 100 #NOTE: let's consider time frames < 100\ng = pt.tensor(g[layer, :], dtype=pt.float32)\nX = g[:, 1:3] #NOTE: Previously we've read incorrect columns\ny = g[:, 3].reshape(-1, 1)\n# if pt.cuda.is_available():\n# X = X.cuda()\n# y = y.cuda()\n\ntoPlot = []\ntotalTime = 0\nfor segi in range(len(cell_max_min_segments)):\n print(' Mapping segment {} of {}...'.format(segi+1,len(cell_max_min_segments)))\n cell_max_min = cell_max_min_segments[segi]\n\n bhm_mdl = BHM2D_PYTORCH(gamma=gamma, grid=None, cell_resolution=cell_resolution, cell_max_min=cell_max_min, X=X, nIter=1)\n\n t1 = time.time()\n bhm_mdl.fit(X, y)\n t2 = time.time()\n totalTime += (t2-t1)\n\n # query the model\n q_resolution = 1\n xx, yy= np.meshgrid(np.arange(cell_max_min[0], cell_max_min[1] - 1, q_resolution),\n np.arange(cell_max_min[2], cell_max_min[3] - 1, q_resolution))\n grid = np.hstack((xx.ravel()[:, np.newaxis], yy.ravel()[:, np.newaxis]))\n Xq = pt.tensor(grid, dtype=pt.float32)\n yq = bhm_mdl.predict(Xq)\n toPlot.append((Xq,yq))\nprint(' Total training time={} s'.format(np.round(totalTime, 2)))\n\n# Plot occupancy map\npl.close('all')\npl.figure(figsize=(10,5))\npl.subplot(121)\n# Scatter plot raw data\npl.rcParams['figure.facecolor'] = 'white'\npl.scatter(X[:,0], X[:,1], c=y, s=5, cmap='jet')\npl.subplot(122)\nfor segi in range(len(cell_max_min_segments)):\n ploti = toPlot[segi]\n Xq, yq = ploti[0], ploti[1]\n pl.scatter(Xq[:, 0], Xq[:, 1], c=yq, cmap='jet', s=5, vmin=0, vmax=1)\npl.colorbar()\n#pl.xlim([0,200]); pl.ylim([-100,150])\npl.title(filename)\n#pl.savefig(os.path.abspath('../../Outputs/'+filename+'.png'))\npl.show()\n","repo_name":"julia-lina-tan/multi-robot-bhm","sub_path":"BHM/BHM/pytorch/demo_static_cpu.py","file_name":"demo_static_cpu.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74976400804","text":"# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\ndef solution(S, P, Q):\n # write your code in Python 3.6\n sumC = [0]\n sumG = [0]\n sumT = [0]\n sumA = [0]\n array = []\n for i,key in enumerate(S):\n if key == 'C':\n sumC.append(sumC[i]+1)\n sumG.append(sumG[i])\n sumT.append(sumT[i])\n sumA.append(sumA[i])\n elif key == 'G':\n sumC.append(sumC[i])\n sumG.append(sumG[i]+1)\n sumT.append(sumT[i])\n sumA.append(sumA[i])\n elif key == 'T':\n sumC.append(sumC[i])\n sumG.append(sumG[i])\n sumT.append(sumT[i]+1)\n sumA.append(sumA[i])\n elif key == 'A':\n sumC.append(sumC[i])\n sumG.append(sumG[i])\n sumT.append(sumT[i])\n sumA.append(sumA[i]+1)\n ##print(sumA)\n #print(sumC)\n #print(sumG)\n #print(sumT)\n for i in range(0, len(P)):\n if sumA[P[i]+1] != sumA[Q[i]+1] or sumA[P[i]] != sumA[P[i]+1]:\n array.append(1)\n elif sumC[P[i]+1] != sumC[Q[i]+1] or sumC[P[i]] != sumC[P[i]+1]:\n array.append(2)\n elif sumG[P[i]+1] != sumG[Q[i]+1] or sumG[P[i]] != sumG[P[i]+1]:\n array.append(3)\n else:\n array.append(4)\n #print(array)\n return array\n","repo_name":"False1dol/Codility","sub_path":"GenomicRangeQuery.py","file_name":"GenomicRangeQuery.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":"12505797925","text":"import json\nimport logging\nimport sys\n\nfrom google.appengine.ext import ndb\n\n# TODO(eakuefner): Move these helpers so we don't have to import add_point or\n# add_point_queue directly.\nfrom dashboard import add_histograms\nfrom dashboard import add_point\nfrom dashboard import add_point_queue\nfrom dashboard import find_anomalies\nfrom dashboard import graph_revisions\nfrom dashboard.common import datastore_hooks\nfrom dashboard.common import histogram_helpers\nfrom dashboard.common import request_handler\nfrom dashboard.common import stored_object\nfrom dashboard.common import utils\nfrom dashboard.models import anomaly\nfrom dashboard.models import graph_data\nfrom dashboard.models import histogram\nfrom tracing.value import histogram as histogram_module\nfrom tracing.value import histogram_set\nfrom tracing.value.diagnostics import diagnostic\nfrom tracing.value.diagnostics import diagnostic_ref\nfrom tracing.value.diagnostics import reserved_infos\n\nDIAGNOSTIC_NAMES_TO_ANNOTATION_NAMES = {\n reserved_infos.CHROMIUM_COMMIT_POSITIONS.name: 'r_commit_pos',\n reserved_infos.V8_COMMIT_POSITIONS.name: 'r_v8_commit_pos',\n reserved_infos.CHROMIUM_REVISIONS.name: 'r_chromium',\n reserved_infos.V8_REVISIONS.name: 'r_v8_rev',\n # TODO(eakuefner): Add r_catapult_git to Dashboard revision_info map (see\n # https://github.com/catapult-project/catapult/issues/3545).\n reserved_infos.CATAPULT_REVISIONS.name: 'r_catapult_git',\n reserved_infos.ANGLE_REVISIONS.name: 'r_angle_git',\n reserved_infos.WEBRTC_REVISIONS.name: 'r_webrtc_git',\n reserved_infos.FUCHSIA_GARNET_REVISIONS.name: 'r_fuchsia_garnet_git',\n reserved_infos.FUCHSIA_PERIDOT_REVISIONS.name: 'r_fuchsia_peridot_git',\n reserved_infos.FUCHSIA_TOPAZ_REVISIONS.name: 'r_fuchsia_topaz_git',\n reserved_infos.FUCHSIA_ZIRCON_REVISIONS.name: 'r_fuchsia_zircon_git'\n}\n\n\nclass BadRequestError(Exception):\n pass\n\n\ndef _CheckRequest(condition, msg):\n if not condition:\n raise BadRequestError(msg)\n\n\nclass AddHistogramsQueueHandler(request_handler.RequestHandler):\n \"\"\"Request handler to process a histogram and add it to the datastore.\n\n This request handler is intended to be used only by requests using the\n task queue; it shouldn't be directly from outside.\n \"\"\"\n\n def get(self):\n self.post()\n\n def post(self):\n \"\"\"Adds a single histogram or sparse shared diagnostic to the datastore.\n\n The |data| request parameter can be either a histogram or a sparse shared\n diagnostic; the set of diagnostics that are considered sparse (meaning that\n they don't normally change on every upload for a given benchmark from a\n given bot) is shown in add_histograms.SPARSE_DIAGNOSTIC_TYPES.\n\n See https://goo.gl/lHzea6 for detailed information on the JSON format for\n histograms and diagnostics.\n\n Request parameters:\n data: JSON encoding of a histogram or shared diagnostic.\n revision: a revision, given as an int.\n test_path: the test path to which this diagnostic or histogram should be\n attached.\n \"\"\"\n datastore_hooks.SetPrivilegedRequest()\n\n bot_whitelist_future = stored_object.GetAsync(\n add_point_queue.BOT_WHITELIST_KEY)\n\n params = json.loads(self.request.body)\n\n _PrewarmGets(params)\n\n bot_whitelist = bot_whitelist_future.get_result()\n\n # Roughly, the processing of histograms and the processing of rows can be\n # done in parallel since there are no dependencies.\n\n futures = []\n\n for p in params:\n futures.extend(_ProcessRowAndHistogram(p, bot_whitelist))\n\n ndb.Future.wait_all(futures)\n\n\ndef _GetStoryFromDiagnosticsDict(diagnostics):\n if not diagnostics:\n return None\n\n story_name = diagnostics.get(reserved_infos.STORIES.name)\n if not story_name:\n return None\n\n story_name = diagnostic.Diagnostic.FromDict(story_name)\n if story_name and len(story_name) == 1:\n return story_name.GetOnlyElement()\n return None\n\n\ndef _PrewarmGets(params):\n keys = set()\n\n for p in params:\n test_path = p['test_path']\n path_parts = test_path.split('/')\n\n keys.add(ndb.Key('Master', path_parts[0]))\n keys.add(ndb.Key('Bot', path_parts[1]))\n\n test_parts = path_parts[2:]\n test_key = '%s/%s' % (path_parts[0], path_parts[1])\n for p in test_parts:\n test_key += '/%s' % p\n keys.add(ndb.Key('TestMetadata', test_key))\n\n ndb.get_multi_async(list(keys))\n\n\ndef _ProcessRowAndHistogram(params, bot_whitelist):\n revision = int(params['revision'])\n test_path = params['test_path']\n benchmark_description = params['benchmark_description']\n data_dict = params['data']\n\n logging.info('Processing: %s', test_path)\n\n hist = histogram_module.Histogram.FromDict(data_dict)\n\n if hist.num_values == 0:\n return []\n\n test_path_parts = test_path.split('/')\n master = test_path_parts[0]\n bot = test_path_parts[1]\n benchmark_name = test_path_parts[2]\n histogram_name = test_path_parts[3]\n if len(test_path_parts) > 4:\n rest = '/'.join(test_path_parts[4:])\n else:\n rest = None\n full_test_name = '/'.join(test_path_parts[2:])\n internal_only = add_point_queue.BotInternalOnly(bot, bot_whitelist)\n extra_args = GetUnitArgs(hist.unit)\n\n unescaped_story_name = _GetStoryFromDiagnosticsDict(params.get('diagnostics'))\n\n # TDOO(eakuefner): Populate benchmark_description once it appears in\n # diagnostics.\n # https://github.com/catapult-project/catapult/issues/4096\n parent_test = add_point_queue.GetOrCreateAncestors(\n master, bot, full_test_name, internal_only=internal_only,\n unescaped_story_name=unescaped_story_name,\n benchmark_description=benchmark_description, **extra_args)\n test_key = parent_test.key\n\n statistics_scalars = hist.statistics_scalars\n legacy_parent_tests = {}\n\n # TODO(#4213): Stop doing this.\n if histogram_helpers.IsLegacyBenchmark(benchmark_name):\n statistics_scalars = {}\n\n for stat_name, scalar in statistics_scalars.iteritems():\n if histogram_helpers.ShouldFilterStatistic(\n histogram_name, benchmark_name, stat_name):\n continue\n extra_args = GetUnitArgs(scalar.unit)\n suffixed_name = '%s/%s_%s' % (\n benchmark_name, histogram_name, stat_name)\n if rest is not None:\n suffixed_name += '/' + rest\n legacy_parent_tests[stat_name] = add_point_queue.GetOrCreateAncestors(\n master, bot, suffixed_name, internal_only=internal_only,\n unescaped_story_name=unescaped_story_name, **extra_args)\n\n return [\n _AddRowsFromData(params, revision, parent_test, legacy_parent_tests),\n _AddHistogramFromData(params, revision, test_key, internal_only)]\n\n\n@ndb.tasklet\ndef _AddRowsFromData(params, revision, parent_test, legacy_parent_tests):\n data_dict = params['data']\n test_key = parent_test.key\n\n stat_names_to_test_keys = {k: v.key for k, v in\n legacy_parent_tests.iteritems()}\n rows = CreateRowEntities(\n data_dict, test_key, stat_names_to_test_keys, revision)\n if not rows:\n raise ndb.Return()\n\n yield ndb.put_multi_async(rows) + [r.UpdateParentAsync() for r in rows]\n\n tests_keys = []\n is_monitored = parent_test.sheriff and parent_test.has_rows\n if is_monitored:\n tests_keys.append(parent_test.key)\n\n for legacy_parent_test in legacy_parent_tests.itervalues():\n is_monitored = legacy_parent_test.sheriff and legacy_parent_test.has_rows\n if is_monitored:\n tests_keys.append(legacy_parent_test.key)\n\n tests_keys = [\n k for k in tests_keys if not add_point_queue.IsRefBuild(k)]\n\n # Updating of the cached graph revisions should happen after put because\n # it requires the new row to have a timestamp, which happens upon put.\n futures = [\n graph_revisions.AddRowsToCacheAsync(rows),\n find_anomalies.ProcessTestsAsync(tests_keys)]\n yield futures\n\n\n@ndb.tasklet\ndef _AddHistogramFromData(params, revision, test_key, internal_only):\n data_dict = params['data']\n guid = data_dict['guid']\n diagnostics = params.get('diagnostics')\n new_guids_to_existing_diagnostics = yield ProcessDiagnostics(\n diagnostics, revision, test_key, internal_only)\n\n # TODO(eakuefner): Move per-histogram monkeypatching logic to Histogram.\n hs = histogram_set.HistogramSet()\n hs.ImportDicts([data_dict])\n # TODO(eakuefner): Share code for replacement logic with add_histograms\n for new_guid, existing_diagnostic in (\n new_guids_to_existing_diagnostics.iteritems()):\n hs.ReplaceSharedDiagnostic(\n new_guid, diagnostic_ref.DiagnosticRef(\n existing_diagnostic['guid']))\n data = hs.GetFirstHistogram().AsDict()\n\n entity = histogram.Histogram(\n id=guid, data=data, test=test_key, revision=revision,\n internal_only=internal_only)\n yield entity.put_async()\n\n\n@ndb.tasklet\ndef ProcessDiagnostics(diagnostic_data, revision, test_key, internal_only):\n if not diagnostic_data:\n raise ndb.Return({})\n\n diagnostic_entities = []\n for name, diagnostic_datum in diagnostic_data.iteritems():\n # TODO(eakuefner): Pass map of guid to dict to avoid overhead\n guid = diagnostic_datum['guid']\n diagnostic_entities.append(histogram.SparseDiagnostic(\n id=guid, name=name, data=diagnostic_datum, test=test_key,\n start_revision=revision, end_revision=sys.maxint,\n internal_only=internal_only))\n new_guids_to_existing_diagnostics = yield (\n add_histograms.DeduplicateAndPutAsync(\n diagnostic_entities, test_key, revision))\n\n raise ndb.Return(new_guids_to_existing_diagnostics)\n\n\ndef GetUnitArgs(unit):\n unit_args = {\n 'units': unit\n }\n # TODO(eakuefner): Port unit system to Python and use that here\n histogram_improvement_direction = unit.split('_')[-1]\n if histogram_improvement_direction == 'biggerIsBetter':\n unit_args['improvement_direction'] = anomaly.UP\n elif histogram_improvement_direction == 'smallerIsBetter':\n unit_args['improvement_direction'] = anomaly.DOWN\n else:\n unit_args['improvement_direction'] = anomaly.UNKNOWN\n return unit_args\n\n\ndef CreateRowEntities(\n histogram_dict, test_metadata_key, stat_names_to_test_keys, revision):\n h = histogram_module.Histogram.FromDict(histogram_dict)\n # TODO(eakuefner): Move this check into _PopulateNumericalFields once we\n # know that it's okay to put rows that don't have a value/error (see\n # https://github.com/catapult-project/catapult/issues/3564).\n if h.num_values == 0:\n return None\n\n rows = []\n\n row_dict = _MakeRowDict(revision, test_metadata_key.id(), h)\n properties = add_point.GetAndValidateRowProperties(row_dict)\n test_container_key = utils.GetTestContainerKey(test_metadata_key)\n rows.append(graph_data.Row(id=revision, parent=test_container_key,\n **properties))\n\n for stat_name, suffixed_key in stat_names_to_test_keys.iteritems():\n row_dict = _MakeRowDict(revision, suffixed_key.id(), h, stat_name=stat_name)\n properties = add_point.GetAndValidateRowProperties(row_dict)\n test_container_key = utils.GetTestContainerKey(suffixed_key)\n rows.append(graph_data.Row(\n id=revision, parent=suffixed_key, **properties))\n\n return rows\n\ndef _MakeRowDict(revision, test_path, tracing_histogram, stat_name=None):\n d = {}\n test_parts = test_path.split('/')\n d['master'] = test_parts[0]\n d['bot'] = test_parts[1]\n d['test'] = '/'.join(test_parts[2:])\n d['revision'] = revision\n d['supplemental_columns'] = {}\n\n # TODO(#3628): Remove this annotation when the frontend displays the full\n # histogram and all its diagnostics including the full set of trace urls.\n trace_url_set = tracing_histogram.diagnostics.get(\n reserved_infos.TRACE_URLS.name)\n # We don't show trace URLs for summary values in the legacy pipeline\n is_summary = reserved_infos.SUMMARY_KEYS.name in tracing_histogram.diagnostics\n if trace_url_set and not is_summary:\n d['supplemental_columns']['a_tracing_uri'] = list(trace_url_set)[-1]\n\n for diag_name, annotation in DIAGNOSTIC_NAMES_TO_ANNOTATION_NAMES.iteritems():\n revision_info = tracing_histogram.diagnostics.get(diag_name)\n value = list(revision_info) if revision_info else None\n # TODO(eakuefner): Formalize unique-per-upload diagnostics to make this\n # check an earlier error. RevisionInfo's fields have to be lists, but there\n # should be only one revision of each type per upload.\n if not value:\n continue\n _CheckRequest(\n len(value) == 1,\n 'RevisionInfo fields must contain at most one revision')\n\n d['supplemental_columns'][annotation] = value[0]\n\n _AddStdioUris(tracing_histogram, d)\n\n if stat_name is not None:\n d['value'] = tracing_histogram.statistics_scalars[stat_name].value\n d['error'] = 0.0\n if stat_name == 'avg':\n d['error'] = tracing_histogram.standard_deviation\n else:\n _PopulateNumericalFields(d, tracing_histogram)\n return d\n\n\ndef _AddStdioUris(tracing_histogram, row_dict):\n log_urls = tracing_histogram.diagnostics.get(reserved_infos.LOG_URLS.name)\n if not log_urls:\n return\n\n if len(log_urls) == 1:\n _AddStdioUri('a_stdio_uri', log_urls.GetOnlyElement(), row_dict)\n\n\ndef _AddStdioUri(name, link_list, row_dict):\n # TODO(#4397): Change this to an assert after infra-side fixes roll\n if isinstance(link_list, list):\n row_dict['supplemental_columns'][name] = '[%s](%s)' % tuple(link_list)\n # Support busted format until infra changes roll\n elif isinstance(link_list, str):\n row_dict['supplemental_columns'][name] = link_list\n\n\ndef _PopulateNumericalFields(row_dict, tracing_histogram):\n statistics_scalars = tracing_histogram.statistics_scalars\n for name, scalar in statistics_scalars.iteritems():\n # We'll skip avg/std since these are already stored as value/error in rows.\n if name in ('avg', 'std'):\n continue\n\n row_dict['supplemental_columns']['d_%s' % name] = scalar.value\n\n row_dict['value'] = tracing_histogram.average\n row_dict['error'] = tracing_histogram.standard_deviation\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/dashboard/dashboard/add_histograms_queue.py","file_name":"add_histograms_queue.py","file_ext":"py","file_size_in_byte":13835,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"} +{"seq_id":"26649686024","text":"from .constants.apps import CSGO\r\nfrom .engine.engine import Engine\r\nfrom .engine.session import Session\r\nfrom .market.request import (\r\n ItemNameId,\r\n ItemOrdersHistogram,\r\n ItemPricing,\r\n SaleHistory,\r\n)\r\n\r\n\r\ndef _main():\r\n e = Engine(Session.load_from_file(\"session.json\"))\r\n # print(e.request(ItemPricing(CSGO, 'Clutch Case')))\r\n # print(e.request(ItemNameId(CSGO, 'Clutch Case')))\r\n # print(e.request(ItemOrdersHistogram(176241017)))\r\n print(e.request(SaleHistory(CSGO, \"Clutch Case\")))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n _main()\r\n","repo_name":"saltisgood/steam_exchange","sub_path":"steam_exchange/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8742740607","text":"\n\ndef on_link_activated(link):\n print(link)\n\nfrom PySide import QtCore, QtGui\nimport sys\n\n\nclass SampleWindow(QtGui.QWidget):\n def __init__(self):\n super(SampleWindow, self).__init__()\nwindow.setWindowTitle(\"Class QLabel\")\nwindow.resize(300, 150)\nlabel = QtGui.QLabel()\nlabel.setText(\"\"\"Это гиперссылка 1\nЭто гиперссылка 2\n\"\"\")\nlabel.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)\nlabel.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard)\nlabel.linkActivated[\"const QString&\"].connect(on_link_activated)\nvbox = QtGui.QVBoxLayout()\nvbox.addWidget(label)\nwindow.setLayout(vbox)\n","repo_name":"syurskyi/Python_Topics","sub_path":"140_gui/pyqt_pyside/examples/PyQt_PySide_book/004_Main components/001_Inscription/157_LinksAccessibleByKeyboard - toClass.py","file_name":"157_LinksAccessibleByKeyboard - toClass.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"254900306","text":"import random\nimport time\nfor x in range(5):\n var1 = random.randint(1,3)\n var2 = random.randint(1,3)\n time.sleep(1)\n if var1 == 1:\n print('Rock...')\n elif var1 == 2:\n print('Paper...')\n elif var1 == 3:\n print('Scissors...')\n time.sleep(2)\n if var2 == 1:\n print('Rock...')\n elif var2 == 2:\n print('Paper...')\n elif var2 == 3:\n print('Scissors...')\n time.sleep(1)\n if var1 == var2:\n print('Tie, nobody wins')\n if (var1 == 1 and var2 == 2) or (var1 == 2 and var2 == 1):\n print('Paper beats rock')\n elif (var1 == 1 and var2 == 3) or (var1 == 3 and var2 == 1):\n print('Rock beats scissors')\n elif (var1 == 2 and var2 == 3) or (var1 == 3 and var2 == 2):\n print('Scissors beats paper')\n time.sleep(1)","repo_name":"nickciliberto/python-codewars","sub_path":"rock-paper-scissors.py","file_name":"rock-paper-scissors.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20524087880","text":"from random import randint, choice\r\n\r\nMAIN_QUESTION = 'What number is missing in the progression?'\r\n\r\n\r\ndef generating_a_question_and_answer():\r\n j = 1\r\n d = randint(1, 10)\r\n number1 = randint(1, 30)\r\n progression = [number1]\r\n correct_answer = None\r\n while j < 10:\r\n progression.append(progression[j - 1] + d)\r\n j = j + 1\r\n index = randint(0, 9)\r\n correct_answer = progression[index]\r\n progression[index] = \"..\"\r\n question = (\"Question: {}\\n\".format(' '.join(map(str, progression))))\r\n return question, correct_answer\r\n","repo_name":"ProskurenkoDanylo/Brain-games","sub_path":"brain_games/games/brain_progression.py","file_name":"brain_progression.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"7357893728","text":"import codecs\nimport os\n\nfrom jinja2 import Template\nfrom parglare import Grammar, Parser\n\nfrom model_converter.converter.app.model.rule import Rule, Property, \\\n Connection, Pattern, Predicate\nfrom model_converter.converter.app.model.subsystem import Subsystem\nfrom model_converter.converter.app.model.terminal import Terminal, Port\nfrom model_converter.converter.app.model.data_holder import DataHolder, \\\n SubsystemDataHolder\nimport logging\n\nfrom model_converter.converter.app.util import get_root_path\n\n\nclass BaseParser:\n\n def __init__(self):\n try:\n from typhoon.api.schematic_editor import model as mdl\n # Temporary fix for namespace clashing in THCC\n except ImportError:\n from typhoon.api.impl.schematic_editor import model as mdl\n self.mdl = mdl\n\n self.rule_file_path = None\n self.input_file_path = None\n self.user_lib = None\n self.detailed_log_path = None\n root_path = get_root_path()\n self.rule_grammar = \\\n Grammar.from_file(os.path.join(root_path,\n 'converter',\n 'grammars',\n 'TyphoonRuleGrammar.pg'))\n\n self.rule_parser = Parser(self.rule_grammar)\n #\n # Should be set by child classes\n #\n self.input_parser = None\n self.match_rules = None\n self.patterns = {}\n #\n # Hierarchy of converted components (DataHolders),\n # used to connect components at the end of the conversion.\n # node_dict = {subsystem_handle(str):{node_id(str/int):\n # [terminal_handle1(str),\n # terminal_handle2(str),...]\n # }\n # }\n # Added None as the root level.\n #\n self.node_dict = {None:{}}\n self.conversion_dict = {}\n\n #\n # Dictionary which holds all subsystems\n # converted from the netlist, used to place\n # components into their parent subsystems\n #\n self.temp_subsystem_dict = {}\n\n #\n # Dictionary which holds all source components,\n # in TYPE:[INSTANCE1, INSTANCE2...] pairs\n #\n self.source_comp_dict_by_type = {\"Subsystem\": []}\n\n self.compiled = False\n\n def read_rules(self):\n with codecs.open(self.rule_file_path, 'r', errors='ignore') \\\n as fileData:\n rules = self.rule_parser.parse(fileData.read())\n\n self.match_rules = self._create_rule_obj_model(rules)\n\n def read_input(self):\n raise NotImplementedError(\"Reimplement this method in a child class.\")\n\n def _create_rule_obj_model(self, rule_list):\n \"\"\"\n Creates a Rule object model from the parsed\n rule file.\n\n Also creates patterns if defined,\n and adds them to the self.patterns dict under\n the pattern names.\n\n Args:\n rule_list (list): list of rules, each of which is essentially\n a nested list (list of lists)\n\n Returns:\n rules (list): Rule objects\n \"\"\"\n rules = []\n\n if len(rule_list) == 2:\n #\n for pattern in rule_list[0]:\n pattern_obj = self._create_pattern_rule(pattern)\n self.patterns[pattern_obj.name] = pattern_obj\n for rule in rule_list[1]:\n if rule[1][0] == \"*\":\n if rule[1][3] == \"{\":\n rules.append(self._create_n_to_m_rule(rule))\n else:\n rules.append(self._create_n_to_one_rule(rule))\n else:\n if rule[1][2] == \"{\":\n rules.append(self._create_n_to_m_rule(rule))\n else:\n rules.append(self._create_n_to_one_rule(rule))\n return rules\n\n def _create_predicate_obj(self, predicate_node):\n property_name = None\n condition = \"==\"\n property_value = None\n if len(predicate_node.split(\">=\")) == 2:\n condition = \">=\"\n elif len(predicate_node.split(\"=<\")) == 2:\n condition = \"<=\"\n elif len(predicate_node.split(\">\")) == 2:\n condition = \">\"\n elif len(predicate_node.split(\"<\")) == 2:\n condition = \"<\"\n property_name, property_value = predicate_node.split(condition)\n\n return Predicate(property_name, condition, property_value)\n\n def _create_property_obj(self, prop_node):\n \"\"\"\n Creates a Property object from the parsed property rule.\n\n Args:\n prop_node (list): nested list containing\n all the parsed (DSL) terminal values\n\n Returns:\n prop_obj (Property)\n \"\"\"\n prop_obj = Property(name=prop_node[0])\n #\n # Str property\n #\n if \"\\\"\" == prop_node[2][0] and \"\\\"\" == prop_node[2][-1] \\\n or \"'\" == prop_node[2][0] and \"'\" == prop_node[2][-1]:\n prop_obj.prop_type = \"str\"\n prop_obj.value = prop_node[2].strip(\"\\\"\").strip(\"'\")\n #\n # Num property\n #\n elif prop_node[2].isdigit():\n prop_obj.prop_type = \"num\"\n prop_obj.value = float(prop_node[2])\n #\n # Checking if property value is a function call or\n # just a property with parentheses in its name\n #\n elif \"(\" in prop_node[2]:\n prop_split = prop_node[2].split(\"(\", 1)\n func_name = prop_split[0]\n function = getattr(self.user_lib, func_name, None)\n # Checking if there is a user defined function with this name\n if function:\n prop_obj.prop_type = \"func\"\n prop_obj.value = func_name\n params = prop_split[1].strip(\")\")\n if params:\n param_list = params.split(\",\")\n for parameter in param_list:\n key, value = parameter.split(\"=\")\n if \"(\" in value and \")\" not in value:\n value += \")\"\n prop_obj.params[key.strip(\" \")] = value.strip(\" \")\n # Property value is a reference to a source component property\n else:\n prop_obj.prop_type = \"ref\"\n prop_obj.value = prop_node[2]\n #\n # Reference property\n #\n else:\n prop_obj.prop_type = \"ref\"\n prop_obj.value = prop_node[2]\n\n return prop_obj\n\n def _create_n_to_m_rule(self, rule_node):\n \"\"\"\n\n Args:\n rule_node:\n\n Returns:\n\n \"\"\"\n #\n # Checking if the \"source type\" is a pattern.\n # If it is a pattern, all indices are moved by 1,\n # and the pattern first must be found before\n # converting by this rule.\n #\n predicates = rule_node[0]\n rule_node = rule_node[1]\n is_pattern_match = rule_node[0] == \"*\"\n\n source_type = rule_node[1] if is_pattern_match else rule_node[0]\n typhoon_type = rule_node[3] if is_pattern_match \\\n and rule_node[3] != \"{\" else \"N-to-M\"\n\n rule_obj = Rule(source_type=source_type,\n typhoon_type=typhoon_type,\n pattern_match=is_pattern_match)\n\n for predicate in predicates:\n rule_obj.predicates.append(self._create_predicate_obj(predicate[1]))\n\n #\n # List containing all components which will\n # be created in this new subsystem\n #\n component_list = rule_node[4] if is_pattern_match else rule_node[3]\n for component in component_list:\n comp_rule_obj = Rule(typhoon_type=component[2])\n #\n # Setting property mapping\n #\n for prop in component[4]:\n comp_rule_obj.properties.append(self._create_property_obj(prop))\n rule_obj.components[component[0]] = comp_rule_obj\n #\n # List containing connections between the\n # newly created components inside the subsystem\n #\n connection_list = rule_node[7] if is_pattern_match else rule_node[6]\n\n for connection in connection_list:\n conn_obj = Connection(start_handle=connection[0],\n start_terminal=connection[2],\n end_handle=connection[4],\n end_terminal=connection[6])\n rule_obj.connections.append(conn_obj)\n\n port_list = rule_node[11] if is_pattern_match else rule_node[10]\n for port in port_list:\n comp_handle = port[0]\n comp_term = port[2]\n term_type = port[4]\n if is_pattern_match:\n pattern_handle = port[7]\n term_node = port[9]\n else:\n # 1:N conversion, there is no\n # pattern component handle\n # example: just '0' instead of 'MyComponent.0'\n pattern_handle = None\n term_node = port[7]\n rule_obj.ports[pattern_handle, term_node] = (term_type, comp_handle, comp_term)\n return rule_obj\n\n def _create_one_to_one_rule(self, rule_node):\n \"\"\"\n Creates a Rule object from the parsed 1:1 rule.\n\n Args:\n rule_node (list): nested list containing\n all the parsed (DSL) terminal values\n\n Returns:\n rule_obj (Rule)\n \"\"\"\n rule_obj = Rule(source_type=rule_node[0], typhoon_type=rule_node[2])\n\n #\n # Setting property mapping\n #\n for prop in rule_node[4]:\n rule_obj.properties.append(self._create_property_obj(prop))\n\n #\n # Setting terminal node mapping\n #\n\n for terminal in rule_node[7]:\n term_name = terminal[0]\n term_type = terminal[2]\n term_node = terminal[5]\n rule_obj.terminals[term_node] = (term_type, term_name)\n\n return rule_obj\n\n def _create_pattern_rule(self, pattern_node):\n \"\"\"\n Creates pattern objects which are used in conversion rules.\n\n Example of a conversion rule with pattern matching:\n *Buck => Buck\n (pattern name => Typhoon component type)\n\n Args:\n pattern_node (list): nested list of lists containing\n components and their connections\n\n Returns:\n pattern_obj (Pattern)\n \"\"\"\n pattern_obj = Pattern(pattern_node[0].strip())\n #\n # Mapping user defined handles to their component types\n #\n for component in pattern_node[4]:\n pattern_obj.components[component[0]] = component[2]\n #\n # Mapping the connections between pattern components\n #\n for connection in pattern_node[8]:\n start_handle = connection[0]\n start_terminal = connection[2]\n end_handle = connection[4]\n end_terminal = connection[6]\n connection_obj = Connection(start_handle=start_handle,\n start_terminal=start_terminal,\n end_handle=end_handle,\n end_terminal=end_terminal)\n pattern_obj.connections.append(connection_obj)\n\n return pattern_obj\n\n def _create_n_to_one_rule(self, rule_node):\n \"\"\"\n Creates a Rule object from the parsed N:1 rule.\n\n Args:\n rule_node (list): nested list of lists containing\n components and their connections\n\n Returns:\n rule_obj (Rule)\n \"\"\"\n predicates = rule_node[0]\n rule_node = rule_node[1]\n is_pattern_match = rule_node[0] == \"*\"\n\n source_type = rule_node[1] if is_pattern_match else rule_node[0]\n typhoon_type = rule_node[3] if is_pattern_match else rule_node[2]\n rule_obj = Rule(source_type=source_type,\n typhoon_type=typhoon_type,\n pattern_match=is_pattern_match)\n\n rule_list = rule_node[5] if is_pattern_match else rule_node[4]\n for prop in rule_list:\n rule_obj.properties.append(self._create_property_obj(prop))\n\n for predicate in predicates:\n rule_obj.predicates.append(self._create_predicate_obj(predicate[1]))\n\n terminal_list = rule_node[8] if is_pattern_match else rule_node[7]\n for terminal in terminal_list:\n term_name = terminal[0]\n term_kind = terminal[2]\n if is_pattern_match:\n term_parent = terminal[5]\n term_node = terminal[7]\n else:\n term_parent = None\n term_node = terminal[5]\n rule_obj.terminals[term_parent, term_node] = (term_kind,\n term_parent,\n term_name)\n\n return rule_obj\n\n def _pattern_match(self, start_collection, end_collection, connection):\n matched = {}\n for start_comp in start_collection:\n if start_comp.converted:\n continue\n for end_comp in end_collection:\n if start_comp is end_comp:\n continue\n if end_comp.converted:\n continue\n start_terminal = \\\n start_comp.terminals[connection.start_terminal]\n end_terminal = end_comp.terminals[connection.end_terminal]\n if start_terminal.node_id == end_terminal.node_id:\n if connection.start_handle not in matched:\n matched[connection.start_handle] = start_terminal\n if connection.end_handle not in matched:\n matched[connection.end_handle] = end_terminal\n return matched\n\n def _create_conversion_subsystems(self,\n component_parent: (Subsystem, None),\n current_sub: Subsystem = None):\n\n if component_parent is None:\n return None\n\n subsystem = \\\n self.temp_subsystem_dict.get(component_parent.name, None)\n if subsystem is None:\n subsystem = SubsystemDataHolder()\n subsystem.name = component_parent.name.split(\".\")[-1]\n subsystem.components[\"Subsystem\"] = []\n subsystem.ports = [port.clone() for port\n in component_parent.terminals]\n\n subsystem.set_port_sides()\n self.temp_subsystem_dict[component_parent.name] = subsystem\n\n if current_sub is not None and \\\n current_sub not in subsystem.components[\"Subsystem\"]:\n subsystem.components[\"Subsystem\"].append(current_sub)\n if component_parent.parent is None:\n if subsystem not in self.conversion_dict[\"Subsystem\"]:\n self.conversion_dict[\"Subsystem\"].append(subsystem)\n return subsystem\n\n\n parent = self._create_conversion_subsystems(component_parent.parent,\n subsystem)\n subsystem.parent = parent\n return subsystem\n\n\n\n def get_original_file_name(self, file_name:str):\n \"\"\"\n Returns the file TSE file name\n Args:\n file_name: (str) input file's filename\n\n Returns:\n tse file name (str)\n \"\"\"\n path = \"\"\n path = os.path.join(path, *file_name)\n return path+\".tse\"\n\n\n def get_available_file_name(self, file_name:str):\n \"\"\"\n Checks if the input file's filename is available as the output file's\n filename. If the name is already taken, appends an index (or increments\n it if there is already an index present) to the output file's filename.\n Args:\n file_name: (str) input file's filename\n\n Returns:\n new file name (str)\n \"\"\"\n index = 0\n path = \"\"\n path = os.path.join(path, *file_name)\n while True:\n if os.path.isfile(path+\".tse\"):\n index+=1\n else:\n return path+\".tse\"\n if not os.path.isfile(path+\"(\"+str(index)+\").tse\"):\n return path+\"(\"+str(index)+\").tse\"\n\n\n def _save_single_component(self, component, parent=None):\n try:\n from typhoon.api.schematic_editor.exception import SchApiException\n # Temporary fix for namespace clashing in THCC\n except ImportError:\n from typhoon.api.impl.schematic_editor.exception import \\\n SchApiException\n component.parent = parent\n component_handle = \\\n self.mdl.create_component(\n component.typhoon_type,\n parent=parent,\n name=component.name,\n rotation=component.orientation,\n position=component.position)\n\n for key, value in component.properties.items():\n try:\n self.mdl.set_property_value(\n self.mdl.prop(component_handle, key), value)\n except SchApiException:\n logging.warning(f\"(Property setting error) \"\n f\"{component.name}- error setting\"\n f\" property \\\"{key}\\\" to \"\n f\"\\\"{value}\\\".\")\n self.mdl.set_position(component_handle, component.position)\n\n for term in component.terminals:\n try:\n #\n # !! NOTE !!\n # This may raise the SchApiException if the component\n # does not have a terminal with the passed name\n #\n terminal_handle = self.mdl.term(component_handle, term.name)\n\n subsystem_dict = self.node_dict.get(parent, None)\n # If the parent key is not present, create a new dict\n # and set the reference to it so it can be populated\n # with node id's and the corresponding terminal handles\n if subsystem_dict is None:\n new_subsystem = {}\n self.node_dict[parent] = new_subsystem\n subsystem_dict = new_subsystem\n connectables = subsystem_dict.get(term.node_id, None)\n if connectables is None:\n subsystem_dict[term.node_id] = []\n subsystem_dict[term.node_id].append(\n [False, terminal_handle, component])\n except SchApiException:\n logging.warning(f\"[Terminal connection error] Cannot retrieve \"\n f\"terminal \\\"{term.name}\\\" of the \"\n f\"\\\"{component_handle.fqn}\\\"\"\n f\"({component.typhoon_type}) component.\")\n return component_handle\n\n def save_component(self, component, parent=None):\n try:\n from typhoon.api.schematic_editor.exception import SchApiException\n # Temporary fix for namespace clashing in THCC\n except ImportError:\n from typhoon.api.impl.schematic_editor.exception import \\\n SchApiException\n if isinstance(component, SubsystemDataHolder):\n component_handle = \\\n self.mdl.create_component(component.typhoon_type,\n parent=parent,\n name=component.name,\n position=component.position,\n rotation=component.orientation)\n temp_handle_dict = {}\n #\n # Creating child components inside the subsystem\n #\n for handle, child_comp_list in component.components.items():\n for child_comp in child_comp_list:\n child_comp.parent = component_handle\n if isinstance(child_comp, SubsystemDataHolder):\n self.save_component(child_comp, component_handle)\n else:\n child_handle = \\\n self._save_single_component(child_comp,\n component_handle)\n\n temp_handle_dict[handle] = child_handle\n\n #\n # Creating inner component connections\n #\n for connection in component.connections:\n start_handle = temp_handle_dict[connection.start_handle]\n start_term = connection.start_terminal\n\n #\n # Creating logging strings, used in except blocks below\n #\n child_handles = \"(\"\n for handle in component.components.keys():\n child_handles += handle + \", \"\n child_handles = child_handles.strip().strip(\",\") + \")\"\n\n # Retrieving start terminal\n try:\n start_terminal = self.mdl.term(start_handle, start_term)\n except SchApiException:\n typhoon_type = \\\n component.components[start_handle].typhoon_type\n logging.warning(f\"[N -> M conversion error - \"\n f\"{child_handles}] Cannot retrieve terminal\"\n f\" {start_term} of component {start_handle}\"\n f\" ({typhoon_type}).\")\n continue\n end_handle = temp_handle_dict[connection.end_handle]\n end_term = connection.end_terminal\n # Retrieving end terminal\n try:\n end_terminal = self.mdl.term(end_handle, end_term)\n except SchApiException:\n typhoon_type = \\\n component.components[end_handle].typhoon_type\n logging.warning(f\"[N -> M conversion error - \"\n f\"{child_handles}] Cannot retrieve terminal\"\n f\" {end_term} of component {end_handle}\"\n f\" ({typhoon_type}).\")\n continue\n # Connecting child component terminals\n try:\n self.mdl.create_connection(start_terminal, end_terminal)\n except SchApiException:\n logging.warning(f\"[N -> M conversion error - \"\n f\"{child_handles}] Cannot connect terminals\"\n f\"{start_terminal} with {end_terminal}.\")\n # Counter for unique port names.\n UID = 0\n left_pos = [component.comp_grid_dimensions[0][0],\n component.comp_grid_dimensions[1][0]]\n right_pos = [component.comp_grid_dimensions[0][1],\n component.comp_grid_dimensions[1][0]]\n for port in component.ports:\n\n if port.side == \"left\":\n position = (left_pos[0],\n left_pos[1])\n # Next port should be placed beneath the last one\n # on that side\n left_pos[1] += 50\n elif port.side == \"right\":\n position = (right_pos[0],\n right_pos[1])\n # Next port should be placed beneath the last one\n # on that side\n right_pos[1] += 50\n\n\n # If the parent_component of a port is a string,\n # the conversion was 1:Sub. This means the port_name\n # should contain the parent_component name to avoid\n # port name duplication\n if isinstance(port.parent_component, str):\n port_name = f\"{port.parent_component} {port.name}\"\n else:\n port_name = \"Port\" + str(UID) if port.name is None \\\n else port.name\n if port.kind == \"sp\":\n port_handle = self.mdl.create_port(parent=component_handle,\n kind=port.kind,\n direction=port.direction,\n name=port_name,\n position=position,\n terminal_position=\n (port.side, \"auto\"))\n else:\n port_handle = self.mdl.create_port(parent=component_handle,\n kind=port.kind,\n name=port_name,\n position=position,\n terminal_position=\n (port.side, \"auto\"))\n #\n # Checking if the parent_component of this port is\n # a string value. If it is, the Subsystem was not\n # present in the original netlist, and this port\n # should be connected to the component which set\n # its node ID.\n #\n if isinstance(port.parent_component, str):\n source_term = \\\n self.mdl.term(temp_handle_dict[port.parent_component],\n port.name)\n self.mdl.create_connection(port_handle, source_term)\n\n\n UID += 1 # Incrementation of the unique ID number.\n level = self.node_dict.get(component_handle, None)\n if level is None:\n self.node_dict[component_handle] = \\\n {port.node_id: [\n [False, port_handle, component]]}\n else:\n connectables = level.get(port.node_id, None)\n if connectables is None:\n level[port.node_id] = []\n\n level[port.node_id].append(\n [False, port_handle, component])\n\n parent_level = self.node_dict.get(\n parent, None)\n if parent_level is None:\n self.node_dict[parent] = {\n port.node_id: [\n [False, self.mdl.term(component_handle, port_name),\n component]]}\n else:\n parent_connectables = parent_level.get(port.node_id,\n None)\n if parent_connectables is None:\n parent_level[port.node_id] = []\n\n parent_level[port.node_id].append(\n [False, self.mdl.term(component_handle, port_name),\n component])\n\n else:\n self._save_single_component(component, parent)\n\n\n def save_subsystem(self, subsystem, parent_subsystem_handle):\n sub = self.mdl.create_component(\"core/Empty Subsystem\",\n parent=parent_subsystem_handle,\n name=subsystem.name.split(\".\")[-1],\n position=subsystem.position)\n\n # Counter for unique port names.\n UID = 0\n for port in subsystem.ports:\n port_name = \"Port\" + str(UID)\n port_handle = self.mdl.create_port(parent=sub,\n kind=port.kind,\n name=port_name,\n position=port.position,\n terminal_position=\n (port.side, \"auto\")\n )\n\n UID += 1 # Incrementation of the unique ID number.\n level = self.node_dict.get(sub, None)\n if level is None:\n self.node_dict[sub] = \\\n {port.node_id:[[False,port_handle, subsystem]]}\n else:\n connectables = level.get(port.node_id, None)\n if connectables is None:\n level[port.node_id] = [[False,port_handle, subsystem]]\n else:\n level[port.node_id].append([False,port_handle, subsystem])\n parent_level = self.node_dict.get(parent_subsystem_handle, None)\n if not parent_level:\n self.node_dict[parent_subsystem_handle] = {port.node_id:[[False,self.mdl.term(sub,port_name), subsystem]]}\n else:\n parent_connectables = parent_level.get(port.node_id, None)\n if parent_connectables is None:\n parent_level[port.node_id] = [[False, self.mdl.term(sub,port_name), subsystem]]\n else:\n parent_level[port.node_id].append([False, self.mdl.term(sub,port_name), subsystem])\n\n for type, component in subsystem.components.items():\n component.parent = sub\n if type == \"Subsystem\":\n self.save_subsystem(component, sub)\n else:\n self.save_component(component, sub)\n\n\n def save_schematic(self, device_id, config_id, compile_model=False):\n \"\"\"\n Instantiates a Schematic API client, creates a new model and configures\n it, and saves each converted component.\n\n Also connects terminals in each node for each level in the hierarchy.\n\n Depending on the compile_model flag, the model will be\n compiled after saving and connecting all components.\n\n Args:\n device_id (str): device identifier - example: \"HIL604\"\n config_id (str): configuration identifier - example: \"1\"\n compile_model (bool): compilation flag\n\n Returns:\n None\n \"\"\"\n\n self.mdl.create_new_model()\n #\n # !! Setting HIL model !!\n #\n self.mdl.set_model_property_value(\"hil_device\", device_id)\n self.mdl.set_model_property_value(\"hil_configuration_id\", config_id)\n\n # API calls for component creation, property setting,\n # child element creation etc...\n for type, components in self.conversion_dict.items():\n for component in components:\n self.save_component(component, component.parent)\n #\n # API calls for terminal connection\n #\n for connectable_dict in self.node_dict.values():\n for key, connectable_list in connectable_dict.items():\n # Terminals might not be connected,\n # in this case their Node ID is None.\n # node_id:[terminal list]\n if key is None:\n continue\n self._connect(connectable_list)\n path = self.input_file_path.split(os.path.sep)\n path[0] += os.path.sep\n path[-1] = path[-1].replace(\".xml\", \"\").replace(\".slx\", \"\")\n self.save_path = self.get_original_file_name(path)\n self.mdl.save_as(self.save_path)\n if compile_model:\n self.compiled = self.mdl.compile()\n self.mdl.close_model()\n\n def _connect(self, connectable_list:list):\n \"\"\"\n Connecting terminal handles from the same node,\n contained in the connectable_list.\n\n If there are more than two terminals in a node,\n a junction will be created and used to connect\n all terminals together.\n\n Args:\n connectable_list (list): terminal handle list,\n all of which are in\n the same node.\n\n Returns:\n None\n \"\"\"\n try:\n from typhoon.api.schematic_editor.exception import SchApiException\n # Temporary fix for namespace clashing in THCC\n except ImportError:\n from typhoon.api.impl.schematic_editor.exception import \\\n SchApiException\n junction = None\n # Checking if a junction should be used to connect\n # terminals from this node list\n if len(connectable_list) > 2 and junction is None:\n kind = \"sp\" if [term for term in connectable_list\n if self.mdl.get_connectable_kind(term[1]) == \"sp\"] \\\n else \"pe\"\n position = [0, 0]\n for connectable in connectable_list:\n position[0] += connectable[2].position[0]\n position[1] += connectable[2].position[1]\n position[0] = int(position[0]/len(connectable_list))\n position[1] = int(position[1]/len(connectable_list))\n connectable_parent = connectable_list[0][2].parent\n\n junction = \\\n self.mdl.create_junction(parent=connectable_parent,\n position=position,\n kind=kind)\n #\n # Connecting all terminals from the same\n # node with the newly created junction\n #\n if junction:\n for connectable in connectable_list:\n try:\n self.mdl.create_connection(junction,\n connectable[1])\n except SchApiException:\n logging.warning(f\"[Connecting Schematic components] Unable \"\n f\"to connect {junction} with \"\n f\"{connectable[1].fqn}.\")\n #\n # Connecting terminals directly with each other\n #\n else:\n for connectable_A in connectable_list:\n for connectable_B in connectable_list:\n if connectable_A is connectable_B:\n continue\n if connectable_A[0] or connectable_B[0]:\n continue\n #\n # !! Note !!\n #\n # Uncomment this to prevent the connecting of\n # two or more terminals of the same component\n # with each other\n\n # if connectable_A[2] is connectable_B[2]:\n # continue\n\n try:\n self.mdl.create_connection(connectable_A[1],\n connectable_B[1])\n connectable_B[0] = True\n except SchApiException:\n logging.warning(f\"[Connecting Schematic components] \"\n f\"Unable to connect \"\n f\"{connectable_A[1].fqn} with \"\n f\"{connectable_B[1].fqn}.\")\n\n def _convert_one_to_sub(self, rule, component, parent_subsystem):\n \"\"\"\n Converts the component into a Subsystem.\n All child components defined by the rule\n are also created and added to the components\n dictionary.\n\n Args:\n rule (Rule): Rule object which defines the new Subsystem\n component (Component): netlist Component object\n parent_subsystem (Subsystem): the component's parent\n (None if this is on the root level)\n\n Returns:\n sub (SubsystemDataHolder)\n \"\"\"\n sub = SubsystemDataHolder()\n sub.position = component.position\n sub.name = component.name\n\n for handle, child_comp_rule in rule.components.items():\n dh = self._convert_one_to_one(child_comp_rule,\n component,\n None)\n dh.name = handle\n sub.components[handle] = [dh]\n\n sub.calculate_grid_dimensions()\n\n sub.connections = rule.connections\n\n try:\n for i, items in enumerate(rule.ports.items()):\n key = items[0][1]\n values = items[1]\n node_id = component.terminals[key].node_id\n port = Port()\n port.node_id = node_id\n port.kind = values[0]\n port.parent_component = values[1]\n port.name = values[2]\n sub.ports.append(port)\n except KeyError:\n logging.warning(f\"[1:M - {rule.source_type} ({component.name}) -> \"\n f\"core/Subsystem] Port mapping #{i} is incorrect, \"\n f\"missing terminal with the ID \\\"{key}\\\" in the \"\n f\"source component.\")\n return None\n sub.set_port_sides()\n sub.parent = parent_subsystem\n return sub\n\n def _convert_one_to_n(self, rule):\n \"\"\"\n Iterates through all source components of\n the specified source type - defined in the rule object,\n and converts them into either a single new component (DataHolder)\n or a whole subsystem with child components (SubsystemDataHolder).\n\n Args:\n rule (Rule): Rule object\n\n Returns:\n ret_val (list): list of DataHolders or SubsystemDataHolders\n \"\"\"\n if rule.source_type not in self.source_comp_dict_by_type:\n return\n ret_val = []\n for component in self.source_comp_dict_by_type.get(rule.source_type,[]):\n if component.converted is True:\n continue\n #\n # Predicate check. If all conditions are not met,\n # the current component will be skipped\n # (and not marked as converted)\n #\n conditions_fulfilled = True\n for predicate in rule.predicates:\n if predicate.evaluate(component) is False:\n conditions_fulfilled = False\n break\n if conditions_fulfilled is False:\n continue\n dh = None\n parent_subsystem = None\n #\n # Creating hierarchy for the component if needed\n # (if the component is in a subsystem)\n #\n if component.parent is not None and \\\n component.parent.name in self.temp_subsystem_dict:\n parent_subsystem = \\\n self.temp_subsystem_dict[component.parent.name]\n else:\n parent_subsystem = \\\n self._create_conversion_subsystems(component.parent)\n\n if parent_subsystem is not None:\n parent_subsystem.position = [coord for coord in\n component.parent.position]\n if rule.components:\n dh = self._convert_one_to_sub(rule, component, parent_subsystem)\n if dh is None:\n continue\n else:\n dh = self._convert_one_to_one(rule, component, parent_subsystem)\n\n\n #\n # !! Important part !!\n #\n # Adds the DataHolder of this component to\n # the conversion_dict if it is found on the root level\n #\n if parent_subsystem is None:\n if dh.typhoon_type not in self.conversion_dict:\n self.conversion_dict[dh.typhoon_type] = [dh]\n else:\n self.conversion_dict[dh.typhoon_type].append(dh)\n ret_val.append(dh)\n #\n # If the component is not on the root level,\n # the parent subsystem's component dict will be\n # updated with the newly converted component, and\n # since the parent subsystem has already been added\n # to the conversion dict no other action is required\n #\n else:\n if dh.typhoon_type not in parent_subsystem.components:\n parent_subsystem.components[dh.typhoon_type] = []\n\n parent_subsystem.components[dh.typhoon_type].append(dh)\n if ret_val:\n return ret_val\n\n def _find_pattern(self, rule):\n \"\"\"\n This method finds the pattern (collection of components\n which are interconnected) by retrieving lists of candidate\n components and iterating through the connections list of the\n pattern to check if the candidate components are linked in the\n specified way.\n\n If a pattern is found, the components are marked as converted.\n\n Args:\n rule (Rule): Rule object with the candidate types\n and their connections\n\n Returns:\n SubsystemDataHolder\n \"\"\"\n pattern = self.patterns.get(rule.source_type)\n pattern_candidates = \\\n {handle: self.source_comp_dict_by_type.get(comp_type, [])\n for handle, comp_type in pattern.components.items()}\n matched = {}\n for connection in pattern.connections:\n #\n # Connection start elements\n #\n if connection.start_handle in matched:\n start_collection = \\\n [matched[connection.start_handle].parent_component]\n else:\n start_collection = \\\n pattern_candidates.get(connection.start_handle, [])\n #\n # Connection end elements\n #\n if connection.end_handle in matched:\n end_collection = \\\n [matched[connection.end_handle].parent_component]\n else:\n end_collection = \\\n pattern_candidates.get(connection.end_handle, [])\n\n #\n # Returns a dictionary with the start\n # and end handles and their terminals,\n # or an empty dictionary if nothing was\n # matched\n #\n matched_terminals = self._pattern_match(start_collection,\n end_collection,\n connection)\n #\n # If connected terminals were found,\n # adding the entries to the matched dictionary\n #\n if matched_terminals:\n matched.update(matched_terminals)\n #\n # If any part of the pattern connection\n # was not found, returning None\n #\n else:\n return None\n\n # Checking if the number of matched\n # terminals is the same as the number\n # of components defined in the pattern rule\n if len(matched) == len(pattern.components):\n for terminal in matched.values():\n terminal.parent_component.converted = True\n # Converting the matched terminals' parents\n return self._convert_pattern(matched, rule)\n else:\n return None\n\n def _convert_one_to_one(self, rule, component, parent_subsystem=None):\n \"\"\"\n Converts a component into a single DataHolder,\n sets its properties and maps its terminals.\n\n Args:\n rule (Rule): Rule object which defines the conversion\n component (Component): Component object created from the netlist\n parent_subsystem (Subsystem): parent subsystem of the component\n\n Returns:\n dh (DataHolder)\n \"\"\"\n #\n # DataHolder objects are POPO objects which\n # will be used when calling the TyphoonHIL API\n # to create components and set their properties\n #\n dh = DataHolder()\n dh.typhoon_type = rule.typhoon_type\n dh.source_type = rule.source_type\n dh.name = component.name\n dh.orientation = component.orientation\n dh.position = component.position\n\n if parent_subsystem is not None:\n dh.parent = parent_subsystem\n\n # Setting properties\n for prop in rule.properties:\n # Property is a reference to a component property\n if prop.prop_type == \"ref\":\n if prop.value in component.properties:\n dh.properties[prop.name] = \\\n component.properties[prop.value]\n else:\n logging.warning(f\"[1:1 - {rule.source_type} \"\n f\"({component.name}) -> \"\n f\"{rule.typhoon_type}] Missing property\"\n f\" \\\"{prop.value}\\\" in \"\n f\"source component, unable to set \"\n f\"\\\"{prop.name}\\\".\")\n # Property is a String or number\n elif prop.prop_type in {\"str\", \"num\"}:\n dh.properties[prop.name] = prop.value\n # Property is the return value of a function call\n else:\n params = {}\n call_func = True\n for name, value in prop.params.items():\n if value.isdigit():\n params[name] = float(value)\n elif \"\\\"\" == value[0] and \"\\\"\" == value[-1] or \\\n \"'\" == value[0] and \"'\" == value[-1]:\n params[name] = value\n else:\n if value in component.properties:\n params[name] = component.properties[value]\n else:\n logging.warning(f\"[1:1 - {rule.source_type} \"\n f\"({component.name}) -> \"\n f\"{rule.typhoon_type}] Missing\"\n f\" property \\\"{value}\\\" for \"\n f\"function call \"\n f\"\\\"{prop.value}\\\" - kwarg \"\n f\"\\\"{name}\\\", unable to set \"\n f\"\\\"{prop.name}\\\".\")\n call_func = False\n if call_func:\n dh.properties[prop.name] = \\\n getattr(self.user_lib, prop.value)(**params)\n\n for i, items in enumerate(rule.terminals.items()):\n key = items[0][1]\n values = items[1]\n terminal_obj = Terminal()\n try:\n orig_terminal = component.terminals[key]\n except KeyError:\n logging.warning(f\"[1:1 - {rule.source_type} \"\n f\"({component.name}) -> \"\n f\"{rule.typhoon_type}] Terminal mapping #{i} is\"\n f\" incorrect, missing terminal \\\"{key}\\\" in the\"\n f\" source component.\")\n continue\n terminal_obj.node_id = orig_terminal.node_id\n terminal_obj.index = orig_terminal.index\n terminal_obj.kind = values[0]\n terminal_obj.name = values[2]\n terminal_obj.position = orig_terminal.position\n terminal_obj.parent_component = dh\n terminal_obj.side = orig_terminal.side\n dh.terminals.append(terminal_obj)\n\n component.converted = True\n return dh\n\n def _convert_sub_to_sub(self, matched_terminals, rule):\n \"\"\"\n Converts a matched pattern into a Subsystem.\n Args:\n matched_terminals (dict): passed by the _find_pattern method\n rule (Rule): Rule object which defines the conversion\n\n Returns:\n sub (SubsystemDataHolder)\n \"\"\"\n sub = SubsystemDataHolder()\n components = {}\n # Initial position\n init_position = [50, 50]\n\n name = \"|\"\n #\n # Concatenating each component's\n # name with the initial name of this new Subsystem\n #\n for match in matched_terminals.values():\n name += match.parent_component.name+\"|\"\n\n sub.name = name\n\n for handle, child_comp_rule in rule.components.items():\n dh = DataHolder()\n dh.typhoon_type = child_comp_rule.typhoon_type\n dh.source_type = \"\"\n dh.name = handle\n dh.orientation = \"up\"\n dh.position = [i * 2 for i in init_position]\n init_position = dh.position\n\n dh.parent = sub\n #\n # Setting properties\n #\n for prop in child_comp_rule.properties:\n # Property is a reference to a component property\n if prop.prop_type == \"ref\":\n prop_value_split = prop.value.split(\".\")\n comp_handle = None\n comp_prop = None\n component = None\n if len(prop_value_split) == 2:\n comp_handle, comp_prop = prop_value_split\n if comp_handle not in matched_terminals:\n logging.warning(f\"[N:M - {rule.source_type} -> \"\n f\"core/Subsystem] Error in \"\n f\"property mapping \"\n f\"\\\"{prop.name}\\\", the entered \"\n f\"pattern component handle \"\n f\"\\\"{comp_handle}\\\" is \"\n f\"not present in the pattern. \"\n f\"Unable to set it to the \"\n f\"value of the pattern \"\n f\"component's property.\")\n continue\n component = \\\n matched_terminals[comp_handle].parent_component\n else:\n logging.warning(f\"[N:M - {rule.source_type} -> \"\n f\"core/Subsystem] Error in property\"\n f\" mapping \\\"{prop.name}\\\", missing\"\n f\" pattern component handle. \"\n f\"Unable to set it to the value of \"\n f\"the pattern component's \"\n f\"property.\")\n continue\n if comp_prop in component.properties:\n dh.properties[prop.name] = \\\n component.properties[comp_prop]\n else:\n logging.warning(f\"[N:M - {rule.source_type} \"\n f\" -> core/Subsystem] Missing \"\n f\"property \\\"{comp_prop}\\\" in \"\n f\"source component \"\n f\"\\\"{component.type}\\\", unable to\"\n f\" set \\\"{prop.name}\\\".\")\n # Property is a String or number\n elif prop.prop_type in {\"str\", \"num\"}:\n dh.properties[prop.name] = prop.value\n # Property is the return value of a function call\n else:\n params = {}\n call_func = True\n for name, value in prop.params.items():\n if not call_func:\n break\n # Arg is digit\n if value.isdigit():\n params[name] = float(value)\n # Arg is string\n elif \"\\\"\" == value[0] and \"\\\"\" == value[-1] or \\\n \"'\" == value[0] and \"'\" == value[-1]:\n params[name] = value\n # Arg is reference to component value\n else:\n arg_value_split = value.split(\".\")\n comp_handle = None\n comp_prop = None\n component = None\n if len(arg_value_split) == 2:\n comp_handle, comp_prop = arg_value_split\n if comp_handle not in matched_terminals:\n logging.warning(f\"[N:M - \"\n f\"{rule.source_type} ->\"\n f\" core/Subsystem] \"\n f\"Error in property \"\n f\"mapping \"\n f\"\\\"{prop.name}\\\", the \"\n f\"entered pattern \"\n f\"component handle \"\n f\"\\\"{comp_handle}\\\" is \"\n f\"not present in the \"\n f\"pattern. Unable to \"\n f\"set its property \"\n f\"\\\"{comp_prop}\\\" as \"\n f\"the kwarg \"\n f\"\\\"{name}\\\".\")\n call_func = False\n continue\n component = \\\n matched_terminals[\n comp_handle].parent_component\n else:\n logging.warning(\n f\"[N:M - {rule.source_type} -> \"\n f\"core/Subsystem] Error in property\"\n f\" mapping \\\"{prop.name}\\\", missing\"\n f\" pattern component handle. \"\n f\"Unable to set it to the value of \"\n f\"the pattern component's \"\n f\"property.\")\n call_func = False\n continue\n if comp_prop in component.properties:\n params[name] = \\\n component.properties[comp_prop]\n else:\n logging.warning(f\"[N:M - \"\n f\"{rule.source_type} ->\"\n f\" core/Subsystem] \"\n f\"Error in property \"\n f\"mapping \"\n f\"\\\"{prop.name}\\\", the \"\n f\"property \\\"{comp_prop}\\\"\"\n f\"was not found in the \"\n f\"component \"\n f\"\\\"{component.name}\\\" - \"\n f\"handle \\\"{comp_handle}\\\".\"\n f\"Unable to set it as \"\n f\"the kwarg \"\n f\"\\\"{name}\\\".\")\n call_func = False\n if call_func:\n dh.properties[prop.name] = \\\n getattr(self.user_lib, prop.value)(**params)\n # DataHolders are to be added to lists\n # since the parent is a SubsystemDataHolder,\n # and its components will be iterated through\n # upon creation via API\n components[handle] = [dh]\n sub.components = components\n sub.calculate_grid_dimensions()\n sub.connections = rule.connections\n try:\n for i, items in enumerate(rule.ports.items()):\n component = matched_terminals[items[0][0]].parent_component\n key = items[0][1]\n values = items[1]\n node_id = component.terminals[key].node_id\n port = Port()\n port.node_id = node_id\n port.kind = values[0]\n port.parent_component = values[1]\n port.name = values[2]\n sub.ports.append(port)\n except KeyError:\n logging.warning(\n f\"[N:M - {rule.source_type} ({component.name}) -> \"\n f\"core/Subsystem] Port mapping #{i} is incorrect, \"\n f\"missing terminal with the ID \\\"{key}\\\" in the \"\n f\"source component.\")\n return None\n\n sub.set_port_sides()\n\n self.conversion_dict[\"Subsystem\"].append(sub)\n return sub\n\n def _convert_sub_to_one(self, matched_terminals, rule):\n \"\"\"\n Converts a matched pattern into a single DataHolder.\n\n Args:\n matched_terminals (dict): passed by the _find_pattern method\n rule (Rule): Rule object which defines the conversion\n\n Returns:\n dh (DataHolder)\n \"\"\"\n dh = DataHolder()\n dh.source_type = rule.source_type\n dh.typhoon_type = rule.typhoon_type\n name = \"|\"\n position = [0, 0]\n for term in matched_terminals.values():\n name += term.parent_component.name + \"|\"\n position[0] += term.parent_component.position[0]\n position[1] += term.parent_component.position[1]\n position[0] = int(position[0] / len(matched_terminals))\n position[1] = int(position[1] / len(matched_terminals))\n\n dh.position = position\n dh.name = name\n\n for prop in rule.properties:\n if prop.prop_type == \"ref\":\n # User defined handle in the pattern.\n comp_ref = prop.value[0]\n # Property name of the matched component\n comp_prop_name = prop.value[1]\n component = matched_terminals.get(comp_ref, None)\n if component is None:\n logging.warning(f\"[N:1 - {rule.source_type} -> \"\n f\"{rule.typhoon_type}] Error in property \"\n f\"mapping \\\"{prop.name}\\\", \"\n f\"\\\"{comp_ref}\\\" handle was not found \"\n f\"in the defined pattern.\")\n continue\n\n component_property = \\\n component.properties.get(comp_prop_name, None)\n if component_property is None:\n logging.warning(f\"[N:1 - {rule.source_type} -> \"\n f\"{rule.typhoon_type}] Error in property \"\n f\"mapping \\\"{prop.name}\\\", \"\n f\"\\\"{comp_prop_name}\\\" property was not \"\n f\"found in the pattern matched \"\n f\"\\\"{comp_ref}\\\" component.\")\n continue\n dh.properties[prop.name] = component_property\n elif prop.prop_type in {\"str\", \"num\"}:\n dh.properties[prop.name] = prop.value\n else:\n # Function value\n func_name = prop.value\n func_params = {arg: matched_terminals[handle].parent_component\n for arg, handle in prop.params.items()}\n func_ret_val = \\\n getattr(self.user_lib, func_name)(**func_params)\n dh.properties[prop.name] = func_ret_val\n\n for term_name, term_props in rule.terminals.items():\n orig_terminal = matched_terminals.get(term_props[1], None)\n if orig_terminal is None:\n logging.warning(f\"[N:1 - {rule.source_type} -> \"\n f\"{rule.typhoon_type}] Error in terminal \"\n f\"mapping, \\\"{term_props[1]}\\\" terminal \"\n f\"was not found.\")\n\n continue\n terminal_obj = Terminal()\n terminal_obj.node_id = \\\n orig_terminal.parent_component.terminals[\n term_name[1]].node_id\n terminal_obj.index = orig_terminal.index\n terminal_obj.kind = term_props[0]\n terminal_obj.name = term_props[2]\n terminal_obj.position = orig_terminal.position\n terminal_obj.side = orig_terminal.side\n dh.terminals.append(terminal_obj)\n\n if dh.typhoon_type not in self.conversion_dict:\n self.conversion_dict[dh.typhoon_type] = []\n\n self.conversion_dict[dh.typhoon_type].append(dh)\n\n return dh\n\n def _convert_pattern(self, matched_terminals, rule):\n #\n # Subsystem pattern\n #\n if len(rule.components) > 0:\n return self._convert_sub_to_sub(matched_terminals, rule)\n #\n # N:1 conversion\n #\n else:\n return self._convert_sub_to_one(matched_terminals, rule)\n\n\n def convert(self):\n \"\"\"\n Converts all components in the netlist.\n\n Returns:\n converted_components (list): list of (Subsystem)DataHolders\n \"\"\"\n converted_components = []\n for rule in self.match_rules:\n if rule.pattern_match is True:\n components = []\n component = self._find_pattern(rule)\n while component:\n components.append(component)\n component = self._find_pattern(rule)\n if components:\n converted_components.append(components)\n elif rule.pattern_match is False:\n component = self._convert_one_to_n(rule)\n if component is not None:\n converted_components.append(component)\n\n for subsystem in self.conversion_dict[\"Subsystem\"]:\n subsystem.calculate_grid_dimensions()\n\n return converted_components\n\n def convert_schema(self, device_id, config_id, compile_model=False):\n import platform\n\n input_file_dir = self.input_file_path.split(os.path.sep)[:-1]\n # If the OS is Windows, the split input_file_path will\n # contain the drive letter without the path separator,\n # which is a problem when the path is joined again\n if platform.system() == \"Windows\":\n input_file_dir.insert(1, os.path.sep)\n\n self.detailed_log_path = os.path.join(*input_file_dir, \"conversion.log\")\n\n logging.basicConfig(filename=self.detailed_log_path,\n filemode=\"w\", level=logging.WARNING)\n\n self.report_path = None\n self.save_path = None\n self.converted = self.convert()\n self.save_schematic(device_id,\n config_id,\n compile_model)\n\n report_path = self.generate_report()\n return self.save_path, self.compiled, report_path\n\n def generate_report(self):\n \"\"\"\n Generates a conversion report file at the source file location.\n \"\"\"\n input_components = self.source_comp_dict_by_type.values()\n converted = []\n unconverted = []\n for component_list in input_components:\n for component in component_list:\n # Not reporting subsystem conversion\n if isinstance(component, Subsystem):\n break\n whitespace = 20 - len(component.name)\n if whitespace < 0:\n whitespace = 0\n component.whitespace = whitespace\n if component.converted:\n converted.append(component)\n else:\n unconverted.append(component)\n template_path = os.path.join(get_root_path(),\n \"converter\",\n \"app\",\n \"resources\",\n \"report_template.txt\")\n with open(template_path) as file_:\n template = Template(file_.read())\n\n save_path = self.input_file_path.split(os.path.sep)\n save_path[-1] = \"report.txt\"\n save_path[0] += os.path.sep\n save_path = os.path.join(*save_path)\n converted.sort(key=lambda x: x.type)\n unconverted.sort(key=lambda x: x.type)\n count = len(converted) + len(unconverted)\n with open(save_path, \"w\") as report_file:\n report_file.write(\n template.render(path_to_source=self.input_file_path,\n source_component_count=count,\n successful_conversions=converted,\n unsuccessful_conversions=unconverted,\n save_path=self.save_path))\n\n return save_path\n","repo_name":"typhoon-hil/model-converter","sub_path":"model_converter/converter/parsers/base_parser.py","file_name":"base_parser.py","file_ext":"py","file_size_in_byte":65978,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"8740134181","text":"# Problem 14\n# Longest Collatz sequence\n\nimport time\nstart = time.time()\n\ncountMax = 0\nnumMax = 0\nnumsSeen = {}\nnumRange = 1_000_000\n\nfor num in range(1,numRange):\n \n if num not in numsSeen or numsSeen[num] < 0:\n \n tempNum = num\n tempCount = 1\n\n while tempNum != 1:\n\n if tempNum % 2 == 0:\n tempNum /= 2\n\n elif tempNum % 2 == 1:\n tempNum = tempNum * 3 + 1\n \n if tempNum in numsSeen:\n if numsSeen[tempNum] > 0:\n tempCount += numsSeen[tempNum]\n break\n else:\n numsSeen[tempNum] = -1\n\n tempCount += 1\n \n numsSeen[num] = tempCount\n\n if tempCount > countMax:\n countMax = tempCount\n numMax = num\n\nprint(f'{numMax}: {tempCount}')\nprint(f'Done in {time.time() - start} seconds')","repo_name":"cavandervoort/Project-Euler-001-to-100","sub_path":"Euler_014.py","file_name":"Euler_014.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27417837049","text":"\ndef solve(arr):\n\n\t#in satck we can pop till value of top != -1 but as we are using 2 stacks in one arr, we \n\t#can't meet that condition here because if we try to do so we will end up deleting elem from \n\t#stack1. What we can do here is that we can store the min top values of stacks in a top array.\n\ttop = [4, 9]\n\t#top[0] -> initial value of top for stack 1\n\t#top[1] -> initial value of top for stack 2\n\t#and so on in case we need more stacks\n\t\n\t#lets pop 2 elem from stack1 and store it in temp array\n\toperations = ['d1', 'd1', 'd2', 'd2', ['i1', 55], ['i2', 99], 'p1', 'p2']\n\ttemp = []\n\n\tfor op in operations:\n\t\tif op[0] == 'd':\n\t\t\tindx = int(op[1])-1#-1 is done for converting top to 0 based index.\n\t\t\tx = arr.pop(top[indx])\n\t\t\ttemp.append(x)\n\t\t\t#decrese all the top value by 1 for all stacks that follwos current stack \n\t\t\tfor i in range(indx,len(top)):\n\t\t\t\ttop[i] -= 1\n\n\t\telif op[0] == 'p':\n\t\t\tindx = int(op[1])-1\n\t\t\tif indx == 0:\n\t\t\t\tprint(f'Number of elem in stack{indx+1} is {top[indx]+1}')\n\t\t\t\tfor i in range(top[indx]+1):\n\t\t\t\t\tprint(arr[i], end=' ')\n\t\t\telse:\n\t\t\t\tprint(f'Number of elem in stack{indx+1} is {top[indx]-top[indx-1]}')\n\t\t\t\tfor i in range(top[indx-1]+1, top[indx]+1):\n\t\t\t\t\tprint(arr[i], end=' ')\n\t\t\tprint()\n\t\telse:\n\t\t\t#as all delete operation is over we are printing its value\n\t\t\tindx = int(op[0][1])-1\n\t\t\tarr.insert(top[indx]+1, op[1])\n\t\t\tfor i in range(indx, len(top)):\n\t\t\t\ttop[i] += 1\n \n #printing deleted values in sorted order\n\ttemp.sort()\t\t\t\t\n\tprint('Deleted elements are: ')\n\tprint(*temp)\n\t\n\n#creating an array\narr = [8, 5, 7, 6, 4, 12, 15, 17, 16, 14]\n#calling function solve with arr as argument\nsolve(arr)\n","repo_name":"lokesh-lraj/A-helping-hand","sub_path":"multiple_stack.py","file_name":"multiple_stack.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23264802625","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom app.forms import studentForm\n\ndef student_input_view(request):\n sent=False\n if request.method=='POST':\n form=studentForm(request.POST)\n if form.is_valid():\n print('Form validation success')\n print('Name',form.cleaned_data['name'])\n print(\"Mark\",form.cleaned_data['mark'])\n sent=True\n form=studentForm()\n return render(request,'index.html',context={'form':form,'sent':sent})\n ","repo_name":"narendragolla1/Django","sub_path":"form_proj/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"944158921","text":"from bs4 import BeautifulSoup\nimport requests\nimport urllib\nimport time\n\nurlMain = 'http://bj.58.com/pbdn/0/'\n\nurl = 'http://bj.58.com/pingbandiannao/25669149490503x.shtml'\n# api = http://jst1.58.com/counter?infoid=25669149490503&userid=&uname=&sid=514968980&lid=1&px=512862527&cfpath=5,38484\n\nheader = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36'}\n\ndef get_count(url):\n usr_id = url.split('/')[-1].strip('x.shtml')\n api = 'http://jst1.58.com/counter?infoid={}'.format(usr_id)\n js = requests.get(api)\n print(js.text)\n views = js.text.split('=')[-1]\n print(views)\n return views\n\ndef get_info(url, header = None):\n web_data = requests.get(url, headers = header)\n soup = BeautifulSoup(web_data.text, 'lxml')\n\n title = soup.select('div.col_sub.mainTitle > h1')[0].text\n cate = soup.select('span.crb_i > a')[0].text\n time = soup.select('li.time')[0].text\n price = soup.select('div.su_con > span')[0].text\n quality = soup.select('div.su_con > span')[1].text.strip()\n region = soup.select('div.su_con > span.c_25d > a')[0].text if soup.find_all('span','c_25d') else None\n totalCount = get_count(url)\n\n data = {'title' : title,\n 'category' : cate,\n 'time' : time,\n 'price' : price,\n 'quality' : quality,\n 'region' : region,\n 'count' : totalCount}\n\n print(title)\n print(cate)\n print(time)\n print(price)\n print(quality)\n print(region)\n print(totalCount)\n return data\n\ndef get_root_page(url, header = None):\n web_data = requests.get(url, headers=header)\n soup = BeautifulSoup(web_data.text, 'lxml')\n\n links = soup.select('div.cleft > table.tbimg > tr > td.t > a.t')\n link_zz = soup.select('tr.zzinfo > td.t > a.t')\n\n urlSet = []\n for url in links:\n if url not in link_zz:\n urlSet.append(url.get('href').split('?')[0])\n\n return urlSet\n\ndef main_scrapy(url, header = None):\n urls = get_root_page(url, header)\n datas = []\n\n for url in urls:\n data = get_info(url, header)\n time.sleep(2)\n datas.append(data)\n print(datas)\n return datas\n\n\n\nget_info(url, header)\n# main_scrapy(urlMain, header = header)\n\n\n\n","repo_name":"guoyinwang/web-crawler-with-python","sub_path":"week1/week1_homework/answer_of_homework/web_crawler1.py","file_name":"web_crawler1.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"37747060363","text":"def get_period(day, N, backwards=False):\n backwards_flag = -1 if backwards else 1\n # get the list with in the timedelta format\n datelst = [\n datetime.strptime(day, '%Y-%m-%d') + backwards_flag \n * timedelta(days=x) for x in range(N)\n ]\n # convert the list to the string forrmat\n datelst = [x.strftime('%Y-%m-%d') for x in datelst]\n \n return datelst\n","repo_name":"groversalgo/snippets","sub_path":"dates_list.py","file_name":"dates_list.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14378196635","text":"# -*- coding:utf-8 -*-\n\n# terminal run: python setup.py install\n\nfrom distutils.core import setup, Extension\n\nMOD = \"test_module\" # defined in test_pyc_module.c\n# sources_list = [include called c files, use \",\" to split]\nsources_list = ['test_pyc_module.c','test_pyc.c', 'test_multip.c']\n\nsetup(name=MOD,\n version=\"0.1\",\n description=\"python c api test module\", \n ext_modules=[Extension(MOD, sources=sources_list)]\n )","repo_name":"xiaosimple/python_c_api_sample","sub_path":"setup.py","file_name":"setup.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":"36051636754","text":"from liczby_zespolone import Complex\nimport re\n\n\ndef menu():\n print(\"Which operation would you like to perform? (pick a number)\\n\"\n \"1. Addition\\n\"\n \"2. Subtraction\\n\"\n \"3. Multiplication\\n\"\n \"4. Division\\n\"\n \"5. Quit\\n\")\n opcode = int(input())\n while opcode not in range(1,6):\n opcode = int(input(\"Please select a number from 1 to 5\\n\"))\n if opcode == 5:\n exit(0)\n z1 = input(\"Enter the first complex number in the following format: a+bj\\n\")\n while not re.match(r'\\d+(\\.\\d*)?[\\+\\-]\\d+(.\\d*)?[ij]', z1):\n z1 = input(\"Incorrect format. Enter the number again in the following format: a+bj\\n\")\n z2 = input(\"Enter the second complex number in the following format: a+bj\\n\")\n while not re.match(r'\\d+(\\.\\d*)?[\\+\\-]\\d+(.\\d*)?[ij]', z2):\n z1 = input(\"Incorrect format. Enter the number again in the following format: a+bj\\n\")\n return z1, z2, opcode\n\nif __name__ == \"__main__\":\n while True:\n z1, z2, opcode = menu()\n if opcode == 1:\n result = Complex(z1) + Complex(z2)\n elif opcode == 2:\n result = Complex(z1) - Complex(z2)\n elif opcode == 3:\n result = Complex(z1) * Complex(z2)\n elif opcode == 4:\n result = Complex(z1) / Complex(z2)\n print(f\"\\nRESULT: {result}\\n\\n\")\n\n\n\n\n","repo_name":"harvastum/PwJS-PiLB","sub_path":"5/kalkulator.py","file_name":"kalkulator.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39935926807","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 28 21:03:50 2019\n\n@author: User\n\"\"\"\n\nimport shapefile #Import library shapefile\nsf = shapefile.Reader(\"soal1\") #Memanggil fungsi untuk membaca file PYSHP dengan nama soal1\nanu = sf.shapes() #Memanggil semua shapes yang telah dibaca dan mengkonversinya dengan bentuk array\nprint(anu[0].parts) #Mengelompokkan kumpulan point menjadi shapes\nsf.close() #Menutup reader pyshp","repo_name":"Sistem-Informasi-Geografi-2017/SIG-3B","sub_path":"src/2/1174050/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73189004324","text":"import time\n\nimport cv2\nimport v4l2\nimport arducam_mipicamera as arducam\n\nimport numpy as np\nimport math\n\n# init system\nprint('Creating camera object...')\ncamera = arducam.mipi_camera()\nprint(\"Initalizing camera...\")\ncamera.init_camera()\nprint(\"Setting mode...\")\ncamera.set_mode(0)\n\ncamera.set_control(v4l2.V4L2_CID_EXPOSURE,1000)\ncamera.set_control(v4l2.V4L2_CID_GAIN,0)\n\nfmt = camera.set_resolution(640,480)\n\n# first one is slow for some reason...\n# MyTime = time.time()\nframe = camera.capture(encoding = 'raw')\n# print('Raw Capture time: ' + str(time.time()-MyTime))\n\nIterations = 25\nTimeSum = 0\nfor i in range(Iterations):\n MyTime = time.time()\n frame = camera.capture(encoding = 'jpeg')\n TimeSum += time.time()-MyTime\nAvgTime = TimeSum/Iterations\nprint(\"Avg JPEG Capture Time: \" + str(AvgTime))\n# print(\"Sample JPEG length: \" + str(len(frame.data)))\n# print(\"JPEG data type: \" + str(type(frame.data)))\n\nTimeSum = 0\nfor i in range(Iterations):\n MyTime = time.time()\n frame = camera.capture(encoding = 'i420')\n TimeSum += time.time()-MyTime\nAvgTime = TimeSum/Iterations\nprint(\"Avg i420 Capture Time: \" + str(AvgTime))\n# print(\"Sample i420 length: \" + str(len(frame.data)))\n# print(\"i420 data type: \" + str(type(frame.data)))\n\nTimeSum = 0\nfor i in range(Iterations):\n MyTime = time.time()\n frame = camera.capture(encoding = 'raw')\n TimeSum += time.time()-MyTime\nAvgTime = TimeSum/Iterations\nprint(\"Avg raw Capture Time: \" + str(AvgTime))\n# print(\"Sample raw length: \" + str(len(frame.data)))\n# print(\"raw data type: \" + str(type(frame.data)))\n\n# Height = int(math.ceil(fmt[1]/16.0)*16)\n# Width = int(math.ceil(fmt[0]/32.0)*32)\n# Array = frame.as_array.reshape(Height,Width)\n# print(Array.shape)\n\ncamera.close_camera()","repo_name":"Mason-Schellenberg/MIPI_Camera","sub_path":"WebcamSpeedTest.py","file_name":"WebcamSpeedTest.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36586435652","text":"#!/usr/bin/env python3\n\nimport itertools\nimport numbers\nimport pathlib\nimport re\nimport sys\nimport textwrap\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nANY = slice(None)\n\ndef warn(message):\n sys.stderr.write(\"Warning: \" + message + \"\\n\")\n\ndef varying_levels(index):\n return {name for name, levels in zip(index.names, index.levels) if len(levels) > 1}\n\ndef enumerate_keys(index, names):\n # TODO: Only enumerate combinations that are actually used by the index.\n name_list = [name for name in index.names if name in names]\n dimensions = [list(levels) for name, levels in zip(index.names, index.levels) if name in names]\n return name_list, list(itertools.product(*dimensions))\n\ndef describe_key_value(name, value):\n pretty_name = name.replace('_', ' ')\n if isinstance(value, bool):\n return pretty_name if value else \"no \" + pretty_name\n elif isinstance(value, numbers.Number):\n return pretty_name + \" \" + str(value)\n else:\n return str(value)\n\ndef describe_key(names, key):\n parts = [describe_key_value(name, value) for name, value in zip(names, key)]\n return \", \".join([part for part in parts if part is not None])\n\ndef key_to_selector(index, names, key):\n return tuple([(key[names.index(name)] if name in names else ANY) for name in index.names])\n\n\nclass Data:\n subplot_font = {'fontsize': 11}\n\n def __init__(self, name, df):\n self.name = name\n self.df = df\n\n # job_levels = ['experiment', 'formula', 'event_rate', 'index_rate', 'strategy', 'processors', part']\n\n def select(self, experiment=ANY, formula=ANY, event_rate=ANY, index_rate=ANY, strategy=ANY, processors=ANY, part=ANY):\n view = self.df.loc[(experiment, formula, event_rate, index_rate, strategy, processors, part), :]\n return Data(self.name, view)\n\n def export(self, *columns, drop_levels=[], path=None):\n index = self.df.index.remove_unused_levels()\n key_levels = varying_levels(index) - set(drop_levels)\n unused_levels = set(index.names) - key_levels\n\n columns = self.df.columns.intersection(columns)\n result = self.df.loc[:, columns].copy()\n result.reset_index(list(unused_levels), drop=True, inplace=True)\n result.reset_index(inplace=True)\n\n if path is not None:\n result.to_csv(path, index=False)\n return result\n\n def plot(self, x_level, y_columns, series_levels=[], column_levels=[], box_plot=None, style='-o', title=None, path=None):\n if box_plot:\n df = self.df\n else:\n df = self.df.reset_index(level=x_level)\n\n y_columns = [y_columns] if isinstance(y_columns, str) else y_columns\n series_levels = set(series_levels)\n column_levels = set(column_levels)\n\n index = df.index.remove_unused_levels()\n levels = varying_levels(index)\n extra_levels = levels - series_levels - {x_level}\n if box_plot:\n extra_levels -= {box_plot}\n\n row_levels = extra_levels - column_levels\n column_levels = extra_levels & column_levels\n series_levels = levels & set(series_levels)\n\n row_level_list, row_keys = enumerate_keys(index, row_levels)\n column_level_list, column_keys = enumerate_keys(index, column_levels)\n series_level_list, series_keys = enumerate_keys(index, series_levels)\n plot_key_names = row_level_list + column_level_list\n series_key_names = plot_key_names + series_level_list\n\n if box_plot:\n series_key_names += [x_level]\n x_keys = list(index.levels[index.names.index(x_level)])\n\n nrows = len(row_keys)\n ncols = len(column_keys) * len(y_columns)\n figsize = (4.0 * ncols, 3.0 * nrows)\n fig, axes = plt.subplots(nrows, ncols, sharex='row', sharey='row', squeeze=False, figsize=figsize)\n if title is not None:\n fig.suptitle(title, y = 1 - 0.3 / figsize[1])\n\n lines = []\n for row, row_key in enumerate(row_keys):\n for col1, column_key in enumerate(column_keys):\n for col2, y_column in enumerate(y_columns):\n col = col1 * len(y_columns) + col2\n plot_key = row_key + column_key\n\n ax = axes[row, col]\n plot_title = describe_key(plot_key_names, plot_key)\n ax.set_title('\\n'.join(textwrap.wrap(plot_title, 40)), fontdict=self.subplot_font)\n ax.set_xlabel(x_level)\n ax.set_ylabel(y_column)\n\n lines = []\n for series in series_keys:\n if box_plot:\n samples = [df.loc[key_to_selector(index, series_key_names, plot_key + series + (x,)), y_column].values for x in x_keys]\n ax.boxplot(samples, labels=x_keys)\n else:\n selector = key_to_selector(index, series_key_names, plot_key + series)\n X = df.loc[selector, x_level]\n Y = df.loc[selector, y_column]\n lines += ax.plot(X, Y, style)\n\n if not box_plot:\n fig.legend(lines, map(lambda k: describe_key(series_level_list, k), series_keys), 'upper right')\n fig.tight_layout(pad=0.5, h_pad=1, w_pad=0.5, rect=[0, 0, 1 - 1 / figsize[0], 1 - 0.8 / figsize[1]])\n if path is not None:\n fig.savefig(path)\n return fig\n\n\nclass Loader:\n job_levels = ['experiment', 'formula', 'event_rate', 'index_rate', 'strategy', 'processors'] \n #add part, repetition and slice\n job_levels_full = job_levels + ['part', 'slice', 'repetition']\n\n log_levels = ['experiment', 'formula', 'event_rate', 'index_rate', 'strategy', 'part', 'processors']\n log_levels_full = ['experiment', 'formula', 'event_rate', 'index_rate', 'strategy', 'processors', 'part', 'slice']\n \n levels = ['experiment', 'formula', 'event_rate', 'index_rate', 'strategy', 'processors', 'part']\n\n\n job_regex = r\"(nokia|gen|genh|genadaptive)_(-S|-L|-T)_(\\d+)_(\\d+)_(\\d+)_(\\d+)\"\n slices_pattern = re.compile(job_regex)\n\n #_____part__slice\n log_regex = r\"(nokia|gen|genh|genadaptive)_(\\d+)_(-S|-L|-T)_(\\d+)_(\\d+)_part(\\d+)\"\n logs_pattern = re.compile(log_regex)\n\n num_cpus = [4, 8, 16]\n\n \n slices_header = ['baseline', 'merge', 'monitor', 'split']\n slices_header_full = slices_header + ['adaptive', 'overhead']\n \n slice_size_header_full = ['baseline_num','slice_num']\n\n slices_keys = []\n slices_data = []\n\n log_keys = []\n log_data = []\n\n def warn_skipped_path(self, path):\n #warn(\"Skipped \" + str(path))\n pass\n\n def warn_invalid_file(self, path):\n warn(\"Invalid data in file \" + str(path))\n\n def read_slices(self, key, path):\n try:\n df = pd.read_csv(path, header=0, sep=',\\s+', engine='python', index_col=[0,1])\n except Exception as e:\n raise Exception(\"Error while reading file \" + str(path)) from e\n\n \n if df.shape[0] > 0 and df.index.names == ['Part', 'Repetition'] and set(df.columns) >= {'Baseline0', 'Split0', 'Monitor0', 'Merge0'}:\n df.replace(to_replace='- ', inplace=True, method='ffill', value=0)\n df.replace(to_replace=' -', inplace=True, method='ffill', value=0)\n df.replace(to_replace='-', inplace=True, method='ffill', value=0)\n \n summary = df\n self.slices_keys.append(key)\n self.slices_data.append(summary)\n\n else:\n self.warn_invalid_file(path)\n \n def read_logs(self, key, path):\n for cpus in self.num_cpus:\n data=[]\n for c in range(0,cpus):\n tuple_num=int(os.popen('grep -o \"(\" ' + str(path.absolute()) + '_' + str(cpus) + '_slice' + str(c) + ' | wc -l').read())\n tuple_baseline_num=int(os.popen('grep -o \"(\" ' + str(path.absolute()) + '_' + str(cpus) + '_baseline_slice' + str(c) + ' | wc -l').read())\n data.append([tuple_baseline_num,tuple_num])\n \n data_df = pd.DataFrame(data, columns=self.slice_size_header_full)\n data_df.index.name = 'slice'\n self.log_keys.append((key[0], key[1], key[2], key[3], key[4], key[5], cpus))\n self.log_data.append(data_df)\n\n \n\n def read_file(self, path):\n #monitor times\n metrics_match = self.slices_pattern.fullmatch(path.name)\n if metrics_match:\n key = (\n metrics_match.group(1), # experiment\n metrics_match.group(2), # formula \n int(metrics_match.group(3)), # ER\n int(metrics_match.group(4)), # IR\n int(metrics_match.group(5)), # strategy\n int(metrics_match.group(6)) # numcpus\n )\n self.read_slices(key, path)\n return\n\n #slice sizes\n log_match = self.logs_pattern.fullmatch(path.name)\n if log_match:\n key = (\n log_match.group(1), # experiment\n log_match.group(3), # formula\n int(log_match.group(4)), # ER\n int(log_match.group(5)), # IR\n int(log_match.group(2)), # strategy\n int(log_match.group(6)) # part\n )\n self.read_logs(key, path)\n return\n\n self.warn_skipped_path(path)\n\n def read_files(self, path):\n if path.is_file():\n self.read_file(path)\n elif path.is_dir():\n for entry in path.iterdir():\n if entry.is_file():\n self.read_file(entry)\n else:\n self.warn_skipped_path(path)\n\n def max_memory(self, df):\n group_levels = list(df.index.names)\n group_levels.remove('monitor')\n return df.groupby(level=group_levels).max()\n\n def average_repetitions(self, df):\n group_levels = list(df.index.names)\n group_levels.remove('repetition')\n return df.groupby(level=group_levels).mean()\n\n def max_slice(self, df):\n group_levels = list(df.index.names)\n group_levels.remove('slice')\n return df.groupby(level=group_levels).max()\n\n def process(self):\n\n # Monitor times\n slices=pd.DataFrame([], columns=self.slices_header_full, index=pd.MultiIndex(levels=[[],[],[],[],[],[],[]], labels=[[],[],[],[],[],[],[]], names=self.levels))\n if len(self.slices_data) != 0:\n names = self.job_levels+['part', 'repetition']\n\n raw = pd.concat(self.slices_data, keys=self.slices_keys, names=self.job_levels, sort=True)\n raw.index.rename(names)\n\n raw=raw.drop(axis=0,labels=0,level=6)\n\n raw=raw.apply(pd.to_numeric)\n \n cpus = raw.index.levels[5].max()\n df_dict = {}\n for i in range(0,cpus):\n tmp = raw.loc[:, ['Baseline'+str(i), 'Merge'+str(i),'Monitor'+str(i),'Split'+str(i)]]\n tmp = tmp.rename(columns=dict(list(zip(tmp.columns.tolist(),self.slices_header))))\n df_dict[i]=tmp\n \n raw = pd.concat(df_dict.values(), keys=df_dict.keys(), axis=0, names=['slice']+names, sort=True)\n raw = raw.reorder_levels(self.job_levels_full)\n slices = raw.dropna(axis=0, how = 'all')\n slices = self.average_repetitions(slices)\n slices = self.max_slice(slices)\n slices['adaptive']=slices[['merge','monitor','split']].sum(axis=1)\n slices['overhead']=slices[['merge','split']].sum(axis=1)\n\n # Slice sizes\n slice_sizes=pd.DataFrame([], columns=self.slice_size_header_full, index=pd.MultiIndex(levels=[[],[],[],[],[],[],[]], labels=[[],[],[],[],[],[],[]], names=self.levels))\n if len(self.log_data) != 0:\n raw_slices = pd.concat(self.log_data, keys=self.log_keys, names=self.log_levels, sort=True)\n raw_slices=raw_slices.apply(pd.to_numeric)\n raw_slices = raw_slices.reorder_levels(self.log_levels_full)\n slice_sizes = self.max_slice(raw_slices)\n \n return (Data(\"Monitor times\", slices), Data(\"Slice sizes\", slice_sizes))\n\n @classmethod\n def load(cls, paths):\n loader = cls()\n for path in paths:\n loader.read_files(path)\n return loader.process()\n\n\nif __name__ == '__main__':\n if len(sys.argv) >= 2:\n paths = map(pathlib.Path, sys.argv[1:])\n (times,slices) = Loader.load(paths)\n\n #ADAPTIVE\n #Index: ['experiment', 'formula', 'event_rate', 'index_rate', 'strategy', 'processors', 'part']\n #Columns: ['baseline', 'merge', 'monitor', 'split', 'adaptive']\n\n # times\n gen_adapt_strat = times.select(experiment='genadaptive', part=2)\n gen_adapt_strat.plot('strategy', ['baseline', 'adaptive'], series_levels=['event_rate','index_rate'], column_levels=['formula'], title=\"Time x-strategy\" , path=\"gen_adapt_strat.pdf\")\n \n gen_adapt_nproc = times.select(experiment='genadaptive', part=2)\n gen_adapt_nproc.plot('processors', ['baseline', 'adaptive'], series_levels=['event_rate','index_rate'], column_levels=['formula'], title=\"Time x-processors\" , path=\"gen_adapt_nproc.pdf\")\n \n gen_adapt_strat.export('baseline', 'adaptive', 'overhead', path=\"gen_adapt_strat.csv\")\n\n # slices\n gen_adapt_size = slices.select(experiment='genadaptive', part=2)\n gen_adapt_size.plot('strategy', ['baseline_num', 'slice_num'], series_levels=['event_rate','index_rate'], column_levels=['formula'], title=\"Time x-strategy\" , path=\"gen_adapt_size.pdf\")\n \n gen_adapt_size.export('baseline_num', 'slice_num', path=\"gen_adapt_size.csv\")\n\n \n\n else:\n sys.stderr.write(\"Usage: {} path ...\\n\".format(sys.argv[0]))\n sys.exit(1)","repo_name":"emmahedvigpindhansen/flinkMonitor","sub_path":"evaluation/flinkless/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":14006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43375210261","text":"# Constraint Satisfaction Problem Class\n# Brendan Shaw, 2023\n# For use with the methods included in the GenericCSPProblem Class. \n# See MapColoringProblem and CircuitBoardProblem for example implementations\n\nimport copy\n\nclass CSP:\n # constructor\n def __init__(self, csp, inference=False):\n self.csp = csp\n self.assignment = {}\n self.inference = inference\n\n\n # Backtracking Algorithm\n def backtrack(self, domains=None):\n # if this is the first call, set the domains to all possible values\n if domains == None:\n domains = self.csp.get_domains()\n\n # If the assignment is complete, return it as a solution.\n if self.is_assignment_complete(self.assignment):\n return self.assignment\n\n # Select an unassigned variable using variable selection heuristics.\n variable = self.csp.choose_next_variable(self.assignment, domains)\n\n # Loop through the values in the domain of the selected variable\n for value in self.csp.get_domains(self.assignment, domains, variable):\n # Check if the assignment of the value to the variable is consistent with the rest of the assignment.\n if self.csp.is_consistent(self.assignment, variable, value):\n\n # Assign the value to the variable.\n self.assignment[variable] = value\n\n # If inference enabled: Recursively attempt to complete the assignment.\n if self.inference:\n # copy the domain for the recursive calls\n domains_copy = copy.deepcopy(domains)\n # edit the domain of the assigned variable\n domains_copy[variable] = [value]\n # call mac3 to edit domain\n inferences = self.MAC3(domains_copy, variable)\n # if these are all consistent, keep going\n if inferences: \n result = self.backtrack(domains_copy)\n else: \n result = None\n # if inference isn't enabled, call backtrack recursively again with the same domain\n else:\n result = self.backtrack(domains)\n\n # If a solution is found, return it.\n if result:\n return result\n\n # If no solution is found, undo the assignment.\n del self.assignment[variable]\n\n # If no solution is found, return None to indicate failure.\n return None\n\n def MAC3(self, domains, assigned_variable):\n # Initialize a queue for consistency checks\n queue = []\n\n # add all of the arcs from the neighbors of the variable to that variable\n for neighbor in self.csp.get_neighbors(assigned_variable):\n # if the neighbor isn't in the assignment already:\n if neighbor not in self.assignment:\n # add the tuple of the arc from neighbor to variable as a tuple\n queue.append((neighbor, assigned_variable))\n\n # while there are still items in the queue:\n while queue:\n # get the next variable assignment\n neighbor, assigned_variable = queue.pop() \n \n # if the neighbor's domain was changed\n if self.revise(domains, neighbor, assigned_variable):\n # if the domain is now empty after the change\n if not self.csp.get_domains(self.assignment, domains, neighbor): # If a domain becomes empty, return failure\n return False\n \n # otherwise, loop thorugh the neighbors, adding them to the queue to be edited as well\n for neighbor_neighbor in self.csp.get_neighbors(neighbor):\n # if the neighbor is not assigned (this includes assigned_variable):\n if neighbor_neighbor not in self.assignment:\n queue.append((neighbor_neighbor, neighbor))\n return True\n\n def revise(self, domains, neighbor, assigned_variable):\n # starts at false\n revised = False\n\n # for each value in the domain of the neighbor (D_i)\n neighbor_values = list(self.csp.get_domains(self.assignment, domains, neighbor))\n for neighbor_value in neighbor_values:\n # for each value in the domain of the variable\n consistent = False\n for value in self.csp.get_domains(self.assignment, domains, assigned_variable):\n\n # if that variable doesn't satisfy the constraint\n if self.csp.is_consistent({neighbor:neighbor_value}, assigned_variable, value):\n consistent = True\n break\n if not consistent:\n domains[neighbor].remove(neighbor_value) # Remove inconsistent values from the domain\n revised = True\n\n return revised\n\n # returns true if all the variables have been assigned\n def is_assignment_complete(self, assignment): \n # if the length of the assignment is the same as the number of countries\n if len(assignment) == len(self.csp.get_variables()): \n return True\n return False","repo_name":"brendanshaw14/CS-76-Projects","sub_path":"CSP/CSP.py","file_name":"CSP.py","file_ext":"py","file_size_in_byte":5237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"39492292097","text":"'''\nTo help debug issues\nOne off functions that are temporarily used\n'''\nimport pandas as pd\nimport pprint\nimport logging\n\npp = pprint.PrettyPrinter(indent=4)\n\nlog = logging.getLogger(__name__)\n\n\ndef debug_dataframe(\n df: pd.DataFrame,\n msg,\n nrows=5,\n usecols=None,\n # **kwargs\n):\n '''\n Help diagnose issues with dataframes\n '''\n # pd.set_option('display.max_rows', 200)\n # pd.set_option('display.max_colwidth', -1)\n # verbose=True\n intro = \"\"\"\n === Debug dataframe : {msg} ===\n \"\"\"\n log.debug(intro.format(msg=msg))\n log.debug(df.info())\n # log.debug(df.columns)\n log.debug(pp.pformat(df.dtypes))\n with pd.option_context('float_format', '{:f}'.format):\n sdf = df\n if usecols:\n sdf = df[usecols]\n print(sdf.head(nrows, ))\n # log.debug(sdf.head(nrows, ))\n\n# https://stackoverflow.com/questions/52686559/read-csv-get-the-line-where-exception-occured\ndef read_csv_debug(fields, fd, *args, first_try=True, **kwargs):\n \"\"\"\n Help debugging dataframe loading errors (with dtypes/converters)\n chunksize: number of lines to read\n first_try:\n # with chunksize Return TextFileReader object for iteration\n\n WARNING: be careful when using\n \"\"\"\n\n chunksize = kwargs.get(\"chunksize\")\n\n if first_try:\n kwargs.pop(\"chunksize\", None)\n\n parse_dates = kwargs.get('parse_dates', [])\n\n if parse_dates != []:\n print(\"WARNING: adding parsed dates to used columns\")\n\n # print(kwargs.get(\"dtype\"))\n\n for field in fields:\n print(\"TESTING field %s (first_try ? %s ) \" % (field, first_try))\n # dtype might be absent because field has a converter\n print(\"dtype: \", kwargs.get(\"dtype\").get(field, \"not present\"))\n try:\n res = pd.read_csv(\n fd,\n *args,\n usecols=[field] + parse_dates,\n **kwargs\n )\n if chunksize is not None:\n print(\"chunk of size\", chunksize)\n for i, chunk in enumerate(res):\n # print(\"chunk %d\" % i)\n print(chunk)\n except TypeError as e:\n # TODO retry with chunksize\n if first_try:\n kwargs.update({\"chunksize\": chunksize or 40})\n fd.seek(0)\n read_csv_debug([field], fd, *args, first_try=False, **kwargs)\n else:\n print(fd.readlines(chunksize))\n raise e\n\n finally:\n fd.seek(0)\n\n\n\n# def save_dataframe_to_xls():\n # if log level >= DEBUG then save to xls too !\n # if True:\n # filename = cachename + \".xls\"\n # logging.debug(\"Saved a debug excel copy at %s\" % filename)\n # merged_df.to_excel(filename)\n","repo_name":"teto/pymptcpanalyzer","sub_path":"mptcpanalyzer/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"52"} +{"seq_id":"13300475040","text":"# -*- coding: utf-8 -*-\n\nfrom b3j0f.utils.ut import UTCase\nfrom mock import MagicMock, Mock\nfrom unittest import main\n\nfrom link.middleware.core import Middleware\nfrom link.feature import Feature, addfeatures\n\nfrom link.dbrequest.lazy import Query, Procedure\nfrom link.dbrequest.manager import QueryManager\n\nfrom link.dbrequest.comparison import C\nfrom link.dbrequest.assignment import A\nfrom link.dbrequest.expression import E, F\n\nfrom link.dbrequest.ast import AST\nfrom link.dbrequest.ast import ASTSingleStatementError\nfrom link.dbrequest.ast import ASTLastStatementError\nfrom link.dbrequest.ast import ASTInvalidStatementError\nfrom link.dbrequest.ast import ASTInvalidFormatError\n\n\nclass QueryManagerTest(UTCase):\n def setUp(self):\n self.inserted_doc = {'_id': 'some id', 'foo': 'bar'}\n\n self.feature = Mock()\n\n featurecls = MagicMock(return_value=self.feature)\n featurecls.__class__ = type\n featurecls.name = 'query'\n featurecls.mro = MagicMock(return_value=[Feature])\n\n cls = type('DummyDriver', (Middleware,), {})\n cls = addfeatures([featurecls])(cls)\n\n self.query = QueryManager()\n self.query.set_child_middleware(cls())\n\n def test_all(self):\n q = self.query.all()\n\n self.assertIsInstance(q, Query)\n self.assertEqual(q.ast, [])\n self.assertIs(q.manager, self.query)\n\n def test_from_ast(self):\n expected = [\n AST(\n 'filter',\n AST(\n 'cond_eq', [\n AST('prop', 'foo'),\n AST('val', 'bar')\n ]\n )\n )\n ]\n\n attrs = {\n 'find_elements.return_value': []\n }\n self.feature.configure_mock(**attrs)\n\n q = self.query.from_ast(expected)\n\n self.assertIsInstance(q, Query)\n self.assertEqual(q.ast, expected)\n\n list(q)\n\n self.feature.find_elements.assert_called_with(expected)\n\n def test_to_ast(self):\n expected = [\n {\n 'name': 'filter',\n 'val': {\n 'name': 'cond_eq',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': 'bar'\n }\n ]\n }\n }\n ]\n\n q = self.query.all().filter(C('foo') == 'bar')\n\n self.assertEqual(q.to_ast(), expected)\n\n def test_validate_ast(self):\n with self.assertRaises(ASTSingleStatementError):\n self.query.validate_ast(AST('not_get_or_create_or_run', 'unused'))\n\n for stmt in ['update', 'delete', 'get', 'count', 'group']:\n with self.assertRaises(ASTLastStatementError):\n self.query.validate_ast([\n AST(stmt, 'unused'),\n AST('unused', 'unused')\n ])\n\n with self.assertRaises(ASTInvalidStatementError):\n self.query.validate_ast([\n AST('unknown', 'unused')\n ])\n\n with self.assertRaises(ASTInvalidFormatError):\n self.query.validate_ast('invalid format')\n\n self.query.validate_ast([\n AST('filter', 'unused'),\n AST('update', 'unused')\n ])\n\n def test_manager_get_none(self):\n attrs = {\n 'find_elements.return_value': []\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.get(C('foo'))\n\n self.assertIsNone(result)\n\n self.feature.find_elements.assert_called_with({\n 'name': 'cond_exists',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': True\n }\n ]\n })\n\n def test_manager_get_one(self):\n expected = {'foo': 'bar'}\n attrs = {\n 'find_elements.return_value': [expected]\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.get(C('foo'))\n\n self.assertEqual(result, expected)\n\n self.feature.find_elements.assert_called_with({\n 'name': 'cond_exists',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': True\n }\n ]\n })\n\n def test_manager_create(self):\n expected = {'_id': 'some id', 'foo': 'bar'}\n attrs = {\n 'put_element.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.create(A('foo', 'bar'))\n\n self.assertEqual(result, expected)\n\n self.feature.put_element.assert_called_with([{\n 'name': 'assign',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': 'bar'\n }\n ]\n }])\n\n def test_query_copy(self):\n q1 = self.query.all()\n q2 = q1.copy()\n\n self.assertIsInstance(q1, Query)\n self.assertIsInstance(q2, Query)\n self.assertIsNot(q1, q2)\n\n self.assertIs(q1.manager, q2.manager)\n self.assertEqual(q1.ast, q2.ast)\n\n def test_query_count(self):\n attrs = {\n 'count_elements.return_value': 3\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().filter(C('foo') == 'bar').count()\n\n self.assertEqual(result, 3)\n\n self.feature.count_elements.assert_called_with([{\n 'name': 'filter',\n 'val': {\n 'name': 'cond_eq',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': 'bar'\n }\n ]\n }\n }])\n\n def test_query_get_none(self):\n attrs = {\n 'find_elements.return_value': []\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().get(C('foo'))\n\n self.assertIsNone(result)\n\n self.feature.find_elements.assert_called_with([\n {\n 'name': 'get',\n 'val': {\n 'name': 'cond_exists',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': True\n }\n ]\n }\n }\n ])\n\n def test_query_get_one(self):\n expected = {'foo': 'bar'}\n attrs = {\n 'find_elements.return_value': [expected]\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().get(C('foo'))\n\n self.assertEqual(result, expected)\n\n self.feature.find_elements.assert_called_with([\n {\n 'name': 'get',\n 'val': {\n 'name': 'cond_exists',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': True\n }\n ]\n }\n }\n ])\n\n def test_query_filter(self):\n expected = [\n {'_id': 'some id 1', 'foo': 'bar'},\n {'_id': 'some id 2', 'foo': 'bar'},\n {'_id': 'some id 3', 'foo': 'bar'}\n ]\n attrs = {\n 'find_elements.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().filter(C('foo') == 'bar')\n\n self.assertIsInstance(result, Query)\n\n result = list(result)\n self.assertEqual(result, expected)\n\n self.feature.find_elements.assert_called_with([\n {\n 'name': 'filter',\n 'val': {\n 'name': 'cond_eq',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': 'bar'\n }\n ]\n }\n }\n ])\n\n def test_query_exclude(self):\n expected = [\n {'_id': 'some id 1', 'foo': 'baz'},\n {'_id': 'some id 2', 'foo': 'baz'},\n {'_id': 'some id 3', 'foo': 'baz'}\n ]\n attrs = {\n 'find_elements.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().exclude(C('foo') == 'bar')\n\n self.assertIsInstance(result, Query)\n\n result = list(result)\n self.assertEqual(result, expected)\n\n self.feature.find_elements.assert_called_with([\n {\n 'name': 'exclude',\n 'val': {\n 'name': 'cond_eq',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': 'bar'\n }\n ]\n }\n }\n ])\n\n def test_query_slice(self):\n expected = [\n {'_id': 'some id 2', 'foo': 'bar'},\n {'_id': 'some id 3', 'foo': 'bar'}\n ]\n attrs = {\n 'find_elements.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all()[1:2]\n\n self.assertIsInstance(result, Query)\n\n result = list(result)\n self.assertEqual(result, expected)\n\n self.feature.find_elements.assert_called_with([\n {\n 'name': 'slice',\n 'val': slice(1, 2)\n }\n ])\n\n def test_query_cache(self):\n expected = [\n {'_id': 'some id 1', 'foo': 'bar'},\n {'_id': 'some id 2', 'foo': 'bar'},\n {'_id': 'some id 3', 'foo': 'bar'}\n ]\n attrs = {\n 'find_elements.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n query = self.query.all()\n\n self.assertIsInstance(query, Query)\n\n result1 = list(query)\n self.assertEqual(result1, expected)\n\n result2 = list(query)\n self.assertEqual(result2, expected)\n\n self.feature.find_elements.assert_called_once_with([])\n\n def test_query_update(self):\n attrs = {\n 'update_elements.return_value': 3\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().update(A('foo', 'bar'))\n\n self.assertEqual(result, 3)\n self.feature.update_elements.assert_called_with([], [\n {\n 'name': 'assign',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'val',\n 'val': 'bar'\n }\n ]\n }\n ])\n\n def test_query_delete(self):\n attrs = {\n 'remove_elements.return_value': 3\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().delete()\n\n self.assertEqual(result, 3)\n self.feature.remove_elements.assert_called_with([])\n\n def test_query_group(self):\n expected = {'foo': ['bar', 'baz', 'biz']}\n attrs = {\n 'find_elements.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n result = self.query.all().group('foo', F('sum', E('bar')))\n\n self.assertEqual(result, expected)\n\n self.feature.find_elements.assert_called_with([\n {\n 'name': 'group',\n 'val': [\n {\n 'name': 'prop',\n 'val': 'foo'\n },\n {\n 'name': 'func_sum',\n 'val': [\n {\n 'name': 'ref',\n 'val': 'bar'\n }\n ]\n }\n ]\n }\n ])\n\n def test_scoped_query(self):\n q1 = self.query.all()\n self.assertEqual(q1.scope, [])\n\n q2 = self.query.subset(q1)\n self.assertEqual(q2.scope, [q1])\n\n def test_procedure(self):\n f = F('sum')\n q = self.query.all()\n p = self.query.prepare(f, q)\n\n self.assertIsInstance(p, Procedure)\n self.assertIs(p.manager, self.query)\n self.assertIs(p.f, f)\n self.assertEqual(p.scope, [q])\n\n def test_run(self):\n expected = 'result'\n attrs = {\n 'run_procedure.return_value': expected\n }\n self.feature.configure_mock(**attrs)\n\n q = self.query.all()\n ret = self.query.run(F('sum'), q)\n\n self.assertEqual(ret, expected)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"linkdd/link.dbrequest","sub_path":"link/dbrequest/test/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":13920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4599269053","text":"# coding=utf-8\n\"\"\"\"Tests for client module API\n\n.. note:: This program is free software; you can redistribute it and/or modify\n it under the terms of the Mozilla Public License 2.0.\n\n\"\"\"\n\n__author__ = 'elpaso@itopen.it'\n__date__ = '2019-06-03'\n__copyright__ = 'Copyright 2019, Gis3w'\n\nimport os\nimport json\nfrom django.conf import settings\nfrom django.urls import reverse\nfrom django.test import override_settings\nfrom django.core.files import File\nfrom django.core.cache import caches\nfrom guardian.shortcuts import remove_perm\nfrom qdjango.models import Project\nfrom qdjango.utils.data import QgisProject\nfrom core.tests.base import CoreTestBase\nfrom core.models import MacroGroup, Group, G3WSpatialRefSys\nfrom core.utils.structure import FIELD_TYPES_MAPPING\nfrom qdjango.models import Widget, WIDGET_TYPES\nfrom qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransformContext\n\n# Re-use test data from qdjango module\nPROJECTS_PATH = os.path.join(os.getcwd(), 'qdjango', 'tests', 'data')\nDATASOURCE_PATH = f'{PROJECTS_PATH}/geodata'\nQGS310_FILE = 'g3wsuite_project_test_qgis310.qgs'\nQGS310_FILE_1A = 'g3wsuite_project_test_qgis310_2.qgs'\nQGS310_FILE_1 = 'edit-widget_g3w-suite-project-test.qgs'\nQGS310_FILE_2 = 'init_extent_max_extent test_qgis310.qgs'\nQGS310_FILE_3 = 'gruppo-1_custom_layer_order_qgis316.qgs'\nQGS310_FILE_4 = 'gruppo-1_empty_vector_layer316.qgs'\n\n@override_settings(MEDIA_ROOT=PROJECTS_PATH)\n@override_settings(DATASOURCE_PATH=DATASOURCE_PATH)\nclass ClientApiTest(CoreTestBase):\n \"\"\"Test client API\"\"\"\n\n # These are stored in core module\n fixtures = CoreTestBase.fixtures + [\n # except for this one which is in qdjango:\n \"G3WSampleProjectAndGroup.json\",\n ]\n\n @classmethod\n def setUpClass(cls):\n super(ClientApiTest, cls).setUpClass()\n\n # Fill the cache with getprojectsettings response so we don't need a QGIS instance running\n # TODO: eventually move to QgsServer\n cls.prj_test = Project.objects.get(title='Un progetto')\n\n # new properties has to save before caching, signal on svaing project invalidate cache['django']\n\n cls.prj_test.thumbnail = '/fake/project.png'\n cls.prj_test.save()\n\n # create a group print for follow project\n cls.print_group = Group(\n name='Print Group', title='Print Group', header_logo_img='', srid=cls.prj_test.group.srid)\n cls.print_group.save()\n\n qgis_project_file_print = File(open('{}/{}'.format(PROJECTS_PATH, QGS310_FILE), 'r'))\n cls.project_print310 = QgisProject(qgis_project_file_print)\n cls.project_print310.group = cls.print_group\n cls.project_print310.save()\n\n qgis_project_file_print_1a = File(open('{}/{}'.format(PROJECTS_PATH, QGS310_FILE_1A), 'r'))\n cls.project_print310_1a = QgisProject(qgis_project_file_print_1a)\n cls.project_print310_1a.group = cls.print_group\n cls.project_print310_1a.save()\n\n cache_key = settings.QDJANGO_PRJ_CACHE_KEY.format(cls.prj_test.pk)\n cache = caches['qdjango']\n cache.set(cache_key, open(os.path.join(PROJECTS_PATH, 'getProjectSettings_gruppo-1_un-progetto_qgis310.xml'),\n 'rb').read())\n\n cache_key = settings.QDJANGO_PRJ_CACHE_KEY.format(cls.project_print310.instance.pk)\n cache.set(cache_key, open(os.path.join(PROJECTS_PATH, 'getProjectSettings_g3wsuite_project_test_qgis310.xml'),\n 'rb').read())\n\n qgis_project_file_1 = File(open('{}/{}'.format(PROJECTS_PATH, QGS310_FILE_1), 'r'))\n cls.project_print310_1 = QgisProject(qgis_project_file_1)\n cls.project_print310_1.group = cls.print_group\n cls.project_print310_1.save()\n qgis_project_file_1.close()\n\n cls.extent_group = Group(\n name='Extent Group', title='Extent Group', header_logo_img='', srid=G3WSpatialRefSys.objects.get(srid=32633))\n cls.extent_group.save()\n qgis_project_file_2 = File(open('{}/{}'.format(PROJECTS_PATH, QGS310_FILE_2), 'r'))\n cls.project_extent310_2 = QgisProject(qgis_project_file_2)\n cls.project_extent310_2.group = cls.extent_group\n cls.project_extent310_2.save()\n qgis_project_file_2.close()\n\n cls.custom_order_layer_group = Group(\n name='Custom Order Layer Group', title='Custom Order Layer Group', header_logo_img='',\n srid=G3WSpatialRefSys.objects.get(srid=4326))\n cls.custom_order_layer_group.save()\n qgis_project_file_3 = File(open('{}/{}'.format(PROJECTS_PATH, QGS310_FILE_3), 'r'))\n cls.project_extent316_1 = QgisProject(qgis_project_file_3)\n cls.project_extent316_1.group = cls.custom_order_layer_group\n cls.project_extent316_1.save()\n qgis_project_file_3.close()\n\n cls.empty_vector_layer_layer_group = Group(\n name='Empty vector layer Layer Group', title='Empty vector layer Layer Group', header_logo_img='',\n srid=G3WSpatialRefSys.objects.get(srid=4326))\n cls.empty_vector_layer_layer_group.save()\n qgis_project_file_4 = File(open('{}/{}'.format(PROJECTS_PATH, QGS310_FILE_4), 'r'))\n cls.project_extent316_2 = QgisProject(qgis_project_file_4)\n cls.project_extent316_2.group = cls.empty_vector_layer_layer_group\n cls.project_extent316_2.save()\n qgis_project_file_4.close()\n\n @override_settings(VENDOR_KEYS={'google': '123456789'})\n def testGroupConfigApiView(self):\n \"\"\"Test call to config\"\"\"\n\n response = self._testApiCall('group-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n self.assertEqual(resp[\"vectorurl\"], \"/vector/api/\")\n self.assertEqual(resp[\"group\"][\"crs\"], {\n 'epsg': 4326,\n 'proj4': '+proj=longlat +datum=WGS84 +no_defs',\n 'geographic': True,\n 'axisinverted': True,\n 'extent': [-180.0, -90.0, 180.0, 90.0]\n })\n print(resp[\"group\"][\"mapcontrols\"])\n self.assertEqual(resp[\"group\"][\"mapcontrols\"], ['zoom', 'zoombox', 'zoomtoextent', 'query', 'querybbox', 'querybypolygon', 'overview', 'scaleline', 'geolocation', 'streetview', 'nominatim', 'addlayers', 'length', 'area', 'mouseposition', 'scale'])\n self.assertEqual(resp[\"group\"][\"header_logo_img\"], \"logo_img/qgis-logo.png\")\n self.assertEqual(resp[\"group\"][\"name\"], \"Gruppo 1\")\n self.assertIsNone(resp[\"group\"][\"header_logo_link\"])\n self.assertEqual(resp[\"group\"][\"initproject\"], \"qdjango:1\")\n self.assertEqual(resp[\"group\"][\"header_terms_of_use_link\"], \"\")\n self.assertTrue(resp[\"group\"][\"powered_by\"])\n self.assertEqual(resp[\"group\"][\"baselayers\"], [{'crs': {'epsg': 3857, 'proj4': '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs', 'geographic': False, 'axisinverted': False}, 'servertype': 'OSM', 'attribution': \"OpenStreetMap contributors\", 'name': 'OpenStreetMap', 'title': 'OSM', 'scalebasedvisibility': False, 'maxscale': 0, 'minscale': 100000000, 'id': 3, 'icon': None}])\n self.assertEqual(resp[\"group\"][\"header_terms_of_use_text\"], \"\")\n self.assertEqual(resp[\"group\"][\"header_custom_links\"], [])\n self.assertEqual(resp[\"group\"][\"background_color\"], \"#ffffff\")\n self.assertEqual(resp[\"group\"][\"id\"], 1)\n self.assertEqual(resp[\"group\"][\"slug\"], 'gruppo-1')\n self.assertEqual(len(resp[\"group\"][\"projects\"]), 1)\n\n self.assertIn('vendorkeys', resp[\"group\"])\n self.assertEqual(resp[\"group\"][\"vendorkeys\"], {'google': '123456789'})\n\n project = resp[\"group\"][\"projects\"][0]\n to_compare = {'description': '

progetto 1

', 'title': 'Un progetto',\n 'thumbnail': '/fake/project.png', 'gid': 'qdjango:1', 'type': 'qdjango', 'id': 1}\n for k in list(to_compare.keys()):\n self.assertEqual(project[k], to_compare[k])\n\n self.assertIsNone(resp[\"group\"][\"overviewproject\"])\n self.assertIsNone(resp[\"main_map_title\"])\n self.assertEqual(resp[\"mediaurl\"], \"/media/\")\n self.assertEqual(resp[\"baseurl\"], \"/\")\n self.assertEqual(resp[\"vectorurl\"], \"/vector/api/\")\n self.assertEqual(resp[\"rasterurl\"], \"/raster/api/\")\n self.assertEqual(resp[\"proxyurl\"], reverse('interface-proxy'))\n self.assertEqual(resp[\"credits\"], \"/en/credits/\")\n self.assertEqual(resp[\"client\"], \"client/\")\n self.assertEqual(resp[\"staticurl\"], \"/static/\")\n self.assertEqual(resp[\"user\"][\"username\"], \"admin01\")\n self.assertEqual(resp[\"user\"][\"first_name\"], \"\")\n self.assertEqual(resp[\"user\"][\"last_name\"], \"\")\n self.assertEqual(resp[\"user\"][\"admin_url\"], \"/en/\")\n self.assertEqual(resp[\"user\"][\"logout_url\"], \"/en/logout/?next=/en/map/gruppo-1/qdjango/1/\")\n self.assertEqual(resp[\"user\"][\"login_url\"], \"/en/login/?next=/en/map/gruppo-1/qdjango/1/\")\n self.assertEqual(resp[\"user\"][\"groups\"], [])\n self.assertEqual(resp[\"user\"][\"i18n\"], \"en\")\n self.assertEqual(resp[\"g3wsuite_logo_img\"], \"g3wsuite_logo_h40.png\")\n self.assertEqual(resp['i18n'], json.loads(json.dumps(settings.LANGUAGES)))\n\n # Test GroupIsActivePermission\n # ------------------------------------------------------------\n\n g = Group.objects.get(slug='gruppo-1')\n g.is_active = False\n g.save()\n\n self.client.login(username=self.test_admin1.username, password=self.test_admin1.username)\n url = reverse('group-map-config', args=['gruppo-1', 'qdjango', '1'])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, 403)\n\n self.client.logout()\n\n # Restore group\n g.is_active = True\n g.save()\n\n\n def testClientConfigApiView(self):\n \"\"\"Test call to project config\"\"\"\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n\n self.assertEqual(resp[\"layerstree\"], [\n {'visible': True, 'expanded': False, 'name': 'spatialite_points',\n 'id': 'spatialite_points20190604101052075'},\n {'visible': True, 'expanded': False, 'name': 'world', 'id': 'world20181008111156525'},\n {'visible': True, 'expanded': True, 'name': 'bluemarble', 'id': 'bluemarble20181008111156906'}])\n self.assertEqual(resp[\"search\"], [])\n self.assertFalse(resp[\"wms_use_layer_ids\"])\n self.assertEqual(resp[\"qgis_version\"], \"2.18.16\")\n self.assertEqual(resp[\"feature_count\"], 5)\n self.assertEqual(resp[\"widget\"], [])\n self.assertEqual(resp[\"relations\"], [])\n self.assertEqual(resp[\"id\"], 1)\n self.assertEqual(resp[\"initextent\"], [-189.0, -130.14542038524587, 189.0, 123.92015338524588])\n self.assertEqual(resp[\"extent\"], [-189.0, -130.14542038524587, 189.0, 123.92015338524588])\n self.assertEqual(resp[\"ows_method\"], \"GET\")\n self.assertEqual(resp[\"print\"], [])\n self.assertEqual(resp[\"querymultilayers\"], ['query', 'querybbox', 'querybypolygon'])\n self.assertFalse(resp[\"context_base_legend\"])\n self.assertEqual(resp[\"initbaselayer\"], 3)\n self.assertEqual(resp[\"metadata\"][\"accessconstraints\"], \"copyright\")\n self.assertEqual(resp[\"metadata\"][\"name\"], \"WMS\")\n self.assertEqual(resp[\"metadata\"][\"title\"], \"Yet another WMS serving anything\")\n self.assertEqual(resp[\"metadata\"][\"abstract\"], \"Lorem ipsum sit amet\")\n self.assertEqual(resp[\"metadata\"][\"contactinformation\"][\"contactelectronicmailaddress\"], \"mail@email.com\")\n self.assertEqual(resp[\"metadata\"][\"contactinformation\"][\"contactvoicetelephone\"], \"1234578\")\n #self.assertEqual(resp[\"metadata\"][\"wms_url\"], \"\")\n self.assertEqual(resp[\"metadata\"][\"fees\"], \"no conditions apply\")\n self.assertEqual(resp[\"metadata\"][\"keywords\"], ['keyword1', 'keyword2'])\n self.assertEqual(resp[\"thumbnail\"], '/media/fake/project.png')\n self.assertEqual(resp[\"name\"], \"Un progetto\")\n self.assertEqual(resp[\"search_endpoint\"], 'ows')\n\n # test for tab_toc_default\n self.assertTrue(resp[\"toc_tab_default\"], 'layers')\n\n # check for layers and fields\n self.assertEqual(len(resp['layers']), 3)\n for l in resp['layers']:\n if l['id'] == 'world20181008111156525':\n\n # check fields\n self.assertEqual(len(l['fields']), 5)\n self.assertEqual([\n {'name': 'NAME', 'type': FIELD_TYPES_MAPPING['QSTRING'], 'label': 'NAME', 'show': True},\n {'name': 'CAPITAL', 'type': FIELD_TYPES_MAPPING['QSTRING'], 'label': 'CAPITAL', 'show': True},\n {'name': 'APPROX', 'type': FIELD_TYPES_MAPPING['QLONGLONG'], 'label': 'APPROX', 'show': True},\n {'name': 'AREA', 'type': FIELD_TYPES_MAPPING['DOUBLE'], 'label': 'AREA', 'show': True},\n {'name': 'SOURCETHM', 'type': FIELD_TYPES_MAPPING['QSTRING'], 'label': 'SOURCETHM', 'show': True}]\n , l['fields'])\n\n # capabilities\n self.assertEqual(l['capabilities'], settings.QUERYABLE | settings.FILTRABLE)\n\n # bbox\n self.assertAlmostEqual(l['bbox']['minx'], -180, 4)\n self.assertAlmostEqual(l['bbox']['miny'], -89.90000000000000568, 4)\n self.assertAlmostEqual(l['bbox']['maxx'], 180, 4)\n self.assertAlmostEqual(l['bbox']['maxy'], 83.67473300000000336, 4)\n\n # metadata\n metadata_expected = {\n \"title\": \"world\",\n \"attributes\": [\n {\n \"name\": \"NAME\",\n \"typeName\": \"String\",\n \"comment\": \"\",\n \"length\": 40,\n \"precision\": 0,\n \"type\": \"QString\",\n \"alias\": \"\"\n },\n {\n \"name\": \"CAPITAL\",\n \"typeName\": \"String\",\n \"comment\": \"\",\n \"length\": 64,\n \"precision\": 0,\n \"type\": \"QString\",\n \"alias\": \"\"\n },\n {\n \"name\": \"APPROX\",\n \"typeName\": \"Integer64\",\n \"comment\": \"\",\n \"length\": 15,\n \"precision\": 0,\n \"type\": \"qlonglong\",\n \"alias\": \"\"\n },\n {\n \"name\": \"AREA\",\n \"typeName\": \"Real\",\n \"comment\": \"\",\n \"length\": 19,\n \"precision\": 15,\n \"type\": \"double\",\n \"alias\": \"\"\n },\n {\n \"name\": \"SOURCETHM\",\n \"typeName\": \"String\",\n \"comment\": \"\",\n \"length\": 16,\n \"precision\": 0,\n \"type\": \"QString\",\n \"alias\": \"\"\n }\n ],\n \"crs\": [\n\n ],\n \"dataurl\": {\n\n },\n \"metadataurl\": {\n\n },\n \"attribution\": {\n\n }\n }\n\n self.assertEqual(l['metadata'], metadata_expected)\n\n # crs\n self.assertEqual(l['crs'], {\n 'epsg': 4326,\n 'proj4': '+proj=longlat +datum=WGS84 +no_defs',\n 'geographic': True,\n 'axisinverted': True,\n 'extent': [-180.0, -90.0, 180.0, 90.0]\n })\n\n if l['id'] == 'spatialite_points20190604101052075':\n\n # check fields\n self.assertEqual(len(l['fields']), 2)\n self.assertEqual([\n {'name': 'pkuid', 'type': FIELD_TYPES_MAPPING['QLONGLONG'], 'label': 'pkuid', 'show': True},\n {'name': 'name', 'type': FIELD_TYPES_MAPPING['QSTRING'], 'label': 'name', 'show': True}]\n , l['fields'])\n\n # capabilities\n self.assertEqual(l['capabilities'], settings.QUERYABLE | settings.FILTRABLE)\n\n # bbox\n self.assertAlmostEqual(l['bbox']['minx'], 1.98008936077027897, 4)\n self.assertAlmostEqual(l['bbox']['miny'], 28.77977157557936039, 4)\n self.assertAlmostEqual(l['bbox']['maxx'], 10.68524667507452364, 4)\n self.assertAlmostEqual(l['bbox']['maxy'], 44.35096846172920948, 4)\n\n # metadata\n metadata_expected = {\n 'title': 'spatialite_points',\n 'attributes': [\n {\n 'name': 'pkuid',\n 'typeName': 'integer',\n 'comment': '',\n 'length': 0,\n 'precision': 0,\n 'type': 'qlonglong',\n 'alias': ''\n },\n {\n 'name': 'name',\n 'typeName': 'text',\n 'comment': '',\n 'length': 0,\n 'precision': 0,\n 'type': 'QString',\n 'alias': ''\n }\n ],\n 'crs': [],\n 'dataurl': {},\n 'metadataurl': {},\n 'attribution': {}\n }\n\n self.assertEqual(l['metadata'], metadata_expected)\n\n # crs\n self.assertEqual(l['crs'], {\n 'epsg': 4326,\n 'proj4': '+proj=longlat +datum=WGS84 +no_defs',\n 'geographic': True,\n 'axisinverted': True,\n 'extent': [-180.0, -90.0, 180.0, 90.0]\n })\n\n if l['id'] == 'bluemarble20181008111156906':\n pass\n # capabilities\n # fixeme: ask to elpaso why into test thios raster is sercheable\n #self.assertEqual(l['capabilities'], settings.QUERYABLE)\n\n # bbox\n self.assertAlmostEqual(l['bbox']['minx'], -180, 4)\n self.assertAlmostEqual(l['bbox']['miny'], -90, 4)\n self.assertAlmostEqual(l['bbox']['maxx'], 180, 4)\n self.assertAlmostEqual(l['bbox']['maxy'], 90, 4)\n\n # crs\n self.assertEqual(l['crs'], {\n 'epsg': 4326,\n 'proj4': '+proj=longlat +datum=WGS84 +no_defs',\n 'geographic': True,\n 'axisinverted': True,\n 'extent': [-180.0, -90.0, 180.0, 90.0]\n })\n\n # Test ProjectIsActivePermission\n # ------------------------------------------------------------\n\n p = Project.objects.get(pk=1)\n p.is_active = False\n p.save()\n\n self.client.login(username=self.test_admin1.username, password=self.test_admin1.username)\n url = reverse('group-project-map-config', args=['gruppo-1', 'qdjango', '1'])\n response = self.client.get(url)\n\n self.assertEqual(response.status_code, 403)\n\n self.client.logout()\n\n # Restore group\n p.is_active = True\n p.save()\n\n\n def test_custom_layer_order(self):\n \"\"\"Testing qgis custom layer order\"\"\"\n\n response = self._testApiCall('group-project-map-config', ['custom-order-layer-group', 'qdjango',\n self.project_extent316_1.instance.pk])\n resp = json.loads(response.content)\n\n self.assertTrue(resp['layers'][0]['id'], 'bluemarble20181008111156906')\n self.assertTrue(resp['layers'][1]['id'], 'world20181008111156525')\n self.assertTrue(resp['layers'][2]['id'], 'spatialite_points20190604101052075')\n self.assertTrue(resp['layers'][3]['id'], 'popolation_femme_2019_4a0ec267_1fc5_466c_be89_1c7525744e11')\n\n def test_empty_vector_layer(self):\n \"\"\"Testing remove empty vector layer from config client API\"\"\"\n\n\n\n # G3W_CLIENT_NOT_SHOW_EMPTY_VECTORLAYER = False\n # --------------------------------------------\n with self.settings(G3W_CLIENT_NOT_SHOW_EMPTY_VECTORLAYER=False):\n response = self._testApiCall('group-project-map-config', ['empty_vector_layer_layer_group', 'qdjango',\n self.project_extent316_2.instance.pk])\n resp = json.loads(response.content)\n layers = [l['id'] for l in resp['layers']]\n\n self.assertTrue('empty_table_c24561b9_a94f_4515_ba52_0c12e5608094' in layers)\n\n # G3W_CLIENT_NOT_SHOW_EMPTY_VECTORLAYER = True\n # --------------------------------------------\n with self.settings(G3W_CLIENT_NOT_SHOW_EMPTY_VECTORLAYER=True):\n response = self._testApiCall('group-project-map-config', ['empty_vector_layer_layer_group', 'qdjango',\n self.project_extent316_2.instance.pk])\n resp = json.loads(response.content)\n layers = [l['id'] for l in resp['layers']]\n\n self.assertFalse('empty_table_c24561b9_a94f_4515_ba52_0c12e5608094' in layers)\n\n def test_init_max_extent_policy(self):\n \"\"\" Test init and maxextent policy by checked or not of use_map_extent_as_init_extent\"\"\"\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n\n self.assertEqual(resp[\"initextent\"], resp[\"extent\"])\n\n self.prj_test.use_map_extent_as_init_extent = True\n self.prj_test.save()\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n\n self.assertNotEqual(resp[\"initextent\"], resp[\"extent\"])\n\n self.prj_test.use_map_extent_as_init_extent = False\n self.prj_test.save()\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n\n self.assertEqual(resp[\"initextent\"], resp[\"extent\"])\n\n\n def testClientConfigApiThumbnailView(self):\n \"\"\" Test api project config for thumbnail param \"\"\"\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n self.assertEqual(resp[\"thumbnail\"], '/media/fake/project.png')\n\n # add group to macrogroup\n macrogorup = MacroGroup(name='thgroup_test', title='thgroup_test', logo_img='/fake/macrogroup.png')\n macrogorup.save()\n macrogorup.group_set.add(self.prj_test.group)\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n self.assertEqual(resp[\"thumbnail\"], '/media/fake/project.png')\n\n # Check use_logo_client by macrogroup\n macrogorup.use_logo_client = True\n macrogorup.save()\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n self.assertEqual(resp[\"thumbnail\"], '/media/fake/macrogroup.png')\n\n # Check use_logo_client by group\n self.prj_test.group.use_logo_client = True\n self.prj_test.group.save()\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n self.assertEqual(resp[\"thumbnail\"], self.prj_test.group.header_logo_img.url)\n\n def testClientConfigApiWidget(self):\n \"\"\"Test layer widget config section\"\"\"\n\n layer = self.prj_test.layer_set.get(qgs_layer_id='spatialite_points20190604101052075')\n\n # update datasource to work\n layer.datasource = f\"dbname='{DATASOURCE_PATH}/geodata/un-progetto.db' table=\\\"spatialite_points\\\" (geom) sql=\"\n layer.save()\n\n # create a search widget with selectbox\n # -------------------------------------------\n widget_body = {\n \"title\": \"asert\",\n \"query\": \"simpleWmsSearch\",\n \"usewmsrequest\": True,\n \"fields\": [\n {\n \"name\": \"name\",\n \"label\": \"name\",\n \"blanktext\": \"\",\n \"filterop\": \"eq\",\n \"widgettype\": \"selectbox\",\n \"input\": {\n \"type\": \"textfield\",\n \"options\": {}\n },\n \"logicop\": 'and'\n }\n ],\n \"results\":[],\n \"selectionlayer\": \"spatialite_points20190604101052075\",\n \"selectionzoom\": 0,\n \"dozoomtoextent\": True\n }\n\n widget = Widget(\n widget_type='search',\n name='Test selectbox',\n datasource=layer.datasource,\n body=json.dumps(widget_body)\n )\n widget.save()\n widget.layers.add(layer)\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n\n self.assertTrue(len(resp[\"search\"]) > 0)\n resp_serach = resp['search'][0]\n self.assertEqual(resp_serach['name'], 'Test selectbox')\n self.assertEqual(resp_serach['type'], 'search')\n self.assertEqual(resp_serach['options']['filter'][0]['input']['type'], 'selectfield')\n self.assertEqual(resp_serach['options']['filter'][0]['input']['options']['values'], [])\n self.assertEqual(resp_serach['options']['filter'][0]['logicop'], 'AND')\n\n # create a search widget with autocompletebox\n # -------------------------------------------\n widget_body = {\n \"title\": \"autocomplete test title\",\n \"query\": \"simpleWmsSearch\",\n \"usewmsrequest\": True,\n \"fields\": [\n {\n \"name\": \"name\",\n \"label\": \"name\",\n \"blanktext\": \"\",\n \"filterop\": \"eq\",\n \"widgettype\": \"autocompletebox\",\n \"input\": {\n \"type\": \"textfield\",\n \"options\": {}\n },\n \"logicop\": 'and'\n }\n ],\n \"results\": [],\n \"selectionlayer\": \"spatialite_points20190604101052075\",\n \"selectionzoom\": 0,\n \"dozoomtoextent\": True\n }\n\n widget = Widget(\n widget_type='search',\n name='Test autocompletebox',\n datasource=layer.datasource,\n body=json.dumps(widget_body)\n )\n widget.save()\n widget.layers.add(layer)\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', '1'])\n resp = json.loads(response.content)\n\n self.assertTrue(len(resp[\"search\"]) == 2)\n resp_serach = resp['search'][1]\n self.assertEqual(resp_serach['name'], 'Test autocompletebox')\n self.assertEqual(resp_serach['type'], 'search')\n self.assertEqual(resp_serach['options']['filter'][0]['input']['type'], 'autocompletefield')\n self.assertEqual(resp_serach['options']['filter'][0]['logicop'], 'AND')\n\n # create a search widget with selectbox for a field with a ValueMap edit widget\n # -----------------------------------------------------------------------------\n\n layer = self.project_print310_1.instance.layer_set.get(qgs_layer_id='layer_for_edit_widget_d16f33ed_6014_4dae_b9fe_1aa0381d81c3')\n\n widget_body = {\n \"title\": \"asert\",\n \"query\": \"simpleWmsSearch\",\n \"usewmsrequest\": True,\n \"fields\": [\n {\n \"name\": \"t_code_a\",\n \"label\": \"t_code_a\",\n \"blanktext\": \"\",\n \"filterop\": \"eq\",\n \"widgettype\": \"selectbox\",\n \"input\": {\n \"type\": \"textfield\",\n \"options\": {}\n },\n \"logicop\": 'and'\n }\n ],\n \"results\": [],\n \"selectionlayer\": \"layer_for_edit_widget_d16f33ed_6014_4dae_b9fe_1aa0381d81c3\",\n \"selectionzoom\": 0,\n \"dozoomtoextent\": True\n }\n\n widget = Widget(\n widget_type='search',\n name='Test selectbox for field with valuemap',\n datasource=layer.datasource,\n body=json.dumps(widget_body)\n )\n widget.save()\n widget.layers.add(layer)\n\n response = self._testApiCall('group-project-map-config', ['gruppo-1', 'qdjango', self.project_print310_1.instance.pk])\n resp = json.loads(response.content)\n\n self.assertTrue(len(resp[\"search\"]) > 0)\n resp_serach = resp['search'][0]\n self.assertEqual(resp_serach['name'], 'Test selectbox for field with valuemap')\n self.assertEqual(resp_serach['type'], 'search')\n self.assertEqual(resp_serach['options']['filter'][0]['input']['type'], 'selectfield')\n self.assertEqual(resp_serach['options']['filter'][0]['input']['options']['values'],\n [\n {\"value\": \"1\", \"key\": \"LOW\"},\n {\"value\": \"2\", \"key\": \"MEDIUM\"},\n {\"value\": \"3\", \"key\": \"HIGHT\"}\n ]\n )\n self.assertEqual(resp_serach['options']['filter'][0]['logicop'], 'AND')\n\n def testClientConfigApiViewForPrint(self):\n \"\"\"Test client config API for print section\"\"\"\n\n response = self._testApiCall('group-project-map-config',\n ['gruppo-1', 'qdjango', self.project_print310.instance.pk])\n resp = json.loads(response.content)\n\n self.assertEqual(\n resp[\"print\"],\n json.loads('['\n '{\"name\": \"A4\", \"w\": 297.0, \"h\": 210.0, \"labels\": [{\"id\": \"Print\", \"text\": \"Print\"}], \"maps\": [{\"name\": \"map0\", \"displayname\": \"Map 1\", \"w\": 189.53, \"h\": 117.75944852941177, \"overview\": false, \"scale\": 24651341.004171893, \"extent\": {\"xmin\": -33.650906640076606, \"ymin\": 20.637462798706206, \"xmax\": 60.849040859923356, \"ymax\": 79.35250370863265}}]},'\n '{\"name\": \"atlas_test\", \"w\": 297.0, \"h\": 210.0, \"labels\": [],\"atlas\": {\"qgs_layer_id\": \"countries_simpl20171228095706310\", \"field_name\": \"ISOCODE\"}, \"maps\": [{\"name\": \"map0\", \"displayname\": \"Map 1\", \"w\": 117.063, \"h\": 76.29999107142858, \"overview\": false, \"scale\": 2621775.4915320138, \"extent\": {\"xmin\": 17.62596823561644, \"ymin\": 39.497494100000004, \"xmax\": 22.71810776438356, \"ymax\": 42.8164779}}]}'\n ']')\n )\n\n def testClientConfigApiViewForInitMaxExtent(self):\n \"\"\"Test init max extent for client config api\"\"\"\n\n # check for tab_doc_dafault: set to legend\n self.project_extent310_2.instance.toc_tab_default = 'legend'\n self.project_extent310_2.instance.save()\n\n\n\n response = self._testApiCall('group-project-map-config',\n [self.extent_group.slug, 'qdjango', self.project_extent310_2.instance.pk])\n resp = json.loads(response.content)\n\n self.assertEqual([int(i) for i in resp['extent']],\n [166021, 0, 534994, 9329005])\n\n self.assertEqual(resp['toc_tab_default'], 'legend')\n\n def testClientConfigApiViewForFilterByUser(self):\n \"\"\"Test Filter by User/Group\"\"\"\n\n\n path = reverse('group-project-map-config', args=[self.project_print310.group.slug, 'qdjango', self.project_print310.instance.pk])\n res = self.client.get(path)\n self.assertEqual(res.status_code, 403)\n\n # grant to viewer_1 and\n self.project_print310.instance.addPermissionsToViewers([self.test_viewer1.pk])\n self.project_print310.instance.add_permissions_to_viewer_user_groups([self.test_gu_viewer2.pk])\n\n # grant to viewer_1 to project 1a with same layer ids\n self.project_print310_1a.instance.addPermissionsToViewers([self.test_viewer1.pk])\n self.project_print310_1a.instance.add_permissions_to_viewer_user_groups([self.test_gu_viewer2.pk])\n\n self.client.login(username=self.test_viewer1.username, password=self.test_viewer1.username)\n res = self.client.get(path)\n\n self.assertEqual(res.status_code, 200)\n jres = json.loads(res.content)\n\n layers = [l['name'] for l in jres['layers']]\n\n self.assertTrue(\"Cities\" in layers)\n self.assertTrue(\"Countries\" in layers)\n self.assertTrue(\"Rivers\" in layers)\n\n layerstree = json.dumps(jres['layerstree'])\n\n self.assertTrue('\"name\": \"Cities\"' in layerstree)\n self.assertTrue('\"name\": \"Countries\"' in layerstree)\n self.assertTrue('\"name\": \"Rivers\"' in layerstree)\n\n layer_cities = self.project_print310.instance.layer_set.filter(name=\"Cities\")\n layer_countries = self.project_print310.instance.layer_set.filter(name=\"Countries\")\n\n # remove Cities for viewer_1\n remove_perm('qdjango.view_layer', self.test_viewer1, layer_cities)\n\n # remove Countries and Cities for group GU-VIEWER2\n remove_perm('qdjango.view_layer', self.test_gu_viewer2, layer_cities)\n remove_perm('qdjango.view_layer', self.test_gu_viewer2, layer_countries)\n\n res = self.client.get(path)\n\n self.assertEqual(res.status_code, 200)\n jres = json.loads(res.content)\n\n layers = [l['name'] for l in jres['layers']]\n\n self.assertFalse(\"Cities\" in layers)\n self.assertTrue(\"Countries\" in layers)\n self.assertTrue(\"Rivers\" in layers)\n\n layerstree = json.dumps(jres['layerstree'])\n\n self.assertFalse('\"name\": \"Cities\"' in layerstree)\n self.assertTrue('\"name\": \"Countries\"' in layerstree)\n self.assertTrue('\"name\": \"Rivers\"' in layerstree)\n\n self.client.logout()\n\n # Check vs other project with same layer ids\n path_1a = reverse('group-project-map-config',\n args=[self.project_print310_1a.group.slug, 'qdjango', self.project_print310_1a.instance.pk])\n\n self.client.login(username=self.test_viewer1.username, password=self.test_viewer1.username)\n res = self.client.get(path_1a)\n\n self.assertEqual(res.status_code, 200)\n jres = json.loads(res.content)\n\n layers = [l['name'] for l in jres['layers']]\n\n self.assertTrue(\"Cities\" in layers)\n self.assertTrue(\"Countries\" in layers)\n self.assertTrue(\"Rivers\" in layers)\n\n layerstree = json.dumps(jres['layerstree'])\n\n self.assertTrue('\"name\": \"Cities\"' in layerstree)\n self.assertTrue('\"name\": \"Countries\"' in layerstree)\n self.assertTrue('\"name\": \"Rivers\"' in layerstree)\n\n self.client.logout()\n\n # login as viewer1.3 inside group gu_viewer2\n self.client.login(username=self.test_viewer1_3.username, password=self.test_viewer1_3.username)\n res = self.client.get(path)\n\n self.assertEqual(res.status_code, 200)\n jres = json.loads(res.content)\n\n layers = [l['name'] for l in jres['layers']]\n\n self.assertFalse(\"Cities\" in layers)\n self.assertFalse(\"Countries\" in layers)\n self.assertTrue(\"Rivers\" in layers)\n\n layerstree = json.dumps(jres['layerstree'])\n\n self.assertFalse('\"name\": \"Cities\"' in layerstree)\n self.assertFalse('\"name\": \"Countries\"' in layerstree)\n self.assertTrue('\"name\": \"Rivers\"' in layerstree)\n\n self.client.logout()\n\n # Check vs other project with same layer ids for user groups\n self.client.login(username=self.test_viewer1_3.username, password=self.test_viewer1_3.username)\n res = self.client.get(path_1a)\n\n self.assertEqual(res.status_code, 200)\n jres = json.loads(res.content)\n\n layers = [l['name'] for l in jres['layers']]\n\n self.assertTrue(\"Cities\" in layers)\n self.assertTrue(\"Countries\" in layers)\n self.assertTrue(\"Rivers\" in layers)\n\n layerstree = json.dumps(jres['layerstree'])\n\n self.assertTrue('\"name\": \"Cities\"' in layerstree)\n self.assertTrue('\"name\": \"Countries\"' in layerstree)\n self.assertTrue('\"name\": \"Rivers\"' in layerstree)\n\n\n","repo_name":"g3w-suite/g3w-admin","sub_path":"g3w-admin/client/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":37830,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"52"} +{"seq_id":"13225881337","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nimport time\r\nimport timeit\r\nimport re\r\n# import openpyxl\r\nimport win32timezone\r\nimport win32com.client as win32\r\nimport easygui\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.ie.options import Options\r\n\r\nimport WebControl\r\nimport ActionItem \r\nimport CreatorFunctions\r\n\r\ndef FindEditBoxValue(SheetName, KeyWord):\r\n for nRow in range(1, SheetName.UsedRange.Rows.Count + 1):\r\n for nCol in range (1, 50):\r\n if SheetName.Cells(nRow, nCol).Value == KeyWord:\r\n return SheetName.Cells(nRow, nCol + 1).Value\r\n\r\n\r\nprint(\"Ticket Creating has been started.\\nPlease select an Excel file.\")\r\nnTotalStart = timeit.default_timer()\r\n\r\n#Get Excel File Path\r\nsExcelPath = easygui.fileopenbox('Select Ticket Creator')\r\n\r\nif sExcelPath == None: \r\n os._exit(0)\r\nelse:\r\n isExcel = re.search(\".xlsm\", sExcelPath)\r\n if isExcel == None:\r\n sErrorString = \"Program will be terminated.\\n\\nWrong excel file: \" + str(sExcelPath)\r\n easygui.msgbox(sErrorString, \"Warning.\")\r\n os._exit(0)\r\n else:\r\n # fExcelFile = openpyxl.load_workbook(filename = sExcelPath, data_only=True)\r\n excel = win32.gencache.EnsureDispatch('Excel.Application')\r\n try:\r\n fExcelFile = excel.Workbooks.Open(sExcelPath)\r\n except:\r\n print (\"You have to Save excel file before run this program. \")\r\n fExcelFile.Save()\r\n \r\n RecordingSheet = fExcelFile.Worksheets('Recording')\r\n KpmCreateSheet = fExcelFile.Worksheets('kpmcreate') \r\n \r\n if FindEditBoxValue(RecordingSheet, \"Excel Visible\") == 'O':\r\n excel.Visible = True\r\n else:\r\n excel.Visible = False\r\n \r\n#ColumeDictionary Setting\r\nRecColDict = {}\r\nKpmColDict = {}\r\nCreatorFunctions.DictionarySetting(RecordingSheet, RecColDict, 8, True)\r\nCreatorFunctions.DictionarySetting(KpmCreateSheet, KpmColDict, 1, True)\r\n\r\nprint(\"Loading WebBrowser\")\r\nbBrowserType = FindEditBoxValue(RecordingSheet, \"Browser Type\")\r\nif bBrowserType == \"Firefox\":\r\n KPMwebbrowser = webdriver.Firefox(executable_path=r\"C:\\WebDrivers\\geckodriver.exe\")\r\nelif bBrowserType == \"Chrome\":\r\n KPMwebbrowser = webdriver.Chrome(executable_path=r\"C:\\WebDrivers\\chromedriver.exe\")\r\nelse:#ie\r\n # KPMwebbrowser = webdriver.Ie(executable_path=r\"C:\\WebDrivers\\IEDriverServer_32bit.exe\")\r\n # caps = webdriver.DesiredCapabilities.INTERNETEXPLORER\r\n # # capabilities['ie.enableFullPageScreenshot'] = False\r\n # # capabilities['ie.ensureCleanSession'] = True\r\n # caps[\"requireWindowFocus\"] = True\r\n # caps[\"ignoreProtectedModeSettings\"] = True\r\n # caps['ignoreZoomSetting'] = True\r\n # caps[\"javascriptEnabled\"] = True\r\n # caps['INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS']=True\r\n ie_options = Options()\r\n ie_options.ignore_protected_mode_settings = True\r\n KPMwebbrowser = webdriver.Ie(executable_path=r\"C:\\WebDrivers\\IEDriverServer_64bit.exe\", options=ie_options)\r\n # KPMwebbrowser = webdriver.Ie(executable_path=r\"C:\\WebDrivers\\IEDriverServer_32bit.exe\", options=ie_options)\r\n\r\nKPMwebbrowser.implicitly_wait(10)\r\n\r\n\r\nif FindEditBoxValue(RecordingSheet, \"WebType\") == 'B2C':\r\n url = \"https://quasi.vw.vwg/kpm/kpmweb/Index.action\"\r\n WebControl.GoToURL(KPMwebbrowser, url)\r\n easygui.msgbox(\"Wait!!! Login and Go to Main page. And then press OK\", \"Please Login KPM\")\r\n if FindEditBoxValue(RecordingSheet, \"Brand\") == 'AU':\r\n ActionListSheet = fExcelFile.Worksheets('AU_B2C') \r\n else:\r\n ActionListSheet = fExcelFile.Worksheets('PO_B2C') \r\n \r\nelse:\r\n # if bBrowserType == \"Firefox\" or bBrowserType == \"Chrome\":\r\n sID = FindEditBoxValue(RecordingSheet, \"B2B Site ID\")\r\n sPW = FindEditBoxValue(RecordingSheet, \"B2B Site PW\")\r\n if sID != None and sPW != None:\r\n url = \"https://\"+sID+\":\"+sPW+\"@sso.volkswagen.de/kpmweb/index.do;jsessionid=ydr9irMbCOcxffBE27_cuxwg-64Lit_sYNMYCCLgz9PAWFo67z4s!761829767\" \r\n WebControl.GoToURL(KPMwebbrowser, url)\r\n else:\r\n url = \"https://sso.volkswagen.de/kpmweb/index.do;jsessionid=ydr9irMbCOcxffBE27_cuxwg-64Lit_sYNMYCCLgz9PAWFo67z4s!761829767\"\r\n WebControl.GoToURL(KPMwebbrowser, url)\r\n easygui.msgbox(\"Wait!!! Login and Go to Main page. And then press OK\", \"Please Login KPM\")\r\n if FindEditBoxValue(RecordingSheet, \"Brand\") == 'AU':\r\n ActionListSheet = fExcelFile.Worksheets('AU_B2B')\r\n else:\r\n ActionListSheet = fExcelFile.Worksheets('PO_B2B')\r\n\r\npHNDLInfo = ActionItem.WindowHandleInfo(KPMwebbrowser.current_window_handle, None, KPMwebbrowser.current_window_handle)\r\n\r\n#Create tickets!\r\nlActionList = ActionItem.GetActionItemList(1, \"StartEvent\", ActionListSheet, RecordingSheet, KpmCreateSheet, RecColDict, KpmColDict) \r\nCreatorFunctions.ExecuteActionList(KPMwebbrowser, lActionList, pHNDLInfo, KpmCreateSheet, 0)\r\n\r\nfor nRow in range(2, KpmCreateSheet.UsedRange.Rows.Count + 1):\r\n nRecordingCol = nRow + 7\r\n if KpmCreateSheet.Cells(nRow, 1).Value == None : # No KPM Number\r\n if RecordingSheet.Cells(nRecordingCol, 1).Value != None: # Timestamp is Ok\r\n # Then Create Ticket\r\n lActionList = ActionItem.GetActionItemList(nRow, \"CreateTicket\", ActionListSheet, RecordingSheet, KpmCreateSheet, RecColDict, KpmColDict) \r\n CreatorFunctions.ExecuteActionList(KPMwebbrowser, lActionList, pHNDLInfo, KpmCreateSheet, nRow)\r\n \r\n fExcelFile.Save() #Save Excel File\r\n \r\n if KpmCreateSheet.Cells(nRow, CreatorFunctions.FindDictVal(KpmColDict, \"Re-Upload\")).Value != \"X\":\r\n CreatorFunctions.UploadAttachment( KPMwebbrowser, lActionList, pHNDLInfo, \r\n KpmCreateSheet, RecordingSheet, ActionListSheet, \r\n nRecordingCol, nRow,\r\n RecColDict, KpmColDict )\r\n \r\n #Back to main screen\r\n lActionList = ActionItem.GetActionItemList(nRow, \"Finish\", ActionListSheet, RecordingSheet, KpmCreateSheet, RecColDict, KpmColDict) \r\n CreatorFunctions.ExecuteActionList(KPMwebbrowser, lActionList, pHNDLInfo, KpmCreateSheet, nRow)\r\n\r\n fExcelFile.Save() #Save Excel File\r\n else:\r\n pass\r\n else:\r\n #Only upload attachments\r\n if KpmCreateSheet.Cells(nRow, CreatorFunctions.FindDictVal(KpmColDict, \"Re-Upload\")).Value == \"O\":\r\n print (\"Upload Attachment ticket / \", KpmCreateSheet.Cells(nRow, 1).Value)\r\n \r\n lActionList = ActionItem.GetActionItemList(nRow, \"SearchTicket\", ActionListSheet, RecordingSheet, KpmCreateSheet, RecColDict, KpmColDict) \r\n CreatorFunctions.ExecuteActionList(KPMwebbrowser, lActionList, pHNDLInfo, KpmCreateSheet, nRow)\r\n\r\n CreatorFunctions.UploadAttachment( KPMwebbrowser, lActionList, pHNDLInfo, \r\n KpmCreateSheet, RecordingSheet, ActionListSheet, \r\n nRecordingCol, nRow,\r\n RecColDict, KpmColDict )\r\n \r\n #Back to main screen\r\n lActionList = ActionItem.GetActionItemList(nRow, \"Finish\", ActionListSheet, RecordingSheet, KpmCreateSheet, RecColDict, KpmColDict) \r\n CreatorFunctions.ExecuteActionList(KPMwebbrowser, lActionList, pHNDLInfo, KpmCreateSheet, nRow)\r\n\r\n fExcelFile.Save() #Save Excel File\r\n else:\r\n print (\"Ticket is created. / \", KpmCreateSheet.Cells(nRow, 1).Value)\r\n\r\nnTotalTime = timeit.default_timer() - nTotalStart\r\nnHr = int(nTotalTime / 3600)\r\nnMin = int((nTotalTime - 3600 * nHr) / 60)\r\nnSec = int(nTotalTime % 60)\r\n\r\nsLastString = \"[Ticket Creation is Done!] Spend time = \" + str(nHr) +\"h, \" + str(nMin) + \"min, \" + str(nSec) + \"sec.\"\r\n# easygui.msgbox(sLastString, \"Finish\")\r\nprint(sLastString)\r\n","repo_name":"Hong822/py_KPM_Creator","sub_path":"TicketCreator.py","file_name":"TicketCreator.py","file_ext":"py","file_size_in_byte":8195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12443626470","text":"from django import forms\n\ndef check_n(value):\n if value[0]==\"N\":\n raise forms.ValidationError('it cant start with N ')\n\ndef max_lenth(value):\n if len(value)<=5:\n raise forms.ValidationError('it will be take only more then length of 5')\n\n\nclass NameForm(forms.Form):\n name=forms.CharField(max_length=100,validators=[check_n,])\n father_name=forms.CharField(max_length=100,validators=[max_lenth,])\n email=forms.EmailField()\n reemail=forms.EmailField()\n botcatcher=forms.CharField(widget=forms.HiddenInput,required=False)\n \n def clean(self):\n e=self.cleaned_data['email']\n r=self.cleaned_data['reemail']\n if e!=r:\n raise forms.ValidationError('emails are not matched')\n def clean_botcatcher(self):\n bot=self.cleaned_data['botcatcher']\n if len(bot)<=5:\n raise forms.ValidationError('it hieden data')","repo_name":"Nagarjuna6309/validations","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29542942429","text":"from typing import Awaitable, Callable, List\n\nfrom aiogram import Bot, Dispatcher, executor\nfrom aiogram import types as AIOGramTypes\n\nfrom .entities.state_manager import StateManager\nfrom .types.message import ParseMode\nfrom .utils.config import Config, create_config, get_config_path\nfrom .utils.media_adapters import create_photo_array\n\n\nclass Application:\n \"\"\"\n Класс-ядро приложения, который упрощает взаимодействие с `Telegram Bot API`, в частности - с\n библиотекой `aiogram`. Данный класс реализует основной функционал Telegram Bot API более\n простыми методами, чтобы ускорить разработку основной логики приложения.\n \"\"\"\n\n __dispatcher: Dispatcher\n __bot: Bot\n\n state: StateManager\n\n def __init__(self) -> None:\n config = create_config(get_config_path())\n\n bot = Bot(token = config.get(\"Telegram\", \"TOKEN\"))\n dispatcher = Dispatcher(bot)\n\n self.__dispatcher = dispatcher\n self.__bot = bot\n\n self.state = StateManager()\n\n def run(self) -> None:\n print(\"Running bot application...\")\n executor.start_polling(self.__dispatcher, skip_updates = True)\n\n def add_command_handler(self, command: List[str], handler: Awaitable):\n \"\"\"\n Подписывает функции на определённый список команд\n\n :param command: массив строк с командами, по получении которых должна отрабатывать функция\n :param handler: функция, которая будет вызвана после получения одной из переданных команд\n ```\n \"\"\"\n\n @self.__dispatcher.message_handler(commands = command or None)\n async def _(message: AIOGramTypes.Message):\n await handler(message)\n\n def add_inline_keyboard_handler(self, handler: Callable) -> None:\n \"\"\"\n Подписывает функции на сообщения, отправленные при помощи inline клавиатуры\n\n :param handler: функция, которая будет вызвана после получения одной из переданных команд\n ```\n \"\"\"\n\n @self.__dispatcher.callback_query_handler()\n async def _(call):\n await handler(call)\n\n\n async def send_message(\n self,\n chat_id: int,\n text: str,\n disable_notification: bool | None = None,\n protect_content: bool | None = None,\n reply_to_message_id: int | None = None,\n allow_sending_without_reply: bool | None = None,\n parse_mode: ParseMode = ParseMode.MARKDOWN,\n disable_web_page_preview: bool = False,\n reply_markup: AIOGramTypes.InlineKeyboardButton |\n AIOGramTypes.ReplyKeyboardMarkup |\n AIOGramTypes.ReplyKeyboardRemove |\n AIOGramTypes.ForceReply |\n None = None\n ) -> None:\n \"\"\"\n (Асинхронный метод) Отправляет сообщения пользователю, возможно добавление клавиатуры\n\n :param chat_id: id чата, куда нужно отправить сообщение\n :param text: текст сообщения, которое будет отправлено пользователю\n :param disable_notification: отправить сообщение в \"бесшумном\" режиме\n :param protect_content: запретить пересылать и скачивать отправленный контент\n :param reply_to_message_id: id оригинального сообщения, если команда является ответом\n :param allow_sending_without_reply: отправить, даже если нет сообщения, на которое нужно ответить\n :param parse_mode: Markdown/HTML\n :param reply_markup: клавиатура\n :param disable_web_page_preview: отключение превью ссылок\n\n @see https://core.telegram.org/bots/api#sendmessage\n \"\"\"\n\n await self.__bot.send_message(\n chat_id = chat_id,\n text = text,\n disable_notification = disable_notification,\n protect_content = protect_content,\n reply_to_message_id = reply_to_message_id,\n allow_sending_without_reply = allow_sending_without_reply,\n parse_mode = parse_mode,\n reply_markup = reply_markup,\n disable_web_page_preview = disable_web_page_preview\n )\n\n async def send_message_with_photo(\n self,\n chat_id: int,\n photo: str,\n text: str | None = None,\n disable_notification: bool | None = None,\n protect_content: bool | None = None,\n reply_to_message_id: int | None = None,\n allow_sending_without_reply: bool | None = None,\n parse_mode: str = ParseMode.MARKDOWN,\n reply_markup: AIOGramTypes.InlineKeyboardButton |\n AIOGramTypes.ReplyKeyboardMarkup |\n AIOGramTypes.ReplyKeyboardRemove |\n AIOGramTypes.ForceReply |\n None = None\n ) -> None:\n \"\"\"\n (Асинхронный метод) Отправляет картинки пользователю, возможно добавление клавиатуры\n\n :param chat_id: id чата, куда нужно отправить сообщение\n :param photo: строковый путь до картинки (абсолютный)\n :param text: текст, который будет отправлен вместе с картинкой\n :param disable_notification: отправить сообщение в \"бесшумном\" режиме\n :param protect_content: запретить пересылать и скачивать отправленный контент\n :param reply_to_message_id: id оригинального сообщения, если команда является ответом\n :param allow_sending_without_reply: отправить, даже если нет сообщения, на которое нужно ответить\n :param parse_mode: Markdown/HTML\n :param reply_markup: клавиатура, которая будет отправлена вместе с сообщением\n\n @see https://core.telegram.org/bots/api#sendphoto\n \"\"\"\n\n await self.__bot.send_photo(\n chat_id = chat_id,\n photo = photo,\n caption = text,\n parse_mode = parse_mode,\n disable_notification = disable_notification,\n protect_content = protect_content,\n reply_to_message_id = reply_to_message_id,\n allow_sending_without_reply = allow_sending_without_reply,\n reply_markup = reply_markup,\n )\n\n async def send_multiple_pictures(\n self,\n chat_id: int,\n media: List[str],\n message_thread_id: int | None = None,\n disable_notification: bool | None = None,\n protect_content: bool | None = None,\n reply_to_message_id: int | None = None,\n allow_sending_without_reply: bool | None = None,\n ) -> None:\n \"\"\"\n (Асинхронный метод) Отправляет несколько картинок пользователю\n\n :param chat_id: id чата, куда нужно отправить сообщение\n :param media: массив JSON, описывающий фото для отправки\n :param message_thread_id: идентификатор цепочки сообщений\n :param disable_notification: отправить сообщение в \"бесшумном\" режиме\n :param protect_content: запретить пересылать и скачивать отправленный контент\n :param reply_to_message_id: id сообщения, если команда является ответом\n :param allow_sending_without_reply: отправить, даже если нет сообщения, на которое нужно ответить\n\n @see https://core.telegram.org/bots/api#sendmediagroup\n \"\"\"\n\n try:\n await self.__bot.send_media_group(\n chat_id = chat_id,\n media = create_photo_array(media),\n message_thread_id = message_thread_id,\n disable_notification = disable_notification,\n protect_content = protect_content,\n reply_to_message_id = reply_to_message_id,\n allow_sending_without_reply = allow_sending_without_reply\n )\n\n except Exception as e:\n print(repr(e))\n\n @staticmethod\n def is_private_message(chat_type: str) -> bool:\n return chat_type == \"private\"\n","repo_name":"elysian-projects/miit-guide-bot","sub_path":"src/bot/_application.py","file_name":"_application.py","file_ext":"py","file_size_in_byte":9240,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"73606801124","text":"# coding: utf-8\nfrom aliyunsdkcore import client\nfrom .aliyunsdkafs.request.v20180112 import AuthenticateSigRequest\nfrom aliyunsdkcore.profile import region_provider\nregion_provider.add_endpoint('afs', 'cn-hangzhou', 'afs.aliyuncs.com')\nAccessKeyId = 'LTAI6o809CEmwzYW'\nAccessKeySecret = 'ZPjATsftV9yc9kbL7kWfz1dE1TWCIe'\n\nclt = client.AcsClient(AccessKeyId, AccessKeySecret, 'cn-hangzhou')\n\n\ndef check_aliyun_captcha(session, sig, token, scene, ip):\n request = AuthenticateSigRequest.AuthenticateSigRequest()\n # 必填参数:从前端获取,不可更改,android和ios只传这个参数即可\n request.set_SessionId(session)\n # 必填参数:从前端获取,不可更改\n request.set_Sig(sig)\n # 必填参数:从前端获取,不可更改\n request.set_Token(token)\n # 必填参数:从前端获取,不可更改\n request.set_Scene(scene)\n # 必填参数:后端填写\n request.set_AppKey('FFFF0N00000000006E27')\n # 必填参数:后端填写\n request.set_RemoteIp(ip)\n result = clt.do_action(request) # 返回code 100表示验签通过,900表示验签失败\n\n\n","repo_name":"lemon-mccdull/history","sub_path":"libs/captcha/captcha.py","file_name":"captcha.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"38508540181","text":"import abc\nfrom copy import deepcopy\nfrom typing import Dict\n\nimport numpy as np\nimport torch\nfrom scipy import stats\nfrom torch import Tensor\nfrom torch.distributions.dirichlet import Dirichlet\nfrom torch_geometric import data as gd\n\nfrom gflownet.config import Config\nfrom gflownet.utils import metrics\nfrom gflownet.utils.focus_model import TabularFocusModel\nfrom gflownet.utils.transforms import thermometer\n\n\nclass Conditional(abc.ABC):\n def sample(self, n):\n raise NotImplementedError()\n\n @abc.abstractmethod\n def transform(self, cond_info: Dict[str, Tensor], properties: Tensor) -> Tensor:\n raise NotImplementedError()\n\n def encoding_size(self):\n raise NotImplementedError()\n\n def encode(self, conditional: Tensor) -> Tensor:\n raise NotImplementedError()\n\n\nclass TemperatureConditional(Conditional):\n def __init__(self, cfg: Config, rng: np.random.Generator):\n self.cfg = cfg\n tmp_cfg = self.cfg.cond.temperature\n self.rng = rng\n self.upper_bound = 1024\n if tmp_cfg.sample_dist == \"gamma\":\n loc, scale = tmp_cfg.dist_params\n self.upper_bound = stats.gamma.ppf(0.95, loc, scale=scale)\n elif tmp_cfg.sample_dist == \"uniform\":\n self.upper_bound = tmp_cfg.dist_params[1]\n elif tmp_cfg.sample_dist == \"loguniform\":\n self.upper_bound = tmp_cfg.dist_params[1]\n elif tmp_cfg.sample_dist == \"beta\":\n self.upper_bound = 1\n\n def encoding_size(self):\n return self.cfg.cond.temperature.num_thermometer_dim\n\n def sample(self, n):\n cfg = self.cfg.cond.temperature\n beta = None\n if cfg.sample_dist == \"constant\":\n assert isinstance(cfg.dist_params[0], float)\n beta = np.array(cfg.dist_params[0]).repeat(n).astype(np.float32)\n beta_enc = torch.zeros((n, cfg.num_thermometer_dim))\n else:\n if cfg.sample_dist == \"gamma\":\n loc, scale = cfg.dist_params\n beta = self.rng.gamma(loc, scale, n).astype(np.float32)\n elif cfg.sample_dist == \"uniform\":\n a, b = float(cfg.dist_params[0]), float(cfg.dist_params[1])\n beta = self.rng.uniform(a, b, n).astype(np.float32)\n elif cfg.sample_dist == \"loguniform\":\n low, high = np.log(cfg.dist_params)\n beta = np.exp(self.rng.uniform(low, high, n).astype(np.float32))\n elif cfg.sample_dist == \"beta\":\n a, b = float(cfg.dist_params[0]), float(cfg.dist_params[1])\n beta = self.rng.beta(a, b, n).astype(np.float32)\n beta_enc = thermometer(torch.tensor(beta), cfg.num_thermometer_dim, 0, self.upper_bound)\n\n assert len(beta.shape) == 1, f\"beta should be a 1D array, got {beta.shape}\"\n return {\"beta\": torch.tensor(beta), \"encoding\": beta_enc}\n\n def transform(self, cond_info: Dict[str, Tensor], linear_reward: Tensor) -> Tensor:\n scalar_logreward = linear_reward.squeeze().clamp(min=1e-30).log()\n assert len(scalar_logreward.shape) == len(\n cond_info[\"beta\"].shape\n ), f\"dangerous shape mismatch: {scalar_logreward.shape} vs {cond_info['beta'].shape}\"\n return scalar_logreward * cond_info[\"beta\"]\n\n def encode(self, conditional: Tensor) -> Tensor:\n cfg = self.cfg.cond.temperature\n if cfg.sample_dist == \"constant\":\n return torch.zeros((conditional.shape[0], cfg.num_thermometer_dim))\n return thermometer(torch.tensor(conditional), cfg.num_thermometer_dim, 0, self.upper_bound)\n\n\nclass MultiObjectiveWeightedPreferences(Conditional):\n def __init__(self, cfg: Config):\n self.cfg = cfg.cond.weighted_prefs\n self.num_objectives = cfg.cond.moo.num_objectives\n self.num_thermometer_dim = cfg.cond.moo.num_thermometer_dim\n if self.cfg.preference_type == \"seeded\":\n self.seeded_prefs = np.random.default_rng(142857 + int(cfg.seed)).dirichlet([1] * self.num_objectives)\n\n def sample(self, n):\n if self.cfg.preference_type is None:\n preferences = torch.ones((n, self.num_objectives))\n elif self.cfg.preference_type == \"seeded\":\n preferences = torch.tensor(self.seeded_prefs).float().repeat(n, 1)\n elif self.cfg.preference_type == \"dirichlet_exponential\":\n a = np.random.dirichlet([1] * self.num_objectives, n)\n b = np.random.exponential(1, n)[:, None]\n preferences = Dirichlet(torch.tensor(a * b)).sample([1])[0].float()\n elif self.cfg.preference_type == \"dirichlet\":\n m = Dirichlet(torch.FloatTensor([1.0] * self.num_objectives))\n preferences = m.sample([n])\n else:\n raise ValueError(f\"Unknown preference type {self.cfg.preference_type}\")\n preferences = torch.as_tensor(preferences).float()\n return {\"preferences\": preferences, \"encoding\": self.encode(preferences)}\n\n def transform(self, cond_info: Dict[str, Tensor], flat_reward: Tensor) -> Tensor:\n scalar_logreward = (flat_reward * cond_info[\"preferences\"]).sum(1).clamp(min=1e-30).log()\n assert len(scalar_logreward.shape) == 1, f\"scalar_logreward should be a 1D array, got {scalar_logreward.shape}\"\n return scalar_logreward\n\n def encoding_size(self):\n return max(1, self.num_thermometer_dim * self.num_objectives)\n\n def encode(self, conditional: Tensor) -> Tensor:\n if self.num_thermometer_dim > 0:\n return thermometer(conditional, self.num_thermometer_dim, 0, 1).reshape(conditional.shape[0], -1)\n else:\n return conditional.unsqueeze(1)\n\n\nclass FocusRegionConditional(Conditional):\n def __init__(self, cfg: Config, n_valid: int, rng: np.random.Generator):\n self.cfg = cfg.cond.focus_region\n self.n_valid = n_valid\n self.n_objectives = cfg.cond.moo.num_objectives\n self.ocfg = cfg\n self.rng = rng\n self.num_thermometer_dim = cfg.cond.moo.num_thermometer_dim if self.cfg.use_steer_thermomether else 0\n\n focus_type = self.cfg.focus_type\n if focus_type is not None and \"learned\" in focus_type:\n if focus_type == \"learned-tabular\":\n self.focus_model = TabularFocusModel(\n # TODO: proper device propagation\n device=torch.device(\"cpu\"),\n n_objectives=cfg.cond.moo.num_objectives,\n state_space_res=self.cfg.focus_model_state_space_res,\n )\n else:\n raise NotImplementedError(\"Unknown focus model type {self.focus_type}\")\n else:\n self.focus_model = None\n self.setup_focus_regions()\n\n def encoding_size(self):\n if self.num_thermometer_dim > 0:\n return self.num_thermometer_dim * self.n_objectives\n return self.n_objectives\n\n def setup_focus_regions(self):\n # focus regions\n if self.cfg.focus_type is None:\n valid_focus_dirs = np.zeros((self.n_valid, self.n_objectives))\n self.fixed_focus_dirs = valid_focus_dirs\n elif self.cfg.focus_type == \"centered\":\n valid_focus_dirs = np.ones((self.n_valid, self.n_objectives))\n self.fixed_focus_dirs = valid_focus_dirs\n elif self.cfg.focus_type == \"partitioned\":\n valid_focus_dirs = metrics.partition_hypersphere(d=self.n_objectives, k=self.n_valid, normalisation=\"l2\")\n self.fixed_focus_dirs = valid_focus_dirs\n elif self.cfg.focus_type in [\"dirichlet\", \"learned-gfn\"]:\n valid_focus_dirs = metrics.partition_hypersphere(d=self.n_objectives, k=self.n_valid, normalisation=\"l1\")\n self.fixed_focus_dirs = None\n elif self.cfg.focus_type in [\"hyperspherical\", \"learned-tabular\"]:\n valid_focus_dirs = metrics.partition_hypersphere(d=self.n_objectives, k=self.n_valid, normalisation=\"l2\")\n self.fixed_focus_dirs = None\n elif isinstance(self.cfg.focus_type, list):\n if len(self.cfg.focus_type) == 1:\n valid_focus_dirs = np.array([self.cfg.focus_type[0]] * self.n_valid)\n self.fixed_focus_dirs = valid_focus_dirs\n else:\n valid_focus_dirs = np.array(self.cfg.focus_type)\n self.fixed_focus_dirs = valid_focus_dirs\n else:\n raise NotImplementedError(\n f\"focus_type should be None, a list of fixed_focus_dirs, or a string describing one of the supported \"\n f\"focus_type, but here: {self.cfg.focus_type}\"\n )\n self.valid_focus_dirs = valid_focus_dirs\n\n def sample(self, n: int, train_it: int = None):\n train_it = train_it or 0\n if self.fixed_focus_dirs is not None:\n focus_dir = torch.tensor(\n np.array(self.fixed_focus_dirs)[self.rng.choice(len(self.fixed_focus_dirs), n)].astype(np.float32)\n )\n elif self.cfg.focus_type == \"dirichlet\":\n m = Dirichlet(torch.FloatTensor([1.0] * self.n_objectives))\n focus_dir = m.sample([n])\n elif self.cfg.focus_type == \"hyperspherical\":\n focus_dir = torch.tensor(\n metrics.sample_positiveQuadrant_ndim_sphere(n, self.n_objectives, normalisation=\"l2\")\n ).float()\n elif self.cfg.focus_type is not None and \"learned\" in self.cfg.focus_type:\n if (\n self.focus_model is not None\n and train_it >= self.cfg.focus_model_training_limits[0] * self.cfg.max_train_it\n ):\n focus_dir = self.focus_model.sample_focus_directions(n)\n else:\n focus_dir = torch.tensor(\n metrics.sample_positiveQuadrant_ndim_sphere(n, self.n_objectives, normalisation=\"l2\")\n ).float()\n else:\n raise NotImplementedError(f\"Unsupported focus_type={type(self.cfg.focus_type)}\")\n\n return {\"focus_dir\": focus_dir, \"encoding\": self.encode(focus_dir)}\n\n def encode(self, conditional: Tensor) -> Tensor:\n return (\n thermometer(conditional, self.ocfg.cond.moo.num_thermometer_dim, 0, 1).reshape(conditional.shape[0], -1)\n if self.cfg.use_steer_thermomether\n else conditional\n )\n\n def transform(self, cond_info: Dict[str, Tensor], flat_rewards: Tensor, scalar_logreward: Tensor = None) -> Tensor:\n focus_coef, in_focus_mask = metrics.compute_focus_coef(\n flat_rewards, cond_info[\"focus_dir\"], self.cfg.focus_cosim, self.cfg.focus_limit_coef\n )\n if scalar_logreward is None:\n scalar_logreward = torch.log(focus_coef)\n else:\n scalar_logreward[in_focus_mask] += torch.log(focus_coef[in_focus_mask])\n scalar_logreward[~in_focus_mask] = self.ocfg.algo.illegal_action_logreward\n\n return scalar_logreward\n\n def step_focus_model(self, batch: gd.Batch, train_it: int):\n focus_model_training_limits = self.cfg.focus_model_training_limits\n max_train_it = self.ocfg.num_training_steps\n if (\n self.focus_model is not None\n and train_it >= focus_model_training_limits[0] * max_train_it\n and train_it <= focus_model_training_limits[1] * max_train_it\n ):\n self.focus_model.update_belief(deepcopy(batch.focus_dir), deepcopy(batch.flat_rewards))\n","repo_name":"recursionpharma/gflownet","sub_path":"src/gflownet/utils/conditioning.py","file_name":"conditioning.py","file_ext":"py","file_size_in_byte":11402,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"52"} +{"seq_id":"12504885929","text":"from flask import Flask, request, redirect, session # Import session here\nimport requests\nimport base64\nimport hashlib\nimport os\n\n\napp = Flask(__name__)\n\nCLIENT_ID = '8f277978604007d8782b45e94e34a3cc' # Replace with your Client ID\nCLIENT_SECRET = '84fb3fb5f28a9cd0171d4e7367537c581b04ac8f1183435b04d403176afd3b59' # Replace with your Client Secret\nREDIRECT_URI = 'http://127.0.0.1:100/auth/callback'\n\n\n# Function to create a code_verifier\ndef create_code_verifier():\n token = base64.urlsafe_b64encode(os.urandom(40)).decode('utf-8')\n return token.replace('=', '')\n\n# Function to create a code_challenge\ndef create_code_challenge(verifier):\n sha256 = hashlib.sha256(verifier.encode('utf-8')).digest()\n return base64.urlsafe_b64encode(sha256).decode('utf-8').replace('=', '')\n\n@app.route('/')\ndef home():\n code_verifier = create_code_verifier()\n code_challenge = create_code_challenge(code_verifier)\n # Store code_verifier in session for later use\n session['code_verifier'] = code_verifier\n auth_url = f'https://myanimelist.net/v1/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&code_challenge={code_challenge}&code_challenge_method=S256&redirect_uri={REDIRECT_URI}'\n return f'Authorize'\n\n@app.route('/auth/callback')\ndef auth_callback():\n code = request.args.get('code')\n code_verifier = session.get('code_verifier')\n print(f'Code: {code}') # Log the code\n print(f'Code Verifier: {code_verifier}') # Log the code verifier\n if code and code_verifier:\n token_url = 'https://myanimelist.net/v1/oauth2/token'\n token_data = {\n 'client_id': CLIENT_ID,\n 'client_secret': CLIENT_SECRET,\n 'code': code,\n 'code_verifier': code_verifier,\n 'grant_type': 'authorization_code',\n 'redirect_uri': REDIRECT_URI,\n }\n response = requests.post(token_url, data=token_data)\n if response.status_code == 200:\n access_token = response.json().get('access_token')\n return f'Authorization successful! Access Token: {access_token}'\n else:\n return f'Failed to retrieve access token. Status Code: {response.status_code}. Response: {response.text}'\n else:\n return 'Missing code or code_verifier'\n\n\nif __name__ == '__main__':\n app.secret_key = os.urandom(24) # Set a secret key for session management\n app.run(port=100)\n","repo_name":"Syn7hesis/AniMatch","sub_path":"LocalRedirectPort.py","file_name":"LocalRedirectPort.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":"44218135210","text":"def sentidoPercurso(p1,p2,p3):\n a = p2[0] - p1[0]\n b = p3[1] - p1[1]\n c = p3[0] - p1[0]\n d = p2[1] - p1[1]\n a = (a*b)-(c*d)\n if (a > 0):\n return 1\n elif (a < 0):\n return -1\n else:\n return 0\n \ndef poligonoConvexo(poligono,n):\n s = sentidoPercurso(poligono[n-2], poligono[n-1], poligono[0])\n if (s != sentidoPercurso(poligono[n-1], poligono[0], poligono[1])):\n return 0\n for i in range(0,n-2):\n if (s != sentidoPercurso(poligono[i], poligono[i+1], poligono[i+2])):\n return 0\n return 1\n\ndef areaPoligono(poligono,n):\n poligono[n] = poligono[0]\n c = 0\n for i in range(0,n):\n c = c + ((poligono[i][0]*poligono[i+1][1]) - (poligono[i+1][0]*poligono[i][1]))\n return c/2.0\n\ndef teoremaFelizErdos():\n nCasos = int(input())\n while(nCasos > 0):\n pontos = input().split(\" \")\n poligono = [0]*(10+1)\n\n for i in range(10):\n poligono[i] = int(pontos[i])\n \n for i in range(5):\n poligono[i:i+2] = [poligono[i:i+2]]\n\n maneiras = [[poligono[0],poligono[0],poligono[1],poligono[2],poligono[3]],\n [poligono[0],poligono[0],poligono[1],poligono[3],poligono[2]],\n [poligono[0],poligono[0],poligono[2],poligono[1],poligono[3]],\n [poligono[0],poligono[0],poligono[2],poligono[3],poligono[1]],\n [poligono[0],poligono[0],poligono[3],poligono[1],poligono[2]]]\n \n area = 0\n\n ponto = [0,0]\n for i in range(5):\n ponto = [[maneiras[i][0],maneiras[i][0],maneiras[i][1],maneiras[i][2],maneiras[i][3]],\n [maneiras[i][0],maneiras[i][0],maneiras[i][1],maneiras[i][3],maneiras[i][2]],\n [maneiras[i][0],maneiras[i][0],maneiras[i][2],maneiras[i][1],maneiras[i][3]],\n [maneiras[i][0],maneiras[i][0],maneiras[i][2],maneiras[i][3],maneiras[i][1]]]\n if(poligonoConvexo(ponto,4)):\n areaPoligono = abs(areaPoligono(ponto[i],4))\n area = max(area,areaPoligono)\n \n print(area)\n nCasos -= 1\n\nteoremaFelizErdos()","repo_name":"mercietc/Algorithms-Development-and-Implementation---Beecrowd-Challenges","sub_path":"Semana14-Geometria-Discreta-I/teoremaFelizErdos-ERRADO.py","file_name":"teoremaFelizErdos-ERRADO.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"22066899807","text":"from email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\nimport aiosmtplib\nfrom logging import log, INFO\nfrom config import Config\n\nEmail = Config.Email\n\n\nasync def send_email(recipient, subject, message):\n try:\n msg = MIMEText(message)\n msg[\"Subject\"] = subject\n await aiosmtplib.send(message=msg,\n sender=Email.sender_email,\n recipients=recipient,\n hostname=Email.email_server,\n port=Email.email_port,\n username=Email.email_login,\n password=Email.email_password,\n timeout=1,\n start_tls=True)\n log(msg=f\"Success email[{recipient}]: {message}\", level=INFO)\n except Exception as _ex:\n log(msg=f\"{Exception}: {_ex}: Failed to send email[{recipient}]\", level=INFO)\n\n\nasync def send_email_photo(recipient, subject, message, file):\n try:\n msg = MIMEMultipart()\n text = MIMEText(message)\n msg.attach(text)\n msg[\"Subject\"] = subject\n image = MIMEImage(file)\n msg.attach(image)\n await aiosmtplib.send(message=msg,\n sender=Email.sender_email,\n recipients=recipient,\n hostname=Email.email_server,\n port=Email.email_port,\n username=Email.email_login,\n password=Email.email_password,\n timeout=1,\n start_tls=True)\n log(msg=f\"Success email[{recipient}]\", level=INFO)\n except Exception as _ex:\n log(msg=f\"{Exception}: {_ex}: Failed to send email[{recipient}]\", level=INFO)\n","repo_name":"gulyaeve/example_telegram_bot","sub_path":"utils/email_sender.py","file_name":"email_sender.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9701201237","text":"import sys\ninput = sys.stdin.readline#빠른 입력을 위해\n\nminval=10000000000 #최소값을 가장 큰 값으로 설정\nmaxval=-1000000000 #최대값을 가장 작은 값으로 설정\n\nn=int(input()) #수의 개수\nnumbers=list(map(int,input().split())) #숫자들\narr=list(map(int,input().split())) #+,-,*,/ 갯수\n\ndef calc(num,calced,a,b,c,d): #n번째 숫자 num, 이전 호출에서 계산된 값, abcd=사칙연산 갯수\n global minval,maxval #최대,최소값의 전역벽수화\n if num==n-1: #마지막 값인 경우(calc에 num+1과의 계산 값이 있으므로 n-1과 비교) 최대최소 입력\n maxval=max(maxval,calced)\n minval=min(minval,calced)\n\n #이하 식들을 else를 사용하지 않음으로서 모든 계산의 경우에 대해 진행\n\n if a!=0: #+연산이 남은경우\n calc(num+1,calced+numbers[num+1],a-1,b,c,d)\n\n if b!=0: #-연산이 남은경우\n calc(num+1,calced-numbers[num+1],a,b-1,c,d)\n\n if c!=0: #*연산이 남은경우\n calc(num+1,calced*numbers[num+1],a,b,c-1,d)\n\n if d!=0: #/연산이 남은경우\n if calced<0: #만약 음수를 나누는 경우\n temp = (-1)*calced//numbers[num+1] #양수화\n temp = (-1)*temp #결과 음수화\n\n else: \n temp = calced//numbers[num+1] #양수인경우 바로 연산\n\n calc(num+1,temp,a,b,c,d-1) #연산값 대입 후 진행\n\n \n#초기 index 0, 처음숫자 ,+,-,*,/ 개수\ncalc(0,numbers[0],arr[0],arr[1],arr[2],arr[3])\nprint(maxval)\nprint(minval)\n\n\n\n","repo_name":"qkrtndh/coding_test_python","sub_path":"백준/14888/14888.py","file_name":"14888.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25120924055","text":"from copy import deepcopy\n\ndef addr(regs, a, b, c):\n regs[c] = regs[a] + regs[b]\n return regs\n\n\ndef addi(regs, a, b, c):\n regs[c] = regs[a] + b\n return regs\n\n\ndef mulr(regs, a, b, c):\n regs[c] = regs[a] * regs[b]\n return regs\n\n\ndef muli(regs, a, b, c):\n regs[c] = regs[a] * b\n return regs\n\n\ndef banr(regs, a, b, c):\n regs[c] = regs[a] & regs[b]\n return regs\n\n\ndef bani(regs, a, b, c):\n regs[c] = regs[a] & b\n return regs\n\n\ndef borr(regs, a, b, c):\n regs[c] = regs[a] | regs[b]\n return regs\n\n\ndef bori(regs, a, b, c):\n regs[c] = regs[a] | b\n return regs\n\n\ndef setr(regs, a, b, c):\n regs[c] = regs[a]\n return regs\n\n\ndef seti(regs, a, b, c):\n regs[c] = a\n return regs\n\n\ndef gtir(regs, a, b, c):\n regs[c] = 1 if a > regs[b] else 0\n return regs\n\n\ndef gtri(regs, a, b, c):\n regs[c] = 1 if regs[a] > b else 0\n return regs\n\n\ndef gtrr(regs, a, b, c):\n regs[c] = 1 if regs[a] > regs[b] else 0\n return regs\n\n\ndef eqir(regs, a, b, c):\n regs[c] = 1 if a == regs[b] else 0\n return regs\n\n\ndef eqri(regs, a, b, c):\n regs[c] = 1 if regs[a] == b else 0\n return regs\n\n\ndef eqrr(regs, a, b, c):\n regs[c] = 1 if regs[a] == regs[b] else 0\n return regs\n\n\nopcodes = {\n 'addr': addr,\n 'addi': addi,\n 'mulr': mulr,\n 'muli': muli,\n 'banr': banr,\n 'bani': bani,\n 'borr': borr,\n 'bori': bori,\n 'setr': setr,\n 'seti': seti,\n 'gtir': gtir,\n 'gtri': gtri,\n 'gtrr': gtrr,\n 'eqir': eqir,\n 'eqri': eqri,\n 'eqrr': eqrr\n}\n\n\ndef explain(line, opcode, a, b, c):\n \n if opcode == 'addr':\n print(\"%s\\tAdd reg %s and reg %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'addi':\n print(\"%s\\tAdd reg %s and %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'mulr':\n print(\"%s\\tMultiply reg %s and reg %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'muli':\n print(\"%s\\tMultiply reg %s and %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'banr':\n print(\"%s\\treg %s & reg %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'bani':\n print(\"%s\\treg %s & %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'borr':\n print(\"%s\\treg %s | reg %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'bori':\n print(\"%s\\treg %s | %s, stores in reg %s\" % (line, a,b,c))\n if opcode == 'setr':\n print(\"%s\\tcopy reg %s to reg %s\" % (line, a,c))\n if opcode == 'seti':\n print(\"%s\\tcopy %s to reg %s\" % (line, a,c))\n if opcode == 'gtir':\n print(\"%s\\treg %s=%s > reg %s ? 1 : 0\" % (line, c, a, b))\n if opcode == 'gtri':\n print(\"%s\\treg %s=reg %s > %s ? 1 : 0\" % (line, c, a, b))\n if opcode == 'gtrr':\n print(\"%s\\treg %s=reg %s > reg %s ? 1 : 0\" % (line, c, a, b))\n if opcode == 'eqir':\n print(\"%s\\treg %s=%s == reg %s ? 1 : 0\" % (line, c, a, b))\n if opcode == 'eqri':\n print(\"%s\\treg %s=reg %s == %s ? 1 : 0\" % (line, c, a, b))\n if opcode == 'eqrr':\n print(\"%s\\treg %s=reg %s == reg %s ? 1 : 0\" % (line, c, a, b))\n\n\ndef method1(registers, ip_reg, instructions):\n ip = 1\n\n while ip < len(instructions):\n registers[ip_reg] = ip\n # if ip == 3:\n # print(\"!!! new loop ! registers : %s\" % registers)\n debug = \"ip=%s %s\" % (ip, registers)\n s = instructions[ip]\n instruction, a, b, c = s.split()\n a = int(a)\n b = int(b)\n c = int(c)\n registers = opcodes[instruction](registers, a, b, c)\n debug += \" %s %s\" % (s, registers)\n #print(debug)\n #explain(ip, instruction, a, b, c)\n ip = registers[ip_reg] + 1\n\n print(\"register #0=%s\" % registers[0])\n\n\ndef method2(registers, ip_reg, instructions):\n # 1\n registers[3] = 1\n # 2\n registers[5] = 1\n\n while True:\n # print(\"!!! new loop ! registers : %s\" % registers)\n # 3\n registers[2] = registers[3] * registers[5]\n # 4\n registers[2] = 1 if registers[2] == registers[4] else 0\n # 5\n if registers[2] == 1:\n # 7\n registers[0] += registers[3]\n # 6+8\n registers[5] += 1\n # 9\n registers[2] = 1 if registers[5] > registers[4] else 0\n # 10\n if registers[2] == 1:\n # 12\n registers[3] += 1\n # 13\n registers[2] = 1 if registers[3] > registers[4] else 0\n # 14\n if registers[2] == 1:\n # 16\n print(registers[0])\n return\n # 2\n registers[5] = 1\n \"\"\"\n 1 #3 = 1\n\n2 #5 = 1\n\n3 #2 = #3*#5\n4 #2 = 1 if #2 == #4 else 0\n5 jump to 7 if #2 == 1\n6 jump to 8 if #2 == 0\n7 #0 += #3\n8 #5 += 1\n9 #2 = 1 if #5 > #4 else 0\n10 jump to 12 if #2 == 1\n11 jump to 3\n12 #3 += 1\n13 #2 = 1 if #3 > #4\n14 jump to 16 if #2 == 1\n15 jump to 2\n16 jump to 256 (halt)\n \"\"\"\n\n\ndef method3(registers, ip_reg, instructions):\n # 1\n registers[3] = 1\n # 2\n registers[5] = 1\n\n while True:\n # print(\"!!! new loop ! registers : %s\" % registers)\n # 3, 4, 5, 7\n if registers[3] * registers[5] == registers[4]:\n registers[0] += registers[3]\n # 6+8\n registers[5] += 1\n # 9, 10\n if registers[5] > registers[4]:\n # 12\n registers[3] += 1\n # 13, 14\n if registers[3] > registers[4]:\n # 16\n print(registers[0])\n return\n # 2\n registers[5] = 1\n\n\ndef method4(registers, ip_reg, instructions):\n for i in range(1, registers[4]+1):\n for j in range(1, registers[4]+1):\n # if i * j == total, add i\n if i*j == registers[4]:\n registers[0] += i\n break\n print(registers[0])\n\n\ndef method5(registers, ip_reg, instructions):\n result = registers[0]\n v = registers[4]\n for i in range(1, v+1):\n if v % i == 0:\n result += i\n print(result)\n\n\ndata = \"\"\"seti 5 0 1\nseti 6 0 2\naddi 0 1 0\naddr 1 2 3\nsetr 1 0 0\nseti 8 0 4\nseti 9 0 5\n\"\"\"\n\nip_reg = 0\n\ndata = \"\"\"addi 1 16 1\nseti 1 1 3\nseti 1 9 5\nmulr 3 5 2\neqrr 2 4 2\naddr 2 1 1\naddi 1 1 1\naddr 3 0 0\naddi 5 1 5\ngtrr 5 4 2\naddr 1 2 1\nseti 2 6 1\naddi 3 1 3\ngtrr 3 4 2\naddr 2 1 1\nseti 1 6 1\nmulr 1 1 1\naddi 4 2 4\nmulr 4 4 4\nmulr 1 4 4\nmuli 4 11 4\naddi 2 6 2\nmulr 2 1 2\naddi 2 2 2\naddr 4 2 4\naddr 1 0 1\nseti 0 3 1\nsetr 1 4 2\nmulr 2 1 2\naddr 1 2 2\nmulr 1 2 2\nmuli 2 14 2\nmulr 2 1 2\naddr 4 2 4\nseti 0 0 0\nseti 0 4 1\"\"\"\n\nip_reg = 1\n\ninstructions = data.splitlines()\n\n# line = 0\n# for i in instructions:\n# opcode, a, b, c = i.split()\n# explain(line, opcode, a, b, c)\n# line += 1\n\n\n# lines 17 to 35 means :\n# #4 = 2*2*19*11 + 6*22+2\n# 836 + 134 = 970\n# #2 = ((27 * 28 + 29) * 30 * 14) * 32\n#\n# #4 = #4 + #2\n#\n# #2 = 10550400\n# #4 = 10551370\n\n# lines 0 to 16 :\n\"\"\"\n1 #3 = 1\n2 #5 = 1\n3 #2 = #3*#5 = 1\n4 #2 = 1 if #2 == #4 else 0\n5 jump to 7 if #2 == 1\n6 jump to 8 if #2 == 0\n7 #0 += #3\n8 #5 += 1\n9 #2 = 1 if #5 > #4 else 0\n10 jump to 12 if #2 == 1\n11 jump to 3\n12 #3 += 1\n13 #2 = 1 if #3 > #4\n14 jump to 16 if #2 == 1\n15 jump to 2\n16 jump to 256 (halt)\n\n\neq.\n\n#2 = 10550400\n#4 = 10551370\n#3 = 1\n\nwhile #3 <= #4:\n #5 = 1\n while #5 <= #4:\n #2 = #3 * #5\n if #3 * #5 != #4:\n #0 += #3\n #5 += 1\n #3 += 1\n\nso :\n\nfor #3 in range(1, 10551370 + 1):\n for #5 in range (1, 10551370 + 1):\n #2 = #3 * #5\n if #3 * #5 == #4\n #0 += #3\n \nso with #3 = 1 and #5 = 10551370, #3 * #5 == #4\n\nso :\n\na = 1\nfor i in range(1, 10551370+1):\n if 10551370 is divisible by i, add i to a\nprint(a)\n\n\"\"\"\n\nregisters = [0, 0, 0, 0, 10551370, 0]\n\nip_reg = 1\n\ninstructions = data.splitlines()\n# method1(deepcopy(registers), ip_reg, instructions)\n# method2(deepcopy(registers), ip_reg, instructions)\n# method3(deepcopy(registers), ip_reg, instructions)\n# method4(deepcopy(registers), ip_reg, instructions)\nmethod5(deepcopy(registers), ip_reg, instructions)\n#\n# a = 1\n# for i in range(1, registers[4]):\n# a += i\n# print(a)\n","repo_name":"jeremylongo/aoc","sub_path":"day19_2.py","file_name":"day19_2.py","file_ext":"py","file_size_in_byte":8056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70755727845","text":"import os\nfrom django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom fifa.apps.views import PlayerJSONList\n\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(\n r'^$',\n TemplateView.as_view(template_name='base.html'),\n name='homepage'\n ),\n url(r'^admin/', include(admin.site.urls)),\n\n # Clubs\n url(r'^clubs/', include('fifa.apps.clubs.urls', namespace='clubs')),\n\n # Leagues\n url(r'^leagues/', include('fifa.apps.leagues.urls', namespace='leagues')),\n\n # Nations\n url(r'^nations/', include('fifa.apps.nations.urls', namespace='nations')),\n\n # Players\n url(r'^players/', include('fifa.apps.players.urls', namespace='players')),\n\n # API\n url(r'^api/players/$', PlayerJSONList.as_view(), name=\"api\"),\n\n url(r'^djangojs/', include('djangojs.urls')),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns(\n '',\n url(\"^404/$\", TemplateView.as_view(template_name=\"404.html\")),\n url(\"^500/$\", TemplateView.as_view(template_name=\"500.html\")),\n ) + static(\n settings.MEDIA_URL, document_root=settings.MEDIA_ROOT\n ) + static(\n settings.ASSET_URL, document_root=settings.ASSETFILES_ROOT\n ) + static(\n '/node_modules/', document_root=os.path.join(settings.BASE_DIR, 'node_modules')\n )\n","repo_name":"dan-gamble/fifa-x","sub_path":"fifa/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41218155748","text":"\"\"\"\nMinimum Domino version supported by this python-domino library\n\"\"\"\nMINIMUM_SUPPORTED_DOMINO_VERSION = '4.1.0'\n\n\"\"\"\nMinimum Domino version supporting on demand spark cluster\n\"\"\"\nMINIMUM_ON_DEMAND_SPARK_CLUSTER_SUPPORT_DOMINO_VERSION = '4.2.0'\n\n\"\"\"\nEnvironment variable names used by this python-domino library\n\"\"\"\nDOMINO_TOKEN_FILE_KEY_NAME = 'DOMINO_TOKEN_FILE'\nDOMINO_USER_API_KEY_KEY_NAME = 'DOMINO_USER_API_KEY'\nDOMINO_HOST_KEY_NAME = 'DOMINO_API_HOST'\nDOMINO_LOG_LEVEL_KEY_NAME = 'DOMINO_LOG_LEVEL'\n","repo_name":"rion334/python-domino","sub_path":"domino/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"32525272891","text":"import base64\nimport json\nimport string\n\nfrom ioc_finder import find_iocs\n\nfrom machina.core.worker import Worker\nfrom machina.core.models.utils import resolve_db_node_cls\n\ndef _strings(data, min=4):\n result = \"\"\n for c in data:\n if c in string.printable:\n result += c\n continue\n if len(result) >= min:\n yield result\n result = \"\"\n if len(result) >= min: # catch result at EOF\n yield result\n\nclass FindURLs(Worker):\n\n types_blacklist = ['url']\n next_queues = ['Identifier']\n\n def __init__(self, *args, **kwargs):\n super(FindURLs, self).__init__(*args, **kwargs)\n\n def callback(self, data, properties):\n data = json.loads(data)\n\n # resolve path\n target = self.get_binary_path(data['ts'], data['hashes']['md5'])\n\n with open(target, 'r', errors=\"ignore\") as f:\n strings = ' '.join(_strings(f.read()))\n\n urls = find_iocs(strings)['urls']\n\n self.logger.info(f\"found urls: {urls}\")\n\n # get the appropriate OGM class for the object that was analyzed\n obj_cls = resolve_db_node_cls(data['type']) \n obj = obj_cls.nodes.get(uid=data['uid'])\n\n # For each URL, resubmit the URL to Identifier and\n # manually type it as 'url'\n for url in urls:\n data_encoded = base64.b64encode(url.encode()).decode()\n body = json.dumps(\n {\n 'data': data_encoded,\n 'origin': {\n 'ts': data['ts'],\n 'md5': data['hashes']['md5'],\n 'uid': data['uid'],\n 'type': data['type']\n },\n 'type': 'url'\n }\n )\n self.publish_next(body)\n\n","repo_name":"ehrenb/machina-findurls","sub_path":"src/findurls.py","file_name":"findurls.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13098168208","text":"\"\"\"\nState machine processing.\n\n\"\"\"\nfrom microcosm_daemon.reloader import Reloader\n\n\nclass StateMachine:\n \"\"\"\n A state machine for driving daemon processing.\n\n \"\"\"\n def __init__(self, graph, initial_state, never_reload=False):\n self.graph = graph\n self.current_state = initial_state\n self.reloader = Reloader() if graph.metadata.debug and not never_reload else None\n\n def step(self):\n \"\"\"\n Take one step through the state transition.\n\n \"\"\"\n next_state = None\n with self.graph.error_policy:\n with self.graph.sleep_policy:\n next_state = self.current_state(self.graph)\n\n if callable(next_state):\n # advance to a new state\n return next_state\n else:\n # stay in the same state\n return self.current_state\n\n def advance(self):\n \"\"\"\n Advance once step.\n\n \"\"\"\n self.current_state = self.step()\n return self.current_state\n\n def should_run(self):\n \"\"\"\n Should the state machine keep running?\n\n \"\"\"\n return (\n self.current_state and\n not self.graph.signal_handler.interrupted\n )\n\n def run(self):\n \"\"\"\n Run the state machine.\n\n \"\"\"\n try:\n with self.graph.signal_handler:\n while self.should_run():\n self.advance()\n if self.reloader:\n self.reloader()\n except Exception:\n pass\n","repo_name":"globality-corp/microcosm-daemon","sub_path":"microcosm_daemon/state_machine.py","file_name":"state_machine.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29159079514","text":"import cv2 as cv\n\nimg = cv.imread(\"D:\\Personal\\Pictures\\wallpaper\\woman.jpg\")\nimg = cv.resize(img, None, fx = 0.2, fy = 0.2)\n\nimgUp = cv.pyrUp(img)\nimgDown = cv.pyrDown(imgUp)\ndiffer = img - imgDown\n\ncv.imshow(\"Origenal Image\", img)\ncv.imshow(\"Up Image\", imgUp)\ncv.imshow(\"Down Image\", imgDown)\ncv.imshow(\"Differ Image\", differ)\n\ncv.waitKey(0)\ncv.destroyAllWindows()","repo_name":"Aaron-labo/OpenCV_StudyNotes","sub_path":"7_pyramids.py","file_name":"7_pyramids.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42125716109","text":"from test_framework import generic_test\n\n\n#O(n) for a brute force by going through each bit, O(1) Space\n# def parity(x):\n# numOnes = 0\n#\n# while (x):\n# if ((x & 1) == 1):\n# numOnes += 1\n# x = x >> 1\n# return numOnes % 2\n\n#O(k), let k be the number of bits set to 1 in a particular word. O(1) Space\ndef parity(x):\n result = 0\n while x:\n result = result ^ 1\n x = x & (x - 1)\n return result\n\n#O(n/L) time complexity with caching where n is the word size(For example 64 bits)\n#and L is the width of the key in bits (For example 16 bits)\n\n#O(log n) solution where n is the word size by using XOR. We can combine caching and this approach\n# def parity(x):\n# x = x ^ (x >> 32)\n# x = x ^ (x >> 16)\n# x = x ^ (x >> 8)\n# x = x ^ (x >> 4)\n# x = x ^ (x >> 2)\n# x = x ^ (x >> 1)\n# return x & 0x1\n\n\nif __name__ == '__main__':\n exit(generic_test.generic_test_main(\"parity.py\", 'parity.tsv', parity))\n","repo_name":"sCAIwalker/MyEPISolutions","sub_path":"parity.py","file_name":"parity.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26041412470","text":"import pygame\r\nimport os\r\n\r\nclass Player(pygame.sprite.Sprite):\r\n def __init__(self, file_to_load, x, y):\r\n super().__init__()\r\n self.sprite_sheet = pygame.image.load(file_to_load)\r\n print(\"self.sprite_sheet: \" + str(self.sprite_sheet))\r\n self.position = [x, y]\r\n self.speed = 1\r\n self.running = False\r\n self.moving = [0, 0]\r\n\r\n self.looks = {\r\n \"down\": 0,\r\n \"left\": 1,\r\n \"right\": 2,\r\n \"up\": 3\r\n }\r\n \r\n self.walk = 1\r\n self.current_look = \"down\"\r\n\r\n self.image = self.get_image(self.walk, self.looks[\"down\"])\r\n self.image.set_colorkey((0, 0, 0))\r\n self.rect = self.image.get_rect()\r\n \r\n self.feet = pygame.Rect(self.rect.x, self.rect.y + self.rect.height, self.rect.width, 1)\r\n \r\n def stay(self):\r\n self.walk = 1\r\n self.image = self.get_image(self.walk, self.looks[self.current_look])\r\n self.image.set_colorkey((0, 0, 0))\r\n return self.image\r\n\r\n def walk_animation(self):\r\n self.walk += 1\r\n if (self.walk > 2):\r\n self.walk = 0\r\n print(self.current_look)\r\n self.image = self.get_image(self.walk, self.looks[self.current_look])\r\n self.image.set_colorkey((0, 0, 0))\r\n\r\n\r\n def key_pressed(self, key):\r\n if key[pygame.K_UP]:\r\n self.moving[1] = - 5\r\n self.current_look = \"up\"\r\n if key[pygame.K_DOWN]:\r\n self.moving[1] = 5\r\n self.current_look = \"down\"\r\n if key[pygame.K_LEFT]:\r\n self.moving[0] = -5\r\n self.current_look = \"left\"\r\n if key[pygame.K_RIGHT]:\r\n self.moving[0] = 5\r\n self.current_look = \"right\"\r\n \r\n def key_released(self, event):\r\n if (event.key == pygame.K_UP):\r\n if (self.moving[0] == -5):\r\n self.current_look = \"left\"\r\n elif (self.moving[0] == 5):\r\n self.current_look = \"right\"\r\n self.moving[1] = 0\r\n elif (event.key == pygame.K_DOWN):\r\n if (self.moving[0] == -5):\r\n self.current_look = \"left\"\r\n elif (self.moving[0] == 5):\r\n self.current_look = \"right\"\r\n self.moving[1] = 0\r\n elif (event.key == pygame.K_LEFT):\r\n if (self.moving[1] == -5):\r\n self.current_look = \"up\"\r\n elif (self.moving[1] == 5):\r\n self.current_look = \"down\"\r\n self.moving[0] = 0\r\n elif (event.key == pygame.K_RIGHT):\r\n if (self.moving[1] == -5):\r\n self.current_look = \"up\"\r\n elif (self.moving[1] == 5):\r\n self.current_look = \"down\"\r\n self.moving[0] = 0\r\n\r\n # moving = [x, y]\r\n \r\n \r\n def check_collision(self, future_x, future_y, walls):\r\n future_feet = pygame.Rect(future_x, future_y + self.rect.height, self.rect.width, 1)\r\n if (future_feet.collidelist(walls) != -1):\r\n return True\r\n return False\r\n\r\n def move(self, walls):\r\n if (self.check_collision(self.position[0] + (self.moving[0] * self.speed), self.position[1] + (self.moving[1] * self.speed), walls) == True):\r\n return\r\n self.position[0] += (self.moving[0] * self.speed)\r\n self.position[1] += (self.moving[1] * self.speed)\r\n if (self.moving[0] != 0 or self.moving[1] != 0):\r\n self.walk_animation()\r\n else:\r\n self.stay()\r\n \r\n def update(self, screen):\r\n self.rect.x = self.position[0]\r\n self.rect.y = self.position[1]\r\n screen.blit(self.image, self.rect)\r\n \r\n def get_image(self, x, y):\r\n image = pygame.Surface([32, 32])\r\n image.blit(self.sprite_sheet, (0, 0), (x * 32, y * 32, 32, 32))\r\n return image\r\n \r\n ","repo_name":"Petroflo/Roots-ggj","sub_path":"Graphical_Engine/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37414848229","text":"import sys\nimport tempfile\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\n\npath = (Path(__file__).parents[1]).as_posix()\nsys.path.insert(0, path)\n\nfrom tracking.data_association import (\n bipartite_local_matching,\n clean_detections,\n get_detections,\n get_detections_array,\n get_detections_with_disparity,\n get_iou,\n hungarian_global_matching,\n is_bbox_in_bbox,\n load_disparities,\n load_tracks_from_cvat_txt_format,\n load_tracks_from_mot_format,\n make_array_from_dets,\n make_array_from_tracks,\n make_dets_from_array,\n make_tracks_from_array,\n match_detections,\n save_tracks_to_cvat_txt_format,\n save_tracks_to_mot_format,\n zero_out_of_image_bboxs,\n)\nfrom tracking.stats import (\n get_gt_object_match,\n get_stats_for_frame,\n get_stats_for_track,\n get_stats_for_tracks,\n)\nfrom tracking.stereo_gt import get_matched_track_ids, load_matched_tracks_ids\nfrom tracking.tracklet_operations import (\n add_remove_tracks_by_disp_infos,\n append_tracks_with_cam_id_match_id,\n arrange_track_ids,\n get_candidates_disparity_infos,\n get_matches_from_candidates_disparity_infos,\n match_primary_track_to_secondry_tracklets,\n remove_detects_change_track_ids,\n remove_short_tracks,\n select_from_overlaps,\n)\n\ndata_path = Path(__file__).parent / \"data\"\nannos = load_tracks_from_cvat_txt_format(data_path / \"04_07_22_G_2_rect_valid_gt.txt\")\natracks = load_tracks_from_cvat_txt_format(data_path / \"tracks.txt\")\nim_width, im_height = 2098, 1220\n\n\ndef test_get_iou():\n det1 = (0, 0, 4, 2)\n det2 = (2, 1, 3, 2)\n\n np.testing.assert_equal(get_iou(det1, det2), 0.125)\n\n det1 = (0, 0, 4, 2)\n det2 = (4, 2, 5, 6)\n np.testing.assert_equal(get_iou(det1, det2), 0.0)\n\n\ndef test_is_bbox_in_bbox():\n adets = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_2.txt\", im_width, im_height, 1\n )\n assert is_bbox_in_bbox(adets[5, 3:7], adets[1, 3:7]) == True\n assert is_bbox_in_bbox(adets[1, 3:7], adets[5, 3:7]) == False\n assert is_bbox_in_bbox(adets[1, 3:7], adets[8, 3:7]) == False\n\n\ndef test_load_tracks_from_cvat_txt_format():\n tracks = make_tracks_from_array(atracks)\n tracks_array = make_array_from_tracks(tracks)\n\n with tempfile.NamedTemporaryFile() as tmp:\n track_file = tmp.name\n save_tracks_to_cvat_txt_format(Path(track_file), atracks)\n atracks_new = load_tracks_from_cvat_txt_format(Path(track_file))\n np.testing.assert_equal(atracks_new[:, :2], atracks[:, :2])\n np.testing.assert_almost_equal(atracks_new[:, 3:], atracks[:, 3:], decimal=0)\n\n np.testing.assert_equal(tracks_array[:, :2], atracks[:, :2])\n np.testing.assert_almost_equal(tracks_array[:, 3:], atracks[:, 3:], decimal=0)\n\n\ndef test_load_tracks_from_mot_format():\n with tempfile.TemporaryDirectory() as tmp_dir:\n save_tracks_to_mot_format(Path(tmp_dir) / \"tmp.zip\", atracks, make_zip=False)\n atracks_new = load_tracks_from_mot_format(Path(tmp_dir) / \"gt/gt.txt\")\n np.testing.assert_equal(atracks_new[:, :2], atracks[:, :2])\n np.testing.assert_almost_equal(atracks_new[:, 3:], atracks[:, 3:], decimal=0)\n\n\ndef test_make_tracks_from_array_and_reverse():\n tracks = make_tracks_from_array(annos)\n tracks_array = make_array_from_tracks(tracks)\n\n np.testing.assert_equal(tracks_array[:, :2], annos[:, :2])\n np.testing.assert_almost_equal(tracks_array[:, 3:], annos[:, 3:], decimal=0)\n\n\ndef test_get_gt_object_match():\n det1, det2 = get_gt_object_match(\n atracks, annos, track_id=4, frame_number=0, thres=20\n )\n assert det1[0] == 4\n assert det2[0] == 5\n\n det1, det2 = get_gt_object_match(\n atracks, annos, track_id=28, frame_number=32, thres=20, min_iou=0.05\n )\n assert det1[0] == 28\n assert det2[0] == 1\n\n det1, det2 = get_gt_object_match(\n atracks, annos, track_id=28, frame_number=32, thres=20, min_iou=0.2\n )\n assert det1[0] == 28\n assert det2 == None\n\n\ndef test_get_gt_object_match_frame0():\n frame_number = 0\n gt_track_ids = np.unique(annos[annos[:, 1] == frame_number, 0])\n matched_ids = []\n for gt_track_id in gt_track_ids:\n det1, det2 = get_gt_object_match(\n atracks, annos, gt_track_id, frame_number, thres=20, min_iou=0.1\n )\n if det2 is not None:\n matched_ids.append([det1[0], det2[0]])\n matched_ids = np.array(matched_ids).astype(np.int64)\n\n desired = np.round(\n np.loadtxt(data_path / \"matched_ids_frame0.txt\", skiprows=1, delimiter=\",\")\n ).astype(np.int64)\n np.testing.assert_equal(matched_ids, desired)\n\n\ndef test_get_stats_for_frame():\n tp, fp, fn = get_stats_for_frame(annos, atracks, 0)\n np.testing.assert_equal((tp, fp, fn), (36, 5, 1))\n\n\ndef test_get_stats_for_track():\n gt_track_id = 7\n desired = np.loadtxt(\n data_path / f\"matched_ids_track{gt_track_id}.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n tp, fp, fn, sw, uid, matched_ids = get_stats_for_track(annos, atracks, gt_track_id)\n np.testing.assert_equal(matched_ids, desired)\n np.testing.assert_equal((tp, fp, fn, sw, uid), (567, 0, 33, 0, 1))\n\n gt_track_id = 5\n desired = np.loadtxt(\n data_path / f\"matched_ids_track{gt_track_id}.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n tp, fp, fn, sw, uid, matched_ids = get_stats_for_track(annos, atracks, gt_track_id)\n np.testing.assert_equal(matched_ids, desired)\n np.testing.assert_equal((tp, fp, fn, sw, uid), (419, 0, 181, 49, 3))\n\n gt_track_id = 28\n desired = np.loadtxt(\n data_path / f\"matched_ids_track{gt_track_id}.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n tp, fp, fn, sw, uid, matched_ids = get_stats_for_track(annos, atracks, gt_track_id)\n np.testing.assert_equal(matched_ids, desired)\n np.testing.assert_equal((tp, fp, fn, sw, uid), (341, 0, 258, 193, 14))\n assert tp + fn == len(annos[annos[:, 0] == gt_track_id])\n\n\ndef test_get_stats_for_track_after_iou_bug():\n atracks = load_tracks_from_cvat_txt_format(data_path / \"tracks_iou_bug.txt\")\n gt_track_id = 28\n tp, fp, fn, sw, uid, _ = get_stats_for_track(annos, atracks, gt_track_id)\n np.testing.assert_equal((tp, fp, fn, sw, uid), (346, 0, 253, 199, 14))\n assert tp + fn == len(annos[annos[:, 0] == gt_track_id])\n\n\ndef test_make_array_from_dets_reverse():\n dets = get_detections(\n data_path / \"04_07_22_G_2_rect_valid_2.txt\", im_width, im_height, 1\n )\n dets_array = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_2.txt\", im_width, im_height, 1\n )\n actual = make_array_from_dets(dets)\n np.testing.assert_equal(actual, dets_array)\n\n actual = make_dets_from_array(dets_array)\n assert actual[10].x == dets[10].x\n assert actual[10].y == dets[10].y\n assert actual[10].w == dets[10].w\n assert actual[10].h == dets[10].h\n assert actual[10].frame_number == dets[10].frame_number\n assert actual[10].det_id == dets[10].det_id\n\n\ndef test_clean_detections():\n dets_array = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_2.txt\", im_width, im_height, 1\n )\n cleaned_dets = clean_detections(dets_array)\n removed_det_ids = [0, 2, 12, 25, 1, 5, 8, 10, 6]\n assert len(cleaned_dets) == len(dets_array) - len(removed_det_ids)\n for det_id in removed_det_ids:\n assert det_id not in list(cleaned_dets[:, 0])\n\n\ndef test_match_ddetections():\n desired = np.loadtxt(\n data_path / \"matched_ids_dets.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n adets1 = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_2.txt\", im_width, im_height, 1\n )\n adets2 = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_3.txt\", im_width, im_height, 2\n )\n _, _, matched_ids = match_detections(adets1, adets2)\n idxs1, idxs2, matched_ids_cleaned = match_detections(\n clean_detections(adets1), clean_detections(adets2)\n )\n assert len(matched_ids) == 39\n np.testing.assert_equal(matched_ids_cleaned, desired)\n assert matched_ids_cleaned[0, 0] == clean_detections(adets1)[idxs1[0], 2]\n assert matched_ids_cleaned[0, 1] == clean_detections(adets2)[idxs2[0], 2]\n\n\ndef test_match_ddetections2():\n adets1 = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_1.txt\", im_width, im_height, 0\n )\n adets2 = get_detections_array(\n data_path / \"04_07_22_G_2_rect_valid_2.txt\", im_width, im_height, 1\n )\n _, _, matched_ids = match_detections(adets1, adets2)\n idxs1, idxs2, matched_ids_cleaned = match_detections(\n clean_detections(adets1), clean_detections(adets2)\n )\n assert matched_ids_cleaned[0, 0] == clean_detections(adets1)[idxs1[0], 2]\n assert matched_ids_cleaned[0, 1] == clean_detections(adets2)[idxs2[0], 2]\n assert matched_ids_cleaned[-1, 0] == clean_detections(adets1)[idxs1[-1], 2]\n assert matched_ids_cleaned[-1, 1] == clean_detections(adets2)[idxs2[-1], 2]\n\n\ndef test_bipartite_matching():\n pred_dets = load_tracks_from_cvat_txt_format(data_path / \"pred_dets_56.txt\")\n dets = load_tracks_from_cvat_txt_format(data_path / \"dets_56.txt\")\n pred_ids, ids = bipartite_local_matching(\n make_dets_from_array(pred_dets), make_dets_from_array(dets)\n )\n desired = np.loadtxt(\n data_path / \"matched_ids_56.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n np.testing.assert_equal(pred_ids, desired[:, 0])\n np.testing.assert_equal(ids, desired[:, 1])\n\n\ndef test_hungarian_global_matching():\n pred_dets = load_tracks_from_cvat_txt_format(data_path / \"pred_dets_56.txt\")\n dets = load_tracks_from_cvat_txt_format(data_path / \"dets_56.txt\")\n pred_ids, ids = hungarian_global_matching(\n make_dets_from_array(pred_dets), make_dets_from_array(dets)\n )\n desired = np.loadtxt(\n data_path / \"matched_ids_56.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n np.testing.assert_equal(pred_ids, desired[:, 0])\n np.testing.assert_equal(ids, desired[:, 1])\n\n\n@pytest.mark.slow\ndef test_get_stats_for_tracks():\n desired = np.loadtxt(\n data_path / \"track_stats.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n track_stats = get_stats_for_tracks(annos, atracks)\n np.testing.assert_equal(track_stats, desired)\n for gt_track_id in range(40):\n tp = track_stats[gt_track_id, 1]\n fn = track_stats[gt_track_id, 3]\n assert tp + fn == len(annos[annos[:, 0] == gt_track_id])\n\n\n@pytest.mark.temp\ndef test_get_stats_for_track_after_no_prediction():\n atracks = load_tracks_from_cvat_txt_format(data_path / \"tracks_no_prediction.txt\")\n track_stats = get_stats_for_tracks(annos, atracks)\n desired = np.loadtxt(\n data_path / \"track_stats_no_prediction.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n np.testing.assert_equal(track_stats, desired)\n for gt_track_id in range(40):\n tp = track_stats[gt_track_id, 1]\n fn = track_stats[gt_track_id, 3]\n assert tp + fn == len(annos[annos[:, 0] == gt_track_id])\n\n\n@pytest.mark.temp\ndef test_get_stats_for_track_after_new_tracks():\n atracks = load_tracks_from_cvat_txt_format(data_path / \"tracks_new_tracks.txt\")\n track_stats = get_stats_for_tracks(annos, atracks)\n desired = np.loadtxt(\n data_path / \"track_stats_new_tracks.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n np.testing.assert_equal(track_stats, desired)\n for gt_track_id in range(40):\n tp = track_stats[gt_track_id, 1]\n fn = track_stats[gt_track_id, 3]\n assert tp + fn == len(annos[annos[:, 0] == gt_track_id])\n\n\n@pytest.mark.temp\ndef test_get_stats_for_track_after_remove_occlusions():\n atracks = load_tracks_from_cvat_txt_format(\n data_path / \"tracks_remove_occlusions.txt\"\n )\n track_stats = get_stats_for_tracks(annos, atracks)\n desired = np.loadtxt(\n data_path / \"track_stats_remove_occlusions.txt\", skiprows=1, delimiter=\",\"\n ).astype(np.int64)\n np.testing.assert_equal(track_stats, desired)\n for gt_track_id in range(40):\n tp = track_stats[gt_track_id, 1]\n fn = track_stats[gt_track_id, 3]\n assert tp + fn == len(annos[annos[:, 0] == gt_track_id])\n\n\n@pytest.mark.temp\ndef test_disparities():\n desired = load_disparities(data_path / \"disparities_frame81.txt\")\n disparities = get_detections_with_disparity(\n data_path / \"04_07_22_F_2_rect_valid_82.txt\",\n data_path / \"04_07_22_G_2_rect_valid_82.txt\",\n im_width,\n im_height,\n )\n actual = []\n for disparity in disparities:\n if len(disparity.candidates) != 0:\n actual.append(disparity)\n for disp_act, disp_desired in zip(actual, desired):\n assert disp_act.track_id == disp_desired.track_id\n assert disp_act.frame_number == disp_desired.frame_number\n assert disp_act.det_id == disp_desired.det_id\n assert disp_act.candidates == disp_desired.candidates\n assert disp_act.det_ids == disp_desired.det_ids\n\n\n@pytest.mark.slow\ndef test_get_matched_track_ids():\n desired = np.array(load_matched_tracks_ids())\n\n annos1 = load_tracks_from_cvat_txt_format(\n data_path / \"04_07_22_F_2_rect_valid_gt.txt\"\n )\n matches = np.array(get_matched_track_ids(annos1, annos))\n matches = matches[matches[:, 2] < 5]\n np.testing.assert_equal(matches[:, :2], desired[:, :2])\n\n\nfrom tracking.data_association import (\n cen_wh_from_tl_br,\n get_track_from_track_id,\n interpolate_two_bboxes,\n tl_br_from_cen_wh,\n)\nfrom tracking.stereo_gt import get_disparity_info_from_stereo_track\nfrom tracking.tracklet_operations import (\n add_remove_tracks,\n get_start_ends_missing_frames,\n)\n\n\n# TODO maybe remove\ndef test_add_remove_tracks():\n remove_tracks = np.random.randint(10, size=(3, 2))\n remove_lengths = np.random.randint(10, size=(3, 2))\n add_tracks = np.empty(shape=(0, 2), dtype=np.int64)\n\n desired = remove_tracks.copy()\n inds = np.array([0])\n while remove_tracks.size != 0:\n remove_tracks, remove_lengths, add_tracks = add_remove_tracks(\n remove_tracks, remove_lengths, add_tracks, inds\n )\n np.testing.assert_equal(add_tracks, desired)\n assert remove_tracks.size == 0\n assert remove_lengths.size == 0\n\n\ndef test_get_disparity_info_from_stereo_track():\n annos1 = load_tracks_from_cvat_txt_format(\n data_path / \"04_07_22_F_2_rect_valid_gt.txt\"\n )\n annos2 = annos.copy()\n\n len_disparity = 20\n track1_id = 21\n track2_id = 16\n track1 = get_track_from_track_id(annos1, track1_id)\n track2 = get_track_from_track_id(annos2, track2_id)\n disparity_info = get_disparity_info_from_stereo_track(\n track1[: 80 + len_disparity], track2[80:150]\n )\n align_errors = disparity_info[:, 3]\n desired = np.array([1, 1, 0, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2, 2, 0, 2, 1])\n assert disparity_info.shape[0] == len_disparity\n np.testing.assert_equal(align_errors, desired)\n np.testing.assert_equal(disparity_info[:, 0], np.repeat(track1_id, len_disparity))\n np.testing.assert_equal(disparity_info[:, 1], np.repeat(track2_id, len_disparity))\n np.testing.assert_equal(disparity_info[:, 2], np.arange(80, 100))\n\n\ndef test_interpolate_two_bboxes():\n bbox1 = 2, 2, 5, 5\n bbox2 = 22, 32, 15, 25\n frame_number1 = 20\n frame_number2 = 24\n bboxes = interpolate_two_bboxes(bbox1, bbox2, frame_number1, frame_number2)\n desired = [\n (7.0, 9.5, 7.5, 10.0),\n (12.0, 17.0, 10.0, 15.0),\n (17.0, 24.5, 12.5, 20.0),\n ]\n np.testing.assert_equal(bboxes, desired)\n\n\ndef test_get_start_ends_missing_frames():\n missing_frames = np.array([4, 5, 6, 10, 11, 15, 18, 19])\n desired = [(3, 7), (9, 12), (14, 16), (17, 20)]\n\n start_ends = get_start_ends_missing_frames(missing_frames)\n np.testing.assert_equal(start_ends, desired)\n\n missing_frames = np.append(missing_frames, 25)\n desired = desired + [(24, 26)]\n\n start_ends = get_start_ends_missing_frames(missing_frames)\n np.testing.assert_equal(start_ends, desired)\n\n\ndef test_tl_br_from_cen_wh_and_reverse():\n det = np.array([43, 599, 0, 430, 440, 466, 461, 448, 450, 36, 21])\n cen_wh = cen_wh_from_tl_br(*det[3:7])\n tl_br = tl_br_from_cen_wh(*det[7:])\n\n np.testing.assert_almost_equal(cen_wh, det[7:11], decimal=0)\n np.testing.assert_almost_equal(tl_br, det[3:7], decimal=0)\n\n\n# TODO: remove?\n@pytest.mark.slow\ndef test_add_remove_tracks_by_disp_infos():\n annos1 = load_tracks_from_cvat_txt_format(\n data_path / \"04_07_22_F_2_rect_valid_gt.txt\"\n )\n annos2 = annos.copy()\n tracks1 = arrange_track_ids(\n remove_short_tracks(remove_detects_change_track_ids(annos1), 10)\n )\n tracks2 = arrange_track_ids(\n remove_short_tracks(remove_detects_change_track_ids(annos2), 10)\n )\n\n ls_tracks = np.empty(shape=(0, 13), dtype=np.int64)\n p_track = get_track_from_track_id(tracks2, 14)\n s_tracks = append_tracks_with_cam_id_match_id(tracks1, 1)\n cands = match_primary_track_to_secondry_tracklets(p_track, tracks1)\n ls_tracks, new_s_tracks = add_remove_tracks_by_disp_infos(\n cands, ls_tracks, s_tracks\n )\n track_item = new_s_tracks[(new_s_tracks[:, 0] == 72) & (new_s_tracks[:, 1] == 500)]\n assert track_item.size != 0\n assert ls_tracks.shape[0] + new_s_tracks.shape[0] == s_tracks.shape[0]\n\n\ndef test_get_matches_from_candidates_disparity_infos():\n annos1 = load_tracks_from_cvat_txt_format(\n data_path / \"04_07_22_F_2_rect_valid_gt.txt\"\n )\n annos2 = annos.copy()\n tracks1 = arrange_track_ids(\n remove_short_tracks(remove_detects_change_track_ids(annos1), 10)\n )\n tracks2 = arrange_track_ids(\n remove_short_tracks(remove_detects_change_track_ids(annos2), 10)\n )\n\n p_tracks = append_tracks_with_cam_id_match_id(tracks1, 1)\n s_tracks = append_tracks_with_cam_id_match_id(tracks2, 2)\n p_track = get_track_from_track_id(p_tracks, 20)\n cands = get_candidates_disparity_infos(p_track, s_tracks)\n\n sel_track_id = select_from_overlaps(4, [5, 16], cands)\n assert sel_track_id == 16\n sel_track_id = select_from_overlaps(72, [73], cands)\n assert sel_track_id == 73\n cands2 = get_matches_from_candidates_disparity_infos(cands)\n np.testing.assert_equal(np.unique(cands2[:, 1]), np.array([16, 53, 73, 83]))\n\n\ndef test_zero_out_of_image_bboxs():\n bboxs = np.array(\n [\n [9, 205, -1, 216, 27],\n [10, 489, 30, 501, 49],\n [11, 406, 427, 417, 434],\n [5, 416, 548, 453, 570],\n [6, 541, 515, 558, 529],\n ]\n )\n desired = np.array(\n [\n [9, 205, 0, 216, 27],\n [10, 489, 30, 501, 49],\n [11, 0, 0, 0, 0],\n [5, 0, 0, 0, 0],\n [6, 0, 0, 0, 0],\n ]\n )\n actual = zero_out_of_image_bboxs(bboxs, 512, 256)\n np.testing.assert_equal(actual, desired)\n\n\n\"\"\"\na = np.random.randint(10, size=(3, 2))\nb = np.empty(shape=(0, 2), dtype=np.int64)\nwhile a.size != 0:\n inds = np.array([0])\n b = np.append(b, a[inds], axis=0)\n a = np.delete(a, inds, axis=0)\n\n# 21 <-> 16\n# 21 -> 17, 72 len:(236, 332)\n# 16 -> 14, 79 len: (361, 219)\n# 17 <-> 14\n# 72 <-> 14, 79\n\n# 7 <-> 24\n# 7 -> 5, 54, 71, 79, 84, 90 len:(80, 107, 39, 12, 58, 201)\n# 24 -> 21, 63 len:(262, 313)\n# 21 <-> 5, 54, 71\n# 63 <-> 79, 84, 90\n\n\n# tk.match_primary_track_to_secondry_tracklets(p_track1, tracks2)\n# [[14, 1.0], [38, 6.0], [39, 3.0], [48, 2.0], [50, 1.0], [56, 6.0]]\n\n\np_track = da.get_track_from_track_id(annos1, 7)\ns_track = da.get_track_from_track_id(annos2, 24)\n\nfig, axs = plt.subplots(1, 2, sharex=True)\naxs[0].plot(p_track[:,1], p_track[:,8],'-*',label='p_annos')\naxs[0].plot(s_track[:,1], s_track[:,8],'-*',label='s_annos')\n\nfor track_id in [21, 63]:\n track = da.get_track_from_track_id(tracks2, track_id)\n axs[1].plot(track[:,1], track[:,8],'-*',label=f's_{track_id}')\n\nfor track_id in [5, 54, 71, 79, 84, 90]:\n track = da.get_track_from_track_id(tracks1, track_id)\n axs[1].plot(track[:,1], track[:,8],'-*',label=f'p_{track_id}')\naxs[1].legend()\n\"\"\"\n","repo_name":"fkariminejadasl/tracking","sub_path":"tests/tests_data_association.py","file_name":"tests_data_association.py","file_ext":"py","file_size_in_byte":20129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4424152828","text":"from typing import Final\nfrom pathlib import Path\n\n\n# Endpoint to request access tokens\nBLIZZARD_TOKENS_URL: Final[str] = \"https://us.battle.net/oauth/token\"\n\n# Brazilian Realms\nBRAZILIAN_REALMS: Final[str] = [\"azralon\", \"nemesis\", \"goldrinn\", \"gallywix\", \"tol-barad\"]\n\n# Endpoint that provides the PVP Data\nPVP_RATING_API: Final[str] = (\n \"https://us.api.blizzard.com/data/wow/pvp-season/{session}/pvp-leaderboard/{bracket}?\"\n \"namespace=dynamic-us&locale=en_US&access_token={accessToken}\"\n)\n\n# Endpoint that returns the character's profile data\nPROFILE_API: Final[str] = (\n \"https://us.api.blizzard.com/profile/wow/character/{realmSlug}/{charName}?namespace=profile-us&locale=en_US\"\n \"&access_token={accessToken}\"\n)\n\n# Endpoint that returns the character's pictures\nCHAR_MEDIA_API: Final[str] = (\n \"https://us.api.blizzard.com/profile/wow/character/{realmSlug}/{charName}/character-media?namespace=profile-us\"\n \"&locale=en_US&access_token={accessToken}\"\n)\n\n# Endpoint that returns all the data from wow classes\nALL_CLASSES_API: Final[\n str\n] = \"https://us.api.blizzard.com/data/wow/playable-class/index?namespace=static-us&locale=en_US&access_token={accessToken}\"\n\n# Endpoint that returns the icon for a wow class\nCLASS_MEDIA_API: Final[str] = (\n \"https://us.api.blizzard.com/data/wow/media/playable-class/{classId}?namespace=static-us&locale=en_US\"\n \"&access_token={accessToken}\"\n)\n\n# Endpoint that returns all the data from specs\nALL_SPECS_API: Final[str] = (\n \"https://us.api.blizzard.com/data/wow/playable-specialization/index?namespace=static-us&locale=en_US\"\n \"&access_token={accessToken}\"\n)\n\n# Endpoint that returns the icon for a class spec\nSPEC_MEDIA_API: Final[str] = (\n \"https://us.api.blizzard.com/data/wow/media/playable-specialization/{specId}?namespace=static-us&locale=en_US\"\n \"&access_token={accessToken}\"\n)\n\n# Timeout setting for the requests (In seconds)\nTIMEOUT: Final[int] = 30\n\n# Delay time between requests in order to not be affected by throttle\nDELAY: Final[int] = 3\n\n# Number of requests per second\nREQUESTS_PER_SEC: Final[int] = 100\n\n# Amount of time a HTTP request must be re-sent\nMAX_RETRIES: Final[int] = 5\n\n# Setting for the recurrence time of the fetching process (In seconds)\nUPDATE_EVERY: Final[int] = 15\n\n# Directory outside of src\nBASE_DIR = Path(__file__).resolve().parent.parent.parent\n","repo_name":"firminoneto11/wow-arena-leaderboards","sub_path":"backend/service/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37018573391","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\inflight\\squadrons\\abilityIcon.py\r\nfrom carbonui.primitives.container import Container\r\nimport carbonui.const as uiconst\r\nfrom carbonui.primitives.sprite import Sprite\r\nfrom eve.client.script.ui.control.eveIcon import Icon\r\nfrom eve.client.script.ui.control.eveLabel import EveLabelSmall\r\nfrom eve.client.script.ui.inflight.squadrons.shipFighterState import GetShipFighterState\r\nfrom localization import GetByMessageID\r\n\r\nclass AbilityIcon(Container):\r\n default_width = 48\r\n default_height = 48\r\n default_align = uiconst.TOPLEFT\r\n default_state = uiconst.UI_NORMAL\r\n\r\n def ApplyAttributes(self, attributes):\r\n Container.ApplyAttributes(self, attributes)\r\n self.shipFighterState = GetShipFighterState()\r\n self.stateLabel = EveLabelSmall(parent=self, align=uiconst.CENTER)\r\n self.controller = attributes.controller\r\n self.slotID = self.controller.slotID\r\n self.fighterID = attributes.fighterID\r\n ability = self.GetAbilityInfo()\r\n nameID = ability.displayNameID\r\n iconID = ability.iconID\r\n self.abilityIcon = Icon(parent=self, align=uiconst.CENTER, width=32, height=32, icon=iconID)\r\n bgSprite = Sprite(parent=self, align=uiconst.CENTER, width=64, height=64, texturePath='res:/UI/Texture/classes/ShipUI/Fighters/slotFighterAbility.png')\r\n self.abilityIcon.SetSize(32, 32)\r\n self.abilityIcon.OnClick = self.OnAbilityClick\r\n if not self.controller.IsAbilityActive():\r\n self.SetModuleDeactivated()\r\n self.targetMode = ability.targetMode\r\n self.abilityIcon.hint = GetByMessageID(nameID)\r\n self.shipFighterState.signalOnAbilityActivated.connect(self.OnAbilityActivated)\r\n self.shipFighterState.signalOnAbilityDeactivated.connect(self.OnAbilityDeactivated)\r\n\r\n def GetAbilityInfo(self):\r\n ability = self.controller.GetAbilityInfo()\r\n return ability\r\n\r\n def OnAbilityActivated(self, fighterID, slotID):\r\n if slotID == self.slotID and fighterID == self.fighterID:\r\n self.SetModuleActivated()\r\n\r\n def OnAbilityDeactivated(self, fighterID, slotID):\r\n if slotID == self.slotID and fighterID == self.fighterID:\r\n self.SetModuleDeactivated()\r\n\r\n def SetModuleActivated(self):\r\n self.abilityIcon.SetAlpha(1.0)\r\n\r\n def SetModuleDeactivated(self):\r\n self.abilityIcon.SetAlpha(0.5)\r\n\r\n def OnAbilityClick(self, *args):\r\n self.controller.OnAbilityClick(self.targetMode)\r\n\r\n def Close(self):\r\n self.shipFighterState.signalOnAbilityActivated.disconnect(self.OnAbilityActivated)\r\n self.shipFighterState.signalOnAbilityDeactivated.disconnect(self.OnAbilityDeactivated)\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/eve/client/script/ui/inflight/squadrons/abilityIcon.py","file_name":"abilityIcon.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"12216851403","text":"from typing import List\n# https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n\nclass Solution:\n def findMin(self, nums: List[int]) -> int:\n \"\"\"\n Binary Search\n \"\"\"\n n = len(nums)\n if n == 1 or nums[-1] > nums[0]:\n return nums[0]\n idx = n // 2\n while True:\n n = n // 2 + 1\n if nums[idx - 1] > nums[idx]:\n return nums[idx]\n elif nums[idx] < nums[0]:\n idx -= n // 2\n n = n // 2 + 1\n else:\n idx += n // 2\n","repo_name":"elibroftw/contest-questions","sub_path":"LeetCode/153. Find Minimum in Rotated Sorted Array.py","file_name":"153. Find Minimum in Rotated Sorted Array.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"} +{"seq_id":"17433412381","text":"print(\"Input 10 number: \")\r\nx = 10\r\nwhile(x != 0):\r\n list = []\r\n for i in range(10):\r\n num = int(input())\r\n if num % 42 not in list:\r\n list.append(num % 42)\r\n print(len(list))\r\n x = x - 1\r\n break\r\n","repo_name":"rachelhera/4-reserved","sub_path":"modul42.py","file_name":"modul42.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"5040520594","text":"## Ethan Coyle\n# November 10,2021 \n# This is in classs work for our in class work\n\n\n\nclass Node:\n\n #intilize the node data and then pointing to\n # none which is null\n def __init__(self, data):\n self.data = data # node data\n self.next = None # null value\n\n# create the class link list\nclass LinkedList:\n\n # intitilize the head of the link list\n # pointing to null(None)\n def __init__(self):\n self.head = None# null value\n\n # inserting pushing to the node\n # head to the node\n def AddNode(self, new_data):\n new_node = Node(new_data)# insertin new data\n new_node.next = self.head #\n self.head = new_node\n\n # Add contents of two linked lists and return the head\n # node of list \n def addTwoLists(self, first, second):\n # both pointing to null value until is updated\n prev = None\n temp = None\n carry = 0\n\n # if first or second is not pointing to null\n while(first is not None or second is not None):\n FirstData = 0 if first is None else first.data\n SecData = 0 if second is None else second.data\n Sum = carry + FirstData + SecData\n\n # update for calculating next\n carry = 1 if Sum >= 10 else 0\n\n # update the sum if is greater\n Sum = Sum if Sum < 10 else Sum % 10\n\n # Create a new node with sum as data\n temp = Node(Sum)\n\n # if this is the first node then set it as head\n # of the output list\n if self.head is None:\n self.head = temp\n else:\n prev.next = temp\n\n # set previus so can insert node\n prev = temp\n\n # Move first and second pointers to next nodes\n if first is not None:\n first = first.next\n if second is not None:\n second = second.next\n\n if carry > 0:\n temp.next = Node(carry)\n\n # printing out the link list inplemented as a method\n def printList(self):\n temp = self.head\n while(temp is not None):\n print(temp.data)\n temp = temp.next\n\n\n\n# Driver code\n# create the two lists and then AddNode add the values each \nfirst = LinkedList()\nsecond = LinkedList()\n\n# Create first list\nfirst.AddNode(3)\nfirst.AddNode(2)\nfirst.AddNode(1)\n# after adding, we print out the contents of our list\nprint(\"\\r\\nThe contents of our first list is :\\n\",first.printList())\n\n# Now creating our second list AddNode\nsecond.AddNode(6)\nsecond.AddNode(5)\nsecond.AddNode(4)\n# output the contents of our list after adding all the nodes\nprint( \"\\r\\n The contents of our second list is :\\n, \",second.printList())\n\n# AddedLink list contatins contents of the first two into addelink list which has the value of the \n# two list aded together and stores\nAddedLinkList = LinkedList()\nAddedLinkList.addTwoLists(first.head, second.head)\nprint(\"\\r\\n The REsult of Adding the two lists together is :\\n\",AddedLinkList.printList())\n","repo_name":"ethancoyle7/CMPS-4143-Java-And-Python-","sub_path":"PythonPrograms/linklist.py","file_name":"linklist.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"71045544486","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nimport re\nfrom Zhaoping.items import ZhaopingItem\n\n\nclass ZhaopinSpider(scrapy.Spider):\n name = 'job_spider'\n baseUrl='https://fe-api.zhaopin.com/c/i/sou?start={0}&pageSize=90&cityId=489&kw={1}&kt=3'\n\n offset = 0 # 偏移量\n def start_requests(self):\n '''\n 初始换爬取地址,取关键词组成爬取初始地址\n :return: url\n '''\n with open('keywords.json', 'r') as f:\n keywords_list = json.load(f)\n\n start_urls=[]\n for item in keywords_list:\n for job_key in item['Job_keywords']:\n start_urls.append(self.baseUrl.format(str(self.offset),job_key))\n\n if start_urls is not None:\n for url in start_urls:\n print(\"start_url:\",url)\n yield scrapy.Request(url=url,callback=self.parse,meta={'start_url':url})\n\n def parse(self, response):\n data_list=json.loads(response.body)['data']['results']\n if len(data_list)==0: return\n for data in data_list:\n item=ZhaopingItem()\n item['jobType']=data['jobType']['items'][0][\"name\"] #职位所属种类\n item['jobName']=data['jobName'] #职位名称\n item['eduLevel']=data['eduLevel']['name'] #学历要求\n item['companyName']=data['company']['name'] #公司名称\n item['salary']=data['salary'] #薪资\n item['city']=data['city']['display'] #工作城市\n item['workingExp']=data['workingExp']['name'] #工作经验\n item['extractSkillTag']=data['positionLabel'] # 职位技能关键字\n item['releaseTime']=data['updateDate'] # 职位发布时间\n yield item\n init_url=response.meta['start_url']\n self.offset += 90\n str_offset = str(self.offset)\n pattern = 'start=(.*?)&'\n replace_str = 'start=' + str_offset + '&'\n url = re.sub(pattern=pattern, repl=replace_str, string=init_url)\n yield scrapy.Request(url=url,callback=self.parse)\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Chauncey2/zhaopin_spider","sub_path":"Zhaoping/spiders/job_spider.py","file_name":"job_spider.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"} +{"seq_id":"37337405817","text":"with open(\"2022/2022-12-06-input.txt\", \"r\") as file:\n stream = file.read().strip()\n\n\ndef find_index(n):\n \"\"\"Find start of marker, with n unique values in string\"\"\"\n for s in range(len(stream) - 1):\n s1 = stream[s : s + n]\n if len(s1) == n & len(s1) == len(set(s1)):\n return s + n\n\n\nprint(find_index(4))\nprint(find_index(14))\n","repo_name":"renehlavova/advent-of-code","sub_path":"2022/2022-12-06.py","file_name":"2022-12-06.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6225551587","text":"# Created on November 22, 2019\n# Andrew Simonds - 20056566 - 16avs6\n\nimport sys\n\n\n# Used method three from Lab 9 to change\ndef f2mod(s):\n result = 0\n for char in s:\n result = (7 * result + ord(char)) % 100000\n return result\n\n\n# Returns length of LCS for X[0..m-1], Y[0..n-1]\ndef longestCommonSubsequence(X, Y, m, n):\n tableL = [[0 for x in range(n + 1)] for x in range(m + 1)]\n\n for i in range(m + 1):\n for j in range(n + 1):\n if i == 0 or j == 0:\n tableL[i][j] = 0\n # First check if not equal with function\n elif f2mod(X[i - 1]) != f2mod(Y[j - 1]):\n tableL[i][j] = max(tableL[i - 1][j], tableL[i][j - 1])\n # If they are equal from the function, check the actual strings\n else:\n if X[i - 1] == Y[j - 1]:\n tableL[i][j] = tableL[i - 1][j - 1] + 1\n else:\n tableL[i][j] = max(tableL[i - 1][j], tableL[i][j - 1])\n\n index = tableL[m][n] # Bottom right corner of table\n\n lcs = [\"\"] * (index + 1)\n lcs[index] = \"\"\n\n # Start iteration at bottom right corner\n i = m\n j = n\n\n while i > 0 and j > 0:\n # If current string in X and Y are the same then it must be apart of the longest common subsequence\n if X[i - 1] == Y[j - 1]:\n lcs[index - 1] = X[i - 1]\n # Decrement row, column, and index\n i -= 1\n j -= 1\n index -= 1\n # Find next largest value, being either above or beside, and move to that one\n elif tableL[i - 1][j] > tableL[i][j - 1]:\n i -= 1\n else:\n j -= 1\n\n print(\"LCS of is \\n\")\n lineCount = 0\n for x in range(len(lcs)):\n print(lcs[x])\n lineCount = lineCount + 1\n print(lineCount)\n print(\"'lcs' contains all lines that are equal in X and Y\")\n print(lcs[64])\n return lcs\n\n\n# file1 = \"Three_Bears.v1.txt\"\n# file2 = \"Three_Bears.v2.txt\"\n\nfile1 = \"Dijkstra.py\"\nfile2 = \"Dijkstra_py3.py\"\n\nwith open(file1) as f:\n lineList1 = f.read().splitlines()\n\nwith open(file2) as f:\n lineList2 = f.read().splitlines()\n\nlengthList1 = len(lineList1)\nlengthList2 = len(lineList2)\n\ncommonLineList = longestCommonSubsequence(lineList1, lineList2, lengthList1, lengthList2)\n\n# Keep track of where we are in the files\nlineCount1 = 0\nlineCount2 = 0\ncommonCount = 0\n\n# Store line numbers where the common line is in each file\nfileLine1 = []\nfileLine2 = []\n\nwhile lineCount1 < lengthList1 and lineCount2 < lengthList2:\n if lineList1[lineCount1] == commonLineList[commonCount]:\n fileLine1.append(lineCount1 + 1)\n while True:\n if lineList2[lineCount2] == commonLineList[commonCount]:\n fileLine2.append(lineCount2 + 1)\n commonCount = commonCount + 1\n lineCount2 = lineCount2 + 1\n break\n lineCount2 = lineCount2 + 1\n\n lineCount1 = lineCount1 + 1\n\nprint(\"Outputting arrays\")\n\nfor x in range(len(fileLine1)):\n print(fileLine1[x])\n\nfor x in range(len(fileLine2)):\n print(fileLine2[x])\n\n# Print final output\ncount1 = 0\ncount2 = 0\n\nprint(len(fileLine1))\nprint(len(fileLine2))\n\nwhile count1 + 1 < len(fileLine1) and count2 + 1 < len(fileLine2):\n # Print sequence of matches\n print(\"Match: \", end=\" \")\n print(file1, end=\" \")\n\n temp1 = fileLine1[count1]\n tempCount = 0\n while ((fileLine1[count1 + 1] - fileLine1[count1]) == 1) and ((count1 + 2) < len(fileLine1)):\n count1 = count1 + 1\n tempCount = tempCount + 1\n\n if (count1 + 2) >= len(fileLine1):\n count1 = count1 + 1\n\n print(\"<{} .. {}>\".format(temp1, fileLine1[count1]), end=\" \")\n print(\" ---> \", end=\" \")\n print(file2, end=\" \")\n\n temp2 = fileLine2[count2]\n tempCount = 0\n while (fileLine2[count2 + 1] - fileLine2[count2]) == 1 and (count2 + 2) < len(fileLine2) and tempCount < (\n fileLine1[count1] - temp1):\n count2 = count2 + 1\n tempCount = tempCount + 1\n\n if (count2 + 2) >= len(fileLine1):\n count2 = count2 + 1\n\n print(\"<{} .. {}>\".format(temp2, fileLine2[count2]))\n\n if not ((count1 + 1) < len(fileLine1) and (count2 + 1) < len(fileLine2)):\n break\n\n # Print sequence of mismatches\n print(\"Mismatch: \", end=\" \")\n print(file1, end=\" \")\n if (fileLine1[count1 + 1] - fileLine1[count1]) == 1:\n print(\"None\", end=\" \")\n else:\n print(\"<{} .. {}>\".format(fileLine1[count1] + 1, fileLine1[count1 + 1] - 1), end=\" \")\n print(\" ---> \", end=\" \")\n print(file2, end=\" \")\n if (fileLine2[count2 + 1] - fileLine2[count2]) == 1:\n print(\"None\")\n else:\n print(\"<{} .. {}>\".format(fileLine2[count2] + 1, fileLine2[count2 + 1] - 1))\n\n count1 = count1 + 1\n count2 = count2 + 1\n","repo_name":"andrewsimonds14/UniversityProgramming","sub_path":"Algorithms-CMPE365/DifferenceInFiles/FindDifference.py","file_name":"FindDifference.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3129146483","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport misc_functions as mf\n\nDF = pd.read_excel(\"Fidelity.xlsx\")\nDFA = DF.iloc[:14,:]\nmA,bA,rsqA = mf.lin_reg(DFA[\"n\"],DFA[\"Portfolio value\"])\ntxtA = \"y = {:4.2f}x + {:4.2f}, rsq = {:4.4f}\".format(mA,bA,rsqA)\n\nyA = []\nfor i in DFA[\"n\"]:\n yA.append(mA*i + bA)\n\nDFB = DF.iloc[20:33,:]\nDFB.reset_index(inplace=True)\nmB,bB,rsqB = mf.lin_reg(DFB[\"n\"],DFB[\"Portfolio value\"])\nbB += DFB[\"n\"][0]\ntxtB = \"y = {:4.2f}x + {:4.2f}, rsq = {:4.4f}\".format(mB,bB,rsqB)\n\nyB = []\nfor i in DFB[\"n\"]:\n yB.append(mB*i + bB)\n\nDFC = DF.iloc[35:51,:]\nDFC.reset_index(inplace=True)\nmC,bC,rsqC = mf.lin_reg(DFC[\"n\"],DFC[\"Portfolio value\"])\nbC += DFC[\"n\"][0]\ntxtC = \"y = {:4.2f}x + {:4.2f}, rsq = {:4.4f}\".format(mC,bC,rsqC)\n\nyC = []\nfor i in DFC[\"n\"]:\n yC.append(mC*i+bC)\n\nm = (mA+mB+mC)/3 # find the average slope of the three models\nm_sd = np.array([mA,mB,mC]).std()\nprint(\"~N({:4.2f},{:4.4f})\".format(m,m_sd))\n\n## ------ Plotting section -------- ##\nfig,ax = plt.subplots(1,1,figsize=(10,6))\nax.scatter(DFA[\"n\"],DFA[\"Portfolio value\"],color='b')\nax.plot(DFA[\"n\"],yA,color='k')\nax.text(DFA[\"n\"][0]+3,DFA[\"Portfolio value\"][0],txtA)\n\nax.scatter(DFB[\"n\"],DFB[\"Portfolio value\"],color='b')\nax.plot(DFB[\"n\"],yB,color='k')\nax.text(DFB[\"n\"][0]-10,DFB[\"Portfolio value\"][0]-4500,txtB)\n\nax.scatter(DFC[\"n\"],DFC[\"Portfolio value\"],color='b')\nax.plot(DFC[\"n\"],yC,color='k')\nax.text(DFC[\"n\"][0]-3,DFC[\"Portfolio value\"][0]-4500,txtC)\n\nplt.show()\n","repo_name":"gmclapp/Personal_library","sub_path":"Financial plots.py","file_name":"Financial plots.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"945700288","text":"import numpy as np\nimport cv2\nimport os\nfrom matplotlib import pyplot as plt\n\npath = r'./images/sample/'\nsave_path = r'./images/sample_label/'\nfor i in os.listdir(path):\n # 이미지 로드 및 그레이 이미지로 변경\n \n image = cv2.imread(path+i)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n \n # 이미지 노이즈 제거\n kernel1 = np.ones((5,5),np.float32)/25\n dst1 = cv2.filter2D(gray,-1,kernel1)\n\n # plt.imshow( dst1)\n # threshold 이미지 필터 생성\n ret2, th2 = cv2.threshold(dst1, 45, 255, cv2.THRESH_TRUNC+cv2.THRESH_OTSU) # cv2.THRESH_BINARY+cv2.THRESH_OTSU\n\n # plt.imshow( th2)\n # 불규칙한 모양과 노이즈 제거\n kernel3 = np.ones((5,5), np.uint8) \n img_erosion = cv2.erode(th2, kernel3, iterations=5)\n\n # 관심 영역에 대한 확장\n img_dilation = cv2.dilate(img_erosion, kernel3, iterations=5)\n\n contours, hierarchy = cv2.findContours(img_dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n if len(contours) != 0:\n c = max(contours, key = cv2.contourArea)\n x,y,w,h = cv2.boundingRect(c)\n new_img = gray[y:y+h,x:x+w]\n # plt.imshow( new_img)\n\n median_filter = cv2.medianBlur(new_img, 5)\n\n kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(9,9))\n erosion = cv2.morphologyEx(median_filter, cv2.MORPH_ERODE, kernel)\n dilation = cv2.morphologyEx(erosion, cv2.MORPH_DILATE, kernel)\n\n ret3,th3 = cv2.threshold(dilation,110,255,cv2.THRESH_BINARY)\n th3 = cv2.bitwise_not(th3)\n\n # 뇌종양일 경우 이미지위에 튜머 표시\n contours,hierarchy = cv2.findContours(th3, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n if len(contours) != 0:\n c = max(contours, key = cv2.contourArea)\n x,y,w,h = cv2.boundingRect(c)\n tumor = image[y:y+h,x:x+w]\n \n new_img = cv2.rectangle(image, (x, y), (x + w, y + h), (255,255,255), 1)\n \n cv2.imwrite(save_path+i,th3 )\n ","repo_name":"alsrb0607/medical-image-diagnosis","sub_path":"server_flask/skin-api/skin_segmentation.py","file_name":"skin_segmentation.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18479860038","text":"import numpy as np\nfrom typing import List\n\nimport numpy as np\nimport pydantic\nimport xarray as xr\nfrom rastermap.mapping import Rastermap\n\nfrom config import *\nfrom pydantic_models import FlatFlyAcquisitions\n\n\n#%%\n\n\ndef load(xrds_file):\n ds = xr.load_dataset(stat_file.with_name('xrds_suite2p_outputs_xid0.nc'))\n ds = ds.sortby('cells')\n good_xid = ds.attrs['good_xid']\n ds = ds.where(ds.xid.isin(good_xid), drop=True)\n return ds\n\n\ndef transform(ds):\n ##########################\n # Run rastermap clustering\n ##########################\n ops = {'n_components': 1,\n 'n_X': 40,\n 'alpha': 1.,\n 'K': 1.,\n 'nPC': 200, 'constraints': 2,\n 'annealing': True, 'init': 'pca'}\n\n model = Rastermap(**ops)\n embedding = model.fit_transform(ds.Fc_normed.to_numpy())\n return model, ops, embedding\n\n\ndef save_embedding(filepath, ops, model, data_description, cells):\n np.save(filepath,\n dict(ops=ops,\n model=model,\n data_description=data_description,\n cells=cells))\n return filepath\n\n\ndef save_embedding_as_dict(filepath, ops, model, data_description, cells):\n np.save(filepath,\n dict(ops=ops,\n model=model.__dict__,\n data_description=data_description,\n cells=cells))\n return filepath\n\n\nif __name__ == '__main__':\n\n movie_types = ['kiwi', 'control1', 'control1_top2_ramps', 'kiwi_ea_eb_only']\n\n manifest_json = Path(\"/local/storage/Remy/natural_mixtures/manifestos/flat_linked_thor_acquisitions.json\")\n flat_acqs = pydantic.parse_file_as(List[FlatFlyAcquisitions], manifest_json)\n\n for flacq in filter(lambda x: x.movie_type in movie_types, flat_acqs):\n print('---')\n print(f\"\\n{flacq}\")\n\n stat_file = NAS_PROC_DIR.joinpath(flacq.s2p_stat_file)\n\n ###################################\n # load data, make sure it's sorted\n ###################################\n xrds_suite2p_outputs = xr.load_dataset(stat_file.with_name('xrds_suite2p_outputs_xid0.nc'))\n xrds_suite2p_outputs = xrds_suite2p_outputs.sortby('cells')\n\n ###########################################\n # drop all cells not in a good_xid cluster\n ###########################################\n good_xid = xrds_suite2p_outputs.attrs['good_xid']\n ds = xrds_suite2p_outputs.where(xrds_suite2p_outputs.xid.isin(good_xid), drop=True)\n\n ##########################\n # Run rastermap clustering\n ##########################\n ops = {'n_components': 1,\n 'n_X': 40,\n 'alpha': 1.,\n 'K': 1.,\n 'nPC': 200, 'constraints': 2,\n 'annealing': True, 'init': 'pca'}\n\n model = Rastermap(**ops)\n embedding = model.fit_transform(ds.Fc_normed.to_numpy())\n\n ###############\n # save results\n ###############\n save_embedding(stat_file.with_name('embedding_goodxids.npy'), ops=ops, model=model,\n data_description='Fc_normed', cells=ds.cells.to_numpy())\n\n save_embedding_as_dict(stat_file.with_name('embedding_goodxids.npy'), ops=ops, model=model,\n data_description='Fc_normed', cells=ds.cells.to_numpy())\n\n ds = ds.assign_coords(dict(xid1=('cells', model.xid)))\n ds = ds.assign_coords(dict(embedding1=('cells', model.embedding.squeeze())))\n ds.to_netcdf(stat_file.with_name('xrds_suite2p_outputs_xid1.nc'))\n\n\n","repo_name":"jyang-2/CalciumVolumetric","sub_path":"src/s2p/rastermap_round_two.py","file_name":"rastermap_round_two.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1536281724","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport glob\nfrom os.path import isfile, join\n\n\ndef get_pixel(img, center, x, y):\n new_value = 0\n try:\n if img[x][y] >= center:\n new_value = 1\n except:\n pass\n return new_value\n\n\ndef lbp_calculated_pixel(img, x, y):\n '''\n 64 | 128 | 1\n ----------------\n 32 | 0 | 2\n ----------------\n 16 | 8 | 4 \n '''\n center = img[x][y]\n val_ar = []\n val_ar.append(get_pixel(img, center, x-1, y+1)) # top_right\n val_ar.append(get_pixel(img, center, x, y+1)) # right\n val_ar.append(get_pixel(img, center, x+1, y+1)) # bottom_right\n val_ar.append(get_pixel(img, center, x+1, y)) # bottom\n val_ar.append(get_pixel(img, center, x+1, y-1)) # bottom_left\n val_ar.append(get_pixel(img, center, x, y-1)) # left\n val_ar.append(get_pixel(img, center, x-1, y-1)) # top_left\n val_ar.append(get_pixel(img, center, x-1, y)) # top\n\n power_val = [1, 2, 4, 8, 16, 32, 64, 128]\n val = 0\n for i in range(len(val_ar)):\n val += val_ar[i] * power_val[i]\n return val\n\n\ndef read_folder(path):\n filenames = glob.glob(path)\n filenames.sort()\n images = [cv2.imread(file) for file in filenames]\n return images\n\n\ndef Melanoma(img_lbp, i):\n cv2.imwrite(\n \"/home/alex/Área de Trabalho/teste_lbp/ISIC/Melanoma/ImgLBP_{:>03}.png\".format(i), img_lbp)\n print(\"ISIC - LBP MELANOMA\", i+1)\n\n\ndef NoMelanoma(img_lbp, i):\n cv2.imwrite(\n \"/home/alex/Área de Trabalho/teste_lbp/ISIC/NãoMelanoma/ImgLBP_{:>03}.png\".format(i), img_lbp)\n print(\"ISIC - LBP NAO MELANOMA\", i+1)\n\n\ndef main():\n img_bgr = read_folder(\n \"/home/alex/Documentos/TCC2/ISIC/NaoMelanomaSegmentada/*.png\")\n for cont in range(len(img_bgr)):\n height, width, channel = img_bgr[cont].shape\n img_gray = cv2.cvtColor(img_bgr[cont], cv2.COLOR_BGR2GRAY)\n\n img_lbp = np.zeros((height, width, 3), np.uint8)\n for i in range(0, height):\n for j in range(0, width):\n img_lbp[i, j] = lbp_calculated_pixel(img_gray, i, j)\n\n Melanoma(img_lbp, cont)\n NoMelanoma(img_lbp, cont)\n\n\nmain()\n","repo_name":"alexwilliam1/digital_image_processing","sub_path":"LBP - Local Binary Patterns/LBP.py","file_name":"LBP.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25100880864","text":"# EJERCICIO II - PARCIAL 1\r\n\r\nH = int(input(\"Ingrese la profundidad del pozo (en metros): \"))\r\nLd = int(input(\"Ingrese lo que asciende el caracol durante el día (en metros): \"))\r\nLn = int(input(\"Ingrese lo que desciende el caracol durante la noche (en metros): \"))\r\n\r\nposicion = Ld - Ln\r\nL = 0\r\ndias = 0\r\n\r\nif posicion <= 0:\r\n print(\"El caracol nunca saldrá del pozo :(\")\r\n \r\nwhile Ld > 0:\r\n \r\n if posicion > 0:\r\n L += posicion\r\n dias += 1 # --> 24 horas\r\n \r\n if L + Ld >= H:\r\n break\r\n \r\nprint(\"El caracol tardó\",dias,\"días en salir del pozo\") \r\n\r\n","repo_name":"gelsysonnessa/Tareas","sub_path":"PEP - Ejercicio II - Gelsy Sonnessa.py","file_name":"PEP - Ejercicio II - Gelsy Sonnessa.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11320960436","text":"#Intersection of 2 Arrays\n\n\"\"\"Given 2 integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.\"\"\"\n\nclass Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n nums11 = list(set(nums1))\n nums21 = list(set(nums2))\n ans = []\n if len(nums11) == len(nums21):\n for i in nums11:\n if i in nums21:\n ans.append(i)\n elif len(nums11) > len(nums21):\n for i in nums11:\n if i in nums21:\n ans.append(i)\n else:\n for i in nums21:\n if i in nums11:\n ans.append(i)\n return ans\n","repo_name":"shrutityagi4102/myleetcodesolutions","sub_path":"50.py","file_name":"50.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11460227035","text":"import os\nimport subprocess\nimport shutil\nimport pkg_resources;\n\nhook_templates = {\n \"pre-push\": \"./pre-push.txt\"\n}\n\ndef create_hook(hook_type):\n dest_dirpath = os.path.join(os.getcwd(), \".git/hooks\")\n if not os.path.exists(dest_dirpath):\n print(\"Command should be run in the root directory of the git repository\")\n return\n\n source_file = pkg_resources.resource_filename(__name__, hook_templates[hook_type])\n destination_file = os.path.join(dest_dirpath, hook_type)\n \n try:\n with open(source_file, 'r') as source:\n try:\n with open(destination_file, 'w') as destination:\n shutil.copyfileobj(source, destination)\n command = f\"chmod +x {destination_file}\"\n subprocess.run(command, shell=True, check=True)\n\n print(\"Successfully made hook file an executable\")\n print(f\"Hook file '{destination_file}' successfully populated.\")\n except FileNotFoundError:\n print(\"Error: destination file not found.\")\n except Exception as e:\n print(f\"An error occurred: {e}\")\n\n except FileNotFoundError:\n print(\"Error: Source file not found.\")\n except Exception as e:\n print(f\"An error occurred: {e}\")\n\ndef create_all_hooks():\n for hook_type in hook_templates:\n create_hook(hook_type)\n\ncreate_all_hooks()\n","repo_name":"NikaEco/env-minion","sub_path":"pip-package/src/env_minion/hook_factory.py","file_name":"hook_factory.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37571944140","text":"\"\"\"Const for Sonos.\"\"\"\nfrom homeassistant.components.media_player.const import (\n MEDIA_CLASS_ALBUM,\n MEDIA_CLASS_ARTIST,\n MEDIA_CLASS_COMPOSER,\n MEDIA_CLASS_CONTRIBUTING_ARTIST,\n MEDIA_CLASS_GENRE,\n MEDIA_CLASS_PLAYLIST,\n MEDIA_CLASS_TRACK,\n MEDIA_TYPE_ALBUM,\n MEDIA_TYPE_ARTIST,\n MEDIA_TYPE_COMPOSER,\n MEDIA_TYPE_CONTRIBUTING_ARTIST,\n MEDIA_TYPE_GENRE,\n MEDIA_TYPE_PLAYLIST,\n MEDIA_TYPE_TRACK,\n)\n\nDOMAIN = \"sonos\"\nDATA_SONOS = \"sonos_media_player\"\n\nSONOS_ARTIST = \"artists\"\nSONOS_ALBUM = \"albums\"\nSONOS_PLAYLISTS = \"playlists\"\nSONOS_GENRE = \"genres\"\nSONOS_ALBUM_ARTIST = \"album_artists\"\nSONOS_TRACKS = \"tracks\"\nSONOS_COMPOSER = \"composers\"\n\nEXPANDABLE_MEDIA_TYPES = [\n MEDIA_TYPE_ALBUM,\n MEDIA_TYPE_ARTIST,\n MEDIA_TYPE_COMPOSER,\n MEDIA_TYPE_GENRE,\n MEDIA_TYPE_PLAYLIST,\n SONOS_ALBUM,\n SONOS_ALBUM_ARTIST,\n SONOS_ARTIST,\n SONOS_GENRE,\n SONOS_COMPOSER,\n SONOS_PLAYLISTS,\n]\n\nSONOS_TO_MEDIA_CLASSES = {\n SONOS_ALBUM: MEDIA_CLASS_ALBUM,\n SONOS_ALBUM_ARTIST: MEDIA_CLASS_ARTIST,\n SONOS_ARTIST: MEDIA_CLASS_CONTRIBUTING_ARTIST,\n SONOS_COMPOSER: MEDIA_CLASS_COMPOSER,\n SONOS_GENRE: MEDIA_CLASS_GENRE,\n SONOS_PLAYLISTS: MEDIA_CLASS_PLAYLIST,\n SONOS_TRACKS: MEDIA_CLASS_TRACK,\n \"object.container.album.musicAlbum\": MEDIA_CLASS_ALBUM,\n \"object.container.genre.musicGenre\": MEDIA_CLASS_PLAYLIST,\n \"object.container.person.composer\": MEDIA_CLASS_PLAYLIST,\n \"object.container.person.musicArtist\": MEDIA_CLASS_ARTIST,\n \"object.container.playlistContainer.sameArtist\": MEDIA_CLASS_ARTIST,\n \"object.container.playlistContainer\": MEDIA_CLASS_PLAYLIST,\n \"object.item.audioItem.musicTrack\": MEDIA_CLASS_TRACK,\n}\n\nSONOS_TO_MEDIA_TYPES = {\n SONOS_ALBUM: MEDIA_TYPE_ALBUM,\n SONOS_ALBUM_ARTIST: MEDIA_TYPE_ARTIST,\n SONOS_ARTIST: MEDIA_TYPE_CONTRIBUTING_ARTIST,\n SONOS_COMPOSER: MEDIA_TYPE_COMPOSER,\n SONOS_GENRE: MEDIA_TYPE_GENRE,\n SONOS_PLAYLISTS: MEDIA_TYPE_PLAYLIST,\n SONOS_TRACKS: MEDIA_TYPE_TRACK,\n \"object.container.album.musicAlbum\": MEDIA_TYPE_ALBUM,\n \"object.container.genre.musicGenre\": MEDIA_TYPE_PLAYLIST,\n \"object.container.person.composer\": MEDIA_TYPE_PLAYLIST,\n \"object.container.person.musicArtist\": MEDIA_TYPE_ARTIST,\n \"object.container.playlistContainer.sameArtist\": MEDIA_TYPE_ARTIST,\n \"object.container.playlistContainer\": MEDIA_TYPE_PLAYLIST,\n \"object.item.audioItem.musicTrack\": MEDIA_TYPE_TRACK,\n}\n\nMEDIA_TYPES_TO_SONOS = {\n MEDIA_TYPE_ALBUM: SONOS_ALBUM,\n MEDIA_TYPE_ARTIST: SONOS_ALBUM_ARTIST,\n MEDIA_TYPE_CONTRIBUTING_ARTIST: SONOS_ARTIST,\n MEDIA_TYPE_COMPOSER: SONOS_COMPOSER,\n MEDIA_TYPE_GENRE: SONOS_GENRE,\n MEDIA_TYPE_PLAYLIST: SONOS_PLAYLISTS,\n MEDIA_TYPE_TRACK: SONOS_TRACKS,\n}\n\nSONOS_TYPES_MAPPING = {\n \"A:ALBUM\": SONOS_ALBUM,\n \"A:ALBUMARTIST\": SONOS_ALBUM_ARTIST,\n \"A:ARTIST\": SONOS_ARTIST,\n \"A:COMPOSER\": SONOS_COMPOSER,\n \"A:GENRE\": SONOS_GENRE,\n \"A:PLAYLISTS\": SONOS_PLAYLISTS,\n \"A:TRACKS\": SONOS_TRACKS,\n \"object.container.album.musicAlbum\": SONOS_ALBUM,\n \"object.container.genre.musicGenre\": SONOS_GENRE,\n \"object.container.person.composer\": SONOS_COMPOSER,\n \"object.container.person.musicArtist\": SONOS_ALBUM_ARTIST,\n \"object.container.playlistContainer.sameArtist\": SONOS_ARTIST,\n \"object.container.playlistContainer\": SONOS_PLAYLISTS,\n \"object.item.audioItem.musicTrack\": SONOS_TRACKS,\n}\n\nLIBRARY_TITLES_MAPPING = {\n \"A:ALBUM\": \"Albums\",\n \"A:ALBUMARTIST\": \"Artists\",\n \"A:ARTIST\": \"Contributing Artists\",\n \"A:COMPOSER\": \"Composers\",\n \"A:GENRE\": \"Genres\",\n \"A:PLAYLISTS\": \"Playlists\",\n \"A:TRACKS\": \"Tracks\",\n}\n\nPLAYABLE_MEDIA_TYPES = [\n MEDIA_TYPE_ALBUM,\n MEDIA_TYPE_ARTIST,\n MEDIA_TYPE_COMPOSER,\n MEDIA_TYPE_CONTRIBUTING_ARTIST,\n MEDIA_TYPE_GENRE,\n MEDIA_TYPE_PLAYLIST,\n MEDIA_TYPE_TRACK,\n]\n","repo_name":"fpetillo/home-assistant","sub_path":"homeassistant/components/sonos/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6010835964","text":"import smtplib\nimport ssl\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom dominate import document\nfrom dominate.tags import *\nfrom string import Template\nimport numpy as np\n\n# server URL, in case of Debugging use '127.0.0.1:5000'\nURL = '161.35.20.108'\n\n\"\"\"\ngenerate HTML file that represent the algorithm results.\nand save the HTML with unique identifier in the generated_html folder.\n:param agents represent the agents names list (str list)\n:param items represent the items names list (str list)\n:param data represent the Algorithm results as numpy.np\n:param file_name represent the output file name (unique identifier)\n\"\"\"\n\n\ndef generate_table(agents, items, data, file_name, data_json):\n with document(title='Algorithm Results') as doc:\n head_page = head()\n head_page += link(rel='shortcut icon', href=\"../images/web-logo.png\")\n head_page += link(rel=\"stylesheet\", type=\"text/css\", href=\"../css/Home.css\")\n head_page += link(href=\"https://fonts.googleapis.com/css2?family=Special+Elite&display=swap\", rel=\"stylesheet\")\n head_page += link(href=\"https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap\",\n rel=\"stylesheet\")\n link(rel=\"stylesheet\", href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\",\n integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\",\n crossorigin=\"anonymous\")\n link(rel=\"stylesheet\", type=\"text/css\", href=\"../css/styles.css\")\n content_div = div(cls='topnav')\n content_div += a('Home', cls='active', href='../Home.html')\n content_div += a('About Us', cls='active', href='../About_Us.html')\n content_div += a('Contact us', cls='active', href='../Contact_Us.html')\n\n h1('Results', cls='header')\n\n result_table = table(cls='content-table')\n link(rel='stylesheet', href='../css/table.css')\n header_thread = thead()\n header_tr = tr()\n header_tr += th('Items')\n for agent in agents:\n header_tr += th(agent)\n header_thread += header_tr\n\n item_index = 0\n\n thread_body = tbody()\n for item in items:\n item_tr = tr()\n item_tr += th(item)\n for score in [z[item_index] for z in data[0:]]:\n item_tr += td('{} %'.format(score))\n item_index += 1\n thread_body += item_tr\n\n result_table += header_thread\n result_table += thread_body\n\n if data_json['problem'] == 'EnvyFree':\n explanations = build_envy_free_output(data, data_json)\n elif data_json['problem'] == 'Proportional':\n explanations = build_proportional_output(data, data_json)\n\n h1('Results Explanation', cls='header')\n\n result_explanation_table = table(cls='content-table')\n thread_body = tbody()\n for index, explanation in enumerate(explanations):\n item_tr = tr()\n item_tr += th(agents[index])\n item_tr += td(explanation)\n thread_body += item_tr\n result_explanation_table += thread_body\n\n with open('/var/www/html/fairness-algorithm-rest/web/generated_html/{}.html'.format(file_name), 'w') as f:\n f.write(doc.render())\n\n with open('/var/www/html/fairness-algorithm-rest/web/generated_html/{}.html'.format(file_name), 'r') as f:\n file_data = f.read()\n\n # Replace the target string\n file_data = file_data.replace('<br>', '
')\n\n # Write the file out again\n with open('/var/www/html/fairness-algorithm-rest/web/generated_html/{}.html'.format(file_name), 'w') as f:\n f.write(file_data)\n\n print('generated url is {}'.format(file_name))\n return '{}/generated_html/{}.html'.format(URL, file_name)\n\n\n\"\"\"\nsending email with the algorithm results.\n:param email_receiver is a valid email of the receiver of the results\n:param url represent the site url that contain the algorithm results\n\"\"\"\n\n\ndef send_email(email_receiver, url):\n print('send email to: {}'.format(email_receiver))\n sender_email = \"fairnessalgorithm.io@gmail.com\"\n receiver_email = email_receiver\n password = ''\n\n message = MIMEMultipart(\"alternative\")\n message[\"Subject\"] = \"Fairness.io Results\"\n message[\"From\"] = sender_email\n message[\"To\"] = receiver_email\n\n # Create the plain-text and HTML version of your message\n\n with open('/var/www/html/fairness-algorithm-rest/web/html_email_template.html', 'r+') as f:\n template = Template(f.read())\n html = (template.substitute(URL=url))\n\n # Turn these into plain/html MIMEText objects\n part2 = MIMEText(html, \"html\")\n\n # Add HTML/plain-text parts to MIMEMultipart message\n # The email client will try to render the last part first\n message.attach(part2)\n\n # Create secure connection with server and send email\n context = ssl.create_default_context()\n with smtplib.SMTP_SSL(\"smtp.gmail.com\", 465, context=context) as server:\n server.login(sender_email, password)\n server.sendmail(\n sender_email, receiver_email, message.as_string()\n )\n\n\n\"\"\"\nbuild proportional explanation with the algorithm results for each user.\n:param results represent the proportional algorithm results\n:param data represent the JSON data as described in README file\n\"\"\"\n\n\ndef build_proportional_output(results, data):\n points_per_item = np.array(results) * np.array(data['values'])\n agents_results = [sum(e) for e in points_per_item]\n explanation = []\n for index, agent_result in enumerate(agents_results):\n explanation.append(\n 'Hey {}, The total value of the items you received, according to your evaluation, is {} points.{}' \\\n 'This is at least 1/{} of the total value of your rates which is {}.'.format(\n data['agents'][index], agent_result, '
', len(agents_results), 100))\n return explanation\n\n\n\"\"\"\nbuild envy-free explanation with the algorithm results for each user.\n:param results represent the proportional algorithm results\n:param data represent the JSON data as described in README file\n\"\"\"\n\n\ndef build_envy_free_output(results, data):\n explanation = []\n for agent_index, agent in enumerate(data['agents']):\n\n results_per_agent_index = np.array(results) * np.array(data['values'][agent_index])\n agents_results = [sum(e) for e in results_per_agent_index]\n explanation_per_agent = 'Hey {}, The total value of the items you received, according to your evaluation ' \\\n 'is {} points. {} according to your evaluation: '.format(agent,\n agents_results[agent_index],\n '
')\n\n for other_agent_index, other_agent in enumerate(data['agents']):\n if agent_index != other_agent_index:\n explanation_per_agent += '{} got {} points .'.format(other_agent,\n agents_results[other_agent_index])\n explanation_per_agent += '{} but according to your evaluation you got {} points, which is the best result ' \\\n 'according to your evaluation '.format('
', agents_results[agent_index])\n explanation.append(explanation_per_agent)\n return explanation\n","repo_name":"DanielAbergel/Distribution-Algorithm","sub_path":"server/server_utils.py","file_name":"server_utils.py","file_ext":"py","file_size_in_byte":7506,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"39663534721","text":"def removeTabHelper(master, index, name):\n tab = None\n for t in master.tabs:\n if t.name == name:\n tab = t\n\n # Starts to remove person from every field\n for person in master.people:\n if person.getName() == name:\n master.people.remove(person)\n\n for item in master.items:\n for person in item.people:\n if person == name:\n item.people.remove(name)\n break\n\n master.notebook.forget(index)\n\n if len(master.taxEntry.get()) == 0:\n taxPercentageFloat = 1\n else:\n taxPercentageFloat = float(master.taxEntry.get().strip(\"%\")) / 100 + 1\n\n # Updating price\n\n # For main window\n totPrice = 0.0\n for item in master.items:\n totPrice += float(\"{:.2f}\".format(float(item.getPrice())))\n\n totPrice *= taxPercentageFloat\n master.priceLabelVar.set(f\"Price: ${round(totPrice, 2)}\")\n\n # Updating every tab item; This is very ugly, hopefully i would change this soon\n # Finding each person\n for person in master.people:\n # Finding the tab that corresponds to the person\n for t in master.tabs:\n if t.name == person.name:\n # Loop through the tree\n for row in t.tree.get_children():\n # Looping through the person's items to find the price\n for item in person.items:\n if item.name == t.tree.item(row)[\"values\"][0]:\n name = t.tree.item(row)[\"values\"][0]\n quantity = t.tree.item(row)[\"values\"][1]\n\n # Price is based on how many people share the item\n price = float(\"{:.2f}\".format(float(item.getPrice()) / len(item.people)))\n t.tree.item(row, values=(name, quantity, price))\n break\n\n # For every tab\n for tab in master.tabs:\n totPrice = 0.0\n for row in tab.tree.get_children():\n totPrice += float(tab.tree.item(row)[\"values\"][2])\n\n totPrice *= taxPercentageFloat\n tab.priceLabelVar.set(f\"Price: $ {round(totPrice, 2)}\")\n\n # Gray out non-claimed items\n for row in master.itemTree.get_children():\n for item in master.items:\n if item.name == master.itemTree.item(row)[\"values\"][0]:\n if len(item.getPeople()) == 0:\n master.itemTree.item(row, tags=(\"noPeople\",))\n break\n\n master.itemTree.update()\n","repo_name":"brianlin725/BillSplit","sub_path":"utils/RemoveTab.py","file_name":"RemoveTab.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17118133712","text":"import time\n\nfrom twitter.error import TwitterError\n\nfrom parse_messages import parse_message\nfrom commands import process_command_from_message\nfrom database_utils import bind_database_session\n\nfrom utils import (\n get_twitter_api,\n get_logger,\n NewMessageStates\n)\n\nlogger = get_logger()\n\nDATE_FORMAT = '%Y-%m-%d'\nTIME_FORMAT = \"%H-%M-%S\"\n\n\nMESSAGE_REQUEST_COUNT = 50\nSLEEP_TIME = 90\n\n\ntwitter_api = get_twitter_api(config_file='config.yml')\nbind_database_session()\n\nself_id = twitter_api._access_token_key.split(\"-\")[0]\n\n\ndef backup_last_dm(dm_id):\n # type: (int) -> None\n with open(\"last_dm.id\", 'w') as dm:\n dm.write(str(dm_id))\n\n\ndef get_last_dm_id():\n # type: () -> int\n _id = -1\n try:\n with open(\"last_dm.id\", 'r') as dm:\n lines = dm.readlines()\n if lines:\n _id = int(lines[0])\n except FileNotFoundError:\n pass\n\n return _id\n\n\nhighest_id_seen = get_last_dm_id()\nlast_id_parsed = highest_id_seen\n\n\ndef send_message_to_user(_id, text_list):\n # type: (int, list) -> None\n\n logger.debug(f\"ID: {_id}, text_list: {text_list}\")\n if not text_list:\n logger.error(f\"Message not sent\")\n twitter_api.PostDirectMessage(text=\"You should't be seeing this message.\", user_id=_id)\n else:\n text = \"\"\n sent_count = 0\n for txt in text_list:\n if sent_count > 4:\n twitter_api.PostDirectMessage(text=\"Too many message send attempts!\", user_id=_id)\n elif len(text) + len(txt) > 10000:\n twitter_api.PostDirectMessage(text=text, user_id=_id)\n text = txt\n sent_count += 1\n else:\n text += txt\n twitter_api.PostDirectMessage(text=text, user_id=_id)\n\n\ndef first_last_message_id(latest_dms):\n # type: (dict) -> tuple\n num_of_messages = len(latest_dms.get('events'))\n\n if num_of_messages:\n first_message_in_page_id = int(latest_dms.get('events')[0].get('id'))\n last_message_in_page_id = int(latest_dms.get('events')[num_of_messages - 1].get('id'))\n else:\n logger.debug(f\"DM EVENTS EMPTY:\\n{latest_dms}\")\n first_message_in_page_id = last_message_in_page_id = -1\n\n return first_message_in_page_id, last_message_in_page_id\n\n\ndef are_new_messages(latest_dms, count=MESSAGE_REQUEST_COUNT):\n # type: (dict, int) -> NewMessageStates\n\n first_message_in_page_id, last_message_in_page_id = first_last_message_id(latest_dms)\n\n if last_message_in_page_id > highest_id_seen:\n if len(latest_dms.get('events')) < count:\n return NewMessageStates.CHECK_THIS_PAGE_ONLY\n return NewMessageStates.CHECK_NEXT_PAGE\n elif first_message_in_page_id > highest_id_seen:\n return NewMessageStates.CHECK_THIS_PAGE_ONLY\n else:\n return NewMessageStates.NO_NEW_MESSAGES\n\n\ndef get_latest_dms(return_json=True, count=MESSAGE_REQUEST_COUNT, next_cursor=None):\n # type: (bool, int, str) -> dict\n logger.debug(f\"Getting messages, next_cursor={next_cursor}\")\n try:\n latest_dms = twitter_api.GetDirectMessages(return_json=return_json, count=count, cursor=next_cursor)\n except TwitterError as e:\n error_code = e.message[0]['code']\n if error_code == 88:\n logger.error(\"DirectMessage.show rate limit Exceeded\")\n latest_dms = dict(events=[], ratelimited=True)\n else:\n raise e\n\n logger.debug(f\"Got {len(latest_dms.get('events'))} dms.\")\n return latest_dms\n\n\ndef main():\n global last_id_parsed, highest_id_seen\n logger.debug(\"Getting DMs.\")\n dms = []\n latest_dms = get_latest_dms()\n state = are_new_messages(latest_dms)\n\n while state in (NewMessageStates.CHECK_THIS_PAGE_ONLY, NewMessageStates.CHECK_NEXT_PAGE):\n dms.extend(latest_dms.get('events'))\n next_cursor = latest_dms.get('next_cursor')\n\n first_id, last_id = first_last_message_id(latest_dms)\n\n if first_id > last_id_parsed:\n last_id_parsed = first_id\n else:\n logger.debug(f\"First ID({first_id}) < last_id_parsed({last_id_parsed})\")\n\n if state == NewMessageStates.CHECK_NEXT_PAGE and next_cursor:\n latest_dms = get_latest_dms(next_cursor=next_cursor) # try TwitterError.Code = 88 RateLimit\n state = are_new_messages(latest_dms)\n else:\n logger.debug(f\"Logic failed: No new messages will be assessed. state={state}, next_cursor={next_cursor}\")\n state = NewMessageStates.NO_NEW_MESSAGES\n\n logger.info(\"Processing DMs into commands.\")\n for dm in reversed(dms):\n message = parse_message(dm)\n _from = message.get('from')\n if _from != self_id and message.get('id') > highest_id_seen:\n result = process_command_from_message(message)\n send_message_to_user(_from, result)\n\n if last_id_parsed > highest_id_seen:\n highest_id_seen = last_id_parsed\n backup_last_dm(highest_id_seen)\n\n logger.debug(f\"Sleeping for {SLEEP_TIME}s.\")\n time.sleep(SLEEP_TIME)\n\n\nif __name__ == \"__main__\":\n while True:\n main()\n\n'''\nfor i in reversed(dms):\nprint(time.strftime(f\"{DATE_FORMAT}-{TIME_FORMAT}\", time.gmtime(time_sent)))\nlogger.info(f\"Done {count}\\nLastDm: {last_dm_sent_id}\\nLoL: {len(dms)}\\n\")\n\ntime.sleep(60)\n'''\n","repo_name":"Kyu/Bookmarks-Plus","sub_path":"stream_dms.py","file_name":"stream_dms.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"7676155702","text":"'''\n크기가 N(> 0)인 정수들의 배열이 있다. \n이 배열내의 중복된 번호들을 제거하고 남은 번호들만을 저장하는 배열을 만드는 알고리즘을 구체적이고 명확하게 기술하라.\n작성한 알고리즘의 시간복잡도를 θ(Theta)-표기로 나타내라.\n'''\n\n\ndef deleteDuplicateElement(A):\n R = []\n\n for i in A:\n isDuplicated = 0\n\n for j in R:\n if i == j:\n isDuplicated = 1\n break\n\n if isDuplicated == 0:\n R.append(i)\n\n return R\n\n\nif __name__ == '__main__':\n A = [1, 2, 6, 2, 3, 6, 8, 2, 2, 4, 5]\n\n R = deleteDuplicateElement(A)\n print(R)\n","repo_name":"rdd9223/Algorithm","sub_path":"assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9329685161","text":"# Code use with Python 3.7.4 32 bit with line-bot-sdk installed\nfrom datetime import datetime\nfrom datetime import date\nimport pyodbc\nimport numpy as np\nimport pandas as pd\nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\n#cwd = os.getcwd()\n#print(cwd)\n\ndef Write_data_to_database(df_input):\n print('------------- Start WriteDB -------------')\n #df_write=df_input.replace([np.inf,-np.inf,np.nan],-999)\n\n df_write=df_input\n print(' col : ',df_write.columns)\n \n\t## ODBC Driver 17 for SQL Server\n conn1 = pyodbc.connect('Driver={SQL Server};'\n 'Server=SBNDCBIPBST02;'\n 'Database=TSR_ADHOC;'\n 'Trusted_Connection=yes;')\n\n #- Delete all records from the table \n #sql=\"\"\"SELECT * FROM TSR_ADHOC.dbo.S_FCT_AG_SALEOUT\"\"\"\n sql=\"\"\"delete FROM [TSR_ADHOC].[dbo].[TEST_AG_SALEOUT] where YYYYMM = CONVERT(VARCHAR(6), DATEADD(month, -1, GETDATE()), 112)\"\"\"\n \n cursor=conn1.cursor()\n cursor.execute(sql)\n conn1.commit()\n\n\n for index, row in df_write.iterrows():\n cursor.execute(\"\"\"INSERT INTO [TSR_ADHOC].[dbo].[TEST_AG_SALEOUT](\t\n [YYYYMM] \n ,[AGENT_CODE]\n ,[AGENT_NM]\n ,[CUST_TYPE]\n ,[PRD_CATG]\n ,[PRD_BRAND]\n ,[REGION]\n ,[PROVINCE]\n ,[TM_CAL_PERIOD]\n ,[AG_SALE_OUT_OTHER_FLG]\n ,[AG_SALE_OUT_FLG]\n ,[SALE_OUT_AGENT]\n ,[SALE_OUT_AGENT_OTHER]\n ,[BEG_STOCK_AGENT]\n ,[END_STOCK_AGENT]\n ,[BUY_IN]\n ,[collected_at]\n\t) \n values(?,?,?,?,\n ?,?,?,?,\n ?,?,?,?,\n ?,?,?,?,?)\"\"\", \n row['YYYYMM']\n ,row['AGENT_CODE']\n ,row['AGENT_NM']\n ,row['CUST_TYPE']\n ,row['PRD_CATG']\n ,row['PRD_BRAND']\n ,row['REGION']\n ,row['PROVINCE']\n ,row['TM_CAL_PERIOD']\n ,row['AG_SALE_OUT_OTHER_FLG']\n ,row['AG_SALE_OUT_FLG']\n ,row['SALE_OUT_AGENT']\n ,row['SALE_OUT_AGENT_OTHER']\n ,row['BEG_STOCK_AGENT']\n ,row['END_STOCK_AGENT']\n ,row['BUY_IN']\n ,row['collected_at']\t \n ) \n conn1.commit()\n\n cursor.close()\n conn1.close()\n print('------------Complete WriteDB-------------')\n\nfilepath=r'C:\\\\Users\\\\70018928\\\\Documents\\\\Project2021\\\\Experiment\\\\SqlFromDataFrame\\\\'\nfilename='test_saleout_202102.xlsx'\n\n# Specify columns to be mapped to String in order to make sure that the ID will be considered as categorical var\ncvt={'AGENT_CODE':str}\ndf_input=pd.read_excel(filepath+filename, converters=cvt) \n\n# Convert NaN or Null to None before writing to database otherwise code cannot write to database\ndf_input=df_input.replace({np.nan:None})\n#print(' ==> ',df_input)\n\n\nWrite_data_to_database(df_input)","repo_name":"hkbtotw/SqlToPython","sub_path":"ModAGSaleout_Data_To_DataBase.py","file_name":"ModAGSaleout_Data_To_DataBase.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32755483085","text":"from scipy import stats\r\nimport numpy as np\r\nimport scipy.stats\r\n\r\nrequest_c = []\r\nf = open(\"D:\\\\Connection\\\\Superiortemporal_real\\\\ad.txt\", \"r\")\r\nfor line in f.readlines():\r\n line = line.strip('\\n')\r\n request_c.append(np.float(line))\r\n # print(line)\r\nf.close()\r\na = np.array(request_c)\r\n\r\n\r\nrequest_e = []\r\nf = open(\"D:\\\\Connection\\\\Superiortemporal_real\\\\cn.txt\", \"r\")\r\nfor line in f.readlines():\r\n line = line.strip('\\n')\r\n request_e.append(np.float(line))\r\n # print(line)\r\nf.close()\r\nb = np.array(request_e)\r\n\r\n\r\nrequest_c = np.array([30, 152, 267, 369, 478, 1, 333])\r\nrequest_e = np.array([30, 152, 277, 383, 497])\r\n\r\nt, pval = scipy.stats.ttest_ind(request_c, request_e)\r\n\r\nprint(t,pval)\r\n","repo_name":"xiaoxingxingkz/MACN-Mindspore","sub_path":"ttest.py","file_name":"ttest.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"8688865293","text":"import random\n\nimport ibis\nfrom pathlib import Path\n\nfrom otree.api import Page, cu\n\nfrom .constants import Constants\n\n\nclass Outcome(Page):\n form_model = \"player\"\n\n @staticmethod\n def is_displayed(player):\n return player.round_number == Constants.NUM_LOTTERIES * Constants.ROUNDS_PER_LOTTERY\n\n @staticmethod\n def vars_for_template(player):\n earnings = player.ticket_value_after - player.bid\n return {\n \"player\": player,\n **player.participant.vars['part_one_bid_payoff_data']\n }\n\n\nclass BestGuess(Page):\n form_model = \"player\"\n form_fields = [\"guess\"]\n\n @staticmethod\n def vars_for_template(player):\n return {\n \"player\": player,\n \"num_rounds\": range(1, Constants.ROUNDS_PER_LOTTERY+1),\n \"num_lotteries\": range(1, Constants.NUM_LOTTERIES+1),\n \"min_value\": Constants.MIN_VALUATION,\n \"max_value\": Constants.MAX_VALUATION,\n \"new_lottery\":\n (\n player.round_number != 1\n and ((player.round_number - 1) % Constants.ROUNDS_PER_LOTTERY) == 0\n ),\n }\n\n @staticmethod\n def js_vars(player):\n return dict(\n display_intro=(player.round_number == 1),\n lottery_max_value=player.lottery_max_value,\n mapping_divisor=player.fixed_value,\n is_probability_treatment=player.is_probability_treatment,\n is_cv_treatment=player.is_value_treatment,\n selected_value_text=player.selected_value_text,\n )\n\n\nclass Interval(Page):\n form_model = \"player\"\n form_fields = [\"guess\", \"min_guess\", \"max_guess\"]\n\n @staticmethod\n def vars_for_template(player):\n return {\n \"player\": player,\n \"num_rounds\": range(1, Constants.ROUNDS_PER_LOTTERY+1),\n \"num_lotteries\": range(1, Constants.NUM_LOTTERIES+1),\n \"min_valuation\": Constants.MIN_VALUATION,\n \"max_valuation\": Constants.MAX_VALUATION,\n \"new_lottery\":\n (\n player.round_number != 1\n and ((player.round_number - 1) % Constants.ROUNDS_PER_LOTTERY) == 0\n ),\n \"signal\": player.signal,\n \"signal1\": player.signal1,\n \"signal2\": player.signal2,\n \"signal3\": player.signal3,\n \"signal4\": player.signal4,\n }\n\n @staticmethod\n def before_next_page(player, timeout_happened):\n player.set_guess(player.guess)\n player.set_min_guess(player.min_guess)\n player.set_max_guess(player.max_guess)\n\n if player.is_part_one_payoff(Constants.ROUNDS_PER_LOTTERY):\n # Emin = fix * alpha\n # Emax = fix * beta\n player.prep_emin = player.fixed_value * player.alpha / 100\n player.prep_emax = player.fixed_value * player.beta / 100\n\n # ---------------------------------------------------------------------\n # Question 1a: point belief about highest of the other 3 bids\n # ---------------------------------------------------------------------\n # Computer computes loss function L= (X-OthersHBid)^2\n player.computed_loss = float((player.guess - player.others_high_bid) ** 2)\n # Computer draws random number K ~ U[0,1296]\n MAX_DISTANCE = 1296\n player.random_k = random.randint(0, MAX_DISTANCE)\n # Computer pays 12 credits if L1296)\n # (Note: For the upper threshold of K we took the maximum distance (Emax-Emin) ^ 2 = 36 ^ 2.)\n player.l_less_than_k = player.computed_loss < player.random_k\n if player.l_less_than_k:\n player.guess_earnings = 12.0\n else:\n player.guess_earnings = 0.0\n\n player.prob_k_greater_than_l = int(((MAX_DISTANCE - player.computed_loss) / MAX_DISTANCE) * 100.0)\n # ---------------------------------------------------------------------\n # Question 1b: confidence interval about worth of the lottery.\n # ---------------------------------------------------------------------\n # Computer computes 12*[1- (u-l)/(Emax-Emin)] if positive and OthersHBid in [l,u] (worth is in interval); 0 otherwise\n player.confidence_value = round(12.0 * (\n 1.0 - (float(player.max_guess - player.min_guess) / float(player.prep_emax - player.prep_emin))),\n 2)\n player.high_bid_within_interval = player.min_guess <= player.others_high_bid <= player.max_guess\n player.computed_value_non_zero = player.confidence_value > 0.0\n if player.computed_value_non_zero and player.high_bid_within_interval:\n player.interval_earnings = player.confidence_value\n else:\n player.interval_earnings = 0\n\n player.is_payment_round = True\n player.participant.vars['guess_payoff_data'] = {\n \"fixed_value\": player.fixed_value,\n \"alpha\": player.alpha,\n \"beta\": player.beta,\n \"epsilon\": player.epsilon,\n \"signal\": player.signal,\n \"treatment\": player.treatment,\n \"lottery_order\": player.lottery_order,\n \"lottery_round_number\": player.lottery_round_number,\n \"ticket_value_after\": player.ticket_value_after,\n \"ticket_value_before\": player.ticket_value_before,\n \"ticket_probability\": player.ticket_probability,\n \"is_probability_treatment\": player.is_probability_treatment,\n \"is_value_treatment\": player.is_value_treatment,\n # Question 1 Variables\n # \"prob\": player.prob_k_greater_than_l,\n \"prob_k_greater_than_l\": player.prob_k_greater_than_l,\n \"prep_emax\": player.prep_emax,\n \"prep_emin\": player.prep_emin,\n \"guess_earnings\": player.guess_earnings,\n \"max_guess\": player.max_guess,\n \"min_guess\": player.min_guess,\n \"guess\": player.guess,\n \"interval_earnings\": player.interval_earnings,\n \"earnings\": player.guess_earnings + player.interval_earnings,\n # \"is_worth_within_interval\": player.is_others_high_bid_within_interval,\n \"high_bid_within_interval\": player.high_bid_within_interval,\n \"prep_worth\": player.prep_worth,\n \"random_k\": player.random_k,\n \"computed_loss\": player.computed_loss,\n \"confidence_value\": player.confidence_value,\n # \"is_guess_sufficiently_close_to_worth\": player.l_less_than_k,\n \"l_less_than_k\": player.l_less_than_k,\n \"computed_value_non_zero\": player.computed_value_non_zero,\n \"others_high_bid\": player.others_high_bid,\n }\n\n @staticmethod\n def error_message(player, values):\n if values[\"min_guess\"] > values[\"guess\"] or values[\"max_guess\"] < values[\"guess\"]:\n return f\"Invalid values entered.\"\n\n\n\n @staticmethod\n def js_vars(player):\n return dict(\n display_intro=(player.round_number == 1),\n guess=player.guess,\n lottery_max_value=player.lottery_max_value,\n mapping_divisor=player.fixed_value,\n is_probability_treatment=player.is_probability_treatment,\n is_cv_treatment=player.is_value_treatment,\n selected_value_text=player.selected_value_text,\n )\n\n\nclass Instructions(Page):\n @staticmethod\n def is_displayed(player):\n return player.round_number == 1\n\n @staticmethod\n def vars_for_template(player):\n return {\"treatment\": player.session_treatment}\n\n\n","repo_name":"cesslab/winners-curse-v8","sub_path":"partone/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21456312937","text":"# source : opencv-python-tutroals\r\n# modify : jogilsang\r\n\r\nimport cv2\r\nimport pyautogui\r\nimport os\r\nimport datetime\r\nimport numpy as np\r\n\r\n# FourCC code is passed as cv2.VideoWriter_fourcc('M','J','P','G') or cv2.\r\n# VideoWriter_fourcc(*'MJPG) for MJPG.\r\n\r\nos.chdir('C:\\\\Users\\\\user\\\\Desktop\\\\opencv')\r\n\r\ncap = cv2.VideoCapture(0)\r\n# Define the codec and create VideoWriter object\r\nfourcc = cv2.VideoWriter_fourcc(*'XVID')\r\nout = cv2.VideoWriter('realtime_cam.avi',fourcc, 20.0, (640,480))\r\nwhile(cap.isOpened()) :\r\n\r\n ret, frame = cap.read()\r\n if ret==True:\r\n frame = cv2.flip(frame,0)\r\n # write the flipped frame\r\n out.write(frame)\r\n cv2.imshow('frame',frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n else:\r\n break\r\n\r\n\r\ncap.release()\r\n# Release everything if job is finished\r\nout.release()\r\ncv2.destroyAllWindows()","repo_name":"jogilsang/beginner-opencvTutorial","sub_path":"opencv-tutorial-study-master/taskCode/savevideo.py","file_name":"savevideo.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8063838412","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 13 11:22:44 2017\n@author: denys\n\"\"\"\n\nimport math\nimport copy\n#import time\nimport numpy as np\n#from scipy import interpolate\nfrom scipy.interpolate import interp1d\nimport warnings\nfrom classes.signal_class import signal_class\nimport settings\n\ndef apply_transfer_function(Uout, H):\n\n f_rep = settings.f_rep\n freq = H.f\n\n fn = Uout.sample_rate / 2\n\n df = Uout.f_rep\n\n f_max = min(max(H.f), fn)\n f_min = max(min(H.f), df)\n\n ind_Y_min = int(np.ceil((f_min) / df))\n f_min = ind_Y_min * df\n\n ind_w_max = int(np.floor((f_max - f_min) / df)) + 1\n f_max = ind_w_max * df\n # x = int(np.floor(f_max / f_rep))\n\n w = np.linspace(f_min, f_max, ind_w_max)\n\n\n version = 1\n\n if version == 1 :\n\n t = Uout.time\n\n\n int_Ha = interp1d(H.f, H.a)\n Ha = int_Ha(w)\n #\n # # Hph = np.angle(H_neu)\n #\n int_Hph = interp1d(H.f, H.p)\n Hph = int_Hph(w)\n\n\n u=copy.copy(Uout.in_V)\n #fft\n L=len(u)\n NFFT = L\n\n\n\n\n ufft = np.fft.fft(u, NFFT)\n Y = ufft / L\n\n\n Uquest = np.zeros([L, 2])\n Uquest[:,0] = Uout.time\n\n for k in range(len(w) - 1):\n\n rnd = 11 # round by , since fft is only this precise and would otherwise leave a negligable imaginary part which would throw a warning\n\n k_shifted = ind_Y_min + k - 1\n\n a_n = round(Y[k_shifted + 1], rnd) + round(Y[len(Y) - 1 - k_shifted], rnd)\n b_n = 1j * (round(Y[k_shifted + 1], rnd) - round(Y[len(Y) - 1 - k_shifted], rnd))\n\n omegat = 2 * math.pi * ((k_shifted + 1) * df) * t\n gamma = Hph[k] * np.ones(len(t))\n phi = omegat + gamma\n\n c_ = 1 * abs(Ha[k]) * (a_n * np.cos(phi) + b_n * np.sin(phi))\n\n if any(c_.imag != 0.0):\n warnings.warn(\"c is not purely real\")\n\n c = c_.real\n\n Uquest[:, 1] = Uquest[:, 1] + c\n\n Uquest_obj = signal_class( Uout.time, Uquest[:,1] )\n\n return Uquest_obj\n\n elif version == 2 :\n\n from helpers.plot_helper import plot_2_transfer_functions\n from helpers.plot_helper import plot_vector, plot_transfer_function, plot_2_signals\n\n Uout_vector = Uout.in_V\n # Fns = 1 / (Uout.time[1] - Uout.time[0])\n #\n # # -------- get FFT\n n = Uout_vector.size\n Uout_fft = np.fft.fft(Uout_vector)\n #\n\n int_Hc = interp1d(H.f, H.c)\n Hc = int_Hc(w)\n\n faktor = n / (ind_w_max * 2 + 1)\n\n Uout_fft_first_half = Uout_fft[1:ind_w_max+1]\n Uout_fft_0 = Uout_fft[0]\n\n Uquest_fft_0 = Uout_fft_0\n Uquest_fft_first_half = Uout_fft_first_half * Hc\n Uquest_fft_second_half = np.fliplr([np.conj(Uquest_fft_first_half)])[0]\n\n Uquest_fft = np.concatenate(([Uquest_fft_0], Uquest_fft_first_half, Uquest_fft_second_half), axis=0)\n\n Uquest_vector = np.fft.ifft(Uquest_fft) / faktor\n\n Uquest_obj = signal_class.gen_signal_from_f_rep(Uquest_vector, Uout.f_rep)\n\n return Uquest_obj","repo_name":"Mosarvit/PjSemBeschlTech","sub_path":"Implementierung/Python/nichtLinear/helpers/apply_transfer_function.py","file_name":"apply_transfer_function.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1894581828","text":"import genotype\nimport random\nimport mutators\n\ndef run(genome, iterations, chance):\n champ = genome\n for i in range(iterations):\n #contender = mutators.deepMutate(genome, chance)\n contender = mutators.flipOne(champ)\n if contender.getFitness() < champ.getFitness():\n champ = contender\n\n return champ","repo_name":"BrendanRogerss/GeneticAlgorithms","sub_path":"LocalSearch/hillClimbing.py","file_name":"hillClimbing.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72287296806","text":"import logging\nimport pytz\nfrom datetime import datetime, timedelta\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom models.event import Event\n\n\ndef scrape_staatsoper(api_client, dry_run=False):\n logger = logging.getLogger(__name__)\n logger.info(\"start scraping staatsoper\")\n\n # Create a new instance of the Chrome driver\n options = webdriver.FirefoxOptions()\n options.add_argument('-headless')\n driver = webdriver.Firefox(options=options)\n\n # Navigate to the website\n url = \"https://www.staatsoper.de/spielplan/\"\n driver.get(url)\n\n # Wait for the page to load and for the cookie consent banner to disappear\n wait = WebDriverWait(driver, 10)\n wait.until(EC.invisibility_of_element_located((By.ID, \"cookie-consent\")))\n\n events = []\n\n # Scrape events from current month's page and the next 11 months\n current_month = datetime.now().date().replace(day=1)\n for i in range(12):\n month_url = current_month.strftime(\"https://www.staatsoper.de/spielplan/%Y-%m\")\n driver.get(month_url)\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n\n activity_groups = soup.find_all('div', class_='activity-group')\n for group in activity_groups:\n group_rows = group.find_all('div', class_='activity-list__row')\n for group_row in group_rows:\n name = group_row.find('h3').text.strip()\n\n time_and_location_text = group_row.find('div', class_='activity-list__text').find('span').text\n location = time_and_location_text.split(\"|\")[1].strip()\n date = group_row['data-date']\n start = build_start_datetime(date, time_and_location_text)\n\n category_text = group_row.find('div', class_='activity-list__channel hide-on-md').text.strip()\n category = determine_category(category_text)\n price_info = group_row.find('p', class_='activity-list-price-info').find('span').text.strip()\\\n .replace(\"\\n\", \"\")\n organizer = \"Bayerische Staatsoper\"\n link = \"https://www.staatsoper.de\" + group_row.find('a', class_='activity-list__content')['href']\n\n identifier = group_row.find('input', class_='activity-list--toggle')['value']\n\n event = Event(name=name, start=start, location=location, price_info=price_info, organizer=organizer,\n link=link, identifier=identifier, category=category)\n logger.debug(event)\n events.append(event)\n\n if not dry_run:\n api_client.create_or_update_event(event)\n\n current_month += timedelta(days=30)\n\n # Close the browser\n driver.quit()\n\n logger.info(f\"scraped {len(events)} events\")\n logger.info(\"finished scrapping staatsoper\")\n\n\ndef build_start_datetime(date, time_and_location_text):\n time = time_and_location_text.split(\"|\")[0].strip()[:5]\n return datetime.strptime(date + \" \" + time, \"%Y-%m-%d %H.%M\").astimezone(pytz.timezone('Europe/Berlin'))\n\n\ndef determine_category(category_text):\n main_event_types = [\"ballett\", \"oper\", \"konzert\"]\n if category_text.lower() in main_event_types:\n category = category_text.title()\n else:\n category = \"Staatsoper_Extra\"\n return category\n","repo_name":"fkropfhamer/ivent-platform","sub_path":"scraper/services/staatsoper.py","file_name":"staatsoper.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"28652189369","text":"#!/usr/bin/env python\n\n#Extract Archive\n#(c) Noprianto , 2009, GPL\n#\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport tarfile as tar\n\nclass Main:\n def __init__(self):\n self.archive = ''\n self.contents = []\n self.mode = 'r'\n self.outdir = ''\n \n self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n self.window.set_title('List/extract arsip Tar, Tar.gz, Tar.bz2')\n self.window.set_size_request(400, 200)\n self.window.connect('destroy', gtk.main_quit)\n \n self.btn_fin = gtk.Button(stock=gtk.STOCK_OPEN)\n self.btn_fin.connect('clicked', self.do_open)\n \n self.btn_dout = gtk.FileChooserButton('Pilih direktori output')\n self.btn_dout.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)\n \n self.btn_extract = gtk.Button('E_xtract')\n self.btn_extract.connect('clicked', self.do_extract)\n \n self.hbox1 = gtk.HBox(True)\n self.hbox1.pack_start(gtk.Label('Select archive'))\n self.hbox1.pack_start(self.btn_fin)\n \n self.hbox2 = gtk.HBox(True)\n self.hbox2.pack_start(gtk.Label('Output dir'))\n self.hbox2.pack_start(self.btn_dout)\n \n self.hbox3 = gtk.HBox(True)\n self.hbox3.pack_start(gtk.Label('Click to extract'))\n self.hbox3.pack_start(self.btn_extract)\n\n self.textb = gtk.TextBuffer()\n self.textv = gtk.TextView(self.textb)\n self.scrollw = gtk.ScrolledWindow()\n self.scrollw.set_policy(gtk.POLICY_AUTOMATIC,\n gtk.POLICY_AUTOMATIC)\n self.scrollw.add(self.textv)\n\n self.statbar = gtk.Statusbar()\n\n self.vbox = gtk.VBox(True)\n self.vbox.pack_start(self.hbox1)\n self.vbox.pack_start(self.hbox2)\n self.vbox.pack_start(self.hbox3)\n self.vbox.pack_start(self.scrollw)\n self.vbox.pack_start(self.statbar)\n \n self.window.add(self.vbox)\n self.window.show_all()\n \n def do_open(self, widget):\n self.archive = ''\n \n dialog = gtk.FileChooserDialog('Choose Archive', self.window,\n action=gtk.FILE_CHOOSER_ACTION_OPEN,\n buttons=(gtk.STOCK_OPEN, gtk.RESPONSE_OK))\n \n filter_tar = gtk.FileFilter()\n filter_tar.set_name('Tarball')\n filter_tar.add_pattern('*.tar')\n\n filter_targz = gtk.FileFilter()\n filter_targz.set_name('Gzip Tarball')\n filter_targz.add_pattern('*.tar.gz')\n\n filter_tarbz2 = gtk.FileFilter()\n filter_tarbz2.set_name('Bzip2 Tarball')\n filter_tarbz2.add_pattern('*.tar.bz2')\n \n dialog.add_filter(filter_tar)\n dialog.add_filter(filter_targz)\n dialog.add_filter(filter_tarbz2)\n \n dialog.set_select_multiple(False)\n \n result = dialog.run()\n if result == gtk.RESPONSE_OK:\n filename = dialog.get_filename()\n if filename:\n self.archive = filename\n if self.archive.endswith('.tar.gz'):\n self.mode = 'r:gz'\n elif self.archive.endswith('.tar.bz2'):\n self.mode = 'r:bz2'\n else:\n self.mode = 'r'\n \n dialog.destroy()\n \n tarball = tar.open(self.archive, self.mode)\n self.contents = tarball.getnames()\n tarball.close()\n\n text = '\\n'.join(self.contents)\n self.textb.set_text(text)\n\n self.statbar.push(1, self.archive)\n \n def do_extract(self, widget):\n self.outdir = self.btn_dout.get_filename()\n\n tarball = tar.open(self.archive, self.mode)\n for f in self.contents:\n while gtk.events_pending():\n gtk.main_iteration(False)\n self.statbar.push(1, f)\n tarball.extract(f, self.outdir)\n tarball.close()\n\n self.statbar.push(1, 'Done')\n\nif __name__ == '__main__':\n app = Main()\n gtk.main()\n","repo_name":"WarungData/codes","sub_path":"python-pygtk/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"7570731997","text":"from aula29072019.ListaLigada import ListaLigada\nlistaLigada = ListaLigada()\nlistaLigada.inserirInicio(2, 'Mario', '222222222-22')\nlistaLigada.inserirInicio(1, 'Vandre', '111111111-11')\nlistaLigada.inserirFim(3, 'José', '333333333-33')\nlistaLigada.inserir('500', 'Boby', '999999999-99', 3)\nprint('---Inserções:')\nlistaLigada.imprimirLista()\nprint('---Tamanho:')\nprint(listaLigada.imprimirTamanho())\nprint('---Remoções:')\nlistaLigada.remover(3)\nlistaLigada.remover(1)\nlistaLigada.remover(0)\n\nlistaLigada.imprimirLista()\nprint('---Tamanho:')\nprint(listaLigada.imprimirTamanho())\n# print('Buscar Elemento:')\n# print(listaLigada.buscarElemento(2).toString())","repo_name":"mariosiqueira/aedpython","sub_path":"aula29072019/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32296275786","text":"# 24분\n# 키워드 : 조합\n\n# 주어진 메뉴들을 course에 있는 숫자의 갯수별로 조합을 만든뒤, 몇번 등장하는지 세어 딕셔너리에 저장\n# 딕셔너리를 순회하며 갯수별로 최대로 많이 호출된 메뉴조합을 result에 담은 뒤 정렬\n# 튜플로 리턴된 combination을 문자열로 변환하는 코드 <= 다른 방법은 없는지 찾아보자\n\n\nfrom itertools import combinations\n\ndef solution(orders, course):\n answer = []\n results = {}\n for order in orders:\n orderArr = sorted([a for a in order])\n for pickNum in course:\n combination = [ \"\".join(i) for i in combinations(orderArr, pickNum)]\n for c in combination:\n if c in results : results[c] += 1 \n else : results[c] = 1\n \n for pickNum in course:\n count = 2\n pickResult = []\n for result in results:\n if len(result) == pickNum and results[result] >= count :\n count = results[result]\n pickResult.append(result)\n pickResult = [p for p in pickResult if results[p] >= count]\n for p in pickResult:\n answer.append(p)\n \n answer.sort()\n \n return answer","repo_name":"sang-gyeong/Coding_Test","sub_path":"HASH/메뉴리뉴얼.py","file_name":"메뉴리뉴얼.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2717062775","text":"\"\"\"\nVarious uses of the Sobel operator for edge gradient thresholding.\n\"\"\"\nimport numpy as np\nimport cv2\n\ndef gray_rgb(img):\n \"\"\"\n # Convert to grayscale\n \"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\ndef absolute_threshold(img, orient='x', kernel=3, thresh=(0, 255)):\n \"\"\"\n Define a function that applies Sobel x or y,\n then takes an absolute value and applies a threshold.\n Note: calling your function with orient='x', thresh_min=5, thresh_max=100\n should produce output like the example image shown above this quiz.\n \"\"\"\n # Apply the following steps to img\n # 2) Take the derivative in x or y given orient = 'x' or 'y'\n if orient == 'x':\n sobel = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=kernel)\n elif orient == 'y':\n sobel = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=kernel)\n else:\n raise ValueError(\"orient must be in ['x', 'y']\")\n # 3) Take the absolute value of the derivative or gradient\n abs_sobel = np.absolute(sobel)\n # 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8\n scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n # 5) Create a mask of 1's where the scaled gradient magnitude\n # is > thresh_min and < thresh_max\n binary_output = np.zeros_like(scaled_sobel)\n binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1\n\n return binary_output\n\ndef magnitude_threshold(img, orient='x', kernel=3, thresh=(0, 255)):\n \"\"\"\n Define a function that applies Sobel x and y, then computes the magnitude of the gradient\n and applies a threshold\n \"\"\"\n # Apply the following steps to img\n # 2) Take the derivative in x or y given orient = 'x' or 'y'\n sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=kernel)\n sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=kernel)\n # 3) Calculate the magnitude\n if orient == 'x':\n magnitude = np.sqrt(sobel_x**2)\n elif orient == 'y':\n magnitude = np.sqrt(sobel_y**2)\n elif orient == 'b':\n magnitude = np.sqrt(sobel_x**2 + sobel_y**2)\n else:\n raise ValueError(\"orient must be in ['x', 'y', 'b']\")\n\n # 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8\n scale_factor = np.max(magnitude) / 255\n magnitude = (magnitude/scale_factor).astype(np.uint8)\n # 5) Create a binary mask where mag thresholds are met, zeros otherwise\n binary_output = np.zeros_like(magnitude)\n binary_output[(magnitude >= thresh[0]) & (magnitude <= thresh[1])] = 1\n # 6) Return this mask as your binary_output image\n return binary_output\n\ndef direction_threshold(img, kernel=3, thresh=(0, np.pi/2)):\n \"\"\"\n Define a function that applies Sobel x and y, then computes the direction of the gradient\n and applies a threshold.\n \"\"\"\n # Apply the following steps to img\n # 2) Take the gradient in x and y separately\n sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=kernel)\n sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=kernel)\n # 3) Take the absolute value of the x and y gradients\n abs_sobelx = np.sqrt(sobel_x**2)\n abs_sobely = np.sqrt(sobel_y**2)\n # 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient\n direction = np.arctan2(abs_sobely, abs_sobelx)\n # 5) Create a binary mask where direction thresholds are met\n binary_output = np.zeros_like(direction)\n binary_output[(direction >= thresh[0]) & (direction <= thresh[1])] = 1\n\n # 6) Return this mask as your binary_output image\n return binary_output\n","repo_name":"bqpham/udacity","sub_path":"sdcnd/CarND-Advanced-Lane-Lines/sobel.py","file_name":"sobel.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20478955057","text":"import logging\n\n# Blender imports\nimport bpy\nfrom bpy.props import IntProperty, FloatProperty, BoolProperty, StringProperty, EnumProperty, CollectionProperty\n\n# RobotDesigner imports\nfrom ..core import PluginManager\nfrom ..core.logfile import operator_logger, LogFunction\nfrom ..operators.segments import SelectSegment, UpdateSegments\nfrom ..core.property import PropertyGroupHandlerBase, PropertyHandler\n\nclass RDSelectedObjects(PropertyGroupHandlerBase):\n\n def __init__(self):\n\n self.visible = PropertyHandler()\n\nclass RDGlobals(PropertyGroupHandlerBase):\n \"\"\"\n Property group that contains all globally defined parameters mostly related to the state of the GUI\n \"\"\"\n\n @staticmethod\n def debug_level_callback(self, context):\n operator_logger.info('Switching debug level')\n level = global_properties.operator_debug_level.get(context.scene)\n if level == 'debug':\n operator_logger.setLevel(logging.DEBUG)\n elif level == 'info':\n operator_logger.setLevel(logging.INFO)\n elif level == 'warning':\n operator_logger.setLevel(logging.WARNING)\n else:\n operator_logger.setLevel(logging.ERROR)\n\n @staticmethod\n def updateGlobals(self, context):\n model_name = context.active_object.name\n segment_name = context.active_bone.name\n\n UpdateSegments.run(model_name=model_name, segment_name=segment_name)\n\n\n @staticmethod\n def updateBoneName(self, context):\n\n SelectSegment.run(segment_name=global_properties.segment_name.get(context.scene))\n\n @staticmethod\n def update_geometry_name(self, context):\n print(\"Udpate Mesh name\")\n for i in [i for i in bpy.context.selected_objects if i.name != context.active_object.name]:\n i.select = False\n try:\n bpy.data.objects[global_properties.mesh_name.get(context.scene)].select = True\n except KeyError:\n pass # This happens when the search title is selected\n\n @staticmethod\n def display_geometries(self, context):\n \"\"\"\n Hides/Shows mesh objects in dependence of the respective Global property\n \"\"\"\n\n hide_geometry = global_properties.display_mesh_selection.get(context.scene)\n geometry_name = [obj.name for obj in bpy.data.objects if\n not obj.parent_bone is None and\n obj.type == 'MESH']\n for mesh in geometry_name:\n obj = bpy.data.objects[mesh]\n if hide_geometry == 'all':\n obj.hide = False\n elif hide_geometry == 'collision' and obj.RobotEditor.tag == 'COLLISION':\n obj.hide = False\n elif hide_geometry == 'visual' and obj.RobotEditor.tag == 'DEFAULT':\n obj.hide = False\n elif hide_geometry == 'none':\n obj.hide = False\n else:\n obj.hide = True\n\n def __init__(self):\n\n # Holds the current selected kinematics model (armature) name\n self.model_name = PropertyHandler(StringProperty())\n\n # Holds the name of the currently selected segment (Bone)\n self.segment_name = PropertyHandler(StringProperty(update=self.updateBoneName))\n\n # Holds the name of the currently selected geometry (Mesh object)\n self.mesh_name = PropertyHandler(StringProperty(update=self.update_geometry_name))\n\n # Holds the name of the currently selected physics frame (Empty object)\n self.physics_frame_name = PropertyHandler(StringProperty())\n\n # Holds the name of the currently selected physics frame (Empty object)\n self.camera_sensor_name = PropertyHandler(StringProperty())\n\n # Used to realize the main tab in the GUI\n self.gui_tab = PropertyHandler(EnumProperty(\n items=[('armatures', 'Robot', 'Modify the Robot'),\n ('bones', 'Segments', 'Modify segements'),\n ('meshes', 'Geometries', 'Assign meshes to segments'),\n ('sensors', 'Sensors', 'Assign sensors to segments'),\n # ('markers', 'Markers', 'Assign markers to bones'),\n # ('controller', 'Controller', 'Modify controller parameter'),\n ('tools', 'Tools', 'Tools'),\n ('files', 'Files', 'Export Armature')],\n ))\n\n # Holds the selection to operate on colission geometries OR visual geometries\n self.mesh_type = PropertyHandler(EnumProperty(\n items=[('DEFAULT', 'Visual geometries', 'Edit visual geometries'),\n ('COLLISION', 'Collision geometries', 'Edit collision geometries')]\n ))\n\n self.sensor_type = PropertyHandler(EnumProperty(\n items=[('CAMERA_SENSOR','Cameras', 'Edit camera sensors'),\n ('LASER_SENSOR', 'Laser scanners', 'Edit laser scanners')]\n # ('POSITION', 'Position sensors', 'Edit position sensors')]\n ))\n\n self.physics_type = PropertyHandler(EnumProperty(items=[('PHYSICS_FRAME', 'Mass object', 'Mass object')]))\n\n # Holds the selection to list connected or unassigned meshes in dropdown menus\n self.list_meshes = PropertyHandler(EnumProperty(\n items=[(\"all\", 'List all', 'Show all meshes in menu', 'RESTRICT_VIEW_OFF', 1),\n (\"connected\", 'List connected', 'Show only connected meshes in menu', 'OUTLINER_OB_ARMATURE', 2),\n ('disconnected', 'List disconnected', 'Show only disconnected meshes in menu',\n 'ARMATURE_DATA', 3)]))\n\n # Holds the selection of wheter do hide/display connected/unassigned meshes in the 3D viewport\n self.display_mesh_selection = PropertyHandler(EnumProperty(\n items=[('all', 'All',\n 'Show all objects in viewport'),\n ('collision', 'Collision',\n 'Show only connected collision models'),\n ('visual', 'Visual',\n 'Show only connected visual models'),\n ('none', \"None\", \"Show no connected model\")],\n update=self.display_geometries))\n\n # Holds the selection to list connected or unassigned segments in dropdown menus\n self.list_segments = PropertyHandler(EnumProperty(\n items=[(\"all\", 'List all', 'Show all bones in menu', 'RESTRICT_VIEW_OFF', 1),\n (\"connected\", 'List connected', 'Show only bones with connected meshes in menu',\n 'OUTLINER_OB_ARMATURE', 2,),\n ('disconnected', 'List disconnected',\n 'List only bones without connected meshes in menu', 'ARMATURE_DATA', 3)]))\n\n self.storage_mode = PropertyHandler(EnumProperty(items=[('temporary', 'Non-persistant GIT',\n 'Stores/retrieves files from GIT temporary' +\n ' repository'),\n ('git', 'Persitant GIT',\n 'Stores/retrieves files from persistent GIT repository'),\n ('local', 'Local',\n 'Stores/retrieves from local hard disk')]))\n self.git_url = PropertyHandler(StringProperty(name='GIT URL'))\n self.git_repository = PropertyHandler(StringProperty(name='GIT Repository'))\n\n self.segment_tab = PropertyHandler(EnumProperty(\n items=[('kinematics', 'Kinematics', 'Edit kinematic properties'),\n ('dynamics', 'Dynamics', 'Edit Dynamic properties'),\n ('controller', 'Controller', 'Edit Controller properties')],\n name=\"asdf\"))\n\n self.bone_length = PropertyHandler(FloatProperty(name=\"Global bone length\", default=1, min=0.001,\n update=self.updateGlobals))\n self.do_kinematic_update = PropertyHandler(BoolProperty(name=\"Import Update\", default=True))\n\n self.gazebo_tags = PropertyHandler(StringProperty(name=\"Gazebo tags\", default=\"\"))\n\n self.operator_debug_level = PropertyHandler(EnumProperty(\n items=[('debug', 'Debug', 'Log everything including debug messages (verbose)'),\n ('info', 'Info', 'Log information'),\n ('warning', 'Warning', 'Log only warnings'),\n ('error', 'Error', 'Log only errors')], update=self.debug_level_callback))\n\n\nglobal_properties = RDGlobals()\nglobal_properties.register(bpy.types.Scene)\n","repo_name":"higain/BlenderRobotDesigner","sub_path":"robot_designer_plugin/properties/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":8659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"8084201803","text":"import json\nfrom typing import Union\n\nimport gym\n\nfrom minerl.herobraine.env_spec import EnvSpec\n\ndef _gym_space_to_dict(space: Union[dict, gym.Space]) -> dict:\n if isinstance(space, gym.spaces.Dict):\n dct = {}\n for k in space.spaces:\n dct[k] = _gym_space_to_dict(space.spaces[k])\n return dct\n else:\n return space\n\ndef _format_dict(arg: dict) -> str:\n arg = {\":ref:`{} <{}>`\".format(k, k): arg[k] for k in arg}\n json_obj = json.dumps(arg, sort_keys=True, indent=8, default=lambda o: str(o))\n json_obj = json_obj[:-1] + \" })\"\n return f'.. parsed-literal:: \\n\\n Dict({json_obj}\\n\\n\\n'\n\ndef print_env_spec_sphinx(env_spec: EnvSpec) -> None:\n env = env_spec()\n env_name = env.name\n print(\"_\" * len(env_name))\n print(f\"{env_name}\")\n print(\"_\" * len(env_name))\n print(env.__doc__)\n if hasattr(env, \"inventory\"):\n print(\"..................\")\n print(\"Starting Inventory\")\n print(\"..................\")\n starting_inv_canonical = {}\n for stack in env.inventory:\n item_id = stack[\"type\"]\n starting_inv_canonical[item_id] = stack[\"quantity\"]\n print(_format_dict(starting_inv_canonical))\n if hasattr(env, \"max_episode_steps\"):\n print(\"..................\")\n print(\"Max Episode Steps\")\n print(\"..................\")\n print(f\":code:`{env.max_episode_steps}`\")\n print(\"\\n.....\")\n print(\"Usage\")\n print(\".....\")\n usage_str = f'''.. code-block:: python\n \n env = gym.make(\"{env.name}\")\n '''\n print(usage_str)\n","repo_name":"minerllabs/minerl","sub_path":"minerl/utils/documentation.py","file_name":"documentation.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":587,"dataset":"github-code","pt":"52"} +{"seq_id":"18123475394","text":"from random import Random\r\nimport pandas as pd\r\nimport streamlit as st\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom PIL import Image\r\n\r\n\r\nst.write(\"\"\"\r\n# :rocket:Predicting Data on Diabetes Patients \r\n\r\n\"\"\"\r\n)\r\n#Displaying an image\r\nimage = Image.open('diabetic_patient.jpg')\r\n\r\nst.image(image,caption='diabetic patient')\r\n\r\n# if st.checkbox('show dataset'):\r\n# st.table(ds)\r\n\r\n# ds\r\n\r\n# st.line_chart(ds)\r\n\r\nst.write(\"\"\"\r\n## Sample Data on which the patient are tested : \r\n\"\"\")\r\ndf = pd.read_csv('diabetes.csv')\r\n\r\nshow_ds = df.iloc[:5,:-1]\r\nst.table(show_ds)\r\n\r\nst.write('## showing statistics and chart :')\r\n\r\nst.write(show_ds.describe())\r\n\r\nst.write('## showing bar chart :')\r\n\r\nchart = st.bar_chart(df)\r\n\r\n#spliting the dataset into train and test\r\n\r\nx = df.iloc[:,:-1]\r\ny = df.iloc[:,-1]\r\n\r\nx_train, x_test, y_train , y_test = train_test_split(x, y, test_size=0.25, random_state=0)\r\n\r\ndef get_user_input():\r\n pregnancies = st.sidebar.slider('pregnancies' , 0 , 17 , 3)\r\n Glucose = st.sidebar.slider('glucose' , 0 , 200 , 30)\r\n BloodPressure = st.sidebar.slider('bloodpressure' , 75 , 123 , 50)\r\n SkinThickness = st.sidebar.slider('skinthickness' , 75 , 123 , 30)\r\n Insulin = st.sidebar.slider('insulin' , 0 , 847 , 120)\r\n bmi = st.sidebar.slider('bmi' , 0 , 847 , 120)\r\n DPF = st.sidebar.slider('spf', 0.08, 2.42 , 1.0)\r\n Age = st.sidebar.slider('age', 21 , 81)\r\n\r\n user_data = {'pregnancies':pregnancies,\r\n 'glucose':Glucose,\r\n 'bloodpressure': BloodPressure,\r\n 'skinthickness': SkinThickness,\r\n 'insulin':Insulin,\r\n 'bmi':bmi,\r\n 'dpf':DPF,\r\n 'age':Age\r\n }\r\n \r\n features = pd.DataFrame(user_data,index=[0])\r\n\r\n return features\r\n\r\n#giving the subheader and displaying the user input\r\nuser_input = get_user_input()\r\nst.write(\"\"\"\r\n## Displaying the user input\r\n\"\"\")\r\n\r\nst.write(user_input)\r\n\r\n#creating and training the model\r\nRFClassifiers = RandomForestClassifier()\r\nRFClassifiers.fit(x_train, y_train)\r\n\r\n\r\n\r\n#store the prediction of the model in a variable\r\nst.subheader('Result :')\r\npredict = RFClassifiers.predict(user_input)\r\n\r\nif predict == 0:\r\n st.write(\"# you don't have Diabetes :smile: :thumbsup:\")\r\nelse:\r\n st.write(\"# Sorry , You have Diabetes 😢\")\r\nst.write(predict)\r\n\r\n#showing the accuracy score\r\nst.subheader('## Model Accuracy score :')\r\nst.write(str(accuracy_score(y_test, RFClassifiers.predict(x_test))* 100 )+ '%')\r\n\r\nst.write(\"\"\"\r\n## A Project by [shadman](www.github.com/shady4real)\r\n\"\"\")\r\n\r\n","repo_name":"shadmanshaikh/diabetes_prediction_model","sub_path":"diabetes.py","file_name":"diabetes.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"5000345363","text":"from __future__ import division\nfrom neuron import h\nfrom neuron import gui\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.ion()\n###################\n# # Build Model # #\n###################\n\nsoma = h.Section(name=\"soma\")\nsoma.L = 10 # um\nsoma.diam = 10 # um\nsoma.Ra = 100\nsoma.insert('pas')\nsoma.g_pas = 1/10000 # 1/Rm - Rm ohm*cm^2\n\ndend = h.Section(name=\"dend\")\ndend.L = 500 # um\ndend.diam = 1 # um\ndend.Ra = 100 # ohm*cm\ndend.insert('pas')\ndend.g_pas = 1/10000\n\ndend.connect(soma, 1, 0) #connect the end of the soma to the start of the dendrite\n\nh(\"forall { nseg = int((L/(0.1*lambda_f(100))+0.9)/2)*2 + 1 }\")\n\n#########################\n# # Set up experiment # #\n#########################\n\nstim = h.IClamp(soma(0.5)) # add a current clamp the the middle of the soma\nstim.delay = 10 # ms\nstim.dur = 100 # ms\nstim.amp = 0.1 # nA\n\nsoma_v = h.Vector() # set up a recording vector\nsoma_v.record(soma(0.5)._ref_v) # record voltage at the middle of the soma\n\n# Record voltage from all segments in the dendrite\ndend_vs = []\nfor seg in dend:\n\tdend_vs.append(h.Vector())\n\tdend_vs[-1].record(seg._ref_v)\n\nt = h.Vector()\nt.record(h._ref_t) #record time.\nh.v_init = -70 # set starting voltage \nh.tstop = 200 # set simulation time\nh.run() # run simulation\n\n\n################\n# Plot Results #\n################\nplt.figure(figsize=(8,5))\nplt.plot(t, soma_v,color='k',label='soma(0.5)')\nfor i,v in list(enumerate(dend_vs))[::3]:\n\tplt.plot(t, v, color=(0,0,0.5+0.5*i/len(dend_vs)), \n\t\t label = 'dend({:.2})'.format(i/len(dend_vs)))\n\nplt.xlim(0,200)\nplt.xlabel('Time (ms)', fontsize = 15)\nplt.ylabel('Voltage (mV)', fontsize = 15)\nplt.legend(fontsize = 14, frameon=False)\nplt.tight_layout()\n\n\n###########################\n# Add HH channels to soma #\n###########################\n\nh.tstop = 25\nstim.dur = 5\nsoma.insert('kv') # add potassium channel\nsoma.gbar_kv = 2000 # set the potassium conductance\n\nsoma.insert('na') # add sodium channel\nsoma.gbar_na = 10000 # set the sodium conductance\nh.celsius = 30\n\nh.run()\nplt.figure(figsize=(8,5))\nplt.plot(t, soma_v,color='k',label='soma(0.5)')\nfor i,v in list(enumerate(dend_vs))[::3]:\n\tplt.plot(t, v, color=(0,0,0.5+0.5*i/len(dend_vs)), \n\t\t label = 'dend({:.2})'.format(i/len(dend_vs)))\n\n\nplt.xlabel('Time (ms)', fontsize = 15)\nplt.ylabel('Voltage (mV)', fontsize = 15)\nplt.legend(fontsize = 14, frameon=False)\nplt.tight_layout()\n\n\n\n\n\n\n\n","repo_name":"orena1/NEURON_tutorial","sub_path":"Python_scripts/Ball_and_Stick.py","file_name":"Ball_and_Stick.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"52"} +{"seq_id":"2977425098","text":"import numpy as np\nimport pdb\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# Backbone Network similar to VoxelNet\n\nclass Backbone(nn.Module):\n def __init__(self, in_channel, out_channels, layer_nums, layer_strides=[2, 2, 2]):\n super().__init__()\n assert len(out_channels) == len(layer_nums)\n assert len(out_channels) == len(layer_strides)\n \n self.multi_blocks = nn.ModuleList()\n for i in range(len(layer_strides)):\n blocks = []\n blocks.append(nn.Conv2d(in_channel, out_channels[i], 3, stride=layer_strides[i], bias=False, padding=1))\n blocks.append(nn.BatchNorm2d(out_channels[i], eps=1e-3, momentum=0.01))\n blocks.append(nn.ReLU(inplace=True))\n\n for _ in range(layer_nums[i]):\n blocks.append(nn.Conv2d(out_channels[i], out_channels[i], 3, bias=False, padding=1))\n blocks.append(nn.BatchNorm2d(out_channels[i], eps=1e-3, momentum=0.01))\n blocks.append(nn.ReLU(inplace=True))\n\n in_channel = out_channels[i]\n self.multi_blocks.append(nn.Sequential(*blocks))\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n\n def forward(self, x):\n '''\n x: (b, c, y_l, x_l). Default: (6, 64, 496, 432)\n return: list[]. Default: [(6, 64, 248, 216), (6, 128, 124, 108), (6, 256, 62, 54)]\n '''\n outs = []\n for i in range(len(self.multi_blocks)):\n x = self.multi_blocks[i](x)\n outs.append(x)\n return outs\n\n\nclass Neck(nn.Module):\n def __init__(self, in_channels, upsample_strides, out_channels):\n super().__init__()\n assert len(in_channels) == len(upsample_strides)\n assert len(upsample_strides) == len(out_channels)\n\n self.decoder_blocks = nn.ModuleList()\n for i in range(len(in_channels)):\n decoder_block = []\n decoder_block.append(nn.ConvTranspose2d(in_channels[i], \n out_channels[i], \n upsample_strides[i], \n stride=upsample_strides[i],\n bias=False))\n decoder_block.append(nn.BatchNorm2d(out_channels[i], eps=1e-3, momentum=0.01))\n decoder_block.append(nn.ReLU(inplace=True))\n\n self.decoder_blocks.append(nn.Sequential(*decoder_block))\n \n # in consitent with mmdet3d\n for m in self.modules():\n if isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n\n def forward(self, x):\n '''\n x: [(bs, 64, 248, 216), (bs, 128, 124, 108), (bs, 256, 62, 54)]\n return: (bs, 384, 248, 216)\n '''\n outs = []\n for i in range(len(self.decoder_blocks)):\n xi = self.decoder_blocks[i](x[i]) # (bs, 128, 248, 216)\n outs.append(xi)\n out = torch.cat(outs, dim=1)\n return out\n","repo_name":"Loahit5101/PointPillars-Camera-LiDAR-Fusion","sub_path":"backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"} +{"seq_id":"32771197894","text":"#BFS Traversal of Graphs\n\nfrom collections import deque\n\nclass Node:\n def __init__(self, val):\n self.node = val\n self.next = None\n\n\nclass Graph:\n def __init__(self, vertices):\n self.vertices = vertices\n self.graph = [None] * self.vertices\n\n def addEdge(self, src, dest):\n new = Node(dest)\n temp = self.graph[src]\n if temp:\n while temp.next:\n temp = temp.next\n temp.next = new\n else: self.graph[src] = new\n\n if src != dest:\n new = Node(src)\n temp = self.graph[dest]\n if temp:\n while temp.next:\n temp = temp.next\n temp.next = new\n else:\n self.graph[dest] = new\n\n def display(self):\n for i in range(self.vertices):\n temp = self.graph[i]\n print('Vertex', i)\n print('Root ->', end=\"\")\n while temp:\n print(temp.node, '->' ,end=\"\")\n temp = temp.next\n print('/','\\n')\n\n def bfs(self, start):\n visited = set()\n queue = deque()\n queue.append(start)\n visited.add(start)\n print('BFS Traversal')\n while queue:\n curr = queue.popleft()\n print(curr, end=\" \")\n temp = self.graph[curr]\n # print(temp.val)\n while temp:\n if temp.node not in visited:\n queue.append(temp.node)\n visited.add(temp.node)\n temp = temp.next\n\n\n\ndef main():\n vertices = 7\n graph = Graph(vertices)\n graph.addEdge(0, 1)\n graph.addEdge(0, 2)\n graph.addEdge(1, 1)\n graph.addEdge(1, 3)\n graph.addEdge(1, 4)\n graph.addEdge(3, 4)\n graph.addEdge(2, 3)\n graph.addEdge(5, 6)\n graph.addEdge(6, 4)\n graph.addEdge(5, 2)\n graph.display()\n graph.bfs(1)\n\n\nmain()\n","repo_name":"nishantchaudhary12/Graphs","sub_path":"bfsTraversal.py","file_name":"bfsTraversal.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21318910430","text":"\nBlack_player= 'B'\nWhite_player= 'W'\nnone='.'\n\nall_directions=[[-1,0],[-1,-1],[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1]]\n\nclass Invalid_move(Exception):\n pass\n\nclass gameover_error(Exception):\n pass\n\nclass game_state:\n\n def __init__(self,column,row,turn:'B or W'):\n self.board_row = row\n self.board_column = column\n self.turnn = turn\n self.valid=[]\n self.board =[]\n\n\n def pieces_start(self, lst) -> list:\n\n self.board.extend(lst)\n return self.board\n \n\n def print_board(self):\n print('B: {} W: {}'.format(self.black_score, self.white_score))\n \n for x in range(0, self.board_row):\n for i in self.board[x]:\n print(i, end = ' ')\n print()\n\n \n\n def copy_board(self, current_board):\n board_copy=[]\n for row in range(self.board_row):\n board_copy.append([])\n for column in range(self.board_column):\n board_copy[-1].append(current_board[row][column])\n self.black_score,self.white_score = self.total_score()\n self.print_board()\n return board_copy\n\n\n\n\n\n def opposite_turn(self):\n if self.turnn == Black_player:\n self.turnn = White_player\n elif self.turnn == White_player:\n self.turnn = Black_player\n return self.turnn\n\n\n\n def loc_same_color(self):\n self.location_list=[]\n for row in range(0, self.board_row):\n for column in range(0, self.board_column):\n if self.board[row][column]== self.turnn:\n self.location_list.append([row, column])\n return self.location_list\n\n\n def change_player(self):\n self.other_piece= White_player\n if self.turnn == Black_player:\n self.other_piece = White_player\n elif self.turnn == White_player:\n self.other_piece = Black_player\n return self.other_piece\n \n\n def flipping(self):\n adjacent_list =[]\n self.piece_flip_list=[]\n self.valid=[]\n self.other_piece = self.change_player()\n \n for xdirection, ydirection in all_directions:\n for each_spot in self.location_list:\n self.adjacent_row = each_spot[0] + xdirection\n self.adjacent_column = each_spot[1] + ydirection\n if self.valid_position(self.adjacent_row,self.adjacent_column) and self.board[self.adjacent_row][self.adjacent_column] == self.other_piece:\n adjacent_list.append([self.adjacent_row, self.adjacent_column])\n\n while self.board[self.adjacent_row][self.adjacent_column] == self.other_piece:\n \n self.adjacent_row = self.adjacent_row + xdirection\n self.adjacent_column = self.adjacent_column + ydirection\n if not self.valid_position(self.adjacent_row,self.adjacent_column): \n break\n\n if self.valid_position(self.adjacent_row,self.adjacent_column):\n if self.board[self.adjacent_row][self.adjacent_column] == none: \n self.valid.append([self.adjacent_row,self.adjacent_column])\n \n elif self.board[self.adjacent_row][self.adjacent_column] == self.turnn:\n while True:\n self.adjacent_row = self.adjacent_row - xdirection\n self.adjacent_column = self.adjacent_column - ydirection\n if self.board[self.adjacent_row][self.adjacent_column] == self.turnn:\n break\n self.piece_flip_list.append([self.adjacent_row,self.adjacent_column])\n\n\n \n def make_move(self,row_select,column_select): \n while True:\n if [row_select ,column_select] not in self.valid:\n raise Invalid_move\n elif [row_select ,column_select] in self.valid:\n self.board[row_select][column_select] = self.turnn\n self.flipping()\n current_board = self.flip_pieces()\n return current_board\n \n def valid_position(self,row_select,column_select):\n return 0 <= row_select < self.board_row and 0 <= column_select < self.board_column\n\n\n\n def flip_pieces (self):\n for pieces in self.piece_flip_list:\n self.board[pieces[0]][pieces[1]] = self.turnn\n return self.board\n\n def total_score(self):\n total_score_black= 0\n total_score_white= 0\n for row in range(int(self.board_row)):\n for column in range(int(self.board_column)):\n if self.board[row][column] == Black_player:\n total_score_black += 1\n elif self.board[row][column] == White_player:\n total_score_white += 1\n return (total_score_black,total_score_white)\n\n\n def game_over(self):\n x = len(self.valid)\n if x == 0:\n return True\n elif x > 0 :\n return False\n\n def winner_least_points(self):\n winner=Black_player\n if self.game_over():\n if self.black_score > self.white_score:\n winner = White_player\n elif self.white_score > self.black_score:\n winner = Black_player\n elif self.white_score == self.black_score:\n winner = \"NONE\"\n return winner\n\n def winner_most_points(self):\n winner= Black_player\n if self.game_over():\n if self.black_score > self.white_score:\n winner = Black_player\n elif self.white_score > self.black_score:\n winner = White_player\n elif self.white_score == self.black_score:\n winner = \"NONE\"\n return winner\n\n\n\n\n","repo_name":"minabedwany/Python_Projects","sub_path":"Othello game/game_logic.py","file_name":"game_logic.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73253512806","text":"from itertools import islice, chain\n\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.exceptions import ValidationError\nfrom django.http import Http404\nfrom django.http import HttpResponse, JsonResponse\nfrom django.template import loader\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\nfrom crispy_forms.utils import render_crispy_form\nfrom django.template.context_processors import csrf\n\nimport bleach\n\nfrom backend.models import Yarn, Manufacturer, Material, Needlesize, Color, \\\n Projectidea, Weight, FinishedObject, Yarnshop, Swatch\nfrom backend.forms import YarnForm, ColorForm, ProjectideaForm, FinishedObjectForm, ManufacturerForm,\\\n YarnshopForm, SwatchForm, MaterialForm, ProjectideaForm2\n\n# Create your views here.\n\ndef index(request):\n \"\"\"returns index site\"\"\"\n return render(request, 'backend/index.html')\n # template = loader.get_template('backend/index.html')\n # context = {}\n # return HttpResponse(template.render(context, request))\n\n\n@login_required\ndef yarns(request):\n \"\"\"shows all yarns in stash and yarns currently unstashed \"\"\"\n\n yarns = Yarn.objects.filter(color__own_it=True).distinct() \\\n .order_by('manufacturer__name', 'name')\n\n unstashed_yarns = Yarn.objects.exclude(color__own_it=True).distinct() \\\n .order_by('manufacturer__name', 'name')\n\n materials = Material.objects.all()\n colors = Color.objects.all()\n\n return render(request, 'backend/yarns.html', {\n 'yarns': yarns,\n 'materials': materials,\n 'colors': colors,\n 'unstashed_yarns': unstashed_yarns,\n })\n\n\n@login_required\ndef yarn_detail(request, yarntype_id):\n \"\"\"shows one single yarn type and its proberties\"\"\"\n colors = Color.objects.filter(yarntype=yarntype_id, own_it=True)\n yarn = Yarn.objects.get(pk=yarntype_id)\n\n return render(request, 'backend/yarn_detail.html', {\n 'colors': colors,\n 'yarn':yarn,\n })\n\n\n@login_required\ndef delete_yarn(request, yarntype_id):\n \"\"\"delete a yarntype from the database and all of its colors\"\"\"\n\n yarn = get_object_or_404(Yarn, pk=yarntype_id)\n yarn.delete()\n messages.info(request, 'The yarn %s was successfully deleted' %yarn.name)\n\n return redirect('yarns')\n\n\n@login_required\ndef add_yarn(request):\n \"\"\"Add a new yarn\"\"\"\n\n form = YarnForm(request.POST)\n manufacturerform = ManufacturerForm(request.POST)\n\n materialform = MaterialForm(request.POST)\n\n\n\n if request.method != \"POST\":\n return render(request, 'backend/add_yarn.html', {'form': form, 'manufacturerform': manufacturerform,\n 'materialform': materialform})\n\n else:\n if form.is_valid():\n yarn = form.save()\n\n return redirect('yarn_detail', yarntype_id=yarn.pk)\n\n else:\n return render(request, 'backend/add_yarn.html', {'form': form, 'manufacturerform': manufacturerform,\n 'materialform': materialform})\n\n\n@login_required\ndef edit_yarn(request, yarntype_id):\n \"\"\"edit an existing yarn type\"\"\"\n yarn = get_object_or_404(Yarn, id=yarntype_id)\n form = YarnForm(request.POST or None, instance=yarn)\n form.helper.form_action = 'edit'\n manufacturerform = ManufacturerForm(request.POST)\n materialform = MaterialForm(request.POST)\n if form.is_valid():\n form.save()\n\n return redirect('yarn_detail', yarntype_id=yarn.id)\n\n return render(request, 'backend/edit_yarn.html', {'form': form, 'manufacturerform': manufacturerform,\n 'materialform': materialform})\n\n\n@login_required\ndef color_detail(request, yarntype_id, color_id):\n \"\"\"shows one color of a specific yarn\"\"\"\n color = Color.objects.filter(yarntype_id=yarntype_id).get(pk=color_id)\n\n return render(request, 'backend/color.html', {'color': color,})\n\n\n@login_required\ndef add_color(request, yarntype_id):\n \"\"\"add a new color for an existing yarn type\"\"\"\n if request.method == 'POST':\n form = ColorForm(request.POST)\n if form.is_valid():\n\n color = form.save(commit=False)\n # check if color is already in db\n if Color.objects.filter(color=color.color,\n col_nr=color.col_nr,\n yarntype=yarntype_id):\n col = Color.objects.get(color=color.color,\n yarntype=yarntype_id )\n return redirect('edit_color', yarntype_id=col.yarntype.id,\n color_id=col.id)\n\n\n yarn = Yarn.objects.get(pk=yarntype_id)\n color.yarntype = yarn\n if color.quantity > 0:\n color.own_it = True\n\n\n color.save()\n\n return redirect('color_detail',\n yarntype_id=yarntype_id,\n color_id=color.pk)\n\n else:\n form = ColorForm()\n\n return render(request, 'backend/add_color.html', {'form': form, })\n\n\n@login_required\ndef edit_color(request, yarntype_id, color_id):\n \"\"\"edit an existing color\"\"\"\n\n color = get_object_or_404(Color, pk=color_id)\n form = ColorForm(request.POST or None, instance=color)\n if form.is_valid():\n color.own_it = color.quantity > 0\n form.save()\n\n return redirect('color_detail',\n yarntype_id=yarntype_id,\n color_id=color.id)\n\n return render(request, 'backend/edit_color.html', {'form': form, })\n\n\n@login_required\ndef delete_color(request, yarntype_id, color_id):\n \"\"\" delete a color from the db \"\"\"\n color = get_object_or_404(Color, pk=color_id)\n color.delete()\n messages.info(request,\n 'The color %s was successfully deleted' % color.color)\n\n return redirect('yarn_detail', yarntype_id)\n\n\n@login_required\ndef projectideas(request):\n \"\"\"show all existing projectideas\"\"\"\n projectideas = Projectidea.objects.all()\n yarns = Yarn.objects.all()\n colors = Color.objects.all()\n weights = Weight.objects.all()\n\n return render(request, 'backend/projectideas.html', {\n 'projectideas': projectideas,\n 'yarns': yarns,\n 'colors': colors,\n 'weights': weights,\n })\n\n\n@login_required\ndef add_projectidea(request):\n \"\"\"add a new idea for a project\"\"\"\n yarnshopform = YarnshopForm()\n if request.method == 'POST':\n form = ProjectideaForm(request.POST)\n\n if form.is_valid():\n projectidea = form.save()\n\n return redirect('projectidea_detail',\n projectidea_id=projectidea.pk)\n\n else:\n form = ProjectideaForm()\n\n return render(request, 'backend/add_projectidea.html', {'form': form, 'yarnshopform': yarnshopform},)\n\n\n@login_required\ndef load_colors(request):\n \"\"\"load colors depending on yarnchoice\"\"\"\n yarn_id = request.GET.get('yarn')\n colors = Color.objects.filter(yarntype=yarn_id).order_by('color')\n\n return render(request, 'backend/dropdownlist_colors.html',\n {'colors': colors,})\n\n\n@login_required\ndef projectidea_detail(request, projectidea_id):\n \"\"\"display one projectidea\"\"\"\n projectidea = get_object_or_404(Projectidea, pk=projectidea_id)\n colors = Color.objects.filter(projectidea__id=projectidea_id)\n\n return render(request, 'backend/projectidea_detail.html', {\n 'projectidea': projectidea,\n 'colors': colors,\n })\n\n\n@login_required\ndef delete_projectidea(request, projectidea_id):\n \"\"\"remove a projectidea from db\"\"\"\n project = get_object_or_404(Projectidea, pk=projectidea_id)\n project.delete()\n messages.info(request,\n 'The projectidea %s was successfully deleted' % project.name)\n\n return redirect('projectideas')\n\n\n@login_required\ndef edit_projectidea(request, projectidea_id):\n \"\"\"edit an existing projectidea\"\"\"\n # projectidea_id = request.POST.get('projectidea_id')\n instance = get_object_or_404(Projectidea, id=projectidea_id)\n\n\n form = ProjectideaForm(request.POST or None, instance=instance)\n form.helper.form_action = 'edit'\n if form.is_valid():\n form.save()\n\n return redirect('projectidea_detail', projectidea_id=instance.id)\n\n return render(request, 'backend/edit_projectidea.html', {'form': form})\n\n\n@login_required\ndef finishedobjects(request):\n \"\"\"show all finished objects\"\"\"\n finishedobjects = FinishedObject.objects.all()\n yarns = Yarn.objects.all()\n needlesizes = Needlesize.objects.all()\n colors = Color.objects.all()\n\n return render(request, 'backend/finishedobjects.html',\n {'finishedobjects': finishedobjects, 'yarns':yarns,\n 'needlesizes': needlesizes, 'colors':colors},)\n\n@login_required\ndef add_fo(request):\n \"\"\"add a finished object\"\"\"\n\n if request.method == 'POST':\n form = FinishedObjectForm(request.POST)\n form.helper.form_action ='add'\n if form.is_valid():\n finishedobject = form.save()\n\n return redirect('finishedobject_detail',\n finishedobject_id=finishedobject.pk)\n\n else:\n form = FinishedObjectForm()\n form.helper.form_action = 'add'\n\n return render(request, 'backend/add_finishedobject.html', {'form': form}, )\n\n\n@login_required\ndef finishedobject_detail(request, finishedobject_id):\n \"\"\"shows details of a selected finished object\"\"\"\n\n finishedobject = FinishedObject.objects.get(pk=finishedobject_id)\n colors = Color.objects.all()\n needlesizes = Needlesize.objects.all()\n\n return render(request, 'backend/finishedobject_detail.html',\n {'finishedobject': finishedobject, 'colors': colors,\n 'needlesizes': needlesizes},)\n\n\n@login_required\ndef delete_finishedobject(request, finishedobject_id):\n \"\"\"delete a finished object\"\"\"\n\n fo = get_object_or_404(FinishedObject, pk=finishedobject_id)\n fo.delete()\n messages.info(request, 'The finished object %s was successfully deleted' % fo.name)\n\n return redirect('finishedobjects')\n\n\n@login_required\ndef edit_fo(request, finishedobject_id):\n \"\"\"edit an existing finished object\"\"\"\n\n fo = get_object_or_404(FinishedObject, id=finishedobject_id)\n\n form = FinishedObjectForm(request.POST or None, instance=fo)\n form.helper.form_action = 'edit'\n if form.is_valid():\n form.save()\n\n return redirect('finishedobject_detail', finishedobject_id=fo.id)\n\n return render(request, 'backend/edit_finishedobject.html', {'form': form})\n\n\n@login_required\ndef manufacturers(request):\n \"\"\"show all manufacturers in db\"\"\"\n manufacturers = Manufacturer.objects.all()\n\n return render(request, 'backend/manufacturers.html', {'manufacturers':manufacturers})\n\n\n@login_required\ndef add_manufacturer(request):\n \"\"\"add a new manufacturer\"\"\"\n\n if request.method == 'POST':\n form = ManufacturerForm(request.POST)\n\n if form.is_valid():\n manufacturer = form.save()\n\n return redirect('manufacturers')\n\n else:\n form = ManufacturerForm()\n\n return render(request, 'backend/add_manufacturer.html', {'form': form}, )\n\n\n@login_required\ndef add_manufacturer_modal(request):\n \"\"\"add a new manufacturer when creating a new yarn\"\"\"\n form = ManufacturerForm()\n if request.method == 'POST':\n form = ManufacturerForm(request.POST)\n\n if form.is_valid():\n manufacturer = form.save()\n newname = bleach.clean(manufacturer.name)\n\n\n return JsonResponse({'name': newname,\n 'id': manufacturer.id})\n else:\n\n return JsonResponse({'error': form.errors}, status=400)\n\n\n return render(request, 'backend/add_manufacturer_modal.html',\n {'form': form}, )\n\n@login_required\ndef add_yarnshop_collapse(request):\n \"\"\"open yarnshop form in a collapsible\"\"\"\n form = YarnshopForm()\n if request.method == 'POST':\n form = YarnshopForm(request.POST)\n\n if form.is_valid():\n yarnshop = form.save()\n newname = bleach.clean(yarnshop.name)\n\n return JsonResponse({'name': newname,\n 'id': yarnshop.id})\n else:\n return JsonResponse({'error': form.errors}, status=400)\n\n return render(request, 'backend/add_yarnshop_collapse.html',\n {'form': form})\n\n\n@login_required\ndef add_material_modal(request):\n \"\"\"add a new material when creating a new yarn\"\"\"\n\n form = MaterialForm()\n if request.method == 'POST':\n form = MaterialForm(request.POST)\n\n if form.is_valid():\n material = form.save()\n newname = bleach.clean(material.name)\n\n\n return JsonResponse({'name': newname,\n 'id': material.id})\n else:\n\n return JsonResponse({'error': form.errors}, status=400)\n\n return render(request, 'backend/add_material_modal.html',\n {'form': form}, )\n\n\n@login_required\ndef add_projectidea_modal(request):\n \"\"\"add a missing projectidea when creating a new finished object\"\"\"\n\n form = ProjectideaForm2()\n\n\n if request.method == 'POST':\n form = ProjectideaForm2(request.POST)\n\n\n\n if form.is_valid():\n projectidea = form.save()\n newname = bleach.clean(projectidea.name)\n\n return JsonResponse({'name': newname, 'id': projectidea.id})\n\n else:\n\n return JsonResponse({'error': form.errors}, status=400)\n\n return render(request, 'backend/add_projectidea_modal.html',\n {'form': form})\n\n\n\n@login_required\ndef add_yarnshop_modal(request):\n \"\"\"add a new yarnshop when creating a new color\"\"\"\n form = YarnshopForm()\n if request.method == 'POST':\n form = YarnshopForm(request.POST)\n\n if form.is_valid():\n yarnshop = form.save()\n newname = bleach.clean(yarnshop.name)\n\n return JsonResponse({'name': newname, 'id': yarnshop.id})\n\n else:\n\n return JsonResponse({'error': form.errors}, status=400)\n\n return render(request, 'backend/add_yarnshop_modal.html', {'form': form},)\n\n\n@login_required\ndef add_yarn_modal(request):\n \"\"\"add a yarn when creating a new projectidea\"\"\"\n form = YarnForm()\n\n if request.method == 'POST':\n form = YarnForm(request.POST)\n\n if form.is_valid():\n yarn = form.save()\n newname = bleach.clean(yarn.name)\n\n return JsonResponse({'name': newname, 'id': yarn.id})\n\n else:\n\n return JsonResponse({'error': form.errors}, status=400)\n\n return render(request, 'backend/add_yarn_modal.html', {'form': form})\n\n\n@login_required\ndef add_color_modal(request):\n \"\"\"add a color when creating a new projectidea\"\"\"\n\n form = ColorForm()\n if request.method == 'POST':\n form = ColorForm(request.POST)\n\n if form.is_valid():\n color = form.save()\n newname = bleach.clean(color.name)\n\n return JsonResponse({'name': newname, 'id': color.id})\n\n else:\n return JsonResponse({'error': form.errors}, status=400)\n\n return render(request, 'backend/add_color_modal.html', {'form': form})\n\n\n@login_required\ndef delete_manufacturer(request, manufacturer_id):\n \"\"\"delete selected manufacturer from db\"\"\"\n\n manufacturer = get_object_or_404(Manufacturer, pk=manufacturer_id)\n manufacturer.delete()\n\n messages.info(request, 'The manufacturer %s was successfully deleted' % manufacturer.name)\n\n return redirect('manufacturers')\n\n\n@login_required\ndef yarnshops(request):\n \"\"\"show all yarnshops\"\"\"\n\n yarnshops = Yarnshop.objects.all()\n\n return render(request, 'backend/yarnshops.html', {'yarnshops': yarnshops})\n\n\n@login_required\ndef add_yarnshop(request):\n \"\"\"add a new yarnshop\"\"\"\n\n if request.method == 'POST':\n form = YarnshopForm(request.POST)\n if form.is_valid():\n yarnshop = form.save()\n\n return redirect('yarnshops')\n\n else:\n form = YarnshopForm()\n\n return render(request, 'backend/add_yarnshop.html', {'form': form})\n\n\n@login_required\ndef delete_yarnshop(request, yarnshop_id):\n \"\"\"delete a specific yarnshop\"\"\"\n\n shop = get_object_or_404(Yarnshop, pk=yarnshop_id)\n shop.delete()\n messages.info(request, 'The yarnshop %s was successfully deleted' % shop.name)\n\n return redirect('yarnshops')\n\n\n@login_required\ndef swatches(request):\n \"\"\"show all swatches\"\"\"\n\n swatches = Swatch.objects.all()\n needlesizes = Needlesize.objects.all()\n yarns = Yarn.objects.all()\n\n return render(request, 'backend/swatches.html', {'swatches': swatches,\n 'needlesizes': needlesizes,\n 'yarns': yarns})\n\n@login_required\ndef add_swatch(request):\n \"\"\"add a swatch\"\"\"\n\n if request.method == 'POST':\n form = SwatchForm(request.POST)\n if form.is_valid():\n swatch = form.save()\n\n return redirect('swatches')\n\n else:\n form = SwatchForm()\n\n return render(request, 'backend/add_swatch.html', {'form': form})\n\n\n@login_required\ndef delete_swatch(request, swatch_id):\n \"\"\"delete swatch from db\"\"\"\n\n swatch = get_object_or_404(Swatch, pk=swatch_id)\n swatch.delete()\n messages.info(request, 'The swatch %s was successfully deleted' % swatch.name)\n\n return redirect('swatches')\n\n\n@login_required\ndef materials(request):\n \"\"\"show all materials\"\"\"\n\n materials = Material.objects.all()\n\n return render(request, 'backend/materials.html', {'materials': materials})\n\n\n@login_required\ndef add_material(request):\n \"\"\" add a material\"\"\"\n if request.method == 'POST':\n form = MaterialForm(request.POST)\n if form.is_valid():\n material = form.save()\n\n return redirect('materials')\n\n else:\n form = MaterialForm()\n\n return render(request, 'backend/add_material.html', {'form': form})\n\n\n@login_required\ndef delete_material(request, material_id):\n \"\"\"delete material from db\"\"\"\n material = get_object_or_404(Material, pk=material_id)\n material.delete()\n messages.info(request, 'The material %s was successfully deleted' % material.name)\n\n return redirect('materials')\n\n\n@login_required\ndef projectidea_to_finishedobject(request, projectidea_id):\n \"\"\"take a projectidea and make a new finished object with the data\"\"\"\n\n projectidea = get_object_or_404(Projectidea, id=projectidea_id)\n fo = FinishedObject(name=projectidea.name, projectidea=projectidea, notes=projectidea.notes,\n skeins_used=projectidea.skeins_needed, yarn=projectidea.yarn)\n\n form = FinishedObjectForm(instance=fo)\n if request.method == 'POST':\n form = FinishedObjectForm(request.POST, instance=fo)\n if form.is_valid():\n fo = form.save()\n return finishedobject_detail(request, finishedobject_id=fo.id)\n else:\n errors = form.errors.as_data()\n\n return render(request, 'backend/edit_finishedobject.html', {'form': form, 'errors': errors})\n else:\n\n return render(request, 'backend/edit_finishedobject.html', {'form': form})\n\n\n\n\n\n","repo_name":"lhannig/wooly-mammoth","sub_path":"WoolDB/backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19209850898","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import datasets, layers, optimizers\nimport os\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n(x, y), _ = datasets.mnist.load_data()\nx = tf.convert_to_tensor(x, dtype=tf.float32) / 50.\ny = tf.convert_to_tensor(y)\ny = tf.one_hot(y, depth=10)\nprint('x:', x.shape, 'y:', y.shape)\ntrain_db = tf.data.Dataset.from_tensor_slices((x, y)).batch(128).repeat(30)\nx, y = next(iter(train_db))\nprint('sample:', x.shape, y.shape)\n\n\ndef main():\n # 784=>512\n w1 = tf.Variable(tf.random.truncated_normal([784, 512], stddev=0.01)) # 解决梯度爆炸问题\n b1 = tf.Variable(tf.zeros([512]))\n # 512=>256\n w2 = tf.Variable(tf.random.truncated_normal([512, 256], stddev=0.01))\n b2 = tf.Variable(tf.zeros([256]))\n # 256 => 10\n w3 = tf.Variable(tf.random.truncated_normal([256, 10], stddev=0.01))\n b3 = tf.Variable(tf.zeros([10]))\n\n optimizer = optimizers.SGD(lr=0.01)\n\n for step, (x, y) in enumerate(train_db):\n # x:[128,28,28]\n # y:[128]\n\n # 需要去做一个维度变换,才能够将数据载入到我们的前向传播中\n # [b,28,28]->[b,28*28]\n x = tf.reshape(x, [-1, 28 * 28])\n\n # 包装在一个求导的环境下,方便计算\n # 出现与权值相关的代码一定要放进去\n with tf.GradientTape() as tape: # 只会跟踪tf.Variable类型的数据,如果将权值定义成常量,会报错\n # x:[b,28*28]\n # h1=x@w1+b1\n # [b,784]@[784,256]+[256]->[b,256]+[256]->[b,256]+[b,256]\n h1 = x @ w1 + b1\n h1 = tf.nn.relu(h1) # 非线性层激活函数\n # [b,256]->[b,128]\n h2 = h1 @ w2 + b2\n h2 = tf.nn.relu(h2)\n # 输出层\n out = h2 @ w3 + b3\n\n # compute loss\n # out:[b,10]\n # y:[b]-> [b,10]\n\n # mse=mean(sum(y-out)^2)\n # [b,10]\n loss = tf.square(y - out)\n # mean:scalar\n loss = tf.reduce_mean(loss, axis=1)\n # [b]=>scalar\n loss = tf.reduce_mean(loss)\n # 利用上面包装好的部分计算梯度\n grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])\n # 观察可能出现的梯度下降过多的问题\n print(\"==before==\")\n for g in grads:\n print(tf.norm(g))\n\n # 限制下降的梯度幅度\n grads, _ = tf.clip_by_global_norm(grads, 15)\n print(\"==after==\")\n for g in grads:\n print(tf.norm(g))\n # 更新梯度\n optimizer.apply_gradients(zip(grads, [w1, b1, w2, b2, w3, b3]))\n\n if step % 100 == 0:\n print(step, 'loss:', float(loss))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"LegendZh/tensorflow-learning","sub_path":"数据限幅/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"71553628646","text":"import cv2\nimport numpy as np\nimport math\nimport serial\n\n# Sends data to arduino via serial\n# Data must be sent/received as S123456\n# 123 = x servo angle, 456 = y servo angle\ndef send_data(arduino, x, y):\n message = 'S' + str(x).zfill(3) + str(y).zfill(3)\n arduino.write(message.encode())\n # print(message)\n\n# Connects serial port to arduino\ndef connect_arduino(port):\n port = '/dev/cu.usbmodem1442201'\n try:\n arduino = serial.Serial(port, 115200)\n return arduino\n except (FileNotFoundError, serial.serialutil.SerialException):\n print(\"No port at \" + port)\n return False\n\n# Calibrates cammera position\ndef calibrate_camera(img):\n worked = True\n img_blur = cv2.GaussianBlur(img,(3,3), sigmaX=0, sigmaY=0)\n hsv = cv2.cvtColor(img_blur, cv2.COLOR_BGR2HSV)\n # Find Red mask\n lower_red = np.array([0, 100, 100])\n upper_red = np.array([8, 255, 255])\n mask_red = cv2.inRange(hsv,lower_red,upper_red)\n # Find Blue mask\n lower_blue = np.array([105, 100, 100])\n upper_blue = np.array([135, 255, 255])\n mask_blue = cv2.inRange(hsv,lower_blue,upper_blue)\n # Both Masks\n mask_all = mask_red + mask_blue\n\n mass_red_y, mass_red_x = np.where(mask_red >= 255)\n if (not mass_red_x.any()) or (not mass_red_y.any()):\n worked = False # If no blue is found\n return worked, 0, 0, 0, 0\n red_x = np.average(mass_red_x)\n red_y = np.average(mass_red_y)\n\n mass_blue_y, mass_blue_x = np.where(mask_blue >= 255)\n if (not mass_blue_x.any()) or (not mass_blue_y.any()):\n worked = False # If no blue is found\n return worked, 0, 0, 0, 0\n blue_x = np.average(mass_blue_x)\n blue_y = np.average(mass_blue_y)\n\n # Calculate scale (mm/pixles)\n scale_pixle = abs(red_y - blue_y)\n\n # Draw\n result = cv2.bitwise_and(img_blur, img_blur, mask=mask_all)\n result = cv2.circle(result, (int(red_x), int(red_y)), 5, (255, 0, 0), 2)\n result = cv2.circle(result, (int(blue_x), int(blue_y)), 5, (255, 0, 0), 2)\n\n return worked, red_x, red_y, scale_pixle, result\n\n# # Connect to arduino via serial\n# port = '/dev/cu.usbmodem1442201'\n# arduino = connect_arduino(port)\n# # Set to no tilt\n# send_data(arduino, 90, 90)\n\n# # Settup camera\n# cam = cv2.VideoCapture(0)\n\n# while True:\n# ret, img = cam.read()\n# img = cv2.flip(img[0:690, 300:929], -1)\n# worked, center_x, center_y, scale, result = calibrate_camera(img)\n# if worked:\n# print(scale)\n# cv2.imshow('mask', result)\n# cv2.waitKey(1)\n# break\n\n# print('Center and Scale found')\n\n# Finds raw x,y pixle ball position\ndef findBall(img):\n found = True\n\n img_blur = cv2.GaussianBlur(img,(3,3), sigmaX=0, sigmaY=0)\n hsv = cv2.cvtColor(img_blur, cv2.COLOR_BGR2HSV)\n\n lower_yellow = np.array([20, 100, 100])\n upper_yellow = np.array([75, 255, 255])\n\n mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)\n result = cv2.bitwise_and(img_blur, img_blur, mask=mask_yellow)\n\n mass_yellow_y, mass_yellow_x = np.where(mask_yellow >= 255)\n if (not mass_yellow_x.any()) or (not mass_yellow_y.any()):\n found = False # If no blue is found\n return found, 0, 0, 0\n yellow_x = np.average(mass_yellow_x)\n yellow_y = np.average(mass_yellow_y)\n\n result = cv2.circle(img, [int(yellow_x), int(yellow_y)], radius= 5, color = (255, 0, 0), thickness = 5)\n\n return found, yellow_x, yellow_y, result\n\n# while True:\n# ret, img = cam.read()\n# img = cv2.flip(img[0:690, 300:929], -1)\n# found, x_pixle, y_pixle, result = findBall(img)\n# if found:\n# print(x_pixle)\n# cv2.imshow('FindBall', result)\n# cv2.waitKey(1)","repo_name":"pjcrann219/BallBalanceV2","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19763460876","text":"def parse_to_bitboards(string: str):\n lines = string.strip().split(\"\\n\")\n black = 0\n white = 0\n y = 0\n\n for line in [l.strip() for l in lines]:\n if line[:2] == '##':\n continue\n for i, ch in enumerate(line[1:9]):\n if ch == 'O':\n black |= 1 << (y*8+i)\n elif ch == 'X':\n white |= 1 << (y*8+i)\n y += 1\n\n return black, white\n\n\ndef parse_ggf_board_to_bitboard(string: str):\n white = black = 0\n for i, ch in enumerate(string):\n if ch == \"*\":\n black |= 1 << i\n elif ch == \"O\":\n white |= 1 << i\n return black, white\n","repo_name":"mokemokechicken/reversi-alpha-zero","sub_path":"src/reversi_zero/lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":658,"dataset":"github-code","pt":"52"} +{"seq_id":"22045350135","text":"from odoo import _, api, fields, models\n\n\nclass OrganizationTypeServiceSousCategorie(models.Model):\n _name = \"organization.type.service.sous.categorie\"\n _inherit = \"portal.mixin\"\n _description = \"Type de services sous-catégorie\"\n _rec_name = \"nom\"\n\n nom = fields.Char()\n\n active = fields.Boolean(\n string=\"Actif\",\n default=True,\n help=(\n \"Lorsque non actif, cette sous-catégorie n'est plus en fonction,\"\n \" mais demeure accessible.\"\n ),\n )\n\n approuver = fields.Boolean(\n string=\"Approuvé\",\n help=\"Permet d'approuver cette sous-catégorie.\",\n )\n\n categorie = fields.Many2one(\n comodel_name=\"organization.type.service.categorie\",\n string=\"Catégorie\",\n required=True,\n )\n\n sous_categorie_service = fields.Char(\n string=\"Sous-catégorie\",\n required=True,\n )\n\n type_service = fields.One2many(\n comodel_name=\"organization.type.service\",\n inverse_name=\"sous_categorie_id\",\n help=\"Type Service relation\",\n )\n\n def _compute_access_url(self):\n super(OrganizationTypeServiceSousCategorie, self)._compute_access_url()\n for organization_type_service_sous_categorie in self:\n organization_type_service_sous_categorie.access_url = (\n \"/my/organization_type_service_sous_categorie/%s\"\n % organization_type_service_sous_categorie.id\n )\n","repo_name":"TechnoLibre/odoo-code-generator-template","sub_path":"demo_mariadb_sql_example_1/models/organization_type_service_sous_categorie.py","file_name":"organization_type_service_sous_categorie.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"31382111477","text":"#Practise Set\r\n\r\n#Q.1 Write a python program to add two numbers\r\n\r\na=45\r\nb=55\r\nc=a+b\r\nprint(c)\r\n\r\n#Q.2 Write a Python Programm Program to find remindersnwhen a number is divided by 2\r\n\r\nd=a%b\r\nprint(d)\r\n\r\n#Q.3 Check the style of the variable assigned using input() function\r\n\r\nn1=input(\"Enter number you want:\")\r\nprint(\"You Entered :\",n1)\r\nn1=int(n1)\r\nprint(\"Type of Variable is\",type(n1))\r\n\r\n# Q.4 Use comparison operator to find out wheather a given variable 'a' is greater than 'b' or not\r\n#Take a=34 & b=80\r\n\r\na1=34\r\nb1=80\r\nprint(a1>b1)\r\nprint(b1>a1)\r\n\r\n# Q.5 Write a Python to find average of two numbers entered by the user\r\n\r\nnum1=input(\"Enter 1st numbers:\")\r\nnum2=input(\"Enter 2nd numbers:\")\r\nnum1=int(num1)\r\nnum2=int(num2)\r\navg=(num1+num2)/2\r\nprint(avg)\r\n\r\n#Q.6 Write a python program to calculate cube of number enterd by the user\r\n\r\nnum3=input(\"Enter Number You Want:\")\r\nnum3=int(num3)\r\nprint(num3*num3*num3)\r\n","repo_name":"Suraj5188/Python-Practise-Program-Topic-wise","sub_path":"7_Practise_set(Operators).py","file_name":"7_Practise_set(Operators).py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"15804230022","text":"#witのelsx'paste-rowdata'にwitの生データ.txtを貼り付ける\r\n#読み込み速度の観点から,読み込む列を限定しても良いかもしれない\r\nimport csv\r\nimport openpyxl as px\r\nfrom mymodule import hhmmss\r\n\r\nxxx_name = ['001','002','003','004','005','006','007','008','009','010','011','012','013','014','015','016','017','018','019','020','021','022','023','024','025','026','027','028','029','030']\r\n\r\nfor i in range(15,25):\r\n btemp_path = './Result/xlsx_template/1st_Bonaly_xxx.xlsx'\r\n bonxl_path = './Result/1st_Bonaly_' + xxx_name[i] + '.xlsx'\r\n hr_path = './Data/Bonaly_001-030/1st_Bonaly_' + xxx_name[i] + '/' + xxx_name[i] +'.csv'\r\n acl_path = './Data/Bonaly_001-030/1st_Bonaly_' + xxx_name[i] + '/' + xxx_name[i] +'_acl.csv'\r\n\r\n wb = px.load_workbook(btemp_path)\r\n wsH = wb['hrate']\r\n wsA = wb['accel']\r\n\r\n #グラフタイトル名の参照用セルに書き込み\r\n wb['hrate_graph']['H1'].value = '1次_心拍_' + xxx_name[i]\r\n\r\n #.csvの貼付け\r\n with open(hr_path, encoding='UTF-8') as file: #txtを開くときと同じ\r\n line1d = csv.reader(file) #readlineでも可能だが,csv.readerを使う方が勝手がよさそう\r\n line2d = [row for row in line1d] #二次元配列=リストのリストとして取得\r\n\r\n for i in range(len(line2d)): #このfileの行数分繰返し\r\n L_data = line2d[i] \r\n for j in range(len(L_data)): #各リストの要素数分だけ繰返し\r\n wsH.cell(row=i+1, column=j+1).value = line2d[i][j]\r\n\r\n #_acl.csvの貼付け\r\n with open(acl_path, encoding='UTF-8') as file: #txtを開くときと同じ\r\n line1D = csv.reader(file) #readlineでも可能だが,csv.readerを使う方が勝手がよさそう\r\n line2D = [row for row in line1D] #二次元配列=リストのリストとして取得\r\n\r\n for i in range(len(line2D)): #このfileの行数分繰返し\r\n L_data = line2D[i] \r\n for j in range(len(L_data)): #各リストの要素数分だけ繰返し\r\n wsA.cell(row=i+1, column=j+1).value = line2D[i][j]\r\n\r\n #'accel' A>G hh:mm:ss\r\n del line2D[0]\r\n for i in range(len(line2D)):\r\n wsA.cell(row=i+2, column=7).value = float(line2D[i][0])/(24*3600)\r\n\r\n #hrateのstart-timeに該当するセルをaccelから探し出し,その経過時刻をhrateのEventに記入,+2してfilldown\r\n fill_a = px.styles.PatternFill(patternType='solid', fgColor='FFDC00', bgColor='FFDC00') #赤っぽい色に塗りつぶし\r\n\r\n start_list = []\r\n\r\n for i in range(len(line2D)):\r\n hrate_value = str(hhmmss.main(wsH['A12'].value)) #hrateのhh:mm:ss表記のstart時刻をs表記に変換\r\n acl_value = str(wsA.cell(row=i+1, column=1).value) #aclのA列,s表記時刻を指定\r\n if hrate_value in acl_value: #aclの時刻(0.1s刻み)文字列にhrateの時刻(2s刻み)文字列が入っていればtrue\r\n wsA.cell(row=i+1, column=7).fill = fill_a\r\n start_list.append(i+1) #list\"line2D\"は要素を1つ消していて,行数が合わなくなるので+1\r\n\r\n wsA.cell(row=start_list[0], column=9).value = 0 #accelのI列に0を記入\r\n wsH.cell(row=12, column=2).value = wsA.cell(row=start_list[0], column=8).value #accelのH列「経過時間」をhrateのB12に記入\r\n\r\n for i in range(len(line2d)-12): \r\n wsH.cell(row=i+13, column=2).value = wsH.cell(row=i+12, column=2).value + 2 #hrateのB列を12行目から2ずつ足していく\r\n\r\n wb.save(bonxl_path)","repo_name":"Gidd-chopin1979/Nurse","sub_path":"bon1.py","file_name":"bon1.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72306364006","text":"from functools import reduce\nfrom dataclasses import dataclass\n\nfrom charm.toolbox.pairinggroup import PairingGroup, G1, G2, pair, extract_key\n\nfrom omnes_pro_uno.utils import prf, enc as enc_f, dec as dec_f\n\n\ndef prod(iter): return reduce(lambda a, b: a * b, iter)\ndef e(a, b): return pair(a, b)\n\n\n@dataclass\nclass Msk:\n gamma: int\n delta: int\n\n\n@dataclass\nclass Pk:\n gamma_g2: int\n delta_g2: int\n\n\n@dataclass\nclass Ak:\n k: int\n b: int\n\n\n@dataclass\nclass C:\n c1: int\n c2: int\n c30: (bytes, bytes)\n c31: (bytes, bytes)\n\n\nclass Ickae:\n def __init__(self, data_owner_num):\n self.n = data_owner_num\n self.group = PairingGroup('MNT224')\n self.g1 = self.group.random(G1)\n self.g2 = self.group.random(G2)\n self.gt = e(self.g1, self.g2)\n assert self.g1.initPP(), \"failed to init pre-computation table\"\n assert self.g2.initPP(), \"failed to init pre-computation table\"\n assert self.gt.initPP(), \"failed to init pre-computation table\"\n\n def setup(self):\n self.alpha = self.group.random()\n self.alpha_g1s = [self.g1 ** self.alpha ** i for i in range(1, 2 * self.n + 1)]\n self.alpha_g2s = [self.g2 ** self.alpha ** i for i in range(1, self.n + 1)]\n self.alpha_gt = self.gt ** self.alpha ** (self.n + 1)\n\n def keygen(self):\n gamma = self.group.random()\n delta = self.group.random()\n msk = Msk(gamma, delta)\n gamma_g2 = self.g2 ** gamma\n delta_g2 = self.g2 ** delta\n pk = Pk(gamma_g2, delta_g2)\n self.pk = pk\n return msk\n\n def extract(self, msk: Msk, s, id: bytes):\n b = prf(id, b'b')[0] & 0b1\n hb = self.group.hash(id + bytes([b]), G1)\n k = prod([self.alpha_g1s[self.n - 1 - j] for j in s]) ** msk.gamma * hb ** msk.delta\n ak = Ak(k, b)\n return ak\n\n def enc(self, i, id: bytes, m: bytes):\n r = self.group.random()\n c1 = self.g2 ** r\n c2 = (self.pk.gamma_g2 * self.alpha_g2s[i]) ** r\n h0 = self.group.hash(id + bytes([0]), G1)\n h1 = self.group.hash(id + bytes([1]), G1)\n c30 = enc_f(extract_key(self.alpha_gt ** r / e(h0, self.pk.delta_g2) ** r), m)\n c31 = enc_f(extract_key(self.alpha_gt ** r / e(h1, self.pk.delta_g2) ** r), m)\n c = C(c1, c2, c30, c31)\n return c\n\n def dec(self, ak: Ak, s, i, c: C):\n u = prod([e(self.alpha_g1s[self.n - 1 - j], c.c2) for j in s]) \\\n / e((ak.k * prod([self.alpha_g1s[self.n + i - j] for j in s if j != i])), c.c1)\n c3b = c.c30 if ak.b == 0 else c.c31\n return dec_f(extract_key(u), c3b[0], c3b[1])\n","repo_name":"myl7/omnes-pro-uno","sub_path":"omnes_pro_uno/ickae.py","file_name":"ickae.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16941258140","text":"import pandas as pd\nimport numpy as np\nkek = pd.read_csv(\"botresponses.csv\", na_values='thisisnotadrill')\nprint(kek)\nstimulus = []\nresponse = []\nwhatsaid = \"\"\nnum = 0\nusertoclone = 'Fakeuser#1234'\n#get responses\nfor i in range(1, int(kek.shape[0])): \n if kek.loc[i,'Author'] == usertoclone: \n if type(kek.loc[i-1,'Content']) is float:\n whatsaid += (str(kek.loc[i-1,'Attachments']))\n else: \n whatsaid += (str(kek.loc[i-1,'Content']))\n if whatsaid != \"\":\n stimulus.append(str(whatsaid))\n whatsaid = \"\"\n#get answer\nfor i in range(0, kek.shape[0]): \n if kek.loc[i,'Author'] == usertoclone: \n if type(kek.loc[i,'Content']) is float:\n whatsaid += (str(kek.loc[i,'Attachments']))\n else: \n whatsaid += (str(kek.loc[i,'Content']))\n if i < int(kek.shape[0]-1):\n if kek.loc[i+1,'Author'] == usertoclone: \n if type(kek.loc[i+1,'Content']) is float:\n whatsaid += (str(kek.loc[i+1,'Attachments']))\n else: \n whatsaid += (str(kek.loc[[i+1],'Content']))\n if whatsaid != \"\":\n response.append(str(whatsaid))\n whatsaid = \"\"\n\n#print(response)\nf = open('training-data.txt', 'a')\nh = open('training-stimuli.txt', 'a')\nj = open('training-responses.txt', 'a')\nif len(stimulus) > len(response): \n for i in range(len(response)):\n print(stimulus[i], file= f)\n print(response[i], file= f)\n print(stimulus[i], file= h)\n print(response[i], file= j)\nelse: \n for i in range(len(stimulus)):\n print(stimulus[i], file = f)\n print(response[i], file = f)\n print(stimulus[i], file = h)\n print(response[i], file = j)\n# if kek.loc[i-1,'Author'] == usertoclone:\n\n \n","repo_name":"isnes2000/el-boto","sub_path":"Aquire-data.py","file_name":"Aquire-data.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11364732120","text":"from app.models import db, Server, environment, SCHEMA\nfrom sqlalchemy.sql import text\n\ndef seed_servers():\n s1 = Server(\n name='League of Legends', user_id= 1, image= 'https://res.cloudinary.com/dmdiqj57t/image/upload/v1694896867/LoL_icon.svg_z0xivn.png', private=False\n )\n s2 = Server(\n name='Call of Duty', user_id= 1, image= 'https://res.cloudinary.com/dmdiqj57t/image/upload/v1694896865/Call-of-Duty-Logo-2010-2011_fqyi8h.png', private=False\n )\n s3 = Server(\n name='World of Warcraft', user_id= 2, image= 'https://res.cloudinary.com/dmdiqj57t/image/upload/v1694896942/world-of-warcraft-logo-png-transparent_ihmg9s.png', private=False\n )\n db.session.add(s1)\n db.session.add(s2)\n db.session.add(s3)\n db.session.commit()\n\ndef undo_servers():\n if environment == \"production\":\n db.session.execute(f\"TRUNCATE table {SCHEMA}.users RESTART IDENTITY CASCADE;\")\n else:\n db.session.execute(text(\"DELETE FROM servers\"))\n\n db.session.commit()\n","repo_name":"matt7xu/gamerCord","sub_path":"app/seeds/servers.py","file_name":"servers.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8128594867","text":"from bs4 import BeautifulSoup\nimport utils\nimport scraping\nimport dictwriter_csv\n\ndef get_product_url_for_category(category_url):\n links = []\n soup = utils.request(category_url)# r = requests.get(category_url)\n boutonNext = soup.find(\"li\", {\"class\": \"next\"})\n index = 1\n articles = soup.find_all('article', 'product_pod') \n for article in articles:\n a = article.find('a')\n link = a['href']\n url_article = link.replace('../../../', 'http://books.toscrape.com/catalogue/')\n links.append(url_article)\n while boutonNext is not None:\n index +=1\n category_url = category_url.replace(\"index.html\", \"page-\" + str(index) + '.html')\n soup = utils.request(category_url)# r = requests.get(category_url)\n articles = soup.findAll('article', 'product_pod') \n for article in articles:\n a = article.find('a')\n link = a['href']\n url_article = link.replace('../../../', 'http://books.toscrape.com/catalogue/')\n links.append(url_article)\n boutonNext = soup.find(\"li\", {\"class\": \"next\"})\n for link in links:\n soup = utils.request(link)#r = requests.get(link)\n book = scraping.scrap_book(link)\n file = dictwriter_csv.write_csv(book)\n return file\n\n","repo_name":"BernicheAurelie/Projet2","sub_path":"def_get_article_for_category_page1_2.py","file_name":"def_get_article_for_category_page1_2.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19790309769","text":"import sys\nimport pygame\nimport config\n\n\nFONT_SIZE = config.FONT_SIZE\n\n\nclass Game:\n FPS = 30\n WINDOW_SIZE = config.WINDOW_SIZE\n CELL_SIZE = config.CELL_SIZE\n LIVE_COLOR = config.LIVE_COLOR\n DEAD_COLOR = config.DEAD_COLOR\n play = False\n\n def __init__(self):\n pygame.init()\n self.font_pygame = pygame.font.SysFont('Arial', FONT_SIZE)\n self.surface = pygame.display.set_mode(\n (self.WINDOW_SIZE+300, self.WINDOW_SIZE))\n self.clock = pygame.time.Clock()\n\n def draw_cells(self, cells):\n for i in range(len(cells)):\n if cells[i].status:\n pygame.draw.rect(self.surface, self.LIVE_COLOR, (cells[i].x*self.CELL_SIZE,\n cells[i].y *\n self.CELL_SIZE,\n self.CELL_SIZE,\n self.CELL_SIZE))\n\n def draw_info(self, generation, live_cells, cells):\n info_sc = pygame.Surface((300, self.WINDOW_SIZE))\n info_sc.fill(self.DEAD_COLOR)\n text_gen = self.font_pygame.render(\n \"GENERATION: \" + str(generation), 1, self.LIVE_COLOR)\n text_count_cells = self.font_pygame.render(\n \"ALIVE CELLS: \" + str(live_cells), 1, self.LIVE_COLOR)\n text_count_cells1 = self.font_pygame.render(\n \"DEAD CELLS: \" + str(abs(len(cells)-live_cells)), 1, self.LIVE_COLOR)\n\n info_sc.blit(text_gen, (0, 0))\n info_sc.blit(text_count_cells, (0, FONT_SIZE))\n info_sc.blit(text_count_cells1, (0, FONT_SIZE*2))\n\n self.surface.blit(info_sc, (self.WINDOW_SIZE, 0))\n\n def check_events(self):\n for i in pygame.event.get():\n if i.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif i.type == pygame.KEYDOWN:\n if i.key == pygame.K_SPACE:\n return ['PLAY_UPDATE']\n elif i.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n pos = (pos[0] // self.CELL_SIZE, pos[1] // self.CELL_SIZE)\n return ['NEIGHBORS_UPDATE', pos]\n return ['']\n\n def display_update(self):\n pygame.display.update()\n","repo_name":"mikhailKhmel/CellularAutomaton","sub_path":"front.py","file_name":"front.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"21563902086","text":"#\n# csf 파일에서 process list를 추출한다.\n#\n# 210906 j 처음 만듦\n# 향후 :\n# - target file 이름에서 output file 이름을 생성한다.\n# - 실행시간이 너무 오래 걸린다. 단축하자\n\nimport sys\nfrom bs4 import BeautifulSoup\nimport time\n\nprint('---- process start ----')\nstart_time = time.time()\n\ntarget_file = './DKT_VINA_20210726a.csf'\noutput_file = './DKT_VINA_20210726a_process_list.txt'\n\nwith open(target_file, 'r') as f:\n bs_data = BeautifulSoup(f, 'lxml')\n\n# 반환된 값이 소문자로 변환됨, find_all 사용시 소문자로 검색\n# userprocesses = bs_data.find_all('userprocess')\nprocessnumes = bs_data.find_all('processnum')\nprocessnames = bs_data.find_all('processname')\nprocesstypes = bs_data.find_all('processtype') # idle - disalbe된 process\n\nwith open(output_file, 'w') as f:\n for i in range(len(processnumes)):\n # print(f'{processnumes[i].string}\\t {processtypes[i].string}\\t {processnames[i].string}')\n f.write(\n f'{processnumes[i].string}\\t {processtypes[i].string}\\t {processnames[i].string}\\n')\n\n\nend_time = time.time()\nprint('---- process end ----')\nprint('프로그램 수행 시간 (mSec): {}'.format((end_time-start_time)*1000))\n","repo_name":"jaegyo/utils","sub_path":"extract_process_list_from_csf_file.py","file_name":"extract_process_list_from_csf_file.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"33462936857","text":"import numpy as np\n\nfrom log_utils import *\nfrom plot_utils import *\n\nfrom sim import *\nfrom batch_sim import *\nfrom intersection_sim import IntersectionAttack\n\n# *********************************** IntersectionAttack ******************************* #\n\"\"\"\nTreat the participants as n bins.\nFor each observed participant, place a ball in its corresponding bin.\nTarget is revealed as soon as the height of a bin is greater than the rest.\n\"\"\"\nclass IntersectionAttack_wBatches(object):\n def __init__(self, env, n, target_i=0):\n self.env = env\n self.n = n\n self.target_i = target_i\n \n self.bin_l = [0 for _ in range(n)]\n self.secondMaxBinHeight = 0 # target_bin will always have the max height\n\n self.startTime = self.env.now\n self.D = None\n self.newBatchEvent = None\n self.wait = self.env.process(self.run())\n \n def __repr__(self):\n return 'IntersectionAttack_wBatches[n={}]'.format(self.n)\n\n def state(self):\n return 'target_bin= {}, secondMaxBinHeight= {}'.format(self.bin_l[self.target_i], self.secondMaxBinHeight)\n\n def get_candidate_l(self):\n l = [0]\n for i in range(1, n):\n if self.bin_l[i] == self.bin_l[self.target_i]:\n l.append(i)\n return l\n\n def batch(self, i_l):\n # slog(WARNING, self.env, self, \"batch\", i_l)\n for i in i_l:\n self.bin_l[i] += 1\n if i != self.target_i:\n if self.bin_l[i] > self.secondMaxBinHeight:\n self.secondMaxBinHeight = self.bin_l[i]\n \n self.newBatchEvent.succeed()\n \n def is_complete(self):\n return self.bin_l[self.target_i] > self.secondMaxBinHeight;\n \n def run(self):\n while 1:\n self.newBatchEvent = self.env.event()\n yield self.newBatchEvent\n self.newBatchEvent = None\n # slog(WARNING, self.env, self, \"current secondMaxBinHeight= {}\".format(self.secondMaxBinHeight), self.bin_l)\n if self.is_complete():\n self.D = self.env.now - self.startTime\n return\n \n# ************************************* Batch Mix ****************************************** #\nclass BatchMix(Mix):\n def __init__(self, env, _id, n, k, adversary=None):\n super().__init__(env, _id, n, k)\n self.adversary = adversary\n\n self.numBatchDeparturesWTarget = 0\n self.msgRecvedFromTarget = False\n\n def __repr__(self):\n return \"BatchMix[_id= {}, n={}, k={}]\".format(self._id, self.n, self.k)\n\n def put(self, m):\n slog(DEBUG, self.env, self, \"recved\", m)\n \n if self.adversary is not None and m.target:\n # self.adversary.msg_generated(m)\n # slog(WARNING, self.env, self, \"A msg received from target\", m)\n self.msgRecvedFromTarget = True\n\n m.entranceTime = self.env.now\n self.i_q_l[m.flowId].put(m)\n\n i_l = []\n for i, q in enumerate(self.i_q_l):\n if q.length():\n i_l.append(i)\n\n if len(i_l) >= self.k:\n for i in i_l:\n self.i_q_l[i].release()\n\n if self.adversary is not None and m.target:\n self.numBatchDeparturesWTarget += 1\n \n if self.adversary is not None and self.msgRecvedFromTarget:\n self.msgRecvedFromTarget = False\n # for i in i_l:\n # self.adversary.msg_delivered(Msg_wTarget(0, flowId=i))\n # slog(WARNING, self.env, self, \"Batch departure after a target\", i_l)\n self.adversary.batch(i_l)\n\n# ************************************* SamplekMix ****************************************** #\n## n servers with independent arrivals, every time a message arrives, k queues are selected at uniformly random and released.\nclass SamplekMix(BatchMix):\n def __init__(self, env, n, k, pd=None):\n super().__init__(env, _id, n, k)\n self.pd = pd if pd is not None else 1/n\n\n def __repr__(self):\n return 'SamplekMix[n={}, k={}]'.format(self.n, self.k)\n\n def put(self, p):\n slog(DEBUG, self.env, self, \"recved\", p)\n self.i_q_l[p.flow_id].put(p)\n\n l = list(range(self.n) )\n l.remove(p.flow_id)\n if np.random.uniform(0, 1) <= self.pd:\n i_l = [p.flow_id] + [l[i] for i in np.random.choice(self.n-1, self.k-1, replace=False) ]\n else:\n i_l = [l[i] for i in np.random.choice(self.n-1, self.k, replace=False) ]\n # print(\"i_l= {}\".format(i_l) )\n for i in i_l:\n self.i_q_l[i].release()\n\n# ************************************* True_SamplekMix ****************************************** #\n## n servers with independent arrivals.\n## Every time a message arrives, *and if all queues are non-empty*, then k queues are selected at uniformly random and released.\nclass True_SamplekMix(BatchMix):\n def __init__(self, env, _id, n, k):\n super().__init__(env, _id, n, k)\n\n def __repr__(self):\n return 'True_SamplekMix[n={}, k={}]'.format(self.n, self.k)\n\n def put(self, p):\n slog(DEBUG, self.env, self, \"recved\", p)\n self.i_q_l[p.flow_id].put(p)\n\n if any(q.length() == 0 for q in self.i_q_l):\n slog(DEBUG, self.env, self, \"There is an empty q, won't release any. Received:\", p)\n return\n\n i_l = np.random.choice(self.n, self.k, replace=False)\n slog(DEBUG, self.env, self, \"will release q's:\", i_l)\n for i in i_l:\n self.i_q_l[i].release()\n\n# ############################## Random ############################### #\ndef sim_N_random(n, k):\n if k == n:\n log(ERROR, \"Intersection attack will never deanonymize; k = n = {}\".format(k))\n return\n\n target_bin = 0\n bin_l = [0 for _ in range(n-1)]\n\n secondMaxBinHeight = 0 # target_bin will always have the max height\n def update_second_max(m):\n nonlocal secondMaxBinHeight\n if m > secondMaxBinHeight:\n secondMaxBinHeight = m\n\n range_l = list(range(n-1))\n step = 0\n while target_bin == secondMaxBinHeight:\n target_bin += 1\n for o in random.sample(range_l, k-1):\n bin_l[o] += 1\n update_second_max(bin_l[o])\n step += 1\n # print(\"target_bin= {}, secondMaxBinHeight= {}\".format(target_bin, secondMaxBinHeight) )\n return step\n\ndef sim_EN_random(n, k, numSimRuns=1000):\n if k == n:\n log(ERROR, \"Intersection attack will never deanonymize; k = n = {}\".format(k))\n return\n return np.mean([sim_N_random(n, k) for _ in range(numSimRuns)])\n\n# ############################# Batch mix ############################# #\ndef sim_N_D_T_BatchMix(n, k, targetRate, recvRate, Delta):\n env = simpy.Environment()\n # adv = IntersectionAttack(env, n, m=0, M=0.01, target_i=0)\n adv = IntersectionAttack_wBatches(env, n)\n mix = BatchMix(env, 'bm', n, k, adv)\n if Delta:\n nw = Network(env, 'nw', delayRV=TPareto(Delta/10, Delta, 2), out=mix)\n mg = MsgGen_wTarget(env, 'mg', [recvRate]*n, targetPercRate=targetRate/recvRate, out=nw)\n else:\n mg = MsgGen_wTarget(env, 'mg', [recvRate]*n, targetPercRate=targetRate/recvRate, out=mix)\n env.run(until=adv.wait)\n return mix.numBatchDeparturesWTarget, adv.D, mix.ET()\n\ndef sim_BatchMix(n, k, targetRate, recvRate, Delta, numSimRuns=1000):\n if k == n:\n log(ERROR, \"Intersection attack will never finish; k = n = {}\".format(k))\n return\n \n N_total, D_total, T_total, T_max = 0, 0, 0, 0\n for _ in range(numSimRuns):\n N, D, T = sim_N_D_T_BatchMix(n, k, targetRate, recvRate, Delta)\n N_total += N\n D_total += D\n T_total += T\n T_max = max(T_max, T)\n return {\n 'EN': N_total/numSimRuns,\n 'ED': D_total/numSimRuns,\n 'ET': T_total/numSimRuns,\n 'T_max': T_max}\n","repo_name":"mfatihaktas/anonymity-mixes","sub_path":"batch_sim.py","file_name":"batch_sim.py","file_ext":"py","file_size_in_byte":7267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25846481622","text":"#Bansari Shah\r\n#ICS3U0\r\n#Waterloo J2; 2002\r\n#21 Oct 2020\r\n\r\nwhile True:\r\n word = input()\r\n\r\n if word == \"quit!\":\r\n break\r\n\r\n if (len(word) > 4) and (word.endswith(\"or\")):\r\n word = word.replace(\"or\", \"our\")\r\n \r\n print(word)\r\n\r\n \r\n","repo_name":"bxnsari2312/Small-Games","sub_path":"SIMPLE-GAME_OR_APPLICATIONS/Waterloo J2; 2002; AmeriCanadian.py","file_name":"Waterloo J2; 2002; AmeriCanadian.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32960622312","text":"import json\nimport pandas as pd\nfrom pymongo import MongoClient\nimport firebase_admin\nfrom firebase_admin import credentials\n\ndef startup():\n with open('config.json') as json_file:\n config = json.load(json_file)\n\n cluster = MongoClient(config['config']['mongodb']['uri'])\n db = cluster[config['config']['mongodb']['cluster']]\n distributors = db[config['config']['mongodb']['collection']]\n sales_contacts = db['SalesContacts']\n\n cred = credentials.Certificate(config['config']['firebase'])\n firebase_admin.initialize_app(cred)\n\n df = pd.read_excel(config['config']['excel'], header=0, index_col=None)\n\n config['config']['mongodb']['uri']\n\n return distributors, sales_contacts, cred, df\n\n\n","repo_name":"MrSteelTitan/Account_Management_Skript","sub_path":"startup.py","file_name":"startup.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"45292300628","text":"from django.urls import path\nfrom administration import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path(\"governing_body\", views.governing_body, name=\"Governing_Body\"),\n path(\"pta\", views.pta_page, name=\"PTA\"),\n path(\"office/\", views.office_page, name=\"Office\"),\n path('iqac', views.iqac_page, name='iqac'),\n path('anti_ragging_cell', views.anti_ragging_cell_page, name='anti_ragging_cell'),\n path('sc_st_committee_cell', views.sc_st_monitoring_cell_page, name='sc_st_committee_cell'),\n path('examination_cell', views.examination_cell_page, name='examination_cell'),\n path('organogram',views.organogram_page,name='organogram'),\n path('mandatory_disclosure',views.mandatory_disclosure_page,name='mandatory_disclosure'),\n path('academic_administration',views.academic_administration_page,name='academic_administration'),\n path(\"grivence//\",views.grivence_redressal_page,name=\"grivence_redressal\"),\n\n]\n\nif settings.DEBUG: \n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"cce-websitecoordinator/cce-website","sub_path":"administration/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"73434885604","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n\t\tdef maxPathSum(self, root: TreeNode) -> int:\n\t\t\tself.maxvalue = float('-inf')\n\t\t\tdef dfs(node):\n\t\t\t\tif node is None:\n\t\t\t\t\treturn 0\n\t\t\t\tleft = dfs(node.left)\n\t\t\t\tright = dfs(node.right)\n\t\t\t\trootval = max(left,right)\n\t\t\t\tself.maxvalue = max(self.maxvalue, node.val+left+right)\n\t\t\t\tif rootval + node.val >= 0 :\n\t\t\t\t\tself.maxvalue = max(self.maxvalue, rootval + node.val)\n\t\t\t\t\treturn rootval + node.val\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\t\t\tdfs(root)\n\t\t\treturn self.maxvalue","repo_name":"bharat787/DSA","sub_path":"LC/maxPathSUm.py","file_name":"maxPathSUm.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19369228021","text":"import os.path\nimport sys\nfrom pathlib import Path\n\n\nclass PGSPaletteGrayscaler:\n\n def __init__(self, pgs_bytes):\n self.segment_type_palette = int('0x14', 16)\n self.header_size = 13\n self.pgs_bytes = pgs_bytes\n\n def __find_next_segment_by_magic_number(self, current_segment_location):\n for i in range(current_segment_location+2, len(self.pgs_bytes)):\n if self.pgs_bytes[i:i + 2] == b'PG':\n return i\n raise Exception(f'panic - next segment was not found, starting from byte {current_segment_location}')\n\n def __next_segment(self):\n i = 0\n while i < len(self.pgs_bytes):\n if self.pgs_bytes[i:i + 2] != b'PG':\n raise Exception('panic')\n segment_size = self.header_size + int.from_bytes(self.pgs_bytes[i + 11:i + 13], byteorder='big')\n if i+segment_size < len(self.pgs_bytes) and self.pgs_bytes[i + segment_size:i + segment_size + 2] != b'PG':\n next_segment_magic_number_location = self.__find_next_segment_by_magic_number(i)\n print(f'WARNING: declared segment size was {segment_size}, but it seems to be {next_segment_magic_number_location - i} at byte {i}')\n segment_size = next_segment_magic_number_location - i\n segment = self.pgs_bytes[i:i + segment_size]\n segment_type = self.pgs_bytes[i + 10]\n i += segment_size\n yield segment_type, segment\n\n @staticmethod\n def __transform_segment(segment, brighten_factor=0.7):\n modified_segment = segment[:15]\n for palette in range(15, len(segment), 5):\n id_y_cr_cb_alpha = bytearray(segment[palette:palette+5])\n id_y_cr_cb_alpha[2:4] = [128, 128] # changing color to grayscale in YCrCb color space\n if id_y_cr_cb_alpha[1] < 128:\n id_y_cr_cb_alpha[1] = int(id_y_cr_cb_alpha[1] * brighten_factor)\n else:\n id_y_cr_cb_alpha[1] = int(255 - (255 - id_y_cr_cb_alpha[1]) * brighten_factor)\n modified_segment += id_y_cr_cb_alpha\n if len(segment) != len(modified_segment):\n raise Exception('panic - different size of modified segment')\n return modified_segment\n\n def grayscale(self):\n modified_pgs = bytes()\n for segment_type, segment in self.__next_segment():\n if segment_type == self.segment_type_palette:\n modified_pgs += self.__transform_segment(segment)\n else:\n modified_pgs += segment\n if len(self.pgs_bytes) != len(modified_pgs):\n raise Exception('panic - different size of pgs_bytes')\n return modified_pgs\n\n\ndef modify_subtitles(files, suffix='_bw'):\n for file in files:\n name_file_src, name_file_ext = os.path.splitext(os.path.basename(file))\n file_path_src = os.path.join(os.path.dirname(file), name_file_src + name_file_ext)\n file_path_dst = os.path.join(os.path.dirname(file), name_file_src + suffix + name_file_ext)\n with open(file_path_src, 'rb') as pgs_src:\n magic_number = pgs_src.read(2)\n pgs_src.seek(0, 0)\n if magic_number == b'PG':\n with open(file_path_dst, 'wb') as pgs_dst:\n print(f'PGS: {name_file_src+name_file_ext}')\n grayscaler = PGSPaletteGrayscaler(pgs_src.read())\n try:\n pgs_dst.write(grayscaler.grayscale())\n except Exception as e:\n print(f'ERROR: {str(e)}')\n else:\n print(f'Not a PGS file: {name_file_src+name_file_ext}')\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n for arg in sys.argv[1:]:\n if '*' in os.path.basename(arg):\n files = [x for x in Path(os.path.dirname(arg)).glob(os.path.basename(arg))]\n else:\n files = [arg]\n modify_subtitles(files)\n else:\n print('no input given')\n","repo_name":"SuddenSelect/pgs-recolor","sub_path":"pgs-recolor.py","file_name":"pgs-recolor.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36557147111","text":"from .spectral import geostwind\n\ndef pseudo_spectral_wind(history, grid, params, verbose, **kwargs):\n \"\"\"Wrap the spectral methods to fit the architecture.\n \n :param history: Current history of state\n :type history: :class:`History` object\n :param grid: Spatial grid of the simulation\n :type grid: :class:`Grid` object:\n :param params: Dictionary of usefull parameters\n :type params: dictionary \n :param verbose: verbose, defaults to 0\n :type verbose: int, optional\n \"\"\"\n assert history.size > 0\n current_state = history.state_list[-1]\n \n ut, vt = geostwind(grid.Lx, grid.Ly, current_state.vrs['theta_t'], params, z=0, verbose=verbose)\n us, vs = geostwind(grid.Lx, grid.Ly, current_state.vrs['theta_t'], params, z=params['z_star'], verbose=verbose)\n \n current_state.vrs['ut'] = ut\n current_state.vrs['vt'] = vt\n current_state.vrs['us'] = us\n current_state.vrs['vs'] = vs","repo_name":"pablo-richard/PROFITROLL-Master","sub_path":"profitroll/methods/pseudo_spectral_wind.py","file_name":"pseudo_spectral_wind.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"4462404629","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 15 16:41:11 2020\r\n\r\n@author: AwwTim\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nimport matplotlib\r\n\r\n\r\nresolution = 20\r\n\r\ndef writeArr(ys):\r\n arr = np.empty([100,100])\r\n index = 0\r\n for y in range(0,100,5):\r\n for x in range(0,100,5):\r\n #print(ys[index])\r\n for yy in range(5):\r\n for xx in range(5):\r\n #print(y+yy, x+xx)\r\n arr[y+yy][x+xx] = ys[index]\r\n index += 1\r\n return arr\r\n\r\ndef xorAI():\r\n inputs = tf.keras.Input(shape=(2))\r\n x = tf.keras.layers.Dense(16, activation=tf.nn.sigmoid)(inputs)\r\n outputs = tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)(x)\r\n model = tf.keras.Model(inputs=inputs, outputs=outputs)\r\n optimizer = \"adam\"\r\n model.compile(optimizer = optimizer, loss = \"mean_squared_error\",\r\n )\r\n #model.summary()\r\n \r\n return model\r\n\r\nmodel = xorAI() \r\n \r\ntrain_xs =np.array([\r\n [0,0],\r\n [1,0],\r\n [0,1],\r\n [1,1]\r\n ], \"float32\")\r\n\r\ntrain_ys =np.array([\r\n [0],\r\n [1],\r\n [1],\r\n [0]\r\n ], \"float32\")\r\n\r\ncols = 400 // (resolution)\r\nrows = 400 // (resolution)\r\n\r\nxs = []\r\nfor i in range(cols):\r\n for j in range(rows):\r\n x1 = i/cols\r\n x2 = j/rows\r\n xs.append([x1,x2])\r\n\r\n#Train and make predictions each epoch\r\nfig =plt.figure()\r\ncollection = []#np.empty([100,100,100])\r\nfor i in range(5000):\r\n print(i)\r\n model.fit(train_xs, train_ys, shuffle = True, epochs = 1, verbose = None)\r\n ys = model.predict(xs)\r\n imarr = writeArr(ys)\r\n im = plt.imshow(imarr, animated = True)\r\n collection.append([im]) \r\n \r\n#Create ans Save the Animation\r\nani = animation.ArtistAnimation(fig, collection, interval=50, blit=True,\r\n repeat_delay=1000)\r\nani.save('xor.htm')\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":"sunjaeyoon/CodingTrainInspirations","sub_path":"XORtf.py","file_name":"XORtf.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28873665135","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on %(date)s\n\n@author: %(username)s\n\"\"\"\nimport os\nimport sys\nimport argparse\nimport logging\nimport json\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction import text \nimport pandas as pd\n\n\n# set argument parser\nparser = argparse.ArgumentParser(description='Feature extraction.')\nparser.add_argument(\"-outdir\", type = str,\n help = \"Directory to store output of this file.\",\n default = \"data/friends\")\nparser.add_argument(\"-csvdir\", type = str,\n help = \"Directory to store output of this file.\",\n default = \"data/csv\")\nparser.add_argument(\"-v\", \"--verbose\", \n help = \"Set logging level to DEBUG.\",\n action = \"store_true\")\nargs = parser.parse_args()\n\n# set logging\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.ERROR)\nif args.verbose:\n log.setLevel(logging.DEBUG)\nloghandler = logging.StreamHandler(sys.stderr)\nloghandler.setFormatter(logging.Formatter(\"[%(asctime)s %(message)s]\"))\nlog.addHandler(loghandler)\n\n\n\"\"\" STEP 1 \"\"\"\ndef scrape_userobj(user_obj):\n \"\"\"\n Scrapes relevant information from user_obj,\n ----\n user_obj (dict, user obj dictionary)\n \"\"\"\n \n try:\n id_ = user_obj['id_str']\n except:\n id_ = None\n try:\n name_ = user_obj['name']\n except:\n name_ = None\n# try:\n# screenname_ = user_obj['screenname']\n# except:\n# screenname_ = None\n try:\n location_ = user_obj['location']\n except:\n location_ = None\n try:\n description_ = user_obj['description']\n except:\n description_ = None\n try:\n verified_ = user_obj['verified']\n created_at = user_obj['created_at']\n except:\n verified_ = created_at = None\n try:\n url_ = user_obj['url']\n except:\n url_ = None\n try:\n followers = user_obj['followers_count']\n except:\n followers = None\n \n dict_ = { \"id\": id_,\n \"name\": name_,\n# \"screenname\": screenname_,\n \"location\": location_,\n \"description\": description_,\n \"verified\": verified_,\n \"created_at\": created_at,\n \"url\": url_, \n \"n_followers\": followers}\n \n log.info(dict_['name'])\n return dict_\n \n\n\"\"\" STEP 2 \"\"\"\ndef bag_of_words(corpus):\n \"\"\"\n Perform bag-of-words analysis: \n 1. get top 50 terms in the corpus;\n 2. get keyword frequencies.\n ----\n corpus (list of strings)\n \"\"\"\n \n # Fit CountVectorizer\n stop_words = text.ENGLISH_STOP_WORDS.union(\n ('twitter', 'email', 'https', 'com', 'politics', 'gmail', 'account',\n 'tweets', 'views', 'american', 'state', 'opinions'))\n vectorizer = CountVectorizer(stop_words = stop_words, \n analyzer = \"word\")\n X = vectorizer.fit_transform(corpus)\n features = vectorizer.get_feature_names()\n log.info(\"Output of bag of words: {} \\n {}\".format(type(X), X.shape))\n \n # get top 50 terms\n Xcolsum = np.array(X.sum(axis = 0))[0] # sum along axis and convert to list\n asc_ordered_Xindex = Xcolsum.argsort()\n ordered_Xindex = asc_ordered_Xindex[::-1]\n with open(os.path.join(args.outdir, \"top_50terms.txt\"), \"w\") as t:\n for i in ordered_Xindex[:50]: # save to file\n log.info(\"Top 50 terms, # {}: {}\".format(Xcolsum[i], features[i]))\n t.write(\"{}, {}\".format(Xcolsum[i], features[i]) + os.linesep)\n t.close()\n \n # count keyword frequencies\n keywords = [\"house\", \"senator\", \"rep.\", \"sen\", \"governor\", \"candidate\",\n \"Democratic\",\"Republican\", \"campaign\", \n \"(R)\", \"(D)\"]\n keyfeatures = [i for i in keywords if i in features]\n keywordcount = dict(zip(keyfeatures, [features.index(w) for w in keyfeatures]))\n with open(os.path.join(args.outdir, \"count_keywords.txt\"), \"w\") as t:\n for k, v in keywordcount.items():\n t.write(\"# of accounts mentioning '{}': {}\".format(k, Xcolsum[v]) +\n os.linesep)\n log.info(\"{}: {}\\n\".format(k, Xcolsum[v]))\n t.close()\n \n\n # save result to csv file\n df = pd.DataFrame(X.todense(), columns = features)\n df.to_csv(os.path.join(args.csvdir, \"friends_bagofwords.csv\"))\n \n\nif __name__ == \"__main__\":\n \n # Build corpus and create pandas dataframe from scrape_userobj\n corpus = []\n df = pd.DataFrame()\n for i in range(4):\n scraped = {}\n filename = os.path.join(args.outdir, \"friends_lookup_\" + str(i) + \".json\")\n with open(filename, \"r\") as j:\n users = json.load(j)\n for user in users:\n dict_ = scrape_userobj(user)\n row = pd.DataFrame(dict_, index = [0])\n df = pd.concat([df, row], axis = 0, ignore_index = True)\n scraped.update({dict_['id']: dict_.pop('id')})\n corpus.append(dict_['description'])\n filename = filename.replace(\"lookup\", \"scraped\")\n with open(filename, \"w\") as j:\n json.dump(scraped, j)\n \n log.info(df.shape)\n df.to_csv(os.path.join(args.csvdir, \"friends_of_PTTP.csv\"))\n \n # Conduct bag of words on corpus\n bag_of_words(corpus)\n \n \n sys.exit()","repo_name":"amikami102/pizza_to_the_polls","sub_path":"script/friends_of_PTTP/bagofwords.py","file_name":"bagofwords.py","file_ext":"py","file_size_in_byte":5383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11607326987","text":"#\n# @lc app=leetcode id=283 lang=python\n#\n# [283] Move Zeroes\n#\n\n# @lc code=start\nclass Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n\n i = 0\n for j in range(1, len(nums)):\n if nums[i] != 0:\n i += 1\n elif nums[j] != 0:\n nums[i], nums[j] = nums[j], nums[i]\n i += 1\n\n# @lc code=end\n","repo_name":"aryanjain28/Striver","sub_path":"easy_leetCode/283.move-zeroes.py","file_name":"283.move-zeroes.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24341179046","text":"import pandas as pd\nimport scikit_posthocs as sp\n\nfrom scipy import stats\n\n\ndef run_tests(df):\n strategies = ['browserbite', 'crosscheck', 'browserninja1', 'browserninja2']\n algs = ['dt', 'randomforest', 'svm', 'nn']\n\n is_parametric = True\n\n for strategy in strategies:\n for alg in algs:\n r = stats.shapiro(df.loc[:, '%s-%s' % (strategy, alg)])\n print('Shapiro wilk in %s with %s - p-value=%f' % (strategy, alg, r.pvalue))\n if r.pvalue < 0.05:\n is_parametric = False\n\n params = df.to_numpy().tolist()\n if is_parametric:\n anova_result = stats.f_oneway(*params)\n print('One-Way Anova F=%f and p-value=%f' %\n (anova_result.statistic, anova_result.pvalue))\n tukey_result = stats.tukey_hsd(*params)\n matrix = tukey_result.pvalue.tolist()\n print('Posthoc Nemenyi pairwise comparisons test for unreplicated blocked data')\n cache = {}\n for i, row in enumerate(matrix):\n for j, pvalue in enumerate(row):\n if ('%d-%d' % (j, i)) in cache: continue\n cache['%d-%d' % (i, j)] = True\n if pvalue < 0.05:\n mean_i = df.loc[:, df.columns[i]].mean()\n mean_j = df.loc[:, df.columns[j]].mean()\n bigger_index = i if mean_i > mean_j else j\n smaller_index = i if mean_i < mean_j else j\n\n print(' - %s (%f) and %s (%f) with p-value=%f' %\n (df.columns[bigger_index], df.loc[:, df.columns[bigger_index]].mean(),\n df.columns[smaller_index], df.loc[:, df.columns[smaller_index]].mean(),\n pvalue))\n else:\n friedman_result = stats.friedmanchisquare(*params)\n print('Friedman test for repeated samples F=%f and p-value=%f' %\n (friedman_result.statistic, friedman_result.pvalue))\n nemeyi_result = sp.posthoc_nemenyi_friedman(df)\n\n print('Posthoc Nemenyi pairwise comparisons test for unreplicated blocked data')\n cache = {}\n for col in nemeyi_result.columns.tolist():\n for row in nemeyi_result.index.tolist():\n if ('%s-%s' % (row, col)) in cache: continue\n cache['%s-%s' % (col, row)] = True\n pvalue = nemeyi_result.loc[row, col]\n if pvalue < 0.05:\n mean_i = df.loc[:, col].mean()\n mean_j = df.loc[:, row].mean()\n bigger_index = col if mean_i > mean_j else row\n smaller_index = col if mean_i < mean_j else row\n\n print(' - %s (%f) and %s (%f) with p-value=%f' %\n (bigger_index, df.loc[:, bigger_index].mean(),\n smaller_index, df.loc[:, smaller_index].mean(), pvalue))\n\n\nmetrics = ['precision', 'recall', 'fscore']\nincompatibilities = ['external', 'internal']\n\nfor inc in incompatibilities:\n for met in metrics:\n print('''\n*******************************\n %s - %s\n*******************************\n''' % (met, inc))\n df = pd.read_csv('../%s-%s.csv' % (met, inc), index_col=0)\n df.columns = [ col.replace('-%s' % (inc), '') for col in df.columns ]\n df = df.reindex(df.mean().sort_values(ascending=False).index, axis=1)\n run_tests(df)\n\n\n\n\n","repo_name":"watinha/xbi-detection","sub_path":"results/statistics/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"42422654269","text":"# PR2018-09-02\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.core.mail import send_mail\nfrom django.db.models.functions import Lower\nfrom django.db.models import Q\nfrom django.db import connection\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nfrom django.utils.decorators import method_decorator\n#PR2022-02-13 was ugettext_lazy as _, replaced by: gettext_lazy as _\nfrom django.utils.translation import activate, gettext, pgettext_lazy, gettext_lazy as _\nfrom django.views.generic import View\n\nfrom accounts import views as acc_view\nfrom accounts import permits as acc_prm\n\nfrom awpr import menus as awpr_menu, excel as grd_exc\nfrom awpr import constants as c\nfrom awpr import settings as s\nfrom awpr import validators as av\nfrom awpr import functions as af\nfrom awpr import library as awpr_lib\nfrom awpr import logs as awpr_log\n\nfrom grades import views as grd_view\nfrom grades import validators as grad_val\nfrom grades import calc_results as calc_res\n\nfrom subjects import models as subj_mod\nfrom subjects import views as subj_vw\nfrom schools import models as sch_mod\nfrom students import models as stud_mod\nfrom students import functions as stud_fnc\nfrom students import validators as stud_val\n\nfrom subjects import views as sj_vw\n\n\n# PR2019-01-04 https://stackoverflow.com/questions/19734724/django-is-not-json-serializable-when-using-ugettext-lazy\nfrom django.utils.functional import Promise\nfrom django.utils.encoding import force_text\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nimport json\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass LazyEncoder(DjangoJSONEncoder):\n def default(self, obj):\n if isinstance(obj, Promise):\n return force_text(obj)\n return super(LazyEncoder, self).default(obj)\n\n\n# ======== Student =====================================\n\n@method_decorator([login_required], name='dispatch')\nclass StudentListView(View): # PR2018-09-02 PR2020-10-27 PR2021-03-25 PR2023-04-05\n\n def get(self, request):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(\" ===== StudentListView =====\")\n\n# - get user_lang\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get headerbar parameters\n page = 'page_student'\n params = awpr_menu.get_headerbar_param(request, page)\n if logging_on:\n logger.debug(\" params: \" + str(params))\n\n# - save this page in Usersetting, so at next login this page will open. Used in LoggedIn\n # PR2021-06-22 moved to get_headerbar_param\n\n return render(request, 'students.html', params)\n\n\n# ======== StudentsubjectListView =======\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectListView(View): # PR2020-09-29 PR2021-03-25 PR2022-07-05\n\n def get(self, request):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(\" ===== StudentsubjectListView =====\")\n\n# - get user_lang\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - for btn text 'Proof of Knowledge' or 'Proof of Exemption'\n is_evelex_school = False\n selected_dict = acc_prm.get_usersetting_dict(c.KEY_SELECTED_PK, request)\n sel_examyear_pk = selected_dict.get(c.KEY_SEL_EXAMYEAR_PK) if selected_dict else None\n if request.user:\n sel_school = sch_mod.School.objects.get_or_none(\n base=request.user.schoolbase,\n examyear_id=sel_examyear_pk\n )\n if sel_school:\n is_evelex_school = sel_school.iseveningschool or sel_school.islexschool\n\n if is_evelex_school:\n pok_pex_str = _('Proof of exemption')\n else:\n pok_pex_str = _('Proof of knowledge')\n\n# - get headerbar parameters\n page = 'page_studsubj'\n param = {'pok_pex': pok_pex_str}\n params = awpr_menu.get_headerbar_param(request, page, param)\n return render(request, 'studentsubjects.html', params)\n\n\n# ======== OrderlistsListView =======\n@method_decorator([login_required], name='dispatch')\nclass OrderlistsListView(View): # PR2021-07-04\n\n def get(self, request):\n #logger.debug(\" ===== OrderlistsListView =====\")\n\n# - get user_lang\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get headerbar parameters\n page = 'page_orderlist'\n param = {'display_school': False, 'display_department': False}\n params = awpr_menu.get_headerbar_param(request, page, param)\n\n return render(request, 'orderlists.html', params)\n# - end of OrderlistsListView\n\n\n#/////////////////////////////////////////////////////////////////\ndef create_student_rows(request, sel_examyear, sel_schoolbase, sel_depbase, append_dict, show_deleted=False, student_pk_list=None):\n # --- create rows of all students of this examyear / school PR2020-10-27 PR2022-01-03 PR2022-02-15 PR2023-01-11\n # - show only students that are not tobedeleted\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ----- create_student_rows -----')\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_schoolbase: ' + str(sel_schoolbase))\n logger.debug(' sel_depbase: ' + str(sel_depbase))\n logger.debug(' show_deleted: ' + str(show_deleted))\n\n sql_keys = {'ey_id': sel_examyear.pk if sel_examyear else None,\n 'sb_id': sel_schoolbase.pk if sel_schoolbase else None,\n 'db_id': sel_depbase.pk if sel_depbase else None}\n sql_clause_arr = []\n\n # sel_schoolbase is already checked on allowed schoolbases in function download_setting / get_settings_schoolbase / get_sel_schoolbase_instance\n # sel_depbase is already checked on allowed depbases in function download_setting / get_settings_departmentbase / get_sel_depbase_instance\n\n sel_school = sch_mod.School.objects.get_or_none(\n examyear=sel_examyear,\n base=sel_schoolbase\n )\n sel_department = sch_mod.Department.objects.get_or_none(\n examyear=sel_examyear,\n base=sel_depbase\n )\n level_is_required = sel_department.level_req if sel_department else False\n\n if logging_on:\n logger.debug(' ----------')\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug(' level_is_required: ' + str(level_is_required))\n\n# - get allowed_sections_dict from userallowed\n allowed_sections_dict = acc_prm.get_userallowed_sections_dict_from_request(request)\n # allowed_sections_dict: {'13': {'1': {'-9': []}, '2': {'-9': []}}} key is schoolbase_pk / depbase_pk / lvlbase_pk\n\n# - get allowed_schoolbase_dict from allowed_sections_dict\n allowed_schoolbase_dict, allowed_depbases_pk_arr = acc_prm.get_userallowed_schoolbase_dict_depbases_pk_arr(\n userallowed_sections_dict=allowed_sections_dict,\n sel_schoolbase_pk=sel_schoolbase.pk if sel_schoolbase else None\n )\n # allowed_schoolbase_dict: {'1': {'-9': []}, '2': {'-9': []}} key is depbase_pk / lvlbase_pk\n\n# - get allowed_depbase_dict from allowed_schoolbase_dict\n allowed_depbase_dict, allowed_lvlbase_pk_arr = acc_prm.get_userallowed_depbase_dict_lvlbases_pk_arr(\n allowed_schoolbase_dict=allowed_schoolbase_dict,\n sel_depbase_pk=sel_depbase.pk if sel_depbase else None\n )\n # allowed_depbase_dict: {'-9': []}\n\n if logging_on:\n logger.debug(' ----------')\n logger.debug(' allowed_sections_dict: ' + str(allowed_sections_dict))\n logger.debug(' allowed_schoolbase_dict: ' + str(allowed_schoolbase_dict))\n logger.debug(' allowed_depbase_dict: ' + str(allowed_depbase_dict))\n\n sel_lvlbase_pk_arr = []\n\n# - get selected_pk_dict from usersettings\n selected_pk_dict = acc_prm.get_usersetting_dict(c.KEY_SELECTED_PK, request)\n\n if level_is_required:\n\n# - get saved_lvlbase_pk of req_usr\n saved_lvlbase_pk = selected_pk_dict.get(c.KEY_SEL_LVLBASE_PK)\n if logging_on:\n logger.debug(' ----------')\n logger.debug(' saved_lvlbase_pk: ' + str(saved_lvlbase_pk) + ' ' + str(type(saved_lvlbase_pk)))\n\n# - filter only the saved_lvlbase_pk if exists and allowed\n # if sel_lvlbase_pk_arr is empty all lvlbases are allowed\n if not saved_lvlbase_pk or saved_lvlbase_pk == '-9':\n if allowed_depbase_dict:\n # if '-9' in allowed_depbase_dict: all levels are allowed, no filter\n # else: add all allowed lvlbase_pk to sel_lvlbase_pk_arr\n if '-9' not in allowed_depbase_dict:\n for lvlbase_pk_str in allowed_depbase_dict:\n sel_lvlbase_pk_arr.append(int(lvlbase_pk_str))\n #else:\n # - all lvlbases are allowed if allowed_depbase_dict is empty\n\n else:\n if allowed_depbase_dict:\n if str(saved_lvlbase_pk) in allowed_depbase_dict or \\\n '-9' in allowed_depbase_dict:\n sel_lvlbase_pk_arr.append(saved_lvlbase_pk)\n else:\n sel_lvlbase_pk_arr.append(saved_lvlbase_pk)\n\n if logging_on:\n logger.debug(' sel_lvlbase_pk_arr: ' + str(sel_lvlbase_pk_arr) + ' ' + str(type(sel_lvlbase_pk_arr)))\n\n# - create lvlbase_clause\n lvlbase_clause = None\n if sel_lvlbase_pk_arr:\n if len(sel_lvlbase_pk_arr) == 1:\n sql_keys['lvlbase_pk'] = sel_lvlbase_pk_arr[0]\n lvlbase_clause = \"lvl.base_id = %(lvlbase_pk)s::INT\"\n else:\n sql_keys['lvlbase_pk_arr'] = sel_lvlbase_pk_arr\n lvlbase_clause = \"lvl.base_id IN (SELECT UNNEST(%(lvlbase_pk_arr)s::INT[]))\"\n sql_clause_arr.append(lvlbase_clause)\n\n if logging_on:\n logger.debug(' lvlbase_clause: ' + str(lvlbase_clause))\n\n #allowed_depbase_dict = acc_view.get_requsr_allowed_lvlbases_dict(\n # allowed_depbases_dict=allowed_depbases_dict,\n # sel_depbase_pk=sel_depbase.pk if sel_depbase else None\n #)\n\n # - get selected sctbase_pk of req_usr\n #PR2023-09-06 debug: Dorothee Inspection: had selected sector = n&G, but that is a Havo Vwo sector.\n # when Vsbo selected 'all sectors' are showing in sbr, but sel_sectorbase_pk has value 9.\n # therefore no students are showing.\n # solution: add check if sel_debbase is in field depbases\n saved_sctbase_pk = selected_pk_dict.get(c.KEY_SEL_SCTBASE_PK)\n if saved_sctbase_pk and saved_sctbase_pk != -9:\n sel_sector = subj_mod.Sector.objects.get_or_none(pk=saved_sctbase_pk)\n if sel_sector and sel_sector.depbases:\n db_wrapped = \";\" + sel_sector.depbases + \";\"\n db_lookup = \";\" + str(sel_depbase.pk) + \";\"\n if db_lookup in db_wrapped:\n sql_clause_arr.append(''.join((\"(sct.base_id = \", str(saved_sctbase_pk), \"::INT)\")))\n\n sql_clause = 'AND ' + ' AND '.join(sql_clause_arr) if sql_clause_arr else ''\n\n student_rows = []\n error_dict = {} # PR2021-11-17 new way of err msg, like in TSA\n\n if sel_examyear and sel_schoolbase and sel_depbase:\n try:\n\n sql_studsubj_agg = \"SELECT student_id FROM students_studentsubject WHERE NOT deleted AND subj_published_id IS NOT NULL GROUP BY student_id\"\n\n sql_list = [\"WITH studsubj AS (\", sql_studsubj_agg, \")\",\n \"SELECT st.id, st.base_id, st.school_id AS s_id,\",\n \"school.locked AS s_locked, ey.locked AS ey_locked, \",\n \"st.department_id AS dep_id, st.level_id AS lvl_id, st.sector_id AS sct_id, st.scheme_id,\",\n \"dep.base_id AS depbase_id, lvl.base_id AS lvlbase_id, sct.base_id AS sctbase_id, \"\n \"dep.abbrev AS dep_abbrev, db.code AS db_code,\",\n \"dep.level_req AS lvl_req, lvl.abbrev AS lvl_abbrev,\",\n \"dep.sector_req AS sct_req, sct.abbrev AS sct_abbrev, scheme.name AS scheme_name,\",\n \"dep.has_profiel AS dep_has_profiel, sct.abbrev AS sct_abbrev,\",\n \"CONCAT('student_', st.id::TEXT) AS mapid,\",\n\n \"CONCAT_WS (' ', st.prefix, CONCAT(st.lastname, ','), st.firstname) AS fullname,\",\n \"st.lastname, st.firstname, st.prefix, st.gender,\",\n \"st.idnumber, st.birthdate, st.birthcountry, st.birthcity,\",\n\n \"st.classname, st.examnumber, st.regnumber, st.diplomanumber, st.gradelistnumber,\",\n \"st.extrafacilities, st.iseveningstudent, st.islexstudent,\",\n \"st.bis_exam, st.partial_exam,\",\n\n \"st.linked, st.notlinked, st.sr_count, st.reex_count, st.reex03_count, st.withdrawn,\",\n \"st.gl_ce_avg, st.gl_combi_avg, st.gl_final_avg,\",\n\n \"st.gl_status, st.gl_auth1by_id, st.gl_modifiedat,\",\n \"gl_auth1.last_name AS gl_auth1_username,\",\n\n \"st.ep01_result, st.ep02_result, st.result, st.result_status, st.result_info, st.deleted, st.tobedeleted,\",\n\n \"CASE WHEN studsubj.student_id IS NOT NULL THEN TRUE ELSE FALSE END AS has_submitted_subjects,\",\n\n \"st.modifiedby_id, st.modifiedat, au.last_name AS modby_username\",\n\n \"FROM students_student AS st\",\n \"INNER JOIN schools_school AS school ON (school.id = st.school_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = school.examyear_id)\",\n \"LEFT JOIN schools_department AS dep ON (dep.id = st.department_id)\",\n \"INNER JOIN schools_departmentbase AS db ON (db.id = dep.base_id)\",\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = st.level_id)\",\n \"LEFT JOIN subjects_sector AS sct ON (sct.id = st.sector_id)\",\n \"LEFT JOIN subjects_scheme AS scheme ON (scheme.id = st.scheme_id)\",\n\n \"LEFT JOIN accounts_user AS au ON (au.id = st.modifiedby_id)\",\n\n \"LEFT JOIN accounts_user AS gl_auth1 ON (gl_auth1.id = st.gl_auth1by_id)\",\n\n \"LEFT JOIN studsubj ON (studsubj.student_id = st.id)\",\n\n \"WHERE school.examyear_id = %(ey_id)s::INT\",\n \"AND school.base_id = %(sb_id)s::INT\",\n \"AND dep.base_id = %(db_id)s::INT\",\n\n # PR2023-01-14 tobedeleted records must also be shown\n # was: \"AND NOT st.tobedeleted\"\n\n ]\n\n # show deleted students only when SBR 'Show all' is clicked\n if not show_deleted:\n sql_list.append('AND NOT st.deleted')\n\n if student_pk_list:\n if len(student_pk_list) == 1:\n sql_list.extend((\"AND st.id = \", str(student_pk_list[0]), \"::INT\"))\n else:\n sql_list.extend((\"AND st.id IN (SELECT UNNEST(ARRAY\", str(student_pk_list), \"::INT[]))\"))\n else:\n # sql_clause = acc_view.get_userfilter_allowed_school_dep_lvl_sct(request)\n if logging_on:\n logger.debug(' sql_clause: ' + str(sql_clause))\n if sql_clause:\n sql_list.append(sql_clause)\n\n # order by id necessary to make sure that lookup function on client gets the right row\n sql_list.append(\"ORDER BY st.id\")\n\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n student_rows = af.dictfetchall(cursor)\n\n if logging_on:\n logger.debug(' sql: ' + str(sql))\n # logger.debug(' student_rows: ' + str(student_rows))\n # logger.debug('connection.queries: ' + str(connection.queries))\n\n # - add lastname_firstname_initials to rows\n if student_rows:\n for row in student_rows:\n first_name = row.get('firstname')\n last_name = row.get('lastname')\n prefix = row.get('prefix')\n row['name_first_init'] = stud_fnc.get_lastname_firstname_initials(last_name, first_name, prefix)\n\n # - add messages to student_row\n if student_pk_list and len(student_pk_list) == 1 and student_rows and append_dict:\n # when updating single student student_pk_list has only 1 row\n row = student_rows[0]\n if row:\n for key, value in append_dict.items():\n row[key] = value\n\n except Exception as e:\n # - return msg_err when instance not created\n # msg format: [ { class: \"border_bg_invalid\", header: 'Update this', msg_html: \"An eror occurred.\" }]\n logger.error(getattr(e, 'message', str(e)))\n #   add 4 'hard' spaces\n msg_html = '
'.join((\n str(_('An error occurred while loading list of candidates')) + ':',\n ' ' + str(e) + ''\n ))\n error_dict = {'class': 'border_bg_invalid', 'msg_html': msg_html}\n\n return student_rows, error_dict\n# --- end of create_student_rows\n\n\ndef create_check_birthcountry_rows(sel_examyear, sel_schoolbase, sel_depbase):\n # --- check_birthcountry rows of all students of this examyear / school PR2022-06-20\n # - show only students that are not tobedeleted\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- create_check_birthcountry_rows -----')\n\n log_list = []\n msg_html = None\n is_sxm = sel_examyear.country.abbrev == 'Sxm'\n birthcountry_regex = '%maarten%' if is_sxm else 'cura%'\n country = 'Sint Maarten' if is_sxm else 'Curaçao'\n\n # PR2023-06-02 change requested by Pien van DIjk email 31-05-23\n # Het lijkt me het beste dat we aanhouden wat Kranchi zegt.\n # Maar omdat het niet zoveel uitmaakt op het diploma moet het maar zo dan.\n default_birthplace = c.BIRTHPLACE_DEFAULT_SXM if is_sxm else c.BIRTHPLACE_DEFAULT_CUR\n\n if logging_on:\n logger.debug('birthcountry_regex: ' + str(birthcountry_regex))\n\n if sel_examyear and sel_schoolbase and sel_depbase:\n try:\n if logging_on:\n logger.debug('sel_examyear: ' + str(sel_examyear))\n logger.debug('sel_schoolbase: ' + str(sel_schoolbase))\n logger.debug('sel_depbase: ' + str(sel_depbase))\n\n sql_keys = {'ey_id': sel_examyear.pk if sel_examyear else None,\n 'sb_id': sel_schoolbase.pk if sel_schoolbase else None,\n 'db_id': sel_depbase.pk if sel_depbase else None,\n 'regex': birthcountry_regex\n }\n sql_list = [\"SELECT st.lastname, st.firstname, st.prefix,\",\n \"st.birthcountry, COALESCE(st.birthcity, '-') AS birthcity, st.birthdate\",\n \"FROM students_student AS st\",\n \"INNER JOIN schools_school AS sch ON (sch.id = st.school_id)\",\n \"LEFT JOIN schools_department AS dep ON (dep.id = st.department_id)\",\n\n \"WHERE sch.base_id = %(sb_id)s::INT\",\n \"AND sch.examyear_id = %(ey_id)s::INT\",\n \"AND dep.base_id = %(db_id)s::INT\",\n\n \"AND st.birthdate < '2010-10-10'::DATE\",\n # PR2022-06-21 debug: got error 'argument formats can't be mixed' when using: \" ILIKE '\" + birthcountry_regex + \"'\"\n # solved biij changing to %(regex)s::TEXT, without apostroph\n # see https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries\n \"AND TRIM(st.birthcountry) ILIKE %(regex)s::TEXT\", # ILIKE is case insensitive\n #\"AND (POSITION('\" + birthcountry + \"' IN LOWER(st.birthcountry)) > 0)\",\n \"AND NOT st.tobedeleted\",\n \"ORDER BY st.lastname, st.firstname\"]\n sql = ' '.join(sql_list)\n if logging_on:\n logger.debug('sql: ' + str(sql))\n\n count_wrong_birthcountry = 0\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = cursor.fetchall()\n if rows:\n count_wrong_birthcountry = len(rows)\n\n if count_wrong_birthcountry:\n count_str = str(_(\"There is 1 candidate\") if count_wrong_birthcountry == 1 else _(\"There are %(count)s candidates\") % {'count': str(count_wrong_birthcountry)})\n # PR2023-07-13 was: is_are_str = str(_('is') if count_wrong_birthcountry == 1 else _('are'))\n is_are_str = get_is_are_text(count_wrong_birthcountry)\n this_these_str = str(_(\"This candidate\").lower() if count_wrong_birthcountry == 1 else _('these candidates'))\n msg_html = '
'.join((\"

\" + count_str + \\\n str(_(\" with country of birth: '%(cpt)s', who %(is_are)s born before October 10, 2010.\") \\\n % {'cpt': country, 'is_are': is_are_str}),\n str(_(\"This is not correct, because before that date, the country was 'Nederlandse Antillen', not '%(cpt)s'.\") % {'cpt': country}),\n str(_(\"Click 'OK' to change the country of birth of %(this_these)s to 'Nederlandse Antillen' and the place of birth to '%(cpt)s' \") \\\n % {'this_these': this_these_str, 'cpt': default_birthplace}),\n str(_(\"The list of candidates, whose country of birth will be changed, has been downloaded.\")) + '

'\n ))\n log_list.append(str(_(\"List of candidates, whose country of birth will be changed to 'Nederlandse Antillen'\")))\n log_list.append(' ')\n log_list.append(' '.join((\n (str(_('Candidate')).upper() + c.STRING_SPACE_30)[:30],\n (str(_('Country of birth')).upper() + c.STRING_SPACE_20)[:20],\n (str(_('Place of birth')).upper() + c.STRING_SPACE_20)[:20],\n str(_('Birthdate')).upper()\n )))\n for row in rows:\n lastname_firstname_initial = stud_fnc.get_lastname_firstname_initials(row[0], row[1], row[2])\n log_list.append(' '.join((\n (lastname_firstname_initial + c.STRING_SPACE_30)[:30],\n (row[3] + c.STRING_SPACE_20)[:20],\n (row[4] + c.STRING_SPACE_20)[:20],\n str(row[5])\n )))\n if logging_on:\n logger.debug('log_list: ' + str(log_list))\n # logger.debug('connection.queries: ' + str(connection.queries))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n return log_list, msg_html\n# --- end of create_check_birthcountry_rows\n\n\ndef change_birthcountry(sel_examyear, sel_schoolbase, sel_depbase, request):\n # --- change birthcountry in all students of this examyear / school PR2022-06-20\n # - show only students that are not tobedeleted\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- change_birthcountry -----')\n\n msg_dict = {}\n is_sxm = sel_examyear.country.abbrev == 'Sxm'\n birthcountry_regex = '%maarten%' if is_sxm else 'cura%'\n country = 'Sint Maarten' if is_sxm else 'Curaçao'\n\n # PR2023-06-02 change requested by Pien van DIjk email 31-05-23\n # Het lijkt me het beste dat we aanhouden wat Kranchi zegt.\n # Maar omdat het niet zoveel uitmaakt op het diploma moet het maar zo dan.\n default_birthplace = c.BIRTHPLACE_DEFAULT_SXM if is_sxm else c.BIRTHPLACE_DEFAULT_CUR\n\n\n modifiedby_pk_str = str(request.user.pk)\n modifiedat_str = str(timezone.now())\n\n if logging_on:\n logger.debug('birthcountry_regex: ' + str(birthcountry_regex))\n\n if sel_examyear and sel_schoolbase and sel_depbase:\n try:\n if logging_on:\n logger.debug('sel_examyear: ' + str(sel_examyear))\n logger.debug('sel_schoolbase: ' + str(sel_schoolbase))\n logger.debug('sel_depbase: ' + str(sel_depbase))\n\n sql_keys = {'ey_id': sel_examyear.pk if sel_examyear else None,\n 'sb_id': sel_schoolbase.pk if sel_schoolbase else None,\n 'db_id': sel_depbase.pk if sel_depbase else None,\n 'regex': birthcountry_regex\n }\n\n # - select students with country 'Sint Maarten' or 'Curacao'\n sub_sql_list = [\"SELECT st.id AS stud_id\",\n \"FROM students_student AS st\",\n \"INNER JOIN schools_school AS sch ON (sch.id = st.school_id)\",\n \"LEFT JOIN schools_department AS dep ON (dep.id = st.department_id)\",\n\n \"WHERE sch.base_id = %(sb_id)s::INT\",\n \"AND sch.examyear_id = %(ey_id)s::INT\",\n \"AND dep.base_id = %(db_id)s::INT\",\n\n \"AND st.birthdate < '2010-10-10'::DATE\",\n \"AND TRIM(st.birthcountry) ILIKE %(regex)s::TEXT\", # ILIKE is case insensitive\n\n \"AND NOT st.tobedeleted\"]\n sub_sql = ' '.join(sub_sql_list)\n # - update birthcountry and birthcity in student\n sql_list = [\n \"WITH sub_sql AS (\", sub_sql, \")\",\n \"UPDATE students_student AS stud\",\n \"SET birthcountry = 'Nederlandse Antillen', birthcity = '\" + default_birthplace + \"',\",\n \"modifiedby_id = \", modifiedby_pk_str, \", modifiedat = '\", modifiedat_str, \"'\",\n\n \"FROM sub_sql\",\n \"WHERE stud.id = sub_sql.stud_id\",\n \"RETURNING stud.id\"\n ]\n\n sql = ' '.join(sql_list)\n if logging_on:\n logger.debug('sql: ' + str(sql))\n record_count = 0\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = cursor.fetchall()\n if rows:\n updated_count = len(rows)\n # logger.debug('connection.queries: ' + str(connection.queries))\n if logging_on:\n logger.debug('rows: ' + str(rows))\n\n count_str = str(_(\"1 candidate\") if updated_count == 1 else _(\"%(count)s candidates\") % {'count': updated_count})\n\n class_str = 'border_bg_valid' if updated_count else 'border_bg_invalid'\n msg_html = str(_(\"The birth country of %(cnt)s have been changed to 'Nederlandse Antillen'.\") % {'cnt': count_str})\n msg_dict = {'class': class_str, 'msg_html': msg_html}\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n return msg_dict\n# --- end of change_birthcountry\n\n\n#/////////////////////////////////////////////////////////////////\ndef create_results_per_school_rows(request, sel_examyear, sel_schoolbase):\n # --- create rows of all students of this examyear / school PR2020-10-27 PR2022-01-03 PR2022-02-15\n # - show only students that are not tobedeleted\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- create_results_per_school_rows -----')\n\n result_dict = {}\n result_rows = []\n error_dict = {} # PR2021-11-17 new way of err msg, like in TSA\n\n if sel_examyear:\n try:\n\n if logging_on:\n logger.debug('sel_examyear: ' + str(sel_examyear))\n logger.debug('sel_schoolbase: ' + str(sel_schoolbase))\n\n sql_keys = {'ey_id': sel_examyear.pk, 'sb_id': sel_schoolbase.pk}\n if logging_on:\n logger.debug('sql_keys: ' + str(sql_keys))\n\n subsql_list = [\"SELECT st.id AS stud_id,\",\n \"(LOWER(st.gender) = 'm')::INT AS m,\",\n \"(LOWER(st.gender) = 'v')::INT AS v,\",\n # partal exam and tobedeleted are filtered out PR2023-06-14 debug: also st.deleted added\n # return withdrawn if result is withdrawn\n \"CASE WHEN result = 4 THEN 4 ELSE\",\n # return passed if any result is passed, also when reex_count > 0\n \"CASE WHEN st.ep01_result = 1 OR ep02_result = 1 OR result = 1 THEN 1 ELSE\",\n # return failed if result is failed\n \"CASE WHEN (result = 2) THEN 2 ELSE\",\n # return reex if reex_count > 0\n # return noo result if no reex\n \"CASE WHEN st.reex_count > 0 OR st.reex03_count > 0 THEN 3 ELSE 0 END\",\n \"END\",\n \"END\",\n \"END AS resultcalc\",\n \"FROM students_student AS st\",\n \"WHERE NOT st.partial_exam\",\n \"AND NOT st.deleted AND NOT st.tobedeleted\"\n ]\n sub_sql = ' '.join(subsql_list)\n\n sql_list = [\"WITH subsql AS (\" + sub_sql + \")\",\n \"SELECT db.id AS db_id, db.code AS db_code, dep.name AS dep_name,\",\n \"lvlbase.id AS lvlbase_id, lvlbase.code AS lvl_code, lvl.name AS lvl_name,\",\n \"sb.id AS sb_id, sch.name as sch_name, sb.code as sb_code,\",\n\n \"SUM(subsql.m) AS c_m,\",\n \"SUM(subsql.v) AS c_v,\",\n \"COUNT(*) AS c_t,\",\n\n \"SUM((subsql.resultcalc = 1 AND subsql.m = 1)::INT) AS r_p_m,\",\n \"SUM((subsql.resultcalc = 1 AND subsql.v = 1)::INT) AS r_p_v,\",\n \"SUM((subsql.resultcalc = 1)::INT) AS r_p_t,\",\n\n \"SUM((subsql.resultcalc = 2 AND subsql.m = 1)::INT) AS r_f_m,\",\n \"SUM((subsql.resultcalc = 2 AND subsql.v = 1)::INT) AS r_f_v,\",\n \"SUM((subsql.resultcalc = 2)::INT) AS r_f_t,\",\n\n \"SUM((subsql.resultcalc = 3 AND subsql.m = 1)::INT) AS r_r_m,\",\n \"SUM((subsql.resultcalc = 3 AND subsql.v = 1)::INT) AS r_r_v,\",\n \"SUM((subsql.resultcalc = 3)::INT) AS r_r_t,\",\n\n \"SUM((subsql.resultcalc = 4 AND subsql.m = 1)::INT) AS r_w_m,\",\n \"SUM((subsql.resultcalc = 4 AND subsql.v = 1)::INT) AS r_w_v,\",\n \"SUM((subsql.resultcalc = 4)::INT) AS r_w_t,\",\n\n \"SUM((subsql.resultcalc = 0 AND subsql.m = 1)::INT) AS r_n_m,\",\n \"SUM((subsql.resultcalc = 0 AND subsql.v = 1)::INT) AS r_n_v,\",\n \"SUM((subsql.resultcalc = 0)::INT) AS r_n_t\",\n\n \"FROM students_student AS st\",\n \"INNER JOIN subsql ON (subsql.stud_id = st.id)\",\n\n \"INNER JOIN schools_school AS sch ON (sch.id = st.school_id)\",\n \"INNER JOIN schools_schoolbase AS sb ON (sb.id = sch.base_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = sch.examyear_id)\",\n \"INNER JOIN schools_department AS dep ON (dep.id = st.department_id)\",\n \"INNER JOIN schools_departmentbase AS db ON (db.id = dep.base_id)\",\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = st.level_id)\",\n \"LEFT JOIN subjects_levelbase AS lvlbase ON (lvlbase.id = lvl.base_id)\",\n\n \"WHERE sch.examyear_id = %(ey_id)s::INT\"]\n\n if request.user.is_role_school:\n sql_keys['sb_id'] = sel_schoolbase.pk if sel_schoolbase else None\n sql_list.append('AND sb.id = %(sb_id)s::INT')\n\n sql_list.append(\"GROUP BY db.id, dep.sequence, db.code, dep.name, lvlbase.id, lvl.sequence, lvlbase.code, lvl.name, sb.id, sb.code, sch.name\")\n sql_list.append(\"ORDER BY dep.sequence, lvl.sequence, sb.code\")\n\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n result_rows = af.dictfetchall(cursor)\n\n if logging_on:\n for row in result_rows:\n logger.debug('row: ' + str(row))\n\n except Exception as e:\n # - return msg_err when instance not created\n # msg format: [ { class: \"border_bg_invalid\", header: 'Update this', msg_html: \"An eror occurred.\" }]\n logger.error(getattr(e, 'message', str(e)))\n #   add 4 'hard' spaces\n msg_html = '
'.join((str(_('An error occurred')) + ':',' ' + str(e) + ''))\n error_dict = {'class': 'border_bg_invalid', 'msg_html': msg_html}\n\n return result_rows, error_dict\n# --- end of create_results_per_school_rows\n\n\ndef create_result_dict_per_school(request, sel_examyear, sel_schoolbase):\n # --- create rows of all students of this examyear / school PR2022-06-17\n # - show only students that are not tobedeleted\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- create_result_dict_per_school -----')\n\n result_dict = {}\n\n result_rows, error_dict = create_results_per_school_rows(request, sel_examyear, sel_schoolbase)\n\n if result_rows:\n for row in result_rows:\n db_id = row.get('db_id') or 0\n lvlbase_id = row.get('lvlbase_id') or 0\n sb_id = row.get('sb_id') or 0\n\n if db_id not in result_dict:\n result_dict[db_id] = {'db_id': db_id, 'db_code': row.get('db_code'),\n 'dep_name': row.get('dep_name')}\n db_dict = result_dict[db_id]\n\n if lvlbase_id not in db_dict:\n db_dict[lvlbase_id] = {'lvlbase_id': lvlbase_id, 'lvl_code': row.get('lvl_code'),\n 'lvl_name': row.get('lvl_name')}\n lvl_dict = db_dict[lvlbase_id]\n\n if sb_id not in lvl_dict:\n lvl_dict[sb_id] = row\n\n if logging_on:\n logger.debug('result_dict: ' + str(result_dict))\n\n \"\"\"\n result_dict: \n {1: {'db_id': 1, 'db_code': 'Vsbo', 'dep_name': 'Voorbereidend Secundair Beroepsonderwijs', \n 4: {'lvlbase_id': 4, 'lvl_code': 'TKL', 'lvl_name': 'Theoretisch Kadergerichte Leerweg', \n 13: {'db_id': 1, 'db_code': 'Vsbo', 'dep_name': 'Voorbereidend Secundair Beroepsonderwijs', 'lvlbase_id': 4, 'lvl_code': 'TKL', 'lvl_name': 'Theoretisch Kadergerichte Leerweg', 'sb_id': 13, 'sch_name': 'Abel Tasman College', 'sb_code': 'CUR13', 'c_m': 4, 'c_v': 6, 'c_t': 10, 'r_p_m': 3, 'r_p_v': 6, 'r_p_t': 9, 'r_f_m': 0, 'r_f_v': 0, 'r_f_t': 0, 'r_r_m': 0, 'r_r_v': 0, 'r_r_t': 0, 'r_w_m': 0, 'r_w_v': 0, 'r_w_t': 0, 'r_n_m': 1, 'r_n_v': 0, 'r_n_t': 1}}}, \n 2: {'db_id': 2, 'db_code': 'Havo', 'dep_name': 'Hoger Algemeen Voortgezet Onderwijs', \n 0: {'lvlbase_id': 0, 'lvl_code': None, 'lvl_name': None, \n 13: {'db_id': 2, 'db_code': 'Havo', 'dep_name': 'Hoger Algemeen Voortgezet Onderwijs', 'lvlbase_id': None, 'lvl_code': None, 'lvl_name': None, 'sb_id': 13, 'sch_name': 'Abel Tasman College', 'sb_code': 'CUR13', 'c_m': 12, 'c_v': 9, 'c_t': 21, 'r_p_m': 7, 'r_p_v': 6, 'r_p_t': 13, 'r_f_m': 0, 'r_f_v': 2, 'r_f_t': 2, 'r_r_m': 5, 'r_r_v': 1, 'r_r_t': 6, 'r_w_m': 0, 'r_w_v': 0, 'r_w_t': 0, 'r_n_m': 0, 'r_n_v': 0, 'r_n_t': 0}}}, \n 3: {'db_id': 3, 'db_code': 'Vwo', 'dep_name': 'Voorbereidend Wetenschappelijk Onderwijs', \n 0: {'lvlbase_id': 0, 'lvl_code': None, 'lvl_name': None, \n 13: {'db_id': 3, 'db_code': 'Vwo', 'dep_name': 'Voorbereidend Wetenschappelijk Onderwijs', 'lvlbase_id': None, 'lvl_code': None, 'lvl_name': None, 'sb_id': 13, 'sch_name': 'Abel Tasman College', 'sb_code': 'CUR13', 'c_m': 2, 'c_v': 5, 'c_t': 7, 'r_p_m': 1, 'r_p_v': 3, 'r_p_t': 4, 'r_f_m': 0, 'r_f_v': 0, 'r_f_t': 0, 'r_r_m': 1, 'r_r_v': 2, 'r_r_t': 3, 'r_w_m': 0, 'r_w_v': 0, 'r_w_t': 0, 'r_n_m': 0, 'r_n_v': 0, 'r_n_t': 0}}}}\n \"\"\"\n\n return result_dict, error_dict\n# --- end of create_result_dict_per_school\n#/////////////////////////////////////////////////////////////////\n\n\n@method_decorator([login_required], name='dispatch')\nclass ValidateCompositionView(View): # PR2022-08-25\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= ValidateCompositionView ============= ')\n\n update_wrap = {}\n msg_list = []\n\n # - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get permit, only inspectorate kan set validation\n has_permit = request.user.role == c.ROLE_032_INSP and acc_prm.get_permit_crud_of_this_page('page_studsubj', request)\n\n if not has_permit:\n msg_txt = gettext(\"You don't have permission %(cpt)s.\") % {'cpt': gettext('to validate the composition of subjects')}\n msg_html = ''.join((\"
\", msg_txt, \"
\"))\n else:\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n \"\"\"\n upload_dict: {\n 'student_pk': 2132,\n 'subj_dispensation': True\n } \n \"\"\"\n# - get variables\n student_pk = upload_dict.get('student_pk')\n subj_dispensation = upload_dict.get('subj_dispensation') or False\n\n if logging_on:\n logger.debug('upload_dict: ' + str(upload_dict))\n\n updated_rows = []\n error_list = []\n append_dict = {}\n\n# ----- get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - country is locked,\n # - examyear is not found, not published or locked\n # - school is not found, not same_school, or locked\n # - department is not found, not in user allowed depbase or not in school_depbase\n #sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n # acc_view.get_selected_ey_school_dep_lvl_from_usersetting(\n # request=request,\n # skip_same_school_clause=True\n # )\n selected_pk_dict = acc_prm.get_selected_pk_dict_of_user_instance(request.user)\n sel_examyear = acc_prm.get_sel_examyear_from_selected_pk_dict(selected_pk_dict)\n sel_schoolbase = acc_prm.get_sel_schoolbase_from_selected_pk_dict(selected_pk_dict)\n sel_depbase = acc_prm.get_sel_depbase_from_selected_pk_dict(selected_pk_dict)\n if logging_on:\n logger.debug(' student_pk: ' + str(student_pk))\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_schoolbase: ' + str(sel_schoolbase))\n logger.debug(' sel_depbase: ' + str(sel_depbase))\n\n# +++ get existing student\n student_instance = stud_mod.Student.objects.get_or_none(\n id=student_pk,\n school__examyear=sel_examyear\n )\n if logging_on:\n logger.debug('..... student_instance: ' + str(student_instance))\n\n# - set subj_dispensation\n if student_instance:\n setattr(student_instance, 'subj_dispensation', subj_dispensation)\n setattr(student_instance, 'subj_disp_modifiedby', request.user)\n setattr(student_instance, 'subj_disp_modifiedat', timezone.now())\n\n # don't update student modifiedby (don't use 'save(reuqest=request)')\n student_instance.save()\n\n if logging_on:\n logger.debug(' student_instance.saved: ' + str(student_instance))\n\n# - get studsubj_rows of this student, create list of pk's\n #studsubj_pk_list = []\n #sql_keys = {'stud_id': student_instance.pk}\n #sql_list = [\"SELECT studsubj.id\",\n # \"FROM students_studentsubject AS studsubj\",\n # \"WHERE studsubj.student_id = %(stud_id)s::INT\",\n # \"AND NOT studsubj.deleted\"\n # ]\n #sql = ' '.join(sql_list)\n\n #with connection.cursor() as cursor:\n # cursor.execute(sql, sql_keys)\n # for row in cursor.fetchall():\n # studsubj_pk_list.append(row[0])\n\n #if logging_on:\n # logger.debug(' studsubj_pk_list: ' + str(studsubj_pk_list))\n\n# - get studentsubject_rows of this student, return to client\n updated_studsubj_rows = create_studentsubject_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_schoolbase,\n sel_depbase=sel_depbase,\n append_dict={},\n request=request,\n student_pk=student_instance.pk\n )\n update_wrap['updated_studsubj_rows'] = updated_studsubj_rows\n if logging_on:\n for row in updated_studsubj_rows:\n logger.debug(' row: ' + str(row))\n\n if logging_on:\n logger.debug(' msg_list: ' + str(msg_list))\n\n# - addd messages to update_wrap\n if msg_list:\n header_txt = gettext(\"Validate subject composition\")\n msg_html = '
'.join(msg_list)\n\n if logging_on:\n logger.debug(' header_txt: ' + str(header_txt))\n logger.debug(' msg_html: ' + str(msg_html))\n update_wrap['messages'] = [{'class': \"border_bg_invalid\", 'header': header_txt, 'msg_html': msg_html}]\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of ValidateCompositionView\n\n\n@method_decorator([login_required], name='dispatch')\nclass ClusterUploadView(View): # PR2022-01-06 PR2023-05-31\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= ClusterUploadView ============= ')\n\n######## private functions #################\n\n def create_cluster(subject, cluster_pk, cluster_name):\n # --- create cluster # PR2022-01-06 PR2022-12-23\n if logging_on:\n logger.debug(' ----- create_cluster -----')\n\n err_list = []\n new_cluster_pk = None\n if sel_school and sel_department and subject:\n # - get value of 'cluster_name'\n new_value = cluster_name.strip() if cluster_name else None\n if logging_on:\n logger.debug('new_value: ' + str(new_value))\n\n try:\n # - validate length of cluster name\n msg_err = av.validate_notblank_maxlength(new_value, c.MAX_LENGTH_KEY, _('The cluster name'))\n if msg_err:\n err_list.append(msg_err)\n else:\n # - validate if cluster already exists\n name_exists = subj_mod.Cluster.objects.filter(\n school=sel_school,\n department=sel_department,\n name__iexact=new_value\n )\n if name_exists:\n err_list.append(str(_(\"%(cpt)s '%(val)s' already exists.\") \\\n % {'cpt': _('Cluster name'), 'val': new_value}))\n else:\n # - create and save cluster\n cluster = subj_mod.Cluster(\n school=sel_school,\n department=sel_department,\n subject=subject,\n name=new_value\n )\n cluster.save(request=request)\n\n if cluster and cluster.pk:\n new_cluster_pk = cluster.pk\n # mapped_cluster_pk_dict: {'new_1': 296}\n mapped_cluster_pk_dict[cluster_pk] = new_cluster_pk\n if logging_on:\n logger.debug('new cluster: ' + str(cluster))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n err_list.append(str(_('An error occurred.')))\n err_list.append(\n str(_(\"%(cpt)s '%(val)s' could not be added.\") % {'cpt': str(_('Cluster')),\n 'val': new_value}))\n\n return err_list, new_cluster_pk\n # - end of create_cluster\n\n def delete_cluster_instance(cluster_instance):\n # --- delete cluster # PR2022-01-06 PR2022-08-08 PR2022-12-24\n if logging_on and False:\n logger.debug(' ----- delete_cluster_instance -----')\n logger.debug(' cluster_instance: ' + str(cluster_instance))\n\n msg_html = None\n this_txt = _(\"Cluster '%(val)s' \") % {'val': cluster_instance.name}\n\n updated_studsubj_pk_list = []\n\n # - create list of studsubj_pk with thos cluster, to update the stdsubj rows in client\n if cluster_instance:\n try:\n # when secret_exam field 'ete_cluster_id' is used, otherwise field 'cluster_id' is used\n sql = ''.join((\n \"SELECT id FROM students_studentsubject WHERE \",\n \"ete_cluster_id\" if is_secret_exam else \"cluster_id\",\n \" = \", str(cluster_instance.pk) , \"::INT\"\n ))\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n for row in cursor.fetchall():\n updated_studsubj_pk_list.append(row[0])\n\n except Exception as e:\n if logging_on:\n logger.error(getattr(e, 'message', str(e)))\n\n deleted_row, err_html = sch_mod.delete_instance(\n table='cluster',\n instance=cluster_instance,\n request=request,\n this_txt=this_txt\n )\n if err_html:\n msg_html = err_html\n\n if logging_on and False:\n logger.debug(' deleted_row: ' + str(deleted_row))\n logger.debug(' msg_html: ' + str(msg_html))\n\n return deleted_row, updated_studsubj_pk_list, msg_html\n # - end of delete_cluster_instance\n\n def update_cluster_instance(cluster_instance, cluster_dict):\n # --- update existing cluster name PR2022-01-10\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- update_cluster_instance -----')\n\n err_list = []\n updated_cluster_pk = None\n if cluster_instance:\n try:\n field = 'name'\n\n # - get value of 'cluster_name'\n cluster_name = cluster_dict.get('cluster_name')\n new_value = cluster_name.strip() if cluster_name else None\n\n # - get saved value of cluster name\n saved_value = getattr(cluster_instance, field)\n\n if new_value != saved_value:\n\n # - validate length of cluster name\n msg_err = av.validate_notblank_maxlength(new_value, c.MAX_LENGTH_KEY, _('The cluster name'))\n if msg_err:\n err_list.append(msg_err)\n else:\n\n # - validate if cluster already exists\n name_exists = subj_mod.Cluster.objects.filter(\n school=sel_school,\n department=sel_department,\n name__iexact=new_value\n )\n if name_exists:\n err_list.append(str(_(\"%(cpt)s '%(val)s' already exists.\") \\\n % {'cpt': _('Cluster name'), 'val': new_value}))\n else:\n\n # - save changes\n setattr(cluster_instance, field, new_value)\n cluster_instance.save(request=request)\n updated_cluster_pk = cluster_instance.pk\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n err_list.append(''.join((str(_('An error occurred')), ' (', str(e), ').')))\n err_list.append(str(_(\"%(cpt)s have not been saved.\") % {'cpt': _('The changes')}))\n\n if logging_on:\n logger.debug(' updated_cluster_pk: ' + str(updated_cluster_pk))\n return err_list, updated_cluster_pk\n # - end of update_cluster_instance\n\n def loop_cluster_list(sel_school, sel_department, cluster_list, mapped_cluster_pk_dict):\n logging_on = s.LOGGING_ON\n if logging_on:\n if logging_on:\n logger.debug(' +++++ loop_cluster_list +++++')\n\n err_list = []\n created_cluster_pk_arr = []\n updated_cluster_pk_arr = []\n deleted_cluster_rows = []\n updated_studsubj_pk_list = []\n\n for cluster_dict in cluster_list:\n if logging_on:\n logger.debug(' ..... cluster_dict: ' + str(cluster_dict))\n # 'cluster_dict': {'cluster_pk': 'new_1', 'cluster_name': 'spdltl - 1', 'subject_pk': 220, 'mode': 'create'}\n\n # note: cluster_upload uses subject_pk, not subjbase_pk\n\n subject_pk = cluster_dict.get('subject_pk')\n subject = subj_mod.Subject.objects.get_or_none(\n pk=subject_pk\n )\n if subject:\n cluster_pk = cluster_dict.get('cluster_pk')\n\n mode = cluster_dict.get('mode')\n is_create = mode == 'create'\n is_delete = mode == 'delete'\n\n if logging_on:\n logger.debug(' mode: ' + str(mode))\n logger.debug(' cluster_pk: ' + str(cluster_pk))\n\n # +++ Create new cluster\n if is_create:\n cluster_name = cluster_dict.get('cluster_name')\n err_lst, new_cluster_pk = create_cluster(\n subject=subject,\n cluster_pk=cluster_pk,\n cluster_name=cluster_name\n )\n if err_lst:\n err_list.extend(err_lst)\n if new_cluster_pk:\n created_cluster_pk_arr.append(new_cluster_pk)\n if logging_on:\n logger.debug(' new_cluster_pk: ' + str(new_cluster_pk))\n logger.debug(' created_cluster_pk_arr: ' + str(created_cluster_pk_arr))\n logger.debug(' mapped_cluster_pk_dict: ' + str(mapped_cluster_pk_dict))\n\n # +++ or get existing cluster\n # filter out 'new_1', should not happen\n elif isinstance(cluster_pk, int):\n cluster_instance = subj_mod.Cluster.objects.get_or_none(\n pk=cluster_pk,\n school=sel_school,\n department=sel_department\n )\n if logging_on:\n logger.debug(' cluster_instance: ' + str(cluster_instance))\n\n if cluster_instance:\n # +++ Delete cluster\n if is_delete:\n messages = []\n deleted_row, studsubj_pk_list, err_html = delete_cluster_instance(cluster_instance)\n if logging_on:\n logger.debug(' deleted_row: ' + str(deleted_row))\n logger.debug(' msg_html: ' + str(err_html))\n\n if err_html:\n messages.append(\n {'header': str(_(\"Delete cluster\")),\n 'class': \"border_bg_invalid\",\n 'msg_html': err_html}\n )\n\n err_list.append(err_html)\n elif deleted_row:\n deleted_cluster_rows.append(deleted_row)\n if studsubj_pk_list:\n updated_studsubj_pk_list.extend(studsubj_pk_list)\n\n\n # +++ Update cluster, not when it is created, not when delete has failed (when deleted ok there is no cluster)\n else:\n err_lst, updated_cluster_pk = update_cluster_instance(\n cluster_instance=cluster_instance,\n cluster_dict=cluster_dict\n )\n if err_lst:\n err_list.extend(err_lst)\n if updated_cluster_pk:\n updated_cluster_pk_arr.append(updated_cluster_pk)\n if logging_on:\n logger.debug(' created_cluster_pk_arr: ' + str(created_cluster_pk_arr))\n logger.debug(' updated_cluster_pk_arr: ' + str(updated_cluster_pk_arr))\n logger.debug(' deleted_cluster_rows: ' + str(deleted_cluster_rows))\n\n return err_list, created_cluster_pk_arr, updated_cluster_pk_arr, deleted_cluster_rows, updated_studsubj_pk_list\n # - end of loop_cluster_list\n\n######## end of private functions #################\n\n update_wrap = {}\n msg_list = []\n border_class = None\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n \"\"\"\n upload_dict: {\n 'subject_pk': 2132, 'subject_name': 'Zorg en Welzijn Intrasectoraal',\n 'cluster_list': [\n {'cluster_pk': 210, 'cluster_name': 'zwi - 222', 'subjbase_pk': 445, 'mode': 'update'}, \n {'cluster_pk': 'new_1', 'cluster_name': 'zwi - 6', 'subjbase_pk': 445, 'mode': 'create'}], \n 'studsubj_list': [\n {'studsubj_pk': 68838, 'cluster_pk': 'new_1'}, \n {'studsubj_pk': 68862, 'cluster_pk': 'new_1'}, \n {'studsubj_pk': 68886, 'cluster_pk': 'new_1'}]} \n \"\"\"\n\n# - get permit\n page_name = upload_dict.get('page') or 'page_studsubj'\n has_permit = acc_prm.get_permit_crud_of_this_page(page_name, request)\n\n if not has_permit:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(acc_prm.err_txt_no_permit()) # default: 'to perform this action')\n else:\n\n# - get variables\n is_secret_exam = upload_dict.get('is_secret_exam')\n cluster_list = upload_dict.get('cluster_list')\n studsubj_list = upload_dict.get('studsubj_list')\n\n if logging_on:\n logger.debug('upload_dict: ' + str(upload_dict))\n\n append_dict = {}\n\n# ----- get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - country is locked,\n # - examyear is not found, not published or locked\n # - school is not found, not same_school, not activated, or locked\n # - department is not found, not in user allowed depbase or not in school_depbase\n\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug(' sel_level: ' + str(sel_level))\n logger.debug(' may_edit: ' + str(may_edit))\n logger.debug(' sel_msg_list: ' + str(sel_msg_list))\n logger.debug(' cluster_list: ' + str(cluster_list))\n logger.debug(' studsubj_list: ' + str(studsubj_list))\n\n if sel_msg_list:\n msg_list.extend(sel_msg_list)\n else:\n # - when called by page secret_exam: use school of requsr as school\n if is_secret_exam:\n sel_schoolbase = request.user.schoolbase\n sel_school = sch_mod.School.objects.get_or_none(\n base=sel_schoolbase,\n examyear=sel_examyear\n )\n else:\n sel_schoolbase = sel_school.base if sel_school else None\n\n sel_depbase = sel_department.base if sel_department else None\n\n mapped_cluster_pk_dict = {}\n\n updated_cluster_pk_list = []\n updated_studsubj_pk_list = []\n updated_cluster_pk_arr = []\n\n if cluster_list:\n updated_cluster_rows = []\n err_list, created_cluster_pk_arr, updated_cluster_pk_arr, deleted_cluster_rows, \\\n updated_studsubj_pk_arr = \\\n loop_cluster_list(\n sel_school=sel_school,\n sel_department=sel_department,\n cluster_list=cluster_list,\n mapped_cluster_pk_dict=mapped_cluster_pk_dict\n )\n if err_list:\n msg_list.extend(err_list)\n\n if updated_cluster_pk_arr:\n updated_cluster_pk_list.extend(updated_cluster_pk_arr)\n\n if updated_studsubj_pk_arr:\n updated_studsubj_pk_list.extend(updated_studsubj_pk_arr)\n\n if logging_on:\n logger.debug(' created_cluster_pk_arr: ' + str(created_cluster_pk_arr))\n logger.debug(' updated_cluster_pk_arr: ' + str(updated_cluster_pk_arr))\n logger.debug(' deleted_cluster_rows: ' + str(deleted_cluster_rows))\n logger.debug(' updated_studsubj_pk_arr: ' + str(updated_studsubj_pk_arr))\n\n if created_cluster_pk_arr:\n cluster_rows = sj_vw.create_cluster_rows(\n request=request,\n page='studsubj',\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_schoolbase,\n sel_depbase=sel_depbase,\n cluster_pk_list=created_cluster_pk_arr\n )\n\n if logging_on:\n logger.debug(' ??? created_cluster_pk_arr: ' + str(created_cluster_pk_arr))\n logger.debug(' ??? cluster_rows: ' + str(cluster_rows))\n\n if cluster_rows:\n # - add key 'created' to created rows, used in client to add to table Clustres\n for row in cluster_rows:\n row['created'] = True\n updated_cluster_rows.extend(cluster_rows)\n##################\n if updated_cluster_pk_arr:\n cluster_rows = sj_vw.create_cluster_rows(\n request=request,\n page='studsubj',\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_schoolbase,\n sel_depbase=sel_depbase,\n cluster_pk_list=updated_cluster_pk_arr\n )\n\n if logging_on:\n logger.debug(' ??? updated_cluster_pk_arr: ' + str(updated_cluster_pk_arr))\n logger.debug(' ??? cluster_rows: ' + str(cluster_rows))\n\n if cluster_rows:\n updated_cluster_rows.extend(cluster_rows)\n\n # - add deleted cluster_rows to updated_cluster_rows\n # since seleted cluster does not exist any more, add info of deleted_cluster_rows directly to updated_cluster_rows\n if deleted_cluster_rows:\n updated_cluster_rows.extend(deleted_cluster_rows)\n\n if logging_on:\n logger.debug(' >> updated_cluster_rows: ' + str(updated_cluster_rows))\n\n # - add updated_cluster_rows to update_wrap\n if updated_cluster_rows:\n update_wrap['updated_cluster_rows'] = updated_cluster_rows\n\n if studsubj_list:\n err_list, studsubj_pk_list = loop_studsubj_list(request, is_secret_exam, studsubj_list, mapped_cluster_pk_dict)\n if err_list:\n msg_list.extend(err_list)\n if studsubj_pk_list:\n updated_studsubj_pk_list.extend(studsubj_pk_list )\n if logging_on:\n logger.debug('studsubj_pk_list: ' + str(studsubj_pk_list))\n\n if updated_studsubj_pk_list or updated_cluster_pk_arr:\n if is_secret_exam:\n #tudsubj_list: [{'grade_pk': 76903, 'studsubj_pk': 46327, 'cluster_pk': 'new_1'},\n\n # - convert updated updated_studsubj_pk_list to grade_pk_list\n if studsubj_list:\n grade_pk_list = []\n sel_examperiod = None\n for studsubj_dict in studsubj_list:\n studsubj_pk = studsubj_dict.get('studsubj_pk')\n if studsubj_pk in updated_studsubj_pk_list:\n grade_pk = studsubj_dict.get('grade_pk')\n grade_pk_list.append(grade_pk)\n if sel_examperiod is None:\n sel_examperiod = studsubj_dict.get('examperiod')\n\n if logging_on:\n logger.debug('grade_pk_list: ' + str(grade_pk_list))\n if sel_examperiod and grade_pk_list:\n grade_rows = grd_view.create_grade_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_schoolbase,\n sel_depbase=sel_depbase,\n sel_lvlbase=None, # value not used when grade_pk_list has value\n sel_examperiod=sel_examperiod,\n secret_exams_only=is_secret_exam,\n grade_pk_list=grade_pk_list,\n request=request\n )\n\n if grade_rows:\n update_wrap['updated_grade_rows'] = grade_rows\n\n else:\n studsubj_rows = create_studentsubject_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_schoolbase,\n sel_depbase=sel_depbase,\n append_dict=append_dict,\n request=request,\n requsr_same_school=not is_secret_exam, # check for same_school is included in may_edit\n studsubj_pk_list=updated_studsubj_pk_list,\n cluster_pk_list=updated_cluster_pk_arr\n )\n\n if studsubj_rows:\n update_wrap['updated_studsubj_rows'] = studsubj_rows\n\n # - addd messages to update_wrap\n if msg_list:\n update_wrap['msg_html'] = acc_prm.msghtml_from_msglist_with_border(msg_list, border_class)\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of ClusterUploadView\n\n\ndef loop_studsubj_list(request, is_secret_exam, studsubj_list, mapped_cluster_pk_dict):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- loop_studsubj_list -----')\n logger.debug('studsubj_list: ' + str(studsubj_list))\n logger.debug('mapped_cluster_pk_dict: ' + str(mapped_cluster_pk_dict))\n\n err_list = []\n updated_studsubj_list = []\n \"\"\"\n 'studsubj_list': [\n {'studsubj_pk': 68838, 'cluster_pk': 'new_1'},\n {'studsubj_pk': 68862, 'cluster_pk': 'new_1'},\n {'studsubj_pk': 68886, 'cluster_pk': 'new_1'}]}\n \"\"\"\n if studsubj_list:\n\n sql_studsubj_list = []\n for studsubj_dict in studsubj_list:\n studsubj_pk = studsubj_dict.get('studsubj_pk')\n\n if logging_on:\n logger.debug('....studsubj_dict: ' + str(studsubj_dict))\n # studsubj_dict: {'studsubj_pk': 45092, 'cluster_pk': 'new_1'}\n\n if studsubj_pk:\n cluster_pk = studsubj_dict.get('cluster_pk')\n if logging_on:\n logger.debug(' cluster_pk: ' + str(cluster_pk) + ' ' + str(type(cluster_pk)))\n\n # replace cluster_pk 'new_1' bij saved cluster_pk\n clean_cluster_pk = None\n if isinstance(cluster_pk, int):\n clean_cluster_pk = cluster_pk\n if logging_on:\n logger.debug(' clean_cluster_pk: ' + str(clean_cluster_pk) + ' ' + str(type(clean_cluster_pk)))\n elif cluster_pk in mapped_cluster_pk_dict:\n clean_cluster_pk = mapped_cluster_pk_dict[cluster_pk]\n if logging_on:\n logger.debug(' mapped_cluster_pk_dict clean_cluster_pk: ' + str(clean_cluster_pk) + ' ' + str(type(clean_cluster_pk)))\n\n clean_cluster_str = str(clean_cluster_pk) if clean_cluster_pk else 'NULL'\n\n sql_studsubj_list.append((str(studsubj_pk), clean_cluster_str))\n\n if logging_on:\n logger.debug(' clean_cluster_pk: ' + str(clean_cluster_pk) + ' ' + str(type(clean_cluster_pk)))\n logger.debug(' clean_cluster_str: ' + str(clean_cluster_str))\n logger.debug(' sql_studsubj_list: ' + str(sql_studsubj_list))\n\n # sql_keys = {'ey_id': school.examyear.pk, 'sch_id': school.pk, 'dep_id': department.pk}\n\n \"\"\"\n # you can define the types by casting the values of the first row:\n CREATE TEMP TABLE lookup (key, val) AS\n VALUES \n (0::bigint, -99999::int), \n (1, 100) ;\n \"\"\"\n\n modifiedby_pk_str = str(request.user.pk)\n modifiedat_str = str(timezone.now())\n cluster_field = 'ete_cluster_id' if is_secret_exam else 'cluster_id'\n # fields are: [studentsubject_id, cluster_id, modifiedby_id, modifiedat]\n sql_list = [\"DROP TABLE IF EXISTS tmp; CREATE TEMP TABLE tmp (ss_id, cl_id) AS VALUES (0::INT, 0::INT) \"]\n\n for row in sql_studsubj_list:\n sql_list.extend((\", (\", str(row[0]), ', ', str(row[1]), \") \"))\n\n sql_list.append(\"; UPDATE students_studentsubject AS ss \")\n if is_secret_exam:\n # when adding cluster of secret exam: use field ete_cluster_id, dont update modified fiels\n sql_list.extend((\"SET ete_cluster_id = tmp.cl_id \"))\n else:\n sql_list.extend((\"SET cluster_id = tmp.cl_id, modifiedby_id =\", modifiedby_pk_str, \", modifiedat = '\", modifiedat_str, \"' \"))\n sql_list.append(\"FROM tmp WHERE ss.id = tmp.ss_id RETURNING ss.id;\")\n sql = ''.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n rows = cursor.fetchall()\n if logging_on:\n logger.debug('rows: ' + str(rows))\n\n if rows:\n for row in rows:\n updated_studsubj_list.append(row[0])\n # - end of save_studsubj_batch\n\n\n return err_list, updated_studsubj_list\n# - end of loop_studsubj_list\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentUploadView(View): # PR2020-10-01 PR2021-07-18 PR2022-12-27 PR2023-01-16 PR2023-05-30\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= StudentUploadView ============= ')\n\n messages = []\n msg_list = []\n border_class = None\n update_wrap = {}\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n mode = upload_dict.get('mode')\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get permit\n page_name = 'page_result' if mode == 'withdrawn' else 'page_student'\n has_permit = acc_prm.get_permit_crud_of_this_page(page_name, request)\n\n if logging_on:\n logger.debug(' has_permit:' + str(has_permit))\n\n if not has_permit:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(acc_prm.err_txt_no_permit()) # default: 'to perform this action')\n else:\n\n# - get variables\n student_pk = upload_dict.get('student_pk')\n is_create = mode == 'create'\n is_delete = mode == 'delete_candidate'\n is_restore = mode == 'restore_candidate'\n\n updated_rows = []\n error_list = []\n\n append_dict = {}\n\n header_txt = _('Add candidate') if is_create else _('Delete candidate') if is_delete else _('Edit candidate')\n\n# ----- get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - country is locked,\n # - examyear is not found, not published or locked\n # - school is not found, not same_school, or locked\n # - department is not found, not in user allowed depbase or not in school_depbase\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' may_edit: ' + str(may_edit))\n logger.debug(' sel_msg_list: ' + str(sel_msg_list))\n logger.debug(' upload_dict: ' + str(upload_dict))\n \"\"\"\n sel_msg_list = msg_list.append(str(_(\"You don't have permission to view department %(val)s.\") % {'val': sel_depbase.code}))\n upload_dict: {'table': 'student', 'mode': 'create', 'lastname': 'aa', 'firstname': 'aa', 'gender': 'M', 'idnumber': '2000101010', 'level': 6, 'sector': 12}\n \n \"\"\"\n if sel_msg_list:\n border_class = c.HTMLCLASS_border_bg_warning\n msg_list.extend(sel_msg_list)\n else:\n\n# +++ Create new student\n if is_create:\n student_instance = None\n\n id_number = upload_dict.get('idnumber')\n last_name = upload_dict.get('lastname')\n first_name = upload_dict.get('firstname')\n prefix = upload_dict.get('prefix')\n lvlbase_pk = upload_dict.get('level')\n sctbase_pk = upload_dict.get('sector')\n\n idnumber_nodots, msg_err_list, birthdate_dteobjNIU = stud_val.get_idnumber_nodots_stripped_lower(\n id_number)\n if msg_err_list:\n error_list.extend(msg_err_list)\n\n lastname_stripped, msg_err = stud_val.get_string_convert_type_and_strip(_('Last name'), last_name, True) # True = blank_not_allowed\n if msg_err:\n error_list.append(str(msg_err))\n\n firstname_stripped, msg_err = stud_val.get_string_convert_type_and_strip(_('First name'), first_name, True) # True = blank_not_allowed\n if msg_err:\n error_list.append(str(msg_err))\n\n prefix_stripped, msg_err = stud_val.get_string_convert_type_and_strip(_('Prefix'), prefix, False) # False = blank_allowed\n if msg_err :\n error_list.append(str(msg_err))\n\n full_name = stud_val.get_prefix_lastname_comma_firstname(lastname_stripped, firstname_stripped, prefix_stripped)\n\n # - create student record\n if not error_list:\n student_instance, error_list = create_student_instance(\n examyear=sel_examyear,\n school=sel_school,\n department=sel_department,\n idnumber_nodots=idnumber_nodots,\n lastname_stripped=lastname_stripped,\n firstname_stripped=firstname_stripped,\n prefix_stripped=prefix_stripped,\n full_name=full_name,\n lvlbase_pk=lvlbase_pk,\n sctbase_pk=sctbase_pk,\n request=request,\n found_is_error=True,\n skip_save=False\n )\n\n if error_list:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.extend(error_list)\n\n if student_instance:\n append_dict['created'] = True\n else:\n\n# +++ or get existing student\n student_instance = stud_mod.Student.objects.get_or_none(\n id=student_pk,\n school=sel_school\n )\n if logging_on:\n logger.debug('student_instance: ' + str(student_instance))\n\n restored_student_success = False\n\n if student_instance:\n\n# +++ Delete student\n if is_delete:\n deleted_row, err_html = set_student_instance_tobedeleted(student_instance, request)\n if err_html:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(err_html)\n\n elif deleted_row:\n student_instance = None\n updated_rows.append(deleted_row)\n\n if logging_on:\n logger.debug(' is_delete: ' + str(is_delete))\n logger.debug(' deleted_row: ' + str(deleted_row))\n logger.debug(' err_html: ' + str(err_html))\n\n# +++ restore tobedeleted student\n elif is_restore:\n restored_student_success, updated_studsubj_rows, msg_html = restore_student_instance(student_instance, request)\n if msg_html:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(msg_html)\n\n if not restored_student_success:\n student_instance = None\n\n if logging_on:\n logger.debug(' is_restore: ' + str(is_restore))\n logger.debug(' restored_student_success: ' + str(restored_student_success))\n logger.debug(' updated_studsubj_rows: ' + str(updated_studsubj_rows))\n logger.debug(' msg_html: ' + str(msg_html))\n\n# +++ Update student, also when it is created, not when delete has failed (when deleted ok there is no student)\n else:\n err_fields = []\n idnumber_list = []\n examnumber_list = []\n update_student_instance(\n instance=student_instance,\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n upload_dict=upload_dict,\n idnumber_list=idnumber_list,\n examnumber_list=examnumber_list,\n msg_list=msg_list,\n error_list=error_list,\n err_fields=err_fields, # err_fields is only used in update student\n log_list=[], # log_list is only used in upload students\n request=request,\n skip_save=False\n )\n\n# - create student_row, also when deleting failed, not when deleted ok, in that case student_row is added in delete_student\n if student_instance:\n updated_rows, error_dictNIU = create_student_rows(\n request=request,\n sel_examyear=sel_school.examyear,\n sel_schoolbase=sel_school.base,\n sel_depbase=sel_department.base,\n append_dict=append_dict,\n student_pk_list=[student_instance.pk]\n )\n\n if restored_student_success and updated_rows:\n for row in updated_rows:\n row['restored'] = True\n\n\n update_wrap['updated_student_rows'] = updated_rows\n\n# - addd msg_html to update_wrap\n if msg_list:\n update_wrap['msg_html'] = acc_prm.msghtml_from_msglist_with_border(msg_list, border_class)\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentUploadView\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentCreateExamnumbersView(View): # PR2023-09-02\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= StudentCreateExamnumbersView ============= ')\n\n def remove_existing_examnumbers():\n err_html = None\n try:\n sql_list = [\n \"UPDATE students_student SET examnumber = NULL \",\n \"WHERE school_id = \", str(sel_school.pk), \"::INT \",\n \"AND department_id = \", str(sel_department.pk), \"::INT \"\n ]\n\n if sel_department.level_req and sel_level is not None:\n sql_list.extend((\"AND level_id = \", str(sel_level.pk), \"::INT \"))\n\n sql_list.extend((\n \"AND examnumber IS NOT NULL \",\n \"AND NOT deleted AND NOT tobedeleted;\"\n ))\n sql = ''.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n err_html = acc_prm.errhtml_error_occurred_no_border(e, acc_prm.err_txt_changes_not_saved())\n return err_html\n\n\n def add_new_examnumbers():\n updated_student_pk_list = []\n err_list = None\n try:\n new_examnumber = stud_fnc.get_next_examnumber(sel_school, sel_department)\n\n crit = Q(school=sel_school) & \\\n Q(department=sel_department) & \\\n Q(tobedeleted=False) & \\\n Q(deleted=False) & \\\n Q(examnumber__isnull=True)\n if sel_department.level_req and sel_level:\n crit.add(Q(level=sel_level), crit.connector)\n\n students = stud_mod.Student.objects.filter(crit).order_by(Lower('lastname'), Lower('firstname'))\n\n\n for student in students:\n new_examnumber_str = str(new_examnumber) if new_examnumber else None\n if logging_on:\n logger.debug(' student: ' + str(student))\n logger.debug(' new_examnumber: ' + str(new_examnumber) + str(type(new_examnumber)) )\n logger.debug(' new_examnumber_str: ' + str(new_examnumber_str))\n\n setattr(student, 'examnumber', new_examnumber_str)\n if logging_on:\n logger.debug(' setattr student: ' + str(student))\n student.save(request=request)\n\n if logging_on:\n logger.debug(' save student: ' + str(student))\n updated_student_pk_list.append(student.pk)\n\n new_examnumber += 1\n\n awpr_log.savetolog_student(student.pk, 'u', request, ['examnumber'])\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n err_list = acc_prm.errlist_error_occurred(e, acc_prm.err_txt_changes_not_saved())\n return updated_student_pk_list, err_list\n###############\n\n msg_list = []\n border_class = None\n update_wrap = {}\n\n # - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n\n # - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n # - get permit\n page_name = 'page_student'\n has_permit = acc_prm.get_permit_crud_of_this_page(page_name, request)\n if logging_on:\n logger.debug(' has_permit:' + str(has_permit))\n\n if not has_permit:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(acc_prm.err_txt_no_permit()) # default: 'to perform this action')\n else:\n\n # - get variables\n replace_all = upload_dict.get('replace_all') or False\n\n # ----- get selected examyear, school and department and sel_level from usersettings\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n\n if sel_msg_list:\n border_class = c.HTMLCLASS_border_bg_warning\n msg_list.extend(sel_msg_list)\n else:\n if replace_all:\n err_html = remove_existing_examnumbers()\n if err_html:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(err_html)\n\n if not msg_list:\n updated_student_pk_list, err_list = add_new_examnumbers()\n if err_list:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.extend(err_list)\n elif updated_student_pk_list:\n\n updated_rows, error_dictNIU = create_student_rows(\n request=request,\n sel_examyear=sel_school.examyear,\n sel_schoolbase=sel_school.base,\n sel_depbase=sel_department.base,\n append_dict={},\n student_pk_list=updated_student_pk_list\n )\n if updated_rows:\n update_wrap['updated_student_rows'] = updated_rows\n\n # - addd msg_html to update_wrap\n if msg_list:\n update_wrap['msg_html'] = acc_prm.msghtml_from_msglist_with_border(msg_list, border_class)\n\n # - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# +++ end of StudentCreateExamnumbersView\n\n\n\n#####################\n\n@method_decorator([login_required], name='dispatch')\nclass StudentApproveResultView(View): # PR2023-06-11\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= StudentApproveResultView ============= ')\n\n def update_students(gl_status_value, student_pk_list):\n err_html = None\n updated_student_rows = []\n\n if student_pk_list:\n try:\n # PR2023-06-20 remove modifiedby and modifiedat when removing approval or rejection\n modifiedby_pk_str = str(request.user.pk) if gl_status_value else 'NULL'\n modifiedat_str =''.join((\"'\", str(timezone.now()), \"'\")) if gl_status_value else 'NULL'\n\n sql_list = [\"UPDATE students_student SET gl_status=\", str(gl_status_value),\n \", gl_auth1by_id=\", modifiedby_pk_str, \", gl_modifiedat=\", modifiedat_str, \" \",\n \"WHERE NOT tobedeleted AND NOT deleted \",\n \"AND id IN (SELECT UNNEST(ARRAY\", str(student_pk_list), \"::INT[])) \"\n \"RETURNING id;\"\n ]\n sql = ''.join(sql_list)\n\n if logging_on:\n for sql_txt in sql_list:\n logger.debug(' > ' + str(sql_txt))\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n rows = cursor.fetchall()\n if rows:\n for row in rows:\n updated_student_rows.append(row[0])\n if logging_on:\n logger.debug(' updated_student_rows: ' + str(updated_student_rows))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n err_html = acc_prm.errhtml_error_occurred_with_border(e, _('The changes have not been saved.'))\n\n return updated_student_rows, err_html\n########################\n\n msg_html = None\n border_class = None\n update_wrap = {}\n\n # - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n\n # - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n # - get permit\n has_permit = acc_prm.get_permit_of_this_page('page_result', 'approve_result', request)\n if logging_on:\n logger.debug(' has_permit:' + str(has_permit))\n\n if not has_permit:\n msg_html = acc_prm.err_html_no_permit() # default: 'to perform this action')\n\n else:\n updated_rows = []\n\n # ----- get selected examyear, school and department from usersettings\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' may_edit: ' + str(may_edit))\n logger.debug(' sel_msg_list: ' + str(sel_msg_list))\n logger.debug(' upload_dict: ' + str(upload_dict))\n \"\"\"\n sel_msg_list = msg_list.append(str(_(\"You don't have permission to view department %(val)s.\") % {'val': sel_depbase.code}))\n upload_dict: {'table': 'student', 'mode': 'create', 'lastname': 'aa', 'firstname': 'aa', 'gender': 'M', 'idnumber': '2000101010', 'level': 6, 'sector': 12}\n\n \"\"\"\n if sel_msg_list:\n msg_html = acc_prm.msghtml_from_msglist_with_border(sel_msg_list, c.HTMLCLASS_border_bg_warning)\n else:\n\n # - get variables\n gl_status = upload_dict.get('gl_status')\n student_pk_list = upload_dict.get('student_pk_list')\n\n updated_student_rows, err_html = update_students(gl_status, student_pk_list)\n if err_html:\n msg_html = err_html\n elif updated_student_rows:\n updated_rows, error_dictNIU = create_student_rows(\n request=request,\n sel_examyear=sel_school.examyear,\n sel_schoolbase=sel_school.base,\n sel_depbase=sel_department.base,\n append_dict={},\n student_pk_list=updated_student_rows\n )\n\n update_wrap['updated_student_rows'] = updated_rows\n\n # - addd msg_html to update_wrap\n if msg_html:\n update_wrap['msg_html'] = msg_html\n # - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n\n# - end of StudentApproveResultView\n\n\n##################\n@method_decorator([login_required], name='dispatch')\nclass ChangeBirthcountryView(View): # PR2022-06-20\n\n def post(self, request):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= ChangeBirthcountryView ============= ')\n\n update_wrap = {}\n messages = []\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n mode = upload_dict.get('mode')\n\n# - get permit\n page_name = 'page_result' if mode == 'withdrawn' else 'page_student'\n has_permit = acc_prm.get_permit_crud_of_this_page(page_name, request)\n\n if has_permit:\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# ----- get selected examyear, school and department from usersettings\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug('sel_examyear: ' + str(sel_examyear))\n logger.debug('sel_school: ' + str(sel_school))\n logger.debug('sel_department: ' + str(sel_department))\n logger.debug('may_edit: ' + str(may_edit))\n logger.debug('sel_msg_list: ' + str(sel_msg_list))\n\n if len(sel_msg_list):\n msg_html = '
'.join(sel_msg_list)\n messages.append({'class': \"border_bg_warning\", 'msg_html': msg_html})\n else:\n msg_dict = change_birthcountry(sel_examyear, sel_school.base, sel_department.base, request)\n if msg_dict:\n messages.append(msg_dict)\n\n# - addd messages to update_wrap\n if len(messages):\n update_wrap['messages'] = messages\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentUploadView\n# - end of ChangeBirthcountryView\n\n@method_decorator([login_required], name='dispatch')\nclass StudentMultipleOccurrencesView(View): # PR2021-09-05\n\n def post(self, request):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ============= StudentMultipleOccurrencesView ============= ')\n\n # function validates studentsubject records of all students of this dep PR2021-07-10\n # exclude deleted and other country PR2023-01-17\n update_wrap = {}\n multiple_occurrences_list = []\n\n# - get permit - only download list when user has permit_crud\n has_permit = acc_prm.get_permit_crud_of_this_page('page_studsubj', request)\n if has_permit:\n\n# - reset language\n #user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n #activate(user_lang)\n\n # - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n\n # ----- get selected examyear, school and department from usersettings\n sel_examyear, sel_school, sel_department, sel_level, may_edit, msg_listNIU = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n # +++ get dict of multiple_occurrences\n if sel_examyear and sel_school and sel_department and may_edit:\n multiple_occurrences_list, multiple_occurrences_dict = stud_val.get_multiple_occurrences(sel_examyear, sel_school.base, sel_department.base)\n\n # +++ link students with the same idnumber , lastname and firstname\n #if dictlist:\n # stud_val.link_students_with_multiple_occurrences(dictlist)\n if multiple_occurrences_list:\n update_wrap['multiple_occurrences_dict'] = multiple_occurrences_dict\n\n update_wrap['multiple_occurrences_list'] = multiple_occurrences_list\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentMultipleOccurrencesView\n\n\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentLinkStudentView(View): # PR2021-09-06\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= StudentLinkStudentView ============= ')\n\n update_wrap = {}\n messages = []\n\n# - get permit - StudentLinkStudentView is called from page studsubj\n has_permit = acc_prm.get_permit_crud_of_this_page('page_studsubj', request)\n if has_permit:\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n # upload_dict: {'mode': 'tick', 'cur_stud_id': 6259, 'oth_stud_id': 5991, 'table': 'student', 'linked': False}\n\n# - get variables\n mode = upload_dict.get('mode')\n cur_stud_pk = upload_dict.get('cur_stud_id')\n oth_stud_pk = upload_dict.get('oth_stud_id')\n\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n logger.debug(' mode: ' + str(mode))\n logger.debug(' cur_stud_pk: ' + str(cur_stud_pk))\n logger.debug(' oth_stud_pk: ' + str(oth_stud_pk))\n\n updated_rows = []\n append_dict = {}\n error_list = []\n\n# ----- get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - country is locked,\n # - examyear is not found, not published or locked\n # - school is not found, not same_school, not activated, or locked\n # - department is not found, not in user allowed depbase or not in school_depbase\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug(' may_edit: ' + str(may_edit))\n logger.debug(' sel_msg_list: ' + str(sel_msg_list))\n logger.debug('.....')\n\n if len(sel_msg_list):\n msg_html = '
'.join(sel_msg_list)\n messages.append({'class': \"border_bg_warning\", 'msg_html': msg_html})\n else:\n\n try:\n # +++ get current student\n cur_student = stud_mod.Student.objects.get_or_none(\n id=cur_stud_pk,\n school=sel_school\n )\n\n if cur_student and oth_stud_pk:\n other_stud_pk_str = str(oth_stud_pk)\n if logging_on:\n logger.debug(' cur_student: ' + str(cur_student))\n logger.debug(' other_stud_pk_str: ' + str(other_stud_pk_str))\n\n # get linked_arr and notlinked_arr from cur_student\n linked_str = getattr(cur_student, 'linked')\n linked_arr = linked_str.split(';') if linked_str else []\n # linked_arr: ['5991', '8531']\n\n notlinked_str = getattr(cur_student, 'notlinked')\n notlinked_arr = notlinked_str.split(';') if notlinked_str else []\n # notlinked_arr: ['8422']\n\n if logging_on:\n logger.debug(' mode: ' + str(mode))\n logger.debug(' linked_arr: ' + str(linked_arr))\n logger.debug(' notlinked_arr: ' + str(notlinked_arr))\n logger.debug(' other_student_islinked: ' + str(other_stud_pk_str in linked_arr))\n logger.debug(' other_student_notlinked: ' + str(other_stud_pk_str in notlinked_arr))\n\n # ===== link ============================\n if mode == 'link':\n\n # when clicked on tick: 'linked' = True sets link, 'linked' = False removes link\n set_linked = upload_dict.get('linked', False)\n\n set_student_linked_ok = set_student_linked(\n set_linked, linked_arr, notlinked_arr, other_stud_pk_str, cur_student,\n request)\n\n # TODO make_student_biscandidate(cur_student, other_student, request)\n # add exemptions\n\n #if set_student_linked_ok:\n # set_student_bisexam_and_exemptions(cur_student, other_stud_pk_str)\n # ===== unlink ============================\n elif mode == 'unlink':\n\n # when clicked on cross: 'unlinked' = True sets unlink, 'unlinked' = False removes unlink\n\n # unlink if other_student is different from cur_student:\n # - add oth_stud_pk to notlinked charfield, if not exists yet\n # - remove oth_stud_pk from linked charfield, if exists\n\n set_notlinked = upload_dict.get('notlinked', False)\n set_student_notlinked(set_notlinked, linked_arr, notlinked_arr, other_stud_pk_str,\n cur_student, request)\n\n\n # - create student_row, also when deleting failed, not when deleted ok, in that case student_row is added in delete_student\n #this is not used, check if can be removed\n # student_pk = cur_student.pk if cur_student else None\n #updated_rows, error_dictNIU = create_student_rows(\n # request=request,\n # sel_examyear=sel_school.examyear,\n # sel_schoolbase=sel_school.base,\n # sel_depbase=sel_department.base,\n # append_dict=append_dict,\n # student_pk=student_pk)\n\n # bewijs van vrijstelling is valid for 10 years when evening or lex school\n if sel_school.iseveningschool or sel_school.islexschool:\n firstinrange_examyear_int = sel_examyear.code - 10 if sel_examyear.code else None\n else:\n firstinrange_examyear_int = sel_examyear.code - 1 if sel_examyear.code else None\n\n student_idnumber = getattr(cur_student, 'idnumber')\n student_dict = stud_val.lookup_multiple_occurrences(\n firstinrange_examyear_int=firstinrange_examyear_int,\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base,\n sel_depbase=sel_department.base,\n student_idnumber=student_idnumber\n )\n update_wrap['updated_multiple_occurrences'] = [student_dict]\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n if len(messages):\n update_wrap['messages'] = messages\n # - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentLinkStudentView\n\n\ndef set_student_linked(set_linked, linked_arr, notlinked_arr, other_stud_pk_str, cur_student, request):\n # PR2021-09-06 PR2023-01-17\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ----- set_student_linked -----')\n logger.debug(' cur_student: ' + str(cur_student))\n logger.debug(' set_linked: ' + str(set_linked))\n logger.debug(' other_stud_pk_str: ' + str(other_stud_pk_str))\n set_student_linked_ok = False\n if cur_student and other_stud_pk_str:\n try:\n\n if set_linked:\n # - add oth_stud_pk to linked_arr\n if other_stud_pk_str not in linked_arr:\n linked_arr.append(other_stud_pk_str)\n if linked_arr:\n linked_arr.sort()\n linked_str = ';'.join(linked_arr)\n setattr(cur_student, 'linked', linked_str)\n set_student_linked_ok = True\n\n if logging_on:\n logger.debug(' ----set_linked------')\n logger.debug(' cur_student.linked: ' + str(cur_student.linked))\n logger.debug(' cur_student.notlinked: ' + str(cur_student.notlinked))\n logger.debug(' set_student_linked_ok: ' + str(set_student_linked_ok))\n\n\n # - remove all occurrencies of oth_stud_pk from unlinked charfield, if exists\n if notlinked_arr and other_stud_pk_str in notlinked_arr:\n # - note: arr.remove(str) removes only the first occuuerncy\n # - this removes all occurrencies of oth_stud_pk from linked charfield\n # PR2021-09-17 from: https://note.nkmk.me/en/python-list-comprehension/\n new_notlinked_arr = [pk_str for pk_str in notlinked_arr if pk_str != other_stud_pk_str]\n new_notlinked_str = ';'.join(new_notlinked_arr) if new_notlinked_arr else None\n\n setattr(cur_student, 'notlinked', new_notlinked_str)\n\n cur_student.save(request=request)\n\n else:\n # - remove other_stud_pk from linked_arr\n if linked_arr and other_stud_pk_str in linked_arr:\n # - note: arr.remove(str) removes only the first occuuerncy\n # - this removes all occurrencies of oth_stud_pk from linked charfield\n # PR2021-09-17 from: https://note.nkmk.me/en/python-list-comprehension/\n new_linked_arr = [pk_str for pk_str in linked_arr if pk_str != other_stud_pk_str]\n new_linked_str = ';'.join(new_linked_arr) if new_linked_arr else None\n\n setattr(cur_student, 'linked', new_linked_str)\n\n cur_student.save(request=request)\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n if logging_on:\n logger.debug(' ----------')\n logger.debug(' cur_student.linked: ' + str(cur_student.linked))\n logger.debug(' cur_student.notlinked: ' + str(cur_student.notlinked))\n logger.debug(' set_student_linked_ok: ' + str(set_student_linked_ok))\n\n return set_student_linked_ok\n\n# - end of set_student_linked\n\n\ndef set_student_notlinked(set_notlinked, linked_arr, notlinked_arr, other_stud_pk_str, cur_student, request):\n # PR2021-09-06 PR2023-01-17\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ----- set_student_notlinked -----')\n\n set_student_notlinked_ok = False\n if cur_student and other_stud_pk_str:\n\n try:\n # if notlinked: add other_stud_pk_str to notlinked\n if set_notlinked:\n # - add other_stud_pk_str to notlinked, remove linked if necessary\n notlinked_arr.append(other_stud_pk_str)\n notlinked_arr.sort()\n notlinked_str = ';'.join(notlinked_arr)\n\n setattr(cur_student, 'notlinked', notlinked_str)\n\n # - remove all occurrencies of oth_stud_pk from linked charfield\n if other_stud_pk_str in linked_arr:\n # PR2021-09-17 from: https://note.nkmk.me/en/python-list-comprehension/\n new_linked_arr = [pk_str for pk_str in linked_arr if pk_str != other_stud_pk_str]\n new_linked_str = ';'.join(new_linked_arr) if new_linked_arr else None\n\n setattr(cur_student, 'linked', new_linked_str)\n logger.debug('new_linked_str: ' + str(new_linked_str))\n\n cur_student.save(request=request)\n set_student_notlinked_ok = True\n else:\n # dont update modifiedat when only other_student removed from nonlinked field\n cur_student.save()\n\n else:\n # if notlinked = False: remove other_stud_pk_str from notlinked\n if other_stud_pk_str in notlinked_arr:\n # - remove all occurrencies of oth_stud_pk from notlinked charfield\n # PR2021-09-17 from: https://note.nkmk.me/en/python-list-comprehension/\n new_notlinked_arr = [pk_str for pk_str in notlinked_arr if pk_str != other_stud_pk_str]\n new_notlinked_str = ';'.join(new_notlinked_arr) if new_notlinked_arr else None\n\n setattr(cur_student, 'notlinked', new_notlinked_str)\n logger.debug('new_linked_str: ' + str(new_notlinked_str))\n\n # dont update modifiedat when only other_student removed from nonlinked field\n cur_student.save()\n\n if logging_on:\n logger.debug('.............')\n logger.debug(' cur_student: ' + str(cur_student))\n logger.debug(' cur_student.linked: ' + str(cur_student.linked))\n logger.debug(' cur_student.notlinked: ' + str(cur_student.notlinked))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n return set_student_notlinked_ok\n# - end of set_student_notlinked\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentEnterExemptionsView(View): # PR203-01-24\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('')\n logger.debug(' ============= StudentEnterExemptionsView ============= ')\n\n update_wrap = {}\n messages = []\n\n log_list = []\n\n\n #PR2023-04-24 TODO implement fuzzy approximate string matching\n \"\"\"\n https://stackoverflow.com/questions/31642940/finding-if-two-strings-are-almost-similar\n \n You can use difflib.sequencematcher if you want something from the stdlib:\n\n from difflib import SequenceMatcher\n s_1 = 'Mohan Mehta'\n s_2 = 'Mohan Mehte'\n print(SequenceMatcher(a=s_1,b=s_2).ratio())\n 0.909090909091\n\n \"\"\"\n\n# - get permit - StudentLinkStudentView is called from page studsubj\n has_permit = acc_prm.get_permit_crud_of_this_page('page_studsubj', request)\n if has_permit:\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n # upload_dict: {'mode': 'tick', 'cur_stud_id': 6259, 'oth_stud_id': 5991, 'table': 'student', 'linked': False}\n\n# - get variables\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n\n sel_examyear, sel_school, sel_department, sel_level, may_edit, sel_msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug('.....')\n\n if len(sel_msg_list):\n msg_html = '
'.join(sel_msg_list)\n messages.append({'class': \"border_bg_warning\", 'msg_html': msg_html})\n else:\n\n try:\n # +++ get dict of multiple_occurrences\n\n if sel_examyear and sel_school and sel_department and may_edit:\n updated_grade_pk_list = []\n # - create log_list\n today_dte = af.get_today_dateobj()\n today_formatted = af.format_WDMY_from_dte(today_dte, user_lang)\n\n school_name = sel_school.base.code + ' ' + sel_school.name\n log_list.append(c.STRING_DOUBLELINE_80)\n log_list.append(str(_('Enter exemptions')) + ' ' + str(_('date')) + ': ' + str(today_formatted))\n log_list.append(c.STRING_DOUBLELINE_80)\n\n log_list.append(c.STRING_SPACE_05 + str(_(\"School : %(name)s\") % {'name': school_name}))\n log_list.append(c.STRING_SPACE_05 + str(_(\"Department: %(dep)s\") % {'dep': sel_department.name}))\n log_list.append(c.STRING_SPACE_05 + str(_(\"Exam year : %(ey)s\") % {'ey': str(sel_examyear.code)}))\n\n log_list.append(c.STRING_SPACE_05)\n\n linked_students = stud_mod.Student.objects.filter(\n school=sel_school,\n department=sel_department,\n linked__isnull=False,\n partial_exam=False,\n deleted=False,\n tobedeleted=False\n )\n if linked_students:\n append_dict = {}\n for cur_stud in linked_students:\n cur_examyear_code = cur_stud.school.examyear.code\n cur_depbase = cur_stud.department.base\n cur_depbase_code = cur_depbase.code\n cur_lvlbase = cur_stud.level.base\n cur_sctbase = cur_stud.sector.base\n cur_lvlbase_code = cur_lvlbase.code if cur_lvlbase else ''\n cur_sctbase_code = cur_sctbase.code if cur_sctbase else ''\n\n linked_arr = list(map(int, cur_stud.linked.split(';')))\n\n is_evelex = cur_stud.iseveningstudent or cur_stud.islexstudent\n\n curstud_logtxt_added = False\n\n if logging_on:\n logger.debug('cur_stud: ' + str(cur_stud))\n logger.debug(' cur_examyear_code: ' + str(cur_examyear_code))\n logger.debug(' cur_depbase: ' + str(cur_depbase))\n logger.debug(' cur_lvlbase: ' + str(cur_lvlbase))\n logger.debug(' linked_arr: ' + str(linked_arr))\n logger.debug(' ..........')\n\n if linked_arr:\n\n # ++++++ loop through other_students\n for other_student_pk in linked_arr:\n other_stud = stud_mod.Student.objects.get_or_none(\n pk=other_student_pk,\n deleted=False,\n tobedeleted=False,\n partial_exam=False,\n result=c.RESULT_FAILED\n )\n if other_stud:\n other_examyear_code = other_stud.school.examyear.code\n other_depbase = other_stud.department.base\n other_lvlbase = other_stud.level.base\n other_sctbase = other_stud.sector.base\n other_result_status = other_stud.result_status\n other_failed = (other_stud.result == c.RESULT_FAILED)\n other_school = other_stud.school.name\n other_depbase_code = other_depbase.code\n other_lvlbase_code = other_lvlbase.code if other_lvlbase else ''\n other_sctbase_code = other_sctbase.code if other_sctbase else ''\n\n if logging_on:\n logger.debug(' other_stud: ' + str(other_stud))\n logger.debug(' other_examyear_code: ' + str(other_examyear_code))\n logger.debug(' other_depbase: ' + str(other_depbase))\n logger.debug(' other_lvlbase: ' + str(other_lvlbase))\n logger.debug(' other_failed: ' + str(other_failed))\n\n # is exam year correct?\n valid_years = 10 if is_evelex else 1\n examyear_is_correct = (other_examyear_code < cur_examyear_code and\n other_examyear_code >= cur_examyear_code - valid_years)\n if logging_on:\n logger.debug(' examyear_is_correct: ' + str(examyear_is_correct))\n\n if examyear_is_correct:\n # dep and level correct?\n if other_depbase == cur_depbase and other_lvlbase == cur_lvlbase:\n\n if logging_on:\n logger.debug(' BINGO: ')\n\n # set student bis_exam = True if False\n cur_stud_bis_exam = getattr(cur_stud, 'bis_exam')\n if not cur_stud_bis_exam:\n setattr(cur_stud, 'bis_exam', True)\n cur_stud.save(request=request)\n\n # - create log header for this student\n if not curstud_logtxt_added:\n log_list.append(' ')\n\n log_list.append(''.join((\n cur_stud.fullname,\n ' - ' + cur_depbase_code,\n ' - ' + cur_lvlbase_code if cur_lvlbase else '',\n ' - ' + cur_sctbase_code if cur_sctbase else ''\n )))\n log_list.append(c.STRING_SPACE_05 + str(\n _(\"The exam of this candidate is %(is_already)s marked as 'bis-exam'.\") %\n {'is_already': _(\n 'already') if cur_stud_bis_exam else 'now'}))\n\n curstud_logtxt_added = True\n\n log_list.append(''.join((c.STRING_SPACE_05,\n (str(other_examyear_code) + c.STRING_SPACE_05)[:5],\n other_school,\n ' - ' + other_depbase_code,\n ' - ' + other_lvlbase_code if other_lvlbase else '',\n ' - ' + other_sctbase_code if other_sctbase else ''\n ' - ' + other_sctbase_code if other_sctbase else '',\n ' - ' + other_result_status if other_result_status else '',\n )))\n\n # - get subjects with pok of other student\n other_studsubjects = stud_mod.Studentsubject.objects.filter(\n student=other_stud,\n tobedeleted=False,\n deleted=False,\n pok_validthru__isnull=False\n )\n if other_studsubjects is None:\n log_list.append(''.join((c.STRING_SPACE_10,\n str(_('This candidate has no Proofs of Knowledge.'))\n )))\n else:\n for other_studsubj in other_studsubjects:\n\n subj_code = other_studsubj.schemeitem.subject.base.code if other_studsubj.schemeitem.subject.base.code else '---'\n pok_sesr = other_studsubj.pok_sesr.replace('.', ',') if other_studsubj.pok_sesr else '-'\n pok_pece = other_studsubj.pok_pece.replace('.', ',') if other_studsubj.pok_pece else '-'\n pok_final = other_studsubj.pok_final.replace('.', ',') if other_studsubj.pok_final else '-'\n\n if logging_on:\n logger.debug('........ ')\n logger.debug(' other_studsubj: ' + str(other_studsubj))\n logger.debug(' other_studsubj: ' + str(other_studsubj.schemeitem.subject.base.code))\n logger.debug(' other_studsubj pok_validthru: ' + str(other_studsubj.pok_validthru))\n logger.debug(' other_studsubj pok_final: ' + str(other_studsubj.pok_final))\n\n # get corresonding cur_studsubject\n cur_studsubj = stud_mod.Studentsubject.objects.get_or_none(\n student=cur_stud,\n schemeitem__subject__base=other_studsubj.schemeitem.subject.base,\n tobedeleted=False,\n deleted=False\n )\n if cur_studsubj:\n\n if logging_on:\n logger.debug(' cur_studsubj: ' + str(cur_studsubj))\n logger.debug(' cur_studsubj: ' + str(cur_studsubj.schemeitem.subject.base.code))\n logger.debug(' cur_studsubj pok_validthru: ' + str(cur_studsubj.pok_validthru))\n logger.debug(' cur_studsubj pok_final: ' + str(cur_studsubj.pok_final))\n\n logger.debug(' cur_studsubj pk: ' + str(cur_studsubj.pk))\n\n grade_logtxt = ''.join((c.STRING_SPACE_10,\n (subj_code + c.STRING_SPACE_10)[:8],\n 's: ', (pok_sesr + c.STRING_SPACE_05)[:5],\n 'c: ', (pok_pece + c.STRING_SPACE_05)[:5],\n 'e: ', (pok_final + c.STRING_SPACE_05)[:5]\n ))\n\n # check if cur_studsubj has already an exemption grade\n cur_exem_grade = stud_mod.Grade.objects.filter(\n studentsubject=cur_studsubj,\n examperiod=c.EXAMPERIOD_EXEMPTION\n ).order_by('pk').first()\n\n if cur_exem_grade is None:\n\n if logging_on:\n logger.debug(' cur_exem_grade is None')\n cur_exem_grade = stud_mod.Grade(\n studentsubject=cur_studsubj,\n examperiod=c.EXAMPERIOD_EXEMPTION,\n segrade=other_studsubj.pok_sesr,\n cegrade=other_studsubj.pok_pece,\n finalgrade=other_studsubj.pok_final,\n exemption_imported=True # PR2023-01-24 added to skip approval\n )\n cur_exem_grade.save(request=request)\n\n append_dict[cur_exem_grade.pk] = {'created': True}\n\n if cur_exem_grade.pk not in updated_grade_pk_list:\n updated_grade_pk_list.append(cur_exem_grade.pk)\n\n grade_logtxt += ''.join((' (', str(_('added')), ')'))\n\n else:\n # check if exemption is alreay submitted\n if cur_exem_grade.se_published or cur_exem_grade.ce_published:\n grade_logtxt = ''.join((c.STRING_SPACE_10,\n (subj_code + c.STRING_SPACE_10)[:8],\n str(_('is already submitted'))\n ))\n elif other_studsubj.pok_sesr != cur_exem_grade.segrade or \\\n other_studsubj.pok_pece != cur_exem_grade.cegrade or \\\n other_studsubj.pok_final != cur_exem_grade.finalgrade or \\\n cur_exem_grade.tobedeleted or \\\n cur_exem_grade.deleted:\n\n if cur_exem_grade.tobedeleted or cur_exem_grade.deleted:\n\n if logging_on:\n logger.debug(' cur_exem_grade is deleted')\n setattr(cur_exem_grade, 'tobedeleted', False)\n setattr(cur_exem_grade, 'deleted', False)\n\n grade_logtxt += ''.join((' (', str(_('was deleted')), ')'))\n\n append_dict[cur_exem_grade.pk] = {'created': True}\n if logging_on:\n logger.debug(' append_dict: ' + str(append_dict))\n else:\n cur_sesr = cur_exem_grade.segrade.replace(\n '.',\n ',') if cur_exem_grade.segrade else '-'\n cur_pece = cur_exem_grade.cegrade.replace(\n '.',\n ',') if cur_exem_grade.cegrade else '-'\n cur_finalgrade = cur_exem_grade.finalgrade.replace(\n '.',\n ',') if cur_exem_grade.finalgrade else '-'\n\n grade_logtxt += ''.join(\n (' (', str(_('was')),\n ': s: ', cur_sesr,\n ' c: ', cur_pece,\n ' e: ', cur_finalgrade,\n ')'))\n setattr(cur_exem_grade, 'segrade', other_studsubj.pok_sesr)\n setattr(cur_exem_grade, 'cegrade', other_studsubj.pok_pece)\n setattr(cur_exem_grade, 'finalgrade', other_studsubj.pok_final)\n\n setattr(cur_exem_grade, 'exemption_imported', True) # PR2023-01-24 added to skip approval\n\n for examtype in ('se', 'ce'):\n setattr(cur_exem_grade, examtype + '_blocked', False)\n setattr(cur_exem_grade, examtype + '_published_id', None)\n setattr(cur_exem_grade, examtype + '_auth1by_id', None)\n setattr(cur_exem_grade, examtype + '_auth2by_id', None)\n\n cur_exem_grade.save(request=request)\n\n if cur_exem_grade.pk not in updated_grade_pk_list:\n updated_grade_pk_list.append(\n cur_exem_grade.pk)\n\n else:\n grade_logtxt += ''.join((' (', str(_('is already entered')), ')'))\n\n log_list.append(grade_logtxt)\n\n if logging_on:\n logger.debug(' +++cur_segrade: ' + str(cur_exem_grade.segrade))\n logger.debug(' cur_cegrade: ' + str(cur_exem_grade.cegrade))\n logger.debug(' cur_exem_grade: ' + str(cur_exem_grade.finalgrade))\n\n setattr(cur_studsubj, 'exemption_year', other_examyear_code)\n setattr(cur_studsubj, 'has_exemption', True)\n cur_studsubj.save(request=request)\n\n if logging_on:\n logger.debug(' cur_studsubj.has_exemption: ' + str(cur_studsubj.has_exemption))\n\n # ++++++ end of loop through other_students\n\n # has failed? - is inlcuded in query\n\n if logging_on:\n logger.debug(' XXXXXXXXXXXX append_dict: ' + str(append_dict))\n\n # enter exemptions\n grade_rows = grd_view.create_grade_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base if sel_school else None,\n sel_depbase=sel_department.base if sel_department else None,\n sel_lvlbase=None,\n sel_examperiod=c.EXAMPERIOD_EXEMPTION,\n request=request,\n append_dict=append_dict,\n grade_pk_list=updated_grade_pk_list,\n remove_note_status=True\n )\n if grade_rows:\n update_wrap['updated_grade_rows'] = grade_rows\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n update_wrap['log_list'] = log_list\n\n if len(messages):\n update_wrap['messages'] = messages\n # - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n\n# end of StudentEnterExemptionsView\n\n\ndef set_student_bisexam_and_exemptions(cur_student, other_stud_pk_str, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ============= set_student_bisexam_and_exemptions ============= ')\n logger.debug('cur_student.iseveningstudent: ' + str(cur_student.iseveningstudent))\n logger.debug('cur_student.islexstudent: ' + str(cur_student.islexstudent))\n\n\n if cur_student and other_stud_pk_str:\n\n cur_stud_does_partialexam = cur_student.partial_exam\n # is cur_student an evening or lex student?\n cur_stud_is_evelexstudent = cur_student.iseveningstudent or cur_student.islexstudent\n cur_stud_is_bisexam = cur_student.bis_exam\n\n cur_examyear_code = cur_student.school.examyear.code\n\n try:\n\n if cur_stud_does_partialexam:\n # don't add exemptions when student does partial exam\n pass\n else:\n\n# is cur_student an evening or lex student?\n# - get other_student\n other_student = stud_mod.Student.objects.get_or_none(\n pk=int(other_stud_pk_str)\n )\n if other_student:\n other_examyear_code = other_student.school.examyear.code\n\n other_examyear_ok = False\n\n if cur_stud_is_evelexstudent:\n # other_examyear_code must be max ten year less than current examyear\n if other_examyear_code <= cur_examyear_code - 1 and \\\n other_examyear_code >= cur_examyear_code - 10:\n other_examyear_ok = True\n else:\n # other_examyear_code must be one year less than current examyear\n if other_examyear_code == cur_examyear_code - 1:\n other_examyear_ok = True\n\n if other_examyear_ok:\n # set student as bis_exam - not when evelex student\n if not cur_stud_is_evelexstudent:\n cur_student.bis_exam = True\n cur_student.save(request=request)\n\n # get list of pok (proof of knowledge)\n\n\n# is cur_student an evening or lex student?\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n\n# end of set_student_bisexam_and_exemptions\n\ndef make_student_biscandidate(cur_student, other_student, request):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ============= make_student_biscandidate ============= ')\n logger.debug('cur_student.iseveningstudent: ' + str(cur_student.iseveningstudent))\n logger.debug('cur_student.islexstudent: ' + str(cur_student.islexstudent))\n\n # TODO how to deal with evening school\n if not cur_student.iseveningstudent and not cur_student.islexstudent:\n try:\n is_biscand = False\n other_student_examyear_int = other_student.school.examyear.code\n # not in chceklist: student can only be biscandidate when he has failed\n # - student can not be biscandidate when he is withdrawn\n if logging_on:\n logger.debug('other_student.withdrawn: ' + str(other_student.withdrawn))\n if not other_student.withdrawn:\n # - student can only be biscandidate when other_student is from previous year\n if logging_on:\n logger.debug('cur_student.school.examyear.code: ' + str(cur_student.school.examyear.code))\n logger.debug('other_student_examyear_int: ' + str(other_student_examyear_int))\n if cur_student.school.examyear.code == other_student_examyear_int + 1:\n # - student can only be biscandidate when the depbases are the same\n if logging_on:\n logger.debug('cur_student.department.base_id: ' + str(cur_student.department.base_id))\n logger.debug('other_student.department.base_id: ' + str(other_student.department.base_id))\n logger.debug('cur_student.department.level_req: ' + str(cur_student.department.level_req))\n #logger.debug('cur_student.level.base_id: ' + str(cur_student.level.base_id))\n #logger.debug('other_student.level.base_id: ' + str(other_student.level.base_id))\n\n if cur_student.department.base_id == other_student.department.base_id:\n\n # - student can only be biscandidate when the lvlbases are the same (only when not level_req)\n if cur_student.department.level_req:\n if cur_student.level and other_student.level and cur_student.level.base_id == other_student.level.base_id:\n is_biscand = True\n else:\n is_biscand = True\n if logging_on:\n logger.debug('is_biscand: ' + str(is_biscand))\n if is_biscand:\n cur_student.bis_exam = True\n cur_student.save(request=request)\n\n # get proof of knowledge subjects from other_student\n other_studsubjects = stud_mod.Studentsubject.objects.filter(\n student=other_student,\n pok_validthru__isnull=False\n )\n # loop through list of proof of knowledge subjects of other_student\n for other_studsubj in other_studsubjects:\n other_subjectbase = other_studsubj.schemeitem.subject.base\n other_subjbase_code = other_studsubj.schemeitem.subject.base.code\n if logging_on:\n logger.debug('........................................')\n logger.debug('other_subject.name_nl: ' + str(other_studsubj.schemeitem.subject.name_nl))\n logger.debug('other_subjectbase.code: ' + str(other_subjbase_code))\n logger.debug('other_subjectbase.pk: ' + str(other_subjectbase.pk))\n\n # lookup same subject in current student\n cur_studsubj = stud_mod.Studentsubject.objects.get_or_none(\n student=cur_student,\n schemeitem__subject__base__code__iexact=other_subjbase_code\n )\n if cur_studsubj:\n cur_subjbase_code = cur_studsubj.schemeitem.subject.base.code\n if logging_on:\n if logging_on:\n logger.debug('cur_subject.name_nl: ' + str(cur_studsubj.schemeitem.subject.name_nl))\n logger.debug('cur_subjbase_code: ' + str(cur_subjbase_code))\n logger.debug('cur_subjectbase.pk: ' + str(cur_studsubj.schemeitem.subject.base.pk))\n\n if other_subjbase_code.lower() == cur_subjbase_code.lower():\n if logging_on:\n logger.debug('>>>> other_subjbase_code.lower() == cur_subjbase_code.lower() ')\n\n # create exemption grade if not yet exist\n cur_exem_grade = stud_mod.Grade.objects.filter(\n studentsubject=cur_studsubj,\n examperiod=c.EXAMPERIOD_EXEMPTION\n ).order_by('pk').first()\n if logging_on:\n logger.debug('cur_exem_grade ' + str(cur_exem_grade))\n\n if cur_exem_grade is None:\n cur_exem_grade = stud_mod.Grade.objects.create(\n studentsubject=cur_studsubj,\n examperiod=c.EXAMPERIOD_EXEMPTION\n )\n if logging_on:\n logger.debug('cur_exem_grade.created ' + str(cur_exem_grade))\n if cur_exem_grade:\n setattr(cur_exem_grade, 'sesrgrade', other_studsubj.gradelist_sesrgrade)\n setattr(cur_exem_grade, 'pecegrade', other_studsubj.gradelist_pecegrade)\n setattr(cur_exem_grade, 'finalgrade', other_studsubj.gradelist_finalgrade)\n cur_exem_grade.save(request=request)\n if logging_on:\n logger.debug('cur_exem_grade.saved ' + str(cur_exem_grade))\n\n # set pok_validthru = examyear_int + 1\n pok_validthru = other_student_examyear_int + 1\n setattr(cur_studsubj, 'pok_validthru', pok_validthru)\n cur_studsubj.save(request=request)\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n# - end of make_student_biscandidate\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectnoteDownloadView(View): # PR2021-03-15\n\n def post(self, request):\n logger.debug(' ============= StudentsubjectnoteDownloadView ============= ')\n logger.debug('request.POST: ' + str(request.POST))\n datalists_json = '{}'\n if request.user and request.user.country and request.user.schoolbase:\n if 'upload' in request.POST and request.POST['upload']:\n upload_dict = json.loads(request.POST['upload'])\n datalists = {'studentsubjectnote_rows': create_studentsubjectnote_rows(upload_dict, request) }\n\n datalists_json = json.dumps(datalists, cls=af.LazyEncoder)\n\n return HttpResponse(datalists_json)\n\n\n############################################################################\n@method_decorator([login_required], name='dispatch')\nclass NoteAttachmentDownloadView(View): # PR2021-03-17\n\n def get(self, request, pk_int):\n logger.debug(' ============= NoteAttachmentDownloadView ============= ')\n logger.debug('pk_int: ' + str(pk_int))\n # download file from server\n response = None\n\n if pk_int:\n attachment = stud_mod.Noteattachment.objects.get_or_none(pk=pk_int)\n logger.debug('attachment' + str(attachment))\n if attachment:\n file = attachment.file\n logger.debug('file: ' + str(file) + ' ' + str(type(file)))\n file_url = file.url\n logger.debug('file_url: ' + str(file_url) + ' ' + str(type(file_url)))\n\n\n if response:\n return response\n else:\n logger.debug('HTTP_REFERER: ' + str(request.META.get('HTTP_REFERER')))\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n# - end of DownloadPublishedFile\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectValidateAllView(View): # PR2021-07-24\n\n def post(self, request):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectValidateAllView ============= ')\n\n # function validates studentsubject records of all students of this dep PR2021-07-10\n\n update_wrap = {}\n\n# - get permit - no permit necessary\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_json from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n # upload_dict: {'studsubj_validate': {'get': True}}\n\n# ----- get selected examyear, school and department from usersettings\n sel_examyear, sel_school, sel_department, sel_level, may_editNIU, msg_listNIU = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n if logging_on:\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug(' sel_level: ' + str(sel_level))\n\n# +++ validate subjects of all students of this dep, used to update studsubj table\n # TODO to speed up: get info in 1 request, no msg_text\n crit = Q(school=sel_school) & \\\n Q(department=sel_department) & \\\n Q(deleted=False)\n\n if sel_level:\n crit.add(Q(level=sel_level), crit.connector)\n\n students = stud_mod.Student.objects.filter(crit)\n if logging_on:\n logger.debug(' students: ' + str(students))\n\n if students:\n validate_studsubj_list = []\n for student in students:\n\n if logging_on:\n logger.debug('----student: ' + str(student))\n\n # validate_studentsubjects_no_msg returns True when there is an error PR2022-08-25\n no_error = not stud_val.validate_studentsubjects_no_msg(student, 'nl')\n\n if (not student.subj_composition_checked) or \\\n (student.subj_composition_checked and student.subj_composition_ok != no_error):\n setattr(student, 'subj_composition_checked', True)\n setattr(student, 'subj_composition_ok', no_error)\n # dont update modified by\n student.save()\n if logging_on:\n logger.debug(' student.save no_error: ' + str(no_error))\n\n if not no_error:\n if student.pk not in validate_studsubj_list:\n validate_studsubj_list.append(student.pk)\n\n if logging_on:\n logger.debug(' no_error: ' + str(no_error))\n\n if validate_studsubj_list:\n update_wrap['validate_studsubj_list'] = validate_studsubj_list\n if logging_on:\n logger.debug(' update_wrap: ' + str(update_wrap))\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentsubjectValidateAllView\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectValidateTestView(View):\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectValidateTestView ============= ')\n\n # function validates studentsubject records after opening modal, subjects are in list PR2021-08-17 PR2021-08-31\n # Note: don't filter on allowed, it will skip not-allowed subjects and give incorrect validation\n\n update_wrap = {'is_test': True}\n\n# - get permit - no permit necessary\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n\n# ----- get selected examyear, school and department from usersettings\n # PR2022-12-23 debug: don't filter on allowed, it will skip not-allowed subjects and give incorrect validation\n sel_examyear, sel_school, sel_department, sel_level, may_editNIU, msg_listNIU = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n# +++ validate subjects of one student, used in modal\n student_pk = upload_dict .get('student_pk')\n studsubj_dictlist = upload_dict.get('studsubj_dictlist')\n\n if logging_on:\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug(' student_pk: ' + str(student_pk) + ' ' + str(type(student_pk)))\n logger.debug(' studsubj_dictlist: ' + str(studsubj_dictlist))\n \"\"\"\n studsubj_dictlist: [\n {'tobecreated': True, 'tobedeleted': False, 'tobechanged': False, 'schemeitem_id': 20635, 'studsubj_id': None, 'subj_id': 2641, 'subj_code': 'ak', 'is_extra_counts': False, 'is_extra_nocount': False}, \n {'tobecreated': True, 'tobedeleted': False, 'tobechanged': False, 'schemeitem_id': 20231, 'studsubj_id': None, 'subj_id': 2637, 'subj_code': 'sk', 'is_extra_counts': False, 'is_extra_nocount': False}, \n {'tobecreated': True, 'tobedeleted': False, 'tobechanged': False, 'schemeitem_id': 20420, 'studsubj_id': None, 'subj_id': 2647, 'subj_code': 'asw', 'is_extra_counts': False, 'is_extra_nocount': False}, \n \n \"\"\"\n if student_pk:\n student = stud_mod.Student.objects.get_or_none(id=student_pk)\n if logging_on:\n logger.debug(' sel_school.pk: ' + str(sel_school.pk))\n logger.debug(' sel_department.pk: ' + str(sel_department.pk))\n logger.debug(' student: ' + str(student))\n\n if student:\n msg_html = stud_val.validate_studentsubjects_TEST(student, studsubj_dictlist, user_lang)\n if msg_html:\n update_wrap['studsubj_validate_html'] = msg_html\n if logging_on:\n logger.debug('msg_html' + str(msg_html))\n\n if logging_on:\n logger.debug('update_wrap' + str(update_wrap))\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n\n# - end of StudentsubjectValidateTestView\n\n#####################################################################################\n\n@method_decorator([login_required], name='dispatch')\nclass SendEmailVerifcodeView(View): # PR2021-07-26 PR2022-04-18\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= SendEmailVerifcodeView ============= ')\n\n update_wrap = {}\n\n class_str = 'border_bg_transparent'\n\n# - get user_lang\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n \"\"\"\n upload_dict: {'table': 'grade', 'mode': 'submit_save', 'form': 'ex2', 'verificationcode': '', 'verificationkey': None, 'auth_index': 2, 'now_arr': [2022, 4, 18, 11, 21]}\n upload_dict: {'table': 'studsubj', 'form': 'ex4', 'examperiod': 2, 'now_arr': [2022, 5, 31, 7, 29], 'mode': 'request_verif'}\n upload_dict: {'table': 'grade', 'form': 'ex5', 'auth_index': 2, 'now_arr': [2022, 6, 12, 18, 51]}\n\n \"\"\"\n# - get permit\n has_permit = False\n req_usr = request.user\n mode = upload_dict.get('mode')\n table = upload_dict.get('table')\n form = upload_dict.get('form')\n\n if table == 'result':\n sel_page = 'page_result'\n elif table == 'grade':\n sel_page = 'page_grade'\n elif mode == 'publish_exam':\n sel_page = 'page_exams'\n elif mode == 'submit_grade_exam':\n sel_page = 'page_wolf'\n else:\n sel_page ='page_studsubj'\n\n if logging_on:\n logger.debug(' mode: ' + str(mode))\n logger.debug(' sel_page: ' + str(sel_page))\n\n if req_usr and req_usr.country and req_usr.schoolbase:\n permit_list = acc_prm.get_permit_list(sel_page, req_usr)\n\n if logging_on:\n logger.debug(' permit_list: ' + str(permit_list))\n\n requsr_usergroup_list, allowed_sections_dictNIU, allowed_clusters_listNIU, sel_examyear_instanceNIU = acc_prm.get_allowedusergrouplist_allowedsectionsdict_allowedclusterlist(req_usr)\n\n if permit_list and requsr_usergroup_list:\n if 'auth1' in requsr_usergroup_list or 'auth2' in requsr_usergroup_list:\n if table == 'result':\n has_permit = 'permit_submit_ex5' in permit_list\n elif table == 'grade':\n has_permit = 'permit_submit_grade' in permit_list\n elif mode == 'publish_exam':\n has_permit = 'permit_publish_exam' in permit_list\n elif mode == 'submit_grade_exam':\n has_permit = 'permit_submit_exam' in permit_list\n else:\n has_permit = 'permit_approve_subject' in permit_list\n\n if logging_on:\n logger.debug(' mode: ' + str(mode))\n logger.debug(' sel_page: ' + str(sel_page))\n logger.debug(' has_permit: ' + str(has_permit))\n\n if has_permit:\n sel_level = None\n\n if mode == 'publish_exam':\n formname = 'ete_exam'\n sel_school, sel_department = None, None\n sel_examyear, msg_list = acc_view.get_selected_examyear_from_usersetting(request)\n\n elif mode == 'submit_grade_exam':\n formname = 'grade_exam'\n sel_examyear, sel_school, sel_department, sel_level, may_edit, msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n else:\n formname = upload_dict.get('form')\n sel_examyear, sel_school, sel_department, sel_level, may_edit, msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if not msg_list:\n try:\n # create _verificationcode and key, store in usersetting, send key to client, set expiration to 30 minutes\n verif_key, verif_code = af.create_verificationcode(formname, request)\n update_wrap['verificationkey'] = verif_key\n\n if logging_on:\n logger.debug(' verif_key: ' + str(verif_key))\n logger.debug(' verif_code: ' + str(verif_code))\n\n\n subject = str(_('AWP-online verificationcode'))\n from_email = 'AWP-online '\n\n if mode == 'publish_exam':\n template_str = 'email_send_verifcode_exam.html'\n elif mode == 'submit_grade_exam':\n template_str = 'email_send_verifcode_grade_exam.html'\n else:\n template_str = 'send_verifcode_exform_email.html'\n\n ex_form = ''\n if form == 'ex1':\n ex_form = _('Ex1 form')\n elif form =='ex2':\n ex_form = _('Ex2 form')\n elif form =='ex2a':\n ex_form = _('Ex2A form')\n elif form =='ex4':\n ex_form = _('Ex4 form')\n elif form =='ex5':\n ex_form = _('Ex5 form')\n elif form =='ex4ep3':\n ex_form = _('Ex4 form 3rd exam period')\n elif form == 'comp':\n ex_form = _('compensation form')\n\n message = render_to_string(template_str, {\n 'user': request.user,\n 'examyear': sel_examyear,\n 'school': sel_school,\n 'ex_form': ex_form,\n 'department': sel_department,\n 'level': sel_level,\n 'verificationcode': verif_code\n })\n if logging_on:\n logger.debug('message: ' + str(message))\n\n # PR2018-04-25 arguments: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)\n mail_count = send_mail(subject, message, from_email, [req_usr.email], fail_silently=False)\n if logging_on:\n logger.debug('mail_count: ' + str(mail_count))\n\n if not mail_count:\n class_str = 'border_bg_invalid'\n msg_list += (\"

\",\n str(_('An error occurred')),\n str(_('The email has not been sent.')), '

')\n else:\n # - return message 'We have sent an email to user'\n class_str = 'border_bg_transparent'\n if mode == 'publish_exam':\n msg_txt = str(_('Enter the verification code and click the ENTER key to publish the exams.'))\n else:\n btn_txt = _('Submit compensation form') if form == 'comp' else _('Submit Ex form')\n frm_txt = _('compensations') if form == 'comp' else _('Ex')\n msg_txt = str(_(\"Enter the verification code and click '%(btn)s' or the ENTER key to submit the %(frm)s form.\")\n % {'btn': btn_txt, 'frm': frm_txt})\n\n msg_list += (\"

\",\n str(_(\"We have sent an email with a 6 digit verification code to the email address:\")), '

',\n \"

\", req_usr.email, '

',\n \"

\",\n msg_txt,\n '

')\n\n except Exception as e:\n class_str = 'border_bg_invalid'\n msg_list += (\"

\",\n str(_('An error occurred')),':
', str(e), '
',\n str(_('The email has not been sent.')),'

')\n\n if msg_list:\n msg_wrap_start = [\"
\"]\n msg_wrap_end = ['

']\n\n msg_html = ''.join(msg_wrap_start + msg_list + msg_wrap_end)\n\n # - add msg_dict to update_wrap\n update_wrap['approve_msg_html'] = msg_html\n\n # - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n\n# - end of SendEmailVerifcodeView\n\n\n#####################################################################################\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectApproveOrSubmitEx1Ex4View(View): # PR2021-07-26 PR2022-05-30 PR2023-01-10\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectApproveOrSubmitEx1Ex4View ============= ')\n\n ################################\n def get_studsubject_rows(sel_examperiod, sel_school, sel_department, sel_level, is_submit):\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug('----- get_studsubject_rows -----')\n logger.debug(' is_submit: ' + str(is_submit))\n\n # PR2023-02-12 PR2023-07-13\n studsubject_rows = []\n err_txt = None\n\n if (sel_examperiod and sel_school and sel_department):\n try:\n if sel_examperiod == 2:\n auth_clause = \"studsubj.reex_auth1by_id AS auth1by_id, studsubj.reex_auth2by_id AS auth2by_id, studsubj.reex_published_id AS published_id,\"\n elif sel_examperiod == 3:\n auth_clause = \"studsubj.reex3_auth1by_id AS auth1by_id, studsubj.reex3_auth2by_id AS auth2by_id, studsubj.reex3_published_id AS published_id,\"\n else:\n auth_clause = \"studsubj.subj_auth1by_id AS auth1by_id, studsubj.subj_auth2by_id AS auth2by_id, studsubj.subj_published_id AS published_id,\"\n\n sql_list = [\n \"SELECT stud.id AS stud_id, stud.idnumber AS idnr, stud.examnumber AS exnr, stud.gender,\",\n \"stud.lastname AS ln, stud.firstname AS fn, stud.prefix AS pref, stud.classname AS class, \",\n \"stud.level_id, lvl.name AS lvl_name, lvl.abbrev AS lvl_abbrev, sct.abbrev AS sct_abbrev, \",\n\n \"CASE WHEN stud.subj_composition_ok OR stud.subj_dispensation\",\n # PR2023-02-17 skip composition check when iseveningstudent, islexstudent or partial_exam\n \"OR stud.iseveningstudent OR stud.islexstudent OR stud.partial_exam\",\n \"THEN FALSE ELSE TRUE END AS composition_error,\",\n\n \"stud.regnumber AS regnr, stud.diplomanumber AS dipnr, stud.gradelistnumber AS glnr,\",\n \"stud.iseveningstudent AS evest, stud.islexstudent AS lexst,\",\n \"stud.bis_exam AS bisst, stud.partial_exam AS partst, stud.withdrawn AS wdr,\",\n\n \"studsubj.id AS studsubj_id, studsubj.tobedeleted AS studsubj_tobedeleted,\",\n\n auth_clause,\n \"subj.id AS subj_id, subjbase.code AS subj_code\",\n\n \"FROM students_studentsubject AS studsubj\",\n \"INNER JOIN students_student AS stud ON (stud.id = studsubj.student_id)\",\n \"INNER JOIN subjects_schemeitem AS si ON (si.id = studsubj.schemeitem_id)\",\n \"INNER JOIN subjects_subject AS subj ON (subj.id = si.subject_id)\",\n \"INNER JOIN subjects_subjectbase AS subjbase ON (subjbase.id = subj.base_id)\",\n\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = stud.level_id)\",\n \"LEFT JOIN subjects_sector AS sct ON (sct.id = stud.sector_id)\",\n\n \"INNER JOIN schools_school AS school ON (school.id = stud.school_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = school.examyear_id)\",\n \"INNER JOIN schools_department AS dep ON (dep.id = stud.department_id)\",\n\n \"WHERE school.id = \" + str(sel_school.pk) + \"::INT\",\n \"AND dep.id = \" + str(sel_department.pk) + \"::INT\",\n\n \"AND NOT stud.deleted AND NOT studsubj.deleted\"\n ]\n # filter reex subjects when ex4 or ex4ep3\n if sel_examperiod == 2:\n sql_list.append(\"AND studsubj.has_reex\")\n elif sel_examperiod == 3:\n sql_list.append(\"AND studsubj.has_reex03\")\n\n # - may also filter on level when submitting Ex form\n # PR2023-02-12 request MPC: must be able to submit per level tkl / pkl/pbl\n\n # PR2023-02-19 debug: VWO didnt show records, because of filter sel_lvlbase_pk=5\n # solved bij adding: if sel_department.level_req\n\n if sel_department.level_req and sel_level:\n sql_list.append(''.join((\"AND (lvl.base_id = \", str(sel_level.base_id), \"::INT)\")))\n\n # - other filters are only allowed when approving, not when is_submit\n if not is_submit:\n # - get selected values from usersetting selected_dict\n sel_sctbase_pk, sel_subject_pk, sel_cluster_pk = None, None, None\n selected_dict = acc_prm.get_usersetting_dict(c.KEY_SELECTED_PK, request)\n if selected_dict:\n sel_sctbase_pk = selected_dict.get(c.KEY_SEL_SCTBASE_PK)\n sel_subject_pk = selected_dict.get(c.KEY_SEL_SUBJECT_PK)\n sel_cluster_pk = selected_dict.get(c.KEY_SEL_CLUSTER_PK)\n\n if sel_sctbase_pk:\n sql_list.append(''.join((\"AND sct.base_id = \", str(sel_sctbase_pk), \"::INT\")))\n\n # - filter on selected subject, not when is_submit TODO to be changed to subjectbase\n if sel_subject_pk:\n sql_list.append(''.join((\"AND subj.id = \", str(sel_subject_pk), \"::INT\")))\n\n # - filter on selected sel_cluster_pk, not when is_submit\n if sel_cluster_pk and not is_submit:\n sql_list.append(''.join((\"AND (studsubj.cluster_id = \", str(sel_cluster_pk), \"::INT)\")))\n\n # - get allowed_sections_dict from request\n userallowed_sections_dict = acc_prm.get_userallowed_sections_dict_from_request(request)\n # allowed_sections_dict: {'2': {'1': {'4': [117, 114], '5': [], '-9': [118, 121]}}} \n\n # - filter on allowed depbases, levelbase, subjectbases, not when is_submit PR2023-02-18\n # TODO when approve: filter on all allowed, when submit: only filter on allowed lvlbase\n # dont filter on allowed subjects and allowed clusters, but do filter on allowed lvlbases'\n userallowed_schoolbase_dict, userallowed_depbases_pk_arr = acc_prm.get_userallowed_schoolbase_dict_depbases_pk_arr(\n userallowed_sections_dict, sel_school.base_id)\n allowed_depbase_dict, allowed_lvlbase_pk_arr = acc_prm.get_userallowed_depbase_dict_lvlbases_pk_arr(\n userallowed_schoolbase_dict, sel_department.base_id)\n\n allowed_lvlbase_clause = acc_prm.get_sqlclause_allowed_lvlbase_from_lvlbase_pk_arr(\n allowed_lvlbase_pk_arr)\n\n if logging_on:\n logger.debug(' allowed_sections_dict: ' + str(userallowed_sections_dict))\n logger.debug(' userallowed_schoolbase_dict: ' + str(userallowed_schoolbase_dict))\n logger.debug(' allowed_depbase_dict: ' + str(allowed_depbase_dict))\n logger.debug(' allowed_lvlbase_pk_arr: ' + str(allowed_lvlbase_pk_arr))\n logger.debug(' allowed_lvlbase_clause: ' + str(allowed_lvlbase_clause))\n\n if allowed_lvlbase_clause:\n sql_list.append(allowed_lvlbase_clause)\n\n if logging_on and False:\n for sql_txt in sql_list:\n logger.debug(' > ' + str(sql_txt))\n\n # - don't filter on allowed clusters PR2023-02-18\n # PR2022-04-20 tel Bruno New Song: chairperson is also examiner.\n # must be able to approve all subjects as chairperson.\n # therefore: don't filter on allowed clusters when requsr is chairperson or secretary\n\n sql_list.append(\"ORDER BY stud.lastname, stud.firstname\")\n\n sql = ' '.join(sql_list)\n with connection.cursor() as cursor:\n cursor.execute(sql)\n studsubject_rows = af.dictfetchall(cursor)\n\n if logging_on:\n for row in studsubject_rows:\n logger.debug(' row: ' + str(row))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n err_txt = acc_prm.errhtml_error_occurred_no_border(e)\n\n return studsubject_rows, err_txt\n ################################\n\n # function sets auth and publish of studentsubject records of current department / level # PR2021-07-25\n update_wrap = {}\n requsr_auth = None\n msg_html = None\n\n# - get user_lang\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get permit\n # \n # only users with role > student and perm_edit can change student data\n # only school that is requsr_school can be changed\n # current schoolbase can be different from request.user.schoolbase (when role is insp, admin, system)\n # only if country/examyear/school/student not locked, examyear is published and school is activated\n\n has_permit = False\n req_usr = request.user\n if req_usr and req_usr.country and req_usr.schoolbase:\n permit_list = acc_prm.get_permit_list('page_studsubj', req_usr)\n if logging_on:\n logger.debug(' permit_list: ' + str(permit_list))\n\n if permit_list and 'permit_approve_subject' in permit_list:\n # msg_err is made on client side. Here: just skip if user has no or multiple functions\n\n # PR2023-02-12 was: requsr_usergroup_list, allowed_sections_dictNIU, allowed_clusters_list, sel_examyear_instance = acc_prm.get_allowedusergrouplist_allowedsectionsdict_allowedclusterlist(req_usr)\n userallowed_instance = acc_prm.get_userallowed_instance_from_user_instance(req_usr)\n requsr_usergroup_list = acc_prm.get_usergroup_list(userallowed_instance)\n if logging_on:\n logger.debug(' requsr_usergroup_list: ' + str(requsr_usergroup_list))\n\n is_auth1 = (requsr_usergroup_list and 'auth1' in requsr_usergroup_list)\n is_auth2 = (requsr_usergroup_list and 'auth2' in requsr_usergroup_list)\n if is_auth1 + is_auth2 == 1:\n if is_auth1:\n requsr_auth = 'auth1'\n elif is_auth2:\n requsr_auth = 'auth2'\n if requsr_auth:\n has_permit = True\n\n if logging_on:\n logger.debug(' has_permit approve_subject: ' + str(has_permit))\n\n if not has_permit:\n msg_html = acc_prm.err_html_no_permit() # default: 'to perform this action')\n else:\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n\n# ----- get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - examyear, schoolbase, school, depbase or department is None\n # - country, examyear or school is locked\n # - not requsr_same_school,\n # - not sel_examyear.published,\n # not af.is_allowed_depbase_requsr or not af.is_allowed_depbase_school,\n\n sel_examyear, sel_school, sel_department, sel_level, may_edit, err_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n # TODO: get sel_examperiod as part from get_selected_ey_school_dep_lvl_from_usersetting\n examperiod = upload_dict.get('examperiod')\n prefix = 'reex3_' if examperiod == 3 else 'reex_' if examperiod == 2 else 'subj_'\n form_name = 'ex4ep3' if examperiod == 3 else 'ex4' if examperiod == 2 else 'ex1'\n\n if examperiod not in (1, 2, 3):\n msg_txt = gettext('The exam period is not valid.')\n msg_html = ''.join((\"
\", msg_txt, \"
\"))\n err_list.append(msg_html)\n\n if err_list:\n msg_html = '
'.join(err_list)\n else:\n\n # - get selected mode. Modes are 'approve_test', 'approve_save', 'approve_reset', 'submit_test' 'submit_save'\n mode = upload_dict.get('mode')\n is_approve = True if mode in ('approve_test', 'approve_save', 'approve_reset') else False\n is_submit = True if mode in ('submit_test', 'submit_save') else False\n is_reset = True if mode == 'approve_reset' else False\n is_test = True if mode in ('approve_test', 'submit_test') else False\n\n if logging_on:\n logger.debug(' upload_dict ' + str(upload_dict))\n logger.debug(' mode: ' + str(mode))\n logger.debug(' examperiod: ' + str(examperiod))\n logger.debug(' prefix: ' + str(prefix))\n logger.debug(' form_name: ' + str(form_name))\n\n# - when mode = submit_submit: check verificationcode.\n verification_is_ok = True\n if is_submit and not is_test:\n upload_dict['form'] = form_name\n verification_is_ok, verif_msg_html = af.check_verifcode_local(upload_dict, request)\n if verif_msg_html:\n msg_html = verif_msg_html\n if verification_is_ok:\n update_wrap['verification_is_ok'] = True\n\n if verification_is_ok:\n #sel_lvlbase_pk, sel_sctbase_pk, sel_subject_pk, sel_cluster_pk, sel_student_pk = None, None, None, None, None\n # don't filter on sel_sctbase_pk, sel_subject_pk, sel_cluster_pk or allowed when is_submit\n # PR2023-01-10 may filter on level, so MPC TKL can submit their own Ex1\n\n# +++ get selected studsubj_rows\n # PR2023-01-09 new approach:\n # - include published studsubjects\n # - include tobedeleted studsubjects\n # when a subject is set 'tobedeleted', the published info is removed, to show up when submitted\n\n # when submit: don't filter on sector, subject or cluster\n # PR2023-02-12 request MPC: must be able to submit per level tkl / pkl/pbl\n # also filter on level when submitting Ex form\n\n studsubject_rows, err_txt = get_studsubject_rows(\n sel_examperiod=examperiod,\n sel_school=sel_school,\n sel_department=sel_department,\n sel_level=sel_level,\n is_submit=is_submit\n )\n\n if err_txt:\n msg_html = ''.join((\"
\", err_txt, \"
\"))\n\n else:\n count_dict = {}\n\n# +++ create new published_instance. Only save it when it is not a test\n # file_name will be added after creating Ex-form\n published_instance = None\n published_instance_pk = None\n published_instance_filename = '---'\n published_instance_file_url = '#'\n if is_submit and not is_test:\n now_arr = upload_dict.get('now_arr')\n\n published_instance = create_published_Ex1_Ex4_instance(\n sel_school=sel_school,\n sel_department=sel_department,\n sel_level=sel_level,\n examperiod=examperiod,\n now_arr=now_arr,\n request=request)\n if published_instance:\n published_instance_pk = published_instance.pk\n published_instance_filename = published_instance.filename\n if published_instance.file:\n published_instance_file_url = published_instance.file.url\n\n studsubj_rows = []\n\n row_count = 0\n student_pk_list, student_committed_list, student_saved_list= [],[], []\n student_composition_error_list, student_composition_error_namelist, student_saved_error_list = [],[], []\n\n # PR2022-12-30 instead of updating each studsubj instance separately, create list of tobesaved studsubj_pk\n # and batch update at the end\n tobesaved_studsubj_pk_list = []\n\n # PR2023-05-02 debug: email Pien van Dijk ETE: student gets deleted,\n # apparently after deleting subject.\n # was: PR2023-01-12 create list of tobedeleted student_pk and batch delete at the end\n # tobedeleted_student_pk_list = []\n\n# +++++ loop through studsubject_rows +++++\n for studsubj in studsubject_rows:\n\n if logging_on and False:\n logger.debug('............ ')\n logger.debug(' ' + str(studsubj))\n\n row_count += 1\n\n is_committed = False\n is_saved = False\n\n if is_approve:\n is_committed, is_saved = approve_studsubj(\n studsubj=studsubj,\n requsr_auth=requsr_auth,\n prefix=prefix,\n is_test=is_test,\n is_reset=is_reset,\n count_dict=count_dict,\n request=request\n )\n\n elif is_submit:\n is_published, is_committed, is_saved = submit_studsubj(\n studsubj=studsubj,\n prefix=prefix,\n is_test=is_test,\n count_dict=count_dict\n )\n\n if is_saved:\n studsubj_pk = studsubj.get('studsubj_id')\n if studsubj_pk:\n tobesaved_studsubj_pk_list.append(studsubj_pk)\n\n # - add student_pk to student_pk_list, student_committed_list or student_saved_list\n # this is used to count the students in msg: '4 students with 39 subjects are added'\n # after the loop the totals are added to count_dict['student_count'] etc\n # PR2022-08-25 submit not allowed when subject composition not correct and no dispensation\n student_pk = studsubj.get('stud_id')\n if logging_on and False:\n logger.debug(' student_pk: ' + str(student_pk))\n\n if student_pk not in student_composition_error_list:\n if studsubj.get('composition_error'):\n student_composition_error_list.append(student_pk)\n student_composition_error_namelist.append(', '.join((studsubj.get('ln', '-'), studsubj.get('fn', '-'))))\n\n if student_pk not in student_pk_list:\n student_pk_list.append(student_pk)\n\n # PR2023-05-02 debug: email Pien van Dijk ETE: student gets deleted,\n # apparently after deleting subject.\n # was:\n # if studsubj.get('studsubj_tobedeleted') and student_pk not in tobedeleted_student_pk_list:\n # tobedeleted_student_pk_list.append(student_pk)\n\n if is_committed:\n if student_pk not in student_committed_list:\n student_committed_list.append(student_pk)\n if is_saved:\n if student_pk not in student_saved_list:\n student_saved_list.append(student_pk)\n\n# +++++ end of loop through studsubjects\n\n if logging_on:\n logger.debug(' tobesaved_studsubj_pk_list: ' + str(tobesaved_studsubj_pk_list))\n\n auth_missing_count = count_dict.get('auth_missing', 0)\n double_approved_count = count_dict.get('double_approved', 0)\n\n student_composition_error_count = len(student_composition_error_list)\n student_committed_count = len(student_committed_list)\n\n test_has_failed = False\n if not row_count:\n test_has_failed = True\n\n elif is_submit and auth_missing_count:\n test_has_failed = True\n elif is_submit and double_approved_count:\n test_has_failed = True\n elif is_submit and student_composition_error_count:\n test_has_failed = True\n\n elif not student_committed_count:\n # PR2023-07-13 must be able to resubmit Ex4 form 3rd period\n if examperiod != c.EXAMPERIOD_THIRD:\n test_has_failed = True\n\n count_dict['count'] = row_count\n count_dict['student_count'] = len(student_pk_list)\n count_dict['student_composition_error_count'] = student_composition_error_count\n count_dict['student_committed_count'] = student_committed_count\n count_dict['student_saved_count'] = len(student_saved_list)\n\n if logging_on:\n logger.debug(' count_dict: ' + str(count_dict))\n\n update_wrap['approve_count_dict'] = count_dict\n\n# +++++ create Ex1 Ex4 form\n is_saved_to_disk = False\n if row_count:\n saved_studsubj_pk_list = []\n if not is_test:\n if is_submit:\n is_saved_to_disk = self.create_ex1_ex4_form(\n published_instance=published_instance,\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n sel_level=sel_level,\n examperiod=examperiod,\n prefix=prefix,\n save_to_disk=True,\n request=request,\n user_lang=user_lang\n )\n if is_saved_to_disk and published_instance.file:\n published_instance_file_url = published_instance.file.url\n\n if logging_on:\n logger.debug(' published_instance_file_url: ' + str(published_instance_file_url))\n\n# +++++ batch save approval / published PR2023-01-10\n if logging_on:\n logger.debug(' tobesaved_studsubj_pk_list: ' + str(tobesaved_studsubj_pk_list))\n\n if tobesaved_studsubj_pk_list:\n err_html = None\n if is_approve:\n saved_studsubj_pk_list, err_html = self.save_approved_in_studsubj(tobesaved_studsubj_pk_list, is_reset, prefix, requsr_auth, request.user)\n elif is_submit:\n saved_studsubj_pk_list, err_html = self.save_published_in_studsubj(tobesaved_studsubj_pk_list, prefix, published_instance.pk)\n\n if err_html:\n msg_html = \"
\" + err_html + \"
\"\n\n if logging_on:\n logger.debug(' saved_studsubj_pk_list: ' + str(saved_studsubj_pk_list))\n\n # PR2023-05-02 debug: email Pien van Dijk ETE: student gets deleted,\n # apparently after deleting subject.\n # cause: self.set_student_deleted(tobedeleted_student_pk_list, request)\n # was: if is_submit and tobedeleted_student_pk_list:\n # self.set_student_deleted(tobedeleted_student_pk_list, request)\n\n # - delete the 'tobedeleted' rows from StudSubject, only after submitting and no test!\n\n # PR2022-12-30 instead of updating each studsubj instance separately, create list of tobesaved studsubj_pk\n # list is created outside this function, when is_saved = True\n\n # TODO put back 'tobedeleted' functions\n #self.delete_tobedeleted_from_studsubj(\n # published_instance=published_instance,\n # sel_examyear=sel_examyear,\n # sel_school=sel_school,\n # sel_department=sel_department,\n # request=request\n #)\n\n if logging_on:\n logger.debug(' saved_studsubj_pk_list: ' + str(saved_studsubj_pk_list))\n\n # - add rows to studsubj_rows, to be sent back to page\n # to increase speed, dont create return rows but refresh page after finishing this request\n if saved_studsubj_pk_list:\n studsubj_rows = create_studentsubject_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base if sel_school else None,\n sel_depbase=sel_department.base if sel_department else None,\n append_dict={},\n request=request,\n requsr_same_school=True, # when requsr_same_school=True, it includes students without studsubjects\n studsubj_pk_list=saved_studsubj_pk_list\n )\n\n if (studsubj_rows):\n update_wrap['updated_studsubj_approve_rows'] = studsubj_rows\n\n if is_test:\n if not test_has_failed:\n update_wrap['test_is_ok'] = True\n\n # > end of if row_count\n\n# - create msg_html with info of rows\n msg_html = self.create_ex1_ex4_msg_list(\n sel_department=sel_department,\n sel_level=sel_level,\n count_dict=count_dict,\n requsr_auth=requsr_auth,\n is_approve=is_approve,\n is_test=is_test,\n is_saved_to_disk=is_saved_to_disk,\n examperiod=examperiod,\n published_instance_filename=published_instance_filename,\n published_instance_file_url=published_instance_file_url,\n student_composition_error_namelist=student_composition_error_namelist\n )\n\n # > end of if studsubjects\n # > end of if verification_is_ok\n # > end of 'if not err_list'\n # - add msg_html to update_wrap (this one triggers MASS_UpdateFromResponse in page studsubjcts\n update_wrap['approve_msg_html'] = msg_html\n\n # - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n # - end of StudentsubjectApproveOrSubmitEx1Ex4View.post\n\n\n def save_approved_in_studsubj(self, studsubj_pk_list, is_reset, prefix, requsr_auth, req_user):\n # PR2023-01-10\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug('----- save_approved_in_studsubj -----')\n\n saved_studsubj_pk_list = []\n err_html = None\n try:\n # prefix = 'reex3_' if examperiod == 3 else 'reex_' if examperiod == 2 else 'subj_'\n requsr_authby_field = ''.join((prefix, requsr_auth, 'by_id'))\n\n # was: setattr(studsubj, requsr_authby_field, req_user)\n # - remove authby when is_reset\n requsr_authby_value = \"NULL\" if is_reset else str(req_user.pk)\n\n sql_list = [\"UPDATE students_studentsubject\",\n \" SET\", requsr_authby_field, \"=\", requsr_authby_value,\n \" WHERE id IN (SELECT UNNEST(ARRAY\", str(studsubj_pk_list), \"::INT[]))\",\n \" AND NOT deleted\",\n \" RETURNING id, \", requsr_authby_field]\n\n sql = ' '.join(sql_list)\n\n if logging_on:\n logger.debug(' sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n\n rows = cursor.fetchall()\n if rows:\n for row in rows:\n if logging_on:\n logger.debug(' row: ' + str(row))\n saved_studsubj_pk_list.append(row[0])\n\n if logging_on:\n logger.debug(' saved_studsubj_pk_list: ' + str(saved_studsubj_pk_list))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n err_html = ''.join((\n str(_('An error occurred')), ':
', ' ', str(e), '
',\n str(_('The subjects could not be approved.'))\n ))\n\n if logging_on:\n logger.debug(' err_html: ' + str(err_html))\n\n return saved_studsubj_pk_list, err_html\n# - end of save_approved_in_studsubj\n\n def set_student_deletedNIU(self, student_pk_list, request):\n # PR2023-01-12\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug('----- set_student_deleted -----')\n logger.debug(' student_pk_list: ' + str(student_pk_list))\n\n deleted_student_pk_list = []\n err_html = None\n\n try:\n\n modifiedby_pk_str = str(request.user.pk)\n modifiedat_str = str(timezone.now())\n\n sql_keys = {'st_arr': student_pk_list}\n\n sql_list = [\"UPDATE students_student\",\n \"SET deleted = TRUE, tobedeleted=FALSE,\",\n\n \"modifiedby_id = \", modifiedby_pk_str, \", modifiedat = '\", modifiedat_str, \"'\",\n \"WHERE id IN (SELECT UNNEST(%(st_arr)s::INT[]))\",\n\n \"RETURNING id;\"]\n\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = cursor.fetchall()\n if rows:\n for row in rows:\n deleted_student_pk_list.append(row[0])\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n err_html = ''.join((\n str(_('An error occurred')), ':
', ' ', str(e), '
',\n str(_('The subjects could not be approved.'))\n ))\n\n if logging_on:\n logger.debug(' deleted_student_pk_list: ' + str(deleted_student_pk_list))\n\n return deleted_student_pk_list, err_html\n# - end of set_student_deleted\n\n def save_published_in_studsubj(self, studsubj_pk_list, prefix, published_pk):\n # PR2022-12-31 PR2023-01-10\n\n \"\"\"\n # when is_approve:\n # requsr_authby_field = prefix + requsr_auth + 'by'\n # # PR2022-12-30 was: setattr(studsubj, requsr_authby_field, req_user)\n\n # submit:\n published = getattr(studsubj, prefix + 'published')\n put published_id in field subj_published:\n # setattr(studsubj, prefix + 'published', published_instance)\n # -\n \"\"\"\n\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug('----- save_published_in_studsubj -----')\n\n saved_studsubj_pk_list = []\n err_html = None\n\n try:\n published_field = prefix + 'published_id'\n sql_keys = {'publ_pk': published_pk, 'sb_arr': studsubj_pk_list}\n\n sql_list = [\"UPDATE students_studentsubject AS studsubj\",\n \"SET\", published_field, \"= %(publ_pk)s::INT,\",\n \"deleted=tobedeleted, tobedeleted=FALSE, tobechanged=FALSE,\",\n \"prev_auth1by_id=NULL, prev_auth2by_id=NULL, prev_published_id=NULL\",\n \"WHERE studsubj.id IN (SELECT UNNEST(%(sb_arr)s::INT[]))\",\n \"AND studsubj.deleted = FALSE\",\n\n \"RETURNING id;\"]\n\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = cursor.fetchall()\n if rows:\n for row in rows:\n saved_studsubj_pk_list.append(row[0])\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n err_html = ''.join((\n str(_('An error occurred')), ':
', ' ', str(e), '
',\n str(_('The subjects could not be approved.'))\n ))\n\n if logging_on:\n logger.debug(' saved_studsubj_pk_list: ' + str(saved_studsubj_pk_list))\n\n return saved_studsubj_pk_list, err_html\n # - end of save_published_in_studsubj\n\n def delete_tobedeleted_from_studsubj(self, published_instance, sel_examyear, sel_school, sel_department, request):\n # PR2021-09-30\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- delete_tobedeleted_from_studsubj -----')\n\n studentsubjects = stud_mod.Studentsubject.objects.filter(\n subj_published=published_instance,\n student__school__examyear=sel_examyear,\n student__school=sel_school,\n student__department=sel_department,\n tobedeleted=True\n )\n if logging_on:\n logger.debug('studentsubjects: ' + str(studentsubjects))\n\n if studentsubjects:\n for studsubj in studentsubjects:\n studsubj.delete(request=request)\n if logging_on:\n logger.debug('deleted _studsubj: ' + str(studsubj))\n# - end of delete_tobedeleted_from_studsubj\n\n def create_ex1_ex4_msg_list(self, sel_department, sel_level, count_dict, requsr_auth, is_approve, is_test, is_saved_to_disk,\n examperiod, published_instance_filename, published_instance_file_url, student_composition_error_namelist):\n # PR2022-08-25 PR2023-01-15\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- create_ex1_ex4_msg_list -----')\n logger.debug(' count_dict: ' + str(count_dict))\n logger.debug(' is_test: ' + str(is_test))\n\n \"\"\"\n PR2023-07-12\n count_dict: {'count': 1, 'student_count': 1, 'student_committed_count': 0, 'student_saved_count': 0, \n 'already_published': 1, 'double_approved': 0, 'studsubj_tobedeleted': 0, \n 'committed': 0, 'saved': 0, 'saved_error': 0, 'reset': 0,\n 'already_approved': 0, 'auth_missing': 0, 'student_composition_error_count': 0}\n \"\"\"\n\n count = count_dict.get('count', 0)\n student_count = count_dict.get('student_count', 0)\n committed = count_dict.get('committed', 0)\n student_committed_count = count_dict.get('student_committed_count', 0)\n saved = count_dict.get('saved', 0)\n saved_error = count_dict.get('saved_error', 0)\n student_saved_count = count_dict.get('student_saved_count', 0)\n student_saved_error_count = count_dict.get('student_saved_error_count', 0)\n already_published = count_dict.get('already_published', 0)\n\n all_published = count and already_published == count\n\n auth_missing = count_dict.get('auth_missing', 0)\n already_approved = count_dict.get('already_approved', 0)\n double_approved = count_dict.get('double_approved', 0)\n\n studsubj_tobedeleted = count_dict.get('studsubj_tobedeleted', 0)\n\n student_composition_error_count = count_dict.get('student_composition_error_count', 0)\n\n subjects_singular = gettext('Re-examination 3rd period').lower() if examperiod == 3 else gettext(\n 'Re-examination').lower() if examperiod == 2 else gettext('Subject').lower()\n subjects_plural = gettext('Re-examinations 3rd period').lower() if examperiod == 3 else gettext(\n 'Re-examinations').lower() if examperiod == 2 else gettext('Subjects').lower()\n\n form_txt = _('Ex1') if examperiod == 1 else _('Ex4')\n\n show_msg_first_approve_by_pres_secr = False\n show_msg_frm_cannot_be_submitted = False\n show_msg_request_verifcode = False\n\n class_str = c.HTMLCLASS_border_bg_transparent\n if is_test:\n if is_approve:\n if committed:\n class_str = c.HTMLCLASS_border_bg_valid\n else:\n if all_published:\n class_str = c.HTMLCLASS_border_bg_transparent\n elif student_composition_error_count:\n class_str = c.HTMLCLASS_border_bg_invalid\n elif auth_missing or double_approved:\n class_str = c.HTMLCLASS_border_bg_invalid\n elif committed:\n class_str = c.HTMLCLASS_border_bg_valid\n else:\n class_str = c.HTMLCLASS_border_bg_invalid\n else:\n if student_saved_error_count:\n class_str = c.HTMLCLASS_border_bg_invalid\n elif student_saved_count:\n class_str = c.HTMLCLASS_border_bg_valid\n\n if logging_on:\n logger.debug(' class_str: ' + str(class_str))\n\n msg_list = []\n\n# - create warning frame with 'only candidates of the learning path' when level_req\n # PR2023-07-12 added: only when is test\n if is_test and sel_department and sel_department.level_req:\n if sel_level and sel_level.abbrev:\n abbrev = sel_level.abbrev if sel_level.abbrev else '-'\n level_txt = ''.join((\n gettext('The selection contains only %(cpt)s of the learning path: %(lvl_abbrev)s.')\n % {'cpt': gettext('Candidates').lower(), 'lvl_abbrev': abbrev},\n '
',\n gettext(\n \"Select 'All learning paths' in the vertical gray bar on the left to submit all learning paths.\")\n ))\n else:\n level_txt = ''.join((\n '', gettext('ATTENTION'), ': ',\n gettext('The selection contains the candidates of all learning paths.'), '
',\n gettext('Select a learning path in the vertical gray bar on the left to submit one learning path.')\n ))\n msg_list.extend((\"
\", level_txt, '
'))\n\n msg_list.extend((\"
\"))\n\n tobedeleted_html = ''\n if studsubj_tobedeleted:\n tobedeleted_html = ' ' + str(_('%(subj)s marked to be deleted.') % {'subj': get_subjects_are_text(examperiod, studsubj_tobedeleted)})\n\n# - create first line with 'The selection contains 4 candidates with 39 subjects'\n if is_test:\n subj_txt = get_subject_count_text(examperiod, count)\n if not count:\n msg_txt = _(\"The selection contains %(val)s.\") % {'val': subj_txt}\n else:\n stud_txt = get_student_count_text(student_count)\n msg_txt = _(\"The selection contains %(stud)s with %(subj)s.\") % {'stud': stud_txt, 'subj': subj_txt}\n msg_list.append(''.join(( \"
\", str(msg_txt), ' ', tobedeleted_html, '
')))\n\n# if students with errors in composition: skip other msg\n try:\n composition_error_names_html = ''\n if student_composition_error_namelist:\n student_composition_error_namelist.sort()\n composition_error_names_html = ''.join((\n \"
  • \",\n \"
  • \".join(student_composition_error_namelist),\n \"
\"\n ))\n\n############## is_approve #########################\n if is_approve:\n\n #++++++++++++++++ is_test +++++++++++++++++++++++++\n if is_test:\n\n # - if any subjects skipped: create lines 'The following subjects will be skipped' plus the reason\n if not count:\n subj_txt = get_subject_count_text(examperiod, count)\n msg_list.append(gettext(\"The selection contains %(val)s.\") % {'val': subj_txt})\n\n elif committed == count:\n msg_list.append(\"
\" + str(_(\"All %(cpt)s will be approved.\") % {'cpt': subjects_plural}) + ':
    ')\n else:\n willbe_or_are_txt = pgettext_lazy('plural', 'will be') if is_test else _('are')\n msg_list.append(\"
    \" + str(_(\"The following %(cpt)s %(willbe)s skipped\")\n % {'cpt': subjects_plural, 'willbe': willbe_or_are_txt}) + \\\n \":
      \")\n if already_published:\n msg_list.append('
    • ' + str(_(\"%(val)s already submitted\") %\n {'val': get_subjects_are_text(examperiod, already_published)}) + ';
    • ')\n\n if logging_on:\n logger.debug(' already_published: ' + str(already_published))\n\n if auth_missing:\n msg_list.append('
    • ' + str(_(\"%(subj)s not fully approved\") %\n {'subj': get_subjects_are_text(examperiod, auth_missing)}) + ';
    • ')\n show_msg_first_approve_by_pres_secr = True\n if logging_on:\n logger.debug(' auth_missing: ' + str(auth_missing))\n\n if already_approved:\n msg_list.append('
    • ' + get_subjects_are_text(examperiod, already_approved) + str(_(' already approved')) + ';
    • ')\n if logging_on:\n logger.debug(' already_approved: ' + str(already_approved))\n\n if double_approved:\n other_function = str(_('chairperson')) if requsr_auth == 'auth2' else str(_('secretary'))\n caption = _('subject') if examperiod == 1 else _('re-examination')\n msg_list.append(''.join(('
    • ', get_subjects_are_text(examperiod, double_approved),\n str(_(' already approved by you as ')), other_function, '.
      ',\n str(_(\"You cannot approve a %(cpt)s both as chairperson and as secretary.\") % {'cpt': caption} ), '
    • ')))\n if logging_on:\n logger.debug(' double_approved: ' + str(double_approved))\n\n msg_list.append('
    ')\n\n # - line with text how many subjects will be approved / submitted\n msg_list.append(\"
    \")\n if not committed:\n msg_str = _(\"No %(cpts)s will be approved.\") % {'cpts': subjects_plural}\n if logging_on:\n logger.debug(' is_approve not committed: ' + str(not committed))\n\n else:\n student_count_txt = get_student_count_text(student_committed_count)\n subject_count_txt = get_subject_count_text(examperiod, committed)\n will_be_text = get_will_be_text(committed)\n msg_str = ' '.join((str(subject_count_txt), str(_('of')), str(student_count_txt),\n str(will_be_text),\n gettext('approved') + '.'\n ))\n if logging_on:\n logger.debug(' is_approve msg_str: ' + str(not msg_str))\n\n msg_list.append(str(msg_str))\n msg_list.append('
    ')\n\n # - add line 'both president and secretary must first approve all subjects before you can submit the Ex form\n if show_msg_first_approve_by_pres_secr:\n msg_txt = ''.join(('
    ',\n str(_('The chairperson and the secretary must approve all %(cpt)s before you can submit the %(frm)s form.') \\\n % {'cpt': subjects_plural, 'frm': form_txt}),\n '
    '))\n msg_list.append(msg_txt)\n\n # ++++++++++++++++ not is_test +++++++++++++++++++++++++\n else:\n\n # - line with text how many subjects have been approved\n msg_list.append('
    ')\n\n student_count_txt = get_student_count_text(student_saved_count)\n subject_count_txt = get_subject_count_text(examperiod, saved)\n student_saved_error_count_txt = get_student_count_text(student_saved_error_count)\n subject_error_count_txt = get_subject_count_text(examperiod, saved_error)\n\n if logging_on:\n logger.debug(' student_count_txt: ' + str(student_count_txt))\n logger.debug(' subject_count_txt: ' + str(subject_count_txt))\n logger.debug(' student_saved_error_count_txt: ' + str(student_saved_error_count_txt))\n logger.debug(' subject_error_count_txt: ' + str(subject_error_count_txt))\n\n # - line with text how many subjects have been approved / submitted\n if not saved and not saved_error:\n msg_str = str(_(\"No subjects have been approved.\"))\n else:\n if saved:\n have_has_been_txt = _('has been') if saved == 1 else _('have been')\n msg_str = str(_(\"%(subj)s of %(stud)s %(havehasbeen)s approved.\")\n % {'subj': subject_count_txt, 'stud': student_count_txt,\n 'havehasbeen': have_has_been_txt})\n else:\n msg_str = str(_(\"No subjects have been approved.\"))\n if saved_error:\n if msg_str:\n msg_str += '
    '\n could_txt = pgettext_lazy('singular', 'could') if saved_error == 1 else pgettext_lazy(\n 'plural', 'could')\n msg_str += str(\n _(\"%(subj)s of %(stud)s %(could)s not be approved because an error occurred.\")\n % {'subj': subject_error_count_txt, 'stud': student_saved_error_count_txt,\n 'could': could_txt})\n\n msg_list.append(str(msg_str))\n msg_list.append('
    ')\n\n############## is submit #########################\n else:\n if not count:\n show_msg_frm_cannot_be_submitted = True\n else:\n if all_published :\n msg_list.append(''.join((\n \"
    \",\n gettext(\"All %(cpts)s are already submitted.\") %{'cpts': subjects_plural},\n \"
    \")))\n\n elif auth_missing or double_approved or student_composition_error_count:\n show_msg_frm_cannot_be_submitted = True\n missing_double_lst = [\"
      \"]\n if auth_missing:\n show_msg_first_approve_by_pres_secr = True\n\n is_are_txt = get_is_are_text(auth_missing)\n that_txt = str(pgettext_lazy('dat singular', 'that') if auth_missing == 1 else pgettext_lazy('die plural', 'that'))\n subjects_txt = subjects_singular if auth_missing == 1 else subjects_plural\n missing_double_lst.extend((\"
    • \", gettext(\"There %(is_are)s %(val)s %(cpt)s %(that)s %(is_are)s not fully approved.\")\n % {'is_are': is_are_txt, 'that': that_txt, 'val': auth_missing, 'cpt': subjects_txt}, \"
    • \", ))\n\n if double_approved:\n is_are_txt = get_is_are_text(double_approved)\n that_txt = str(pgettext_lazy('dat singular', 'that')if double_approved == 1 else pgettext_lazy('die plural', 'that'))\n subjects_txt = subjects_singular if double_approved == 1 else subjects_plural\n missing_double_lst.extend((\"
    • \", gettext(\"There %(is_are)s %(val)s %(cpt)s %(that)s %(is_are)s double approved by the same person.\")\n % {'is_are': is_are_txt, 'that': that_txt, 'val': double_approved, 'cpt': subjects_txt}, \"
    • \", ))\n\n if student_composition_error_count:\n is_are_txt = get_is_are_text(student_composition_error_count)\n that_txt = str(pgettext_lazy('dat singular', 'that')if student_composition_error_count == 1 else pgettext_lazy('die plural', 'that'))\n candidates_txt = str( _('candidate') if student_composition_error_count == 1 else _('candidates'))\n missing_double_lst.extend((\"
    • \", gettext(\"There %(is_are)s %(val)s %(cpt)s whose subject composition is not correct.\")\n % {'is_are': is_are_txt, 'val': student_composition_error_count, 'cpt': candidates_txt}, \"
    • \", ))\n\n missing_double_lst.append('
    ')\n msg_list.append(''.join(missing_double_lst))\n else:\n\n if is_test:\n show_msg_request_verifcode = True\n if already_published:\n msg_list.extend((\"
    • \",\n gettext(\"%(val)s already submitted\") % {'val': get_subjects_are_text(examperiod, already_published)},\n '
    '))\n\n # - line with text how many subjects will be approved / submitted\n student_count_txt = get_student_count_text(student_committed_count)\n subject_count_txt = get_subject_count_text(examperiod, committed)\n will_be_text = get_will_be_text(committed)\n approve_txt = gettext('added to the %(frm)s form.') % {'frm': form_txt}\n\n if logging_on:\n logger.debug(' student_count_txt: ' + str(student_count_txt))\n logger.debug(' will_be_text: ' + str(will_be_text))\n logger.debug(' approve_txt: ' + str(approve_txt))\n\n\n msg_list.append(' '.join((\"
    \", str(subject_count_txt), str(_('of')), str(student_count_txt),\n str(will_be_text), approve_txt, '
    ')))\n\n if not is_test:\n msg_list.append(\"
    \")\n if not is_saved_to_disk:\n msg_list.append(gettext(\"The %(frm)s form has not been submitted.\") % {'frm': form_txt})\n else:\n msg_list.append(''.join((\n gettext(\"The %(frm)s form has been submitted.\") % {'frm': form_txt}, ' ',\n gettext(\"Click here to download it.\")\n % {'href': published_instance_file_url},\n '
    ',\n gettext(\"It has been saved in the page 'Archive' as '%(frm)s'.\")\n % {'frm': published_instance_filename},\n )))\n msg_list.append('
    ')\n if show_msg_first_approve_by_pres_secr:\n msg_list.append(''.join((\"
    \",\n gettext(\n 'The chairperson and the secretary must approve all %(cpt)s before you can submit the %(frm)s form.') \\\n % {'cpt': subjects_plural, 'frm': form_txt},\n '
    ')))\n\n if show_msg_frm_cannot_be_submitted:\n msg_list.append(''.join((\"
    \",\n gettext(\"The %(frm)s form can not be submitted.\") % {'frm': form_txt},\n '
    ')))\n\n msg_list.append('
')\n\n# - create warning frame with 'subject composition is not correct'\n if is_test and student_composition_error_count:\n is_are_txt = get_is_are_text(student_composition_error_count)\n candidates_txt = str(_('candidate') if student_composition_error_count == 1 else _('candidates'))\n\n msg_list.append(''.join((\"
\", str(_(\"ATTENTION\")), ': ',\n gettext(\"There %(is_are)s %(val)s %(cpt)s whose subject composition is not correct.\")\n % {'is_are': is_are_txt, 'val': student_composition_error_count, 'cpt': candidates_txt},\n composition_error_names_html, \"
\",\n gettext( \"Make the necessary corrections in the subject composition or contact the Inspectorate.\"),\n \"
\"\n )))\n\n# - create 'You need a 6 digit verification code' line\n # PR2023-07-12 added: only when is test\n if show_msg_request_verifcode:\n msg_list.extend((\n \"
\",\n gettext(\"You need a 6 digit verification code to submit the Ex form.\"), '
',\n gettext(\"Click 'Request verification code' and we will send you an email with the verification code.\"), '
',\n gettext(\"The verification code expires in 30 minutes.\"),\n '
'\n ))\n\n msg_html = ''.join(msg_list)\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n msg_html = acc_prm.errhtml_error_occurred_with_border(e)\n return msg_html\n# - end of create_ex1_ex4_msg_list\n\n def create_ex1_ex4_form(self, published_instance, sel_examyear, sel_school, sel_department, sel_level,\n examperiod, prefix, save_to_disk, request, user_lang):\n #PR2021-07-27 PR2021-08-14\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= create_ex1_ex4_form ============= ')\n logger.debug(' examperiod: ' + str(examperiod))\n logger.debug(' sel_level: ' + str(sel_level))\n logger.debug(' save_to_disk: ' + str(save_to_disk))\n\n is_saved_to_disk = False\n# +++ create Ex1 xlsx file\n if examperiod == 1:\n\n # get text from examyearsetting\n settings = awpr_lib.get_library(sel_examyear, ['exform', 'ex1'])\n # if logging_on:\n # logger.debug('settings: ' + str(settings))\n\n response, is_saved_to_disk = grd_exc.create_ex1_xlsx(\n published_instance=published_instance,\n examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n sel_level=sel_level,\n examperiod=examperiod,\n prefix=prefix,\n settings=settings,\n save_to_disk=save_to_disk,\n request=request,\n user_lang=user_lang)\n\n elif examperiod in (2, 3):\n response, is_saved_to_disk = grd_exc.create_ex4_xlsx(\n published_instance=published_instance,\n examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n sel_level=sel_level,\n examperiod=examperiod,\n prefix=prefix,\n save_to_disk=save_to_disk,\n request=request,\n user_lang=user_lang)\n\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= end of create_ex1_ex4_form ============= ')\n return is_saved_to_disk\n# --- end of create_ex1_ex4_form\n\n\n#################################################################################\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectApproveSingleView(View): # PR2021-07-25 PR2023-02-18\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectApproveSingleView ============= ')\n\n# function sets auth and publish of studentsubject records of current department # PR2021-07-25\n update_wrap = {}\n msg_list = []\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get permit\n has_permit = False\n req_usr = request.user\n if req_usr and req_usr.country and req_usr.schoolbase:\n permit_list = acc_prm.get_permit_list('page_studsubj', req_usr)\n if permit_list:\n has_permit = 'permit_approve_subject' in permit_list\n\n if not has_permit:\n msg_list.append(str(_(\"You don't have permission to perform this action.\")))\n else:\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n\n# ----- get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - examyear, schoolbase, school, depbase or department is None\n # - country, examyear or school is locked\n # - not requsr_same_school,\n # - not sel_examyear.published,\n # not af.is_allowed_depbase_requsr or not af.is_allowed_depbase_school,\n\n sel_examyear, sel_school, sel_department, sel_level, may_editNIU, err_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n if err_list:\n msg_list.extend(err_list)\n else:\n\n# check if studsubj is allowed PR2023-02-12\n userallowed_instance = acc_prm.get_userallowed_instance_from_request(request)\n if logging_on:\n logger.debug(' userallowed_instance: ' + str(userallowed_instance))\n\n userallowed_sections_dict = acc_prm.get_userallowed_sections_dict(userallowed_instance)\n if logging_on:\n logger.debug(' userallowed_sections_dict: ' + str(userallowed_sections_dict))\n\n userallowed_schoolbase_dict, userallowed_depbases_pk_arr = acc_prm.get_userallowed_schoolbase_dict_depbases_pk_arr(userallowed_sections_dict, sel_school.base_id)\n if logging_on:\n logger.debug(' userallowed_schoolbase_dict: ' + str(userallowed_schoolbase_dict))\n logger.debug(' userallowed_depbases_pk_arr: ' + str(userallowed_depbases_pk_arr))\n\n userallowed_depbase_dict, userallowed_lvlbase_pk_arr = acc_prm.get_userallowed_depbase_dict_lvlbases_pk_arr(userallowed_schoolbase_dict, sel_department.base_id)\n if logging_on:\n logger.debug(' userallowed_depbase_dict: ' + str(userallowed_depbase_dict))\n logger.debug(' userallowed_lvlbase_pk_arr: ' + str(userallowed_lvlbase_pk_arr))\n\n sel_lvlbase_pk = sel_level.base_id if sel_level else None\n userallowed_subjbase_pk_list = acc_prm.get_userallowed_subjbase_arr(userallowed_depbase_dict, userallowed_lvlbase_pk_arr, sel_lvlbase_pk)\n\n userallowed_cluster_pk_list = acc_prm.get_userallowed_cluster_pk_list(userallowed_instance)\n if logging_on:\n logger.debug(' userallowed_subjbase_pk_list: ' + str(userallowed_subjbase_pk_list))\n logger.debug(' userallowed_cluster_pk_list: ' + str(userallowed_cluster_pk_list))\n\n# - get list of studentsubjects from upload_dict\n studsubj_list = upload_dict.get('studsubj_list')\n # 'studsubj_list': [{'student_pk': 7959, 'studsubj_pk': 64174, 'subj_auth1by': True}]}\n if studsubj_list:\n studsubj_rows = []\n# -------------------------------------------------\n# - loop through list of uploaded studentsubjects\n for studsubj_dict in studsubj_list:\n student_pk = studsubj_dict.get('student_pk')\n studsubj_pk = studsubj_dict.get('studsubj_pk')\n\n append_dict = {}\n error_dict = {}\n\n# - get current student and studsubj\n student = stud_mod.Student.objects.get_or_none(\n id=student_pk,\n department=sel_department\n )\n studsubj = stud_mod.Studentsubject.objects.get_or_none(\n id=studsubj_pk,\n student=student\n )\n if logging_on:\n logger.debug('---------- ')\n logger.debug(' student: ' + str(student))\n logger.debug(' studsubj: ' + str(studsubj))\n\n may_edit = False\n if student and studsubj:\n\n# +++ check if updating is allowed:\n may_edit = True\n if userallowed_cluster_pk_list:\n may_edit = False\n if studsubj.cluster_id and studsubj.cluster_id in userallowed_cluster_pk_list:\n may_edit = True\n else:\n msg_list.append(\n gettext(\"You don't have permission %(cpt)s.\") % {'cpt': gettext('to approve subjects of this cluster')})\n\n# +++ update studsubj\n if may_edit:\n si_pk = studsubj.schemeitem_id\n schemeitems_dict = subj_vw.get_scheme_si_dict(sel_examyear.pk, sel_department.base_id, si_pk)\n si_dict = schemeitems_dict.get(si_pk)\n\n err_list, err_fields = [], []\n update_studsubj(studsubj, studsubj_dict, si_dict,\n sel_examyear, sel_school, sel_department, False,\n err_list, err_fields, request)\n if logging_on:\n logger.debug('>>>>> err_list: ' + str(err_list))\n logger.debug('>>>>> err_fields: ' + str(err_fields))\n\n if err_list:\n msg_list.extend(err_list)\n if err_fields:\n append_dict['err_fields'] = err_fields\n\n # TODO check value of error_dict\n # error_dict = {err_update: \"Er is een fout opgetreden. De wijzigingen zijn niet opgeslagen.\"}\n if error_dict:\n append_dict['error'] = error_dict\n setting_dict = {\n 'sel_examyear_pk': sel_school.examyear.pk,\n 'sel_schoolbase_pk': sel_school.base_id,\n 'sel_depbase_pk': sel_department.base_id\n }\n\n if logging_on:\n logger.debug('studsubj.pk: ' + str(studsubj.pk))\n studsubj_pk_list = [studsubj.pk] if studsubj.pk else None\n\n rows = create_studentsubject_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base if sel_school else None,\n sel_depbase=sel_department.base if sel_department else None,\n append_dict=append_dict,\n request=request,\n sel_lvlbase=sel_level.base if sel_level else None,\n requsr_same_school=True, # check for same_school is included in may_edit\n student_pk=student.pk,\n studsubj_pk_list=studsubj_pk_list\n )\n if rows:\n studsubj_row = rows[0]\n if studsubj_row:\n studsubj_rows.append(studsubj_row)\n# - end of loop\n# -------------------------------------------------\n if studsubj_rows:\n update_wrap['updated_studsubj_approve_rows'] = studsubj_rows\n\n if logging_on:\n logger.debug('>>>>> msg_list: ')\n if msg_list:\n for msg in msg_list:\n logger.debug('msg: ' + str(msg))\n if msg_list:\n messages = []\n msg_html = '
'.join(msg_list)\n messages.append({'class': \"border_bg_warning\", 'msg_html': msg_html})\n update_wrap['messages'] = messages\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentsubjectApproveSingleView\n##################################################################################\n\n\ndef get_student_count_text(student_count):\n if not student_count:\n msg_text = str(_('no candidates'))\n elif student_count == 1:\n msg_text = str(_('1 candidate'))\n else:\n msg_text = ' '.join((str(student_count), str(_('candidates'))))\n return msg_text\n\n\ndef get_will_be_text(count):\n if count == 1:\n msg_text = str(pgettext_lazy('singular', 'will be'))\n else:\n msg_text = str(pgettext_lazy('plural', 'will be'))\n return msg_text\n\n\ndef get_is_are_text(count):\n return gettext('is') if count == 1 else gettext('are')\n\ndef get_subject_count_text(examperiod, count):\n # PR2023-07-13\n cpt_singular = gettext('Re-examination 3rd period') if examperiod == 3 else gettext('Re-examination') if examperiod == 2 else gettext('Subject')\n cpt_plural = gettext('Re-examinations 3rd period') if examperiod == 3 else gettext('Re-examinations') if examperiod == 2 else gettext('Subjects')\n cpt = cpt_singular if count == 1 else cpt_plural\n\n val = str(count) if count else str(pgettext_lazy('geen', 'no'))\n return ' '.join((val, cpt.lower()))\n\n\ndef get_subjects_are_text(examperiod, count):\n #PR023-07-13\n return ' '.join((\n get_subject_count_text(examperiod, count),\n gettext('is') if count == 1 else gettext('are')\n ))\n\n\ndef get_subjects_willbe_text(examperiod, count):\n #PR023-07-13\n return ' '.join((\n get_subject_count_text(examperiod, count),\n get_will_be_text(count)\n ))\n\n\ndef approve_studsubj(studsubj, requsr_auth, prefix, is_test, is_reset, count_dict, request):\n # PR2021-07-26 PR2022-05-30 PR2022-12-30 PR2023-02-12\n # auth_bool_at_index is not used to set or rest value. Instead 'is_reset' is used to reset, set otherwise PR2021-03-27\n # prefix = 'reex3_' 'reex_' 'subj_'\n\n # PR2022-12-30 instead of updating each studsubj instance separately, create list of tobesaved studsubj_pk\n # list is created outside this function, when is_saved = True\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('----- approve_studsubj -----')\n logger.debug(' requsr_auth: ' + str(requsr_auth))\n logger.debug(' prefix: ' + str(prefix))\n logger.debug(' is_reset: ' + str(is_reset))\n logger.debug(' studsubj: ' + str(studsubj))\n\n is_committed = False\n is_saved = False\n\n if studsubj:\n req_user = request.user\n\n# - skip when this studsubj is already published\n # PR2023-02-12 was: published = getattr(studsubj, prefix + 'published')\n published = True if studsubj.get('published_id') else False\n if logging_on:\n logger.debug(' published: ' + str(published))\n\n if studsubj.get('studsubj_tobedeleted'):\n af.add_one_to_count_dict(count_dict, 'studsubj_tobedeleted')\n if logging_on:\n logger.debug(' studsubj_tobedeleted: ')\n\n if published:\n af.add_one_to_count_dict(count_dict, 'already_published')\n else:\n\n# - skip if other_auth has already approved and other_auth is same as this auth. - may not approve if same auth has already approved\n\n # PR2023-02-12 use sql instead of model:\n # field auth1by_id, auth2by_id, published_id contains the value are of\n # - when axamperiod = 2: studsubj.reex_auth1by_id\n # - when axamperiod = 3: studsubj.reex3_auth1by_id\n # - else: studsubj.subj_auth1by_id\n\n # was: requsr_authby_field = prefix + requsr_auth + 'by'\n # auth1by = getattr(studsubj, prefix +'auth1by')\n # auth2by = getattr(studsubj, prefix +'auth2by')\n\n auth1by_id = studsubj.get('auth1by_id')\n auth2by_id = studsubj.get('auth2by_id')\n if logging_on:\n logger.debug(' auth1by_id: ' + str(auth1by_id))\n logger.debug(' auth2by_id: ' + str(auth2by_id))\n\n save_changes = False\n\n# - remove authby when is_reset\n if is_reset:\n # PR2022-12-30 was: setattr(studsubj, requsr_authby_field, None)\n af.add_one_to_count_dict(count_dict, 'reset')\n save_changes = True\n else:\n\n# - skip if this studsubj is already approved\n # requsr_authby_value = getattr(studsubj, requsr_authby_field)\n requsr_authby_value = auth1by_id if requsr_auth == 'auth1' else auth2by_id if requsr_auth == 'auth2' else None\n requsr_authby_field_already_approved = True if requsr_authby_value else False\n if logging_on:\n logger.debug(' requsr_authby_field_already_approved: ' + str(requsr_authby_field_already_approved))\n\n if requsr_authby_field_already_approved:\n af.add_one_to_count_dict(count_dict, 'already_approved')\n else:\n\n# - skip if this author (like 'chairperson') has already approved this studsubj\n # under a different permit (like 'secretary' or 'corrector')\n\n if logging_on:\n logger.debug(' > requsr_auth: ' + str(requsr_auth))\n logger.debug(' > req_user: ' + str(req_user))\n logger.debug(' > auth1by_id: ' + str(auth1by_id))\n logger.debug(' > auth2by_id: ' + str(auth2by_id))\n\n double_approved = False\n if requsr_auth == 'auth1':\n double_approved = True if auth2by_id and auth2by_id == req_user.pk else False\n elif requsr_auth == 'auth2':\n double_approved = True if auth1by_id and auth1by_id == req_user.pk else False\n\n if logging_on:\n logger.debug(' double_approved: ' + str(double_approved))\n\n if double_approved:\n af.add_one_to_count_dict(count_dict, 'double_approved')\n else:\n # PR2022-12-30 was: setattr(studsubj, requsr_authby_field, req_user)\n save_changes = True\n if logging_on:\n logger.debug(' save_changes: ' + str(save_changes))\n\n# - set value of requsr_authby_field\n if save_changes:\n if is_test:\n af.add_one_to_count_dict(count_dict, 'committed')\n is_committed = True\n else:\n\n# - save changes\n af.add_one_to_count_dict(count_dict, 'saved')\n is_saved = True\n if logging_on:\n logger.debug(' is_committed: ' + str(is_committed))\n logger.debug(' is_saved: ' + str(is_saved))\n\n return is_committed, is_saved\n# - end of approve_studsubj\n\n\ndef submit_studsubj(studsubj, prefix, is_test, count_dict):\n # PR2021-01-21 PR2021-07-27 PR2022-05-30 PR2022-12-30 PR2023-02-12\n\n # PR2022-12-30 instead of updating each studsubj instance separately, create list of tobesaved studsubj_pk\n # list is created outside this function, when is_saved = True\n\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug('----- submit_studsubj -----')\n logger.debug(' prefix: ' + str(prefix))\n\n is_published = False\n is_committed = False\n is_saved = False\n\n if studsubj:\n\n# - check if this studsubj is already published\n #published = getattr(studsubj, prefix + 'published')\n is_published = True if studsubj.get('published_id') else False\n if logging_on:\n logger.debug(' is_published: ' + str(is_published))\n\n if studsubj.get('studsubj_tobedeleted'):\n af.add_one_to_count_dict(count_dict, 'studsubj_tobedeleted')\n\n if is_published:\n af.add_one_to_count_dict(count_dict, 'already_published')\n else:\n\n# - check if this studsubj / examtype is approved by all auth\n #auth1by = getattr(studsubj, prefix + 'auth1by')\n #auth2by = getattr(studsubj, prefix + 'auth2by')\n\n auth1by_id = studsubj.get('auth1by_id')\n auth2by_id = studsubj.get('auth2by_id')\n auth_missing = auth1by_id is None or auth2by_id is None\n if logging_on:\n logger.debug(' auth1by_id: ' + str(auth1by_id))\n logger.debug(' auth2by_id: ' + str(auth2by_id))\n logger.debug(' auth_missing: ' + str(auth_missing))\n\n if auth_missing:\n af.add_one_to_count_dict(count_dict, 'auth_missing')\n else:\n# - check if all auth are different\n double_approved = auth1by_id == auth2by_id\n if logging_on:\n logger.debug(' double_approved: ' + str(double_approved))\n\n if double_approved and not auth_missing:\n af.add_one_to_count_dict(count_dict, 'double_approved')\n else:\n# - set value of published_instance and exatmtype_status field\n if is_test:\n af.add_one_to_count_dict(count_dict, 'committed')\n is_committed = True\n else:\n af.add_one_to_count_dict(count_dict, 'saved')\n is_saved = True\n\n return is_published, is_committed, is_saved\n# - end of submit_studsubj\n\n\ndef create_published_Ex1_Ex4_instance(sel_school, sel_department, sel_level, examperiod, now_arr, request):\n # PR2021-07-27 PR2022-08-21\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('----- create_published_Ex1_Ex4_instance -----')\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n logger.debug(' sel_level: ' + str(sel_level))\n logger.debug(' examperiod: ' + str(examperiod))\n logger.debug(' now_arr: ' + str(now_arr))\n logger.debug(' request.user: ' + str(request.user))\n\n # create new published_instance and save it when it is not a test (this function is only called when it is not a test)\n # filename is added after creating file in create_ex1_xlsx\n depbase_code = sel_department.base.code if sel_department.base.code else '-'\n school_code = sel_school.base.code if sel_school.base.code else '-'\n school_abbrev = sel_school.abbrev if sel_school.abbrev else '-'\n\n if sel_level and sel_department.level_req and sel_level.abbrev:\n depbase_code += ' ' + sel_level.abbrev\n\n if logging_on:\n logger.debug(' depbase_code: ' + str(depbase_code))\n logger.debug(' school_code: ' + str(school_code))\n logger.debug(' school_abbrev: ' + str(school_abbrev))\n\n # to be used when submitting Ex4 form\n examtype_caption = ''\n exform = 'Ex4 3e tijdvak' if examperiod == 3 else 'Ex4' if examperiod == 2 else 'Ex1' if examperiod == 1 else '-'\n examtype_caption = 'tv3' if examperiod == 3 else 'tv2' if examperiod == 2 else 'tv1' if examperiod == 1 else '-'\n\n if logging_on:\n logger.debug(' exform: ' + str(exform))\n logger.debug(' examtype_cpt: ' + str(examtype_caption))\n\n today_date = af.get_date_from_arr(now_arr)\n if logging_on:\n logger.debug(' today_date: ' + str(today_date) + ' ' + str(type(today_date)))\n\n year_str = str(now_arr[0])\n month_str = (\"00\" + str(now_arr[1]))[-2:]\n date_str = (\"00\" + str(now_arr[2]))[-2:]\n hour_str = (\"00\" + str(now_arr[3]))[-2:]\n minute_str = (\"00\" +str( now_arr[4]))[-2:]\n now_formatted = ''.join([year_str, \"-\", month_str, \"-\", date_str, \" \", hour_str, \"u\", minute_str])\n\n file_name = ' '.join((exform, school_code, school_abbrev, depbase_code, examtype_caption, now_formatted))\n # skip school_abbrev if total file_name is too long\n if len(file_name) > c.MAX_LENGTH_FIRSTLASTNAME:\n file_name = ' '.join((exform, school_code, depbase_code, examtype_caption, now_formatted))\n # if total file_name is still too long: cut off\n if len(file_name) > c.MAX_LENGTH_FIRSTLASTNAME:\n file_name = file_name[0:c.MAX_LENGTH_FIRSTLASTNAME]\n\n if logging_on:\n logger.debug(' file_name: ' + str(file_name))\n\n published_instance = None\n try:\n #sel_examtype = '-'\n published_instance = sch_mod.Published(\n school=sel_school,\n department=sel_department,\n #examtype=sel_examtype,\n examperiod=examperiod,\n name=file_name,\n datepublished=today_date\n )\n\n published_instance.filename = file_name + '.xlsx'\n\n published_instance.save(request=request)\n\n if logging_on:\n logger.debug(' published_instance.saved: ' + str(published_instance))\n logger.debug(' published_instance.pk: ' + str(published_instance.pk))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n return published_instance\n# - end of create_published_Ex1_Ex4_instance\n\n\n#################################################################################\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectValidateSchemeView(View): # PR2021-08-28\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectValidateSchemeView ============= ')\n\n # function checks if schemeitem schemes are the same as the student scheme\n # can only be used by system.\n # Function is added to check and correct schemeitems, because of wrong schemeitems in SMAC students.\n # STiil don't know why those students got the wrong schemeitems\n update_wrap = {}\n\n req_usr = request.user\n if req_usr and req_usr.country and req_usr.schoolbase:\n\n # - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n # - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n correct_errors = False\n if upload_json:\n upload_dict = json.loads(upload_json)\n correct_errors = upload_dict.get('correct_errors', False)\n\n sel_examyear, sel_school, sel_department, sel_level, may_edit, msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n stud_row_count, stud_row_error, student_rows = validate_students_scheme(sel_examyear, correct_errors, request)\n response_dict = {}\n response_dict['stud_row_count'] = stud_row_count\n response_dict['stud_row_error'] = stud_row_error\n response_dict['student_rows'] = student_rows\n\n studsubj_row_count, studsubj_row_error, studsubj_rows = validate_studsubj_scheme(sel_examyear, correct_errors, request)\n\n response_dict['studsubj_row_count'] = studsubj_row_count\n response_dict['studsubj_row_error'] = studsubj_row_error\n response_dict['studsubj_rows'] = studsubj_rows\n\n update_wrap['validate_scheme_response'] = response_dict\n\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentsubjectValidateSchemeView\n\n\ndef validate_students_scheme(sel_examyear, correct_errors, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug('----- validate_students_scheme ----- ')\n logger.debug('sel_examyear: ' + str(sel_examyear))\n logger.debug('correct_errors: ' + str(correct_errors))\n\n row_count, row_error, student_rows = 0, 0, []\n try:\n sql_keys = {'ey_id': sel_examyear.pk}\n\n sql_list = [\"WITH sub_scheme AS (\",\n \"SELECT scheme.id AS scheme_id,\",\n \"dep.id AS scheme_dep_id, dep.base_id AS scheme_depbase_id,\",\n \"lvl.id AS scheme_level_id, lvl.base_id AS scheme_lvlbase_id,\",\n \"sct.id AS scheme_sector_id, sct.base_id AS scheme_sctbase_id\",\n \"FROM subjects_scheme AS scheme\",\n \"INNER JOIN schools_department AS dep ON (dep.id = scheme.department_id)\",\n \"INNER JOIN subjects_level AS lvl ON (lvl.id = scheme.level_id)\",\n \"INNER JOIN subjects_sector AS sct ON (sct.id = scheme.sector_id)\"\n , \")\",\n\n \"SELECT st.id AS student_id, st.lastname, st.firstname, st.school_id AS s_id,\",\n \"sbase.code AS school_code, sch.name AS school_name, \",\n \"dep.id AS st_dep_id, dep.base_id AS st_depbase_id, \",\n \"lvl.id AS st_lvl_id, lvl.base_id AS st_lvlbase_id, \",\n \"sct.id AS st_sct_id, sct.base_id AS st_sctbase_id, \",\n \"st.scheme_id AS st_scheme_id, \",\n \"scheme_dep_id, scheme_depbase_id, \",\n \"scheme_dep_id, scheme_depbase_id, \",\n \"scheme_level_id, scheme_lvlbase_id, \",\n \"scheme_sector_id, scheme_sctbase_id \",\n\n \"FROM students_student AS st\",\n \"INNER JOIN schools_school AS sch ON (sch.id = st.school_id)\",\n \"INNER JOIN schools_schoolbase AS sbase ON (sbase.id = sch.base_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = sch.examyear_id)\",\n\n \"INNER JOIN schools_department AS dep ON (dep.id = st.department_id)\",\n \"INNER JOIN schools_departmentbase AS db ON (db.id = dep.base_id)\",\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = st.level_id)\",\n \"LEFT JOIN subjects_sector AS sct ON (sct.id = st.sector_id)\",\n \"LEFT JOIN sub_scheme ON (sub_scheme.scheme_id = st.scheme_id)\",\n \"WHERE sch.examyear_id = %(ey_id)s::INT\"]\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = af.dictfetchall(cursor)\n # logger.debug('connection.queries: ' + str(connection.queries))\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n if rows:\n for row in rows:\n row_count += 1\n\n student_id = row.get('student_id')\n student = stud_mod.Student.objects.get_or_none(pk=student_id)\n if student:\n # get scheme, based on value of dep, sct and maybe lvl\n department = student.department\n level = student.level\n sector = student.sector\n student_scheme = student.scheme\n\n deplvlsct_scheme = None\n if department and sector:\n if level is None:\n deplvlsct_scheme = subj_mod.Scheme.objects.filter(\n department=department,\n level_id__isnull=True,\n sector=sector,\n ).order_by('pk').first()\n else:\n deplvlsct_scheme = subj_mod.Scheme.objects.filter(\n department=department,\n level_id=level,\n sector=sector,\n ).order_by('pk').first()\n\n err_txt = None\n if deplvlsct_scheme is None:\n if student_scheme is not None:\n err_txt = 'Student has scheme ' + str(student_scheme.name) + ', but deplvlsct_scheme not found'\n else:\n if student_scheme is None:\n err_txt = 'student_scheme is None, but deplvlsct_scheme is: ' + str(deplvlsct_scheme.name)\n elif student_scheme.pk != deplvlsct_scheme.pk:\n err_txt = 'Student_scheme: ' + str(\n student_scheme.name) + ' not equal to deplvlsct_scheme: ' + str(deplvlsct_scheme.name)\n if err_txt:\n row_error += 1\n if correct_errors:\n setattr(student, 'scheme', deplvlsct_scheme)\n student.save(request=request)\n\n row_dict = {}\n row_dict['STUDENT'] = str(student.fullname)\n row_dict['SCHOOL'] = student.school.name\n row_dict['ERROR'] = err_txt\n\n student_rows.append(row_dict)\n\n if logging_on:\n logger.debug('row_count: ' + str(row_count))\n logger.debug('row_error: ' + str(row_error))\n logger.debug('student_rows: ' + str(student_rows))\n\n return row_count, row_error, student_rows\n# - end of validate_students_scheme\n\n\ndef validate_studsubj_scheme(sel_examyear, correct_errors, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ----- validate_studsubj_scheme ----- ')\n logger.debug('sel_examyear: ' + str(sel_examyear))\n logger.debug('correct_errors: ' + str(correct_errors))\n\n row_count, row_error, studsubj_rows = 0, 0, []\n try:\n sql_keys = {'ey_id': sel_examyear.pk}\n\n sql_list = [\"SELECT studsubj.id AS studsubj_id, st.id AS student_id, st.lastname, st.firstname, st.school_id AS s_id,\",\n \"sbase.code AS school_code, sch.name AS school_name,\",\n \"studsubj.schemeitem_id AS studsubj_si_id, \",\n \"st.scheme_id AS student_scheme_id,\",\n \"si_scheme.id AS studsubj_scheme_id, si_scheme.name AS studsubj_scheme_name,\",\n \"subjbase.code AS studsubj_subjbase_code\",\n\n \"FROM students_studentsubject AS studsubj\",\n \"INNER JOIN students_student AS st ON (st.id = studsubj.student_id)\",\n \"INNER JOIN schools_school AS sch ON (sch.id = st.school_id)\",\n \"INNER JOIN schools_schoolbase AS sbase ON (sbase.id = sch.base_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = sch.examyear_id)\",\n \"LEFT JOIN subjects_scheme AS stud_scheme ON (stud_scheme.id = st.scheme_id)\",\n\n \"INNER JOIN subjects_schemeitem AS si ON (si.id = studsubj.schemeitem_id)\",\n \"INNER JOIN subjects_scheme AS si_scheme ON (si_scheme.id = si.scheme_id)\",\n \"INNER JOIN subjects_subject AS subj ON (subj.id = si.subject_id)\",\n \"INNER JOIN subjects_subjectbase AS subjbase ON (subjbase.id = subj.base_id)\",\n \"WHERE sch.examyear_id = %(ey_id)s::INT\"]\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = af.dictfetchall(cursor)\n # logger.debug('connection.queries: ' + str(connection.queries))\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n if rows:\n for row in rows:\n row_count += 1\n student_scheme_id = row.get('student_scheme_id')\n studsubj_scheme_id = row.get('studsubj_scheme_id')\n\n if student_scheme_id and studsubj_scheme_id:\n if student_scheme_id != studsubj_scheme_id:\n row_error += 1\n row_dict = {}\n\n studsubj_id = row.get('studsubj_id')\n studsubj = stud_mod.Studentsubject.objects.get_or_none(pk=studsubj_id)\n\n # - get student\n if studsubj:\n student = studsubj.student\n student_scheme = student.scheme\n if student_scheme:\n\n # - first get subject and subjecttype from studsubj_schemeitem\n current_schemeitem = studsubj.schemeitem\n current_subject = current_schemeitem.subject\n current_sjtype = current_schemeitem.subjecttype\n\n row_dict['STUDENT'] = str(student.fullname)\n row_dict['SCHOOL'] = student.school.name\n row_dict['ERROR'] = 'student scheme is: ' + str(student_scheme.name) + ', studsubj scheme is: ' + str(\n current_schemeitem.scheme.name)\n row_dict['CURRENT'] = 'Subject: ' + str(current_subject.name_nl ) + ', Subjecttype: ' + current_sjtype.abbrev\n\n # - check if student scheme also has schemeitems with same subject and subjecttype as studsubj_schemeitem\n new_schemeitem = subj_mod.Schemeitem.objects.filter(\n scheme=student_scheme,\n subject=current_subject,\n subjecttype__base=current_sjtype.base\n ).order_by('pk').first()\n # - save new_schemeitem if student scheme also has schemeitems with same subject and subjecttype\n if new_schemeitem:\n row_dict['new_with_same_sjtype'] = 'subject: ' + str(new_schemeitem.subject.base.code) + ', Subjecttype: ' + new_schemeitem.subjecttype.abbrev\n if correct_errors:\n setattr(studsubj, 'schemeitem', new_schemeitem)\n studsubj.save(request=request)\n else:\n # - check if student scheme has schemeitems with same subject but differenet subjecttype\n new_schemeitem = subj_mod.Schemeitem.objects.filter(\n scheme=student_scheme,\n subject=current_subject\n ).order_by('subjecttype__base__sequence').first()\n if new_schemeitem:\n row_dict['new_with_different_sjtype'] = 'Subject: ' + str(new_schemeitem.subject.base.code) + ', Subjecttype: ' + new_schemeitem.subjecttype.abbrev\n setattr(studsubj, 'schemeitem', new_schemeitem)\n if correct_errors:\n setattr(studsubj, 'schemeitem', new_schemeitem)\n studsubj.save(request=request)\n else:\n # - delete studsubj if new scheme does not have this subject\n row_dict['not_in_new_scheme'] = 'Subject ' + str(current_subject.base.code) + ' will be deleted'\n if correct_errors:\n studsubj.delete(request=request)\n studsubj_rows.append(row_dict)\n if logging_on:\n logger.debug('row_count: ' + str(row_count))\n logger.debug('row_error: ' + str(row_error))\n logger.debug('studsubj_rows: ' + str(studsubj_rows))\n\n return row_count, row_error, studsubj_rows\n# - end of validate_studsubj_scheme\n#################################################################################\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectMultipleUploadView(View): # PR2020-11-20 PR2021-08-17 PR2021-09-28 PR2022-08-30 PR2023-01-07\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectMultipleUploadView ============= ')\n\n # function creates, deletes and updates studentsubject records of current student PR2020-11-21\n update_wrap = {}\n messages = []\n\n# - get permit\n has_permit = False\n req_usr = request.user\n if req_usr and req_usr.country and req_usr.schoolbase:\n permit_list = acc_prm.get_permit_list('page_studsubj', req_usr)\n if permit_list:\n has_permit = 'permit_crud' in permit_list\n if logging_on:\n logger.debug(' permit_list: ' + str(permit_list))\n\n if logging_on:\n logger.debug(' has_permit: ' + str(has_permit))\n if has_permit:\n\n # - check for double subjects, double subjects are not allowed -> happens in create_studsubj PR2021-07-11\n # - TODO when deleting: return warning when subject grades have values\n\n # - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n\n # - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n # - get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - examyear, schoolbase, school, depbase or department is None\n # - country, examyear or school is locked\n # - not requsr_same_school,\n # - not sel_examyear.published,\n # not af.is_allowed_depbase_requsr or not af.is_allowed_depbase_school,\n\n sel_examyear, sel_school, sel_department, sel_level, may_edit, err_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n if logging_on:\n logger.debug(' upload_dict' + str(upload_dict))\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n\n # - get info from upload_dict\n # - get current student from upload_dict, filter: sel_school, sel_department, student is not locked\n student_instance = None\n\n if len(err_list):\n msg_html = '
'.join(err_list)\n messages.append({'class': \"border_bg_warning\", 'msg_html': msg_html})\n elif may_edit:\n student_pk = upload_dict.get('student_pk')\n student_instance = stud_mod.Student.objects.get_or_none(\n id=student_pk,\n school=sel_school,\n department=sel_department\n )\n if logging_on:\n logger.debug(' student_instance: ' + str(student_instance))\n\n# - get list of studentsubjects from upload_dict\n studsubj_list = None\n if student_instance:\n studsubj_list = upload_dict.get('studsubj_list')\n\n if studsubj_list:\n\n# - get schemitem_info of the scheme of this student, separately, instead of getting it for each subject, should be faster\n schemeitems_dict = subj_vw.get_scheme_si_dict(sel_examyear.pk, sel_department.base_id, student_instance.scheme_id)\n\n # PR2023-02-22 when studsubj is set to 'deleted' instead of 'tobedeleted' (happens when row is not published),\n # it is not included in updated rows.\n # add it to list 'deleted_rows' and add it to updated_rows at the end.\n # necessary to remove deleted row from studsubj table\n deleted_rows = []\n updated_rows = []\n updated_rows_append_dict = {}\n recalc_subj_composition = False\n\n# -------------------------------------------------\n# - loop through list of uploaded studentsubjects\n for studsubj_dict in studsubj_list:\n # values of mode are: 'delete', 'create', 'update'\n mode = studsubj_dict.get('mode')\n\n studsubj_pk = studsubj_dict.get('studsubj_pk')\n schemeitem_pk = studsubj_dict.get('schemeitem_pk')\n\n if logging_on:\n logger.debug('---------- loop through list of uploaded studentsubjects ')\n logger.debug(' mode: ' + str(mode))\n logger.debug(' studsubj_dict: ' + str(studsubj_dict))\n logger.debug(' studsubj_pk: ' + str(studsubj_pk))\n logger.debug(' schemeitem_pk: ' + str(schemeitem_pk))\n\n# - get current studsubj - when mode is 'create': studsubj is None. It will be created at \"elif mode == 'create'\"\n studsubj_instance = stud_mod.Studentsubject.objects.get_or_none(\n id=studsubj_pk,\n student=student_instance\n )\n if logging_on:\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n\n append_dict = {}\n deleted_rows = []\n\n# +++ delete studsubj ++++++++++++\n if mode == 'delete':\n if studsubj_instance:\n deleted_row, tobedeleted_studsubj_pk, err_html = delete_studentsubject(\n student_instance=student_instance,\n studsubj_instance=studsubj_instance,\n request=request\n )\n if err_html:\n messages.append(\n {'header': str(_('Delete subject')),\n 'class': \"border_bg_invalid\",\n 'msg_html': err_html}\n )\n\n # - when studsubj is submitted, tobedeleted is set True, studsubj will be retrieved by updated_rows = create_studentsubject_rows\n # the key 'tobedeleted' must be added via append_dict\n\n elif tobedeleted_studsubj_pk:\n append_dict[tobedeleted_studsubj_pk] = {'tobedeleted': True}\n\n studsubj = None\n recalc_subj_composition = True\n\n # - when studsubj is not yet submitted, deleted is set True, studsubj will NOT be retrieved by updated_rows = create_studentsubject_rows\n # therefore a dict with the info af the deleted row must be added to updated_rows at the end, to remove the dict from the data_dicts and the tblrow\n\n elif deleted_row:\n deleted_rows.append(deleted_row)\n\n studsubj = None\n recalc_subj_composition = True\n\n # +++ create or restore new studentsubject, also create grade of first examperiod\n elif mode == 'create':\n schemeitem = subj_mod.Schemeitem.objects.get_or_none(id=schemeitem_pk)\n error_list = []\n\n studsubj, append_key = create_studsubj(\n student=student_instance,\n schemeitem=schemeitem,\n messages=messages,\n error_list=error_list,\n request=request,\n skip_save=False,\n is_import=False\n )\n\n if logging_on:\n logger.debug(' studsubj: ' + str(studsubj))\n logger.debug(' append_key: ' + str(append_key))\n\n if studsubj:\n # PR2023-01-03 was: append_dict['created'] = True\n #updated_studsubj_pk_list.append(studsubj.pk)\n #if logging_on:\n # logger.debug(' updated_studsubj_pk_list: ' + str(updated_studsubj_pk_list))\n\n recalc_subj_composition = True\n\n # values of append_key are 'created' 'changed' 'restored' or None\n if append_key:\n append_dict = {append_key: True}\n\n elif error_list:\n # TODO check if error is displayed correctly PR2021-07-21\n # yes, but messages html is displayed in msg_box. This one not in use??\n # PR2023-01-03 was: append_dict['err_create'] = ' '.join(error_list)\n append_dict = {'err_create': ' '.join(error_list)}\n if logging_on:\n logger.debug(' schemeitem: ' + str(schemeitem))\n logger.debug(' append_dict: ' + str(append_dict))\n\n# +++ update existing studsubj - also when studsubj is created - studsubj is None when deleted\n if studsubj and mode in ('create', 'update'):\n si_pk = studsubj.schemeitem_id\n si_dict = schemeitems_dict.get(si_pk)\n err_fields = []\n\n studsubj_pk_list, recalc_subj_comp = update_studsubj(\n studsubj_instance=studsubj,\n upload_dict=studsubj_dict,\n si_dict=si_dict,\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n is_secret_exam=False,\n msg_list=err_list,\n err_fields=err_fields,\n request=request\n )\n #if studsubj_pk_list:\n # for studsubj_pk in studsubj_pk_list:\n # if studsubj_pk not in updated_studsubj_pk_list:\n # updated_studsubj_pk_list.append(studsubj_pk)\n if recalc_subj_comp:\n recalc_subj_composition = True\n\n if studsubj and append_dict:\n updated_rows_append_dict[studsubj.pk] = append_dict\n# - end of loop\n# -------------------------------------------------\n if recalc_subj_composition:\n update_student_subj_composition(student_instance)\n\n if len(err_list):\n msg_html = '
'.join(err_list)\n messages.append({'class': \"border_bg_invalid\", 'msg_html': msg_html})\n\n# - add update_dict to update_wrap\n\n# must update all studsubjects from this student, because the exclamation sign must be updated\n # in all sudsubjects, not only the updeted ones\n updated_rows = create_studentsubject_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base if sel_school else None,\n sel_depbase=sel_department.base if sel_department else None,\n append_dict= updated_rows_append_dict,\n request=request,\n requsr_same_school=True, # check for same_school is included in may_edit\n student_pk=student_instance.pk\n )\n #PR2023-01-07 added to update composistion tickmark in all studsubjects of this student\n for row in updated_rows:\n row['changed'] = True\n\n if deleted_rows:\n updated_rows.extend(deleted_rows)\n\n if logging_on and False:\n logger.debug(' updated_rows: ' + str(updated_rows))\n\n if updated_rows:\n update_wrap['updated_studsubj_rows'] = updated_rows\n\n# +++ validate subjects of student\n # no message necessary, done by test before saving\n #msg_html = stud_val.Fstudent)\n #if msg_html:\n # update_wrap['studsubj_validate_html'] = msg_html\n #if logging_on:\n # logger.debug('msg_html: ' + str(msg_html))\n\n # has_error = stud_val.validate_studentsubjects_no_msg(student_instance, user_lang)\n\n #update_wrap['subj_error'] = has_error\n #update_wrap['stud_pk'] = student_instance.pk\n\n if len(messages):\n update_wrap['messages'] = messages\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# --- end of StudentsubjectMultipleUploadView\n\n\ndef delete_studentsubject(student_instance, studsubj_instance, request):\n # PR2021-07-18 PR2022-02-16 PR2022-08-05 PR2023-02-22\n\n # published fields are: subj_published, exem_published, reex_published, reex3_published, pok_published\n # if published: don't delete, but set 'tobedeleted' = True, so its remains in the Ex1 form\n # also remove approved and published info\n # PR2023-02-12 dont have to set grades 'tobedeleted', grdaes of deleted studsubj are fitered out by sql studsubj.tobedeleted=False\n # only exem, reex and reex03 grades are set tobedeleted when deleteingexem, reex or reex 3\n # was: also set grades 'tobedeleted'=True\n # if not published: delete studsubj, grades will be cascade deleted\n\n # PR2022-02-15 studentsubject can always be deleted\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- delete_studentsubject ----- ')\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n\n msg_html = None\n err_html = ''\n\n this_txt = None\n if studsubj_instance.schemeitem:\n subject = studsubj_instance.schemeitem.subject\n if subject and subject.name_nl:\n this_txt = _(\"Subject '%(tbl)s' \") % {'tbl': subject.name_nl}\n\n if logging_on:\n logger.debug(' subject: ' + str(subject))\n\n# - check if studsubj_instance is submitted\n if studsubj_instance.subj_published_id or \\\n studsubj_instance.sr_published_id or \\\n studsubj_instance.reex_published_id or \\\n studsubj_instance.reex3_published_id:\n is_submitted = True\n else:\n is_submitted = False\n if logging_on:\n logger.debug(' is_submitted: ' + str(is_submitted))\n\n# - when studsubj is submitted, tobedeleted is set True, studsubj will be retrieved by updated_rows = create_studentsubject_rows\n # the key 'tobedeleted' must be added via append_dict\n\n# - when studsubj is not yet submitted, deleted is set True, studsubj will NOT be retrieved by updated_rows = create_studentsubject_rows\n # therefore a dict with the info af the deleted row must be added to updated_rows at the end,\n # to remove the dict from the data_dicts and the tblrow\n\n deleted_row, tobedeleted_studsubj_pk = None, None\n\n studsubj_instance_pk = studsubj_instance.pk\n map_id = '_'.join(('studsubj', str(student_instance.pk), str(studsubj_instance.pk)))\n\n# - check if studentsubject has submitted grades or school is locked or examyear is locked PR2021-08-21\n # PR2022-02-15 studentsubject can always be deleted\n\n # PR2022-08-30 MAJOR BUG: student was deleted instead of studsubj,\n # because 'instance=student_instance' instead of 'instance=studsubj_instance'\n\n # PR2022-12-18 set tobedeleted=True and remove published info instead of deleting record, also in table grades\n # was:\n # # delete student will also cascade delete Grades\n # deleted_rowNIU, err_html = sch_mod.delete_instance(\n # table='studsubj', # used to create mapid in deleted_row\n # instance=studsubj_instance, # MAJOR BUG was: instance=student_instance\n # request=request,\n # this_txt=this_txt)\n\n try:\n\n updated_fields = []\n if is_submitted:\n setattr(studsubj_instance, 'tobedeleted', True)\n updated_fields.append('tobedeleted')\n\n # - also remove approved and published info, store it in prev_auth1by_id etc\n setattr(studsubj_instance, 'prev_auth1by_id', getattr(studsubj_instance, 'subj_auth1by_id', None))\n setattr(studsubj_instance, 'prev_auth2by_id', getattr(studsubj_instance, 'subj_auth2by_id', None))\n setattr(studsubj_instance, 'prev_published_id', getattr(studsubj_instance, 'subj_published_id', None))\n\n tobedeleted_studsubj_pk = studsubj_instance.pk\n else:\n setattr(studsubj_instance, 'deleted', True)\n setattr(studsubj_instance, 'tobedeleted', False)\n updated_fields.extend(('deleted', 'tobedeleted'))\n\n setattr(studsubj_instance, 'prev_auth1by_id', None)\n setattr(studsubj_instance, 'prev_auth2by_id', None)\n setattr(studsubj_instance, 'prev_published_id',None)\n\n # - create deleted_row, to be sent back to page\n deleted_row = {'id': studsubj_instance_pk,\n 'mapid': '_'.join(('studsubj', str(student_instance.pk), str(studsubj_instance.pk))),\n 'deleted': True}\n\n setattr(studsubj_instance, 'subj_auth1by_id', None)\n setattr(studsubj_instance, 'subj_auth2by_id', None)\n setattr(studsubj_instance, 'subj_published_id', None)\n updated_fields.extend(('subj_auth1by_id', 'subj_auth2by_id', 'subj_published_id'))\n\n studsubj_instance.save(request=request)\n\n # PR2023-08-14 Note: subj_auth1by_id etc have no effect in log, because value is already None.\n # must see if an extra field 'is_removed' is necessary\n awpr_log.savetolog_studentsubject(studsubj_instance.pk, 'u', request, updated_fields)\n\n if logging_on:\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n err_html = ''.join((\n str(_('An error occurred')), ':
', ' ', str(e), '
',\n str(_('%(cpt)s could not be deleted.') % {'cpt': this_txt})\n ))\n # msg_dict = {'header': header_txt, 'class': 'border_bg_invalid', 'msg_html': msg_html}\n\n # grades.tobedeleted and deleted are only used in exem, reex and reex3\n # NIU: err_html = delete_studentsubject_grades(studsubj_instance, this_txt, tobedeleted_row, updated_rows, request)\n\n if err_html:\n msg_html = err_html\n\n if logging_on:\n logger.debug('msg_html: ' + str(msg_html))\n logger.debug('deleted_row' + str(deleted_row))\n\n return deleted_row, tobedeleted_studsubj_pk, msg_html\n# - end of delete_studentsubject\n\n\ndef delete_studentsubject_grades(studsubj_instance, this_txt, request):\n logging_on = s.LOGGING_ON\n #PR2023-02-12 dont set grade.tobedeleted.\n # grade.tobedeleted is only used when deleting exem. reex or reex03\n err_html = None\n try:\n grades = stud_mod.Grade.objects.filter(\n studentsubject=studsubj_instance,\n tobedeleted=False\n )\n\n if logging_on:\n logger.debug(' grades: ' + str(grades))\n\n modifiedby_pk_str = str(request.user.pk)\n modifiedat_str = str(timezone.now())\n sql_keys = {'studsubj_id': studsubj_instance.pk}\n\n sql_list = [\n \"UPDATE students_grade\",\n \"SET tobedeleted = TRUE, deleted = TRUE,\",\n \"modifiedby_id =\", modifiedby_pk_str, \", modifiedat = '\", modifiedat_str, \"'\",\n \"WHERE students_grade.studentsubject_id = %(studsubj_id)s::INT\",\n \"RETURNING id;\"\n ]\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n\n if logging_on:\n rows = cursor.fetchall()\n logger.debug(' grade rows: ' + str(rows))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n err_html = ''.join((\n str(_('An error occurred')), ':
', ' ', str(e), '
',\n str(_('%(cpt)s could not be deleted.') % {'cpt': this_txt})\n ))\n deleted_row = None\n return err_html\n# end of delete_studentsubject_grades\n\n####################################################\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectSingleUpdateView(View): # PR2021-09-18 PR2023-04-01\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' ============= StudentsubjectSingleUpdateView ============= ')\n\n # function updates single studentsubject record\n update_wrap = {}\n\n msg_list = []\n err_fields = []\n border_class = None\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n page_name = upload_dict.get('page') or 'page_studsubj'\n is_secret_exam = page_name == 'page_secretexam'\n# - get permit\n # PR2023-05-31 also called by page secret exam to change ete_cluster\n has_permit = False\n req_usr = request.user\n if req_usr and req_usr.country and req_usr.schoolbase:\n has_permit = acc_prm.get_permit_crud_of_this_page(page_name, request)\n if logging_on:\n logger.debug(' has_permit: ' + str(has_permit))\n\n if not has_permit:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(acc_prm.err_txt_no_permit()) # default: 'to perform this action')\n else:\n\n # upload_dict: {'student_pk': 8470, 'studsubj_pk': 61203, 'has_exemption': True}\n # requsr_same_school = (request.user.role == c.ROLE_008_SCHOOL and request.user.schoolbase.pk == sel_schoolbase_pk)\n\n# - get selected examyear, school and department from usersettings\n # may_edit = False when:\n # - country is locked,\n # - examyear is not found, not published or locked\n # - school is not found, not same_school, not activated, or locked\n # - department is not found, not in user allowed depbase or not in school_depbase\n # - skip when student is tobedeleted or studsubj is tobedeleted happens further in this function\n\n # check requsr_same_school is part of get_selected_ey_school_dep_lvl_from_usersetting\n sel_examyear, sel_school, sel_department, sel_level, may_edit, err_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n if err_list:\n err_list.append(str(_('You cannot make changes.')))\n msg_list.extend(err_list)\n border_class = c.HTMLCLASS_border_bg_invalid\n else:\n if logging_on:\n logger.debug(' upload_dict: ' + str(upload_dict))\n logger.debug(' sel_examyear: ' + str(sel_examyear))\n logger.debug(' sel_school: ' + str(sel_school))\n logger.debug(' sel_department: ' + str(sel_department))\n\n# - get current student from upload_dict, filter: sel_school, sel_department, student is not locked\n\n student_pk = upload_dict.get('student_pk')\n student_instance = stud_mod.Student.objects.get_or_none(\n id=student_pk\n )\n if student_instance is None:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(str(_('%(cpt)s is not found.') % {'cpt': _('Candidate')}))\n elif student_instance.deleted:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(gettext(\"This candidate is deleted.\"))\n elif student_instance.tobedeleted:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.extend([gettext(\"This candidate is marked for deletion.\"), gettext(\"You cannot make changes.\")])\n else:\n if logging_on:\n logger.debug(' msg_list: ' + str(msg_list))\n logger.debug(' may_edit: ' + str(may_edit))\n logger.debug(' student_instance: ' + str(student_instance))\n\n # - get studentsubject from upload_dict\n studsubj_pk = upload_dict.get('studsubj_pk')\n studsubj = stud_mod.Studentsubject.objects.get_or_none(\n id=studsubj_pk,\n student=student_instance\n )\n if studsubj:\n if studsubj.deleted:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.append(gettext(\"This subject is deleted.\"))\n elif studsubj.tobedeleted:\n border_class = c.HTMLCLASS_border_bg_invalid\n msg_list.extend([gettext(\"This subject is marked for deletion.\"),\n gettext(\"You cannot make changes.\")])\n else:\n\n studsubj_pk_list = [studsubj.pk]\n\n if logging_on:\n logger.debug(' studsubj: ' + str(studsubj))\n\n # - validate if requsr has allowed_cluster to change this subject - validate allowed levl / subjects not necessary, because only allowed subjects are shown\n cluster_pk = studsubj.cluster_id\n userallowed_cluster_pk_list = acc_prm.get_userallowed_cluster_pk_list_from_request(request)\n # don't check allowed whenis_secret_exam\n is_allowed = acc_prm.validate_userallowed_cluster(userallowed_cluster_pk_list, cluster_pk) \\\n or is_secret_exam\n if not is_allowed:\n msg_list.append(gettext(\"You don't have permission %(cpt)s.\") % {\n 'cpt': gettext('to make changes in subjects of this cluster')})\n\n # return err_fields, to restore old value on client\n for fld_name in upload_dict:\n if fld_name in ('cluster_pk', 'pws_title', 'pws_subjects', 'exemption_year', 'is_thumbrule',\n 'is_extra_nocount', 'is_extra_countsNIU', 'has_exemption', 'has_reex', 'has_reex03', '_auth'):\n err_fields.append(fld_name)\n\n if logging_on:\n logger.debug(' err_fields: ' + str(err_fields))\n else:\n\n # - get schemitem_info, separately, instead of getting from grade_instance, should be faster\n si_pk = studsubj.schemeitem_id\n if logging_on:\n logger.debug('si_pk: ' + str(si_pk))\n\n schemeitems_dict = subj_vw.get_scheme_si_dict(\n examyear_pk=sel_examyear.pk,\n depbase_pk=sel_department.base_id,\n schemeitem_pk=si_pk\n )\n si_dict = schemeitems_dict.get(si_pk)\n\n # +++++ update studentsubject\n updated_pk_list, recalc_subj_comp = update_studsubj(\n studsubj_instance=studsubj,\n upload_dict=upload_dict,\n si_dict=si_dict,\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n is_secret_exam=is_secret_exam,\n msg_list=msg_list,\n err_fields=err_fields,\n request=request\n )\n if updated_pk_list:\n studsubj_pk_list.extend(updated_pk_list)\n\n if logging_on:\n logger.debug('updated_pk_list: ' + str(updated_pk_list))\n\n if recalc_subj_comp:\n update_student_subj_composition(student_instance)\n\n # - add update_dict to update_wrap\n # TODO check value of msg_dict\n # msg_dict['err_' + field] = str(_(\"Title and subjects only allowed in subjects with character 'Werkstuk'.\"))\n # msg_dict['err_update'] = _('An error occurred. The changes have not been saved.')\n append_dict = {}\n if err_fields:\n # PR2023-02-18 note: append_dict has key with studsubj_pk\n append_dict[studsubj.pk] = {'err_fields': err_fields}\n border_class = c.HTMLCLASS_border_bg_invalid\n\n if logging_on:\n logger.debug(' append_dict: ' + str(append_dict))\n\n # TODO PR2022-12-22 check if sel_lvlbase must get value\n if is_secret_exam:\n grade_pk = upload_dict.get('grade_pk')\n selected_pk_dict = acc_prm.get_usersetting_dict(c.KEY_SELECTED_PK, request)\n\n if logging_on:\n logger.debug('grade_pk: ' + str(grade_pk))\n logger.debug('selected_pk_dict: ' + str(selected_pk_dict))\n\n if grade_pk and selected_pk_dict:\n\n sel_examperiod = selected_pk_dict.get(c.KEY_SEL_EXAMPERIOD)\n if logging_on:\n logger.debug('sel_examperiod: ' + str(sel_examperiod))\n\n updated_grade_rows = grd_view.create_grade_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base if sel_school else None,\n sel_depbase=sel_department.base if sel_department else None,\n sel_lvlbase=sel_level.base if sel_level else None,\n sel_examperiod=sel_examperiod,\n secret_exams_only=is_secret_exam,\n # PR2021-06-01 debug. Remove key 'note_status', otherwise it will erase note icon when refreshing this row\n remove_note_status=True,\n request=request,\n append_dict=append_dict,\n grade_pk_list=[grade_pk]\n )\n if updated_grade_rows:\n update_wrap['updated_grade_rows'] = updated_grade_rows\n\n else:\n studsubj_rows = create_studentsubject_rows(\n sel_examyear=sel_examyear,\n sel_schoolbase=sel_school.base if sel_school else None,\n sel_depbase=sel_department.base if sel_department else None,\n append_dict=append_dict,\n request=request,\n requsr_same_school=True, # check for same_school is included in may_edit\n student_pk=student_instance.pk,\n studsubj_pk_list=studsubj_pk_list\n )\n if studsubj_rows:\n update_wrap['updated_studsubj_rows'] = studsubj_rows\n\n if msg_list:\n update_wrap['msg_html'] = acc_prm.msghtml_from_msglist_with_border(msg_list, border_class)\n\n# - return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=af.LazyEncoder))\n# - end of StudentsubjectSingleUpdateView\n\n\n#######################################################\ndef update_studsubj(studsubj_instance, upload_dict, si_dict, sel_examyear, sel_school, sel_department, is_secret_exam,\n msg_list, err_fields, request):\n # PR2019-06-06 PR2021-12-25 PR2022-04-15 PR2022-06-25 PR2022-08-25\n # --- update existing and new studsubj_instance PR2019-06-06\n # called by StudentsubjectMultipleUploadView, StudentsubjectSingleUpdateView, StudentsubjectApproveSingleView\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ------- update_studsubj -------')\n logger.debug(' upload_dict: ' + str(upload_dict))\n \"\"\"\n upload_dict{'mode': 'update', 'studsubj_pk': 26993, 'schemeitem_pk': 2033, 'subj_auth2by': 48}\n upload_dict: {'student_pk': 9224, 'studsubj_pk': 67818, 'has_reex': False}\n upload_dict: {'student_pk': 9226, 'studsubj_pk': 67836, 'subj_auth2by': True}\n \n when changing schemeitem_pk:\n upload_dict: {\n 'mode': 'update', \n 'student_pk': 5231, 'studsubj_pk': 45376, 'schemeitem_pk': 1721, \n 'is_extra_nocount': False, 'is_extra_counts': False, 'pws_title': None, 'pws_subjects': None, \n 'tobedeleted': False}\n \"\"\"\n\n save_changes = False\n recalc_finalgrade = False\n recalc_subj_composition = False\n updated_fields = []\n\n studsubj_pk_list = []\n for field, new_value in upload_dict.items():\n\n# +++ save changes in studsubj_instance fields\n if field == 'schemeitem_pk':\n saved_schemeitem = getattr(studsubj_instance, 'schemeitem')\n new_schemeitem = subj_mod.Schemeitem.objects.get_or_none(pk=new_value)\n if logging_on:\n logger.debug(' saved studsubj_schemeitem: ' + str(saved_schemeitem))\n logger.debug(' new_schemeitem: ' + str(new_schemeitem))\n\n if new_schemeitem is None:\n msg_list.append(str(_(\"Subject scheme of this subject is not found.\")))\n\n elif saved_schemeitem:\n if new_schemeitem.pk != saved_schemeitem.pk:\n setattr(studsubj_instance, 'schemeitem', new_schemeitem)\n\n # - also remove approved and published info\n # TODO also from grades??\n subj_published_id = getattr(studsubj_instance, 'subj_published_id')\n setattr(studsubj_instance, 'prev_auth1by_id', getattr(studsubj_instance, 'subj_auth1by_id', None))\n setattr(studsubj_instance, 'prev_auth2by_id', getattr(studsubj_instance, 'subj_auth2by_id', None))\n setattr(studsubj_instance, 'prev_published_id', subj_published_id)\n\n setattr(studsubj_instance, 'subj_auth1by', None)\n setattr(studsubj_instance, 'subj_auth2by', None)\n setattr(studsubj_instance, 'subj_published', None)\n\n # PR2023-08-30 Hans Vlinkervleugel: gives open circle before submitting first Ex1.\n # solved bij adding check if is_published\n if subj_published_id:\n setattr(studsubj_instance, 'tobechanged', True)\n\n save_changes = True\n recalc_finalgrade = True\n recalc_subj_composition = True\n updated_fields.append('schemeitem_id')\n\n if logging_on:\n logger.debug('>>>>> new_schemeitem save')\n\n elif field in ['pws_title', 'pws_subjects']:\n # only allowed when subjecttype has_pws = True\n if not studsubj_instance.schemeitem.subjecttype.has_pws:\n if new_value:\n subj_name = studsubj_instance.schemeitem.subject.name_nl\n msg_list.append(str(_(\"Title and subjects are not allowed in subject %(cpt)s.\") % {'cpt': subj_name}))\n else:\n err_list = []\n saved_value = getattr(studsubj_instance, field)\n if logging_on:\n logger.debug('saved_value: ' + str(saved_value))\n\n if new_value:\n err_list = stud_val.validate_studsubj_pws_title_subjects_length(field, new_value)\n if err_list:\n msg_list.extend(err_list)\n err_fields.append(field)\n\n if not err_list:\n if new_value != saved_value:\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n\n elif field == 'cluster_pk':\n new_cluster = subj_mod.Cluster.objects.get_or_none(pk=new_value)\n # when secret_exam the field 'ete_cluster' is used PR2023-05-31\n db_field = 'ete_cluster' if is_secret_exam else 'cluster'\n saved_cluster = getattr(studsubj_instance, db_field)\n if new_cluster != saved_cluster:\n setattr(studsubj_instance, db_field, new_cluster)\n save_changes = True\n updated_fields.append('cluster_id')\n\n elif field == 'exemption_year':\n # changing is only allowed when evening or lex student. Is set on client side\n saved_value = getattr(studsubj_instance, field)\n if logging_on:\n logger.debug('field: ' + str(field))\n logger.debug('new_value: ' + str(new_value))\n logger.debug('saved_value: ' + str(saved_value))\n if new_value != saved_value:\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n recalc_finalgrade = True\n updated_fields.append(field)\n\n elif field == 'is_thumbrule':\n saved_value = getattr(studsubj_instance, field)\n err_list = []\n if new_value:\n err_list = stud_val.validate_thumbrule_allowed(studsubj_instance, si_dict)\n if err_list:\n msg_list.extend(err_list)\n err_fields.append(field)\n\n if not err_list:\n if logging_on:\n logger.debug('saved_value: ' + str(saved_value) + str(type(new_value)))\n logger.debug('new_value: ' + str(new_value) + str(type(new_value)))\n\n if new_value != saved_value:\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n err_fields.append(field)\n\n # when combi: apply or remove thumbrule also to other combi subjects\n if studsubj_instance.schemeitem.is_combi:\n other_combi_subjects = stud_mod.Studentsubject.objects.filter(\n student=studsubj_instance.student,\n schemeitem__is_combi=True,\n tobedeleted=False,\n deleted=False\n ).exclude(pk=studsubj_instance.pk)\n\n if other_combi_subjects:\n for other_combi in other_combi_subjects:\n setattr(other_combi, field, new_value)\n other_combi.save(request=request)\n studsubj_pk_list.append(other_combi.pk)\n\n if new_value:\n set_remove = str(pgettext_lazy('the thumbrule is set to', 'set to'))\n else:\n set_remove =str(pgettext_lazy('the thumbrule is removed from', 'removed from'))\n msg_list.append(\n str(_('The thumb rule is only applicable to the combination grade, not to individual combi subjects.')))\n msg_list.append(\n str(_('Therefore the thumbrule is also %(cpt)s the other combi subjects of this candidate.') %{'cpt': set_remove}))\n\n elif field in ('is_extra_nocount', 'is_extra_countsNIU'):\n err_list = []\n if new_value:\n err_list = stud_val.validate_extra_nocount_allowed(studsubj_instance)\n if err_list:\n msg_list.extend(err_list)\n err_fields.append(field)\n\n if not err_list:\n saved_value = getattr(studsubj_instance, field)\n if logging_on:\n logger.debug(\"new value of field '\" + str(field) + \"': \" + str(new_value))\n logger.debug(\"saved value of field '\" + str(field) + \"': \" + str(saved_value))\n\n if new_value != saved_value:\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n err_fields.append(field)\n\n # TODO check or delete has_sr, disabled for now\n elif field == 'has_sr' and False:\n saved_value = getattr(studsubj_instance, field)\n# +++++ add or delete re-examination school exam\n # - toggle value of has_sr:\n # - set sr = None\n # - recalc grade (sesr, pece, final)\n # - recalc max_ etc in studsubj\n # - recalc result in student\n if new_value != saved_value:\n err_list = []\n # - get grade of first exam period\n grade_firstperiod = stud_mod.Grade.objects.get_or_none(\n studentsubject=studsubj_instance,\n examperiod=c.EXAMPERIOD_FIRST\n )\n\n if logging_on:\n logger.debug('grade_firstperiod: ' + str(grade_firstperiod))\n\n if grade_firstperiod is None:\n msg_list.append(str(_('An error occurred')))\n msg_list.append(str(_('Grade record not found')))\n else:\n recalc_grade_firstperiod = False\n # +++ add re-examination school exam:\n if new_value:\n # - check if adding sr is allowed\n err_list = stud_val.validate_studsubj_sr_allowed(si_dict)\n if err_list:\n msg_list.extend(err_list)\n else:\n # - save has_sr\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n recalc_finalgrade = True\n recalc_grade_firstperiod = True\n err_fields.append(field)\n else:\n# +++ delete re-examination school exam:\n # - check if deleting sr is allowed\n # note: a sr can be deleted when it is submitted but does not have an approved grade yet\n\n this_item_cpt = str(_('This re-examination school exam'))\n err_list = grad_val.validate_grade_published_from_gradeinstance(grade_firstperiod, 'sr', this_item_cpt)\n if err_list:\n err_list.append(str(_('You cannot delete %(cpt)s.') % {'cpt': this_item_cpt.lower()}))\n\n if logging_on:\n logger.debug('.............. err_list: ' + str(err_list))\n\n if err_list:\n msg_list.extend(err_list)\n else:\n # - save when new_value != saved_value and no error\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n recalc_finalgrade = True\n err_fields.append(field)\n\n # remove value from srgrade, also remove approval and published info\n setattr(grade_firstperiod, 'srgrade', None)\n setattr(grade_firstperiod, 'sr_auth1by_id', None)\n setattr(grade_firstperiod, 'sr_auth2by_id', None)\n setattr(grade_firstperiod, 'sr_published_id', None)\n recalc_grade_firstperiod = True\n\n if recalc_grade_firstperiod:\n # recalculate sesr, pece, final in all grade_periods\n grd_view.recalc_finalgrade_in_grade_and_save(grade_firstperiod, si_dict)\n grade_firstperiod.save()\n # TODO savelog\n # - count 'exemption', 'sr', 'reex', 'reex03', 'is_thumbrule' records of this student an save count in student\n update_reexcount_etc_in_student(field, studsubj_instance.student_id)\n\n elif field in ['has_exemption', 'has_reex', 'has_reex03']:\n # upload_dict: {'student_pk': 4432, 'studsubj_pk': 27484, 'has_reex': False}\n # field = 'has_reex', new_value = False\n\n# +++++ add or delete exemption, reex, reex03\n # - toggle value of has_exemption, has_reex or has_reex03\n # - when add: add grade with examperiod = 4, 2 or 3\n # - when reex or reex03: add segrade, srgrade and pegrade in reex grade_instance\n # - when delete: set 'tobedeleted' = True and reset all values of grade\n # - recalc max_ etc in studsubj\n # - recalc result in student\n\n must_add_or_delete_exem_reex_reex03 = False\n\n# +++++ add exemption, reex, reex03\n if new_value:\n\n # - validate if adding reex or reex03 is allowed\n err_list = stud_val.validate_studsubj_add_reex_reex03_allowed(field, si_dict)\n\n # don't check if the number of re-examinations equals or exceeds the maximum\n # students that have been sick may do multiple reex\n # was: if not err_list:\n # err_list = stud_val.validate_reex_count(studsubj_instance, si_dict)\n\n if err_list:\n msg_list.extend(err_list)\n err_fields.append(field)\n else:\n saved_value = getattr(studsubj_instance, field)\n if logging_on:\n logger.debug(' add reex, field: ' + str(field) + ' new_value: ' + str(new_value) + ' saved_value: ' + str(saved_value))\n\n if new_value != saved_value:\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n recalc_finalgrade = True\n must_add_or_delete_exem_reex_reex03 = True\n err_fields.append(field)\n\n if logging_on:\n logger.debug(' add reex, field: ' + str(field) + ' ' + str(new_value))\n\n recalc_reex_grade = field in ('has_reex', 'has_reex03')\n # - when setting exemption: fill in previous examyear as exemption_year PR2022-04-15\n if field == 'has_exemption':\n previous_exam_year = sel_examyear.code - 1\n setattr(studsubj_instance, 'exemption_year', previous_exam_year)\n\n else:\n\n# +++++ delete exemption, sr, reex, reex03\n # - get saved value\n saved_value = getattr(studsubj_instance, field)\n if logging_on:\n logger.debug(' delete reex, field: ' + str(field))\n logger.debug(' delete reex, saved_value: ' + str(saved_value))\n logger.debug(' delete reex, new_value: ' + str(new_value))\n\n # - save when new_value != saved_value\n if new_value != saved_value:\n\n # - check if deleting is allowed\n # check if grade is authorized, published or blocked\n err_list = grad_val.validate_exem_sr_reex_reex03_delete_allowed(\n studsubj_instance=studsubj_instance,\n field=field\n )\n\n if err_list:\n msg_list.extend(err_list)\n err_fields.append(field)\n else:\n # - set 'has_exemption' or 'has_reex' or 'has_reex03 False\n setattr(studsubj_instance, field, new_value)\n save_changes = True\n recalc_finalgrade = True\n must_add_or_delete_exem_reex_reex03 = True\n err_fields.append(field)\n\n if logging_on:\n logger.debug(' removed reex, field: ' + str(field) + ' new_value: ' + str(new_value))\n\n # - when deleting exemption: also delete exemption_year PR2022-04-15\n if field == 'has_exemption':\n setattr(studsubj_instance, 'exemption_year', None)\n err_fields.append('exemption_year')\n\n# --- add exem, reex, reex03 grade or make grade 'tobedeleted'\n # when adding: also put values of segrade, srgrade and pegrade in new grade_instance\n if must_add_or_delete_exem_reex_reex03:\n err_list = add_or_delete_grade_exem_reex_reex03( field, studsubj_instance, new_value, request)\n if logging_on:\n logger.debug(' err_list: ' + str(err_list))\n\n if err_list:\n msg_list.extend(err_list)\n err_fields.append(field)\n # - count 'exemption', 'sr', 'reex', 'reex03' records of this student an save count in student\n update_reexcount_etc_in_student(field, studsubj_instance.student_id)\n\n elif '_auth' in field:\n\n prefix, authby = field.split('_')\n if logging_on:\n\n logger.debug(' field: ' + str(field) )\n logger.debug(' new_value: ' + str(new_value))\n logger.debug(' prefix: ' + str(prefix) )\n logger.debug(' authby: ' + str(authby) )\n\n# - check if instance is published. Authorization of published instances cannot be changed.\n err_published, err_same_user = False, False\n fld_published = prefix + '_published'\n item_published = getattr(studsubj_instance, fld_published)\n if logging_on:\n logger.debug(str(fld_published) + ': ' + str(item_published))\n\n if item_published:\n err_published = True\n msg_list.append(str(_('This item is published. You cannot change its authorization.')))\n\n# - check other authorization, to check if it is the same user. Only when auth is set to True\n elif new_value:\n authby_other = 'auth2by' if authby == 'auth1by' else 'auth1by'\n fld_other = prefix + '_' + authby_other\n other_authby = getattr(studsubj_instance, fld_other)\n if logging_on:\n logger.debug(' fld_other: ' + str(fld_other))\n logger.debug(' other_authby: ' + str(other_authby))\n logger.debug(' request.user: ' + str(request.user) )\n\n if other_authby and other_authby == request.user:\n err_same_user = True\n err_fields.append(field)\n\n msg_list.extend((\n gettext('You already have approved %(cpt)s in a different function.') % {\n 'cpt': gettext('this subject')},\n gettext('You cannot approve %(cpt)s in multiple functions.') % {'cpt': gettext('a subject')}\n ))\n\n if logging_on:\n logger.debug(' err_same_user: ' + str(err_same_user))\n\n if not err_published and not err_same_user:\n # value of new_value is True or False, not aurh_id or None\n # use request.user or None as new_value\n if logging_on:\n logger.debug('new_value: ' + str(new_value) )\n if new_value:\n setattr(studsubj_instance, field, request.user)\n else:\n setattr(studsubj_instance, field, None)\n save_changes = True\n # --- end of for loop ---\n\n# 5. save changes`\n if save_changes:\n try:\n studsubj_instance.save(request=request)\n if logging_on:\n logger.debug('The changes have been saved: ' + str(studsubj_instance))\n\n awpr_log.savetolog_studentsubject(studsubj_instance.pk, 'u', request, updated_fields)\n\n except Exception as e:\n recalc_subj_composition = False\n logger.error(getattr(e, 'message', str(e)))\n msg_list.append(acc_prm.errhtml_error_occurred_with_border(e, _('The changes have not been saved.')))\n else:\n\n if logging_on:\n logger.debug(' recalc_finalgrade: ' + str(recalc_finalgrade))\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n\n if recalc_finalgrade:\n grades = stud_mod.Grade.objects.filter(\n studentsubject=studsubj_instance,\n tobedeleted=False,\n deleted=False\n )\n if logging_on:\n logger.debug('grades: ' + str(grades))\n\n for grade_instance in grades:\n if logging_on:\n logger.debug('grade_instance: ' + str(grade_instance))\n logger.debug('grade_instance.examperiod: ' + str(grade_instance.examperiod))\n # - recalculate gl_sesr, gl_pece, gl_final, gl_use_exem in studsubj record\n if grade_instance and grade_instance.examperiod == c.EXAMPERIOD_FIRST:\n # when first examperiod: also update and save grades in reex, reex03, if exist\n grd_view.recalc_finalgrade_in_reex_reex03_grade_and_save(grade_instance, si_dict)\n\n sql_studsubj_list, sql_student_list = [], []\n try:\n student = studsubj_instance.student\n if logging_on:\n logger.debug('student: ' + str(student))\n\n sql_studsubj_list, sql_student_list = grd_view.update_studsubj_and_recalc_student_result(\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n student=studsubj_instance.student\n )\n if logging_on:\n logger.debug('sql_studsubj_list: ' + str(sql_studsubj_list))\n logger.debug('sql_student_list: ' + str(sql_student_list))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n try:\n if sql_studsubj_list:\n calc_res.save_studsubj_batch(sql_studsubj_list)\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n try:\n # save calculated fields in student\n if sql_student_list:\n calc_res.save_student_batch(sql_student_list)\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n if logging_on:\n logger.debug('msg_list: ' + str(msg_list))\n logger.debug(' ..... end of update_studsubj .....')\n return studsubj_pk_list, recalc_subj_composition\n# --- end of update_studsubj\n\n\ndef update_student_subj_composition(student_instance):\n # PR2022-08-30\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ------- update_student_subj_composition -------')\n logger.debug(' student_instance: ' + str(student_instance))\n\n\n no_error = not stud_val.validate_studentsubjects_no_msg(student_instance, 'nl')\n if (not student_instance.subj_composition_checked) or \\\n (student_instance.subj_composition_checked and student_instance.subj_composition_ok != no_error):\n setattr(student_instance, 'subj_composition_checked', True)\n setattr(student_instance, 'subj_composition_ok', no_error)\n # dont update modified by\n student_instance.save()\n\n if logging_on:\n logger.debug(' subj_composition_checked: ' + str(student_instance.subj_composition_checked))\n logger.debug(' subj_composition_ok: ' + str(student_instance.subj_composition_ok))\n\n# --- end of update_student_subj_composition\n\n\ndef add_or_delete_grade_exem_reex_reex03(field, studsubj_instance, new_value, request): # PR2021-12-15 PR2023-05-27\n # fields are 'has_exemption', 'has_reex', 'has_reex03'\n # when new_value = True: add or undelete grade\n # when new_value = False: make grade 'tobedeleted', remove all values if allowed\n\n # PR2023-05-27 add exam if only one published exam\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ------- add_or_delete_grade_exem_reex_reex03 -------')\n logger.debug(' field: ' + str(field))\n\n exam_period = None\n if field == 'has_exemption':\n exam_period = c.EXAMPERIOD_EXEMPTION\n elif field == 'has_reex':\n exam_period = c.EXAMPERIOD_SECOND\n elif field == 'has_reex03':\n exam_period = c.EXAMPERIOD_THIRD\n\n if logging_on:\n logger.debug(' exam_period: ' + str(exam_period))\n logger.debug(' new_value: ' + str(new_value))\n\n err_list = []\n\n try:\n save_changes = False\n\n# if new_value = True: check if reex / reex03 has only one exam\n ce_exam = None\n if new_value:\n ce_exam = get_exam_if_only_one_available_from_studsubj(studsubj_instance, exam_period)\n\n# - check if grade of this exam_period exists\n # Note: don't use get_or_none, returns None when multiple records exists and therefore will add another one\n grade = stud_mod.Grade.objects.filter(\n studentsubject=studsubj_instance,\n examperiod=exam_period\n ).first()\n\n if logging_on:\n logger.debug(' grade exists: ' + str(grade))\n\n# +++ add or undelete grade\n # when new_value = True: add or undelete grade\n if new_value:\n save_changes = True\n\n if grade:\n if logging_on:\n logger.debug(' grade deleted: ' + str(grade.deleted))\n # - if grade exists: it must be deleted row. Undelete\n\n # TODO PR2023-01-23 replace grade 'tobedeleted' by grade 'deleted', let 'tobedeleted' stay for now\n setattr(grade, 'tobedeleted', False)\n setattr(grade, 'deleted', False)\n # when deleting grade, ce_exam info is erased. Add exam if found\n setattr(grade, 'ce_exam', ce_exam)\n\n ce_exam = ce_exam\n\n if logging_on:\n logger.debug(' grade deleted: ' + str(grade.deleted))\n else:\n # - if grade does not exist: create new grade row\n grade = stud_mod.Grade(\n studentsubject=studsubj_instance,\n examperiod=exam_period,\n # add ce_exam if found\n ce_exam=ce_exam\n )\n\n if logging_on:\n logger.debug(' grade new: ' + str(exam_period))\n\n # if 2nd or 3rd period: get se sr pe from first period and put them in new grade\n # PR2022-01-05 dont save se, sr, pe in reex reex03 any more\n # PR2022-05-29 changed my mind: due to batch update needs those grades in reex_grade to calc final grade\n # must make sure that values in reex_grade are updated when update them in ep 1\n if exam_period in (c.EXAMPERIOD_SECOND, c.EXAMPERIOD_THIRD):\n found, segrade, srgrade, pegrade = get_se_sr_pe_from_grade_ep1(studsubj_instance)\n\n if logging_on:\n logger.debug(' segrade: ' + str(segrade))\n\n if found:\n setattr(grade, 'segrade', segrade)\n setattr(grade, 'srgrade', srgrade)\n setattr(grade, 'pegrade', pegrade)\n if logging_on:\n logger.debug(' segrade: ' + str(segrade))\n else:\n if grade:\n if logging_on:\n logger.debug(' set grade tobedeleted ')\n\n# +++ when new_value = False: set grade tobedeleted\n # - when new has_exemption etc. is False: delete row by setting deleted=True and reset all fields\n clear_grade_fields(grade)\n # TODO PR2023-012-12 check difference between grade 'tobedeleted' and grade 'deleted'\n setattr(grade, 'tobedeleted', True)\n setattr(grade, 'deleted', True)\n save_changes = True\n\n if logging_on:\n logger.debug(' set grade deleted and tobedeleted : ' + str(grade.deleted))\n\n if save_changes:\n grade.save(request=request)\n if logging_on:\n logger.debug(' changes in grade are saved ')\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n err_list.append(str(_('An error occurred. The changes have not been saved.')))\n\n return err_list\n# --- end of add_or_delete_grade_exem_reex_reex03\n\n\ndef get_exam_if_only_one_available_from_studsubj(studsubj_instance, examperiod):\n # PR2022-08-26 PR2023-05-27\n # this function counts number of exams of this subject / dep / level / examperiod\n\n # - skip when there is more than 1 exam for this subject / dep / level / examperiod\n # in SXM subject may have ETE exams (ey=cur) and DUO examns (ey=sxm) How to deal with this?\n # - first check number of exams both in cur and sxm (filter by ey_code)\n # if only 1 exists: get that one\n # - if multiple exist: check number of exams in this country, if 1 exists: get that one\n # - when sxm has not his own exam,\n\n # PR2023-05-27 add exam if only one published exam\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ------- get_exam_if_only_one_available_from_studsubj -------')\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n logger.debug(' examperiod: ' + str(examperiod))\n\n def get_studsubj_info():\n studsub_sql = ' '.join((\n \"SELECT dep.base_id, lvl.base_id, subj.base_id, dep.examyear_id, ey.code\",\n \"FROM students_studentsubject AS studsub\",\n \"INNER JOIN subjects_schemeitem AS si ON (si.id = studsub.schemeitem_id)\",\n \"INNER JOIN subjects_scheme AS scheme ON (scheme.id = si.scheme_id)\",\n \"INNER JOIN subjects_subject AS subj ON (subj.id = si.subject_id)\",\n \"INNER JOIN schools_department AS dep ON (dep.id = scheme.department_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = dep.examyear_id)\",\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = scheme.level_id)\",\n \"WHERE studsub.id =\", str(studsubj_instance.pk), \"::INT\"\n ))\n\n with connection.cursor() as cursor:\n cursor.execute(studsub_sql)\n row = cursor.fetchone()\n if row:\n # depbase_id, lvlbase_id, subjbase_id, ey_id, ey_code\n return row[0], row[1], row[2], row[3], row[4]\n else:\n return None, None, None, None, None\n\n def get_exam_if_only_one_available(ey_pk, ey_code, examperiod, depbase_id, lvlbase_id, subjbase_id, get_from_all_countries):\n # PR2023-05-27 add exam if only one published exam\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ......... get_exam_if_only_one_available .........')\n logger.debug(' get_from_all_countries: ' + str(get_from_all_countries))\n\n exams_found = False\n exam_id = None\n\n sql_list = [\n \"SELECT exam.id\",\n \"FROM subjects_exam AS exam\",\n \"INNER JOIN subjects_subject AS subj ON (subj.id = exam.subject_id)\",\n\n \"INNER JOIN schools_department AS dep ON (dep.id = exam.department_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = dep.examyear_id)\",\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = exam.level_id)\",\n\n \"WHERE dep.base_id =\", str(depbase_id), \"::INT\",\n \"AND subj.base_id =\", str(subjbase_id), \"::INT\",\n \"AND exam.examperiod =\", str(examperiod), \"::INT\",\n ]\n\n if lvlbase_id:\n sql_list.extend((\"AND lvl.base_id =\", str(lvlbase_id), \"::INT\"))\n\n if get_from_all_countries:\n # when all_countries: only get published ETE exams\n sql_list.extend((\n \"AND ey.code =\", str(ey_code), \"::INT\",\n \"AND (exam.published_id IS NOT NULL AND exam.ete_exam)\"\n ))\n else:\n # when only this country: get CVTE exams + published ETE exams\n sql_list.extend((\n \"AND ey.id =\", str(ey_pk), \"::INT\",\n \"AND (exam.published_id IS NOT NULL OR NOT exam.ete_exam)\"\n ))\n\n sql = ' '.join(sql_list)\n\n if logging_on:\n logger.debug(' sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql)\n rows = cursor.fetchall()\n\n if logging_on:\n logger.debug(' len(rows): ' + str(len(rows)))\n\n # when there is only one exam: take that one (can be from this country or other country (when sxm has ETE exam)\n if rows:\n exams_found = True\n if len(rows) == 1:\n exam_id = rows[0][0]\n\n if logging_on:\n for row in rows:\n logger.debug(' > : ' + str(row))\n\n return exams_found, exam_id\n# - end of get_exam_if_only_one_available\n\n# - get studsubj info\n depbase_id, lvlbase_id, subjbase_id, ey_pk, ey_code = get_studsubj_info()\n\n if logging_on:\n logger.debug(' depbase_id: ' + str(depbase_id))\n logger.debug(' lvlbase_id: ' + str(lvlbase_id))\n logger.debug(' subjbase_id: ' + str(subjbase_id))\n logger.debug(' ey_pk: ' + str(ey_pk))\n logger.debug(' ey_code: ' + str(ey_code))\n\n# - first check if there are published exams of this country\n get_from_all_countries = False\n exams_found, exam_id = get_exam_if_only_one_available(\n ey_pk, ey_code, examperiod, depbase_id, lvlbase_id, subjbase_id, get_from_all_countries)\n\n if logging_on:\n logger.debug(' exams_found: ' + str(exams_found))\n logger.debug(' exam_id: ' + str(exam_id))\n\n# - if there are no published exams of this country: check if any in all countries\n if not exams_found:\n get_from_all_countries = True\n exams_found, exam_id = get_exam_if_only_one_available(\n ey_pk, ey_code, examperiod, depbase_id, lvlbase_id, subjbase_id, get_from_all_countries)\n if logging_on:\n logger.debug(' exams_found: ' + str(exams_found))\n logger.debug(' exam_id: ' + str(exam_id))\n\n exam = None\n if exam_id:\n exam = subj_mod.Exam.objects.get_or_none(pk=exam_id)\n\n if logging_on:\n logger.debug(' exam: ' + str(exam))\n\n return exam\n# --- end of get_exam_if_only_one_available_from_studsubj\n\n\ndef clear_grade_fields(grade_instance): # PR2021-12-24\n for fld in ('pescore', 'cescore', 'segrade', 'srgrade', 'sesrgrade',\n 'pegrade', 'cegrade', 'pecegrade', 'finalgrade'):\n setattr(grade_instance, fld, None)\n\n for prefix in ('se', 'sr', 'pe', 'ce'):\n for suffix in ('auth1by_id', 'auth2by_id', 'auth3by_id', 'auth4by_id', 'published_id'):\n fld = '_'.join((prefix, suffix))\n setattr(grade_instance, fld, None)\n\n fld = '_'.join((prefix, 'status'))\n setattr(grade_instance, fld, 0)\n\n fld = '_'.join((prefix, 'blocked'))\n setattr(grade_instance, fld, False)\n\n for prefix in ('pe', 'ce'):\n for suffix in ('exam_id', 'exam_result', 'exam_auth1by_id', 'exam_auth2by_id', 'exam_published_id'):\n fld = '_'.join((prefix, suffix))\n setattr(grade_instance, fld, None)\n fld = '_'.join((prefix, 'blocked'))\n setattr(grade_instance, fld, False)\n# - end of clear_grade_fields\n\n\ndef get_se_sr_pe_from_grade_ep1(studentsubject): # PR2021-12-25 PR2022-05-29\n # functions returns value of se, sr, pe from first period,\n # called when creating grade of 2nd or 3rd period\n\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ------- get_se_sr_pe_from_grade_ep1 -------')\n logger.debug('studentsubject: ' + str(studentsubject))\n\n segrade, srgrade, pegrade = None, None, None\n found = False\n\n# get grade of first examperiod\n # Note: with .values a dict is returned, not a model instance\n # grade_first_period: {'segrade': '5,7', 'srgrade': None, 'pegrade': '4.3'}\n grades_first_period = stud_mod.Grade.objects.filter(\n studentsubject=studentsubject,\n examperiod=c.EXAMPERIOD_FIRST\n ).values('segrade', 'srgrade', 'pegrade')\n\n grade_first_period = None\n found, multiple_found = False, False\n if grades_first_period:\n for row in grades_first_period:\n if logging_on:\n logger.debug('row: ' + str(row))\n\n if not found:\n found = True\n grade_first_period = row\n else:\n multiple_found = True\n break\n\n# - give error when there are zero or multiple grade rows with first examperiod, should not be possible\n if grade_first_period is None:\n logger.error('ERROR: ' + ('multiple' if multiple_found else 'no' ) + ' grades found in first examperiod.')\n logger.error(' studentsubject: ' + str(studentsubject))\n logger.error(' student: ' + str(studentsubject.student))\n else:\n found = True\n segrade = grade_first_period.get('segrade')\n srgrade = grade_first_period.get('srgrade')\n pegrade = grade_first_period.get('pegrade')\n\n if logging_on:\n logger.debug(' >>> segrade: ' + str(segrade))\n logger.debug(' >>> srgrade: ' + str(srgrade))\n logger.debug(' >>> pegrade: ' + str(pegrade))\n\n return found, segrade, srgrade, pegrade\n# - end of get_se_sr_pe_from_grade_ep1\n\n# NOT IN USE\ndef copy_grade_fields_from_firstperiod(grade_instance): # PR2021-12-25\n for fld in ('pescore', 'cescore', 'segrade', 'srgrade', 'sesrgrade',\n 'pegrade', 'cegrade', 'pecegrade', 'finalgrade'):\n\n setattr(grade_instance, fld, None)\n\n for prefix in ('se', 'sr', 'pe', 'ce'):\n for suffix in ('auth1by_id', 'auth2by_id', 'auth3by_id', 'auth4by_id', 'published_id'):\n fld = '_'.join((prefix, suffix))\n setattr(grade_instance, fld, None)\n\n fld = '_'.join((prefix, 'status'))\n setattr(grade_instance, fld, 0)\n\n fld = '_'.join((prefix, 'blocked'))\n setattr(grade_instance, fld, False)\n\n for prefix in ('pe', 'ce'):\n for suffix in ('exam_id', 'exam_result', 'exam_auth1by_id', 'exam_auth2by_id', 'exam_published_id'):\n fld = '_'.join((prefix, suffix))\n setattr(grade_instance, fld, None)\n fld = '_'.join((prefix, 'blocked'))\n setattr(grade_instance, fld, False)\n\n\ndef update_reexcount_etc_in_student(field, student_pk=None): # PR2021-12-19 PR2021-12-25 PR2022-06-05\n # values of field are 'has_exemption', 'has_sr', 'has_reex', 'has_reex03'\n\n # when 'has_exemption', 'has_reex', 'has_reex03': function counts grade records of this student\n # when 'has_sr', 'is_thumbrule': function counts studsubj records with value = True\n\n # with filter:\n # - student_pk\n # - sel_examperiod\n # - 'grd.tobedeleted' = False and studsubj.tobedeleted = False\n # - when has_sr: studsubj.has_sr = True\n # - when exemption, reex, reex03: no check on has_reex; grade with this ep does not exist when has_reex = False\n # Attention: must count after adding grade or saving tobedeleted = True\n\n logging_on = False #s.LOGGING_ON\n if logging_on:\n logger.debug('----------- update_reexcount_etc_in_student ----------- ')\n logger.debug(' field: ' + str(field))\n logger.debug(' student_pk: ' + str(student_pk))\n\n if field in ('has_exemption', 'has_sr', 'has_reex', 'has_reex03', 'is_thumbrule'):\n if True:\n # try:\n examperiod = c.EXAMPERIOD_EXEMPTION if field == 'has_exemption' else \\\n c.EXAMPERIOD_THIRD if field == 'has_reex03' else \\\n c.EXAMPERIOD_SECOND if field == 'has_reex' else \\\n c.EXAMPERIOD_FIRST\n db_field = 'exemption_count' if field == 'has_exemption' else \\\n 'reex03_count' if field == 'has_reex03' else \\\n 'reex_count' if field == 'has_reex' else \\\n 'thumbrule_count' if field == 'is_thumbrule' else \\\n 'sr_count'\n\n if logging_on:\n logger.debug(' examperiod: ' + str(examperiod))\n logger.debug(' db_field: ' + str(db_field))\n logger.debug(' student_pk: ' + str(student_pk))\n\n sql_keys = {'ep': examperiod}\n\n sub_sql_list = [\n \"SELECT stud.id AS student_id, COUNT(*) AS record_count\",\n\n \"FROM students_grade AS grd\",\n \"INNER JOIN students_studentsubject AS studsubj ON (studsubj.id = grd.studentsubject_id)\",\n \"INNER JOIN students_student AS stud ON (stud.id = studsubj.student_id)\",\n\n \"WHERE grd.examperiod = %(ep)s::INT\",\n \"AND NOT grd.tobedeleted AND NOT grd.deleted AND NOT studsubj.tobedeleted\"\n ]\n if field == 'has_sr':\n sub_sql_list.append(\"AND studsubj.has_sr\")\n elif field == 'is_thumbrule':\n sub_sql_list.append(\"AND studsubj.is_thumbrule\")\n\n sub_sql_list.append( \"GROUP BY stud.id\")\n sub_sql = ' '.join(sub_sql_list)\n\n # sub_sql row: {'student_id': 4671, 'count': 4}\n\n sql_list = [\"WITH grades AS (\", sub_sql, \")\",\n \"UPDATE students_student\",\n \"SET \", db_field, \" = grades.record_count\",\n \"FROM grades\",\n \"WHERE grades.student_id = students_student.id\"\n ]\n\n if student_pk:\n sql_keys['stud_pk'] = student_pk\n sql_list.append(\"AND students_student.id = %(stud_pk)s::INT\")\n\n sql_list.append(\"RETURNING students_student.id;\")\n\n sql = ' '.join(sql_list)\n\n if logging_on:\n logger.debug(' sql_keys: ' + str(sql_keys))\n logger.debug(' sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n\n if logging_on:\n logger.debug(' cursor.execute: ')\n for cq in connection.queries:\n logger.debug('query: ' + str(cq.get('sql')))\n\n rows = cursor.fetchall()\n for row in rows:\n # row is tuple: (3957, 1)\n logger.debug(' row: ' + str(row))\n\n sql_list = [\"SELECT exemption_count, reex_count, reex03_count, thumbrule_count, sr_count, id, lastname, firstname\",\n \"FROM students_student\",\n \"WHERE exemption_count > 0 OR reex_count > 0 OR reex03_count > 0 OR thumbrule_count > 0 OR sr_count > 0\",\n ]\n sql = ' '.join(sql_list)\n cursor.execute(sql)\n rows = cursor.fetchall()\n for row in rows:\n logger.debug(' row: ' + str(row))\n\n #except Exception as e:\n # logger.error(getattr(e, 'message', str(e)))\n# --- end of update_reexcount_etc_in_student\n\n\n@method_decorator([login_required], name='dispatch')\nclass StudentsubjectnoteUploadView(View): # PR2021-01-16\n\n def post(self, request):\n logging_on = s.LOGGING_ON\n\n files = request.FILES\n file = files.get('file')\n if logging_on:\n logger.debug(' ============= StudentsubjectnoteUploadView ============= ')\n logger.debug('files: ' + str(files) + ' ' + str(type(files)))\n logger.debug('file: ' + str(file) + ' ' + str(type(file)))\n\n # function creates, deletes and updates studentsubject records of current student PR2020-11-21\n update_wrap = {}\n\n #\n # only users with role > student and perm_edit can change student data\n # only school that is requsr_school can be changed\n # current schoolbase can be different from request.user.schoolbase (when role is insp, admin, system)\n # only if country/examyear/school/student not locked, examyear is published and school is activated\n has_permit = False\n if request.user and request.user.country and request.user.schoolbase:\n has_permit = True # (request.user.role > c.ROLE_002_STUDENT and request.user.is_group_edit)\n if has_permit:\n\n# - reset language\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n activate(user_lang)\n\n# - get upload_dict from request.POST\n upload_json = request.POST.get('upload', None)\n if upload_json:\n upload_dict = json.loads(upload_json)\n if logging_on:\n logger.debug('upload_dict: ' + str(upload_dict))\n\n # - get selected examyear, school and department from usersettings\n # was: sel_examyear, sel_school, sel_department, is_locked, \\\n #examyear_published, school_activated, is_requsr_school =\n sel_examyear, sel_school, sel_department, sel_level, may_edit, msg_list = \\\n acc_view.get_selected_ey_school_dep_lvl_from_usersetting(request)\n\n# - get current grade - when mode is 'create': studsubj is None. It will be created at \"elif mode == 'create'\"\n examperiod = upload_dict.get('examperiod')\n studsubj_pk = upload_dict.get('studsubj_pk')\n note = upload_dict.get('note')\n\n file_type = upload_dict.get('file_type')\n file_name = upload_dict.get('file_name')\n file_size = upload_dict.get('file_size')\n\n studsubj = stud_mod.Studentsubject.objects.get_or_none(\n id=studsubj_pk,\n student__school=sel_school,\n student__department=sel_department\n )\n\n if logging_on:\n logger.debug('studsubj: ' + str(studsubj))\n logger.debug('note: ' + str(note))\n logger.debug('file_type: ' + str(file_type))\n logger.debug('file_name: ' + str(file_name))\n logger.debug('file_size: ' + str(file_size))\n\n# - Create new studsubjnote if is_create:\n # studsubjnote is also called when studsubjnote is_created, save_to_log is called in update_studsubjnote\n if studsubj and (note or file):\n note_status = upload_dict.get('note_status')\n\n # if is_internal_note: get schoolbase of request_user, to be put in intern_schoolbase\n is_internal_note = upload_dict.get('is_internal_note', False)\n intern_schoolbase = None\n if is_internal_note:\n intern_schoolbase = request.user.schoolbase\n if logging_on:\n logger.debug('is_internal_note: ' + str(is_internal_note))\n logger.debug('intern_schoolbase: ' + str(intern_schoolbase))\n\n studsubjnote = stud_mod.Studentsubjectnote(\n studentsubject=studsubj,\n note=note,\n note_status=note_status,\n intern_schoolbase=intern_schoolbase\n )\n if logging_on:\n logger.debug('studsubjnote.note: ' + str(studsubjnote.note))\n studsubjnote.save(request=request)\n\n if logging_on:\n logger.debug('studsubjnote.pk: ' + str(studsubjnote.pk))\n logger.debug('file_type: ' + str(file_type))\n logger.debug('file_name: ' + str(file_name))\n logger.debug('file: ' + str(file))\n\n # attachments are stored in spaces awpmedia/awpmedia/media/private\n\n# +++ save attachment\n if studsubjnote and file:\n# --- create file_path\n # PR2021-08-07 file_dir = 'country/examyear/attachments/'\n # this one gives path:awpmedia/awpmedia/media/cur/2022/published\n requsr_school = sch_mod.School.objects.get_or_none(\n base=request.user.schoolbase,\n examyear=sel_examyear\n )\n requsr_schoolcode = requsr_school.base.code if requsr_school.base.code else '---'\n country_abbrev = sel_examyear.country.abbrev.lower()\n examyear_str = str(sel_examyear.code)\n file_dir = '/'.join((country_abbrev, examyear_str, requsr_schoolcode, 'attachment'))\n file_path = '/'.join((file_dir, file_name))\n\n if logging_on:\n logger.debug('file_dir: ' + str(file_dir))\n logger.debug('file_name: ' + str(file_name))\n logger.debug('filepath: ' + str(file_path))\n\n instance = stud_mod.Noteattachment(\n studentsubjectnote=studsubjnote,\n contenttype=file_type,\n filename=file_name,\n )\n instance.save()\n instance.file.save(file_path, file)\n\n if logging_on:\n logger.debug('instance: ' + str(instance))\n logger.debug('instance.pk: ' + str(instance.pk))\n\n#======================\n\n grade_note_icon_rows = grd_view.create_grade_note_icon_rows(\n sel_examyear_pk=sel_examyear.pk,\n sel_schoolbase_pk=sel_school.base_id,\n sel_depbase_pk=sel_department.base_id,\n sel_examperiod=examperiod,\n studsubj_pk=studsubj.pk,\n request=request)\n if grade_note_icon_rows:\n update_wrap['grade_note_icon_rows'] = grade_note_icon_rows\n\n# 9. return update_wrap\n return HttpResponse(json.dumps(update_wrap, cls=LazyEncoder))\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndef set_student_instance_tobedeleted(student_instance, request):\n # --- delete student # PR2021-07-18 PR2022-02-16 PR2022-08-05 PR2022-12-27 PR2023-01-16\n # dont delete student when student has submitted subjects, but set tobedeleted\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- set_student_instance_tobedeleted ----- ')\n logger.debug(' student_instance: ' + str(student_instance))\n\n deleted_row = None\n msg_html = None\n this_txt = _(\"Candidate '%(tbl)s' \") % {'tbl': student_instance.fullname}\n\n# - check if student has submitted subjects PR2021-08-21 PR2022-05-15\n has_publ_studsubj = stud_mod.Studentsubject.objects.filter(\n student=student_instance,\n subj_published_id__isnull=False\n ).exists()\n if logging_on:\n logger.debug(' has_publ_studsubj: ' + str(has_publ_studsubj))\n\n if has_publ_studsubj:\n\n# - if student has submitted subjects: mark candidate as 'tobedeleted'\n setattr(student_instance, 'tobedeleted', True)\n student_instance.save(request=request)\n\n # remove approval and subj_published from studentsubject, add published info to prev_published fields\n updated_studsubj_pk_list, err_html = set_studsubjects_tobedeleted(request, student_instance.pk)\n if err_html:\n msg_html = err_html\n else:\n # mark candidate as 'tobedeleted'\n setattr(student_instance, 'tobedeleted', True)\n student_instance.save(request=request)\n awpr_log.savetolog_student(student_instance.pk, 'u', request, ['tobedeleted'])\n\n else:\n deleted_row = {'id': student_instance.pk,\n 'mapid': 'student_' + str(student_instance.pk),\n 'deleted': True}\n if logging_on:\n logger.debug(' deleted_row: ' + str(deleted_row))\n\n# - if student doesn't have submitted subjects: mark candidate as 'deleted'\n # also delete studsubj rows (Not necessary, studsub and grades of deletedsudents are filtered out\n err_html = None\n try:\n setattr(student_instance, 'deleted', True)\n setattr(student_instance, 'tobedeleted', False)\n student_instance.save(request=request)\n\n student_pk = deleted_row.get('id')\n awpr_log.savetolog_student(student_pk, 'u', request, ['deleted', 'tobedeleted'])\n\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n deleted_row = None\n\n caption = _('Candidate')\n full_name = stud_fnc.get_full_name(student_instance.lastname, student_instance.firstname, student_instance.prefix)\n err_html = ''.join((str(_('An error occurred')), ': ', '
', str(e), '
',\n str(_(\"%(cpt)s '%(val)s' could not be deleted.\") % {'cpt': caption, 'val': full_name})))\n\n if err_html:\n msg_html = err_html\n if logging_on:\n logger.debug(' deleted_row: ' + str(deleted_row))\n logger.debug(' err_html: ' + str(err_html))\n\n if logging_on:\n logger.debug(' deleted_row: ' + str(deleted_row))\n logger.debug(' msg_html: ' + str(msg_html))\n\n return deleted_row, msg_html\n# - end of set_student_instance_tobedeleted\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndef restore_student_instance(student_instance, request):\n # --- restore student and studsubjects # PR2022-12-28\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- restore_student_instance ----- ')\n logger.debug(' student_instance: ' + str(student_instance))\n\n restored_student_success = False\n restored_studsubj_pk_list = []\n msg_html = None\n\n this_txt = _(\"Candidate '%(tbl)s' \") % {'tbl': student_instance.fullname}\n\n if student_instance.tobedeleted or student_instance.deleted:\n\n # resore approval and subj_published from studentsubject, from prev_published fields\n restored_studsubj_pk_list, msg_html = restore_tobedeleted_studsubjects(\n request=request,\n student_pk=student_instance.pk,\n include_deleted=student_instance.deleted,\n )\n\n if not msg_html:\n # remove 'tobedeleted' from candidate\n try:\n setattr(student_instance, 'tobedeleted', False)\n setattr(student_instance, 'deleted', False)\n student_instance.save(request=request)\n restored_student_success = True\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n msg_html = ''.join((str(_('An error occurred')), ': ', '
', str(e), '
',\n str(_(\"%(cpt)s could not be restored.\") % {'cpt':this_txt})))\n\n if logging_on:\n logger.debug(' restored_student_success: ' + str(restored_student_success))\n logger.debug(' restored_studsubj_pk_list: ' + str(restored_studsubj_pk_list))\n logger.debug(' msg_html: ' + str(msg_html))\n\n return restored_student_success, restored_studsubj_pk_list , msg_html\n# - end of restore_student_instance\n\n\ndef create_or_get_studentbase(country, upload_dict, messages, error_list, skip_save):\n # --- create studentbase PR2021-07-18\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- create_or_get_studentbase ----- ')\n logger.debug('upload_dict: ' + str(upload_dict))\n\n studentbase = None\n\n# - get value of 'studentbase_pk'\n studentbase_pk = upload_dict.get('studentbase_pk')\n\n try:\n\n# - lookup existing studentbase record\n if studentbase_pk:\n studentbase = stud_mod.Studentbase.objects.get_or_none(pk=studentbase_pk)\n\n# - create studentbase record if it does not exist yet\n if studentbase is None:\n studentbase = stud_mod.Studentbase(\n country=country\n )\n\n# - save studentbase record, only when not is_test\n if not skip_save:\n studentbase.save()\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n last_name = upload_dict.get('lastname', '')\n first_name = upload_dict.get('firstname', '')\n name = ' '.join((first_name, last_name))\n # messages is list of dicts with format: {'field': fldName, header': header_txt, 'class': 'border_bg_invalid', 'msg_html': msg_html}\n err_01 = str(_('An error occurred:'))\n err_02 = str(e)\n err_03 = str(_(\"%(cpt)s '%(val)s' could not be added.\") % {'cpt': str(_('Candidate')), 'val': name})\n error_list.extend((err_01, err_02, err_03))\n\n msg_html = '
'.join((err_01, '' + err_02 + '', err_03))\n messages.append({'class': \"alert-danger\", 'msg_html': msg_html})\n\n if logging_on:\n logger.debug('messages: ' + str(messages))\n\n return studentbase\n# - end of create_or_get_studentbase\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndef create_student_instance(examyear, school, department, idnumber_nodots,\n lastname_stripped, firstname_stripped, prefix_stripped, full_name,\n lvlbase_pk, sctbase_pk, request, found_is_error, skip_save, is_import=False):\n # --- create student # PR2019-07-30 PR2020-10-11 PR2020-12-14 PR2021-06-15 PR2022-08-20\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' +++++++++++++++++ create_student_instance +++++++++++++++++ ')\n logger.debug(' school: ' + str(school))\n logger.debug(' department: ' + str(department))\n\n student = None\n error_list = []\n# - create but don't save studentbase\n # save studentbase at the end, to prevent studentbases without student\n studentbase = stud_mod.Studentbase()\n\n if studentbase and school:\n has_error = False\n error_list = []\n\n msg_err = av.validate_notblank_maxlength(lastname_stripped, c.MAX_LENGTH_FIRSTLASTNAME, _('The last name'))\n if logging_on:\n logger.debug(' validate_lastname_stripped msg_err: ' + str(msg_err))\n if msg_err:\n has_error = True\n error_list.append(str(msg_err))\n\n msg_err = av.validate_notblank_maxlength(firstname_stripped, c.MAX_LENGTH_FIRSTLASTNAME, _('The first name'))\n if logging_on:\n logger.debug(' validate_firstname_stripped msg_err: ' + str(msg_err))\n if msg_err:\n has_error = True\n error_list.append(str(msg_err))\n\n# - validate level sector\n msg_lst = av.validate_level_sector_in_student(examyear, school, department, lvlbase_pk, sctbase_pk)\n if logging_on:\n logger.debug(' validate_firstname_stripped msg_lst: ' + str(msg_lst))\n if msg_lst:\n has_error = True\n error_list.extend(msg_lst)\n\n if not has_error:\n# - validate if student already exists\n # when importing, this function is already called in the parent function. Let it stay.\n # when importing: dont give error when found, but return found student error_when_found\n # either student, not_found or has_error is trueish\n student, not_found, err_list = \\\n stud_val.lookup_student_by_idnumber_nodots(\n school=school,\n department=department,\n idnumber_nodots=idnumber_nodots,\n upload_fullname=full_name,\n found_is_error=found_is_error\n )\n if err_list:\n has_error = True\n error_list.append(err_list)\n if logging_on:\n logger.debug(' lookup_student_by_idnumber_nodots err_list: ' + str(err_list))\n logger.debug(' student: ' + str(student))\n logger.debug(' not_found: ' + str(not_found))\n logger.debug(' has_error: ' + str(has_error))\n\n if not has_error:\n\n# - make iseveningstudent / islexstudent true when iseveningschool / islexschool, not when also isdayschool\n # PR 2021-09-08 debug tel Lionel Mongen CAL: validation still chekcs for required subjects\n # reason: CAL iseveningschool, but styudents were not set iseveningstudent\n # also solved by checking validation on iseveningstudent only when school is both dayschool and evveningschool,\n # set is_evening_student = True or is_lex_student = True, only when school is not a dayschool (in that case you must select field in mosstudent)\n is_evening_student, is_lex_student = False, False\n if not school.isdayschool:\n is_evening_student = school.iseveningschool\n is_lex_student= school.islexschool\n\n# - save studentbase\n # if studentbase is created but not yet saved: studentbase = True and studentbase.pk = None\n # save studentbase here, to prevent studentbases without student\n if not skip_save and studentbase.pk is None:\n studentbase.save()\n\n if logging_on:\n logger.debug(' studentbase: ' + str(studentbase))\n# - create and save student\n try:\n student = stud_mod.Student(\n base=studentbase,\n school=school,\n department=department,\n lastname=lastname_stripped,\n firstname=firstname_stripped,\n prefix=prefix_stripped,\n idnumber=idnumber_nodots,\n iseveningstudent=is_evening_student,\n islexstudent=is_lex_student\n )\n if logging_on:\n logger.debug(' student: ' + str(student))\n if not skip_save:\n student.save(request=request)\n mode = 'i' if is_import else 'c'\n awpr_log.savetolog_student(student.pk, mode, request, [])\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n error_list.append(''.join((\n str(_('An error occurred')), ':
', ' ', str(e), '
',\n str(_(\"%(cpt)s '%(val)s' could not be added.\") % {'cpt': _('Candidate'), 'val': full_name})\n )))\n\n if logging_on:\n student_pk = student.pk if student else 'None'\n logger.debug(' ---student: ' + str(student))\n logger.debug(' student_pk: ' + str(student_pk))\n logger.debug(' error_list: ' + str(error_list))\n\n return student, error_list\n# - end of create_student\n\n\n#######################################################\ndef update_student_instance(instance, sel_examyear, sel_school, sel_department, upload_dict,\n idnumber_list, examnumber_list,\n msg_list, error_list, err_fields, log_list, request, skip_save, is_import=False):\n # --- update existing and new instance PR2019-06-06 PR2021-07-19 PR2022-04-11 PR2022-06-04 PR2022-09-01 PR2023-08-13\n # log_list is only used when uploading students, is None otherwise\n instance_pk = instance.pk if instance else None\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ------- update_student_instance -------')\n logger.debug(' upload_dict: ' + str(upload_dict))\n logger.debug(' instance: ' + str(instance))\n\n def get_log_txt(caption, new_value, saved_value):\n blank_str = str(_('blank'))\n log_txt = ' = '.join(((caption + c.STRING_SPACE_20)[:20],\n (str(new_value) if new_value else blank_str)[:20]\n ))\n if logging_on:\n logger.debug(' ------- get_log_txt -------')\n logger.debug(' caption: ' + str(caption))\n logger.debug(' new_value: ' + str(new_value))\n logger.debug(' saved_value: ' + str(saved_value))\n logger.debug(' blank_str: ' + blank_str)\n\n if saved_value:\n saved_str = str(saved_value) if saved_value else blank_str\n log_txt += ''.join((' (', str(_('was')), ': ', saved_str, ')'))\n return log_txt\n\n# ----- get user_lang\n user_lang = request.user.lang if request.user.lang else c.LANG_DEFAULT\n\n changes_are_saved = False\n save_error = False\n field_error = False\n\n # TODO add error fieldname to err_fields, instead of field_error\n\n if instance:\n save_changes = False\n update_scheme = False\n recalc_regnumber = False\n remove_exemptions = False\n recalc_passed_failed = False\n recalc_subj_composition = False\n\n updated_fields = []\n\n for field, new_value in upload_dict.items():\n try:\n # - save changes in fields 'lastname', 'firstname'\n if field in ['lastname', 'firstname']:\n saved_value = getattr(instance, field)\n\n # PR2022-06-29 debug: when value is None it converts it to string 'None'\n if new_value is not None:\n if not isinstance(new_value, str):\n new_value = str(new_value)\n\n if new_value != saved_value:\n if logging_on and False:\n logger.debug('lastname firstname saved_value: ' + str(saved_value) + ' ' + str(type(saved_value)))\n logger.debug('lastname firstname new_value: ' + str(new_value)+ ' ' + str(type(new_value)))\n\n name_first = None\n name_last = None\n if field == 'firstname':\n name_first = new_value\n name_last = getattr(instance, 'lastname')\n elif field == 'lastname':\n name_first = getattr(instance, 'firstname')\n name_last = new_value\n # TODO check if student namefirst / namelast combination already exists\n \"\"\"\n field_error = validate_namelast_namefirst(\n namelast=name_last,\n namefirst=name_first,\n company=request.user.company,\n update_field=field,\n msg_dict=msg_dict,\n this_pk=instance.pk)\n \"\"\"\n has_error = False\n if not has_error:\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n else:\n field_error = True\n\n elif field == 'gender':\n new_gender = None\n has_error = False\n\n # PR2022-06-29 debug: when value is None it converts it to string 'None'\n if new_value is not None:\n if not isinstance(new_value, str):\n new_value = str(new_value)\n\n if new_value:\n new_gender = new_value[:1].upper()\n if new_gender == 'F':\n new_gender = 'V'\n if new_gender not in ['M', 'V']:\n has_error = True\n\n if has_error:\n field_error = True\n err_txt = _(\"%(cpt)s '%(val)s' is not allowed.\") \\\n % {'cpt': str(_('Gender')), 'val': new_value}\n error_list.append(err_txt)\n err_fields.append(field)\n msg_list.append({'class': \"border_bg_warning\", 'msg_html': err_txt})\n else:\n saved_value = getattr(instance, field)\n\n if new_gender != saved_value:\n if logging_on and False:\n logger.debug('gender saved_value: ' + str(saved_value) + ' ' + str(type(saved_value)))\n logger.debug('gender new_gender: ' + str(new_gender) + ' ' + str(type(new_gender)))\n\n setattr(instance, field, new_gender)\n save_changes = True\n recalc_regnumber = True\n updated_fields.append(field)\n\n elif field == 'idnumber':\n caption = _('ID-number')\n err_txt = None\n class_txt = None\n\n # PR2022-06-29 debug: when value is None it converts it to string 'None'\n if new_value is not None:\n if not isinstance(new_value, str):\n new_value = str(new_value)\n # PR2022-09-01 debug: blank ID number was not giving error, because of 'if new_value'\n # was:\n # if new_value:\n\n # - remove dots, check if idnumber is correct\n idnumber_nodots_stripped_lower, msg_err_list, birthdate_dteobj = stud_val.get_idnumber_nodots_stripped_lower(new_value)\n if msg_err_list:\n err_txt = ' '.join(msg_err_list)\n class_txt = c.HTMLCLASS_border_bg_invalid\n\n if err_txt is None:\n # check idnumber_already_exists\n idnumber_already_exists = False\n idnumber_already_exists_namelist = []\n\n # when updating single student, idnumber_list is not filled yet. in that case: get idnumber_list\n if not idnumber_list:\n stud_val.get_idnumberlist_from_database(instance.school, idnumber_list)\n\n if logging_on :\n logger.debug(' idnumber_list: ' + str(idnumber_list))\n\n if idnumber_list:\n for row in idnumber_list:\n # row is a tuple with (id, idnumber, lastname, firstname, prefix), id=0 when instance not saved yet\n # (8518, '2000120411', 'Suarez Mendoza', 'Mayra Alejandra', '')\n # skip idnumber of this student\n if instance_pk is None or row[0] != instance_pk:\n if row[1] and row[1] == idnumber_nodots_stripped_lower:\n idnumber_already_exists = True\n idnumber_already_exists_namelist.append(\n stud_fnc.get_firstname_prefix_lastname(row[2], row[3], row[4])\n )\n\n if idnumber_already_exists:\n class_txt = \"border_bg_invalid\"\n err_txt = '
'.join((\n str(_(\"%(cpt)s '%(val)s' already exists.\") % {'cpt': str(caption), 'val': idnumber_nodots_stripped_lower}),\n str(_(\"%(cand)s has this ID number.\") % {'cand': ', '.join(idnumber_already_exists_namelist)})\n ))\n\n else:\n # add new_value to idnumber_list if it doesn't exist yet\n\n # PR2022-08-22 debug Guribaldi Gouv Lauffer: string index out of range\n # cause: idnumber_list item is [studenk_pk_int, idnumber_str]\n # add student_pk as first value, add 0 when new student\n # was: idnumber_list.append(new_value)\n\n if logging_on:\n logger.debug(' instance_pk: ' + str(instance_pk))\n if instance_pk is None:\n idnumber_list.append((0, idnumber_nodots_stripped_lower))\n\n if err_txt:\n field_error = True\n error_list.append(err_txt)\n err_fields.append(field)\n msg_list.append({'class': class_txt, 'msg_html': err_txt})\n else:\n saved_value = getattr(instance, field)\n if new_value != saved_value:\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n\n elif field == 'examnumber':\n caption = _('Exam number')\n err_txt = None\n class_txt = None\n\n # PR2022-06-29 debug: when value is None it converts it to string 'None'\n if new_value is not None:\n if not isinstance(new_value, str):\n new_value = str(new_value)\n\n if new_value:\n # check max length\n new_value = new_value.strip()\n if len(new_value) > c.MAX_LENGTH_EXAMNUMBER:\n err_txt = str(_(\"%(cpt)s '%(val)s' is too long.
Maximum %(max)s characters.\") \\\n % {'cpt': caption, 'val': new_value, 'max': c.MAX_LENGTH_EXAMNUMBER})\n class_txt = \"border_bg_invalid\"\n\n if err_txt is None:\n\n # check if examnumber_already_exists\n examnumber_already_exists = False\n studentname_list = []\n\n # PR2022-09-01 Angela Richardson Maris Stella: cannot upload students\n # error: new_value.lower(): 'NoneType' object has no attribute 'lower'\n # solved by adding if new_value. new_value is converted sto string above\n\n if new_value:\n # when updating single student, idnumber_list is not filled yet. in that case: get idnumber_list\n if not examnumber_list:\n stud_val.get_examnumberlist_from_database(instance.school, instance.department, examnumber_list)\n\n if examnumber_list:\n # examnumber_list: list of tuples (student_pk, LOWER(examnumber)) [(4445, '201'), (4545, '202'), (4546, '203'), (4547, '204'), (5888, '205'), (4549, '206'), (6016, '207')]\n # examnumber_list: list of dictionaties: {'student_id': -9, 'examnumber': '#$%#@', 'lastname': '-', 'firstname': '-', 'prefix': None}\n\n for row in examnumber_list:\n # skip exam number of this student\n\n student_pk = row.get('student_id')\n if instance_pk is None or student_pk != instance_pk:\n examnumber_lower = row.get('examnumber')\n if examnumber_lower and examnumber_lower == new_value.lower():\n examnumber_already_exists = True\n studentname_list.append(stud_fnc.get_full_name(row.get('lastname'), row.get('firstname'), row.get('prefix')))\n\n if examnumber_already_exists:\n class_txt = \"border_bg_invalid\"\n err_txt = gettext(\"%(cpt)s '%(val)s' already exists at\") % {'cpt': str(caption), 'val': new_value}\n err_txt += ':
    '\n for stud in studentname_list:\n err_txt += ''.join(('
  • ', stud, '
  • '))\n err_txt += '
'\n else:\n # add new_value to examnumber_list if it doesn't exist yet\n\n # PR2022-08-22 debug Guribaldi Gouv Lauffer: string index out of range\n # cause: examnumber_list item is [studenk_pk_int, examnumber_str]\n # add student_pk as first value, add 0 when new student\n # was: examnumber_list.append(new_value)\n if instance_pk is None:\n examnumber_list.append((0, new_value))\n\n if logging_on and False:\n logger.debug(' err_txt: ' + str(err_txt))\n logger.debug(' --------------')\n\n if err_txt:\n field_error = True\n error_list.append(err_txt)\n err_fields.append(field)\n msg_list.append({'class': class_txt, 'msg_html': err_txt})\n else:\n saved_value = getattr(instance, field)\n\n if new_value != saved_value:\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n # recalc_regnumber is only used when examyear < 2023\n recalc_regnumber = True\n\n elif field in ('diplomanumber', 'gradelistnumber'):\n # field diplomanumber gradelistnumber are only used when examyear < 2023\n caption = str(_('Diploma number')) if field == 'diplomanumber' else str(_('Gradelist number'))\n err_txt = None\n class_txt = None\n\n # PR2022-06-29 debug: when value is None it converts it to string 'None'\n if new_value is not None:\n if not isinstance(new_value, str):\n new_value = str(new_value)\n\n if new_value:\n # - validate length of new_value\n err_txt = stud_val.validate_length(caption, new_value, c.MAX_LENGTH_EXAMNUMBER, True) # True = blank_allowed\n #if err_txt is None:\n # PR2022-07-04 debug Angela Richardson Maris Stella: cannot enter number, already exists in other level\n # skip check for double numbers\n # check if new_value already exists in value_list, but skip idnumber of this instance\n #value_list = diplomanumber_list if field == 'diplomanumber' else gradelistnumber_list\n\n # when updating single student, value_list is not filled yet. in that case: get diplomanumber_list\n #if not value_list:\n # value_list = stud_val.get_diplomanumberlist_gradelistnumberlist_from_database(field, sel_school)\n\n # value_list contains tuples with (id, value), id is needed to skip value of this student\n #if value_list:\n # double_student_id_list = []\n # for row in value_list:\n # # row is a tuple with (id, value)\n # if row[1] == new_value:\n # # unsaved instance has id = None\n # lookup_id = row[0]\n # skip_this_student = False\n # saved_id = getattr(instance, 'id')\n # if saved_id:\n # if saved_id and lookup_id == saved_id:\n # skip_this_student = True\n # if not skip_this_student:\n # double_student_id_list.append(lookup_id)\n #\n # if double_student_id_list:\n # err_txt = _(\"%(cpt)s '%(val)s' already exists at:\") \\\n # % {'cpt': str(caption), 'val': new_value}\n # class_txt = \"border_bg_invalid\"\n #\n # for student_id in double_student_id_list:\n # stud = stud_mod.Student.objects.get_or_none(pk=student_id)\n # if stud:\n # full_name = stud_fnc.get_full_name(stud.lastname, stud.firstname, stud.prefix)\n # err_txt += '
- ' + full_name\n\n #if err_txt is None:\n # # add new_value to value_list if it doesn't exist yet\n # value_list.append(new_value)\n\n # = put err_txt in error_list\n if err_txt:\n field_error = True\n error_list.append(err_txt)\n err_fields.append(field)\n msg_list.append({'class': class_txt, 'msg_html': err_txt})\n else:\n saved_value = getattr(instance, field)\n\n if new_value != saved_value:\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n if log_list is not None:\n log_list.append(get_log_txt(caption, new_value, saved_value))\n\n # 2. save changes in birthdate field\n elif field == 'birthdate':\n # new_value has format of date-iso, Excel ordinal format is already converted\n saved_dateobj = getattr(instance, field)\n\n new_dateobj = af.get_date_from_ISO(new_value)\n\n if new_dateobj != saved_dateobj:\n if logging_on and False:\n logger.debug('birthdate saved: ' + str(saved_dateobj) + ' ' + str(type(saved_dateobj)))\n logger.debug('birthdate new : ' + str(new_dateobj) + ' ' + str(type(new_dateobj)))\n\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n\n # 2. save changes in text fields\n elif field in ('prefix', 'birthcountry', 'birthcity', 'classname'):\n saved_value = getattr(instance, field)\n\n # PR2022-06-29 debug: when value is None it converts it to string 'None'\n if new_value is not None:\n if not isinstance(new_value, str):\n new_value = str(new_value)\n\n if logging_on and False:\n logger.debug('field: ' + field + ' saved_value: ' + str(saved_value) + ' ' + str(type(saved_value)))\n logger.debug('field: ' + field + ' new_value: ' + str(new_value) + ' ' + str(type(new_value)))\n\n if new_value != saved_value:\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n if logging_on and False:\n logger.debug('save_changes field: ' + field + ' new_value: ' + str(new_value))\n\n # 3. save changes in department, level or sector\n # department cannot be changed\n # change 'profiel' into 'sector\n elif field in ('level', 'sector', 'profiel'):\n if field == 'profiel':\n field = 'sector'\n\n #TODO PR2022-07-07 error on CAL and Omega: sector disappears when changing student, then subjects get deleted without deleting grade info\n if logging_on and False:\n logger.debug(' >> field: ' + str(field) + ' ' + str(type(field)))\n logger.debug(' new_value: ' + str(new_value) + ' ' + str(type(new_value)))\n logger.debug(' old_level: ' + str(getattr(instance, 'level')))\n logger.debug(' old_sector: ' + str(getattr(instance, 'sector')))\n logger.debug(' old_scheme: ' + str(getattr(instance, 'scheme')))\n logger.debug(' old_department: ' + str(getattr(instance, 'department')))\n\n new_lvl_or_sct = None\n school = getattr(instance, 'school')\n if logging_on and False:\n logger.debug(' school: ' + str(school) + ' ' + str(type(school)))\n if school:\n examyear = getattr(school, 'examyear')\n if logging_on and False:\n logger.debug(' examyear: ' + str(examyear) + ' ' + str(type(examyear)))\n if examyear:\n if field == 'level':\n new_lvl_or_sct = subj_mod.Level.objects.get_or_none(\n base_id=new_value,\n examyear=examyear\n )\n elif field == 'sector':\n new_lvl_or_sct = subj_mod.Sector.objects.get_or_none(\n base_id=new_value,\n examyear=examyear\n )\n\n saved_lvl_or_sct = getattr(instance, field)\n if logging_on and False:\n logger.debug(' new_lvl_or_sct: ' + str(new_lvl_or_sct) + ' ' + str(type(new_lvl_or_sct)))\n logger.debug(' saved_lvl_or_sct: ' + str(saved_lvl_or_sct) + ' ' + str(type(saved_lvl_or_sct)))\n\n # new_value is levelbase_pk or sectorbase_pk\n if new_lvl_or_sct != saved_lvl_or_sct:\n if logging_on and False:\n logger.debug('saved ' + str(field) + ': ' + str(saved_lvl_or_sct) + ' ' + str(type(saved_lvl_or_sct)))\n logger.debug('new ' + str(field) + ': ' + str(new_lvl_or_sct) + ' ' + str(type(new_lvl_or_sct)))\n\n setattr(instance, field, new_lvl_or_sct)\n save_changes = True\n update_scheme = True\n recalc_subj_composition = True\n updated_fields.append(field + '_id')\n\n if field == 'level':\n recalc_regnumber = True\n\n # - save changes in field 'bis_exam'\n elif field == 'bis_exam':\n saved_value = getattr(instance, field)\n if new_value is None:\n new_value = False\n # PR2021-08-29 debug: when importing value can be 'x'. Convert to True when not a boolean\n elif not isinstance(new_value, bool):\n new_value = True\n\n if new_value != saved_value:\n # check if student has published grades when removing bis_exam\n # not when it is evening / lex student\n has_published_exemptions = False\n if not new_value:\n is_evelex = False\n for evelex_field in ('iseveningstudent', 'islexstudent'):\n if upload_dict.get(evelex_field):\n is_evelex = True\n elif getattr(instance, evelex_field):\n is_evelex = True\n\n if not is_evelex:\n has_errorNIU, has_published = stud_val.validate_submitted_locked_grades(\n student_pk=instance.pk,\n examperiod=c.EXAMPERIOD_EXEMPTION\n )\n if has_published:\n has_published_exemptions = True\n field_error = True\n err_txt1 = str(_('This candidate has submitted exemptions.'))\n err_txt2 = str(_('The bis-exam cannot be removed.'))\n error_list.append(' '.join((err_txt1, err_txt2)))\n err_fields.append(field)\n msg_list.append({'class': \"border_bg_warning\", 'msg_html': '
'.join((err_txt1, err_txt2))})\n else:\n remove_exemptions = True\n\n if not has_published_exemptions:\n setattr(instance, field, new_value)\n save_changes = True\n updated_fields.append(field)\n\n elif field == 'withdrawn': # PR2022-06-04\n if not new_value:\n new_value = False\n saved_value = getattr(instance, field) or False\n if logging_on and False:\n logger.debug('new_value: ' + str(new_value))\n logger.debug('saved_value: ' + str(saved_value))\n if new_value != saved_value:\n setattr(instance, field, new_value)\n save_changes = True\n recalc_passed_failed = True\n updated_fields.append(field)\n\n # also set result\n result_index = c.RESULT_WITHDRAWN if new_value else c.RESULT_NORESULT\n result_status = str(_('Withdrawn')) if new_value else str(_('No result'))\n setattr(instance, 'result', result_index)\n setattr(instance, 'result_status', result_status)\n setattr(instance, 'result_info', None)\n\n updated_fields.extend(['result', 'result_status', 'result_info'])\n\n elif field == 'gl_status': # PR2023-06-10\n if not new_value:\n new_value = 0\n saved_value = getattr(instance, field) or False\n if logging_on:\n logger.debug('new_value: ' + str(new_value))\n logger.debug('saved_value: ' + str(saved_value))\n\n if new_value != saved_value:\n setattr(instance, field, new_value)\n save_changes = True\n\n setattr(instance, 'gl_auth1by', request.user)\n setattr(instance, 'gl_modifiedat', timezone.now())\n\n updated_fields.extend(['gl_status', 'gl_auth1by', 'gl_modifiedat'])\n\n # - save changes in other fields\n elif field in ('iseveningstudent', 'islexstudent', 'partial_exam', 'extrafacilities'):\n saved_value = getattr(instance, field)\n if new_value is None:\n new_value = False\n # PR2021-08-29 debug: when importing value can be 'x'. Convert to True when not a boolean\n elif not isinstance(new_value, bool):\n new_value = True\n\n if new_value != saved_value:\n has_published_exemptions = False\n # check if student has published grades when removing iseveningstudent', 'islexstudent\n # not when it is bis_exam\n if not new_value and field in ('iseveningstudent', 'islexstudent'):\n is_bisexam = False\n if upload_dict.get('bis_exam'):\n is_bisexam = True\n elif getattr(instance, 'bis_exam'):\n is_bisexam = True\n\n if not is_bisexam:\n has_errorNIU, has_published = stud_val.validate_submitted_locked_grades(\n student_pk=instance.pk,\n examperiod=c.EXAMPERIOD_EXEMPTION\n )\n if has_published:\n has_published_exemptions = True\n field_error = True\n err_txt1 = str(_('This candidate has submitted exemptions.'))\n caption = 'landsexamen candidate' if field == 'islexstudent' else 'evening candidate'\n err_txt2 = str(_(\"The label '%(cpt)s' cannot be removed.\") % {'cpt': caption})\n error_list.append(' '.join((err_txt1, err_txt2)))\n err_fields.append(field)\n msg_list.append({'class': \"border_bg_warning\", 'msg_html': '
'.join((err_txt1, err_txt2))})\n else:\n remove_exemptions = True\n\n if not has_published_exemptions:\n setattr(instance, field, new_value)\n save_changes = True\n\n updated_fields.append(field)\n\n if field in ('iseveningstudent', 'islexstudent', 'partial_exam'):\n recalc_subj_composition = True\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n logger.error('field: ' + str(field) + ' new_value: ' + str(new_value) + ' ' + str(type(new_value)))\n\n# --- end of for loop ---\n\n school = getattr(instance, 'school')\n department = getattr(instance, 'department')\n\n# - update scheme if level or sector have changed\n if update_scheme:\n level = getattr(instance, 'level')\n sector = getattr(instance, 'sector')\n scheme = subj_mod.Scheme.objects.get_or_none(\n department=department,\n level=level,\n sector=sector)\n setattr(instance, 'scheme', scheme)\n updated_fields.append('scheme_id')\n\n if scheme is None:\n msg_arr = []\n if department.level_req:\n if level is None:\n msg_arr.append(str(_(\"The learning path is not entered.\")))\n if sector is None:\n if department.has_profiel:\n msg_arr.append(str(_(\"The profile is not entered.\")))\n else:\n msg_arr.append(str(_(\"The sector is not entered.\")))\n if msg_arr:\n msg_txt = ' '.join(msg_arr)\n error_list.append(msg_txt)\n\n # - update scheme in student instance, also remove scheme if necessary\n # - update scheme in all studsubj of this student\n update_scheme_in_studsubj(instance, request)\n\n# - create examnumber if it does not yet exist\n examnumber = getattr(instance, 'examnumber')\n if examnumber is None:\n # get highest examnumber + 1\n examnumber = stud_fnc.get_next_examnumber(school, department)\n examnumber_str = str(examnumber) if examnumber else None\n setattr(instance, 'examnumber', examnumber_str)\n save_changes = True\n updated_fields.append('examnumber')\n if logging_on:\n logger.debug('setattr(instance, examnumber, examnumber: ' + str(examnumber))\n\n# - calculate registration number\n #PR2023-08-11 from 2023 regnumber is created when printing diploma or gradelist\n # only 2022 has regnumbers stored in table Student- not used in student any more\n if recalc_regnumber and sel_examyear.code < 2023:\n school_code, depbase, levelbase, bis_exam = None, None, None, False\n\n if school:\n schoolbase = getattr(school, 'base')\n if schoolbase:\n school_code = schoolbase.code\n\n if department:\n depbase = getattr(department, 'base')\n\n level = getattr(instance, 'level')\n if level:\n levelbase = getattr(level, 'base')\n\n gender = getattr(instance, 'gender')\n\n # - calc_regnumber\n bis_exam = getattr(instance, 'bis_exam') or False\n depbase_code = depbase.code if depbase else None\n levelbase_code = levelbase.code if levelbase else None\n\n new_regnumber = stud_fnc.calc_regnumber_2022(\n school_code=school_code,\n gender=gender,\n examyear_str=str(sel_examyear.code),\n examnumber_str=examnumber,\n depbase_code=depbase_code,\n levelbase_code=levelbase_code,\n bis_exam=bis_exam\n )\n\n saved_value = getattr(instance, 'regnumber')\n if new_regnumber != saved_value:\n setattr(instance, 'regnumber', new_regnumber)\n save_changes = True\n updated_fields.append('regnumber')\n if logging_on:\n logger.debug('setattr(instance, regnumber, new_regnumber: ' + str(new_regnumber))\n\n# 5. save changes\n if save_changes:\n\n # update subj_composition_checked and subj_composition_ok when recalc_subj_composition PR2022-08-30\n if recalc_subj_composition:\n # validate_studentsubjects_no_msg returns True when there is an error\n no_error = not stud_val.validate_studentsubjects_no_msg(instance, 'nl')\n if (not instance.subj_composition_checked) or \\\n (instance.subj_composition_checked and instance.subj_composition_ok != no_error):\n setattr(instance, 'subj_composition_checked', True)\n setattr(instance, 'subj_composition_ok', no_error)\n updated_fields.extend(['subj_composition_checked', 'subj_composition_ok'])\n\n try:\n if not skip_save:\n instance.save(request=request)\n\n mode = 'i' if is_import else 'u'\n awpr_log.savetolog_student(instance.pk, mode, request, updated_fields)\n\n changes_are_saved = True\n except Exception as e:\n save_error = True\n err_txt1 = str(_('An error occurred'))\n err_txt2 = str(e)\n err_txt3 = str(_(\"The changes have not been saved.\"))\n error_list.append(''.join((err_txt1, ': ', err_txt2)))\n\n msg_html = ''.join((err_txt1, ': ', '
', err_txt2, '
',err_txt3))\n msg_dict = {'header': str(_('Save changes')), 'class': 'border_bg_invalid', 'msg_html': msg_html}\n msg_list.append(msg_dict)\n\n logger.error(getattr(e, 'message', str(e)))\n\n if instance and changes_are_saved:\n if remove_exemptions:\n if logging_on:\n logger.debug(' --- remove_exemptions --- ')\n # get exemptions of this student\n # check for published exemptions is already done above.\n # PR2022-04-11 Richard Westerink ATC: eveningstudent may have exemptions.\n # Don't remove exemptions when iseveningstudent or islexstudent\n if not instance.bis_exam and not instance.iseveningstudent and not instance.islexstudent:\n if student_has_exemptions(instance.pk):\n recalc_studsubj_and_student = delete_exemptions(instance.pk)\n # TODO recalc_studsubj_and_student\n\n sql_studsubj_list, sql_student_list = \\\n grd_view.update_studsubj_and_recalc_student_result(\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n student=instance)\n if sql_studsubj_list:\n calc_res.save_studsubj_batch(sql_studsubj_list)\n\n #if recalc_studsubj_and_student:\n # calc_res.calc_student_result(examyear, department, student_dict, scheme_dict,\n # schemeitems_dict, log_list,\n # sql_studsubj_list, sql_student_list)\n\n if recalc_passed_failed:\n sel_lvlbase_pk = instance.level.base_id if instance.level else None\n calc_res.calc_batch_student_result(\n sel_examyear=sel_examyear,\n sel_school=sel_school,\n sel_department=sel_department,\n student_pk_list=[instance.pk],\n sel_lvlbase_pk=sel_lvlbase_pk,\n user_lang=user_lang\n )\n\n\n if logging_on:\n logger.debug('changes_are_saved: ' + str(changes_are_saved))\n logger.debug('field_error: ' + str(field_error))\n logger.debug('error_list: ' + str(error_list))\n logger.debug('err_fields: ' + str(err_fields))\n\n return changes_are_saved, save_error, field_error\n# - end of update_student_instance\n\n\ndef student_has_exemptions(student_pk):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' --- student_has_exemptions --- ')\n\n # check if student has exemptions\n\n has_exemptions = False\n if student_pk:\n try:\n # check if exemptions exist\n sql_keys = {'stud_id': student_pk}\n sql_list = [\n \"SELECT grd_id\",\n \"FROM students_grade AS grd\",\n \"INNER JOIN students_studentsubject AS studsubj ON (studsubj.id = grd.studentsubject_id)\",\n \"WHERE studsubj.student_id = %(stud_id)s::INT)\",\n \"AND grd.examperiod = \", str(c.EXAMPERIOD_EXEMPTION),\n \"LIMIT 1;\"\n ]\n sql = ' '.join(sql_list)\n if logging_on:\n logger.debug('sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n rows = cursor.fetchall()\n has_exemptions = len(rows)\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n return has_exemptions\n\n\ndef delete_exemptions(student_pk):\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' --- delete_exemptions --- ')\n\n # check if student has exemptions\n recalc_studsubj_and_student = False\n if student_pk:\n try:\n # check if exemptions exist\n sql_keys = {'stud_id': student_pk}\n sql_list = [\n \"DELETE FROM students_grade AS grd\",\n \"WHERE grd.examperiod = 4\",\n \"AND EXISTS (SELECT * FROM students_studentsubject AS studsubj\",\n \"WHERE studsubj.id = grd.studentsubject_id\",\n \"AND studsubj.student_id = %(stud_id)s::INT)\",\n \"RETURNING grd.id;\"\n ]\n sql = ' '.join(sql_list)\n if logging_on:\n logger.debug('sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n # return list of updated grades, to calculate final grades\n rows = cursor.fetchall()\n if len(rows):\n recalc_studsubj_and_student = True\n\n # TODO recalc_studsubj_and_student\n # remove 'has_exemption' and 'exemption_year' from students_studentsubject\n sql_list = [\"UPDATE students_studentsubject AS studsubj\",\n \"SET has_exemption=False, exemption_year=NULL\"\n \"WHERE studsubj.student_id = %(stud_id)s::INT)\",\n ]\n sql = ' '.join(sql_list)\n if logging_on:\n logger.debug('sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n\n for row in cursor.fetchall():\n logger.debug('row: ' + str(row))\n\n\n if logging_on:\n logger.debug('sql: ' + str(sql))\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n # return list of updated grades, to calculate final grades\n\n for row in cursor.fetchall():\n logger.debug('row: ' + str(row))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n return recalc_studsubj_and_student\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndef update_scheme_in_studsubj(student, request):\n # --- update_scheme_in_studsubj # PR2021-03-13 PR2022-07-10\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- update_scheme_in_studsubj ----- ')\n logger.debug(' student: ' + str(student))\n # TOD add 'is_test' and log_file before uopdating scheme\n if student:\n # - update scheme in student, also remove if necessary\n new_scheme = subj_mod.Scheme.objects.get_or_none(\n department=student.department,\n level=student.level,\n sector=student.sector)\n setattr(student, 'scheme', new_scheme)\n\n if logging_on:\n logger.debug(' new_scheme: ' + str(new_scheme))\n\n # PR2022-05-18 CAL, Omega: all subjects disappear.\n # Cause: tobedeleted is set True. Dont know why yet\n\n # delete studsubj when no scheme\n # check if studsubj is submitted, set tobedeleted = True if submitted\n # PR2022-05-18 debug: Omega College: grades have disappeared\n # TODO instead of deleting studsubj: prevent making changes PR2022-07-10\n # TODO delete or change exam in grades when changing level\n\n if new_scheme:\n # - loop through studsubj of this student\n studsubjects = stud_mod.Studentsubject.objects.filter(\n student=student\n )\n for studsubj in studsubjects:\n old_subject = studsubj.schemeitem.subject\n old_subjecttype = studsubj.schemeitem.subjecttype\n\n if logging_on:\n logger.debug('....old_subject: ' + str(old_subject))\n logger.debug(' old_subjecttype: ' + str(old_subjecttype))\n\n # skip when studsub scheme equals new_scheme\n if studsubj.schemeitem.scheme != new_scheme:\n save_studsubj = False\n\n # check id studsubj is already approved or submitted\n studsubj_is_submitted = studsubj.subj_published is not None\n studsubj_is_approved = False\n if not studsubj_is_submitted:\n studsubj_is_approved = studsubj.subj_auth1by is not None or studsubj.subj_auth2by is not None\n\n # check how many times this subject occurs in new scheme\n count_subject_in_newscheme = subj_mod.Schemeitem.objects.filter(\n scheme=new_scheme,\n subject=old_subject\n ).count()\n if logging_on:\n logger.debug(' count_subject_in_newscheme: ' + str(count_subject_in_newscheme))\n\n if not count_subject_in_newscheme:\n # delete studsub when subject does not exist in new_scheme\n # check if studsubj is submitted, set tobedeleted = True if submitted\n # was: set_studsubj_tobedeleted_or_tobechanged(studsubj, True, None, request) # True = tobedeleted\n setattr(studsubj, 'tobedeleted', True)\n save_studsubj = True\n if logging_on:\n logger.debug(' count = 0 > set deleted = True')\n\n elif count_subject_in_newscheme == 1:\n # if subject occurs only once in new_scheme: replace schemeitem by new schemeitem\n new_schemeitem = subj_mod.Schemeitem.objects.get_or_none(\n scheme=new_scheme,\n subject=old_subject\n )\n if new_schemeitem:\n # change schemeitem in studsubj, set tobechanged = True if submitted\n # was: set_studsubj_tobedeleted_or_tobechanged(studsubj, False, new_schemeitem, request) # False = tobechanged\n setattr(studsubj, 'schemeitem', new_schemeitem)\n save_studsubj = True\n\n if logging_on:\n logger.debug(' count = 1 > setattr = new_schemeitem')\n logger.debug(' new_subjecttype: ' + str(new_schemeitem.subjecttype))\n else:\n # if subject occurs multiple times in new_scheme: check if one exist with same subjecttype\n new_schemeitem = subj_mod.Schemeitem.objects.get_or_none(\n scheme=new_scheme,\n subject=old_subject,\n subjecttype=old_subjecttype\n )\n if new_schemeitem:\n studsubj.schemeitem = new_schemeitem\n save_studsubj = True\n else:\n # if no schemeitem exist with same subjecttype: get schemeitem with lowest sequence\n new_schemeitem = subj_mod.Schemeitem.objects.filter(\n scheme=new_scheme,\n subject=studsubj.schemeitem.subject\n ).order_by('subjecttype__base__sequence').first()\n if new_schemeitem:\n studsubj.schemeitem = new_schemeitem\n save_studsubj = True\n if logging_on:\n logger.debug(' count = 1 > setattr = new_schemeitem')\n logger.debug(' new_subjecttype: ' + str(new_schemeitem.subjecttype))\n if save_studsubj:\n studsubj.save(request=request)\n# end of update_scheme_in_studsubj\n\n\ndef set_studsubjects_tobedeleted(request, student_pk, set_deleted=False, studsubj_pk=None):\n # PR2021-08-23 PR2022-12-28\n # delete studsubj when no scheme > PR2022-07-10 don't, instead: prevent changes when no scheme\n # check if studsubj is submitted, set tobedeleted = True if submitted\n # called by update_scheme_in_studsubj 3 times\n\n # PR2022-05-18 CAL, Omega: all subjects disappear.\n # Cause: tobedeleted is set True. Dont know why yet\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('----- set_studsubjects_tobedeleted ----- ')\n logger.debug(' student_pk: ' + str(student_pk))\n logger.debug(' studsubj_pk: ' + str(studsubj_pk))\n\n msg_html = None\n updated_studsubj_pk_list = []\n\n if student_pk:\n try:\n modifiedby_pk_str = str(request.user.pk)\n modifiedat_str = str(timezone.now())\n\n # store subj_auth and subj_published info in prev_auth and prev_published fields\n # set subj_auth and subj_published to NULL\n # set tobedeleted= True, update modified\n\n # when set_deleted = True: set deleted, otherwise: set tobedeleted\n set_deleted_str = \"deleted=TRUE, tobedeleted=False, \" if set_deleted else \"tobedeleted=TRUE, \"\n deleted_clause_str = \"AND NOT deleted \" if set_deleted else \"AND NOT tobedeleted AND NOT deleted \"\n\n sql_keys = {'stud_id': student_pk}\n sql_list = [\"UPDATE students_studentsubject AS studsubj \",\n \"SET prev_auth1by_id=subj_auth1by_id, \",\n \"prev_auth2by_id=subj_auth2by_id, \",\n \"prev_published_id=subj_published_id, \",\n \"subj_auth1by_id=NULL, subj_auth2by_id=NULL, subj_published_id=NULL, \",\n set_deleted_str,\n \"modifiedby_id=\", modifiedby_pk_str, \", modifiedat='\", modifiedat_str, \"' \",\n \"WHERE studsubj.student_id = %(stud_id)s::INT \",\n deleted_clause_str,\n ]\n\n if studsubj_pk:\n sql_keys['studsubj_id'] = studsubj_pk\n sql_list.append(\"AND id = %(studsubj_id)s::INT \")\n\n sql_list.append(\"RETURNING studsubj.id;\")\n\n sql = ''.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n updated_rows = cursor.fetchall()\n if updated_rows:\n for row in updated_rows:\n updated_studsubj_pk_list.append(row[0])\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n msg_html = ''.join((str(_('An error occurred')), ': ', '
', str(e), '
',\n str(_(\"%(cpt)s could not be restored.\") % {'cpt': _('This candidate')})))\n\n return updated_studsubj_pk_list, msg_html\n# - end of set_studsubjects_tobedeleted\n\n\ndef restore_tobedeleted_studsubjects(request, student_pk, studsubj_pk=None, include_deleted=False):\n # PR2022-12-28 PR2023-01-14\n\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug('----- restore_tobedeleted_studsubjects ----- ')\n logger.debug(' student_pk: ' + str(student_pk))\n logger.debug(' studsubj_pk: ' + str(studsubj_pk))\n\n msg_html = None\n updated_studsubj_pk_list = []\n\n if student_pk:\n try:\n modifiedby_pk_str = str(request.user.pk)\n modifiedat_str = str(timezone.now())\n\n # restore subj_auth and subj_published info from prev_auth and prev_published fields\n # set tobedeleted= False, update modified\n\n sql_keys = {'stud_id': student_pk}\n sql_list = [\"UPDATE students_studentsubject AS studsubj \",\n \"SET subj_auth1by_id=prev_auth1by_id, \",\n \"subj_auth2by_id=prev_auth2by_id, \",\n \"subj_published_id=prev_published_id, \",\n \"tobedeleted=FALSE, \",\n \"modifiedby_id=\", modifiedby_pk_str, \", modifiedat='\", modifiedat_str, \"' \",\n \"WHERE studsubj.student_id = %(stud_id)s::INT AND tobedeleted \",\n ]\n\n if not include_deleted:\n sql_list.append(\"AND NOT deleted \")\n\n if studsubj_pk:\n sql_keys['studsubj_id'] = studsubj_pk\n sql_list.append(\"AND id = %(studsubj_id)s::INT \")\n\n sql_list.append(\"RETURNING studsubj.id;\")\n\n sql = ''.join(sql_list)\n\n with connection.cursor() as cursor:\n cursor.execute(sql, sql_keys)\n updated_rows = cursor.fetchall()\n if updated_rows:\n for row in updated_rows:\n updated_studsubj_pk_list.append(row[0])\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n\n msg_html = ''.join((str(_('An error occurred')), ': ', '
', str(e), '
',\n str(_(\"%(cpt)s could not be restored.\") % {'cpt': _('This candidate')})))\n\n if logging_on:\n logger.debug(' updated_studsubj_pk_list: ' + str(updated_studsubj_pk_list))\n logger.debug(' msg_html: ' + str(msg_html))\n\n return updated_studsubj_pk_list, msg_html\n# end of restore_tobedeleted_studsubjects\n\n\n# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndef create_studsubj(student, schemeitem, messages, error_list, request, skip_save, is_import):\n # --- create student subject # PR2020-11-21 PR2021-07-21 PR2023-01-02 PR2023-08-14\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' ----- create_studsubj ----- ')\n logger.debug(' student: ' + str(student))\n logger.debug(' schemeitem: ' + str(schemeitem))\n\n has_error = False\n studsubj_instance = None\n append_key = None\n\n savetolog_fields = [] # used in savetolog_studentsubject\n savetolog_mode = None\n\n\n if student and schemeitem:\n subject_name = schemeitem.subject.name_nl if schemeitem.subject and schemeitem.subject.name_nl else '---'\n\n# - check if student already has this subject (should be not more than one)\n studsubj_instance = stud_mod.Studentsubject.objects.filter(\n student=student,\n schemeitem__subject=schemeitem.subject\n ).first()\n\n if logging_on:\n logger.debug(' subject_name: ' + str(subject_name))\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n\n# ++++++++++ studsubj_instance exists\n\n if studsubj_instance:\n\n # +++ if studsubj is not tobedeleted and not deleted:\n if not studsubj_instance.deleted and not studsubj_instance.tobedeleted:\n\n if logging_on:\n logger.debug(' studsubj_instance.tobedeleted: ' + str(studsubj_instance.tobedeleted))\n logger.debug(' studsubj_instance.deleted: ' + str(studsubj_instance.deleted))\n\n #has_error = True\n #err_01 = str(_(\"%(cpt)s '%(val)s' already exists.\") % {'cpt': _('Subject'), 'val': subject_name})\n ## error_list not in use when using modal form, message is displayed in modmessages\n #error_list.append(err_01)\n\n ## this one closes modal and shows modmessage with msg_html\n #msg_dict = {'header': _('Add subject'), 'class': 'border_bg_warning', 'msg_html': err_01}\n #messages.append(msg_dict)\n\n if schemeitem != studsubj_instance.schemeitem:\n try:\n subj_published_id = getattr(studsubj_instance, 'subj_published_id')\n\n # set schemeitem\n setattr(studsubj_instance, 'schemeitem', schemeitem)\n\n setattr(studsubj_instance, 'prev_auth1by_id', None)\n setattr(studsubj_instance, 'prev_auth2by_id', None)\n setattr(studsubj_instance, 'prev_published_id', None)\n\n setattr(studsubj_instance, 'subj_auth1by_id', None)\n setattr(studsubj_instance, 'subj_auth2by_id', None)\n setattr(studsubj_instance, 'subj_published_id', None)\n\n # PR2023-08-30 Hans Vlinkervleugel: gives open circle before submitting first Ex1.\n # solved bij adding check if is_published\n if subj_published_id:\n setattr(studsubj_instance, 'tobechanged', True)\n\n append_key = 'changed'\n\n if not skip_save:\n studsubj_instance.save(request=request)\n\n savetolog_mode = 'u'\n savetolog_fields.extend(('schemeitem_id', 'tobechanged'))\n\n except Exception as e:\n has_error = True\n logger.error(getattr(e, 'message', str(e)))\n # error_list not in use when using modal form, message is displayed in modmesages\n err_01 = str(_('An error occurred:'))\n err_02 = str(e)\n err_03 = str(_(\"%(cpt)s '%(val)s' could not be changed.\") % {'cpt': str(_('Subject')),\n 'val': subject_name})\n error_list.extend((err_01, err_02, err_03))\n\n # this one closes modal and shows modmessage with msg_html\n msg_html = '
'.join((err_01, '' + err_02 + '', err_03))\n messages.append({'class': \"alert-danger\", 'msg_html': msg_html})\n\n else:\n # +++ subject is found but is tobedeleted or deleted\n try:\n if studsubj_instance.deleted:\n # subject is deleted > remove deleted, remove prev_published, remove published\n setattr(studsubj_instance, 'deleted', False)\n setattr(studsubj_instance, 'tobedeleted', False)\n\n setattr(studsubj_instance, 'prev_auth1by_id', None)\n setattr(studsubj_instance, 'prev_auth2by_id', None)\n setattr(studsubj_instance, 'prev_published_id', None)\n\n setattr(studsubj_instance, 'subj_auth1by_id', None)\n setattr(studsubj_instance, 'subj_auth2by_id', None)\n setattr(studsubj_instance, 'subj_published_id', None)\n\n # set schemeitem\n setattr(studsubj_instance, 'schemeitem', schemeitem)\n\n append_key = 'created'\n\n savetolog_mode = 'u'\n savetolog_fields.extend(('deleted', 'tobedeleted'))\n\n elif studsubj_instance.tobedeleted:\n if schemeitem == studsubj_instance.schemeitem:\n # if new studsubj has same schemeitem as tobedeleted one\n # if studsubject is tobedeleted > restore studsubject: remove tobedeleted, restore published, remove prev_published (should be None already)\n setattr(studsubj_instance, 'deleted', False)\n setattr(studsubj_instance, 'tobedeleted', False)\n\n setattr(studsubj_instance, 'subj_auth1by_id',getattr(studsubj_instance, 'prev_auth1by_id', None))\n setattr(studsubj_instance, 'subj_auth2by_id',getattr(studsubj_instance, 'prev_auth2by_id', None))\n setattr(studsubj_instance, 'subj_published_id',getattr(studsubj_instance, 'prev_published_id', None))\n\n setattr(studsubj_instance, 'prev_auth1by_id', None)\n setattr(studsubj_instance, 'prev_auth2by_id', None)\n setattr(studsubj_instance, 'prev_published_id', None)\n\n else:\n # if new studsubj has different schemeitem as tobedeleted one:\n # if studsubject is tobedeleted > remove tobedeleted, set schemeitem, keep prevpublished , remove published (should be None already)\n\n subj_published_id = getattr(studsubj_instance, 'subj_published_id')\n\n setattr(studsubj_instance, 'deleted', False)\n setattr(studsubj_instance, 'tobedeleted', False)\n\n setattr(studsubj_instance, 'subj_auth1by_id', None)\n setattr(studsubj_instance, 'subj_auth2by_id', None)\n setattr(studsubj_instance, 'subj_published_id', None)\n\n # PR2023-08-30 Hans Vlinkervleugel: gives open circle before submitting first Ex1.\n # solved bij adding check if is_published\n if subj_published_id:\n setattr(studsubj_instance, 'tobechanged', True)\n\n # set schemeitem\n setattr(studsubj_instance, 'schemeitem', schemeitem)\n\n append_key = 'restored'\n\n if not skip_save:\n studsubj_instance.save(request=request)\n\n savetolog_mode = 'u'\n savetolog_fields.extend(('tobechanged', 'deleted', 'tobedeleted'))\n\n # +++++ also undelete grades\n # PR2023-02-12 grades are only set tobedeleted or deleted when exem. reex or reex03\n # restore previously deleted grades with ep=1\n crit = Q(studentsubject=studsubj_instance) & \\\n Q(examperiod=c.EXAMPERIOD_FIRST) & \\\n (Q(tobedeleted=True) | Q(deleted=True))\n grades = stud_mod.Grade.objects.filter(crit)\n\n if grades:\n for grade in grades:\n setattr(grade, 'tobedeleted', False)\n setattr(grade, 'deleted', False)\n if not skip_save:\n grade.save(request=request)\n\n awpr_log.savetolog_grade(\n grade_pk=grade.pk,\n req_mode='u',\n request=request,\n updated_fields=('deleted', 'tobedeleted')\n )\n\n except Exception as e:\n has_error = True\n logger.error(getattr(e, 'message', str(e)))\n # error_list not in use when using modal form, message is displayed in modmesasges\n err_01 = str(_('An error occurred:'))\n err_02 = str(e)\n err_03 = str(_(\"%(cpt)s '%(val)s' could not be added.\") % {'cpt': str(_('Subject')),\n 'val': subject_name})\n error_list.extend((err_01, err_02, err_03))\n\n # this one closes modal and shows modmessage with msg_html\n msg_html = '
'.join((err_01, '' + err_02 + '', err_03))\n messages.append({'class': \"alert-danger\", 'msg_html': msg_html})\n\n# +++++ if studsubj_instance is None: create and save Studentsubject\n else:\n try:\n studsubj_instance = stud_mod.Studentsubject(\n student=student,\n schemeitem=schemeitem\n )\n if not skip_save:\n studsubj_instance.save(request=request)\n savetolog_mode = 'i' if is_import else 'c'\n\n # - also create grade of first examperiod\n grade = stud_mod.Grade(\n studentsubject=studsubj_instance,\n examperiod=c.EXAMPERIOD_FIRST\n )\n if not skip_save:\n grade.save(request=request)\n awpr_log.savetolog_grade(\n grade_pk=grade.pk,\n req_mode='c',\n request=request,\n updated_fields=[]\n )\n\n append_key = 'created'\n\n except Exception as e:\n has_error = True\n logger.error(getattr(e, 'message', str(e)))\n\n # error_list not in use when using modal form, message is displayed in modmesasges\n err_01 = str(_('An error occurred:'))\n err_02 = str(e)\n err_03 = str(_(\"%(cpt)s '%(val)s' could not be added.\") % {'cpt': str(_('Subject')), 'val': subject_name})\n error_list.extend((err_01, err_02, err_03))\n\n # this one closes modal and shows modmessage with msg_html\n msg_html = '
'.join((err_01, '' + err_02 + '', err_03))\n messages.append({'class': \"alert-danger\", 'msg_html': msg_html})\n\n if has_error:\n studsubj_instance = None\n\n # save to log\n elif savetolog_mode:\n # PR2023-08-14 Note: subj_auth1by_id etc have no effect in log, because value is already None.\n # must see if an extra field 'is_removed' is necessary\n # updated_fields.extend(('subj_auth1by_id', 'subj_auth2by_id', 'subj_published_id'))\n awpr_log.savetolog_studentsubject(studsubj_instance.pk, savetolog_mode, request, savetolog_fields)\n\n if logging_on:\n logger.debug(' studsubj_instance: ' + str(studsubj_instance))\n logger.debug(' append_key: ' + str(append_key))\n\n return studsubj_instance, append_key\n# - end of create_studsubj\n\n\n#/////////////////////////////////////////////////////////////////\n\ndef create_studentsubject_rows(sel_examyear, sel_schoolbase, sel_depbase, append_dict, request,\n requsr_same_school=False, sel_lvlbase=None, student_pk=None,\n studsubj_pk_list=None, cluster_pk_list=None):\n # --- create rows of all students of this examyear / school / dep PR2020-10-27 PR2022-01-10 studsubj_pk_list added\n # PR2022-02-15 show only not tobeleted students and studentsubjects\n # PR2022-03-23 cluster_pk_list added, to return studsubj with changed clustername\n # PR2022-12-16 allowed filter renewed\n # PR2023-04-18 Sentry error fixed: syntax error at or near \")\" LINE 1: ...cluster_id IN (SELECT UNNEST(ARRAY[1465]::INT[])) ) ORDER BY...\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' ')\n logger.debug(' =============== create_studentsubject_rows ============= ')\n logger.debug(' student_pk: ' + str(student_pk))\n logger.debug(' sel_schoolbase: ' + str(sel_schoolbase))\n logger.debug(' sel_depbase: ' + str(sel_depbase))\n logger.debug(' sel_lvlbase: ' + str(sel_lvlbase))\n logger.debug(' requsr_same_school: ' + str(requsr_same_school))\n logger.debug(' studsubj_pk_list: ' + str(studsubj_pk_list))\n logger.debug(' append_dict: ' + str(append_dict))\n logger.debug(' cluster_pk_list: ' + str(cluster_pk_list))\n logger.debug(' ......................... ')\n\n rows = []\n try:\n # create list of students of this school / examyear, possibly with filter student_pk or studsubj_pk\n # with left join of studentsubjects with deleted=False\n # when role is other than school: only when submitted, don't show students without submitted subjects\n sel_examyear_pk = sel_examyear.pk if sel_examyear else None\n sel_schoolbase_pk = sel_schoolbase.pk if sel_schoolbase else None\n sel_depbase_pk = sel_depbase.pk if sel_depbase else None\n sel_lvlbase_pk = sel_lvlbase.pk if sel_lvlbase else None\n\n # - get selected sctbase_pk of req_usr\n selected_pk_dict = acc_prm.get_selected_pk_dict_of_user_instance(request.user)\n sel_sctbase_pk = selected_pk_dict.get(c.KEY_SEL_SCTBASE_PK) if selected_pk_dict else None\n\n # - get allowed_sections_dict from request\n userallowed_instance = acc_prm.get_userallowed_instance_from_request(request)\n\n userallowed_sections_dict = acc_prm.get_userallowed_sections_dict(userallowed_instance)\n if logging_on:\n logger.debug(\n ' allowed_sections_dict: ' + str(userallowed_sections_dict) + ' ' + str(\n type(userallowed_sections_dict)))\n # allowed_sections_dict: {'2': {'1': {'4': [117, 114], '5': [], '-9': [118, 121]}}} \n\n # dont show students without subject on other users than sameschool\n #PR2022-01-10 also use inner join when studsubj_pk_list has values: only these records must be returned\n #left_or_inner_join = \"LEFT JOIN\" if requsr_same_school and not studsubj_pk_list else \"INNER JOIN\"\n left_or_inner_join = \"LEFT JOIN\"\n\n sql_keys = {'ey_id': sel_examyear_pk, 'sb_id': sel_schoolbase_pk, 'db_id': sel_depbase_pk}\n sql_studsubj_list = [\"SELECT studsubj.id AS studsubj_id, studsubj.student_id,\",\n \"cl.id AS cluster_id, cl.name AS cluster_name, si.id AS schemeitem_id, si.scheme_id AS scheme_id,\",\n \"studsubj.is_extra_nocount, studsubj.is_extra_counts, studsubj.is_thumbrule,\",\n \"studsubj.pws_title, studsubj.pws_subjects,\",\n \"studsubj.has_exemption, studsubj.has_sr, studsubj.has_reex, studsubj.has_reex03, studsubj.exemption_year, studsubj.pok_validthru,\",\n \"si.subject_id, si.subjecttype_id, si.gradetype,\",\n \"subjbase.id AS subjbase_id, subjbase.code AS subj_code, subj.name_nl AS subj_name_nl,\",\n \"si.weight_se, si.weight_ce,\",\n \"si.is_mandatory, si.is_mand_subj_id, si.is_combi, si.extra_count_allowed, si.extra_nocount_allowed,\",\n \"si.has_practexam,\",\n\n \"sjt.id AS sjtp_id, sjt.abbrev AS sjtp_abbrev, sjt.has_prac AS sjtp_has_prac, sjt.has_pws AS sjtp_has_pws,\",\n \"sjtbase.sequence AS sjtbase_sequence,\",\n\n \"studsubj.subj_auth1by_id, subj_auth1.last_name AS subj_auth1_usr,\",\n \"studsubj.subj_auth2by_id , subj_auth2.last_name AS subj_auth2_usr,\",\n \"studsubj.subj_published_id, subj_published.modifiedat AS subj_publ_modat,\",\n\n \"studsubj.exem_auth1by_id , exem_auth1.last_name AS exem_auth1_usr,\",\n \"studsubj.exem_auth2by_id, exem_auth2.last_name AS exem_auth2_usr,\",\n \"studsubj.exem_published_id, exem_published.modifiedat AS exem_publ_modat,\",\n\n \"studsubj.sr_auth1by_id AS sr_auth1by_id, sr_auth1.last_name AS sr_auth1_usr,\",\n \"studsubj.sr_auth2by_id AS sr_auth2by_id, sr_auth2.last_name AS sr_auth2_usr,\",\n \"studsubj.sr_published_id, sr_published.modifiedat AS sr_publ_modat,\",\n\n \"studsubj.reex_auth1by_id, reex_auth1.last_name AS reex_auth1_usr,\",\n \"studsubj.reex_auth2by_id, reex_auth2.last_name AS reex_auth2_usr,\",\n \"studsubj.reex_published_id, reex_published.modifiedat AS reex_publ_modat,\",\n\n \"studsubj.reex3_auth1by_id, reex3_auth1.last_name AS reex3_auth1_usr,\",\n \"studsubj.reex3_auth2by_id, reex3_auth2.last_name AS reex3_auth2_usr,\",\n \"studsubj.reex3_published_id, reex3_published.modifiedat AS reex3_publ_modat,\",\n\n \"studsubj.pok_auth1by_id, pok_auth1.last_name AS pok_auth1_usr,\",\n \"studsubj.pok_auth2by_id, pok_auth2.last_name AS pok_auth2_usr,\",\n \"studsubj.pok_published_id, pok_published.modifiedat AS pok_publ_modat,\",\n\n \"studsubj.tobedeleted, studsubj.modifiedby_id, studsubj.modifiedat,\",\n \"au.last_name AS modby_username\",\n\n \"FROM students_studentsubject AS studsubj\",\n\n \"INNER JOIN students_student AS stud ON (stud.id = studsubj.student_id)\",\n \"INNER JOIN subjects_schemeitem AS si ON (si.id = studsubj.schemeitem_id)\",\n \"INNER JOIN subjects_subject AS subj ON (subj.id = si.subject_id)\",\n \"INNER JOIN subjects_subjectbase AS subjbase ON (subjbase.id = subj.base_id)\",\n \"LEFT JOIN subjects_subjecttype AS sjt ON (sjt.id = si.subjecttype_id)\",\n \"INNER JOIN subjects_subjecttypebase AS sjtbase ON (sjtbase.id = sjt.base_id)\",\n\n \"LEFT JOIN subjects_cluster AS cl ON (cl.id = studsubj.cluster_id)\",\n\n \"LEFT JOIN accounts_user AS au ON (au.id = studsubj.modifiedby_id)\",\n\n \"LEFT JOIN accounts_user AS subj_auth1 ON (subj_auth1.id = studsubj.subj_auth1by_id)\",\n \"LEFT JOIN accounts_user AS subj_auth2 ON (subj_auth2.id = studsubj.subj_auth2by_id)\",\n \"LEFT JOIN schools_published AS subj_published ON (subj_published.id = studsubj.subj_published_id)\",\n\n \"LEFT JOIN accounts_user AS exem_auth1 ON (exem_auth1.id = studsubj.exem_auth1by_id)\",\n \"LEFT JOIN accounts_user AS exem_auth2 ON (exem_auth2.id = studsubj.exem_auth2by_id)\",\n \"LEFT JOIN schools_published AS exem_published ON (exem_published.id = studsubj.exem_published_id)\",\n\n \"LEFT JOIN accounts_user AS sr_auth1 ON (sr_auth1.id = studsubj.sr_auth1by_id)\",\n \"LEFT JOIN accounts_user AS sr_auth2 ON (sr_auth2.id = studsubj.sr_auth2by_id)\",\n \"LEFT JOIN schools_published AS sr_published ON (sr_published.id = studsubj.sr_published_id)\",\n\n \"LEFT JOIN accounts_user AS reex_auth1 ON (reex_auth1.id = studsubj.reex_auth1by_id)\",\n \"LEFT JOIN accounts_user AS reex_auth2 ON (reex_auth2.id = studsubj.reex_auth2by_id)\",\n \"LEFT JOIN schools_published AS reex_published ON (reex_published.id = studsubj.reex_published_id)\",\n\n \"LEFT JOIN accounts_user AS reex3_auth1 ON (reex3_auth1.id = studsubj.reex3_auth1by_id)\",\n \"LEFT JOIN accounts_user AS reex3_auth2 ON (reex3_auth2.id = studsubj.reex3_auth2by_id)\",\n \"LEFT JOIN schools_published AS reex3_published ON (reex3_published.id = studsubj.reex3_published_id)\",\n\n \"LEFT JOIN accounts_user AS pok_auth1 ON (pok_auth1.id = studsubj.pok_auth1by_id)\",\n \"LEFT JOIN accounts_user AS pok_auth2 ON (pok_auth2.id = studsubj.pok_auth2by_id)\",\n \"LEFT JOIN schools_published AS pok_published ON (pok_published.id = studsubj.pok_published_id)\",\n\n \"WHERE NOT stud.deleted AND NOT studsubj.deleted\"\n\n # PR2022-12-26 show tobedeleted records only when they are not submitted yet\n # \"WHERE NOT studsubj.tobedeleted\"\n #\"WHERE ( NOT studsubj.tobedeleted OR (studsubj.tobedeleted AND studsubj.subj_published_id IS NULL) )\"\n ]\n\n # studsubj are only visible for other users than sameschool when they are published\n\n # PR0222-09-06 mail Nancy Josephina Insp: cannot validate.\n # must show alls subjects to Insp, also when they are not published\n # added: 'and not request.user.role == c.ROLE_032_INSP:'\n # PR2023-06-08 filter published removed\n #if not requsr_same_school and not request.user.role == c.ROLE_032_INSP:\n # # PR2022-12-16 NIU: there are no examyears before 2022\n # # PR2021-09-04 debug: examyears before 2022 have no subj_published_id. Show them to others anyway\n # # if sel_examyear is None or sel_examyear.code >= 2022:\n # sql_studsubj_list.append(\"AND studsubj.subj_published_id IS NOT NULL\")\n\n sql_studsubjects = ' '.join(sql_studsubj_list)\n\n sql_list = [\"WITH studsubj AS (\" + sql_studsubjects + \")\",\n \"SELECT st.id AS stud_id, studsubj.studsubj_id, studsubj.subjbase_id, studsubj.schemeitem_id, studsubj.cluster_id, studsubj.cluster_name,\",\n \"CONCAT('studsubj_', st.id::TEXT, '_', studsubj.studsubj_id::TEXT) AS mapid, 'studsubj' AS table,\",\n \"st.lastname, st.firstname, st.prefix, st.examnumber,\",\n \"st.scheme_id, st.iseveningstudent, st.islexstudent, st.classname, \",\n \"st.tobedeleted AS st_tobedeleted, st.reex_count, st.reex03_count, st.bis_exam, st.withdrawn,\",\n\n \"st.subj_composition_checked, st.subj_composition_ok, st.subj_dispensation,\",\n\n \"studsubj.subject_id AS subj_id, studsubj.subj_code, studsubj.subj_name_nl,\",\n \"dep.base_id AS depbase_id, dep.abbrev AS dep_abbrev,\",\n \"lvl.base_id AS lvlbase_id, lvl.abbrev AS lvl_abbrev,\",\n \"sct.base_id AS sctbase_id, sct.abbrev AS sct_abbrev,\",\n\n \"studsubj.is_extra_nocount, studsubj.is_extra_counts, studsubj.is_thumbrule,\",\n \"studsubj.pws_title, studsubj.pws_subjects,\",\n \"studsubj.has_exemption, studsubj.has_sr, studsubj.has_reex, studsubj.has_reex03, studsubj.exemption_year, studsubj.pok_validthru,\",\n\n \"studsubj.is_mandatory, studsubj.is_mand_subj_id, studsubj.is_combi,\",\n \"studsubj.extra_count_allowed, studsubj.extra_nocount_allowed,\",\n \"studsubj.sjtp_id, studsubj.sjtp_abbrev, studsubj.sjtp_has_prac, studsubj.sjtp_has_pws,\",\n \"studsubj.weight_se, studsubj.weight_ce,\",\n \"studsubj.subj_auth1by_id, studsubj.subj_auth1_usr,\",\n \"studsubj.subj_auth2by_id, studsubj.subj_auth2_usr,\",\n \"studsubj.subj_published_id, studsubj.subj_publ_modat,\",\n\n \"studsubj.exem_auth1by_id, studsubj.exem_auth1_usr,\",\n \"studsubj.exem_auth2by_id, studsubj.exem_auth2_usr,\",\n \"studsubj.exem_published_id, studsubj.exem_publ_modat,\",\n\n \"studsubj.sr_auth1by_id, studsubj.sr_auth1_usr,\",\n \"studsubj.sr_auth2by_id, studsubj.sr_auth2_usr,\",\n \"studsubj.sr_published_id, studsubj.sr_publ_modat,\",\n\n \"studsubj.reex_auth1by_id, studsubj.reex_auth1_usr,\",\n \"studsubj.reex_auth2by_id, studsubj.reex_auth2_usr,\",\n \"studsubj.reex_published_id, studsubj.reex_publ_modat,\",\n\n \"studsubj.reex3_auth1by_id, studsubj.reex3_auth1_usr,\",\n \"studsubj.reex3_auth2by_id, studsubj.reex3_auth2_usr,\",\n \"studsubj.reex3_published_id, studsubj.reex3_publ_modat,\",\n\n \"studsubj.pok_auth1by_id, studsubj.pok_auth1_usr,\",\n \"studsubj.pok_auth2by_id, studsubj.pok_auth2_usr,\",\n \"studsubj.pok_published_id, studsubj.pok_publ_modat,\",\n\n \"studsubj.tobedeleted, studsubj.modifiedat, studsubj.modby_username\",\n\n \"FROM students_student AS st\",\n left_or_inner_join, \"studsubj ON (studsubj.student_id = st.id)\",\n \"INNER JOIN schools_school AS school ON (school.id = st.school_id)\",\n \"INNER JOIN schools_department AS dep ON (dep.id = st.department_id)\",\n \"LEFT JOIN subjects_level AS lvl ON (lvl.id = st.level_id)\",\n \"LEFT JOIN subjects_sector AS sct ON (sct.id = st.sector_id)\",\n \"LEFT JOIN subjects_scheme AS scheme ON (scheme.id = st.scheme_id)\",\n \"LEFT JOIN subjects_package AS package ON (package.id = st.package_id)\",\n\n \"WHERE school.base_id=\" + str(sel_schoolbase_pk) + \"::INT\",\n \"AND school.examyear_id=\" + str(sel_examyear_pk) + \"::INT\",\n \"AND dep.base_id=\" + str(sel_depbase_pk) + \"::INT\",\n \"AND NOT st.deleted\"\n ]\n\n if sel_lvlbase_pk:\n sql_list.append(\"\".join((\"AND lvl.base_id=\", str(sel_lvlbase_pk), \"::INT\")))\n\n if sel_sctbase_pk:\n sql_list.append(\"\".join((\"AND sct.base_id=\", str(sel_sctbase_pk), \"::INT\")))\n\n # filter on sel_student_pk\n if student_pk:\n sql_list.append(\"\".join((\"AND st.id=\", str(student_pk), \"::INT\")))\n\n # also return existing studsubj of updated clusters, to show changed name in table\n # - filter on studsubj_pk_list with ANY clause\n # - PR2022-03-23 see https://stackoverflow.com/questions/34627026/in-vs-any-operator-in-postgresql\n if cluster_pk_list:\n sql_keys['cls_pk_list'] = cluster_pk_list\n if studsubj_pk_list:\n # PR2023-02-18 was:\n # sql_keys['ss_pk_list'] = studsubj_pk_list\n # PR2022-12-25 was: sql_list.append(\"AND ( studsubj.studsubj_id = ANY(%(ss_pk_list)s::INT[]) OR studsubj.cluster_id = ANY(%(cls_pk_list)s::INT[]) ) \")\n # sql_list.append(\"AND ( studsubj.studsubj_id IN (SELECT UNNEST(%(ss_pk_list)s::INT[])) OR studsubj.cluster_id IN (SELECT UNNEST(%(cls_pk_list)s::INT[])) )\")\n\n sql_list.append(''.join((\n \"AND (studsubj.studsubj_id IN (SELECT UNNEST(ARRAY\", str(studsubj_pk_list), \"::INT[])) OR \",\n \"studsubj.cluster_id IN (SELECT UNNEST(ARRAY\", str(cluster_pk_list), \"::INT[])) )\"\n )))\n else:\n # PR2023-02-18 was:\n # PR2022-12-26 was: sql_list.append(\"AND studsubj.cluster_id = ANY(%(cls_pk_list)s::INT[])\")\n # sql_list.append(\"AND studsubj.cluster_id IN (SELECT UNNEST( %(cls_pk_list)s::INT[]))\")\n sql_list.append(\n ''.join((\n \"AND studsubj.cluster_id IN (SELECT UNNEST(ARRAY\", str(cluster_pk_list), \"::INT[]))\"\n ))\n )\n\n elif studsubj_pk_list:\n # PR2023-02-18 was:\n # sql_keys['ss_pk_list'] = studsubj_pk_list\n # PR2022-12-25 was: sql_list.append(\"AND studsubj.studsubj_id = ANY(%(ss_pk_list)s::INT[])\")\n # sql_list.append(\"AND studsubj.studsubj_id IN (SELECT UNNEST(%(ss_pk_list)s::INT[]))\")\n sql_list.append(''.join((\"AND studsubj.studsubj_id IN (SELECT UNNEST(ARRAY\", str(studsubj_pk_list), \"::INT[]))\")))\n\n else:\n # --- filter on usersetting and allowed\n\n requsr_corrector = (request.user.role == c.ROLE_016_CORR)\n\n # PR2023-03-27\n # when a corrector has no allowed subjects, must return None.\n # when an examiner has no allowed subjects, must return all subjects.\n return_false_when_no_allowedsubjects = requsr_corrector\n\n sql_clause = acc_prm.get_sqlclause_allowed_NEW(\n table='studsubj',\n sel_schoolbase_pk=sel_schoolbase_pk,\n sel_depbase_pk=sel_depbase_pk,\n sel_lvlbase_pk=sel_lvlbase_pk,\n userallowed_sections_dict=userallowed_sections_dict,\n return_false_when_no_allowedsubjects=return_false_when_no_allowedsubjects\n )\n if sql_clause:\n sql_list.append(sql_clause)\n\n if logging_on :\n logger.debug('sql_clause: ' + str(sql_clause))\n\n sql_list.append('ORDER BY st.id, studsubj.studsubj_id NULLS FIRST;')\n if logging_on and False:\n for sql_str in sql_list:\n logger.debug(' > ' + str(sql_str))\n\n sql = ' '.join(sql_list)\n\n with connection.cursor() as cursor:\n #cursor.execute(sql, sql_keys)\n cursor.execute(sql)\n rows = af.dictfetchall(cursor)\n\n if logging_on and False:\n for q in connection.queries:\n logger.debug(' ' + str(q))\n\n if logging_on:\n logger.debug(' len rows: ' + str(len(rows)))\n\n # - full name to rows\n for row in rows:\n first_name = row.get('firstname')\n last_name = row.get('lastname')\n prefix = row.get('prefix')\n full_name = stud_fnc.get_lastname_firstname_initials(last_name, first_name, prefix)\n row['fullname'] = full_name if full_name else None\n\n # - add additional key/value pairs to studsubj_row, from append_dict, with key = studsubj_id\n if append_dict:\n studsubj_append_dict = append_dict.get(row.get('studsubj_id'))\n if studsubj_append_dict:\n for key, value in studsubj_append_dict.items():\n row[key] = value\n\n if logging_on and False:\n logger.debug('row: ' + str(row))\n\n except Exception as e:\n logger.error(getattr(e, 'message', str(e)))\n return rows\n# --- end of create_studentsubject_rows\n\n\ndef create_studentsubjectnote_rows(upload_dict, request): # PR2021-03-16\n # --- create rows of notes of this studentsubject\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' =============== create_studentsubjectnote_rows ============= ')\n logger.debug('upload_dict: ' + str(upload_dict))\n # create list of studentsubjectnote of this studentsubject, filter intern_schoolbase\n # to show intern note only to user of the same school/insp: filter intern_schoolbase = requsr.schoolbase or null\n # intern_schoolbase only has value when it is an intern memo.\n # It has the value of the school of the user, NOT the school of the student\n note_rows = []\n if upload_dict:\n studsubj_pk = upload_dict.get('studsubj_pk')\n if studsubj_pk:\n if logging_on:\n logger.debug('studsubj_pk: ' + str(studsubj_pk))\n sel_examyear_instance = af.get_selected_examyear_from_usersetting_without_check(request)\n if sel_examyear_instance:\n sql_keys = {\n 'ss_id': studsubj_pk,\n 'ex_yr': sel_examyear_instance.pk,\n 'req_int_sb_id': request.user.schoolbase_id}\n sql_list = [\"SELECT au.id, COALESCE(SUBSTRING (au.username, 7), '') AS name,\",\n \"sb.code AS sb_code, sch.abbrev as sch_abbrev \",\n \"FROM accounts_user AS au\",\n \"INNER JOIN schools_schoolbase AS sb ON (sb.id = au.schoolbase_id)\",\n \"INNER JOIN schools_school AS sch ON (sch.base_id = au.schoolbase_id)\",\n \"WHERE sch.examyear_id = %(ex_yr)s::INT\"\n ]\n\n sql_user = ' '.join(sql_list)\n sql_list = [\"SELECT ssn.id, ssn.studentsubject_id, ssn.note, ssn.note_status, ssn.intern_schoolbase_id,\",\n \"ssn.modifiedat, au.name AS modifiedby, au.sb_code, au.sch_abbrev\",\n\n \"FROM students_studentsubjectnote AS ssn\",\n \"INNER JOIN students_studentsubject AS studsubj ON (studsubj.id = ssn.studentsubject_id)\",\n \"INNER JOIN students_student AS st ON (st.id = studsubj.student_id)\",\n \"LEFT JOIN ( \" + sql_user + \") AS au ON (au.id = ssn.modifiedby_id)\",\n \"WHERE ssn.studentsubject_id = %(ss_id)s::INT\",\n \"AND (ssn.intern_schoolbase_id = %(req_int_sb_id)s::INT OR ssn.intern_schoolbase_id IS NULL)\"\n ]\n sql_list.append(\"ORDER BY ssn.modifiedat DESC\")\n\n sql = ' '.join(sql_list)\n newcursor = connection.cursor()\n newcursor.execute(sql, sql_keys)\n note_rows = af.dictfetchall(newcursor)\n if note_rows:\n for note_row in note_rows:\n ssn_id = note_row.get('id')\n\n if logging_on:\n logger.debug('note_row: ' + str(note_row))\n logger.debug('ssn_id: ' + str(ssn_id))\n sql_keys = {'ssn_id': ssn_id}\n sql_list = [\n \"SELECT nat.id, nat.file, nat.contenttype, nat.studentsubjectnote_id\",\n \"FROM students_noteattachment AS nat\",\n \"WHERE nat.studentsubjectnote_id = %(ssn_id)s::INT\"\n ]\n # \"WHERE nat.studentsubjectnote_id = %(ssn_id)s::INT\"\n sql_list.append(\"ORDER BY nat.file\")\n sql = ' '.join(sql_list)\n newcursor.execute(sql, sql_keys)\n rows = newcursor.fetchall()\n\n if logging_on:\n logger.debug('rows: ' + str(rows))\n\n attachments = stud_mod.Noteattachment.objects.filter(\n studentsubjectnote=ssn_id)\n # get list of attachments\n nat_rows = []\n if attachments:\n for attachment in attachments:\n file = attachment.file\n url = file.url\n nat_rows.append({'id': attachment.pk, 'file_name': str(file), 'url': url})\n if nat_rows:\n note_row['attachments'] = nat_rows\n\n return note_rows\n# - end of create_studentsubjectnote_rows\n\n\ndef create_ssnote_attachment_rows(upload_dict, request): # PR2021-03-17\n # --- create rows of notes of this studentsubject\n logging_on = False # s.LOGGING_ON\n if logging_on:\n logger.debug(' =============== create_studentsubjectnote_rows ============= ')\n logger.debug('upload_dict: ' + str(upload_dict))\n # create list of studentsubjectnote of this studentsubject, filter intern_schoolbase\n # to show intern note only to user of the same school/insp: filter intern_schoolbase = requsr.schoolbase or null\n note_rows = []\n if upload_dict:\n studsubj_pk = upload_dict.get('studsubj_pk')\n if studsubj_pk:\n requsr_intern_schoolbase_pk = request.user.schoolbase_id\n if logging_on:\n logger.debug('studsubj_pk: ' + str(studsubj_pk))\n logger.debug('requsr_intern_schoolbase_pk: ' + str(requsr_intern_schoolbase_pk))\n\n sql_keys = {'ss_id': studsubj_pk, 'int_sb_id': requsr_intern_schoolbase_pk}\n sql_user = \"SELECT au.id, COALESCE(SUBSTRING (au.username, 7), '') AS name, sb.code AS sb_code \" + \\\n \"FROM accounts_user AS au INNER JOIN schools_schoolbase AS sb ON (sb.id = au.schoolbase_id)\"\n\n sql_list = [\"SELECT ssn.id, ssn.studentsubject_id, ssn.note, ssn.note_status, ssn.intern_schoolbase_id,\",\n \"ssn.modifiedat, au.name AS modifiedby, au.sb_code AS schoolcode\",\n \"FROM students_studentsubjectnote AS ssn\",\n \"INNER JOIN students_studentsubject AS studsubj ON (studsubj.id = ssn.studentsubject_id)\",\n \"INNER JOIN students_student AS st ON (st.id = studsubj.student_id)\",\n \"LEFT JOIN ( \" + sql_user + \") AS au ON (au.id = ssn.modifiedby_id)\",\n \"WHERE ssn.studentsubject_id = %(ss_id)s::INT\"\n\n ]\n #\"AND ( ssn.intern_schoolbase_id IS NULL OR ssn.intern_schoolbase_id = %(int_sb_id)s::INT ) \"\n\n sql_list.append(\"ORDER BY ssn.modifiedat DESC\")\n\n sql = ' '.join(sql_list)\n newcursor = connection.cursor()\n newcursor.execute(sql, sql_keys)\n note_rows = af.dictfetchall(newcursor)\n\n return note_rows\n# - end of create_studentsubjectnote_rows\n\n\ndef create_student_with_thumbrule2023_TEMP_rows_NIU(): # PR2023-07-01\n # --- temporary, to get list ofstudents with thumbrule in 2023, should not have happened\n logging_on = s.LOGGING_ON\n if logging_on:\n logger.debug(' =============== create_student_with_thumbrule2023_TEMP_rows_NIU ============= ')\n\n student_with_thumbrule_rows = []\n\n sql = ' '.join((\"SELECT studsubj.id, sb.code, school.abbrev, dep.abbrev AS depcode, stud.lastname, stud.firstname, studsubj.deleted, studsubj.tobedeleted,\",\n \"au.last_name AS modifiedby, studsubj.modifiedat\",\n\n \"FROM students_studentsubject AS studsubj\",\n \"INNER JOIN students_student AS stud ON (stud.id = studsubj.student_id)\",\n \"INNER JOIN schools_school AS school ON (school.id = stud.school_id)\",\n \"INNER JOIN schools_department AS dep ON (dep.id = stud.department_id)\",\n \"INNER JOIN schools_schoolbase AS sb ON (sb.id = school.base_id)\",\n \"INNER JOIN schools_examyear AS ey ON (ey.id = school.examyear_id)\",\n \"LEFT JOIN accounts_user AS au ON (au.id = studsubj.modifiedby_id)\",\n\n \"WHERE studsubj.is_thumbrule\",\n \"AND ey.code = 2023\"\n ))\n\n cursor = connection.cursor()\n cursor.execute(sql)\n student_with_thumbrule_rows = af.dictfetchall(cursor)\n\n if logging_on:\n for row in student_with_thumbrule_rows:\n logger.debug(str(row))\n\n return student_with_thumbrule_rows\n# - end of create_student_with_thumbrule2023_TEMP_rows_NIU\n\n\n","repo_name":"hansmeijs/awpr","sub_path":"awpr/students/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":458273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34720823893","text":"class PriorityQueue(object):\r\n\tdef __init__(self):\r\n\t\tself.queue = []\r\n\tdef __str__(self):\r\n\t\treturn ' '.join([str(i) for i in self.queue])\r\n\tdef isEmpty(self):\r\n\t\treturn len(self.queue) == 0\r\n\tdef insert(self, data):\r\n\t\tself.queue.append(data)\r\n\tdef delete(self):\r\n\t\ttry:\r\n\t\t\tmax_val = 0\r\n\t\t\tfor i in range(len(self.queue)):\r\n\t\t\t\tif self.queue[i] > self.queue[max_val]:\r\n\t\t\t\t\tmax_val = i\r\n\t\t\titem = self.queue[max_val]\r\n\t\t\tdel self.queue[max_val]\r\n\t\t\treturn item\r\n\t\texcept IndexError:\r\n\t\t\tprint()\r\n\t\t\texit()\r\nmyQueue = PriorityQueue()\r\nmyQueue.insert(12)\r\nmyQueue.insert(1)\r\nmyQueue.insert(14)\r\nmyQueue.insert(7)\r\nprint(\"Initial queue:\",myQueue)\t\r\nprint(\"After dequeue, Priority Queue:\")\t\r\nwhile not myQueue.isEmpty():\r\n print(myQueue.delete())","repo_name":"traxhcxn/PortaPrograms","sub_path":"priority-queue.py","file_name":"priority-queue.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"15367643195","text":"import xlrd\r\nimport numpy as np\r\nimport torch.utils.data as data\r\nimport torch\r\nimport random\r\n\r\nseed = 1\r\ntorch.manual_seed(seed)\r\ntorch.cuda.manual_seed(seed)\r\ntorch.cuda.manual_seed_all(seed)\r\nnp.random.seed(seed)\r\nrandom.seed(seed)\r\n\r\nclass Folder(data.Dataset):\r\n def __init__(self, train):\r\n\r\n self.train = train\r\n\r\n # 打开excel\r\n wb = xlrd.open_workbook('test.xlsx')\r\n # 按工作簿定位工作表\r\n sh = wb.sheet_by_name('Sheet1')\r\n\r\n data_dict = dict()\r\n train_dict = dict()\r\n test_dict = dict()\r\n for title in sh.row_values(0):\r\n data_dict[title] = [] # 读取第一行的标题, 每个标题作为data_dict的一个键, 初始化各个键的值为空列表\r\n train_dict[title] = []\r\n test_dict[title] = []\r\n index_dict = {0: \"x1\", 1: \"x2\", 2: \"y1\", 3: \"y2\", 4: \"y3\"}\r\n key_list = [\"x1\", \"x2\", \"y1\", \"y2\", \"y3\"]\r\n\r\n # 载入数据\r\n row_num = sh.nrows\r\n col_num = sh.ncols\r\n for row_i in range(1, row_num):\r\n for col_i in range(col_num):\r\n data_dict[index_dict[col_i]].append(sh.cell(row_i, col_i).value)\r\n\r\n # 数据归一化\r\n scaled_data_dict = self.data_scale(data_dict, key_list)\r\n\r\n\r\n # 划分训练集和测试集\r\n self.index = list(range(row_num-1))\r\n random.shuffle(self.index)\r\n train_index = self.index[0:int(round(0.8 * len(self.index)))]\r\n test_index = self.index[int(round(0.8 * len(self.index))):len(self.index)]\r\n\r\n for row_i in range(len(self.index)):\r\n if row_i in test_index:\r\n for col_i in range(col_num):\r\n test_dict[index_dict[col_i]].append(scaled_data_dict[index_dict[col_i]][row_i])\r\n else:\r\n for col_i in range(col_num):\r\n train_dict[index_dict[col_i]].append(scaled_data_dict[index_dict[col_i]][row_i])\r\n\r\n\r\n # 扩充维度\r\n for key, values in train_dict.items():\r\n train_dict[key] = np.expand_dims(np.array(values), axis=1)\r\n for key, values in test_dict.items():\r\n test_dict[key] = np.expand_dims(np.array(values), axis=1)\r\n\r\n\r\n\r\n input_key = [\"x1\", \"x2\"]\r\n output_key = [\"y1\", \"y2\", \"y3\"]\r\n if self.train:\r\n self.input = np.concatenate((train_dict[input_key[0]],train_dict[input_key[1]]),axis=1)\r\n self.label = np.concatenate((train_dict[output_key[0]],\r\n train_dict[output_key[1]],\r\n train_dict[output_key[2]]), axis=1)\r\n self.input = torch.from_numpy(self.input)\r\n self.label = torch.from_numpy(self.label)\r\n else:\r\n self.input = np.concatenate((test_dict[input_key[0]], test_dict[input_key[1]]), axis=1)\r\n self.label = np.concatenate((test_dict[output_key[0]],\r\n test_dict[output_key[1]],\r\n test_dict[output_key[2]]), axis=1)\r\n self.input = torch.from_numpy(self.input)\r\n self.label = torch.from_numpy(self.label)\r\n print(self.input.shape[0])\r\n print(self.label.shape[0])\r\n\r\n def __getitem__(self, item):\r\n return self.input[item], self.label[item]\r\n\r\n def __len__(self):\r\n length = self.input.shape[0]\r\n return length\r\n\r\n\r\n def data_scale(self, data, input_info):\r\n # 初始化最大值和最小值\r\n # 把最大值设置的非常小,更容易遇到比它大的去更新最大值(因为不清楚各列的最大值到底多大,有的可能10e-5就是最大值了,因此需要把初始最大值设的非常小)\r\n max_values = np.zeros(5) - 1e10\r\n # 同理,把最小值设的非常大。\r\n min_values = np.zeros(5) + 1e10\r\n\r\n # 分别更新每列的最大值和最小值\r\n for i, key in enumerate(input_info):\r\n for j in range(len(data[key])): # 遍历每一列\r\n # 更新第i列的最大值\r\n if data[key][j] > max_values[i]:\r\n max_values[i] = data[key][j]\r\n # 更新第i列的最小值\r\n if data[key][j] < min_values[i]:\r\n min_values[i] = data[key][j]\r\n\r\n # # 打印各列的最大最小值\r\n print(max_values)\r\n print(min_values)\r\n\r\n # 得到各列的最大最小值后,并应用缩放公式对各列数据进行特征缩放\r\n for i, key in enumerate(input_info):\r\n for j in range(len(data[key])):\r\n data[key][j] = (data[key][j] - min_values[i]) / (max_values[i] - min_values[i])\r\n\r\n return data\r\n\r\nif __name__ == \"__main__\":\r\n a = Folder(train=True)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# print(sh.nrows)#有效数据行数\r\n# print(sh.ncols)#有效数据列数\r\n# print(sh.cell(0,0).value)#输出第一行第一列的值\r\n# print(sh.row_values(0))#输出第一行的所有值\r\n# #将数据和标题组合成字典\r\n# print(dict(zip(sh.row_values(0),sh.row_values(1))))\r\n# #遍历excel,打印所有数据\r\n# for i in range(sh.nrows):\r\n# print(sh.row_values(i))\r\n\r\n\r\n","repo_name":"thebestYezhang/data_ans","sub_path":"data_ans/y2/y2/folders.py","file_name":"folders.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70585359524","text":"from src.MQTT.Message.Message import Message\nfrom src.MQTT.Message.Formatters.JsonFormatter import JsonFormatter\n\n\nclass MQTT:\n def __init__(self, logger, mqtt_client, publish_topic):\n self._mqtt_client = mqtt_client\n self._publish_topic = publish_topic\n self._logger = logger\n self._logger.debug('Initialising MQTT signal subscriber')\n\n def notify(self, sender=None, **kwargs):\n message = Message()\n message_formatter = JsonFormatter()\n\n for key, value in kwargs.items():\n message.add_key_value(key=key, value=value)\n\n topic = self._publish_topic\n if 'mqtt_topic_additons' in kwargs:\n topic = self._publish_topic + kwargs['mqtt_topic_additons']\n\n self._logger.debug('Publishing on topic {}'.format(topic))\n self._mqtt_client.publish(topic, message_formatter.format(message=message.get_message()))\n","repo_name":"dashford/sentinel","sub_path":"src/Signals/Subscribers/MQTT.py","file_name":"MQTT.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"652051904","text":"import torch\r\nimport torch.nn as nn\r\nimport math\r\nfrom ...parsers import get_class\r\nfrom . import quantized\r\n\r\nclass ModelConfig():\r\n ''' Contains the layers used for the model\r\n if @all is set, its value will override @conv & @act\r\n '''\r\n def __init__(self, bn=None, act=None, conv=None, fc=None, pixel_shuffle=None):\r\n self.conv = lambda *args, **kwargs: get_class(conv, [quantized, torch.nn], *args, **kwargs)\r\n\r\n # TODO: BN not supported yet -> should add instance BN in the future\r\n self.bn = nn.BatchNorm2d\r\n\r\n self.act = lambda *args, **kwargs: get_class(act, [quantized, torch.nn], *args, **kwargs)\r\n\r\n self.fc = lambda *args, **kwargs: get_class(fc, [quantized, torch.nn], *args, **kwargs)\r\n\r\n self.pixel_shuffle = lambda *args, **kwargs: get_class(pixel_shuffle, [quantized, torch.nn], *args, **kwargs)\r\n\r\n@torch.no_grad()\r\ndef init_weights(model, cfg):\r\n params = cfg[\"network\"].get(\"weight_init\", {})\r\n\r\n # This part fixes pytorch buggy default implementation\r\n act = cfg[\"network\"][\"layers\"][\"act\"][\"type\"]\r\n act = cfg[\"network\"][\"layers\"][\"act\"].get(\"qfx\", act).lower()\r\n if \"leaky\" in act:\r\n neg_slope = 0.01\r\n nonlin = \"leaky_relu\"\r\n sampling = \"kaiming\"\r\n elif \"relu\" in act:\r\n neg_slope = 0\r\n nonlin = \"relu\"\r\n sampling = \"kaiming\"\r\n elif \"tanh\" in act:\r\n neg_slope = 0\r\n nonlin = \"tanh\"\r\n sampling = \"kaiming\"\r\n else:\r\n print(f\"Activation of type {act} is not supported yet\")\r\n # Divide by sqrt(2) to support pytorch's stupid way of implementing xavier\r\n gain = nn.init.calculate_gain(nonlin, neg_slope)\r\n\r\n # Override default params\r\n gamma = params.get(\"gamma\", 1.0)\r\n momentum = params.get(\"momentum\", 0.9)\r\n sampling = params.get(\"sampling\", sampling)\r\n distribution = params.get(\"distribution\", \"normal\")\r\n fan_mode = params.get(\"fan_mode\", \"fan_in\")\r\n probas_scale = params.get(\"probas\", 1)\r\n probas_distribution = params.get(\"probas_distribution\", \"constant\")\r\n gain = params.get(\"gain\", gain)\r\n\r\n assert sampling in [\"kaiming\", \"xavier\"]\r\n assert distribution in [\"normal\", \"uniform\"]\r\n assert fan_mode in [\"fan_in\", \"fan_out\", \"fan_avg\"]\r\n\r\n def custom_weights_init(m):\r\n # This custom part does things by the book and mirrors Keras'\r\n # implementation instead of the wonky pytorch one\r\n # Support for depthwise convolutions has also been added\r\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\r\n if isinstance(m, nn.Conv2d):\r\n ksize = m.kernel_size[0] * m.kernel_size[1]\r\n ksize = ksize / m.groups\r\n fan_out = m.out_channels * ksize\r\n fan_in = m.in_channels * ksize\r\n else:\r\n fan_out = m.out_features\r\n fan_in = m.in_features\r\n fan_avg = (fan_in + fan_out)/2\r\n\r\n if sampling == \"xavier\":\r\n std = gain/math.sqrt(fan_in+fan_out)\r\n elif sampling == \"kaiming\":\r\n fan = {\r\n \"fan_in\": fan_in, \"fan_out\": fan_out, \"fan_avg\": fan_avg\r\n }[fan_mode]\r\n fan = fan # FIXME 0.95??\r\n std = gain/math.sqrt(fan)\r\n\r\n\r\n if distribution == \"normal\":\r\n m.weight.normal_(0, std)\r\n else:\r\n limit = math.sqrt(3)*std\r\n m.weight.uniform_(-limit, limit)\r\n\r\n if hasattr(m, \"probas\"):\r\n if probas_distribution==\"constant\":\r\n m.probas.fill_(probas_scale)\r\n else:\r\n nn.init.kaiming_uniform_(m.probas, a=probas_scale)\r\n\r\n elif isinstance(m, nn.BatchNorm2d):\r\n m.weight.fill_(gamma)\r\n m.momentum = momentum\r\n\r\n if hasattr(m, \"bias\") and hasattr(m.bias, \"data\"):\r\n m.bias.zero_()\r\n\r\n if \"seed\" in params:\r\n torch.manual_seed(params[\"seed\"])\r\n model.apply(custom_weights_init)\r\n\r\n # Override weights with pretrained ones if necessary\r\n pretrained_path = params.get(\"pretrained\", \"\")\r\n if pretrained_path != \"\":\r\n load_pretrained_weights(model, pretrained_path)\r\n\r\n\r\n@torch.no_grad()\r\ndef load_pretrained_weights(model, pretrained_path):\r\n pretrained_params = torch.load(pretrained_path, map_location=\"cpu\")\r\n if pretrained_path.endswith(\".ckpt\"):\r\n all_params = pretrained_params[\"state_dict\"]\r\n pretrained_params = {}\r\n for wname, w in all_params.items():\r\n if wname.endswith(\".total_ops\") or wname.endswith(\".total_params\"):\r\n continue\r\n if wname.startswith(\"model.\"):\r\n pretrained_params[wname[6:]] = w\r\n\r\n print(f\"Using pretrained weights from {pretrained_path}\")\r\n if not extensive_pretrained_match(model, pretrained_params):\r\n exit(-1)\r\n\r\n# Adds compatibility for loading old ResNet-50 pretrained weights\r\ndef extensive_pretrained_match(model, pretrained_params):\r\n for n_try in range(2):\r\n try:\r\n load_result = model.load_state_dict(pretrained_params)#, strict=True)\r\n if len(load_result.missing_keys) == 0 and len(load_result.unexpected_keys) == 0:\r\n break\r\n print(\"WARNING: missing or unexpected keys found\")\r\n print(\"Missing:\\n\", load_result.missing_keys)\r\n print(\"Unexpected:\\n\", load_result.unexpected_keys)\r\n except RuntimeError as e:\r\n print(e)\r\n if n_try > 0:\r\n return False\r\n original_params = model.state_dict()\r\n print(len(pretrained_params), len(original_params))\r\n if len(pretrained_params) != len(original_params):\r\n print(\"Not the same number of parameters, will try to match as close as possible\")\r\n\r\n if n_try > 0:\r\n return True\r\n print(\"WARNING: will try to match keys in a different fashion\")\r\n\r\n # Batchnorm compatibility layer for pytorch < 0.4.1\r\n original_keys = list(original_params.keys())\r\n pretrained_keys = list(pretrained_params.keys())\r\n if len([key for key in pretrained_keys if \".num_batches_tracked\" in key]) == 0:\r\n original_keys = [key for key in original_keys if \".num_batches_tracked\" not in key]\r\n # batchnorm.weight -> bn1.running_mean\r\n # batchnorm.bias -> bn1.running_var\r\n # batchnorm.running_mean -> bn1.weight\r\n # batchnorm.running_var -> bn1.bias\r\n def _swap_bn_keys(key, orig_key):\r\n # downsample.1 is there for very specific pytorch bullshittery\r\n if \".bn\" not in orig_key and \".batchnorm\" not in orig_key:\r\n return key\r\n if key.rsplit('.')[-1] == orig_key.rsplit('.')[-1]:\r\n return key\r\n if key.endswith(\".running_mean\"):\r\n return key.replace(\".running_mean\", \".weight\")\r\n elif key.endswith(\".running_var\"):\r\n return key.replace(\".running_var\", \".bias\")\r\n elif key.endswith(\".weight\"):\r\n return key.replace(\".weight\", \".running_mean\")\r\n elif key.endswith(\".bias\"):\r\n return key.replace(\".bias\", \".running_var\")\r\n pretrained_keys = [_swap_bn_keys(key, orig_key) for key, orig_key in zip(pretrained_keys, original_keys)]\r\n\r\n\r\n for original_key, pretrained_key in zip(original_keys, pretrained_keys):\r\n original_val = original_params[original_key]\r\n pretrained_val = pretrained_params[pretrained_key]\r\n if original_val.shape != pretrained_val.shape or original_key.rsplit('.')[-1] != pretrained_key.rsplit('.')[-1]:\r\n print(f\"Failed on key '{pretrained_key}'/'{original_key}': {pretrained_val.shape} instead of {original_val.shape}\")\r\n else:\r\n original_params[original_key] = pretrained_val\r\n pretrained_params = original_params\r\n return True","repo_name":"vanderschuea/stthree","sub_path":"stthree/models/layers/model_config.py","file_name":"model_config.py","file_ext":"py","file_size_in_byte":8093,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"} +{"seq_id":"34900669231","text":"html = '''\n \n Upload File\n

图片上传

\n
\n \n \n
\n '''\n\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST' and 'photo' in request.files:\n filename = photos.save(request.files['photo'])\n file_url = photos.url(filename)\n return html + '
'\n return render_template('upload.html')","repo_name":"akhilesh1311/The_Art_of_Seeing","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"21498451614","text":"from trackings import Trackings\nfrom utils.date import get_date_range, get_month_from_date, get_months\nfrom utils.logger import log_error\nfrom dateutil.relativedelta import relativedelta\n\nfrom pprint import pprint\nfrom time import sleep\nfrom datetime import datetime\nfrom collections import defaultdict\n\nclass MAUReport:\n def __init__(self):\n self.trackings = Trackings()\n self.rows = []\n\n def add_header(self, rows):\n updated_at = f'Atualizado em: {datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")}'\n empty_line = []\n rows.insert(0, empty_line)\n rows.insert(0, [updated_at])\n return rows\n\n def generate(self):\n print('Running the \"MAU\" report...')\n\n begin_date, end_date = get_date_range()\n months = get_months(begin_date.month, end_date.month)\n\n oneMonth = relativedelta(months = +1)\n oneDay = relativedelta(days = +1)\n for month_name, month_number in months:\n \n total_MAU = self.trackings.getMAU(begin_date, (begin_date + oneMonth) - oneDay)\n begin_date += oneMonth\n\n self.rows.append([month_name] + [total_MAU])\n\n print(f'{month_name}: {total_MAU}')\n \n self.rows = self.add_header(self.rows)\n return self.rows","repo_name":"gleisonbs/trackings-report","sub_path":"reports/mau_report.py","file_name":"mau_report.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"16282049342","text":"\r\n#Susmitha Shailesh\r\n#I pledge my honor that I have abided by the Stevens Honor System.\r\n\r\nfrom cs115 import *\r\nfrom math import *\r\nimport math\r\n\r\ndef inverse(n):\r\n '''returns the inverse of input n'''\r\n return (1/n)\r\n\r\ndef e(n):\r\n '''returns an approximation of e as a Taylor polynomial with n+1 terms'''\r\n L = range(1,n+1)\r\n L2 = map(factorial,L)\r\n L3 = map(inverse,L2)\r\n return(1+sum(L3))\r\n\r\ndef error(n):\r\n '''returns the absolute value of the difference between e and the Taylor\r\n approximation for e with n+1 terms'''\r\n taylor = e(n)\r\n actual = math.e\r\n answer = abs(taylor-actual)\r\n return answer\r\n\r\n","repo_name":"suzyshailesh/Intro-to-CS","sub_path":"LABS/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"10390513739","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 25 16:38:32 2020\n\n@author: luis.boluna@keysight.com\n\nExample code using the M8070PatternToolbox\n\nPurpose of this code is an attempt to create patterns that are created by \nIQTools where the AUTO next to sample rate is not enabled/checked. The overflow\nis aded to the pattern and based on user's length input.\n\n\"\"\"\n\nimport numpy as np\nimport M8070PatternToolbox as pat\n\n\n\nif __name__ == '__main__':\n \n# Create prbs13q per 120.5.121.2.1::\n fpoly = [13,12,2,1]\n fcoeff = [1,1,1,1]\n state = np.array([0,0,0,0,0,1,0,1,0,1,0,1,1])\n L1 = pat.pylfsr2.LFSR(fpoly=fpoly,fcoeff = fcoeff , initstate=state, verbose=False)\n #L1.info()\n L1.runFullCycle()\n \n prbs13bin = ''\n for y in enumerate(L1.seq.tolist()):\n prbs13bin += str(y[1])\n \n prbs13bin2 = prbs13bin+pat.sequence.invertBIN(prbs13bin) #spec says to repeat pattern twice so even number of symbols\n prbs13pamg = pat.sequence.gray(prbs13bin2) #graycoded pam-4\n \n \n # Save PRBS13Q to test file as M8070 ptrn file\n # prbs13ptrn = pat.Pattern.pattern()\n # prbs13ptrn.name = 'PRBS13Q'\n # prbs13ptrn.data = prbs13bin+prbs13bin\n # prbs13ptrn.length = len(prbs13bin2)\n # prbs13ptrn.properties\n #prbs13ptrn.writeptrn('newPRBS13Q.ptrn')\n \n symbols = int( input('Enter Number of Symbols you see in IQTools = ') )\n prbs_length = len(prbs13pamg)\n prbs_spillover = symbols%prbs_length\n prbs_repeat = int((symbols-prbs_spillover)/prbs_length)\n resulting_pattern = (prbs13pamg*prbs_repeat)+prbs13pamg[-prbs_spillover:]\n print(f\"\\n\\nPRBS13Q in PAM-4, gray coded {len(resulting_pattern)} symbols long:\\n{resulting_pattern}\")\n print('\\n\\n')\n \n # Save PRBS13Q to test file as M8070 ptrn file\n result = pat.Pattern.pattern()\n result.name = 'IQTools_PRBS13Q'\n ung_result = pat.sequence.ungray(resulting_pattern)\n result.data = pat.sequence.enc_bin_to_PAM4(ung_result)\n result.length = len(result.data)\n result.properties\n result.writeptrn('IQTools_PRBS13Q.ptrn')\n","repo_name":"lboluna/m8070patterntoolbox","sub_path":"CreateIQTooslPRBS13Q.py","file_name":"CreateIQTooslPRBS13Q.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"14730581260","text":"from sklearn.model_selection import ParameterSampler\n\n\nmodel_name = \"lasso\"\nparams_grid = {\n \"alpha\": [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.02, 0.05, 0.1, 0.3, 0.5, 0.8, 1.0, 2.0, 5.0, 7.0, 10.0],\n \"fit_intercept\": [True, False],\n \"normalize\": [True, False],\n \"random_state\": [123],\n \"max_iter\": [10000]\n}\n\nmodel_args = list(ParameterSampler(params_grid, n_iter=100, random_state=123))\n\nout_path = \"/home/alka/Documents/zindi_challenges/malawi_flood_prediction/random_search_results\"\nexp_name = \"lasso_1\"\n","repo_name":"AlkaSaliss/challenges","sub_path":"my_libs/configs/model/lasso_rs.py","file_name":"lasso_rs.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"74923423843","text":"from Monopoly.Cell import Cell\nfrom Monopoly.Owner import Owner\nfrom Monopoly.ClassManager.Singleton import Singleton\n\nfrom Monopoly import Card\nfrom Monopoly.Datas import Enum_buidable\n\n\n@Singleton\nclass Board(Owner):\n \"\"\"\n This class represents the board game (unique owner).\n \"\"\"\n\n def __init__(self, name, money):\n \"\"\"This method is the constructor of the class.\n\n :param name: Name of the board game.\n :type name: string\n :param money: Money possessed by the board game.\n :type money: integer\n \"\"\"\n super().__init__(name, money)\n self.name = name\n self.cell_number = 40\n self.money = money\n self.pawn = 0\n self.cell = Cell(position, name, group)\n\n def launch_cell_actions(self, pawn, owner=None, rent=None, card=None):\n \"\"\"\n This method launches different actions due to pawn position on the board.\n\n :param card: Instance of Card.\n :type card: Card\n :param pawn: The current position of the pawn.\n :type pawn: Pawn\n :param owner: The owner of the cell.\n :type owner: Owner\n :param rent: From the class rent we obtain the rent of the owned cell\n :type rent: Rent\n :return: Actions launched due to pawn position\n :rtype: void\n \"\"\"\n community_cells = [2, 17, 33]\n chance_cells = [7, 22, 36]\n special_cells = [0, 10]\n free_park_cell = 20\n jail_cell = 30\n\n # For community_cells\n if pawn.position in community_cells:\n pawn.draw_card(card.deck_community)\n # For chance_cells\n elif pawn.position in chance_cells:\n pawn.draw_card(card.deck_chance)\n # For tax cell\n elif pawn.position == 4:\n pawn.give_money(20_000, owner)\n # For income cell\n elif pawn.position == 38:\n pawn.give_money(10_000, owner)\n # For special_cells\n elif pawn.position in special_cells:\n pass\n # For free_park_cells\n elif pawn.position in free_park_cell:\n self.give_money(self.money, pawn)\n # For jail_cells\n elif pawn.position in jail_cell:\n pawn.go_to_jail()\n # For ownership_cells\n else:\n for _ in Enum_buidable:\n if owner is self.name:\n pawn.buy_ownership()\n else:\n rent(pawn, pawn.dice_result)\n","repo_name":"kecarrillo/monopoly","sub_path":"Monopoly/Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15377310880","text":"#coding:utf-8\nimport re\nimport time\nfrom random import randint\n\nfrom util.handler import BaseHandler\n\nfrom model.sms_log import SMSLog \nfrom model.account import Account\n\nfrom tasks.sms import send_sms\n\n'''\n发送短信验证码\n'''\nclass SendCode(BaseHandler):\n def post(self):\n sms_type = self.get_argument(\"sms_type\", \"\")\n phone = self.get_argument(\"phone\", \"\")\n if phone == \"\":\n return self.json_message(1, {}, \"请填写手机号\")\n\n if not re.match(\"^1[3456789]\\\\d{9}$\", phone):\n return self.json_message(1, {}, \"手机号码格式错误\")\n\n account = Account.objects(account = phone).first()\n\n if sms_type == \"signup\":\n if account:\n if account.is_actived == True:\n return self.json_message(1,{}, \"该手机号已经在注册过\")\n\n if sms_type == \"forget_password\":\n if not account:\n return self.json_message(1,{}, \"该手机号还未注册\")\n\n if account.is_actived == False:\n return self.json_message(1,{}, \"该手机号还未注册激活\")\n\n if SMSLog.objects(created_ip = self.request.remote_ip).count() > 50:\n self.json_message(1, {},\"抱歉,您当日操作过于频繁,请明日再试\")\n\n #60s 内同一手机号只能发送一次\n key = \"sms_%s_%s\" % (sms_type, phone)\n timestamp = self.redis.get(key)\n if timestamp:\n k = int(timestamp) - int(time.time())\n if k < 0:\n self.redis.delete(key)\n else:\n self.json_message(1, {},\"请您%s秒后再试。\" % k)\n return\n\n self.redis.set(key,str(int(time.time())+60))\n self.redis.expire(key, 60)\n\n\n code = randint(100000,999999)\n\n sms_log = SMSLog()\n sms_log.phone = phone\n sms_log.code = \"%d\" % code\n sms_log.send_type = sms_type\n sms_log.created_ip = self.request.remote_ip\n sms_log.save()\n \n # celery 发送短信\n send_sms.delay(phone, code, sms_type)\n\n self.json_message(0, {},\"验证码发送成功\")\n\nhandlers = [\n (r\"/auth/send_sms_code\", SendCode)\n]\n\n\n","repo_name":"hellousworld/saas","sub_path":"handler/main/sms_code.py","file_name":"sms_code.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25095447071","text":"import os\nfrom functools import partial\nfrom typing import Dict\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nfrom outside.OYT_Settings import app_settings_uploaders\nfrom outside.functions import update_combobox\nfrom outside.message_boxes import error_func, warning_func\nfrom outside.Upload import TableModels\nfrom outside.views_py import (\n SelectUploadVideos_Dialog,\n UpdateTime_Dialog,\n UploadTime_for_Video_Dialog,\n)\nfrom outside.YT.functions import get_google_login, upload_video\n\nfrom . import upload_time_max_rows\nfrom .. import TableModels as CommonTables\n\n\nclass SetPublishTimeDelegate(QtWidgets.QStyledItemDelegate):\n def __init__(self, parent=None, table=None) -> None:\n self.table = table\n super().__init__(parent)\n\n def editorEvent(self, event, model, option, index):\n if event.type() in [event.MouseButtonDblClick, event.MouseButtonDblClick,\n event.MouseButtonDblClick,\n event.MouseButtonDblClick]:\n set_upload_time_for_video(self.parent(), self.table, index.row())\n return super().editorEvent(event, model, option, index)\n\n\ndef open_upload_select_videos(parent, table):\n dialog = QtWidgets.QDialog(parent)\n dialog_settings = SelectUploadVideos_Dialog.Ui_SelectVideos_Dialog()\n dialog_settings.setupUi(dialog)\n items = ['No default account', *app_settings_uploaders.accounts.keys()]\n dialog_settings.Users_ComboBox = update_combobox(dialog_settings.Users_ComboBox, items,\n app_settings_uploaders.def_account)\n\n def select_video(next_func):\n path = ''\n try:\n path = QtWidgets.QFileDialog.getExistingDirectory(None,\n 'Select Video', '.',\n QtWidgets.QFileDialog.ShowDirsOnly)\n next_func(path=path)\n dialog.accept()\n except Exception as e:\n if not path:\n return\n error_func(f'Error.\\n {e}')\n\n def del_vids_folder():\n try:\n app_settings_uploaders.del_vids_folder()\n dialog.accept()\n except Exception as e:\n error_func(f'Error.\\n {e}')\n\n def select_folder(path):\n user = dialog_settings.Users_ComboBox.currentText()\n if user == 'No default account':\n user = ''\n for smth in os.scandir(path):\n if smth.is_dir():\n TableModels.add_video_for_uploading(table, path=os.path.abspath(smth), user=user)\n\n dialog_settings.SelectVideo_Button.clicked.connect(\n partial(select_video, partial(TableModels.add_video_for_uploading, table=table)))\n dialog_settings.SelectFolderForUser_Button.clicked.connect(partial(select_video,\n select_folder))\n dialog_settings.ChangeDefFolder_Button.clicked.connect(partial(select_video,\n change_def_folder))\n dialog_settings.SetDefFolder_Button.clicked.connect(del_vids_folder)\n dialog.exec_()\n\n\ndef scan_videos_folder(table):\n users = list(app_settings_uploaders.accounts.keys())\n for user in users:\n for vid in os.scandir(os.path.join(app_settings_uploaders.vids_folder, user)):\n if vid.is_dir():\n TableModels.add_video_for_uploading(table, os.path.abspath(vid), user)\n\n\ndef change_def_folder(path):\n if not path:\n return\n if os.path.isdir(path):\n app_settings_uploaders.add_vids_folder(path)\n else:\n error_func('This is not a directory!')\n\n\ndef google_login(login, mail, parent: QtWidgets.QDialog, table_settings):\n added = False\n if login in list(table_settings.accounts.keys()):\n error_func('This account name is already used!')\n else:\n try:\n added = get_google_login(login, mail, str(table_settings))\n parent.parent().update()\n except Exception as e:\n error_func(f'Error. \\n{e}')\n return added\n\n\ndef set_upload_time(parent, table: QtWidgets.QTableView):\n dialog = QtWidgets.QDialog(parent)\n dialog.setStyle(QtWidgets.QStyleFactory.create('Fusion'))\n dialog_settings = UpdateTime_Dialog.Ui_Upload_Time()\n dialog_settings.setupUi(dialog)\n items = ['All accounts', *app_settings_uploaders.accounts.keys()]\n dialog_settings.User_ComboBox_1 = update_combobox(dialog_settings.User_ComboBox_1, items,\n app_settings_uploaders.def_account)\n dialog_settings.User_ComboBox_1.setCurrentIndex(0)\n dialog_settings.startTimeEdit_1.setDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate().addDays(1), QtCore.QTime(0, 0, 0)))\n dialog_settings.startTimeEdit_1.setMinimumDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate(), QtCore.QTime.currentTime().addSecs(\n 60 * 60)))\n dialog_settings.startTimeEdit_1.setMaximumDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate().addYears(2),\n QtCore.QTime.currentTime().addSecs(\n 60 * 60)))\n lines_visible = [dialog_settings.label_User, dialog_settings.User_ComboBox_1]\n\n def add_line():\n font = QtGui.QFont()\n font.setFamily('Arial')\n font.setPointSize(16)\n row = dialog_settings.gridLayout.rowCount()\n if row > upload_time_max_rows:\n error_func('Too many loops!')\n return\n start = QtWidgets.QDateTimeEdit(dialog)\n start.setFont(font)\n start.setCalendarPopup(True)\n start.setObjectName(f'startTimeEdit_{row}')\n start.setDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate().addDays(1), QtCore.QTime(0, 0, 0)))\n start.setMinimumDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate(),\n QtCore.QTime.currentTime().addSecs(60 * 60)))\n start.setMaximumDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate().addYears(2),\n QtCore.QTime.currentTime().addSecs(60 * 60)))\n dialog_settings.gridLayout.addWidget(start, row, 0, 1, 1)\n setattr(dialog_settings, f'startTimeEdit_{row}', start)\n\n time_layout = QtWidgets.QHBoxLayout()\n time_layout.setObjectName(f'time_layout_{row}')\n\n days_Spin = QtWidgets.QSpinBox(dialog)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(days_Spin.sizePolicy().hasHeightForWidth())\n days_Spin.setSizePolicy(sizePolicy)\n days_Spin.setFont(font)\n days_Spin.setObjectName(f'days_Spin_{row}')\n time_layout.addWidget(days_Spin)\n setattr(dialog_settings, f'days_Spin_{row}', days_Spin)\n\n timeEdit = QtWidgets.QTimeEdit(dialog)\n timeEdit.setFont(font)\n timeEdit.setObjectName(f'timeEdit_{row}')\n time_layout.addWidget(timeEdit)\n dialog_settings.gridLayout.addLayout(time_layout, row, 1, 1, 1)\n setattr(dialog_settings, f'timeEdit_{row}', timeEdit)\n\n combo = QtWidgets.QComboBox(dialog)\n combo.setFont(font)\n combo.setObjectName(f'User_ComboBox_{row}')\n combo = update_combobox(combo,\n ['All accounts', *app_settings_uploaders.accounts.keys()],\n app_settings_uploaders.def_account)\n combo.setCurrentIndex(0)\n dialog_settings.gridLayout.addWidget(combo, row, 2, 1, 1)\n setattr(dialog_settings, f'User_ComboBox_{row}', combo)\n lines_visible.append(combo)\n\n video_spin = QtWidgets.QSpinBox(dialog)\n video_spin.setFont(font)\n video_spin.setObjectName(f'videoCount_Spin_{row}')\n dialog_settings.gridLayout.addWidget(video_spin, row, 3, 1, 1)\n setattr(dialog_settings, f'videoCount_Spin_{row}', video_spin)\n\n dialog_settings.AddLoop_Button.clicked.connect(add_line)\n\n def change_radio(chk: bool):\n for el in lines_visible:\n el.setVisible(chk)\n\n dialog_settings.Loop_radio.toggled.connect(lambda: change_radio(True))\n dialog_settings.LoopGlobal_radio.toggled.connect(lambda: change_radio(False))\n\n def ok():\n if dialog_settings.Loop_radio.isChecked():\n for row in range(1, dialog_settings.gridLayout.rowCount()):\n data = table.model().get_data()\n user = getattr(dialog_settings, f'User_ComboBox_{row}').currentText()\n if user == 'All accounts':\n user_lines = data[\n data['Publish'].isin([table.model().default_content['Publish'], ''])\n ].reset_index(drop=True)\n else:\n user_lines = data[(data['User'] == user) & (\n data['Publish'].isin([table.model().default_content['Publish'],\n '']))].reset_index(drop=True)\n if len(user_lines) == 0:\n continue\n time = getattr(dialog_settings, f'timeEdit_{row}').time()\n days = getattr(dialog_settings, f'days_Spin_{row}').value()\n upload_time = getattr(dialog_settings, f'startTimeEdit_{row}').dateTime()\n vids_count = getattr(dialog_settings, f'videoCount_Spin_{row}').value()\n if vids_count == 0:\n vids_count = len(user_lines)\n vids_count = min(vids_count, len(user_lines))\n for i in range(vids_count):\n table.model().setData(\n table.model().index(int(user_lines.loc[i, 'id']) - 1,\n list(user_lines.columns).index('Publish'),\n QtCore.QModelIndex()),\n upload_time.toString('dd.MM.yyyy hh:mm'),\n role=QtCore.Qt.DisplayRole)\n upload_time = upload_time.addDays(days)\n upload_time = upload_time.addSecs(\n time.hour() * 3600 + time.minute() * 60 + time.second())\n else:\n pass\n table.update()\n dialog.accept()\n\n dialog_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(\n dialog.reject)\n dialog_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(ok)\n dialog.exec_()\n\n\ndef set_upload_time_for_video(parent, table, video_id):\n dialog = QtWidgets.QDialog(parent)\n dialog.setStyle(QtWidgets.QStyleFactory.create('Fusion'))\n dialog_settings = UploadTime_for_Video_Dialog.Ui_Upload_Time_for_video()\n dialog_settings.setupUi(dialog)\n dialog_settings.Video_label.setText(table.model().get_data().at[video_id, 'Title'])\n dialog_settings.Day.setDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate().addDays(1), QtCore.QTime(0, 0, 0)))\n dialog_settings.Day.setMinimumDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate(), QtCore.QTime.currentTime().addSecs(60 * 60)))\n dialog_settings.Day.setMaximumDateTime(\n QtCore.QDateTime(QtCore.QDate.currentDate().addYears(2),\n QtCore.QTime.currentTime().addSecs(60 * 60)))\n\n def ok():\n date = dialog_settings.Day.date().toString('dd.MM.yyyy')\n time = dialog_settings.Time.time().toString('hh:mm')\n date = ' '.join([date, time])\n table.model()._data.at[video_id, 'Publish'] = date\n table.update()\n dialog.accept()\n\n dialog_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(\n dialog.reject)\n dialog_settings.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(ok)\n dialog.exec_()\n\n\ndef clear_upload_time(parent, table: QtWidgets.QTableView):\n if warning_func('Are you sure?\\nAll upload times will be deleted!', parent):\n table.model()._data['Publish'] = table.model().default_content['Publish']\n table.update()\n\n\ndef upload_video_to_youtube(video: Dict, driver_headless: bool,\n callback_func=None, callback_error=None, callback_info=None,\n stop_signal=None):\n try:\n if video['Publish'] == 'Not used.':\n video['Publish'] = None\n if upload_video(user=video['User'],\n title=video['Title'],\n publish=video['Publish'],\n video=video['Video'],\n description=video['Description'],\n playlist=video['Playlist'].split('\\n'),\n preview=video['Preview'],\n tags=video['Tags'],\n ends=video['Ends'],\n cards=video['Cards'],\n access=video['Access'],\n save_title=video['Save filename?'],\n driver_headless=driver_headless,\n _callback_func=callback_func,\n _callback_info=callback_info,\n _callback_error=callback_error,\n __check_stop=stop_signal):\n return True\n except Exception as e:\n if callback_error:\n callback_error(f'Error.\\n{e}')\n return False\n\n\ndef update_uploads_delegate(upload_table):\n user_combo_del = CommonTables.ComboBoxDelegate(upload_table,\n app_settings_uploaders.accounts.keys())\n upload_table.setItemDelegateForColumn(\n list(upload_table.model().get_data().columns).index('User'), user_combo_del)\n","repo_name":"Outsider-corp/OutsideYT","sub_path":"outside/Upload/dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":13810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31473173364","text":"from flask import Flask, render_template, request, send_file, send_from_directory, jsonify\nimport base64\nfrom DataCrawler import SNPCrawl\nimport os\nimport io\n\napp = Flask(__name__, template_folder='templates')\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef main():\n print(vars(request.form))\n if os.path.exists(\"SNPedia\"):\n joiner = os.path.join(os.path.curdir,\"SNPedia\")\n else:\n joiner = os.path.curdir\n filepath = os.path.join(joiner, \"templates\", 'snp_resource.html')\n return render_template('snp_resource.html')\n\n@app.route(\"/excel\", methods=['GET', 'POST'])\ndef create_file():\n content = request.form\n\n filename = content['fileName']\n filecontents = content['base64']\n filecontents = base64.b64decode(filecontents)\n\n bytesIO = io.BytesIO()\n bytesIO.write(filecontents)\n bytesIO.seek(0)\n\n return send_file(bytesIO,\n attachment_filename=filename,\n as_attachment=True)\n\n\n@app.route('/images/')\ndef send_image(path):\n return send_from_directory('images', path)\n\n\n@app.route('/js/')\ndef send_js(path):\n return send_from_directory('js', path)\n\n\n@app.route('/css/')\ndef send_css(path):\n return send_from_directory('css', path)\n\n\n@app.route(\"/api/rsids\", methods=['GET'])\ndef get_types():\n return jsonify({\"results\":dfCrawl.rsidList})\n\nif __name__ == \"__main__\":\n if os.path.exists(\"SNPedia\"):\n joiner = os.path.join(os.path.curdir,\"SNPedia\")\n else:\n joiner = os.path.curdir\n filepath = os.path.join(joiner, \"data\", 'rsidDict.json')\n snppath = os.path.join(joiner, \"data\", 'snpDict.json')\n if os.path.isfile(filepath):\n if os.path.isfile(snppath):\n dfCrawl = SNPCrawl(filepath=filepath, snppath=snppath)\n else:\n dfCrawl = SNPCrawl(filepath=filepath)\n app.run(debug=True)\n","repo_name":"mentatpsi/OSGenome","sub_path":"SNPedia/SnpApi.py","file_name":"SnpApi.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"52"} +{"seq_id":"12677721122","text":"class Colors:\n def __init__(self):\n self.colors = {\n \"reset\" : \"0\",\n \"red\" : \"31\",\n \"green\" : \"32\",\n \"yellow\" : \"33\",\n \"blue\" : \"34\",\n \"purple\" : \"35\",\n \"cyan\" : \"36\",\n \"white\" : \"37\"\n }\n\n def get(self, color):\n if (color in self.colors.keys()):\n return (self.colors[color])\n return (self.colors[\"reset\"])\n\n def build(self, color):\n return (\"\\033[{};{}m\".format(\n self.get(color),\n 1\n ))\n\nclass Logs:\n def __init__(self):\n self.colors = Colors()\n self.logs = {\n \"action\" : \"::\",\n \"success\" : \"--\",\n \"error\" : \"##\",\n \"warning\" : \"==\"\n }\n\n def action(self, message):\n self.render(\n self.colors.build(\"blue\"),\n \"{} {}{}\".format(\n self.logs[\"action\"],\n self.colors.build(\"reset\"),\n message\n )\n )\n\n def success(self, message):\n self.render(\n self.colors.build(\"cyan\"),\n \" {} {} \".format(\n self.logs[\"success\"],\n message\n )\n )\n\n def error(self, message):\n self.render(\n self.colors.build(\"red\"),\n \" {} {} \".format(\n self.logs[\"error\"],\n message\n )\n )\n\n def warning(self, message):\n self.render(\n self.colors.build(\"yellow\"),\n \"{} {} \".format(\n self.logs[\"warning\"],\n message\n )\n )\n\n def render(self, color, message):\n print(\"{}{}{}\".format(\n color,\n message,\n self.colors.build(\"reset\")\n ))\n","repo_name":"Neotoxic-off/opm","sub_path":"src/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"15572505434","text":"\"\"\"\nCode in this file is handling postgres database connection\n\"\"\"\nimport os\nfrom psycopg2 import connect, ProgrammingError\n\n\nclass DatabaseConnection:\n \"\"\"\n handle database connection: open, close\n execute passed queries\n \"\"\"\n def __init__(self, connection_config: dict):\n self.connection = connect(**connection_config)\n\n def execute_query(self, query: str, data=None) -> tuple:\n \"\"\"\n execute SQL query with given params if some\n raise critical exception on error\n \"\"\"\n result = None\n cursor = self.connection.cursor()\n if data:\n cursor.execute(query, data)\n try:\n result = cursor.fetchall()\n except ProgrammingError:\n result = []\n else:\n cursor.execute(query)\n self.connection.commit()\n cursor.close()\n return result\n\n def close(self):\n \"\"\"close database connection\"\"\"\n self.connection.close()\n\n\nclass QueriesManager:\n \"\"\"\n preload & store SQL queries\n this object is supposed to be initialized with load_queries function (see\n below)\n \"\"\"\n def __init__(self):\n self._queries = {}\n\n def add_query(self, path: str, name: str):\n \"\"\"\n load SQL queries from files, and store them\n \"\"\"\n with open(path, \"r\", encoding=\"utf-8\") as file:\n contents = file.read()\n self._queries[name] = contents\n\n def __getitem__(self, query_name: str) -> str:\n return self._queries[query_name]\n\n def __setitem__(self, query_name: str, path: str) -> str:\n \"\"\"more convenient way of adding queries\"\"\"\n return self.add_query(path, query_name)\n\n def items(self):\n \"\"\"\n convenient iterator - so object looks more like a simple dictionary\n \"\"\"\n for name, query in self._queries.items():\n yield name, query\n\n def __str__(self) -> str:\n \"\"\"pretty print the object - for debugging purposes\"\"\"\n result = []\n result.append(\"QueriesManager\")\n for query_name, query in self._queries.items():\n shortened_query = query.split()[0]\n buffer = f\"\\t{query_name}: {shortened_query}...;\"\n result.append(buffer)\n result = \"\\n\".join(result)\n return result\n\n\ndef load_queries() -> QueriesManager:\n \"\"\"add all SQL queries from `queries` directory to QueriesManager\"\"\"\n base_path = \"database/queries/\"\n manager = QueriesManager()\n for root, _, files in os.walk(base_path):\n for name in files:\n nice_name = name.split(\".\")[0]\n manager[nice_name] = os.path.join(root, name)\n return manager\n","repo_name":"mb6ockatf/kesk-bot","sub_path":"database/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"37261593545","text":"import os\nimport sys\nimport math\nimport random\nimport pickle\nimport skimage\nimport numpy as np\nimport tensorflow as tf\nimport skimage.io as imgio\nfrom datetime import datetime\nimport skimage.transform as imgtf\n\nclass dataset_dsrg():\n def __init__(self,config={}):\n self.config = config\n self.w,self.h = self.config.get(\"input_size\",(321,321))\n self.categorys = self.config.get(\"categorys\",[\"train\"])\n self.category_num = self.config.get(\"category_num\",21)\n self.main_path = self.config.get(\"main_path\",os.path.join(\"data\",\"VOCdevkit\",\"VOC2012\"))\n self.ignore_label = self.config.get(\"ignore_label\",255)\n self.default_category = self.config.get(\"default_category\",self.categorys[0])\n self.img_mean = np.ones((self.w,self.h,3))\n self.img_mean[:,:,0] *= 104.00698793\n self.img_mean[:,:,1] *= 116.66876762\n self.img_mean[:,:,2] *= 122.67891434\n\n self.data_f,self.data_len = self.get_data_f()\n\n def get_data_f(self):\n self.cues_data = pickle.load(open(\"data/localization_cues-sal.pickle\",\"rb\"),encoding=\"iso-8859-1\")\n data_f = {}\n data_len = {}\n for category in self.categorys:\n data_f[category] = {\"img\":[],\"gt\":[],\"label\":[],\"id\":[],\"id_for_slice\":[]}\n data_len[category] = 0\n for one in self.categorys:\n assert one == \"train\", \"extra category found!\"\n with open(os.path.join(\"data\",\"input_list.txt\"),\"r\") as f:\n for line in f.readlines():\n line = line.rstrip(\"\\n\")\n id_name,id_identy = line.split(\" \")\n id_name = id_name[:-4] # then id_name is like '2007_007028'\n data_f[one][\"id\"].append(id_name)\n data_f[one][\"id_for_slice\"].append(id_identy)\n data_f[one][\"img\"].append(os.path.join(self.main_path,\"JPEGImages\",\"%s.jpg\" % id_name))\n data_f[one][\"gt\"].append(os.path.join(self.main_path,\"SegmentationClassAug\",\"%s.png\" % id_name))\n \n if \"length\" in self.config:\n length = self.config[\"length\"]\n data_f[one][\"id\"] = data_f[one][\"id\"][:length]\n data_f[one][\"id_for_slice\"] = data_f[one][\"id_for_slice\"][:length]\n data_f[one][\"img\"] = data_f[one][\"img\"][:length]\n data_f[one][\"gt\"] = data_f[one][\"gt\"][:length]\n print(\"id:%s\" % str(data_f[one][\"id\"]))\n print(\"img:%s\" % str(data_f[one][\"img\"]))\n print(\"id_for_slice:%s\" % str(data_f[one][\"id_for_slice\"]))\n\n data_len[one] = len(data_f[one][\"id\"])\n\n print(\"len:%s\" % str(data_len))\n return data_f,data_len\n\n def next_batch(self,category=None,batch_size=None,epoches=-1):\n if category is None: category = self.default_category\n if batch_size is None:\n batch_size = self.config.get(\"batch_size\",1)\n dataset = tf.data.Dataset.from_tensor_slices({\n \"id\":self.data_f[category][\"id\"],\n \"id_for_slice\":self.data_f[category][\"id_for_slice\"],\n \"img_f\":self.data_f[category][\"img\"],\n \"gt_f\":self.data_f[category][\"gt\"],\n })\n def m(x):\n id_ = x[\"id\"]\n\n img_f = x[\"img_f\"]\n img_raw = tf.read_file(img_f)\n img = tf.image.decode_image(img_raw)\n gt_f = x[\"gt_f\"]\n gt_raw = tf.read_file(gt_f)\n gt = tf.image.decode_image(gt_raw)[:,:,0:1]\n\n id_for_slice = x[\"id_for_slice\"]\n def get_data(identy):\n identy = identy.decode()\n tag = np.zeros([self.category_num])\n tag[self.cues_data[\"%s_labels\" % identy]] = 1.0\n tag[0] = 1.0\n cues = np.zeros([41,41,21])\n cues_i = self.cues_data[\"%s_cues\" % identy]\n cues[cues_i[1],cues_i[2],cues_i[0]] = 1.0\n return tag.astype(np.float32),cues.astype(np.float32)\n\n tag,cues = tf.py_func(get_data,[id_for_slice],[tf.float32,tf.float32])\n img,gt,cues = self.image_preprocess(img,gt,cues,flip=True)\n\n img = tf.reshape(img,[self.h,self.w,3])\n gt = tf.reshape(gt,[self.h,self.w,1])\n tag.set_shape([21])\n cues.set_shape([41,41,21])\n\n return img,gt,tag,cues,id_\n\n dataset = dataset.repeat(epoches)\n dataset = dataset.shuffle(self.data_len[category])\n dataset = dataset.map(m)\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_initializable_iterator()\n img,gt,tag,cues,id_ = iterator.get_next()\n \n return img,gt,tag,cues,id_,iterator\n\n def image_preprocess(self,img,gt,cues,flip=False):\n #img = tf.image.resize_image_with_crop_or_pad(img, self.h, self.w)\n #gt = tf.image.resize_image_with_crop_or_pad(gt, self.h, self.w)\n img = tf.expand_dims(img,axis=0)\n img = tf.image.resize_bilinear(img,(self.h,self.w))\n img = tf.squeeze(img,axis=0)\n gt = tf.expand_dims(gt,axis=0)\n gt = tf.image.resize_nearest_neighbor(gt,(self.h,self.w))\n gt = tf.squeeze(gt,axis=0)\n\n r,g,b = tf.split(axis=2,num_or_size_splits=3,value=img)\n img = tf.cast(tf.concat([b,g,r],2),dtype=tf.float32)\n img -= self.img_mean\n\n if flip is True:\n r = tf.random_uniform([1])\n r = tf.reduce_sum(r)\n img = tf.cond(r < 0.5, lambda:tf.image.flip_left_right(img),lambda:img)\n gt = tf.cond(r < 0.5, lambda:tf.image.flip_left_right(gt),lambda:gt)\n cues = tf.cond(r < 0.5, lambda:tf.image.flip_left_right(cues),lambda:cues)\n\n return img,gt,cues\n","repo_name":"xtudbxk/DSRG-tensorflow","sub_path":"pythonlib/dataset_DSRG.py","file_name":"dataset_DSRG.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"52"} +{"seq_id":"28564753517","text":"import numpy as np\nimport torch\nimport gym\n\nfrom dfp import Transition\n\n\nclass DFPReplay:\n\n def __init__(self, capacity, ob_space, future_steps, min_horizon=4, obs_fn=None, target_fn=None, device=None):\n assert isinstance(ob_space, gym.spaces.Dict)\n assert 'meas' in ob_space.spaces\n\n self.capacity = capacity\n self.ob_space = ob_space\n self.future_steps = future_steps\n self.min_horizon = min_horizon\n self.obs_fn = obs_fn or (lambda x: x)\n self.target_fn = target_fn or (lambda x: x)\n self.device = device\n\n # dictionary observations (images, measurements)\n self._obs = {}\n for name, space in ob_space.spaces.items():\n self._obs[name] = np.empty(shape=(capacity, *space.shape), dtype=space.dtype)\n\n self._actions = np.empty(capacity, dtype=np.int64)\n self._rewards = np.empty(capacity, dtype=np.float32)\n self._terminals = np.empty(capacity, dtype=np.float32)\n\n # book keeping\n self._load = 0\n self._pointer = 0\n self._current_episode = 0\n self._episode_idx = np.empty(capacity, dtype=np.int64)\n\n def push(self, transition: Transition):\n\n for k, v in transition.obs.items():\n self._obs[k][self._pointer] = v\n\n self._actions[self._pointer] = transition.action\n self._rewards[self._pointer] = transition.reward\n self._terminals[self._pointer] = transition.terminal\n\n self._episode_idx[self._pointer] = self._current_episode\n\n # NOTE: If episodes are terminated early (before done is True),\n # training data will be incorrect, namely, future time steps\n # from different episode will be seen as from the same episode.\n if transition.terminal:\n self._current_episode += 1\n\n self._pointer = (self._pointer + 1) % self.capacity\n self._load = min(self._load + 1, self.capacity)\n\n def sample(self, batch_size):\n\n valid_idx = self._sample_valid_indices(batch_size)\n\n observations = {k: self._obs[k][valid_idx] for k in self.ob_space.spaces}\n actions = self._actions[valid_idx]\n targets, target_masks = self._make_targets(valid_idx)\n\n observations = self.obs_fn(observations)\n targets = self.target_fn(targets)\n\n actions = torch.from_numpy(actions).to(self.device)\n target_masks = torch.from_numpy(target_masks).to(self.device)\n\n return observations, actions, targets, target_masks\n\n def _sample_valid_indices(self, batch_size):\n \"\"\" Sample transitions with enough future time steps \"\"\"\n\n valid_idx = []\n num_valid_idx = 0\n while num_valid_idx < batch_size:\n\n # sample random indices and get their episode ids\n idx = np.random.randint(self._load, size=batch_size)\n episode_idx = self._episode_idx[idx]\n\n # consider the indices at t + min_horizon\n min_horizon_idx = (idx + self.min_horizon) % self.capacity\n min_horizon_episode_idx = self._episode_idx[min_horizon_idx]\n\n # if episode_id, is the same in the future, the sample is valid\n valid_samples_mask = episode_idx == min_horizon_episode_idx\n valid_samples = idx[valid_samples_mask]\n\n valid_idx.append(valid_samples)\n num_valid_idx += len(valid_samples)\n\n valid_idx = np.concatenate(valid_idx)\n\n return valid_idx[:batch_size]\n\n def _make_targets(self, items):\n\n # [B, 1]\n episode_idx = self._episode_idx[items].reshape(-1, 1)\n\n measurements = self._obs['meas']\n dim_meas = measurements.shape[1]\n\n # [B, Dm]\n meas_t = measurements[items]\n\n # [B, T]\n future_items = items.reshape(-1, 1) + self.future_steps\n future_items = future_items % self.capacity\n future_episode_idx = self._episode_idx[future_items]\n valid_times_mask = future_episode_idx == episode_idx\n\n # [B, T, Dm]\n future_meas = measurements[future_items]\n meas_diffs = future_meas - np.expand_dims(meas_t, 1)\n\n # [B, T x Dm]\n B = meas_diffs.shape[0]\n targets = meas_diffs.reshape(B, -1)\n\n # [B, T] --> [B, T x Dm]\n valid_target_mask = np.repeat(valid_times_mask, dim_meas, 1)\n\n return targets, valid_target_mask\n\n def _compute_target_scale(self):\n measurements = self._obs['meas']\n meas_std = np.nanstd(measurements, 0)\n meas_std[meas_std == 0] = 1 # avoid divisions by zero\n target_scale = np.tile(meas_std, len(self.future_steps)) # T x Dm\n return target_scale\n\n def __len__(self):\n return self._load\n\n def is_full(self):\n return self._load == self.capacity\n","repo_name":"johny-c/dfp","sub_path":"dfp/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"27427198162","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#Library\nimport sys\nimport threading\nimport traceback\nimport numpy as np\nimport pandas as pd\nimport pyqtgraph as pg\nimport load_data as ld\nimport tabledialog as _tabledialog\nfrom sklearn.cluster import KMeans\nfrom PyQt5 import QtWidgets, QtCore\nfrom matplotlib.figure import Figure as _Figure\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvasQTAgg as _FigureCanvas,\n NavigationToolbar2QT as _Toolbar)\nfrom PyQt5.QtWidgets import QMessageBox as QMessageBox\n\n#Interface\nfrom main_screen import *\nfrom numpy.f2py.auxfuncs import isarray, isinteger\n\nclass PlotDialog(QtWidgets.QDialog):\n \"\"\"Matplotlib plot dialog.\"\"\"\n\n def __init__(self, parent=None):\n \"\"\"Add figure canvas to layout.\"\"\"\n super().__init__(parent)\n\n self.figure = _Figure()\n self.canvas = _FigureCanvas(self.figure)\n self.ax = self.figure.add_subplot(111)\n\n _layout = QtWidgets.QVBoxLayout()\n _layout.addWidget(self.canvas)\n self.toolbar = _Toolbar(self.canvas, self)\n _layout.addWidget(self.toolbar)\n self.setLayout(_layout)\n\n def updatePlot(self):\n \"\"\"Update plot.\"\"\"\n self.canvas.draw()\n\n def show(self):\n \"\"\"Show dialog.\"\"\"\n self.updatePlot()\n super().show()\n\nclass ApplicationWindow(QtWidgets.QWidget):\n \"\"\"Machine Learning for Magnetic Measurement user interface\"\"\"\n def __init__(self, parent=None):\n super(ApplicationWindow, self).__init__(parent)\n\n self.ui = Ui_Machine_Learn_Interface()\n self.ui.setupUi(self)\n self.plot_dialog = PlotDialog()\n self.flag = False\n self.lastClicked = []\n self.dictionary()\n self.signals()\n \n def signals(self):\n \"\"\"Connects UI signals and functions.\"\"\"\n self.ui.pb_openfiles.clicked.connect(self.master_data)\n self.ui.pb_kmeans.clicked.connect(self.k_means)\n self.ui.cb_x_values.currentIndexChanged.connect(self.change_x_graphs_values)\n self.ui.cb_x_n_order.currentIndexChanged.connect(self.change_x_graphs_values)\n self.ui.cb_y_values.currentIndexChanged.connect(self.change_y_graphs_values)\n self.ui.cb_y_n_order.currentIndexChanged.connect(self.change_y_graphs_values)\n self.ui.pb_viewtable.clicked.connect(self.screen_table)\n self.ui.pb_cluster_hint.clicked.connect(self.cluster_hint)\n \n def master_data(self):\n \"\"\"Data manipulate from database\"\"\"\n try:\n self.data_in = ld.Main_Script()\n _archives = self.data_in.load_files()\n if _archives:\n self.data_in.DataFile()\n if self.data_in is not None:\n if (self.ui.cb_x_values.count() == 0) and (self.ui.cb_y_values.count() == 0): \n self.combo_box_x_value()\n self.combo_box_y_value()\n self.get_offsets()\n self.get_roll()\n self.ui.pb_kmeans.setEnabled(True)\n self.magnet_name()\n QtWidgets.QMessageBox.information(self,\n 'Info','Files successfully updated',QtWidgets.QMessageBox.Ok)\n else:\n return\n QtWidgets.QApplication.processEvents()\n else:\n raise\n except:\n QtWidgets.QMessageBox.critical(self,\n 'Critical','Files do not loaded.',QtWidgets.QMessageBox.Ok)\n return\n \n def get_offsets(self):\n \"\"\" Pick up the offsets values from data\"\"\"\n self.data_in._calc_offsets()\n \n def get_roll(self):\n \"\"\"Pick up the roll angle\"\"\"\n self.data_in._set_roll() \n\n def combo_box_x_value(self):\n \"\"\"Fill the X values combo box after load data\"\"\"\n self.ui.cb_x_values.addItems(\n [s.replace(\"(T/m^n-2)\", \"\").strip() for s in self.data_in.Data[0].columns_names])\n self.ui.cb_x_values.addItems([\"main currents\", \"X offset\", \"roll angle\"])\n \n def combo_box_y_value(self):\n \"\"\"Fill the Y values combo box after load data\"\"\"\n self.ui.cb_y_values.addItems(\n [s.replace(\"(T/m^n-2)\", \"\").strip() for s in self.data_in.Data[0].columns_names])\n self.ui.cb_y_values.addItems([\"main currents\", \"Y offset\", \"roll angle\"])\n \n def dictionary(self):\n self._dict = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5,\n '6': 6, '7': 7, '8': 8, '9': 9, '10': 10,\n '11': 11, '12': 12}\n \n def change_x_n_order(self, i, idx_label):\n _x_order = self.ui.cb_x_n_order.currentIndex()\n self.var_x = np.append(self.var_x,\n self.data_in.Data[i].multipoles[_x_order][idx_label])\n# print('harmonic X: ', _x_order)\n \n def change_y_n_order(self, i, idx_label): \n _y_order = self.ui.cb_y_n_order.currentIndex()\n self.var_y = np.append(self.var_y,\n self.data_in.Data[i].multipoles[_y_order][idx_label])\n# print('harmonic Y: ', _y_order)\n \n def change_x_graphs_values(self):\n try:\n self.var_x = np.array([])\n idx_label = self.ui.cb_x_values.currentIndex()\n for i in range(len(self.data_in.files)):\n if idx_label == 13:\n self.ui.cb_x_n_order.setEnabled(False)\n self.var_x = np.append(self.var_x, self.data_in.Data[i].main_current)\n elif idx_label == 14:\n self.ui.cb_x_n_order.setEnabled(False)\n self.var_x = np.append(self.var_x, self.data_in.Data[i].offset_x)\n elif idx_label == 15:\n self.ui.cb_x_n_order.setEnabled(False)\n self.var_x = np.append(self.var_x, self.data_in.Data[i].roll)\n elif idx_label == 0:\n self.ui.cb_x_n_order.setEnabled(False)\n pass\n elif str(idx_label) in self._dict:\n self.ui.cb_x_n_order.setEnabled(True)\n self.change_x_n_order(i, idx_label)\n# print(self.var_x)\n \n except:\n traceback.print_exc(file=sys.stdout) \n \n def change_y_graphs_values(self):\n try:\n self.var_y = np.array([])\n idx_label = self.ui.cb_y_values.currentIndex()\n for i in range(len(self.data_in.files)):\n if idx_label == 0:\n pass\n elif idx_label == 13:\n self.ui.cb_y_n_order.setEnabled(False)\n self.var_y = np.append(self.var_y, self.data_in.Data[i].main_current)\n elif idx_label == 14:\n self.ui.cb_y_n_order.setEnabled(False)\n self.var_y = np.append(self.var_y, self.data_in.Data[i].offset_y)\n elif idx_label == 15:\n self.ui.cb_y_n_order.setEnabled(False)\n self.var_y = np.append(self.var_y, self.data_in.Data[i].roll)\n elif str(idx_label) in self._dict:\n self.ui.cb_y_n_order.setEnabled(True)\n self.change_y_n_order(i, idx_label) \n# print(self.var_y)\n except:\n traceback.print_exc(file=sys.stdout)\n \n def data_frame_manager(self): \n if (len(self.var_x)) and (len(self.var_y)) > 0:\n self.DF = {'x': self.var_x,\n 'y': self.var_y}\n self.DF = pd.DataFrame(self.DF, columns=['x', 'y'])\n \n def k_means(self):\n \"\"\"Method for clustering data with k-means\"\"\"\n try:\n self.data_frame_manager()\n \n _n_cluster = self.ui.sb_cluster_number.value()\n \n if len(self.DF.columns) > 2:\n self.DF.drop(['magnet', 'class'], axis=1, inplace=True) \n \n #Applying kmeans functions\n _kmeans = KMeans(n_clusters=_n_cluster).fit(self.DF)\n \n #Predicts\n _predicts = _kmeans.labels_\n \n #Centroids\n _centroids = _kmeans.cluster_centers_\n \n if len(self.DF.columns) == 2:\n _names = np.array([])\n _prev = np.array([])\n for j in range(len(self.data_in.files)):\n _names = np.append(_names, self.data_in.Data[j].magnet_name)\n _prev = np.append(_prev, _predicts[j])\n self.DF['magnet'] = pd.Series(_names, index=self.DF.index)\n self.DF['class'] = pd.Series(_prev, index=self.DF.index)\n# print(self.DF.head())\n \n self.ui.pb_viewtable.setEnabled(True)\n self.plot_view(self.DF, _centroids)\n except:\n traceback.print_exc(file=sys.stdout)\n \n def filter_class(self, df):#, n):\n '''**Implementar para qualquer númaero de cluster. Dica: Tentar usar dicionários**\n for i in range (n): #n = number of clusters\n _class[i]...\n '''\n try:\n _class_0, _class_0_x, _class_0_y = 0,0,0\n _class_1, _class_1_x, _class_1_y = 0,0,0\n _class_2, _class_2_x, _class_2_y = 0,0,0\n \n #Filter spots class == 0\n _class_0 = df.loc[(df['class'] == 0)]\n _class_0_x = _class_0.x.values\n _class_0_y = _class_0.y.values\n \n #Filter spots class == 1\n _class_1 = df.loc[(df['class'] == 1)]\n _class_1_x = _class_1.x.values\n _class_1_y = _class_1.y.values\n \n #Filter spots class == 2\n _class_2 = df.loc[(df['class'] == 2)]\n _class_2_x = _class_2.x.values\n _class_2_y = _class_2.y.values\n \n return _class_0_x, _class_0_y, _class_1_x, _class_1_y, _class_2_x, _class_2_y\n except:\n traceback.print_exc(file=sys.stdout)\n \n def plot_view(self, df, center):\n \"\"\"Plotting graphs in Graphics View QWidget\"\"\"\n try: \n #Clear screen\n self.ui.graphicsView.clear()\n \n #Closing previous legend\n if self.flag:\n self.ui.graphicsView.plotItem.legend.close()\n \n #Creating the new legend\n self.ui.graphicsView.plotItem.addLegend()\n \n _vars = self.filter_class(df)\n \n _s1 = pg.ScatterPlotItem(_vars[0],\n _vars[1],\n size=10,\n pen=pg.mkPen({'color': \"F4425F\", 'width': 1}), #Red\n brush=pg.mkBrush(244, 115, 136, 120),\n name='class 0') # Class = 0\n \n _s2 = pg.ScatterPlotItem(_vars[2],\n _vars[3],\n size=10,\n pen=pg.mkPen({'color': \"1003BC\", 'width': 1}), #Blue\n brush=pg.mkBrush(49, 104, 224, 120),\n name='class 1') # Class = 1\n \n _s3 = pg.ScatterPlotItem(_vars[4],\n _vars[5],\n size=10,\n pen=pg.mkPen({'color': \"DD9D1C\", 'width': 1}), #Yellow\n brush=pg.mkBrush(237, 192, 101, 120),\n name='class 2') # Class = 2\n #Adding centers points\n _s4 = pg.ScatterPlotItem(center[:, 0],\n center[:, 1],\n symbol='d',\n size=12,\n pen=pg.mkPen(None),\n brush='g') # Centers\n\n self.ui.graphicsView.plotItem.setLabel('left', self.ui.cb_y_values.currentText())\n self.ui.graphicsView.plotItem.setLabel('bottom', self.ui.cb_x_values.currentText())\n self.ui.graphicsView.plotItem.showGrid(x=True, y=True, alpha=0.2)\n self.ui.graphicsView.addItem(_s1)\n self.ui.graphicsView.addItem(_s2)\n self.ui.graphicsView.addItem(_s3)\n self.ui.graphicsView.addItem(_s4)\n self.ui.graphicsView.plotItem.legend.addItem(_s1, ' class 0')\n self.ui.graphicsView.plotItem.legend.addItem(_s2, ' class 1')\n self.ui.graphicsView.plotItem.legend.addItem(_s3, ' class 2')\n self.ui.graphicsView.plotItem.legend.addItem(_s4, ' centroids')\n _s1.sigClicked.connect(self.clicked)\n _s2.sigClicked.connect(self.clicked)\n _s3.sigClicked.connect(self.clicked)\n self.flag = True\n QtWidgets.QApplication.processEvents()\n except:\n traceback.print_exc(file=sys.stdout)\n \n def counter(self):\n \"\"\"Count the number of elements in each cluster\"\"\"\n pass\n \n def magnet_name(self):\n _magnet = self.data_in.Data[0].magnet_name[:3]\n return self.ui.lb_magnt_name.setText(_magnet)\n \n def cluster_hint(self):\n \"\"\"Ideal determination of number of clusters (elbow method)\"\"\"\n try: \n wcss = [] \n for i in range(1, 11):\n kmeans = KMeans(n_clusters = i, init = 'random')\n if len(self.DF.columns) > 2:\n _DF_for_hint = self.DF.drop(['magnet', 'class'], axis=1)\n kmeans.fit(_DF_for_hint)\n else:\n kmeans.fit(self.DF)\n wcss.append(kmeans.inertia_) \n fig = self.plot_dialog.figure\n ax = self.plot_dialog.ax\n ax.clear()\n ax.plot(np.arange(1, 11), wcss)\n ax.set_xlabel('Number of Clusters')\n ax.set_ylabel('Within cluster sum of squares (WSS)')\n ax.set_title('Elbow Method')\n ax.grid('on', alpha=0.3)\n fig.tight_layout()\n self.plot_dialog.show()\n except:\n QtWidgets.QMessageBox.information(self,'Info',\n 'Please, select X or Y values and click in K-Means button.',QtWidgets.QMessageBox.Ok)\n return\n \n def screen_table(self):\n \"\"\"Create new screen with table.\"\"\"\n try:\n dialog_table = _tabledialog.TableDialog(table_df=self.DF)\n dialog_table.exec_()\n\n except Exception:\n QtWidgets.QMessageBox.critical(\n self, 'Failure', 'Failed to open table.', _QMessageBox.Ok)\n \n def clicked(self, plot, points):\n \"\"\"Make all plots clickable\"\"\"\n try:\n #global lastClicked\n for p in self.lastClicked:\n p.resetPen()\n print(\"clicked points: \", points[0].pos())\n for p in points:\n p.setPen('b', width=2)\n self.lastClicked = points\n except:\n traceback.print_exc(file=sys.stdout)\n return \n \nclass main(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.start()\n\n def run(self):\n # Starts Graphic Interface\n self.App = QtWidgets.QApplication(sys.argv)\n self.myapp = ApplicationWindow()\n self.myapp.show()\n self.App.exec_()\n \na = main()\n","repo_name":"LucasIB/Machine-Learning-for-Rotating-Coil-Magnetic-Measurements","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15789,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"17534053529","text":"\n# coding: utf-8\n\nimport DTW_song_dongKa_sampling as DTW\nimport matplotlib.pyplot as plt\nimport gc\nimport numpy as np\n\n#查詢data organize table (母)後一個一個執行 DTW_song_dongKa_sampling並且串成train set\n\nDir = 'motif/aaaaa/song1/order1/don'\nsample_order1 = DTW.Main_Execure(Dir)\ntrain_set = sample_order1\n\n#AAE\n\ndef create_lstm_vae_train(input_dim, \ntimesteps, \nbatch_size, \nintermediate_dim, \nlatent_dim,\nepsilon_std=1.,\nfirst_second=False \n):\n\n \"\"\"\n Creates an LSTM Variational Autoencoder (VAE). Returns VAE, Encoder, Generator. \n\n # Arguments\n input_dim: int.\n timesteps: int, input timestep dimension.\n batch_size: int.\n intermediate_dim: int, output shape of LSTM. \n latent_dim: int, latent z-layer shape. \n epsilon_std: float, z-layer sigma.\n\n\n # References\n - [Building Autoencoders in Keras](https://blog.keras.io/building-autoencoders-in-keras.html)\n - [Generating sentences from a continuous space](https://arxiv.org/abs/1511.06349)\n \"\"\"\n x = Input(shape=(timesteps, input_dim,))\n if (first_second==False):\n # LSTM encoding\n h = LSTM(intermediate_dim)(x)\n\n # VAE Z layer\n z_mean = Dense(latent_dim)(h)\n z_log_sigma = Dense(latent_dim)(h)\n elif(first_second==True): #fix weights for encoder\n # LSTM encoding\n h = LSTM(intermediate_dim)(x)\n\n # VAE Z layer\n z_mean = Dense(latent_dim)(h)\n z_log_sigma = Dense(latent_dim)(h)\n\n def sampling(args):\n z_mean, z_log_sigma = args\n epsilon = K.random_normal(shape=(batch_size, latent_dim),\n mean=0., stddev=epsilon_std)\n return z_mean + z_log_sigma * epsilon\n\n # note that \"output_shape\" isn't necessary with the TensorFlow backend\n # so you could write `Lambda(sampling)([z_mean, z_log_sigma])`\n z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_sigma])\n\n # decoded LSTM layer\n decoder_h = LSTM(intermediate_dim, return_sequences=True)\n decoder_mean = LSTM(input_dim, return_sequences=True)\n\n h_decoded = RepeatVector(timesteps)(z)\n h_decoded = decoder_h(h_decoded)\n\n # decoded layer\n x_decoded_mean = decoder_mean(h_decoded)\n\n # end-to-end autoencoder\n vae = Model(x, x_decoded_mean)\n\n # encoder, from inputs to latent space\n encoder = Model(x, z_mean)\n\n if(first_second ==True):\n encoder.load_weights('encoder.h5')\n\n # generator, from latent space to reconstructed inputs\n decoder_input = Input(shape=(latent_dim,))\n\n _h_decoded = RepeatVector(timesteps)(decoder_input)\n _h_decoded = decoder_h(_h_decoded)\n\n _x_decoded_mean = decoder_mean(_h_decoded)\n generator = Model(decoder_input, _x_decoded_mean)\n\n def vae_loss(x, x_decoded_mean):\n xent_loss = objectives.mse(x, x_decoded_mean)\n kl_loss = - 0.5 * K.mean(1 + z_log_sigma - K.square(z_mean) - K.exp(z_log_sigma))\n loss = xent_loss + kl_loss\n return loss\n\n vae.compile(optimizer='rmsprop', loss=vae_loss)\n\n return vae, encoder, generator\n\n# training\nimport tensorflow as tf\nimport keras\nfrom keras import backend as K\nfrom keras.models import Sequential, Model\nfrom keras.layers.core import Flatten, Dense, Dropout, Lambda\nfrom keras.optimizers import SGD, RMSprop, Adam\nfrom keras import objectives\nfrom keras.constraints import non_neg\nfrom sklearn.preprocessing import MinMaxScaler\nfrom lstm_vae import create_lstm_vae\nfrom keras.callbacks import History \nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import Input, LSTM, RepeatVector\nfrom keras.backend.tensorflow_backend import set_session\n\ndef conservative_train_AAE(data1,data2=[]):\n \n config = tf.ConfigProto()\n config.gpu_options.allocator_type = 'BFC' #A \"Best-fit with coalescing\" algorithm, simplified from a version of dlmalloc.\n config.gpu_options.per_process_gpu_memory_fraction = 0.1\n config.gpu_options.allow_growth = True\n set_session(tf.Session(config=config)) \n\n #traning\n if __name__ == \"__main__\":\n x = data1\n y = data2\n \n \n \n if(y!=[]):\n consercative_or_not = True\n else:\n consercative_or_not = False\n \n if (consercative_or_not ==True):\n xY = np.vstack((x,y))\n \n input_dim = xY.shape[-1] \n print (input_dim)\n timesteps = xY.shape[1]\n print (timesteps)\n batch_size = 1\n \n \n vae, enc, gen = create_lstm_vae_train(input_dim, \n timesteps, \n batch_size, \n intermediate_dim=64,\n latent_dim=5,\n epsilon_std=1.,\n first_second= True\n )\n \n early_stopping = EarlyStopping(monitor='loss', patience=100, verbose=2)\n vae.fit(xY, xY, epochs=10000,callbacks=[early_stopping]) \n enc.save_weights('encoder.h5')\n preds = vae.predict(xY,batch_size=batch_size)\n \n else:\n input_dim = x.shape[-1] # 13\n print (input_dim)\n timesteps = x.shape[1] # 3\n print (timesteps)\n batch_size = 1\n \n \n vae, enc, gen = create_lstm_vae_train(input_dim, \n timesteps, \n batch_size, \n intermediate_dim=64,\n latent_dim=5,\n epsilon_std=1.)\n\n early_stopping = EarlyStopping(monitor='loss', patience=50, verbose=2)\n vae.fit(x, x, epochs=10000,callbacks=[early_stopping])\n enc.save_weights('encoder.h5')\n preds = vae.predict(x,batch_size=batch_size)\n return vae, enc, gen\n\n gc.collect()\n\n#查詢data organize table (tmp)後一個一個執行 DTW_song_dongKa_sampling並且串成train set\n\n#train(母)串 train(子), then train\nvae, enc, gen = conservative_train_AAE(data1 = train_set)\nprint (' train data finish!')\ngc.collect()\n\n#雷達圖 \ndef Rader(sample):\n Latent_code = enc.predict(sample)\n samplesrar = np.interp(Latent_code, (Latent_code.min(), Latent_code.max()), (50, 100)) #Rescale to 0-100\n# 中文和負號的正常顯示\n plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'\n plt.rcParams['axes.unicode_minus'] = False\n\n # 使用ggplot的繪圖風格\n plt.style.use('ggplot')\n\n # 構造數據\n values = samplesrar[0]\n\n\n\n feature = ['feature01','feature02','feature03','feature04','feature05']\n\n N = len(values)\n # 設置雷達圖的角度,用於平分切開一個圓面\n angles=np.linspace(0, 2*np.pi, N, endpoint=False)\n # 為了使雷達圖一圈封閉起來,需要下面的步驟\n values=np.concatenate((values,[values[0]]))\n\n angles=np.concatenate((angles,[angles[0]]))\n\n # 繪圖\n fig=plt.figure()\n ax = fig.add_subplot(111, polar=True)\n # 繪製折線圖\n ax.plot(angles, values, 'o-', linewidth=0.2, label = 'sample')\n # 填充顏色\n ax.fill(angles, values, alpha=0.25)\n # 繪製第二條折線圖\n\n\n # 添加每個特徵的標籤\n ax.set_thetagrids(angles * 180/np.pi, feature)\n # 設置雷達圖的範圍\n ax.set_ylim(0,100)\n # 添加標題\n plt.title('Radar_subject 02')\n\n # 添加網格線\n ax.grid(True)\n # 設置圖例\n plt.legend(loc = 'best')\n # 顯示圖形\n plt.savefig('Radar.png')\n plt.show()\n\nRader(sample_order1)\n\n","repo_name":"ts03408751/Taiko-AAE","sub_path":".ipynb_checkpoints/AAE_Main_test_Gui-checkpoint.py","file_name":"AAE_Main_test_Gui-checkpoint.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"2213884739","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom model.cell import FAGRUCell, SmoothSparseUnit\nimport numpy as np\nimport math\nimport pywt\nfrom .STFE import *\nfrom .LTFE import *\n\nclass Seq2SeqAttrs:\n def __init__(self, args):\n #self.adj_mx = adj_mx\n self.max_diffusion_step = args.max_diffusion_step\n self.cl_decay_steps = args.cl_decay_steps\n self.filter_type = args.filter_type\n self.num_nodes = args.num_nodes\n self.num_rnn_layers = args.num_rnn_layers\n self.rnn_units = args.rnn_units\n self.output_dim = args.output_dim\n self.hidden_state_size = self.num_nodes * self.rnn_units\n\n\nclass EncoderModel(nn.Module, Seq2SeqAttrs):\n def __init__(self, args):\n nn.Module.__init__(self)\n Seq2SeqAttrs.__init__(self, args)\n self.input_dim = args.input_dim\n self.output_dim = args.output_dim\n self.seq_len = args.seq_len # for the encoder\n self.device = args.device\n self.fagru_layers = nn.ModuleList(\n [FAGRUCell(self.rnn_units, self.max_diffusion_step, self.num_nodes,\n filter_type=self.filter_type, device=self.device) for _ in range(self.num_rnn_layers)])\n\n\n def forward(self, inputs, adj, hidden_state=None):\n \"\"\"\n Encoder forward pass.\n :param inputs: shape (batch_size, self.num_nodes * self.input_dim)\n :param hidden_state: (num_layers, batch_size, self.hidden_state_size)\n optional, zeros if not provided\n :return: output: # shape (batch_size, self.hidden_state_size)\n hidden_state # shape (num_layers, batch_size, self.hidden_state_size)\n (lower indices mean lower layers)\n \"\"\"\n batch_size, _ = inputs.size()\n if hidden_state is None:\n hidden_state = torch.zeros((self.num_rnn_layers, batch_size, self.hidden_state_size),\n device=self.device)\n hidden_states = []\n output = inputs\n for layer_num, fagru_layer in enumerate(self.fagru_layers):\n next_hidden_state = fagru_layer(output, hidden_state[layer_num], adj)\n hidden_states.append(next_hidden_state)\n output = next_hidden_state\n\n return output, torch.stack(hidden_states) # runs in O(num_layers) so not too slow\n\n\nclass DecoderModel(nn.Module, Seq2SeqAttrs):\n def __init__(self, args):\n # super().__init__(is_training, adj_mx, **model_kwargs)\n nn.Module.__init__(self)\n Seq2SeqAttrs.__init__(self, args)\n self.output_dim = args.output_dim\n self.horizon = args.horizon # for the decoder\n self.projection_layer = nn.Linear(self.rnn_units, self.output_dim)\n self.device = args.device\n self.fagru_layers = nn.ModuleList(\n [FAGRUCell(self.rnn_units, self.max_diffusion_step, self.num_nodes,\n filter_type=self.filter_type, device=self.device) for _ in range(self.num_rnn_layers)])\n\n def forward(self, inputs, adj, hidden_state=None):\n \"\"\"\n :param inputs: shape (batch_size, self.num_nodes * self.output_dim)\n :param hidden_state: (num_layers, batch_size, self.hidden_state_size)\n optional, zeros if not provided\n :return: output: # shape (batch_size, self.num_nodes * self.output_dim)\n hidden_state # shape (num_layers, batch_size, self.hidden_state_size)\n (lower indices mean lower layers)\n \"\"\"\n hidden_states = []\n output = inputs\n for layer_num, fagru_layer in enumerate(self.fagru_layers):\n next_hidden_state = fagru_layer(output, hidden_state[layer_num], adj)\n hidden_states.append(next_hidden_state)\n output = next_hidden_state\n\n projected = self.projection_layer(output.view(-1, self.rnn_units))\n output = projected.view(-1, self.num_nodes * self.output_dim)\n\n return output, torch.stack(hidden_states)\n\n\nclass FCDNetModel(nn.Module, Seq2SeqAttrs):\n def __init__(self, node_feas, logger, args):\n super().__init__()\n Seq2SeqAttrs.__init__(self, args)\n self.args = args\n self.encoder_model = EncoderModel(args)\n self.decoder_model = DecoderModel(args)\n self.cl_decay_steps = args.cl_decay_steps\n self.use_curriculum_learning = args.use_curriculum_learning\n self._logger = logger\n self.embedding_size = args.embedding_size\n self.seq_len = args.seq_len\n self.feas_dim = args.feas_dim\n self.input_dim = args.input_dim\n self.kernel_size = args.kernel_size\n self.batch_size= args.batch_size\n self.freq = args.freq\n self.requires_graph = args.requires_graph\n self.level = args.level\n self.num_nodes = args.num_nodes\n self.device = args.device\n self.graphs = self.requires_graph\n self.instant_forecasting = Instant_forecasting(args)\n self.output_dim = args.output_dim\n self.dataset = args.dataset\n self.epis = []\n for index in range(self.requires_graph):\n self.epis.append(nn.Parameter(torch.tensor([0.30], device=self.device), requires_grad=True))\n self.ShortAdj_generator = ShortAdj_generator(args, node_feas)\n self.LongAdj_generator = LongAdj_generator(args, node_feas)\n self.lambdax = torch.nn.Parameter(torch.tensor([0.30], device=self.device), requires_grad=True)\n self.beta = torch.nn.Parameter(torch.tensor([0.10]), requires_grad=True).to(self.device)\n\n def _compute_sampling_threshold(self, batches_seen):\n return self.cl_decay_steps / (\n self.cl_decay_steps + np.exp(batches_seen / self.cl_decay_steps))\n\n def encoder(self, inputs, adj):\n \"\"\"\n Encoder forward pass\n :param inputs: shape (seq_len, batch_size, num_sensor * input_dim)\n :return: encoder_hidden_state: (num_layers, batch_size, self.hidden_state_size)\n \"\"\"\n encoder_hidden_state = None\n for t in range(self.args.seq_len):\n _, encoder_hidden_state = self.encoder_model(inputs[t], adj, encoder_hidden_state)\n\n return encoder_hidden_state\n\n def decoder(self, encoder_hidden_state, adj, labels=None, batches_seen=None):\n \"\"\"\n Decoder forward pass\n :param encoder_hidden_state: (num_layers, batch_size, self.hidden_state_size)\n :param labels: (self.horizon, batch_size, self.num_nodes * self.output_dim) [optional, not exist for inference]\n :param batches_seen: global step [optional, not exist for inference]\n :return: output: (self.horizon, batch_size, self.num_nodes * self.output_dim)\n \"\"\"\n batch_size = encoder_hidden_state.size(1)\n go_symbol = torch.zeros((batch_size, self.num_nodes * self.decoder_model.output_dim),\n device=self.device)\n decoder_hidden_state = encoder_hidden_state\n decoder_input = go_symbol\n outputs = []\n\n for t in range(self.decoder_model.horizon):\n decoder_output, decoder_hidden_state = self.decoder_model(decoder_input, adj, decoder_hidden_state)\n\n decoder_input = decoder_output\n\n outputs.append(decoder_output)\n if self.training and self.use_curriculum_learning:\n c = np.random.uniform(0, 1)\n if c < self._compute_sampling_threshold(batches_seen):\n decoder_input = labels[t]\n outputs = torch.stack(outputs)\n return outputs\n\n def forward(self, inputs, labels=None, batches_seen=None, epoch=None):\n \"\"\"\n :param inputs: shape (seq_len, batch_size, num_sensor * input_dim)\n :param labels: shape (horizon, batch_size, num_sensor * output)\n :param batches_seen: batches seen till now\n :return: output: (self.horizon, batch_size, self.num_nodes * self.output_dim)\n \"\"\"\n\n ShortAdj = self.ShortAdj_generator(inputs)\n Long_Adj = self.LongAdj_generator(inputs)\n adj_list = (ShortAdj + self.lambdax * Long_Adj)/ (1.0+self.lambdax)\n adj = adj_list[0]\n for index in range(1, self.requires_graph):\n adj = adj + self.epis[index] * adj_list[index] # 这里可以设计一个更为复杂的fusion模块\n encoder_hidden_state = self.encoder(inputs, adj)\n outputs = self.decoder(encoder_hidden_state, adj, labels, batches_seen=batches_seen)\n res, adj = self.instant_forecasting(inputs)\n res = res.squeeze(dim=3).permute(1, 0, 2)\n outputs = (outputs + self.beta*res)/ (1.0+self.beta)\n return outputs, adj","repo_name":"onceCWJ/FCDNet","sub_path":"model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8656,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"29562799924","text":"\n# core python\nfrom configparser import ConfigParser\nfrom dataclasses import dataclass\nimport logging\nimport pyodbc\nimport weakref\n\n# pypi\nimport pandas as pd\nfrom sqlalchemy import MetaData, create_engine, sql\n\n# native\nfrom app.infrastructure.util.config import AppConfig\n\n\n# TODO: Make this a static class variable?\n# Cache for created databases. We use two because the weak reference doesn't work with tuples or\n# dicts. Need to revisit this at some point\n_DB_ENGINE_CACHE = weakref.WeakValueDictionary()\n_DB_META_CACHE = weakref.WeakValueDictionary()\n\nMSSQL_CONN_STR = 'mssql+pyodbc://{host}:1433/{db}?driver={driver}&TrustServerCertificate=yes&trusted_connection=yes'\nMSSQL_CONN_STR_WITH_USER = 'mssql+pyodbc://{username}:{password}@{host}:1433/{db}?driver={driver}&TrustServerCertificate=yes&Encrypt=no'\n\n# Driver options in order of preference\nDRIVERS = [\n 'SQL Server Native Client 11.0',\n 'SQL Server Native Client 10.0',\n 'SQL Server',\n 'ODBC Driver 18 for SQL Server'\n]\n\n\ndef get_engine(config_section: str):\n \"\"\"\n Get or create engine. Since each engine object will create a connection to the database server\n we shouldn't create unecessary copies for each table.\n See: http://docs.sqlalchemy.org/en/rel_1_1/core/connections.html#engine-disposal\n \"\"\"\n\n # Get host & DB. Check if already in the cache.\n host = AppConfig().parser.get(config_section, 'host', fallback=None)\n db = AppConfig().parser.get(config_section, 'database', fallback=None)\n key = (host, db)\n\n if key not in _DB_ENGINE_CACHE:\n\n # Get user & pass from config\n username = AppConfig().parser.get(config_section, 'username', fallback=None)\n password = AppConfig().parser.get(config_section, 'password', fallback=None)\n\n # Prepare connection string\n driver = select_driver()\n if not driver:\n raise RuntimeError('No SQL drivers found')\n\n connection_str = MSSQL_CONN_STR.format(\n host=host,\n db=db,\n driver=driver\n )\n\n # If username/password were in config, replace above conn str\n if username is not None and password is not None:\n connection_str = MSSQL_CONN_STR_WITH_USER.format(\n host=host,\n db=db,\n driver=driver,\n username=username,\n password=password\n )\n\n # Add sqlalchemy configs, if provided\n sqlalchemy_pool_size = AppConfig().parser.get(config_section, 'sqlalchemy_pool_size', fallback=None)\n sqlalchemy_pool_timeout = AppConfig().parser.get(config_section, 'sqlalchemy_pool_timeout', fallback=None)\n\n # http://docs.sqlalchemy.org/en/latest/dialects/mssql.html#legacy-schema-mode\n engine_args = {'url': connection_str, 'legacy_schema_aliasing': False}\n # Add optional default overrides\n if sqlalchemy_pool_size is not None:\n engine_args['pool_size'] = sqlalchemy_pool_size\n logging.debug('adding pool size {}'.format(engine_args['pool_size']))\n if sqlalchemy_pool_timeout is not None:\n engine_args['pool_timeout'] = sqlalchemy_pool_timeout\n logging.debug('adding pool timeout {}'.format(engine_args['pool_timeout']))\n engine = create_engine(**engine_args)\n _DB_ENGINE_CACHE[key] = engine\n\n return _DB_ENGINE_CACHE[key]\n\n\ndef get_metadata(config_section: str):\n \"\"\"\n Get or create metadata\n \"\"\"\n \n # Get host & DB. Check if already in the cache.\n host = AppConfig().parser.get(config_section, 'host', fallback=None)\n db = AppConfig().parser.get(config_section, 'database', fallback=None)\n key = (host, db)\n\n if key not in _DB_META_CACHE:\n # MetaData is a container object for table, column, and index definitions.\n # Good description is here\n # http://stackoverflow.com/questions/6983515/why-is-it-useful-to-have-a-metadata-object-which-is-not-bind-to-an-engine-in-sql\n meta = MetaData()\n _DB_META_CACHE[key] = meta\n\n return _DB_META_CACHE[key]\n\n\ndef select_driver():\n \"\"\"\n Select best available driver\n\n :returns: A string representing the driver\n \"\"\"\n installed_drivers = pyodbc.drivers()\n selected_driver = None\n for driver in DRIVERS:\n if driver in installed_drivers:\n selected_driver = driver.replace(' ', '+')\n break\n return selected_driver\n\n\n@dataclass\nclass BaseDB(object):\n \"\"\"A light wrapper around SQLAlchemy Engine and MetaData.\"\"\"\n\n config_section: str\n\n def __post_init__(self):\n \"\"\"\n Initialize Database object and create engine\n\n :param conn_key: Used to lookup db connection info\n :param environment: Optional instance specific override\n :return: None\n \"\"\"\n # Get or create engine and metadata\n self.engine = get_engine(self.config_section)\n self.meta = get_metadata(self.config_section)\n\n def execute_read(self, sql_stmt, log_query=False):\n \"\"\"\n Safely execute a SELECT statement. Execution is done in a transaction that is not\n committed to handle the case when an insert statement is passed by mistake\n\n :param sql_stmt: SqlAlchemy statement\n :param log_query: Set to log compiled query\n :return: Pandas DataFrame with results\n \"\"\"\n if log_query:\n logging.info('=== SQL START ===')\n print(sql_stmt.compile())\n print(sql_stmt.compile().params)\n logging.info('=== SQL END ===')\n\n # Create transaction to run statement in and don't commit for failsafe\n connection = self.engine.connect()\n with connection.begin():\n data = pd.read_sql_query(sql_stmt, connection, coerce_float=False)\n\n return data\n\n def execute_write(self, sql_stmt, log_query=False, commit=None):\n \"\"\"\n Execute an INSERT, UPDATE, or DELETE statement. Execution is done in a transaction and\n COMMIT must be set in order to commit the transaction.\n\n :param sql_stmt: SqlAlchemy statement\n :param log_query: Set to log compiled query\n :param commit: Whether to commit. If not provided, defer to AppConfig\n :return: A sqlalchemy.engine.ResultProxy\n \"\"\"\n if log_query:\n logging.info('=== SQL START ===')\n print(sql_stmt.compile())\n print(sql_stmt.compile().params)\n logging.info('=== SQL END ===')\n\n # Get commit from AppConfig if not provided\n if commit is None:\n commit = AppConfig().parser.get('app', 'commit', fallback=False)\n\n # Create transaction to run statement in. Rollback if commit not set\n connection = self.engine.connect()\n with connection.begin() as transaction:\n result = connection.execute(sql_stmt)\n data = result\n if commit:\n transaction.commit()\n else:\n logging.warning('Commit not set. Rolling back %s', sql_stmt)\n transaction.rollback()\n\n return data\n\n\ndef _convert_to_df(rows, description):\n\t\"\"\"\n\tConvert pyodbc result to dataframe\n\n\t:param rows: Raw pyodbc rows from cursor.fetchall()\n\t:param description: Description of columns from cursor.description\n\t:returns: DataFrame of results\n\t\"\"\"\n\t# Description is a list of tuples. Each tuple is of the form (column name, type code,\n\t# display size, internal size, precision, scale, nullable). Extract just column names\n\tcolumns = [col_description[0] for col_description in description]\n\n\t# Create dict that we can turn into a dataframe\n\tdf_dict = {}\n\tfor column in columns:\n\t\tdf_dict[column] = []\n\n\t# Go through each row and add the values to the dict\n\tfor row in rows:\n\t\tassert len(row) == len(columns)\n\t\tfor i, val in enumerate(row):\n\t\t\tdf_dict[columns[i]].append(val)\n\n\treturn pd.DataFrame(df_dict)\n\n\ndef execute_multi_query(conn, query_str):\n\t\"\"\"\n\tExecutes a query that may return multiple result sets. Each result set is returned as a separate\n\tDataFrame\n\n\t:param conn: A pyodbc connection\n\t:param query_str: The query str to execute\n\t:returns: A list of DataFrames\n\t\"\"\"\n\tcursor = conn.cursor()\n\tcursor.execute(query_str)\n\n\tresults = []\n\twhile True:\n\t\ttry:\n\t\t\trows = cursor.fetchall()\n\t\t\tdf = _convert_to_df(rows, cursor.description)\n\t\t\tresults.append(df)\n\t\texcept pyodbc.ProgrammingError:\n\t\t\t# fetchall will fail if the result set was not a query\n\t\t\tpass\n\n\t\tif not cursor.nextset():\n\t\t\tbreak\n\n\treturn results\n \n\n","repo_name":"cameronj-lw/integration-security-pricing-clean-arch","sub_path":"src/app/infrastructure/util/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":8507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"28758993034","text":"import hashlib\nimport logging\nimport os\nimport shutil\nfrom copy import deepcopy\nfrom datetime import datetime\n\nimport ujson as json\nfrom core import version\nfrom core.feature_flags import flag_set\nfrom core.utils.common import load_func\nfrom core.utils.io import get_all_files_from_dir, get_temp_dir, read_bytes_stream\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils.translation import gettext_lazy as _\nfrom label_studio_converter import Converter\nfrom tasks.models import Annotation\n\nlogger = logging.getLogger(__name__)\n\n\nExportMixin = load_func(settings.EXPORT_MIXIN)\n\n\nclass Export(ExportMixin, models.Model):\n class Status(models.TextChoices):\n CREATED = 'created', _('Created')\n IN_PROGRESS = 'in_progress', _('In progress')\n FAILED = 'failed', _('Failed')\n COMPLETED = 'completed', _('Completed')\n\n title = models.CharField(\n _('title'),\n blank=True,\n default='',\n max_length=2048,\n )\n created_at = models.DateTimeField(\n _('created at'),\n auto_now_add=True,\n help_text='Creation time',\n )\n file = models.FileField(\n upload_to=settings.DELAYED_EXPORT_DIR,\n null=True,\n )\n md5 = models.CharField(\n _('md5 of file'),\n max_length=128,\n default='',\n )\n finished_at = models.DateTimeField(\n _('finished at'),\n help_text='Complete or fail time',\n null=True,\n default=None,\n )\n\n status = models.CharField(\n _('Export status'),\n max_length=64,\n choices=Status.choices,\n default=Status.CREATED,\n )\n counters = models.JSONField(\n _('Exporting meta data'),\n default=dict,\n )\n project = models.ForeignKey(\n 'projects.Project',\n related_name='exports',\n on_delete=models.CASCADE,\n )\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n related_name='+',\n on_delete=models.SET_NULL,\n null=True,\n verbose_name=_('created by'),\n )\n\n\n@receiver(post_save, sender=Export)\ndef set_export_default_name(sender, instance, created, **kwargs):\n if created and not instance.title:\n instance.title = instance.get_default_title()\n instance.save()\n\n\nclass DataExport(object):\n # TODO: deprecated\n @staticmethod\n def save_export_files(project, now, get_args, data, md5, name):\n \"\"\"Generate two files: meta info and result file and store them locally for logging\"\"\"\n filename_results = os.path.join(settings.EXPORT_DIR, name + '.json')\n filename_info = os.path.join(settings.EXPORT_DIR, name + '-info.json')\n annotation_number = Annotation.objects.filter(project=project).count()\n try:\n platform_version = version.get_git_version()\n except: # noqa: E722\n platform_version = 'none'\n logger.error('Version is not detected in save_export_files()')\n info = {\n 'project': {\n 'title': project.title,\n 'id': project.id,\n 'created_at': project.created_at.strftime('%Y-%m-%dT%H:%M:%SZ'),\n 'created_by': project.created_by.email,\n 'task_number': project.tasks.count(),\n 'annotation_number': annotation_number,\n },\n 'platform': {'version': platform_version},\n 'download': {\n 'GET': dict(get_args),\n 'time': now.strftime('%Y-%m-%dT%H:%M:%SZ'),\n 'result_filename': filename_results,\n 'md5': md5,\n },\n }\n\n with open(filename_results, 'w', encoding='utf-8') as f:\n f.write(data)\n with open(filename_info, 'w', encoding='utf-8') as f:\n json.dump(info, f, ensure_ascii=False)\n return filename_results\n\n @staticmethod\n def get_export_formats(project):\n converter = Converter(config=project.get_parsed_config(), project_dir=None)\n formats = []\n supported_formats = set(converter.supported_formats)\n for format, format_info in converter.all_formats().items():\n format_info = deepcopy(format_info)\n format_info['name'] = format.name\n if format.name not in supported_formats:\n format_info['disabled'] = True\n formats.append(format_info)\n return sorted(formats, key=lambda f: f.get('disabled', False))\n\n @staticmethod\n def generate_export_file(project, tasks, output_format, download_resources, get_args):\n # prepare for saving\n now = datetime.now()\n data = json.dumps(tasks, ensure_ascii=False)\n md5 = hashlib.md5(json.dumps(data).encode('utf-8')).hexdigest() # nosec\n name = 'project-' + str(project.id) + '-at-' + now.strftime('%Y-%m-%d-%H-%M') + f'-{md5[0:8]}'\n\n input_json = DataExport.save_export_files(project, now, get_args, data, md5, name)\n\n converter = Converter(\n config=project.get_parsed_config(),\n project_dir=None,\n upload_dir=os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_DIR),\n download_resources=download_resources,\n )\n with get_temp_dir() as tmp_dir:\n converter.convert(input_json, tmp_dir, output_format, is_dir=False)\n files = get_all_files_from_dir(tmp_dir)\n # if only one file is exported - no need to create archive\n if len(os.listdir(tmp_dir)) == 1:\n output_file = files[0]\n ext = os.path.splitext(output_file)[-1]\n content_type = f'application/{ext}'\n out = read_bytes_stream(output_file)\n filename = name + os.path.splitext(output_file)[-1]\n return out, content_type, filename\n\n # otherwise pack output directory into archive\n shutil.make_archive(tmp_dir, 'zip', tmp_dir)\n out = read_bytes_stream(os.path.abspath(tmp_dir + '.zip'))\n content_type = 'application/zip'\n filename = name + '.zip'\n return out, content_type, filename\n\n\nclass ConvertedFormat(models.Model):\n class Status(models.TextChoices):\n CREATED = 'created', _('Created')\n IN_PROGRESS = 'in_progress', _('In progress')\n FAILED = 'failed', _('Failed')\n COMPLETED = 'completed', _('Completed')\n\n project = models.ForeignKey(\n 'projects.Project',\n null=True,\n related_name='export_conversions',\n on_delete=models.CASCADE,\n )\n organization = models.ForeignKey(\n 'organizations.Organization',\n null=True,\n on_delete=models.CASCADE,\n related_name='export_conversions',\n )\n export = models.ForeignKey(\n Export,\n related_name='converted_formats',\n on_delete=models.CASCADE,\n help_text='Export snapshot for this converted file',\n )\n file = models.FileField(\n upload_to=settings.DELAYED_EXPORT_DIR,\n null=True,\n )\n status = models.CharField(\n max_length=64,\n choices=Status.choices,\n default=Status.CREATED,\n )\n traceback = models.TextField(null=True, blank=True, help_text='Traceback report in case of errors')\n export_type = models.CharField(max_length=64)\n created_at = models.DateTimeField(\n _('created at'),\n null=True,\n auto_now_add=True,\n help_text='Creation time',\n )\n updated_at = models.DateTimeField(\n _('updated at'),\n null=True,\n auto_now_add=True,\n help_text='Updated time',\n )\n finished_at = models.DateTimeField(\n _('finished at'),\n help_text='Complete or fail time',\n null=True,\n default=None,\n )\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n related_name='+',\n on_delete=models.SET_NULL,\n null=True,\n verbose_name=_('created by'),\n )\n\n def delete(self, *args, **kwargs):\n if flag_set('ff_back_dev_4664_remove_storage_file_on_export_delete_29032023_short'):\n if self.file:\n self.file.delete()\n super().delete(*args, **kwargs)\n","repo_name":"HumanSignal/label-studio","sub_path":"label_studio/data_export/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8269,"program_lang":"python","lang":"en","doc_type":"code","stars":14812,"dataset":"github-code","pt":"52"} +{"seq_id":"22347493620","text":"from flask import Flask, render_template, jsonify, send_file\nfrom werkzeug.serving import run_simple\nfrom flask_cors import CORS\nfrom flask_restful import Api\n# from gensim.models import Word2Vec\n\nfrom server.settings import MODE, ProductionConfig, DevelopmentConfig\nfrom server.resources.routes import initialize_routes\n\ndef create_app():\n app = Flask(__name__, \n static_folder=\"./static/dist/static\", \n template_folder=\"./static/dist\"\n )\n app.config.from_object(ProductionConfig if MODE == \"production\" else DevelopmentConfig) \n CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n api = Api(app)\n initialize_routes(api)\n return app\n\napp = create_app()\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef catch_all(path):\n return render_template(\"index.html\")\n","repo_name":"pawanpaudel93/np-word2vec-vue","sub_path":"server/app.py","file_name":"app.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":"35756299138","text":"# ��제 - lv.1\n'''\n# #1 - 230214 성공\n 정확성: 100.0\n 합계: 100.0 / 100.0\n 풀이 : for문으로 문자 하나씩 접근하고 p와 y개수를 딕셔너리로 저장\n'''\ndef solution(s):\n char_dict = { 'p' : 0, 'y' : 0}\n\n for c in s:\n if c.lower() == \"p\":\n char_dict['p'] += 1\n elif c.lower() == \"y\":\n char_dict['y'] += 1\n \n return True if char_dict['p'] == char_dict['y'] else False\n\n'''\n개선된 코드는 count() 함수를 써서 아래 처럼 한 줄로 풀이 가능하다. (programmers 풀이 참고함)\n return s.lower().count('p') == s.lower().count('y')\n'''","repo_name":"HyeM207/Algorithm","sub_path":"Programmers/Lv_1/[Prg] 문자열 내 p와 y의 개수.py","file_name":"[Prg] 문자열 내 p와 y의 개수.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"13115577802","text":"# programmers\n# time : 53'\n\ndx = [1, 0, 1]\ndy = [0, 1, 1]\n\ncnt = 0\n\ndef eraser(x, y, board, n, m):\n origin = board[y][x]\n for i in range(3):\n nx, ny = x + dx[i], y + dy[i]\n if 0 <= nx < n and 0 <= ny < m:\n if board[ny][nx] != origin:\n return False\n else:\n return False\n return True\n\ndef fill(x, y, erase, board):\n global cnt\n \n origin = board[y][x]\n if erase[y][x]: \n erase[y][x] = 0\n cnt += 1\n for i in range(3):\n nx, ny = x + dx[i], y + dy[i]\n if erase[ny][nx]: \n erase[ny][nx] = 0\n cnt += 1\n return erase\n\ndef solution(m, n, board):\n answer = 0\n\n for b in range(len(board)):\n board[b] = list(board[b])\n \n \n flag = 1\n while flag:\n flag = 0\n erase = [board[i][:] for i in range(len(board))]\n for i in range(m - 1):\n for j in range(n - 1):\n if board[i][j]:\n if eraser(j, i, board, n, m): # 지울 수 있는 영역\n erase = fill(j, i, erase, board)\n flag = 1\n board = erase\n # 180도 회전\n new = [[] for _ in range(n)]\n for i in range(n):\n for j in range(m):\n if board[m-1-j][i] != 0:\n new[i].append(board[m-1-j][i])\n if len(new[i]) < m:\n new[i] += [0] * (m - len(new[i]))\n \n for i in range(m):\n for j in range(n):\n board[i][j] = new[j][m - 1 - i]\n \n return cnt","repo_name":"olive-su/1day_1Algorithm","sub_path":"22.06_PS/0630_프렌즈4블록.py","file_name":"0630_프렌즈4블록.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"6382284618","text":"\"\"\"Created on Mon Jun 11 17:22:15 2018\n\n@author: Ravikiran.Tamiri\n\"\"\"\n\nfrom bs4 import BeautifulSoup\nimport requests\nfrom nltk.tokenize import sent_tokenize,word_tokenize\nfrom nltk.corpus import stopwords\nfrom collections import defaultdict\nfrom string import punctuation\nfrom heapq import nlargest\n\nmin_cut = 0.1\nmax_cut = 0.9 \nmy_stopwords = set(stopwords.words('english') + list(punctuation))\n \ndef _compute_frequencies(word_sent):\n freq = defaultdict(int)\n for s in word_sent:\n for word in s:\n if word not in my_stopwords:\n freq[word] += 1\n # frequencies normalization and fitering\n m = float(max(freq.values()))\n for w in list(freq):\n freq[w] = freq[w]/m\n if freq[w] >= max_cut or freq[w] <= min_cut:\n del freq[w]\n return freq\n\ndef summarize(text, n):\n sents = sent_tokenize(text)\n assert n <= len(sents)\n word_sent = [word_tokenize(s.lower()) for s in sents]\n _freq = _compute_frequencies(word_sent)\n ranking = defaultdict(int)\n for i,sent in enumerate(word_sent):\n for w in sent:\n if w in _freq:\n ranking[i] += _freq[w]\n sents_idx = _rank(ranking, n) \n return [sents[j] for j in sents_idx]\n\ndef getContentFromURL(url):\n req = requests.get(url)\n soup = BeautifulSoup(req.text, \"html.parser\")\n text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n return text\n\ndef _rank(ranking, n):\n \"\"\" return the first n sentences with highest ranking \"\"\"\n return nlargest(n, ranking, key=ranking.get)\n\ndef summarizeURL(url, total_pars):\n\turl_text = getContentFromURL(url).replace(u\"Â\", u\"\").replace(u\"â\", u\"\")\n\tfinal_summary = summarize(url_text.replace(\"\\n\",\" \"), total_pars)\n\treturn \" \".join(final_summary)\n\ndef process_url(url):\n final_summary = summarizeURL(url, 5)\n print(final_summary)\n \ndef process_text(text):\n final_summary = summarize(text.replace(\"\\n\",\" \"), 5)\n print(final_summary)\n\n#main\nret = input(\"Do you want to enter a \\n 1.URL \\n 2.Text\\n\")\n\nif ret == '1':\n url = input(\"Enter a URL\\n\")\n process_url(url)\nelif ret == '2':\n text = input(\"Enter the text \\n\")\n process_text(text)\nelse:\n print(\"Enter valid input\\n\")\n ","repo_name":"rtamir/MLWork","sub_path":"11-DeepNLP/TextSummarization/text_summarization.py","file_name":"text_summarization.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23528290816","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom apps.content.views import index, about_us, videos, compare_products, cement_vs_ceramic, color_palletes, search, flatpage\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.utils.translation import ugettext_lazy as _\nfrom rest_framework.authtoken import views\nfrom django.views.generic.base import TemplateView\nfrom django.contrib.sitemaps.views import sitemap\nfrom granadatiles_project.sitemaps import StaticViewSitemap, CollectionSiteMap, GroupSiteMap\nfrom django.contrib.flatpages.sitemaps import FlatPageSitemap\n\nsitemaps = {\n 'static': StaticViewSitemap,\n 'flat': FlatPageSitemap,\n 'collections': CollectionSiteMap,\n 'groups': GroupSiteMap\n }\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'customadmin/', include('apps.customadmin.serve_urls' , namespace=\"customadmin\")),\n url(r'^summernote/', include('django_summernote.urls')),\n url(r'^api/', include('apps.tiles.urls', namespace='tiles')),\n url(r'^api/', include('apps.content.urls', namespace='content')),\n url(r'^api/', include('apps.galleries.urls', namespace='galleries')),\n url(r'^api/', include('apps.news.urls', namespace='news')),\n url(r'^api/', include('apps.customadmin.urls', namespace='dashboard')),\n url(r'^api/', include('apps.orders.urls', namespace='orders')),\n url(r'^api/token/', views.obtain_auth_token),\n url('', include('social.apps.django_app.urls', namespace='social')),\n url(r'^robots\\.txt$', TemplateView.as_view(template_name= 'robots.txt', content_type= 'text/plain')),\n url(r'^humans\\.txt$', TemplateView.as_view(template_name= 'humans.txt', content_type= 'text/plain')),\n url(r'^google8b1eebced5a00fe1\\.html$', TemplateView.as_view(template_name= 'google8b1eebced5a00fe1.html')),\n url(r'^sitemap\\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap')\n]\n\nurlpatterns += i18n_patterns(\n url(r'^$', index, name='home'),\n url(_(r'^search/$'), search, name='search'),\n url(_(r'^about-us/$'), about_us, name='about_us'),\n url(_(r'^product-comparison/$'), compare_products, name='compare_products'),\n url(_(r'^cement-vs-ceramic/$'), cement_vs_ceramic, name='cement_vs_ceramic'),\n url(_(r'^color-palletes/$'), color_palletes, name='color_palletes'),\n url(r'^videos/$', videos, name='videos'),\n url(r'^api/', include('apps.cart.urls', namespace='cart')),\n url(_(r'^portfolio/'),\n include('apps.portfolio.serve_urls', namespace='sr-portfolio')),\n url(_(r'^collections/'),\n include('apps.tiles.serve_urls', namespace='sr-collections')),\n url(_(r'^news/'),\n include('apps.news.serve_urls', namespace='sr-news')),\n url(_(r'^gallery/'),\n include('apps.galleries.serve_urls', namespace='sr-galleries')),\n url(_(r'^cart/'),\n include('apps.cart.serve_urls', namespace='sr-cart')),\n #url(r'^', include('django.contrib.flatpages.urls')),\n url(r'^', include('apps.content.serve_urls')),\n)\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","repo_name":"rogergaitan/granadatiles","sub_path":"granadatiles_project/granadatiles_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31007004427","text":"'''Used to start a human vs AI match in ticTacToe'''\nfrom ticTacToe import askPlayerLetters,whoGoesFirst,drawBoard,userMakingMove,isWinner,won,makeAIMove\ngameBoard = [' ']*10\nfor i in range(1,10):\n gameBoard[i]=str(i)\nletters = askPlayerLetters()\ncurrent = whoGoesFirst()\ngameInProgress = True\nmoves = 0\nwhile gameInProgress:\n drawBoard(gameBoard)\n if moves>=9:\n print(\"It's a draw! Well played!\")\n gameInProgress = False\n break\n if current==0: #User move\n userMakingMove(gameBoard,letters[0])\n moves = moves+1\n current = 1\n if moves>=5:\n if isWinner(gameBoard,letters[0]):\n won(0,letters,moves,gameBoard)\n gameInProgress=False\n break\n else: #AI move\n print('Computer\\'s turn:')\n makeAIMove(gameBoard,letters[1])\n moves = moves+1\n current = 0\n if moves>=5:\n if isWinner(gameBoard,letters[1]):\n won(1,letters,moves,gameBoard)\n gameInProgress=False\n break","repo_name":"yashovardhan99/Tic-Tac-Toe","sub_path":"ticTacToeStart.py","file_name":"ticTacToeStart.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35190018986","text":"from django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\nfrom django.contrib.postgres.fields import ArrayField\n\nfrom components.users.models import User\n\n\nclass BookBase(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n is_activate = models.BooleanField(default=True)\n\n class Meta:\n abstract = True\n\n\nclass BookCategory(models.Model):\n name = models.CharField(max_length=128, null=False)\n\n class Meta:\n db_table = 'book_category'\n\n def __str__(self):\n return self.name\n\n\nclass Book(BookBase):\n LANGUAGE_CHOICES = (\n (0, 'VN'),\n (1, 'JP'),\n (2, 'EN'),\n )\n\n name = models.CharField(max_length=256, null=False)\n description = models.TextField()\n image = models.URLField(null=False, blank=True)\n book_category = models.ManyToManyField(BookCategory)\n author = models.CharField(max_length=128, null=True, blank=True)\n paperback = models.IntegerField(default=1)\n language = models.IntegerField(choices=LANGUAGE_CHOICES, default=0)\n publisher = models.CharField(max_length=256, null=True, blank=True)\n price = models.IntegerField(default=0)\n\n class Meta:\n db_table = 'book'\n\n def __str__(self):\n return self.name\n\n\nclass BookReadStatus(BookBase):\n STATUS_CHOICES = (\n (0, 'unread'),\n (1, 'reading'),\n (2, 'read'),\n )\n\n book = models.ForeignKey(Book, on_delete=models.CASCADE)\n user = models.ManyToManyField(User)\n status = models.IntegerField(choices=STATUS_CHOICES, default=0)\n page_reading = models.IntegerField(default=0)\n is_favorite = models.BooleanField(default=False)\n rating = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)])\n\n class Meta:\n db_table = 'book_read_status'\n\n def __str(self):\n return self.page_reading\n\n\nclass BookRequestBuy(BookBase):\n STATUS_CHOICES = (\n (1, 'waiting'),\n (2, 'approved'),\n (3, 'bought'),\n (4, 'reject')\n )\n book_category = models.ManyToManyField(BookCategory)\n book_url = models.URLField(max_length=512)\n name = models.CharField(max_length=256)\n price = models.IntegerField(default=1)\n status = models.IntegerField(choices=STATUS_CHOICES, default=1)\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n\n class Meta:\n db_table = 'book_request_buy'\n\n def __str__(self):\n return self.book_url\n\n\nclass BookReview(BookBase):\n book = models.OneToOneField(Book, on_delete=models.CASCADE)\n messages = ArrayField(ArrayField(models.CharField(max_length=512, blank=True), size=5))\n\n class Meta:\n db_table = 'book_review'\n\n def __str__(self):\n return self.book.name\n","repo_name":"minhhh-0927/brs","sub_path":"components/books/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"43759422872","text":"\"\"\"\n给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。\n如果数组元素个数小于 2,则返回 0。\n示例 1:\n输入: [3,6,9,1]\n输出: 3\n解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。\n示例 2:\n输入: [10]\n输出: 0\n解释: 数组元素个数小于 2,因此返回 0。\n说明:\n你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。\n请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。\n\"\"\"\n\n\nclass Solution:\n def maximumGap(self, nums: list) -> int:\n if not nums or len(nums) < 2:\n return 0\n\n nums.sort()\n k = [nums[i+1] - nums[i] for i in range(len(nums) - 1)]\n return max(k)\n\n def maximumGap(self, nums: list) -> int:\n if not nums or len(nums) < 2:\n return 0\n\n k = [nums[i+1] - nums[i] for i in range(len(nums) - 1)]\n return max(k)\n\n\ndef test():\n assert Solution().maximumGap([3,6,9,1]) == 3\n assert Solution().maximumGap([3]) == 0\n\n\nif __name__ == '__main__':\n test()","repo_name":"spiritdjy/MixLeetCode","sub_path":"mixleet/leecode/164.py","file_name":"164.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23113301652","text":"import asyncio\nimport datetime\nimport random\nimport shelve\nimport json\nimport discord\nimport requests\nfrom bs4 import BeautifulSoup\nfrom discord import app_commands\nfrom discord.ext import commands, tasks\nfrom pathlib import Path\n\n\nclass Auto(commands.Cog, name=\"Auto\"):\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.callout.start()\n self.score_reset.start()\n self.werewolf.start()\n self.lore_backup.start()\n self.GUILD = str(bot.guilds[0].id)\n\n # Load the channel to output to from the config\n with open(\"config.json\") as config_json:\n config = json.load(config_json)\n # Extract just the id int from the channel call string (<#XXXXXX>)\n self.wolf_channel = int(config[self.GUILD][\"wolf_channel\"][2:-1])\n self.callout_channel = int(config[self.GUILD][\"callout_channel\"][2:-1])\n\n async def update_avatar(self, path):\n with open(path, \"rb\") as img:\n avatar = img.read()\n await self.bot.user.edit(avatar=avatar)\n img.close()\n\n # Check every message that comes through and perform a hog-check\n @commands.Cog.listener(\"on_message\")\n async def hog_check(self, message):\n # Do not reply to BB's own messages\n if message.author == self.bot.user:\n return\n\n # Reply to the secret word with 1/10 chance\n if 'hog' in message.clean_content.lower() and 1 == random.randint(1, 10):\n await message.channel.send('HYPEROMEGAHOGGERS')\n\n # Weekly Bad Score Callout Post\n # Publicly humiliate whoever has the lowest score with an automated post each Friday\n @tasks.loop(time=datetime.time(23, 0, 0)) # This represents 7:00 P.M. EST (11:00 P.M. UTC)\n async def callout(self):\n # If today is Friday (noted as 5 by isoweekday(), monday-sunday: 1-7), send the callout post\n if datetime.date.isoweekday(datetime.date.today()) == 5:\n # Sort the current user scores from highest to lowest\n plus_minus = shelve.open(\"plusMinus\")\n score_sorted = sorted(plus_minus.items(), key=lambda x: x[1])\n plus_minus.close()\n\n # Send our fun little message letting our friend know they should try making better jokes\n callout_post = await self.bot.get_channel(self.callout_channel).send(\n \"This is your weekly Bad Score Callout Post, a public \"\n \"service brought to you by Billager Bot. This week, \" +\n str(score_sorted[0][0]) + \" has the worst score so far. All \"\n \"the way down at a fat \" + str(score_sorted[0][1]) + \"!\")\n # Derive the called out role by name\n # TODO: make this more robust later on\n callout_role = discord.utils.get(self.bot.get_guild(self.bot.guilds[0].id).roles, name=\"Called Out\")\n # Apply the called out role to the user mentioned in the callout post\n await callout_post.mentions[0].add_roles(callout_role)\n else:\n return\n\n # Reset the scoreboard at midnight after the last callout post of the month\n @tasks.loop(time=datetime.time(4, 0, 0))\n async def score_reset(self):\n # Get the day of the month of the next friday\n next_friday = datetime.date.today() + datetime.timedelta(days=6)\n # If the loop runs on a Saturday (midnight following callout post on Friday evening,\n # and the next Friday's day is a lower number than yesterday's Friday,\n # then reset the scoreboard since that was the last friday of the month.\n if datetime.date.isoweekday(datetime.date.today()) == 6 and datetime.date.today().day - 1 > next_friday.day:\n plus_minus = shelve.open(\"plusMinus\")\n plus_minus.clear()\n plus_minus.close()\n else:\n return\n\n # Daily lore backup, every 24 hours starting from launch\n @tasks.loop(hours=24)\n async def lore_backup(self):\n # Load the lore and init a dict to export\n all_lore = shelve.open(\"loreKeeper\")\n lore_backup = {}\n\n # Assign each embed (as a dict) to its respective key (title) in a dict\n for key, value in all_lore.items():\n lore_backup[key] = value.to_dict()\n\n # Export the fully populated dict as a .txt file\n with open(\"lore_backup.txt\", \"w\") as backup_file:\n backup_file.write(json.dumps(lore_backup))\n\n # Close files and log that lore was backed up, with timestamp\n all_lore.close()\n backup_file.close()\n print(\"Lore backed up: \" + str(datetime.datetime.now()))\n\n # On the night of a full moon, Billager becomes the Wolfager\n @tasks.loop(time=datetime.time(1, 0, 0)) # 9 P.M. EST\n async def werewolf(self):\n # Get the day / month / year, prepending a 0 if needed as the url uses leading zeroes\n day = str(datetime.date.today().day) if datetime.date.today().day >= 10 \\\n else \"0\" + str(datetime.date.today().day)\n month = str(datetime.date.today().month) if datetime.date.today().month >= 10 \\\n else \"0\" + str(datetime.date.today().month)\n year = str(datetime.date.today().year)\n\n # Scrape the HTML from this moon phase website\n url = \"https://www.moongiant.com/phase/\" + month + \"/\" + day + \"/\" + year + \"/\"\n page = requests.get(url)\n soup = BeautifulSoup(page.content, \"html.parser\")\n results = soup.find(id=\"moonDetails\")\n\n # If the phase of the moon is full, run the werewolf sequence\n if \"Full Moon\" in results.find_next(\"span\"):\n self.werewolf_run.start()\n\n # Duration of the werewolf transformation\n @tasks.loop(hours=9, minutes=45, count=1) # This will add to ten hours, returning BBot to normal at 7 A.M. EST\n async def werewolf_run(self):\n # Update the avatar/presence/nickname and announce Wolfager's arrival\n await self.update_avatar(Path(\"avatars/wolfager.png\"))\n await self.bot.guilds[0].me.edit(nick=\"Wolfager Bot🪓\")\n await self.bot.get_channel(self.wolf_channel).send(\"**AWOOOOOOOOOO**\")\n await self.bot.get_channel(self.wolf_channel).send(\"The *Wolfager* prowls under the full moon tonight.\")\n await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening,\n name=\"the howls of the pack.\"))\n # Run the activity loop\n self.werewolf_activity.start()\n\n # Activity for the Wolfager to do to add some life to him\n @tasks.loop(hours=0, minutes=5, count=5)\n async def werewolf_activity(self):\n actions = [\"I have the urge to visit London for a big dish of beef chow mein\",\n \"c!play werewolves of london\",\n \"Hey anyone wanna watch Wolfcop?\",\n \"**BARK BARK BARK BARK BARK**\",\n \"I have the urge to drink a piña colada at Trader Vic's\",\n \"c!play hungry like the wolf\",\n \"I'll rip your lungs out, Jim\"]\n # Only run starting on the \"second\" loop, since the first would trigger immediately\n if self.werewolf_activity.current_loop > 0:\n self.werewolf_activity.change_interval(minutes=random.randint(15, 59))\n await self.bot.get_channel(self.wolf_channel).send(random.choice(actions))\n\n # Billager returns to normal after his Wolfager sabbatical\n @werewolf_run.after_loop\n async def werewolf_done(self):\n # Change the avatar back to normal\n await self.update_avatar(Path(\"avatars/billager.png\"))\n # Stop the werewolf activity loop if it might still be running\n if self.werewolf_activity.is_running():\n self.werewolf_activity.stop()\n # Return the activity and nickname to normal\n await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing,\n name=\"with his axe.\"))\n await self.bot.guilds[0].me.edit(nick=\"Billager Bot🪓\")\n # Give a buffer for the change to show up in the sidebar / chat log\n await asyncio.sleep(30)\n # Some thoughtful commentary from BBot on the situation\n await self.bot.get_channel(self.wolf_channel).send(\"*coughs up a filthy werewolf hairball*\")\n await self.bot.get_channel(self.wolf_channel).send(\"Isabelle, clear my calendar for the day and book me for \"\n \"a flea bath at Shampoodle immediately.\")\n\n\nasync def setup(bot):\n await bot.add_cog(Auto(bot), guild=discord.Object(id=bot.guilds[0].id))\n","repo_name":"EBraceyIV/Billager-Bot","sub_path":"cogs/auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":8666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"72375087524","text":"#Using NY times API: http://developer.nytimes.com/docs/books_api/Books_API_Best_Sellers\n\nimport requests\nimport json\nimport datetime\nfrom dates import datesList\n\n\n#API Key for NY Times\nquery_params = {'api-key': '5381b9be882d1bb43424ff4d9724131b:13:71711206'}\n\n# Create JSON file with current date in name\ndt = str(datetime.datetime.now())\n\n# Get data\nfor date in datesList:\n date = str(date)\n endpoint = 'http://api.nytimes.com/svc/books/v3/lists/'+date+'/picture-books.json'\n response = requests.get(endpoint, params=query_params)\n datadict = json.loads(response.text)\n \n# Save to file\n if datadict['num_results'] != 0:\n with open('bestsellers_'+dt+'.json', 'a') as f:\n data = response.json()\n json.dump(data, f)\n f.write('\\n')","repo_name":"askebos/NYBestsellers","sub_path":"getbestsellers.py","file_name":"getbestsellers.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4879782427","text":"\n\nimport configparser\nimport argparse\n\n\ndef cnf_file_read(cnf_file):\n # Reads the configuration file\n config = configparser.ConfigParser()\n config.read(cnf_file) # \"./data_specs.cnf\"\n\n # Determines the list of available datasets\n\n num_of_datasets = int(config.get('Available_datasets', 'number'))\n\n lst_datasets = []\n for n_set in range(0, num_of_datasets):\n set_n = \"set_{0:d}\".format(n_set)\n lst_datasets.append(config.get('Available_datasets', set_n))\n\n # Determines the list of available scenarios\n num_of_sc = int(config.get('Scenarios', 'number'))\n\n lst_scenarios = []\n for n_sc in range(0, num_of_sc):\n sc_n = \"scenario_{0:d}\".format(n_sc)\n lst_scenarios.append(config.get('Scenarios', sc_n))\n\n\n conf_data = {\"num_of_datasets\": num_of_datasets,\n \"list_of_datasets\": lst_datasets,\n \"number_of_scenarios\": num_of_sc,\n \"list_of_scenarios\": lst_scenarios}\n return (conf_data)\n\n\ndef cnf_file_scenario_select(cnf_file):\n config = configparser.ConfigParser()\n config.read(cnf_file) # \"./analysis.cnf\"\n\n\n\n # Read a path to a home folder\n path_home_folder = config.get('Paths', 'home_dir')\n # Read a path to a data folder\n path_data_folder = path_home_folder + config.get('Paths', 'data_dir')\n\n path_to_data = config.get('Available_datasets', 'set_1') + '/'\n\n filename = config.get('Scenario_0', 'file_00')\n\n file_path = path_data_folder + path_to_data + filename\n\n return (file_path)\n\n\ndef parse_CMDLine(cnf_file):\n\n conf_data = cnf_file_read(cnf_file)\n # Parses a set of input arguments coming from a command line\n parser = argparse.ArgumentParser(\n description='''\n Script downloads the data\n prepared in a dedicated folder according to a\n pre-defined scenario. Parameters are specified\n in a configuration file. Scenario has to be\n selected by an argument.''')\n # Read command line arguments to get a scenario\n parser.add_argument(\"-s\", \"--scenario\", help='''Sets an analysis to a given\n scenario. The scenario has to\n be one from an existing ones.''')\n # Select the radar to process\n parser.add_argument(\"-l\", \"--list\", action=\"store_true\",\n help=\"Prints a list of available scenarios\")\n # Output folder\n parser.add_argument(\"-o\", \"--output\",\n help=\"Sets path to the folder where output files will be stored.\")\n # Select a scenario\n argv = parser.parse_args()\n\n\n return (conf_data_out)\n","repo_name":"petrbojda/TrioNav","sub_path":"srcpy/utils/config_tools.py","file_name":"config_tools.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"74713699684","text":"import os\nimport sys\nfrom time import sleep as wait\nfrom time import time as timestamp\nfrom yaspin import yaspin\nimport yaml\nfrom termcolor import cprint, colored\nfrom subprocess import run\nfrom PyInquirer import prompt, Separator\nfrom typing import List, Tuple, Dict, Optional, Callable\n\nCHECKMARK = colored(\"√\", 'green')\n\ndef main():\n templates, products, options, before, after = load_yaml_file()\n \n for step_name, command in iterate_steps(before):\n do_step(step_name, command, show=options['show stdout']['before'])\n\n for product in iterate_products(templates, products):\n update_project(**product)\n\n for step_name, command in iterate_steps(after):\n do_step(step_name, command, show=options['show stdout']['after'])\n\ndef load_yaml_file():\n if not os.path.isfile('./.updater.yml'):\n print(\"FATAL: Couldn't file a .updater.yml file in the current directory\")\n sys.exit()\n \n with open('./.updater.yml', 'r') as file:\n raw = file.read()\n parsed = yaml.load(raw, Loader=yaml.SafeLoader)\n \n try:\n products = parsed['products']\n templates = parsed.get('templates', {})\n options = parsed.get('options', { 'show stdout': { 'before': False, 'after': True } })\n before = parsed.get('before', [])\n after = parsed.get('after', [])\n except KeyError:\n print('FATAL: Please set your products in .updater.yml')\n sys.exit()\n \n return templates, products, options, before, after\n \n\ndef iterate_products(\n templates: dict,\n products: List[dict]\n):\n # The yaml is structured like:\n # products:\n # - Verbose product name:\n # pm2: ...\n # dir: ...\n # ...\n cleaned_products = []\n for product in products:\n cleaned_product = {}\n for verbose_name, product in product.items():\n cleaned_product['verbose_name'] = verbose_name\n for key, val in product.items():\n val = _apply_template(key, val, templates)\n key = key.replace(' ', '_')\n cleaned_product[key] = val\n cleaned_products.append(cleaned_product)\n\n for product in cleaned_products:\n yield product\n\ndef _apply_template(\n key: str,\n value: str,\n templates: dict\n):\n if key in templates.keys():\n return templates[key] % value\n else:\n return value\n\ndef update_project(\n dir: str,\n pm2: Optional[str],\n clone_url: str,\n verbose_name: Optional[str], \n steps: List[Tuple[str, str, Optional[Dict]]]\n):\n ## Print a header\n cprint('\\n\\n' + (verbose_name or pm2 or dir).upper() + '\\n\\n', 'yellow', attrs=['bold'])\n ## Create the dir & clone if it doesnt exist\n if not os.path.isdir(dir):\n if prompt([{\n 'type': 'confirm',\n 'message': \"The repository does not exist. Do I clone it?\",\n 'default': True,\n 'name': 'clone'\n }])['clone']:\n git_clone(clone_url, dir)\n else:\n return\n with working_dir(dir):\n ## Check if the repo is up to date\n uptodate = is_up_to_date()\n ## Get choices (if the app is not managed by pm2, we can't show the \"Just restart the app\" option)\n what_to_do_choices = [\n 'Nothing',\n 'Do as if it was not up to date',\n Separator(),\n ]\n if pm2: what_to_do_choices.append('Just restart the app')\n for step_name, _ in iterate_steps(steps):\n what_to_do_choices.append(step_name)\n what_to_do = ''\n ## If the repo is up to date, ask what to do\n if uptodate:\n what_to_do = prompt([{\n 'type': 'list',\n 'message': \"The repository is already up to date. What should I do?\",\n 'name': 'what_to_do',\n 'default': 'Nothing',\n 'choices': what_to_do_choices\n }])['what_to_do']\n ## Exit\n if what_to_do == 'Nothing':\n return\n\n ## Pull from origin\n if not uptodate:\n git_pull()\n print(CHECKMARK + ' Pulled.')\n ## Do the steps\n if uptodate and what_to_do in [s[0] for s in iterate_steps(steps)]:\n for step_name, command in iterate_steps(steps):\n do_step(step_name, command)\n elif not uptodate or what_to_do == 'Do as if it was not up to date':\n update(steps)\n ## Restart (if the app is managed by pm2)\n if pm2:\n restart(pm2)\n print(CHECKMARK + ' Restarted.')\n\n\nclass working_dir:\n def __init__(self, path):\n self.path = path\n self.cwd = os.getcwd()\n def __enter__(self):\n os.chdir(self.path)\n cprint(f\"Now at {os.getcwd()}\", attrs=['dark'])\n def __exit__(self, type, value, traceback):\n os.chdir(self.cwd)\n cprint(f\"Now at {os.getcwd()}\", attrs=['dark'])\n\n@yaspin(text=\"Checking for updates...\", color=\"cyan\")\ndef is_up_to_date():\n shell('sudo git fetch')\n stdout = shell('git --no-pager log HEAD..origin/master --oneline').stdout\n uptodate = stdout == b''\n return uptodate\n\n@yaspin(text=\"Pulling from origin...\", color=\"cyan\")\ndef git_pull():\n shell('git pull')\n # print(\"Done.\")\n\n@yaspin(text=\"Cloning repository...\", color=\"cyan\")\ndef git_clone(git_clone_url, dir_name):\n shell(f'git clone {git_clone_url} {dir_name}')\n\n@yaspin(text=\"Restarting...\", color=\"cyan\")\ndef restart(pm2_app):\n shell(f'pm2 restart {pm2_app}')\n\ndef update(steps):\n for spinner_text, command in iterate_steps(steps):\n do_step(spinner_text, command)\n\ndef do_step(text, command, **opts):\n @yaspin(text=text+'...', color='cyan')\n def doit():\n shell(command, **opts)\n doit()\n print(CHECKMARK + ' ' + _word_being_to_preterit(text, 'Done') + '.')\n\ndef iterate_steps(steps):\n for step in steps:\n for (verbose_name, command) in step.items():\n yield verbose_name, command\n\ndef _word_being_to_preterit(text: str, fallback: str):\n \"\"\"\n Replaces the first word of :text: with its preterit tense, \n or return :fallback:\n \"\"\"\n REPLACE_MAP = {\n 'Installing': 'Installed',\n 'Building': 'Built',\n 'Activating': 'Activated',\n 'Copying': 'Copied',\n 'Moving': 'Moved',\n 'Compiling': 'Compiled',\n 'Linting': 'Linted',\n 'Stopping': 'Stopped',\n 'Getting': 'Got',\n 'Setting': 'Set',\n 'Extracting': 'Extracted',\n 'Restarting': 'Restarted',\n 'Reloading': 'Reloaded',\n 'Launching': 'Launched',\n 'Applying': 'Applied'\n }\n for (being, preterit) in REPLACE_MAP.items():\n if being in text.split(' '):\n return text.replace(being, preterit)\n return fallback\n\ndef shell(command, show=False):\n return run(command, shell=True, capture_output=not show)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ewen-lbh/deploy-tools","sub_path":"update-products.py","file_name":"update-products.py","file_ext":"py","file_size_in_byte":6316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40466532181","text":"#!usr/bin/python3\nimport os\n\n# stat 信息\nstatinfo = os.stat('os_link.py')\n\nprint(statinfo)\n\n# 参数\n# newvalue -- 如果为 True, 调用 stat() 返回 floats,如果 False, 调用 stat 返回 ints。如果没有该参数返回当前设置。\nstatinfo = os.stat_float_times()\n\nprint(statinfo)\n\n# 3.7 弃用\n# AttributeError: module 'os' has no attribute 'stat_float_times'","repo_name":"Woaijiangnanyu/PythonTree","sub_path":"os/os_stat_float_times.py","file_name":"os_stat_float_times.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"24595384048","text":"\"\"\"\nEnthält vom Programm verwendete statische Veriablen. Die Parameter können auf das eigene System angepasst werden.\n\"\"\"\n\n# Pfad des Konfigurationsverzeichnisses von Wireguard. Muss mit einem / enden. Standard: /etc/wireguard/\nWG_DIR = \"../res/\"\n\n# Dateiname der Serverkonfiguration. Standard: wg0.conf\nSERVER_CONFIG_FILENAME = \"wg0.conf\"\n\n# Quelle: https://docs.sweeting.me/s/wireguard#Overview\n# Parameter der Sektion Interface\nINTERFACE_CONFIG_PARAMETERS = (\"Address\", \"ListenPort\", \"PrivateKey\", \"DNS\", \"Table\", \"MTU\", \"PreUp\", \"PostUp\",\n \"PreDown\", \"PostDown\")\n\n# Parameter der Sektion Peer\nPEER_CONFIG_PARAMETERS = (\"AllowedIPs\", \"Endpoint\", \"PublicKey\", \"PersistentKeepalive\")\n\n# Alle Konfigurationsparameter\nCONFIG_PARAMETERS = INTERFACE_CONFIG_PARAMETERS + PEER_CONFIG_PARAMETERS\n\n# Zusätzliche Ausgaben zum Programmablauf ausgeben\nDEBUG = False\n\n# Für den Betrieb notwendige Konfigurationsparameter. Hinterlegt in kleinbuchstaben.\nMINIMAL_CONFIG_PARAMETERS = (\"address\", \"privatekey\")\n\n# Regulärer Ausdruck für die Erkennung eines einzelnen Parameters. Es dürfen Leerzeichen vor und hinter dem Parameter\n# stehen. Die erste Gruppe enthält den Parameter ohne äußere Leerzeichen.\nRE_MATCH_KEY = r\"^ *([a-zA-Z]*) *\"\n\n# Regulärer Ausdruck für die Erkennung eines Name-Wert Paares. Es dürfen Leerzeichen zwischen Name, dem\n# Zuweisungsoperator = und dem Wert stehen. Die erste Gruppe beinhaltet den Parameternamen ohne Leerzeichen. Die\n# zweite Gruppe beinhaltet den Wert ohne führende Leerzeichen.\nRE_MATCH_KEY_VALUE = r\"^([^ ]*) *= *(.*)\"\n\n# Relativer Ordnerpfad zu WG_DIR für die Datensicherung. Muss mit einem / enden.\nSAVEDIR = \".wg_conf_bak/\"\n\n# Relativer Ordnerpfad zu WG_DIR für die Datensicherung. Wird nach erfolgreicher Erstellung in SAVEDIR umbenannt,\n# um Datenverlust bei einem Fehler im Export vorzubeugen. Muss mit einem / enden.\nSAVEDIR_NEW = \".wg_conf_bak_new/\"\n\n# Datensicherung beim Export deaktivieren\nDISABLE_BACKUP = False\n","repo_name":"Jomibe/wireguard-config-generator","sub_path":"src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20921140040","text":"from random import randint\n \na = []\nfor i in range(10):\n a.append(randint(1, 99))\na.sort()\nprint('Массив: ', a)\n \nvalue = int(input('Введите искомое число: '))\n \nmid = len(a) // 2\nlow = 0\nhigh = len(a) - 1\n \nwhile a[mid] != value and low <= high:\n if value > a[mid]:\n low = mid + 1\n else:\n high = mid - 1\n mid = (low + high) // 2\n \nif low > high:\n print(\"Число в массиве отсутствует!\")\nelse:\n print(\"Индекс искомого числа в массиве =\", mid)","repo_name":"DVS2022/4_mod","sub_path":"4_1.py","file_name":"4_1.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40585637217","text":"# Alex Feeley\n# December 6, 2020\n# This class aims to monitor the safety of the complete controller by ensuring that\n# two aircraft never collide and that the aircraft never enter each other's danger\n# zones.\n\n\nclass SafetyMonitor:\n def __init__(self):\n # True if danger zone ever encountered or planes crash\n self.danger = False\n\n # Enters danger state if planes enter danger zone or crash\n def error(self, plane1, plane2):\n # Current position of planes puts them in each others danger zones\n if abs(plane1.getXPos() - plane2.getXPos()) < 0.5 and abs(plane1.getYPos() - plane2.getYPos()) < 0.5:\n self.danger = True\n # Check if plane's positions overlapped in x-direction (aka they crashed!)\n elif plane1.getXPos() == plane2.xLast and plane1.getYPos() == plane2.getYPos() and \\\n plane1.xLast == plane2.getXPos():\n self.danger = True\n # Check if plane's positions overlapped in y-direction (aka they crashed!)\n elif plane1.getYPos() == plane2.yLast and plane1.yLast == plane2.getYPos() and \\\n plane1.getXPos() == plane2.getXPos():\n self.danger = True\n\n return self.danger\n\n # The controller is safe if danger == False\n def safety(self):\n return not self.danger\n","repo_name":"AlexFeeley/Aircraft-Collision-Avoidance","sub_path":"SafetyMonitor.py","file_name":"SafetyMonitor.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"4443746788","text":"import time\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\nfrom sklearn.covariance import OAS\nfrom sklearn.decomposition import PCA\nfrom utils import *\nimport sys\nimport get_parameters\n\n\nstart = time.time ()\nparameters = get_parameters.parse_args_get_paths()\n\nexpression_file = parameters.expMatrix\ncell_type_file = parameters.clusterArray\noutput_file = \"{}_paths.txt\".format(parameters.output)\nall_output_file = \"{}_all_paths.txt\".format(parameters.output)\n\nexpression_matrix = np.loadtxt (expression_file, dtype=float)\ncell_type_array = np.loadtxt (cell_type_file, dtype=str)\nall_cell_types = sorted (list (set (cell_type_array)), key=sort_key)\ncell_subtype_array = np.array ([None] * len (cell_type_array))\n\ngene_number = len(expression_matrix[0])\ncell_number = len(expression_matrix)\ncell_cluster_number = len(all_cell_types)\nprint (\"Data information :\")\nprint (\"gene : \", gene_number)\nprint (\"cell : \", cell_number)\nprint (\"clusters : \", all_cell_types)\n\nn_components_pca = parameters.nComponentsPCA\nif n_components_pca == False:\n n_components_pca = min(5*(cell_cluster_number-1), int(0.01*gene_number))\n\nn_components_lda = parameters.nComponentsLDA\nif n_components_lda == False:\n n_components_lda = min(cell_cluster_number - 1, n_components_pca)\n\nif n_components_pca < n_components_lda:\n print(\"--nComponentsPCA(-np) should not be less than --nComponentsLDA(-nl)\")\n sys.exit (0)\n\nexpression_matrix = PCA (n_components=n_components_pca, svd_solver=\"full\").fit_transform (expression_matrix)\nprint(\"Matrix shape after PCA: \", expression_matrix.shape)\noa = OAS(store_precision=False, assume_centered=False)\nexpression_matrix = LDA (n_components=n_components_lda,\n covariance_estimator=OAS(store_precision=False, assume_centered=False),\n solver='eigen').fit_transform (expression_matrix, cell_type_array)\nprint(\"Matrix shape after LDA: \", expression_matrix.shape)\n\naverage_size_subclusters = parameters.sizeSubcluster\ncelltype2subtype = {}\nfor celltype in all_cell_types:\n idx = np.where (cell_type_array == celltype)[0]\n n_clu = int (len (idx) / average_size_subclusters) + 1\n cells_of_this_celltype = expression_matrix[idx]\n predict_of_subtype = kmeans (cells_of_this_celltype, n_clusters=n_clu)\n subcelltype = np.array ([\"{}*SustechJinLab*{}\".format (celltype, p) for p in predict_of_subtype.labels_])\n celltype2subtype[celltype] = sorted (list (set (subcelltype)), key=sort_key)\n cell_subtype_array[idx] = subcelltype\n\nall_cell_subtypes = sorted (list (set (cell_subtype_array)), key=sort_key)\n\nsubcelltype_centers = np.array (\n [expression_matrix[cell_subtype_array == subtype].mean (axis=0) for subtype in all_cell_subtypes])\nsubcelltype_centers_dis_matrix = get_distance_matricx (subcelltype_centers, all_cell_subtypes)\n\ncelltype_centers = np.array (\n [expression_matrix[cell_type_array == cell_type].mean (axis=0) for cell_type in all_cell_types])\ncelltype_centers_dis_matrix = get_distance_matricx (celltype_centers, all_cell_types)\n\ncelltype_centers_bf_matrix = get_bayes_factor_matrix(expression_matrix, cell_type_array, all_cell_types,\n num_calculation=parameters.nCalculationBayesFactor)\nprint(\"Bayes Factor Matirx: \")\nprint(celltype_centers_bf_matrix)\ncelltype_centers_bf_matrix.rename (index=lambda x: \"to_\" + x).to_csv(\"{}_BF.txt\".format(output_file), sep=\"\\t\",\n header=True, index=True, float_format=\"%f\")\n\nif parameters.plotBayesFactorMatrix:\n plot_bf_matrix(celltype_centers_bf_matrix.rename (index=lambda x: \"to_\" + x), path=\"{}_BF.pdf\".format(output_file))\n\nsearch_dic_sub = matrix2dic (subcelltype_centers_dis_matrix, celltype2subtype)\n\nsearch_dic = {}\nfor k1, v1 in search_dic_sub.items ():\n k1 = k1.split (\"*SustechJinLab*\")[0]\n # print(k1)\n if k1 not in search_dic.keys ():\n search_dic[k1] = []\n for k2, v2 in v1.items ():\n k2 = k2.split (\"*SustechJinLab*\")[0]\n if k2 != k1 and k2 not in search_dic[k1]:\n search_dic[k1].append(k2)\n\nk_neighbor_clu = parameters.kNeighbor\nfor k1, v1 in search_dic.items ():\n if len (v1) > k_neighbor_clu:\n cutoff = sorted(list(map(lambda clu: celltype_centers_bf_matrix[k1][clu], v1)))[-k_neighbor_clu]\n search_dic[k1] = [clu for clu in v1 if celltype_centers_bf_matrix[k1][clu] >= cutoff]\n\nmandatory_link = parameters.mandatoryLink\nonly_mandatory_link = parameters.onlyMandatoryLink\n\ncancel_link = parameters.cancelLink\n\nprint(\"The original search graph: \")\nprint_dict(search_dic)\n\nundirected_link = parameters.undirectedLink\nif undirected_link == True:\n for kk in search_dic.keys():\n for vv in search_dic[kk]:\n if kk not in search_dic[vv]:\n search_dic[vv].append(kk)\n print (\"\\nTransform links into undirected links: \")\n print_dict (search_dic)\n\nfor k, v in mandatory_link.items():\n if only_mandatory_link:\n search_dic[k] = list(v)\n else:\n search_dic[k] = list(set(search_dic[k]+v))\n\nif len(mandatory_link) != 0:\n print (\"\\nMandatory links: \")\n print_dict (mandatory_link)\n if only_mandatory_link:\n print(\"Only mandatory links !!!!\")\n print(\"The search graph: \")\n print_dict (search_dic)\n\nfor k, v in cancel_link.items ():\n for p in v:\n if p in search_dic[k]:\n search_dic[k].remove(p)\n\nif len(cancel_link) != 0:\n print (\"\\nCancel links: \")\n print_dict (cancel_link)\n print(\"The search graph: \")\n print_dict (search_dic)\n\nstart_points = parameters.beginning\nprint(\"Beginnings: {}\".format(start_points))\nend_points = parameters.destination\nprint(\"Destinations: {}\".format(end_points))\nfind_more_end_point = parameters.newDestination\nnew_find_end_points = None\n\npaths = []\nif len (end_points) == 0:\n\n Queue = [[start_point] for start_point in start_points]\n while len (Queue) != 0:\n path = Queue.pop (0)\n last_point = path[-1]\n next_points = [point for point in search_dic[last_point] if point not in path]\n if len (next_points) == 0:\n paths.append (path)\n else:\n for point in next_points:\n newpath = path + [point]\n Queue.append (newpath)\nelse:\n\n Queue = [[start_point] for start_point in start_points]\n while len (Queue) != 0:\n path = Queue.pop (0)\n last_point = path[-1]\n if last_point not in end_points:\n next_points = [point for point in search_dic[last_point] if point not in path]\n else:\n next_points = []\n if len (next_points) == 0:\n paths.append (path)\n else:\n for point in next_points:\n newpath = path + [point]\n Queue.append (newpath)\n\n if find_more_end_point:\n print (\"Finding new ends.\")\n new_find_end_points = [path[-1] for path in paths if path[-1] not in end_points]\n new_find_end_points = list (set (new_find_end_points))\n\n if len (new_find_end_points) != 0:\n print (\"Find new ends: {}\".format (\" \".join (new_find_end_points)))\n else:\n print (\"No new end is found.\")\n\n else:\n print (\"Ignoring unlisted end points: {} paths -->>\".format(len(paths)), end=\" \")\n paths = [path for path in paths if path[-1] in end_points]\n print(\"{} paths\".format(len(paths)))\n\nif len(paths) == 0:\n print(\"Sorry, no path was left with the listed end points, \"\n \"maybe you can add more points in the list \"\n \"or use --newDestination(-nd)\")\n sys.exit (0)\n\npaths = [(get_score_of_a_path(celltype_centers_bf_matrix, path), path) for path in paths]\npaths.sort (key=lambda x: len(x[1]))\n\nfinal_paths = []\nfinal_paths_sets = [set(paths[0][1])]\nfinal_paths_indexs = [{0}]\n\nfor i in range(1, len (paths)):\n the_path = paths[i][1]\n the_set = set (the_path)\n flag_found = False\n for j in range (len (final_paths_sets)):\n old_set = final_paths_sets[j]\n if the_set <= old_set:\n final_paths_indexs[j].add(i)\n flag_found = True\n elif the_set > old_set:\n final_paths_sets[j] = the_set\n final_paths_indexs[j].add(i)\n flag_found = True\n if not flag_found:\n final_paths_sets.append (the_set)\n final_paths_indexs.append ({i})\n\ntemp_final_paths_sets = [final_paths_sets[0]]\ntemp_final_paths_indexs = [final_paths_indexs[0]]\n\nfor temp1 in range(1, len(final_paths_sets)):\n new_set = final_paths_sets[temp1]\n flag_found = False\n for temp2 in range(len(temp_final_paths_sets)):\n old_set = temp_final_paths_sets[temp2]\n if new_set == old_set:\n temp_final_paths_indexs[temp2] |= final_paths_indexs[temp1]\n flag_found = True\n # elif new_set > old_set:\n # temp_final_paths_sets[temp2] = new_set\n # temp_final_paths_indexs[temp2] += final_paths_indexs[temp1]\n # flag_found = True\n if not flag_found:\n temp_final_paths_sets.append (new_set)\n temp_final_paths_indexs.append (final_paths_indexs[temp1])\n\nprint(\"\\nFinal paths: \")\n\nfinal_paths_indexs = temp_final_paths_indexs\nfinal_paths_sets = temp_final_paths_sets\n\nfor indexs_list in final_paths_indexs:\n the_path = [paths[m] for m in indexs_list]\n the_avgbf = [paths[m][0] for m in indexs_list]\n final_paths.append (the_path[the_avgbf.index (max (the_avgbf))])\n\nfinal_paths.sort(reverse=True)\npaths.sort(reverse=True)\nfor p in final_paths:\n print(p)\n\nwrite_path_file(path=output_file, infor=final_paths)\nwrite_path_file(path=all_output_file, infor=paths)\n\n","repo_name":"c235gsy/scTrack","sub_path":"get_paths.py","file_name":"get_paths.py","file_ext":"py","file_size_in_byte":9688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29516128419","text":"from pico2d import*\nimport threading\n\n\nclass Map:\n def __init__(self):\n self.image = load_image('map.png')\n\n def draw(self):\n self.image.draw(VIEW_WIDTH/2, VIEW_HEIGHT/2)\n\n\nclass Wall:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.SIZE = 64\n self.image = load_image('wall.png')\n\n def update(self):\n self.image.x = self.x * TILESIZE\n self.image.y = self.y * TILESIZE\n\n def draw(self):\n self.image.clip_draw(0, 0, 64, 64, self.image.x, self.image.y)\n\n\nclass Weapon:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.frame2 = 0\n self.SIZE = 64\n self.frame = 0\n self.unit = load_image('weapon.png')\n\n def move(self, dx=0, dy=0):\n self.x += player.move(dx)\n self.y += player.move(dy)\n\n def idle_update(self):\n self.frame = (self.frame + 1) % 4\n threading.Timer(0.3, self.idle_update).start()\n\n def update(self):\n self.unit.x = self.x * TILESIZE\n self.unit.y = self.y * TILESIZE\n if way:\n self.frame2 = 64\n else:\n self.frame2 = 0\n\n def draw(self):\n self.unit.clip_draw(self.frame * self.SIZE, self.frame2, 64, 64, self.unit.x, self.unit.y)\n\n\nclass Player:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.frame2 = 0\n self.SIZE = 64\n self.frame = 0\n self.unit = load_image('player_idle2.png')\n self.unit2 = load_image('weapon.png')\n\n def move(self, dx=0, dy=0):\n self.x += dx\n self.y += dy\n\n def wall(self):\n pass\n\n def idle_update(self):\n self.frame = (self.frame + 1) % 4\n threading.Timer(0.3, self.idle_update).start()\n\n def update(self):\n self.unit.x = self.x * TILESIZE\n self.unit.y = self.y * TILESIZE\n self.unit2.x = self.x * TILESIZE\n self.unit2.y = self.y * TILESIZE\n if way:\n self.frame2 = 64\n else:\n self.frame2 = 0\n\n def draw(self):\n self.unit.clip_draw(self.frame * self.SIZE, self.frame2, 64, 64, self.unit.x, self.unit.y)\n\n def weapon_draw(self):\n self.unit2.clip_draw(0, 0, 64, 64, self.unit2.x + TILESIZE/3, self.unit2.y - TILESIZE/8)\n\n\nclass Mouse:\n def __init__(self, x, y):\n hide_cursor()\n self.x = x\n self.y = y\n self.image = load_image(\"mouse.png\")\n\n def move(self, dx=0, dy=0):\n self.x = dx\n self.y = dy\n\n def update(self):\n self.image.x = self.x\n self.image.y = self.y\n\n def draw(self):\n self.image.draw(self.image.x, self.image.y)\n\n\ndef handle_events():\n global running\n global way\n global x, y\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n running = False\n elif event.type == SDL_MOUSEMOTION:\n mouse.move(dx=event.x, dy=VIEW_HEIGHT-1-event.y)\n elif event.type == SDL_KEYDOWN:\n if event.key == SDLK_a:\n player.move(dx=-1)\n way = True\n elif event.key == SDLK_d:\n player.move(dx=+1)\n way = False\n elif event.key == SDLK_w:\n player.move(dy=+1)\n if way:\n way = True\n elif not way:\n way = False\n elif event.key == SDLK_s:\n player.move(dy=-1)\n elif event.key == SDLK_ESCAPE:\n running = False\n\n\nclass Time:\n def __init__(self):\n pass\n\n def new(self):\n pass\n\n def update(self):\n pass\n\n\nVIEW_WIDTH = 1024\nVIEW_HEIGHT = 768\n\nFPS = 60\nTILESIZE = 64\nopen_canvas(VIEW_WIDTH, VIEW_HEIGHT)\nplayer = Player((VIEW_WIDTH/2)/TILESIZE, (VIEW_HEIGHT/2)/TILESIZE)\nway = True\nrunning = True\ndirt = Map()\nwall = Wall(100, 100)\nplayer.idle_update()\nmouse = Mouse(100, 100)\nweapon = Weapon((VIEW_WIDTH/2)/TILESIZE, (VIEW_HEIGHT/2)/TILESIZE)\n\nwhile running:\n main()\n handle_events()\n player.update()\n mouse.update()\n wall.update()\n clear_canvas()\n dirt.draw()\n mouse.draw()\n player.draw()\n player.weapon_draw()\n wall.draw()\n update_canvas()\n\n\n\n\n\n\nclose_canvas()","repo_name":"ryng-un-kim/2DGP","sub_path":"Project_Cave/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"21747093864","text":"'''\n# breif : \n# history : guo created 20210126\n# detail :\n 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。\n\n 示例 1:\n\n 输入: 121\n 输出: true\n 示例 2:\n\n 输入: -121\n 输出: false\n 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。\n 示例 3:\n\n 输入: 10\n 输出: false\n 解释: 从右向左读, 为 01 。因此它不是一个回文数。\n\n 来源:力扣(LeetCode)\n 链接:https://leetcode-cn.com/problems/palindrome-number\n 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n# note : 思路:\n# step1: 剔除异常 负数和0\n step2: 讲int转为str 然后首尾第i个所有对应相等,则为回文数\n\n'''\nclass Solution(object):\n def isPalindrome(self, x):\n if x < 0:\n return False\n elif x == 0:\n return True\n else:\n str_x = str(x)\n for i in range(len(str_x)):\n if str_x[i] != str_x[len(str_x)-1-i]:\n return False\n return True\nif __name__ == '__main__':\n import unittest\n class Test(unittest.TestCase):\n def test_all_case(self):\n S = Solution()\n # test 1:\n print( S.isPalindrome(121) )\n self.assertEqual(S.isPalindrome(121) , True)\n # test 2:\n print( S.isPalindrome(-121) )\n self.assertEqual(S.isPalindrome(-121) , False)\n # test 3:\n print( S.isPalindrome(10) )\n self.assertEqual(S.isPalindrome(10) , False)\n unittest.main()\n","repo_name":"grb2015/leetcode","sub_path":"simple_execise/9_palindrome-number.py","file_name":"9_palindrome-number.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"17701253081","text":"# -*- coding: utf-8 -*-\nimport os\nfrom flask import Flask, url_for, redirect, render_template, request, abort\nimport pymysql\n#from db_config import mysql\nfrom flask import jsonify\nfrom flask import flash, request\nfrom werkzeug import generate_password_hash, check_password_hash\nfrom functools import update_wrapper\nimport json\nfrom flaskext.mysql import MySQL\nfrom flask_cors import CORS, cross_origin\n\n\ndef crossdomain(origin=None, methods=None, headers=None,\n\t\t\t\tmax_age=21600, attach_to_all=True,\n\t\t\t\tautomatic_options=True):\n\tif methods is not None:\n\t\tmethods = ', '.join(sorted(x.upper() for x in methods))\n\tif headers is not None and not isinstance(headers, basestring):\n\t\theaders = ', '.join(x.upper() for x in headers)\n\tif not isinstance(origin, basestring):\n\t\torigin = ', '.join(origin)\n\tif isinstance(max_age, timedelta):\n\t\tmax_age = max_age.total_seconds()\n\n\tdef get_methods():\n\t\tif methods is not None:\n\t\t\treturn methods\n\n\t\toptions_resp = current_app.make_default_options_response()\n\t\treturn options_resp.headers['allow']\n\n\tdef decorator(f):\n\t\tdef wrapped_function(*args, **kwargs):\n\t\t\tif automatic_options and request.method == 'OPTIONS':\n\t\t\t\tresp = current_app.make_default_options_response()\n\t\t\telse:\n\t\t\t\tresp = make_response(f(*args, **kwargs))\n\t\t\tif not attach_to_all and request.method != 'OPTIONS':\n\t\t\t\treturn resp\n\n\t\t\th = resp.headers\n\n\t\t\th['Access-Control-Allow-Origin'] = origin\n\t\t\th['Access-Control-Allow-Methods'] = get_methods()\n\t\t\th['Access-Control-Max-Age'] = str(max_age)\n\t\t\tif headers is not None:\n\t\t\t\th['Access-Control-Allow-Headers'] = headers\n\t\t\treturn resp\n\n\t\tf.provide_automatic_options = False\n\t\treturn update_wrapper(wrapped_function, f)\n\treturn decorator\n\nmysql = MySQL()\n\n# MySQL configurations\n\n# Create Flask application\napp = Flask(__name__)\napp.config['MYSQL_DATABASE_USER'] = 'magbangla'\napp.config['MYSQL_DATABASE_PASSWORD'] = 'password'\napp.config['MYSQL_DATABASE_DB'] = 'mti777'\napp.config['MYSQL_DATABASE_HOST'] = 'db4free.net'\nmysql.init_app(app)\napp.config['CORS_HEADERS'] = 'application/json'\ncors = CORS(app, resources={r\"/getall\": {\"origins\": \"*\"},r\"/rescherche\": {\"origins\": \"*\"}})\napp.config['CORS_HEADERS'] = 'Content-Type'\n@app.route('/', methods=['GET'])\ndef index():\n\treturn \"API WORKS\"\n\n@app.route('/getall', methods=['GET','OPTIONS'])\n@cross_origin(origin='*',headers=['Content-Type','Authorization'])\ndef getall():\n\ttry:\n\t\tsql = \"SELECT * FROM annonces ORDER BY loyer ASC\"\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor(pymysql.cursors.DictCursor)\n\t\tcursor.execute(sql)\n\t\trows = cursor.fetchall()\n\t\tphotos_=None\n\t\tdata=[]\n\t\tfor l in rows:\n\t\t\tdata_row={\"id_annonces\":l[\"id_annonces\"],\n\t\t\t\t\t\"titre_annonce\":l[\"titre_annonce\"],\n\t\t\t\t\t\"adresse\":l[\"adresse\"],\n\t\t\t\t\t\"loyer\":l[\"loyer\"],\n\t\t\t\t\t\"details\":l[\"details\"],\n\t\t\t\t\t\"url_annonce\":l[\"url_annonce\"],\n\t\t\t\t\t\"disponibilite\":l[\"disponibilite\"],\n\t\t\t\t\t\"thumbnail_url\":l[\"thumb\"]\n\t\t\t}\n\t\t\tdata.append(data_row)\n\t\tresp = jsonify(data)\n\t\tresp.status_code = 200\n\t\t#return resp\n\t\treturn resp\n\texcept Exception as e:\n\t\tprint(e)\n\tfinally:\n\t\tcursor.close()\n\t\tconn.close()\n\n@app.route('/recherche', methods=['POST','OPTIONS'])\n@cross_origin(origin='*',headers=['Content-Type','Authorization'])\ndef recherche():\n\tdata=request.json\n\tdata['type_de_chambre']=\"\"\n\t#constituer le sql de la requête\n\tsql = \"SELECT * FROM annonces WHERE \"\n\tif data[\"adresse\"]!=\"\":\n\t param1=\"adresse like '%\"+str(data[\"adresse\"])+\"%'\"\n\t sql=sql+param1+\" AND \"\n\tif data[\"type_de_chambre\"]!=\"\":\n\t param2=\"type_chambre= \"+str(data[\"type_de_chambre\"])\n\t sql=sql+param2+ \" AND \"\n\tif data[\"loyer\"]!=\"\":\n\t param3=\"loyer BETWEEN \"+str(data[\"loyer\"][0])+\" AND \"+ str(data[\"loyer\"][1])\n\t sql=sql+ param3 +\" ORDER BY loyer ASC\"\n\tprint(sql)\n\ttry:\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor(pymysql.cursors.DictCursor)\n\t\tcursor.execute(sql)\n\t\trows = cursor.fetchall()\n\t\tprint (rows)\n\t\tphotos_=None\n\t\tdata=[]\n\n\t\tfor l in rows:\n\t\t\tid=l['id_annonces']\n\t\t\tsql_=sql = \"SELECT * FROM photos WHERE photos.id_annonce= '\"+id+\"'\"\n\t\t\tcursor.execute(sql_)\n\t\t\trows_photos = cursor.fetchall()\n\t\t\tphotos_object=[]\n\t\t\tfor ph in rows_photos:\n\t\t\t\tstg_photos={\"url_images\":ph[\"url_images\"]}\n\t\t\t\tphotos_object.append(stg_photos)\n\t\t\tdata_row={\"id_annonces\":l[\"id_annonces\"],\n\t\t\t\t\t\t\"titre_annonce\":l[\"titre_annonce\"],\n\t\t\t\t\t\t\"adresse\":l[\"adresse\"],\n\t\t\t\t\t\t\"loyer\":l[\"loyer\"],\n\t\t\t\t\t\t\"details\":l[\"details\"],\n\t\t\t\t\t\t\"url_annonce\":l[\"url_annonce\"],\n\t\t\t\t\t\t\"disponibilite\":l[\"disponibilite\"],\n\t\t\t\t\t\t\"photos\":photos_object\n\t\t\t}\n\t\t\tdata.append(data_row)\n\t\tresp = jsonify(data)\n\t\tresp.status_code = 200\n\t\t#return resp\n\t\treturn resp\n\texcept Exception as e:\n\t\tprint(e)\n\tfinally:\n\t\tcursor.close()\n\t\tconn.close()\n\n@app.route('/getphotos/', methods=['GET'])\ndef getphotos(annonce):\n\ttry:\n\t\tsql = \"SELECT * FROM photos WHERE photos.id_annonce = '\"+annonce+\"'\"\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor(pymysql.cursors.DictCursor)\n\t\tcursor.execute(sql)\n\t\trows_photos = cursor.fetchall()\n\t\tphotos_object=[]\n\t\tfor ph in rows_photos:\n\t\t\tstg_photos={\"url_images\":ph[\"url_images\"]}\n\t\t\tphotos_object.append(stg_photos)\n\t\tresp = jsonify(photos_object)\n\t\tresp.status_code = 200\n\t\t#return resp\n\t\treturn resp\n\texcept Exception as e:\n\t\tprint(e)\n\tfinally:\n\t\tcursor.close()\n\t\tconn.close()\n\n@app.route('/getdetails/', methods=['POST'])\ndef getdetails():\n\ttry:\n\t\tsql = \"SELECT * FROM annonces ORDER BY loyer ASC\"\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor(pymysql.cursors.DictCursor)\n\t\tcursor.execute(sql)\n\t\trows = cursor.fetchall()\n\t\tphotos_=None\n\t\tdata=[]\n\t\tfor l in rows:\n\t\t\tid=l['id_annonces']\n\t\t\tsql_=sql = \"SELECT * FROM photos WHERE photos.id_annonce= '\"+id+\"'\"\n\t\t\tcursor.execute(sql_)\n\t\t\trows_photos = cursor.fetchall()\n\t\t\tphotos_object=[]\n\t\t\tfor ph in rows_photos:\n\t\t\t\tstg_photos={\"url_images\":ph[\"url_images\"]}\n\t\t\t\tphotos_object.append(stg_photos)\n\t\t\tdata_row={\"id_annonces\":l[\"id_annonces\"],\n\t\t\t\t\t\"titre_annonce\":l[\"titre_annonce\"],\n\t\t\t\t\t\"adresse\":l[\"adresse\"],\n\t\t\t\t\t\"loyer\":l[\"loyer\"],\n\t\t\t\t\t\"details\":l[\"details\"],\n\t\t\t\t\t\"url_annonce\":l[\"url_annonce\"],\n\t\t\t\t\t\"disponibilite\":l[\"disponibilite\"],\n\t\t\t\t\t\"thumbnail_url\":l[\"thumb\"],\n\t\t\t\t\t\"photos\":photos_object\n\t\t\t}\n\t\t\tdata.append(data_row)\n\t\tresp = jsonify(data)\n\t\tresp.status_code = 200\n\t\t#return resp\n\t\treturn resp\n\texcept Exception as e:\n\t\tprint(e)\n\tfinally:\n\t\tcursor.close()\n\t\tconn.close()\n\nif __name__ == '__main__':\n\t# Start app\n\tapp.run(debug=True,port=\"5891\")\n","repo_name":"magbangla/mti777-session","sub_path":"API/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27425759186","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(int(1e5))\ndef dfs(x,depth): # 루트 부터 시작해서 깊이를 구하는 함수\n c[x] = True\n d[x] = depth\n\n for i in graph[x]:\n if c[i]:\n continue\n parent[i][0] = x\n dfs(i,depth+1)\n\ndef set_parent(): # 전체 부모의 관계 설정\n dfs(1,0) # 루트노드\n for i in range(1,LOG):\n for j in range(1,v+1):\n parent[j][i] = parent[parent[j][i-1]][i-1]\n\ndef lca(a,b): # 최소 공통 조상\n if d[a] > d[b]: # b가 더 깊도록 설정\n a,b = b,a\n for i in range(LOG-1,-1,-1): # 깊이가 동일 하도록 맞춰줌\n if d[b] -d[a] >= (1< %s\" % (id(self), self.type)\n return(s)\n\n\nclass ClassifyByTarget(C274):\n def __init__(self, lw=[]):\n # FIXME: Call superclass, here and for all classes\n self.type = str(self.__class__)\n self.allWords = 0\n self.theCount = 0\n self.nonTarget = []\n self.set_target_words(lw)\n self.initTF()\n return\n\n def initTF(self):\n self.TP = 0\n self.FP = 0\n self.TN = 0\n self.FN = 0\n return\n\n def get_TF(self):\n return(self.TP, self.FP, self.TN, self.FN)\n\n # FIXME: Use Python properties\n # https://www.python-course.eu/python3_properties.php\n def set_target_words(self, lw):\n # Could also do self.targetWords = lw.copy(). Thanks, TA Jason Cannon\n self.targetWords = copy.deepcopy(lw)\n return\n\n def get_target_words(self):\n return(self.targetWords)\n\n def get_allWords(self):\n return(self.allWords)\n\n def incr_allWords(self):\n self.allWords += 1\n return\n\n def get_theCount(self):\n return(self.theCount)\n\n def incr_theCount(self):\n self.theCount += 1\n return\n\n def get_nonTarget(self):\n return(self.nonTarget)\n\n def add_nonTarget(self, w):\n self.nonTarget.append(w)\n return\n\n def print_config(self):\n print(\"-------- Print Config --------\")\n ln = len(self.get_target_words())\n print(\"TargetWords Hardcoded (%d): \" % ln, end='')\n print(self.get_target_words())\n return\n\n def print_run_info(self):\n print(\"-------- Print Run Info --------\")\n print(\"All words:%3s. \" % self.get_allWords(), end='')\n print(\" Target words:%3s\" % self.get_theCount())\n print(\"Non-Target words (%d): \" % len(self.get_nonTarget()), end='')\n print(self.get_nonTarget())\n return\n\n def print_confusion_matrix(self, targetLabel, doKey=False, tag=\"\"):\n assert (self.TP + self.TP + self.FP + self.TN) > 0\n print(tag+\"-------- Confusion Matrix --------\")\n print(tag+\"%10s | %13s\" % ('Predict', 'Label'))\n print(tag+\"-----------+----------------------\")\n print(tag+\"%10s | %10s %10s\" % (' ', targetLabel, 'not'))\n if doKey:\n print(tag+\"%10s | %10s %10s\" % ('', 'TP ', 'FP '))\n print(tag+\"%10s | %10d %10d\" % (targetLabel, self.TP, self.FP))\n if doKey:\n print(tag+\"%10s | %10s %10s\" % ('', 'FN ', 'TN '))\n print(tag+\"%10s | %10d %10d\" % ('not', self.FN, self.TN))\n return\n\n def eval_training_set(self, tset, targetLabel):\n print(\"-------- Evaluate Training Set --------\")\n self.initTF()\n z = zip(tset.get_instances(), tset.get_lines())\n for ti, w in z:\n lb = ti.get_label()\n cl = ti.get_class()\n if lb == targetLabel:\n if cl:\n self.TP += 1\n outcome = \"TP\"\n else:\n self.FN += 1\n outcome = \"FN\"\n else:\n if cl:\n self.FP += 1\n outcome = \"FP\"\n else:\n self.TN += 1\n outcome = \"TN\"\n explain = ti.get_explain()\n print(\"TW %s: ( %10s) %s\" % (outcome, explain, w))\n if Debug:\n print(\"-->\", ti.get_words())\n self.print_confusion_matrix(targetLabel)\n return\n\n def classify_by_words(self, ti, update=False, tlabel=\"last\"):\n inClass = False\n evidence = ''\n lw = ti.get_words()\n for w in lw:\n if update:\n self.incr_allWords()\n if w in self.get_target_words(): # FIXME Write predicate\n inClass = True\n if update:\n self.incr_theCount()\n if evidence == '':\n evidence = w # FIXME Use first word, but change\n elif w != '':\n if update and (w not in self.get_nonTarget()):\n self.add_nonTarget(w)\n if evidence == '':\n evidence = '#negative'\n if update:\n ti.set_class(inClass, tlabel, evidence)\n return(inClass, evidence)\n\n # Could use a decorator, but not now\n def classify(self, ti, update=False, tlabel=\"last\"):\n cl, e = self.classify_by_words(ti, update, tlabel)\n return(cl, e)\n\n\n# Define new class which is a subclass of ClassifyByTarget\nclass ClassifyByTopN(ClassifyByTarget):\n # Initialize this class and let it inherit all the attributes of\n # ClassifyByTarget\n def __init__(self, lw=[]):\n self.type = str(self.__class__)\n super().__init__(lw)\n return\n\n # In a given training set (tset), this method will find the top num\n # most frequent words whose label matches the given label (label)\n def target_top_n(self, tset, num=5, label=''):\n # initialize dictionary to store count of each word\n counts = {}\n # loop through the whole training set\n for ti in tset.get_instances():\n # if a given training instance has the desired label, we are\n # interested in all the words in that list\n if ti.inst[\"label\"] == label:\n # iterate over the training instances and count how many times\n # each unique word occurs\n for word in ti.inst[\"words\"]:\n # if word is new, set its count to 1\n if word not in counts:\n counts[word] = 1\n # if word already exists in dictionary, increment its\n # count by 1\n else:\n counts[word] += 1\n # initialize list to store count values\n count_list = []\n # loop through dictionary keys\n for x in counts:\n # add *unique* count values to count_list\n if counts[x] not in count_list:\n count_list.append(counts[x])\n # create a sub list containing the top num count values from the\n # dictionary\n temp = sorted(count_list, reverse = True)[:num]\n # initialize list to contain top num most frequent words, including\n # ties\n top_words = []\n # iterate over dictionary keys\n for y in counts:\n # check if the count value of each unique word is in the list of\n # the num highest counts. If so, append that word to top_words\n if counts[y] in temp:\n top_words.append(y)\n # update target words so that they only consist of the top num most\n # common words\n self.set_target_words(top_words)\n return\n\n\nclass TrainingInstance(C274):\n def __init__(self):\n self.type = str(self.__class__)\n self.inst = dict()\n # FIXME: Get rid of dict, and use attributes\n self.inst[\"label\"] = \"N/A\" # Class, given by oracle\n self.inst[\"words\"] = [] # Bag of words\n self.inst[\"class\"] = \"\" # Class, by classifier\n self.inst[\"explain\"] = \"\" # Explanation for classification\n self.inst[\"experiments\"] = dict() # Previous classifier runs\n return\n\n def get_label(self):\n return(self.inst[\"label\"])\n\n def get_words(self):\n return(self.inst[\"words\"])\n\n def set_class(self, theClass, tlabel=\"last\", explain=\"\"):\n # tlabel = tag label\n self.inst[\"class\"] = theClass\n self.inst[\"experiments\"][tlabel] = theClass\n self.inst[\"explain\"] = explain\n return\n\n def get_class_by_tag(self, tlabel): # tlabel = tag label\n cl = self.inst[\"experiments\"].get(tlabel)\n if cl is None:\n return(\"N/A\")\n else:\n return(cl)\n\n def get_explain(self):\n cl = self.inst.get(\"explain\")\n if cl is None:\n return(\"N/A\")\n else:\n return(cl)\n\n def get_class(self):\n return self.inst[\"class\"]\n\n def process_input_line(\n self, line, run=None,\n tlabel=\"read\", inclLabel=True\n ):\n for w in line.split():\n if w[0] == \"#\":\n self.inst[\"label\"] = w\n # FIXME: For testing only. Compare to previous version.\n if inclLabel:\n self.inst[\"words\"].append(w)\n else:\n self.inst[\"words\"].append(w)\n\n if not (run is None):\n cl, e = run.classify(self, update=True, tlabel=tlabel)\n return(self)\n\n def lowercase(self):\n # using list comprehension, turn each word in the training instance\n # to a fully lowercase word\n self.inst[\"words\"] = [x.lower() for x in self.inst[\"words\"]]\n return(self)\n\n def remove_symbols(self):\n # initialize list that will contain the amended strings\n new_words = []\n # This for loop iterates over each training instance\n for x in self.inst[\"words\"]:\n # This for loop iterates over each string in each training\n # instance\n for y in x:\n # if the character is neither a digit nor a letter, remove it\n if not (y.isdigit() or y.isalpha()):\n x = x.replace(y, \"\")\n # add updated string to new_words\n new_words.append(x)\n # update the training instance with the new list of modified words\n self.inst[\"words\"] = new_words\n return(self)\n\n def remove_numbers(self):\n # initialize list that will contain the amended strings\n new_words = []\n # This for loop iterates over the training instance\n for x in self.inst[\"words\"]:\n # If the string is entirely numeric, it will not be changed\n if not x.isdigit():\n # This for loop iterates over each string that is not entirely\n # numeric\n for y in x:\n # Remove the digits in each string\n if y.isdigit():\n x = x.replace(y, \"\")\n # Add strings to new_words\n new_words.append(x)\n # update the training instance with the new list of modified words\n self.inst[\"words\"] = new_words\n return(self)\n\n def remove_stops(self):\n # A given list containing all the stopwords\n stopwords = [\"i\", \"me\", \"my\", \"myself\", \"we\", \"our\", \"ours\", \"ourselves\",\n \"you\", \"your\", \"yours\", \"yourself\", \"yourselves\", \"he\", \"him\", \"his\",\n \"himself\", \"she\", \"her\", \"hers\", \"herself\", \"it\", \"its\", \"itself\",\n \"they\", \"them\", \"their\", \"theirs\", \"themselves\", \"what\", \"which\",\n \"who\", \"whom\", \"this\", \"that\", \"these\", \"those\", \"am\", \"is\", \"are\",\n \"was\", \"were\", \"be\",\"been\", \"being\", \"have\", \"has\", \"had\", \"having\",\n \"do\", \"does\", \"did\", \"doing\", \"a\", \"an\",\"the\", \"and\", \"but\", \"if\",\n \"or\", \"because\", \"as\", \"until\", \"while\", \"of\", \"at\", \"by\", \"for\",\n \"with\", \"about\", \"against\", \"between\", \"into\", \"through\", \"during\",\n \"before\", \"after\", \"above\", \"below\", \"to\", \"from\", \"up\", \"down\", \"in\",\n \"out\", \"on\", \"off\", \"over\", \"under\", \"again\", \"further\", \"then\",\n \"once\", \"here\", \"there\", \"when\", \"where\", \"why\", \"how\", \"all\", \"any\",\n \"both\", \"each\", \"few\", \"more\", \"most\", \"other\", \"some\", \"such\", \"no\",\n \"nor\", \"not\", \"only\", \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"s\",\n \"t\", \"can\", \"will\", \"just\", \"don\", \"should\", \"now\"]\n # initialize list that will contain the desired strings\n new_words = []\n # This for loop iterates over the training instance\n for x in self.inst[\"words\"]:\n # Keep all the strings in the training instance that are not\n # also in stopwords\n if x not in stopwords:\n # Add them to new_words\n new_words.append(x)\n # update training instance with new list of modified words\n self.inst[\"words\"] = new_words\n return(self)\n\n def preprocess_words(self, mode=''):\n # depending on the value of mode, invoke the appropriate methods to\n # transform the training instance in the desired way\n if mode == \"keep-digits\":\n self.lowercase().remove_symbols().remove_stops()\n elif mode == \"keep-stops\":\n self.lowercase().remove_symbols().remove_numbers()\n elif mode == \"keep-symbols\":\n self.lowercase().remove_numbers().remove_stops()\n else:\n self.lowercase().remove_symbols().remove_numbers().remove_stops()\n return(self.inst[\"words\"])\n\nclass TrainingSet(C274):\n def __init__(self):\n self.type = str(self.__class__)\n self.inObjList = [] # Unparsed lines, from training set\n self.inObjHash = [] # Parsed lines, in dictionary/hash\n return\n\n def get_instances(self):\n return(self.inObjHash) # FIXME Should protect this more\n\n def get_lines(self):\n return(self.inObjList) # FIXME Should protect this more\n\n def print_training_set(self):\n print(\"-------- Print Training Set --------\")\n z = zip(self.inObjHash, self.inObjList)\n for ti, w in z:\n lb = ti.get_label()\n cl = ti.get_class_by_tag(\"last\") # Not used\n explain = ti.get_explain()\n print(\"( %s) (%s) %s\" % (lb, explain, w))\n if Debug:\n print(\"-->\", ti.get_words())\n return\n\n def process_input_stream(self, inFile, run=None):\n assert not (inFile is None), \"Assume valid file object\"\n cFlag = True\n while cFlag:\n line, cFlag = safe_input(inFile)\n if not cFlag:\n break\n assert cFlag, \"Assume valid input hereafter\"\n\n # Check for comments\n if line[0] == '%': # Comments must start with %\n continue\n\n # Save the training data input, by line\n self.inObjList.append(line)\n # Save the training data input, after parsing\n ti = TrainingInstance()\n ti.process_input_line(line, run=run)\n self.inObjHash.append(ti)\n return\n\n def preprocess(self, mode=''):\n # this method invokes the method preprocess_words from class\n # TrainingInstance and invokes it on the whole training set,\n # according to the specified mode. This preprocesses all training\n # instances in a given training set \n for x in self.inObjHash:\n x.preprocess_words(mode=mode)\n return\n\n def return_nfolds(self, num=3):\n # initialize list that will contain the folds created\n fold_list = []\n # this for loop iterates once for each fold desired, creating a\n # deepcopy of the original training set, but emtpying the inObjList and\n # inObjHash attributes of each one\n for n in range(num):\n t_s = copy.deepcopy(self)\n t_s.inObjList = []\n t_s.inObjHash = []\n fold_list.append(t_s)\n # flag for while loop\n flag = 1\n # initialize counter for indexing purposes\n counter = 0\n # this while loop executes until it reaches the end of the training\n # set\n while flag:\n # this for loop divides the original training set into num folds\n # in a \"round robin\" fashion\n for x in range(num):\n # check if end of training set is reached. if so, break out\n # of for loop\n if counter >= (len(self.inObjList)-1):\n break\n fold_list[x].inObjList.append(self.inObjList[counter])\n fold_list[x].inObjHash.append(self.inObjHash[counter])\n # increment indexing value\n counter+=1\n # exit while loop when end of training set is reached\n flag = 0\n # return list of folds, each fold being an object of class trainin\n # set \n return(fold_list)\n\n def copy(self):\n # using deepcopy, create a copy of the original training set \n t_s = copy.deepcopy(self)\n # return it\n return(t_s)\n\n def add_fold(self, tset):\n # create copy of given training set (fold) using deepcopy\n temp = copy.deepcopy(tset)\n # iterate for the length inObjList (same as length of inObjHash)\n for x in range(len(temp.inObjList)):\n # append each training instance of tset to the training set\n self.inObjList.append(temp.inObjList[x])\n self.inObjHash.append(temp.inObjHash[x])\n return\n\n\ndef basemain():\n tset = TrainingSet()\n run1 = ClassifyByTarget(TargetWords)\n print(run1) # Just to show __str__\n lr = [run1]\n print(lr) # Just to show __repr__\n\n argc = len(sys.argv)\n if argc == 1: # Use stdin, or default filename\n inFile = open_file()\n assert not (inFile is None), \"Assume valid file object\"\n tset.process_input_stream(inFile, run1)\n inFile.close()\n else:\n for f in sys.argv[1:]:\n inFile = open_file(f)\n assert not (inFile is None), \"Assume valid file object\"\n tset.process_input_stream(inFile, run1)\n inFile.close()\n\n if Debug:\n tset.print_training_set()\n run1.print_config()\n run1.print_run_info()\n run1.eval_training_set(tset, '#weather')\n\n return\n\n\nif __name__ == \"__main__\":\n basemain()","repo_name":"gurbirsandha/OO-Classifier-Python","sub_path":"ooclassifier.py","file_name":"ooclassifier.py","file_ext":"py","file_size_in_byte":19152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"32031824486","text":"import requests\nimport re\nimport json\nimport time\nfrom datetime import datetime,timezone\nimport config_handler\n\nwith open(\"list.txt\", \"r\") as urlListRaw:\n urlListLines = urlListRaw.readlines()\nurlList = list(map(str.strip, urlListLines))\n\nutc_time = datetime.now(timezone.utc).strftime(\"%Y-%m-%d_%H-%M-%S\")\n\nin_stock_list = []\n\nstock_delay = config_handler.read(\"config.cfg\",\"stock\",\"stock_delay\")\nrequest_fail_delay = config_handler.read(\"config.cfg\",\"stock\",\"request_fail_delay\")\n\ndef stock_checker(url):\n convert_url = re.sub(\"(? y_resolution:\r\n self.sq_x = new_pos\r\n self.sq_y = -200\r\n\r\n if Player_sprite.sprite_y < self.sq_y + 35:\r\n if Player_sprite.sprite_x + (img_width * .65) > self.sq_x > Player_sprite.sprite_x - (img_width * .25):\r\n Player_sprite.sprite_x = x_resolution * .0001\r\n Player_sprite.sprite_y = y_resolution * .845\r\n score = 0\r\n \r\n if direction is 'up':\r\n self.sq_y -= sq_movingBLOCKSPEED * speed\r\n if self.sq_y < -200:\r\n self.sq_x = new_pos\r\n self.sq_y = y_resolution\r\n\r\n if direction is 'left':\r\n self.sq_x += sq_movingBLOCKSPEED * speed\r\n if self.sq_x > x_resolution:\r\n self.sq_x = -200\r\n self.sq_y = new_pos\r\n\r\n if direction is 'right':\r\n self.sq_x -= sq_movingBLOCKSPEED * speed\r\n if self.sq_x < 0:\r\n self.sq_x = 1400\r\n self.sq_y = new_pos\r\n\r\n def bouncing_square(self, speed, tf, tf2):\r\n \r\n rect_object = ((self.sq_x, self.sq_y), (self.sq_width, self.sq_height))\r\n\r\n game_display.fill(self.sq_color, rect_object)\r\n \r\n if self.sq_x < x_resolution and self.sq_y < y_resolution:\r\n\r\n if tf is True: \r\n self.sq_x += self.sq_movingBLOCKSPEED_x * speed\r\n self.sq_y += self.sq_movingBLOCKSPEED_y * speed\r\n if self.sq_x > x_resolution - 35: \r\n self.sq_movingBLOCKSPEED_x = -8 \r\n if self.sq_x < 0: \r\n self.sq_movingBLOCKSPEED_x = 8 \r\n if self.sq_y > y_resolution - 35: \r\n self.sq_movingBLOCKSPEED_y = -8 \r\n if self.sq_y < 0:\r\n self.sq_movingBLOCKSPEED_y = 8 \r\n else:\r\n self.sq_x -= self.sq_movingBLOCKSPEED_x * speed\r\n self.sq_y -= self.sq_movingBLOCKSPEED_y * speed\r\n if self.sq_x > x_resolution - 35:\r\n self.sq_movingBLOCKSPEED_x = 8 \r\n if self.sq_x < 0:\r\n self.sq_movingBLOCKSPEED_x = -8 \r\n if self.sq_y > y_resolution - 35:\r\n self.sq_movingBLOCKSPEED_y = 8 \r\n if self.sq_y < 0:\r\n self.sq_movingBLOCKSPEED_y = -8\r\n\r\nclass Draw_button(Draw_square):\r\n\r\n def button(self, inactive_color, active_color, pressed_color):\r\n mouse_press = pygame.mouse.get_pressed()\r\n\r\n global new_pressed\r\n\r\n if self.sq_x + self.sq_width > mouse_pos[0] > self.sq_x and self.sq_y + self.sq_height > mouse_pos[1] > self.sq_y:\r\n inactive_color = active_color\r\n new_pressed = False\r\n if mouse_press == (1,0,0):\r\n inactive_color = pressed_color\r\n new_pressed = True\r\n else:\r\n inactive_color = inactive_color\r\n new_pressed = False\r\n\r\n rect_object = ((self.sq_x, self.sq_y), (self.sq_width, self.sq_height))\r\n game_display.fill(inactive_color, rect_object)\r\n\r\n def text_button(self, inactive_color, active_color, pressed_color, text, text_color, font_select, font_size, mov_x, mov_y):\r\n mouse_press = pygame.mouse.get_pressed()\r\n\r\n global pressed\r\n\r\n font_choice = pygame.font.Font(font_select, font_size)\r\n font = font_choice\r\n words = font.render(text, True, text_color)\r\n\r\n if self.sq_x + self.sq_width > mouse_pos[0] > self.sq_x and self.sq_y + self.sq_height > mouse_pos[1] > self.sq_y:\r\n inactive_color = active_color\r\n if mouse_press == (1, 0, 0):\r\n inactive_color = pressed_color\r\n pressed = True\r\n else:\r\n pressed = False\r\n\r\n else:\r\n inactive_color = inactive_color\r\n pressed = False\r\n\r\n rect_object = ((self.sq_x, self.sq_y), (self.sq_width, self.sq_height))\r\n game_display.fill(inactive_color, rect_object)\r\n game_display.blit(words, [self.sq_x + mov_x, self.sq_y + mov_y])\r\n\r\n\r\ndef intro_loop():\r\n\r\n while True:\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_q:\r\n quit()\r\n if event.key == pygame.K_RETURN:\r\n game_loop_func()\r\n\r\n game_display.fill(black)\r\n text_object(font1, 75, 'WANDER', white, x_resolution/2.7, y_resolution/2.4)\r\n text_object(font1, 25, 'Press \\\"Enter\\\" to begin', white, x_resolution * .075, y_resolution * .95)\r\n text_object(font1, 25, 'Press \\\"Q\\\" to exit', white, x_resolution * .75, y_resolution * .95)\r\n pygame.display.flip()\r\n\r\n\r\ndef pause_loop():\r\n\r\n paused = True\r\n\r\n while paused is True:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quit()\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_q:\r\n intro_loop()\r\n if event.key == pygame.K_p:\r\n paused = False\r\n\r\n game_display.fill(black)\r\n text_object(font1, 75, 'PAUSED', white, x_resolution/2.7, y_resolution/2.4)\r\n text_object(font1, 25, 'Press \\\"P\\\" to resume', white, x_resolution * .4, y_resolution * .6)\r\n text_object(font1, 25, 'Press \\\"Q\\\" to return to the Start Screen', white, x_resolution * .6, y_resolution * .01)\r\n pygame.display.flip()\r\n\r\n\r\ndef game_loop_func():\r\n\r\n global mouse_pos\r\n global score\r\n\r\n random_int0 = random.randrange(1, 255)\r\n\r\n player_sprite_x_change = 0\r\n player_sprite_y_change = 0\r\n\r\n game_sequence = True\r\n help_sequence = True\r\n exit_text = False\r\n \r\n quit_event = pygame.USEREVENT + 1\r\n pygame.time.set_timer(quit_event, 750)\r\n\r\n b_square0 = Draw_square(random.randrange(img_width + 50, x_resolution), 0, 35, 35, (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255)))\r\n b_square1 = Draw_square(random.randrange(img_width + 50, x_resolution), 0, 35, 35, (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255)))\r\n b_square2 = Draw_square(random.randrange(img_width + 50, x_resolution), 0, 35, 35, (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255)))\r\n b_square3 = Draw_square(random.randrange(img_width + 50, x_resolution), 0, 35, 35, (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255)))\r\n b_square4 = Draw_square(random.randrange(img_width + 50, x_resolution), 0, 35, 35, (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255)))\r\n\r\n b_button0 = Draw_button(x_resolution/2, y_resolution/2, 50, 50, white)\r\n\r\n player_sprite = Player_sprite(x_resolution * 0, y_resolution * .845, tomboy_sprite)\r\n\r\n while game_sequence is True:\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n quit()\r\n\r\n if event.type == pygame.MOUSEMOTION:\r\n mouse_pos = pygame.mouse.get_pos()\r\n\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_d:\r\n player_sprite_x_change = 5\r\n if event.key == pygame.K_a:\r\n if player_sprite.sprite_x > img_width * -.5:\r\n player_sprite_x_change = -5\r\n if event.key == pygame.K_SPACE:\r\n if Player_sprite.sprite_y > y_resolution - (img_width - 1):\r\n player_sprite_y_change = -125\r\n if event.key == pygame.K_r:\r\n Player_sprite.sprite_x = x_resolution * 0\r\n Player_sprite.sprite_y = y_resolution * .845\r\n score = 0\r\n if event.key == pygame.K_h:\r\n if help_sequence is True:\r\n help_sequence = False\r\n else:\r\n help_sequence = True\r\n if event.key == pygame.K_p: \r\n pause_loop()\r\n if event.key == pygame.K_q:\r\n exit_text = True\r\n score = 0\r\n if exit_text == True:\r\n if event.type == quit_event:\r\n game_sequence = False\r\n\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_d:\r\n player_sprite_x_change = 0\r\n if event.key == pygame.K_a:\r\n player_sprite_x_change = 0\r\n\r\n Player_sprite.sprite_x += player_sprite_x_change\r\n Player_sprite.sprite_y += player_sprite_y_change\r\n\r\n if Player_sprite.sprite_y < y_resolution:\r\n player_sprite_y_change = 5\r\n if Player_sprite.sprite_y > y_resolution - (img_width - 1) or Player_sprite.sprite_y < 0:\r\n player_sprite_y_change = 0\r\n if Player_sprite.sprite_x < img_width * -.5:\r\n player_sprite_x_change = 0\r\n if Player_sprite.sprite_x > x_resolution - (img_width * .5):\r\n Player_sprite.sprite_x = x_resolution * -.03\r\n Player_sprite.sprite_y = (y_resolution * .845)\r\n score += 1\r\n\r\n if score > 0:\r\n help_sequence = False\r\n if score >= random.randrange(5,9):\r\n random_int0 = random.randrange(1, 255)\r\n if score >= 9:\r\n random_int1 = random.randrange(1, 255)\r\n random_int2 = random.randrange(1, 255)\r\n random_int3 = random.randrange(1, 255)\r\n\r\n game_display.fill(black)\r\n\r\n b_button0.button(green, red, grey)\r\n\r\n rain_square = Draw_square(random.randrange(1, x_resolution), random.randrange(1, y_resolution), 10, 15, grey)\r\n rain_square.square()\r\n if score >= 0:\r\n b_square0.moving_square(1, random.randrange(img_width + 50, x_resolution), 'down')\r\n if b_square0.sq_y == -200 or 0:\r\n b_square0.sq_color = (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255))\r\n if score >= 3:\r\n b_square1.moving_square(1.15, random.randrange(img_width + 50, x_resolution), 'down')\r\n if b_square1.sq_y == -200:\r\n b_square1.sq_color = (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255))\r\n if score >= 5:\r\n b_square2.moving_square(1.35, random.randrange(img_width + 50, x_resolution), 'down')\r\n if b_square2.sq_y == -200:\r\n b_square2.sq_color = (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255))\r\n if score >= 7:\r\n b_square3.moving_square(1.55, random.randrange(img_width + 50, x_resolution), 'down')\r\n if b_square3.sq_y == -200:\r\n b_square3.sq_color = (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255))\r\n if score >= 10:\r\n b_square4.moving_square(1.75, random.randrange(img_width + 50, x_resolution), 'down')\r\n if b_square4.sq_y == -200:\r\n b_square4.sq_color = (random.randrange(1,255), random.randrange(1,255), random.randrange(1,255))\r\n\r\n player_sprite.place_sprite()\r\n\r\n text_object(font3, int(float(x_resolution * .02)), str(score), green, x_resolution *.98, y_resolution/80)\r\n text_object(font3, int(float(x_resolution * .02)), 'Press \\\"Q\\\" to EXIT', red, x_resolution/50, y_resolution/75)\r\n if help_sequence is True:\r\n text_object(font3, int(float(x_resolution * .02)), 'Use \\\"A\\\" and \\\"D\\\" to move!', white, x_resolution/35, y_resolution/10) \r\n text_object(font3, int(float(x_resolution * .02)), 'Press \\\"SPACE\\\" to jump!', white, x_resolution/35, y_resolution/7.5)\r\n text_object(font3, int(float(x_resolution * .017)), 'Use \\\"R\\\" to return to the start', white, x_resolution/35, y_resolution/6)\r\n text_object(font3, int(float(x_resolution * .017)), 'Use \\\"P\\\" to pause the game!', white, x_resolution/35, y_resolution/4.5)\r\n text_object(font3, int(float(x_resolution * .017)), 'BEWARE!', red, x_resolution/35, y_resolution/5.2)\r\n text_object(font3, int(float(x_resolution * .017)), 'Score will reset as well!', green, x_resolution/10, y_resolution/5.2)\r\n if Player_sprite.sprite_x < x_resolution/3 and score == 0:\r\n text_object(font3, int(float(x_resolution * .025)), 'Why is it always raining...', blue, x_resolution/20, y_resolution * .75)\r\n if exit_text is True:\r\n text_object(font3, int(float(x_resolution * .02)), 'Exiting...', red, x_resolution/50, y_resolution/25)\r\n if score < 2:\r\n text_object(font3, int(float(x_resolution * .018)), 'Press \\\"H\\\" to view controls', white, x_resolution/2, y_resolution/75)\r\n if player_sprite.sprite_x < x_resolution * -.05:\r\n text_object(font3, int(float(x_resolution * .02)), 'You can\\'t escape...', red, x_resolution/75, y_resolution/4)\r\n if 10 > score >= 5:\r\n text_object(font3, int(float(x_resolution * .03)), 'Why are you still here...', [random_int0, 0, 0], x_resolution*.3, y_resolution/2)\r\n if score >= 10:\r\n text_object(font3, int(float(x_resolution * .04)), 'I WANT TO BE ALONE', [random_int1, random_int2, random_int3], x_resolution*.3, y_resolution/2)\r\n\r\n if new_pressed is True:\r\n b_square0.sq_movingBLOCKSPEED = 0\r\n b_square1.sq_movingBLOCKSPEED = 0\r\n b_square2.sq_movingBLOCKSPEED = 0\r\n b_square3.sq_movingBLOCKSPEED = 0\r\n b_square4.sq_movingBLOCKSPEED = 0\r\n else:\r\n b_square0.sq_movingBLOCKSPEED = 8\r\n b_square1.sq_movingBLOCKSPEED = 8\r\n b_square2.sq_movingBLOCKSPEED = 8\r\n b_square3.sq_movingBLOCKSPEED = 8\r\n b_square4.sq_movingBLOCKSPEED = 8\r\n\r\n clock.tick(60)\r\n pygame.display.flip()\r\n\r\nintro_loop()\r\n","repo_name":"Mooksc/WANDER","sub_path":"wander.py","file_name":"wander.py","file_ext":"py","file_size_in_byte":16616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20202875161","text":"import logging\nfrom datetime import datetime\n\nLOG_FILE = f\"./logs/{datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}.log\"\nLOG_FORMAT = '[%(asctime)s] - %(name)s - %(levelname)s - %(message)s'\nLOGGING_LEVEL = logging.INFO\n\nlogging.basicConfig(\n filename=LOG_FILE,\n format=LOG_FORMAT,\n level=logging.INFO,\n datefmt='%Y/%m/%d %H:%M:%S'\n)\n","repo_name":"nctung4/project-based-soft-dev-ml","sub_path":"helper/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"20766559104","text":"import sys\nfrom collections import Counter\n\nimport msgspec.json\nimport pytest\n\nfrom nautilus_trader.adapters.betfair.providers import BetfairInstrumentProvider\nfrom nautilus_trader.backtest.node import BacktestNode\nfrom nautilus_trader.common.clock import LiveClock\nfrom nautilus_trader.common.logging import Logger\nfrom nautilus_trader.common.logging import LoggerAdapter\nfrom nautilus_trader.config import BacktestDataConfig\nfrom nautilus_trader.config import BacktestEngineConfig\nfrom nautilus_trader.config import BacktestRunConfig\nfrom nautilus_trader.config import ImportableStrategyConfig\nfrom nautilus_trader.config import NautilusKernelConfig\nfrom nautilus_trader.core.data import Data\nfrom nautilus_trader.model.data.tick import TradeTick\nfrom nautilus_trader.model.data.venue import InstrumentStatusUpdate\nfrom nautilus_trader.persistence.external.core import process_files\nfrom nautilus_trader.persistence.external.readers import CSVReader\nfrom nautilus_trader.persistence.streaming.writer import generate_signal_class\nfrom nautilus_trader.test_kit.mocks.data import NewsEventData\nfrom nautilus_trader.test_kit.mocks.data import data_catalog_setup\nfrom nautilus_trader.test_kit.stubs.persistence import TestPersistenceStubs\nfrom tests import TEST_DATA_DIR\nfrom tests.integration_tests.adapters.betfair.test_kit import BetfairTestStubs\n\n\n@pytest.mark.skipif(sys.platform == \"win32\", reason=\"failing on Windows\")\nclass TestPersistenceStreaming:\n def setup(self):\n self.catalog = data_catalog_setup(protocol=\"memory\", path=\"/.nautilus/catalog\") # ,\n self.fs = self.catalog.fs\n self._load_data_into_catalog()\n self._logger = Logger(clock=LiveClock())\n self.logger = LoggerAdapter(\"test\", logger=self._logger)\n\n def _load_data_into_catalog(self):\n self.instrument_provider = BetfairInstrumentProvider.from_instruments([])\n result = process_files(\n glob_path=TEST_DATA_DIR + \"/betfair/1.166564490.bz2\",\n reader=BetfairTestStubs.betfair_reader(instrument_provider=self.instrument_provider),\n instrument_provider=self.instrument_provider,\n catalog=self.catalog,\n )\n assert result\n data = (\n self.catalog.instruments(as_nautilus=True)\n + self.catalog.instrument_status_updates(as_nautilus=True)\n + self.catalog.trade_ticks(as_nautilus=True)\n + self.catalog.order_book_deltas(as_nautilus=True)\n + self.catalog.tickers(as_nautilus=True)\n )\n assert len(data) == 2535\n\n @pytest.mark.skipif(sys.platform == \"win32\", reason=\"Currently flaky on Windows\")\n def test_feather_writer(self):\n # Arrange\n instrument = self.catalog.instruments(as_nautilus=True)[0]\n\n catalog_path = \"/.nautilus/catalog\"\n\n run_config = BetfairTestStubs.betfair_backtest_run_config(\n catalog_path=catalog_path,\n catalog_fs_protocol=\"memory\",\n instrument_id=instrument.id.value,\n flush_interval_ms=5000,\n )\n\n node = BacktestNode(configs=[run_config])\n\n # Act\n backtest_result = node.run()\n\n # Assert\n result = self.catalog.read_backtest(\n backtest_run_id=backtest_result[0].instance_id,\n raise_on_failed_deserialize=True,\n )\n result = dict(Counter([r.__class__.__name__ for r in result]))\n\n expected = {\n \"AccountState\": 670,\n \"BettingInstrument\": 1,\n \"ComponentStateChanged\": 21,\n \"OrderAccepted\": 324,\n \"OrderBookDeltas\": 1077,\n \"OrderBookSnapshot\": 1,\n \"OrderFilled\": 346,\n \"OrderInitialized\": 325,\n \"OrderSubmitted\": 325,\n \"PositionChanged\": 343,\n \"PositionClosed\": 2,\n \"PositionOpened\": 3,\n \"TradeTick\": 198,\n }\n\n assert result == expected\n\n def test_feather_writer_generic_data(self):\n # Arrange\n TestPersistenceStubs.setup_news_event_persistence()\n\n process_files(\n glob_path=f\"{TEST_DATA_DIR}/news_events.csv\",\n reader=CSVReader(block_parser=TestPersistenceStubs.news_event_parser),\n catalog=self.catalog,\n )\n\n data_config = BacktestDataConfig(\n catalog_path=self.catalog.path,\n catalog_fs_protocol=\"memory\",\n data_cls=NewsEventData.fully_qualified_name(),\n client_id=\"NewsClient\",\n )\n # Add some arbitrary instrument data to appease BacktestEngine\n instrument_data_config = BacktestDataConfig(\n catalog_path=self.catalog.path,\n catalog_fs_protocol=\"memory\",\n data_cls=InstrumentStatusUpdate.fully_qualified_name(),\n )\n\n streaming = BetfairTestStubs.streaming_config(\n catalog_path=self.catalog.path,\n )\n\n run_config = BacktestRunConfig(\n engine=BacktestEngineConfig(streaming=streaming),\n data=[data_config, instrument_data_config],\n venues=[BetfairTestStubs.betfair_venue_config()],\n )\n\n # Act\n node = BacktestNode(configs=[run_config])\n r = node.run()\n\n # Assert\n result = self.catalog.read_backtest(\n backtest_run_id=r[0].instance_id,\n raise_on_failed_deserialize=True,\n )\n\n result = Counter([r.__class__.__name__ for r in result])\n assert result[\"NewsEventData\"] == 86985\n\n def test_feather_writer_signal_data(self):\n # Arrange\n instrument_id = self.catalog.instruments(as_nautilus=True)[0].id.value\n data_config = BacktestDataConfig(\n catalog_path=self.catalog.path,\n catalog_fs_protocol=\"memory\",\n data_cls=TradeTick,\n )\n\n streaming = BetfairTestStubs.streaming_config(\n catalog_path=self.catalog.path,\n )\n run_config = BacktestRunConfig(\n engine=BacktestEngineConfig(\n streaming=streaming,\n strategies=[\n ImportableStrategyConfig(\n strategy_path=\"nautilus_trader.examples.strategies.signal_strategy:SignalStrategy\",\n config_path=\"nautilus_trader.examples.strategies.signal_strategy:SignalStrategyConfig\",\n config={\"instrument_id\": instrument_id},\n ),\n ],\n ),\n data=[data_config],\n venues=[BetfairTestStubs.betfair_venue_config()],\n )\n\n # Act\n node = BacktestNode(configs=[run_config])\n r = node.run()\n\n # Assert\n result = self.catalog.read_backtest(\n backtest_run_id=r[0].instance_id,\n raise_on_failed_deserialize=True,\n )\n\n result = Counter([r.__class__.__name__ for r in result])\n assert result[\"SignalCounter\"] == 198\n\n def test_generate_signal_class(self):\n # Arrange\n cls = generate_signal_class(name=\"test\", value_type=float)\n\n # Act\n instance = cls(value=5.0, ts_event=0, ts_init=0)\n\n # Assert\n assert isinstance(instance, Data)\n assert instance.ts_event == 0\n assert instance.value == 5.0\n assert instance.ts_init == 0\n\n def test_config_write(self):\n # Arrange\n instrument_id = self.catalog.instruments(as_nautilus=True)[0].id.value\n streaming = BetfairTestStubs.streaming_config(\n catalog_path=self.catalog.path,\n )\n data_config = BacktestDataConfig(\n catalog_path=self.catalog.path,\n catalog_fs_protocol=\"memory\",\n data_cls=TradeTick,\n )\n\n run_config = BacktestRunConfig(\n engine=BacktestEngineConfig(\n streaming=streaming,\n strategies=[\n ImportableStrategyConfig(\n strategy_path=\"nautilus_trader.examples.strategies.signal_strategy:SignalStrategy\",\n config_path=\"nautilus_trader.examples.strategies.signal_strategy:SignalStrategyConfig\",\n config={\"instrument_id\": instrument_id},\n ),\n ],\n ),\n data=[data_config],\n venues=[BetfairTestStubs.betfair_venue_config()],\n )\n\n # Act\n node = BacktestNode(configs=[run_config])\n r = node.run()\n\n # Assert\n config_file = f\"{self.catalog.path}/backtest/{r[0].instance_id}.feather/config.json\"\n assert self.catalog.fs.exists(config_file)\n raw = self.catalog.fs.open(config_file, \"rb\").read()\n assert msgspec.json.decode(raw, type=NautilusKernelConfig)\n","repo_name":"ZYJ-q/test_0","sub_path":"tests/unit_tests/persistence/test_streaming.py","file_name":"test_streaming.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}