', itemSelect)\n\n update(dict_keys)\n root.mainloop()\n\nsearchVariables()\n\n","sub_path":"testingAutofillUserInput.py","file_name":"testingAutofillUserInput.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"379107948","text":"# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nfrom oslo_policy import policy\n\nfrom designate.common.policies import base\n\n\nrules = [\n policy.DocumentedRuleDefault(\n name=\"create_zone_import\",\n check_str=base.RULE_ADMIN_OR_OWNER,\n description=\"Create Zone Import\",\n operations=[\n {\n 'path': '/v2/zones/tasks/imports',\n 'method': 'POST'\n }\n ]\n ),\n policy.DocumentedRuleDefault(\n name=\"find_zone_imports\",\n check_str=base.RULE_ADMIN_OR_OWNER,\n description=\"List all Zone Imports\",\n operations=[\n {\n 'path': '/v2/zones/tasks/imports',\n 'method': 'GET'\n }\n ]\n ),\n policy.DocumentedRuleDefault(\n name=\"get_zone_import\",\n check_str=base.RULE_ADMIN_OR_OWNER,\n description=\"Get Zone Imports\",\n operations=[\n {\n 'path': '/v2/zones/tasks/imports/{zone_import_id}',\n 'method': 'GET'\n }\n ]\n ),\n policy.DocumentedRuleDefault(\n name=\"update_zone_import\",\n check_str=base.RULE_ADMIN_OR_OWNER,\n description=\"Update Zone Imports\",\n operations=[\n {\n 'path': '/v2/zones/tasks/imports',\n 'method': 'POST'\n }\n ]\n ),\n policy.DocumentedRuleDefault(\n name=\"delete_zone_import\",\n check_str=base.RULE_ADMIN_OR_OWNER,\n description=\"Delete a Zone Import\",\n operations=[\n {\n 'path': '/v2/zones/tasks/imports/{zone_import_id}',\n 'method': 'GET'\n }\n ]\n )\n]\n\n\ndef list_rules():\n return rules\n","sub_path":"designate-8.0.0/designate/common/policies/zone_import.py","file_name":"zone_import.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"398732363","text":"from flask import current_app, _app_ctx_stack\nfrom flask_philo_core import ConfigurationError\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\n\nclass Connection(object):\n def __init__(self, engine, session):\n \"\"\"\n Encapsulates an engine and session to a database\n \"\"\"\n self.engine = engine\n self.session = session\n\n\nclass ConnectionPool:\n \"\"\"\n Flask-philo supports multiple postgresql database connections,\n this class stores one connection by every db\n \"\"\"\n connections = {}\n\n def __init__(self, app=None):\n self.app = app\n\n def initialize_connections(self, scopefunc=None):\n \"\"\"\n Initialize a database connection by each connection string\n defined in the configuration file\n \"\"\"\n for connection_name, connection_string in\\\n self.app.config['FLASK_PHILO_SQLALCHEMY'].items():\n engine = create_engine(connection_string)\n session = scoped_session(sessionmaker(), scopefunc=scopefunc)\n session.configure(bind=engine)\n self.connections[connection_name] = Connection(engine, session)\n\n def close(self):\n for k, v in self.connections.items():\n v.session.remove()\n\n def commit(self, connection_name='DEFAULT'):\n if connection_name is None:\n for conn_name, conn in self.connections.items():\n conn.session.commit()\n else:\n self.connections[connection_name].session.commit()\n\n def rollback(self, connection_name='DEFAULT'):\n if connection_name is None:\n for conn_name, conn in self.connections.items():\n conn.session.rollback()\n else:\n self.connections[connection_name].session.rollback()\n\n\ndef create_pool():\n app = current_app._get_current_object()\n if 'FLASK_PHILO_SQLALCHEMY' not in app.config:\n raise ConfigurationError(\n 'Not configuration found for Flask-Philo-SQLAlchemy')\n ctx = _app_ctx_stack.top\n if ctx is not None:\n if not hasattr(ctx, 'sqlalchemy_pool'):\n pool = ConnectionPool(app)\n pool.initialize_connections(scopefunc=_app_ctx_stack)\n ctx.sqlalchemy_pool = pool\n else:\n pool = ctx.sqlalchemy_pool\n\n @app.before_request\n def before_request():\n \"\"\"\n Assign postgresql connection pool to the global\n flask object at the beginning of every request\n \"\"\"\n ctx = _app_ctx_stack.top\n pool = ConnectionPool(app)\n pool.initialize_connections(scopefunc=_app_ctx_stack)\n ctx.sqlalchemy_pool = pool\n\n @app.teardown_request\n def teardown_request(exception):\n \"\"\"\n Releasing connection after finish request, not required in unit\n testing\n \"\"\"\n ctx = _app_ctx_stack.top\n pool = getattr(ctx, 'sqlalchemy_pool', None)\n if pool is not None:\n for k, v in pool.connections.items():\n v.session.remove()\n return pool\n","sub_path":"flask_philo_sqlalchemy/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"472272306","text":"import io\nimport json\nimport os\nimport unittest\n\nfrom mock import patch\n\nfrom snips_nlu_metrics.engine import build_nlu_engine_class\nfrom snips_nlu_metrics.metrics import (compute_cross_val_metrics,\n compute_train_test_metrics,\n compute_cross_val_nlu_metrics,\n compute_train_test_nlu_metrics)\nfrom snips_nlu_metrics.tests.engine_config import NLU_CONFIG\nfrom snips_nlu_metrics.tests.mock_engine import (MockTrainingEngine,\n MockInferenceEngine)\nfrom snips_nlu_metrics.utils.constants import METRICS, PARSING_ERRORS\n\n\nclass TestMetrics(unittest.TestCase):\n def test_cross_val_nlu_metrics(self):\n # Given\n dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n \"resources\", \"beverage_dataset.json\")\n # When\n try:\n res = compute_cross_val_nlu_metrics(\n dataset=dataset_path, training_engine_class=MockTrainingEngine,\n inference_engine_class=MockInferenceEngine, nb_folds=2)\n except Exception as e:\n self.fail(e.args[0])\n\n # Then\n expected_metrics = {\n 'null': {\n 'intent': {\n 'true_positive': 0,\n 'false_positive': 11,\n 'false_negative': 0,\n 'precision': 0.0,\n 'recall': 0.0\n },\n 'slots': {},\n 'intent_utterances': 0\n },\n 'MakeCoffee': {\n 'intent': {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 7,\n 'precision': 0.0,\n 'recall': 0.0\n },\n 'slots': {\n 'number_of_cups': {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 0,\n 'precision': 0.0,\n 'recall': 0.0\n }\n },\n 'intent_utterances': 7\n },\n 'MakeTea': {\n 'intent': {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 4,\n 'precision': 0.0,\n 'recall': 0.0\n },\n 'slots': {\n 'number_of_cups': {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 0,\n 'precision': 0.0,\n 'recall': 0.0\n },\n 'beverage_temperature': {\n 'true_positive': 0,\n 'false_positive': 0,\n 'false_negative': 0,\n 'precision': 0.0,\n 'recall': 0.0\n }\n },\n 'intent_utterances': 4\n }\n }\n\n self.assertDictEqual(expected_metrics, res[\"metrics\"])\n\n def test_cross_val_metrics_should_skip_when_not_enough_data(self):\n # Given\n dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n \"resources\", \"beverage_dataset.json\")\n\n # When\n result = compute_cross_val_nlu_metrics(\n dataset=dataset_path, training_engine_class=MockTrainingEngine,\n inference_engine_class=MockInferenceEngine, nb_folds=11)\n\n # Then\n expected_result = {\n METRICS: None,\n PARSING_ERRORS: []\n }\n self.assertDictEqual(expected_result, result)\n\n def test_end_to_end_cross_val_metrics(self):\n # Given\n dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n \"resources\", \"beverage_dataset.json\")\n with io.open(dataset_path, encoding=\"utf8\") as f:\n dataset = json.load(f)\n\n # When/Then\n try:\n engine_class = build_nlu_engine_class(MockTrainingEngine,\n MockInferenceEngine)\n compute_cross_val_metrics(dataset=dataset,\n engine_class=engine_class, nb_folds=5)\n except Exception as e:\n self.fail(e.args[0])\n\n @patch('snips_nlu_metrics.metrics.compute_train_test_metrics')\n def test_train_test_nlu_metrics(self, mocked_train_test_metrics):\n # Given\n mocked_metrics_result = {\"metrics\": \"ok\"}\n mocked_train_test_metrics.return_value = mocked_metrics_result\n dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n \"resources\", \"beverage_dataset.json\")\n with io.open(dataset_path, encoding=\"utf8\") as f:\n dataset = json.load(f)\n\n # When/Then\n try:\n res = compute_train_test_nlu_metrics(\n train_dataset=dataset, test_dataset=dataset,\n training_engine_class=MockTrainingEngine,\n inference_engine_class=MockInferenceEngine)\n except Exception as e:\n self.fail(e.args[0])\n\n self.assertDictEqual(mocked_metrics_result, res)\n\n def test_end_to_end_train_test_metrics(self):\n # Given\n dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n \"resources\", \"beverage_dataset.json\")\n with io.open(dataset_path, encoding=\"utf8\") as f:\n dataset = json.load(f)\n\n # When/Then\n try:\n engine_class = build_nlu_engine_class(MockTrainingEngine,\n MockInferenceEngine)\n compute_train_test_metrics(\n train_dataset=dataset, test_dataset=dataset,\n engine_class=engine_class)\n except Exception as e:\n self.fail(e.args[0])\n\n def test_end_to_end_train_test_metrics_with_training_config(self):\n # Given\n dataset_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n \"resources\", \"beverage_dataset.json\")\n with io.open(dataset_path, encoding=\"utf8\") as f:\n dataset = json.load(f)\n\n # When/Then\n try:\n engine_class = build_nlu_engine_class(MockTrainingEngine,\n MockInferenceEngine,\n training_config=NLU_CONFIG)\n compute_train_test_metrics(\n train_dataset=dataset, test_dataset=dataset,\n engine_class=engine_class)\n except Exception as e:\n self.fail(e.args[0])\n","sub_path":"snips_nlu_metrics/tests/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":6958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"281763121","text":"from bs4 import BeautifulSoup\nfrom attrnames import getAttributeName, getSectionName\n\ndef parseCase(html):\n\t# Import into BS\n\tsoup = BeautifulSoup(html, 'html.parser')\n\n\t# Temporary KVP store\n\tdata = {}\n\t# Full data list\n\toutput = []\n\n\t# Get KVPs, headers, and separators\n\trows = soup.find_all(['span', 'h5', 'h6', 'i', 'hr'])\n\t# Iterate thru page rows\n\ti = 0\n\twhile i < len(rows):\n\t\trow = rows[i]\n\n\t\t# Save class list\n\t\tclasses = row.attrs.get('class', [])\n\n\t\tif 'AltBodyWindowDcCivil' not in classes:\n\t\t\t# Field names\n\t\t\tif 'FirstColumnPrompt' in classes or 'Prompt' in classes:\n\t\t\t\theaderval = row.get_text()\n\n\t\t\t\t# Remove unnecessary end chars\n\t\t\t\tif headerval.endswith(':'): headerval = headerval[:-1]\n\t\t\t\tif headerval.endswith('?'): headerval = headerval[:-1]\n\n\t\t\t\theaderval = stripWhitespace(headerval)\n\n\t\t\t\t# Parse newer charge statue code format\n\t\t\t\tif headerval == 'Article' and stripWhitespace(rows[i+2].get_text()) == 'Sec:':\n\t\t\t\t\t# Build statute code from individual fields\n\t\t\t\t\tstatuteCode = []\n\t\t\t\t\tfor j in range(i+1, i+10, 2):\n\t\t\t\t\t\tif 'Value' in rows[j].attrs.get('class', []):\n\t\t\t\t\t\t\tstatuteCode.append(stripWhitespace(rows[j].get_text()))\n\t\t\t\t\t# Append as KVP\n\t\t\t\t\tdata['Statute Code'] = '.'.join(filter(None, statuteCode))\n\t\t\t\t\t# Skip to the next section after this\n\t\t\t\t\ti += 10\n\t\t\t\t# Parse jail and probation terms\n\t\t\t\telif headerval in {'Jail Term', 'Suspended Term', 'UnSuspended Term', 'Probation', 'Supervised', 'UnSupervised'}:\n\t\t\t\t\t# Generate interval string from yrs+mos+days+hrs fields\n\t\t\t\t\tyrs = stripWhitespace(rows[i+2].get_text()) or '0'\n\t\t\t\t\tmos = stripWhitespace(rows[i+4].get_text()) or '0'\n\t\t\t\t\tdays = stripWhitespace(rows[i+6].get_text()) or '0'\n\t\t\t\t\thrs = stripWhitespace(rows[i+8].get_text()) or '0'\n\t\t\t\t\t# Cleanup intervals\n\t\t\t\t\tif yrs.isdigit() and mos.isdigit():\n\t\t\t\t\t\tiyrs = int(yrs)\n\t\t\t\t\t\timos = int(mos)\n\t\t\t\t\t\tif imos > 12:\n\t\t\t\t\t\t\tiyrs += imos // 12\n\t\t\t\t\t\t\timos %= 12\n\t\t\t\t\t\t\tyrs = str(iyrs)\n\t\t\t\t\t\t\tmos = str(imos)\n\t\t\t\t\tinterval = yrs + '-' + mos + ' ' + days + ' ' + hrs + ':00:00'\n\t\t\t\t\t# Append as KVP\n\t\t\t\t\tdata[headerval] = interval\n\t\t\t\t\t# Skip to the next section after this\n\t\t\t\t\ti += 8\n\t\t\t\t# Parse newer event table format\n\t\t\t\telif row.parent.name == 'th' and headerval == 'Event Type':\n\t\t\t\t\t# Get number of table columns\n\t\t\t\t\theaderVals = []\n\t\t\t\t\tfor j in range(i, len(rows)):\n\t\t\t\t\t\tif rows[j].parent.name != 'th':\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\theaderVals.append(stripWhitespace(rows[j].get_text()))\n\t\t\t\t\t# Get row values\n\t\t\t\t\trowVals = []\n\t\t\t\t\tfor k in range(i+len(headerVals), len(rows)):\n\t\t\t\t\t\tif not 'Value' in rows[k].attrs.get('class', []):\n\t\t\t\t\t\t\ti = k # Skip to the next section after this\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\trowVals.append(stripWhitespace(rows[k].get_text()))\n\t\t\t\t\t# Split and append events\n\t\t\t\t\tfor l in range(0, len(rowVals), len(headerVals)):\n\t\t\t\t\t\teventData = {x[0]: x[1] for x in zip(headerVals, rowVals[l:l+len(headerVals)])}\n\t\t\t\t\t\toutput.append(eventData)\n\t\t\t# Values\n\t\t\telif 'Value' in classes:\n\t\t\t\tdataval = stripWhitespace(row.get_text())\n\t\t\t\tif headerval and dataval != 'MONEY JUDGMENT': # The 'money judgement' header is useless\n\t\t\t\t\tdata[headerval] = dataval\n\t\t\t# Headers and separators\n\t\t\telse:\n\t\t\t\tif 'InfoChargeStatement' not in classes:\n\t\t\t\t\tif row.name in {'hr', 'h5', 'h6', 'i'}:\n\t\t\t\t\t\theader = stripWhitespace(row.get_text())\n\t\t\t\t\t\t# Skip over the charge subheadings\n\t\t\t\t\t\tif not (header in {'Disposition', 'Jail', 'Probation', 'Fine', 'Community Work Service'} and row.name == 'i' and row.parent.name == 'left'):\n\t\t\t\t\t\t\t# Append the KVPs and reset the temporary dict\n\t\t\t\t\t\t\tif data:\n\t\t\t\t\t\t\t\toutput.append(data)\n\t\t\t\t\t\t\t\tdata = {}\n\t\t\t\t\t\t\t# Add the header to the data list\n\t\t\t\t\t\t\tif row.name != 'hr':\n\t\t\t\t\t\t\t\tif header:\n\t\t\t\t\t\t\t\t\toutput.append(header)\n\n\t\t# Increment index\n\t\ti += 1\n\n\t# Append any remaining KVPs\n\tif data:\n\t\toutput.append(data)\n\t\tdata = {}\n\n\treturn formatOutput(output)\n\ndef formatOutput(data):\n\t# Final output dict\n\toutput = {}\n\n\t# Add case information header if necessary\n\tif len(data) > 0 and not isinstance(data[0], str):\n\t\tdata.insert(0, 'Case Information')\n\n\t# Iterate thru data list\n\tfor i in range(len(data)):\n\t\t# Check if item is a section header\n\t\tif isinstance(data[i], str):\n\t\t\t# Get proper attribute name\n\t\t\theader = getSectionName(data[i])\n\t\t\t# Make sure section is going to be stored\n\t\t\tif header:\n\t\t\t\tentries = []\n\t\t\t\t# Find KVP dicts corresponding to this header\n\t\t\t\tfor j in range(i+1, len(data)):\n\t\t\t\t\t# Stop looking when we reach a different header\n\t\t\t\t\tif isinstance(data[j], str):\n\t\t\t\t\t\tbreak\n\t\t\t\t\t# Get proper attribute names for fields\n\t\t\t\t\tattrMap = formatAttrs(data[j], data[i], header)\n\t\t\t\t\t# Save this dict if it hasn't been nullified\n\t\t\t\t\tif attrMap:\n\t\t\t\t\t\tentries.append(attrMap)\n\t\t\t\t# Add all the data we found to the master dict\n\t\t\t\tif output.get(header):\n\t\t\t\t\toutput[header] += entries\n\t\t\t\telif entries:\n\t\t\t\t\toutput[header] = entries\n\n\t# Move attorneys listed under parties to attorneys\n\tparties = output.get('parties', [])\n\tj = 0\n\twhile j < len(parties):\n\t\tpartyType = parties[j].get('type')\n\t\t# Check if party type is an attorney\n\t\tif partyType and partyType.lower().startswith('attorney for '):\n\t\t\t# Remove the party from the parties list\n\t\t\tparty = parties.pop(j)\n\t\t\tj -= 1\n\t\t\t# Set the type to the appropriate attorney type\n\t\t\tparty['type'] = partyType[13:]\n\t\t\t# Create attorneys key if necessary\n\t\t\tif not output.get('attorneys'):\n\t\t\t\toutput['attorneys'] = []\n\t\t\t# Append this attorney\n\t\t\toutput['attorneys'].append(party)\n\t\tj += 1\n\n\treturn output\n\ndef formatAttrs(data, section, header):\n\t# Formatted output dict\n\td = {}\n\n\t# Iterate thru fields in input dict\n\tfor field in data:\n\t\t# Get proper field names\n\t\tformattedName = getAttributeName(field)\n\t\td[formattedName] = data[field]\n\t\tif data[field]:\n\t\t\t# Format heights\n\t\t\tif formattedName == 'height' and ('\\'' in data[field] or '\"' in data[field]):\n\t\t\t\tvals = data[field].replace('\"', '\\'').split('\\'')\n\t\t\t\td[formattedName] = str(int(vals[0] or 0) * 12 + int(vals[1] or 0))\n\t\t\t# Format sex\n\t\t\telif formattedName == 'sex':\n\t\t\t\td[formattedName] = data[field].upper()[0]\n\t\t\t# Format dates\n\t\t\telif ('date' in formattedName or formattedName == 'dob'):\n\t\t\t\tvals = data[field].split('/')\n\t\t\t\tif len(vals) < 3:\n\t\t\t\t\td[formattedName] = vals[0] + '/01/' + vals[1]\n\t\t\t# Format booleans\n\t\t\telif formattedName in {'probable_cause', 'accident_contribution', 'property_damage', 'seatbelts_used', 'mandatory_court_appearance'}:\n\t\t\t\td[formattedName] = data[field].lower() in {'y', 'yes'}\n\t\t\t# Format traffic accident injuries\n\t\t\telif formattedName == 'injuries' and not data[field].isdigit():\n\t\t\t\td[formattedName] = 0\n\n\t# Assign attorneys a type based on what section they're in\n\tif section.startswith('Attorney(s) for the '):\n\t\tif d.get('appearance_date') or (d.get('name') and 'attorney' in d.get('name').lower()):\n\t\t\td['type'] = section[20:]\n\t\t# Discard party information in the attorney sections\n\t\telse:\n\t\t\treturn None\n\t# Assign officers a type to indicate that they're officers\n\telif header == 'parties' and ('Surety' in section or 'Bond' in section or 'Defendant' in section or 'Plaintiff' in section or 'Officer' in section):\n\t\td['type'] = section.replace(' Information', '')\n\n\treturn d\n\ndef stripWhitespace(s):\n\treturn ' '.join(s.split())\n\n# This is only for testing\nif __name__ == '__main__': print(parseCase(open('test.html', 'r').read()))\n","sub_path":"md_case_parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"266737545","text":"from pybrain.datasets.supervised import SupervisedDataSet\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.supervised.trainers import BackpropTrainer\nfrom pybrain.tools.customxml.networkwriter import NetworkWriter\nfrom pybrain.tools.customxml.networkreader import NetworkReader\nimport matplotlib.pyplot as plt\n\n\n\nimport csv, datetime, glob, matplotlib\n\n# fireRisk.py r160520\n\"\"\"\n\nThe MIT License (MIT)\n\nCopyright (c) 2016 Bernardo Alecrim.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\"\"\"\n\nfireArray = []\nstations = []\n\n\ndef norm(array):\n return [float(i)/max(array) for i in array]\n\n\nclass fire:\n def __init__(self, lat, long, dateString, rainAmount, daysWithoutRain):\n self.lat = lat\n self.long = long\n\n self.date = datetime.datetime.strptime(dateString, '%Y-%m-%d')\n self.rainAmount = rainAmount\n self.daysWithoutRain = daysWithoutRain\n\n\nclass station:\n def __init__(self, lat, long, data):\n self.lat = lat\n self.long = long\n self.data = data\n\n\nclass stationData:\n def __init__(self, date, precipitation, maxTemp, minTemp, insol, avgTemp, humidity, windSpeed):\n self.date = datetime.datetime.strptime(date, '%m/%d/%y')\n self.precipitation = precipitation\n self.maxTemp = maxTemp\n self.minTemp = minTemp\n self.insol = insol\n self.avgTemp = avgTemp\n self.humidity = humidity\n self.windSpeed = windSpeed\n\n\nprint(\"\\nFireRisk NN r160520\")\nprint(\"\\nPopulating fire incident array...\")\n\n#########################################\n# reading fire information from files...#\n#########################################\n\nwith open('fires2.csv', 'rt') as firesFile:\n fireReader = csv.reader(firesFile, dialect='excel')\n\n for row in fireReader:\n currentFire = fire(lat=row[0], long=row[1], dateString=row[2], rainAmount=row[4],\n daysWithoutRain=row[5])\n fireArray.append(currentFire)\n\n print(\"Total number of fire incidents: \" + len(fireArray).__str__() + \"\\n\")\n\n\n#####################################\n# reading station data from files...#\n#####################################\n\nprint(\"Populating weather station array...\")\nstationFiles = glob.glob('./stations_ready/*.csv')\nprint(\"Number of station data files found: \" + str(len(stationFiles)) + \"\\n\")\n\nfor file in stationFiles:\n\n with open(file, 'rt') as stationFile:\n\n stationReader = list(csv.reader(stationFile, dialect='excel'))\n\n currentStation = station(stationReader[0][9], stationReader[0][10], [])\n\n for row in stationReader:\n currentStation.data.append(stationData(row[0], row[2], row[3], row[4], row[5], row[6], row[7], row[8]))\n\n stations.append(currentStation)\n\n####################################\n# building datasets for training...#\n####################################\n\n # for a given day, we'll do the following:\n # 1. Grab temperature, humidity and location for a given day;\n # 2. Get the number of fires that happened in the area that day;\n # 3. Normalize the vectors;\n\n# extracting data from objects for normalization\n\nprint(\"Building organized dataset...\\n\")\n\ntempVector = []\nhumidityVector = []\nprecipitationVector = []\ndateVector = []\n\n# for station in stations:\nstation = stations[0]\nfor stationData in station.data:\n tempVector.append(float(stationData.avgTemp))\n humidityVector.append(float(stationData.humidity))\n precipitationVector.append(float(stationData.precipitation))\n dateVector.append(stationData.date)\n\n# running normalizer function\n\ntempVector = norm(tempVector)\nhumidityVector = norm(humidityVector)\nprecipitationVector = norm(precipitationVector)\n\n\n# calculating amount of fires by day.\n\nfiresByDay = []\n\nfor date in dateVector:\n fireCount = 0\n\n for fire in fireArray:\n\n if fire.date == date:\n fireCount += 1\n\n firesByDay.append(fireCount)\n\nfireNormVector = norm(firesByDay)\n\ninputList = []\n\nfor i in range(0, (len(tempVector))):\n currentPoint = []\n currentPoint.append(tempVector[i])\n currentPoint.append(humidityVector[i])\n currentPoint.append(precipitationVector[i])\n\n inputList.append(currentPoint)\n\n ds = SupervisedDataSet(3, 1)\n\nfor i in range(0, len(tempVector)):\n\n ds.addSample((precipitationVector[i], humidityVector[i], tempVector[i]), (fireNormVector[i],))\n\nprint(ds)\n\n# plt.plot(fireNormVector, precipitationVector)\n# plt.show()\n\n#############################\n# training neural network...#\n#############################\n\nprint(\"Network is in training phase...\\n\")\n\nnet = buildNetwork(3, 20, 1)\ntrainer = BackpropTrainer(net, ds, learningrate=0.1, momentum=0.5, verbose=True)\n\ntry:\n while trainer.train() > 0.001:\n pass\n\nexcept: KeyboardInterrupt\n\nprint(\"Writing network to file.\\n\")\nNetworkWriter.writeToFile(net, 'network.xml')\n\n\n# to read the network from file...\n# net = NetworkReader.readFrom('filename.xml')\n","sub_path":"fireRisk.py","file_name":"fireRisk.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"504786391","text":"import os\n\n\nclass C64File:\n\n def __init__(self, filename=None):\n self.file = None\n self.name = None\n self.mode = None\n self.joyport = None\n self.video_format = None\n self.accurate_disk = \"\"\n self.read_only = \"\"\n self.set_mode_c64()\n self.set_mode_pal()\n self.set_joyport_2()\n self.set_accurate_disk(False)\n self.set_readonly(False)\n if filename:\n self.load(filename)\n\n def load(self, filename):\n self.file = filename\n if os.path.exists(self.file):\n temp = os.path.basename(self.file)\n self.name = os.path.splitext(temp)[0] \n else:\n raise FileNotFoundError(self.file)\n \n def set_accurate_disk(self, enable=True):\n if enable:\n self.accurate_disk = \"accuratedisk\"\n else:\n self.accurate_disk = \"\"\n \n def set_readonly(self, enable=False):\n if enable:\n self.read_only = \"readonly\"\n else:\n self.read_only = \"\"\n \n def set_mode_c64(self):\n self.mode = \"64\"\n\n def set_mode_vic20(self):\n self.mode = \"vic\"\n \n def set_mode_pal(self):\n self.video_format = \"pal\"\n \n def set_mode_ntsc(self):\n self.video_format = \"ntsc\"\n\n def set_joyport_1(self):\n self.joyport = 1\n \n def set_joyport_2(self):\n self.joyport = 2\n\n def save_cjm(self):\n status = \"\"\n status += self.mode + \",\"\n status += self.video_format + \",\"\n status += self.accurate_disk + \",\" if self.accurate_disk != \"\" else \"\"\n status += self.read_only + \",\" if self.read_only != \"\" else \"\"\n breakpoint()\n if status[-1] == \",\":\n status = status[0:-1]\n temp = \"X:\" + status + \"\\r\\n\"\n temp += \"J:1\"\n if self.joyport == 1:\n temp += \"*\"\n temp += \":JU,JD,JL,JR,JF,JF,RS,SP,SP,RS,F1,F7,RS\" + \"\\r\\n\"\n temp += \"J:2\"\n if self.joyport == 2:\n temp += \"*\"\n temp += \":JU,JD,JL,JR,JF,JF,RS,SP,SP,RS,F1,F7,RS\" + \"\\r\\n\"\n my_path = os.path.dirname(self.file)\n my_path = os.path.join(my_path, self.name + \".cjm\")\n f = open(my_path, \"w\")\n f.write(temp)\n f.close()\n return my_path","sub_path":"easy64/c64file.py","file_name":"c64file.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"401280437","text":"#Разложение Холецкого\n\nimport numpy as np\nfrom math import sqrt\n\ndef Holecki(A):\n\n\tresult = np.zeros((len(A),len(A)),float)\n\n\tfor i in range(0,len(A),1):\n\n\t\ttemp1 = 0\n\t\ttemp2 = 0\n\n\t\tfor j in range(0,i,1):\n\t\t\tfor k in range(0,j,1):\n\t\t\t\ttemp1 = temp1 + result[i,k]*result[j,k]\n\t\t\tresult[i,j] = (A[i,j] - temp1)/result[j,j]\n \n\t\tfor t in range(0,i,1):\n\t\t\ttemp2 = temp2 + result[i,t]*result[i,t]\n\t\tresult[i,i] = sqrt(A[i,i] - temp2)\n\n\treturn result\n\ndef sol_bottomtr(C,b):\n\n\ty = np.zeros(len(C))\n\n\tfor i in range(0,len(C),1):\n\n\t\ttemp = 0\n\n\t\tfor j in range (0,i,1):\n\t\t\ttemp = temp + C[i,j]*y[j]\n\t\ty[i] = (b[i] - temp)/C[i,i]\n\n\treturn(y)\n\ndef sol_toptr(CT,y):\n\n\tx = np.zeros(len(CT),float)\n\n\tfor i in range (len(CT),0,-1):\n\n\t\ttemp = 0\n\n\t\tfor j in range (i,len(CT),1):\n\t\t\ttemp = temp + CT[i-1,j]*x[j]\n\t\tx[i-1] = (y[i-1] - temp)/CT[i-1,i-1]\n\n\treturn(x)\n\n\nA = np.array([[15,1,8],[5,13,-1],[11,-1,17]],float)\nx = np.array([7,4,5])\nb = np.dot(A,x)\nC = Holecki(A)\nprint(C)\ny = sol_bottomtr(C,b)\nx = sol_toptr(C.transpose(),y)\nprint(x)","sub_path":"task_1_3.py","file_name":"task_1_3.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"463288749","text":"\"\"\"\n元数据管理\n\n数据格式:\n\nparent_asset_type: \"上级资产类型\"\nasset_type: \"资产类型\"\nasset_type_title: \"资产类型标题\"\nenv: \"环境\"\n\n\"\"\"\nimport json\n\nfrom bson.json_util import dumps\nfrom flask import Blueprint, request\n\nfrom common import common_service\nfrom common.common_service import MyServiceException, ResResult\nfrom component import my_data_struct2\nfrom component.my_mongo import mongodb\n\napp = Blueprint('general_asset_manage_system__metadata_manage', __name__,\n url_prefix='/general_asset_manage_system/metadata_manage')\n\ngeneral_asset_manage_system__metadata_co = mongodb['general_asset_manage_system__metadata']\n\n\"\"\"\n初始化数据:\n[\n{\"pid\": \"\", \"id\": \"1\", \"name\": \"服务器\"}\n,{\"pid\": \"\", \"id\": \"2\", \"name\": \"数据库\"}\n,{\"pid\": \"2\", \"id\": \"2_1\", \"name\": \"MySQL\"}\n,{\"pid\": \"2\", \"id\": \"2_2\", \"name\": \"Oracle\"}\n,{\"pid\": \"\", \"id\": \"3\", \"name\": \"容器调度\"}\n,{\"pid\": \"3\", \"id\": \"3_1\", \"name\": \"K8S\"}\n,{\"pid\": \"\", \"id\": \"4\", \"name\": \"构建服务\"}\n,{\"pid\": \"4\", \"id\": \"4_1\", \"name\": \"Jenkins\"}\n,{\"pid\": \"\", \"id\": \"5\", \"name\": \"源码\"}\n,{\"pid\": \"5\", \"id\": \"5_1\", \"name\": \"SVN\"}\n]\n\"\"\"\n\n\n@app.route('/insert', methods=['POST'])\ndef insert():\n \"\"\"\n 插入\n \"\"\"\n try:\n request_data = common_service.check_request_dat_not_null([\"pid\", \"slice_len\"])\n pid = request_data[\"pid\"]\n slice_len = request_data[\"slice_len\"]\n slice_len = str(int(slice_len) + 1)\n print(\"插入数据: \", \"pid=\", pid, \"slice_len=\", slice_len)\n if \"root\" == pid:\n pid = \"\"\n _id = str(slice_len)\n else:\n _id = str(pid) + \"_\" + slice_len\n general_asset_manage_system__metadata_co.insert_one({\n \"pid\": str(pid), \"id\": str(_id), \"name\": \"\", \"env\": \"dev\", \"env_name\": \"开发环境\"\n })\n return {\"id\": _id}\n except MyServiceException as e:\n print(e)\n return ResResult.return500(str(e))\n\n\n@app.route('/delete', methods=['POST'])\ndef delete():\n \"\"\"\n 删除\n \"\"\"\n try:\n request_data = common_service.check_request_dat_not_null([\"id\"])\n _id = request_data[\"id\"]\n if not _id or _id == \"\":\n raise MyServiceException(\"不能删除空id节点\")\n # 删除指定id节点\n general_asset_manage_system__metadata_co.delete_one(filter={\n \"id\": _id\n })\n # 删除子节点\n general_asset_manage_system__metadata_co.delete_many(filter={\n \"id\": {'$regex': \"^\" + _id + \".*\"}\n })\n return {}\n except MyServiceException as e:\n print(e)\n return ResResult.return500(str(e))\n\n\n@app.route('/update', methods=['POST'])\ndef update():\n \"\"\"\n 修改\n \"\"\"\n try:\n request_data = common_service.check_request_dat_not_null([\"id\", \"name\"])\n _id = request_data[\"id\"]\n name = request_data[\"name\"]\n if not _id or _id == \"\":\n raise MyServiceException(\"不能修改空id节点\")\n process_instance = {\n \"name\": name\n }\n general_asset_manage_system__metadata_co.update_one(filter={'id': _id},\n update={'$set': process_instance})\n except MyServiceException as e:\n print(e)\n return ResResult.return500(str(e))\n return {}\n\n\n@app.route('/select', methods=['POST'])\ndef select():\n \"\"\"\n 查询\n \"\"\"\n request_data = request.get_data()\n # 搜索\n # 分页\n return dumps(general_asset_manage_system__metadata_co.find())\n\n\n@app.route('/select_tree', methods=['POST'])\ndef select_tree():\n \"\"\"\n 查询-树状\n \"\"\"\n metadata_db_result = json.loads(select())\n print(\"metadata_db_result:\", metadata_db_result)\n tree_data = my_data_struct2.List.convert_to_tree(metadata_db_result)\n res_result = [{\n \"id\": \"root\",\n \"title\": \"根目录\",\n \"spread\": True,\n \"children\": tree_data}]\n return json.dumps(res_result)\n\n\ndef get_asset_type_by_asset_type_str(asset_type_str):\n db_query_res = json.loads(dumps(general_asset_manage_system__metadata_co.find_one(filter={\n \"name\": asset_type_str\n })))\n if db_query_res:\n return db_query_res[\"id\"]\n return None\n","sub_path":"system/general_asset_manage_system/service/metadata_manage.py","file_name":"metadata_manage.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"521868713","text":"from collections import namedtuple\nfrom decimal import Decimal\nfrom django.utils.translation import gettext_lazy as _\nfrom oscar.core.utils import round_half_up\nimport itertools\n\n\nPriceBreakdownStackEntry = namedtuple(\n \"PriceBreakdownStackEntry\",\n (\n \"quantity_with_discount\",\n \"discount_delta_unit\",\n ),\n)\n\nLineDiscountDescription = namedtuple(\n \"LineDiscountDescription\",\n (\n \"amount\",\n \"offer_name\",\n \"offer_description\",\n \"voucher_name\",\n \"voucher_code\",\n ),\n)\n\n\nclass BluelightBasketMixin(object):\n @property\n def offer_post_order_actions(self):\n \"\"\"\n Return post order actions from offers\n \"\"\"\n return self.offer_applications.offer_post_order_actions\n\n @property\n def voucher_post_order_actions(self):\n \"\"\"\n Return post order actions from offers\n \"\"\"\n return self.offer_applications.voucher_post_order_actions\n\n def clear_offer_upsells(self):\n for line in self.all_lines():\n line.clear_offer_upsells()\n\n def add_offer_upsell(self, offer_upsell):\n for line in self.all_lines():\n if line.product and offer_upsell.is_relevant_to_product(line.product):\n line.add_offer_upsell(offer_upsell)\n\n def get_offer_upsells(self):\n offer_upsells = set([])\n for line in self.all_lines():\n for upsell in line.get_offer_upsells():\n offer_upsells.add(upsell)\n return list(offer_upsells)\n\n\nclass BluelightBasketLineMixin(object):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Keep track of the discount amount at the start of offer group application, so that we can tell what\n # the current offer group has accomplished, versus previous offer groups.\n self._offer_group_starting_discount = Decimal(\"0.00\")\n\n # Used to record a \"stack\" of prices as they decrease via offer group application, used when calculating the price breakdown.\n self._price_breakdown_stack = []\n\n # Used to track descriptions of why discounts where applied to the line.\n self._discount_descriptions = []\n\n # Used to track offer upsell messages\n self._offer_upsells = []\n\n @property\n def unit_effective_price(self):\n \"\"\"\n The price to use for offer calculations.\n\n We have to override this so that the price used to calculate offers takes into account\n previously applied, compounding discounts.\n\n Description of logic:\n\n During offer application, because of the existence of OfferGroup, discount may be > 0 even\n when ``self.consumer.consumed`` is 0. This is because Applicator resets the affected quantity\n to 0 when progressing onto the next OfferGroup, so that the it may affect the same lines that\n the previous OfferGroup just did, e.g. compounding offers. However, since by default Offers\n all calculate their discounts using the full unit price excluding discounts, this has the\n possibility of creating negatively priced lines. For instance:\n\n == ======== ========== ===========\n Basket\n -------------------------------------\n ID Quantity Unit Price Total Price\n == ======== ========== ===========\n 1 2 $100 $200\n == ======== ========== ===========\n\n 1. Applicator applies Offer Group 1:\n 1. A MultibuyDiscountBenefit makes one item free. Total is now $100 and affected quantity of\n line 1 is 1.\n 2. Applicator resets affected quantity of line 1 to 0\n 2. Applicator applies Offer Group 2:\n 1. A $300 AbsoluteDiscountBenefit subtracts $200 from the line. Total is now -$100 and\n affected quantity of line 1 is 2.\n 2. Applicator resets affected quantity of line 1 to 0.\n 3. Applicator sets affected quantity of line 1 to 2 (min of the *line 1's quantity* and the *internal\n line 1 affected counter*).\n\n Point 2.1 occurs because this method, unit_effective_price, always returns the full item price, $100.\n The correct functionality is:\n\n 1. Applicator applies Offer Group 1:\n 1. A MultibuyDiscountBenefit makes one item free. Total is now $100 and affected quantity of\n line 1 is 1.\n 2. Applicator resets affected quantity of line 1 to 0\n 2. Applicator applies Offer Group 2:\n 1. A $300 AbsoluteDiscountBenefit subtracts $100 from the line. Total is now $0 and\n affected quantity of line 1 is 2.\n 2. Applicator resets affected quantity of line 1 to 0.\n 3. Applicator sets affected quantity of line 1 to 2 (min of the *line 1's quantity* and the *internal\n line 1 affected counter*).\n\n In order for point 2.1 to work that way and subtract $100 instead of $200, it must start with the already\n discounted line price of $100, which equates to a unit_effective_price of $50.\n \"\"\"\n if self._discount_incl_tax > Decimal(\"0.00\"):\n raise RuntimeError(\n _(\"Bluelight does not support tax-inclusive discounting.\")\n )\n\n # Protect against divide by 0 errors\n if self.quantity == 0:\n return Decimal(\"0.00\")\n\n # Cannot compare None with Decimal below, so return None\n if self.purchase_info.price.effective_price is None:\n return None\n\n # Figure out the per-unit discount by taking the discount at the start of offer group application and\n # dividing it by the line quantity.\n per_unit_discount = self._offer_group_starting_discount / self.quantity\n unit_price_full = self.purchase_info.price.effective_price\n unit_price_discounted = unit_price_full - per_unit_discount\n return unit_price_discounted\n\n @property\n def line_price_incl_tax_incl_discounts(self):\n if self.line_price_incl_tax is not None:\n return max(0, round_half_up(self.line_price_incl_tax - self.discount_value))\n return None\n\n def clear_discount(self):\n \"\"\"\n Remove any discounts from this line.\n \"\"\"\n super().clear_discount()\n self._offer_group_starting_discount = Decimal(\"0.00\")\n self._price_breakdown_stack = []\n self._discount_descriptions = []\n\n def discount(self, discount_value, affected_quantity, incl_tax=True, offer=None):\n \"\"\"\n Apply a discount to this line.\n\n Blocks any discounts with include tax since Bluelight does not support this behavior, due\n to the challenges of OfferGroup compounding offers.\n \"\"\"\n if incl_tax:\n raise RuntimeError(\n _(\n \"Attempting to discount the tax-inclusive price of a line \"\n \"when tax-exclusive discounts are already applied\"\n )\n )\n if self._discount_incl_tax > 0:\n raise RuntimeError(\n _(\n \"Attempting to discount the tax-exclusive price of a line \"\n \"when tax-inclusive discounts are already applied\"\n )\n )\n\n # Increase the total line discount amount\n self._discount_excl_tax += discount_value\n\n # Increment tracking counters\n self.consume(affected_quantity, offer=offer)\n self.consumer.discount(affected_quantity)\n\n # Push description of discount onto the stack\n if offer:\n voucher = offer.get_voucher()\n descr = LineDiscountDescription(\n amount=discount_value,\n offer_name=offer.name,\n offer_description=offer.description,\n voucher_name=voucher.name if voucher else None,\n voucher_code=voucher.code if voucher else None,\n )\n self._discount_descriptions.append(descr)\n\n def get_discount_descriptions(self):\n return self._discount_descriptions\n\n def begin_offer_group_application(self):\n \"\"\"\n Signal that the Applicator will begin to apply a new group of offers.\n\n Since line consumption is name-spaced within each offer group, we record the discount\n amount at the start of application and we reset the ``_affected_quantity`` property to 0.\n This allows offers to re-consume lines already consumed by previous offer groups while\n still calculating their discount amounts correctly.\n \"\"\"\n self.consumer.begin_offer_group_application()\n self._offer_group_starting_discount = self.discount_value\n\n def end_offer_group_application(self):\n \"\"\"\n Signal that the Applicator has finished applying a group of offers.\n \"\"\"\n discounted_quantity = self.consumer.discounted()\n if discounted_quantity > 0:\n delta_line = self.discount_value - self._offer_group_starting_discount\n delta_unit = delta_line / discounted_quantity\n item = PriceBreakdownStackEntry(\n quantity_with_discount=discounted_quantity,\n discount_delta_unit=delta_unit,\n )\n self._price_breakdown_stack.append(item)\n self.consumer.end_offer_group_application()\n\n def finalize_offer_group_applications(self):\n \"\"\"\n Signal that all offer groups (and therefore all offers) have now been applied.\n \"\"\"\n self.consumer.finalize_offer_group_applications()\n self._offer_group_starting_discount = self.discount_value\n\n def clear_offer_upsells(self):\n self._offer_upsells = []\n\n def add_offer_upsell(self, offer_upsell):\n self._offer_upsells.append(offer_upsell)\n\n def get_offer_upsells(self):\n return self._offer_upsells\n\n def get_price_breakdown(self):\n \"\"\"\n Return a breakdown of line prices after discounts have been applied.\n\n Returns a list of (unit_price_incl_tax, unit_price_excl_tax, quantity) tuples.\n \"\"\"\n if not self.is_tax_known:\n raise RuntimeError(\n _(\"A price breakdown can only be determined when taxes are known\")\n )\n\n # Create an array of the pre-discount unit prices with length equal to the line quantity\n item_prices = []\n for i in range(self.quantity):\n item_prices.append(self.unit_price_excl_tax)\n\n # Make sure _price_breakdown_stack adequately describes the total discount applied (in-case\n # somehow we applied a benefit but didn't call ``end_offer_group_application``. If it was\n # called, this is a no-op.\n self.end_offer_group_application()\n\n # Based on the discounts and affected quantities recorded in the _price_breakdown_stack, decrease each\n # unit price in the line until the full discount amount is exhausted.\n for discount_group in self._price_breakdown_stack:\n remaining_qty_affected = discount_group.quantity_with_discount\n iterations = 0\n while remaining_qty_affected > 0 and iterations <= self.quantity:\n for i in range(self.quantity):\n if item_prices[i] >= discount_group.discount_delta_unit:\n item_prices[i] -= discount_group.discount_delta_unit\n remaining_qty_affected -= 1\n\n if remaining_qty_affected <= 0:\n break\n iterations += 1\n\n # Remove the duplicate unit prices, resulting in a list of tuples containing a unit price and the quantity at that unit price\n price_qtys = []\n for price, prices in itertools.groupby(sorted(item_prices)):\n qty = len(list(prices))\n price_qty = (price, qty)\n price_qtys.append(price_qty)\n\n # Return a list of (unit_price_incl_tax, unit_price_excl_tax, quantity)\n prices = []\n line_price_excl_tax_incl_discounts = self.line_price_excl_tax_incl_discounts\n line_tax = self.line_tax\n\n # Avoid a divide by 0 error when the line is completely free, but still has tax applied to it.\n free = Decimal(\"0.00\")\n if line_price_excl_tax_incl_discounts <= free:\n prices.append((line_tax, free, self.quantity))\n return prices\n\n # When the line isn't free, distribute tax evenly based on what share of the total line price this unit prices accounts for.\n for unit_price_excl_tax, quantity in price_qtys:\n unit_tax = (\n unit_price_excl_tax / line_price_excl_tax_incl_discounts\n ) * line_tax\n unit_price_incl_tax = (unit_price_excl_tax + unit_tax).quantize(\n unit_price_excl_tax\n )\n prices.append((unit_price_incl_tax, unit_price_excl_tax, quantity))\n\n return prices\n","sub_path":"server/src/oscarbluelight/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":12939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"61067306","text":"# connect_to_ipy_kernel.py is part of the 'spartan' package.\n# It was written by Gus Dunn and was created on 9/4/14.\n# \n# Please see the license info in the root folder of this package.\n\n\"\"\"\n=================================================\nconnect_to_ipy_kernel.py\n=================================================\nPurpose:\nManage exchanging security kernel info and connecting to remote ipython notebook.\n\"\"\"\n__author__ = 'Gus Dunn'\nimport sh\nimport json\n\n# NOTE: this turned out not to require such a complicated solution. But this may be useful at some point so I am not\n# Killing it completely\n\nclass RemoteMachine(object):\n \"\"\"\n Manages doing stuff on the remote machine through ssh.\n \"\"\"\n def __init__(self, user, server, kernel_info_path, pub_key_path=None):\n \"\"\"\n\n :param user:\n :param server:\n :param pub_key_path:\n :return:\n \"\"\"\n self.user = user\n self.server = server\n self.pub_key = pub_key_path\n self.kernel_id = kernel_info_path\n self.kernel_data = None\n self.kernel_name = None\n\n try:\n # TODO: figure out how to test this HERE not later and find out if `ssh-copy-id yourservername` would help\n self.connection = sh.ssh.bake(\"%s@%s\" % (self.user, self.server))\n except:\n raise\n\n def get_kernel_info(self):\n \"\"\"\n Retrieves remote kernel info.\n :return:\n \"\"\"\n\n self.kernel_data = json.loads(str(self.connection(\"cat %s\" % self.kernel_id)))\n\n self.kernel_name = self.kernel_id.split('/')[-1]\n with open(\"~/.ipython/profile_default/security/%s\" % self.kernel_name, 'w') as self.local_kernel_info:\n self.local_kernel_info.write(json.dumps(self.kernel_data, indent=2))\n\n def open_port_forwarding(self):\n \"\"\"\n Opens correct ports in remote for forwarding.\n :return:\n \"\"\"\n\n base_command = \"ssh %(user)s@%(server)s -f -N -L %(port)s:%(ip)s:%(port)s\"\n\n # open stdin_port\n sh.ssh(base_command\n % {\"user\": self.user,\n \"server\": self.server,\n \"port\": self.kernel_data.get(\"stdin_port\"),\n \"ip\": self.kernel_data.get(\"ip\")})\n\n # open control_port\n sh.ssh(base_command\n % {\"user\": self.user,\n \"server\": self.server,\n \"port\": self.kernel_data.get(\"control_port\"),\n \"ip\": self.kernel_data.get(\"ip\")})\n\n # open hb_port\n sh.ssh(base_command\n % {\"user\": self.user,\n \"server\": self.server,\n \"port\": self.kernel_data.get(\"hb_port\"),\n \"ip\": self.kernel_data.get(\"ip\")})\n\n # open shell_port\n sh.ssh(base_command\n % {\"user\": self.user,\n \"server\": self.server,\n \"port\": self.kernel_data.get(\"shell_port\"),\n \"ip\": self.kernel_data.get(\"ip\")})\n\n # open iopub_port\n sh.ssh(base_command\n % {\"user\": self.user,\n \"server\": self.server,\n \"port\": self.kernel_data.get(\"iopub_port\"),\n \"ip\": self.kernel_data.get(\"ip\")})\n\n def start_notebook(self):\n \"\"\"\n Start a notebook on the local machine.\n :return:\n \"\"\"\n\n base_command = \"notebook --existing %(kernel_name)s\"\n fill_ins = {\"kernel_name\": self.kernel_name}\n\n sh.ipython(base_command % fill_ins)\n\n","sub_path":"src/spartan/scripts/connect_to_ipy_kernel.py","file_name":"connect_to_ipy_kernel.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"307157891","text":"#---coding:utf-8\n\n__author__ = 'peic'\n\nimport logging\n\n\ndef foo(s):\n n = int(s)\n\n # 使用print检查n\n print('n = ', n)\n\n # 使用assert代替print\n try:\n assert n != 0, 'n is zero'\n except AssertionError as e:\n print('AssertionError: ',e)\n\n\n # 使用logging来记录\n # 日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET\n # 默认的日志级别设置为WARNING\n logging.debug('n = %d' %(n))\n\n\n\n\n\n\n return n\n\nif __name__ == '__main__':\n\n print(foo('0'))\n\n\n # logging.basicConfig(level=logging.INFO,\n # format='%(asctime)s %(filename)s[line:%(line)d] %(levelname)s %(message)s',\n # datefmt='%a, %d %b %Y %H:%M:%S',\n # filename='D:\\\\PycharmProjects\\\\Test\\\\Simple_Prcatice\\\\logging.log',\n # filemode='w')\n # logging.debug('debug message')\n # logging.info('info message')\n # logging.warning('warning message')\n # logging.error('error message')\n # logging.critical('critical message')\n","sub_path":"python-toys/learn-python/Debug.py","file_name":"Debug.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"405600763","text":"# !/usr/bin/python\n# coding=UTF-8\nfrom services.stock_services import get_stock_by_id\n\n__author__ = 'xiaofeng.huang'\nimport mysql_data_client\n\nsql = [\n '''\n SELECT\n * FROM candle\n '''\n]\n\n\ndef find_all_hammer_line():\n for item in mysql_data_client.query(sql[0]):\n if is_hammer_line(item):\n print(get_stock_by_id(int(item['stock_id']))[0]['security_code'])\n\n\ndef is_hammer_line(candle):\n candle = converter(candle)\n upper_shadow_line = candle['upper_shadow_line']\n lower_shadow_line = candle['lower_shadow_line']\n entry = candle['entry']\n flag = False\n if lower_shadow_line != 0:\n if (upper_shadow_line == 0 or upper_shadow_line / lower_shadow_line < 0.01) and lower_shadow_line > 2 * abs(\n entry):\n flag = True\n return flag\n\n\ndef converter(candle):\n candle['entry'] = float(candle['entry'])\n candle['upper_shadow_line'] = float(candle['upper_shadow_line'])\n candle['lower_shadow_line'] = float(candle['lower_shadow_line'])\n return candle\n\n\nif __name__ == '__main__':\n find_all_hammer_line()\n","sub_path":"lib/services/candle_service.py","file_name":"candle_service.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"504841724","text":"#################################################\n#\thelper functions for the master routing\t\t#\n#\tfile in python-flask\t\t\t\t\t\t#\n#\tmaster.py \t\t\t\t\t\t\t\t\t#\n#################################################\n\nfrom globalData import *\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom random import randint, shuffle\nfrom time import sleep\nimport gameVars\nimport json\n\n#################################################\n# Begin in-game functions \t\t\t\t\t\t#\n#################################################\n\n# kill\n#\tmurderer's action. Sends the kill function to the NPC\n#\tthat the murderer has selected\ndef killNpc(gd, gameId, npcInd):\n\tgame = gd.getGameIndex()[gameId]\n\tround = game.getCurrentRound()\n\tturn = round.getCurrentTurn()\n\tnpc = round.getGameBoard()[npcInd]\n\tnpc.selectToKill()\n\tturn.setNextVic(npc.getName())\n\n# accuseNpc\n#\tone of the police's actions. \n#\tTODO - returns an error code, maybe?\ndef accuseNpc(gd, gameId, npcInd):\n\tgame = gd.getGameIndex()[gameId]\n\tround = game.getCurrentRound()\n\tnpc = round.getGameBoard()[npcInd]\n\tnpc.accuse()\n\n# saveNpc\n#\tone of the police's actions. \n#\tTODO - returns an error code, maybe?\ndef saveNpc(gd, gameId, npcInd):\n\tgame = gd.getGameIndex()[gameId]\n\tround = game.getCurrentRound()\n\tnpc = round.getGameBoard()[npcInd]\n\tnpc.save()\n\n# getNewRoundData\n# creates a new game with randomized names, pictures, locations\n# for the individual characters\ndef getNewRoundData(gd, gameId):\n\tdata = {}\n\tnpcList = []\n\tgame = gd.getGameIndex()[gameId]\n\tround = game.newRound()\n\tturn = round.newTurn()\n\tturn.advPhase()\n\tgBoard = round.getGameBoard()\n\tfor i in range(0, 15):\n\t\tnpc = {}\n\t\tnpc['img'] = gBoard[i].getPicPath()\n\t\tnpc['name'] = gBoard[i].getName()\n\t\tnpc['bio'] = gBoard[i].getBio()\n\t\tnpcList.append(npc)\n\tdata['roles'] = round.getRoleMap()\n\tdata['npcList'] = npcList\n\tdata['activePlayer'] = data['roles'][0]\n\tdata['killerName'] = round.getThisRoundKiller().getName()\n\treturn data\n\n# getInitRoundData\n# gets the round data for non-ogs\ndef getInitRoundData(gd, gameId):\n\tdata = {}\n\tnpcList = []\n\tgame = gd.getGameIndex()[gameId]\n\tround = game.getCurrentRound()\n\twhile (round == None):\n\t\tsleep(0.1)\n\t\tround = game.getCurrentRound()\n\tturn = round.getCurrentTurn()\n\tgBoard = round.getGameBoard()\n\tfor i in range(0, 15):\n\t\tnpc = {}\n\t\tnpc['img'] = gBoard[i].getPicPath()\n\t\tnpc['name'] = gBoard[i].getName()\n\t\tnpc['bio'] = gBoard[i].getBio()\n\t\tnpcList.append(npc)\n\tdata['roles'] = round.getRoleMap()\n\tdata['npcList'] = npcList\n\tdata['activePlayer'] = data['roles'][0]\n\tdata['killerName'] = round.getThisRoundKiller().getName()\n\treturn data\n\n# getGamesCurRound\n#\treturns the current round of the passed-in game\ndef getGamesCurRound(gd, gameId):\n\treturn gd.getGameIndex()[gameId].getCurrentRound()\n\n\n#################################################\n# End in-game functions \t\t\t\t\t\t#\n#################################################\n\n#################################################\n# Begin Pregame functions \t\t\t\t\t\t#\n#################################################\n\n# getUpdatedPregameInfo\n# \treturns the pregame info, all of it, despite\n#\twhat the name suggests\ndef getUpdatedPregameInfo(gd, gameId, playerId):\n\tdata = dict()\n\tgame = gd.getGameIndex()[gameId]\n\tdata = game.getUpdatedInfo(playerId)\n\tif data['update']:\n\t\tdata['playerInfos'] = []\n\t\tfor pl in data['players']:\n\t\t\tplayerInfo = dict()\n\t\t\tplayerInfo['id'] = pl\n\t\t\tplayerInfo['name'] = gd.getUsers()[pl]['name']\n\t\t\tdata['playerInfos'].append(playerInfo)\n\t\tdel data['players']\n\t\treturn data\n\treturn data\n\n#################################################\n# End pregame functions \t\t\t\t\t\t#\n#################################################\n\n#################################################\n# Begin lobby functions \t\t\t\t\t\t#\n#################################################\n\n# getListUpdate\n#\tCalled by the lobby code - will figure out if the list\n#\tof open and not open games has changed\ndef getListUpdate(gd):\n\tdata = {}\n\tdata['msg'] = \"message!\"\n\tdata['update'] = True\n\tdata['games'] = []\n\tdata['openGames'] = []\n\tplayers = []\n\tgames = gd.getSessions()\n\topenGames = gd.getOpenSessions()\n\tgameIndex = gd.getGameIndex()\n\tgameDict = {}\n\tfor id in games:\n\t\tgame = gameIndex[id]\n\t\tgameDict = {}\n\t\tgameDict['id'] = id\n\t\tgameDict['name'] = game.getName()\n\t\tplayers = game.getPlayers()\n\t\tgameDict['players'] = []\n\t\tfor player in players:\n\t\t\tgameDict['players'].append(int(player))\n\t\tdata['games'].append(gameDict)\n\tfor id in openGames:\n\t\topenGame = gameIndex[id]\n\t\tgameDict = {}\n\t\tgameDict['id'] = id\n\t\tgameDict['name'] = game.getName()\n\t\tplayers = game.getPlayers()\n\t\tgameDict['players'] = []\n\t\tfor player in players:\n\t\t\tgameDict['players'].append(int(player))\n\t\tdata['openGames'].append(gameDict)\n\treturn data\n\n#################################################\n# End lobby functions \t\t\t\t\t\t #\n#################################################\n","sub_path":"mystery/app/helperFunctions.py","file_name":"helperFunctions.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"442099345","text":"## 1. Computer components ##\n\nprint(\"Hello World!\")\n\n## 2. Data storage ##\n\nmy_int = 12\nint_addr = id(my_int)\nmy_str = \"Dadadada Nonsense!\"\nstr_addr = id(my_str)\n\n## 4. Data storage in Python ##\n\nimport sys\n\nmy_int = 200\nsize_of_my_int = sys.getsizeof(my_int)\n\nint1 = 10\nint2 = 100000\nstr1 = \"Hello\"\nstr2 = \"Hi\"\n\nint_diff = sys.getsizeof(int2) - sys.getsizeof(int1)\nprint(int_diff)\n\nstr_diff = sys.getsizeof(str2) - sys.getsizeof(str1)\nprint(str_diff)\n\n## 6. Disk storage ##\n\nimport time\nimport csv\n\nbefore_file = time.clock()\nf = open(\"list.csv\", \"r\")\nlist_from_file = list(csv.reader(f))\nafter_file = time.clock()\nlist_from_RAM = \"1,2,3,4,5,6,7,8,9,10\".split(\",\")\nafter_ram = time.clock()\n\nfile_time = after_file - before_file\nRAM_time = after_ram - after_file\nprint(file_time)\nprint(RAM_time)\n\n## 9. Binary ##\n\n# num1 = (1*2^1) + (1*2^2) = 2 + 4 = 6\n# num2 = (1*2^0) + (1*2^3) = 1 + 8 = 9\n# num3 = (1*2^2) + (1*2^5) = 4 + 32 = 36\nnum1 = 6\nnum2 = 9\nnum3 = 36\n\n## 10. Computation and control flow ##\n\na = 5\nb = 10\nprint(\"On line 3\")\nif a == 5:\n print(\"On line 5\")\nelse:\n print(\"On line 7\")\nif b < a:\n print(\"On line 9\")\nelif b == a:\n print(\"On line 11\")\nelse:\n for i in range(3):\n print(\"On line 14\")\n\nprinted_lines = [3, 5, 14, 14, 14]\n\n## 11. Functions in memory ##\n\ndef my_func():\n print(\"On line 2\")\na = 5\nb = 10\nprint(\"On line 5\")\nmy_func()\nprint(\"On line 7\")\nmy_func()\n\nprinted_lines = [5, 2, 7, 2]","sub_path":"dataquest_exercises/python_advanced/exercise_intro_computer_architecture.py","file_name":"exercise_intro_computer_architecture.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"650252940","text":"import requests\nimport re\nurl = \"http://192.168.23.153/i8/Portal.mvc/LoginValidation\"\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n }\nd = {\n \"Logid\":\"tz\",\n \"Password\":\"\",\n \"Hostname\":\"lenovo-PC\",\n \"DBSelectIndex\":\"0\",\n \"DataBase\":\"0001\",\n \"ConnectType\":\"TCP\",\n \"Language\":\"zh-CN\",\n \"LoginStyle\":\"0\",\n \"isQRlogin\":\"false\",\n \"PagesecCode\":\"99\",\n \"mobileOREmail\":\"\"\n}\nr = requests.post(url, headers=headers, data=d)\n#t = re.findall(r'(.+?)
', r.content)\nprint(r.status_code)\nresult = r.json()\nprint(result)\nmsg = result[\"ErrorMsg\"]\nprint(msg)\n\n\n","sub_path":"case/各种小资源/test01.py","file_name":"test01.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"334096295","text":"import peewee, curses, datetime, sys\nimport npyscreen # tem que ficar\n\n\n# arquivo_bd = 'teste.db'\narquivo_bd = 'financeiro.db'\ndb = peewee.SqliteDatabase(arquivo_bd)\n\n\nclass Conta(peewee.Model):\n\n nome = peewee.CharField(60)\n # ATIVO, PASSIVO, DESPESA, RECEITA\n tipo = peewee.CharField(7)\n saldo_inicial_credito = peewee.DecimalField(13, 2)\n saldo_inicial_debito = peewee.DecimalField(13, 2)\n\n class Meta:\n database = db\n\n\nclass Lancamento(peewee.Model):\n\n conta_debito = peewee.ForeignKeyField(Conta)\n conta_credito = peewee.ForeignKeyField(Conta)\n\n data = peewee.DateField()\n data_vencimento = peewee.DateField(null=True)\n valor = peewee.DecimalField(max_digits=12, decimal_places=2)\n historico = peewee.TextField(null=True)\n\n conciliado = peewee.BooleanField(default=0)\n\n class Meta:\n database = db\n\n def save(self, force_insert=False, only=None):\n if self.data_vencimento is None or len(str(self.data_vencimento)) == 0:\n self.data_vencimento = self.data\n super(Lancamento, self).save(force_insert, only)\n\n\nclass Programacao(peewee.Model):\n conta_debito = peewee.ForeignKeyField(Conta)\n conta_credito = peewee.ForeignKeyField(Conta)\n\n valor = peewee.DecimalField(max_digits=12, decimal_places=2)\n historico = peewee.TextField(null=True)\n\n proxima_data = peewee.DateField()\n quantidade = peewee.IntegerField()\n a_cada = peewee.IntegerField()\n intervalo = peewee.CharField(max_length=1)\n falta = peewee.IntegerField()\n\n\n class Meta:\n database = db\n\n\nclass Migrate(peewee.Model):\n\n identificacao = peewee.CharField()\n data = peewee.DateTimeField(default=datetime.datetime.now())\n\n class Meta:\n database = db\n\n\nclass TipoConta:\n def __init__(self, id, nome):\n self.id = id\n self.nome = nome\n\n def __str__(self):\n return str(self.id)\n\nclass Intervalo:\n def __init__(self, chave:str, nome:str):\n self.nome = nome\n self.chave = chave\n\n @property\n def id(self):\n return str(self.chave)\n\n def __str__(self):\n return str(self.id)\n\n\nclass OpcaoMenu:\n\n dict_atalho = {\n curses.KEY_LEFT: '<-',\n curses.KEY_RIGHT: '->',\n curses.KEY_F12: 'F12',\n curses.ascii.SP: 'Space',\n ord('q'): 'q'\n }\n\n def __init__(self, atalho, funcao, texto, ativo=True, exibindo=False, principal=False):\n \"\"\"\n\n :param atalho: str ou int\n Atalho de teclado ou tecla que aciona a opção de menu. Exemplo ^C -> Ctrl+C ou curses.KEY_F12 -> Tecla F12\n :param funcao: callback\n Função que será chamada quando o usuário acionar a opção de menu.\n :param texto: str\n Texo que será exibido na opção de menu\n :param ativo: bool\n Define se a opção de menu está ativa no momento\n :param exibindo: bool\n Define se a opção de menu está sendo exibida no momento.\n\n >>> import curses\n >>> def teste(*args, **kwargs):\n ... print('passou!!')\n ...\n >>> op = OpcaoMenu(curses.KEY_UP, teste, 'Passou?')\n >>> print(op.texto)\n Passou?\n >>> op.funcao()\n passou!!\n >>> op.exibindo = False\n >>> op.exibindo\n False\n >>> op.principal\n False\n \"\"\"\n self.atalho = atalho\n self.funcao = funcao\n self.texto = texto\n self.ativo = ativo\n self.exibindo = exibindo\n self.principal = principal\n\n @property\n def atalho_exibicao(self):\n \"\"\"\n Retorna o atalho que será exibido na legenda,traduzido quando necessário.\n\n :return: str\n\n >>> import curses\n >>> def teste(*args, **kwargs):\n ... print('passou!!')\n ...\n >>> op = OpcaoMenu(curses.KEY_LEFT, teste, 'Esquerda')\n >>> op.atalho_exibicao\n '<-'\n >>> op.atalho = '^C'\n >>> op.atalho_exibicao\n '^C'\n \"\"\"\n if isinstance(self.atalho, int):\n return self.dict_atalho[self.atalho] if self.atalho in self.dict_atalho else '?'\n else:\n return self.atalho\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()","sub_path":"entidades.py","file_name":"entidades.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"549050387","text":"def replaceString(str1,str2,str3):\n product = list(str1)\n str1 = list(str1)\n for x in range(len(str1)):\n word = \"\"\n for y in range(len(str2)):\n try:\n if str1[x+y].lower() == str2[y].lower():\n word += f\"{str1[x+y]}\"\n if word.lower() == str2.lower():\n product[x]=str3\n for y in range(1,len(str2)):\n product.pop(x+y)\n str1.pop(x+y)\n except:\n continue\n return \"\".join(product)\nprint(replaceString(\"Is this the real life? Is this just fantasy?\",\"iS\",\"cool\"))","sub_path":"exercise6/strengemanipulasjon.py","file_name":"strengemanipulasjon.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"37330605","text":"#! /usr/bin/env python3\nimport sys\nimport traceback\nimport time\nimport random\nimport socketserver\n\n__author__ = 'damazdejong'\n\n\nclass Instrument:\n def __init__(self, **kwargs):\n self.commandcounter = 0\n self.resistor = 50\n self.current = 0\n self.state = 1\n\n def packet_handler(self, msg):\n msg = msg.upper()\n r = \"\"\n try:\n if msg.startswith('READ:'):\n self.commandcounter += 1\n r = self.readhandler(msg[5:])\n elif msg.startswith('SET:'):\n self.commandcounter += 1\n r = self.sethandler(msg[4:])\n else:\n r = \"ERR:CMD?\"\n except:\n print(\"Houston, We have a problem!!!\")\n print(msg)\n traceback.print_exc(file=sys.stdout)\n r = None\n # todo shout!!!\n return r\n\n def readhandler(self, command):\n if self.state == 0:\n #time.sleep(20)\n return None\n time.sleep(0.01)\n if random.random() > 0.95:\n return \"ERR:BUSY\"\n elif command.startswith('VOL'):\n return \"STAT:VOL:\" + str(self.current * self.resistor * (\n 0.8 + 0.4 * random.random())) + \"V\"\n elif command.startswith('RES'):\n return \"STAT:RES:\" + str(self.resistor) + \"Ohm\"\n elif command.startswith('CUR'):\n return \"STAT:CUR:\" + str(self.current) + \"A\"\n return \"ERR:CMD?\"\n\n def sethandler(self, command):\n if self.state == 0:\n #time.sleep(20)\n return None\n time.sleep(0.01)\n time.sleep(0.01)\n if random.random() > 0.95:\n return \"ERR:BUSY\"\n elif command.startswith(\"RES\"):\n res = ''.join([c for c in command if c in '1234567890.'])\n r = float(res)\n for ref in [1, 10, 100, 1000]:\n if ref == r:\n self.resistor = ref\n return \"STAT:RES:\" + str(res) + \"Ohm\"\n return \"ERR:RES?\"\n elif command.startswith(\"CUR\"):\n cur = ''.join([c for c in command if c in '-1234567890.'])\n try:\n i = float(cur)\n if abs(i) > 1:\n return \"ERR:RNG?\"\n else:\n self.current = i\n return \"STAT:CUR:\" + str(i) + \"A\"\n except:\n return \"ERR:VAL?\"\n\n return \"ERR:CMD?\"\n\n\ninstrument = Instrument()\n\nclass Server(socketserver.BaseRequestHandler):\n\n def handle(self):\n data = self.request.recv(1024).strip().decode('utf8')\n response = instrument.packet_handler(data)\n if response is not None:\n self.request.send(response.encode('utf8'))\n # otherwise don't respond -- let the client hang\n\nif __name__ == \"__main__\":\n HOST, PORT = \"0.0.0.0\", 5000\n\n # Create the server, binding to localhost on port 5000\n server = socketserver.TCPServer((HOST, PORT), Server, bind_and_activate=False)\n server.allow_reuse_address = True\n server.server_bind()\n server.server_activate()\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n try:\n server.serve_forever()\n except KeyboardInterrupt:\n pass\n finally:\n server.server_close()\n","sub_path":"Material/day5/voltage_measurement.py","file_name":"voltage_measurement.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"146292345","text":"from ddtrace.vendor import wrapt\n\nfrom ...pin import Pin\nfrom ...utils.wrappers import unwrap\n\n\ntry:\n # instrument external packages only if they're available\n import aiohttp_jinja2\n from .template import _trace_render_template\n\n template_module = True\nexcept ImportError:\n template_module = False\n\n\ndef patch():\n \"\"\"\n Patch aiohttp third party modules:\n * aiohttp_jinja2\n \"\"\"\n if template_module:\n if getattr(aiohttp_jinja2, '__datadog_patch', False):\n return\n setattr(aiohttp_jinja2, '__datadog_patch', True)\n\n _w = wrapt.wrap_function_wrapper\n _w('aiohttp_jinja2', 'render_template', _trace_render_template)\n Pin(app='aiohttp', service=None).onto(aiohttp_jinja2)\n\n\ndef unpatch():\n \"\"\"\n Remove tracing from patched modules.\n \"\"\"\n if template_module:\n if getattr(aiohttp_jinja2, '__datadog_patch', False):\n setattr(aiohttp_jinja2, '__datadog_patch', False)\n unwrap(aiohttp_jinja2, 'render_template')\n","sub_path":"ddtrace/contrib/aiohttp/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"211183117","text":"'''\nThis module defines DataSet classes related to RT-LAB.\n'''\n\nimport os\n\nfrom optoolbox import OpLog\nlogger = OpLog.getLogger('main')\n\nfrom optoolbox import optest\nfrom optoolbox import SimulinkModelConfig\n\n# Tell the DataSet class that there are some others keys to restrict usage\noptest.DataSet.addRestrictedKeys(['model', 'extraFiles'])\n\n\nclass RtlabModelDataSet(optest.DataSet):\n '''\n This class implements a DataSet that specifies Model data for an optest Execution.\n '''\n\n def __init__(self, name, modelPath, modelAttributes={}, **kwargs):\n \"\"\"\n Constructor method. Validate data types of required and optional inputs.\n \n Args:\n - name: String passed to the base class. This is the name of the dataSet and must be unique.\n - modelPath: A string giving the path to the Simulink model file to use. The model must have .mdl or .slx extension.\n - modelAttributes: An optional dictionary of attributes to be set on the model llm file.\n - kwargs: An optional list of keyword arguments to include some additional user information in the DataSet.\n \n Raises:\n TypeError if modelPath is not a string\n TypeError if modelAttributes is not a dict.\n \"\"\"\n super(RtlabModelDataSet,self).__init__(name, **kwargs)\n \n if not isinstance(modelPath, basestring):\n raise TypeError(\"RtlabModelDataSet: The modelPath parameter is not a string for DataSet object '{0}'. Current type is {1} and current value is {2}.\".format(self.name, type(modelPath), modelPath))\n else:\n self.data['modelPath'] = os.path.abspath(modelPath)\n\n if not isinstance(modelAttributes, dict):\n raise TypeError(\"RtlabModelDataSet: The attributes parameter is not a dictionary for DataSet object '{0}'. Current type is {1} and current value is {2}.\".format(self.name, type(modelAttributes), modelAttributes))\n else:\n self.data['modelAttributes'] = modelAttributes\n\n\n def validate(self):\n \"\"\"Validate the data beyond data types.\n If the data contained in the dataSet is valid, the method will return a single entry dictionary\n with value representing the dataSet object.\n \n Note: This method is used to defer validation of information at a later point than the __init__ method.\n \n Note: For now this method does not do much besides validating some .ini config file that can come\n along with the model file, but maybe later it will do more validation.\n \n Returns:\n - A dictionary of one item giving {name:dataSet}\n \n Raises:\n - TypeError if some data in the dataSet is not of the correct type.\n \"\"\"\n\n if not os.path.isfile(self.data['modelPath']):\n raise ValueError(\"RtlabModelDataSet: The modelPath '{0}' does not point to a valid file. Check that the file exists and has .mdl or .slx extension.\".format(self.data['modelPath']))\n\n self.data['model'] = None # We will instantiate a SimulinkModel object later.\n\n # Get the config file\n ### TODO: Merge attributes and config file. Only the latter should be used ! Also need to use the standard config validator classes!\n configPath = \"{0}.ini\".format(os.path.splitext(self.data['modelPath'])[0])\n configValidator = SimulinkModelConfig(configPath)\n self.data['extraFiles'] = configValidator.getExtraFiles()\n \n return {self.name:self.data}\n \n\n\nclass RtlabProjectDataSet(optest.DataSet):\n '''\n This class implements a DataSet that specifies Project data for an optest Execution.\n '''\n\n def __init__(self, name, projectPath, modelFileName, modelAttributes={}, **kwargs):\n \"\"\"\n Constructor method. Validate data types of required and optional inputs.\n \n Args:\n - name: String passed to the base class. This is the name of the dataSet and must be unique.\n - projectPath: A string giving the path to the RT-LAB project to use (must be an .llp file).\n - modelFileName: A string giving the name of the model to execute within the project. The model must exists inside the project.\n - modelAttributes: An optional dictionary of attributes to be set on the model llm file.\n - kwargs: An optional list of keyword arguments to include some additional user information in the DataSet.\n \n Raises:\n TypeError if projectPath is not a string\n TypeError if modelFileName is not a string\n TypeError if modelAttributes is not a dict.\n \"\"\"\n super(RtlabProjectDataSet,self).__init__(name, **kwargs)\n\n if not isinstance(projectPath, basestring):\n raise TypeError(\"RtlabProjectDataSet: The projectPath parameter is not a string for DataSet object '{0}'. Current type is {1} and current value is {2}.\".format(self.name, type(projectPath), projectPath))\n else:\n self.data['projectPath'] = os.path.abspath(projectPath)\n\n if not isinstance(modelFileName, basestring):\n raise TypeError(\"RtlabProjectDataSet: The modelFileName parameter is not a string for DataSet object '{0}'. Current type is {1} and current value is {2}.\".format(self.name, type(modelFileName), modelFileName))\n else:\n self.data['modelFileName'] = modelFileName\n\n if not isinstance(modelAttributes, dict):\n raise TypeError(\"RtlabProjectDataSet: The attributes parameter is not a dictionary for DataSet object '{0}'. Current type is {1} and current value is {2}.\".format(self.name, type(modelAttributes), modelAttributes))\n else:\n self.data['modelAttributes'] = modelAttributes\n\n\n def validate(self):\n \"\"\"Validate the data beyond data types.\n If the data contained in the dataSet is valid, the method will return a single entry dictionary\n with value representing the dataSet object.\n \n Note: This method is used to defer validation of information at a later point than the __init__ method.\n \n Note: For now this method does not do much besides validating that the projectPath points to an .llp file,\n but maybe later it will do more validation.\n \n Returns:\n - A dictionary of one item giving {name:dataSet}\n \n Raises:\n - ValueError if projectPath does not end with .llp\n \"\"\"\n\n if not (os.path.isfile(self.data['projectPath']) and self.data['projectPath'].endswith('.llp')):\n raise ValueError(\"RtlabProjectDataSet: The projectPath parameter must point to a valid .llp file (file extension required) for DataSet object '{0}'. Current value is {1}.\".format(self.name, self.data['projectPath']))\n \n self.data['model'] = None # We do not know the model location before opening the project, so we will let RT-LAB tell us at a later point.\n \n return {self.name:self.data}\n\n\n\n\nif __name__ == '__main__':\n o=RtlabModelDataSet('unNom', tata='toto')\n o.validate()","sub_path":"src/optoolbox/rtlabtools/rtlabDataSet.py","file_name":"rtlabDataSet.py","file_ext":"py","file_size_in_byte":7147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"420644665","text":"import pymysql\nfrom dotenv import load_dotenv\nimport os\n\n\nclass DataBase:\n\n def __init__(self):\n load_dotenv(os.getcwd() + \"/.env.orangeHRM\")\n\n host = os.getenv('HOST')\n user = os.getenv('USER_DB')\n password = os.getenv('PASSWORD')\n db = os.getenv('DB')\n\n self.connection = pymysql.connect(\n host=host,\n user=user,\n password=password,\n db=db\n )\n\n self.cursor = self.connection.cursor()\n\n def get_employee_by_id(self, employee_id):\n\n try:\n sql = 'SELECT * FROM hs_hr_employee WHERE employee_id=%s'\n value = employee_id\n self.cursor.execute(sql, value)\n result = self.cursor.fetchone()\n\n return result\n\n except Exception as e:\n self.connection.rollback()\n print(f'Exception to get employee: {e}')\n\n finally:\n self.connection.close()\n\n def get_employee_number(self, employee_number):\n\n try:\n sql = 'SELECT * FROM hs_hr_employee WHERE emp_number=%s'\n value = employee_number\n self.cursor.execute(sql, value)\n result = self.cursor.fetchone()\n\n return result\n\n except Exception as e:\n self.connection.rollback()\n print(f'Exception to get employee: {e}')\n\n finally:\n self.connection.close()\n\n def get_salary_component(self, salary_component):\n\n try:\n sql = 'SELECT * FROM hs_hr_emp_basicsalary WHERE salary_component=%s'\n value = salary_component\n self.cursor.execute(sql, value)\n result = self.cursor.fetchone()\n\n return result\n\n except Exception as e:\n self.connection.rollback()\n print(f'Exception to get employee: {e}')\n\n finally:\n self.connection.close()\n\n","sub_path":"BDD-Selenium/features/lib/data/query_employee.py","file_name":"query_employee.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"70455647","text":"import pygame as p\r\nimport random as r\r\nimport time as t\r\n\r\np.init()\r\n\r\nsize = (800,400)\r\nw = (255,255,255)\r\nsc = p.display.set_mode(size)\r\np.display.set_caption(\"두더지 게임\")\r\ndo_image = p.image.load(\"q.png\") \r\ndo_list = []\r\nfor i in range(5): \r\n do = do_image.get_rect(left=r.randint(0,750),top = r.randint(0,350))\r\n do_list.append(do)\r\nplaying = True\r\nclock = p.time.Clock()\r\n\r\nfont = p.font.SysFont('malgungothic',20)\r\nscore = 0\r\n\r\nt1=int(t.time())\r\n\r\n\r\np.mixer.init()\r\nhit=p.mixer.Sound(\"야.wav\")\r\n \r\n\r\n\r\nwhile playing:\r\n\r\n clock.tick(60)\r\n\r\n for event in p.event.get():\r\n if event.type == p.QUIT:\r\n playing = False\r\n p.quit()\r\n quit\r\n if event.type == p.MOUSEBUTTONDOWN: #1.마우스를 클릭했을때\r\n for do in do_list: \r\n if do.collidepoint(event.pos):#2. 두더지들을 클릭하게되면\r\n \r\n score= score+1\r\n do_list.remove(do) #3.리스트에 있는 두더지 삭제\r\n do = do_image.get_rect(left=r.randint(0,700),top = r.randint(0,300)) #4.두더지 재배치\r\n do_list.append(do)#5.리스트에 추가\r\n hit.play()\r\n \r\n sc.fill(w)\r\n for do in do_list: \r\n sc.blit(do_image,do)\r\n\r\n text = font.render(\"점수: {}\".format(score),True,(0,0,0))\r\n sc.blit(text,(300,0))\r\n t2=int(t.time())\r\n ti=60 - (t2-t1)\r\n text1 = font.render(\"남은 시간: {}\".format(ti),True,(0,0,0))\r\n if ti==0 :\r\n playing=False\r\n sc.blit(text1,(650,0))\r\n p.display.flip()\r\n\r\n \r\n","sub_path":"04.두더지 게임_점수 .py","file_name":"04.두더지 게임_점수 .py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"487219053","text":"import socket\n\nclass mySerSocket:\n def __init__(self, ip, port, socket=None):\n self.ip = ip\n self.port = port\n self.socket = socket\n \n def createSerSocket(self):\n self.socket = socket.socket()\n self.socket.bind((self.ip, self.port))\n return self.socket\n\n def destroySerSocket(self):\n self.socket.close()\n\n def startSerSocket(self, socket, listen_num=5, buffer_size=1024):\n if socket != None:\n socket.listen(listen_num)\n flag = True\n while flag:\n clisock, cliaddr = socket.accept()\n \n data = clisock.recv(buffer_size)\n print(\"from client:\"+cliaddr+\" \"+data)\n if data == 'exit':\n flag = False\n clisock.send(\"OK!\")\n clisock.close()\n else:\n print(\"Socket Error!\\n\")\n\nclass myCliSocket:\n def __init__(self, ip, port, socket=None):\n self.ip = ip\n self.port = port\n self.socket = socket\n\n def createCliSocket(self):\n self.socket = socket.socket()\n return self.socket\n\n def destroyCliSocket(self):\n self.socket.close()\n\n def startCliSocket(self, socket, buffer_size, send_content=None):\n if send_content == None:\n if socket != None:\n socket.connect((self.ip, self.port))\n inform = raw_input('client>')\n socket.send(inform)\n response = socket.recv(buffer_size)\n print(\"get info:\"+response)\n return response\n else:\n print(\"Socket Error!\\n\")\n return None\n else:\n if socket != None:\n socket.connect((self.ip, self.port))\n socket.send(send_content)\n response = socket.recv(buffer_size)\n print(\"get info:\"+response)\n return response\n else:\n print(\"Socket Error!\\n\")\n return None\n\n\n \n \n\n\n\n","sub_path":"agent/server_comm.py","file_name":"server_comm.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"434904130","text":"import torch\nimport numpy as np\nfrom numpy import linalg as LA\nimport os.path as osp\nfrom graph_dataset import Graph_Dataset\nfrom torch_geometric.data import DataLoader\nimport torch.nn.functional as F\nfrom torch.nn import Sequential as Seq, Linear as Lin, ReLU, BatchNorm1d as BN, Softmax\nfrom torch_geometric.nn import radius, TAGConv, global_max_pool as gmp, fps\nfrom train import Net\n\nif __name__ == '__main__':\n dataset_name = 'ModelNet10'\n path = osp.join('dataset', dataset_name)\n train_dataset = Graph_Dataset(path, '10', True)\n test_dataset = Graph_Dataset(path, '10', False)\n print(len(train_dataset))\n print(len(test_dataset))\n print('Dataset loaded.')\n\n train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True, drop_last=True,\n num_workers=2)\n test_loader = DataLoader(test_dataset, batch_size=16, shuffle=True, drop_last=True,\n num_workers=2)\n\n device = torch.device('cuda')\n\n model = Net()\n\n model.to(device)\n\n it = iter(train_loader)\n data = next(it)\n data = data.to(device)\n\n r, pos, batch = data.r, data.pos, data.batch\n #idx = fps(pos, batch, ratio=0.5)\n #print(idx[:10])\n #print(idx[4096-10:])\n \n bz = batch[-1]+1\n rep_index = np.array(list(range(128)))\n idx = torch.tensor([rep_index+512*i for i in range(bz)])\n idx = idx.view(-1,1)\n idx = torch.squeeze(idx)\n idx = idx.long()\n idx = idx.to(device)\n r_limit = r[0]*1.5\n\n #row, col = radius(pos, pos[idx], r_limit, batch, batch[idx], max_num_neighbors=64)\n #edge_index = torch.stack([col, row], dim=0)# (col, row), or (col row)\n #edge_attr = torch.ones((edge_index.shape[1],1))\n y = model(data,idx)\n print(y)\n ","sub_path":"tdd.py","file_name":"tdd.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"594181698","text":"# \nimport os\nimport os.path as p\nimport re\nimport sys\nimport datetime\nfrom time import time\nfrom argparse import ArgumentParser\n\nsys.path.append(p.join(p.dirname(__file__), '..'))\nsys.path.append(p.join(p.dirname(__file__), '../..'))\n# \n\n# \narp = ArgumentParser(description='Prepare vectors for training a base index.')\n\narp.add_argument('input_file', help='')\narp.add_argument('output_dir', help='')\narp.add_argument('-v', '--verbose', action='store_true',\n help='Shows progress of batch vectorization.')\narp.add_argument('-V', '--verbose_vectorizer', action='store_true', default=False,\n help='Shows vectorization time for each mini-batch.')\narp.add_argument('-l', '--USE_large', action='store_true',\n help='Toggle large Universal Sentence Encoder (Transformer NN).')\narp.add_argument('-m', '--m_per_batch', type=int, default=512*128,\n help='Sentences per batch.')\narp.add_argument('-n', '--n_per_minibatch', type=int, default=64,\n help='Sentences per mini-batch.')\narp.add_argument('-t', '--num_threads',\n help='Set CPU thread budget for numpy.')\nopts = arp.parse_args()\n# \n\nif opts.num_threads:\n print(f'\\nRestricting numpy to {opts.num_threads} thread(s)\\n')\n os.environ['OPENBLAS_NUM_THREADS'] = opts.num_threads\n os.environ['NUMEXPR_NUM_THREADS'] = opts.num_threads\n os.environ['MKL_NUM_THREADS'] = opts.num_threads\n os.environ['OMP_NUM_THREADS'] = opts.num_threads\n\nfrom dt_sim.data_reader.jl_io_funcs import check_training_docs, get_training_docs\nfrom dt_sim.data_reader.npz_io_funcs import save_with_ids\nfrom dt_sim.data_reader.misc_io_funcs import check_unique\nfrom dt_sim.vectorizer.sentence_vectorizer import SentenceVectorizer\nfrom dt_sim.processor.corpus_processor import CorpusProcessor\n\n\n# Init\nsv = SentenceVectorizer(large=opts.USE_large)\ncp = CorpusProcessor(vectorizer=sv)\n\n\ndef main():\n # Paths\n input_file = opts.input_file\n if opts.report:\n print(f'Will process: {input_file}\\n')\n\n date_today = str(datetime.date.today())\n if date_today in input_file:\n date = date_today\n else:\n seed = str(r'\\d{4}[-/]\\d{2}[-/]\\d{2}')\n date = re.search(seed, input_file).group()\n\n # Nested output dirs\n if not opts.output_dir:\n output_dir = p.abspath(p.join(p.dirname(input_file),\n '../training_npzs/'))\n else:\n output_dir = opts.output_dir\n daily_dir = p.join(output_dir, date)\n if not p.isdir(output_dir):\n os.mkdir(output_dir)\n if not p.isdir(daily_dir):\n os.mkdir(daily_dir)\n\n # Check File Content\n if opts.report:\n print(f'\\nReading file: {input_file}')\n\n line_counts = check_training_docs(input_file, batch_size=opts.m_per_batch)\n (doc_count, line_count, good_sents, junk, n_batches, n_good_batches) = line_counts\n if opts.report:\n print(f'* Found {doc_count} good documents with {line_count} lines '\n f'and {good_sents} good sentences\\n'\n f'* Will skip {junk} junk documents\\n'\n f'* Processing {n_good_batches}:{n_batches} batches\\n')\n\n # Make Training Vectors\n t_start = time()\n doc_batch_gen = get_training_docs(input_file, batch_size=opts.m_per_batch)\n for i, (batched_sents, batched_ids) in enumerate(doc_batch_gen, start=1):\n t_0 = time()\n if opts.report:\n print(f' Starting doc batch: {i:3d}')\n\n npz = str(input_file.split('/')[-1]).replace('.jl', f'_{i:03d}_train.npz')\n npz_path = p.join(daily_dir, npz)\n\n if p.exists(npz_path):\n print(f' File exists: {npz_path} \\n Skipping... ')\n else:\n # Vectorize\n emb_batch, id_batch = cp.batch_vectorize(\n text_batch=batched_sents, id_batch=batched_ids,\n n_minibatch=opts.n_per_minibatch, very_verbose=opts.verbose_vectorizer\n )\n t_vect = time()\n if opts.report:\n print(f' * Vectorized in {t_vect - t_0:6.2f}s')\n\n # Save .npz for later\n npz_path = check_unique(npz_path)\n save_with_ids(npz_path, embeddings=emb_batch, sent_ids=id_batch,\n sentences=batched_sents, compressed=False)\n t_npz = time()\n if opts.report:\n print(f' * Saved .npz in {t_npz - t_vect:6.2f}s')\n\n # Clear graph\n del emb_batch, id_batch, batched_sents, batched_ids\n cp.vectorizer.close_session()\n t_reset = time()\n if opts.report:\n print(f' * Cleared TF in {t_reset - t_npz:6.2f}s')\n\n # Restart TF session if necessary\n if i < n_batches:\n cp.vectorizer.start_session()\n if opts.report:\n print(f' * Started TF in {time() - t_reset:6.2f}s')\n\n if opts.report:\n mp, sp = divmod(time() - t_start, 60)\n print(f' Completed doc batch: {i:3d}/{n_good_batches} '\n f' Total time passed: {int(mp):3d}m{sp:0.2f}s\\n')\n\n\nif __name__ == '__main__':\n if p.isfile(opts.input_file):\n main()\n else:\n print(f'File not found: {opts.input_file}')\n","sub_path":"py_scripts/preprocessing/make_training_vectors.py","file_name":"make_training_vectors.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"206124739","text":"from django import forms \nfrom .models import *\n\nclass Booking_form(forms.ModelForm):\n\n\t\n cname = forms.CharField()\n email = forms.EmailField()\n ph_no = forms.CharField()\n start_date = forms.DateField()\n end_date = forms.DateField()\n Address = forms.CharField( widget=forms.Textarea )\n class Meta:\n model = Booking\n fields=['cname','email','ph_no','start_date','end_date','Address']\n","sub_path":"fronted/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"504689784","text":"from django.test import TestCase\nfrom district.models import District\nfrom Province.models import Province\n\n\nclass TestModel(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n\n province_data = {\n 'sinhalaName': \"බස්නාහිර\",\n \"englishName\": \"Western\",\n \"tamilName\": \"மேல் மாகாணம்\"\n }\n\n cls.province = Province.objects.create(**province_data)\n cls.district = District.objects.create(\n **province_data, province=cls.province\n )\n\n def test_absolute_url(self):\n\n ACTUAL_PATH = self.district.get_absolute_url()\n EXPECTED_URL = \"/adminpanel/district/edit/{}/\".format(\n self.district.pk)\n\n self.assertEqual(ACTUAL_PATH, EXPECTED_URL)\n\n def test_info(self):\n\n self.assertEqual(self.district.sinhalaName, \"බස්නාහිර\")\n self.assertEqual(self.district.englishName, \"Western\")\n self.assertEqual(self.district.tamilName, \"மேல் மாகாணம்\")\n","sub_path":"district/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"181867673","text":"# How to run\n# 1. Create a Kafka topic wordcounttopic and pass in your ZooKeeper server\n# /usr/hdp/current/kafka-broker/bin/kafka-topics.sh --create --zookeeper localhost:2181 --topic wordcounttopic --partitions 1 --replication-factor 1\n\n# pyspark to run\nfrom __future__ import print_function\n\nimport sys\n\nfrom pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: kafka_wordcount.py \", file=sys.stderr)\n exit(-1)\n\n sc = SparkContext(appName=\"PythonStreamingKafkaWordCount\")\n sc.setLogLevel(\"WARN\")\n ssc = StreamingContext(sc, 1)\n\n zkQuorum, topic = sys.argv[1:]\n kvs = KafkaUtils.createStream(ssc, zkQuorum, \"spark-streaming-consumer\", {topic: 1})\n lines = kvs.map(lambda x: x[1])\n counts = lines.flatMap(lambda line: line.split(\" \")) \\\n .map(lambda word: (word, 1)) \\\n .reduceByKey(lambda a, b: a+b)\n counts.pprint()\n\n ssc.start()\n ssc.awaitTermination()\n\n\n\n# In another window, start a Kafka producer that publishes to wordcounttopic:\n# $ /usr/hdp/current/kafka-broker/bin/kafka-console-producer.sh --broker-list realhostname:6667 --topic wordcounttopic\n\n# To verify this console producer\n# /usr/hdp/current/kafka-broker/bin/kafka-simple-consumer-shell.sh --broker-list realhostname:6667 --topic wordcounttopic --partition 0\n\n# spark-submit --jars /usr/hdp/2.5.0.0-1133/spark/lib/spark-streaming-kafka-assembly_2.10-1.6.0.jar \\\n# SparkStreamingKafkaWordCount.py \\\n# localhost:2181 wordcounttopic\n\n","sub_path":"SparkStreamingKafkaWordCount.py","file_name":"SparkStreamingKafkaWordCount.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"124566767","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 ('public', '0007_remove_homepage_name'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='homepage',\n name='name',\n field=models.CharField(default='what', unique=True, max_length=30),\n preserve_default=False,\n ),\n ]\n","sub_path":"public/migrations/0008_homepage_name.py","file_name":"0008_homepage_name.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"630840449","text":"import selenium\nfrom selenium import webdriver\nfrom datetime import datetime\nimport time\nimport datetime as DT\nimport urllib\nimport zipfile\nimport os\nimport os.path\nimport base64\n\nsavePath = 'D:\\\\Files\\list.zip'\nusername = 'Vincent.Wei'\npassword = 'Dd123456'\ntargetUrl = 'https://' + username + ':' + password +'@e1cube.ef.cn/adhocquery'\ndomain = 'https://e1cube.ef.cn'\n\ndirname = os.path.dirname(savePath)\nif os.path.exists(dirname)== False:\n os.makedirs(dirname)\n\nif os.path.exists(os.path.join(dirname,'list.csv')) == True:\n raise Exception('old data not clean.')\n\nbrowser = webdriver.Firefox()\nbrowser.get(targetUrl)\n\nsuccess = False;\nwhile success == False:\n try:\n browser.implicitly_wait(5)\n txtSQL = browser.find_element_by_id('txtSQL')\n submit_button = browser.find_element_by_id('btnExecute')\n cancel_button = browser.find_element_by_id('btnCancel')\n\n querydate = str(DT.date.today() - DT.timedelta(days=1))\n query = 'SELECT\\\n Country\\\n ,City\\\n ,CourseLevel\\\n ,DeepBlueSchoolCode\\\n ,Email\\\n ,FirstName\\\n ,EnquiryStatusCode\\\n ,EnquirySubStatusName\\\n ,MobilePhoneNo\\\n ,DateSubmitted \\\n FROM\\\n (\\\n SELECT \\\n *,ROW_NUMBER() OVER(PARTITION BY EMAIL ORDER BY DateSubmitted DESC) AS NUM\\\n FROM MKTAnalysis.dbo.Offlinedetails WHERE Email != \\'-\\' AND CourseLevel in(\\'YA\\',\\'hf\\',\\'tb\\',\\'ss\\')\\\n ) T \\\n WHERE T.NUM = 1 and DateSubmitted > \\'' + querydate +'\\''\n\n #init text\n txtSQL.clear()\n txtSQL.send_keys(query)\n browser.implicitly_wait(1)\n\n #start to try click btn\n print('try start query')\n submit_button.click()\n browser.implicitly_wait(3)\n clickTryCount = 0\n\n #make sure btn is click\n while submit_button.get_attribute('disabled') == None:\n if(clickTryCount > 3):\n print('reopen page')\n raise Exception('')\n \n submit_button.click()\n browser.implicitly_wait(3)\n clickTryCount=clickTryCount+1\n print('retry start query')\n\n #get file address.\n print('query started')\n starttime = time.time()\n maxWaitSecond = 600\n filelink = 'notGet'\n while 'zip' not in filelink:\n filelink = browser.find_element_by_id('lnkDownload').get_attribute('href')\n if(filelink == None):\n filelink = 'notGet'\n time.sleep(10)\n #bug of page both btn disabled.\n if(time.time()-starttime > maxWaitSecond):\n print('reopen page for download timeout')\n raise Exception('')\n \n print('query compelete')\n fileaddress = domain + filelink.split('e1cube.ef.cn')[1]\n print('down load address : '+fileaddress)\n\n #download\n urllib.request.urlretrieve(fileaddress, savePath)\n \n while os.path.isfile(savePath) == False:\n print('downloading...')\n time.sleep(10)\n\n #decompress\n zfile = zipfile.ZipFile(savePath)\n for name in zfile.namelist():\n print(\"Decompressing \" + name + \" on \" + dirname)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n zfile.extract(name, dirname)\n os.rename(os.path.join(dirname,name),os.path.join(dirname,'list.csv'))\n\n print('Done')\n #close all \n zfile.close()\n success = True\n browser.close()\n os.system('tskill geckodriver')\n except selenium.common.exceptions.UnexpectedAlertPresentException:\n browser.implicitly_wait(5)\n alert = browser.switch_to.alert\n if(alert != None):\n alert.dismiss();\n except selenium.common.exceptions.WebDriverException:\n browser.implicitly_wait(5)\n alert = browser.switch_to.alert\n if(alert != None):\n alert.dismiss();\n except selenium.common.exceptions.NoSuchElementException:\n browser.implicitly_wait(5)\n alert = browser.switch_to.alert\n print(alert)\n if(alert != None):\n alert.dismiss();\n except Exception as e:\n print(e)\n browser.implicitly_wait(5)\n browser.get(targetUrl)\n \n \n\n \n","sub_path":"fetchData.py","file_name":"fetchData.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"111487220","text":"# import glob\r\n# #http://matplotlib.org/downloads.html\r\nimport matplotlib.pyplot as plt\r\n# from sklearn import manifold\r\n# from sklearn.metrics import euclidean_distances\r\n\r\n\r\nfile1 = open(\"ds_features/ds1_features.txt\", \"r\")\r\n\r\nresult_arr = []\r\nfor line in file1:\r\n current_arr = []\r\n for val in line.split(\" \"):\r\n val = val.replace(\"\\r\", \"\")\r\n val = val.replace(\"\\n\", \"\")\r\n current_arr.append(val)\r\n result_arr.append(current_arr)\r\n\r\nz=[]\r\n\r\nfor arr in result_arr:\r\n for x in arr:\r\n try:\r\n plt.scatter( float(x), 10 )\r\n except ValueError:\r\n x = x\r\n\r\n\r\nplt.show()","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"117183397","text":"from django.shortcuts import render\nfrom django.http import HttpResponse , JsonResponse, StreamingHttpResponse\nfrom django.http.request import QueryDict\nfrom django.views.decorators.http import require_http_methods\nfrom django.template import loader\nfrom django.views.generic import View, TemplateView, ListView\nfrom .models import TableName\nimport json, csv\n\n\n\nfrom django.core.paginator import Page, Paginator\n\n # name = models.CharField(max_length=128, blank=True, null=True)\n # price = models.IntegerField(blank=True, null=True)\n # link = models.CharField(max_length=512, blank=True, null=True)\n # pic_path = models.CharField(max_length=64, blank=True, null=True)\n\n\n\n# 这个应该没啥用\nclass BookListView(View):\n def get(self, request, *args, **kwargs):\n return HttpResponse('success')\n\n# 这个应该没啥用\nclass AddBookView(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'add_article.html')\n\n def post(self, request, *args, **kwargs):\n title = request.POST.get(\"title\")\n content = request.POST.get(\"content\")\n args = request.POST.getlist(\"tags\")\n print(title,content,args)\n return HttpResponse(\"success\")\n def http_method_not_allowed(self, request, *args, **kwargs):\n return HttpResponse(\"你请求的方法不存在!\")\n\n# 这个应该没啥用\nclass AboutView(TemplateView):\n template_name = 'about.html'\n\n def get_context_data(self, **kwargs):\n content = {\n 'phone': \"111111\"\n }\n return content\n\n\n\n# 这个应该没啥用\ndef add_article(request):\n articles = []\n for x in range(0, 102):\n article = Article(title='标题:%s' % x, content='内容:%s' % x)\n articles.append(article)\n # article = Article(title='标题:', content='内容:')\n # article.save()\n # articles.append(article)\n # print(article)\n # print(articles)\n Article.objects.bulk_create(articles)\n return HttpResponse(\"插入成功\")\n\n\n\n\n# 这个是关键\nclass ArticleListView(ListView):\n model = TableName #数据库表格名称\n template_name = 'article_list.html'\n context_object_name = 'articles'\n #这个是提交给html的变量\n # 也就是说,类视图里面是context_object_name\n # html则是articles.\n # 两者完全对应\n paginate_by = 10\n # ordering = 'create_time'\n\n\n\n def get_pagination_data(self, paginator, page_obj, around_count=2):\n current_page = page_obj.number\n num_page = paginator.num_pages\n\n left_has_more = False\n right_has_more = False\n\n if current_page <= around_count + 2:\n left_page = range(1, current_page)\n else:\n left_has_more = True\n left_page = range(current_page-around_count, current_page)\n if current_page >= num_page-around_count-1:\n right_page = range(current_page+1, num_page+1)\n else:\n right_has_more = True\n right_page = range(current_page+1, current_page+3)\n return {\n 'left_pages': left_page,\n 'right_pages': right_page,\n 'current_page': current_page,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n }\n\n\n def get_context_data(self, **kwargs):\n context = super(ArticleListView, self).get_context_data(**kwargs)\n # print(\"*\"*20)\n # print(context)\n # print(\"*\"*20)\n paginator = context.get('paginator')\n # print(paginator.count)\n # print(paginator.num_pages)\n # print(paginator.page_range)\n page_obj = context.get('page_obj')\n # print(page_obj.has_next())\n # print(page_obj.next_page_number)\n paginator_data = self.get_pagination_data(paginator, page_obj)\n context.update(paginator_data)\n print(\"dir(context)=\",dir(context))\n return context\n\n # def get_queryset(self):\n # return Article.objects.filter(id__lte=9)\n\n","sub_path":"分页功能探索-完成/cnblogs-商品分页代码-完成/fenye/front/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"69065461","text":"import os\nfrom timeit import default_timer as timer\n\nimport ctc\nimport lasagne\nimport theano\nimport theano.tensor as T\n\nfrom support import toy_batch_ctc, default_params, write_results, print_results, plot_results\n\n# Experiment_type\nframework = 'lasagne'\nexperiment = '4x320LSTM_CTC'\n\n# Get data\nbX, b_lenX, maskX, bY, b_lenY, classes = toy_batch_ctc()\nbatch_size, seq_len, inp_dims = bX.shape\nrnn_size, learning_rate, epochs = default_params()\n\n# Create symbolic vars\ninput_var = T.ftensor3('bX')\ninput_var_lens = T.ivector('b_lenX')\nmask_var = T.matrix('maskX')\ntarget_var = T.ivector('bY')\ntarget_var_lens = T.ivector('b_lenY')\n\n\n# Create network\ndef get_bench_net_lstm(input_var, mask_var, inp_dim, rnn_size, classes):\n # Input layer\n l_in = lasagne.layers.InputLayer(shape=(None, None, inp_dim), input_var=input_var)\n\n # Masking layer\n l_mask = lasagne.layers.InputLayer(shape=(None, None), input_var=mask_var)\n\n # Allows arbitrary sizes\n batch_size, seq_len, _ = input_var.shape\n\n # RNN layers\n h1f = lasagne.layers.LSTMLayer(l_in, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform())\n h1b = lasagne.layers.LSTMLayer(l_in, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform(),\n backwards=True)\n h1 = lasagne.layers.ConcatLayer([h1f, h1b], axis=2)\n\n h2f = lasagne.layers.LSTMLayer(h1, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform())\n h2b = lasagne.layers.LSTMLayer(h1, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform(),\n backwards=True)\n h2 = lasagne.layers.ConcatLayer([h2f, h2b], axis=2)\n\n h3f = lasagne.layers.LSTMLayer(h2, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform())\n h3b = lasagne.layers.LSTMLayer(h2, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform(),\n backwards=True)\n h3 = lasagne.layers.ConcatLayer([h3f, h3b], axis=2)\n\n h4f = lasagne.layers.LSTMLayer(h3, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform())\n h4b = lasagne.layers.LSTMLayer(h3, num_units=rnn_size, mask_input=l_mask, hid_init=lasagne.init.GlorotUniform(),\n backwards=True)\n h4 = lasagne.layers.ConcatLayer([h4f, h4b], axis=2)\n\n h5 = non_flattening_dense(h4, batch_size=batch_size, seq_len=seq_len, num_units=classes,\n nonlinearity=lasagne.nonlinearities.linear)\n\n h6 = lasagne.layers.DimshuffleLayer(h5, (1, 0, 2))\n\n return h6\n\n\ndef non_flattening_dense(l_in, batch_size, seq_len, *args, **kwargs):\n # Flatten down the dimensions for everything but the features\n l_flat = lasagne.layers.ReshapeLayer(l_in, (-1, [2]))\n # Make a dense layer connected to it\n l_dense = lasagne.layers.DenseLayer(l_flat, *args, **kwargs)\n # Reshape it back out\n l_nonflat = lasagne.layers.ReshapeLayer(l_dense, (batch_size, seq_len, l_dense.output_shape[1]))\n return l_nonflat\n\n\n# Create network\nnetwork = get_bench_net_lstm(input_var=input_var, mask_var=mask_var, inp_dim=inp_dims, rnn_size=rnn_size,\n classes=classes)\n\n# Create loss, optimizer and train function\nprediction = lasagne.layers.get_output(network)\nloss = T.mean(ctc.cpu_ctc_th(prediction, input_var_lens, target_var, target_var_lens))\n\nparams = lasagne.layers.get_all_params(network, trainable=True)\nupdates = lasagne.updates.adam(loss, params, learning_rate=learning_rate)\n\nfn_inputs = [input_var, input_var_lens, mask_var, target_var, target_var_lens]\ntrain_fn = theano.function(fn_inputs, loss, updates=updates)\noutput_fn = theano.function([input_var, mask_var], prediction)\n\n# Print parameter count\nparams = lasagne.layers.count_params(network)\nprint('# network parameters: ' + str(params))\n\n# Start training\ntime = []\nfor i in range(epochs):\n print('Epoch {}/{}'.format(i, epochs))\n\n start = timer()\n train_loss = train_fn(bX, b_lenX, maskX, bY, b_lenY)\n end = timer()\n time.append(end - start)\n output = output_fn(bX, maskX)\n assert (output.shape == (seq_len, batch_size, classes))\n\nwrite_results(script_name=os.path.basename(__file__), framework=framework, experiment=experiment, parameters=params,\n run_time=time)\nprint_results(time)\n\n# Plot results\nfig, ax = plot_results(time)\nfig.savefig('{}_{}.pdf'.format(framework, experiment), bbox_inches='tight')\n","sub_path":"4x320-LSTM_ctc/bench_lasagne.py","file_name":"bench_lasagne.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"413691939","text":"import psi4\nimport numpy as np\n\n# Initial setup\npsi4.set_memory('2 GB')\npsi4.set_num_threads(2)\n\nfile_prefix = 'methane_HF-DZ'\n\nch4 = psi4.geometry(\"\"\"\nsymmetry c1\n0 1\n C -0.85972 2.41258 0.00000\n H 0.21028 2.41258 0.00000\n H -1.21638 2.69390 -0.96879\n H -1.21639 3.11091 0.72802\n H -1.21639 1.43293 0.24076\n\"\"\")\n\n\n# Geometry optimization\npsi4.set_output_file(file_prefix + '_geomopt.dat', False)\npsi4.set_options({'g_convergence': 'gau_tight'})\npsi4.optimize('scf/cc-pVDZ', molecule=ch4)\n\n\n# Run vibrational frequency analysis\npsi4.set_output_file(file_prefix + '_vibfreq.dat', False)\nscf_energy, scf_wfn = psi4.frequency('scf/cc-pVDZ', molecule=ch4, return_wfn=True, dertype='gradient')\n\n# Save \"raw\" frequencies into a variable\nomegaEntry = scf_wfn.frequency_analysis[\"omega\"].data\nomegaArrayReal = np.real(omegaEntry)\n\n#only keep real entries with a real value of greater than 10\nclipped_omegaArray = omegaArrayReal[omegaArrayReal>10]\n\n#round each entry to an integer\nrounded_omegaArray = np.rint(clipped_omegaArray)\n\n#create an array with only unique frequencies\nunique_omegaArray = np.unique(rounded_omegaArray)\n\n#define an empty two-column array\nfreqValArray = np.empty((0,2), int)\nfor i in range(len(unique_omegaArray)):\n freq = np.count_nonzero(rounded_omegaArray == unique_omegaArray[i])\n freqValArray = np.append(freqValArray, np.array([[freq, unique_omegaArray[i]]]), axis=0)\n\n#Print data into text file called frequency_list.txt\nprint(\"List of Frequencies for %s \\n\\n\" %(file_prefix), file=open(\"frequency_list.txt\", \"w\"))\n\nfor i in range(len(unique_omegaArray)):\n print(\"%s: Degeneracy: %s Frequency: %s\" %(i, freqValArray[i,0],freqValArray[i,1]), file=open(\"frequency_list.txt\", \"a\"))\n","sub_path":"Methane-VibFreqAnalysis.py","file_name":"Methane-VibFreqAnalysis.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"222512639","text":"n = int(input())\narr = [[] for _ in range(n)]\n\nblue = 0\nwhite = 0\n\nfor i in range(n):\n arr[i] = list(map(int, input().split()))\n\ndef is_one_zero(arr):\n x = len(arr)\n s = 0\n\n for i in range(x):\n s+= sum(arr[i])\n\n if(s == x*x):\n return 1\n\n if(s == 0):\n return 0\n\n else:\n return -1\n\ndef _2630(arr):\n global blue\n global white\n\n s = is_one_zero(arr)\n\n if(s == 1):\n blue +=1\n return\n if(s == 0):\n white += 1\n return\n\n n = len(arr)\n m = len(arr) // 2\n\n temp = []\n for i in range(0,m):\n temp.append(arr[i][:m])\n\n _2630(temp)\n\n temp = []\n for i in range(0,m):\n temp.append(arr[i][m:])\n\n _2630(temp)\n\n temp = []\n for i in range(m,n):\n temp.append(arr[i][:m])\n\n _2630(temp)\n\n temp = []\n for i in range(m,n):\n temp.append(arr[i][m:])\n\n _2630(temp)\n\n return\n\n_2630(arr)\nprint(white, blue)","sub_path":"by category/divide&conquer/2630.py","file_name":"2630.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"67852109","text":"import os\nimport sys\nimport operator\n\nfrom reader.reader import *\nfrom tools.normalization import *\n\ndef get_topics_list(path):\n with open(path, 'r') as fr:\n lines = fr.readlines()\n fr.close()\n\n topics = [line.rstrip() for line in lines]\n return topics\n\ndef align_topics_docid_mlscore(learner, test_data, test_pred):\n topics_docid_score = {}\n with open(test_data, 'r') as fr:\n test_data_lines = fr.readlines()\n fr.close()\n\n with open(test_pred, 'r') as fr:\n test_pred_lines = fr.readlines()\n fr.close()\n\n for itr in range(len(test_data_lines)):\n line = test_data_lines[itr]\n parts = line.rstrip().split(\"#\")\n\n part = parts[0]\n sub_part = part.split(\" \")\n q_qid = sub_part[1]\n\n qid = q_qid.split(\":\")[1]\n docid = parts[1].strip()\n pred_line = test_pred_lines[itr].rstrip()\n\n if learner == \"svm\":\n pred = pred_line\n else:\n pred = pred_line.split(\"\\t\")[2]\n\n docid_score = topics_docid_score.get(qid)\n if docid_score is None:\n docid_score = {}\n docid_score[docid] = float(pred)\n topics_docid_score[qid] = docid_score\n\n return topics_docid_score\n\ndef prepare_ml_ranked(cmt_path, learner, nfolds, input_folder, output_folder, run_folder):\n\n run_path = os.path.join(run_folder, cmt_path+'_'+learner+'_reranked.res')\n with open(run_path, 'w') as fw:\n for f in range(1, (nfolds+1)):\n topics_fold_path = os.path.join(input_folder, 'f'+str(f))\n topics_id = get_topics_list(topics_fold_path)\n test_data = os.path.join(output_folder, 'test/'+cmt_path+'_query.ltr.test.f'+str(f)+'te')\n test_pred = os.path.join(output_folder, 'test/'+cmt_path+'_query.ltr.test.f'+str(f)+'te.'+learner+'.pred')\n\n #aligning prediction score of test data\n topics_docid_score = align_topics_docid_mlscore(learner, test_data, test_pred)\n\n #writing the run file\n for topic_id in topics_id:\n docid_score = topics_docid_score.get(topic_id)\n #sorted_docid_score = sorted(docid_score, key=sortSecond, reverse=True)\n #rank = 1\n #for docid, score in sorted_docid_score:\n # line = str(topic_id)+' '+'Q0'+' '+str(docid)+' '+str(rank)+' '+str(score)+' svm-rank\\n'\n # rank = rank + 1\n # fw.write(line)\n #\n if docid_score is None:\n print (topic_id)\n continue\n sorted_docids = sorted(docid_score, key=docid_score.get, reverse=True)\n rank = 1\n for docid in sorted_docids:\n score = docid_score.get(docid)\n line = str(topic_id)+' '+'Q0'+' '+str(docid)+' '+str(rank)+' '+str(score)+' '+learner+'\\n'\n rank = rank + 1\n fw.write(line)\n fw.close()\n\ndef sortSecond(val):\n return val[1]\n\ndef main():\n coll = sys.argv[1]\n model = sys.argv[2]\n topics = sys.argv[3]\n learner = sys.argv[4]\n #nfolds = int(sys.argv[5])\n nfolds = 5\n #input_folder = sys.argv[6]\n input_folder = \"input/data\"\n #output_folder = sys.argv[7]\n output_folder = \"output/l2r-dataset\"\n #run_folder = sys.argv[8]\n run_folder = \"output/runs\"\n\n cmt_path = coll + '_' + model + '_' + topics\n prepare_ml_ranked(cmt_path, learner, nfolds, input_folder, output_folder, run_folder)\n\nif __name__ == '__main__':\n main()\n","sub_path":"prepare_ml_ranking.py","file_name":"prepare_ml_ranking.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"579367276","text":"\"\"\"\nviews for table 12a xls export\n\"\"\"\nfrom datetime import datetime\nimport xlwt\n\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom gsd.admissions_info.models import AdmissionsInfo\nfrom gsd.report_table_field.models import ReportTable\nfrom gsd.student.models import GraduateStudent, GraduateStudentStatusEnrolledID, GraduateStudentStatusGraduatedID, GraduateStudentStatusWithdrewID\nfrom gsd.dissertation.models import ThesisDefense\nfrom gsd.nih_report_specs.models import NIHReportingParameters\nfrom gsd.utils import xls_styles\nfrom gsd.utils.view_util import get_not_logged_in_page\n\n\ndef view_table_12a_xls(request):\n \"\"\"view table 12a xls\"\"\"\n if not (request.user.is_authenticated and request.user.is_staff):\n return HttpResponseRedirect(get_not_logged_in_page())\n\n NIH_PARAMS = NIHReportingParameters.get_params()\n\n grad_students = GraduateStudent.objects.filter(\n appointed_to_training_grant=True,\n program__id__in=NIH_PARAMS.get_program_ids(),\n home_department__id__in=NIH_PARAMS.get_home_department_ids()\n ).exclude(\n degree_award_date__lt=NIH_PARAMS.graduation_cutoff_date\n ).exclude(\n start_year__lt=NIH_PARAMS.min_start_year_cutoff\n ).exclude(\n start_year__gt=NIH_PARAMS.max_start_year_cutoff\n ).order_by('start_year', 'last_name', 'first_name')\n\n nih_table = ReportTable.objects.get(table_number__icontains='Table 12A')\n\n title = '%s - %s' % (nih_table.table_number, nih_table.name)\n\n book = xlwt.Workbook(encoding=\"utf-8\")\n # With a workbook object made we can now add some sheets.\n sheet1 = book.add_sheet('Table %s' % nih_table.table_number)\n sheet1.portrait = False\n\n date_obj = datetime.now()\n info_line = \"Generated on %s\" % (date_obj.strftime('%m/%d/%Y - %I:%M %p'))\n sheet1 = make_table12a_spreadsheet(sheet1, info_line, grad_students, title)\n fname = 'table12a_predoc_qualifications_%s.xls' % (date_obj.strftime('%m%d-%I-%M%p-%S').lower())\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=%s' % (fname)\n\n # send .xls spreadsheet to response stream\n book.save(response)\n return response\n\n\ndef make_table12a_spreadsheet(sheet1, info_line, grad_students, sheet_title):\n \"\"\"make table12a sheet\"\"\"\n if sheet1 is None:\n return None\n\n if grad_students is None:\n return sheet1\n\n excel_row_num = 0\n\n sheet1.write_merge(excel_row_num, excel_row_num, 0, 8, sheet_title, xls_styles.style_title_cell)\n excel_row_num += 1\n\n column_attributes = [\\\n ('Trainee, Year of Entry, Prior Degree & Institution (Mentor - Department / Program)', 'trainee', 25)\\\n ]\n\n cnt = 0\n for idx, gyear in enumerate(range(3, 13)):\n cnt += 1\n yr_range = '%s-%s' % ('gyear'.zfill(2), 'gyear + 1'.zfill(2))\n col_title = 'Grant Year -%s\\n%s' % ('cnt'.zfill(2), yr_range)\n column_attributes.append((col_title, 'blank', 8))\n\n column_attributes += [\n ('Title of Research Project or Research Topic', 'research_project', 15),\n ('Degree(s) Received (Year)', 'degree_year', 10),\n ('Current Position and Institution (Grant Support Obtained)', 'current_position', 15),\n ('Click for Grad DB', 'grad_db', 12)\n ]\n\n #----------------------------\n # Add the header row and set column widths\n #----------------------------\n char_multiplier = 256\n excel_row_num += 1\n for col_idx, (col_name, attr_name, col_width) in enumerate(column_attributes):\n if attr_name == 'grad_db':\n sheet1.write(excel_row_num, col_idx, col_name, xls_styles.style_info_cell_light_blue)\n else:\n sheet1.write(excel_row_num, col_idx, col_name, xls_styles.style_header_gray)\n\n sheet1.col(col_idx).width = col_width * char_multiplier\n\n\n # Iterate through each student\n #----------------------------------\n current_start_year = None\n for rec in grad_students:\n excel_row_num += 1\n if not rec.start_year == current_start_year:\n sheet1.write_merge(excel_row_num, excel_row_num, 0, 14, 'Entered %s' % rec.start_year, xls_styles.style_header_gray)\n\n #sheet1.write(excel_row_num, col_idx, 'Entered %s' % rec.start_year, style_info_cell_wrap_on_center)\n current_start_year = rec.start_year\n excel_row_num += 1\n\n #print '\\n(%s) trainee: %s, %s' % (excel_row_num, rec)\n for col_idx, (col_name, attr, col_width) in enumerate(column_attributes):\n if attr == 'skip_it':\n continue\n elif attr == 'blank':\n sheet1.write(excel_row_num, col_idx, '', xls_styles.style_info_cell_wrap_on_center)\n elif attr == 'grad_db':\n hlink = 'HYPERLINK(\"https://adminapps.mcb.harvard.edu/mcb-grad/mco-control-panel/student/graduatestudent/%s/\", \"grad db\" )' % rec.id\n sheet1.write(excel_row_num, col_idx, xlwt.Formula(hlink), xls_styles.style_info_cell_light_blue)\n\n\n elif attr == 'trainee':\n tinfo = '%s, %s, %s' % (rec.last_name, rec.first_name, rec.start_year)\n try:\n admit_rec = rec.admissionsinfo\n prior_degree_info = admit_rec.get_prior_degree_at_entry()\n if prior_degree_info:\n tinfo = '%s %s,\\n%s' % (tinfo\\\n , prior_degree_info.degree_type\\\n , prior_degree_info.school.name.title())\n except AdmissionsInfo.DoesNotExist:\n pass\n\n advisor = rec.get_current_advisor()\n if advisor is not None:\n if advisor.faculty_member.department.abbreviation == 'MCB':\n tinfo = '%s\\n(%s-MCB)' % (tinfo\\\n , advisor.faculty_member.last_name)\n\n else:\n tinfo = '%s\\n(%s-%s)' % (tinfo\\\n , advisor.faculty_member.last_name\\\n , advisor.faculty_member.department.name)\n\n sheet1.write(excel_row_num, col_idx, tinfo, xls_styles.style_info_cell_wrap_on)\n\n elif attr == 'research_project':\n if ThesisDefense.objects.filter(student=rec).count() > 0:\n thesis_defense = ThesisDefense.objects.filter(student=rec)[0]\n sheet1.write(excel_row_num, col_idx, thesis_defense.title, xls_styles.style_info_cell_wrap_on)\n\n elif rec.research_interest:\n sheet1.write(excel_row_num, col_idx, rec.research_interest, xls_styles.style_info_cell_wrap_on)\n\n else:\n sheet1.write(excel_row_num, col_idx, '', xls_styles.style_info_cell_wrap_on)\n\n\n elif attr == 'degree_year':\n if rec.status.id == GraduateStudentStatusGraduatedID and rec.degree_award_date:\n val = 'PhD\\n(%s)' % rec.degree_award_date.year\n sheet1.write(excel_row_num, col_idx, val, xls_styles.style_info_cell_wrap_on_center)\n else:\n sheet1.write(excel_row_num, col_idx, '', xls_styles.style_info_cell_wrap_on_center)\n\n elif attr == 'current_position':\n if rec.status.id == GraduateStudentStatusEnrolledID:\n sheet1.write(excel_row_num, col_idx, 'In Training', xls_styles.style_info_cell_wrap_on)\n\n elif rec.status.id == GraduateStudentStatusWithdrewID:\n sheet1.write(excel_row_num, col_idx, 'Withdrew', xls_styles.style_info_cell_wrap_on)\n\n elif rec.status.id == GraduateStudentStatusGraduatedID:\n\n current_position = rec.get_current_position()\n if current_position:\n alum_position = '%s, %s, %s' % (current_position.title\\\n , current_position.organization\\\n , current_position.location)\n sheet1.write(excel_row_num, col_idx, alum_position, xls_styles.style_info_cell_wrap_on)\n else:\n sheet1.write(excel_row_num, col_idx, '(n/a)', xls_styles.style_info_cell_wrap_on)\n else:\n sheet1.write(excel_row_num, col_idx, '(n/a)', xls_styles.style_info_cell_wrap_on)\n\n else:\n pass\n\n return sheet1\n","sub_path":"gsd/nih_reports/views_table_12a_xls.py","file_name":"views_table_12a_xls.py","file_ext":"py","file_size_in_byte":8499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"139537166","text":"'''\nCreated on Nov 8, 2011\n\n@author: maja\n'''\nimport pango\nimport gtk \n\nclass PrintMenu(object): \n \n def _print_sentence(self, data, context, total_lines, page_height, page_breaks, key, font, alignment, justify, text):\n '''\n @param data PrintScrapData: scrap's data to be printed\n @param context PangoContext: print environment\n @param total_lines integer: how many lines are already been printed inside the page\n @param page_height float: cumulative height for the total lines\n @param page_breaks: how many pages are already been printed (with the number of lines inside the page)\n @param key: sentence's identifier\n @param font: sentence's font\n @param alignment: sentence's alignment\n @param justify: sentence's justify\n @param text: sentence's text\n \n @return (num_lines, page_height, page_breaks): (sentence's number of lines, \n page height with this sentence printed, \n how many page breaks are been reached)\n '''\n width = context.get_width()\n height = context.get_height() \n \n data.layout[key] = context.create_pango_layout()\n data.layout[key].set_font_description(pango.FontDescription(font))\n data.layout[key].set_width(int(width*pango.SCALE)) \n data.layout[key].set_alignment(alignment)\n data.layout[key].set_justify(justify) \n data.layout[key].set_text(text)\n\n num_lines = data.layout[key].get_line_count()\n \n for line in xrange(num_lines):\n if line < num_lines: \n layout_line = data.layout[key].get_line(line)\n _ink_rect, logical_rect = layout_line.get_extents()\n _lx, _ly, _lwidth, lheight = logical_rect\n line_height = lheight / 1024.0\n if page_height + line_height > height:\n page_breaks.append(line+total_lines)\n page_height = 0\n page_height += line_height\n \n data.layout[key].line_height = lheight\n total_lines = total_lines + num_lines \n \n return (total_lines, page_height, page_breaks) \n \n def begin_print(self, operation, context, print_data):\n\n \n page_height = 0\n page_breaks = []\n total_lines = 0\n for collection_name, collection_data in print_data.collections_data.iteritems(): \n \n (total_lines, page_height, page_breaks) = self._print_sentence(collection_data, \n context, \n total_lines, \n page_height, \n page_breaks, \n \"collection\", \n \"Serif 21\", \n pango.ALIGN_LEFT, \n False, \n collection_name) \n \n for (scrap, data) in collection_data.iterPrintScrapData():\n for (key, text, font, alignment, justify) in (\n (\"scrap\", scrap.text, data.appearance.font, pango.ALIGN_LEFT, True),\n (\"details\", scrap.book.author.name + \", \" + scrap.book.title, \"Serif 6\", pango.ALIGN_RIGHT, False)\n ):\n \n (total_lines, page_height, page_breaks) = self._print_sentence(data, \n context, \n total_lines, \n page_height, \n page_breaks, \n key, \n font, \n alignment, \n justify, \n text)\n operation.set_n_pages(len(page_breaks) + 1)\n print_data.page_breaks = page_breaks \n \n def draw_page(self, operation, context, page_nr, print_data): \n i = 0\n start_pos = 0 \n scrap_end_pos = 0\n for _collection_name, collection_data in print_data.collections_data.iteritems(): \n for data in collection_data.iterPrintSentenceData():\n for layout in data.layout.itervalues():\n assert isinstance(print_data.page_breaks, list)\n if page_nr == 0:\n start = 0\n else:\n start = print_data.page_breaks[page_nr - 1]\n \n try:\n end = print_data.page_breaks[page_nr]\n except IndexError:\n end = start + layout.get_line_count() + i\n \n cr = context.get_cairo_context()\n \n cr.set_source_rgb(0, 0, 0) \n \n iter = layout.get_iter()\n while 1:\n if i >= start and i < end:\n line = iter.get_line()\n _, logical_rect = iter.get_line_extents()\n lx, ly, _lwidth, _lheight = logical_rect\n baseline = iter.get_baseline() + scrap_end_pos\n if i == start:\n start_pos = ly / 1024.0;\n cr.move_to(lx / 1024.0, baseline / 1024.0 - start_pos)\n cr.show_layout_line(line)\n i += 1\n if not (i < end and iter.next_line()):\n if i > start:\n scrap_end_pos = baseline + layout.line_height\n break\n i = i + 1 # added a blank line\n \n class PrintSentenceData(object):\n \n def __init__(self, appearance):\n self.appearance = appearance\n self.layout = {}\n self.scrap_start_position = None\n self.line_height = None\n \n class PrintCollectionData(PrintSentenceData):\n \n def __init__(self):\n super(PrintMenu.PrintCollectionData, self).__init__(None)\n self.data = {}\n self.page_breaks = None\n \n def add(self, scrap, appearance):\n self.data[scrap] = PrintMenu.PrintSentenceData(appearance)\n \n def iterPrintSentenceData(self):\n yield self\n for (_scrap, data) in self.data.iteritems():\n yield data\n \n def iterPrintScrapData(self):\n for (scrap, data) in self.data.iteritems():\n yield (scrap, data) \n \n class PrintData(object):\n \n def __init__(self):\n self.collections_data = {}\n \n def add(self, collection_name):\n self.collections_data[collection_name] = PrintMenu.PrintCollectionData()\n return self.collections_data[collection_name]\n \n def on_print_button_clicked(self, widget):\n operation = gtk.PrintOperation()\n print_data = self.PrintData()\n for (path, category_name) in self.iterSelectedCategories():\n collection_data = print_data.add(category_name)\n (_manager, scraps_iterator) = self.getScrapsIteratorFromCategory(path, category_name)\n for scrap in scraps_iterator.scraps:\n appearance = scraps_iterator.getScrapAppearance(scrap)\n collection_data.add(scrap, appearance)\n \n operation.connect(\"begin_print\", self.begin_print, print_data)\n operation.connect(\"draw_page\", self.draw_page, print_data)\n \n response = operation.run(gtk.PRINT_OPERATION_ACTION_PRINT_DIALOG, self.window)\n if response == gtk.PRINT_OPERATION_RESULT_ERROR:\n error_dialog = gtk.MessageDialog(self.window,\n gtk.DIALOG_DESTROY_WITH_PARENT,\n gtk.MESSAGE_ERROR,\n gtk.BUTTONS_CLOSE,\n \"Error printing file:\\n\")\n error_dialog.connect(\"response\", lambda w, _id: w.destroy())\n error_dialog.show()","sub_path":"src/commonplace_book_gtk/print_menu.py","file_name":"print_menu.py","file_ext":"py","file_size_in_byte":9374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"521510994","text":"#import tensorflow\nfrom EnvironmentSetup import Environment\nfrom Qlearning import QLearningAgent\nimport hexafunc as simulator\nimport LoadAndUnLoadObservation as lu\n\n# current_state,next_state,reward,epsilon,decay_rate,Q_value:state\n\ndef train(env, agent):\n for i in range(5000):\n s = env.reset_environment()\n com_rewa = 0\n file = open(\"epsilon.txt\", 'r')\n epsilon = file.readline()\n epsilon = float(epsilon)\n agent.epsilon = epsilon\n\n for t in range(90):\n \n info = ''\n q_states = ''\n prev = s # previous state\n a = agent.get_action(s) # leg1_up\n print(a)\n r, next_s, _ = env.step(a)\n agent.update(s, a, r, next_s)\n s = next_s\n com_rewa += r\n\n Q_table = agent.get_qvalues_table()\n for key, values in Q_table[prev].items():\n q_states += key + '[' + str(values)+']'+','\n info += s+','+next_s+','+str(r)+','+str(agent.epsilon)+','+str(agent.discount)+','+str(com_rewa)+',' + q_states\n \n with open(\"log.txt\",'a') as log:\n log.write(info+'\\n')\n\n print(\"After \",i,\" iteration reward is:: \", com_rewa)\n lu.save_experiance(agent)\n lu.load_reward(i, com_rewa)\n env.reset_environment()\n\n\nif __name__ == '__main__':\n simulator.startConnection('127.0.0.1',19997)\n env = Environment(\"Q-learning\")\n agent = QLearningAgent(0.5, 0.9, 0.5)\n print(\"Loading the Agent experiances\")\n lu.load_experiance(agent)\n train(env, agent)\n\n\n\n\n\n\n\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"8460693","text":"#python2\r\nimport httplib, urllib\r\nfrom server.Admin_setting import *\r\nfrom server.http_api import http_api_admin\r\nfrom server.http_api import http_api\r\n#httpClient = none\r\nclass SERVER_command():\r\n\t@staticmethod\r\n\tdef get_information(checkcode,code,debugmode):\r\n\t\tparams = urllib.urlencode(admin_user)\t\r\n\r\n\t\tif checkcode ==1:\r\n\t\t\tprint(\"Check simulation is on\")\r\n\t\telse:\r\n\t\t\ttry:\r\n\t\t\t\thttpClient = httplib.HTTPConnection(httpconn, httpport)\r\n\t\t\t\thttpClient.request(\"POST\", http_api_admin.login, params, headers)\r\n\t\t\t\tresponse = httpClient.getresponse()\r\n\r\n\t\t\t\tprint(\"%s and %s\"%(response.reason,response.status))\t\t\t\t\r\n\t\t\t\thttpClient.request(\"POST\", http_api_admin.logout, \"\", headers)\r\n\t\t\t\tresponse2 = httpClient.getresponse()\r\n\t\t\t\tprint(response2.status)\r\n\t\t\t\thttpClient.close()\r\n\t\t\t\treturn response2.reason,response2.status\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint(\"Connection error : %s\"%e)\r\n\t\t\t\t# return response2.reason,e\r\n\r\n\t@staticmethod\r\n\tdef update(time,code,debugmode):\r\n\t\t# here will write the information and update to server\r\n\t\tparams = urllib.urlencode(admin_user)\r\n\r\n\t\tif code == 1:\r\n\t\t\ttry:\r\n\t\t\t\t# here will write simulation code to check scan data\r\n\t\t\t\tprint (\"simulation is on\")\r\n\t\t\t\tif debugmode == 1:\r\n\t\t\t\t\tprint(\"scan time : %s\"%time)\r\n\t\t\t\t\tprint(headers)\r\n\t\t\t\t\tprint(\"http connecting : %s:%s\"%(httpconn,httpport))\r\n\t\t\t\t\tprint(\"POST side : %s\"%http_api_admin.login)\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint(\"Wrong type error : %s\"%e)\r\n\t\telse:\r\n\t\t\tprint(\"simulation is off\")\r\n\t\t\ttry:\r\n\t\t\t\t# here will write real scan data\r\n\t\t\t\thttpClient = httplib.HTTPConnection(httpconn, httpport)\r\n\t\t\t\thttpClient.request(\"POST\", http_api_admin.login, params, headers)\r\n\t\t\t\tresponse = httpClient.getresponse()\r\n\t\t\t\tprint(response.status)\r\n\t\t\t\thttpClient.close()\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint(\"Wrong connection : %s\"%e)","sub_path":"python2/old update/170119/server/server_command.py","file_name":"server_command.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"264437153","text":"import logging\nimport re\nimport sys\nfrom types import TracebackType\nfrom typing import Optional, Sequence, Type, cast\n\n\nclass ExtraConsoleOutputInTestException(Exception):\n pass\n\n\nclass ExtraConsoleOutputFinder:\n def __init__(self) -> None:\n self.latest_test_name = \"\"\n valid_line_patterns = [\n # Example: Running zerver.tests.test_attachments.AttachmentsTests.test_delete_unauthenticated\n \"^Running \",\n # Example: ** Test is TOO slow: analytics.tests.test_counts.TestRealmActiveHumans.test_end_to_end (0.581 s)\n \"^\\\\*\\\\* Test is TOO slow: \",\n \"^----------------------------------------------------------------------\",\n # Example: INFO: URL coverage report is in var/url_coverage.txt\n \"^INFO: URL coverage report is in\",\n # Example: INFO: Try running: ./tools/create-test-api-docs\n \"^INFO: Try running:\",\n # Example: -- Running tests in parallel mode with 4 processes\n \"^-- Running tests in\",\n \"^OK\",\n # Example: Ran 2139 tests in 115.659s\n \"^Ran [0-9]+ tests in\",\n # Destroying test database for alias 'default'...\n \"^Destroying test database for alias \",\n \"^Using existing clone\",\n \"^\\\\*\\\\* Skipping \",\n ]\n self.compiled_line_patterns = []\n for pattern in valid_line_patterns:\n self.compiled_line_patterns.append(re.compile(pattern))\n self.full_extra_output = \"\"\n\n def find_extra_output(self, data: str) -> None:\n lines = data.split(\"\\n\")\n for line in lines:\n if not line:\n continue\n found_extra_output = True\n for compiled_pattern in self.compiled_line_patterns:\n if compiled_pattern.match(line):\n found_extra_output = False\n break\n if found_extra_output:\n self.full_extra_output += f\"{line}\\n\"\n\n\nclass TeeStderrAndFindExtraConsoleOutput:\n def __init__(self, extra_output_finder: ExtraConsoleOutputFinder) -> None:\n self.stderr_stream = sys.stderr\n\n # get shared console handler instance from any logger that have it\n self.console_log_handler = cast(\n logging.StreamHandler, logging.getLogger(\"django.server\").handlers[0]\n )\n\n assert isinstance(self.console_log_handler, logging.StreamHandler)\n assert self.console_log_handler.stream == sys.stderr\n self.extra_output_finder = extra_output_finder\n\n def __enter__(self) -> None:\n sys.stderr = self # type: ignore[assignment] # Doing tee by swapping stderr stream with custom file like class\n self.console_log_handler.stream = self # type: ignore[assignment] # Doing tee by swapping stderr stream with custom file like class\n\n def __exit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_value: Optional[BaseException],\n traceback: Optional[TracebackType],\n ) -> None:\n sys.stderr = self.stderr_stream\n self.console_log_handler.stream = sys.stderr\n\n def write(self, data: str) -> None:\n self.stderr_stream.write(data)\n self.extra_output_finder.find_extra_output(data)\n\n def writelines(self, data: Sequence[str]) -> None:\n self.stderr_stream.writelines(data)\n lines = \"\".join(data)\n self.extra_output_finder.find_extra_output(lines)\n\n def flush(self) -> None:\n self.stderr_stream.flush()\n\n\nclass TeeStdoutAndFindExtraConsoleOutput:\n def __init__(self, extra_output_finder: ExtraConsoleOutputFinder) -> None:\n self.stdout_stream = sys.stdout\n self.extra_output_finder = extra_output_finder\n\n def __enter__(self) -> None:\n sys.stdout = self # type: ignore[assignment] # Doing tee by swapping stderr stream with custom file like class\n\n def __exit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_value: Optional[BaseException],\n traceback: Optional[TracebackType],\n ) -> None:\n sys.stdout = self.stdout_stream\n\n def write(self, data: str) -> None:\n self.stdout_stream.write(data)\n self.extra_output_finder.find_extra_output(data)\n\n def writelines(self, data: Sequence[str]) -> None:\n self.stdout_stream.writelines(data)\n lines = \"\".join(data)\n self.extra_output_finder.find_extra_output(lines)\n\n def flush(self) -> None:\n self.stdout_stream.flush()\n","sub_path":"zerver/lib/test_console_output.py","file_name":"test_console_output.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"107188308","text":"#How many questions component version 3\n#This piece of code gives the User the option of how many questions they want to answer\n#The User can choose how many questions they want to answer with the minimum number of questions the\n#User has to input being 1 and there is\n#no maximum number for how many questions they want to answer\n#If thd User inputs a value less than 1 an Error message will appear\n#If the User inputs a value more than or equal to 50 they will be asked if they wish to answer this many questions\n#If the User answer yes the program will continue\n#If the User answers no they will be advised to input a lower value\n#This component is integrated with the Yes/No Checker\n\n#Yes/No Checker\n#Check If the User's input is valid\ndef yes_no_checker(question):\n valid = False\n while not valid:\n #The User response will be lowercased\n response = input(question).lower()\n\n #If user response is either 'yes' or 'y' the response will be outputed as yes.\n if response == \"yes\" or response == \"y\":\n response = \"yes\"\n return response\n\n #If user response is either 'no' or 'n' the response will be outputed as no.\n elif response == \"no\" or response == \"n\":\n response = \"no\"\n return response\n\n #If user response is anything other than yes or no, User will be asked to answer yes or no.\n else:\n print(\" please answer Yes/No (Y/N). \")\n print()\n\ndef check_how_many_questions(question):\n while True:\n\n #How many questions error\n how_many_questions_error = \"Please input either an integer that is more than 0.\"\n try:\n #Ask the User how many questions they want to answer\n #The User can choose how many questions they want to answer (minimum is 1 and there is no maximum)\n response = int(input(question))\n #If the User's response is too low, less than an error message will be displayed to the User and the question will be asked again\n if response < 1:\n print(how_many_questions_error)\n continue\n\n #If the User's respinse is more then 50, they will be aksed if they are sure they want to answer this many questions (Y/N)\n #This functions includes the yes no checker function\n if response >= 50:\n too_many_questions = yes_no_checker(\"Are you sure you want to answer {} questions (Y/N)? \".format(response))\n\n #If the User answers yes the program will continue\n if too_many_questions == \"yes\":\n print(\"Ok! Sorry for asking\")\n\n #If the User answers no they will be advised to input a lower value\n elif too_many_questions == \"no\":\n print(\"Ok! Try input a lower value\")\n continue\n\n return response\n\n #If the User inputs an unexpected Value an error message will be displayed to the User and the question will be asked again\n except ValueError:\n print(how_many_questions_error)\n continue\n\n#Main routine goes here\n\n#Number of questions the User has answered\nnumber_of_questions_answered = 0\n\n#Ask the User how many questions they want to answer\nuser_choice_of_questions = check_how_many_questions(\"How many Questions would you like to answer (Please input an integer more than 0)? \")\n\n#Question heading\nheading = \"Question {} of {}\".format(number_of_questions_answered + 1, user_choice_of_questions)\n\n#The question heading is outputed to the User\nprint(heading)\n","sub_path":"03_How_many_questions_v3.py","file_name":"03_How_many_questions_v3.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"53467506","text":"from flask import Flask,render_template,session,url_for,request,redirect\nimport random, string\n\n# pip install oauth2client\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nimport httplib2\nimport json\nfrom flask import make_response\nimport requests\n\napp = Flask(__name__)\n\n# required for session to work\napp.config['SECRET_KEY']= ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(24))\n\n# Loading Json structure which contains client id and secret Key\ngoogle_client_json_path = 'templates\\\\google_client_secret.json'\ngoogle_client_json = json.loads(open(google_client_json_path,'r').read())\n\nGOOGLE_CLIENT_ID = google_client_json ['web']['client_id']\n\n\n# FaceBook\nfacebook_client_json_path = 'templates\\\\facebook_client_secret.json'\nfacebook_client_json = json.loads(open(facebook_client_json_path,'r').read())\n\nFACEBOOK_CLIENT_ID = facebook_client_json['web']['app_id']\nFACEBOOK_CLIENT_SECRET = facebook_client_json['web']['app_secret']\n\n@app.route('/')\ndef home():\n try:\n log=0\n if session.get('user_data'):\n log=1\n return render_template(\"googleFacebookLogin.html\",log=log)\n except Exception as e:\n return str(e)\n\n\n@app.route('/index/')\ndef index():\n try:\n # check if user as logged in otherwise redirect to home page\n if session.get('user_data') is None:\n return redirect('/')\n \n # ['given_name'] defined in json provided by google\n return \"HELLO \"+str(session.get('user_data')['given_name'])\n except Exception as e:\n return str(e)\n\n# Route generate a state token for anti-forgery of request\n@app.route('/getToken/',methods=['GET','POST'])\ndef getToken():\n try:\n # genertaing a state token for anti-forgery \n state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))\n session['token'] = state\n return session['token']\n\n except Exception as e:\n return str(e)\n \n@app.route('/googleSignIn/',methods=['POST','GET'])\ndef googleSignIn():\n try:\n # For this to work make sure session is not saved in client side\n # ( Genertaing a state token for anti-forgery )\n # Default flask session is saved on client side\n # use Flask-Session\n if session['token']!=request.args.get('token'):\n return \"Error miss matched token\"\n\n # One time client connect code\n client_code = request.data\n\n # To indicates its for one time flow only set redirect_uri='postmessage'\n flow = flow_from_clientsecrets(google_client_json_path,scope='',redirect_uri='postmessage')\n credentials = flow.step2_exchange(client_code)\n \n # Check access token is valid\n access_token = credentials.access_token\n\n token_url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='+str(access_token))\n \n _http = httplib2.Http()\n \n # the returned as two values in one response header and second response itself\n # so we do _http.request(token_url,'GET')[1] but the data is in bytes form and\n # needs to be converted to string\n result = json.loads(_http.request(token_url,'GET')[1].decode('utf-8'))\n\n # check if the access token is valid i.e not expired\n if result.get('error') is not None:\n return \"error: token expired\"\n \n # Check if the access token provided is for the user we want (not required as such)\n google_user_id =credentials.id_token['sub']\n if result['user_id'] != google_user_id:\n return \"error: invalid user \"\n \n # check if the token was for us by checking the client_id provided to us\n if result['issued_to'] != GOOGLE_CLIENT_ID:\n return \"error: invalid publisher\"\n \n # load user data\n user_url = ('https://www.googleapis.com/oauth2/v1/userinfo?access_token='+str(access_token))\n user_data = json.loads(_http.request(user_url,'GET')[1].decode('utf-8'))\n \n # Check if user already exists\n # If not then ask for Sign Up\n # Assuming user doesnt exist\n already = True #userExists() -> with some dbs logic\n \n\n # User Exists then save their data in session\n if already:\n # saving data in login session\n session['type']='google'\n session['email'] = user_data['email']\n session['acces_token'] = access_token\n session['user_data'] = user_data\n\n return str(already)\n except FlowExchangeError:\n return (\"Erron in generating credentials..\")\n except Exception as e:\n return str(e)\n\n@app.route('/facebookSignIn/',methods=['POST'])\ndef facebookSignIn():\n try:\n # For this to work make sure session is not saved in client side\n # ( Genertaing a state token for anti-forgery )\n # Default flask session is saved on client side\n # use Flask-Session\n if session['token']!=request.args.get('token'):\n return \"Error miss matched token\"\n \n # One time client connect code\n access_token = request.data.decode(\"utf-8\")\n \n # Get user details\n url = 'https://graph.facebook.com/v2.11/me?fields=name,birthday,email,gender,location,picture{url}&access_token=%s'%(access_token)\n _http = httplib2.Http()\n result = json.loads(_http.request(url,'GET')[1].decode('utf-8'))\n \n # Check if user already exists\n # If not then ask for Sign Up\n # Assuming user doesnt exist\n already = True #userExists() -> with some dbs logic\n\n # User Exists then save their data in session\n if already:\n # saving data in login session\n session['type']='facebook'\n session['email'] = result['email']\n session['acces_token'] = access_token\n session['user_data'] = result\n \n return str(already)\n except Exception as e:\n return str(e)\n \n@app.route('/logout/',methods=['GET'])\ndef logout():\n try:\n # check if logged in using facebook, google or normal method \n login_type=session['type']\n session.pop('type', None)\n session.pop('email', None)\n session.pop('acces_token', None)\n session.pop('user_data', None)\n\n return login_type\n except Exception as e:\n return str(e)\n\nif __name__==\"__main__\":\n\tapp.run()\n\n\n","sub_path":"google facebook login/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"298938663","text":"from typing import Any, Dict, List, Union\n\nimport pandas as pd\n\n\ndef labels_from_categorical_csv(\n csv: str,\n index_col: str,\n feature_cols: List,\n return_dict: bool = True,\n index_col_collate_fn: Any = None\n) -> Union[Dict, List]:\n \"\"\"\n Returns a dictionary with {index_col: label} for each entry in the csv.\n\n Expects a csv of this form:\n\n index_col, b, c, d\n some_name, 0 0 1\n some_name_b, 1 0 0\n\n \"\"\"\n df = pd.read_csv(csv)\n # get names\n names = df[index_col].to_list()\n\n # apply colate fn to index_col\n if index_col_collate_fn:\n for i in range(len(names)):\n names[i] = index_col_collate_fn(names[i])\n\n # everything else is binary\n feature_df = df[feature_cols]\n labels = feature_df.to_numpy().argmax(1).tolist()\n\n if return_dict:\n labels = {name: label for name, label in zip(names, labels)}\n\n return labels\n","sub_path":"flash/data/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"448871780","text":"import numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport os\nimport tensorflow as tf\n\ndef load_dataset():\n os.chdir('E:\\\\datasets')\n train_dataset = h5py.File('train_signs.h5', \"r\")\n train_set_x_orig = np.array(train_dataset[\"train_set_x\"][:]) # your train set features\n train_set_y_orig = np.array(train_dataset[\"train_set_y\"][:]) # your train set labels\n\n test_dataset = h5py.File('test_signs.h5', \"r\")\n test_set_x_orig = np.array(test_dataset[\"test_set_x\"][:]) # your test set features\n test_set_y_orig = np.array(test_dataset[\"test_set_y\"][:]) # your test set labels\n\n classes = np.array(test_dataset[\"list_classes\"][:]) # the list of classes\n\n train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))\n test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))\n\n return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes\n\nX_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()\n# Example of a picture\nindex = np.random.randint(0, X_train_orig.shape[0]-1)\nplt.imshow(X_train_orig[index])\n# plt.show()\nprint (\"y = \" + str(np.squeeze(Y_train_orig[:, index])))\n\ndef convert_to_one_hot(Y, C):\n Y = np.eye(C)[Y.reshape(-1)].T\n return Y\nX_train = X_train_orig/255.\nX_test = X_test_orig/255.\nY_train = convert_to_one_hot(Y_train_orig, 6).T\nY_test = convert_to_one_hot(Y_test_orig, 6).T\nprint (\"number of training examples = \" + str(X_train.shape[0]))\nprint (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape)) #(1080, 64, 64, 3)\nprint (\"Y_train shape: \" + str(Y_train.shape))\nprint (\"X_test shape: \" + str(X_test.shape))\nprint (\"Y_test shape: \" + str(Y_test.shape))\n\n#每个批次的大小\nbatch_size = 128\n#计算一共有多少个批次\nn_batch = X_train.shape[0] // batch_size\n# mini-batch的建立\ndef random_mini_batches(X, Y, mini_batch_size=64, seed=0):\n m = X.shape[0] # number of training examples\n mini_batches = []\n np.random.seed(seed)\n\n # Step 1: Shuffle (X, Y)\n permutation = list(np.random.permutation(m))\n shuffled_X = X[permutation, :, :, :]\n shuffled_Y = Y[permutation, :]\n\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_minibatches = int(np.floor(m / mini_batch_size)) # number of mini batches of size mini_batch_size in your partitionning\n for k in range(num_complete_minibatches):\n mini_batch_X = shuffled_X[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :, :, :]\n mini_batch_Y = shuffled_Y[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size: m, :, :, :]\n mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size: m, :]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n return mini_batches\n\ndef create_placeholders(n_H0,n_W0,n_C0,ny):\n X = tf.placeholder(tf.float32,shape=[None,n_H0,n_W0,n_C0])\n Y = tf.placeholder(tf.float32,shape=[None,ny])\n return X,Y\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape,stddev = 0.1)\n return tf.Variable(initial)\ndef bias_variable(shape):\n initial = tf.constant(0.1,shape=shape)\n return tf.Variable(initial)\ndef conv2d(x,W,stride=1):\n return tf.nn.conv2d(x,W,strides=[1,stride,stride,1],padding='SAME')\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\ndef average_pool_6x6(x):\n return tf.nn.avg_pool(x,ksize=[1,6,6,1],strides=[1,6,6,1],padding='SAME')\ndef identity_block(X_input,kernel_size, in_filter, out_filters):\n\n f1, f2, f3 = out_filters\n X_shortcut = X_input\n\n # first\n W_conv1 = weight_variable([1, 1, in_filter, f1])\n X = tf.nn.conv2d(X_input, W_conv1, strides=[1, 1, 1, 1], padding='SAME')\n X = tf.layers.batch_normalization(X, axis=-1)\n X = tf.nn.relu(X )\n\n # second\n W_conv2 = weight_variable([kernel_size, kernel_size, f1, f2])\n X = tf.nn.conv2d(X, W_conv2, strides=[1, 1, 1, 1], padding='SAME')\n X = tf.layers.batch_normalization(X, axis=-1)\n X = tf.nn.relu(X)\n\n # third\n\n W_conv3 = weight_variable([1, 1, f2, f3])\n X = tf.nn.conv2d(X, W_conv3, strides=[1, 1, 1, 1], padding='SAME')\n X = tf.layers.batch_normalization(X, axis=-1)\n\n # final step\n add = tf.add(X, X_shortcut)\n add_result = tf.nn.relu(add)\n\n return add_result\ndef convolutional_block(X_input, kernel_size, in_filter,out_filters,stride=1):\n f1, f2, f3 = out_filters\n\n x_shortcut = X_input\n # first\n W_conv1 = weight_variable([1, 1, in_filter, f1])\n X = tf.nn.conv2d(X_input, W_conv1, strides=[1, stride, stride, 1], padding='SAME')\n X = tf.layers.batch_normalization(X, axis=-1)\n X = tf.nn.relu(X)\n\n # second\n W_conv2 = weight_variable([kernel_size, kernel_size, f1, f2])\n X = tf.nn.conv2d(X, W_conv2, strides=[1, 1, 1, 1], padding='SAME')\n X = tf.layers.batch_normalization(X, axis=-1)\n X = tf.nn.relu(X)\n\n # third\n W_conv3 = weight_variable([1, 1, f2, f3])\n X = tf.nn.conv2d(X, W_conv3, strides=[1, 1, 1, 1], padding='SAME')\n X = tf.layers.batch_normalization(X, axis=-1)\n\n # shortcut path\n W_shortcut = weight_variable([1, 1, in_filter, f3])\n x_shortcut = tf.nn.conv2d(x_shortcut, W_shortcut, strides=[1, stride, stride, 1], padding='SAME')\n\n # final\n add = tf.add(x_shortcut, X)\n add_result = tf.nn.relu(add)\n\n return add_result\n# 占位符\nX, Y = create_placeholders(64,64,3,6) #(1080, 64, 64, 3)\n# 卷积层的变量\nW_conv1 = weight_variable([5,5,3,64])\nb_conv1 = bias_variable([64])\n# 卷积层和池化层\nh_conv1 = tf.nn.relu(conv2d(X,W_conv1,stride=2) + b_conv1) #(1080,64,64,16)\nx = max_pool_2x2(h_conv1)\n# 加入残差层\nx = convolutional_block(x, 3, 64, [64, 64, 256])\nx = identity_block(x, 3, 256, [64, 64, 256])\nx = identity_block(x, 3, 256, [64, 64, 256])\n\nx = convolutional_block(x, 3, 256, [128, 128, 512])\nx = identity_block(x, 3, 512, [128, 128, 512])\nx = identity_block(x, 3, 512, [128, 128, 512])\nx = identity_block(x, 3, 512, [128, 128, 512])\n\nx = convolutional_block(x, 3, 512, [256, 256, 1024])\nx = identity_block(x, 3, 1024, [256, 256, 1024])\nx = identity_block(x, 3, 1024, [256, 256, 1024])\nx = identity_block(x, 3, 1024, [256, 256, 1024])\nx = identity_block(x, 3, 1024, [256, 256, 1024])\nx = identity_block(x, 3, 1024, [256, 256, 1024])\n\n# stage 5\nx = convolutional_block(x, 3, 1024, [512, 512, 2048])\nx = identity_block(x, 3, 2048, [512, 512, 2048])\nx = identity_block(x, 3, 2048, [512, 512, 2048])\n\n# 平均池化层\nx = tf.nn.avg_pool(x, [1, 2, 2, 1], strides=[1, 1, 1, 1], padding='VALID')\n# 将卷积层的输出拉成一列向量\nh_flatten = tf.contrib.layers.flatten(x)\n# 利用keep_prob来存放dropout中神经元的存留概率\nkeep_prob = tf.placeholder(tf.float32)\n# 第一层全连接层\nh_fc1 = tf.contrib.layers.fully_connected(h_flatten, 500, activation_fn=tf.nn.relu)\nh_fc1_dropout = tf.nn.dropout(h_fc1,keep_prob) # dropout\n# 第二层全连接层\nh_fc2 = tf.contrib.layers.fully_connected(h_fc1_dropout, 100, activation_fn=tf.nn.relu)\nh_fc2_dropout = tf.nn.dropout(h_fc2,keep_prob) # dropout\n# 第三层全连接层\nh_fc3 = tf.contrib.layers.fully_connected(h_fc2_dropout, 6, activation_fn = tf.nn.softmax)\n# 交叉熵代价函数\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=h_fc3,labels=Y))\n# 利用Adam进行优化\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n# 结果存放在一个Bool型的列表中\ncorrect_prediction = tf.equal(tf.argmax(h_fc3,1),tf.argmax(Y,1)) #返回张量中最大值所在的位置\naccurracy = tf.reduce_mean(tf.cast(correct_prediction,'float'))\n# 保存模型\nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n loss = []\n accurracy_list = []\n for epoch in range(50):\n minibatches = random_mini_batches(X_train, Y_train, batch_size)\n for minibatch in minibatches:\n minibatch_X, minibatch_Y = minibatch\n sess.run(train_step,feed_dict={X:minibatch_X,Y:minibatch_Y,keep_prob:0.7})\n train_acc = sess.run(accurracy, feed_dict={X: X_train, Y: Y_train,keep_prob:1})\n test_acc = sess.run(accurracy, feed_dict={X: X_test, Y: Y_test,keep_prob:1})\n accurracy_list.append(sess.run(accurracy, feed_dict={X: X_test, Y: Y_test,keep_prob:1}))\n loss.append(sess.run(cross_entropy,feed_dict={X: X_train, Y: Y_train,keep_prob:1}))\n print('Iteration'+ str(epoch) +', Train accuracy: %.2f%%' %(train_acc*100) +', Testing accuracy: %.2f%%' %(test_acc*100))\n # saver.save(sess,'E:\\\\model/')\nax1 = plt.subplot(211)\nax1.plot(loss,'r--')\nplt.ylabel('Loss')\nplt.title('Change of Training Loss')\nax2 = plt.subplot(212)\nax2.plot(accurracy_list,'b')\nplt.xlabel('Iteration number')\nplt.ylabel('Accurracy')\nplt.title('Change of Training Accuracy')\nplt.show()\n\n","sub_path":"ResNet/resnet_tensorflow.py","file_name":"resnet_tensorflow.py","file_ext":"py","file_size_in_byte":9170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"537032753","text":"__author__ = 'jiacheng'\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*\nfrom urllib import request\nimport urllib\nimport re\nfrom apic import apics\nfrom download import down\n\n\ndef picss(pid):\n try:\n req = request.Request('http://www.pixiv.net/member_illust.php?mode=medium&illust_id=%s' % pid)\n reqs = request.Request('http://www.pixiv.net/member_illust.php?mode=manga&illust_id=%s' % pid)\n ss = request.urlopen(reqs).read().decode()\n s = request.urlopen(req).read().decode()\n re_p = r'(\\d{4}/\\d{2}/\\d{2}/\\d{2}/\\d{2}/\\d{2}/)'\n if re.search(re_p, s):\n m = re.search(re_p, s)\n time = m.group()\n else:\n print(\"failed\")\n for k in range(0, 5):\n for i in range(1, 5):\n url_p = \"http://i%d.pixiv.net/img-original/img/%s%s_p%s.png\" % (i, m.group(), pid, k)\n if not down(url_p):\n url_p = \"http://i%d.pixiv.net/img-original/img/%s%s_p%s.jpg\" % (i, m.group(), pid, k)\n down(url_p)\n else:\n break\n except urllib.error.HTTPError as e:\n apics(pid)\n finally:\n pass\n\n\n\nif __name__ == '__main__':\n picss(\"52113838\")","sub_path":"P站/pics.py","file_name":"pics.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"532517231","text":"import numpy as np\nimport cv2\n\nclass Box:\n\n def __init__(self):\n x = 640/2\n y = 480-22\n\n w = 300\n h = 20\n\n self.lowerLeftCorner = np.array([x - w/2, y + h/2])\n self.upperRightCorner = np.array([x + w/2, y - h/2])\n\n def ClipLine(self,dimension,v0,v1,f_low,f_high):\n\n f_dim_low =0\n f_dim_high =0\n\n f_dim_low = (self.lowerLeftCorner[dimension] - v0[dimension]) / (v1[dimension] - v0[dimension])\n f_dim_high = (self.upperRightCorner[dimension] - v0[dimension]) / (v1[dimension] - v0[dimension])\n\n if f_dim_high f_high:\n return False,0,0\n\n f_low = max(f_dim_low,f_low)\n f_high = min (f_dim_high,f_high)\n\n if f_low > f_high:\n return False,0,0\n\n return True,f_low,f_high\n\n def LineBoxIntersection(self,v0,v1):\n f_low = 0\n f_high = 1\n\n valueReturned,f_low,f_high= self.ClipLine (0,v0,v1,f_low,f_high)\n if valueReturned ==False:\n return None\n valueReturned, f_low, f_high = self.ClipLine(1, v0, v1, f_low, f_high)\n if valueReturned == False:\n return None\n b = v1-v0\n intersection = v0 + f_low * b\n\n return intersection\n\n\n def intersection(self,img,v0,v1):\n\n intersect = self.LineBoxIntersection(v0,v1)\n if intersect!=None:\n img = cv2.circle(img,(int(intersect[0]),int(intersect[1])),3,(0,0,0),10)\n\n return img","sub_path":"Autonomous-RCVehiclePython/AutonomousRpi/kalmanFilter/box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"607002368","text":"import pkg_resources\nimport functools\n\nimport transaction\nfrom kinto.core.events import ACTIONS, ResourceChanged\nfrom pyramid.exceptions import ConfigurationError\nfrom pyramid.events import NewRequest\nfrom pyramid.settings import asbool\n\nfrom kinto_signer.signer import heartbeat\nfrom kinto_signer import utils\nfrom kinto_signer import listeners\n\n#: Module version, as defined in PEP-0396.\n__version__ = pkg_resources.get_distribution(__package__).version\n\n\ndef _signer_dotted_location(settings, resource):\n \"\"\"\n Returns the Python dotted location for the specified `resource`, along\n the associated settings prefix.\n\n If a ``signer_backend`` setting is defined for a particular bucket\n or a particular collection, then use the same prefix for every other\n settings names.\n\n .. note::\n\n This means that every signer settings must be duplicated for each\n dedicated signer.\n \"\"\"\n backend_setting = 'signer_backend'\n prefix = 'signer.'\n bucket_wide = '{bucket}.'.format(**resource['source'])\n collection_wide = '{bucket}_{collection}.'.format(**resource['source'])\n if (prefix + collection_wide + backend_setting) in settings:\n prefix += collection_wide\n elif (prefix + bucket_wide + backend_setting) in settings:\n prefix += bucket_wide\n\n # Fallback to the local ECDSA signer.\n default_signer_module = \"kinto_signer.signer.local_ecdsa\"\n signer_dotted_location = settings.get(prefix + backend_setting,\n default_signer_module)\n return signer_dotted_location, prefix\n\n\ndef includeme(config):\n # Register heartbeat to check signer integration.\n config.registry.heartbeats['signer'] = heartbeat\n\n settings = config.get_settings()\n\n # Check source and destination resources are configured.\n raw_resources = settings.get('signer.resources')\n if raw_resources is None:\n error_msg = \"Please specify the kinto.signer.resources setting.\"\n raise ConfigurationError(error_msg)\n resources = utils.parse_resources(raw_resources)\n\n reviewers_group = settings.get(\"signer.reviewers_group\", \"reviewers\")\n editors_group = settings.get(\"signer.editors_group\", \"editors\")\n to_review_enabled = asbool(settings.get(\"signer.to_review_enabled\", False))\n group_check_enabled = asbool(settings.get(\"signer.group_check_enabled\",\n False))\n\n config.registry.signers = {}\n for key, resource in resources.items():\n # Load the signers associated to each resource.\n dotted_location, prefix = _signer_dotted_location(settings, resource)\n signer_module = config.maybe_dotted(dotted_location)\n backend = signer_module.load_from_settings(settings, prefix)\n config.registry.signers[key] = backend\n\n # Load the setttings associated to each resource.\n prefix = \"{source[bucket]}_{source[collection]}\".format(**resource)\n for setting in (\"reviewers_group\", \"editors_group\",\n \"to_review_enabled\", \"group_check_enabled\"):\n value = settings.get(\"signer.%s.%s\" % (prefix, setting),\n settings.get(\"signer.%s_%s\" % (prefix, setting)))\n if value is not None:\n resource[setting] = value\n\n # Expose the capabilities in the root endpoint.\n message = \"Digital signatures for integrity and authenticity of records.\"\n docs = \"https://github.com/Kinto/kinto-signer#kinto-signer\"\n config.add_api_capability(\"signer\", message, docs,\n version=__version__,\n resources=resources.values(),\n to_review_enabled=to_review_enabled,\n group_check_enabled=group_check_enabled,\n editors_group=editors_group,\n reviewers_group=reviewers_group)\n\n config.add_subscriber(\n functools.partial(listeners.set_work_in_progress_status,\n resources=resources),\n ResourceChanged,\n for_resources=('record',))\n\n config.add_subscriber(\n functools.partial(listeners.check_collection_status,\n resources=resources,\n to_review_enabled=to_review_enabled,\n group_check_enabled=group_check_enabled,\n editors_group=editors_group,\n reviewers_group=reviewers_group),\n ResourceChanged,\n for_actions=(ACTIONS.CREATE, ACTIONS.UPDATE),\n for_resources=('collection',))\n\n config.add_subscriber(\n functools.partial(listeners.check_collection_tracking,\n resources=resources),\n ResourceChanged,\n for_actions=(ACTIONS.CREATE, ACTIONS.UPDATE),\n for_resources=('collection',))\n\n sign_data_listener = functools.partial(listeners.sign_collection_data,\n resources=resources)\n\n # If StatsD is enabled, monitor execution time of listener.\n if config.registry.statsd:\n # Due to https://github.com/jsocol/pystatsd/issues/85\n for attr in ('__module__', '__name__'):\n origin = getattr(listeners.sign_collection_data, attr)\n setattr(sign_data_listener, attr, origin)\n\n statsd_client = config.registry.statsd\n key = 'plugins.signer'\n sign_data_listener = statsd_client.timer(key)(sign_data_listener)\n\n config.add_subscriber(\n sign_data_listener,\n ResourceChanged,\n for_actions=(ACTIONS.CREATE, ACTIONS.UPDATE),\n for_resources=('collection',))\n\n def on_new_request(event):\n \"\"\"Send the kinto-signer events in the before commit hook.\n This allows database operations done in subscribers to be automatically\n committed or rolledback.\n \"\"\"\n # Since there is one transaction per batch, ignore subrequests.\n if hasattr(event.request, 'parent'):\n return\n current = transaction.get()\n current.addBeforeCommitHook(listeners.send_signer_events,\n args=(event,))\n\n config.add_subscriber(on_new_request, NewRequest)\n","sub_path":"kinto_signer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"133769671","text":"from flask import Blueprint, jsonify\nfrom src import db\nfrom src.models import City\n\ncity_blueprint = Blueprint('city', __name__)\n\n\n@city_blueprint.route('/', methods=['GET'])\ndef get_cities():\n response = [\n {\n \"_id\": city.id,\n \"name\": city.name\n } for city in db.session.query(City).all()]\n return jsonify(response)\n\n\n@city_blueprint.route('//street/')\ndef get_city_streets(city_id):\n city = db.session.query(City).filter_by(id=city_id).first()\n if not city:\n return jsonify([]), 400\n streets = [\n {\n \"_id\": r.id,\n \"street\": r.name,\n \"city\": city.name\n } for r in city.streets]\n return jsonify(streets)\n","sub_path":"src/city/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"468606558","text":"\"\"\"\nRunning this will show samples of your data set.\n\"\"\"\n\nimport os\nimport sys\nimport random\nimport numpy as np\n\n# Root directory of the project\nROOT_DIR = os.path.abspath(\"../../\")\n\n# Import Mask RCNN\nsys.path.append(ROOT_DIR) # To find local version of the library\nfrom mrcnn import utils\nfrom mrcnn import visualize\nfrom mrcnn.model import log\nfrom samples.ImageDetection import private\n\n\n# Configuration:\nconfig = private.ImageDetectionConfig\nDIR = os.path.join(ROOT_DIR, \"datasets/private_dataset/\")\nprint(DIR)\n\n\n# **************************************************************************** #\n# / // // // // // // // // // // // // // // // // // // // // // // // // /\n# Data set.\n# \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\n# **************************************************************************** #\n\n\n# Load dataset\ndataset = private.ImageDetectionDataset()\ndataset.load_private(DIR, \"val\")\n\n# Must call before using the dataset\ndataset.prepare()\n\nprint(\"Image Count: {}\".format(len(dataset.image_ids)))\nprint(\"Class Count: {}\".format(dataset.num_classes))\nfor i, info in enumerate(dataset.class_info):\n print(\"{:3}. {:50}\".format(i, info['name']))\n\n\n# **************************************************************************** #\n# / // // // // // // // // // // // // // // // // // // // // // // // // /\n# Displaying the samples and bounding boxes\n# \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\\ \\\n# **************************************************************************** #\n\ndef display_dataset(num_of_random_samples):\n # Load and display random samples\n if num_of_random_samples >= len(dataset.image_ids):\n print(\"The number of samples cannot be larger than the amount of samples available\")\n print(\"\\nSetting the amount of equal to the amount of samples\")\n num_of_random_samples = len(dataset.image_ids) - 1\n\n image_ids = np.random.choice(dataset.image_ids, num_of_random_samples)\n\n for image_id in image_ids:\n image = dataset.load_image(image_id)\n mask, class_ids = dataset.load_mask(image_id)\n visualize.display_top_masks(image, mask, class_ids, dataset.class_names)\n\n # Load random image and mask.\n image_id = random.choice(dataset.image_ids)\n image = dataset.load_image(image_id)\n mask, class_ids = dataset.load_mask(image_id)\n # Compute Bounding box\n bbox = utils.extract_bboxes(mask)\n\n # Display image and additional stats\n print(\"image_id \", image_id, dataset.image_reference(image_id))\n log(\"image\", image)\n log(\"mask\", mask)\n log(\"class_ids\", class_ids)\n log(\"bbox\", bbox)\n # Display image and instances\n visualize.display_instances(image, bbox, mask, class_ids, dataset.class_names)\n\n\nif __name__ == '__main__':\n import argparse\n display_dataset(50)\n\n\n parser = argparse.ArgumentParser(\n description='Inspecting Data...')\n parser.add_argument(\"command\",\n metavar=\"\",\n help=\"'inspect'\")\n parser.add_argument('--nsi', required=False,\n metavar=\"N\", type=int,\n help='Number of samples to inspect (int)')\n args = parser.parse_args()\n\n # Configurations\n if args.command == \"inspect\":\n display_dataset(args.nsi)\n\n\n\n","sub_path":"samples/ImageDetection/private_inspect_data.py","file_name":"private_inspect_data.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"284774897","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.integrate import odeint #Integrador de scipy que se usara como solucion exacta\r\n\r\n\r\n#Asignacion de valores de las constantes\r\na=1.\r\nb=1.\r\nc=1.\r\nd=1.\r\n\r\n\r\n#Usando metodo RK4\r\n#Definimos las ecuaciones diferenciales dentro de la misma funcion\r\ndef F(N,t):\r\n n1,n2=N\r\n return np.array([n1*(a-b*n2), -n2*(c-d*n1)])\r\n#Se implementa el RK4 para la solucion de las ecuaciones acopladas\r\ndef RK4(f,u0,t0,tf,n):\r\n t=np.linspace(t0,tf,n+1) #Se establece la particion para la integracion\r\n N=np.array((n+1)*[u0]) #Variable en la cual se guarda la solucion\r\n h=t[1]-t[0] \r\n for i in range(n):\r\n k1=h*f(N[i],t[i]) \r\n k2=h*f(N[i]+0.5*k1,t[i]+0.5*h)\r\n k3=h*f(N[i]+0.5*k2,t[i]+0.5*h)\r\n k4=h*f(N[i]+k3,t[i]+0.5*h)\r\n N[i+1]=N[i]+(k1+2*k2+2*k3+k4)/6 \r\n return N, t\r\n#se aplica el metodo con un valor de n=1000, condiciones iniciales n01=1.5 y n02=1.0\r\nN,t=RK4(F, np.array([1.5, 1]), 0., 12., 1000) #se definen los valores arrojados por el RK4 de las poblaciones y a su vez el arreglo temporal globlal para las graficas\r\nn1k4=N[:,0]\r\nn2k4=N[:,1] #Soluciones que arroja el metodo RK4 para las poblaciones de las particulas\r\n\r\n\r\n#Usando metodo de scipy odeint\r\ndef f(sl, t): #de nuevo se define el sistema de ecuaciones dentro de esta funcion\r\n n1,n2=sl\r\n return n1*(a-b*n2), -n2*(c-d*n1)\r\nsl0=[1.5,1] #condiciones iniciales del problema\r\nsls=odeint(f,sl0,t)#se usa el mismo t definido por el RK4\r\nn1Od=sls[:,0] #soluciones arrojados por odeint, se consideraran estas como exactas\r\nn2Od=sls[:,1]\r\n\r\n\r\n#Usando metodo de euler\r\ndef F(N,t):#definicion dentro de una funcion del sistema de ecuaciones\r\n n1,n2=N\r\n return np.array([n1*(a-b*n2), -n2*(c-d*n1)])\r\n#se define el metodo de euler \r\ndef euler(f,u0,t0,tf,n):\r\n t=np.linspace(t0,tf,n+1)\r\n N=np.array((n+1)*[u0])\r\n h=t[1]-t[0] \r\n for i in range(n):\r\n k1=h*f(N[i],t[i]) \r\n N[i+1]=N[i]+(k1)\r\n return N, t\r\n#se aplica el metodo con un valor de n=1000, condiciones iniciales n01=1.5 y n02=1.0\r\nN,t=euler(F, np.array([1.5, 1]), 0., 12., 1000) #se definen los valores arrojados por el metodo de euler de las poblaciones y a su vez el arreglo del tiempo para las graficas\r\nn1Eu=N[:,0]\r\nn2Eu=N[:,1] #Soluciones que arroja el metodo euler para las poblaciones de las particulas\r\n\r\n####################################################################\r\n####################################################################\r\n\r\n#Grafica de las soluciones\r\n\r\n#Graficando para el metodo de scipy odeint\r\n#Grafica en los planos t,n1 y t,n2\r\nplt.figure(figsize=(10,5))\r\nN1Od=plt.plot(t,n1Od, c=\"red\",label=\"Poblacion 1 \")\r\nN2Od=plt.plot(t,n2Od, c=\"blue\",label=\"Poblacion 2\")\r\nplt.legend(fontsize=10)\r\nplt.xlabel(\"Tiempo\")\r\nplt.ylabel(\"Poblacion de particulas\")\r\nplt.xlim(0,12)\r\nplt.ylim(0,2)\r\nplt.grid(True)\r\nplt.title(\"Poblaciones de las particulas en el tiempo usando Odeint\")\r\nplt.savefig(\"Figura1\")\r\n#plt.show()\r\n\r\n#Grafica en los planos n1,n1\r\nplt.figure(figsize=(10,5))\r\nNHG=plt.plot(n2Od,n1Od, c=\"blue\")\r\nplt.xlim(0,12)\r\nplt.ylim(0,2)\r\nplt.ylabel(\"Poblacion 1\")\r\nplt.xlabel(\"Poblacion 2\")\r\nplt.grid(True)\r\nplt.title(\"Grafica en el plano n1,n2 usando Odeint\")\r\nplt.savefig(\"Figura2\")\r\n#plt.show()\r\n\r\n#Graficando para el metodo RK4\r\n#Grafica en los planos t,n1 y t,n2\r\nplt.figure(figsize=(10,5))\r\nN1k4=plt.plot(t,n1k4, c=\"red\",label=\"Poblacion 1 \")\r\nN2k4=plt.plot(t,n2k4, c=\"blue\",label=\"Poblacion 2\")\r\nplt.legend(fontsize=10)\r\nplt.xlabel(\"Tiempo\")\r\nplt.ylabel(\"Poblacion de particulas\")\r\nplt.xlim(0,12)\r\nplt.ylim(0,2)\r\nplt.grid(True)\r\nplt.title(\"Poblaciones de las particulas en el tiempo usando RK4\")\r\nplt.savefig(\"Figura3\")\r\n#plt.show()\r\n\r\n#Grafica en los planos n1,n1\r\nplt.figure(figsize=(10,5))\r\nNHGk=plt.plot(n2k4,n1k4, c=\"blue\")\r\nplt.xlim(0,12)\r\nplt.ylim(0,2)\r\nplt.ylabel(\"Poblacion 1\")\r\nplt.xlabel(\"Poblacion 2\")\r\nplt.grid(True)\r\nplt.title(\"Grafica en el plano n1,n2 usando RK4\")\r\nplt.savefig(\"Figura4\")\r\n#plt.show()\r\n\r\n#Graficando para el metodo euler\r\n#Grafica en los planos t,n1 y t,n2\r\nplt.figure(figsize=(10,5))\r\nN1Eu=plt.plot(t,n1Eu, c=\"red\",label=\"Poblacion 1 \")\r\nN2Eu=plt.plot(t,n2Eu, c=\"blue\",label=\"Poblacion 2\")\r\nplt.legend(fontsize=10)\r\nplt.xlabel(\"Tiempo\")\r\nplt.ylabel(\"Poblacion de particulas\")\r\nplt.xlim(0,12)\r\nplt.ylim(0,2)\r\nplt.grid(True)\r\nplt.title(\"Poblaciones de las particulas en el tiempo usando metodo de euler\")\r\nplt.savefig(\"Figura5\")\r\n#plt.show()\r\n\r\n#Grafica en los planos n1,n1\r\nplt.figure(figsize=(10,5))\r\nNHGk=plt.plot(n2Eu,n1Eu, c=\"blue\")\r\nplt.xlim(0,12)\r\nplt.ylim(0,2)\r\nplt.ylabel(\"Poblacion 1\")\r\nplt.xlabel(\"Poblacion 2\")\r\nplt.grid(True)\r\nplt.title(\"Grafica en el plano n1,n2 usando metodo de euler\")\r\nplt.savefig(\"Figura6\")\r\n#plt.show()\r\n\r\n###################################################################################################\r\n###################################################################################################\r\n\r\n#prueba de convergencia\r\n#Se implementa el RK4 y el metodo de euler para diferentes valores del paso h, luego se escoge el valor maximo de la lista de \r\n#errores derivada del valor absoluto de las soluciones por el metodo y las que se toman como exactas y se grafican estos \r\n#en funcion del paso h\r\n\r\n#En este ciclo se hace la lista de los valores del paso h\r\ntf=12.\r\nt0=0.\r\nH=[]\r\nfor n in (10,100,1000,10000,100000):\r\n h=(tf-t0)/n\r\n H.append(h)\r\n n=n+1\r\n\r\n#Prueba para el metodo RK4 y la particion t [0,12]\r\nErrores1k4=[]\r\nErrores2k4=[]\r\nfor j in H:\r\n N,t=RK4(F, np.array([1.5, 1]), 0., 12.,int(12/j) ) #se definen los valores arrojados por el RK4 de las poblaciones y a su vez el arreglo temporal globlal para las graficas\r\n n1k4=N[:,0]\r\n n2k4=N[:,1]\r\n sl0=[1.5,1] #condiciones iniciales del problema\r\n sls=odeint(f,sl0,t)#se usa el mismo t definido por el RK4\r\n n1Od=sls[:,0] #soluciones arrojados por odeint, se consideraran estas como exactas\r\n n2Od=sls[:,1]\r\n Err1=np.abs(n1k4-n1Od)\r\n Err2=np.abs(n2k4-n2Od)\r\n Errores1k4.append(max(Err1))\r\n Errores2k4.append(max(Err2))\r\n\r\n#Prueba para el metodo de euler y la particion t [0,12]\r\nErrores1Eu=[]\r\nErrores2Eu=[]\r\nfor l in H:\r\n N,t=euler(F, np.array([1.5, 1]), 0., 12., int(12/l)) #se definen los valores arrojados por el metodo euler de las poblaciones y a su vez el arreglo del tiempo para las graficas\r\n n1Eu=N[:,0]\r\n n2Eu=N[:,1]\r\n sl0=[1.5,1] #condiciones iniciales del problema\r\n sls=odeint(f,sl0,t)\r\n n1Od=sls[:,0] #soluciones arrojados por odeint, se consideraran estas como exactas\r\n n2Od=sls[:,1]\r\n Err1=np.abs(n1Eu-n1Od)\r\n Err2=np.abs(n2Eu-n2Od)\r\n Errores1Eu.append(max(Err1))\r\n Errores2Eu.append(max(Err2))\r\n\r\n#se grafican los maximos de la lista de errores en funcion del paso h, asi se garantiza que los demas convergen igualmente a cero\r\n#grafica para los errores del metodo RK4\r\nplt.figure(figsize=(10,5))\r\nA=plt.plot(H,Errores1k4, c=\"green\", label='Error en la poblacion 1')\r\nB=plt.plot(H,Errores2k4, c=\"black\", label='Error en la poblacion 2')\r\nplt.ylabel(\"Error\")\r\nplt.xlabel(\"Valor de h\")\r\nplt.grid()\r\nplt.legend()\r\nplt.title(\"Error del metodo RK4 para valores del paso h\")\r\nplt.savefig(\"Figura7\")\r\n#plt.show()\r\n\r\n#grafica para los errores del metodo de euler\r\nplt.figure(figsize=(10,5))\r\nC=plt.plot(H,Errores1Eu, c=\"green\", label='Error en la poblacion 1')\r\nD=plt.plot(H,Errores2Eu, c=\"black\", label='Error en la poblacion 2')\r\nplt.ylabel(\"Error\")\r\nplt.xlabel(\"Valor de h\")\r\nplt.grid()\r\nplt.legend()\r\nplt.title(\"Error del metodo de euler para valores del paso h\")\r\nplt.savefig(\"Figura8\")\r\n#plt.show()\r\n\r\n#de estas graficas se puede observar que ambos metodos convergen ya que el valor del error tomando el odeint como\r\n#la solucion exacta se hace cero mediante h se acerca a cero\r\n","sub_path":"Parciales/Parcial1/N1036783619/Parcial1P2.py","file_name":"Parcial1P2.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"359238619","text":"#coding=utf-8\nfrom appium import webdriver\nfrom appium.webdriver.common.mobileby import MobileBy\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nimport time\n\ndesired_caps = {}\ndesired_caps['platformName'] = 'Android'\ndesired_caps['platformVersion'] = '7.1.1'\ndesired_caps['deviceName'] = 'Android Emulator'\ndesired_caps['appPackage'] = 'com.android.calculator2'\ndesired_caps['appActivity'] = '.Calculator'\n\ndriver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)\n\ntime.sleep(1)\n\n# 切换之前按一下Home button显得更自然,不是必须步骤\ndriver.press_keycode(3)\n\ntime.sleep(2)\n\n# 打开另一个新的App\ndriver.start_activity('com.google.android.apps.messaging', '.ui.ConversationListActivity')\n\ntime.sleep(1)\n\n# 新打开的App自动变成当前driver指向的对象,这个与Seleniumg不同,可以直接云Find Eldement\nWebDriverWait(driver, 5, 0.5).until(EC.element_to_be_clickable((MobileBy.ANDROID_UIAUTOMATOR, \"new UiSelector().description(\\\"%s\\\")\" % \"Start new conversation\"))).click()\n\n# 这个方法是关闭desired_caps指定的App而不是当前的App\ndriver.close_app()\n\n#print(driver.window_handles)\n\ntime.sleep(3)\n\ndriver.quit()\n","sub_path":"Python-Library/Appium/MultiActivities/StartNewActivities.py","file_name":"StartNewActivities.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"214501168","text":"#!/usr/bin/python3\n\"\"\"Fabricfile that distributes web_static contents from AirBnB_v2 folder\"\"\"\nfrom fabric.api import local, hide, put, run, env, sudo, settings\nfrom datetime import datetime\nenv.hosts = ['35.231.116.248', '54.83.93.155']\n\n\ndef do_pack():\n \"\"\"Compresses folder in tgz format\"\"\"\n\n time = datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\n name = \"web_static\"\n loc = \"versions\"\n with hide('running'):\n local(\"mkdir -p versions\", capture=False)\n local(\"echo \\\"Packing {} to {}/{}_{}.tgz\\\"\"\n .format(name, loc, name, time))\n result = local(\"tar -cvzf {}/{}_{}.tgz web_static\"\n .format(loc, name, time))\n if not result.failed:\n return \"{}/{}_{}.tgz\".format(loc, name, time)\n else:\n return None\n\n\ndef do_deploy(archive_path):\n \"\"\"Sends archive_path to web server\"\"\"\n\n try:\n f = open(archive_path)\n f.close()\n except:\n return False\n root = \"/data/web_static\"\n arc_lst = archive_path.split(\"/\")\n res_f = list()\n result = put(\"{}\".format(archive_path), \"/tmp\")\n res_f.append(result.succeeded)\n run(\"mkdir -p {}/releases/{}\".format(root, arc_lst[1].split(\".\")[0]))\n result = run(\"tar -xzf /tmp/{} -C {}/releases/{} --strip=1\"\n .format(arc_lst[1], root, arc_lst[1].split(\".\")[0]))\n res_f.append(result.succeeded)\n result = run(\"rm -f {}/current /tmp/{}\".format(root, arc_lst[1]))\n res_f.append(result.succeeded)\n result = run(\"ln -snf {}/releases/{} {}/current\"\n .format(root, arc_lst[1].split(\".\")[0], root))\n res_f.append(result.succeeded)\n result = sudo(\"nginx -s reload\")\n res_f.append(result.succeeded)\n if False not in res_f:\n return True\n else:\n return False\n","sub_path":"2-do_deploy_web_static.py","file_name":"2-do_deploy_web_static.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"322628343","text":"import pickle\n\n\ndef write_data():\n \n try:\n while True:\n\n with open('/home/surajshukla7656/Documents/Python/nextpython/advanced_python/binary_file_handling/binaryFile','ab') as f:\n\n name=input('Enter name : ')\n \n if name=='':\n break\n\n pickle.dump(name,f)\n\n except:\n print()\nwrite_data()\n","sub_path":"advanced_python/binary_file_handling/prog1_write.py","file_name":"prog1_write.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"302856688","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 4 18:03:18 2019\n\n@author: MabuXayda\n\"\"\"\n\nimport sys\nimport time\nfrom datetime import datetime\n\ndef print_example():\n file = open(\"F:/temp/NordicCoder/python_analysis/test_schedule.txt\", \"w\") \n current_time = datetime.now()\n file.write(\"Job start at {}\".format(current_time))\n\nif __name__ == \"__main__\":\n if sys.argv[1] == \"test\":\n current_time = datetime.now()\n print(current_time)\n time.sleep(200)\n elif sys.argv[1] == \"print\":\n print_example()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"371355789","text":"import json\r\nimport datetime\r\nfrom functools import reduce\r\n\r\n\r\nwith open('todos.json', \"r\") as f:\r\n data = json.load(f)\r\n\r\n\r\ndef group_tasks_by_user(user_tasks):\r\n\r\n grouped_users_tasks = {}\r\n for task in user_tasks:\r\n if \"userId\" in task:\r\n user_id = task['userId']\r\n tasks = grouped_users_tasks[user_id] if user_id in grouped_users_tasks else []\r\n tasks.append(task)\r\n grouped_users_tasks[task['userId']] = tasks\r\n return grouped_users_tasks\r\n\r\n\r\ndef group_task_by_completed():\r\n\r\n completed_task = {}\r\n uncompleted_task = {}\r\n for user_id in group_tasks_by_user(data):\r\n tasks = group_tasks_by_user(data)[user_id]\r\n completed_task[user_id] = reduce((lambda x, y: str(x) + \"\\n\" + str(y)),\r\n map((lambda t: t[\"title\"] if len(t[\"title\"]) < 50 else t[\"title\"][0:50] + \"...\"), filter((lambda t: t['completed']), tasks)))\r\n uncompleted_task[user_id] = reduce((lambda x, y: str(x) + \"\\n\" + str(y)),\r\n map((lambda t: t[\"title\"] if len(t[\"title\"]) < 50 else t[\"title\"][0:50] + \"...\"), filter((lambda t: t['completed'] == False), tasks)))\r\n return completed_task, uncompleted_task\r\n\r\n\r\n\r\ndef write_in_file(completed_task, uncompleted_task):\r\n for user_id in group_tasks_by_user(data):\r\n today_data = datetime.datetime.today()\r\n with open(str(user_id) + str(today_data.strftime('_%Y-%m-%dT%H-%M')) + \".txt\", 'w', encoding='utf-8') as f:\r\n f.write(\"#Сотрудник №\" + str(user_id) + \"\\n\")\r\n f.write(str(today_data.strftime('%d.%m.%Y %H:%M')) + \"\\n\")\r\n f.write(\"\\n\")\r\n f.write(\"## Завершённые задачи:\\n\")\r\n f.write(completed_task[user_id] + \"\\n\")\r\n f.write(\"\\n\")\r\n f.write(\"## Оставшиеся задачи:\\n\")\r\n f.write(uncompleted_task[user_id])\r\n\r\n\r\ndef main():\r\n completed_task, uncompleted_task = group_task_by_completed()\r\n write_in_file(completed_task, uncompleted_task)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"577900802","text":"\"\"\"\n\nApproximate inference using Belief Propagation\nHere we can rely on some existing library,\nfor example https://github.com/mbforbes/py-factorgraph\nAuthors: lingxiao@cmu.edu\n kkorovin@cs.cmu.edu\n markcheu@andrew.cmu.edu\n\"\"\"\nimport numpy as np \nfrom scipy.special import logsumexp\n\nfrom inference.core import Inference\n\n\nclass BeliefPropagation_nonsparse(Inference):\n \"\"\"\n A special case implementation of BP\n for binary MRFs.\n Exact BP in tree structure only need two passes,\n LBP need multiple passes until convergene. \n \"\"\"\n\n def _safe_norm_exp(self, logit):\n logit -= np.max(logit, axis=1, keepdims=True)\n prob = np.exp(logit)\n prob /= prob.sum(axis=1, keepdims=True)\n return prob \n\n def _safe_divide(self, a, b):\n '''\n Divies a by b, then turns nans and infs into 0, so all division by 0\n becomes 0.\n '''\n c = a / b\n c[c == np.inf] = 0.0\n c = np.nan_to_num(c)\n return c\n\n def run_one(self, graph, use_log=True, smooth=0):\n # Asynchronous BP \n # Sketch of algorithm:\n # -------------------\n # preprocessing:\n # - sort nodes by number of edges\n # Algo:\n # - initialize messages to 1\n # - until convergence or max iters reached:\n # - for each node in sorted list (fewest edges to most):\n # - compute outgoing messages to neighbors\n # - check convergence of messages\n\n if self.mode == \"marginal\": # not using log\n sumOp = logsumexp if use_log else np.sum\n else:\n sumOp = np.max\n # storage, W should be symmetric \n max_iters = 100\n epsilon = 1e-10 # determines when to stop\n\n n_nodes = graph.W.shape[0]\n messages = np.zeros((n_nodes,n_nodes,2))\n x_potential = np.array([-1,1])\n for iter in range(max_iters):\n converged = True\n # save old message for checking convergence\n old_messages = messages.copy()\n # update messages\n for i in range(n_nodes):\n for j in range(n_nodes):\n if graph.W[i,j] != 0:\n for x_j in range(2):\n s = []\n for x_i in range(2):\n log_sum = graph.W[i,j]*x_potential[x_i]*x_potential[x_j]+graph.b[x_i]*x_potential[x_i]\n for k in range(n_nodes):\n if (graph.W[i,k]!=0 and k!=j):\n log_sum+=messages[k,i,x_i]\n s.append(log_sum)\n messages[i,j,x_j] = logsumexp(s)\n error = (messages - old_messages)**2\n error = error.mean()\n if error < epsilon: break\n\n if self.verbose: print(\"Is BP converged: {}\".format(converged))\n\n # calculate marginal\n probs = np.zeros((n_nodes,2))\n for i in range(n_nodes):\n for x_i in range(2):\n probs[i,x_i] = graph.b[i]*x_potential[x_i] # -1, 1\n for k in range(n_nodes):\n if(graph.W[i,k]!=0):\n probs[i,x_i] += messages[k,i,x_i]\n results = self._safe_norm_exp(probs)\n\n\n return results\n\n\n def run(self, graphs, use_log=True, verbose=False):\n self.verbose = verbose\n res = []\n for graph in graphs:\n res.append(self.run_one(graph, use_log=use_log))\n return res\n\n\nif __name__ == \"__main__\":\n bp = BeliefPropagation_nonsparse(\"marginal\")\n \n","sub_path":"inference/bp_nonsparse.py","file_name":"bp_nonsparse.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"20244288","text":"import itchat\nimport random\nimport os\n\n\ndef yellow_time(msg):\n if not len(images):\n path = '/home/nfs/share/Pixiv_H/'\n tmp = os.listdir(path)\n for i in tmp:\n images.append(path+i)\n msg.user.send_image(images[random.randint(0, len(images))])\n return\n\n\n@itchat.msg_register(itchat.content.TEXT)\ndef return_all(msg):\n print(msg.text)\n for i in functions:\n if msg.text in i:\n functions[i](msg)\n return\n\n\nfunctions = {\n ':色图time': yellow_time\n}\nimages = list()\n\ngui = not os.environ.get('GDMSESSION')\n\nitchat.auto_login(hotReload=True, enableCmdQR=gui)\nitchat.run()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"200199906","text":"\nimport socket\nimport logging\nimport psycopg2 \n\nlogging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)\n\ndef connect_db():\n\tdb_instance = psycopg2.connect(database='basic_values', user='postgres', password='password', host='127.0.0.1', port='5432')\n\tprint('opened database')\n\tdb_cursor = db_instance.cursor()\n\treturn db_instance, db_cursor\n\ndef create_clean_table(db_instance, db_cursor):\n\tdb_cursor.execute('DROP TABLE IF EXISTS numbers;')\n\tdb_instance.commit()\n\tdb_cursor.execute('CREATE TABLE IF NOT EXISTS numbers (row serial NOT NULL, input VARCHAR NOT NULL);')\n\tdb_instance.commit()\n\tlogging.info('Table created')\n\ndef socket_setup():\n\thost = socket.gethostname()\n\tdns_addr = socket.gethostbyname(host)\n\tport = 12345 # initiate port no above 1024\n\tserver_socket = socket.socket() # get instance\n\tserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t# look closely. The bind() function takes tuple as argument\n\tserver_socket.bind((dns_addr, port)) # bind host address and port together\n\n # configure how many client the server can listen simultaneously\n\tserver_socket.listen(2)\n\tconn, address = server_socket.accept() # accept new connection\n\tlogging.info(\"Connection from: %s\", address)\n\treturn conn\t\n\ndef server_program():\n\t# get the hostname\n\t# host = socket.gethostname()\n\t# dns_addr = socket.gethostbyname(host)\n\t# port = 12345 # initiate port no above 1024\n\n\tconn = socket_setup()\n\tdb_instance, db_cursor = connect_db()\n\n\tcreate_clean_table(db_instance, db_cursor)\n\t\n\twhile True:\n\t\t# receive data stream. it won't accept data packet greater than 1024 bytes\n\t\tdata = conn.recv(1024).decode()\n\t\tdata = data.lower()\n\t\tif data.endswith('bye') or not data:\n\t\t\tbreak\t\t\t\n\t\telif data.split()[0] == 'get':\n\t\t\t# msg = storage[int(data.split()[1])]\n\t\t\ttry:\n\t\t\t\trow_number = int(data.split()[1])\n\t\t\texcept:\n\t\t\t\tlogging.warning('Get row_number %s does not exist', data.split()[1])\n\t\t\t\tmsg = 'Invalid get request'\n\t\t\t\tconn.send(msg.encode())\n\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tdb_cursor.execute('SELECT input FROM numbers WHERE row = %d;' % (row_number))\n\t\t\t\trows = db_cursor.fetchall()\n\t\t\t\tprint(\"ROWS\", rows)\t\n\t\t\t\tmsg = ' '.join(rows[0])\n\t\t\texcept:\n\t\t\t\tlogging.warning('Row number %d for get request does not exist in table', row_number)\t\n\t\t\t\tmsg = 'Row does not exist'\t\t\n\t\telse:\n\t\t\tsql = 'INSERT INTO numbers (input) VALUES(%s);'\n\t\t\tprint(data)\n\t\t\tquery = db_cursor.mogrify(sql, (data,))\n\t\t\tdb_cursor.execute(query)\n\t\t\tdb_instance.commit()\n\t\t\tmsg = (data + ' added to index ')\n\t\tlogging.info(\"from connected user: \" + str(data))\n\t\tconn.send(msg.encode())\n\n\tconn.close() # close the connection\n\n\nif __name__ == '__main__':\n\tserver_program()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"191219715","text":"from ex4 import est_pair, afficher_caractere\n\ndef somme_range(nbr):\n\tsomme = 0\n\tfor i in range(nbr+1):\n\t\tsomme += i\n\treturn somme\n\ndef afficher_pair(s):\n\tfor i in range(len(s)):\n\t\tif est_pair(i):\n\t\t\tafficher_caractere(s, i)\t\t\n\ndef est_palyndrome(s):\n\ti = 0\n\tfor j in range(len(s)-1, -1, -1):\n\t\tif s[i] != s[j]:\n\t\t\treturn False\n\t\ti += 1\n\treturn True\n\n\n\n\ndef multiplie_par_9(n):\n\ti = 0\n\tsomme = 0\n\twhile i < 9:\n\t\tsomme += n\n\t\ti += 1\n\treturn str(somme)\n","sub_path":"Exercices/Introduction/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"503165749","text":"\n#\n# Copyright 2019 Xilinx Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Linear(nn.Linear):\n \"\"\"A linear module attached with FakeQuantize modules for both output\n activation and weight, used for quantization aware training.\n\n We adopt the same interface as `torch.nn.Linear`, please see\n https://pytorch.org/docs/stable/nn.html#torch.nn.Linear\n for documentation.\n\n Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to\n default.\n\n \"\"\"\n _FLOAT_MODULE = nn.Linear\n\n def __init__(self, in_features, out_features, bias=True, qconfig=None):\n super(Linear, self).__init__(in_features, out_features, bias)\n #assert qconfig, 'qconfig must be provided for QAT module'\n self.qconfig = qconfig\n\n self.weight_quantizer = qconfig.weight\n if bias:\n self.bias_quantizer = qconfig.bias\n\n def forward(self, input):\n weight = self.weight_quantizer(self.weight)\n bias = self.bias_quantizer(self.bias) if self.bias is not None else None\n return F.linear(input, weight, bias)\n\n def extra_repr(self):\n return super(Linear, self).extra_repr()\n\n @classmethod\n def from_float(cls, mod, qconfig):\n \"\"\"Create a qat module from a float module or qparams_dict\n\n Args: `mod` a float module, either produced by torch.quantization utilities\n or directly from user\n \"\"\"\n assert qconfig, 'Input float module must have a valid qconfig'\n assert type(mod) == cls._FLOAT_MODULE, ' qat.' + cls.__name__ + '.from_float only works for ' + \\\n cls._FLOAT_MODULE.__name__\n\n qat_linear = cls(\n mod.in_features,\n mod.out_features,\n bias=mod.bias is not None,\n qconfig=qconfig)\n qat_linear.weight = mod.weight\n qat_linear.bias = mod.bias\n return qat_linear\n","sub_path":"tools/RNN/rnn_quantizer/pytorch_binding/pytorch_nndct/nn/qat/modules/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"594022524","text":"# This client is designed to easily interact with Webmetrics' API.\n# Copyright (C) 2014 Shane Barbetta\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n__author__ = 'Shane Barbetta'\n\nimport urllib\nimport urllib2\nimport base64\nimport hashlib\nimport time\nimport json\n\n# store the URL and signature as state\n\nclass ApiConnection:\n\tdef __init__(self):\n\t\tself.username = ''\n\t\tself.sig = ''\n\t\tself.api_key = ''\n\t\tself.base_url = 'https://api.webmetrics.com/v2/?'\n\t\t\n\t# Authentication\n\t# The ability to created a signature hash value and retain it for\n\t# its +/- 10 minute duration, while dynamically refreshing the sig\n\t# once it becomes stale. If a request fails, it should try again\n\t# with a new auth token.\n\tdef auth(self, username, api_key):\n\t\tself.username = username\n\t\tself.api_key = api_key\n\t\ttimestamp = str(int(time.time()))\n\t\tself.sig = base64.b64encode(hashlib.sha1(username + api_key + timestamp).digest())\n\t\n\tdef _refresh(self, method):\n\t\tself.auth(self.username, self.api_key)\n\t\treturn self._do_call(method, False)\n\t\n\t# Requests\n\t# Methods for accessing the API using Python's native urllib2\n\t# libraries. Use the auth methods to verify the stored signature \n\t# and refresh if needed.\n\tdef get(self, method):\n\t\treturn self._do_call(method)\n\t\n\tdef _do_call(self, method, retry=True):\n\t\tbase_query = { 'username' : self.username, 'sig' : self.sig, 'format' : 'json' }\n\t\tbase_query.update(method)\n\t\trequest = self.base_url + urllib.urlencode(base_query)\n\t\t# print request\n\t\tresponse = urllib2.urlopen(request)\n\t\tdata = json.load(response)\n\t\t# print json.dumps(data)\n\t\ttime.sleep(3)\n\t\tif data['stat'] == 'fail' and retry == False:\n\t\t\traise Exception(\"Authentication failed.\")\n\t\telif data['stat'] == 'fail':\n\t\t\treturn self._refresh(method)\n\t\telse:\n\t\t\treturn json.dumps(data)","sub_path":"src/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"214534724","text":"# -*- coding:utf-8 -*-\n# 简单动画\n# 来自 《玩转Python轻松过二级》,作者 董国付\n\nimport tkinter as tk \nimport time\n\napp = tk.Tk()\napp.title('Animation')\napp['width'] = 800\napp['height'] = 600\ncanvas = tk.Canvas(app, bg='white', width=800, height=600)\n# 打开并加载图片\nimage = tk.PhotoImage(file=r'C:\\\\Users\\\\Jianlong Jin\\\\Pictures\\\\lala.gif') # 只支持gif文件\n# 记下图片编号\nid_actor = canvas.create_image(80, 80, image=image)\n# 控制是否自动运动的变量\nflag = False\n# 单击,角色自由运动\ndef onLeftButtonDown(event):\n global flag\n flag = True\n while flag:\n # id_actor 表示要运动的图形编号\n # 第二个参数表示 x 方向的移动距离,5表示向右移动5个像素\n # 第三个参数表示 y 方向的移动距离,0表示不移动\n canvas.move(id_actor, 5, 0)\n canvas.update()\n time.sleep(0.05)\ncanvas.bind('', onLeftButtonDown)\n\ndef onRightButtonUp():\n global flag\n flag = False\ncanvas.bind('', onRightButtonUp)\n\n# 支持键盘上的4个方向控制键来控制图片移动\ndef keyControl(event):\n if event.keysym=='Up':\n canvas.move(id_actor,0,-5)\n canvas.update()\n elif event.keysym=='Down':\n canvas.move(id_actor,0,5)\n canvas.update()\n elif event.keysym=='Left':\n canvas.move(id_actor,-5,0)\n canvas.update()\n elif event.keysym=='Right':\n canvas.move(id_actor,5,0)\n canvas.update()\ncanvas.bind_all('',keyControl)\ncanvas.bind_all('',keyControl)\ncanvas.bind_all('',keyControl)\ncanvas.bind_all('',keyControl)\n\ncanvas.pack(fill=tk.BOTH, expand=tk.YES)\ncanvas.focus()\n\napp.mainloop()\n\n","sub_path":"tkinter/Animation.pyw","file_name":"Animation.pyw","file_ext":"pyw","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"531845676","text":"from typing import Union\n\nfrom lxml.etree import ElementBase\n\nfrom manga_py.exceptions import InvalidChapter\nfrom manga_py.libs import fs\nfrom ._file import BaseFile\n\n\nclass File(BaseFile):\n def __init__(self, idx, data, provider):\n super().__init__(idx, data, provider)\n self._location = self.provider.temp_path_location\n\n def _parse_data(self, data: Union[tuple, ElementBase]):\n if not isinstance(data, (tuple, ElementBase)):\n InvalidChapter(data)\n if isinstance(data, ElementBase):\n self._url = self._http.normalize_uri(data.get('src'))\n name = fs.basename(self._url)\n name = fs.remove_query(name)\n else:\n # ('absolute_url', 'relative_file_name')\n self._url = data[0]\n name = data[1]\n self._name = self._normalize_name(name)\n\n def _normalize_name(self, name):\n if self.provider.arg('rename-pages'):\n return '{:0>3}'.format(self._idx)\n return '{:0>3}_{}'.format(self._idx, name)\n","sub_path":"manga_py/libs/base/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"129514099","text":"import sys, os, os.path, configparser, subprocess, shutil, tempfile, time\n\nimport pmaker.problem\n\ndef error(msg):\n print(msg)\n\nhelp_info = []\ncommands_list = []\n\ndef cmd(want=[], arg=None, manual=None, long_help=None):\n def wrapper(f):\n def new_func(argv, __ptr=0, __kwargs=dict()):\n if (__ptr == len(want)):\n return f(**__kwargs)\n\n feature = want[__ptr]\n if feature == \"prob-old\":\n prob = lookup_problem(os.path.realpath(\".\"))\n if not prob:\n error(\"fatal: couldn't find problem\")\n return 1\n\n __kwargs[\"prob\"] = prob\n return new_func(argv, __ptr=__ptr+1, __kwargs=__kwargs)\n \n if feature == \"prob\":\n import pmaker.problem\n prob = pmaker.problem.lookup_problem()\n if not prob:\n error(\"fatal: couldn't find problem\")\n return 1\n\n __kwargs[\"prob\"] = prob\n return new_func(argv, __ptr=__ptr+1, __kwargs=__kwargs)\n\n if feature == \"imanager\":\n from pmaker.invocation_manager import new_invocation_manager\n \n __kwargs[\"imanager\"] = new_invocation_manager(__kwargs[\"prob\"], __kwargs[\"prob\"].relative(\"work\", \"invocations\"))\n return new_func(argv, __ptr=__ptr+1, __kwargs=__kwargs)\n\n if feature == \"ui\":\n from pmaker.ui.web.web import WebUI\n __kwargs[\"ui\"] = WebUI(__kwargs[\"prob\"])\n return new_func(argv, __ptr=__ptr+1, __kwargs=__kwargs)\n\n if feature == \"argv\":\n __kwargs[\"argv\"] = argv\n return new_func(argv, __ptr=__ptr+1, __kwargs=__kwargs)\n \n if feature == \"judge\":\n from pmaker.judge import new_judge\n with new_judge() as judge:\n __kwargs[\"judge\"] = judge\n return new_func(argv, __ptr=__ptr+1, __kwargs=__kwargs)\n\n raise ValueError(\"Unsupported feature {}\".format(feature))\n\n if (manual):\n help_info.append((arg, manual, long_help))\n commands_list.append((arg, new_func))\n return new_func\n\n return wrapper\n\n@cmd(want=[\"prob\", \"judge\"], arg=\"tests\", manual=\"Update problem's tests, solutions, etc.\",\n long_help = \"\"\"tests command, does the following:\n \n * Compiles the checker.\n * Runs and analyses test script\n * Compiles required generators\n * Generates all tests\n * Compiles validator and validates tests (if validator present)\n * Compiles model solution\n * Generates all model answers\n\nDue to heavy usage of cache, many jobs will be skipped, if they are up to date.\n \"\"\")\ndef cmd_tests(prob=None, judge=None):\n prob.set_judge(judge)\n prob.update_tests()\n return 0\n\n@cmd(want=[\"prob\", \"imanager\", \"judge\", \"ui\", \"argv\"], arg=\"invoke\",\n manual=\"Invoke specified solutions\",\n long_help=\"\"\"Invokes the specified solutions\n\nUsage: pmaker invoke [list-of-solutions],\nor pmaker invoke @all\n\nYou will probably want to run \"pmaker tests\" prior this command.\n\nThe link http://localhost:8128/ will redirect you to the ongoing invocation\nSee also http://localhost:8128/invocation for invocation list\n\"\"\")\ndef cmd_invoke(prob=None, imanager=None, judge=None, ui=None, argv=None):\n import threading\n\n prob.set_judge(judge) \n solutions = argv\n test_cnt = prob.get_testset().size()\n test_indices = list(range(1, test_cnt + 1))\n \n if solutions == [\"@all\"]:\n solutions = os.listdir(prob.relative(\"solutions\"))\n solutions.sort()\n \n uid, invocation = imanager.new_invocation(judge, solutions, test_indices)\n ithread = threading.Thread(target=invocation.start)\n ithread.start()\n \n ui.mode_invocation(uid, imanager)\n ui.start()\n \n ithread.join()\n return 0\n\n\n@cmd(want=[\"prob\", \"argv\"], arg=\"run\",\n manual=\"Run the solution interactively in CLI\",\n long_help=\"\"\"Invokes the specified solution for interactive communication\nUsage: pmaker run \n\nCompiles and interactively runs the specified solution name in the CLI.\n\nUse stdin and stdout to communicate with the solution.\n\nWarning: solution is runned without been sandboxed.\n\"\"\")\ndef cmd_run(prob=None, argv=None):\n import subprocess\n\n if (len(argv) != 1):\n print(\"usage: pmaker run \")\n return 1\n\n sol = argv[0]\n \n need_compile = False\n try:\n prob.compile(\"solutions\", sol, check_only=True)\n except pmaker.problem.ProblemJobOutdated:\n need_compile = True\n\n if need_compile:\n from pmaker.judge import new_judge\n with new_judge() as judge:\n prob.set_judge(judge)\n prob.compile(\"solutions\", sol)\n \n prob.compile(\"solutions\", sol)\n path = prob.compilation_result(\"solutions\", sol)\n \n res = subprocess.run(path, universal_newlines=True)\n print(\"Exitted with code {}\".format(res.returncode), file=sys.stderr)\n return res.returncode\n\n\n@cmd(want=[\"prob\", \"imanager\", \"ui\"], arg=\"invocation-list\",\n manual=\"Show previous invocations\",\n long_help=\"\"\"Starts the web server so you can examine previous invocations\n \nSee http://localhost:8128/invocation for invocation list\nAnd http://localhost:8128/invocation/ for the previous invocation\n \"\"\")\ndef cmd_invocation_list(prob=None, imanager=None, ui=None):\n ui.mode_invocation_list(imanager)\n ui.start()\n return 0\n\n@cmd(want=[\"prob\", \"ui\"], arg=\"testview\", manual=\"Show test data\",\n long_help = \"\"\"Examine the tests\n \nConnect to http://localhost:8128/ or localhost::8128/test_view\nTo browse the tests\n\nYou probably want run \"pmaker tests\" prior this command.\n\"\"\")\ndef cmd_testview(prob=None, ui=None):\n ui.mode_testview()\n ui.start()\n return 0\n\n\n@cmd(want=[\"argv\"], arg=\"help\", manual=\"Show this help\")\ndef cmd_help(argv=None):\n if len(argv) == 1:\n for (cmd, desc, hlp) in help_info:\n if cmd == argv[0]:\n print(\"Help for {}\".format(cmd))\n print(\"=\" * len(\"Help for {}\".format(cmd)))\n print(hlp)\n \n return 0\n\n print(\"Failed to find help for the {}\".format(cmd))\n return 1\n\n if len(argv) > 2:\n print(\"Invalid help topic\")\n return 1\n \n import pmaker\n print(\"PMaker v{}\".format(pmaker.__version__))\n print(\"\")\n print(\"Usage:\")\n print(\"======\")\n\n max_cmd = 0\n for (cmd, desc, hlp) in help_info:\n max_cmd = max(max_cmd, len(cmd))\n \n for (cmd, desc, hlp) in help_info:\n print(cmd + \" \" * (3 + max_cmd - len(cmd)) + desc)\n\n print(\"\")\n print(\"For more information use help \")\n\n@cmd(arg=\"--help\")\ndef cmd_help2():\n return cmd_help([])\n\n@cmd(want=[\"prob\", \"argv\"], arg=\"clean\", manual=\"Wipe data\",\n long_help = \"\"\"Wipes all generated data and cache, except invocations.\n\nAdd \"--mrpropper\" flag to wipe invocations as well.\n\"\"\")\ndef cmd_clean(prob=None, argv=None):\n if not argv in [[], [\"--mrpropper\"]]:\n print(\"Unrecognized arg\")\n\n prob.wipe(mrpropper=(argv == [\"--mrpropper\"]))\n return 0\n\n@cmd(want=[\"prob\"], arg=\"make_valuer\")\ndef cmd_valuer(prob=None):\n #print(\"# # # generated with pmaker # # #\")\n print(\"\"\"\nglobal {\n stat_to_judges 1;\n stat_to_users 1;\n}\"\"\")\n\n tests = prob.get_testset()\n group_info = prob.get_testset().group_info()\n \n samples = []\n offline = []\n not_offline = []\n line = prob._parser.get(\"scoring\", \"samples\", fallback=None)\n if line:\n samples = list(map(lambda s: s.strip(), line.split(\";\")))\n \n line = prob._parser.get(\"scoring\", \"offline\", fallback=None)\n if line:\n offline = list(map(lambda s: s.strip(), line.split(\";\")))\n \n test_score_list = ['0' for i in range(tests.size())]\n sum_score = 0\n sum_user_score = 0\n \n for gr in sorted(group_info.keys(), key=int):\n if len(group_info[gr]) != 1:\n print(\"Group {} is not contigious\".format(gr), file=sys.stderr)\n sys.exit(1)\n\n test_score_list[group_info[gr][0][1] - 1] = prob._parser.get(\"scoring\", \"score_\" + gr, fallback=\"0\")\n if not gr in offline:\n not_offline.append(gr)\n \n for gr in sorted(group_info.keys(), key=int):\n sc = int(prob._parser.get(\"scoring\", \"score_\" + gr, fallback=\"0\"))\n sum_score += sc\n if not gr in offline:\n sum_user_score += sc\n\n req = \"\"\n line = prob._parser.get(\"scoring\", \"require_\" + gr, fallback=None)\n if line:\n req = \"requires {};\".format(\",\".join(map(lambda s: s.strip(), line.split(\";\"))))\n\n print(\"group %s {\" % gr)\n print(\" tests %d-%d;\" % (group_info[gr][0][0], group_info[gr][0][1]))\n print(\" score %d;\" % sc)\n\n if gr in offline:\n print(\" offline;\")\n\n if len(not_offline) != 0 and gr == not_offline[-1]:\n print(\" sets_marked_if_passed %s;\" % \", \".join(not_offline))\n \n print(\" %s\" % req)\n print(\"}\")\n \n print('# test_score_list=\"{}\"'.format(\" \".join(test_score_list)))\n open_tests = []\n for gr in sorted(group_info.keys(), key=int):\n if gr in samples:\n open_tests.append(\"%d-%d:full\" % (group_info[gr][0][0], group_info[gr][0][1]))\n elif gr in offline:\n open_tests.append(\"%d-%d:hidden\" % (group_info[gr][0][0], group_info[gr][0][1]))\n else:\n open_tests.append(\"%d-%d:brief\" % (group_info[gr][0][0], group_info[gr][0][1]))\n if open_tests:\n print('# open_tests=\"{}\"'.format(\",\".join(open_tests)))\n print('# full_score=%d' % sum_score)\n print('# full_user_score=%d' % sum_user_score)\n\ndef main():\n try:\n argv = sys.argv[1:]\n if len(argv) == 0:\n argv = [\"--help\"]\n\n for (matcher, command) in commands_list:\n if (matcher == argv[0]):\n return command(argv[1:])\n\n print(\"There is no such command\")\n argv = [\"--help\"]\n\n for (matcher, command) in commands_list:\n if (matcher == argv[0]):\n return command(argv[1:])\n except KeyboardInterrupt as ex:\n print(\"Interrupted\")\n sys.exit(0)\n","sub_path":"src/pmaker/enter.py","file_name":"enter.py","file_ext":"py","file_size_in_byte":10392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"463992585","text":"# coding: utf-8\n# author: HotDogDevBr.\n# E-mail: hotdogdevbr@gmail.com.\n\"\"\"\n Escreva um programa que converta uma temperatura digitada\n\"C em F\".\n\"\"\"\n\n\nc = int(input(\"Digite uma temperatura C°(Graus): \"))\nf = (9 * c) / 5 + 32\n\nprint(\"Converta de C° {} para Fº: {}\".format(c, f))\n","sub_path":"Exercicios Livro Python/capitulo 3/exercicio 3.13.py","file_name":"exercicio 3.13.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"45647047","text":"from django import template\nfrom django.conf import settings\n\nregister = template.Library()\n\nclass ShowMixpanelInit(template.Node):\n def render(self, context):\n mixpanel_token = getattr(settings, 'MIXPANEL_TOKEN', None)\n if not mixpanel_token:\n return ''.join([\"\\n\",\n \"\\n\"\n \"\"\"\\n\"\"\",\n \"\"\"\\n\"\"\",\n \"\"\"\\n\"\"\"])\n\n if 'user' in context and context['user'] and context['user'].is_staff:\n return ''.join([\"\\n\",\n \"\\n\"\n \"\"\"\\n\"\"\",\n \"\"\"\\n\"\"\",\n \"\"\"\\n\"\"\"])\n\n return ''.join([\"\\n\",\n \"\"\"\\n\"\"\",\n \"\"\"\\n\"\"\",\n \"\"\"\\n\"\"\"])\n\n # Snippet taken from mixpanel docs:\n # https://mixpanel.com/help/reference/javascript\n mixpanel_init_code = ''.join([\n \"\"\"(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;b._i=[\"\"\",\n \"\"\"];b.init=function(a,e,d){function f(b,h){var a=h.split(\".\");2==\"\"\",\n \"\"\"a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(\"\"\",\n \"\"\"Array.prototype.slice.call(arguments,0)))}}var c=b;\"undefined\"!\"\"\",\n \"\"\"==typeof d?c=b[d]=[]:d=\"mixpanel\";c.people=c.people||[];c.toStr\"\"\",\n \"\"\"ing=function(b){var a=\"mixpanel\";\"mixpanel\"!==d&&(a+=\".\"+d);b||\"\"\",\n \"\"\"(a+=\" (stub)\");return a};c.people.toString=function(){return c.\"\"\",\n \"\"\"toString(1)+\".people (stub)\"};i=\"disable track track_pageview t\"\"\",\n \"\"\"rack_links track_forms register register_once alias unregister \"\"\",\n \"\"\"identify name_tag set_config people.set people.set_once people.\"\"\",\n \"\"\"increment people.append people.track_charge people.clear_charge\"\"\",\n \"\"\"s people.delete_user\".split(\" \");\\n\"\"\",\n \"\"\"for(g=0;g\"\n# helps match 'http.server', as in 'http.server.HTTPServer(...)'\npower_twoname = u\"pow=power< {fmt_name} trailer< '.' {fmt_attr} > trailer< '.' using=any > any* >\"\n# helps match 'dbm.whichdb', as in 'dbm.whichdb(...)'\npower_onename = u\"pow=power< {fmt_name} trailer< '.' using=any > any* >\"\n# helps match 'from http.server import HTTPServer'\n# also helps match 'from http.server import HTTPServer, SimpleHTTPRequestHandler'\n# also helps match 'from http.server import *'\nfrom_import = u\"from_import=import_from< 'from' {modules} 'import' (import_as_name< using=any 'as' renamed=any> | in_list=import_as_names< using=any* > | using='*' | using=NAME) >\"\n# helps match 'import urllib.request'\nname_import = u\"name_import=import_name< 'import' ({fmt_name} | in_list=dotted_as_names< imp_list=any* >) >\"\n\n#############\n# WON'T FIX #\n#############\n\n# helps match 'import urllib.request as name'\nname_import_rename = u\"name_import_rename=dotted_as_name< {fmt_name} 'as' renamed=any >\"\n# helps match 'from http import server'\nfrom_import_rename = u\"from_import_rename=import_from< 'from' {fmt_name} 'import' ({fmt_attr} | import_as_name< {fmt_attr} 'as' renamed=any > | in_list=import_as_names< any* ({fmt_attr} | import_as_name< {fmt_attr} 'as' renamed=any >) any* >) >\"\n\n\ndef all_modules_subpattern():\n u\"\"\"\n Builds a pattern for all toplevel names\n (urllib, http, etc)\n \"\"\"\n names_dot_attrs = [mod.split(u\".\") for mod in MAPPING]\n ret = u\"( \" + u\" | \".join([dotted_name.format(fmt_name=simple_name.format(name=mod[0]),\n fmt_attr=simple_attr.format(attr=mod[1])) for mod in names_dot_attrs])\n ret += u\" | \"\n ret += u\" | \".join([simple_name.format(name=mod[0])\n for mod in names_dot_attrs if mod[1] == u\"__init__\"]) + u\" )\"\n return ret\n\n\ndef all_candidates(name, attr, MAPPING=MAPPING):\n u\"\"\"\n Returns all candidate packages for the name.attr\n \"\"\"\n dotted = name + u'.' + attr\n assert dotted in MAPPING, u\"No matching package found.\"\n ret = MAPPING[dotted]\n if attr == u'__init__':\n return ret + (name,)\n return ret\n\n\ndef new_package(name, attr, using, MAPPING=MAPPING, PY2MODULES=PY2MODULES):\n u\"\"\"\n Returns which candidate package for name.attr provides using\n \"\"\"\n for candidate in all_candidates(name, attr, MAPPING):\n if using in PY2MODULES[candidate]:\n break\n else:\n candidate = None\n\n return candidate\n\n\ndef build_import_pattern(mapping1, mapping2):\n u\"\"\"\n mapping1: A dict mapping py3k modules to all possible py2k replacements\n mapping2: A dict mapping py2k modules to the things they do\n This builds a HUGE pattern to match all ways that things can be imported\n \"\"\"\n # py3k: urllib.request, py2k: ('urllib2', 'urllib')\n yield from_import.format(modules=all_modules_subpattern())\n for py3k, py2k in mapping1.items():\n name, attr = py3k.split(u'.')\n s_name = simple_name.format(name=name)\n s_attr = simple_attr.format(attr=attr)\n d_name = dotted_name.format(fmt_name=s_name, fmt_attr=s_attr)\n yield name_import.format(fmt_name=d_name)\n yield power_twoname.format(fmt_name=s_name, fmt_attr=s_attr)\n if attr == u'__init__':\n yield name_import.format(fmt_name=s_name)\n yield power_onename.format(fmt_name=s_name)\n yield name_import_rename.format(fmt_name=d_name)\n yield from_import_rename.format(fmt_name=s_name, fmt_attr=s_attr)\n\n\ndef name_import_replacement(name, attr):\n children = [Name(u\"import\")]\n for c in all_candidates(name.value, attr.value):\n children.append(Name(c, prefix=u\" \"))\n children.append(Comma())\n children.pop()\n replacement = Node(syms.import_name, children)\n return replacement\n\n\nclass FixImports2(fixer_base.BaseFix):\n\n run_order = 4\n\n PATTERN = u\" | \\n\".join(build_import_pattern(MAPPING, PY2MODULES))\n\n def transform(self, node, results):\n # The patterns dictate which of these names will be defined\n name = results.get(u\"name\")\n attr = results.get(u\"attr\")\n if attr is None:\n attr = Name(u\"__init__\")\n using = results.get(u\"using\")\n in_list = results.get(u\"in_list\")\n imp_list = results.get(u\"imp_list\")\n power = results.get(u\"pow\")\n before = results.get(u\"before\")\n after = results.get(u\"after\")\n d_name = results.get(u\"dotted_name\")\n # An import_stmt is always contained within a simple_stmt\n simple_stmt = node.parent\n # The parent is useful for adding new import_stmts\n parent = simple_stmt.parent\n idx = parent.children.index(simple_stmt)\n if any((results.get(u\"from_import_rename\") is not None,\n results.get(u\"name_import_rename\") is not None)):\n self.cannot_convert(\n node, reason=u\"ambiguity: import binds a single name\")\n\n elif using is None and not in_list:\n # import urllib.request, single-name import\n replacement = name_import_replacement(name, attr)\n replacement.prefix = node.prefix\n node.replace(replacement)\n\n elif using is None:\n # import ..., urllib.request, math, http.sever, ...\n for d_name in imp_list:\n if d_name.type == syms.dotted_name:\n name = d_name.children[0]\n attr = d_name.children[2]\n elif d_name.type == token.NAME and d_name.value + u\".__init__\" in MAPPING:\n name = d_name\n attr = Name(u\"__init__\")\n else:\n continue\n if name.value + u\".\" + attr.value not in MAPPING:\n continue\n candidates = all_candidates(name.value, attr.value)\n children = [Name(u\"import\")]\n for c in candidates:\n children.append(Name(c, prefix=u\" \"))\n children.append(Comma())\n children.pop()\n # Put in the new statement.\n indent = indentation(simple_stmt)\n next_stmt = Node(\n syms.simple_stmt, [Node(syms.import_name, children), Newline()])\n parent.insert_child(idx + 1, next_stmt)\n parent.insert_child(idx + 1, Leaf(token.INDENT, indent))\n # Remove the old imported name\n test_comma = d_name.next_sibling\n if test_comma and test_comma.type == token.COMMA:\n test_comma.remove()\n elif test_comma is None:\n test_comma = d_name.prev_sibling\n if test_comma and test_comma.type == token.COMMA:\n test_comma.remove()\n d_name.remove()\n if not in_list.children:\n simple_stmt.remove()\n\n elif in_list is not None:\n ##########################################################\n # \"from urllib.request import urlopen, urlretrieve, ...\" #\n # Replace one import statement with potentially many. #\n ##########################################################\n packages = dict([(n, []) for n in all_candidates(name.value,\n attr.value)])\n # Figure out what names need to be imported from what\n # Add them to a dict to be parsed once we're completely done\n for imported in using:\n if imported.type == token.COMMA:\n continue\n if imported.type == syms.import_as_name:\n test_name = imported.children[0].value\n if len(imported.children) > 2:\n # 'as' whatever\n rename = imported.children[2].value\n else:\n rename = None\n elif imported.type == token.NAME:\n test_name = imported.value\n rename = None\n pkg = new_package(name.value, attr.value, test_name)\n packages[pkg].append((test_name, rename))\n\n # Parse the dict to create new import statements to replace this\n # one\n imports = []\n for new_pkg, names in packages.items():\n if not names:\n # Didn't import anything from that package, move along\n continue\n new_names = []\n for test_name, rename in names:\n if rename is None:\n new_names.append(Name(test_name, prefix=u\" \"))\n else:\n new_names.append(\n ImportAsName(test_name, rename, prefix=u\" \"))\n new_names.append(Comma())\n new_names.pop()\n imports.append(FromImport(new_pkg, new_names))\n # Replace this import statement with one of the others\n replacement = imports.pop()\n replacement.prefix = node.prefix\n node.replace(replacement)\n indent = indentation(simple_stmt)\n # Add the remainder of the imports as new statements.\n while imports:\n next_stmt = Node(syms.simple_stmt, [imports.pop(), Newline()])\n parent.insert_child(idx + 1, next_stmt)\n parent.insert_child(idx + 1, Leaf(token.INDENT, indent))\n\n elif using.type == token.STAR:\n # from urllib.request import *\n nodes = [FromImport(pkg, [Star(prefix=u\" \")]) for pkg in\n all_candidates(name.value, attr.value)]\n replacement = nodes.pop()\n replacement.prefix = node.prefix\n node.replace(replacement)\n indent = indentation(simple_stmt)\n while nodes:\n next_stmt = Node(syms.simple_stmt, [nodes.pop(), Newline()])\n parent.insert_child(idx + 1, next_stmt)\n parent.insert_child(idx + 1, Leaf(token.INDENT, indent))\n elif power is not None:\n # urllib.request.urlopen\n # Replace it with urllib2.urlopen\n pkg = new_package(name.value, attr.value, using.value)\n # Remove the trailer node that contains attr.\n if pkg:\n if attr.parent:\n attr.parent.remove()\n name.replace(Name(pkg, prefix=name.prefix))\n\n elif using.type == token.NAME:\n # from urllib.request import urlopen\n pkg = new_package(name.value, attr.value, using.value)\n if attr.value == u\"__init__\" and pkg == name.value:\n # Replacing \"from abc import xyz\" with \"from abc import xyz\"\n # Just leave it alone so as not to mess with other fixers\n return\n else:\n node.replace(FromImport(pkg, [using]))\n","sub_path":"3to2-1.0/lib3to2/fixes/imports2_fix_alt_formatting.py","file_name":"imports2_fix_alt_formatting.py","file_ext":"py","file_size_in_byte":16243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"416970720","text":"from os.path import basename, dirname\n\nfrom irods.manager import Manager\nfrom irods.data_object import iRODSDataObject\nfrom irods.models import (DataObject, Collection, User, DataAccess)\nfrom irods.access import iRODSAccess\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass AccessManager(Manager):\n def get(self, path):\n\n conditions = [\n Collection.name == dirname(path), \n DataObject.name == basename(path)\n ]\n\n results = self.sess.query(User.name, User.id, DataObject.id, DataAccess.name)\\\n .filter(*conditions).all()\n\n return [iRODSAccess(\n access_name = row[DataAccess.name],\n user_id = row[User.id],\n data_id = row[DataObject.id],\n user_name = row[User.name]\n ) for row in results]\n","sub_path":"irods/manager/access_manager.py","file_name":"access_manager.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"260492532","text":"#fibonacci using recursion\ndef fib(x):\n if x == 0 or x == 1:\n return 1\n else: \n return fib(x-1) + fib(x-2)\n#4th fibonacci term\nprint(fib(4))\n\n#to print the series\nnum = int(input())\nfor i in range(num):\n print(fib(i))","sub_path":"other topics/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"324271170","text":"\"\"\"\nCouchSink - CouchDB alerts store with the AlertProcessor.\n\n\"\"\"\n\nimport logging\n\nfrom WMCore.Database.CMSCouch import Document, Database, CouchServer\n\n\nclass CouchSink(object):\n \"\"\"\n Alert sink for pushing alerts to a couch database.\n\n \"\"\"\n def __init__(self, config):\n self.config = config\n logging.info(\"Instantiating ...\")\n # test if the configured database does not exist, create it\n server = CouchServer(self.config.url)\n databases = server.listDatabases()\n if self.config.database not in databases:\n logging.warn(\"'%s' database does not exist on %s, creating it ...\" %\n (self.config.database, self.config.url))\n server.createDatabase(self.config.database)\n logging.warn(\"Created.\")\n logging.info(\"'%s' database exists on %s\" % (self.config.database, self.config.url))\n self.database = Database(self.config.database, self.config.url)\n logging.info(\"Initialized.\")\n\n\n def send(self, alerts):\n \"\"\"\n Handle list of alerts.\n\n \"\"\"\n retVals = []\n for a in alerts:\n doc = Document(None, a)\n retVal = self.database.commitOne(doc)\n retVals.append(retVal)\n logging.debug(\"Stored %s alerts to CouchDB, retVals: %s\" % (len(alerts), retVals))\n return retVals\n","sub_path":"src/python/WMCore/Alerts/ZMQ/Sinks/CouchSink.py","file_name":"CouchSink.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"531564587","text":"import pandas as pd\nfrom pandas import pivot_table\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom app.models import AccountingRecordBase\nfrom app.views.serializers import AccountingRecordBaseSerializer\n\nindices = ['accountType', 'accountName', 'accountId', 'accountNumber']\ncolumn_order = [[i for i in range(1, 13)]]\n\n\nclass Spreadsheet(APIView):\n def get(self, request):\n base = AccountingRecordBase.objects.order_by(\"date\").all()\n\n data = AccountingRecordBaseSerializer(base, many=True).data\n\n df = pd.DataFrame.from_dict(data)\n\n table1 = get_table(df, [\"AS\", \"LI\"], True)\n table2 = get_table(df, [\"EX\", \"RE\"], False)\n\n table1.reset_index(inplace=True)\n table2.reset_index(inplace=True)\n\n cols = [i for i in range(1, 13)] + indices\n\n table = pd.merge(table1, table2, 'outer', on=cols)\n\n return Response(pd.json.loads(table.to_json(orient='records')))\n\n\ndef get_table(df, cols, cum_sum):\n df = df[df[\"accountType\"].isin(cols)]\n\n table = pivot_table(df, values='amount', index=indices,\n columns=['month'], aggfunc=pd.np.sum)\n\n if cum_sum:\n table = table.cumsum(axis=1)\n\n table = table.reindex_axis(column_order, axis=1)\n\n table = table.reindex_axis([[\"AS\", \"LI\", \"RE\", \"EX\"]], axis=0, level=0)\n\n return table\n\n","sub_path":"accounting-app/app/views/statistics/spreadsheet.py","file_name":"spreadsheet.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"75"}
+{"seq_id":"527792576","text":"import torchvision\n\nfrom PIL import Image, ImageDraw\n\nfrom src.MagnetCluster import MagnetCluster\nfrom src.Matcher import Matcher\nimport argparse\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Find face on picture.')\n parser.add_argument('-f','--filename', metavar='FILENAME', type=str, default=\"assemblee.jpg\",\n help='File name')\n parser.add_argument('-p','--path', metavar='PATH', type=str, default=\"samples/\",\n help='Path of the file')\n parser.add_argument('-mh', '--maxheight', metavar='MAXHEIGHT', type=int, default=1000,\n help='Picture is resized to a max height (0 for unlimited height)')\n parser.add_argument('-t', '--threshold', metavar='THRESHOLD', type=float, default=0.99,\n help='Threshold for face detection')\n parser.add_argument('-o', '--offset', metavar='OFFSET', type=int, default=10,\n help='Offset of the window')\n parser.add_argument('-md', '--min-dist', metavar='MIN-DIST', type=int, default=20,\n help='Minimum distance for clustering window')\n parser.add_argument('-mv', '--min-votes', metavar='MIN-VOTES', type=int, default=1,\n help='Number minimum of vote for face detection')\n parser.add_argument('-m', '--model', metavar='MODEL', type=str, default=\"model.pt\",\n help='Name of the model (in \"models\" folder)')\n\n args = parser.parse_args()\n\n image = Image.open(\"../\"+ args.path + args.filename)\n\n if args.maxheight != 0 and image.size[1] > args.maxheight:\n preprocessedWidth = int(args.maxheight * image.size[0] / image.size[1])\n image = torchvision.transforms.Resize((args.maxheight, preprocessedWidth))(image)\n\n matcher = Matcher(image, sampleSize=(36, 36), offset=(args.offset, args.offset), threshold=args.threshold, model=args.model)\n\n matches = matcher.matches\n\n bestMatches = MagnetCluster.extract(matches, args.min_dist, args.min_votes)\n\n print(str(len(bestMatches)) + \" best matches found\")\n\n # Return a color between red 0%, yellow 50% and green 100%\n def compute_color(probability):\n if probability < 0.5:\n q = probability / 0.50\n r = round(0xDB + q * (0xFB - 0xDB))\n g = round(0x28 + q * (0xBD - 0x28))\n b = round(0x28 + q * (0x08 - 0x28))\n else:\n q = (probability - 0.50) / 0.75\n r = round(0xFB + q * (0x21 - 0xFB))\n g = round(0xBD + q * (0xBA - 0xBD))\n b = round(0x08 + q * (0x45 - 0x08))\n return r, g, b, 192\n\n\n # Draw best matches\n\n image = image.convert('RGBA')\n layer = Image.new('RGBA', image.size, (255, 255, 255, 0))\n\n draw = ImageDraw.Draw(layer)\n\n for bestMatch in bestMatches:\n normalizedProbability = bestMatch.probability\n color = compute_color(normalizedProbability)\n # color = (0,0,0)\n width = 2\n\n draw.line((bestMatch.left, bestMatch.top, bestMatch.right(), bestMatch.top), fill=color, width=width) # top\n draw.line((bestMatch.left, bestMatch.bottom(), bestMatch.right(), bestMatch.bottom()), fill=color,\n width=width) # bottom\n draw.line((bestMatch.left, bestMatch.top, bestMatch.left, bestMatch.bottom()), fill=color, width=width) # left\n draw.line((bestMatch.right(), bestMatch.top, bestMatch.right(), bestMatch.bottom()), fill=color,\n width=width) # right\n draw.line((bestMatch.left, bestMatch.top, bestMatch.right() + 1, bestMatch.top), fill=color, width=width) # text bg\n\n x = round((bestMatch.left + bestMatch.right()) / 2)\n y = round((bestMatch.top + bestMatch.bottom()) / 2)\n\n draw.line((x, y, x+1, y+1), fill=color, width=width) # center point\n\n draw.line((bestMatch.left, bestMatch.top + 5, bestMatch.right() + 1, bestMatch.top + 5), fill=color,\n width=14) # top\n\n draw.text((bestMatch.left + 2, bestMatch.top), str(bestMatch.nbVotes) + \" - \" + str(normalizedProbability)[0:7], (255, 255, 255, 192))\n\n out = Image.alpha_composite(image, layer)\n\n out.show()\n\n out = out.convert('RGB')\n out.save(\"../results/result_\" + args.filename)","sub_path":"src/Visualizator.py","file_name":"Visualizator.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"165654906","text":"import os\nimport operator\nimport string\nimport copy\nimport itertools\nimport numpy as np\nimport networkx as nx\nimport scipy.ndimage as nd\nimport image_ops\nfrom from_fits import create_image_from_fits_file\nfrom skimage.morphology import medial_axis\nfrom scipy import nanmean\nimport matplotlib.pyplot as plt\n\n\n# Create 4 to 8-connected elements to use with binary hit-or-miss\nstruct1 = np.array([[1, 0, 0],\n [0, 1, 1],\n [0, 0, 0]])\n\nstruct2 = np.array([[0, 0, 1],\n [1, 1, 0],\n [0, 0, 0]])\n\n# Next check the three elements which will be double counted\ncheck1 = np.array([[1, 1, 0, 0],\n [0, 0, 1, 1]])\n\ncheck2 = np.array([[0, 0, 1, 1],\n [1, 1, 0, 0]])\n\ncheck3 = np.array([[1, 1, 0],\n [0, 0, 1],\n [0, 0, 1]])\n\n\ndef eight_con():\n return np.ones((3, 3))\n\n\ndef _fix_small_holes(mask_array, rel_size=0.1):\n '''\n Helper function to remove only small holes within a masked region.\n\n Parameters\n ----------\n mask_array : numpy.ndarray\n Array containing the masked region.\n\n rel_size : float, optional\n If < 1.0, sets the minimum size a hole must be relative to the area\n of the mask. Otherwise, this is the maximum number of pixels the hole\n must have to be deleted.\n\n Returns\n -------\n mask_array : numpy.ndarray\n Altered array.\n '''\n\n if rel_size <= 0.0:\n raise ValueError(\"rel_size must be positive.\")\n elif rel_size > 1.0:\n pixel_flag = True\n else:\n pixel_flag = False\n\n # Find the region area\n reg_area = len(np.where(mask_array == 1)[0])\n\n # Label the holes\n holes = np.logical_not(mask_array).astype(float)\n lab_holes, n_holes = nd.label(holes, eight_con())\n\n # If no holes, return\n if n_holes == 1:\n return mask_array\n\n # Ignore area outside of the region.\n out_label = lab_holes[0, 0]\n # Set size to be just larger than the region. Thus it can never be\n # deleted.\n holes[np.where(lab_holes == out_label)] = reg_area + 1.\n\n # Sum up the regions and find holes smaller than the threshold.\n sums = nd.sum(holes, lab_holes, range(1, n_holes + 1))\n if pixel_flag: # Use number of pixels\n delete_holes = np.where(sums < rel_size)[0]\n else: # Use relative size of holes.\n delete_holes = np.where(sums / reg_area < rel_size)[0]\n\n # Return if there is nothing to delete.\n if delete_holes == []:\n return mask_array\n\n # Add one to take into account 0 in list if object label 1.\n delete_holes += 1\n for label in delete_holes:\n mask_array[np.where(lab_holes == label)] = 1\n\n return mask_array\n\n\ndef isolateregions(binary_array, size_threshold=0, pad_size=5,\n fill_hole=False, rel_size=0.1, morph_smooth=False):\n '''\n\n Labels regions in a boolean array and returns individual arrays for each\n region. Regions below a threshold can optionlly be removed. Small holes\n may also be filled in.\n\n Parameters\n ----------\n binary_array : numpy.ndarray\n A binary array of regions.\n size_threshold : int, optional\n Sets the pixel size on the size of regions.\n pad_size : int, optional\n Padding to be added to the individual arrays.\n fill_hole : int, optional\n Enables hole filling.\n rel_size : float or int, optional\n If < 1.0, sets the minimum size a hole must be relative to the area\n of the mask. Otherwise, this is the maximum number of pixels the hole\n must have to be deleted.\n morph_smooth : bool, optional\n Morphologically smooth the image using a binar opening and closing.\n\n Returns\n -------\n output_arrays : list\n Regions separated into individual arrays.\n num : int\n Number of filaments\n corners : list\n Contains the indices where each skeleton array was taken from\n the original.\n\n '''\n\n output_arrays = []\n corners = []\n\n # Label skeletons\n labels, num = nd.label(binary_array, eight_con())\n\n # Remove skeletons which have fewer pixels than the threshold.\n if size_threshold != 0:\n sums = nd.sum(binary_array, labels, range(1, num + 1))\n remove_fils = np.where(sums <= size_threshold)[0]\n for lab in remove_fils:\n binary_array[np.where(labels == lab + 1)] = 0\n\n # Relabel after deleting short skeletons.\n labels, num = nd.label(binary_array, eight_con())\n\n # Split each skeleton into its own array.\n for n in range(1, num + 1):\n x, y = np.where(labels == n)\n # Make an array shaped to the skeletons size and padded on each edge\n # the +1 is because, e.g., range(0, 5) only has 5 elements, but the\n # indices we're using are range(0, 6)\n shapes = (x.max() - x.min() + 2 * pad_size,\n y.max() - y.min() + 2 * pad_size)\n eachfil = np.zeros(shapes)\n eachfil[x - x.min() + pad_size, y - y.min() + pad_size] = 1\n # Fill in small holes\n if fill_hole:\n eachfil = _fix_small_holes(eachfil, rel_size=rel_size)\n if morph_smooth:\n eachfil = nd.binary_opening(eachfil, np.ones((3, 3)))\n eachfil = nd.binary_closing(eachfil, np.ones((3, 3)))\n output_arrays.append(eachfil)\n # Keep the coordinates from the original image\n lower = (x.min() - pad_size, y.min() - pad_size)\n upper = (x.max() + pad_size + 1, y.max() + pad_size + 1)\n corners.append([lower, upper])\n\n return output_arrays, num, corners\n\n\ndef shifter(l, n):\n return l[n:] + l[:n]\n\n\ndef distance(x, x1, y, y1):\n return np.sqrt((x - x1) ** 2.0 + (y - y1) ** 2.0)\n\n\ndef find_filpix(branches, labelfil, final=True):\n '''\n\n Identifies the types of pixels in the given skeletons. Identification is\n based on the connectivity of the pixel.\n\n Parameters\n ----------\n branches : list\n Contains the number of branches in each skeleton.\n labelfil : list\n Contains the arrays of each skeleton.\n final : bool, optional\n If true, corner points, intersections, and body points are all\n labeled as a body point for use when the skeletons have already\n been cleaned.\n\n Returns\n -------\n fila_pts : list\n All points on the body of each skeleton.\n inters : list\n All points associated with an intersection in each skeleton.\n labelfil : list\n Contains the arrays of each skeleton where all intersections\n have been removed.\n endpts_return : list\n The end points of each branch of each skeleton.\n '''\n\n initslices = []\n initlist = []\n shiftlist = []\n sublist = []\n endpts = []\n blockpts = []\n bodypts = []\n slices = []\n vallist = []\n shiftvallist = []\n cornerpts = []\n subvallist = []\n subslist = []\n pix = []\n filpix = []\n intertemps = []\n fila_pts = []\n inters = []\n repeat = []\n temp_group = []\n all_pts = []\n pairs = []\n endpts_return = []\n\n for k in range(1, branches + 1):\n x, y = np.where(labelfil == k)\n # pixel_slices = np.empty((len(x)+1,8))\n for i in range(len(x)):\n if x[i] < labelfil.shape[0] - 1 and y[i] < labelfil.shape[1] - 1:\n pix.append((x[i], y[i]))\n initslices.append(np.array([[labelfil[x[i] - 1, y[i] + 1],\n labelfil[x[i], y[i] + 1],\n labelfil[x[i] + 1, y[i] + 1]],\n [labelfil[x[i] - 1, y[i]], 0,\n labelfil[x[i] + 1, y[i]]],\n [labelfil[x[i] - 1, y[i] - 1],\n labelfil[x[i], y[i] - 1],\n labelfil[x[i] + 1, y[i] - 1]]]))\n\n filpix.append(pix)\n slices.append(initslices)\n initslices = []\n pix = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n initlist.append([slices[i][k][0, 0],\n slices[i][k][0, 1],\n slices[i][k][0, 2],\n slices[i][k][1, 2],\n slices[i][k][2, 2],\n slices[i][k][2, 1],\n slices[i][k][2, 0],\n slices[i][k][1, 0]])\n vallist.append(initlist)\n initlist = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n shiftlist.append(shifter(vallist[i][k], 1))\n shiftvallist.append(shiftlist)\n shiftlist = []\n\n for k in range(len(slices)):\n for i in range(len(vallist[k])):\n for j in range(8):\n sublist.append(\n int(vallist[k][i][j]) - int(shiftvallist[k][i][j]))\n subslist.append(sublist)\n sublist = []\n subvallist.append(subslist)\n subslist = []\n\n # x represents the subtracted list (step-ups) and y is the values of the\n # surrounding pixels. The categories of pixels are ENDPTS (x<=1),\n # BODYPTS (x=2,y=2),CORNERPTS (x=2,y=3),BLOCKPTS (x=3,y>=4), and\n # INTERPTS (x>=3).\n # A cornerpt is [*,0,0] (*s) associated with an intersection,\n # but their exclusion from\n # [1,*,0] the intersection keeps eight-connectivity, they are included\n # [0,1,0] intersections for this reason.\n # A blockpt is [1,0,1] They are typically found in a group of four,\n # where all four\n # [0,*,*] constitute a single intersection.\n # [1,*,*]\n # The \"final\" designation is used when finding the final branch lengths.\n # At this point, blockpts and cornerpts should be eliminated.\n for k in range(branches):\n for l in range(len(filpix[k])):\n x = [j for j, y in enumerate(subvallist[k][l]) if y == k + 1]\n y = [j for j, z in enumerate(vallist[k][l]) if z == k + 1]\n\n if len(x) <= 1:\n endpts.append(filpix[k][l])\n endpts_return.append(filpix[k][l])\n elif len(x) == 2:\n if final:\n bodypts.append(filpix[k][l])\n else:\n if len(y) == 2:\n bodypts.append(filpix[k][l])\n elif len(y) == 3:\n cornerpts.append(filpix[k][l])\n elif len(y) >= 4:\n blockpts.append(filpix[k][l])\n elif len(x) >= 3:\n intertemps.append(filpix[k][l])\n endpts = list(set(endpts))\n bodypts = list(set(bodypts))\n dups = set(endpts) & set(bodypts)\n if len(dups) > 0:\n for i in dups:\n bodypts.remove(i)\n # Cornerpts without a partner diagonally attached can be included as a\n # bodypt.\n if len(cornerpts) > 0:\n deleted_cornerpts = []\n for i, j in zip(cornerpts, cornerpts):\n if i != j:\n if distance(i[0], j[0], i[1], j[1]) == np.sqrt(2.0):\n proximity = [(i[0], i[1] - 1),\n (i[0], i[1] + 1),\n (i[0] - 1, i[1]),\n (i[0] + 1, i[1]),\n (i[0] - 1, i[1] + 1),\n (i[0] + 1, i[1] + 1),\n (i[0] - 1, i[1] - 1),\n (i[0] + 1, i[1] - 1)]\n match = set(intertemps) & set(proximity)\n if len(match) == 1:\n pairs.append([i, j])\n deleted_cornerpts.append(i)\n deleted_cornerpts.append(j)\n cornerpts = list(set(cornerpts).difference(set(deleted_cornerpts)))\n\n if len(cornerpts) > 0:\n for l in cornerpts:\n proximity = [(l[0], l[1] - 1),\n (l[0], l[1] + 1),\n (l[0] - 1, l[1]),\n (l[0] + 1, l[1]),\n (l[0] - 1, l[1] + 1),\n (l[0] + 1, l[1] + 1),\n (l[0] - 1, l[1] - 1),\n (l[0] + 1, l[1] - 1)]\n match = set(intertemps) & set(proximity)\n if len(match) == 1:\n intertemps.append(l)\n fila_pts.append(endpts + bodypts)\n else:\n fila_pts.append(endpts + bodypts + [l])\n # cornerpts.remove(l)\n else:\n fila_pts.append(endpts + bodypts)\n\n # Reset lists\n cornerpts = []\n endpts = []\n bodypts = []\n\n if len(pairs) > 0:\n for i in range(len(pairs)):\n for j in pairs[i]:\n all_pts.append(j)\n if len(blockpts) > 0:\n for i in blockpts:\n all_pts.append(i)\n if len(intertemps) > 0:\n for i in intertemps:\n all_pts.append(i)\n # Pairs of cornerpts, blockpts, and interpts are combined into an\n # array. If there is eight connectivity between them, they are labelled\n # as a single intersection.\n arr = np.zeros((labelfil.shape))\n for z in all_pts:\n labelfil[z[0], z[1]] = 0\n arr[z[0], z[1]] = 1\n lab, nums = nd.label(arr, eight_con())\n for k in range(1, nums + 1):\n objs_pix = np.where(lab == k)\n for l in range(len(objs_pix[0])):\n temp_group.append((objs_pix[0][l], objs_pix[1][l]))\n inters.append(temp_group)\n temp_group = []\n for i in range(len(inters) - 1):\n if inters[i] == inters[i + 1]:\n repeat.append(inters[i])\n for i in repeat:\n inters.remove(i)\n\n return fila_pts, inters, labelfil, endpts_return\n\n\ndef pix_identify(isolatefilarr, num):\n '''\n This function is essentially a wrapper on find_filpix. It returns the\n outputs of find_filpix in the form that are used during the analysis.\n\n Parameters\n ----------\n isolatefilarr : list\n Contains individual arrays of each skeleton.\n num : int\n The number of skeletons.\n\n Returns\n -------\n interpts : list\n Contains lists of all intersections points in each skeleton.\n hubs : list\n Contains the number of intersections in each filament. This is\n useful for identifying those with no intersections as their analysis\n is straight-forward.\n ends : list\n Contains the positions of all end points in each skeleton.\n filbranches : list\n Contains the number of branches in each skeleton.\n labelisofil : list\n Contains individual arrays for each skeleton where the\n branches are labeled and the intersections have been removed.\n '''\n\n interpts = []\n hubs = []\n ends = []\n filbranches = []\n labelisofil = []\n\n for n in range(num):\n funcreturn = find_filpix(1, isolatefilarr[n], final=False)\n interpts.append(funcreturn[1])\n hubs.append(len(funcreturn[1]))\n isolatefilarr.pop(n)\n isolatefilarr.insert(n, funcreturn[2])\n ends.append(funcreturn[3])\n\n label_branch, num_branch = nd.label(isolatefilarr[n], eight_con())\n filbranches.append(num_branch)\n labelisofil.append(label_branch)\n\n return interpts, hubs, ends, filbranches, labelisofil\n\n\ndef skeleton_length(skeleton):\n '''\n Length finding via morphological operators. We use the differences in\n connectivity between 4 and 8-connected to split regions. Connections\n between 4 and 8-connected regions are found using a series of hit-miss\n operators.\n\n The inputted skeleton MUST have no intersections otherwise the returned\n length will not be correct!\n\n Parameters\n ----------\n skeleton : numpy.ndarray\n Array containing the skeleton.\n\n Returns\n -------\n length : float\n Length of the skeleton.\n\n '''\n\n # 4-connected labels\n four_labels = nd.label(skeleton)[0]\n\n four_sizes = nd.sum(skeleton, four_labels, range(np.max(four_labels) + 1))\n\n # Lengths is the number of pixels minus number of objects with more\n # than 1 pixel.\n four_length = np.sum(\n four_sizes[four_sizes > 1]) - len(four_sizes[four_sizes > 1])\n\n # Find pixels which a 4-connected and subtract them off the skeleton\n\n four_objects = np.where(four_sizes > 1)[0]\n\n skel_copy = copy.copy(skeleton)\n for val in four_objects:\n skel_copy[np.where(four_labels == val)] = 0\n\n # Remaining pixels are only 8-connected\n # Lengths is same as before, multiplied by sqrt(2)\n\n eight_labels = nd.label(skel_copy, eight_con())[0]\n\n eight_sizes = nd.sum(\n skel_copy, eight_labels, range(np.max(eight_labels) + 1))\n\n eight_length = (\n np.sum(eight_sizes) - np.max(eight_labels)) * np.sqrt(2)\n\n # If there are no 4-connected pixels, we don't need the hit-miss portion.\n if four_length == 0.0:\n conn_length = 0.0\n\n else:\n\n store = np.zeros(skeleton.shape)\n\n # Loop through the 4 rotations of the structuring elements\n for k in range(0, 4):\n hm1 = nd.binary_hit_or_miss(\n skeleton, structure1=np.rot90(struct1, k=k))\n store += hm1\n\n hm2 = nd.binary_hit_or_miss(\n skeleton, structure1=np.rot90(struct2, k=k))\n store += hm2\n\n hm_check3 = nd.binary_hit_or_miss(\n skeleton, structure1=np.rot90(check3, k=k))\n store -= hm_check3\n\n if k <= 1:\n hm_check1 = nd.binary_hit_or_miss(\n skeleton, structure1=np.rot90(check1, k=k))\n store -= hm_check1\n\n hm_check2 = nd.binary_hit_or_miss(\n skeleton, structure1=np.rot90(check2, k=k))\n store -= hm_check2\n\n conn_length = np.sqrt(2) * \\\n np.sum(np.sum(store, axis=1), axis=0) # hits\n\n return conn_length + eight_length + four_length\n\n\ndef init_lengths(labelisofil, filbranches, array_offsets, img):\n '''\n\n This is a wrapper on fil_length for running on the branches of the\n skeletons.\n\n Parameters\n ----------\n\n labelisofil : list\n Contains individual arrays for each skeleton where the\n branches are labeled and the intersections have been removed.\n\n filbranches : list\n Contains the number of branches in each skeleton.\n\n array_offsets : List\n The indices of where each filament array fits in the\n original image.\n\n img : numpy.ndarray\n Original image.\n\n Returns\n -------\n\n branch_properties: dict\n Contains the lengths and intensities of the branches.\n Keys are *length* and *intensity*.\n\n '''\n num = len(labelisofil)\n\n # Initialize Lists\n lengths = []\n av_branch_intensity = []\n\n for n in range(num):\n leng = []\n av_intensity = []\n\n label_copy = copy.copy(labelisofil[n])\n objects = nd.find_objects(label_copy)\n for obj in objects:\n # Scale the branch array to the branch size\n branch_array = label_copy[obj]\n\n # Find the skeleton points and set those to 1\n branch_pts = np.where(branch_array > 0)\n branch_array[branch_pts] = 1\n\n # Now find the length on the branch\n branch_length = skeleton_length(branch_array)\n if branch_length == 0.0:\n # For use in longest path algorithm, will be set to zero for\n # final analysis\n branch_length = 0.5\n\n leng.append(branch_length)\n\n # Now let's find the average intensity along each branch\n # Get the offsets from the original array and\n # add on the offset the branch array introduces.\n x_offset = obj[0].start + array_offsets[n][0][0]\n y_offset = obj[1].start + array_offsets[n][0][1]\n av_intensity.append(\n nanmean([img[x + x_offset, y + y_offset]\n for x, y in zip(*branch_pts)\n if np.isfinite(img[x + x_offset, y + y_offset]) and\n not img[x + x_offset, y + y_offset] < 0.0]))\n\n lengths.append(leng)\n av_branch_intensity.append(av_intensity)\n\n branch_properties = {\n \"length\": lengths, \"intensity\": av_branch_intensity}\n\n return branch_properties\n\n\ndef product_gen(n):\n for r in itertools.count(1):\n for i in itertools.product(n, repeat=r):\n yield \"\".join(i)\n\n\ndef pre_graph(labelisofil, branch_properties, interpts, ends):\n '''\n\n This function converts the skeletons into a graph object compatible with\n networkx. The graphs have nodes corresponding to end and\n intersection points and edges defining the connectivity as the branches\n with the weights set to the branch length.\n\n Parameters\n ----------\n\n labelisofil : list\n Contains individual arrays for each skeleton where the\n branches are labeled and the intersections have been removed.\n\n branch_properties : dict\n Contains the lengths and intensities of all branches.\n\n interpts : list\n Contains the pixels which belong to each intersection.\n\n ends : list\n Contains the end pixels for each skeleton.\n\n Returns\n -------\n\n end_nodes : list\n Contains the nodes corresponding to end points.\n\n inter_nodes : list\n Contains the nodes corresponding to intersection points.\n\n edge_list : list\n Contains the connectivity information for the graphs.\n\n nodes : list\n A complete list of all of the nodes. The other nodes lists have\n been separated as they are labeled differently.\n\n '''\n\n num = len(labelisofil)\n\n end_nodes = []\n inter_nodes = []\n nodes = []\n edge_list = []\n\n def path_weighting(idx, length, intensity, w=0.5):\n '''\n\n Relative weighting for the shortest path algorithm using the branch\n lengths and the average intensity along the branch.\n\n '''\n if w > 1.0 or w < 0.0:\n raise ValueError(\n \"Relative weighting w must be between 0.0 and 1.0.\")\n return (1 - w) * (length[idx] / np.sum(length)) + \\\n w * (intensity[idx] / np.sum(intensity))\n\n lengths = branch_properties[\"length\"]\n branch_intensity = branch_properties[\"intensity\"]\n\n for n in range(num):\n inter_nodes_temp = []\n # Create end_nodes, which contains lengths, and nodes, which we will\n # later add in the intersections\n end_nodes.append([(labelisofil[n][i[0], i[1]],\n path_weighting(int(labelisofil[n][i[0], i[1]] - 1),\n lengths[n],\n branch_intensity[n]),\n lengths[n][int(labelisofil[n][i[0], i[1]] - 1)],\n branch_intensity[n][int(labelisofil[n][i[0], i[1]] - 1)])\n for i in ends[n]])\n nodes.append([labelisofil[n][i[0], i[1]] for i in ends[n]])\n\n # Intersection nodes are given by the intersections points of the filament.\n # They are labeled alphabetically (if len(interpts[n])>26,\n # subsequent labels are AA,AB,...).\n # The branch labels attached to each intersection are included for future\n # use.\n for intersec in interpts[n]:\n uniqs = []\n for i in intersec: # Intersections can contain multiple pixels\n int_arr = np.array([[labelisofil[n][i[0] - 1, i[1] + 1],\n labelisofil[n][i[0], i[1] + 1],\n labelisofil[n][i[0] + 1, i[1] + 1]],\n [labelisofil[n][i[0] - 1, i[1]], 0,\n labelisofil[n][i[0] + 1, i[1]]],\n [labelisofil[n][i[0] - 1, i[1] - 1],\n labelisofil[n][i[0], i[1] - 1],\n labelisofil[n][i[0] + 1, i[1] - 1]]]).astype(int)\n for x in np.unique(int_arr[np.nonzero(int_arr)]):\n uniqs.append((x,\n path_weighting(x - 1, lengths[n],\n branch_intensity[n]),\n lengths[n][x - 1],\n branch_intensity[n][x - 1]))\n # Intersections with multiple pixels can give the same branches.\n # Get rid of duplicates\n uniqs = list(set(uniqs))\n inter_nodes_temp.append(uniqs)\n\n # Add the intersection labels. Also append those to nodes\n inter_nodes.append(\n zip(product_gen(string.ascii_uppercase), inter_nodes_temp))\n for alpha, node in zip(product_gen(string.ascii_uppercase),\n inter_nodes_temp):\n nodes[n].append(alpha)\n # Edges are created from the information contained in the nodes.\n edge_list_temp = []\n for i, inters in enumerate(inter_nodes[n]):\n end_match = list(set(inters[1]) & set(end_nodes[n]))\n for k in end_match:\n edge_list_temp.append((inters[0], k[0], k))\n\n for j, inters_2 in enumerate(inter_nodes[n]):\n if i != j:\n match = list(set(inters[1]) & set(inters_2[1]))\n new_edge = None\n if len(match) == 1:\n new_edge = (inters[0], inters_2[0], match[0])\n elif len(match) > 1:\n multi = [match[l][1] for l in range(len(match))]\n keep = multi.index(min(multi))\n new_edge = (inters[0], inters_2[0], match[keep])\n if new_edge is not None:\n if not (new_edge[1], new_edge[0], new_edge[2]) in edge_list_temp \\\n and new_edge not in edge_list_temp:\n edge_list_temp.append(new_edge)\n\n # Remove duplicated edges between intersections\n\n edge_list.append(edge_list_temp)\n\n return edge_list, nodes\n\n\ndef try_mkdir(name):\n '''\n Checks if a folder exists, and makes it if it doesn't\n '''\n\n if not os.path.isdir(os.path.join(os.getcwd(), name)):\n os.mkdir(os.path.join(os.getcwd(), name))\n\n\ndef longest_path(edge_list, nodes, verbose=False,\n skeleton_arrays=None, save_png=False, save_name=None):\n '''\n Takes the output of pre_graph and runs the shortest path algorithm.\n\n Parameters\n ----------\n\n edge_list : list\n Contains the connectivity information for the graphs.\n\n nodes : list\n A complete list of all of the nodes. The other nodes lists have\n been separated as they are labeled differently.\n\n verbose : bool, optional\n If True, enables the plotting of the graph.\n\n skeleton_arrays : list, optional\n List of the skeleton arrays. Required when verbose=True.\n\n save_png : bool, optional\n Saves the plot made in verbose mode. Disabled by default.\n\n save_name : str, optional\n For use when ``save_png`` is enabled.\n **MUST be specified when ``save_png`` is enabled.**\n\n Returns\n -------\n\n max_path : list\n Contains the paths corresponding to the longest lengths for\n each skeleton.\n\n extremum : list\n Contains the starting and ending points of max_path\n\n '''\n num = len(nodes)\n\n # Initialize lists\n max_path = []\n extremum = []\n graphs = []\n\n for n in range(num):\n G = nx.Graph()\n G.add_nodes_from(nodes[n])\n for i in edge_list[n]:\n G.add_edge(i[0], i[1], weight=i[2][1])\n paths = nx.shortest_path_length(G, weight='weight')\n values = []\n node_extrema = []\n for i in paths.keys():\n j = max(paths[i].items(), key=operator.itemgetter(1))\n node_extrema.append((j[0], i))\n values.append(j[1])\n start, finish = node_extrema[values.index(max(values))]\n extremum.append([start, finish])\n max_path.append(nx.shortest_path(G, start, finish))\n graphs.append(G)\n\n if verbose or save_png:\n if not skeleton_arrays:\n Warning(\"Must input skeleton arrays if verbose or save_png is\"\n \" enabled. No plots will be created.\")\n elif save_png and save_name is None:\n Warning(\"Must give a save_name when save_png is enabled. No\"\n \" plots will be created.\")\n else:\n # Check if skeleton_arrays is a list\n assert isinstance(skeleton_arrays, list)\n import matplotlib.pyplot as p\n if verbose:\n print(\"Filament: %s / %s\" % (n + 1, num))\n p.subplot(1, 2, 1)\n p.imshow(skeleton_arrays[n], interpolation=\"nearest\",\n origin=\"lower\")\n\n p.subplot(1, 2, 2)\n elist = [(u, v) for (u, v, d) in G.edges(data=True)]\n pos = nx.spring_layout(G)\n nx.draw_networkx_nodes(G, pos, node_size=200)\n nx.draw_networkx_edges(G, pos, edgelist=elist, width=2)\n nx.draw_networkx_labels(\n G, pos, font_size=10, font_family='sans-serif')\n p.axis('off')\n\n if save_png:\n try_mkdir(save_name)\n p.savefig(os.path.join(save_name,\n save_name + \"_longest_path_\" + str(n) + \".png\"))\n if verbose:\n p.show()\n p.clf()\n\n return max_path, extremum, graphs\n\n\ndef prune_graph(G, nodes, edge_list, max_path, labelisofil, branch_properties,\n length_thresh, relintens_thresh=0.2):\n '''\n Function to remove unnecessary branches, while maintaining connectivity\n in the graph. Also updates edge_list, nodes, branch_lengths and\n filbranches.\n\n Parameters\n ----------\n G : list\n Contains the networkx Graph objects.\n nodes : list\n A complete list of all of the nodes. The other nodes lists have\n been separated as they are labeled differently.\n edge_list : list\n Contains the connectivity information for the graphs.\n max_path : list\n Contains the paths corresponding to the longest lengths for\n each skeleton.\n labelisofil : list\n Contains individual arrays for each skeleton where the\n branches are labeled and the intersections have been removed.\n branch_properties : dict\n Contains the lengths and intensities of all branches.\n length_thresh : int or float\n Minimum length a branch must be to be kept. Can be overridden if the\n branch is bright relative to the entire skeleton.\n relintens_thresh : float between 0 and 1, optional.\n Threshold for how bright the branch must be relative to the entire\n skeleton. Can be overridden by length.\n\n Returns\n -------\n labelisofil : list\n Updated from input.\n edge_list : list\n Updated from input.\n nodes : list\n Updated from input.\n branch_properties : dict\n Updated from input.\n '''\n\n num = len(labelisofil)\n\n for n in range(num):\n degree = G[n].degree()\n single_connect = [key for key in degree.keys() if degree[key] == 1]\n\n delete_candidate = list(\n (set(nodes[n]) - set(max_path[n])) & set(single_connect))\n\n if not delete_candidate: # Nothing to delete!\n continue\n\n edge_candidates = [edge for edge in edge_list[n] if edge[\n 0] in delete_candidate or edge[1] in delete_candidate]\n intensities = [edge[2][3] for edge in edge_list[n]]\n for edge in edge_candidates:\n # In the odd case where a loop meets at the same intersection,\n # ensure that edge is kept.\n if isinstance(edge[0], str) & isinstance(edge[1], str):\n continue\n # If its too short and relatively not as intense, delete it\n length = edge[2][2]\n av_intensity = edge[2][3]\n if length < length_thresh \\\n and (av_intensity / np.sum(intensities)) < relintens_thresh:\n edge_pts = np.where(labelisofil[n] == edge[2][0])\n labelisofil[n][edge_pts] = 0\n edge_list[n].remove(edge)\n nodes[n].remove(edge[1])\n branch_properties[\"length\"][n].remove(length)\n branch_properties[\"intensity\"][n].remove(av_intensity)\n branch_properties[\"number\"][n] -= 1\n\n return labelisofil, edge_list, nodes, branch_properties\n\n\ndef extremum_pts(labelisofil, extremum, ends):\n '''\n This function returns the the farthest extents of each filament. This\n is useful for determining how well the shortest path algorithm has worked.\n\n Parameters\n ----------\n labelisofil : list\n Contains individual arrays for each skeleton.\n extremum : list\n Contains the extents as determined by the shortest\n path algorithm.\n ends : list\n Contains the positions of each end point in eahch filament.\n\n Returns\n -------\n extrem_pts : list\n Contains the indices of the extremum points.\n '''\n\n num = len(labelisofil)\n extrem_pts = []\n\n for n in range(num):\n per_fil = []\n for i, j in ends[n]:\n if labelisofil[n][i, j] == extremum[n][0] or labelisofil[n][i, j] == extremum[n][1]:\n per_fil.append([i, j])\n extrem_pts.append(per_fil)\n\n return extrem_pts\n\n\ndef main_length(max_path, edge_list, labelisofil, interpts, branch_lengths,\n img_scale, verbose=False, save_png=False, save_name=None):\n '''\n Wraps previous functionality together for all of the skeletons in the\n image. To find the overall length for each skeleton, intersections are\n added back in, and any extraneous pixels they bring with them are deleted.\n\n Parameters\n ----------\n max_path : list\n Contains the paths corresponding to the longest lengths for\n each skeleton.\n edge_list : list\n Contains the connectivity information for the graphs.\n labelisofil : list\n Contains individual arrays for each skeleton where the\n branches are labeled and the intersections have been removed.\n interpts : list\n Contains the pixels which belong to each intersection.\n branch_lengths : list\n Lengths of individual branches in each skeleton.\n img_scale : float\n Conversion from pixel to physical units.\n verbose : bool, optional\n Returns plots of the longest path skeletons.\n save_png : bool, optional\n Saves the plot made in verbose mode. Disabled by default.\n save_name : str, optional\n For use when ``save_png`` is enabled.\n **MUST be specified when ``save_png`` is enabled.**\n\n Returns\n -------\n main_lengths : list\n Lengths of the skeletons.\n longpath_arrays : list\n Arrays of the longest paths in the skeletons.\n '''\n\n main_lengths = []\n longpath_arrays = []\n\n for num, (path, edges, inters, skel_arr, lengths) in \\\n enumerate(zip(max_path, edge_list, interpts, labelisofil,\n branch_lengths)):\n\n if len(path) == 1:\n main_lengths.append(lengths[0] * img_scale)\n skeleton = skel_arr # for viewing purposes when verbose\n else:\n skeleton = np.zeros(skel_arr.shape)\n\n # Add edges along longest path\n good_edge_list = [(path[i], path[i + 1])\n for i in range(len(path) - 1)]\n # Find the branches along the longest path.\n for i in good_edge_list:\n for j in edges:\n if (i[0] == j[0] and i[1] == j[1]) or \\\n (i[0] == j[1] and i[1] == j[0]):\n label = j[2][0]\n skeleton[np.where(skel_arr == label)] = 1\n\n # Add intersections along longest path\n intersec_pts = []\n for label in path:\n try:\n label = int(label)\n except ValueError:\n pass\n if not isinstance(label, int):\n k = 1\n while zip(product_gen(string.ascii_uppercase),\n [1] * k)[-1][0] != label:\n k += 1\n intersec_pts.extend(inters[k - 1])\n skeleton[zip(*inters[k - 1])] = 2\n\n # Remove unnecessary pixels\n count = 0\n while True:\n for pt in intersec_pts:\n # If we have already eliminated the point, continue\n if skeleton[pt] == 0:\n continue\n skeleton[pt] = 0\n lab_try, n = nd.label(skeleton, eight_con())\n if n > 1:\n skeleton[pt] = 1\n else:\n count += 1\n if count == 0:\n break\n count = 0\n\n main_lengths.append(skeleton_length(skeleton) * img_scale)\n\n longpath_arrays.append(skeleton.astype(int))\n\n if verbose or save_png:\n if save_png and save_name is None:\n Warning(\"Must give a save_name when save_png is enabled. No\"\n \" plots will be created.\")\n import matplotlib.pyplot as p\n if verbose:\n print(\"Filament: %s / %s\" % (num + 1, len(labelisofil)))\n\n p.subplot(121)\n p.imshow(skeleton, origin='lower', interpolation=\"nearest\")\n p.subplot(122)\n p.imshow(labelisofil[num], origin='lower',\n interpolation=\"nearest\")\n\n if save_png:\n try_mkdir(save_name)\n p.savefig(os.path.join(save_name,\n save_name + \"_main_length_\" + str(num) + \".png\"))\n if verbose:\n p.show()\n p.clf()\n\n return main_lengths, longpath_arrays\n\n\ndef find_extran(branches, labelfil):\n '''\n Identify pixels that are not necessary to keep the connectivity of the\n skeleton. It uses the same labeling process as find_filpix. Extraneous\n pixels tend to be those from former intersections, whose attached branch\n was eliminated in the cleaning process.\n\n Parameters\n ----------\n branches : list\n Contains the number of branches in each skeleton.\n labelfil : list\n Contains arrays of the labeled versions of each skeleton.\n\n Returns\n -------\n labelfil : list\n Contains the updated labeled arrays with extraneous pieces\n removed.\n '''\n\n initslices = []\n initlist = []\n shiftlist = []\n sublist = []\n extran = []\n slices = []\n vallist = []\n shiftvallist = []\n subvallist = []\n subslist = []\n pix = []\n filpix = []\n\n for k in range(1, branches + 1):\n x, y = np.where(labelfil == k)\n for i in range(len(x)):\n if x[i] < labelfil.shape[0] - 1 and y[i] < labelfil.shape[1] - 1:\n pix.append((x[i], y[i]))\n initslices.append(np.array([[labelfil[x[i] - 1, y[i] + 1],\n labelfil[x[i], y[i] + 1],\n labelfil[x[i] + 1, y[i] + 1]],\n [labelfil[x[i] - 1, y[i]], 0,\n labelfil[x[i] + 1, y[i]]],\n [labelfil[x[i] - 1, y[i] - 1],\n labelfil[x[i], y[i] - 1],\n labelfil[x[i] + 1, y[i] - 1]]]))\n\n filpix.append(pix)\n slices.append(initslices)\n initslices = []\n pix = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n initlist.append([slices[i][k][0, 0],\n slices[i][k][0, 1],\n slices[i][k][0, 2],\n slices[i][k][1, 2],\n slices[i][k][2, 2],\n slices[i][k][2, 1],\n slices[i][k][2, 0],\n slices[i][k][1, 0]])\n vallist.append(initlist)\n initlist = []\n\n for i in range(len(slices)):\n for k in range(len(slices[i])):\n shiftlist.append(shifter(vallist[i][k], 1))\n shiftvallist.append(shiftlist)\n shiftlist = []\n\n for k in range(len(slices)):\n for i in range(len(vallist[k])):\n for j in range(8):\n sublist.append(\n int(vallist[k][i][j]) - int(shiftvallist[k][i][j]))\n subslist.append(sublist)\n sublist = []\n subvallist.append(subslist)\n subslist = []\n\n for k in range(len(slices)):\n for l in range(len(filpix[k])):\n x = [j for j, y in enumerate(subvallist[k][l]) if y == k + 1]\n y = [j for j, z in enumerate(vallist[k][l]) if z == k + 1]\n if len(x) == 0:\n labelfil[filpix[k][l][0], filpix[k][l][1]] = 0\n if len(x) == 1:\n if len(y) >= 2:\n extran.append(filpix[k][l])\n labelfil[filpix[k][l][0], filpix[k][l][1]] = 0\n # if len(extran) >= 2:\n # for i in extran:\n # for j in extran:\n # if i != j:\n # if distance(i[0], j[0], i[1], j[1]) == np.sqrt(2.0):\n # proximity = [(i[0], i[1] - 1),\n # (i[0], i[1] + 1),\n # (i[0] - 1, i[1]),\n # (i[0] + 1, i[1]),\n # (i[0] - 1, i[1] + 1),\n # (i[0] + 1, i[1] + 1),\n # (i[0] - 1, i[1] - 1),\n # (i[0] + 1, i[1] - 1)]\n # match = set(filpix[k]) & set(proximity)\n # if len(match) > 0:\n # for z in match:\n # labelfil[z[0], z[1]] = 0\n return labelfil\n\n\ndef in_ipynb():\n try:\n cfg = get_ipython().config\n if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':\n return True\n else:\n return False\n except NameError:\n return False\n\n\ndef make_final_skeletons(labelisofil, inters, verbose=False, save_png=False,\n save_name=None):\n '''\n Creates the final skeletons outputted by the algorithm.\n\n Parameters\n ----------\n labelisofil : list\n List of labeled skeletons.\n inters : list\n Positions of the intersections in each skeleton.\n verbose : bool, optional\n Enables plotting of the final skeleton.\n save_png : bool, optional\n Saves the plot made in verbose mode. Disabled by default.\n save_name : str, optional\n For use when ``save_png`` is enabled.\n **MUST be specified when ``save_png`` is enabled.**\n\n Returns\n -------\n filament_arrays : list\n List of the final skeletons.\n '''\n\n filament_arrays = []\n\n for n, (skel_array, intersec) in enumerate(zip(labelisofil, inters)):\n copy_array = np.zeros(skel_array.shape, dtype=int)\n\n for inter in intersec:\n for pts in inter:\n x, y = pts\n copy_array[x, y] = 1\n\n copy_array[np.where(skel_array >= 1)] = 1\n\n cleaned_array = find_extran(1, copy_array)\n\n filament_arrays.append(cleaned_array)\n\n if verbose or save_png:\n if save_png and save_name is None:\n Warning(\"Must give a save_name when save_png is enabled. No\"\n \" plots will be created.\")\n\n plt.clf()\n plt.imshow(cleaned_array, origin='lower', interpolation='nearest')\n\n if save_png:\n try_mkdir(save_name)\n plt.savefig(os.path.join(save_name,\n save_name+\"_final_skeleton_\"+str(n)+\".png\"))\n if verbose:\n plt.show()\n if in_ipynb():\n plt.clf()\n\n return filament_arrays\n\n\ndef recombine_skeletons(skeletons, offsets, orig_size, pad_size,\n verbose=False):\n '''\n Takes a list of skeleton arrays and combines them back into\n the original array.\n\n Parameters\n ----------\n skeletons : list\n Arrays of each skeleton.\n offsets : list\n Coordinates where the skeleton arrays have been sliced from the\n image.\n orig_size : tuple\n Size of the image.\n pad_size : int\n Size of the array padding.\n verbose : bool, optional\n Enables printing when a skeleton array needs to be resized to fit\n into the image.\n\n Returns\n -------\n master_array : numpy.ndarray\n Contains all skeletons placed in their original positions in the image.\n '''\n\n num = len(skeletons)\n\n master_array = np.zeros(orig_size)\n for n in range(num):\n x_off, y_off = offsets[n][0] # These are the coordinates of the bottom\n # left in the master array.\n x_top, y_top = offsets[n][1]\n\n # Now check if padding will put the array outside of the original array\n # size\n excess_x_top = x_top - orig_size[0]\n\n excess_y_top = y_top - orig_size[1]\n\n copy_skeleton = copy.copy(skeletons[n])\n\n size_change_flag = False\n\n if excess_x_top > 0:\n copy_skeleton = copy_skeleton[:-excess_x_top, :]\n size_change_flag = True\n\n if excess_y_top > 0:\n copy_skeleton = copy_skeleton[:, :-excess_y_top]\n size_change_flag = True\n\n if x_off < 0:\n copy_skeleton = copy_skeleton[-x_off:, :]\n x_off = 0\n size_change_flag = True\n\n if y_off < 0:\n copy_skeleton = copy_skeleton[:, -y_off:]\n y_off = 0\n size_change_flag = True\n\n if verbose & size_change_flag:\n print(\"REDUCED FILAMENT %s/%s TO FIT IN ORIGINAL ARRAY\" % (n, num))\n\n x, y = np.where(copy_skeleton >= 1)\n for i in range(len(x)):\n master_array[x[i] + x_off, y[i] + y_off] = 1\n\n return master_array\n","sub_path":"vlbi_errors/skel_utils.py","file_name":"skel_utils.py","file_ext":"py","file_size_in_byte":47419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"273898113","text":"import os\nimport pygame\nimport random\npygame.init()\nwhite = (255,255,255)\nblack = (0,0,0)\nred = (255,0,0)\ngreen = (0,155,0)\nbrown = (205,133,63)\nblue = (135,206,250)\nFPS = 60\n#the dimension of the game\ndisplay_width = 680\ndisplay_height = 440\n# Class for the player\nclass Player(object):\n def __init__(self):\n self.rect = pygame.Rect(40, 40, 30, 30)\n def move(self, dx, dy):\n # Move each axis separately. Note that this checks for collisions both times.\n if dx != 0:\n self.move_single_axis(dx, 0)\n if dy != 0:\n self.move_single_axis(0, dy)\n def move_single_axis(self, dx, dy):\n # Move the rect\n self.rect.x += dx\n self.rect.y += dy\n # If you collide with a wall, move out based on velocity\n for wall in walls:\n if self.rect.colliderect(wall.rect):\n if dx > 0: # Moving right, Hit the left side of the wall\n self.rect.right = wall.rect.left\n if dx < 0: # Moving left, Hit the right side of the wall\n self.rect.left = wall.rect.right\n if dy > 0: # Moving down, Hit the top side of the wall\n self.rect.bottom = wall.rect.top\n if dy < 0: # Moving up, Hit the bottom side of the wall\n self.rect.top = wall.rect.bottom\n# Class to hold a wall rect\nclass Wall(object):\n def __init__(self, pos):\n walls.append(self)\n self.rect = pygame.Rect(pos[0], pos[1], 40, 40)\nfont = pygame.font.SysFont(None, 50)\ndef message_to_screen(msg,color):\n screen_text = font.render(msg, True, color)\n gameDisplay.blit(screen_text, [680/2, display_height/2])\n# Initialise pygame\nos.environ[\"Time to play\"] = \"1\"\n# Set up the display\npygame.display.set_caption(\"Wrath of the gods\")\ngameDisplay = pygame.display.set_mode((display_width,display_height))\nclock = pygame.time.Clock()\nwalls = [] # List to hold the walls\nplayer = None\nend_rect = None\ndef reinit():\n global player, end_rect\n player = Player() # Create the player\n # Holds the level layout in a list of strings.\n level = [\n \"WWWWWWWWWWWWWWWWW\",\n \"W W W W\",\n \"W WW W WW WWW W\",\n \"W W W W W W W W\",\n \"W WWWWW WWW W W W\",\n \"W W W W W W\",\n \"WW W WW WWWWWWW W\",\n \"W W W W\",\n \"W WWWW W WW W WW\",\n \"W W\",\n \"W WW W WW WWW W\",\n \"W W W W W W W W\",\n \"W WWWWW WWW W W W\",\n \"W W W W W W\",\n \"WW W WW WWWWWWW W\",\n \"W W W W\",\n \"W WWWW W WW W WW\",\n \"W W\",\n \"W WW W WW WWW W\",\n \"W W W W W W W W\",\n \"W WWWWW WWW W W W\",\n \"W W W W W W\",\n \"WW W WW WWWWWWW W\",\n \"W W W W\",\n \"W WWWW W WW W WW\",\n \"W W\",\n \"WWWWWWWWWWWWWWWEW\",\n ]\n # W = wall, E = exit\n x = y = 0\n for row in level:\n for col in row:\n if col == \"W\":\n Wall((x, y))\n if col == \"E\":\n end_rect = pygame.Rect(x, y, 40, 40)\n x += 40\n y += 40\n x = 0\nreinit()\nbigfont = pygame.font.Font(None, 80)\nsmallfont = pygame.font.Font(None, 45)\ndef play_again():\n SCREEN_WIDTH = display_width\n SCREEN_HEIGHT = display_height\n screen = gameDisplay\n text = bigfont.render('Play again?', 13, (0, 0, 0))\n textx = SCREEN_WIDTH / 2 - text.get_width() / 2\n texty = SCREEN_HEIGHT / 2 - text.get_height() / 2\n textx_size = text.get_width()\n texty_size = text.get_height()\n pygame.draw.rect(screen, (255, 255, 255), ((textx - 5, texty - 5),\n (textx_size + 10, texty_size +\n 10)))\n screen.blit(text, (SCREEN_WIDTH / 2 - text.get_width() / 2,\n SCREEN_HEIGHT / 2 - text.get_height() / 2))\n #clock = pygame.time.Clock()\n pygame.display.flip()\n in_main_menu = True\n while in_main_menu:\n clock.tick(50)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n in_main_menu = False\n return False\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n x, y = event.pos\n if x >= textx - 5 and x <= textx + textx_size + 5:\n if y >= texty - 5 and y <= texty + texty_size + 5:\n in_main_menu = False\n return True\nrunning = True\nwhile running:\n clock.tick(FPS)\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n running = False\n if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:\n running = False\n # Move the player\n key = pygame.key.get_pressed()\n if key[pygame.K_LEFT]:\n player.move(-2, 0)\n if key[pygame.K_RIGHT]:\n player.move(2, 0)\n if key[pygame.K_UP]:\n player.move(0, -2)\n if key[pygame.K_DOWN]:\n player.move(0, 2)\n if player.rect.colliderect(end_rect):\n again = play_again()\n if again:\n reinit()\n else:\n break\n # Draw the scene\n gameDisplay.fill((brown))\n for wall in walls:\n pygame.draw.rect(gameDisplay, green, wall.rect)\n pygame.draw.rect(gameDisplay, red, end_rect)\n pygame.draw.rect(gameDisplay, white, player.rect)\n pygame.display.flip()\npygame.quit()\nquit()","sub_path":"socket/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"136863675","text":"import discord\r\nfrom discord.ext.commands import Bot\r\nfrom discord.utils import get\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport time\r\nimport os\r\nimport random\r\n\r\nclient = discord.Client()\r\nclient = commands.Bot(command_prefix = \"\")\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Bot is ready!\")\r\n await client.change_presence(game=discord.Game(name=\"say bowl\"))\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author.id != client.user.id and \"bowl\" in message.content and \"max\" in message.content:\r\n await client.send_message(message.channel, message.content.replace(\"bowl\", \"<:bowlcut:492887126820651028>\").replace(\"max\", \"<:max:536609206829056014>\"))\r\n await client.delete_message(message)\r\n elif message.author.id != client.user.id and \"bowl\" in message.content:\r\n await client.send_message(message.channel, message.content.replace(\"bowl\", \"<:bowlcut:492887126820651028>\"))\r\n await client.delete_message(message)\r\n elif message.author.id != client.user.id and \"max\" in message.content:\r\n await client.send_message(message.channel, message.content.replace(\"max\", \"<:max:536609206829056014>\"))\r\n await client.delete_message(message)\r\n elif message.content.startswith(\"!version\"):\r\n emb = (discord.Embed(description=\"- Max and Derrick in same sentence\", colour=0x3DF270))\r\n emb.set_author(name=\"Version 0.4.3\", icon_url='https://i.kym-cdn.com/photos/images/original/001/288/150/85a.jpg')\r\n await client.send_message(message.channel, embed=emb)\r\n elif message.content.startswith(\"!8\"):\r\n await client.send_message(message.channel, random.choice([\"It is certain\",\r\n \"It is decidedly so\",\r\n \"Very doubtful\",\r\n \"Concentrate and ask again\"])) \r\n \r\nclient.run(os.getenv('TOKEN'))\r\n","sub_path":"bowlbot.py","file_name":"bowlbot.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"404572952","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nTests for multiple_function_arguments.\n\"\"\"\n\nimport unittest\nimport types\n\nfrom pyknowledge import multiple_function_arguments\n\n\nclass TestMultipleFunctionArguments(unittest.TestCase):\n\n def test_build_string(self):\n \"\"\"\n Test that the multiple argument function behaves as expected.\n \"\"\"\n returned = multiple_function_arguments.build_string(\n 'I', 'really', 'love', 'python', 'it', 'is', 'cool',\n twice='really', thrice='cool'\n )\n self.assertEqual(type(returned), types.StringType)\n self.assertEqual('I really really love python it is cool cool cool', returned)\n","sub_path":"tests/test_multiple_function_arguments.py","file_name":"test_multiple_function_arguments.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"252429189","text":"#!/usr/local/bin/python3.6\nimport argparse\nfrom main import main\nfrom GUI_input import GUI_input\n\nparser=argparse.ArgumentParser(description='Find a solution of a Sudoku board')\nparser.add_argument('Board',metavar='Board',type=str,help='A string of 81 digits representing the board')\nparser.add_argument('--show-process',action='store_true',default=False,dest='display',help='If given, the process of finding a solution will be displayed.')\n\nargs=parser.parse_args()\nb=args.Board\ndisplay=args.display\n\nif __name__ == '__main__':\n\n\tif b == 'GUI':\n\t\tGUI_input()\n\telse:\n\t\ttry:\n\t\t\tint(b)\n\t\t\tif not len(b)==81:\n\t\t\t\traise ValueError\n\t\texcept ValueError:\n\t\t\traise ValueError('The board must be a string with 81 digits')\n\n\n\t\tprint('Solution:',main(b,display))\n","sub_path":"Sudoku_Solver.py","file_name":"Sudoku_Solver.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"259555000","text":"#Input\n#user_name,single_char=input(\"Enter comma separated User's Name and single character :\").split(\",\")\n#Output\n#print(f\"Length of User Name {user_name}: {len(user_name)}\")\n#print(f\"Count of Single Character {single_char} : { user_name.count(single_char.upper()) + user_name.count(single_char.lower())}\")\n#------------------------------------------------------------\n#Number guessing Game\n# winning_number=3\n# guess_number=int(input(\"Enter any number between 1 to 10 : \" ))\n# if(guess_number==winning_number):\n# print(\"YOU WIN !!!\")\n# else:\n# if(winning_number>guess_number):\n# print(\"Entered low number !!!\")\n# else:\n# print(\"Entered high number !!!\")\n\n\n# Find Pallindrome\n\nprint(3&5)\n\n\n#print(6**6)\nname='Rohit'\nprint(f\"My name is {name}\")\n\np=15\nq=3\np*=q\nprint(p)\n\nX=300 \nY= 17\nX%=Y\nprint(280%15)\nz=45\nz=float(z)\nprint(z)\n\nprint('for'.isidentifier())\n\nsentence='a b c'\nmatched = re.match(r'(.*) () () ')\n","sub_path":"Chapter3.py","file_name":"Chapter3.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"275866987","text":"# Copyright 2016 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport pecan\nfrom pecan import expose\nfrom pecan import rest\n\nfrom oslo_log import log as logging\nfrom oslo_utils import uuidutils\n\nimport trio2o.common.context as t_context\nfrom trio2o.common import exceptions\nfrom trio2o.common.i18n import _\nfrom trio2o.common.i18n import _LE\nfrom trio2o.common import utils\nimport trio2o.db.api as db_api\nfrom trio2o.db import core\nfrom trio2o.db import models\n\nLOG = logging.getLogger(__name__)\n\n\nclass VolumeTypeController(rest.RestController):\n\n def __init__(self, tenant_id):\n self.tenant_id = tenant_id\n\n def _metadata_refs(self, metadata_dict, meta_class):\n metadata_refs = []\n\n if metadata_dict:\n for k, v in metadata_dict.items():\n metadata_ref = meta_class()\n metadata_ref['key'] = k\n metadata_ref['value'] = v\n metadata_refs.append(metadata_ref)\n return metadata_refs\n\n @expose(generic=True, template='json')\n def post(self, **kw):\n \"\"\"Creates volume types.\"\"\"\n context = t_context.extract_context_from_environ()\n\n if not context.is_admin:\n return utils.format_cinder_error(\n 403, _(\"Policy doesn't allow volume_extension:types_manage \"\n \"to be performed.\"))\n\n if 'volume_type' not in kw:\n return utils.format_cinder_error(\n 400, _(\"Missing required element 'volume_type' in \"\n \"request body.\"))\n\n projects = []\n\n if self.tenant_id is not None:\n projects = [self.tenant_id]\n\n vol_type = kw['volume_type']\n name = vol_type.get('name', None)\n description = vol_type.get('description')\n specs = vol_type.get('extra_specs', {})\n is_public = vol_type.pop('os-volume-type-access:is_public', True)\n\n if name is None or len(name.strip()) == 0:\n return utils.format_cinder_error(\n 400, _(\"Volume type name can not be empty.\"))\n\n try:\n utils.check_string_length(name, 'Type name',\n min_len=1, max_len=255)\n except exceptions.InvalidInput as e:\n return utils.format_cinder_error(\n 400, e.message)\n\n if description is not None:\n try:\n utils.check_string_length(description, 'Type description',\n min_len=0, max_len=255)\n except exceptions.InvalidInput as e:\n return utils.format_cinder_error(400, e.message)\n\n if not utils.is_valid_boolstr(is_public):\n msg = _(\"Invalid value '%(is_public)s' for is_public. \"\n \"Accepted values: True or False.\") % {\n 'is_public': is_public}\n return utils.format_cinder_error(400, msg)\n\n vol_type['extra_specs'] = specs\n vol_type['is_public'] = is_public\n vol_type['id'] = uuidutils.generate_uuid()\n\n session = core.get_session()\n with session.begin():\n try:\n db_api.volume_type_get_by_name(context, vol_type['name'],\n session)\n return utils.format_cinder_error(\n 409, _(\"Volume Type %(id)s already exists.\") % {\n 'id': vol_type['id']})\n except exceptions.VolumeTypeNotFoundByName:\n pass\n try:\n extra_specs = vol_type['extra_specs']\n vol_type['extra_specs'] = \\\n self._metadata_refs(vol_type.get('extra_specs'),\n models.VolumeTypeExtraSpecs)\n volume_type_ref = models.VolumeTypes()\n volume_type_ref.update(vol_type)\n session.add(volume_type_ref)\n for project in set(projects):\n access_ref = models.VolumeTypeProjects()\n access_ref.update({\"volume_type_id\": volume_type_ref.id,\n \"project_id\": project})\n access_ref.save(session=session)\n except Exception as e:\n LOG.exception(_LE('Fail to create volume type: %(name)s,'\n '%(exception)s'),\n {'name': vol_type['name'],\n 'exception': e})\n return utils.format_cinder_error(\n 500, _('Fail to create volume type'))\n\n vol_type['extra_specs'] = extra_specs\n return {'volume_type': vol_type}\n\n @expose(generic=True, template='json')\n def get_one(self, _id):\n \"\"\"Retrieves single volume type by id.\n\n :param _id: id of volume type to be retrieved\n :returns: retrieved volume type\n \"\"\"\n context = t_context.extract_context_from_environ()\n try:\n result = db_api.volume_type_get(context, _id)\n except exceptions.VolumeTypeNotFound as e:\n return utils.format_cinder_error(404, e.message)\n except Exception as e:\n LOG.exception(_LE('Volume type not found: %(id)s,'\n '%(exception)s'),\n {'id': _id,\n 'exception': e})\n return utils.format_cinder_error(\n 404, _(\"Volume type %(id)s could not be found.\") % {\n 'id': _id})\n return {'volume_type': result}\n\n @expose(generic=True, template='json')\n def get_all(self):\n \"\"\"Get all non-deleted volume_types.\"\"\"\n filters = {}\n context = t_context.extract_context_from_environ()\n if not context.is_admin:\n # Only admin has query access to all volume types\n filters['is_public'] = True\n try:\n list_result = db_api.volume_type_get_all(context,\n list_result=True,\n filters=filters)\n except Exception as e:\n LOG.exception(_LE('Fail to retrieve volume types: %(exception)s'),\n {'exception': e})\n return utils.format_cinder_error(500, e)\n\n return {'volume_types': list_result}\n\n @expose(generic=True, template='json')\n def put(self, _id, **kw):\n \"\"\"Update volume type by id.\n\n :param _id: id of volume type to be updated\n :param kw: dictionary of values to be updated\n :returns: updated volume type\n \"\"\"\n context = t_context.extract_context_from_environ()\n\n if not context.is_admin:\n return utils.format_cinder_error(\n 403, _(\"Policy doesn't allow volume_extension:types_manage \"\n \"to be performed.\"))\n\n if 'volume_type' not in kw:\n return utils.format_cinder_error(\n 400, _(\"Missing required element 'volume_type' in \"\n \"request body.\"))\n\n values = kw['volume_type']\n name = values.get('name')\n description = values.get('description')\n is_public = values.get('os-volume-type-access:is_public')\n\n # Name and description can not be both None.\n # If name specified, name can not be empty.\n if name and len(name.strip()) == 0:\n return utils.format_cinder_error(\n 400, _(\"Volume type name can not be empty.\"))\n\n if name is None and description is None and is_public is None:\n msg = _(\"Specify volume type name, description, is_public or \"\n \"a combination thereof.\")\n return utils.format_cinder_error(400, msg)\n\n if is_public is not None and not utils.is_valid_boolstr(is_public):\n msg = _(\"Invalid value '%(is_public)s' for is_public. Accepted \"\n \"values: True or False.\") % {'is_public': is_public}\n return utils.format_cinder_error(400, msg)\n\n if name:\n try:\n utils.check_string_length(name, 'Type name',\n min_len=1, max_len=255)\n except exceptions.InvalidInput as e:\n return utils.format_cinder_error(400, e.message)\n\n if description is not None:\n try:\n utils.check_string_length(description, 'Type description',\n min_len=0, max_len=255)\n except exceptions.InvalidInput as e:\n return utils.format_cinder_error(400, e.message)\n\n try:\n type_updated = \\\n db_api.volume_type_update(context, _id,\n dict(name=name,\n description=description,\n is_public=is_public))\n except exceptions.VolumeTypeNotFound as e:\n return utils.format_cinder_error(404, e.message)\n except exceptions.VolumeTypeExists as e:\n return utils.format_cinder_error(409, e.message)\n except exceptions.VolumeTypeUpdateFailed as e:\n return utils.format_cinder_error(500, e.message)\n except Exception as e:\n LOG.exception(_LE('Fail to update volume type: %(name)s,'\n '%(exception)s'),\n {'name': values['name'],\n 'exception': e})\n return utils.format_cinder_error(\n 500, _(\"Fail to update volume type.\"))\n return {'volume_type': type_updated}\n\n @expose(generic=True, template='json')\n def delete(self, _id):\n \"\"\"Marks volume types as deleted.\n\n :param _id: id of volume type to be deleted\n \"\"\"\n context = t_context.extract_context_from_environ()\n\n if not context.is_admin:\n return utils.format_cinder_error(\n 403, _(\"Policy doesn't allow volume_extension:types_manage \"\n \"to be performed.\"))\n\n session = core.get_session()\n with session.begin():\n try:\n db_api.volume_type_get(context, _id, session)\n except exceptions.VolumeTypeNotFound as e:\n return utils.format_cinder_error(404, e.message)\n try:\n db_api.volume_type_delete(context, _id, session)\n except Exception as e:\n LOG.exception(_LE('Fail to update volume type: %(id)s,'\n '%(exception)s'),\n {'id': _id,\n 'exception': e})\n return utils.format_cinder_error(\n 500, _('Fail to delete volume type.'))\n\n pecan.response.status = 202\n return pecan.response\n","sub_path":"trio2o/cinder_apigw/controllers/volume_type.py","file_name":"volume_type.py","file_ext":"py","file_size_in_byte":11424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"81305221","text":"import pytest\nimport os\nimport time\nimport re\nfrom queue import Queue, Empty\nfrom glob import iglob\nfrom watchdog.observers import Observer\nfrom rtAtten.RtAttenClient import FileNotifyHandler\n\ntestDir = '/tmp/'\n\ndef test_watchdog():\n observer = Observer()\n eventQueue = Queue()\n fileHandler = FileNotifyHandler(eventQueue, [\"*.watchdog\"])\n observer.schedule(fileHandler, testDir, recursive=False)\n observer.start()\n\n # remove any existing testfiles\n for filename in iglob(testDir + \"test*.watchdog\"):\n # print(\"remove {}\".format(filename))\n os.remove(filename)\n\n # create the new files\n for i in range(5):\n filename = testDir + \"test{}.watchdog\".format(i)\n # print(\"create {}\".format(filename))\n with open(filename, \"w\") as f:\n f.write(\"hello {}\".format(i))\n time.sleep(0.25) # without sleep the events can get out of order\n\n # check that we got an event for each file\n print(\"get events\")\n for i in range(5):\n filename = testDir + \"test{}.watchdog\".format(i)\n try:\n event, ts = eventQueue.get(block=True, timeout=0.5)\n except Empty as err:\n assert False # we don't expect an empty queue\n # print(\"received event for {}, {}\".format(event.src_path, event.event_type))\n assert re.match(filename, event.src_path)\n\n assert eventQueue.empty()\n observer.stop()\n","sub_path":"tests/rtfMRI/test_watchdog.py","file_name":"test_watchdog.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"107897421","text":"#coding:utf-8\nimport socket\n\nfrom multiprocessing import Process\n\nHTML_ROOT_DIR = \"\"\n\ndef handle_client(client_socket):\n\t\"處理客戶端請求\"\n\t# 獲取客戶端請求數據\n\trequest_data = client_socket.recv(1024)\n\tprint(\"request data: \",request_data)\n\n\t# 構造響應數據\n\tresponse_start_line = \"HTTP/1.1 200 OK\\r\\n\"\n\tresponse_headers = \"Server:My server\\r\\n\"\n\tresponse_body = \"hello itcast\"\n\tresponse = response_start_line + response_headers+\"\\r\\n\" +response_body\n\tprint(\"response data:\",response)\n\n\t# 向客戶端返回響應數據\n\tclient_socket.send(bytes(response,\"utf-8\"))\n\t\n\t# 關閉客戶端鏈接\n\tclient_socket.close()\n\nif __name__==\"__main__\":\n\tserver_socket = socket.socket(socket.AF_INET,\n\t\tsocket.SOCK_STREAM)\n\tserver_socket.bind((\"\",8000))\n\tserver_socket.listen(128)\n\n\twhile True:\n\t\tclient_socket,client_addr = server_socket.accept()\n\t\tprint(\"[%s,%s]用戶已鏈接\"%client_addr)\n\t\thandle_client_process = Process(target=handle_client,\n\t\t\targs=(client_socket,))\n\t\thandle_client_process.start()\n\t\tclient_socket.close()\n\n\n","sub_path":"11-web服務器抄録版.py","file_name":"11-web服務器抄録版.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"288515472","text":"# from django.test import TestCase\nimport pytest\n# Create your tests here.\n\n\n@pytest.mark.django_db\nclass TestUsers:\n def test_login_view(self, client):\n\n # if this simple test is failing,\n # try running 'python manage.py collectstatic'\n response = client.get('/user/login/')\n assert response.status_code == 200\n","sub_path":"apps/users/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"99723215","text":"from wtforms import Form, StringField, IntegerField, BooleanField, HiddenField, SubmitField, SelectField\nfrom lxml import etree\nfrom .tools import str2bool\n\n\n\nclass AlarmPeriodic:\n\tdef __init__(self):\n\t\tself.enable = False\n\t\tself.weekday = []\n\t\tfor i in range(7):\n\t\t\tself.weekday.append(False)\n\n\tdef parseForm(self, form):\n\t\tself.enable = form.alarm_period_enable.data\n\t\tself.weekday[0] = form.alarm_period_monday.data\n\t\tself.weekday[1] = form.alarm_period_tuesday.data\n\t\tself.weekday[2] = form.alarm_period_wednesday.data\n\t\tself.weekday[3] = form.alarm_period_thursday.data\n\t\tself.weekday[4] = form.alarm_period_friday.data\n\t\tself.weekday[5] = form.alarm_period_saturday.data\n\t\tself.weekday[6] = form.alarm_period_sunday.data\n\n\tdef parseXML(self, xml):\n\t\tfor ch in xml.getchildren():\n\t\t\tif ch.tag == 'enable':\n\t\t\t\tself.enable = str2bool(ch.text)\n\t\t\tif ch.tag == 'monday':\n\t\t\t\tself.weekday[0] = str2bool(ch.text)\n\t\t\tif ch.tag == 'tuesday':\n\t\t\t\tself.weekday[1] = str2bool(ch.text)\n\t\t\tif ch.tag == 'wednesday':\n\t\t\t\tself.weekday[2] = str2bool(ch.text)\n\t\t\tif ch.tag == 'thursday':\n\t\t\t\tself.weekday[3] = str2bool(ch.text)\n\t\t\tif ch.tag == 'friday':\n\t\t\t\tself.weekday[4] = str2bool(ch.text)\n\t\t\tif ch.tag == 'saturday':\n\t\t\t\tself.weekday[5] = str2bool(ch.text)\n\t\t\tif ch.tag == 'sunday':\n\t\t\t\tself.weekday[6] = str2bool(ch.text)\n\n\nclass AlarmSource:\n\tdef __init__(self):\n\t\tself.type = ''\n\t\tself.item = ''\n\t\tself.randomize = False\n\n\tdef parseForm(self, form):\n\t\tself.type = form.alarm_src_type.data\n\t\tself.item = form.alarm_src_item.data\n\t\tself.randomize = form.alarm_src_random.data\n\n\tdef parseXML(self, xml):\n\t\tfor ch in xml.getchildren():\n\t\t\tif ch.tag == 'type':\n\t\t\t\tself.type = ch.text\n\t\t\tif ch.tag == 'item':\n\t\t\t\tself.item = ch.text\n\t\t\tif ch.tag == 'randomize':\n\t\t\t\tself.randomize = str2bool(ch.text)\n\n\nclass AlarmVolume:\n\tdef __init__(self):\n\t\tself.start = 50\n\t\tself.end = 50\n\t\tself.ramptime = 0\n\t\tself.current=0\n\t\tself.tstart=None\n\t\tself.tstop=None\n\n\tdef parseForm(self, form):\n\t\tself.start = form.alarm_vol_start.data\n\t\tself.end = form.alarm_vol_end.data\n\t\tself.ramptime = form.alarm_vol_ramptime.data\n\n\tdef parseXML(self, xml):\n\t\tfor ch in xml.getchildren():\n\t\t\tif ch.tag == 'start':\n\t\t\t\tself.start = int(ch.text)\n\t\t\tif ch.tag == 'end':\n\t\t\t\tself.end = int(ch.text)\n\t\t\tif ch.tag == 'ramptime':\n\t\t\t\tself.ramptime = int(ch.text)\n\n\nclass AlarmSnooze:\n\tdef __init__(self):\n\t\tself.enable = False\n\t\tself.time = 10\n\t\tself.timestamp = None\n\n\tdef parseForm(self, form):\n\t\tself.enable = form.alarm_snz_enable.data\n\t\tself.time = form.alarm_snz_time.data\n\n\tdef parseXML(self, xml):\n\t\tfor ch in xml.getchildren():\n\t\t\tif ch.tag == 'enable':\n\t\t\t\tself.enable = str2bool(ch.text)\n\t\t\tif ch.tag == 'time':\n\t\t\t\tself.time = int(ch.text)\n\n\nclass AlarmWeather:\n\tdef __init__(self):\n\t\tself.enable = False\n\t\tself.greeting = ''\n\t\tself.delay = 1\n\t\tself.timestamp = None\n\t\tself.executed = False\n\n\tdef parseForm(self, form):\n\t\tself.enable = form.alarm_wth_enable.data\n\t\tself.greeting = form.alarm_wth_greeting.data\n\t\tself.delay = form.alarm_wth_delay.data\n\n\tdef parseXML(self, xml):\n\t\tfor ch in xml.getchildren():\n\t\t\tif ch.tag == 'enable':\n\t\t\t\tself.enable = str2bool(ch.text)\n\t\t\tif ch.tag == 'greeting':\n\t\t\t\tself.greeting = ch.text\n\t\t\tif ch.tag == 'delay':\n\t\t\t\tself.delay = int(ch.text)\n\n\nclass Alarm:\n\n\tdef __init__(self, form=None, xml=None):\n\t\tself.name = ''\n\t\tself.hour = 0\n\t\tself.minute = 0\n\t\tself.periodic = AlarmPeriodic()\n\t\tself.source = AlarmSource()\n\t\tself.volume = AlarmVolume()\n\t\tself.snooze = AlarmSnooze()\n\t\tself.weather = AlarmWeather()\n\t\tself.status='idle'\n\t\tif form != None:\n\t\t\tself.parseForm(form)\n\t\tif xml != None:\n\t\t\tself.parseXML(xml)\n\n\tdef parseForm(self, form):\n\t\tself.name = form.name.data\n\t\tself.hour = form.hour.data\n\t\tself.minute = form.minute.data\n\t\tself.periodic.parseForm(form)\n\t\tself.source.parseForm(form)\n\t\tself.volume.parseForm(form)\n\t\tself.snooze.parseForm(form)\n\t\tself.weather.parseForm(form)\n\n\tdef parseXML(self, xml):\n\t\tfor ch in xml.getchildren():\n\t\t\tif ch.tag == 'name':\n\t\t\t\tself.name = ch.text\n\t\t\tif ch.tag == 'hour':\n\t\t\t\tself.hour = int(ch.text)\n\t\t\tif ch.tag == 'minute':\n\t\t\t\tself.minute = int(ch.text)\n\t\t\tif ch.tag == 'periodic':\n\t\t\t\tself.periodic.parseXML(ch)\n\t\t\tif ch.tag == 'source':\n\t\t\t\tself.source.parseXML(ch)\n\t\t\tif ch.tag == 'volume':\n\t\t\t\tself.volume.parseXML(ch)\n\t\t\tif ch.tag == 'snooze':\n\t\t\t\tself.snooze.parseXML(ch)\n\t\t\tif ch.tag == 'weather':\n\t\t\t\tself.weather.parseXML(ch)\n\n\nclass AlarmForm(Form):\n\tname = StringField(label='Name', render_kw={\"placeholder\": \"Alarm Name\", \"style\":\"font-size:30px\", \"size\":\"23\"})\n\thour = IntegerField(label='Hour', render_kw={\"placeholder\": \"HH\",\"style\":\"font-size:30px\", \"size\":\"1\"})\n\tminute = IntegerField(label='Minute', render_kw={\"placeholder\": \"MM\",\"style\":\"font-size:30px\", \"size\":\"1\"})\n\talarm_period_enable = BooleanField(label='Enable periodic alarm')\n\talarm_period_monday = BooleanField(label='Monday')\n\talarm_period_tuesday = BooleanField(label='Tuesday')\n\talarm_period_wednesday = BooleanField(label='Wednesday')\n\talarm_period_thursday = BooleanField(label='Thursday')\n\talarm_period_friday = BooleanField(label='Friday')\n\talarm_period_saturday = BooleanField(label='Saturday')\n\talarm_period_sunday = BooleanField(label='Sunday')\t\n\ttype_choices = [('radio', 'radio'),\n\t\t\t ('spotify', 'spotify')]\n\talarm_src_type = SelectField('Type', choices=type_choices)\n\talarm_src_item = StringField(label='Source item', render_kw={\"placeholder\": \"URI/Freq.\", \"size\":\"35\"})\n\talarm_src_random = BooleanField(label='random')\n\talarm_vol_start = IntegerField(label='Start volume (%)', render_kw={\"placeholder\": \"0-100\", \"size\":\"1\"})\n\talarm_vol_end = IntegerField(label='End volume (%)', render_kw={\"placeholder\": \"0-100\", \"size\":\"1\"})\n\talarm_vol_ramptime = IntegerField(label='Ramptime (min)', render_kw={\"placeholder\": \"Rmp\", \"size\":\"1\"})\n\talarm_snz_enable = BooleanField(label='Enable snooze')\n\talarm_snz_time = IntegerField(label='Snooze time (min)', render_kw={\"placeholder\": \"Snz\", \"size\":\"1\"})\n\talarm_wth_enable = BooleanField(label='Enable weather forecast')\n\talarm_wth_greeting = StringField(label='Greeting', render_kw={\"placeholder\": \"Greeting\", \"size\":\"35\"})\n\talarm_wth_delay = IntegerField(label='Weather delay (min)', render_kw={\"placeholder\": \"Wth\", \"size\":\"1\"})\n\tidx = HiddenField()\n\tdelete = SubmitField(label='Delete')\n\tupdate = SubmitField(label='Update')\n\tnew = SubmitField(label='New')\n\n\tdef readobject(self, alarm):\n\t\tself.name.data = alarm.name\n\t\tself.hour.data = alarm.hour\n\t\tself.minute.data = alarm.minute\n\t\tself.alarm_period_enable.data = alarm.periodic.enable\n\t\tself.alarm_period_monday.data = alarm.periodic.weekday[0]\n\t\tself.alarm_period_tuesday.data = alarm.periodic.weekday[1]\n\t\tself.alarm_period_wednesday.data = alarm.periodic.weekday[2]\n\t\tself.alarm_period_thursday.data = alarm.periodic.weekday[3]\n\t\tself.alarm_period_friday.data = alarm.periodic.weekday[4]\n\t\tself.alarm_period_saturday.data = alarm.periodic.weekday[5]\n\t\tself.alarm_period_sunday.data = alarm.periodic.weekday[6]\n\t\tself.alarm_src_type.data = alarm.source.type\n\t\tself.alarm_src_item.data = alarm.source.item\n\t\tself.alarm_src_random.data = alarm.source.randomize\n\t\tself.alarm_vol_start.data = alarm.volume.start\n\t\tself.alarm_vol_end.data = alarm.volume.end\n\t\tself.alarm_vol_ramptime.data = alarm.volume.ramptime\n\t\tself.alarm_snz_enable.data = alarm.snooze.enable\n\t\tself.alarm_snz_time.data = alarm.snooze.time\n\t\tself.alarm_wth_enable.data = alarm.weather.enable\n\t\tself.alarm_wth_greeting.data = alarm.weather.greeting\n\t\tself.alarm_wth_delay.data = alarm.weather.delay\n\n\ndef save_alarm_list(alarms, filename):\n\t# Create main element\n\talist = etree.Element('alarms')\n\tfor alarm in alarms:\n\t\t# Create alarm element\n\t\tal = etree.SubElement(alist, 'alarm')\n\t\t# Main tags\n\t\tse = etree.SubElement(al, 'name')\n\t\tse.text = alarm.name\n\t\tse = etree.SubElement(al, 'hour')\n\t\tse.text = str(alarm.hour)\n\t\tse = etree.SubElement(al, 'minute')\n\t\tse.text = str(alarm.minute)\n\t\t# Periodic tags\n\t\tperiodic = etree.SubElement(al, 'periodic')\n\t\tse = etree.SubElement(periodic, 'enable')\n\t\tse.text = str(alarm.periodic.enable)\n\t\tse = etree.SubElement(periodic, 'monday')\n\t\tse.text = str(alarm.periodic.weekday[0])\n\t\tse = etree.SubElement(periodic, 'tuesday')\n\t\tse.text = str(alarm.periodic.weekday[1])\n\t\tse = etree.SubElement(periodic, 'wednesday')\n\t\tse.text = str(alarm.periodic.weekday[2])\n\t\tse = etree.SubElement(periodic, 'thursday')\n\t\tse.text = str(alarm.periodic.weekday[3])\n\t\tse = etree.SubElement(periodic, 'friday')\n\t\tse.text = str(alarm.periodic.weekday[4])\n\t\tse = etree.SubElement(periodic, 'saturday')\n\t\tse.text = str(alarm.periodic.weekday[5])\n\t\tse = etree.SubElement(periodic, 'sunday')\n\t\tse.text = str(alarm.periodic.weekday[6])\n\t\t# Source tags\n\t\tsource = etree.SubElement(al, 'source')\n\t\tse = etree.SubElement(source, 'type')\n\t\tse.text = alarm.source.type\n\t\tse = etree.SubElement(source, 'item')\n\t\tse.text = alarm.source.item\n\t\tse = etree.SubElement(source, 'randomize')\n\t\tse.text = str(alarm.source.randomize)\n\t\t# Volume tags\n\t\tvolume = etree.SubElement(al, 'volume')\n\t\tse = etree.SubElement(volume, 'start')\n\t\tse.text = str(alarm.volume.start)\n\t\tse = etree.SubElement(volume, 'end')\n\t\tse.text = str(alarm.volume.end)\n\t\tse = etree.SubElement(volume, 'ramptime')\n\t\tse.text = str(alarm.volume.ramptime)\n\t\t# Snooze tags\n\t\tsnooze = etree.SubElement(al, 'snooze')\n\t\tse = etree.SubElement(snooze, 'enable')\n\t\tse.text = str(alarm.snooze.enable)\n\t\tse = etree.SubElement(snooze, 'time')\n\t\tse.text = str(alarm.snooze.time)\n\t\t# Weather tags\n\t\tweather = etree.SubElement(al, 'weather')\n\t\tse = etree.SubElement(weather, 'enable')\n\t\tse.text = str(alarm.weather.enable)\n\t\tse = etree.SubElement(weather, 'greeting')\n\t\tse.text = alarm.weather.greeting\n\t\tse = etree.SubElement(weather, 'delay')\n\t\tse.text = str(alarm.weather.delay)\n\n\twith open(filename, 'w', encoding='utf8') as doc:\n\t\tdoc.write(etree.tostring(alist, pretty_print=True, encoding='unicode'))\n\ndef load_alarm_list(filename):\n\ttree = etree.parse(filename)\n\n\t# Create alarm objects from XML\n\talarms = []\n\tfor el in tree.findall('alarm'):\n\t\talarm = Alarm(xml=el)\n\t\talarms.append(alarm)\n\n\t# Return alarm object list\n\treturn alarms","sub_path":"rpi_sw/flip-clock/frontend/alarm_models.py","file_name":"alarm_models.py","file_ext":"py","file_size_in_byte":10113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"}
+{"seq_id":"261481757","text":"# \n# model to process input.txt, write to output.txt\n\n# what it needs:\n\n# - function to read from input.txt and convert to term def dict\n# - use regex to identify term def pairs, event date pairs, etc.\n# - after finding patterns, identify additional important terms using frequencies, these create new keys with empty string values\n# --> dictionary \n# - function to take in dictionary returned from previous function and write to output.txt in quizlet import format\n# - format should be \n# term + ',' + def + '\\n'\n# for each key:value pair\n# \n\n\nimport re\n\ndef execute():\n writeOutput(createCardDictionary())\n\n\n\ndef createCardDictionary():\n \n fullDictionary = []\n words = []\n\n #input is in format thing then 10 dashes\n #input_text = open(r'image_to_txt\\saved_defenitions.txt', 'r', encoding='utf8').read()\n input_text = open(r'input.txt', 'r', encoding='utf8').read()\n \n \n input_text = input_text.replace('\\n', ' ')\n \n input_sentences = re.split(\"(?<=[^A-Z])\\.|\\?[^a-zA-Z]\" , input_text) #problem: acronyms. Solution: nltk library, would have to load into repo or something\n \n \n for j in range(len(input_sentences)):\n input_sentences[j] = \"\\. \" + input_sentences[j]\n \n #creates flashcard and adds to dictionary\n def appendCardToDictionary(foundDefinitions, foundWords):\n \n for i in range(min(len(foundDefinitions), len(foundWords))):\n if len(foundDefinitions[i]) <= 2:\n continue\n\n\n flashcard = {\n 'word': '',\n 'definition': ''\n }\n\n #makes dictionary/flashcard\n \n newWord = foundWords[i].lstrip()\n newDefinition = foundDefinitions[i].lstrip()\n if newWord not in words:\n flashcard['word'] = newWord\n flashcard['definition'] = newDefinition\n #appends pair to dictionary\n fullDictionary.append(flashcard)\n words.append(newWord) \n print(flashcard) \n \n \n #Works in format \"[start indicator] [word] [indicator phrase] [definition] [end indicator]\"\n def findBoundedIndicator(startBound, indicator, endBound):\n # does not return anything, modifies fullDictionary\n \n #iterates through every sentence \n for j in range(len(input_sentences)):\n #sets regex, calls it to find word\n word = re.compile('(?<=' + startBound + ').*(?=' + indicator + ')')\n \n\n #finds definition\n definition = re.compile('(?<=' + indicator + ').*(?=' + endBound + ')')\n\n #finds all instances of format\n foundWords = word.findall(input_sentences[j], re.IGNORECASE)\n foundDefinitions = definition.findall(input_sentences[j], re.IGNORECASE)\n\n #loops through all word/definition pairs, appends to dictionary\n #must be same length\n appendCardToDictionary(foundDefinitions, foundWords)\n\n #works with format [indicator] [definition] [endBound]\n def findIndicatorToEndBound(indicator, endBound):\n # does not return anything, modifies toRet\n \n #iterates through every sentence \n for j in range(len(input_sentences)):\n\n #finds definition\n definition = re.compile('(?<=' + indicator + ').*(?=' + endBound + ')')\n\n #finds all instances of format\n foundWords = re.findall(indicator, input_sentences[j], re.IGNORECASE)\n foundDefinitions = definition.findall(input_sentences[j], re.IGNORECASE)\n\n #loops through all word/definition pairs, appends to dictionary\n #must be same length\n appendCardToDictionary(foundDefinitions, foundWords)\n\n \n def findKeywords():\n # does not return anything, modifies toRet\n pass\n \n\n findBoundedIndicator(\". \", \"(?\n \n Test Page\n \n \n {greet} {who}!
\n \n